Compare commits

..
Author SHA1 Message Date
paseo-bot[bot]andClaude Opus 5.5 878a89b10e test(android): build panel edge tests on the shared mounting context
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 09:33:28 +00:00
paseo-bot[bot]andClaude Opus 5.5 e167602ac5 chore: update panel scrolling branch from main
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 09:12:16 +00:00
965e28e3d6 feat(highlight): add diff/patch and zero-dependency legacy-mode syntax highlighting (#11026)
* feat(highlight): highlight diff and patch fences and files

Register CodeMirror's legacy diff mode for .diff and .patch files and diff/patch code fences, mapping inserted/deleted tokens to diffAddition/diffDeletion roles and stripping legacy trailing-whitespace error prefixes so CodeMirror emits no unknown-tag warnings.

Co-authored-by: Hyacinthe Malaspina <malaspina.hyacinthe@gmail.com>

* feat(highlight): add Ruby syntax highlighting

Register @codemirror/legacy-modes ruby via StreamLanguage for rb, rbw, rake,
gemspec, ru, jbuilder, podspec and thor, plus extensionless Ruby files
(Gemfile, Rakefile, Guardfile, Capfile, Podfile, Vagrantfile, ...).

* feat(highlight): add Kotlin syntax highlighting for .kt/.kts files

Kotlin files previously rendered as plain text in diffs, the read-only
source panel, and the editor because the extension map in
@getpaseo/highlight had no entry for kt/kts. Register the kotlin stream
parser from @codemirror/legacy-modes/mode/clike, the same package already
used for Swift and Dart.

* test(highlight): assert Kotlin token styles in highlightCode

Follow-up to review feedback: the parsers tests only checked that
kt/kts are registered. Add a Kotlin case to the highlightCode suite,
mirroring the Swift and Dart cases, asserting keyword ('class', 'val'),
type ('String'), and string token styles. Fails on main without the
parser registration, passes with it.

* feat(highlight): add TOML syntax highlighting

* feat(highlight): add remaining legacy-mode languages and fence aliases

Register SQL, Lua, Protobuf, PowerShell, Groovy/Gradle, Scala, CMake (including CMakeLists.txt), Properties/INI, R, Perl, and LaTeX/TeX from @codemirror/legacy-modes, and add fence alias parity (including shell, ruby, kotlin, powershell/pwsh, protobuf, perl, and latex) in HighlightedCodeBlock.

Co-authored-by: Maxime Conan <maximeconan@MacBook-Pro-de-Maxime.local>

* fix(highlight): unify diff token colors and support binary diff frames

Append diffAddition and diffDeletion to DIFF_HIGHLIGHT_STYLES so Changes panel binary diff frames preserve diff colors for .diff/.patch files while older clients safely decode unknown indices as null. Unify syntaxTokenStyles onto theme.colors.syntax and tune light syntax theme diff colors to >=4.0:1 contrast on code surfaces.

---------

Co-authored-by: Hyacinthe Malaspina <malaspina.hyacinthe@gmail.com>
Co-authored-by: Karol Bąk <kukicola@gmail.com>
Co-authored-by: Anton Prokhorov <anton.prokhorov@jetbrains.com>
Co-authored-by: chandlerok <chandleroking@gmail.com>
Co-authored-by: Maxime Conan <maximeconan@MacBook-Pro-de-Maxime.local>
2026-11-27 15:31:57 +07:00
Mohamed Boudra 690f6970c3 fix(app): focus composer when dropping attachments (#11022)
Workspace file drops already called focusInput(), but raster image drops went directly to addImages() and generic file drops only uploaded without focusing. Focus the composer when dropped images attach and as soon as dropped files are accepted for upload, so users can type right away without waiting for uploads to finish.
2026-11-27 14:33:30 +07:00
paseo-bot[bot] bcb0097344 test(terminal): accept socket-overflow output that arrives after the replay (#11016)
The PTY child finishing its write does not mean the worker has parsed those
bytes. On Windows, ConPTY renders before the worker reads, so the reconnect
snapshot can be cut before the last marker; that marker then reaches the
viewer as live output. Wait for it across the replay and the live output
that follows the replay end.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-27 06:59:00 +00:00
Mohamed Boudra 9eab3b278f Stop client plugins from crashing iOS when importing react-native (#11011)
* fix(plugins): prevent iOS PushNotificationIOS crash when plugins import react-native

Filter unsupported throwing getters (PushNotificationIOS, AsyncStorage, ImagePickerIOS, ProgressViewIOS, DatePickerIOS, Slider) and raw default from the react-native runtime exposed to client plugins, while preserving lazy property descriptors on safe exports.

Also replace eager Hermes CommonJS interop evaluation (value: from[key]) with per-key lazy getter closures (get: ((k) => () => from[k])(key)) in the server plugin compiler so namespace imports no longer evaluate unrelated host module getters.

Closes #10978

* fix(plugins): allowlist safe react-native exports for client plugins

Replace the react-native denylist in evaluate.ts with an explicit allowlist of cross-platform UI, layout, and animation exports (PLUGIN_REACT_NATIVE_EXPORTS) while preserving lazy property descriptors.

Add a wiring test verifying require('react-native') returns the allowlisted runtime object rather than the raw ReactNative namespace, plus a contract test verifying every allowlisted key exists as a non-deprecated, non-throwing getter in react-native/index.js.

* fix(plugins): retain SafeAreaView and InteractionManager in react-native allowlist

Keep SafeAreaView and InteractionManager in PLUGIN_REACT_NATIVE_EXPORTS so existing published plugins that import them from react-native (e.g. SafeAreaView insets and InteractionManager.runAfterInteractions) keep working on iOS, Android, and web. Both exports are safe cross-platform getters on iOS and react-native-web and remain lazy under the compiler's per-key getter interop.

Also harden the react-native/index.js getter contract test to assert the parser matched getters and that PushNotificationIOS stays excluded.

* fix(plugins): omit only PushNotificationIOS and default from plugin react-native runtime

Replace the 46-key react-native allowlist with copying all own enumerable descriptors from Object.keys(source) lazily while skipping only PushNotificationIOS and default. An audit of published plugins showed 14 plugins rely on react-native exports outside the allowlist (TurboModuleRegistry, NativeModules, UIManager, DeviceEventEmitter, AppRegistry, Clipboard, Settings, and RN-web render).

Keep the lazy per-key Hermes interop fix in compiler-build.ts, the require('react-native') wiring test, and the react-native/index.js enumerable getter contract test.
2026-11-27 13:49:51 +07:00
Mohamed Boudra fcfcdf156a Make ACP catalog probing respectful and clean up Antigravity ACP hygiene (#10992)
* feat(acp): make ACP catalog probing respectful and clean up Antigravity ACP hygiene

* fix(acp): address Windows CI failures and paseo-bot review findings

* refactor(acp): remove manual catalog mode and use on_demand for Antigravity

* fix(server): share Windows WinGet candidate resolution when findExecutable skips probing

* test(server): compare Windows PATHEXT casing case-insensitively in executable-resolution test
2026-11-27 13:29:55 +07:00
paseo-bot[bot] f792ac8a4e chore: update panel scrolling branch from main 2026-11-06 07:49:20 +00:00
paseo-bot[bot] e8a9e2d699 chore(android): carry panel scrolling fix onto the current timeline 2026-11-06 07:48:53 +00:00
paseo-bot[bot]andluckxine 5feec6fa35 fix(android): contain nested panel motion in the current timeline
Identify the forward-order timeline by its existing native identity so panel edges stay still while ordinary parents retain Android handoff. Preserve the native content-position corrections.

Co-authored-by: luckxine <91582901+luckxine@users.noreply.github.com>
2026-11-06 07:46:51 +00:00
paseo-bot[bot]andluckxine 138d9d63ab fix(android): keep panel overscroll inside inverted timelines
Android forwards a nested panel’s unconsumed scroll and fling to its inverted parent, moving the timeline in the opposite visual direction. Keep that motion inside the panel while preserving ordinary parent scrolling and nested-scroll registration.

Co-authored-by: luckxine <91582901+luckxine@users.noreply.github.com>
2026-11-01 14:32:01 +00:00
246 changed files with 6817 additions and 22378 deletions
-1
View File
@@ -55,7 +55,6 @@ At the start of non-trivial work, list `docs/` and skim anything relevant to the
| [docs/permissions.md](docs/permissions.md) | Semantic daemon permissions, principals, credentials, pairing invitations, and Hub authority |
| [docs/terminal-performance.md](docs/terminal-performance.md) | Terminal latency pipeline, coalescing/backpressure invariants, benchmark + perf spec usage |
| [docs/terminal-rendering.md](docs/terminal-rendering.md) | Native terminal view: xterm owns the grid, cluster placement, emoji widths, mixed-direction limits, render regression |
| [docs/timeline-sync.md](docs/timeline-sync.md) | Owned agent history, rewind retirements, live stream vs authoritative fetch, paged catch-up, client replica |
| [docs/agent-stream-performance.md](docs/agent-stream-performance.md) | Assistant text pipeline — coalescing window, paced reveal, why arrival lumps are smoothed at render |
| [docs/agent-stream-disclosure.md](docs/agent-stream-disclosure.md) | Expand/collapse in the chat timeline — hold contract, native anchor sequence, frame spacing, render-window cost |
| [docs/markdown-renderer.md](docs/markdown-renderer.md) | Shared Markdown engine, the vendored library fork, native selection, links, images and library constraints |
+3 -6
View File
@@ -39,8 +39,8 @@ An unarchived agent may be `closed` without being deleted or archived. Closing r
processes and subscriptions while retaining its Paseo identity, persistence handle, timeline,
workspace, labels, title, usage, attention, timestamps, and parent relationship. Opening or prompting
the agent runs through `ensureAgentLoaded()`, which resumes the durable provider session under the
same Paseo agent ID. Resume does not read provider history when the agent already has a timeline;
see [owned history](timeline-sync.md#owned-history).
same Paseo agent ID. Provider history is not appended again when the canonical timeline is already
primed.
Reload releases the old runtime before resuming its durable session: an idle provider process can
still own an exclusive writer. A close failure retains that runtime for cleanup and blocks the
@@ -268,8 +268,7 @@ lifecycle is separate from public workspace visibility and is not a public creat
Archive is a **soft delete**: the agent record stays on disk with `archivedAt` set, the runtime is closed, and the agent disappears from active lists. Archive is **global** — it lives on the server and propagates to every connected client.
Archive sets `archivedAt`, invokes the provider's native archive hook, and cascades to managed
children. The timeline and the provider children stay, so an archived chat reads them without its
provider; deleting the agent removes them.
children.
`create_agent_request` can opt an agent into `autoArchive`. In that mode the daemon archives the agent after the first terminal turn event (`turn_completed`, `turn_failed`, or `turn_canceled`). When the agent owns an isolated workspace, auto-archive archives that workspace too; the managed worktree is removed when its final workspace reference is gone.
@@ -365,8 +364,6 @@ Workspace status is an aggregate activity signal computed **per `workspaceId`**.
Running provider-native subagents contribute `running` to the workspace owned by their parent agent. Their completed, failed, and canceled states stay in the parent's subagents track.
Only the parent's current runtime makes a provider child running. A child's stored status is the last report about it, and that report can come from provider history or from a runtime an earlier daemon ran, so a stored `running` child does not make the workspace running or keep the parent's runtime alive. It counts again once the live session reports it running. Closing a runtime cancels the children that runtime reported running; children it never reported keep their stored status.
A finished or failed workspace can be marked unread after it has been reviewed. The daemon restores
attention on its newest eligible workspace-root agent, `error` for an agent whose lifecycle is
`error` and `finished` otherwise, without sending a new notification. Opening a workspace restores
+11 -2
View File
@@ -202,8 +202,17 @@ This is the Android counterpart of the iOS local-simulator flow in [development.
`modules/paseo-scroll` replaces React Native's vertical scroll view with `PaseoScrollView`, which
keeps React Native's scroll manager interface and corrects how the chat timeline holds its position.
[agent-stream-disclosure.md](agent-stream-disclosure.md#scroll-view-corrections) lists the
corrections and the React Native issues they work around. Its instrumentation tests run the scroll
view in a real window, mounting through React Native's own mounting manager and injecting touches:
corrections and the React Native issues they work around.
The timeline's `nativeID` (`agent-chat-scroll-native-virtualized`) also identifies it to the native
scroll owner: a nested panel's edge overshoot and unconsumed fling must leave the timeline still.
Ordinary scroll parents retain Android's handoff. Keep that identity in sync with
`agent-stream/strategy-native.tsx`; the end pin is absent while reading history, so it cannot
identify the timeline for this rule.
Its instrumentation tests run the scroll view in a real window, mounting through React Native's own
mounting manager and injecting touches. `PanelEdgeTest` covers both panel edges, flings,
interior/direct scrolling, and ordinary-parent handoff:
```bash
cd packages/app/android
+1 -3
View File
@@ -94,7 +94,6 @@ workspace for a directory clears it. The store lives in memory and resets on dae
| `server/directory-sync/` | Daemon-global latest-state sequences for projects, workspaces, and agents |
| `server/workspace-labels/` | Host-local label catalog, assignment mutations, and explicit subscriptions |
| `server/agent/agent-manager.ts` | Agent lifecycle state machine, timeline tracking, subscriber management |
| `server/agent/timeline/` | Owned agent history, provider children, rewind retirements, behind a backend |
| `server/agent/agent-storage.ts` | File-backed JSON persistence at `$PASEO_HOME/agents/` |
| `server/agent/tools/` | Transport-neutral catalog for workspaces, agents, permissions, and automation |
| `server/agent/mcp-server.ts` | Thin MCP adapter that registers the Paseo tool catalog with the MCP SDK |
@@ -403,7 +402,7 @@ initializing → idle ⇄ running
client-side dedup; the default fetch page is 200 items.
- Timeline row `timestamp` values are canonical daemon-owned timestamps. Providers may supply original replay timestamps, but clients must not guess timestamp trust or hide time UI based on local clock heuristics.
- Events stream to connected clients in real time; correctness is backed by authoritative timeline fetches and paged-to-completion catch-up.
- Agent state persists to `$PASEO_HOME/agents/{cwd-with-dashes}/{agent-id}.json`. That storage path is derived from `cwd`, not from workspace id. Timeline rows persist in the daemon database, `$PASEO_HOME/paseo.db`. They are the transcript authority after the first import of provider history. See [owned history](timeline-sync.md#owned-history).
- Agent state persists to `$PASEO_HOME/agents/{cwd-with-dashes}/{agent-id}.json`. Timeline rows are runtime memory; provider history is the durable transcript authority and resumed agents rebuild from it. That storage path is derived from `cwd`, not from workspace id.
## Right-sidebar boundary: directory-backed vs workspace-owned
@@ -479,7 +478,6 @@ Providers that can accept native tool definitions should set `supportsNativePase
```
$PASEO_HOME/
├── agents/{cwd-with-dashes}/{agent-id}.json # Agent record
├── paseo.db # Daemon database (SQLite): agent timelines
├── projects/projects.json # Project registry
├── projects/workspaces.json # Workspace registry
├── projects/icons/ # Custom project icon images
+1 -41
View File
@@ -34,7 +34,7 @@ Workspace archive runs lifecycle teardown from the exact `cwd` but removes only
`worktreeRoot` after its last active reference disappears. Worktree recovery recreates that backing
checkout from `mainRepoRoot`, then restores the relative path from `worktreeRoot` to `cwd`.
Paseo persists most stores as JSON files, and agent timelines in the [daemon database](#daemon-database). JSON data is validated at runtime with Zod schemas. Most JSON stores write atomically (write to temp file, then rename); a few still use plain `writeFile` — see each section. JSON stores have no schema-versioning/migration framework — schemas rely on optional fields with defaults for forward compatibility, with a small amount of inline normalization in `persisted-config.ts` for legacy provider/speech entries.
Paseo uses **file-based JSON persistence** instead of a traditional database. All data is validated at runtime with Zod schemas. Most stores write atomically (write to temp file, then rename); a few still use plain `writeFile` — see each section. There is no schema-versioning/migration framework — schemas rely on optional fields with defaults for forward compatibility, with a small amount of inline normalization in `persisted-config.ts` for legacy provider/speech entries.
All server-side stores live under `$PASEO_HOME` (defaults to `~/.paseo`).
@@ -53,7 +53,6 @@ $PASEO_HOME/
├── daemon-keypair.json # E2EE keypair for relay (mode 0600)
├── paseo.pid # Daemon PID lock file
├── local-credential # Per-run local client credential (mode 0600)
├── paseo.db # Daemon database (SQLite, with -wal and -shm files)
├── daemon.log # Default log file (path configurable)
├── agents/
│ └── {sanitized-cwd}/
@@ -182,45 +181,6 @@ Terminal activity contributes to the workspace status bucket **per `workspaceId`
---
## Daemon database
`$PASEO_HOME/paseo.db` is one SQLite file that the daemon opens at startup with `node:sqlite`
(`packages/server/src/server/database/`). Agent timelines are its only store today. Each store is a
`SchemaModule`: its own table-name prefix and an append-only list of migrations.
- **Migrations.** Startup runs every module's pending migrations in one transaction, so a failed
migration leaves the file as it was. `schema_versions` records each module's version and
`min_reader_version`. Mark a migration `breaking` when an older daemon cannot read the result,
for example a dropped or renamed column. An older daemon then refuses to start with
`DatabaseSchemaTooNewError`. Additive migrations leave older daemons working, and they ignore
modules they do not know. This matters because the app and the daemon update separately, and a
user can run an older daemon on the same `$PASEO_HOME`.
- **Failure.** A file that SQLite cannot open stops the daemon with `DatabaseOpenError`, which
names the path. The daemon does not delete or recreate the file.
- **Access.** The file holds every prompt and reply, so the daemon sets it and its `-wal` and `-shm`
files to mode `0600` on every open. SQLite gives the WAL files it creates the mode of the database
file.
- **Durability.** The database uses WAL with `synchronous = NORMAL`. A power loss can drop the
last commits but does not corrupt the file.
- **Checkpoints.** A checkpoint syncs the file to disk and takes up to 100 ms. SQLite's
auto-checkpoint runs it on the committing thread, which stalled the event loop during streaming.
The daemon turns it off and checkpoints from a worker thread with its own connection. If the
worker exits, the daemon turns auto-checkpoint back on.
- **Transactions.** `write` and `read` callbacks are synchronous, so a transaction never spans an
`await` and transactions never interleave.
- **Node.** `node:sqlite` needs Node 22.16 or later. Node 22 prints an experimental warning once,
when the daemon opens the database.
### Agent timelines
`AgentTimeline` owns each agent's history, and its SQLite backend stores the projected rows, the
source ranges, retirements, the open rewind, and provider children in `timeline_*` tables. The text
of a streamed assistant or reasoning message is stored as one chunk per source event, beside its
row, so a chunk never rewrites the message. An earlier file store rewrote the whole transcript on
every update. See [owned history](timeline-sync.md#owned-history).
---
## 2. Daemon Configuration
**Path:** `$PASEO_HOME/config.json`
+11 -68
View File
@@ -5,9 +5,15 @@ Agent chat delivery has two paths:
1. **Live stream** — `agent_stream` WebSocket messages for immediacy. These may be delta-shaped lifecycle updates.
2. **Authoritative history** — `fetch_agent_timeline_request` for correctness. This always returns full projected timeline items, never lifecycle deltas.
Pagination bounds each read, not total resident history. Streaming overhead must remain
proportional to the retained transcript. Cumulative text snapshots must be released after their
deltas have been consumed.
The daemon retains projected items in memory. Each source event advances the stream sequence,
then replaces the previous tool state or merges into the current text item. Intermediate payloads
are never retained for history or catch-up. Provider history is the durable transcript authority
and rebuilds the projection when an agent resumes.
Pagination bounds each read, not total resident history. Active and idle agents retain their
projected transcript; archive releases it and later history reads rebuild it from the provider.
Streaming overhead must remain proportional to the retained transcript. Cumulative text snapshots
must be released after their deltas have been consumed.
The invariants are:
@@ -26,50 +32,6 @@ bounded item is used for runtime timeline rows and live stream events. Provider
applies the same rule so reopening an agent cannot restore an oversized payload. Fetches apply it
again to assistant and reasoning rows the projection merges from many chunks.
## Owned history
The daemon owns each agent's history in `AgentTimeline`
(`packages/server/src/server/agent/timeline/`): one ordered history per agent, with each provider
child's descriptor and history in a child scope of the same agent. Each source event advances the
stream sequence, then replaces the previous tool state or merges into the current text item.
Intermediate payloads are never retained for history or catch-up.
History is append-only: rewind, import, reload and archive never delete or rewrite a row. Only
deleting the agent, or a provider removing one of its own children, deletes history.
- **Rewind** retires a range of rows. They leave the conversation and stay stored, in the same
epoch. See [Rewind retires rows](#rewind-retires-rows).
- **Provider history** is imported only into an agent that has no history. After that, resume
does not read it. Reload agent and Unarchive require the provider history to start with the
same prompt IDs and text in order. They then append whole new turns, starting at the next
prompt. Existing replies, including partial replies, stay as recorded. If the prompts differ,
for example because the provider stored expanded attachment text, the chat stays unchanged and
Paseo reports a mismatch. A provider child Paseo already holds, listed or retired, is never imported again.
- **Archive and reload** keep the history and the provider children. An archived chat reads them
without its provider. Opening a stored agent that has no provider session to resume starts its
first session on the same history.
- **Delete** removes the agent's history and every child's, retired ones included, before the
agent record. If the history cannot be removed, the request fails and the agent stays listed. The
user can keep using it and delete it again.
`epoch` is the stored history's identity, minted once when the history is created.
`AgentTimeline` serializes every operation of one agent, child scopes included, and keeps its
state in an `AgentTimelineBackend`: the sequence, the rows and retirements, prompt identities, the
open rewind, and the children. The backend contract suite is `agent-timeline.test.ts`, run over
`TIMELINE_CONTRACT_BACKENDS` in `timeline/testing.ts`. The daemon uses the SQLite backend in the
[daemon database](data-model.md#daemon-database). History, retirements, the open rewind, and
provider children survive a daemon restart in the same epoch, so clients keep their cursors. A
closed or archived agent holds no history in memory. Each fetch reads the page from the database
and starts no provider. An internal agent, such as the one that writes a commit message, keeps its
history in a memory backend instead, so it leaves nothing on disk. The memory backend also serves
tests.
An open rewind is stored with the history. Resuming an agent whose history holds one settles it
before the agent takes prompts: a recorded provider cut is committed, and an unknown outcome is
judged from the resumed provider history. When that history proves nothing, the rewind stays open
and the agent refuses prompts with the unknown-outcome error.
## Presence is not delivery
Client heartbeat reports presence:
@@ -211,7 +173,7 @@ or retry backoff. This cannot keep a mobile socket alive after the operating sys
bookkeeping without replacing timeline arrays, preserving an upward-scrolled viewport.
- When the page overlaps or is adjacent to the local end cursor, only projected items newer than
that cursor are applied. Already-covered rows are not replayed.
- A true middle gap or epoch change atomically replaces stale canonical history with the
- A true middle gap, epoch change, or rewind atomically replaces stale canonical history with the
latest tail. The replacement reconciles positioned live rows beyond its coverage and unresolved
local submissions; it never retains two discontiguous canonical ranges.
@@ -224,24 +186,6 @@ history replay. The pending approval UI can hide that tool from presentation, bu
must retain its position. Creating a new history card on rejection places it after the prompt that
rejected it; changing steer-event ordering would also put new assistant output before that prompt.
## Rewind retires rows
A conversation rewind commits a retirement `{ seq, retireFromSeq }`: active rows anchored in
`[retireFromSeq, seq)` leave the conversation, and `seq` is the retirement's own position in the
sequence. The provider children spawned by retired tool calls, and their descendants, are retired
in the same commit. They leave the listing, keep their history, and drop late provider events.
Clients learn of a retirement live through `agent.timeline.rewind`, and on pages through
`retirements`, which lists the retirements whose `seq` lies inside the page's span. The client
drops the rows it holds in that range; rows without a timeline position are unechoed local sends
and stay. Retired ranges and the retirement's `seq` count as covered, so forward cursors advance
through them. Tail, before and prompt-jump pages are served from active rows, so one served before
a retirement the client already applied is stale and is refetched (`viewed-timeline-sync.ts`).
Clients without `timeline_rewind_operations` cannot drop retired rows. For them the session derives
a wire epoch that changes with each retirement, so they take the destructive replacement they
always took on rewind. The shim is tagged `COMPAT(timelineRewindOperations)`.
## Provider child history
Child transcripts use the same projected-page reconciliation as the main conversation. The client
@@ -419,7 +363,7 @@ the draft-create handoff is the one boundary that also permits the legacy canoni
arrived first. Generic reducers and consumers do not reimplement message identity matching.
Ordinary bootstrap, same-epoch reset, and catch-up replacement preserve unmatched locally submitted
rows because a provider may never echo them. A known epoch change replaces history and
rows because a provider may never echo them. A known epoch change or rewind replaces history and
drops acknowledged local rows omitted by the new canonical epoch; every transaction not yet
acknowledged by the provider, and no other local row, crosses that destructive boundary. A cold
reset without an existing epoch is destructive because the client has no continuity anchor.
@@ -435,7 +379,6 @@ canonical assistant prefix, it stays in the head lane. No row may be returned in
## Relevant code
- Server owned history: `packages/server/src/server/agent/timeline/`
- Server live stream forwarding: `packages/server/src/server/session.ts`
- App sync planning: `packages/app/src/timeline/timeline-sync-plan.ts`
- App viewed-agent synchronization: `packages/app/src/timeline/viewed-timeline-sync.ts`
+1 -20
View File
@@ -45,9 +45,6 @@
"react-dom": "19.2.3",
"typescript": "^5.9.3",
"ws": "^8.20.0"
},
"engines": {
"node": ">=22.16.0"
}
},
"node_modules/@0no-co/graphql.web": {
@@ -39722,9 +39719,6 @@
"typescript": "^5.2.2",
"vitest": "^4.1.6",
"zx": "^8.8.5"
},
"engines": {
"node": ">=22.16.0"
}
},
"packages/cli/node_modules/@vitest/expect": {
@@ -40653,7 +40647,7 @@
"@playwright/test": "^1.56.1",
"@types/express": "^4.17.20",
"@types/markdown-it": "^14.2.0",
"@types/node": "^22.16.0",
"@types/node": "^20.9.0",
"@types/qrcode": "^1.5.6",
"@types/uuid": "^9.0.7",
"@types/ws": "^8.5.8",
@@ -40661,9 +40655,6 @@
"cross-env": "^10.1.0",
"tsx": "^4.6.0",
"vitest": "^4.1.6"
},
"engines": {
"node": ">=22.16.0"
}
},
"packages/server/node_modules/@esbuild/aix-ppc64": {
@@ -41111,16 +41102,6 @@
"@types/mdurl": "^2"
}
},
"packages/server/node_modules/@types/node": {
"version": "22.20.5",
"resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.5.tgz",
"integrity": "sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==",
"dev": true,
"license": "MIT",
"dependencies": {
"undici-types": "~6.21.0"
}
},
"packages/server/node_modules/@vitest/expect": {
"version": "4.1.6",
"resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.6.tgz",
-3
View File
@@ -169,8 +169,5 @@
"tiny-async-pool": {
"semver@^5": "5.7.2"
}
},
"engines": {
"node": ">=22.16.0"
}
}
@@ -13,13 +13,6 @@ import {
import { expectNearBottom, scrollChatAwayFromBottom } from "../support/helpers/agent-bottom-anchor";
import { holdRewindCompletion } from "../support/helpers/agent-timeline-gate";
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
import { userScrollsTimelineToHistoryStart } from "../support/helpers/timeline-pagination";
import {
closeWorkspaceAgentTab,
fetchAgentArchivedAt,
primeAdditionalPage,
resetSeededPageState,
} from "../support/helpers/archive-tab";
async function completeSubmittedTurn(
page: Page,
@@ -55,102 +48,26 @@ async function expectTurnCompletesNormally(
await expectAgentIdle(page);
}
async function openAgentOnAnotherClient(
page: Page,
agent: Awaited<ReturnType<typeof seedMockAgentWorkspace>>,
): Promise<void> {
await primeAdditionalPage(page);
await resetSeededPageState(page);
await openAgentRoute(page, agent);
await expectComposerVisible(page);
}
/** The prompts the chat shows, in order, each exactly once. */
async function expectPrompts(page: Page, prompts: string[]): Promise<void> {
const messages = page.getByTestId("user-message");
await expect(messages).toHaveCount(prompts.length);
await expect(messages).toContainText(prompts);
}
async function reloadAgentFromTabMenu(page: Page, agentId: string): Promise<void> {
const tabId = `workspace-tab-agent_${agentId}`;
await page.getByTestId(tabId).filter({ visible: true }).first().click({ button: "right" });
await page.getByTestId(`workspace-tab-context-agent_${agentId}-reload-agent`).click();
}
async function archiveAgentByClosingTab(
page: Page,
agent: Awaited<ReturnType<typeof seedMockAgentWorkspace>>,
): Promise<void> {
await closeWorkspaceAgentTab(page, agent.agentId);
await expect.poll(() => fetchAgentArchivedAt(agent.client, agent.agentId)).not.toBeNull();
}
async function unarchiveAgent(page: Page): Promise<void> {
await page.getByRole("button", { name: "Unarchive", exact: true }).click();
await expect(page.getByText("This agent is archived", { exact: true })).toHaveCount(0, {
timeout: 30_000,
});
}
async function expectToast(page: Page, message: string): Promise<void> {
await expect(page.getByTestId("app-toast-message")).toHaveText(message, { timeout: 30_000 });
}
// The mock provider's resumed session holds no history, so it never matches what Paseo shows.
const UNSYNCED_RELOAD =
"Reloaded agent, but the provider's history doesn't match this chat, so it wasn't synced";
/** The prompts of the whole conversation, after scrolling up through its older pages. */
async function expectConversationPrompts(page: Page, prompts: string[]): Promise<void> {
const messages = page.getByTestId("user-message");
await expect
.poll(async () => {
await userScrollsTimelineToHistoryStart(page);
return await messages.count();
})
.toBe(prompts.length);
await expect(messages).toContainText(prompts);
}
// A row React remounts loses this attribute; one that stays mounted keeps it.
async function markMounted(row: Locator): Promise<void> {
await row.evaluate((element) => element.setAttribute("data-e2e-mounted", "before-rewind"));
}
async function expectStillMounted(row: Locator): Promise<void> {
await expect(row).toHaveAttribute("data-e2e-mounted", "before-rewind");
}
test.describe("Agent message rewind", () => {
test("rewinds a prompt in place on every open client and keeps a human draft", async ({
test("rewinds a submitted prompt without replaying history and preserves a human draft", async ({
page,
}) => {
test.setTimeout(150_000);
test.setTimeout(90_000);
const retainedPrompt = "Keep this completed turn after rewind.";
const rewoundPrompt = "Remove this completed turn after rewind.";
const nextPrompt = "Continue after the rewind.";
const preservedDraft = "Keep this human draft after rewind.";
const agent = await seedMockAgentWorkspace({
repoPrefix: "message-rewind-roundtrip-",
title: "Message rewind roundtrip",
model: "ten-second-stream",
});
const otherClient = await page.context().newPage();
try {
const rewindCompletion = await holdRewindCompletion(page, agent.agentId);
await openAgentRoute(page, agent);
await expectComposerVisible(page);
const retainedMessage = await completeSubmittedTurn(page, agent, retainedPrompt);
await completeSubmittedTurn(page, agent, retainedPrompt);
const userMessage = await completeSubmittedTurn(page, agent, rewoundPrompt);
await test.step("a second client opens the same chat", async () => {
await openAgentOnAnotherClient(otherClient, agent);
await expectPrompts(otherClient, [retainedPrompt, rewoundPrompt]);
});
await markMounted(retainedMessage);
await scrollChatAwayFromBottom(page, {
deltaY: -900,
minDistanceFromBottom: 300,
@@ -159,92 +76,19 @@ test.describe("Agent message rewind", () => {
await blurComposerInput(page);
rewindCompletion.clearTimelineStreamCount();
await test.step("the rewind stays pending until the daemon answers", async () => {
const rewind = rewindConversation(page, userMessage, rewoundPrompt);
await rewindCompletion.waitForDelayedResponse();
await expect(page.getByTestId("rewind-menu-conversation")).toBeDisabled();
expect(rewindCompletion.timelineStreamCount()).toBe(0);
rewindCompletion.release();
await rewind;
});
const rewind = rewindConversation(page, userMessage, rewoundPrompt);
await rewindCompletion.waitForDelayedResponse();
await expect(page.getByTestId("rewind-menu-conversation")).toBeDisabled();
expect(rewindCompletion.timelineStreamCount()).toBe(0);
rewindCompletion.release();
await rewind;
await test.step("the rewound turn leaves without reloading the chat", async () => {
await expectPrompts(page, [retainedPrompt]);
await expectStillMounted(retainedMessage);
expect(rewindCompletion.timelineFetchCount()).toBe(0);
await expectComposerDraft(page, preservedDraft);
await expectComposerNotFocused(page);
await expectNearBottom(page);
await expectPrompts(otherClient, [retainedPrompt]);
});
await test.step("the next prompt appears once on both clients", async () => {
await completeSubmittedTurn(otherClient, agent, nextPrompt);
await expectPrompts(otherClient, [retainedPrompt, nextPrompt]);
await expectPrompts(page, [retainedPrompt, nextPrompt]);
});
await test.step("a reconnecting client loads the rewound conversation", async () => {
await otherClient.reload();
await expectPrompts(otherClient, [retainedPrompt, nextPrompt]);
});
} finally {
await otherClient.close();
await agent.cleanup();
}
});
test("keeps the rewound conversation through Reload agent, archive and unarchive", async ({
page,
}) => {
test.setTimeout(150_000);
const keptPrompt = "Keep this turn through reload and archive.";
const rewoundPrompt = "Rewind this turn before reloading.";
const nextPrompt = "Continue after the rewind, then reload.";
const agent = await seedMockAgentWorkspace({
repoPrefix: "message-rewind-reload-archive-",
title: "Message rewind reload archive",
model: "ten-second-stream",
});
try {
await openAgentRoute(page, agent);
await expectComposerVisible(page);
await completeSubmittedTurn(page, agent, keptPrompt);
const rewound = await completeSubmittedTurn(page, agent, rewoundPrompt);
await rewindConversation(page, rewound, rewoundPrompt);
await expectPrompts(page, [keptPrompt]);
await completeSubmittedTurn(page, agent, nextPrompt);
await expectPrompts(page, [keptPrompt, nextPrompt]);
await test.step("Reload agent keeps the chat and says the provider's history was not synced", async () => {
await reloadAgentFromTabMenu(page, agent.agentId);
await expectToast(page, UNSYNCED_RELOAD);
await expectPrompts(page, [keptPrompt, nextPrompt]);
await expectComposerVisible(page);
});
await test.step("the archived chat shows the rewound conversation", async () => {
await archiveAgentByClosingTab(page, agent);
await openAgentRoute(page, agent);
await expect(page.getByText("This agent is archived", { exact: true })).toBeVisible({
timeout: 30_000,
});
await expectConversationPrompts(page, [keptPrompt, nextPrompt]);
});
await test.step("unarchiving keeps the rewound conversation", async () => {
await unarchiveAgent(page);
await expectToast(page, UNSYNCED_RELOAD);
await expectComposerVisible(page);
await expectConversationPrompts(page, [keptPrompt, nextPrompt]);
});
await test.step("a reconnecting client loads the same conversation", async () => {
await page.reload();
await expectComposerVisible(page);
await expectConversationPrompts(page, [keptPrompt, nextPrompt]);
});
await expect(page.getByTestId("user-message").filter({ hasText: rewoundPrompt })).toHaveCount(
0,
);
await expectComposerDraft(page, preservedDraft);
await expectComposerNotFocused(page);
await expectNearBottom(page);
} finally {
await agent.cleanup();
}
@@ -45,26 +45,6 @@ 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([]);
@@ -89,8 +69,8 @@ test.describe("Agent profiles in the model picker", () => {
page,
}) => {
const seed = await seedAgentProfiles([PROFILE]);
// With only the mock provider enabled on this host, the picker opens
// directly into its models and shows its pinned 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.
const workspace = await seedMockAgentWorkspace({
repoPrefix: "agent-profiles-picker-",
title: "Agent profiles picker",
@@ -12,9 +12,12 @@ import {
openImageLightbox,
closeImageLightbox,
pressInterruptShortcut,
blurComposerInput,
expectComposerDraft,
expectComposerDisabled,
expectComposerEditable,
expectComposerFocused,
expectComposerNotFocused,
expectAttachButtonDisabled,
fillComposerDraft,
dropFileOnComposer,
@@ -175,8 +178,19 @@ test.describe("Composer attachments", () => {
await test.step("remove the image and attach a dropped file", async () => {
await removeAttachmentPill(page, "composer-image-attachment-pill", "Remove image attachment");
await expect(page.getByTestId("composer-image-attachment-pill")).toHaveCount(0);
await blurComposerInput(page);
await expectComposerNotFocused(page);
await dropFileOnComposer(page, TEST_JSON);
await expectAttachmentPill(page, "composer-file-attachment-pill");
await expectComposerFocused(page);
});
await test.step("dropping an image focuses the composer", async () => {
await blurComposerInput(page);
await expectComposerNotFocused(page);
await dropFileOnComposer(page, TEST_IMAGE);
await expectAttachmentPill(page, "composer-image-attachment-pill");
await expectComposerFocused(page);
});
});
@@ -198,9 +212,12 @@ test.describe("Composer attachments", () => {
projectDisplayName: workspace.projectDisplayName,
});
await blurComposerInput(page);
await expectComposerNotFocused(page);
await dropFileOnComposer(page, TEST_JSON);
await expectAttachmentPill(page, "composer-file-attachment-pill");
await expectComposerFocused(page);
} finally {
await workspace.cleanup();
}
@@ -0,0 +1,235 @@
import { mkdir, writeFile } from "node:fs/promises";
import path from "node:path";
import { expect, test, type Page } from "../support/fixtures";
import {
openFileExplorer,
openFileFromExplorer,
expectFileTabOpen,
} from "../support/helpers/file-explorer";
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
const APP_SETTINGS_KEY = "@paseo:app-settings";
const DIFF_FIXTURE = [
"Here is a diff block:",
"",
"```diff",
"diff --git a/src/greet.ts b/src/greet.ts",
"--- a/src/greet.ts",
"+++ b/src/greet.ts",
"@@ -1,3 +1,4 @@ export function greet(name: string) {",
" const prefix = 'Hello';",
"- return `${prefix}, ${name}`;",
"+ const trimmed = name.trim();",
"+ return `${prefix}, ${trimmed}!`;",
"```",
"",
"And a patch block:",
"",
"```patch",
"--- a/README.md",
"+++ b/README.md",
"@@ -1,2 +1,2 @@",
" # Paseo",
"-Old description",
"+New description",
"```",
"",
"Plus Ruby, Kotlin, TOML, and SQL:",
"",
"```ruby",
"class Greeter",
' def hi(name) = "Hello #{name}"',
"end",
"```",
"",
"```kotlin",
'val message: String = "Kotlin ready"',
"```",
"",
"```toml",
"[server]",
'host = "localhost"',
"```",
"",
"```sql",
"SELECT id, name FROM users WHERE active = TRUE;",
"```",
].join("\n");
const FILE_DIFF_CONTENT = [
"diff --git a/app.py b/app.py",
"index 1111111..2222222 100644",
"--- a/app.py",
"+++ b/app.py",
"@@ -1,3 +1,3 @@ def greet():",
" print('hello')",
"-old_value = 1",
"+new_value = 2",
].join("\n");
async function saveScreenshot(page: Page, name: string): Promise<void> {
const dir = process.env.PASEO_QA_SCREENSHOT_DIR;
if (!dir) return;
await mkdir(dir, { recursive: true });
await page.screenshot({ path: path.join(dir, name), fullPage: true });
}
function assistantMessages(page: Page) {
return page.locator("[data-message-id]").filter({ has: page.getByTestId("assistant-message") });
}
test.describe("diff and patch syntax highlighting", () => {
for (const theme of ["dark", "light"] as const) {
test(`highlights diff and patch fences in chat (${theme} theme)`, async ({ page }) => {
await page.addInitScript(
({ key, mode }) => {
localStorage.setItem(key, JSON.stringify({ theme: mode }));
},
{ key: APP_SETTINGS_KEY, mode: theme },
);
const agent = await seedMockAgentWorkspace({
repoPrefix: `diff-chat-${theme}-`,
title: `Diff highlight (${theme})`,
initialPrompt: "Show me the diff and patch.",
featureValues: { mockAssistantResponse: DIFF_FIXTURE },
});
try {
await agent.client.waitForAgentUpsert(
agent.agentId,
(snapshot) => snapshot.status === "idle",
30_000,
);
await openAgentRoute(page, agent);
const message = assistantMessages(page);
const expectedColors =
theme === "dark"
? {
addition: "rgb(152, 195, 121)",
deletion: "rgb(224, 108, 117)",
meta: "rgb(92, 99, 112)",
}
: {
addition: "rgb(52, 130, 51)",
deletion: "rgb(214, 59, 47)",
meta: "rgb(160, 161, 167)",
};
const diffAdd = message.getByText("+ const trimmed = name.trim();", { exact: true });
const diffDel = message.getByText("- return `${prefix}, ${name}`;", { exact: true });
const diffMeta = message.getByText(
"@@ -1,3 +1,4 @@ export function greet(name: string) {",
{
exact: true,
},
);
const patchAdd = message.getByText("+New description", { exact: true });
const patchDel = message.getByText("-Old description", { exact: true });
await expect(diffAdd).toBeVisible({ timeout: 30_000 });
await expect(diffAdd).toHaveCSS("color", expectedColors.addition);
await expect(diffDel).toHaveCSS("color", expectedColors.deletion);
await expect(diffMeta).toHaveCSS("color", expectedColors.meta);
await expect(patchAdd).toHaveCSS("color", expectedColors.addition);
await expect(patchDel).toHaveCSS("color", expectedColors.deletion);
const rubyDef = message.getByText("def", { exact: true });
const kotlinVal = message.getByText("val", { exact: true });
const tomlHost = message.getByText("host", { exact: true });
const sqlSelect = message.getByText("SELECT", { exact: true });
const expectedKeyword = theme === "dark" ? "rgb(198, 120, 221)" : "rgb(166, 38, 164)";
const expectedProperty = theme === "dark" ? "rgb(209, 154, 102)" : "rgb(152, 104, 1)";
await expect(rubyDef).toHaveCSS("color", expectedKeyword);
await expect(kotlinVal).toHaveCSS("color", expectedKeyword);
await expect(tomlHost).toHaveCSS("color", expectedProperty);
await expect(sqlSelect).toHaveCSS("color", expectedKeyword);
await saveScreenshot(page, `chat-diff-patch-${theme}.png`);
} finally {
await agent.cleanup();
}
});
}
test("highlights a .diff file in the Files viewer", async ({ page, withWorkspace }) => {
await page.addInitScript(
({ key }) => {
localStorage.setItem(key, JSON.stringify({ theme: "dark" }));
},
{ key: APP_SETTINGS_KEY },
);
const workspace = await withWorkspace({ prefix: "diff-file-viewer-" });
await writeFile(path.join(workspace.repoPath, "changes.diff"), FILE_DIFF_CONTENT);
await workspace.navigateTo();
await openFileExplorer(page);
await openFileFromExplorer(page, "changes.diff");
await expectFileTabOpen(page, "changes.diff");
const editor = page.getByTestId("file-source-editor").filter({ visible: true });
await expect(editor).toBeVisible({ timeout: 30_000 });
const addLine = editor
.locator(".cm-line", { hasText: "+new_value = 2" })
.locator("span")
.first();
const delLine = editor
.locator(".cm-line", { hasText: "-old_value = 1" })
.locator("span")
.first();
const metaLine = editor
.locator(".cm-line", { hasText: "@@ -1,3 +1,3 @@ def greet():" })
.locator("span")
.first();
await expect(addLine).toHaveCSS("color", "rgb(152, 195, 121)");
await expect(delLine).toHaveCSS("color", "rgb(224, 108, 117)");
await expect(metaLine).toHaveCSS("color", "rgb(92, 99, 112)");
await saveScreenshot(page, "files-viewer-diff-dark.png");
});
test("highlights a .patch file in the Files viewer (light theme)", async ({
page,
withWorkspace,
}) => {
await page.addInitScript(
({ key }) => {
localStorage.setItem(key, JSON.stringify({ theme: "light" }));
},
{ key: APP_SETTINGS_KEY },
);
const workspace = await withWorkspace({ prefix: "patch-file-viewer-" });
await writeFile(path.join(workspace.repoPath, "fix.patch"), FILE_DIFF_CONTENT);
await workspace.navigateTo();
await openFileExplorer(page);
await openFileFromExplorer(page, "fix.patch");
await expectFileTabOpen(page, "fix.patch");
const editor = page.getByTestId("file-source-editor").filter({ visible: true });
await expect(editor).toBeVisible({ timeout: 30_000 });
const addLine = editor
.locator(".cm-line", { hasText: "+new_value = 2" })
.locator("span")
.first();
const delLine = editor
.locator(".cm-line", { hasText: "-old_value = 1" })
.locator("span")
.first();
const metaLine = editor
.locator(".cm-line", { hasText: "@@ -1,3 +1,3 @@ def greet():" })
.locator("span")
.first();
await expect(addLine).toHaveCSS("color", "rgb(52, 130, 51)");
await expect(delLine).toHaveCSS("color", "rgb(214, 59, 47)");
await expect(metaLine).toHaveCSS("color", "rgb(160, 161, 167)");
await saveScreenshot(page, "files-viewer-patch-light.png");
});
});
@@ -1,559 +0,0 @@
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 browserSheet = page.getByTestId("agent-controls-model-browser-sheet");
const browserViewport = page.getByTestId("agent-controls-model-browser-viewport");
await expect(browserViewport).toBeVisible({ timeout: 30_000 });
const backButton = browserSheet.getByTestId("sheet-header-back");
if (await backButton.isVisible()) {
await backButton.click();
}
await browserViewport.getByTestId(`model-provider-${DIRECT_PROVIDER.id}`).click();
await browserViewport
.getByTestId(`model-row-${DIRECT_PROVIDER.id}-${DIRECT_PROVIDER.modelId}`)
.click();
await expect(browserViewport).toHaveCount(0, { timeout: 30_000 });
// Dismiss the outer 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, 0);
await expectUserMessageCount(page, 1);
await expectComposerDraft(page, firstPrompt);
await expectComposerFocused(page);
@@ -243,7 +243,7 @@ test.describe("Rewind sheet", () => {
await expectUserMessageVisible(page, replacementPrompt);
await expect(userMessage(page, secondPrompt)).toHaveCount(0);
await expect(page.getByText("Cycle 1", { exact: true })).toHaveCount(0);
await expectUserMessageCount(page, 1);
await expectUserMessageCount(page, 2);
await fillComposerDraft(page, "");
await composerLocator(page).evaluate((element) => element.blur());
@@ -254,19 +254,7 @@ test.describe("Rewind sheet", () => {
await expect(page.getByTestId("rewind-menu-content")).toHaveCount(0);
await expectComposerDraft(page, "");
await expectComposerNotFocused(page);
await expectUserMessageCount(page, 1);
const preservedDraft = "Keep this human draft after rewind.";
await fillComposerDraft(page, preservedDraft);
await composerLocator(page).evaluate((element) => element.blur());
await userMessage(page, replacementPrompt).hover();
await page.getByTestId("rewind-menu-trigger").last().click();
await expect(page.getByTestId("rewind-menu-content")).toBeVisible();
await selectRewindOption(page, "Rewind files");
await expect(page.getByTestId("rewind-menu-content")).toHaveCount(0);
await expectComposerDraft(page, preservedDraft);
await expectComposerNotFocused(page);
await expectUserMessageCount(page, 1);
await expectUserMessageCount(page, 2);
await fillComposerDraft(page, "");
await composerLocator(page).evaluate((element) => element.blur());
@@ -277,7 +265,7 @@ test.describe("Rewind sheet", () => {
await expect(page.getByTestId("rewind-menu-content")).toHaveCount(0);
await expectComposerDraft(page, replacementPrompt);
await expectComposerFocused(page);
await expectUserMessageCount(page, 0);
await expectUserMessageCount(page, 1);
} finally {
await session.cleanup();
}
@@ -31,8 +31,6 @@ export interface RewindCompletionGate {
clearTimelineStreamCount(): void;
release(): void;
timelineStreamCount(): number;
/** Timeline reads this page sent since the last clear. */
timelineFetchCount(): number;
waitForDelayedResponse(): Promise<void>;
}
@@ -188,20 +186,12 @@ export async function holdDaemonHydration(page: Page): Promise<DaemonHydrationGa
};
}
// The rewind response and the timeline change it causes; the change removes the rewound row too.
const REWIND_COMPLETION_MESSAGES = new Set([
"agent.rewind.response",
"agent.timeline.rewind",
"agent.timeline.replacement",
]);
export async function holdRewindCompletion(
page: Page,
agentId: string,
): Promise<RewindCompletionGate> {
let released = false;
let timelineStreamCount = 0;
let timelineFetchCount = 0;
const delayedForwards: Array<() => void> = [];
let resolveDelayedResponse: (() => void) | null = null;
const delayedResponse = new Promise<void>((resolve) => {
@@ -210,16 +200,7 @@ export async function holdRewindCompletion(
await page.routeWebSocket(daemonWsRoutePattern(), (ws) => {
const server = ws.connectToServer();
ws.onMessage((message) => {
const sessionMessage = getSessionMessage(message);
if (
sessionMessage?.type === "fetch_agent_timeline_request" &&
sessionMessage.agentId === agentId
) {
timelineFetchCount += 1;
}
server.send(message);
});
ws.onMessage((message) => server.send(message));
server.onMessage((message) => {
const sessionMessage = getSessionMessage(message);
const payload = sessionMessage ? getPayload(sessionMessage) : null;
@@ -235,11 +216,11 @@ export async function holdRewindCompletion(
}
if (
!released &&
sessionMessage &&
REWIND_COMPLETION_MESSAGES.has(String(sessionMessage.type)) &&
(sessionMessage?.type === "agent.rewind.response" ||
sessionMessage?.type === "agent.timeline.replacement") &&
payload?.agentId === agentId
) {
// The rewind also signals completion and removes the rewound row/menu.
// The replacement also signals completion and removes the rewound row/menu.
// Hold it with the response so the pending-state assertion observes a pending rewind.
delayedForwards.push(() => ws.send(message));
if (sessionMessage.type === "agent.rewind.response") resolveDelayedResponse?.();
@@ -252,7 +233,6 @@ export async function holdRewindCompletion(
return {
clearTimelineStreamCount() {
timelineStreamCount = 0;
timelineFetchCount = 0;
},
release() {
released = true;
@@ -261,7 +241,6 @@ export async function holdRewindCompletion(
}
},
timelineStreamCount: () => timelineStreamCount,
timelineFetchCount: () => timelineFetchCount,
waitForDelayedResponse: () => delayedResponse,
};
}
@@ -0,0 +1,158 @@
package sh.paseo.scroll
import android.app.Activity
import android.content.Intent
import android.os.SystemClock
import android.view.View
import android.widget.FrameLayout
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import com.facebook.react.soloader.OpenSourceMergedSoMapping
import com.facebook.react.uimanager.DisplayMetricsHolder
import com.facebook.react.uimanager.ThemedReactContext
import com.facebook.react.views.scroll.ReactScrollView
import com.facebook.react.views.scroll.ReactScrollViewManager
import com.facebook.react.views.view.ReactViewGroup
import com.facebook.soloader.SoLoader
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
/** Forward-order parent, as used by the current Android timeline, and a nested panel at its edge. */
@RunWith(AndroidJUnit4::class)
class PanelEdgeTest {
private val instrumentation = InstrumentationRegistry.getInstrumentation()
private var activity: Activity? = null
private lateinit var manager: ReactScrollViewManager
@After fun finish() {
instrumentation.runOnMainSync { activity?.finish() }
}
@Test fun panelBottomEdgeLeavesTimelineStill() {
val (parent, child) = openPanel()
instrumentation.runOnMainSync {
child.scrollTo(0, 600)
assertTrue(child.startNestedScroll(View.SCROLL_AXIS_VERTICAL))
child.dispatchNestedScroll(0, 0, 0, 100, null)
child.stopNestedScroll()
assertEquals("Panel stays at its bottom", 600, child.scrollY)
assertEquals("Panel overshoot must leave timeline still", 400, parent.scrollY)
}
}
@Test fun panelTopEdgeLeavesTimelineStill() {
val (parent, child) = openPanel()
instrumentation.runOnMainSync {
child.scrollTo(0, 0)
assertTrue(child.startNestedScroll(View.SCROLL_AXIS_VERTICAL))
child.dispatchNestedScroll(0, 0, 0, -100, null)
child.stopNestedScroll()
assertEquals("Panel stays at its top", 0, child.scrollY)
assertEquals("Panel overshoot must leave timeline still", 400, parent.scrollY)
}
}
@Test fun panelFlingLeavesTimelineStill() {
val (parent, child) = openPanel()
instrumentation.runOnMainSync {
child.scrollTo(0, 600)
assertTrue(child.startNestedScroll(View.SCROLL_AXIS_VERTICAL))
child.dispatchNestedFling(0f, 1500f, false)
child.stopNestedScroll()
}
SystemClock.sleep(500)
instrumentation.runOnMainSync {
assertEquals("Panel fling must leave timeline still", 400, parent.scrollY)
}
}
@Test fun disablingChildNestedScrollPreventsHandoff() {
val (parent, child) = openPanel()
instrumentation.runOnMainSync {
child.isNestedScrollingEnabled = false
assertEquals(false, child.startNestedScroll(View.SCROLL_AXIS_VERTICAL))
child.dispatchNestedScroll(0, 0, 0, 100, null)
assertEquals(400, parent.scrollY)
}
}
@Test fun ordinaryParentStillConsumesNestedOvershoot() {
val (parent, child) = openPanel()
instrumentation.runOnMainSync {
manager.setNativeId(parent, "ordinary-scroll-parent")
assertTrue(child.startNestedScroll(View.SCROLL_AXIS_VERTICAL))
child.dispatchNestedScroll(0, 0, 0, 100, null)
child.stopNestedScroll()
assertEquals("Ordinary parent retains framework handoff", 500, parent.scrollY)
}
}
@Test fun ordinaryParentStillConsumesUnconsumedFling() {
val (parent, child) = openPanel()
instrumentation.runOnMainSync {
manager.setNativeId(parent, "ordinary-scroll-parent")
child.scrollTo(0, 600)
assertTrue(child.startNestedScroll(View.SCROLL_AXIS_VERTICAL))
child.dispatchNestedFling(0f, 1500f, false)
child.stopNestedScroll()
}
SystemClock.sleep(500)
instrumentation.runOnMainSync { assertTrue(parent.scrollY > 400) }
}
@Test fun consumedPanelFlingDoesNotStartParentFling() {
val (parent, child) = openPanel()
instrumentation.runOnMainSync {
assertTrue(child.startNestedScroll(View.SCROLL_AXIS_VERTICAL))
assertEquals(false, child.dispatchNestedFling(0f, 1500f, true))
child.stopNestedScroll()
assertEquals(400, parent.scrollY)
}
}
@Test fun panelInteriorScrollingLeavesTimelineStill() {
val (parent, child) = openPanel()
instrumentation.runOnMainSync {
child.scrollTo(0, 100)
assertEquals(100, child.scrollY)
assertEquals(400, parent.scrollY)
parent.scrollTo(0, 500)
assertEquals("Direct timeline scrolling remains available", 500, parent.scrollY)
}
}
private fun openPanel(): Pair<ReactScrollView, ReactScrollView> {
val started = instrumentation.startActivitySync(
Intent(instrumentation.targetContext, Activity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
)
activity = started
lateinit var parent: ReactScrollView
lateinit var child: ReactScrollView
instrumentation.runOnMainSync {
DisplayMetricsHolder.initDisplayMetricsIfNotInitialized(started)
SoLoader.init(started, OpenSourceMergedSoMapping)
val react = MountingReactContext(started.applicationContext)
val context = ThemedReactContext(react, started)
manager = PaseoScrollPackage().createViewManager(react, ReactScrollViewManager.REACT_CLASS) as ReactScrollViewManager
parent = manager.createViewInstance(context)
manager.setNativeId(parent, "agent-chat-scroll-native-virtualized")
child = manager.createViewInstance(context)
child.isNestedScrollingEnabled = true
val content = ReactViewGroup(context)
content.addView(child, FrameLayout.LayoutParams(300, 200).apply { topMargin = 400 })
parent.addView(content)
val childContent = ReactViewGroup(context)
child.addView(childContent)
started.setContentView(FrameLayout(started).apply { addView(parent, FrameLayout.LayoutParams(300, 400)) })
parent.layout(0, 0, 300, 400)
content.layout(0, 0, 300, 2000)
child.layout(0, 400, 300, 600)
childContent.layout(0, 0, 300, 800)
parent.scrollTo(0, 400)
}
return Pair(parent, child)
}
}
@@ -14,10 +14,13 @@ import com.facebook.react.views.scroll.ReactScrollView;
import com.facebook.react.views.scroll.ReactScrollViewHelper;
/**
* React Native's vertical scroll view with five corrections. Java, because the content-position
* React Native's vertical scroll view with six corrections. Java, because the content-position
* config type is internal to React Native's Kotlin module.
*/
final class PaseoScrollView extends ReactScrollView {
// The chat timeline, packages/app/src/agent-stream/strategy-native.tsx.
private static final String TIMELINE_NATIVE_ID = "agent-chat-scroll-native-virtualized";
// The chat timeline's end pin, packages/app/src/agent-stream/native-end-pin.tsx.
private static final String END_PIN_NATIVE_ID = "paseo-end-pin";
@@ -35,6 +38,26 @@ final class PaseoScrollView extends ReactScrollView {
super(context);
}
// A panel owns its gesture through its edges; remaining child motion must not move the chat
// behind it. The timeline's native identity stays present when its end pin is removed for
// reading history. Ordinary parents retain Android's nested-scroll handoff.
@Override
public void onNestedScroll(
View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed) {
if (isTimeline()) return;
super.onNestedScroll(target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed);
}
@Override
public boolean onNestedFling(View target, float velocityX, float velocityY, boolean consumed) {
if (isTimeline() && !consumed) return true;
return super.onNestedFling(target, velocityX, velocityY, consumed);
}
private boolean isTimeline() {
return TIMELINE_NATIVE_ID.equals(getTag(R.id.view_tag_native_id));
}
@Override
public void setMaintainVisibleContentPosition(
@Nullable MaintainVisibleScrollPositionHelper.Config config) {
@@ -23,15 +23,7 @@ export interface DraftAgentProfileControls {
}
export type AgentProfileApplyTarget =
| {
kind: "agent";
agentId: string;
availableModeIds: readonly string[] | null;
currentProvider?: string | null;
isSwitchInFlight?: () => boolean;
onApplySameProvider?: () => void;
onStageProviderSwitch?: (profile: MaterializedAgentProfile) => void;
}
| { kind: "agent"; agentId: string; availableModeIds: readonly string[] | null }
| { kind: "draft"; controls: DraftAgentProfileControls };
/** Everything the model picker renders for one profile. It never sees the profile itself. */
@@ -154,16 +146,6 @@ 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;
@@ -173,11 +155,7 @@ export function useAgentProfilePicker(
return;
}
void client
.applyAgentConfig(
target.agentId,
toAgentConfigApply(reconciled),
target.currentProvider ? { expectedProvider: target.currentProvider } : undefined,
)
.applyAgentConfig(target.agentId, toAgentConfigApply(reconciled))
.then((notice) => showProviderNoticeToast(toast, notice))
.catch((error) => {
console.warn("[useAgentProfilePicker] applyAgentConfig failed", error);
@@ -56,7 +56,6 @@ export function ChatFind({
agentId,
serverId,
epoch,
rewindSeq,
items,
viewportRef,
revealLoadedMessage,
@@ -96,8 +95,8 @@ export function ChatFind({
);
const state = useSyncExternalStore(model.subscribe, model.getSnapshot, model.getSnapshot);
useEffect(() => {
model.updateHistory(epoch, items, rewindSeq);
}, [model, epoch, items, rewindSeq]);
model.updateHistory(epoch, items);
}, [model, epoch, items]);
useEffect(() => () => model.close(), [model]);
useEffect(() => {
if (!active) model.close();
@@ -18,7 +18,7 @@ function message(seq: number, text = "target"): StreamItem {
kind: "assistant_message",
text,
timestamp: new Date(0),
timelineCursor: { epoch: "epoch", seq, anchorSeq: seq },
timelineCursor: { epoch: "epoch", seq },
};
}
@@ -39,7 +39,7 @@ it("loads an older location and searches a response merged across suppressed tas
source.map((item, index) => ({
event: { type: "timeline" as const, provider: "claude" as const, item },
timestamp: new Date(0),
timelineCursor: { epoch: "epoch", seq: index + 1, anchorSeq: index + 1 },
timelineCursor: { epoch: "epoch", seq: index + 1 },
})),
{ source: "canonical" },
);
@@ -55,7 +55,7 @@ it("loads an older location and searches a response merged across suppressed tas
},
async load(_epoch, seq) {
loaded.push(seq);
model.updateHistory("epoch", history, null);
model.updateHistory("epoch", history);
},
async reveal(_id, _query, occurrence) {
revealed.push(occurrence);
@@ -64,7 +64,7 @@ it("loads an older location and searches a response merged across suppressed tas
clear() {},
});
try {
model.updateHistory("epoch", [], null);
model.updateHistory("epoch", []);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
@@ -99,7 +99,7 @@ it("skips a source-only candidate and highlights a displayed match", async () =>
clear() {},
});
try {
model.updateHistory("epoch", [message(1), message(2)], null);
model.updateHistory("epoch", [message(1), message(2)]);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().selectedItemId).toBe("row-2");
@@ -129,7 +129,7 @@ it("ignores replies after closing and does not navigate", async () => {
},
clear() {},
});
model.updateHistory("epoch", [message(1)], null);
model.updateHistory("epoch", [message(1)]);
model.open();
model.setQuery("target");
await expect.poll(() => calls).toEqual(["search"]);
@@ -155,7 +155,7 @@ it("retains a failed search for retry and distinguishes failure from zero matche
};
const model = new ChatFindModel(operations);
try {
model.updateHistory("epoch", [], null);
model.updateHistory("epoch", []);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().phase).toBe("error");
@@ -185,7 +185,7 @@ it("reports a failed timeline load as a connection failure", async () => {
clear() {},
});
try {
model.updateHistory("epoch", [], null);
model.updateHistory("epoch", []);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().phase).toBe("error");
@@ -207,160 +207,24 @@ it("reports a search result that outlived its epoch as a changed history", async
clear() {},
});
try {
model.updateHistory("epoch", [message(1)], null);
model.updateHistory("epoch", [message(1)]);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
model.updateHistory("epoch-2", [message(1)], null);
model.updateHistory("epoch-2", [message(1)]);
expect(model.getSnapshot()).toMatchObject({ phase: "error", failure: "historyChanged" });
} finally {
model.close();
}
});
it("reports results that a rewind took messages from as a changed history", async () => {
const model = new ChatFindModel({
async search() {
return response([{ seq: 2, role: "assistant" }]);
},
async load() {},
async reveal() {
return { count: 1, occurrence: 0 };
},
clear() {},
});
try {
model.updateHistory("epoch", [message(1), message(2)], null);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
expect(model.getSnapshot()).toMatchObject({ selectedItemId: "row-2", count: 1 });
// Another client rewinds the turn holding the match; the epoch stays.
model.updateHistory("epoch", [message(1)], 3);
expect(model.getSnapshot()).toMatchObject({
phase: "error",
failure: "historyChanged",
selectedItemId: null,
});
} finally {
model.close();
}
});
it("stops a search still receiving pages when a rewind lands between them", async () => {
let pages = 0;
let releaseSecondPage!: () => void;
const secondPage = new Promise<void>((resolve) => {
releaseSecondPage = resolve;
});
const model = new ChatFindModel({
async search(_query, cursor) {
pages += 1;
if (cursor === undefined)
return { ...response([{ seq: 2, role: "assistant" }]), nextCursor: 2 };
await secondPage;
return response([{ seq: 1, role: "assistant" }]);
},
async load() {},
async reveal() {
return { count: 1, occurrence: 0 };
},
clear() {},
});
try {
model.updateHistory("epoch", [message(1), message(2)], null);
model.open();
model.setQuery("target");
await expect.poll(() => pages).toBe(2);
model.updateHistory("epoch", [message(1)], 3);
releaseSecondPage();
await expect.poll(() => model.getSnapshot().failure).toBe("historyChanged");
expect(model.getSnapshot()).toMatchObject({ phase: "error", selectedItemId: null });
} finally {
model.close();
}
});
it.each([
["Next", "next"],
["Previous", "previous"],
] as const)("reports a rewind after %s as a changed history", async (_label, step) => {
const model = new ChatFindModel({
async search() {
return response([
{ seq: 1, role: "assistant" },
{ seq: 2, role: "assistant" },
]);
},
async load() {},
async reveal() {
return { count: 1, occurrence: 0 };
},
clear() {},
});
try {
model.updateHistory("epoch", [message(1), message(2)], null);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
model[step]();
await expect.poll(() => model.getSnapshot().selectedItemId).toBe("row-2");
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
model.updateHistory("epoch", [message(1)], 3);
expect(model.getSnapshot()).toMatchObject({
phase: "error",
failure: "historyChanged",
selectedItemId: null,
});
} finally {
model.close();
}
});
it("stops a pending Next when a rewind lands before it reveals", async () => {
let reveals = 0;
let revealSecond!: () => void;
const secondReveal = new Promise<void>((resolve) => {
revealSecond = resolve;
});
const model = new ChatFindModel({
async search() {
return response([
{ seq: 1, role: "assistant" },
{ seq: 2, role: "assistant" },
]);
},
async load() {},
async reveal() {
reveals += 1;
if (reveals > 1) await secondReveal;
return { count: 1, occurrence: 0 };
},
clear() {},
});
try {
model.updateHistory("epoch", [message(1), message(2)], null);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
model.next();
await expect.poll(() => reveals).toBe(2);
model.updateHistory("epoch", [message(1)], 3);
revealSecond();
await expect.poll(() => model.getSnapshot().failure).toBe("historyChanged");
expect(model.getSnapshot()).toMatchObject({ phase: "error", selectedItemId: null });
} finally {
model.close();
}
});
it("can load a search location before the initial chat history has arrived", async () => {
const model = new ChatFindModel({
async search() {
return response([{ seq: 1, role: "assistant" }]);
},
async load() {
model.updateHistory("epoch", [message(1)], null);
model.updateHistory("epoch", [message(1)]);
},
async reveal() {
return { count: 1, occurrence: 0 };
@@ -368,7 +232,7 @@ it("can load a search location before the initial chat history has arrived", asy
clear() {},
});
try {
model.updateHistory(null, [], null);
model.updateHistory(null, []);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
@@ -396,7 +260,7 @@ it("reports the position across the whole chat and corrects it with rendered cou
clear() {},
});
try {
model.updateHistory("epoch", [message(1), message(2)], null);
model.updateHistory("epoch", [message(1), message(2)]);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
@@ -433,7 +297,7 @@ it("counts one match per message from a host that reports no counts", async () =
clear() {},
});
try {
model.updateHistory("epoch", [message(1), message(2)], null);
model.updateHistory("epoch", [message(1), message(2)]);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
@@ -76,10 +76,6 @@ export class ChatFindModel {
private items: StreamItem[] = [];
private epoch: string | null = null;
private resultEpoch: string | null = null;
/** The latest rewind applied to the history. A rewind keeps the epoch and retires messages. */
private rewindSeq: number | null = null;
/** The latest rewind when the current result set's search started; undefined until a search starts. */
private searchedRewindSeq: number | null | undefined = undefined;
private locations: Location[] = [];
private resolved = new Map<Location, Target>();
private current = -1;
@@ -117,7 +113,6 @@ export class ChatFindModel {
this.cancel();
this.locations = [];
this.resultEpoch = null;
this.searchedRewindSeq = undefined;
this.resolved.clear();
this.current = -1;
this.inMessage = { occurrence: 0, count: 0 };
@@ -149,7 +144,6 @@ export class ChatFindModel {
});
}
private async search(signal: AbortSignal) {
this.searchedRewindSeq = this.rewindSeq;
try {
let cursor: number | undefined;
do {
@@ -174,14 +168,15 @@ export class ChatFindModel {
this.fail(error, signal);
}
}
/** `rewindSeq` is the sequence number of the latest rewind applied to this history. */
updateHistory(epoch: string | null, items: StreamItem[], rewindSeq: number | null) {
const replaced = this.resultEpoch !== null && epoch !== null && epoch !== this.resultEpoch;
const rewound = this.searchedRewindSeq !== undefined && rewindSeq !== this.searchedRewindSeq;
if ((replaced || rewound) && this.state.open) {
updateHistory(epoch: string | null, items: StreamItem[]) {
if (
this.resultEpoch !== null &&
epoch !== null &&
epoch !== this.resultEpoch &&
this.state.open
) {
this.fail(new ChatFindFailureError("historyChanged"), this.abort.signal);
}
this.rewindSeq = rewindSeq;
this.epoch = epoch;
this.items = items;
this.historyListeners.forEach((listener) => listener());
@@ -9,8 +9,6 @@ export interface ChatFindProps {
agentId: string;
serverId: string;
epoch: string | null;
/** The sequence number of the latest rewind applied to this history, if any. */
rewindSeq: number | null;
items: StreamItem[];
viewportRef: RefObject<StreamViewportHandle | null>;
revealLoadedMessage(messageId: string): boolean;
@@ -139,7 +139,7 @@ describe("useChatOutline", () => {
kind: "user_message",
text: "live prompt",
timestamp: new Date(seq),
timelineCursor: { epoch: "epoch-1", seq, anchorSeq: seq },
timelineCursor: { epoch: "epoch-1", seq },
});
rerender({ tail: [loadedPrompt(2)] });
await waitFor(() => expect(runtime.listAgentTimelinePrompts).toHaveBeenCalledTimes(2));
@@ -198,7 +198,7 @@ describe("useChatOutline", () => {
kind: "assistant_message",
text: "chunk",
timestamp: new Date(),
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 2 },
timelineCursor: { epoch: "epoch-1", seq: 2 },
},
],
timelineEpoch: "epoch-1",
@@ -219,7 +219,7 @@ describe("useChatOutline", () => {
kind: "user_message",
text: "Replaced conversation",
timestamp: new Date(2),
timelineCursor: { epoch: "epoch-2", seq: 1, anchorSeq: 1 },
timelineCursor: { epoch: "epoch-2", seq: 1 },
},
],
timelineEpoch: "epoch-2",
@@ -275,7 +275,7 @@ describe("useChatOutline", () => {
kind: "user_message" as const,
text: "prompt",
timestamp: new Date(1),
timelineCursor: { epoch: "epoch-1", seq: 1, anchorSeq: 1 },
timelineCursor: { epoch: "epoch-1", seq: 1 },
},
];
const { result, rerender } = renderHook(
@@ -326,7 +326,7 @@ describe("useChatOutline", () => {
kind: "user_message" as const,
text: "prompt",
timestamp: new Date(1),
timelineCursor: { epoch: "epoch-1", seq: 1, anchorSeq: 1 },
timelineCursor: { epoch: "epoch-1", seq: 1 },
};
const { result, rerender } = renderHook(
({ tail, mountedHistoryMessageIds }) =>
@@ -381,7 +381,7 @@ describe("useChatOutline", () => {
kind: "user_message" as const,
text: "prompt",
timestamp: new Date(2),
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 2 },
timelineCursor: { epoch: "epoch-1", seq: 2 },
};
const revealLoadedMessage = vi.fn();
revealLoadedMessage.mockReturnValue(false);
@@ -320,7 +320,7 @@ describe("stream presentation through installed plugins", () => {
const source = harness.source();
const live = source.head[0];
if (live?.kind !== "assistant_message") throw new Error("Expected a live assistant message");
const canonical = { ...live, timelineCursor: { epoch: "epoch-1", seq: 42, anchorSeq: 42 } };
const canonical = { ...live, timelineCursor: { epoch: "epoch-1", seq: 42 } };
const present = createStreamPresentation();
present({ ...presentationOptions, tail: [], head: [live], transform: undefined });
const repointed = rows(
@@ -330,7 +330,7 @@ describe("stream presentation through installed plugins", () => {
{
id: streamed[0]!.id,
text: "Streamed answer",
timelineCursor: { epoch: "epoch-1", seq: 42, anchorSeq: 42 },
timelineCursor: { epoch: "epoch-1", seq: 42 },
},
]);
});
@@ -517,7 +517,7 @@ describe("timeline presentation", () => {
messageId: "provider-message",
clientMessageId: "client-message",
turnId: "turn-1",
timelineCursor: { epoch: "epoch", seq: 12, anchorSeq: 12 },
timelineCursor: { epoch: "epoch", seq: 12 },
});
const presentMessage = () =>
present({
@@ -775,6 +775,7 @@ function NativeStreamViewport(props: StreamRenderInput & { strategy: StreamStrat
extraData={renderHistoryMountedRow}
keyExtractor={keyExtractor}
testID="agent-chat-scroll"
// The Android scroll owner identifies the timeline to contain nested panel gestures.
nativeID="agent-chat-scroll-native-virtualized"
ListHeaderComponent={historyStartContent}
ListFooterComponent={liveAuxiliaryContent ?? undefined}
@@ -33,7 +33,7 @@ describe("resolveAssistantTurnForkBoundary", () => {
it("forks a failed assistant turn from its Paseo timeline cursor without a provider message id", () => {
const failedTurn = {
...assistantMessage("assistant-error", 2),
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 42 },
timelineCursor: { epoch: "timeline-1", seq: 42 },
};
expect(
@@ -50,7 +50,7 @@ describe("resolveAssistantTurnForkBoundary", () => {
it("includes the provider message id with a supported timeline cursor", () => {
const selected = {
...assistantMessage("assistant-1", 2, "msg-assistant-1"),
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 42 },
timelineCursor: { epoch: "timeline-1", seq: 42 },
};
expect(
@@ -68,7 +68,7 @@ describe("resolveAssistantTurnForkBoundary", () => {
it("falls back to the provider message id when timeline cursors are unsupported", () => {
const selected = {
...assistantMessage("assistant-1", 2, "msg-assistant-1"),
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 42 },
timelineCursor: { epoch: "timeline-1", seq: 42 },
};
expect(
@@ -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, anchorSeq: 42 },
timelineCursor: { epoch: "timeline-1", seq: 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, anchorSeq: 42 },
timelineCursor: { epoch: "timeline-1", seq: 42 },
timestamp: timestamp(2),
pluginId: "plugin",
pluginItemId: "card-1",
@@ -1,13 +1,7 @@
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;
}
import { getAssistantReply, type StreamItem, type TimelinePosition } from "@/types/stream";
export type AssistantTurnForkBoundary =
| { boundaryCursor: TimelineBoundaryCursor; boundaryMessageId?: string }
| { boundaryCursor: TimelinePosition; boundaryMessageId?: string }
| { boundaryCursor?: undefined; boundaryMessageId: string };
export function resolveAssistantTurnForkBoundary(input: {
@@ -21,7 +15,7 @@ export function resolveAssistantTurnForkBoundary(input: {
}
if (input.supportsTimelineCursor && reply.timelineCursor) {
return {
boundaryCursor: { epoch: reply.timelineCursor.epoch, seq: reply.timelineCursor.seq },
boundaryCursor: reply.timelineCursor,
...(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, anchorSeq: 7 };
const cursor = { epoch: "epoch-1", seq: 7 };
const placed = [{ ...user("u1"), timelineCursor: cursor }, shell("c1"), reply("r1")];
const canonical = collapse(placed, { previousSummaryRowsByHostId: live.summaryRowsByHostId });
expect(canonical.summaryRowsByHostId.get("u1")).not.toBe(live.summaryRowsByHostId.get("u1"));
@@ -101,7 +101,7 @@ function summaryRow(
}
function staysVisibleWhenCollapsed(item: StreamItem): boolean {
return isTurnTrigger(item) || item.kind === "compaction" || item.kind === "provider_switch";
return isTurnTrigger(item) || item.kind === "compaction";
}
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, anchorSeq: 5 },
timelineCursor: { epoch: "e1", seq: 5 },
timestamp: FRIDAY_NIGHT,
},
timelineCursor: { epoch: "e1", seq: 5, anchorSeq: 5 },
timelineCursor: { epoch: "e1", seq: 5 },
timestamp: FRIDAY_NIGHT,
pluginId: "genui",
pluginItemId: "reply/1",
+2 -35
View File
@@ -37,7 +37,6 @@ import {
ToolCall,
TodoListCard,
CompactionMarker,
ProviderSwitchMarker,
MessageOuterSpacingProvider,
type InlinePathTarget,
} from "@/components/message";
@@ -58,7 +57,6 @@ 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";
@@ -410,10 +408,6 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
const timelineEpoch = useSessionStore(
(state) => state.sessions[resolvedServerId]?.agentTimelineCursor.get(agentId)?.epoch ?? null,
);
const timelineRewindSeq = useSessionStore((state) => {
const rewind = state.sessions[resolvedServerId]?.agentTimelineLatestRewind.get(agentId);
return rewind && rewind.epoch === timelineEpoch ? rewind.seq : null;
});
const isTimelineDetached = useSessionStore(
(state) => state.sessions[resolvedServerId]?.agentTimelineHasNewer.get(agentId) === true,
);
@@ -717,15 +711,8 @@ 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}
@@ -737,7 +724,7 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
images={item.images}
attachments={item.attachments}
timestamp={item.timestamp.getTime()}
capabilities={canRewindPrompt ? context.capabilities : undefined}
capabilities={context.capabilities}
client={client}
isFirstInGroup={layoutItem.isFirstInUserGroup}
isLastInGroup={layoutItem.isLastInUserGroup}
@@ -748,14 +735,7 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
/>
);
},
[
activeSegmentStartSeq,
context.capabilities,
agentId,
client,
pendingClientMessageIds,
resolvedServerId,
],
[context.capabilities, agentId, client, pendingClientMessageIds, resolvedServerId],
);
const renderAssistantMessageItem = useCallback(
@@ -961,18 +941,6 @@ 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} />
@@ -1198,7 +1166,6 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
agentId={agentId}
serverId={resolvedServerId}
epoch={timelineEpoch}
rewindSeq={timelineRewindSeq}
items={findItems}
viewportRef={viewportRef}
revealLoadedMessage={revealLoadedMessage}
@@ -75,7 +75,6 @@ export function estimateStreamItemHeight({
case "notification":
return 88;
case "compaction":
case "provider_switch":
return 72;
default:
return 120;
@@ -61,6 +61,8 @@ export function appearanceStyleBoundaryKey(theme: Theme): string {
theme.colors.syntax.meta,
theme.colors.syntax.heading,
theme.colors.syntax.link,
theme.colors.syntax.diffAddition,
theme.colors.syntax.diffDeletion,
].join("\u0000");
}
@@ -81,7 +81,6 @@ export function ArchivedAgentCallout({
agentId,
isWorkspaceRestoring = false,
}: ArchivedAgentCalloutProps) {
const { t } = useTranslation();
const targetKey = `${serverId}:${agentId}`;
const toast = useToast();
const { unarchive, isUnarchiving, canUnarchive } = useUnarchiveAgent({ serverId, agentId });
@@ -111,15 +110,7 @@ export function ArchivedAgentCallout({
const attemptKey = targetKey;
setUnarchiveErrorState(null);
try {
await unarchive({
onRefreshed: (refreshed) => {
if (refreshed.historyDiverged) {
toast.show(t("workspace.tabs.toasts.reloadedAgentHistoryDiverged"), {
variant: "warning",
});
}
},
});
await unarchive();
} catch (error) {
deliverUnarchiveError({
error,
@@ -130,7 +121,7 @@ export function ArchivedAgentCallout({
onToastError: toast.error,
});
}
}, [canUnarchive, t, targetKey, toast, unarchive]);
}, [canUnarchive, targetKey, toast, unarchive]);
return (
<KeyboardTranslateView style={styles.container}>
@@ -0,0 +1,66 @@
import { describe, expect, it } from "vitest";
import { tokenizeToLines } from "@/utils/highlight-cache";
import { fenceLanguageToExtension } from "./highlighted-code-block";
describe("fenceLanguageToExtension", () => {
it.each([
["shell", "sh"],
["ruby", "rb"],
["kotlin", "kt"],
["powershell", "ps1"],
["pwsh", "ps1"],
["protobuf", "proto"],
["latex", "tex"],
["stex", "tex"],
["diff", "diff"],
["patch", "patch"],
["sql", "sql"],
["lua", "lua"],
["proto", "proto"],
["groovy", "groovy"],
["gradle", "gradle"],
["scala", "scala"],
["cmake", "cmake"],
["properties", "properties"],
["ini", "ini"],
["conf", "conf"],
["r", "r"],
["perl", "pl"],
["toml", "toml"],
])("maps fence info %s to %s", (info, expected) => {
expect(fenceLanguageToExtension(info)).toBe(expected);
});
it("produces syntax tokens for every mapped fence alias", () => {
const samples: Array<[string, string]> = [
["shell", 'export FOO="bar"'],
["ruby", 'def hi\n "ok"\nend'],
["kotlin", 'val x: String = "ok"'],
["powershell", 'function Get-X { "ok" }'],
["pwsh", '$x = "ok"'],
["protobuf", 'syntax = "proto3";'],
["latex", "\\documentclass{article}"],
["perl", 'my $x = "ok";'],
["sql", "SELECT 1;"],
["lua", "local x = 1"],
["gradle", 'id "java"'],
["scala", "val x = 1"],
["cmake", "project(Paseo)"],
["ini", "[section]\nkey = value"],
["r", "x <- function(a) a"],
["toml", '[server]\nhost = "localhost"'],
["diff", "+added"],
["patch", "-removed"],
];
for (const [info, code] of samples) {
const ext = fenceLanguageToExtension(info);
const lines = tokenizeToLines(code, ext);
expect(lines, info).not.toBeNull();
expect(
lines?.flat().some((token) => token.style !== null),
info,
).toBe(true);
}
});
});
@@ -39,9 +39,18 @@ const LANGUAGE_ALIASES: Record<string, string> = {
markdown: "md",
elixir: "ex",
terraform: "tf",
shell: "sh",
ruby: "rb",
kotlin: "kt",
powershell: "ps1",
pwsh: "ps1",
protobuf: "proto",
perl: "pl",
latex: "tex",
stex: "tex",
};
function fenceLanguageToExtension(info: string | null | undefined): string | null {
export function fenceLanguageToExtension(info: string | null | undefined): string | null {
if (!info) return null;
const first = info.trim().split(/\s+/)[0]?.toLowerCase();
if (!first) return null;
-206
View File
@@ -19,11 +19,9 @@ 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";
@@ -42,17 +40,13 @@ 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,
@@ -1493,206 +1487,6 @@ 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;
@@ -10,11 +10,7 @@ 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 {
isPromptInActiveSegment,
isRewindableMessage,
useRewindMenuItems,
} from "./use-rewind-capabilities";
import { isRewindableMessage, useRewindMenuItems } from "./use-rewind-capabilities";
export function RewindCommandCenterRegistration({
serverId,
@@ -46,16 +42,10 @@ export function RewindCommandCenterRegistration({
if (timeline.status !== "synced" || timeline.newer === "available") {
return undefined;
}
const candidate =
return (
session.agentStreamHead.get(agentId)?.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;
timeline.items.findLast((item) => item.kind === "user_message")
);
});
const { rewindAgent, isPending } = useRewindAgentMutation({
serverId,
@@ -9,7 +9,6 @@ import { useRewindComposerRestore } from "./composer-restore";
import { useSessionStore } from "@/stores/session-store";
import { shouldRestoreComposerForRewindMode } from "./rewind-mode";
import { getHostRuntimeStore } from "@/runtime/host-runtime";
import { hostSupportsFeature } from "@/runtime/host-features";
interface UseRewindAgentMutationInput {
serverId?: string;
@@ -43,16 +42,7 @@ export function useRewindAgentMutation(input: UseRewindAgentMutationInput): {
throw new Error(t("common.errors.daemonClientUnavailable"));
}
await input.client.rewindAgent(input.agentId, input.messageId, mode);
// COMPAT(timelineRewindOperations): added in v0.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) {
if (mode !== "files") {
const cursor = input.serverId
? useSessionStore
.getState()
@@ -26,20 +26,6 @@ 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<
+7 -79
View File
@@ -1,13 +1,7 @@
import type { SelectedFile } from "@/attachments/selected-file";
import { FILE_UPLOAD_MAX_BYTES } from "@/attachments/upload-limit";
import type { AgentProvider, ProviderOptions } from "@getpaseo/protocol/agent-types";
import type {
ActiveTurnBehavior,
AgentSnapshotPayload,
ForgeSearchItem,
} from "@getpaseo/protocol/messages";
import { AgentProviderSwitchError } from "@getpaseo/client/internal/daemon-client";
import type { StagedProviderSwitch } from "@/composer/provider-switch";
import type { ForgeSearchItem } from "@getpaseo/protocol/messages";
import type { ActiveTurnBehavior } from "@getpaseo/protocol/messages";
import type {
AttachmentMetadata,
ComposerAttachment,
@@ -21,13 +15,7 @@ import {
splitComposerAttachmentsForSubmit,
type ComposerAttachmentSubmitFormat,
} from "@/composer/attachments/submit";
import {
createPendingProviderSwitchItem,
createUserMessage,
generateMessageId,
type ProviderSwitchItem,
type UserMessageItem,
} from "@/types/stream";
import { createUserMessage, generateMessageId, 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";
@@ -68,20 +56,6 @@ 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: {
@@ -101,11 +75,7 @@ export interface ComposerCancelClient {
}
export interface MessageSubmissionWriter {
begin: (
agentId: string,
message: UserMessageItem,
options?: { providerSwitch?: ProviderSwitchItem },
) => void;
begin: (agentId: string, message: UserMessageItem) => void;
accept: (agentId: string, clientMessageId: string) => void;
reject: (agentId: string, clientMessageId: string) => MessageSubmissionRejectionOutcome;
}
@@ -227,10 +197,6 @@ 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>;
}
export async function dispatchComposerAgentMessage(
@@ -240,54 +206,19 @@ export async function dispatchComposerAgentMessage(
format: input.attachmentSubmitFormat,
});
const clientMessageId = generateMessageId();
const timestamp = new Date();
const userMessage = createUserMessage({
clientMessageId,
text: input.text,
timestamp,
timestamp: new Date(),
images: wirePayload.images,
attachments: wirePayload.attachments,
...(input.activeTurnBehavior === "steer" && input.activeTurnId && !input.stagedProviderSwitch
...(input.activeTurnBehavior === "steer" && input.activeTurnId
? { turnId: input.activeTurnId }
: {}),
});
const pendingProviderSwitch =
input.stagedProviderSwitch &&
input.client.switchAgentProvider &&
input.currentProvider &&
input.stagedProviderSwitch.provider !== input.currentProvider
? createPendingProviderSwitchItem({
clientMessageId,
fromProvider: input.currentProvider,
toProvider: input.stagedProviderSwitch.provider,
fromModel: input.currentModel ?? null,
toModel: input.stagedProviderSwitch.model,
timestamp,
})
: undefined;
input.submission.begin(
input.agentId,
userMessage,
pendingProviderSwitch ? { providerSwitch: pendingProviderSwitch } : undefined,
);
input.submission.begin(input.agentId, userMessage);
try {
const imagesData = await input.encodeImages(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,
images: imagesData ?? [],
attachments: wirePayload.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 } : {}),
@@ -297,9 +228,6 @@ 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,21 +16,12 @@ 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 {
@@ -111,7 +102,6 @@ import {
type AgentProfilePicker,
type AgentProfileSeed,
type DraftAgentProfileControls,
type MaterializedAgentProfile,
} from "@/agent-profiles";
import { buildSettingsHostSectionRoute } from "@/utils/host-routes";
@@ -148,7 +138,6 @@ interface ControlledAgentControlsProps {
modeControl?: AgentModeControlValue | null;
modelSelectorServerId?: string | null;
isCompactLayout?: boolean;
openModelBrowserAtProviders?: boolean;
}
export interface DraftAgentControlsProps {
@@ -462,7 +451,6 @@ function ControlledAgentControls({
modeControl,
modelSelectorServerId = null,
isCompactLayout,
openModelBrowserAtProviders,
}: ControlledAgentControlsProps) {
const { t } = useTranslation();
const isCompactFormFactor = useIsCompactFormFactor();
@@ -722,7 +710,6 @@ function ControlledAgentControls({
showLabels={presentation.showModelLabel}
modelSelectorServerId={modelSelectorServerId}
canSwitchProvider={Boolean(onSelectProviderAndModel)}
openModelBrowserAtProviders={openModelBrowserAtProviders}
/>
)}
{!isCompact ? (
@@ -920,7 +907,6 @@ interface SheetAgentControlsContentProps extends AgentControlsContentProps {
displayThinking: string | null;
handleSheetModelSelect: (providerId: string, modelId: string) => void;
canSwitchProvider: boolean;
openModelBrowserAtProviders?: boolean;
}
function SheetAgentControlsContent(props: SheetAgentControlsContentProps) {
@@ -953,7 +939,6 @@ function SheetAgentControlsContent(props: SheetAgentControlsContentProps) {
showLabels,
modelSelectorServerId,
canSwitchProvider,
openModelBrowserAtProviders,
} = props;
const sheetControls = (
@@ -1003,7 +988,6 @@ function SheetAgentControlsContent(props: SheetAgentControlsContentProps) {
glyphs={glyphs}
showLabels={showLabels}
canSwitchProvider={canSwitchProvider}
openModelBrowserAtProviders={openModelBrowserAtProviders}
>
{sheetControls}
</CompactModelSheet>
@@ -1022,148 +1006,6 @@ 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,
@@ -1171,22 +1013,15 @@ export const AgentControls = memo(function AgentControls({
onDropdownClose,
isCompactLayout,
}: AgentControlsProps) {
const { preferences, updatePreferences } = useFormPreferences();
const { 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 liveModeControl = useLiveAgentModeControl(serverId, agentId);
const modeControl = useLiveAgentModeControl(serverId, agentId);
const commandCenterModes = toCommandCenterModes(modeControl);
const modeProviderDefinitions = getModeProviderDefinitions(modeControl);
const {
entries: snapshotEntries,
@@ -1196,35 +1031,24 @@ 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, effectiveProvider),
[snapshotEntries, effectiveProvider],
() => resolveProviderSnapshotEntry(snapshotEntries, agent?.provider),
[snapshotEntries, agent?.provider],
);
const models = filterSelectableModels(snapshotSelectedEntry?.models ?? null);
const selectedProviderIsLoading = snapshotSelectedEntry?.status === "loading";
const agentProviderDefinitions = useMemo(
() => buildAgentProviderDefinitions(effectiveProvider, snapshotEntries),
[effectiveProvider, snapshotEntries],
() => buildAgentProviderDefinitions(agent?.provider, snapshotEntries),
[agent?.provider, snapshotEntries],
);
const agentProviderModels = useMemo(
() => buildAgentProviderModels(effectiveProvider, models),
[effectiveProvider, models],
() => buildAgentProviderModels(agent?.provider, models),
[agent?.provider, 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)];
}
@@ -1232,19 +1056,14 @@ export const AgentControls = memo(function AgentControls({
providerDefinitions: agentProviderDefinitions,
modelsByProvider: agentProviderModels,
});
}, [
agentProviderDefinitions,
agentProviderModels,
effectiveProvider,
snapshotEntries,
snapshotSelectedEntry,
supportsProviderSwitching,
]);
}, [agentProviderDefinitions, agentProviderModels, snapshotSelectedEntry]);
const modelSelection = resolveAgentModelSelectionWithStagedSwitch({
const modelSelection = resolveAgentModelSelection({
models,
agent,
activeStagedSwitch,
runtimeModelId: agent?.runtimeModelId,
configuredModelId: agent?.model,
runtimeThinkingOptionId: agent?.runtimeThinkingOptionId,
explicitThinkingOptionId: agent?.thinkingOptionId,
});
const modelOptions = useMemo<AgentControlOption[]>(() => {
@@ -1261,71 +1080,13 @@ export const AgentControls = memo(function AgentControls({
const agentProvider = agent?.provider;
const activeModelId = modelSelection.activeModelId;
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(
const handleSelectModel = useCallback(
async (modelId: string) => {
if (!client || !agentProvider) {
return;
}
try {
await client.setAgentModel(agentId, modelId, { expectedProvider: agentProvider });
await client.setAgentModel(agentId, modelId);
await updatePreferences((current) =>
mergeProviderPreferences({
preferences: current,
@@ -1340,147 +1101,21 @@ export const AgentControls = memo(function AgentControls({
},
[agentId, agentProvider, client, toast, updatePreferences],
);
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,
],
);
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],
(_provider: AgentProvider, modelId: string) => handleSelectModel(modelId),
[handleSelectModel],
);
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],
);
// 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 profileModeIds = useMemo(
() => resolveSnapshotModeIds(liveSnapshotEntry),
[liveSnapshotEntry],
() => resolveSnapshotModeIds(snapshotSelectedEntry),
[snapshotSelectedEntry],
);
const profileTarget = useMemo<AgentProfileApplyTarget>(
() => ({
kind: "agent",
agentId,
availableModeIds: profileModeIds,
currentProvider: agentProvider,
isSwitchInFlight: () => isStagedProviderSwitchInFlight(serverId, agentId),
onApplySameProvider: handleClearStagedSwitchOnProfile,
onStageProviderSwitch: supportsProviderSwitching ? handleStageAgentProfileSwitch : undefined,
}),
[
agentId,
agentProvider,
handleClearStagedSwitchOnProfile,
handleStageAgentProfileSwitch,
profileModeIds,
serverId,
supportsProviderSwitching,
],
() => ({ kind: "agent", agentId, availableModeIds: profileModeIds }),
[agentId, profileModeIds],
);
const agentProfiles = useAgentProfilePicker({
serverId,
@@ -1493,13 +1128,6 @@ 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;
}
@@ -1520,35 +1148,18 @@ export const AgentControls = memo(function AgentControls({
});
}
void client
.setAgentThinkingOption(agentId, thinkingOptionId, { expectedProvider: agentProvider })
.setAgentThinkingOption(agentId, thinkingOptionId)
.then((notice) => showProviderNoticeToast(toast, notice))
.catch((error) => {
console.warn("[AgentControls] setAgentThinkingOption failed", error);
toast.error(toErrorMessage(error));
});
},
[
activeModelId,
activeStagedSwitch,
agentId,
agentProvider,
client,
serverId,
toast,
updatePreferences,
],
[activeModelId, agentId, agentProvider, client, 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;
}
@@ -1565,36 +1176,15 @@ export const AgentControls = memo(function AgentControls({
).catch((error) => {
console.warn("[AgentControls] persist option preference failed", error);
});
void client
.setAgentOptions(agentId, { [key]: value }, { expectedProvider: agentProvider })
.catch((error) => {
console.warn("[AgentControls] setAgentOptions failed", error);
toast.error(toErrorMessage(error));
});
void client.setAgentOptions(agentId, { [key]: value }).catch((error) => {
console.warn("[AgentControls] setAgentOptions failed", error);
toast.error(toErrorMessage(error));
});
},
[
activeStagedSwitch,
agentId,
agentProvider,
client,
serverId,
stagedDraftOptions,
toast,
updatePreferences,
],
[agentId, agentProvider, client, toast, updatePreferences],
);
const liveOptionControls = useAgentOptionControls(agent, handleSetOption);
const agentOptionControls = useMemo<ComposerOptionControls>(
() =>
resolveAgentOptionControlsForComposer({
activeStagedSwitch,
stagedControls: stagedDraftOptions.optionControls,
liveOptionControls,
onSetOption: handleSetOption,
}),
[activeStagedSwitch, handleSetOption, liveOptionControls, stagedDraftOptions.optionControls],
);
const agentOptionControls = useAgentOptionControls(agent, handleSetOption);
// The agent's composer exists apart from this component; while this is mounted, prompt
// commands go through the input the user is typing in.
@@ -1618,12 +1208,12 @@ export const AgentControls = memo(function AgentControls({
() => ({
serverId,
ownerKey: agentId,
provider: effectiveProvider,
provider: agentProvider,
providerDefinitions: modeProviderDefinitions,
profiles: agentProfiles,
models: {
providers: agentModelSelectorProviders,
selectedProvider: effectiveProvider,
selectedProvider: agentProvider,
selectedModelId: activeModelId,
select: handleSelectCommandCenterModel,
},
@@ -1642,7 +1232,7 @@ export const AgentControls = memo(function AgentControls({
client,
agentId,
agentModelSelectorProviders,
effectiveProvider,
agentProvider,
commandCenterModes,
handleSelectCommandCenterModel,
handleSelectThinkingOption,
@@ -1662,8 +1252,8 @@ export const AgentControls = memo(function AgentControls({
);
const handleModelSelectorOpen = useCallback(() => {
refetchSnapshotIfStale(supportsProviderSwitching ? undefined : effectiveProvider);
}, [effectiveProvider, refetchSnapshotIfStale, supportsProviderSwitching]);
refetchSnapshotIfStale(agentProvider);
}, [agentProvider, refetchSnapshotIfStale]);
const handleRetryModelProvider = useCallback(
(provider: AgentProvider) => {
@@ -1676,18 +1266,6 @@ 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}
@@ -1695,17 +1273,21 @@ export const AgentControls = memo(function AgentControls({
<>
{profileEditor.element}
<ControlledAgentControls
{...resolvedControlProps}
provider={agent.provider}
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}
@@ -1939,7 +1521,6 @@ export function DraftAgentControls({
modeControl={modeControl}
modelSelectorServerId={modelSelectorServerId}
isCompactLayout={isCompactLayout}
openModelBrowserAtProviders
/>
</>
) : null}
@@ -282,7 +282,7 @@ export function useLiveAgentModeControl(
console.warn("[AgentModeControl] persist mode preference failed", error);
});
void client
.setAgentMode(agentId, modeId, { expectedProvider: slice.provider })
.setAgentMode(agentId, modeId)
.then((notice) => showProviderNoticeToast(toast, notice))
.catch((error) => {
console.warn("[AgentModeControl] setAgentMode failed", error);
@@ -13,17 +13,17 @@ describe("model sheet opening", () => {
it("starts drafts at providers even when only one provider is available", () => {
expect(
resolveModelSheetOpening({
openAtProviders: true,
canSwitchProvider: true,
providers: [codex],
selectedProvider: "codex",
}),
).toEqual({ kind: "all" });
});
it("opens a running agent directly at its current provider even when other providers are available", () => {
it("opens a running agent directly at its fixed provider", () => {
expect(
resolveModelSheetOpening({
openAtProviders: false,
canSwitchProvider: false,
providers: [claude, codex],
selectedProvider: "codex",
}),
@@ -33,7 +33,7 @@ describe("model sheet opening", () => {
it("falls back to the only provider while live state catches up", () => {
expect(
resolveModelSheetOpening({
openAtProviders: false,
canSwitchProvider: false,
providers: [codex],
selectedProvider: "",
}),
@@ -2,16 +2,15 @@ import type { ModelBrowserView } from "@/components/model-browser-view";
import type { ProviderSelectorProvider } from "@/provider-selection/provider-selection";
export function resolveModelSheetOpening({
openAtProviders,
canSwitchProvider,
providers,
selectedProvider,
}: {
/** Drafts open at the provider list; live agents open directly at their active provider. */
openAtProviders: boolean;
canSwitchProvider: boolean;
providers: ProviderSelectorProvider[];
selectedProvider: string;
}): ModelBrowserView {
if (openAtProviders) return { kind: "all" };
if (canSwitchProvider) return { kind: "all" };
const provider = providers.find((entry) => entry.id === selectedProvider) ?? providers[0] ?? null;
return provider
@@ -68,8 +68,6 @@ interface CompactModelSheetProps {
/** False when the toolbar is too narrow for labels: the trigger shows the provider glyph only. */
showLabels: boolean;
canSwitchProvider: boolean;
/** Drafts open the model browser at the all-providers list; live agents open at their active provider. */
openModelBrowserAtProviders?: boolean;
/** Carries the composer's contexts into the sheets, which draw away from it. */
contextBridge?: ContextBridge | null;
children: ReactNode;
@@ -162,7 +160,6 @@ export function CompactModelSheet({
glyphs,
showLabels,
canSwitchProvider,
openModelBrowserAtProviders = false,
contextBridge = null,
children,
}: CompactModelSheetProps) {
@@ -242,7 +239,7 @@ export function CompactModelSheet({
const openModelBrowser = useCallback(() => {
Keyboard.dismiss();
const destination = resolveModelSheetOpening({
openAtProviders: openModelBrowserAtProviders,
canSwitchProvider,
providers: availableProviders,
selectedProvider,
});
@@ -252,7 +249,7 @@ export function CompactModelSheet({
modelBrowser.drillDown(destination.providerId, destination.providerLabel);
}
setIsModelBrowserOpen(true);
}, [availableProviders, modelBrowser, openModelBrowserAtProviders, selectedProvider]);
}, [availableProviders, canSwitchProvider, modelBrowser, selectedProvider]);
const closeModelBrowser = useCallback(() => {
setIsModelBrowserOpen(false);
+43 -238
View File
@@ -9,21 +9,6 @@ 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,
@@ -63,7 +48,6 @@ import { usePanelStore, type MobilePanelView } from "@/stores/panel-store";
import { usePointerCapabilities } from "@/hooks/pointer-capabilities";
import { useShallow } from "zustand/shallow";
import {
ArrowRightLeft,
ArrowUp,
Square,
Pencil,
@@ -314,29 +298,16 @@ 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 {
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,
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,
};
};
}
@@ -1380,57 +1351,10 @@ 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);
@@ -1732,6 +1656,15 @@ function ComposerContentImpl({
});
}, []);
const handleImagesDropped = useCallback(
(images: ImageAttachment[]) => {
if (images.length === 0) return;
addImages(images);
focusInput();
},
[addImages, focusInput],
);
const handleWorkspaceFileDropped = useCallback(
(payload: WorkspaceFileDragPayload) => {
if (!workspaceId) {
@@ -1785,64 +1718,25 @@ function ComposerContentImpl({
if (!client) {
throw new Error(t("workspace.terminal.hostDisconnected"));
}
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,
}),
encodeImages,
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);
}
}
await dispatchComposerAgentMessage({
client,
agentId: targetAgentId,
text,
attachments: sendAttachments,
attachmentSubmitFormat: resolveComposerAttachmentSubmitFormat({
supportsForgeAttachments: supportsForgeSearch,
}),
encodeImages,
submission: createMessageSubmissionWriter(serverId),
activeTurnBehavior,
activeTurnId:
activeTurnBehavior === "steer"
? (selectAgentTurnPresentation(
useSessionStore.getState().sessions[serverId],
targetAgentId,
).turnId ?? undefined)
: undefined,
});
onAttentionPromptSend?.();
};
}, [appSettings.sendBehavior, client, onAttentionPromptSend, serverId, supportsForgeSearch, t]);
@@ -1918,7 +1812,7 @@ function ComposerContentImpl({
attachments: outgoingAttachments,
hasExternalContent,
allowEmptySubmit,
forceSend: stagedSwitch && isAgentRunning ? false : forceSend,
forceSend,
submitBehavior,
isAgentRunning,
// Parent-managed submits are still valid submit paths even when the
@@ -1960,7 +1854,6 @@ function ComposerContentImpl({
queueMessage,
setSelectedAttachments,
replaceUserInput,
stagedSwitch,
submitBehavior,
submitMessage,
t,
@@ -2104,6 +1997,7 @@ function ComposerContentImpl({
toastErrorRef.current(t("composer.errors.daemonClientDisconnected"));
return;
}
focusInput();
await uploadSelectedFiles(files);
} catch (error) {
console.error("[Composer] Failed to upload dropped files:", error);
@@ -2112,7 +2006,7 @@ function ComposerContentImpl({
);
}
},
[client, isConnected, t, uploadSelectedFiles],
[client, focusInput, isConnected, t, uploadSelectedFiles],
);
const handleRemoveAttachment = useCallback(
@@ -2195,17 +2089,15 @@ function ComposerContentImpl({
queue: queueWriter,
});
if (!result) return;
useSessionStore.getState().setQueuedSendError(serverId, agentId, null);
replaceUserInput(result.text);
setSelectedAttachments(result.attachments);
},
[agentId, queueWriter, replaceUserInput, serverId, setSelectedAttachments],
[agentId, queueWriter, replaceUserInput, 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,
@@ -2219,7 +2111,7 @@ function ComposerContentImpl({
setSendError(result.errorMessage);
}
},
[agentId, queueWriter, serverId, submitMessage, t],
[agentId, queueWriter, submitMessage, t],
);
const handleQueue = useCallback(
@@ -2662,7 +2554,7 @@ function ComposerContentImpl({
// backdrop and rejects the drop atomically, instead of accepting a drop with no feedback.
useFileDrop(
{
onFiles: addImages,
onFiles: handleImagesDropped,
onGenericFiles: handleGenericFilesDropped,
onWorkspaceFile: handleWorkspaceFileDropped,
},
@@ -2672,78 +2564,18 @@ 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 || failedStartupSettings?.errorMessage || queuedSendError;
const displayError = externalError || sendError;
const sendErrorNode = useMemo(
() =>
displayError ? (
<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>
<Alert variant="error" size="sm" description={displayError} testID="composer-error" />
) : null,
[
displayError,
failedStartupSettings,
handleDismissFailedStartupSettings,
handleRetryFailedStartupSettings,
t,
],
[displayError],
);
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
@@ -2769,7 +2601,6 @@ function ComposerContentImpl({
>
<View style={inputAreaContentStyle}>
{isFullscreen ? null : queueList}
{isFullscreen ? null : stagedSwitchBannerNode}
{!isFullscreen && sendErrorNode}
<ComposerAutocompleteBinding
@@ -3025,35 +2856,9 @@ 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);
@@ -1,20 +0,0 @@
export {
applyFailedStartupSettings,
beginStagedProviderSwitch,
clearStagedProviderSwitch,
discardFailedStartupSettings,
endStagedProviderSwitch,
getFailedStartupSettings,
getStagedProviderSwitch,
isStagedProviderSwitchInFlight,
settleCommittedProviderSwitch,
settleStagedProviderSwitch,
useFailedStartupSettings,
useIsStagedProviderSwitchInFlight,
useStagedProviderSwitch,
useStagedProviderSwitchStore,
type FailedStartupSettings,
type LiveAgentSettingsWriter,
type SettleCommittedProviderSwitchResult,
type StagedProviderSwitch,
} from "./store";
File diff suppressed because it is too large Load Diff
@@ -1,86 +0,0 @@
import { beforeEach, describe, expect, it } from "vitest";
import {
clearStagedProviderSwitch,
getStagedProviderSwitch,
settleStagedProviderSwitch,
useStagedProviderSwitchStore,
} from "./index";
describe("staged provider switch store", () => {
beforeEach(() => {
useStagedProviderSwitchStore.setState({ stagedByKey: new Map() });
});
it("stages, patches, and clears per server and agent", () => {
const store = useStagedProviderSwitchStore.getState();
store.stage("srv-1", "agent-1", {
provider: "codex",
model: "gpt-5.4",
thinkingOptionId: "high",
modeId: "auto",
providerOptions: { fast_mode: true },
});
store.stage("srv-1", "agent-2", {
provider: "opencode",
model: null,
thinkingOptionId: null,
modeId: null,
providerOptions: {},
});
expect(getStagedProviderSwitch("srv-1", "agent-1")).toEqual({
provider: "codex",
model: "gpt-5.4",
thinkingOptionId: "high",
modeId: "auto",
providerOptions: { fast_mode: true },
});
store.patch("srv-1", "agent-1", (current) => ({
...current,
thinkingOptionId: "medium",
}));
expect(getStagedProviderSwitch("srv-1", "agent-1")?.thinkingOptionId).toBe("medium");
clearStagedProviderSwitch("srv-1", "agent-1");
expect(getStagedProviderSwitch("srv-1", "agent-1")).toBeNull();
expect(getStagedProviderSwitch("srv-1", "agent-2")?.provider).toBe("opencode");
store.clearForServer("srv-1");
expect(getStagedProviderSwitch("srv-1", "agent-2")).toBeNull();
});
it("settles only the draft that was sent and preserves any newer selection or edit", () => {
const store = useStagedProviderSwitchStore.getState();
store.stage("srv-1", "agent-1", {
provider: "codex",
model: "gpt-5.4",
thinkingOptionId: null,
modeId: null,
providerOptions: {},
});
const sentDraft = getStagedProviderSwitch("srv-1", "agent-1")!;
// User chooses Copilot before Codex reply returns -> settling Codex draft preserves Copilot.
store.stage("srv-1", "agent-1", {
provider: "copilot",
model: "gpt-5",
thinkingOptionId: null,
modeId: null,
providerOptions: {},
});
settleStagedProviderSwitch("srv-1", "agent-1", sentDraft);
const copilotDraft = getStagedProviderSwitch("srv-1", "agent-1")!;
expect(copilotDraft.provider).toBe("copilot");
// Patching the draft also produces a newer revision that settling the older reference preserves.
store.patch("srv-1", "agent-1", (current) => ({ ...current, thinkingOptionId: "high" }));
settleStagedProviderSwitch("srv-1", "agent-1", copilotDraft);
const patchedCopilot = getStagedProviderSwitch("srv-1", "agent-1")!;
expect(patchedCopilot.thinkingOptionId).toBe("high");
// Settling the current draft clears it cleanly.
settleStagedProviderSwitch("srv-1", "agent-1", patchedCopilot);
expect(getStagedProviderSwitch("srv-1", "agent-1")).toBeNull();
});
});
@@ -1,407 +0,0 @@
import { create } from "zustand";
import type { AgentProvider, ProviderOptions } from "@getpaseo/protocol/agent-types";
import type { AgentConfigApply } from "@getpaseo/protocol/messages";
export interface StagedProviderSwitch {
provider: AgentProvider;
model: string | null;
thinkingOptionId: string | null;
modeId: string | null;
providerOptions: ProviderOptions;
}
function stagedKey(serverId: string, agentId: string): string {
return `${serverId}:${agentId}`;
}
export interface LiveAgentSettingsWriter {
applyAgentConfig?: (
agentId: string,
config: AgentConfigApply,
options?: { expectedProvider?: AgentProvider },
) => Promise<unknown>;
setAgentModel?: (
agentId: string,
modelId: string | null,
options?: { expectedProvider?: AgentProvider },
) => Promise<unknown>;
setAgentMode?: (
agentId: string,
modeId: string,
options?: { expectedProvider?: AgentProvider },
) => Promise<unknown>;
setAgentThinkingOption?: (
agentId: string,
thinkingOptionId: string,
options?: { expectedProvider?: AgentProvider },
) => Promise<unknown>;
setAgentOptions?: (
agentId: string,
options: ProviderOptions,
mutationOptions?: { expectedProvider?: AgentProvider },
) => Promise<unknown>;
}
export interface FailedStartupSettings {
provider: AgentProvider;
bundle: AgentConfigApply;
errorMessage: string;
}
export type SettleCommittedProviderSwitchResult =
| { applied: true }
| { applied: false; errorMessage: string };
interface StagedProviderSwitchState {
stagedByKey: Map<string, StagedProviderSwitch>;
inFlightByKey: Map<string, number>;
failedStartupSettingsByKey: Map<string, FailedStartupSettings>;
stage: (serverId: string, agentId: string, draft: StagedProviderSwitch) => void;
patch: (
serverId: string,
agentId: string,
updater: (current: StagedProviderSwitch) => StagedProviderSwitch,
) => void;
beginSwitch: (serverId: string, agentId: string) => void;
endSwitch: (serverId: string, agentId: string) => void;
setFailedStartupSettings: (
serverId: string,
agentId: string,
failed: FailedStartupSettings | null,
) => void;
settle: (serverId: string, agentId: string, sentDraft: StagedProviderSwitch) => void;
clear: (serverId: string, agentId: string) => void;
clearForServer: (serverId: string) => void;
}
export const useStagedProviderSwitchStore = create<StagedProviderSwitchState>((set) => ({
stagedByKey: new Map(),
inFlightByKey: new Map(),
failedStartupSettingsByKey: new Map(),
stage: (serverId, agentId, draft) =>
set((state) => {
const next = new Map(state.stagedByKey);
next.set(stagedKey(serverId, agentId), draft);
return { stagedByKey: next };
}),
patch: (serverId, agentId, updater) =>
set((state) => {
const key = stagedKey(serverId, agentId);
const current = state.stagedByKey.get(key);
if (!current) return state;
const updated = updater(current);
if (updated === current) return state;
const next = new Map(state.stagedByKey);
next.set(key, updated);
return { stagedByKey: next };
}),
beginSwitch: (serverId, agentId) =>
set((state) => {
const key = stagedKey(serverId, agentId);
const next = new Map(state.inFlightByKey);
next.set(key, (next.get(key) ?? 0) + 1);
return { inFlightByKey: next };
}),
endSwitch: (serverId, agentId) =>
set((state) => {
const key = stagedKey(serverId, agentId);
const count = state.inFlightByKey.get(key) ?? 0;
if (count <= 0) return state;
const next = new Map(state.inFlightByKey);
if (count === 1) {
next.delete(key);
} else {
next.set(key, count - 1);
}
return { inFlightByKey: next };
}),
setFailedStartupSettings: (serverId, agentId, failed) =>
set((state) => {
const key = stagedKey(serverId, agentId);
const next = new Map(state.failedStartupSettingsByKey);
if (failed === null) {
if (!next.has(key)) return state;
next.delete(key);
} else {
next.set(key, failed);
}
return { failedStartupSettingsByKey: next };
}),
settle: (serverId, agentId, sentDraft) =>
set((state) => {
const key = stagedKey(serverId, agentId);
const current = state.stagedByKey.get(key);
if (!current || current !== sentDraft) return state;
const next = new Map(state.stagedByKey);
next.delete(key);
return { stagedByKey: next };
}),
clear: (serverId, agentId) =>
set((state) => {
const key = stagedKey(serverId, agentId);
if (!state.stagedByKey.has(key)) return state;
const next = new Map(state.stagedByKey);
next.delete(key);
return { stagedByKey: next };
}),
clearForServer: (serverId) =>
set((state) => {
const prefix = `${serverId}:`;
let changed = false;
const next = new Map(state.stagedByKey);
for (const key of next.keys()) {
if (key.startsWith(prefix)) {
next.delete(key);
changed = true;
}
}
const nextInFlight = new Map(state.inFlightByKey);
for (const key of nextInFlight.keys()) {
if (key.startsWith(prefix)) {
nextInFlight.delete(key);
changed = true;
}
}
const nextFailed = new Map(state.failedStartupSettingsByKey);
for (const key of nextFailed.keys()) {
if (key.startsWith(prefix)) {
nextFailed.delete(key);
changed = true;
}
}
return changed
? {
stagedByKey: next,
inFlightByKey: nextInFlight,
failedStartupSettingsByKey: nextFailed,
}
: state;
}),
}));
export function getStagedProviderSwitch(
serverId: string,
agentId: string,
): StagedProviderSwitch | null {
return (
useStagedProviderSwitchStore.getState().stagedByKey.get(stagedKey(serverId, agentId)) ?? null
);
}
export function beginStagedProviderSwitch(serverId: string, agentId: string): void {
useStagedProviderSwitchStore.getState().beginSwitch(serverId, agentId);
}
export function endStagedProviderSwitch(serverId: string, agentId: string): void {
useStagedProviderSwitchStore.getState().endSwitch(serverId, agentId);
}
export function isStagedProviderSwitchInFlight(serverId: string, agentId: string): boolean {
return (
(useStagedProviderSwitchStore.getState().inFlightByKey.get(stagedKey(serverId, agentId)) ?? 0) >
0
);
}
export function getFailedStartupSettings(
serverId: string,
agentId: string,
): FailedStartupSettings | null {
return (
useStagedProviderSwitchStore
.getState()
.failedStartupSettingsByKey.get(stagedKey(serverId, agentId)) ?? null
);
}
export function useFailedStartupSettings(
serverId: string,
agentId: string,
): FailedStartupSettings | null {
return useStagedProviderSwitchStore(
(state) => state.failedStartupSettingsByKey.get(stagedKey(serverId, agentId)) ?? null,
);
}
export function discardFailedStartupSettings(serverId: string, agentId: string): void {
useStagedProviderSwitchStore.getState().setFailedStartupSettings(serverId, agentId, null);
}
export function settleStagedProviderSwitch(
serverId: string,
agentId: string,
sentDraft: StagedProviderSwitch,
): void {
useStagedProviderSwitchStore.getState().settle(serverId, agentId, sentDraft);
}
function diffProviderOptions(
sent: ProviderOptions,
edited: ProviderOptions,
): ProviderOptions | null {
const patch: ProviderOptions = {};
let hasDiff = false;
for (const [key, value] of Object.entries(edited)) {
if (sent[key] !== value) {
patch[key] = value;
hasDiff = true;
}
}
return hasDiff ? patch : null;
}
function buildEditedSettingsBundle(
sentDraft: StagedProviderSwitch,
editedDraft: StagedProviderSwitch,
): AgentConfigApply | null {
const config: AgentConfigApply = {};
let hasChanges = false;
if (editedDraft.model !== sentDraft.model) {
config.modelId = editedDraft.model;
hasChanges = true;
}
if (editedDraft.modeId !== sentDraft.modeId && editedDraft.modeId !== null) {
config.modeId = editedDraft.modeId;
hasChanges = true;
}
if (
editedDraft.thinkingOptionId !== sentDraft.thinkingOptionId &&
editedDraft.thinkingOptionId !== null
) {
config.thinkingOptionId = editedDraft.thinkingOptionId;
hasChanges = true;
}
const optionsPatch = diffProviderOptions(sentDraft.providerOptions, editedDraft.providerOptions);
if (optionsPatch) {
config.options = optionsPatch;
hasChanges = true;
}
return hasChanges ? config : null;
}
async function applyEditedDraftSettingsToLiveAgent(
agentId: string,
bundle: AgentConfigApply,
expectedProvider: AgentProvider,
client: LiveAgentSettingsWriter,
): Promise<void> {
const providerGuard = { expectedProvider };
if (client.applyAgentConfig) {
await client.applyAgentConfig(agentId, bundle, providerGuard);
return;
}
if (bundle.modelId !== undefined && client.setAgentModel) {
await client.setAgentModel(agentId, bundle.modelId, providerGuard);
}
if (bundle.modeId !== undefined && client.setAgentMode) {
await client.setAgentMode(agentId, bundle.modeId, providerGuard);
}
if (
bundle.thinkingOptionId !== undefined &&
bundle.thinkingOptionId !== null &&
client.setAgentThinkingOption
) {
await client.setAgentThinkingOption(agentId, bundle.thinkingOptionId, providerGuard);
}
if (bundle.options && client.setAgentOptions) {
await client.setAgentOptions(agentId, bundle.options, providerGuard);
}
}
/**
* Settles the staged draft captured by a committed switch and awaits any edited settings
* for the provider that just became live before callers release queued follow-up prompts.
* - Untouched draft: cleared.
* - Newer draft targeting a different provider: preserved for the next switch.
* - Newer draft editing settings of the provider that just became live: applied atomically
* (via `applyAgentConfig` when available, else sequential setters) before settling the draft.
* If the daemon rejects an edit, the draft is kept intact and `{ applied: false, errorMessage }`
* is returned so callers surface the error and hold any queued follow-up prompt.
*/
export async function settleCommittedProviderSwitch(input: {
serverId: string;
agentId: string;
sentDraft: StagedProviderSwitch;
committedProvider?: AgentProvider | null;
client?: LiveAgentSettingsWriter | null;
}): Promise<SettleCommittedProviderSwitchResult> {
const { serverId, agentId, sentDraft, committedProvider, client } = input;
const store = useStagedProviderSwitchStore.getState();
store.settle(serverId, agentId, sentDraft);
const remaining = getStagedProviderSwitch(serverId, agentId);
const liveProvider = committedProvider ?? sentDraft.provider;
if (!remaining || remaining.provider !== liveProvider) {
return { applied: true };
}
const bundle = buildEditedSettingsBundle(sentDraft, remaining);
if (!bundle || !client) {
store.settle(serverId, agentId, remaining);
return { applied: true };
}
try {
await applyEditedDraftSettingsToLiveAgent(agentId, bundle, liveProvider, client);
store.settle(serverId, agentId, remaining);
return { applied: true };
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
store.settle(serverId, agentId, remaining);
store.setFailedStartupSettings(serverId, agentId, {
provider: liveProvider,
bundle,
errorMessage,
});
console.warn("[ProviderSwitch] failed to forward edited settings after switch", error);
return { applied: false, errorMessage };
}
}
/** Retries applying previously failed startup settings for a committed provider switch. */
export async function applyFailedStartupSettings(input: {
serverId: string;
agentId: string;
client: LiveAgentSettingsWriter;
}): Promise<SettleCommittedProviderSwitchResult> {
const { serverId, agentId, client } = input;
const failed = getFailedStartupSettings(serverId, agentId);
if (!failed) {
return { applied: true };
}
const store = useStagedProviderSwitchStore.getState();
try {
await applyEditedDraftSettingsToLiveAgent(agentId, failed.bundle, failed.provider, client);
store.setFailedStartupSettings(serverId, agentId, null);
return { applied: true };
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
store.setFailedStartupSettings(serverId, agentId, { ...failed, errorMessage });
console.warn("[ProviderSwitch] failed to retry startup settings", error);
return { applied: false, errorMessage };
}
}
export function clearStagedProviderSwitch(serverId: string, agentId: string): void {
useStagedProviderSwitchStore.getState().clear(serverId, agentId);
}
export function useStagedProviderSwitch(
serverId: string,
agentId: string,
): StagedProviderSwitch | null {
return useStagedProviderSwitchStore(
(state) => state.stagedByKey.get(stagedKey(serverId, agentId)) ?? null,
);
}
export function useIsStagedProviderSwitchInFlight(serverId: string, agentId: string): boolean {
return useStagedProviderSwitchStore(
(state) => (state.inFlightByKey.get(stagedKey(serverId, agentId)) ?? 0) > 0,
);
}
+7 -21
View File
@@ -3,30 +3,17 @@ import { useSessionStore } from "@/stores/session-store";
import {
appendSubmittedUserMessage,
removeSubmittedUserMessage,
type ProviderSwitchItem,
type UserMessageItem,
} from "@/types/stream";
function appendUntrackedSubmission(
serverId: string,
agentId: string,
message: UserMessageItem,
options?: { providerSwitch?: ProviderSwitchItem },
) {
function appendUntrackedSubmission(serverId: string, agentId: string, message: UserMessageItem) {
const session = useSessionStore.getState().sessions[serverId];
if (!session) return;
const tail = session.agentStreamTail.get(agentId) ?? [];
const head = session.agentStreamHead.get(agentId) ?? [];
useSessionStore.getState().setAgentStreamState(
serverId,
agentId,
appendSubmittedUserMessage({
tail,
head,
message,
providerSwitch: options?.providerSwitch,
}),
);
useSessionStore
.getState()
.setAgentStreamState(serverId, agentId, appendSubmittedUserMessage({ tail, head, message }));
}
function removeUntrackedSubmission(
@@ -49,8 +36,7 @@ function removeUntrackedSubmission(
function createUntrackedMessageSubmissionWriter(serverId: string): MessageSubmissionWriter {
return {
begin: (agentId, message, options) =>
appendUntrackedSubmission(serverId, agentId, message, options),
begin: (agentId, message) => appendUntrackedSubmission(serverId, agentId, message),
accept: () => undefined,
reject: (agentId, clientMessageId) => {
removeUntrackedSubmission(serverId, agentId, clientMessageId);
@@ -68,8 +54,8 @@ export function createMessageSubmissionWriter(serverId: string): MessageSubmissi
return createUntrackedMessageSubmissionWriter(serverId);
}
return {
begin: (agentId, message, options) =>
useSessionStore.getState().beginAgentMessageSubmission(serverId, agentId, message, options),
begin: (agentId, message) =>
useSessionStore.getState().beginAgentMessageSubmission(serverId, agentId, message),
accept: (agentId, clientMessageId) =>
useSessionStore.getState().acceptAgentMessageSubmission(serverId, agentId, clientMessageId),
reject: (agentId, clientMessageId) =>
@@ -293,16 +293,6 @@ function SessionProviderInternal({ children, serverId, client }: SessionProvider
console.warn("[Session] timeline replacement refresh failed", { serverId, error });
});
};
const onRewind = (message: SessionOutboundMessage) => {
if (message.type !== "agent.timeline.rewind") return;
const { agentId, epoch, seq, retireFromSeq } = message.payload;
sync.applyStreamEvent(agentId, {
event: { type: "rewind", retireFromSeq },
seq,
epoch,
timestamp: new Date(),
});
};
const sync = getHostRuntimeStore().createViewedTimelineOwner(serverId, {
canCheckFreshness: () =>
client.getLastServerInfoMessage()?.features?.timelineFreshnessCheck === true,
@@ -313,7 +303,6 @@ function SessionProviderInternal({ children, serverId, client }: SessionProvider
update: (message) => {
if (message.type === "agent_stream") onStream(message);
else if (message.type === "agent.timeline.replacement") onReplacement(message);
else if (message.type === "agent.timeline.rewind") onRewind(message);
},
});
return observation;
@@ -166,7 +166,7 @@ describe("ensureAgentIsInitialized", () => {
kind: "assistant_message",
id: "canonical-item",
text: "Canonical before restart",
timelineCursor: { epoch: "epoch-1", seq: 12, anchorSeq: 12 },
timelineCursor: { epoch: "epoch-1", seq: 12 },
timestamp: new Date("2026-07-27T10:00:00.000Z"),
},
],
+6 -23
View File
@@ -18,22 +18,16 @@ function useIsAgentUnarchiving({ serverId, agentId }: UnarchiveAgentTarget): boo
export async function runAgentUnarchive(input: {
serverId: string;
agentId: string;
client: {
refreshAgent: (agentId: string) => Promise<{ historyDiverged?: boolean } | unknown>;
} | null;
client: { refreshAgent: (agentId: string) => Promise<unknown> } | null;
isConnected: boolean;
onRefreshed?: (result: { historyDiverged?: boolean }) => void;
}): Promise<boolean> {
const { serverId, agentId, client, isConnected, onRefreshed } = input;
const { serverId, agentId, client, isConnected } = input;
if (!client || !isConnected || isAgentUnarchiving({ serverId, agentId })) {
return false;
}
const token = beginAgentUnarchive({ serverId, agentId });
try {
const refreshed = await client.refreshAgent(agentId);
if (refreshed && typeof refreshed === "object" && "historyDiverged" in refreshed) {
onRefreshed?.(refreshed as { historyDiverged?: boolean });
}
await client.refreshAgent(agentId);
return true;
} finally {
finishAgentUnarchive({ serverId, agentId }, token);
@@ -45,20 +39,9 @@ export function useUnarchiveAgent({ serverId, agentId }: UnarchiveAgentTarget) {
const isConnected = useHostRuntimeIsConnected(serverId);
const isUnarchiving = useIsAgentUnarchiving({ serverId, agentId });
const unarchive = useCallback(
async (options?: {
onRefreshed?: (result: { historyDiverged?: boolean }) => void;
}): Promise<void> => {
await runAgentUnarchive({
serverId,
agentId,
client,
isConnected,
onRefreshed: options?.onRefreshed,
});
},
[agentId, client, isConnected, serverId],
);
const unarchive = useCallback(async (): Promise<void> => {
await runAgentUnarchive({ serverId, agentId, client, isConnected });
}, [agentId, client, isConnected, serverId]);
return {
unarchive,
-13
View File
@@ -205,10 +205,6 @@ export const ar: TranslationResources = {
pasteImageFailed: "تعذر لصق الصورة",
fileTooLarge: "{{fileName}} is too large (max {{size}})",
},
providerSwitch: {
switchingNextMessage: "التبديل إلى {{provider}} في الرسالة التالية",
switchingAfterTurn: "سيتم التبديل إلى {{provider}} بعد هذا الدور",
},
clientCommands: {
archiveAgent: "أرشفة الوكيل الحالي",
freshDraft: "أرشفة هذا الوكيل وابدأ مسودة جديدة",
@@ -441,13 +437,6 @@ export const ar: TranslationResources = {
turnFooter: {
workedFor: "عمل لمدة {{duration}}",
},
providerSwitch: {
switched: "تم التبديل من {{from}} إلى {{to}}",
contextSummary: "تم نقل {{count}} عنصر ({{chars}} / {{budget}} حرف)",
trimmed: "تم الاقتطاع: {{reasons}}",
reasonTailWindow: "سجل أقدم خارج النطاق",
reasonCharBudget: "حد الأحرف",
},
compaction: {
loading: "الضغط...",
auto: "يتم ضغط السياق تلقائيًا",
@@ -771,8 +760,6 @@ export const ar: TranslationResources = {
resumeCommandUnavailable: "أمر الاستئناف غير متوفر",
reloadingAgent: "وكيل إعادة التحميل...",
reloadedAgent: "وكيل إعادة تحميل",
reloadedAgentHistoryDiverged:
"تمت إعادة تحميل الوكيل، لكن سجل المزوّد لا يطابق هذه المحادثة، لذا لم تتم مزامنته",
failedToReloadAgent: "فشل في إعادة تحميل الوكيل",
failedToCloseAgent: "فشل في إغلاق الوكيل",
},
-13
View File
@@ -203,10 +203,6 @@ export const en = {
pasteImageFailed: "Failed to paste image",
fileTooLarge: "{{fileName}} is too large (max {{size}})",
},
providerSwitch: {
switchingNextMessage: "Switching to {{provider}} on next message",
switchingAfterTurn: "Will switch to {{provider}} after this turn",
},
clientCommands: {
archiveAgent: "Archive the current agent",
freshDraft: "Archive this agent and start a fresh draft",
@@ -440,13 +436,6 @@ export const en = {
turnFooter: {
workedFor: "Worked for {{duration}}",
},
providerSwitch: {
switched: "Switched from {{from}} to {{to}}",
contextSummary: "{{count}} items transferred ({{chars}} / {{budget}} chars)",
trimmed: "Trimmed: {{reasons}}",
reasonTailWindow: "older history beyond window",
reasonCharBudget: "character budget",
},
compaction: {
loading: "Compacting...",
auto: "Context automatically compacted",
@@ -770,8 +759,6 @@ export const en = {
resumeCommandUnavailable: "Resume command not available",
reloadingAgent: "Reloading agent...",
reloadedAgent: "Reloaded agent",
reloadedAgentHistoryDiverged:
"Reloaded agent, but the provider's history doesn't match this chat, so it wasn't synced",
failedToReloadAgent: "Failed to reload agent",
failedToCloseAgent: "Failed to close agent",
},
-13
View File
@@ -207,10 +207,6 @@ export const es: TranslationResources = {
pasteImageFailed: "No se pudo pegar la imagen",
fileTooLarge: "{{fileName}} is too large (max {{size}})",
},
providerSwitch: {
switchingNextMessage: "Cambiando a {{provider}} en el próximo mensaje",
switchingAfterTurn: "Se cambiará a {{provider}} después de este turno",
},
clientCommands: {
archiveAgent: "Archivar el agente actual",
freshDraft: "Archive este agente y comience un nuevo borrador",
@@ -446,13 +442,6 @@ export const es: TranslationResources = {
turnFooter: {
workedFor: "Trabajó durante {{duration}}",
},
providerSwitch: {
switched: "Cambiado de {{from}} a {{to}}",
contextSummary: "{{count}} elementos transferidos ({{chars}} / {{budget}} caracteres)",
trimmed: "Recortado: {{reasons}}",
reasonTailWindow: "historial anterior fuera de la ventana",
reasonCharBudget: "límite de caracteres",
},
compaction: {
loading: "Compactando...",
auto: "Contexto compactado automáticamente",
@@ -778,8 +767,6 @@ export const es: TranslationResources = {
resumeCommandUnavailable: "Comando de reanudación no disponible",
reloadingAgent: "Agente de recarga...",
reloadedAgent: "Agente recargado",
reloadedAgentHistoryDiverged:
"Agente recargado, pero el historial del proveedor no coincide con este chat, así que no se sincronizó",
failedToReloadAgent: "No se pudo recargar el agente",
failedToCloseAgent: "No se pudo cerrar el agente",
},
-13
View File
@@ -208,10 +208,6 @@ export const fr: TranslationResources = {
pasteImageFailed: "Impossible de coller l’image",
fileTooLarge: "{{fileName}} est trop volumineux (maximum {{size}})",
},
providerSwitch: {
switchingNextMessage: "Passage à {{provider}} au prochain message",
switchingAfterTurn: "Passage à {{provider}} après ce tour",
},
clientCommands: {
archiveAgent: "Archiver l’agent actuel",
freshDraft: "Archiver cet agent et démarrer un nouveau brouillon",
@@ -446,13 +442,6 @@ export const fr: TranslationResources = {
turnFooter: {
workedFor: "A travaillé pendant {{duration}}",
},
providerSwitch: {
switched: "Passé de {{from}} à {{to}}",
contextSummary: "{{count}} éléments transférés ({{chars}} / {{budget}} caractères)",
trimmed: "Tronqué : {{reasons}}",
reasonTailWindow: "historique antérieur hors fenêtre",
reasonCharBudget: "limite de caractères",
},
compaction: {
loading: "Compaction…",
auto: "Contexte compacté automatiquement",
@@ -778,8 +767,6 @@ export const fr: TranslationResources = {
resumeCommandUnavailable: "Commande de reprise indisponible",
reloadingAgent: "Rechargement de l’agent…",
reloadedAgent: "Agent rechargé",
reloadedAgentHistoryDiverged:
"Agent rechargé, mais l’historique du fournisseur ne correspond pas à cette conversation, il n’a donc pas été synchronisé",
failedToReloadAgent: "Impossible de recharger l’agent",
failedToCloseAgent: "Impossible de fermer l’agent",
},
-13
View File
@@ -207,10 +207,6 @@ export const ja: TranslationResources = {
pasteImageFailed: "画像を貼り付けられませんでした",
fileTooLarge: "{{fileName}}が大きすぎます(最大{{size}})",
},
providerSwitch: {
switchingNextMessage: "次のメッセージで {{provider}} に切り替えます",
switchingAfterTurn: "このターン終了後に {{provider}} に切り替えます",
},
clientCommands: {
archiveAgent: "現在のエージェントをアーカイブ",
freshDraft: "このエージェントをアーカイブして新しい下書きを開始",
@@ -446,13 +442,6 @@ export const ja: TranslationResources = {
turnFooter: {
workedFor: "作業時間 {{duration}}",
},
providerSwitch: {
switched: "{{from}} から {{to}} に切り替えました",
contextSummary: "{{count}} 件を引き継ぎました ({{chars}} / {{budget}} 文字)",
trimmed: "省略: {{reasons}}",
reasonTailWindow: "ウィンドウ外の古い履歴",
reasonCharBudget: "文字数上限",
},
compaction: {
loading: "コンテキストを圧縮中...",
auto: "コンテキストが自動的に圧縮されました",
@@ -778,8 +767,6 @@ export const ja: TranslationResources = {
resumeCommandUnavailable: "再開コマンドが利用できません",
reloadingAgent: "エージェントを再読み込み中...",
reloadedAgent: "エージェントを再読み込みしました",
reloadedAgentHistoryDiverged:
"エージェントを再読み込みしましたが、プロバイダーの履歴がこのチャットと一致しないため同期しませんでした",
failedToReloadAgent: "エージェントの再読み込みに失敗しました",
failedToCloseAgent: "エージェントを閉じられませんでした",
},
-13
View File
@@ -205,10 +205,6 @@ export const ko: TranslationResources = {
pasteImageFailed: "이미지를 붙여넣지 못했습니다.",
fileTooLarge: "{{fileName}}이(가) 너무 큽니다 (최대 {{size}})",
},
providerSwitch: {
switchingNextMessage: "다음 메시지에서 {{provider}}(으)로 전환합니다",
switchingAfterTurn: "이 턴이 끝난 후 {{provider}}(으)로 전환합니다",
},
clientCommands: {
archiveAgent: "현재 에이전트 보관",
freshDraft: "이 에이전트를 보관하고 새 초안을 시작합니다",
@@ -442,13 +438,6 @@ export const ko: TranslationResources = {
turnFooter: {
workedFor: "작업 시간 {{duration}}",
},
providerSwitch: {
switched: "{{from}}에서 {{to}}(으)로 전환됨",
contextSummary: "{{count}}개 항목 전달됨 ({{chars}} / {{budget}}자)",
trimmed: "생략됨: {{reasons}}",
reasonTailWindow: "창 범위를 벗어난 이전 기록",
reasonCharBudget: "문자 수 제한",
},
compaction: {
loading: "압축하는 중...",
auto: "컨텍스트가 자동으로 압축되었습니다",
@@ -773,8 +762,6 @@ export const ko: TranslationResources = {
resumeCommandUnavailable: "재개 명령을 사용할 수 없습니다",
reloadingAgent: "에이전트 다시 로드 중...",
reloadedAgent: "에이전트를 다시 로드했습니다",
reloadedAgentHistoryDiverged:
"에이전트를 다시 로드했지만 제공자 기록이 이 채팅과 일치하지 않아 동기화하지 않았습니다",
failedToReloadAgent: "에이전트를 다시 로드하지 못했습니다",
failedToCloseAgent: "에이전트를 닫지 못했습니다",
},
-13
View File
@@ -206,10 +206,6 @@ export const ptBR: TranslationResources = {
pasteImageFailed: "Falha ao colar a imagem",
fileTooLarge: "{{fileName}} é grande demais (máximo {{size}})",
},
providerSwitch: {
switchingNextMessage: "Trocando para {{provider}} na próxima mensagem",
switchingAfterTurn: "Trocará para {{provider}} após este turno",
},
clientCommands: {
archiveAgent: "Arquivar o agente atual",
freshDraft: "Arquivar este agente e iniciar um novo rascunho",
@@ -445,13 +441,6 @@ export const ptBR: TranslationResources = {
turnFooter: {
workedFor: "Trabalhou por {{duration}}",
},
providerSwitch: {
switched: "Trocado de {{from}} para {{to}}",
contextSummary: "{{count}} itens transferidos ({{chars}} / {{budget}} caracteres)",
trimmed: "Cortado: {{reasons}}",
reasonTailWindow: "histórico anterior além da janela",
reasonCharBudget: "limite de caracteres",
},
compaction: {
loading: "Compactando...",
auto: "Contexto compactado automaticamente",
@@ -776,8 +765,6 @@ export const ptBR: TranslationResources = {
resumeCommandUnavailable: "Comando de retomada indisponível",
reloadingAgent: "Recarregando agente...",
reloadedAgent: "Agente recarregado",
reloadedAgentHistoryDiverged:
"Agente recarregado, mas o histórico do provedor não corresponde a este chat, então não foi sincronizado",
failedToReloadAgent: "Falha ao recarregar agente",
failedToCloseAgent: "Falha ao fechar agente",
},
-13
View File
@@ -207,10 +207,6 @@ export const ru: TranslationResources = {
pasteImageFailed: "Не удалось вставить изображение",
fileTooLarge: "Файл {{fileName}} слишком большой (максимальный размер: {{size}})",
},
providerSwitch: {
switchingNextMessage: "Переключение на {{provider}} в следующем сообщении",
switchingAfterTurn: "Переключение на {{provider}} после этого хода",
},
clientCommands: {
archiveAgent: "Архивировать текущего агента",
freshDraft: "Архивировать этого агента и создать новый черновик",
@@ -445,13 +441,6 @@ export const ru: TranslationResources = {
turnFooter: {
workedFor: "Время работы: {{duration}}",
},
providerSwitch: {
switched: "Переключено с {{from}} на {{to}}",
contextSummary: "Передано элементов: {{count}} ({{chars}} / {{budget}} симв.)",
trimmed: "Сокращено: {{reasons}}",
reasonTailWindow: "более ранняя история вне окна",
reasonCharBudget: "лимит символов",
},
compaction: {
loading: "Сжатие контекста...",
auto: "Контекст сжат автоматически",
@@ -779,8 +768,6 @@ export const ru: TranslationResources = {
resumeCommandUnavailable: "Команда возобновления недоступна",
reloadingAgent: "Перезагрузка агента...",
reloadedAgent: "Агент перезагружен",
reloadedAgentHistoryDiverged:
"Агент перезагружен, но история провайдера не совпадает с этим чатом, поэтому она не синхронизирована",
failedToReloadAgent: "Не удалось перезагрузить агента",
failedToCloseAgent: "Не удалось закрыть агента",
},
-13
View File
@@ -205,10 +205,6 @@ export const zhCN: TranslationResources = {
pasteImageFailed: "无法粘贴图片",
fileTooLarge: "{{fileName}} is too large (max {{size}})",
},
providerSwitch: {
switchingNextMessage: "下一条消息将切换到 {{provider}}",
switchingAfterTurn: "本轮结束后将切换到 {{provider}}",
},
clientCommands: {
archiveAgent: "归档当前 Agent",
freshDraft: "归档此 Agent 并开始新的草稿",
@@ -441,13 +437,6 @@ export const zhCN: TranslationResources = {
turnFooter: {
workedFor: "工作了 {{duration}}",
},
providerSwitch: {
switched: "已从 {{from}} 切换到 {{to}}",
contextSummary: "已传递 {{count}} 项上下文({{chars}} / {{budget}} 字符)",
trimmed: "已裁剪:{{reasons}}",
reasonTailWindow: "超出窗口的早期历史",
reasonCharBudget: "字符预算限制",
},
compaction: {
loading: "正在压缩...",
auto: "上下文已自动压缩",
@@ -771,8 +760,6 @@ export const zhCN: TranslationResources = {
resumeCommandUnavailable: "恢复命令不可用",
reloadingAgent: "正在重新加载 Agent...",
reloadedAgent: "已重新加载 Agent",
reloadedAgentHistoryDiverged:
"已重新加载 Agent,但提供方的历史记录与此对话不一致,因此未同步",
failedToReloadAgent: "重新加载 Agent 失败",
failedToCloseAgent: "关闭 Agent 失败",
},
@@ -224,9 +224,8 @@ export function useOverlayRegistration({
activeRef.current && typeof window !== "undefined" && typeof document !== "undefined";
if (!shouldRegister) {
const shouldRestoreFocus = !activeRef.current;
const removeEntry = removeEntryRef.current ?? detachedRemoveEntryRef.current;
if (registeredRef.current || shouldRestoreFocus) {
removeEntry?.({ restoreFocus: shouldRestoreFocus });
removeEntryRef.current?.({ restoreFocus: shouldRestoreFocus });
}
registeredRef.current = false;
if (shouldRestoreFocus) {
@@ -269,14 +268,8 @@ export function useOverlayRegistration({
[syncRegistration],
);
// Run `active` transitions in layout effects (after React's `resetAfterCommit`), so closing a
// fading overlay restores focus after React's commit-time selection restoration instead of
// having `resetAfterCommit` pull focus back into the still-mounted closing dialog.
useLayoutEffect(() => {
syncRegistration();
}, [active, syncRegistration]);
useLayoutEffect(() => {
return () => {
const removeEntry = removeEntryRef.current ?? detachedRemoveEntryRef.current;
removeEntry?.();
@@ -284,7 +277,7 @@ export function useOverlayRegistration({
detachedRemoveEntryRef.current = null;
registeredRef.current = false;
};
}, [syncRegistration]);
}, [active, syncRegistration]);
return setScope;
}
@@ -74,74 +74,6 @@ describe("useOverlayRegistration in the browser", () => {
expect(openerFocusCalls).toBe(1);
});
it("restores focus to the non-first opener button when a fading upper overlay closes over a lower overlay", async () => {
function StackedHarness({ upperActive }: { upperActive: boolean }) {
const setLowerScope = useOverlayRegistration({
keys: ["Escape"],
active: true,
layer: 10,
onKeyDown: () => false,
});
const setUpperScope = useOverlayRegistration({
keys: ["Escape"],
active: upperActive,
layer: 30,
onKeyDown: () => false,
});
return (
<>
<div
data-testid="lower-scope"
ref={setLowerScope as RefCallback<HTMLDivElement>}
tabIndex={-1}
>
<button data-testid="lower-first" type="button">
Back
</button>
<button data-testid="lower-second" type="button">
Settings
</button>
</div>
<div
data-testid="upper-scope"
ref={setUpperScope as RefCallback<HTMLDivElement>}
tabIndex={-1}
>
<button data-testid="upper-close" type="button">
Close
</button>
</div>
</>
);
}
flushSync(() => {
root.render(<StackedHarness upperActive={false} />);
});
await nextFrame();
const lowerSecond = document.querySelector<HTMLButtonElement>('[data-testid="lower-second"]');
expect(lowerSecond).toBeTruthy();
lowerSecond?.focus();
expect(document.activeElement).toBe(lowerSecond);
flushSync(() => {
root.render(<StackedHarness upperActive />);
});
await nextFrame();
const upperClose = document.querySelector<HTMLButtonElement>('[data-testid="upper-close"]');
expect(document.activeElement).toBe(upperClose);
// Keep upper-scope mounted while closing (mirrors AdaptiveModalSheet's web fade-out).
flushSync(() => {
root.render(<StackedHarness upperActive={false} />);
});
await nextFrame();
expect(document.activeElement).toBe(lowerSecond);
});
});
describe("hasOpenDomPopover", () => {
+121 -1
View File
@@ -1,6 +1,15 @@
import { readFileSync } from "node:fs";
import { createRequire } from "node:module";
// eslint-disable-next-line no-restricted-imports -- verify plugin runtime does not leak raw ReactNative.
import * as ReactNative from "react-native";
import { describe, expect, it } from "vitest";
import { useRevealedText } from "@/hooks/use-revealed-text";
import { runPluginClientBundle, type PluginClientRuntime } from "./evaluate";
import {
OMITTED_REACT_NATIVE_EXPORTS,
createPluginReactNativeRuntime,
runPluginClientBundle,
type PluginClientRuntime,
} from "./evaluate";
const runtime = {
paseo: {},
@@ -909,6 +918,117 @@ describe("evaluatePluginClientBundle", () => {
),
).toThrow("setup exploded");
});
it("omits PushNotificationIOS, default, and non-enumerable getters while keeping other exports lazy", () => {
let platformReads = 0;
let pushReads = 0;
let nativeModulesReads = 0;
let asyncStorageReads = 0;
const raw = {
get Platform() {
platformReads += 1;
return { OS: "ios" };
},
get PushNotificationIOS() {
pushReads += 1;
throw new Error("`new NativeEventEmitter()` requires a non-null argument.");
},
get NativeModules() {
nativeModulesReads += 1;
return { CustomModule: true };
},
};
const interopNamespace = Object.defineProperties(
{},
{
Platform: Object.getOwnPropertyDescriptor(raw, "Platform")!,
PushNotificationIOS: Object.getOwnPropertyDescriptor(raw, "PushNotificationIOS")!,
NativeModules: Object.getOwnPropertyDescriptor(raw, "NativeModules")!,
AsyncStorage: {
configurable: true,
enumerable: false,
get() {
asyncStorageReads += 1;
throw new Error("AsyncStorage has been removed from react-native core.");
},
},
default: { enumerable: true, value: raw },
},
);
const safe = createPluginReactNativeRuntime(interopNamespace);
expect(platformReads).toBe(0);
expect(pushReads).toBe(0);
expect(nativeModulesReads).toBe(0);
expect(asyncStorageReads).toBe(0);
expect(Object.getOwnPropertyNames(safe)).toEqual(["Platform", "NativeModules"]);
expect("PushNotificationIOS" in safe).toBe(false);
expect("AsyncStorage" in safe).toBe(false);
expect("default" in safe).toBe(false);
expect(Object.assign({}, safe)).toEqual({
Platform: { OS: "ios" },
NativeModules: { CustomModule: true },
});
expect(platformReads).toBe(1);
expect(nativeModulesReads).toBe(1);
expect(pushReads).toBe(0);
expect(asyncStorageReads).toBe(0);
});
it("wires require('react-native') to the filtered runtime instead of the raw namespace", () => {
let exposed: Record<string, unknown> | undefined;
const plugin = evaluatePluginClientBundle(
"rn-safe",
`(function(require) {
const rn = require("react-native");
return {
default: function(plugin) {
plugin.addSurface("probe", function() { return null; });
globalThis.__testPluginRn = rn;
return function() {};
},
};
})`,
);
exposed = (globalThis as Record<string, unknown>).__testPluginRn as
| Record<string, unknown>
| undefined;
delete (globalThis as Record<string, unknown>).__testPluginRn;
expect(plugin.id).toBe("rn-safe");
expect(exposed).toBeDefined();
expect(exposed).not.toBe(ReactNative);
const expectedKeys = Object.keys(ReactNative)
.filter((key) => !OMITTED_REACT_NATIVE_EXPORTS.has(key))
.sort();
expect(Object.getOwnPropertyNames(exposed!).sort()).toEqual(expectedKeys);
expect("PushNotificationIOS" in exposed!).toBe(false);
expect("default" in exposed!).toBe(false);
expect(exposed!.Platform).toBe(ReactNative.Platform);
expect(exposed!.NativeModules).toBe(ReactNative.NativeModules);
});
it("excludes PushNotificationIOS and checks enumerable react-native/index.js getters for invariant throws", () => {
const require = createRequire(import.meta.url);
const rnIndexPath = require.resolve("react-native/index.js");
const rnIndexSource = readFileSync(rnIndexPath, "utf8");
const getterBodies = new Map<string, string>();
const getterPattern = /get\s+([A-Za-z0-9_$]+)\s*\(\)\s*\{([\s\S]*?)\n\s*\},/g;
for (const match of rnIndexSource.matchAll(getterPattern)) {
getterBodies.set(match[1]!, match[2]!);
}
expect(getterBodies.size).toBeGreaterThan(0);
expect(getterBodies.has("PushNotificationIOS")).toBe(true);
expect(OMITTED_REACT_NATIVE_EXPORTS.has("PushNotificationIOS")).toBe(true);
for (const [name, body] of getterBodies) {
if (OMITTED_REACT_NATIVE_EXPORTS.has(name)) continue;
expect(body, `throwing enumerable getter ${name} in react-native/index.js`).not.toContain(
"invariant(",
);
}
});
});
it("binds imported getters to each originating installation across delayed callbacks", async () => {
+24 -1
View File
@@ -123,6 +123,29 @@ export type PluginClientRuntime = Pick<
// The 0.12 entry exposed the reveal hook as well as UI components.
const pluginReactNativeCompatRuntime = { ...pluginUiRuntime, useRevealedText };
// PushNotificationIOS crashes iOS fatally via Metro's guardedLoadModule ->
// RCTExceptionsManager.reportFatal because RCTPushNotificationManager is not linked
// in Expo builds, bypassing PluginRegistry's try/catch. Omit it and raw `default`
// while preserving all other enumerable react-native exports as lazy descriptors.
export const OMITTED_REACT_NATIVE_EXPORTS = new Set(["PushNotificationIOS", "default"]);
export function createPluginReactNativeRuntime(
source: Record<string, unknown>,
): Record<string, unknown> {
const runtime: Record<string, unknown> = {};
for (const key of Object.keys(source)) {
if (OMITTED_REACT_NATIVE_EXPORTS.has(key)) continue;
const descriptor = Object.getOwnPropertyDescriptor(source, key);
if (!descriptor) continue;
Object.defineProperty(runtime, key, descriptor);
}
return runtime;
}
const pluginReactNativeRuntime = createPluginReactNativeRuntime(
ReactNative as unknown as Record<string, unknown>,
);
export function runPluginClientBundle(
id: string,
bundle: string,
@@ -588,7 +611,7 @@ export function runPluginClientBundle(
if (name === "@getpaseo/plugin/client/ui") return pluginUiRuntime;
if (name === "react") return React;
if (name === "react/jsx-runtime") return ReactJsxRuntime;
if (name === "react-native") return ReactNative;
if (name === "react-native") return pluginReactNativeRuntime;
if (name === "@getpaseo/plugin") return pluginSharedRuntime;
if (name === "@getpaseo/plugin/client")
return {
@@ -197,7 +197,7 @@ describe("plugin timeline projection", () => {
kind: "assistant_message",
id: "assistant-1",
messageId: "provider-msg-1",
timelineCursor: { epoch: "e1", seq: 7, anchorSeq: 7 },
timelineCursor: { epoch: "e1", seq: 7 },
turnId: "turn-1",
text: 'Summary\n\n```ui\nCard("Hi", [])\n```',
timestamp: new Date("2026-01-01T00:00:02.000Z"),
@@ -226,13 +226,13 @@ describe("plugin timeline projection", () => {
{
kind: "plugin",
id: "genui/assistant-1/text",
timelineCursor: { epoch: "e1", seq: 7, anchorSeq: 7 },
timelineCursor: { epoch: "e1", seq: 7 },
turnId: "turn-1",
},
{
kind: "plugin",
id: "genui/assistant-1/card",
timelineCursor: { epoch: "e1", seq: 7, anchorSeq: 7 },
timelineCursor: { epoch: "e1", seq: 7 },
turnId: "turn-1",
},
]);
@@ -65,7 +65,6 @@ function sourceTimelineItem(item: StreamItem): AgentTimelineItem | null {
...(item.preTokens !== undefined ? { preTokens: item.preTokens } : {}),
};
case "plugin":
case "provider_switch":
case "turn_summary":
return null;
}
@@ -91,7 +91,7 @@ describe("AgentDirectoryReplica", () => {
id: "reply",
text: "server history",
timestamp: new Date(),
timelineCursor: { epoch: "e", seq: 1, anchorSeq: 1 },
timelineCursor: { epoch: "e", seq: 1 },
},
],
head: [],
+24 -146
View File
@@ -83,18 +83,8 @@ import {
} from "@/desktop/browser/automation/handler";
import { schedulesQueryBaseKey } from "@/schedules/aggregated-schedules";
import { dispatchComposerAgentMessage, sendQueuedComposerMessageNow } from "@/composer/actions";
import {
applyFailedStartupSettings,
beginStagedProviderSwitch,
discardFailedStartupSettings,
endStagedProviderSwitch,
getFailedStartupSettings,
getStagedProviderSwitch,
settleCommittedProviderSwitch,
} from "@/composer/provider-switch";
import { createMessageSubmissionWriter } from "@/composer/submission/writer";
import { resolveComposerAttachmentSubmitFormat } from "@/composer/attachments/submit";
import { normalizeAgentSnapshot } from "@/utils/agent-snapshots";
import { encodeImages } from "@/utils/encode-images";
import { DirectorySync, type RefreshAgentDirectoryResult } from "@/runtime/directory-sync";
import { ReplicaCache } from "@/runtime/replica-cache";
@@ -265,7 +255,6 @@ const PROBE_INACTIVE_WHILE_ONLINE_MAX_MS = 30 * 60_000;
const ACTIVE_RTT_WINDOW_MS = 60_000;
const ADAPTIVE_SWITCH_THRESHOLD_MS = 40;
const ADAPTIVE_SWITCH_MIN_IMPROVEMENT_RATIO = 0.35;
const MAX_STALE_TIMELINE_PAGE_ATTEMPTS = 3;
const ADAPTIVE_SWITCH_CONSECUTIVE_PROBES = 3;
const CONFIGURED_OVERRIDE_BOOTSTRAP_RETRY_MS = 1_000;
@@ -1928,7 +1917,6 @@ export class HostRuntimeStore {
private lastOnlineEpochByServer = new Map<string, number>();
private connectionStatusStartedAtByServer = new Map<string, number>();
private queuedAgentDrainInFlight = new Set<string>();
private queuedAgentDrainPending = new Set<string>();
private directorySyncByServer = new Map<string, DirectorySync>();
private nextCancellationRequestId = 0;
private timelineReplicaByServer = new Map<string, TimelineReplica>();
@@ -2893,58 +2881,9 @@ export class HostRuntimeStore {
}
}
private resumeIdleQueueIfReady(serverId: string, agentId: string): void {
const latestSession = useSessionStore.getState().sessions[serverId];
const latestAgent = latestSession?.agents.get(agentId);
const remainingQueue = latestSession?.queuedMessages.get(agentId);
if (
latestAgent?.status === "idle" &&
remainingQueue &&
remainingQueue.length > 0 &&
latestSession?.initializingAgents.get(agentId) !== true
) {
this.drainQueuedAgentMessage(serverId, agentId);
}
}
/**
* Explicitly retries or discards startup settings that failed after a provider switch,
* then resumes automatic draining if the chat is idle with queued messages.
*/
async recoverFailedStartupSettings(
serverId: string,
agentId: string,
action: "retry" | "discard",
): Promise<boolean> {
if (action === "discard") {
discardFailedStartupSettings(serverId, agentId);
useSessionStore.getState().setQueuedSendError(serverId, agentId, null);
this.resumeIdleQueueIfReady(serverId, agentId);
return true;
}
const client = useSessionStore.getState().sessions[serverId]?.client;
if (!client) {
return false;
}
const result = await applyFailedStartupSettings({ serverId, agentId, client });
if (!result.applied) {
useSessionStore.getState().setQueuedSendError(serverId, agentId, result.errorMessage);
return false;
}
useSessionStore.getState().setQueuedSendError(serverId, agentId, null);
this.resumeIdleQueueIfReady(serverId, agentId);
return true;
}
drainQueuedAgentMessage(serverId: string, agentId: string): void {
if (getFailedStartupSettings(serverId, agentId)) {
return;
}
const drainKey = `${serverId}:${agentId}`;
if (this.queuedAgentDrainInFlight.has(drainKey)) {
this.queuedAgentDrainPending.add(drainKey);
return;
}
if (this.queuedAgentDrainInFlight.has(drainKey)) return;
const store = useSessionStore.getState();
const session = store.sessions[serverId];
const queue = session?.queuedMessages.get(agentId);
@@ -2953,11 +2892,7 @@ export class HostRuntimeStore {
return;
}
this.queuedAgentDrainInFlight.add(drainKey);
this.queuedAgentDrainPending.delete(drainKey);
useSessionStore.getState().setQueuedSendError(serverId, agentId, null);
const next = queue[0];
let drainSent = false;
let drainBlockedBySettingsError: string | null = null;
void sendQueuedComposerMessageNow({
agentId,
messageId: next.id,
@@ -2967,71 +2902,28 @@ export class HostRuntimeStore {
write: (update) => useSessionStore.getState().setQueuedMessages(serverId, update),
},
submitMessage: async ({ text, attachments }) => {
const currentSession = useSessionStore.getState().sessions[serverId];
const supportsForgeAttachments = currentSession?.serverInfo?.features?.forgeSearch === true;
const supportsProviderSwitching =
currentSession?.serverInfo?.features?.providerSwitching === true;
const liveProvider = currentSession?.agents.get(agentId)?.provider;
const rawStagedSwitch = supportsProviderSwitching
? getStagedProviderSwitch(serverId, agentId)
: null;
const stagedProviderSwitch =
rawStagedSwitch && rawStagedSwitch.provider !== liveProvider ? rawStagedSwitch : null;
if (stagedProviderSwitch) {
beginStagedProviderSwitch(serverId, agentId);
}
try {
await dispatchComposerAgentMessage({
client,
agentId,
text,
attachments,
attachmentSubmitFormat: resolveComposerAttachmentSubmitFormat({
supportsForgeAttachments,
}),
encodeImages,
submission: createMessageSubmissionWriter(serverId),
currentProvider: liveProvider ?? null,
currentModel: currentSession?.agents.get(agentId)?.model ?? null,
stagedProviderSwitch,
onProviderSwitchCommitted: async (agent) => {
if (agent) {
this.tryAcceptAgentSnapshot(serverId, normalizeAgentSnapshot(agent, serverId));
}
if (stagedProviderSwitch) {
const settled = await settleCommittedProviderSwitch({
serverId,
agentId,
sentDraft: stagedProviderSwitch,
committedProvider: agent?.provider ?? null,
client,
});
if (!settled.applied) {
drainBlockedBySettingsError = settled.errorMessage;
}
}
},
// The queue drains when the agent goes idle, but the agent can start a turn of its own
// in that same moment (a wake-up after background work). Steering folds the message
// into that turn instead of interrupting it; with no turn running, the daemon starts
// a normal one.
activeTurnBehavior: "steer",
});
} finally {
if (stagedProviderSwitch) {
endStagedProviderSwitch(serverId, agentId);
}
}
const supportsForgeAttachments =
useSessionStore.getState().sessions[serverId]?.serverInfo?.features?.forgeSearch === true;
await dispatchComposerAgentMessage({
client,
agentId,
text,
attachments,
attachmentSubmitFormat: resolveComposerAttachmentSubmitFormat({
supportsForgeAttachments,
}),
encodeImages,
submission: createMessageSubmissionWriter(serverId),
// The queue drains when the agent goes idle, but the agent can start a turn of its own
// in that same moment (a wake-up after background work). Steering folds the message
// into that turn instead of interrupting it; with no turn running, the daemon starts
// a normal one.
activeTurnBehavior: "steer",
});
},
})
.then((result) => {
if (result.status === "submitted") {
drainSent = drainBlockedBySettingsError === null;
useSessionStore
.getState()
.setQueuedSendError(serverId, agentId, drainBlockedBySettingsError);
} else if (result.status === "failed") {
useSessionStore.getState().setQueuedSendError(serverId, agentId, result.errorMessage);
if (result.status === "failed") {
console.error("[HostRuntime] failed to drain queued agent message", {
serverId,
agentId,
@@ -3042,9 +2934,6 @@ export class HostRuntimeStore {
})
.finally(() => {
this.queuedAgentDrainInFlight.delete(drainKey);
const hadPendingDrain = this.queuedAgentDrainPending.delete(drainKey);
if (!drainSent || !hadPendingDrain) return;
this.resumeIdleQueueIfReady(serverId, agentId);
});
}
@@ -3070,10 +2959,6 @@ export class HostRuntimeStore {
return this.requireDirectory(serverId).acceptAgent(agent);
}
tryAcceptAgentSnapshot(serverId: string, agent: Agent): Agent | null {
return this.directorySyncByServer.get(serverId)?.acceptAgent(agent) ?? null;
}
archiveAgentSnapshot(serverId: string, agentId: string, archivedAt: string): void {
this.requireDirectory(serverId).archiveAgent(agentId, archivedAt);
}
@@ -3243,19 +3128,12 @@ export class HostRuntimeStore {
const directory = this.directorySyncByServer.get(serverId);
if (!directory) throw new Error(`Unknown host runtime for serverId ${serverId}`);
const owner = useSessionStore.getState().sessions[serverId]?.viewedTimelineSync;
// A page served before a rewind this client applied is asked for again. Seqs only grow within
// an epoch, so the next page includes the rewind unless another one landed meanwhile.
for (let attempt = 1; ; attempt += 1) {
const page = await directory.fetchTimeline(agentId, request);
if (!owner || useSessionStore.getState().sessions[serverId]?.viewedTimelineSync !== owner) {
return page;
}
const page = await directory.fetchTimeline(agentId, request);
if (owner && useSessionStore.getState().sessions[serverId]?.viewedTimelineSync === owner) {
owner.flushStreamAgent(agentId);
if (owner.applyTimelineResponse(page) !== "stale") return page;
if (attempt === MAX_STALE_TIMELINE_PAGE_ATTEMPTS) {
throw new Error(`Timeline page for ${agentId} stayed behind a rewind`);
}
owner.applyTimelineResponse(page);
}
return page;
}
createViewedTimelineOwner(
@@ -67,7 +67,7 @@ it("does not store a checkpoint for rows that another tab evicted", async () =>
id: "message-1",
text: "x".repeat(16_384),
timestamp: new Date("2026-07-18T08:02:00.000Z"),
timelineCursor: { epoch: "epoch-1", anchorSeq: 12, seq: 12 },
timelineCursor: { epoch: "epoch-1", seq: 12 },
},
],
range: { epoch: "epoch-1", startSeq: 1, endSeq: 12 },
@@ -189,7 +189,7 @@ function timelineItem(text = "Cached"): StreamItem {
id: "message-1",
text,
timestamp: new Date("2026-07-18T08:02:00.000Z"),
timelineCursor: { epoch: "epoch-1", seq: 12, anchorSeq: 12 },
timelineCursor: { epoch: "epoch-1", seq: 12 },
};
}
@@ -840,7 +840,7 @@ describe("ReplicaCache", () => {
version: 1,
data: { passed: 4, failed: 0 },
timestamp: new Date("2026-07-18T08:02:00.000Z"),
timelineCursor: { epoch: "epoch-1", seq: 12, anchorSeq: 12 },
timelineCursor: { epoch: "epoch-1", seq: 12 },
};
writer.commitTimeline(SERVER_ID, "agent-1", {
agentId: "agent-1",
@@ -885,32 +885,6 @@ describe("ReplicaCache", () => {
expect(await createCache(storage).readTimeline(SERVER_ID, "agent-1")).toBeUndefined();
});
it("keeps where each cached row started, and refetches a timeline cached without it", async () => {
const storage = new MemoryStorage();
const writer = createCache(storage);
const updatedAfterItStarted: StreamItem = {
...timelineItem(),
timelineCursor: { epoch: "epoch-1", seq: 12, anchorSeq: 9 },
};
writer.commitTimeline(SERVER_ID, "agent-1", { ...timeline(), items: [updatedAfterItStarted] });
await writer.flush();
expect((await createCache(storage).readTimeline(SERVER_ID, "agent-1"))?.items).toEqual([
updatedAfterItStarted,
]);
const row = requireTimelineRow(storage);
const payload = JSON.parse(row.payload) as {
items: Array<{ timelineCursor?: Record<string, unknown> }>;
};
delete payload.items[0]?.timelineCursor?.anchorSeq;
storage.rows.set(`${row.serverId}:${row.kind}:${row.id}`, {
...row,
payload: JSON.stringify(payload),
});
expect(await createCache(storage).readTimeline(SERVER_ID, "agent-1")).toBeUndefined();
});
it("refetches old cached Markdown fragments instead of offering them as whole messages", async () => {
const storage = new MemoryStorage();
const writer = createCache(storage);
@@ -1381,7 +1355,7 @@ it("retains semantic agent messages across disk-cache reconstruction", async ()
kind: "tool_call",
id: "delivery",
timestamp: new Date(1),
timelineCursor: { epoch: "epoch-1", seq: 12, anchorSeq: 12 },
timelineCursor: { epoch: "epoch-1", seq: 12 },
payload: {
source: "agent",
data: {
@@ -22,7 +22,6 @@ import {
isUnreconciledLocalUserMessage,
type AgentToolCallData,
type StreamItem,
type TimelinePosition,
} from "@/types/stream";
import type { UnsettledTurn } from "@/timeline/turn-liveness";
import { normalizeAgentSnapshot } from "@/utils/agent-snapshots";
@@ -83,15 +82,7 @@ const IsoDateSchema = z.iso.datetime();
const TimelinePositionSchema = z.strictObject({
epoch: z.string(),
seq: z.number().int().nonnegative(),
// COMPAT(timelineRewindOperations): absent on caches written before rows were anchored, added in
// v0.18.0, remove after 2027-05-25. Such a cache is not restored; the chat loads its tail instead.
anchorSeq: z.number().int().nonnegative().optional(),
});
type StoredTimelinePosition = z.infer<typeof TimelinePositionSchema>;
function isAnchored(position: StoredTimelinePosition | undefined): boolean {
return position === undefined || position.anchorSeq !== undefined;
}
const PluginTimelineDataSchema: z.ZodType<PluginTimelineData> = z.lazy(() =>
z.union([
z.null(),
@@ -170,23 +161,6 @@ const StoredTimelineItemSchema = z.discriminatedUnion("kind", [
trigger: z.enum(["auto", "manual"]).optional(),
preTokens: z.number().nonnegative().optional(),
}),
z.strictObject({
...TimelineItemBaseShape,
kind: z.literal("provider_switch"),
fromProvider: AgentProviderSchema,
toProvider: AgentProviderSchema,
fromModel: z.string().nullable().optional(),
toModel: z.string().nullable().optional(),
fromSessionId: z.string().nullable().optional(),
toSessionId: z.string().nullable().optional(),
context: z.strictObject({
includedItems: z.number().int().nonnegative(),
truncated: z.boolean(),
charCount: z.number().int().nonnegative(),
budgetChars: z.number().int().positive(),
omittedReasons: z.array(z.string()).optional(),
}),
}),
z.strictObject({
...TimelineItemBaseShape,
kind: z.literal("tool_call"),
@@ -388,7 +362,6 @@ const StoredTimelineSchema = z.strictObject({
epoch: z.string(),
startSeq: z.number().int().nonnegative(),
endSeq: z.number().int().nonnegative(),
activeSegmentStartSeq: z.number().int().nonnegative().optional(),
})
.nullable(),
hasOlder: z.boolean(),
@@ -450,10 +423,6 @@ function deserializeTimeline(stored: StoredTimeline | null): CachedTimeline | nu
if (!stored) {
return null;
}
// A rewind retires rows by anchor, so an unanchored row could not be retired.
if (!stored.items.every((item) => isAnchored(item.timelineCursor))) {
return null;
}
return {
agentId: stored.agentId,
items: stored.items.map(deserializeTimelineItem),
@@ -500,26 +469,6 @@ function serializeAgentToolCall(data: AgentToolCallData): StoredToolCall {
}
}
function serializeProviderSwitchItem(
base: ReturnType<typeof timelineBase>,
item: Extract<StreamItem, { kind: "provider_switch" }>,
): StoredTimelineItem | null {
if (!item.context || item.pendingClientMessageId !== undefined) {
return null;
}
return {
...base,
kind: item.kind,
fromProvider: item.fromProvider,
toProvider: item.toProvider,
...(item.fromModel !== undefined ? { fromModel: item.fromModel } : {}),
...(item.toModel !== undefined ? { toModel: item.toModel } : {}),
...(item.fromSessionId !== undefined ? { fromSessionId: item.fromSessionId } : {}),
...(item.toSessionId !== undefined ? { toSessionId: item.toSessionId } : {}),
context: item.context,
};
}
function serializeTimelineItem(item: StreamItem): StoredTimelineItem | null {
const base = timelineBase(item);
switch (item.kind) {
@@ -565,8 +514,6 @@ function serializeTimelineItem(item: StreamItem): StoredTimelineItem | null {
...(item.trigger ? { trigger: item.trigger } : {}),
...(item.preTokens !== undefined ? { preTokens: item.preTokens } : {}),
};
case "provider_switch":
return serializeProviderSwitchItem(base, item);
case "tool_call":
if (item.payload.source !== "agent") return null;
return {
@@ -592,20 +539,11 @@ function serializeTimelineItem(item: StreamItem): StoredTimelineItem | null {
}
}
function anchoredPosition(position: StoredTimelinePosition | undefined): {
timelineCursor?: TimelinePosition;
} {
if (!position || position.anchorSeq === undefined) return {};
return {
timelineCursor: { epoch: position.epoch, seq: position.seq, anchorSeq: position.anchorSeq },
};
}
function deserializeTimelineItem(item: StoredTimelineItem): StreamItem {
if (item.kind === "plugin") {
return {
id: item.id,
...anchoredPosition(item.timelineCursor),
...(item.timelineCursor ? { timelineCursor: item.timelineCursor } : {}),
...(item.turnId ? { turnId: item.turnId } : {}),
timestamp: new Date(item.timestamp),
kind: item.kind,
@@ -619,29 +557,12 @@ function deserializeTimelineItem(item: StoredTimelineItem): StreamItem {
return deserializeBuiltinTimelineItem(item);
}
function deserializeProviderSwitchItem(
base: { id: string; timelineCursor?: TimelinePosition; turnId?: string; timestamp: Date },
item: Extract<StoredTimelineItem, { kind: "provider_switch" }>,
): StreamItem {
return {
...base,
kind: item.kind,
fromProvider: item.fromProvider,
toProvider: item.toProvider,
...(item.fromModel !== undefined ? { fromModel: item.fromModel } : {}),
...(item.toModel !== undefined ? { toModel: item.toModel } : {}),
...(item.fromSessionId !== undefined ? { fromSessionId: item.fromSessionId } : {}),
...(item.toSessionId !== undefined ? { toSessionId: item.toSessionId } : {}),
context: item.context,
};
}
function deserializeBuiltinTimelineItem(
item: Exclude<StoredTimelineItem, { kind: "plugin" }>,
): StreamItem {
const base = {
id: item.id,
...anchoredPosition(item.timelineCursor),
...(item.timelineCursor ? { timelineCursor: item.timelineCursor } : {}),
...(item.turnId ? { turnId: item.turnId } : {}),
timestamp: new Date(item.timestamp),
};
@@ -688,8 +609,6 @@ function deserializeBuiltinTimelineItem(
...(item.trigger ? { trigger: item.trigger } : {}),
...(item.preTokens !== undefined ? { preTokens: item.preTokens } : {}),
};
case "provider_switch":
return deserializeProviderSwitchItem(base, item);
case "tool_call": {
const tool = item.item;
if (tool.type !== "tool_call") {
@@ -921,14 +840,7 @@ function serializeTimeline(timeline: CachedTimeline): StoredTimeline | null {
agentId: timeline.agentId,
items,
range: canPersistCoverage
? {
epoch: range.epoch,
startSeq: range.startSeq,
endSeq: range.endSeq,
...(range.activeSegmentStartSeq !== undefined
? { activeSegmentStartSeq: range.activeSegmentStartSeq }
: {}),
}
? { epoch: range.epoch, startSeq: range.startSeq, endSeq: range.endSeq }
: null,
hasOlder: canPersistCoverage ? timeline.hasOlder : false,
...(timeline.unsettledTurn
@@ -2217,10 +2217,11 @@ function WorkspaceScreenContent({
toast.show(t("workspace.tabs.toasts.reloadingAgent"), { durationMs: null });
try {
const refreshed = await client.refreshAgent(agentId);
// Send the existing cursor: Reload agent keeps the history, so the server
// returns only the rows it added. When the history was imported again
// under a new epoch, the cursor reads as stale and the server resets.
await client.refreshAgent(agentId);
// Send the existing cursor so the server detects the new epoch and
// returns reset:true. Without a cursor, the server returns reset:false
// and the client takes the incremental path, where new-epoch rows are
// dropped against the stale cursor.
const sessionState = useSessionStore.getState().sessions[normalizedServerId];
const currentCursor = sessionState?.agentTimelineCursor.get(agentId);
await getHostRuntimeStore().fetchAgentTimeline(normalizedServerId, agentId, {
@@ -2229,13 +2230,7 @@ function WorkspaceScreenContent({
? { cursor: { epoch: currentCursor.epoch, seq: currentCursor.endSeq } }
: {}),
});
if (refreshed.historyDiverged) {
toast.show(t("workspace.tabs.toasts.reloadedAgentHistoryDiverged"), {
variant: "warning",
});
} else {
toast.show(t("workspace.tabs.toasts.reloadedAgent"), { variant: "success" });
}
toast.show(t("workspace.tabs.toasts.reloadedAgent"), { variant: "success" });
} catch (error) {
toast.error(
error instanceof Error ? error.message : t("workspace.tabs.toasts.failedToReloadAgent"),
+1 -66
View File
@@ -9,7 +9,6 @@ import {
appendSubmittedUserMessage,
handoffCreatedAgentUserMessageToStream,
removeSubmittedUserMessage,
type ProviderSwitchItem,
type StreamItem,
type TodoEntry,
type UserMessageItem,
@@ -319,7 +318,6 @@ export interface AgentTimelineCursorState {
epoch: string;
startSeq: number;
endSeq: number;
activeSegmentStartSeq?: number;
retainedRanges?: Array<{
startSeq: number;
endSeq: number;
@@ -327,12 +325,6 @@ export interface AgentTimelineCursorState {
}>;
}
/** The latest conversation rewind applied to an agent's history, by its sequence number. */
export interface AgentTimelineRewind {
epoch: string;
seq: number;
}
export type AgentTimelineState =
| { status: "cold" }
| { status: "painted"; items: StreamItem[] }
@@ -507,7 +499,6 @@ export interface SessionState {
agentTimelineUnsettledTurn: Map<string, UnsettledTurn>;
agentTimelineHasOlder: Map<string, boolean>;
agentTimelineHasNewer: Map<string, boolean>;
agentTimelineLatestRewind: Map<string, AgentTimelineRewind>;
agentTimelineOlderFetchInFlight: Map<string, boolean>;
historySyncGeneration: number;
agentHistorySyncGeneration: Map<string, number>;
@@ -538,7 +529,6 @@ export interface SessionState {
string,
Array<{ id: string; text: string; attachments: ComposerAttachment[] }>
>;
queuedSendErrors: Map<string, string>;
}
// Global store state
@@ -597,7 +587,6 @@ interface SessionStoreActions {
serverId: string,
agentId: string,
message: UserMessageItem,
options?: { providerSwitch?: ProviderSwitchItem },
) => void;
acceptAgentMessageSubmission: (
serverId: string,
@@ -631,12 +620,6 @@ interface SessionStoreActions {
serverId: string,
state: Map<string, boolean> | ((prev: Map<string, boolean>) => Map<string, boolean>),
) => void;
/** Records a rewind applied to the agent's history; an older one of the same history is ignored. */
recordAgentTimelineRewind: (
serverId: string,
agentId: string,
rewind: AgentTimelineRewind,
) => void;
setAgentTimelineOlderFetchInFlight: (
serverId: string,
state: Map<string, boolean> | ((prev: Map<string, boolean>) => Map<string, boolean>),
@@ -733,7 +716,6 @@ interface SessionStoreActions {
prev: Map<string, Array<{ id: string; text: string; attachments: ComposerAttachment[] }>>,
) => Map<string, Array<{ id: string; text: string; attachments: ComposerAttachment[] }>>),
) => void;
setQueuedSendError: (serverId: string, agentId: string, error: string | null) => void;
// Hydration
setHasHydratedAgents: (serverId: string, hydrated: boolean) => void;
@@ -774,7 +756,6 @@ function createInitialSessionState(
agentTimelineUnsettledTurn: new Map(),
agentTimelineHasOlder: new Map(),
agentTimelineHasNewer: new Map(),
agentTimelineLatestRewind: new Map(),
agentTimelineOlderFetchInFlight: new Map(),
historySyncGeneration: 0,
agentHistorySyncGeneration: new Map(),
@@ -789,7 +770,6 @@ function createInitialSessionState(
pendingPermissions: new Map(),
fileExplorer: new Map(),
queuedMessages: new Map(),
queuedSendErrors: new Map(),
};
}
@@ -1192,7 +1172,7 @@ export const useSessionStore = create<SessionStore>()(
});
},
beginAgentMessageSubmission: (serverId, agentId, message, options) => {
beginAgentMessageSubmission: (serverId, agentId, message) => {
set((prev) => {
const session = prev.sessions[serverId];
if (!session) return prev;
@@ -1205,7 +1185,6 @@ export const useSessionStore = create<SessionStore>()(
tail: currentTail,
head: currentHead,
message,
providerSwitch: options?.providerSwitch,
});
const submissions = beginMessageSubmission(
session.messageSubmissions.get(agentId) ?? [],
@@ -1455,24 +1434,6 @@ export const useSessionStore = create<SessionStore>()(
});
},
recordAgentTimelineRewind: (serverId, agentId, rewind) => {
set((prev) => {
const session = prev.sessions[serverId];
if (!session) return prev;
const current = session.agentTimelineLatestRewind.get(agentId);
if (current && current.epoch === rewind.epoch && current.seq >= rewind.seq) return prev;
const next = new Map(session.agentTimelineLatestRewind);
next.set(agentId, rewind);
return {
...prev,
sessions: {
...prev.sessions,
[serverId]: { ...session, agentTimelineLatestRewind: next },
},
};
});
},
setAgentTimelineOlderFetchInFlight: (serverId, state) => {
set((prev) => {
const session = prev.sessions[serverId];
@@ -2016,32 +1977,6 @@ export const useSessionStore = create<SessionStore>()(
});
},
setQueuedSendError: (serverId, agentId, error) => {
set((prev) => {
const session = prev.sessions[serverId];
if (!session) {
return prev;
}
const existing = session.queuedSendErrors.get(agentId) ?? null;
if (existing === error) {
return prev;
}
const next = new Map(session.queuedSendErrors);
if (error === null) {
next.delete(agentId);
} else {
next.set(agentId, error);
}
return {
...prev,
sessions: {
...prev.sessions,
[serverId]: { ...session, queuedSendErrors: next },
},
};
});
},
// Hydration
setHasHydratedAgents: (serverId, hydrated) => {
set((prev) => {
@@ -0,0 +1,73 @@
import { lightHighlightColors, type HighlightStyle } from "@getpaseo/highlight";
import { describe, expect, it } from "vitest";
import { appearanceStyleBoundaryKey } from "@/components/appearance-style-boundary";
import { lightTheme } from "./theme";
import { syntaxTokenStyleFor, syntaxTokenStyles } from "./syntax-token-styles";
describe("syntaxTokenStyleFor", () => {
it("maps diffAddition, diffDeletion, and meta to distinct token colors", () => {
expect(syntaxTokenStyleFor("diffAddition")).toEqual({
color: lightHighlightColors.diffAddition,
});
expect(syntaxTokenStyleFor("diffDeletion")).toEqual({
color: lightHighlightColors.diffDeletion,
});
expect(syntaxTokenStyleFor("meta")).toEqual({ color: lightHighlightColors.meta });
});
it("resolves every HighlightStyle without falling back to base", () => {
const styles: HighlightStyle[] = [
"keyword",
"comment",
"string",
"number",
"literal",
"function",
"definition",
"class",
"type",
"tag",
"attribute",
"property",
"variable",
"operator",
"punctuation",
"regexp",
"escape",
"meta",
"heading",
"link",
"diffAddition",
"diffDeletion",
];
for (const style of styles) {
expect(syntaxTokenStyleFor(style)).toBe(syntaxTokenStyles[style]);
}
expect(syntaxTokenStyleFor(null)).toBe(syntaxTokenStyles.base);
expect(syntaxTokenStyleFor("unknown")).toBe(syntaxTokenStyles.base);
});
it("tracks diffAddition and diffDeletion in appearanceStyleBoundaryKey", () => {
const changedAddition = {
...lightTheme,
colors: {
...lightTheme.colors,
syntax: { ...lightTheme.colors.syntax, diffAddition: "#00ff00" },
},
};
const changedDeletion = {
...lightTheme,
colors: {
...lightTheme.colors,
syntax: { ...lightTheme.colors.syntax, diffDeletion: "#ff0000" },
},
};
expect(appearanceStyleBoundaryKey(changedAddition)).not.toBe(
appearanceStyleBoundaryKey(lightTheme),
);
expect(appearanceStyleBoundaryKey(changedDeletion)).not.toBe(
appearanceStyleBoundaryKey(lightTheme),
);
});
});
@@ -26,6 +26,8 @@ export const syntaxTokenStyles = StyleSheet.create((theme) => ({
meta: { color: theme.colors.syntax.meta },
heading: { color: theme.colors.syntax.heading },
link: { color: theme.colors.syntax.link },
diffAddition: { color: theme.colors.syntax.diffAddition },
diffDeletion: { color: theme.colors.syntax.diffDeletion },
}));
type SyntaxTokenStyleValue = (typeof syntaxTokenStyles)["base"];
+1 -230
View File
@@ -47,7 +47,7 @@ function item(id: string, text: string, seq: number): StreamItem {
id,
text,
timestamp: new Date("2026-08-26T10:00:00.000Z"),
timelineCursor: { epoch: "epoch-1", seq, anchorSeq: seq },
timelineCursor: { epoch: "epoch-1", seq },
};
}
@@ -693,235 +693,6 @@ describe("viewed timeline persistence", () => {
});
});
describe("conversation rewind through the owner", () => {
const page = {
requestId: "page-1",
agentId: AGENT_ID,
agent: null,
direction: "tail",
projection: "projected",
reset: false,
epoch: "epoch-1",
error: null,
hasNewer: false,
hasOlder: false,
staleCursor: false,
gap: false,
} as const;
function entry(seq: number, type: "user_message" | "assistant_message", text: string) {
return {
seqStart: seq,
seqEnd: seq,
sourceSeqRanges: [{ startSeq: seq, endSeq: seq }],
collapsed: [],
provider: "codex",
item: { type, text },
timestamp: `2026-08-26T10:00:0${seq}.000Z`,
};
}
function texts(items: readonly StreamItem[]): string[] {
return items.flatMap((row) =>
row.kind === "user_message" || row.kind === "assistant_message" ? [row.text] : [],
);
}
function viewed(): string[] {
const session = useSessionStore.getState().sessions[SERVER_ID];
const timeline = selectAgentTimelineState(session, AGENT_ID);
const tail = timeline.status === "cold" ? [] : timeline.items;
return texts([...tail, ...(session?.agentStreamHead.get(AGENT_ID) ?? [])]);
}
function latestRewind() {
return useSessionStore.getState().sessions[SERVER_ID]?.agentTimelineLatestRewind.get(AGENT_ID);
}
it("retires B from the viewed and persisted timeline without refetching", () => {
useSessionStore.getState().initializeSession(SERVER_ID, null);
const commits: CachedTimeline[] = [];
const owner = createOwner({
readTimeline: async () => undefined,
commitTimeline: (_serverId, _agentId, timeline) => commits.push(timeline),
});
owner.applyTimelineResponse({
...page,
window: { minSeq: 1, maxSeq: 4, nextSeq: 5 },
startCursor: { epoch: "epoch-1", seq: 1 },
endCursor: { epoch: "epoch-1", seq: 4 },
entries: [
entry(1, "user_message", "A"),
entry(2, "assistant_message", "reply A"),
entry(3, "user_message", "B"),
entry(4, "assistant_message", "reply B"),
],
});
owner.applyStreamEvent(AGENT_ID, {
event: { type: "rewind", retireFromSeq: 3 },
seq: 5,
epoch: "epoch-1",
timestamp: new Date("2026-08-26T10:00:05.000Z"),
});
owner.applyStreamEvent(AGENT_ID, {
event: {
type: "timeline",
provider: "codex",
item: { type: "user_message", text: "C", messageId: "c" },
} as AgentStreamEventPayload,
seq: 6,
epoch: "epoch-1",
timestamp: new Date("2026-08-26T10:00:06.000Z"),
});
owner.flushStreamAgent(AGENT_ID);
expect(viewed()).toEqual(["A", "reply A", "C"]);
expect(texts(commits.at(-1)?.items ?? [])).toEqual(["A", "reply A", "C"]);
expect(commits.at(-1)?.range).toMatchObject({ epoch: "epoch-1", endSeq: 6 });
expect(latestRewind()).toEqual({ epoch: "epoch-1", seq: 5 });
owner.dispose();
});
it("brings a second client that loads after the rewind to the same conversation", () => {
useSessionStore.getState().initializeSession(SERVER_ID, null);
const owner = createOwner({ readTimeline: async () => undefined, commitTimeline: () => {} });
owner.applyTimelineResponse({
...page,
window: { minSeq: 1, maxSeq: 6, nextSeq: 7 },
startCursor: { epoch: "epoch-1", seq: 1 },
endCursor: { epoch: "epoch-1", seq: 6 },
entries: [
entry(1, "user_message", "A"),
entry(2, "assistant_message", "reply A"),
entry(6, "user_message", "C"),
],
retirements: [{ seq: 5, retireFromSeq: 3 }],
});
expect(viewed()).toEqual(["A", "reply A", "C"]);
expect(latestRewind()).toEqual({ epoch: "epoch-1", seq: 5 });
owner.dispose();
});
function liveRewindOfB(owner: ViewedTimelineOwner, retirement: { seq: number }): void {
owner.applyStreamEvent(AGENT_ID, {
event: { type: "rewind", retireFromSeq: 3 },
seq: retirement.seq,
epoch: "epoch-1",
timestamp: new Date("2026-08-26T10:00:06.000Z"),
});
owner.applyStreamEvent(AGENT_ID, {
event: {
type: "timeline",
provider: "codex",
item: { type: "user_message", text: "C", messageId: "c" },
} as AgentStreamEventPayload,
seq: retirement.seq + 1,
epoch: "epoch-1",
timestamp: new Date("2026-08-26T10:00:07.000Z"),
});
owner.flushStreamAgent(AGENT_ID);
}
/** A, reply A, B, reply B as a page served before B was rewound. */
const pageServedBeforeTheRewind: Parameters<ViewedTimelineOwner["applyTimelineResponse"]>[0] = {
...page,
direction: "before",
hasOlder: false,
window: { minSeq: 1, maxSeq: 5, nextSeq: 6 },
startCursor: { epoch: "epoch-1", seq: 1 },
endCursor: { epoch: "epoch-1", seq: 4 },
entries: [
entry(1, "user_message", "A"),
entry(2, "assistant_message", "reply A"),
entry(3, "user_message", "B"),
entry(4, "assistant_message", "reply B"),
],
};
function loadTheEndOfB(owner: ViewedTimelineOwner): void {
owner.applyTimelineResponse({
...page,
hasOlder: true,
window: { minSeq: 1, maxSeq: 5, nextSeq: 6 },
startCursor: { epoch: "epoch-1", seq: 5 },
endCursor: { epoch: "epoch-1", seq: 5 },
entries: [entry(5, "assistant_message", "more of B")],
});
}
it("refuses an older page served before the rewind and takes the one served after it", () => {
useSessionStore.getState().initializeSession(SERVER_ID, null);
const owner = createOwner({ readTimeline: async () => undefined, commitTimeline: () => {} });
loadTheEndOfB(owner);
liveRewindOfB(owner, { seq: 6 });
expect(viewed()).toEqual(["C"]);
const outcome = owner.applyTimelineResponse(pageServedBeforeTheRewind);
expect(viewed()).toEqual(["C"]);
expect(outcome).toBe("stale");
owner.applyTimelineResponse({
...pageServedBeforeTheRewind,
window: { minSeq: 1, maxSeq: 7, nextSeq: 8 },
// Retired rows count as covered, so the page reaches the loaded start.
endCursor: { epoch: "epoch-1", seq: 4 },
entries: [entry(1, "user_message", "A"), entry(2, "assistant_message", "reply A")],
});
expect(viewed()).toEqual(["A", "reply A", "C"]);
owner.dispose();
});
it("refuses a prompt jump window served before the rewind", () => {
useSessionStore.getState().initializeSession(SERVER_ID, null);
const owner = createOwner({ readTimeline: async () => undefined, commitTimeline: () => {} });
loadTheEndOfB(owner);
liveRewindOfB(owner, { seq: 6 });
const outcome = owner.applyTimelineResponse({
...pageServedBeforeTheRewind,
mergeWindow: true,
});
expect(viewed()).toEqual(["C"]);
expect(outcome).toBe("stale");
owner.dispose();
});
it("refuses a first page served before a rewind that reached the chat while it loaded", () => {
useSessionStore.getState().initializeSession(SERVER_ID, null);
const owner = createOwner({ readTimeline: async () => undefined, commitTimeline: () => {} });
liveRewindOfB(owner, { seq: 5 });
const outcome = owner.applyTimelineResponse({
...pageServedBeforeTheRewind,
direction: "tail",
window: { minSeq: 1, maxSeq: 4, nextSeq: 5 },
});
expect(viewed()).toEqual(["C"]);
expect(outcome).toBe("stale");
owner.applyTimelineResponse({
...page,
window: { minSeq: 1, maxSeq: 6, nextSeq: 7 },
startCursor: { epoch: "epoch-1", seq: 1 },
endCursor: { epoch: "epoch-1", seq: 6 },
entries: [
entry(1, "user_message", "A"),
entry(2, "assistant_message", "reply A"),
{
...entry(6, "user_message", "C"),
item: { type: "user_message", text: "C", messageId: "c" },
},
],
retirements: [{ seq: 5, retireFromSeq: 3 }],
});
expect(viewed()).toEqual(["A", "reply A", "C"]);
owner.dispose();
});
});
describe("turn boundaries", () => {
it("commits a turn's final reply before the turn stops running", () => {
useSessionStore.getState().initializeSession(SERVER_ID, null);
@@ -398,7 +398,7 @@ describe("processTimelineResponse", () => {
messageId: "provider-message",
text: "local prompt",
timestamp: new Date(1000),
timelineCursor: { epoch: "epoch-1", seq: 1, anchorSeq: 1 },
timelineCursor: { epoch: "epoch-1", seq: 1 },
turnId: "turn-1",
});
const hello = createUserMessage({
@@ -406,7 +406,7 @@ describe("processTimelineResponse", () => {
clientMessageId: "hello-client",
text: "hello",
timestamp: new Date(1500),
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 2 },
timelineCursor: { epoch: "epoch-1", seq: 2 },
turnId: "turn-1",
});
const currentTail = [canonical, makeAssistantItem("existing tail", "existing-tail"), hello];
@@ -456,7 +456,7 @@ describe("processTimelineResponse", () => {
id: "stale-history",
text: "stale history",
timestamp: new Date(1040),
timelineCursor: { epoch: "epoch-1", seq: 40, anchorSeq: 40 },
timelineCursor: { epoch: "epoch-1", seq: 40 },
},
],
currentCursor: { epoch: "epoch-1", startSeq: 1, endSeq: 40 },
@@ -484,11 +484,11 @@ describe("processTimelineResponse", () => {
const unresolved = makeSubmittedUserMessage("unresolved prompt", "client-unresolved");
const coveredLive: StreamItem = {
...makeAssistantItem("covered live", "covered-live"),
timelineCursor: { epoch: "epoch-1", seq: 235, anchorSeq: 235 },
timelineCursor: { epoch: "epoch-1", seq: 235 },
};
const newerLive: StreamItem = {
...makeAssistantItem("newer live", "newer-live"),
timelineCursor: { epoch: "epoch-1", seq: 245, anchorSeq: 245 },
timelineCursor: { epoch: "epoch-1", seq: 245 },
};
const result = processTimelineResponse({
@@ -573,7 +573,7 @@ describe("processTimelineResponse", () => {
expect.objectContaining({
kind: "assistant_message",
text: "[System Error] failed",
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 40 },
timelineCursor: { epoch: "timeline-1", seq: 42 },
}),
]);
});
@@ -745,7 +745,7 @@ describe("processTimelineResponse", () => {
}).item,
} as AgentStreamEventPayload,
timestamp: new Date(2000),
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 2 },
timelineCursor: { epoch: "epoch-1", seq: 2 },
},
],
{ source: "canonical" },
@@ -775,7 +775,7 @@ describe("processTimelineResponse", () => {
expect(getAgentToolCalls([...result.tail, ...result.head])).toEqual([
expect.objectContaining({
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 1 },
timelineCursor: { epoch: "epoch-1", seq: 2 },
payload: expect.objectContaining({
data: expect.objectContaining({ callId, status: "completed" }),
}),
@@ -796,7 +796,7 @@ describe("processTimelineResponse", () => {
},
} as AgentStreamEventPayload,
timestamp: new Date(2000),
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 2 },
timelineCursor: { epoch: "epoch-1", seq: 2 },
},
],
{ source: "canonical" },
@@ -831,7 +831,7 @@ describe("processTimelineResponse", () => {
expect([...result.tail, ...result.head].filter((item) => item.kind === "todo_list")).toEqual([
expect.objectContaining({
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 1 },
timelineCursor: { epoch: "epoch-1", seq: 2 },
items: [{ text: "Verify hydration", completed: true }],
}),
]);
@@ -847,7 +847,7 @@ describe("processTimelineResponse", () => {
item: { type: "compaction", status: "completed", trigger: "auto", preTokens: 1200 },
} as AgentStreamEventPayload,
timestamp: new Date(2000),
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 2 },
timelineCursor: { epoch: "epoch-1", seq: 2 },
},
],
{ source: "canonical" },
@@ -879,7 +879,7 @@ describe("processTimelineResponse", () => {
expect([...result.tail, ...result.head].filter((item) => item.kind === "compaction")).toEqual([
expect.objectContaining({
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 1 },
timelineCursor: { epoch: "epoch-1", seq: 2 },
status: "completed",
trigger: "auto",
preTokens: 1200,
@@ -918,7 +918,7 @@ describe("processTimelineResponse", () => {
messageId: "assistant-live",
text: " continuation",
timestamp: new Date(2001),
timelineCursor: { epoch: "epoch-1", seq: 101, anchorSeq: 101 },
timelineCursor: { epoch: "epoch-1", seq: 101 },
},
],
isInitializing: true,
@@ -946,7 +946,7 @@ describe("processTimelineResponse", () => {
);
expect(assistants).toHaveLength(1);
expect(assistants[0]?.text).toBe("canonical prefix continuation");
expect(assistants[0]?.timelineCursor).toEqual({ epoch: "epoch-1", seq: 101, anchorSeq: 100 });
expect(assistants[0]?.timelineCursor).toEqual({ epoch: "epoch-1", seq: 101 });
});
it("keeps assistant segments separate when a live tool sits between them", () => {
@@ -963,12 +963,12 @@ describe("processTimelineResponse", () => {
}).item,
} as AgentStreamEventPayload,
timestamp: new Date(2101),
timelineCursor: { epoch: "epoch-1", seq: 101, anchorSeq: 101 },
timelineCursor: { epoch: "epoch-1", seq: 101 },
},
{
event: makeAssistantTimelineEvent("after tool", messageId),
timestamp: new Date(2102),
timelineCursor: { epoch: "epoch-1", seq: 102, anchorSeq: 102 },
timelineCursor: { epoch: "epoch-1", seq: 102 },
},
],
{ source: "canonical" },
@@ -1019,7 +1019,7 @@ describe("processTimelineResponse", () => {
id: "assistant-live",
text: "canonical prefix continuation",
timestamp: new Date(2001),
timelineCursor: { epoch: "epoch-1", seq: 101, anchorSeq: 101 },
timelineCursor: { epoch: "epoch-1", seq: 101 },
},
],
isInitializing: true,
@@ -1038,7 +1038,7 @@ describe("processTimelineResponse", () => {
);
expect(assistants).toHaveLength(1);
expect(assistants[0]?.text).toBe("canonical prefix continuation");
expect(assistants[0]?.timelineCursor).toEqual({ epoch: "epoch-1", seq: 101, anchorSeq: 100 });
expect(assistants[0]?.timelineCursor).toEqual({ epoch: "epoch-1", seq: 101 });
});
it("keeps a canonical live user row newer than the bootstrap page", () => {
@@ -1060,7 +1060,7 @@ describe("processTimelineResponse", () => {
});
expect(live.head[0]).toMatchObject({
kind: "user_message",
timelineCursor: { epoch: "epoch-1", seq: 101, anchorSeq: 101 },
timelineCursor: { epoch: "epoch-1", seq: 101 },
});
const result = processTimelineResponse({
@@ -1123,7 +1123,7 @@ describe("processTimelineResponse", () => {
kind: "user_message",
clientMessageId: "client-message-1",
messageId: "provider-message-1",
timelineCursor: { epoch: "epoch-1", seq: 51, anchorSeq: 51 },
timelineCursor: { epoch: "epoch-1", seq: 51 },
});
});
@@ -2808,7 +2808,7 @@ describe("processTimelineResponse", () => {
id: "newest",
text: "newest",
timestamp: new Date(1000),
timelineCursor: { epoch: "epoch-1", seq: 100, anchorSeq: 100 },
timelineCursor: { epoch: "epoch-1", seq: 100 },
},
makeSubmittedUserMessage("pending submission", "pending-submission"),
],
@@ -2886,14 +2886,14 @@ describe("processTimelineResponse", () => {
id: "oldest",
text: "oldest",
timestamp: new Date(1000),
timelineCursor: { epoch: "epoch-1", seq: 1, anchorSeq: 1 },
timelineCursor: { epoch: "epoch-1", seq: 1 },
},
{
kind: "user_message",
id: "newest",
text: "newest",
timestamp: new Date(100_000),
timelineCursor: { epoch: "epoch-1", seq: 100, anchorSeq: 100 },
timelineCursor: { epoch: "epoch-1", seq: 100 },
},
];
@@ -2935,7 +2935,7 @@ describe("processTimelineResponse", () => {
id: "newest",
text: "newest",
timestamp: new Date(100_000),
timelineCursor: { epoch: "epoch-1", seq: 100, anchorSeq: 100 },
timelineCursor: { epoch: "epoch-1", seq: 100 },
},
...(lane === "tail" ? [pending] : []),
],
@@ -2976,13 +2976,9 @@ describe("processTimelineResponse", () => {
{
text: "local pending prompt",
messageId: "canonical-message",
timelineCursor: { epoch: "epoch-1", seq: 1, anchorSeq: 1 },
},
{
text: "newest",
messageId: undefined,
timelineCursor: { epoch: "epoch-1", seq: 100, anchorSeq: 100 },
timelineCursor: { epoch: "epoch-1", seq: 1 },
},
{ text: "newest", messageId: undefined, timelineCursor: { epoch: "epoch-1", seq: 100 } },
],
head: [],
acknowledgedClientMessageIds: [clientMessageId],
@@ -2996,7 +2992,7 @@ describe("processTimelineResponse", () => {
{
event: makeToolCallTimelineEvent("call-1"),
timestamp: new Date(500),
timelineCursor: { epoch: "epoch-1", seq: 500, anchorSeq: 500 },
timelineCursor: { epoch: "epoch-1", seq: 500 },
},
],
{ source: "canonical" },
@@ -3042,7 +3038,7 @@ describe("processTimelineResponse", () => {
{
callId: "call-1",
status: "completed",
timelineCursor: { epoch: "epoch-1", seq: 500, anchorSeq: 1 },
timelineCursor: { epoch: "epoch-1", seq: 500 },
},
]);
});
@@ -3054,7 +3050,7 @@ describe("processTimelineResponse", () => {
...makeAssistantItem("projected response", "loaded-assistant"),
messageId: "assistant-message",
timestamp,
timelineCursor: { epoch: "epoch-1", seq: 500, anchorSeq: 500 },
timelineCursor: { epoch: "epoch-1", seq: 500 },
},
];
const result = processTimelineResponse({
@@ -3104,7 +3100,7 @@ describe("processTimelineResponse", () => {
id: "loaded-assistant",
text: "projected response",
messageId: "assistant-message",
timelineCursor: { epoch: "epoch-1", seq: 500, anchorSeq: 1 },
timelineCursor: { epoch: "epoch-1", seq: 500 },
},
]);
});
@@ -3116,7 +3112,7 @@ describe("processTimelineResponse", () => {
id: "current-200",
text: "current-200",
timestamp: new Date(3200),
timelineCursor: { epoch: "epoch-1", seq: 200, anchorSeq: 200 },
timelineCursor: { epoch: "epoch-1", seq: 200 },
},
];
const existingCursor: TimelineCursor = {
@@ -3223,7 +3219,7 @@ describe("processTimelineResponse", () => {
const currentTail = [
{
...makeAssistantItem("newer chunk", "assistant-newer"),
timelineCursor: { epoch: "epoch-1", seq: 3, anchorSeq: 3 },
timelineCursor: { epoch: "epoch-1", seq: 3 },
},
];
const existingCursor: TimelineCursor = {
@@ -3250,7 +3246,7 @@ describe("processTimelineResponse", () => {
expect(result.tail[0]).toEqual(
expect.objectContaining({
id: "assistant-newer",
timelineCursor: { epoch: "epoch-1", seq: 3, anchorSeq: 3 },
timelineCursor: { epoch: "epoch-1", seq: 3 },
}),
);
expect(result.cursor).toEqual({
@@ -3690,7 +3686,7 @@ describe("processAgentStreamEvent", () => {
expect.objectContaining({
kind: "assistant_message",
text: "[System Error] failed",
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 42 },
timelineCursor: { epoch: "timeline-1", seq: 42 },
}),
]);
});
@@ -3939,7 +3935,7 @@ describe("processAgentStreamEvent", () => {
expect(getUserTexts(result.head)).toEqual(["live before bootstrap"]);
expect(result.head[0]).toMatchObject({
kind: "user_message",
timelineCursor: { epoch: "epoch-1", seq: 51, anchorSeq: 51 },
timelineCursor: { epoch: "epoch-1", seq: 51 },
});
expect(result.cursorChanged).toBe(false);
expect(result.cursor).toBeNull();
@@ -3974,7 +3970,7 @@ describe("processAgentStreamEvent", () => {
clientMessageId: "client-message-1",
messageId: "provider-message-1",
text: "submitted before bootstrap",
timelineCursor: { epoch: "epoch-1", seq: 51, anchorSeq: 51 },
timelineCursor: { epoch: "epoch-1", seq: 51 },
}),
]);
});
@@ -4565,279 +4561,6 @@ describe("createAgentStreamReducerQueue", () => {
});
});
// ---------------------------------------------------------------------------
// Conversation rewind: A, B, rewind B, C
// ---------------------------------------------------------------------------
describe("conversation rewind", () => {
const rewindB = { seq: 5, retireFromSeq: 3 };
function loadAB(): { tail: StreamItem[]; head: StreamItem[]; cursor: TimelineCursor } {
const result = processTimelineResponse({
...baseTimelineInput,
isInitializing: true,
hasActiveInitDeferred: true,
payload: {
...baseTimelineInput.payload,
direction: "tail",
window: { minSeq: 1, maxSeq: 4, nextSeq: 5 },
startCursor: { seq: 1 },
endCursor: { seq: 4 },
entries: [
makeTimelineEntry(1, "A", "user_message"),
makeTimelineEntry(2, "reply A"),
makeTimelineEntry(3, "B", "user_message"),
makeTimelineEntry(4, "reply B"),
],
},
});
if (!result.cursor) throw new Error("expected a loaded range");
return { tail: result.tail, head: result.head, cursor: result.cursor };
}
function live(
state: { tail: StreamItem[]; head: StreamItem[]; cursor: TimelineCursor },
events: AgentStreamReducerEvent[],
) {
const result = processAgentStreamEvents({
events,
currentTail: state.tail,
currentHead: state.head,
currentCursor: state.cursor,
hasAuthoritativeBaseline: true,
});
return {
tail: result.tail,
head: result.head,
cursor: result.cursor ?? state.cursor,
sideEffects: result.sideEffects,
};
}
function rewindEvent(retirement: { seq: number; retireFromSeq: number }) {
return {
event: { type: "rewind" as const, retireFromSeq: retirement.retireFromSeq },
seq: retirement.seq,
epoch: "epoch-1",
timestamp: new Date(1000 + retirement.seq),
};
}
const promptC = [
makeStreamReducerEvent(makeTimelineEvent("C", "user_message"), 6),
makeStreamReducerEvent(makeTimelineEvent("reply C"), 7),
];
function conversation(state: { tail: StreamItem[]; head: StreamItem[] }) {
return [...state.tail, ...state.head].map((item) =>
item.kind === "user_message" || item.kind === "assistant_message" ? item.text : item.kind,
);
}
it("retires B in place, keeps A mounted, and shows C once", () => {
const loaded = loadAB();
const [promptA, replyA] = loaded.tail;
const rewound = live(loaded, [rewindEvent(rewindB), ...promptC]);
expect(conversation(rewound)).toEqual(["A", "reply A", "C", "reply C"]);
expect(rewound.tail[0]).toBe(promptA);
expect(rewound.tail[1]).toBe(replyA);
expect(rewound.cursor).toMatchObject({ epoch: "epoch-1", startSeq: 1, endSeq: 7 });
expect(rewound.sideEffects).toEqual([]);
});
it("ignores a duplicate rewind so C is not retired", () => {
const rewound = live(loadAB(), [rewindEvent(rewindB), ...promptC]);
const replayed = live(rewound, [rewindEvent(rewindB)]);
expect(conversation(replayed)).toEqual(["A", "reply A", "C", "reply C"]);
expect(replayed.cursor.endSeq).toBe(7);
});
it("does not let an old page resurrect B after the rewind applied", () => {
const rewound = live(loadAB(), [rewindEvent(rewindB), ...promptC]);
const stale = processTimelineResponse({
...baseTimelineInput,
currentTail: rewound.tail,
currentHead: rewound.head,
currentCursor: rewound.cursor,
payload: {
...baseTimelineInput.payload,
direction: "after",
window: { minSeq: 1, maxSeq: 4, nextSeq: 5 },
startCursor: { seq: 3 },
endCursor: { seq: 4 },
entries: [makeTimelineEntry(3, "B", "user_message"), makeTimelineEntry(4, "reply B")],
},
});
expect(conversation(stale)).toEqual(["A", "reply A", "C", "reply C"]);
expect(stale.cursorChanged).toBe(false);
});
it("drops a late live delivery for the retired range", () => {
const rewound = live(loadAB(), [rewindEvent(rewindB)]);
const late = live(rewound, [makeStreamReducerEvent(makeTimelineEvent("late B"), 4)]);
expect(conversation(late)).toEqual(["A", "reply A"]);
});
it("catches up through a page that only carries the retirement", () => {
const loaded = loadAB();
const caughtUp = processTimelineResponse({
...baseTimelineInput,
currentTail: loaded.tail,
currentHead: loaded.head,
currentCursor: loaded.cursor,
payload: {
...baseTimelineInput.payload,
direction: "after",
window: { minSeq: 1, maxSeq: 5, nextSeq: 6 },
startCursor: { seq: 5 },
endCursor: { seq: 5 },
entries: [],
retirements: [rewindB],
},
});
if (!caughtUp.cursor) throw new Error("expected a loaded range");
expect(conversation(caughtUp)).toEqual(["A", "reply A"]);
expect(caughtUp.cursor.endSeq).toBe(5);
expect(caughtUp.sideEffects).not.toContainEqual(expect.objectContaining({ type: "catch_up" }));
const continued = live({ ...caughtUp, cursor: caughtUp.cursor }, promptC);
expect(conversation(continued)).toEqual(["A", "reply A", "C", "reply C"]);
});
it("converges after reconnect from a resume page that crosses the rewind", () => {
const loaded = loadAB();
const resumed = processTimelineResponse({
...baseTimelineInput,
currentTail: loaded.tail,
currentHead: loaded.head,
currentCursor: loaded.cursor,
payload: {
...baseTimelineInput.payload,
direction: "tail",
window: { minSeq: 1, maxSeq: 7, nextSeq: 8 },
startCursor: { seq: 1 },
endCursor: { seq: 7 },
entries: [
makeTimelineEntry(1, "A", "user_message"),
makeTimelineEntry(2, "reply A"),
makeTimelineEntry(6, "C", "user_message"),
makeTimelineEntry(7, "reply C"),
],
retirements: [rewindB],
},
});
expect(conversation(resumed)).toEqual(["A", "reply A", "C", "reply C"]);
expect(resumed.tail[0]).toBe(loaded.tail[0]);
expect(resumed.cursor).toMatchObject({ endSeq: 7 });
});
it("recovers a rewind that skips past the loaded end", () => {
const loaded = loadAB();
const gapped = live(loaded, [rewindEvent({ seq: 9, retireFromSeq: 3 })]);
expect(conversation(gapped)).toEqual(["A", "reply A", "B", "reply B"]);
expect(gapped.sideEffects).toEqual([
{ type: "catch_up", cursor: { epoch: "epoch-1", endSeq: 4 } },
]);
});
it("keeps an A row whose late update carries a seq inside B's range", () => {
const loaded = loadAB();
const [promptA, replyA, ...rest] = loaded.tail;
const lateTool = hydrateStreamState(
[
{
event: makeToolCallTimelineEvent("call-a"),
timestamp: new Date(1002),
timelineCursor: { epoch: "epoch-1", seq: 4, anchorSeq: 2 },
},
],
{ source: "canonical" },
);
const state = { ...loaded, tail: [promptA, replyA, ...lateTool, ...rest] };
const rewound = live(state, [rewindEvent(rewindB)]);
expect(conversation(rewound)).toEqual(["A", "reply A", "tool_call"]);
});
it("keeps a tool that started before B when B's prompt is not loaded and the tool updated after B", () => {
const toolA = {
...makeToolCallTimelineEntry(2, "call-a", "completed", {
type: "read",
filePath: "/tmp/a.ts",
}),
seqEnd: 6,
sourceSeqRanges: [
{ startSeq: 2, endSeq: 2 },
{ startSeq: 6, endSeq: 6 },
],
};
const loaded = processTimelineResponse({
...baseTimelineInput,
isInitializing: true,
hasActiveInitDeferred: true,
payload: {
...baseTimelineInput.payload,
direction: "tail",
window: { minSeq: 1, maxSeq: 6, nextSeq: 7 },
startCursor: { seq: 1 },
endCursor: { seq: 6 },
entries: [makeTimelineEntry(1, "A", "user_message"), toolA],
},
});
if (!loaded.cursor) throw new Error("expected a loaded range");
const rewound = live({ tail: loaded.tail, head: loaded.head, cursor: loaded.cursor }, [
rewindEvent({ seq: 7, retireFromSeq: 3 }),
]);
expect(conversation(rewound)).toEqual(["A", "tool_call"]);
});
it("keeps C from the live overlay when the first page brings the retirement C followed", () => {
const overlay = processAgentStreamEvents({
events: [rewindEvent(rewindB), ...promptC],
currentTail: [],
currentHead: [],
currentCursor: undefined,
hasAuthoritativeBaseline: false,
});
const initialized = processTimelineResponse({
...baseTimelineInput,
isInitializing: true,
hasActiveInitDeferred: true,
currentTail: overlay.tail,
currentHead: overlay.head,
payload: {
...baseTimelineInput.payload,
direction: "tail",
window: { minSeq: 1, maxSeq: 5, nextSeq: 6 },
startCursor: { seq: 1 },
endCursor: { seq: 5 },
entries: [makeTimelineEntry(1, "A", "user_message"), makeTimelineEntry(2, "reply A")],
retirements: [rewindB],
},
});
expect(conversation(initialized)).toEqual(["A", "reply A", "C", "reply C"]);
});
});
describe("turn metrics", () => {
const metrics = [
{ label: "Model", value: "opus" },
@@ -5095,30 +4818,4 @@ describe("turn metrics", () => {
expect(repeated.tail).toBe(first.tail);
});
it("stamps turn metrics carried on a live timeline event appended by reload", () => {
const result = processAgentStreamEvents({
events: [
makeStreamReducerEvent(makeTimelineEvent("question", "user_message"), 1),
makeStreamReducerEvent(
{
type: "timeline",
provider: "claude",
item: { type: "assistant_message", text: "Appended reply." },
turnMetrics: metrics,
},
2,
),
],
currentTail: [],
currentHead: [],
currentCursor: { epoch: "epoch-1", startSeq: 0, endSeq: 0 },
hasAuthoritativeBaseline: true,
});
expect(metricsByKind([...result.tail, ...result.head])).toEqual([
{ kind: "user_message", turnMetrics: undefined },
{ kind: "assistant_message", turnMetrics: metrics },
]);
});
});
@@ -1,13 +1,7 @@
import type { AgentMetric, AgentTimelineItem } from "@getpaseo/protocol/agent-types";
import type { AgentStreamEventPayload } from "@getpaseo/protocol/messages";
import { selectAgentTimelineState, useSessionStore } from "@/stores/session-store";
import {
advanceTimelinePosition,
type AssistantMessageItem,
type StreamItem,
type TimelinePosition,
type TodoEntry,
} from "@/types/stream";
import type { AssistantMessageItem, StreamItem, TodoEntry } from "@/types/stream";
import type { TurnLivenessTransition } from "@/timeline/turn-liveness";
import { stampTimelineTurnMetrics } from "@/timeline/turn-metrics";
import {
@@ -40,7 +34,6 @@ export interface TimelineCursor {
epoch: string;
startSeq: number;
endSeq: number;
activeSegmentStartSeq?: number;
retainedRanges?: TimelineLoadedRange[];
}
@@ -79,64 +72,6 @@ interface TimelineSeqRange {
endSeq: number;
}
/** A conversation rewind took the rows anchored in `[retireFromSeq, seq)` out of the conversation. */
export interface TimelineRetirement {
seq: number;
retireFromSeq: number;
}
/** The live form of a retirement; it is sequenced with the stream events around it. */
export interface TimelineRewindEvent {
type: "rewind";
retireFromSeq: number;
}
/**
* Drops the rows a retirement took out of the conversation: those anchored in
* `[retireFromSeq, seq)`. Anchors do not move on update, so an earlier row updated after the
* rewound prompt stays, and a row that started after the retirement stays. Items without a
* timeline position are local sends the daemon has not echoed and stay.
*/
function retireRewoundStreamItems(input: {
tail: StreamItem[];
head: StreamItem[];
epoch: string;
retirement: TimelineRetirement;
}): { tail: StreamItem[]; head: StreamItem[] } {
const { tail, head, epoch, retirement } = input;
const isRetired = (item: StreamItem) => {
const position = item.timelineCursor;
return (
position?.epoch === epoch &&
position.anchorSeq >= retirement.retireFromSeq &&
position.anchorSeq < retirement.seq
);
};
const nextTail = tail.filter((item) => !isRetired(item));
const nextHead = head.filter((item) => !isRetired(item));
return {
tail: nextTail.length === tail.length ? tail : nextTail,
head: nextHead.length === head.length ? head : nextHead,
};
}
/**
* Applies a page's retirements to what this client holds. The page's own entries are already
* active. Applying a retirement twice changes nothing, since its range is bounded.
*/
function retireForPage(input: {
payload: ProcessTimelineResponseInput["payload"];
tail: StreamItem[];
head: StreamItem[];
}): { tail: StreamItem[]; head: StreamItem[] } {
const { payload } = input;
let held = { tail: input.tail, head: input.head };
for (const retirement of payload.retirements ?? []) {
held = retireRewoundStreamItems({ ...held, epoch: payload.epoch, retirement });
}
return held;
}
function mergeTimelineCoverage(
current: TimelineCursor,
added: TimelineLoadedRange,
@@ -165,9 +100,6 @@ function mergeTimelineCoverage(
epoch: current.epoch,
startSeq: contiguous.startSeq,
endSeq: contiguous.endSeq,
...(current.activeSegmentStartSeq !== undefined
? { activeSegmentStartSeq: current.activeSegmentStartSeq }
: {}),
...(retainedRanges.length > 0 ? { retainedRanges } : {}),
};
}
@@ -176,8 +108,7 @@ function timelineCursorEquals(left: TimelineCursor, right: TimelineCursor): bool
if (
left.epoch !== right.epoch ||
left.startSeq !== right.startSeq ||
left.endSeq !== right.endSeq ||
(left.activeSegmentStartSeq ?? 0) !== (right.activeSegmentStartSeq ?? 0)
left.endSeq !== right.endSeq
) {
return false;
}
@@ -221,8 +152,6 @@ export interface ProcessTimelineResponseInput {
hasNewer: boolean;
hasOlder: boolean;
mergeWindow?: boolean;
retirements?: TimelineRetirement[];
activeSegmentStartSeq?: number;
};
currentTail: StreamItem[];
currentHead: StreamItem[];
@@ -467,7 +396,7 @@ function mergeTimelineWindow(args: {
toHydratedEvents: (units: TimelineUnit[]) => Array<{
event: AgentStreamEventPayload;
timestamp: Date;
timelineCursor: TimelinePosition;
timelineCursor: { epoch: string; seq: number };
}>;
}): TimelinePathResult {
const { timelineUnits, payload, currentTail, currentHead, currentCursor, toHydratedEvents } =
@@ -831,7 +760,7 @@ function replaceLiveAssistantWithProjectedText(params: {
head: StreamItem[];
event: AgentStreamEventPayload;
timestamp: Date;
timelineCursor: TimelinePosition;
timelineCursor: { epoch: string; seq: number };
}): StreamItem[] | null {
const { head, event, timestamp, timelineCursor } = params;
if (event.type !== "timeline" || event.item.type !== "assistant_message") {
@@ -850,7 +779,7 @@ function replaceLiveAssistantWithProjectedText(params: {
...current,
text: event.item.text,
timestamp,
...advanceTimelinePosition(current.timelineCursor, timelineCursor),
timelineCursor,
};
return next;
}
@@ -900,7 +829,7 @@ function reconcileOverlappingProjectedAssistant(params: {
...(messageId !== undefined ? { messageId } : {}),
text: projectedText,
timestamp: unit.timestamp,
timelineCursor: { epoch: params.epoch, seq: unit.seqEnd, anchorSeq: unit.seq },
timelineCursor: { epoch: params.epoch, seq: unit.seqEnd },
};
const replaceMatch = (items: StreamItem[], index: number) => {
const next = [...items];
@@ -1017,8 +946,8 @@ function applyCanonicalForwardUnit(params: {
unit: TimelineUnit;
epoch: string;
}): { tail: StreamItem[]; head: StreamItem[]; acknowledgedClientMessageIds: string[] } {
const { event, timestamp, seq, seqEnd } = params.unit;
const timelineCursor: TimelinePosition = { epoch: params.epoch, seq: seqEnd, anchorSeq: seq };
const { event, timestamp, seqEnd } = params.unit;
const timelineCursor = { epoch: params.epoch, seq: seqEnd };
if (event.type === "timeline" && event.item.type === "user_message") {
const applied = applyStreamEvent({
tail: params.tail,
@@ -1217,10 +1146,10 @@ function applyAcceptedTimelinePage(input: {
});
}
const olderTail = hydrateStreamState(
acceptedUnits.map(({ event, timestamp, seq, seqEnd }) => ({
acceptedUnits.map(({ event, timestamp, seqEnd }) => ({
event,
timestamp,
timelineCursor: { epoch: payload.epoch, seq: seqEnd, anchorSeq: seq },
timelineCursor: { epoch: payload.epoch, seq: seqEnd },
})),
{
source: "canonical",
@@ -1252,12 +1181,7 @@ function applyTimelineIncrementalPath(args: {
let cursorChanged = false;
const sideEffects: TimelineReducerSideEffect[] = [];
// A forward page of retirements alone still advances the loaded end.
if (
timelineUnits.length === 0 &&
payload.direction !== "before" &&
(payload.retirements?.length ?? 0) === 0
) {
if (timelineUnits.length === 0 && payload.direction !== "before") {
return {
tail: currentTail,
head: currentHead,
@@ -1310,62 +1234,13 @@ function applyTimelineIncrementalPath(args: {
};
}
function mergeResponseActiveSegmentCursor(
cursor: TimelineCursor | null | undefined,
cursorChanged: boolean,
currentCursor: TimelineCursor | undefined,
incomingActiveSegmentStartSeq: number | undefined,
): { cursor: TimelineCursor | null | undefined; cursorChanged: boolean } {
if (!cursor) {
return { cursor, cursorChanged };
}
const prevSegment =
currentCursor?.epoch === cursor.epoch ? (currentCursor.activeSegmentStartSeq ?? 0) : 0;
const incomingSegment = incomingActiveSegmentStartSeq ?? cursor.activeSegmentStartSeq ?? 0;
const mergedSegment = Math.max(prevSegment, incomingSegment);
if (mergedSegment > 0 && cursor.activeSegmentStartSeq !== mergedSegment) {
return { cursor: { ...cursor, activeSegmentStartSeq: mergedSegment }, cursorChanged: true };
}
return { cursor, cursorChanged };
}
function advanceLiveActiveSegmentCursor(input: {
shouldApply: boolean;
event: AgentStreamEventPayload;
seq: number | undefined;
epoch: string | undefined;
nextCursor: TimelineCursor | null;
cursorChanged: boolean;
currentCursor: TimelineCursor | undefined;
}): { cursor: TimelineCursor | null; cursorChanged: boolean } {
const { shouldApply, event, seq, epoch, nextCursor, cursorChanged, currentCursor } = input;
if (
!shouldApply ||
event.type !== "timeline" ||
event.item.type !== "provider_switch" ||
typeof seq !== "number" ||
typeof epoch !== "string"
) {
return { cursor: nextCursor, cursorChanged };
}
const baseCursor =
nextCursor ??
(currentCursor?.epoch === epoch ? currentCursor : { epoch, startSeq: seq, endSeq: seq });
const nextActiveSegment = Math.max(baseCursor.activeSegmentStartSeq ?? 0, seq);
if (baseCursor.activeSegmentStartSeq !== nextActiveSegment || nextCursor === null) {
return {
cursor: { ...baseCursor, activeSegmentStartSeq: nextActiveSegment },
cursorChanged: true,
};
}
return { cursor: nextCursor, cursorChanged };
}
export function processTimelineResponse(
input: ProcessTimelineResponseInput,
): ProcessTimelineResponseOutput {
const {
payload,
currentTail,
currentHead,
currentCursor,
isInitializing,
hasActiveInitDeferred,
@@ -1379,8 +1254,8 @@ export function processTimelineResponse(
if (payload.error) {
return {
commit: "apply",
tail: input.currentTail,
head: input.currentHead,
tail: currentTail,
head: currentHead,
cursor: currentCursor,
cursorChanged: false,
older: "unchanged",
@@ -1392,13 +1267,6 @@ export function processTimelineResponse(
};
}
// Entries are already free of retired rows; the retirements apply to what this client holds.
const { tail: currentTail, head: currentHead } = retireForPage({
payload,
tail: input.currentTail,
head: input.currentHead,
});
// ------------------------------------------------------------------
// Convert entries to timeline units
// ------------------------------------------------------------------
@@ -1424,12 +1292,12 @@ export function processTimelineResponse(
): Array<{
event: AgentStreamEventPayload;
timestamp: Date;
timelineCursor: TimelinePosition;
timelineCursor: { epoch: string; seq: number };
}> =>
units.map(({ event, timestamp, seq, seqEnd }) => ({
units.map(({ event, timestamp, seqEnd }) => ({
event,
timestamp,
timelineCursor: { epoch: payload.epoch, seq: seqEnd, anchorSeq: seq },
timelineCursor: { epoch: payload.epoch, seq: seqEnd },
}));
// ------------------------------------------------------------------
@@ -1516,12 +1384,8 @@ export function processTimelineResponse(
const nextTail = stampTimelineTurnMetrics(timelineResult.tail, payload.epoch, pageEntries);
const nextHead = stampTimelineTurnMetrics(timelineResult.head, payload.epoch, pageEntries);
const { cursor: nextCursor, cursorChanged } = mergeResponseActiveSegmentCursor(
timelineResult.cursor,
timelineResult.cursorChanged,
currentCursor,
payload.activeSegmentStartSeq,
);
const nextCursor = timelineResult.cursor;
const cursorChanged = timelineResult.cursorChanged;
sideEffects.push(...timelineResult.sideEffects);
// ------------------------------------------------------------------
@@ -1568,7 +1432,7 @@ export function processTimelineResponse(
// ---------------------------------------------------------------------------
export interface ProcessAgentStreamEventInput {
event: AgentStreamEventPayload | TimelineRewindEvent;
event: AgentStreamEventPayload;
seq: number | undefined;
epoch: string | undefined;
currentTail: StreamItem[];
@@ -1591,7 +1455,7 @@ export interface ProcessAgentStreamEventOutput {
}
export interface AgentStreamReducerEvent {
event: AgentStreamEventPayload | TimelineRewindEvent;
event: AgentStreamEventPayload;
seq: number | undefined;
epoch: string | undefined;
timestamp: Date;
@@ -1714,70 +1578,11 @@ function processTimelineSequencingGate(input: {
};
}
/**
* Applies a live rewind in sequence with the stream. One that does not follow the loaded end is
* stale (already applied, or older than a page this client took) or leaves a gap to catch up.
*/
function processTimelineRewind(
input: ProcessAgentStreamEventInput & { event: TimelineRewindEvent },
): ProcessAgentStreamEventOutput {
const { event, seq, epoch, currentTail, currentHead, currentCursor } = input;
const unchanged: ProcessAgentStreamEventOutput = {
tail: currentTail,
head: currentHead,
changedTail: false,
changedHead: false,
cursor: null,
cursorChanged: false,
acknowledgedClientMessageIds: [],
sideEffects: [],
};
if (seq === undefined || epoch === undefined) return unchanged;
const decision =
input.hasAuthoritativeBaseline === false
? "overlay"
: classifySessionTimelineSeq({
cursor: currentCursor
? { epoch: currentCursor.epoch, endSeq: currentCursor.endSeq }
: null,
epoch,
seq,
});
if (decision === "gap" && currentCursor) {
return {
...unchanged,
sideEffects: [
{ type: "catch_up", cursor: { epoch: currentCursor.epoch, endSeq: currentCursor.endSeq } },
],
};
}
if (decision !== "accept" && decision !== "init" && decision !== "overlay") return unchanged;
const retired = retireRewoundStreamItems({
tail: currentTail,
head: currentHead,
epoch,
retirement: { seq, retireFromSeq: event.retireFromSeq },
});
let cursor: TimelineCursor | null = null;
if (decision === "accept" && currentCursor) cursor = { ...currentCursor, endSeq: seq };
if (decision === "init") cursor = { epoch, startSeq: seq, endSeq: seq };
return {
...unchanged,
tail: retired.tail,
head: retired.head,
changedTail: retired.tail !== currentTail,
changedHead: retired.head !== currentHead,
cursor,
cursorChanged: cursor !== null,
};
}
export function processAgentStreamEvent(
input: ProcessAgentStreamEventInput,
): ProcessAgentStreamEventOutput {
const event = input.event;
if (event.type === "rewind") return processTimelineRewind({ ...input, event });
const {
event,
seq,
epoch,
currentTail,
@@ -1796,7 +1601,7 @@ export function processAgentStreamEvent(
});
const timelineCursor =
event.type === "timeline" && seq !== undefined && epoch !== undefined
? { epoch, seq, anchorSeq: seq }
? { epoch, seq }
: undefined;
// ------------------------------------------------------------------
// Apply stream event to tail/head
@@ -1845,23 +1650,14 @@ export function processAgentStreamEvent(
});
}
const { tail, head, changedTail, changedHead } = streamResult;
const { cursor: nextTimelineCursor, cursorChanged } = advanceLiveActiveSegmentCursor({
shouldApply: sequencing.shouldApplyStreamEvent,
event,
seq,
epoch,
nextCursor: sequencing.nextTimelineCursor,
cursorChanged: sequencing.cursorChanged,
currentCursor,
});
return {
tail,
head,
changedTail,
changedHead,
cursor: nextTimelineCursor,
cursorChanged,
cursor: sequencing.nextTimelineCursor,
cursorChanged: sequencing.cursorChanged,
acknowledgedClientMessageIds: streamResult.acknowledgedClientMessageIds ?? [],
...(sequencing.shouldApplyStreamEvent && event.type === "timeline" && event.item.type === "todo"
? { taskSnapshot: event.item.items }
@@ -2119,10 +1915,6 @@ export function createSessionAgentStreamReducerQueue(
};
},
commit: (agentId, result, events) => {
for (const { event, seq, epoch } of events) {
if (event.type !== "rewind" || seq === undefined || epoch === undefined) continue;
useSessionStore.getState().recordAgentTimelineRewind(serverId, agentId, { epoch, seq });
}
if (
result.changedTail ||
result.changedHead ||
@@ -244,13 +244,6 @@ function commitProcessedTimeline(input: {
const agentId = payload.agentId;
const store = useSessionStore.getState();
if (result.commit !== "discard") {
const latestRewindSeq = Math.max(...(payload.retirements ?? []).map(({ seq }) => seq));
if (Number.isFinite(latestRewindSeq)) {
store.recordAgentTimelineRewind(serverId, agentId, {
epoch: payload.epoch,
seq: latestRewindSeq,
});
}
store.applyAgentTimelineResponseState(serverId, agentId, {
items: result.tail,
head: result.head,
@@ -484,15 +477,8 @@ export type ViewedTimelineOwnerPorts = Omit<
| "applyCurrentTimeline"
>;
/**
* `stale`: the page was served before a rewind this client already applied, so it can hold rows
* that rewind retired. Nothing was applied; request the page again.
* `discarded`: the archived chat was released while the page was in flight. Nothing was applied.
*/
export type TimelineResponseOutcome = "applied" | "stale" | "discarded";
export interface ViewedTimelineOwner extends ViewedTimelineSync {
applyTimelineResponse(payload: TimelineResponsePayload): TimelineResponseOutcome;
applyTimelineResponse(payload: TimelineResponsePayload): void;
/**
* Accepts one live stream event. Content is coalesced to the next frame; a turn boundary
* commits the turn's queued content before its liveness changes, so the view never shows
@@ -502,37 +488,6 @@ export interface ViewedTimelineOwner extends ViewedTimelineSync {
flushStreamAgent(agentId: string): void;
}
/**
* The latest retirement each chat has seen, live or on a page. Tail, older and prompt-jump pages
* are served from active rows at one moment; one served before that retirement can still hold the
* rows it retired, and has no retirement to drop them with. Forward pages are sequenced against
* the loaded end instead, so they are never stale here.
*/
function createRetirementHighWater() {
const latest = new Map<string, { epoch: string; seq: number }>();
function note(agentId: string, retirement: { epoch: string; seq: number }): void {
const current = latest.get(agentId);
if (current?.epoch === retirement.epoch && current.seq >= retirement.seq) return;
latest.set(agentId, retirement);
}
return {
note,
notePage(payload: TimelineResponsePayload): void {
for (const retirement of payload.retirements ?? []) {
note(payload.agentId, { epoch: payload.epoch, seq: retirement.seq });
}
},
servedBefore(payload: TimelineResponsePayload): boolean {
const known = latest.get(payload.agentId);
return (
payload.direction !== "after" &&
known?.epoch === payload.epoch &&
payload.window.maxSeq < known.seq
);
},
};
}
export function createViewedTimelineOwner(input: {
serverId: string;
replica: TimelineReplica;
@@ -547,7 +502,6 @@ export function createViewedTimelineOwner(input: {
// Active chats stay resident while hidden so switching back needs no fetch. An archived
// chat is resident only while it is shown, as when it is open from History.
const isResident = (agentId: string) => sync.isVisible(agentId) || !isArchived(agentId);
const retirements = createRetirementHighWater();
const sync = createViewedTimelineSync({
...input.ports,
isArchived,
@@ -623,9 +577,7 @@ export function createViewedTimelineOwner(input: {
},
applyTimelineResponse(receivedPayload) {
// A read that answers after its archived chat was released must not bring it back.
if (!isResident(receivedPayload.agentId)) return "discarded";
if (retirements.servedBefore(receivedPayload)) return "stale";
retirements.notePage(receivedPayload);
if (!isResident(receivedPayload.agentId)) return;
const payload = consumeForcedTimelineTailReplacement(receivedPayload, forcedTailReplacements);
const accepted = applyAuthoritativeTimelineResponse({
serverId: input.serverId,
@@ -635,13 +587,9 @@ export function createViewedTimelineOwner(input: {
drainQueuedAgentMessage: input.drainQueuedAgentMessage,
});
if (accepted) input.replica.timelineUpdated(payload.agentId);
return "applied";
},
applyStreamEvent(agentId, event) {
if (!isResident(agentId)) return;
if (event.event.type === "rewind" && event.epoch !== undefined && event.seq !== undefined) {
retirements.note(agentId, { epoch: event.epoch, seq: event.seq });
}
streamQueue.enqueue(agentId, event);
const turnLiveness = deriveAgentStreamTurnLiveness([event]);
if (turnLiveness.length === 0) return;
+3 -7
View File
@@ -1009,7 +1009,7 @@ describe("stream reducer canonical tool calls", () => {
});
it("keeps the timeline position on the whole assistant message", () => {
const timelineCursor = { epoch: "epoch-1", seq: 42, anchorSeq: 42 };
const timelineCursor = { epoch: "epoch-1", seq: 42 };
const result = applyStreamEvent({
tail: [],
head: [],
@@ -1890,7 +1890,7 @@ describe("turn lifecycle events", () => {
new Date("2025-01-01T15:03:11Z"),
{
source: "canonical",
timelineCursor: { epoch: "epoch-1", seq: 42, anchorSeq: 42 },
timelineCursor: { epoch: "epoch-1", seq: 42 },
},
);
@@ -1902,11 +1902,7 @@ describe("turn lifecycle events", () => {
assert.strictEqual(userMessage.messageId, "provider-owned-canonical");
assert.strictEqual(userMessage.text, "Analyze this");
assert.strictEqual(userMessage.timestamp.getTime(), submittedTimestamp.getTime());
assert.deepStrictEqual(userMessage.timelineCursor, {
epoch: "epoch-1",
seq: 42,
anchorSeq: 42,
});
assert.deepStrictEqual(userMessage.timelineCursor, { epoch: "epoch-1", seq: 42 });
assert.deepStrictEqual(userMessage.images, [image]);
assert.deepStrictEqual(userMessage.attachments, [attachment]);
});
+21 -241
View File
@@ -4,7 +4,6 @@ import type {
AgentProvider,
AgentTimelineItem,
JsonValue,
ProviderSwitchContextSummary,
ToolCallDetail,
} from "@getpaseo/protocol/agent-types";
import { timelineItemIdentity } from "@getpaseo/protocol/timeline-identity";
@@ -90,47 +89,9 @@ export type StreamItem =
| TodoListItem
| NotificationItem
| CompactionItem
| ProviderSwitchItem
| PluginTimelineStreamItem
| TurnSummaryItem;
export interface ProviderSwitchItem {
kind: "provider_switch";
id: string;
/** Present only while optimistically shown for an in-flight provider switch submission. */
pendingClientMessageId?: string;
timelineCursor?: TimelinePosition;
turnId?: string;
timestamp: Date;
fromProvider: AgentProvider;
toProvider: AgentProvider;
fromModel?: string | null;
toModel?: string | null;
fromSessionId?: string | null;
toSessionId?: string | null;
context?: ProviderSwitchContextSummary;
}
export function createPendingProviderSwitchItem(params: {
clientMessageId: string;
fromProvider: AgentProvider;
toProvider: AgentProvider;
fromModel?: string | null;
toModel?: string | null;
timestamp: Date;
}): ProviderSwitchItem {
return {
kind: "provider_switch",
id: `provider_switch:pending:${params.clientMessageId}`,
pendingClientMessageId: params.clientMessageId,
timestamp: params.timestamp,
fromProvider: params.fromProvider,
toProvider: params.toProvider,
...(params.fromModel !== undefined ? { fromModel: params.fromModel } : {}),
...(params.toModel !== undefined ? { toModel: params.toModel } : {}),
};
}
export type UserMessageImageAttachment = AttachmentMetadata;
export interface UserMessageItem {
@@ -193,7 +154,6 @@ export function appendSubmittedUserMessage(input: {
tail: StreamItem[];
head: StreamItem[];
message: UserMessageItem;
providerSwitch?: ProviderSwitchItem;
}): { tail: StreamItem[]; head: StreamItem[] } {
const clientMessageId = input.message.clientMessageId;
if (!clientMessageId) {
@@ -205,12 +165,9 @@ export function appendSubmittedUserMessage(input: {
if (alreadyExists) {
throw new Error(`Submitted user message already exists: ${clientMessageId}`);
}
const appended: StreamItem[] = input.providerSwitch
? [input.providerSwitch, input.message]
: [input.message];
return input.head.length > 0
? { tail: input.tail, head: [...input.head, ...appended] }
: { tail: [...input.tail, ...appended], head: input.head };
? { tail: input.tail, head: [...input.head, input.message] }
: { tail: [...input.tail, input.message], head: input.head };
}
export function removeSubmittedUserMessage(input: {
@@ -219,20 +176,12 @@ export function removeSubmittedUserMessage(input: {
clientMessageId: string;
}): { tail: StreamItem[]; head: StreamItem[] } {
const remove = (items: StreamItem[]) => {
const next = items.filter((item) => {
if (
item.kind === "provider_switch" &&
item.pendingClientMessageId === input.clientMessageId &&
item.timelineCursor === undefined
) {
return false;
}
return (
const next = items.filter(
(item) =>
item.kind !== "user_message" ||
item.clientMessageId !== input.clientMessageId ||
!isUnreconciledLocalUserMessage(item)
);
});
!isUnreconciledLocalUserMessage(item),
);
return next.length === items.length ? items : next;
};
return { tail: remove(input.tail), head: remove(input.head) };
@@ -317,7 +266,7 @@ function produceUserMessage(
...presentation,
clientMessageId: incoming.clientMessageId ?? existing.clientMessageId,
messageId: incoming.messageId ?? existing.messageId,
...advanceTimelinePosition(existing.timelineCursor, incoming.timelineCursor),
timelineCursor: incoming.timelineCursor ?? existing.timelineCursor,
});
if (
existing.id === merged.id &&
@@ -533,7 +482,7 @@ function mergeRetainedLifecycleItem(tail: StreamItem[], retained: StreamItem): S
const next = [...tail];
next[tailIndex] = {
...existing,
...advanceTimelinePosition(existing.timelineCursor, retained.timelineCursor),
timelineCursor: retained.timelineCursor,
timestamp: retained.timestamp,
items: retained.items,
};
@@ -550,7 +499,7 @@ function mergeRetainedLifecycleItem(tail: StreamItem[], retained: StreamItem): S
const next = [...tail];
next[tailIndex] = {
...existing,
...advanceTimelinePosition(existing.timelineCursor, retained.timelineCursor),
timelineCursor: retained.timelineCursor,
status: "completed",
trigger: retained.trigger ?? existing.trigger,
preTokens: retained.preTokens ?? existing.preTokens,
@@ -570,10 +519,7 @@ function replaceTimelineIdentityItem(
const existing = items[index];
if (index < 0 || !existing || existing.kind !== "plugin") return null;
const next = [...items];
next[index] = {
...retained,
...advanceTimelinePosition(existing.timelineCursor, retained.timelineCursor),
};
next[index] = retained;
return next;
}
@@ -664,11 +610,7 @@ function preserveReplacementHead(
: `${tailAssistant.text}${liveAssistant.text}`;
const head = [
...unreconciledHead.slice(0, liveAssistantIndex),
{
...liveAssistant,
text,
...advanceTimelinePosition(tailAssistant.timelineCursor, liveAssistant.timelineCursor),
},
{ ...liveAssistant, text },
...unreconciledHead.slice(liveAssistantIndex + 1),
];
return {
@@ -683,13 +625,7 @@ function preserveReplacementHead(
const head = [
...unreconciledHead.slice(0, liveAssistantIndex),
{
...liveAssistant,
text: tailAssistant.text,
...(liveAssistant.timelineCursor
? advanceTimelinePosition(tailAssistant.timelineCursor, liveAssistant.timelineCursor)
: {}),
},
{ ...liveAssistant, text: tailAssistant.text },
...unreconciledHead.slice(liveAssistantIndex + 1),
];
return {
@@ -699,50 +635,10 @@ function preserveReplacementHead(
};
}
function collectPendingProviderSwitches(
tail: readonly StreamItem[],
head: readonly StreamItem[],
): Map<string, ProviderSwitchItem> {
const byClientId = new Map<string, ProviderSwitchItem>();
for (const item of [...tail, ...head]) {
if (
item.kind === "provider_switch" &&
item.pendingClientMessageId !== undefined &&
item.timelineCursor === undefined
) {
byClientId.set(item.pendingClientMessageId, item);
}
}
return byClientId;
}
function appendPendingProviderSwitchIfUncommitted(
nextTail: StreamItem[],
local: UserMessageItem,
pendingSwitchesByClientId: ReadonlyMap<string, ProviderSwitchItem>,
): void {
const pendingSwitch = local.clientMessageId
? pendingSwitchesByClientId.get(local.clientMessageId)
: undefined;
if (!pendingSwitch) return;
const lastCanonical = nextTail.at(-1);
const alreadyCommittedAtTail =
lastCanonical?.kind === "provider_switch" &&
lastCanonical.fromProvider === pendingSwitch.fromProvider &&
lastCanonical.toProvider === pendingSwitch.toProvider;
if (!alreadyCommittedAtTail) {
nextTail.push(pendingSwitch);
}
}
export function replaceWithCanonicalStream(
input: CanonicalStreamReplacementInput,
): CanonicalStreamReplacementResult {
const sendingClientMessageIds = new Set(input.sendingClientMessageIds);
const pendingSwitchesByClientId = collectPendingProviderSwitches(
input.previousTail,
input.previousHead,
);
let unmatchedTailMessages = input.previousTail.filter(
(item): item is UserMessageItem =>
item.kind === "user_message" && item.clientMessageId !== undefined,
@@ -789,7 +685,6 @@ export function replaceWithCanonicalStream(
? isUnreconciledLocalUserMessage(local)
: local.clientMessageId !== undefined && sendingClientMessageIds.has(local.clientMessageId);
if (preserveLocal) {
appendPendingProviderSwitchIfUncommitted(nextTail, local, pendingSwitchesByClientId);
nextTail.push(local);
} else if (
input.preserveContinuity &&
@@ -829,27 +724,7 @@ export interface AssistantMessageItem {
export interface TimelinePosition {
epoch: string;
/** The latest seq that changed this row. */
seq: number;
/** The seq the row started at. Updates never move it; rewinds retire rows by it. */
anchorSeq: number;
}
/**
* The position of a row after an update: it moves to the update's seq and stays anchored where it
* started. Without an incoming position the row keeps the one it has.
*/
export function advanceTimelinePosition(
existing: TimelinePosition | undefined,
incoming: TimelinePosition | undefined,
): { timelineCursor?: TimelinePosition } {
if (!incoming) return existing ? { timelineCursor: existing } : {};
if (!existing || existing.epoch !== incoming.epoch) return { timelineCursor: incoming };
const anchorSeq = Math.min(existing.anchorSeq, incoming.anchorSeq);
if (existing.seq === incoming.seq && existing.anchorSeq === anchorSeq) {
return { timelineCursor: existing };
}
return { timelineCursor: { ...incoming, anchorSeq } };
}
export type ThoughtStatus = "loading" | "ready";
@@ -1108,7 +983,7 @@ function appendAssistantMessage(
...last,
text: `${last.text}${chunk}`,
timestamp,
...advanceTimelinePosition(last.timelineCursor, timelineCursor),
...(timelineCursor ? { timelineCursor } : {}),
};
return [...state.slice(0, -1), updated];
}
@@ -1126,7 +1001,7 @@ function appendAssistantMessage(
...secondLast,
text: `${secondLast.text}${chunk}`,
timestamp,
...advanceTimelinePosition(secondLast.timelineCursor, timelineCursor),
...(timelineCursor ? { timelineCursor } : {}),
};
return [...state.slice(0, -2), updated, last];
}
@@ -1164,7 +1039,7 @@ function appendThought(
if (last && last.kind === "thought" && last.turnId === turnId) {
const updated: ThoughtItem = {
...last,
...advanceTimelinePosition(last.timelineCursor, timelineCursor),
...(timelineCursor ? { timelineCursor } : {}),
text: `${last.text}${chunk}`,
timestamp,
status: "loading",
@@ -1344,7 +1219,7 @@ export function mergeAgentToolCallItem(
return {
...existing,
...advanceTimelinePosition(existing.timelineCursor, timelineCursor),
...(timelineCursor ? { timelineCursor } : {}),
timestamp,
payload: {
source: "agent",
@@ -1450,11 +1325,7 @@ function appendPluginTimelineItem(
const existing = state[existingIndex];
if (!existing || existing.kind !== "plugin") return state;
const next = [...state];
next[existingIndex] = {
...nextItem,
id: existing.id,
...advanceTimelinePosition(existing.timelineCursor, timelineCursor),
};
next[existingIndex] = { ...nextItem, id: existing.id };
return next;
}
@@ -1485,7 +1356,7 @@ function appendTodoList(
const next = [...state];
next[previousIndex] = {
...previous,
...advanceTimelinePosition(previous.timelineCursor, timelineCursor),
...(timelineCursor ? { timelineCursor } : {}),
items: normalizedItems,
timestamp,
};
@@ -1504,7 +1375,7 @@ function appendTodoList(
const next = [...state];
next[next.length - 1] = {
...lastItem,
...advanceTimelinePosition(lastItem.timelineCursor, timelineCursor),
...(timelineCursor ? { timelineCursor } : {}),
items: normalizedItems,
activity: { type: "created", count: normalizedItems.length },
timestamp,
@@ -1649,7 +1520,7 @@ function reduceTimelineCompaction(
if (loadingIdx >= 0 && existing && existing.kind === "compaction") {
const updated: CompactionItem = {
...existing,
...advanceTimelinePosition(existing.timelineCursor, timelineCursor),
...(timelineCursor ? { timelineCursor } : {}),
status: "completed",
trigger: item.trigger ?? existing.trigger,
preTokens: item.preTokens ?? existing.preTokens,
@@ -1672,90 +1543,6 @@ function reduceTimelineCompaction(
return [...state, compaction];
}
function reduceTimelineProviderSwitch(
state: StreamItem[],
item: Extract<AgentTimelineItem, { type: "provider_switch" }>,
timestamp: Date,
timelineCursor?: TimelinePosition,
): StreamItem[] {
const switchId =
timelineCursor !== undefined
? `provider_switch:${timelineCursor.epoch}:${timelineCursor.anchorSeq}`
: createUniqueTimelineId(
state,
"provider_switch",
`${item.fromProvider}->${item.toProvider}`,
timestamp,
);
const alreadyPresent = state.some(
(existing) =>
existing.kind === "provider_switch" &&
(existing.id === switchId ||
(timelineCursor !== undefined &&
existing.timelineCursor !== undefined &&
existing.timelineCursor.epoch === timelineCursor.epoch &&
existing.timelineCursor.anchorSeq === timelineCursor.anchorSeq)),
);
if (alreadyPresent) {
return state;
}
// Reconcile an optimistic pending marker in place, keeping its stable id so the mounted
// row never unmounts, remounts, or shifts position when the daemon commits the switch.
const pendingIndex = state.findIndex(
(existing) =>
existing.kind === "provider_switch" &&
existing.pendingClientMessageId !== undefined &&
existing.timelineCursor === undefined &&
existing.fromProvider === item.fromProvider &&
existing.toProvider === item.toProvider,
);
if (pendingIndex >= 0) {
const existing = state[pendingIndex] as ProviderSwitchItem;
const upgraded: ProviderSwitchItem = {
kind: "provider_switch",
id: existing.id,
...(timelineCursor ? { timelineCursor } : {}),
timestamp,
fromProvider: item.fromProvider,
toProvider: item.toProvider,
...(item.fromModel !== undefined ? { fromModel: item.fromModel } : {}),
...(item.toModel !== undefined ? { toModel: item.toModel } : {}),
...(item.fromSessionId !== undefined ? { fromSessionId: item.fromSessionId } : {}),
...(item.toSessionId !== undefined ? { toSessionId: item.toSessionId } : {}),
context: item.context,
};
return [...state.slice(0, pendingIndex), upgraded, ...state.slice(pendingIndex + 1)];
}
const marker: ProviderSwitchItem = {
kind: "provider_switch",
id: switchId,
...(timelineCursor ? { timelineCursor } : {}),
timestamp,
fromProvider: item.fromProvider,
toProvider: item.toProvider,
...(item.fromModel !== undefined ? { fromModel: item.fromModel } : {}),
...(item.toModel !== undefined ? { toModel: item.toModel } : {}),
...(item.fromSessionId !== undefined ? { fromSessionId: item.fromSessionId } : {}),
...(item.toSessionId !== undefined ? { toSessionId: item.toSessionId } : {}),
context: item.context,
};
// Defense in depth: if an unanchored optimistic user message is already at the tail,
// place the committed switch marker directly above it so the marker never paints below it.
let insertAt = state.length;
while (insertAt > 0) {
const candidate = state[insertAt - 1];
if (candidate?.kind === "user_message" && isUnreconciledLocalUserMessage(candidate)) {
insertAt -= 1;
continue;
}
break;
}
return [...state.slice(0, insertAt), marker, ...state.slice(insertAt)];
}
function reduceTimelineEvent(
state: StreamItem[],
event: Extract<AgentStreamEventPayload, { type: "timeline" }>,
@@ -1827,8 +1614,6 @@ function reduceTimelineEvent(
}
case "compaction":
return reduceTimelineCompaction(state, item, timestamp, timelineCursor);
case "provider_switch":
return reduceTimelineProviderSwitch(state, item, timestamp, timelineCursor);
case "plugin":
return appendPluginTimelineItem(state, item, timestamp, timelineCursor);
default:
@@ -1860,10 +1645,7 @@ export function reduceStreamUpdate(
),
event,
);
const stamped = event.turnMetrics?.length
? stampCompletedTurnMetrics(updated, event.turnMetrics, event.turnId)
: updated;
return event.item.type === "reasoning" ? stamped : finalizeActiveThoughts(stamped);
return event.item.type === "reasoning" ? updated : finalizeActiveThoughts(updated);
}
case "turn_completed":
return stampCompletedTurnMetrics(finalizeActiveThoughts(state), event.metrics, event.turnId);
@@ -1994,8 +1776,6 @@ function getEventItemKind(event: AgentStreamEventPayload): StreamItem["kind"] |
return "notification";
case "plugin":
return "plugin";
case "provider_switch":
return "provider_switch";
default:
return null;
}
@@ -9,6 +9,17 @@ describe("tokenizeToLines", () => {
expect(lines?.[0].some((token) => token.style === "keyword")).toBe(true);
});
it.each(["diff", "patch"])("tokenizes %s fences with diff roles", (lang) => {
const lines = tokenizeToLines("--- a/f.ts\n+++ b/f.ts\n@@ -1 +1 @@\n-old\n+new", lang);
expect(lines).toEqual([
[{ text: "--- a/f.ts", style: "diffDeletion" }],
[{ text: "+++ b/f.ts", style: "diffAddition" }],
[{ text: "@@ -1 +1 @@", style: "meta" }],
[{ text: "-old", style: "diffDeletion" }],
[{ text: "+new", style: "diffAddition" }],
]);
});
it("returns null when there is no filename", () => {
expect(tokenizeToLines("whatever", null)).toBeNull();
});
@@ -16,7 +16,6 @@ export const ArrowDownUp = StubIcon;
export const ArrowLeft = StubIcon;
export const ArrowLeftToLine = StubIcon;
export const ArrowRight = StubIcon;
export const ArrowRightLeft = StubIcon;
export const ArrowUp = StubIcon;
export const ArrowUpRight = StubIcon;
export const AudioLines = StubIcon;
-3
View File
@@ -47,8 +47,5 @@
"typescript": "^5.2.2",
"vitest": "^4.1.6",
"zx": "^8.8.5"
},
"engines": {
"node": ">=22.16.0"
}
}
@@ -146,10 +146,6 @@ export async function runAttachCommand(
const unsubscribe = client.subscribeAgentTimeline(resolvedId, (message) => {
if (message.type === "agent.timeline.replacement") {
console.log("\n[Timeline replaced; earlier output is no longer current]");
} else if (message.type === "agent.timeline.rewind") {
console.log(
"\n[Conversation rewound; output since the rewound message is no longer current]",
);
} else if (message.type === "agent.timeline.subscription_restored") {
console.log("\n[Reconnected; live output resumed. Events may have been missed.]");
} else if (message.type === "agent.timeline.error") {
+1 -5
View File
@@ -408,6 +408,7 @@ async function runFollowMode({
} catch (error) {
console.warn("Warning: failed to fetch existing timeline", error);
}
// Apply filter to existing items
if (options.filter) {
existingItems = existingItems.filter((item) => matchesFilter(item, options.filter));
@@ -438,11 +439,6 @@ async function runFollowMode({
notice("\n[Timeline replaced; earlier output is no longer current]");
return;
}
if (message.type === "agent.timeline.rewind") {
writer.end();
notice("\n[Conversation rewound; output since the rewound message is no longer current]");
return;
}
if (message.type === "agent.timeline.error") {
writer.end();
@@ -210,12 +210,7 @@ try {
console.log("Foreground SIGINT reached the supervisor. The worker and ACP processes exited.");
daemon = await startSupervisor();
// The stored timeline is served without reopening the agent.
const storedIdle = (await daemon.client.fetchAgentTimeline(idle.id)).agent;
assert.equal(storedIdle?.status, "closed");
assert.equal(storedIdle?.requiresAttention, false);
await daemon.client.refreshAgent(idle.id);
const restoredIdle = (await daemon.client.fetchAgent(idle.id))?.agent;
const restoredIdle = (await daemon.client.fetchAgentTimeline(idle.id)).agent;
assert.equal(restoredIdle?.status, "idle");
assert.equal(restoredIdle?.requiresAttention, false);
await waitFor(async () => {
-31
View File
@@ -211,37 +211,6 @@ test("SDK subscribers receive timeline replacement instead of silently losing hi
}
});
test("SDK subscribers receive a conversation rewind as a retired range", async () => {
const { createPaseoApi } = await import("./index");
const h = connection();
const received: unknown[] = [];
try {
const ready = h.client.connect();
h.open();
await ready;
const off = createPaseoApi(h.client)
.agents.ref("agent")
.timeline.subscribe((event) => received.push(event));
await off.ready;
h.receive({
type: "agent.timeline.rewind",
payload: {
agentId: "agent",
epoch: "epoch-1",
seq: 12,
retireFromSeq: 7,
subscriptionId: off.subscriptionId,
},
});
expect(received).toEqual([
{ agentId: "agent", event: { type: "rewind", epoch: "epoch-1", seq: 12, retireFromSeq: 7 } },
]);
off();
} finally {
await h.client.close();
}
});
test("local listeners create no demand before or after reconnect", async () => {
const h = connection();
try {
-2
View File
@@ -141,10 +141,8 @@ export const DEFAULT_CLIENT_CAPABILITIES = {
[CLIENT_CAPS.compactProviderSnapshots]: true,
[CLIENT_CAPS.providerSnapshotReferences]: true,
[CLIENT_CAPS.timelineReplacementInvalidation]: true,
[CLIENT_CAPS.timelineRewindOperations]: true,
[CLIENT_CAPS.timelineNotifications]: true,
[CLIENT_CAPS.pluginTimelineItems]: true,
[CLIENT_CAPS.timelineProviderSwitches]: true,
[CLIENT_CAPS.workspaceSetupBlocked]: true,
[CLIENT_CAPS.workspaceSetupObservation]: true,
[CLIENT_CAPS.pluginBinaryPayloads]: true,
+1 -3
View File
@@ -246,9 +246,7 @@ export class LegacySubscriptions {
);
case "agent.timeline.set_subscription.request":
return (
(message.type === "agent_stream" ||
message.type === "agent.timeline.replacement" ||
message.type === "agent.timeline.rewind") &&
(message.type === "agent_stream" || message.type === "agent.timeline.replacement") &&
(query.agentIds as string[]).includes(message.payload.agentId)
);
case "session.events.set_subscription.request":
@@ -1132,7 +1132,6 @@ test("advertises client capabilities in hello", async () => {
all_providers: true,
selective_agent_timeline: true,
timeline_replacement_invalidation: true,
timeline_rewind_operations: true,
provider_snapshot_references: true,
explicit_event_subscriptions: true,
owned_subscriptions: true,
@@ -1146,7 +1145,6 @@ test("advertises client capabilities in hello", async () => {
terminal_reflowable_snapshot: true,
terminal_chunked_replay: true,
timeline_notifications: true,
timeline_provider_switches: true,
plugin_timeline_items: true,
plugin_binary_payloads: true,
workspace_setup_blocked: true,
+5 -112
View File
@@ -130,8 +130,6 @@ import type {
DaemonConfigReloadResponse,
DiagnosticsResponse,
AgentRewindResponseMessage,
AgentProviderSwitchRequest,
AgentProviderSwitchResponseMessage,
ListTerminalsResponse,
CreateTerminalResponse,
SubscribeTerminalResponse,
@@ -514,28 +512,6 @@ export interface SendMessageOptions {
attachments?: SendAgentMessageRequest["attachments"];
}
export interface SwitchAgentProviderOptions {
provider: AgentProvider;
model?: string | null;
modeId?: string | null;
thinkingOptionId?: string | null;
providerOptions?: Record<string, unknown>;
text: string;
messageId?: string;
images?: Array<{ data: string; mimeType: string }>;
attachments?: AgentProviderSwitchRequest["attachments"];
}
export class AgentProviderSwitchError extends Error {
constructor(
message: string,
readonly agent?: AgentSnapshotPayload,
) {
super(message);
this.name = "AgentProviderSwitchError";
}
}
export interface AgentAttentionRequiredNotification {
agentId: string;
reason: "finished" | "error" | "permission";
@@ -4368,56 +4344,6 @@ export class DaemonClient {
};
}
async switchAgentProvider(
agentId: string,
options: SwitchAgentProviderOptions,
): Promise<{ agent?: AgentSnapshotPayload }> {
if (this.lastServerInfoMessage?.features?.providerSwitching !== true) {
throw new Error("Update the Paseo host to switch providers in an existing chat.");
}
const requestId = this.createRequestId();
const messageId = options.messageId ?? crypto.randomUUID();
const message = SessionInboundMessageSchema.parse({
type: "agent.provider.switch.request",
requestId,
agentId,
provider: options.provider,
...(options.model !== undefined ? { model: options.model } : {}),
...(options.modeId !== undefined ? { modeId: options.modeId } : {}),
...(options.thinkingOptionId !== undefined
? { thinkingOptionId: options.thinkingOptionId }
: {}),
...(options.providerOptions !== undefined
? { providerOptions: options.providerOptions }
: {}),
text: options.text,
messageId,
images: options.images,
attachments: options.attachments,
});
const payload: AgentProviderSwitchResponseMessage["payload"] = await this.sendRequest({
requestId,
message,
options: { skipQueue: true },
select: (msg) => {
if (msg.type !== "agent.provider.switch.response") {
return null;
}
if (msg.payload.requestId !== requestId) {
return null;
}
return msg.payload;
},
});
if (!payload.accepted) {
throw new AgentProviderSwitchError(
payload.error ?? "switchAgentProvider rejected",
payload.agent,
);
}
return payload.agent ? { agent: payload.agent } : {};
}
/** The behavior to put on the wire for this host. */
private activeTurnBehaviorForHost(
options: SendMessageOptions,
@@ -4506,29 +4432,12 @@ export class DaemonClient {
}
}
private expectedProviderWireField(options?: {
expectedProvider?: AgentProvider;
}): { expectedProvider: AgentProvider } | Record<string, never> {
if (
options?.expectedProvider &&
this.lastServerInfoMessage?.features?.providerSwitching === true
) {
return { expectedProvider: options.expectedProvider };
}
return {};
}
async setAgentMode(
agentId: string,
modeId: string,
options?: { expectedProvider?: AgentProvider },
): Promise<AgentProviderNotice | null> {
async setAgentMode(agentId: string, modeId: string): Promise<AgentProviderNotice | null> {
const requestId = this.createRequestId();
const message = SessionInboundMessageSchema.parse({
type: "set_agent_mode_request",
agentId,
modeId,
...this.expectedProviderWireField(options),
requestId,
});
const payload = await this.sendRequest({
@@ -4551,17 +4460,12 @@ export class DaemonClient {
return payload.notice ?? null;
}
async setAgentModel(
agentId: string,
modelId: string | null,
options?: { expectedProvider?: AgentProvider },
): Promise<void> {
async setAgentModel(agentId: string, modelId: string | null): Promise<void> {
const requestId = this.createRequestId();
const message = SessionInboundMessageSchema.parse({
type: "set_agent_model_request",
agentId,
modelId,
...this.expectedProviderWireField(options),
requestId,
});
const payload = await this.sendRequest({
@@ -4583,19 +4487,13 @@ export class DaemonClient {
}
}
async setAgentFeature(
agentId: string,
featureId: string,
value: unknown,
options?: { expectedProvider?: AgentProvider },
): Promise<void> {
async setAgentFeature(agentId: string, featureId: string, value: unknown): Promise<void> {
const requestId = this.createRequestId();
const message = SessionInboundMessageSchema.parse({
type: "set_agent_feature_request",
agentId,
featureId,
value,
...this.expectedProviderWireField(options),
requestId,
});
const payload = await this.sendRequest({
@@ -4624,7 +4522,6 @@ export class DaemonClient {
async setAgentOptions(
agentId: string,
patch: Record<string, unknown>,
options?: { expectedProvider?: AgentProvider },
): Promise<AgentProviderNotice | null> {
const legacy = this.legacyProviderOptions();
if (legacy) {
@@ -4632,11 +4529,11 @@ export class DaemonClient {
const pending = this.legacyResetControls(agentId, patch);
const controls = pending ? await pending : [];
for (const [featureId, value] of legacy.featureWrites(patch, controls)) {
await this.setAgentFeature(agentId, featureId, value, options);
await this.setAgentFeature(agentId, featureId, value);
}
return null;
}
return this.applyAgentConfig(agentId, { options: patch }, options);
return this.applyAgentConfig(agentId, { options: patch });
}
/**
@@ -4656,14 +4553,12 @@ export class DaemonClient {
async setAgentThinkingOption(
agentId: string,
thinkingOptionId: string | null,
options?: { expectedProvider?: AgentProvider },
): Promise<AgentProviderNotice | null> {
const requestId = this.createRequestId();
const message = SessionInboundMessageSchema.parse({
type: "set_agent_thinking_request",
agentId,
thinkingOptionId,
...this.expectedProviderWireField(options),
requestId,
});
const payload = await this.sendRequest({
@@ -4696,7 +4591,6 @@ export class DaemonClient {
async applyAgentConfig(
agentId: string,
config: AgentConfigApply,
options?: { expectedProvider?: AgentProvider },
): Promise<AgentProviderNotice | null> {
let wireConfig = config;
const legacy = this.legacyProviderOptions();
@@ -4710,7 +4604,6 @@ export class DaemonClient {
type: "agent.config.apply.request",
agentId,
config: wireConfig,
...this.expectedProviderWireField(options),
requestId,
});
const payload = await this.sendRequest({
+1 -21
View File
@@ -346,14 +346,6 @@ export type PaseoAgentTimelineEvent =
agentId: string;
event: { type: "replacement"; epoch: string };
}
| {
/**
* A conversation rewind removed the rows anchored in `[retireFromSeq, seq)` from the active
* history. Rows after `seq` belong to the rewound conversation.
*/
agentId: string;
event: { type: "rewind"; epoch: string; seq: number; retireFromSeq: number };
}
| {
agentId: string;
subscriptionId: string;
@@ -375,9 +367,7 @@ export interface PaseoAgentTimelineHandle {
* Delivers live events only. After reconnect, subscription_restored precedes
* subsequent updates. History may have been missed; use refetch() to request
* the range you need. No history is fetched automatically. A replacement event
* invalidates the previous epoch. A rewind event removes `[retireFromSeq, seq)`
* from the active history without changing the epoch. Subscription errors
* release this observation.
* invalidates the previous epoch. Subscription errors release this observation.
* Await the returned unsubscribe function's `ready` promise before starting
* work that must be observed. It rejects if establishment fails.
*/
@@ -1057,16 +1047,6 @@ function createAgentHandleFactory(
agentId: id,
event: { type: "replacement", epoch: message.payload.epoch },
});
case "agent.timeline.rewind":
return handler({
agentId: id,
event: {
type: "rewind",
epoch: message.payload.epoch,
seq: message.payload.seq,
retireFromSeq: message.payload.retireFromSeq,
},
});
}
}),
},
@@ -3,7 +3,7 @@ import type { OwnedSubscription, TimelineSubscription } from "../connection/inde
type TimelineUpdate = Extract<
SessionOutboundMessage,
{ type: "agent_stream" | "agent.timeline.replacement" | "agent.timeline.rewind" }
{ type: "agent_stream" | "agent.timeline.replacement" }
>;
/** Local SDK lifecycle messages; these are not additional wire RPCs. */
@@ -59,11 +59,7 @@ export function subscribeTimeline(
});
},
update: (message) => {
if (
message.type === "agent_stream" ||
message.type === "agent.timeline.replacement" ||
message.type === "agent.timeline.rewind"
)
if (message.type === "agent_stream" || message.type === "agent.timeline.replacement")
notify(message);
},
error: fail,
@@ -23,6 +23,8 @@ const allStyles: HighlightStyle[] = [
"meta",
"heading",
"link",
"diffAddition",
"diffDeletion",
];
describe("darkHighlightColors", () => {
@@ -1,4 +1,4 @@
import { describe, it, expect } from "vitest";
import { describe, it, expect, vi } from "vitest";
import { setImmediate } from "node:timers/promises";
import { highlightCodeWithBudget, HIGHLIGHT_MAX_SOURCE_BYTES } from "../budgeted-highlighter.js";
import type { HighlightToken } from "../types.js";
@@ -49,6 +49,35 @@ describe("highlightCode", () => {
},
);
it("highlights Ruby code", () => {
const code = [
"class Greeter < Base",
" # say hello",
" def greet(name)",
' puts "hello #{name}" if name',
" end",
"end",
].join("\n");
const result = highlightCode(code, "greeter.rb");
expect(result).toHaveLength(6);
expect(result[0].find((t) => t.text === "class")?.style).toBe("keyword");
expect(result[1].find((t) => t.text.includes("say hello"))?.style).toBe("comment");
expect(result[2].find((t) => t.text === "def")?.style).toBe("keyword");
expect(result[3].find((t) => t.text.includes("hello"))?.style).toBe("string");
expect(result[3].find((t) => t.text === "if")?.style).toBe("keyword");
});
it("highlights extensionless Ruby files by name", () => {
const code = 'source "https://rubygems.org"\n\ngem "rails", "~> 7.1"';
for (const filename of ["Gemfile", "app/Gemfile", "tasks.rake", "app.gemspec"]) {
const result = highlightCode(code, filename);
expect(result).toHaveLength(3);
expect(result[0].find((t) => t.text.includes("rubygems"))?.style).toBe("string");
expect(result[2].find((t) => t.text.includes("rails"))?.style).toBe("string");
}
});
it("highlights Swift code", () => {
const code = 'struct Greeter {\n let message = "hello"\n}';
const result = highlightCode(code, "test.swift");
@@ -81,6 +110,236 @@ describe("highlightCode", () => {
expect(stringToken?.style).toBe("string");
});
it.each(["changes.diff", "bug.patch", "diff", "patch"])(
"highlights unified diffs for %s without trailing-whitespace warnings",
(target) => {
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
try {
const code = [
"diff --git a/app.py b/app.py",
"index 1111111..2222222 100644",
"--- a/app.py",
"+++ b/app.py",
"@@ -1,3 +1,3 @@ def greet():",
" print('hello')",
" ",
"-old = 1 ",
"+new = 2 ",
].join("\n");
const result = highlightCode(code, target);
expect(result).toHaveLength(9);
expect(result[0]).toEqual([{ text: "diff --git a/app.py b/app.py", style: null }]);
expect(result[1]).toEqual([{ text: "index 1111111..2222222 100644", style: null }]);
expect(result[2]).toEqual([{ text: "--- a/app.py", style: "diffDeletion" }]);
expect(result[3]).toEqual([{ text: "+++ b/app.py", style: "diffAddition" }]);
expect(result[4]).toEqual([{ text: "@@ -1,3 +1,3 @@ def greet():", style: "meta" }]);
expect(result[5]).toEqual([{ text: " print('hello')", style: null }]);
expect(result[6]).toEqual([{ text: " ", style: null }]);
expect(result[7]).toEqual([{ text: "-old = 1 ", style: "diffDeletion" }]);
expect(result[8]).toEqual([{ text: "+new = 2 ", style: "diffAddition" }]);
expect(warn).not.toHaveBeenCalled();
} finally {
warn.mockRestore();
}
},
);
it("highlights Kotlin code", () => {
const code = 'class Greeter {\n val message: String = "hello"\n}';
const result = highlightCode(code, "test.kt");
expect(result).toHaveLength(3);
const classToken = result[0].find((t) => t.text === "class");
expect(classToken?.style).toBe("keyword");
const valToken = result[1].find((t) => t.text === "val");
expect(valToken?.style).toBe("keyword");
const typeToken = result[1].find((t) => t.text === "String");
expect(typeToken?.style).toBe("type");
const stringToken = result[1].find((t) => t.text.includes("hello"));
expect(stringToken?.style).toBe("string");
});
it("highlights TOML code", () => {
const code = [
"[server]",
'host = "localhost"',
"port = 8080",
"enabled = true",
"born = 1979-05-27T07:32:00Z",
].join("\n");
const result = highlightCode(code, "config.toml");
expect(result).toHaveLength(5);
expect(result[0].find((t) => t.text === "[server]")?.style).toBe("keyword");
expect(result[1].find((t) => t.text === "host")?.style).toBe("property");
expect(result[1].find((t) => t.text === '"localhost"')?.style).toBe("string");
expect(result[2].find((t) => t.text === "port")?.style).toBe("property");
expect(result[2].find((t) => t.text === "8080")?.style).toBe("number");
expect(result[3].find((t) => t.text === "enabled")?.style).toBe("property");
expect(result[3].find((t) => t.text === "true")?.style).toBe("keyword");
expect(result[4].find((t) => t.text === "born")?.style).toBe("property");
expect(result[4].find((t) => t.text === "1979-05-27T07:32:00Z")?.style).toBe("keyword");
});
it("highlights SQL code", () => {
const code =
"-- Fetch active users\nSELECT id, name FROM users WHERE active = TRUE AND age > 18;";
const result = highlightCode(code, "query.sql");
expect(result[0][0]).toEqual({ text: "-- Fetch active users", style: "comment" });
expect(result[1]).toContainEqual({ text: "SELECT", style: "keyword" });
expect(result[1]).toContainEqual({ text: "FROM", style: "keyword" });
expect(result[1]).toContainEqual({ text: "WHERE", style: "keyword" });
});
it("highlights Lua code", () => {
const code = '-- Greeting\nlocal function greet(name)\n return "hi " .. name\nend';
const result = highlightCode(code, "script.lua");
expect(result[0][0]).toEqual({ text: "-- Greeting", style: "comment" });
expect(result[1]).toContainEqual({ text: "local", style: "keyword" });
expect(result[1]).toContainEqual({ text: "function", style: "keyword" });
expect(result[2].find((t) => t.text.includes("hi"))?.style).toBe("string");
});
it("highlights Protobuf definitions", () => {
const code = 'syntax = "proto3";\nmessage User {\n string id = 1;\n}';
const result = highlightCode(code, "schema.proto");
expect(result[0]).toContainEqual({ text: "syntax", style: "keyword" });
expect(result[0]).toContainEqual({ text: '"proto3"', style: "string" });
expect(result[1]).toContainEqual({ text: "message", style: "keyword" });
expect(result[2]).toContainEqual({ text: "string", style: "keyword" });
});
it.each(["deploy.ps1", "module.psm1", "manifest.psd1"])(
"highlights PowerShell in %s",
(filename) => {
const code = '# Greet\nfunction Get-Name {\n $msg = "hello"\n return $msg\n}';
const result = highlightCode(code, filename);
expect(result[0][0]).toEqual({ text: "# Greet", style: "comment" });
expect(result[1]).toContainEqual({ text: "function", style: "keyword" });
expect(result[2].find((t) => t.text.includes("hello"))?.style).toBe("string");
},
);
it.each(["build.groovy", "build.gradle"])("highlights Groovy/Gradle in %s", (filename) => {
const code = '// Build\ndef version = "1.0"\nplugins {\n id "java"\n}';
const result = highlightCode(code, filename);
expect(result[0][0]).toEqual({ text: "// Build", style: "comment" });
expect(result[1]).toContainEqual({ text: "def", style: "keyword" });
expect(result[1]).toContainEqual({ text: '"1.0"', style: "string" });
expect(result[3]).toContainEqual({ text: '"java"', style: "string" });
});
it.each(["Main.scala", "script.sc"])("highlights Scala in %s", (filename) => {
const code = 'case class User(name: String)\nobject Main { val msg = "hi" }';
const result = highlightCode(code, filename);
expect(result[0]).toContainEqual({ text: "case", style: "keyword" });
expect(result[0]).toContainEqual({ text: "class", style: "keyword" });
expect(result[0]).toContainEqual({ text: "String", style: "type" });
expect(result[1]).toContainEqual({ text: "object", style: "keyword" });
expect(result[1]).toContainEqual({ text: '"hi"', style: "string" });
});
it.each(["CMakeLists.txt", "app/CMakeLists.txt", "toolchain.cmake"])(
"highlights CMake in %s",
(filename) => {
const code = "# Build\ncmake_minimum_required(VERSION 3.20)\nproject(Paseo)";
const result = highlightCode(code, filename);
expect(result[0][0]).toEqual({ text: "# Build", style: "comment" });
expect(result[1]).toContainEqual({ text: "cmake_minimum_required", style: "definition" });
expect(result[2]).toContainEqual({ text: "project", style: "definition" });
},
);
it.each(["app.properties", "config.ini", "service.conf"])(
"highlights properties/INI in %s",
(filename) => {
const code = "# Settings\n[database]\nhost = localhost";
const result = highlightCode(code, filename);
expect(result[0][0]).toEqual({ text: "# Settings", style: "comment" });
expect(result[1]).toContainEqual({ text: "[database]", style: "heading" });
expect(result[2].some((t) => t.style !== null)).toBe(true);
},
);
it.each(["analysis.r", "analysis.R"])("highlights R in %s", (filename) => {
const code = "# Compute mean\nmean_val <- function(x) {\n return(mean(x))\n}";
const result = highlightCode(code, filename);
expect(result[0][0]).toEqual({ text: "# Compute mean", style: "comment" });
expect(result[1]).toContainEqual({ text: "<-", style: "operator" });
expect(result[1]).toContainEqual({ text: "function", style: "keyword" });
});
it.each(["script.pl", "Module.pm"])("highlights Perl in %s", (filename) => {
const code = '# Greet\nuse strict;\nmy $name = "world";';
const result = highlightCode(code, filename);
expect(result[0][0]).toEqual({ text: "# Greet", style: "comment" });
expect(result[1]).toContainEqual({ text: "use", style: "keyword" });
expect(result[2]).toContainEqual({ text: "my", style: "definition" });
expect(result[2]).toContainEqual({ text: '"world"', style: "string" });
});
it.each(["paper.tex", "style.sty", "article.cls"])("highlights LaTeX in %s", (filename) => {
const code =
"% Header\n\\documentclass{article}\n\\begin{document}\nHello $x^2$.\n\\end{document}";
const result = highlightCode(code, filename);
expect(result[0][0]).toEqual({ text: "% Header", style: "comment" });
expect(result[1]).toContainEqual({ text: "\\documentclass", style: "tag" });
expect(result[2]).toContainEqual({ text: "\\begin", style: "tag" });
});
it.each([
"changes.diff",
"bug.patch",
"greeter.rb",
"Gemfile",
"test.kt",
"config.toml",
"query.sql",
"script.lua",
"schema.proto",
"deploy.ps1",
"build.gradle",
"Main.scala",
"CMakeLists.txt",
"config.ini",
"analysis.R",
"script.pl",
"paper.tex",
])("handles empty input and long lines cleanly in %s", (filename) => {
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
try {
expect(highlightCode("", filename)).toEqual([[{ text: "", style: null }]]);
const longLine = "x".repeat(5000);
const result = highlightCode(longLine, filename);
expect(result).toHaveLength(1);
expect(result[0].map((t) => t.text).join("")).toBe(longLine);
expect(warn).not.toHaveBeenCalled();
} finally {
warn.mockRestore();
}
});
it("highlights C# code", () => {
const code = 'class Greeter {\n string message = "hello";\n}';
const result = highlightCode(code, "test.cs");
@@ -346,6 +605,8 @@ const title = "Hello";
"meta",
"heading",
"link",
"diffAddition",
"diffDeletion",
null,
]);

Some files were not shown because too many files have changed in this diff Show More