mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-30 12:16:12 +00:00
Compare commits
18
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d2d4105366 | ||
|
|
37cb22dac8 | ||
|
|
397d1e14d6 | ||
|
|
d193e419e9 | ||
|
|
bd20e3fe98 | ||
|
|
39eaba6181 | ||
|
|
63ede58d7d | ||
|
|
3986e8b808 | ||
|
|
9fd8921697 | ||
|
|
269fa33491 | ||
|
|
ebcea47942 | ||
|
|
fb9a1644f0 | ||
|
|
93278b217b | ||
|
|
5f453a2f74 | ||
|
|
01aced8cd2 | ||
|
|
9d994aca9b | ||
|
|
839d45103b | ||
|
|
96fee23fbd |
@@ -55,6 +55,7 @@ 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 |
|
||||
|
||||
@@ -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. Provider history is not appended again when the canonical timeline is already
|
||||
primed.
|
||||
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).
|
||||
|
||||
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
|
||||
@@ -277,7 +277,8 @@ 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.
|
||||
children. The timeline and the provider children stay, so an archived chat reads them without its
|
||||
provider; deleting the agent removes them.
|
||||
|
||||
`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.
|
||||
|
||||
@@ -373,6 +374,8 @@ 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,6 +94,7 @@ 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 |
|
||||
@@ -402,7 +403,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`. 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.
|
||||
- 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).
|
||||
|
||||
## Right-sidebar boundary: directory-backed vs workspace-owned
|
||||
|
||||
@@ -478,6 +479,7 @@ 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
|
||||
|
||||
+41
-1
@@ -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 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.
|
||||
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.
|
||||
|
||||
All server-side stores live under `$PASEO_HOME` (defaults to `~/.paseo`).
|
||||
|
||||
@@ -53,6 +53,7 @@ $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}/
|
||||
@@ -181,6 +182,45 @@ 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`
|
||||
|
||||
@@ -36,6 +36,10 @@ ordinary `WorkspaceTab` (`SheetTab` in the store) and is an `IsolatedBottomSheet
|
||||
other sheet in the app, so it sits on the one app-wide stack: a sheet opened from any sheet lands on
|
||||
top of it, and closing the top sheet (drag, Close, backdrop, or Android Back) uncovers the one below.
|
||||
|
||||
Because that stack is app-wide and hidden workspace screens stay mounted, a sheet is not presented
|
||||
until its workspace has been on screen. A target opened in a workspace before the user gets there
|
||||
waits in the store and appears on arrival.
|
||||
|
||||
A subagent chosen from the subagents list is the exception. It opens as a page of the list's own
|
||||
sheet and replaces the list in place: Back returns to the list, Close ends both, and Open parent
|
||||
closes the list, landing on the pane the list was opened from. The store's `selectSheetTab` describes
|
||||
|
||||
@@ -26,7 +26,7 @@ The package keeps the npm tarball's layout, including its build output:
|
||||
|
||||
- Metro, Vitest and TypeScript load `lib/`, not `src/`. A JavaScript change edits `src/` and the matching `lib/module` and `lib/typescript` files.
|
||||
- `android/generated` and `ios/generated` are checked-in codegen output (`includesGeneratedCode`). A change to a native component spec regenerates both; `scripts/postinstall-patches.test.mjs` compares them against the specs.
|
||||
- `src/web/wasm/md4c.js` and `lib/module/web/wasm/md4c.js` are an Emscripten build of `cpp/md4c`. A parser change rebuilds them with upstream's `packages/core/cpp/wasm/build.sh`.
|
||||
- `src/web/wasm/md4c.js` and `lib/module/web/wasm/md4c.js` are an Emscripten build of `cpp/md4c`, `cpp/parser` and `cpp/wasm`. A parser change rebuilds both, or web keeps the old behavior while iOS and Android change. Run `cpp/wasm/build.sh` with `OUT_DIR` set to `src/web/wasm`, in `emscripten/emsdk:4.0.10` with the `-s GROWABLE_ARRAYBUFFERS=0` line removed. That version reproduces the committed JavaScript glue and has no such setting. The `lib/module` copy is the Babel output of the new file.
|
||||
- Upstream's Gradle, CMake and CocoaPods scripts detect upstream's own monorepo by the paths `packages/core` and a root `vendor/`. Do not add either path to this repository.
|
||||
- `postinstall.mjs` downloads the tree-sitter grammars into the ignored `cpp/highlight/vendor/grammars` and `vendor/tree-sitter`. The `enriched-markdown` block in `packages/app/package.json` chooses the languages.
|
||||
|
||||
@@ -42,7 +42,7 @@ Some fork changes are backports. A sync past the upstream version drops them in
|
||||
|
||||
## Engine constraints
|
||||
|
||||
Math and video are disabled. Task lists and admonitions are enabled; task checkboxes are read-only. Source adaptation spaces adjacent empty GFM table delimiters before escaping prose spoiler delimiters and decodes entity text before the engine can discard it. Code spans and fences keep their literal source. Comment HTML is normalized to Markdown before parsing; details show their summary and body expanded.
|
||||
Math and video are disabled. Task lists and admonitions are enabled; task checkboxes are read-only. Source adaptation spaces adjacent empty GFM table delimiters before escaping prose spoiler delimiters and decodes entity text before the engine can discard it. Code spans and fences keep their literal source. Comment HTML is normalized to Markdown before parsing; details show their summary and body expanded. `<br>` becomes a Markdown hard break, except inside a table, where a newline would end the row. There it becomes U+2028, and `cpp/parser/MD4CParser.cpp` turns U+2028 back into a line break in table cell text, never in code.
|
||||
|
||||
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.
|
||||
|
||||
|
||||
+6
-2
@@ -267,6 +267,10 @@ Plugin UI runs on desktop and mobile across multiple themes: color every `Text`
|
||||
`theme.colors.foreground` or `theme.colors.foregroundMuted`, and size layout from `layout.compact`.
|
||||
See `public-docs/plugins/reference.md`.
|
||||
|
||||
A plugin reads and arranges panes and tabs through `PluginWorkspaceLayout`. Its host,
|
||||
`packages/app/src/plugins/workspace-layout/`, is a facade over the layout store and `workspace-tabs`,
|
||||
so add behavior to those owners and keep layout mechanics out of the SDK types.
|
||||
|
||||
### SDK import boundaries
|
||||
|
||||
Classify every SDK export before adding it. All client entry points and implementations live under
|
||||
@@ -1018,8 +1022,8 @@ payload that cannot be rendered intact. The daemon advertises this RPC through
|
||||
|
||||
`addSlashCommand` registers an agent- or workspace-context command in the composer. The
|
||||
callback runs in the app, receives the trimmed text after the command name as `args`, and receives
|
||||
the same `paseo`, `rpc`, `openScreen`, workspace, agent, and `openPanel` capabilities as the matching
|
||||
Command Center callback.
|
||||
the same `paseo`, `rpc`, `openScreen`, workspace, agent, and `workspaceLayout` capabilities as the
|
||||
matching Command Center callback.
|
||||
|
||||
```ts
|
||||
client.addSlashCommand({
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
# Online client replacement: timeline recovery
|
||||
|
||||
Verified on macOS arm64 with Node 22.20.0, Chromium 145 (Playwright), and a real isolated daemon. Replies use the deterministic test provider; no external AI API is involved.
|
||||
|
||||
## Reproduction
|
||||
|
||||
1. Open two chats on one host and return to the first.
|
||||
2. Delay the active connection's real pong frames by 1 second, forwarding all real traffic, and wait for a measured liveness RTT.
|
||||
3. Add another direct endpoint for the same daemon.
|
||||
4. Advance the browser clock in 10-second steps. Each step waits for real delayed heartbeat replies and the public probe-cycle completion barrier, including replacement handshakes. The production selector and its timer constants are unchanged.
|
||||
5. Verify that every observed host snapshot stays online with a client, then confirm exactly one client-generation change to the faster endpoint.
|
||||
6. Require the Reconnecting alert to disappear within 3 seconds and verify a new message in the visible chat.
|
||||
7. Commit a message to the hidden second chat before reopening it. Verify that message is recovered, then verify another live message.
|
||||
|
||||
The two paths are localhost and 127.0.0.1 to the same daemon. The test does not force host state or replace a private client field. It controls browser time, not the daemon clock or real socket responses. Subscription assertions require the needed agents without requiring all other agents to be absent; exact matching remains the shared helper's default. The test has a 180-second timeout and a bounded clock-step budget allowing one candidate backoff. Observers, handles, timers, and scenario data are cleaned up even on failure.
|
||||
|
||||
## Before: exact final test source
|
||||
|
||||
Temporarily remove only the production `sync.setConnected(...)` seed, run the final regression, and restore the source in a `finally` block. The host remains online and changes to generation 2, but Reconnecting does not settle:
|
||||
|
||||
```text
|
||||
Error: expect(locator).toHaveCount(expected) failed
|
||||
Locator: getByRole('alert').filter({ hasText: 'Reconnecting' })
|
||||
Expected: 0
|
||||
Received: 1
|
||||
Timeout: 3000ms
|
||||
1 failed
|
||||
```
|
||||
|
||||
The frame below is extracted without modification from that final RED trace while the assertion was waiting, before fixture cleanup.
|
||||
|
||||

|
||||
|
||||
## After
|
||||
|
||||
Restore the production seed without changing the test files, then run:
|
||||
|
||||
```sh
|
||||
npm run test:e2e --workspace=@getpaseo/app -- \
|
||||
e2e/browser/viewed-agent-timelines.spec.ts \
|
||||
--grep 'online connection replacement|visible chat reports updating until reconnect' \
|
||||
--workers=1
|
||||
```
|
||||
|
||||
```text
|
||||
✓ an online connection replacement keeps every open chat synchronized (1.6m)
|
||||
✓ a visible chat reports updating until reconnect catch-up completes (35.9s)
|
||||
2 passed (2.3m)
|
||||
```
|
||||
|
||||
The online replacement case previously took 4.8 minutes with wall-clock probe waits. The final controlled-clock run takes 1.6 minutes. [Recorded hashes](red-green.json) confirm both test files are identical between final RED and GREEN and the production source was restored exactly.
|
||||
|
||||

|
||||
|
||||
## Other checks
|
||||
|
||||
```sh
|
||||
npm run typecheck
|
||||
npm run lint -- packages/app/e2e/browser/viewed-agent-timelines.spec.ts packages/app/e2e/support/helpers/timeline-delivery.ts
|
||||
npm run format
|
||||
```
|
||||
|
||||
Whole-workspace typecheck exited 0. Changed-file lint reported `Found 0 warnings and 0 errors.` Formatting passed.
|
||||
|
||||
The original runtime fix is unchanged by this test follow-up. Its previous native validation remains: both unmodified and fixed renderers exported with `PASEO_WEB_PLATFORM=electron npm exec -- expo export --platform web`; server dependencies and desktop main built through repository scripts; both packaged locally with `electron-builder --config electron-builder.yml --publish never --mac --arm64 --dir -c.mac.notarize=false`, with certificate discovery disabled.
|
||||
|
||||
The existing `packages/desktop/e2e/packaged-app-smoke.js --app <built-app>` passed for both packages with fresh temporary user data/daemon homes and loopback ports:
|
||||
|
||||
```text
|
||||
Packaged desktop smoke: real app renderer and preload bridge loaded
|
||||
Packaged desktop smoke: renderer-started desktop daemon reported running
|
||||
Packaged desktop smoke: every built-in plugin started
|
||||
Packaged desktop smoke: running bundled CLI shim daemon status
|
||||
Packaged desktop smoke: creating terminal through bundled CLI shim
|
||||
Packaged desktop smoke: terminal hook command completed
|
||||
Packaged desktop smoke passed: real renderer and preload loaded; renderer-started desktop daemon;
|
||||
CLI shim daemon status and terminal smoke succeeded
|
||||
```
|
||||
|
||||
The final summary omits ephemeral PID/listen values. The native smoke establishes packaged startup and terminal functionality, not native reconnect coverage.
|
||||
|
||||
## Coverage limits
|
||||
|
||||
- Web: real browser/daemon regression, with controlled browser scheduling, before and after.
|
||||
- macOS desktop: prior arm64 packaging and native startup/CLI/terminal smoke of the unchanged runtime fix.
|
||||
- iOS, Android, Windows desktop, Linux desktop: not tested.
|
||||
- External relay transport and a real provider turn: not tested by this regression.
|
||||
- The test requires eventual history recovery; it does not change the product's hidden-chat subscription policy or prohibit every transient toast frame.
|
||||
- These are local results. No full-suite or GitHub CI pass is claimed.
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 128 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 57 KiB |
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"production_source_restored": true,
|
||||
"test_sha256": {
|
||||
"packages/app/e2e/browser/viewed-agent-timelines.spec.ts": "1857d0ca187648d8377557cd82428a64546530795cf884c7474e921a1118c003",
|
||||
"packages/app/e2e/support/helpers/timeline-delivery.ts": "23d0adb9f92daac6d0841d584abb7aa272a2981861d7d211c8213e98a9af90da"
|
||||
},
|
||||
"red": {
|
||||
"result": "expected failure",
|
||||
"assertion": "Reconnecting alert expected 0, received 1",
|
||||
"timeout_ms": 3000
|
||||
},
|
||||
"green": {
|
||||
"passed": 2,
|
||||
"online_replacement_duration": "1.6m",
|
||||
"ordinary_reconnect_duration": "35.9s",
|
||||
"total_duration": "2.3m"
|
||||
}
|
||||
}
|
||||
+68
-11
@@ -5,15 +5,9 @@ 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.
|
||||
|
||||
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.
|
||||
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 invariants are:
|
||||
|
||||
@@ -32,6 +26,50 @@ 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:
|
||||
@@ -173,7 +211,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, epoch change, or rewind atomically replaces stale canonical history with the
|
||||
- A true middle gap or epoch change 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.
|
||||
|
||||
@@ -186,6 +224,24 @@ 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
|
||||
@@ -379,7 +435,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 or rewind replaces history and
|
||||
rows because a provider may never echo them. A known epoch change 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.
|
||||
@@ -395,6 +451,7 @@ 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-vrmauZ6dprc1M88FePLIvVT6FhgnmS9HjHGzPcCypyk=
|
||||
sha256-ZVIrRfb7oyTwx7kz6F51hs/ctT45qUdZM4v0QRLW9zA=
|
||||
|
||||
Generated
+20
-1
@@ -46,6 +46,9 @@
|
||||
"react-dom": "19.2.3",
|
||||
"typescript": "^5.9.3",
|
||||
"ws": "^8.20.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.16.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@0no-co/graphql.web": {
|
||||
@@ -39721,6 +39724,9 @@
|
||||
"typescript": "^5.2.2",
|
||||
"vitest": "^4.1.6",
|
||||
"zx": "^8.8.5"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.16.0"
|
||||
}
|
||||
},
|
||||
"packages/cli/node_modules/@vitest/expect": {
|
||||
@@ -40649,7 +40655,7 @@
|
||||
"@playwright/test": "^1.56.1",
|
||||
"@types/express": "^4.17.20",
|
||||
"@types/markdown-it": "^14.2.0",
|
||||
"@types/node": "^20.9.0",
|
||||
"@types/node": "^22.16.0",
|
||||
"@types/qrcode": "^1.5.6",
|
||||
"@types/uuid": "^9.0.7",
|
||||
"@types/ws": "^8.5.8",
|
||||
@@ -40657,6 +40663,9 @@
|
||||
"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": {
|
||||
@@ -41104,6 +41113,16 @@
|
||||
"@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",
|
||||
|
||||
@@ -172,5 +172,8 @@
|
||||
"tiny-async-pool": {
|
||||
"semver@^5": "5.7.2"
|
||||
}
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.16.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,6 +13,13 @@ 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,
|
||||
@@ -48,26 +55,98 @@ 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 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 submitted prompt without replaying history and preserves a human draft", async ({
|
||||
test("rewinds a prompt in place on every open client and keeps a human draft", async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(90_000);
|
||||
test.setTimeout(150_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);
|
||||
await completeSubmittedTurn(page, agent, retainedPrompt);
|
||||
const retainedMessage = 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,
|
||||
@@ -76,19 +155,91 @@ test.describe("Agent message rewind", () => {
|
||||
await blurComposerInput(page);
|
||||
rewindCompletion.clearTimelineStreamCount();
|
||||
|
||||
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 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;
|
||||
});
|
||||
|
||||
await expect(page.getByTestId("user-message").filter({ hasText: rewoundPrompt })).toHaveCount(
|
||||
0,
|
||||
);
|
||||
await expectComposerDraft(page, preservedDraft);
|
||||
await expectComposerNotFocused(page);
|
||||
await expectNearBottom(page);
|
||||
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 rewound conversation", async () => {
|
||||
await reloadAgentFromTabMenu(page, agent.agentId);
|
||||
await expectToast(page, "Reloaded agent");
|
||||
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 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]);
|
||||
});
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
|
||||
@@ -44,6 +44,26 @@ const PROFILE = {
|
||||
|
||||
const PROFILE_SUMMARY = "Mock Load Test · One minute stream · Approval test";
|
||||
|
||||
// Isolate this suite to the sole mock provider so it tests single-provider picker
|
||||
// behavior deterministically regardless of which CLIs are installed on the host.
|
||||
test.use({
|
||||
e2eDaemonConfig: {
|
||||
version: 1,
|
||||
agents: {
|
||||
providers: {
|
||||
claude: { enabled: false },
|
||||
codex: { enabled: false },
|
||||
copilot: { enabled: false },
|
||||
opencode: { enabled: false },
|
||||
pi: { enabled: false },
|
||||
omp: { enabled: false },
|
||||
antigravity: { enabled: false },
|
||||
hoplite: { enabled: false },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
test.describe("Agent profiles in the model picker", () => {
|
||||
test("an empty host still exposes agent profile settings from the picker", async ({ page }) => {
|
||||
const seed = await seedAgentProfiles([]);
|
||||
@@ -68,8 +88,8 @@ test.describe("Agent profiles in the model picker", () => {
|
||||
page,
|
||||
}) => {
|
||||
const seed = await seedAgentProfiles([PROFILE]);
|
||||
// A live agent is one provider's process, so the profile has to name that
|
||||
// same provider or the picker will not offer it at all.
|
||||
// With only the mock provider enabled on this host, the picker opens
|
||||
// directly into its models and shows its pinned profile.
|
||||
const workspace = await seedMockAgentWorkspace({
|
||||
repoPrefix: "agent-profiles-picker-",
|
||||
title: "Agent profiles picker",
|
||||
|
||||
@@ -0,0 +1,324 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import type { Locator } from "@playwright/test";
|
||||
import { expect, test, type Page } from "../support/fixtures";
|
||||
import { openCommandCenter } from "../support/helpers/command-center";
|
||||
import { runWorkspaceActionFromCommandCenter } from "../support/helpers/command-center-workspace-actions";
|
||||
import { submitMessageWithButton } from "../support/helpers/composer";
|
||||
import { openFileExplorer, openFileFromExplorer } from "../support/helpers/file-explorer";
|
||||
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
|
||||
import { connectNewWorkspaceDaemonClient } from "../support/helpers/new-workspace";
|
||||
import { copyPluginExample } from "../support/helpers/plugin-fixture";
|
||||
import { runCommand } from "../support/helpers/plugin-sidebar-items";
|
||||
import {
|
||||
closeSheet,
|
||||
expectNoSheetOpen,
|
||||
expectOneSheetOpen,
|
||||
promptMentioning,
|
||||
sheet,
|
||||
} from "../support/helpers/sheet";
|
||||
import {
|
||||
closeMobileExplorer,
|
||||
expectMobileExplorerHidden,
|
||||
expectMobileExplorerVisible,
|
||||
openMobileAgentSidebar,
|
||||
selectWorkspaceInSidebar,
|
||||
} from "../support/helpers/sidebar";
|
||||
import { getServerId } from "../support/helpers/server-id";
|
||||
|
||||
const WIDE = { width: 1600, height: 900 };
|
||||
const COMPACT = { width: 390, height: 844 };
|
||||
const AGENT_TITLE = "Layout agent";
|
||||
const FILE_LINK = "README.md:1";
|
||||
const NO_FILE = "Focus a file to see its outline";
|
||||
|
||||
const REPO_FILES = [
|
||||
{ path: "README.md", content: "# Guide\n\n## Install\n" },
|
||||
{ path: "notes.md", content: "# Notes\n\n## Open questions\n" },
|
||||
{ path: "src/app.ts", content: "// TODO: handle errors\nexport const ready = true;\n" },
|
||||
];
|
||||
|
||||
const REVIEW_TAB = "workspace-tab-plugin_agent_16_workspace-layout_6_review_";
|
||||
const FINDINGS_TAB = "workspace-tab-plugin_workspace_16_workspace-layout_8_findings";
|
||||
const OUTLINE_TAB = "workspace-tab-plugin_workspace_16_workspace-layout_7_outline";
|
||||
|
||||
async function withLayoutExample(
|
||||
initialPrompt: string | undefined,
|
||||
run: (agent: { agentId: string; workspaceId: string }) => Promise<void>,
|
||||
): Promise<void> {
|
||||
const example = await copyPluginExample("workspace-layout");
|
||||
const workspace = await seedMockAgentWorkspace({
|
||||
repoPrefix: "plugin-workspace-layout-",
|
||||
title: AGENT_TITLE,
|
||||
repo: { files: REPO_FILES },
|
||||
initialPrompt,
|
||||
});
|
||||
try {
|
||||
await withPluginInstalled(example.directory, () => run(workspace));
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
await example.cleanup();
|
||||
}
|
||||
}
|
||||
|
||||
async function withPluginInstalled(directory: string, run: () => Promise<void>): Promise<void> {
|
||||
const client = await connectNewWorkspaceDaemonClient({ ownProjects: false });
|
||||
const previous = await client.getDaemonConfig();
|
||||
try {
|
||||
await client.patchDaemonConfig({ pluginsEnabled: true });
|
||||
await client.installDirectoryPlugin(directory);
|
||||
await run();
|
||||
} finally {
|
||||
await client.removePlugin("workspace-layout").catch(() => undefined);
|
||||
await client.patchDaemonConfig({ pluginsEnabled: previous.config.pluginsEnabled ?? false });
|
||||
await client.close();
|
||||
}
|
||||
}
|
||||
|
||||
/** `/open-elsewhere <id>` opens a file in that workspace, then one where the command ran. */
|
||||
const OPEN_ELSEWHERE_ENTRY = `import type { PluginClientContext } from "@getpaseo/plugin/client";
|
||||
|
||||
export default function contribute(client: PluginClientContext) {
|
||||
client.addSlashCommand({
|
||||
name: "open-elsewhere",
|
||||
description: "Open a file there, then one here",
|
||||
argumentHint: "<workspaceId>",
|
||||
context: "agent",
|
||||
onSubmit({ args, workspaceLayout }) {
|
||||
const there = client.workspaceLayout(args.trim());
|
||||
there.open({ panelId: "paseo/file", params: { path: "README.md" } });
|
||||
workspaceLayout.open({ panelId: "paseo/file", params: { path: "notes.md" } });
|
||||
},
|
||||
});
|
||||
return () => {};
|
||||
}
|
||||
`;
|
||||
|
||||
async function withTwoWorkspaces(
|
||||
run: (workspaces: {
|
||||
first: { agentId: string; workspaceId: string };
|
||||
second: { agentId: string; workspaceId: string };
|
||||
}) => Promise<void>,
|
||||
): Promise<void> {
|
||||
const example = await copyPluginExample("workspace-layout");
|
||||
await writeFile(path.join(example.directory, "index.client.tsx"), OPEN_ELSEWHERE_ENTRY);
|
||||
const seed = (title: string) =>
|
||||
seedMockAgentWorkspace({
|
||||
repoPrefix: "plugin-workspace-layout-",
|
||||
title,
|
||||
repo: { files: REPO_FILES },
|
||||
});
|
||||
const first = await seed("First agent");
|
||||
const second = await seed("Second agent");
|
||||
try {
|
||||
await withPluginInstalled(example.directory, () => run({ first, second }));
|
||||
} finally {
|
||||
await second.cleanup();
|
||||
await first.cleanup();
|
||||
await example.cleanup();
|
||||
}
|
||||
}
|
||||
|
||||
/** Picks a workspace in a phone's agent list. */
|
||||
async function switchToWorkspace(page: Page, workspaceId: string): Promise<void> {
|
||||
await openMobileAgentSidebar(page);
|
||||
await selectWorkspaceInSidebar(page, workspaceId);
|
||||
await expect(
|
||||
page.getByTestId(`workspace-deck-entry-${getServerId()}:${workspaceId}`),
|
||||
).toBeVisible();
|
||||
await expect(composerIn(page.locator("body"))).toBeEditable({ timeout: 30_000 });
|
||||
}
|
||||
|
||||
function mainPanes(page: Page): Locator {
|
||||
return page.locator('[data-testid^="workspace-pane-"]').filter({ visible: true });
|
||||
}
|
||||
|
||||
function explorer(page: Page): Locator {
|
||||
return page.getByTestId("workspace-explorer-sidebar");
|
||||
}
|
||||
|
||||
function agentTabs(scope: Locator): Locator {
|
||||
return scope.locator('[data-testid^="workspace-tab-agent_"]');
|
||||
}
|
||||
|
||||
function composerIn(scope: Locator): Locator {
|
||||
return scope.getByRole("textbox", { name: "Message agent..." }).filter({ visible: true });
|
||||
}
|
||||
|
||||
async function sendToMainChat(page: Page, text: string): Promise<void> {
|
||||
const composer = composerIn(mainPanes(page).first());
|
||||
await expect(composer).toBeEditable({ timeout: 30_000 });
|
||||
await composer.fill(text);
|
||||
await composer.press("Enter");
|
||||
}
|
||||
|
||||
async function expectAsideChat(page: Page, input: { message: string; tabs: number }) {
|
||||
const chats = agentTabs(explorer(page));
|
||||
await expect(chats).toHaveCount(input.tabs, { timeout: 30_000 });
|
||||
await expect(chats.last()).toHaveAttribute("aria-selected", "true");
|
||||
await expect(
|
||||
explorer(page).getByTestId("user-message").getByText(input.message, { exact: true }),
|
||||
).toBeVisible();
|
||||
await expect(composerIn(explorer(page))).toBeEditable();
|
||||
}
|
||||
|
||||
/** Every visible tab chip, pane by pane, to compare the arrangement before and after. */
|
||||
async function tabsByPane(page: Page): Promise<string[][]> {
|
||||
const scopes = [...(await mainPanes(page).all()), explorer(page)];
|
||||
return Promise.all(
|
||||
scopes.map((scope) =>
|
||||
scope
|
||||
.getByTestId("workspace-tabs-row")
|
||||
.locator('[data-testid^="workspace-tab-"]:not([data-testid^="workspace-tab-tooltip"])')
|
||||
.evaluateAll((chips) => chips.map((chip) => chip.getAttribute("data-testid") ?? "")),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
async function expectReviewLayout(page: Page, agentId: string): Promise<void> {
|
||||
await expect(mainPanes(page)).toHaveCount(2);
|
||||
const left = mainPanes(page).first();
|
||||
const right = mainPanes(page).last();
|
||||
await expect(left.getByTestId(`workspace-tab-agent_${agentId}`)).toBeVisible();
|
||||
|
||||
const review = right.getByTestId(`${REVIEW_TAB}${agentId.length}_${agentId}`);
|
||||
await expect(review).toHaveAttribute("aria-selected", "true");
|
||||
await expect(right.getByText(`Reviewing ${AGENT_TITLE}`, { exact: true })).toBeVisible();
|
||||
await expect(right.getByTestId("workspace-tab-working_diff")).toHaveAttribute(
|
||||
"aria-selected",
|
||||
"false",
|
||||
);
|
||||
await expect(explorer(page).getByTestId(FINDINGS_TAB)).toBeVisible();
|
||||
|
||||
const [leftBox, rightBox] = [await left.boundingBox(), await right.boundingBox()];
|
||||
if (!leftBox || !rightBox) throw new Error("Review layout panes have no bounds");
|
||||
expect(rightBox.x).toBeGreaterThan(leftBox.x);
|
||||
expect(rightBox.width / (leftBox.width + rightBox.width)).toBeCloseTo(0.4, 1);
|
||||
}
|
||||
|
||||
async function openFileInFocusedPane(page: Page, name: string): Promise<void> {
|
||||
await openFileExplorer(page);
|
||||
await openFileFromExplorer(page, name);
|
||||
await expect(mainPanes(page).getByTestId(`workspace-tab-file_${name}`)).toBeVisible();
|
||||
}
|
||||
|
||||
async function expectOutline(page: Page, lines: string[]): Promise<void> {
|
||||
const outline = page.getByTestId("workspace-layout-outline");
|
||||
for (const line of lines) {
|
||||
await expect(outline.getByText(line, { exact: true })).toHaveCount(1);
|
||||
}
|
||||
}
|
||||
|
||||
test("the workspace layout example arranges a wide workspace", async ({ page }) => {
|
||||
test.setTimeout(180_000);
|
||||
await withLayoutExample(undefined, async ({ agentId, workspaceId }) => {
|
||||
await page.setViewportSize(WIDE);
|
||||
await openAgentRoute(page, { workspaceId, agentId });
|
||||
|
||||
await test.step("/aside opens the child agent's chat in the Explorer", async () => {
|
||||
await sendToMainChat(page, "/aside hey");
|
||||
await expectAsideChat(page, { message: "hey", tabs: 1 });
|
||||
await expect(agentTabs(mainPanes(page))).toHaveCount(1);
|
||||
});
|
||||
|
||||
await test.step("a second /aside adds a second tab", async () => {
|
||||
await sendToMainChat(page, "/aside again");
|
||||
await expectAsideChat(page, { message: "again", tabs: 2 });
|
||||
await expect(agentTabs(mainPanes(page))).toHaveCount(1);
|
||||
});
|
||||
|
||||
await test.step("Review layout splits the workspace, and running it again changes nothing", async () => {
|
||||
await runCommand(page, "Review layout");
|
||||
await expectReviewLayout(page, agentId);
|
||||
const arranged = await tabsByPane(page);
|
||||
|
||||
await mainPanes(page).first().getByTestId(`workspace-tab-agent_${agentId}`).click();
|
||||
await runCommand(page, "Review layout");
|
||||
await expectReviewLayout(page, agentId);
|
||||
expect(await tabsByPane(page)).toEqual(arranged);
|
||||
});
|
||||
|
||||
await test.step("the outline follows the focused file across split panes", async () => {
|
||||
await mainPanes(page).first().getByTestId(`workspace-tab-agent_${agentId}`).click();
|
||||
await runCommand(page, "Show outline");
|
||||
await expectOutline(page, [NO_FILE]);
|
||||
|
||||
await openFileInFocusedPane(page, "README.md");
|
||||
await explorer(page).getByTestId(OUTLINE_TAB).click();
|
||||
await expectOutline(page, ["README.md", "Guide", "Install"]);
|
||||
|
||||
await runWorkspaceActionFromCommandCenter(page, "Split pane right");
|
||||
await expect(mainPanes(page)).toHaveCount(3);
|
||||
await openFileInFocusedPane(page, "notes.md");
|
||||
await explorer(page).getByTestId(OUTLINE_TAB).click();
|
||||
await expectOutline(page, ["notes.md", "Notes", "Open questions"]);
|
||||
|
||||
await mainPanes(page).getByTestId("workspace-tab-file_README.md").click();
|
||||
await expectOutline(page, ["README.md", "Guide", "Install"]);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test("the workspace layout example opens over a phone's chat", async ({ page }) => {
|
||||
test.setTimeout(180_000);
|
||||
await withLayoutExample(promptMentioning(FILE_LINK), async ({ agentId, workspaceId }) => {
|
||||
await page.setViewportSize(COMPACT);
|
||||
await openAgentRoute(page, { workspaceId, agentId });
|
||||
|
||||
await test.step("/aside opens the Explorer over the chat", async () => {
|
||||
await submitMessageWithButton(page, "/aside hey");
|
||||
await expectMobileExplorerVisible(page);
|
||||
await expectAsideChat(page, { message: "hey", tabs: 1 });
|
||||
await closeMobileExplorer(page);
|
||||
await expectMobileExplorerHidden(page);
|
||||
await expect(
|
||||
page.getByRole("button", { name: "Switch tabs (1 open)" }).filter({ visible: true }),
|
||||
).toBeVisible();
|
||||
});
|
||||
|
||||
await test.step("a file sheet updates the outline, and closing it restores it", async () => {
|
||||
await openMobileAgentSidebar(page);
|
||||
const commandCenter = await openCommandCenter(page);
|
||||
await commandCenter.getByTestId("command-center-input").fill("Show outline");
|
||||
await commandCenter.getByRole("button", { name: "Show outline", exact: true }).click();
|
||||
await expectMobileExplorerVisible(page);
|
||||
await expectOutline(page, [NO_FILE]);
|
||||
await closeMobileExplorer(page);
|
||||
await expectMobileExplorerHidden(page);
|
||||
|
||||
await page.getByText(FILE_LINK, { exact: true }).first().click();
|
||||
await expect(sheet(page, "README.md")).toBeVisible();
|
||||
// The sheet covers the Explorer, so the outline can only be read, not seen.
|
||||
await expectOutline(page, ["README.md", "Guide", "Install"]);
|
||||
await closeSheet(page, "README.md");
|
||||
await expectOutline(page, [NO_FILE]);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test("a file a plugin opens in another workspace waits there on a phone", async ({ page }) => {
|
||||
test.setTimeout(180_000);
|
||||
await withTwoWorkspaces(async ({ first, second }) => {
|
||||
await page.setViewportSize(COMPACT);
|
||||
// Visiting the first workspace leaves its screen mounted behind the second.
|
||||
await openAgentRoute(page, first);
|
||||
await expect(composerIn(page.locator("body"))).toBeEditable({ timeout: 30_000 });
|
||||
await switchToWorkspace(page, second.workspaceId);
|
||||
|
||||
await test.step("only the sheet of the workspace on screen is shown", async () => {
|
||||
await submitMessageWithButton(page, `/open-elsewhere ${first.workspaceId}`);
|
||||
await expect(sheet(page, "notes.md")).toBeVisible();
|
||||
await expectOneSheetOpen(page);
|
||||
await closeSheet(page, "notes.md");
|
||||
await expectNoSheetOpen(page);
|
||||
});
|
||||
|
||||
await test.step("the other sheet is there when the user goes to its workspace", async () => {
|
||||
await switchToWorkspace(page, first.workspaceId);
|
||||
await expect(sheet(page, "README.md")).toBeVisible();
|
||||
await expectOneSheetOpen(page);
|
||||
await closeSheet(page, "README.md");
|
||||
await expectNoSheetOpen(page);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,555 @@
|
||||
import { mkdir } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import type { Locator } from "@playwright/test";
|
||||
import { expect, test, type Page } from "../support/fixtures";
|
||||
import { expectAgentIdle, expectAgentReadyToInterrupt } from "../support/helpers/agent-stream";
|
||||
import {
|
||||
drillIntoProvider,
|
||||
expectComposerMode,
|
||||
expectComposerModel,
|
||||
openModelPicker,
|
||||
selectModelRow,
|
||||
} from "../support/helpers/agent-profiles";
|
||||
import { expectWorkspaceAgentConfiguration } from "../support/helpers/command-center-agent-controls";
|
||||
import {
|
||||
expectComposerVisible,
|
||||
expectQueuedMessageButton,
|
||||
submitMessage,
|
||||
submitMessageWithButton,
|
||||
} from "../support/helpers/composer";
|
||||
import { connectDaemonClient } from "../support/helpers/daemon-client-loader";
|
||||
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
|
||||
import { copyPluginExample } from "../support/helpers/plugin-fixture";
|
||||
import { userScrollsTimelineToHistoryStart } from "../support/helpers/timeline-pagination";
|
||||
|
||||
const DIRECT_PROVIDER = {
|
||||
id: "direct-example",
|
||||
label: "Direct provider example",
|
||||
pluginId: "provider-direct-example",
|
||||
modelId: "example-1",
|
||||
modelLabel: "Example 1",
|
||||
modeLabel: "Build",
|
||||
} as const;
|
||||
|
||||
// Disable external CLIs so the E2E host deterministically exposes only Mock +
|
||||
// the installed Direct provider plugin on both developer machines and CI.
|
||||
test.use({
|
||||
e2eDaemonConfig: {
|
||||
version: 1,
|
||||
agents: {
|
||||
providers: {
|
||||
claude: { enabled: false },
|
||||
codex: { enabled: false },
|
||||
copilot: { enabled: false },
|
||||
opencode: { enabled: false },
|
||||
pi: { enabled: false },
|
||||
omp: { enabled: false },
|
||||
antigravity: { enabled: false },
|
||||
hoplite: { enabled: false },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
interface PluginInstallDaemonClient {
|
||||
connect(): Promise<void>;
|
||||
close(): Promise<void>;
|
||||
getDaemonConfig(): Promise<{ config: { pluginsEnabled?: boolean } }>;
|
||||
patchDaemonConfig(config: { pluginsEnabled?: boolean }): Promise<unknown>;
|
||||
installDirectoryPlugin(directory: string): Promise<unknown>;
|
||||
removePlugin(pluginId: string): Promise<void>;
|
||||
getProvidersSnapshot(): Promise<{
|
||||
entries: Array<{ provider: string; available?: boolean }>;
|
||||
}>;
|
||||
}
|
||||
|
||||
async function hasDirectProvider(client: PluginInstallDaemonClient): Promise<boolean> {
|
||||
const snapshot = await client.getProvidersSnapshot();
|
||||
return snapshot.entries.some((entry) => entry.provider === DIRECT_PROVIDER.id);
|
||||
}
|
||||
|
||||
async function expectSwitchMarkerCountAfterScroll(page: Page, expected: number): Promise<void> {
|
||||
await expect
|
||||
.poll(
|
||||
async () => {
|
||||
await userScrollsTimelineToHistoryStart(page);
|
||||
return await page.getByTestId("provider-switch-marker").count();
|
||||
},
|
||||
{ timeout: 30_000 },
|
||||
)
|
||||
.toBe(expected);
|
||||
}
|
||||
|
||||
async function captureQaScreenshot(page: Page, fileName: string): Promise<void> {
|
||||
const dir = process.env.PASEO_QA_SCREENSHOT_DIR?.trim();
|
||||
if (!dir) return;
|
||||
await mkdir(dir, { recursive: true });
|
||||
await page.screenshot({ path: path.join(dir, fileName), fullPage: false });
|
||||
}
|
||||
|
||||
async function expectNoHorizontalOverflow(page: Page): Promise<void> {
|
||||
const overflow = await page.evaluate(() => {
|
||||
const doc = document.documentElement;
|
||||
return Math.ceil(doc.scrollWidth - doc.clientWidth);
|
||||
});
|
||||
expect(overflow).toBeLessThanOrEqual(1);
|
||||
}
|
||||
|
||||
async function startSwitchOrderGuard(page: Page): Promise<void> {
|
||||
await page.evaluate(() => {
|
||||
const violations: string[] = [];
|
||||
let stopped = false;
|
||||
const step = () => {
|
||||
const msgs = Array.from(document.querySelectorAll('[data-testid="user-message"]'));
|
||||
const markers = Array.from(
|
||||
document.querySelectorAll('[data-testid="provider-switch-marker"]'),
|
||||
);
|
||||
const banner = document.querySelector('[data-testid="staged-provider-switch-banner"]');
|
||||
if (msgs.length >= 2) {
|
||||
const secondMsg = msgs[msgs.length - 1];
|
||||
const lastMarker = markers[markers.length - 1];
|
||||
if (!lastMarker) {
|
||||
violations.push("user-message painted without switch marker");
|
||||
} else {
|
||||
const msgRect = secondMsg.getBoundingClientRect();
|
||||
const markerRect = lastMarker.getBoundingClientRect();
|
||||
if (markerRect.top > msgRect.top) {
|
||||
violations.push(
|
||||
`switch marker painted below user-message (${Math.round(markerRect.top)} > ${Math.round(msgRect.top)})`,
|
||||
);
|
||||
}
|
||||
}
|
||||
if (banner && banner.getBoundingClientRect().height > 0) {
|
||||
violations.push("staged-provider-switch-banner stayed visible after submit");
|
||||
}
|
||||
}
|
||||
if (!stopped) requestAnimationFrame(step);
|
||||
};
|
||||
requestAnimationFrame(step);
|
||||
(window as unknown as { __stopSwitchOrderGuard?: () => string[] }).__stopSwitchOrderGuard =
|
||||
() => {
|
||||
stopped = true;
|
||||
return violations;
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
async function stopSwitchOrderGuard(page: Page): Promise<string[]> {
|
||||
return await page.evaluate(
|
||||
() =>
|
||||
(
|
||||
window as unknown as { __stopSwitchOrderGuard?: () => string[] }
|
||||
).__stopSwitchOrderGuard?.() ?? [],
|
||||
);
|
||||
}
|
||||
|
||||
async function completeMockTurn(
|
||||
page: Page,
|
||||
agent: Awaited<ReturnType<typeof seedMockAgentWorkspace>>,
|
||||
prompt: string,
|
||||
): Promise<Locator> {
|
||||
await submitMessage(page, prompt);
|
||||
const userMessage = page.getByTestId("user-message").filter({ hasText: prompt });
|
||||
await expect(userMessage).toBeVisible({ timeout: 30_000 });
|
||||
const finish = await agent.client.waitForFinish(agent.agentId, 30_000);
|
||||
expect(finish.status).toBe("idle");
|
||||
await expectAgentIdle(page);
|
||||
await expect(userMessage).toHaveAttribute("aria-busy", "false");
|
||||
return userMessage;
|
||||
}
|
||||
|
||||
async function completeDirectTurn(
|
||||
page: Page,
|
||||
agent: Awaited<ReturnType<typeof seedMockAgentWorkspace>>,
|
||||
prompt: string,
|
||||
options?: { useSendButton?: boolean },
|
||||
): Promise<Locator> {
|
||||
if (options?.useSendButton) {
|
||||
await submitMessageWithButton(page, prompt);
|
||||
} else {
|
||||
await submitMessage(page, prompt);
|
||||
}
|
||||
const userMessage = page.getByTestId("user-message").filter({ hasText: prompt });
|
||||
await expect(userMessage).toBeVisible({ timeout: 30_000 });
|
||||
const finish = await agent.client.waitForFinish(agent.agentId, 30_000);
|
||||
expect(finish.status).toBe("idle");
|
||||
await expectAgentIdle(page);
|
||||
await expect(userMessage).toHaveAttribute("aria-busy", "false");
|
||||
return userMessage;
|
||||
}
|
||||
|
||||
async function stageProviderDesktop(
|
||||
page: Page,
|
||||
providerId: string,
|
||||
modelId: string,
|
||||
): Promise<void> {
|
||||
await openModelPicker(page);
|
||||
const picker = page.getByTestId("combobox-desktop-container");
|
||||
const backButton = picker.getByTestId("sheet-header-back");
|
||||
if (await backButton.isVisible()) {
|
||||
await backButton.click();
|
||||
}
|
||||
await drillIntoProvider(page, providerId);
|
||||
await selectModelRow(page, { provider: providerId, modelId });
|
||||
await expect(page.getByTestId("staged-provider-switch-banner")).toBeVisible({ timeout: 30_000 });
|
||||
}
|
||||
|
||||
async function stageDirectProviderDesktop(page: Page): Promise<void> {
|
||||
await stageProviderDesktop(page, DIRECT_PROVIDER.id, DIRECT_PROVIDER.modelId);
|
||||
}
|
||||
|
||||
async function stageDirectProviderCompact(page: Page): Promise<void> {
|
||||
await page.getByTestId("combined-model-selector").filter({ visible: true }).first().click();
|
||||
await expect(page.getByTestId("agent-controls-model")).toBeVisible({ timeout: 30_000 });
|
||||
await page.getByTestId("agent-controls-model").click();
|
||||
const modelPage = page.getByTestId("mobile-model-page");
|
||||
await expect(modelPage).toBeVisible({ timeout: 30_000 });
|
||||
const collapsedProvider = modelPage.getByTestId(`model-provider-${DIRECT_PROVIDER.id}`);
|
||||
if (await collapsedProvider.isVisible()) {
|
||||
await collapsedProvider.click();
|
||||
}
|
||||
await modelPage.getByTestId(`model-row-${DIRECT_PROVIDER.id}-${DIRECT_PROVIDER.modelId}`).click();
|
||||
await expect(page.getByTestId("agent-controls-settings-list")).toBeVisible({ timeout: 30_000 });
|
||||
// Dismiss the agent-controls sheet so the composer and banner are ready to submit.
|
||||
await page.getByRole("button", { name: "Close", exact: true }).last().click();
|
||||
await expect(page.getByTestId("agent-controls-model")).toHaveCount(0, { timeout: 30_000 });
|
||||
await expect(page.getByTestId("staged-provider-switch-banner")).toBeVisible({ timeout: 30_000 });
|
||||
}
|
||||
|
||||
async function rewindConversation(page: Page, userMessage: Locator, prompt: string): Promise<void> {
|
||||
await userMessage.getByText(prompt, { exact: true }).hover();
|
||||
await userMessage.getByRole("button", { name: "Rewind to this message", exact: true }).click();
|
||||
await page.getByRole("menuitem", { name: "Rewind conversation", exact: true }).click();
|
||||
}
|
||||
|
||||
test.describe.serial("Provider switching in chat", () => {
|
||||
let pluginClient: PluginInstallDaemonClient;
|
||||
let pluginFixture: Awaited<ReturnType<typeof copyPluginExample>>;
|
||||
let previousPluginsEnabled: boolean | undefined;
|
||||
|
||||
test.beforeAll(async () => {
|
||||
pluginClient = await connectDaemonClient<PluginInstallDaemonClient>({
|
||||
clientIdPrefix: "provider-switching-e2e",
|
||||
});
|
||||
pluginFixture = await copyPluginExample("provider-direct");
|
||||
previousPluginsEnabled = (await pluginClient.getDaemonConfig()).config.pluginsEnabled;
|
||||
await pluginClient.patchDaemonConfig({ pluginsEnabled: true });
|
||||
await pluginClient.installDirectoryPlugin(pluginFixture.directory);
|
||||
await expect.poll(() => hasDirectProvider(pluginClient), { timeout: 30_000 }).toBe(true);
|
||||
});
|
||||
|
||||
test.afterAll(async () => {
|
||||
await pluginClient?.removePlugin(DIRECT_PROVIDER.pluginId).catch(() => undefined);
|
||||
await pluginClient
|
||||
?.patchDaemonConfig({ pluginsEnabled: previousPluginsEnabled })
|
||||
.catch(() => undefined);
|
||||
await pluginClient?.close().catch(() => undefined);
|
||||
await pluginFixture?.cleanup().catch(() => undefined);
|
||||
});
|
||||
|
||||
test("stages, cancels, switches providers, inspects marker, scopes rewind, and survives reload", async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(150_000);
|
||||
await page.setViewportSize({ width: 1280, height: 800 });
|
||||
|
||||
const preSwitchPrompt = "First prompt on Mock before switching.";
|
||||
const postSwitchPrompt = "Follow up on Direct provider after switching.";
|
||||
const postRewindPrompt = "Continue on Direct provider after rewinding.";
|
||||
|
||||
const workspace = await seedMockAgentWorkspace({
|
||||
repoPrefix: "provider-switch-desktop-",
|
||||
title: "Provider switch desktop",
|
||||
model: "e2e-fast-stream",
|
||||
modeId: "load-test",
|
||||
});
|
||||
|
||||
try {
|
||||
await openAgentRoute(page, workspace);
|
||||
await expectComposerVisible(page);
|
||||
await expectComposerMode(page, "Load test");
|
||||
|
||||
const initialUrl = page.url();
|
||||
await completeMockTurn(page, workspace, preSwitchPrompt);
|
||||
|
||||
await test.step("staging updates only draft state and Cancel restores the live provider", async () => {
|
||||
await stageDirectProviderDesktop(page);
|
||||
await expectComposerModel(page, DIRECT_PROVIDER.modelLabel);
|
||||
await expectComposerMode(page, DIRECT_PROVIDER.modeLabel);
|
||||
await expect(page.getByTestId("staged-provider-switch-banner")).toContainText(
|
||||
DIRECT_PROVIDER.label,
|
||||
);
|
||||
await expectWorkspaceAgentConfiguration(workspace, {
|
||||
id: workspace.agentId,
|
||||
provider: "mock",
|
||||
model: "e2e-fast-stream",
|
||||
modeId: "load-test",
|
||||
});
|
||||
// Editing a staged provider option must keep all staged option controls visible.
|
||||
const conciseToggle = page.getByRole("button", { name: /Concise responses/i }).first();
|
||||
const voiceSelect = page.getByRole("button", { name: /Voice/i }).first();
|
||||
await expect(conciseToggle).toBeVisible();
|
||||
await expect(voiceSelect).toBeVisible();
|
||||
await conciseToggle.click();
|
||||
await expect(conciseToggle).toBeVisible();
|
||||
await expect(voiceSelect).toBeVisible();
|
||||
await expectNoHorizontalOverflow(page);
|
||||
await captureQaScreenshot(page, "desktop-staged-switch.png");
|
||||
|
||||
await page.getByTestId("cancel-staged-provider-switch").click();
|
||||
await expect(page.getByTestId("staged-provider-switch-banner")).toHaveCount(0);
|
||||
await expectComposerMode(page, "Load test");
|
||||
|
||||
// Returning to the live provider by choosing a different model clears the staged switch
|
||||
// and applies the newly chosen model directly to the live provider.
|
||||
await stageDirectProviderDesktop(page);
|
||||
await openModelPicker(page);
|
||||
const picker = page.getByTestId("combobox-desktop-container");
|
||||
const backButton = picker.getByTestId("sheet-header-back");
|
||||
if (await backButton.isVisible()) {
|
||||
await backButton.click();
|
||||
}
|
||||
await drillIntoProvider(page, "mock");
|
||||
await selectModelRow(page, { provider: "mock", modelId: "one-minute-stream" });
|
||||
await expect(page.getByTestId("staged-provider-switch-banner")).toHaveCount(0);
|
||||
await expectComposerModel(page, "One minute stream");
|
||||
await expectWorkspaceAgentConfiguration(workspace, {
|
||||
id: workspace.agentId,
|
||||
provider: "mock",
|
||||
model: "one-minute-stream",
|
||||
modeId: "load-test",
|
||||
});
|
||||
});
|
||||
|
||||
await test.step("submitting commits the switch in place with clean user display text and inspectable marker", async () => {
|
||||
await stageDirectProviderDesktop(page);
|
||||
await startSwitchOrderGuard(page);
|
||||
const switchedMessage = await completeDirectTurn(page, workspace, postSwitchPrompt);
|
||||
expect(await stopSwitchOrderGuard(page)).toEqual([]);
|
||||
|
||||
expect(page.url()).toBe(initialUrl);
|
||||
await expect(page.getByTestId("staged-provider-switch-banner")).toHaveCount(0);
|
||||
await expectWorkspaceAgentConfiguration(workspace, {
|
||||
id: workspace.agentId,
|
||||
provider: DIRECT_PROVIDER.id,
|
||||
model: DIRECT_PROVIDER.modelId,
|
||||
modeId: "build",
|
||||
});
|
||||
|
||||
// Clean display text: handoff summary must never leak into the visible user bubble.
|
||||
await expect(switchedMessage).toContainText(postSwitchPrompt);
|
||||
await expect(switchedMessage).not.toContainText("<chat-history-summary>");
|
||||
|
||||
// Direct provider echoes its prompt, proving bounded pre-switch context was attached.
|
||||
const directReply = page
|
||||
.getByTestId("assistant-message")
|
||||
.filter({ hasText: "Echo:" })
|
||||
.last();
|
||||
await expect(directReply).toContainText(preSwitchPrompt);
|
||||
await expect(directReply).toContainText(postSwitchPrompt);
|
||||
|
||||
// Switch marker is visible and expands to show context handoff details.
|
||||
const marker = page.getByTestId("provider-switch-marker");
|
||||
await expect(marker).toBeVisible({ timeout: 30_000 });
|
||||
await marker.scrollIntoViewIfNeeded();
|
||||
await marker.getByTestId("provider-switch-marker-toggle").click();
|
||||
const details = marker.getByTestId("provider-switch-marker-details");
|
||||
await expect(details).toBeVisible();
|
||||
await expect(details).toContainText("Mock");
|
||||
await expect(details).toContainText(DIRECT_PROVIDER.label);
|
||||
await marker.scrollIntoViewIfNeeded();
|
||||
await expectNoHorizontalOverflow(page);
|
||||
await captureQaScreenshot(page, "desktop-switched-expanded.png");
|
||||
await marker.getByTestId("provider-switch-marker-toggle").click();
|
||||
await expect(details).toHaveCount(0);
|
||||
});
|
||||
|
||||
await test.step("switching back to Mock enforces segment-scoped rewind and preserves pre-switch turns", async () => {
|
||||
const backToMockPrompt = "Switch back to Mock for segment-scoped rewind.";
|
||||
await stageProviderDesktop(page, "mock", "ten-second-stream");
|
||||
await expect(page.getByTestId("staged-provider-switch-banner")).toContainText("Mock");
|
||||
|
||||
const backToMockMessage = await completeMockTurn(page, workspace, backToMockPrompt);
|
||||
await expect(backToMockMessage).not.toContainText("<chat-history-summary>");
|
||||
await expect(page.getByTestId("provider-switch-marker")).toHaveCount(2, {
|
||||
timeout: 30_000,
|
||||
});
|
||||
await expectWorkspaceAgentConfiguration(workspace, {
|
||||
id: workspace.agentId,
|
||||
provider: "mock",
|
||||
model: "ten-second-stream",
|
||||
modeId: "load-test",
|
||||
});
|
||||
|
||||
// Pre-switch prompts from earlier segments must not expose rewind even though Mock supports it.
|
||||
const preSwitchMessage = page
|
||||
.getByTestId("user-message")
|
||||
.filter({ hasText: preSwitchPrompt });
|
||||
await preSwitchMessage.scrollIntoViewIfNeeded();
|
||||
await preSwitchMessage.getByText(preSwitchPrompt, { exact: true }).hover();
|
||||
await expect(
|
||||
preSwitchMessage.getByRole("button", { name: "Rewind to this message", exact: true }),
|
||||
).toHaveCount(0);
|
||||
|
||||
const directMessage = page
|
||||
.getByTestId("user-message")
|
||||
.filter({ hasText: postSwitchPrompt });
|
||||
await directMessage.scrollIntoViewIfNeeded();
|
||||
await directMessage.getByText(postSwitchPrompt, { exact: true }).hover();
|
||||
await expect(
|
||||
directMessage.getByRole("button", { name: "Rewind to this message", exact: true }),
|
||||
).toHaveCount(0);
|
||||
|
||||
// Post-switch prompt on Mock CAN rewind without retiring earlier segments or markers.
|
||||
await backToMockMessage.scrollIntoViewIfNeeded();
|
||||
await rewindConversation(page, backToMockMessage, backToMockPrompt);
|
||||
await expect(
|
||||
page.getByTestId("user-message").filter({ hasText: backToMockPrompt }),
|
||||
).toHaveCount(0, { timeout: 30_000 });
|
||||
await expect(
|
||||
page.getByTestId("user-message").filter({ hasText: preSwitchPrompt }),
|
||||
).toBeVisible();
|
||||
await expect(
|
||||
page.getByTestId("user-message").filter({ hasText: postSwitchPrompt }),
|
||||
).toBeVisible();
|
||||
await expect(page.getByTestId("provider-switch-marker")).toHaveCount(2);
|
||||
|
||||
// Continuing in the now-empty active segment completes cleanly.
|
||||
const retriedMessage = await completeMockTurn(page, workspace, postRewindPrompt);
|
||||
await expect(retriedMessage).not.toContainText("<chat-history-summary>");
|
||||
});
|
||||
|
||||
await test.step("reload preserves the switched provider, markers, and rewind boundary", async () => {
|
||||
await page.reload();
|
||||
await expectComposerVisible(page);
|
||||
await expectComposerModel(page, "Ten second stream");
|
||||
await expectSwitchMarkerCountAfterScroll(page, 2);
|
||||
const reloadedDirect = page
|
||||
.getByTestId("user-message")
|
||||
.filter({ hasText: postSwitchPrompt });
|
||||
await expect(reloadedDirect).toBeVisible();
|
||||
await expect(
|
||||
page.getByTestId("user-message").filter({ hasText: postRewindPrompt }),
|
||||
).toBeVisible();
|
||||
|
||||
await reloadedDirect.scrollIntoViewIfNeeded();
|
||||
await reloadedDirect.getByText(postSwitchPrompt, { exact: true }).hover();
|
||||
await expect(
|
||||
reloadedDirect.getByRole("button", { name: "Rewind to this message", exact: true }),
|
||||
).toHaveCount(0);
|
||||
});
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("stages a switch mid-turn, queues the prompt, and switches cleanly between turns", async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(150_000);
|
||||
await page.setViewportSize({ width: 1280, height: 800 });
|
||||
|
||||
const runningPrompt = "Run a ten-second mock turn first.";
|
||||
const queuedPrompt = "Queued handoff prompt for Direct provider.";
|
||||
|
||||
const workspace = await seedMockAgentWorkspace({
|
||||
repoPrefix: "provider-switch-midturn-",
|
||||
title: "Provider switch midturn",
|
||||
model: "ten-second-stream",
|
||||
modeId: "load-test",
|
||||
});
|
||||
|
||||
try {
|
||||
await openAgentRoute(page, workspace);
|
||||
await expectComposerVisible(page);
|
||||
|
||||
await submitMessage(page, runningPrompt);
|
||||
await expectAgentReadyToInterrupt(page);
|
||||
|
||||
// Stage Direct provider while Mock is actively streaming.
|
||||
await stageDirectProviderDesktop(page);
|
||||
await expectWorkspaceAgentConfiguration(workspace, {
|
||||
id: workspace.agentId,
|
||||
provider: "mock",
|
||||
model: "ten-second-stream",
|
||||
modeId: "load-test",
|
||||
});
|
||||
|
||||
// Submitting queues the prompt instead of racing the live turn.
|
||||
await submitMessage(page, queuedPrompt);
|
||||
await expectQueuedMessageButton(page);
|
||||
|
||||
// Once the mock turn completes, the queue drains and commits the switch.
|
||||
await expect(page.getByTestId("provider-switch-marker")).toBeVisible({ timeout: 45_000 });
|
||||
await expect(page.getByTestId("staged-provider-switch-banner")).toHaveCount(0, {
|
||||
timeout: 30_000,
|
||||
});
|
||||
await expect(
|
||||
page.getByTestId("assistant-message").filter({ hasText: queuedPrompt }).last(),
|
||||
).toBeVisible({ timeout: 30_000 });
|
||||
await expectAgentIdle(page);
|
||||
await expectWorkspaceAgentConfiguration(workspace, {
|
||||
id: workspace.agentId,
|
||||
provider: DIRECT_PROVIDER.id,
|
||||
model: DIRECT_PROVIDER.modelId,
|
||||
modeId: "build",
|
||||
});
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("switches providers cleanly on a compact viewport with zero horizontal overflow", async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(150_000);
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
|
||||
const preSwitchPrompt = "Compact turn on Mock.";
|
||||
const postSwitchPrompt = "Compact handoff on Direct.";
|
||||
|
||||
const workspace = await seedMockAgentWorkspace({
|
||||
repoPrefix: "provider-switch-compact-",
|
||||
title: "Provider switch compact",
|
||||
model: "e2e-fast-stream",
|
||||
modeId: "load-test",
|
||||
});
|
||||
|
||||
try {
|
||||
await openAgentRoute(page, workspace);
|
||||
await expectComposerVisible(page);
|
||||
|
||||
await submitMessageWithButton(page, preSwitchPrompt);
|
||||
await expect(
|
||||
page.getByTestId("user-message").filter({ hasText: preSwitchPrompt }),
|
||||
).toBeVisible({ timeout: 30_000 });
|
||||
const firstFinish = await workspace.client.waitForFinish(workspace.agentId, 30_000);
|
||||
expect(firstFinish.status).toBe("idle");
|
||||
await expectAgentIdle(page);
|
||||
|
||||
await stageDirectProviderCompact(page);
|
||||
await expectNoHorizontalOverflow(page);
|
||||
await captureQaScreenshot(page, "compact-staged-switch.png");
|
||||
|
||||
const switchedMessage = await completeDirectTurn(page, workspace, postSwitchPrompt, {
|
||||
useSendButton: true,
|
||||
});
|
||||
await expect(switchedMessage).not.toContainText("<chat-history-summary>");
|
||||
|
||||
const marker = page.getByTestId("provider-switch-marker");
|
||||
await expect(marker).toBeVisible({ timeout: 30_000 });
|
||||
await marker.scrollIntoViewIfNeeded();
|
||||
const toggle = marker.getByTestId("provider-switch-marker-toggle");
|
||||
const toggleBox = await toggle.boundingBox();
|
||||
expect(toggleBox).not.toBeNull();
|
||||
expect((toggleBox?.x ?? 0) + (toggleBox?.width ?? 0)).toBeLessThanOrEqual(390);
|
||||
await toggle.click();
|
||||
await expect(marker.getByTestId("provider-switch-marker-details")).toBeVisible();
|
||||
await marker.scrollIntoViewIfNeeded();
|
||||
await expectNoHorizontalOverflow(page);
|
||||
await captureQaScreenshot(page, "compact-switched-expanded.png");
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -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, 1);
|
||||
await expectUserMessageCount(page, 0);
|
||||
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, 2);
|
||||
await expectUserMessageCount(page, 1);
|
||||
|
||||
await fillComposerDraft(page, "");
|
||||
await composerLocator(page).evaluate((element) => element.blur());
|
||||
@@ -254,7 +254,19 @@ test.describe("Rewind sheet", () => {
|
||||
await expect(page.getByTestId("rewind-menu-content")).toHaveCount(0);
|
||||
await expectComposerDraft(page, "");
|
||||
await expectComposerNotFocused(page);
|
||||
await expectUserMessageCount(page, 2);
|
||||
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 fillComposerDraft(page, "");
|
||||
await composerLocator(page).evaluate((element) => element.blur());
|
||||
@@ -265,7 +277,7 @@ test.describe("Rewind sheet", () => {
|
||||
await expect(page.getByTestId("rewind-menu-content")).toHaveCount(0);
|
||||
await expectComposerDraft(page, replacementPrompt);
|
||||
await expectComposerFocused(page);
|
||||
await expectUserMessageCount(page, 1);
|
||||
await expectUserMessageCount(page, 0);
|
||||
} finally {
|
||||
await session.cleanup();
|
||||
}
|
||||
|
||||
@@ -35,7 +35,13 @@ import {
|
||||
expectSettingsHeader,
|
||||
openAddHostFlow,
|
||||
selectHostConnectionType,
|
||||
toggleHostAdvanced,
|
||||
selectDirectConnectionMode,
|
||||
expectDirectConnectionMode,
|
||||
expectDirectFormModeDisabled,
|
||||
connectDirectHost,
|
||||
connectDirectHostExpectingPassword,
|
||||
pasteIntoDirectHost,
|
||||
fillDirectHostPromptPassword,
|
||||
openCompactSettings,
|
||||
expectCompactSettingsList,
|
||||
expectSettingsSidebarVisible,
|
||||
@@ -50,11 +56,11 @@ import {
|
||||
fillDirectHostUri,
|
||||
expectDirectHostFormValues,
|
||||
expectDirectHostSslEnabled,
|
||||
expectDirectHostSslDisabled,
|
||||
fillDirectHostAddress,
|
||||
toggleDirectHostSsl,
|
||||
expectDirectHostUriValue,
|
||||
expectDirectHostUriHidden,
|
||||
expectDirectFormFullyVisible,
|
||||
expectDiagnosticsContent,
|
||||
expectAboutContent,
|
||||
expectGeneralContent,
|
||||
@@ -71,6 +77,7 @@ import {
|
||||
bindCommandCenterToEnter,
|
||||
} from "../support/helpers/settings";
|
||||
import { getServerId } from "../support/helpers/server-id";
|
||||
import { startIsolatedHostDaemon } from "../support/helpers/isolated-host-daemon";
|
||||
import { expectAppRoute } from "../support/helpers/route-assertions";
|
||||
import { clickNewChat, gotoWorkspace } from "../support/helpers/launcher";
|
||||
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
|
||||
@@ -327,44 +334,105 @@ test.describe("Settings sidebar navigation", () => {
|
||||
await verifyLegacyHostSettingsRedirect(page);
|
||||
});
|
||||
|
||||
test("direct connection advanced URI round-trips SSL and password into the form", async ({
|
||||
page,
|
||||
}) => {
|
||||
test("direct connection converts between Form and URI modes", async ({ page }) => {
|
||||
await gotoAppShell(page);
|
||||
await openSettings(page);
|
||||
await openAddHostFlow(page);
|
||||
await expectAddHostMethodOptions(page);
|
||||
await selectHostConnectionType(page, "direct");
|
||||
await expectDirectConnectionMode(page, "Form");
|
||||
|
||||
await fillDirectHostAddress(page, "example.paseo.test", "7443");
|
||||
await expectDirectHostSslDisabled(page);
|
||||
await toggleDirectHostSsl(page);
|
||||
await expectDirectHostSslEnabled(page);
|
||||
await toggleHostAdvanced(page);
|
||||
await expectDirectHostUriValue(page, "tcp://example.paseo.test:7443?ssl=true");
|
||||
await toggleHostAdvanced(page);
|
||||
await toggleDirectHostSsl(page);
|
||||
await expectDirectHostSslDisabled(page);
|
||||
|
||||
await toggleHostAdvanced(page);
|
||||
await fillDirectHostUri(page, "tcp://example.paseo.test:7443?ssl=true&password=shared-secret");
|
||||
await toggleHostAdvanced(page);
|
||||
|
||||
await expectDirectHostFormValues(page, {
|
||||
host: "example.paseo.test",
|
||||
port: "7443",
|
||||
password: "shared-secret",
|
||||
await test.step("Form fields become a URI", async () => {
|
||||
await fillDirectHostAddress(page, "example.paseo.test", "7443");
|
||||
await toggleDirectHostSsl(page);
|
||||
await selectDirectConnectionMode(page, "URI");
|
||||
await expectDirectHostUriValue(page, "tcp://example.paseo.test:7443?ssl=true");
|
||||
});
|
||||
await expectDirectHostSslEnabled(page);
|
||||
await expectDirectHostUriHidden(page);
|
||||
|
||||
await toggleHostAdvanced(page);
|
||||
await expectDirectHostUriValue(
|
||||
page,
|
||||
"tcp://example.paseo.test:7443?ssl=true&password=shared-secret",
|
||||
);
|
||||
await toggleHostAdvanced(page);
|
||||
await expectDirectHostUriHidden(page);
|
||||
await test.step("a URI becomes Form fields", async () => {
|
||||
await fillDirectHostUri(
|
||||
page,
|
||||
"tcp://example.paseo.test:7443?ssl=true&password=shared-secret",
|
||||
);
|
||||
await selectDirectConnectionMode(page, "Form");
|
||||
await expectDirectHostFormValues(page, {
|
||||
host: "example.paseo.test",
|
||||
port: "7443",
|
||||
password: "shared-secret",
|
||||
});
|
||||
await expectDirectHostSslEnabled(page);
|
||||
await expectDirectHostUriHidden(page);
|
||||
});
|
||||
|
||||
await test.step("a pairing link pasted into Host stays a URI", async () => {
|
||||
const link = "relay://relay.paseo.test:443/srv_e2e_pairing?key=daemon-key&ssl=true";
|
||||
await pasteIntoDirectHost(page, link);
|
||||
await expectDirectConnectionMode(page, "URI");
|
||||
await expectDirectHostUriValue(page, link);
|
||||
await expectDirectFormModeDisabled(page);
|
||||
});
|
||||
});
|
||||
|
||||
test("direct connection connects to a URI with Host blank", async ({ page }) => {
|
||||
await gotoAppShell(page);
|
||||
await openSettings(page);
|
||||
await openAddHostFlow(page);
|
||||
await selectHostConnectionType(page, "direct");
|
||||
|
||||
await selectDirectConnectionMode(page, "URI");
|
||||
await fillDirectHostUri(page, `tcp://127.0.0.1:${getE2EDaemonPort()}`);
|
||||
|
||||
await connectDirectHost(page);
|
||||
});
|
||||
|
||||
test("direct connection connects to an edited URI instead of the form", async ({ page }) => {
|
||||
await gotoAppShell(page);
|
||||
await openSettings(page);
|
||||
await openAddHostFlow(page);
|
||||
await selectHostConnectionType(page, "direct");
|
||||
|
||||
await fillDirectHostAddress(page, "127.0.0.1", "9");
|
||||
await selectDirectConnectionMode(page, "URI");
|
||||
await expectDirectHostUriValue(page, "tcp://127.0.0.1:9");
|
||||
await fillDirectHostUri(page, `tcp://127.0.0.1:${getE2EDaemonPort()}`);
|
||||
|
||||
await connectDirectHost(page);
|
||||
});
|
||||
|
||||
test("direct connection sends the password in a URI and asks again when it is wrong", async ({
|
||||
page,
|
||||
}) => {
|
||||
const password = "e2e uri password";
|
||||
const daemon = await startIsolatedHostDaemon("srv_e2e_uri_password_host", {
|
||||
environment: { ...process.env, PASEO_PASSWORD: password },
|
||||
});
|
||||
try {
|
||||
await gotoAppShell(page);
|
||||
await openSettings(page);
|
||||
|
||||
await test.step("a URI with the password connects with one tap", async () => {
|
||||
await openAddHostFlow(page);
|
||||
await selectHostConnectionType(page, "direct");
|
||||
await selectDirectConnectionMode(page, "URI");
|
||||
await fillDirectHostUri(
|
||||
page,
|
||||
`tcp://127.0.0.1:${daemon.port}?password=${encodeURIComponent(password)}`,
|
||||
);
|
||||
await connectDirectHost(page);
|
||||
});
|
||||
|
||||
await test.step("a wrong password asks for the host's password inline", async () => {
|
||||
await openAddHostFlow(page);
|
||||
await selectHostConnectionType(page, "direct");
|
||||
await selectDirectConnectionMode(page, "URI");
|
||||
await fillDirectHostUri(page, `tcp://127.0.0.1:${daemon.port}?password=wrong`);
|
||||
await connectDirectHostExpectingPassword(page, `127.0.0.1:${daemon.port}`);
|
||||
await fillDirectHostPromptPassword(page, password);
|
||||
await connectDirectHost(page);
|
||||
});
|
||||
} finally {
|
||||
await daemon.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("Escape lets settings dropdowns and modals close before leaving settings", async ({
|
||||
@@ -697,3 +765,16 @@ test("docked navigation keeps its density and Settings preserves reading width",
|
||||
await expectSettingsSidebarHidden(page);
|
||||
await expectAppearanceContent(page);
|
||||
});
|
||||
|
||||
test.describe("Settings — small phone", () => {
|
||||
test.use({ viewport: { width: 360, height: 640 } });
|
||||
|
||||
test("direct connection shows the whole form above Cancel and Connect", async ({ page }) => {
|
||||
await gotoAppShell(page);
|
||||
await openCompactSidebar(page);
|
||||
await openSettingsFromCompactSidebar(page);
|
||||
await openAddHostFlow(page);
|
||||
await selectHostConnectionType(page, "direct");
|
||||
await expectDirectFormFullyVisible(page);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,6 +3,7 @@ import { buildHostAgentDetailRoute } from "@/utils/host-routes";
|
||||
import { test } from "../support/fixtures";
|
||||
import { seedWorkspace, type SeedDaemonClient } from "../support/helpers/seed-client";
|
||||
import { getServerId } from "../support/helpers/server-id";
|
||||
import { getE2EDaemonPort } from "../support/helpers/daemon-port";
|
||||
import { observeTimelineSubscriptions } from "../support/helpers/timeline-delivery";
|
||||
import { waitForWorkspaceTabsVisible } from "../support/helpers/workspace-tabs";
|
||||
import { selectWorkspaceInSidebar } from "../support/helpers/sidebar";
|
||||
@@ -254,7 +255,226 @@ async function expectCurrentChatWithoutCatchUp(page: Page, message: string) {
|
||||
await expect(page.getByRole("alert").filter({ hasText: "Updating messages" })).toHaveCount(0);
|
||||
}
|
||||
|
||||
async function delayActiveDaemonPongs(page: Page, port: string) {
|
||||
let deliveredPongs = 0;
|
||||
let inFlightPings = 0;
|
||||
const delayedPongs = new Set<ReturnType<typeof setTimeout>>();
|
||||
await page.routeWebSocket(
|
||||
(url) => url.hostname === "localhost" && url.port === port,
|
||||
(socket) => {
|
||||
const server = socket.connectToServer();
|
||||
socket.onMessage((message) => {
|
||||
if (typeof message === "string" && JSON.parse(message).type === "ping") inFlightPings += 1;
|
||||
server.send(message);
|
||||
});
|
||||
server.onMessage((message) => {
|
||||
if (typeof message === "string" && JSON.parse(message).type === "pong") {
|
||||
const timer = setTimeout(() => {
|
||||
delayedPongs.delete(timer);
|
||||
socket.send(message);
|
||||
deliveredPongs += 1;
|
||||
inFlightPings -= 1;
|
||||
}, 1_000);
|
||||
delayedPongs.add(timer);
|
||||
} else {
|
||||
socket.send(message);
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
return {
|
||||
delivered: () => deliveredPongs,
|
||||
settled: () => inFlightPings === 0 && delayedPongs.size === 0,
|
||||
dispose: () => {
|
||||
for (const timer of delayedPongs) clearTimeout(timer);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function readActiveLivenessRtt(page: Page): Promise<number> {
|
||||
return page.evaluate((serverId) => {
|
||||
const runtime = Reflect.get(globalThis, "__paseoHostRuntimeStore") as {
|
||||
getClient(id: string): { getLastLivenessRttMs(): number | null } | null;
|
||||
};
|
||||
return runtime.getClient(serverId)?.getLastLivenessRttMs() ?? 0;
|
||||
}, getServerId());
|
||||
}
|
||||
|
||||
async function readHostConnection(page: Page) {
|
||||
return page.evaluate((serverId) => {
|
||||
const runtime = Reflect.get(globalThis, "__paseoHostRuntimeStore") as {
|
||||
getSnapshot(id: string): {
|
||||
clientGeneration: number;
|
||||
connectionStatus: string;
|
||||
activeConnectionId: string;
|
||||
};
|
||||
};
|
||||
const snapshot = runtime.getSnapshot(serverId);
|
||||
return {
|
||||
generation: snapshot.clientGeneration,
|
||||
status: snapshot.connectionStatus,
|
||||
connection: snapshot.activeConnectionId,
|
||||
};
|
||||
}, getServerId());
|
||||
}
|
||||
|
||||
async function settleHostProbeCycle(page: Page): Promise<void> {
|
||||
await page.evaluate(async (serverId) => {
|
||||
const runtime = Reflect.get(globalThis, "__paseoHostRuntimeStore") as {
|
||||
runProbeCycleNow(id: string): Promise<void>;
|
||||
};
|
||||
// Joins any in-flight cycle through its final replacement handshake.
|
||||
await runtime.runProbeCycleNow(serverId);
|
||||
}, getServerId());
|
||||
}
|
||||
|
||||
async function observeContinuousHostConnection(page: Page) {
|
||||
const observation = await page.evaluateHandle((serverId) => {
|
||||
const runtime = Reflect.get(globalThis, "__paseoHostRuntimeStore") as {
|
||||
getSnapshot(id: string): { connectionStatus: string; client: unknown } | null;
|
||||
subscribe(id: string, listener: () => void): () => void;
|
||||
};
|
||||
const connected: boolean[] = [];
|
||||
const record = () => {
|
||||
const snapshot = runtime.getSnapshot(serverId);
|
||||
connected.push(snapshot?.connectionStatus === "online" && snapshot.client !== null);
|
||||
};
|
||||
record();
|
||||
const unsubscribe = runtime.subscribe(serverId, record);
|
||||
return {
|
||||
stop() {
|
||||
unsubscribe();
|
||||
return connected;
|
||||
},
|
||||
};
|
||||
}, getServerId());
|
||||
let stopped: Promise<boolean[]> | null = null;
|
||||
return {
|
||||
stop() {
|
||||
stopped ??= observation
|
||||
.evaluate((recorder) => recorder.stop())
|
||||
.finally(() => observation.dispose());
|
||||
return stopped;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function advanceToOnlineReplacement(
|
||||
page: Page,
|
||||
delayedPongs: Awaited<ReturnType<typeof delayActiveDaemonPongs>>,
|
||||
beforeGeneration: number,
|
||||
) {
|
||||
// Advance scheduling, not the sockets: settle real heartbeat and probe replies
|
||||
// between hops, including the replacement handshake, without altering production timers.
|
||||
for (let step = 0; step < 60; step += 1) {
|
||||
if ((await readHostConnection(page)).generation !== beforeGeneration) break;
|
||||
await expect.poll(delayedPongs.settled, { timeout: 10_000 }).toBe(true);
|
||||
await settleHostProbeCycle(page);
|
||||
const pongsBefore = delayedPongs.delivered();
|
||||
await page.clock.fastForward(10_000);
|
||||
await expect
|
||||
.poll(
|
||||
async () =>
|
||||
(await readHostConnection(page)).generation !== beforeGeneration ||
|
||||
delayedPongs.delivered() > pongsBefore,
|
||||
{ timeout: 10_000 },
|
||||
)
|
||||
.toBe(true);
|
||||
await settleHostProbeCycle(page);
|
||||
}
|
||||
}
|
||||
|
||||
test.describe("Viewed agent timelines", () => {
|
||||
test("an online connection replacement keeps every open chat synchronized", async ({
|
||||
page,
|
||||
}, testInfo) => {
|
||||
test.setTimeout(180_000);
|
||||
await page.clock.install();
|
||||
const port = getE2EDaemonPort();
|
||||
const delayedEndpoint = `localhost:${port}`;
|
||||
const fasterEndpoint = `127.0.0.1:${port}`;
|
||||
const delayedPongs = await delayActiveDaemonPongs(page, port);
|
||||
const subscriptions = observeTimelineSubscriptions(page);
|
||||
const scenario = await seedViewedTimelineScenario();
|
||||
let connectionObservation:
|
||||
| Awaited<ReturnType<typeof observeContinuousHostConnection>>
|
||||
| undefined;
|
||||
try {
|
||||
await commitMessage(scenario, scenario.firstAgentId, "BEFORE_CONNECTION_REPLACEMENT");
|
||||
await openAgent(page, scenario, scenario.firstAgentId);
|
||||
await selectAgent(page, "Second viewed chat");
|
||||
await selectAgent(page, "First viewed chat");
|
||||
await subscriptions.waitForSubscribedAgents([scenario.firstAgentId, scenario.secondAgentId]);
|
||||
await expectReconnectingToastGone(page);
|
||||
// The adaptive selector needs an RTT from the active socket, not only its startup probe.
|
||||
await expect.poll(delayedPongs.delivered, { timeout: 30_000 }).toBeGreaterThan(1);
|
||||
await expect
|
||||
.poll(() => readActiveLivenessRtt(page), { timeout: 30_000 })
|
||||
.toBeGreaterThanOrEqual(800);
|
||||
|
||||
// Add another real route to the same daemon. Delaying only the active route's real
|
||||
// pong frames gives the ordinary adaptive selector three consistently faster probes.
|
||||
// No host state is forced offline and no client or timeline owner is replaced by the test.
|
||||
connectionObservation = await observeContinuousHostConnection(page);
|
||||
const beforeGeneration = await page.evaluate(
|
||||
async ({ serverId, endpoint, activeEndpoint }) => {
|
||||
const runtime = Reflect.get(globalThis, "__paseoHostRuntimeStore") as {
|
||||
getSnapshot(id: string): {
|
||||
clientGeneration: number;
|
||||
connectionStatus: string;
|
||||
activeConnectionId: string;
|
||||
};
|
||||
upsertDirectConnection(input: { serverId: string; endpoint: string }): Promise<unknown>;
|
||||
};
|
||||
const before = runtime.getSnapshot(serverId);
|
||||
if (
|
||||
before.connectionStatus !== "online" ||
|
||||
before.activeConnectionId !== `direct:${activeEndpoint}`
|
||||
) {
|
||||
throw new Error("Expected the initial real connection to be online");
|
||||
}
|
||||
await runtime.upsertDirectConnection({ serverId, endpoint });
|
||||
return before.clientGeneration;
|
||||
},
|
||||
{ serverId: getServerId(), endpoint: fasterEndpoint, activeEndpoint: delayedEndpoint },
|
||||
);
|
||||
subscriptions.reset();
|
||||
await advanceToOnlineReplacement(page, delayedPongs, beforeGeneration);
|
||||
await expect
|
||||
.poll(() => readHostConnection(page), { timeout: 3_000 })
|
||||
.toEqual({
|
||||
generation: beforeGeneration + 1,
|
||||
status: "online",
|
||||
connection: `direct:${fasterEndpoint}`,
|
||||
});
|
||||
expect(await connectionObservation.stop()).not.toContain(false);
|
||||
await expectReconnectingToastGone(page, { timeout: 3_000 });
|
||||
await page.screenshot({
|
||||
path: testInfo.outputPath("after-online-connection-replacement.png"),
|
||||
});
|
||||
await subscriptions.waitForSubscribedAgents([scenario.firstAgentId], { match: "includes" });
|
||||
await commitMessage(scenario, scenario.firstAgentId, "FIRST_CHAT_AFTER_REPLACEMENT");
|
||||
await expect(page.getByText("FIRST_CHAT_AFTER_REPLACEMENT", { exact: true })).toBeVisible();
|
||||
await commitMessage(scenario, scenario.secondAgentId, "SECOND_CHAT_WHILE_HIDDEN");
|
||||
await selectAgent(page, "Second viewed chat");
|
||||
await expectReconnectingToastGone(page, { timeout: 3_000 });
|
||||
await expect(page.getByText("SECOND_CHAT_WHILE_HIDDEN", { exact: true })).toBeVisible();
|
||||
await subscriptions.waitForSubscribedAgents([scenario.firstAgentId, scenario.secondAgentId], {
|
||||
match: "includes",
|
||||
});
|
||||
await commitMessage(scenario, scenario.secondAgentId, "SECOND_CHAT_AFTER_REPLACEMENT");
|
||||
await expect(page.getByText("SECOND_CHAT_AFTER_REPLACEMENT", { exact: true })).toBeVisible();
|
||||
await page.screenshot({ path: testInfo.outputPath("both-chats-synchronized.png") });
|
||||
} finally {
|
||||
try {
|
||||
await connectionObservation?.stop();
|
||||
} finally {
|
||||
delayedPongs.dispose();
|
||||
await scenario.cleanup();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("a reloaded layout subscribes only the chat it restores into", async ({ page }) => {
|
||||
test.setTimeout(120_000);
|
||||
const subscriptions = observeTimelineSubscriptions(page);
|
||||
|
||||
@@ -111,7 +111,7 @@ Keep generated screenshots, recordings, and run logs outside the repository.
|
||||
confirmation. It first types without tapping the input to verify autofocus, then cancels the
|
||||
confirmation, closes and reopens the underlying sheet, confirms again,
|
||||
and completes the password retry. `stacked-settings.ad` checks the same return and retry through
|
||||
Settings → add host → Direct connection → Advanced. Run both on phones and tablets so both the
|
||||
Settings → add host → Direct connection → URI. Run both on phones and tablets so both the
|
||||
bottom sheet and centered dialog are exercised.
|
||||
|
||||
These integration journeys require the host-confirmation flow in the test app. Include both the
|
||||
@@ -146,7 +146,7 @@ Android uses the same journeys: copy each script outside the repository, change
|
||||
artifacts, and sessions separate from other runs. These host-dependent journeys remain outside the
|
||||
default mobile suite, alongside the existing modal-sheet scripts.
|
||||
|
||||
On iPhone, bulk replacement or bulk keyboard entry of the advanced URI field triggers a
|
||||
On iPhone, bulk replacement or bulk keyboard entry of the Connection URI field triggers a
|
||||
repeated-update error with both the parent and stacked-sheet implementations. Entering the complete
|
||||
URI one character at a time passed with both implementations; faster typing remains unverified.
|
||||
On iPad, replacing the field a second time appends text. For this Settings journey, use the
|
||||
|
||||
@@ -10,7 +10,7 @@ wait "id=\"add-host-method-direct\"" 10000
|
||||
screenshot "${OUT}/10-add-host-methods.png"
|
||||
press "id=\"add-host-method-direct\""
|
||||
wait stable
|
||||
press "id=\"direct-host-advanced-toggle\""
|
||||
press "id=\"direct-mode-uri\""
|
||||
wait stable
|
||||
fill "id=\"direct-host-uri-input\"" "${PAIRING_LINK}"
|
||||
wait stable
|
||||
@@ -32,9 +32,9 @@ wait "id=\"host-confirmation-connect\"" 10000
|
||||
screenshot "${OUT}/14-add-host-confirmation-reopens.png"
|
||||
press "id=\"host-confirmation-connect\""
|
||||
wait stable
|
||||
wait "id=\"direct-password-input\"" 20000
|
||||
wait "id=\"direct-uri-password-input\"" 20000
|
||||
screenshot "${OUT}/15-add-host-password.png"
|
||||
fill "id=\"direct-password-input\"" "${PASSWORD}"
|
||||
fill "id=\"direct-uri-password-input\"" "${PASSWORD}"
|
||||
wait stable
|
||||
press "id=\"direct-host-submit\""
|
||||
wait stable
|
||||
|
||||
@@ -31,6 +31,8 @@ export interface RewindCompletionGate {
|
||||
clearTimelineStreamCount(): void;
|
||||
release(): void;
|
||||
timelineStreamCount(): number;
|
||||
/** Timeline reads this page sent since the last clear. */
|
||||
timelineFetchCount(): number;
|
||||
waitForDelayedResponse(): Promise<void>;
|
||||
}
|
||||
|
||||
@@ -186,12 +188,20 @@ 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) => {
|
||||
@@ -200,7 +210,16 @@ export async function holdRewindCompletion(
|
||||
|
||||
await page.routeWebSocket(daemonWsRoutePattern(), (ws) => {
|
||||
const server = ws.connectToServer();
|
||||
ws.onMessage((message) => server.send(message));
|
||||
ws.onMessage((message) => {
|
||||
const sessionMessage = getSessionMessage(message);
|
||||
if (
|
||||
sessionMessage?.type === "fetch_agent_timeline_request" &&
|
||||
sessionMessage.agentId === agentId
|
||||
) {
|
||||
timelineFetchCount += 1;
|
||||
}
|
||||
server.send(message);
|
||||
});
|
||||
server.onMessage((message) => {
|
||||
const sessionMessage = getSessionMessage(message);
|
||||
const payload = sessionMessage ? getPayload(sessionMessage) : null;
|
||||
@@ -216,11 +235,11 @@ export async function holdRewindCompletion(
|
||||
}
|
||||
if (
|
||||
!released &&
|
||||
(sessionMessage?.type === "agent.rewind.response" ||
|
||||
sessionMessage?.type === "agent.timeline.replacement") &&
|
||||
sessionMessage &&
|
||||
REWIND_COMPLETION_MESSAGES.has(String(sessionMessage.type)) &&
|
||||
payload?.agentId === agentId
|
||||
) {
|
||||
// The replacement also signals completion and removes the rewound row/menu.
|
||||
// The rewind 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?.();
|
||||
@@ -233,6 +252,7 @@ export async function holdRewindCompletion(
|
||||
return {
|
||||
clearTimelineStreamCount() {
|
||||
timelineStreamCount = 0;
|
||||
timelineFetchCount = 0;
|
||||
},
|
||||
release() {
|
||||
released = true;
|
||||
@@ -241,6 +261,7 @@ export async function holdRewindCompletion(
|
||||
}
|
||||
},
|
||||
timelineStreamCount: () => timelineStreamCount,
|
||||
timelineFetchCount: () => timelineFetchCount,
|
||||
waitForDelayedResponse: () => delayedResponse,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -258,8 +258,37 @@ export async function expectAddHostFieldDrawnAsInput(page: Page, testId: string)
|
||||
await expect(field).not.toHaveCSS("background-color", "rgba(0, 0, 0, 0)");
|
||||
}
|
||||
|
||||
export async function toggleHostAdvanced(page: Page): Promise<void> {
|
||||
await page.getByTestId("direct-host-advanced-toggle").click();
|
||||
function directConnectionModeSegment(page: Page, mode: "Form" | "URI") {
|
||||
return page.getByTestId("direct-mode").getByRole("button", { name: mode, exact: true });
|
||||
}
|
||||
|
||||
export async function selectDirectConnectionMode(page: Page, mode: "Form" | "URI"): Promise<void> {
|
||||
await directConnectionModeSegment(page, mode).click();
|
||||
await expectDirectConnectionMode(page, mode);
|
||||
}
|
||||
|
||||
export async function expectDirectConnectionMode(page: Page, mode: "Form" | "URI"): Promise<void> {
|
||||
await expect(directConnectionModeSegment(page, mode)).toHaveAttribute("aria-selected", "true");
|
||||
}
|
||||
|
||||
export async function expectDirectFormModeDisabled(page: Page): Promise<void> {
|
||||
await expect(directConnectionModeSegment(page, "Form")).toBeDisabled();
|
||||
}
|
||||
|
||||
export async function connectDirectHost(page: Page): Promise<void> {
|
||||
await page.getByTestId("direct-host-submit").click();
|
||||
await expect(page.getByTestId("add-host-modal")).toHaveCount(0, { timeout: 30_000 });
|
||||
}
|
||||
|
||||
export async function connectDirectHostExpectingPassword(page: Page, host: string): Promise<void> {
|
||||
await page.getByTestId("direct-host-submit").click();
|
||||
await expect(page.getByText(`Password for ${host}`, { exact: true })).toBeVisible({
|
||||
timeout: 30_000,
|
||||
});
|
||||
}
|
||||
|
||||
export async function fillDirectHostPromptPassword(page: Page, password: string): Promise<void> {
|
||||
await page.getByRole("textbox", { name: "Host password", exact: true }).fill(password);
|
||||
}
|
||||
|
||||
export async function openCompactSettings(page: Page, expectedStartRoute: string): Promise<void> {
|
||||
@@ -422,6 +451,10 @@ export async function fillDirectHostAddress(page: Page, host: string, port: stri
|
||||
await page.getByRole("textbox", { name: "Port", exact: true }).fill(port);
|
||||
}
|
||||
|
||||
export async function pasteIntoDirectHost(page: Page, text: string): Promise<void> {
|
||||
await page.getByRole("textbox", { name: "Host", exact: true }).fill(text);
|
||||
}
|
||||
|
||||
export async function toggleDirectHostSsl(page: Page): Promise<void> {
|
||||
await page.getByRole("checkbox", { name: "Use SSL", exact: true }).click();
|
||||
}
|
||||
@@ -439,6 +472,12 @@ export async function expectDirectHostUriHidden(page: Page): Promise<void> {
|
||||
await expect(page.getByTestId("direct-host-uri-input")).toHaveCount(0);
|
||||
}
|
||||
|
||||
/** The whole form shows above Cancel and Connect, with nothing cut off by the footer. */
|
||||
export async function expectDirectFormFullyVisible(page: Page): Promise<void> {
|
||||
await expect(page.getByTestId("direct-password-input")).toBeInViewport({ ratio: 1 });
|
||||
await expect(page.getByTestId("direct-password-visibility-toggle")).toBeInViewport({ ratio: 1 });
|
||||
}
|
||||
|
||||
export async function expectDiagnosticsContent(page: Page): Promise<void> {
|
||||
await expect(page.getByRole("button", { name: "Run" })).toBeVisible();
|
||||
await expect(page.getByRole("button", { name: "Play test" })).toBeVisible();
|
||||
|
||||
@@ -9,6 +9,7 @@ interface SessionMessage {
|
||||
|
||||
interface TimelineSubscriptionWaitOptions {
|
||||
timeout?: number;
|
||||
match?: "exact" | "includes";
|
||||
}
|
||||
|
||||
function readSessionMessage(message: WebSocketMessage): SessionMessage | null {
|
||||
@@ -56,7 +57,7 @@ export function observeTimelineSubscriptions(page: Page) {
|
||||
.poll(() => acknowledgedAgentIds?.slice().sort() ?? null, {
|
||||
timeout: options.timeout ?? 15_000,
|
||||
})
|
||||
.toEqual(expected);
|
||||
.toEqual(options.match === "includes" ? expect.arrayContaining(expected) : expected);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -3,9 +3,12 @@ import { useTranslation } from "react-i18next";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
import { useProviderIcon } from "@/components/provider-icons";
|
||||
import type { PanelDescriptor } from "@/panels/panel-registry";
|
||||
import { resolveAgentLabel } from "@/panels/tab-labels";
|
||||
import { useSessionStore, selectAgentTurnPresentation, type Agent } from "@/stores/session-store";
|
||||
import { deriveSidebarStateBucket } from "@/utils/sidebar-agent-state";
|
||||
|
||||
export { resolveAgentLabel };
|
||||
|
||||
function formatProviderLabel(provider: Agent["provider"]): string {
|
||||
if (!provider) {
|
||||
return "Agent";
|
||||
@@ -17,20 +20,6 @@ function formatProviderLabel(provider: Agent["provider"]): string {
|
||||
.join(" ");
|
||||
}
|
||||
|
||||
export function resolveAgentLabel(title: string | null | undefined): string | null {
|
||||
if (typeof title !== "string") {
|
||||
return null;
|
||||
}
|
||||
const normalized = title.trim();
|
||||
if (!normalized) {
|
||||
return null;
|
||||
}
|
||||
if (normalized.toLowerCase() === "new agent") {
|
||||
return null;
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
export function useAgentDescriptor(
|
||||
target: { kind: "agent"; agentId: string },
|
||||
context: { serverId: string },
|
||||
|
||||
@@ -23,7 +23,15 @@ export interface DraftAgentProfileControls {
|
||||
}
|
||||
|
||||
export type AgentProfileApplyTarget =
|
||||
| { kind: "agent"; agentId: string; availableModeIds: readonly string[] | null }
|
||||
| {
|
||||
kind: "agent";
|
||||
agentId: string;
|
||||
availableModeIds: readonly string[] | null;
|
||||
currentProvider?: string | null;
|
||||
isSwitchInFlight?: () => boolean;
|
||||
onApplySameProvider?: () => void;
|
||||
onStageProviderSwitch?: (profile: MaterializedAgentProfile) => void;
|
||||
}
|
||||
| { kind: "draft"; controls: DraftAgentProfileControls };
|
||||
|
||||
/** Everything the model picker renders for one profile. It never sees the profile itself. */
|
||||
@@ -148,6 +156,16 @@ export function useAgentProfilePicker(
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
target.onStageProviderSwitch &&
|
||||
(target.isSwitchInFlight?.() ||
|
||||
(target.currentProvider && resolved.provider !== target.currentProvider))
|
||||
) {
|
||||
target.onStageProviderSwitch(resolved);
|
||||
return;
|
||||
}
|
||||
|
||||
target.onApplySameProvider?.();
|
||||
const reconciled = reconcileMaterializedProfileMode(resolved, target.availableModeIds);
|
||||
if (!reconciled) {
|
||||
return;
|
||||
@@ -157,7 +175,11 @@ export function useAgentProfilePicker(
|
||||
return;
|
||||
}
|
||||
void client
|
||||
.applyAgentConfig(target.agentId, toAgentConfigApply(reconciled))
|
||||
.applyAgentConfig(
|
||||
target.agentId,
|
||||
toAgentConfigApply(reconciled),
|
||||
target.currentProvider ? { expectedProvider: target.currentProvider } : undefined,
|
||||
)
|
||||
.then((notice) => showProviderNoticeToast(toast, notice))
|
||||
.catch((error) => {
|
||||
console.warn("[useAgentProfilePicker] applyAgentConfig failed", error);
|
||||
|
||||
@@ -56,6 +56,7 @@ export function ChatFind({
|
||||
agentId,
|
||||
serverId,
|
||||
epoch,
|
||||
rewindSeq,
|
||||
items,
|
||||
viewportRef,
|
||||
revealLoadedMessage,
|
||||
@@ -95,8 +96,8 @@ export function ChatFind({
|
||||
);
|
||||
const state = useSyncExternalStore(model.subscribe, model.getSnapshot, model.getSnapshot);
|
||||
useEffect(() => {
|
||||
model.updateHistory(epoch, items);
|
||||
}, [model, epoch, items]);
|
||||
model.updateHistory(epoch, items, rewindSeq);
|
||||
}, [model, epoch, items, rewindSeq]);
|
||||
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 },
|
||||
timelineCursor: { epoch: "epoch", seq, anchorSeq: 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 },
|
||||
timelineCursor: { epoch: "epoch", seq: index + 1, anchorSeq: 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);
|
||||
model.updateHistory("epoch", history, null);
|
||||
},
|
||||
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", []);
|
||||
model.updateHistory("epoch", [], null);
|
||||
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)]);
|
||||
model.updateHistory("epoch", [message(1), message(2)], null);
|
||||
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)]);
|
||||
model.updateHistory("epoch", [message(1)], null);
|
||||
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", []);
|
||||
model.updateHistory("epoch", [], null);
|
||||
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", []);
|
||||
model.updateHistory("epoch", [], null);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("error");
|
||||
@@ -207,24 +207,160 @@ it("reports a search result that outlived its epoch as a changed history", async
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory("epoch", [message(1)]);
|
||||
model.updateHistory("epoch", [message(1)], null);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
|
||||
model.updateHistory("epoch-2", [message(1)]);
|
||||
model.updateHistory("epoch-2", [message(1)], null);
|
||||
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)]);
|
||||
model.updateHistory("epoch", [message(1)], null);
|
||||
},
|
||||
async reveal() {
|
||||
return { count: 1, occurrence: 0 };
|
||||
@@ -232,7 +368,7 @@ it("can load a search location before the initial chat history has arrived", asy
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory(null, []);
|
||||
model.updateHistory(null, [], null);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
|
||||
@@ -260,7 +396,7 @@ it("reports the position across the whole chat and corrects it with rendered cou
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory("epoch", [message(1), message(2)]);
|
||||
model.updateHistory("epoch", [message(1), message(2)], null);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
|
||||
@@ -297,7 +433,7 @@ it("counts one match per message from a host that reports no counts", async () =
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory("epoch", [message(1), message(2)]);
|
||||
model.updateHistory("epoch", [message(1), message(2)], null);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
|
||||
|
||||
@@ -76,6 +76,10 @@ 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;
|
||||
@@ -113,6 +117,7 @@ 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 };
|
||||
@@ -144,6 +149,7 @@ export class ChatFindModel {
|
||||
});
|
||||
}
|
||||
private async search(signal: AbortSignal) {
|
||||
this.searchedRewindSeq = this.rewindSeq;
|
||||
try {
|
||||
let cursor: number | undefined;
|
||||
do {
|
||||
@@ -168,15 +174,14 @@ export class ChatFindModel {
|
||||
this.fail(error, signal);
|
||||
}
|
||||
}
|
||||
updateHistory(epoch: string | null, items: StreamItem[]) {
|
||||
if (
|
||||
this.resultEpoch !== null &&
|
||||
epoch !== null &&
|
||||
epoch !== this.resultEpoch &&
|
||||
this.state.open
|
||||
) {
|
||||
/** `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) {
|
||||
this.fail(new ChatFindFailureError("historyChanged"), this.abort.signal);
|
||||
}
|
||||
this.rewindSeq = rewindSeq;
|
||||
this.epoch = epoch;
|
||||
this.items = items;
|
||||
this.historyListeners.forEach((listener) => listener());
|
||||
|
||||
@@ -9,6 +9,8 @@ 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 },
|
||||
timelineCursor: { epoch: "epoch-1", seq, anchorSeq: 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 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 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 },
|
||||
timelineCursor: { epoch: "epoch-2", seq: 1, anchorSeq: 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 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 1, anchorSeq: 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 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 1, anchorSeq: 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 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 2 },
|
||||
};
|
||||
const revealLoadedMessage = vi.fn();
|
||||
revealLoadedMessage.mockReturnValue(false);
|
||||
|
||||
@@ -58,7 +58,11 @@ function installProbe(
|
||||
return function() {};
|
||||
} };
|
||||
})`;
|
||||
const evaluated = runPluginClientBundle("probe-plugin", clientBundle, runtime);
|
||||
const evaluated = runPluginClientBundle(
|
||||
{ serverId: "test-host", pluginId: "probe-plugin" },
|
||||
clientBundle,
|
||||
runtime,
|
||||
);
|
||||
return {
|
||||
...evaluated,
|
||||
serverId: "host-1",
|
||||
@@ -322,7 +326,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 } };
|
||||
const canonical = { ...live, timelineCursor: { epoch: "epoch-1", seq: 42, anchorSeq: 42 } };
|
||||
const present = createStreamPresentation();
|
||||
present({ ...presentationOptions, tail: [], head: [live], transform: undefined });
|
||||
const repointed = rows(
|
||||
@@ -332,7 +336,7 @@ describe("stream presentation through installed plugins", () => {
|
||||
{
|
||||
id: streamed[0]!.id,
|
||||
text: "Streamed answer",
|
||||
timelineCursor: { epoch: "epoch-1", seq: 42 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 42, anchorSeq: 42 },
|
||||
},
|
||||
]);
|
||||
});
|
||||
@@ -519,7 +523,7 @@ describe("timeline presentation", () => {
|
||||
messageId: "provider-message",
|
||||
clientMessageId: "client-message",
|
||||
turnId: "turn-1",
|
||||
timelineCursor: { epoch: "epoch", seq: 12 },
|
||||
timelineCursor: { epoch: "epoch", seq: 12, anchorSeq: 12 },
|
||||
});
|
||||
const presentMessage = () =>
|
||||
present({
|
||||
|
||||
@@ -1677,7 +1677,7 @@ describe("createWebStreamStrategy", () => {
|
||||
},
|
||||
},
|
||||
timestamp: new Date("2026-11-29T13:00:00.000Z"),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 1 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 1, anchorSeq: 1 },
|
||||
},
|
||||
{
|
||||
event: {
|
||||
@@ -1691,7 +1691,7 @@ describe("createWebStreamStrategy", () => {
|
||||
},
|
||||
},
|
||||
timestamp: new Date("2026-11-29T13:00:01.000Z"),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 2 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 2 },
|
||||
},
|
||||
],
|
||||
{ source: "canonical" },
|
||||
|
||||
@@ -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 },
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 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 },
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 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 },
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 42 },
|
||||
};
|
||||
|
||||
expect(
|
||||
@@ -116,7 +116,7 @@ describe("resolveAssistantTurnForkBoundary", () => {
|
||||
it("resolves a fork boundary from the reply a plugin card replaced", () => {
|
||||
const reply = {
|
||||
...assistantMessage("assistant-1", 2, "msg-assistant-1"),
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42 },
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 42 },
|
||||
};
|
||||
const card: StreamItem = {
|
||||
kind: "plugin",
|
||||
@@ -154,7 +154,7 @@ describe("resolveAssistantTurnForkBoundary", () => {
|
||||
const appended: StreamItem = {
|
||||
kind: "plugin",
|
||||
id: "plugin/card-1",
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42 },
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 42 },
|
||||
timestamp: timestamp(2),
|
||||
pluginId: "plugin",
|
||||
pluginItemId: "card-1",
|
||||
|
||||
@@ -1,7 +1,13 @@
|
||||
import { getAssistantReply, type StreamItem, type TimelinePosition } from "@/types/stream";
|
||||
import { getAssistantReply, type StreamItem } from "@/types/stream";
|
||||
|
||||
/** The daemon's timeline cursor; the row's anchor stays in the client. */
|
||||
interface TimelineBoundaryCursor {
|
||||
epoch: string;
|
||||
seq: number;
|
||||
}
|
||||
|
||||
export type AssistantTurnForkBoundary =
|
||||
| { boundaryCursor: TimelinePosition; boundaryMessageId?: string }
|
||||
| { boundaryCursor: TimelineBoundaryCursor; boundaryMessageId?: string }
|
||||
| { boundaryCursor?: undefined; boundaryMessageId: string };
|
||||
|
||||
export function resolveAssistantTurnForkBoundary(input: {
|
||||
@@ -15,7 +21,7 @@ export function resolveAssistantTurnForkBoundary(input: {
|
||||
}
|
||||
if (input.supportsTimelineCursor && reply.timelineCursor) {
|
||||
return {
|
||||
boundaryCursor: reply.timelineCursor,
|
||||
boundaryCursor: { epoch: reply.timelineCursor.epoch, seq: reply.timelineCursor.seq },
|
||||
...(reply.messageId ? { boundaryMessageId: reply.messageId } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -139,7 +139,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 };
|
||||
const cursor = { epoch: "epoch-1", seq: 7, anchorSeq: 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"));
|
||||
|
||||
@@ -101,7 +101,7 @@ function summaryRow(
|
||||
}
|
||||
|
||||
function staysVisibleWhenCollapsed(item: StreamItem): boolean {
|
||||
return isTurnTrigger(item) || item.kind === "compaction";
|
||||
return isTurnTrigger(item) || item.kind === "compaction" || item.kind === "provider_switch";
|
||||
}
|
||||
|
||||
function findLastReplyIndex(tail: StreamItem[], start: number, end: number): number {
|
||||
|
||||
@@ -159,10 +159,10 @@ const projectedReply: StreamItem = {
|
||||
id: "reply",
|
||||
messageId: "provider-reply-1",
|
||||
text: 'Done.\n\n```ui\nCard("Summary", [])\n```',
|
||||
timelineCursor: { epoch: "e1", seq: 5 },
|
||||
timelineCursor: { epoch: "e1", seq: 5, anchorSeq: 5 },
|
||||
timestamp: FRIDAY_NIGHT,
|
||||
},
|
||||
timelineCursor: { epoch: "e1", seq: 5 },
|
||||
timelineCursor: { epoch: "e1", seq: 5, anchorSeq: 5 },
|
||||
timestamp: FRIDAY_NIGHT,
|
||||
pluginId: "genui",
|
||||
pluginItemId: "reply/1",
|
||||
|
||||
@@ -37,6 +37,7 @@ import {
|
||||
ToolCall,
|
||||
TodoListCard,
|
||||
CompactionMarker,
|
||||
ProviderSwitchMarker,
|
||||
MessageOuterSpacingProvider,
|
||||
type InlinePathTarget,
|
||||
} from "@/components/message";
|
||||
@@ -57,6 +58,7 @@ import { useFileExplorerActions } from "@/hooks/use-file-explorer-actions";
|
||||
import { useLoadOlderAgentHistory } from "@/hooks/use-load-older-agent-history";
|
||||
import { resolveContentMaxWidth, useSettings } from "@/hooks/use-settings";
|
||||
import type { ToastApi } from "@/components/toast-host";
|
||||
import { isPromptInActiveSegment } from "@/components/rewind/use-rewind-capabilities";
|
||||
import { returnToTimelineTail } from "./timeline-tail-navigation";
|
||||
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
import { ToolCallDetailsContent } from "@/components/tool-call-details";
|
||||
@@ -408,6 +410,10 @@ 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,
|
||||
);
|
||||
@@ -711,8 +717,15 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
|
||||
|
||||
const setToolCallGroupExpanded = toolCallExpansion.setGroupExpanded;
|
||||
|
||||
const activeSegmentStartSeq = useSessionStore(
|
||||
(state) =>
|
||||
state.sessions[resolvedServerId]?.agentTimelineCursor.get(agentId)?.activeSegmentStartSeq ??
|
||||
0,
|
||||
);
|
||||
|
||||
const renderUserMessageItem = useCallback(
|
||||
(layoutItem: StreamLayoutItem, item: Extract<StreamItem, { kind: "user_message" }>) => {
|
||||
const canRewindPrompt = isPromptInActiveSegment(item.timelineCursor, activeSegmentStartSeq);
|
||||
return (
|
||||
<UserMessage
|
||||
itemId={item.id}
|
||||
@@ -724,7 +737,7 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
|
||||
images={item.images}
|
||||
attachments={item.attachments}
|
||||
timestamp={item.timestamp.getTime()}
|
||||
capabilities={context.capabilities}
|
||||
capabilities={canRewindPrompt ? context.capabilities : undefined}
|
||||
client={client}
|
||||
isFirstInGroup={layoutItem.isFirstInUserGroup}
|
||||
isLastInGroup={layoutItem.isLastInUserGroup}
|
||||
@@ -735,7 +748,14 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
|
||||
/>
|
||||
);
|
||||
},
|
||||
[context.capabilities, agentId, client, pendingClientMessageIds, resolvedServerId],
|
||||
[
|
||||
activeSegmentStartSeq,
|
||||
context.capabilities,
|
||||
agentId,
|
||||
client,
|
||||
pendingClientMessageIds,
|
||||
resolvedServerId,
|
||||
],
|
||||
);
|
||||
|
||||
const renderAssistantMessageItem = useCallback(
|
||||
@@ -949,6 +969,18 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
|
||||
/>
|
||||
);
|
||||
|
||||
case "provider_switch":
|
||||
return (
|
||||
<ProviderSwitchMarker
|
||||
serverId={resolvedServerId}
|
||||
fromProvider={item.fromProvider}
|
||||
toProvider={item.toProvider}
|
||||
fromModel={item.fromModel}
|
||||
toModel={item.toModel}
|
||||
context={item.context}
|
||||
/>
|
||||
);
|
||||
|
||||
case "plugin":
|
||||
return (
|
||||
<PluginTimelineItemView agentId={agentId} item={item} serverId={resolvedServerId} />
|
||||
@@ -1174,6 +1206,7 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
|
||||
agentId={agentId}
|
||||
serverId={resolvedServerId}
|
||||
epoch={timelineEpoch}
|
||||
rewindSeq={timelineRewindSeq}
|
||||
items={findItems}
|
||||
viewportRef={viewportRef}
|
||||
revealLoadedMessage={revealLoadedMessage}
|
||||
|
||||
@@ -75,6 +75,7 @@ export function estimateStreamItemHeight({
|
||||
case "notification":
|
||||
return 88;
|
||||
case "compaction":
|
||||
case "provider_switch":
|
||||
return 72;
|
||||
default:
|
||||
return 120;
|
||||
|
||||
@@ -79,6 +79,7 @@ import { HorizontalScrollProvider } from "@/contexts/horizontal-scroll-context";
|
||||
import { SessionProvider } from "@/contexts/session-context";
|
||||
import { SidebarCalloutProvider } from "@/contexts/sidebar-callout-context";
|
||||
import { ToastProvider } from "@/contexts/toast-context";
|
||||
import { WorkspaceTabCloseErrorToasts } from "@/workspace-tabs/close";
|
||||
import { VoiceProvider } from "@/contexts/voice-context";
|
||||
import {
|
||||
resolveStartupBlocker,
|
||||
@@ -994,6 +995,7 @@ function RootOverlayProviders({ children }: { children: ReactNode }) {
|
||||
<BottomSheetModalProvider>
|
||||
{children}
|
||||
<WindowLayoutActionsHost />
|
||||
<WorkspaceTabCloseErrorToasts />
|
||||
</BottomSheetModalProvider>
|
||||
</PortalProvider>
|
||||
</ToastProvider>
|
||||
|
||||
@@ -954,6 +954,19 @@ it("keeps table cell pipes escaped in text/plain table syntax and literal in tex
|
||||
expect(content?.html).toContain("<td>Value | detail</td>");
|
||||
});
|
||||
|
||||
it("keeps a table cell's line breaks inside its row", () => {
|
||||
const message = mountFixture();
|
||||
message.innerHTML =
|
||||
"<table><thead><tr><th>Name<br>label</th><th>Note</th></tr></thead><tbody><tr><td>first<br>second</td><td><br> stays text</td></tr></tbody></table>";
|
||||
const content = createAssistantSelectionClipboardContent(selectNodeContents(message));
|
||||
expect(content?.plainText).toBe(
|
||||
"| Name<br>label | Note |\n| --- | --- |\n| first<br>second | <br> stays text |",
|
||||
);
|
||||
expect(content?.html).toContain("<th>Name<br>\nlabel</th>");
|
||||
expect(content?.html).toContain("<td>first<br>\nsecond</td>");
|
||||
expect(content?.html).toContain("<td><br> stays text</td>");
|
||||
});
|
||||
|
||||
it("copies a workspace image path instead of its temporary display URL", () => {
|
||||
const message = mountFixture();
|
||||
const sources = JSON.stringify({ "blob:preview": "assets/chart.png" });
|
||||
|
||||
@@ -69,12 +69,13 @@ function createTurndown(flavor: "markdown" | "plain"): TurndownService {
|
||||
});
|
||||
turndown.use(gfm);
|
||||
// text/plain still carries tables as GFM syntax, so a cell's pipe stays escaped there.
|
||||
// A row is one line, so a cell's line break goes back to `<br>`.
|
||||
turndown.addRule("escapedGfmTableCell", {
|
||||
filter: ["th", "td"],
|
||||
replacement: (content, node) => {
|
||||
const index = node.parentNode ? Array.from(node.parentNode.childNodes).indexOf(node) : 0;
|
||||
const prefix = index === 0 ? "| " : " ";
|
||||
return `${prefix}${content.replace(/\|/g, "\\|")} |`;
|
||||
return `${prefix}${content.replace(/\|/g, "\\|").replace(/ *\n/g, "<br>")} |`;
|
||||
},
|
||||
});
|
||||
// A link Paseo recognized pastes as the text the reply showed. Rich paste keeps it as a
|
||||
|
||||
@@ -81,6 +81,7 @@ export function ArchivedAgentCallout({
|
||||
agentId,
|
||||
isWorkspaceRestoring = false,
|
||||
}: ArchivedAgentCalloutProps) {
|
||||
const { t } = useTranslation();
|
||||
const targetKey = `${serverId}:${agentId}`;
|
||||
const toast = useToast();
|
||||
const { unarchive, isUnarchiving, canUnarchive } = useUnarchiveAgent({ serverId, agentId });
|
||||
@@ -110,7 +111,15 @@ export function ArchivedAgentCallout({
|
||||
const attemptKey = targetKey;
|
||||
setUnarchiveErrorState(null);
|
||||
try {
|
||||
await unarchive();
|
||||
await unarchive({
|
||||
onRefreshed: (refreshed) => {
|
||||
if (refreshed.historyDiverged) {
|
||||
toast.show(t("workspace.tabs.toasts.reloadedAgentHistoryDiverged"), {
|
||||
variant: "warning",
|
||||
});
|
||||
}
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
deliverUnarchiveError({
|
||||
error,
|
||||
@@ -121,7 +130,7 @@ export function ArchivedAgentCallout({
|
||||
onToastError: toast.error,
|
||||
});
|
||||
}
|
||||
}, [canUnarchive, targetKey, toast, unarchive]);
|
||||
}, [canUnarchive, t, targetKey, toast, unarchive]);
|
||||
|
||||
return (
|
||||
<KeyboardTranslateView style={styles.container}>
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { Parser } from "htmlparser2";
|
||||
import { fromMarkdown } from "mdast-util-from-markdown";
|
||||
import { gfmTableFromMarkdown } from "mdast-util-gfm-table";
|
||||
import { gfmTable } from "micromark-extension-gfm-table";
|
||||
import { decodeString } from "micromark-util-decode-string";
|
||||
import type { Nodes } from "mdast";
|
||||
|
||||
@@ -53,6 +55,8 @@ export function normalizeMarkdownHtml(source: string): string {
|
||||
} else if ("children" in node) node.children.forEach(protectCode);
|
||||
}
|
||||
protectCode(tree);
|
||||
// Only `<br>` reads these, so a source without one skips the extra parse.
|
||||
const tableRanges = /<br/i.test(source) ? collectTableRanges(source, codeRanges) : [];
|
||||
const links: (string | undefined)[] = [];
|
||||
let previousTag: { name: string; end: number } | null = null;
|
||||
const convert = (raw: string, offset: number): string => {
|
||||
@@ -84,7 +88,16 @@ export function normalizeMarkdownHtml(source: string): string {
|
||||
: /^\s*$/.test(source.slice(0, offset));
|
||||
previousTag = { name, end: offset + raw.length };
|
||||
if (EMPHASIS[name]) return EMPHASIS[name];
|
||||
const boundary = layoutBoundary(name, source, raw, offset, closing, startsAfterBoundary);
|
||||
const inTable = tableRanges.some(({ start, end }) => offset >= start && offset < end);
|
||||
const boundary = layoutBoundary(
|
||||
name,
|
||||
source,
|
||||
raw,
|
||||
offset,
|
||||
closing,
|
||||
startsAfterBoundary,
|
||||
inTable,
|
||||
);
|
||||
if (boundary !== null) return boundary;
|
||||
if (name === "a") return markdownAnchor(raw, closing, links);
|
||||
if (name === "img" && !closing) {
|
||||
@@ -167,8 +180,15 @@ function layoutBoundary(
|
||||
offset: number,
|
||||
closing: boolean,
|
||||
startsAfterBoundary: boolean,
|
||||
inTable: boolean,
|
||||
): string | null {
|
||||
if (name === "br") return closing ? "" : " \n";
|
||||
// Inside GFM table cells, emit ` \u2028 ` so row boundaries stay intact while giving flanking
|
||||
// emphasis/strikethrough delimiters and URLs/autolinks whitespace boundaries on both sides before
|
||||
// the cell-scoped parser turns ` \u2028 ` back into a `LineBreak` node.
|
||||
if (name === "br") {
|
||||
if (closing) return "";
|
||||
return inTable ? " \u2028 " : " \n";
|
||||
}
|
||||
if (name === "summary") return closing ? "**\n\n" : "**";
|
||||
if (name === "details")
|
||||
return (closing ? offset + raw.length === source.length : offset === 0) ? "" : "\n\n";
|
||||
@@ -177,3 +197,67 @@ function layoutBoundary(
|
||||
return /^<t[dh]\b/i.test(source.slice(offset + raw.length)) ? " " : "";
|
||||
return null;
|
||||
}
|
||||
|
||||
function hasNonWhitespaceAfterNewline(value: string): boolean {
|
||||
const lastNewline = value.lastIndexOf("\n");
|
||||
return /[^\s]/.test(lastNewline === -1 ? value : value.slice(lastNewline + 1));
|
||||
}
|
||||
|
||||
function isTableWrapperTag(raw: string, inCode: boolean): boolean {
|
||||
if (inCode) return false;
|
||||
if (raw.startsWith("<!--")) return true;
|
||||
const name = /^<\/?([A-Za-z][A-Za-z0-9-]*)/.exec(raw)?.[1].toLowerCase();
|
||||
return name === "summary" || name === "details" || (name !== undefined && BLOCK_TAGS.has(name));
|
||||
}
|
||||
|
||||
function collectTableRanges(
|
||||
source: string,
|
||||
codeRanges: readonly { start: number; end: number }[],
|
||||
): { start: number; end: number }[] {
|
||||
let cursor = 0;
|
||||
let codeIndex = 0;
|
||||
let lineHasPrefixText = false;
|
||||
// Advance line/code state monotonically in a single forward pass so large single-line HTML tables stay O(n)
|
||||
// while nested leading wrappers (e.g. `<details><summary>Results</summary><div>| A | B |`) follow
|
||||
// line breaks introduced by earlier masked tags.
|
||||
const tableSource = source.replace(HTML, (raw, offset: number) => {
|
||||
for (let index = cursor; index < offset; index++) {
|
||||
const code = source.charCodeAt(index);
|
||||
if (code === 10) lineHasPrefixText = false;
|
||||
else if (code !== 32 && code !== 9 && code !== 13) lineHasPrefixText = true;
|
||||
}
|
||||
cursor = offset + raw.length;
|
||||
while (codeIndex < codeRanges.length && codeRanges[codeIndex].end <= offset) codeIndex++;
|
||||
const inCode = codeIndex < codeRanges.length && offset >= codeRanges[codeIndex].start;
|
||||
if (!isTableWrapperTag(raw, inCode)) {
|
||||
if (inCode || /^<code\b/i.test(raw)) {
|
||||
if (hasNonWhitespaceAfterNewline(raw)) lineHasPrefixText = true;
|
||||
else if (raw.includes("\n")) lineHasPrefixText = false;
|
||||
} else if (raw.includes("\n")) {
|
||||
lineHasPrefixText = false;
|
||||
}
|
||||
return raw;
|
||||
}
|
||||
const blanked = raw.replace(/[^\n]/g, " ");
|
||||
if (!lineHasPrefixText && blanked.length > 0 && !blanked.endsWith("\n")) {
|
||||
return `${blanked.slice(0, -1)}\n`;
|
||||
}
|
||||
if (blanked.includes("\n")) lineHasPrefixText = false;
|
||||
return blanked;
|
||||
});
|
||||
const tableRanges: { start: number; end: number }[] = [];
|
||||
function findTables(node: Nodes) {
|
||||
if (node.type === "table" && node.position) {
|
||||
const start = node.position.start.offset;
|
||||
const end = node.position.end.offset;
|
||||
if (start !== undefined && end !== undefined) tableRanges.push({ start, end });
|
||||
} else if ("children" in node) node.children.forEach(findTables);
|
||||
}
|
||||
findTables(
|
||||
fromMarkdown(tableSource, {
|
||||
extensions: [{ disable: { null: ["htmlFlow", "htmlText"] } }, gfmTable()],
|
||||
mdastExtensions: [gfmTableFromMarkdown()],
|
||||
}),
|
||||
);
|
||||
return tableRanges;
|
||||
}
|
||||
|
||||
@@ -838,6 +838,188 @@ describe("GitHub comment HTML normalization", () => {
|
||||
])("normalizes %s without changing code", (source, expected) => {
|
||||
expect(prepareMarkdownSource(source).render()).toBe(expected);
|
||||
});
|
||||
|
||||
it("keeps <br> line breaks inside GFM table headers and cells within a single row", async () => {
|
||||
const source = [
|
||||
"| Col<br>One | Col<br />Two |",
|
||||
"| --- | --- |",
|
||||
"| First<br>Second<br/>Third | Plain |",
|
||||
].join("\n");
|
||||
const tree = await parseMarkdown(prepareMarkdownSource(source).render(), {
|
||||
hardSoftBreaks: true,
|
||||
latexMath: false,
|
||||
});
|
||||
const table = tree.children?.find((node) => node.type === "Table");
|
||||
expect(table).toBeDefined();
|
||||
const headRows = table?.children?.find((node) => node.type === "TableHead")?.children ?? [];
|
||||
const bodyRows = table?.children?.find((node) => node.type === "TableBody")?.children ?? [];
|
||||
expect(headRows).toHaveLength(1);
|
||||
expect(bodyRows).toHaveLength(1);
|
||||
const [headCells, bodyCells] = [headRows[0].children ?? [], bodyRows[0].children ?? []];
|
||||
expect(headCells[0].children).toEqual([
|
||||
{ type: "Text", content: "Col" },
|
||||
{ type: "LineBreak" },
|
||||
{ type: "Text", content: "One" },
|
||||
]);
|
||||
expect(headCells[1].children).toEqual([
|
||||
{ type: "Text", content: "Col" },
|
||||
{ type: "LineBreak" },
|
||||
{ type: "Text", content: "Two" },
|
||||
]);
|
||||
expect(bodyCells[0].children).toEqual([
|
||||
{ type: "Text", content: "First" },
|
||||
{ type: "LineBreak" },
|
||||
{ type: "Text", content: "Second" },
|
||||
{ type: "LineBreak" },
|
||||
{ type: "Text", content: "Third" },
|
||||
]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
"<details><summary>Results</summary>\n\n| A | B |\n| - | - |\n| 1<br>2 | 3 |\n</details>",
|
||||
"<details><summary>Results</summary>| A | B |\n| - | - |\n| 1<br>2 | 3 |</details>",
|
||||
"<details><summary>Results</summary><div>| A | B |\n| - | - |\n| 1<br>2 | 3 |</div></details>",
|
||||
"<span></span><div>| A | B |\n| - | - |\n| 1<br>2 | 3 |</div>",
|
||||
])("keeps table <br> inside wrapped table cells: %s", async (source) => {
|
||||
const tree = await parseMarkdown(prepareMarkdownSource(source).render(), {
|
||||
hardSoftBreaks: true,
|
||||
latexMath: false,
|
||||
});
|
||||
const table = tree.children?.find((node) => node.type === "Table");
|
||||
expect(table).toBeDefined();
|
||||
const body = table?.children?.find((node) => node.type === "TableBody");
|
||||
expect(body?.children).toHaveLength(1);
|
||||
expect(body?.children?.[0]?.children?.[0]?.children).toEqual([
|
||||
{ type: "Text", content: "1" },
|
||||
{ type: "LineBreak" },
|
||||
{ type: "Text", content: "2" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("recognizes file paths and URLs separated by <br> inside table cells", async () => {
|
||||
const source = [
|
||||
"| Paths | Mixed | URLs |",
|
||||
"| --- | --- | --- |",
|
||||
"| src/first.ts<br>src/second.ts | https://example.com/first<br>src/second.ts | https://example.com/first<br>https://example.com/second |",
|
||||
].join("\n");
|
||||
const prepared = prepareMarkdownSource(source);
|
||||
const linked = recognizeTextLinks(
|
||||
await parseMarkdown(prepared.render(), {
|
||||
hardSoftBreaks: true,
|
||||
latexMath: false,
|
||||
}),
|
||||
prepared.linkRecognition.text,
|
||||
prepared.linkRecognition.inlineCode,
|
||||
);
|
||||
const table = linked.children?.find((node) => node.type === "Table");
|
||||
const row = table?.children?.find((node) => node.type === "TableBody")?.children?.[0];
|
||||
expect(row?.children?.[0]?.children).toEqual([
|
||||
{
|
||||
type: "Link",
|
||||
attributes: { url: "src/first.ts", recognizedLink: "true" },
|
||||
children: [{ type: "Text", content: "src/first.ts" }],
|
||||
},
|
||||
{ type: "LineBreak" },
|
||||
{
|
||||
type: "Link",
|
||||
attributes: { url: "src/second.ts", recognizedLink: "true" },
|
||||
children: [{ type: "Text", content: "src/second.ts" }],
|
||||
},
|
||||
]);
|
||||
expect(row?.children?.[1]?.children).toEqual([
|
||||
{
|
||||
type: "Link",
|
||||
attributes: { url: "https://example.com/first" },
|
||||
children: [{ type: "Text", content: "https://example.com/first" }],
|
||||
},
|
||||
{ type: "LineBreak" },
|
||||
{
|
||||
type: "Link",
|
||||
attributes: { url: "src/second.ts", recognizedLink: "true" },
|
||||
children: [{ type: "Text", content: "src/second.ts" }],
|
||||
},
|
||||
]);
|
||||
expect(row?.children?.[2]?.children).toEqual([
|
||||
{
|
||||
type: "Link",
|
||||
attributes: { url: "https://example.com/first" },
|
||||
children: [{ type: "Text", content: "https://example.com/first" }],
|
||||
},
|
||||
{ type: "LineBreak" },
|
||||
{
|
||||
type: "Link",
|
||||
attributes: { url: "https://example.com/second" },
|
||||
children: [{ type: "Text", content: "https://example.com/second" }],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps literal U+2028 outside tables, inline code, and escaped <br> untouched", async () => {
|
||||
const source = [
|
||||
"before\u2028after `before\u2028after`",
|
||||
"",
|
||||
"| Inline | Escaped | Entity |",
|
||||
"| --- | --- | --- |",
|
||||
"| `before\u2028after` | \\<br> | <br> `<br>` |",
|
||||
].join("\n");
|
||||
const tree = await parseMarkdown(prepareMarkdownSource(source).render(), {
|
||||
hardSoftBreaks: true,
|
||||
latexMath: false,
|
||||
});
|
||||
const collectLineBreaks = (node: ASTNode): number =>
|
||||
(node.type === "LineBreak" ? 1 : 0) +
|
||||
(node.children?.reduce((count, child) => count + collectLineBreaks(child), 0) ?? 0);
|
||||
expect(collectLineBreaks(tree)).toBe(0);
|
||||
|
||||
const paragraph = tree.children?.find((node) => node.type === "Paragraph");
|
||||
expect(paragraph?.children).toEqual([
|
||||
{ type: "Text", content: "before\u2028after " },
|
||||
{ type: "Code", children: [{ type: "Text", content: "before\u2028after" }] },
|
||||
]);
|
||||
|
||||
const row = tree.children
|
||||
?.find((node) => node.type === "Table")
|
||||
?.children?.find((node) => node.type === "TableBody")?.children?.[0];
|
||||
expect(row?.children?.[0]?.children).toEqual([
|
||||
{ type: "Code", children: [{ type: "Text", content: "before\u2028after" }] },
|
||||
]);
|
||||
expect(row?.children?.[1]?.children).toEqual([{ type: "Text", content: "<br>" }]);
|
||||
expect(row?.children?.[2]?.children).toEqual([
|
||||
{ type: "Text", content: "<br> " },
|
||||
{ type: "Code", children: [{ type: "Text", content: "<br>" }] },
|
||||
]);
|
||||
expect(prepareMarkdownSource("<table><tr><td>a<br>b</td></tr></table>").render()).toBe(
|
||||
"a \nb",
|
||||
);
|
||||
});
|
||||
|
||||
it("preserves emphasis and strong delimiters adjacent to <br> inside table cells", async () => {
|
||||
const source = [
|
||||
"| A | B |",
|
||||
"| --- | --- |",
|
||||
"| **方案 B(最猛 · 推荐)**<br>阶梯首充 | **`基准 → 30% → 50%`**<br>*(复购:基准)* |",
|
||||
].join("\n");
|
||||
const tree = await parseMarkdown(prepareMarkdownSource(source).render(), {
|
||||
hardSoftBreaks: true,
|
||||
latexMath: false,
|
||||
});
|
||||
const row = tree.children
|
||||
?.find((node) => node.type === "Table")
|
||||
?.children?.find((node) => node.type === "TableBody")?.children?.[0];
|
||||
expect(row?.children?.[0]?.children).toEqual([
|
||||
{ type: "Strong", children: [{ type: "Text", content: "方案 B(最猛 · 推荐)" }] },
|
||||
{ type: "LineBreak" },
|
||||
{ type: "Text", content: "阶梯首充" },
|
||||
]);
|
||||
expect(row?.children?.[1]?.children).toEqual([
|
||||
{
|
||||
type: "Strong",
|
||||
children: [{ type: "Code", children: [{ type: "Text", content: "基准 → 30% → 50%" }] }],
|
||||
},
|
||||
{ type: "LineBreak" },
|
||||
{ type: "Emphasis", children: [{ type: "Text", content: "(复购:基准)" }] },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves backslashes and decodes entities inside HTML code", () => {
|
||||
|
||||
@@ -21,9 +21,11 @@ import {
|
||||
type RewindMode,
|
||||
} from "@/components/rewind";
|
||||
import { TaskListRow } from "@/components/task-list-row";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { LoadingSpinner } from "@/components/ui/loading-spinner";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { isNative, isWeb } from "@/constants/platform";
|
||||
import { useProvidersSnapshot } from "@/hooks/use-providers-snapshot";
|
||||
import { useRevealedText, type MarkdownPhase } from "@/hooks/use-revealed-text";
|
||||
import { ICON_SIZE, type Theme } from "@/styles/theme";
|
||||
import { inlineUnistylesStyle } from "@/styles/unistyles-inline-style";
|
||||
@@ -47,13 +49,17 @@ import type { AgentMessage } from "@getpaseo/protocol/agent-message";
|
||||
import type {
|
||||
AgentCapabilityFlags,
|
||||
AgentMetric,
|
||||
AgentProvider,
|
||||
ProviderSwitchContextSummary,
|
||||
ToolCallDetail,
|
||||
} from "@getpaseo/protocol/agent-types";
|
||||
import type { AgentAttachment } from "@getpaseo/protocol/messages";
|
||||
import MaskedView from "@react-native-masked-view/masked-view";
|
||||
import {
|
||||
ArrowRightLeft,
|
||||
Check,
|
||||
CheckSquare,
|
||||
ChevronDown,
|
||||
ChevronRight,
|
||||
CircleDot,
|
||||
Copy,
|
||||
@@ -1575,6 +1581,206 @@ export const CompactionMarker = memo(function CompactionMarker({
|
||||
);
|
||||
});
|
||||
|
||||
const StyledSwitchIcon = withUnistyles(ArrowRightLeft, (theme) => ({
|
||||
color: theme.colors.foregroundMuted,
|
||||
}));
|
||||
const StyledChevronDownIcon = withUnistyles(ChevronDown, (theme) => ({
|
||||
color: theme.colors.foregroundMuted,
|
||||
}));
|
||||
const StyledChevronRightIcon = withUnistyles(ChevronRight, (theme) => ({
|
||||
color: theme.colors.foregroundMuted,
|
||||
}));
|
||||
|
||||
export interface ProviderSwitchMarkerProps {
|
||||
serverId?: string | null;
|
||||
fromProvider: AgentProvider;
|
||||
toProvider: AgentProvider;
|
||||
fromModel?: string | null;
|
||||
toModel?: string | null;
|
||||
context?: ProviderSwitchContextSummary;
|
||||
}
|
||||
|
||||
const providerSwitchStylesheet = StyleSheet.create((theme) => ({
|
||||
wrapper: {
|
||||
paddingVertical: theme.spacing[2],
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
row: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[2],
|
||||
width: "100%",
|
||||
},
|
||||
line: {
|
||||
flex: 1,
|
||||
minWidth: 12,
|
||||
height: 1,
|
||||
backgroundColor: theme.colors.border,
|
||||
},
|
||||
triggerButton: {
|
||||
flexShrink: 1,
|
||||
minWidth: 0,
|
||||
maxWidth: "85%",
|
||||
},
|
||||
triggerContent: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
flexShrink: 1,
|
||||
minWidth: 0,
|
||||
maxWidth: "100%",
|
||||
gap: theme.spacing[1.5],
|
||||
},
|
||||
triggerText: {
|
||||
flexShrink: 1,
|
||||
minWidth: 0,
|
||||
fontFamily: theme.fontFamily.ui,
|
||||
fontSize: 13,
|
||||
color: theme.colors.foregroundMuted,
|
||||
},
|
||||
chevronSlot: {
|
||||
width: 12,
|
||||
height: 12,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
detailsCard: {
|
||||
alignSelf: "center",
|
||||
maxWidth: 480,
|
||||
width: "100%",
|
||||
paddingVertical: theme.spacing[2],
|
||||
paddingHorizontal: theme.spacing[3],
|
||||
borderRadius: theme.borderRadius.md,
|
||||
borderWidth: 1,
|
||||
borderColor: theme.colors.border,
|
||||
backgroundColor: theme.colors.surface0,
|
||||
gap: theme.spacing[1],
|
||||
},
|
||||
detailRow: {
|
||||
fontFamily: theme.fontFamily.ui,
|
||||
fontSize: 12,
|
||||
color: theme.colors.foregroundMuted,
|
||||
},
|
||||
}));
|
||||
|
||||
function resolveProviderSwitchLabel(
|
||||
provider: string,
|
||||
entries: ReturnType<typeof useProvidersSnapshot>["entries"],
|
||||
): string {
|
||||
return entries?.find((entry) => entry.provider === provider)?.label ?? provider;
|
||||
}
|
||||
|
||||
function resolveProviderSwitchModelLabel(
|
||||
provider: string,
|
||||
modelId: string | null | undefined,
|
||||
entries: ReturnType<typeof useProvidersSnapshot>["entries"],
|
||||
): string | null {
|
||||
if (!modelId) return null;
|
||||
const entry = entries?.find((candidate) => candidate.provider === provider);
|
||||
return entry?.models?.find((model) => model.id === modelId)?.label ?? modelId;
|
||||
}
|
||||
|
||||
function formatProviderSwitchEndpoint(providerLabel: string, modelLabel: string | null): string {
|
||||
return modelLabel ? `${providerLabel} (${modelLabel})` : providerLabel;
|
||||
}
|
||||
|
||||
export const ProviderSwitchMarker = memo(function ProviderSwitchMarker({
|
||||
serverId = null,
|
||||
fromProvider,
|
||||
toProvider,
|
||||
fromModel,
|
||||
toModel,
|
||||
context,
|
||||
}: ProviderSwitchMarkerProps) {
|
||||
const { t } = useTranslation();
|
||||
const { entries: providerEntries } = useProvidersSnapshot(serverId);
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
const handleToggle = useCallback(() => setExpanded((prev) => !prev), []);
|
||||
|
||||
const fromLabel = resolveProviderSwitchLabel(fromProvider, providerEntries);
|
||||
const toLabel = resolveProviderSwitchLabel(toProvider, providerEntries);
|
||||
const fromModelLabel = resolveProviderSwitchModelLabel(fromProvider, fromModel, providerEntries);
|
||||
const toModelLabel = resolveProviderSwitchModelLabel(toProvider, toModel, providerEntries);
|
||||
|
||||
const title = t("message.providerSwitch.switched", {
|
||||
from: fromLabel,
|
||||
to: toLabel,
|
||||
});
|
||||
const contextLine = context
|
||||
? t("message.providerSwitch.contextSummary", {
|
||||
count: context.includedItems,
|
||||
chars: context.charCount.toLocaleString(),
|
||||
budget: context.budgetChars.toLocaleString(),
|
||||
})
|
||||
: null;
|
||||
const reasonsLine =
|
||||
context?.truncated && context.omittedReasons?.length
|
||||
? t("message.providerSwitch.trimmed", {
|
||||
reasons: context.omittedReasons
|
||||
.map((reason) => {
|
||||
if (reason === "tail_window_limit") {
|
||||
return t("message.providerSwitch.reasonTailWindow");
|
||||
}
|
||||
if (reason === "char_budget") {
|
||||
return t("message.providerSwitch.reasonCharBudget");
|
||||
}
|
||||
return reason;
|
||||
})
|
||||
.join(", "),
|
||||
})
|
||||
: null;
|
||||
|
||||
let chevronIcon: React.ReactNode = null;
|
||||
if (context) {
|
||||
chevronIcon = expanded ? (
|
||||
<StyledChevronDownIcon size={12} />
|
||||
) : (
|
||||
<StyledChevronRightIcon size={12} />
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<View style={providerSwitchStylesheet.wrapper} testID="provider-switch-marker">
|
||||
<View style={providerSwitchStylesheet.row}>
|
||||
<View style={providerSwitchStylesheet.line} />
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
style={providerSwitchStylesheet.triggerButton}
|
||||
onPress={context ? handleToggle : undefined}
|
||||
accessibilityLabel={title}
|
||||
testID="provider-switch-marker-toggle"
|
||||
>
|
||||
<View style={providerSwitchStylesheet.triggerContent}>
|
||||
<StyledSwitchIcon size={12} />
|
||||
<Text
|
||||
style={providerSwitchStylesheet.triggerText}
|
||||
numberOfLines={1}
|
||||
ellipsizeMode="tail"
|
||||
>
|
||||
{title}
|
||||
</Text>
|
||||
<View style={providerSwitchStylesheet.chevronSlot}>{chevronIcon}</View>
|
||||
</View>
|
||||
</Button>
|
||||
<View style={providerSwitchStylesheet.line} />
|
||||
</View>
|
||||
{expanded && context ? (
|
||||
<View style={providerSwitchStylesheet.detailsCard} testID="provider-switch-marker-details">
|
||||
<Text style={providerSwitchStylesheet.detailRow}>
|
||||
{`${formatProviderSwitchEndpoint(fromLabel, fromModelLabel)} → ${formatProviderSwitchEndpoint(toLabel, toModelLabel)}`}
|
||||
</Text>
|
||||
{contextLine ? (
|
||||
<Text style={providerSwitchStylesheet.detailRow}>{contextLine}</Text>
|
||||
) : null}
|
||||
{reasonsLine ? (
|
||||
<Text style={providerSwitchStylesheet.detailRow}>{reasonsLine}</Text>
|
||||
) : null}
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
});
|
||||
|
||||
interface TodoListCardProps {
|
||||
items: TodoEntry[];
|
||||
activity: TaskActivity;
|
||||
|
||||
@@ -11,11 +11,6 @@ describe("pairing target password", () => {
|
||||
expect(target.changeUrl(second)).toBe(false);
|
||||
});
|
||||
|
||||
it("clears the direct form credential when its advanced URI changes to a relay target", () => {
|
||||
const target = new PairingTargetTracker("", true);
|
||||
expect(target.changeUrl("relay://relay.example:443/srv_new?key=BBBB&ssl=true")).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps the password when a relay URI receives harmless whitespace", () => {
|
||||
const uri = "relay://relay.example:443/srv_a?key=AAAA&ssl=true";
|
||||
const target = new PairingTargetTracker(uri);
|
||||
|
||||
@@ -19,8 +19,8 @@ function pairingTarget(url: string): string | null {
|
||||
export class PairingTargetTracker {
|
||||
private currentTarget: string | null;
|
||||
|
||||
constructor(initialUrl = "", startsFromDirectForm = false) {
|
||||
this.currentTarget = pairingTarget(initialUrl) ?? (startsFromDirectForm ? "direct-form" : null);
|
||||
constructor(initialUrl = "") {
|
||||
this.currentTarget = pairingTarget(initialUrl);
|
||||
}
|
||||
|
||||
changeUrl(nextUrl: string): boolean {
|
||||
|
||||
@@ -10,7 +10,11 @@ import { useToast } from "@/contexts/toast-context";
|
||||
import type { AgentScreenReadySyncState } from "@/hooks/use-agent-screen-state-machine";
|
||||
import { selectAgentTimelineState, useSessionStore } from "@/stores/session-store";
|
||||
import { useRewindAgentMutation } from "./use-rewind-agent-mutation";
|
||||
import { isRewindableMessage, useRewindMenuItems } from "./use-rewind-capabilities";
|
||||
import {
|
||||
isPromptInActiveSegment,
|
||||
isRewindableMessage,
|
||||
useRewindMenuItems,
|
||||
} from "./use-rewind-capabilities";
|
||||
|
||||
export function RewindCommandCenterRegistration({
|
||||
serverId,
|
||||
@@ -42,10 +46,16 @@ export function RewindCommandCenterRegistration({
|
||||
if (timeline.status !== "synced" || timeline.newer === "available") {
|
||||
return undefined;
|
||||
}
|
||||
return (
|
||||
const candidate =
|
||||
session.agentStreamHead.get(agentId)?.findLast((item) => item.kind === "user_message") ??
|
||||
timeline.items.findLast((item) => item.kind === "user_message")
|
||||
);
|
||||
timeline.items.findLast((item) => item.kind === "user_message");
|
||||
if (
|
||||
!candidate ||
|
||||
!isPromptInActiveSegment(candidate.timelineCursor, timeline.range?.activeSegmentStartSeq)
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
return candidate;
|
||||
});
|
||||
const { rewindAgent, isPending } = useRewindAgentMutation({
|
||||
serverId,
|
||||
|
||||
@@ -9,6 +9,7 @@ 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;
|
||||
@@ -42,7 +43,16 @@ export function useRewindAgentMutation(input: UseRewindAgentMutationInput): {
|
||||
throw new Error(t("common.errors.daemonClientUnavailable"));
|
||||
}
|
||||
await input.client.rewindAgent(input.agentId, input.messageId, mode);
|
||||
if (mode !== "files") {
|
||||
// COMPAT(timelineRewindOperations): added in v0.18.0, remove after 2027-05-25. 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) {
|
||||
const cursor = input.serverId
|
||||
? useSessionStore
|
||||
.getState()
|
||||
|
||||
@@ -26,6 +26,20 @@ export function isRewindableMessage(messageId: string | undefined, text: string)
|
||||
return Boolean(messageId) && text.trim().length > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a user prompt belongs to the active provider segment (after the latest provider switch).
|
||||
* Prompts from earlier provider segments cannot be rewound.
|
||||
*/
|
||||
export function isPromptInActiveSegment(
|
||||
timelineCursor: { anchorSeq?: number; seq?: number } | undefined,
|
||||
activeSegmentStartSeq: number | undefined,
|
||||
): boolean {
|
||||
if (!activeSegmentStartSeq || activeSegmentStartSeq <= 0) return true;
|
||||
const anchor = timelineCursor?.anchorSeq ?? timelineCursor?.seq;
|
||||
if (anchor === undefined) return true;
|
||||
return anchor > activeSegmentStartSeq;
|
||||
}
|
||||
|
||||
export function resolveRewindMenuItems(
|
||||
capabilities:
|
||||
| Pick<
|
||||
|
||||
@@ -54,6 +54,8 @@ import type { WorkspaceTabDescriptor } from "@/screens/workspace/workspace-tabs-
|
||||
import {
|
||||
collectAllPanes,
|
||||
createDefaultLayout,
|
||||
resolveGroupSizes,
|
||||
resolveMainSplitTree,
|
||||
selectExplorerSidebarPaneId,
|
||||
useWorkspaceLayoutStore,
|
||||
type SplitNode,
|
||||
@@ -80,7 +82,7 @@ interface SplitContainerProps {
|
||||
uiTabs: WorkspaceTab[];
|
||||
hoveredCloseTabKey: string | null;
|
||||
setHoveredCloseTabKey: Dispatch<SetStateAction<string | null>>;
|
||||
closingTabIds: Set<string>;
|
||||
closingTabIds: ReadonlySet<string>;
|
||||
onNavigateTab: (tabId: string) => void;
|
||||
onCloseTab: (tabId: string) => Promise<void> | void;
|
||||
onCopyResumeCommand: (agentId: string) => Promise<void> | void;
|
||||
@@ -205,7 +207,7 @@ export function SplitContainer({
|
||||
);
|
||||
|
||||
const mainRoot = useMemo(
|
||||
() => removePaneFromSplitTree(layout.root, explorerSidebarPaneId),
|
||||
() => resolveMainSplitTree(layout.root, explorerSidebarPaneId),
|
||||
[layout.root, explorerSidebarPaneId],
|
||||
);
|
||||
const workspaceHasMultiplePanes = Boolean(mainRoot && hasMultipleVisiblePanes(mainRoot));
|
||||
@@ -459,11 +461,10 @@ function SplitNodeView({
|
||||
);
|
||||
const groupChildren = node.kind === "group" ? node.group.children : EMPTY_SPLIT_NODES;
|
||||
// Dragged sizes live per group id, apart from the layout tree, and a group keeps its id when
|
||||
// panes are added or removed. They only apply while they still have one entry per child;
|
||||
// otherwise the dividers past the end of the list could not move.
|
||||
const layoutGroupSizes = node.kind === "group" ? node.group.sizes : EMPTY_SPLIT_SIZES;
|
||||
// panes are added or removed. A list of the wrong length would leave the dividers past its end
|
||||
// unable to move.
|
||||
const groupSizes =
|
||||
storedGroupSizes?.length === groupChildren.length ? storedGroupSizes : layoutGroupSizes;
|
||||
node.kind === "group" ? resolveGroupSizes(node.group, storedGroupSizes) : EMPTY_SPLIT_SIZES;
|
||||
const visibleFlex = useMemo(
|
||||
() => resolveVisibleGroupFlex(groupChildren, groupSizes, maximizedPaneId),
|
||||
[groupChildren, groupSizes, maximizedPaneId],
|
||||
@@ -910,34 +911,6 @@ function wrapRootPaneForStableMount(node: SplitNode): SplitNode {
|
||||
};
|
||||
}
|
||||
|
||||
function removePaneFromSplitTree(node: SplitNode, paneId: string | null): SplitNode | null {
|
||||
if (!paneId) {
|
||||
return node;
|
||||
}
|
||||
if (node.kind === "pane") {
|
||||
return node.pane.id === paneId ? null : node;
|
||||
}
|
||||
|
||||
const children = node.group.children.flatMap((child) => {
|
||||
const nextChild = removePaneFromSplitTree(child, paneId);
|
||||
return nextChild ? [nextChild] : [];
|
||||
});
|
||||
if (children.length === 0) {
|
||||
return null;
|
||||
}
|
||||
if (children.length === 1) {
|
||||
return children[0] ?? null;
|
||||
}
|
||||
return {
|
||||
kind: "group",
|
||||
group: {
|
||||
...node.group,
|
||||
children,
|
||||
sizes: children.map(() => 1 / children.length),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
workspaceShell: {
|
||||
flex: 1,
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
import type { SelectedFile } from "@/attachments/selected-file";
|
||||
import { prepareImageAttachmentsForSend } from "@/attachments/service";
|
||||
import { FILE_UPLOAD_MAX_BYTES } from "@/attachments/upload-limit";
|
||||
import type { AgentProvider, ProviderOptions } from "@getpaseo/protocol/agent-types";
|
||||
import type {
|
||||
ActiveTurnBehavior,
|
||||
AgentSnapshotPayload,
|
||||
ForgeSearchItem,
|
||||
UploadedFileAttachment,
|
||||
} from "@getpaseo/protocol/messages";
|
||||
import { AgentProviderSwitchError } from "@getpaseo/client/internal/daemon-client";
|
||||
import type { StagedProviderSwitch } from "@/composer/provider-switch";
|
||||
import type {
|
||||
AttachmentMetadata,
|
||||
ComposerAttachment,
|
||||
@@ -19,7 +23,13 @@ import {
|
||||
splitComposerAttachmentsForSubmit,
|
||||
type ComposerAttachmentSubmitFormat,
|
||||
} from "@/composer/attachments/submit";
|
||||
import { createUserMessage, generateMessageId, type UserMessageItem } from "@/types/stream";
|
||||
import {
|
||||
createPendingProviderSwitchItem,
|
||||
createUserMessage,
|
||||
generateMessageId,
|
||||
type ProviderSwitchItem,
|
||||
type UserMessageItem,
|
||||
} from "@/types/stream";
|
||||
import type { MessageSubmissionRejectionOutcome } from "@/composer/submission/model";
|
||||
import type { PickedImageAttachmentInput } from "@/hooks/image-attachment-picker";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
@@ -60,6 +70,20 @@ export interface ComposerSendClient {
|
||||
attachments: ReturnType<typeof splitComposerAttachmentsForSubmit>["attachments"];
|
||||
},
|
||||
) => Promise<unknown>;
|
||||
switchAgentProvider?: (
|
||||
agentId: string,
|
||||
options: {
|
||||
provider: AgentProvider;
|
||||
model?: string | null;
|
||||
modeId?: string | null;
|
||||
thinkingOptionId?: string | null;
|
||||
providerOptions?: ProviderOptions;
|
||||
text: string;
|
||||
messageId: string;
|
||||
images?: Array<{ data: string; mimeType: string }>;
|
||||
attachments?: ReturnType<typeof splitComposerAttachmentsForSubmit>["attachments"];
|
||||
},
|
||||
) => Promise<{ agent?: AgentSnapshotPayload }>;
|
||||
uploadFile: (input: { fileName: string; mimeType: string; bytes: Uint8Array }) => Promise<{
|
||||
requestId: string;
|
||||
file: UploadedFileAttachment | null;
|
||||
@@ -73,7 +97,11 @@ export interface ComposerCancelClient {
|
||||
}
|
||||
|
||||
export interface MessageSubmissionWriter {
|
||||
begin: (agentId: string, message: UserMessageItem) => void;
|
||||
begin: (
|
||||
agentId: string,
|
||||
message: UserMessageItem,
|
||||
options?: { providerSwitch?: ProviderSwitchItem },
|
||||
) => void;
|
||||
accept: (agentId: string, clientMessageId: string) => void;
|
||||
reject: (agentId: string, clientMessageId: string) => MessageSubmissionRejectionOutcome;
|
||||
}
|
||||
@@ -193,6 +221,33 @@ export interface DispatchComposerAgentMessageInput {
|
||||
submission: MessageSubmissionWriter;
|
||||
activeTurnBehavior?: ActiveTurnBehavior;
|
||||
activeTurnId?: string;
|
||||
currentProvider?: AgentProvider | null;
|
||||
currentModel?: string | null;
|
||||
stagedProviderSwitch?: StagedProviderSwitch | null;
|
||||
onProviderSwitchCommitted?: (agent: AgentSnapshotPayload | undefined) => void | Promise<void>;
|
||||
}
|
||||
|
||||
function buildPendingProviderSwitch(
|
||||
input: DispatchComposerAgentMessageInput,
|
||||
clientMessageId: string,
|
||||
timestamp: Date,
|
||||
): ProviderSwitchItem | undefined {
|
||||
if (
|
||||
!input.stagedProviderSwitch ||
|
||||
!input.client.switchAgentProvider ||
|
||||
!input.currentProvider ||
|
||||
input.stagedProviderSwitch.provider === input.currentProvider
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
return createPendingProviderSwitchItem({
|
||||
clientMessageId,
|
||||
fromProvider: input.currentProvider,
|
||||
toProvider: input.stagedProviderSwitch.provider,
|
||||
fromModel: input.currentModel ?? null,
|
||||
toModel: input.stagedProviderSwitch.model,
|
||||
timestamp,
|
||||
});
|
||||
}
|
||||
|
||||
export async function dispatchComposerAgentMessage(
|
||||
@@ -202,17 +257,23 @@ export async function dispatchComposerAgentMessage(
|
||||
format: input.attachmentSubmitFormat,
|
||||
});
|
||||
const clientMessageId = generateMessageId();
|
||||
const timestamp = new Date();
|
||||
const userMessage = createUserMessage({
|
||||
clientMessageId,
|
||||
text: input.text,
|
||||
timestamp: new Date(),
|
||||
timestamp,
|
||||
images: wirePayload.images,
|
||||
attachments: wirePayload.attachments,
|
||||
...(input.activeTurnBehavior === "steer" && input.activeTurnId
|
||||
...(input.activeTurnBehavior === "steer" && input.activeTurnId && !input.stagedProviderSwitch
|
||||
? { turnId: input.activeTurnId }
|
||||
: {}),
|
||||
});
|
||||
input.submission.begin(input.agentId, userMessage);
|
||||
const pendingProviderSwitch = buildPendingProviderSwitch(input, clientMessageId, timestamp);
|
||||
input.submission.begin(
|
||||
input.agentId,
|
||||
userMessage,
|
||||
pendingProviderSwitch ? { providerSwitch: pendingProviderSwitch } : undefined,
|
||||
);
|
||||
try {
|
||||
const imagePayload = input.uploadImages
|
||||
? { attachments: await input.uploadImages(wirePayload.images) }
|
||||
@@ -220,6 +281,22 @@ export async function dispatchComposerAgentMessage(
|
||||
client: input.client,
|
||||
images: wirePayload.images,
|
||||
});
|
||||
if (input.stagedProviderSwitch && input.client.switchAgentProvider) {
|
||||
const result = await input.client.switchAgentProvider(input.agentId, {
|
||||
provider: input.stagedProviderSwitch.provider,
|
||||
model: input.stagedProviderSwitch.model,
|
||||
modeId: input.stagedProviderSwitch.modeId,
|
||||
thinkingOptionId: input.stagedProviderSwitch.thinkingOptionId,
|
||||
providerOptions: input.stagedProviderSwitch.providerOptions,
|
||||
text: input.text,
|
||||
messageId: clientMessageId,
|
||||
...(imagePayload.images ? { images: imagePayload.images } : {}),
|
||||
attachments: [...wirePayload.attachments, ...(imagePayload.attachments ?? [])],
|
||||
});
|
||||
input.submission.accept(input.agentId, clientMessageId);
|
||||
await input.onProviderSwitchCommitted?.(result.agent);
|
||||
return;
|
||||
}
|
||||
await input.client.sendAgentMessage(input.agentId, input.text, {
|
||||
messageId: clientMessageId,
|
||||
...(input.activeTurnBehavior ? { activeTurnBehavior: input.activeTurnBehavior } : {}),
|
||||
@@ -229,6 +306,9 @@ export async function dispatchComposerAgentMessage(
|
||||
input.submission.accept(input.agentId, clientMessageId);
|
||||
} catch (error) {
|
||||
input.submission.reject(input.agentId, clientMessageId);
|
||||
if (error instanceof AgentProviderSwitchError && error.agent) {
|
||||
await input.onProviderSwitchCommitted?.(error.agent);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,12 +16,21 @@ import { formatThinkingOptionLabel } from "@/agent-controls/labels";
|
||||
import { CombinedModelSelector } from "@/components/combined-model-selector";
|
||||
import {
|
||||
buildProviderSelectorProviders,
|
||||
buildSelectableProviderSelectorProviders,
|
||||
buildSelectorProvider,
|
||||
type ProviderSelectorProvider,
|
||||
} from "@/provider-selection/provider-selection";
|
||||
import { filterSelectableModels } from "@/provider-selection/model-catalog";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
import { useProvidersSnapshot } from "@/hooks/use-providers-snapshot";
|
||||
import { useDraftProviderOptions } from "@/hooks/use-draft-provider-options";
|
||||
import {
|
||||
clearStagedProviderSwitch,
|
||||
isStagedProviderSwitchInFlight,
|
||||
type StagedProviderSwitch,
|
||||
useStagedProviderSwitch,
|
||||
useStagedProviderSwitchStore,
|
||||
} from "@/composer/provider-switch";
|
||||
import { resolveProviderDefinition } from "@/utils/provider-definitions";
|
||||
import { mergeProviderPreferences, useFormPreferences } from "@/hooks/use-form-preferences";
|
||||
import {
|
||||
@@ -104,6 +113,7 @@ import {
|
||||
type AgentProfilePicker,
|
||||
type AgentProfileSeed,
|
||||
type DraftAgentProfileControls,
|
||||
type MaterializedAgentProfile,
|
||||
} from "@/agent-profiles";
|
||||
import { buildSettingsHostSectionRoute } from "@/utils/host-routes";
|
||||
|
||||
@@ -996,6 +1006,148 @@ function useAgentOptionControls(
|
||||
);
|
||||
}
|
||||
|
||||
function resolveActiveStagedSwitch(
|
||||
supportsProviderSwitching: boolean,
|
||||
rawStagedSwitch: StagedProviderSwitch | null,
|
||||
liveProvider: string | undefined,
|
||||
): StagedProviderSwitch | null {
|
||||
if (!supportsProviderSwitching || !rawStagedSwitch || !liveProvider) {
|
||||
return null;
|
||||
}
|
||||
return rawStagedSwitch.provider !== liveProvider ? rawStagedSwitch : null;
|
||||
}
|
||||
|
||||
function resolveDraftTargetModelId(
|
||||
modelId: string,
|
||||
preferredModel: string | undefined,
|
||||
nextModels: AgentModelDefinition[] | null,
|
||||
): string | null {
|
||||
if (modelId) return modelId;
|
||||
if (preferredModel) return preferredModel;
|
||||
const defaultModel = nextModels?.find((m) => m.isDefault);
|
||||
return defaultModel?.id ?? nextModels?.[0]?.id ?? null;
|
||||
}
|
||||
|
||||
function resolveDraftThinkingOptionId(
|
||||
targetModelId: string | null,
|
||||
targetModel: AgentModelDefinition | undefined,
|
||||
thinkingByModel: Record<string, string> | undefined,
|
||||
): string | null {
|
||||
const preferred = targetModelId ? thinkingByModel?.[targetModelId] : undefined;
|
||||
if (preferred) return preferred;
|
||||
return targetModel?.defaultThinkingOptionId ?? targetModel?.thinkingOptions?.[0]?.id ?? null;
|
||||
}
|
||||
|
||||
function resolveDraftModeId(
|
||||
preferredMode: string | undefined,
|
||||
nextEntry: ReturnType<typeof resolveProviderSnapshotEntry>,
|
||||
): string | null {
|
||||
if (preferredMode) return preferredMode;
|
||||
return nextEntry?.defaultModeId ?? nextEntry?.modes?.[0]?.id ?? null;
|
||||
}
|
||||
|
||||
function buildStagedProviderSwitchDraft(input: {
|
||||
nextProvider: string;
|
||||
modelId: string;
|
||||
snapshotEntries: ReturnType<typeof useProvidersSnapshot>["entries"];
|
||||
providerPreferences: ReturnType<typeof useFormPreferences>["preferences"]["providerPreferences"];
|
||||
}): StagedProviderSwitch {
|
||||
const { nextProvider, modelId, snapshotEntries, providerPreferences } = input;
|
||||
const nextEntry = resolveProviderSnapshotEntry(snapshotEntries, nextProvider);
|
||||
const nextModels = filterSelectableModels(nextEntry?.models ?? null);
|
||||
const preferred = providerPreferences?.[nextProvider];
|
||||
const targetModelId = resolveDraftTargetModelId(modelId, preferred?.model, nextModels);
|
||||
const targetModel = nextModels?.find((m) => m.id === targetModelId);
|
||||
return {
|
||||
provider: nextProvider,
|
||||
model: targetModelId,
|
||||
thinkingOptionId: resolveDraftThinkingOptionId(
|
||||
targetModelId,
|
||||
targetModel,
|
||||
preferred?.thinkingByModel,
|
||||
),
|
||||
modeId: resolveDraftModeId(preferred?.mode, nextEntry),
|
||||
providerOptions: preferred?.options ? { ...preferred.options } : {},
|
||||
};
|
||||
}
|
||||
|
||||
function resolveAgentModelSelectionWithStagedSwitch(input: {
|
||||
models: AgentModelDefinition[] | null;
|
||||
agent: AgentControlsSlice;
|
||||
activeStagedSwitch: StagedProviderSwitch | null;
|
||||
}) {
|
||||
const { models, agent, activeStagedSwitch } = input;
|
||||
return resolveAgentModelSelection({
|
||||
models,
|
||||
runtimeModelId: activeStagedSwitch ? null : agent?.runtimeModelId,
|
||||
configuredModelId: activeStagedSwitch ? activeStagedSwitch.model : agent?.model,
|
||||
runtimeThinkingOptionId: activeStagedSwitch ? null : agent?.runtimeThinkingOptionId,
|
||||
explicitThinkingOptionId: activeStagedSwitch
|
||||
? activeStagedSwitch.thinkingOptionId
|
||||
: agent?.thinkingOptionId,
|
||||
});
|
||||
}
|
||||
|
||||
function buildStagedDraftOptionsParams(input: {
|
||||
serverId: string;
|
||||
agentCwd: string | null | undefined;
|
||||
activeStagedSwitch: StagedProviderSwitch | null;
|
||||
getProvider: () => AgentProvider | null;
|
||||
modelId: string | null;
|
||||
thinkingOptionId: string | null;
|
||||
}) {
|
||||
const { serverId, agentCwd, activeStagedSwitch, getProvider, modelId, thinkingOptionId } = input;
|
||||
return {
|
||||
serverId: activeStagedSwitch ? serverId : null,
|
||||
provider: activeStagedSwitch ? activeStagedSwitch.provider : null,
|
||||
getProvider,
|
||||
cwd: agentCwd,
|
||||
modeId: activeStagedSwitch?.modeId ?? null,
|
||||
modelId,
|
||||
thinkingOptionId,
|
||||
initialOptions: activeStagedSwitch?.providerOptions,
|
||||
};
|
||||
}
|
||||
|
||||
function resolveAgentOptionControlsForComposer(input: {
|
||||
activeStagedSwitch: StagedProviderSwitch | null;
|
||||
stagedControls: ComposerOptionControls | null | undefined;
|
||||
liveOptionControls: ComposerOptionControls;
|
||||
onSetOption: (key: string, value: unknown) => void;
|
||||
}): ComposerOptionControls {
|
||||
const { activeStagedSwitch, stagedControls, liveOptionControls, onSetOption } = input;
|
||||
if (!activeStagedSwitch) {
|
||||
return liveOptionControls;
|
||||
}
|
||||
if (stagedControls) {
|
||||
return { ...stagedControls, onSetOption };
|
||||
}
|
||||
return { controls: [], options: activeStagedSwitch.providerOptions, onSetOption };
|
||||
}
|
||||
|
||||
function resolveControlledAgentControlsProps(input: {
|
||||
effectiveProvider: string | undefined;
|
||||
liveProvider: string;
|
||||
selectedModelId: string | null;
|
||||
selectedThinkingId: string | null;
|
||||
thinkingOptions: AgentControlOption[];
|
||||
supportsProviderSwitching: boolean;
|
||||
handleSelectProviderAndModel: (provider: string, modelId: string) => void;
|
||||
snapshotIsLoading: boolean;
|
||||
selectedProviderIsLoading: boolean;
|
||||
}) {
|
||||
return {
|
||||
provider: input.effectiveProvider ?? input.liveProvider,
|
||||
selectedModelId: input.selectedModelId ?? undefined,
|
||||
selectedThinkingOptionId: input.selectedThinkingId ?? undefined,
|
||||
thinkingOptions: input.thinkingOptions.length > 0 ? input.thinkingOptions : undefined,
|
||||
onSelectProviderAndModel: input.supportsProviderSwitching
|
||||
? input.handleSelectProviderAndModel
|
||||
: undefined,
|
||||
isModelLoading: input.snapshotIsLoading || input.selectedProviderIsLoading,
|
||||
};
|
||||
}
|
||||
|
||||
export const AgentControls = memo(function AgentControls({
|
||||
showToolbar,
|
||||
agentId,
|
||||
@@ -1003,15 +1155,22 @@ export const AgentControls = memo(function AgentControls({
|
||||
onDropdownClose,
|
||||
isCompactLayout,
|
||||
}: AgentControlsProps) {
|
||||
const { updatePreferences } = useFormPreferences();
|
||||
const { preferences, updatePreferences } = useFormPreferences();
|
||||
const agent = useSessionStore(
|
||||
useShallow((state) => selectAgentControlsSlice(state, serverId, agentId)),
|
||||
);
|
||||
const client = useSessionStore((state) => state.sessions[serverId]?.client ?? null);
|
||||
const supportsProviderSwitching = useSessionStore(
|
||||
(state) => state.sessions[serverId]?.serverInfo?.features?.providerSwitching === true,
|
||||
);
|
||||
const rawStagedSwitch = useStagedProviderSwitch(serverId, agentId);
|
||||
const activeStagedSwitch = resolveActiveStagedSwitch(
|
||||
supportsProviderSwitching,
|
||||
rawStagedSwitch,
|
||||
agent?.provider,
|
||||
);
|
||||
const toast = useToast();
|
||||
const modeControl = useLiveAgentModeControl(serverId, agentId);
|
||||
const commandCenterModes = toCommandCenterModes(modeControl);
|
||||
const modeProviderDefinitions = getModeProviderDefinitions(modeControl);
|
||||
const liveModeControl = useLiveAgentModeControl(serverId, agentId);
|
||||
|
||||
const {
|
||||
entries: snapshotEntries,
|
||||
@@ -1021,24 +1180,35 @@ export const AgentControls = memo(function AgentControls({
|
||||
refetchIfStale: refetchSnapshotIfStale,
|
||||
} = useProvidersSnapshot(serverId, { cwd: agent?.cwd });
|
||||
|
||||
const stagedProvider = activeStagedSwitch ? activeStagedSwitch.provider : null;
|
||||
const effectiveProvider = stagedProvider ?? agent?.provider;
|
||||
const stagedProviderRef = useRef<AgentProvider | null>(stagedProvider);
|
||||
stagedProviderRef.current = stagedProvider;
|
||||
|
||||
const snapshotSelectedEntry = useMemo(
|
||||
() => resolveProviderSnapshotEntry(snapshotEntries, agent?.provider),
|
||||
[snapshotEntries, agent?.provider],
|
||||
() => resolveProviderSnapshotEntry(snapshotEntries, effectiveProvider),
|
||||
[snapshotEntries, effectiveProvider],
|
||||
);
|
||||
|
||||
const models = filterSelectableModels(snapshotSelectedEntry?.models ?? null);
|
||||
const selectedProviderIsLoading = snapshotSelectedEntry?.status === "loading";
|
||||
|
||||
const agentProviderDefinitions = useMemo(
|
||||
() => buildAgentProviderDefinitions(agent?.provider, snapshotEntries),
|
||||
[agent?.provider, snapshotEntries],
|
||||
() => buildAgentProviderDefinitions(effectiveProvider, snapshotEntries),
|
||||
[effectiveProvider, snapshotEntries],
|
||||
);
|
||||
|
||||
const agentProviderModels = useMemo(
|
||||
() => buildAgentProviderModels(agent?.provider, models),
|
||||
[agent?.provider, models],
|
||||
() => buildAgentProviderModels(effectiveProvider, models),
|
||||
[effectiveProvider, models],
|
||||
);
|
||||
const agentModelSelectorProviders = useMemo(() => {
|
||||
if (supportsProviderSwitching && snapshotEntries && snapshotEntries.length > 0) {
|
||||
const selectable = buildSelectableProviderSelectorProviders(snapshotEntries, {
|
||||
selectedProvider: effectiveProvider ?? null,
|
||||
});
|
||||
if (selectable.length > 0) return selectable;
|
||||
}
|
||||
if (snapshotSelectedEntry) {
|
||||
return [buildSelectorProvider(snapshotSelectedEntry)];
|
||||
}
|
||||
@@ -1046,14 +1216,19 @@ export const AgentControls = memo(function AgentControls({
|
||||
providerDefinitions: agentProviderDefinitions,
|
||||
modelsByProvider: agentProviderModels,
|
||||
});
|
||||
}, [agentProviderDefinitions, agentProviderModels, snapshotSelectedEntry]);
|
||||
}, [
|
||||
agentProviderDefinitions,
|
||||
agentProviderModels,
|
||||
effectiveProvider,
|
||||
snapshotEntries,
|
||||
snapshotSelectedEntry,
|
||||
supportsProviderSwitching,
|
||||
]);
|
||||
|
||||
const modelSelection = resolveAgentModelSelection({
|
||||
const modelSelection = resolveAgentModelSelectionWithStagedSwitch({
|
||||
models,
|
||||
runtimeModelId: agent?.runtimeModelId,
|
||||
configuredModelId: agent?.model,
|
||||
runtimeThinkingOptionId: agent?.runtimeThinkingOptionId,
|
||||
explicitThinkingOptionId: agent?.thinkingOptionId,
|
||||
agent,
|
||||
activeStagedSwitch,
|
||||
});
|
||||
|
||||
const modelOptions = useMemo<AgentControlOption[]>(() => {
|
||||
@@ -1070,13 +1245,71 @@ export const AgentControls = memo(function AgentControls({
|
||||
const agentProvider = agent?.provider;
|
||||
const activeModelId = modelSelection.activeModelId;
|
||||
|
||||
const handleSelectModel = useCallback(
|
||||
const stagedModeOptions = useMemo<AgentMode[]>(() => {
|
||||
if (!activeStagedSwitch || !snapshotSelectedEntry?.modes) return [];
|
||||
return snapshotSelectedEntry.modes.map((mode) => ({
|
||||
id: mode.id,
|
||||
label: mode.label,
|
||||
description: mode.description ?? "",
|
||||
}));
|
||||
}, [activeStagedSwitch, snapshotSelectedEntry?.modes]);
|
||||
|
||||
const handleSelectStagedMode = useCallback(
|
||||
(modeId: string) => {
|
||||
useStagedProviderSwitchStore.getState().patch(serverId, agentId, (current) => ({
|
||||
...current,
|
||||
modeId,
|
||||
}));
|
||||
},
|
||||
[agentId, serverId],
|
||||
);
|
||||
|
||||
const modeControl = useMemo<AgentModeControlValue | null>(() => {
|
||||
if (!activeStagedSwitch) return liveModeControl;
|
||||
if (stagedModeOptions.length === 0) return null;
|
||||
return {
|
||||
provider: activeStagedSwitch.provider,
|
||||
providerDefinitions: agentProviderDefinitions,
|
||||
modeOptions: stagedModeOptions,
|
||||
selectedModeId:
|
||||
activeStagedSwitch.modeId ??
|
||||
snapshotSelectedEntry?.defaultModeId ??
|
||||
stagedModeOptions[0]?.id ??
|
||||
null,
|
||||
onSelectMode: handleSelectStagedMode,
|
||||
disabled: !client,
|
||||
};
|
||||
}, [
|
||||
activeStagedSwitch,
|
||||
agentProviderDefinitions,
|
||||
client,
|
||||
handleSelectStagedMode,
|
||||
liveModeControl,
|
||||
snapshotSelectedEntry?.defaultModeId,
|
||||
stagedModeOptions,
|
||||
]);
|
||||
const commandCenterModes = toCommandCenterModes(modeControl);
|
||||
const modeProviderDefinitions = getModeProviderDefinitions(modeControl);
|
||||
|
||||
const getStagedProvider = useCallback(() => stagedProviderRef.current, []);
|
||||
const stagedDraftOptions = useDraftProviderOptions(
|
||||
buildStagedDraftOptionsParams({
|
||||
serverId,
|
||||
agentCwd: agent?.cwd,
|
||||
activeStagedSwitch,
|
||||
getProvider: getStagedProvider,
|
||||
modelId: modelSelection.activeModelId,
|
||||
thinkingOptionId: modelSelection.selectedThinkingId,
|
||||
}),
|
||||
);
|
||||
|
||||
const applyLiveModel = useCallback(
|
||||
async (modelId: string) => {
|
||||
if (!client || !agentProvider) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await client.setAgentModel(agentId, modelId);
|
||||
await client.setAgentModel(agentId, modelId, { expectedProvider: agentProvider });
|
||||
await updatePreferences((current) =>
|
||||
mergeProviderPreferences({
|
||||
preferences: current,
|
||||
@@ -1091,21 +1324,147 @@ export const AgentControls = memo(function AgentControls({
|
||||
},
|
||||
[agentId, agentProvider, client, toast, updatePreferences],
|
||||
);
|
||||
const handleSelectCommandCenterModel = useCallback(
|
||||
(_provider: AgentProvider, modelId: string) => handleSelectModel(modelId),
|
||||
[handleSelectModel],
|
||||
|
||||
const handleSelectModel = useCallback(
|
||||
async (modelId: string) => {
|
||||
if (activeStagedSwitch) {
|
||||
const nextModel = models?.find((candidate) => candidate.id === modelId);
|
||||
const preferredThinking =
|
||||
preferences.providerPreferences?.[activeStagedSwitch.provider]?.thinkingByModel?.[
|
||||
modelId
|
||||
];
|
||||
const nextThinking =
|
||||
preferredThinking ??
|
||||
nextModel?.defaultThinkingOptionId ??
|
||||
nextModel?.thinkingOptions?.[0]?.id ??
|
||||
null;
|
||||
useStagedProviderSwitchStore.getState().patch(serverId, agentId, (current) => ({
|
||||
...current,
|
||||
model: modelId,
|
||||
thinkingOptionId: nextThinking,
|
||||
}));
|
||||
return;
|
||||
}
|
||||
await applyLiveModel(modelId);
|
||||
},
|
||||
[
|
||||
activeStagedSwitch,
|
||||
agentId,
|
||||
applyLiveModel,
|
||||
models,
|
||||
preferences.providerPreferences,
|
||||
serverId,
|
||||
],
|
||||
);
|
||||
|
||||
// A running agent is one provider's process, so only that provider's profiles
|
||||
// can apply to it.
|
||||
const profileProviders = useMemo(() => (agentProvider ? [agentProvider] : []), [agentProvider]);
|
||||
const handleSelectProviderAndModel = useCallback(
|
||||
(nextProvider: string, modelId: string) => {
|
||||
if (!agentProvider) return;
|
||||
if (nextProvider === agentProvider && !isStagedProviderSwitchInFlight(serverId, agentId)) {
|
||||
clearStagedProviderSwitch(serverId, agentId);
|
||||
const liveModelId = agent?.runtimeModelId ?? agent?.model ?? null;
|
||||
if (modelId && modelId !== liveModelId) {
|
||||
void applyLiveModel(modelId);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (!supportsProviderSwitching) return;
|
||||
useStagedProviderSwitchStore.getState().stage(
|
||||
serverId,
|
||||
agentId,
|
||||
buildStagedProviderSwitchDraft({
|
||||
nextProvider,
|
||||
modelId,
|
||||
snapshotEntries,
|
||||
providerPreferences: preferences.providerPreferences,
|
||||
}),
|
||||
);
|
||||
},
|
||||
[
|
||||
agent?.model,
|
||||
agent?.runtimeModelId,
|
||||
agentId,
|
||||
agentProvider,
|
||||
applyLiveModel,
|
||||
preferences.providerPreferences,
|
||||
serverId,
|
||||
snapshotEntries,
|
||||
supportsProviderSwitching,
|
||||
],
|
||||
);
|
||||
|
||||
const handleSelectCommandCenterModel = useCallback(
|
||||
(provider: AgentProvider, modelId: string) => {
|
||||
if (supportsProviderSwitching) {
|
||||
handleSelectProviderAndModel(provider, modelId);
|
||||
return;
|
||||
}
|
||||
void handleSelectModel(modelId);
|
||||
},
|
||||
[handleSelectModel, handleSelectProviderAndModel, supportsProviderSwitching],
|
||||
);
|
||||
|
||||
const handleStageAgentProfileSwitch = useCallback(
|
||||
(resolved: MaterializedAgentProfile) => {
|
||||
if (!supportsProviderSwitching) return;
|
||||
const nextEntry = resolveProviderSnapshotEntry(snapshotEntries, resolved.provider);
|
||||
const modeIds = resolveSnapshotModeIds(nextEntry);
|
||||
const validModeId =
|
||||
resolved.modeId && (!modeIds || modeIds.includes(resolved.modeId))
|
||||
? resolved.modeId
|
||||
: (nextEntry?.defaultModeId ?? nextEntry?.modes?.[0]?.id ?? null);
|
||||
useStagedProviderSwitchStore.getState().stage(serverId, agentId, {
|
||||
provider: resolved.provider,
|
||||
model: resolved.modelId ?? null,
|
||||
modeId: validModeId,
|
||||
thinkingOptionId: resolved.thinkingOptionId ?? null,
|
||||
providerOptions: resolved.options ? { ...resolved.options } : {},
|
||||
});
|
||||
stagedDraftOptions.applyProfile({
|
||||
provider: resolved.provider,
|
||||
options: resolved.options ?? {},
|
||||
});
|
||||
},
|
||||
[agentId, serverId, snapshotEntries, stagedDraftOptions, supportsProviderSwitching],
|
||||
);
|
||||
|
||||
const handleClearStagedSwitchOnProfile = useCallback(() => {
|
||||
clearStagedProviderSwitch(serverId, agentId);
|
||||
}, [agentId, serverId]);
|
||||
|
||||
const profileProviders = useMemo(() => {
|
||||
if (supportsProviderSwitching) {
|
||||
return agentModelSelectorProviders.map((entry) => entry.id);
|
||||
}
|
||||
return agentProvider ? [agentProvider] : [];
|
||||
}, [agentModelSelectorProviders, agentProvider, supportsProviderSwitching]);
|
||||
const liveSnapshotEntry = useMemo(
|
||||
() => resolveProviderSnapshotEntry(snapshotEntries, agentProvider),
|
||||
[snapshotEntries, agentProvider],
|
||||
);
|
||||
const profileModeIds = useMemo(
|
||||
() => resolveSnapshotModeIds(snapshotSelectedEntry),
|
||||
[snapshotSelectedEntry],
|
||||
() => resolveSnapshotModeIds(liveSnapshotEntry),
|
||||
[liveSnapshotEntry],
|
||||
);
|
||||
const profileTarget = useMemo<AgentProfileApplyTarget>(
|
||||
() => ({ kind: "agent", agentId, availableModeIds: profileModeIds }),
|
||||
[agentId, profileModeIds],
|
||||
() => ({
|
||||
kind: "agent",
|
||||
agentId,
|
||||
availableModeIds: profileModeIds,
|
||||
currentProvider: agentProvider,
|
||||
isSwitchInFlight: () => isStagedProviderSwitchInFlight(serverId, agentId),
|
||||
onApplySameProvider: handleClearStagedSwitchOnProfile,
|
||||
onStageProviderSwitch: supportsProviderSwitching ? handleStageAgentProfileSwitch : undefined,
|
||||
}),
|
||||
[
|
||||
agentId,
|
||||
agentProvider,
|
||||
handleClearStagedSwitchOnProfile,
|
||||
handleStageAgentProfileSwitch,
|
||||
profileModeIds,
|
||||
serverId,
|
||||
supportsProviderSwitching,
|
||||
],
|
||||
);
|
||||
const agentProfiles = useAgentProfilePicker({
|
||||
serverId,
|
||||
@@ -1118,6 +1477,13 @@ export const AgentControls = memo(function AgentControls({
|
||||
|
||||
const handleSelectThinkingOption = useCallback(
|
||||
(thinkingOptionId: string) => {
|
||||
if (activeStagedSwitch) {
|
||||
useStagedProviderSwitchStore.getState().patch(serverId, agentId, (current) => ({
|
||||
...current,
|
||||
thinkingOptionId,
|
||||
}));
|
||||
return;
|
||||
}
|
||||
if (!client || !agentProvider) {
|
||||
return;
|
||||
}
|
||||
@@ -1138,18 +1504,35 @@ export const AgentControls = memo(function AgentControls({
|
||||
});
|
||||
}
|
||||
void client
|
||||
.setAgentThinkingOption(agentId, thinkingOptionId)
|
||||
.setAgentThinkingOption(agentId, thinkingOptionId, { expectedProvider: agentProvider })
|
||||
.then((notice) => showProviderNoticeToast(toast, notice))
|
||||
.catch((error) => {
|
||||
console.warn("[AgentControls] setAgentThinkingOption failed", error);
|
||||
toast.error(toErrorMessage(error));
|
||||
});
|
||||
},
|
||||
[activeModelId, agentId, agentProvider, client, toast, updatePreferences],
|
||||
[
|
||||
activeModelId,
|
||||
activeStagedSwitch,
|
||||
agentId,
|
||||
agentProvider,
|
||||
client,
|
||||
serverId,
|
||||
toast,
|
||||
updatePreferences,
|
||||
],
|
||||
);
|
||||
|
||||
const handleSetOption = useCallback(
|
||||
(key: string, value: unknown) => {
|
||||
if (activeStagedSwitch) {
|
||||
stagedDraftOptions.setOption(key, value);
|
||||
useStagedProviderSwitchStore.getState().patch(serverId, agentId, (current) => ({
|
||||
...current,
|
||||
providerOptions: { ...current.providerOptions, [key]: value },
|
||||
}));
|
||||
return;
|
||||
}
|
||||
if (!client || !agentProvider) {
|
||||
return;
|
||||
}
|
||||
@@ -1166,15 +1549,36 @@ export const AgentControls = memo(function AgentControls({
|
||||
).catch((error) => {
|
||||
console.warn("[AgentControls] persist option preference failed", error);
|
||||
});
|
||||
void client.setAgentOptions(agentId, { [key]: value }).catch((error) => {
|
||||
console.warn("[AgentControls] setAgentOptions failed", error);
|
||||
toast.error(toErrorMessage(error));
|
||||
});
|
||||
void client
|
||||
.setAgentOptions(agentId, { [key]: value }, { expectedProvider: agentProvider })
|
||||
.catch((error) => {
|
||||
console.warn("[AgentControls] setAgentOptions failed", error);
|
||||
toast.error(toErrorMessage(error));
|
||||
});
|
||||
},
|
||||
[agentId, agentProvider, client, toast, updatePreferences],
|
||||
[
|
||||
activeStagedSwitch,
|
||||
agentId,
|
||||
agentProvider,
|
||||
client,
|
||||
serverId,
|
||||
stagedDraftOptions,
|
||||
toast,
|
||||
updatePreferences,
|
||||
],
|
||||
);
|
||||
|
||||
const agentOptionControls = useAgentOptionControls(agent, handleSetOption);
|
||||
const liveOptionControls = useAgentOptionControls(agent, handleSetOption);
|
||||
const agentOptionControls = useMemo<ComposerOptionControls>(
|
||||
() =>
|
||||
resolveAgentOptionControlsForComposer({
|
||||
activeStagedSwitch,
|
||||
stagedControls: stagedDraftOptions.optionControls,
|
||||
liveOptionControls,
|
||||
onSetOption: handleSetOption,
|
||||
}),
|
||||
[activeStagedSwitch, handleSetOption, liveOptionControls, stagedDraftOptions.optionControls],
|
||||
);
|
||||
|
||||
// The agent's composer exists apart from this component; while this is mounted, prompt
|
||||
// commands go through the input the user is typing in.
|
||||
@@ -1198,12 +1602,12 @@ export const AgentControls = memo(function AgentControls({
|
||||
() => ({
|
||||
serverId,
|
||||
ownerKey: agentId,
|
||||
provider: agentProvider,
|
||||
provider: effectiveProvider,
|
||||
providerDefinitions: modeProviderDefinitions,
|
||||
profiles: agentProfiles,
|
||||
models: {
|
||||
providers: agentModelSelectorProviders,
|
||||
selectedProvider: agentProvider,
|
||||
selectedProvider: effectiveProvider,
|
||||
selectedModelId: activeModelId,
|
||||
select: handleSelectCommandCenterModel,
|
||||
},
|
||||
@@ -1222,7 +1626,7 @@ export const AgentControls = memo(function AgentControls({
|
||||
client,
|
||||
agentId,
|
||||
agentModelSelectorProviders,
|
||||
agentProvider,
|
||||
effectiveProvider,
|
||||
commandCenterModes,
|
||||
handleSelectCommandCenterModel,
|
||||
handleSelectThinkingOption,
|
||||
@@ -1242,8 +1646,8 @@ export const AgentControls = memo(function AgentControls({
|
||||
);
|
||||
|
||||
const handleModelSelectorOpen = useCallback(() => {
|
||||
refetchSnapshotIfStale(agentProvider);
|
||||
}, [agentProvider, refetchSnapshotIfStale]);
|
||||
refetchSnapshotIfStale(supportsProviderSwitching ? undefined : effectiveProvider);
|
||||
}, [effectiveProvider, refetchSnapshotIfStale, supportsProviderSwitching]);
|
||||
|
||||
const handleRetryModelProvider = useCallback(
|
||||
(provider: AgentProvider) => {
|
||||
@@ -1256,6 +1660,18 @@ export const AgentControls = memo(function AgentControls({
|
||||
return null;
|
||||
}
|
||||
|
||||
const resolvedControlProps = resolveControlledAgentControlsProps({
|
||||
effectiveProvider,
|
||||
liveProvider: agent.provider,
|
||||
selectedModelId: modelSelection.activeModelId,
|
||||
selectedThinkingId: modelSelection.selectedThinkingId,
|
||||
thinkingOptions,
|
||||
supportsProviderSwitching,
|
||||
handleSelectProviderAndModel,
|
||||
snapshotIsLoading,
|
||||
selectedProviderIsLoading,
|
||||
});
|
||||
|
||||
return (
|
||||
<ComposerModelProvider value={composer}>
|
||||
{commandCenterRegistration}
|
||||
@@ -1263,21 +1679,17 @@ export const AgentControls = memo(function AgentControls({
|
||||
<>
|
||||
{profileEditor.element}
|
||||
<ControlledAgentControls
|
||||
provider={agent.provider}
|
||||
{...resolvedControlProps}
|
||||
modelSelectorProviders={agentModelSelectorProviders}
|
||||
modelOptions={modelOptions}
|
||||
selectedModelId={modelSelection.activeModelId ?? undefined}
|
||||
onSelectModel={handleSelectModel}
|
||||
agentProfiles={agentProfiles}
|
||||
onApplyAgentProfile={agentProfiles?.applyProfile}
|
||||
onEditAgentProfiles={handleEditAgentProfiles}
|
||||
onCreateAgentProfile={profileActions.create}
|
||||
onEditAgentProfile={profileActions.edit}
|
||||
thinkingOptions={thinkingOptions.length > 0 ? thinkingOptions : undefined}
|
||||
selectedThinkingOptionId={modelSelection.selectedThinkingId ?? undefined}
|
||||
onSelectThinkingOption={handleSelectThinkingOption}
|
||||
optionControls={agentOptionControls}
|
||||
isModelLoading={snapshotIsLoading || selectedProviderIsLoading}
|
||||
onModelSelectorOpen={handleModelSelectorOpen}
|
||||
onRetryModelProvider={handleRetryModelProvider}
|
||||
isRetryingModelProvider={snapshotIsRefreshing}
|
||||
|
||||
@@ -296,7 +296,7 @@ export function useLiveAgentModeControl(
|
||||
console.warn("[AgentModeControl] persist mode preference failed", error);
|
||||
});
|
||||
void client
|
||||
.setAgentMode(agentId, modeId)
|
||||
.setAgentMode(agentId, modeId, { expectedProvider: slice.provider })
|
||||
.then((notice) => showProviderNoticeToast(toast, notice))
|
||||
.catch((error) => {
|
||||
console.warn("[AgentModeControl] setAgentMode failed", error);
|
||||
|
||||
@@ -9,6 +9,21 @@ import { useStore } from "zustand";
|
||||
import { getHostRuntimeStore } from "@/runtime/host-runtime";
|
||||
import { LoadingSpinner } from "@/components/ui/loading-spinner";
|
||||
import { Alert } from "@/components/ui/alert";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
beginStagedProviderSwitch,
|
||||
clearStagedProviderSwitch,
|
||||
endStagedProviderSwitch,
|
||||
getStagedProviderSwitch,
|
||||
isStagedProviderSwitchInFlight,
|
||||
settleCommittedProviderSwitch,
|
||||
useFailedStartupSettings,
|
||||
useIsStagedProviderSwitchInFlight,
|
||||
useStagedProviderSwitch,
|
||||
} from "@/composer/provider-switch";
|
||||
import { useProvidersSnapshot } from "@/hooks/use-providers-snapshot";
|
||||
import { normalizeAgentSnapshot } from "@/utils/agent-snapshots";
|
||||
import { resolveProviderLabel } from "@/utils/provider-definitions";
|
||||
import {
|
||||
View,
|
||||
Pressable,
|
||||
@@ -48,6 +63,7 @@ import { usePanelStore, type MobilePanelView } from "@/stores/panel-store";
|
||||
import { usePointerCapabilities } from "@/hooks/pointer-capabilities";
|
||||
import { useShallow } from "zustand/shallow";
|
||||
import {
|
||||
ArrowRightLeft,
|
||||
ArrowUp,
|
||||
Square,
|
||||
Pencil,
|
||||
@@ -298,16 +314,29 @@ function buildRealtimeVoiceButtonStyle(pressed: boolean, voiceButtonDisabled: bo
|
||||
|
||||
const EMPTY_METRICS: AgentMetric[] = [];
|
||||
|
||||
const EMPTY_AGENT_STATE = {
|
||||
provider: null,
|
||||
status: null,
|
||||
contextWindowMaxTokens: null,
|
||||
contextWindowUsedTokens: null,
|
||||
totalCostUsd: null,
|
||||
sessionMetrics: EMPTY_METRICS,
|
||||
model: null,
|
||||
};
|
||||
|
||||
function buildAgentStateSelector(serverId: string, agentId: string) {
|
||||
return (state: ReturnType<typeof useSessionStore.getState>) => {
|
||||
const agent = state.sessions[serverId]?.agents?.get(agentId) ?? null;
|
||||
if (!agent) return EMPTY_AGENT_STATE;
|
||||
const usage = agent.lastUsage;
|
||||
return {
|
||||
status: agent?.status ?? null,
|
||||
contextWindowMaxTokens: agent?.lastUsage?.contextWindowMaxTokens ?? null,
|
||||
contextWindowUsedTokens: agent?.lastUsage?.contextWindowUsedTokens ?? null,
|
||||
totalCostUsd: agent?.lastUsage?.totalCostUsd ?? null,
|
||||
sessionMetrics: agent?.sessionMetrics ?? EMPTY_METRICS,
|
||||
model: agent?.model ?? null,
|
||||
provider: agent.provider ?? null,
|
||||
status: agent.status ?? null,
|
||||
contextWindowMaxTokens: usage?.contextWindowMaxTokens ?? null,
|
||||
contextWindowUsedTokens: usage?.contextWindowUsedTokens ?? null,
|
||||
totalCostUsd: usage?.totalCostUsd ?? null,
|
||||
sessionMetrics: agent.sessionMetrics ?? EMPTY_METRICS,
|
||||
model: agent.model ?? null,
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -1352,10 +1381,57 @@ function ComposerContentImpl({
|
||||
const { settings: appSettings } = useAppSettings();
|
||||
|
||||
const agentState = useSessionStore(useShallow(buildAgentStateSelector(serverId, agentId)));
|
||||
const supportsProviderSwitching = useSessionStore(
|
||||
(state) => state.sessions[serverId]?.serverInfo?.features?.providerSwitching === true,
|
||||
);
|
||||
const rawStagedSwitch = useStagedProviderSwitch(serverId, agentId);
|
||||
const isStagedSwitchInFlight = useIsStagedProviderSwitchInFlight(serverId, agentId);
|
||||
const failedStartupSettings = useFailedStartupSettings(serverId, agentId);
|
||||
const stagedSwitch =
|
||||
supportsProviderSwitching &&
|
||||
rawStagedSwitch &&
|
||||
agentState.provider &&
|
||||
rawStagedSwitch.provider !== agentState.provider
|
||||
? rawStagedSwitch
|
||||
: null;
|
||||
const { entries: providerSnapshotEntries } = useProvidersSnapshot(serverId, { cwd });
|
||||
const stagedProviderLabel = stagedSwitch
|
||||
? resolveProviderLabel(stagedSwitch.provider, providerSnapshotEntries)
|
||||
: null;
|
||||
|
||||
useEffect(() => {
|
||||
if (
|
||||
rawStagedSwitch &&
|
||||
agentState.provider &&
|
||||
rawStagedSwitch.provider === agentState.provider &&
|
||||
!isStagedProviderSwitchInFlight(serverId, agentId)
|
||||
) {
|
||||
clearStagedProviderSwitch(serverId, agentId);
|
||||
}
|
||||
}, [agentId, agentState.provider, rawStagedSwitch, serverId]);
|
||||
|
||||
const handleCancelStagedSwitch = useCallback(() => {
|
||||
clearStagedProviderSwitch(serverId, agentId);
|
||||
setSendError(null);
|
||||
useSessionStore.getState().setQueuedSendError(serverId, agentId, null);
|
||||
}, [agentId, serverId]);
|
||||
|
||||
const handleRetryFailedStartupSettings = useCallback(() => {
|
||||
setSendError(null);
|
||||
void getHostRuntimeStore().recoverFailedStartupSettings(serverId, agentId, "retry");
|
||||
}, [agentId, serverId]);
|
||||
|
||||
const handleDismissFailedStartupSettings = useCallback(() => {
|
||||
setSendError(null);
|
||||
void getHostRuntimeStore().recoverFailedStartupSettings(serverId, agentId, "discard");
|
||||
}, [agentId, serverId]);
|
||||
|
||||
const queuedMessagesRaw = useSessionStore((state) =>
|
||||
state.sessions[serverId]?.queuedMessages?.get(agentId),
|
||||
);
|
||||
const queuedSendError = useSessionStore(
|
||||
(state) => state.sessions[serverId]?.queuedSendErrors?.get(agentId) ?? null,
|
||||
);
|
||||
const queuedMessages = queuedMessagesRaw ?? EMPTY_ARRAY;
|
||||
|
||||
const setQueuedMessages = useSessionStore((state) => state.setQueuedMessages);
|
||||
@@ -1719,24 +1795,63 @@ function ComposerContentImpl({
|
||||
if (!client) {
|
||||
throw new Error(t("workspace.terminal.hostDisconnected"));
|
||||
}
|
||||
await dispatchComposerAgentMessage({
|
||||
client,
|
||||
agentId: targetAgentId,
|
||||
text,
|
||||
attachments: sendAttachments,
|
||||
attachmentSubmitFormat: resolveComposerAttachmentSubmitFormat({
|
||||
supportsForgeAttachments: supportsForgeSearch,
|
||||
}),
|
||||
submission: createMessageSubmissionWriter(serverId),
|
||||
activeTurnBehavior,
|
||||
activeTurnId:
|
||||
activeTurnBehavior === "steer"
|
||||
? (selectAgentTurnPresentation(
|
||||
useSessionStore.getState().sessions[serverId],
|
||||
targetAgentId,
|
||||
).turnId ?? undefined)
|
||||
: undefined,
|
||||
});
|
||||
const sessionState = useSessionStore.getState().sessions[serverId];
|
||||
const liveProvider = sessionState?.agents.get(targetAgentId)?.provider;
|
||||
const canSwitch = sessionState?.serverInfo?.features?.providerSwitching === true;
|
||||
const pendingSwitch = canSwitch ? getStagedProviderSwitch(serverId, targetAgentId) : null;
|
||||
const stagedProviderSwitch =
|
||||
pendingSwitch && pendingSwitch.provider !== liveProvider ? pendingSwitch : null;
|
||||
useSessionStore.getState().setQueuedSendError(serverId, targetAgentId, null);
|
||||
if (stagedProviderSwitch) {
|
||||
beginStagedProviderSwitch(serverId, targetAgentId);
|
||||
}
|
||||
try {
|
||||
await dispatchComposerAgentMessage({
|
||||
client,
|
||||
agentId: targetAgentId,
|
||||
text,
|
||||
attachments: sendAttachments,
|
||||
attachmentSubmitFormat: resolveComposerAttachmentSubmitFormat({
|
||||
supportsForgeAttachments: supportsForgeSearch,
|
||||
}),
|
||||
submission: createMessageSubmissionWriter(serverId),
|
||||
currentProvider: liveProvider ?? null,
|
||||
currentModel: sessionState?.agents.get(targetAgentId)?.model ?? null,
|
||||
stagedProviderSwitch,
|
||||
onProviderSwitchCommitted: async (agent) => {
|
||||
if (agent) {
|
||||
getHostRuntimeStore().tryAcceptAgentSnapshot(
|
||||
serverId,
|
||||
normalizeAgentSnapshot(agent, serverId),
|
||||
);
|
||||
}
|
||||
if (stagedProviderSwitch) {
|
||||
const settled = await settleCommittedProviderSwitch({
|
||||
serverId,
|
||||
agentId: targetAgentId,
|
||||
sentDraft: stagedProviderSwitch,
|
||||
committedProvider: agent?.provider ?? null,
|
||||
client,
|
||||
});
|
||||
if (!settled.applied) {
|
||||
setSendError(settled.errorMessage);
|
||||
}
|
||||
}
|
||||
},
|
||||
activeTurnBehavior,
|
||||
activeTurnId:
|
||||
activeTurnBehavior === "steer"
|
||||
? (selectAgentTurnPresentation(
|
||||
useSessionStore.getState().sessions[serverId],
|
||||
targetAgentId,
|
||||
).turnId ?? undefined)
|
||||
: undefined,
|
||||
});
|
||||
} finally {
|
||||
if (stagedProviderSwitch) {
|
||||
endStagedProviderSwitch(serverId, targetAgentId);
|
||||
}
|
||||
}
|
||||
onAttentionPromptSend?.();
|
||||
};
|
||||
}, [appSettings.sendBehavior, client, onAttentionPromptSend, serverId, supportsForgeSearch, t]);
|
||||
@@ -1812,7 +1927,7 @@ function ComposerContentImpl({
|
||||
attachments: outgoingAttachments,
|
||||
hasExternalContent,
|
||||
allowEmptySubmit,
|
||||
forceSend,
|
||||
forceSend: stagedSwitch && isAgentRunning ? false : forceSend,
|
||||
submitBehavior,
|
||||
isAgentRunning,
|
||||
// Parent-managed submits are still valid submit paths even when the
|
||||
@@ -1854,6 +1969,7 @@ function ComposerContentImpl({
|
||||
queueMessage,
|
||||
setSelectedAttachments,
|
||||
replaceUserInput,
|
||||
stagedSwitch,
|
||||
submitBehavior,
|
||||
submitMessage,
|
||||
t,
|
||||
@@ -2106,15 +2222,17 @@ function ComposerContentImpl({
|
||||
queue: queueWriter,
|
||||
});
|
||||
if (!result) return;
|
||||
useSessionStore.getState().setQueuedSendError(serverId, agentId, null);
|
||||
replaceUserInput(result.text);
|
||||
setSelectedAttachments(result.attachments);
|
||||
},
|
||||
[agentId, queueWriter, replaceUserInput, setSelectedAttachments],
|
||||
[agentId, queueWriter, replaceUserInput, serverId, setSelectedAttachments],
|
||||
);
|
||||
|
||||
const handleSendQueuedNow = useCallback(
|
||||
async (id: string) => {
|
||||
if (!sendAgentMessageRef.current && !onSubmitMessageRef.current) return;
|
||||
useSessionStore.getState().setQueuedSendError(serverId, agentId, null);
|
||||
// Reuse the regular send path; server-side send atomically interrupts any active run.
|
||||
const result = await sendQueuedComposerMessageNow({
|
||||
agentId,
|
||||
@@ -2128,7 +2246,7 @@ function ComposerContentImpl({
|
||||
setSendError(result.errorMessage);
|
||||
}
|
||||
},
|
||||
[agentId, queueWriter, submitMessage, t],
|
||||
[agentId, queueWriter, serverId, submitMessage, t],
|
||||
);
|
||||
|
||||
const handleQueue = useCallback(
|
||||
@@ -2581,18 +2699,78 @@ function ComposerContentImpl({
|
||||
// Focusing the composer on a touch screen raises the on-screen keyboard over the conversation.
|
||||
const messageInputAutoFocus = autoFocus && isDesktopWebBreakpoint && hasFinePointer;
|
||||
const submitLoadingPressHandler = isAgentRunning ? handleCancelAgent : undefined;
|
||||
const displayError = externalError || sendError;
|
||||
const displayError =
|
||||
externalError || sendError || failedStartupSettings?.errorMessage || queuedSendError;
|
||||
const sendErrorNode = useMemo(
|
||||
() =>
|
||||
displayError ? (
|
||||
<Alert variant="error" size="sm" description={displayError} testID="composer-error" />
|
||||
<Alert variant="error" size="sm" description={displayError} testID="composer-error">
|
||||
{failedStartupSettings ? (
|
||||
<>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onPress={handleRetryFailedStartupSettings}
|
||||
testID="retry-failed-startup-settings"
|
||||
>
|
||||
{t("common.actions.retry")}
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onPress={handleDismissFailedStartupSettings}
|
||||
testID="dismiss-failed-startup-settings"
|
||||
>
|
||||
{t("common.actions.dismiss")}
|
||||
</Button>
|
||||
</>
|
||||
) : null}
|
||||
</Alert>
|
||||
) : null,
|
||||
[displayError],
|
||||
[
|
||||
displayError,
|
||||
failedStartupSettings,
|
||||
handleDismissFailedStartupSettings,
|
||||
handleRetryFailedStartupSettings,
|
||||
t,
|
||||
],
|
||||
);
|
||||
const githubEmptyText = githubSearchResultsQuery.isFetching
|
||||
? t("composer.github.searching")
|
||||
: t("composer.github.noResults");
|
||||
|
||||
const stagedSwitchBannerNode = useMemo(() => {
|
||||
if (!stagedSwitch || !stagedProviderLabel || isStagedSwitchInFlight) return null;
|
||||
const message = isAgentRunning
|
||||
? t("composer.providerSwitch.switchingAfterTurn", { provider: stagedProviderLabel })
|
||||
: t("composer.providerSwitch.switchingNextMessage", { provider: stagedProviderLabel });
|
||||
return (
|
||||
<View style={styles.stagedSwitchBanner} testID="staged-provider-switch-banner">
|
||||
<View style={styles.stagedSwitchLabelRow}>
|
||||
<ThemedArrowRightLeft size={ICON_SIZE.sm} uniProps={iconForegroundMutedMapping} />
|
||||
<Text style={styles.stagedSwitchText} numberOfLines={1}>
|
||||
{message}
|
||||
</Text>
|
||||
</View>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onPress={handleCancelStagedSwitch}
|
||||
testID="cancel-staged-provider-switch"
|
||||
>
|
||||
{t("common.actions.cancel")}
|
||||
</Button>
|
||||
</View>
|
||||
);
|
||||
}, [
|
||||
handleCancelStagedSwitch,
|
||||
isAgentRunning,
|
||||
isStagedSwitchInFlight,
|
||||
stagedProviderLabel,
|
||||
stagedSwitch,
|
||||
t,
|
||||
]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<ComposerKeyboardRegistration
|
||||
@@ -2618,6 +2796,7 @@ function ComposerContentImpl({
|
||||
>
|
||||
<View style={inputAreaContentStyle}>
|
||||
{isFullscreen ? null : queueList}
|
||||
{isFullscreen ? null : stagedSwitchBannerNode}
|
||||
{!isFullscreen && sendErrorNode}
|
||||
|
||||
<ComposerAutocompleteBinding
|
||||
@@ -2873,9 +3052,35 @@ const styles = StyleSheet.create((theme: Theme) => ({
|
||||
queueSendButton: {
|
||||
backgroundColor: theme.colors.accent,
|
||||
},
|
||||
stagedSwitchBanner: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
justifyContent: "space-between",
|
||||
paddingLeft: theme.spacing[3],
|
||||
paddingRight: theme.spacing[1.5],
|
||||
paddingVertical: theme.spacing[1],
|
||||
backgroundColor: theme.colors.surface1,
|
||||
borderRadius: theme.borderRadius.md,
|
||||
borderWidth: theme.borderWidth[1],
|
||||
borderColor: theme.colors.border,
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
stagedSwitchLabelRow: {
|
||||
flex: 1,
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[1.5],
|
||||
minWidth: 0,
|
||||
},
|
||||
stagedSwitchText: {
|
||||
flex: 1,
|
||||
fontSize: theme.fontSize.sm,
|
||||
color: theme.colors.foregroundMuted,
|
||||
},
|
||||
})) as unknown as Record<string, object>;
|
||||
|
||||
const ThemedAttachmentSpinner = withUnistyles(LoadingSpinner);
|
||||
const ThemedArrowRightLeft = withUnistyles(ArrowRightLeft);
|
||||
const ThemedPencil = withUnistyles(Pencil);
|
||||
const ThemedArrowUp = withUnistyles(ArrowUp);
|
||||
const ThemedGitPullRequest = withUnistyles(GitPullRequest);
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
import React, { act, useCallback, useMemo, useRef, useState, type FormEvent } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { expect, it } from "vitest";
|
||||
import { useComposerHeight } from "./height.web";
|
||||
|
||||
it("keeps height measurement bounded when editing a long multiline draft", () => {
|
||||
function Composer() {
|
||||
const textarea = useRef<HTMLTextAreaElement>(null);
|
||||
const [renderedLines, setRenderedLines] = useState(1);
|
||||
const getText = useCallback(() => textarea.current?.value ?? "", []);
|
||||
const sizing = useComposerHeight({
|
||||
getText,
|
||||
textareaRef: textarea,
|
||||
minHeight: 24,
|
||||
maxHeight: 96,
|
||||
onRenderedLinesChange: setRenderedLines,
|
||||
});
|
||||
if (sizing.mode !== "measured") throw new Error("Expected web height measurement");
|
||||
|
||||
const { onTextChange } = sizing;
|
||||
const edit = useCallback(
|
||||
(event: FormEvent<HTMLTextAreaElement>) => onTextChange("", event.currentTarget.value),
|
||||
[onTextChange],
|
||||
);
|
||||
const style = useMemo(
|
||||
() => ({ height: Number(sizing.style.height), width: 400, lineHeight: "20px" }),
|
||||
[sizing.style.height],
|
||||
);
|
||||
|
||||
return (
|
||||
<textarea ref={textarea} onInput={edit} style={style} data-multiline={renderedLines > 2} />
|
||||
);
|
||||
}
|
||||
|
||||
const container = document.body.appendChild(document.createElement("div"));
|
||||
const root = createRoot(container);
|
||||
try {
|
||||
act(() => root.render(<Composer />));
|
||||
const editor = container.querySelector("textarea")!;
|
||||
const draft = "Review the resulting change.\n".repeat(9_000);
|
||||
|
||||
function replaceText(text: string) {
|
||||
act(() => {
|
||||
editor.value = text;
|
||||
editor.dispatchEvent(new InputEvent("input", { bubbles: true }));
|
||||
});
|
||||
}
|
||||
|
||||
replaceText(draft);
|
||||
replaceText(draft + "x");
|
||||
|
||||
expect(editor.value).toBe(draft + "x");
|
||||
expect(editor.style.height).toBe("96px");
|
||||
expect(editor.dataset.multiline).toBe("true");
|
||||
const measurement = document.querySelector<HTMLTextAreaElement>(
|
||||
'textarea[aria-hidden="true"]',
|
||||
)!;
|
||||
expect(measurement.value.length).toBeLessThan(400);
|
||||
|
||||
replaceText("Short draft");
|
||||
expect(editor.style.height).toBe("24px");
|
||||
expect(editor.dataset.multiline).toBe("false");
|
||||
} finally {
|
||||
act(() => root.unmount());
|
||||
container.remove();
|
||||
}
|
||||
});
|
||||
@@ -33,6 +33,15 @@ const COPIED_STYLES = [
|
||||
"paddingLeft",
|
||||
] as const;
|
||||
|
||||
function prefixThroughHardLines(text: string, lines: number): string {
|
||||
let lineEnd = -1;
|
||||
for (let line = 0; line < lines; line += 1) {
|
||||
lineEnd = text.indexOf("\n", lineEnd + 1);
|
||||
if (lineEnd === -1) return text;
|
||||
}
|
||||
return text.slice(0, lineEnd + 1);
|
||||
}
|
||||
|
||||
export function useComposerHeight({
|
||||
getText,
|
||||
textareaRef,
|
||||
@@ -68,15 +77,29 @@ export function useComposerHeight({
|
||||
mirror.style[property] = computedStyle[property];
|
||||
}
|
||||
mirror.style.width = `${sourceWidth}px`;
|
||||
mirror.value = text.endsWith("\n") ? `${text} ` : text;
|
||||
const padding =
|
||||
parseFloat(computedStyle.paddingTop) + parseFloat(computedStyle.paddingBottom);
|
||||
const lineHeight = parseFloat(computedStyle.lineHeight);
|
||||
if (lineHeight > 0)
|
||||
paramsRef.current.onRenderedLinesChange?.(
|
||||
Math.round((mirror.scrollHeight - padding) / lineHeight),
|
||||
);
|
||||
setBoundedHeight(mirror.scrollHeight);
|
||||
const { maxHeight: currentMax, onRenderedLinesChange: reportLines } = paramsRef.current;
|
||||
// Complete hard lines can prove the height cap and the three-line fullscreen threshold.
|
||||
// Keep measuring the whole draft when the prefix cannot prove both.
|
||||
const measuredText =
|
||||
Number.isFinite(currentMax) && lineHeight > 0
|
||||
? prefixThroughHardLines(
|
||||
text,
|
||||
Math.max(3, Math.ceil((currentMax - padding) / lineHeight)),
|
||||
)
|
||||
: text;
|
||||
mirror.value = measuredText.endsWith("\n") ? `${measuredText} ` : measuredText;
|
||||
let scrollHeight = mirror.scrollHeight;
|
||||
if (measuredText !== text && scrollHeight < currentMax) {
|
||||
mirror.value = text.endsWith("\n") ? `${text} ` : text;
|
||||
scrollHeight = mirror.scrollHeight;
|
||||
}
|
||||
if (lineHeight > 0) {
|
||||
reportLines?.(Math.round((scrollHeight - padding) / lineHeight));
|
||||
}
|
||||
setBoundedHeight(scrollHeight);
|
||||
},
|
||||
[setBoundedHeight, textareaRef],
|
||||
);
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
export {
|
||||
applyFailedStartupSettings,
|
||||
beginStagedProviderSwitch,
|
||||
clearStagedProviderSwitch,
|
||||
discardFailedStartupSettings,
|
||||
endStagedProviderSwitch,
|
||||
getFailedStartupSettings,
|
||||
getStagedProviderSwitch,
|
||||
isStagedProviderSwitchInFlight,
|
||||
settleCommittedProviderSwitch,
|
||||
settleStagedProviderSwitch,
|
||||
useFailedStartupSettings,
|
||||
useIsStagedProviderSwitchInFlight,
|
||||
useStagedProviderSwitch,
|
||||
useStagedProviderSwitchStore,
|
||||
type FailedStartupSettings,
|
||||
type LiveAgentSettingsWriter,
|
||||
type SettleCommittedProviderSwitchResult,
|
||||
type StagedProviderSwitch,
|
||||
} from "./store";
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,86 @@
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import {
|
||||
clearStagedProviderSwitch,
|
||||
getStagedProviderSwitch,
|
||||
settleStagedProviderSwitch,
|
||||
useStagedProviderSwitchStore,
|
||||
} from "./index";
|
||||
|
||||
describe("staged provider switch store", () => {
|
||||
beforeEach(() => {
|
||||
useStagedProviderSwitchStore.setState({ stagedByKey: new Map() });
|
||||
});
|
||||
|
||||
it("stages, patches, and clears per server and agent", () => {
|
||||
const store = useStagedProviderSwitchStore.getState();
|
||||
store.stage("srv-1", "agent-1", {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
thinkingOptionId: "high",
|
||||
modeId: "auto",
|
||||
providerOptions: { fast_mode: true },
|
||||
});
|
||||
store.stage("srv-1", "agent-2", {
|
||||
provider: "opencode",
|
||||
model: null,
|
||||
thinkingOptionId: null,
|
||||
modeId: null,
|
||||
providerOptions: {},
|
||||
});
|
||||
|
||||
expect(getStagedProviderSwitch("srv-1", "agent-1")).toEqual({
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
thinkingOptionId: "high",
|
||||
modeId: "auto",
|
||||
providerOptions: { fast_mode: true },
|
||||
});
|
||||
|
||||
store.patch("srv-1", "agent-1", (current) => ({
|
||||
...current,
|
||||
thinkingOptionId: "medium",
|
||||
}));
|
||||
expect(getStagedProviderSwitch("srv-1", "agent-1")?.thinkingOptionId).toBe("medium");
|
||||
|
||||
clearStagedProviderSwitch("srv-1", "agent-1");
|
||||
expect(getStagedProviderSwitch("srv-1", "agent-1")).toBeNull();
|
||||
expect(getStagedProviderSwitch("srv-1", "agent-2")?.provider).toBe("opencode");
|
||||
|
||||
store.clearForServer("srv-1");
|
||||
expect(getStagedProviderSwitch("srv-1", "agent-2")).toBeNull();
|
||||
});
|
||||
|
||||
it("settles only the draft that was sent and preserves any newer selection or edit", () => {
|
||||
const store = useStagedProviderSwitchStore.getState();
|
||||
store.stage("srv-1", "agent-1", {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
thinkingOptionId: null,
|
||||
modeId: null,
|
||||
providerOptions: {},
|
||||
});
|
||||
const sentDraft = getStagedProviderSwitch("srv-1", "agent-1")!;
|
||||
|
||||
// User chooses Copilot before Codex reply returns -> settling Codex draft preserves Copilot.
|
||||
store.stage("srv-1", "agent-1", {
|
||||
provider: "copilot",
|
||||
model: "gpt-5",
|
||||
thinkingOptionId: null,
|
||||
modeId: null,
|
||||
providerOptions: {},
|
||||
});
|
||||
settleStagedProviderSwitch("srv-1", "agent-1", sentDraft);
|
||||
const copilotDraft = getStagedProviderSwitch("srv-1", "agent-1")!;
|
||||
expect(copilotDraft.provider).toBe("copilot");
|
||||
|
||||
// Patching the draft also produces a newer revision that settling the older reference preserves.
|
||||
store.patch("srv-1", "agent-1", (current) => ({ ...current, thinkingOptionId: "high" }));
|
||||
settleStagedProviderSwitch("srv-1", "agent-1", copilotDraft);
|
||||
const patchedCopilot = getStagedProviderSwitch("srv-1", "agent-1")!;
|
||||
expect(patchedCopilot.thinkingOptionId).toBe("high");
|
||||
|
||||
// Settling the current draft clears it cleanly.
|
||||
settleStagedProviderSwitch("srv-1", "agent-1", patchedCopilot);
|
||||
expect(getStagedProviderSwitch("srv-1", "agent-1")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,407 @@
|
||||
import { create } from "zustand";
|
||||
import type { AgentProvider, ProviderOptions } from "@getpaseo/protocol/agent-types";
|
||||
import type { AgentConfigApply } from "@getpaseo/protocol/messages";
|
||||
|
||||
export interface StagedProviderSwitch {
|
||||
provider: AgentProvider;
|
||||
model: string | null;
|
||||
thinkingOptionId: string | null;
|
||||
modeId: string | null;
|
||||
providerOptions: ProviderOptions;
|
||||
}
|
||||
|
||||
function stagedKey(serverId: string, agentId: string): string {
|
||||
return `${serverId}:${agentId}`;
|
||||
}
|
||||
|
||||
export interface LiveAgentSettingsWriter {
|
||||
applyAgentConfig?: (
|
||||
agentId: string,
|
||||
config: AgentConfigApply,
|
||||
options?: { expectedProvider?: AgentProvider },
|
||||
) => Promise<unknown>;
|
||||
setAgentModel?: (
|
||||
agentId: string,
|
||||
modelId: string | null,
|
||||
options?: { expectedProvider?: AgentProvider },
|
||||
) => Promise<unknown>;
|
||||
setAgentMode?: (
|
||||
agentId: string,
|
||||
modeId: string,
|
||||
options?: { expectedProvider?: AgentProvider },
|
||||
) => Promise<unknown>;
|
||||
setAgentThinkingOption?: (
|
||||
agentId: string,
|
||||
thinkingOptionId: string,
|
||||
options?: { expectedProvider?: AgentProvider },
|
||||
) => Promise<unknown>;
|
||||
setAgentOptions?: (
|
||||
agentId: string,
|
||||
options: ProviderOptions,
|
||||
mutationOptions?: { expectedProvider?: AgentProvider },
|
||||
) => Promise<unknown>;
|
||||
}
|
||||
|
||||
export interface FailedStartupSettings {
|
||||
provider: AgentProvider;
|
||||
bundle: AgentConfigApply;
|
||||
errorMessage: string;
|
||||
}
|
||||
|
||||
export type SettleCommittedProviderSwitchResult =
|
||||
| { applied: true }
|
||||
| { applied: false; errorMessage: string };
|
||||
|
||||
interface StagedProviderSwitchState {
|
||||
stagedByKey: Map<string, StagedProviderSwitch>;
|
||||
inFlightByKey: Map<string, number>;
|
||||
failedStartupSettingsByKey: Map<string, FailedStartupSettings>;
|
||||
stage: (serverId: string, agentId: string, draft: StagedProviderSwitch) => void;
|
||||
patch: (
|
||||
serverId: string,
|
||||
agentId: string,
|
||||
updater: (current: StagedProviderSwitch) => StagedProviderSwitch,
|
||||
) => void;
|
||||
beginSwitch: (serverId: string, agentId: string) => void;
|
||||
endSwitch: (serverId: string, agentId: string) => void;
|
||||
setFailedStartupSettings: (
|
||||
serverId: string,
|
||||
agentId: string,
|
||||
failed: FailedStartupSettings | null,
|
||||
) => void;
|
||||
settle: (serverId: string, agentId: string, sentDraft: StagedProviderSwitch) => void;
|
||||
clear: (serverId: string, agentId: string) => void;
|
||||
clearForServer: (serverId: string) => void;
|
||||
}
|
||||
|
||||
export const useStagedProviderSwitchStore = create<StagedProviderSwitchState>((set) => ({
|
||||
stagedByKey: new Map(),
|
||||
inFlightByKey: new Map(),
|
||||
failedStartupSettingsByKey: new Map(),
|
||||
|
||||
stage: (serverId, agentId, draft) =>
|
||||
set((state) => {
|
||||
const next = new Map(state.stagedByKey);
|
||||
next.set(stagedKey(serverId, agentId), draft);
|
||||
return { stagedByKey: next };
|
||||
}),
|
||||
|
||||
patch: (serverId, agentId, updater) =>
|
||||
set((state) => {
|
||||
const key = stagedKey(serverId, agentId);
|
||||
const current = state.stagedByKey.get(key);
|
||||
if (!current) return state;
|
||||
const updated = updater(current);
|
||||
if (updated === current) return state;
|
||||
const next = new Map(state.stagedByKey);
|
||||
next.set(key, updated);
|
||||
return { stagedByKey: next };
|
||||
}),
|
||||
|
||||
beginSwitch: (serverId, agentId) =>
|
||||
set((state) => {
|
||||
const key = stagedKey(serverId, agentId);
|
||||
const next = new Map(state.inFlightByKey);
|
||||
next.set(key, (next.get(key) ?? 0) + 1);
|
||||
return { inFlightByKey: next };
|
||||
}),
|
||||
|
||||
endSwitch: (serverId, agentId) =>
|
||||
set((state) => {
|
||||
const key = stagedKey(serverId, agentId);
|
||||
const count = state.inFlightByKey.get(key) ?? 0;
|
||||
if (count <= 0) return state;
|
||||
const next = new Map(state.inFlightByKey);
|
||||
if (count === 1) {
|
||||
next.delete(key);
|
||||
} else {
|
||||
next.set(key, count - 1);
|
||||
}
|
||||
return { inFlightByKey: next };
|
||||
}),
|
||||
|
||||
setFailedStartupSettings: (serverId, agentId, failed) =>
|
||||
set((state) => {
|
||||
const key = stagedKey(serverId, agentId);
|
||||
const next = new Map(state.failedStartupSettingsByKey);
|
||||
if (failed === null) {
|
||||
if (!next.has(key)) return state;
|
||||
next.delete(key);
|
||||
} else {
|
||||
next.set(key, failed);
|
||||
}
|
||||
return { failedStartupSettingsByKey: next };
|
||||
}),
|
||||
|
||||
settle: (serverId, agentId, sentDraft) =>
|
||||
set((state) => {
|
||||
const key = stagedKey(serverId, agentId);
|
||||
const current = state.stagedByKey.get(key);
|
||||
if (!current || current !== sentDraft) return state;
|
||||
const next = new Map(state.stagedByKey);
|
||||
next.delete(key);
|
||||
return { stagedByKey: next };
|
||||
}),
|
||||
|
||||
clear: (serverId, agentId) =>
|
||||
set((state) => {
|
||||
const key = stagedKey(serverId, agentId);
|
||||
if (!state.stagedByKey.has(key)) return state;
|
||||
const next = new Map(state.stagedByKey);
|
||||
next.delete(key);
|
||||
return { stagedByKey: next };
|
||||
}),
|
||||
|
||||
clearForServer: (serverId) =>
|
||||
set((state) => {
|
||||
const prefix = `${serverId}:`;
|
||||
let changed = false;
|
||||
const next = new Map(state.stagedByKey);
|
||||
for (const key of next.keys()) {
|
||||
if (key.startsWith(prefix)) {
|
||||
next.delete(key);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
const nextInFlight = new Map(state.inFlightByKey);
|
||||
for (const key of nextInFlight.keys()) {
|
||||
if (key.startsWith(prefix)) {
|
||||
nextInFlight.delete(key);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
const nextFailed = new Map(state.failedStartupSettingsByKey);
|
||||
for (const key of nextFailed.keys()) {
|
||||
if (key.startsWith(prefix)) {
|
||||
nextFailed.delete(key);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
return changed
|
||||
? {
|
||||
stagedByKey: next,
|
||||
inFlightByKey: nextInFlight,
|
||||
failedStartupSettingsByKey: nextFailed,
|
||||
}
|
||||
: state;
|
||||
}),
|
||||
}));
|
||||
|
||||
export function getStagedProviderSwitch(
|
||||
serverId: string,
|
||||
agentId: string,
|
||||
): StagedProviderSwitch | null {
|
||||
return (
|
||||
useStagedProviderSwitchStore.getState().stagedByKey.get(stagedKey(serverId, agentId)) ?? null
|
||||
);
|
||||
}
|
||||
|
||||
export function beginStagedProviderSwitch(serverId: string, agentId: string): void {
|
||||
useStagedProviderSwitchStore.getState().beginSwitch(serverId, agentId);
|
||||
}
|
||||
|
||||
export function endStagedProviderSwitch(serverId: string, agentId: string): void {
|
||||
useStagedProviderSwitchStore.getState().endSwitch(serverId, agentId);
|
||||
}
|
||||
|
||||
export function isStagedProviderSwitchInFlight(serverId: string, agentId: string): boolean {
|
||||
return (
|
||||
(useStagedProviderSwitchStore.getState().inFlightByKey.get(stagedKey(serverId, agentId)) ?? 0) >
|
||||
0
|
||||
);
|
||||
}
|
||||
|
||||
export function getFailedStartupSettings(
|
||||
serverId: string,
|
||||
agentId: string,
|
||||
): FailedStartupSettings | null {
|
||||
return (
|
||||
useStagedProviderSwitchStore
|
||||
.getState()
|
||||
.failedStartupSettingsByKey.get(stagedKey(serverId, agentId)) ?? null
|
||||
);
|
||||
}
|
||||
|
||||
export function useFailedStartupSettings(
|
||||
serverId: string,
|
||||
agentId: string,
|
||||
): FailedStartupSettings | null {
|
||||
return useStagedProviderSwitchStore(
|
||||
(state) => state.failedStartupSettingsByKey.get(stagedKey(serverId, agentId)) ?? null,
|
||||
);
|
||||
}
|
||||
|
||||
export function discardFailedStartupSettings(serverId: string, agentId: string): void {
|
||||
useStagedProviderSwitchStore.getState().setFailedStartupSettings(serverId, agentId, null);
|
||||
}
|
||||
|
||||
export function settleStagedProviderSwitch(
|
||||
serverId: string,
|
||||
agentId: string,
|
||||
sentDraft: StagedProviderSwitch,
|
||||
): void {
|
||||
useStagedProviderSwitchStore.getState().settle(serverId, agentId, sentDraft);
|
||||
}
|
||||
|
||||
function diffProviderOptions(
|
||||
sent: ProviderOptions,
|
||||
edited: ProviderOptions,
|
||||
): ProviderOptions | null {
|
||||
const patch: ProviderOptions = {};
|
||||
let hasDiff = false;
|
||||
for (const [key, value] of Object.entries(edited)) {
|
||||
if (sent[key] !== value) {
|
||||
patch[key] = value;
|
||||
hasDiff = true;
|
||||
}
|
||||
}
|
||||
return hasDiff ? patch : null;
|
||||
}
|
||||
|
||||
function buildEditedSettingsBundle(
|
||||
sentDraft: StagedProviderSwitch,
|
||||
editedDraft: StagedProviderSwitch,
|
||||
): AgentConfigApply | null {
|
||||
const config: AgentConfigApply = {};
|
||||
let hasChanges = false;
|
||||
if (editedDraft.model !== sentDraft.model) {
|
||||
config.modelId = editedDraft.model;
|
||||
hasChanges = true;
|
||||
}
|
||||
if (editedDraft.modeId !== sentDraft.modeId && editedDraft.modeId !== null) {
|
||||
config.modeId = editedDraft.modeId;
|
||||
hasChanges = true;
|
||||
}
|
||||
if (
|
||||
editedDraft.thinkingOptionId !== sentDraft.thinkingOptionId &&
|
||||
editedDraft.thinkingOptionId !== null
|
||||
) {
|
||||
config.thinkingOptionId = editedDraft.thinkingOptionId;
|
||||
hasChanges = true;
|
||||
}
|
||||
const optionsPatch = diffProviderOptions(sentDraft.providerOptions, editedDraft.providerOptions);
|
||||
if (optionsPatch) {
|
||||
config.options = optionsPatch;
|
||||
hasChanges = true;
|
||||
}
|
||||
return hasChanges ? config : null;
|
||||
}
|
||||
|
||||
async function applyEditedDraftSettingsToLiveAgent(
|
||||
agentId: string,
|
||||
bundle: AgentConfigApply,
|
||||
expectedProvider: AgentProvider,
|
||||
client: LiveAgentSettingsWriter,
|
||||
): Promise<void> {
|
||||
const providerGuard = { expectedProvider };
|
||||
if (client.applyAgentConfig) {
|
||||
await client.applyAgentConfig(agentId, bundle, providerGuard);
|
||||
return;
|
||||
}
|
||||
if (bundle.modelId !== undefined && client.setAgentModel) {
|
||||
await client.setAgentModel(agentId, bundle.modelId, providerGuard);
|
||||
}
|
||||
if (bundle.modeId !== undefined && client.setAgentMode) {
|
||||
await client.setAgentMode(agentId, bundle.modeId, providerGuard);
|
||||
}
|
||||
if (
|
||||
bundle.thinkingOptionId !== undefined &&
|
||||
bundle.thinkingOptionId !== null &&
|
||||
client.setAgentThinkingOption
|
||||
) {
|
||||
await client.setAgentThinkingOption(agentId, bundle.thinkingOptionId, providerGuard);
|
||||
}
|
||||
if (bundle.options && client.setAgentOptions) {
|
||||
await client.setAgentOptions(agentId, bundle.options, providerGuard);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Settles the staged draft captured by a committed switch and awaits any edited settings
|
||||
* for the provider that just became live before callers release queued follow-up prompts.
|
||||
* - Untouched draft: cleared.
|
||||
* - Newer draft targeting a different provider: preserved for the next switch.
|
||||
* - Newer draft editing settings of the provider that just became live: applied atomically
|
||||
* (via `applyAgentConfig` when available, else sequential setters) before settling the draft.
|
||||
* If the daemon rejects an edit, the draft is kept intact and `{ applied: false, errorMessage }`
|
||||
* is returned so callers surface the error and hold any queued follow-up prompt.
|
||||
*/
|
||||
export async function settleCommittedProviderSwitch(input: {
|
||||
serverId: string;
|
||||
agentId: string;
|
||||
sentDraft: StagedProviderSwitch;
|
||||
committedProvider?: AgentProvider | null;
|
||||
client?: LiveAgentSettingsWriter | null;
|
||||
}): Promise<SettleCommittedProviderSwitchResult> {
|
||||
const { serverId, agentId, sentDraft, committedProvider, client } = input;
|
||||
const store = useStagedProviderSwitchStore.getState();
|
||||
store.settle(serverId, agentId, sentDraft);
|
||||
const remaining = getStagedProviderSwitch(serverId, agentId);
|
||||
const liveProvider = committedProvider ?? sentDraft.provider;
|
||||
if (!remaining || remaining.provider !== liveProvider) {
|
||||
return { applied: true };
|
||||
}
|
||||
const bundle = buildEditedSettingsBundle(sentDraft, remaining);
|
||||
if (!bundle || !client) {
|
||||
store.settle(serverId, agentId, remaining);
|
||||
return { applied: true };
|
||||
}
|
||||
try {
|
||||
await applyEditedDraftSettingsToLiveAgent(agentId, bundle, liveProvider, client);
|
||||
store.settle(serverId, agentId, remaining);
|
||||
return { applied: true };
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : String(error);
|
||||
store.settle(serverId, agentId, remaining);
|
||||
store.setFailedStartupSettings(serverId, agentId, {
|
||||
provider: liveProvider,
|
||||
bundle,
|
||||
errorMessage,
|
||||
});
|
||||
console.warn("[ProviderSwitch] failed to forward edited settings after switch", error);
|
||||
return { applied: false, errorMessage };
|
||||
}
|
||||
}
|
||||
|
||||
/** Retries applying previously failed startup settings for a committed provider switch. */
|
||||
export async function applyFailedStartupSettings(input: {
|
||||
serverId: string;
|
||||
agentId: string;
|
||||
client: LiveAgentSettingsWriter;
|
||||
}): Promise<SettleCommittedProviderSwitchResult> {
|
||||
const { serverId, agentId, client } = input;
|
||||
const failed = getFailedStartupSettings(serverId, agentId);
|
||||
if (!failed) {
|
||||
return { applied: true };
|
||||
}
|
||||
const store = useStagedProviderSwitchStore.getState();
|
||||
try {
|
||||
await applyEditedDraftSettingsToLiveAgent(agentId, failed.bundle, failed.provider, client);
|
||||
store.setFailedStartupSettings(serverId, agentId, null);
|
||||
return { applied: true };
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : String(error);
|
||||
store.setFailedStartupSettings(serverId, agentId, { ...failed, errorMessage });
|
||||
console.warn("[ProviderSwitch] failed to retry startup settings", error);
|
||||
return { applied: false, errorMessage };
|
||||
}
|
||||
}
|
||||
|
||||
export function clearStagedProviderSwitch(serverId: string, agentId: string): void {
|
||||
useStagedProviderSwitchStore.getState().clear(serverId, agentId);
|
||||
}
|
||||
|
||||
export function useStagedProviderSwitch(
|
||||
serverId: string,
|
||||
agentId: string,
|
||||
): StagedProviderSwitch | null {
|
||||
return useStagedProviderSwitchStore(
|
||||
(state) => state.stagedByKey.get(stagedKey(serverId, agentId)) ?? null,
|
||||
);
|
||||
}
|
||||
|
||||
export function useIsStagedProviderSwitchInFlight(serverId: string, agentId: string): boolean {
|
||||
return useStagedProviderSwitchStore(
|
||||
(state) => (state.inFlightByKey.get(stagedKey(serverId, agentId)) ?? 0) > 0,
|
||||
);
|
||||
}
|
||||
@@ -3,17 +3,30 @@ import { useSessionStore } from "@/stores/session-store";
|
||||
import {
|
||||
appendSubmittedUserMessage,
|
||||
removeSubmittedUserMessage,
|
||||
type ProviderSwitchItem,
|
||||
type UserMessageItem,
|
||||
} from "@/types/stream";
|
||||
|
||||
function appendUntrackedSubmission(serverId: string, agentId: string, message: UserMessageItem) {
|
||||
function appendUntrackedSubmission(
|
||||
serverId: string,
|
||||
agentId: string,
|
||||
message: UserMessageItem,
|
||||
options?: { providerSwitch?: ProviderSwitchItem },
|
||||
) {
|
||||
const session = useSessionStore.getState().sessions[serverId];
|
||||
if (!session) return;
|
||||
const tail = session.agentStreamTail.get(agentId) ?? [];
|
||||
const head = session.agentStreamHead.get(agentId) ?? [];
|
||||
useSessionStore
|
||||
.getState()
|
||||
.setAgentStreamState(serverId, agentId, appendSubmittedUserMessage({ tail, head, message }));
|
||||
useSessionStore.getState().setAgentStreamState(
|
||||
serverId,
|
||||
agentId,
|
||||
appendSubmittedUserMessage({
|
||||
tail,
|
||||
head,
|
||||
message,
|
||||
providerSwitch: options?.providerSwitch,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function removeUntrackedSubmission(
|
||||
@@ -36,7 +49,8 @@ function removeUntrackedSubmission(
|
||||
|
||||
function createUntrackedMessageSubmissionWriter(serverId: string): MessageSubmissionWriter {
|
||||
return {
|
||||
begin: (agentId, message) => appendUntrackedSubmission(serverId, agentId, message),
|
||||
begin: (agentId, message, options) =>
|
||||
appendUntrackedSubmission(serverId, agentId, message, options),
|
||||
accept: () => undefined,
|
||||
reject: (agentId, clientMessageId) => {
|
||||
removeUntrackedSubmission(serverId, agentId, clientMessageId);
|
||||
@@ -54,8 +68,8 @@ export function createMessageSubmissionWriter(serverId: string): MessageSubmissi
|
||||
return createUntrackedMessageSubmissionWriter(serverId);
|
||||
}
|
||||
return {
|
||||
begin: (agentId, message) =>
|
||||
useSessionStore.getState().beginAgentMessageSubmission(serverId, agentId, message),
|
||||
begin: (agentId, message, options) =>
|
||||
useSessionStore.getState().beginAgentMessageSubmission(serverId, agentId, message, options),
|
||||
accept: (agentId, clientMessageId) =>
|
||||
useSessionStore.getState().acceptAgentMessageSubmission(serverId, agentId, clientMessageId),
|
||||
reject: (agentId, clientMessageId) =>
|
||||
|
||||
@@ -293,6 +293,16 @@ 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,
|
||||
@@ -303,6 +313,7 @@ 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;
|
||||
@@ -355,6 +366,8 @@ function SessionProviderInternal({ children, serverId, client }: SessionProvider
|
||||
viewedTimelineSyncRef.current = sync;
|
||||
setViewedTimelineSync(serverId, sync);
|
||||
sync.setActive(getIsAppVisible(appStateRef.current));
|
||||
// An online client replacement leaves isConnected unchanged, so seed each new owner.
|
||||
sync.setConnected(client.getConnectionState().status === "connected");
|
||||
const stopObservingOpenChats = observeOpenWorkspaceAgentIds(serverId, (agentIds) =>
|
||||
sync.replaceOpenTabAgentIds(agentIds),
|
||||
);
|
||||
|
||||
@@ -5,23 +5,10 @@ import invariant from "tiny-invariant";
|
||||
import { BrowserPane } from "@/desktop/browser/pane";
|
||||
import { usePaneContext, usePaneFocus } from "@/panels/pane-context";
|
||||
import { definePanel, type PanelDescriptor, type PanelIconProps } from "@/panels/panel-registry";
|
||||
import { browserTabLabel } from "@/panels/tab-labels";
|
||||
import { useBrowserStore } from "@/desktop/browser/store";
|
||||
import { useWorkspaceDirectory } from "@/stores/session-store-hooks";
|
||||
|
||||
function getBrowserLabel(input: { title: string; url: string }): string {
|
||||
const title = input.title.trim();
|
||||
if (title) {
|
||||
return title;
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = new URL(input.url);
|
||||
return parsed.hostname || input.url;
|
||||
} catch {
|
||||
return input.url;
|
||||
}
|
||||
}
|
||||
|
||||
function createBrowserTabIcon(faviconUrl: string | null) {
|
||||
return function BrowserTabIcon({ size, color }: PanelIconProps) {
|
||||
const source = useMemo(() => (faviconUrl ? { uri: faviconUrl } : undefined), []);
|
||||
@@ -42,7 +29,7 @@ function useBrowserPanelDescriptor(target: {
|
||||
const browser = useBrowserStore((state) => state.browsersById[target.browserId] ?? null);
|
||||
const url = browser?.url ?? "https://example.com";
|
||||
const icon = createBrowserTabIcon(browser?.faviconUrl ?? null);
|
||||
const label = getBrowserLabel({ title: browser?.title ?? "", url });
|
||||
const label = browserTabLabel({ title: browser?.title ?? "", url });
|
||||
|
||||
return {
|
||||
label,
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
/** One workspace's file tree state, driven from inside and outside React. */
|
||||
import {
|
||||
loadExplorerDirectory,
|
||||
type DirectoryListingResult,
|
||||
} from "@/file-explorer/directory-listings";
|
||||
import { clearFileFilter } from "@/file-explorer/filter";
|
||||
import { useExplorerRevealStore } from "@/file-explorer/reveal-request";
|
||||
import { revealExplorerEntry } from "@/file-explorer/tree";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
import { usePanelStore } from "@/stores/panel-store";
|
||||
import { useSessionStore, type AgentFileExplorerState } from "@/stores/session-store";
|
||||
|
||||
export interface FileExplorerWorkspaceScope {
|
||||
workspaceId?: string | null;
|
||||
workspaceRoot?: string | null;
|
||||
}
|
||||
|
||||
/** The tree being driven: its host, its state key, and the directory it lists. */
|
||||
export interface WorkspaceFileTree {
|
||||
serverId: string;
|
||||
stateKey: string;
|
||||
workspaceRoot: string | null;
|
||||
}
|
||||
|
||||
function createExplorerState(): AgentFileExplorerState {
|
||||
return {
|
||||
listingGeneration: 0,
|
||||
directories: new Map(),
|
||||
isLoading: false,
|
||||
lastError: null,
|
||||
pendingRequest: null,
|
||||
currentPath: ".",
|
||||
history: ["."],
|
||||
lastVisitedPath: ".",
|
||||
selectedEntryPath: null,
|
||||
};
|
||||
}
|
||||
|
||||
export function normalizeWorkspaceValue(value: string | null | undefined): string | null {
|
||||
if (typeof value !== "string") {
|
||||
return null;
|
||||
}
|
||||
const trimmed = value.trim();
|
||||
return trimmed.length > 0 ? trimmed : null;
|
||||
}
|
||||
|
||||
export function buildWorkspaceExplorerStateKey(scope: FileExplorerWorkspaceScope): string | null {
|
||||
const normalizedWorkspaceId = normalizeWorkspaceValue(scope.workspaceId);
|
||||
if (normalizedWorkspaceId) {
|
||||
return `workspace:${normalizedWorkspaceId}`;
|
||||
}
|
||||
const normalizedWorkspaceRoot = normalizeWorkspaceValue(scope.workspaceRoot);
|
||||
if (!normalizedWorkspaceRoot) {
|
||||
return null;
|
||||
}
|
||||
return `root:${normalizedWorkspaceRoot}`;
|
||||
}
|
||||
|
||||
export function updateWorkspaceExplorerState(
|
||||
tree: Pick<WorkspaceFileTree, "serverId" | "stateKey">,
|
||||
updater: (prev: AgentFileExplorerState) => AgentFileExplorerState,
|
||||
): AgentFileExplorerState | null {
|
||||
let updated: AgentFileExplorerState | null = null;
|
||||
useSessionStore.getState().setFileExplorer(tree.serverId, (prev) => {
|
||||
const next = new Map(prev);
|
||||
const current = next.get(tree.stateKey) ?? createExplorerState();
|
||||
updated = updater(current);
|
||||
next.set(tree.stateKey, updated);
|
||||
return next;
|
||||
});
|
||||
return updated;
|
||||
}
|
||||
|
||||
export function listWorkspaceExplorerDirectory(
|
||||
tree: WorkspaceFileTree,
|
||||
path: string,
|
||||
options?: { recordHistory?: boolean; setCurrentPath?: boolean },
|
||||
): Promise<DirectoryListingResult> {
|
||||
const normalizedPath = path && path.length > 0 ? path : ".";
|
||||
return loadExplorerDirectory({
|
||||
path: normalizedPath,
|
||||
options,
|
||||
updateState: (updater) => updateWorkspaceExplorerState(tree, updater),
|
||||
fallbackError: i18n.t("workspace.fileExplorer.errors.failedToListDirectory"),
|
||||
listDirectory: async () => {
|
||||
if (!tree.workspaceRoot) {
|
||||
throw new Error(i18n.t("workspace.fileExplorer.states.unavailable"));
|
||||
}
|
||||
const client = useSessionStore.getState().sessions[tree.serverId]?.client;
|
||||
if (!client) throw new Error(i18n.t("workspace.terminal.hostDisconnected"));
|
||||
return client.listDirectory(tree.workspaceRoot, normalizedPath);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function showWorkspaceExplorerHiddenFiles(): void {
|
||||
const panel = usePanelStore.getState();
|
||||
if (!panel.explorerShowHiddenFiles) panel.toggleExplorerShowHiddenFiles();
|
||||
}
|
||||
|
||||
export function expandWorkspaceExplorerPaths(stateKey: string, paths: string[]): void {
|
||||
usePanelStore
|
||||
.getState()
|
||||
.setExpandedPathsForWorkspace(stateKey, (current) =>
|
||||
Array.from(new Set([...current, ...paths])),
|
||||
);
|
||||
}
|
||||
|
||||
/** Selects an entry the tree has expanded to, and asks the tree to scroll to it. */
|
||||
export function showWorkspaceExplorerEntry(
|
||||
tree: Pick<WorkspaceFileTree, "serverId" | "stateKey">,
|
||||
entryPath: string,
|
||||
): void {
|
||||
updateWorkspaceExplorerState(tree, (state) => ({ ...state, selectedEntryPath: entryPath }));
|
||||
useExplorerRevealStore.getState().request(tree.stateKey, entryPath);
|
||||
}
|
||||
|
||||
/** Expands to an entry, selects it, and asks the tree to scroll to it. */
|
||||
export async function revealWorkspaceExplorerEntry(
|
||||
tree: WorkspaceFileTree,
|
||||
entryPath: string,
|
||||
): Promise<boolean> {
|
||||
const found = await revealExplorerEntry({
|
||||
entryPath,
|
||||
requestDirectoryListing: (path) =>
|
||||
listWorkspaceExplorerDirectory(tree, path, { recordHistory: false, setCurrentPath: false }),
|
||||
showHiddenFiles: showWorkspaceExplorerHiddenFiles,
|
||||
expandPaths: (paths) => expandWorkspaceExplorerPaths(tree.stateKey, paths),
|
||||
});
|
||||
if (found) {
|
||||
clearFileFilter(tree.stateKey);
|
||||
showWorkspaceExplorerEntry(tree, entryPath);
|
||||
}
|
||||
return found;
|
||||
}
|
||||
@@ -155,14 +155,15 @@ function MountedFilePanel({
|
||||
revision: number;
|
||||
onModifiedChange: (modified: boolean) => void;
|
||||
}) {
|
||||
const { state, setCurrentTabState } = usePaneContext();
|
||||
const { tabId, state, setCurrentTabState } = usePaneContext();
|
||||
const tab = useMemo<PluginTab>(
|
||||
() => ({
|
||||
id: tabId,
|
||||
setModified: onModifiedChange,
|
||||
state,
|
||||
setState: setCurrentTabState,
|
||||
}),
|
||||
[onModifiedChange, state, setCurrentTabState],
|
||||
[tabId, onModifiedChange, state, setCurrentTabState],
|
||||
);
|
||||
useEffect(() => () => onModifiedChange(false), [onModifiedChange]);
|
||||
return <FilePanelView panel={panel} file={file} tab={tab} params={params} revision={revision} />;
|
||||
|
||||
@@ -166,7 +166,7 @@ describe("ensureAgentIsInitialized", () => {
|
||||
kind: "assistant_message",
|
||||
id: "canonical-item",
|
||||
text: "Canonical before restart",
|
||||
timelineCursor: { epoch: "epoch-1", seq: 12 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 12, anchorSeq: 12 },
|
||||
timestamp: new Date("2026-07-27T10:00:00.000Z"),
|
||||
},
|
||||
],
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import { getHostRuntimeStore } from "@/runtime/host-runtime";
|
||||
import { useCallback, useMemo } from "react";
|
||||
import {
|
||||
useMutation,
|
||||
useQuery,
|
||||
useQueryClient,
|
||||
type MutationOptions,
|
||||
type QueryClient,
|
||||
type QueryKey,
|
||||
} from "@tanstack/react-query";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
import { agentHistoryQueryKey, allAgentHistoryQueryRootKey } from "./agent-history-query-key";
|
||||
|
||||
@@ -380,87 +380,95 @@ export function usePendingArchiveAgentIds(serverId: string): ReadonlySet<string>
|
||||
);
|
||||
}
|
||||
|
||||
export function useArchiveAgent() {
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
|
||||
const pendingQuery = useArchiveAgentPendingQuery();
|
||||
|
||||
const archiveMutation = useMutation({
|
||||
mutationFn: async (input: ArchiveAgentInput): Promise<{ archivedAt: string }> => {
|
||||
const client = useSessionStore.getState().sessions[input.serverId]?.client ?? null;
|
||||
/**
|
||||
* Archives an agent: hides it right away, then asks the daemon, and puts it back if that fails.
|
||||
*/
|
||||
export async function archiveAgent(
|
||||
queryClient: QueryClient,
|
||||
input: ArchiveAgentInput,
|
||||
): Promise<void> {
|
||||
const options: MutationOptions<
|
||||
{ archivedAt: string },
|
||||
Error,
|
||||
ArchiveAgentInput,
|
||||
ArchiveAgentMutationContext
|
||||
> = {
|
||||
mutationFn: async (variables) => {
|
||||
const client = useSessionStore.getState().sessions[variables.serverId]?.client ?? null;
|
||||
if (!client) {
|
||||
throw new Error(t("common.errors.daemonClientUnavailable"));
|
||||
throw new Error(i18n.t("common.errors.daemonClientUnavailable"));
|
||||
}
|
||||
return await client.archiveAgent(input.agentId);
|
||||
return await client.archiveAgent(variables.agentId);
|
||||
},
|
||||
onMutate: (input) => {
|
||||
onMutate: (variables) => {
|
||||
const context: ArchiveAgentMutationContext = {
|
||||
agent: getStoredAgentSnapshot(input),
|
||||
lists: getArchivedAgentListCacheSnapshot(queryClient, input.serverId),
|
||||
agent: getStoredAgentSnapshot(variables),
|
||||
lists: getArchivedAgentListCacheSnapshot(queryClient, variables.serverId),
|
||||
};
|
||||
const archivedAt = new Date().toISOString();
|
||||
|
||||
applyArchivedAgentCloseResults({
|
||||
queryClient,
|
||||
serverId: input.serverId,
|
||||
results: [{ agentId: input.agentId, archivedAt }],
|
||||
serverId: variables.serverId,
|
||||
results: [{ agentId: variables.agentId, archivedAt }],
|
||||
invalidateQueries: false,
|
||||
});
|
||||
setAgentArchiving({
|
||||
queryClient,
|
||||
serverId: input.serverId,
|
||||
agentId: input.agentId,
|
||||
serverId: variables.serverId,
|
||||
agentId: variables.agentId,
|
||||
isArchiving: true,
|
||||
});
|
||||
return context;
|
||||
},
|
||||
onSuccess: (result, input) => {
|
||||
onSuccess: (result, variables) => {
|
||||
markAgentArchivedInStore({
|
||||
serverId: input.serverId,
|
||||
agentId: input.agentId,
|
||||
serverId: variables.serverId,
|
||||
agentId: variables.agentId,
|
||||
archivedAt: result.archivedAt,
|
||||
});
|
||||
},
|
||||
onError: (_error, input, context) => {
|
||||
onError: (_error, variables, context) => {
|
||||
if (!context) {
|
||||
return;
|
||||
}
|
||||
restoreAgentSnapshot({
|
||||
serverId: input.serverId,
|
||||
agentId: input.agentId,
|
||||
serverId: variables.serverId,
|
||||
agentId: variables.agentId,
|
||||
agent: context.agent,
|
||||
});
|
||||
restoreArchivedAgentListCacheSnapshot(queryClient, input.serverId, context.lists);
|
||||
restoreArchivedAgentListCacheSnapshot(queryClient, variables.serverId, context.lists);
|
||||
},
|
||||
onSettled: (_result, _error, input) => {
|
||||
onSettled: (_result, _error, variables) => {
|
||||
clearArchiveAgentPending({
|
||||
queryClient,
|
||||
serverId: input.serverId,
|
||||
agentId: input.agentId,
|
||||
serverId: variables.serverId,
|
||||
agentId: variables.agentId,
|
||||
});
|
||||
void queryClient.invalidateQueries({
|
||||
queryKey: ["sidebarAgentsList", input.serverId],
|
||||
queryKey: ["sidebarAgentsList", variables.serverId],
|
||||
});
|
||||
void queryClient.invalidateQueries({
|
||||
queryKey: ["allAgents", input.serverId],
|
||||
queryKey: ["allAgents", variables.serverId],
|
||||
});
|
||||
void queryClient.invalidateQueries({
|
||||
queryKey: agentHistoryQueryKey(input.serverId),
|
||||
queryKey: agentHistoryQueryKey(variables.serverId),
|
||||
});
|
||||
void queryClient.invalidateQueries({
|
||||
queryKey: allAgentHistoryQueryRootKey(),
|
||||
});
|
||||
},
|
||||
});
|
||||
};
|
||||
await queryClient.getMutationCache().build(queryClient, options).execute(input);
|
||||
}
|
||||
|
||||
const archiveMutateAsync = archiveMutation.mutateAsync;
|
||||
export function useArchiveAgent() {
|
||||
const queryClient = useQueryClient();
|
||||
const pendingQuery = useArchiveAgentPendingQuery();
|
||||
|
||||
const archiveAgent = useCallback(
|
||||
async (input: ArchiveAgentInput): Promise<void> => {
|
||||
await archiveMutateAsync(input);
|
||||
},
|
||||
[archiveMutateAsync],
|
||||
const archive = useCallback(
|
||||
(input: ArchiveAgentInput): Promise<void> => archiveAgent(queryClient, input),
|
||||
[queryClient],
|
||||
);
|
||||
|
||||
const isArchivingAgent = useCallback(
|
||||
@@ -475,7 +483,7 @@ export function useArchiveAgent() {
|
||||
);
|
||||
|
||||
return {
|
||||
archiveAgent,
|
||||
archiveAgent: archive,
|
||||
isArchivingAgent,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,61 +1,32 @@
|
||||
import { useCallback, useMemo } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useSessionStore, type AgentFileExplorerState } from "@/stores/session-store";
|
||||
import { usePanelStore } from "@/stores/panel-store";
|
||||
import { revealExplorerDirectory, revealExplorerEntry } from "@/file-explorer/tree";
|
||||
import { useExplorerRevealStore } from "@/file-explorer/reveal-request";
|
||||
import { revealExplorerDirectory } from "@/file-explorer/tree";
|
||||
import { clearFileFilter } from "@/file-explorer/filter";
|
||||
import {
|
||||
loadExplorerDirectory,
|
||||
type DirectoryListingResult,
|
||||
invalidateExplorerDirectoryListings,
|
||||
} from "@/file-explorer/directory-listings";
|
||||
import {
|
||||
buildWorkspaceExplorerStateKey,
|
||||
expandWorkspaceExplorerPaths,
|
||||
listWorkspaceExplorerDirectory,
|
||||
normalizeWorkspaceValue,
|
||||
revealWorkspaceExplorerEntry,
|
||||
showWorkspaceExplorerEntry,
|
||||
showWorkspaceExplorerHiddenFiles,
|
||||
updateWorkspaceExplorerState,
|
||||
type FileExplorerWorkspaceScope,
|
||||
type WorkspaceFileTree,
|
||||
} from "@/file-explorer/workspace-tree";
|
||||
import { parentExplorerPath } from "@/utils/explorer-paths";
|
||||
|
||||
function createExplorerState(): AgentFileExplorerState {
|
||||
return {
|
||||
listingGeneration: 0,
|
||||
directories: new Map(),
|
||||
isLoading: false,
|
||||
lastError: null,
|
||||
pendingRequest: null,
|
||||
currentPath: ".",
|
||||
history: ["."],
|
||||
lastVisitedPath: ".",
|
||||
selectedEntryPath: null,
|
||||
};
|
||||
}
|
||||
|
||||
export interface FileExplorerWorkspaceScope {
|
||||
workspaceId?: string | null;
|
||||
workspaceRoot?: string | null;
|
||||
}
|
||||
|
||||
function normalizeWorkspaceValue(value: string | null | undefined): string | null {
|
||||
if (typeof value !== "string") {
|
||||
return null;
|
||||
}
|
||||
const trimmed = value.trim();
|
||||
return trimmed.length > 0 ? trimmed : null;
|
||||
}
|
||||
|
||||
export function buildWorkspaceExplorerStateKey(scope: FileExplorerWorkspaceScope): string | null {
|
||||
const normalizedWorkspaceId = normalizeWorkspaceValue(scope.workspaceId);
|
||||
if (normalizedWorkspaceId) {
|
||||
return `workspace:${normalizedWorkspaceId}`;
|
||||
}
|
||||
const normalizedWorkspaceRoot = normalizeWorkspaceValue(scope.workspaceRoot);
|
||||
if (!normalizedWorkspaceRoot) {
|
||||
return null;
|
||||
}
|
||||
return `root:${normalizedWorkspaceRoot}`;
|
||||
}
|
||||
export { buildWorkspaceExplorerStateKey, type FileExplorerWorkspaceScope };
|
||||
|
||||
export function useFileExplorerActions(params: { serverId: string } & FileExplorerWorkspaceScope) {
|
||||
const { t } = useTranslation();
|
||||
const { serverId, workspaceId, workspaceRoot } = params;
|
||||
const client = useSessionStore((state) => state.sessions[serverId]?.client ?? null);
|
||||
const setFileExplorer = useSessionStore((state) => state.setFileExplorer);
|
||||
const normalizedWorkspaceRoot = useMemo(
|
||||
() => normalizeWorkspaceValue(workspaceRoot),
|
||||
[workspaceRoot],
|
||||
@@ -69,66 +40,28 @@ export function useFileExplorerActions(params: { serverId: string } & FileExplor
|
||||
[workspaceId, normalizedWorkspaceRoot],
|
||||
);
|
||||
|
||||
const tree = useMemo<WorkspaceFileTree | null>(
|
||||
() =>
|
||||
workspaceStateKey
|
||||
? { serverId, stateKey: workspaceStateKey, workspaceRoot: normalizedWorkspaceRoot }
|
||||
: null,
|
||||
[normalizedWorkspaceRoot, serverId, workspaceStateKey],
|
||||
);
|
||||
|
||||
const updateExplorerState = useCallback(
|
||||
(
|
||||
updater: (prev: AgentFileExplorerState) => AgentFileExplorerState,
|
||||
): AgentFileExplorerState | null => {
|
||||
if (!workspaceStateKey) {
|
||||
return null;
|
||||
}
|
||||
let updated: AgentFileExplorerState | null = null;
|
||||
setFileExplorer(serverId, (prev) => {
|
||||
const next = new Map(prev);
|
||||
const current = next.get(workspaceStateKey) ?? createExplorerState();
|
||||
updated = updater(current);
|
||||
next.set(workspaceStateKey, updated);
|
||||
return next;
|
||||
});
|
||||
return updated;
|
||||
},
|
||||
[serverId, setFileExplorer, workspaceStateKey],
|
||||
): AgentFileExplorerState | null => (tree ? updateWorkspaceExplorerState(tree, updater) : null),
|
||||
[tree],
|
||||
);
|
||||
|
||||
const requestDirectoryListing = useCallback(
|
||||
async (
|
||||
path: string,
|
||||
options?: { recordHistory?: boolean; setCurrentPath?: boolean },
|
||||
): Promise<DirectoryListingResult> => {
|
||||
if (!workspaceStateKey) {
|
||||
return null;
|
||||
}
|
||||
const normalizedPath = path && path.length > 0 ? path : ".";
|
||||
return loadExplorerDirectory({
|
||||
path: normalizedPath,
|
||||
options,
|
||||
updateState: updateExplorerState,
|
||||
fallbackError: t("workspace.fileExplorer.errors.failedToListDirectory"),
|
||||
listDirectory: async () => {
|
||||
if (!normalizedWorkspaceRoot)
|
||||
throw new Error(t("workspace.fileExplorer.states.unavailable"));
|
||||
if (!client) throw new Error(t("workspace.terminal.hostDisconnected"));
|
||||
return client.listDirectory(normalizedWorkspaceRoot, normalizedPath);
|
||||
},
|
||||
});
|
||||
},
|
||||
[client, normalizedWorkspaceRoot, t, updateExplorerState, workspaceStateKey],
|
||||
);
|
||||
|
||||
const showHiddenFiles = useCallback(() => {
|
||||
const panel = usePanelStore.getState();
|
||||
if (!panel.explorerShowHiddenFiles) panel.toggleExplorerShowHiddenFiles();
|
||||
}, []);
|
||||
|
||||
const expandPaths = useCallback(
|
||||
(paths: string[]) => {
|
||||
if (!workspaceStateKey) return;
|
||||
usePanelStore
|
||||
.getState()
|
||||
.setExpandedPathsForWorkspace(workspaceStateKey, (current) =>
|
||||
Array.from(new Set([...current, ...paths])),
|
||||
);
|
||||
},
|
||||
[workspaceStateKey],
|
||||
): Promise<DirectoryListingResult> =>
|
||||
tree ? listWorkspaceExplorerDirectory(tree, path, options) : null,
|
||||
[tree],
|
||||
);
|
||||
|
||||
const selectExplorerEntry = useCallback(
|
||||
@@ -141,50 +74,27 @@ export function useFileExplorerActions(params: { serverId: string } & FileExplor
|
||||
[updateExplorerState],
|
||||
);
|
||||
|
||||
/** Selects an entry the tree has expanded to, and asks the tree to scroll to it. */
|
||||
const showEntry = useCallback(
|
||||
(entryPath: string) => {
|
||||
if (!workspaceStateKey) return;
|
||||
selectExplorerEntry(entryPath);
|
||||
useExplorerRevealStore.getState().request(workspaceStateKey, entryPath);
|
||||
},
|
||||
[selectExplorerEntry, workspaceStateKey],
|
||||
);
|
||||
|
||||
/** Expands to a directory and into it. `select` also selects it and scrolls the tree to it. */
|
||||
const revealDirectory = useCallback(
|
||||
async (directoryPath: string, { select = false }: { select?: boolean } = {}) => {
|
||||
if (!workspaceStateKey) return;
|
||||
if (!tree) return;
|
||||
const listed = await revealExplorerDirectory({
|
||||
directoryPath,
|
||||
requestDirectoryListing,
|
||||
showHiddenFiles,
|
||||
expandPaths,
|
||||
showHiddenFiles: showWorkspaceExplorerHiddenFiles,
|
||||
expandPaths: (paths) => expandWorkspaceExplorerPaths(tree.stateKey, paths),
|
||||
});
|
||||
clearFileFilter(workspaceStateKey);
|
||||
if (listed && select) showEntry(directoryPath);
|
||||
clearFileFilter(tree.stateKey);
|
||||
if (listed && select) showWorkspaceExplorerEntry(tree, directoryPath);
|
||||
},
|
||||
[expandPaths, requestDirectoryListing, showEntry, showHiddenFiles, workspaceStateKey],
|
||||
[requestDirectoryListing, tree],
|
||||
);
|
||||
|
||||
/** Expands to an entry, selects it, and asks the tree to scroll to it. */
|
||||
const revealEntry = useCallback(
|
||||
async (entryPath: string): Promise<boolean> => {
|
||||
if (!workspaceStateKey) return false;
|
||||
const found = await revealExplorerEntry({
|
||||
entryPath,
|
||||
requestDirectoryListing: (path) =>
|
||||
requestDirectoryListing(path, { recordHistory: false, setCurrentPath: false }),
|
||||
showHiddenFiles,
|
||||
expandPaths,
|
||||
});
|
||||
if (found) {
|
||||
clearFileFilter(workspaceStateKey);
|
||||
showEntry(entryPath);
|
||||
}
|
||||
return found;
|
||||
},
|
||||
[expandPaths, requestDirectoryListing, showEntry, showHiddenFiles, workspaceStateKey],
|
||||
async (entryPath: string): Promise<boolean> =>
|
||||
tree ? revealWorkspaceExplorerEntry(tree, entryPath) : false,
|
||||
[tree],
|
||||
);
|
||||
|
||||
const requestFileDownloadToken = useCallback(
|
||||
|
||||
@@ -18,16 +18,22 @@ function useIsAgentUnarchiving({ serverId, agentId }: UnarchiveAgentTarget): boo
|
||||
export async function runAgentUnarchive(input: {
|
||||
serverId: string;
|
||||
agentId: string;
|
||||
client: { refreshAgent: (agentId: string) => Promise<unknown> } | null;
|
||||
client: {
|
||||
refreshAgent: (agentId: string) => Promise<{ historyDiverged?: boolean } | unknown>;
|
||||
} | null;
|
||||
isConnected: boolean;
|
||||
onRefreshed?: (result: { historyDiverged?: boolean }) => void;
|
||||
}): Promise<boolean> {
|
||||
const { serverId, agentId, client, isConnected } = input;
|
||||
const { serverId, agentId, client, isConnected, onRefreshed } = input;
|
||||
if (!client || !isConnected || isAgentUnarchiving({ serverId, agentId })) {
|
||||
return false;
|
||||
}
|
||||
const token = beginAgentUnarchive({ serverId, agentId });
|
||||
try {
|
||||
await client.refreshAgent(agentId);
|
||||
const refreshed = await client.refreshAgent(agentId);
|
||||
if (refreshed && typeof refreshed === "object" && "historyDiverged" in refreshed) {
|
||||
onRefreshed?.(refreshed as { historyDiverged?: boolean });
|
||||
}
|
||||
return true;
|
||||
} finally {
|
||||
finishAgentUnarchive({ serverId, agentId }, token);
|
||||
@@ -39,9 +45,20 @@ export function useUnarchiveAgent({ serverId, agentId }: UnarchiveAgentTarget) {
|
||||
const isConnected = useHostRuntimeIsConnected(serverId);
|
||||
const isUnarchiving = useIsAgentUnarchiving({ serverId, agentId });
|
||||
|
||||
const unarchive = useCallback(async (): Promise<void> => {
|
||||
await runAgentUnarchive({ serverId, agentId, client, isConnected });
|
||||
}, [agentId, client, isConnected, serverId]);
|
||||
const unarchive = useCallback(
|
||||
async (options?: {
|
||||
onRefreshed?: (result: { historyDiverged?: boolean }) => void;
|
||||
}): Promise<void> => {
|
||||
await runAgentUnarchive({
|
||||
serverId,
|
||||
agentId,
|
||||
client,
|
||||
isConnected,
|
||||
onRefreshed: options?.onRefreshed,
|
||||
});
|
||||
},
|
||||
[agentId, client, isConnected, serverId],
|
||||
);
|
||||
|
||||
return {
|
||||
unarchive,
|
||||
|
||||
@@ -1,13 +1,12 @@
|
||||
import { PressHighlight } from "@/components/ui/press-highlight";
|
||||
import { useCallback, useMemo, useReducer, useRef, useState } from "react";
|
||||
import { useCallback, useMemo, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Alert, Text, View } from "react-native";
|
||||
import { Alert, Text, View, type LayoutChangeEvent } from "react-native";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { Check, ChevronDown, ChevronRight, Eye, EyeOff, Link2 } from "lucide-react-native";
|
||||
import { Check, Eye, EyeOff, Link2 } from "lucide-react-native";
|
||||
import type { HostProfile } from "@/types/host-connection";
|
||||
import { useHosts, useHostMutations } from "@/runtime/host-runtime";
|
||||
import { parseConnectionUri, serializeConnectionUri } from "@/utils/daemon-endpoints";
|
||||
import { buildConnectionFailureCopy } from "@/components/connection-failure-copy";
|
||||
import {
|
||||
AdaptiveModalSheet,
|
||||
@@ -15,24 +14,30 @@ import {
|
||||
type SheetHeader,
|
||||
} from "@/components/adaptive-modal-sheet";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { PairingTargetTracker } from "@/components/pair-link-credentials";
|
||||
import { buildDirectConnectionUri } from "@/components/direct-connection-host";
|
||||
import { SegmentedControl, type SegmentedControlOption } from "@/components/ui/segmented-control";
|
||||
import { useHardwareKeyboardPresent } from "@/keyboard/availability";
|
||||
import { getConnectionAuthFailureReason } from "@/utils/test-daemon-connection";
|
||||
import {
|
||||
canSwitchToForm,
|
||||
editForm,
|
||||
editHost,
|
||||
editPromptPassword,
|
||||
editUri,
|
||||
openDirectConnection,
|
||||
promptForPassword,
|
||||
resolveConnection,
|
||||
switchMode,
|
||||
type DirectConnectionForm,
|
||||
type DirectConnectionInput,
|
||||
type DirectConnectionMode,
|
||||
type DirectConnectionUri,
|
||||
type ResolvedDirectConnection,
|
||||
} from "./direct-connection";
|
||||
|
||||
const FLEX_ONE_STYLE = { flex: 1 } as const;
|
||||
|
||||
interface DirectConnectionDraft {
|
||||
host: string;
|
||||
port: string;
|
||||
useTls: boolean;
|
||||
password: string;
|
||||
}
|
||||
|
||||
interface PreparedDirectConnection {
|
||||
uri: string;
|
||||
endpoint: string;
|
||||
useTls: boolean;
|
||||
password?: string;
|
||||
}
|
||||
// The sheet's default first stop (65%) cuts off Password on phones about 690dp tall or shorter.
|
||||
// 80% fits the whole form above Cancel and Connect down to 640dp.
|
||||
const SNAP_POINTS = ["80%", "92%"];
|
||||
|
||||
interface DirectConnectionLabels {
|
||||
hostRequired: string;
|
||||
@@ -49,6 +54,9 @@ interface DirectConnectionLabels {
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
modeBody: {
|
||||
gap: theme.spacing[4],
|
||||
},
|
||||
field: {
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
@@ -114,26 +122,10 @@ const styles = StyleSheet.create((theme) => ({
|
||||
backgroundColor: theme.colors.accent,
|
||||
borderColor: theme.colors.accent,
|
||||
},
|
||||
advancedToggle: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[2],
|
||||
alignSelf: "flex-start",
|
||||
paddingVertical: theme.spacing[1],
|
||||
},
|
||||
advancedText: {
|
||||
color: theme.colors.foreground,
|
||||
fontSize: theme.fontSize.base,
|
||||
fontWeight: theme.fontWeight.medium,
|
||||
},
|
||||
actions: {
|
||||
footer: {
|
||||
flex: 1,
|
||||
flexDirection: "row",
|
||||
gap: theme.spacing[3],
|
||||
marginTop: theme.spacing[2],
|
||||
},
|
||||
helper: {
|
||||
color: theme.colors.foregroundMuted,
|
||||
fontSize: theme.fontSize.base,
|
||||
},
|
||||
error: {
|
||||
color: theme.colors.destructive,
|
||||
@@ -141,33 +133,6 @@ const styles = StyleSheet.create((theme) => ({
|
||||
},
|
||||
}));
|
||||
|
||||
function prepareDirectConnection(
|
||||
draft: DirectConnectionDraft,
|
||||
labels: DirectConnectionLabels,
|
||||
): PreparedDirectConnection {
|
||||
const parsed = parseConnectionUri(buildDirectConnectionUri(draft, labels));
|
||||
const endpoint = parsed.isIpv6
|
||||
? `[${parsed.host}]:${parsed.port}`
|
||||
: `${parsed.host}:${parsed.port}`;
|
||||
|
||||
return {
|
||||
uri: serializeConnectionUri(parsed),
|
||||
endpoint,
|
||||
useTls: parsed.useTls,
|
||||
...(parsed.password ? { password: parsed.password } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function draftFromConnectionUri(uri: string): DirectConnectionDraft {
|
||||
const parsed = parseConnectionUri(uri);
|
||||
return {
|
||||
host: parsed.host,
|
||||
port: String(parsed.port),
|
||||
useTls: parsed.useTls,
|
||||
password: parsed.password ?? "",
|
||||
};
|
||||
}
|
||||
|
||||
export interface AddHostModalProps {
|
||||
visible: boolean;
|
||||
onClose: () => void;
|
||||
@@ -198,31 +163,19 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
|
||||
const { probeAndUpsertDirectConnection, beginLinkPairing } = useHostMutations();
|
||||
const [linkPairing] = useState(() => beginLinkPairing());
|
||||
const isMobile = useIsCompactFormFactor();
|
||||
const keyboardPresent = useHardwareKeyboardPresent();
|
||||
|
||||
const [input, setInput] = useState<DirectConnectionInput>(openDirectConnection);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
const [errorMessage, setErrorMessage] = useState("");
|
||||
const [host, setHost] = useState("");
|
||||
const [port, setPort] = useState("6767");
|
||||
const [useTls, setUseTls] = useState(false);
|
||||
const [password, setPassword] = useState("");
|
||||
const [isPasswordVisible, setIsPasswordVisible] = useState(false);
|
||||
const [isAdvancedOpen, setIsAdvancedOpen] = useState(false);
|
||||
const [advancedUri, setAdvancedUri] = useState("");
|
||||
const [inputResetKey, bumpInputResetKey] = useReducer((key: number) => key + 1, 0);
|
||||
const advancedTarget = useRef(new PairingTargetTracker("", true));
|
||||
// Switching modes mounts the other mode's fields. They take focus when the user was typing
|
||||
// or has a keyboard, so a phone's keyboard stays up instead of closing on the switch.
|
||||
const [focusModeBody, setFocusModeBody] = useState(false);
|
||||
const fieldFocused = useRef(false);
|
||||
// URI mode keeps the Form body's height, so Cancel and Connect stay where they are.
|
||||
const [formBodyHeight, setFormBodyHeight] = useState<number | null>(null);
|
||||
|
||||
const connectIcon = useMemo(() => <ThemedLink2 size={16} />, []);
|
||||
const hostFieldStyle = useMemo(() => [styles.field, styles.hostField], []);
|
||||
const portFieldStyle = useMemo(() => [styles.field, styles.portField], []);
|
||||
const checkboxStyle = useMemo(
|
||||
() => [styles.checkbox, useTls ? styles.checkboxChecked : null],
|
||||
[useTls],
|
||||
);
|
||||
const passwordInputStyle = useMemo(() => [styles.input, styles.passwordInput], []);
|
||||
const useTlsAccessibilityState = useMemo(
|
||||
() => ({ checked: useTls, disabled: isSaving }),
|
||||
[isSaving, useTls],
|
||||
);
|
||||
const directConnectionLabels = useMemo<DirectConnectionLabels>(
|
||||
() => ({
|
||||
hostRequired: t("pairing.direct.errors.hostRequired"),
|
||||
@@ -241,6 +194,21 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
|
||||
);
|
||||
const header = useMemo<SheetHeader>(() => ({ title: t("pairing.direct.title") }), [t]);
|
||||
|
||||
const formAvailable = canSwitchToForm(input);
|
||||
const modeOptions = useMemo<SegmentedControlOption<DirectConnectionMode>[]>(
|
||||
() => [
|
||||
{
|
||||
value: "form",
|
||||
label: t("pairing.direct.modes.form"),
|
||||
testID: "direct-mode-form",
|
||||
disabled: !formAvailable,
|
||||
...(formAvailable ? {} : { tooltip: t("pairing.direct.modes.uriOnlyLink") }),
|
||||
},
|
||||
{ value: "uri", label: t("pairing.direct.modes.uri"), testID: "direct-mode-uri" },
|
||||
],
|
||||
[formAvailable, t],
|
||||
);
|
||||
|
||||
// Each open mounts a fresh form (see AddHostModal), so closing needs no reset.
|
||||
const handleClose = useCallback(() => {
|
||||
if (isSaving) return;
|
||||
@@ -252,71 +220,37 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
|
||||
(onCancel ?? onClose)();
|
||||
}, [isSaving, onCancel, onClose]);
|
||||
|
||||
const handleSaveRelay = useCallback(
|
||||
async (relayUri: string) => {
|
||||
try {
|
||||
setIsSaving(true);
|
||||
const commitInput = useCallback(
|
||||
(next: DirectConnectionInput) => {
|
||||
if (next.mode !== input.mode) {
|
||||
setFocusModeBody(keyboardPresent || fieldFocused.current);
|
||||
setErrorMessage("");
|
||||
const result = await linkPairing.submit(relayUri, password || undefined);
|
||||
if (result.status === "cancelled") return;
|
||||
const { profile, serverId, hostname } = result;
|
||||
const isNewHost = !daemons.some((daemon) => daemon.serverId === serverId);
|
||||
onSaved?.({ profile, serverId, hostname, isNewHost });
|
||||
handleClose();
|
||||
} catch (error) {
|
||||
setErrorMessage(
|
||||
error instanceof Error ? error.message : directConnectionLabels.invalidConnection,
|
||||
);
|
||||
} finally {
|
||||
setIsSaving(false);
|
||||
}
|
||||
setInput(next);
|
||||
},
|
||||
[
|
||||
daemons,
|
||||
directConnectionLabels.invalidConnection,
|
||||
handleClose,
|
||||
linkPairing,
|
||||
onSaved,
|
||||
password,
|
||||
],
|
||||
[input.mode, keyboardPresent],
|
||||
);
|
||||
|
||||
const handleSave = useCallback(async () => {
|
||||
if (isSaving) return;
|
||||
|
||||
const relayUri = isAdvancedOpen ? advancedUri.trim() : "";
|
||||
if (relayUri.startsWith("relay://") || relayUri.includes("#connect=")) {
|
||||
await handleSaveRelay(relayUri);
|
||||
return;
|
||||
}
|
||||
|
||||
let connection: PreparedDirectConnection;
|
||||
try {
|
||||
connection = prepareDirectConnection(
|
||||
{ host, port, useTls, password },
|
||||
directConnectionLabels,
|
||||
);
|
||||
} catch (error) {
|
||||
const message =
|
||||
error instanceof Error ? error.message : directConnectionLabels.invalidConnection;
|
||||
setErrorMessage(message);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setIsSaving(true);
|
||||
setErrorMessage("");
|
||||
|
||||
const { profile, serverId, hostname } = await probeAndUpsertDirectConnection({
|
||||
const connect = useCallback(
|
||||
async (connection: ResolvedDirectConnection) => {
|
||||
if (connection.kind === "relay") {
|
||||
const result = await linkPairing.submit(connection.link, connection.password);
|
||||
return result.status === "cancelled" ? null : result;
|
||||
}
|
||||
return probeAndUpsertDirectConnection({
|
||||
endpoint: connection.endpoint,
|
||||
useTls: connection.useTls,
|
||||
...(connection.password ? { password: connection.password } : {}),
|
||||
});
|
||||
const isNewHost = !daemons.some((daemon) => daemon.serverId === serverId);
|
||||
},
|
||||
[linkPairing, probeAndUpsertDirectConnection],
|
||||
);
|
||||
|
||||
onSaved?.({ profile, serverId, hostname, isNewHost });
|
||||
handleClose();
|
||||
} catch (error) {
|
||||
const describeFailure = useCallback(
|
||||
(connection: ResolvedDirectConnection, error: unknown) => {
|
||||
if (connection.kind === "relay") {
|
||||
return error instanceof Error ? error.message : directConnectionLabels.invalidConnection;
|
||||
}
|
||||
const {
|
||||
title,
|
||||
detail,
|
||||
@@ -326,108 +260,224 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
|
||||
error,
|
||||
labels: directConnectionLabels,
|
||||
});
|
||||
let combined: string;
|
||||
if (rawDetail && detail && rawDetail !== detail) {
|
||||
combined = `${title}\n${detail}\n${t("pairing.direct.errors.details", {
|
||||
detail: rawDetail,
|
||||
})}`;
|
||||
} else if (detail) {
|
||||
combined = `${title}\n${detail}`;
|
||||
} else {
|
||||
combined = title;
|
||||
return `${title}\n${detail}\n${t("pairing.direct.errors.details", { detail: rawDetail })}`;
|
||||
}
|
||||
setErrorMessage(combined);
|
||||
if (!isMobile) {
|
||||
Alert.alert(t("pairing.direct.errors.failedTitle"), combined);
|
||||
return detail ? `${title}\n${detail}` : title;
|
||||
},
|
||||
[directConnectionLabels, t],
|
||||
);
|
||||
|
||||
const handleSave = useCallback(async () => {
|
||||
if (isSaving) return;
|
||||
|
||||
let connection: ResolvedDirectConnection;
|
||||
try {
|
||||
connection = resolveConnection(input, directConnectionLabels);
|
||||
} catch (error) {
|
||||
setErrorMessage(
|
||||
error instanceof Error ? error.message : directConnectionLabels.invalidConnection,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setIsSaving(true);
|
||||
setErrorMessage("");
|
||||
const result = await connect(connection);
|
||||
if (!result) return;
|
||||
const { profile, serverId, hostname } = result;
|
||||
const isNewHost = !daemons.some((daemon) => daemon.serverId === serverId);
|
||||
onSaved?.({ profile, serverId, hostname, isNewHost });
|
||||
handleClose();
|
||||
} catch (error) {
|
||||
const message = describeFailure(connection, error);
|
||||
setErrorMessage(message);
|
||||
// URI mode has no Password field, so a rejected password is asked for here.
|
||||
if (input.mode === "uri" && getConnectionAuthFailureReason(error)) {
|
||||
setInput((current) => promptForPassword(current));
|
||||
return;
|
||||
}
|
||||
if (connection.kind === "direct" && !isMobile) {
|
||||
Alert.alert(t("pairing.direct.errors.failedTitle"), message);
|
||||
}
|
||||
} finally {
|
||||
setIsSaving(false);
|
||||
}
|
||||
}, [
|
||||
advancedUri,
|
||||
connect,
|
||||
daemons,
|
||||
describeFailure,
|
||||
directConnectionLabels,
|
||||
handleClose,
|
||||
host,
|
||||
isAdvancedOpen,
|
||||
input,
|
||||
isMobile,
|
||||
isSaving,
|
||||
onSaved,
|
||||
password,
|
||||
port,
|
||||
probeAndUpsertDirectConnection,
|
||||
t,
|
||||
handleSaveRelay,
|
||||
useTls,
|
||||
]);
|
||||
|
||||
const handleSubmitEditing = useCallback(() => {
|
||||
const handleSubmit = useCallback(() => {
|
||||
void handleSave();
|
||||
}, [handleSave]);
|
||||
|
||||
const handleSavePress = useCallback(() => {
|
||||
void handleSave();
|
||||
}, [handleSave]);
|
||||
const handleModeChange = useCallback(
|
||||
(mode: DirectConnectionMode) => commitInput(switchMode(input, mode)),
|
||||
[commitInput, input],
|
||||
);
|
||||
|
||||
const handleChangeAdvancedUri = useCallback((next: string) => {
|
||||
if (advancedTarget.current.changeUrl(next)) {
|
||||
setPassword("");
|
||||
bumpInputResetKey();
|
||||
setErrorMessage("");
|
||||
}
|
||||
setAdvancedUri(next);
|
||||
const handleFieldFocus = useCallback(() => {
|
||||
fieldFocused.current = true;
|
||||
}, []);
|
||||
|
||||
const handleToggleUseTls = useCallback(() => {
|
||||
if (isSaving) return;
|
||||
setUseTls((current) => !current);
|
||||
}, [isSaving]);
|
||||
|
||||
const handleTogglePasswordVisibility = useCallback(() => {
|
||||
setIsPasswordVisible((current) => !current);
|
||||
const handleFieldBlur = useCallback(() => {
|
||||
fieldFocused.current = false;
|
||||
}, []);
|
||||
|
||||
const handleToggleAdvanced = useCallback(() => {
|
||||
if (!isAdvancedOpen) {
|
||||
advancedTarget.current = new PairingTargetTracker("", true);
|
||||
try {
|
||||
setAdvancedUri(
|
||||
buildDirectConnectionUri({ host, port, useTls, password }, directConnectionLabels),
|
||||
);
|
||||
} catch {
|
||||
setAdvancedUri("");
|
||||
}
|
||||
setErrorMessage("");
|
||||
setIsAdvancedOpen(true);
|
||||
return;
|
||||
}
|
||||
const handleFormBodyLayout = useCallback((event: LayoutChangeEvent) => {
|
||||
setFormBodyHeight(event.nativeEvent.layout.height);
|
||||
}, []);
|
||||
|
||||
try {
|
||||
const next = draftFromConnectionUri(advancedUri);
|
||||
setHost(next.host);
|
||||
setPort(next.port);
|
||||
setUseTls(next.useTls);
|
||||
setPassword(next.password);
|
||||
setErrorMessage("");
|
||||
bumpInputResetKey();
|
||||
} catch {
|
||||
setErrorMessage("");
|
||||
}
|
||||
setIsAdvancedOpen(false);
|
||||
}, [advancedUri, directConnectionLabels, host, isAdvancedOpen, password, port, useTls]);
|
||||
const uriBodyStyle = useMemo(
|
||||
() => [styles.modeBody, formBodyHeight === null ? null : { minHeight: formBodyHeight }],
|
||||
[formBodyHeight],
|
||||
);
|
||||
|
||||
const AdvancedIcon = isAdvancedOpen ? ThemedChevronDown : ThemedChevronRight;
|
||||
const PasswordIcon = isPasswordVisible ? ThemedEyeOff : ThemedEye;
|
||||
const fieldEvents = useMemo<FieldEvents>(
|
||||
() => ({
|
||||
autoFocus: focusModeBody,
|
||||
onFocus: handleFieldFocus,
|
||||
onBlur: handleFieldBlur,
|
||||
onSubmit: handleSubmit,
|
||||
}),
|
||||
[focusModeBody, handleFieldBlur, handleFieldFocus, handleSubmit],
|
||||
);
|
||||
|
||||
const footer = useMemo(
|
||||
() => (
|
||||
<View style={styles.footer}>
|
||||
<Button
|
||||
style={FLEX_ONE_STYLE}
|
||||
variant="secondary"
|
||||
onPress={handleCancel}
|
||||
disabled={isSaving}
|
||||
>
|
||||
{t("pairing.direct.actions.cancel")}
|
||||
</Button>
|
||||
<Button
|
||||
style={FLEX_ONE_STYLE}
|
||||
variant="default"
|
||||
onPress={handleSubmit}
|
||||
disabled={isSaving}
|
||||
leftIcon={connectIcon}
|
||||
testID="direct-host-submit"
|
||||
>
|
||||
{isSaving ? t("pairing.direct.actions.connecting") : t("pairing.direct.actions.connect")}
|
||||
</Button>
|
||||
</View>
|
||||
),
|
||||
[connectIcon, handleCancel, handleSubmit, isSaving, t],
|
||||
);
|
||||
|
||||
return (
|
||||
<AdaptiveModalSheet
|
||||
header={header}
|
||||
visible={visible}
|
||||
onClose={handleClose}
|
||||
footer={footer}
|
||||
snapPoints={SNAP_POINTS}
|
||||
testID="add-host-modal"
|
||||
>
|
||||
<Text style={styles.helper}>{t("pairing.direct.helper")}</Text>
|
||||
<SegmentedControl
|
||||
options={modeOptions}
|
||||
value={input.mode}
|
||||
onValueChange={handleModeChange}
|
||||
fill
|
||||
testID="direct-mode"
|
||||
/>
|
||||
|
||||
{input.mode === "form" ? (
|
||||
<View key="form" style={styles.modeBody} onLayout={handleFormBodyLayout}>
|
||||
<DirectFormFields
|
||||
input={input}
|
||||
isSaving={isSaving}
|
||||
fieldEvents={fieldEvents}
|
||||
onChange={commitInput}
|
||||
/>
|
||||
</View>
|
||||
) : (
|
||||
<View key="uri" style={uriBodyStyle}>
|
||||
<DirectUriFields
|
||||
input={input}
|
||||
isSaving={isSaving}
|
||||
fieldEvents={fieldEvents}
|
||||
onChange={commitInput}
|
||||
/>
|
||||
</View>
|
||||
)}
|
||||
|
||||
{errorMessage ? <Text style={styles.error}>{errorMessage}</Text> : null}
|
||||
</AdaptiveModalSheet>
|
||||
);
|
||||
}
|
||||
|
||||
interface FieldEvents {
|
||||
/** Whether the mode's first field takes focus when it mounts. */
|
||||
autoFocus: boolean;
|
||||
onFocus: () => void;
|
||||
onBlur: () => void;
|
||||
onSubmit: () => void;
|
||||
}
|
||||
|
||||
function DirectFormFields({
|
||||
input,
|
||||
isSaving,
|
||||
fieldEvents,
|
||||
onChange,
|
||||
}: {
|
||||
input: DirectConnectionForm;
|
||||
isSaving: boolean;
|
||||
fieldEvents: FieldEvents;
|
||||
onChange: (next: DirectConnectionInput) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const [isPasswordVisible, setIsPasswordVisible] = useState(false);
|
||||
const hostFieldStyle = useMemo(() => [styles.field, styles.hostField], []);
|
||||
const portFieldStyle = useMemo(() => [styles.field, styles.portField], []);
|
||||
const passwordInputStyle = useMemo(() => [styles.input, styles.passwordInput], []);
|
||||
const checkboxStyle = useMemo(
|
||||
() => [styles.checkbox, input.useTls ? styles.checkboxChecked : null],
|
||||
[input.useTls],
|
||||
);
|
||||
const useTlsAccessibilityState = useMemo(
|
||||
() => ({ checked: input.useTls, disabled: isSaving }),
|
||||
[isSaving, input.useTls],
|
||||
);
|
||||
|
||||
const handleHostChange = useCallback(
|
||||
(host: string) => onChange(editHost(input, host)),
|
||||
[input, onChange],
|
||||
);
|
||||
const handlePortChange = useCallback(
|
||||
(port: string) => onChange(editForm(input, { port })),
|
||||
[input, onChange],
|
||||
);
|
||||
const handlePasswordChange = useCallback(
|
||||
(password: string) => onChange(editForm(input, { password })),
|
||||
[input, onChange],
|
||||
);
|
||||
const handleToggleUseTls = useCallback(() => {
|
||||
if (isSaving) return;
|
||||
onChange(editForm(input, { useTls: !input.useTls }));
|
||||
}, [input, isSaving, onChange]);
|
||||
const handleTogglePasswordVisibility = useCallback(() => {
|
||||
setIsPasswordVisible((current) => !current);
|
||||
}, []);
|
||||
|
||||
const PasswordIcon = isPasswordVisible ? ThemedEyeOff : ThemedEye;
|
||||
|
||||
return (
|
||||
<>
|
||||
<View style={styles.portRow}>
|
||||
<View style={hostFieldStyle}>
|
||||
<Text style={styles.label}>{t("pairing.direct.fields.host")}</Text>
|
||||
@@ -435,9 +485,11 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
|
||||
testID="direct-host-input"
|
||||
nativeID="direct-host-input"
|
||||
accessibilityLabel={t("pairing.direct.fields.host")}
|
||||
initialValue={host}
|
||||
resetKey={`direct-host-${inputResetKey}`}
|
||||
onChangeText={setHost}
|
||||
initialValue={input.host}
|
||||
onChangeText={handleHostChange}
|
||||
onFocus={fieldEvents.onFocus}
|
||||
onBlur={fieldEvents.onBlur}
|
||||
autoFocus={fieldEvents.autoFocus}
|
||||
placeholder="localhost"
|
||||
style={styles.input}
|
||||
autoCapitalize="none"
|
||||
@@ -453,9 +505,10 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
|
||||
testID="direct-port-input"
|
||||
nativeID="direct-port-input"
|
||||
accessibilityLabel={t("pairing.direct.fields.port")}
|
||||
initialValue={port}
|
||||
resetKey={`direct-port-${inputResetKey}`}
|
||||
onChangeText={setPort}
|
||||
initialValue={input.port}
|
||||
onChangeText={handlePortChange}
|
||||
onFocus={fieldEvents.onFocus}
|
||||
onBlur={fieldEvents.onBlur}
|
||||
placeholder="6767"
|
||||
style={styles.input}
|
||||
autoCapitalize="none"
|
||||
@@ -463,7 +516,7 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
|
||||
keyboardType="number-pad"
|
||||
editable={!isSaving}
|
||||
returnKeyType="done"
|
||||
onSubmitEditing={handleSubmitEditing}
|
||||
onSubmitEditing={fieldEvents.onSubmit}
|
||||
/>
|
||||
</View>
|
||||
</View>
|
||||
@@ -475,11 +528,11 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
|
||||
accessibilityRole="checkbox"
|
||||
accessibilityLabel={t("pairing.direct.fields.useSsl")}
|
||||
accessibilityState={useTlsAccessibilityState}
|
||||
aria-checked={useTls}
|
||||
aria-checked={input.useTls}
|
||||
testID="direct-ssl-toggle"
|
||||
>
|
||||
<View style={checkboxStyle}>
|
||||
{useTls ? (
|
||||
{input.useTls ? (
|
||||
<View testID="direct-ssl-toggle-checked">
|
||||
<ThemedCheck size={14} />
|
||||
</View>
|
||||
@@ -495,9 +548,10 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
|
||||
testID="direct-password-input"
|
||||
nativeID="direct-password-input"
|
||||
accessibilityLabel={t("pairing.direct.fields.password")}
|
||||
initialValue={password}
|
||||
resetKey={`direct-password-${inputResetKey}`}
|
||||
onChangeText={setPassword}
|
||||
initialValue={input.password}
|
||||
onChangeText={handlePasswordChange}
|
||||
onFocus={fieldEvents.onFocus}
|
||||
onBlur={fieldEvents.onBlur}
|
||||
placeholder={t("pairing.direct.fields.optional")}
|
||||
style={passwordInputStyle}
|
||||
autoCapitalize="none"
|
||||
@@ -505,7 +559,7 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
|
||||
secureTextEntry={!isPasswordVisible}
|
||||
editable={!isSaving}
|
||||
returnKeyType="done"
|
||||
onSubmitEditing={handleSubmitEditing}
|
||||
onSubmitEditing={fieldEvents.onSubmit}
|
||||
/>
|
||||
<PressHighlight
|
||||
style={styles.iconButton}
|
||||
@@ -523,63 +577,80 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
|
||||
</PressHighlight>
|
||||
</View>
|
||||
</View>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function DirectUriFields({
|
||||
input,
|
||||
isSaving,
|
||||
fieldEvents,
|
||||
onChange,
|
||||
}: {
|
||||
input: DirectConnectionUri;
|
||||
isSaving: boolean;
|
||||
fieldEvents: FieldEvents;
|
||||
onChange: (next: DirectConnectionInput) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const handleUriChange = useCallback(
|
||||
(uri: string) => onChange(editUri(input, uri)),
|
||||
[input, onChange],
|
||||
);
|
||||
const handlePromptPasswordChange = useCallback(
|
||||
(password: string) => onChange(editPromptPassword(input, password)),
|
||||
[input, onChange],
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<View style={styles.field}>
|
||||
<PressHighlight
|
||||
style={styles.advancedToggle}
|
||||
onPress={handleToggleAdvanced}
|
||||
disabled={isSaving}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={
|
||||
isAdvancedOpen ? t("pairing.direct.advanced.hide") : t("pairing.direct.advanced.show")
|
||||
}
|
||||
testID="direct-host-advanced-toggle"
|
||||
>
|
||||
<AdvancedIcon size={16} />
|
||||
<Text style={styles.advancedText}>{t("pairing.direct.advanced.label")}</Text>
|
||||
</PressHighlight>
|
||||
{isAdvancedOpen ? (
|
||||
<Text style={styles.label}>{t("pairing.direct.fields.connectionUri")}</Text>
|
||||
<AdaptiveTextInput
|
||||
testID="direct-host-uri-input"
|
||||
nativeID="direct-host-uri-input"
|
||||
accessibilityLabel={t("pairing.direct.fields.connectionUri")}
|
||||
initialValue={input.uri}
|
||||
onChangeText={handleUriChange}
|
||||
onFocus={fieldEvents.onFocus}
|
||||
onBlur={fieldEvents.onBlur}
|
||||
autoFocus={fieldEvents.autoFocus}
|
||||
placeholder="tcp://localhost:6767?ssl=true"
|
||||
style={styles.input}
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
keyboardType="url"
|
||||
editable={!isSaving}
|
||||
returnKeyType="done"
|
||||
onSubmitEditing={fieldEvents.onSubmit}
|
||||
/>
|
||||
</View>
|
||||
|
||||
{input.prompt ? (
|
||||
<View style={styles.field}>
|
||||
<Text style={styles.label}>
|
||||
{t("pairing.hostPassword.title", { host: input.prompt.host })}
|
||||
</Text>
|
||||
<AdaptiveTextInput
|
||||
testID="direct-host-uri-input"
|
||||
nativeID="direct-host-uri-input"
|
||||
accessibilityLabel={t("pairing.direct.fields.connectionUri")}
|
||||
initialValue={advancedUri}
|
||||
resetKey={`direct-host-uri-${inputResetKey}`}
|
||||
onChangeText={handleChangeAdvancedUri}
|
||||
placeholder="tcp://localhost:6767?ssl=true"
|
||||
style={styles.input}
|
||||
testID="direct-uri-password-input"
|
||||
accessibilityLabel={t("pairing.hostPassword.label")}
|
||||
placeholder={t("pairing.hostPassword.label")}
|
||||
initialValue={input.prompt.password}
|
||||
onChangeText={handlePromptPasswordChange}
|
||||
onFocus={fieldEvents.onFocus}
|
||||
onBlur={fieldEvents.onBlur}
|
||||
autoFocus
|
||||
secureTextEntry
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
keyboardType="url"
|
||||
editable={!isSaving}
|
||||
returnKeyType="done"
|
||||
onSubmitEditing={handleToggleAdvanced}
|
||||
onSubmitEditing={fieldEvents.onSubmit}
|
||||
style={styles.input}
|
||||
/>
|
||||
) : null}
|
||||
{errorMessage ? <Text style={styles.error}>{errorMessage}</Text> : null}
|
||||
</View>
|
||||
|
||||
<View style={styles.actions}>
|
||||
<Button
|
||||
style={FLEX_ONE_STYLE}
|
||||
variant="secondary"
|
||||
onPress={handleCancel}
|
||||
disabled={isSaving}
|
||||
>
|
||||
{t("pairing.direct.actions.cancel")}
|
||||
</Button>
|
||||
<Button
|
||||
style={FLEX_ONE_STYLE}
|
||||
variant="default"
|
||||
onPress={handleSavePress}
|
||||
disabled={isSaving}
|
||||
leftIcon={connectIcon}
|
||||
testID="direct-host-submit"
|
||||
>
|
||||
{isSaving ? t("pairing.direct.actions.connecting") : t("pairing.direct.actions.connect")}
|
||||
</Button>
|
||||
</View>
|
||||
</AdaptiveModalSheet>
|
||||
</View>
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -587,14 +658,6 @@ const ThemedLink2 = withUnistyles(Link2, (theme) => ({ color: theme.colors.accen
|
||||
|
||||
const ThemedCheck = withUnistyles(Check, (theme) => ({ color: theme.colors.accentForeground }));
|
||||
|
||||
const ThemedChevronDown = withUnistyles(ChevronDown, (theme) => ({
|
||||
color: theme.colors.foregroundMuted,
|
||||
}));
|
||||
|
||||
const ThemedChevronRight = withUnistyles(ChevronRight, (theme) => ({
|
||||
color: theme.colors.foregroundMuted,
|
||||
}));
|
||||
|
||||
const ThemedEye = withUnistyles(Eye, (theme) => ({ color: theme.colors.foregroundMuted }));
|
||||
|
||||
const ThemedEyeOff = withUnistyles(EyeOff, (theme) => ({ color: theme.colors.foregroundMuted }));
|
||||
|
||||
@@ -0,0 +1,270 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
canSwitchToForm,
|
||||
editForm,
|
||||
editHost,
|
||||
editPromptPassword,
|
||||
editUri,
|
||||
openDirectConnection,
|
||||
promptForPassword,
|
||||
resolveConnection,
|
||||
switchMode,
|
||||
type DirectConnectionForm,
|
||||
type DirectConnectionInput,
|
||||
} from "./direct-connection";
|
||||
|
||||
const LABELS = { hostRequired: "Host is required", invalidPort: "Port is invalid" };
|
||||
const RELAY_LINK = "relay://relay.paseo.test:443/srv_abc?key=daemon-key&ssl=true";
|
||||
// The link `paseo daemon pair` prints first, next to the relay:// URI.
|
||||
const OFFER_LINK = `https://app.paseo.sh/#offer=${Buffer.from(
|
||||
JSON.stringify({
|
||||
v: 2,
|
||||
serverId: "srv_offer",
|
||||
daemonPublicKeyB64: "daemon-key",
|
||||
relay: { endpoint: "relay.paseo.test:443" },
|
||||
}),
|
||||
).toString("base64url")}`;
|
||||
|
||||
function form(fields: Partial<Omit<DirectConnectionForm, "mode">>): DirectConnectionInput {
|
||||
const { host = "", ...rest } = fields;
|
||||
return editForm(editHost(openDirectConnection(), host), rest);
|
||||
}
|
||||
|
||||
function uri(text: string): DirectConnectionInput {
|
||||
return editUri(switchMode(openDirectConnection(), "uri"), text);
|
||||
}
|
||||
|
||||
describe("opening Direct connection", () => {
|
||||
it("opens as an empty form on the default port", () => {
|
||||
expect(openDirectConnection()).toEqual({
|
||||
mode: "form",
|
||||
host: "",
|
||||
port: "6767",
|
||||
useTls: false,
|
||||
password: "",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("switching from Form to URI", () => {
|
||||
it("leaves the URI empty when Host is empty", () => {
|
||||
expect(switchMode(openDirectConnection(), "uri")).toEqual({
|
||||
mode: "uri",
|
||||
uri: "",
|
||||
prompt: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("carries host, port, SSL and password into the URI", () => {
|
||||
const input = form({ host: "192.168.1.20", port: "6767", useTls: true, password: "pw" });
|
||||
expect(switchMode(input, "uri")).toMatchObject({
|
||||
uri: "tcp://192.168.1.20:6767?ssl=true&password=pw",
|
||||
});
|
||||
});
|
||||
|
||||
it("normalizes a pasted host:port or URL in Host", () => {
|
||||
expect(switchMode(form({ host: "myhost:7000" }), "uri")).toMatchObject({
|
||||
uri: "tcp://myhost:7000",
|
||||
});
|
||||
expect(switchMode(form({ host: "http://myhost:7000/" }), "uri")).toMatchObject({
|
||||
uri: "tcp://myhost:7000",
|
||||
});
|
||||
});
|
||||
|
||||
it("brackets an IPv6 host", () => {
|
||||
expect(switchMode(form({ host: "::1", port: "7000" }), "uri")).toMatchObject({
|
||||
uri: "tcp://[::1]:7000",
|
||||
});
|
||||
});
|
||||
|
||||
it("encodes a password with reserved characters", () => {
|
||||
const input = form({ host: "h", password: "a&b=c d" });
|
||||
const switched = switchMode(input, "uri");
|
||||
expect(switched).toMatchObject({ uri: "tcp://h:6767?password=a%26b%3Dc+d" });
|
||||
expect(switchMode(switched, "form")).toMatchObject({ password: "a&b=c d" });
|
||||
});
|
||||
|
||||
it("keeps an invalid port as text so Connect reports it", () => {
|
||||
expect(switchMode(form({ host: "host", port: "abc" }), "uri")).toMatchObject({
|
||||
uri: "tcp://host:abc",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("switching from URI to Form", () => {
|
||||
it("opens the default form when the URI is empty", () => {
|
||||
expect(switchMode(uri(""), "form")).toEqual(openDirectConnection());
|
||||
});
|
||||
|
||||
it("fills the fields from a valid URI", () => {
|
||||
expect(switchMode(uri("tcp://h:7443?ssl=true&password=x"), "form")).toEqual({
|
||||
mode: "form",
|
||||
host: "h",
|
||||
port: "7443",
|
||||
useTls: true,
|
||||
password: "x",
|
||||
});
|
||||
});
|
||||
|
||||
it("parses a partial URI leniently", () => {
|
||||
expect(switchMode(uri("tcp://myhost"), "form")).toMatchObject({
|
||||
host: "myhost",
|
||||
port: "6767",
|
||||
});
|
||||
expect(switchMode(uri("myhost:70"), "form")).toMatchObject({ host: "myhost", port: "70" });
|
||||
expect(switchMode(uri("tcp://h:6767?pass"), "form")).toEqual({
|
||||
mode: "form",
|
||||
host: "h",
|
||||
port: "6767",
|
||||
useTls: false,
|
||||
password: "",
|
||||
});
|
||||
expect(switchMode(uri("tcp://host:abc"), "form")).toMatchObject({
|
||||
host: "host",
|
||||
port: "abc",
|
||||
});
|
||||
expect(switchMode(uri("tcp://[::1]:7000?ssl=true"), "form")).toMatchObject({
|
||||
host: "::1",
|
||||
port: "7000",
|
||||
useTls: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("round-trips any form with a host", () => {
|
||||
const forms = [
|
||||
form({ host: "example.paseo.test", port: "7443", useTls: true, password: "secret" }),
|
||||
form({ host: "::1", port: "7000" }),
|
||||
form({ host: "h", port: "abc" }),
|
||||
];
|
||||
for (const input of forms) {
|
||||
expect(switchMode(switchMode(input, "uri"), "form")).toEqual(input);
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps a pairing link in URI mode", () => {
|
||||
const relay = uri(RELAY_LINK);
|
||||
expect(canSwitchToForm(relay)).toBe(false);
|
||||
expect(switchMode(relay, "form")).toBe(relay);
|
||||
expect(canSwitchToForm(uri("https://app.paseo.sh/#connect=abc"))).toBe(false);
|
||||
expect(canSwitchToForm(uri(OFFER_LINK))).toBe(false);
|
||||
expect(canSwitchToForm(uri("tcp://h:1"))).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("typing in Host", () => {
|
||||
it("keeps host:port and URL shapes in Host", () => {
|
||||
for (const text of ["host:7000", "http://host:7000/", "[::1]:7000"]) {
|
||||
expect(editHost(openDirectConnection(), text)).toMatchObject({ mode: "form", host: text });
|
||||
}
|
||||
});
|
||||
|
||||
it("moves a typed or pasted URI to URI mode", () => {
|
||||
expect(editHost(openDirectConnection(), "tcp://h:7000?password=x")).toEqual({
|
||||
mode: "uri",
|
||||
uri: "tcp://h:7000?password=x",
|
||||
prompt: null,
|
||||
});
|
||||
expect(editHost(openDirectConnection(), RELAY_LINK)).toMatchObject({
|
||||
mode: "uri",
|
||||
uri: RELAY_LINK,
|
||||
});
|
||||
expect(editHost(openDirectConnection(), "https://app.paseo.sh/#connect=abc")).toMatchObject({
|
||||
mode: "uri",
|
||||
});
|
||||
expect(editHost(openDirectConnection(), OFFER_LINK)).toEqual({
|
||||
mode: "uri",
|
||||
uri: OFFER_LINK,
|
||||
prompt: null,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("password prompt", () => {
|
||||
it("asks for the host's password and keeps it while the target stays the same", () => {
|
||||
const prompted = editPromptPassword(promptForPassword(uri("tcp://h:7000")), "pw");
|
||||
expect(prompted).toMatchObject({ prompt: { host: "h:7000", password: "pw" } });
|
||||
expect(editUri(prompted, "tcp://h:7000?ssl=true")).toMatchObject({
|
||||
prompt: { host: "h:7000", password: "pw" },
|
||||
});
|
||||
expect(editUri(prompted, "tcp://h:70")).toMatchObject({ prompt: null });
|
||||
});
|
||||
|
||||
it("keeps the prompt while the URI is incomplete", () => {
|
||||
const prompted = promptForPassword(uri("tcp://h:7000"));
|
||||
expect(editUri(prompted, "tcp://")).toMatchObject({ prompt: { host: "h:7000" } });
|
||||
});
|
||||
|
||||
it("names a relay host by its server id", () => {
|
||||
expect(promptForPassword(uri(RELAY_LINK))).toMatchObject({ prompt: { host: "srv_abc" } });
|
||||
expect(promptForPassword(uri(OFFER_LINK))).toMatchObject({ prompt: { host: "srv_offer" } });
|
||||
});
|
||||
|
||||
it("keeps a typed password when the host asks again", () => {
|
||||
const prompted = editPromptPassword(promptForPassword(uri("tcp://h:7000")), "wrong");
|
||||
expect(promptForPassword(prompted)).toBe(prompted);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolving the connection", () => {
|
||||
it("connects to the form fields in Form mode", () => {
|
||||
expect(
|
||||
resolveConnection(form({ host: "h", port: "7000", useTls: true, password: "pw" }), LABELS),
|
||||
).toEqual({
|
||||
kind: "direct",
|
||||
uri: "tcp://h:7000?ssl=true",
|
||||
endpoint: "h:7000",
|
||||
useTls: true,
|
||||
password: "pw",
|
||||
});
|
||||
});
|
||||
|
||||
it("reports form validation errors", () => {
|
||||
expect(() => resolveConnection(openDirectConnection(), LABELS)).toThrow("Host is required");
|
||||
expect(() => resolveConnection(form({ host: "h", port: "abc" }), LABELS)).toThrow(
|
||||
"Port is invalid",
|
||||
);
|
||||
});
|
||||
|
||||
it("connects to the URI in URI mode", () => {
|
||||
expect(resolveConnection(uri("tcp://127.0.0.1:7000?password=pw"), LABELS)).toEqual({
|
||||
kind: "direct",
|
||||
uri: "tcp://127.0.0.1:7000",
|
||||
endpoint: "127.0.0.1:7000",
|
||||
useTls: false,
|
||||
password: "pw",
|
||||
});
|
||||
expect(resolveConnection(uri("tcp://[::1]:7000"), LABELS)).toMatchObject({
|
||||
endpoint: "[::1]:7000",
|
||||
});
|
||||
});
|
||||
|
||||
it("prefers the prompt password over the URI password", () => {
|
||||
const input = editPromptPassword(promptForPassword(uri("tcp://h:7000?password=old")), "new");
|
||||
expect(resolveConnection(input, LABELS)).toMatchObject({ password: "new" });
|
||||
});
|
||||
|
||||
it("reports an invalid URI", () => {
|
||||
expect(() => resolveConnection(uri("tcp://host:abc"), LABELS)).toThrow();
|
||||
expect(() => resolveConnection(uri("tls://h:7000"), LABELS)).toThrow(
|
||||
"Connection URI protocol must be tcp:",
|
||||
);
|
||||
expect(() => resolveConnection(uri(""), LABELS)).toThrow("Connection URI is required");
|
||||
});
|
||||
|
||||
it("pairs through an offer link", () => {
|
||||
expect(resolveConnection(uri(OFFER_LINK), LABELS)).toEqual({ kind: "relay", link: OFFER_LINK });
|
||||
});
|
||||
|
||||
it("pairs through a relay link with the prompt password", () => {
|
||||
expect(resolveConnection(uri(` ${RELAY_LINK} `), LABELS)).toEqual({
|
||||
kind: "relay",
|
||||
link: RELAY_LINK,
|
||||
});
|
||||
const prompted = editPromptPassword(promptForPassword(uri(RELAY_LINK)), "pw");
|
||||
expect(resolveConnection(prompted, LABELS)).toEqual({
|
||||
kind: "relay",
|
||||
link: RELAY_LINK,
|
||||
password: "pw",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,208 @@
|
||||
import {
|
||||
buildDirectConnectionUri,
|
||||
normalizeDirectConnectionHost,
|
||||
type DirectConnectionHostLabels,
|
||||
} from "@/components/direct-connection-host";
|
||||
import { parseConnectionOfferFromUrl } from "@getpaseo/protocol/connection-offer";
|
||||
import {
|
||||
parseConnectionUri,
|
||||
parseRelayConnectionUri,
|
||||
serializeConnectionUri,
|
||||
} from "@/utils/daemon-endpoints";
|
||||
|
||||
/**
|
||||
* What the Direct connection step holds. The mode is the input: a hidden mode keeps no values,
|
||||
* so Connect can only read what the user sees.
|
||||
*/
|
||||
export type DirectConnectionInput = DirectConnectionForm | DirectConnectionUri;
|
||||
|
||||
export type DirectConnectionMode = DirectConnectionInput["mode"];
|
||||
|
||||
export interface DirectConnectionForm {
|
||||
mode: "form";
|
||||
host: string;
|
||||
port: string;
|
||||
useTls: boolean;
|
||||
password: string;
|
||||
}
|
||||
|
||||
export interface DirectConnectionUri {
|
||||
mode: "uri";
|
||||
uri: string;
|
||||
/** The password a host asked for after Connect. Null until a host rejects the connection. */
|
||||
prompt: { host: string; password: string } | null;
|
||||
}
|
||||
|
||||
export type ResolvedDirectConnection =
|
||||
| { kind: "direct"; uri: string; endpoint: string; useTls: boolean; password?: string }
|
||||
| { kind: "relay"; link: string; password?: string };
|
||||
|
||||
const DEFAULT_PORT = "6767";
|
||||
const TCP_URI_PATTERN = /^tcp:\/\//i;
|
||||
|
||||
export function openDirectConnection(): DirectConnectionForm {
|
||||
return { mode: "form", host: "", port: DEFAULT_PORT, useTls: false, password: "" };
|
||||
}
|
||||
|
||||
/** Converts the input to the other mode. A pairing link stays a URI; see `canSwitchToForm`. */
|
||||
export function switchMode(
|
||||
input: DirectConnectionInput,
|
||||
mode: DirectConnectionMode,
|
||||
): DirectConnectionInput {
|
||||
if (input.mode === mode) return input;
|
||||
if (input.mode === "form") return { mode: "uri", uri: formToUri(input), prompt: null };
|
||||
if (!canSwitchToForm(input)) return input;
|
||||
return uriToForm(input.uri);
|
||||
}
|
||||
|
||||
export function canSwitchToForm(input: DirectConnectionInput): boolean {
|
||||
return input.mode === "form" || !isPairingLink(input.uri);
|
||||
}
|
||||
|
||||
export function editForm(
|
||||
input: DirectConnectionInput,
|
||||
fields: Partial<Omit<DirectConnectionForm, "mode" | "host">>,
|
||||
): DirectConnectionInput {
|
||||
if (input.mode !== "form") return input;
|
||||
return { ...input, ...fields };
|
||||
}
|
||||
|
||||
/** A URI typed or pasted into Host moves to URI mode, where its query and pairing data count. */
|
||||
export function editHost(input: DirectConnectionInput, text: string): DirectConnectionInput {
|
||||
if (input.mode !== "form") return input;
|
||||
if (looksLikeUri(text)) return { mode: "uri", uri: text.trim(), prompt: null };
|
||||
return { ...input, host: text };
|
||||
}
|
||||
|
||||
/** Editing the URI to point at another host drops the password typed for the previous one. */
|
||||
export function editUri(input: DirectConnectionInput, text: string): DirectConnectionInput {
|
||||
if (input.mode !== "uri") return input;
|
||||
const target = uriHostLabel(text);
|
||||
const prompt = input.prompt && target && target !== input.prompt.host ? null : input.prompt;
|
||||
return { mode: "uri", uri: text, prompt };
|
||||
}
|
||||
|
||||
export function promptForPassword(input: DirectConnectionInput): DirectConnectionInput {
|
||||
if (input.mode !== "uri" || input.prompt) return input;
|
||||
return { ...input, prompt: { host: uriHostLabel(input.uri) ?? "host", password: "" } };
|
||||
}
|
||||
|
||||
export function editPromptPassword(
|
||||
input: DirectConnectionInput,
|
||||
password: string,
|
||||
): DirectConnectionInput {
|
||||
if (input.mode !== "uri" || !input.prompt) return input;
|
||||
return { ...input, prompt: { ...input.prompt, password } };
|
||||
}
|
||||
|
||||
/** What Connect dials. Throws the validation error to show when the input cannot connect. */
|
||||
export function resolveConnection(
|
||||
input: DirectConnectionInput,
|
||||
labels: DirectConnectionHostLabels,
|
||||
): ResolvedDirectConnection {
|
||||
if (input.mode === "form") {
|
||||
return resolveTcpUri(buildDirectConnectionUri(input, labels));
|
||||
}
|
||||
const uri = input.uri.trim();
|
||||
const promptPassword = input.prompt?.password || undefined;
|
||||
if (isPairingLink(uri)) {
|
||||
return { kind: "relay", link: uri, ...(promptPassword ? { password: promptPassword } : {}) };
|
||||
}
|
||||
return resolveTcpUri(uri, promptPassword);
|
||||
}
|
||||
|
||||
function resolveTcpUri(uri: string, passwordOverride?: string): ResolvedDirectConnection {
|
||||
const parsed = parseConnectionUri(uri);
|
||||
const password = passwordOverride ?? parsed.password;
|
||||
return {
|
||||
kind: "direct",
|
||||
uri: serializeConnectionUri(parsed),
|
||||
endpoint: parsed.isIpv6 ? `[${parsed.host}]:${parsed.port}` : `${parsed.host}:${parsed.port}`,
|
||||
useTls: parsed.useTls,
|
||||
...(password ? { password } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/** The three link formats a daemon prints for pairing: `relay://`, `#connect=`, and `#offer=`. */
|
||||
function isPairingLink(uri: string): boolean {
|
||||
const trimmed = uri.trim();
|
||||
return (
|
||||
trimmed.toLowerCase().startsWith("relay://") ||
|
||||
trimmed.includes("#connect=") ||
|
||||
trimmed.includes("#offer=")
|
||||
);
|
||||
}
|
||||
|
||||
function looksLikeUri(text: string): boolean {
|
||||
return TCP_URI_PATTERN.test(text.trim()) || isPairingLink(text);
|
||||
}
|
||||
|
||||
// Built as text, not through the strict serializer, so an invalid port carries over and Connect
|
||||
// reports it instead of the switch failing.
|
||||
function formToUri(input: DirectConnectionForm): string {
|
||||
const normalized = normalizeDirectConnectionHost(input.host);
|
||||
if (!normalized.host) return "";
|
||||
const host = normalized.isIpv6 ? `[${normalized.host}]` : normalized.host;
|
||||
const port = normalized.port ?? input.port.trim();
|
||||
const query = new URLSearchParams();
|
||||
if (input.useTls) query.set("ssl", "true");
|
||||
if (input.password) query.set("password", input.password);
|
||||
const search = query.toString();
|
||||
return `tcp://${host}:${port}${search ? `?${search}` : ""}`;
|
||||
}
|
||||
|
||||
function uriToForm(uri: string): DirectConnectionForm {
|
||||
const address = splitUri(uri);
|
||||
if (!address.host) return openDirectConnection();
|
||||
return {
|
||||
mode: "form",
|
||||
host: address.host,
|
||||
port: address.port ?? DEFAULT_PORT,
|
||||
useTls: address.query.get("ssl") === "true",
|
||||
password: address.query.get("password") ?? "",
|
||||
};
|
||||
}
|
||||
|
||||
function uriHostLabel(uri: string): string | null {
|
||||
const trimmed = uri.trim();
|
||||
if (isPairingLink(trimmed)) {
|
||||
try {
|
||||
return trimmed.includes("#offer=")
|
||||
? (parseConnectionOfferFromUrl(trimmed)?.serverId ?? null)
|
||||
: parseRelayConnectionUri(trimmed).offer.serverId;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
const address = splitUri(trimmed);
|
||||
if (!address.host || !address.port) return null;
|
||||
return address.isIpv6 ? `[${address.host}]:${address.port}` : `${address.host}:${address.port}`;
|
||||
}
|
||||
|
||||
const SCHEME_PATTERN = /^[a-z][a-z0-9+.-]*:\/\//i;
|
||||
const BRACKETED_IPV6_PATTERN = /^\[([^\]]*)\](?::(.*))?$/;
|
||||
|
||||
/** Lenient split of a typed URI. Keeps an invalid port as text instead of rejecting it. */
|
||||
function splitUri(uri: string): {
|
||||
host: string;
|
||||
port: string | null;
|
||||
isIpv6: boolean;
|
||||
query: URLSearchParams;
|
||||
} {
|
||||
const rest = uri.trim().replace(SCHEME_PATTERN, "");
|
||||
const queryIndex = rest.indexOf("?");
|
||||
const query = new URLSearchParams(
|
||||
queryIndex === -1 ? "" : rest.slice(queryIndex + 1).split("#")[0],
|
||||
);
|
||||
const authority = rest.split(/[/?#]/)[0] ?? "";
|
||||
|
||||
const bracketed = BRACKETED_IPV6_PATTERN.exec(authority);
|
||||
if (bracketed) {
|
||||
return { host: bracketed[1] ?? "", port: bracketed[2] || null, isIpv6: true, query };
|
||||
}
|
||||
const parts = authority.split(":");
|
||||
if (parts.length === 2) {
|
||||
return { host: parts[0] ?? "", port: parts[1] || null, isIpv6: false, query };
|
||||
}
|
||||
return { host: authority, port: null, isIpv6: parts.length > 2, query };
|
||||
}
|
||||
@@ -205,6 +205,10 @@ export const ar: TranslationResources = {
|
||||
pasteImageFailed: "تعذر لصق الصورة",
|
||||
fileTooLarge: "{{fileName}} is too large (max {{size}})",
|
||||
},
|
||||
providerSwitch: {
|
||||
switchingNextMessage: "التبديل إلى {{provider}} في الرسالة التالية",
|
||||
switchingAfterTurn: "سيتم التبديل إلى {{provider}} بعد هذا الدور",
|
||||
},
|
||||
clientCommands: {
|
||||
archiveAgent: "أرشفة الوكيل الحالي",
|
||||
freshDraft: "أرشفة هذا الوكيل وابدأ مسودة جديدة",
|
||||
@@ -442,6 +446,13 @@ export const ar: TranslationResources = {
|
||||
turnFooter: {
|
||||
workedFor: "عمل لمدة {{duration}}",
|
||||
},
|
||||
providerSwitch: {
|
||||
switched: "تم التبديل من {{from}} إلى {{to}}",
|
||||
contextSummary: "تم نقل {{count}} عنصر ({{chars}} / {{budget}} حرف)",
|
||||
trimmed: "تم الاقتطاع: {{reasons}}",
|
||||
reasonTailWindow: "سجل أقدم خارج النطاق",
|
||||
reasonCharBudget: "حد الأحرف",
|
||||
},
|
||||
compaction: {
|
||||
loading: "الضغط...",
|
||||
auto: "يتم ضغط السياق تلقائيًا",
|
||||
@@ -783,6 +794,8 @@ export const ar: TranslationResources = {
|
||||
resumeCommandUnavailable: "أمر الاستئناف غير متوفر",
|
||||
reloadingAgent: "وكيل إعادة التحميل...",
|
||||
reloadedAgent: "وكيل إعادة تحميل",
|
||||
reloadedAgentHistoryDiverged:
|
||||
"تمت إعادة تحميل الوكيل، لكن سجل المزوّد لا يطابق هذه المحادثة، لذا لم تتم مزامنته",
|
||||
failedToReloadAgent: "فشل في إعادة تحميل الوكيل",
|
||||
failedToCloseAgent: "فشل في إغلاق الوكيل",
|
||||
},
|
||||
@@ -1997,7 +2010,6 @@ export const ar: TranslationResources = {
|
||||
},
|
||||
direct: {
|
||||
title: "اتصال مباشر",
|
||||
helper: "أدخل عنوان خادم Paseo.",
|
||||
fields: {
|
||||
host: "Host",
|
||||
port: "ميناء",
|
||||
@@ -2006,10 +2018,10 @@ export const ar: TranslationResources = {
|
||||
useSsl: "استخدم طبقة المقابس الآمنة",
|
||||
connectionUri: "معرف URI للاتصال",
|
||||
},
|
||||
advanced: {
|
||||
label: "متقدم",
|
||||
show: "عرض متقدم",
|
||||
hide: "إخفاء المتقدمة",
|
||||
modes: {
|
||||
form: "نموذج",
|
||||
uri: "URI",
|
||||
uriOnlyLink: "روابط الاقتران تعمل كـ URI فقط",
|
||||
},
|
||||
passwordVisibility: {
|
||||
show: "إظهار كلمة المرور",
|
||||
|
||||
@@ -203,6 +203,10 @@ export const en = {
|
||||
pasteImageFailed: "Failed to paste image",
|
||||
fileTooLarge: "{{fileName}} is too large (max {{size}})",
|
||||
},
|
||||
providerSwitch: {
|
||||
switchingNextMessage: "Switching to {{provider}} on next message",
|
||||
switchingAfterTurn: "Will switch to {{provider}} after this turn",
|
||||
},
|
||||
clientCommands: {
|
||||
archiveAgent: "Archive the current agent",
|
||||
freshDraft: "Archive this agent and start a fresh draft",
|
||||
@@ -441,6 +445,13 @@ export const en = {
|
||||
turnFooter: {
|
||||
workedFor: "Worked for {{duration}}",
|
||||
},
|
||||
providerSwitch: {
|
||||
switched: "Switched from {{from}} to {{to}}",
|
||||
contextSummary: "{{count}} items transferred ({{chars}} / {{budget}} chars)",
|
||||
trimmed: "Trimmed: {{reasons}}",
|
||||
reasonTailWindow: "older history beyond window",
|
||||
reasonCharBudget: "character budget",
|
||||
},
|
||||
compaction: {
|
||||
loading: "Compacting...",
|
||||
auto: "Context automatically compacted",
|
||||
@@ -782,6 +793,8 @@ export const en = {
|
||||
resumeCommandUnavailable: "Resume command not available",
|
||||
reloadingAgent: "Reloading agent...",
|
||||
reloadedAgent: "Reloaded agent",
|
||||
reloadedAgentHistoryDiverged:
|
||||
"Reloaded agent, but the provider's history doesn't match this chat, so it wasn't synced",
|
||||
failedToReloadAgent: "Failed to reload agent",
|
||||
failedToCloseAgent: "Failed to close agent",
|
||||
},
|
||||
@@ -2027,7 +2040,6 @@ export const en = {
|
||||
},
|
||||
direct: {
|
||||
title: "Direct connection",
|
||||
helper: "Enter the address of a Paseo server.",
|
||||
fields: {
|
||||
host: "Host",
|
||||
port: "Port",
|
||||
@@ -2036,10 +2048,10 @@ export const en = {
|
||||
useSsl: "Use SSL",
|
||||
connectionUri: "Connection URI",
|
||||
},
|
||||
advanced: {
|
||||
label: "Advanced",
|
||||
show: "Show advanced",
|
||||
hide: "Hide advanced",
|
||||
modes: {
|
||||
form: "Form",
|
||||
uri: "URI",
|
||||
uriOnlyLink: "Pairing links only work as a URI",
|
||||
},
|
||||
passwordVisibility: {
|
||||
show: "Show password",
|
||||
|
||||
@@ -207,6 +207,10 @@ export const es: TranslationResources = {
|
||||
pasteImageFailed: "No se pudo pegar la imagen",
|
||||
fileTooLarge: "{{fileName}} is too large (max {{size}})",
|
||||
},
|
||||
providerSwitch: {
|
||||
switchingNextMessage: "Cambiando a {{provider}} en el próximo mensaje",
|
||||
switchingAfterTurn: "Se cambiará a {{provider}} después de este turno",
|
||||
},
|
||||
clientCommands: {
|
||||
archiveAgent: "Archivar el agente actual",
|
||||
freshDraft: "Archive este agente y comience un nuevo borrador",
|
||||
@@ -447,6 +451,13 @@ export const es: TranslationResources = {
|
||||
turnFooter: {
|
||||
workedFor: "Trabajó durante {{duration}}",
|
||||
},
|
||||
providerSwitch: {
|
||||
switched: "Cambiado de {{from}} a {{to}}",
|
||||
contextSummary: "{{count}} elementos transferidos ({{chars}} / {{budget}} caracteres)",
|
||||
trimmed: "Recortado: {{reasons}}",
|
||||
reasonTailWindow: "historial anterior fuera de la ventana",
|
||||
reasonCharBudget: "límite de caracteres",
|
||||
},
|
||||
compaction: {
|
||||
loading: "Compactando...",
|
||||
auto: "Contexto compactado automáticamente",
|
||||
@@ -790,6 +801,8 @@ export const es: TranslationResources = {
|
||||
resumeCommandUnavailable: "Comando de reanudación no disponible",
|
||||
reloadingAgent: "Agente de recarga...",
|
||||
reloadedAgent: "Agente recargado",
|
||||
reloadedAgentHistoryDiverged:
|
||||
"Agente recargado, pero el historial del proveedor no coincide con este chat, así que no se sincronizó",
|
||||
failedToReloadAgent: "No se pudo recargar el agente",
|
||||
failedToCloseAgent: "No se pudo cerrar el agente",
|
||||
},
|
||||
@@ -2051,7 +2064,6 @@ export const es: TranslationResources = {
|
||||
},
|
||||
direct: {
|
||||
title: "Conexión directa",
|
||||
helper: "Ingrese la dirección de un servidorPaseo.",
|
||||
fields: {
|
||||
host: "Host",
|
||||
port: "Puerto",
|
||||
@@ -2060,10 +2072,10 @@ export const es: TranslationResources = {
|
||||
useSsl: "Usar SSL",
|
||||
connectionUri: "URI de conexión",
|
||||
},
|
||||
advanced: {
|
||||
label: "Avanzado",
|
||||
show: "Mostrar avanzado",
|
||||
hide: "Ocultar avanzado",
|
||||
modes: {
|
||||
form: "Formulario",
|
||||
uri: "URI",
|
||||
uriOnlyLink: "Los enlaces de emparejamiento solo funcionan como URI",
|
||||
},
|
||||
passwordVisibility: {
|
||||
show: "Mostrar contraseña",
|
||||
|
||||
@@ -208,6 +208,10 @@ export const fr: TranslationResources = {
|
||||
pasteImageFailed: "Impossible de coller l’image",
|
||||
fileTooLarge: "{{fileName}} est trop volumineux (maximum {{size}})",
|
||||
},
|
||||
providerSwitch: {
|
||||
switchingNextMessage: "Passage à {{provider}} au prochain message",
|
||||
switchingAfterTurn: "Passage à {{provider}} après ce tour",
|
||||
},
|
||||
clientCommands: {
|
||||
archiveAgent: "Archiver l’agent actuel",
|
||||
freshDraft: "Archiver cet agent et démarrer un nouveau brouillon",
|
||||
@@ -447,6 +451,13 @@ export const fr: TranslationResources = {
|
||||
turnFooter: {
|
||||
workedFor: "A travaillé pendant {{duration}}",
|
||||
},
|
||||
providerSwitch: {
|
||||
switched: "Passé de {{from}} à {{to}}",
|
||||
contextSummary: "{{count}} éléments transférés ({{chars}} / {{budget}} caractères)",
|
||||
trimmed: "Tronqué : {{reasons}}",
|
||||
reasonTailWindow: "historique antérieur hors fenêtre",
|
||||
reasonCharBudget: "limite de caractères",
|
||||
},
|
||||
compaction: {
|
||||
loading: "Compaction…",
|
||||
auto: "Contexte compacté automatiquement",
|
||||
@@ -790,6 +801,8 @@ export const fr: TranslationResources = {
|
||||
resumeCommandUnavailable: "Commande de reprise indisponible",
|
||||
reloadingAgent: "Rechargement de l’agent…",
|
||||
reloadedAgent: "Agent rechargé",
|
||||
reloadedAgentHistoryDiverged:
|
||||
"Agent rechargé, mais l’historique du fournisseur ne correspond pas à cette conversation, il n’a donc pas été synchronisé",
|
||||
failedToReloadAgent: "Impossible de recharger l’agent",
|
||||
failedToCloseAgent: "Impossible de fermer l’agent",
|
||||
},
|
||||
@@ -2048,7 +2061,6 @@ export const fr: TranslationResources = {
|
||||
},
|
||||
direct: {
|
||||
title: "Connexion directe",
|
||||
helper: "Saisissez l’adresse d’un serveur Paseo.",
|
||||
fields: {
|
||||
host: "Hôte",
|
||||
port: "Port",
|
||||
@@ -2057,10 +2069,10 @@ export const fr: TranslationResources = {
|
||||
useSsl: "Utiliser SSL",
|
||||
connectionUri: "URI de connexion",
|
||||
},
|
||||
advanced: {
|
||||
label: "Options avancées",
|
||||
show: "Afficher les options avancées",
|
||||
hide: "Masquer les options avancées",
|
||||
modes: {
|
||||
form: "Formulaire",
|
||||
uri: "URI",
|
||||
uriOnlyLink: "Les liens d’association ne fonctionnent qu’en URI",
|
||||
},
|
||||
passwordVisibility: {
|
||||
show: "Afficher le mot de passe",
|
||||
|
||||
@@ -207,6 +207,10 @@ export const ja: TranslationResources = {
|
||||
pasteImageFailed: "画像を貼り付けられませんでした",
|
||||
fileTooLarge: "{{fileName}}が大きすぎます(最大{{size}})",
|
||||
},
|
||||
providerSwitch: {
|
||||
switchingNextMessage: "次のメッセージで {{provider}} に切り替えます",
|
||||
switchingAfterTurn: "このターン終了後に {{provider}} に切り替えます",
|
||||
},
|
||||
clientCommands: {
|
||||
archiveAgent: "現在のエージェントをアーカイブ",
|
||||
freshDraft: "このエージェントをアーカイブして新しい下書きを開始",
|
||||
@@ -447,6 +451,13 @@ export const ja: TranslationResources = {
|
||||
turnFooter: {
|
||||
workedFor: "作業時間 {{duration}}",
|
||||
},
|
||||
providerSwitch: {
|
||||
switched: "{{from}} から {{to}} に切り替えました",
|
||||
contextSummary: "{{count}} 件を引き継ぎました ({{chars}} / {{budget}} 文字)",
|
||||
trimmed: "省略: {{reasons}}",
|
||||
reasonTailWindow: "ウィンドウ外の古い履歴",
|
||||
reasonCharBudget: "文字数上限",
|
||||
},
|
||||
compaction: {
|
||||
loading: "コンテキストを圧縮中...",
|
||||
auto: "コンテキストが自動的に圧縮されました",
|
||||
@@ -790,6 +801,8 @@ export const ja: TranslationResources = {
|
||||
resumeCommandUnavailable: "再開コマンドが利用できません",
|
||||
reloadingAgent: "エージェントを再読み込み中...",
|
||||
reloadedAgent: "エージェントを再読み込みしました",
|
||||
reloadedAgentHistoryDiverged:
|
||||
"エージェントを再読み込みしましたが、プロバイダーの履歴がこのチャットと一致しないため同期しませんでした",
|
||||
failedToReloadAgent: "エージェントの再読み込みに失敗しました",
|
||||
failedToCloseAgent: "エージェントを閉じられませんでした",
|
||||
},
|
||||
@@ -2018,7 +2031,6 @@ export const ja: TranslationResources = {
|
||||
},
|
||||
direct: {
|
||||
title: "直接接続",
|
||||
helper: "Paseoサーバーのアドレスを入力してください。",
|
||||
fields: {
|
||||
host: "ホスト",
|
||||
port: "ポート",
|
||||
@@ -2027,10 +2039,10 @@ export const ja: TranslationResources = {
|
||||
useSsl: "SSLを使用",
|
||||
connectionUri: "接続URI",
|
||||
},
|
||||
advanced: {
|
||||
label: "詳細設定",
|
||||
show: "詳細設定を表示",
|
||||
hide: "詳細設定を非表示",
|
||||
modes: {
|
||||
form: "フォーム",
|
||||
uri: "URI",
|
||||
uriOnlyLink: "ペアリングリンクはURIでのみ使用できます",
|
||||
},
|
||||
passwordVisibility: {
|
||||
show: "パスワードを表示",
|
||||
|
||||
@@ -205,6 +205,10 @@ export const ko: TranslationResources = {
|
||||
pasteImageFailed: "이미지를 붙여넣지 못했습니다.",
|
||||
fileTooLarge: "{{fileName}}이(가) 너무 큽니다 (최대 {{size}})",
|
||||
},
|
||||
providerSwitch: {
|
||||
switchingNextMessage: "다음 메시지에서 {{provider}}(으)로 전환합니다",
|
||||
switchingAfterTurn: "이 턴이 끝난 후 {{provider}}(으)로 전환합니다",
|
||||
},
|
||||
clientCommands: {
|
||||
archiveAgent: "현재 에이전트 보관",
|
||||
freshDraft: "이 에이전트를 보관하고 새 초안을 시작합니다",
|
||||
@@ -443,6 +447,13 @@ export const ko: TranslationResources = {
|
||||
turnFooter: {
|
||||
workedFor: "작업 시간 {{duration}}",
|
||||
},
|
||||
providerSwitch: {
|
||||
switched: "{{from}}에서 {{to}}(으)로 전환됨",
|
||||
contextSummary: "{{count}}개 항목 전달됨 ({{chars}} / {{budget}}자)",
|
||||
trimmed: "생략됨: {{reasons}}",
|
||||
reasonTailWindow: "창 범위를 벗어난 이전 기록",
|
||||
reasonCharBudget: "문자 수 제한",
|
||||
},
|
||||
compaction: {
|
||||
loading: "압축하는 중...",
|
||||
auto: "컨텍스트가 자동으로 압축되었습니다",
|
||||
@@ -785,6 +796,8 @@ export const ko: TranslationResources = {
|
||||
resumeCommandUnavailable: "재개 명령을 사용할 수 없습니다",
|
||||
reloadingAgent: "에이전트 다시 로드 중...",
|
||||
reloadedAgent: "에이전트를 다시 로드했습니다",
|
||||
reloadedAgentHistoryDiverged:
|
||||
"에이전트를 다시 로드했지만 제공자 기록이 이 채팅과 일치하지 않아 동기화하지 않았습니다",
|
||||
failedToReloadAgent: "에이전트를 다시 로드하지 못했습니다",
|
||||
failedToCloseAgent: "에이전트를 닫지 못했습니다",
|
||||
},
|
||||
@@ -2009,7 +2022,6 @@ export const ko: TranslationResources = {
|
||||
},
|
||||
direct: {
|
||||
title: "직접 연결",
|
||||
helper: "Paseo 서버의 주소를 입력하세요.",
|
||||
fields: {
|
||||
host: "호스트",
|
||||
port: "포트",
|
||||
@@ -2018,10 +2030,10 @@ export const ko: TranslationResources = {
|
||||
useSsl: "SSL 사용",
|
||||
connectionUri: "연결 URI",
|
||||
},
|
||||
advanced: {
|
||||
label: "고급",
|
||||
show: "고급 표시",
|
||||
hide: "고급 숨기기",
|
||||
modes: {
|
||||
form: "양식",
|
||||
uri: "URI",
|
||||
uriOnlyLink: "페어링 링크는 URI로만 사용할 수 있습니다",
|
||||
},
|
||||
passwordVisibility: {
|
||||
show: "비밀번호 표시",
|
||||
|
||||
@@ -206,6 +206,10 @@ export const ptBR: TranslationResources = {
|
||||
pasteImageFailed: "Falha ao colar a imagem",
|
||||
fileTooLarge: "{{fileName}} é grande demais (máximo {{size}})",
|
||||
},
|
||||
providerSwitch: {
|
||||
switchingNextMessage: "Trocando para {{provider}} na próxima mensagem",
|
||||
switchingAfterTurn: "Trocará para {{provider}} após este turno",
|
||||
},
|
||||
clientCommands: {
|
||||
archiveAgent: "Arquivar o agente atual",
|
||||
freshDraft: "Arquivar este agente e iniciar um novo rascunho",
|
||||
@@ -446,6 +450,13 @@ export const ptBR: TranslationResources = {
|
||||
turnFooter: {
|
||||
workedFor: "Trabalhou por {{duration}}",
|
||||
},
|
||||
providerSwitch: {
|
||||
switched: "Trocado de {{from}} para {{to}}",
|
||||
contextSummary: "{{count}} itens transferidos ({{chars}} / {{budget}} caracteres)",
|
||||
trimmed: "Cortado: {{reasons}}",
|
||||
reasonTailWindow: "histórico anterior além da janela",
|
||||
reasonCharBudget: "limite de caracteres",
|
||||
},
|
||||
compaction: {
|
||||
loading: "Compactando...",
|
||||
auto: "Contexto compactado automaticamente",
|
||||
@@ -788,6 +799,8 @@ export const ptBR: TranslationResources = {
|
||||
resumeCommandUnavailable: "Comando de retomada indisponível",
|
||||
reloadingAgent: "Recarregando agente...",
|
||||
reloadedAgent: "Agente recarregado",
|
||||
reloadedAgentHistoryDiverged:
|
||||
"Agente recarregado, mas o histórico do provedor não corresponde a este chat, então não foi sincronizado",
|
||||
failedToReloadAgent: "Falha ao recarregar agente",
|
||||
failedToCloseAgent: "Falha ao fechar agente",
|
||||
},
|
||||
@@ -2035,7 +2048,6 @@ export const ptBR: TranslationResources = {
|
||||
},
|
||||
direct: {
|
||||
title: "Conexão direta",
|
||||
helper: "Informe o endereço de um servidor Paseo.",
|
||||
fields: {
|
||||
host: "Host",
|
||||
port: "Porta",
|
||||
@@ -2044,10 +2056,10 @@ export const ptBR: TranslationResources = {
|
||||
useSsl: "Usar SSL",
|
||||
connectionUri: "URI da conexão",
|
||||
},
|
||||
advanced: {
|
||||
label: "Avançado",
|
||||
show: "Mostrar avançado",
|
||||
hide: "Ocultar avançado",
|
||||
modes: {
|
||||
form: "Formulário",
|
||||
uri: "URI",
|
||||
uriOnlyLink: "Links de pareamento só funcionam como URI",
|
||||
},
|
||||
passwordVisibility: {
|
||||
show: "Mostrar senha",
|
||||
|
||||
@@ -207,6 +207,10 @@ export const ru: TranslationResources = {
|
||||
pasteImageFailed: "Не удалось вставить изображение",
|
||||
fileTooLarge: "Файл {{fileName}} слишком большой (максимальный размер: {{size}})",
|
||||
},
|
||||
providerSwitch: {
|
||||
switchingNextMessage: "Переключение на {{provider}} в следующем сообщении",
|
||||
switchingAfterTurn: "Переключение на {{provider}} после этого хода",
|
||||
},
|
||||
clientCommands: {
|
||||
archiveAgent: "Архивировать текущего агента",
|
||||
freshDraft: "Архивировать этого агента и создать новый черновик",
|
||||
@@ -446,6 +450,13 @@ export const ru: TranslationResources = {
|
||||
turnFooter: {
|
||||
workedFor: "Время работы: {{duration}}",
|
||||
},
|
||||
providerSwitch: {
|
||||
switched: "Переключено с {{from}} на {{to}}",
|
||||
contextSummary: "Передано элементов: {{count}} ({{chars}} / {{budget}} симв.)",
|
||||
trimmed: "Сокращено: {{reasons}}",
|
||||
reasonTailWindow: "более ранняя история вне окна",
|
||||
reasonCharBudget: "лимит символов",
|
||||
},
|
||||
compaction: {
|
||||
loading: "Сжатие контекста...",
|
||||
auto: "Контекст сжат автоматически",
|
||||
@@ -791,6 +802,8 @@ export const ru: TranslationResources = {
|
||||
resumeCommandUnavailable: "Команда возобновления недоступна",
|
||||
reloadingAgent: "Перезагрузка агента...",
|
||||
reloadedAgent: "Агент перезагружен",
|
||||
reloadedAgentHistoryDiverged:
|
||||
"Агент перезагружен, но история провайдера не совпадает с этим чатом, поэтому она не синхронизирована",
|
||||
failedToReloadAgent: "Не удалось перезагрузить агента",
|
||||
failedToCloseAgent: "Не удалось закрыть агента",
|
||||
},
|
||||
@@ -2034,7 +2047,6 @@ export const ru: TranslationResources = {
|
||||
},
|
||||
direct: {
|
||||
title: "Прямое подключение",
|
||||
helper: "Введите адрес сервера Paseo.",
|
||||
fields: {
|
||||
host: "Хост",
|
||||
port: "Порт",
|
||||
@@ -2043,10 +2055,10 @@ export const ru: TranslationResources = {
|
||||
useSsl: "Использовать SSL",
|
||||
connectionUri: "URI подключения",
|
||||
},
|
||||
advanced: {
|
||||
label: "Дополнительные параметры",
|
||||
show: "Показать дополнительные параметры",
|
||||
hide: "Скрыть дополнительные параметры",
|
||||
modes: {
|
||||
form: "Форма",
|
||||
uri: "URI",
|
||||
uriOnlyLink: "Ссылки для сопряжения работают только как URI",
|
||||
},
|
||||
passwordVisibility: {
|
||||
show: "Показать пароль",
|
||||
|
||||
@@ -205,6 +205,10 @@ export const zhCN: TranslationResources = {
|
||||
pasteImageFailed: "无法粘贴图片",
|
||||
fileTooLarge: "{{fileName}} is too large (max {{size}})",
|
||||
},
|
||||
providerSwitch: {
|
||||
switchingNextMessage: "下一条消息将切换到 {{provider}}",
|
||||
switchingAfterTurn: "本轮结束后将切换到 {{provider}}",
|
||||
},
|
||||
clientCommands: {
|
||||
archiveAgent: "归档当前 Agent",
|
||||
freshDraft: "归档此 Agent 并开始新的草稿",
|
||||
@@ -442,6 +446,13 @@ export const zhCN: TranslationResources = {
|
||||
turnFooter: {
|
||||
workedFor: "工作了 {{duration}}",
|
||||
},
|
||||
providerSwitch: {
|
||||
switched: "已从 {{from}} 切换到 {{to}}",
|
||||
contextSummary: "已传递 {{count}} 项上下文({{chars}} / {{budget}} 字符)",
|
||||
trimmed: "已裁剪:{{reasons}}",
|
||||
reasonTailWindow: "超出窗口的早期历史",
|
||||
reasonCharBudget: "字符预算限制",
|
||||
},
|
||||
compaction: {
|
||||
loading: "正在压缩...",
|
||||
auto: "上下文已自动压缩",
|
||||
@@ -783,6 +794,8 @@ export const zhCN: TranslationResources = {
|
||||
resumeCommandUnavailable: "恢复命令不可用",
|
||||
reloadingAgent: "正在重新加载 Agent...",
|
||||
reloadedAgent: "已重新加载 Agent",
|
||||
reloadedAgentHistoryDiverged:
|
||||
"已重新加载 Agent,但提供方的历史记录与此对话不一致,因此未同步",
|
||||
failedToReloadAgent: "重新加载 Agent 失败",
|
||||
failedToCloseAgent: "关闭 Agent 失败",
|
||||
},
|
||||
@@ -1978,7 +1991,6 @@ export const zhCN: TranslationResources = {
|
||||
},
|
||||
direct: {
|
||||
title: "直接连接",
|
||||
helper: "输入 Paseo server 的地址。",
|
||||
fields: {
|
||||
host: "Host",
|
||||
port: "端口",
|
||||
@@ -1987,10 +1999,10 @@ export const zhCN: TranslationResources = {
|
||||
useSsl: "使用 SSL",
|
||||
connectionUri: "连接 URI",
|
||||
},
|
||||
advanced: {
|
||||
label: "高级",
|
||||
show: "显示高级选项",
|
||||
hide: "隐藏高级选项",
|
||||
modes: {
|
||||
form: "表单",
|
||||
uri: "URI",
|
||||
uriOnlyLink: "配对链接只能以 URI 形式使用",
|
||||
},
|
||||
passwordVisibility: {
|
||||
show: "显示密码",
|
||||
|
||||
@@ -383,6 +383,74 @@ describe("useOverlayRegistration in the browser", () => {
|
||||
expect(document.activeElement).toBe(trigger);
|
||||
expect(openedAfterClose).toEqual([]);
|
||||
});
|
||||
|
||||
it("restores focus to the non-first opener button when a fading upper overlay closes over a lower overlay", async () => {
|
||||
function StackedHarness({ upperActive }: { upperActive: boolean }) {
|
||||
const setLowerScope = useOverlayRegistration({
|
||||
keys: ["Escape"],
|
||||
active: true,
|
||||
layer: 10,
|
||||
onKeyDown: () => false,
|
||||
});
|
||||
const setUpperScope = useOverlayRegistration({
|
||||
keys: ["Escape"],
|
||||
active: upperActive,
|
||||
layer: 30,
|
||||
onKeyDown: () => false,
|
||||
});
|
||||
return (
|
||||
<>
|
||||
<div
|
||||
data-testid="lower-scope"
|
||||
ref={setLowerScope as RefCallback<HTMLDivElement>}
|
||||
tabIndex={-1}
|
||||
>
|
||||
<button data-testid="lower-first" type="button">
|
||||
Back
|
||||
</button>
|
||||
<button data-testid="lower-second" type="button">
|
||||
Settings
|
||||
</button>
|
||||
</div>
|
||||
<div
|
||||
data-testid="upper-scope"
|
||||
ref={setUpperScope as RefCallback<HTMLDivElement>}
|
||||
tabIndex={-1}
|
||||
>
|
||||
<button data-testid="upper-close" type="button">
|
||||
Close
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
flushSync(() => {
|
||||
root.render(<StackedHarness upperActive={false} />);
|
||||
});
|
||||
await nextFrame();
|
||||
|
||||
const lowerSecond = document.querySelector<HTMLButtonElement>('[data-testid="lower-second"]');
|
||||
expect(lowerSecond).toBeTruthy();
|
||||
lowerSecond?.focus();
|
||||
expect(document.activeElement).toBe(lowerSecond);
|
||||
|
||||
flushSync(() => {
|
||||
root.render(<StackedHarness upperActive />);
|
||||
});
|
||||
await nextFrame();
|
||||
|
||||
const upperClose = document.querySelector<HTMLButtonElement>('[data-testid="upper-close"]');
|
||||
expect(document.activeElement).toBe(upperClose);
|
||||
|
||||
// Keep upper-scope mounted while closing (mirrors AdaptiveModalSheet's web fade-out).
|
||||
flushSync(() => {
|
||||
root.render(<StackedHarness upperActive={false} />);
|
||||
});
|
||||
await nextFrame();
|
||||
|
||||
expect(document.activeElement).toBe(lowerSecond);
|
||||
});
|
||||
});
|
||||
|
||||
describe("hasOpenDomPopover", () => {
|
||||
|
||||
@@ -16,6 +16,7 @@ import { useChangesPreferences } from "@/hooks/use-changes-preferences";
|
||||
import { useAppSettings } from "@/hooks/use-settings";
|
||||
import { usePaneContext } from "@/panels/pane-context";
|
||||
import { definePanel, type PanelDescriptor, type PanelPresentation } from "@/panels/panel-registry";
|
||||
import { commitDiffTabLabel } from "@/panels/tab-labels";
|
||||
import { useAddFileToChat } from "@/panels/use-add-file-to-chat";
|
||||
import { useWorkspaceDirectory } from "@/stores/session-store-hooks";
|
||||
import type { WorkspaceTabTarget } from "@/workspace-tabs/model";
|
||||
@@ -228,7 +229,7 @@ function useCommitDiffPanelDescriptor(
|
||||
): PanelDescriptor {
|
||||
const { t } = useTranslation();
|
||||
return {
|
||||
label: target.sha.slice(0, 7),
|
||||
label: commitDiffTabLabel(target.sha),
|
||||
subtitle: t("panels.diff.commitSubtitle"),
|
||||
tooltip: target.sha,
|
||||
titleState: "ready",
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { ComponentType } from "react";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
import type { PanelDescriptor, PanelIconProps } from "@/panels/panel-registry";
|
||||
import { draftTabLabel } from "@/panels/tab-labels";
|
||||
|
||||
export function buildDraftPanelDescriptor(input: {
|
||||
isCreating: boolean;
|
||||
@@ -9,7 +10,7 @@ export function buildDraftPanelDescriptor(input: {
|
||||
}): PanelDescriptor {
|
||||
const { icon, isCreating, pendingPrompt } = input;
|
||||
const newAgentLabel = i18n.t("panels.draft.newAgent");
|
||||
const creatingLabel = pendingPrompt?.trim() || newAgentLabel;
|
||||
const creatingLabel = draftTabLabel({ isCreating, pendingPrompt, newAgentLabel });
|
||||
if (isCreating) {
|
||||
return {
|
||||
label: creatingLabel,
|
||||
|
||||
@@ -5,6 +5,7 @@ import { useTranslation } from "react-i18next";
|
||||
import { FilePane } from "@/file-pane/pane";
|
||||
import { usePaneContext } from "@/panels/pane-context";
|
||||
import { definePanel } from "@/panels/panel-registry";
|
||||
import { fileTabLabel } from "@/panels/tab-labels";
|
||||
import { useWorkspaceDirectory } from "@/stores/session-store-hooks";
|
||||
import { createMaterialFileIcon } from "@/components/material-file-icon";
|
||||
|
||||
@@ -16,7 +17,7 @@ const CENTERED_PADDED_STYLE = {
|
||||
} as const;
|
||||
|
||||
function useFilePanelDescriptor(target: { kind: "file"; path: string }) {
|
||||
const fileName = target.path.split("/").findLast(Boolean) ?? target.path;
|
||||
const fileName = fileTabLabel(target.path);
|
||||
const icon = useMemo(() => createMaterialFileIcon(fileName), [fileName]);
|
||||
return {
|
||||
label: fileName,
|
||||
|
||||
@@ -60,16 +60,21 @@ export function setPanelInstanceAttributes(
|
||||
for (const listener of allListeners) listener();
|
||||
}
|
||||
|
||||
/** Calls back when any panel's attributes change. */
|
||||
export function subscribeAllPanelInstanceAttributes(listener: () => void): () => void {
|
||||
allListeners.add(listener);
|
||||
return () => {
|
||||
allListeners.delete(listener);
|
||||
};
|
||||
}
|
||||
|
||||
export function useModifiedPanelTabIds(input: {
|
||||
serverId: string;
|
||||
workspaceId: string;
|
||||
tabIds: string[];
|
||||
}): Set<string> {
|
||||
const revision = useSyncExternalStore(
|
||||
useCallback((listener: () => void) => {
|
||||
allListeners.add(listener);
|
||||
return () => allListeners.delete(listener);
|
||||
}, []),
|
||||
subscribeAllPanelInstanceAttributes,
|
||||
() => attributesRevision,
|
||||
() => attributesRevision,
|
||||
);
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
import type { PluginPanelTargetParams } from "@getpaseo/plugin/client";
|
||||
import { z } from "zod";
|
||||
import { isAbsolutePath } from "@/utils/path";
|
||||
import { normalizeWorkspaceTabTarget } from "@/workspace-tabs/identity";
|
||||
import type { WorkspaceTabTarget } from "@/workspace-tabs/model";
|
||||
|
||||
/** Where a tab renders: a split pane, the Explorer dock, or the compact workspace sheet. */
|
||||
@@ -22,6 +26,26 @@ type CompactSheetRule<K extends WorkspaceTabTarget["kind"]> =
|
||||
facts: PanelTargetFacts,
|
||||
) => CompactSheetPolicy | null);
|
||||
|
||||
/** What opening a panel by its public identity asks the workspace to do. */
|
||||
export interface PanelOpenRequest {
|
||||
target: WorkspaceTabTarget;
|
||||
/** A workspace-relative path the panel expands to and selects once it shows. */
|
||||
revealPath?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* How plugins name a kind and spell one instance of it. Ids and param names are a published
|
||||
* contract: add optional params, never rename, narrow or require one.
|
||||
*/
|
||||
export interface PanelPublicIdentity<
|
||||
K extends WorkspaceTabTarget["kind"] = WorkspaceTabTarget["kind"],
|
||||
> {
|
||||
publicId: `paseo/${string}`;
|
||||
toParams(target: Extract<WorkspaceTabTarget, { kind: K }>): PluginPanelTargetParams;
|
||||
/** Null for params this panel does not accept. */
|
||||
fromParams(params: PluginPanelTargetParams): PanelOpenRequest | null;
|
||||
}
|
||||
|
||||
export interface PanelManifest<K extends WorkspaceTabTarget["kind"] = WorkspaceTabTarget["kind"]> {
|
||||
kind: K;
|
||||
/** The sheet is never listed: a kind renders there exactly when it has a `compactSheet` rule. */
|
||||
@@ -34,101 +58,219 @@ export interface PanelManifest<K extends WorkspaceTabTarget["kind"] = WorkspaceT
|
||||
*/
|
||||
compactSheet: CompactSheetRule<K>;
|
||||
resourceKey(target: Extract<WorkspaceTabTarget, { kind: K }>): string;
|
||||
/** One instance, such as an agent's chat or a terminal, never has a second tab. */
|
||||
oneTabPerInstance: boolean;
|
||||
/** Null for a kind plugins cannot open. */
|
||||
public: PanelPublicIdentity<K> | null;
|
||||
}
|
||||
|
||||
type PanelManifestByKind = {
|
||||
[K in WorkspaceTabTarget["kind"]]: PanelManifest<K>;
|
||||
};
|
||||
|
||||
function publicPanel<K extends WorkspaceTabTarget["kind"], Params>(input: {
|
||||
publicId: `paseo/${string}`;
|
||||
params: z.ZodType<Params>;
|
||||
toRequest(params: Params): PanelOpenRequest;
|
||||
toParams(target: Extract<WorkspaceTabTarget, { kind: K }>): PluginPanelTargetParams;
|
||||
}): PanelPublicIdentity<K> {
|
||||
return {
|
||||
publicId: input.publicId,
|
||||
toParams: input.toParams,
|
||||
fromParams(params) {
|
||||
const parsed = input.params.safeParse(params);
|
||||
if (!parsed.success) return null;
|
||||
const request = input.toRequest(parsed.data);
|
||||
const target = normalizeWorkspaceTabTarget(request.target);
|
||||
return target ? { ...request, target } : null;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const noParams = z.strictObject({});
|
||||
|
||||
const lineNumber = z.number().int().positive();
|
||||
|
||||
const fileParams = z
|
||||
.strictObject({
|
||||
path: z.string(),
|
||||
lineStart: lineNumber.optional(),
|
||||
lineEnd: lineNumber.optional(),
|
||||
})
|
||||
.refine(
|
||||
({ lineStart, lineEnd }) =>
|
||||
lineEnd === undefined || (lineStart !== undefined && lineEnd >= lineStart),
|
||||
);
|
||||
|
||||
const filesParams = z.strictObject({
|
||||
reveal: z
|
||||
.string()
|
||||
.transform((path) => path.trim().replace(/\\/g, "/"))
|
||||
.refine((path) => path.length > 0 && !isAbsolutePath(path) && !path.split("/").includes(".."))
|
||||
.optional(),
|
||||
});
|
||||
|
||||
const manifests = {
|
||||
new_tab: {
|
||||
kind: "new_tab",
|
||||
supportedHosts: ["main", "explorer"],
|
||||
showCloseButton: true,
|
||||
singleton: false,
|
||||
oneTabPerInstance: false,
|
||||
compactSheet: null,
|
||||
resourceKey: () => "new_tab",
|
||||
public: null,
|
||||
},
|
||||
draft: {
|
||||
kind: "draft",
|
||||
supportedHosts: ["main", "explorer"],
|
||||
showCloseButton: true,
|
||||
singleton: false,
|
||||
oneTabPerInstance: false,
|
||||
compactSheet: null,
|
||||
resourceKey: (target) => target.draftId,
|
||||
public: null,
|
||||
},
|
||||
agent: {
|
||||
kind: "agent",
|
||||
supportedHosts: ["main", "explorer"],
|
||||
showCloseButton: true,
|
||||
singleton: false,
|
||||
oneTabPerInstance: true,
|
||||
compactSheet: (target, facts) =>
|
||||
facts.isWorkspaceRootAgent(target.agentId) ? null : { openAsTab: true },
|
||||
resourceKey: (target) => target.agentId,
|
||||
public: publicPanel<"agent", { agentId: string }>({
|
||||
publicId: "paseo/agent",
|
||||
params: z.strictObject({ agentId: z.string() }),
|
||||
toRequest: ({ agentId }) => ({ target: { kind: "agent", agentId } }),
|
||||
toParams: ({ agentId }) => ({ agentId }),
|
||||
}),
|
||||
},
|
||||
provider_subagent: {
|
||||
kind: "provider_subagent",
|
||||
supportedHosts: ["main", "explorer"],
|
||||
showCloseButton: true,
|
||||
singleton: false,
|
||||
oneTabPerInstance: false,
|
||||
compactSheet: { openAsTab: false },
|
||||
resourceKey: (target) => `${target.parentAgentId}:${target.subagentId}`,
|
||||
public: publicPanel<"provider_subagent", { parentAgentId: string; subagentId: string }>({
|
||||
publicId: "paseo/subagent",
|
||||
params: z.strictObject({ parentAgentId: z.string(), subagentId: z.string() }),
|
||||
toRequest: (params) => ({ target: { kind: "provider_subagent", ...params } }),
|
||||
toParams: ({ parentAgentId, subagentId }) => ({ parentAgentId, subagentId }),
|
||||
}),
|
||||
},
|
||||
terminal: {
|
||||
kind: "terminal",
|
||||
supportedHosts: ["main", "explorer"],
|
||||
showCloseButton: true,
|
||||
singleton: false,
|
||||
oneTabPerInstance: true,
|
||||
compactSheet: null,
|
||||
resourceKey: (target) => target.terminalId,
|
||||
public: publicPanel<"terminal", { terminalId: string }>({
|
||||
publicId: "paseo/terminal",
|
||||
params: z.strictObject({ terminalId: z.string() }),
|
||||
toRequest: ({ terminalId }) => ({ target: { kind: "terminal", terminalId } }),
|
||||
toParams: ({ terminalId }) => ({ terminalId }),
|
||||
}),
|
||||
},
|
||||
browser: {
|
||||
kind: "browser",
|
||||
supportedHosts: ["main"],
|
||||
showCloseButton: true,
|
||||
singleton: false,
|
||||
oneTabPerInstance: true,
|
||||
compactSheet: null,
|
||||
resourceKey: (target) => target.browserId,
|
||||
public: publicPanel<"browser", { browserId: string }>({
|
||||
publicId: "paseo/browser",
|
||||
params: z.strictObject({ browserId: z.string() }),
|
||||
toRequest: ({ browserId }) => ({ target: { kind: "browser", browserId } }),
|
||||
toParams: ({ browserId }) => ({ browserId }),
|
||||
}),
|
||||
},
|
||||
changes_tree: {
|
||||
kind: "changes_tree",
|
||||
supportedHosts: ["explorer"],
|
||||
showCloseButton: false,
|
||||
singleton: true,
|
||||
oneTabPerInstance: true,
|
||||
compactSheet: null,
|
||||
resourceKey: () => "changes_tree",
|
||||
public: publicPanel<"changes_tree", Record<string, never>>({
|
||||
publicId: "paseo/changes",
|
||||
params: noParams,
|
||||
toRequest: () => ({ target: { kind: "changes_tree" } }),
|
||||
toParams: () => ({}),
|
||||
}),
|
||||
},
|
||||
files: {
|
||||
kind: "files",
|
||||
supportedHosts: ["explorer"],
|
||||
showCloseButton: false,
|
||||
singleton: true,
|
||||
oneTabPerInstance: true,
|
||||
compactSheet: null,
|
||||
resourceKey: () => "files",
|
||||
public: publicPanel<"files", { reveal?: string }>({
|
||||
publicId: "paseo/files",
|
||||
params: filesParams,
|
||||
toRequest: ({ reveal }) => ({ target: { kind: "files" }, revealPath: reveal }),
|
||||
// A reveal is something to do once, not part of which tab this is.
|
||||
toParams: () => ({}),
|
||||
}),
|
||||
},
|
||||
pull_request: {
|
||||
kind: "pull_request",
|
||||
supportedHosts: ["main", "explorer"],
|
||||
showCloseButton: true,
|
||||
singleton: false,
|
||||
oneTabPerInstance: false,
|
||||
compactSheet: null,
|
||||
resourceKey: () => "pull_request",
|
||||
public: publicPanel<"pull_request", Record<string, never>>({
|
||||
publicId: "paseo/pull-request",
|
||||
params: noParams,
|
||||
toRequest: () => ({ target: { kind: "pull_request" } }),
|
||||
toParams: () => ({}),
|
||||
}),
|
||||
},
|
||||
file: {
|
||||
kind: "file",
|
||||
supportedHosts: ["main", "explorer"],
|
||||
showCloseButton: true,
|
||||
singleton: false,
|
||||
oneTabPerInstance: false,
|
||||
compactSheet: { openAsTab: false },
|
||||
resourceKey: (target) => target.path,
|
||||
public: publicPanel<"file", z.infer<typeof fileParams>>({
|
||||
publicId: "paseo/file",
|
||||
params: fileParams,
|
||||
toRequest: (params) => ({ target: { kind: "file", ...params } }),
|
||||
toParams: ({ path, lineStart, lineEnd }) => ({
|
||||
path,
|
||||
...(lineStart ? { lineStart } : {}),
|
||||
...(lineEnd ? { lineEnd } : {}),
|
||||
}),
|
||||
}),
|
||||
},
|
||||
working_diff: {
|
||||
kind: "working_diff",
|
||||
supportedHosts: ["main", "explorer"],
|
||||
showCloseButton: true,
|
||||
singleton: false,
|
||||
oneTabPerInstance: false,
|
||||
compactSheet: null,
|
||||
resourceKey: () => "working_diff",
|
||||
public: publicPanel<"working_diff", Record<string, never>>({
|
||||
publicId: "paseo/diff",
|
||||
params: noParams,
|
||||
toRequest: () => ({ target: { kind: "working_diff" } }),
|
||||
toParams: () => ({}),
|
||||
}),
|
||||
},
|
||||
plugin: {
|
||||
kind: "plugin",
|
||||
@@ -136,27 +278,39 @@ const manifests = {
|
||||
supportedHosts: ["main", "explorer"],
|
||||
showCloseButton: true,
|
||||
singleton: false,
|
||||
oneTabPerInstance: false,
|
||||
compactSheet: null,
|
||||
resourceKey: (target) =>
|
||||
target.context === "agent"
|
||||
? `${target.pluginId}:${target.panelId}:agent:${target.agentId}`
|
||||
: `${target.pluginId}:${target.panelId}:workspace`,
|
||||
// Plugin panels are named by their registration, not by this kind.
|
||||
public: null,
|
||||
},
|
||||
setup: {
|
||||
kind: "setup",
|
||||
supportedHosts: ["main"],
|
||||
showCloseButton: true,
|
||||
singleton: false,
|
||||
oneTabPerInstance: false,
|
||||
compactSheet: null,
|
||||
resourceKey: (target) => target.workspaceId,
|
||||
public: null,
|
||||
},
|
||||
commit_diff: {
|
||||
kind: "commit_diff",
|
||||
supportedHosts: ["main", "explorer"],
|
||||
showCloseButton: true,
|
||||
singleton: false,
|
||||
oneTabPerInstance: false,
|
||||
compactSheet: null,
|
||||
resourceKey: (target) => target.sha,
|
||||
public: publicPanel<"commit_diff", { sha: string }>({
|
||||
publicId: "paseo/commit-diff",
|
||||
params: z.strictObject({ sha: z.string() }),
|
||||
toRequest: ({ sha }) => ({ target: { kind: "commit_diff", sha } }),
|
||||
toParams: ({ sha }) => ({ sha }),
|
||||
}),
|
||||
},
|
||||
} satisfies PanelManifestByKind;
|
||||
|
||||
@@ -189,3 +343,22 @@ export function panelResourceKey(target: WorkspaceTabTarget): string {
|
||||
const manifest = getPanelManifest(target.kind);
|
||||
return `${target.kind}:${manifest.resourceKey(target as never)}`;
|
||||
}
|
||||
|
||||
/** How plugins read a built-in tab back. A kind they cannot open reads as its kind name. */
|
||||
export function panelPublicReference(target: Exclude<WorkspaceTabTarget, { kind: "plugin" }>): {
|
||||
panelId: string;
|
||||
params: PluginPanelTargetParams;
|
||||
} {
|
||||
const identity = getPanelManifest(target.kind).public;
|
||||
if (!identity) return { panelId: `paseo/${target.kind}`, params: {} };
|
||||
return { panelId: identity.publicId, params: identity.toParams(target as never) };
|
||||
}
|
||||
|
||||
export function findPublicPanel(publicId: string): PanelPublicIdentity | null {
|
||||
for (const manifest of Object.values(manifests)) {
|
||||
if (manifest.public?.publicId === publicId) {
|
||||
return manifest.public as unknown as PanelPublicIdentity;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ import type { AgentScreenAgent } from "@/hooks/use-agent-screen-state-machine";
|
||||
import { usePaneContext } from "@/panels/pane-context";
|
||||
import { PaneSubtitle } from "@/panels/pane-subtitle";
|
||||
import { definePanel, type PanelDescriptor } from "@/panels/panel-registry";
|
||||
import { providerSubagentTabLabel } from "@/panels/tab-labels";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
import type { SheetTab } from "@/stores/workspace-layout-store";
|
||||
import { ParentAgentCallout } from "@/subagents/parent";
|
||||
@@ -96,9 +97,8 @@ function useProviderSubagentDescriptor(
|
||||
(state) => state.sessions[context.serverId]?.agents.get(target.parentAgentId)?.provider,
|
||||
);
|
||||
const provider = descriptor?.provider ?? parentProvider ?? "agent";
|
||||
// The task names the tab; the subagent type is supporting detail beside the provider.
|
||||
const subagentType = descriptor?.title?.trim();
|
||||
const label = descriptor?.description?.trim() || subagentType || "Subagent";
|
||||
const label = providerSubagentTabLabel(descriptor);
|
||||
const providerLabel = `${formatProviderLabel(provider)} subagent`;
|
||||
return {
|
||||
label,
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
/** Naming rules shared by a tab's React descriptor and the title read outside React. */
|
||||
|
||||
/** Null until the agent has a name of its own. */
|
||||
export function resolveAgentLabel(title: string | null | undefined): string | null {
|
||||
if (typeof title !== "string") {
|
||||
return null;
|
||||
}
|
||||
const normalized = title.trim();
|
||||
if (!normalized) {
|
||||
return null;
|
||||
}
|
||||
if (normalized.toLowerCase() === "new agent") {
|
||||
return null;
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
export function terminalTabLabel(
|
||||
terminal: { title?: string | null; name?: string | null } | null | undefined,
|
||||
fallback: string,
|
||||
): string {
|
||||
return (terminal?.title ?? terminal?.name)?.trim() || fallback;
|
||||
}
|
||||
|
||||
export function browserTabLabel(input: { title: string; url: string }): string {
|
||||
const title = input.title.trim();
|
||||
if (title) {
|
||||
return title;
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = new URL(input.url);
|
||||
return parsed.hostname || input.url;
|
||||
} catch {
|
||||
return input.url;
|
||||
}
|
||||
}
|
||||
|
||||
// The task names the tab; the subagent type is supporting detail.
|
||||
export function providerSubagentTabLabel(
|
||||
descriptor: { description?: string | null; title?: string | null } | null | undefined,
|
||||
): string {
|
||||
return descriptor?.description?.trim() || descriptor?.title?.trim() || "Subagent";
|
||||
}
|
||||
|
||||
export function draftTabLabel(input: {
|
||||
isCreating: boolean;
|
||||
pendingPrompt?: string | null;
|
||||
newAgentLabel: string;
|
||||
}): string {
|
||||
return (input.isCreating && input.pendingPrompt?.trim()) || input.newAgentLabel;
|
||||
}
|
||||
|
||||
export function fileTabLabel(path: string): string {
|
||||
return path.split("/").findLast(Boolean) ?? path;
|
||||
}
|
||||
|
||||
export function commitDiffTabLabel(sha: string): string {
|
||||
return sha.slice(0, 7);
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
import type { ListTerminalsResponse } from "@getpaseo/protocol/messages";
|
||||
import { queryClient } from "@/data/query-client";
|
||||
import { useBrowserStore } from "@/desktop/browser/store";
|
||||
import type { CheckoutPrStatusPayload } from "@/git/pr-status";
|
||||
import { formatPrTabLabel } from "@/git/pull-request-panel/tab-label";
|
||||
import { checkoutPrStatusQueryKey } from "@/git/query-keys";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
import {
|
||||
browserTabLabel,
|
||||
commitDiffTabLabel,
|
||||
draftTabLabel,
|
||||
fileTabLabel,
|
||||
providerSubagentTabLabel,
|
||||
resolveAgentLabel,
|
||||
terminalTabLabel,
|
||||
} from "@/panels/tab-labels";
|
||||
import { pluginRegistry } from "@/plugins/registry";
|
||||
import { resolvePluginWorkspacePanel } from "@/plugins/workspace-panels/resolution";
|
||||
import { buildTerminalsQueryKey } from "@/screens/workspace/terminals/state";
|
||||
import { useCreateFlowStore } from "@/stores/create-flow-store";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
import { selectWorkspaceDirectory } from "@/stores/session-store-hooks/selectors";
|
||||
import { providerSubagentKey, useProviderSubagentStore } from "@/subagents/provider-store";
|
||||
import type { PluginWorkspaceTabTarget, WorkspaceTabTarget } from "@/workspace-tabs/model";
|
||||
|
||||
interface TabTitleInput {
|
||||
serverId: string;
|
||||
workspaceId: string;
|
||||
target: WorkspaceTabTarget;
|
||||
}
|
||||
|
||||
/**
|
||||
* What a tab is called, from what the client already holds. Reads only: a terminal or pull
|
||||
* request nobody has loaded yet keeps its generic name.
|
||||
*/
|
||||
export function readTabTitle({ serverId, workspaceId, target }: TabTitleInput): string {
|
||||
switch (target.kind) {
|
||||
case "new_tab":
|
||||
return i18n.t("workspace.tabs.actions.newTab");
|
||||
case "draft":
|
||||
return readDraftTitle(serverId, target.draftId);
|
||||
case "agent":
|
||||
return readAgentTitle(serverId, target.agentId);
|
||||
case "provider_subagent":
|
||||
return providerSubagentTabLabel(
|
||||
useProviderSubagentStore
|
||||
.getState()
|
||||
.descriptors.get(providerSubagentKey(serverId, target.parentAgentId, target.subagentId)),
|
||||
);
|
||||
case "terminal":
|
||||
return readTerminalTitle(serverId, workspaceId, target.terminalId);
|
||||
case "browser": {
|
||||
const browser = useBrowserStore.getState().browsersById[target.browserId];
|
||||
return browserTabLabel({
|
||||
title: browser?.title ?? "",
|
||||
url: browser?.url ?? "https://example.com",
|
||||
});
|
||||
}
|
||||
case "changes_tree":
|
||||
return i18n.t("panels.diff.changesLabel");
|
||||
case "files":
|
||||
return i18n.t("panels.files.label");
|
||||
case "pull_request":
|
||||
return readPullRequestTitle(serverId, workspaceId);
|
||||
case "file":
|
||||
return fileTabLabel(target.path);
|
||||
case "working_diff":
|
||||
return i18n.t("panels.diff.diffLabel");
|
||||
case "plugin":
|
||||
return readPluginPanelTitle(serverId, target);
|
||||
case "setup":
|
||||
return i18n.t("workspace.setup.descriptor.label");
|
||||
case "commit_diff":
|
||||
return commitDiffTabLabel(target.sha);
|
||||
}
|
||||
}
|
||||
|
||||
/** Calls back whenever a title may read differently. */
|
||||
export function subscribeTabTitles(listener: () => void): () => void {
|
||||
i18n.on("languageChanged", listener);
|
||||
const releases = [
|
||||
useSessionStore.subscribe(listener),
|
||||
useCreateFlowStore.subscribe(listener),
|
||||
useProviderSubagentStore.subscribe(listener),
|
||||
useBrowserStore.subscribe(listener),
|
||||
queryClient.getQueryCache().subscribe(listener),
|
||||
pluginRegistry.subscribe(listener),
|
||||
() => {
|
||||
i18n.off("languageChanged", listener);
|
||||
},
|
||||
];
|
||||
return () => {
|
||||
for (const release of releases) release();
|
||||
};
|
||||
}
|
||||
|
||||
function readDraftTitle(serverId: string, draftId: string): string {
|
||||
const pending = useCreateFlowStore.getState().pendingByDraftId[draftId];
|
||||
return draftTabLabel({
|
||||
isCreating: pending?.serverId === serverId && pending.lifecycle === "active",
|
||||
pendingPrompt: pending?.text,
|
||||
newAgentLabel: i18n.t("panels.draft.newAgent"),
|
||||
});
|
||||
}
|
||||
|
||||
function readAgentTitle(serverId: string, agentId: string): string {
|
||||
const session = useSessionStore.getState().sessions[serverId];
|
||||
const agent = session?.agents.get(agentId) ?? session?.agentDetails.get(agentId);
|
||||
return resolveAgentLabel(agent?.title) ?? "";
|
||||
}
|
||||
|
||||
function readTerminalTitle(serverId: string, workspaceId: string, terminalId: string): string {
|
||||
const directory = selectWorkspaceDirectory(useSessionStore.getState(), serverId, workspaceId);
|
||||
const list = queryClient.getQueryData<ListTerminalsResponse["payload"]>(
|
||||
buildTerminalsQueryKey(serverId, directory, workspaceId),
|
||||
);
|
||||
return terminalTabLabel(
|
||||
list?.terminals.find((terminal) => terminal.id === terminalId),
|
||||
i18n.t("workspace.tabs.fallback.terminal"),
|
||||
);
|
||||
}
|
||||
|
||||
function readPullRequestTitle(serverId: string, workspaceId: string): string {
|
||||
const directory = selectWorkspaceDirectory(useSessionStore.getState(), serverId, workspaceId);
|
||||
const payload = queryClient.getQueryData<CheckoutPrStatusPayload>(
|
||||
checkoutPrStatusQueryKey(serverId, directory ?? ""),
|
||||
);
|
||||
const prNumber = payload?.status?.number ?? null;
|
||||
return prNumber === null ? i18n.t("panels.pullRequest.label") : formatPrTabLabel(prNumber);
|
||||
}
|
||||
|
||||
function readPluginPanelTitle(serverId: string, target: PluginWorkspaceTabTarget): string {
|
||||
const plugin =
|
||||
pluginRegistry
|
||||
.getSnapshot()
|
||||
.find((candidate) => candidate.serverId === serverId && candidate.id === target.pluginId) ??
|
||||
null;
|
||||
const panel = resolvePluginWorkspacePanel(plugin, target);
|
||||
if (!plugin || !panel) return "Plugin unavailable";
|
||||
return plugin.i18n.resolve(panel.title, plugin.locale);
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import { TerminalPane } from "@/components/terminal-pane";
|
||||
import { openUrlInWorkspaceBrowser } from "@/desktop/browser/open-url-in-workspace";
|
||||
import { usePaneContext, usePaneFocus } from "@/panels/pane-context";
|
||||
import { definePanel, type PanelDescriptor } from "@/panels/panel-registry";
|
||||
import { terminalTabLabel } from "@/panels/tab-labels";
|
||||
import { queryClient } from "@/data/query-client";
|
||||
import { buildTerminalsQueryKey } from "@/screens/workspace/terminals/state";
|
||||
import { showExplorerSidebar } from "@/workspace-tabs/explorer-sidebar";
|
||||
@@ -27,14 +28,6 @@ const CENTERED_PADDED_STYLE = {
|
||||
padding: 16,
|
||||
} as const;
|
||||
|
||||
function trimNonEmpty(value: string | null | undefined): string | null {
|
||||
if (typeof value !== "string") {
|
||||
return null;
|
||||
}
|
||||
const trimmed = value.trim();
|
||||
return trimmed.length > 0 ? trimmed : null;
|
||||
}
|
||||
|
||||
function useTerminalPanelDescriptor(
|
||||
target: { kind: "terminal"; terminalId: string },
|
||||
context: { serverId: string; workspaceId: string },
|
||||
@@ -64,9 +57,7 @@ function useTerminalPanelDescriptor(
|
||||
);
|
||||
const terminal =
|
||||
terminalsQuery.data?.terminals.find((entry) => entry.id === target.terminalId) ?? null;
|
||||
const label =
|
||||
trimNonEmpty(terminal?.title ?? terminal?.name ?? null) ??
|
||||
t("workspace.tabs.fallback.terminal");
|
||||
const label = terminalTabLabel(terminal, t("workspace.tabs.fallback.terminal"));
|
||||
|
||||
return {
|
||||
label,
|
||||
|
||||
@@ -12,6 +12,7 @@ import type { PluginClientStateSource } from "@getpaseo/plugin/client/host";
|
||||
import { resolvePluginPanelOpenLocation } from "./workspace-panels/locations";
|
||||
import { parsePluginOpenScreenInput } from "./surface-contribution";
|
||||
import type { InstalledPlugin } from "./types";
|
||||
import { pluginWorkspaceLayoutSource } from "./workspace-layout";
|
||||
|
||||
export interface PluginNavigation {
|
||||
openSettings(pluginId: string, screenId: string): void;
|
||||
@@ -64,6 +65,7 @@ export function createPluginAgentActionContext(input: {
|
||||
...createPluginCapabilities(plugin, navigation),
|
||||
workspace,
|
||||
agent,
|
||||
workspaceLayout: pluginWorkspaceLayoutSource(plugin).layout(workspace.id),
|
||||
openPanel(panelId, options) {
|
||||
const panel = plugin.workspacePanels.find((candidate) => candidate.id === panelId);
|
||||
if (!panel) throw new Error(`Workspace panel is unavailable: ${panelId}`);
|
||||
@@ -90,6 +92,7 @@ export function createPluginWorkspaceActionContext(input: {
|
||||
context: "workspace",
|
||||
...createPluginCapabilities(plugin, navigation),
|
||||
workspace,
|
||||
workspaceLayout: pluginWorkspaceLayoutSource(plugin).layout(workspace.id),
|
||||
openPanel(panelId, options) {
|
||||
const panel = plugin.workspacePanels.find(
|
||||
(candidate) => candidate.id === panelId && candidate.context === "workspace",
|
||||
|
||||
@@ -153,6 +153,9 @@ function harness() {
|
||||
openSurface() {},
|
||||
composers: () => [],
|
||||
async playAudio() {},
|
||||
workspaceLayout: () => {
|
||||
throw new Error("Layouts are not used here");
|
||||
},
|
||||
openPanel() {},
|
||||
addComposerPill: () => ({ update() {}, remove() {} }),
|
||||
addHeaderButton: () => ({ update() {}, remove() {} }),
|
||||
|
||||
@@ -12,6 +12,7 @@ import type { PluginClientRuntime } from "./evaluate";
|
||||
import { createPluginNavigation } from "./navigation";
|
||||
import { pluginButtonStore } from "./buttons";
|
||||
import type { InstalledPlugin } from "./types";
|
||||
import { pluginWorkspaceLayoutSource } from "./workspace-layout";
|
||||
|
||||
export function createPluginClientRuntime(
|
||||
installation: InstalledPlugin,
|
||||
@@ -33,6 +34,7 @@ export function createPluginClientRuntime(
|
||||
addHeaderButton(contribution) {
|
||||
return pluginButtonStore.addHeaderButton(installation, contribution);
|
||||
},
|
||||
workspaceLayout: (workspaceId) => pluginWorkspaceLayoutSource(installation).layout(workspaceId),
|
||||
openPanel(panelId, options) {
|
||||
openClientPanel({ installation, state, panelId, options });
|
||||
},
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user