mirror of
https://github.com/getpaseo/paseo.git
synced 2026-12-01 04:36:26 +00:00
Compare commits
23
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4abe1e9ca0 | ||
|
|
24ceb52147 | ||
|
|
4c4b384c7f | ||
|
|
1a606451cd | ||
|
|
23934841f0 | ||
|
|
d2d4105366 | ||
|
|
37cb22dac8 | ||
|
|
397d1e14d6 | ||
|
|
d193e419e9 | ||
|
|
bd20e3fe98 | ||
|
|
39eaba6181 | ||
|
|
63ede58d7d | ||
|
|
3986e8b808 | ||
|
|
9fd8921697 | ||
|
|
269fa33491 | ||
|
|
ebcea47942 | ||
|
|
fb9a1644f0 | ||
|
|
93278b217b | ||
|
|
5f453a2f74 | ||
|
|
01aced8cd2 | ||
|
|
9d994aca9b | ||
|
|
839d45103b | ||
|
|
96fee23fbd |
@@ -55,8 +55,10 @@ 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/running-indicators.md](docs/running-indicators.md) | Loader, status ring, tool-call shimmer — motion policy, compositor loops on web, native-driver clock, why not CSS keyframes |
|
||||
| [docs/markdown-renderer.md](docs/markdown-renderer.md) | Shared Markdown engine, the vendored library fork, native selection, links, images and library constraints |
|
||||
| [docs/native-text-selection.md](docs/native-text-selection.md) | Native diagram grouping, selection boundaries and leading inline image limitations |
|
||||
| [docs/file-observation.md](docs/file-observation.md) | Recursive watcher ownership, Linux constraints, teardown invariants, and Parcel comparison |
|
||||
|
||||
@@ -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
|
||||
|
||||
+1
-1
@@ -4,7 +4,7 @@ Paseo Hub is an explicit opt-in connection from one Paseo daemon to one Hub. Run
|
||||
not register it with a Hub. The relationship begins only when a user runs
|
||||
`paseo hub connect [url]` from the daemon machine with an explicit API key or matching stored CLI login.
|
||||
|
||||
The human CLI login and daemon relationship are separate identities. `paseo hub login [url]` stores a durable organization-scoped CLI credential keyed by normalized Hub origin under `PASEO_HOME`. Interactive login optionally connects the local daemon, then points to the Hub UI for trigger configuration; it does not scaffold or deploy configuration. `paseo hub init` remains the explicit triggers-as-code scaffold: it writes one self-contained organization trigger under `.paseo/triggers/`, validates it through the trigger API, and optionally installs it. `paseo hub deploy` validates and installs every trigger in that directory; passing `--project` keeps deploying the legacy project bundle instead. `paseo hub export [directory]` writes the active organization's current triggers in the same layout, using the active login unless another Hub or API key is selected. `paseo hub run` dispatches a `manual.run` trigger through `POST /api/v1/manual-runs`, which takes inputs and prompt as one string; the CLI rejects what Hub would silently read as prompt text (`packages/cli/src/commands/hub/run/`). Origin resolution uses explicit command input, `PASEO_HUB_URL`, active login, then `https://hub.paseo.sh`. Connect uses exact-origin authority to request a one-time enrollment token, then passes only that token to the daemon. The daemon generates and persists its own relationship credential.
|
||||
The human CLI login and daemon relationship are separate identities. `paseo hub login [url]` stores a durable organization-scoped CLI credential keyed by normalized Hub origin under `PASEO_HOME`. Interactive login optionally connects the local daemon, then points to the Hub UI for trigger configuration; it does not scaffold or deploy configuration. `paseo hub init` remains the explicit triggers-as-code scaffold: it writes one self-contained organization trigger under `.paseo/triggers/`, validates it through the trigger API, and optionally installs it. `paseo hub deploy` validates and installs every trigger in that directory; passing `--project` keeps deploying the legacy project bundle instead. `paseo hub export [directory]` writes the active organization's current triggers in the same layout, using the active login unless another Hub or API key is selected. Origin resolution uses explicit command input, `PASEO_HUB_URL`, active login, then `https://hub.paseo.sh`. Connect uses exact-origin authority to request a one-time enrollment token, then passes only that token to the daemon. The daemon generates and persists its own relationship credential.
|
||||
|
||||
## Connection and authority
|
||||
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
# Running indicators
|
||||
|
||||
Three things animate for as long as an agent works: the six-dot loader in the turn footer
|
||||
(`components/synced-loader`), the status ring on a running workspace or tab
|
||||
(`components/status-ring`), and the highlight that sweeps a running tool call's label
|
||||
(`components/label-shimmer`). A turn can run for an hour, so each of them must cost nothing on the
|
||||
thread that runs React.
|
||||
|
||||
## The rule
|
||||
|
||||
A perpetual animation is handed to the platform's animation engine once and then left alone. It
|
||||
does not go through React state, `requestAnimationFrame`, a timer per frame, or a Reanimated shared
|
||||
value.
|
||||
|
||||
`components/indicator-motion` owns the two pieces every indicator shares:
|
||||
|
||||
- `useIndicatorMotion()` decides whether an indicator may move: not under reduced motion, not in a
|
||||
retained panel that is not showing, not while the app is in the background. An indicator that may
|
||||
not move draws its resting frame and runs nothing. Ask this hook; do not read reduced motion or
|
||||
visibility yourself.
|
||||
- The driver: `loop.web.ts` on web, `clock.ts` on native.
|
||||
|
||||
Animate only `transform` and `opacity`. Anything else is painted on the main thread every frame.
|
||||
|
||||
## Web
|
||||
|
||||
`useIndicatorLoop` runs a keyframe loop through the Web Animations API (`element.animate`). The
|
||||
compositor carries it; the page runs no script, restyles nothing and repaints nothing to keep it
|
||||
moving.
|
||||
|
||||
Do not declare these as CSS `@keyframes`. A CSS animation fires `animationiteration`, React listens
|
||||
for it at the root, and Chromium wakes the main thread around the end of every cycle of every CSS
|
||||
animation in a document that has such a listener. Measured on a quiet running turn: 13 main-thread
|
||||
commits and 14 style recalculations a second with `@keyframes`, against the 3 commits a second the
|
||||
page produces with nothing moving. The Web Animations API has no iteration event.
|
||||
|
||||
Two more reasons the stylesheet route does not work here:
|
||||
|
||||
- Unistyles owns style conversion on web, so React Native Web's `animationKeyframes` is ignored.
|
||||
- React Native Web's `StyleSheet.create` validation deletes `animationName` in development.
|
||||
|
||||
Indicators that must move together use `phase: "shared"`, which starts the loop at the document
|
||||
timeline's origin instead of at mount. Every ring and every loader is then at the same point of its
|
||||
cycle wherever and whenever it mounted. A stepped animation sets `easing: "step-end"` on each
|
||||
keyframe; the compositor then draws a frame when a step changes and none in between.
|
||||
|
||||
## Native
|
||||
|
||||
Reanimated commits a cloned shadow tree on the UI thread for every frame a shared value changes.
|
||||
For a transition that is fine. For an indicator that runs for an hour it was 22–28% of a core on
|
||||
the UI thread of an Android emulator.
|
||||
|
||||
React Native's own `Animated` with `useNativeDriver: true` updates the view from the native driver
|
||||
and commits nothing. `clock.ts` builds a clock out of it: a decay that never slows, at one unit per
|
||||
millisecond, is the time since it started. Decay is the one native-driven animation that computes
|
||||
its value from the frame timestamp instead of replaying a 60 fps recording, so it is exact at any
|
||||
refresh rate and needs no loop restart. `Animated.modulo` and `interpolate` turn the clock into a
|
||||
rotation or a translation, all inside the native driver.
|
||||
|
||||
The loader changes six times per cycle, so it does not ride the frame clock. `step-ticker.ts` wakes
|
||||
the JS thread once per step, aligned to wall-clock step boundaries, and publishes the step into a
|
||||
native `Animated.Value`. A wake-up that arrives late publishes the step that is current by then, so
|
||||
the loader never drifts and every loader shows the same step.
|
||||
|
||||
Do not apply Unistyles dynamic styles to these `Animated.View`s; see
|
||||
[unistyles.md](unistyles.md#reanimated-animatedview--dynamic-styles-crashes).
|
||||
|
||||
## Measuring
|
||||
|
||||
`e2e/browser/running-indicators.spec.ts` holds the web budgets: animation-frame callbacks, style
|
||||
recalculations, paints and main-thread commits per second on a quiet running turn, React renders of
|
||||
the indicator components, the loader's cadence, reduced motion, and a hidden tab. Run it with
|
||||
`PASEO_RUNNING_INDICATORS_FRAMES=1` to also save reference frames of every indicator at fixed
|
||||
points of its cycle, for a pixel comparison across a change.
|
||||
|
||||
To hold a turn in the running state without streaming, send the mock load-test agent
|
||||
`Hold a running shell tool call for <N>ms`.
|
||||
|
||||
On Android, compare `adb shell dumpsys gfxinfo <package>` frame counts and per-thread CPU from
|
||||
`/proc/<pid>/task/*/stat` over a fixed window. The UI thread (`sh.paseo.debug`) is the one a
|
||||
regression shows up on; `RenderThread` draws 60 frames a second whenever a ring or a shimmer is on
|
||||
screen, and that part is the cost of the motion itself.
|
||||
+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();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { test, expect } from "../support/fixtures";
|
||||
import {
|
||||
readReactRenders,
|
||||
recordReactRenders,
|
||||
resetReactRenders,
|
||||
} from "../support/helpers/react-renders";
|
||||
import {
|
||||
captureLoaderSteps,
|
||||
freezeAnimationsAt,
|
||||
openQuietRunningTurn,
|
||||
readAnimatingTargets,
|
||||
readLoaderStep,
|
||||
readRunningAnimations,
|
||||
recordLoaderStepChanges,
|
||||
runningToolCall,
|
||||
statusRings,
|
||||
workingLoader,
|
||||
} from "../support/helpers/running-indicators";
|
||||
import { measureSteadyStateActivity } from "../support/helpers/steady-state-activity";
|
||||
import { setTabVisibility } from "../support/helpers/workspace-ui";
|
||||
|
||||
/**
|
||||
* A running turn that is otherwise quiet shows three animated indicators: the six-dot loader, the
|
||||
* tool-call label shimmer and the status rings. None of them may cost main-thread work: the
|
||||
* browser's compositor carries them, so the page neither runs script, restyles nor repaints to
|
||||
* keep them moving.
|
||||
*
|
||||
* The budgets sit between what the rest of the page does on its own and the cheapest way these
|
||||
* indicators have been measured getting it wrong. With nothing moving, the main thread still
|
||||
* commits to the compositor about three times a second (the elapsed counter and the app's own
|
||||
* timers), and each commit restyles whatever is animating. Declaring the same animations as CSS
|
||||
* `@keyframes` costs thirteen commits and fourteen restyles a second; driving them from script
|
||||
* costs sixty frames a second.
|
||||
*/
|
||||
|
||||
const SAMPLE_WINDOW_MS = 5_000;
|
||||
const ANIMATION_FRAME_CALLBACKS_PER_SECOND_BUDGET = 2;
|
||||
const STYLE_RECALCS_PER_SECOND_BUDGET = 8;
|
||||
const MAIN_THREAD_COMMITS_PER_SECOND_BUDGET = 8;
|
||||
const PAINTS_PER_SECOND_BUDGET = 4;
|
||||
// The elapsed counter's repaint reports the whole viewport as its clip once a second. Sixty
|
||||
// indicator frames a second repainted seventy viewports' worth.
|
||||
const PAINTED_VIEWPORTS_PER_SECOND_BUDGET = 4;
|
||||
const LOADER_PERIOD_MS = 950;
|
||||
const LOADER_STEP_MS = LOADER_PERIOD_MS / 6;
|
||||
const STATUS_RING_PERIOD_MS = 900;
|
||||
|
||||
// React renders these once when the indicator appears. Rendering again while the turn is quiet
|
||||
// means the animation is being driven through React.
|
||||
const INDICATOR_COMPONENTS = /SyncedLoader|StatusRing|Shimmer|ExpandableBadge|WorkingIndicator/;
|
||||
|
||||
function indicatorRenders(renders: Record<string, number>): string[] {
|
||||
return Object.keys(renders).filter((name) => INDICATOR_COMPONENTS.test(name));
|
||||
}
|
||||
|
||||
test.describe("Running indicators", () => {
|
||||
test("keep moving without waking the main thread", async ({ page, browser }, testInfo) => {
|
||||
test.setTimeout(180_000);
|
||||
await recordReactRenders(page);
|
||||
const agent = await openQuietRunningTurn(page);
|
||||
try {
|
||||
await resetReactRenders(page);
|
||||
const activity = await measureSteadyStateActivity({
|
||||
browser,
|
||||
page,
|
||||
windowMs: SAMPLE_WINDOW_MS,
|
||||
});
|
||||
const renders = await readReactRenders(page);
|
||||
const animations = await readRunningAnimations(page);
|
||||
const stepChanges = await recordLoaderStepChanges(page, 3_000);
|
||||
const evidence = { activity, renders, animations, stepChanges };
|
||||
await writeFile(testInfo.outputPath("evidence.json"), JSON.stringify(evidence, null, 2));
|
||||
|
||||
expect
|
||||
.soft(activity.animationFrameCallbacksPerSecond)
|
||||
.toBeLessThan(ANIMATION_FRAME_CALLBACKS_PER_SECOND_BUDGET);
|
||||
expect.soft(activity.styleRecalcsPerSecond).toBeLessThan(STYLE_RECALCS_PER_SECOND_BUDGET);
|
||||
expect.soft(activity.paintsPerSecond).toBeLessThan(PAINTS_PER_SECOND_BUDGET);
|
||||
expect
|
||||
.soft(activity.paintedViewportsPerSecond)
|
||||
.toBeLessThan(PAINTED_VIEWPORTS_PER_SECOND_BUDGET);
|
||||
expect
|
||||
.soft(activity.mainThreadCommitsPerSecond)
|
||||
.toBeLessThan(MAIN_THREAD_COMMITS_PER_SECOND_BUDGET);
|
||||
expect.soft(indicatorRenders(renders)).toEqual([]);
|
||||
|
||||
// The cadence is part of the design: six even steps in 950 ms, in order.
|
||||
const steps = stepChanges.slice(1);
|
||||
expect.soft(steps.length).toBeGreaterThan(12);
|
||||
for (let index = 1; index < steps.length; index += 1) {
|
||||
expect.soft(steps[index].step).toBe((steps[index - 1].step + 1) % 6);
|
||||
}
|
||||
const measuredStepMs = (steps.at(-1)!.atMs - steps[0].atMs) / (steps.length - 1);
|
||||
expect.soft(Math.abs(measuredStepMs - LOADER_STEP_MS)).toBeLessThan(8);
|
||||
|
||||
const ringAnimations = animations.filter((animation) => animation.target === "status-ring");
|
||||
expect.soft(ringAnimations.length).toBeGreaterThan(0);
|
||||
for (const ring of ringAnimations) {
|
||||
expect.soft(ring).toMatchObject({
|
||||
durationMs: STATUS_RING_PERIOD_MS,
|
||||
easing: "linear",
|
||||
iterations: Number.POSITIVE_INFINITY,
|
||||
properties: ["transform"],
|
||||
});
|
||||
}
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("hold still when the system asks for reduced motion", async ({
|
||||
page,
|
||||
browser,
|
||||
}, testInfo) => {
|
||||
test.setTimeout(180_000);
|
||||
await page.emulateMedia({ reducedMotion: "reduce" });
|
||||
await recordReactRenders(page);
|
||||
const agent = await openQuietRunningTurn(page);
|
||||
try {
|
||||
await resetReactRenders(page);
|
||||
const activity = await measureSteadyStateActivity({
|
||||
browser,
|
||||
page,
|
||||
windowMs: SAMPLE_WINDOW_MS,
|
||||
});
|
||||
const renders = await readReactRenders(page);
|
||||
const animations = await readRunningAnimations(page);
|
||||
await writeFile(
|
||||
testInfo.outputPath("evidence.json"),
|
||||
JSON.stringify({ activity, renders, animations }, null, 2),
|
||||
);
|
||||
await page.screenshot({ path: testInfo.outputPath("page-reduced-motion.png") });
|
||||
await workingLoader(page).screenshot({ path: testInfo.outputPath("loader.png") });
|
||||
await runningToolCall(page).screenshot({ path: testInfo.outputPath("tool-call.png") });
|
||||
await statusRings(page)
|
||||
.first()
|
||||
.screenshot({ path: testInfo.outputPath("status-ring.png") });
|
||||
|
||||
expect.soft(animations).toEqual([]);
|
||||
expect.soft(await readLoaderStep(page)).toBe(0);
|
||||
expect
|
||||
.soft(activity.animationFrameCallbacksPerSecond)
|
||||
.toBeLessThan(ANIMATION_FRAME_CALLBACKS_PER_SECOND_BUDGET);
|
||||
expect.soft(activity.styleRecalcsPerSecond).toBeLessThan(STYLE_RECALCS_PER_SECOND_BUDGET);
|
||||
expect.soft(activity.paintsPerSecond).toBeLessThan(PAINTS_PER_SECOND_BUDGET);
|
||||
// With nothing moving the compositor only draws for the elapsed counter.
|
||||
expect.soft(activity.compositorFramesPerSecond).toBeLessThan(4);
|
||||
expect.soft(indicatorRenders(renders)).toEqual([]);
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("stop while the tab is hidden and resume when it is shown", async ({ page }) => {
|
||||
test.setTimeout(180_000);
|
||||
const agent = await openQuietRunningTurn(page);
|
||||
try {
|
||||
const everyIndicator = expect.arrayContaining([
|
||||
"status-ring",
|
||||
"synced-loader-dot",
|
||||
"label-shimmer",
|
||||
]);
|
||||
await expect.poll(() => readAnimatingTargets(page)).toEqual(everyIndicator);
|
||||
|
||||
await setTabVisibility(page, "hidden");
|
||||
await expect.poll(() => readAnimatingTargets(page)).toEqual([]);
|
||||
expect(await readLoaderStep(page)).toBe(0);
|
||||
|
||||
await setTabVisibility(page, "visible");
|
||||
await expect.poll(() => readAnimatingTargets(page)).toEqual(everyIndicator);
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("look the same frame for frame", async ({ page }, testInfo) => {
|
||||
test.setTimeout(180_000);
|
||||
test.skip(
|
||||
process.env.PASEO_RUNNING_INDICATORS_FRAMES !== "1",
|
||||
"Captures reference frames for a before/after comparison; not an assertion.",
|
||||
);
|
||||
const agent = await openQuietRunningTurn(page);
|
||||
try {
|
||||
const capturedSteps = await captureLoaderSteps(page, (step) =>
|
||||
testInfo.outputPath(`loader-step-${step}.png`),
|
||||
);
|
||||
expect(capturedSteps).toEqual([0, 1, 2, 3, 4, 5]);
|
||||
|
||||
for (const progress of [0, 0.13, 0.31, 0.5, 0.77, 0.94]) {
|
||||
await freezeAnimationsAt(page, progress);
|
||||
const label = String(Math.round(progress * 100)).padStart(2, "0");
|
||||
await runningToolCall(page).screenshot({
|
||||
path: testInfo.outputPath(`tool-call-${label}.png`),
|
||||
});
|
||||
await statusRings(page)
|
||||
.first()
|
||||
.screenshot({ path: testInfo.outputPath(`status-ring-${label}.png`) });
|
||||
await page.screenshot({
|
||||
path: testInfo.outputPath(`page-${label}.png`),
|
||||
mask: [page.getByTestId("turn-footer")],
|
||||
});
|
||||
}
|
||||
} finally {
|
||||
await agent.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);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -5,30 +5,34 @@ import { expectComposerVisible } from "../support/helpers/composer";
|
||||
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
|
||||
|
||||
interface ShimmerEvidence {
|
||||
animationDuration: string;
|
||||
durationMs: number;
|
||||
endPx: number;
|
||||
label: string;
|
||||
renderedWidth: number;
|
||||
startPx: number;
|
||||
}
|
||||
|
||||
async function readShimmerEvidence(locator: Locator): Promise<ShimmerEvidence> {
|
||||
return locator.evaluate((root) => {
|
||||
const shimmer = Array.from(root.querySelectorAll<HTMLElement>("*")).find((element) =>
|
||||
getComputedStyle(element).animationName.includes("paseo-toolcall-shimmer"),
|
||||
);
|
||||
if (!shimmer) {
|
||||
throw new Error("Expected a running shimmer inside the badge");
|
||||
}
|
||||
const style = getComputedStyle(shimmer);
|
||||
return {
|
||||
animationDuration: style.animationDuration,
|
||||
endPx: Number.parseFloat(style.getPropertyValue("--paseo-shimmer-end")),
|
||||
label: shimmer.textContent ?? "",
|
||||
renderedWidth: shimmer.getBoundingClientRect().width,
|
||||
startPx: Number.parseFloat(style.getPropertyValue("--paseo-shimmer-start")),
|
||||
};
|
||||
});
|
||||
// The band is the shimmer's moving window; its animation carries the sweep it was measured for.
|
||||
async function readShimmerEvidence(badge: Locator): Promise<ShimmerEvidence> {
|
||||
return badge
|
||||
.getByTestId("label-shimmer")
|
||||
.first()
|
||||
.evaluate((shimmer) => {
|
||||
const effect = shimmer.firstElementChild?.getAnimations()[0]?.effect;
|
||||
if (!(effect instanceof KeyframeEffect)) {
|
||||
throw new Error("Expected a running shimmer inside the badge");
|
||||
}
|
||||
const [startPx, endPx] = effect
|
||||
.getKeyframes()
|
||||
.map((keyframe) => new DOMMatrix(String(keyframe.transform)).m41);
|
||||
return {
|
||||
durationMs: Number(effect.getComputedTiming().duration),
|
||||
endPx,
|
||||
label: shimmer.textContent ?? "",
|
||||
renderedWidth: shimmer.getBoundingClientRect().width,
|
||||
startPx,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
test("measures an overview heading that becomes loading after its idle mount", async ({
|
||||
@@ -63,11 +67,11 @@ test("measures an overview heading that becomes loading after its idle mount", a
|
||||
if (!idleGroupHandle) {
|
||||
throw new Error("Expected the idle tool-call group to be mounted");
|
||||
}
|
||||
await expect(group.locator('[style*="paseo-toolcall-shimmer"]')).toHaveCount(0);
|
||||
await expect(group.getByTestId("label-shimmer")).toHaveCount(0);
|
||||
|
||||
await gate.waitForSecondRunning();
|
||||
gate.releaseSecondRunning();
|
||||
await expect(group.locator('[style*="paseo-toolcall-shimmer"]')).not.toHaveCount(0);
|
||||
await expect(group.getByTestId("label-shimmer")).not.toHaveCount(0);
|
||||
const sameGroupNode = await group.evaluate(
|
||||
(node, previous) => node === previous,
|
||||
idleGroupHandle,
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -30,7 +30,7 @@ import {
|
||||
pressArchiveShortcut,
|
||||
pressUndoShortcut,
|
||||
readSidebarListLayout,
|
||||
recordLastRowBottomPerFrame,
|
||||
recordLastRowDuringToastExpiry,
|
||||
resizeSidebarToMinimum,
|
||||
rowArchiveButton,
|
||||
rowKebab,
|
||||
@@ -187,7 +187,6 @@ test.describe("Workspace archive undo", () => {
|
||||
test("a long list scrolls its last row clear of the toast, and settles back smoothly after it", async ({
|
||||
page,
|
||||
}) => {
|
||||
await page.clock.install({ time: Date.now() });
|
||||
const fillers: Array<{ path: string; cleanup: () => Promise<void> }> = [];
|
||||
const fillerProjectIds: string[] = [];
|
||||
try {
|
||||
@@ -204,30 +203,30 @@ test.describe("Workspace archive undo", () => {
|
||||
|
||||
await archiveFromRowButton(page, worktree.workspaceId);
|
||||
await page.mouse.move(0, 0);
|
||||
const toastBox = await archivedToast(page).boundingBox();
|
||||
if (!toastBox) throw new Error("Toast is not laid out");
|
||||
// The list keeps its usual end gap, measured from the toast's top instead of its own bottom.
|
||||
// Read both edges together because the sidebar can resize while the toast is open.
|
||||
await expect
|
||||
.poll(async () => {
|
||||
const layout = await scrollSidebarListToEnd(page);
|
||||
const toastBox = await archivedToast(page).boundingBox();
|
||||
if (!toastBox) throw new Error("Toast is not laid out");
|
||||
return Math.round(toastBox.y - layout.rowBottoms.at(-1)!);
|
||||
})
|
||||
.toBe(Math.round(restingEndGap));
|
||||
.toBeGreaterThanOrEqual(Math.round(restingEndGap));
|
||||
|
||||
const frames = recordLastRowBottomPerFrame(page, 40);
|
||||
await outlastUndoWindow(page);
|
||||
const bottoms = await frames;
|
||||
await expect(archivedToast(page)).toHaveCount(0);
|
||||
const bottoms = await recordLastRowDuringToastExpiry(page);
|
||||
|
||||
// Without scrolling again, the list ends just below its last row once more.
|
||||
// Without scrolling again, the list returns to its usual gap below the last row.
|
||||
const settled = await readSidebarListLayout(page);
|
||||
expect(settled.listBottom - settled.rowBottoms.at(-1)!).toBeCloseTo(restingEndGap, 0);
|
||||
// The rows travel down by the toast's height over several frames, never in one jump.
|
||||
const travel = bottoms.at(-1)! - bottoms[0]!;
|
||||
expect(travel).toBeGreaterThan(toastBox.height);
|
||||
const steps = bottoms.slice(1).map((bottom, index) => bottom - bottoms[index]!);
|
||||
const settledBottom = settled.rowBottoms.at(-1)!;
|
||||
expect(settled.listBottom - settledBottom).toBeCloseTo(restingEndGap, 0);
|
||||
|
||||
// The last row moves through an intermediate position without reversing direction.
|
||||
const startBottom = bottoms[0]!;
|
||||
expect(bottoms.some((bottom) => bottom > startBottom && bottom < settledBottom)).toBe(true);
|
||||
const steps = [...bottoms, settledBottom]
|
||||
.slice(1)
|
||||
.map((bottom, index) => bottom - bottoms[index]!);
|
||||
expect(Math.min(...steps)).toBeGreaterThanOrEqual(0);
|
||||
expect(Math.max(...steps)).toBeLessThan(travel / 2);
|
||||
} finally {
|
||||
for (const projectId of fillerProjectIds) {
|
||||
await client.removeProject(projectId).catch(() => undefined);
|
||||
|
||||
@@ -7,9 +7,29 @@ code-to-body size ratio at every heading level; fenced code keeps the code-size
|
||||
token. Bold and links preserve the resulting size. Check the glyphs, not the background height: native backgrounds use
|
||||
line metrics.
|
||||
|
||||
Use a development client rebuilt from this checkout. Follow the temporary entry
|
||||
point and Metro workflow in [status-ring](../status-ring/README.md), importing
|
||||
`MarkdownFormattingRegression` from `./e2e/mobile/markdown-formatting/native`.
|
||||
Use a development client rebuilt from this checkout. In a disposable checkout,
|
||||
temporarily replace `packages/app/index.ts` with:
|
||||
|
||||
```tsx
|
||||
import "./src/polyfills/install-early";
|
||||
import "./src/styles/unistyles";
|
||||
import { registerRootComponent } from "expo";
|
||||
import MarkdownFormattingRegression from "./e2e/mobile/markdown-formatting/native";
|
||||
registerRootComponent(MarkdownFormattingRegression);
|
||||
```
|
||||
|
||||
Start Metro in `packages/app`:
|
||||
|
||||
```sh
|
||||
APP_VARIANT=development npx expo start --localhost --port 8096
|
||||
```
|
||||
|
||||
With one Android emulator running, open that bundle:
|
||||
|
||||
```sh
|
||||
agent-device open sh.paseo.debug 'exp+voice-mobile://expo-development-client/?url=http%3A%2F%2F10.0.2.2%3A8096' --platform android --session <session> --metro-port 8096
|
||||
```
|
||||
|
||||
Open the same Metro URL in a browser to compare web. Restore `index.ts` afterward.
|
||||
|
||||
With this fixture open in an Android Agent Device session, run:
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -1,45 +0,0 @@
|
||||
# Native retained status-ring regression
|
||||
|
||||
This runs the production native ring and clock inside real retained panels with
|
||||
Reanimated on Android. A probe consumes the same public rotation hook and counts
|
||||
UI-runtime value changes. No Reanimated mocks or provider processes are used.
|
||||
|
||||
Use an Android development client compatible with the checkout's native dependencies.
|
||||
In a disposable checkout, temporarily replace `packages/app/index.ts` with:
|
||||
|
||||
```tsx
|
||||
import "./src/polyfills/install-early";
|
||||
import "./src/styles/unistyles";
|
||||
import { registerRootComponent } from "expo";
|
||||
import NativeRingRegression from "./e2e/mobile/status-ring/native";
|
||||
registerRootComponent(NativeRingRegression);
|
||||
```
|
||||
|
||||
Start Metro in `packages/app`:
|
||||
|
||||
```sh
|
||||
APP_VARIANT=development npx expo start --localhost --port 8096
|
||||
```
|
||||
|
||||
With one Android emulator running, open that bundle:
|
||||
|
||||
```sh
|
||||
agent-device open sh.paseo.debug 'exp+voice-mobile://expo-development-client/?url=http%3A%2F%2F10.0.2.2%3A8096' --platform android --session status-ring --metro-port 8096
|
||||
```
|
||||
|
||||
From the repository root:
|
||||
|
||||
```sh
|
||||
node packages/app/e2e/mobile/status-ring/android.mjs status-ring http://127.0.0.1:8096
|
||||
```
|
||||
|
||||
The test checks visible rotation, hidden-panel inactivity while another ring is
|
||||
visible, inactivity with both panels hidden, and synchronized resumption. Each
|
||||
sample reads counters on the UI runtime; elapsed time includes device-command
|
||||
latency. The baseline fails at the first hidden-panel assertion.
|
||||
|
||||
Restore the original `packages/app/index.ts`, close the agent-device session,
|
||||
and stop Metro afterward. The fixture substitutes running rings for a live agent
|
||||
and toggles retained panels directly; it does not exercise workspace navigation
|
||||
or measure whole-app CPU usage. It is excluded from routine unit tests because
|
||||
it requires a native runtime.
|
||||
@@ -1,71 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { setTimeout as delay } from "node:timers/promises";
|
||||
|
||||
const [, , session, metroUrl] = process.argv;
|
||||
assert(session && metroUrl, "Pass an agent-device session and Metro URL serving native.tsx");
|
||||
function ad(...args) {
|
||||
return execFileSync("agent-device", ["--session", session, ...args], {
|
||||
encoding: "utf8",
|
||||
timeout: 60_000,
|
||||
});
|
||||
}
|
||||
function evaluate(expression) {
|
||||
const value = ad("cdp", "runtime", "eval", "--expr", expression, "--json").trim();
|
||||
return value === "undefined" ? undefined : JSON.parse(value);
|
||||
}
|
||||
let target;
|
||||
const deadline = Date.now() + 30_000;
|
||||
do {
|
||||
target = ad("cdp", "target", "list", "--url", metroUrl)
|
||||
.split("\n")
|
||||
.find((line) => line.includes("sh.paseo.debug"));
|
||||
if (!target) await delay(250);
|
||||
} while (!target && Date.now() < deadline);
|
||||
assert(target, "Open the Android dev client on this Metro bundle first");
|
||||
ad("cdp", "target", "select", target.split(/\s+/)[0]);
|
||||
let ready = false;
|
||||
do {
|
||||
ready = evaluate("Object.keys(globalThis.__ringReaders ?? {}).length === 2");
|
||||
if (!ready) await delay(250);
|
||||
} while (!ready && Date.now() < deadline);
|
||||
assert(ready, "The two native probes must mount before sampling");
|
||||
async function sample() {
|
||||
evaluate("Object.values(globalThis.__ringReaders).forEach(read => read())");
|
||||
await delay(100);
|
||||
return JSON.parse(evaluate("JSON.stringify(globalThis.__ringSamples)"));
|
||||
}
|
||||
async function observe(label) {
|
||||
const before = await sample();
|
||||
await delay(600);
|
||||
const after = await sample();
|
||||
const deltas = Object.fromEntries(
|
||||
Object.keys(before).map((key) => [key, after[key].updates - before[key].updates]),
|
||||
);
|
||||
console.log(JSON.stringify({ label, deltas, after }));
|
||||
return { deltas, after };
|
||||
}
|
||||
const visible = await observe("both visible");
|
||||
assert(visible.deltas.first > 0 && visible.deltas.second > 0);
|
||||
assert.equal(visible.after.first.rotation, visible.after.second.rotation);
|
||||
ad("press", 'label="HIDE FIRST"');
|
||||
await delay(200);
|
||||
const hidden = await observe("first hidden, second visible");
|
||||
assert.equal(hidden.deltas.first, 0, "A retained hidden ring must stop UI-thread rotation updates");
|
||||
assert(hidden.deltas.second > 0, "Visible rings must continue rotating");
|
||||
ad("press", 'label="HIDE SECOND"');
|
||||
await delay(200);
|
||||
const allHidden = await observe("both hidden");
|
||||
assert.equal(allHidden.deltas.first, 0);
|
||||
assert.equal(allHidden.deltas.second, 0);
|
||||
ad("press", 'label="SHOW FIRST"');
|
||||
ad("press", 'label="SHOW SECOND"');
|
||||
await delay(200);
|
||||
const restored = await observe("both shown again");
|
||||
assert(restored.deltas.first > 0 && restored.deltas.second > 0);
|
||||
assert.equal(
|
||||
restored.after.first.rotation,
|
||||
restored.after.second.rotation,
|
||||
"Restored rings must share the current phase",
|
||||
);
|
||||
console.log("PASS native retained-ring lifecycle");
|
||||
@@ -1,69 +0,0 @@
|
||||
import { useCallback, useLayoutEffect, useState } from "react";
|
||||
import { Button, Text, View } from "react-native";
|
||||
import { useAnimatedReaction, useSharedValue } from "react-native-reanimated";
|
||||
import { scheduleOnRN, scheduleOnUI } from "react-native-worklets";
|
||||
import { RetainedPanel } from "@/components/retained-panel";
|
||||
import { useStatusRingRotation } from "@/components/status-ring/clock";
|
||||
import { StatusRing } from "@/components/status-ring";
|
||||
|
||||
interface Sample {
|
||||
updates: number;
|
||||
rotation: number;
|
||||
}
|
||||
|
||||
declare global {
|
||||
var __ringSamples: Record<string, Sample>;
|
||||
var __ringReaders: Record<string, () => void>;
|
||||
}
|
||||
|
||||
function recordSample(name: string, value: { updates: number; rotation: number }) {
|
||||
globalThis.__ringSamples[name] = value;
|
||||
}
|
||||
|
||||
function Probe({ name }: { name: string }) {
|
||||
const rotation = useStatusRingRotation();
|
||||
const updates = useSharedValue(0);
|
||||
useAnimatedReaction(
|
||||
() => rotation.value,
|
||||
() => {
|
||||
updates.value += 1;
|
||||
},
|
||||
);
|
||||
// Read the real UI runtime, without scheduling a continuous JS observer.
|
||||
useLayoutEffect(() => {
|
||||
globalThis.__ringSamples ??= {};
|
||||
globalThis.__ringReaders ??= {};
|
||||
globalThis.__ringReaders[name] = () =>
|
||||
scheduleOnUI(() => {
|
||||
"worklet";
|
||||
const sample = { updates: updates.value, rotation: rotation.value };
|
||||
scheduleOnRN(recordSample, name, sample);
|
||||
});
|
||||
return () => {
|
||||
delete globalThis.__ringReaders[name];
|
||||
};
|
||||
}, [name, rotation, updates]);
|
||||
return <StatusRing />;
|
||||
}
|
||||
|
||||
const containerStyle = { flex: 1, padding: 60, backgroundColor: "white" };
|
||||
|
||||
export default function NativeRingRegression() {
|
||||
const [first, setFirst] = useState(true);
|
||||
const [second, setSecond] = useState(true);
|
||||
const toggleFirst = useCallback(() => setFirst((value) => !value), []);
|
||||
const toggleSecond = useCallback(() => setSecond((value) => !value), []);
|
||||
return (
|
||||
<View style={containerStyle}>
|
||||
<Text>Native retained status rings</Text>
|
||||
<Button title={first ? "Hide first" : "Show first"} onPress={toggleFirst} />
|
||||
<Button title={second ? "Hide second" : "Show second"} onPress={toggleSecond} />
|
||||
<RetainedPanel active={first}>
|
||||
<Probe name="first" />
|
||||
</RetainedPanel>
|
||||
<RetainedPanel active={second}>
|
||||
<Probe name="second" />
|
||||
</RetainedPanel>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { expect, type Locator, type Page } from "@playwright/test";
|
||||
import {
|
||||
SYNCED_LOADER_DOT_COUNT,
|
||||
getSyncedLoaderDotOpacity,
|
||||
} from "../../../src/components/synced-loader/state";
|
||||
import { expectComposerVisible } from "./composer";
|
||||
import { openAgentRoute, seedMockAgentWorkspace, type MockAgentWorkspace } from "./mock-agent";
|
||||
|
||||
const HELD_TOOL_CALL_PROMPT = "Hold a running shell tool call for 600000ms.";
|
||||
|
||||
export function workingLoader(page: Page): Locator {
|
||||
return page.getByTestId("synced-loader").filter({ visible: true });
|
||||
}
|
||||
|
||||
function loaderDots(page: Page): Locator {
|
||||
return page.getByTestId("synced-loader-dot").filter({ visible: true });
|
||||
}
|
||||
|
||||
export function statusRings(page: Page): Locator {
|
||||
return page.getByTestId("status-ring").filter({ visible: true });
|
||||
}
|
||||
|
||||
export function runningToolCall(page: Page): Locator {
|
||||
return page.getByTestId("tool-call-badge").last();
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens an agent whose turn is one running tool call and nothing else: the six-dot loader, the
|
||||
* tool-call label shimmer and the status rings are all on screen, and nothing streams.
|
||||
*/
|
||||
export async function openQuietRunningTurn(page: Page): Promise<MockAgentWorkspace> {
|
||||
const agent = await seedMockAgentWorkspace({
|
||||
repoPrefix: "running-indicators-",
|
||||
title: "Running indicators",
|
||||
});
|
||||
try {
|
||||
await openAgentRoute(page, { workspaceId: agent.workspaceId, agentId: agent.agentId });
|
||||
await expectComposerVisible(page);
|
||||
await agent.client.sendAgentMessage(agent.agentId, HELD_TOOL_CALL_PROMPT);
|
||||
await expect(workingLoader(page)).toBeVisible({ timeout: 30_000 });
|
||||
await expect(runningToolCall(page)).toBeVisible();
|
||||
await expect(statusRings(page).first()).toBeVisible();
|
||||
// Park the pointer on empty chat so no hover state repaints during a measurement.
|
||||
await page.mouse.move(900, 300);
|
||||
return agent;
|
||||
} catch (error) {
|
||||
await agent.cleanup();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/** The loader's current step, or null while the dots are between two readable states. */
|
||||
export async function readLoaderStep(page: Page): Promise<number | null> {
|
||||
const opacities = await loaderDots(page).evaluateAll((dots) =>
|
||||
dots.map((dot) => Number.parseFloat(getComputedStyle(dot).opacity)),
|
||||
);
|
||||
if (opacities.length !== SYNCED_LOADER_DOT_COUNT) {
|
||||
throw new Error(`Expected ${SYNCED_LOADER_DOT_COUNT} loader dots, found ${opacities.length}`);
|
||||
}
|
||||
for (let step = 0; step < SYNCED_LOADER_DOT_COUNT; step += 1) {
|
||||
const matches = opacities.every(
|
||||
(opacity, dot) => Math.abs(opacity - getSyncedLoaderDotOpacity(step, dot)) < 0.005,
|
||||
);
|
||||
if (matches) {
|
||||
return step;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export interface LoaderStepChange {
|
||||
step: number;
|
||||
atMs: number;
|
||||
}
|
||||
|
||||
/** Every step change the loader shows over the window, timestamped on the page's clock. */
|
||||
export async function recordLoaderStepChanges(
|
||||
page: Page,
|
||||
windowMs: number,
|
||||
): Promise<LoaderStepChange[]> {
|
||||
const states = Array.from({ length: SYNCED_LOADER_DOT_COUNT }, (_, step) =>
|
||||
Array.from({ length: SYNCED_LOADER_DOT_COUNT }, (__, dot) =>
|
||||
getSyncedLoaderDotOpacity(step, dot),
|
||||
),
|
||||
);
|
||||
return loaderDots(page).evaluateAll(
|
||||
(dots, input) =>
|
||||
new Promise<LoaderStepChange[]>((resolve) => {
|
||||
const readStep = () => {
|
||||
const opacities = dots.map((dot) => Number.parseFloat(getComputedStyle(dot).opacity));
|
||||
return input.states.findIndex((state) =>
|
||||
state.every((opacity, dot) => Math.abs(opacity - opacities[dot]) < 0.005),
|
||||
);
|
||||
};
|
||||
const changes: LoaderStepChange[] = [];
|
||||
const startedAt = performance.now();
|
||||
const sample = () => {
|
||||
const atMs = performance.now() - startedAt;
|
||||
const step = readStep();
|
||||
if (step !== -1 && step !== changes.at(-1)?.step) {
|
||||
changes.push({ step, atMs });
|
||||
}
|
||||
if (atMs >= input.windowMs) {
|
||||
resolve(changes);
|
||||
return;
|
||||
}
|
||||
requestAnimationFrame(sample);
|
||||
};
|
||||
sample();
|
||||
}),
|
||||
{ states, windowMs },
|
||||
);
|
||||
}
|
||||
|
||||
export interface RunningAnimation {
|
||||
name: string;
|
||||
target: string;
|
||||
durationMs: number;
|
||||
easing: string;
|
||||
iterations: number;
|
||||
properties: string[];
|
||||
}
|
||||
|
||||
/** Every animation the document is currently running, by what it animates. */
|
||||
export async function readRunningAnimations(page: Page): Promise<RunningAnimation[]> {
|
||||
return page.evaluate(() => {
|
||||
const timingKeys = new Set(["offset", "computedOffset", "easing", "composite"]);
|
||||
const running: RunningAnimation[] = [];
|
||||
for (const animation of document.getAnimations()) {
|
||||
const effect = animation.effect;
|
||||
if (animation.playState !== "running" || !(effect instanceof KeyframeEffect)) {
|
||||
continue;
|
||||
}
|
||||
const properties = new Set<string>();
|
||||
for (const keyframe of effect.getKeyframes()) {
|
||||
for (const key of Object.keys(keyframe)) {
|
||||
if (!timingKeys.has(key)) {
|
||||
properties.add(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
const timing = effect.getComputedTiming();
|
||||
const target = effect.target;
|
||||
running.push({
|
||||
name: animation instanceof CSSAnimation ? animation.animationName : "script",
|
||||
target:
|
||||
target?.closest("[data-testid]")?.getAttribute("data-testid") ?? target?.tagName ?? "",
|
||||
durationMs: Number(timing.duration),
|
||||
easing: String(timing.easing),
|
||||
iterations: Number(timing.iterations),
|
||||
properties: [...properties],
|
||||
});
|
||||
}
|
||||
return running;
|
||||
});
|
||||
}
|
||||
|
||||
/** What is currently animating, by test id. */
|
||||
export async function readAnimatingTargets(page: Page): Promise<string[]> {
|
||||
const animations = await readRunningAnimations(page);
|
||||
return animations.map((animation) => animation.target);
|
||||
}
|
||||
|
||||
/** Freezes every running animation at the same point of its cycle so a frame can be compared. */
|
||||
export async function freezeAnimationsAt(page: Page, progress: number): Promise<void> {
|
||||
await page.evaluate(async (cycleProgress) => {
|
||||
for (const animation of document.getAnimations()) {
|
||||
const duration = Number(animation.effect?.getComputedTiming().duration);
|
||||
animation.pause();
|
||||
animation.currentTime = duration * cycleProgress;
|
||||
}
|
||||
await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)));
|
||||
}, progress);
|
||||
}
|
||||
|
||||
/** Saves one image of the loader for each of its steps, named by step. */
|
||||
export async function captureLoaderSteps(
|
||||
page: Page,
|
||||
pathForStep: (step: number) => string,
|
||||
): Promise<number[]> {
|
||||
const loader = workingLoader(page);
|
||||
const captured = new Set<number>();
|
||||
for (let attempt = 0; attempt < 200 && captured.size < SYNCED_LOADER_DOT_COUNT; attempt += 1) {
|
||||
const before = await readLoaderStep(page);
|
||||
if (before === null || captured.has(before)) {
|
||||
continue;
|
||||
}
|
||||
const image = await loader.screenshot();
|
||||
// The step can turn over mid-capture; only an image bracketed by one step is that step.
|
||||
if ((await readLoaderStep(page)) !== before) {
|
||||
continue;
|
||||
}
|
||||
await writeFile(pathForStep(before), image);
|
||||
captured.add(before);
|
||||
}
|
||||
return [...captured].sort((a, b) => a - b);
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
import type { Browser, CDPSession, Page } from "@playwright/test";
|
||||
|
||||
/**
|
||||
* What a page costs while nothing on it is supposed to be changing: how often the main thread is
|
||||
* woken, how much it restyles and repaints, and how much CPU the renderer burns doing it.
|
||||
* Rates are per second of the sampled window.
|
||||
*/
|
||||
export interface SteadyStateActivity {
|
||||
animationFrameCallbacksPerSecond: number;
|
||||
timerCallbacksPerSecond: number;
|
||||
styleRecalcsPerSecond: number;
|
||||
layoutsPerSecond: number;
|
||||
paintsPerSecond: number;
|
||||
/** Repainted area per second, in viewports. */
|
||||
paintedViewportsPerSecond: number;
|
||||
/** Times the main thread committed new work to the compositor. */
|
||||
mainThreadCommitsPerSecond: number;
|
||||
rasterTasksPerSecond: number;
|
||||
/** Frames the compositor drew, with or without the main thread. */
|
||||
compositorFramesPerSecond: number;
|
||||
mainThreadBusyMsPerSecond: number;
|
||||
rendererCpuPercent: number;
|
||||
gpuCpuPercent: number;
|
||||
}
|
||||
|
||||
interface TraceEvent {
|
||||
name: string;
|
||||
ph: string;
|
||||
pid: number;
|
||||
args?: {
|
||||
data?: {
|
||||
clip?: number[];
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
const TRACE_CATEGORIES = [
|
||||
"devtools.timeline",
|
||||
"disabled-by-default-devtools.timeline",
|
||||
"disabled-by-default-devtools.timeline.frame",
|
||||
];
|
||||
|
||||
async function readProcessCpuSeconds(session: CDPSession): Promise<Map<string, number>> {
|
||||
const { processInfo } = await session.send("SystemInfo.getProcessInfo");
|
||||
const cpuByType = new Map<string, number>();
|
||||
for (const process of processInfo) {
|
||||
cpuByType.set(process.type, (cpuByType.get(process.type) ?? 0) + process.cpuTime);
|
||||
}
|
||||
return cpuByType;
|
||||
}
|
||||
|
||||
async function readMainThreadBusySeconds(session: CDPSession): Promise<number> {
|
||||
const { metrics } = await session.send("Performance.getMetrics");
|
||||
return metrics.find((metric) => metric.name === "TaskDuration")?.value ?? 0;
|
||||
}
|
||||
|
||||
function quadArea(clip: number[] | undefined): number {
|
||||
if (!clip || clip.length !== 8) {
|
||||
return 0;
|
||||
}
|
||||
const xs = [clip[0], clip[2], clip[4], clip[6]];
|
||||
const ys = [clip[1], clip[3], clip[5], clip[7]];
|
||||
return (Math.max(...xs) - Math.min(...xs)) * (Math.max(...ys) - Math.min(...ys));
|
||||
}
|
||||
|
||||
function summarizeTrace(input: {
|
||||
events: TraceEvent[];
|
||||
seconds: number;
|
||||
viewportArea: number;
|
||||
}): Pick<
|
||||
SteadyStateActivity,
|
||||
| "animationFrameCallbacksPerSecond"
|
||||
| "timerCallbacksPerSecond"
|
||||
| "styleRecalcsPerSecond"
|
||||
| "layoutsPerSecond"
|
||||
| "paintsPerSecond"
|
||||
| "paintedViewportsPerSecond"
|
||||
| "mainThreadCommitsPerSecond"
|
||||
| "rasterTasksPerSecond"
|
||||
| "compositorFramesPerSecond"
|
||||
> {
|
||||
const { events, seconds, viewportArea } = input;
|
||||
const counts = new Map<string, number>();
|
||||
let paintedArea = 0;
|
||||
for (const event of events) {
|
||||
// "B"/"X" open a slice and "I" is an instant; skipping "E" keeps begin/end pairs at one count.
|
||||
if (event.ph === "E") {
|
||||
continue;
|
||||
}
|
||||
counts.set(event.name, (counts.get(event.name) ?? 0) + 1);
|
||||
if (event.name === "Paint") {
|
||||
paintedArea += quadArea(event.args?.data?.clip);
|
||||
}
|
||||
}
|
||||
const perSecond = (name: string) => (counts.get(name) ?? 0) / seconds;
|
||||
return {
|
||||
animationFrameCallbacksPerSecond: perSecond("FireAnimationFrame"),
|
||||
timerCallbacksPerSecond: perSecond("TimerFire"),
|
||||
styleRecalcsPerSecond: perSecond("UpdateLayoutTree"),
|
||||
layoutsPerSecond: perSecond("Layout"),
|
||||
paintsPerSecond: perSecond("Paint"),
|
||||
paintedViewportsPerSecond: paintedArea / viewportArea / seconds,
|
||||
mainThreadCommitsPerSecond: perSecond("BeginCommitCompositorFrame"),
|
||||
rasterTasksPerSecond: perSecond("RasterTask"),
|
||||
compositorFramesPerSecond: perSecond("DrawFrame"),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Samples the page twice: once untraced for CPU and main-thread time, so the tracer's own cost
|
||||
* stays out of those numbers, then once traced for the per-event counts.
|
||||
*/
|
||||
export async function measureSteadyStateActivity(input: {
|
||||
browser: Browser;
|
||||
page: Page;
|
||||
windowMs: number;
|
||||
}): Promise<SteadyStateActivity> {
|
||||
const { browser, page, windowMs } = input;
|
||||
const seconds = windowMs / 1000;
|
||||
const viewport = page.viewportSize();
|
||||
if (!viewport) {
|
||||
throw new Error("Steady-state activity needs a fixed viewport");
|
||||
}
|
||||
|
||||
const pageSession = await page.context().newCDPSession(page);
|
||||
const browserSession = await browser.newBrowserCDPSession();
|
||||
try {
|
||||
await pageSession.send("Performance.enable");
|
||||
const cpuBefore = await readProcessCpuSeconds(browserSession);
|
||||
const busyBefore = await readMainThreadBusySeconds(pageSession);
|
||||
await page.waitForTimeout(windowMs);
|
||||
const busyAfter = await readMainThreadBusySeconds(pageSession);
|
||||
const cpuAfter = await readProcessCpuSeconds(browserSession);
|
||||
|
||||
await browser.startTracing(page, { categories: TRACE_CATEGORIES });
|
||||
await page.waitForTimeout(windowMs);
|
||||
const trace = JSON.parse((await browser.stopTracing()).toString("utf8")) as {
|
||||
traceEvents: TraceEvent[];
|
||||
};
|
||||
|
||||
const cpuPercent = (type: string) =>
|
||||
(((cpuAfter.get(type) ?? 0) - (cpuBefore.get(type) ?? 0)) / seconds) * 100;
|
||||
return {
|
||||
...summarizeTrace({
|
||||
events: trace.traceEvents,
|
||||
seconds,
|
||||
viewportArea: viewport.width * viewport.height,
|
||||
}),
|
||||
mainThreadBusyMsPerSecond: ((busyAfter - busyBefore) * 1000) / seconds,
|
||||
rendererCpuPercent: cpuPercent("renderer"),
|
||||
gpuCpuPercent: cpuPercent("GPU"),
|
||||
};
|
||||
} finally {
|
||||
await pageSession.detach().catch(() => undefined);
|
||||
await browserSession.detach().catch(() => undefined);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -204,25 +204,25 @@ export async function readSidebarListLayout(page: Page): Promise<SidebarListLayo
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts recording the bottom edge of the sidebar list's last row once per painted frame.
|
||||
* Resolves with one value per frame after `frameCount` frames.
|
||||
*/
|
||||
export function recordLastRowBottomPerFrame(page: Page, frameCount: number): Promise<number[]> {
|
||||
/** Records the last row's positions until the archive toast finishes fading out. */
|
||||
export function recordLastRowDuringToastExpiry(page: Page): Promise<number[]> {
|
||||
return page.getByTestId(SIDEBAR_LIST).evaluate(
|
||||
(element, count) =>
|
||||
(element) =>
|
||||
new Promise<number[]>((resolve) => {
|
||||
const bottoms: number[] = [];
|
||||
const sample = () => {
|
||||
const rows = element.querySelectorAll<HTMLElement>(
|
||||
'[data-testid^="sidebar-workspace-row-"],[data-testid^="sidebar-project-row-"]',
|
||||
);
|
||||
bottoms.push(Math.max(...Array.from(rows, (row) => row.getBoundingClientRect().bottom)));
|
||||
if (bottoms.length >= count) resolve(bottoms);
|
||||
else requestAnimationFrame(sample);
|
||||
const bottom = Math.max(...Array.from(rows, (row) => row.getBoundingClientRect().bottom));
|
||||
if (bottom !== bottoms.at(-1)) bottoms.push(bottom);
|
||||
if (document.querySelector('[data-testid="workspace-archived-toast"]')) {
|
||||
requestAnimationFrame(sample);
|
||||
} else {
|
||||
resolve(bottoms);
|
||||
}
|
||||
};
|
||||
requestAnimationFrame(sample);
|
||||
sample();
|
||||
}),
|
||||
frameCount,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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}>
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import { useEffect } from "react";
|
||||
import { Animated } from "react-native";
|
||||
|
||||
// A decay that never slows is a clock: with a velocity of one unit per millisecond the value is the
|
||||
// time since it started. Decay is the one native-driven animation that computes its value from the
|
||||
// frame's timestamp instead of replaying a 60 fps recording, so the motion is exact at any refresh
|
||||
// rate and never ends or loops.
|
||||
const CLOCK_CONFIG = { velocity: 1, deceleration: 1 - 1e-12, useNativeDriver: true };
|
||||
|
||||
/**
|
||||
* Milliseconds, counted on the UI thread by React Native's native animation driver.
|
||||
*
|
||||
* Views bound to it are updated by the native driver directly. Nothing reaches the JS thread, React
|
||||
* does not render, and no shadow tree is committed — which is what a Reanimated shared value costs
|
||||
* on every frame it changes.
|
||||
*/
|
||||
export interface IndicatorClock {
|
||||
/** Where a cycle of `periodMs` currently is, as milliseconds into the cycle. */
|
||||
cycle(periodMs: number): Animated.AnimatedModulo<number>;
|
||||
/** Runs the clock until the returned function is called. It restarts from zero when idle. */
|
||||
run(): () => void;
|
||||
}
|
||||
|
||||
export function createIndicatorClock(): IndicatorClock {
|
||||
const elapsedMs = new Animated.Value(0, { useNativeDriver: true });
|
||||
let runners = 0;
|
||||
let ticking: Animated.CompositeAnimation | null = null;
|
||||
|
||||
return {
|
||||
cycle(periodMs) {
|
||||
return Animated.modulo(elapsedMs, periodMs);
|
||||
},
|
||||
run() {
|
||||
runners += 1;
|
||||
if (!ticking) {
|
||||
elapsedMs.setValue(0);
|
||||
ticking = Animated.decay(elapsedMs, CLOCK_CONFIG);
|
||||
ticking.start();
|
||||
}
|
||||
return () => {
|
||||
runners -= 1;
|
||||
if (runners === 0) {
|
||||
ticking?.stop();
|
||||
ticking = null;
|
||||
}
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** One clock for indicators that must move as one, wherever they are on screen. */
|
||||
export const sharedIndicatorClock = createIndicatorClock();
|
||||
|
||||
/** Runs the clock for as long as an indicator bound to it is moving. */
|
||||
export function useRunningClock(clock: IndicatorClock, moving: boolean): void {
|
||||
useEffect(() => {
|
||||
if (!moving) return;
|
||||
return clock.run();
|
||||
}, [clock, moving]);
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { useSyncExternalStore } from "react";
|
||||
import { AccessibilityInfo } from "react-native";
|
||||
import { useReducedMotion as useReducedMotionAtLaunch } from "react-native-reanimated";
|
||||
import { useRetainedPanelActive } from "@/components/retained-panel";
|
||||
import { useAppVisible } from "@/hooks/use-app-visible";
|
||||
|
||||
// Reanimated knows the setting synchronously but only as it was at launch; React Native reports
|
||||
// every later change but answers the first question asynchronously. Together they are right from
|
||||
// the first render onwards.
|
||||
let reducedMotionSinceLaunch: boolean | null = null;
|
||||
const reducedMotionListeners = new Set<() => void>();
|
||||
|
||||
AccessibilityInfo.addEventListener("reduceMotionChanged", (reducedMotion) => {
|
||||
reducedMotionSinceLaunch = reducedMotion;
|
||||
for (const listener of reducedMotionListeners) listener();
|
||||
});
|
||||
|
||||
function subscribeToReducedMotion(listener: () => void): () => void {
|
||||
reducedMotionListeners.add(listener);
|
||||
return () => reducedMotionListeners.delete(listener);
|
||||
}
|
||||
|
||||
function getReducedMotionSinceLaunch(): boolean | null {
|
||||
return reducedMotionSinceLaunch;
|
||||
}
|
||||
|
||||
function useReducedMotion(): boolean {
|
||||
const atLaunch = useReducedMotionAtLaunch();
|
||||
const sinceLaunch = useSyncExternalStore(
|
||||
subscribeToReducedMotion,
|
||||
getReducedMotionSinceLaunch,
|
||||
getReducedMotionSinceLaunch,
|
||||
);
|
||||
return sinceLaunch ?? atLaunch;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a running indicator may move right now. It holds still when the system asks for reduced
|
||||
* motion, and while nobody can see it: in a retained panel that is not showing, or in an app that
|
||||
* is in the background.
|
||||
*
|
||||
* An indicator that is not moving draws its resting frame and runs nothing.
|
||||
*/
|
||||
export function useIndicatorMotion(): boolean {
|
||||
const panelActive = useRetainedPanelActive();
|
||||
const appVisible = useAppVisible();
|
||||
const reducedMotion = useReducedMotion();
|
||||
return panelActive && appVisible && !reducedMotion;
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import { useLayoutEffect, useRef, type RefObject } from "react";
|
||||
import type { View } from "react-native";
|
||||
|
||||
const TIMELINE_ORIGIN_MS = 0;
|
||||
|
||||
export interface IndicatorLoop {
|
||||
/** One cycle. Keep the array's identity stable: a new array restarts the loop. */
|
||||
keyframes: Keyframe[];
|
||||
durationMs: number;
|
||||
/**
|
||||
* `shared` puts every instance at the same point of the cycle, wherever and whenever it mounted:
|
||||
* the loop counts from the document timeline's origin instead of from its own start. `own` starts
|
||||
* the cycle when the loop does.
|
||||
*/
|
||||
phase: "shared" | "own";
|
||||
}
|
||||
|
||||
/**
|
||||
* Repeats `loop` on the element the returned ref is attached to, for as long as `loop` is given.
|
||||
*
|
||||
* The browser's animation engine runs it. A loop over `transform` or `opacity` is carried by the
|
||||
* compositor, so the page does no work per frame: no script, no style, no paint.
|
||||
*
|
||||
* It is declared through the Web Animations API, not a CSS `@keyframes` rule, on purpose. A CSS
|
||||
* animation fires `animationiteration`, React listens for that event at the root, and a document
|
||||
* with a listener for it makes Chromium bring the main thread up around the end of every cycle of
|
||||
* every CSS animation. A script-declared animation has no such event and never wakes it.
|
||||
*/
|
||||
export function useIndicatorLoop(loop: IndicatorLoop | null): RefObject<View | null> {
|
||||
const target = useRef<View | null>(null);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const element: unknown = target.current;
|
||||
if (!loop || !(element instanceof HTMLElement)) {
|
||||
return;
|
||||
}
|
||||
const animation = element.animate(loop.keyframes, {
|
||||
duration: loop.durationMs,
|
||||
iterations: Number.POSITIVE_INFINITY,
|
||||
});
|
||||
// An explicit start also keeps loops that start in the same commit exactly together.
|
||||
animation.startTime =
|
||||
loop.phase === "shared" ? TIMELINE_ORIGIN_MS : document.timeline.currentTime;
|
||||
return () => {
|
||||
animation.cancel();
|
||||
};
|
||||
}, [loop]);
|
||||
|
||||
return target;
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
import { memo, useMemo, useState } from "react";
|
||||
import { Animated, StyleSheet, Text, View } from "react-native";
|
||||
import MaskedView from "@react-native-masked-view/masked-view";
|
||||
import Svg, { Defs, Rect, Stop, LinearGradient as SvgLinearGradient } from "react-native-svg";
|
||||
import { useIndicatorMotion } from "@/components/indicator-motion";
|
||||
import { createIndicatorClock, useRunningClock } from "@/components/indicator-motion/clock";
|
||||
import { type LabelShimmerProps, getRowSweep, getShimmerDurationMs } from "./sweep";
|
||||
|
||||
export { useLabelMeasurements } from "./measurements";
|
||||
|
||||
const MASK_TEXT = { color: "#000000", opacity: 1 };
|
||||
|
||||
// Plain React Native styles: the band is an `Animated.View` the native animation driver writes to,
|
||||
// and a theme-tracked style on the same node gives it two writers. See docs/unistyles.md.
|
||||
const styles = StyleSheet.create({
|
||||
overlay: {
|
||||
position: "absolute",
|
||||
top: 0,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
left: 0,
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
overflow: "hidden",
|
||||
},
|
||||
track: {
|
||||
position: "absolute",
|
||||
top: 0,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
left: 0,
|
||||
overflow: "hidden",
|
||||
},
|
||||
maskRow: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
},
|
||||
band: {
|
||||
position: "absolute",
|
||||
top: 0,
|
||||
bottom: 0,
|
||||
left: 0,
|
||||
},
|
||||
spacer: {
|
||||
flex: 1,
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* Native label shimmer: a gradient band slides behind a mask cut in the shape of the label. The
|
||||
* native animation driver moves the band; see `indicator-motion/clock.ts`. Each shimmer has its own
|
||||
* clock so the highlight enters from the left when the label appears.
|
||||
*/
|
||||
export const LabelShimmer = memo(function LabelShimmer({
|
||||
label,
|
||||
secondaryLabel,
|
||||
labelStyle,
|
||||
secondaryLabelStyle,
|
||||
measurements,
|
||||
}: LabelShimmerProps) {
|
||||
const { rowSize } = measurements;
|
||||
const measured = rowSize.width > 0 && rowSize.height > 0;
|
||||
const moving = useIndicatorMotion() && measured;
|
||||
const [clock] = useState(createIndicatorClock);
|
||||
const [gradientId] = useState(
|
||||
() => `shimmer-gradient-${Math.random().toString(36).substring(2, 9)}`,
|
||||
);
|
||||
useRunningClock(clock, moving);
|
||||
|
||||
const durationMs = getShimmerDurationMs(label, secondaryLabel);
|
||||
const { peakWidth, fromX, toX } = getRowSweep(rowSize.width);
|
||||
const { width, height } = rowSize;
|
||||
|
||||
const trackStyle = useMemo(() => [styles.track, { width, height }], [height, width]);
|
||||
const bandStyle = useMemo(
|
||||
() => [
|
||||
styles.band,
|
||||
{ width: peakWidth, height },
|
||||
{
|
||||
transform: [
|
||||
{
|
||||
translateX: clock.cycle(durationMs).interpolate({
|
||||
inputRange: [0, durationMs],
|
||||
outputRange: [fromX, toX],
|
||||
}),
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
[clock, durationMs, fromX, height, peakWidth, toX],
|
||||
);
|
||||
const maskElement = useMemo(
|
||||
() => (
|
||||
<View pointerEvents="none" style={[styles.maskRow, { width, height }]}>
|
||||
<Text style={[labelStyle, MASK_TEXT]} numberOfLines={1}>
|
||||
{label}
|
||||
</Text>
|
||||
{secondaryLabel ? (
|
||||
<Text style={[secondaryLabelStyle, MASK_TEXT]} numberOfLines={1}>
|
||||
{secondaryLabel}
|
||||
</Text>
|
||||
) : (
|
||||
<View style={styles.spacer} />
|
||||
)}
|
||||
</View>
|
||||
),
|
||||
[height, label, labelStyle, secondaryLabel, secondaryLabelStyle, width],
|
||||
);
|
||||
|
||||
if (!moving) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<View style={styles.overlay} pointerEvents="none">
|
||||
<MaskedView pointerEvents="none" style={trackStyle} maskElement={maskElement}>
|
||||
<View pointerEvents="none" style={trackStyle}>
|
||||
<Animated.View pointerEvents="none" style={bandStyle}>
|
||||
<BandGradient id={gradientId} />
|
||||
</Animated.View>
|
||||
</View>
|
||||
</MaskedView>
|
||||
</View>
|
||||
);
|
||||
});
|
||||
|
||||
function BandGradient({ id }: { id: string }) {
|
||||
return (
|
||||
<Svg width="100%" height="100%" preserveAspectRatio="none">
|
||||
<Defs>
|
||||
<SvgLinearGradient id={id} x1="0%" y1="0%" x2="100%" y2="0%">
|
||||
<Stop offset="0%" stopColor="#ffffff" stopOpacity={0} />
|
||||
<Stop offset="50%" stopColor="#ffffff" stopOpacity={1} />
|
||||
<Stop offset="100%" stopColor="#ffffff" stopOpacity={0} />
|
||||
</SvgLinearGradient>
|
||||
</Defs>
|
||||
<Rect x="0" y="0" width="100%" height="100%" fill={`url(#${id})`} />
|
||||
</Svg>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
import { memo, useMemo } from "react";
|
||||
import { Text, View, type TextStyle, type ViewStyle } from "react-native";
|
||||
import { useIndicatorMotion } from "@/components/indicator-motion";
|
||||
import { type IndicatorLoop, useIndicatorLoop } from "@/components/indicator-motion/loop.web";
|
||||
import { type LabelShimmerProps, getShimmerDurationMs, getTextSweep } from "./sweep";
|
||||
|
||||
export { useLabelMeasurements } from "./measurements";
|
||||
|
||||
const BAND_GRADIENT =
|
||||
"linear-gradient(90deg, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.45) 24%, #ffffff 40%, #ffffff 60%, rgba(255, 255, 255, 0.45) 76%, rgba(255, 255, 255, 0) 100%)";
|
||||
|
||||
// Solid white text. Filling the glyphs through a clipped background instead of colouring them keeps
|
||||
// the rasteriser on the path the highlight has always been drawn with; plain white text is drawn
|
||||
// measurably heavier.
|
||||
const WHITE_TEXT = {
|
||||
opacity: 1,
|
||||
color: "transparent",
|
||||
WebkitTextFillColor: "transparent",
|
||||
backgroundColor: "#ffffff",
|
||||
backgroundClip: "text",
|
||||
WebkitBackgroundClip: "text",
|
||||
} as TextStyle;
|
||||
|
||||
const FILL: ViewStyle = { position: "absolute", top: 0, right: 0, bottom: 0, left: 0 };
|
||||
|
||||
// React Native's style types do not know the CSS mask properties.
|
||||
const overlayStyle: ViewStyle = { ...FILL, overflow: "hidden" };
|
||||
// The window: the row, cut down by a mask to a band with soft edges.
|
||||
const bandBaseStyle = {
|
||||
...FILL,
|
||||
maskImage: BAND_GRADIENT,
|
||||
WebkitMaskImage: BAND_GRADIENT,
|
||||
maskRepeat: "no-repeat",
|
||||
WebkitMaskRepeat: "no-repeat",
|
||||
} as ViewStyle;
|
||||
// The white text seen through the window, laid out exactly over the label.
|
||||
const textStyle: ViewStyle = { ...FILL, flexDirection: "row", alignItems: "center" };
|
||||
const spacerStyle: ViewStyle = { flex: 1 };
|
||||
|
||||
function slide(fromX: number, toX: number, durationMs: number): IndicatorLoop {
|
||||
return {
|
||||
keyframes: [{ transform: `translateX(${fromX}px)` }, { transform: `translateX(${toX}px)` }],
|
||||
durationMs,
|
||||
phase: "own",
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Web label shimmer. The window slides across the row while the text seen through it slides back by
|
||||
* the same amount, and so stays where it is. Both are `transform` loops, so the browser's
|
||||
* compositor moves two layers it has already painted; see `loop.web.ts`. Animating the highlight as
|
||||
* a text-clipped background instead repaints the text on the main thread every frame.
|
||||
*/
|
||||
export const LabelShimmer = memo(function LabelShimmer({
|
||||
label,
|
||||
secondaryLabel,
|
||||
labelStyle,
|
||||
secondaryLabelStyle,
|
||||
measurements,
|
||||
}: LabelShimmerProps) {
|
||||
const { labelSpan, secondarySpan } = measurements;
|
||||
const moving = useIndicatorMotion();
|
||||
const durationMs = getShimmerDurationMs(label, secondaryLabel);
|
||||
const sweep = getTextSweep({ labelSpan, secondarySpan: secondaryLabel ? secondarySpan : null });
|
||||
|
||||
// Both loops change together, so they restart together and stay exactly opposed.
|
||||
const bandLoop = useMemo(
|
||||
() => (moving ? slide(sweep.fromX, sweep.toX, durationMs) : null),
|
||||
[durationMs, moving, sweep.fromX, sweep.toX],
|
||||
);
|
||||
const textLoop = useMemo(
|
||||
() => (moving ? slide(-sweep.fromX, -sweep.toX, durationMs) : null),
|
||||
[durationMs, moving, sweep.fromX, sweep.toX],
|
||||
);
|
||||
const bandRef = useIndicatorLoop(bandLoop);
|
||||
const textRef = useIndicatorLoop(textLoop);
|
||||
|
||||
const bandStyle = useMemo(
|
||||
() => [
|
||||
bandBaseStyle,
|
||||
{
|
||||
maskSize: `${sweep.peakWidth}px 100%`,
|
||||
WebkitMaskSize: `${sweep.peakWidth}px 100%`,
|
||||
} as ViewStyle,
|
||||
],
|
||||
[sweep.peakWidth],
|
||||
);
|
||||
const labelTextStyle = useMemo(() => [labelStyle, WHITE_TEXT], [labelStyle]);
|
||||
const secondaryTextStyle = useMemo(
|
||||
() => [secondaryLabelStyle, WHITE_TEXT],
|
||||
[secondaryLabelStyle],
|
||||
);
|
||||
|
||||
if (!moving) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<View style={overlayStyle} pointerEvents="none" testID="label-shimmer">
|
||||
<View ref={bandRef} style={bandStyle}>
|
||||
<View ref={textRef} style={textStyle}>
|
||||
<Text style={labelTextStyle} numberOfLines={1}>
|
||||
{label}
|
||||
</Text>
|
||||
{secondaryLabel ? (
|
||||
<Text style={secondaryTextStyle} numberOfLines={1}>
|
||||
{secondaryLabel}
|
||||
</Text>
|
||||
) : (
|
||||
<View style={spacerStyle} />
|
||||
)}
|
||||
</View>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,67 @@
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
import type { LayoutChangeEvent } from "react-native";
|
||||
import { isNative, isWeb } from "@/constants/platform";
|
||||
import type { LabelMeasurements, LabelRowSize, LabelSpan } from "./sweep";
|
||||
|
||||
type LayoutHandler = (event: LayoutChangeEvent) => void;
|
||||
|
||||
export interface LabelMeasuring {
|
||||
measurements: LabelMeasurements;
|
||||
/** Attach each to its element's `onLayout`. One that is undefined needs no measuring. */
|
||||
onRowLayout: LayoutHandler | undefined;
|
||||
onLabelLayout: LayoutHandler | undefined;
|
||||
onSecondaryLayout: LayoutHandler | undefined;
|
||||
}
|
||||
|
||||
const UNMEASURED_ROW_SIZE: LabelRowSize = { width: 0, height: 0 };
|
||||
const UNMEASURED_SPAN: LabelSpan = { x: 0, width: 0 };
|
||||
|
||||
// Layout reports sub-pixel noise; a measurement that moved less than half a pixel is the same one.
|
||||
function isSameMeasurement(previous: number, next: number): boolean {
|
||||
return Math.abs(previous - next) <= 0.5;
|
||||
}
|
||||
|
||||
function isSameSpan(previous: LabelSpan, x: number, width: number): boolean {
|
||||
return isSameMeasurement(previous.x, x) && isSameMeasurement(previous.width, width);
|
||||
}
|
||||
|
||||
/**
|
||||
* Measures a label row for its shimmer. The web highlight follows the two pieces of text; the
|
||||
* native one crosses the whole row.
|
||||
*/
|
||||
export function useLabelMeasurements(shimmering: boolean): LabelMeasuring {
|
||||
const [rowSize, setRowSize] = useState(UNMEASURED_ROW_SIZE);
|
||||
const [labelSpan, setLabelSpan] = useState(UNMEASURED_SPAN);
|
||||
const [secondarySpan, setSecondarySpan] = useState(UNMEASURED_SPAN);
|
||||
|
||||
const handleRowLayout = useCallback((event: LayoutChangeEvent) => {
|
||||
const { width, height } = event.nativeEvent.layout;
|
||||
setRowSize((previous) =>
|
||||
isSameMeasurement(previous.width, width) && isSameMeasurement(previous.height, height)
|
||||
? previous
|
||||
: { width, height },
|
||||
);
|
||||
}, []);
|
||||
const handleLabelLayout = useCallback((event: LayoutChangeEvent) => {
|
||||
const { x, width } = event.nativeEvent.layout;
|
||||
setLabelSpan((previous) => (isSameSpan(previous, x, width) ? previous : { x, width }));
|
||||
}, []);
|
||||
const handleSecondaryLayout = useCallback((event: LayoutChangeEvent) => {
|
||||
const { x, width } = event.nativeEvent.layout;
|
||||
setSecondarySpan((previous) => (isSameSpan(previous, x, width) ? previous : { x, width }));
|
||||
}, []);
|
||||
|
||||
const measurements = useMemo(
|
||||
() => ({ rowSize, labelSpan, secondarySpan }),
|
||||
[rowSize, labelSpan, secondarySpan],
|
||||
);
|
||||
|
||||
return {
|
||||
measurements,
|
||||
onRowLayout: isNative && shimmering ? handleRowLayout : undefined,
|
||||
// React Native Web only observes a node when onLayout exists at mount. Measure while idle too,
|
||||
// so a retained row has its dimensions when it starts shimmering.
|
||||
onLabelLayout: isWeb ? handleLabelLayout : undefined,
|
||||
onSecondaryLayout: isWeb ? handleSecondaryLayout : undefined,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { getRowSweep, getShimmerDurationMs, getTextSweep } from "./sweep";
|
||||
|
||||
describe("label shimmer sweep", () => {
|
||||
test("takes longer on longer labels, between one and 2.3 seconds", () => {
|
||||
expect(getShimmerDurationMs("Shell", "sleep 600")).toBeCloseTo(1362);
|
||||
expect(getShimmerDurationMs("Read", undefined)).toBeCloseTo(1032);
|
||||
expect(getShimmerDurationMs(" Edit ", " a.ts ")).toBe(getShimmerDurationMs("Edit", "a.ts"));
|
||||
expect(getShimmerDurationMs("", undefined)).toBe(1000);
|
||||
expect(getShimmerDurationMs("x".repeat(400), undefined)).toBe(2300);
|
||||
});
|
||||
|
||||
test("crosses the text from one band width before the label to the end of the last text", () => {
|
||||
const sweep = getTextSweep({
|
||||
labelSpan: { x: 20, width: 36 },
|
||||
secondarySpan: { x: 64, width: 400 },
|
||||
});
|
||||
|
||||
expect(sweep.peakWidth).toBeCloseTo(97.68);
|
||||
expect(sweep.fromX).toBeCloseTo(20 - 97.68);
|
||||
expect(sweep.toX).toBe(464);
|
||||
});
|
||||
|
||||
test("ends at the label when there is no secondary text", () => {
|
||||
expect(getTextSweep({ labelSpan: { x: 20, width: 36 }, secondarySpan: null })).toEqual({
|
||||
peakWidth: 42,
|
||||
fromX: -22,
|
||||
toX: 56,
|
||||
});
|
||||
});
|
||||
|
||||
test("keeps the band between 42 and 120 wide on text", () => {
|
||||
const wide = getTextSweep({ labelSpan: { x: 0, width: 2000 }, secondarySpan: null });
|
||||
const unmeasured = getTextSweep({ labelSpan: { x: 0, width: 0 }, secondarySpan: null });
|
||||
|
||||
expect(wide.peakWidth).toBe(120);
|
||||
expect(unmeasured).toEqual({ peakWidth: 42, fromX: -42, toX: 0 });
|
||||
});
|
||||
|
||||
test("crosses the whole row with one band width of run-in and run-out", () => {
|
||||
const sweep = getRowSweep(300);
|
||||
expect(sweep.peakWidth).toBeCloseTo(84);
|
||||
expect(sweep.fromX).toBeCloseTo(-84);
|
||||
expect(sweep.toX).toBeCloseTo(384);
|
||||
expect(getRowSweep(50)).toEqual({ peakWidth: 32, fromX: -32, toX: 82 });
|
||||
expect(getRowSweep(2000)).toEqual({ peakWidth: 120, fromX: -120, toX: 2120 });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,62 @@
|
||||
import type { StyleProp, TextStyle } from "react-native";
|
||||
|
||||
/** Where a piece of text sits on the label row, as the row's layout reported it. */
|
||||
export interface LabelSpan {
|
||||
x: number;
|
||||
width: number;
|
||||
}
|
||||
|
||||
export interface LabelRowSize {
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
/** The row's measured geometry. A measurement that has not arrived yet is zero. */
|
||||
export interface LabelMeasurements {
|
||||
rowSize: LabelRowSize;
|
||||
labelSpan: LabelSpan;
|
||||
secondarySpan: LabelSpan;
|
||||
}
|
||||
|
||||
export interface LabelShimmerProps {
|
||||
label: string;
|
||||
secondaryLabel?: string;
|
||||
/** The row's own text styles: the highlight is set in the same type, at the same place. */
|
||||
labelStyle: StyleProp<TextStyle>;
|
||||
secondaryLabelStyle: StyleProp<TextStyle>;
|
||||
measurements: LabelMeasurements;
|
||||
}
|
||||
|
||||
/** One pass of the highlight: a band `peakWidth` wide whose left edge travels `fromX` to `toX`. */
|
||||
export interface ShimmerSweep {
|
||||
peakWidth: number;
|
||||
fromX: number;
|
||||
toX: number;
|
||||
}
|
||||
|
||||
/** Longer labels take longer to cross, within limits, so the highlight's speed reads the same. */
|
||||
export function getShimmerDurationMs(label: string, secondaryLabel: string | undefined): number {
|
||||
const characters = label.trim().length + (secondaryLabel?.trim().length ?? 0);
|
||||
const shortLabelAdjustment = characters <= 12 ? 0.25 : 0;
|
||||
const seconds = Math.max(1, Math.min(2.3, 1.25 + characters * 0.008 - shortLabelAdjustment));
|
||||
return seconds * 1000;
|
||||
}
|
||||
|
||||
/** Sweeps the text itself: in from just left of the label, out at the end of the last text. */
|
||||
export function getTextSweep(input: {
|
||||
labelSpan: LabelSpan;
|
||||
secondarySpan: LabelSpan | null;
|
||||
}): ShimmerSweep {
|
||||
const startX = input.labelSpan.x;
|
||||
const endX = input.secondarySpan
|
||||
? input.secondarySpan.x + input.secondarySpan.width
|
||||
: input.labelSpan.x + input.labelSpan.width;
|
||||
const peakWidth = Math.max(42, Math.min(120, Math.max(1, endX - startX) * 0.22));
|
||||
return { peakWidth, fromX: startX - peakWidth, toX: endX };
|
||||
}
|
||||
|
||||
/** Sweeps the whole row: in from just left of it, out just right of it. */
|
||||
export function getRowSweep(rowWidth: number): ShimmerSweep {
|
||||
const peakWidth = Math.max(32, Math.min(120, rowWidth * 0.28));
|
||||
return { peakWidth, fromX: -peakWidth, toX: rowWidth + peakWidth };
|
||||
}
|
||||
@@ -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", () => {
|
||||
|
||||
@@ -13,7 +13,6 @@ import {
|
||||
AttachmentThumbnail,
|
||||
} from "@/components/attachment-pill";
|
||||
import { MarkdownRenderer } from "@/components/markdown/renderer";
|
||||
import { useRetainedPanelActive } from "@/components/retained-panel";
|
||||
import {
|
||||
isRewindableMessage,
|
||||
RewindMenu,
|
||||
@@ -21,12 +20,15 @@ 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";
|
||||
import { LabelShimmer, useLabelMeasurements } from "@/components/label-shimmer";
|
||||
import { buildToolCallPresentation } from "@/tool-calls/presentation";
|
||||
import type {
|
||||
DaemonUploadedImageAttachment,
|
||||
@@ -47,13 +49,16 @@ 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,
|
||||
@@ -88,15 +93,6 @@ import {
|
||||
type LayoutChangeEvent,
|
||||
type TextStyle,
|
||||
} from "react-native";
|
||||
import Animated, {
|
||||
Easing,
|
||||
cancelAnimation,
|
||||
useAnimatedStyle,
|
||||
useSharedValue,
|
||||
withRepeat,
|
||||
withTiming,
|
||||
} from "react-native-reanimated";
|
||||
import Svg, { Defs, Rect, Stop, LinearGradient as SvgLinearGradient } from "react-native-svg";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { capAssistantMessageForRender, getUtf8ByteLength } from "./assistant-message-render-limit";
|
||||
import { getTurnDurationLabel } from "./assistant-turn-footer-label";
|
||||
@@ -147,8 +143,6 @@ function useDisableOuterSpacing(disableOuterSpacing: boolean | undefined) {
|
||||
return disableOuterSpacing ?? contextValue;
|
||||
}
|
||||
|
||||
const WEB_TOOLCALL_SHIMMER_KEYFRAME_ID = "paseo-toolcall-shimmer-keyframes";
|
||||
const WEB_TOOLCALL_SHIMMER_ANIMATION_NAME = "paseo-toolcall-shimmer";
|
||||
const ThemedMicVocal = withUnistyles(MicVocal);
|
||||
const ThemedFileSymlinkIcon = withUnistyles(FileSymlink);
|
||||
const ThemedTriangleAlertIcon = withUnistyles(TriangleAlertIcon);
|
||||
@@ -167,17 +161,6 @@ const mutedForegroundColorMapping = (theme: Theme) => ({
|
||||
const destructiveColorMapping = (theme: Theme) => ({ color: theme.colors.destructive });
|
||||
const infoColorMapping = (theme: Theme) => ({ color: theme.colors.palette.blue[300] });
|
||||
const warningColorMapping = (theme: Theme) => ({ color: theme.colors.palette.amber[500] });
|
||||
const WEB_TOOLCALL_SHIMMER_KEYFRAME_CSS = `
|
||||
@keyframes ${WEB_TOOLCALL_SHIMMER_ANIMATION_NAME} {
|
||||
0% {
|
||||
background-position: var(--paseo-shimmer-start, -200px) 0;
|
||||
}
|
||||
100% {
|
||||
background-position: var(--paseo-shimmer-end, 200px) 0;
|
||||
}
|
||||
}
|
||||
`;
|
||||
let webToolCallShimmerRegistered = false;
|
||||
const SCROLL_EDGE_EPSILON = 0.5;
|
||||
|
||||
// Font size for stream metadata (timestamps, durations, live elapsed timer).
|
||||
@@ -185,31 +168,6 @@ const SCROLL_EDGE_EPSILON = 0.5;
|
||||
export const STREAM_METADATA_FONT_SIZE = 13;
|
||||
type ScrollAxis = "x" | "y";
|
||||
|
||||
function ensureWebToolCallShimmerKeyframes() {
|
||||
if (isNative) {
|
||||
return;
|
||||
}
|
||||
if (typeof document === "undefined") {
|
||||
return;
|
||||
}
|
||||
const existing = document.getElementById(WEB_TOOLCALL_SHIMMER_KEYFRAME_ID);
|
||||
if (existing) {
|
||||
if (existing.textContent !== WEB_TOOLCALL_SHIMMER_KEYFRAME_CSS) {
|
||||
existing.textContent = WEB_TOOLCALL_SHIMMER_KEYFRAME_CSS;
|
||||
}
|
||||
webToolCallShimmerRegistered = true;
|
||||
return;
|
||||
}
|
||||
if (webToolCallShimmerRegistered) {
|
||||
return;
|
||||
}
|
||||
const styleElement = document.createElement("style");
|
||||
styleElement.id = WEB_TOOLCALL_SHIMMER_KEYFRAME_ID;
|
||||
styleElement.textContent = WEB_TOOLCALL_SHIMMER_KEYFRAME_CSS;
|
||||
document.head.appendChild(styleElement);
|
||||
webToolCallShimmerRegistered = true;
|
||||
}
|
||||
|
||||
function getWheelEventElementTarget(event: WheelEvent, fallback: HTMLElement): HTMLElement {
|
||||
const { target } = event;
|
||||
if (target instanceof HTMLElement) {
|
||||
@@ -1085,14 +1043,6 @@ const expandableBadgeStylesheet = StyleSheet.create((theme) => ({
|
||||
secondaryLabelActive: {
|
||||
color: theme.colors.foreground,
|
||||
},
|
||||
shimmerText: {
|
||||
color: "transparent",
|
||||
fontSize: theme.fontSize.base,
|
||||
fontWeight: theme.fontWeight.normal,
|
||||
},
|
||||
spacer: {
|
||||
flex: 1,
|
||||
},
|
||||
chevron: {
|
||||
flexShrink: 0,
|
||||
},
|
||||
@@ -1131,160 +1081,8 @@ const expandableBadgeStylesheet = StyleSheet.create((theme) => ({
|
||||
detailWrapperBorderless: {
|
||||
borderWidth: 0,
|
||||
},
|
||||
shimmerOverlay: {
|
||||
position: "absolute",
|
||||
top: 0,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
left: 0,
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
overflow: "hidden",
|
||||
},
|
||||
shimmerMaskRow: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
width: "100%",
|
||||
height: "100%",
|
||||
},
|
||||
nativeShimmerTrack: {
|
||||
position: "absolute",
|
||||
top: 0,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
left: 0,
|
||||
overflow: "hidden",
|
||||
},
|
||||
nativeShimmerPeak: {
|
||||
position: "absolute",
|
||||
top: 0,
|
||||
bottom: 0,
|
||||
left: 0,
|
||||
},
|
||||
}));
|
||||
|
||||
interface NativeExpandableBadgeShimmerProps {
|
||||
label: string;
|
||||
secondaryLabel?: string;
|
||||
rowWidth: number;
|
||||
rowHeight: number;
|
||||
peakWidth: number;
|
||||
durationSeconds: number;
|
||||
gradientId: string;
|
||||
}
|
||||
|
||||
const NativeExpandableBadgeShimmer = memo(function NativeExpandableBadgeShimmer({
|
||||
label,
|
||||
secondaryLabel,
|
||||
rowWidth,
|
||||
rowHeight,
|
||||
peakWidth,
|
||||
durationSeconds,
|
||||
gradientId,
|
||||
}: NativeExpandableBadgeShimmerProps) {
|
||||
const isPanelActive = useRetainedPanelActive();
|
||||
const shimmerTranslateX = useSharedValue(0);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isPanelActive) {
|
||||
cancelAnimation(shimmerTranslateX);
|
||||
return;
|
||||
}
|
||||
const startPosition = -peakWidth;
|
||||
const endPosition = rowWidth + peakWidth;
|
||||
shimmerTranslateX.value = startPosition;
|
||||
shimmerTranslateX.value = withRepeat(
|
||||
withTiming(endPosition, {
|
||||
duration: durationSeconds * 1000,
|
||||
easing: Easing.linear,
|
||||
}),
|
||||
-1,
|
||||
false,
|
||||
);
|
||||
return () => {
|
||||
cancelAnimation(shimmerTranslateX);
|
||||
};
|
||||
}, [durationSeconds, isPanelActive, peakWidth, rowWidth, shimmerTranslateX]);
|
||||
|
||||
const nativeShimmerPeakStyle = useAnimatedStyle(() => ({
|
||||
transform: [{ translateX: shimmerTranslateX.value }],
|
||||
}));
|
||||
|
||||
const nativeShimmerTrackStyle = useMemo(
|
||||
() => [expandableBadgeStylesheet.nativeShimmerTrack, { width: rowWidth, height: rowHeight }],
|
||||
[rowHeight, rowWidth],
|
||||
);
|
||||
|
||||
const nativeShimmerMaskStyle = useMemo(
|
||||
() => [expandableBadgeStylesheet.shimmerMaskRow, { width: rowWidth, height: rowHeight }],
|
||||
[rowHeight, rowWidth],
|
||||
);
|
||||
|
||||
const nativeLabelMaskStyle = useMemo(
|
||||
() => [expandableBadgeStylesheet.label, { color: "#000000", opacity: 1 }],
|
||||
[],
|
||||
);
|
||||
|
||||
const nativeSecondaryMaskStyle = useMemo(
|
||||
() => [expandableBadgeStylesheet.secondaryLabel, { color: "#000000", opacity: 1 }],
|
||||
[],
|
||||
);
|
||||
|
||||
const nativeShimmerPeakCombinedStyle = useMemo(
|
||||
() => [
|
||||
expandableBadgeStylesheet.nativeShimmerPeak,
|
||||
nativeShimmerPeakStyle,
|
||||
{ width: peakWidth, height: rowHeight },
|
||||
],
|
||||
[nativeShimmerPeakStyle, peakWidth, rowHeight],
|
||||
);
|
||||
|
||||
const maskElement = useMemo(
|
||||
() => (
|
||||
<View pointerEvents="none" style={nativeShimmerMaskStyle}>
|
||||
<Text style={nativeLabelMaskStyle} numberOfLines={1}>
|
||||
{label}
|
||||
</Text>
|
||||
{secondaryLabel ? (
|
||||
<Text style={nativeSecondaryMaskStyle} numberOfLines={1}>
|
||||
{secondaryLabel}
|
||||
</Text>
|
||||
) : (
|
||||
<View style={expandableBadgeStylesheet.spacer} />
|
||||
)}
|
||||
</View>
|
||||
),
|
||||
[nativeShimmerMaskStyle, nativeLabelMaskStyle, nativeSecondaryMaskStyle, label, secondaryLabel],
|
||||
);
|
||||
|
||||
return (
|
||||
<View style={expandableBadgeStylesheet.shimmerOverlay} pointerEvents="none">
|
||||
<MaskedView pointerEvents="none" style={nativeShimmerTrackStyle} maskElement={maskElement}>
|
||||
<View pointerEvents="none" style={nativeShimmerTrackStyle}>
|
||||
<Animated.View pointerEvents="none" style={nativeShimmerPeakCombinedStyle}>
|
||||
<NativeShimmerPeakSvg gradientId={gradientId} />
|
||||
</Animated.View>
|
||||
</View>
|
||||
</MaskedView>
|
||||
</View>
|
||||
);
|
||||
});
|
||||
|
||||
function NativeShimmerPeakSvg({ gradientId }: { gradientId: string }) {
|
||||
return (
|
||||
<Svg width="100%" height="100%" preserveAspectRatio="none">
|
||||
<Defs>
|
||||
<SvgLinearGradient id={gradientId} x1="0%" y1="0%" x2="100%" y2="0%">
|
||||
<Stop offset="0%" stopColor="#ffffff" stopOpacity={0} />
|
||||
<Stop offset="50%" stopColor="#ffffff" stopOpacity={1} />
|
||||
<Stop offset="100%" stopColor="#ffffff" stopOpacity={0} />
|
||||
</SvgLinearGradient>
|
||||
</Defs>
|
||||
<Rect x="0" y="0" width="100%" height="100%" fill={`url(#${gradientId})`} />
|
||||
</Svg>
|
||||
);
|
||||
}
|
||||
|
||||
export const AssistantMessage = memo(function AssistantMessage({
|
||||
renderFullContent = false,
|
||||
occurrenceKey,
|
||||
@@ -1575,6 +1373,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;
|
||||
@@ -1678,77 +1676,30 @@ interface ExpandableBadgeProps {
|
||||
interface ExpandableBadgeSecondaryLabelProps {
|
||||
secondaryLabel?: string;
|
||||
secondaryLabelStyle: StyleProp<TextStyle>;
|
||||
shouldMeasureWebShimmer: boolean;
|
||||
onSecondaryLayout: (event: LayoutChangeEvent) => void;
|
||||
onLayout: ((event: LayoutChangeEvent) => void) | undefined;
|
||||
}
|
||||
|
||||
function ExpandableBadgeSecondaryLabel({
|
||||
secondaryLabel,
|
||||
secondaryLabelStyle,
|
||||
shouldMeasureWebShimmer,
|
||||
onSecondaryLayout,
|
||||
onLayout,
|
||||
}: ExpandableBadgeSecondaryLabelProps) {
|
||||
if (!secondaryLabel) {
|
||||
return null;
|
||||
}
|
||||
return (
|
||||
<Text
|
||||
style={secondaryLabelStyle}
|
||||
numberOfLines={1}
|
||||
onLayout={shouldMeasureWebShimmer ? onSecondaryLayout : undefined}
|
||||
>
|
||||
<Text style={secondaryLabelStyle} numberOfLines={1} onLayout={onLayout}>
|
||||
{secondaryLabel}
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
|
||||
interface ExpandableBadgeWebShimmerOverlayProps {
|
||||
label: string;
|
||||
secondaryLabel?: string;
|
||||
shimmerLabelTextStyle: StyleProp<TextStyle>;
|
||||
shimmerSecondaryTextStyle: StyleProp<TextStyle>;
|
||||
}
|
||||
|
||||
function ExpandableBadgeWebShimmerOverlay({
|
||||
label,
|
||||
secondaryLabel,
|
||||
shimmerLabelTextStyle,
|
||||
shimmerSecondaryTextStyle,
|
||||
}: ExpandableBadgeWebShimmerOverlayProps) {
|
||||
return (
|
||||
<View style={expandableBadgeStylesheet.shimmerOverlay} pointerEvents="none">
|
||||
<Text style={shimmerLabelTextStyle} numberOfLines={1}>
|
||||
{label}
|
||||
</Text>
|
||||
{secondaryLabel ? (
|
||||
<Text style={shimmerSecondaryTextStyle} numberOfLines={1}>
|
||||
{secondaryLabel}
|
||||
</Text>
|
||||
) : null}
|
||||
{!secondaryLabel ? <View style={expandableBadgeStylesheet.spacer} /> : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
interface ExpandableBadgeLabelRowProps {
|
||||
label: string;
|
||||
labelStyle: StyleProp<TextStyle>;
|
||||
secondaryLabel?: string;
|
||||
secondaryLabelStyle: StyleProp<TextStyle>;
|
||||
shouldMeasureWebShimmer: boolean;
|
||||
shouldMeasureNativeShimmer: boolean;
|
||||
isWebShimmer: boolean;
|
||||
isNativeShimmer: boolean;
|
||||
shimmerLabelTextStyle: StyleProp<TextStyle>;
|
||||
shimmerSecondaryTextStyle: StyleProp<TextStyle>;
|
||||
labelRowWidth: number;
|
||||
labelRowHeight: number;
|
||||
nativeShimmerPeakWidth: number;
|
||||
shimmerDuration: number;
|
||||
nativeGradientId: string;
|
||||
onLabelRowLayout: (event: LayoutChangeEvent) => void;
|
||||
onLabelLayout: (event: LayoutChangeEvent) => void;
|
||||
onSecondaryLayout: (event: LayoutChangeEvent) => void;
|
||||
isLoading: boolean;
|
||||
}
|
||||
|
||||
function ExpandableBadgeLabelRow({
|
||||
@@ -1756,56 +1707,26 @@ function ExpandableBadgeLabelRow({
|
||||
labelStyle,
|
||||
secondaryLabel,
|
||||
secondaryLabelStyle,
|
||||
shouldMeasureWebShimmer,
|
||||
shouldMeasureNativeShimmer,
|
||||
isWebShimmer,
|
||||
isNativeShimmer,
|
||||
shimmerLabelTextStyle,
|
||||
shimmerSecondaryTextStyle,
|
||||
labelRowWidth,
|
||||
labelRowHeight,
|
||||
nativeShimmerPeakWidth,
|
||||
shimmerDuration,
|
||||
nativeGradientId,
|
||||
onLabelRowLayout,
|
||||
onLabelLayout,
|
||||
onSecondaryLayout,
|
||||
isLoading,
|
||||
}: ExpandableBadgeLabelRowProps) {
|
||||
const measuring = useLabelMeasurements(isLoading);
|
||||
return (
|
||||
<View
|
||||
style={expandableBadgeStylesheet.labelRow}
|
||||
onLayout={shouldMeasureNativeShimmer ? onLabelRowLayout : undefined}
|
||||
>
|
||||
<Text
|
||||
style={labelStyle}
|
||||
numberOfLines={1}
|
||||
onLayout={shouldMeasureWebShimmer ? onLabelLayout : undefined}
|
||||
>
|
||||
<View style={expandableBadgeStylesheet.labelRow} onLayout={measuring.onRowLayout}>
|
||||
<Text style={labelStyle} numberOfLines={1} onLayout={measuring.onLabelLayout}>
|
||||
{label}
|
||||
</Text>
|
||||
<ExpandableBadgeSecondaryLabel
|
||||
secondaryLabel={secondaryLabel}
|
||||
secondaryLabelStyle={secondaryLabelStyle}
|
||||
shouldMeasureWebShimmer={shouldMeasureWebShimmer}
|
||||
onSecondaryLayout={onSecondaryLayout}
|
||||
onLayout={measuring.onSecondaryLayout}
|
||||
/>
|
||||
{isWebShimmer ? (
|
||||
<ExpandableBadgeWebShimmerOverlay
|
||||
{isLoading ? (
|
||||
<LabelShimmer
|
||||
label={label}
|
||||
secondaryLabel={secondaryLabel}
|
||||
shimmerLabelTextStyle={shimmerLabelTextStyle}
|
||||
shimmerSecondaryTextStyle={shimmerSecondaryTextStyle}
|
||||
/>
|
||||
) : null}
|
||||
{isNativeShimmer ? (
|
||||
<NativeExpandableBadgeShimmer
|
||||
label={label}
|
||||
secondaryLabel={secondaryLabel}
|
||||
rowWidth={labelRowWidth}
|
||||
rowHeight={labelRowHeight}
|
||||
peakWidth={nativeShimmerPeakWidth}
|
||||
durationSeconds={shimmerDuration}
|
||||
gradientId={nativeGradientId}
|
||||
labelStyle={expandableBadgeStylesheet.label}
|
||||
secondaryLabelStyle={expandableBadgeStylesheet.secondaryLabel}
|
||||
measurements={measuring.measurements}
|
||||
/>
|
||||
) : null}
|
||||
</View>
|
||||
@@ -1880,55 +1801,6 @@ function renderExpandableBadgeIconSlot({
|
||||
return iconNode;
|
||||
}
|
||||
|
||||
function computeShimmerMetrics(input: {
|
||||
label: string;
|
||||
secondaryLabel: string | undefined;
|
||||
isLoading: boolean;
|
||||
labelRowWidth: number;
|
||||
labelRowHeight: number;
|
||||
labelOffsetX: number;
|
||||
labelWidth: number;
|
||||
secondaryOffsetX: number;
|
||||
secondaryWidth: number;
|
||||
}) {
|
||||
const totalShimmerChars = input.label.trim().length + (input.secondaryLabel?.trim().length ?? 0);
|
||||
const shortTextDurationAdjustment = totalShimmerChars <= 12 ? 0.25 : 0;
|
||||
const shimmerDuration = Math.max(
|
||||
1,
|
||||
Math.min(2.3, 1.25 + totalShimmerChars * 0.008 - shortTextDurationAdjustment),
|
||||
);
|
||||
const nativeShimmerPeakWidth = Math.max(
|
||||
32,
|
||||
Math.min(120, input.labelRowWidth > 0 ? input.labelRowWidth * 0.28 : 0),
|
||||
);
|
||||
const isWebShimmer = input.isLoading && isWeb;
|
||||
// React Native Web only observes a node when onLayout exists at mount. Keep
|
||||
// measuring while idle so a retained badge has dimensions when it starts loading.
|
||||
const shouldMeasureWebShimmer = isWeb;
|
||||
const shouldMeasureNativeShimmer = input.isLoading && isNative;
|
||||
const isNativeShimmer =
|
||||
shouldMeasureNativeShimmer && input.labelRowWidth > 0 && input.labelRowHeight > 0;
|
||||
const webShimmerSpanStartX = input.labelOffsetX;
|
||||
const webShimmerSpanEndX = input.secondaryLabel
|
||||
? input.secondaryOffsetX + input.secondaryWidth
|
||||
: input.labelOffsetX + input.labelWidth;
|
||||
const webShimmerSpanWidth = Math.max(1, webShimmerSpanEndX - webShimmerSpanStartX);
|
||||
const webShimmerPeakWidth = Math.max(42, Math.min(120, webShimmerSpanWidth * 0.22));
|
||||
const webShimmerTrackStart = webShimmerSpanStartX - webShimmerPeakWidth;
|
||||
const webShimmerTrackEnd = webShimmerSpanEndX;
|
||||
return {
|
||||
shimmerDuration,
|
||||
nativeShimmerPeakWidth,
|
||||
isWebShimmer,
|
||||
shouldMeasureWebShimmer,
|
||||
shouldMeasureNativeShimmer,
|
||||
isNativeShimmer,
|
||||
webShimmerPeakWidth,
|
||||
webShimmerTrackStart,
|
||||
webShimmerTrackEnd,
|
||||
};
|
||||
}
|
||||
|
||||
function useDetailWheelPropagationBlocker(input: {
|
||||
detailWrapperRef: React.RefObject<View | null>;
|
||||
enabled: boolean;
|
||||
@@ -1955,33 +1827,6 @@ function useDetailWheelPropagationBlocker(input: {
|
||||
}, [detailWrapperRef, enabled]);
|
||||
}
|
||||
|
||||
const SHIMMER_GRADIENT =
|
||||
"linear-gradient(90deg, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.45) 24%, #ffffff 40%, #ffffff 60%, rgba(255, 255, 255, 0.45) 76%, rgba(255, 255, 255, 0) 100%)";
|
||||
|
||||
function buildShimmerTextStyle(input: {
|
||||
isWebShimmer: boolean;
|
||||
webShimmerPeakWidth: number;
|
||||
shimmerDuration: number;
|
||||
webShimmerTrackStart: number;
|
||||
webShimmerTrackEnd: number;
|
||||
offsetX: number;
|
||||
}): object | null {
|
||||
if (!input.isWebShimmer) return null;
|
||||
return inlineUnistylesStyle({
|
||||
opacity: 1,
|
||||
color: "transparent",
|
||||
backgroundImage: SHIMMER_GRADIENT,
|
||||
backgroundSize: `${input.webShimmerPeakWidth}px 100%`,
|
||||
backgroundRepeat: "no-repeat",
|
||||
backgroundClip: "text",
|
||||
WebkitBackgroundClip: "text",
|
||||
WebkitTextFillColor: "transparent",
|
||||
animation: `${WEB_TOOLCALL_SHIMMER_ANIMATION_NAME} ${input.shimmerDuration}s linear infinite`,
|
||||
"--paseo-shimmer-start": `${input.webShimmerTrackStart - input.offsetX}px`,
|
||||
"--paseo-shimmer-end": `${input.webShimmerTrackEnd - input.offsetX}px`,
|
||||
});
|
||||
}
|
||||
|
||||
export const ExpandableBadge = memo(function ExpandableBadge({
|
||||
label,
|
||||
style,
|
||||
@@ -2025,126 +1870,11 @@ export const ExpandableBadge = memo(function ExpandableBadge({
|
||||
const handleOpenFileHoverIn = useCallback(() => setIsOpenFileHovered(true), []);
|
||||
const handleOpenFileHoverOut = useCallback(() => setIsOpenFileHovered(false), []);
|
||||
|
||||
const nativeGradientIdRef = useRef(
|
||||
`shimmer-gradient-${Math.random().toString(36).substring(2, 9)}`,
|
||||
);
|
||||
const [labelRowWidth, setLabelRowWidth] = useState(0);
|
||||
const [labelRowHeight, setLabelRowHeight] = useState(0);
|
||||
const [labelOffsetX, setLabelOffsetX] = useState(0);
|
||||
const [labelWidth, setLabelWidth] = useState(0);
|
||||
const [secondaryOffsetX, setSecondaryOffsetX] = useState(0);
|
||||
const [secondaryWidth, setSecondaryWidth] = useState(0);
|
||||
|
||||
const {
|
||||
shimmerDuration,
|
||||
nativeShimmerPeakWidth,
|
||||
isWebShimmer,
|
||||
shouldMeasureWebShimmer,
|
||||
shouldMeasureNativeShimmer,
|
||||
isNativeShimmer,
|
||||
webShimmerPeakWidth,
|
||||
webShimmerTrackStart,
|
||||
webShimmerTrackEnd,
|
||||
} = computeShimmerMetrics({
|
||||
label,
|
||||
secondaryLabel,
|
||||
isLoading,
|
||||
labelRowWidth,
|
||||
labelRowHeight,
|
||||
labelOffsetX,
|
||||
labelWidth,
|
||||
secondaryOffsetX,
|
||||
secondaryWidth,
|
||||
});
|
||||
|
||||
const handleLabelRowLayout = useCallback(
|
||||
(event: LayoutChangeEvent) => {
|
||||
if (!shouldMeasureNativeShimmer) {
|
||||
return;
|
||||
}
|
||||
const { width, height } = event.nativeEvent.layout;
|
||||
setLabelRowWidth((previous) => (Math.abs(previous - width) > 0.5 ? width : previous));
|
||||
setLabelRowHeight((previous) => (Math.abs(previous - height) > 0.5 ? height : previous));
|
||||
},
|
||||
[shouldMeasureNativeShimmer],
|
||||
);
|
||||
|
||||
const handleLabelLayout = useCallback(
|
||||
(event: LayoutChangeEvent) => {
|
||||
if (!shouldMeasureWebShimmer) {
|
||||
return;
|
||||
}
|
||||
const { x, width } = event.nativeEvent.layout;
|
||||
setLabelOffsetX((previous) => (Math.abs(previous - x) > 0.5 ? x : previous));
|
||||
setLabelWidth((previous) => (Math.abs(previous - width) > 0.5 ? width : previous));
|
||||
},
|
||||
[shouldMeasureWebShimmer],
|
||||
);
|
||||
|
||||
const handleSecondaryLayout = useCallback(
|
||||
(event: LayoutChangeEvent) => {
|
||||
if (!shouldMeasureWebShimmer || !secondaryLabel) {
|
||||
return;
|
||||
}
|
||||
const { x, width } = event.nativeEvent.layout;
|
||||
setSecondaryOffsetX((previous) => (Math.abs(previous - x) > 0.5 ? x : previous));
|
||||
setSecondaryWidth((previous) => (Math.abs(previous - width) > 0.5 ? width : previous));
|
||||
},
|
||||
[shouldMeasureWebShimmer, secondaryLabel],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isWebShimmer) {
|
||||
return;
|
||||
}
|
||||
ensureWebToolCallShimmerKeyframes();
|
||||
}, [isWebShimmer]);
|
||||
|
||||
useDetailWheelPropagationBlocker({
|
||||
detailWrapperRef,
|
||||
enabled: !isNative && isExpanded && hasDetailContent,
|
||||
});
|
||||
|
||||
const shimmerLabelStyle = useMemo<StyleProp<TextStyle>>(
|
||||
() =>
|
||||
buildShimmerTextStyle({
|
||||
isWebShimmer,
|
||||
webShimmerPeakWidth,
|
||||
shimmerDuration,
|
||||
webShimmerTrackStart,
|
||||
webShimmerTrackEnd,
|
||||
offsetX: labelOffsetX,
|
||||
}),
|
||||
[
|
||||
isWebShimmer,
|
||||
webShimmerPeakWidth,
|
||||
shimmerDuration,
|
||||
webShimmerTrackStart,
|
||||
webShimmerTrackEnd,
|
||||
labelOffsetX,
|
||||
],
|
||||
);
|
||||
|
||||
const shimmerSecondaryStyle = useMemo<StyleProp<TextStyle>>(
|
||||
() =>
|
||||
buildShimmerTextStyle({
|
||||
isWebShimmer,
|
||||
webShimmerPeakWidth,
|
||||
shimmerDuration,
|
||||
webShimmerTrackStart,
|
||||
webShimmerTrackEnd,
|
||||
offsetX: secondaryOffsetX,
|
||||
}),
|
||||
[
|
||||
isWebShimmer,
|
||||
webShimmerPeakWidth,
|
||||
shimmerDuration,
|
||||
webShimmerTrackStart,
|
||||
webShimmerTrackEnd,
|
||||
secondaryOffsetX,
|
||||
],
|
||||
);
|
||||
|
||||
const containerStyle = useMemo(
|
||||
() => [
|
||||
expandableBadgeStylesheet.container,
|
||||
@@ -2202,25 +1932,6 @@ export const ExpandableBadge = memo(function ExpandableBadge({
|
||||
[isActive],
|
||||
);
|
||||
|
||||
const shimmerLabelTextStyle = useMemo(
|
||||
() => [
|
||||
expandableBadgeStylesheet.label,
|
||||
isLoading && expandableBadgeStylesheet.labelLoading,
|
||||
expandableBadgeStylesheet.shimmerText,
|
||||
shimmerLabelStyle,
|
||||
],
|
||||
[isLoading, shimmerLabelStyle],
|
||||
);
|
||||
|
||||
const shimmerSecondaryTextStyle = useMemo(
|
||||
() => [
|
||||
expandableBadgeStylesheet.secondaryLabel,
|
||||
expandableBadgeStylesheet.shimmerText,
|
||||
shimmerSecondaryStyle,
|
||||
],
|
||||
[shimmerSecondaryStyle],
|
||||
);
|
||||
|
||||
const chevronStyle = useMemo(
|
||||
() => [
|
||||
expandableBadgeStylesheet.chevron,
|
||||
@@ -2269,20 +1980,7 @@ export const ExpandableBadge = memo(function ExpandableBadge({
|
||||
labelStyle={labelStyle}
|
||||
secondaryLabel={secondaryLabel}
|
||||
secondaryLabelStyle={secondaryLabelStyle}
|
||||
shouldMeasureWebShimmer={shouldMeasureWebShimmer}
|
||||
shouldMeasureNativeShimmer={shouldMeasureNativeShimmer}
|
||||
isWebShimmer={isWebShimmer}
|
||||
isNativeShimmer={isNativeShimmer}
|
||||
shimmerLabelTextStyle={shimmerLabelTextStyle}
|
||||
shimmerSecondaryTextStyle={shimmerSecondaryTextStyle}
|
||||
labelRowWidth={labelRowWidth}
|
||||
labelRowHeight={labelRowHeight}
|
||||
nativeShimmerPeakWidth={nativeShimmerPeakWidth}
|
||||
shimmerDuration={shimmerDuration}
|
||||
nativeGradientId={nativeGradientIdRef.current}
|
||||
onLabelRowLayout={handleLabelRowLayout}
|
||||
onLabelLayout={handleLabelLayout}
|
||||
onSecondaryLayout={handleSecondaryLayout}
|
||||
isLoading={isLoading}
|
||||
/>
|
||||
</Pressable>
|
||||
{onOpenFile && isHovered ? (
|
||||
|
||||
@@ -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<
|
||||
|
||||
@@ -555,6 +555,7 @@ function ProjectMenuItems({
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const toast = useToast();
|
||||
const localDaemonServerId = useLocalDaemonServerId();
|
||||
const handleOpenProjectSettings = useCallback(() => {
|
||||
if (!settingsTarget) return;
|
||||
router.navigate(buildProjectSettingsRoute(settingsTarget.serverId, settingsTarget.projectId));
|
||||
@@ -594,6 +595,7 @@ function ProjectMenuItems({
|
||||
</ProjectMenuItem>
|
||||
) : null}
|
||||
<OpenInFileManagerMenuItem
|
||||
serverId={localDaemonServerId}
|
||||
surface={surface}
|
||||
path={projectPath}
|
||||
testID={`sidebar-project-menu-open-folder-${projectViewKey}`}
|
||||
|
||||
@@ -268,6 +268,7 @@ function SidebarWorkspaceMenuItems({
|
||||
</DropdownMenuSubTrigger>
|
||||
) : null}
|
||||
<OpenInFileManagerMenuItem
|
||||
serverId={serverId}
|
||||
surface={surface}
|
||||
path={openInFileManagerPath}
|
||||
testID={`sidebar-workspace-menu-open-folder-${workspaceKey}`}
|
||||
|
||||
@@ -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,74 +0,0 @@
|
||||
import { useLayoutEffect, useState } from "react";
|
||||
import { makeMutable, type SharedValue, useSharedValue } from "react-native-reanimated";
|
||||
import { scheduleOnUI } from "react-native-worklets";
|
||||
import { useRetainedPanelActive } from "@/components/retained-panel";
|
||||
import { getStatusRingRotation } from "@/components/status-ring/geometry";
|
||||
|
||||
const sharedRotation = makeMutable(getStatusRingRotation(Date.now()));
|
||||
const activeRingCount = makeMutable(0);
|
||||
const clockRunning = makeMutable(false);
|
||||
let nextListenerId = 1;
|
||||
|
||||
function advanceSharedRotation(): void {
|
||||
"worklet";
|
||||
if (activeRingCount.value === 0) {
|
||||
clockRunning.value = false;
|
||||
return;
|
||||
}
|
||||
|
||||
sharedRotation.value = getStatusRingRotation(Date.now());
|
||||
requestAnimationFrame(advanceSharedRotation);
|
||||
}
|
||||
|
||||
function registerStatusRing(
|
||||
rotation: SharedValue<number>,
|
||||
registered: SharedValue<boolean>,
|
||||
listenerId: number,
|
||||
): void {
|
||||
"worklet";
|
||||
if (registered.value) {
|
||||
return;
|
||||
}
|
||||
|
||||
registered.value = true;
|
||||
rotation.value = getStatusRingRotation(Date.now());
|
||||
sharedRotation.addListener(listenerId, (value) => {
|
||||
rotation.value = value;
|
||||
});
|
||||
activeRingCount.value += 1;
|
||||
|
||||
if (!clockRunning.value) {
|
||||
clockRunning.value = true;
|
||||
sharedRotation.value = getStatusRingRotation(Date.now());
|
||||
requestAnimationFrame(advanceSharedRotation);
|
||||
}
|
||||
}
|
||||
|
||||
function unregisterStatusRing(registered: SharedValue<boolean>, listenerId: number): void {
|
||||
"worklet";
|
||||
if (!registered.value) {
|
||||
return;
|
||||
}
|
||||
|
||||
registered.value = false;
|
||||
sharedRotation.removeListener(listenerId);
|
||||
activeRingCount.value -= 1;
|
||||
}
|
||||
|
||||
export function useStatusRingRotation(): SharedValue<number> {
|
||||
const active = useRetainedPanelActive();
|
||||
// Hidden retained views must not subscribe their animated styles to the shared clock.
|
||||
const rotation = useSharedValue(getStatusRingRotation(Date.now()));
|
||||
const registered = useSharedValue(false);
|
||||
const [listenerId] = useState(() => nextListenerId++);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (!active) return;
|
||||
scheduleOnUI(registerStatusRing, rotation, registered, listenerId);
|
||||
return () => {
|
||||
scheduleOnUI(unregisterStatusRing, registered, listenerId);
|
||||
};
|
||||
}, [active, listenerId, registered, rotation]);
|
||||
|
||||
return rotation;
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
import { useCallback, useLayoutEffect, useRef, type RefCallback } from "react";
|
||||
import type { View as NativeView } from "react-native";
|
||||
import { STATUS_RING_PERIOD_MS } from "@/components/status-ring/geometry";
|
||||
|
||||
const STATUS_RING_KEYFRAMES: PropertyIndexedKeyframes = {
|
||||
transform: ["rotate(0deg)", "rotate(360deg)"],
|
||||
};
|
||||
const STATUS_RING_TIMING: KeyframeAnimationOptions = {
|
||||
duration: STATUS_RING_PERIOD_MS,
|
||||
easing: "linear",
|
||||
iterations: Number.POSITIVE_INFINITY,
|
||||
};
|
||||
const STATUS_RING_TIMELINE_START_MS = 0;
|
||||
|
||||
export function useStatusRingAnimationRef(): RefCallback<NativeView> {
|
||||
const arcElement = useRef<HTMLElement | null>(null);
|
||||
const setArcElement = useCallback((instance: NativeView | null) => {
|
||||
arcElement.current = instance instanceof HTMLElement ? instance : null;
|
||||
}, []);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const element = arcElement.current;
|
||||
if (!element) {
|
||||
return;
|
||||
}
|
||||
|
||||
const animation = element.animate(STATUS_RING_KEYFRAMES, STATUS_RING_TIMING);
|
||||
animation.startTime = STATUS_RING_TIMELINE_START_MS;
|
||||
return () => {
|
||||
animation.cancel();
|
||||
};
|
||||
}, []);
|
||||
|
||||
return setArcElement;
|
||||
}
|
||||
@@ -32,7 +32,7 @@ export interface StatusRingProps {
|
||||
*/
|
||||
export function StatusRingFrame({ backdrop, children }: StatusRingProps & { children: ReactNode }) {
|
||||
return (
|
||||
<View style={[styles.frame, getBackdropStyle(backdrop)]}>
|
||||
<View style={[styles.frame, getBackdropStyle(backdrop)]} testID="status-ring">
|
||||
<View style={styles.track} />
|
||||
{children}
|
||||
<View style={styles.centerDot} />
|
||||
@@ -60,10 +60,9 @@ function getBackdropStyle(backdrop: SurfaceBackdrop | null | undefined) {
|
||||
}
|
||||
|
||||
// The rotating quarter's geometry, deliberately plain React Native rather than Unistyles: on
|
||||
// native this style lands on a Reanimated `Animated.View`, and applying a theme-tracked style to
|
||||
// one crashes when the theme changes — Unistyles and Reanimated both mutate the same native node.
|
||||
// See docs/unistyles.md. The colour it needs lives on `styles.arc`, one level in, on a view
|
||||
// Reanimated never touches.
|
||||
// native this style lands on an `Animated.View` the native animation driver writes to, and a
|
||||
// theme-tracked style on the same node gives it two writers. See docs/unistyles.md. The colour it
|
||||
// needs lives on `styles.arc`, one level in, on a view nothing animates.
|
||||
export const rotatorStyles = RNStyleSheet.create({
|
||||
rotator: {
|
||||
position: "absolute",
|
||||
|
||||
@@ -26,17 +26,11 @@ export const STATUS_RING_FRAME_SIZE = STATUS_RING_SIZE + STATUS_RING_HALO_INSET
|
||||
export const STATUS_RING_TRACK_OPACITY = 0.3;
|
||||
export const STATUS_RING_HEAD_OPACITY = 0.9;
|
||||
|
||||
// One period for every ring in the app. Each platform owns one mount-independent timeline: web
|
||||
// animations share an absolute document-timeline start, while native publishes this wall-clock
|
||||
// phase from one UI-thread clock. A row that appears mid-flight therefore lands in step with the
|
||||
// rings already turning.
|
||||
// One period for every ring in the app. Each platform runs the rings off one clock that does not
|
||||
// depend on when a ring mounted, so a row that appears mid-flight lands in step with the rings
|
||||
// already turning.
|
||||
export const STATUS_RING_PERIOD_MS = 900;
|
||||
|
||||
export function getStatusRingRotation(nowMs: number): number {
|
||||
"worklet";
|
||||
return ((nowMs % STATUS_RING_PERIOD_MS) / STATUS_RING_PERIOD_MS) * 360;
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-anchors a corner status dot's offset for the ring that replaces it.
|
||||
*
|
||||
|
||||
@@ -1,30 +1,31 @@
|
||||
import { memo } from "react";
|
||||
import { View } from "react-native";
|
||||
import Animated, { useAnimatedStyle } from "react-native-reanimated";
|
||||
import { Animated, View } from "react-native";
|
||||
import { useIndicatorMotion } from "@/components/indicator-motion";
|
||||
import { sharedIndicatorClock, useRunningClock } from "@/components/indicator-motion/clock";
|
||||
import {
|
||||
StatusRingFrame,
|
||||
type StatusRingProps,
|
||||
rotatorStyles,
|
||||
styles,
|
||||
} from "@/components/status-ring/frame";
|
||||
import { useStatusRingRotation } from "@/components/status-ring/clock";
|
||||
import { STATUS_RING_PERIOD_MS } from "@/components/status-ring/geometry";
|
||||
|
||||
/**
|
||||
* Native running indicator. The rotation is published by one shared UI-thread clock rather than
|
||||
* per-instance timing, so a ring that mounts mid-flight is already in phase — see `clock.ts`.
|
||||
*
|
||||
* The rotated view carries no theme-tracked style; the coloured arc is nested inside it. Putting
|
||||
* a Unistyles style on a Reanimated view crashes on theme change (docs/unistyles.md).
|
||||
*/
|
||||
// One rotation for every ring in the app, so a row that appears mid-flight lands in step with the
|
||||
// rings already turning.
|
||||
const rotation = sharedIndicatorClock.cycle(STATUS_RING_PERIOD_MS).interpolate({
|
||||
inputRange: [0, STATUS_RING_PERIOD_MS],
|
||||
outputRange: ["0deg", "360deg"],
|
||||
});
|
||||
const turning = { transform: [{ rotate: rotation }] };
|
||||
|
||||
/** Native running indicator. The native animation driver turns the quarter; see `clock.ts`. */
|
||||
export const StatusRing = memo(function StatusRing({ backdrop }: StatusRingProps) {
|
||||
const rotation = useStatusRingRotation();
|
||||
const rotatorStyle = useAnimatedStyle(() => ({
|
||||
transform: [{ rotate: `${rotation.value}deg` }],
|
||||
}));
|
||||
const moving = useIndicatorMotion();
|
||||
useRunningClock(sharedIndicatorClock, moving);
|
||||
|
||||
return (
|
||||
<StatusRingFrame backdrop={backdrop}>
|
||||
<Animated.View style={[rotatorStyles.rotator, rotatorStyle]}>
|
||||
<Animated.View style={[rotatorStyles.rotator, moving && turning]}>
|
||||
<View style={styles.arc} />
|
||||
</Animated.View>
|
||||
</StatusRingFrame>
|
||||
|
||||
@@ -1,20 +1,27 @@
|
||||
import { memo } from "react";
|
||||
import { View } from "react-native";
|
||||
import { useIndicatorMotion } from "@/components/indicator-motion";
|
||||
import { type IndicatorLoop, useIndicatorLoop } from "@/components/indicator-motion/loop.web";
|
||||
import {
|
||||
StatusRingFrame,
|
||||
type StatusRingProps,
|
||||
rotatorStyles,
|
||||
styles,
|
||||
} from "@/components/status-ring/frame";
|
||||
import { useStatusRingAnimationRef } from "@/components/status-ring/clock.web";
|
||||
import { STATUS_RING_PERIOD_MS } from "@/components/status-ring/geometry";
|
||||
|
||||
/**
|
||||
* Web running indicator. A sidebar full of agents can hold dozens of these at once, so the browser
|
||||
* drives the rotation from one absolute document-timeline epoch rather than from mount time — see
|
||||
* `clock.web.ts`.
|
||||
*/
|
||||
// A sidebar full of agents can hold dozens of rings at once; the shared phase keeps them turning as
|
||||
// one, and a row that appears mid-flight lands in step with the rings already turning.
|
||||
const TURNING: IndicatorLoop = {
|
||||
keyframes: [{ transform: "rotate(0deg)" }, { transform: "rotate(360deg)" }],
|
||||
durationMs: STATUS_RING_PERIOD_MS,
|
||||
phase: "shared",
|
||||
};
|
||||
|
||||
/** Web running indicator. The browser's compositor turns the quarter; see `loop.web.ts`. */
|
||||
export const StatusRing = memo(function StatusRing({ backdrop }: StatusRingProps) {
|
||||
const rotatorRef = useStatusRingAnimationRef();
|
||||
const moving = useIndicatorMotion();
|
||||
const rotatorRef = useIndicatorLoop(moving ? TURNING : null);
|
||||
|
||||
return (
|
||||
<StatusRingFrame backdrop={backdrop}>
|
||||
|
||||
@@ -1,184 +0,0 @@
|
||||
import { useLayoutEffect, useMemo, useState } from "react";
|
||||
import { View } from "react-native";
|
||||
import Animated, {
|
||||
makeMutable,
|
||||
type SharedValue,
|
||||
useAnimatedStyle,
|
||||
useReducedMotion,
|
||||
useSharedValue,
|
||||
} from "react-native-reanimated";
|
||||
import { scheduleOnUI } from "react-native-worklets";
|
||||
import { useRetainedPanelActive } from "@/components/retained-panel";
|
||||
import {
|
||||
SYNCED_LOADER_DOT_COUNT,
|
||||
getSyncedLoaderDotOpacity,
|
||||
getSyncedLoaderStep,
|
||||
} from "@/components/synced-loader-state";
|
||||
|
||||
const GRID_COLUMNS = 2;
|
||||
const DOT_KEYS = Array.from({ length: SYNCED_LOADER_DOT_COUNT }, (_, i) => `dot-${i}`);
|
||||
const sharedStep = makeMutable(0);
|
||||
const activeLoaderCount = makeMutable(0);
|
||||
const clockRunning = makeMutable(false);
|
||||
let nextStepListenerId = 1;
|
||||
|
||||
function advanceSharedStep(): void {
|
||||
"worklet";
|
||||
if (activeLoaderCount.value === 0) {
|
||||
clockRunning.value = false;
|
||||
return;
|
||||
}
|
||||
|
||||
const nextStep = getSyncedLoaderStep(Date.now());
|
||||
if (sharedStep.value !== nextStep) {
|
||||
sharedStep.value = nextStep;
|
||||
}
|
||||
requestAnimationFrame(advanceSharedStep);
|
||||
}
|
||||
|
||||
function registerStepListener(
|
||||
step: SharedValue<number>,
|
||||
registered: SharedValue<boolean>,
|
||||
listenerId: number,
|
||||
): void {
|
||||
"worklet";
|
||||
if (registered.value) {
|
||||
return;
|
||||
}
|
||||
|
||||
registered.value = true;
|
||||
step.value = getSyncedLoaderStep(Date.now());
|
||||
sharedStep.addListener(listenerId, (nextStep) => {
|
||||
step.value = nextStep;
|
||||
});
|
||||
activeLoaderCount.value += 1;
|
||||
|
||||
if (!clockRunning.value) {
|
||||
clockRunning.value = true;
|
||||
sharedStep.value = step.value;
|
||||
requestAnimationFrame(advanceSharedStep);
|
||||
}
|
||||
}
|
||||
|
||||
function unregisterStepListener(registered: SharedValue<boolean>, listenerId: number): void {
|
||||
"worklet";
|
||||
if (!registered.value) {
|
||||
return;
|
||||
}
|
||||
|
||||
registered.value = false;
|
||||
sharedStep.removeListener(listenerId);
|
||||
activeLoaderCount.value -= 1;
|
||||
}
|
||||
|
||||
function useSyncedLoaderStep(active: boolean, reduceMotion: boolean): SharedValue<number> {
|
||||
// The local value lets retained loaders detach from the app-wide clock without
|
||||
// unmounting their animated views or leaving hidden style worklets subscribed.
|
||||
const step = useSharedValue(reduceMotion ? 0 : getSyncedLoaderStep(Date.now()));
|
||||
const registered = useSharedValue(false);
|
||||
const [listenerId] = useState(() => nextStepListenerId++);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (!active || reduceMotion) {
|
||||
return;
|
||||
}
|
||||
|
||||
scheduleOnUI(registerStepListener, step, registered, listenerId);
|
||||
return () => {
|
||||
scheduleOnUI(unregisterStepListener, registered, listenerId);
|
||||
};
|
||||
}, [active, listenerId, reduceMotion, registered, step]);
|
||||
|
||||
return step;
|
||||
}
|
||||
|
||||
export function SyncedLoader({ size = 10, color }: { size?: number; color: string }) {
|
||||
const active = useRetainedPanelActive();
|
||||
const reduceMotion = useReducedMotion();
|
||||
const step = useSyncedLoaderStep(active, reduceMotion);
|
||||
|
||||
// The 2x3 grid fills `size` exactly on its long axis: the dot is whatever is left after
|
||||
// the two gaps, not a floored integer. Flooring cost the grid up to a third of a dot per
|
||||
// row — at size 10 it drew 8pt of ink in a 10pt box and read as a small mark in a large
|
||||
// slot. Fractional dots are fine here; these are sub-pixel radii on a moving glyph.
|
||||
const gap = Math.max(1, Math.round(size * 0.12));
|
||||
const dotSize = Math.max(2, (size - gap * 2) / 3);
|
||||
const gridWidth = dotSize * 2 + gap;
|
||||
const gridHeight = dotSize * 3 + gap * 2;
|
||||
|
||||
const gridStyle = useMemo(
|
||||
() => ({ width: gridWidth, height: gridHeight }),
|
||||
[gridHeight, gridWidth],
|
||||
);
|
||||
const containerStyle = useMemo(
|
||||
() =>
|
||||
({
|
||||
width: size,
|
||||
height: size,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
}) as const,
|
||||
[size],
|
||||
);
|
||||
|
||||
return (
|
||||
<View style={containerStyle}>
|
||||
<View style={gridStyle}>
|
||||
{Array.from({ length: SYNCED_LOADER_DOT_COUNT }).map((_, dotIndex) => {
|
||||
const rowIndex = Math.floor(dotIndex / GRID_COLUMNS);
|
||||
const columnIndex = dotIndex % GRID_COLUMNS;
|
||||
|
||||
return (
|
||||
<SpinnerDot
|
||||
key={DOT_KEYS[dotIndex]}
|
||||
color={color}
|
||||
dotSize={dotSize}
|
||||
dotIndex={dotIndex}
|
||||
step={step}
|
||||
left={columnIndex * (dotSize + gap)}
|
||||
top={rowIndex * (dotSize + gap)}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function SpinnerDot({
|
||||
color,
|
||||
dotSize,
|
||||
dotIndex,
|
||||
step,
|
||||
left,
|
||||
top,
|
||||
}: {
|
||||
color: string;
|
||||
dotSize: number;
|
||||
dotIndex: number;
|
||||
step: SharedValue<number>;
|
||||
left: number;
|
||||
top: number;
|
||||
}) {
|
||||
const animatedStyle = useAnimatedStyle(() => ({
|
||||
opacity: getSyncedLoaderDotOpacity(step.value, dotIndex),
|
||||
}));
|
||||
|
||||
const dotStyle = useMemo(
|
||||
() => [
|
||||
animatedStyle,
|
||||
{
|
||||
width: dotSize,
|
||||
height: dotSize,
|
||||
borderRadius: dotSize / 2,
|
||||
backgroundColor: color,
|
||||
position: "absolute" as const,
|
||||
left,
|
||||
top,
|
||||
},
|
||||
],
|
||||
[animatedStyle, dotSize, color, left, top],
|
||||
);
|
||||
|
||||
return <Animated.View style={dotStyle} />;
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import { useEffect } from "react";
|
||||
import { Animated, View } from "react-native";
|
||||
import { useIndicatorMotion } from "@/components/indicator-motion";
|
||||
import { type SyncedLoaderProps, useSyncedLoaderLayout } from "./layout";
|
||||
import {
|
||||
SYNCED_LOADER_DOT_COUNT,
|
||||
SYNCED_LOADER_RESTING_STEP,
|
||||
getSyncedLoaderDotOpacity,
|
||||
} from "./state";
|
||||
import { createSyncedLoaderStepTicker } from "./step-ticker";
|
||||
|
||||
const DOTS = Array.from({ length: SYNCED_LOADER_DOT_COUNT }, (_, dot) => dot);
|
||||
const STEPS = DOTS;
|
||||
|
||||
// The step every loader in the app is on. It lives in the native animation driver: setting it
|
||||
// updates the dots on the UI thread without a React render or a shadow tree commit.
|
||||
const step = new Animated.Value(SYNCED_LOADER_RESTING_STEP, { useNativeDriver: true });
|
||||
const ticker = createSyncedLoaderStepTicker((nextStep) => step.setValue(nextStep));
|
||||
|
||||
const blinking = DOTS.map((dot) => ({
|
||||
opacity: step.interpolate({
|
||||
inputRange: STEPS,
|
||||
outputRange: STEPS.map((atStep) => getSyncedLoaderDotOpacity(atStep, dot)),
|
||||
}),
|
||||
}));
|
||||
|
||||
const resting = DOTS.map((dot) => ({
|
||||
opacity: getSyncedLoaderDotOpacity(SYNCED_LOADER_RESTING_STEP, dot),
|
||||
}));
|
||||
|
||||
/**
|
||||
* Native loader. The step changes six times a cycle, so a timer wakes the JS thread six times a
|
||||
* cycle and hands the step to the native animation driver. No frame callback runs between steps.
|
||||
*/
|
||||
export function SyncedLoader(props: SyncedLoaderProps) {
|
||||
const layout = useSyncedLoaderLayout(props);
|
||||
const moving = useIndicatorMotion();
|
||||
const motion = moving ? blinking : resting;
|
||||
|
||||
useEffect(() => {
|
||||
if (!moving) return;
|
||||
return ticker.run();
|
||||
}, [moving]);
|
||||
|
||||
return (
|
||||
<View style={layout.container} testID="synced-loader">
|
||||
<View style={layout.grid}>
|
||||
{DOTS.map((dot) => (
|
||||
<Animated.View
|
||||
key={dot}
|
||||
style={[layout.dots[dot], motion[dot]]}
|
||||
testID="synced-loader-dot"
|
||||
/>
|
||||
))}
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import { View, type ViewStyle } from "react-native";
|
||||
import { useIndicatorMotion } from "@/components/indicator-motion";
|
||||
import { type IndicatorLoop, useIndicatorLoop } from "@/components/indicator-motion/loop.web";
|
||||
import { type SyncedLoaderProps, useSyncedLoaderLayout } from "./layout";
|
||||
import {
|
||||
SYNCED_LOADER_DOT_COUNT,
|
||||
SYNCED_LOADER_DURATION_MS,
|
||||
SYNCED_LOADER_RESTING_STEP,
|
||||
getSyncedLoaderDotOpacity,
|
||||
} from "./state";
|
||||
|
||||
const DOTS = Array.from({ length: SYNCED_LOADER_DOT_COUNT }, (_, dot) => dot);
|
||||
|
||||
// One keyframe per step, held until the next: `step-end` makes the opacity jump instead of fade.
|
||||
// The shared phase keeps every loader in the app on the same step.
|
||||
const BLINKING: IndicatorLoop[] = DOTS.map((dot) => ({
|
||||
keyframes: [
|
||||
...DOTS.map((step) => ({
|
||||
offset: step / SYNCED_LOADER_DOT_COUNT,
|
||||
opacity: getSyncedLoaderDotOpacity(step, dot),
|
||||
easing: "step-end",
|
||||
})),
|
||||
{ offset: 1, opacity: getSyncedLoaderDotOpacity(0, dot) },
|
||||
],
|
||||
durationMs: SYNCED_LOADER_DURATION_MS,
|
||||
phase: "shared",
|
||||
}));
|
||||
|
||||
const RESTING = DOTS.map(
|
||||
(dot): ViewStyle => ({ opacity: getSyncedLoaderDotOpacity(SYNCED_LOADER_RESTING_STEP, dot) }),
|
||||
);
|
||||
|
||||
/**
|
||||
* Web loader. Each dot steps through its six opacities on the browser's compositor, which draws a
|
||||
* frame when a step changes and nothing in between; see `loop.web.ts`.
|
||||
*/
|
||||
export function SyncedLoader(props: SyncedLoaderProps) {
|
||||
const layout = useSyncedLoaderLayout(props);
|
||||
const moving = useIndicatorMotion();
|
||||
|
||||
return (
|
||||
<View style={layout.container} testID="synced-loader">
|
||||
<View style={layout.grid}>
|
||||
{DOTS.map((dot) => (
|
||||
<Dot key={dot} dot={dot} style={layout.dots[dot]} moving={moving} />
|
||||
))}
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function Dot({ dot, style, moving }: { dot: number; style: ViewStyle; moving: boolean }) {
|
||||
const dotRef = useIndicatorLoop(moving ? BLINKING[dot] : null);
|
||||
return <View ref={dotRef} style={[style, RESTING[dot]]} testID="synced-loader-dot" />;
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { useMemo } from "react";
|
||||
import type { ViewStyle } from "react-native";
|
||||
import { SYNCED_LOADER_DOT_COUNT } from "./state";
|
||||
|
||||
const GRID_COLUMNS = 2;
|
||||
|
||||
export interface SyncedLoaderProps {
|
||||
size?: number;
|
||||
color: string;
|
||||
}
|
||||
|
||||
export interface SyncedLoaderLayout {
|
||||
container: ViewStyle;
|
||||
grid: ViewStyle;
|
||||
/** One entry per dot, in the order the opacity states list them. */
|
||||
dots: ViewStyle[];
|
||||
}
|
||||
|
||||
/** Where the loader's six dots sit and what they look like. The platform files own how they blink. */
|
||||
export function useSyncedLoaderLayout({ size = 10, color }: SyncedLoaderProps): SyncedLoaderLayout {
|
||||
return useMemo(() => {
|
||||
// The 2x3 grid fills `size` exactly on its long axis: the dot is whatever is left after
|
||||
// the two gaps, not a floored integer. Flooring cost the grid up to a third of a dot per
|
||||
// row — at size 10 it drew 8pt of ink in a 10pt box and read as a small mark in a large
|
||||
// slot. Fractional dots are fine here; these are sub-pixel radii on a moving glyph.
|
||||
const gap = Math.max(1, Math.round(size * 0.12));
|
||||
const dotSize = Math.max(2, (size - gap * 2) / 3);
|
||||
|
||||
return {
|
||||
container: { width: size, height: size, alignItems: "center", justifyContent: "center" },
|
||||
grid: { width: dotSize * 2 + gap, height: dotSize * 3 + gap * 2 },
|
||||
dots: Array.from({ length: SYNCED_LOADER_DOT_COUNT }, (_, dot) => ({
|
||||
position: "absolute",
|
||||
left: (dot % GRID_COLUMNS) * (dotSize + gap),
|
||||
top: Math.floor(dot / GRID_COLUMNS) * (dotSize + gap),
|
||||
width: dotSize,
|
||||
height: dotSize,
|
||||
borderRadius: dotSize / 2,
|
||||
backgroundColor: color,
|
||||
})),
|
||||
};
|
||||
}, [color, size]);
|
||||
}
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { getSyncedLoaderDotOpacity, getSyncedLoaderStep } from "./synced-loader-state";
|
||||
import { getSyncedLoaderDotOpacity, getSyncedLoaderStep } from "./state";
|
||||
|
||||
describe("synced loader state", () => {
|
||||
test("advances through six wall-clock-aligned steps every 950 milliseconds", () => {
|
||||
+12
-3
@@ -1,4 +1,4 @@
|
||||
const SYNCED_LOADER_DURATION_MS = 950;
|
||||
export const SYNCED_LOADER_DURATION_MS = 950;
|
||||
export const SYNCED_LOADER_DOT_COUNT = 6;
|
||||
|
||||
const SYNCED_LOADER_OPACITY_STATES = [
|
||||
@@ -10,13 +10,22 @@ const SYNCED_LOADER_OPACITY_STATES = [
|
||||
[0, 0, 1, 0.34, 0.78, 0.56],
|
||||
] as const;
|
||||
|
||||
// The frame a loader rests on when it is not moving.
|
||||
export const SYNCED_LOADER_RESTING_STEP = 0;
|
||||
|
||||
export function getSyncedLoaderStep(nowMs: number): number {
|
||||
"worklet";
|
||||
const elapsedMs = nowMs % SYNCED_LOADER_DURATION_MS;
|
||||
return Math.floor((elapsedMs * SYNCED_LOADER_DOT_COUNT) / SYNCED_LOADER_DURATION_MS);
|
||||
}
|
||||
|
||||
/** How long after `nowMs` the loader shows its next step. Always at least a millisecond. */
|
||||
export function getSyncedLoaderStepRemainingMs(nowMs: number): number {
|
||||
const elapsedMs = nowMs % SYNCED_LOADER_DURATION_MS;
|
||||
const nextStepAtMs =
|
||||
((getSyncedLoaderStep(nowMs) + 1) * SYNCED_LOADER_DURATION_MS) / SYNCED_LOADER_DOT_COUNT;
|
||||
return Math.max(1, Math.ceil(nextStepAtMs - elapsedMs));
|
||||
}
|
||||
|
||||
export function getSyncedLoaderDotOpacity(step: number, dot: number): number {
|
||||
"worklet";
|
||||
return SYNCED_LOADER_OPACITY_STATES[step]?.[dot] ?? 0;
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
|
||||
import { createSyncedLoaderStepTicker } from "./step-ticker";
|
||||
|
||||
interface PublishedStep {
|
||||
step: number;
|
||||
atMs: number;
|
||||
}
|
||||
|
||||
function startRecordingTicker() {
|
||||
const published: PublishedStep[] = [];
|
||||
const ticker = createSyncedLoaderStepTicker((step) => {
|
||||
published.push({ step, atMs: Date.now() });
|
||||
});
|
||||
return { ticker, published };
|
||||
}
|
||||
|
||||
describe("synced loader step ticker", () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(0);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
test("wakes once per step, six times a cycle", () => {
|
||||
const { ticker, published } = startRecordingTicker();
|
||||
|
||||
const stop = ticker.run();
|
||||
vi.advanceTimersByTime(949);
|
||||
stop();
|
||||
|
||||
expect(published).toEqual([
|
||||
{ step: 0, atMs: 0 },
|
||||
{ step: 1, atMs: 159 },
|
||||
{ step: 2, atMs: 317 },
|
||||
{ step: 3, atMs: 475 },
|
||||
{ step: 4, atMs: 634 },
|
||||
{ step: 5, atMs: 792 },
|
||||
]);
|
||||
});
|
||||
|
||||
test("starts mid-cycle on the step the wall clock is on", () => {
|
||||
vi.setSystemTime(950 * 4 + 500);
|
||||
const { ticker, published } = startRecordingTicker();
|
||||
|
||||
const stop = ticker.run();
|
||||
vi.advanceTimersByTime(140);
|
||||
stop();
|
||||
|
||||
expect(published).toEqual([
|
||||
{ step: 3, atMs: 950 * 4 + 500 },
|
||||
{ step: 4, atMs: 950 * 4 + 634 },
|
||||
]);
|
||||
});
|
||||
|
||||
test("catches up to the wall clock after a late wake-up instead of drifting", () => {
|
||||
const { ticker, published } = startRecordingTicker();
|
||||
|
||||
const stop = ticker.run();
|
||||
// The thread is busy for 400 ms, so the wake-up due at 159 ms happens at 559 ms.
|
||||
vi.setSystemTime(400);
|
||||
vi.advanceTimersByTime(159);
|
||||
vi.advanceTimersByTime(75);
|
||||
stop();
|
||||
|
||||
expect(published).toEqual([
|
||||
{ step: 0, atMs: 0 },
|
||||
{ step: 3, atMs: 559 },
|
||||
{ step: 4, atMs: 634 },
|
||||
]);
|
||||
});
|
||||
|
||||
test("keeps one timer for every loader and stops with the last one", () => {
|
||||
const { ticker, published } = startRecordingTicker();
|
||||
|
||||
const stopFirst = ticker.run();
|
||||
const stopSecond = ticker.run();
|
||||
vi.advanceTimersByTime(160);
|
||||
expect(published.map((entry) => entry.step)).toEqual([0, 1]);
|
||||
expect(vi.getTimerCount()).toBe(1);
|
||||
|
||||
stopFirst();
|
||||
vi.advanceTimersByTime(158);
|
||||
expect(published.map((entry) => entry.step)).toEqual([0, 1, 2]);
|
||||
|
||||
stopSecond();
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
vi.advanceTimersByTime(950);
|
||||
expect(published.map((entry) => entry.step)).toEqual([0, 1, 2]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,42 @@
|
||||
import { getSyncedLoaderStep, getSyncedLoaderStepRemainingMs } from "./state";
|
||||
|
||||
/**
|
||||
* Publishes the loader's step each time it changes, and at no other time.
|
||||
*
|
||||
* The loader has six frames a cycle, so it needs six wake-ups a cycle. Each wake-up reads the wall
|
||||
* clock and sleeps until the next step is due, which keeps a late timer from pushing every later
|
||||
* step back and keeps every loader in the app on the same step.
|
||||
*/
|
||||
export interface SyncedLoaderStepTicker {
|
||||
/** Ticks until the returned function is called. Publishes the current step at once. */
|
||||
run(): () => void;
|
||||
}
|
||||
|
||||
export function createSyncedLoaderStepTicker(
|
||||
publish: (step: number) => void,
|
||||
): SyncedLoaderStepTicker {
|
||||
let runners = 0;
|
||||
let timer: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
function tick(): void {
|
||||
const nowMs = Date.now();
|
||||
publish(getSyncedLoaderStep(nowMs));
|
||||
timer = setTimeout(tick, getSyncedLoaderStepRemainingMs(nowMs));
|
||||
}
|
||||
|
||||
return {
|
||||
run() {
|
||||
runners += 1;
|
||||
if (timer === null) {
|
||||
tick();
|
||||
}
|
||||
return () => {
|
||||
runners -= 1;
|
||||
if (runners === 0 && timer !== null) {
|
||||
clearTimeout(timer);
|
||||
timer = null;
|
||||
}
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -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],
|
||||
);
|
||||
|
||||
@@ -1583,7 +1583,11 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
|
||||
const autoSend = sendAfterTranscriptRef.current;
|
||||
sendAfterTranscriptRef.current = false;
|
||||
applyDictationTranscript(text, {
|
||||
value: valueRef.current,
|
||||
input: getComposerInputSnapshot(
|
||||
textInputRef.current,
|
||||
valueRef.current,
|
||||
selectionRef.current,
|
||||
),
|
||||
defaultSendBehavior,
|
||||
isAgentRunning,
|
||||
onQueue,
|
||||
|
||||
@@ -172,11 +172,37 @@ describe("dictation keyboard behavior", () => {
|
||||
});
|
||||
|
||||
describe("dictation transcript behavior", () => {
|
||||
it("inserts dictated words into the paragraph at the cursor", () => {
|
||||
const value = "Intro: \n\nKeep this as the second paragraph.";
|
||||
let draft = value;
|
||||
let selection = { start: 7, end: 7 };
|
||||
|
||||
applyDictationTranscript("Spoken words.", {
|
||||
input: { text: value, selection: { start: 7, end: 7 } },
|
||||
defaultSendBehavior: "interrupt" as const,
|
||||
isAgentRunning: false,
|
||||
onQueue: undefined,
|
||||
replaceText: (text, caret) => {
|
||||
draft = text;
|
||||
selection = caret ?? selection;
|
||||
},
|
||||
onSubmit: () => {
|
||||
throw new Error("Insert must leave the message unsent");
|
||||
},
|
||||
attachments: [],
|
||||
cwd: "/repo",
|
||||
autoSend: false,
|
||||
});
|
||||
|
||||
expect(draft).toBe("Intro: Spoken words.\n\nKeep this as the second paragraph.");
|
||||
expect(selection).toEqual({ start: 20, end: 20 });
|
||||
});
|
||||
|
||||
it("publishes an auto-sent transcript to the composer before submitting it", () => {
|
||||
const actions: string[] = [];
|
||||
|
||||
applyDictationTranscript("spoken prompt", {
|
||||
value: "typed context",
|
||||
input: { text: "typed context", selection: { start: 13, end: 13 } },
|
||||
defaultSendBehavior: "interrupt",
|
||||
isAgentRunning: false,
|
||||
onQueue: undefined,
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user