mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-25 09:46:05 +00:00
Compare commits
18
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
831f2472f3 | ||
|
|
8df6672de1 | ||
|
|
feb7882e5c | ||
|
|
cd2e56f1fa | ||
|
|
1ff119dc2a | ||
|
|
6e6f224e44 | ||
|
|
395a5a5f80 | ||
|
|
12bc84046c | ||
|
|
44d1d6ab29 | ||
|
|
cfcf0dc7d1 | ||
|
|
0a856ab7fc | ||
|
|
ad20814ec8 | ||
|
|
0688ae83fe | ||
|
|
311728a780 | ||
|
|
cf1a5a9e73 | ||
|
|
e06bfbb94c | ||
|
|
7bcd598f09 | ||
|
|
c626bf3707 |
@@ -422,7 +422,6 @@
|
||||
"packages/app/src/components/headers/back-header.tsx",
|
||||
"packages/app/src/components/headers/screen-header.tsx",
|
||||
"packages/app/src/components/host-status-dot.tsx",
|
||||
"packages/app/src/components/hosts/host-picker.tsx",
|
||||
"packages/app/src/components/icons/paseo-logo.tsx",
|
||||
"packages/app/src/components/left-sidebar.tsx",
|
||||
"packages/app/src/components/plan-card.tsx",
|
||||
@@ -552,9 +551,7 @@
|
||||
"packages/app/src/components/download-toast.tsx",
|
||||
"packages/app/src/components/file-explorer-pane.tsx",
|
||||
"packages/app/src/components/headers/back-header.tsx",
|
||||
"packages/app/src/components/highlighted-code-block.tsx",
|
||||
"packages/app/src/components/hosts/host-filter.tsx",
|
||||
"packages/app/src/components/hosts/host-picker.tsx",
|
||||
"packages/app/src/components/import-session-sheet.tsx",
|
||||
"packages/app/src/components/left-sidebar.tsx",
|
||||
"packages/app/src/components/markdown/fence/mermaid/host.native.tsx",
|
||||
|
||||
@@ -54,7 +54,6 @@ At the start of non-trivial work, list `docs/` and skim anything relevant to the
|
||||
| [docs/permissions.md](docs/permissions.md) | Semantic daemon permissions, principals, credentials, pairing invitations, and Hub authority |
|
||||
| [docs/terminal-performance.md](docs/terminal-performance.md) | Terminal latency pipeline, coalescing/backpressure invariants, benchmark + perf spec usage |
|
||||
| [docs/terminal-rendering.md](docs/terminal-rendering.md) | Native terminal view: xterm owns the grid, cluster placement, emoji widths, mixed-direction limits, render regression |
|
||||
| [docs/timeline-sync.md](docs/timeline-sync.md) | Owned agent history, rewind retirements, live stream vs authoritative fetch, paged catch-up, client replica |
|
||||
| [docs/agent-stream-performance.md](docs/agent-stream-performance.md) | Assistant text pipeline — coalescing window, paced reveal, why arrival lumps are smoothed at render |
|
||||
| [docs/agent-stream-disclosure.md](docs/agent-stream-disclosure.md) | Expand/collapse in the chat timeline — hold contract, native anchor sequence, frame spacing, render-window cost |
|
||||
| [docs/markdown-renderer.md](docs/markdown-renderer.md) | Shared Markdown engine, the vendored library fork, native selection, links, images and library constraints |
|
||||
|
||||
@@ -48,7 +48,7 @@ Paseo is an open source agentic development environment for desktop, mobile, web
|
||||
- **Multi-provider:** Claude Code, Codex, Copilot, OpenCode, Pi, Antigravity, and Muse Code through the same interface. Pick the right model for each job.
|
||||
- **Voice control:** Dictate tasks or talk through problems in voice mode. Hands-free when you need it.
|
||||
- **Cross-device:** iOS, Android, desktop, web, and CLI. Start work at your desk, check in from your phone, script it from the terminal.
|
||||
- **Privacy-first:** Paseo doesn't have any telemetry, tracking, or forced log-ins.
|
||||
- **Privacy-first:** No telemetry, tracking, or forced login. Remote access uses an optional end-to-end encrypted relay.
|
||||
|
||||
[Run parallel tasks in Paseo](https://paseo.sh/docs/parallel-development): start agents in separate worktrees, review their diffs, run each app, and check it in the built-in browser.
|
||||
|
||||
|
||||
+3
-3
@@ -51,7 +51,7 @@
|
||||
- **多提供商:** 通过同一个界面使用 Claude Code、Codex、Copilot、OpenCode 和 Pi。为每个任务选择合适的模型。
|
||||
- **语音控制:** 在语音模式下口述任务或讨论问题。需要免手操作时很方便。
|
||||
- **跨设备:** 支持 iOS、Android、桌面端、Web 和 CLI。在桌前开始工作,用手机查看进度,也可以从终端脚本化操作。
|
||||
- **隐私优先:** Paseo 没有遥测、追踪,也不会强制登录。
|
||||
- **隐私优先**:无遥测、无追踪、不强制登录。远程访问可使用可选的端到端加密中继。
|
||||
|
||||
## 赞助商
|
||||
|
||||
@@ -93,7 +93,7 @@ npm install -g @getpaseo/cli
|
||||
paseo
|
||||
```
|
||||
|
||||
终端中会显示一个二维码。你可以从任意客户端连接。这个方式适合服务器和远程机器。
|
||||
Paseo 启动后会询问是否启用端到端加密中继以进行设备配对。如果拒绝,可以通过 TCP、Tailscale 或其他 VPN 直接连接。这个方式适合服务器和远程机器。
|
||||
|
||||
完整安装和配置见:
|
||||
|
||||
@@ -140,7 +140,7 @@ Monorepo 包结构速览:
|
||||
- `packages/app`:Expo 客户端(iOS、Android、Web)
|
||||
- `packages/cli`:用于 daemon 和 agent 工作流的 `paseo` CLI
|
||||
- `packages/desktop`:Electron 桌面 app
|
||||
- `packages/relay`:用于远程连接的 relay 包
|
||||
- `packages/relay`:daemon 和客户端使用的中继传输与端到端加密包
|
||||
- `packages/website`:营销站点和文档(`paseo.sh`)
|
||||
|
||||
常用命令:
|
||||
|
||||
+1
-1
@@ -33,7 +33,7 @@ The relay sees only: IP addresses, timing, message sizes, session IDs, and the p
|
||||
The daemon requires a valid cryptographic handshake before processing any commands. A compromised relay cannot:
|
||||
|
||||
- **Impersonate the daemon to your phone** — Without the daemon's secret key, it cannot derive the shared key, so any traffic it injects fails authenticated decryption on the phone
|
||||
- **Send commands as you** — The daemon only accepts traffic that decrypts and authenticates under a shared key derived with its own secret key. The phone's keypair is ephemeral per connection, so there is no persistent phone-side secret to steal; protection comes from the daemon's secret key never leaving the daemon.
|
||||
- **Open a session without pairing** — The daemon's public key is carried only in the pairing offer and is never sent to the relay. With a daemon password configured, the daemon also rejects any relay client that does not send the right password inside the encrypted channel.
|
||||
- **Read your traffic** — After the handshake every message is encrypted: ChaCha20-Poly1305 in protected mode, XSalsa20-Poly1305 (NaCl box) in legacy mode
|
||||
- **Forge messages** — Both constructions are authenticated encryption; a tampered message is rejected in either mode
|
||||
- **Replay old messages** — In protected mode the daemon contributes a fresh ephemeral key to every session and every record carries a strictly increasing counter, so a recorded session cannot be replayed into a new one and a duplicated, reordered, or reflected record closes the session. Legacy mode has neither property: it uses random nonces, and a daemon that still admits legacy clients accepts a recorded legacy transcript (hello, credentials, commands) as a new session. Set `daemon.relay.requireProtectedSecurity: true` to refuse legacy clients once every client you use has updated.
|
||||
|
||||
@@ -39,8 +39,8 @@ An unarchived agent may be `closed` without being deleted or archived. Closing r
|
||||
processes and subscriptions while retaining its Paseo identity, persistence handle, timeline,
|
||||
workspace, labels, title, usage, attention, timestamps, and parent relationship. Opening or prompting
|
||||
the agent runs through `ensureAgentLoaded()`, which resumes the durable provider session under the
|
||||
same Paseo agent ID. Resume does not read provider history when the agent already has a timeline;
|
||||
see [owned history](timeline-sync.md#owned-history).
|
||||
same Paseo agent ID. Provider history is not appended again when the canonical timeline is already
|
||||
primed.
|
||||
|
||||
Reload releases the old runtime before resuming its durable session: an idle provider process can
|
||||
still own an exclusive writer. A close failure retains that runtime for cleanup and blocks the
|
||||
@@ -256,8 +256,7 @@ lifecycle is separate from public workspace visibility and is not a public creat
|
||||
Archive is a **soft delete**: the agent record stays on disk with `archivedAt` set, the runtime is closed, and the agent disappears from active lists. Archive is **global** — it lives on the server and propagates to every connected client.
|
||||
|
||||
Archive sets `archivedAt`, invokes the provider's native archive hook, and cascades to managed
|
||||
children. The timeline and the provider children stay, so an archived chat reads them without its
|
||||
provider; deleting the agent removes them.
|
||||
children.
|
||||
|
||||
`create_agent_request` can opt an agent into `autoArchive`. In that mode the daemon archives the agent after the first terminal turn event (`turn_completed`, `turn_failed`, or `turn_canceled`). When the agent owns an isolated workspace, auto-archive archives that workspace too; the managed worktree is removed when its final workspace reference is gone.
|
||||
|
||||
@@ -353,8 +352,6 @@ Workspace status is an aggregate activity signal computed **per `workspaceId`**.
|
||||
|
||||
Running provider-native subagents contribute `running` to the workspace owned by their parent agent. Their completed, failed, and canceled states stay in the parent's subagents track.
|
||||
|
||||
Only the parent's current runtime makes a provider child running. A child's stored status is the last report about it, and that report can come from provider history or from a runtime an earlier daemon ran, so a stored `running` child does not make the workspace running or keep the parent's runtime alive. It counts again once the live session reports it running. Closing a runtime cancels the children that runtime reported running; children it never reported keep their stored status.
|
||||
|
||||
A finished or failed workspace can be marked unread after it has been reviewed. The daemon restores
|
||||
attention on its newest eligible workspace-root agent, `error` for an agent whose lifecycle is
|
||||
`error` and `finished` otherwise, without sending a new notification. Opening a workspace restores
|
||||
|
||||
@@ -94,7 +94,6 @@ workspace for a directory clears it. The store lives in memory and resets on dae
|
||||
| `server/directory-sync/` | Daemon-global latest-state sequences for projects, workspaces, and agents |
|
||||
| `server/workspace-labels/` | Host-local label catalog, assignment mutations, and explicit subscriptions |
|
||||
| `server/agent/agent-manager.ts` | Agent lifecycle state machine, timeline tracking, subscriber management |
|
||||
| `server/agent/timeline/` | Owned agent history, provider children, rewind retirements, behind a backend |
|
||||
| `server/agent/agent-storage.ts` | File-backed JSON persistence at `$PASEO_HOME/agents/` |
|
||||
| `server/agent/tools/` | Transport-neutral catalog for workspaces, agents, permissions, and automation |
|
||||
| `server/agent/mcp-server.ts` | Thin MCP adapter that registers the Paseo tool catalog with the MCP SDK |
|
||||
@@ -403,7 +402,7 @@ initializing → idle ⇄ running
|
||||
client-side dedup; the default fetch page is 200 items.
|
||||
- Timeline row `timestamp` values are canonical daemon-owned timestamps. Providers may supply original replay timestamps, but clients must not guess timestamp trust or hide time UI based on local clock heuristics.
|
||||
- Events stream to connected clients in real time; correctness is backed by authoritative timeline fetches and paged-to-completion catch-up.
|
||||
- Agent state persists to `$PASEO_HOME/agents/{cwd-with-dashes}/{agent-id}.json`. That storage path is derived from `cwd`, not from workspace id. Timeline rows persist in the daemon database, `$PASEO_HOME/paseo.db`. They are the transcript authority after the first import of provider history. See [owned history](timeline-sync.md#owned-history).
|
||||
- Agent state persists to `$PASEO_HOME/agents/{cwd-with-dashes}/{agent-id}.json`. Timeline rows are runtime memory; provider history is the durable transcript authority and resumed agents rebuild from it. That storage path is derived from `cwd`, not from workspace id.
|
||||
|
||||
## Right-sidebar boundary: directory-backed vs workspace-owned
|
||||
|
||||
@@ -479,7 +478,6 @@ Providers that can accept native tool definitions should set `supportsNativePase
|
||||
```
|
||||
$PASEO_HOME/
|
||||
├── agents/{cwd-with-dashes}/{agent-id}.json # Agent record
|
||||
├── paseo.db # Daemon database (SQLite): agent timelines
|
||||
├── projects/projects.json # Project registry
|
||||
├── projects/workspaces.json # Workspace registry
|
||||
├── projects/icons/ # Custom project icon images
|
||||
|
||||
@@ -133,7 +133,9 @@ A configured URL takes precedence even when unreachable; Paseo reports the conne
|
||||
|
||||
An explicitly configured server needs the bridge installed separately. Connect once and start a session: the setup error gives the local package directory. Copy that directory to the server's OpenCode global `plugins` directory, then retry. For a server on another machine, set `PASEO_OPENCODE_BRIDGE_PORT` in the Paseo OpenCode provider environment before starting Paseo, and set `PASEO_OPENCODE_BRIDGE_URL` to the URL the OpenCode server can use to reach that port. For example, an SSH reverse tunnel can expose the Paseo loopback port on the OpenCode host. The bridge token is exchanged through the OpenCode connection and is not written into the plugin package.
|
||||
|
||||
OpenCode's custom MCP registrations are shared by all sessions in a location. Paseo rejects custom MCP servers and per-agent process environment overrides on a reused server rather than applying them to other sessions or ignoring them. Session identity is applied to each session's shell environment. A Paseo-owned helper supports custom process and MCP settings; it is selected when there is no explicit URL or healthy registered service.
|
||||
Agent MCP servers and per-agent environment work on a reused server with OpenCode 2.0.29 or newer. Paseo connects each agent's MCP servers itself and shows their tools only to that agent and its subagents. Other agents in the same directory and your own OpenCode sessions do not see them. The agent's environment applies to its shell commands, its subagents, and its stdio MCP servers.
|
||||
|
||||
The provider `env` configures the OpenCode process. When it sets variables other than the connection variables above and `XDG_CONFIG_HOME`, `XDG_STATE_HOME`, or `OPENCODE_CONFIG_DIR`, Paseo ignores a registered service and starts its own helper. With an explicit URL, Paseo reports those variables as an error.
|
||||
|
||||
---
|
||||
|
||||
|
||||
+1
-41
@@ -34,7 +34,7 @@ Workspace archive runs lifecycle teardown from the exact `cwd` but removes only
|
||||
`worktreeRoot` after its last active reference disappears. Worktree recovery recreates that backing
|
||||
checkout from `mainRepoRoot`, then restores the relative path from `worktreeRoot` to `cwd`.
|
||||
|
||||
Paseo persists most stores as JSON files, and agent timelines in the [daemon database](#daemon-database). JSON data is validated at runtime with Zod schemas. Most JSON stores write atomically (write to temp file, then rename); a few still use plain `writeFile` — see each section. JSON stores have no schema-versioning/migration framework — schemas rely on optional fields with defaults for forward compatibility, with a small amount of inline normalization in `persisted-config.ts` for legacy provider/speech entries.
|
||||
Paseo uses **file-based JSON persistence** instead of a traditional database. All data is validated at runtime with Zod schemas. Most stores write atomically (write to temp file, then rename); a few still use plain `writeFile` — see each section. There is no schema-versioning/migration framework — schemas rely on optional fields with defaults for forward compatibility, with a small amount of inline normalization in `persisted-config.ts` for legacy provider/speech entries.
|
||||
|
||||
All server-side stores live under `$PASEO_HOME` (defaults to `~/.paseo`).
|
||||
|
||||
@@ -53,7 +53,6 @@ $PASEO_HOME/
|
||||
├── daemon-keypair.json # E2EE keypair for relay (mode 0600)
|
||||
├── paseo.pid # Daemon PID lock file
|
||||
├── local-credential # Per-run local client credential (mode 0600)
|
||||
├── paseo.db # Daemon database (SQLite, with -wal and -shm files)
|
||||
├── daemon.log # Default log file (path configurable)
|
||||
├── agents/
|
||||
│ └── {sanitized-cwd}/
|
||||
@@ -182,45 +181,6 @@ Terminal activity contributes to the workspace status bucket **per `workspaceId`
|
||||
|
||||
---
|
||||
|
||||
## Daemon database
|
||||
|
||||
`$PASEO_HOME/paseo.db` is one SQLite file that the daemon opens at startup with `node:sqlite`
|
||||
(`packages/server/src/server/database/`). Agent timelines are its only store today. Each store is a
|
||||
`SchemaModule`: its own table-name prefix and an append-only list of migrations.
|
||||
|
||||
- **Migrations.** Startup runs every module's pending migrations in one transaction, so a failed
|
||||
migration leaves the file as it was. `schema_versions` records each module's version and
|
||||
`min_reader_version`. Mark a migration `breaking` when an older daemon cannot read the result,
|
||||
for example a dropped or renamed column. An older daemon then refuses to start with
|
||||
`DatabaseSchemaTooNewError`. Additive migrations leave older daemons working, and they ignore
|
||||
modules they do not know. This matters because the app and the daemon update separately, and a
|
||||
user can run an older daemon on the same `$PASEO_HOME`.
|
||||
- **Failure.** A file that SQLite cannot open stops the daemon with `DatabaseOpenError`, which
|
||||
names the path. The daemon does not delete or recreate the file.
|
||||
- **Access.** The file holds every prompt and reply, so the daemon sets it and its `-wal` and `-shm`
|
||||
files to mode `0600` on every open. SQLite gives the WAL files it creates the mode of the database
|
||||
file.
|
||||
- **Durability.** The database uses WAL with `synchronous = NORMAL`. A power loss can drop the
|
||||
last commits but does not corrupt the file.
|
||||
- **Checkpoints.** A checkpoint syncs the file to disk and takes up to 100 ms. SQLite's
|
||||
auto-checkpoint runs it on the committing thread, which stalled the event loop during streaming.
|
||||
The daemon turns it off and checkpoints from a worker thread with its own connection. If the
|
||||
worker exits, the daemon turns auto-checkpoint back on.
|
||||
- **Transactions.** `write` and `read` callbacks are synchronous, so a transaction never spans an
|
||||
`await` and transactions never interleave.
|
||||
- **Node.** `node:sqlite` needs Node 22.16 or later. Node 22 prints an experimental warning once,
|
||||
when the daemon opens the database.
|
||||
|
||||
### Agent timelines
|
||||
|
||||
`AgentTimeline` owns each agent's history, and its SQLite backend stores the projected rows, the
|
||||
source ranges, retirements, the open rewind, and provider children in `timeline_*` tables. The text
|
||||
of a streamed assistant or reasoning message is stored as one chunk per source event, beside its
|
||||
row, so a chunk never rewrites the message. An earlier file store rewrote the whole transcript on
|
||||
every update. See [owned history](timeline-sync.md#owned-history).
|
||||
|
||||
---
|
||||
|
||||
## 2. Daemon Configuration
|
||||
|
||||
**Path:** `$PASEO_HOME/config.json`
|
||||
|
||||
@@ -43,7 +43,11 @@ Math and video are disabled. Task lists and admonitions are enabled; task checkb
|
||||
|
||||
Mermaid fences use the existing isolated diagram runtime and fullscreen viewer. Web dispatches them through the library’s code-block override. Native has no block-renderer hook, so the renderer extracts only Mermaid fences and places the existing WebView host between library-rendered segments. This is the only block exception; see [native selection limitations](native-text-selection.md) for diagram grouping and leading inline images. Streaming keeps the last valid diagram visible while the next revision renders.
|
||||
|
||||
Native code blocks use the library's copy control and compiled grammars. Web code blocks use `HighlightedCodeBlock` through the library's `renderers.codeBlock` override. Selection copy has to tell links Paseo recognized in the text (paths, forge references, code spans) from links in the Markdown, so the web link renderer marks the recognized ones. Plain-text paste carries them as the text the reply showed, and rich paste keeps them as links only when they point to an `http` or `https` URL. Authored links and parser autolinks such as a bare `www.example.com` copy as links. The fork also keeps the library's block spacing around the web code block override, preserves web list numbering and link titles, marks pending parses with `aria-busy` so Find waits for rendered text, and carries link syntax through native and web tap events. Web inline code inside a link inherits only the link colour; its code font, size and background stay intact. Keep link variants colour-only: native pills replace text runs and prevent paths from wrapping; Android pills also use the surrounding block’s font size. [Upstream PR #997](https://github.com/software-mansion/enriched-markdown/pull/997) tracks these changes.
|
||||
Code blocks and plain quotes have a copy control in their top trailing corner. Native code blocks use the library's compiled grammars. On native, the code block and quote container views share one control (`HeaderCopyButton` on Android, `ENRMHeaderCopyButton` on iOS). A quote reserves the code block's header band above its body, so the control never covers quote text at any font size. On web, code blocks use `HighlightedCodeBlock` through the library's `renderers.codeBlock` override, and quotes use `WebBlockquote` through `renderers.blockquote`. Both use `BlockCopyButton`. On compact layouts the control is always visible, so the web quote reserves a band above its body, as native does. On wide layouts the control appears on hover or focus, so the quote keeps a right gutter instead; a band there would leave an empty strip above every quote.
|
||||
|
||||
A quote copies its body without the `>` markers, with its nested Markdown, and reads the content at the time of the press, so a streaming quote copies what it shows. A nested quote or code block keeps its own control. Web quote copy uses the same two clipboard flavors as selection copy: `text/plain` is unescaped Markdown and `text/html` is rendered from escaped Markdown. A rendered Mermaid diagram copies as its fence because its wrapper carries the fence source. Native quote copy serializes the quote's parsed Markdown, so a workspace image copies as its cached file URL, as native selection copy does; native has no map back to the workspace path. A native Mermaid diagram in a quote renders outside it (see [native selection limitations](native-text-selection.md)), so each quote fragment copies only its own text. Admonitions get no control: web renders them with a separate library renderer. On web an admonition inside a copied quote copies as its `> [!TYPE]` source; the fork marks the box and its generated title for this. Selection copy keeps the text it shows, because the cloned range cannot tell a whole callout from part of one. On native, quotes inside list items get no control, because they render as text spans in the item. Web renders them as blocks, so they get one.
|
||||
|
||||
Selection copy has to tell links Paseo recognized in the text (paths, forge references, code spans) from links in the Markdown, so the web link renderer marks the recognized ones. Plain-text paste carries them as the text the reply showed, and rich paste keeps them as links only when they point to an `http` or `https` URL. Authored links and parser autolinks such as a bare `www.example.com` copy as links. The fork also keeps the library's block spacing around the web code block override, preserves web list numbering and link titles, marks pending parses with `aria-busy` so Find waits for rendered text, and carries link syntax through native and web tap events. Web inline code inside a link inherits only the link colour; its code font, size and background stay intact. Keep link variants colour-only: native pills replace text runs and prevent paths from wrapping; Android pills also use the surrounding block’s font size. [Upstream PR #997](https://github.com/software-mansion/enriched-markdown/pull/997) tracks these changes.
|
||||
|
||||
The fork also keeps overflowing native horizontal blocks in control of their drags: Android claims parent interception at touch-down and releases it for vertical drags so the chat list can scroll; iOS keeps its scroll recognizer active for outward drags at the leading edge. This prevents compact sidebar pans from taking block scrolling without changing sidebar swipes on prose or non-overflowing blocks. Native changes require a client rebuild.
|
||||
|
||||
@@ -55,4 +59,4 @@ The library determines how incomplete Markdown appears during streaming. Complet
|
||||
|
||||
## Verification
|
||||
|
||||
Follow [QA](qa.md) and [mobile testing](mobile-testing.md). Exercise chat, file preview, plan and PR content on all three platforms. Include cross-paragraph selection, progressive streaming, a file-link tap, code copy/highlighting, a table and a workspace image. On iPad, repeat preview selection after opening and closing Explorer and after rotation. Check web find, selection-copy and source-message navigation after DOM changes.
|
||||
Follow [QA](qa.md) and [mobile testing](mobile-testing.md). Exercise chat, file preview, plan and PR content on all three platforms. Include cross-paragraph selection, progressive streaming, a file-link tap, code copy/highlighting, quote copy (nested quote, code block in a quote, admonition, large font on native), a table and a workspace image. On iPad, repeat preview selection after opening and closing Explorer and after rotation. Check web find, selection-copy and source-message navigation after DOM changes.
|
||||
|
||||
+1
-1
@@ -171,7 +171,7 @@ V2.0.4 also removed the activation endpoint that gated a cold location, and a co
|
||||
|
||||
Paseo installs its OpenCode tool bridge through `OPENCODE_CONFIG_CONTENT`. V1 accepts a plugin file; v2 silently skips configured files and requires a package directory with a server entry point. Both versions use the daemon's private loopback bridge for caller-scoped tools. The global manifest must use agent-scoped schemas before a session is bound, because every bridge call executes in an agent session. V2 discovers definitions from each bound session's catalog: plugin-contributed tools can be absent from the global manifest, and an allowlist cannot register a missing definition. Registration is location-wide, so session filtering and caller-scoped execution must remain in place. Bridge context lives only in daemon memory and is removed when the Paseo session closes. The content-addressed plugin artifacts contain no session data or secrets. V2 also needs this plugin when native Paseo tools are disabled: its prompt API has no structured-output format, so the plugin supplies a schema-validated final-answer tool.
|
||||
|
||||
An agent with custom environment variables or user-configured MCP servers gets a dedicated OpenCode server. V2 supports session environment, but its MCP configuration remains location-scoped, so separate servers still prevent one agent from changing another agent's MCP setup. Configure custom MCP with `mcp.add`; do not follow it with `mcp.connect`, which only toggles config-backed servers.
|
||||
No v2 agent gets a dedicated OpenCode server, because a reused server cannot provide one. OpenCode's MCP configuration is location-scoped, so Paseo never calls `mcp.add` for an agent. The daemon connects the agent's MCP servers itself (`v2/session-mcp.ts`), and the v2 plugin exposes their tools under OpenCode's native `<server>_<tool>` names. Each name registers once per location. The plugin's `context` hook gives each session its own definition and removes the tool from other sessions. If the user's own OpenCode configuration registered a tool with the same name first, other sessions keep that tool and its execution. Execution routes to the calling session's root binding. The hook also adds the servers' instructions to each request. OpenCode loads instruction entries before the hook runs, so an entry written when a child is adopted would miss the child's first request. The plugin calls OpenCode's `permission.assert` before each call, so `toolPolicy.preapproved` grants still apply. That API exists from OpenCode 2.0.29. Bind reports `features.mcpTools`, so an older server or a stale plugin fails the session at creation instead of hiding its tools. Per-agent `launch.env` reaches shells through `session.environment`, which child sessions do not inherit. The plugin asks the daemon to adopt each descendant in its first `context` hook, before its first model request.
|
||||
|
||||
OpenCode owns user message IDs. Do not pass Paseo-generated IDs to OpenCode prompt APIs; let OpenCode create `msg*` IDs and record the user timeline item from the `message.updated` event.
|
||||
|
||||
|
||||
+11
-68
@@ -5,9 +5,15 @@ Agent chat delivery has two paths:
|
||||
1. **Live stream** — `agent_stream` WebSocket messages for immediacy. These may be delta-shaped lifecycle updates.
|
||||
2. **Authoritative history** — `fetch_agent_timeline_request` for correctness. This always returns full projected timeline items, never lifecycle deltas.
|
||||
|
||||
Pagination bounds each read, not total resident history. Streaming overhead must remain
|
||||
proportional to the retained transcript. Cumulative text snapshots must be released after their
|
||||
deltas have been consumed.
|
||||
The daemon retains projected items in memory. Each source event advances the stream sequence,
|
||||
then replaces the previous tool state or merges into the current text item. Intermediate payloads
|
||||
are never retained for history or catch-up. Provider history is the durable transcript authority
|
||||
and rebuilds the projection when an agent resumes.
|
||||
|
||||
Pagination bounds each read, not total resident history. Active and idle agents retain their
|
||||
projected transcript; archive releases it and later history reads rebuild it from the provider.
|
||||
Streaming overhead must remain proportional to the retained transcript. Cumulative text snapshots
|
||||
must be released after their deltas have been consumed.
|
||||
|
||||
The invariants are:
|
||||
|
||||
@@ -26,50 +32,6 @@ bounded item is used for runtime timeline rows and live stream events. Provider
|
||||
applies the same rule so reopening an agent cannot restore an oversized payload. Fetches apply it
|
||||
again to assistant and reasoning rows the projection merges from many chunks.
|
||||
|
||||
## Owned history
|
||||
|
||||
The daemon owns each agent's history in `AgentTimeline`
|
||||
(`packages/server/src/server/agent/timeline/`): one ordered history per agent, with each provider
|
||||
child's descriptor and history in a child scope of the same agent. Each source event advances the
|
||||
stream sequence, then replaces the previous tool state or merges into the current text item.
|
||||
Intermediate payloads are never retained for history or catch-up.
|
||||
|
||||
History is append-only: rewind, import, reload and archive never delete or rewrite a row. Only
|
||||
deleting the agent, or a provider removing one of its own children, deletes history.
|
||||
|
||||
- **Rewind** retires a range of rows. They leave the conversation and stay stored, in the same
|
||||
epoch. See [Rewind retires rows](#rewind-retires-rows).
|
||||
- **Provider history** is imported only into an agent that has no history. After that, resume
|
||||
does not read it. Reload agent and Unarchive require the provider history to start with the
|
||||
same prompt IDs and text in order. They then append whole new turns, starting at the next
|
||||
prompt. Existing replies, including partial replies, stay as recorded. If the prompts differ,
|
||||
for example because the provider stored expanded attachment text, the chat stays unchanged and
|
||||
Paseo reports a mismatch. A provider child Paseo already holds, listed or retired, is never imported again.
|
||||
- **Archive and reload** keep the history and the provider children. An archived chat reads them
|
||||
without its provider. Opening a stored agent that has no provider session to resume starts its
|
||||
first session on the same history.
|
||||
- **Delete** removes the agent's history and every child's, retired ones included, before the
|
||||
agent record. If the history cannot be removed, the request fails and the agent stays listed. The
|
||||
user can keep using it and delete it again.
|
||||
|
||||
`epoch` is the stored history's identity, minted once when the history is created.
|
||||
|
||||
`AgentTimeline` serializes every operation of one agent, child scopes included, and keeps its
|
||||
state in an `AgentTimelineBackend`: the sequence, the rows and retirements, prompt identities, the
|
||||
open rewind, and the children. The backend contract suite is `agent-timeline.test.ts`, run over
|
||||
`TIMELINE_CONTRACT_BACKENDS` in `timeline/testing.ts`. The daemon uses the SQLite backend in the
|
||||
[daemon database](data-model.md#daemon-database). History, retirements, the open rewind, and
|
||||
provider children survive a daemon restart in the same epoch, so clients keep their cursors. A
|
||||
closed or archived agent holds no history in memory. Each fetch reads the page from the database
|
||||
and starts no provider. An internal agent, such as the one that writes a commit message, keeps its
|
||||
history in a memory backend instead, so it leaves nothing on disk. The memory backend also serves
|
||||
tests.
|
||||
|
||||
An open rewind is stored with the history. Resuming an agent whose history holds one settles it
|
||||
before the agent takes prompts: a recorded provider cut is committed, and an unknown outcome is
|
||||
judged from the resumed provider history. When that history proves nothing, the rewind stays open
|
||||
and the agent refuses prompts with the unknown-outcome error.
|
||||
|
||||
## Presence is not delivery
|
||||
|
||||
Client heartbeat reports presence:
|
||||
@@ -206,7 +168,7 @@ or retry backoff. This cannot keep a mobile socket alive after the operating sys
|
||||
bookkeeping without replacing timeline arrays, preserving an upward-scrolled viewport.
|
||||
- When the page overlaps or is adjacent to the local end cursor, only projected items newer than
|
||||
that cursor are applied. Already-covered rows are not replayed.
|
||||
- A true middle gap or epoch change atomically replaces stale canonical history with the
|
||||
- A true middle gap, epoch change, or rewind atomically replaces stale canonical history with the
|
||||
latest tail. The replacement reconciles positioned live rows beyond its coverage and unresolved
|
||||
local submissions; it never retains two discontiguous canonical ranges.
|
||||
|
||||
@@ -219,24 +181,6 @@ history replay. The pending approval UI can hide that tool from presentation, bu
|
||||
must retain its position. Creating a new history card on rejection places it after the prompt that
|
||||
rejected it; changing steer-event ordering would also put new assistant output before that prompt.
|
||||
|
||||
## Rewind retires rows
|
||||
|
||||
A conversation rewind commits a retirement `{ seq, retireFromSeq }`: active rows anchored in
|
||||
`[retireFromSeq, seq)` leave the conversation, and `seq` is the retirement's own position in the
|
||||
sequence. The provider children spawned by retired tool calls, and their descendants, are retired
|
||||
in the same commit. They leave the listing, keep their history, and drop late provider events.
|
||||
|
||||
Clients learn of a retirement live through `agent.timeline.rewind`, and on pages through
|
||||
`retirements`, which lists the retirements whose `seq` lies inside the page's span. The client
|
||||
drops the rows it holds in that range; rows without a timeline position are unechoed local sends
|
||||
and stay. Retired ranges and the retirement's `seq` count as covered, so forward cursors advance
|
||||
through them. Tail, before and prompt-jump pages are served from active rows, so one served before
|
||||
a retirement the client already applied is stale and is refetched (`viewed-timeline-sync.ts`).
|
||||
|
||||
Clients without `timeline_rewind_operations` cannot drop retired rows. For them the session derives
|
||||
a wire epoch that changes with each retirement, so they take the destructive replacement they
|
||||
always took on rewind. The shim is tagged `COMPAT(timelineRewindOperations)`.
|
||||
|
||||
## Provider child history
|
||||
|
||||
Child transcripts use the same projected-page reconciliation as the main conversation. The client
|
||||
@@ -401,7 +345,7 @@ the draft-create handoff is the one boundary that also permits the legacy canoni
|
||||
arrived first. Generic reducers and consumers do not reimplement message identity matching.
|
||||
|
||||
Ordinary bootstrap, same-epoch reset, and catch-up replacement preserve unmatched locally submitted
|
||||
rows because a provider may never echo them. A known epoch change replaces history and
|
||||
rows because a provider may never echo them. A known epoch change or rewind replaces history and
|
||||
drops acknowledged local rows omitted by the new canonical epoch; every transaction not yet
|
||||
acknowledged by the provider, and no other local row, crosses that destructive boundary. A cold
|
||||
reset without an existing epoch is destructive because the client has no continuity anchor.
|
||||
@@ -417,7 +361,6 @@ canonical assistant prefix, it stays in the head lane. No row may be returned in
|
||||
|
||||
## Relevant code
|
||||
|
||||
- Server owned history: `packages/server/src/server/agent/timeline/`
|
||||
- Server live stream forwarding: `packages/server/src/server/session.ts`
|
||||
- App sync planning: `packages/app/src/timeline/timeline-sync-plan.ts`
|
||||
- App viewed-agent synchronization: `packages/app/src/timeline/viewed-timeline-sync.ts`
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
sha256-IAhKhkolW4xvFvMaAEFdhYvPAhTm2azsqbGMKCKL3q0=
|
||||
sha256-TAVzJzziWDAapQkG4TLkLzOlodkdFNKSl3y/Tm9HB28=
|
||||
|
||||
Generated
+1
-20
@@ -45,9 +45,6 @@
|
||||
"react-dom": "19.2.3",
|
||||
"typescript": "^5.9.3",
|
||||
"ws": "^8.20.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.16.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@0no-co/graphql.web": {
|
||||
@@ -39722,9 +39719,6 @@
|
||||
"typescript": "^5.2.2",
|
||||
"vitest": "^4.1.6",
|
||||
"zx": "^8.8.5"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.16.0"
|
||||
}
|
||||
},
|
||||
"packages/cli/node_modules/@vitest/expect": {
|
||||
@@ -40652,7 +40646,7 @@
|
||||
"@playwright/test": "^1.56.1",
|
||||
"@types/express": "^4.17.20",
|
||||
"@types/markdown-it": "^14.2.0",
|
||||
"@types/node": "^22.16.0",
|
||||
"@types/node": "^20.9.0",
|
||||
"@types/qrcode": "^1.5.6",
|
||||
"@types/uuid": "^9.0.7",
|
||||
"@types/ws": "^8.5.8",
|
||||
@@ -40660,9 +40654,6 @@
|
||||
"cross-env": "^10.1.0",
|
||||
"tsx": "^4.6.0",
|
||||
"vitest": "^4.1.6"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.16.0"
|
||||
}
|
||||
},
|
||||
"packages/server/node_modules/@esbuild/aix-ppc64": {
|
||||
@@ -41110,16 +41101,6 @@
|
||||
"@types/mdurl": "^2"
|
||||
}
|
||||
},
|
||||
"packages/server/node_modules/@types/node": {
|
||||
"version": "22.20.5",
|
||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.5.tgz",
|
||||
"integrity": "sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"undici-types": "~6.21.0"
|
||||
}
|
||||
},
|
||||
"packages/server/node_modules/@vitest/expect": {
|
||||
"version": "4.1.6",
|
||||
"resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.6.tgz",
|
||||
|
||||
@@ -169,8 +169,5 @@
|
||||
"tiny-async-pool": {
|
||||
"semver@^5": "5.7.2"
|
||||
}
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.16.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,27 +5,26 @@ import path from "node:path";
|
||||
import { test, expect } from "../support/fixtures";
|
||||
import {
|
||||
addProjectFlow,
|
||||
chooseAddHostFromProjectFlow,
|
||||
addProjectFlowBack,
|
||||
addProjectFlowHost,
|
||||
addProjectFlowHostTrigger,
|
||||
addProjectFlowInput,
|
||||
addProjectFlowMethod,
|
||||
chooseAddProjectMethod,
|
||||
expectAddProjectPage,
|
||||
expectNewWorkspaceForAddedProject,
|
||||
addProjectFlowSubmit,
|
||||
chooseAddHostFromProjectFlow,
|
||||
chooseAddProjectHost,
|
||||
chooseAddProjectLocation,
|
||||
chooseAddProjectTab,
|
||||
expectAddProjectResultVisible,
|
||||
expectAddProjectTab,
|
||||
expectNewWorkspaceForAddedProject,
|
||||
navigateAddProjectResults,
|
||||
navigateAndDismissAddProject,
|
||||
watchAddProjectRenderWarnings,
|
||||
openAddProjectFlow,
|
||||
openAddProjectHostSelection,
|
||||
watchAddProjectRenderWarnings,
|
||||
} from "../support/helpers/add-project-flow";
|
||||
import { gotoAppShell } from "../support/helpers/app";
|
||||
import {
|
||||
disconnectAllHostsAndReload,
|
||||
addConnectedHostAndReload,
|
||||
addConnectedHostsAndReload,
|
||||
addOfflineHostAndReload,
|
||||
disconnectAllHostsAndReload,
|
||||
waitForConnectedHost,
|
||||
} from "../support/helpers/hosts";
|
||||
import {
|
||||
@@ -36,6 +35,8 @@ import { expectOpenedProject } from "../support/helpers/project-picker-ui";
|
||||
import { connectSeedClient } from "../support/helpers/seed-client";
|
||||
import { getServerId } from "../support/helpers/server-id";
|
||||
|
||||
const MOD = process.platform === "darwin" ? "Meta" : "Control";
|
||||
|
||||
const SECONDARY_HOST_ID = "add-project-flow-secondary";
|
||||
const SECONDARY_HOST_LABEL = "Secondary Host";
|
||||
|
||||
@@ -70,13 +71,14 @@ async function expectProjectHasNoWorkspaces(projectId: string): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
test.describe("Add Project command-center flow", () => {
|
||||
test.describe("Add project sheet", () => {
|
||||
test.describe.configure({ timeout: 180_000 });
|
||||
|
||||
test("Add host replaces the project dialog when no hosts are connected", async ({ page }) => {
|
||||
test("Add host replaces the project sheet when no hosts are connected", async ({ page }) => {
|
||||
await gotoAppShell(page);
|
||||
await disconnectAllHostsAndReload(page);
|
||||
await openAddProjectHostSelection(page);
|
||||
await page.locator('[data-testid="sidebar-add-project"]:visible').click();
|
||||
await expect(addProjectFlow(page)).toContainText("No connected hosts");
|
||||
const originalUrl = page.url();
|
||||
await chooseAddHostFromProjectFlow(page);
|
||||
await expect(addProjectFlow(page)).toBeHidden();
|
||||
@@ -86,22 +88,36 @@ test.describe("Add Project command-center flow", () => {
|
||||
await expect(page).toHaveURL(originalUrl);
|
||||
});
|
||||
|
||||
test("method selection shows the daemon's available project sources without search", async ({
|
||||
test("opens on Existing, switches tabs with Mod+1/2/3, keeps each draft, and closes on Escape", async ({
|
||||
page,
|
||||
}) => {
|
||||
const renderWarnings = watchAddProjectRenderWarnings(page);
|
||||
await gotoAppShell(page);
|
||||
|
||||
await openAddProjectFlow(page);
|
||||
|
||||
await expect(addProjectFlowMethod(page, "directory-search")).toBeVisible();
|
||||
await expect(addProjectFlowMethod(page, "github")).toContainText("Clone from GitHub");
|
||||
await expect(addProjectFlowMethod(page, "new-directory")).toContainText("New directory");
|
||||
await expect(addProjectFlowInput(page)).toHaveCount(0);
|
||||
await expect(addProjectFlow(page).getByRole("textbox")).toHaveCount(0);
|
||||
await expect(page.getByTestId("add-project-flow-page-host")).toHaveCount(0);
|
||||
await page.keyboard.type("paseo");
|
||||
await page.keyboard.press(`${MOD}+2`);
|
||||
await expectAddProjectTab(page, "clone");
|
||||
await expect(addProjectFlowInput(page)).toBeFocused();
|
||||
await page.keyboard.type("getpaseo/");
|
||||
await page.keyboard.press(`${MOD}+3`);
|
||||
await expectAddProjectTab(page, "new-folder");
|
||||
await expect(addProjectFlowSubmit(page)).toBeDisabled();
|
||||
|
||||
await page.keyboard.press(`${MOD}+1`);
|
||||
await expectAddProjectTab(page, "existing");
|
||||
await expect(addProjectFlowInput(page)).toHaveValue("paseo");
|
||||
await chooseAddProjectTab(page, "clone");
|
||||
await expect(addProjectFlowInput(page)).toHaveValue("getpaseo/");
|
||||
|
||||
await navigateAndDismissAddProject(page);
|
||||
await expect(addProjectFlow(page)).not.toBeVisible();
|
||||
expect(renderWarnings).toEqual([]);
|
||||
});
|
||||
|
||||
test("an offline extra host neither appears nor forces host selection", async ({ page }) => {
|
||||
test("a single connected host shows no host picker, even with an offline host", async ({
|
||||
page,
|
||||
}) => {
|
||||
await gotoAppShell(page);
|
||||
await addOfflineHostAndReload(page, {
|
||||
serverId: "add-project-flow-offline",
|
||||
@@ -110,8 +126,7 @@ test.describe("Add Project command-center flow", () => {
|
||||
|
||||
await openAddProjectFlow(page);
|
||||
|
||||
await expect(addProjectFlowHost(page, "add-project-flow-offline")).toHaveCount(0);
|
||||
await expect(addProjectFlowMethod(page, "directory-search")).toBeVisible();
|
||||
await expect(addProjectFlowHostTrigger(page)).toHaveCount(0);
|
||||
});
|
||||
|
||||
test.describe("with two connected hosts", () => {
|
||||
@@ -125,73 +140,7 @@ test.describe("Add Project command-center flow", () => {
|
||||
await secondaryHost?.close();
|
||||
});
|
||||
|
||||
test("keyboard selection chooses the second host", async ({ page }) => {
|
||||
await gotoAppShell(page);
|
||||
await addConnectedHostAndReload(page, {
|
||||
serverId: secondaryHost.serverId,
|
||||
label: SECONDARY_HOST_LABEL,
|
||||
port: secondaryHost.port,
|
||||
});
|
||||
await waitForConnectedHost(page, {
|
||||
serverId: SECONDARY_HOST_ID,
|
||||
endpoint: `localhost:${secondaryHost.port}`,
|
||||
});
|
||||
await openAddProjectHostSelection(page);
|
||||
|
||||
await page.keyboard.press("ArrowDown");
|
||||
await page.keyboard.press("Enter");
|
||||
|
||||
await expectAddProjectPage(page, "method");
|
||||
await expect(addProjectFlow(page)).toContainText(SECONDARY_HOST_LABEL);
|
||||
});
|
||||
|
||||
test("Escape and Back restore searchable page input before closing at the root", async ({
|
||||
page,
|
||||
}) => {
|
||||
const renderWarnings = watchAddProjectRenderWarnings(page);
|
||||
await gotoAppShell(page);
|
||||
await addConnectedHostAndReload(page, {
|
||||
serverId: secondaryHost.serverId,
|
||||
label: SECONDARY_HOST_LABEL,
|
||||
port: secondaryHost.port,
|
||||
});
|
||||
await waitForConnectedHost(page, {
|
||||
serverId: SECONDARY_HOST_ID,
|
||||
endpoint: `localhost:${secondaryHost.port}`,
|
||||
});
|
||||
await openAddProjectHostSelection(page);
|
||||
|
||||
await addProjectFlowInput(page).fill("o");
|
||||
await page.keyboard.press("ArrowDown");
|
||||
await page.keyboard.press("Enter");
|
||||
await expectAddProjectPage(page, "method");
|
||||
|
||||
await chooseAddProjectMethod(page, "new-directory");
|
||||
await expectAddProjectPage(page, "new-directory-parent");
|
||||
await page.keyboard.press("Escape");
|
||||
|
||||
await expectAddProjectPage(page, "method");
|
||||
await expect(addProjectFlowInput(page)).toHaveCount(0);
|
||||
await chooseAddProjectMethod(page, "new-directory");
|
||||
await expectAddProjectPage(page, "new-directory-parent");
|
||||
await addProjectFlowBack(page).click();
|
||||
|
||||
await expectAddProjectPage(page, "method");
|
||||
await addProjectFlowBack(page).click();
|
||||
await expectAddProjectPage(page, "host");
|
||||
await expect(addProjectFlowInput(page)).toHaveValue("o");
|
||||
await page.keyboard.press("Enter");
|
||||
await expectAddProjectPage(page, "method");
|
||||
await expect(addProjectFlow(page)).toContainText(SECONDARY_HOST_LABEL);
|
||||
|
||||
await page.keyboard.press("Escape");
|
||||
await expectAddProjectPage(page, "host");
|
||||
await navigateAndDismissAddProject(page);
|
||||
await expect(addProjectFlow(page)).not.toBeVisible();
|
||||
expect(renderWarnings).toEqual([]);
|
||||
});
|
||||
|
||||
test("New directory creates a Project on the selected remote host", async ({ page }) => {
|
||||
test("New folder creates a Project on the host chosen in the sheet", async ({ page }) => {
|
||||
const parentDirectory = await mkdtemp(path.join(tmpdir(), "paseo-e2e-remote-project-"));
|
||||
const directoryName = `remote-${randomUUID().slice(0, 8)}`;
|
||||
const directoryPath = path.join(parentDirectory, directoryName);
|
||||
@@ -207,18 +156,15 @@ test.describe("Add Project command-center flow", () => {
|
||||
serverId: SECONDARY_HOST_ID,
|
||||
endpoint: `localhost:${secondaryHost.port}`,
|
||||
});
|
||||
await openAddProjectHostSelection(page);
|
||||
await addProjectFlowHost(page, SECONDARY_HOST_ID).click();
|
||||
await expectAddProjectPage(page, "method");
|
||||
await openAddProjectFlow(page);
|
||||
await chooseAddProjectTab(page, "new-folder");
|
||||
await addProjectFlowInput(page).fill(directoryName);
|
||||
|
||||
await expect(addProjectFlowMethod(page, "new-directory")).toContainText(
|
||||
`Create an empty directory on ${SECONDARY_HOST_LABEL}`,
|
||||
);
|
||||
await chooseAddProjectMethod(page, "new-directory");
|
||||
await addProjectFlowInput(page).fill(parentDirectory);
|
||||
await page.keyboard.press("Enter");
|
||||
await expectAddProjectPage(page, "new-directory-name");
|
||||
await page.keyboard.type(directoryName);
|
||||
await chooseAddProjectHost(page, SECONDARY_HOST_ID);
|
||||
await expect(addProjectFlowHostTrigger(page)).toContainText(SECONDARY_HOST_LABEL);
|
||||
await expect(addProjectFlowInput(page)).toHaveValue(directoryName);
|
||||
await chooseAddProjectLocation(page, parentDirectory);
|
||||
await addProjectFlowInput(page).focus();
|
||||
await page.keyboard.press("Enter");
|
||||
|
||||
const projectId = await expectOpenedProject(page, directoryName);
|
||||
@@ -236,57 +182,35 @@ test.describe("Add Project command-center flow", () => {
|
||||
});
|
||||
});
|
||||
|
||||
test("filtered hosts keep the keyboard-selected row visible", async ({ page }) => {
|
||||
const hosts: IsolatedHostDaemon[] = [];
|
||||
test("a host that disconnects keeps its draft and blocks submit instead of moving it", async ({
|
||||
page,
|
||||
}) => {
|
||||
const droppingHost = await startIsolatedHostDaemon("add-project-flow-dropping");
|
||||
try {
|
||||
for (let index = 1; index <= 3; index += 1) {
|
||||
hosts.push(await startIsolatedHostDaemon(`scroll-host-${index}`));
|
||||
}
|
||||
await page.setViewportSize({ width: 1280, height: 360 });
|
||||
await gotoAppShell(page);
|
||||
await addConnectedHostsAndReload(
|
||||
page,
|
||||
hosts.map((host, index) => ({
|
||||
serverId: host.serverId,
|
||||
port: host.port,
|
||||
label: index < 2 ? `Fleet 0${index + 1}` : "Other host",
|
||||
})),
|
||||
{ primaryLabel: "Fleet 00" },
|
||||
await addConnectedHostAndReload(page, {
|
||||
serverId: droppingHost.serverId,
|
||||
label: "Dropping Host",
|
||||
port: droppingHost.port,
|
||||
});
|
||||
await waitForConnectedHost(page, {
|
||||
serverId: droppingHost.serverId,
|
||||
endpoint: `localhost:${droppingHost.port}`,
|
||||
});
|
||||
await openAddProjectFlow(page);
|
||||
await chooseAddProjectHost(page, droppingHost.serverId);
|
||||
await addProjectFlowInput(page).fill(homedir());
|
||||
|
||||
await droppingHost.close();
|
||||
await expect(page.getByTestId("add-project-flow-error")).toHaveText(
|
||||
"Dropping Host is offline",
|
||||
{ timeout: 30_000 },
|
||||
);
|
||||
for (const host of hosts) {
|
||||
await waitForConnectedHost(page, {
|
||||
serverId: host.serverId,
|
||||
endpoint: `localhost:${host.port}`,
|
||||
});
|
||||
}
|
||||
await openAddProjectHostSelection(page);
|
||||
await expect(
|
||||
addProjectFlow(page).getByRole("button").filter({ hasText: "Other host" }),
|
||||
).toBeVisible();
|
||||
|
||||
await addProjectFlowInput(page).fill("Fleet");
|
||||
await expect(addProjectFlowHost(page, hosts[2]!.serverId)).toHaveCount(0);
|
||||
await navigateAddProjectResults(page, "ArrowDown", 2);
|
||||
await expectAddProjectResultVisible(page, "Fleet 02");
|
||||
|
||||
// Filtering out the first host moves retained rows to new positions.
|
||||
await addProjectFlowInput(page).fill("scroll-host");
|
||||
await expect(addProjectFlowHost(page, getServerId())).toHaveCount(0);
|
||||
await expectAddProjectResultVisible(page, "Fleet 01");
|
||||
await navigateAddProjectResults(page, "ArrowDown", 2);
|
||||
await expectAddProjectResultVisible(page, "Other host");
|
||||
await navigateAddProjectResults(page, "ArrowDown", 1);
|
||||
await expectAddProjectResultVisible(page, "Fleet 01");
|
||||
|
||||
await addProjectFlowInput(page).fill("Fleet");
|
||||
await expectAddProjectResultVisible(page, "Fleet 00");
|
||||
await navigateAddProjectResults(page, "ArrowDown", 2);
|
||||
await expectAddProjectResultVisible(page, "Fleet 02");
|
||||
await page.keyboard.press("Enter");
|
||||
await expectAddProjectPage(page, "method");
|
||||
await expect(addProjectFlow(page)).toContainText("Fleet 02");
|
||||
await expect(addProjectFlowHostTrigger(page)).toContainText("Dropping Host");
|
||||
await expect(addProjectFlowInput(page)).toHaveValue(homedir());
|
||||
await expect(addProjectFlowSubmit(page)).toBeDisabled();
|
||||
} finally {
|
||||
await Promise.all(hosts.map((host) => host.close()));
|
||||
await droppingHost.close();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -297,9 +221,6 @@ test.describe("Add Project command-center flow", () => {
|
||||
await gotoAppShell(page);
|
||||
await openAddProjectFlow(page);
|
||||
|
||||
await page.keyboard.press("Enter");
|
||||
await expectAddProjectPage(page, "directory-search");
|
||||
await expect(addProjectFlowInput(page)).toBeFocused();
|
||||
await page.keyboard.type(projectPickerFixture.fuzzyQuery);
|
||||
await expect(addProjectFlow(page)).toContainText(projectPickerFixture.projectName, {
|
||||
timeout: 30_000,
|
||||
@@ -323,45 +244,32 @@ test.describe("Add Project command-center flow", () => {
|
||||
const parentDirectory = await mkdtemp(path.join(homedir(), "paseo-e2e-scroll-"));
|
||||
const rowPath = (index: number) =>
|
||||
path.join(parentDirectory, `scroll-probe-${String(index).padStart(2, "0")}`);
|
||||
const rowName = (index: number) => path.basename(rowPath(index));
|
||||
let projectId: string | null = null;
|
||||
try {
|
||||
await Promise.all(Array.from({ length: 16 }, (_, index) => mkdir(rowPath(index))));
|
||||
await gotoAppShell(page);
|
||||
await openAddProjectFlow(page);
|
||||
await chooseAddProjectMethod(page, "directory-search");
|
||||
await addProjectFlowInput(page).fill(path.basename(parentDirectory));
|
||||
await addProjectFlowInput(page).fill(`${path.basename(parentDirectory)}/scroll-probe`);
|
||||
const results = page.getByTestId("add-project-flow-results");
|
||||
await expect(results.getByRole("button", { name: /scroll-probe-/ })).toHaveCount(16, {
|
||||
timeout: 30_000,
|
||||
});
|
||||
|
||||
await navigateAddProjectResults(page, "ArrowDown", 12);
|
||||
await expectAddProjectResultVisible(page, rowPath(11));
|
||||
await navigateAddProjectResults(page, "ArrowDown", 11);
|
||||
await expectAddProjectResultVisible(page, rowName(11));
|
||||
await navigateAddProjectResults(page, "ArrowUp", 12);
|
||||
await expectAddProjectResultVisible(page, parentDirectory);
|
||||
await navigateAddProjectResults(page, "ArrowUp", 1);
|
||||
await expectAddProjectResultVisible(page, rowPath(15));
|
||||
await expectAddProjectResultVisible(page, rowName(15));
|
||||
await navigateAddProjectResults(page, "ArrowDown", 1);
|
||||
await expectAddProjectResultVisible(page, parentDirectory);
|
||||
await expectAddProjectResultVisible(page, rowName(0));
|
||||
|
||||
await navigateAddProjectResults(page, "ArrowDown", 12);
|
||||
await expectAddProjectResultVisible(page, rowPath(11));
|
||||
await addProjectFlowInput(page).fill(`${path.basename(parentDirectory)}probe`);
|
||||
await expect(results.getByRole("button")).toHaveCount(16);
|
||||
await expectAddProjectResultVisible(page, rowPath(0));
|
||||
await navigateAddProjectResults(page, "ArrowDown", 12);
|
||||
await expectAddProjectResultVisible(page, rowPath(12));
|
||||
await addProjectFlowInput(page).fill(path.basename(parentDirectory));
|
||||
await expect(results.getByRole("button")).toHaveCount(17);
|
||||
await expectAddProjectResultVisible(page, parentDirectory);
|
||||
await navigateAddProjectResults(page, "ArrowDown", 12);
|
||||
await expectAddProjectResultVisible(page, rowPath(11));
|
||||
await navigateAddProjectResults(page, "ArrowDown", 11);
|
||||
await page.keyboard.press("Enter");
|
||||
projectId = await expectOpenedProject(page, "scroll-probe-11");
|
||||
projectId = await expectOpenedProject(page, rowName(11));
|
||||
await expectNewWorkspaceForAddedProject(page, {
|
||||
serverId: getServerId(),
|
||||
projectId,
|
||||
projectName: "scroll-probe-11",
|
||||
projectName: rowName(11),
|
||||
projectPath: rowPath(11),
|
||||
});
|
||||
} finally {
|
||||
@@ -370,28 +278,146 @@ test.describe("Add Project command-center flow", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("a complete repository URL remains selectable without a GitHub search result", async ({
|
||||
test("Enter on a focused result adds that folder, not the one picked before", async ({
|
||||
page,
|
||||
}) => {
|
||||
const parentDirectory = await mkdtemp(path.join(homedir(), "paseo-e2e-focus-"));
|
||||
const firstPath = path.join(parentDirectory, "focus-probe-a");
|
||||
const secondPath = path.join(parentDirectory, "focus-probe-b");
|
||||
let projectId: string | null = null;
|
||||
try {
|
||||
await Promise.all([mkdir(firstPath), mkdir(secondPath)]);
|
||||
await gotoAppShell(page);
|
||||
await openAddProjectFlow(page);
|
||||
await addProjectFlowInput(page).fill(`${path.basename(parentDirectory)}/focus-probe`);
|
||||
const results = page.getByTestId("add-project-flow-results");
|
||||
await expect(results.getByRole("button", { name: /focus-probe-/ })).toHaveCount(2, {
|
||||
timeout: 30_000,
|
||||
});
|
||||
|
||||
await results.getByRole("button", { name: /focus-probe-b/ }).focus();
|
||||
await page.keyboard.press("Enter");
|
||||
projectId = await expectOpenedProject(page, "focus-probe-b");
|
||||
await expectNewWorkspaceForAddedProject(page, {
|
||||
serverId: getServerId(),
|
||||
projectId,
|
||||
projectName: "focus-probe-b",
|
||||
projectPath: secondPath,
|
||||
});
|
||||
} finally {
|
||||
if (projectId) await removeCreatedProject(secondPath, projectId);
|
||||
await rm(parentDirectory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("Enter while a new search runs does not open a row from the previous search", async ({
|
||||
page,
|
||||
}) => {
|
||||
const parentDirectory = await mkdtemp(path.join(homedir(), "paseo-e2e-stale-"));
|
||||
try {
|
||||
await mkdir(path.join(parentDirectory, "stale-probe-a"));
|
||||
await gotoAppShell(page);
|
||||
await openAddProjectFlow(page);
|
||||
const prefix = path.basename(parentDirectory);
|
||||
await addProjectFlowInput(page).fill(`${prefix}/stale-probe`);
|
||||
const results = page.getByTestId("add-project-flow-results");
|
||||
await expect(results.getByRole("button", { name: /stale-probe-a/ })).toBeVisible({
|
||||
timeout: 30_000,
|
||||
});
|
||||
|
||||
await addProjectFlowInput(page).fill(`${prefix}/no-such-folder`);
|
||||
await page.keyboard.press("Enter");
|
||||
await expect(addProjectFlow(page).getByText("No matching folders")).toBeVisible({
|
||||
timeout: 30_000,
|
||||
});
|
||||
await expect(addProjectFlow(page)).toBeVisible();
|
||||
await expect(addProjectFlowSubmit(page)).toBeDisabled();
|
||||
} finally {
|
||||
await rm(parentDirectory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("a complete repository URL is cloneable without a GitHub search result", async ({
|
||||
page,
|
||||
}) => {
|
||||
await gotoAppShell(page);
|
||||
await openAddProjectFlow(page);
|
||||
await chooseAddProjectMethod(page, "github");
|
||||
await chooseAddProjectTab(page, "clone");
|
||||
|
||||
const remote = "https://github.invalid/acme/manual.git";
|
||||
await addProjectFlowInput(page).fill(remote);
|
||||
await expect(addProjectFlow(page).getByText("manual", { exact: true })).toBeVisible();
|
||||
await page.keyboard.press("Enter");
|
||||
|
||||
await expectAddProjectPage(page, "github-location");
|
||||
const title = addProjectFlow(page).getByTestId("add-project-flow-title");
|
||||
await expect(title.getByText("Choose destination", { exact: true })).toBeVisible();
|
||||
await expect(title.getByText("localhost", { exact: true })).toBeVisible();
|
||||
await expect(title).not.toContainText("Where should Paseo create");
|
||||
await addProjectFlowBack(page).click();
|
||||
await expect(addProjectFlowInput(page)).toHaveValue(remote);
|
||||
await expect(page.getByTestId("add-project-flow-location")).toContainText("/manual");
|
||||
await expect(addProjectFlowSubmit(page)).toBeEnabled();
|
||||
});
|
||||
|
||||
test("New directory validates the name, restores parent and name state, then creates a Project", async ({
|
||||
test("Enter activates a focused button instead of the primary action", async ({ page }) => {
|
||||
await gotoAppShell(page);
|
||||
await openAddProjectFlow(page);
|
||||
await chooseAddProjectTab(page, "clone");
|
||||
await addProjectFlowInput(page).fill("https://github.invalid/acme/manual.git");
|
||||
await expect(addProjectFlowSubmit(page)).toBeEnabled();
|
||||
|
||||
await addProjectFlow(page).getByRole("button", { name: "Close", exact: true }).focus();
|
||||
await page.keyboard.press("Enter");
|
||||
await expect(addProjectFlow(page)).toBeHidden();
|
||||
});
|
||||
|
||||
test("a row picked during a search is not replaced by the answer's first row", async ({
|
||||
page,
|
||||
}) => {
|
||||
const parentDirectory = await mkdtemp(path.join(homedir(), "paseo-e2e-dropped-pick-"));
|
||||
try {
|
||||
await Promise.all([
|
||||
mkdir(path.join(parentDirectory, "previous-probe")),
|
||||
mkdir(path.join(parentDirectory, "incoming-probe")),
|
||||
]);
|
||||
await gotoAppShell(page);
|
||||
await openAddProjectFlow(page);
|
||||
const prefix = path.basename(parentDirectory);
|
||||
const results = page.getByTestId("add-project-flow-results");
|
||||
await addProjectFlowInput(page).fill(`${prefix}/previous-probe`);
|
||||
await expect(results.getByRole("button", { name: /previous-probe/ })).toBeVisible({
|
||||
timeout: 30_000,
|
||||
});
|
||||
|
||||
await addProjectFlowInput(page).fill(`${prefix}/incoming-probe`);
|
||||
await page.keyboard.press("ArrowDown");
|
||||
await expect(results.getByRole("button", { name: /incoming-probe/ })).toBeVisible({
|
||||
timeout: 30_000,
|
||||
});
|
||||
await expect(addProjectFlowSubmit(page)).toBeDisabled();
|
||||
} finally {
|
||||
await rm(parentDirectory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("Enter in Location while a new search runs keeps the current location", async ({ page }) => {
|
||||
const parentDirectory = await mkdtemp(path.join(homedir(), "paseo-e2e-stale-location-"));
|
||||
try {
|
||||
await mkdir(path.join(parentDirectory, "stale-probe-a"));
|
||||
await gotoAppShell(page);
|
||||
await openAddProjectFlow(page);
|
||||
await chooseAddProjectTab(page, "new-folder");
|
||||
const location = page.getByTestId("add-project-flow-location");
|
||||
const locationBefore = await location.textContent();
|
||||
await location.click();
|
||||
const search = page.getByPlaceholder("Search folders or enter a path").last();
|
||||
const prefix = path.basename(parentDirectory);
|
||||
await search.fill(`${prefix}/stale-probe`);
|
||||
await expect(page.getByText(/stale-probe-a/).last()).toBeVisible({ timeout: 30_000 });
|
||||
|
||||
await search.fill(`${prefix}/no-such-folder`);
|
||||
await page.keyboard.press("Enter");
|
||||
await expect(page.getByText("No matching folders")).toBeVisible({ timeout: 30_000 });
|
||||
await expect(search).toBeVisible();
|
||||
await expect(location).toHaveText(locationBefore ?? "");
|
||||
} finally {
|
||||
await rm(parentDirectory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("New folder validates the name, then creates a Project in the chosen location", async ({
|
||||
page,
|
||||
}) => {
|
||||
const parentDirectory = await mkdtemp(path.join(tmpdir(), "paseo-e2e-new-project-"));
|
||||
@@ -402,27 +428,23 @@ test.describe("Add Project command-center flow", () => {
|
||||
try {
|
||||
await gotoAppShell(page);
|
||||
await openAddProjectFlow(page);
|
||||
await chooseAddProjectMethod(page, "new-directory");
|
||||
await chooseAddProjectTab(page, "new-folder");
|
||||
await chooseAddProjectLocation(page, parentDirectory);
|
||||
|
||||
await page.keyboard.type(parentDirectory);
|
||||
await page.keyboard.press("Enter");
|
||||
await expectAddProjectPage(page, "new-directory-name");
|
||||
await page.keyboard.type("../invalid");
|
||||
await page.keyboard.press("Enter");
|
||||
await addProjectFlowInput(page).fill("../invalid");
|
||||
const nameError = page.getByTestId("add-project-flow-name-field-error");
|
||||
await expect(nameError).toHaveText("Use a name without slashes");
|
||||
await expect(addProjectFlowSubmit(page)).toBeDisabled();
|
||||
|
||||
const error = page.getByTestId("add-project-flow-error");
|
||||
await expect(error).toBeVisible();
|
||||
await expect(error).toContainText(/name|separator|directory/i);
|
||||
await expectAddProjectPage(page, "new-directory-name");
|
||||
await addProjectFlowInput(page).fill("C:repo");
|
||||
await expect(nameError).toHaveText("Use a name without a drive letter");
|
||||
await expect(addProjectFlowSubmit(page)).toBeDisabled();
|
||||
|
||||
await addProjectFlowInput(page).fill(directoryName);
|
||||
await addProjectFlowBack(page).click();
|
||||
await expectAddProjectPage(page, "new-directory-parent");
|
||||
await expect(addProjectFlowInput(page)).toHaveValue(parentDirectory);
|
||||
await page.keyboard.press("Enter");
|
||||
await expectAddProjectPage(page, "new-directory-name");
|
||||
await expect(addProjectFlowInput(page)).toHaveValue(directoryName);
|
||||
await page.keyboard.press("Enter");
|
||||
await expect(nameError).toBeHidden();
|
||||
await expect(addProjectFlowSubmit(page)).toBeEnabled();
|
||||
await expect(page.getByTestId("add-project-flow-location")).toContainText(directoryName);
|
||||
await addProjectFlowSubmit(page).click();
|
||||
|
||||
projectId = await expectOpenedProject(page, directoryName);
|
||||
await expectNewWorkspaceForAddedProject(page, {
|
||||
@@ -461,10 +483,11 @@ test.describe("Compact Add project context", () => {
|
||||
await gotoAppShell(page);
|
||||
await page.getByRole("button", { name: "Open menu", exact: true }).click();
|
||||
await openAddProjectFlow(page);
|
||||
await chooseAddProjectMethod(page, "directory-search");
|
||||
await addProjectFlowInput(page).fill(projectPickerFixture.fuzzyQuery);
|
||||
await expect(addProjectFlow(page)).toContainText(projectPickerFixture.projectName);
|
||||
await page.keyboard.press("Enter");
|
||||
await expect(
|
||||
page.getByRole("button", { name: new RegExp(projectPickerFixture.projectName) }).first(),
|
||||
).toBeVisible({ timeout: 30_000 });
|
||||
await addProjectFlowSubmit(page).click();
|
||||
const projectId = await expectOpenedProject(page, projectPickerFixture.projectName);
|
||||
projectPickerFixture.rememberProjectId(projectId);
|
||||
await expectNewWorkspaceForAddedProject(page, {
|
||||
|
||||
@@ -4,10 +4,9 @@ import path from "node:path";
|
||||
import { expect, test } from "../support/fixtures";
|
||||
import {
|
||||
addProjectFlow,
|
||||
addProjectFlowBack,
|
||||
addProjectFlowInput,
|
||||
chooseAddProjectMethod,
|
||||
expectAddProjectPage,
|
||||
chooseAddProjectLocation,
|
||||
chooseAddProjectTab,
|
||||
expectNewWorkspaceForAddedProject,
|
||||
openAddProjectFlow,
|
||||
} from "../support/helpers/add-project-flow";
|
||||
@@ -39,28 +38,22 @@ test.describe("Add Project GitHub flow", () => {
|
||||
|
||||
await gotoAppShell(page);
|
||||
await openAddProjectFlow(page);
|
||||
await chooseAddProjectMethod(page, "github");
|
||||
await chooseAddProjectTab(page, "clone");
|
||||
|
||||
await addProjectFlowInput(page).fill("getpaseo/paseo");
|
||||
await expect(addProjectFlow(page).getByText("getpaseo/paseo", { exact: true })).toBeVisible({
|
||||
timeout: 30_000,
|
||||
});
|
||||
await addProjectFlowInput(page).fill("");
|
||||
await addProjectFlowInput(page).fill(repository.fullName);
|
||||
|
||||
const repositoryRow = addProjectFlow(page).getByText(repository.fullName, { exact: true });
|
||||
await expect(repositoryRow).toBeVisible({ timeout: 30_000 });
|
||||
await repositoryRow.click();
|
||||
await expectAddProjectPage(page, "github-location");
|
||||
|
||||
await addProjectFlowInput(page).fill(parentDirectory);
|
||||
await expect(addProjectFlow(page)).toContainText(checkoutPath, { timeout: 30_000 });
|
||||
|
||||
await addProjectFlowBack(page).click();
|
||||
await expectAddProjectPage(page, "github-search");
|
||||
await expect(repositoryRow).toBeVisible();
|
||||
await repositoryRow.click();
|
||||
await expectAddProjectPage(page, "github-location");
|
||||
await expect(addProjectFlowInput(page)).toHaveValue(parentDirectory);
|
||||
await chooseAddProjectLocation(page, parentDirectory);
|
||||
await expect(page.getByTestId("add-project-flow-location")).toContainText(
|
||||
path.join(path.basename(parentDirectory), repository.name),
|
||||
);
|
||||
await addProjectFlowInput(page).focus();
|
||||
|
||||
await mkdir(checkoutPath);
|
||||
await page.keyboard.press("Enter");
|
||||
|
||||
@@ -13,13 +13,6 @@ import {
|
||||
import { expectNearBottom, scrollChatAwayFromBottom } from "../support/helpers/agent-bottom-anchor";
|
||||
import { holdRewindCompletion } from "../support/helpers/agent-timeline-gate";
|
||||
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
|
||||
import { userScrollsTimelineToHistoryStart } from "../support/helpers/timeline-pagination";
|
||||
import {
|
||||
closeWorkspaceAgentTab,
|
||||
fetchAgentArchivedAt,
|
||||
primeAdditionalPage,
|
||||
resetSeededPageState,
|
||||
} from "../support/helpers/archive-tab";
|
||||
|
||||
async function completeSubmittedTurn(
|
||||
page: Page,
|
||||
@@ -55,102 +48,26 @@ async function expectTurnCompletesNormally(
|
||||
await expectAgentIdle(page);
|
||||
}
|
||||
|
||||
async function openAgentOnAnotherClient(
|
||||
page: Page,
|
||||
agent: Awaited<ReturnType<typeof seedMockAgentWorkspace>>,
|
||||
): Promise<void> {
|
||||
await primeAdditionalPage(page);
|
||||
await resetSeededPageState(page);
|
||||
await openAgentRoute(page, agent);
|
||||
await expectComposerVisible(page);
|
||||
}
|
||||
|
||||
/** The prompts the chat shows, in order, each exactly once. */
|
||||
async function expectPrompts(page: Page, prompts: string[]): Promise<void> {
|
||||
const messages = page.getByTestId("user-message");
|
||||
await expect(messages).toHaveCount(prompts.length);
|
||||
await expect(messages).toContainText(prompts);
|
||||
}
|
||||
|
||||
async function reloadAgentFromTabMenu(page: Page, agentId: string): Promise<void> {
|
||||
const tabId = `workspace-tab-agent_${agentId}`;
|
||||
await page.getByTestId(tabId).filter({ visible: true }).first().click({ button: "right" });
|
||||
await page.getByTestId(`workspace-tab-context-agent_${agentId}-reload-agent`).click();
|
||||
}
|
||||
|
||||
async function archiveAgentByClosingTab(
|
||||
page: Page,
|
||||
agent: Awaited<ReturnType<typeof seedMockAgentWorkspace>>,
|
||||
): Promise<void> {
|
||||
await closeWorkspaceAgentTab(page, agent.agentId);
|
||||
await expect.poll(() => fetchAgentArchivedAt(agent.client, agent.agentId)).not.toBeNull();
|
||||
}
|
||||
|
||||
async function unarchiveAgent(page: Page): Promise<void> {
|
||||
await page.getByRole("button", { name: "Unarchive", exact: true }).click();
|
||||
await expect(page.getByText("This agent is archived", { exact: true })).toHaveCount(0, {
|
||||
timeout: 30_000,
|
||||
});
|
||||
}
|
||||
|
||||
async function expectToast(page: Page, message: string): Promise<void> {
|
||||
await expect(page.getByTestId("app-toast-message")).toHaveText(message, { timeout: 30_000 });
|
||||
}
|
||||
|
||||
// The mock provider's resumed session holds no history, so it never matches what Paseo shows.
|
||||
const UNSYNCED_RELOAD =
|
||||
"Reloaded agent, but the provider's history doesn't match this chat, so it wasn't synced";
|
||||
|
||||
/** The prompts of the whole conversation, after scrolling up through its older pages. */
|
||||
async function expectConversationPrompts(page: Page, prompts: string[]): Promise<void> {
|
||||
const messages = page.getByTestId("user-message");
|
||||
await expect
|
||||
.poll(async () => {
|
||||
await userScrollsTimelineToHistoryStart(page);
|
||||
return await messages.count();
|
||||
})
|
||||
.toBe(prompts.length);
|
||||
await expect(messages).toContainText(prompts);
|
||||
}
|
||||
|
||||
// A row React remounts loses this attribute; one that stays mounted keeps it.
|
||||
async function markMounted(row: Locator): Promise<void> {
|
||||
await row.evaluate((element) => element.setAttribute("data-e2e-mounted", "before-rewind"));
|
||||
}
|
||||
|
||||
async function expectStillMounted(row: Locator): Promise<void> {
|
||||
await expect(row).toHaveAttribute("data-e2e-mounted", "before-rewind");
|
||||
}
|
||||
|
||||
test.describe("Agent message rewind", () => {
|
||||
test("rewinds a prompt in place on every open client and keeps a human draft", async ({
|
||||
test("rewinds a submitted prompt without replaying history and preserves a human draft", async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(150_000);
|
||||
test.setTimeout(90_000);
|
||||
const retainedPrompt = "Keep this completed turn after rewind.";
|
||||
const rewoundPrompt = "Remove this completed turn after rewind.";
|
||||
const nextPrompt = "Continue after the rewind.";
|
||||
const preservedDraft = "Keep this human draft after rewind.";
|
||||
const agent = await seedMockAgentWorkspace({
|
||||
repoPrefix: "message-rewind-roundtrip-",
|
||||
title: "Message rewind roundtrip",
|
||||
model: "ten-second-stream",
|
||||
});
|
||||
const otherClient = await page.context().newPage();
|
||||
|
||||
try {
|
||||
const rewindCompletion = await holdRewindCompletion(page, agent.agentId);
|
||||
await openAgentRoute(page, agent);
|
||||
await expectComposerVisible(page);
|
||||
const retainedMessage = await completeSubmittedTurn(page, agent, retainedPrompt);
|
||||
await completeSubmittedTurn(page, agent, retainedPrompt);
|
||||
const userMessage = await completeSubmittedTurn(page, agent, rewoundPrompt);
|
||||
|
||||
await test.step("a second client opens the same chat", async () => {
|
||||
await openAgentOnAnotherClient(otherClient, agent);
|
||||
await expectPrompts(otherClient, [retainedPrompt, rewoundPrompt]);
|
||||
});
|
||||
|
||||
await markMounted(retainedMessage);
|
||||
await scrollChatAwayFromBottom(page, {
|
||||
deltaY: -900,
|
||||
minDistanceFromBottom: 300,
|
||||
@@ -159,92 +76,19 @@ test.describe("Agent message rewind", () => {
|
||||
await blurComposerInput(page);
|
||||
rewindCompletion.clearTimelineStreamCount();
|
||||
|
||||
await test.step("the rewind stays pending until the daemon answers", async () => {
|
||||
const rewind = rewindConversation(page, userMessage, rewoundPrompt);
|
||||
await rewindCompletion.waitForDelayedResponse();
|
||||
await expect(page.getByTestId("rewind-menu-conversation")).toBeDisabled();
|
||||
expect(rewindCompletion.timelineStreamCount()).toBe(0);
|
||||
rewindCompletion.release();
|
||||
await rewind;
|
||||
});
|
||||
const rewind = rewindConversation(page, userMessage, rewoundPrompt);
|
||||
await rewindCompletion.waitForDelayedResponse();
|
||||
await expect(page.getByTestId("rewind-menu-conversation")).toBeDisabled();
|
||||
expect(rewindCompletion.timelineStreamCount()).toBe(0);
|
||||
rewindCompletion.release();
|
||||
await rewind;
|
||||
|
||||
await test.step("the rewound turn leaves without reloading the chat", async () => {
|
||||
await expectPrompts(page, [retainedPrompt]);
|
||||
await expectStillMounted(retainedMessage);
|
||||
expect(rewindCompletion.timelineFetchCount()).toBe(0);
|
||||
await expectComposerDraft(page, preservedDraft);
|
||||
await expectComposerNotFocused(page);
|
||||
await expectNearBottom(page);
|
||||
await expectPrompts(otherClient, [retainedPrompt]);
|
||||
});
|
||||
|
||||
await test.step("the next prompt appears once on both clients", async () => {
|
||||
await completeSubmittedTurn(otherClient, agent, nextPrompt);
|
||||
await expectPrompts(otherClient, [retainedPrompt, nextPrompt]);
|
||||
await expectPrompts(page, [retainedPrompt, nextPrompt]);
|
||||
});
|
||||
|
||||
await test.step("a reconnecting client loads the rewound conversation", async () => {
|
||||
await otherClient.reload();
|
||||
await expectPrompts(otherClient, [retainedPrompt, nextPrompt]);
|
||||
});
|
||||
} finally {
|
||||
await otherClient.close();
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("keeps the rewound conversation through Reload agent, archive and unarchive", async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(150_000);
|
||||
const keptPrompt = "Keep this turn through reload and archive.";
|
||||
const rewoundPrompt = "Rewind this turn before reloading.";
|
||||
const nextPrompt = "Continue after the rewind, then reload.";
|
||||
const agent = await seedMockAgentWorkspace({
|
||||
repoPrefix: "message-rewind-reload-archive-",
|
||||
title: "Message rewind reload archive",
|
||||
model: "ten-second-stream",
|
||||
});
|
||||
|
||||
try {
|
||||
await openAgentRoute(page, agent);
|
||||
await expectComposerVisible(page);
|
||||
await completeSubmittedTurn(page, agent, keptPrompt);
|
||||
const rewound = await completeSubmittedTurn(page, agent, rewoundPrompt);
|
||||
await rewindConversation(page, rewound, rewoundPrompt);
|
||||
await expectPrompts(page, [keptPrompt]);
|
||||
await completeSubmittedTurn(page, agent, nextPrompt);
|
||||
await expectPrompts(page, [keptPrompt, nextPrompt]);
|
||||
|
||||
await test.step("Reload agent keeps the chat and says the provider's history was not synced", async () => {
|
||||
await reloadAgentFromTabMenu(page, agent.agentId);
|
||||
await expectToast(page, UNSYNCED_RELOAD);
|
||||
await expectPrompts(page, [keptPrompt, nextPrompt]);
|
||||
await expectComposerVisible(page);
|
||||
});
|
||||
|
||||
await test.step("the archived chat shows the rewound conversation", async () => {
|
||||
await archiveAgentByClosingTab(page, agent);
|
||||
await openAgentRoute(page, agent);
|
||||
await expect(page.getByText("This agent is archived", { exact: true })).toBeVisible({
|
||||
timeout: 30_000,
|
||||
});
|
||||
await expectConversationPrompts(page, [keptPrompt, nextPrompt]);
|
||||
});
|
||||
|
||||
await test.step("unarchiving keeps the rewound conversation", async () => {
|
||||
await unarchiveAgent(page);
|
||||
await expectToast(page, UNSYNCED_RELOAD);
|
||||
await expectComposerVisible(page);
|
||||
await expectConversationPrompts(page, [keptPrompt, nextPrompt]);
|
||||
});
|
||||
|
||||
await test.step("a reconnecting client loads the same conversation", async () => {
|
||||
await page.reload();
|
||||
await expectComposerVisible(page);
|
||||
await expectConversationPrompts(page, [keptPrompt, nextPrompt]);
|
||||
});
|
||||
await expect(page.getByTestId("user-message").filter({ hasText: rewoundPrompt })).toHaveCount(
|
||||
0,
|
||||
);
|
||||
await expectComposerDraft(page, preservedDraft);
|
||||
await expectComposerNotFocused(page);
|
||||
await expectNearBottom(page);
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
|
||||
@@ -11,13 +11,20 @@ import {
|
||||
expectModelRowProfileActionBesideRow,
|
||||
expectModelRowSelected,
|
||||
expectProfileEditIsPencilOnly,
|
||||
expectProfileReachableByScrolling,
|
||||
expectProfileSearchResult,
|
||||
expectProfileVisibleForProvider,
|
||||
openModelPicker,
|
||||
openAgentProfilesFromEmptyPrompt,
|
||||
searchModelPicker,
|
||||
seedAgentProfiles,
|
||||
selectModelRow,
|
||||
} from "../support/helpers/agent-profiles";
|
||||
import { expectWorkspaceAgentConfiguration } from "../support/helpers/command-center-agent-controls";
|
||||
import {
|
||||
chooseCommandCenterAgentControl,
|
||||
expectWorkspaceAgentConfiguration,
|
||||
openCommandCenterForAgent,
|
||||
} from "../support/helpers/command-center-agent-controls";
|
||||
import { expectComposerVisible } from "../support/helpers/composer";
|
||||
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
|
||||
|
||||
@@ -148,4 +155,83 @@ test.describe("Agent profiles in the model picker", () => {
|
||||
await seed.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test("a profile is found by searching the model picker or the command center", async ({
|
||||
page,
|
||||
}) => {
|
||||
const seed = await seedAgentProfiles([PROFILE]);
|
||||
const workspace = await seedMockAgentWorkspace({
|
||||
repoPrefix: "agent-profiles-search-",
|
||||
title: "Agent profiles search",
|
||||
model: "ten-second-stream",
|
||||
modeId: "load-test",
|
||||
});
|
||||
|
||||
try {
|
||||
await test.step("searching its name in the model picker lists only the profile", async () => {
|
||||
await openAgentRoute(page, workspace);
|
||||
await expectComposerVisible(page);
|
||||
await openModelPicker(page);
|
||||
await searchModelPicker(page, "ui work");
|
||||
await expectProfileSearchResult(page, { name: PROFILE.name });
|
||||
});
|
||||
|
||||
await test.step("searching its model lists the profile above the model", async () => {
|
||||
await searchModelPicker(page, "one minute");
|
||||
await expectProfileSearchResult(page, {
|
||||
name: PROFILE.name,
|
||||
model: { provider: "mock", modelId: "one-minute-stream" },
|
||||
});
|
||||
await closeModelPicker(page);
|
||||
});
|
||||
|
||||
await test.step("choosing it from the command center applies it", async () => {
|
||||
await openCommandCenterForAgent(page, workspace);
|
||||
await chooseCommandCenterAgentControl({
|
||||
page,
|
||||
query: "ui work",
|
||||
choice: `Profile › ${PROFILE.name}`,
|
||||
});
|
||||
await expectComposerModel(page, "One minute stream");
|
||||
await expectComposerMode(page, "Approval test");
|
||||
await expectWorkspaceAgentConfiguration(workspace, {
|
||||
id: workspace.agentId,
|
||||
provider: "mock",
|
||||
model: "one-minute-stream",
|
||||
modeId: "approval-test",
|
||||
});
|
||||
});
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
await seed.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test("profile-only search results scroll inside the picker", async ({ page }) => {
|
||||
const profiles = Array.from({ length: 12 }, (_, index) => ({
|
||||
id: `agent_profile_e2e_release_${index + 1}`,
|
||||
name: `Release review ${String(index + 1).padStart(2, "0")}`,
|
||||
provider: "mock",
|
||||
model: "one-minute-stream",
|
||||
}));
|
||||
const seed = await seedAgentProfiles(profiles);
|
||||
const workspace = await seedMockAgentWorkspace({
|
||||
repoPrefix: "agent-profiles-search-scroll-",
|
||||
title: "Agent profiles search scroll",
|
||||
model: "ten-second-stream",
|
||||
modeId: "load-test",
|
||||
});
|
||||
|
||||
try {
|
||||
await openAgentRoute(page, workspace);
|
||||
await expectComposerVisible(page);
|
||||
await openModelPicker(page);
|
||||
await searchModelPicker(page, "release review");
|
||||
await expectProfileSearchResult(page, { name: "Release review 01" });
|
||||
await expectProfileReachableByScrolling(page, "Release review 12");
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
await seed.restore();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -757,6 +757,161 @@ test("pasting an assistant selection preserves literal underscores and authored
|
||||
}
|
||||
});
|
||||
|
||||
const QUOTE_BODY = [
|
||||
"Draft for the team: **ship it** with [the notes](https://example.com/notes).",
|
||||
"",
|
||||
"> Nested reply.",
|
||||
"",
|
||||
"```ts",
|
||||
"const quoted = 1;",
|
||||
"```",
|
||||
"",
|
||||
"```mermaid",
|
||||
"flowchart LR",
|
||||
" Start --> Done",
|
||||
"```",
|
||||
"",
|
||||
"Thanks!",
|
||||
].join("\n");
|
||||
|
||||
const QUOTE_MARKDOWN = [
|
||||
"Text before the quote.",
|
||||
"",
|
||||
...QUOTE_BODY.split("\n").map((line) => (line ? `> ${line}` : ">")),
|
||||
"",
|
||||
"> [!NOTE]",
|
||||
"> Heads up before you paste.",
|
||||
"",
|
||||
"Text after the quote.",
|
||||
].join("\n");
|
||||
|
||||
function assistantQuote(page: Page, index: number): Locator {
|
||||
return assistantMessageBlocks(page).getByRole("blockquote").nth(index);
|
||||
}
|
||||
|
||||
/** A quote's own control is its first, ahead of any nested quote's. */
|
||||
function quoteCopyControl(quote: Locator): Locator {
|
||||
return quote.getByRole("button", { name: "Copy quote" }).first();
|
||||
}
|
||||
|
||||
async function copyQuote(quote: Locator): Promise<void> {
|
||||
await quote.hover();
|
||||
await quoteCopyControl(quote).click();
|
||||
await expect(quote.getByRole("button", { name: "Copied" })).toBeVisible();
|
||||
}
|
||||
|
||||
async function pasteIntoPlainAndRichFields(page: Page): Promise<{ plain: Locator; rich: Locator }> {
|
||||
await page.evaluate(() => {
|
||||
const fields = document.createElement("div");
|
||||
fields.style.cssText = "position: fixed; bottom: 0; left: 0; z-index: 10000; background: white";
|
||||
const plainText = document.createElement("textarea");
|
||||
plainText.setAttribute("aria-label", "Plain text paste");
|
||||
const richText = document.createElement("div");
|
||||
richText.contentEditable = "true";
|
||||
richText.setAttribute("role", "textbox");
|
||||
richText.setAttribute("aria-label", "Rich text paste");
|
||||
fields.append(plainText, richText);
|
||||
document.body.append(fields);
|
||||
});
|
||||
const plain = page.getByRole("textbox", { name: "Plain text paste" });
|
||||
await plain.focus();
|
||||
await page.keyboard.press("ControlOrMeta+v");
|
||||
const rich = page.getByRole("textbox", { name: "Rich text paste" });
|
||||
await rich.focus();
|
||||
await page.keyboard.press("ControlOrMeta+v");
|
||||
return { plain, rich };
|
||||
}
|
||||
|
||||
test("a quote's copy control copies only that quote's body", async ({ context, page }) => {
|
||||
const agent = await seedMockAgentWorkspace({
|
||||
repoPrefix: "assistant-quote-copy-",
|
||||
title: "Assistant quote copy",
|
||||
initialPrompt: "Render the quote fixture.",
|
||||
featureValues: { mockAssistantResponse: QUOTE_MARKDOWN },
|
||||
});
|
||||
|
||||
try {
|
||||
await allowRichClipboard(context);
|
||||
await agent.client.waitForAgentUpsert(
|
||||
agent.agentId,
|
||||
(snapshot) => snapshot.status === "idle",
|
||||
30_000,
|
||||
);
|
||||
await openAgentRoute(page, agent);
|
||||
const quote = assistantQuote(page, 0);
|
||||
const nested = assistantQuote(page, 1);
|
||||
await expect(quote).toContainText("Thanks!");
|
||||
|
||||
await test.step("an admonition has no copy control", async () => {
|
||||
await expect(assistantMessageBlocks(page)).toContainText("Heads up before you paste.");
|
||||
await expect(
|
||||
assistantMessageBlocks(page).getByRole("button", { name: "Copy quote" }),
|
||||
).toHaveCount(2);
|
||||
});
|
||||
|
||||
await test.step("the control appears on hover or keyboard focus", async () => {
|
||||
const control = quoteCopyControl(quote);
|
||||
await expect(control).toHaveCSS("opacity", "0");
|
||||
await quote.hover();
|
||||
await expect(control).toHaveCSS("opacity", "1");
|
||||
await page.mouse.move(0, 0);
|
||||
await expect(control).toHaveCSS("opacity", "0");
|
||||
await control.focus();
|
||||
await expect(control).toHaveCSS("opacity", "1");
|
||||
await control.blur();
|
||||
});
|
||||
|
||||
await test.step("copying the quote takes its body, with a diagram as its fence", async () => {
|
||||
await expect(quote.getByRole("img", { name: "Diagram" })).toBeVisible({ timeout: 30_000 });
|
||||
await copyQuote(quote);
|
||||
const copied = await readRichClipboard(page);
|
||||
expect(copied.plainText).toBe(QUOTE_BODY);
|
||||
expect(copied.html).toContain("<strong>ship it</strong>");
|
||||
expect(copied.html).toContain("<blockquote>");
|
||||
});
|
||||
|
||||
await test.step("the copy pastes as Markdown and as rich text", async () => {
|
||||
const { plain, rich } = await pasteIntoPlainAndRichFields(page);
|
||||
await expect(plain).toHaveValue(QUOTE_BODY);
|
||||
await expect(rich.locator("strong")).toHaveText("ship it");
|
||||
await expect(rich.getByRole("link", { name: "the notes" })).toHaveAttribute(
|
||||
"href",
|
||||
"https://example.com/notes",
|
||||
);
|
||||
await expect(rich).not.toContainText("Text before the quote.");
|
||||
});
|
||||
|
||||
await test.step("a nested quote copies only itself", async () => {
|
||||
await copyQuote(nested);
|
||||
await expect
|
||||
.poll(async () => (await readRichClipboard(page)).plainText)
|
||||
.toBe("Nested reply.");
|
||||
});
|
||||
|
||||
await test.step("a code block in the quote keeps its own copy", async () => {
|
||||
const code = quote.getByText("const quoted = 1;", { exact: true });
|
||||
await code.hover();
|
||||
await quote.getByRole("button", { name: "Copy code" }).first().click();
|
||||
await expect.poll(() => readPlainClipboard(page)).toBe("const quoted = 1;");
|
||||
});
|
||||
|
||||
await test.step("a phone-sized layout shows the control above the full-width text", async () => {
|
||||
await page.mouse.move(0, 0);
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
const control = quoteCopyControl(quote);
|
||||
await expect(control).toHaveCSS("opacity", "1");
|
||||
const controlBox = await control.boundingBox();
|
||||
const firstLine = await quote.getByText(/^Draft for the team/).boundingBox();
|
||||
expect(controlBox && firstLine).toBeTruthy();
|
||||
// The text starts below the control instead of wrapping short of it.
|
||||
expect(firstLine!.y).toBeGreaterThanOrEqual(controlBox!.y + controlBox!.height);
|
||||
expect(firstLine!.x + firstLine!.width).toBeGreaterThan(controlBox!.x);
|
||||
});
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("copying a selection across an assistant image keeps its Markdown source and alt text", async ({
|
||||
context,
|
||||
page,
|
||||
|
||||
@@ -4,7 +4,7 @@ import { test, expect, type Page } from "../support/fixtures";
|
||||
import { gotoAppShell } from "../support/helpers/app";
|
||||
import {
|
||||
addProjectFlowInput,
|
||||
chooseAddProjectMethod,
|
||||
addProjectFlowSubmit,
|
||||
openAddProjectFlow,
|
||||
} from "../support/helpers/add-project-flow";
|
||||
import { expectOpenedProject } from "../support/helpers/project-picker-ui";
|
||||
@@ -53,7 +53,6 @@ async function removeProjectFromSidebar(page: Page, projectViewKey: string): Pro
|
||||
|
||||
async function addProjectFromPicker(page: Page, projectPath: string): Promise<string> {
|
||||
await openAddProjectFlow(page);
|
||||
await chooseAddProjectMethod(page, "directory-search");
|
||||
|
||||
const input = addProjectFlowInput(page);
|
||||
await input.fill(projectPath);
|
||||
@@ -85,7 +84,6 @@ test.describe("Project picker search", () => {
|
||||
await gotoAppShell(page);
|
||||
await waitForSidebarProjectListReady(page);
|
||||
await openAddProjectFlow(page);
|
||||
await chooseAddProjectMethod(page, "directory-search");
|
||||
|
||||
const input = addProjectFlowInput(page);
|
||||
await input.fill(projectPickerFixture.fuzzyQuery);
|
||||
@@ -93,6 +91,7 @@ test.describe("Project picker search", () => {
|
||||
const suggestion = page.getByText(projectPickerFixture.projectName, { exact: false }).first();
|
||||
await expect(suggestion).toBeVisible({ timeout: 30_000 });
|
||||
await suggestion.click();
|
||||
await addProjectFlowSubmit(page).click();
|
||||
|
||||
const projectId = await expectOpenedProject(page, projectPickerFixture.projectName);
|
||||
projectPickerFixture.rememberProjectId(projectId);
|
||||
@@ -104,13 +103,11 @@ test.describe("Project picker search", () => {
|
||||
await gotoAppShell(page);
|
||||
await waitForSidebarProjectListReady(page);
|
||||
await openAddProjectFlow(page);
|
||||
await chooseAddProjectMethod(page, "directory-search");
|
||||
|
||||
const input = addProjectFlowInput(page);
|
||||
await input.fill("paseo-loading-state-no-match");
|
||||
|
||||
await expect(page.getByText("Start typing a path", { exact: true })).toHaveCount(0);
|
||||
await expect(page.getByText("Loading...", { exact: true })).toBeVisible();
|
||||
await expect(page.getByText("Searching...", { exact: true })).toBeVisible();
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
addConnectedHostAndReload,
|
||||
chooseHostBadgeDisplay,
|
||||
chooseHostColor,
|
||||
chooseHostIcon,
|
||||
expectHostAppearancePreview,
|
||||
expectHostBadgeIconOnly,
|
||||
expectHostBadgeName,
|
||||
@@ -115,12 +116,21 @@ test("customizes a host badge and preserves its appearance after reload", async
|
||||
expect(widths.content).toBeLessThanOrEqual(widths.client);
|
||||
});
|
||||
|
||||
await test.step("preview a color and apply it to the sidebar badge", async () => {
|
||||
await test.step("preview a color and icon and apply them to the sidebar badge and host popover", async () => {
|
||||
await openHostAppearanceSettings(page, badge.serverId);
|
||||
await chooseHostColor(page, "Teal");
|
||||
await chooseHostIcon(page, "Laptop");
|
||||
await expectHostAppearancePreview(page, { serverId: badge.serverId, hostName, color: "teal" });
|
||||
await leaveHostAppearanceSettings(page);
|
||||
await expectHostBadgeTinted(page, { ...badge, hostName, color: "teal" });
|
||||
|
||||
await page.getByTestId("sidebar-hosts-trigger").click();
|
||||
const hostRow = page.getByTestId(`sidebar-host-row-${badge.serverId}`);
|
||||
await expect(hostRow).toBeVisible();
|
||||
await expect(hostRow).toContainText("Direct");
|
||||
await expect(hostRow).toContainText(/\d+(?:\.\d+)?(?:µs|ms|s)/);
|
||||
await expect(hostRow).not.toContainText(/agents?/i);
|
||||
await page.keyboard.press("Escape");
|
||||
});
|
||||
|
||||
await test.step("keep the icon-only preference through reload", async () => {
|
||||
@@ -145,3 +155,30 @@ test("customizes a host badge and preserves its appearance after reload", async
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
base(
|
||||
"activates Add host from the sidebar host picker via focus+Enter and Arrow+Enter",
|
||||
async ({ page }) => {
|
||||
await gotoAppShell(page);
|
||||
const trigger = page.getByTestId("sidebar-hosts-trigger");
|
||||
await expect(trigger).toBeVisible();
|
||||
|
||||
// Focus + Enter on Add host must open the Add connection dialog rather than selecting the active host.
|
||||
const addConnectionDialog = page.getByRole("dialog").filter({ hasText: "Add connection" });
|
||||
await trigger.click();
|
||||
const addHostButton = page.getByRole("button", { name: "Add host", exact: true });
|
||||
await expect(addHostButton).toBeVisible();
|
||||
await addHostButton.focus();
|
||||
await page.keyboard.press("Enter");
|
||||
await expect(addConnectionDialog).toBeVisible();
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(addConnectionDialog).toBeHidden();
|
||||
|
||||
// ArrowDown + Enter must also reach Add host from the host list.
|
||||
await trigger.click();
|
||||
await expect(addHostButton).toBeVisible();
|
||||
await page.keyboard.press("ArrowDown");
|
||||
await page.keyboard.press("Enter");
|
||||
await expect(addConnectionDialog).toBeVisible();
|
||||
},
|
||||
);
|
||||
|
||||
@@ -55,7 +55,7 @@ import {
|
||||
import { getServerId } from "../support/helpers/server-id";
|
||||
import { selectSidebarStatusGrouping } from "../support/helpers/sidebar";
|
||||
import { getE2EDaemonPort } from "../support/helpers/daemon-port";
|
||||
import { chooseAddProjectMethod, expectAddProjectPage } from "../support/helpers/add-project-flow";
|
||||
import { expectAddProjectTab } from "../support/helpers/add-project-flow";
|
||||
import { seedSavedSettingsHosts } from "../support/helpers/settings";
|
||||
import {
|
||||
expectSidebarWorkspaceSelected,
|
||||
@@ -291,8 +291,7 @@ test.describe("New workspace flow", () => {
|
||||
await expect(addProject).toContainText(/(?:⌘|Ctrl\+)O/);
|
||||
await addProject.click();
|
||||
|
||||
await expectAddProjectPage(page, "method");
|
||||
await chooseAddProjectMethod(page, "directory-search");
|
||||
await expectAddProjectTab(page, "existing");
|
||||
} finally {
|
||||
await repo.cleanup();
|
||||
}
|
||||
|
||||
@@ -46,11 +46,7 @@ import {
|
||||
} from "../support/helpers/project-settings";
|
||||
import { gotoAppShell } from "../support/helpers/app";
|
||||
import { openCompactSettings } from "../support/helpers/settings";
|
||||
import {
|
||||
addProjectFlowInput,
|
||||
chooseAddProjectMethod,
|
||||
openAddProjectFlow,
|
||||
} from "../support/helpers/add-project-flow";
|
||||
import { addProjectFlowInput, openAddProjectFlow } from "../support/helpers/add-project-flow";
|
||||
import { createTempGitRepo } from "../support/helpers/workspace";
|
||||
import {
|
||||
buildOpenProjectRoute,
|
||||
@@ -167,7 +163,6 @@ async function readProjectConfigFile(project: ProjectsSettingsProject): Promise<
|
||||
|
||||
async function addProjectFromSidebar(page: Page, projectPath: string): Promise<string> {
|
||||
await openAddProjectFlow(page);
|
||||
await chooseAddProjectMethod(page, "directory-search");
|
||||
|
||||
const input = addProjectFlowInput(page);
|
||||
await input.fill(projectPath);
|
||||
|
||||
@@ -235,7 +235,7 @@ test.describe("Rewind sheet", () => {
|
||||
await expect(page.getByTestId("rewind-menu-content")).toHaveCount(0);
|
||||
await expect(userMessage(page, secondPrompt)).toHaveCount(0);
|
||||
await expect(page.getByText("Cycle 1", { exact: true })).toHaveCount(0);
|
||||
await expectUserMessageCount(page, 0);
|
||||
await expectUserMessageCount(page, 1);
|
||||
await expectComposerDraft(page, firstPrompt);
|
||||
await expectComposerFocused(page);
|
||||
|
||||
@@ -243,7 +243,7 @@ test.describe("Rewind sheet", () => {
|
||||
await expectUserMessageVisible(page, replacementPrompt);
|
||||
await expect(userMessage(page, secondPrompt)).toHaveCount(0);
|
||||
await expect(page.getByText("Cycle 1", { exact: true })).toHaveCount(0);
|
||||
await expectUserMessageCount(page, 1);
|
||||
await expectUserMessageCount(page, 2);
|
||||
|
||||
await fillComposerDraft(page, "");
|
||||
await composerLocator(page).evaluate((element) => element.blur());
|
||||
@@ -254,19 +254,7 @@ test.describe("Rewind sheet", () => {
|
||||
await expect(page.getByTestId("rewind-menu-content")).toHaveCount(0);
|
||||
await expectComposerDraft(page, "");
|
||||
await expectComposerNotFocused(page);
|
||||
await expectUserMessageCount(page, 1);
|
||||
|
||||
const preservedDraft = "Keep this human draft after rewind.";
|
||||
await fillComposerDraft(page, preservedDraft);
|
||||
await composerLocator(page).evaluate((element) => element.blur());
|
||||
await userMessage(page, replacementPrompt).hover();
|
||||
await page.getByTestId("rewind-menu-trigger").last().click();
|
||||
await expect(page.getByTestId("rewind-menu-content")).toBeVisible();
|
||||
await selectRewindOption(page, "Rewind files");
|
||||
await expect(page.getByTestId("rewind-menu-content")).toHaveCount(0);
|
||||
await expectComposerDraft(page, preservedDraft);
|
||||
await expectComposerNotFocused(page);
|
||||
await expectUserMessageCount(page, 1);
|
||||
await expectUserMessageCount(page, 2);
|
||||
|
||||
await fillComposerDraft(page, "");
|
||||
await composerLocator(page).evaluate((element) => element.blur());
|
||||
@@ -277,7 +265,7 @@ test.describe("Rewind sheet", () => {
|
||||
await expect(page.getByTestId("rewind-menu-content")).toHaveCount(0);
|
||||
await expectComposerDraft(page, replacementPrompt);
|
||||
await expectComposerFocused(page);
|
||||
await expectUserMessageCount(page, 0);
|
||||
await expectUserMessageCount(page, 1);
|
||||
} finally {
|
||||
await session.cleanup();
|
||||
}
|
||||
|
||||
@@ -65,8 +65,7 @@ import {
|
||||
openSettingsHostSection,
|
||||
removeCurrentHostFromSettings,
|
||||
openSidebarHostPicker,
|
||||
sidebarHostSettingsButton,
|
||||
expectStandaloneSidebarHostSettingsButton,
|
||||
sidebarHostRowButton,
|
||||
activateSidebarHostSettingsWithKeyboard,
|
||||
bindCommandCenterToEnter,
|
||||
} from "../support/helpers/settings";
|
||||
@@ -192,17 +191,16 @@ test.describe("Settings sidebar scroll position", () => {
|
||||
});
|
||||
|
||||
test.describe("Settings sidebar navigation", () => {
|
||||
test("the sidebar host gear opens Overview in one click", async ({ page, withWorkspace }) => {
|
||||
test("the sidebar host row opens Overview in one click", async ({ page, withWorkspace }) => {
|
||||
const workspace = await withWorkspace({ prefix: "sidebar-host-settings-" });
|
||||
await openWorkspace(page, workspace);
|
||||
await openSidebarHostPicker(page);
|
||||
await expectStandaloneSidebarHostSettingsButton(page);
|
||||
await sidebarHostSettingsButton(page).click();
|
||||
await sidebarHostRowButton(page).click();
|
||||
|
||||
await expectAppRoute(page, buildSettingsHostSectionRoute(getServerId(), "host"));
|
||||
});
|
||||
|
||||
test("Enter opens the focused sidebar host gear", async ({ page, withWorkspace }) => {
|
||||
test("Enter opens the active sidebar host row", async ({ page, withWorkspace }) => {
|
||||
await bindCommandCenterToEnter(page);
|
||||
const workspace = await withWorkspace({ prefix: "keyboard-host-settings-" });
|
||||
await openWorkspace(page, workspace);
|
||||
@@ -566,7 +564,7 @@ test.describe("Settings — compact master-detail", () => {
|
||||
await openWorkspace(page, workspace);
|
||||
await page.getByRole("button", { name: "Open menu", exact: true }).click();
|
||||
await page.getByTestId("sidebar-hosts-trigger").click();
|
||||
await page.getByRole("button", { name: /Open .* settings/ }).click();
|
||||
await sidebarHostRowButton(page).click();
|
||||
|
||||
await expectAppRoute(page, buildSettingsHostSectionRoute(getServerId(), "host"));
|
||||
await expect(page.getByText("Overview", { exact: true })).toBeVisible();
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
import path from "node:path";
|
||||
import {
|
||||
expectTimelinePromptVisible,
|
||||
holdOlderHistoryPages,
|
||||
scrollTimelineRowIntoView,
|
||||
userScrollsTimelineToHistoryStart,
|
||||
waitForTimelineGeometryToSettle,
|
||||
} from "../support/helpers/timeline-pagination";
|
||||
import { getActiveTabTestId } from "../support/helpers/launcher";
|
||||
import type { Page, Locator } from "@playwright/test";
|
||||
@@ -491,6 +493,39 @@ async function seedWholeTurnHistory() {
|
||||
return agent;
|
||||
}
|
||||
|
||||
/** Read every command across the scroll window, without requiring offscreen rows to mount. */
|
||||
async function expectExpandedCommandsReadable(page: Page, count: number) {
|
||||
const timeline = page.getByTestId("agent-chat-scroll");
|
||||
const commands = new Set<number>();
|
||||
await timeline.hover();
|
||||
await waitForTimelineGeometryToSettle(page);
|
||||
for (let step = 0; step < count && commands.size < count; step += 1) {
|
||||
const labels = await timeline
|
||||
.getByRole("button", { name: /echo stress-\d+/ })
|
||||
.allTextContents();
|
||||
for (const label of labels) {
|
||||
const command = /echo stress-(\d+)/.exec(label);
|
||||
if (command) commands.add(Number(command[1]));
|
||||
}
|
||||
if (commands.size < count) {
|
||||
await page.mouse.wheel(0, 300);
|
||||
await waitForTimelineGeometryToSettle(page);
|
||||
}
|
||||
}
|
||||
expect([...commands].sort((a, b) => a - b)).toEqual(
|
||||
Array.from({ length: count }, (_, index) => index),
|
||||
);
|
||||
}
|
||||
|
||||
async function returnToExpandedSummary(page: Page, summary: Locator) {
|
||||
await page.getByTestId("agent-chat-scroll").hover();
|
||||
for (let step = 0; step < 120 && !(await summary.isVisible()); step += 1) {
|
||||
await page.mouse.wheel(0, -300);
|
||||
await waitForTimelineGeometryToSettle(page);
|
||||
}
|
||||
await scrollTimelineRowIntoView(page, summary);
|
||||
}
|
||||
|
||||
async function expectInitialFillIsConcealed(page: Page) {
|
||||
await expect(page.getByTestId("agent-initial-fill")).toBeVisible();
|
||||
await expect(page.getByTestId("agent-chat-scroll")).toHaveCSS("opacity", "0");
|
||||
@@ -564,14 +599,14 @@ test("loads complete long turns and preserves expansion while revealing older hi
|
||||
).toBeVisible();
|
||||
await expect.poll(() => rowsBetweenLatestSummaryAndReply(page)).toBe(0);
|
||||
await latest.click();
|
||||
await expect.poll(() => rowsBetweenLatestSummaryAndReply(page)).toBe(120);
|
||||
await expectExpandedCommandsReadable(page, 120);
|
||||
await userScrollsTimelineToHistoryStart(page);
|
||||
await history.expectRequestedPages(3);
|
||||
history.releasePage(3);
|
||||
await page.getByTestId("scroll-to-bottom-button").click();
|
||||
await expect.poll(() => rowsBetweenLatestSummaryAndReply(page)).toBe(120);
|
||||
await expectTimelinePromptVisible(page, "Short 4: emit 1 coalesced agent stream updates");
|
||||
await expectExpandedCommandsReadable(page, 120);
|
||||
history.expectNoRepeatedEntries();
|
||||
await scrollTimelineRowIntoView(page, latest);
|
||||
await returnToExpandedSummary(page, latest);
|
||||
await latest.click();
|
||||
await expect.poll(() => rowsBetweenLatestSummaryAndReply(page)).toBe(0);
|
||||
} finally {
|
||||
|
||||
@@ -1,73 +1,61 @@
|
||||
import path from "node:path";
|
||||
import { expect, type Locator, type Page } from "@playwright/test";
|
||||
|
||||
export type AddProjectFlowPage =
|
||||
| "host"
|
||||
| "method"
|
||||
| "directory-search"
|
||||
| "github-search"
|
||||
| "github-location"
|
||||
| "new-directory-parent"
|
||||
| "new-directory-name";
|
||||
|
||||
export type AddProjectMethod = "directory-search" | "browse" | "github" | "new-directory";
|
||||
|
||||
const METHOD_DESTINATIONS: Record<Exclude<AddProjectMethod, "browse">, AddProjectFlowPage> = {
|
||||
"directory-search": "directory-search",
|
||||
github: "github-search",
|
||||
"new-directory": "new-directory-parent",
|
||||
};
|
||||
export type AddProjectTab = "existing" | "clone" | "new-folder";
|
||||
|
||||
export function addProjectFlow(page: Page): Locator {
|
||||
return page.getByTestId("add-project-flow");
|
||||
}
|
||||
|
||||
/** The current tab's search or name field. */
|
||||
export function addProjectFlowInput(page: Page): Locator {
|
||||
return page.getByTestId("add-project-flow-input");
|
||||
}
|
||||
|
||||
export function addProjectFlowBack(page: Page): Locator {
|
||||
return page.getByTestId("add-project-flow-back");
|
||||
export function addProjectFlowTab(page: Page, tab: AddProjectTab): Locator {
|
||||
return page.getByTestId(`add-project-flow-tab-${tab}`);
|
||||
}
|
||||
|
||||
export function addProjectFlowHost(page: Page, serverId: string): Locator {
|
||||
return page.getByTestId(`add-project-flow-host-${serverId}`);
|
||||
export function addProjectFlowSubmit(page: Page): Locator {
|
||||
return page.getByTestId("add-project-flow-submit");
|
||||
}
|
||||
|
||||
export function addProjectFlowMethod(page: Page, method: AddProjectMethod): Locator {
|
||||
return page.getByTestId(`add-project-flow-method-${method}`);
|
||||
export function addProjectFlowHostTrigger(page: Page): Locator {
|
||||
return page.getByTestId("add-project-flow-host-trigger");
|
||||
}
|
||||
|
||||
export async function expectAddProjectPage(page: Page, kind: AddProjectFlowPage): Promise<Locator> {
|
||||
const currentPage = page.getByTestId(`add-project-flow-page-${kind}`);
|
||||
await expect(currentPage).toBeVisible({ timeout: 30_000 });
|
||||
return currentPage;
|
||||
export async function expectAddProjectTab(page: Page, tab: AddProjectTab): Promise<void> {
|
||||
await expect(addProjectFlowTab(page, tab)).toHaveAttribute("aria-selected", "true", {
|
||||
timeout: 30_000,
|
||||
});
|
||||
}
|
||||
|
||||
async function openAddProjectFlowSurface(
|
||||
page: Page,
|
||||
expectedPage: "host" | "method",
|
||||
): Promise<void> {
|
||||
/** Opens Add project from the sidebar; it starts on Existing with the search focused. */
|
||||
export async function openAddProjectFlow(page: Page): Promise<void> {
|
||||
await page.locator('[data-testid="sidebar-add-project"]:visible').click();
|
||||
await expect(addProjectFlow(page)).toBeVisible({ timeout: 30_000 });
|
||||
await expectAddProjectPage(page, expectedPage);
|
||||
}
|
||||
|
||||
export async function openAddProjectFlow(page: Page): Promise<void> {
|
||||
await openAddProjectFlowSurface(page, "method");
|
||||
}
|
||||
|
||||
export async function openAddProjectHostSelection(page: Page): Promise<void> {
|
||||
await openAddProjectFlowSurface(page, "host");
|
||||
await expectAddProjectTab(page, "existing");
|
||||
await expect(addProjectFlowInput(page)).toBeFocused();
|
||||
}
|
||||
|
||||
export async function chooseAddProjectMethod(page: Page, method: AddProjectMethod): Promise<void> {
|
||||
const option = addProjectFlowMethod(page, method);
|
||||
await expect(option).toBeVisible();
|
||||
await option.click();
|
||||
if (method !== "browse") {
|
||||
await expectAddProjectPage(page, METHOD_DESTINATIONS[method]);
|
||||
}
|
||||
export async function chooseAddProjectTab(page: Page, tab: AddProjectTab): Promise<void> {
|
||||
await addProjectFlowTab(page, tab).click();
|
||||
await expectAddProjectTab(page, tab);
|
||||
}
|
||||
|
||||
export async function chooseAddProjectHost(page: Page, serverId: string): Promise<void> {
|
||||
await addProjectFlowHostTrigger(page).click();
|
||||
await page.getByTestId(`add-project-flow-host-${serverId}`).click();
|
||||
}
|
||||
|
||||
/** Types a parent directory into the Location picker and uses it as typed. */
|
||||
export async function chooseAddProjectLocation(page: Page, location: string): Promise<void> {
|
||||
await page.getByTestId("add-project-flow-location").click();
|
||||
await page.getByPlaceholder("Search folders or enter a path").last().fill(location);
|
||||
await page.getByText("Use this folder", { exact: true }).click();
|
||||
await expect(page.getByTestId("add-project-flow-location")).toContainText(
|
||||
path.basename(location),
|
||||
);
|
||||
}
|
||||
|
||||
export async function expectNewWorkspaceForAddedProject(
|
||||
@@ -114,8 +102,10 @@ export async function expectAddProjectResultVisible(page: Page, text: string): P
|
||||
.toBe(true);
|
||||
}
|
||||
|
||||
/** Presses Enter on the focused Add host button, which the sheet's own Enter must not swallow. */
|
||||
export async function chooseAddHostFromProjectFlow(page: Page): Promise<void> {
|
||||
await page.getByRole("button", { name: /Add host.*No connected hosts/ }).click();
|
||||
await addProjectFlow(page).getByRole("button", { name: "Add host", exact: true }).focus();
|
||||
await page.keyboard.press("Enter");
|
||||
}
|
||||
|
||||
export async function navigateAndDismissAddProject(page: Page): Promise<void> {
|
||||
|
||||
@@ -449,6 +449,41 @@ async function boxTop(locator: Locator): Promise<number> {
|
||||
return box.y;
|
||||
}
|
||||
|
||||
export async function searchModelPicker(page: Page, query: string): Promise<void> {
|
||||
await pickerViewport(page).getByTestId("model-search-input").fill(query);
|
||||
}
|
||||
|
||||
/** A search lists matching profiles first, then the matching models under their own heading. */
|
||||
export async function expectProfileSearchResult(
|
||||
page: Page,
|
||||
input: { name: string; model?: { provider: string; modelId: string } },
|
||||
): Promise<void> {
|
||||
const viewport = pickerViewport(page);
|
||||
const row = profilePickerRow(page, input.name);
|
||||
await expect(row).toBeVisible({ timeout: 30_000 });
|
||||
if (!input.model) {
|
||||
await expect(viewport.getByText("Models", { exact: true })).toHaveCount(0);
|
||||
return;
|
||||
}
|
||||
const matchedModel = modelRow(page, input.model);
|
||||
await expect(viewport.getByText("Models", { exact: true })).toBeVisible();
|
||||
await expect(matchedModel).toBeVisible();
|
||||
expect(await boxTop(row)).toBeLessThan(await boxTop(matchedModel));
|
||||
}
|
||||
|
||||
/** Wheel-scrolls the picker the way a pointer user would until the profile row is on screen. */
|
||||
export async function expectProfileReachableByScrolling(page: Page, name: string): Promise<void> {
|
||||
const row = profilePickerRow(page, name);
|
||||
await expect(row).toBeAttached({ timeout: 30_000 });
|
||||
const box = await pickerViewport(page).boundingBox();
|
||||
if (!box) throw new Error("model picker has no layout box");
|
||||
await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2);
|
||||
await expect(async () => {
|
||||
await page.mouse.wheel(0, 400);
|
||||
await expect(row).toBeInViewport({ timeout: 500 });
|
||||
}).toPass({ timeout: 15_000 });
|
||||
}
|
||||
|
||||
export async function applyProfileFromPicker(page: Page, name: string): Promise<void> {
|
||||
await profilePickerRow(page, name).click();
|
||||
await expect(pickerViewport(page)).toHaveCount(0, { timeout: 30_000 });
|
||||
|
||||
@@ -31,8 +31,6 @@ export interface RewindCompletionGate {
|
||||
clearTimelineStreamCount(): void;
|
||||
release(): void;
|
||||
timelineStreamCount(): number;
|
||||
/** Timeline reads this page sent since the last clear. */
|
||||
timelineFetchCount(): number;
|
||||
waitForDelayedResponse(): Promise<void>;
|
||||
}
|
||||
|
||||
@@ -188,20 +186,12 @@ export async function holdDaemonHydration(page: Page): Promise<DaemonHydrationGa
|
||||
};
|
||||
}
|
||||
|
||||
// The rewind response and the timeline change it causes; the change removes the rewound row too.
|
||||
const REWIND_COMPLETION_MESSAGES = new Set([
|
||||
"agent.rewind.response",
|
||||
"agent.timeline.rewind",
|
||||
"agent.timeline.replacement",
|
||||
]);
|
||||
|
||||
export async function holdRewindCompletion(
|
||||
page: Page,
|
||||
agentId: string,
|
||||
): Promise<RewindCompletionGate> {
|
||||
let released = false;
|
||||
let timelineStreamCount = 0;
|
||||
let timelineFetchCount = 0;
|
||||
const delayedForwards: Array<() => void> = [];
|
||||
let resolveDelayedResponse: (() => void) | null = null;
|
||||
const delayedResponse = new Promise<void>((resolve) => {
|
||||
@@ -210,16 +200,7 @@ export async function holdRewindCompletion(
|
||||
|
||||
await page.routeWebSocket(daemonWsRoutePattern(), (ws) => {
|
||||
const server = ws.connectToServer();
|
||||
ws.onMessage((message) => {
|
||||
const sessionMessage = getSessionMessage(message);
|
||||
if (
|
||||
sessionMessage?.type === "fetch_agent_timeline_request" &&
|
||||
sessionMessage.agentId === agentId
|
||||
) {
|
||||
timelineFetchCount += 1;
|
||||
}
|
||||
server.send(message);
|
||||
});
|
||||
ws.onMessage((message) => server.send(message));
|
||||
server.onMessage((message) => {
|
||||
const sessionMessage = getSessionMessage(message);
|
||||
const payload = sessionMessage ? getPayload(sessionMessage) : null;
|
||||
@@ -235,11 +216,11 @@ export async function holdRewindCompletion(
|
||||
}
|
||||
if (
|
||||
!released &&
|
||||
sessionMessage &&
|
||||
REWIND_COMPLETION_MESSAGES.has(String(sessionMessage.type)) &&
|
||||
(sessionMessage?.type === "agent.rewind.response" ||
|
||||
sessionMessage?.type === "agent.timeline.replacement") &&
|
||||
payload?.agentId === agentId
|
||||
) {
|
||||
// The rewind also signals completion and removes the rewound row/menu.
|
||||
// The replacement also signals completion and removes the rewound row/menu.
|
||||
// Hold it with the response so the pending-state assertion observes a pending rewind.
|
||||
delayedForwards.push(() => ws.send(message));
|
||||
if (sessionMessage.type === "agent.rewind.response") resolveDelayedResponse?.();
|
||||
@@ -252,7 +233,6 @@ export async function holdRewindCompletion(
|
||||
return {
|
||||
clearTimelineStreamCount() {
|
||||
timelineStreamCount = 0;
|
||||
timelineFetchCount = 0;
|
||||
},
|
||||
release() {
|
||||
released = true;
|
||||
@@ -261,7 +241,6 @@ export async function holdRewindCompletion(
|
||||
}
|
||||
},
|
||||
timelineStreamCount: () => timelineStreamCount,
|
||||
timelineFetchCount: () => timelineFetchCount,
|
||||
waitForDelayedResponse: () => delayedResponse,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -132,7 +132,10 @@ export async function waitForConnectedHost(
|
||||
): Promise<void> {
|
||||
await page.getByTestId("sidebar-hosts-trigger").click();
|
||||
const host = page.getByTestId(`sidebar-host-row-${input.serverId}`);
|
||||
await expect(host).toContainText(input.endpoint, { timeout: 30_000 });
|
||||
const escapedEndpoint = input.endpoint.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
// Local daemons render "Local" without repeating localhost:<port>; remote hosts render the endpoint.
|
||||
await expect(host).toContainText(new RegExp(`${escapedEndpoint}|Local`), { timeout: 30_000 });
|
||||
await expect(host).toContainText(/\d+(?:\.\d+)?(?:µs|ms|s)/, { timeout: 30_000 });
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(host).not.toBeVisible();
|
||||
}
|
||||
@@ -195,6 +198,12 @@ export async function chooseHostColor(page: Page, colorName: string): Promise<vo
|
||||
await expect(page.getByRole("button", { name: `Color, ${colorName}` })).toBeVisible();
|
||||
}
|
||||
|
||||
export async function chooseHostIcon(page: Page, iconName: string): Promise<void> {
|
||||
await page.getByTestId("host-appearance-icon").click();
|
||||
await page.getByRole("menuitem", { name: iconName, exact: true }).click();
|
||||
await expect(page.getByRole("button", { name: `Icon, ${iconName}` })).toBeVisible();
|
||||
}
|
||||
|
||||
export async function chooseHostBadgeDisplay(
|
||||
page: Page,
|
||||
option: "Name" | "Icon only" | "Hidden",
|
||||
|
||||
@@ -4,7 +4,7 @@ import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { expect, type Locator, type Page } from "@playwright/test";
|
||||
import type { DaemonClient as InternalDaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
import { addProjectFlow, addProjectFlowInput, chooseAddProjectMethod } from "./add-project-flow";
|
||||
import { addProjectFlow, addProjectFlowInput, expectAddProjectTab } from "./add-project-flow";
|
||||
import { connectDaemonClient } from "./daemon-client-loader";
|
||||
import { buildCreateAgentPreferences, buildSeededHost } from "./daemon-registry";
|
||||
import { startIsolatedHostDaemon, type IsolatedHostDaemonOptions } from "./isolated-host-daemon";
|
||||
@@ -122,7 +122,7 @@ export async function skipSetup(page: Page): Promise<void> {
|
||||
export async function addProjectFromSetup(page: Page, projectPath: string): Promise<void> {
|
||||
await setupModal(page).getByRole("button", { name: "Add project", exact: true }).click();
|
||||
await expect(addProjectFlow(page)).toBeVisible({ timeout: 30_000 });
|
||||
await chooseAddProjectMethod(page, "directory-search");
|
||||
await expectAddProjectTab(page, "existing");
|
||||
await addProjectFlowInput(page).fill(projectPath);
|
||||
await page.keyboard.press("Enter");
|
||||
await expect(addProjectFlow(page)).toHaveCount(0, { timeout: 30_000 });
|
||||
|
||||
@@ -16,8 +16,8 @@ export async function openSidebarHostPicker(page: Page) {
|
||||
await page.getByRole("button", { name: "Hosts", exact: true }).click();
|
||||
}
|
||||
|
||||
export function sidebarHostSettingsButton(page: Page) {
|
||||
return page.getByRole("button", { name: `Open ${TEST_HOST_LABEL} settings`, exact: true });
|
||||
export function sidebarHostRowButton(page: Page) {
|
||||
return page.getByTestId(`sidebar-host-row-${getServerId()}`);
|
||||
}
|
||||
|
||||
export async function bindCommandCenterToEnter(page: Page) {
|
||||
@@ -32,20 +32,10 @@ export async function bindCommandCenterToEnter(page: Page) {
|
||||
});
|
||||
}
|
||||
|
||||
export async function expectStandaloneSidebarHostSettingsButton(page: Page) {
|
||||
const gear = sidebarHostSettingsButton(page);
|
||||
await expect(gear).toBeVisible();
|
||||
expect(await gear.evaluate((button) => button.parentElement?.closest("button") === null)).toBe(
|
||||
true,
|
||||
);
|
||||
}
|
||||
|
||||
export async function activateSidebarHostSettingsWithKeyboard(page: Page) {
|
||||
const host = page.getByRole("button", { name: TEST_HOST_LABEL, exact: true });
|
||||
const host = sidebarHostRowButton(page);
|
||||
await expect(host).toBeVisible();
|
||||
await expect(host).toBeFocused();
|
||||
await page.keyboard.press("ArrowDown");
|
||||
await page.keyboard.press("Tab");
|
||||
await expect(sidebarHostSettingsButton(page)).toBeFocused();
|
||||
await page.keyboard.press("Enter");
|
||||
}
|
||||
|
||||
|
||||
@@ -40,7 +40,7 @@
|
||||
"dev:ios": "npm --prefix ../.. run build:client && cross-env APP_VARIANT=development expo run:ios",
|
||||
"build:apk": "npm --prefix ../.. run build:apk",
|
||||
"build:apk:arm64": "npm --prefix ../.. run build:apk:arm64",
|
||||
"test:android": "expo prebuild --platform android --no-install && cd android && ./gradlew :paseo-native-trace:testReleaseUnitTest :paseo-hardware-keyboard:testReleaseUnitTest :react-native-enriched-markdown:testReleaseUnitTest --tests '*InlineCodeFormattingTest' --tests '*ListRenderingTest' --tests '*TaskListInteractionTest' --tests '*ListBlockquoteMeasurementTest' --no-daemon --max-workers=2 -Dorg.gradle.parallel=false"
|
||||
"test:android": "expo prebuild --platform android --no-install && cd android && ./gradlew :paseo-native-trace:testReleaseUnitTest :paseo-hardware-keyboard:testReleaseUnitTest :react-native-enriched-markdown:testReleaseUnitTest --tests '*InlineCodeFormattingTest' --tests '*ListRenderingTest' --tests '*TaskListInteractionTest' --tests '*ListBlockquoteMeasurementTest' --tests '*BlockquoteCopyTest' --no-daemon --max-workers=2 -Dorg.gradle.parallel=false"
|
||||
},
|
||||
"dependencies": {
|
||||
"@codemirror/commands": "6.10.4",
|
||||
|
||||
@@ -0,0 +1,204 @@
|
||||
import { useMemo } from "react";
|
||||
import { View } from "react-native";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { GitHubIcon } from "@/components/icons/github-icon";
|
||||
import { FormTextInput } from "@/components/ui/form-field";
|
||||
import { isWeb } from "@/constants/platform";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
import { ICON_SIZE } from "@/styles/theme";
|
||||
import type { AddProjectActions } from "./use-add-project-actions";
|
||||
import type { AddProjectFlowState, AddProjectHost, GithubRepositoryChoice } from "./model";
|
||||
import { LocationField } from "./location-field";
|
||||
import {
|
||||
buildManualGithubRepositoryChoices,
|
||||
checkoutName,
|
||||
joinDirectoryPath,
|
||||
MANUAL_CHOICE_PREFIX,
|
||||
} from "./options";
|
||||
import { ResultList, type ResultRow } from "./result-list";
|
||||
import { RESULTS_TEST_ID } from "./result-list-id";
|
||||
import { useGithubRepositorySearch } from "./searches";
|
||||
import { resolveActiveIndex, type AddProjectTabView } from "./tab-view";
|
||||
|
||||
const ThemedGitHubIcon = withUnistyles(GitHubIcon);
|
||||
const mutedColor = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
|
||||
const githubIcon = <ThemedGitHubIcon size={ICON_SIZE.md} uniProps={mutedColor} />;
|
||||
|
||||
/**
|
||||
* The project the query names comes first: the search result that matches it exactly, or else
|
||||
* the pasted URL or owner/repo as typed.
|
||||
*/
|
||||
function buildCloneChoices(
|
||||
query: string,
|
||||
found: GithubRepositoryChoice[],
|
||||
): GithubRepositoryChoice[] {
|
||||
const normalized = query.trim().toLowerCase();
|
||||
const isExact = (repository: GithubRepositoryChoice) =>
|
||||
repository.nameWithOwner.toLowerCase() === normalized ||
|
||||
repository.cloneUrl.toLowerCase() === normalized;
|
||||
const exact = found.filter(isExact);
|
||||
if (exact.length === 0) return [...buildManualGithubRepositoryChoices(query), ...found];
|
||||
return [...exact, ...found.filter((repository) => !isExact(repository))];
|
||||
}
|
||||
|
||||
/** A choice built from the typed URL or owner/repo rather than from a search answer. */
|
||||
function isTypedChoice(choice: GithubRepositoryChoice | undefined): boolean {
|
||||
return choice?.id.startsWith(MANUAL_CHOICE_PREFIX) === true;
|
||||
}
|
||||
|
||||
function cloneEmptyText(host: AddProjectHost, query: string): string {
|
||||
if (!host.canSearchGithubRepositories) return "Paste a Git URL or owner/repo";
|
||||
return query.trim() ? "No matching projects" : "Search GitHub or paste a Git URL";
|
||||
}
|
||||
|
||||
export interface CloneTabView extends AddProjectTabView {
|
||||
location: string;
|
||||
destination: string;
|
||||
}
|
||||
|
||||
const CLONE_UNAVAILABLE = "Update the host to clone projects";
|
||||
|
||||
export function useCloneTab(input: {
|
||||
state: AddProjectFlowState;
|
||||
host: AddProjectHost | null;
|
||||
defaultLocation: string;
|
||||
actions: AddProjectActions;
|
||||
}): CloneTabView {
|
||||
const { state, host, defaultLocation, actions } = input;
|
||||
const { query } = state.clone;
|
||||
const canClone = host?.canCloneGithubRepositories === true;
|
||||
const search = useGithubRepositorySearch({
|
||||
hostId: state.hostId,
|
||||
query,
|
||||
enabled: state.tab === "clone" && canClone && host?.canSearchGithubRepositories === true,
|
||||
});
|
||||
|
||||
const choices = useMemo(
|
||||
() => (canClone ? buildCloneChoices(query, search.items) : []),
|
||||
[canClone, query, search.items],
|
||||
);
|
||||
const rows = useMemo<ResultRow[]>(
|
||||
() =>
|
||||
choices.map((repository) => ({
|
||||
id: repository.id,
|
||||
title: repository.cloneProtocol
|
||||
? `${repository.nameWithOwner} via ${repository.cloneProtocol.toUpperCase()}`
|
||||
: repository.nameWithOwner,
|
||||
subtitle: repository.description,
|
||||
icon: GitHubIcon,
|
||||
testID: `add-project-flow-repository-${repository.id}`,
|
||||
})),
|
||||
[choices],
|
||||
);
|
||||
// While the search for new text runs, the rows on screen answer the old text. None of them is
|
||||
// picked until the new answer arrives or the user picks one, unless it is the typed URL.
|
||||
const awaitingRows =
|
||||
search.pending && state.clone.selectedId === null && !isTypedChoice(choices[0]);
|
||||
const activeIndex = awaitingRows ? -1 : resolveActiveIndex(rows, state.clone.selectedId);
|
||||
const repository = choices[activeIndex] ?? null;
|
||||
const location = state.clone.location ?? defaultLocation;
|
||||
const destination = repository
|
||||
? joinDirectoryPath(location, checkoutName(repository.nameWithOwner))
|
||||
: location;
|
||||
|
||||
return useMemo<CloneTabView>(() => {
|
||||
const unavailable = host && canClone ? null : CLONE_UNAVAILABLE;
|
||||
let notice: AddProjectTabView["notice"] = null;
|
||||
if (!host || unavailable) notice = { kind: "empty", text: CLONE_UNAVAILABLE };
|
||||
else if (search.error) notice = { kind: "error", text: search.error };
|
||||
else if (search.pending) notice = { kind: "pending", text: "Searching..." };
|
||||
else notice = { kind: "empty", text: cloneEmptyText(host, query) };
|
||||
return {
|
||||
rows,
|
||||
activeIndex,
|
||||
notice,
|
||||
unavailable,
|
||||
location,
|
||||
destination,
|
||||
primary: {
|
||||
label: "Clone project",
|
||||
submit: repository ? () => actions.clone(repository, location) : null,
|
||||
},
|
||||
};
|
||||
}, [
|
||||
actions,
|
||||
activeIndex,
|
||||
canClone,
|
||||
destination,
|
||||
host,
|
||||
location,
|
||||
query,
|
||||
repository,
|
||||
rows,
|
||||
search.error,
|
||||
search.pending,
|
||||
]);
|
||||
}
|
||||
|
||||
export function CloneTab({
|
||||
view,
|
||||
query,
|
||||
hostId,
|
||||
recommendedPaths,
|
||||
disabled,
|
||||
autoFocus,
|
||||
onQueryChange,
|
||||
onSelectRow,
|
||||
onLocationChange,
|
||||
}: {
|
||||
view: CloneTabView;
|
||||
query: string;
|
||||
hostId: string | null;
|
||||
recommendedPaths: string[];
|
||||
disabled: boolean;
|
||||
/** Focus the field on mount; only with a hardware keyboard, so touch keeps the list in view. */
|
||||
autoFocus: boolean;
|
||||
onQueryChange: (query: string) => void;
|
||||
onSelectRow: (index: number) => void;
|
||||
onLocationChange: (location: string) => void;
|
||||
}) {
|
||||
const editable = !disabled && !view.unavailable;
|
||||
return (
|
||||
<View style={styles.body}>
|
||||
<FormTextInput
|
||||
initialValue={query}
|
||||
onChangeText={onQueryChange}
|
||||
onSubmitEditing={isWeb ? undefined : (view.primary.submit ?? undefined)}
|
||||
leading={githubIcon}
|
||||
placeholder="Search GitHub or paste a Git URL"
|
||||
accessibilityLabel="Search GitHub"
|
||||
autoFocus={autoFocus}
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
returnKeyType="go"
|
||||
editable={editable}
|
||||
testID="add-project-flow-input"
|
||||
/>
|
||||
<ResultList
|
||||
rows={view.rows}
|
||||
activeIndex={view.activeIndex}
|
||||
notice={view.notice}
|
||||
onSelect={onSelectRow}
|
||||
disabled={disabled}
|
||||
testID={RESULTS_TEST_ID}
|
||||
/>
|
||||
<LocationField
|
||||
hostId={hostId}
|
||||
location={view.location}
|
||||
destination={view.destination}
|
||||
recommendedPaths={recommendedPaths}
|
||||
onChange={onLocationChange}
|
||||
disabled={!editable}
|
||||
testID="add-project-flow-location"
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
body: {
|
||||
flex: 1,
|
||||
minHeight: 0,
|
||||
gap: theme.spacing[3],
|
||||
},
|
||||
}));
|
||||
@@ -0,0 +1,166 @@
|
||||
import { useMemo } from "react";
|
||||
import { View } from "react-native";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { Folder, FolderOpen, Search } from "lucide-react-native";
|
||||
import { buildProjectPickerOptions } from "@/components/project-picker-options";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { FormTextInput } from "@/components/ui/form-field";
|
||||
import { isWeb } from "@/constants/platform";
|
||||
import { ICON_SIZE, type Theme } from "@/styles/theme";
|
||||
import { shortenPath } from "@/utils/shorten-path";
|
||||
import type { AddProjectActions } from "./use-add-project-actions";
|
||||
import type { AddProjectFlowState, AddProjectHost } from "./model";
|
||||
import { pathBaseName } from "./options";
|
||||
import { ResultList, type ResultRow } from "./result-list";
|
||||
import { RESULTS_TEST_ID } from "./result-list-id";
|
||||
import { useDirectorySearch } from "./searches";
|
||||
import { resolveActiveIndex, type AddProjectTabView } from "./tab-view";
|
||||
|
||||
const ThemedSearch = withUnistyles(Search);
|
||||
const mutedColor = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
|
||||
const searchIcon = <ThemedSearch size={ICON_SIZE.md} uniProps={mutedColor} />;
|
||||
|
||||
export function useExistingTab(input: {
|
||||
state: AddProjectFlowState;
|
||||
host: AddProjectHost | null;
|
||||
recommendedPaths: string[];
|
||||
actions: AddProjectActions;
|
||||
}): AddProjectTabView {
|
||||
const { state, host, recommendedPaths, actions } = input;
|
||||
const { query } = state.existing;
|
||||
const canAddProject = host?.canAddProject === true;
|
||||
const search = useDirectorySearch({
|
||||
hostId: state.hostId,
|
||||
query,
|
||||
// The host answers a blank query with nothing, so only search once there is text.
|
||||
enabled: state.tab === "existing" && canAddProject && query.trim().length > 0,
|
||||
});
|
||||
|
||||
const paths = useMemo(
|
||||
() =>
|
||||
canAddProject
|
||||
? buildProjectPickerOptions({ recommendedPaths, serverPaths: search.items, query })
|
||||
: [],
|
||||
[canAddProject, query, recommendedPaths, search.items],
|
||||
);
|
||||
const rows = useMemo<ResultRow[]>(
|
||||
() =>
|
||||
paths.map((option) => {
|
||||
const shortPath = shortenPath(option.path);
|
||||
return {
|
||||
id: option.path,
|
||||
title: option.kind === "path" ? shortPath : pathBaseName(option.path),
|
||||
subtitle: option.kind === "path" ? "Open this path" : shortPath,
|
||||
icon: Folder,
|
||||
testID: `add-project-flow-folder-${encodeURIComponent(option.path)}`,
|
||||
};
|
||||
}),
|
||||
[paths],
|
||||
);
|
||||
// While the search for new text runs, the rows on screen answer the old text. None of them is
|
||||
// picked until the new answer arrives or the user picks one, unless it is the typed path.
|
||||
const awaitingRows =
|
||||
search.pending && state.existing.selectedId === null && paths[0]?.kind !== "path";
|
||||
const activeIndex = awaitingRows ? -1 : resolveActiveIndex(rows, state.existing.selectedId);
|
||||
const activePath = paths[activeIndex]?.path ?? null;
|
||||
|
||||
return useMemo<AddProjectTabView>(() => {
|
||||
const unavailable = canAddProject ? null : "Update the host to add projects";
|
||||
let notice: AddProjectTabView["notice"] = null;
|
||||
if (unavailable) notice = { kind: "empty", text: unavailable };
|
||||
else if (search.error) notice = { kind: "error", text: search.error };
|
||||
else if (search.pending) notice = { kind: "pending", text: "Searching..." };
|
||||
else notice = { kind: "empty", text: query.trim() ? "No matching folders" : "No folders yet" };
|
||||
return {
|
||||
rows,
|
||||
activeIndex,
|
||||
notice,
|
||||
unavailable,
|
||||
primary: {
|
||||
label: "Open project",
|
||||
submit: activePath ? () => actions.openFolder(activePath) : null,
|
||||
},
|
||||
};
|
||||
}, [actions, activeIndex, activePath, canAddProject, query, rows, search.error, search.pending]);
|
||||
}
|
||||
|
||||
export function ExistingTab({
|
||||
view,
|
||||
query,
|
||||
canBrowse,
|
||||
disabled,
|
||||
autoFocus,
|
||||
onQueryChange,
|
||||
onSelectRow,
|
||||
onBrowse,
|
||||
}: {
|
||||
view: AddProjectTabView;
|
||||
query: string;
|
||||
canBrowse: boolean;
|
||||
disabled: boolean;
|
||||
/** Focus the field on mount; only with a hardware keyboard, so touch keeps the list in view. */
|
||||
autoFocus: boolean;
|
||||
onQueryChange: (query: string) => void;
|
||||
onSelectRow: (index: number) => void;
|
||||
onBrowse: () => void;
|
||||
}) {
|
||||
const editable = !disabled && !view.unavailable;
|
||||
return (
|
||||
<View style={styles.body}>
|
||||
<View style={styles.searchRow}>
|
||||
<View style={styles.searchField}>
|
||||
<FormTextInput
|
||||
initialValue={query}
|
||||
onChangeText={onQueryChange}
|
||||
onSubmitEditing={isWeb ? undefined : (view.primary.submit ?? undefined)}
|
||||
leading={searchIcon}
|
||||
placeholder="Search folders or enter a path"
|
||||
accessibilityLabel="Search folders"
|
||||
autoFocus={autoFocus}
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
returnKeyType="go"
|
||||
editable={editable}
|
||||
testID="add-project-flow-input"
|
||||
/>
|
||||
</View>
|
||||
{canBrowse ? (
|
||||
<Button
|
||||
variant="secondary"
|
||||
leftIcon={FolderOpen}
|
||||
onPress={onBrowse}
|
||||
disabled={!editable}
|
||||
testID="add-project-flow-browse"
|
||||
>
|
||||
Browse
|
||||
</Button>
|
||||
) : null}
|
||||
</View>
|
||||
<ResultList
|
||||
rows={view.rows}
|
||||
activeIndex={view.activeIndex}
|
||||
notice={view.notice}
|
||||
onSelect={onSelectRow}
|
||||
disabled={disabled}
|
||||
testID={RESULTS_TEST_ID}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
body: {
|
||||
flex: 1,
|
||||
minHeight: 0,
|
||||
gap: theme.spacing[3],
|
||||
},
|
||||
searchRow: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
searchField: {
|
||||
flex: 1,
|
||||
minWidth: 0,
|
||||
},
|
||||
}));
|
||||
@@ -0,0 +1,4 @@
|
||||
/** Native moves no focus to buttons from a hardware keyboard, so Enter always reaches the sheet. */
|
||||
export function focusedControlOwnsEnter(): boolean {
|
||||
return false;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { RESULTS_TEST_ID } from "./result-list-id";
|
||||
|
||||
const ACTIVATES_ON_ENTER =
|
||||
'button, a[href], [role="button"], [role="link"], [role="tab"], [role="combobox"], [role="menuitem"]';
|
||||
|
||||
/**
|
||||
* Whether the focused element handles Enter itself, such as the Close button, a tab, or the
|
||||
* Location field. Result rows are buttons too, but focusing a row picks it, so Enter on a row
|
||||
* runs the primary action for that row.
|
||||
*/
|
||||
export function focusedControlOwnsEnter(): boolean {
|
||||
const active = document.activeElement;
|
||||
if (!(active instanceof HTMLElement)) return false;
|
||||
if (active.closest(`[data-testid="${RESULTS_TEST_ID}"]`)) return false;
|
||||
return active.matches(ACTIVATES_ON_ENTER);
|
||||
}
|
||||
@@ -0,0 +1,492 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
|
||||
import { Text, View } from "react-native";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import { Folder, FolderPlus, Plus } from "lucide-react-native";
|
||||
import { AdaptiveModalSheet, type SheetKeyboard } from "@/components/adaptive-modal-sheet";
|
||||
import { HostStatusDot } from "@/components/host-status-dot";
|
||||
import { HostPicker } from "@/components/hosts/host-picker";
|
||||
import { GitHubIcon } from "@/components/icons/github-icon";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { SegmentedControl, type SegmentedControlOption } from "@/components/ui/segmented-control";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { useAddHost } from "@/hosts/add-host";
|
||||
import { useHardwareKeyboardPresent, type KeyboardInputEvent } from "@/keyboard";
|
||||
import { Shortcut } from "@/components/ui/shortcut";
|
||||
import { FieldTrigger } from "@/screens/new-workspace/form/field-trigger";
|
||||
import {
|
||||
useAddProjectFlowStore,
|
||||
type AddProjectFlowRequest,
|
||||
} from "@/stores/add-project-flow-store";
|
||||
import { useRecommendedProjectPaths } from "@/stores/session-store-hooks";
|
||||
import { formatShortcut } from "@/utils/format-shortcut";
|
||||
import { getShortcutOs } from "@/utils/shortcut-platform";
|
||||
import { CloneTab, useCloneTab } from "./clone-tab";
|
||||
import { ExistingTab, useExistingTab } from "./existing-tab";
|
||||
import { focusedControlOwnsEnter } from "./focused-control";
|
||||
import {
|
||||
ADD_PROJECT_KEYS,
|
||||
addProjectFailure,
|
||||
applyAvailableAddProjectHosts,
|
||||
currentAddProjectHost,
|
||||
selectableAddProjectHosts,
|
||||
isAddProjectSubmitting,
|
||||
moveAddProjectActiveIndex,
|
||||
openAddProjectFlow,
|
||||
resolveAddProjectKey,
|
||||
selectAddProjectHost,
|
||||
selectAddProjectRow,
|
||||
selectAddProjectTab,
|
||||
setAddProjectLocation,
|
||||
setAddProjectQuery,
|
||||
setNewFolderName,
|
||||
type AddProjectTab,
|
||||
} from "./model";
|
||||
import { NewFolderTab, useNewFolderTab } from "./new-folder-tab";
|
||||
import { defaultProjectLocation } from "./options";
|
||||
import type { AddProjectTabView } from "./tab-view";
|
||||
import { useAddProjectActions } from "./use-add-project-actions";
|
||||
import { useAddProjectHosts } from "./use-add-project-hosts";
|
||||
|
||||
const SNAP_POINTS = ["90%"];
|
||||
// Tall enough for a search field, six result rows, and the location field, so switching tabs
|
||||
// never resizes the card.
|
||||
const DESKTOP_HEIGHT = 560;
|
||||
|
||||
// Compact drops the segment icons so the three labels fit a phone's width.
|
||||
const TABS: {
|
||||
value: AddProjectTab;
|
||||
label: string;
|
||||
key: string;
|
||||
icon: SegmentedControlOption<AddProjectTab>["icon"];
|
||||
}[] = [
|
||||
{
|
||||
value: "existing",
|
||||
label: "Existing",
|
||||
key: "1",
|
||||
icon: ({ color, size }) => <Folder color={color} size={size} />,
|
||||
},
|
||||
{
|
||||
value: "clone",
|
||||
label: "Clone",
|
||||
key: "2",
|
||||
icon: ({ color, size }) => <GitHubIcon color={color} size={size} />,
|
||||
},
|
||||
{
|
||||
value: "new-folder",
|
||||
label: "New folder",
|
||||
key: "3",
|
||||
icon: ({ color, size }) => <FolderPlus color={color} size={size} />,
|
||||
},
|
||||
];
|
||||
|
||||
/** `lockedTo` is the tab a running submission belongs to; the others are disabled until it ends. */
|
||||
function buildTabOptions(
|
||||
isMac: boolean,
|
||||
withIcons: boolean,
|
||||
lockedTo: AddProjectTab | null,
|
||||
): SegmentedControlOption<AddProjectTab>[] {
|
||||
const os = isMac ? "mac" : "non-mac";
|
||||
return TABS.map(
|
||||
(tab): SegmentedControlOption<AddProjectTab> => ({
|
||||
value: tab.value,
|
||||
label: tab.label,
|
||||
icon: withIcons ? tab.icon : undefined,
|
||||
tooltip: formatShortcut(["mod", tab.key], os),
|
||||
testID: `add-project-flow-tab-${tab.value}`,
|
||||
disabled: lockedTo !== null && tab.value !== lockedTo,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
interface AddProjectFlowProps {
|
||||
request: AddProjectFlowRequest;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add project: one sheet with a tab per way to add one. The flow state lives in `./model`; this
|
||||
* component wires it to the host, the searches, and the keys.
|
||||
*/
|
||||
export function AddProjectFlow({ request, onClose }: AddProjectFlowProps) {
|
||||
const isCompact = useIsCompactFormFactor();
|
||||
const isMac = getShortcutOs() === "mac";
|
||||
const keyboardPresent = useHardwareKeyboardPresent();
|
||||
const availableHosts = useAddProjectHosts();
|
||||
const [state, setState] = useState(() =>
|
||||
openAddProjectFlow({
|
||||
hosts: availableHosts,
|
||||
...(request.preferredHostId ? { preferredHostId: request.preferredHostId } : {}),
|
||||
}),
|
||||
);
|
||||
useEffect(() => {
|
||||
setState((current) => applyAvailableAddProjectHosts(current, availableHosts));
|
||||
}, [availableHosts]);
|
||||
|
||||
const host = currentAddProjectHost(state);
|
||||
const submitting = isAddProjectSubmitting(state);
|
||||
const failure = addProjectFailure(state);
|
||||
const recommendedPaths = useRecommendedProjectPaths(state.hostId);
|
||||
const rememberedLocation = useAddProjectFlowStore((store) =>
|
||||
state.hostId ? store.lastLocationByHost[state.hostId] : undefined,
|
||||
);
|
||||
const defaultLocation = defaultProjectLocation({
|
||||
remembered: rememberedLocation,
|
||||
projectPaths: recommendedPaths,
|
||||
});
|
||||
const actions = useAddProjectActions({ hostId: state.hostId, setState, onClose });
|
||||
|
||||
// An offline host keeps its drafts, but nothing submits until it is back or the user picks
|
||||
// another host. Gated here, once, so the footer, Enter and the native Go key all agree.
|
||||
const offline = host?.online === false;
|
||||
const existing = blockSubmitWhen(
|
||||
offline,
|
||||
useExistingTab({ state, host, recommendedPaths, actions }),
|
||||
);
|
||||
const clone = blockSubmitWhen(offline, useCloneTab({ state, host, defaultLocation, actions }));
|
||||
const newFolder = blockSubmitWhen(
|
||||
offline,
|
||||
useNewFolderTab({ state, host, defaultLocation, actions }),
|
||||
);
|
||||
const views: Record<AddProjectTab, AddProjectTabView> = {
|
||||
existing,
|
||||
clone,
|
||||
"new-folder": newFolder,
|
||||
};
|
||||
const view = views[state.tab];
|
||||
|
||||
const selectTab = useCallback(
|
||||
(tab: AddProjectTab) => setState((current) => selectAddProjectTab(current, tab)),
|
||||
[],
|
||||
);
|
||||
const selectHost = useCallback(
|
||||
(hostId: string) => setState((current) => selectAddProjectHost(current, hostId)),
|
||||
[],
|
||||
);
|
||||
const changeQuery = useCallback(
|
||||
(query: string) => setState((current) => setAddProjectQuery(current, query)),
|
||||
[],
|
||||
);
|
||||
const changeLocation = useCallback(
|
||||
(location: string) => setState((current) => setAddProjectLocation(current, location)),
|
||||
[],
|
||||
);
|
||||
const changeName = useCallback(
|
||||
(name: string) => setState((current) => setNewFolderName(current, name)),
|
||||
[],
|
||||
);
|
||||
|
||||
// The key handler reads the latest view without re-registering the overlay on every keystroke.
|
||||
const viewRef = useRef(view);
|
||||
viewRef.current = view;
|
||||
const hasHostRef = useRef(host !== null);
|
||||
hasHostRef.current = host !== null;
|
||||
/** Picks the row at `index` of the current tab's list, remembered by its id. */
|
||||
const selectRow = useCallback((index: number) => {
|
||||
const row = viewRef.current.rows[index];
|
||||
if (row) setState((current) => selectAddProjectRow(current, row.id));
|
||||
}, []);
|
||||
const keyboard = useMemo<SheetKeyboard>(
|
||||
() => ({
|
||||
keys: ADD_PROJECT_KEYS,
|
||||
onKeyDown: (event: KeyboardInputEvent) => {
|
||||
// With no host there is nothing to switch to or submit; Enter belongs to Add host.
|
||||
if (!hasHostRef.current) return false;
|
||||
const command = resolveAddProjectKey(event, isMac);
|
||||
if (!command) return false;
|
||||
const current = viewRef.current;
|
||||
if (command.kind === "tab") {
|
||||
selectTab(command.tab);
|
||||
return true;
|
||||
}
|
||||
if (command.kind === "move") {
|
||||
if (current.rows.length === 0) return false;
|
||||
selectRow(
|
||||
moveAddProjectActiveIndex(current.activeIndex, current.rows.length, command.direction),
|
||||
);
|
||||
return true;
|
||||
}
|
||||
if (!current.primary.submit || focusedControlOwnsEnter()) return false;
|
||||
current.primary.submit();
|
||||
return true;
|
||||
},
|
||||
}),
|
||||
[isMac, selectRow, selectTab],
|
||||
);
|
||||
|
||||
const lockedTab = submitting ? state.tab : null;
|
||||
const tabOptions = useMemo(
|
||||
() => buildTabOptions(isMac, !isCompact, lockedTab),
|
||||
[isCompact, isMac, lockedTab],
|
||||
);
|
||||
const selectableHosts = useMemo(() => selectableAddProjectHosts(state), [state]);
|
||||
const header = useMemo(
|
||||
() => ({
|
||||
title: "Add project",
|
||||
titleTestID: "add-project-flow-title",
|
||||
actions:
|
||||
selectableHosts.length > 1 && state.hostId ? (
|
||||
<HostPill
|
||||
hosts={selectableHosts}
|
||||
hostId={state.hostId}
|
||||
onSelect={selectHost}
|
||||
disabled={submitting}
|
||||
/>
|
||||
) : undefined,
|
||||
}),
|
||||
[selectHost, selectableHosts, state.hostId, submitting],
|
||||
);
|
||||
|
||||
// On a pointer layout the failure sits left of the button; compact stacks it above a
|
||||
// full-width button.
|
||||
const problem = failure ?? (offline && host ? `${host.label} is offline` : null);
|
||||
const failureLine = problem ? (
|
||||
<Text style={styles.failure} numberOfLines={2} testID="add-project-flow-error">
|
||||
{problem}
|
||||
</Text>
|
||||
) : null;
|
||||
const footer = host ? (
|
||||
<>
|
||||
{failureLine ?? (isCompact ? null : <KeyHints canMove={view.rows.length > 0} />)}
|
||||
<Button
|
||||
variant="default"
|
||||
onPress={view.primary.submit ?? undefined}
|
||||
disabled={!view.primary.submit}
|
||||
loading={submitting}
|
||||
style={isCompact ? styles.primaryCompact : styles.primary}
|
||||
testID="add-project-flow-submit"
|
||||
>
|
||||
{view.primary.label}
|
||||
</Button>
|
||||
</>
|
||||
) : null;
|
||||
|
||||
let body: ReactNode;
|
||||
if (!host) {
|
||||
body = <NoHosts onClose={onClose} />;
|
||||
} else if (state.tab === "existing") {
|
||||
body = (
|
||||
<ExistingTab
|
||||
view={existing}
|
||||
query={state.existing.query}
|
||||
canBrowse={host.canBrowse && !offline}
|
||||
disabled={submitting}
|
||||
autoFocus={keyboardPresent}
|
||||
onQueryChange={changeQuery}
|
||||
onSelectRow={selectRow}
|
||||
onBrowse={actions.browse}
|
||||
/>
|
||||
);
|
||||
} else if (state.tab === "clone") {
|
||||
body = (
|
||||
<CloneTab
|
||||
view={clone}
|
||||
query={state.clone.query}
|
||||
hostId={state.hostId}
|
||||
recommendedPaths={recommendedPaths}
|
||||
disabled={submitting}
|
||||
autoFocus={keyboardPresent}
|
||||
onQueryChange={changeQuery}
|
||||
onSelectRow={selectRow}
|
||||
onLocationChange={changeLocation}
|
||||
/>
|
||||
);
|
||||
} else {
|
||||
body = (
|
||||
<NewFolderTab
|
||||
view={newFolder}
|
||||
name={state.newFolder.name}
|
||||
hostId={state.hostId}
|
||||
recommendedPaths={recommendedPaths}
|
||||
disabled={submitting}
|
||||
autoFocus={keyboardPresent}
|
||||
onNameChange={changeName}
|
||||
onLocationChange={changeLocation}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<AdaptiveModalSheet
|
||||
visible
|
||||
onClose={onClose}
|
||||
header={header}
|
||||
footer={footer}
|
||||
footerContainerStyle={isCompact ? styles.footerContainerCompact : undefined}
|
||||
snapPoints={SNAP_POINTS}
|
||||
desktopHeight={DESKTOP_HEIGHT}
|
||||
scrollable={false}
|
||||
keyboard={keyboard}
|
||||
contentStyle={styles.content}
|
||||
testID="add-project-flow"
|
||||
>
|
||||
{host ? (
|
||||
<SegmentedControl
|
||||
options={tabOptions}
|
||||
value={state.tab}
|
||||
onValueChange={selectTab}
|
||||
fill
|
||||
testID="add-project-flow-tabs"
|
||||
/>
|
||||
) : null}
|
||||
{/* Keyed by tab so each tab's input mounts with its own draft and takes focus. */}
|
||||
<View key={host ? state.tab : "no-host"} style={styles.tabBody}>
|
||||
{body}
|
||||
</View>
|
||||
</AdaptiveModalSheet>
|
||||
);
|
||||
}
|
||||
|
||||
function blockSubmitWhen<TabView extends AddProjectTabView>(
|
||||
blocked: boolean,
|
||||
view: TabView,
|
||||
): TabView {
|
||||
return blocked ? { ...view, primary: { ...view.primary, submit: null } } : view;
|
||||
}
|
||||
|
||||
function hostOptionTestID(serverId: string): string {
|
||||
return `add-project-flow-host-${serverId}`;
|
||||
}
|
||||
|
||||
function HostPill({
|
||||
hosts,
|
||||
hostId,
|
||||
onSelect,
|
||||
disabled,
|
||||
}: {
|
||||
hosts: { serverId: string; label: string }[];
|
||||
hostId: string;
|
||||
onSelect: (hostId: string) => void;
|
||||
disabled: boolean;
|
||||
}) {
|
||||
const anchorRef = useRef<View>(null);
|
||||
const [open, setOpen] = useState(false);
|
||||
const openPicker = useCallback(() => setOpen(true), []);
|
||||
const label = hosts.find((host) => host.serverId === hostId)?.label ?? hostId;
|
||||
const icon = useMemo(() => <HostStatusDot serverId={hostId} />, [hostId]);
|
||||
return (
|
||||
<HostPicker
|
||||
hosts={hosts}
|
||||
value={hostId}
|
||||
onSelect={onSelect}
|
||||
open={open}
|
||||
onOpenChange={setOpen}
|
||||
anchorRef={anchorRef}
|
||||
searchable={false}
|
||||
title="Host"
|
||||
desktopPlacement="bottom-end"
|
||||
desktopMinWidth={240}
|
||||
hostOptionTestID={hostOptionTestID}
|
||||
>
|
||||
<FieldTrigger
|
||||
ref={anchorRef}
|
||||
variant="badge"
|
||||
label="Host"
|
||||
accessibilityLabel="Project host"
|
||||
tooltip="Host"
|
||||
icon={icon}
|
||||
value={label}
|
||||
onPress={openPicker}
|
||||
disabled={disabled}
|
||||
testID="add-project-flow-host-trigger"
|
||||
/>
|
||||
</HostPicker>
|
||||
);
|
||||
}
|
||||
|
||||
const MOVE_KEYS = ["↑↓"];
|
||||
const TAB_KEYS = ["mod", "1–3"];
|
||||
|
||||
/** The keys that are not on any control: list movement and tab switching. */
|
||||
function KeyHints({ canMove }: { canMove: boolean }) {
|
||||
const keyboardPresent = useHardwareKeyboardPresent();
|
||||
if (!keyboardPresent) return <View />;
|
||||
return (
|
||||
<View style={styles.hints}>
|
||||
{canMove ? (
|
||||
<View style={styles.hint}>
|
||||
<Shortcut keys={MOVE_KEYS} />
|
||||
<Text style={styles.hintText}>Move</Text>
|
||||
</View>
|
||||
) : null}
|
||||
<View style={styles.hint}>
|
||||
<Shortcut keys={TAB_KEYS} />
|
||||
<Text style={styles.hintText}>Switch</Text>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function NoHosts({ onClose }: { onClose: () => void }) {
|
||||
const addHost = useAddHost();
|
||||
const handleAddHost = useCallback(() => {
|
||||
// The project sheet must release its window before the add-host sheet opens.
|
||||
onClose();
|
||||
addHost();
|
||||
}, [addHost, onClose]);
|
||||
return (
|
||||
<View style={styles.noHosts}>
|
||||
<Text style={styles.noHostsText}>No connected hosts</Text>
|
||||
<Button
|
||||
variant="secondary"
|
||||
leftIcon={Plus}
|
||||
onPress={handleAddHost}
|
||||
testID="add-project-flow-add-host"
|
||||
>
|
||||
Add host
|
||||
</Button>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
content: {
|
||||
flex: 1,
|
||||
minHeight: 0,
|
||||
},
|
||||
tabBody: {
|
||||
flex: 1,
|
||||
minHeight: 0,
|
||||
},
|
||||
footerContainerCompact: {
|
||||
flexDirection: "column",
|
||||
alignItems: "stretch",
|
||||
},
|
||||
// The message wraps beside the button; the button keeps its width.
|
||||
failure: {
|
||||
flexShrink: 1,
|
||||
minWidth: 0,
|
||||
color: theme.colors.statusDanger,
|
||||
fontSize: theme.fontSize.sm,
|
||||
},
|
||||
hints: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[4],
|
||||
},
|
||||
hint: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[1.5],
|
||||
},
|
||||
hintText: {
|
||||
color: theme.colors.foregroundMuted,
|
||||
fontSize: theme.fontSize.sm,
|
||||
},
|
||||
primary: {
|
||||
flexShrink: 0,
|
||||
},
|
||||
primaryCompact: {
|
||||
flexShrink: 0,
|
||||
alignSelf: "stretch",
|
||||
},
|
||||
noHosts: {
|
||||
flex: 1,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
gap: theme.spacing[3],
|
||||
},
|
||||
noHostsText: {
|
||||
color: theme.colors.foregroundMuted,
|
||||
fontSize: theme.fontSize.base,
|
||||
},
|
||||
}));
|
||||
@@ -0,0 +1,109 @@
|
||||
import { useCallback, useMemo, useRef, useState } from "react";
|
||||
import type { View } from "react-native";
|
||||
import { withUnistyles } from "react-native-unistyles";
|
||||
import { HardDrive } from "lucide-react-native";
|
||||
import { buildProjectPickerOptions } from "@/components/project-picker-options";
|
||||
import { Combobox, type ComboboxOption } from "@/components/ui/combobox";
|
||||
import { FieldTrigger } from "@/screens/new-workspace/form/field-trigger";
|
||||
import { ICON_SIZE, type Theme } from "@/styles/theme";
|
||||
import { shortenPath } from "@/utils/shorten-path";
|
||||
import { buildSuggestedParentDirectories } from "./options";
|
||||
import { useDirectorySearch } from "./searches";
|
||||
|
||||
const ThemedHardDrive = withUnistyles(HardDrive);
|
||||
const mutedColor = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
|
||||
const locationIcon = <ThemedHardDrive size={ICON_SIZE.md} uniProps={mutedColor} />;
|
||||
|
||||
interface LocationFieldProps {
|
||||
hostId: string | null;
|
||||
/** The parent directory the project goes into. */
|
||||
location: string;
|
||||
/** Where the project ends up, shown on the field so the user rarely needs to open it. */
|
||||
destination: string;
|
||||
recommendedPaths: string[];
|
||||
onChange: (location: string) => void;
|
||||
disabled: boolean;
|
||||
testID: string;
|
||||
}
|
||||
|
||||
/** Picks the parent directory for a new project: recent parents, a folder search, or a typed path. */
|
||||
export function LocationField({
|
||||
hostId,
|
||||
location,
|
||||
destination,
|
||||
recommendedPaths,
|
||||
onChange,
|
||||
disabled,
|
||||
testID,
|
||||
}: LocationFieldProps) {
|
||||
const anchorRef = useRef<View>(null);
|
||||
const [open, setOpen] = useState(false);
|
||||
const [query, setQuery] = useState("");
|
||||
const search = useDirectorySearch({ hostId, query, enabled: open && query.trim().length > 0 });
|
||||
|
||||
// The same builder as the Existing tab: a typed path first, then matching suggestions and
|
||||
// folders the host found.
|
||||
const pickerOptions = useMemo(() => {
|
||||
const suggestions = [
|
||||
location,
|
||||
...buildSuggestedParentDirectories(recommendedPaths).filter((path) => path !== location),
|
||||
];
|
||||
return buildProjectPickerOptions({
|
||||
recommendedPaths: suggestions,
|
||||
serverPaths: search.items,
|
||||
query,
|
||||
});
|
||||
}, [location, query, recommendedPaths, search.items]);
|
||||
const options = useMemo<ComboboxOption[]>(
|
||||
() =>
|
||||
pickerOptions.map(
|
||||
(option): ComboboxOption => ({
|
||||
id: option.path,
|
||||
label: shortenPath(option.path),
|
||||
description: option.kind === "path" ? "Use this folder" : undefined,
|
||||
kind: "directory",
|
||||
}),
|
||||
),
|
||||
[pickerOptions],
|
||||
);
|
||||
// Like the Existing tab: while a new search runs, only a typed path is picked for Enter.
|
||||
const awaitingOptions = search.pending && pickerOptions[0]?.kind !== "path";
|
||||
|
||||
const handleOpen = useCallback(() => setOpen(true), []);
|
||||
const handleOpenChange = useCallback((next: boolean) => {
|
||||
setOpen(next);
|
||||
if (!next) setQuery("");
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<>
|
||||
<FieldTrigger
|
||||
ref={anchorRef}
|
||||
variant="field"
|
||||
label="Location"
|
||||
accessibilityLabel="Project location"
|
||||
icon={locationIcon}
|
||||
value={shortenPath(destination)}
|
||||
onPress={handleOpen}
|
||||
disabled={disabled}
|
||||
testID={testID}
|
||||
/>
|
||||
<Combobox
|
||||
options={options}
|
||||
value={location}
|
||||
onSelect={onChange}
|
||||
searchable
|
||||
remoteSearch
|
||||
remoteSearchPending={awaitingOptions}
|
||||
onSearchQueryChange={setQuery}
|
||||
searchPlaceholder="Search folders or enter a path"
|
||||
emptyText={search.error ?? (search.pending ? "Searching..." : "No matching folders")}
|
||||
title="Location"
|
||||
open={open}
|
||||
onOpenChange={handleOpenChange}
|
||||
anchorRef={anchorRef}
|
||||
desktopPlacement="bottom-start"
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,153 +1,194 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
backAddProjectPage,
|
||||
chooseAddProjectHost,
|
||||
currentAddProjectPage,
|
||||
applyAvailableAddProjectHosts,
|
||||
selectableAddProjectHosts,
|
||||
failAddProjectSubmission,
|
||||
moveAddProjectActiveIndex,
|
||||
moveAddProjectSelection,
|
||||
openAddProjectFlow,
|
||||
openDirectorySearchPage,
|
||||
openGithubLocationPage,
|
||||
openNewDirectoryNamePage,
|
||||
openNewDirectoryParentPage,
|
||||
setAddProjectActiveIndex,
|
||||
setAddProjectPageInput,
|
||||
setNewDirectoryName,
|
||||
resolveAddProjectKey,
|
||||
selectAddProjectHost,
|
||||
selectAddProjectRow,
|
||||
selectAddProjectTab,
|
||||
setAddProjectLocation,
|
||||
setAddProjectQuery,
|
||||
setNewFolderName,
|
||||
startAddProjectSubmission,
|
||||
type AddProjectHost,
|
||||
} from "./model";
|
||||
import {
|
||||
addProjectMethodEmptyText,
|
||||
buildAddProjectMethods,
|
||||
buildCloneLocationOptions,
|
||||
buildManualGithubRepositoryChoices,
|
||||
checkoutName,
|
||||
defaultProjectLocation,
|
||||
joinDirectoryPath,
|
||||
parentDirectory,
|
||||
validateNewFolderName,
|
||||
} from "./options";
|
||||
import { resolveActiveIndex } from "./tab-view";
|
||||
|
||||
const HOST: AddProjectHost = {
|
||||
serverId: "host-1",
|
||||
label: "Local",
|
||||
online: true,
|
||||
canAddProject: true,
|
||||
canBrowse: true,
|
||||
canCloneGithubRepositories: true,
|
||||
canSearchGithubRepositories: true,
|
||||
canCreateDirectory: true,
|
||||
};
|
||||
const REMOTE: AddProjectHost = { ...HOST, serverId: "host-2", label: "Remote", canBrowse: false };
|
||||
const REMOTE_OFFLINE: AddProjectHost = { ...REMOTE, online: false };
|
||||
|
||||
describe("Add Project navigation", () => {
|
||||
it("skips a single connected host without adding it to history", () => {
|
||||
const state = openAddProjectFlow({ hosts: [HOST] });
|
||||
const KEY = { key: "", ctrlKey: false, metaKey: false, altKey: false, shiftKey: false };
|
||||
|
||||
expect(currentAddProjectPage(state)).toEqual({
|
||||
kind: "method",
|
||||
hostId: "host-1",
|
||||
activeIndex: 0,
|
||||
error: null,
|
||||
isSubmitting: false,
|
||||
});
|
||||
expect(backAddProjectPage(state)).toBeNull();
|
||||
describe("Add Project flow", () => {
|
||||
it("opens on the Existing tab of the preferred host", () => {
|
||||
const state = openAddProjectFlow({ hosts: [HOST, REMOTE], preferredHostId: "host-2" });
|
||||
|
||||
expect(state.tab).toBe("existing");
|
||||
expect(state.hostId).toBe("host-2");
|
||||
});
|
||||
|
||||
it("restores page input and selection after Back", () => {
|
||||
const secondHost = { ...HOST, serverId: "host-2", label: "Remote" };
|
||||
let state = openAddProjectFlow({ hosts: [HOST, secondHost] });
|
||||
state = setAddProjectPageInput(state, "rem");
|
||||
state = setAddProjectActiveIndex(state, 1);
|
||||
state = chooseAddProjectHost(state, secondHost.serverId);
|
||||
state = openDirectorySearchPage(state, secondHost.serverId);
|
||||
|
||||
state = backAddProjectPage(state) ?? state;
|
||||
state = backAddProjectPage(state) ?? state;
|
||||
|
||||
expect(currentAddProjectPage(state)).toEqual({
|
||||
kind: "host",
|
||||
query: "rem",
|
||||
activeIndex: 1,
|
||||
error: null,
|
||||
});
|
||||
it("falls back to the first host, and to no host when none is connected", () => {
|
||||
expect(openAddProjectFlow({ hosts: [HOST, REMOTE] }).hostId).toBe("host-1");
|
||||
expect(openAddProjectFlow({ hosts: [] }).hostId).toBeNull();
|
||||
});
|
||||
|
||||
it("wraps keyboard selection in both directions", () => {
|
||||
it("keeps each tab's input when switching tabs", () => {
|
||||
let state = openAddProjectFlow({ hosts: [HOST] });
|
||||
state = setAddProjectQuery(state, "paseo");
|
||||
state = selectAddProjectTab(state, "clone");
|
||||
state = setAddProjectQuery(state, "getpaseo/");
|
||||
state = selectAddProjectTab(state, "new-folder");
|
||||
state = setNewFolderName(state, "acme-api");
|
||||
state = selectAddProjectTab(state, "existing");
|
||||
|
||||
expect(state.existing.query).toBe("paseo");
|
||||
expect(state.clone.query).toBe("getpaseo/");
|
||||
expect(state.newFolder.name).toBe("acme-api");
|
||||
});
|
||||
|
||||
it("switching host keeps typed input but drops host-specific locations and selection", () => {
|
||||
let state = openAddProjectFlow({ hosts: [HOST, REMOTE] });
|
||||
state = setAddProjectQuery(state, "paseo");
|
||||
state = selectAddProjectRow(state, "/code/paseo");
|
||||
state = selectAddProjectTab(state, "new-folder");
|
||||
state = setNewFolderName(state, "acme-api");
|
||||
state = setAddProjectLocation(state, "~/work");
|
||||
|
||||
state = selectAddProjectHost(state, "host-2");
|
||||
|
||||
expect(state.hostId).toBe("host-2");
|
||||
expect(state.existing).toEqual({ query: "paseo", selectedId: null });
|
||||
expect(state.newFolder).toEqual({ name: "acme-api", location: null });
|
||||
});
|
||||
|
||||
it("locks tab and host while a submission runs, and unlocks with the failure", () => {
|
||||
let state = openAddProjectFlow({ hosts: [HOST, REMOTE] });
|
||||
state = selectAddProjectTab(state, "clone");
|
||||
state = startAddProjectSubmission(state);
|
||||
|
||||
expect(selectAddProjectTab(state, "existing").tab).toBe("clone");
|
||||
expect(selectAddProjectHost(state, "host-2").hostId).toBe("host-1");
|
||||
expect(selectAddProjectRow(state, "acme/app")).toBe(state);
|
||||
expect(startAddProjectSubmission(state)).toBe(state);
|
||||
|
||||
state = failAddProjectSubmission(state, "Unable to clone project");
|
||||
expect(state.submission).toEqual({
|
||||
status: "failed",
|
||||
tab: "clone",
|
||||
message: "Unable to clone project",
|
||||
});
|
||||
expect(selectAddProjectTab(state, "existing").submission).toEqual({ status: "idle" });
|
||||
});
|
||||
|
||||
it("clears a failure once the user edits the input or picks another row", () => {
|
||||
let state = openAddProjectFlow({ hosts: [HOST] });
|
||||
state = startAddProjectSubmission(state);
|
||||
state = failAddProjectSubmission(state, "Directory not found");
|
||||
|
||||
expect(setAddProjectQuery(state, "~/dev").submission).toEqual({ status: "idle" });
|
||||
expect(selectAddProjectRow(state, "/code/app").submission).toEqual({ status: "idle" });
|
||||
});
|
||||
|
||||
it("keeps the chosen host and its draft while it is offline, never moving them to another host", () => {
|
||||
let state = openAddProjectFlow({ hosts: [HOST, REMOTE] });
|
||||
state = selectAddProjectHost(state, "host-2");
|
||||
state = setAddProjectQuery(state, "/srv/app");
|
||||
|
||||
const offline = applyAvailableAddProjectHosts(state, [HOST, REMOTE_OFFLINE]);
|
||||
expect(offline.hostId).toBe("host-2");
|
||||
expect(offline.existing.query).toBe("/srv/app");
|
||||
expect(selectableAddProjectHosts(offline).map((host) => host.serverId)).toEqual([
|
||||
"host-1",
|
||||
"host-2",
|
||||
]);
|
||||
|
||||
const back = applyAvailableAddProjectHosts(offline, [HOST, REMOTE]);
|
||||
expect(back.hostId).toBe("host-2");
|
||||
expect(back.existing.query).toBe("/srv/app");
|
||||
expect(selectAddProjectHost(offline, "host-1").hostId).toBe("host-1");
|
||||
});
|
||||
|
||||
it("picks only an online host, and another one when the chosen host is removed", () => {
|
||||
expect(openAddProjectFlow({ hosts: [REMOTE_OFFLINE, HOST] }).hostId).toBe("host-1");
|
||||
expect(
|
||||
openAddProjectFlow({ hosts: [REMOTE_OFFLINE, HOST], preferredHostId: "host-2" }).hostId,
|
||||
).toBe("host-1");
|
||||
expect(openAddProjectFlow({ hosts: [REMOTE_OFFLINE] }).hostId).toBeNull();
|
||||
expect(
|
||||
selectAddProjectHost(openAddProjectFlow({ hosts: [HOST, REMOTE_OFFLINE] }), "host-2").hostId,
|
||||
).toBe("host-1");
|
||||
|
||||
const state = selectAddProjectHost(openAddProjectFlow({ hosts: [HOST, REMOTE] }), "host-2");
|
||||
expect(applyAvailableAddProjectHosts(state, [HOST]).hostId).toBe("host-1");
|
||||
expect(applyAvailableAddProjectHosts(openAddProjectFlow({ hosts: [] }), [REMOTE]).hostId).toBe(
|
||||
"host-2",
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps the user's pick across a reorder and never swaps a dropped pick for another row", () => {
|
||||
const rows = [{ id: "/code/beta" }, { id: "/code/alpha" }];
|
||||
expect(resolveActiveIndex(rows, "/code/alpha")).toBe(1);
|
||||
expect(resolveActiveIndex(rows, null)).toBe(0);
|
||||
expect(resolveActiveIndex(rows, "/code/gone")).toBe(-1);
|
||||
expect(resolveActiveIndex([], null)).toBe(-1);
|
||||
});
|
||||
|
||||
it("wraps keyboard selection at both ends", () => {
|
||||
expect(moveAddProjectActiveIndex(2, 3, "next")).toBe(0);
|
||||
expect(moveAddProjectActiveIndex(0, 3, "previous")).toBe(2);
|
||||
expect(moveAddProjectSelection(0, [true, false, true], "next")).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Add Project keys", () => {
|
||||
it("maps Mod+1/2/3 to tabs using the platform's modifier", () => {
|
||||
expect(resolveAddProjectKey({ ...KEY, key: "2", metaKey: true }, true)).toEqual({
|
||||
kind: "tab",
|
||||
tab: "clone",
|
||||
});
|
||||
expect(resolveAddProjectKey({ ...KEY, key: "3", ctrlKey: true }, false)).toEqual({
|
||||
kind: "tab",
|
||||
tab: "new-folder",
|
||||
});
|
||||
expect(resolveAddProjectKey({ ...KEY, key: "1", ctrlKey: true }, true)).toBeNull();
|
||||
expect(resolveAddProjectKey({ ...KEY, key: "1" }, true)).toBeNull();
|
||||
});
|
||||
|
||||
it("restores a directory name after returning to and reselecting its parent", () => {
|
||||
let state = openAddProjectFlow({ hosts: [HOST] });
|
||||
state = openNewDirectoryParentPage(state, HOST.serverId);
|
||||
state = openNewDirectoryNamePage(state, HOST.serverId, "~/dev");
|
||||
state = setNewDirectoryName(state, "command-center");
|
||||
state = backAddProjectPage(state) ?? state;
|
||||
state = openNewDirectoryNamePage(state, HOST.serverId, "~/dev");
|
||||
|
||||
expect(currentAddProjectPage(state)).toMatchObject({
|
||||
kind: "new-directory-name",
|
||||
parentPath: "~/dev",
|
||||
name: "command-center",
|
||||
it("maps arrows and Enter to list commands", () => {
|
||||
expect(resolveAddProjectKey({ ...KEY, key: "ArrowDown" }, true)).toEqual({
|
||||
kind: "move",
|
||||
direction: "next",
|
||||
});
|
||||
});
|
||||
|
||||
it("restores the GitHub destination query and active parent when reopening a repository", () => {
|
||||
const repository = {
|
||||
id: "repo-1",
|
||||
nameWithOwner: "getpaseo/paseo",
|
||||
cloneUrl: "git@github.com:getpaseo/paseo.git",
|
||||
description: null,
|
||||
visibility: "public",
|
||||
updatedAt: null,
|
||||
};
|
||||
let state = openAddProjectFlow({ hosts: [HOST] });
|
||||
state = openGithubLocationPage(state, HOST.serverId, repository);
|
||||
state = setAddProjectPageInput(state, "~/dev");
|
||||
state = setAddProjectActiveIndex(state, 2);
|
||||
state = backAddProjectPage(state) ?? state;
|
||||
state = openGithubLocationPage(state, HOST.serverId, repository);
|
||||
|
||||
expect(currentAddProjectPage(state)).toMatchObject({
|
||||
kind: "github-location",
|
||||
query: "~/dev",
|
||||
activeIndex: 2,
|
||||
expect(resolveAddProjectKey({ ...KEY, key: "ArrowUp" }, true)).toEqual({
|
||||
kind: "move",
|
||||
direction: "previous",
|
||||
});
|
||||
expect(resolveAddProjectKey({ ...KEY, key: "Enter" }, true)).toEqual({ kind: "submit" });
|
||||
expect(resolveAddProjectKey({ ...KEY, key: "Enter", shiftKey: true }, true)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Add Project options", () => {
|
||||
it("hides every mutating method when the host lacks stable project identity", () => {
|
||||
const outdatedHost = { ...HOST, canAddProject: false };
|
||||
|
||||
expect(buildAddProjectMethods(outdatedHost)).toEqual([]);
|
||||
expect(addProjectMethodEmptyText(outdatedHost)).toBe("Update the host to use Add Project.");
|
||||
});
|
||||
|
||||
it("keeps host-upgrade methods discoverable while hiding local-only Browse", () => {
|
||||
expect(
|
||||
buildAddProjectMethods({
|
||||
...HOST,
|
||||
canBrowse: false,
|
||||
canCloneGithubRepositories: false,
|
||||
canSearchGithubRepositories: false,
|
||||
canCreateDirectory: false,
|
||||
}),
|
||||
).toEqual([
|
||||
{
|
||||
id: "directory-search",
|
||||
label: "Search for directory",
|
||||
description: "Find a directory on Local",
|
||||
},
|
||||
{
|
||||
id: "github",
|
||||
label: "Clone from GitHub",
|
||||
description: "Update this host to clone GitHub repositories",
|
||||
disabled: true,
|
||||
},
|
||||
{
|
||||
id: "new-directory",
|
||||
label: "New directory",
|
||||
description: "Update this host to create directories",
|
||||
disabled: true,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("offers manual URL and protocol-specific owner/repo clone choices", () => {
|
||||
expect(buildManualGithubRepositoryChoices("git@github.com:getpaseo/paseo.git")).toEqual([
|
||||
expect.objectContaining({
|
||||
@@ -163,46 +204,42 @@ describe("Add Project options", () => {
|
||||
expect(buildManualGithubRepositoryChoices("paseo")).toEqual([]);
|
||||
});
|
||||
|
||||
it("shows final clone paths while retaining parent paths as values", () => {
|
||||
expect(
|
||||
buildCloneLocationOptions({
|
||||
parents: ["~/dev", "~/workspace"],
|
||||
repositoryName: "paseo",
|
||||
existingPaths: ["~/workspace/paseo"],
|
||||
}),
|
||||
).toEqual([
|
||||
{
|
||||
id: "~/dev",
|
||||
path: "~/dev",
|
||||
displayPath: "~/dev/paseo",
|
||||
secondaryText: "Parent directory: ~/dev",
|
||||
disabled: false,
|
||||
},
|
||||
{
|
||||
id: "~/workspace",
|
||||
path: "~/workspace",
|
||||
displayPath: "~/workspace/paseo",
|
||||
secondaryText: "Already exists",
|
||||
disabled: true,
|
||||
},
|
||||
]);
|
||||
it("defaults the location to a folder that exists", () => {
|
||||
expect(defaultProjectLocation({ remembered: undefined, projectPaths: [] })).toBe("~");
|
||||
expect(defaultProjectLocation({ remembered: undefined, projectPaths: ["/code/app"] })).toBe(
|
||||
"/code",
|
||||
);
|
||||
expect(defaultProjectLocation({ remembered: "~/work", projectPaths: ["/code/app"] })).toBe(
|
||||
"~/work",
|
||||
);
|
||||
});
|
||||
|
||||
it("shows equivalent absolute-home and tilde destinations only once", () => {
|
||||
expect(
|
||||
buildCloneLocationOptions({
|
||||
parents: ["/Users/moboudra/dev", "~/dev"],
|
||||
repositoryName: "dotfiles",
|
||||
existingPaths: [],
|
||||
}),
|
||||
).toEqual([
|
||||
{
|
||||
id: "/Users/moboudra/dev",
|
||||
path: "/Users/moboudra/dev",
|
||||
displayPath: "/Users/moboudra/dev/dotfiles",
|
||||
secondaryText: "Parent directory: /Users/moboudra/dev",
|
||||
disabled: false,
|
||||
},
|
||||
]);
|
||||
it("keeps a drive or filesystem root when deriving and joining a location", () => {
|
||||
expect(parentDirectory("C:\\repo")).toBe("C:\\");
|
||||
expect(parentDirectory("/repo")).toBe("/");
|
||||
expect(parentDirectory("\\\\nas\\work")).toBeNull();
|
||||
expect(parentDirectory("\\\\nas\\work\\app")).toBe("\\\\nas\\work");
|
||||
expect(defaultProjectLocation({ remembered: undefined, projectPaths: ["\\\\nas\\work"] })).toBe(
|
||||
"~",
|
||||
);
|
||||
expect(parentDirectory("/code/app")).toBe("/code");
|
||||
expect(joinDirectoryPath("C:\\", "new-project")).toBe("C:\\new-project");
|
||||
expect(joinDirectoryPath("/", "new-project")).toBe("/new-project");
|
||||
expect(defaultProjectLocation({ remembered: undefined, projectPaths: ["C:\\repo"] })).toBe(
|
||||
"C:\\",
|
||||
);
|
||||
});
|
||||
|
||||
it("names the checkout the way the host does", () => {
|
||||
expect(checkoutName("acme/app.git")).toBe("app");
|
||||
expect(checkoutName("acme/app")).toBe("app");
|
||||
});
|
||||
|
||||
it("rejects folder names that are empty or leave the location", () => {
|
||||
expect(validateNewFolderName("")).toBe("Enter a folder name");
|
||||
expect(validateNewFolderName("..")).toBe("Enter a folder name");
|
||||
expect(validateNewFolderName("../invalid")).toBe("Use a name without slashes");
|
||||
expect(validateNewFolderName("C:repo")).toBe("Use a name without a drive letter");
|
||||
expect(validateNewFolderName(" acme-api ")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
export interface AddProjectHost {
|
||||
serverId: string;
|
||||
label: string;
|
||||
online: boolean;
|
||||
canAddProject: boolean;
|
||||
canBrowse: boolean;
|
||||
canCloneGithubRepositories: boolean;
|
||||
@@ -17,42 +18,42 @@ export interface GithubRepositoryChoice {
|
||||
updatedAt: string | null;
|
||||
}
|
||||
|
||||
interface PageState {
|
||||
activeIndex: number;
|
||||
error: string | null;
|
||||
}
|
||||
/** The three ways to add a project, in the order the segmented control and Mod+1/2/3 walk them. */
|
||||
export const ADD_PROJECT_TABS = ["existing", "clone", "new-folder"] as const;
|
||||
export type AddProjectTab = (typeof ADD_PROJECT_TABS)[number];
|
||||
|
||||
interface SearchPageState extends PageState {
|
||||
interface ListDraft {
|
||||
query: string;
|
||||
/**
|
||||
* The row the user picked, by id, so it stays picked when a search refresh reorders the rows.
|
||||
* `null`, or an id no longer listed, means the first row.
|
||||
*/
|
||||
selectedId: string | null;
|
||||
}
|
||||
|
||||
export type AddProjectPage =
|
||||
| ({ kind: "host" } & SearchPageState)
|
||||
| ({ kind: "method"; hostId: string; isSubmitting: boolean } & PageState)
|
||||
| ({ kind: "directory-search"; hostId: string; isSubmitting: boolean } & SearchPageState)
|
||||
| ({ kind: "github-search"; hostId: string } & SearchPageState)
|
||||
| ({
|
||||
kind: "github-location";
|
||||
hostId: string;
|
||||
repository: GithubRepositoryChoice;
|
||||
isSubmitting: boolean;
|
||||
} & SearchPageState)
|
||||
| ({ kind: "new-directory-parent"; hostId: string } & SearchPageState)
|
||||
| {
|
||||
kind: "new-directory-name";
|
||||
hostId: string;
|
||||
parentPath: string;
|
||||
name: string;
|
||||
activeIndex: number;
|
||||
error: string | null;
|
||||
isSubmitting: boolean;
|
||||
};
|
||||
/** `location: null` means the default parent directory for the current host. */
|
||||
interface CloneDraft extends ListDraft {
|
||||
location: string | null;
|
||||
}
|
||||
|
||||
interface NewFolderDraft {
|
||||
name: string;
|
||||
location: string | null;
|
||||
}
|
||||
|
||||
export type AddProjectSubmission =
|
||||
| { status: "idle" }
|
||||
| { status: "submitting"; tab: AddProjectTab }
|
||||
| { status: "failed"; tab: AddProjectTab; message: string };
|
||||
|
||||
export interface AddProjectFlowState {
|
||||
hosts: AddProjectHost[];
|
||||
pages: AddProjectPage[];
|
||||
newDirectoryNameDrafts: Record<string, string>;
|
||||
githubLocationDrafts: Record<string, { query: string; activeIndex: number }>;
|
||||
hostId: string | null;
|
||||
tab: AddProjectTab;
|
||||
existing: ListDraft;
|
||||
clone: CloneDraft;
|
||||
newFolder: NewFolderDraft;
|
||||
submission: AddProjectSubmission;
|
||||
}
|
||||
|
||||
export interface OpenAddProjectFlowInput {
|
||||
@@ -60,214 +61,144 @@ export interface OpenAddProjectFlowInput {
|
||||
preferredHostId?: string;
|
||||
}
|
||||
|
||||
type SearchPageKind = Extract<AddProjectPage, { query: string }>["kind"];
|
||||
const IDLE: AddProjectSubmission = { status: "idle" };
|
||||
|
||||
function searchPage<TKind extends SearchPageKind>(kind: TKind) {
|
||||
return { kind, query: "", activeIndex: 0, error: null } as const;
|
||||
}
|
||||
|
||||
function methodPage(hostId: string): AddProjectPage {
|
||||
return { kind: "method", hostId, activeIndex: 0, error: null, isSubmitting: false };
|
||||
function pickHostId(hosts: AddProjectHost[], preferredHostId?: string | null): string | null {
|
||||
const online = hosts.filter((host) => host.online);
|
||||
const preferred = preferredHostId
|
||||
? online.find((host) => host.serverId === preferredHostId)
|
||||
: undefined;
|
||||
return (preferred ?? online[0])?.serverId ?? null;
|
||||
}
|
||||
|
||||
export function openAddProjectFlow(input: OpenAddProjectFlowInput): AddProjectFlowState {
|
||||
const preferredHost = input.preferredHostId
|
||||
? input.hosts.find((host) => host.serverId === input.preferredHostId)
|
||||
: null;
|
||||
const onlyHost = input.hosts.length === 1 ? input.hosts[0] : null;
|
||||
const initialHost = preferredHost ?? onlyHost;
|
||||
|
||||
return {
|
||||
hosts: input.hosts,
|
||||
pages: initialHost ? [methodPage(initialHost.serverId)] : [searchPage("host")],
|
||||
newDirectoryNameDrafts: {},
|
||||
githubLocationDrafts: {},
|
||||
hostId: pickHostId(input.hosts, input.preferredHostId),
|
||||
tab: "existing",
|
||||
existing: { query: "", selectedId: null },
|
||||
clone: { query: "", selectedId: null, location: null },
|
||||
newFolder: { name: "", location: null },
|
||||
submission: IDLE,
|
||||
};
|
||||
}
|
||||
|
||||
export function currentAddProjectHost(state: AddProjectFlowState): AddProjectHost | null {
|
||||
return state.hosts.find((host) => host.serverId === state.hostId) ?? null;
|
||||
}
|
||||
|
||||
export function isAddProjectSubmitting(state: AddProjectFlowState): boolean {
|
||||
return state.submission.status === "submitting";
|
||||
}
|
||||
|
||||
/** The failure to show on the current tab, if the last submission there failed. */
|
||||
export function addProjectFailure(state: AddProjectFlowState): string | null {
|
||||
const { submission } = state;
|
||||
return submission.status === "failed" && submission.tab === state.tab ? submission.message : null;
|
||||
}
|
||||
|
||||
/** The hosts the user can switch to: every online host, plus the current one even while offline. */
|
||||
export function selectableAddProjectHosts(state: AddProjectFlowState): AddProjectHost[] {
|
||||
return state.hosts.filter((host) => host.online || host.serverId === state.hostId);
|
||||
}
|
||||
|
||||
/**
|
||||
* The chosen host stays chosen while it is offline, with its drafts, so a disconnect never sends
|
||||
* them to another host. A host is picked only when none is chosen or the chosen one was removed.
|
||||
*/
|
||||
export function applyAvailableAddProjectHosts(
|
||||
state: AddProjectFlowState,
|
||||
hosts: AddProjectHost[],
|
||||
preferredHostId?: string,
|
||||
): AddProjectFlowState {
|
||||
const current = currentAddProjectPage(state);
|
||||
if (state.pages.length !== 1 || current.kind !== "host") {
|
||||
return { ...state, hosts };
|
||||
}
|
||||
const preferredHost = preferredHostId
|
||||
? hosts.find((host) => host.serverId === preferredHostId)
|
||||
: null;
|
||||
const onlyHost = hosts.length === 1 ? hosts[0] : null;
|
||||
const initialHost = preferredHost ?? onlyHost;
|
||||
const stillListed = hosts.some((host) => host.serverId === state.hostId);
|
||||
if (stillListed) return { ...state, hosts };
|
||||
return withHost({ ...state, hosts }, pickHostId(hosts));
|
||||
}
|
||||
|
||||
function withHost(state: AddProjectFlowState, hostId: string | null): AddProjectFlowState {
|
||||
return {
|
||||
...state,
|
||||
hosts,
|
||||
pages: initialHost ? [methodPage(initialHost.serverId)] : state.pages,
|
||||
hostId,
|
||||
existing: { ...state.existing, selectedId: null },
|
||||
clone: { ...state.clone, selectedId: null, location: null },
|
||||
newFolder: { ...state.newFolder, location: null },
|
||||
submission: IDLE,
|
||||
};
|
||||
}
|
||||
|
||||
export function currentAddProjectPage(state: AddProjectFlowState): AddProjectPage {
|
||||
const page = state.pages[state.pages.length - 1];
|
||||
if (!page) {
|
||||
throw new Error("Add Project flow must always contain a page");
|
||||
export function selectAddProjectHost(
|
||||
state: AddProjectFlowState,
|
||||
hostId: string,
|
||||
): AddProjectFlowState {
|
||||
if (isAddProjectSubmitting(state) || hostId === state.hostId) return state;
|
||||
if (!state.hosts.some((host) => host.serverId === hostId && host.online)) return state;
|
||||
return withHost(state, hostId);
|
||||
}
|
||||
|
||||
export function selectAddProjectTab(
|
||||
state: AddProjectFlowState,
|
||||
tab: AddProjectTab,
|
||||
): AddProjectFlowState {
|
||||
if (isAddProjectSubmitting(state) || tab === state.tab) return state;
|
||||
return { ...state, tab, submission: IDLE };
|
||||
}
|
||||
|
||||
/** Sets the search text of the current list tab. */
|
||||
export function setAddProjectQuery(state: AddProjectFlowState, query: string): AddProjectFlowState {
|
||||
if (state.tab === "existing") {
|
||||
return { ...state, existing: { query, selectedId: null }, submission: IDLE };
|
||||
}
|
||||
return page;
|
||||
}
|
||||
|
||||
export function updateCurrentAddProjectPage(
|
||||
state: AddProjectFlowState,
|
||||
update: (page: AddProjectPage) => AddProjectPage,
|
||||
): AddProjectFlowState {
|
||||
const index = state.pages.length - 1;
|
||||
return {
|
||||
...state,
|
||||
pages: state.pages.map((page, pageIndex) => (pageIndex === index ? update(page) : page)),
|
||||
};
|
||||
}
|
||||
|
||||
export function pushAddProjectPage(
|
||||
state: AddProjectFlowState,
|
||||
page: AddProjectPage,
|
||||
): AddProjectFlowState {
|
||||
return { ...state, pages: [...state.pages, page] };
|
||||
}
|
||||
|
||||
export function backAddProjectPage(state: AddProjectFlowState): AddProjectFlowState | null {
|
||||
if (state.pages.length === 1) {
|
||||
return null;
|
||||
if (state.tab === "clone") {
|
||||
return { ...state, clone: { ...state.clone, query, selectedId: null }, submission: IDLE };
|
||||
}
|
||||
return { ...state, pages: state.pages.slice(0, -1) };
|
||||
return state;
|
||||
}
|
||||
|
||||
export function chooseAddProjectHost(
|
||||
export function setNewFolderName(state: AddProjectFlowState, name: string): AddProjectFlowState {
|
||||
return { ...state, newFolder: { ...state.newFolder, name }, submission: IDLE };
|
||||
}
|
||||
|
||||
/** Sets the parent directory of the current tab that creates a folder. */
|
||||
export function setAddProjectLocation(
|
||||
state: AddProjectFlowState,
|
||||
hostId: string,
|
||||
location: string,
|
||||
): AddProjectFlowState {
|
||||
return pushAddProjectPage(state, methodPage(hostId));
|
||||
if (state.tab === "clone") {
|
||||
return { ...state, clone: { ...state.clone, location }, submission: IDLE };
|
||||
}
|
||||
if (state.tab === "new-folder") {
|
||||
return { ...state, newFolder: { ...state.newFolder, location }, submission: IDLE };
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
||||
export function openDirectorySearchPage(
|
||||
export function selectAddProjectRow(
|
||||
state: AddProjectFlowState,
|
||||
hostId: string,
|
||||
selectedId: string,
|
||||
): AddProjectFlowState {
|
||||
return pushAddProjectPage(state, {
|
||||
...searchPage("directory-search"),
|
||||
hostId,
|
||||
isSubmitting: false,
|
||||
});
|
||||
// The row being added stays put until its submission ends; choosing another clears the
|
||||
// failure of the last one.
|
||||
if (isAddProjectSubmitting(state)) return state;
|
||||
if (state.tab === "existing") {
|
||||
return { ...state, existing: { ...state.existing, selectedId }, submission: IDLE };
|
||||
}
|
||||
if (state.tab === "clone") {
|
||||
return { ...state, clone: { ...state.clone, selectedId }, submission: IDLE };
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
||||
export function openGithubSearchPage(
|
||||
export function startAddProjectSubmission(state: AddProjectFlowState): AddProjectFlowState {
|
||||
if (isAddProjectSubmitting(state)) return state;
|
||||
return { ...state, submission: { status: "submitting", tab: state.tab } };
|
||||
}
|
||||
|
||||
export function failAddProjectSubmission(
|
||||
state: AddProjectFlowState,
|
||||
hostId: string,
|
||||
message: string,
|
||||
): AddProjectFlowState {
|
||||
return pushAddProjectPage(state, { ...searchPage("github-search"), hostId });
|
||||
}
|
||||
|
||||
export function openGithubLocationPage(
|
||||
state: AddProjectFlowState,
|
||||
hostId: string,
|
||||
repository: GithubRepositoryChoice,
|
||||
): AddProjectFlowState {
|
||||
const draft = state.githubLocationDrafts[githubLocationDraftKey(hostId, repository.id)];
|
||||
return pushAddProjectPage(state, {
|
||||
kind: "github-location",
|
||||
query: draft?.query ?? "",
|
||||
activeIndex: draft?.activeIndex ?? 0,
|
||||
error: null,
|
||||
hostId,
|
||||
repository,
|
||||
isSubmitting: false,
|
||||
});
|
||||
}
|
||||
|
||||
export function openNewDirectoryParentPage(
|
||||
state: AddProjectFlowState,
|
||||
hostId: string,
|
||||
): AddProjectFlowState {
|
||||
return pushAddProjectPage(state, { ...searchPage("new-directory-parent"), hostId });
|
||||
}
|
||||
|
||||
export function openNewDirectoryNamePage(
|
||||
state: AddProjectFlowState,
|
||||
hostId: string,
|
||||
parentPath: string,
|
||||
): AddProjectFlowState {
|
||||
const draftKey = newDirectoryDraftKey(hostId, parentPath);
|
||||
return pushAddProjectPage(state, {
|
||||
kind: "new-directory-name",
|
||||
hostId,
|
||||
parentPath,
|
||||
name: state.newDirectoryNameDrafts[draftKey] ?? "",
|
||||
activeIndex: 0,
|
||||
error: null,
|
||||
isSubmitting: false,
|
||||
});
|
||||
}
|
||||
|
||||
export function setAddProjectPageInput(
|
||||
state: AddProjectFlowState,
|
||||
value: string,
|
||||
): AddProjectFlowState {
|
||||
const page = currentAddProjectPage(state);
|
||||
const updated = updateCurrentAddProjectPage(state, (current) => {
|
||||
if (current.kind === "new-directory-name") {
|
||||
return { ...current, name: value, activeIndex: 0, error: null };
|
||||
}
|
||||
if (current.kind === "method") return current;
|
||||
return { ...current, query: value, activeIndex: 0, error: null };
|
||||
});
|
||||
if (page.kind !== "github-location") return updated;
|
||||
const draftKey = githubLocationDraftKey(page.hostId, page.repository.id);
|
||||
return {
|
||||
...updated,
|
||||
githubLocationDrafts: {
|
||||
...updated.githubLocationDrafts,
|
||||
[draftKey]: { query: value, activeIndex: 0 },
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function setNewDirectoryName(
|
||||
state: AddProjectFlowState,
|
||||
value: string,
|
||||
): AddProjectFlowState {
|
||||
const page = currentAddProjectPage(state);
|
||||
if (page.kind !== "new-directory-name") return state;
|
||||
const draftKey = newDirectoryDraftKey(page.hostId, page.parentPath);
|
||||
const updated = setAddProjectPageInput(state, value);
|
||||
return {
|
||||
...updated,
|
||||
newDirectoryNameDrafts: {
|
||||
...updated.newDirectoryNameDrafts,
|
||||
[draftKey]: value,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function newDirectoryDraftKey(hostId: string, parentPath: string): string {
|
||||
return `${hostId}\u0000${parentPath}`;
|
||||
}
|
||||
|
||||
function githubLocationDraftKey(hostId: string, repositoryId: string): string {
|
||||
return `${hostId}\u0000${repositoryId}`;
|
||||
}
|
||||
|
||||
export function setAddProjectActiveIndex(
|
||||
state: AddProjectFlowState,
|
||||
activeIndex: number,
|
||||
): AddProjectFlowState {
|
||||
const page = currentAddProjectPage(state);
|
||||
const updated = updateCurrentAddProjectPage(state, (current) => ({ ...current, activeIndex }));
|
||||
if (page.kind !== "github-location") return updated;
|
||||
const draftKey = githubLocationDraftKey(page.hostId, page.repository.id);
|
||||
return {
|
||||
...updated,
|
||||
githubLocationDrafts: {
|
||||
...updated.githubLocationDrafts,
|
||||
[draftKey]: { query: page.query, activeIndex },
|
||||
},
|
||||
};
|
||||
if (state.submission.status !== "submitting") return state;
|
||||
return { ...state, submission: { status: "failed", tab: state.submission.tab, message } };
|
||||
}
|
||||
|
||||
export function moveAddProjectActiveIndex(
|
||||
@@ -283,16 +214,37 @@ export function moveAddProjectActiveIndex(
|
||||
return next;
|
||||
}
|
||||
|
||||
export function moveAddProjectSelection(
|
||||
activeIndex: number,
|
||||
selectable: readonly boolean[],
|
||||
direction: "next" | "previous",
|
||||
): number {
|
||||
if (!selectable.some(Boolean)) return 0;
|
||||
let next = activeIndex;
|
||||
for (let count = 0; count < selectable.length; count += 1) {
|
||||
next = moveAddProjectActiveIndex(next, selectable.length, direction);
|
||||
if (selectable[next]) return next;
|
||||
}
|
||||
return activeIndex;
|
||||
export interface AddProjectKeyInput {
|
||||
key: string;
|
||||
metaKey: boolean;
|
||||
ctrlKey: boolean;
|
||||
altKey: boolean;
|
||||
shiftKey: boolean;
|
||||
}
|
||||
|
||||
export type AddProjectKeyCommand =
|
||||
| { kind: "tab"; tab: AddProjectTab }
|
||||
| { kind: "move"; direction: "next" | "previous" }
|
||||
| { kind: "submit" };
|
||||
|
||||
/** Keys the sheet claims besides Escape. Digits only act with the platform's Mod key. */
|
||||
export const ADD_PROJECT_KEYS = ["Enter", "ArrowUp", "ArrowDown", "1", "2", "3"] as const;
|
||||
|
||||
export function resolveAddProjectKey(
|
||||
input: AddProjectKeyInput,
|
||||
isMac: boolean,
|
||||
): AddProjectKeyCommand | null {
|
||||
const modOnly =
|
||||
(isMac ? input.metaKey && !input.ctrlKey : input.ctrlKey && !input.metaKey) &&
|
||||
!input.altKey &&
|
||||
!input.shiftKey;
|
||||
const plain = !input.metaKey && !input.ctrlKey && !input.altKey && !input.shiftKey;
|
||||
const tabIndex = ["1", "2", "3"].indexOf(input.key);
|
||||
const tab = ADD_PROJECT_TABS[tabIndex];
|
||||
if (tab && modOnly) return { kind: "tab", tab };
|
||||
if (!plain) return null;
|
||||
if (input.key === "ArrowDown") return { kind: "move", direction: "next" };
|
||||
if (input.key === "ArrowUp") return { kind: "move", direction: "previous" };
|
||||
if (input.key === "Enter") return { kind: "submit" };
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
import { useMemo } from "react";
|
||||
import { View } from "react-native";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import { Field, FormTextInput } from "@/components/ui/form-field";
|
||||
import { isWeb } from "@/constants/platform";
|
||||
import type { AddProjectActions } from "./use-add-project-actions";
|
||||
import type { AddProjectFlowState, AddProjectHost } from "./model";
|
||||
import { LocationField } from "./location-field";
|
||||
import { joinDirectoryPath, validateNewFolderName } from "./options";
|
||||
import type { AddProjectTabView } from "./tab-view";
|
||||
|
||||
export interface NewFolderTabView extends AddProjectTabView {
|
||||
location: string;
|
||||
destination: string;
|
||||
/** Why the typed name cannot be a folder; null while empty or valid. */
|
||||
nameError: string | null;
|
||||
}
|
||||
|
||||
export function useNewFolderTab(input: {
|
||||
state: AddProjectFlowState;
|
||||
host: AddProjectHost | null;
|
||||
defaultLocation: string;
|
||||
actions: AddProjectActions;
|
||||
}): NewFolderTabView {
|
||||
const { state, host, defaultLocation, actions } = input;
|
||||
const { name } = state.newFolder;
|
||||
const location = state.newFolder.location ?? defaultLocation;
|
||||
const trimmed = name.trim();
|
||||
const nameError = trimmed ? validateNewFolderName(name) : null;
|
||||
// Preview and create only a name that can be created, so the field never shows a path that
|
||||
// escapes the location.
|
||||
const previewName = trimmed && !nameError ? trimmed : null;
|
||||
const canCreate = host?.canCreateDirectory === true;
|
||||
|
||||
return useMemo<NewFolderTabView>(
|
||||
() => ({
|
||||
rows: [],
|
||||
activeIndex: 0,
|
||||
notice: null,
|
||||
location,
|
||||
destination: previewName ? joinDirectoryPath(location, previewName) : location,
|
||||
unavailable: canCreate ? null : "Update the host to create folders",
|
||||
nameError,
|
||||
primary: {
|
||||
label: "Create project",
|
||||
submit: canCreate && previewName ? () => actions.createFolder(name, location) : null,
|
||||
},
|
||||
}),
|
||||
[actions, canCreate, location, name, nameError, previewName],
|
||||
);
|
||||
}
|
||||
|
||||
export function NewFolderTab({
|
||||
view,
|
||||
name,
|
||||
hostId,
|
||||
recommendedPaths,
|
||||
disabled,
|
||||
autoFocus,
|
||||
onNameChange,
|
||||
onLocationChange,
|
||||
}: {
|
||||
view: NewFolderTabView;
|
||||
name: string;
|
||||
hostId: string | null;
|
||||
recommendedPaths: string[];
|
||||
disabled: boolean;
|
||||
/** Focus the field on mount; only with a hardware keyboard, so touch keeps the list in view. */
|
||||
autoFocus: boolean;
|
||||
onNameChange: (name: string) => void;
|
||||
onLocationChange: (location: string) => void;
|
||||
}) {
|
||||
const editable = !disabled && !view.unavailable;
|
||||
return (
|
||||
<View style={styles.body}>
|
||||
<Field
|
||||
label="Name"
|
||||
hint={view.unavailable ?? undefined}
|
||||
error={view.nameError}
|
||||
testID="add-project-flow-name-field"
|
||||
>
|
||||
<FormTextInput
|
||||
initialValue={name}
|
||||
onChangeText={onNameChange}
|
||||
onSubmitEditing={isWeb ? undefined : (view.primary.submit ?? undefined)}
|
||||
placeholder="my-project"
|
||||
accessibilityLabel="Folder name"
|
||||
autoFocus={autoFocus}
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
returnKeyType="go"
|
||||
editable={editable}
|
||||
invalid={Boolean(view.nameError)}
|
||||
testID="add-project-flow-input"
|
||||
/>
|
||||
</Field>
|
||||
<LocationField
|
||||
hostId={hostId}
|
||||
location={view.location}
|
||||
destination={view.destination}
|
||||
recommendedPaths={recommendedPaths}
|
||||
onChange={onLocationChange}
|
||||
disabled={!editable}
|
||||
testID="add-project-flow-location"
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
body: {
|
||||
gap: theme.spacing[4],
|
||||
},
|
||||
}));
|
||||
@@ -3,83 +3,7 @@ import {
|
||||
parseGitHubRemoteUrl,
|
||||
parseGitRemoteLocation,
|
||||
} from "@getpaseo/protocol/git-remote";
|
||||
import { shortenPath } from "@/utils/shorten-path";
|
||||
import type { AddProjectHost, GithubRepositoryChoice } from "./model";
|
||||
|
||||
export type AddProjectMethodId = "directory-search" | "browse" | "github" | "new-directory";
|
||||
|
||||
export interface AddProjectMethodOption {
|
||||
id: AddProjectMethodId;
|
||||
label: string;
|
||||
description: string;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
export interface AddProjectPathOption {
|
||||
id: string;
|
||||
path: string;
|
||||
displayPath: string;
|
||||
secondaryText: string | null;
|
||||
disabled: boolean;
|
||||
}
|
||||
|
||||
export function filterAddProjectHosts(hosts: AddProjectHost[], query: string): AddProjectHost[] {
|
||||
const normalized = query.trim().toLowerCase();
|
||||
if (!normalized) return hosts;
|
||||
return hosts.filter(
|
||||
(host) =>
|
||||
host.label.toLowerCase().includes(normalized) ||
|
||||
host.serverId.toLowerCase().includes(normalized),
|
||||
);
|
||||
}
|
||||
|
||||
export function buildAddProjectMethods(host: AddProjectHost): AddProjectMethodOption[] {
|
||||
if (!host.canAddProject) return [];
|
||||
const options: AddProjectMethodOption[] = [];
|
||||
options.push({
|
||||
id: "directory-search",
|
||||
label: "Search for directory",
|
||||
description: `Find a directory on ${host.label}`,
|
||||
});
|
||||
if (host.canBrowse) {
|
||||
options.push({
|
||||
id: "browse",
|
||||
label: "Browse",
|
||||
description: "Choose or create a directory in Finder",
|
||||
});
|
||||
}
|
||||
options.push({
|
||||
id: "github",
|
||||
label: "Clone from GitHub",
|
||||
description: githubMethodDescription(host),
|
||||
disabled: !host.canCloneGithubRepositories,
|
||||
});
|
||||
options.push({
|
||||
id: "new-directory",
|
||||
label: "New directory",
|
||||
description: host.canCreateDirectory
|
||||
? `Create an empty directory on ${host.label}`
|
||||
: "Update this host to create directories",
|
||||
disabled: !host.canCreateDirectory,
|
||||
});
|
||||
return options;
|
||||
}
|
||||
|
||||
export function addProjectMethodEmptyText(host: AddProjectHost | null): string {
|
||||
return host?.canAddProject === false
|
||||
? "Update the host to use Add Project."
|
||||
: "No matching options";
|
||||
}
|
||||
|
||||
function githubMethodDescription(host: AddProjectHost): string {
|
||||
if (!host.canCloneGithubRepositories) {
|
||||
return "Update this host to clone GitHub repositories";
|
||||
}
|
||||
if (host.canSearchGithubRepositories) {
|
||||
return "Search projects available to your GitHub account";
|
||||
}
|
||||
return "Enter a GitHub URL or owner/repo";
|
||||
}
|
||||
import type { GithubRepositoryChoice } from "./model";
|
||||
|
||||
export function pathBaseName(path: string): string {
|
||||
const trimmed = path.replace(/[\\/]+$/, "");
|
||||
@@ -87,6 +11,9 @@ export function pathBaseName(path: string): string {
|
||||
return parts[parts.length - 1] ?? trimmed;
|
||||
}
|
||||
|
||||
/** Starts the id of every choice built from what the user typed. */
|
||||
export const MANUAL_CHOICE_PREFIX = "manual:";
|
||||
|
||||
export function buildManualGithubRepositoryChoices(query: string): GithubRepositoryChoice[] {
|
||||
const repo = query.trim();
|
||||
if (!repo) return [];
|
||||
@@ -97,7 +24,7 @@ export function buildManualGithubRepositoryChoices(query: string): GithubReposit
|
||||
const remoteName = location ? pathBaseName(location.path).replace(/\.git$/u, "") : repo;
|
||||
return [
|
||||
{
|
||||
id: `manual:${repo}`,
|
||||
id: `${MANUAL_CHOICE_PREFIX}${repo}`,
|
||||
nameWithOwner: identity?.repo ?? remoteName,
|
||||
cloneUrl: repo,
|
||||
description: "Clone this repository URL",
|
||||
@@ -110,7 +37,7 @@ export function buildManualGithubRepositoryChoices(query: string): GithubReposit
|
||||
if (!shorthand) return [];
|
||||
const nameWithOwner = `${shorthand[1]}/${shorthand[2]}`;
|
||||
return (["https", "ssh"] as const).map((cloneProtocol) => ({
|
||||
id: `manual:${cloneProtocol}:${nameWithOwner}`,
|
||||
id: `${MANUAL_CHOICE_PREFIX}${cloneProtocol}:${nameWithOwner}`,
|
||||
nameWithOwner,
|
||||
cloneUrl: nameWithOwner,
|
||||
cloneProtocol,
|
||||
@@ -119,18 +46,21 @@ export function buildManualGithubRepositoryChoices(query: string): GithubReposit
|
||||
}));
|
||||
}
|
||||
|
||||
/** The folder that holds `path`. A root keeps its separator: `C:\repo` gives `C:\`, not `C:`. */
|
||||
export function parentDirectory(path: string): string | null {
|
||||
const trimmed = path.replace(/[\\/]+$/, "");
|
||||
// A share root (\\server\share) has no parent folder; `\\server` alone is not a directory.
|
||||
if (/^[\\/]{2}[^\\/]+[\\/][^\\/]+$/u.test(trimmed)) return null;
|
||||
const index = Math.max(trimmed.lastIndexOf("/"), trimmed.lastIndexOf("\\"));
|
||||
if (index < 0) return null;
|
||||
if (index === 0) return trimmed.slice(0, 1);
|
||||
return trimmed.slice(0, index);
|
||||
const parent = trimmed.slice(0, index);
|
||||
const isRoot = parent === "" || /^[A-Za-z]:$/u.test(parent);
|
||||
return isRoot ? trimmed.slice(0, index + 1) : parent;
|
||||
}
|
||||
|
||||
export function joinDirectoryPath(parent: string, name: string): string {
|
||||
const trimmedParent = parent.replace(/[\\/]+$/, "");
|
||||
const separator = trimmedParent.includes("\\") && !trimmedParent.includes("/") ? "\\" : "/";
|
||||
return `${trimmedParent}${separator}${name}`;
|
||||
const separator = parent.includes("\\") && !parent.includes("/") ? "\\" : "/";
|
||||
return `${parent.replace(/[\\/]+$/, "")}${separator}${name}`;
|
||||
}
|
||||
|
||||
export function buildSuggestedParentDirectories(projectPaths: string[]): string[] {
|
||||
@@ -149,34 +79,31 @@ export function buildSuggestedParentDirectories(projectPaths: string[]): string[
|
||||
return [...new Set(values)];
|
||||
}
|
||||
|
||||
export function buildCloneLocationOptions(input: {
|
||||
parents: string[];
|
||||
repositoryName: string;
|
||||
existingPaths: string[];
|
||||
}): AddProjectPathOption[] {
|
||||
const existing = new Set(input.existingPaths.map(pathIdentity));
|
||||
const seen = new Set<string>();
|
||||
return input.parents.flatMap((parent) => {
|
||||
const path = joinDirectoryPath(parent, input.repositoryName);
|
||||
const identity = pathIdentity(path);
|
||||
if (seen.has(identity)) return [];
|
||||
seen.add(identity);
|
||||
const pathExists = existing.has(identity);
|
||||
return [
|
||||
{
|
||||
id: parent,
|
||||
path: parent,
|
||||
displayPath: path,
|
||||
secondaryText: pathExists ? "Already exists" : `Parent directory: ${parent}`,
|
||||
disabled: pathExists,
|
||||
},
|
||||
];
|
||||
});
|
||||
/**
|
||||
* Where a new folder or clone goes when the user has not picked a location on this host: the last
|
||||
* one used, else the parent of a recent project, else home. Only folders known to exist qualify;
|
||||
* guesses like `~/dev` stay suggestions in the Location picker.
|
||||
*/
|
||||
export function defaultProjectLocation(input: {
|
||||
remembered: string | undefined;
|
||||
projectPaths: string[];
|
||||
}): string {
|
||||
const projectParent = input.projectPaths
|
||||
.map(parentDirectory)
|
||||
.find((parent): parent is string => parent !== null);
|
||||
return input.remembered ?? projectParent ?? "~";
|
||||
}
|
||||
|
||||
function pathIdentity(path: string): string {
|
||||
const normalized = shortenPath(path.trim()).replace(/\\/g, "/").replace(/\/+$/u, "");
|
||||
return /^[A-Za-z]:\//u.test(normalized) || normalized.startsWith("//")
|
||||
? normalized.toLowerCase()
|
||||
: normalized;
|
||||
/** The folder a clone of `nameWithOwner` checks out into; the host drops a trailing `.git`. */
|
||||
export function checkoutName(nameWithOwner: string): string {
|
||||
return pathBaseName(nameWithOwner).replace(/\.git$/u, "");
|
||||
}
|
||||
|
||||
export function validateNewFolderName(name: string): string | null {
|
||||
const trimmed = name.trim();
|
||||
if (!trimmed || trimmed === "." || trimmed === "..") return "Enter a folder name";
|
||||
if (/[\\/]/.test(trimmed)) return "Use a name without slashes";
|
||||
// The host rejects a drive prefix on every platform.
|
||||
if (/^[A-Za-z]:/u.test(trimmed)) return "Use a name without a drive letter";
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
/** The result list's test ID, which the web Enter check also uses to recognise a focused row. */
|
||||
export const RESULTS_TEST_ID = "add-project-flow-results";
|
||||
@@ -0,0 +1,243 @@
|
||||
import { useCallback, useMemo, useRef, type ComponentType, type RefObject } from "react";
|
||||
import { Check } from "lucide-react-native";
|
||||
import { Text, View, type ScrollView as NativeScrollView } from "react-native";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { LoadingSpinner } from "@/components/ui/loading-spinner";
|
||||
import { PressHighlight } from "@/components/ui/press-highlight";
|
||||
import { ScrollView } from "@/components/ui/scroll-view";
|
||||
import { useRevealActiveItem } from "@/components/ui/scroll-reveal";
|
||||
import { Shortcut } from "@/components/ui/shortcut";
|
||||
import { useHardwareKeyboardPresent } from "@/keyboard";
|
||||
import { settingsStyles } from "@/styles/settings";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
|
||||
type RowIcon = ComponentType<{ size?: number; color?: string }>;
|
||||
|
||||
export interface ResultRow {
|
||||
id: string;
|
||||
title: string;
|
||||
subtitle: string | null;
|
||||
icon: RowIcon;
|
||||
testID: string;
|
||||
}
|
||||
|
||||
/** What the list says when it has no rows to show. */
|
||||
export type ResultListNotice =
|
||||
| { kind: "pending"; text: string }
|
||||
| { kind: "empty"; text: string }
|
||||
| { kind: "error"; text: string };
|
||||
|
||||
interface ResultListProps {
|
||||
rows: ResultRow[];
|
||||
activeIndex: number;
|
||||
/** Shown in place of the rows when there are none, or above them for an error. */
|
||||
notice: ResultListNotice | null;
|
||||
onSelect: (index: number) => void;
|
||||
disabled?: boolean;
|
||||
testID: string;
|
||||
}
|
||||
|
||||
const ENTER_KEYS = ["Enter"];
|
||||
// Fixed line heights make a two-line row the same height on every platform.
|
||||
const TITLE_LINE_HEIGHT = 18;
|
||||
const SUBTITLE_LINE_HEIGHT = 16;
|
||||
|
||||
function RowGlyph({ icon: Icon, size, color }: { icon: RowIcon; size: number; color?: string }) {
|
||||
return <Icon size={size} color={color} />;
|
||||
}
|
||||
const MutedRowGlyph = withUnistyles(RowGlyph, (theme: Theme) => ({
|
||||
color: theme.colors.foregroundMuted,
|
||||
}));
|
||||
const AccentCheck = withUnistyles(Check, (theme: Theme) => ({ color: theme.colors.accent }));
|
||||
const ThemedSpinner = withUnistyles(LoadingSpinner, (theme: Theme) => ({
|
||||
color: theme.colors.foregroundMuted,
|
||||
}));
|
||||
|
||||
/** Enter commits the active row when there is a keyboard; on touch, a check marks the choice. */
|
||||
function ActiveMark() {
|
||||
const keyboardPresent = useHardwareKeyboardPresent();
|
||||
return keyboardPresent ? <Shortcut keys={ENTER_KEYS} /> : <AccentCheck size={16} />;
|
||||
}
|
||||
|
||||
function ResultRowView({
|
||||
row,
|
||||
index,
|
||||
active,
|
||||
disabled,
|
||||
activeItemRef,
|
||||
onActiveLayout,
|
||||
onSelect,
|
||||
}: {
|
||||
row: ResultRow;
|
||||
index: number;
|
||||
active: boolean;
|
||||
disabled: boolean;
|
||||
activeItemRef: RefObject<View | null>;
|
||||
onActiveLayout: () => void;
|
||||
onSelect: (index: number) => void;
|
||||
}) {
|
||||
const handlePress = useCallback(() => onSelect(index), [index, onSelect]);
|
||||
const style = useMemo(
|
||||
() => [
|
||||
settingsStyles.row,
|
||||
styles.row,
|
||||
index > 0 && settingsStyles.rowBorder,
|
||||
active && styles.rowActive,
|
||||
],
|
||||
[active, index],
|
||||
);
|
||||
const accessibilityState = useMemo(() => ({ selected: active, disabled }), [active, disabled]);
|
||||
return (
|
||||
<PressHighlight
|
||||
ref={active ? activeItemRef : undefined}
|
||||
onLayout={active ? onActiveLayout : undefined}
|
||||
accessibilityRole="button"
|
||||
accessibilityState={accessibilityState}
|
||||
disabled={disabled}
|
||||
onPress={handlePress}
|
||||
// Tabbing to a row picks it, so Enter commits the row that has focus.
|
||||
onFocus={handlePress}
|
||||
style={style}
|
||||
highlightStyle={styles.rowActive}
|
||||
testID={row.testID}
|
||||
>
|
||||
<View style={styles.iconSlot}>
|
||||
<MutedRowGlyph icon={row.icon} size={16} />
|
||||
</View>
|
||||
<View style={styles.rowText}>
|
||||
<Text style={[settingsStyles.rowTitle, styles.rowTitle]} numberOfLines={1}>
|
||||
{row.title}
|
||||
</Text>
|
||||
{row.subtitle ? (
|
||||
<Text style={styles.rowSubtitle} numberOfLines={1}>
|
||||
{row.subtitle}
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
{/* Reserved on every row so the active row's mark never shifts its text. */}
|
||||
<View style={styles.trailingSlot}>{active ? <ActiveMark /> : null}</View>
|
||||
</PressHighlight>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* A card of choices with one active row. Arrow keys, taps, and keyboard focus move the active
|
||||
* row; the sheet's primary action commits it. The list keeps the active row scrolled into view.
|
||||
*/
|
||||
export function ResultList({
|
||||
rows,
|
||||
activeIndex,
|
||||
notice,
|
||||
onSelect,
|
||||
disabled = false,
|
||||
testID,
|
||||
}: ResultListProps) {
|
||||
const scrollRef = useRef<NativeScrollView>(null);
|
||||
const listKey = useMemo(() => rows.map((row) => row.id).join("\u0000"), [rows]);
|
||||
const { activeItemRef, contentRef, onItemLayout, onViewportLayout, onScroll } =
|
||||
useRevealActiveItem({ activeIndex, listKey, scrollRef });
|
||||
const showNotice = notice && (rows.length === 0 || notice.kind === "error");
|
||||
|
||||
return (
|
||||
<View style={styles.frame}>
|
||||
{showNotice ? (
|
||||
<View style={[settingsStyles.card, styles.noticeCard]} testID={`${testID}-notice`}>
|
||||
{notice.kind === "pending" ? <ThemedSpinner size={14} /> : null}
|
||||
<Text
|
||||
style={notice.kind === "error" ? styles.noticeError : styles.noticeText}
|
||||
numberOfLines={2}
|
||||
>
|
||||
{notice.text}
|
||||
</Text>
|
||||
</View>
|
||||
) : null}
|
||||
{rows.length > 0 ? (
|
||||
<View style={[settingsStyles.card, styles.listCard]}>
|
||||
<ScrollView
|
||||
ref={scrollRef}
|
||||
keyboardShouldPersistTaps="always"
|
||||
onLayout={onViewportLayout}
|
||||
onScroll={onScroll}
|
||||
scrollEventThrottle={16}
|
||||
showsVerticalScrollIndicator={false}
|
||||
testID={testID}
|
||||
>
|
||||
<View ref={contentRef} collapsable={false}>
|
||||
{rows.map((row, index) => (
|
||||
<ResultRowView
|
||||
key={row.id}
|
||||
row={row}
|
||||
index={index}
|
||||
active={index === activeIndex}
|
||||
disabled={disabled}
|
||||
activeItemRef={activeItemRef}
|
||||
onActiveLayout={onItemLayout}
|
||||
onSelect={onSelect}
|
||||
/>
|
||||
))}
|
||||
</View>
|
||||
</ScrollView>
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
frame: {
|
||||
flex: 1,
|
||||
minHeight: 0,
|
||||
gap: theme.spacing[3],
|
||||
},
|
||||
listCard: {
|
||||
flexShrink: 1,
|
||||
minHeight: 0,
|
||||
},
|
||||
// Every row is as tall as a two-line row, so rows without a subtitle do not break the rhythm.
|
||||
row: {
|
||||
minHeight: theme.spacing[3] * 2 + TITLE_LINE_HEIGHT + SUBTITLE_LINE_HEIGHT,
|
||||
paddingVertical: theme.spacing[3],
|
||||
justifyContent: "flex-start",
|
||||
gap: theme.spacing[3],
|
||||
},
|
||||
rowActive: {
|
||||
backgroundColor: theme.colors.surface2,
|
||||
},
|
||||
iconSlot: {
|
||||
width: 16,
|
||||
alignItems: "center",
|
||||
},
|
||||
rowText: {
|
||||
flex: 1,
|
||||
minWidth: 0,
|
||||
},
|
||||
rowTitle: {
|
||||
lineHeight: TITLE_LINE_HEIGHT,
|
||||
},
|
||||
rowSubtitle: {
|
||||
color: theme.colors.foregroundMuted,
|
||||
fontSize: theme.fontSize.sm,
|
||||
lineHeight: SUBTITLE_LINE_HEIGHT,
|
||||
},
|
||||
trailingSlot: {
|
||||
minWidth: theme.spacing[6],
|
||||
alignItems: "flex-end",
|
||||
},
|
||||
noticeCard: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[2],
|
||||
paddingHorizontal: theme.spacing[4],
|
||||
paddingVertical: theme.spacing[4],
|
||||
},
|
||||
noticeText: {
|
||||
flex: 1,
|
||||
color: theme.colors.foregroundMuted,
|
||||
fontSize: theme.fontSize.base,
|
||||
},
|
||||
noticeError: {
|
||||
flex: 1,
|
||||
color: theme.colors.statusDanger,
|
||||
fontSize: theme.fontSize.base,
|
||||
},
|
||||
}));
|
||||
@@ -0,0 +1,70 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { resolveSearch, type SearchAnswer } from "./search-result";
|
||||
|
||||
const EMPTY: string[] = [];
|
||||
|
||||
function answer(overrides: Partial<SearchAnswer<string>> = {}): SearchAnswer<string> {
|
||||
return { hostId: "host-1", query: "app", items: ["/code/app"], error: null, ...overrides };
|
||||
}
|
||||
|
||||
function resolve(overrides: Partial<Parameters<typeof resolveSearch<string>>[0]> = {}) {
|
||||
return resolveSearch<string>({
|
||||
enabled: true,
|
||||
hostId: "host-1",
|
||||
query: "app",
|
||||
debouncedQuery: "app",
|
||||
data: answer(),
|
||||
failed: null,
|
||||
empty: EMPTY,
|
||||
...overrides,
|
||||
});
|
||||
}
|
||||
|
||||
describe("resolveSearch", () => {
|
||||
it("shows the answer for the current query", () => {
|
||||
expect(resolve()).toEqual({ items: ["/code/app"], pending: false, error: null });
|
||||
});
|
||||
|
||||
it("keeps the last items while the next query is pending", () => {
|
||||
expect(resolve({ query: "apps", debouncedQuery: "apps" })).toEqual({
|
||||
items: ["/code/app"],
|
||||
pending: true,
|
||||
error: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("never shows another host's answer, even for the same query", () => {
|
||||
expect(resolve({ hostId: "host-2" })).toEqual({ items: [], pending: true, error: null });
|
||||
});
|
||||
|
||||
it("drops the last query's error while the next query is pending", () => {
|
||||
const failedAnswer = answer({ items: [], error: "Rate limited" });
|
||||
expect(resolve({ data: failedAnswer })).toEqual({
|
||||
items: [],
|
||||
pending: false,
|
||||
error: "Rate limited",
|
||||
});
|
||||
expect(resolve({ data: failedAnswer, query: "apps" })).toEqual({
|
||||
items: [],
|
||||
pending: true,
|
||||
error: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("shows a failed request only once the user stops typing", () => {
|
||||
expect(resolve({ data: undefined, failed: "Unable to search" })).toEqual({
|
||||
items: [],
|
||||
pending: false,
|
||||
error: "Unable to search",
|
||||
});
|
||||
expect(resolve({ data: undefined, failed: "Unable to search", query: "apps" })).toEqual({
|
||||
items: [],
|
||||
pending: true,
|
||||
error: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("is idle when disabled", () => {
|
||||
expect(resolve({ enabled: false })).toEqual({ items: [], pending: false, error: null });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,47 @@
|
||||
/**
|
||||
* What a search shows while the user types. `items` keep the last results until the current
|
||||
* query's results arrive, so rows do not flash away on every keystroke.
|
||||
*/
|
||||
export interface SearchResult<T> {
|
||||
items: T[];
|
||||
/** Results for the current query have not arrived yet. */
|
||||
pending: boolean;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
/** One answer from the host: what it found for `query`, or why it could not search. */
|
||||
export interface SearchAnswer<T> {
|
||||
hostId: string | null;
|
||||
query: string;
|
||||
items: T[];
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Decides what to show for `query` on `hostId`. An answer from another host never shows. While
|
||||
* the current query is pending the last items stay, but an old error does not.
|
||||
*/
|
||||
export function resolveSearch<T>(input: {
|
||||
enabled: boolean;
|
||||
hostId: string | null;
|
||||
/** What the user typed. */
|
||||
query: string;
|
||||
/** The query the last request was sent for; it trails `query` while the user types. */
|
||||
debouncedQuery: string;
|
||||
/** The latest answer, which may be for an earlier query or another host. */
|
||||
data: SearchAnswer<T> | undefined;
|
||||
/** Why the request for `debouncedQuery` failed, if it did. */
|
||||
failed: string | null;
|
||||
empty: T[];
|
||||
}): SearchResult<T> {
|
||||
const { enabled, hostId, query, debouncedQuery, data, failed, empty } = input;
|
||||
if (!enabled) return { items: empty, pending: false, error: null };
|
||||
if (failed) {
|
||||
return query === debouncedQuery
|
||||
? { items: empty, pending: false, error: failed }
|
||||
: { items: empty, pending: true, error: null };
|
||||
}
|
||||
const answer = data?.hostId === hostId ? data : undefined;
|
||||
if (answer?.query === query) return { items: answer.items, pending: false, error: answer.error };
|
||||
return { items: answer && !answer.error ? answer.items : empty, pending: true, error: null };
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
import { useMemo } from "react";
|
||||
import { useFetchQuery } from "@/data/query";
|
||||
import { useDebouncedValue } from "@/hooks/use-debounced-value";
|
||||
import { useHostRuntimeClient } from "@/runtime/host-runtime";
|
||||
import type { GithubRepositoryChoice } from "./model";
|
||||
import { resolveSearch, type SearchResult } from "./search-result";
|
||||
|
||||
export type { SearchResult } from "./search-result";
|
||||
|
||||
const SEARCH_DEBOUNCE_MS = 250;
|
||||
const EMPTY_PATHS: string[] = [];
|
||||
const EMPTY_REPOSITORIES: GithubRepositoryChoice[] = [];
|
||||
|
||||
/** Directories on the host matching `query`, debounced while the user types. */
|
||||
export function useDirectorySearch(input: {
|
||||
hostId: string | null;
|
||||
query: string;
|
||||
enabled: boolean;
|
||||
}): SearchResult<string> {
|
||||
const { hostId } = input;
|
||||
const client = useHostRuntimeClient(hostId ?? "");
|
||||
const debouncedQuery = useDebouncedValue(input.query, SEARCH_DEBOUNCE_MS);
|
||||
const enabled = Boolean(client && input.enabled);
|
||||
const search = useFetchQuery({
|
||||
queryKey: ["add-project-flow-directories", hostId, debouncedQuery],
|
||||
queryFn: async () => {
|
||||
if (!client) throw new Error("Host is unavailable");
|
||||
const payload = await client.getDirectorySuggestions({
|
||||
query: debouncedQuery,
|
||||
includeDirectories: true,
|
||||
includeFiles: false,
|
||||
limit: 30,
|
||||
});
|
||||
const items =
|
||||
payload.entries?.flatMap((entry) => (entry.kind === "directory" ? [entry.path] : [])) ?? [];
|
||||
return { hostId, query: debouncedQuery, items, error: payload.error ?? null };
|
||||
},
|
||||
enabled,
|
||||
dataShape: "list",
|
||||
retry: false,
|
||||
staleTimeMs: 15_000,
|
||||
});
|
||||
const failed = search.isError ? "Unable to search folders" : null;
|
||||
return useMemo(
|
||||
() =>
|
||||
resolveSearch({
|
||||
enabled,
|
||||
hostId,
|
||||
query: input.query,
|
||||
debouncedQuery,
|
||||
data: search.data,
|
||||
failed,
|
||||
empty: EMPTY_PATHS,
|
||||
}),
|
||||
[debouncedQuery, enabled, failed, hostId, input.query, search.data],
|
||||
);
|
||||
}
|
||||
|
||||
/** GitHub repositories the host's account can see, matching `query`. */
|
||||
export function useGithubRepositorySearch(input: {
|
||||
hostId: string | null;
|
||||
query: string;
|
||||
enabled: boolean;
|
||||
}): SearchResult<GithubRepositoryChoice> {
|
||||
const { hostId } = input;
|
||||
const client = useHostRuntimeClient(hostId ?? "");
|
||||
const debouncedQuery = useDebouncedValue(input.query, SEARCH_DEBOUNCE_MS);
|
||||
const enabled = Boolean(client && input.enabled);
|
||||
const search = useFetchQuery({
|
||||
queryKey: ["add-project-flow-github", hostId, debouncedQuery],
|
||||
queryFn: async () => {
|
||||
if (!client) throw new Error("Host is unavailable");
|
||||
const payload = await client.searchGithubRepositories({ query: debouncedQuery, limit: 30 });
|
||||
let error: string | null = payload.error ?? null;
|
||||
if (!error && payload.available === false) error = "GitHub search is unavailable";
|
||||
return {
|
||||
hostId,
|
||||
query: debouncedQuery,
|
||||
items: error ? EMPTY_REPOSITORIES : payload.repositories,
|
||||
error,
|
||||
};
|
||||
},
|
||||
enabled,
|
||||
dataShape: "list",
|
||||
retry: false,
|
||||
staleTimeMs: 15_000,
|
||||
});
|
||||
const failed = search.isError ? "Unable to search GitHub" : null;
|
||||
return useMemo(
|
||||
() =>
|
||||
resolveSearch({
|
||||
enabled,
|
||||
hostId,
|
||||
query: input.query,
|
||||
debouncedQuery,
|
||||
data: search.data,
|
||||
failed,
|
||||
empty: EMPTY_REPOSITORIES,
|
||||
}),
|
||||
[debouncedQuery, enabled, failed, hostId, input.query, search.data],
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import type { ResultListNotice, ResultRow } from "./result-list";
|
||||
|
||||
/** What the sheet needs from the current tab to drive its keys and its primary button. */
|
||||
export interface AddProjectTabView {
|
||||
/** The rows Up and Down walk; empty for a tab without a list. */
|
||||
rows: ResultRow[];
|
||||
/** The active row, or -1 when none is: an older search's rows, or a pick the new answer dropped. */
|
||||
activeIndex: number;
|
||||
notice: ResultListNotice | null;
|
||||
/** Why this host cannot do what the tab offers; the tab's fields are read-only while set. */
|
||||
unavailable: string | null;
|
||||
primary: {
|
||||
label: string;
|
||||
/** Absent when there is nothing to commit yet. */
|
||||
submit: (() => void) | null;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Where the user's pick sits in `rows`. Without a pick, the first row is the default. A pick that
|
||||
* a new answer dropped is not swapped for another row: nothing is active until the user picks again.
|
||||
*/
|
||||
export function resolveActiveIndex(
|
||||
rows: readonly { id: string }[],
|
||||
selectedId: string | null,
|
||||
): number {
|
||||
if (selectedId === null) return rows.length > 0 ? 0 : -1;
|
||||
return rows.findIndex((row) => row.id === selectedId);
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
import { useCallback, useEffect, useRef, type Dispatch, type SetStateAction } from "react";
|
||||
import { router } from "expo-router";
|
||||
import type { WorkspaceProjectDescriptorPayload } from "@getpaseo/protocol/messages";
|
||||
import { pickDirectory } from "@/desktop/pick-directory";
|
||||
import { getOpenProjectFailureReason, registerProjectDescriptor } from "@/hooks/open-project";
|
||||
import { useCloneGithubProject, useOpenProject } from "@/hooks/use-open-project";
|
||||
import { getHostRuntimeStore, useHostRuntimeClient } from "@/runtime/host-runtime";
|
||||
import { useAddProjectFlowStore } from "@/stores/add-project-flow-store";
|
||||
import { usePanelStore } from "@/stores/panel-store";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
import { buildNewWorkspaceRoute } from "@/utils/host-routes";
|
||||
import {
|
||||
failAddProjectSubmission,
|
||||
startAddProjectSubmission,
|
||||
type AddProjectFlowState,
|
||||
type GithubRepositoryChoice,
|
||||
} from "./model";
|
||||
|
||||
/** A failure found before any work starts, shown the same way as one the host reports. */
|
||||
function rejectSubmission(state: AddProjectFlowState, message: string): AddProjectFlowState {
|
||||
return failAddProjectSubmission(startAddProjectSubmission(state), message);
|
||||
}
|
||||
|
||||
export interface AddProjectActions {
|
||||
openFolder: (path: string) => void;
|
||||
browse: () => void;
|
||||
clone: (repository: GithubRepositoryChoice, location: string) => void;
|
||||
/** Expects a name that passed `validateNewFolderName`; the New folder tab only offers those. */
|
||||
createFolder: (name: string, location: string) => void;
|
||||
}
|
||||
|
||||
/** What a submission's work reports: the project to open, or why it failed. */
|
||||
type SubmissionOutcome =
|
||||
| { ok: true; project: WorkspaceProjectDescriptorPayload }
|
||||
| { ok: false; error: string };
|
||||
|
||||
/**
|
||||
* The three ways a project gets added. Each one records its progress and failure in the flow
|
||||
* state and, on success, closes the flow and opens a new workspace for the project.
|
||||
*/
|
||||
export function useAddProjectActions(input: {
|
||||
hostId: string | null;
|
||||
setState: Dispatch<SetStateAction<AddProjectFlowState>>;
|
||||
onClose: () => void;
|
||||
}): AddProjectActions {
|
||||
const { hostId, setState, onClose } = input;
|
||||
const client = useHostRuntimeClient(hostId ?? "");
|
||||
const openProject = useOpenProject(hostId);
|
||||
const cloneGithubProject = useCloneGithubProject(hostId);
|
||||
const setHasHydratedWorkspaces = useSessionStore((store) => store.setHasHydratedWorkspaces);
|
||||
const rememberLocation = useAddProjectFlowStore((store) => store.rememberLocation);
|
||||
// The running submission, if any. It belongs to the open sheet and the host it started on:
|
||||
// closing the sheet or losing that host abandons it, so a late result neither navigates nor
|
||||
// blocks the next submission.
|
||||
const submissionRef = useRef<symbol | null>(null);
|
||||
useEffect(
|
||||
() => () => {
|
||||
submissionRef.current = null;
|
||||
},
|
||||
[hostId],
|
||||
);
|
||||
|
||||
/** Runs one submission at a time and opens a new workspace for the project it adds. */
|
||||
const run = useCallback(
|
||||
async (serverId: string, work: () => Promise<SubmissionOutcome>, fallbackError: string) => {
|
||||
if (submissionRef.current) return;
|
||||
const submission = Symbol("add-project-submission");
|
||||
submissionRef.current = submission;
|
||||
const isCurrent = () => submissionRef.current === submission;
|
||||
setState(startAddProjectSubmission);
|
||||
let outcome: SubmissionOutcome;
|
||||
try {
|
||||
outcome = await work();
|
||||
} catch (error) {
|
||||
const message = error instanceof Error && error.message ? error.message : fallbackError;
|
||||
outcome = { ok: false, error: message };
|
||||
}
|
||||
if (!isCurrent()) return;
|
||||
submissionRef.current = null;
|
||||
if (!outcome.ok) {
|
||||
setState((state) => failAddProjectSubmission(state, outcome.error));
|
||||
return;
|
||||
}
|
||||
onClose();
|
||||
usePanelStore.getState().showMobileAgent();
|
||||
router.push(
|
||||
buildNewWorkspaceRoute({
|
||||
serverId,
|
||||
projectId: outcome.project.projectId,
|
||||
sourceDirectory: outcome.project.projectRootPath,
|
||||
displayName: outcome.project.projectDisplayName,
|
||||
}),
|
||||
);
|
||||
},
|
||||
[onClose, setState],
|
||||
);
|
||||
|
||||
const openFolder = useCallback(
|
||||
(path: string) => {
|
||||
if (!hostId) return;
|
||||
void run(
|
||||
hostId,
|
||||
async () => {
|
||||
const result = await openProject(path);
|
||||
if (result.ok) return { ok: true, project: result.project };
|
||||
if (getOpenProjectFailureReason(result) === "directory_not_found") {
|
||||
return { ok: false, error: "Folder not found" };
|
||||
}
|
||||
return { ok: false, error: result.error ?? "Unable to add project" };
|
||||
},
|
||||
"Unable to add project",
|
||||
);
|
||||
},
|
||||
[hostId, openProject, run],
|
||||
);
|
||||
|
||||
// The desktop folder dialog is modal to the window, so nothing else can start while it is open.
|
||||
const browse = useCallback(() => {
|
||||
if (!hostId || submissionRef.current) return;
|
||||
void (async () => {
|
||||
try {
|
||||
const path = await pickDirectory();
|
||||
if (path) openFolder(path);
|
||||
} catch {
|
||||
setState((state) => rejectSubmission(state, "Unable to browse for a folder"));
|
||||
}
|
||||
})();
|
||||
}, [hostId, openFolder, setState]);
|
||||
|
||||
const clone = useCallback(
|
||||
(repository: GithubRepositoryChoice, location: string) => {
|
||||
if (!hostId) return;
|
||||
void run(
|
||||
hostId,
|
||||
async () => {
|
||||
const result = await cloneGithubProject(
|
||||
repository.cloneUrl,
|
||||
location,
|
||||
repository.cloneProtocol,
|
||||
);
|
||||
if (!result.ok) return { ok: false, error: result.error ?? "Unable to clone project" };
|
||||
rememberLocation(hostId, location);
|
||||
return { ok: true, project: result.project };
|
||||
},
|
||||
"Unable to clone project",
|
||||
);
|
||||
},
|
||||
[cloneGithubProject, hostId, rememberLocation, run],
|
||||
);
|
||||
|
||||
const createFolder = useCallback(
|
||||
(name: string, location: string) => {
|
||||
if (!hostId) return;
|
||||
void run(
|
||||
hostId,
|
||||
async () => {
|
||||
if (!client) return { ok: false, error: "Unable to create folder" };
|
||||
const payload = await client.createProjectDirectory({
|
||||
parentPath: location,
|
||||
name: name.trim(),
|
||||
});
|
||||
if (payload.error || !payload.project) {
|
||||
return { ok: false, error: payload.error ?? "Unable to create folder" };
|
||||
}
|
||||
registerProjectDescriptor({
|
||||
serverId: hostId,
|
||||
project: payload.project,
|
||||
upsertProject: (serverId, project) =>
|
||||
getHostRuntimeStore().acceptProjectSnapshot(serverId, project),
|
||||
setHasHydratedWorkspaces,
|
||||
});
|
||||
rememberLocation(hostId, location);
|
||||
return { ok: true, project: payload.project };
|
||||
},
|
||||
"Unable to create folder",
|
||||
);
|
||||
},
|
||||
[client, hostId, rememberLocation, run, setHasHydratedWorkspaces],
|
||||
);
|
||||
|
||||
return { openFolder, browse, clone, createFolder };
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import { useMemo } from "react";
|
||||
import { getIsElectronRuntime } from "@/constants/layout";
|
||||
import { useLocalDaemonServerId } from "@/hooks/use-is-local-daemon";
|
||||
import { useHosts, useHostRuntimeConnectionStatuses } from "@/runtime/host-runtime";
|
||||
import { useHostFeatureMap } from "@/runtime/host-features";
|
||||
import { orderHostsLocalFirst } from "@/types/host-connection";
|
||||
import type { AddProjectHost } from "./model";
|
||||
|
||||
/** Every host, whether it is online, and what each can do in Add project, the local host first. */
|
||||
export function useAddProjectHosts(): AddProjectHost[] {
|
||||
const hosts = useHosts();
|
||||
const hostIds = useMemo(() => hosts.map((host) => host.serverId), [hosts]);
|
||||
const connectionStatuses = useHostRuntimeConnectionStatuses(hostIds);
|
||||
const projectAddByHost = useHostFeatureMap(hostIds, "projectAdd");
|
||||
// COMPAT(stableProjectIdentity): added in v0.1.109, remove gate after 2027-01-15.
|
||||
const stableProjectIdentityByHost = useHostFeatureMap(hostIds, "stableProjectIdentity");
|
||||
// COMPAT(projectGithubClone): added in v0.1.108, remove gate after 2027-01-15.
|
||||
const githubCloneByHost = useHostFeatureMap(hostIds, "projectGithubClone");
|
||||
// COMPAT(workspaceGithubRepositorySearch): added in v0.1.108, remove gate after 2027-01-15.
|
||||
const githubSearchByHost = useHostFeatureMap(hostIds, "workspaceGithubRepositorySearch");
|
||||
// COMPAT(projectCreateDirectory): added in v0.1.108, remove gate after 2027-01-15.
|
||||
const createDirectoryByHost = useHostFeatureMap(hostIds, "projectCreateDirectory");
|
||||
const localServerId = useLocalDaemonServerId();
|
||||
|
||||
return useMemo<AddProjectHost[]>(() => {
|
||||
return orderHostsLocalFirst(hosts, localServerId).map((host) => {
|
||||
const canAddProject =
|
||||
projectAddByHost.get(host.serverId) === true &&
|
||||
stableProjectIdentityByHost.get(host.serverId) === true;
|
||||
return {
|
||||
serverId: host.serverId,
|
||||
label: host.label,
|
||||
online: connectionStatuses.get(host.serverId) === "online",
|
||||
canAddProject,
|
||||
canBrowse: canAddProject && getIsElectronRuntime() && localServerId === host.serverId,
|
||||
canCloneGithubRepositories: githubCloneByHost.get(host.serverId) === true,
|
||||
canSearchGithubRepositories: githubSearchByHost.get(host.serverId) === true,
|
||||
canCreateDirectory: createDirectoryByHost.get(host.serverId) === true,
|
||||
};
|
||||
});
|
||||
}, [
|
||||
connectionStatuses,
|
||||
createDirectoryByHost,
|
||||
githubCloneByHost,
|
||||
githubSearchByHost,
|
||||
hosts,
|
||||
localServerId,
|
||||
projectAddByHost,
|
||||
stableProjectIdentityByHost,
|
||||
]);
|
||||
}
|
||||
@@ -8,8 +8,9 @@
|
||||
* rules, the icon registry, the row and modal chrome) is internal; import from
|
||||
* `@/agent-profiles`, never a path inside it.
|
||||
*
|
||||
* `useAgentProfilePicker` deliberately hands the picker a flat row view model
|
||||
* and one `applyProfile(id)` callback rather than the profiles themselves: what
|
||||
* `useAgentProfilePicker` deliberately hands the picker — and the Command Center,
|
||||
* which offers the same rows — a flat row view model and one `applyProfile(id)`
|
||||
* callback rather than the profiles themselves: what
|
||||
* a profile contains, and how it reaches a live agent versus a draft, stays in
|
||||
* here.
|
||||
*/
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { AgentProfile } from "@getpaseo/protocol/messages";
|
||||
import { selectApplicableProfiles } from "./applicable-profiles";
|
||||
|
||||
function profile(id: string, provider: string, name = id): AgentProfile {
|
||||
return { id, name, provider };
|
||||
}
|
||||
|
||||
describe("selectApplicableProfiles", () => {
|
||||
it("keeps only profiles naming a provider the composer can run", () => {
|
||||
const claude = profile("a", "claude");
|
||||
const codex = profile("b", "codex");
|
||||
expect(selectApplicableProfiles([claude, codex], ["claude"])).toEqual([claude]);
|
||||
});
|
||||
|
||||
it("keeps the first profile when a stored config repeats an id", () => {
|
||||
const first = profile("same", "claude", "First");
|
||||
const second = profile("same", "claude", "Second");
|
||||
expect(selectApplicableProfiles([first, second], ["claude"])).toEqual([first]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,22 @@
|
||||
import type { AgentProfile } from "@getpaseo/protocol/messages";
|
||||
|
||||
/**
|
||||
* The profiles a composer can offer: those naming a provider it can run, one
|
||||
* per id. The daemon stores whatever list it is given, so a hand-edited config
|
||||
* can repeat an id; the first entry wins, which is also the one `applyProfile`
|
||||
* resolves, and every surface that keys on the id stays unique.
|
||||
*/
|
||||
export function selectApplicableProfiles(
|
||||
profiles: readonly AgentProfile[],
|
||||
availableProviders: readonly string[],
|
||||
): AgentProfile[] {
|
||||
const available = new Set(availableProviders);
|
||||
const seenIds = new Set<string>();
|
||||
const applicable: AgentProfile[] = [];
|
||||
for (const profile of profiles) {
|
||||
if (!available.has(profile.provider) || seenIds.has(profile.id)) continue;
|
||||
seenIds.add(profile.id);
|
||||
applicable.push(profile);
|
||||
}
|
||||
return applicable;
|
||||
}
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
toAgentConfigApply,
|
||||
type MaterializedAgentProfile,
|
||||
} from "./materialize-profile";
|
||||
import { selectApplicableProfiles } from "./applicable-profiles";
|
||||
import { buildAgentProfileTags } from "./profile-summary";
|
||||
import { useAgentProfiles } from "./use-agent-profiles";
|
||||
|
||||
@@ -80,8 +81,7 @@ export function useAgentProfilePicker(
|
||||
if (!isSupported || !profiles) {
|
||||
return [];
|
||||
}
|
||||
const available = new Set(availableProviders);
|
||||
return profiles.filter((profile) => available.has(profile.provider));
|
||||
return selectApplicableProfiles(profiles, availableProviders);
|
||||
}, [availableProviders, isSupported, profiles]);
|
||||
|
||||
const formatFeatureCount = useCallback(
|
||||
|
||||
@@ -56,7 +56,6 @@ export function ChatFind({
|
||||
agentId,
|
||||
serverId,
|
||||
epoch,
|
||||
rewindSeq,
|
||||
items,
|
||||
viewportRef,
|
||||
revealLoadedMessage,
|
||||
@@ -96,8 +95,8 @@ export function ChatFind({
|
||||
);
|
||||
const state = useSyncExternalStore(model.subscribe, model.getSnapshot, model.getSnapshot);
|
||||
useEffect(() => {
|
||||
model.updateHistory(epoch, items, rewindSeq);
|
||||
}, [model, epoch, items, rewindSeq]);
|
||||
model.updateHistory(epoch, items);
|
||||
}, [model, epoch, items]);
|
||||
useEffect(() => () => model.close(), [model]);
|
||||
useEffect(() => {
|
||||
if (!active) model.close();
|
||||
|
||||
@@ -18,7 +18,7 @@ function message(seq: number, text = "target"): StreamItem {
|
||||
kind: "assistant_message",
|
||||
text,
|
||||
timestamp: new Date(0),
|
||||
timelineCursor: { epoch: "epoch", seq, anchorSeq: seq },
|
||||
timelineCursor: { epoch: "epoch", seq },
|
||||
};
|
||||
}
|
||||
|
||||
@@ -39,7 +39,7 @@ it("loads an older location and searches a response merged across suppressed tas
|
||||
source.map((item, index) => ({
|
||||
event: { type: "timeline" as const, provider: "claude" as const, item },
|
||||
timestamp: new Date(0),
|
||||
timelineCursor: { epoch: "epoch", seq: index + 1, anchorSeq: index + 1 },
|
||||
timelineCursor: { epoch: "epoch", seq: index + 1 },
|
||||
})),
|
||||
{ source: "canonical" },
|
||||
);
|
||||
@@ -55,7 +55,7 @@ it("loads an older location and searches a response merged across suppressed tas
|
||||
},
|
||||
async load(_epoch, seq) {
|
||||
loaded.push(seq);
|
||||
model.updateHistory("epoch", history, null);
|
||||
model.updateHistory("epoch", history);
|
||||
},
|
||||
async reveal(_id, _query, occurrence) {
|
||||
revealed.push(occurrence);
|
||||
@@ -64,7 +64,7 @@ it("loads an older location and searches a response merged across suppressed tas
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory("epoch", [], null);
|
||||
model.updateHistory("epoch", []);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
|
||||
@@ -99,7 +99,7 @@ it("skips a source-only candidate and highlights a displayed match", async () =>
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory("epoch", [message(1), message(2)], null);
|
||||
model.updateHistory("epoch", [message(1), message(2)]);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().selectedItemId).toBe("row-2");
|
||||
@@ -129,7 +129,7 @@ it("ignores replies after closing and does not navigate", async () => {
|
||||
},
|
||||
clear() {},
|
||||
});
|
||||
model.updateHistory("epoch", [message(1)], null);
|
||||
model.updateHistory("epoch", [message(1)]);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => calls).toEqual(["search"]);
|
||||
@@ -155,7 +155,7 @@ it("retains a failed search for retry and distinguishes failure from zero matche
|
||||
};
|
||||
const model = new ChatFindModel(operations);
|
||||
try {
|
||||
model.updateHistory("epoch", [], null);
|
||||
model.updateHistory("epoch", []);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("error");
|
||||
@@ -185,7 +185,7 @@ it("reports a failed timeline load as a connection failure", async () => {
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory("epoch", [], null);
|
||||
model.updateHistory("epoch", []);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("error");
|
||||
@@ -207,160 +207,24 @@ it("reports a search result that outlived its epoch as a changed history", async
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory("epoch", [message(1)], null);
|
||||
model.updateHistory("epoch", [message(1)]);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
|
||||
model.updateHistory("epoch-2", [message(1)], null);
|
||||
model.updateHistory("epoch-2", [message(1)]);
|
||||
expect(model.getSnapshot()).toMatchObject({ phase: "error", failure: "historyChanged" });
|
||||
} finally {
|
||||
model.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("reports results that a rewind took messages from as a changed history", async () => {
|
||||
const model = new ChatFindModel({
|
||||
async search() {
|
||||
return response([{ seq: 2, role: "assistant" }]);
|
||||
},
|
||||
async load() {},
|
||||
async reveal() {
|
||||
return { count: 1, occurrence: 0 };
|
||||
},
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory("epoch", [message(1), message(2)], null);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
|
||||
expect(model.getSnapshot()).toMatchObject({ selectedItemId: "row-2", count: 1 });
|
||||
// Another client rewinds the turn holding the match; the epoch stays.
|
||||
model.updateHistory("epoch", [message(1)], 3);
|
||||
expect(model.getSnapshot()).toMatchObject({
|
||||
phase: "error",
|
||||
failure: "historyChanged",
|
||||
selectedItemId: null,
|
||||
});
|
||||
} finally {
|
||||
model.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("stops a search still receiving pages when a rewind lands between them", async () => {
|
||||
let pages = 0;
|
||||
let releaseSecondPage!: () => void;
|
||||
const secondPage = new Promise<void>((resolve) => {
|
||||
releaseSecondPage = resolve;
|
||||
});
|
||||
const model = new ChatFindModel({
|
||||
async search(_query, cursor) {
|
||||
pages += 1;
|
||||
if (cursor === undefined)
|
||||
return { ...response([{ seq: 2, role: "assistant" }]), nextCursor: 2 };
|
||||
await secondPage;
|
||||
return response([{ seq: 1, role: "assistant" }]);
|
||||
},
|
||||
async load() {},
|
||||
async reveal() {
|
||||
return { count: 1, occurrence: 0 };
|
||||
},
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory("epoch", [message(1), message(2)], null);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => pages).toBe(2);
|
||||
model.updateHistory("epoch", [message(1)], 3);
|
||||
releaseSecondPage();
|
||||
await expect.poll(() => model.getSnapshot().failure).toBe("historyChanged");
|
||||
expect(model.getSnapshot()).toMatchObject({ phase: "error", selectedItemId: null });
|
||||
} finally {
|
||||
model.close();
|
||||
}
|
||||
});
|
||||
|
||||
it.each([
|
||||
["Next", "next"],
|
||||
["Previous", "previous"],
|
||||
] as const)("reports a rewind after %s as a changed history", async (_label, step) => {
|
||||
const model = new ChatFindModel({
|
||||
async search() {
|
||||
return response([
|
||||
{ seq: 1, role: "assistant" },
|
||||
{ seq: 2, role: "assistant" },
|
||||
]);
|
||||
},
|
||||
async load() {},
|
||||
async reveal() {
|
||||
return { count: 1, occurrence: 0 };
|
||||
},
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory("epoch", [message(1), message(2)], null);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
|
||||
model[step]();
|
||||
await expect.poll(() => model.getSnapshot().selectedItemId).toBe("row-2");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
|
||||
model.updateHistory("epoch", [message(1)], 3);
|
||||
expect(model.getSnapshot()).toMatchObject({
|
||||
phase: "error",
|
||||
failure: "historyChanged",
|
||||
selectedItemId: null,
|
||||
});
|
||||
} finally {
|
||||
model.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("stops a pending Next when a rewind lands before it reveals", async () => {
|
||||
let reveals = 0;
|
||||
let revealSecond!: () => void;
|
||||
const secondReveal = new Promise<void>((resolve) => {
|
||||
revealSecond = resolve;
|
||||
});
|
||||
const model = new ChatFindModel({
|
||||
async search() {
|
||||
return response([
|
||||
{ seq: 1, role: "assistant" },
|
||||
{ seq: 2, role: "assistant" },
|
||||
]);
|
||||
},
|
||||
async load() {},
|
||||
async reveal() {
|
||||
reveals += 1;
|
||||
if (reveals > 1) await secondReveal;
|
||||
return { count: 1, occurrence: 0 };
|
||||
},
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory("epoch", [message(1), message(2)], null);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
|
||||
model.next();
|
||||
await expect.poll(() => reveals).toBe(2);
|
||||
model.updateHistory("epoch", [message(1)], 3);
|
||||
revealSecond();
|
||||
await expect.poll(() => model.getSnapshot().failure).toBe("historyChanged");
|
||||
expect(model.getSnapshot()).toMatchObject({ phase: "error", selectedItemId: null });
|
||||
} finally {
|
||||
model.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("can load a search location before the initial chat history has arrived", async () => {
|
||||
const model = new ChatFindModel({
|
||||
async search() {
|
||||
return response([{ seq: 1, role: "assistant" }]);
|
||||
},
|
||||
async load() {
|
||||
model.updateHistory("epoch", [message(1)], null);
|
||||
model.updateHistory("epoch", [message(1)]);
|
||||
},
|
||||
async reveal() {
|
||||
return { count: 1, occurrence: 0 };
|
||||
@@ -368,7 +232,7 @@ it("can load a search location before the initial chat history has arrived", asy
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory(null, [], null);
|
||||
model.updateHistory(null, []);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
|
||||
@@ -396,7 +260,7 @@ it("reports the position across the whole chat and corrects it with rendered cou
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory("epoch", [message(1), message(2)], null);
|
||||
model.updateHistory("epoch", [message(1), message(2)]);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
|
||||
@@ -433,7 +297,7 @@ it("counts one match per message from a host that reports no counts", async () =
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory("epoch", [message(1), message(2)], null);
|
||||
model.updateHistory("epoch", [message(1), message(2)]);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
|
||||
|
||||
@@ -76,10 +76,6 @@ export class ChatFindModel {
|
||||
private items: StreamItem[] = [];
|
||||
private epoch: string | null = null;
|
||||
private resultEpoch: string | null = null;
|
||||
/** The latest rewind applied to the history. A rewind keeps the epoch and retires messages. */
|
||||
private rewindSeq: number | null = null;
|
||||
/** The latest rewind when the current result set's search started; undefined until a search starts. */
|
||||
private searchedRewindSeq: number | null | undefined = undefined;
|
||||
private locations: Location[] = [];
|
||||
private resolved = new Map<Location, Target>();
|
||||
private current = -1;
|
||||
@@ -117,7 +113,6 @@ export class ChatFindModel {
|
||||
this.cancel();
|
||||
this.locations = [];
|
||||
this.resultEpoch = null;
|
||||
this.searchedRewindSeq = undefined;
|
||||
this.resolved.clear();
|
||||
this.current = -1;
|
||||
this.inMessage = { occurrence: 0, count: 0 };
|
||||
@@ -149,7 +144,6 @@ export class ChatFindModel {
|
||||
});
|
||||
}
|
||||
private async search(signal: AbortSignal) {
|
||||
this.searchedRewindSeq = this.rewindSeq;
|
||||
try {
|
||||
let cursor: number | undefined;
|
||||
do {
|
||||
@@ -174,14 +168,15 @@ export class ChatFindModel {
|
||||
this.fail(error, signal);
|
||||
}
|
||||
}
|
||||
/** `rewindSeq` is the sequence number of the latest rewind applied to this history. */
|
||||
updateHistory(epoch: string | null, items: StreamItem[], rewindSeq: number | null) {
|
||||
const replaced = this.resultEpoch !== null && epoch !== null && epoch !== this.resultEpoch;
|
||||
const rewound = this.searchedRewindSeq !== undefined && rewindSeq !== this.searchedRewindSeq;
|
||||
if ((replaced || rewound) && this.state.open) {
|
||||
updateHistory(epoch: string | null, items: StreamItem[]) {
|
||||
if (
|
||||
this.resultEpoch !== null &&
|
||||
epoch !== null &&
|
||||
epoch !== this.resultEpoch &&
|
||||
this.state.open
|
||||
) {
|
||||
this.fail(new ChatFindFailureError("historyChanged"), this.abort.signal);
|
||||
}
|
||||
this.rewindSeq = rewindSeq;
|
||||
this.epoch = epoch;
|
||||
this.items = items;
|
||||
this.historyListeners.forEach((listener) => listener());
|
||||
|
||||
@@ -9,8 +9,6 @@ export interface ChatFindProps {
|
||||
agentId: string;
|
||||
serverId: string;
|
||||
epoch: string | null;
|
||||
/** The sequence number of the latest rewind applied to this history, if any. */
|
||||
rewindSeq: number | null;
|
||||
items: StreamItem[];
|
||||
viewportRef: RefObject<StreamViewportHandle | null>;
|
||||
revealLoadedMessage(messageId: string): boolean;
|
||||
|
||||
@@ -139,7 +139,7 @@ describe("useChatOutline", () => {
|
||||
kind: "user_message",
|
||||
text: "live prompt",
|
||||
timestamp: new Date(seq),
|
||||
timelineCursor: { epoch: "epoch-1", seq, anchorSeq: seq },
|
||||
timelineCursor: { epoch: "epoch-1", seq },
|
||||
});
|
||||
rerender({ tail: [loadedPrompt(2)] });
|
||||
await waitFor(() => expect(runtime.listAgentTimelinePrompts).toHaveBeenCalledTimes(2));
|
||||
@@ -198,7 +198,7 @@ describe("useChatOutline", () => {
|
||||
kind: "assistant_message",
|
||||
text: "chunk",
|
||||
timestamp: new Date(),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 2 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 2 },
|
||||
},
|
||||
],
|
||||
timelineEpoch: "epoch-1",
|
||||
@@ -219,7 +219,7 @@ describe("useChatOutline", () => {
|
||||
kind: "user_message",
|
||||
text: "Replaced conversation",
|
||||
timestamp: new Date(2),
|
||||
timelineCursor: { epoch: "epoch-2", seq: 1, anchorSeq: 1 },
|
||||
timelineCursor: { epoch: "epoch-2", seq: 1 },
|
||||
},
|
||||
],
|
||||
timelineEpoch: "epoch-2",
|
||||
@@ -275,7 +275,7 @@ describe("useChatOutline", () => {
|
||||
kind: "user_message" as const,
|
||||
text: "prompt",
|
||||
timestamp: new Date(1),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 1, anchorSeq: 1 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 1 },
|
||||
},
|
||||
];
|
||||
const { result, rerender } = renderHook(
|
||||
@@ -326,7 +326,7 @@ describe("useChatOutline", () => {
|
||||
kind: "user_message" as const,
|
||||
text: "prompt",
|
||||
timestamp: new Date(1),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 1, anchorSeq: 1 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 1 },
|
||||
};
|
||||
const { result, rerender } = renderHook(
|
||||
({ tail, mountedHistoryMessageIds }) =>
|
||||
@@ -381,7 +381,7 @@ describe("useChatOutline", () => {
|
||||
kind: "user_message" as const,
|
||||
text: "prompt",
|
||||
timestamp: new Date(2),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 2 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 2 },
|
||||
};
|
||||
const revealLoadedMessage = vi.fn();
|
||||
revealLoadedMessage.mockReturnValue(false);
|
||||
|
||||
@@ -26,14 +26,22 @@ export function getMountedRecentStreamItems(): number {
|
||||
export function findMountedWindowStart(input: {
|
||||
items: StreamItem[];
|
||||
minMountedCount: number;
|
||||
// Caps how far turn alignment may rewind. History paging and the replica
|
||||
// cache omit it and still keep a whole turn.
|
||||
maxMountedCount?: number;
|
||||
}): number {
|
||||
const { items, minMountedCount } = input;
|
||||
if (items.length <= minMountedCount) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const mountedLimit =
|
||||
input.maxMountedCount === undefined
|
||||
? items.length
|
||||
: Math.max(minMountedCount, input.maxMountedCount);
|
||||
const earliestStart = Math.max(0, items.length - mountedLimit);
|
||||
let startIndex = Math.max(items.length - minMountedCount, 0);
|
||||
while (startIndex > 0 && continuesTurn(items[startIndex - 1], items[startIndex])) {
|
||||
while (startIndex > earliestStart && continuesTurn(items[startIndex - 1], items[startIndex])) {
|
||||
startIndex -= 1;
|
||||
}
|
||||
return startIndex;
|
||||
|
||||
@@ -2,7 +2,7 @@ import { LegendList, type LegendListRef } from "@legendapp/list/react-native";
|
||||
import React, { act, useSyncExternalStore } from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { View } from "react-native";
|
||||
import { afterEach, beforeEach, expect, it } from "vitest";
|
||||
import { afterEach, beforeEach, expect, it, vi } from "vitest";
|
||||
import { disclosureAnchor } from "./native-disclosure-hold";
|
||||
|
||||
// The native chat timeline runs on the patched LegendList (patches/@legendapp+list+3.7.1.patch).
|
||||
@@ -90,7 +90,7 @@ function keyExtractor(item: Row) {
|
||||
return item.id;
|
||||
}
|
||||
|
||||
function estimateRowSize(item: Row) {
|
||||
function rowHeight(item: Row) {
|
||||
return item.height;
|
||||
}
|
||||
|
||||
@@ -289,7 +289,7 @@ it("expands the draw distance of a placed end-anchored list without moving its b
|
||||
keyExtractor={keyExtractor}
|
||||
estimatedListSize={ESTIMATED_LIST_SIZE}
|
||||
recycleItems={false}
|
||||
getEstimatedItemSize={estimateRowSize}
|
||||
getEstimatedItemSize={rowHeight}
|
||||
drawDistance={drawDistance}
|
||||
alignItemsAtEnd
|
||||
initialScrollAtEnd
|
||||
@@ -315,3 +315,96 @@ it("expands the draw distance of a placed end-anchored list without moving its b
|
||||
expect(expanded?.scroll).toBe(initial?.scroll);
|
||||
expect(expanded?.positionByKey(lastRow.id)).toBe(lastRowTop);
|
||||
});
|
||||
|
||||
it.each([2, 4])("reveals an end-anchored list with a footer %sx the viewport", async (scale) => {
|
||||
const rows: Row[] = Array.from({ length: 10 }, (_, index) => ({
|
||||
id: `row-${index}`,
|
||||
height: 40,
|
||||
}));
|
||||
const footerHeight = VIEWPORT_HEIGHT * scale;
|
||||
const listRef = React.createRef<LegendListRef>();
|
||||
const footer = React.createElement(View, { style: rowStyle(footerHeight) });
|
||||
const onReady = vi.fn();
|
||||
|
||||
act(() => {
|
||||
root.render(
|
||||
<LegendList
|
||||
ref={listRef}
|
||||
data={rows}
|
||||
renderItem={renderRow}
|
||||
keyExtractor={keyExtractor}
|
||||
estimatedListSize={ESTIMATED_LIST_SIZE}
|
||||
getEstimatedItemSize={rowHeight}
|
||||
drawDistance={50}
|
||||
recycleItems={false}
|
||||
alignItemsAtEnd
|
||||
initialScrollAtEnd
|
||||
ListFooterComponent={footer}
|
||||
onReady={onReady}
|
||||
style={LIST_STYLE}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
await expect
|
||||
.poll(async () => {
|
||||
await wait(16);
|
||||
return onReady.mock.calls.length;
|
||||
})
|
||||
.toBe(1);
|
||||
expect(listRef.current?.getState().scroll).toBe(
|
||||
rows.length * 40 + footerHeight - VIEWPORT_HEIGHT,
|
||||
);
|
||||
});
|
||||
|
||||
const END_PADDED_CONTENT_STYLE = { paddingBottom: 125 };
|
||||
|
||||
it("reveals buffered rows when the scroll view takes over initial end positioning", () => {
|
||||
const rowSize = 40;
|
||||
const rows: Row[] = Array.from({ length: 10 }, (_, index) => ({
|
||||
id: `row-${index}`,
|
||||
height: rowSize,
|
||||
}));
|
||||
const listRef = React.createRef<LegendListRef>();
|
||||
const onReady = vi.fn();
|
||||
|
||||
act(() => {
|
||||
root.render(
|
||||
<LegendList
|
||||
ref={listRef}
|
||||
data={rows}
|
||||
renderItem={renderRow}
|
||||
keyExtractor={keyExtractor}
|
||||
estimatedListSize={ESTIMATED_LIST_SIZE}
|
||||
getFixedItemSize={rowHeight}
|
||||
drawDistance={120}
|
||||
recycleItems={false}
|
||||
alignItemsAtEnd
|
||||
initialScrollAtEnd
|
||||
contentContainerStyle={END_PADDED_CONTENT_STYLE}
|
||||
onReady={onReady}
|
||||
style={LIST_STYLE}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
const list = listRef.current;
|
||||
if (!list) throw new Error("The list did not mount");
|
||||
const scroller: unknown = list.getScrollableNode();
|
||||
if (!(scroller instanceof HTMLElement)) throw new Error("The list has no scroll element");
|
||||
const endOffset =
|
||||
rows.length * rowSize + END_PADDED_CONTENT_STYLE.paddingBottom - VIEWPORT_HEIGHT;
|
||||
|
||||
act(() => {
|
||||
// Deliver the scroll view's observed end offset before canceling the list's initial scroll.
|
||||
// Keep both calls in one task so a later layout pass cannot complete the reveal for them.
|
||||
scroller.scrollTop = endOffset;
|
||||
scroller.dispatchEvent(new Event("scroll"));
|
||||
expect(onReady).not.toHaveBeenCalled();
|
||||
list.cancelScroll();
|
||||
});
|
||||
const state = list.getState();
|
||||
expect(state.scroll).toBe(endOffset);
|
||||
expect(state.start).toBeNull();
|
||||
expect(state.endBuffered).toBe(rows.length - 1);
|
||||
expect(state.sizeAtIndex(rows.length - 1)).toBe(rowSize);
|
||||
expect(onReady).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
@@ -3,6 +3,7 @@ import type { StreamItem } from "@/types/stream";
|
||||
import { projectPluginTimelineItems } from "@/plugins/timeline/projection";
|
||||
import { findMountedWindowStart } from "./history-window";
|
||||
import { buildAgentStreamRenderModel } from "./model";
|
||||
import { MAX_MOUNTED_WEB_WINDOW_ITEMS } from "./web-virtualization";
|
||||
|
||||
function createTimestamp(seed: number): Date {
|
||||
return new Date(`2026-01-01T00:00:${seed.toString().padStart(2, "0")}.000Z`);
|
||||
@@ -125,6 +126,30 @@ describe("buildAgentStreamRenderModel", () => {
|
||||
expect(model.history).not.toContain(head[0]);
|
||||
});
|
||||
|
||||
it("virtualizes a desktop web turn that runs past the mounted cap", () => {
|
||||
const length = MAX_MOUNTED_WEB_WINDOW_ITEMS + 80;
|
||||
const tail = Array.from({ length }, (_, index) => ({
|
||||
...userMessage(`row-${index}`, index % 60),
|
||||
turnId: "long-run",
|
||||
}));
|
||||
|
||||
const model = buildAgentStreamRenderModel({
|
||||
isTurnActive: false,
|
||||
activeTurnStartedAt: null,
|
||||
tail,
|
||||
head: [],
|
||||
platform: "web",
|
||||
isMobileBreakpoint: false,
|
||||
});
|
||||
|
||||
expect(model.segments.historyMounted).toHaveLength(MAX_MOUNTED_WEB_WINDOW_ITEMS);
|
||||
expect(model.segments.historyVirtualized).toHaveLength(80);
|
||||
expect(model.segments.historyMounted[0]?.id).toBe(
|
||||
`row-${length - MAX_MOUNTED_WEB_WINDOW_ITEMS}`,
|
||||
);
|
||||
expect(model.segments.historyVirtualized[0]?.id).toBe("row-0");
|
||||
});
|
||||
|
||||
it("keeps the full committed tail mounted on mobile web", () => {
|
||||
const tail = [userMessage("u1", 1), assistantMessage("a1", 2)];
|
||||
const head = [assistantMessage("live-a", 3)];
|
||||
|
||||
@@ -2,7 +2,10 @@ import type { ReactNode } from "react";
|
||||
import { deriveStreamTurnTiming, type StreamTurnTiming } from "@/timeline/turn-time";
|
||||
import type { StreamItem } from "@/types/stream";
|
||||
import { findMountedWindowStart, getMountedRecentStreamItems } from "./history-window";
|
||||
import { getWebPartialVirtualizationThreshold } from "./web-virtualization";
|
||||
import {
|
||||
getWebPartialVirtualizationThreshold,
|
||||
MAX_MOUNTED_WEB_WINDOW_ITEMS,
|
||||
} from "./web-virtualization";
|
||||
import { orderHeadForStreamRenderStrategy, orderTailForStreamRenderStrategy } from "./strategy";
|
||||
import { resolveStreamRenderStrategy } from "./strategy-resolver";
|
||||
|
||||
@@ -134,6 +137,7 @@ function splitOrderedTail(params: {
|
||||
const mountedWindowStart = findMountedWindowStart({
|
||||
items: orderedTail,
|
||||
minMountedCount: getMountedRecentStreamItems(),
|
||||
maxMountedCount: MAX_MOUNTED_WEB_WINDOW_ITEMS,
|
||||
});
|
||||
const split = {
|
||||
history: orderedTail,
|
||||
|
||||
@@ -320,7 +320,7 @@ describe("stream presentation through installed plugins", () => {
|
||||
const source = harness.source();
|
||||
const live = source.head[0];
|
||||
if (live?.kind !== "assistant_message") throw new Error("Expected a live assistant message");
|
||||
const canonical = { ...live, timelineCursor: { epoch: "epoch-1", seq: 42, anchorSeq: 42 } };
|
||||
const canonical = { ...live, timelineCursor: { epoch: "epoch-1", seq: 42 } };
|
||||
const present = createStreamPresentation();
|
||||
present({ ...presentationOptions, tail: [], head: [live], transform: undefined });
|
||||
const repointed = rows(
|
||||
@@ -330,7 +330,7 @@ describe("stream presentation through installed plugins", () => {
|
||||
{
|
||||
id: streamed[0]!.id,
|
||||
text: "Streamed answer",
|
||||
timelineCursor: { epoch: "epoch-1", seq: 42, anchorSeq: 42 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 42 },
|
||||
},
|
||||
]);
|
||||
});
|
||||
@@ -517,7 +517,7 @@ describe("timeline presentation", () => {
|
||||
messageId: "provider-message",
|
||||
clientMessageId: "client-message",
|
||||
turnId: "turn-1",
|
||||
timelineCursor: { epoch: "epoch", seq: 12, anchorSeq: 12 },
|
||||
timelineCursor: { epoch: "epoch", seq: 12 },
|
||||
});
|
||||
const presentMessage = () =>
|
||||
present({
|
||||
|
||||
@@ -33,7 +33,7 @@ describe("resolveAssistantTurnForkBoundary", () => {
|
||||
it("forks a failed assistant turn from its Paseo timeline cursor without a provider message id", () => {
|
||||
const failedTurn = {
|
||||
...assistantMessage("assistant-error", 2),
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 42 },
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42 },
|
||||
};
|
||||
|
||||
expect(
|
||||
@@ -50,7 +50,7 @@ describe("resolveAssistantTurnForkBoundary", () => {
|
||||
it("includes the provider message id with a supported timeline cursor", () => {
|
||||
const selected = {
|
||||
...assistantMessage("assistant-1", 2, "msg-assistant-1"),
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 42 },
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42 },
|
||||
};
|
||||
|
||||
expect(
|
||||
@@ -68,7 +68,7 @@ describe("resolveAssistantTurnForkBoundary", () => {
|
||||
it("falls back to the provider message id when timeline cursors are unsupported", () => {
|
||||
const selected = {
|
||||
...assistantMessage("assistant-1", 2, "msg-assistant-1"),
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 42 },
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42 },
|
||||
};
|
||||
|
||||
expect(
|
||||
|
||||
@@ -1,13 +1,7 @@
|
||||
import type { StreamItem } from "@/types/stream";
|
||||
|
||||
/** The daemon's timeline cursor; the row's anchor stays in the client. */
|
||||
interface TimelineBoundaryCursor {
|
||||
epoch: string;
|
||||
seq: number;
|
||||
}
|
||||
import type { StreamItem, TimelinePosition } from "@/types/stream";
|
||||
|
||||
export type AssistantTurnForkBoundary =
|
||||
| { boundaryCursor: TimelineBoundaryCursor; boundaryMessageId?: string }
|
||||
| { boundaryCursor: TimelinePosition; boundaryMessageId?: string }
|
||||
| { boundaryCursor?: undefined; boundaryMessageId: string };
|
||||
|
||||
export function resolveAssistantTurnForkBoundary(input: {
|
||||
@@ -21,7 +15,7 @@ export function resolveAssistantTurnForkBoundary(input: {
|
||||
}
|
||||
if (input.supportsTimelineCursor && item.timelineCursor) {
|
||||
return {
|
||||
boundaryCursor: { epoch: item.timelineCursor.epoch, seq: item.timelineCursor.seq },
|
||||
boundaryCursor: item.timelineCursor,
|
||||
...(item.messageId ? { boundaryMessageId: item.messageId } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -140,7 +140,7 @@ describe("collapseTurns", () => {
|
||||
it("stands at its host's timeline position, taking a new row when that position lands", () => {
|
||||
const live = collapse([user("u1"), shell("c1"), reply("r1")]);
|
||||
expect(live.summaryRowsByHostId.get("u1")).not.toHaveProperty("timelineCursor");
|
||||
const cursor = { epoch: "epoch-1", seq: 7, anchorSeq: 7 };
|
||||
const cursor = { epoch: "epoch-1", seq: 7 };
|
||||
const placed = [{ ...user("u1"), timelineCursor: cursor }, shell("c1"), reply("r1")];
|
||||
const canonical = collapse(placed, { previousSummaryRowsByHostId: live.summaryRowsByHostId });
|
||||
expect(canonical.summaryRowsByHostId.get("u1")).not.toBe(live.summaryRowsByHostId.get("u1"));
|
||||
|
||||
@@ -408,10 +408,6 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
|
||||
const timelineEpoch = useSessionStore(
|
||||
(state) => state.sessions[resolvedServerId]?.agentTimelineCursor.get(agentId)?.epoch ?? null,
|
||||
);
|
||||
const timelineRewindSeq = useSessionStore((state) => {
|
||||
const rewind = state.sessions[resolvedServerId]?.agentTimelineLatestRewind.get(agentId);
|
||||
return rewind && rewind.epoch === timelineEpoch ? rewind.seq : null;
|
||||
});
|
||||
const isTimelineDetached = useSessionStore(
|
||||
(state) => state.sessions[resolvedServerId]?.agentTimelineHasNewer.get(agentId) === true,
|
||||
);
|
||||
@@ -1170,7 +1166,6 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
|
||||
agentId={agentId}
|
||||
serverId={resolvedServerId}
|
||||
epoch={timelineEpoch}
|
||||
rewindSeq={timelineRewindSeq}
|
||||
items={findItems}
|
||||
viewportRef={viewportRef}
|
||||
revealLoadedMessage={revealLoadedMessage}
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
DEFAULT_WEB_PARTIAL_VIRTUALIZATION_THRESHOLD,
|
||||
estimateStreamItemHeight,
|
||||
findMountedWindowStart,
|
||||
MAX_MOUNTED_WEB_WINDOW_ITEMS,
|
||||
getWebMountedRecentStreamItems,
|
||||
getWebPartialVirtualizationThreshold,
|
||||
splitWebVirtualizedHistory,
|
||||
@@ -108,6 +109,37 @@ describe("findMountedWindowStart", () => {
|
||||
}),
|
||||
).toBe(39);
|
||||
});
|
||||
|
||||
it("keeps a whole turn when the caller does not cap the rewind", () => {
|
||||
const items = Array.from({ length: MAX_MOUNTED_WEB_WINDOW_ITEMS + 40 }, (_, index) => ({
|
||||
...toolCall(`t${index}`, index % 60),
|
||||
turnId: "long",
|
||||
}));
|
||||
|
||||
expect(findMountedWindowStart({ items, minMountedCount: 20 })).toBe(0);
|
||||
});
|
||||
|
||||
it("stops a long turn at the cap and still honors a larger minimum", () => {
|
||||
const items = Array.from({ length: 200 }, (_, index) => ({
|
||||
...toolCall(`t${index}`, index % 60),
|
||||
turnId: "long",
|
||||
}));
|
||||
|
||||
expect(
|
||||
findMountedWindowStart({
|
||||
items,
|
||||
minMountedCount: 20,
|
||||
maxMountedCount: MAX_MOUNTED_WEB_WINDOW_ITEMS,
|
||||
}),
|
||||
).toBe(200 - MAX_MOUNTED_WEB_WINDOW_ITEMS);
|
||||
expect(
|
||||
findMountedWindowStart({
|
||||
items,
|
||||
minMountedCount: 80,
|
||||
maxMountedCount: MAX_MOUNTED_WEB_WINDOW_ITEMS,
|
||||
}),
|
||||
).toBe(120);
|
||||
});
|
||||
});
|
||||
|
||||
describe("splitWebVirtualizedHistory", () => {
|
||||
@@ -130,6 +162,39 @@ describe("splitWebVirtualizedHistory", () => {
|
||||
expect(window.mountedEntries[0]?.item.id).toBe("u5");
|
||||
expect(window.mountedEntries).toHaveLength(50);
|
||||
});
|
||||
|
||||
it("virtualizes the older rows of a turn that is longer than the mounted cap", () => {
|
||||
const length = MAX_MOUNTED_WEB_WINDOW_ITEMS + 25;
|
||||
const items = Array.from({ length }, (_, index) => ({
|
||||
...toolCall(`t${index}`, index % 60),
|
||||
turnId: "long",
|
||||
}));
|
||||
|
||||
const window = splitWebVirtualizedHistory({
|
||||
entries: indexEntries(items),
|
||||
minMountedCount: DEFAULT_WEB_MOUNTED_RECENT_STREAM_ITEMS,
|
||||
});
|
||||
|
||||
expect(window.mountedEntries).toHaveLength(MAX_MOUNTED_WEB_WINDOW_ITEMS);
|
||||
expect(window.virtualizedEntries).toHaveLength(25);
|
||||
expect(window.mountedEntries[0]?.item.id).toBe(`t${length - MAX_MOUNTED_WEB_WINDOW_ITEMS}`);
|
||||
expect(window.virtualizedEntries[0]?.item.id).toBe("t0");
|
||||
});
|
||||
|
||||
it("keeps a turn that fits under the cap mounted together", () => {
|
||||
const items = Array.from({ length: 40 }, (_, index) => ({
|
||||
...toolCall(`t${index}`, index),
|
||||
turnId: "short",
|
||||
}));
|
||||
|
||||
const window = splitWebVirtualizedHistory({
|
||||
entries: indexEntries(items),
|
||||
minMountedCount: DEFAULT_WEB_MOUNTED_RECENT_STREAM_ITEMS,
|
||||
});
|
||||
|
||||
expect(window.virtualizedEntries).toHaveLength(0);
|
||||
expect(window.mountedEntries).toHaveLength(40);
|
||||
});
|
||||
});
|
||||
|
||||
describe("estimateStreamItemHeight", () => {
|
||||
|
||||
@@ -8,6 +8,9 @@ import {
|
||||
|
||||
export const DEFAULT_WEB_PARTIAL_VIRTUALIZATION_THRESHOLD = 100;
|
||||
export const DEFAULT_WEB_MOUNTED_RECENT_STREAM_ITEMS = DEFAULT_MOUNTED_RECENT_STREAM_ITEMS;
|
||||
// Collapsed tool rows are about 40px, so this stays past a desktop viewport.
|
||||
// Opening a long run mounts that tail and virtualizes the older rows.
|
||||
export const MAX_MOUNTED_WEB_WINDOW_ITEMS = 60;
|
||||
const COLLAPSED_TOOL_SEQUENCE_ROW_HEIGHT_ESTIMATE = 40;
|
||||
|
||||
type BottomAnchorE2ETestGlobals = typeof globalThis & {
|
||||
@@ -87,6 +90,7 @@ export function splitWebVirtualizedHistory(input: {
|
||||
const startIndex = findMountedWindowStart({
|
||||
items: input.entries.map((entry) => entry.item),
|
||||
minMountedCount: input.minMountedCount,
|
||||
maxMountedCount: MAX_MOUNTED_WEB_WINDOW_ITEMS,
|
||||
});
|
||||
return {
|
||||
virtualizedEntries: input.entries.slice(0, startIndex),
|
||||
|
||||
@@ -1,5 +1,20 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { createAssistantSelectionClipboardContent } from "./content.web";
|
||||
import { createElement as h } from "react";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { flushSync } from "react-dom";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { within } from "@testing-library/dom";
|
||||
import { EnrichedMarkdownText } from "react-native-enriched-markdown";
|
||||
import { I18nextProvider } from "react-i18next";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { WEB_RENDERERS } from "@/components/markdown/renderers.web";
|
||||
import type { ToastApi } from "@/components/toast-host";
|
||||
import { ToastApiProvider } from "@/contexts/toast-api-context";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
import {
|
||||
createAssistantSelectionClipboardContent,
|
||||
createElementClipboardContent,
|
||||
} from "./content.web";
|
||||
import { MARKDOWN_COPY_FENCE_SOURCE_ATTRIBUTE } from "./markup";
|
||||
|
||||
const fixture = `
|
||||
<div data-testid="assistant-message">
|
||||
@@ -953,3 +968,158 @@ it("copies a workspace image path instead of its temporary display URL", () => {
|
||||
"",
|
||||
);
|
||||
});
|
||||
|
||||
describe("quote copy", () => {
|
||||
let root: Root | undefined;
|
||||
let host: HTMLDivElement | undefined;
|
||||
const toast: ToastApi = { show: () => () => {}, copied: () => {}, error: () => {} };
|
||||
const queryClient = new QueryClient();
|
||||
|
||||
afterEach(() => {
|
||||
const mounted = root;
|
||||
if (mounted) flushSync(() => mounted.unmount());
|
||||
root = undefined;
|
||||
host?.remove();
|
||||
host = undefined;
|
||||
});
|
||||
|
||||
/** Renders Markdown through the web engine with the app's renderers, as a message does. */
|
||||
async function renderMarkdown(markdown: string, lastText: string): Promise<HTMLElement> {
|
||||
if (!host || !root) {
|
||||
host = document.createElement("div");
|
||||
document.body.append(host);
|
||||
root = createRoot(host);
|
||||
}
|
||||
const mounted = root;
|
||||
flushSync(() =>
|
||||
mounted.render(
|
||||
h(
|
||||
QueryClientProvider,
|
||||
{ client: queryClient },
|
||||
h(
|
||||
I18nextProvider,
|
||||
{ i18n },
|
||||
h(ToastApiProvider, {
|
||||
api: toast,
|
||||
children: h(EnrichedMarkdownText, {
|
||||
markdown,
|
||||
flavor: "github",
|
||||
md4cFlags: { latexMath: false, admonitions: true },
|
||||
renderers: WEB_RENDERERS,
|
||||
}),
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
const rendered = host;
|
||||
await vi.waitFor(() => expect(rendered.textContent).toContain(lastText));
|
||||
return rendered;
|
||||
}
|
||||
|
||||
it("copies a quote's body with its formatting and without the quote marker", async () => {
|
||||
const rendered = await renderMarkdown(
|
||||
"> Hello **team**, see [the PR](https://example.test/pr).\n>\n> - Review\n>\n> > Nested reply",
|
||||
"Nested reply",
|
||||
);
|
||||
|
||||
const content = createElementClipboardContent(fixtureElement(rendered, "blockquote"));
|
||||
|
||||
expect(content?.plainText).toBe(
|
||||
"Hello **team**, see [the PR](https://example.test/pr).\n\n- Review\n\n> Nested reply",
|
||||
);
|
||||
expect(content?.html).toContain("<strong>team</strong>");
|
||||
expect(content?.html).toContain("<blockquote>");
|
||||
expect(content?.html).not.toContain("Copy quote");
|
||||
});
|
||||
|
||||
it("gives a nested quote its own control that copies only the nested quote", async () => {
|
||||
const rendered = await renderMarkdown("> Outer\n>\n> > Nested reply", "Nested reply");
|
||||
const nested = fixtureElement(rendered, "blockquote", 1);
|
||||
|
||||
expect(within(rendered).getAllByRole("button", { name: "Copy quote" })).toHaveLength(2);
|
||||
expect(within(nested).getAllByRole("button", { name: "Copy quote" })).toHaveLength(1);
|
||||
expect(createElementClipboardContent(nested)?.plainText).toBe("Nested reply");
|
||||
});
|
||||
|
||||
it("copies a code block inside a quote as its fence and keeps the code's own control", async () => {
|
||||
const rendered = await renderMarkdown("> Run:\n>\n> ```sh\n> npm test\n> ```", "npm test");
|
||||
const quote = fixtureElement(rendered, "blockquote");
|
||||
|
||||
expect(within(quote).getByRole("button", { name: "Copy code" })).toBeTruthy();
|
||||
expect(createElementClipboardContent(quote)?.plainText).toBe("Run:\n\n```sh\nnpm test\n```");
|
||||
});
|
||||
|
||||
it("copies what a streaming quote shows at the time of the copy", async () => {
|
||||
const first = await renderMarkdown("> First draft", "First draft");
|
||||
const quote = fixtureElement(first, "blockquote");
|
||||
|
||||
const revised = await renderMarkdown("> First draft, revised", "revised");
|
||||
|
||||
expect(fixtureElement(revised, "blockquote")).toBe(quote);
|
||||
expect(createElementClipboardContent(quote)?.plainText).toBe("First draft, revised");
|
||||
});
|
||||
|
||||
it("copies literal Markdown characters raw in text/plain and escaped in text/html", async () => {
|
||||
const rendered = await renderMarkdown("> literal \\_word\\_ stays literal", "stays literal");
|
||||
|
||||
const content = createElementClipboardContent(fixtureElement(rendered, "blockquote"));
|
||||
|
||||
expect(content?.plainText).toBe("literal _word_ stays literal");
|
||||
expect(content?.html).toContain("literal _word_ stays literal");
|
||||
expect(content?.html).not.toContain("<em>");
|
||||
});
|
||||
|
||||
it("gives an admonition no copy control", async () => {
|
||||
const rendered = await renderMarkdown("> [!NOTE]\n> Heads up", "Heads up");
|
||||
|
||||
expect(within(rendered).queryByRole("button", { name: "Copy quote" })).toBeNull();
|
||||
});
|
||||
|
||||
it("copies a nested admonition as its callout source", async () => {
|
||||
const rendered = await renderMarkdown(
|
||||
"> Before\n>\n> > [!WARNING]\n> > Do not deploy.\n>\n> After",
|
||||
"After",
|
||||
);
|
||||
|
||||
const content = createElementClipboardContent(fixtureElement(rendered, "blockquote"));
|
||||
|
||||
expect(content?.plainText).toBe("Before\n\n> [!WARNING]\n> Do not deploy.\n\nAfter");
|
||||
});
|
||||
|
||||
it("copies a selection across an admonition as the text it shows, without a callout marker", async () => {
|
||||
const rendered = await renderMarkdown(
|
||||
"> Before\n>\n> > [!WARNING]\n> > Do not deploy.\n>\n> After",
|
||||
"After",
|
||||
);
|
||||
rendered.setAttribute("data-testid", "assistant-message");
|
||||
const body = tokenText(rendered, "Do not deploy.");
|
||||
|
||||
expect(
|
||||
copyBetween([body, "Do not ".length], [tokenText(rendered, "After"), 5])?.plainText,
|
||||
).toBe("deploy.\n\nAfter");
|
||||
expect(
|
||||
copyBetween([tokenText(rendered, "Before"), 0], [tokenText(rendered, "Warning"), 4])
|
||||
?.plainText,
|
||||
).toBe("Before\n\nWarn");
|
||||
expect(
|
||||
copyBetween([tokenText(rendered, "Before"), 0], [body, "Do not".length])?.plainText,
|
||||
).not.toContain("[!WARNING]");
|
||||
});
|
||||
|
||||
it("copies a rendered Mermaid diagram as its fence", () => {
|
||||
const quote = document.createElement("blockquote");
|
||||
quote.innerHTML = `<p>Before</p><div ${MARKDOWN_COPY_FENCE_SOURCE_ATTRIBUTE}="graph TD; A-->B" data-paseo-markdown-language="mermaid"><svg aria-label="diagram"></svg></div><p>After</p>`;
|
||||
|
||||
expect(createElementClipboardContent(quote)?.plainText).toBe(
|
||||
"Before\n\n```mermaid\ngraph TD; A-->B\n```\n\nAfter",
|
||||
);
|
||||
});
|
||||
|
||||
it("copies nothing from a quote that holds only its control", () => {
|
||||
const quote = document.createElement("blockquote");
|
||||
quote.innerHTML = '<button data-paseo-markdown-ignore="true">Copy quote</button>';
|
||||
|
||||
expect(createElementClipboardContent(quote)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -6,9 +6,12 @@ import {
|
||||
type MarkdownClipboardContent,
|
||||
} from "@/utils/rich-clipboard";
|
||||
import {
|
||||
MARKDOWN_ADMONITION_TITLE_ATTRIBUTE,
|
||||
MARKDOWN_ADMONITION_TYPE_ATTRIBUTE,
|
||||
MARKDOWN_COPY_IMAGE_SOURCES_ATTRIBUTE,
|
||||
MARKDOWN_COPY_ALIGN_ATTRIBUTE,
|
||||
MARKDOWN_COPY_ALT_ATTRIBUTE,
|
||||
MARKDOWN_COPY_FENCE_SOURCE_ATTRIBUTE,
|
||||
MARKDOWN_COPY_IGNORE_ATTRIBUTE,
|
||||
MARKDOWN_COPY_LANGUAGE_ATTRIBUTE,
|
||||
MARKDOWN_COPY_LIST_MARKER_ATTRIBUTE,
|
||||
@@ -91,6 +94,17 @@ function createTurndown(flavor: "markdown" | "plain"): TurndownService {
|
||||
} else {
|
||||
turndown.escape = (text) => text;
|
||||
}
|
||||
// An admonition copies as its `> [!TYPE]` source.
|
||||
turndown.addRule("admonition", {
|
||||
filter: (node) => node.hasAttribute(MARKDOWN_ADMONITION_TYPE_ATTRIBUTE),
|
||||
replacement: (content, node) => {
|
||||
const type = (node as Element)
|
||||
.getAttribute(MARKDOWN_ADMONITION_TYPE_ATTRIBUTE)!
|
||||
.toUpperCase();
|
||||
const body = content.replace(/^\n+|\n+$/g, "");
|
||||
return `\n\n${`[!${type}]\n${body}`.replace(/^/gm, "> ")}\n\n`;
|
||||
},
|
||||
});
|
||||
turndown.addRule("gfmStrikethrough", {
|
||||
filter: ["del", "s"],
|
||||
replacement: (content) => `~~${content}~~`,
|
||||
@@ -120,6 +134,53 @@ function isWebUrl(href: string): boolean {
|
||||
const markdownTurndown = createTurndown("markdown");
|
||||
const plainTurndown = createTurndown("plain");
|
||||
|
||||
/**
|
||||
* A fence rendered as something other than its code, such as a Mermaid diagram, carries
|
||||
* its source in an attribute. Put the code block back so the fence is what gets copied.
|
||||
*/
|
||||
function restoreFenceSources(container: Element): void {
|
||||
for (const region of container.querySelectorAll(`[${MARKDOWN_COPY_FENCE_SOURCE_ATTRIBUTE}]`)) {
|
||||
const source = region.getAttribute(MARKDOWN_COPY_FENCE_SOURCE_ATTRIBUTE);
|
||||
if (source === null) continue;
|
||||
const pre = document.createElement("pre");
|
||||
const code = document.createElement("code");
|
||||
const language = region.getAttribute(MARKDOWN_COPY_LANGUAGE_ATTRIBUTE);
|
||||
if (language) code.className = `language-${language}`;
|
||||
code.textContent = source;
|
||||
pre.append(code);
|
||||
region.replaceWith(pre);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clipboard payload for everything inside `element`, without the element's own syntax:
|
||||
* a quote's body carries no `>` prefix. Null when there is nothing to copy.
|
||||
*/
|
||||
export function createElementClipboardContent(element: Element): MarkdownClipboardContent | null {
|
||||
const container = document.createElement("div");
|
||||
container.append(...Array.from(element.childNodes, (child) => child.cloneNode(true)));
|
||||
const originals = element.querySelectorAll("*");
|
||||
const copies = container.querySelectorAll("*");
|
||||
originals.forEach((original, index) => copySemanticAttributes(original, copies[index]!));
|
||||
restoreFenceSources(container);
|
||||
restoreAdmonitions(container);
|
||||
restoreMarkdownElements(container);
|
||||
return clipboardContentFromMarkup(container);
|
||||
}
|
||||
|
||||
function clipboardContentFromMarkup(container: HTMLElement): MarkdownClipboardContent | null {
|
||||
const markdown = markdownTurndown.turndown(container).trim();
|
||||
if (!markdown) {
|
||||
return null;
|
||||
}
|
||||
// text/plain carries unescaped Markdown: a plain target shows backslashes literally.
|
||||
// text/html is rendered from escaped Markdown, so literal Markdown characters stay
|
||||
// literal in a rich target.
|
||||
const plainText = plainTurndown.turndown(container).trim();
|
||||
const content = createSelectionClipboardContent(markdown, plainText);
|
||||
return { ...content, html: flattenClipboardListMarkup(content.html) };
|
||||
}
|
||||
|
||||
export function createAssistantSelectionClipboardContent(
|
||||
selection: Selection | null,
|
||||
): MarkdownClipboardContent | null {
|
||||
@@ -145,17 +206,7 @@ export function createAssistantSelectionClipboardContent(
|
||||
container.append(cloneMarkdownSelection(part.range, part.message));
|
||||
}
|
||||
restoreMarkdownElements(container);
|
||||
|
||||
const markdown = markdownTurndown.turndown(container).trim();
|
||||
if (!markdown) {
|
||||
return null;
|
||||
}
|
||||
// text/plain carries unescaped Markdown: a plain target shows backslashes literally.
|
||||
// text/html is rendered from escaped Markdown, so literal Markdown characters stay
|
||||
// literal in a rich target.
|
||||
const plainText = plainTurndown.turndown(container).trim();
|
||||
const content = createSelectionClipboardContent(markdown, plainText);
|
||||
return { ...content, html: flattenClipboardListMarkup(content.html) };
|
||||
return clipboardContentFromMarkup(container);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -702,6 +753,28 @@ function numberOrderedListItems(list: Element, start: number): void {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The library renders an admonition as a box with a generated title. Keep it a quote
|
||||
* with its type, so it copies as its callout source rather than as the title's prose.
|
||||
* Only a whole-element copy does this: a selection cannot tell from its cloned markup
|
||||
* whether it holds the whole callout, so it copies the text it shows.
|
||||
*/
|
||||
function restoreAdmonitions(container: Element): void {
|
||||
const admonitions = Array.from(
|
||||
container.querySelectorAll(`[${MARKDOWN_ADMONITION_TYPE_ATTRIBUTE}]`),
|
||||
);
|
||||
for (const admonition of admonitions.toReversed()) {
|
||||
admonition.querySelector(`:scope > [${MARKDOWN_ADMONITION_TITLE_ATTRIBUTE}]`)?.remove();
|
||||
const quote = document.createElement("blockquote");
|
||||
quote.setAttribute(
|
||||
MARKDOWN_ADMONITION_TYPE_ATTRIBUTE,
|
||||
admonition.getAttribute(MARKDOWN_ADMONITION_TYPE_ATTRIBUTE) ?? "note",
|
||||
);
|
||||
quote.append(...admonition.childNodes);
|
||||
admonition.replaceWith(quote);
|
||||
}
|
||||
}
|
||||
|
||||
function unwrapIncompleteTables(container: HTMLElement): void {
|
||||
for (const table of container.querySelectorAll("table")) {
|
||||
if (hasUsableTableColumnContract(table)) {
|
||||
|
||||
@@ -6,9 +6,13 @@ export const MARKDOWN_COPY_UNWRAP_ATTRIBUTE = "data-paseo-markdown-unwrap";
|
||||
export const MARKDOWN_COPY_RECOGNIZED_LINK_ATTRIBUTE = "data-paseo-markdown-recognized-link";
|
||||
export const MARKDOWN_COPY_LIST_START_ATTRIBUTE = "data-paseo-markdown-list-start";
|
||||
export const MARKDOWN_COPY_LANGUAGE_ATTRIBUTE = "data-paseo-markdown-language";
|
||||
export const MARKDOWN_COPY_FENCE_SOURCE_ATTRIBUTE = "data-paseo-markdown-fence-source";
|
||||
export const MARKDOWN_COPY_ALIGN_ATTRIBUTE = "data-paseo-markdown-align";
|
||||
export const MARKDOWN_COPY_SRC_ATTRIBUTE = "data-paseo-markdown-src";
|
||||
export const MARKDOWN_COPY_ALT_ATTRIBUTE = "data-paseo-markdown-alt";
|
||||
/** Set by the Markdown library's web admonition renderer on the box and on its generated title. */
|
||||
export const MARKDOWN_ADMONITION_TYPE_ATTRIBUTE = "data-enrm-admonition-type";
|
||||
export const MARKDOWN_ADMONITION_TITLE_ATTRIBUTE = "data-enrm-admonition-title";
|
||||
|
||||
/**
|
||||
* Trailing line breaks, with any indentation that followed the last one.
|
||||
|
||||
@@ -16,6 +16,7 @@ function TestIcon() {
|
||||
}
|
||||
|
||||
const LABELS: AgentControlContributionSource["labels"] = {
|
||||
profile: "Profile",
|
||||
model: "Model",
|
||||
thinking: "Thinking",
|
||||
mode: "Mode",
|
||||
@@ -23,6 +24,7 @@ const LABELS: AgentControlContributionSource["labels"] = {
|
||||
fast: "Fast",
|
||||
on: "On",
|
||||
off: "Off",
|
||||
profileKeywords: "profile preset",
|
||||
modelKeywords: "model switch",
|
||||
thinkingKeywords: "reasoning effort",
|
||||
modeKeywords: "access permission",
|
||||
@@ -31,6 +33,7 @@ const LABELS: AgentControlContributionSource["labels"] = {
|
||||
};
|
||||
|
||||
const ICONS: AgentControlContributionSource["icons"] = {
|
||||
profile: () => TestIcon,
|
||||
provider: () => TestIcon,
|
||||
thinking: TestIcon,
|
||||
planMode: TestIcon,
|
||||
@@ -134,6 +137,43 @@ const CLAUDE_MODES: AgentMode[] = [
|
||||
];
|
||||
|
||||
describe("Command Center agent-control contributions", () => {
|
||||
it("offers each profile as a choice that applies it, searchable by its summary", () => {
|
||||
const applied: string[] = [];
|
||||
const contributions = buildAgentControlContributions({
|
||||
...makeSource({ provider: null }),
|
||||
profiles: {
|
||||
rows: [
|
||||
{
|
||||
id: "reviewer",
|
||||
name: "Reviewer",
|
||||
summary: "Claude Code · Opus 5 · Plan",
|
||||
icon: "eye",
|
||||
color: "blue",
|
||||
},
|
||||
],
|
||||
apply: (profileId) => {
|
||||
applied.push(profileId);
|
||||
},
|
||||
},
|
||||
}).filter((contribution) => contribution.group === "profiles");
|
||||
|
||||
expect(contributions).toHaveLength(1);
|
||||
expect(contributions[0]).toMatchObject({
|
||||
id: "profiles:reviewer",
|
||||
groupRank: 0.9,
|
||||
keywords: ["profile preset", "Claude Code · Opus 5 · Plan"],
|
||||
presentation: {
|
||||
kind: "choice",
|
||||
path: ["Profile", "Reviewer"],
|
||||
selected: false,
|
||||
testId: "command-center-profile-host:agent:reviewer",
|
||||
},
|
||||
});
|
||||
contributions[0].run();
|
||||
contributions[0].run();
|
||||
expect(applied).toEqual(["reviewer", "reviewer"]);
|
||||
});
|
||||
|
||||
it("omits mode-derived choices when no mode control is available", () => {
|
||||
const contributions = buildAgentControlContributions({
|
||||
...makeSource({
|
||||
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
import type { CommandCenterContribution, CommandCenterIcon } from "./contributions";
|
||||
|
||||
const GROUP_RANK = {
|
||||
profiles: 0.9,
|
||||
models: 1,
|
||||
thinking: 1.1,
|
||||
modes: 1.2,
|
||||
@@ -24,6 +25,7 @@ const GROUP_RANK = {
|
||||
} as const;
|
||||
|
||||
export interface AgentControlContributionLabels {
|
||||
profile: string;
|
||||
model: string;
|
||||
thinking: string;
|
||||
mode: string;
|
||||
@@ -31,6 +33,7 @@ export interface AgentControlContributionLabels {
|
||||
fast: string;
|
||||
on: string;
|
||||
off: string;
|
||||
profileKeywords: string;
|
||||
modelKeywords: string;
|
||||
thinkingKeywords: string;
|
||||
modeKeywords: string;
|
||||
@@ -42,6 +45,7 @@ export function buildAgentControlContributionLabels(
|
||||
t: (key: string) => string,
|
||||
): AgentControlContributionLabels {
|
||||
return {
|
||||
profile: t("shell.commandCenter.profileGroupLabel"),
|
||||
model: t("shell.commandCenter.modelGroupLabel"),
|
||||
thinking: t("shell.commandCenter.thinkingGroupLabel"),
|
||||
mode: t("shell.commandCenter.modeGroupLabel"),
|
||||
@@ -49,6 +53,7 @@ export function buildAgentControlContributionLabels(
|
||||
fast: t("shell.commandCenter.fastModeGroupLabel"),
|
||||
on: t("shell.commandCenter.settingOn"),
|
||||
off: t("shell.commandCenter.settingOff"),
|
||||
profileKeywords: t("shell.commandCenter.profileSearchKeywords"),
|
||||
modelKeywords: t("shell.commandCenter.modelSearchKeywords"),
|
||||
thinkingKeywords: t("shell.commandCenter.thinkingSearchKeywords"),
|
||||
modeKeywords: t("shell.commandCenter.modeSearchKeywords"),
|
||||
@@ -58,6 +63,7 @@ export function buildAgentControlContributionLabels(
|
||||
}
|
||||
|
||||
export interface AgentControlContributionIcons {
|
||||
profile(profile: AgentControlProfile): CommandCenterIcon;
|
||||
provider(provider: AgentProvider): CommandCenterIcon;
|
||||
thinking: CommandCenterIcon;
|
||||
planMode: CommandCenterIcon;
|
||||
@@ -83,12 +89,27 @@ interface CommandCenterChoiceGroup {
|
||||
choices: readonly CommandCenterChoice[];
|
||||
}
|
||||
|
||||
/** A profile as the command center offers it: applied in one step, never "selected". */
|
||||
export interface AgentControlProfile {
|
||||
id: string;
|
||||
name: string;
|
||||
/** "Claude Code · Opus 5 · Plan · Think hard" */
|
||||
summary: string;
|
||||
icon: string;
|
||||
color: string;
|
||||
}
|
||||
|
||||
export interface AgentControlContributionSource {
|
||||
serverId: string;
|
||||
ownerKey: string;
|
||||
provider: string | null;
|
||||
labels: AgentControlContributionLabels;
|
||||
icons: AgentControlContributionIcons;
|
||||
/** Absent when the host has no profiles to offer this surface. */
|
||||
profiles?: {
|
||||
rows: readonly AgentControlProfile[];
|
||||
apply(profileId: string): void;
|
||||
};
|
||||
models: {
|
||||
providers: readonly ProviderSelectorProvider[];
|
||||
selectedProvider: string | null;
|
||||
@@ -138,6 +159,30 @@ function buildContributions(
|
||||
return contributions;
|
||||
}
|
||||
|
||||
function buildProfileGroup(source: AgentControlContributionSource): CommandCenterChoiceGroup {
|
||||
const profiles = source.profiles;
|
||||
const choices = (profiles?.rows ?? []).map(
|
||||
(profile): CommandCenterChoice => ({
|
||||
id: profile.id,
|
||||
path: [profile.name],
|
||||
keywords: [profile.summary],
|
||||
icon: source.icons.profile(profile),
|
||||
// Applying a profile writes its values and leaves nothing bound to it,
|
||||
// so no profile is ever the current choice.
|
||||
selected: false,
|
||||
testId: `command-center-profile-${source.serverId}:${source.ownerKey}:${profile.id}`,
|
||||
select: () => profiles?.apply(profile.id),
|
||||
}),
|
||||
);
|
||||
return {
|
||||
id: "profiles",
|
||||
rank: GROUP_RANK.profiles,
|
||||
label: source.labels.profile,
|
||||
keywords: [source.labels.profileKeywords],
|
||||
choices,
|
||||
};
|
||||
}
|
||||
|
||||
function buildModelGroup(source: AgentControlContributionSource): CommandCenterChoiceGroup {
|
||||
const choices: CommandCenterChoice[] = [];
|
||||
for (const provider of source.models.providers) {
|
||||
@@ -306,7 +351,7 @@ function buildFastModeGroup(source: AgentControlContributionSource): CommandCent
|
||||
export function buildAgentControlContributions(
|
||||
source: AgentControlContributionSource,
|
||||
): CommandCenterContribution[] {
|
||||
const groups = [buildModelGroup(source)];
|
||||
const groups = [buildProfileGroup(source), buildModelGroup(source)];
|
||||
if (source.provider) {
|
||||
groups.push(
|
||||
buildThinkingGroup(source),
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
PlanModeIcon,
|
||||
ThinkingIcon,
|
||||
} from "@/agent-controls/icons";
|
||||
import { AgentProfileGlyph, type AgentProfilePicker } from "@/agent-profiles";
|
||||
import { useProviderIcons } from "@/components/provider-icons";
|
||||
import type { ComposerOptionControls } from "@/agent-controls/option-controls";
|
||||
import type { ProviderSelectorProvider } from "@/provider-selection/provider-selection";
|
||||
@@ -15,7 +16,9 @@ import {
|
||||
buildAgentControlContributions,
|
||||
buildAgentControlContributionLabels,
|
||||
type AgentControlContributionSource,
|
||||
type AgentControlProfile,
|
||||
} from "./agent-control-contributions";
|
||||
import type { CommandCenterIcon, CommandCenterIconProps } from "./contributions";
|
||||
import { getCommandCenterIcon } from "./icon";
|
||||
import { useCommandCenterActions } from "./provider";
|
||||
|
||||
@@ -24,6 +27,8 @@ export interface AgentControlCommandCenterSource {
|
||||
ownerKey: string;
|
||||
provider: string | null | undefined;
|
||||
providerDefinitions: AgentProviderDefinition[];
|
||||
/** The same profiles the model picker offers this composer; `null` when the host has none. */
|
||||
profiles: AgentProfilePicker | null;
|
||||
models: {
|
||||
providers: readonly ProviderSelectorProvider[];
|
||||
selectedProvider: string | null | undefined;
|
||||
@@ -44,6 +49,27 @@ export interface AgentControlCommandCenterSource {
|
||||
optionControls: ComposerOptionControls | null;
|
||||
}
|
||||
|
||||
const profileIcons = new Map<string, CommandCenterIcon>();
|
||||
|
||||
/** One stable component per icon and colour, so results don't remount on every rebuild. */
|
||||
function getProfileCommandCenterIcon(profile: AgentControlProfile): CommandCenterIcon {
|
||||
const key = `${profile.icon}:${profile.color}`;
|
||||
const cached = profileIcons.get(key);
|
||||
if (cached) return cached;
|
||||
function ProfileCommandCenterIcon({ size }: CommandCenterIconProps) {
|
||||
return <AgentProfileGlyph icon={profile.icon} color={profile.color} size={size} />;
|
||||
}
|
||||
profileIcons.set(key, ProfileCommandCenterIcon);
|
||||
return ProfileCommandCenterIcon;
|
||||
}
|
||||
|
||||
function buildProfileContributionSource(
|
||||
profiles: AgentProfilePicker | null,
|
||||
): Pick<AgentControlContributionSource, "profiles"> {
|
||||
if (!profiles) return {};
|
||||
return { profiles: { rows: profiles.rows, apply: profiles.applyProfile } };
|
||||
}
|
||||
|
||||
const NO_OPTION_CONTROLS: ComposerOptionControls = {
|
||||
controls: [],
|
||||
options: {},
|
||||
@@ -83,7 +109,7 @@ export function useAgentControlCommandCenterActions(input: {
|
||||
}): void {
|
||||
const { t } = useTranslation();
|
||||
const { controls } = input;
|
||||
const { optionControls, models, modes, thinking } = controls;
|
||||
const { optionControls, models, modes, profiles, thinking } = controls;
|
||||
const getProviderIcon = useProviderIcons(controls.serverId);
|
||||
const actions = useMemo(
|
||||
() =>
|
||||
@@ -93,6 +119,7 @@ export function useAgentControlCommandCenterActions(input: {
|
||||
provider: controls.provider ?? null,
|
||||
labels: buildAgentControlContributionLabels(t),
|
||||
icons: {
|
||||
profile: getProfileCommandCenterIcon,
|
||||
provider: (provider) => getCommandCenterIcon(getProviderIcon(provider)),
|
||||
thinking: getCommandCenterIcon(ThinkingIcon),
|
||||
planMode: getCommandCenterIcon(PlanModeIcon),
|
||||
@@ -108,6 +135,7 @@ export function useAgentControlCommandCenterActions(input: {
|
||||
selectedModelId: models.selectedModelId ?? null,
|
||||
select: models.select,
|
||||
},
|
||||
...buildProfileContributionSource(profiles),
|
||||
thinking: {
|
||||
options: thinking.options ?? [],
|
||||
selectedId: thinking.selectedId ?? null,
|
||||
@@ -135,6 +163,7 @@ export function useAgentControlCommandCenterActions(input: {
|
||||
modes?.options,
|
||||
modes?.select,
|
||||
modes?.selectedId,
|
||||
profiles,
|
||||
thinking.options,
|
||||
thinking.select,
|
||||
thinking.selectedId,
|
||||
|
||||
@@ -597,6 +597,16 @@ export interface AdaptiveModalSheetProps {
|
||||
contentStyle?: StyleProp<ViewStyle>;
|
||||
/** Re-establishes caller-owned contexts inside the native or compact sheet portal. */
|
||||
contextBridge?: ContextBridge | null;
|
||||
/**
|
||||
* Keys the body handles while the sheet is the top overlay, such as list navigation. Escape
|
||||
* always closes the sheet. Return true from `onKeyDown` to claim the key.
|
||||
*/
|
||||
keyboard?: SheetKeyboard;
|
||||
}
|
||||
|
||||
export interface SheetKeyboard {
|
||||
keys: readonly string[];
|
||||
onKeyDown: (event: KeyboardInputEvent) => boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -696,6 +706,7 @@ export function AdaptiveModalSheet({
|
||||
contentStyle,
|
||||
bodyStyle,
|
||||
contextBridge = null,
|
||||
keyboard,
|
||||
}: AdaptiveModalSheetProps) {
|
||||
const { t } = useTranslation();
|
||||
const isMobile = useIsCompactFormFactor();
|
||||
@@ -754,16 +765,21 @@ export function AdaptiveModalSheet({
|
||||
|
||||
const handleOverlayKeyDown = useCallback(
|
||||
(event: KeyboardInputEvent) => {
|
||||
if (event.key !== "Escape") return false;
|
||||
if (event.key !== "Escape") {
|
||||
if (!keyboard?.onKeyDown(event)) return false;
|
||||
event.preventDefault();
|
||||
return true;
|
||||
}
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
onClose();
|
||||
return true;
|
||||
},
|
||||
[onClose],
|
||||
[keyboard, onClose],
|
||||
);
|
||||
const overlayKeys = useMemo(() => ["Escape", ...(keyboard?.keys ?? [])], [keyboard?.keys]);
|
||||
const setOverlayScope = useOverlayRegistration({
|
||||
keys: ["Escape"],
|
||||
keys: overlayKeys,
|
||||
active: visible,
|
||||
layer: modalLayer,
|
||||
onKeyDown: handleOverlayKeyDown,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { AddProjectFlow } from "@/components/add-project-flow";
|
||||
import { AddProjectFlow } from "@/add-project-flow";
|
||||
import { useAddProjectFlowStore } from "@/stores/add-project-flow-store";
|
||||
|
||||
export function AddProjectFlowHost() {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -7,7 +7,6 @@ import { FOOTER_HEIGHT } from "@/constants/layout";
|
||||
import { useHostRuntimeClient, useHostRuntimeIsConnected } from "@/runtime/host-runtime";
|
||||
import { KeyboardTranslateView } from "@/keyboard/shift";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useToast } from "@/contexts/toast-context";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
import { toErrorMessage } from "@/utils/error-messages";
|
||||
|
||||
@@ -20,7 +19,6 @@ export function ArchivedAgentCallout({ serverId, agentId }: ArchivedAgentCallout
|
||||
const { t } = useTranslation();
|
||||
const client = useHostRuntimeClient(serverId);
|
||||
const isConnected = useHostRuntimeIsConnected(serverId);
|
||||
const toast = useToast();
|
||||
const [isUnarchiving, setIsUnarchiving] = useState(false);
|
||||
const [unarchiveError, setUnarchiveError] = useState<string | null>(null);
|
||||
|
||||
@@ -29,15 +27,12 @@ export function ArchivedAgentCallout({ serverId, agentId }: ArchivedAgentCallout
|
||||
setIsUnarchiving(true);
|
||||
setUnarchiveError(null);
|
||||
try {
|
||||
const refreshed = await client.refreshAgent(agentId);
|
||||
if (refreshed.historyDiverged) {
|
||||
toast.show(t("workspace.tabs.toasts.reloadedAgentHistoryDiverged"), { variant: "warning" });
|
||||
}
|
||||
await client.refreshAgent(agentId);
|
||||
} catch (error) {
|
||||
setUnarchiveError(toErrorMessage(error));
|
||||
setIsUnarchiving(false);
|
||||
}
|
||||
}, [client, isConnected, isUnarchiving, agentId, toast, t]);
|
||||
}, [client, isConnected, isUnarchiving, agentId]);
|
||||
|
||||
return (
|
||||
<KeyboardTranslateView style={styles.container}>
|
||||
|
||||
@@ -1,17 +1,9 @@
|
||||
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import {
|
||||
Pressable,
|
||||
View,
|
||||
Text,
|
||||
type StyleProp,
|
||||
type TextStyle,
|
||||
type ViewStyle,
|
||||
} from "react-native";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import React, { useCallback, useMemo, useState } from "react";
|
||||
import { View, Text, type StyleProp, type TextStyle, type ViewStyle } from "react-native";
|
||||
import * as Clipboard from "expo-clipboard";
|
||||
import { Check, Copy } from "lucide-react-native";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { HighlightToken } from "@getpaseo/highlight";
|
||||
import { BlockCopyButton } from "@/components/markdown/block-copy-button";
|
||||
import { isNative, isWeb } from "@/constants/platform";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { syntaxTokenStyleFor } from "@/styles/syntax-token-styles";
|
||||
@@ -85,6 +77,7 @@ export const HighlightedCodeBlock = React.memo(function HighlightedCodeBlock({
|
||||
[renderedCode, language],
|
||||
);
|
||||
|
||||
const { t } = useTranslation();
|
||||
const isCompact = useIsCompactFormFactor();
|
||||
const [isHovered, setIsHovered] = useState(false);
|
||||
const handlePointerEnter = useCallback(() => setIsHovered(true), []);
|
||||
@@ -93,7 +86,11 @@ export const HighlightedCodeBlock = React.memo(function HighlightedCodeBlock({
|
||||
// Copy the code without its trailing blank lines. A fence body ends in a newline,
|
||||
// and ends in more than one when the author left a blank line before the closing
|
||||
// fence; pasting any of them into a terminal runs the last line.
|
||||
const getCode = useCallback(() => code.replace(TRAILING_CODE_LINE_BREAKS, ""), [code]);
|
||||
const copyCode = useCallback(async () => {
|
||||
const content = code.replace(TRAILING_CODE_LINE_BREAKS, "");
|
||||
if (!content) return false;
|
||||
return Clipboard.setStringAsync(content);
|
||||
}, [code]);
|
||||
|
||||
return (
|
||||
<View
|
||||
@@ -111,7 +108,11 @@ export const HighlightedCodeBlock = React.memo(function HighlightedCodeBlock({
|
||||
{renderedCode}
|
||||
</Text>
|
||||
)}
|
||||
<CopyButton getCode={getCode} visible={controlsVisible} />
|
||||
<BlockCopyButton
|
||||
onCopy={copyCode}
|
||||
visible={controlsVisible}
|
||||
label={t("message.actions.copyCode")}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
});
|
||||
@@ -168,87 +169,3 @@ function splitFenceStyle(inheritedStyles: TextStyle, textStyle: TextStyle): Spli
|
||||
innerTextStyle: [inheritedStyles, textOnly],
|
||||
};
|
||||
}
|
||||
|
||||
interface CopyButtonProps {
|
||||
getCode: () => string;
|
||||
visible: boolean;
|
||||
}
|
||||
|
||||
const COPIED_RESET_MS = 1500;
|
||||
|
||||
const CopyButton = React.memo(function CopyButton({ getCode, visible }: CopyButtonProps) {
|
||||
const { t } = useTranslation();
|
||||
const [copied, setCopied] = useState(false);
|
||||
const resetRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (resetRef.current) clearTimeout(resetRef.current);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const handlePress = useCallback(async () => {
|
||||
const content = getCode();
|
||||
if (!content) return;
|
||||
await Clipboard.setStringAsync(content);
|
||||
setCopied(true);
|
||||
if (resetRef.current) clearTimeout(resetRef.current);
|
||||
resetRef.current = setTimeout(() => {
|
||||
setCopied(false);
|
||||
resetRef.current = null;
|
||||
}, COPIED_RESET_MS);
|
||||
}, [getCode]);
|
||||
|
||||
const visibilityStyle = visible
|
||||
? copyButtonStyles.containerVisible
|
||||
: copyButtonStyles.containerHidden;
|
||||
const wrapperStyle = useMemo(
|
||||
() => [copyButtonStyles.container, visibilityStyle],
|
||||
[visibilityStyle],
|
||||
);
|
||||
|
||||
return (
|
||||
<Pressable
|
||||
onPress={handlePress}
|
||||
style={wrapperStyle}
|
||||
pointerEvents={visible ? "auto" : "none"}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={copied ? t("message.actions.copied") : t("message.actions.copyCode")}
|
||||
hitSlop={8}
|
||||
dataSet={markdownCopyDataSet.ignore}
|
||||
>
|
||||
{({ hovered }) => {
|
||||
const iconColor = hovered
|
||||
? copyButtonStyles.iconHoveredColor.color
|
||||
: copyButtonStyles.iconColor.color;
|
||||
return copied ? (
|
||||
<Check size={14} color={iconColor} />
|
||||
) : (
|
||||
<Copy size={14} color={iconColor} />
|
||||
);
|
||||
}}
|
||||
</Pressable>
|
||||
);
|
||||
});
|
||||
|
||||
const copyButtonStyles = StyleSheet.create((theme) => ({
|
||||
container: {
|
||||
position: "absolute",
|
||||
top: theme.spacing[2],
|
||||
right: theme.spacing[2],
|
||||
padding: theme.spacing[1],
|
||||
},
|
||||
containerVisible: {
|
||||
opacity: 1,
|
||||
},
|
||||
containerHidden: {
|
||||
opacity: 0,
|
||||
},
|
||||
iconColor: {
|
||||
color: theme.colors.foregroundMuted,
|
||||
},
|
||||
iconHoveredColor: {
|
||||
color: theme.colors.foreground,
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -1,11 +1,28 @@
|
||||
import { useCallback, useMemo, type ReactElement, type ReactNode } from "react";
|
||||
import { Pressable, View } from "react-native";
|
||||
import { Plus, Server, Settings } from "lucide-react-native";
|
||||
import { StyleSheet, useUnistyles } from "react-native-unistyles";
|
||||
import {
|
||||
useCallback,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useState,
|
||||
type ReactElement,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Text, View } from "react-native";
|
||||
import { Check, Plus, Server } from "lucide-react-native";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { HostStatusDot } from "@/components/host-status-dot";
|
||||
import { Combobox, ComboboxItem, type ComboboxProps } from "@/components/ui/combobox";
|
||||
import { Combobox, type ComboboxProps } from "@/components/ui/combobox";
|
||||
import { PressHighlight } from "@/components/ui/press-highlight";
|
||||
import { useLocalDaemonServerId } from "@/hooks/use-is-local-daemon";
|
||||
import { useHostRuntimeSnapshot, type ActiveConnection } from "@/runtime/host-runtime";
|
||||
import { defaultHostAppearance, resolveHostIcon, type HostAppearance } from "@/hosts/appearance";
|
||||
import { HostConnectionLine, HostIconGlyph, HostLatencyLabel } from "@/hosts/host-icon";
|
||||
import {
|
||||
getHostRuntimeStore,
|
||||
useHostRuntimeConnectionStatus,
|
||||
useHosts,
|
||||
} from "@/runtime/host-runtime";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
import { ICON_SIZE, type Theme } from "@/styles/theme";
|
||||
import { orderHostsLocalFirst } from "@/types/host-connection";
|
||||
import {
|
||||
ADD_HOST_OPTION_ID,
|
||||
@@ -22,7 +39,16 @@ export {
|
||||
};
|
||||
|
||||
const SEARCHABLE_THRESHOLD = 10;
|
||||
const DEFAULT_DESKTOP_MIN_WIDTH = 328;
|
||||
const LEADING_RAIL_SIZE = 16;
|
||||
const HOST_ROW_ICON_SIZE = 14;
|
||||
type RenderHostOption = NonNullable<ComboboxProps["renderOption"]>;
|
||||
|
||||
const ThemedCheck = withUnistyles(Check);
|
||||
const ThemedPlus = withUnistyles(Plus);
|
||||
const ThemedServer = withUnistyles(Server);
|
||||
const mutedIconMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
|
||||
|
||||
export interface HostPickerHost {
|
||||
serverId: string;
|
||||
label: string;
|
||||
@@ -36,122 +62,166 @@ export function HostStatusDotSlot({ serverId }: { serverId: string }): ReactElem
|
||||
);
|
||||
}
|
||||
|
||||
// Standard secure/plain web ports carry no information in the host display, so
|
||||
// "relay.paseo.sh:443" reads as "relay.paseo.sh" while "127.0.0.1:6767" is kept.
|
||||
function formatConnectionEndpoint(endpoint: string): string {
|
||||
return endpoint.replace(/:(?:443|80)$/, "");
|
||||
}
|
||||
|
||||
// Socket/pipe transports have no host:port — their endpoint is a filesystem
|
||||
// path, so they read as "Local". TCP and relay show the address being used.
|
||||
function formatActiveConnectionLabel(connection: ActiveConnection): string {
|
||||
if (connection.type === "directSocket" || connection.type === "directPipe") {
|
||||
return "Local";
|
||||
}
|
||||
return formatConnectionEndpoint(connection.endpoint);
|
||||
}
|
||||
|
||||
export interface HostPickerOptionProps {
|
||||
serverId: string;
|
||||
label: string;
|
||||
showActiveConnection: boolean;
|
||||
appearance: HostAppearance;
|
||||
selected?: boolean;
|
||||
active: boolean;
|
||||
onPress: () => void;
|
||||
onOpenHostSettings?: (serverId: string) => void;
|
||||
testID?: string;
|
||||
}
|
||||
|
||||
export function HostPickerOption({
|
||||
serverId,
|
||||
label,
|
||||
showActiveConnection,
|
||||
appearance,
|
||||
selected,
|
||||
active,
|
||||
onPress,
|
||||
onOpenHostSettings,
|
||||
testID,
|
||||
}: HostPickerOptionProps): ReactElement {
|
||||
const { theme } = useUnistyles();
|
||||
const activeConnection = useHostRuntimeSnapshot(serverId)?.activeConnection ?? null;
|
||||
const connectionLabel =
|
||||
showActiveConnection && activeConnection
|
||||
? formatActiveConnectionLabel(activeConnection)
|
||||
: undefined;
|
||||
const leadingSlot = useMemo(() => <HostStatusDotSlot serverId={serverId} />, [serverId]);
|
||||
const handleSettingsPress = useCallback(() => {
|
||||
onOpenHostSettings?.(serverId);
|
||||
}, [onOpenHostSettings, serverId]);
|
||||
const trailingAction = useMemo(() => {
|
||||
if (!onOpenHostSettings) return undefined;
|
||||
return (
|
||||
<Pressable
|
||||
onPress={handleSettingsPress}
|
||||
style={styles.settingsAction}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={`Open ${label} settings`}
|
||||
>
|
||||
<Settings size={theme.iconSize.sm} color={theme.colors.foregroundMuted} />
|
||||
</Pressable>
|
||||
);
|
||||
}, [
|
||||
handleSettingsPress,
|
||||
label,
|
||||
onOpenHostSettings,
|
||||
theme.colors.foregroundMuted,
|
||||
theme.iconSize.sm,
|
||||
]);
|
||||
const status = useHostRuntimeConnectionStatus(serverId);
|
||||
const detectedMachineKind = useSessionStore(
|
||||
(state) => state.sessions[serverId]?.serverInfo?.machineKind ?? null,
|
||||
);
|
||||
const resolvedIcon = resolveHostIcon({ appearance, detectedMachineKind });
|
||||
const [hovered, setHovered] = useState(false);
|
||||
const handlePointerEnter = useCallback(() => setHovered(true), []);
|
||||
const handlePointerLeave = useCallback(() => setHovered(false), []);
|
||||
const isOffline = status === "offline" || status === "error";
|
||||
|
||||
return (
|
||||
<ComboboxItem
|
||||
label={label}
|
||||
description={connectionLabel}
|
||||
leadingSlot={leadingSlot}
|
||||
trailingAction={trailingAction}
|
||||
selected={selected}
|
||||
active={active}
|
||||
onPress={onPress}
|
||||
testID={testID}
|
||||
/>
|
||||
<View
|
||||
style={styles.rowEnvelope}
|
||||
onPointerEnter={handlePointerEnter}
|
||||
onPointerLeave={handlePointerLeave}
|
||||
>
|
||||
<PressHighlight
|
||||
testID={testID}
|
||||
onPress={onPress}
|
||||
highlightStyle={styles.rowHighlighted}
|
||||
style={[styles.hostRow, (hovered || active) && styles.rowHighlighted]}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={label}
|
||||
>
|
||||
<View style={styles.leadingRailSlot}>
|
||||
<HostStatusDot serverId={serverId} />
|
||||
</View>
|
||||
<View style={styles.hostBody}>
|
||||
<View style={styles.hostHeaderRow}>
|
||||
<HostIconGlyph
|
||||
icon={resolvedIcon}
|
||||
color={appearance.color}
|
||||
size={HOST_ROW_ICON_SIZE}
|
||||
style={styles.hostGlyph}
|
||||
/>
|
||||
<Text style={[styles.hostName, isOffline && styles.hostNameMuted]} numberOfLines={1}>
|
||||
{label}
|
||||
</Text>
|
||||
</View>
|
||||
<HostConnectionLine serverId={serverId} />
|
||||
</View>
|
||||
<View style={styles.hostTrailing}>
|
||||
<HostLatencyLabel serverId={serverId} />
|
||||
{selected ? <ThemedCheck size={ICON_SIZE.sm} uniProps={mutedIconMapping} /> : null}
|
||||
</View>
|
||||
</PressHighlight>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const SYSTEM_HOST_PICKER_OPTION_LABELS: Record<"add" | "all" | "enableBuiltInDaemon", string> = {
|
||||
add: "Add host",
|
||||
all: "All hosts",
|
||||
enableBuiltInDaemon: "Enable built-in daemon",
|
||||
};
|
||||
|
||||
function SystemHostPickerOption({
|
||||
function AllHostsOption({
|
||||
active,
|
||||
selected,
|
||||
onPress,
|
||||
kind,
|
||||
testID,
|
||||
}: {
|
||||
active: boolean;
|
||||
selected?: boolean;
|
||||
onPress: () => void;
|
||||
kind: "add" | "all" | "enableBuiltInDaemon";
|
||||
testID?: string;
|
||||
}): ReactElement {
|
||||
const { theme } = useUnistyles();
|
||||
const Icon = kind === "add" ? Plus : Server;
|
||||
const label = SYSTEM_HOST_PICKER_OPTION_LABELS[kind];
|
||||
const leadingSlot = useMemo(
|
||||
() => <Icon size={theme.iconSize.sm} color={theme.colors.foregroundMuted} />,
|
||||
[Icon, theme.colors.foregroundMuted, theme.iconSize.sm],
|
||||
);
|
||||
const { t } = useTranslation();
|
||||
const [hovered, setHovered] = useState(false);
|
||||
const handlePointerEnter = useCallback(() => setHovered(true), []);
|
||||
const handlePointerLeave = useCallback(() => setHovered(false), []);
|
||||
const label = t("sidebar.display.hostFilter.all");
|
||||
|
||||
return (
|
||||
<ComboboxItem
|
||||
label={label}
|
||||
leadingSlot={leadingSlot}
|
||||
selected={selected}
|
||||
active={active}
|
||||
onPress={onPress}
|
||||
testID={testID}
|
||||
/>
|
||||
<View
|
||||
style={styles.rowEnvelope}
|
||||
onPointerEnter={handlePointerEnter}
|
||||
onPointerLeave={handlePointerLeave}
|
||||
>
|
||||
<PressHighlight
|
||||
testID={testID}
|
||||
onPress={onPress}
|
||||
highlightStyle={styles.rowHighlighted}
|
||||
style={[styles.actionRow, (hovered || active) && styles.rowHighlighted]}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={label}
|
||||
>
|
||||
<View style={styles.leadingRailSlot}>
|
||||
<ThemedServer size={LEADING_RAIL_SIZE} uniProps={mutedIconMapping} />
|
||||
</View>
|
||||
<Text style={styles.actionLabel} numberOfLines={1}>
|
||||
{label}
|
||||
</Text>
|
||||
{selected ? <ThemedCheck size={ICON_SIZE.sm} uniProps={mutedIconMapping} /> : null}
|
||||
</PressHighlight>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function ActionOptionRow({
|
||||
kind,
|
||||
active,
|
||||
showDivider,
|
||||
onPress,
|
||||
testID,
|
||||
}: {
|
||||
kind: "add" | "enableBuiltInDaemon";
|
||||
active: boolean;
|
||||
showDivider: boolean;
|
||||
onPress: () => void;
|
||||
testID?: string;
|
||||
}): ReactElement {
|
||||
const { t } = useTranslation();
|
||||
const [hovered, setHovered] = useState(false);
|
||||
const handlePointerEnter = useCallback(() => setHovered(true), []);
|
||||
const handlePointerLeave = useCallback(() => setHovered(false), []);
|
||||
const label = kind === "add" ? t("settings.addHost") : t("settings.enableBuiltInDaemon");
|
||||
|
||||
return (
|
||||
<View>
|
||||
{showDivider ? <View style={styles.actionSectionDivider} /> : null}
|
||||
<View
|
||||
style={styles.rowEnvelope}
|
||||
onPointerEnter={handlePointerEnter}
|
||||
onPointerLeave={handlePointerLeave}
|
||||
>
|
||||
<PressHighlight
|
||||
testID={testID}
|
||||
onPress={onPress}
|
||||
highlightStyle={styles.rowHighlighted}
|
||||
style={[styles.actionRow, (hovered || active) && styles.rowHighlighted]}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={label}
|
||||
>
|
||||
<View style={styles.leadingRailSlot}>
|
||||
{kind === "add" ? (
|
||||
<ThemedPlus size={LEADING_RAIL_SIZE} uniProps={mutedIconMapping} />
|
||||
) : (
|
||||
<ThemedServer size={LEADING_RAIL_SIZE} uniProps={mutedIconMapping} />
|
||||
)}
|
||||
</View>
|
||||
<Text style={styles.actionLabel} numberOfLines={1}>
|
||||
{label}
|
||||
</Text>
|
||||
</PressHighlight>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -168,7 +238,6 @@ export interface HostPickerProps {
|
||||
includeEnableBuiltInDaemon?: boolean;
|
||||
onEnableBuiltInDaemon?: () => void;
|
||||
showActiveConnection?: boolean;
|
||||
onOpenHostSettings?: (serverId: string) => void;
|
||||
searchable?: boolean;
|
||||
title?: string;
|
||||
desktopPlacement?: ComboboxProps["desktopPlacement"];
|
||||
@@ -190,74 +259,85 @@ export function HostPicker({
|
||||
onAddHost,
|
||||
includeEnableBuiltInDaemon,
|
||||
onEnableBuiltInDaemon,
|
||||
showActiveConnection,
|
||||
onOpenHostSettings,
|
||||
searchable,
|
||||
title,
|
||||
desktopPlacement = "bottom-start",
|
||||
desktopMinWidth,
|
||||
desktopMinWidth = DEFAULT_DESKTOP_MIN_WIDTH,
|
||||
addHostTestID,
|
||||
hostOptionTestID,
|
||||
children,
|
||||
}: HostPickerProps): ReactElement {
|
||||
const { t } = useTranslation();
|
||||
const localServerId = useLocalDaemonServerId();
|
||||
const allHostProfiles = useHosts();
|
||||
const orderedHosts = useMemo(
|
||||
() => orderHostsLocalFirst(hosts, localServerId),
|
||||
[hosts, localServerId],
|
||||
);
|
||||
|
||||
const appearanceByServerId = useMemo(() => {
|
||||
const map = new Map<string, HostAppearance>();
|
||||
for (const profile of allHostProfiles) {
|
||||
map.set(profile.serverId, profile.appearance);
|
||||
}
|
||||
return map;
|
||||
}, [allHostProfiles]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
getHostRuntimeStore().refreshActiveLatencies(orderedHosts.map((host) => host.serverId));
|
||||
}, [open, orderedHosts]);
|
||||
|
||||
const options = useMemo(() => {
|
||||
const hostOptions = orderedHosts.map((host) => ({ id: host.serverId, label: host.label }));
|
||||
if (includeAllHost) hostOptions.unshift({ id: ALL_HOSTS_OPTION_ID, label: "All hosts" });
|
||||
if (includeAddHost) hostOptions.push({ id: ADD_HOST_OPTION_ID, label: "Add host" });
|
||||
if (includeEnableBuiltInDaemon)
|
||||
if (includeAllHost) {
|
||||
hostOptions.unshift({ id: ALL_HOSTS_OPTION_ID, label: t("sidebar.display.hostFilter.all") });
|
||||
}
|
||||
if (includeAddHost) {
|
||||
hostOptions.push({ id: ADD_HOST_OPTION_ID, label: t("settings.addHost") });
|
||||
}
|
||||
if (includeEnableBuiltInDaemon) {
|
||||
hostOptions.push({
|
||||
id: ENABLE_BUILT_IN_DAEMON_OPTION_ID,
|
||||
label: "Enable built-in daemon",
|
||||
label: t("settings.enableBuiltInDaemon"),
|
||||
});
|
||||
}
|
||||
return hostOptions;
|
||||
}, [orderedHosts, includeAllHost, includeAddHost, includeEnableBuiltInDaemon]);
|
||||
}, [orderedHosts, includeAllHost, includeAddHost, includeEnableBuiltInDaemon, t]);
|
||||
|
||||
let firstActionOptionId: string | null = null;
|
||||
if (includeAddHost) {
|
||||
firstActionOptionId = ADD_HOST_OPTION_ID;
|
||||
} else if (includeEnableBuiltInDaemon) {
|
||||
firstActionOptionId = ENABLE_BUILT_IN_DAEMON_OPTION_ID;
|
||||
}
|
||||
|
||||
const isSearchable = searchable === true && orderedHosts.length > SEARCHABLE_THRESHOLD;
|
||||
const resolvedTitle = title ?? t("sidebar.actions.hosts");
|
||||
|
||||
const handleSelect = useCallback(
|
||||
(id: string) => {
|
||||
if (id === ADD_HOST_OPTION_ID) {
|
||||
onOpenChange(false);
|
||||
onAddHost?.();
|
||||
} else if (id === ENABLE_BUILT_IN_DAEMON_OPTION_ID) {
|
||||
onEnableBuiltInDaemon?.();
|
||||
} else {
|
||||
onSelect(id);
|
||||
return;
|
||||
}
|
||||
if (id === ENABLE_BUILT_IN_DAEMON_OPTION_ID) {
|
||||
onOpenChange(false);
|
||||
onEnableBuiltInDaemon?.();
|
||||
return;
|
||||
}
|
||||
onSelect(id);
|
||||
onOpenChange(false);
|
||||
},
|
||||
[onAddHost, onEnableBuiltInDaemon, onOpenChange, onSelect],
|
||||
);
|
||||
|
||||
const handleOpenHostSettings = useCallback(
|
||||
(serverId: string) => {
|
||||
onOpenHostSettings?.(serverId);
|
||||
onOpenChange(false);
|
||||
},
|
||||
[onOpenHostSettings, onOpenChange],
|
||||
);
|
||||
|
||||
const renderOption = useCallback<RenderHostOption>(
|
||||
({ option, selected, active, onPress }) => {
|
||||
if (option.id === ADD_HOST_OPTION_ID) {
|
||||
return (
|
||||
<SystemHostPickerOption
|
||||
kind="add"
|
||||
active={active}
|
||||
onPress={onPress}
|
||||
testID={addHostTestID}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (option.id === ALL_HOSTS_OPTION_ID) {
|
||||
return (
|
||||
<SystemHostPickerOption
|
||||
kind="all"
|
||||
<AllHostsOption
|
||||
active={active}
|
||||
selected={selected}
|
||||
onPress={onPress}
|
||||
@@ -265,30 +345,48 @@ export function HostPicker({
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (option.id === ENABLE_BUILT_IN_DAEMON_OPTION_ID) {
|
||||
if (option.id === ADD_HOST_OPTION_ID) {
|
||||
return (
|
||||
<SystemHostPickerOption kind="enableBuiltInDaemon" active={active} onPress={onPress} />
|
||||
<ActionOptionRow
|
||||
kind="add"
|
||||
active={active}
|
||||
showDivider={firstActionOptionId === ADD_HOST_OPTION_ID && orderedHosts.length > 0}
|
||||
onPress={onPress}
|
||||
testID={addHostTestID}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (option.id === ENABLE_BUILT_IN_DAEMON_OPTION_ID) {
|
||||
return (
|
||||
<ActionOptionRow
|
||||
kind="enableBuiltInDaemon"
|
||||
active={active}
|
||||
showDivider={
|
||||
firstActionOptionId === ENABLE_BUILT_IN_DAEMON_OPTION_ID && orderedHosts.length > 0
|
||||
}
|
||||
onPress={onPress}
|
||||
/>
|
||||
);
|
||||
}
|
||||
const appearance = appearanceByServerId.get(option.id) ?? defaultHostAppearance();
|
||||
return (
|
||||
<HostPickerOption
|
||||
serverId={option.id}
|
||||
label={option.label}
|
||||
showActiveConnection={showActiveConnection === true}
|
||||
appearance={appearance}
|
||||
selected={selected}
|
||||
active={active}
|
||||
onPress={onPress}
|
||||
onOpenHostSettings={onOpenHostSettings ? handleOpenHostSettings : undefined}
|
||||
testID={hostOptionTestID?.(option.id)}
|
||||
/>
|
||||
);
|
||||
},
|
||||
[
|
||||
addHostTestID,
|
||||
appearanceByServerId,
|
||||
firstActionOptionId,
|
||||
hostOptionTestID,
|
||||
onOpenHostSettings,
|
||||
showActiveConnection,
|
||||
handleOpenHostSettings,
|
||||
orderedHosts.length,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -301,8 +399,8 @@ export function HostPicker({
|
||||
onSelect={handleSelect}
|
||||
renderOption={renderOption}
|
||||
searchable={isSearchable}
|
||||
searchPlaceholder="Search hosts"
|
||||
title={title ?? "Host"}
|
||||
searchPlaceholder={t("sidebar.host.searchPlaceholder")}
|
||||
title={resolvedTitle}
|
||||
open={open}
|
||||
onOpenChange={onOpenChange}
|
||||
anchorRef={anchorRef}
|
||||
@@ -314,16 +412,86 @@ export function HostPicker({
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
settingsAction: {
|
||||
flex: 1,
|
||||
justifyContent: "center",
|
||||
paddingLeft: theme.spacing[1],
|
||||
paddingRight: theme.spacing[3],
|
||||
},
|
||||
statusDotSlot: {
|
||||
width: theme.iconSize.sm,
|
||||
height: theme.iconSize.sm,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
rowEnvelope: {
|
||||
position: "relative",
|
||||
},
|
||||
// Shared leading rail: the status dot on host rows and the '+' / All hosts glyph share one
|
||||
// centered 16px column aligned to the first line's 18px line-height.
|
||||
leadingRailSlot: {
|
||||
width: LEADING_RAIL_SIZE,
|
||||
height: 18,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
flexShrink: 0,
|
||||
},
|
||||
hostRow: {
|
||||
flexDirection: "row",
|
||||
alignItems: "flex-start",
|
||||
gap: theme.spacing[2],
|
||||
marginHorizontal: theme.spacing[1],
|
||||
paddingHorizontal: theme.spacing[2],
|
||||
paddingVertical: theme.spacing[2],
|
||||
borderRadius: theme.borderRadius.md,
|
||||
},
|
||||
rowHighlighted: {
|
||||
backgroundColor: theme.colors.surface1,
|
||||
},
|
||||
hostBody: {
|
||||
flex: 1,
|
||||
minWidth: 0,
|
||||
gap: 2,
|
||||
},
|
||||
hostHeaderRow: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: 6,
|
||||
minWidth: 0,
|
||||
},
|
||||
hostGlyph: {
|
||||
flexShrink: 0,
|
||||
},
|
||||
hostName: {
|
||||
flex: 1,
|
||||
minWidth: 0,
|
||||
fontSize: theme.fontSize.base,
|
||||
lineHeight: 18,
|
||||
color: theme.colors.foreground,
|
||||
},
|
||||
hostNameMuted: {
|
||||
color: theme.colors.foregroundMuted,
|
||||
},
|
||||
hostTrailing: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
height: 18,
|
||||
gap: theme.spacing[2],
|
||||
flexShrink: 0,
|
||||
},
|
||||
actionSectionDivider: {
|
||||
height: theme.borderWidth[1],
|
||||
backgroundColor: theme.colors.border,
|
||||
marginVertical: theme.spacing[1],
|
||||
},
|
||||
actionRow: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[2],
|
||||
marginHorizontal: theme.spacing[1],
|
||||
paddingHorizontal: theme.spacing[2],
|
||||
paddingVertical: theme.spacing[2],
|
||||
borderRadius: theme.borderRadius.md,
|
||||
},
|
||||
actionLabel: {
|
||||
flex: 1,
|
||||
minWidth: 0,
|
||||
fontSize: theme.fontSize.base,
|
||||
lineHeight: 18,
|
||||
color: theme.colors.foreground,
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import Svg, { Circle } from "react-native-svg";
|
||||
|
||||
const TAILSCALE_DOTS = [3, 12, 21].flatMap((cy, row) =>
|
||||
[3, 12, 21].map((cx, column) => ({
|
||||
cx,
|
||||
cy,
|
||||
// The Tailscale mark is a 3x3 dot grid with a solid T (middle row + bottom center).
|
||||
solid: row === 1 || (row === 2 && column === 1),
|
||||
})),
|
||||
);
|
||||
|
||||
export interface TailscaleIconProps {
|
||||
size?: number;
|
||||
color?: string;
|
||||
}
|
||||
|
||||
export function TailscaleIcon({ size = 12, color = "currentColor" }: TailscaleIconProps) {
|
||||
return (
|
||||
<Svg width={size} height={size} viewBox="0 0 24 24" fill={color}>
|
||||
{TAILSCALE_DOTS.map((dot) => (
|
||||
<Circle
|
||||
key={`${dot.cx}:${dot.cy}`}
|
||||
cx={dot.cx}
|
||||
cy={dot.cy}
|
||||
r={3}
|
||||
fill={color}
|
||||
opacity={dot.solid ? 1 : 0.3}
|
||||
/>
|
||||
))}
|
||||
</Svg>
|
||||
);
|
||||
}
|
||||
@@ -388,10 +388,10 @@ function SidebarHostPicker({
|
||||
includeAddHost
|
||||
onAddHost={onAddHost}
|
||||
showActiveConnection
|
||||
onOpenHostSettings={onOpenHostSettings}
|
||||
searchable
|
||||
title={label}
|
||||
desktopPlacement="top-start"
|
||||
desktopMinWidth={240}
|
||||
desktopMinWidth={328}
|
||||
addHostTestID="sidebar-host-add"
|
||||
hostOptionTestID={sidebarHostOptionTestID}
|
||||
>
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
import { flushSync } from "react-dom";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { within } from "@testing-library/dom";
|
||||
import { userEvent } from "vitest/browser";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { I18nextProvider } from "react-i18next";
|
||||
import type { ToastApi } from "@/components/toast-host";
|
||||
import { ToastApiProvider } from "@/contexts/toast-api-context";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
import { BlockCopyButton } from "./block-copy-button";
|
||||
|
||||
const LABEL = "Copy quote";
|
||||
|
||||
let errors: string[] = [];
|
||||
const toast: ToastApi = {
|
||||
show: () => () => {},
|
||||
copied: () => {},
|
||||
error: (message) => errors.push(message),
|
||||
};
|
||||
|
||||
describe("BlockCopyButton", () => {
|
||||
let root: Root;
|
||||
let host: HTMLDivElement;
|
||||
|
||||
beforeEach(async () => {
|
||||
await i18n.changeLanguage("en");
|
||||
errors = [];
|
||||
host = document.createElement("div");
|
||||
document.body.append(host);
|
||||
root = createRoot(host);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
flushSync(() => root.unmount());
|
||||
host.remove();
|
||||
});
|
||||
|
||||
function render(onCopy: () => Promise<boolean>, visible = true) {
|
||||
flushSync(() =>
|
||||
root.render(
|
||||
<I18nextProvider i18n={i18n}>
|
||||
<ToastApiProvider api={toast}>
|
||||
<BlockCopyButton onCopy={onCopy} visible={visible} label={LABEL} />
|
||||
</ToastApiProvider>
|
||||
</I18nextProvider>,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function button(name = LABEL): HTMLElement {
|
||||
return within(host).getByRole("button", { name });
|
||||
}
|
||||
|
||||
it("shows Copied after a write and returns to its label", async () => {
|
||||
let calls = 0;
|
||||
render(async () => {
|
||||
calls += 1;
|
||||
return true;
|
||||
});
|
||||
|
||||
await userEvent.click(button());
|
||||
await vi.waitFor(() => expect(button("Copied")).toBeTruthy());
|
||||
await vi.waitFor(() => expect(button()).toBeTruthy(), { timeout: 2500 });
|
||||
expect(calls).toBe(1);
|
||||
expect(errors).toEqual([]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["resolves false", async () => false],
|
||||
[
|
||||
"rejects",
|
||||
async (): Promise<boolean> => {
|
||||
throw new Error("Clipboard denied");
|
||||
},
|
||||
],
|
||||
])("tells the user and never shows Copied when the write %s", async (_case, failure) => {
|
||||
let calls = 0;
|
||||
render(() => {
|
||||
calls += 1;
|
||||
return calls === 1 ? failure() : Promise.resolve(true);
|
||||
});
|
||||
|
||||
await userEvent.click(button());
|
||||
await vi.waitFor(() => expect(errors).toEqual(["Unable to copy"]));
|
||||
expect(within(host).queryByRole("button", { name: "Copied" })).toBeNull();
|
||||
|
||||
await userEvent.click(button());
|
||||
await vi.waitFor(() => expect(button("Copied")).toBeTruthy());
|
||||
expect(calls).toBe(2);
|
||||
});
|
||||
|
||||
it("does not write twice while a write is pending", async () => {
|
||||
let finish!: (written: boolean) => void;
|
||||
let calls = 0;
|
||||
render(() => {
|
||||
calls += 1;
|
||||
return new Promise<boolean>((resolve) => {
|
||||
finish = resolve;
|
||||
});
|
||||
});
|
||||
|
||||
await userEvent.click(button());
|
||||
await userEvent.click(button());
|
||||
expect(calls).toBe(1);
|
||||
|
||||
finish(true);
|
||||
await vi.waitFor(() => expect(button("Copied")).toBeTruthy());
|
||||
expect(calls).toBe(1);
|
||||
});
|
||||
|
||||
it("stays hidden until its block reveals it or it takes keyboard focus", async () => {
|
||||
render(async () => true, false);
|
||||
expect(getComputedStyle(button()).opacity).toBe("0");
|
||||
|
||||
await userEvent.tab();
|
||||
expect(document.activeElement).toBe(button());
|
||||
await vi.waitFor(() => expect(getComputedStyle(button()).opacity).toBe("1"));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,109 @@
|
||||
import { memo, useCallback, useEffect, useRef, useState } from "react";
|
||||
import { View } from "react-native";
|
||||
import { Check, Copy } from "lucide-react-native";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { markdownCopyDataSet } from "@/assistant-selection-copy/markup";
|
||||
import { mutedIconColorMapping } from "@/components/ui/icon-color";
|
||||
import { smallIconButtonChromeFrameSize } from "@/components/ui/icon-button-chrome";
|
||||
import { paneContentToolbarIconSize, ToolbarButton } from "@/components/ui/pane-content-toolbar";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { useToast } from "@/contexts/toast-api-context";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
|
||||
const ThemedCopy = withUnistyles(Copy, mutedIconColorMapping);
|
||||
const ThemedCheck = withUnistyles(Check, mutedIconColorMapping);
|
||||
|
||||
const COPIED_RESET_MS = 1500;
|
||||
|
||||
/** How far the copy glyph sits from the top and trailing edges of its block. */
|
||||
export function blockCopyGlyphInset(theme: Theme): number {
|
||||
return theme.spacing[2] + theme.spacing[1];
|
||||
}
|
||||
|
||||
interface BlockCopyButtonProps {
|
||||
/** Writes the block to the clipboard. Resolves false, or rejects, when nothing was written. */
|
||||
onCopy: () => Promise<boolean>;
|
||||
/** The block's own reveal state. Keyboard focus shows the button regardless. */
|
||||
visible: boolean;
|
||||
label: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* The copy control in the top trailing corner of a Markdown block. The block is its
|
||||
* positioned ancestor.
|
||||
*/
|
||||
export const BlockCopyButton = memo(function BlockCopyButton({
|
||||
onCopy,
|
||||
visible,
|
||||
label,
|
||||
}: BlockCopyButtonProps) {
|
||||
const { t } = useTranslation();
|
||||
const toast = useToast();
|
||||
const compact = useIsCompactFormFactor();
|
||||
const [copied, setCopied] = useState(false);
|
||||
const [focused, setFocused] = useState(false);
|
||||
const writing = useRef(false);
|
||||
const resetRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const focus = useCallback(() => setFocused(true), []);
|
||||
const blur = useCallback(() => setFocused(false), []);
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (resetRef.current) clearTimeout(resetRef.current);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const handlePress = useCallback(async () => {
|
||||
// A slow clipboard must not queue a second write behind the first.
|
||||
if (writing.current) return;
|
||||
writing.current = true;
|
||||
const written = await onCopy()
|
||||
.catch(() => false)
|
||||
.finally(() => {
|
||||
writing.current = false;
|
||||
});
|
||||
if (!written) {
|
||||
toast.error(t("common.errors.unableToCopy"));
|
||||
return;
|
||||
}
|
||||
setCopied(true);
|
||||
if (resetRef.current) clearTimeout(resetRef.current);
|
||||
resetRef.current = setTimeout(() => setCopied(false), COPIED_RESET_MS);
|
||||
}, [onCopy, t, toast]);
|
||||
|
||||
const shown = visible || focused;
|
||||
const Glyph = copied ? ThemedCheck : ThemedCopy;
|
||||
return (
|
||||
<View style={styles.corner(compact)} dataSet={markdownCopyDataSet.ignore}>
|
||||
<ToolbarButton
|
||||
compact={compact}
|
||||
label={copied ? t("message.actions.copied") : label}
|
||||
onPress={handlePress}
|
||||
onFocus={focus}
|
||||
onBlur={blur}
|
||||
style={shown ? styles.shown : styles.hidden}
|
||||
>
|
||||
<Glyph size={paneContentToolbarIconSize(compact)} />
|
||||
</ToolbarButton>
|
||||
</View>
|
||||
);
|
||||
});
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
// The glyph, not the button frame, sits on the inset; the frame overhangs it.
|
||||
corner: (compact: boolean) => {
|
||||
const frameOverhang =
|
||||
(smallIconButtonChromeFrameSize(compact) - paneContentToolbarIconSize(compact)) / 2;
|
||||
const inset = blockCopyGlyphInset(theme) - frameOverhang;
|
||||
return {
|
||||
position: "absolute" as const,
|
||||
top: inset,
|
||||
right: inset,
|
||||
pointerEvents: "box-none" as const,
|
||||
};
|
||||
},
|
||||
shown: { opacity: 1, pointerEvents: "auto" },
|
||||
hidden: { opacity: 0, pointerEvents: "none" },
|
||||
}));
|
||||
@@ -5,6 +5,10 @@ import { useTranslation } from "react-i18next";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { HighlightedCodeBlock } from "@/components/highlighted-code-block";
|
||||
import { ZoomableViewport } from "@/components/zoomable-viewport";
|
||||
import {
|
||||
MARKDOWN_COPY_FENCE_SOURCE_ATTRIBUTE,
|
||||
MARKDOWN_COPY_LANGUAGE_ATTRIBUTE,
|
||||
} from "@/assistant-selection-copy/markup";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
import type { MarkdownFenceRendererProps } from "./types";
|
||||
import { MermaidFullscreenViewer } from "./fullscreen-viewer.web";
|
||||
@@ -81,6 +85,16 @@ function MermaidFenceHostImpl({
|
||||
[visible],
|
||||
);
|
||||
const sourceVisible = !diagramVisible;
|
||||
// A visible diagram stands in for its fence, so copying the surrounding block takes
|
||||
// the source from here: the revision on screen, which lags `code` while a streamed
|
||||
// revision renders. The source view copies as its own code block.
|
||||
const diagramCopyAttributes =
|
||||
diagramVisible && visible
|
||||
? {
|
||||
[MARKDOWN_COPY_FENCE_SOURCE_ATTRIBUTE]: visible.source,
|
||||
[MARKDOWN_COPY_LANGUAGE_ATTRIBUTE]: "mermaid",
|
||||
}
|
||||
: null;
|
||||
const viewportStyle = diagramVisible ? diagramStyle : measuringStyle;
|
||||
|
||||
return (
|
||||
@@ -111,7 +125,7 @@ function MermaidFenceHostImpl({
|
||||
) : null}
|
||||
</View>
|
||||
) : null}
|
||||
<div inert={!diagramVisible} style={boundaryStyle}>
|
||||
<div inert={!diagramVisible} style={boundaryStyle} {...diagramCopyAttributes}>
|
||||
<ZoomableViewport
|
||||
accessibilityLabel={t("message.diagram.diagram")}
|
||||
actions={actions}
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import { useCallback, useMemo, useRef, useState } from "react";
|
||||
import { withUnistyles } from "react-native-unistyles";
|
||||
import type { BlockquoteRendererProps } from "react-native-enriched-markdown";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { createElementClipboardContent } from "@/assistant-selection-copy/content.web";
|
||||
import { smallIconButtonChromeFrameSize } from "@/components/ui/icon-button-chrome";
|
||||
import { paneContentToolbarIconSize } from "@/components/ui/pane-content-toolbar";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { writeClipboardContent } from "@/utils/rich-clipboard";
|
||||
import { getDefaultMarkdownClipboardEnvironment } from "@/utils/rich-clipboard-default-environment";
|
||||
import { BlockCopyButton, blockCopyGlyphInset } from "./block-copy-button";
|
||||
|
||||
interface WebBlockquoteProps extends BlockquoteRendererProps {
|
||||
copyGlyphInset: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Room the quote reserves so the control never covers its text. Compact layouts always
|
||||
* show the control, so it gets a band above the body and the text keeps the full width.
|
||||
* Wide layouts reveal it on hover, where a band would leave an empty strip above every
|
||||
* quote, so the text wraps short of it instead.
|
||||
*/
|
||||
function copyRoom(compact: boolean, glyphInset: number) {
|
||||
if (compact) {
|
||||
return { paddingTop: glyphInset + paneContentToolbarIconSize(compact) + glyphInset };
|
||||
}
|
||||
return { paddingRight: smallIconButtonChromeFrameSize(compact) + glyphInset };
|
||||
}
|
||||
|
||||
/** A quote with a control that copies its body, for drafts an agent wrote to be pasted elsewhere. */
|
||||
export const WebBlockquote = withUnistyles(
|
||||
function WebBlockquote({ blockquoteProps, children, copyGlyphInset }: WebBlockquoteProps) {
|
||||
const { t } = useTranslation();
|
||||
const quote = useRef<HTMLQuoteElement>(null);
|
||||
const [hovered, setHovered] = useState(false);
|
||||
const compact = useIsCompactFormFactor();
|
||||
const enter = useCallback(() => setHovered(true), []);
|
||||
const leave = useCallback(() => setHovered(false), []);
|
||||
const style = useMemo(
|
||||
() => ({
|
||||
...blockquoteProps.style,
|
||||
position: "relative" as const,
|
||||
...copyRoom(compact, copyGlyphInset),
|
||||
}),
|
||||
[blockquoteProps.style, compact, copyGlyphInset],
|
||||
);
|
||||
const copy = useCallback(async () => {
|
||||
// Read the rendered body at press time: a streaming quote copies what it shows now.
|
||||
const content = quote.current && createElementClipboardContent(quote.current);
|
||||
if (!content) return false;
|
||||
return writeClipboardContent(content, getDefaultMarkdownClipboardEnvironment());
|
||||
}, []);
|
||||
return (
|
||||
<blockquote
|
||||
{...blockquoteProps}
|
||||
ref={quote}
|
||||
style={style}
|
||||
onPointerEnter={enter}
|
||||
onPointerLeave={leave}
|
||||
>
|
||||
<BlockCopyButton
|
||||
onCopy={copy}
|
||||
visible={hovered || compact}
|
||||
label={t("message.actions.copyQuote")}
|
||||
/>
|
||||
{children}
|
||||
</blockquote>
|
||||
);
|
||||
},
|
||||
(theme) => ({ copyGlyphInset: blockCopyGlyphInset(theme) }),
|
||||
);
|
||||
@@ -14,6 +14,7 @@ import { HighlightedCodeBlock } from "@/components/highlighted-code-block";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
import { MermaidFence } from "./fence/mermaid";
|
||||
import { isRecognizedLink, markdownLinkSource } from "./source";
|
||||
import { WebBlockquote } from "./quote-block.web";
|
||||
|
||||
const ThemedCodeBlock = withUnistyles(HighlightedCodeBlock);
|
||||
const codeStyle = (theme: Theme) => ({
|
||||
@@ -111,4 +112,8 @@ const styles = StyleSheet.create((theme) => ({
|
||||
},
|
||||
}));
|
||||
|
||||
export const WEB_RENDERERS: MarkdownRenderers = { codeBlock: WebCodeBlock, link: WebLink };
|
||||
export const WEB_RENDERERS: MarkdownRenderers = {
|
||||
codeBlock: WebCodeBlock,
|
||||
link: WebLink,
|
||||
blockquote: WebBlockquote,
|
||||
};
|
||||
|
||||
@@ -6,6 +6,7 @@ import type {
|
||||
import {
|
||||
resolveInitialModelBrowserView,
|
||||
resolveModelBrowserAllView,
|
||||
filterAndRankProfileRows,
|
||||
groupProfilesByProviderModel,
|
||||
resolveModelBrowserScrolling,
|
||||
} from "./model-browser-view";
|
||||
@@ -155,7 +156,12 @@ describe("model browser all view", () => {
|
||||
|
||||
it("browses providers while the query is empty", () => {
|
||||
expect(
|
||||
resolveModelBrowserAllView({ providers, normalizedQuery: "", isSearchFocused: false }),
|
||||
resolveModelBrowserAllView({
|
||||
providers,
|
||||
profiles: [],
|
||||
normalizedQuery: "",
|
||||
isSearchFocused: false,
|
||||
}),
|
||||
).toEqual({
|
||||
kind: "browse",
|
||||
});
|
||||
@@ -164,6 +170,7 @@ describe("model browser all view", () => {
|
||||
it("shows every searchable model as soon as empty search receives focus", () => {
|
||||
const view = resolveModelBrowserAllView({
|
||||
providers,
|
||||
profiles: [],
|
||||
normalizedQuery: "",
|
||||
isSearchFocused: true,
|
||||
});
|
||||
@@ -180,6 +187,7 @@ describe("model browser all view", () => {
|
||||
it("ranks the same model label across every provider that offers it", () => {
|
||||
const view = resolveModelBrowserAllView({
|
||||
providers,
|
||||
profiles: [],
|
||||
normalizedQuery: "opus",
|
||||
isSearchFocused: true,
|
||||
});
|
||||
@@ -194,6 +202,7 @@ describe("model browser all view", () => {
|
||||
it("matches models by their provider label", () => {
|
||||
const view = resolveModelBrowserAllView({
|
||||
providers,
|
||||
profiles: [],
|
||||
normalizedQuery: "codex",
|
||||
isSearchFocused: true,
|
||||
});
|
||||
@@ -207,6 +216,7 @@ describe("model browser all view", () => {
|
||||
expect(
|
||||
resolveModelBrowserAllView({
|
||||
providers,
|
||||
profiles: [],
|
||||
normalizedQuery: "zzzz",
|
||||
isSearchFocused: true,
|
||||
}),
|
||||
@@ -228,9 +238,48 @@ describe("model browser all view", () => {
|
||||
expect(
|
||||
resolveModelBrowserAllView({
|
||||
providers: [loading, failed],
|
||||
profiles: [],
|
||||
normalizedQuery: "opus",
|
||||
isSearchFocused: true,
|
||||
}),
|
||||
).toEqual({ kind: "noSearchMatches" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("model browser profile search", () => {
|
||||
const claude = provider("claude", "Claude Code", [
|
||||
modelRow("claude", "Claude Code", "opus-5", "Opus 5"),
|
||||
]);
|
||||
const reviewer = { id: "reviewer", name: "Reviewer", summary: "Claude Code · Opus 5 · Plan" };
|
||||
const quick = { id: "quick", name: "Quick fix", summary: "Codex · GPT-5.4" };
|
||||
const profiles = [reviewer, quick];
|
||||
|
||||
it("offers profiles whose name matches the query", () => {
|
||||
const view = resolveModelBrowserAllView({
|
||||
providers: [claude],
|
||||
profiles,
|
||||
normalizedQuery: "review",
|
||||
isSearchFocused: true,
|
||||
});
|
||||
|
||||
expect(view).toEqual({ kind: "searchResults", profiles: [reviewer], rows: [] });
|
||||
});
|
||||
|
||||
it("offers profiles whose summary names the queried model next to the model itself", () => {
|
||||
const view = resolveModelBrowserAllView({
|
||||
providers: [claude],
|
||||
profiles,
|
||||
normalizedQuery: "opus",
|
||||
isSearchFocused: true,
|
||||
});
|
||||
|
||||
expect(view.kind === "searchResults" ? view.profiles : []).toEqual([reviewer]);
|
||||
expect(view.kind === "searchResults" ? view.rows.map((row) => row.modelId) : []).toEqual([
|
||||
"opus-5",
|
||||
]);
|
||||
});
|
||||
|
||||
it("lists every profile while the focused query is empty", () => {
|
||||
expect(filterAndRankProfileRows(profiles, "")).toEqual(profiles);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { compareMatchScores, scoreTextFields } from "@getpaseo/protocol/search/text-match";
|
||||
import {
|
||||
filterAndRankModelRows,
|
||||
getAllProviderModelRows,
|
||||
@@ -49,30 +50,55 @@ export function groupProfilesByProviderModel<T extends ModelProfileRef>(
|
||||
return lookup;
|
||||
}
|
||||
|
||||
/** What a profile row offers search: its name and its "Claude Code · Opus 5 · Plan" summary. */
|
||||
export interface SearchableProfileRow {
|
||||
name: string;
|
||||
summary: string;
|
||||
}
|
||||
|
||||
/** Profiles matching the query, best first. An empty query keeps every profile in order. */
|
||||
export function filterAndRankProfileRows<T extends SearchableProfileRow>(
|
||||
rows: readonly T[],
|
||||
normalizedQuery: string,
|
||||
): T[] {
|
||||
if (!normalizedQuery) return [...rows];
|
||||
return rows
|
||||
.map((row) => ({ row, score: scoreTextFields(normalizedQuery, [row.name, row.summary]) }))
|
||||
.filter((entry): entry is { row: T; score: NonNullable<typeof entry.score> } =>
|
||||
Boolean(entry.score),
|
||||
)
|
||||
.sort((a, b) => compareMatchScores(a.score, b.score) || a.row.name.localeCompare(b.row.name))
|
||||
.map((entry) => entry.row);
|
||||
}
|
||||
|
||||
/** What the root view shows: the provider drill-down, or ranked cross-provider results. */
|
||||
export type ModelBrowserAllView =
|
||||
export type ModelBrowserAllView<T extends SearchableProfileRow> =
|
||||
| { kind: "browse" }
|
||||
| { kind: "searchResults"; rows: ProviderSelectionModelRow[] }
|
||||
| { kind: "searchResults"; profiles: T[]; rows: ProviderSelectionModelRow[] }
|
||||
| { kind: "noSearchMatches" };
|
||||
|
||||
export function resolveModelBrowserAllView({
|
||||
export function resolveModelBrowserAllView<T extends SearchableProfileRow>({
|
||||
providers,
|
||||
profiles,
|
||||
normalizedQuery,
|
||||
isSearchFocused,
|
||||
}: {
|
||||
providers: ProviderSelectorProvider[];
|
||||
/** Profiles the search may offer; empty when the surface shows none. */
|
||||
profiles: readonly T[];
|
||||
normalizedQuery: string;
|
||||
isSearchFocused: boolean;
|
||||
}): ModelBrowserAllView {
|
||||
}): ModelBrowserAllView<T> {
|
||||
if (!normalizedQuery && !isSearchFocused) {
|
||||
return { kind: "browse" };
|
||||
}
|
||||
const allRows = getAllProviderModelRows(providers);
|
||||
const rows = normalizedQuery ? filterAndRankModelRows(allRows, normalizedQuery) : allRows;
|
||||
if (rows.length === 0) {
|
||||
const matchedProfiles = filterAndRankProfileRows(profiles, normalizedQuery);
|
||||
if (rows.length === 0 && matchedProfiles.length === 0) {
|
||||
return { kind: "noSearchMatches" };
|
||||
}
|
||||
return { kind: "searchResults", rows };
|
||||
return { kind: "searchResults", profiles: matchedProfiles, rows };
|
||||
}
|
||||
|
||||
/** Where the picker lands when it opens. A sole provider skips the redundant root view. */
|
||||
|
||||
@@ -56,6 +56,7 @@ import { useProviderSettingsStore } from "@/stores/provider-settings-store";
|
||||
import { useCurrentOverlayLayer } from "@/lib/overlay-root";
|
||||
import { ICON_SIZE, type Theme } from "@/styles/theme";
|
||||
import {
|
||||
filterAndRankProfileRows,
|
||||
groupProfilesByProviderModel,
|
||||
resolveInitialModelBrowserView,
|
||||
resolveModelBrowserAllView,
|
||||
@@ -984,6 +985,38 @@ function AgentProfilesPickerContent({
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Profiles that match a search, above the matching models. The models get their
|
||||
* own heading so they don't read as part of the profiles section.
|
||||
*/
|
||||
function ProfileSearchResultsHeader({
|
||||
rows,
|
||||
hasModelRows,
|
||||
onApplyProfile,
|
||||
onEditProfiles,
|
||||
}: {
|
||||
rows: AgentProfilePickerRowModel[];
|
||||
hasModelRows: boolean;
|
||||
onApplyProfile?: (profileId: string) => void;
|
||||
onEditProfiles?: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<View>
|
||||
<AgentProfilesPickerSection
|
||||
rows={rows}
|
||||
onApplyProfile={onApplyProfile}
|
||||
onEditProfiles={onEditProfiles}
|
||||
/>
|
||||
{hasModelRows ? (
|
||||
<View style={styles.sectionHeading}>
|
||||
<Text style={styles.sectionHeadingText}>{t("modelSelector.models")}</Text>
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function GroupProviderButton({
|
||||
provider,
|
||||
serverId,
|
||||
@@ -1320,24 +1353,39 @@ function ProviderModelBrowserContent({
|
||||
() => profiles?.rows.filter((row) => row.provider === view.providerId) ?? [],
|
||||
[profiles, view.providerId],
|
||||
);
|
||||
const profileHeader = useMemo(
|
||||
() =>
|
||||
normalizedQuery.length === 0 && showProfilesSection && profiles ? (
|
||||
const matchedProfileRows = useMemo(
|
||||
() => filterAndRankProfileRows(providerProfileRows, normalizedQuery),
|
||||
[normalizedQuery, providerProfileRows],
|
||||
);
|
||||
const profileHeader = useMemo(() => {
|
||||
if (!showProfilesSection || !profiles) return undefined;
|
||||
if (normalizedQuery.length === 0) {
|
||||
return (
|
||||
<AgentProfilesPickerContent
|
||||
rows={providerProfileRows}
|
||||
onApplyProfile={onApplyProfile}
|
||||
onEditProfiles={onEditProfiles}
|
||||
/>
|
||||
) : undefined,
|
||||
[
|
||||
normalizedQuery,
|
||||
onApplyProfile,
|
||||
onEditProfiles,
|
||||
profiles,
|
||||
providerProfileRows,
|
||||
showProfilesSection,
|
||||
],
|
||||
);
|
||||
);
|
||||
}
|
||||
return matchedProfileRows.length > 0 ? (
|
||||
<ProfileSearchResultsHeader
|
||||
rows={matchedProfileRows}
|
||||
hasModelRows={visibleRows.length > 0}
|
||||
onApplyProfile={onApplyProfile}
|
||||
onEditProfiles={onEditProfiles}
|
||||
/>
|
||||
) : undefined;
|
||||
}, [
|
||||
matchedProfileRows,
|
||||
normalizedQuery,
|
||||
onApplyProfile,
|
||||
onEditProfiles,
|
||||
profiles,
|
||||
providerProfileRows,
|
||||
showProfilesSection,
|
||||
visibleRows.length,
|
||||
]);
|
||||
|
||||
if (!provider) return <ModelSearchEmptyState />;
|
||||
const selection = provider.modelSelection;
|
||||
@@ -1361,8 +1409,9 @@ function ProviderModelBrowserContent({
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (visibleRows.length === 0) {
|
||||
return profileHeader ?? <ModelSearchEmptyState />;
|
||||
// Profile-only results still go through the list: it owns scrolling.
|
||||
if (visibleRows.length === 0 && !profileHeader) {
|
||||
return <ModelSearchEmptyState />;
|
||||
}
|
||||
return (
|
||||
<ModelRowList
|
||||
@@ -1416,16 +1465,33 @@ function ModelBrowserContent({
|
||||
: null,
|
||||
[providers, view],
|
||||
);
|
||||
const searchableProfileRows = useMemo(
|
||||
() => (showProfilesSection ? (profiles?.rows ?? []) : []),
|
||||
[profiles, showProfilesSection],
|
||||
);
|
||||
const allView = useMemo(
|
||||
() =>
|
||||
resolveModelBrowserAllView({
|
||||
providers,
|
||||
profiles: searchableProfileRows,
|
||||
normalizedQuery,
|
||||
isSearchFocused: searchAllOnFocus && isSearchFocused,
|
||||
}),
|
||||
[isSearchFocused, normalizedQuery, providers, searchAllOnFocus],
|
||||
[isSearchFocused, normalizedQuery, providers, searchAllOnFocus, searchableProfileRows],
|
||||
);
|
||||
const hasResults = profiles !== null || providers.length > 0 || rootBrowseContent != null;
|
||||
const searchResultsHeader = useMemo(
|
||||
() =>
|
||||
allView.kind === "searchResults" && allView.profiles.length > 0 ? (
|
||||
<ProfileSearchResultsHeader
|
||||
rows={allView.profiles}
|
||||
hasModelRows={allView.rows.length > 0}
|
||||
onApplyProfile={onApplyProfile}
|
||||
onEditProfiles={onEditProfiles}
|
||||
/>
|
||||
) : undefined,
|
||||
[allView, onApplyProfile, onEditProfiles],
|
||||
);
|
||||
|
||||
if (view.kind === "provider") {
|
||||
return (
|
||||
@@ -1471,6 +1537,7 @@ function ModelBrowserContent({
|
||||
selectedModel={selectedModel}
|
||||
onSelect={onSelect}
|
||||
showProviderLabel
|
||||
header={searchResultsHeader}
|
||||
scrolling={scrolling}
|
||||
profiledLookup={profiledLookup}
|
||||
onCreateProfile={onCreateProfile}
|
||||
|
||||
@@ -9,7 +9,6 @@ import { useRewindComposerRestore } from "./composer-restore";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
import { shouldRestoreComposerForRewindMode } from "./rewind-mode";
|
||||
import { getHostRuntimeStore } from "@/runtime/host-runtime";
|
||||
import { hostSupportsFeature } from "@/runtime/host-features";
|
||||
|
||||
interface UseRewindAgentMutationInput {
|
||||
serverId?: string;
|
||||
@@ -43,16 +42,7 @@ export function useRewindAgentMutation(input: UseRewindAgentMutationInput): {
|
||||
throw new Error(t("common.errors.daemonClientUnavailable"));
|
||||
}
|
||||
await input.client.rewindAgent(input.agentId, input.messageId, mode);
|
||||
// COMPAT(timelineRewindOperations): added in v0.14.1, remove after 2027-05-10. A daemon with
|
||||
// the feature delivers the rewind on the live timeline; an older one replaced the timeline
|
||||
// and this client has to read it again.
|
||||
const appliesLive =
|
||||
input.serverId !== undefined &&
|
||||
hostSupportsFeature(
|
||||
useSessionStore.getState().sessions[input.serverId]?.serverInfo,
|
||||
"timelineRewindOperations",
|
||||
);
|
||||
if (mode !== "files" && !appliesLive) {
|
||||
if (mode !== "files") {
|
||||
const cursor = input.serverId
|
||||
? useSessionStore
|
||||
.getState()
|
||||
|
||||
@@ -73,9 +73,12 @@ export { buildDesktopFrameStyle } from "./combobox-frame-style";
|
||||
|
||||
const IS_WEB = isWeb;
|
||||
const TRAILING_ACTION_DATASET = { comboboxTrailingAction: true };
|
||||
const FOOTER_DATASET = { comboboxFooter: true };
|
||||
const FOCUSED_COMBOBOX_ACTION_SELECTOR =
|
||||
'[data-combobox-trailing-action] button, [data-combobox-trailing-action] [role="button"], [data-combobox-footer] button, [data-combobox-footer] [role="button"]';
|
||||
|
||||
export type ComboboxOption = ComboboxOptionModel;
|
||||
export type ComboboxDesktopPlacement = "top-start" | "bottom-start";
|
||||
export type ComboboxDesktopPlacement = "top-start" | "bottom-start" | "bottom-end";
|
||||
|
||||
export interface ComboboxProps {
|
||||
options: ComboboxOption[];
|
||||
@@ -91,6 +94,11 @@ export interface ComboboxProps {
|
||||
searchable?: boolean;
|
||||
/** The caller answers the search query itself, so the options are shown as given. */
|
||||
remoteSearch?: boolean;
|
||||
/**
|
||||
* With `remoteSearch`, the options still answer an earlier query. No option is picked until
|
||||
* the user moves to one, so Enter cannot confirm a row the new query may not match.
|
||||
*/
|
||||
remoteSearchPending?: boolean;
|
||||
placeholder?: string;
|
||||
searchPlaceholder?: string;
|
||||
emptyText?: string;
|
||||
@@ -402,6 +410,7 @@ export function ComboboxEmpty({ children }: { children: ReactNode }): ReactEleme
|
||||
type RenderOptionFn = NonNullable<ComboboxProps["renderOption"]>;
|
||||
|
||||
interface OptionRowProps {
|
||||
index: number;
|
||||
option: ComboboxOption;
|
||||
selected: boolean;
|
||||
active: boolean;
|
||||
@@ -409,20 +418,27 @@ interface OptionRowProps {
|
||||
renderOption: RenderOptionFn | undefined;
|
||||
}
|
||||
|
||||
function OptionRow({ option, selected, active, onSelect, renderOption }: OptionRowProps) {
|
||||
function OptionRow({ index, option, selected, active, onSelect, renderOption }: OptionRowProps) {
|
||||
const handlePress = useCallback(() => onSelect(option.id), [onSelect, option.id]);
|
||||
const optionDataset = useMemo(() => ({ comboboxOptionIndex: String(index) }), [index]);
|
||||
if (renderOption) {
|
||||
return <View>{renderOption({ option, selected, active, onPress: handlePress })}</View>;
|
||||
return (
|
||||
<View dataSet={optionDataset}>
|
||||
{renderOption({ option, selected, active, onPress: handlePress })}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<ComboboxItem
|
||||
label={option.label}
|
||||
description={option.description}
|
||||
kind={option.kind}
|
||||
selected={selected}
|
||||
active={active}
|
||||
onPress={handlePress}
|
||||
/>
|
||||
<View dataSet={optionDataset}>
|
||||
<ComboboxItem
|
||||
label={option.label}
|
||||
description={option.description}
|
||||
kind={option.kind}
|
||||
selected={selected}
|
||||
active={active}
|
||||
onPress={handlePress}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -451,6 +467,7 @@ function OptionsList({
|
||||
{options.map((opt, index) => (
|
||||
<OptionRow
|
||||
key={opt.id}
|
||||
index={index}
|
||||
option={opt}
|
||||
selected={opt.id === value}
|
||||
active={index === activeIndex}
|
||||
@@ -598,6 +615,7 @@ interface DesktopKeyHandlerInput {
|
||||
isOpen: boolean;
|
||||
orderedVisibleOptions: ComboboxOption[];
|
||||
activeIndex: number;
|
||||
remoteSearchPending: boolean;
|
||||
setActiveIndex: React.Dispatch<React.SetStateAction<number>>;
|
||||
handleSelect: (id: string) => void;
|
||||
handleClose: () => void;
|
||||
@@ -610,7 +628,9 @@ function handleDesktopArrowKey(input: DesktopKeyHandlerInput, key: "ArrowDown" |
|
||||
function handleDesktopEnterKey(input: DesktopKeyHandlerInput) {
|
||||
if (input.orderedVisibleOptions.length === 0) return;
|
||||
const { activeIndex, orderedVisibleOptions } = input;
|
||||
const index = activeIndex >= 0 && activeIndex < orderedVisibleOptions.length ? activeIndex : 0;
|
||||
const picked = activeIndex >= 0 && activeIndex < orderedVisibleOptions.length;
|
||||
if (!picked && input.remoteSearchPending) return;
|
||||
const index = picked ? activeIndex : 0;
|
||||
input.handleSelect(orderedVisibleOptions[index].id);
|
||||
}
|
||||
|
||||
@@ -666,18 +686,21 @@ function useActiveIndexSync(
|
||||
effectiveOptionsPosition: "below-search" | "above-search",
|
||||
normalizedSearch: string,
|
||||
value: string,
|
||||
remoteSearchPending: boolean,
|
||||
setActiveIndex: React.Dispatch<React.SetStateAction<number>>,
|
||||
) {
|
||||
useEffect(() => {
|
||||
if (!isOpen) return;
|
||||
if (!IS_WEB && isMobile) return;
|
||||
setActiveIndex(
|
||||
resolveInitialActiveIndex(
|
||||
orderedVisibleOptions,
|
||||
effectiveOptionsPosition,
|
||||
normalizedSearch,
|
||||
value,
|
||||
),
|
||||
remoteSearchPending
|
||||
? -1
|
||||
: resolveInitialActiveIndex(
|
||||
orderedVisibleOptions,
|
||||
effectiveOptionsPosition,
|
||||
normalizedSearch,
|
||||
value,
|
||||
),
|
||||
);
|
||||
}, [
|
||||
effectiveOptionsPosition,
|
||||
@@ -686,6 +709,7 @@ function useActiveIndexSync(
|
||||
normalizedSearch,
|
||||
value,
|
||||
orderedVisibleOptions,
|
||||
remoteSearchPending,
|
||||
setActiveIndex,
|
||||
]);
|
||||
}
|
||||
@@ -952,8 +976,9 @@ function dispatchDesktopKey(
|
||||
return true;
|
||||
}
|
||||
if (key === "Enter") {
|
||||
// Consume the shortcut but keep the browser's default button activation.
|
||||
if (isWeb && document.activeElement?.matches("[data-combobox-trailing-action] button")) {
|
||||
// Consume the shortcut but keep the browser's default button activation when the user moved
|
||||
// keyboard focus onto a trailing action or footer button inside the combobox.
|
||||
if (isWeb && document.activeElement?.matches(FOCUSED_COMBOBOX_ACTION_SELECTOR)) {
|
||||
return true;
|
||||
}
|
||||
if (input.orderedVisibleOptions.length === 0) return false;
|
||||
@@ -1127,7 +1152,12 @@ function ComboboxSheetFrame({ footer, children }: { footer?: ReactNode; children
|
||||
[safeAreaBottom],
|
||||
);
|
||||
const footerView = useMemo(
|
||||
() => (footer ? <View style={footerStyle}>{footer}</View> : undefined),
|
||||
() =>
|
||||
footer ? (
|
||||
<View style={footerStyle} dataSet={FOOTER_DATASET}>
|
||||
{footer}
|
||||
</View>
|
||||
) : undefined,
|
||||
[footer, footerStyle],
|
||||
);
|
||||
return (
|
||||
@@ -1341,7 +1371,11 @@ function DesktopComboboxBody(props: DesktopBodyProps): ReactElement | null {
|
||||
renderOption={props.renderOption}
|
||||
/>
|
||||
)}
|
||||
{props.footer ? <View style={styles.footer}>{props.footer}</View> : null}
|
||||
{props.footer ? (
|
||||
<View style={styles.footer} dataSet={FOOTER_DATASET}>
|
||||
{props.footer}
|
||||
</View>
|
||||
) : null}
|
||||
</FloatingSurface>
|
||||
</View>
|
||||
</OverlayLayerProvider>
|
||||
@@ -1376,6 +1410,7 @@ export function Combobox({
|
||||
onSearchQueryChange,
|
||||
searchable = true,
|
||||
remoteSearch,
|
||||
remoteSearchPending,
|
||||
placeholder,
|
||||
searchPlaceholder,
|
||||
emptyText,
|
||||
@@ -1594,9 +1629,34 @@ export function Combobox({
|
||||
effectiveOptionsPosition,
|
||||
normalizedSearch,
|
||||
value,
|
||||
remoteSearchPending === true,
|
||||
setActiveIndex,
|
||||
);
|
||||
|
||||
// Keep activeIndex aligned when a keyboard user Tabs onto a specific option button on web.
|
||||
useEffect(() => {
|
||||
if (!IS_WEB || !isOpen || isMobile) return;
|
||||
const handleFocusIn = (event: FocusEvent) => {
|
||||
const target = event.target;
|
||||
if (!(target instanceof Element)) return;
|
||||
const optionEl = target.closest("[data-combobox-option-index]");
|
||||
if (!optionEl) return;
|
||||
const nextIndex = Number.parseInt(
|
||||
optionEl.getAttribute("data-combobox-option-index") ?? "",
|
||||
10,
|
||||
);
|
||||
if (
|
||||
Number.isInteger(nextIndex) &&
|
||||
nextIndex >= 0 &&
|
||||
nextIndex < orderedVisibleOptions.length
|
||||
) {
|
||||
setActiveIndex(nextIndex);
|
||||
}
|
||||
};
|
||||
document.addEventListener("focusin", handleFocusIn);
|
||||
return () => document.removeEventListener("focusin", handleFocusIn);
|
||||
}, [isMobile, isOpen, orderedVisibleOptions.length]);
|
||||
|
||||
const handleSelect = useCallback(
|
||||
(id: string) => {
|
||||
onSelect(id);
|
||||
@@ -1617,6 +1677,7 @@ export function Combobox({
|
||||
isOpen,
|
||||
orderedVisibleOptions,
|
||||
activeIndex,
|
||||
remoteSearchPending: remoteSearchPending === true,
|
||||
setActiveIndex,
|
||||
handleSelect,
|
||||
handleClose,
|
||||
@@ -1625,7 +1686,7 @@ export function Combobox({
|
||||
event,
|
||||
);
|
||||
},
|
||||
[activeIndex, handleClose, handleSelect, isOpen, orderedVisibleOptions],
|
||||
[activeIndex, handleClose, handleSelect, isOpen, orderedVisibleOptions, remoteSearchPending],
|
||||
);
|
||||
|
||||
useDismissKeyboardOnOpen(isOpen, isMobile);
|
||||
|
||||
@@ -75,6 +75,10 @@ export function Field({ label, children, trailing, hint, error, testID }: FieldP
|
||||
|
||||
type FormTextInputProps = AdaptiveTextInputProps & {
|
||||
size?: ControlSize;
|
||||
/** A glyph inside the field before the text, such as a search icon. */
|
||||
leading?: ReactNode;
|
||||
/** The value is rejected; the border and focus ring turn to the danger color. */
|
||||
invalid?: boolean;
|
||||
};
|
||||
|
||||
type FlatFormTextInputStyle = ViewStyle & TextStyle;
|
||||
@@ -166,7 +170,10 @@ function assignTextInputRef(
|
||||
}
|
||||
|
||||
export const FormTextInput = forwardRef<EditingTextInputHandle, FormTextInputProps>(
|
||||
function FormTextInput({ size: sizeProp, style, onFocus, onBlur, editable, ...props }, ref) {
|
||||
function FormTextInput(
|
||||
{ size: sizeProp, leading, invalid = false, style, onFocus, onBlur, editable, ...props },
|
||||
ref,
|
||||
) {
|
||||
const [focused, setFocused] = useState(false);
|
||||
const containedSize = useContainedControlSize();
|
||||
const size = sizeProp ?? containedSize ?? "md";
|
||||
@@ -202,6 +209,7 @@ export const FormTextInput = forwardRef<EditingTextInputHandle, FormTextInputPro
|
||||
({ hovered = false }: PressableStateCallbackType & { hovered?: boolean }) => [
|
||||
formInputStyles.chrome,
|
||||
chromeSizeStyle,
|
||||
leading ? formInputStyles.chromeWithLeading : null,
|
||||
resolveControlInteractionStyles(
|
||||
{
|
||||
controlRest: formInputStyles.controlRest,
|
||||
@@ -215,13 +223,15 @@ export const FormTextInput = forwardRef<EditingTextInputHandle, FormTextInputPro
|
||||
disabled: isDisabled,
|
||||
},
|
||||
),
|
||||
invalid ? formInputStyles.controlInvalid : null,
|
||||
splitStyle.chromeStyle,
|
||||
],
|
||||
[chromeSizeStyle, focused, isDisabled, splitStyle.chromeStyle],
|
||||
[chromeSizeStyle, focused, invalid, isDisabled, leading, splitStyle.chromeStyle],
|
||||
);
|
||||
|
||||
return (
|
||||
<Pressable disabled={isDisabled} style={chromeStyle}>
|
||||
{leading}
|
||||
<AdaptiveTextInput
|
||||
ref={setInputRef}
|
||||
editable={editable}
|
||||
@@ -271,6 +281,11 @@ const formInputStyles = StyleSheet.create((theme) => {
|
||||
chrome: {
|
||||
backgroundColor: theme.colors.surface2,
|
||||
},
|
||||
chromeWithLeading: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
chromeSm: {
|
||||
...geometry.fieldControlSm,
|
||||
},
|
||||
@@ -289,6 +304,11 @@ const formInputStyles = StyleSheet.create((theme) => {
|
||||
controlDisabled: {
|
||||
...geometry.controlDisabled,
|
||||
},
|
||||
// Matches the inline error under the field (docs/design.md, Errors).
|
||||
controlInvalid: {
|
||||
borderColor: theme.colors.palette.red[300],
|
||||
outlineColor: theme.colors.palette.red[300],
|
||||
},
|
||||
input: {
|
||||
flex: 1,
|
||||
minWidth: 0,
|
||||
|
||||
@@ -29,6 +29,8 @@ interface SegmentedControlProps<T extends string> {
|
||||
onValueChange: (value: T) => void;
|
||||
size?: ControlSize;
|
||||
hideLabels?: boolean;
|
||||
/** Share the container's width equally between the segments, for a control that heads a surface. */
|
||||
fill?: boolean;
|
||||
style?: StyleProp<ViewStyle>;
|
||||
testID?: string;
|
||||
}
|
||||
@@ -54,6 +56,7 @@ export function SegmentedControl<T extends string>({
|
||||
onValueChange,
|
||||
size: sizeProp,
|
||||
hideLabels = false,
|
||||
fill = false,
|
||||
style,
|
||||
testID,
|
||||
}: SegmentedControlProps<T>) {
|
||||
@@ -85,6 +88,7 @@ export function SegmentedControl<T extends string>({
|
||||
isSelected={isSelected}
|
||||
iconSize={iconSize}
|
||||
hideLabels={hideLabels}
|
||||
fill={fill}
|
||||
segmentSizeStyle={segmentSizeStyle}
|
||||
labelSizeStyle={labelSizeStyle}
|
||||
currentValue={value}
|
||||
@@ -101,6 +105,7 @@ function SegmentItem<T extends string>({
|
||||
isSelected,
|
||||
iconSize,
|
||||
hideLabels,
|
||||
fill,
|
||||
segmentSizeStyle,
|
||||
labelSizeStyle,
|
||||
currentValue,
|
||||
@@ -110,6 +115,7 @@ function SegmentItem<T extends string>({
|
||||
isSelected: boolean;
|
||||
iconSize: number;
|
||||
hideLabels: boolean;
|
||||
fill: boolean;
|
||||
segmentSizeStyle: StyleProp<ViewStyle>;
|
||||
labelSizeStyle: StyleProp<TextStyle>;
|
||||
currentValue: T | null;
|
||||
@@ -128,12 +134,13 @@ function SegmentItem<T extends string>({
|
||||
({ hovered, pressed }: PressableStateCallbackType & { hovered?: boolean }) => [
|
||||
styles.segment,
|
||||
segmentSizeStyle,
|
||||
fill && styles.segmentFill,
|
||||
isSelected && styles.segmentSelected,
|
||||
Boolean(hovered) && !isSelected && styles.segmentHover,
|
||||
pressed && !isSelected && styles.segmentPressed,
|
||||
option.disabled && styles.segmentDisabled,
|
||||
],
|
||||
[isSelected, option.disabled, segmentSizeStyle],
|
||||
[fill, isSelected, option.disabled, segmentSizeStyle],
|
||||
);
|
||||
const accessibilityState = useMemo(
|
||||
() => ({ selected: isSelected, disabled: option.disabled }),
|
||||
@@ -203,6 +210,12 @@ const styles = StyleSheet.create((theme) => {
|
||||
segmentMd: {
|
||||
...geometry.segmentedSegmentMd,
|
||||
},
|
||||
segmentFill: {
|
||||
flexGrow: 1,
|
||||
flexBasis: 0,
|
||||
flexShrink: 1,
|
||||
minWidth: 0,
|
||||
},
|
||||
segmentSelected: {
|
||||
backgroundColor: theme.colors.surface3,
|
||||
},
|
||||
|
||||
@@ -1209,6 +1209,7 @@ export const AgentControls = memo(function AgentControls({
|
||||
ownerKey: agentId,
|
||||
provider: agentProvider,
|
||||
providerDefinitions: modeProviderDefinitions,
|
||||
profiles: agentProfiles,
|
||||
models: {
|
||||
providers: agentModelSelectorProviders,
|
||||
selectedProvider: agentProvider,
|
||||
@@ -1226,6 +1227,7 @@ export const AgentControls = memo(function AgentControls({
|
||||
[
|
||||
activeModelId,
|
||||
agentOptionControls,
|
||||
agentProfiles,
|
||||
client,
|
||||
agentId,
|
||||
agentModelSelectorProviders,
|
||||
@@ -1448,6 +1450,7 @@ export function DraftAgentControls({
|
||||
ownerKey: draftId,
|
||||
provider: selectedProvider,
|
||||
providerDefinitions,
|
||||
profiles: agentProfiles,
|
||||
models: {
|
||||
providers: modelSelectorProviders,
|
||||
selectedProvider,
|
||||
@@ -1469,6 +1472,7 @@ export function DraftAgentControls({
|
||||
draftId,
|
||||
selectedProvider,
|
||||
providerDefinitions,
|
||||
agentProfiles,
|
||||
modelSelectorProviders,
|
||||
effectiveModelId,
|
||||
onSelectProviderAndModel,
|
||||
|
||||
@@ -385,16 +385,6 @@ function SessionProviderInternal({ children, serverId, client }: SessionProvider
|
||||
console.warn("[Session] timeline replacement refresh failed", { serverId, error });
|
||||
});
|
||||
};
|
||||
const onRewind = (message: SessionOutboundMessage) => {
|
||||
if (message.type !== "agent.timeline.rewind") return;
|
||||
const { agentId, epoch, seq, retireFromSeq } = message.payload;
|
||||
sync.applyStreamEvent(agentId, {
|
||||
event: { type: "rewind", retireFromSeq },
|
||||
seq,
|
||||
epoch,
|
||||
timestamp: new Date(),
|
||||
});
|
||||
};
|
||||
const sync = getHostRuntimeStore().createViewedTimelineOwner(serverId, {
|
||||
canCheckFreshness: () =>
|
||||
client.getLastServerInfoMessage()?.features?.timelineFreshnessCheck === true,
|
||||
@@ -405,7 +395,6 @@ function SessionProviderInternal({ children, serverId, client }: SessionProvider
|
||||
update: (message) => {
|
||||
if (message.type === "agent_stream") onStream(message);
|
||||
else if (message.type === "agent.timeline.replacement") onReplacement(message);
|
||||
else if (message.type === "agent.timeline.rewind") onRewind(message);
|
||||
},
|
||||
});
|
||||
return observation;
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user