Compare commits

...
Author SHA1 Message Date
Mohamed Boudra 669a7cfd8a test(client): include timeline_provider_switches in hello capabilities assertion 2026-11-25 18:54:02 +01:00
Mohamed Boudra 18876070ea feat(agents): support provider switching within a chat 2026-11-25 18:47:19 +01:00
Mohamed Boudra a9856f12b6 test(server): give the terminal workspace test's cleanup longer on Windows
On Windows the stopped `sleeper` script's process can still hold the project
directory as its working directory when the test removes it, failing cleanup
with EBUSY. rm's retries now wait up to about 5 s for the handle to go.
2026-11-25 16:46:41 +01:00
Mohamed Boudra 1c378330bc fix(timeline): serve an empty older page before a retired first turn in SQLite
The SQLite backend's `before` selection had the same gap as the memory
projection fixed on the base branch: with no active row by the cursor it
returned the first later row as the start of an empty page. It now serves the
empty page, matching the memory backend in the contract and differential tests.
2026-11-25 16:31:25 +01:00
Mohamed Boudra beccad5ede feat(timeline): record the provider that wrote each row
An agent's history can span providers once it switches, so a row served with
the agent's current provider would be rendered as the wrong one. Live writes,
provider history imports, opening notices and subagent rows now store their
provider in the row; the timeline page and replay serve it, falling back to
the agent's provider for rows written before this change. SQLite keeps it in
the row JSON, so the schema is unchanged.
2026-11-25 16:31:25 +01:00
Mohamed Boudra 573e46cf20 fix(daemon): close paseo.db when startup or shutdown fails
A throw while the daemon assembled itself after opening paseo.db, or from a
shutdown step before the timeline close, left the connection and its WAL open
for the next daemon. `createPaseoDaemon` now owns the database and closes it
when assembly throws, and `stop()` closes it in `finally`.
2026-11-25 16:31:25 +01:00
Mohamed Boudra 793ccc5516 fix(timeline): reset an after cursor that is ahead of the history
A client whose cursor is past the stored history (commits lost in a crash, a
restored paseo.db) kept its cursor on an empty page, then dropped the rows
whose seqs it believed it already had. `fetchTimelinePage` now treats it as a
gap, so the client replaces its history with the tail.
2026-11-25 16:31:25 +01:00
Mohamed Boudra 31716f33af test(server): retry removing the restart test's directories on Windows
Windows reported EBUSY removing the agent directory right after the
second daemon closed. Retry the removal as the test daemon's own
cleanup does.
2026-11-25 16:31:25 +01:00
Mohamed Boudra 9b9fef944a perf(timeline): read the chat outline's cursor from the head, not a tail page
The prompt index fetched a one-row tail page only for its epoch and
retirement count. A tool call updated after other rows makes that page
cover every row in between, so the outline still decoded tool output.
AgentTimeline.readPrompts returns the prompt rows with the head they
belong to, in one timeline operation.
2026-11-25 16:31:25 +01:00
Mohamed Boudra a3c1ca6dba fix(agents): let an agent keep saving its record after a failed delete
The delete RPC fences the record against writes before closing the agent.
Since a failed history delete now leaves the record in place, the fence
stayed up for the rest of the process, so a later rename reported success
and never reached disk. The fence now ends when the delete aborts.
2026-11-25 16:31:25 +01:00
Mohamed Boudra 49715f0eae fix(timeline): keep history on reopen, fail deletes that leave it, read only prompts for the outline
- Opening a stored agent with no provider session ran the fresh-create
  cleanup, which deleted its saved timeline. Now that history survives a
  restart, that open erased it; the record-based open now clears only the
  previous session's runtime state.
- The delete RPC removed the registry record first and swallowed a failed
  history delete, replying agent_deleted while the transcript stayed on
  disk with no record to retry from. History now goes first and a failure
  reaches the client as rpc_error with the agent still listed.
- The chat outline built its prompt index from every active row, which on
  SQLite decodes all replies and tool output. Backends now return the
  active prompt rows, which the rewind and import paths already read.
2026-11-25 16:31:25 +01:00
Mohamed Boudra f44f6990a7 chore(nix): update npm dependency hash for the Node 22.16 types 2026-11-25 16:31:25 +01:00
Mohamed Boudra 7e61452dd4 fix(timeline): keep stored history private, exact, and off the turn's path
- paseo.db and its WAL files are set to mode 0600 on every open. They
  hold every prompt and reply.
- Internal agents keep their history in memory. Before this change it
  went to paseo.db and outlived a crash, which broke the rule that
  nothing about an internal agent is on disk.
- Text chunks are stored as JSON strings. node:sqlite reads a TEXT
  value only up to its first NUL, and a chunk can end inside a
  surrogate pair.
- A turn's handler now changes the agent's state before any timeline
  write. Before, a failed metrics stamp skipped the turn_completed
  handler, so a turn the provider started stayed running.
- Node 22.13, which has node:sqlite but not isTransaction, is refused
  at open.
- If the checkpoint worker cannot start, the daemon logs it and falls
  back to SQLite's auto-checkpoint. Before, the error reported an
  already committed write as failed.
2026-11-25 16:31:25 +01:00
Mohamed Boudra cf9683f066 test(cli): reopen the idle agent explicitly after a supervisor restart
Fetching an agent's timeline now reads stored history without loading the agent, so the agent stays closed until it is reopened.
2026-11-25 16:31:25 +01:00
Mohamed Boudra 88bc3ee42b test(agents): prove a run's caller hears a turn whose record failed 2026-11-25 16:31:25 +01:00
Mohamed Boudra a5f4cd06a6 feat(timeline): store agent timelines in paseo.db
Agent history now survives a daemon restart, and closed or archived
agents hold no timeline in memory. A history fetch reads paseo.db and
starts no provider.

The daemon opens one SQLite database at $PASEO_HOME/paseo.db with
node:sqlite. Each schema module owns its tables and migrations, and
records a min_reader_version, so an older daemon refuses a database
it cannot read instead of corrupting it. Node 22.16 is the floor,
because DatabaseSync needs it.

A worker thread runs the WAL checkpoints. A checkpoint syncs the
file, and on the daemon thread it stalled the event loop for up to
119 ms on whichever write crossed the auto-checkpoint threshold. If
the worker exits, the daemon returns to SQLite's auto-checkpoint.

A turn's final event now ends the run even when the timeline fails
to write it. Before this change the error escaped handleStreamEvent
before settleTerminalRun, so the agent stayed running and its waiters
hung. The durable store makes that write fallible, and shutdown made
it fail: settled() rejected after close.
2026-11-25 16:31:24 +01:00
Mohamed Boudra c228a3acac test(website): wait for hydration before submitting a plugin search
`openPlugins` waits only for the server-rendered heading. On WebKit, Enter
could land before hydration attached the search form's handler, so nothing
navigated and the page stayed on /plugins. The two tests that submit right
after opening the directory now wait for hydration first; `openPlugins` itself
stays as it is because a no-JavaScript test uses it.
2026-11-25 16:31:17 +01:00
Mohamed Boudra 1b6308502f fix(timeline): serve an empty older page before a retired first turn
After a rewind of the first prompt and a new turn, a `before` page whose
cursor fell in the retired prefix found no active row before the cursor. The
whole-turn loop then read the row at index -1 and threw, and ordinary paging
returned the first later row's seq as the start, past the page's end.
2026-11-25 16:20:34 +01:00
Mohamed Boudra 9e3107fcb7 test(opencode): read v2 children through the timeline-backed store
The child tests merged from main build a `ProviderSubagentStore` with no
timeline and read `list()` synchronously. On this branch the store keeps
children in the agent's timeline, so it takes one and its reads resolve
asynchronously. Each `apply` queues on the parent's timeline before its first
await, so an awaited `list` observes every event emitted before it.
2026-11-25 16:20:34 +01:00
Mohamed Boudra 5033ad0249 Merge origin/main into plan-provider-switch-sqlite-timelines
Conflicts resolved by keeping both intents:
- turn-boundary: main reads the reply through getAssistantReply (plugin
  cards); this branch narrows the fork cursor to epoch and seq.
- codex rewind: this branch's fork-and-verify flow, with main's
  threadDeveloperInstructions() for the developer instructions.
- agent-manager: this branch's ProviderHistoryReconcile type next to
  main's Omit<..., "signal"> query options.
Main's new plugin-card tests gain the anchorSeq this branch's cursors carry.
2026-11-25 16:00:06 +01:00
Mohamed Boudra 307f65d8f7 Stabilize website scene and keyboard language checks (#10808)
* fix(website): stabilize scene and keyboard language checks

Drive scene frames explicitly so sparse browser paints do not consume the test deadline. Let the landing page commit a locale change while its optional plugin count loads.

* test(website): advance the plugin panel crossfade before asserting removal

* test(website): settle native animations during the plugin panel swap

Playwright advances JavaScript frames, while the browser keeps a separate timeline for native animations. Finish the mockup’s finite native animations at the panel checkpoint so either animation path removes the outgoing panel.
2026-11-25 21:06:43 +07:00
Mohamed Boudra 163162e9f3 Teach the current plugin API in the bundled paseo-plugin skill (#10793)
* docs(skills): teach the current plugin API in the paseo-plugin skill

The skill still taught server.on and server.before, a deprecated panel
context, and an older publishing rule. It linked to hook anchors that
moved to the hooks page, and it had no entry for half of the shipped
contributions. Its RPC example imported a contract that the shared file
did not export.

The skill now indexes every public registration and links to the
reference section that owns its contract. It keeps a few complete
examples. Every ts and tsx block in the skill names its file, and the
blocks under each heading must typecheck as one plugin against the SDK,
so an example cannot drift from the API without a failing test.

* docs(skills): match the plugin skill RPC example to the scaffold and run its tests in CI

The RPC example used names that the generated client entry does not import, and it had no client entry. A PR that changed only the skill also skipped the SDK tests that typecheck its examples.

* docs(skills): keep the generated client entry in the plugin skill RPC example

Replacing index.client.tsx with a screen-only entry removed the scaffold's
Greeting sidebar item, which is the only control that opens the screen.

* docs(skills): say that npm plugins declare build for generated files

Paseo installs npm plugins with lifecycle scripts disabled, so a postinstall
step never runs.
2026-11-25 21:04:18 +07:00
Mohamed Boudra 4a6b8ae080 fix(app): keep the sidebar toggle clear of plugin screen titles (#10773)
With the left sidebar collapsed, every content header renders
SidebarMenuToggle in its leading slot. On macOS it is a blank space
under the toggle the window draws beside the traffic lights; on
Windows and Linux it is the toggle itself. The plugin screen header
built its own left side without it, so on macOS the floating toggle
sat on top of the title, and on Windows and Linux the screen had no
toggle to reopen the sidebar.
2026-11-25 20:59:43 +07:00
paseo-bot[bot] 465db78ab6 fix(opencode): clear deleted subagents from the track (#8332)
* fix(opencode): clear deleted subagents from the track

Handle provider deletion events before fetching the missing session, and reconcile removals after complete parent listings so reconnects also clear stale rows. Keep descendant cleanup scoped to the deleted child.

* fix(opencode): retain live subagents skipped during reconnect

* fix(opencode): reconcile skipped subagent descendants

* fix(opencode): restore live subagents after reconnect

A deleted child rejects environment restoration before reconnect can clean up its row. Let the child tracker remove confirmed deletions and continue restoring live descendants.

* fix(opencode): clear deleted subagents after reconnect

Let the OpenCode SDK decode missing-session responses in both runtimes. The child tracker can then remove the stale row and restore the live children when it reconnects.

---------

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-25 13:49:39 +00:00
Mohamed Boudra 30a155127d Redesign agent profiles settings, inspector drawer, and 1-tap composer creation (#10789)
* feat(app): redesign agent profiles settings, inspector drawer, and 1-tap composer creation

Promote Host -> Agent profiles to its own settings section with a searchable 3-column roster and slide-over inspector drawer, eliminate async layout jump when provider options load, and make composer model picker '+' save, select, and toast with Edit and Undo.

- Seed cached host provider catalogs synchronously and retain same-provider controls while refetching so the form no longer collapses and jumps when switching models or modes.
- Keep form session state above drawer/modal framing so resizing across breakpoints preserves unsaved edits, and render the drawer as a right-edge overlay below 1320px pane width so opening a profile never crushes or reflows table rows.
- Reuse Paseo's SearchField, CombinedModelSelector, SettingsCard, SettingsSwitch, SettingsCollapsibleRow, SegmentedControl, ToolbarButton, DismissBackdrop, WindowChromeRegion, and ToastHost across all surfaces.

* fix(app): preserve remounted drafts, guard duplicate, and serialize profile writes

Seed profile FormTextInput fields from the live session draft so drawer-to-modal resizes and collapsible toggles display the values Save will write. Share one confirmDiscardIfDirty guard between editor transitions and Duplicate. Serialize host profile mutations through a per-host queue in useAgentProfiles so overlapping composer quick-creates and Undo compose against the latest stored list.

* fix(app): keep profile editor across compact settings and Remove cancel

Unify compact and desktop Settings detail pane wrappers into SettingsDetailPane so resizing across the 600px compact breakpoint never unmounts HostAgentProfilesPage or drops an active edit session. Remove the premature onClose() call from AgentProfileEditModal's Remove handler so the caller closes the modal only after confirmation and deletion succeed.

* fix(app): allow roster search with docked drawer and guard Settings exits

Pass manageFocus: overlay to useOverlayRegistration in AgentProfileDrawer so slide-over overlays trap focus while docked drawers keep Escape handling and allow typing in roster search. Add a before-leave guard hook in SettingsScreen wired to AgentProfilesPage's confirmDiscardIfDirty so sidebar section switches, host switches, and back navigation prompt before discarding an unsaved profile draft.

* fix(app): guard browser Back and route removal on unsaved profile draft

Add navigation/route-leave-guard so web popstate events are intercepted before Expo Router's createMemoryHistory resets the root navigator, plus beforeRemove handling for native swipe-back and hardware Back. Canceling restores the history entry and keeps both route and draft; confirming replays the exit cleanly.

* fix(app): preserve intervening history on canceled multi-step Back jumps

Track ordered Expo Router history entry IDs in route-leave-guard instead of restoring via pushState. Canceling any Back/Forward traversal now reverts via history.go(delta) without truncating intervening or forward entries, and confirming replays popstate at the browser's exact selected destination.

* fix(app): restore Back-jump URL after reload and compute dirty from resolved defaults

Persist the tab's ordered history entry IDs in sessionStorage and verify the target entry ID when reverting a canceled popstate traversal, so canceling a multi-step Back jump after a page reload always restores the exact editor URL. Move isDirty into profile-form-model against the resolved initial baseline after catalog defaults hydrate so opening an untouched provider-and-model-only profile closes without a discard prompt.

* fix(app): dismiss profile-saved toast when its composer unmounts

Scope the composer's profile-saved toast to the lifetime of useAgentProfileEditor so closing an agent tab dismisses the toast instead of leaving a dead Edit action.

* fix(app): scope save completion close to the editor session that started it

Skip onSaved when useAgentProfileFormSession has unmounted mid-save, and guard handleSavedClose and composer handleSave by session key/request identity so switching to another profile during a slow save never closes the next profile's draft.

* fix(app): unify delayed editor transitions behind a session token

Track a monotonic editor session token in AgentProfilesPage and route delayed open/close transitions (Save completion, Duplicate completion, and async discard confirmation) through applyDelayedEditTarget so a slow Duplicate updates the roster without replacing a newer profile draft.

* fix(app): track draft revision so post-confirm edits veto delayed Duplicate

Add draftRevision to AgentProfileFormState and read isDirty/draftRevision directly from the live form model instead of mirroring a boolean ref. Approve discard for a specific (sessionToken, draftRevision) pair so any edit made after confirming Duplicate advances draftRevision and keeps the newer draft open when the host responds.

* Scope discard approval to each action so failed duplicates stay dirty

* Report agent profile write failures with toast across web and native

* Use usePreventRemove for Settings dirty-draft guard so native stacks block swipe dismiss

* Keep Settings sidebar scroll anchoring intact across font-size reflows
2026-11-25 20:48:38 +07:00
Mohamed Boudra b7af3da71f fix(timeline): commit confirmed plugin rewind cuts and stream reload turn metrics
Preserve the confirmed at_target cut via RewindAppliedError when plugin session replay fails after session.revert succeeds, so reloading recovers even a first-message rewind. Carry turnMetrics on live timeline events appended by Reload agent so open chats match fresh timeline pages. Fix three async-timeline timing expectations in mcp-server and codex-async-questions tests.
2026-11-24 09:18:19 +01:00
Mohamed Boudra 2789421fbd Merge remote-tracking branch 'origin/main' into plan-provider-switch-sqlite-timelines
# Conflicts:
#	packages/app/e2e/browser/agent-message-rewind.spec.ts
#	packages/app/e2e/browser/rewind-menu.ui-contract.spec.ts
#	packages/app/src/runtime/host-runtime.ts
#	packages/app/src/timeline/session-stream-reducers.test.ts
#	packages/server/src/server/agent/agent-manager.test.ts
#	packages/server/src/server/agent/agent-manager.ts
#	packages/server/src/server/agent/agent-timeline-store-types.ts
#	packages/server/src/server/agent/agent-timeline-store.test.ts
#	packages/server/src/server/agent/agent-timeline-store.ts
#	packages/server/src/server/agent/plugin-provider.ts
#	packages/server/src/server/agent/providers/claude/agent.ts
2026-11-24 09:02:33 +01:00
Mohamed Boudra b7b5acf086 fix(timeline): resolve plugin rewind, id reuse, and startup notice findings
Define plugin session.revert completion as an exact rewind to the supplied token (at_target), allow plugin timeline items to reuse stable ids after a rewind, append session.initialTimeline only when creating a new timeline, and centralize provider-history prompt acknowledgement inside AgentTimeline.
2026-11-24 08:50:13 +01:00
Mohamed Boudra bf83a03ce9 fix(timeline): acknowledge replayed prompts with client IDs 2026-11-18 15:21:47 +01:00
Mohamed Boudra 80240eb851 test(timeline): reload a whole turn after restoring retired children 2026-11-18 15:00:49 +01:00
Mohamed Boudra 0c11263d4d fix(timeline): sync provider history at whole turn boundaries 2026-11-18 14:45:23 +01:00
Mohamed Boudra 28c9806da8 fix(timeline): exclude session status from history comparison 2026-11-18 14:11:13 +01:00
Mohamed Boudra a0add767c0 fix(timeline): reconcile live reconnect notices after updating from main 2026-11-18 13:51:34 +01:00
Mohamed Boudra 25f637e57c Merge remote-tracking branch 'origin/main' into plan-provider-switch-sqlite-timelines
# Conflicts:
#	packages/server/src/server/agent/agent-manager.test.ts
#	packages/server/src/server/agent/agent-manager.ts
#	packages/server/src/server/agent/providers/codex-app-server-agent.ts
#	packages/server/src/server/agent/tools/paseo-tools.ts
2026-11-18 13:35:20 +01:00
Mohamed Boudra 53fa9524cf fix(app): keep rewind invalidation for find results after Next and Previous
The rewind marker of the result set was cleared in cancel(), which also
stops navigation work. Next and Previous call cancel() while keeping the
results, so after one step a remote rewind no longer invalidated them and
the selection could stay on a retired message. The marker now shares the
result set's lifetime and is cleared only when a new query discards it.
2026-11-11 08:51:28 +01:00
Mohamed Boudra 5a8383d237 fix(app): end chat find results when a rewind retires messages
Find validated its results against the timeline epoch only. Capable hosts
rewind in place, so the epoch stays the same and a remote rewind left the
count and selection pointing at retired messages; Next could reveal one.

The replica now records the latest rewind seq per agent, from live rewind
events and from fetched pages carrying retirements. Find treats epoch plus
that seq as the history identity, so a rewind during or after a search
reports the history as changed.
2026-11-11 08:41:00 +01:00
Mohamed Boudra cf3caefa14 fix(server): retire the turns a steered Codex rewind actually removed
Codex rewinds whole native turns. A steered prompt shares its turn with the prompt it joined, so forking before that turn also removes the earlier prompt, and a rollback counted per prompt can remove earlier turns. The session reported at_target, so Paseo kept prompts the provider no longer had. It now reports the cut from the turn index taken before the fork, and an unreported outcome when the fork switched threads but did not finish.
2026-11-11 08:36:58 +01:00
Mohamed Boudra c747a58871 test(app): expect a rewound first prompt to leave the chat in the rewind sheet spec
On main the mock provider's rewind kept the first user message whatever the target, and the chat was rebuilt from that history, so the spec expected the rewound first prompt to stay. The mock now rewinds at the target and the chat retires the rewound turns in place, so rewinding the first prompt empties the chat and returns the prompt to the composer.
2026-11-11 08:26:19 +01:00
Mohamed Boudra c36d398829 perf(server): read the subscription freshness head without fetching the transcript
The freshness check read the head by fetching every row of the agent's history on each subscribe. The timeline head now carries its last committed sequence number, so the check reads only the head.
2026-11-11 04:00:27 +01:00
Mohamed Boudra 183bc736ec test(server): await provider child reads in the replay and pi child tests
These tests came in with the main merge. The child store reads are asynchronous now, so the tests compared a promise with the expected child.
2026-11-11 04:00:11 +01:00
Mohamed Boudra c4ce21a237 test(client): expect the rewind capability in the client hello
The client advertises timeline_rewind_operations since the rewind operations landed, but the hello expectation was never updated.
2026-11-11 03:59:55 +01:00
Mohamed Boudra 9a2236dac3 test(server): give the test session the interface's persistence signature
TestAgentSession.describePersistence had no return type, so TypeScript
inferred a codex-only handle with a UUID session id. The restarted-child test
from 80879eaf7 assigns the resumed AgentPersistenceHandle to it and failed to
typecheck (TS2322). The test double now declares the AgentSession signature,
which also clears the older plugin-provider sites with the same error.
2026-11-10 13:54:12 +01:00
Mohamed Boudra ecd0dd083e fix(server): let an aborted wait end while the provider is starting the turn
10c443a32 made waitForAgentEvent wait for a starting run before reading its
state, but that wait came before the abort listener. A provider start has no
deadline of its own, so a stalled startTurn kept every timed wait (MCP wait,
CLI wait, schedules, finish subscriptions) past its timeout. The start wait
now rejects as soon as the caller's signal aborts.
2026-11-10 13:53:50 +01:00
Mohamed Boudra 10c443a32b fix(server): wait for a starting run to settle before steering or waiting on it
A run's start now awaits the timeline before the provider is called, and a
failed start awaits its timeline writes before the run is cleared. Two
readers raced those windows:

- waitForForegroundStart returned as soon as a start failed, while the failed
  run was still tracked, so a steer send in that window replaced it and
  interrupted the session instead of starting its own turn.
- waitForAgentEvent replayed the idle state from before a starting run and
  finished immediately, so `wait` after a dispatch could return before the
  turn ran.

waitForForegroundStart now resolves only once the turn started or the run is
cleared, as documented, and waitForAgentEvent waits for it before reading the
agent's state. The OMP restored-history test previously finished only through
that early return; its fake now starts the turn it later ends.
2026-11-10 13:47:49 +01:00
Mohamed Boudra 457d8d6ec5 Merge origin/main into plan-provider-switch-sqlite-timelines
Adapts main's changes to the single asynchronous timeline owner:

- The subscribe freshness check (#9175) awaits the loaded timeline head and
  compares the client's cursor against the epoch that client sees, so legacy
  clients compare against their derived epoch after a rewind.
- History reads (#8737) pass purpose "history" when an agent with no stored
  timeline must be loaded; stored history is still read without the provider.
- Background work clears on reload, close and parent delete next to the
  async provider-child cancellation.
- Claude steered-message rewinds (#8372) report an at-target cut. Codex keeps
  main's saved thread id alongside the reported cut.
- Plugin rewinds (#8368) return an unreported outcome; a failed replay after
  the native revert leaves the rewind for the reload to settle rather than a
  retry. Manager-level rewinds target the timeline row's message id.
- Main's tests read the timeline asynchronously, and wait for the provider to
  receive a prompt instead of assuming it arrives in the dispatch tick.
2026-11-10 13:47:17 +01:00
Mohamed Boudra 80879eaf7c fix(timeline): retain child state and recover rewinds on resume
Provider children now live in the parent's timeline next to its history,
so their descriptors, rows and retirements survive close, archive and a
manager rebuilt over the same backend, and deleting the agent removes
them all. Resuming settles a rewind that was still open when the runtime
stopped instead of leaving its rows half-retired.

A stored child's status is only the last report, possibly from provider
history or an earlier runtime. Workspace activity and idle cleanup now
read the children the current runtime reported running, and closing a
runtime cancels only those, so a child stored as running from an earlier
runtime no longer keeps the agent busy or blocks cleanup.
2026-11-10 13:09:38 +01:00
Mohamed Boudra dc85c2bfbc feat(timeline): preserve history across reload and archive
Reload agent used to delete the timeline and replay the provider's
history under a new epoch. That brought back turns the user had rewound
and dropped anything the provider no longer had. Archive deleted the
timeline too.

Paseo's timeline is now the owner of the conversation. Reload agent
keeps it and reconciles the provider's history append-only: turns are
aligned by provider prompt id and compared exactly (prompt text,
assistant and reasoning text, tool calls). When the owned conversation
is a whole-segment prefix of the provider's, the rows after it are
appended as new live rows. Any other difference changes nothing and
agent_refreshed reports historyDiverged, which the app shows as a
warning on Reload agent and Unarchive.

Divergence is deliberately conservative:
- An answer or tool call Paseo saw only partly can never be completed by
  a reload. History rows carry no turn id to update a live row in place.
- A prompt sent with attachments diverges on every reload. Providers
  store the rendered attachment text, and the owned row keeps only the
  typed text. Recording the sent prompt is left to provider handoff work.

Archive now only closes the runtime. Stored history, including provider
children, is read without resuming or even requiring the provider.
Forced provider replacement is removed.

Tradeoff: an archived chat's history stays in memory until the daemon
exits, measured at about 1.1-1.2x its JSON size (about 0.5 MB for a
typical session, about 16 MB for a heavy tool session). Moving
retained history to disk belongs to the persisted backend, not eviction,
which would drop the rewinds this change keeps.
2026-11-10 11:43:10 +01:00
Mohamed Boudra 5ed1f8d108 feat(timeline): apply conversation rewinds without replacing history
Rewinding a prompt used to rotate the timeline epoch, so every open
client refetched and remounted the whole chat. A rewind is now a
retirement: the daemon keeps the rewound turn stored but outside the
conversation, and capable clients remove the rows that started in
[retireFromSeq, seq) in place. Catch-up pages carry the retirements in
their span. Clients without the timeline_rewind_operations capability
get the old replacement shape.

The daemon retires only what the provider actually removed. Providers
report the boundary they kept. A failure known to change nothing keeps
the conversation. Any other failure leaves the rewind open and refuses
prompts until reloading the agent proves the outcome from the
provider's replayed prompts. A recorded cut whose save failed is
committed by the next prompt or the reload, which resumes the rewound
session.

Plugin providers complete session.revert without saying what they
removed. Paseo then reloads the session itself and judges the outcome
from the replay, so a no-op completion is not taken as a cut.

The app anchors each row at the seq it started at, because a late
update moves a row's latest seq into the rewound range. The app also
refuses pages served before the newest retirement it has seen, then
refetches them.

Known limits:
- The automatic plugin settle shows the agent as restoring briefly.
- An empty or mismatched plugin replay leaves the rewind unresolved.
  Fork the chat to recover.
- A plugin's failed revert still needs a manual reload.
- An open rewind lives in memory, so a daemon restart drops it.
2026-11-10 10:16:13 +01:00
Mohamed Boudra 4178497d3d refactor(server): give agent timeline history a single awaitable owner
Agent timeline history had several writers that appended and published
independently, so a persistent backend could not be swapped in without
reordering or losing items. AgentTimeline now owns each agent's history:
one FIFO queue per agent (child agents share the parent's queue) commits
each item and then publishes it, so subscribers never see an item before it
is recorded. Backends may be async, which prepares the SQLite swap.

Terminal turn events wait for queued writes so a finished turn never races
its own last chunks. A subscriber that throws after commit leaves the item
in history. A failed commit surfaces as an agent error ("Conversation
history could not be saved") via the existing lastError/attention path; it
survives the turn's terminal transition and clears on the next run.
2026-11-10 08:11:00 +01:00
233 changed files with 25475 additions and 4978 deletions
+1
View File
@@ -56,6 +56,7 @@ sdk:
- "packages/plugin/**"
- "plugin-examples/**"
- "public-docs/plugins/**"
- "skills/paseo-plugin/**"
- "packages/client/**"
- "packages/highlight/**"
- "packages/protocol/**"
+1
View File
@@ -54,6 +54,7 @@ At the start of non-trivial work, list `docs/` and skim anything relevant to the
| [docs/permissions.md](docs/permissions.md) | Semantic daemon permissions, principals, credentials, pairing invitations, and Hub authority |
| [docs/terminal-performance.md](docs/terminal-performance.md) | Terminal latency pipeline, coalescing/backpressure invariants, benchmark + perf spec usage |
| [docs/terminal-rendering.md](docs/terminal-rendering.md) | Native terminal view: xterm owns the grid, cluster placement, emoji widths, mixed-direction limits, render regression |
| [docs/timeline-sync.md](docs/timeline-sync.md) | Owned agent history, rewind retirements, live stream vs authoritative fetch, paged catch-up, client replica |
| [docs/agent-stream-performance.md](docs/agent-stream-performance.md) | Assistant text pipeline — coalescing window, paced reveal, why arrival lumps are smoothed at render |
| [docs/agent-stream-disclosure.md](docs/agent-stream-disclosure.md) | Expand/collapse in the chat timeline — hold contract, native anchor sequence, frame spacing, render-window cost |
| [docs/markdown-renderer.md](docs/markdown-renderer.md) | Shared Markdown engine, the vendored library fork, native selection, links, images and library constraints |
+6 -3
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. Provider history is not appended again when the canonical timeline is already
primed.
same Paseo agent ID. Resume does not read provider history when the agent already has a timeline;
see [owned history](timeline-sync.md#owned-history).
Reload releases the old runtime before resuming its durable session: an idle provider process can
still own an exclusive writer. A close failure retains that runtime for cleanup and blocks the
@@ -256,7 +256,8 @@ lifecycle is separate from public workspace visibility and is not a public creat
Archive is a **soft delete**: the agent record stays on disk with `archivedAt` set, the runtime is closed, and the agent disappears from active lists. Archive is **global** — it lives on the server and propagates to every connected client.
Archive sets `archivedAt`, invokes the provider's native archive hook, and cascades to managed
children.
children. The timeline and the provider children stay, so an archived chat reads them without its
provider; deleting the agent removes them.
`create_agent_request` can opt an agent into `autoArchive`. In that mode the daemon archives the agent after the first terminal turn event (`turn_completed`, `turn_failed`, or `turn_canceled`). When the agent owns an isolated workspace, auto-archive archives that workspace too; the managed worktree is removed when its final workspace reference is gone.
@@ -352,6 +353,8 @@ Workspace status is an aggregate activity signal computed **per `workspaceId`**.
Running provider-native subagents contribute `running` to the workspace owned by their parent agent. Their completed, failed, and canceled states stay in the parent's subagents track.
Only the parent's current runtime makes a provider child running. A child's stored status is the last report about it, and that report can come from provider history or from a runtime an earlier daemon ran, so a stored `running` child does not make the workspace running or keep the parent's runtime alive. It counts again once the live session reports it running. Closing a runtime cancels the children that runtime reported running; children it never reported keep their stored status.
A finished or failed workspace can be marked unread after it has been reviewed. The daemon restores
attention on its newest eligible workspace-root agent, `error` for an agent whose lifecycle is
`error` and `finished` otherwise, without sending a new notification. Opening a workspace restores
+3 -1
View File
@@ -94,6 +94,7 @@ workspace for a directory clears it. The store lives in memory and resets on dae
| `server/directory-sync/` | Daemon-global latest-state sequences for projects, workspaces, and agents |
| `server/workspace-labels/` | Host-local label catalog, assignment mutations, and explicit subscriptions |
| `server/agent/agent-manager.ts` | Agent lifecycle state machine, timeline tracking, subscriber management |
| `server/agent/timeline/` | Owned agent history, provider children, rewind retirements, behind a backend |
| `server/agent/agent-storage.ts` | File-backed JSON persistence at `$PASEO_HOME/agents/` |
| `server/agent/tools/` | Transport-neutral catalog for workspaces, agents, permissions, and automation |
| `server/agent/mcp-server.ts` | Thin MCP adapter that registers the Paseo tool catalog with the MCP SDK |
@@ -402,7 +403,7 @@ initializing → idle ⇄ running
client-side dedup; the default fetch page is 200 items.
- Timeline row `timestamp` values are canonical daemon-owned timestamps. Providers may supply original replay timestamps, but clients must not guess timestamp trust or hide time UI based on local clock heuristics.
- Events stream to connected clients in real time; correctness is backed by authoritative timeline fetches and paged-to-completion catch-up.
- Agent state persists to `$PASEO_HOME/agents/{cwd-with-dashes}/{agent-id}.json`. Timeline rows are runtime memory; provider history is the durable transcript authority and resumed agents rebuild from it. That storage path is derived from `cwd`, not from workspace id.
- Agent state persists to `$PASEO_HOME/agents/{cwd-with-dashes}/{agent-id}.json`. That storage path is derived from `cwd`, not from workspace id. Timeline rows persist in the daemon database, `$PASEO_HOME/paseo.db`. They are the transcript authority after the first import of provider history. See [owned history](timeline-sync.md#owned-history).
## Right-sidebar boundary: directory-backed vs workspace-owned
@@ -478,6 +479,7 @@ Providers that can accept native tool definitions should set `supportsNativePase
```
$PASEO_HOME/
├── agents/{cwd-with-dashes}/{agent-id}.json # Agent record
├── paseo.db # Daemon database (SQLite): agent timelines
├── projects/projects.json # Project registry
├── projects/workspaces.json # Workspace registry
├── projects/icons/ # Custom project icon images
+41 -1
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 uses **file-based JSON persistence** instead of a traditional database. All data is validated at runtime with Zod schemas. Most stores write atomically (write to temp file, then rename); a few still use plain `writeFile` — see each section. There is no schema-versioning/migration framework — schemas rely on optional fields with defaults for forward compatibility, with a small amount of inline normalization in `persisted-config.ts` for legacy provider/speech entries.
Paseo persists most stores as JSON files, and agent timelines in the [daemon database](#daemon-database). JSON data is validated at runtime with Zod schemas. Most JSON stores write atomically (write to temp file, then rename); a few still use plain `writeFile` — see each section. JSON stores have no schema-versioning/migration framework — schemas rely on optional fields with defaults for forward compatibility, with a small amount of inline normalization in `persisted-config.ts` for legacy provider/speech entries.
All server-side stores live under `$PASEO_HOME` (defaults to `~/.paseo`).
@@ -53,6 +53,7 @@ $PASEO_HOME/
├── daemon-keypair.json # E2EE keypair for relay (mode 0600)
├── paseo.pid # Daemon PID lock file
├── local-credential # Per-run local client credential (mode 0600)
├── paseo.db # Daemon database (SQLite, with -wal and -shm files)
├── daemon.log # Default log file (path configurable)
├── agents/
│ └── {sanitized-cwd}/
@@ -181,6 +182,45 @@ Terminal activity contributes to the workspace status bucket **per `workspaceId`
---
## Daemon database
`$PASEO_HOME/paseo.db` is one SQLite file that the daemon opens at startup with `node:sqlite`
(`packages/server/src/server/database/`). Agent timelines are its only store today. Each store is a
`SchemaModule`: its own table-name prefix and an append-only list of migrations.
- **Migrations.** Startup runs every module's pending migrations in one transaction, so a failed
migration leaves the file as it was. `schema_versions` records each module's version and
`min_reader_version`. Mark a migration `breaking` when an older daemon cannot read the result,
for example a dropped or renamed column. An older daemon then refuses to start with
`DatabaseSchemaTooNewError`. Additive migrations leave older daemons working, and they ignore
modules they do not know. This matters because the app and the daemon update separately, and a
user can run an older daemon on the same `$PASEO_HOME`.
- **Failure.** A file that SQLite cannot open stops the daemon with `DatabaseOpenError`, which
names the path. The daemon does not delete or recreate the file.
- **Access.** The file holds every prompt and reply, so the daemon sets it and its `-wal` and `-shm`
files to mode `0600` on every open. SQLite gives the WAL files it creates the mode of the database
file.
- **Durability.** The database uses WAL with `synchronous = NORMAL`. A power loss can drop the
last commits but does not corrupt the file.
- **Checkpoints.** A checkpoint syncs the file to disk and takes up to 100 ms. SQLite's
auto-checkpoint runs it on the committing thread, which stalled the event loop during streaming.
The daemon turns it off and checkpoints from a worker thread with its own connection. If the
worker exits, the daemon turns auto-checkpoint back on.
- **Transactions.** `write` and `read` callbacks are synchronous, so a transaction never spans an
`await` and transactions never interleave.
- **Node.** `node:sqlite` needs Node 22.16 or later. Node 22 prints an experimental warning once,
when the daemon opens the database.
### Agent timelines
`AgentTimeline` owns each agent's history, and its SQLite backend stores the projected rows, the
source ranges, retirements, the open rewind, and provider children in `timeline_*` tables. The text
of a streamed assistant or reasoning message is stored as one chunk per source event, beside its
row, so a chunk never rewrites the message. An earlier file store rewrote the whole transcript on
every update. See [owned history](timeline-sync.md#owned-history).
---
## 2. Daemon Configuration
**Path:** `$PASEO_HOME/config.json`
+68 -11
View File
@@ -5,15 +5,9 @@ Agent chat delivery has two paths:
1. **Live stream** — `agent_stream` WebSocket messages for immediacy. These may be delta-shaped lifecycle updates.
2. **Authoritative history** — `fetch_agent_timeline_request` for correctness. This always returns full projected timeline items, never lifecycle deltas.
The daemon retains projected items in memory. Each source event advances the stream sequence,
then replaces the previous tool state or merges into the current text item. Intermediate payloads
are never retained for history or catch-up. Provider history is the durable transcript authority
and rebuilds the projection when an agent resumes.
Pagination bounds each read, not total resident history. Active and idle agents retain their
projected transcript; archive releases it and later history reads rebuild it from the provider.
Streaming overhead must remain proportional to the retained transcript. Cumulative text snapshots
must be released after their deltas have been consumed.
Pagination bounds each read, not total resident history. Streaming overhead must remain
proportional to the retained transcript. Cumulative text snapshots must be released after their
deltas have been consumed.
The invariants are:
@@ -32,6 +26,50 @@ bounded item is used for runtime timeline rows and live stream events. Provider
applies the same rule so reopening an agent cannot restore an oversized payload. Fetches apply it
again to assistant and reasoning rows the projection merges from many chunks.
## Owned history
The daemon owns each agent's history in `AgentTimeline`
(`packages/server/src/server/agent/timeline/`): one ordered history per agent, with each provider
child's descriptor and history in a child scope of the same agent. Each source event advances the
stream sequence, then replaces the previous tool state or merges into the current text item.
Intermediate payloads are never retained for history or catch-up.
History is append-only: rewind, import, reload and archive never delete or rewrite a row. Only
deleting the agent, or a provider removing one of its own children, deletes history.
- **Rewind** retires a range of rows. They leave the conversation and stay stored, in the same
epoch. See [Rewind retires rows](#rewind-retires-rows).
- **Provider history** is imported only into an agent that has no history. After that, resume
does not read it. Reload agent and Unarchive require the provider history to start with the
same prompt IDs and text in order. They then append whole new turns, starting at the next
prompt. Existing replies, including partial replies, stay as recorded. If the prompts differ,
for example because the provider stored expanded attachment text, the chat stays unchanged and
Paseo reports a mismatch. A provider child Paseo already holds, listed or retired, is never imported again.
- **Archive and reload** keep the history and the provider children. An archived chat reads them
without its provider. Opening a stored agent that has no provider session to resume starts its
first session on the same history.
- **Delete** removes the agent's history and every child's, retired ones included, before the
agent record. If the history cannot be removed, the request fails and the agent stays listed. The
user can keep using it and delete it again.
`epoch` is the stored history's identity, minted once when the history is created.
`AgentTimeline` serializes every operation of one agent, child scopes included, and keeps its
state in an `AgentTimelineBackend`: the sequence, the rows and retirements, prompt identities, the
open rewind, and the children. The backend contract suite is `agent-timeline.test.ts`, run over
`TIMELINE_CONTRACT_BACKENDS` in `timeline/testing.ts`. The daemon uses the SQLite backend in the
[daemon database](data-model.md#daemon-database). History, retirements, the open rewind, and
provider children survive a daemon restart in the same epoch, so clients keep their cursors. A
closed or archived agent holds no history in memory. Each fetch reads the page from the database
and starts no provider. An internal agent, such as the one that writes a commit message, keeps its
history in a memory backend instead, so it leaves nothing on disk. The memory backend also serves
tests.
An open rewind is stored with the history. Resuming an agent whose history holds one settles it
before the agent takes prompts: a recorded provider cut is committed, and an unknown outcome is
judged from the resumed provider history. When that history proves nothing, the rewind stays open
and the agent refuses prompts with the unknown-outcome error.
## Presence is not delivery
Client heartbeat reports presence:
@@ -168,7 +206,7 @@ or retry backoff. This cannot keep a mobile socket alive after the operating sys
bookkeeping without replacing timeline arrays, preserving an upward-scrolled viewport.
- When the page overlaps or is adjacent to the local end cursor, only projected items newer than
that cursor are applied. Already-covered rows are not replayed.
- A true middle gap, epoch change, or rewind atomically replaces stale canonical history with the
- A true middle gap or epoch change atomically replaces stale canonical history with the
latest tail. The replacement reconciles positioned live rows beyond its coverage and unresolved
local submissions; it never retains two discontiguous canonical ranges.
@@ -181,6 +219,24 @@ history replay. The pending approval UI can hide that tool from presentation, bu
must retain its position. Creating a new history card on rejection places it after the prompt that
rejected it; changing steer-event ordering would also put new assistant output before that prompt.
## Rewind retires rows
A conversation rewind commits a retirement `{ seq, retireFromSeq }`: active rows anchored in
`[retireFromSeq, seq)` leave the conversation, and `seq` is the retirement's own position in the
sequence. The provider children spawned by retired tool calls, and their descendants, are retired
in the same commit. They leave the listing, keep their history, and drop late provider events.
Clients learn of a retirement live through `agent.timeline.rewind`, and on pages through
`retirements`, which lists the retirements whose `seq` lies inside the page's span. The client
drops the rows it holds in that range; rows without a timeline position are unechoed local sends
and stay. Retired ranges and the retirement's `seq` count as covered, so forward cursors advance
through them. Tail, before and prompt-jump pages are served from active rows, so one served before
a retirement the client already applied is stale and is refetched (`viewed-timeline-sync.ts`).
Clients without `timeline_rewind_operations` cannot drop retired rows. For them the session derives
a wire epoch that changes with each retirement, so they take the destructive replacement they
always took on rewind. The shim is tagged `COMPAT(timelineRewindOperations)`.
## Provider child history
Child transcripts use the same projected-page reconciliation as the main conversation. The client
@@ -345,7 +401,7 @@ the draft-create handoff is the one boundary that also permits the legacy canoni
arrived first. Generic reducers and consumers do not reimplement message identity matching.
Ordinary bootstrap, same-epoch reset, and catch-up replacement preserve unmatched locally submitted
rows because a provider may never echo them. A known epoch change or rewind replaces history and
rows because a provider may never echo them. A known epoch change replaces history and
drops acknowledged local rows omitted by the new canonical epoch; every transaction not yet
acknowledged by the provider, and no other local row, crosses that destructive boundary. A cold
reset without an existing epoch is destructive because the client has no continuity anchor.
@@ -361,6 +417,7 @@ canonical assistant prefix, it stays in the head lane. No row may be returned in
## Relevant code
- Server owned history: `packages/server/src/server/agent/timeline/`
- Server live stream forwarding: `packages/server/src/server/session.ts`
- App sync planning: `packages/app/src/timeline/timeline-sync-plan.ts`
- App viewed-agent synchronization: `packages/app/src/timeline/viewed-timeline-sync.ts`
+1 -1
View File
@@ -1 +1 @@
sha256-TAVzJzziWDAapQkG4TLkLzOlodkdFNKSl3y/Tm9HB28=
sha256-IAhKhkolW4xvFvMaAEFdhYvPAhTm2azsqbGMKCKL3q0=
+20 -1
View File
@@ -45,6 +45,9 @@
"react-dom": "19.2.3",
"typescript": "^5.9.3",
"ws": "^8.20.0"
},
"engines": {
"node": ">=22.16.0"
}
},
"node_modules/@0no-co/graphql.web": {
@@ -39719,6 +39722,9 @@
"typescript": "^5.2.2",
"vitest": "^4.1.6",
"zx": "^8.8.5"
},
"engines": {
"node": ">=22.16.0"
}
},
"packages/cli/node_modules/@vitest/expect": {
@@ -40646,7 +40652,7 @@
"@playwright/test": "^1.56.1",
"@types/express": "^4.17.20",
"@types/markdown-it": "^14.2.0",
"@types/node": "^20.9.0",
"@types/node": "^22.16.0",
"@types/qrcode": "^1.5.6",
"@types/uuid": "^9.0.7",
"@types/ws": "^8.5.8",
@@ -40654,6 +40660,9 @@
"cross-env": "^10.1.0",
"tsx": "^4.6.0",
"vitest": "^4.1.6"
},
"engines": {
"node": ">=22.16.0"
}
},
"packages/server/node_modules/@esbuild/aix-ppc64": {
@@ -41101,6 +41110,16 @@
"@types/mdurl": "^2"
}
},
"packages/server/node_modules/@types/node": {
"version": "22.20.5",
"resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.5.tgz",
"integrity": "sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==",
"dev": true,
"license": "MIT",
"dependencies": {
"undici-types": "~6.21.0"
}
},
"packages/server/node_modules/@vitest/expect": {
"version": "4.1.6",
"resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.6.tgz",
+3
View File
@@ -169,5 +169,8 @@
"tiny-async-pool": {
"semver@^5": "5.7.2"
}
},
"engines": {
"node": ">=22.16.0"
}
}
@@ -13,6 +13,13 @@ import {
import { expectNearBottom, scrollChatAwayFromBottom } from "../support/helpers/agent-bottom-anchor";
import { holdRewindCompletion } from "../support/helpers/agent-timeline-gate";
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
import { userScrollsTimelineToHistoryStart } from "../support/helpers/timeline-pagination";
import {
closeWorkspaceAgentTab,
fetchAgentArchivedAt,
primeAdditionalPage,
resetSeededPageState,
} from "../support/helpers/archive-tab";
async function completeSubmittedTurn(
page: Page,
@@ -48,26 +55,102 @@ 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 submitted prompt without replaying history and preserves a human draft", async ({
test("rewinds a prompt in place on every open client and keeps a human draft", async ({
page,
}) => {
test.setTimeout(90_000);
test.setTimeout(150_000);
const retainedPrompt = "Keep this completed turn after rewind.";
const rewoundPrompt = "Remove this completed turn after rewind.";
const nextPrompt = "Continue after the rewind.";
const preservedDraft = "Keep this human draft after rewind.";
const agent = await seedMockAgentWorkspace({
repoPrefix: "message-rewind-roundtrip-",
title: "Message rewind roundtrip",
model: "ten-second-stream",
});
const otherClient = await page.context().newPage();
try {
const rewindCompletion = await holdRewindCompletion(page, agent.agentId);
await openAgentRoute(page, agent);
await expectComposerVisible(page);
await completeSubmittedTurn(page, agent, retainedPrompt);
const retainedMessage = await completeSubmittedTurn(page, agent, retainedPrompt);
const userMessage = await completeSubmittedTurn(page, agent, rewoundPrompt);
await test.step("a second client opens the same chat", async () => {
await openAgentOnAnotherClient(otherClient, agent);
await expectPrompts(otherClient, [retainedPrompt, rewoundPrompt]);
});
await markMounted(retainedMessage);
await scrollChatAwayFromBottom(page, {
deltaY: -900,
minDistanceFromBottom: 300,
@@ -76,19 +159,92 @@ test.describe("Agent message rewind", () => {
await blurComposerInput(page);
rewindCompletion.clearTimelineStreamCount();
const rewind = rewindConversation(page, userMessage, rewoundPrompt);
await rewindCompletion.waitForDelayedResponse();
await expect(page.getByTestId("rewind-menu-conversation")).toBeDisabled();
expect(rewindCompletion.timelineStreamCount()).toBe(0);
rewindCompletion.release();
await rewind;
await test.step("the rewind stays pending until the daemon answers", async () => {
const rewind = rewindConversation(page, userMessage, rewoundPrompt);
await rewindCompletion.waitForDelayedResponse();
await expect(page.getByTestId("rewind-menu-conversation")).toBeDisabled();
expect(rewindCompletion.timelineStreamCount()).toBe(0);
rewindCompletion.release();
await rewind;
});
await expect(page.getByTestId("user-message").filter({ hasText: rewoundPrompt })).toHaveCount(
0,
);
await expectComposerDraft(page, preservedDraft);
await expectComposerNotFocused(page);
await expectNearBottom(page);
await test.step("the rewound turn leaves without reloading the chat", async () => {
await expectPrompts(page, [retainedPrompt]);
await expectStillMounted(retainedMessage);
expect(rewindCompletion.timelineFetchCount()).toBe(0);
await expectComposerDraft(page, preservedDraft);
await expectComposerNotFocused(page);
await expectNearBottom(page);
await expectPrompts(otherClient, [retainedPrompt]);
});
await test.step("the next prompt appears once on both clients", async () => {
await completeSubmittedTurn(otherClient, agent, nextPrompt);
await expectPrompts(otherClient, [retainedPrompt, nextPrompt]);
await expectPrompts(page, [retainedPrompt, nextPrompt]);
});
await test.step("a reconnecting client loads the rewound conversation", async () => {
await otherClient.reload();
await expectPrompts(otherClient, [retainedPrompt, nextPrompt]);
});
} finally {
await otherClient.close();
await agent.cleanup();
}
});
test("keeps the rewound conversation through Reload agent, archive and unarchive", async ({
page,
}) => {
test.setTimeout(150_000);
const keptPrompt = "Keep this turn through reload and archive.";
const rewoundPrompt = "Rewind this turn before reloading.";
const nextPrompt = "Continue after the rewind, then reload.";
const agent = await seedMockAgentWorkspace({
repoPrefix: "message-rewind-reload-archive-",
title: "Message rewind reload archive",
model: "ten-second-stream",
});
try {
await openAgentRoute(page, agent);
await expectComposerVisible(page);
await completeSubmittedTurn(page, agent, keptPrompt);
const rewound = await completeSubmittedTurn(page, agent, rewoundPrompt);
await rewindConversation(page, rewound, rewoundPrompt);
await expectPrompts(page, [keptPrompt]);
await completeSubmittedTurn(page, agent, nextPrompt);
await expectPrompts(page, [keptPrompt, nextPrompt]);
await test.step("Reload agent keeps the 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]);
});
} finally {
await agent.cleanup();
}
@@ -2,8 +2,10 @@ import { expect, test } from "../support/fixtures";
import {
applyProfileFromPicker,
closeModelPicker,
expectAgentProfileNameDraft,
expectComposerDoesNotName,
expectAgentProfilesEmptyPrompt,
expectHostAgentProfiles,
expectProfileEditTooltip,
expectComposerMode,
expectCreateProfileFromModelRow,
@@ -14,8 +16,11 @@ import {
expectProfileReachableByScrolling,
expectProfileSearchResult,
expectProfileVisibleForProvider,
fillAgentProfileName,
openEditProfileFromModelRow,
openModelPicker,
openAgentProfilesFromEmptyPrompt,
removeOpenModalAgentProfileWithConfirm,
searchModelPicker,
seedAgentProfiles,
selectModelRow,
@@ -40,6 +45,26 @@ const PROFILE = {
const PROFILE_SUMMARY = "Mock Load Test · One minute stream · Approval test";
// Isolate this suite to the sole mock provider so it tests single-provider picker
// behavior deterministically regardless of which CLIs are installed on the host.
test.use({
e2eDaemonConfig: {
version: 1,
agents: {
providers: {
claude: { enabled: false },
codex: { enabled: false },
copilot: { enabled: false },
opencode: { enabled: false },
pi: { enabled: false },
omp: { enabled: false },
antigravity: { enabled: false },
hoplite: { enabled: false },
},
},
},
});
test.describe("Agent profiles in the model picker", () => {
test("an empty host still exposes agent profile settings from the picker", async ({ page }) => {
const seed = await seedAgentProfiles([]);
@@ -64,8 +89,8 @@ test.describe("Agent profiles in the model picker", () => {
page,
}) => {
const seed = await seedAgentProfiles([PROFILE]);
// A live agent is one provider's process, so the profile has to name that
// same provider or the picker will not offer it at all.
// With only the mock provider enabled on this host, the picker opens
// directly into its models and shows its pinned profile.
const workspace = await seedMockAgentWorkspace({
repoPrefix: "agent-profiles-picker-",
title: "Agent profiles picker",
@@ -146,10 +171,10 @@ test.describe("Agent profiles in the model picker", () => {
await openModelPicker(page);
await expectModelRowProfileActionBesideRow(page, oneMinute);
await expectCreateProfileFromModelRow(page, oneMinute);
await expectComposerModel(page, "Ten second stream");
await openModelPicker(page);
await selectModelRow(page, oneMinute);
await expectComposerModel(page, oneMinute.modelLabel);
await openModelPicker(page);
await selectModelRow(page, { provider: "mock", modelId: "ten-second-stream" });
await expectComposerModel(page, "Ten second stream");
} finally {
await workspace.cleanup();
await seed.restore();
@@ -234,4 +259,44 @@ test.describe("Agent profiles in the model picker", () => {
await seed.restore();
}
});
test("canceling Remove in the composer profile editor keeps the editor and draft open", async ({
page,
}) => {
const seed = await seedAgentProfiles([PROFILE]);
const workspace = await seedMockAgentWorkspace({
repoPrefix: "agent-profiles-remove-cancel-",
title: "Agent profiles remove cancel",
model: "ten-second-stream",
modeId: "load-test",
});
try {
await openAgentRoute(page, workspace);
await expectComposerVisible(page);
await openModelPicker(page);
await openEditProfileFromModelRow(page, {
provider: "mock",
modelId: "one-minute-stream",
});
await fillAgentProfileName(page, "Draft name");
await test.step("canceling Remove keeps the modal and draft intact", async () => {
await removeOpenModalAgentProfileWithConfirm(page, "dismiss");
await expect(page.getByTestId("agent-profile-edit-modal")).toBeVisible();
await expectAgentProfileNameDraft(page, "Draft name");
});
await test.step("confirming Remove deletes the profile and closes the modal", async () => {
await removeOpenModalAgentProfileWithConfirm(page, "accept");
await expect(page.getByTestId("agent-profile-edit-modal")).toHaveCount(0, {
timeout: 30_000,
});
await expectHostAgentProfiles([]);
});
} finally {
await workspace.cleanup();
await seed.restore();
}
});
});
@@ -1,19 +1,32 @@
import { test } from "../support/fixtures";
import { expect, test } from "../support/fixtures";
import {
browserBackWithConfirm,
browserHistoryJumpWithConfirm,
createAgentProfile,
createAgentProfileFromEmptyState,
duplicateOpenAgentProfileWithConfirm,
editAgentProfile,
expectAgentProfile,
expectAgentProfileForm,
expectAgentProfileNameDraft,
expectAgentProfileNotesDraft,
expectAgentProfileOrder,
expectAgentProfileTagsGone,
expectHostAgentProfiles,
expectNoAgentProfiles,
fillAgentProfileName,
fillAgentProfileNotes,
moveAgentProfileUp,
openAgentProfileEditor,
openAgentProfileSettings,
openCompactAgentProfileSettings,
openCreateAgentProfileEditor,
removeAgentProfile,
saveOpenAgentProfile,
seedAgentProfiles,
stageLegacyFavoritesForHostMigration,
switchSettingsSectionWithConfirm,
toggleAgentProfileCustomize,
} from "../support/helpers/agent-profiles";
const MOCK_PROVIDER_LABEL = "Mock Load Test";
@@ -125,4 +138,252 @@ test.describe("Agent profiles settings", () => {
await seed.restore();
}
});
test("remounting the profile form keeps draft text across resize and collapsible toggles", async ({
page,
}) => {
const seed = await seedAgentProfiles([
{
id: "agent_profile_e2e_remount",
name: "Original profile",
provider: "mock",
model: "one-minute-stream",
notes: "Original note",
},
]);
try {
await page.setViewportSize({ width: 1680, height: 900 });
await openAgentProfileSettings(page);
await test.step("drawer-to-modal and compact resizes keep the edited name and save it", async () => {
await openAgentProfileEditor(page, "Original profile");
await expect(page.getByTestId("agent-profile-drawer")).toBeVisible();
await fillAgentProfileName(page, "Draft rename");
await page.setViewportSize({ width: 1000, height: 900 });
await expect(page.getByTestId("agent-profile-edit-modal")).toBeVisible({ timeout: 30_000 });
await expectAgentProfileNameDraft(page, "Draft rename");
await page.setViewportSize({ width: 390, height: 844 });
await expect(page.getByTestId("agent-profile-edit-modal")).toBeVisible({ timeout: 30_000 });
await expectAgentProfileNameDraft(page, "Draft rename");
await saveOpenAgentProfile(page);
await expectAgentProfile(page, {
name: "Draft rename",
tags: [MOCK_PROVIDER_LABEL, "One minute stream"],
notes: "Original note",
});
});
await test.step("collapsing and reopening advanced settings keeps the draft note", async () => {
await page.setViewportSize({ width: 1000, height: 900 });
await openCreateAgentProfileEditor(page);
await expect(page.getByTestId("agent-profile-edit-modal")).toBeVisible({ timeout: 30_000 });
await toggleAgentProfileCustomize(page);
await fillAgentProfileNotes(page, "Draft routing note");
await toggleAgentProfileCustomize(page);
await toggleAgentProfileCustomize(page);
await expectAgentProfileNotesDraft(page, "Draft routing note");
});
} finally {
await seed.restore();
}
});
test("duplicating while editing asks before discarding unsaved changes", async ({ page }) => {
const seed = await seedAgentProfiles([
{
id: "agent_profile_e2e_duplicate",
name: "UI work",
provider: "mock",
model: "one-minute-stream",
},
]);
try {
await page.setViewportSize({ width: 1680, height: 900 });
await openAgentProfileSettings(page);
await openAgentProfileEditor(page, "UI work");
await expect(page.getByTestId("agent-profile-drawer")).toBeVisible();
await fillAgentProfileName(page, "Draft name");
await test.step("dismissing the prompt keeps the draft and does not create a copy", async () => {
await duplicateOpenAgentProfileWithConfirm(page, "dismiss");
await expectAgentProfileNameDraft(page, "Draft name");
await expectAgentProfileOrder(page, ["UI work"]);
});
await test.step("accepting the prompt creates and opens the copy", async () => {
await duplicateOpenAgentProfileWithConfirm(page, "accept");
await expectAgentProfileOrder(page, ["UI work", "UI work (copy)"]);
await expectAgentProfileNameDraft(page, "UI work (copy)");
});
} finally {
await seed.restore();
}
});
test("docked drawer allows roster search and section switches ask before discarding a draft", async ({
page,
}) => {
const seed = await seedAgentProfiles([
{
id: "agent_profile_e2e_docked_1",
name: "UI work",
provider: "mock",
model: "one-minute-stream",
},
{
id: "agent_profile_e2e_docked_2",
name: "Deep review",
provider: "mock",
model: "five-minute-stream",
},
]);
try {
await page.setViewportSize({ width: 1680, height: 900 });
await openAgentProfileSettings(page);
await openAgentProfileEditor(page, "UI work");
await expect(page.getByTestId("agent-profile-drawer")).toBeVisible();
await test.step("typing in roster search works while the docked drawer is open", async () => {
const searchInput = page.getByTestId("agent-profiles-search-input");
await searchInput.click();
await page.keyboard.type("Deep");
await expect(searchInput).toHaveValue("Deep");
await expect(page.getByTestId("agent-profile-drawer")).toBeVisible();
await expectAgentProfileOrder(page, ["Deep review"]);
await page.getByTestId("agent-profiles-search-clear").click();
});
await test.step("browser Back asks before discarding a draft and canceling keeps route and draft", async () => {
await fillAgentProfileName(page, "Unsaved browser back edit");
const profilesUrl = page.url();
await browserBackWithConfirm(page, "dismiss");
await expect(page).toHaveURL(profilesUrl, { timeout: 15_000 });
await expect(page.getByTestId("agent-profile-drawer")).toBeVisible();
await expectAgentProfileNameDraft(page, "Unsaved browser back edit");
});
await test.step("switching Settings sections asks before discarding an edited draft", async () => {
await fillAgentProfileName(page, "Unsaved sidebar edit");
await switchSettingsSectionWithConfirm(page, "Agents", "dismiss");
await expect(page.getByTestId("agent-profile-drawer")).toBeVisible();
await expectAgentProfileNameDraft(page, "Unsaved sidebar edit");
await switchSettingsSectionWithConfirm(page, "Agents", "accept");
await expect(page.getByTestId("agent-profile-drawer")).toHaveCount(0, { timeout: 30_000 });
await expect(page.getByTestId("settings-detail-header-title")).toHaveText("Agents");
});
await test.step("confirming browser Back leaves Agent profiles and discards the draft", async () => {
await page.getByRole("button", { name: "Agent profiles", exact: true }).click();
await expect(page.getByTestId("agent-profiles-card")).toBeVisible({ timeout: 30_000 });
await openAgentProfileEditor(page, "UI work");
await fillAgentProfileName(page, "Discard on browser back");
const profilesUrl = page.url();
await browserBackWithConfirm(page, "accept");
await expect(page).not.toHaveURL(profilesUrl, { timeout: 15_000 });
await expect(page.getByTestId("agent-profile-drawer")).toHaveCount(0, { timeout: 30_000 });
});
} finally {
await seed.restore();
}
});
test("canceling a multi-step Back jump keeps intervening browser history and confirming reaches the destination", async ({
page,
}) => {
const seed = await seedAgentProfiles([
{
id: "agent_profile_e2e_multistep",
name: "UI work",
provider: "mock",
model: "one-minute-stream",
},
]);
try {
// Narrow viewport pushes Open project -> Settings -> Agent profiles onto history.
await page.setViewportSize({ width: 390, height: 844 });
await openCompactAgentProfileSettings(page);
const profilesUrl = page.url();
await openAgentProfileEditor(page, "UI work");
await fillAgentProfileName(page, "Unsaved multi-step edit");
await test.step("canceling a two-step Back jump keeps Agent profiles, draft, and Settings in history", async () => {
await browserHistoryJumpWithConfirm(page, -2, "dismiss");
await expect(page).toHaveURL(profilesUrl, { timeout: 15_000 });
await expect(page.getByTestId("agent-profile-edit-modal")).toBeVisible();
await expectAgentProfileNameDraft(page, "Unsaved multi-step edit");
});
await test.step("canceling a two-step Back jump after reload still restores the Agent profiles URL", async () => {
await page.reload();
await expect(page.getByTestId("agent-profiles-card")).toBeVisible({ timeout: 30_000 });
await openAgentProfileEditor(page, "UI work");
await fillAgentProfileName(page, "Post-reload draft");
await browserHistoryJumpWithConfirm(page, -2, "dismiss");
await expect(page).toHaveURL(profilesUrl, { timeout: 15_000 });
await expect(page.getByTestId("agent-profile-edit-modal")).toBeVisible();
await expectAgentProfileNameDraft(page, "Post-reload draft");
});
await test.step("confirming a two-step Back jump lands directly on the selected destination", async () => {
await browserHistoryJumpWithConfirm(page, -2, "accept");
await expect(page).toHaveURL(/\/open-project/, { timeout: 15_000 });
await expect(page.getByTestId("agent-profile-edit-modal")).toHaveCount(0, {
timeout: 30_000,
});
});
await test.step("forward navigation confirms the intervening Settings entry survived", async () => {
await page.goForward();
await expect(page).toHaveURL(/\/settings(?:\?|$)/, { timeout: 15_000 });
});
} finally {
await seed.restore();
}
});
test("canceling an untouched provider-and-model-only profile closes without a discard prompt", async ({
page,
}) => {
const seed = await seedAgentProfiles([
{
id: "legacy_favorite:mock:one-minute-stream",
name: "One minute stream",
provider: "mock",
model: "one-minute-stream",
},
]);
let dialogTriggered = false;
const onDialog = async (dialog: { dismiss: () => Promise<void> }) => {
dialogTriggered = true;
await dialog.dismiss();
};
page.on("dialog", onDialog);
try {
await page.setViewportSize({ width: 1680, height: 900 });
await openAgentProfileSettings(page);
await openAgentProfileEditor(page, "One minute stream");
await expect(page.getByTestId("agent-profile-drawer")).toBeVisible();
await page.getByTestId("agent-profile-cancel-button").click();
await expect(page.getByTestId("agent-profile-drawer")).toHaveCount(0, { timeout: 30_000 });
expect(dialogTriggered).toBe(false);
} finally {
page.off("dialog", onDialog);
await seed.restore();
}
});
});
@@ -372,6 +372,25 @@ test.describe("Plugin sidebar items", () => {
await expect(page.getByText("Plugin failed", { exact: false })).toHaveCount(0);
});
test("a plugin screen keeps the sidebar toggle before its title", async ({ page }) => {
await page.setViewportSize(WIDE);
await gotoWorkspace(page, workspaceId);
await expect(headerRow(page, SHOWCASE_PLUGIN_ID, "deploys")).toBeVisible({ timeout: 30_000 });
await runCommand(page, "Open plugin workspaces");
await expect(screenTitle(page)).toHaveText("Workspaces");
await page.keyboard.press("ControlOrMeta+b");
await expect(page.getByTestId("sidebar-global-new-workspace")).not.toBeVisible();
await expect(visibleTestId(page, "menu-button")).toBeVisible();
const toggle = await boxOf(visibleTestId(page, "menu-button"));
const title = await boxOf(screenTitle(page));
expect(toggle.x + toggle.width).toBeLessThanOrEqual(title.x);
await qaScreenshot(page, "plugin-screen-sidebar-collapsed");
await visibleTestId(page, "menu-button").click();
await expect(page.getByTestId("sidebar-global-new-workspace")).toBeVisible();
});
test("a header row's shortcut hint presses the row", async ({ page }) => {
await page.setViewportSize(WIDE);
await gotoWorkspace(page, workspaceId);
@@ -0,0 +1,476 @@
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 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 browserViewport = page.getByTestId("agent-controls-model-browser-viewport");
await expect(browserViewport).toBeVisible({ timeout: 30_000 });
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",
});
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");
});
await test.step("submitting commits the switch in place with clean user display text and inspectable marker", async () => {
await stageDirectProviderDesktop(page);
const switchedMessage = await completeDirectTurn(page, workspace, postSwitchPrompt);
expect(page.url()).toBe(initialUrl);
await expect(page.getByTestId("staged-provider-switch-banner")).toHaveCount(0);
await expectWorkspaceAgentConfiguration(workspace, {
id: workspace.agentId,
provider: DIRECT_PROVIDER.id,
model: DIRECT_PROVIDER.modelId,
modeId: "build",
});
// Clean display text: handoff summary must never leak into the visible user bubble.
await expect(switchedMessage).toContainText(postSwitchPrompt);
await expect(switchedMessage).not.toContainText("<chat-history-summary>");
// Direct provider echoes its prompt, proving bounded pre-switch context was attached.
const directReply = page
.getByTestId("assistant-message")
.filter({ hasText: "Echo:" })
.last();
await expect(directReply).toContainText(preSwitchPrompt);
await expect(directReply).toContainText(postSwitchPrompt);
// Switch marker is visible and expands to show context handoff details.
const marker = page.getByTestId("provider-switch-marker");
await expect(marker).toBeVisible({ timeout: 30_000 });
await marker.scrollIntoViewIfNeeded();
await marker.getByTestId("provider-switch-marker-toggle").click();
const details = marker.getByTestId("provider-switch-marker-details");
await expect(details).toBeVisible();
await expect(details).toContainText("Mock");
await expect(details).toContainText(DIRECT_PROVIDER.label);
await marker.scrollIntoViewIfNeeded();
await expectNoHorizontalOverflow(page);
await captureQaScreenshot(page, "desktop-switched-expanded.png");
await marker.getByTestId("provider-switch-marker-toggle").click();
await expect(details).toHaveCount(0);
});
await test.step("switching back to Mock enforces segment-scoped rewind and preserves pre-switch turns", async () => {
const backToMockPrompt = "Switch back to Mock for segment-scoped rewind.";
await stageProviderDesktop(page, "mock", "ten-second-stream");
await expect(page.getByTestId("staged-provider-switch-banner")).toContainText("Mock");
const backToMockMessage = await completeMockTurn(page, workspace, backToMockPrompt);
await expect(backToMockMessage).not.toContainText("<chat-history-summary>");
await expect(page.getByTestId("provider-switch-marker")).toHaveCount(2, {
timeout: 30_000,
});
await expectWorkspaceAgentConfiguration(workspace, {
id: workspace.agentId,
provider: "mock",
model: "ten-second-stream",
modeId: "load-test",
});
// Pre-switch prompts from earlier segments must not expose rewind even though Mock supports it.
const preSwitchMessage = page
.getByTestId("user-message")
.filter({ hasText: preSwitchPrompt });
await preSwitchMessage.scrollIntoViewIfNeeded();
await preSwitchMessage.getByText(preSwitchPrompt, { exact: true }).hover();
await expect(
preSwitchMessage.getByRole("button", { name: "Rewind to this message", exact: true }),
).toHaveCount(0);
const directMessage = page
.getByTestId("user-message")
.filter({ hasText: postSwitchPrompt });
await directMessage.scrollIntoViewIfNeeded();
await directMessage.getByText(postSwitchPrompt, { exact: true }).hover();
await expect(
directMessage.getByRole("button", { name: "Rewind to this message", exact: true }),
).toHaveCount(0);
// Post-switch prompt on Mock CAN rewind without retiring earlier segments or markers.
await backToMockMessage.scrollIntoViewIfNeeded();
await rewindConversation(page, backToMockMessage, backToMockPrompt);
await expect(
page.getByTestId("user-message").filter({ hasText: backToMockPrompt }),
).toHaveCount(0, { timeout: 30_000 });
await expect(
page.getByTestId("user-message").filter({ hasText: preSwitchPrompt }),
).toBeVisible();
await expect(
page.getByTestId("user-message").filter({ hasText: postSwitchPrompt }),
).toBeVisible();
await expect(page.getByTestId("provider-switch-marker")).toHaveCount(2);
// Continuing in the now-empty active segment completes cleanly.
const retriedMessage = await completeMockTurn(page, workspace, postRewindPrompt);
await expect(retriedMessage).not.toContainText("<chat-history-summary>");
});
await test.step("reload preserves the switched provider, markers, and rewind boundary", async () => {
await page.reload();
await expectComposerVisible(page);
await expectComposerModel(page, "Ten second stream");
await expectSwitchMarkerCountAfterScroll(page, 2);
const reloadedDirect = page
.getByTestId("user-message")
.filter({ hasText: postSwitchPrompt });
await expect(reloadedDirect).toBeVisible();
await expect(
page.getByTestId("user-message").filter({ hasText: postRewindPrompt }),
).toBeVisible();
await reloadedDirect.scrollIntoViewIfNeeded();
await reloadedDirect.getByText(postSwitchPrompt, { exact: true }).hover();
await expect(
reloadedDirect.getByRole("button", { name: "Rewind to this message", exact: true }),
).toHaveCount(0);
});
} finally {
await workspace.cleanup();
}
});
test("stages a switch mid-turn, queues the prompt, and switches cleanly between turns", async ({
page,
}) => {
test.setTimeout(150_000);
await page.setViewportSize({ width: 1280, height: 800 });
const runningPrompt = "Run a ten-second mock turn first.";
const queuedPrompt = "Queued handoff prompt for Direct provider.";
const workspace = await seedMockAgentWorkspace({
repoPrefix: "provider-switch-midturn-",
title: "Provider switch midturn",
model: "ten-second-stream",
modeId: "load-test",
});
try {
await openAgentRoute(page, workspace);
await expectComposerVisible(page);
await submitMessage(page, runningPrompt);
await expectAgentReadyToInterrupt(page);
// Stage Direct provider while Mock is actively streaming.
await stageDirectProviderDesktop(page);
await expectWorkspaceAgentConfiguration(workspace, {
id: workspace.agentId,
provider: "mock",
model: "ten-second-stream",
modeId: "load-test",
});
// Submitting queues the prompt instead of racing the live turn.
await submitMessage(page, queuedPrompt);
await expectQueuedMessageButton(page);
// Once the mock turn completes, the queue drains and commits the switch.
await expect(page.getByTestId("provider-switch-marker")).toBeVisible({ timeout: 45_000 });
await expect(page.getByTestId("staged-provider-switch-banner")).toHaveCount(0, {
timeout: 30_000,
});
await expect(
page.getByTestId("assistant-message").filter({ hasText: queuedPrompt }).last(),
).toBeVisible({ timeout: 30_000 });
await expectAgentIdle(page);
await expectWorkspaceAgentConfiguration(workspace, {
id: workspace.agentId,
provider: DIRECT_PROVIDER.id,
model: DIRECT_PROVIDER.modelId,
modeId: "build",
});
} finally {
await workspace.cleanup();
}
});
test("switches providers cleanly on a compact viewport with zero horizontal overflow", async ({
page,
}) => {
test.setTimeout(150_000);
await page.setViewportSize({ width: 390, height: 844 });
const preSwitchPrompt = "Compact turn on Mock.";
const postSwitchPrompt = "Compact handoff on Direct.";
const workspace = await seedMockAgentWorkspace({
repoPrefix: "provider-switch-compact-",
title: "Provider switch compact",
model: "e2e-fast-stream",
modeId: "load-test",
});
try {
await openAgentRoute(page, workspace);
await expectComposerVisible(page);
await submitMessageWithButton(page, preSwitchPrompt);
await expect(
page.getByTestId("user-message").filter({ hasText: preSwitchPrompt }),
).toBeVisible({ timeout: 30_000 });
const firstFinish = await workspace.client.waitForFinish(workspace.agentId, 30_000);
expect(firstFinish.status).toBe("idle");
await expectAgentIdle(page);
await stageDirectProviderCompact(page);
await expectNoHorizontalOverflow(page);
await captureQaScreenshot(page, "compact-staged-switch.png");
const switchedMessage = await completeDirectTurn(page, workspace, postSwitchPrompt, {
useSendButton: true,
});
await expect(switchedMessage).not.toContainText("<chat-history-summary>");
const marker = page.getByTestId("provider-switch-marker");
await expect(marker).toBeVisible({ timeout: 30_000 });
await marker.scrollIntoViewIfNeeded();
const toggle = marker.getByTestId("provider-switch-marker-toggle");
const toggleBox = await toggle.boundingBox();
expect(toggleBox).not.toBeNull();
expect((toggleBox?.x ?? 0) + (toggleBox?.width ?? 0)).toBeLessThanOrEqual(390);
await toggle.click();
await expect(marker.getByTestId("provider-switch-marker-details")).toBeVisible();
await marker.scrollIntoViewIfNeeded();
await expectNoHorizontalOverflow(page);
await captureQaScreenshot(page, "compact-switched-expanded.png");
} finally {
await workspace.cleanup();
}
});
});
@@ -235,7 +235,7 @@ test.describe("Rewind sheet", () => {
await expect(page.getByTestId("rewind-menu-content")).toHaveCount(0);
await expect(userMessage(page, secondPrompt)).toHaveCount(0);
await expect(page.getByText("Cycle 1", { exact: true })).toHaveCount(0);
await expectUserMessageCount(page, 1);
await expectUserMessageCount(page, 0);
await expectComposerDraft(page, firstPrompt);
await expectComposerFocused(page);
@@ -243,7 +243,7 @@ test.describe("Rewind sheet", () => {
await expectUserMessageVisible(page, replacementPrompt);
await expect(userMessage(page, secondPrompt)).toHaveCount(0);
await expect(page.getByText("Cycle 1", { exact: true })).toHaveCount(0);
await expectUserMessageCount(page, 2);
await expectUserMessageCount(page, 1);
await fillComposerDraft(page, "");
await composerLocator(page).evaluate((element) => element.blur());
@@ -254,7 +254,19 @@ test.describe("Rewind sheet", () => {
await expect(page.getByTestId("rewind-menu-content")).toHaveCount(0);
await expectComposerDraft(page, "");
await expectComposerNotFocused(page);
await expectUserMessageCount(page, 2);
await expectUserMessageCount(page, 1);
const preservedDraft = "Keep this human draft after rewind.";
await fillComposerDraft(page, preservedDraft);
await composerLocator(page).evaluate((element) => element.blur());
await userMessage(page, replacementPrompt).hover();
await page.getByTestId("rewind-menu-trigger").last().click();
await expect(page.getByTestId("rewind-menu-content")).toBeVisible();
await selectRewindOption(page, "Rewind files");
await expect(page.getByTestId("rewind-menu-content")).toHaveCount(0);
await expectComposerDraft(page, preservedDraft);
await expectComposerNotFocused(page);
await expectUserMessageCount(page, 1);
await fillComposerDraft(page, "");
await composerLocator(page).evaluate((element) => element.blur());
@@ -265,7 +277,7 @@ test.describe("Rewind sheet", () => {
await expect(page.getByTestId("rewind-menu-content")).toHaveCount(0);
await expectComposerDraft(page, replacementPrompt);
await expectComposerFocused(page);
await expectUserMessageCount(page, 1);
await expectUserMessageCount(page, 0);
} finally {
await session.cleanup();
}
@@ -15,8 +15,8 @@ press "id=\"model-provider-${PROVIDER_ID}\""
wait "id=\"compact-model-list\"" 3000
# The row's profile action sits inside Android's independent scroll viewport.
press "id=\"model-create-profile-${PROVIDER_ID}-${PROFILE_MODEL_ID}\""
wait "text=\"Add agent profile\"" 5000
# Closing the form keeps the remembered model: the tap did not also select the row.
back
wait "id=\"combined-model-selector\" label=\"Select model (${MODEL_LABEL})\"" 3000
wait "id=\"model-profile-created-toast\"" 5000
# Undo removes the created profile after selecting the model and closing the picker.
press "id=\"model-profile-created-undo\""
wait "id=\"combined-model-selector\"" 3000
close
@@ -142,8 +142,22 @@ export async function openAgentProfileSettings(page: Page): Promise<void> {
await gotoAppShell(page);
await openSettings(page);
await openSettingsHost(page, serverId);
await page.getByRole("button", { name: "Agents", exact: true }).click();
await expectAppRoute(page, buildSettingsHostSectionRoute(serverId, "agents"));
await page.getByRole("button", { name: "Agent profiles", exact: true }).click();
await expectAppRoute(page, buildSettingsHostSectionRoute(serverId, "agent-profiles"));
await expect(page.getByTestId("agent-profiles-card")).toBeVisible({ timeout: 30_000 });
}
/** Reach agent profiles on a compact viewport so Open project -> Settings -> Agent profiles are pushed. */
export async function openCompactAgentProfileSettings(page: Page): Promise<void> {
const serverId = getServerId();
await gotoAppShell(page);
await page.getByRole("button", { name: "Open menu", exact: true }).click();
const settingsButton = page.locator('[data-testid="sidebar-settings"]:visible').first();
await expect(settingsButton).toBeVisible({ timeout: 30_000 });
await settingsButton.click();
await expect(page).toHaveURL(/\/settings(?:\?|$)/, { timeout: 30_000 });
await page.getByRole("button", { name: "Agent profiles", exact: true }).click();
await expectAppRoute(page, buildSettingsHostSectionRoute(serverId, "agent-profiles"));
await expect(page.getByTestId("agent-profiles-card")).toBeVisible({ timeout: 30_000 });
}
@@ -156,7 +170,9 @@ export async function expectNoAgentProfiles(page: Page): Promise<void> {
// ─── Settings: the profile list ────────────────────────────────────────────
export function agentProfileRow(page: Page, name: string): Locator {
return page.locator('[data-testid^="agent-profile-row-"]').filter({ hasText: name });
return page
.locator('[data-testid^="agent-profile-row-"]')
.filter({ has: page.getByText(name, { exact: true }) });
}
export async function expectAgentProfile(
@@ -165,7 +181,9 @@ export async function expectAgentProfile(
): Promise<void> {
const row = agentProfileRow(page, expected.name);
await expect(row).toBeVisible({ timeout: 30_000 });
await expect(row.getByText(expected.tags.join(" · "), { exact: true })).toBeVisible();
for (const tag of expected.tags) {
await expect(row).toContainText(tag);
}
if (expected.notes !== undefined) {
await expect(row.getByText(expected.notes, { exact: true })).toBeVisible();
}
@@ -177,7 +195,7 @@ export async function expectAgentProfileTagsGone(
): Promise<void> {
const row = agentProfileRow(page, input.name);
for (const tag of input.tags) {
await expect(row.getByText(tag, { exact: true })).toHaveCount(0);
await expect(row).not.toContainText(tag);
}
}
@@ -196,12 +214,22 @@ export async function expectAgentProfileOrder(page: Page, names: string[]): Prom
.toEqual(names);
}
async function openRowActionMenu(page: Page, name: string): Promise<void> {
const row = agentProfileRow(page, name);
await row.hover();
const trigger = row.locator('[data-testid^="agent-profile-menu-"]');
await expect(trigger).toBeVisible({ timeout: 15_000 });
await trigger.click();
}
export async function moveAgentProfileUp(page: Page, name: string): Promise<void> {
await agentProfileRow(page, name).getByRole("button", { name: "Move up", exact: true }).click();
await openRowActionMenu(page, name);
await page.getByRole("menuitem", { name: "Move up", exact: true }).click();
}
export async function moveAgentProfileDown(page: Page, name: string): Promise<void> {
await agentProfileRow(page, name).getByRole("button", { name: "Move down", exact: true }).click();
await openRowActionMenu(page, name);
await page.getByRole("menuitem", { name: "Move down", exact: true }).click();
}
/**
@@ -215,12 +243,13 @@ export async function removeAgentProfile(page: Page, name: string): Promise<void
await dialog.accept();
return message;
});
await agentProfileRow(page, name).getByRole("button", { name: "Remove", exact: true }).click();
await openRowActionMenu(page, name);
await page.getByRole("menuitem", { name: "Remove", exact: true }).click();
expect(await dialogMessage).toContain(`Remove "${name}"?`);
await expect(agentProfileRow(page, name)).toHaveCount(0, { timeout: 30_000 });
}
// ─── Settings: the edit modal ──────────────────────────────────────────────
// ─── Settings: the inspector drawer / edit sheet ───────────────────────────
export interface AgentProfileDraft {
name?: string;
@@ -231,62 +260,96 @@ export interface AgentProfileDraft {
notes?: string;
}
function editModal(page: Page): Locator {
return page.getByTestId("agent-profile-edit-modal");
function editSurface(page: Page): Locator {
return page.locator(
'[data-testid="agent-profile-drawer"], [data-testid="agent-profile-edit-modal"]',
);
}
async function chooseSelectFieldOption(
page: Page,
input: { field: "provider" | "model" | "mode" | "thinking"; option: string },
input: { field: "model" | "mode" | "thinking"; option: string },
): Promise<void> {
await editModal(page).getByTestId(`agent-profile-${input.field}-trigger`).click();
await editSurface(page).getByTestId(`agent-profile-${input.field}-trigger`).click();
const option = page
.getByTestId("combobox-desktop-container")
.getByRole("button", { name: input.option, exact: true });
await expect(option).toBeVisible({ timeout: 30_000 });
await option.click();
await expect(
page.getByRole("button", { name: `${capitalize(input.field)} (${input.option})` }),
).toBeVisible({ timeout: 30_000 });
}
function capitalize(value: string): string {
return value.charAt(0).toUpperCase() + value.slice(1);
async function ensureCustomizeExpanded(surface: Locator): Promise<void> {
const toggle = surface.getByTestId("agent-profile-customize-toggle");
if ((await toggle.count()) > 0 && (await toggle.isVisible())) {
await toggle.click();
}
}
async function chooseProfileModel(
page: Page,
input: { provider?: string; model?: string },
): Promise<void> {
await editSurface(page).getByTestId("agent-profile-model-trigger").click();
const container = page.getByTestId("combobox-desktop-container");
await expect(container).toBeVisible({ timeout: 30_000 });
if (input.provider) {
const providerRow = container.getByRole("button", {
name: new RegExp(escapeForRegex(input.provider)),
});
if ((await providerRow.count()) > 0 && (await providerRow.first().isVisible())) {
await providerRow.first().click();
}
}
const targetLabel = input.model ?? input.provider;
if (targetLabel) {
const option = container
.getByRole("button", { name: new RegExp(escapeForRegex(targetLabel)) })
.first();
await expect(option).toBeVisible({ timeout: 30_000 });
await option.click();
}
}
async function fillAgentProfileForm(page: Page, draft: AgentProfileDraft): Promise<void> {
const modal = editModal(page);
const surface = editSurface(page);
// Model first: CombinedModelSelector sets provider + model and auto-suggests defaults.
if (draft.model !== undefined || draft.provider !== undefined) {
await chooseProfileModel(page, { provider: draft.provider, model: draft.model });
}
if (draft.name !== undefined) {
await modal.getByRole("textbox", { name: "Name", exact: true }).fill(draft.name);
await surface.getByRole("textbox", { name: "Name", exact: true }).fill(draft.name);
}
// Provider first: it resets every provider-scoped field below it.
if (draft.provider !== undefined) {
await chooseSelectFieldOption(page, { field: "provider", option: draft.provider });
}
// Thinking after model: thinking levels hang off the model, and switching the
// model drops a level the new one does not offer.
if (draft.model !== undefined) {
await chooseSelectFieldOption(page, { field: "model", option: draft.model });
}
if (draft.thinking !== undefined) {
await chooseSelectFieldOption(page, { field: "thinking", option: draft.thinking });
if (draft.thinking !== undefined || draft.mode !== undefined || draft.notes !== undefined) {
await ensureCustomizeExpanded(surface);
}
if (draft.mode !== undefined) {
await chooseSelectFieldOption(page, { field: "mode", option: draft.mode });
}
if (draft.thinking !== undefined) {
const thinkingContainer = surface.getByTestId("agent-profile-thinking-field");
const segmentButton = thinkingContainer.getByRole("button", {
name: draft.thinking,
exact: true,
});
if ((await segmentButton.count()) > 0) {
await segmentButton.click();
} else {
await chooseSelectFieldOption(page, { field: "thinking", option: draft.thinking });
}
}
if (draft.notes !== undefined) {
await modal.getByRole("textbox", { name: "When to use", exact: true }).fill(draft.notes);
await surface.getByRole("textbox", { name: "When to use", exact: true }).fill(draft.notes);
}
}
async function saveAgentProfile(page: Page): Promise<void> {
await editModal(page).getByRole("button", { name: "Save", exact: true }).click();
await expect(editModal(page)).toHaveCount(0, { timeout: 30_000 });
await page.getByTestId("agent-profile-save-button").click();
await expect(editSurface(page)).toHaveCount(0, { timeout: 30_000 });
}
export async function createAgentProfile(page: Page, draft: AgentProfileDraft): Promise<void> {
await page.getByRole("button", { name: "Add agent profile", exact: true }).click();
await expect(editModal(page)).toBeVisible({ timeout: 30_000 });
await page.getByTestId("agent-profiles-add-button").click();
await expect(editSurface(page)).toBeVisible({ timeout: 30_000 });
await fillAgentProfileForm(page, draft);
await saveAgentProfile(page);
}
@@ -299,7 +362,7 @@ export async function createAgentProfileFromEmptyState(
.getByTestId("agent-profiles-card")
.getByRole("button", { name: "New profile", exact: true })
.click();
await expect(editModal(page)).toBeVisible({ timeout: 30_000 });
await expect(editSurface(page)).toBeVisible({ timeout: 30_000 });
await fillAgentProfileForm(page, draft);
await saveAgentProfile(page);
}
@@ -309,46 +372,183 @@ export async function editAgentProfile(
name: string,
changes: AgentProfileDraft,
): Promise<void> {
await agentProfileRow(page, name)
.getByRole("button", { name: "Edit profile", exact: true })
.click();
await expect(editModal(page)).toBeVisible({ timeout: 30_000 });
await agentProfileRow(page, name).click();
await expect(editSurface(page)).toBeVisible({ timeout: 30_000 });
await fillAgentProfileForm(page, changes);
await saveAgentProfile(page);
}
/** Opens the modal for a profile purely to read back what it stored. */
export async function openAgentProfileEditor(page: Page, name: string): Promise<void> {
await agentProfileRow(page, name).click();
await expect(editSurface(page)).toBeVisible({ timeout: 30_000 });
}
export async function openCreateAgentProfileEditor(page: Page): Promise<void> {
await page.getByTestId("agent-profiles-add-button").click();
await expect(editSurface(page)).toBeVisible({ timeout: 30_000 });
}
export async function fillAgentProfileName(page: Page, name: string): Promise<void> {
await page.getByRole("textbox", { name: "Name", exact: true }).fill(name);
}
export async function expectAgentProfileNameDraft(page: Page, name: string): Promise<void> {
await expect(page.getByRole("textbox", { name: "Name", exact: true })).toHaveValue(name);
}
export async function toggleAgentProfileCustomize(page: Page): Promise<void> {
await page.getByTestId("agent-profile-customize-toggle").click();
}
export async function fillAgentProfileNotes(page: Page, notes: string): Promise<void> {
await page.getByRole("textbox", { name: "When to use", exact: true }).fill(notes);
}
export async function expectAgentProfileNotesDraft(page: Page, notes: string): Promise<void> {
await expect(page.getByRole("textbox", { name: "When to use", exact: true })).toHaveValue(notes);
}
export async function saveOpenAgentProfile(page: Page): Promise<void> {
await saveAgentProfile(page);
}
export async function duplicateOpenAgentProfileWithConfirm(
page: Page,
decision: "accept" | "dismiss",
): Promise<void> {
const dialogMessage = page.waitForEvent("dialog").then(async (dialog) => {
const message = dialog.message();
if (decision === "accept") {
await dialog.accept();
} else {
await dialog.dismiss();
}
return message;
});
await page.getByTestId("agent-profile-drawer-more").click();
await page.getByTestId("agent-profile-drawer-duplicate").click();
expect(await dialogMessage).toMatch(/discard|unsaved/i);
}
export async function openEditProfileFromModelRow(
page: Page,
input: { provider: string; modelId: string },
): Promise<void> {
const row = modelRow(page, input);
await row.hover();
const editButton = pickerViewport(page).getByTestId(
`model-edit-profile-${input.provider}-${input.modelId}`,
);
await expect(editButton).toBeVisible({ timeout: 30_000 });
await editButton.click();
await expect(page.getByTestId("agent-profile-edit-modal")).toBeVisible({ timeout: 30_000 });
}
export async function removeOpenModalAgentProfileWithConfirm(
page: Page,
decision: "accept" | "dismiss",
): Promise<void> {
const dialogMessage = page.waitForEvent("dialog").then(async (dialog) => {
const message = dialog.message();
if (decision === "accept") {
await dialog.accept();
} else {
await dialog.dismiss();
}
return message;
});
await page.getByTestId("agent-profile-modal-remove-button").click();
expect(await dialogMessage).toMatch(/remove/i);
}
export async function switchSettingsSectionWithConfirm(
page: Page,
sectionName: string,
decision: "accept" | "dismiss",
): Promise<void> {
const dialogMessage = page.waitForEvent("dialog").then(async (dialog) => {
const message = dialog.message();
if (decision === "accept") {
await dialog.accept();
} else {
await dialog.dismiss();
}
return message;
});
await page.getByRole("button", { name: sectionName, exact: true }).click();
expect(await dialogMessage).toMatch(/discard|unsaved/i);
}
export async function browserBackWithConfirm(
page: Page,
decision: "accept" | "dismiss",
): Promise<void> {
const dialogMessage = page.waitForEvent("dialog").then(async (dialog) => {
const message = dialog.message();
if (decision === "accept") {
await dialog.accept();
} else {
await dialog.dismiss();
}
return message;
});
await page.goBack();
expect(await dialogMessage).toMatch(/discard|unsaved/i);
}
export async function browserHistoryJumpWithConfirm(
page: Page,
delta: number,
decision: "accept" | "dismiss",
): Promise<void> {
const dialogMessage = page.waitForEvent("dialog").then(async (dialog) => {
const message = dialog.message();
if (decision === "accept") {
await dialog.accept();
} else {
await dialog.dismiss();
}
return message;
});
await page.evaluate((step) => window.history.go(step), delta);
expect(await dialogMessage).toMatch(/discard|unsaved/i);
}
/** Opens the inspector for a profile purely to read back what it stored. */
export async function expectAgentProfileForm(
page: Page,
name: string,
expected: { provider?: string; model?: string; mode?: string; notes?: string },
): Promise<void> {
await agentProfileRow(page, name)
.getByRole("button", { name: "Edit profile", exact: true })
.click();
const modal = editModal(page);
await expect(modal).toBeVisible({ timeout: 30_000 });
await expect(modal.getByRole("textbox", { name: "Name", exact: true })).toHaveValue(name);
const notesHint = modal.getByTestId("agent-profile-notes-field-hint");
await expect(notesHint).toHaveText(
"Helps agents choose this profile when starting another agent.",
);
await agentProfileRow(page, name).click();
const surface = editSurface(page);
await expect(surface).toBeVisible({ timeout: 30_000 });
await expect(surface.getByRole("textbox", { name: "Name", exact: true })).toHaveValue(name);
const notesHint = surface.getByTestId("agent-profile-notes-field-hint");
await expect(notesHint).toHaveText("Tells agents when to pick this profile");
expect(await notesHint.evaluate((element) => getComputedStyle(element).webkitLineClamp)).not.toBe(
"1",
);
for (const [field, value] of Object.entries(expected)) {
if (field === "notes") {
await expect(modal.getByRole("textbox", { name: "When to use", exact: true })).toHaveValue(
value,
);
continue;
}
await expect(
modal.getByRole("button", { name: `${capitalize(field)} (${value})` }),
).toBeVisible({ timeout: 30_000 });
if (expected.model) {
await expect(surface.getByTestId("agent-profile-model-trigger")).toContainText(expected.model);
} else if (expected.provider) {
await expect(surface.getByTestId("agent-profile-model-trigger")).toContainText(
expected.provider,
);
}
await modal.getByRole("button", { name: "Cancel", exact: true }).click();
await expect(editModal(page)).toHaveCount(0, { timeout: 30_000 });
if (expected.provider) {
await expect(surface).toContainText(expected.provider);
}
if (expected.mode) {
await expect(surface.getByTestId("agent-profile-mode-trigger")).toContainText(expected.mode);
}
if (expected.notes !== undefined) {
await expect(surface.getByRole("textbox", { name: "When to use", exact: true })).toHaveValue(
expected.notes,
);
}
await surface.getByRole("button", { name: "Cancel", exact: true }).click();
await expect(editSurface(page)).toHaveCount(0, { timeout: 30_000 });
}
// ─── The model picker ──────────────────────────────────────────────────────
@@ -535,7 +735,10 @@ export async function expectModelRowProfileActionBesideRow(
await expect(row.getByRole("button")).toHaveCount(0);
}
/** The hover-revealed plus on an unprofiled model row opens a seeded profile form. */
/**
* The hover-revealed plus on an unprofiled model row saves the profile,
* selects the model immediately, closes the picker, and surfaces an Edit / Undo toast.
*/
export async function expectCreateProfileFromModelRow(
page: Page,
input: { provider: string; modelId: string; modelLabel: string },
@@ -548,14 +751,14 @@ export async function expectCreateProfileFromModelRow(
await modelRow(page, input).hover();
await expect(action).toHaveCSS("pointer-events", "auto");
await action.click();
const modal = editModal(page);
await expect(modal).toBeVisible({ timeout: 30_000 });
await expect(modal.getByRole("textbox", { name: "Name", exact: true })).toHaveValue(
input.modelLabel,
);
await expect(modal.getByRole("button", { name: `Model (${input.modelLabel})` })).toBeVisible();
await modal.getByRole("button", { name: "Cancel", exact: true }).click();
await expect(modal).toHaveCount(0, { timeout: 30_000 });
const toast = page.getByTestId("model-profile-created-toast");
await expect(toast).toBeVisible({ timeout: 30_000 });
await expect(toast).toContainText(input.modelLabel);
// Undo removes the newly saved profile from the toast.
await toast.getByTestId("model-profile-created-undo").click();
await expect(toast).toHaveCount(0, { timeout: 30_000 });
}
export async function selectModelRow(
@@ -31,6 +31,8 @@ export interface RewindCompletionGate {
clearTimelineStreamCount(): void;
release(): void;
timelineStreamCount(): number;
/** Timeline reads this page sent since the last clear. */
timelineFetchCount(): number;
waitForDelayedResponse(): Promise<void>;
}
@@ -186,12 +188,20 @@ export async function holdDaemonHydration(page: Page): Promise<DaemonHydrationGa
};
}
// The rewind response and the timeline change it causes; the change removes the rewound row too.
const REWIND_COMPLETION_MESSAGES = new Set([
"agent.rewind.response",
"agent.timeline.rewind",
"agent.timeline.replacement",
]);
export async function holdRewindCompletion(
page: Page,
agentId: string,
): Promise<RewindCompletionGate> {
let released = false;
let timelineStreamCount = 0;
let timelineFetchCount = 0;
const delayedForwards: Array<() => void> = [];
let resolveDelayedResponse: (() => void) | null = null;
const delayedResponse = new Promise<void>((resolve) => {
@@ -200,7 +210,16 @@ export async function holdRewindCompletion(
await page.routeWebSocket(daemonWsRoutePattern(), (ws) => {
const server = ws.connectToServer();
ws.onMessage((message) => server.send(message));
ws.onMessage((message) => {
const sessionMessage = getSessionMessage(message);
if (
sessionMessage?.type === "fetch_agent_timeline_request" &&
sessionMessage.agentId === agentId
) {
timelineFetchCount += 1;
}
server.send(message);
});
server.onMessage((message) => {
const sessionMessage = getSessionMessage(message);
const payload = sessionMessage ? getPayload(sessionMessage) : null;
@@ -216,11 +235,11 @@ export async function holdRewindCompletion(
}
if (
!released &&
(sessionMessage?.type === "agent.rewind.response" ||
sessionMessage?.type === "agent.timeline.replacement") &&
sessionMessage &&
REWIND_COMPLETION_MESSAGES.has(String(sessionMessage.type)) &&
payload?.agentId === agentId
) {
// The replacement also signals completion and removes the rewound row/menu.
// The rewind also signals completion and removes the rewound row/menu.
// Hold it with the response so the pending-state assertion observes a pending rewind.
delayedForwards.push(() => ws.send(message));
if (sessionMessage.type === "agent.rewind.response") resolveDelayedResponse?.();
@@ -233,6 +252,7 @@ export async function holdRewindCompletion(
return {
clearTimelineStreamCount() {
timelineStreamCount = 0;
timelineFetchCount = 0;
},
release() {
released = true;
@@ -241,6 +261,7 @@ export async function holdRewindCompletion(
}
},
timelineStreamCount: () => timelineStreamCount,
timelineFetchCount: () => timelineFetchCount,
waitForDelayedResponse: () => delayedResponse,
};
}
@@ -1,11 +1,76 @@
import { useCallback, useMemo, useState, type ReactElement } from "react";
import { useCallback, useEffect, useMemo, useRef, useState, type ReactElement } from "react";
import { Text, View } from "react-native";
import { useTranslation } from "react-i18next";
import { StyleSheet } from "react-native-unistyles";
import type { AgentProfile } from "@getpaseo/protocol/messages";
import { Button } from "@/components/ui/button";
import { useToast } from "@/contexts/toast-context";
import { useProvidersSnapshot } from "@/hooks/use-providers-snapshot";
import { confirmDialog } from "@/utils/confirm-dialog";
import { toErrorMessage } from "@/utils/error-messages";
import { AgentProfileEditModal } from "./settings/agent-profile-edit-modal";
import { generateAgentProfileId } from "./internal/profile-id";
import type { AgentProfileSeed, AgentProfileValue } from "./internal/profile-form-model";
import { useAgentProfiles } from "./internal/use-agent-profiles";
import {
buildInstantAgentProfile,
type AgentProfileSeed,
type AgentProfileValue,
} from "./internal/profile-form-model";
import { removeAgentProfileById, useAgentProfiles } from "./internal/use-agent-profiles";
const PROFILE_SAVED_TOAST_DURATION_MS = 6000;
function ProfileSavedToastContent({
name,
onEdit,
onUndo,
}: {
name: string;
onEdit: () => void;
onUndo: () => void;
}): ReactElement {
const { t } = useTranslation();
return (
<View style={styles.toastRow}>
<Text style={styles.toastText} numberOfLines={1}>
{t("modelSelector.profileSaved", { name })}
</Text>
<View style={styles.toastActions}>
<Button
variant="secondary"
size="sm"
onPress={onEdit}
accessibilityLabel={t("modelSelector.editProfileLabel", { name })}
testID="model-profile-created-edit"
>
{t("modelSelector.editProfiles")}
</Button>
<Button
variant="outline"
size="sm"
onPress={onUndo}
accessibilityLabel={t("modelSelector.undoProfileSave")}
testID="model-profile-created-undo"
>
{t("modelSelector.undo")}
</Button>
</View>
</View>
);
}
function createProfileSavedToast(input: {
name: string;
onEdit: () => void;
onUndo: () => void;
}): ReactElement {
return <ProfileSavedToastContent name={input.name} onEdit={input.onEdit} onUndo={input.onUndo} />;
}
export interface AgentProfileEditorControls {
/** Save a profile immediately from a model row with defaults and show an Edit/Undo toast. */
quickCreateFromModel: (seed: AgentProfileSeed) => Promise<AgentProfile | null>;
/** Undo an instant creation without a confirmation prompt. */
undoCreate: (profileId: string) => Promise<void>;
/** Open the create form pre-filled with provider, model, and suggested name. */
openCreateFromModel: (seed: AgentProfileSeed) => void;
/** Open the edit form for one profile. */
@@ -23,8 +88,78 @@ type EditorRequest =
* never see `saveProfiles` or construct profile records themselves.
*/
export function useAgentProfileEditor(serverId: string | null): AgentProfileEditorControls {
const { profiles, saveProfiles } = useAgentProfiles(serverId);
const { t } = useTranslation();
const toast = useToast();
const { profiles, mutateProfiles } = useAgentProfiles(serverId);
const { entries } = useProvidersSnapshot(serverId, { cwd: null });
const [request, setRequest] = useState<EditorRequest | null>(null);
const mountedRef = useRef(true);
const dismissSavedToastRef = useRef<(() => void) | null>(null);
useEffect(() => {
mountedRef.current = true;
return () => {
mountedRef.current = false;
dismissSavedToastRef.current?.();
dismissSavedToastRef.current = null;
};
}, []);
const undoCreate = useCallback(
async (profileId: string): Promise<void> => {
try {
await mutateProfiles((current) => removeAgentProfileById(current, profileId));
} catch (error) {
toast.error(toErrorMessage(error));
}
},
[mutateProfiles, toast],
);
const quickCreateFromModel = useCallback(
async (seed: AgentProfileSeed): Promise<AgentProfile | null> => {
const value = buildInstantAgentProfile({ seed, entries });
const created: AgentProfile = { id: generateAgentProfileId(), ...value };
try {
const written = await mutateProfiles((current) => [...current, created]);
if (!written || !mountedRef.current) {
return written ? created : null;
}
dismissSavedToastRef.current?.();
let dismiss: (() => void) | null = null;
const clearToast = () => {
dismiss?.();
if (dismissSavedToastRef.current === dismiss) {
dismissSavedToastRef.current = null;
}
};
dismiss = toast.show(
createProfileSavedToast({
name: created.name,
onEdit: () => {
clearToast();
setRequest({ mode: "edit", profile: created });
},
onUndo: () => {
clearToast();
void undoCreate(created.id);
},
}),
{
variant: "success",
durationMs: PROFILE_SAVED_TOAST_DURATION_MS,
testID: "model-profile-created-toast",
},
);
dismissSavedToastRef.current = dismiss;
return created;
} catch (error) {
toast.error(toErrorMessage(error));
return null;
}
},
[entries, mutateProfiles, toast, undoCreate],
);
const openCreateFromModel = useCallback((seed: AgentProfileSeed) => {
setRequest({ mode: "create", seed });
@@ -45,15 +180,59 @@ export function useAgentProfileEditor(serverId: string | null): AgentProfileEdit
const handleSave = useCallback(
async (value: AgentProfileValue) => {
const current = profiles ?? [];
const editing = request?.mode === "edit" ? request.profile : undefined;
const next: AgentProfile[] = editing
? current.map((entry) => (entry.id === editing.id ? { id: entry.id, ...value } : entry))
: [...current, { id: generateAgentProfileId(), ...value }];
await saveProfiles(next);
setRequest(null);
const savedRequest = request;
const editing = savedRequest?.mode === "edit" ? savedRequest.profile : undefined;
const written = await mutateProfiles((current) =>
editing
? current.map((entry) => (entry.id === editing.id ? { id: entry.id, ...value } : entry))
: [...current, { id: generateAgentProfileId(), ...value }],
);
if (!written) {
return;
}
setRequest((current) => (current === savedRequest ? null : current));
},
[profiles, request, saveProfiles],
[mutateProfiles, request],
);
const handleRemove = useCallback(
(profileId: string) => {
const profile = profiles?.find((entry) => entry.id === profileId);
if (!profile) {
return;
}
const confirmAndRemove = async () => {
const confirmed = await confirmDialog({
title: t("settings.host.agentProfiles.removeConfirmTitle"),
message: t("settings.host.agentProfiles.removeConfirmMessage", { name: profile.name }),
confirmLabel: t("settings.host.agentProfiles.remove"),
cancelLabel: t("common.actions.cancel"),
destructive: true,
});
if (!confirmed) {
return;
}
try {
const updated = await mutateProfiles((current) =>
removeAgentProfileById(current, profileId),
);
if (updated) {
setRequest((current) =>
current?.mode === "edit" && current.profile.id === profileId ? null : current,
);
}
} catch (error) {
const detail = toErrorMessage(error);
toast.error(
detail
? `${t("common.errors.unableToSave")}: ${detail}`
: t("common.errors.unableToSave"),
);
}
};
void confirmAndRemove();
},
[mutateProfiles, profiles, t, toast],
);
const element = useMemo(
@@ -66,13 +245,34 @@ export function useAgentProfileEditor(serverId: string | null): AgentProfileEdit
{...(request?.mode === "create" && request.seed ? { seed: request.seed } : {})}
onClose={close}
onSave={handleSave}
onRemove={handleRemove}
/>
),
[close, handleSave, request, serverId],
[close, handleRemove, handleSave, request, serverId],
);
return useMemo(
() => ({ openCreateFromModel, openEdit, element }),
[openCreateFromModel, openEdit, element],
() => ({ quickCreateFromModel, undoCreate, openCreateFromModel, openEdit, element }),
[element, openCreateFromModel, openEdit, quickCreateFromModel, undoCreate],
);
}
const styles = StyleSheet.create((theme) => ({
toastRow: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[3],
maxWidth: "100%",
},
toastText: {
flexShrink: 1,
color: theme.colors.foreground,
fontSize: theme.fontSize.base,
},
toastActions: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[1.5],
flexShrink: 0,
},
}));
+4 -1
View File
@@ -27,4 +27,7 @@ export {
type DraftAgentProfileControls,
} from "./internal/use-agent-profile-picker";
export { AgentProfileGlyph } from "./internal/agent-profile-glyph";
export { AgentProfilesSection } from "./settings/agent-profiles-section";
export {
AgentProfilesPage,
type AgentProfilesBeforeLeaveGuard,
} from "./settings/agent-profiles-section";
@@ -31,6 +31,7 @@ import {
TestTube,
Wrench,
} from "lucide-react-native";
import { useProviderIcon } from "@/components/provider-icons";
import { identityForeground } from "@/styles/identity-colors";
import { ICON_SIZE, type Theme } from "@/styles/theme";
import {
@@ -108,21 +109,57 @@ export function agentProfileColorMapping(
return COLOR_MAPPINGS[color];
}
function ProviderFallbackIcon({
provider,
serverId,
size,
color = "",
}: {
provider: string;
serverId?: string | null;
size: number;
color?: string;
}) {
const Icon = useProviderIcon(provider, serverId);
return <Icon size={size} color={color} />;
}
const ThemedProviderFallbackIcon = withUnistyles(ProviderFallbackIcon);
/**
* How a profile is drawn everywhere it appears — settings list, model picker,
* and the picker grid's own cells. One component so the three can't drift.
* How a profile is drawn everywhere it appears — settings roster, model picker,
* drawer/sheet header, and the picker grid's own cells. When no custom icon is
* chosen and a provider is known, it falls back to that provider's mark instead
* of repeating identical generic stars across every row.
*/
export function AgentProfileGlyph({
icon,
color,
provider,
serverId,
size = ICON_SIZE.md,
}: {
icon?: string | undefined;
color?: string | undefined;
provider?: string | undefined;
serverId?: string | null | undefined;
size?: number;
}) {
const iconKey = resolveAgentProfileIconKey(icon);
const mapping = COLOR_MAPPINGS[resolveAgentProfileColor(color)];
const Icon = iconKey ? THEMED_ICONS[iconKey] : ThemedDefaultIcon;
return <Icon size={size} uniProps={mapping} />;
if (iconKey) {
const Icon = THEMED_ICONS[iconKey];
return <Icon size={size} uniProps={mapping} />;
}
if (provider) {
return (
<ThemedProviderFallbackIcon
provider={provider}
serverId={serverId}
size={size}
uniProps={mapping}
/>
);
}
return <ThemedDefaultIcon size={size} uniProps={mapping} />;
}
@@ -2,6 +2,7 @@ import type { ProviderSnapshotEntry } from "@getpaseo/protocol/agent-types";
import { describe, expect, it } from "vitest";
import {
buildControlsRequestKey,
buildInstantAgentProfile,
openAgentProfileForm,
type AgentProfileFormModel,
} from "./profile-form-model";
@@ -70,6 +71,10 @@ function optionValues(options: readonly { value: string }[]): string[] {
return options.map((option) => option.value);
}
function optionIds(options: readonly { id: string }[]): string[] {
return options.map((option) => option.id);
}
const FAST = {
controls: [{ type: "toggle" as const, key: "fast_mode", label: "Fast" }],
options: { fast_mode: false },
@@ -528,16 +533,71 @@ describe("openAgentProfileForm", () => {
});
});
it("draws no controls for the previous model while another model's answer is pending", () => {
it("keeps previous provider controls mounted while another model's answer is pending to prevent layout jank", () => {
const model = openWithCatalog({ mode: "create" });
selectClaude(model);
model.applyControls(model.getState().controlsRequestKey ?? "", WEB_SEARCH_CONTROLS);
model.setModel("claude-haiku-4-5", { label: "Haiku 4.5" });
expect(model.getState().controlsResolution).toBe("pending");
expect(model.getState().controlsPending).toBe(true);
expect(model.getState().controls).toHaveLength(1);
// Switching providers clears controls immediately so stale controls never cross providers.
model.setProvider("codex", { label: "Codex" });
expect(model.getState().controls).toEqual([]);
});
it("seeds the catalog synchronously when entries are passed in the initial snapshot", () => {
const model = openAgentProfileForm({
mode: "edit",
profile: { id: "p1", name: "UI work", provider: "claude", model: "claude-opus-5" },
entries: ENTRIES,
});
const state = model.getState();
expect(state.catalogResolution).toBe("complete");
expect(state.providerDisplay).toEqual({ label: "Claude Code" });
expect(state.modelDisplay).toEqual({ label: "Opus 5" });
expect(optionIds(state.unifiedModelOptions)).toEqual([
"claude:claude-opus-5",
"claude:claude-haiku-4-5",
"codex:gpt-5.2-codex",
]);
});
it("updates provider, model, and auto-suggested name together via setProviderModel", () => {
const model = openAgentProfileForm({ mode: "create", entries: ENTRIES });
model.setProviderModel("claude", "claude-opus-5", {
provider: { label: "Claude Code" },
model: { label: "Opus 5" },
});
expect(model.getState().name).toBe("Opus 5");
expect(model.getState().provider).toBe("claude");
expect(model.getState().modelId).toBe("claude-opus-5");
expect(model.getState().modeId).toBe("plan");
expect(model.getState().thinkingOptionId).toBe("think");
// Switching to another model while untouched updates the suggested name.
model.setProviderModel("codex", "gpt-5.2-codex", {
provider: { label: "Codex" },
model: { label: "GPT-5.2 Codex" },
});
expect(model.getState().name).toBe("GPT-5.2 Codex");
expect(model.getState().provider).toBe("codex");
expect(model.getState().modeId).toBe("read-only");
// Once the user types a custom name, changing model preserves it.
model.setName("My Custom Worker");
model.setProviderModel("claude", "claude-haiku-4-5", {
provider: { label: "Claude Code" },
model: { label: "Haiku 4.5" },
});
expect(model.getState().name).toBe("My Custom Worker");
});
it("does not save a toggle once the model that drew it is replaced by one without it", () => {
const model = toggledOnOpus();
expect(model.getState().submitValue?.options).toEqual({ fast_mode: true });
@@ -643,6 +703,36 @@ describe("openAgentProfileForm", () => {
expect(notifications).toBe(1);
expect(model.getState().name).toBe("a");
});
it("does not treat catalog-prefilled defaults on a minimal profile as an unsaved edit", () => {
const model = openAgentProfileForm({
mode: "edit",
profile: {
id: "legacy_favorite:claude:claude-opus-5",
name: "Opus 5",
provider: "claude",
model: "claude-opus-5",
},
});
expect(model.getState().isDirty).toBe(false);
// Catalog fills in default modeId ("plan") and thinkingOptionId ("think").
model.applyProviderCatalog(ENTRIES);
expect(model.getState().modeId).toBe("plan");
expect(model.getState().thinkingOptionId).toBe("think");
expect(model.getState().isDirty).toBe(false);
// User edit marks dirty and advances draftRevision; a subsequent edit advances it again.
expect(model.getState().draftRevision).toBe(0);
model.setName("Renamed");
expect(model.getState().isDirty).toBe(true);
expect(model.getState().draftRevision).toBe(1);
model.setName("Renamed again");
expect(model.getState().draftRevision).toBe(2);
model.setName("Opus 5");
expect(model.getState().isDirty).toBe(false);
expect(model.getState().draftRevision).toBe(3);
});
});
describe("buildControlsRequestKey", () => {
@@ -657,3 +747,55 @@ describe("buildControlsRequestKey", () => {
);
});
});
describe("buildInstantAgentProfile", () => {
it("builds a concrete profile with provider defaults from a model seed", () => {
expect(
buildInstantAgentProfile({
seed: { provider: "claude", modelId: "claude-opus-5", name: "Opus 5" },
entries: ENTRIES,
}),
).toEqual({
name: "Opus 5",
provider: "claude",
model: "claude-opus-5",
modeId: "plan",
thinkingOptionId: "think",
options: {},
});
});
it("keeps compatible preferred mode and thinking levels and ignores incompatible ones", () => {
expect(
buildInstantAgentProfile({
seed: { provider: "claude", modelId: "claude-opus-5" },
entries: ENTRIES,
preferredModeId: "accept-edits",
preferredThinkingOptionId: "think-hard",
}),
).toEqual({
name: "Opus 5",
provider: "claude",
model: "claude-opus-5",
modeId: "accept-edits",
thinkingOptionId: "think-hard",
options: {},
});
expect(
buildInstantAgentProfile({
seed: { provider: "claude", modelId: "claude-haiku-4-5" },
entries: ENTRIES,
preferredModeId: "unknown-mode",
preferredThinkingOptionId: "think-hard",
}),
).toEqual({
name: "Haiku 4.5",
provider: "claude",
model: "claude-haiku-4-5",
modeId: "plan",
thinkingOptionId: "think",
options: {},
});
});
});
@@ -41,6 +41,16 @@ export interface AgentProfileFormOption {
testID: string;
}
export interface AgentProfileUnifiedModelOption {
id: string;
provider: string;
providerLabel: string;
modelId: string;
label: string;
description?: string;
testID: string;
}
/**
* Pre-fill values for create mode. Only used when `mode === "create"`; edit
* mode always seeds from the stored `profile` and ignores this.
@@ -55,6 +65,8 @@ export interface AgentProfileFormSnapshot {
mode: "create" | "edit";
profile?: AgentProfile;
seed?: AgentProfileSeed;
/** Optional cached host catalog so the first render is already hydrated without a layout flash. */
entries?: readonly ProviderSnapshotEntry[];
}
/**
@@ -97,6 +109,7 @@ export interface AgentProfileFormState {
optionEdits: ProviderOptions;
providerOptions: AgentProfileFormOption[];
unifiedModelOptions: AgentProfileUnifiedModelOption[];
modelOptions: AgentProfileFormOption[];
modeOptions: AgentProfileFormOption[];
thinkingOptions: AgentProfileFormOption[];
@@ -115,10 +128,14 @@ export interface AgentProfileFormState {
catalogResolution: AgentProfileResolutionStatus;
controlsResolution: AgentProfileResolutionStatus;
controlsPending: boolean;
controlsRequest: AgentProfileControlsRequest | null;
controlsRequestKey: string | null;
disclosure: AgentProfileFormDisclosure;
isDirty: boolean;
/** Monotonic counter incremented on every user edit that changes the draft. */
draftRevision: number;
isSubmitting: boolean;
submitError: string | null;
canSubmit: boolean;
@@ -142,6 +159,11 @@ export interface AgentProfileFormModel {
setAppearance: (value: { icon: string; color: string }) => void;
setNotes: (value: string) => void;
setProvider: (providerId: string, display: AgentProfileFormDisplay) => void;
setProviderModel: (
providerId: string,
modelId: string,
displays: { provider: AgentProfileFormDisplay; model: AgentProfileFormDisplay | null },
) => void;
setModel: (modelId: string, display: AgentProfileFormDisplay | null) => void;
setMode: (modeId: string, display: AgentProfileFormDisplay | null) => void;
setThinking: (thinkingOptionId: string, display: AgentProfileFormDisplay | null) => void;
@@ -224,6 +246,53 @@ function buildProviderOptions(entries: readonly ProviderSnapshotEntry[]): AgentP
);
}
function formatUnifiedModelDescription(providerLabel: string, model: AgentModelDefinition): string {
if (model.description && model.description !== providerLabel) {
return `${providerLabel} · ${model.description}`;
}
if (model.id !== model.label) {
return `${providerLabel} · ${model.id}`;
}
return providerLabel;
}
function buildUnifiedModelOptions(
entries: readonly ProviderSnapshotEntry[],
): AgentProfileUnifiedModelOption[] {
const options: AgentProfileUnifiedModelOption[] = [];
for (const entry of entries) {
if (!entry.enabled) {
continue;
}
const providerLabel = entry.label ?? entry.provider;
const models = filterSelectableModels(entry.models ?? null) ?? [];
if (models.length === 0) {
options.push({
id: `${entry.provider}:`,
provider: entry.provider,
providerLabel,
modelId: "",
label: providerLabel,
...(entry.description ? { description: entry.description } : {}),
testID: `agent-profile-unified-model-${entry.provider}`,
});
continue;
}
for (const model of models) {
options.push({
id: `${entry.provider}:${model.id}`,
provider: entry.provider,
providerLabel,
modelId: model.id,
label: model.label,
description: formatUnifiedModelDescription(providerLabel, model),
testID: `agent-profile-unified-model-${entry.provider}-${model.id}`,
});
}
}
return options;
}
function buildModelOptions(models: readonly AgentModelDefinition[]): AgentProfileFormOption[] {
return models.map((model) =>
formOption({
@@ -385,6 +454,28 @@ export function buildControlsRequestKey(
: scope;
}
function stableOptionsKey(record: ProviderOptions): string {
const keys = Object.keys(record).sort();
if (keys.length === 0) {
return "";
}
return JSON.stringify(keys.map((key) => [key, record[key]]));
}
function formDraftFingerprint(state: AgentProfileFormState): string {
return JSON.stringify([
state.name.trim(),
state.icon,
state.color,
state.provider,
state.modelId,
state.modeId,
state.thinkingOptionId,
state.notes.trim(),
stableOptionsKey(ownOptionsOf(state)),
]);
}
function buildSubmitValue(state: AgentProfileFormState): AgentProfileValue | null {
const name = state.name.trim();
const notes = state.notes.trim();
@@ -446,6 +537,7 @@ function buildInitialState(snapshot: AgentProfileFormSnapshot): AgentProfileForm
options: { ...profile.options },
optionEdits: {},
providerOptions: [],
unifiedModelOptions: [],
modelOptions: [],
modeOptions: [],
thinkingOptions: [],
@@ -459,6 +551,7 @@ function buildInitialState(snapshot: AgentProfileFormSnapshot): AgentProfileForm
thinkingDisplay: seedDisplay(profile.thinkingOptionId),
catalogResolution: "idle",
controlsResolution: "idle",
controlsPending: false,
controlsRequest: null,
controlsRequestKey: null,
disclosure: {
@@ -467,6 +560,8 @@ function buildInitialState(snapshot: AgentProfileFormSnapshot): AgentProfileForm
showThinkingField: false,
showControlsField: false,
},
isDirty: false,
draftRevision: 0,
isSubmitting: false,
submitError: null,
canSubmit: false,
@@ -474,17 +569,118 @@ function buildInitialState(snapshot: AgentProfileFormSnapshot): AgentProfileForm
};
}
function pickMatchingId(
preferred: string | null | undefined,
options: readonly { id: string }[],
fallback: string,
): string {
const trimmed = preferred?.trim() ?? "";
if (trimmed && options.some((option) => option.id === trimmed)) {
return trimmed;
}
return fallback;
}
/**
* Builds a ready-to-save profile in one tap (for composer model-row `+` creation).
* Resolves defaults from the host catalog and preserves compatible composer mode/thinking
* when provided, so the stored profile is concrete from the moment it is created.
*/
export function buildInstantAgentProfile(input: {
seed: AgentProfileSeed;
entries: readonly ProviderSnapshotEntry[] | undefined;
preferredModeId?: string | null;
preferredThinkingOptionId?: string | null;
}): AgentProfileValue {
const entries = input.entries ?? [];
const entry = findEntry(entries, input.seed.provider);
const models = resolveModels(entries, input.seed.provider);
const modes = resolveModes(entries, input.seed.provider);
const modelId = input.seed.modelId?.trim() || defaultModelId(models);
const effectiveModel = resolveEffectiveModel(models, modelId);
const matchedModel = models.find((candidate) => candidate.id === modelId);
const modeId = pickMatchingId(input.preferredModeId, modes, defaultModeId(entry, modes));
const thinkingOptionId = pickMatchingId(
input.preferredThinkingOptionId,
effectiveModel?.thinkingOptions ?? [],
defaultThinkingOptionId(effectiveModel),
);
const name =
[input.seed.name?.trim(), matchedModel?.label, modelId, entry?.label, input.seed.provider].find(
(candidate): candidate is string => Boolean(candidate),
) ?? input.seed.provider;
return {
name,
provider: input.seed.provider,
...(modelId ? { model: modelId } : {}),
...(modeId ? { modeId } : {}),
...(thinkingOptionId ? { thinkingOptionId } : {}),
options: {},
};
}
function resolveModeLabel(modes: readonly AgentMode[], modeId: string): string | null {
const mode = modes.find((entry) => entry.id === modeId);
return mode ? formatAgentModeLabel(mode) : null;
}
function resolveThinkingLabel(options: readonly AgentSelectOption[], id: string): string | null {
const option = options.find((entry) => entry.id === id);
return option ? formatThinkingOptionLabel(option) : null;
}
function resolveControlsSlice(input: {
next: AgentProfileFormState;
controlsRequestKey: string | null;
controlsScopeKey: string | null;
resolvedControlsKey: string | null;
resolvedScopeKey: string | null;
resolvedProvider: string | null;
resolvedControls: AgentOptionControl[];
resolvedOptions: ProviderOptions;
}): {
controls: AgentOptionControl[];
controlOptions: ProviderOptions;
controlsResolution: AgentProfileResolutionStatus;
} {
const featuresAreCurrent =
input.controlsRequestKey !== null && input.controlsRequestKey === input.resolvedControlsKey;
const controlsApply =
input.controlsScopeKey !== null &&
(input.controlsScopeKey === input.resolvedScopeKey ||
(input.next.provider.length > 0 && input.next.provider === input.resolvedProvider));
const controls = controlsApply ? input.resolvedControls : [];
let controlOptions: ProviderOptions = input.next.options;
if (controlsApply) {
controlOptions = featuresAreCurrent
? input.resolvedOptions
: { ...input.resolvedOptions, ...input.next.optionEdits };
}
return {
controls,
controlOptions,
controlsResolution: resolveControlsStatus(input.controlsRequestKey, featuresAreCurrent),
};
}
export function openAgentProfileForm(snapshot: AgentProfileFormSnapshot): AgentProfileFormModel {
let entries: readonly ProviderSnapshotEntry[] = [];
let catalogResolution: AgentProfileResolutionStatus = "idle";
let entries: readonly ProviderSnapshotEntry[] = snapshot.entries ? [...snapshot.entries] : [];
let catalogResolution: AgentProfileResolutionStatus = snapshot.entries ? "complete" : "idle";
let resolvedControlsKey: string | null = null;
let resolvedScopeKey: string | null = null;
let resolvedProvider: string | null = null;
let resolvedControls: AgentOptionControl[] = [];
let resolvedOptions: ProviderOptions = {};
let drawnKeys: ReadonlySet<string> = new Set();
let answeredKeys: ReadonlySet<string> = new Set();
let listeners = new Set<() => void>();
let closed = false;
let hasUserEdited = false;
let draftRevision = 0;
let baselineFingerprint = "";
let autoSuggestedName: string | null =
snapshot.mode === "create" ? (snapshot.seed?.name ?? null) : null;
function derive(incoming: AgentProfileFormState): AgentProfileFormState {
const models = resolveModels(entries, incoming.provider);
@@ -502,24 +698,21 @@ export function openAgentProfileForm(snapshot: AgentProfileFormSnapshot): AgentP
const controlsRequest = buildControlsRequest(next);
const controlsRequestKey = buildControlsRequestKey(controlsRequest);
const controlsScopeKey = buildControlsScopeKey(controlsRequest);
const featuresAreCurrent =
controlsRequestKey !== null && controlsRequestKey === resolvedControlsKey;
// A toggle changes only the options, so the controls stay up while the daemon answers and the
// toggle shows over the last answer. A change of provider, model, mode or thinking draws none
// until its own answer arrives.
const controlsApply = controlsScopeKey !== null && controlsScopeKey === resolvedScopeKey;
const controls = controlsApply ? resolvedControls : [];
let controlOptions: ProviderOptions = next.options;
if (controlsApply) {
controlOptions = featuresAreCurrent
? resolvedOptions
: { ...resolvedOptions, ...next.optionEdits };
}
const controlsResolution = resolveControlsStatus(controlsRequestKey, featuresAreCurrent);
const { controls, controlOptions, controlsResolution } = resolveControlsSlice({
next,
controlsRequestKey,
controlsScopeKey,
resolvedControlsKey,
resolvedScopeKey,
resolvedProvider,
resolvedControls,
resolvedOptions,
});
const withOptions: AgentProfileFormState = {
...next,
providerOptions: buildProviderOptions(entries),
unifiedModelOptions: buildUnifiedModelOptions(entries),
modelOptions: buildModelOptions(models),
modeOptions: buildModeOptions(modes),
thinkingOptions: buildThinkingOptions(thinking),
@@ -538,21 +731,16 @@ export function openAgentProfileForm(snapshot: AgentProfileFormSnapshot): AgentP
modeDisplay: refineDisplay(
next.modeDisplay,
next.modeId,
(() => {
const mode = modes.find((entry) => entry.id === next.modeId);
return mode ? formatAgentModeLabel(mode) : null;
})(),
resolveModeLabel(modes, next.modeId),
),
thinkingDisplay: refineDisplay(
next.thinkingDisplay,
next.thinkingOptionId,
(() => {
const option = thinking.find((entry) => entry.id === next.thinkingOptionId);
return option ? formatThinkingOptionLabel(option) : null;
})(),
resolveThinkingLabel(thinking, next.thinkingOptionId),
),
catalogResolution,
controlsResolution,
controlsPending: controlsResolution === "pending",
controlsRequest,
controlsRequestKey,
};
@@ -572,16 +760,40 @@ export function openAgentProfileForm(snapshot: AgentProfileFormSnapshot): AgentP
withOptions.provider.length > 0 &&
!withOptions.isSubmitting;
const resolved: AgentProfileFormState = { ...withOptions, disclosure, canSubmit };
return { ...resolved, submitValue: canSubmit ? buildSubmitValue(resolved) : null };
const submitValue = canSubmit ? buildSubmitValue(resolved) : null;
const isDirty =
baselineFingerprint.length > 0 && formDraftFingerprint(resolved) !== baselineFingerprint;
return { ...resolved, isDirty, draftRevision, submitValue };
}
let state: AgentProfileFormState = derive(buildInitialState(snapshot));
baselineFingerprint = formDraftFingerprint(state);
function publish(mutate: (current: AgentProfileFormState) => AgentProfileFormState): void {
function publish(
mutate: (current: AgentProfileFormState) => AgentProfileFormState,
options?: { userEdit?: boolean },
): void {
if (closed) {
return;
}
state = derive(mutate(state));
const previousFingerprint = formDraftFingerprint(state);
if (options?.userEdit) {
hasUserEdited = true;
}
let nextState = derive(mutate(state));
if (options?.userEdit && formDraftFingerprint(nextState) !== previousFingerprint) {
draftRevision += 1;
nextState = { ...nextState, draftRevision };
}
// Catalog hydration fills in missing provider defaults (e.g., default mode on a
// migrated favorite); refresh the clean baseline until the user makes an edit.
if (!hasUserEdited) {
baselineFingerprint = formDraftFingerprint(nextState);
if (nextState.isDirty) {
nextState = { ...nextState, isDirty: false };
}
}
state = nextState;
for (const listener of listeners) {
listener();
}
@@ -610,6 +822,7 @@ export function openAgentProfileForm(snapshot: AgentProfileFormSnapshot): AgentP
}
resolvedControlsKey = requestKey;
resolvedScopeKey = buildControlsScopeKey(state.controlsRequest);
resolvedProvider = state.provider || null;
resolvedControls = [...resolved.controls];
resolvedOptions = resolved.options;
answeredKeys = new Set(resolved.controls.map((control) => control.key));
@@ -622,66 +835,149 @@ export function openAgentProfileForm(snapshot: AgentProfileFormSnapshot): AgentP
}
resolvedControlsKey = requestKey;
resolvedScopeKey = buildControlsScopeKey(state.controlsRequest);
resolvedProvider = state.provider || null;
resolvedControls = [];
resolvedOptions = {};
publish((current) => current);
},
setName: (value) => publish((current) => ({ ...current, name: value })),
setName: (value) =>
publish(
(current) => {
if (value !== autoSuggestedName) {
autoSuggestedName = null;
}
return { ...current, name: value };
},
{ userEdit: true },
),
setAppearance: (value) =>
publish((current) => ({ ...current, icon: value.icon, color: value.color })),
setNotes: (value) => publish((current) => ({ ...current, notes: value })),
publish((current) => ({ ...current, icon: value.icon, color: value.color }), {
userEdit: true,
}),
setNotes: (value) => publish((current) => ({ ...current, notes: value }), { userEdit: true }),
setProvider: (providerId, display) =>
publish((current) => {
if (current.provider === providerId) {
return current;
}
// Everything below the provider is provider-scoped: a model id, mode id,
// thinking id or feature id from the old provider means nothing here.
// Clearing them is enough — `derive` seeds the new provider's defaults.
drawnKeys = new Set();
answeredKeys = new Set();
return {
...current,
provider: providerId,
providerDisplay: display,
modelId: "",
modelDisplay: null,
modeId: "",
modeDisplay: null,
thinkingOptionId: "",
thinkingDisplay: null,
options: {},
optionEdits: {},
};
}),
publish(
(current) => {
if (current.provider === providerId) {
return current;
}
// Everything below the provider is provider-scoped: a model id, mode id,
// thinking id or feature id from the old provider means nothing here.
// Clearing them is enough — `derive` seeds the new provider's defaults.
drawnKeys = new Set();
answeredKeys = new Set();
resolvedProvider = null;
resolvedScopeKey = null;
resolvedControlsKey = null;
resolvedControls = [];
resolvedOptions = {};
return {
...current,
provider: providerId,
providerDisplay: display,
modelId: "",
modelDisplay: null,
modeId: "",
modeDisplay: null,
thinkingOptionId: "",
thinkingDisplay: null,
options: {},
optionEdits: {},
};
},
{ userEdit: true },
),
setProviderModel: (providerId, modelId, displays) =>
publish(
(current) => {
const providerChanged = current.provider !== providerId;
const modelChanged = current.modelId !== modelId;
if (!providerChanged && !modelChanged) {
return current;
}
const suggested = displays.model?.label ?? displays.provider.label;
const shouldAutoName =
current.mode === "create" &&
(current.name.trim().length === 0 ||
(autoSuggestedName !== null && current.name === autoSuggestedName));
const nextName = shouldAutoName ? suggested : current.name;
if (shouldAutoName) {
autoSuggestedName = suggested;
}
if (providerChanged) {
drawnKeys = new Set();
answeredKeys = new Set();
resolvedProvider = null;
resolvedScopeKey = null;
resolvedControlsKey = null;
resolvedControls = [];
resolvedOptions = {};
return {
...current,
name: nextName,
provider: providerId,
providerDisplay: displays.provider,
modelId,
modelDisplay: displays.model,
modeId: "",
modeDisplay: null,
thinkingOptionId: "",
thinkingDisplay: null,
options: {},
optionEdits: {},
};
}
const nextThinking = resolveThinkingOptions(entries, current.provider, modelId);
const keepsThinking =
current.thinkingOptionId.length > 0 &&
nextThinking.some((option) => option.id === current.thinkingOptionId);
return {
...current,
name: nextName,
modelId,
modelDisplay: displays.model,
thinkingOptionId: keepsThinking ? current.thinkingOptionId : "",
thinkingDisplay: keepsThinking ? current.thinkingDisplay : null,
};
},
{ userEdit: true },
),
setModel: (modelId, display) =>
publish((current) => {
if (current.modelId === modelId) {
return current;
}
// Thinking options are a property of the model, so a level the new model
// does not offer has to go.
const nextThinking = resolveThinkingOptions(entries, current.provider, modelId);
const keepsThinking =
current.thinkingOptionId.length > 0 &&
nextThinking.some((option) => option.id === current.thinkingOptionId);
return {
...current,
modelId,
modelDisplay: display,
thinkingOptionId: keepsThinking ? current.thinkingOptionId : "",
thinkingDisplay: keepsThinking ? current.thinkingDisplay : null,
};
}),
publish(
(current) => {
if (current.modelId === modelId) {
return current;
}
// Thinking options are a property of the model, so a level the new model
// does not offer has to go.
const nextThinking = resolveThinkingOptions(entries, current.provider, modelId);
const keepsThinking =
current.thinkingOptionId.length > 0 &&
nextThinking.some((option) => option.id === current.thinkingOptionId);
return {
...current,
modelId,
modelDisplay: display,
thinkingOptionId: keepsThinking ? current.thinkingOptionId : "",
thinkingDisplay: keepsThinking ? current.thinkingDisplay : null,
};
},
{ userEdit: true },
),
setMode: (modeId, display) =>
publish((current) => ({ ...current, modeId, modeDisplay: display })),
publish((current) => ({ ...current, modeId, modeDisplay: display }), { userEdit: true }),
setThinking: (thinkingOptionId, display) =>
publish((current) => ({ ...current, thinkingOptionId, thinkingDisplay: display })),
publish((current) => ({ ...current, thinkingOptionId, thinkingDisplay: display }), {
userEdit: true,
}),
setOption: (key, value) =>
publish((current) => ({
...current,
optionEdits: { ...current.optionEdits, [key]: value },
})),
publish(
(current) => ({
...current,
optionEdits: { ...current.optionEdits, [key]: value },
}),
{ userEdit: true },
),
setSubmitting: (value) => publish((current) => ({ ...current, isSubmitting: value })),
setSubmitError: (value) => publish((current) => ({ ...current, submitError: value })),
};
@@ -0,0 +1,83 @@
import { describe, expect, it } from "vitest";
import type { ProviderSnapshotEntry } from "@getpaseo/protocol/agent-types";
import type { AgentProfile } from "@getpaseo/protocol/messages";
import { buildAgentProfileRosterSummary, formatShortModelLabel } from "./profile-summary";
const formatFeatureCount = (count: number) => `${count} option${count === 1 ? "" : "s"}`;
describe("formatShortModelLabel", () => {
it("keeps plain model names intact with no prefix", () => {
expect(formatShortModelLabel("Claude Opus 4.6")).toEqual({
prefix: null,
name: "Claude Opus 4.6",
});
});
it("splits slash-qualified router model ids into prefix and short name", () => {
expect(formatShortModelLabel("openrouter/moonshotai/kimi-k3.1-pro")).toEqual({
prefix: "openrouter/moonshotai/",
name: "kimi-k3.1-pro",
});
});
it("ignores leading or trailing slashes", () => {
expect(formatShortModelLabel("/leading")).toEqual({ prefix: null, name: "/leading" });
expect(formatShortModelLabel("trailing/")).toEqual({ prefix: null, name: "trailing/" });
});
});
describe("buildAgentProfileRosterSummary", () => {
const entries: ProviderSnapshotEntry[] = [
{
provider: "opencode",
status: "ready",
enabled: true,
label: "OpenCode",
models: [
{
provider: "opencode",
id: "openrouter/moonshotai/kimi-k3.1-pro",
label: "openrouter/moonshotai/kimi-k3.1-pro",
},
],
modes: [{ id: "build", label: "Build" }],
},
];
it("separates short model label from provider/mode/thinking/option details", () => {
const profile: AgentProfile = {
id: "p1",
name: "Kimi fast",
provider: "opencode",
model: "openrouter/moonshotai/kimi-k3.1-pro",
modeId: "build",
thinkingOptionId: "high",
options: { fast_mode: true },
};
const summary = buildAgentProfileRosterSummary({ profile, entries, formatFeatureCount });
expect(summary.providerLabel).toBe("OpenCode");
expect(summary.modelLabel).toBe("kimi-k3.1-pro");
expect(summary.modelPrefix).toBe("openrouter/moonshotai/");
expect(summary.runtimeDetails).toEqual(["OpenCode", "Build", "High", "1 option"]);
});
it("falls back to stored provider id when catalog is unavailable", () => {
const profile: AgentProfile = {
id: "p2",
name: "Offline profile",
provider: "custom-agent",
};
const summary = buildAgentProfileRosterSummary({
profile,
entries: undefined,
formatFeatureCount,
});
expect(summary.providerLabel).toBe("custom-agent");
expect(summary.modelLabel).toBeNull();
expect(summary.runtimeDetails).toEqual(["custom-agent"]);
});
});
@@ -7,6 +7,55 @@ export interface AgentProfileTag {
label: string;
}
export interface ShortModelLabel {
prefix: string | null;
name: string;
}
/**
* Splits slash-qualified routing IDs (e.g. `openrouter/moonshotai/kimi-k3.1-pro`)
* into a quiet prefix and the model's short name so dense roster rows stay readable.
*/
export function formatShortModelLabel(modelIdOrLabel: string): ShortModelLabel {
const trimmed = modelIdOrLabel.trim();
const lastSlash = trimmed.lastIndexOf("/");
if (lastSlash <= 0 || lastSlash >= trimmed.length - 1) {
return { prefix: null, name: trimmed };
}
return {
prefix: trimmed.slice(0, lastSlash + 1),
name: trimmed.slice(lastSlash + 1),
};
}
export interface AgentProfileRosterSummary {
providerLabel: string;
modelLabel: string | null;
modelPrefix: string | null;
runtimeDetails: string[];
allTags: AgentProfileTag[];
}
export function buildAgentProfileRosterSummary(input: {
profile: AgentProfile;
entries: readonly ProviderSnapshotEntry[] | undefined;
formatFeatureCount: (count: number) => string;
}): AgentProfileRosterSummary {
const allTags = buildAgentProfileTags(input);
const providerLabel =
allTags.find((tag) => tag.id === "provider")?.label ?? input.profile.provider;
const rawModel = allTags.find((tag) => tag.id === "model")?.label ?? null;
const shortModel = rawModel ? formatShortModelLabel(rawModel) : null;
const runtimeDetails = allTags.filter((tag) => tag.id !== "model").map((tag) => tag.label);
return {
providerLabel,
modelLabel: shortModel?.name ?? null,
modelPrefix: shortModel?.prefix ?? null,
runtimeDetails,
allTags,
};
}
function findEntry(
entries: readonly ProviderSnapshotEntry[],
provider: string,
@@ -0,0 +1,171 @@
import type { AgentProfile } from "@getpaseo/protocol/messages";
import { describe, expect, it } from "vitest";
import { createAgentProfileWriteQueue } from "./profile-write-queue";
function profile(id: string, name = id): AgentProfile {
return { id, name, provider: "claude", model: "claude-opus-5" };
}
function deferred<T>() {
let resolve!: (value: T) => void;
let reject!: (reason?: unknown) => void;
const promise = new Promise<T>((res, rej) => {
resolve = res;
reject = rej;
});
return { promise, resolve, reject };
}
describe("createAgentProfileWriteQueue", () => {
it("serializes overlapping appends on the same host so both profiles persist", async () => {
const queue = createAgentProfileWriteQueue();
let stored: AgentProfile[] = [profile("p0")];
const firstGate = deferred<void>();
const writes: string[][] = [];
const write = async (next: AgentProfile[]) => {
writes.push(next.map((entry) => entry.id));
if (writes.length === 1) {
await firstGate.promise;
}
stored = next;
return stored;
};
const first = queue.enqueue("host-a", {
readCurrent: () => stored,
write,
updater: (current) => [...current, profile("p1")],
});
const second = queue.enqueue("host-a", {
readCurrent: () => stored,
write,
updater: (current) => [...current, profile("p2")],
});
// Wait a microtask so the first write is in flight before releasing it.
await Promise.resolve();
expect(writes).toEqual([["p0", "p1"]]);
firstGate.resolve();
await expect(first).resolves.toEqual([profile("p0"), profile("p1")]);
await expect(second).resolves.toEqual([profile("p0"), profile("p1"), profile("p2")]);
expect(writes).toEqual([
["p0", "p1"],
["p0", "p1", "p2"],
]);
expect(stored.map((entry) => entry.id)).toEqual(["p0", "p1", "p2"]);
});
it("removes only the undone profile when Undo overlaps another in-flight save", async () => {
const queue = createAgentProfileWriteQueue();
let stored: AgentProfile[] = [profile("p0"), profile("p1")];
const saveGate = deferred<void>();
const appendSecond = queue.enqueue("host-a", {
readCurrent: () => stored,
write: async (next) => {
await saveGate.promise;
stored = next;
return stored;
},
updater: (current) => [...current, profile("p2")],
});
const undoFirst = queue.enqueue("host-a", {
readCurrent: () => stored,
write: async (next) => {
stored = next;
return stored;
},
updater: (current) => current.filter((entry) => entry.id !== "p1"),
});
saveGate.resolve();
await appendSecond;
await undoFirst;
expect(stored.map((entry) => entry.id)).toEqual(["p0", "p2"]);
});
it("recovers after a rejected write so subsequent mutations still run", async () => {
const queue = createAgentProfileWriteQueue();
let stored: AgentProfile[] = [profile("p0")];
const failing = queue.enqueue("host-a", {
readCurrent: () => stored,
write: async () => {
throw new Error("network blip");
},
updater: (current) => [...current, profile("p1")],
});
const succeeding = queue.enqueue("host-a", {
readCurrent: () => stored,
write: async (next) => {
stored = next;
return stored;
},
updater: (current) => [...current, profile("p2")],
});
await expect(failing).rejects.toThrow("network blip");
await expect(succeeding).resolves.toEqual([profile("p0"), profile("p2")]);
});
it("skips writing when current profiles are unloaded or the updater returns null", async () => {
const queue = createAgentProfileWriteQueue();
let writeCalls = 0;
const unloaded = await queue.enqueue("host-a", {
readCurrent: () => null,
write: async (next) => {
writeCalls += 1;
return next;
},
updater: (current) => [...current, profile("p1")],
});
expect(unloaded).toBeNull();
const noop = await queue.enqueue("host-a", {
readCurrent: () => [profile("p0")],
write: async (next) => {
writeCalls += 1;
return next;
},
updater: () => null,
});
expect(noop).toBeNull();
expect(writeCalls).toBe(0);
});
it("does not block writes to a different host", async () => {
const queue = createAgentProfileWriteQueue();
const hostAGate = deferred<void>();
let hostA: AgentProfile[] = [];
let hostB: AgentProfile[] = [];
const writeA = queue.enqueue("host-a", {
readCurrent: () => hostA,
write: async (next) => {
await hostAGate.promise;
hostA = next;
return hostA;
},
updater: (current) => [...current, profile("a1")],
});
const writeB = await queue.enqueue("host-b", {
readCurrent: () => hostB,
write: async (next) => {
hostB = next;
return hostB;
},
updater: (current) => [...current, profile("b1")],
});
expect(writeB).toEqual([profile("b1")]);
hostAGate.resolve();
await expect(writeA).resolves.toEqual([profile("a1")]);
});
});
@@ -0,0 +1,65 @@
import type { AgentProfile } from "@getpaseo/protocol/messages";
export type AgentProfileListUpdater = (current: readonly AgentProfile[]) => AgentProfile[] | null;
export interface AgentProfileWriteStep {
readCurrent: () => readonly AgentProfile[] | null;
write: (next: AgentProfile[]) => Promise<AgentProfile[]>;
updater: AgentProfileListUpdater;
}
export interface AgentProfileWriteQueue {
enqueue(serverId: string, step: AgentProfileWriteStep): Promise<AgentProfile[] | null>;
}
/** Removes one profile by id, returning `null` if it is already absent so callers skip no-op writes. */
export function removeAgentProfileById(
current: readonly AgentProfile[],
profileId: string,
): AgentProfile[] | null {
const next = current.filter((entry) => entry.id !== profileId);
return next.length === current.length ? null : next;
}
async function runQueuedWrite(
previous: Promise<void>,
step: AgentProfileWriteStep,
): Promise<AgentProfile[] | null> {
await previous;
const current = step.readCurrent();
if (current === null) {
return null;
}
const next = step.updater(current);
if (next === null) {
return null;
}
return step.write(next);
}
/**
* Serializes profile list writes per host so overlapping mutations (rapid composer
* `+` saves, Undo while another save is in flight, split-pane composers) each compute
* their update against the result of the previous write instead of overwriting it.
*/
export function createAgentProfileWriteQueue(): AgentProfileWriteQueue {
const tails = new Map<string, Promise<void>>();
return {
enqueue(serverId, step) {
const previous = tails.get(serverId) ?? Promise.resolve();
const result = runQueuedWrite(previous, step);
const tail = result.then(
() => undefined,
() => undefined,
);
tails.set(serverId, tail);
void tail.finally(() => {
if (tails.get(serverId) === tail) {
tails.delete(serverId);
}
});
return result;
},
};
}
@@ -23,7 +23,14 @@ export interface DraftAgentProfileControls {
}
export type AgentProfileApplyTarget =
| { kind: "agent"; agentId: string; availableModeIds: readonly string[] | null }
| {
kind: "agent";
agentId: string;
availableModeIds: readonly string[] | null;
currentProvider?: string | null;
onApplySameProvider?: () => void;
onStageProviderSwitch?: (profile: MaterializedAgentProfile) => void;
}
| { kind: "draft"; controls: DraftAgentProfileControls };
/** Everything the model picker renders for one profile. It never sees the profile itself. */
@@ -139,6 +146,16 @@ export function useAgentProfilePicker(
return;
}
if (
target.onStageProviderSwitch &&
target.currentProvider &&
resolved.provider !== target.currentProvider
) {
target.onStageProviderSwitch(resolved);
return;
}
target.onApplySameProvider?.();
const reconciled = reconcileMaterializedProfileMode(resolved, target.availableModeIds);
if (!reconciled) {
return;
@@ -1,8 +1,21 @@
import { useCallback } from "react";
import type { AgentProfile } from "@getpaseo/protocol/messages";
import { useCallback, useMemo } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import type { AgentProfile, MutableDaemonConfig } from "@getpaseo/protocol/messages";
import { daemonConfigQueryKey } from "@/data/daemon-config";
import { useDaemonConfig } from "@/hooks/use-daemon-config";
import { useSessionStore } from "@/stores/session-store";
import { supportsAgentProfiles } from "./capabilities";
import {
createAgentProfileWriteQueue,
removeAgentProfileById,
type AgentProfileListUpdater,
} from "./profile-write-queue";
const sharedProfileWriteQueue = createAgentProfileWriteQueue();
export { removeAgentProfileById };
export type { AgentProfileListUpdater };
export interface UseAgentProfilesResult {
/** `null` until the daemon config has arrived. */
@@ -11,24 +24,56 @@ export interface UseAgentProfilesResult {
isSupported: boolean;
/** Writes the whole list; there is no per-profile RPC. */
saveProfiles: (next: AgentProfile[]) => Promise<void>;
/**
* Applies a serialized mutation against the latest host profile list so
* overlapping writes compose instead of overwriting each other.
*/
mutateProfiles: (updater: AgentProfileListUpdater) => Promise<AgentProfile[] | null>;
}
export function useAgentProfiles(serverId: string | null): UseAgentProfilesResult {
const { t } = useTranslation();
const queryClient = useQueryClient();
const { config, patchConfig } = useDaemonConfig(serverId);
const queryKey = useMemo(() => daemonConfigQueryKey(serverId), [serverId]);
const isSupported = useSessionStore((state) => {
return supportsAgentProfiles(state.sessions[serverId ?? ""]?.serverInfo?.features);
});
const mutateProfiles = useCallback(
async (updater: AgentProfileListUpdater): Promise<AgentProfile[] | null> => {
if (!serverId) {
return null;
}
return sharedProfileWriteQueue.enqueue(serverId, {
readCurrent: () => {
const cached = queryClient.getQueryData<MutableDaemonConfig>(queryKey);
return cached ? (cached.agentProfiles ?? []) : null;
},
write: async (next) => {
const updated = await patchConfig({ agentProfiles: next });
if (!updated) {
throw new Error(t("workspace.terminal.hostDisconnected"));
}
return updated.agentProfiles ?? next;
},
updater,
});
},
[patchConfig, queryClient, queryKey, serverId, t],
);
const saveProfiles = useCallback(
async (next: AgentProfile[]) => {
await patchConfig({ agentProfiles: next });
await mutateProfiles(() => next);
},
[patchConfig],
[mutateProfiles],
);
return {
profiles: config ? (config.agentProfiles ?? []) : null,
isSupported,
saveProfiles,
mutateProfiles,
};
}
@@ -1,14 +1,20 @@
import { useEffect, useState, useSyncExternalStore } from "react";
import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
import type { AgentProfile } from "@getpaseo/protocol/messages";
import { useProvidersSnapshot } from "@/hooks/use-providers-snapshot";
import { toErrorMessage } from "@/utils/error-messages";
import {
openAgentProfileForm,
type AgentProfileFormModel,
type AgentProfileFormSnapshot,
type AgentProfileFormState,
type AgentProfileSeed,
type AgentProfileValue,
} from "./profile-form-model";
import { useAgentProfileFormCatalog, useAgentProfileFormControls } from "./use-profile-form-inputs";
/**
* One model per mount. The modal keys its body on mode + profile id, so create
* and edit never share an instance and reopening always starts from the record.
* One model per mount. The sheet or drawer host keys its session on mode + profile id,
* so create and edit never share an instance and reopening always starts from the record.
*/
export function useAgentProfileFormModel(
snapshot: AgentProfileFormSnapshot,
@@ -27,3 +33,78 @@ export function useAgentProfileFormModel(
export function useAgentProfileFormState(model: AgentProfileFormModel): AgentProfileFormState {
return useSyncExternalStore(model.subscribe, model.getState, model.getState);
}
export interface AgentProfileFormSession {
model: AgentProfileFormModel;
state: AgentProfileFormState;
isDirty: boolean;
save: () => Promise<boolean>;
}
/**
* Shared form session used by both the desktop inspector drawer and the modal sheet.
* Lifting this above drawer/modal framing lets responsive switches preserve unsaved edits.
*/
export function useAgentProfileFormSession({
serverId,
mode,
profile,
seed,
onSave,
onSaved,
}: {
serverId: string;
mode: "create" | "edit";
profile?: AgentProfile;
seed?: AgentProfileSeed;
onSave: (value: AgentProfileValue) => Promise<void>;
onSaved: () => void;
}): AgentProfileFormSession {
const { entries } = useProvidersSnapshot(serverId, { cwd: null });
const snapshot = useMemo<AgentProfileFormSnapshot>(
() => ({
mode,
...(profile ? { profile } : {}),
...(seed ? { seed } : {}),
...(entries ? { entries } : {}),
}),
[entries, mode, profile, seed],
);
const model = useAgentProfileFormModel(snapshot);
const state = useAgentProfileFormState(model);
useAgentProfileFormCatalog({ serverId, model });
useAgentProfileFormControls({ serverId, model, state });
const mountedRef = useRef(true);
useEffect(() => {
mountedRef.current = true;
return () => {
mountedRef.current = false;
};
}, []);
const save = useCallback(async (): Promise<boolean> => {
const value = model.getState().submitValue;
if (!value) {
return false;
}
model.setSubmitError(null);
model.setSubmitting(true);
try {
await onSave(value);
// Only notify completion while this session is still active; switching profiles
// mid-save unmounts this session and must not close the next editor's draft.
if (mountedRef.current) {
onSaved();
}
return true;
} catch (error) {
model.setSubmitError(toErrorMessage(error));
return false;
} finally {
model.setSubmitting(false);
}
}, [model, onSave, onSaved]);
return useMemo(() => ({ model, state, isDirty: state.isDirty, save }), [model, save, state]);
}
@@ -1,16 +1,19 @@
import { useCallback, useMemo, useRef, useState, type ReactElement } from "react";
import { Pressable, View, type PressableStateCallbackType } from "react-native";
import { View, type PressableStateCallbackType } from "react-native";
import { useTranslation } from "react-i18next";
import type { TFunction } from "i18next";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { Check, ChevronDown } from "lucide-react-native";
import { Combobox, type ComboboxOption } from "@/components/ui/combobox";
import {
bySizing,
createControlGeometry,
resolveControlInteractionStyles,
TOUCH_TARGET,
type ControlSize,
} from "@/components/ui/control-geometry";
import { Field } from "@/components/ui/form-field";
import { mutedIconColorMapping } from "@/components/ui/icon-color";
import { PressHighlight } from "@/components/ui/press-highlight";
import { identityForeground } from "@/styles/identity-colors";
import { ICON_SIZE, type Theme } from "@/styles/theme";
import { AgentProfileGlyph } from "../internal/agent-profile-glyph";
@@ -37,7 +40,6 @@ const EMPTY_COMBOBOX_OPTIONS: ComboboxOption[] = [];
const ThemedChevronDown = withUnistyles(ChevronDown);
const ThemedCheck = withUnistyles(Check);
const foregroundMutedMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
const onIdentityMapping = (theme: Theme) => ({ color: theme.colors.background });
/**
@@ -56,39 +58,43 @@ function IconCell({
iconKey,
selected,
color,
provider,
serverId,
onSelect,
}: {
iconKey: AgentProfileIconKey | null;
selected: boolean;
color: AgentProfileColor;
provider?: string;
serverId?: string | null;
onSelect: (iconKey: AgentProfileIconKey | null) => void;
}) {
const handlePress = useCallback(() => onSelect(iconKey), [iconKey, onSelect]);
const accessibilityState = useMemo(() => ({ selected }), [selected]);
const cellStyle = useCallback(
({ hovered, pressed }: PressableStateCallbackType & { hovered?: boolean }) => [
({ hovered }: PressableStateCallbackType & { hovered?: boolean }) => [
styles.cell,
Boolean(hovered) && styles.cellHovered,
pressed && styles.cellPressed,
selected && styles.cellSelected,
],
[selected],
);
return (
<Pressable
<PressHighlight
onPress={handlePress}
style={cellStyle}
highlightStyle={styles.cellPressed}
accessibilityRole="button"
accessibilityState={accessibilityState}
accessibilityLabel={iconKey ?? "default"}
testID={`agent-profile-icon-cell-${iconKey ?? "default"}`}
>
<AgentProfileGlyph
{...(iconKey ? { icon: iconKey } : {})}
{...(iconKey ? { icon: iconKey } : { provider, serverId })}
color={color}
size={ICON_SIZE.lg}
/>
</Pressable>
</PressHighlight>
);
}
@@ -104,58 +110,54 @@ function ColorCell({
const { t } = useTranslation();
const handlePress = useCallback(() => onSelect(color), [color, onSelect]);
const accessibilityState = useMemo(() => ({ selected }), [selected]);
const swatchStyle = useMemo(
() => [styles.swatch, color === "none" ? styles.swatchNone : identitySwatch(color)],
[color],
);
const cellStyle = useCallback(
({ pressed }: PressableStateCallbackType) => [styles.colorCell, pressed && styles.cellPressed],
[],
);
return (
<Pressable
<PressHighlight
onPress={handlePress}
style={cellStyle}
style={styles.colorCell}
highlightStyle={styles.cellPressed}
accessibilityRole="button"
accessibilityState={accessibilityState}
accessibilityLabel={colorLabel(t, color)}
testID={`agent-profile-color-cell-${color}`}
>
<View style={swatchStyle}>
<View style={[styles.swatch, color === "none" ? styles.swatchNone : identitySwatch(color)]}>
{selected ? (
<ThemedCheck
size={ICON_SIZE.sm}
uniProps={color === "none" ? foregroundMutedMapping : onIdentityMapping}
uniProps={color === "none" ? mutedIconColorMapping : onIdentityMapping}
/>
) : null}
</View>
</Pressable>
</PressHighlight>
);
}
/**
* Icon and colour in one popover rather than two fields: the pair is a single
* visual decision, and picking them apart means never seeing the result until
* both are closed. The grid redraws in the chosen colour as you switch colours,
* so the swatch row sits above it.
* Compact clickable icon+color tile that opens the appearance popover without
* requiring a separate labeled field box. Used inline beside the Name input
* and in the inspector drawer header.
*/
export function AgentProfileAppearanceField({
export function AgentProfileIconButton({
label,
icon,
color,
provider,
serverId,
onChange,
size = "md",
variant = "field",
disabled = false,
testID,
triggerTestID,
}: {
label: string;
icon: string;
color: string;
provider?: string;
serverId?: string | null;
onChange: (next: { icon: string; color: string }) => void;
size?: ControlSize;
variant?: "field" | "hero";
disabled?: boolean;
testID?: string;
triggerTestID?: string;
}): ReactElement {
const { t } = useTranslation();
@@ -188,8 +190,10 @@ export function AgentProfileAppearanceField({
const triggerStyle = useCallback(
({ hovered, pressed }: PressableStateCallbackType & { hovered?: boolean }) => [
styles.trigger,
size === "sm" ? styles.triggerSm : styles.triggerMd,
styles.triggerIconOnly,
variant === "hero" && styles.triggerHero,
variant !== "hero" && size === "sm" && styles.triggerSm,
variant !== "hero" && size !== "sm" && styles.triggerMd,
variant === "field" && styles.triggerIconOnly,
resolveControlInteractionStyles(
{
controlRest: styles.controlRest,
@@ -200,29 +204,36 @@ export function AgentProfileAppearanceField({
{ hovered: Boolean(hovered), active: pressed || open, disabled },
),
],
[disabled, open, size],
[disabled, open, size, variant],
);
const header = useMemo(() => ({ title: label }), [label]);
return (
<Field label={label} testID={testID}>
<>
<View ref={anchorRef} collapsable={false}>
<Pressable
<PressHighlight
onPress={handleTriggerPress}
disabled={disabled}
style={triggerStyle}
highlightStyle={styles.triggerPressed}
accessibilityRole="button"
accessibilityLabel={`${label} (${colorLabel(t, selectedColor)})`}
testID={triggerTestID}
>
<AgentProfileGlyph
{...(selectedIcon ? { icon: selectedIcon } : {})}
{...(selectedIcon ? { icon: selectedIcon } : { provider, serverId })}
color={selectedColor}
size={ICON_SIZE.md}
size={variant === "hero" ? ICON_SIZE.lg : ICON_SIZE.md}
/>
<ThemedChevronDown size={ICON_SIZE.sm} uniProps={foregroundMutedMapping} />
</Pressable>
{variant === "hero" ? (
<View style={styles.heroCaretBadge}>
<ThemedChevronDown size={ICON_SIZE.xs} uniProps={mutedIconColorMapping} />
</View>
) : (
<ThemedChevronDown size={ICON_SIZE.xs} uniProps={mutedIconColorMapping} />
)}
</PressHighlight>
</View>
<Combobox
options={EMPTY_COMBOBOX_OPTIONS}
@@ -251,6 +262,8 @@ export function AgentProfileAppearanceField({
iconKey={null}
selected={selectedIcon === null}
color={selectedColor}
provider={provider}
serverId={serverId}
onSelect={handleIconSelect}
/>
{AGENT_PROFILE_ICON_KEYS.map((key) => (
@@ -265,7 +278,7 @@ export function AgentProfileAppearanceField({
</View>
</View>
</Combobox>
</Field>
</>
);
}
@@ -279,6 +292,8 @@ function identitySwatch(color: Exclude<AgentProfileColor, "none">) {
return styles[IDENTITY_SWATCH_STYLE_KEYS[color]];
}
const HERO_BUTTON_SIZE = bySizing({ touch: TOUCH_TARGET, pointer: 40 });
const styles = StyleSheet.create((theme) => {
const geometry = createControlGeometry(theme);
@@ -292,6 +307,29 @@ const styles = StyleSheet.create((theme) => {
},
triggerSm: { ...geometry.fieldControlSm },
triggerMd: { ...geometry.fieldControlMd },
triggerHero: {
width: HERO_BUTTON_SIZE,
height: HERO_BUTTON_SIZE,
borderRadius: theme.borderRadius.lg,
paddingHorizontal: 0,
position: "relative",
},
triggerPressed: {
backgroundColor: theme.colors.surface3,
},
heroCaretBadge: {
position: "absolute",
right: -theme.spacing[1],
bottom: -theme.spacing[1],
width: theme.spacing[4],
height: theme.spacing[4],
borderRadius: theme.borderRadius.full,
backgroundColor: theme.colors.surface1,
borderWidth: theme.borderWidth[1],
borderColor: theme.colors.borderAccent,
alignItems: "center",
justifyContent: "center",
},
// The field geometry pads for a line of text. This trigger holds a glyph and
// a chevron, so it keeps the shared height and drops the text-sized inset.
triggerIconOnly: {
@@ -339,7 +377,7 @@ const styles = StyleSheet.create((theme) => {
backgroundColor: theme.colors.surface2,
},
cellPressed: {
opacity: 0.7,
opacity: theme.opacity[50],
},
cellSelected: {
backgroundColor: theme.colors.surface2,
@@ -0,0 +1,503 @@
import { useCallback, useMemo, type ReactElement } from "react";
import { Text, View } from "react-native";
import { useTranslation } from "react-i18next";
import { ArrowDown, ArrowUp, Copy, MoreVertical, Trash2, X } from "lucide-react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import type { AgentProfile } from "@getpaseo/protocol/messages";
import { TitlebarDragRegion } from "@/components/desktop/titlebar-drag-region";
import { Button } from "@/components/ui/button";
import { DismissBackdrop } from "@/components/ui/dismiss-backdrop";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
} from "@/components/ui/dropdown-menu";
import { mutedIconColorMapping } from "@/components/ui/icon-color";
import { ToolbarButton } from "@/components/ui/pane-content-toolbar";
import { ScrollView } from "@/components/ui/scroll-view";
import { useOverlayRegistration, type KeyboardInputEvent } from "@/keyboard";
import { OverlayLayerProvider, useOverlayLayer } from "@/lib/overlay-root";
import { ICON_SIZE, type Theme } from "@/styles/theme";
import { WindowChromeRegion, WindowChromeSafeArea } from "@/utils/desktop-window";
import type { AgentProfileSeed, AgentProfileValue } from "../internal/profile-form-model";
import {
useAgentProfileFormSession,
type AgentProfileFormSession,
} from "../internal/use-profile-form-model";
import { AgentProfileIconButton } from "./agent-profile-appearance-field";
import { AgentProfileFormFields } from "./agent-profile-form-fields";
export const AGENT_PROFILE_DRAWER_WIDTH = 440;
const ThemedArrowUp = withUnistyles(ArrowUp);
const ThemedArrowDown = withUnistyles(ArrowDown);
const ThemedMoreVertical = withUnistyles(MoreVertical);
const ThemedCopy = withUnistyles(Copy);
const ThemedTrash2 = withUnistyles(Trash2);
const ThemedX = withUnistyles(X);
const destructiveIconColorMapping = (theme: Theme) => ({ color: theme.colors.destructive });
const duplicateMenuIcon = <ThemedCopy size={ICON_SIZE.sm} uniProps={mutedIconColorMapping} />;
const removeMenuIcon = <ThemedTrash2 size={ICON_SIZE.sm} uniProps={destructiveIconColorMapping} />;
export interface AgentProfileDrawerProps {
serverId: string;
mode: "create" | "edit";
profile?: AgentProfile;
seed?: AgentProfileSeed;
/** Optional pre-owned session so resizing between drawer and modal preserves unsaved edits. */
session?: AgentProfileFormSession;
/** Renders as an absolute right-edge slide-over instead of reflowing the roster beside it. */
overlay?: boolean;
canStepPrev?: boolean;
canStepNext?: boolean;
onStepPrev?: () => void;
onStepNext?: () => void;
onClose: () => void;
onSave: (value: AgentProfileValue) => Promise<void>;
onDuplicate?: (profileId: string) => void;
onRemove?: (profileId: string) => void;
}
/**
* Full-height right inspector drawer for creating and editing agent profiles.
* Pinned header + independent scroll + pinned footer prevent vertical re-centering
* when async provider options resolve.
*/
export function AgentProfileDrawer(props: AgentProfileDrawerProps): ReactElement {
if (props.session) {
return <AgentProfileDrawerContent {...props} session={props.session} />;
}
const key =
props.mode === "edit"
? `drawer-edit:${props.profile?.id ?? ""}`
: `drawer-create:${props.seed?.provider ?? ""}:${props.seed?.modelId ?? ""}`;
return <StandaloneAgentProfileDrawer key={key} {...props} />;
}
function StandaloneAgentProfileDrawer(props: AgentProfileDrawerProps): ReactElement {
const session = useAgentProfileFormSession({
serverId: props.serverId,
mode: props.mode,
profile: props.profile,
seed: props.seed,
onSave: props.onSave,
onSaved: props.onClose,
});
return <AgentProfileDrawerContent {...props} session={session} />;
}
function DrawerOverflowMenu({
profileName,
disabled,
onDuplicate,
onRemove,
}: {
profileName: string;
disabled: boolean;
onDuplicate?: () => void;
onRemove?: () => void;
}): ReactElement | null {
const { t } = useTranslation();
if (!onDuplicate && !onRemove) {
return null;
}
return (
<DropdownMenu compactMode="sheet">
<ToolbarButton
kind="menu"
label={t("settings.host.agentProfiles.profileActions", { name: profileName })}
disabled={disabled}
testID="agent-profile-drawer-more"
>
<ThemedMoreVertical size={ICON_SIZE.sm} uniProps={mutedIconColorMapping} />
</ToolbarButton>
<DropdownMenuContent side="bottom" align="end" width={180}>
{onDuplicate ? (
<DropdownMenuItem
leading={duplicateMenuIcon}
onSelect={onDuplicate}
testID="agent-profile-drawer-duplicate"
>
{t("settings.host.agentProfiles.duplicate")}
</DropdownMenuItem>
) : null}
{onDuplicate && onRemove ? <DropdownMenuSeparator /> : null}
{onRemove ? (
<DropdownMenuItem
destructive
leading={removeMenuIcon}
onSelect={onRemove}
testID="agent-profile-drawer-remove"
>
{t("settings.host.agentProfiles.remove")}
</DropdownMenuItem>
) : null}
</DropdownMenuContent>
</DropdownMenu>
);
}
function DrawerHeader({
serverId,
mode,
state,
canStepPrev,
canStepNext,
onStepPrev,
onStepNext,
onDuplicate,
onRemove,
onAppearanceChange,
onClose,
}: {
serverId: string;
mode: "create" | "edit";
state: AgentProfileFormSession["state"];
canStepPrev: boolean;
canStepNext: boolean;
onStepPrev?: () => void;
onStepNext?: () => void;
onDuplicate?: () => void;
onRemove?: () => void;
onAppearanceChange: (value: { icon: string; color: string }) => void;
onClose: () => void;
}): ReactElement {
const { t } = useTranslation();
const fallbackTitle =
mode === "edit"
? t("settings.host.agentProfiles.editProfileTitle")
: t("settings.host.agentProfiles.addProfileTitle");
const title = state.name.trim() || fallbackTitle;
const parts = [state.providerDisplay?.label, state.modelDisplay?.label].filter(Boolean);
const subtitle =
parts.length > 0 ? parts.join(" · ") : t("settings.host.agentProfiles.chooseModelPlaceholder");
const showSteppers = mode === "edit" && Boolean(onStepPrev && onStepNext);
return (
<View style={styles.headerChrome}>
<TitlebarDragRegion />
<WindowChromeSafeArea placement="below" />
<View style={styles.header}>
<View style={styles.headerIdentity}>
<AgentProfileIconButton
label={t("settings.host.agentProfiles.iconLabel")}
icon={state.icon}
color={state.color}
provider={state.provider || undefined}
serverId={serverId}
onChange={onAppearanceChange}
variant="hero"
disabled={state.isSubmitting}
triggerTestID="agent-profile-icon-trigger"
/>
<View style={styles.headerText}>
<Text style={styles.headerTitle} numberOfLines={1} testID="agent-profile-drawer-title">
{title}
</Text>
<Text style={styles.headerSubtitle} numberOfLines={1}>
{subtitle}
</Text>
</View>
</View>
<View style={styles.headerActions}>
{showSteppers && onStepPrev && onStepNext ? (
<>
<ToolbarButton
label={t("settings.host.agentProfiles.previousProfile")}
onPress={onStepPrev}
disabled={!canStepPrev || state.isSubmitting}
testID="agent-profile-drawer-prev"
>
<ThemedArrowUp size={ICON_SIZE.sm} uniProps={mutedIconColorMapping} />
</ToolbarButton>
<ToolbarButton
label={t("settings.host.agentProfiles.nextProfile")}
onPress={onStepNext}
disabled={!canStepNext || state.isSubmitting}
testID="agent-profile-drawer-next"
>
<ThemedArrowDown size={ICON_SIZE.sm} uniProps={mutedIconColorMapping} />
</ToolbarButton>
</>
) : null}
{mode === "edit" ? (
<DrawerOverflowMenu
profileName={title}
disabled={state.isSubmitting}
onDuplicate={onDuplicate}
onRemove={onRemove}
/>
) : null}
<ToolbarButton
label={t("common.actions.close")}
onPress={onClose}
disabled={state.isSubmitting}
testID="agent-profile-drawer-close"
>
<ThemedX size={ICON_SIZE.md} uniProps={mutedIconColorMapping} />
</ToolbarButton>
</View>
</View>
</View>
);
}
function DrawerFooter({
canSubmit,
isSubmitting,
onClose,
onSave,
}: {
canSubmit: boolean;
isSubmitting: boolean;
onClose: () => void;
onSave: () => void;
}): ReactElement {
const { t } = useTranslation();
return (
<View style={styles.footer}>
<Button
variant="secondary"
onPress={onClose}
disabled={isSubmitting}
testID="agent-profile-cancel-button"
>
{t("common.actions.cancel")}
</Button>
<Button
variant="default"
onPress={onSave}
disabled={!canSubmit}
loading={isSubmitting}
testID="agent-profile-save-button"
>
{t("settings.host.agentProfiles.save")}
</Button>
</View>
);
}
function AgentProfileDrawerContent({
serverId,
mode,
profile,
session,
overlay = false,
canStepPrev = false,
canStepNext = false,
onStepPrev,
onStepNext,
onClose,
onDuplicate,
onRemove,
}: AgentProfileDrawerProps & { session: AgentProfileFormSession }): ReactElement {
const { t } = useTranslation();
const { model, state, save } = session;
const drawerLayer = useOverlayLayer("floating");
const handleOverlayKeyDown = useCallback(
(event: KeyboardInputEvent) => {
if (event.key !== "Escape") {
return false;
}
event.preventDefault();
event.stopPropagation();
if (!state.isSubmitting) {
onClose();
}
return true;
},
[onClose, state.isSubmitting],
);
const setOverlayScope = useOverlayRegistration({
keys: ["Escape"],
active: true,
layer: drawerLayer,
// Only trap focus in slide-over overlay mode; a docked drawer sits beside the
// interactive roster and must let users click and type in roster search.
manageFocus: overlay,
onKeyDown: handleOverlayKeyDown,
});
const handleAppearanceChange = useCallback(
(value: { icon: string; color: string }) => model.setAppearance(value),
[model],
);
const handleSavePress = useCallback(() => {
void save();
}, [save]);
const handleDuplicate = useCallback(() => {
if (profile && onDuplicate) {
onDuplicate(profile.id);
}
}, [onDuplicate, profile]);
const handleRemove = useCallback(() => {
if (profile && onRemove) {
onRemove(profile.id);
}
}, [onRemove, profile]);
const handleBackdropPress = useCallback(() => {
if (!state.isSubmitting) {
onClose();
}
}, [onClose, state.isSubmitting]);
const drawerStyle = useMemo(
() => [styles.drawer, overlay && styles.drawerOverlay, overlay && { zIndex: drawerLayer }],
[drawerLayer, overlay],
);
const overlayHostStyle = useMemo(
() => [styles.overlayHost, { zIndex: drawerLayer }],
[drawerLayer],
);
const drawerPanel = (
<WindowChromeRegion corners="top-right">
<OverlayLayerProvider layer={drawerLayer}>
<View ref={setOverlayScope} style={drawerStyle} testID="agent-profile-drawer">
<DrawerHeader
serverId={serverId}
mode={mode}
state={state}
canStepPrev={canStepPrev}
canStepNext={canStepNext}
onStepPrev={onStepPrev}
onStepNext={onStepNext}
onDuplicate={profile && onDuplicate ? handleDuplicate : undefined}
onRemove={profile && onRemove ? handleRemove : undefined}
onAppearanceChange={handleAppearanceChange}
onClose={onClose}
/>
<ScrollView style={styles.scroll} keyboardShouldPersistTaps="handled">
<View style={styles.scrollContent}>
<AgentProfileFormFields
serverId={serverId}
model={model}
state={state}
showInlineIcon={false}
collapsibleDefaults={false}
/>
</View>
</ScrollView>
<DrawerFooter
canSubmit={state.canSubmit}
isSubmitting={state.isSubmitting}
onClose={onClose}
onSave={handleSavePress}
/>
</View>
</OverlayLayerProvider>
</WindowChromeRegion>
);
if (!overlay) {
return drawerPanel;
}
return (
<View style={overlayHostStyle} pointerEvents="box-none">
<View style={styles.overlayBackdrop} pointerEvents="none" />
<DismissBackdrop label={t("common.actions.close")} onPress={handleBackdropPress} />
{drawerPanel}
</View>
);
}
const styles = StyleSheet.create((theme) => ({
overlayHost: {
position: "absolute",
top: 0,
right: 0,
bottom: 0,
left: 0,
flexDirection: "row",
justifyContent: "flex-end",
},
overlayBackdrop: {
position: "absolute",
top: 0,
right: 0,
bottom: 0,
left: 0,
backgroundColor: theme.colors.background,
opacity: theme.opacity[50],
},
drawer: {
width: AGENT_PROFILE_DRAWER_WIDTH,
flexShrink: 0,
backgroundColor: theme.colors.surface0,
borderLeftWidth: theme.borderWidth[1],
borderLeftColor: theme.colors.borderAccent,
},
drawerOverlay: {
height: "100%",
...theme.shadow.lg,
},
headerChrome: {
position: "relative",
borderBottomWidth: theme.borderWidth[1],
borderBottomColor: theme.colors.border,
},
header: {
flexDirection: "row",
alignItems: "center",
justifyContent: "space-between",
gap: theme.spacing[3],
paddingHorizontal: theme.spacing[4],
paddingVertical: theme.spacing[4],
},
headerIdentity: {
flex: 1,
minWidth: 0,
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[3],
},
headerText: {
flex: 1,
minWidth: 0,
gap: theme.spacing[0.5],
},
headerTitle: {
color: theme.colors.foreground,
fontSize: theme.fontSize.base,
fontWeight: theme.fontWeight.medium,
},
headerSubtitle: {
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.sm,
},
headerActions: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[1],
flexShrink: 0,
},
scroll: {
flex: 1,
},
scrollContent: {
padding: theme.spacing[4],
paddingBottom: theme.spacing[8],
},
footer: {
flexDirection: "row",
alignItems: "center",
justifyContent: "flex-end",
gap: theme.spacing[2],
paddingHorizontal: theme.spacing[4],
paddingVertical: theme.spacing[3],
borderTopWidth: theme.borderWidth[1],
borderTopColor: theme.colors.border,
backgroundColor: theme.colors.surface0,
},
}));
@@ -1,36 +1,16 @@
import { useCallback, useEffect, useMemo, useRef, useState, type ReactElement } from "react";
import { Text, View } from "react-native";
import { View } from "react-native";
import { useTranslation } from "react-i18next";
import { StyleSheet } from "react-native-unistyles";
import type { AgentOptionControl, ProviderOptions } from "@getpaseo/protocol/agent-types";
import { readSelectOption, readToggleOption } from "@/agent-controls/option-controls";
import type { AgentProfile } from "@getpaseo/protocol/messages";
import { AdaptiveModalSheet, type SheetHeader } from "@/components/adaptive-modal-sheet";
import { Button } from "@/components/ui/button";
import { type ControlSize } from "@/components/ui/control-geometry";
import { Field, FormTextInput } from "@/components/ui/form-field";
import type { AgentProfileSeed, AgentProfileValue } from "../internal/profile-form-model";
import {
SelectField,
type SelectFieldDisplay,
type SelectFieldOption,
} from "@/components/ui/select-field";
import { Switch } from "@/components/ui/switch";
import { toErrorMessage } from "@/utils/error-messages";
import { AgentProfileAppearanceField } from "./agent-profile-appearance-field";
import type {
AgentProfileFormModel,
AgentProfileFormOption,
AgentProfileSeed,
AgentProfileValue,
} from "../internal/profile-form-model";
import {
useAgentProfileFormCatalog,
useAgentProfileFormControls,
} from "../internal/use-profile-form-inputs";
import {
useAgentProfileFormModel,
useAgentProfileFormState,
useAgentProfileFormSession,
type AgentProfileFormSession,
} from "../internal/use-profile-form-model";
import { AgentProfileFormFields } from "./agent-profile-form-fields";
export interface AgentProfileEditModalProps {
serverId: string;
@@ -38,16 +18,15 @@ export interface AgentProfileEditModalProps {
mode: "create" | "edit";
profile?: AgentProfile;
seed?: AgentProfileSeed;
/** Optional pre-owned session so resizing between drawer and modal preserves unsaved edits. */
session?: AgentProfileFormSession;
/** Starts create mode with Mode, Thinking, Notes & Options collapsed behind a summary row. */
collapsibleDefaults?: boolean;
onClose: () => void;
onSave: (value: AgentProfileValue) => Promise<void>;
onRemove?: (profileId: string) => void;
}
/**
* Only reachable before the catalog lands. Every select is seeded to a concrete
* id as soon as one exists, and none of them offer an "unset" row.
*/
const UNSET_VALUE = "";
function openKey(props: AgentProfileEditModalProps): string {
if (props.mode === "edit") {
return `edit:${props.profile?.id ?? ""}`;
@@ -57,7 +36,11 @@ function openKey(props: AgentProfileEditModalProps): string {
/**
* Create and edit never share a mounted instance: the body is keyed on mode plus
* profile id, so every open constructs a form model seeded from that record.
* profile id (unless the caller lifts `session`), so every open constructs a form
* model seeded from that record.
*
* Used for editing from the composer model picker and on compact/narrow screens
* where Settings cannot host a slide-over drawer.
*/
export function AgentProfileEditModal(props: AgentProfileEditModalProps): ReactElement | null {
const [renderedProps, setRenderedProps] = useState<AgentProfileEditModalProps | null>(() =>
@@ -101,10 +84,24 @@ export function AgentProfileEditModal(props: AgentProfileEditModalProps): ReactE
return null;
}
const activeProps = props.visible ? props : renderedProps;
if (activeProps.session) {
return (
<AgentProfileEditModalContent
{...activeProps}
session={activeProps.session}
visible={sheetVisible}
onClose={requestClose}
onDismiss={handleDismiss}
/>
);
}
return (
<OpenAgentProfileEditModal
key={openKey(renderedProps)}
{...renderedProps}
<StandaloneAgentProfileEditModal
key={openKey(activeProps)}
{...activeProps}
visible={sheetVisible}
onClose={requestClose}
onDismiss={handleDismiss}
@@ -112,36 +109,36 @@ export function AgentProfileEditModal(props: AgentProfileEditModalProps): ReactE
);
}
function toSelectOptions(options: AgentProfileFormOption[]): SelectFieldOption<string>[] {
return options.map((option) => ({
id: option.id,
value: option.value,
label: option.label,
...(option.description ? { description: option.description } : {}),
testID: option.testID,
}));
function StandaloneAgentProfileEditModal(
props: AgentProfileEditModalProps & { onDismiss: () => void },
): ReactElement {
const session = useAgentProfileFormSession({
serverId: props.serverId,
mode: props.mode,
profile: props.profile,
seed: props.seed,
onSave: props.onSave,
onSaved: props.onClose,
});
return <AgentProfileEditModalContent {...props} session={session} />;
}
function OpenAgentProfileEditModal({
function AgentProfileEditModalContent({
serverId,
visible,
mode,
profile,
seed,
session,
collapsibleDefaults,
onClose,
onDismiss,
onSave,
}: AgentProfileEditModalProps & { onDismiss: () => void }): ReactElement {
onRemove,
}: AgentProfileEditModalProps & {
session: AgentProfileFormSession;
onDismiss: () => void;
}): ReactElement {
const { t } = useTranslation();
const controlSize: ControlSize = "md";
const snapshot = useMemo(
() => ({ mode, ...(profile ? { profile } : {}), ...(seed ? { seed } : {}) }),
[mode, profile, seed],
);
const model = useAgentProfileFormModel(snapshot);
const state = useAgentProfileFormState(model);
useAgentProfileFormCatalog({ serverId, model });
useAgentProfileFormControls({ serverId, model, state });
const { model, state, save } = session;
const sheetHeader = useMemo<SheetHeader>(
() => ({
@@ -153,59 +150,9 @@ function OpenAgentProfileEditModal({
[mode, t],
);
const providerOptions = useMemo(
() => toSelectOptions(state.providerOptions),
[state.providerOptions],
);
const modelOptions = useMemo(() => toSelectOptions(state.modelOptions), [state.modelOptions]);
const modeOptions = useMemo(() => toSelectOptions(state.modeOptions), [state.modeOptions]);
const thinkingOptions = useMemo(
() => toSelectOptions(state.thinkingOptions),
[state.thinkingOptions],
);
const handleAppearanceChange = useCallback(
(value: { icon: string; color: string }) => model.setAppearance(value),
[model],
);
const handleProviderChange = useCallback(
(value: string, display: SelectFieldDisplay) => model.setProvider(value, display),
[model],
);
const handleModelChange = useCallback(
(value: string, display: SelectFieldDisplay) => model.setModel(value, value ? display : null),
[model],
);
const handleModeChange = useCallback(
(value: string, display: SelectFieldDisplay) => model.setMode(value, value ? display : null),
[model],
);
const handleThinkingChange = useCallback(
(value: string, display: SelectFieldDisplay) =>
model.setThinking(value, value ? display : null),
[model],
);
const handleSave = useCallback(async () => {
const value = model.getState().submitValue;
if (!value) {
return;
}
model.setSubmitError(null);
model.setSubmitting(true);
try {
await onSave(value);
onClose();
} catch (error) {
model.setSubmitError(toErrorMessage(error));
} finally {
model.setSubmitting(false);
}
}, [model, onClose, onSave]);
const handleSavePress = useCallback(() => {
void handleSave();
}, [handleSave]);
void save();
}, [save]);
const handleCancel = useCallback(() => {
if (state.isSubmitting) {
@@ -214,170 +161,31 @@ function OpenAgentProfileEditModal({
onClose();
}, [onClose, state.isSubmitting]);
return (
<AdaptiveModalSheet
visible={visible}
header={sheetHeader}
onClose={handleCancel}
onDismiss={onDismiss}
desktopMaxWidth={520}
testID="agent-profile-edit-modal"
>
<View style={styles.body}>
<View style={styles.nameRow}>
<View style={styles.iconField}>
<AgentProfileAppearanceField
label={t("settings.host.agentProfiles.iconLabel")}
icon={state.icon}
color={state.color}
onChange={handleAppearanceChange}
const handleRemove = useCallback(() => {
if (!profile || !onRemove) {
return;
}
onRemove(profile.id);
}, [onRemove, profile]);
const footer = useMemo(
() => (
<View style={styles.footer}>
<View style={styles.footerStart}>
{mode === "edit" && profile && onRemove ? (
<Button
variant="outline"
onPress={handleRemove}
disabled={state.isSubmitting}
size={controlSize}
testID="agent-profile-icon-field"
triggerTestID="agent-profile-icon-trigger"
/>
</View>
<View style={styles.nameField}>
<Field
label={t("settings.host.agentProfiles.nameLabel")}
testID="agent-profile-name-field"
testID="agent-profile-modal-remove-button"
>
<FormTextInput
initialValue={seed?.name ?? profile?.name ?? ""}
onChangeText={model.setName}
placeholder={t("settings.host.agentProfiles.namePlaceholder")}
autoCapitalize="none"
autoCorrect={false}
editable={!state.isSubmitting}
size={controlSize}
accessibilityLabel={t("settings.host.agentProfiles.nameLabel")}
testID="agent-profile-name-input"
/>
</Field>
</View>
{t("settings.host.agentProfiles.remove")}
</Button>
) : null}
</View>
<SelectField
label={t("settings.host.agentProfiles.providerLabel")}
value={state.provider || null}
selectedDisplay={state.providerDisplay}
options={providerOptions}
onChange={handleProviderChange}
placeholder={t("settings.host.agentProfiles.providerPlaceholder")}
emptyText={t("settings.host.agentProfiles.noProviders")}
loading={state.catalogResolution !== "complete"}
disabled={state.isSubmitting}
searchable={providerOptions.length > 6}
title={t("settings.host.agentProfiles.providerLabel")}
size={controlSize}
testID="agent-profile-provider-field"
triggerTestID="agent-profile-provider-trigger"
/>
{state.disclosure.showModelField ? (
<SelectField
label={t("settings.host.agentProfiles.modelLabel")}
value={state.modelId || UNSET_VALUE}
selectedDisplay={state.modelDisplay}
options={modelOptions}
onChange={handleModelChange}
placeholder={t("settings.host.agentProfiles.modelLabel")}
emptyText={t("settings.host.agentProfiles.noModels")}
disabled={state.isSubmitting}
searchable={modelOptions.length > 6}
title={t("settings.host.agentProfiles.modelLabel")}
size={controlSize}
testID="agent-profile-model-field"
triggerTestID="agent-profile-model-trigger"
/>
) : null}
{state.disclosure.showModeField ? (
<SelectField
label={t("settings.host.agentProfiles.modeLabel")}
value={state.modeId || UNSET_VALUE}
selectedDisplay={state.modeDisplay}
options={modeOptions}
onChange={handleModeChange}
placeholder={t("settings.host.agentProfiles.modeLabel")}
emptyText={t("settings.host.agentProfiles.noModes")}
disabled={state.isSubmitting}
searchable={modeOptions.length > 6}
title={t("settings.host.agentProfiles.modeLabel")}
size={controlSize}
testID="agent-profile-mode-field"
triggerTestID="agent-profile-mode-trigger"
/>
) : null}
{state.disclosure.showThinkingField ? (
<SelectField
label={t("settings.host.agentProfiles.thinkingLabel")}
value={state.thinkingOptionId || UNSET_VALUE}
selectedDisplay={state.thinkingDisplay}
options={thinkingOptions}
onChange={handleThinkingChange}
placeholder={t("settings.host.agentProfiles.thinkingLabel")}
emptyText={t("settings.host.agentProfiles.noThinkingOptions")}
disabled={state.isSubmitting}
searchable={thinkingOptions.length > 6}
title={t("settings.host.agentProfiles.thinkingLabel")}
size={controlSize}
testID="agent-profile-thinking-field"
triggerTestID="agent-profile-thinking-trigger"
/>
) : null}
{state.disclosure.showControlsField ? (
<Field
label={t("settings.host.agentProfiles.featuresLabel")}
testID="agent-profile-features-field"
>
<View style={styles.featureCard} testID="agent-profile-features-card">
{state.controls.map((control, index) => (
<AgentProfileControlRow
key={control.key}
control={control}
options={state.controlOptions}
isFirst={index === 0}
disabled={state.isSubmitting}
size={controlSize}
model={model}
/>
))}
</View>
</Field>
) : null}
<Field
label={t("settings.host.agentProfiles.notesLabel")}
hint={t("settings.host.agentProfiles.notesHint")}
testID="agent-profile-notes-field"
>
<FormTextInput
initialValue={profile?.notes ?? ""}
onChangeText={model.setNotes}
placeholder={t("settings.host.agentProfiles.notesPlaceholder")}
multiline
numberOfLines={4}
style={styles.notesInput}
editable={!state.isSubmitting}
size={controlSize}
accessibilityLabel={t("settings.host.agentProfiles.notesLabel")}
testID="agent-profile-notes-input"
/>
</Field>
{state.submitError ? (
<Text style={styles.submitError} testID="agent-profile-submit-error">
{state.submitError}
</Text>
) : null}
<View style={styles.actions}>
<View style={styles.footerEnd}>
<Button
variant="secondary"
style={styles.actionButton}
onPress={handleCancel}
disabled={state.isSubmitting}
testID="agent-profile-cancel-button"
@@ -386,177 +194,65 @@ function OpenAgentProfileEditModal({
</Button>
<Button
variant="default"
style={styles.actionButton}
onPress={handleSavePress}
disabled={!state.canSubmit}
loading={state.isSubmitting}
testID="agent-profile-save-button"
>
{state.isSubmitting
? t("settings.host.agentProfiles.saving")
: t("settings.host.agentProfiles.save")}
{t("settings.host.agentProfiles.save")}
</Button>
</View>
</View>
),
[
handleCancel,
handleRemove,
handleSavePress,
mode,
onRemove,
profile,
state.canSubmit,
state.isSubmitting,
t,
],
);
return (
<AdaptiveModalSheet
visible={visible}
header={sheetHeader}
footer={footer}
onClose={handleCancel}
onDismiss={onDismiss}
desktopMaxWidth={500}
testID="agent-profile-edit-modal"
>
<AgentProfileFormFields
serverId={serverId}
model={model}
state={state}
collapsibleDefaults={collapsibleDefaults ?? mode === "create"}
/>
</AdaptiveModalSheet>
);
}
function AgentProfileControlRow({
control,
options,
isFirst,
disabled,
size,
model,
}: {
control: AgentOptionControl;
options: ProviderOptions;
isFirst: boolean;
disabled: boolean;
size: ControlSize;
model: AgentProfileFormModel;
}): ReactElement {
const rowStyle = useMemo(
() => [styles.featureRow, isFirst ? null : styles.featureRowBorder],
[isFirst],
);
const handleToggle = useCallback(
(value: boolean) => model.setOption(control.key, value),
[control.key, model],
);
const handleSelect = useCallback(
(value: string) => model.setOption(control.key, value),
[control.key, model],
);
const selectOptions = useMemo<SelectFieldOption<string>[]>(
() =>
control.type === "select"
? control.choices.map((choice) => ({
id: choice.value,
value: choice.value,
label: choice.label,
...(choice.description ? { description: choice.description } : {}),
testID: `agent-profile-feature-option-${control.key}-${choice.value}`,
}))
: [],
[control],
);
const selectedValue = control.type === "select" ? readSelectOption(control, options) : null;
const selectedDisplay = useMemo<SelectFieldDisplay | null>(() => {
if (control.type !== "select" || !selectedValue) {
return null;
}
const choice = control.choices.find((candidate) => candidate.value === selectedValue);
return { label: choice?.label ?? selectedValue };
}, [control, selectedValue]);
if (control.type === "select") {
return (
<View style={rowStyle} testID={`agent-profile-feature-row-${control.key}`}>
<SelectField
label={control.label}
value={selectedValue}
selectedDisplay={selectedDisplay}
options={selectOptions}
onChange={handleSelect}
placeholder={control.label}
emptyText={control.label}
disabled={disabled}
{...(control.description ? { hint: control.description } : {})}
title={control.label}
size={size}
testID={`agent-profile-feature-field-${control.key}`}
triggerTestID={`agent-profile-feature-trigger-${control.key}`}
/>
</View>
);
}
return (
<View style={rowStyle} testID={`agent-profile-feature-row-${control.key}`}>
<View style={styles.featureMeta}>
<Text style={styles.featureLabel} numberOfLines={1}>
{control.label}
</Text>
{control.description ? (
<Text style={styles.featureDescription} numberOfLines={2}>
{control.description}
</Text>
) : null}
</View>
<Switch
value={readToggleOption(control, options)}
onValueChange={handleToggle}
disabled={disabled}
accessibilityLabel={control.label}
testID={`agent-profile-feature-switch-${control.key}`}
/>
</View>
);
}
const styles = StyleSheet.create((theme) => ({
body: {
gap: theme.spacing[4],
paddingBottom: theme.spacing[2],
},
nameRow: {
flexDirection: "row",
alignItems: "flex-start",
gap: theme.spacing[2],
},
// No width: the trigger is a glyph and a chevron, so it sizes to them.
iconField: {
flexShrink: 0,
},
nameField: {
footer: {
flex: 1,
},
featureCard: {
backgroundColor: theme.colors.surface2,
borderRadius: theme.borderRadius.md,
borderWidth: 1,
borderColor: theme.colors.border,
paddingHorizontal: theme.spacing[3],
},
featureRow: {
flexDirection: "row",
alignItems: "center",
justifyContent: "space-between",
gap: theme.spacing[3],
paddingVertical: theme.spacing[3],
gap: theme.spacing[2],
},
featureRowBorder: {
borderTopWidth: 1,
borderTopColor: theme.colors.border,
},
featureMeta: {
flex: 1,
gap: theme.spacing[1],
},
featureLabel: {
color: theme.colors.foreground,
fontSize: theme.fontSize.base,
},
featureDescription: {
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.sm,
},
notesInput: {
minHeight: 88,
textAlignVertical: "top",
},
submitError: {
color: theme.colors.statusDanger,
fontSize: theme.fontSize.base,
},
actions: {
footerStart: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[2],
marginTop: theme.spacing[2],
},
actionButton: {
flex: 1,
footerEnd: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[2],
},
}));
@@ -0,0 +1,567 @@
import { useCallback, useMemo, useRef, type ReactElement, type ReactNode } from "react";
import { Text, View } from "react-native";
import { useTranslation } from "react-i18next";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import type {
AgentOptionControl,
AgentProvider,
ProviderOptions,
} from "@getpaseo/protocol/agent-types";
import { readSelectOption, readToggleOption } from "@/agent-controls/option-controls";
import { CombinedModelSelector } from "@/components/combined-model-selector";
import {
SettingsCard,
SettingsCollapsibleRow,
SettingsSelect,
SettingsSwitch,
} from "@/components/settings";
import type { ControlSize } from "@/components/ui/control-geometry";
import { Field, FormTextInput } from "@/components/ui/form-field";
import { mutedIconColorMapping } from "@/components/ui/icon-color";
import { LoadingSpinner } from "@/components/ui/loading-spinner";
import { SegmentedControl, type SegmentedControlOption } from "@/components/ui/segmented-control";
import {
SelectField,
SelectFieldTrigger,
type SelectFieldDisplay,
type SelectFieldOption,
} from "@/components/ui/select-field";
import type { EditingTextInputHandle } from "@/components/ui/text-input";
import { useProvidersSnapshot } from "@/hooks/use-providers-snapshot";
import { buildSelectableProviderSelectorProviders } from "@/provider-selection/provider-selection";
import { ICON_SIZE } from "@/styles/theme";
import { AgentProfileGlyph } from "../internal/agent-profile-glyph";
import type {
AgentProfileFormModel,
AgentProfileFormOption,
AgentProfileFormState,
} from "../internal/profile-form-model";
import { AgentProfileIconButton } from "./agent-profile-appearance-field";
const ThemedLoadingSpinner = withUnistyles(LoadingSpinner);
const UNSET_VALUE = "";
function toSelectOptions(options: AgentProfileFormOption[]): SelectFieldOption<string>[] {
return options.map((option) => ({
id: option.id,
value: option.value,
label: option.label,
...(option.description ? { description: option.description } : {}),
testID: option.testID,
}));
}
function canUseSegmentedThinking(options: readonly AgentProfileFormOption[]): boolean {
return (
options.length >= 2 &&
options.length <= 4 &&
options.every((option) => option.label.trim().length <= 12)
);
}
export interface AgentProfileFormFieldsProps {
serverId: string;
model: AgentProfileFormModel;
state: AgentProfileFormState;
controlSize?: ControlSize;
/** Embeds the icon+color picker beside the Name input (used in sheets; drawer places it in its hero). */
showInlineIcon?: boolean;
/** Collapses Mode, Thinking, Notes, and Options behind a SettingsCollapsibleRow until expanded. */
collapsibleDefaults?: boolean;
}
function ThinkingField({
state,
controlSize,
onSelectChange,
onSegmentChange,
}: {
state: AgentProfileFormState;
controlSize: ControlSize;
onSelectChange: (value: string, display: SelectFieldDisplay) => void;
onSegmentChange: (value: string) => void;
}): ReactElement | null {
const { t } = useTranslation();
const thinkingOptions = useMemo(
() => toSelectOptions(state.thinkingOptions),
[state.thinkingOptions],
);
const segmentedThinkingOptions = useMemo<SegmentedControlOption<string>[]>(
() =>
state.thinkingOptions.map((option) => ({
value: option.value,
label: option.label,
disabled: state.isSubmitting,
testID: option.testID,
})),
[state.isSubmitting, state.thinkingOptions],
);
if (!state.disclosure.showThinkingField) {
return null;
}
if (canUseSegmentedThinking(state.thinkingOptions)) {
return (
<Field
label={t("settings.host.agentProfiles.thinkingLabel")}
testID="agent-profile-thinking-field"
>
<SegmentedControl
options={segmentedThinkingOptions}
value={state.thinkingOptionId || null}
onValueChange={onSegmentChange}
size={controlSize}
testID="agent-profile-thinking-trigger"
/>
</Field>
);
}
return (
<SelectField
label={t("settings.host.agentProfiles.thinkingLabel")}
value={state.thinkingOptionId || UNSET_VALUE}
selectedDisplay={state.thinkingDisplay}
options={thinkingOptions}
onChange={onSelectChange}
placeholder={t("settings.host.agentProfiles.thinkingLabel")}
emptyText={t("settings.host.agentProfiles.noThinkingOptions")}
disabled={state.isSubmitting}
searchable={thinkingOptions.length > 6}
title={t("settings.host.agentProfiles.thinkingLabel")}
size={controlSize}
testID="agent-profile-thinking-field"
triggerTestID="agent-profile-thinking-trigger"
/>
);
}
function AgentProfileControlRow({
control,
options,
disabled,
model,
}: {
control: AgentOptionControl;
options: ProviderOptions;
disabled: boolean;
model: AgentProfileFormModel;
}): ReactElement {
const handleToggle = useCallback(
(value: boolean) => model.setOption(control.key, value),
[control.key, model],
);
const handleSelect = useCallback(
(value: string) => model.setOption(control.key, value),
[control.key, model],
);
const selectOptions = useMemo(
() =>
control.type === "select"
? control.choices.map((choice) => ({ label: choice.label, value: choice.value }))
: [],
[control],
);
if (control.type === "select") {
const selectedValue = readSelectOption(control, options) ?? control.choices[0]?.value ?? "";
return (
<SettingsSelect
label={control.label}
hint={control.description}
value={selectedValue}
options={selectOptions}
onValueChange={handleSelect}
disabled={disabled}
testID={`agent-profile-feature-row-${control.key}`}
/>
);
}
return (
<SettingsSwitch
label={control.label}
hint={control.description}
value={readToggleOption(control, options)}
onValueChange={handleToggle}
disabled={disabled}
testID={`agent-profile-feature-row-${control.key}`}
/>
);
}
function AgentProfileAdvancedFields({
model,
state,
controlSize,
onModeChange,
onThinkingSelectChange,
onThinkingSegmentChange,
}: {
model: AgentProfileFormModel;
state: AgentProfileFormState;
controlSize: ControlSize;
onModeChange: (value: string, display: SelectFieldDisplay) => void;
onThinkingSelectChange: (value: string, display: SelectFieldDisplay) => void;
onThinkingSegmentChange: (value: string) => void;
}): ReactElement {
const { t } = useTranslation();
const modeOptions = useMemo(() => toSelectOptions(state.modeOptions), [state.modeOptions]);
const providerOptionsTitle = state.providerDisplay?.label
? t("settings.host.agentProfiles.providerOptionsLabel", {
provider: state.providerDisplay.label,
})
: t("settings.host.agentProfiles.featuresLabel");
const optionsPendingSpinner = useMemo(
() =>
state.controlsPending ? (
<ThemedLoadingSpinner size={ICON_SIZE.sm} uniProps={mutedIconColorMapping} />
) : null,
[state.controlsPending],
);
return (
<>
{state.disclosure.showModeField ? (
<SelectField
label={t("settings.host.agentProfiles.modeLabel")}
value={state.modeId || UNSET_VALUE}
selectedDisplay={state.modeDisplay}
options={modeOptions}
onChange={onModeChange}
placeholder={t("settings.host.agentProfiles.modeLabel")}
emptyText={t("settings.host.agentProfiles.noModes")}
disabled={state.isSubmitting}
searchable={modeOptions.length > 6}
title={t("settings.host.agentProfiles.modeLabel")}
size={controlSize}
testID="agent-profile-mode-field"
triggerTestID="agent-profile-mode-trigger"
/>
) : null}
<ThinkingField
state={state}
controlSize={controlSize}
onSelectChange={onThinkingSelectChange}
onSegmentChange={onThinkingSegmentChange}
/>
<Field
label={t("settings.host.agentProfiles.notesLabel")}
hint={t("settings.host.agentProfiles.notesHint")}
testID="agent-profile-notes-field"
>
<FormTextInput
initialValue={state.notes}
onChangeText={model.setNotes}
placeholder={t("settings.host.agentProfiles.notesPlaceholder")}
multiline
numberOfLines={3}
style={styles.notesInput}
editable={!state.isSubmitting}
size={controlSize}
accessibilityLabel={t("settings.host.agentProfiles.notesLabel")}
testID="agent-profile-notes-input"
/>
</Field>
{state.disclosure.showControlsField ? (
<Field
label={providerOptionsTitle}
trailing={optionsPendingSpinner}
testID="agent-profile-features-field"
>
<View style={state.controlsPending ? styles.featureCardPending : undefined}>
<SettingsCard testID="agent-profile-features-card">
{state.controls.map((control) => (
<AgentProfileControlRow
key={control.key}
control={control}
options={state.controlOptions}
disabled={state.isSubmitting || state.controlsPending}
model={model}
/>
))}
</SettingsCard>
</View>
</Field>
) : null}
</>
);
}
/**
* Shared profile form body used by both the desktop inspector drawer and the modal sheet.
*
* Layout order keeps inputs above async provider options: Model first (using Paseo's
* shared CombinedModelSelector), Name + icon second, Mode & Thinking, "When to use",
* and provider options last so loading options never shift controls above them.
*/
export function AgentProfileFormFields({
serverId,
model,
state,
controlSize = "md",
showInlineIcon = true,
collapsibleDefaults = false,
}: AgentProfileFormFieldsProps): ReactElement {
const { t } = useTranslation();
const nameInputRef = useRef<EditingTextInputHandle>(null);
const { entries, isLoading, isFetching, isRefreshing, refresh } = useProvidersSnapshot(serverId, {
cwd: null,
});
const modelSelectorProviders = useMemo(
() =>
buildSelectableProviderSelectorProviders(entries, {
selectedProvider: state.provider || null,
}),
[entries, state.provider],
);
const modelTriggerLeading = useMemo(
() =>
state.provider ? (
<AgentProfileGlyph provider={state.provider} serverId={serverId} size={ICON_SIZE.sm} />
) : null,
[serverId, state.provider],
);
const renderModelTrigger = useCallback(
({
selectedModelLabel,
disabled,
isOpen,
hovered,
pressed,
}: {
selectedModelLabel: string;
onPress: () => void;
disabled: boolean;
isOpen: boolean;
hovered: boolean;
pressed: boolean;
}): ReactNode => {
const displayLabel =
state.modelDisplay?.label ?? state.providerDisplay?.label ?? selectedModelLabel;
return (
<SelectFieldTrigger
label={displayLabel}
isPlaceholder={!state.provider}
placeholder={t("settings.host.agentProfiles.chooseModelPlaceholder")}
leading={modelTriggerLeading}
disabled={disabled}
active={hovered || pressed || isOpen}
size={controlSize}
testID="agent-profile-model-trigger"
/>
);
},
[
controlSize,
modelTriggerLeading,
state.modelDisplay?.label,
state.provider,
state.providerDisplay?.label,
t,
],
);
const handleAppearanceChange = useCallback(
(value: { icon: string; color: string }) => model.setAppearance(value),
[model],
);
const handleModelSelect = useCallback(
(provider: AgentProvider, modelId: string) => {
const previousName = model.getState().name;
const entry = entries?.find((candidate) => candidate.provider === provider);
const modelDef = entry?.models?.find((candidate) => candidate.id === modelId);
model.setProviderModel(provider, modelId, {
provider: { label: entry?.label ?? provider },
model: modelId ? { label: modelDef?.label ?? modelId } : null,
});
const suggestedName = model.getState().name;
if (suggestedName !== previousName) {
nameInputRef.current?.replaceText(suggestedName);
}
},
[entries, model],
);
const handleRetryProvider = useCallback(
(provider: AgentProvider) => {
void refresh([provider]);
},
[refresh],
);
const handleModeChange = useCallback(
(value: string, display: SelectFieldDisplay) => model.setMode(value, value ? display : null),
[model],
);
const handleThinkingSelectChange = useCallback(
(value: string, display: SelectFieldDisplay) =>
model.setThinking(value, value ? display : null),
[model],
);
const handleThinkingSegmentChange = useCallback(
(value: string) => {
const option = state.thinkingOptions.find((candidate) => candidate.value === value);
model.setThinking(value, option ? { label: option.label } : null);
},
[model, state.thinkingOptions],
);
const hasRuntimeDefaults =
state.disclosure.showModeField ||
state.disclosure.showThinkingField ||
state.disclosure.showControlsField;
const defaultsSummary = useMemo(() => {
const parts: string[] = [];
if (state.modeDisplay?.label) {
parts.push(state.modeDisplay.label);
}
if (state.thinkingDisplay?.label) {
parts.push(state.thinkingDisplay.label);
}
if (state.controls.length > 0) {
parts.push(
state.controls.length === 1
? t("settings.host.agentProfiles.featureCountOne", { count: state.controls.length })
: t("settings.host.agentProfiles.featureCount", { count: state.controls.length }),
);
}
if (!state.notes.trim() && hasRuntimeDefaults) {
parts.push(t("settings.host.agentProfiles.addRoutingNoteShort"));
}
return parts.join(" · ");
}, [
hasRuntimeDefaults,
state.controls.length,
state.modeDisplay?.label,
state.notes,
state.thinkingDisplay?.label,
t,
]);
const collapsibleLabel = hasRuntimeDefaults
? t("settings.host.agentProfiles.customizeSettings")
: t("settings.host.agentProfiles.addRoutingNoteShort");
const advancedFields = (
<AgentProfileAdvancedFields
model={model}
state={state}
controlSize={controlSize}
onModeChange={handleModeChange}
onThinkingSelectChange={handleThinkingSelectChange}
onThinkingSegmentChange={handleThinkingSegmentChange}
/>
);
return (
<View style={styles.body}>
<Field label={t("settings.host.agentProfiles.modelLabel")} testID="agent-profile-model-field">
<CombinedModelSelector
providers={modelSelectorProviders}
selectedProvider={state.provider}
selectedModel={state.modelId}
onSelect={handleModelSelect}
isLoading={isLoading || isFetching}
renderTrigger={renderModelTrigger}
triggerFill
serverId={serverId}
disabled={state.isSubmitting}
onRetryProvider={handleRetryProvider}
isRetryingProvider={isRefreshing}
/>
</Field>
<Field label={t("settings.host.agentProfiles.nameLabel")} testID="agent-profile-name-field">
<View style={styles.nameRow}>
{showInlineIcon ? (
<AgentProfileIconButton
label={t("settings.host.agentProfiles.iconLabel")}
icon={state.icon}
color={state.color}
provider={state.provider || undefined}
serverId={serverId}
onChange={handleAppearanceChange}
disabled={state.isSubmitting}
size={controlSize}
triggerTestID="agent-profile-icon-trigger"
/>
) : null}
<View style={styles.nameInputWrap}>
<FormTextInput
ref={nameInputRef}
initialValue={state.name}
onChangeText={model.setName}
placeholder={t("settings.host.agentProfiles.namePlaceholder")}
autoCapitalize="none"
autoCorrect={false}
editable={!state.isSubmitting}
size={controlSize}
accessibilityLabel={t("settings.host.agentProfiles.nameLabel")}
testID="agent-profile-name-input"
/>
</View>
</View>
</Field>
{collapsibleDefaults ? (
<SettingsCard>
<SettingsCollapsibleRow
label={collapsibleLabel}
summary={defaultsSummary || undefined}
testID="agent-profile-customize"
>
<View style={styles.collapsibleFields}>{advancedFields}</View>
</SettingsCollapsibleRow>
</SettingsCard>
) : (
advancedFields
)}
{state.submitError ? (
<Text style={styles.submitError} testID="agent-profile-submit-error">
{state.submitError}
</Text>
) : null}
</View>
);
}
const styles = StyleSheet.create((theme) => ({
body: {
gap: theme.spacing[4],
},
nameRow: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[2],
},
nameInputWrap: {
flex: 1,
minWidth: 0,
},
collapsibleFields: {
padding: theme.spacing[4],
gap: theme.spacing[4],
},
featureCardPending: {
opacity: theme.opacity[50],
},
notesInput: {
minHeight: theme.spacing[20],
textAlignVertical: "top",
},
submitError: {
color: theme.colors.palette.red[300],
fontSize: theme.fontSize.sm,
},
}));
@@ -1,57 +1,342 @@
import { useCallback, useMemo, type ReactElement } from "react";
import { useCallback, useMemo, useState, type ReactElement } from "react";
import { Text, View } from "react-native";
import { useTranslation } from "react-i18next";
import { ArrowDown, ArrowUp, FileText, Pencil, Trash2 } from "lucide-react-native";
import {
ArrowDown,
ArrowUp,
ArrowUpToLine,
ChevronRight,
Copy,
GripVertical,
MoreVertical,
Pencil,
Trash2,
} from "lucide-react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import type { ProviderSnapshotEntry } from "@getpaseo/protocol/agent-types";
import type { AgentProfile } from "@getpaseo/protocol/messages";
import { Button } from "@/components/ui/button";
import { DraggableListHandle } from "@/components/draggable-list";
import { useOpenKebabMenuVisibility } from "@/components/sidebar/use-open-kebab-menu-visibility";
import { bySizing, TOUCH_TARGET } from "@/components/ui/control-geometry";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
} from "@/components/ui/dropdown-menu";
import {
extraMutedIconColorMapping,
foregroundIconColorMapping,
mutedIconColorMapping,
} from "@/components/ui/icon-color";
import { ToolbarButton } from "@/components/ui/pane-content-toolbar";
import { PressHighlight } from "@/components/ui/press-highlight";
import { useIsCompactFormFactor } from "@/constants/layout";
import { usePointerCapabilities } from "@/hooks/pointer-capabilities";
import { settingsStyles } from "@/styles/settings";
import { ICON_SIZE, type Theme } from "@/styles/theme";
import { AgentProfileGlyph } from "../internal/agent-profile-glyph";
import { buildAgentProfileTags } from "../internal/profile-summary";
import { buildAgentProfileRosterSummary } from "../internal/profile-summary";
/** Shared column & rail geometry consumed by both RosterTableHeader and AgentProfileRow. */
export const ROSTER_COL_PROFILE_WIDTH = 184;
export const ROSTER_COL_RUNTIME_WIDTH = 248;
export const ROSTER_GRIP_WIDTH = bySizing({ touch: 28, pointer: 20 });
export const ROSTER_TRAILING_WIDTH = bySizing({ touch: TOUCH_TARGET + 14, pointer: 42 });
const ROW_MIN_HEIGHT = bySizing({ touch: TOUCH_TARGET + 16, pointer: 56 });
const GRIP_HANDLE_HEIGHT = bySizing({ touch: TOUCH_TARGET, pointer: 28 });
const ThemedGripVertical = withUnistyles(GripVertical);
const ThemedMoreVertical = withUnistyles(MoreVertical);
const ThemedChevronRight = withUnistyles(ChevronRight);
const ThemedPencil = withUnistyles(Pencil);
const ThemedCopy = withUnistyles(Copy);
const ThemedArrowUp = withUnistyles(ArrowUp);
const ThemedArrowDown = withUnistyles(ArrowDown);
const ThemedPencil = withUnistyles(Pencil);
const ThemedArrowUpToLine = withUnistyles(ArrowUpToLine);
const ThemedTrash2 = withUnistyles(Trash2);
const ThemedFileText = withUnistyles(FileText);
const mutedColorMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
const destructiveColorMapping = (theme: Theme) => ({ color: theme.colors.destructive });
const destructiveIconColorMapping = (theme: Theme) => ({ color: theme.colors.destructive });
const moveUpIcon = <ThemedArrowUp size={ICON_SIZE.sm} uniProps={mutedColorMapping} />;
const moveDownIcon = <ThemedArrowDown size={ICON_SIZE.sm} uniProps={mutedColorMapping} />;
const editIcon = <ThemedPencil size={ICON_SIZE.sm} uniProps={mutedColorMapping} />;
const removeIcon = <ThemedTrash2 size={ICON_SIZE.sm} uniProps={destructiveColorMapping} />;
const editMenuIcon = <ThemedPencil size={ICON_SIZE.sm} uniProps={mutedIconColorMapping} />;
const duplicateMenuIcon = <ThemedCopy size={ICON_SIZE.sm} uniProps={mutedIconColorMapping} />;
const moveUpMenuIcon = <ThemedArrowUp size={ICON_SIZE.sm} uniProps={mutedIconColorMapping} />;
const moveDownMenuIcon = <ThemedArrowDown size={ICON_SIZE.sm} uniProps={mutedIconColorMapping} />;
const moveTopMenuIcon = (
<ThemedArrowUpToLine size={ICON_SIZE.sm} uniProps={mutedIconColorMapping} />
);
const removeMenuIcon = <ThemedTrash2 size={ICON_SIZE.sm} uniProps={destructiveIconColorMapping} />;
const HIDDEN_FROM_ASSISTIVE_TECH = {
accessibilityElementsHidden: true,
importantForAccessibility: "no-hide-descendants",
"aria-hidden": true,
} as const;
export interface AgentProfileRowProps {
serverId: string;
profile: AgentProfile;
entries: readonly ProviderSnapshotEntry[] | undefined;
isFirst: boolean;
isLast: boolean;
selected?: boolean;
dragging?: boolean;
/** Stacked layout when narrow or on compact form factors. */
compactLayout?: boolean;
/** Hides the drag handle when showing filtered search results while preserving the rail. */
reorderable?: boolean;
onEdit: (id: string) => void;
onDuplicate: (id: string) => void;
onRemove: (id: string) => void;
onMoveUp: (id: string) => void;
onMoveDown: (id: string) => void;
onMoveToTop: (id: string) => void;
}
function AgentProfileRowMenu({
profileId,
profileName,
isFirst,
isLast,
reorderable,
menuProps,
onEdit,
onDuplicate,
onMoveUp,
onMoveDown,
onMoveToTop,
onRemove,
}: {
profileId: string;
profileName: string;
isFirst: boolean;
isLast: boolean;
reorderable: boolean;
menuProps: { open: boolean; onOpenChange: (open: boolean) => void };
onEdit: () => void;
onDuplicate: () => void;
onMoveUp: () => void;
onMoveDown: () => void;
onMoveToTop: () => void;
onRemove: () => void;
}): ReactElement {
const { t } = useTranslation();
const showReorderItems = reorderable && (!isFirst || !isLast);
return (
<DropdownMenu {...menuProps} compactMode="sheet">
<ToolbarButton
kind="menu"
label={t("settings.host.agentProfiles.profileActions", { name: profileName })}
testID={`agent-profile-menu-${profileId}`}
>
<ThemedMoreVertical size={ICON_SIZE.sm} uniProps={mutedIconColorMapping} />
</ToolbarButton>
<DropdownMenuContent side="bottom" align="end" width={180}>
<DropdownMenuItem
leading={editMenuIcon}
onSelect={onEdit}
testID={`agent-profile-edit-${profileId}`}
>
{t("settings.host.agentProfiles.editProfile")}
</DropdownMenuItem>
<DropdownMenuItem
leading={duplicateMenuIcon}
onSelect={onDuplicate}
testID={`agent-profile-duplicate-${profileId}`}
>
{t("settings.host.agentProfiles.duplicate")}
</DropdownMenuItem>
{showReorderItems ? (
<>
<DropdownMenuSeparator />
{!isFirst ? (
<DropdownMenuItem
leading={moveUpMenuIcon}
onSelect={onMoveUp}
testID={`agent-profile-move-up-${profileId}`}
>
{t("settings.host.agentProfiles.moveUp")}
</DropdownMenuItem>
) : null}
{!isLast ? (
<DropdownMenuItem
leading={moveDownMenuIcon}
onSelect={onMoveDown}
testID={`agent-profile-move-down-${profileId}`}
>
{t("settings.host.agentProfiles.moveDown")}
</DropdownMenuItem>
) : null}
{!isFirst ? (
<DropdownMenuItem
leading={moveTopMenuIcon}
onSelect={onMoveToTop}
testID={`agent-profile-move-top-${profileId}`}
>
{t("settings.host.agentProfiles.moveToTop")}
</DropdownMenuItem>
) : null}
</>
) : null}
<DropdownMenuSeparator />
<DropdownMenuItem
destructive
leading={removeMenuIcon}
onSelect={onRemove}
testID={`agent-profile-remove-${profileId}`}
>
{t("settings.host.agentProfiles.remove")}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
);
}
function AgentProfileRowContent({
serverId,
profile,
modelLabel,
providerLabel,
runtimeSubline,
fullSummary,
isStacked,
}: {
serverId: string;
profile: AgentProfile;
modelLabel: string | null;
providerLabel: string;
runtimeSubline: string;
fullSummary: string;
isStacked: boolean;
}): ReactElement {
const { t } = useTranslation();
const iconTile = (
<View style={styles.iconTile}>
<AgentProfileGlyph
icon={profile.icon}
color={profile.color}
provider={profile.provider}
serverId={serverId}
size={ICON_SIZE.sm}
/>
</View>
);
if (isStacked) {
return (
<View style={[styles.stackedMain, styles.passThrough]}>
{iconTile}
<View style={styles.stackedContent}>
<Text style={styles.nameText} numberOfLines={1}>
{profile.name}
</Text>
<View style={styles.stackedSpecLine}>
<AgentProfileGlyph
provider={profile.provider}
serverId={serverId}
size={ICON_SIZE.xs}
/>
<Text style={styles.stackedSpecText} numberOfLines={1}>
{fullSummary}
</Text>
</View>
{profile.notes ? (
<Text
style={styles.stackedNotesText}
numberOfLines={2}
testID={`agent-profile-notes-${profile.id}`}
>
{profile.notes}
</Text>
) : null}
</View>
</View>
);
}
return (
<View style={[styles.columns, styles.passThrough]}>
<View style={styles.colProfile}>
{iconTile}
<Text style={styles.nameText} numberOfLines={1}>
{profile.name}
</Text>
</View>
<View style={styles.colRuntime}>
<View style={styles.modelLine}>
<AgentProfileGlyph provider={profile.provider} serverId={serverId} size={ICON_SIZE.xs} />
<Text style={styles.modelText} numberOfLines={1}>
{modelLabel ?? providerLabel}
</Text>
</View>
<Text style={styles.runtimeSubtext} numberOfLines={1}>
{runtimeSubline}
</Text>
</View>
<View style={styles.colNotes}>
{profile.notes ? (
<Text
style={styles.notesText}
numberOfLines={2}
testID={`agent-profile-notes-${profile.id}`}
>
{profile.notes}
</Text>
) : (
<Text style={styles.notesEmptyText} numberOfLines={1}>
{t("settings.host.agentProfiles.noRoutingNote")}
</Text>
)}
</View>
</View>
);
}
/**
* Wide roster row (Profile | Model & runtime | When to use) that stacks on narrow panes.
*
* Follows docs/hover.md: hover lives on the outer plain View, tap lives on an
* underlying PressHighlight, and the kebab menu's open state is lifted via
* `useOpenKebabMenuVisibility` so losing hover never unmounts an open menu.
*/
export function AgentProfileRow({
serverId,
profile,
entries,
isFirst,
isLast,
selected = false,
dragging = false,
compactLayout = false,
reorderable = true,
onEdit,
onDuplicate,
onRemove,
onMoveUp,
onMoveDown,
onMoveToTop,
}: AgentProfileRowProps): ReactElement {
const { t } = useTranslation();
const isCompactFormFactor = useIsCompactFormFactor();
const { finePointer, touchScreen } = usePointerCapabilities();
const [isHovered, setIsHovered] = useState(false);
const alwaysShowAffordances = !finePointer || touchScreen || isCompactFormFactor;
const { showKebab, menuProps } = useOpenKebabMenuVisibility(
isHovered || dragging || alwaysShowAffordances,
);
const showRowAffordances = showKebab;
const handlePointerEnter = useCallback(() => setIsHovered(true), []);
const handlePointerLeave = useCallback(() => setIsHovered(false), []);
const handleEdit = useCallback(() => onEdit(profile.id), [onEdit, profile.id]);
const handleDuplicate = useCallback(() => onDuplicate(profile.id), [onDuplicate, profile.id]);
const handleRemove = useCallback(() => onRemove(profile.id), [onRemove, profile.id]);
const handleMoveUp = useCallback(() => onMoveUp(profile.id), [onMoveUp, profile.id]);
const handleMoveDown = useCallback(() => onMoveDown(profile.id), [onMoveDown, profile.id]);
const handleMoveToTop = useCallback(() => onMoveToTop(profile.id), [onMoveToTop, profile.id]);
const formatFeatureCount = useCallback(
(count: number) =>
@@ -60,77 +345,109 @@ export function AgentProfileRow({
: t("settings.host.agentProfiles.featureCount", { count }),
[t],
);
const tags = useMemo(
() => buildAgentProfileTags({ profile, entries, formatFeatureCount }),
const rosterSummary = useMemo(
() => buildAgentProfileRosterSummary({ profile, entries, formatFeatureCount }),
[entries, formatFeatureCount, profile],
);
const summary = useMemo(() => tags.map((tag) => tag.label).join(" · "), [tags]);
const fullSummary = useMemo(
() => rosterSummary.allTags.map((tag) => tag.label).join(" · "),
[rosterSummary.allTags],
);
const runtimeSubline = useMemo(
() => rosterSummary.runtimeDetails.join(" · "),
[rosterSummary.runtimeDetails],
);
const rowStyle = useMemo(
() => [settingsStyles.row, isFirst ? null : settingsStyles.rowBorder, styles.row],
[isFirst],
const isStacked = compactLayout || isCompactFormFactor;
const rowContainerStyle = useMemo(
() => [
styles.row,
!isFirst && settingsStyles.rowBorder,
selected && styles.rowSelected,
(isHovered || menuProps.open) && !selected && styles.rowHovered,
dragging && styles.rowDragging,
],
[dragging, isFirst, isHovered, menuProps.open, selected],
);
const gripVisibilityStyle = useMemo(
() => [styles.gripSlot, !showRowAffordances && styles.affordanceHidden],
[showRowAffordances],
);
const kebabVisibilityStyle = useMemo(
() => [styles.kebabSlot, !showRowAffordances && styles.affordanceHidden],
[showRowAffordances],
);
return (
<View style={rowStyle} testID={`agent-profile-row-${profile.id}`}>
<View style={styles.rowMain}>
<View style={styles.iconWrapper}>
<AgentProfileGlyph icon={profile.icon} color={profile.color} size={ICON_SIZE.md} />
<View
style={rowContainerStyle}
onPointerEnter={handlePointerEnter}
onPointerLeave={handlePointerLeave}
testID={`agent-profile-row-${profile.id}`}
>
<PressHighlight
accessibilityRole="button"
accessibilityLabel={`${profile.name}, ${fullSummary}`}
onPress={handleEdit}
style={styles.pressTarget}
highlightStyle={styles.rowPressed}
testID={`agent-profile-row-press-${profile.id}`}
/>
{selected ? <View style={styles.selectedIndicator} pointerEvents="none" /> : null}
{reorderable ? (
<View style={gripVisibilityStyle} pointerEvents={showRowAffordances ? "auto" : "none"}>
<DraggableListHandle
accessibilityLabel={t("settings.host.agentProfiles.reorderProfile", {
name: profile.name,
})}
style={styles.gripHandle}
testID={`agent-profile-drag-${profile.id}`}
>
<ThemedGripVertical size={ICON_SIZE.sm} uniProps={extraMutedIconColorMapping} />
</DraggableListHandle>
</View>
<View style={settingsStyles.rowContent}>
<View style={styles.titleLine}>
<Text style={settingsStyles.rowTitle} numberOfLines={1}>
{profile.name}
</Text>
<Text style={styles.summary} numberOfLines={1}>
{summary}
</Text>
</View>
{profile.notes ? (
<View style={styles.notes}>
<ThemedFileText size={ICON_SIZE.xs} uniProps={mutedColorMapping} />
<Text
style={styles.notesText}
numberOfLines={2}
testID={`agent-profile-notes-${profile.id}`}
>
{profile.notes}
</Text>
</View>
) : null}
) : (
<View style={isStacked ? styles.gripSpacerCompact : styles.gripSlot} />
)}
<AgentProfileRowContent
serverId={serverId}
profile={profile}
modelLabel={rosterSummary.modelLabel}
providerLabel={rosterSummary.providerLabel}
runtimeSubline={runtimeSubline}
fullSummary={fullSummary}
isStacked={isStacked}
/>
<View style={styles.trailing}>
<View style={kebabVisibilityStyle} pointerEvents={showRowAffordances ? "auto" : "none"}>
<AgentProfileRowMenu
profileId={profile.id}
profileName={profile.name}
isFirst={isFirst}
isLast={isLast}
reorderable={reorderable}
menuProps={menuProps}
onEdit={handleEdit}
onDuplicate={handleDuplicate}
onMoveUp={handleMoveUp}
onMoveDown={handleMoveDown}
onMoveToTop={handleMoveToTop}
onRemove={handleRemove}
/>
</View>
<View style={[styles.chevron, styles.passThrough]} {...HIDDEN_FROM_ASSISTIVE_TECH}>
<ThemedChevronRight
size={ICON_SIZE.sm}
uniProps={isHovered || selected ? foregroundIconColorMapping : mutedIconColorMapping}
/>
</View>
</View>
<View style={styles.rowActions}>
<Button
variant="ghost"
leftIcon={moveUpIcon}
onPress={handleMoveUp}
disabled={isFirst}
accessibilityLabel={t("settings.host.agentProfiles.moveUp")}
testID={`agent-profile-move-up-${profile.id}`}
/>
<Button
variant="ghost"
leftIcon={moveDownIcon}
onPress={handleMoveDown}
disabled={isLast}
accessibilityLabel={t("settings.host.agentProfiles.moveDown")}
testID={`agent-profile-move-down-${profile.id}`}
/>
<Button
variant="ghost"
leftIcon={editIcon}
onPress={handleEdit}
accessibilityLabel={t("settings.host.agentProfiles.editProfile")}
testID={`agent-profile-edit-${profile.id}`}
/>
<Button
variant="ghost"
leftIcon={removeIcon}
onPress={handleRemove}
accessibilityLabel={t("settings.host.agentProfiles.remove")}
testID={`agent-profile-remove-${profile.id}`}
/>
</View>
</View>
);
@@ -138,47 +455,166 @@ export function AgentProfileRow({
const styles = StyleSheet.create((theme) => ({
row: {
gap: theme.spacing[2],
minHeight: 56,
alignItems: "center",
paddingVertical: theme.spacing[3],
},
rowMain: {
flex: 1,
position: "relative",
flexDirection: "row",
alignItems: "flex-start",
alignItems: "center",
minHeight: ROW_MIN_HEIGHT,
paddingVertical: theme.spacing[3],
paddingLeft: theme.spacing[2],
paddingRight: theme.spacing[4],
gap: theme.spacing[2],
},
iconWrapper: {
width: theme.iconSize.md,
rowHovered: {
backgroundColor: theme.colors.surface2,
},
rowSelected: {
backgroundColor: theme.colors.surface3,
},
selectedIndicator: {
position: "absolute",
left: 0,
top: theme.spacing[2],
bottom: theme.spacing[2],
width: theme.borderWidth[2],
borderRadius: theme.borderRadius.full,
backgroundColor: theme.colors.accent,
},
rowPressed: {
backgroundColor: theme.colors.surface3,
},
rowDragging: {
backgroundColor: theme.colors.surface2,
},
pressTarget: {
...StyleSheet.absoluteFill,
},
passThrough: {
pointerEvents: "none",
},
gripSlot: {
width: ROSTER_GRIP_WIDTH,
alignItems: "center",
justifyContent: "center",
marginTop: 1,
flexShrink: 0,
},
titleLine: {
gripSpacerCompact: {
width: theme.spacing[2],
flexShrink: 0,
},
gripHandle: {
width: ROSTER_GRIP_WIDTH,
height: GRIP_HANDLE_HEIGHT,
alignItems: "center",
justifyContent: "center",
},
affordanceHidden: {
opacity: 0,
},
iconTile: {
width: theme.spacing[7],
height: theme.spacing[7],
borderRadius: theme.borderRadius.md,
backgroundColor: theme.colors.surface2,
alignItems: "center",
justifyContent: "center",
flexShrink: 0,
},
columns: {
flex: 1,
minWidth: 0,
flexDirection: "row",
alignItems: "baseline",
alignItems: "center",
gap: theme.spacing[4],
},
colProfile: {
width: ROSTER_COL_PROFILE_WIDTH,
flexShrink: 0,
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[2],
minWidth: 0,
},
summary: {
colRuntime: {
width: ROSTER_COL_RUNTIME_WIDTH,
flexShrink: 0,
gap: theme.spacing[0.5],
minWidth: 0,
},
colNotes: {
flex: 1,
minWidth: 0,
},
nameText: {
flexShrink: 1,
color: theme.colors.foreground,
fontSize: theme.fontSize.base,
fontWeight: theme.fontWeight.normal,
},
modelLine: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[1.5],
minWidth: 0,
},
modelText: {
flexShrink: 1,
color: theme.colors.foreground,
fontSize: theme.fontSize.sm,
},
runtimeSubtext: {
color: theme.colors.foregroundExtraMuted,
fontSize: theme.fontSize.sm,
},
notesText: {
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.sm,
},
notesEmptyText: {
color: theme.colors.foregroundExtraMuted,
fontSize: theme.fontSize.sm,
},
stackedMain: {
flex: 1,
minWidth: 0,
flexDirection: "row",
alignItems: "flex-start",
gap: theme.spacing[3],
},
stackedContent: {
flex: 1,
minWidth: 0,
gap: theme.spacing[0.5],
},
stackedSpecLine: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[1.5],
minWidth: 0,
},
stackedSpecText: {
flexShrink: 1,
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.sm,
},
notes: {
flexDirection: "row",
alignItems: "flex-start",
gap: theme.spacing[1],
marginTop: theme.spacing[1],
},
notesText: {
flex: 1,
color: theme.colors.foregroundMuted,
stackedNotesText: {
color: theme.colors.foregroundExtraMuted,
fontSize: theme.fontSize.sm,
marginTop: theme.spacing[0.5],
},
rowActions: {
trailing: {
width: ROSTER_TRAILING_WIDTH,
flexDirection: "row",
alignItems: "center",
justifyContent: "flex-end",
gap: theme.spacing[1],
flexShrink: 0,
},
kebabSlot: {
alignItems: "center",
justifyContent: "center",
},
// Optical: matches SettingsRowHeader so the chevron sits on the card's trailing rail.
chevron: {
marginRight: -theme.spacing[1],
},
}));
File diff suppressed because it is too large Load Diff
@@ -56,6 +56,7 @@ export function ChatFind({
agentId,
serverId,
epoch,
rewindSeq,
items,
viewportRef,
revealLoadedMessage,
@@ -95,8 +96,8 @@ export function ChatFind({
);
const state = useSyncExternalStore(model.subscribe, model.getSnapshot, model.getSnapshot);
useEffect(() => {
model.updateHistory(epoch, items);
}, [model, epoch, items]);
model.updateHistory(epoch, items, rewindSeq);
}, [model, epoch, items, rewindSeq]);
useEffect(() => () => model.close(), [model]);
useEffect(() => {
if (!active) model.close();
@@ -18,7 +18,7 @@ function message(seq: number, text = "target"): StreamItem {
kind: "assistant_message",
text,
timestamp: new Date(0),
timelineCursor: { epoch: "epoch", seq },
timelineCursor: { epoch: "epoch", seq, anchorSeq: seq },
};
}
@@ -39,7 +39,7 @@ it("loads an older location and searches a response merged across suppressed tas
source.map((item, index) => ({
event: { type: "timeline" as const, provider: "claude" as const, item },
timestamp: new Date(0),
timelineCursor: { epoch: "epoch", seq: index + 1 },
timelineCursor: { epoch: "epoch", seq: index + 1, anchorSeq: index + 1 },
})),
{ source: "canonical" },
);
@@ -55,7 +55,7 @@ it("loads an older location and searches a response merged across suppressed tas
},
async load(_epoch, seq) {
loaded.push(seq);
model.updateHistory("epoch", history);
model.updateHistory("epoch", history, null);
},
async reveal(_id, _query, occurrence) {
revealed.push(occurrence);
@@ -64,7 +64,7 @@ it("loads an older location and searches a response merged across suppressed tas
clear() {},
});
try {
model.updateHistory("epoch", []);
model.updateHistory("epoch", [], null);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
@@ -99,7 +99,7 @@ it("skips a source-only candidate and highlights a displayed match", async () =>
clear() {},
});
try {
model.updateHistory("epoch", [message(1), message(2)]);
model.updateHistory("epoch", [message(1), message(2)], null);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().selectedItemId).toBe("row-2");
@@ -129,7 +129,7 @@ it("ignores replies after closing and does not navigate", async () => {
},
clear() {},
});
model.updateHistory("epoch", [message(1)]);
model.updateHistory("epoch", [message(1)], null);
model.open();
model.setQuery("target");
await expect.poll(() => calls).toEqual(["search"]);
@@ -155,7 +155,7 @@ it("retains a failed search for retry and distinguishes failure from zero matche
};
const model = new ChatFindModel(operations);
try {
model.updateHistory("epoch", []);
model.updateHistory("epoch", [], null);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().phase).toBe("error");
@@ -185,7 +185,7 @@ it("reports a failed timeline load as a connection failure", async () => {
clear() {},
});
try {
model.updateHistory("epoch", []);
model.updateHistory("epoch", [], null);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().phase).toBe("error");
@@ -207,24 +207,160 @@ it("reports a search result that outlived its epoch as a changed history", async
clear() {},
});
try {
model.updateHistory("epoch", [message(1)]);
model.updateHistory("epoch", [message(1)], null);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
model.updateHistory("epoch-2", [message(1)]);
model.updateHistory("epoch-2", [message(1)], null);
expect(model.getSnapshot()).toMatchObject({ phase: "error", failure: "historyChanged" });
} finally {
model.close();
}
});
it("reports results that a rewind took messages from as a changed history", async () => {
const model = new ChatFindModel({
async search() {
return response([{ seq: 2, role: "assistant" }]);
},
async load() {},
async reveal() {
return { count: 1, occurrence: 0 };
},
clear() {},
});
try {
model.updateHistory("epoch", [message(1), message(2)], null);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
expect(model.getSnapshot()).toMatchObject({ selectedItemId: "row-2", count: 1 });
// Another client rewinds the turn holding the match; the epoch stays.
model.updateHistory("epoch", [message(1)], 3);
expect(model.getSnapshot()).toMatchObject({
phase: "error",
failure: "historyChanged",
selectedItemId: null,
});
} finally {
model.close();
}
});
it("stops a search still receiving pages when a rewind lands between them", async () => {
let pages = 0;
let releaseSecondPage!: () => void;
const secondPage = new Promise<void>((resolve) => {
releaseSecondPage = resolve;
});
const model = new ChatFindModel({
async search(_query, cursor) {
pages += 1;
if (cursor === undefined)
return { ...response([{ seq: 2, role: "assistant" }]), nextCursor: 2 };
await secondPage;
return response([{ seq: 1, role: "assistant" }]);
},
async load() {},
async reveal() {
return { count: 1, occurrence: 0 };
},
clear() {},
});
try {
model.updateHistory("epoch", [message(1), message(2)], null);
model.open();
model.setQuery("target");
await expect.poll(() => pages).toBe(2);
model.updateHistory("epoch", [message(1)], 3);
releaseSecondPage();
await expect.poll(() => model.getSnapshot().failure).toBe("historyChanged");
expect(model.getSnapshot()).toMatchObject({ phase: "error", selectedItemId: null });
} finally {
model.close();
}
});
it.each([
["Next", "next"],
["Previous", "previous"],
] as const)("reports a rewind after %s as a changed history", async (_label, step) => {
const model = new ChatFindModel({
async search() {
return response([
{ seq: 1, role: "assistant" },
{ seq: 2, role: "assistant" },
]);
},
async load() {},
async reveal() {
return { count: 1, occurrence: 0 };
},
clear() {},
});
try {
model.updateHistory("epoch", [message(1), message(2)], null);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
model[step]();
await expect.poll(() => model.getSnapshot().selectedItemId).toBe("row-2");
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
model.updateHistory("epoch", [message(1)], 3);
expect(model.getSnapshot()).toMatchObject({
phase: "error",
failure: "historyChanged",
selectedItemId: null,
});
} finally {
model.close();
}
});
it("stops a pending Next when a rewind lands before it reveals", async () => {
let reveals = 0;
let revealSecond!: () => void;
const secondReveal = new Promise<void>((resolve) => {
revealSecond = resolve;
});
const model = new ChatFindModel({
async search() {
return response([
{ seq: 1, role: "assistant" },
{ seq: 2, role: "assistant" },
]);
},
async load() {},
async reveal() {
reveals += 1;
if (reveals > 1) await secondReveal;
return { count: 1, occurrence: 0 };
},
clear() {},
});
try {
model.updateHistory("epoch", [message(1), message(2)], null);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
model.next();
await expect.poll(() => reveals).toBe(2);
model.updateHistory("epoch", [message(1)], 3);
revealSecond();
await expect.poll(() => model.getSnapshot().failure).toBe("historyChanged");
expect(model.getSnapshot()).toMatchObject({ phase: "error", selectedItemId: null });
} finally {
model.close();
}
});
it("can load a search location before the initial chat history has arrived", async () => {
const model = new ChatFindModel({
async search() {
return response([{ seq: 1, role: "assistant" }]);
},
async load() {
model.updateHistory("epoch", [message(1)]);
model.updateHistory("epoch", [message(1)], null);
},
async reveal() {
return { count: 1, occurrence: 0 };
@@ -232,7 +368,7 @@ it("can load a search location before the initial chat history has arrived", asy
clear() {},
});
try {
model.updateHistory(null, []);
model.updateHistory(null, [], null);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
@@ -260,7 +396,7 @@ it("reports the position across the whole chat and corrects it with rendered cou
clear() {},
});
try {
model.updateHistory("epoch", [message(1), message(2)]);
model.updateHistory("epoch", [message(1), message(2)], null);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
@@ -297,7 +433,7 @@ it("counts one match per message from a host that reports no counts", async () =
clear() {},
});
try {
model.updateHistory("epoch", [message(1), message(2)]);
model.updateHistory("epoch", [message(1), message(2)], null);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
@@ -76,6 +76,10 @@ export class ChatFindModel {
private items: StreamItem[] = [];
private epoch: string | null = null;
private resultEpoch: string | null = null;
/** The latest rewind applied to the history. A rewind keeps the epoch and retires messages. */
private rewindSeq: number | null = null;
/** The latest rewind when the current result set's search started; undefined until a search starts. */
private searchedRewindSeq: number | null | undefined = undefined;
private locations: Location[] = [];
private resolved = new Map<Location, Target>();
private current = -1;
@@ -113,6 +117,7 @@ export class ChatFindModel {
this.cancel();
this.locations = [];
this.resultEpoch = null;
this.searchedRewindSeq = undefined;
this.resolved.clear();
this.current = -1;
this.inMessage = { occurrence: 0, count: 0 };
@@ -144,6 +149,7 @@ export class ChatFindModel {
});
}
private async search(signal: AbortSignal) {
this.searchedRewindSeq = this.rewindSeq;
try {
let cursor: number | undefined;
do {
@@ -168,15 +174,14 @@ export class ChatFindModel {
this.fail(error, signal);
}
}
updateHistory(epoch: string | null, items: StreamItem[]) {
if (
this.resultEpoch !== null &&
epoch !== null &&
epoch !== this.resultEpoch &&
this.state.open
) {
/** `rewindSeq` is the sequence number of the latest rewind applied to this history. */
updateHistory(epoch: string | null, items: StreamItem[], rewindSeq: number | null) {
const replaced = this.resultEpoch !== null && epoch !== null && epoch !== this.resultEpoch;
const rewound = this.searchedRewindSeq !== undefined && rewindSeq !== this.searchedRewindSeq;
if ((replaced || rewound) && this.state.open) {
this.fail(new ChatFindFailureError("historyChanged"), this.abort.signal);
}
this.rewindSeq = rewindSeq;
this.epoch = epoch;
this.items = items;
this.historyListeners.forEach((listener) => listener());
@@ -9,6 +9,8 @@ export interface ChatFindProps {
agentId: string;
serverId: string;
epoch: string | null;
/** The sequence number of the latest rewind applied to this history, if any. */
rewindSeq: number | null;
items: StreamItem[];
viewportRef: RefObject<StreamViewportHandle | null>;
revealLoadedMessage(messageId: string): boolean;
@@ -139,7 +139,7 @@ describe("useChatOutline", () => {
kind: "user_message",
text: "live prompt",
timestamp: new Date(seq),
timelineCursor: { epoch: "epoch-1", seq },
timelineCursor: { epoch: "epoch-1", seq, anchorSeq: seq },
});
rerender({ tail: [loadedPrompt(2)] });
await waitFor(() => expect(runtime.listAgentTimelinePrompts).toHaveBeenCalledTimes(2));
@@ -198,7 +198,7 @@ describe("useChatOutline", () => {
kind: "assistant_message",
text: "chunk",
timestamp: new Date(),
timelineCursor: { epoch: "epoch-1", seq: 2 },
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 2 },
},
],
timelineEpoch: "epoch-1",
@@ -219,7 +219,7 @@ describe("useChatOutline", () => {
kind: "user_message",
text: "Replaced conversation",
timestamp: new Date(2),
timelineCursor: { epoch: "epoch-2", seq: 1 },
timelineCursor: { epoch: "epoch-2", seq: 1, anchorSeq: 1 },
},
],
timelineEpoch: "epoch-2",
@@ -275,7 +275,7 @@ describe("useChatOutline", () => {
kind: "user_message" as const,
text: "prompt",
timestamp: new Date(1),
timelineCursor: { epoch: "epoch-1", seq: 1 },
timelineCursor: { epoch: "epoch-1", seq: 1, anchorSeq: 1 },
},
];
const { result, rerender } = renderHook(
@@ -326,7 +326,7 @@ describe("useChatOutline", () => {
kind: "user_message" as const,
text: "prompt",
timestamp: new Date(1),
timelineCursor: { epoch: "epoch-1", seq: 1 },
timelineCursor: { epoch: "epoch-1", seq: 1, anchorSeq: 1 },
};
const { result, rerender } = renderHook(
({ tail, mountedHistoryMessageIds }) =>
@@ -381,7 +381,7 @@ describe("useChatOutline", () => {
kind: "user_message" as const,
text: "prompt",
timestamp: new Date(2),
timelineCursor: { epoch: "epoch-1", seq: 2 },
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 2 },
};
const revealLoadedMessage = vi.fn();
revealLoadedMessage.mockReturnValue(false);
@@ -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 } };
const canonical = { ...live, timelineCursor: { epoch: "epoch-1", seq: 42, anchorSeq: 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 },
timelineCursor: { epoch: "epoch-1", seq: 42, anchorSeq: 42 },
},
]);
});
@@ -517,7 +517,7 @@ describe("timeline presentation", () => {
messageId: "provider-message",
clientMessageId: "client-message",
turnId: "turn-1",
timelineCursor: { epoch: "epoch", seq: 12 },
timelineCursor: { epoch: "epoch", seq: 12, anchorSeq: 12 },
});
const presentMessage = () =>
present({
@@ -33,7 +33,7 @@ describe("resolveAssistantTurnForkBoundary", () => {
it("forks a failed assistant turn from its Paseo timeline cursor without a provider message id", () => {
const failedTurn = {
...assistantMessage("assistant-error", 2),
timelineCursor: { epoch: "timeline-1", seq: 42 },
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 42 },
};
expect(
@@ -50,7 +50,7 @@ describe("resolveAssistantTurnForkBoundary", () => {
it("includes the provider message id with a supported timeline cursor", () => {
const selected = {
...assistantMessage("assistant-1", 2, "msg-assistant-1"),
timelineCursor: { epoch: "timeline-1", seq: 42 },
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 42 },
};
expect(
@@ -68,7 +68,7 @@ describe("resolveAssistantTurnForkBoundary", () => {
it("falls back to the provider message id when timeline cursors are unsupported", () => {
const selected = {
...assistantMessage("assistant-1", 2, "msg-assistant-1"),
timelineCursor: { epoch: "timeline-1", seq: 42 },
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 42 },
};
expect(
@@ -116,7 +116,7 @@ describe("resolveAssistantTurnForkBoundary", () => {
it("resolves a fork boundary from the reply a plugin card replaced", () => {
const reply = {
...assistantMessage("assistant-1", 2, "msg-assistant-1"),
timelineCursor: { epoch: "timeline-1", seq: 42 },
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 42 },
};
const card: StreamItem = {
kind: "plugin",
@@ -154,7 +154,7 @@ describe("resolveAssistantTurnForkBoundary", () => {
const appended: StreamItem = {
kind: "plugin",
id: "plugin/card-1",
timelineCursor: { epoch: "timeline-1", seq: 42 },
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 42 },
timestamp: timestamp(2),
pluginId: "plugin",
pluginItemId: "card-1",
@@ -1,7 +1,13 @@
import { getAssistantReply, type StreamItem, type TimelinePosition } from "@/types/stream";
import { getAssistantReply, type StreamItem } from "@/types/stream";
/** The daemon's timeline cursor; the row's anchor stays in the client. */
interface TimelineBoundaryCursor {
epoch: string;
seq: number;
}
export type AssistantTurnForkBoundary =
| { boundaryCursor: TimelinePosition; boundaryMessageId?: string }
| { boundaryCursor: TimelineBoundaryCursor; boundaryMessageId?: string }
| { boundaryCursor?: undefined; boundaryMessageId: string };
export function resolveAssistantTurnForkBoundary(input: {
@@ -15,7 +21,7 @@ export function resolveAssistantTurnForkBoundary(input: {
}
if (input.supportsTimelineCursor && reply.timelineCursor) {
return {
boundaryCursor: reply.timelineCursor,
boundaryCursor: { epoch: reply.timelineCursor.epoch, seq: reply.timelineCursor.seq },
...(reply.messageId ? { boundaryMessageId: reply.messageId } : {}),
};
}
@@ -139,7 +139,7 @@ describe("collapseTurns", () => {
it("stands at its host's timeline position, taking a new row when that position lands", () => {
const live = collapse([user("u1"), shell("c1"), reply("r1")]);
expect(live.summaryRowsByHostId.get("u1")).not.toHaveProperty("timelineCursor");
const cursor = { epoch: "epoch-1", seq: 7 };
const cursor = { epoch: "epoch-1", seq: 7, anchorSeq: 7 };
const placed = [{ ...user("u1"), timelineCursor: cursor }, shell("c1"), reply("r1")];
const canonical = collapse(placed, { previousSummaryRowsByHostId: live.summaryRowsByHostId });
expect(canonical.summaryRowsByHostId.get("u1")).not.toBe(live.summaryRowsByHostId.get("u1"));
@@ -101,7 +101,7 @@ function summaryRow(
}
function staysVisibleWhenCollapsed(item: StreamItem): boolean {
return isTurnTrigger(item) || item.kind === "compaction";
return isTurnTrigger(item) || item.kind === "compaction" || item.kind === "provider_switch";
}
function findLastReplyIndex(tail: StreamItem[], start: number, end: number): number {
@@ -159,10 +159,10 @@ const projectedReply: StreamItem = {
id: "reply",
messageId: "provider-reply-1",
text: 'Done.\n\n```ui\nCard("Summary", [])\n```',
timelineCursor: { epoch: "e1", seq: 5 },
timelineCursor: { epoch: "e1", seq: 5, anchorSeq: 5 },
timestamp: FRIDAY_NIGHT,
},
timelineCursor: { epoch: "e1", seq: 5 },
timelineCursor: { epoch: "e1", seq: 5, anchorSeq: 5 },
timestamp: FRIDAY_NIGHT,
pluginId: "genui",
pluginItemId: "reply/1",
+35 -2
View File
@@ -37,6 +37,7 @@ import {
ToolCall,
TodoListCard,
CompactionMarker,
ProviderSwitchMarker,
MessageOuterSpacingProvider,
type InlinePathTarget,
} from "@/components/message";
@@ -57,6 +58,7 @@ import { useFileExplorerActions } from "@/hooks/use-file-explorer-actions";
import { useLoadOlderAgentHistory } from "@/hooks/use-load-older-agent-history";
import { resolveContentMaxWidth, useSettings } from "@/hooks/use-settings";
import type { ToastApi } from "@/components/toast-host";
import { isPromptInActiveSegment } from "@/components/rewind/use-rewind-capabilities";
import { returnToTimelineTail } from "./timeline-tail-navigation";
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
import { ToolCallDetailsContent } from "@/components/tool-call-details";
@@ -408,6 +410,10 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
const timelineEpoch = useSessionStore(
(state) => state.sessions[resolvedServerId]?.agentTimelineCursor.get(agentId)?.epoch ?? null,
);
const timelineRewindSeq = useSessionStore((state) => {
const rewind = state.sessions[resolvedServerId]?.agentTimelineLatestRewind.get(agentId);
return rewind && rewind.epoch === timelineEpoch ? rewind.seq : null;
});
const isTimelineDetached = useSessionStore(
(state) => state.sessions[resolvedServerId]?.agentTimelineHasNewer.get(agentId) === true,
);
@@ -711,8 +717,15 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
const setToolCallGroupExpanded = toolCallExpansion.setGroupExpanded;
const activeSegmentStartSeq = useSessionStore(
(state) =>
state.sessions[resolvedServerId]?.agentTimelineCursor.get(agentId)?.activeSegmentStartSeq ??
0,
);
const renderUserMessageItem = useCallback(
(layoutItem: StreamLayoutItem, item: Extract<StreamItem, { kind: "user_message" }>) => {
const canRewindPrompt = isPromptInActiveSegment(item.timelineCursor, activeSegmentStartSeq);
return (
<UserMessage
itemId={item.id}
@@ -724,7 +737,7 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
images={item.images}
attachments={item.attachments}
timestamp={item.timestamp.getTime()}
capabilities={context.capabilities}
capabilities={canRewindPrompt ? context.capabilities : undefined}
client={client}
isFirstInGroup={layoutItem.isFirstInUserGroup}
isLastInGroup={layoutItem.isLastInUserGroup}
@@ -735,7 +748,14 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
/>
);
},
[context.capabilities, agentId, client, pendingClientMessageIds, resolvedServerId],
[
activeSegmentStartSeq,
context.capabilities,
agentId,
client,
pendingClientMessageIds,
resolvedServerId,
],
);
const renderAssistantMessageItem = useCallback(
@@ -941,6 +961,18 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
/>
);
case "provider_switch":
return (
<ProviderSwitchMarker
serverId={resolvedServerId}
fromProvider={item.fromProvider}
toProvider={item.toProvider}
fromModel={item.fromModel}
toModel={item.toModel}
context={item.context}
/>
);
case "plugin":
return (
<PluginTimelineItemView agentId={agentId} item={item} serverId={resolvedServerId} />
@@ -1166,6 +1198,7 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
agentId={agentId}
serverId={resolvedServerId}
epoch={timelineEpoch}
rewindSeq={timelineRewindSeq}
items={findItems}
viewportRef={viewportRef}
revealLoadedMessage={revealLoadedMessage}
@@ -75,6 +75,7 @@ export function estimateStreamItemHeight({
case "notification":
return 88;
case "compaction":
case "provider_switch":
return 72;
default:
return 120;
@@ -7,6 +7,7 @@ import { FOOTER_HEIGHT } from "@/constants/layout";
import { useHostRuntimeClient, useHostRuntimeIsConnected } from "@/runtime/host-runtime";
import { KeyboardTranslateView } from "@/keyboard/shift";
import { Button } from "@/components/ui/button";
import { useToast } from "@/contexts/toast-context";
import type { Theme } from "@/styles/theme";
import { toErrorMessage } from "@/utils/error-messages";
@@ -19,6 +20,7 @@ export function ArchivedAgentCallout({ serverId, agentId }: ArchivedAgentCallout
const { t } = useTranslation();
const client = useHostRuntimeClient(serverId);
const isConnected = useHostRuntimeIsConnected(serverId);
const toast = useToast();
const [isUnarchiving, setIsUnarchiving] = useState(false);
const [unarchiveError, setUnarchiveError] = useState<string | null>(null);
@@ -27,12 +29,15 @@ export function ArchivedAgentCallout({ serverId, agentId }: ArchivedAgentCallout
setIsUnarchiving(true);
setUnarchiveError(null);
try {
await client.refreshAgent(agentId);
const refreshed = await client.refreshAgent(agentId);
if (refreshed.historyDiverged) {
toast.show(t("workspace.tabs.toasts.reloadedAgentHistoryDiverged"), { variant: "warning" });
}
} catch (error) {
setUnarchiveError(toErrorMessage(error));
setIsUnarchiving(false);
}
}, [client, isConnected, isUnarchiving, agentId]);
}, [client, isConnected, isUnarchiving, agentId, toast, t]);
return (
<KeyboardTranslateView style={styles.container}>
@@ -3,7 +3,7 @@ import { Pressable, Text, View, type PressableStateCallbackType } from "react-na
import { useTranslation } from "react-i18next";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import type { AgentProvider } from "@getpaseo/protocol/agent-types";
import type { AgentProfilePicker, AgentProfileSeed } from "@/agent-profiles";
import type { AgentProfile, AgentProfilePicker, AgentProfileSeed } from "@/agent-profiles";
import { ComboboxTrigger } from "@/components/ui/combobox-trigger";
import { LoadingSpinner } from "@/components/ui/loading-spinner";
import { Combobox, type ComboboxOption, type ComboboxProps } from "@/components/ui/combobox";
@@ -40,7 +40,7 @@ interface CombinedModelSelectorProps {
profiles?: AgentProfilePicker | null;
onApplyProfile?: (profileId: string) => void;
onEditProfiles?: () => void;
onCreateProfile?: (seed: AgentProfileSeed) => void;
onCreateProfile?: (seed: AgentProfileSeed) => Promise<AgentProfile | null> | void;
onEditProfile?: (profileId: string) => void;
renderTrigger?: (input: {
selectedModelLabel: string;
@@ -195,12 +195,17 @@ export function CombinedModelSelector({
onEditProfiles?.();
}, [handleOpenChange, onEditProfiles]);
// 1-tap `+` saves the profile, selects the model immediately, and closes the picker;
// useAgentProfileEditor surfaces a toast with Edit and Undo actions.
const handleCreateProfile = useCallback(
(seed: AgentProfileSeed) => {
if (seed.modelId) {
onSelect(seed.provider, seed.modelId);
}
handleOpenChange(false);
onCreateProfile?.(seed);
void onCreateProfile?.(seed);
},
[handleOpenChange, onCreateProfile],
[handleOpenChange, onCreateProfile, onSelect],
);
const handleEditProfile = useCallback(
+188
View File
@@ -19,9 +19,11 @@ import {
type RewindMode,
} from "@/components/rewind";
import { TaskListRow } from "@/components/task-list-row";
import { Button } from "@/components/ui/button";
import { LoadingSpinner } from "@/components/ui/loading-spinner";
import { useIsCompactFormFactor } from "@/constants/layout";
import { isNative, isWeb } from "@/constants/platform";
import { useProvidersSnapshot } from "@/hooks/use-providers-snapshot";
import { useRevealedText, type MarkdownPhase } from "@/hooks/use-revealed-text";
import { ICON_SIZE, type Theme } from "@/styles/theme";
import { inlineUnistylesStyle } from "@/styles/unistyles-inline-style";
@@ -40,13 +42,17 @@ import type { AgentMessage } from "@getpaseo/protocol/agent-message";
import type {
AgentCapabilityFlags,
AgentMetric,
AgentProvider,
ProviderSwitchContextSummary,
ToolCallDetail,
} from "@getpaseo/protocol/agent-types";
import type { AgentAttachment } from "@getpaseo/protocol/messages";
import MaskedView from "@react-native-masked-view/masked-view";
import {
ArrowRightLeft,
Check,
CheckSquare,
ChevronDown,
ChevronRight,
CircleDot,
Copy,
@@ -1487,6 +1493,188 @@ 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],
paddingHorizontal: theme.spacing[4],
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,
},
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 = t("message.providerSwitch.contextSummary", {
count: context.includedItems,
chars: context.charCount.toLocaleString(),
budget: context.budgetChars.toLocaleString(),
});
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;
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={handleToggle}
accessibilityLabel={title}
testID="provider-switch-marker-toggle"
>
<View style={providerSwitchStylesheet.triggerContent}>
<StyledSwitchIcon size={12} />
<Text
style={providerSwitchStylesheet.triggerText}
numberOfLines={1}
ellipsizeMode="tail"
>
{title}
</Text>
{expanded ? <StyledChevronDownIcon size={12} /> : <StyledChevronRightIcon size={12} />}
</View>
</Button>
<View style={providerSwitchStylesheet.line} />
</View>
{expanded ? (
<View style={providerSwitchStylesheet.detailsCard} testID="provider-switch-marker-details">
<Text style={providerSwitchStylesheet.detailRow}>
{`${formatProviderSwitchEndpoint(fromLabel, fromModelLabel)} → ${formatProviderSwitchEndpoint(toLabel, toModelLabel)}`}
</Text>
<Text style={providerSwitchStylesheet.detailRow}>{contextLine}</Text>
{reasonsLine ? (
<Text style={providerSwitchStylesheet.detailRow}>{reasonsLine}</Text>
) : null}
</View>
) : null}
</View>
);
});
interface TodoListCardProps {
items: TodoEntry[];
activity: TaskActivity;
+53 -11
View File
@@ -31,6 +31,7 @@ import {
import type { AgentProvider } from "@getpaseo/protocol/agent-types";
import {
AgentProfileGlyph,
type AgentProfile,
type AgentProfilePicker,
type AgentProfilePickerRow as AgentProfilePickerRowModel,
type AgentProfileSeed,
@@ -221,7 +222,7 @@ interface ModelBrowserProps {
/** Applying a profile resolves the pick and dismisses, exactly like a model row. */
onApplyProfile?: (profileId: string) => void;
onEditProfiles?: () => void;
onCreateProfile?: (seed: AgentProfileSeed) => void;
onCreateProfile?: (seed: AgentProfileSeed) => Promise<AgentProfile | null> | void;
onEditProfile?: (profileId: string) => void;
onRetryProvider?: (provider: AgentProvider) => void;
isRetryingProvider?: boolean;
@@ -695,7 +696,7 @@ function ModelRow({
showProviderLabel?: boolean;
onPress: () => void;
profiledRows: AgentProfilePickerRowModel[];
onCreateProfile?: (seed: AgentProfileSeed) => void;
onCreateProfile?: (seed: AgentProfileSeed) => Promise<AgentProfile | null> | void;
onEditProfile?: (profileId: string) => void;
onEditProfiles?: () => void;
}) {
@@ -758,7 +759,13 @@ function ModelRow({
label={t("modelSelector.editProfileLabel", { name: primary.name })}
testID={`model-edit-profile-${row.provider}-${row.modelId}`}
>
<AgentProfileGlyph icon={primary.icon} color={primary.color} size={ICON_SIZE.xs} />
<AgentProfileGlyph
icon={primary.icon}
color={primary.color}
provider={primary.provider}
serverId={serverId}
size={ICON_SIZE.xs}
/>
</ModelRowProfileAction>
);
}
@@ -772,7 +779,13 @@ function ModelRow({
label={t("modelSelector.editProfilesCount", { count: profiledRows.length })}
testID={`model-edit-profiles-${row.provider}-${row.modelId}`}
>
<AgentProfileGlyph icon={primary.icon} color={primary.color} size={ICON_SIZE.xs} />
<AgentProfileGlyph
icon={primary.icon}
color={primary.color}
provider={primary.provider}
serverId={serverId}
size={ICON_SIZE.xs}
/>
</ModelRowProfileAction>
);
}, [
@@ -787,6 +800,7 @@ function ModelRow({
profiledRows,
row.modelId,
row.provider,
serverId,
t,
]);
@@ -861,7 +875,7 @@ function SelectableModelRow({
showProviderLabel?: boolean;
onSelect: (provider: string, modelId: string) => void;
profiledRows: AgentProfilePickerRowModel[];
onCreateProfile?: (seed: AgentProfileSeed) => void;
onCreateProfile?: (seed: AgentProfileSeed) => Promise<AgentProfile | null> | void;
onEditProfile?: (profileId: string) => void;
onEditProfiles?: () => void;
}) {
@@ -885,15 +899,25 @@ function SelectableModelRow({
function AgentProfilePickerRowView({
row,
serverId,
onApply,
}: {
row: AgentProfilePickerRowModel;
serverId: string | null;
onApply: (profileId: string) => void;
}) {
const handlePress = useCallback(() => onApply(row.id), [onApply, row.id]);
const leadingSlot = useMemo(
() => <AgentProfileGlyph icon={row.icon} color={row.color} size={ICON_SIZE.sm} />,
[row.color, row.icon],
() => (
<AgentProfileGlyph
icon={row.icon}
color={row.color}
provider={row.provider}
serverId={serverId}
size={ICON_SIZE.sm}
/>
),
[row.color, row.icon, row.provider, serverId],
);
return (
<ModelBrowserRow
@@ -914,10 +938,12 @@ function AgentProfilePickerRowView({
*/
function AgentProfilesPickerSection({
rows,
serverId,
onApplyProfile,
onEditProfiles,
}: {
rows: AgentProfilePickerRowModel[];
serverId: string | null;
onApplyProfile?: (profileId: string) => void;
onEditProfiles?: () => void;
}) {
@@ -937,7 +963,12 @@ function AgentProfilesPickerSection({
) : null}
</View>
{rows.map((row) => (
<AgentProfilePickerRowView key={row.id} row={row} onApply={handleApply} />
<AgentProfilePickerRowView
key={row.id}
row={row}
serverId={serverId}
onApply={handleApply}
/>
))}
</View>
);
@@ -966,10 +997,12 @@ function CreateAgentProfileRow({ onPress }: { onPress: () => void }) {
function AgentProfilesPickerContent({
rows,
serverId,
onApplyProfile,
onEditProfiles,
}: {
rows: AgentProfilePickerRowModel[];
serverId: string | null;
onApplyProfile?: (profileId: string) => void;
onEditProfiles?: () => void;
}) {
@@ -979,6 +1012,7 @@ function AgentProfilesPickerContent({
return (
<AgentProfilesPickerSection
rows={rows}
serverId={serverId}
onApplyProfile={onApplyProfile}
onEditProfiles={onEditProfiles}
/>
@@ -991,11 +1025,13 @@ function AgentProfilesPickerContent({
*/
function ProfileSearchResultsHeader({
rows,
serverId,
hasModelRows,
onApplyProfile,
onEditProfiles,
}: {
rows: AgentProfilePickerRowModel[];
serverId: string | null;
hasModelRows: boolean;
onApplyProfile?: (profileId: string) => void;
onEditProfiles?: () => void;
@@ -1005,6 +1041,7 @@ function ProfileSearchResultsHeader({
<View>
<AgentProfilesPickerSection
rows={rows}
serverId={serverId}
onApplyProfile={onApplyProfile}
onEditProfiles={onEditProfiles}
/>
@@ -1207,7 +1244,7 @@ function ModelRowList({
header?: React.ReactElement;
scrolling: "sheet" | "independent";
profiledLookup: Map<string, AgentProfilePickerRowModel[]>;
onCreateProfile?: (seed: AgentProfileSeed) => void;
onCreateProfile?: (seed: AgentProfileSeed) => Promise<AgentProfile | null> | void;
onEditProfile?: (profileId: string) => void;
onEditProfiles?: () => void;
}) {
@@ -1336,7 +1373,7 @@ function ProviderModelBrowserContent({
onSelect: (provider: string, modelId: string) => void;
onApplyProfile?: (profileId: string) => void;
onEditProfiles?: () => void;
onCreateProfile?: (seed: AgentProfileSeed) => void;
onCreateProfile?: (seed: AgentProfileSeed) => Promise<AgentProfile | null> | void;
onEditProfile?: (profileId: string) => void;
profiledLookup: Map<string, AgentProfilePickerRowModel[]>;
showProfilesSection?: boolean;
@@ -1363,6 +1400,7 @@ function ProviderModelBrowserContent({
return (
<AgentProfilesPickerContent
rows={providerProfileRows}
serverId={serverId}
onApplyProfile={onApplyProfile}
onEditProfiles={onEditProfiles}
/>
@@ -1371,6 +1409,7 @@ function ProviderModelBrowserContent({
return matchedProfileRows.length > 0 ? (
<ProfileSearchResultsHeader
rows={matchedProfileRows}
serverId={serverId}
hasModelRows={visibleRows.length > 0}
onApplyProfile={onApplyProfile}
onEditProfiles={onEditProfiles}
@@ -1383,6 +1422,7 @@ function ProviderModelBrowserContent({
onEditProfiles,
profiles,
providerProfileRows,
serverId,
showProfilesSection,
visibleRows.length,
]);
@@ -1485,12 +1525,13 @@ function ModelBrowserContent({
allView.kind === "searchResults" && allView.profiles.length > 0 ? (
<ProfileSearchResultsHeader
rows={allView.profiles}
serverId={serverId}
hasModelRows={allView.rows.length > 0}
onApplyProfile={onApplyProfile}
onEditProfiles={onEditProfiles}
/>
) : undefined,
[allView, onApplyProfile, onEditProfiles],
[allView, onApplyProfile, onEditProfiles, serverId],
);
if (view.kind === "provider") {
@@ -1552,6 +1593,7 @@ function ModelBrowserContent({
{showProfilesSection && profiles ? (
<AgentProfilesPickerContent
rows={profiles.rows}
serverId={serverId}
onApplyProfile={onApplyProfile}
onEditProfiles={onEditProfiles}
/>
@@ -10,7 +10,11 @@ import { useToast } from "@/contexts/toast-context";
import type { AgentScreenReadySyncState } from "@/hooks/use-agent-screen-state-machine";
import { selectAgentTimelineState, useSessionStore } from "@/stores/session-store";
import { useRewindAgentMutation } from "./use-rewind-agent-mutation";
import { isRewindableMessage, useRewindMenuItems } from "./use-rewind-capabilities";
import {
isPromptInActiveSegment,
isRewindableMessage,
useRewindMenuItems,
} from "./use-rewind-capabilities";
export function RewindCommandCenterRegistration({
serverId,
@@ -42,10 +46,16 @@ export function RewindCommandCenterRegistration({
if (timeline.status !== "synced" || timeline.newer === "available") {
return undefined;
}
return (
const candidate =
session.agentStreamHead.get(agentId)?.findLast((item) => item.kind === "user_message") ??
timeline.items.findLast((item) => item.kind === "user_message")
);
timeline.items.findLast((item) => item.kind === "user_message");
if (
!candidate ||
!isPromptInActiveSegment(candidate.timelineCursor, timeline.range?.activeSegmentStartSeq)
) {
return undefined;
}
return candidate;
});
const { rewindAgent, isPending } = useRewindAgentMutation({
serverId,
@@ -9,6 +9,7 @@ import { useRewindComposerRestore } from "./composer-restore";
import { useSessionStore } from "@/stores/session-store";
import { shouldRestoreComposerForRewindMode } from "./rewind-mode";
import { getHostRuntimeStore } from "@/runtime/host-runtime";
import { hostSupportsFeature } from "@/runtime/host-features";
interface UseRewindAgentMutationInput {
serverId?: string;
@@ -42,7 +43,16 @@ export function useRewindAgentMutation(input: UseRewindAgentMutationInput): {
throw new Error(t("common.errors.daemonClientUnavailable"));
}
await input.client.rewindAgent(input.agentId, input.messageId, mode);
if (mode !== "files") {
// COMPAT(timelineRewindOperations): added in v0.14.1, remove after 2027-05-10. A daemon with
// the feature delivers the rewind on the live timeline; an older one replaced the timeline
// and this client has to read it again.
const appliesLive =
input.serverId !== undefined &&
hostSupportsFeature(
useSessionStore.getState().sessions[input.serverId]?.serverInfo,
"timelineRewindOperations",
);
if (mode !== "files" && !appliesLive) {
const cursor = input.serverId
? useSessionStore
.getState()
@@ -26,6 +26,20 @@ export function isRewindableMessage(messageId: string | undefined, text: string)
return Boolean(messageId) && text.trim().length > 0;
}
/**
* Whether a user prompt belongs to the active provider segment (after the latest provider switch).
* Prompts from earlier provider segments cannot be rewound.
*/
export function isPromptInActiveSegment(
timelineCursor: { anchorSeq?: number; seq?: number } | undefined,
activeSegmentStartSeq: number | undefined,
): boolean {
if (!activeSegmentStartSeq || activeSegmentStartSeq <= 0) return true;
const anchor = timelineCursor?.anchorSeq ?? timelineCursor?.seq;
if (anchor === undefined) return true;
return anchor > activeSegmentStartSeq;
}
export function resolveRewindMenuItems(
capabilities:
| Pick<
+44 -3
View File
@@ -1,7 +1,13 @@
import type { SelectedFile } from "@/attachments/selected-file";
import { FILE_UPLOAD_MAX_BYTES } from "@/attachments/upload-limit";
import type { ForgeSearchItem } from "@getpaseo/protocol/messages";
import type { ActiveTurnBehavior } from "@getpaseo/protocol/messages";
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 {
AttachmentMetadata,
ComposerAttachment,
@@ -56,6 +62,20 @@ export interface ComposerSendClient {
attachments: ReturnType<typeof splitComposerAttachmentsForSubmit>["attachments"];
},
) => Promise<unknown>;
switchAgentProvider?: (
agentId: string,
options: {
provider: AgentProvider;
model?: string | null;
modeId?: string | null;
thinkingOptionId?: string | null;
providerOptions?: ProviderOptions;
text: string;
messageId: string;
images?: Array<{ data: string; mimeType: string }>;
attachments?: ReturnType<typeof splitComposerAttachmentsForSubmit>["attachments"];
},
) => Promise<{ agent?: AgentSnapshotPayload }>;
uploadFile: (input: { fileName: string; mimeType: string; bytes: Uint8Array }) => Promise<{
requestId: string;
file: {
@@ -197,6 +217,8 @@ export interface DispatchComposerAgentMessageInput {
submission: MessageSubmissionWriter;
activeTurnBehavior?: ActiveTurnBehavior;
activeTurnId?: string;
stagedProviderSwitch?: StagedProviderSwitch | null;
onProviderSwitchCommitted?: (agent: AgentSnapshotPayload | undefined) => void;
}
export async function dispatchComposerAgentMessage(
@@ -212,13 +234,29 @@ export async function dispatchComposerAgentMessage(
timestamp: new Date(),
images: wirePayload.images,
attachments: wirePayload.attachments,
...(input.activeTurnBehavior === "steer" && input.activeTurnId
...(input.activeTurnBehavior === "steer" && input.activeTurnId && !input.stagedProviderSwitch
? { turnId: input.activeTurnId }
: {}),
});
input.submission.begin(input.agentId, userMessage);
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.onProviderSwitchCommitted?.(result.agent);
input.submission.accept(input.agentId, clientMessageId);
return;
}
await input.client.sendAgentMessage(input.agentId, input.text, {
messageId: clientMessageId,
...(input.activeTurnBehavior ? { activeTurnBehavior: input.activeTurnBehavior } : {}),
@@ -228,6 +266,9 @@ export async function dispatchComposerAgentMessage(
input.submission.accept(input.agentId, clientMessageId);
} catch (error) {
input.submission.reject(input.agentId, clientMessageId);
if (error instanceof AgentProviderSwitchError && error.agent) {
input.onProviderSwitchCommitted?.(error.agent);
}
throw error;
}
}
@@ -16,12 +16,20 @@ 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,
type StagedProviderSwitch,
useStagedProviderSwitch,
useStagedProviderSwitchStore,
} from "@/composer/provider-switch";
import { resolveProviderDefinition } from "@/utils/provider-definitions";
import { mergeProviderPreferences, useFormPreferences } from "@/hooks/use-form-preferences";
import {
@@ -96,11 +104,13 @@ import {
import {
useAgentProfileEditor,
useAgentProfilePicker,
type AgentProfile,
type AgentProfileApplyTarget,
type AgentProfileEditorControls,
type AgentProfilePicker,
type AgentProfileSeed,
type DraftAgentProfileControls,
type MaterializedAgentProfile,
} from "@/agent-profiles";
import { buildSettingsHostSectionRoute } from "@/utils/host-routes";
@@ -127,7 +137,7 @@ interface ControlledAgentControlsProps {
agentProfiles?: AgentProfilePicker | null;
onApplyAgentProfile?: (profileId: string) => void;
onEditAgentProfiles?: () => void;
onCreateAgentProfile?: (seed: AgentProfileSeed) => void;
onCreateAgentProfile?: (seed: AgentProfileSeed) => Promise<AgentProfile | null> | void;
onEditAgentProfile?: (profileId: string) => void;
optionControls?: ComposerOptionControls;
onDropdownClose?: () => void;
@@ -269,7 +279,7 @@ function useEditAgentProfilesNavigation(
): (() => void) | undefined {
const handleEdit = useCallback(() => {
if (!serverId) return;
router.push(buildSettingsHostSectionRoute(serverId, "agents"));
router.push(buildSettingsHostSectionRoute(serverId, "agent-profiles"));
}, [serverId]);
return serverId && isSupported ? handleEdit : undefined;
}
@@ -278,14 +288,14 @@ function resolveAgentProfileEditorActions(
isSupported: boolean,
editor: AgentProfileEditorControls,
): {
create?: (seed: AgentProfileSeed) => void;
create?: (seed: AgentProfileSeed) => Promise<AgentProfile | null>;
edit?: (profileId: string) => void;
} {
if (!isSupported) {
return {};
}
return {
create: editor.openCreateFromModel,
create: editor.quickCreateFromModel,
edit: editor.openEdit,
};
}
@@ -732,7 +742,7 @@ interface AgentControlsContentProps {
featureItems: ComposerControlItem[];
onApplyAgentProfile?: (profileId: string) => void;
onEditAgentProfiles?: () => void;
onCreateAgentProfile?: (seed: AgentProfileSeed) => void;
onCreateAgentProfile?: (seed: AgentProfileSeed) => Promise<AgentProfile | null> | void;
onEditAgentProfile?: (profileId: string) => void;
onDropdownClose?: () => void;
onModelSelectorOpen?: () => void;
@@ -1005,6 +1015,148 @@ function useAgentOptionControls(
);
}
function resolveActiveStagedSwitch(
supportsProviderSwitching: boolean,
rawStagedSwitch: StagedProviderSwitch | null,
liveProvider: string | undefined,
): StagedProviderSwitch | null {
if (!supportsProviderSwitching || !rawStagedSwitch || !liveProvider) {
return null;
}
return rawStagedSwitch.provider !== liveProvider ? rawStagedSwitch : null;
}
function resolveDraftTargetModelId(
modelId: string,
preferredModel: string | undefined,
nextModels: AgentModelDefinition[] | null,
): string | null {
if (modelId) return modelId;
if (preferredModel) return preferredModel;
const defaultModel = nextModels?.find((m) => m.isDefault);
return defaultModel?.id ?? nextModels?.[0]?.id ?? null;
}
function resolveDraftThinkingOptionId(
targetModelId: string | null,
targetModel: AgentModelDefinition | undefined,
thinkingByModel: Record<string, string> | undefined,
): string | null {
const preferred = targetModelId ? thinkingByModel?.[targetModelId] : undefined;
if (preferred) return preferred;
return targetModel?.defaultThinkingOptionId ?? targetModel?.thinkingOptions?.[0]?.id ?? null;
}
function resolveDraftModeId(
preferredMode: string | undefined,
nextEntry: ReturnType<typeof resolveProviderSnapshotEntry>,
): string | null {
if (preferredMode) return preferredMode;
return nextEntry?.defaultModeId ?? nextEntry?.modes?.[0]?.id ?? null;
}
function buildStagedProviderSwitchDraft(input: {
nextProvider: string;
modelId: string;
snapshotEntries: ReturnType<typeof useProvidersSnapshot>["entries"];
providerPreferences: ReturnType<typeof useFormPreferences>["preferences"]["providerPreferences"];
}): StagedProviderSwitch {
const { nextProvider, modelId, snapshotEntries, providerPreferences } = input;
const nextEntry = resolveProviderSnapshotEntry(snapshotEntries, nextProvider);
const nextModels = filterSelectableModels(nextEntry?.models ?? null);
const preferred = providerPreferences?.[nextProvider];
const targetModelId = resolveDraftTargetModelId(modelId, preferred?.model, nextModels);
const targetModel = nextModels?.find((m) => m.id === targetModelId);
return {
provider: nextProvider,
model: targetModelId,
thinkingOptionId: resolveDraftThinkingOptionId(
targetModelId,
targetModel,
preferred?.thinkingByModel,
),
modeId: resolveDraftModeId(preferred?.mode, nextEntry),
providerOptions: preferred?.options ? { ...preferred.options } : {},
};
}
function resolveAgentModelSelectionWithStagedSwitch(input: {
models: AgentModelDefinition[] | null;
agent: AgentControlsSlice;
activeStagedSwitch: StagedProviderSwitch | null;
}) {
const { models, agent, activeStagedSwitch } = input;
return resolveAgentModelSelection({
models,
runtimeModelId: activeStagedSwitch ? null : agent?.runtimeModelId,
configuredModelId: activeStagedSwitch ? activeStagedSwitch.model : agent?.model,
runtimeThinkingOptionId: activeStagedSwitch ? null : agent?.runtimeThinkingOptionId,
explicitThinkingOptionId: activeStagedSwitch
? activeStagedSwitch.thinkingOptionId
: agent?.thinkingOptionId,
});
}
function buildStagedDraftOptionsParams(input: {
serverId: string;
agentCwd: string | null | undefined;
activeStagedSwitch: StagedProviderSwitch | null;
getProvider: () => AgentProvider | null;
modelId: string | null;
thinkingOptionId: string | null;
}) {
const { serverId, agentCwd, activeStagedSwitch, getProvider, modelId, thinkingOptionId } = input;
return {
serverId: activeStagedSwitch ? serverId : null,
provider: activeStagedSwitch ? activeStagedSwitch.provider : null,
getProvider,
cwd: agentCwd,
modeId: activeStagedSwitch?.modeId ?? null,
modelId,
thinkingOptionId,
initialOptions: activeStagedSwitch?.providerOptions,
};
}
function resolveAgentOptionControlsForComposer(input: {
activeStagedSwitch: StagedProviderSwitch | null;
stagedControls: ComposerOptionControls | null | undefined;
liveOptionControls: ComposerOptionControls;
onSetOption: (key: string, value: unknown) => void;
}): ComposerOptionControls {
const { activeStagedSwitch, stagedControls, liveOptionControls, onSetOption } = input;
if (!activeStagedSwitch) {
return liveOptionControls;
}
if (stagedControls) {
return { ...stagedControls, onSetOption };
}
return { controls: [], options: activeStagedSwitch.providerOptions, onSetOption };
}
function resolveControlledAgentControlsProps(input: {
effectiveProvider: string | undefined;
liveProvider: string;
selectedModelId: string | null;
selectedThinkingId: string | null;
thinkingOptions: AgentControlOption[];
supportsProviderSwitching: boolean;
handleSelectProviderAndModel: (provider: string, modelId: string) => void;
snapshotIsLoading: boolean;
selectedProviderIsLoading: boolean;
}) {
return {
provider: input.effectiveProvider ?? input.liveProvider,
selectedModelId: input.selectedModelId ?? undefined,
selectedThinkingOptionId: input.selectedThinkingId ?? undefined,
thinkingOptions: input.thinkingOptions.length > 0 ? input.thinkingOptions : undefined,
onSelectProviderAndModel: input.supportsProviderSwitching
? input.handleSelectProviderAndModel
: undefined,
isModelLoading: input.snapshotIsLoading || input.selectedProviderIsLoading,
};
}
export const AgentControls = memo(function AgentControls({
showToolbar,
agentId,
@@ -1012,15 +1164,22 @@ export const AgentControls = memo(function AgentControls({
onDropdownClose,
isCompactLayout,
}: AgentControlsProps) {
const { updatePreferences } = useFormPreferences();
const { preferences, updatePreferences } = useFormPreferences();
const agent = useSessionStore(
useShallow((state) => selectAgentControlsSlice(state, serverId, agentId)),
);
const client = useSessionStore((state) => state.sessions[serverId]?.client ?? null);
const supportsProviderSwitching = useSessionStore(
(state) => state.sessions[serverId]?.serverInfo?.features?.providerSwitching === true,
);
const rawStagedSwitch = useStagedProviderSwitch(serverId, agentId);
const activeStagedSwitch = resolveActiveStagedSwitch(
supportsProviderSwitching,
rawStagedSwitch,
agent?.provider,
);
const toast = useToast();
const modeControl = useLiveAgentModeControl(serverId, agentId);
const commandCenterModes = toCommandCenterModes(modeControl);
const modeProviderDefinitions = getModeProviderDefinitions(modeControl);
const liveModeControl = useLiveAgentModeControl(serverId, agentId);
const {
entries: snapshotEntries,
@@ -1030,24 +1189,34 @@ export const AgentControls = memo(function AgentControls({
refetchIfStale: refetchSnapshotIfStale,
} = useProvidersSnapshot(serverId, { cwd: agent?.cwd });
const effectiveProvider = activeStagedSwitch?.provider ?? agent?.provider;
const effectiveProviderRef = useRef<AgentProvider | null>(effectiveProvider ?? null);
effectiveProviderRef.current = effectiveProvider ?? null;
const snapshotSelectedEntry = useMemo(
() => resolveProviderSnapshotEntry(snapshotEntries, agent?.provider),
[snapshotEntries, agent?.provider],
() => resolveProviderSnapshotEntry(snapshotEntries, effectiveProvider),
[snapshotEntries, effectiveProvider],
);
const models = filterSelectableModels(snapshotSelectedEntry?.models ?? null);
const selectedProviderIsLoading = snapshotSelectedEntry?.status === "loading";
const agentProviderDefinitions = useMemo(
() => buildAgentProviderDefinitions(agent?.provider, snapshotEntries),
[agent?.provider, snapshotEntries],
() => buildAgentProviderDefinitions(effectiveProvider, snapshotEntries),
[effectiveProvider, snapshotEntries],
);
const agentProviderModels = useMemo(
() => buildAgentProviderModels(agent?.provider, models),
[agent?.provider, models],
() => buildAgentProviderModels(effectiveProvider, models),
[effectiveProvider, models],
);
const agentModelSelectorProviders = useMemo(() => {
if (supportsProviderSwitching && snapshotEntries && snapshotEntries.length > 0) {
const selectable = buildSelectableProviderSelectorProviders(snapshotEntries, {
selectedProvider: effectiveProvider ?? null,
});
if (selectable.length > 0) return selectable;
}
if (snapshotSelectedEntry) {
return [buildSelectorProvider(snapshotSelectedEntry)];
}
@@ -1055,14 +1224,19 @@ export const AgentControls = memo(function AgentControls({
providerDefinitions: agentProviderDefinitions,
modelsByProvider: agentProviderModels,
});
}, [agentProviderDefinitions, agentProviderModels, snapshotSelectedEntry]);
}, [
agentProviderDefinitions,
agentProviderModels,
effectiveProvider,
snapshotEntries,
snapshotSelectedEntry,
supportsProviderSwitching,
]);
const modelSelection = resolveAgentModelSelection({
const modelSelection = resolveAgentModelSelectionWithStagedSwitch({
models,
runtimeModelId: agent?.runtimeModelId,
configuredModelId: agent?.model,
runtimeThinkingOptionId: agent?.runtimeThinkingOptionId,
explicitThinkingOptionId: agent?.thinkingOptionId,
agent,
activeStagedSwitch,
});
const modelOptions = useMemo<AgentControlOption[]>(() => {
@@ -1079,8 +1253,87 @@ 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(
() => (activeStagedSwitch ? effectiveProviderRef.current : null),
[activeStagedSwitch],
);
const stagedDraftOptions = useDraftProviderOptions(
buildStagedDraftOptionsParams({
serverId,
agentCwd: agent?.cwd,
activeStagedSwitch,
getProvider: getStagedProvider,
modelId: modelSelection.activeModelId,
thinkingOptionId: modelSelection.selectedThinkingId,
}),
);
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;
}
if (!client || !agentProvider) {
return;
}
@@ -1098,23 +1351,121 @@ export const AgentControls = memo(function AgentControls({
toast.error(toErrorMessage(error));
}
},
[agentId, agentProvider, client, toast, updatePreferences],
);
const handleSelectCommandCenterModel = useCallback(
(_provider: AgentProvider, modelId: string) => handleSelectModel(modelId),
[handleSelectModel],
[
activeStagedSwitch,
agentId,
agentProvider,
client,
models,
preferences.providerPreferences,
serverId,
toast,
updatePreferences,
],
);
// A running agent is one provider's process, so only that provider's profiles
// can apply to it.
const profileProviders = useMemo(() => (agentProvider ? [agentProvider] : []), [agentProvider]);
const handleSelectProviderAndModel = useCallback(
(nextProvider: string, modelId: string) => {
if (!agentProvider) return;
if (nextProvider === agentProvider) {
clearStagedProviderSwitch(serverId, agentId);
const liveModelId = agent?.runtimeModelId ?? agent?.model ?? null;
if (modelId && modelId !== liveModelId) {
void handleSelectModel(modelId);
}
return;
}
if (!supportsProviderSwitching) return;
useStagedProviderSwitchStore.getState().stage(
serverId,
agentId,
buildStagedProviderSwitchDraft({
nextProvider,
modelId,
snapshotEntries,
providerPreferences: preferences.providerPreferences,
}),
);
},
[
agent?.model,
agent?.runtimeModelId,
agentId,
agentProvider,
handleSelectModel,
preferences.providerPreferences,
serverId,
snapshotEntries,
supportsProviderSwitching,
],
);
const handleSelectCommandCenterModel = useCallback(
(provider: AgentProvider, modelId: string) => {
if (supportsProviderSwitching) {
handleSelectProviderAndModel(provider, modelId);
return;
}
void handleSelectModel(modelId);
},
[handleSelectModel, handleSelectProviderAndModel, supportsProviderSwitching],
);
const handleStageAgentProfileSwitch = useCallback(
(resolved: MaterializedAgentProfile) => {
if (!supportsProviderSwitching) return;
const nextEntry = resolveProviderSnapshotEntry(snapshotEntries, resolved.provider);
const modeIds = resolveSnapshotModeIds(nextEntry);
const validModeId =
resolved.modeId && (!modeIds || modeIds.includes(resolved.modeId))
? resolved.modeId
: (nextEntry?.defaultModeId ?? nextEntry?.modes?.[0]?.id ?? null);
useStagedProviderSwitchStore.getState().stage(serverId, agentId, {
provider: resolved.provider,
model: resolved.modelId ?? null,
modeId: validModeId,
thinkingOptionId: resolved.thinkingOptionId ?? null,
providerOptions: resolved.options ? { ...resolved.options } : {},
});
stagedDraftOptions.applyProfile({
provider: resolved.provider,
options: resolved.options ?? {},
});
},
[agentId, serverId, snapshotEntries, stagedDraftOptions, supportsProviderSwitching],
);
const handleClearStagedSwitchOnProfile = useCallback(() => {
clearStagedProviderSwitch(serverId, agentId);
}, [agentId, serverId]);
const profileProviders = useMemo(() => {
if (supportsProviderSwitching) {
return agentModelSelectorProviders.map((entry) => entry.id);
}
return agentProvider ? [agentProvider] : [];
}, [agentModelSelectorProviders, agentProvider, supportsProviderSwitching]);
const profileModeIds = useMemo(
() => resolveSnapshotModeIds(snapshotSelectedEntry),
[snapshotSelectedEntry],
);
const profileTarget = useMemo<AgentProfileApplyTarget>(
() => ({ kind: "agent", agentId, availableModeIds: profileModeIds }),
[agentId, profileModeIds],
() => ({
kind: "agent",
agentId,
availableModeIds: profileModeIds,
currentProvider: agentProvider,
onApplySameProvider: handleClearStagedSwitchOnProfile,
onStageProviderSwitch: supportsProviderSwitching ? handleStageAgentProfileSwitch : undefined,
}),
[
agentId,
agentProvider,
handleClearStagedSwitchOnProfile,
handleStageAgentProfileSwitch,
profileModeIds,
supportsProviderSwitching,
],
);
const agentProfiles = useAgentProfilePicker({
serverId,
@@ -1127,6 +1478,13 @@ export const AgentControls = memo(function AgentControls({
const handleSelectThinkingOption = useCallback(
(thinkingOptionId: string) => {
if (activeStagedSwitch) {
useStagedProviderSwitchStore.getState().patch(serverId, agentId, (current) => ({
...current,
thinkingOptionId,
}));
return;
}
if (!client || !agentProvider) {
return;
}
@@ -1154,11 +1512,28 @@ export const AgentControls = memo(function AgentControls({
toast.error(toErrorMessage(error));
});
},
[activeModelId, agentId, agentProvider, client, toast, updatePreferences],
[
activeModelId,
activeStagedSwitch,
agentId,
agentProvider,
client,
serverId,
toast,
updatePreferences,
],
);
const handleSetOption = useCallback(
(key: string, value: unknown) => {
if (activeStagedSwitch) {
stagedDraftOptions.setOption(key, value);
useStagedProviderSwitchStore.getState().patch(serverId, agentId, (current) => ({
...current,
providerOptions: { ...current.providerOptions, [key]: value },
}));
return;
}
if (!client || !agentProvider) {
return;
}
@@ -1180,10 +1555,29 @@ export const AgentControls = memo(function AgentControls({
toast.error(toErrorMessage(error));
});
},
[agentId, agentProvider, client, toast, updatePreferences],
[
activeStagedSwitch,
agentId,
agentProvider,
client,
serverId,
stagedDraftOptions,
toast,
updatePreferences,
],
);
const agentOptionControls = useAgentOptionControls(agent, handleSetOption);
const liveOptionControls = useAgentOptionControls(agent, handleSetOption);
const agentOptionControls = useMemo<ComposerOptionControls>(
() =>
resolveAgentOptionControlsForComposer({
activeStagedSwitch,
stagedControls: stagedDraftOptions.optionControls,
liveOptionControls,
onSetOption: handleSetOption,
}),
[activeStagedSwitch, handleSetOption, liveOptionControls, stagedDraftOptions.optionControls],
);
// The agent's composer exists apart from this component; while this is mounted, prompt
// commands go through the input the user is typing in.
@@ -1207,12 +1601,12 @@ export const AgentControls = memo(function AgentControls({
() => ({
serverId,
ownerKey: agentId,
provider: agentProvider,
provider: effectiveProvider,
providerDefinitions: modeProviderDefinitions,
profiles: agentProfiles,
models: {
providers: agentModelSelectorProviders,
selectedProvider: agentProvider,
selectedProvider: effectiveProvider,
selectedModelId: activeModelId,
select: handleSelectCommandCenterModel,
},
@@ -1231,7 +1625,7 @@ export const AgentControls = memo(function AgentControls({
client,
agentId,
agentModelSelectorProviders,
agentProvider,
effectiveProvider,
commandCenterModes,
handleSelectCommandCenterModel,
handleSelectThinkingOption,
@@ -1251,8 +1645,8 @@ export const AgentControls = memo(function AgentControls({
);
const handleModelSelectorOpen = useCallback(() => {
refetchSnapshotIfStale(agentProvider);
}, [agentProvider, refetchSnapshotIfStale]);
refetchSnapshotIfStale(supportsProviderSwitching ? undefined : effectiveProvider);
}, [effectiveProvider, refetchSnapshotIfStale, supportsProviderSwitching]);
const handleRetryModelProvider = useCallback(
(provider: AgentProvider) => {
@@ -1265,6 +1659,18 @@ export const AgentControls = memo(function AgentControls({
return null;
}
const resolvedControlProps = resolveControlledAgentControlsProps({
effectiveProvider,
liveProvider: agent.provider,
selectedModelId: modelSelection.activeModelId,
selectedThinkingId: modelSelection.selectedThinkingId,
thinkingOptions,
supportsProviderSwitching,
handleSelectProviderAndModel,
snapshotIsLoading,
selectedProviderIsLoading,
});
return (
<ComposerModelProvider value={composer}>
{commandCenterRegistration}
@@ -1272,21 +1678,17 @@ export const AgentControls = memo(function AgentControls({
<>
{profileEditor.element}
<ControlledAgentControls
provider={agent.provider}
{...resolvedControlProps}
modelSelectorProviders={agentModelSelectorProviders}
modelOptions={modelOptions}
selectedModelId={modelSelection.activeModelId ?? undefined}
onSelectModel={handleSelectModel}
agentProfiles={agentProfiles}
onApplyAgentProfile={agentProfiles?.applyProfile}
onEditAgentProfiles={handleEditAgentProfiles}
onCreateAgentProfile={profileActions.create}
onEditAgentProfile={profileActions.edit}
thinkingOptions={thinkingOptions.length > 0 ? thinkingOptions : undefined}
selectedThinkingOptionId={modelSelection.selectedThinkingId ?? undefined}
onSelectThinkingOption={handleSelectThinkingOption}
optionControls={agentOptionControls}
isModelLoading={snapshotIsLoading || selectedProviderIsLoading}
onModelSelectorOpen={handleModelSelectorOpen}
onRetryModelProvider={handleRetryModelProvider}
isRetryingModelProvider={snapshotIsRefreshing}
@@ -10,7 +10,7 @@ import {
} from "react-native";
import { StyleSheet } from "react-native-unistyles";
import type { AgentProvider } from "@getpaseo/protocol/agent-types";
import type { AgentProfilePicker, AgentProfileSeed } from "@/agent-profiles";
import type { AgentProfile, AgentProfilePicker, AgentProfileSeed } from "@/agent-profiles";
import { AdaptiveModalSheet } from "@/components/adaptive-modal-sheet";
import type { ContextBridge } from "@/components/ui/isolated-bottom-sheet-modal";
import { ComboboxTrigger } from "@/components/ui/combobox-trigger";
@@ -56,7 +56,7 @@ interface CompactModelSheetProps {
profiles?: AgentProfilePicker | null;
onApplyProfile?: (profileId: string) => void;
onEditProfiles?: () => void;
onCreateProfile?: (seed: AgentProfileSeed) => void;
onCreateProfile?: (seed: AgentProfileSeed) => Promise<AgentProfile | null> | void;
onEditProfile?: (profileId: string) => void;
onOpen?: () => void;
onClose?: () => void;
@@ -74,8 +74,9 @@ interface CompactModelSheetProps {
}
function resolveModelSheetProfileActions(
onCreateProfile: ((seed: AgentProfileSeed) => void) | undefined,
onCreateProfile: ((seed: AgentProfileSeed) => Promise<AgentProfile | null> | void) | undefined,
onEditProfile: ((profileId: string) => void) | undefined,
onSelect: (provider: string, modelId: string) => void,
close: () => void,
): {
create?: (seed: AgentProfileSeed) => void;
@@ -84,8 +85,11 @@ function resolveModelSheetProfileActions(
return {
create: onCreateProfile
? (seed: AgentProfileSeed) => {
if (seed.modelId) {
onSelect(seed.provider, seed.modelId);
}
close();
onCreateProfile(seed);
void onCreateProfile(seed);
}
: undefined,
edit: onEditProfile
@@ -281,7 +285,12 @@ export function CompactModelSheet({
onEditProfiles?.();
}, [close, onEditProfiles]);
const profileActions = resolveModelSheetProfileActions(onCreateProfile, onEditProfile, close);
const profileActions = resolveModelSheetProfileActions(
onCreateProfile,
onEditProfile,
onSelect,
close,
);
const toggle = useCallback(() => {
if (isOpen) {
+129 -7
View File
@@ -9,6 +9,15 @@ 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 {
clearStagedProviderSwitch,
getStagedProviderSwitch,
useStagedProviderSwitch,
} from "@/composer/provider-switch";
import { useProvidersSnapshot } from "@/hooks/use-providers-snapshot";
import { normalizeAgentSnapshot } from "@/utils/agent-snapshots";
import { resolveProviderLabel } from "@/utils/provider-definitions";
import {
View,
Pressable,
@@ -48,6 +57,7 @@ import { usePanelStore, type MobilePanelView } from "@/stores/panel-store";
import { usePointerCapabilities } from "@/hooks/pointer-capabilities";
import { useShallow } from "zustand/shallow";
import {
ArrowRightLeft,
ArrowUp,
Square,
Pencil,
@@ -298,16 +308,29 @@ function buildRealtimeVoiceButtonStyle(pressed: boolean, voiceButtonDisabled: bo
const EMPTY_METRICS: AgentMetric[] = [];
const EMPTY_AGENT_STATE = {
provider: null,
status: null,
contextWindowMaxTokens: null,
contextWindowUsedTokens: null,
totalCostUsd: null,
sessionMetrics: EMPTY_METRICS,
model: null,
};
function buildAgentStateSelector(serverId: string, agentId: string) {
return (state: ReturnType<typeof useSessionStore.getState>) => {
const agent = state.sessions[serverId]?.agents?.get(agentId) ?? null;
if (!agent) return EMPTY_AGENT_STATE;
const usage = agent.lastUsage;
return {
status: agent?.status ?? null,
contextWindowMaxTokens: agent?.lastUsage?.contextWindowMaxTokens ?? null,
contextWindowUsedTokens: agent?.lastUsage?.contextWindowUsedTokens ?? null,
totalCostUsd: agent?.lastUsage?.totalCostUsd ?? null,
sessionMetrics: agent?.sessionMetrics ?? EMPTY_METRICS,
model: agent?.model ?? null,
provider: agent.provider ?? null,
status: agent.status ?? null,
contextWindowMaxTokens: usage?.contextWindowMaxTokens ?? null,
contextWindowUsedTokens: usage?.contextWindowUsedTokens ?? null,
totalCostUsd: usage?.totalCostUsd ?? null,
sessionMetrics: agent.sessionMetrics ?? EMPTY_METRICS,
model: agent.model ?? null,
};
};
}
@@ -1351,6 +1374,36 @@ 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 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
) {
clearStagedProviderSwitch(serverId, agentId);
}
}, [agentId, agentState.provider, rawStagedSwitch, serverId]);
const handleCancelStagedSwitch = useCallback(() => {
clearStagedProviderSwitch(serverId, agentId);
setSendError(null);
}, [agentId, serverId]);
const queuedMessagesRaw = useSessionStore((state) =>
state.sessions[serverId]?.queuedMessages?.get(agentId),
@@ -1709,6 +1762,12 @@ 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;
await dispatchComposerAgentMessage({
client,
agentId: targetAgentId,
@@ -1719,6 +1778,16 @@ function ComposerContentImpl({
}),
encodeImages,
submission: createMessageSubmissionWriter(serverId),
stagedProviderSwitch,
onProviderSwitchCommitted: (agent) => {
clearStagedProviderSwitch(serverId, targetAgentId);
if (agent) {
getHostRuntimeStore().tryAcceptAgentSnapshot(
serverId,
normalizeAgentSnapshot(agent, serverId),
);
}
},
activeTurnBehavior,
activeTurnId:
activeTurnBehavior === "steer"
@@ -1803,7 +1872,7 @@ function ComposerContentImpl({
attachments: outgoingAttachments,
hasExternalContent,
allowEmptySubmit,
forceSend,
forceSend: stagedSwitch && isAgentRunning ? false : forceSend,
submitBehavior,
isAgentRunning,
// Parent-managed submits are still valid submit paths even when the
@@ -1845,6 +1914,7 @@ function ComposerContentImpl({
queueMessage,
setSelectedAttachments,
replaceUserInput,
stagedSwitch,
submitBehavior,
submitMessage,
t,
@@ -2566,6 +2636,31 @@ function ComposerContentImpl({
? t("composer.github.searching")
: t("composer.github.noResults");
const stagedSwitchBannerNode = useMemo(() => {
if (!stagedSwitch || !stagedProviderLabel) 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, stagedProviderLabel, stagedSwitch, t]);
return (
<>
<ComposerKeyboardRegistration
@@ -2591,6 +2686,7 @@ function ComposerContentImpl({
>
<View style={inputAreaContentStyle}>
{isFullscreen ? null : queueList}
{isFullscreen ? null : stagedSwitchBannerNode}
{!isFullscreen && sendErrorNode}
<ComposerAutocompleteBinding
@@ -2846,9 +2942,35 @@ const styles = StyleSheet.create((theme: Theme) => ({
queueSendButton: {
backgroundColor: theme.colors.accent,
},
stagedSwitchBanner: {
flexDirection: "row",
alignItems: "center",
justifyContent: "space-between",
paddingLeft: theme.spacing[3],
paddingRight: theme.spacing[1.5],
paddingVertical: theme.spacing[1],
backgroundColor: theme.colors.surface1,
borderRadius: theme.borderRadius.md,
borderWidth: theme.borderWidth[1],
borderColor: theme.colors.border,
gap: theme.spacing[2],
},
stagedSwitchLabelRow: {
flex: 1,
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[1.5],
minWidth: 0,
},
stagedSwitchText: {
flex: 1,
fontSize: theme.fontSize.sm,
color: theme.colors.foregroundMuted,
},
})) as unknown as Record<string, object>;
const ThemedAttachmentSpinner = withUnistyles(LoadingSpinner);
const ThemedArrowRightLeft = withUnistyles(ArrowRightLeft);
const ThemedPencil = withUnistyles(Pencil);
const ThemedArrowUp = withUnistyles(ArrowUp);
const ThemedGitPullRequest = withUnistyles(GitPullRequest);
@@ -0,0 +1,7 @@
export {
clearStagedProviderSwitch,
getStagedProviderSwitch,
useStagedProviderSwitch,
useStagedProviderSwitchStore,
type StagedProviderSwitch,
} from "./store";
@@ -0,0 +1,462 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { AgentProviderSwitchError } from "@getpaseo/client/internal/daemon-client";
import type { AgentSnapshotPayload } from "@getpaseo/protocol/messages";
import { dispatchComposerAgentMessage } from "@/composer/actions";
import { isPromptInActiveSegment } from "@/components/rewind/use-rewind-capabilities";
import { collapseTurns } from "@/agent-stream/turn-collapse/model";
import {
processAgentStreamEvent,
processTimelineResponse,
} from "@/timeline/session-stream-reducers";
import { ReplicaCache } from "@/runtime/replica-cache";
import type { ReplicaRow, ReplicaRowStore } from "@/runtime/replica-cache/row-store";
import { HostRuntimeStore } from "@/runtime/host-runtime";
import { useSessionStore } from "@/stores/session-store";
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
import type { ProviderSwitchItem, StreamItem, UserMessageItem } from "@/types/stream";
import { getStagedProviderSwitch, useStagedProviderSwitchStore } from "./index";
function createInMemoryRowStore(): ReplicaRowStore {
const rows = new Map<string, ReplicaRow>();
const keyOf = (r: { serverId: string; kind: string; id: string }) =>
`${r.serverId}:${r.kind}:${r.id}`;
return {
async open() {},
async read(serverId, kinds, ids) {
const kindSet = new Set(kinds);
const idSet = ids ? new Set(ids) : null;
return [...rows.values()].filter(
(r) => r.serverId === serverId && kindSet.has(r.kind) && (!idSet || idSet.has(r.id)),
);
},
async readAll() {
const byServer = new Map<string, ReplicaRow[]>();
for (const row of rows.values()) {
const list = byServer.get(row.serverId) ?? [];
list.push(row);
byServer.set(row.serverId, list);
}
return [...byServer.entries()].map(([serverId, list]) => ({ serverId, rows: list }));
},
async apply(changes) {
for (const del of changes.deletes) rows.delete(keyOf(del));
for (const up of changes.upserts) rows.set(keyOf(up), up);
},
async deleteHost(serverId) {
for (const [k, v] of rows) if (v.serverId === serverId) rows.delete(k);
},
async renameHost() {},
async clear() {
rows.clear();
},
};
}
const TS = "2026-11-25T10:00:00.000Z";
function agentSnapshot(provider: string): AgentSnapshotPayload {
return {
id: "agent-1",
provider,
cwd: "/repo",
model: null,
thinkingOptionId: null,
createdAt: TS,
updatedAt: TS,
lastUserMessageAt: null,
status: "idle",
capabilities: {
supportsStreaming: true,
supportsSessionPersistence: true,
supportsDynamicModes: false,
supportsMcpServers: false,
supportsReasoningStream: false,
supportsToolInvocations: true,
supportsRewindConversation: true,
supportsRewindFiles: false,
supportsRewindBoth: false,
},
currentModeId: null,
availableModes: [],
pendingPermissions: [],
persistence: null,
title: null,
labels: {},
};
}
describe("app provider switching integration", () => {
beforeEach(() => {
useStagedProviderSwitchStore.setState({ stagedByKey: new Map() });
});
it("dispatches switchAgentProvider when staged and handles pre-commit vs post-commit failures", async () => {
const committed: Array<AgentSnapshotPayload | undefined> = [];
const sendAgentMessage = vi.fn().mockResolvedValue(undefined);
const switchAgentProvider = vi.fn().mockResolvedValue({ agent: agentSnapshot("codex") });
const submission = {
begin: vi.fn(),
accept: vi.fn(),
reject: vi.fn(),
};
const staged = {
provider: "codex",
model: "gpt-5.4",
thinkingOptionId: "high",
modeId: "auto",
providerOptions: {},
};
// Success path
await dispatchComposerAgentMessage({
client: {
sendAgentMessage,
switchAgentProvider,
uploadFile: vi.fn(),
},
agentId: "agent-1",
text: "Continue with Codex",
attachments: [],
encodeImages: async () => [],
submission,
stagedProviderSwitch: staged,
onProviderSwitchCommitted: (agent) => committed.push(agent),
});
expect(sendAgentMessage).not.toHaveBeenCalled();
expect(switchAgentProvider).toHaveBeenCalledTimes(1);
expect(committed).toEqual([expect.objectContaining({ provider: "codex" })]);
expect(submission.accept).toHaveBeenCalledTimes(1);
// Pre-commit failure: onProviderSwitchCommitted MUST NOT run
committed.length = 0;
switchAgentProvider.mockRejectedValueOnce(new Error("Codex CLI unavailable"));
await expect(
dispatchComposerAgentMessage({
client: { sendAgentMessage, switchAgentProvider, uploadFile: vi.fn() },
agentId: "agent-1",
text: "Retry",
attachments: [],
encodeImages: async () => [],
submission,
stagedProviderSwitch: staged,
onProviderSwitchCommitted: (agent) => committed.push(agent),
}),
).rejects.toThrow("Codex CLI unavailable");
expect(committed).toEqual([]);
// Post-commit start failure (AgentProviderSwitchError with .agent): MUST commit live agent snapshot
switchAgentProvider.mockRejectedValueOnce(
new AgentProviderSwitchError("Rate limited", agentSnapshot("codex")),
);
await expect(
dispatchComposerAgentMessage({
client: { sendAgentMessage, switchAgentProvider, uploadFile: vi.fn() },
agentId: "agent-1",
text: "Retry 2",
attachments: [],
encodeImages: async () => [],
submission,
stagedProviderSwitch: staged,
onProviderSwitchCommitted: (agent) => committed.push(agent),
}),
).rejects.toThrow("Rate limited");
expect(committed).toEqual([expect.objectContaining({ provider: "codex" })]);
});
it("advances activeSegmentStartSeq immediately on live provider_switch events and scopes rewind eligibility", () => {
const preSwitchPrompt: UserMessageItem = {
kind: "user_message",
id: "u1",
messageId: "u1",
text: "Claude prompt",
timestamp: new Date(TS),
timelineCursor: { epoch: "ep-1", seq: 1, anchorSeq: 1 },
};
const liveResult = processAgentStreamEvent({
event: {
type: "timeline",
provider: "codex",
item: {
type: "provider_switch",
fromProvider: "claude",
toProvider: "codex",
fromModel: "sonnet",
toModel: "gpt-5.4",
fromSessionId: "s1",
toSessionId: null,
context: { includedItems: 2, truncated: false, charCount: 100, budgetChars: 100_000 },
},
},
seq: 3,
epoch: "ep-1",
currentTail: [preSwitchPrompt],
currentHead: [],
currentCursor: { epoch: "ep-1", startSeq: 1, endSeq: 2 },
hasAuthoritativeBaseline: true,
timestamp: new Date(TS),
});
expect(liveResult.cursor?.activeSegmentStartSeq).toBe(3);
expect(liveResult.tail.some((item) => item.kind === "provider_switch")).toBe(true);
// Pre-switch prompt (anchor 1 <= 3) is NOT rewindable; post-switch prompt (anchor 4 > 3) IS!
expect(
isPromptInActiveSegment(
preSwitchPrompt.timelineCursor,
liveResult.cursor?.activeSegmentStartSeq,
),
).toBe(false);
expect(
isPromptInActiveSegment({ seq: 4, anchorSeq: 4 }, liveResult.cursor?.activeSegmentStartSeq),
).toBe(true);
// Timeline page response also propagates activeSegmentStartSeq
const pageResult = processTimelineResponse({
payload: {
agentId: "agent-1",
direction: "tail",
projection: "projected",
reset: true,
epoch: "ep-1",
window: { minSeq: 1, maxSeq: 4, nextSeq: 5 },
startCursor: { seq: 1 },
endCursor: { seq: 4 },
hasNewer: false,
hasOlder: false,
activeSegmentStartSeq: 3,
entries: [
{
seqStart: 1,
seqEnd: 1,
provider: "claude",
timestamp: TS,
item: { type: "user_message", text: "Claude prompt", messageId: "u1" },
},
{
seqStart: 3,
seqEnd: 3,
provider: "codex",
timestamp: TS,
item: {
type: "provider_switch",
fromProvider: "claude",
toProvider: "codex",
context: { includedItems: 1, truncated: false, charCount: 50, budgetChars: 100_000 },
},
},
],
error: null,
},
currentTail: [],
currentHead: [],
currentCursor: undefined,
isInitializing: true,
hasActiveInitDeferred: false,
initRequestDirection: "tail",
sendingClientMessageIds: [],
});
expect(pageResult.cursor?.activeSegmentStartSeq).toBe(3);
});
it("persists provider_switch items and activeSegmentStartSeq in ReplicaCache and keeps markers visible when turns collapse", async () => {
const rowStore = createInMemoryRowStore();
const cache = new ReplicaCache(rowStore);
cache.setHosts(["srv-1"]);
const switchItem: ProviderSwitchItem = {
kind: "provider_switch",
id: "provider_switch:ep-1:3",
timestamp: new Date(TS),
timelineCursor: { epoch: "ep-1", seq: 3, anchorSeq: 3 },
fromProvider: "claude",
toProvider: "codex",
fromModel: "sonnet",
toModel: "gpt-5.4",
fromSessionId: "s1",
toSessionId: null,
context: {
includedItems: 2,
truncated: true,
charCount: 150,
budgetChars: 100_000,
omittedReasons: ["tail_window_limit"],
},
};
const items: StreamItem[] = [
{
kind: "user_message",
id: "u1",
messageId: "u1",
text: "Hello",
timestamp: new Date(TS),
timelineCursor: { epoch: "ep-1", seq: 1, anchorSeq: 1 },
},
switchItem,
];
cache.commitTimeline("srv-1", "agent-1", {
agentId: "agent-1",
items,
range: { epoch: "ep-1", startSeq: 1, endSeq: 3, activeSegmentStartSeq: 3 },
hasOlder: false,
});
await cache.flush();
const restored = await cache.readTimeline("srv-1", "agent-1");
expect(restored?.range?.activeSegmentStartSeq).toBe(3);
expect(restored?.items.find((i) => i.kind === "provider_switch")).toMatchObject({
kind: "provider_switch",
fromProvider: "claude",
toProvider: "codex",
context: { truncated: true, omittedReasons: ["tail_window_limit"] },
});
// Turn collapse keeps provider_switch visible
const collapsed = collapseTurns({
tail: [
items[0]!,
{
kind: "tool_call",
id: "tc1",
timestamp: new Date(TS),
payload: {
source: "agent",
data: {
provider: "claude",
callId: "c1",
name: "read",
status: "completed",
error: null,
detail: { type: "read", filePath: "a.ts" },
},
},
},
switchItem,
{
kind: "assistant_message",
id: "a1",
text: "Done",
timestamp: new Date(TS),
},
],
isLatestTurnOpen: false,
expandedHostIds: new Set(),
getGroupedCalls: () => undefined,
previousSummaryRowsByHostId: new Map(),
});
expect(collapsed.tail.some((item) => item.kind === "provider_switch")).toBe(true);
});
it("blocks M2 drain while M1's staged provider switch is in-flight, then sends M2 normally to P2", async () => {
const serverId = "srv_multi_queue_switch";
let resolveSwitch!: (value: { agent: AgentSnapshotPayload }) => void;
const switchPromise = new Promise<{ agent: AgentSnapshotPayload }>((resolve) => {
resolveSwitch = resolve;
});
const switchedCalls: string[] = [];
const sentCalls: string[] = [];
const fakeClient = {
switchAgentProvider: vi.fn(async (_agentId: string, opts: { text: string }) => {
switchedCalls.push(opts.text);
return await switchPromise;
}),
sendAgentMessage: vi.fn(async (_agentId: string, text: string) => {
sentCalls.push(text);
}),
uploadFile: vi.fn(),
} as unknown as DaemonClient;
const runtime = new HostRuntimeStore({
deps: {
createClient: () => fakeClient,
connectToDaemon: async () => ({ client: fakeClient, serverId, hostname: null }),
getClientId: async () => "cid_multi_queue_switch",
},
});
const sessionStore = useSessionStore.getState();
sessionStore.initializeSession(serverId, fakeClient, 1);
useSessionStore.setState((state) => ({
sessions: {
...state.sessions,
[serverId]: {
...state.sessions[serverId]!,
serverInfo: {
serverId,
hostname: "localhost",
version: "0.18.0",
features: { providerSwitching: true },
},
},
},
}));
sessionStore.setAgents(
serverId,
new Map([
[
"agent-1",
{
...agentSnapshot("claude"),
serverId,
parentAgentId: null,
createdAt: new Date(TS),
updatedAt: new Date(TS),
lastUserMessageAt: null,
lastActivityAt: new Date(TS),
attentionTimestamp: null,
archivedAt: null,
turn: { phase: "idle", cancellationRequestId: null },
},
],
]),
);
sessionStore.setQueuedMessages(
serverId,
new Map([
[
"agent-1",
[
{ id: "m1", text: "First queued switch prompt", attachments: [] },
{ id: "m2", text: "Second queued follow-up", attachments: [] },
],
],
]),
);
useStagedProviderSwitchStore.getState().stage(serverId, "agent-1", {
provider: "codex",
model: "gpt-5.4",
thinkingOptionId: null,
modeId: null,
providerOptions: {},
});
// M1 begins switching
runtime.drainQueuedAgentMessage(serverId, "agent-1");
await vi.waitFor(() => {
expect(switchedCalls).toEqual(["First queued switch prompt"]);
});
// Concurrent drain trigger while M1's switch is still in-flight MUST NOT drain M2!
runtime.drainQueuedAgentMessage(serverId, "agent-1");
expect(sentCalls).toEqual([]);
expect(switchedCalls).toHaveLength(1);
expect(useSessionStore.getState().sessions[serverId]?.queuedMessages.get("agent-1")).toEqual([
{ id: "m2", text: "Second queued follow-up", attachments: [] },
]);
// M1 switch completes -> staged switch clears -> M2 drains as a plain sendAgentMessage to Codex!
resolveSwitch({ agent: agentSnapshot("codex") });
await vi.waitFor(() => {
expect(getStagedProviderSwitch(serverId, "agent-1")).toBeNull();
});
runtime.drainQueuedAgentMessage(serverId, "agent-1");
await vi.waitFor(() => {
expect(sentCalls).toEqual(["Second queued follow-up"]);
});
expect(switchedCalls).toHaveLength(1);
sessionStore.clearSession(serverId);
});
});
@@ -0,0 +1,51 @@
import { beforeEach, describe, expect, it } from "vitest";
import {
clearStagedProviderSwitch,
getStagedProviderSwitch,
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();
});
});
@@ -0,0 +1,94 @@
import { create } from "zustand";
import type { AgentProvider, ProviderOptions } from "@getpaseo/protocol/agent-types";
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}`;
}
interface StagedProviderSwitchState {
stagedByKey: Map<string, StagedProviderSwitch>;
stage: (serverId: string, agentId: string, draft: StagedProviderSwitch) => void;
patch: (
serverId: string,
agentId: string,
updater: (current: StagedProviderSwitch) => StagedProviderSwitch,
) => void;
clear: (serverId: string, agentId: string) => void;
clearForServer: (serverId: string) => void;
}
export const useStagedProviderSwitchStore = create<StagedProviderSwitchState>((set) => ({
stagedByKey: 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 };
}),
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;
}
}
return changed ? { stagedByKey: next } : state;
}),
}));
export function getStagedProviderSwitch(
serverId: string,
agentId: string,
): StagedProviderSwitch | null {
return (
useStagedProviderSwitchStore.getState().stagedByKey.get(stagedKey(serverId, agentId)) ?? null
);
}
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,
);
}
@@ -385,6 +385,16 @@ function SessionProviderInternal({ children, serverId, client }: SessionProvider
console.warn("[Session] timeline replacement refresh failed", { serverId, error });
});
};
const onRewind = (message: SessionOutboundMessage) => {
if (message.type !== "agent.timeline.rewind") return;
const { agentId, epoch, seq, retireFromSeq } = message.payload;
sync.applyStreamEvent(agentId, {
event: { type: "rewind", retireFromSeq },
seq,
epoch,
timestamp: new Date(),
});
};
const sync = getHostRuntimeStore().createViewedTimelineOwner(serverId, {
canCheckFreshness: () =>
client.getLastServerInfoMessage()?.features?.timelineFreshnessCheck === true,
@@ -395,6 +405,7 @@ function SessionProviderInternal({ children, serverId, client }: SessionProvider
update: (message) => {
if (message.type === "agent_stream") onStream(message);
else if (message.type === "agent.timeline.replacement") onReplacement(message);
else if (message.type === "agent.timeline.rewind") onRewind(message);
},
});
return observation;
@@ -166,7 +166,7 @@ describe("ensureAgentIsInitialized", () => {
kind: "assistant_message",
id: "canonical-item",
text: "Canonical before restart",
timelineCursor: { epoch: "epoch-1", seq: 12 },
timelineCursor: { epoch: "epoch-1", seq: 12, anchorSeq: 12 },
timestamp: new Date("2026-07-27T10:00:00.000Z"),
},
],
+42
View File
@@ -205,6 +205,10 @@ export const ar: TranslationResources = {
pasteImageFailed: "تعذر لصق الصورة",
fileTooLarge: "{{fileName}} is too large (max {{size}})",
},
providerSwitch: {
switchingNextMessage: "التبديل إلى {{provider}} في الرسالة التالية",
switchingAfterTurn: "سيتم التبديل إلى {{provider}} بعد هذا الدور",
},
clientCommands: {
archiveAgent: "أرشفة الوكيل الحالي",
freshDraft: "أرشفة هذا الوكيل وابدأ مسودة جديدة",
@@ -436,6 +440,13 @@ export const ar: TranslationResources = {
turnFooter: {
workedFor: "عمل لمدة {{duration}}",
},
providerSwitch: {
switched: "تم التبديل من {{from}} إلى {{to}}",
contextSummary: "تم نقل {{count}} عنصر ({{chars}} / {{budget}} حرف)",
trimmed: "تم الاقتطاع: {{reasons}}",
reasonTailWindow: "سجل أقدم خارج النطاق",
reasonCharBudget: "حد الأحرف",
},
compaction: {
loading: "الضغط...",
auto: "يتم ضغط السياق تلقائيًا",
@@ -741,6 +752,8 @@ export const ar: TranslationResources = {
resumeCommandUnavailable: "أمر الاستئناف غير متوفر",
reloadingAgent: "وكيل إعادة التحميل...",
reloadedAgent: "وكيل إعادة تحميل",
reloadedAgentHistoryDiverged:
"تمت إعادة تحميل الوكيل، لكن سجل المزوّد لا يطابق هذه المحادثة، لذا لم تتم مزامنته",
failedToReloadAgent: "فشل في إعادة تحميل الوكيل",
failedToCloseAgent: "فشل في إغلاق الوكيل",
},
@@ -1814,6 +1827,9 @@ export const ar: TranslationResources = {
editProfilesLabel: "تحرير ملفات الوكيل",
createProfile: "إنشاء ملف شخصي",
createProfileFromModel: "إنشاء ملف شخصي من هذا النموذج",
profileSaved: 'تم حفظ "{{name}}"',
undo: "تراجع",
undoProfileSave: "التراجع عن حفظ الملف الشخصي",
editProfileLabel: "تحرير {{name}}",
editProfilesCount: "تحرير الملفات الشخصية ({{count}})",
modelCount: "{{count}} نموذج",
@@ -2430,6 +2446,7 @@ export const ar: TranslationResources = {
projects: "المشاريع",
connections: "اتصالات",
agents: "Agents",
agentProfiles: "ملفات الوكيل",
metadata: "البيانات الوصفية",
voice: "الصوت",
workspaces: "Workspaces",
@@ -3057,6 +3074,31 @@ export const ar: TranslationResources = {
removeConfirmMessage: 'إزالة "{{name}}"؟',
moveUp: "نقل لأعلى",
moveDown: "نقل لأسفل",
searchPlaceholder: "ابحث عن الملفات",
clearSearch: "مسح البحث",
noSearchMatches: 'لا توجد ملفات تطابق "{{query}}"',
noRoutingNote: "بدون ملاحظة",
duplicate: "تكرار",
copyName: "{{name}} (نسخة)",
moveToTop: "نقل إلى الأعلى",
profileActions: "إجراءات {{name}}",
reorderProfile: "إعادة ترتيب {{name}}",
previousProfile: "الملف السابق",
nextProfile: "الملف التالي",
chooseModelPlaceholder: "اختر نموذجًا",
searchModelsPlaceholder: "ابحث عن النماذج",
chooseModelSubtitle: "اختر نموذجًا",
customizeSettings: "تخصيص الإعدادات",
addRoutingNoteShort: "إضافة ملاحظة",
providerOptionsLabel: "خيارات {{provider}}",
discardTitle: "تجاهل التغييرات؟",
discardMessage: "لديك تغييرات غير محفوظة في هذا الملف.",
discardConfirm: "تجاهل",
columns: {
profile: "الملف",
runtime: "النموذج والتشغيل",
whenToUse: "متى يُستخدم",
},
},
daemon: {
rename: {
+43 -1
View File
@@ -203,6 +203,10 @@ export const en = {
pasteImageFailed: "Failed to paste image",
fileTooLarge: "{{fileName}} is too large (max {{size}})",
},
providerSwitch: {
switchingNextMessage: "Switching to {{provider}} on next message",
switchingAfterTurn: "Will switch to {{provider}} after this turn",
},
clientCommands: {
archiveAgent: "Archive the current agent",
freshDraft: "Archive this agent and start a fresh draft",
@@ -435,6 +439,13 @@ export const en = {
turnFooter: {
workedFor: "Worked for {{duration}}",
},
providerSwitch: {
switched: "Switched from {{from}} to {{to}}",
contextSummary: "{{count}} items transferred ({{chars}} / {{budget}} chars)",
trimmed: "Trimmed: {{reasons}}",
reasonTailWindow: "older history beyond window",
reasonCharBudget: "character budget",
},
compaction: {
loading: "Compacting...",
auto: "Context automatically compacted",
@@ -740,6 +751,8 @@ export const en = {
resumeCommandUnavailable: "Resume command not available",
reloadingAgent: "Reloading agent...",
reloadedAgent: "Reloaded agent",
reloadedAgentHistoryDiverged:
"Reloaded agent, but the provider's history doesn't match this chat, so it wasn't synced",
failedToReloadAgent: "Failed to reload agent",
failedToCloseAgent: "Failed to close agent",
},
@@ -1843,6 +1856,9 @@ export const en = {
editProfilesLabel: "Edit agent profiles",
createProfile: "Create profile",
createProfileFromModel: "Create profile from this model",
profileSaved: 'Saved "{{name}}"',
undo: "Undo",
undoProfileSave: "Undo saving profile",
editProfileLabel: "Edit {{name}}",
editProfilesCount: "Edit profiles ({{count}})",
modelCount: "{{count}} model",
@@ -2461,6 +2477,7 @@ export const en = {
projects: "Projects",
connections: "Connections",
agents: "Agents",
agentProfiles: "Agent profiles",
metadata: "Metadata",
voice: "Voice",
workspaces: "Workspaces",
@@ -3147,7 +3164,7 @@ export const en = {
featureCountOne: "{{count}} feature",
notesLabel: "When to use",
notesPlaceholder: "Use for UI work — components, layout and design tokens.",
notesHint: "Helps agents choose this profile when starting another agent.",
notesHint: "Tells agents when to pick this profile",
save: "Save",
saving: "Saving...",
remove: "Remove",
@@ -3155,6 +3172,31 @@ export const en = {
removeConfirmMessage: 'Remove "{{name}}"?',
moveUp: "Move up",
moveDown: "Move down",
searchPlaceholder: "Search profiles",
clearSearch: "Clear search",
noSearchMatches: 'No profiles match "{{query}}"',
noRoutingNote: "No note",
duplicate: "Duplicate",
copyName: "{{name}} (copy)",
moveToTop: "Move to top",
profileActions: "Actions for {{name}}",
reorderProfile: "Reorder {{name}}",
previousProfile: "Previous profile",
nextProfile: "Next profile",
chooseModelPlaceholder: "Select a model",
searchModelsPlaceholder: "Search models",
chooseModelSubtitle: "Select a model",
customizeSettings: "Customize settings",
addRoutingNoteShort: "Add a note",
providerOptionsLabel: "{{provider}} options",
discardTitle: "Discard changes?",
discardMessage: "You have unsaved changes to this profile.",
discardConfirm: "Discard",
columns: {
profile: "Profile",
runtime: "Model & runtime",
whenToUse: "When to use",
},
},
daemon: {
rename: {
+42
View File
@@ -207,6 +207,10 @@ export const es: TranslationResources = {
pasteImageFailed: "No se pudo pegar la imagen",
fileTooLarge: "{{fileName}} is too large (max {{size}})",
},
providerSwitch: {
switchingNextMessage: "Cambiando a {{provider}} en el próximo mensaje",
switchingAfterTurn: "Se cambiará a {{provider}} después de este turno",
},
clientCommands: {
archiveAgent: "Archivar el agente actual",
freshDraft: "Archive este agente y comience un nuevo borrador",
@@ -441,6 +445,13 @@ export const es: TranslationResources = {
turnFooter: {
workedFor: "Trabajó durante {{duration}}",
},
providerSwitch: {
switched: "Cambiado de {{from}} a {{to}}",
contextSummary: "{{count}} elementos transferidos ({{chars}} / {{budget}} caracteres)",
trimmed: "Recortado: {{reasons}}",
reasonTailWindow: "historial anterior fuera de la ventana",
reasonCharBudget: "límite de caracteres",
},
compaction: {
loading: "Compactando...",
auto: "Contexto compactado automáticamente",
@@ -748,6 +759,8 @@ export const es: TranslationResources = {
resumeCommandUnavailable: "Comando de reanudación no disponible",
reloadingAgent: "Agente de recarga...",
reloadedAgent: "Agente recargado",
reloadedAgentHistoryDiverged:
"Agente recargado, pero el historial del proveedor no coincide con este chat, así que no se sincronizó",
failedToReloadAgent: "No se pudo recargar el agente",
failedToCloseAgent: "No se pudo cerrar el agente",
},
@@ -1862,6 +1875,9 @@ export const es: TranslationResources = {
editProfilesLabel: "Editar perfiles de agente",
createProfile: "Crear perfil",
createProfileFromModel: "Crear perfil desde este modelo",
profileSaved: 'Guardado "{{name}}"',
undo: "Deshacer",
undoProfileSave: "Deshacer perfil guardado",
editProfileLabel: "Editar {{name}}",
editProfilesCount: "Editar perfiles ({{count}})",
modelCount: "{{count}} modelo",
@@ -2444,6 +2460,7 @@ export const es: TranslationResources = {
projects: "Proyectos",
connections: "Conexiones",
agents: "Agents",
agentProfiles: "Perfiles de agente",
metadata: "Metadatos",
voice: "Voz",
workspaces: "Workspaces",
@@ -3083,6 +3100,31 @@ export const es: TranslationResources = {
removeConfirmMessage: '¿Eliminar "{{name}}"?',
moveUp: "Mover hacia arriba",
moveDown: "Mover hacia abajo",
searchPlaceholder: "Buscar perfiles",
clearSearch: "Limpiar búsqueda",
noSearchMatches: 'Ningún perfil coincide con "{{query}}"',
noRoutingNote: "Sin nota",
duplicate: "Duplicar",
copyName: "{{name}} (copia)",
moveToTop: "Mover al principio",
profileActions: "Acciones para {{name}}",
reorderProfile: "Reordenar {{name}}",
previousProfile: "Perfil anterior",
nextProfile: "Perfil siguiente",
chooseModelPlaceholder: "Seleccionar un modelo",
searchModelsPlaceholder: "Buscar modelos",
chooseModelSubtitle: "Seleccionar un modelo",
customizeSettings: "Personalizar ajustes",
addRoutingNoteShort: "Añadir una nota",
providerOptionsLabel: "Opciones de {{provider}}",
discardTitle: "¿Descartar cambios?",
discardMessage: "Tienes cambios sin guardar en este perfil.",
discardConfirm: "Descartar",
columns: {
profile: "Perfil",
runtime: "Modelo y ejecución",
whenToUse: "Cuándo usarlo",
},
},
daemon: {
rename: {
+42
View File
@@ -208,6 +208,10 @@ export const fr: TranslationResources = {
pasteImageFailed: "Impossible de coller l’image",
fileTooLarge: "{{fileName}} est trop volumineux (maximum {{size}})",
},
providerSwitch: {
switchingNextMessage: "Passage à {{provider}} au prochain message",
switchingAfterTurn: "Passage à {{provider}} après ce tour",
},
clientCommands: {
archiveAgent: "Archiver l’agent actuel",
freshDraft: "Archiver cet agent et démarrer un nouveau brouillon",
@@ -441,6 +445,13 @@ export const fr: TranslationResources = {
turnFooter: {
workedFor: "A travaillé pendant {{duration}}",
},
providerSwitch: {
switched: "Passé de {{from}} à {{to}}",
contextSummary: "{{count}} éléments transférés ({{chars}} / {{budget}} caractères)",
trimmed: "Tronqué : {{reasons}}",
reasonTailWindow: "historique antérieur hors fenêtre",
reasonCharBudget: "limite de caractères",
},
compaction: {
loading: "Compaction…",
auto: "Contexte compacté automatiquement",
@@ -748,6 +759,8 @@ export const fr: TranslationResources = {
resumeCommandUnavailable: "Commande de reprise indisponible",
reloadingAgent: "Rechargement de l’agent…",
reloadedAgent: "Agent rechargé",
reloadedAgentHistoryDiverged:
"Agent rechargé, mais l’historique du fournisseur ne correspond pas à cette conversation, il n’a donc pas été synchronisé",
failedToReloadAgent: "Impossible de recharger l’agent",
failedToCloseAgent: "Impossible de fermer l’agent",
},
@@ -1860,6 +1873,9 @@ export const fr: TranslationResources = {
editProfilesLabel: "Modifier les profils d’agent",
createProfile: "Créer un profil",
createProfileFromModel: "Créer un profil à partir de ce modèle",
profileSaved: "« {{name}} » enregistré",
undo: "Annuler",
undoProfileSave: "Annuler l’enregistrement du profil",
editProfileLabel: "Modifier {{name}}",
editProfilesCount: "Modifier les profils ({{count}})",
modelCount: "{{count}} modèle",
@@ -2444,6 +2460,7 @@ export const fr: TranslationResources = {
projects: "Projets",
connections: "Connexions",
agents: "Agents",
agentProfiles: "Profils d’agent",
metadata: "Métadonnées",
voice: "Voix",
workspaces: "Espaces de travail",
@@ -3087,6 +3104,31 @@ export const fr: TranslationResources = {
removeConfirmMessage: "Supprimer « {{name}} » ?",
moveUp: "Monter",
moveDown: "Descendre",
searchPlaceholder: "Rechercher des profils",
clearSearch: "Effacer la recherche",
noSearchMatches: "Aucun profil ne correspond à « {{query}} »",
noRoutingNote: "Aucune note",
duplicate: "Dupliquer",
copyName: "{{name}} (copie)",
moveToTop: "Placer en haut",
profileActions: "Actions pour {{name}}",
reorderProfile: "Réorganiser {{name}}",
previousProfile: "Profil précédent",
nextProfile: "Profil suivant",
chooseModelPlaceholder: "Sélectionner un modèle",
searchModelsPlaceholder: "Rechercher des modèles",
chooseModelSubtitle: "Sélectionner un modèle",
customizeSettings: "Personnaliser les réglages",
addRoutingNoteShort: "Ajouter une note",
providerOptionsLabel: "Options {{provider}}",
discardTitle: "Ignorer les modifications ?",
discardMessage: "Vous avez des modifications non enregistrées pour ce profil.",
discardConfirm: "Ignorer",
columns: {
profile: "Profil",
runtime: "Modèle et exécution",
whenToUse: "Quand l’utiliser",
},
},
daemon: {
rename: {
+42
View File
@@ -207,6 +207,10 @@ export const ja: TranslationResources = {
pasteImageFailed: "画像を貼り付けられませんでした",
fileTooLarge: "{{fileName}}が大きすぎます(最大{{size}})",
},
providerSwitch: {
switchingNextMessage: "次のメッセージで {{provider}} に切り替えます",
switchingAfterTurn: "このターン終了後に {{provider}} に切り替えます",
},
clientCommands: {
archiveAgent: "現在のエージェントをアーカイブ",
freshDraft: "このエージェントをアーカイブして新しい下書きを開始",
@@ -441,6 +445,13 @@ export const ja: TranslationResources = {
turnFooter: {
workedFor: "作業時間 {{duration}}",
},
providerSwitch: {
switched: "{{from}} から {{to}} に切り替えました",
contextSummary: "{{count}} 件を引き継ぎました ({{chars}} / {{budget}} 文字)",
trimmed: "省略: {{reasons}}",
reasonTailWindow: "ウィンドウ外の古い履歴",
reasonCharBudget: "文字数上限",
},
compaction: {
loading: "コンテキストを圧縮中...",
auto: "コンテキストが自動的に圧縮されました",
@@ -748,6 +759,8 @@ export const ja: TranslationResources = {
resumeCommandUnavailable: "再開コマンドが利用できません",
reloadingAgent: "エージェントを再読み込み中...",
reloadedAgent: "エージェントを再読み込みしました",
reloadedAgentHistoryDiverged:
"エージェントを再読み込みしましたが、プロバイダーの履歴がこのチャットと一致しないため同期しませんでした",
failedToReloadAgent: "エージェントの再読み込みに失敗しました",
failedToCloseAgent: "エージェントを閉じられませんでした",
},
@@ -1834,6 +1847,9 @@ export const ja: TranslationResources = {
editProfilesLabel: "エージェントプロファイルを編集",
createProfile: "プロファイルを作成",
createProfileFromModel: "このモデルからプロファイルを作成",
profileSaved: "「{{name}}」を保存しました",
undo: "元に戻す",
undoProfileSave: "プロファイル保存を取り消す",
editProfileLabel: "{{name}}を編集",
editProfilesCount: "プロファイルを編集({{count}})",
modelCount: "{{count}}つのモデル",
@@ -2418,6 +2434,7 @@ export const ja: TranslationResources = {
projects: "プロジェクト",
connections: "接続",
agents: "エージェント",
agentProfiles: "エージェントプロファイル",
metadata: "メタデータ",
voice: "音声",
workspaces: "ワークスペース",
@@ -3052,6 +3069,31 @@ export const ja: TranslationResources = {
removeConfirmMessage: '"{{name}}"を削除しますか?',
moveUp: "上に移動",
moveDown: "下に移動",
searchPlaceholder: "プロファイルを検索",
clearSearch: "検索をクリア",
noSearchMatches: "「{{query}}」に一致するプロファイルはありません",
noRoutingNote: "メモなし",
duplicate: "複製",
copyName: "{{name}}(コピー)",
moveToTop: "一番上に移動",
profileActions: "{{name}} の操作",
reorderProfile: "{{name}} を並べ替え",
previousProfile: "前のプロファイル",
nextProfile: "次のプロファイル",
chooseModelPlaceholder: "モデルを選択",
searchModelsPlaceholder: "モデルを検索",
chooseModelSubtitle: "モデルを選択",
customizeSettings: "設定をカスタマイズ",
addRoutingNoteShort: "メモを追加",
providerOptionsLabel: "{{provider}} オプション",
discardTitle: "変更を破棄しますか?",
discardMessage: "このプロファイルに未保存の変更があります。",
discardConfirm: "破棄",
columns: {
profile: "プロファイル",
runtime: "モデルと実行",
whenToUse: "使用場面",
},
},
daemon: {
rename: {
+42
View File
@@ -205,6 +205,10 @@ export const ko: TranslationResources = {
pasteImageFailed: "이미지를 붙여넣지 못했습니다.",
fileTooLarge: "{{fileName}}이(가) 너무 큽니다 (최대 {{size}})",
},
providerSwitch: {
switchingNextMessage: "다음 메시지에서 {{provider}}(으)로 전환합니다",
switchingAfterTurn: "이 턴이 끝난 후 {{provider}}(으)로 전환합니다",
},
clientCommands: {
archiveAgent: "현재 에이전트 보관",
freshDraft: "이 에이전트를 보관하고 새 초안을 시작합니다",
@@ -437,6 +441,13 @@ export const ko: TranslationResources = {
turnFooter: {
workedFor: "작업 시간 {{duration}}",
},
providerSwitch: {
switched: "{{from}}에서 {{to}}(으)로 전환됨",
contextSummary: "{{count}}개 항목 전달됨 ({{chars}} / {{budget}}자)",
trimmed: "생략됨: {{reasons}}",
reasonTailWindow: "창 범위를 벗어난 이전 기록",
reasonCharBudget: "문자 수 제한",
},
compaction: {
loading: "압축하는 중...",
auto: "컨텍스트가 자동으로 압축되었습니다",
@@ -743,6 +754,8 @@ export const ko: TranslationResources = {
resumeCommandUnavailable: "재개 명령을 사용할 수 없습니다",
reloadingAgent: "에이전트 다시 로드 중...",
reloadedAgent: "에이전트를 다시 로드했습니다",
reloadedAgentHistoryDiverged:
"에이전트를 다시 로드했지만 제공자 기록이 이 채팅과 일치하지 않아 동기화하지 않았습니다",
failedToReloadAgent: "에이전트를 다시 로드하지 못했습니다",
failedToCloseAgent: "에이전트를 닫지 못했습니다",
},
@@ -1825,6 +1838,9 @@ export const ko: TranslationResources = {
editProfilesLabel: "에이전트 프로필 편집",
createProfile: "프로필 만들기",
createProfileFromModel: "이 모델에서 프로필 만들기",
profileSaved: '"{{name}}" 저장됨',
undo: "실행 취소",
undoProfileSave: "프로필 저장 취소",
editProfileLabel: "{{name}} 편집",
editProfilesCount: "프로필 편집 ({{count}})",
modelCount: "모델 {{count}}개",
@@ -2405,6 +2421,7 @@ export const ko: TranslationResources = {
projects: "프로젝트",
connections: "연결",
agents: "에이전트",
agentProfiles: "에이전트 프로필",
metadata: "메타데이터",
voice: "음성",
workspaces: "워크스페이스",
@@ -3036,6 +3053,31 @@ export const ko: TranslationResources = {
removeConfirmMessage: '"{{name}}"을(를) 제거할까요?',
moveUp: "위로 이동",
moveDown: "아래로 이동",
searchPlaceholder: "프로필 검색",
clearSearch: "검색 지우기",
noSearchMatches: '"{{query}}"와 일치하는 프로필이 없습니다',
noRoutingNote: "메모 없음",
duplicate: "복제",
copyName: "{{name}} (사본)",
moveToTop: "맨 위로 이동",
profileActions: "{{name}} 작업",
reorderProfile: "{{name}} 순서 변경",
previousProfile: "이전 프로필",
nextProfile: "다음 프로필",
chooseModelPlaceholder: "모델 선택",
searchModelsPlaceholder: "모델 검색",
chooseModelSubtitle: "모델 선택",
customizeSettings: "설정 사용자 지정",
addRoutingNoteShort: "메모 추가",
providerOptionsLabel: "{{provider}} 옵션",
discardTitle: "변경 사항을 버리시겠습니까?",
discardMessage: "이 프로필에 저장되지 않은 변경 사항이 있습니다.",
discardConfirm: "버리기",
columns: {
profile: "프로필",
runtime: "모델 및 런타임",
whenToUse: "사용 시기",
},
},
daemon: {
rename: {
+42
View File
@@ -206,6 +206,10 @@ export const ptBR: TranslationResources = {
pasteImageFailed: "Falha ao colar a imagem",
fileTooLarge: "{{fileName}} é grande demais (máximo {{size}})",
},
providerSwitch: {
switchingNextMessage: "Trocando para {{provider}} na próxima mensagem",
switchingAfterTurn: "Trocará para {{provider}} após este turno",
},
clientCommands: {
archiveAgent: "Arquivar o agente atual",
freshDraft: "Arquivar este agente e iniciar um novo rascunho",
@@ -440,6 +444,13 @@ export const ptBR: TranslationResources = {
turnFooter: {
workedFor: "Trabalhou por {{duration}}",
},
providerSwitch: {
switched: "Trocado de {{from}} para {{to}}",
contextSummary: "{{count}} itens transferidos ({{chars}} / {{budget}} caracteres)",
trimmed: "Cortado: {{reasons}}",
reasonTailWindow: "histórico anterior além da janela",
reasonCharBudget: "limite de caracteres",
},
compaction: {
loading: "Compactando...",
auto: "Contexto compactado automaticamente",
@@ -746,6 +757,8 @@ export const ptBR: TranslationResources = {
resumeCommandUnavailable: "Comando de retomada indisponível",
reloadingAgent: "Recarregando agente...",
reloadedAgent: "Agente recarregado",
reloadedAgentHistoryDiverged:
"Agente recarregado, mas o histórico do provedor não corresponde a este chat, então não foi sincronizado",
failedToReloadAgent: "Falha ao recarregar agente",
failedToCloseAgent: "Falha ao fechar agente",
},
@@ -1847,6 +1860,9 @@ export const ptBR: TranslationResources = {
editProfilesLabel: "Editar perfis de agente",
createProfile: "Criar perfil",
createProfileFromModel: "Criar perfil a partir deste modelo",
profileSaved: 'Salvo "{{name}}"',
undo: "Desfazer",
undoProfileSave: "Desfazer salvamento do perfil",
editProfileLabel: "Editar {{name}}",
editProfilesCount: "Editar perfis ({{count}})",
modelCount: "{{count}} modelo",
@@ -2429,6 +2445,7 @@ export const ptBR: TranslationResources = {
projects: "Projetos",
connections: "Conexões",
agents: "Agentes",
agentProfiles: "Perfis de agente",
metadata: "Metadados",
voice: "Voz",
workspaces: "Workspaces",
@@ -3065,6 +3082,31 @@ export const ptBR: TranslationResources = {
removeConfirmMessage: 'Remover "{{name}}"?',
moveUp: "Mover para cima",
moveDown: "Mover para baixo",
searchPlaceholder: "Buscar perfis",
clearSearch: "Limpar busca",
noSearchMatches: 'Nenhum perfil corresponde a "{{query}}"',
noRoutingNote: "Sem nota",
duplicate: "Duplicar",
copyName: "{{name}} (cópia)",
moveToTop: "Mover para o topo",
profileActions: "Ações para {{name}}",
reorderProfile: "Reordenar {{name}}",
previousProfile: "Perfil anterior",
nextProfile: "Próximo perfil",
chooseModelPlaceholder: "Selecionar um modelo",
searchModelsPlaceholder: "Buscar modelos",
chooseModelSubtitle: "Selecionar um modelo",
customizeSettings: "Personalizar configurações",
addRoutingNoteShort: "Adicionar uma nota",
providerOptionsLabel: "Opções de {{provider}}",
discardTitle: "Descartar alterações?",
discardMessage: "Você tem alterações não salvas neste perfil.",
discardConfirm: "Descartar",
columns: {
profile: "Perfil",
runtime: "Modelo e execução",
whenToUse: "Quando usar",
},
},
daemon: {
rename: {
+42
View File
@@ -207,6 +207,10 @@ export const ru: TranslationResources = {
pasteImageFailed: "Не удалось вставить изображение",
fileTooLarge: "Файл {{fileName}} слишком большой (максимальный размер: {{size}})",
},
providerSwitch: {
switchingNextMessage: "Переключение на {{provider}} в следующем сообщении",
switchingAfterTurn: "Переключение на {{provider}} после этого хода",
},
clientCommands: {
archiveAgent: "Архивировать текущего агента",
freshDraft: "Архивировать этого агента и создать новый черновик",
@@ -440,6 +444,13 @@ export const ru: TranslationResources = {
turnFooter: {
workedFor: "Время работы: {{duration}}",
},
providerSwitch: {
switched: "Переключено с {{from}} на {{to}}",
contextSummary: "Передано элементов: {{count}} ({{chars}} / {{budget}} симв.)",
trimmed: "Сокращено: {{reasons}}",
reasonTailWindow: "более ранняя история вне окна",
reasonCharBudget: "лимит символов",
},
compaction: {
loading: "Сжатие контекста...",
auto: "Контекст сжат автоматически",
@@ -749,6 +760,8 @@ export const ru: TranslationResources = {
resumeCommandUnavailable: "Команда возобновления недоступна",
reloadingAgent: "Перезагрузка агента...",
reloadedAgent: "Агент перезагружен",
reloadedAgentHistoryDiverged:
"Агент перезагружен, но история провайдера не совпадает с этим чатом, поэтому она не синхронизирована",
failedToReloadAgent: "Не удалось перезагрузить агента",
failedToCloseAgent: "Не удалось закрыть агента",
},
@@ -1847,6 +1860,9 @@ export const ru: TranslationResources = {
editProfilesLabel: "Изменить профили агентов",
createProfile: "Создать профиль",
createProfileFromModel: "Создать профиль из этой модели",
profileSaved: "Сохранено: «{{name}}»",
undo: "Отменить",
undoProfileSave: "Отменить сохранение профиля",
editProfileLabel: "Изменить {{name}}",
editProfilesCount: "Изменить профили ({{count}})",
modelCount: "{{count}} модель",
@@ -2431,6 +2447,7 @@ export const ru: TranslationResources = {
projects: "Проекты",
connections: "Подключения",
agents: "Агенты",
agentProfiles: "Профили агентов",
metadata: "Метаданные",
voice: "Голос",
workspaces: "Рабочие пространства",
@@ -3076,6 +3093,31 @@ export const ru: TranslationResources = {
removeConfirmMessage: "Удалить «{{name}}»?",
moveUp: "Переместить вверх",
moveDown: "Переместить вниз",
searchPlaceholder: "Поиск профилей",
clearSearch: "Очистить поиск",
noSearchMatches: "Нет профилей по запросу «{{query}}»",
noRoutingNote: "Без заметки",
duplicate: "Дублировать",
copyName: "{{name}} (копия)",
moveToTop: "В начало списка",
profileActions: "Действия для {{name}}",
reorderProfile: "Изменить порядок {{name}}",
previousProfile: "Предыдущий профиль",
nextProfile: "Следующий профиль",
chooseModelPlaceholder: "Выберите модель",
searchModelsPlaceholder: "Поиск моделей",
chooseModelSubtitle: "Выберите модель",
customizeSettings: "Настроить параметры",
addRoutingNoteShort: "Добавить заметку",
providerOptionsLabel: "Параметры {{provider}}",
discardTitle: "Отменить изменения?",
discardMessage: "В этом профиле есть несохранённые изменения.",
discardConfirm: "Отменить",
columns: {
profile: "Профиль",
runtime: "Модель и запуск",
whenToUse: "Когда использовать",
},
},
daemon: {
rename: {
+42
View File
@@ -205,6 +205,10 @@ export const zhCN: TranslationResources = {
pasteImageFailed: "无法粘贴图片",
fileTooLarge: "{{fileName}} is too large (max {{size}})",
},
providerSwitch: {
switchingNextMessage: "下一条消息将切换到 {{provider}}",
switchingAfterTurn: "本轮结束后将切换到 {{provider}}",
},
clientCommands: {
archiveAgent: "归档当前 Agent",
freshDraft: "归档此 Agent 并开始新的草稿",
@@ -436,6 +440,13 @@ export const zhCN: TranslationResources = {
turnFooter: {
workedFor: "工作了 {{duration}}",
},
providerSwitch: {
switched: "已从 {{from}} 切换到 {{to}}",
contextSummary: "已传递 {{count}} 项上下文({{chars}} / {{budget}} 字符)",
trimmed: "已裁剪:{{reasons}}",
reasonTailWindow: "超出窗口的早期历史",
reasonCharBudget: "字符预算限制",
},
compaction: {
loading: "正在压缩...",
auto: "上下文已自动压缩",
@@ -741,6 +752,8 @@ export const zhCN: TranslationResources = {
resumeCommandUnavailable: "恢复命令不可用",
reloadingAgent: "正在重新加载 Agent...",
reloadedAgent: "已重新加载 Agent",
reloadedAgentHistoryDiverged:
"已重新加载 Agent,但提供方的历史记录与此对话不一致,因此未同步",
failedToReloadAgent: "重新加载 Agent 失败",
failedToCloseAgent: "关闭 Agent 失败",
},
@@ -1796,6 +1809,9 @@ export const zhCN: TranslationResources = {
editProfilesLabel: "编辑智能体配置文件",
createProfile: "创建配置文件",
createProfileFromModel: "从此模型创建配置文件",
profileSaved: "已保存“{{name}}”",
undo: "撤销",
undoProfileSave: "撤销保存配置文件",
editProfileLabel: "编辑 {{name}}",
editProfilesCount: "编辑配置文件 ({{count}})",
modelCount: "{{count}} 个模型",
@@ -2371,6 +2387,7 @@ export const zhCN: TranslationResources = {
projects: "项目",
connections: "连接",
agents: "Agents",
agentProfiles: "智能体配置文件",
metadata: "元数据",
voice: "语音",
workspaces: "Workspaces",
@@ -2991,6 +3008,31 @@ export const zhCN: TranslationResources = {
removeConfirmMessage: "移除「{{name}}」?",
moveUp: "上移",
moveDown: "下移",
searchPlaceholder: "搜索配置文件",
clearSearch: "清除搜索",
noSearchMatches: "没有匹配“{{query}}”的配置文件",
noRoutingNote: "无说明",
duplicate: "复制",
copyName: "{{name}}(副本)",
moveToTop: "移至顶部",
profileActions: "{{name}} 的操作",
reorderProfile: "调整 {{name}} 顺序",
previousProfile: "上一个配置文件",
nextProfile: "下一个配置文件",
chooseModelPlaceholder: "选择模型",
searchModelsPlaceholder: "搜索模型",
chooseModelSubtitle: "选择模型",
customizeSettings: "自定义设置",
addRoutingNoteShort: "添加说明",
providerOptionsLabel: "{{provider}} 选项",
discardTitle: "放弃更改?",
discardMessage: "此配置文件有未保存的更改。",
discardConfirm: "放弃",
columns: {
profile: "配置文件",
runtime: "模型与运行时",
whenToUse: "适用场景",
},
},
daemon: {
rename: {
@@ -0,0 +1,18 @@
export interface RouteLeaveGuard {
isDirty: () => boolean;
confirmDiscard: () => Promise<boolean>;
}
/**
* Installs the web browser history (`popstate`) guard before Expo Router mounts
* its own `popstate` listener. No-op on native, where React Navigation's
* `beforeRemove` owns swipe-back and hardware Back interception.
*/
export function installRouteLeavePopStateGuard(): void {
// Native platforms handle back navigation through React Navigation's beforeRemove event.
}
/** Registers the active screen's leave guard for browser Back/Forward interception. */
export function registerRouteLeaveGuard(_guard: RouteLeaveGuard | null): () => void {
return () => {};
}
@@ -0,0 +1,268 @@
import { describe, expect, it } from "vitest";
import {
createWebPopStateGuard,
type PopStateStorageLike,
type PopStateWindowLike,
} from "./index.web";
interface FakeHistoryEntry {
state: unknown;
path: string;
}
function createMemoryStorage(): PopStateStorageLike {
const store = new Map<string, string>();
return {
getItem: (key) => store.get(key) ?? null,
setItem: (key, value) => {
store.set(key, value);
},
};
}
function createFakeWindow(
initialEntries: FakeHistoryEntry[],
options?: { index?: number; sessionStorage?: PopStateStorageLike },
) {
let entries: FakeHistoryEntry[] = [...initialEntries];
let index = options?.index ?? entries.length - 1;
const listeners: Array<(event: PopStateEvent) => void> = [];
const current = () => entries[index] ?? { state: null, path: "/" };
const dispatchPopState = (state: unknown) => {
let stopped = false;
const event = {
state,
stopImmediatePropagation() {
stopped = true;
},
} as unknown as PopStateEvent;
for (const listener of listeners.slice()) {
if (stopped) {
break;
}
listener(event);
}
return { stopped };
};
const win: PopStateWindowLike = {
...(options?.sessionStorage ? { sessionStorage: options.sessionStorage } : {}),
history: {
get state() {
return current().state;
},
pushState(state, _unused, url) {
const path = typeof url === "string" ? url : String(url ?? "/");
entries = entries.slice(0, index + 1);
entries.push({ state, path });
index = entries.length - 1;
},
replaceState(state, _unused, url) {
const path = typeof url === "string" ? url : String(url ?? "/");
entries[index] = { state, path };
},
go(delta = 0) {
const nextIndex = index + delta;
if (nextIndex < 0 || nextIndex >= entries.length || nextIndex === index) {
return;
}
index = nextIndex;
dispatchPopState(current().state);
},
},
addEventListener(_type, listener) {
listeners.push(listener);
},
removeEventListener(_type, listener) {
const idx = listeners.indexOf(listener);
if (idx >= 0) {
listeners.splice(idx, 1);
}
},
dispatchEvent(event) {
const popEvent = event as PopStateEvent;
dispatchPopState(popEvent.state);
return true;
},
};
return {
win,
getPath: () => current().path,
getEntries: () => entries.map((entry) => entry.path),
getIndex: () => index,
simulateHistoryJump: (delta: number) => {
const nextIndex = index + delta;
index = Math.max(0, Math.min(entries.length - 1, nextIndex));
return dispatchPopState(current().state);
},
};
}
describe("createWebPopStateGuard", () => {
it("preserves intervening history entries when canceling a two-step Back jump", async () => {
const fake = createFakeWindow([{ state: { id: "id-0" }, path: "/open-project" }], {
sessionStorage: createMemoryStorage(),
});
const guard = createWebPopStateGuard(fake.win);
guard.install();
const routerSeenPaths: string[] = [];
fake.win.addEventListener("popstate", () => {
routerSeenPaths.push(fake.getPath());
});
fake.win.history.pushState({ id: "id-1" }, "", "/settings");
fake.win.history.pushState({ id: "id-2" }, "", "/settings/hosts/srv/agent-profiles");
let dirty = true;
guard.register({
isDirty: () => dirty,
confirmDiscard: async () => false,
});
// Jump straight from Agent profiles back two entries to Open project and cancel.
const { stopped } = fake.simulateHistoryJump(-2);
await Promise.resolve();
expect(stopped).toBe(true);
expect(routerSeenPaths).toEqual([]);
expect(fake.getPath()).toBe("/settings/hosts/srv/agent-profiles");
expect(fake.getEntries()).toEqual([
"/open-project",
"/settings",
"/settings/hosts/srv/agent-profiles",
]);
expect(fake.getIndex()).toBe(2);
// After closing the editor, a normal one-step Back still reaches Settings.
dirty = false;
fake.simulateHistoryJump(-1);
expect(fake.getPath()).toBe("/settings");
expect(routerSeenPaths).toEqual(["/settings"]);
});
it("restores the editor URL on a two-step Back jump after a reload (with sessionStorage)", async () => {
const storage = createMemoryStorage();
const beforeReload = createFakeWindow([{ state: { id: "id-0" }, path: "/open-project" }], {
sessionStorage: storage,
});
const firstGuard = createWebPopStateGuard(beforeReload.win);
firstGuard.install();
beforeReload.win.history.pushState({ id: "id-1" }, "", "/settings");
beforeReload.win.history.pushState({ id: "id-2" }, "", "/settings/hosts/srv/agent-profiles");
firstGuard.dispose();
// Simulate reload on Agent profiles with the same browser history and tab sessionStorage.
const afterReload = createFakeWindow(
[
{ state: { id: "id-0" }, path: "/open-project" },
{ state: { id: "id-1" }, path: "/settings" },
{ state: { id: "id-2" }, path: "/settings/hosts/srv/agent-profiles" },
],
{ index: 2, sessionStorage: storage },
);
const guard = createWebPopStateGuard(afterReload.win);
guard.install();
guard.register({
isDirty: () => true,
confirmDiscard: async () => false,
});
afterReload.simulateHistoryJump(-2);
await Promise.resolve();
expect(afterReload.getPath()).toBe("/settings/hosts/srv/agent-profiles");
expect(afterReload.getIndex()).toBe(2);
});
it("steps back to the exact editor entry after a reload even without sessionStorage", async () => {
const afterReload = createFakeWindow(
[
{ state: { id: "id-0" }, path: "/open-project" },
{ state: { id: "id-1" }, path: "/settings" },
{ state: { id: "id-2" }, path: "/settings/hosts/srv/agent-profiles" },
],
{ index: 2 },
);
const guard = createWebPopStateGuard(afterReload.win);
guard.install();
const routerSeenPaths: string[] = [];
afterReload.win.addEventListener("popstate", () => {
routerSeenPaths.push(afterReload.getPath());
});
guard.register({
isDirty: () => true,
confirmDiscard: async () => false,
});
afterReload.simulateHistoryJump(-2);
await Promise.resolve();
expect(routerSeenPaths).toEqual([]);
expect(afterReload.getPath()).toBe("/settings/hosts/srv/agent-profiles");
expect(afterReload.getIndex()).toBe(2);
});
it("reaches the exact two-step destination when confirming a multi-step Back jump", async () => {
const fake = createFakeWindow([{ state: { id: "id-0" }, path: "/open-project" }], {
sessionStorage: createMemoryStorage(),
});
const guard = createWebPopStateGuard(fake.win);
guard.install();
const routerSeenPaths: string[] = [];
fake.win.addEventListener("popstate", () => {
routerSeenPaths.push(fake.getPath());
});
fake.win.history.pushState({ id: "id-1" }, "", "/settings");
fake.win.history.pushState({ id: "id-2" }, "", "/settings/hosts/srv/agent-profiles");
let dirty = true;
guard.register({
isDirty: () => dirty,
confirmDiscard: async () => {
dirty = false;
return true;
},
});
fake.simulateHistoryJump(-2);
await Promise.resolve();
expect(routerSeenPaths).toEqual(["/open-project"]);
expect(fake.getPath()).toBe("/open-project");
expect(fake.getIndex()).toBe(0);
});
it("passes browser Back straight through when the guard is not dirty", () => {
const fake = createFakeWindow([{ state: { id: "id-0" }, path: "/open-project" }]);
const guard = createWebPopStateGuard(fake.win);
guard.install();
let routerSawPopState = 0;
fake.win.addEventListener("popstate", () => {
routerSawPopState += 1;
});
fake.win.history.pushState({ id: "id-1" }, "", "/settings/hosts/srv/agent-profiles");
guard.register({
isDirty: () => false,
confirmDiscard: async () => {
throw new Error("should not prompt when clean");
},
});
const { stopped } = fake.simulateHistoryJump(-1);
expect(stopped).toBe(false);
expect(routerSawPopState).toBe(1);
expect(fake.getPath()).toBe("/open-project");
});
});
@@ -0,0 +1,307 @@
import type { RouteLeaveGuard } from "./index";
export type { RouteLeaveGuard } from "./index";
const HISTORY_STORAGE_KEY = "@paseo:route-leave-history:v1";
const MAX_REVERT_STEPS = 20;
const REVERT_TIMEOUT_MS = 400;
export interface PopStateStorageLike {
getItem(key: string): string | null;
setItem(key: string, value: string): void;
}
export interface PopStateWindowLike {
history: {
readonly state: unknown;
pushState(data: unknown, unused: string, url?: string | URL | null): void;
replaceState(data: unknown, unused: string, url?: string | URL | null): void;
go(delta?: number): void;
};
sessionStorage?: PopStateStorageLike;
addEventListener(type: "popstate", listener: (event: PopStateEvent) => void): void;
removeEventListener(type: "popstate", listener: (event: PopStateEvent) => void): void;
dispatchEvent(event: Event): boolean;
}
export interface WebPopStateGuardController {
install(): void;
register(guard: RouteLeaveGuard | null): () => void;
dispose(): void;
}
function readHistoryStateId(state: unknown): string | null {
if (typeof state === "object" && state !== null && "id" in state) {
const id = (state as { id?: unknown }).id;
return typeof id === "string" && id.length > 0 ? id : null;
}
return null;
}
function createPopStateEvent(state: unknown): PopStateEvent {
if (typeof PopStateEvent === "function") {
return new PopStateEvent("popstate", { state });
}
const event = new Event("popstate") as PopStateEvent;
Object.defineProperty(event, "state", { value: state });
return event;
}
function loadStoredEntryIds(storage: PopStateStorageLike | undefined): Array<string | null> | null {
if (!storage) {
return null;
}
try {
const raw = storage.getItem(HISTORY_STORAGE_KEY);
if (!raw) {
return null;
}
const parsed: unknown = JSON.parse(raw);
if (!Array.isArray(parsed)) {
return null;
}
if (!parsed.every((item) => item === null || typeof item === "string")) {
return null;
}
return parsed as Array<string | null>;
} catch {
return null;
}
}
function persistEntryIds(
storage: PopStateStorageLike | undefined,
entryIds: readonly (string | null)[],
): void {
if (!storage) {
return;
}
try {
storage.setItem(HISTORY_STORAGE_KEY, JSON.stringify(entryIds));
} catch {
// Ignore storage quota or private-mode restrictions; fallback stepping still works.
}
}
/**
* Intercepts browser Back/Forward (`popstate`) before Expo Router's
* `createMemoryHistory` listener runs.
*
* Tracks the ordered history entry IDs written by Expo Router (persisted in
* `sessionStorage` so reloads keep the tab's full index). Canceling any
* traversal reverts via `history.go(delta)` without calling `pushState` or
* truncating intervening entries — and verifies it landed back on the saved
* entry ID (stepping forward if pre-reload history was unknown). Confirming
* replays `popstate` at the browser's exact selected destination.
*/
export function createWebPopStateGuard(win: PopStateWindowLike): WebPopStateGuardController {
let installed = false;
let activeGuard: RouteLeaveGuard | null = null;
let confirmInFlight = false;
let isReverting = false;
let revertingTargetId: string | null = null;
let revertStepDirection: 1 | -1 = 1;
let revertStepsRemaining = 0;
let isReplaying = false;
let revertResetTimer: ReturnType<typeof setTimeout> | null = null;
let entryIds: Array<string | null> = [];
let currentIdx = 0;
let origPushState: PopStateWindowLike["history"]["pushState"] | null = null;
let origReplaceState: PopStateWindowLike["history"]["replaceState"] | null = null;
const clearRevertState = () => {
isReverting = false;
revertingTargetId = null;
revertStepsRemaining = 0;
if (revertResetTimer !== null) {
clearTimeout(revertResetTimer);
revertResetTimer = null;
}
};
const armRevertTimer = () => {
if (revertResetTimer !== null) {
clearTimeout(revertResetTimer);
}
revertResetTimer = setTimeout(() => {
clearRevertState();
}, REVERT_TIMEOUT_MS);
};
const revertToSavedEntry = (savedId: string | null, returnDelta: number) => {
isReverting = true;
revertingTargetId = savedId;
revertStepDirection = returnDelta >= 0 ? 1 : -1;
revertStepsRemaining = MAX_REVERT_STEPS;
armRevertTimer();
win.history.go(returnDelta);
};
const resolveTargetIndex = (state: unknown): number => {
const targetId = readHistoryStateId(state);
if (!targetId) {
return -1;
}
return entryIds.indexOf(targetId);
};
const handleRevertPopState = (event: PopStateEvent) => {
event.stopImmediatePropagation();
const landedId = readHistoryStateId(event.state);
if (revertingTargetId !== null && landedId !== revertingTargetId && revertStepsRemaining > 0) {
revertStepsRemaining -= 1;
armRevertTimer();
win.history.go(revertStepDirection);
return;
}
const landedIdx = resolveTargetIndex(event.state);
if (landedIdx >= 0) {
currentIdx = landedIdx;
}
clearRevertState();
};
const handlePopState = (event: PopStateEvent) => {
if (isReverting) {
handleRevertPopState(event);
return;
}
const targetIdx = resolveTargetIndex(event.state);
if (isReplaying) {
isReplaying = false;
if (targetIdx >= 0) {
currentIdx = targetIdx;
}
return;
}
const guard = activeGuard;
if (!guard?.isDirty()) {
if (targetIdx >= 0) {
currentIdx = targetIdx;
}
return;
}
event.stopImmediatePropagation();
const savedId = entryIds[currentIdx] ?? null;
const returnDelta = targetIdx >= 0 ? currentIdx - targetIdx : 1;
if (confirmInFlight) {
if (returnDelta !== 0) {
revertToSavedEntry(savedId, returnDelta);
}
return;
}
confirmInFlight = true;
const confirmAndResolve = async () => {
try {
const confirmed = await guard.confirmDiscard();
if (confirmed) {
isReplaying = true;
win.dispatchEvent(createPopStateEvent(event.state));
} else if (returnDelta !== 0) {
revertToSavedEntry(savedId, returnDelta);
}
} finally {
confirmInFlight = false;
}
};
void confirmAndResolve();
};
return {
install() {
if (installed) {
return;
}
installed = true;
const initialId = readHistoryStateId(win.history.state);
const stored = loadStoredEntryIds(win.sessionStorage);
const storedIdx = stored && initialId ? stored.indexOf(initialId) : -1;
if (stored && storedIdx >= 0) {
entryIds = stored;
currentIdx = storedIdx;
} else {
entryIds = [initialId];
currentIdx = 0;
persistEntryIds(win.sessionStorage, entryIds);
}
origPushState = win.history.pushState;
origReplaceState = win.history.replaceState;
win.history.pushState = (data, unused, url) => {
origPushState?.call(win.history, data, unused, url);
entryIds = entryIds.slice(0, currentIdx + 1);
entryIds.push(readHistoryStateId(data));
currentIdx = entryIds.length - 1;
persistEntryIds(win.sessionStorage, entryIds);
};
win.history.replaceState = (data, unused, url) => {
origReplaceState?.call(win.history, data, unused, url);
entryIds[currentIdx] = readHistoryStateId(data);
persistEntryIds(win.sessionStorage, entryIds);
};
win.addEventListener("popstate", handlePopState);
},
register(guard) {
activeGuard = guard;
return () => {
if (activeGuard === guard) {
activeGuard = null;
}
};
},
dispose() {
if (!installed) {
return;
}
installed = false;
activeGuard = null;
confirmInFlight = false;
isReplaying = false;
clearRevertState();
win.removeEventListener("popstate", handlePopState);
if (origPushState) {
win.history.pushState = origPushState;
origPushState = null;
}
if (origReplaceState) {
win.history.replaceState = origReplaceState;
origReplaceState = null;
}
},
};
}
let sharedController: WebPopStateGuardController | null = null;
function getSharedController(): WebPopStateGuardController | null {
if (typeof window === "undefined") {
return null;
}
if (!sharedController) {
sharedController = createWebPopStateGuard(window);
}
return sharedController;
}
export function installRouteLeavePopStateGuard(): void {
getSharedController()?.install();
}
export function registerRouteLeaveGuard(guard: RouteLeaveGuard | null): () => void {
const controller = getSharedController();
if (!controller) {
return () => {};
}
controller.install();
return controller.register(guard);
}
@@ -10,6 +10,7 @@ import { HeaderToggleButton } from "@/components/headers/header-toggle-button";
import { CompactHeader } from "@/components/headers/compact-header";
import { ScreenHeader } from "@/components/headers/screen-header";
import { ScreenTitle } from "@/components/headers/screen-title";
import { SidebarMenuToggle } from "@/components/headers/sidebar-menu-toggle";
import { HostFilter } from "@/components/hosts/host-filter";
import type { HostPickerHost } from "@/components/hosts/host-picker";
import { LoadingSpinner } from "@/components/ui/loading-spinner";
@@ -199,6 +200,7 @@ export function PluginSurfaceScreen() {
const headerLeft = useMemo(
() => (
<>
<SidebarMenuToggle />
{icon ? (
<HeaderIconBadge>
<ThemedPluginHeaderIcon icon={icon} uniProps={mutedColorMapping} />
@@ -197,7 +197,7 @@ describe("plugin timeline projection", () => {
kind: "assistant_message",
id: "assistant-1",
messageId: "provider-msg-1",
timelineCursor: { epoch: "e1", seq: 7 },
timelineCursor: { epoch: "e1", seq: 7, anchorSeq: 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 },
timelineCursor: { epoch: "e1", seq: 7, anchorSeq: 7 },
turnId: "turn-1",
},
{
kind: "plugin",
id: "genui/assistant-1/card",
timelineCursor: { epoch: "e1", seq: 7 },
timelineCursor: { epoch: "e1", seq: 7, anchorSeq: 7 },
turnId: "turn-1",
},
]);
@@ -65,6 +65,7 @@ function sourceTimelineItem(item: StreamItem): AgentTimelineItem | null {
...(item.preTokens !== undefined ? { preTokens: item.preTokens } : {}),
};
case "plugin":
case "provider_switch":
case "turn_summary":
return null;
}
+6
View File
@@ -6,6 +6,7 @@ import { QueryClientProvider } from "@tanstack/react-query";
import { SafeAreaProvider } from "react-native-safe-area-context";
import { queryClient } from "@/data/query-client";
import { I18nProvider } from "@/i18n/provider";
import { installRouteLeavePopStateGuard } from "@/navigation/route-leave-guard";
import { RootErrorBoundary } from "@/components/root-error-boundary";
// Keep Expo's platform filtering, route root, and lazy import configuration.
@@ -22,6 +23,11 @@ export function RootApp() {
}
export function RootRouter({ context: routes }: Pick<ComponentProps<typeof ExpoRoot>, "context">) {
// Attach the web popstate guard before ExpoRoot's effect registers its history listener.
useState(() => {
installRouteLeavePopStateGuard();
return true;
});
const [generation, setGeneration] = useState(0);
const reload = useCallback(() => setGeneration((value) => value + 1), []);
@@ -91,7 +91,7 @@ describe("AgentDirectoryReplica", () => {
id: "reply",
text: "server history",
timestamp: new Date(),
timelineCursor: { epoch: "e", seq: 1 },
timelineCursor: { epoch: "e", seq: 1, anchorSeq: 1 },
},
],
head: [],
+35 -6
View File
@@ -83,8 +83,10 @@ import {
} from "@/desktop/browser/automation/handler";
import { schedulesQueryBaseKey } from "@/schedules/aggregated-schedules";
import { dispatchComposerAgentMessage, sendQueuedComposerMessageNow } from "@/composer/actions";
import { clearStagedProviderSwitch, getStagedProviderSwitch } 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";
@@ -255,6 +257,7 @@ 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;
@@ -2902,8 +2905,16 @@ export class HostRuntimeStore {
write: (update) => useSessionStore.getState().setQueuedMessages(serverId, update),
},
submitMessage: async ({ text, attachments }) => {
const supportsForgeAttachments =
useSessionStore.getState().sessions[serverId]?.serverInfo?.features?.forgeSearch === true;
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;
await dispatchComposerAgentMessage({
client,
agentId,
@@ -2914,6 +2925,13 @@ export class HostRuntimeStore {
}),
encodeImages,
submission: createMessageSubmissionWriter(serverId),
stagedProviderSwitch,
onProviderSwitchCommitted: (agent) => {
clearStagedProviderSwitch(serverId, agentId);
if (agent) {
this.tryAcceptAgentSnapshot(serverId, normalizeAgentSnapshot(agent, 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
@@ -2959,6 +2977,10 @@ 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);
}
@@ -3128,12 +3150,19 @@ 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;
const page = await directory.fetchTimeline(agentId, request);
if (owner && useSessionStore.getState().sessions[serverId]?.viewedTimelineSync === owner) {
// 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;
}
owner.flushStreamAgent(agentId);
owner.applyTimelineResponse(page);
if (owner.applyTimelineResponse(page) === "applied") return page;
if (attempt === MAX_STALE_TIMELINE_PAGE_ATTEMPTS) {
throw new Error(`Timeline page for ${agentId} stayed behind a rewind`);
}
}
return page;
}
createViewedTimelineOwner(
@@ -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 },
timelineCursor: { epoch: "epoch-1", seq: 12, anchorSeq: 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 },
timelineCursor: { epoch: "epoch-1", seq: 12, anchorSeq: 12 },
};
writer.commitTimeline(SERVER_ID, "agent-1", {
agentId: "agent-1",
@@ -885,6 +885,32 @@ 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);
@@ -1355,7 +1381,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 },
timelineCursor: { epoch: "epoch-1", seq: 12, anchorSeq: 12 },
payload: {
source: "agent",
data: {
@@ -22,6 +22,7 @@ import {
isUnreconciledLocalUserMessage,
type AgentToolCallData,
type StreamItem,
type TimelinePosition,
} from "@/types/stream";
import type { UnsettledTurn } from "@/timeline/turn-liveness";
import { normalizeAgentSnapshot } from "@/utils/agent-snapshots";
@@ -82,7 +83,15 @@ 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.14.1, remove after 2027-05-10. 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(),
@@ -161,6 +170,23 @@ 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"),
@@ -362,6 +388,7 @@ 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(),
@@ -423,6 +450,10 @@ 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),
@@ -469,6 +500,23 @@ function serializeAgentToolCall(data: AgentToolCallData): StoredToolCall {
}
}
function serializeProviderSwitchItem(
base: ReturnType<typeof timelineBase>,
item: Extract<StreamItem, { kind: "provider_switch" }>,
): StoredTimelineItem {
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) {
@@ -514,6 +562,8 @@ 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 {
@@ -539,11 +589,20 @@ 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,
...(item.timelineCursor ? { timelineCursor: item.timelineCursor } : {}),
...anchoredPosition(item.timelineCursor),
...(item.turnId ? { turnId: item.turnId } : {}),
timestamp: new Date(item.timestamp),
kind: item.kind,
@@ -557,12 +616,29 @@ 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,
...(item.timelineCursor ? { timelineCursor: item.timelineCursor } : {}),
...anchoredPosition(item.timelineCursor),
...(item.turnId ? { turnId: item.turnId } : {}),
timestamp: new Date(item.timestamp),
};
@@ -609,6 +685,8 @@ 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") {
@@ -840,7 +918,14 @@ function serializeTimeline(timeline: CachedTimeline): StoredTimeline | null {
agentId: timeline.agentId,
items,
range: canPersistCoverage
? { epoch: range.epoch, startSeq: range.startSeq, endSeq: range.endSeq }
? {
epoch: range.epoch,
startSeq: range.startSeq,
endSeq: range.endSeq,
...(range.activeSegmentStartSeq !== undefined
? { activeSegmentStartSeq: range.activeSegmentStartSeq }
: {}),
}
: null,
hasOlder: canPersistCoverage ? timeline.hasOlder : false,
...(timeline.unsettledTurn
+225 -85
View File
@@ -1,12 +1,13 @@
import { useSettingsContentPresented } from "@/navigation/settings-presentation";
import { registerRouteLeaveGuard } from "@/navigation/route-leave-guard";
import { AppearanceText as Text } from "@/appearance/text";
import { useHardwareKeyboardPresent } from "@/keyboard";
import { useAddHost } from "@/hosts/add-host";
import { useCallback, useMemo, useRef, useState } from "react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import type { ComponentType, ReactNode } from "react";
import { Alert, Pressable, ScrollView, View, type PressableStateCallbackType } from "react-native";
import { useRouter } from "expo-router";
import { useFocusEffect } from "expo-router/react-navigation";
import { useNavigation, useRouter } from "expo-router";
import { useFocusEffect, usePreventRemove } from "expo-router/react-navigation";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { StyleSheet, useUnistyles } from "react-native-unistyles";
import { useTranslation } from "react-i18next";
@@ -40,6 +41,7 @@ import {
PanelLeft,
MessageSquare,
ChevronRight,
Layers,
} from "lucide-react-native";
import { DropdownTrigger } from "@/components/ui/dropdown-trigger";
import { ComboboxTrigger } from "@/components/ui/combobox-trigger";
@@ -102,6 +104,7 @@ import {
HostConnectionsPage,
HostPairDevicePage,
HostAgentsPage,
HostAgentProfilesPage,
HostSettingsPage,
HostProvidersPage,
HostUsagePage,
@@ -249,6 +252,7 @@ const HOST_SECTION_ITEMS: HostSectionItem[] = [
{ id: "connections", labelKey: "settings.hostSections.connections", icon: Network },
{ id: "pair-device", labelKey: "openProject.tiles.pairDevice.title", icon: Smartphone },
{ id: "agents", labelKey: "settings.hostSections.agents", icon: Bot },
{ id: "agent-profiles", labelKey: "settings.hostSections.agentProfiles", icon: Layers },
{ id: "metadata", labelKey: "settings.hostSections.metadata", icon: Sparkles },
{ id: "voice", labelKey: "settings.hostSections.voice", icon: Mic },
{ id: "workspaces", labelKey: "settings.hostSections.workspaces", icon: FolderGit2 },
@@ -271,6 +275,9 @@ function renderHostSettingsContent(
return <HostPairDevicePage serverId={view.serverId} />;
case "agents":
return <HostAgentsPage serverId={view.serverId} />;
case "agent-profiles":
// Rendered directly in SettingsScreen so AgentProfilesPage owns its wide PageLayout + drawer split.
return null;
case "metadata":
return <MetadataGenerationPage serverId={view.serverId} />;
case "voice":
@@ -1104,6 +1111,139 @@ function SettingsSidebar({
);
}
interface SettingsBeforeLeaveGuard {
isDirty: () => boolean;
confirmDiscard: () => Promise<boolean>;
subscribeDirty?: (listener: () => void) => () => void;
}
/**
* Lets an active Settings editor (such as Agent profiles) veto both in-app
* section switches and route-boundary exits (browser Back, native swipe-back,
* hardware Back) with a single discard confirmation.
*
* Uses `usePreventRemove` so native stacks set `preventNativeDismiss` before
* iOS can interactively dismiss the screen on a back swipe.
*/
function useSettingsBeforeLeaveGuard() {
const navigation = useNavigation();
const beforeLeaveRef = useRef<SettingsBeforeLeaveGuard | null>(null);
const dirtyUnsubRef = useRef<(() => void) | null>(null);
const [preventRemove, setPreventRemove] = useState(false);
const registerBeforeLeave = useCallback((guard: SettingsBeforeLeaveGuard | null) => {
dirtyUnsubRef.current?.();
dirtyUnsubRef.current = null;
beforeLeaveRef.current = guard;
const syncDirty = () => {
setPreventRemove(Boolean(beforeLeaveRef.current?.isDirty()));
};
syncDirty();
if (guard?.subscribeDirty) {
dirtyUnsubRef.current = guard.subscribeDirty(syncDirty);
}
}, []);
useEffect(() => {
return () => {
dirtyUnsubRef.current?.();
dirtyUnsubRef.current = null;
};
}, []);
useEffect(() => {
return registerRouteLeaveGuard({
isDirty: () => Boolean(beforeLeaveRef.current?.isDirty()),
confirmDiscard: async () => (await beforeLeaveRef.current?.confirmDiscard()) ?? true,
});
}, []);
usePreventRemove(preventRemove, ({ data }) => {
const guard = beforeLeaveRef.current;
if (!guard?.isDirty()) {
navigation.dispatch(data.action);
return;
}
const confirmAndLeave = async () => {
if (await guard.confirmDiscard()) {
navigation.dispatch(data.action);
}
};
void confirmAndLeave();
});
const guardNavigation = useCallback((navigate: () => void) => {
const guard = beforeLeaveRef.current;
if (!guard?.isDirty()) {
navigate();
return;
}
const run = async () => {
if (await guard.confirmDiscard()) {
navigate();
}
};
void run();
}, []);
return { registerBeforeLeave, guardNavigation };
}
function SettingsDetailPane({
view,
isCompactLayout,
detailTitle,
detailActions,
detailWidth,
onBack,
onRegisterBeforeLeave,
content,
}: {
view: SettingsView;
isCompactLayout: boolean;
detailTitle: string | undefined;
detailActions: React.ReactNode;
detailWidth: React.ComponentProps<typeof PageLayout>["width"];
onBack: () => void;
onRegisterBeforeLeave: (guard: SettingsBeforeLeaveGuard | null) => void;
content: React.ReactNode;
}) {
const isStandaloneAgentProfilesView = view.kind === "host" && view.section === "agent-profiles";
const pageTitle =
!isCompactLayout && (view.kind === "project" || view.kind === "provider")
? undefined
: detailTitle;
return (
<WindowChromeRegion corners={isCompactLayout ? "both" : "top-right"}>
<View
style={isCompactLayout ? desktopStyles.compactContentPane : desktopStyles.contentPane}
testID={isCompactLayout ? undefined : "settings-detail-pane"}
>
{isStandaloneAgentProfilesView ? (
<HostAgentProfilesPage
serverId={view.serverId}
onBack={isCompactLayout ? onBack : undefined}
onRegisterBeforeLeave={onRegisterBeforeLeave}
/>
) : (
<PageLayout
// A project or provider page draws its own title on desktop, naming the list it came from.
title={pageTitle}
onBack={isCompactLayout ? onBack : undefined}
actions={detailActions}
width={detailWidth}
titleTestID={isCompactLayout ? undefined : "settings-detail-header-title"}
testID={isCompactLayout ? undefined : "settings-detail-scroll-body"}
>
{content}
</PageLayout>
)}
</View>
</WindowChromeRegion>
);
}
// ---------------------------------------------------------------------------
// Main screen
// ---------------------------------------------------------------------------
@@ -1201,10 +1341,10 @@ export default function SettingsScreen({ view }: SettingsScreenProps) {
);
const handleAddHost = useAddHost({ onAdded: handleHostAdded });
const { registerBeforeLeave, guardNavigation } = useSettingsBeforeLeaveGuard();
const handleSelectSection = useCallback(
(section: SettingsSectionSlug) => {
const target = buildSettingsSectionRoute(section);
const navigateRoute = useCallback(
(target: Parameters<typeof router.push>[0]) => {
if (isCompactLayout) {
router.push(target);
} else {
@@ -1214,51 +1354,62 @@ export default function SettingsScreen({ view }: SettingsScreenProps) {
[isCompactLayout, router],
);
const handleSelectSection = useCallback(
(section: SettingsSectionSlug) => {
if (view.kind === "section" && view.section === section) {
return;
}
const target = buildSettingsSectionRoute(section);
guardNavigation(() => navigateRoute(target));
},
[guardNavigation, navigateRoute, view],
);
// Picker: choose the host for host-section rows. If the user is already on a
// host detail route, keep that detail section and swap only the host segment.
const handleSelectHost = useCallback(
(serverId: string) => {
selectSettingsHost(serverId);
if (view.kind === "project" || view.kind === "provider") {
// The detail belongs to the old host; open the same list on the new one.
const target = buildSettingsHostSectionRoute(
serverId,
view.kind === "project" ? "projects" : "providers",
);
if (isCompactLayout) {
router.push(target);
} else {
router.replace(target);
if (view.kind === "host" && view.serverId === serverId) {
return;
}
const applySelection = () => {
selectSettingsHost(serverId);
if (view.kind === "project" || view.kind === "provider") {
// The detail belongs to the old host; open the same list on the new one.
navigateRoute(
buildSettingsHostSectionRoute(
serverId,
view.kind === "project" ? "projects" : "providers",
),
);
return;
}
return;
}
if (view.kind !== "host") {
return;
}
const target = buildSettingsHostSectionRoute(serverId, view.section);
if (isCompactLayout) {
router.push(target);
} else {
router.replace(target);
}
if (view.kind === "host") {
navigateRoute(buildSettingsHostSectionRoute(serverId, view.section));
}
};
guardNavigation(applySelection);
},
[isCompactLayout, router, view],
[guardNavigation, navigateRoute, view],
);
const handleSelectHostSection = useCallback(
(section: HostSectionSlug) => {
if (!activeHostServerId) {
handleAddHost();
guardNavigation(handleAddHost);
return;
}
if (
view.kind === "host" &&
view.serverId === activeHostServerId &&
view.section === section
) {
return;
}
const target = buildSettingsHostSectionRoute(activeHostServerId, section);
if (isCompactLayout) {
router.push(target);
} else {
router.replace(target);
}
guardNavigation(() => navigateRoute(target));
},
[activeHostServerId, handleAddHost, isCompactLayout, router],
[activeHostServerId, guardNavigation, handleAddHost, navigateRoute, view],
);
const handleHostRemoved = useCallback(() => {
@@ -1271,12 +1422,12 @@ export default function SettingsScreen({ view }: SettingsScreenProps) {
}, [isCompactLayout, router]);
const handleBackFromDetail = useCallback(() => {
returnFromSettings(view);
}, [view]);
guardNavigation(() => returnFromSettings(view));
}, [guardNavigation, view]);
const handleBackToWorkspace = useCallback(() => {
returnFromSettings({ kind: "root" });
}, []);
guardNavigation(() => returnFromSettings({ kind: "root" }));
}, [guardNavigation]);
// A plugin's page draws its own header; the compact back header names the plugin.
const pluginPage = useMemo((): { serverId: string; subject: PluginPageSubject } | null => {
@@ -1412,53 +1563,36 @@ export default function SettingsScreen({ view }: SettingsScreenProps) {
);
}
if (isCompactLayout) {
return (
<View style={styles.container} onLayout={onContentLayout}>
<PageLayout
title={detailTitle}
onBack={handleBackFromDetail}
actions={detailActions}
width={detailWidth}
>
{content}
</PageLayout>
</View>
);
}
// Desktop split view — mirrors AppContainer: sidebar owns the titlebar drag
// region + traffic-light padding; detail pane renders whatever header the
// selected section provides.
// Desktop split view and compact detail view share one wrapper tree around the
// detail pane so resizing across the compact breakpoint never unmounts active
// detail screens or discards in-progress edits (e.g., Agent profiles drawer → sheet).
return (
<View style={styles.container} onLayout={onContentLayout}>
<View style={desktopStyles.row}>
<WindowChromeRegion corners="top-left">
<SettingsSidebar
view={view}
onSelectSection={handleSelectSection}
onSelectHostSection={handleSelectHostSection}
onSelectHost={handleSelectHost}
onAddHost={handleAddHost}
onBackToWorkspace={handleBackToWorkspace}
activeHostServerId={activeHostServerId}
layout="desktop"
/>
</WindowChromeRegion>
<WindowChromeRegion corners="top-right">
<View style={desktopStyles.contentPane} testID="settings-detail-pane">
<PageLayout
// A project or provider page draws its own title, which names the list it came from.
title={view.kind === "project" || view.kind === "provider" ? undefined : detailTitle}
actions={detailActions}
width={detailWidth}
titleTestID="settings-detail-header-title"
testID="settings-detail-scroll-body"
>
{content}
</PageLayout>
</View>
</WindowChromeRegion>
{isCompactLayout ? null : (
<WindowChromeRegion corners="top-left">
<SettingsSidebar
view={view}
onSelectSection={handleSelectSection}
onSelectHostSection={handleSelectHostSection}
onSelectHost={handleSelectHost}
onAddHost={handleAddHost}
onBackToWorkspace={handleBackToWorkspace}
activeHostServerId={activeHostServerId}
layout="desktop"
/>
</WindowChromeRegion>
)}
<SettingsDetailPane
view={view}
isCompactLayout={isCompactLayout}
detailTitle={detailTitle}
detailActions={detailActions}
detailWidth={detailWidth}
onBack={handleBackFromDetail}
onRegisterBeforeLeave={registerBeforeLeave}
content={content}
/>
</View>
</View>
);
@@ -1527,6 +1661,10 @@ const desktopStyles = StyleSheet.create({
flex: 1,
minWidth: SETTINGS_DESKTOP_DETAIL_MIN_WIDTH,
},
compactContentPane: {
flex: 1,
minWidth: 0,
},
});
const sidebarStyles = StyleSheet.create((theme) => ({
@@ -1548,8 +1686,10 @@ const sidebarStyles = StyleSheet.create((theme) => ({
paddingHorizontal: theme.spacing[2],
},
// Compact values draw each group as an island of tiles; desktop keeps a plain list.
// Use vertical margin rather than padding so trailing empty group padding cannot
// intersect the scrollport top alone and capture browser scroll anchoring.
group: {
paddingVertical: theme.spacing[2],
marginVertical: theme.spacing[2],
paddingHorizontal: theme.spacing[2],
gap: { xs: theme.spacing[1], md: theme.spacing[0.5] },
},
@@ -21,9 +21,10 @@ import {
getTerminalProfileIcon,
DEFAULT_TERMINAL_PROFILES,
} from "@getpaseo/protocol/terminal-profiles";
import { AgentProfilesSection } from "@/agent-profiles";
import { AgentProfilesPage, type AgentProfilesBeforeLeaveGuard } from "@/agent-profiles";
import { AgentSkillsSection } from "@/agent-skills";
import { AdaptiveModalSheet, type SheetHeader } from "@/components/adaptive-modal-sheet";
import { PageLayout } from "@/components/page-layout";
import { SettingsTextAreaCard } from "@/components/settings-textarea";
import { Alert as InlineAlert } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
@@ -304,11 +305,43 @@ export function HostAgentsPage({ serverId }: { serverId: string }) {
</View>
)}
<AgentSkillsSection serverId={serverId} />
<AgentProfilesSection serverId={serverId} />
</View>
);
}
export function HostAgentProfilesPage({
serverId,
onBack,
onRegisterBeforeLeave,
}: {
serverId: string;
onBack?: () => void;
onRegisterBeforeLeave?: (guard: AgentProfilesBeforeLeaveGuard | null) => void;
}) {
const { t } = useTranslation();
const host = useHostProfile(serverId);
if (!host) {
return (
<PageLayout
title={t("settings.host.agentProfiles.sectionTitle")}
onBack={onBack}
titleTestID="settings-detail-header-title"
>
<HostNotFound />
</PageLayout>
);
}
return (
<AgentProfilesPage
serverId={serverId}
onBack={onBack}
onRegisterBeforeLeave={onRegisterBeforeLeave}
/>
);
}
export function HostWorkspacesPage({ serverId }: { serverId: string }) {
const { t } = useTranslation();
const host = useHostProfile(serverId);
@@ -2188,11 +2188,10 @@ function WorkspaceScreenContent({
toast.show(t("workspace.tabs.toasts.reloadingAgent"), { durationMs: null });
try {
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 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.
const sessionState = useSessionStore.getState().sessions[normalizedServerId];
const currentCursor = sessionState?.agentTimelineCursor.get(agentId);
await getHostRuntimeStore().fetchAgentTimeline(normalizedServerId, agentId, {
@@ -2201,7 +2200,13 @@ function WorkspaceScreenContent({
? { cursor: { epoch: currentCursor.epoch, seq: currentCursor.endSeq } }
: {}),
});
toast.show(t("workspace.tabs.toasts.reloadedAgent"), { variant: "success" });
if (refreshed.historyDiverged) {
toast.show(t("workspace.tabs.toasts.reloadedAgentHistoryDiverged"), {
variant: "warning",
});
} else {
toast.show(t("workspace.tabs.toasts.reloadedAgent"), { variant: "success" });
}
} catch (error) {
toast.error(
error instanceof Error ? error.message : t("workspace.tabs.toasts.failedToReloadAgent"),
+33
View File
@@ -317,6 +317,7 @@ export interface AgentTimelineCursorState {
epoch: string;
startSeq: number;
endSeq: number;
activeSegmentStartSeq?: number;
retainedRanges?: Array<{
startSeq: number;
endSeq: number;
@@ -324,6 +325,12 @@ 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[] }
@@ -498,6 +505,7 @@ 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>;
@@ -617,6 +625,12 @@ 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>),
@@ -753,6 +767,7 @@ function createInitialSessionState(
agentTimelineUnsettledTurn: new Map(),
agentTimelineHasOlder: new Map(),
agentTimelineHasNewer: new Map(),
agentTimelineLatestRewind: new Map(),
agentTimelineOlderFetchInFlight: new Map(),
historySyncGeneration: 0,
agentHistorySyncGeneration: new Map(),
@@ -1401,6 +1416,24 @@ 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];
+230 -1
View File
@@ -39,7 +39,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 },
timelineCursor: { epoch: "epoch-1", seq, anchorSeq: seq },
};
}
@@ -579,6 +579,235 @@ 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 },
timelineCursor: { epoch: "epoch-1", seq: 1, anchorSeq: 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 },
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 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 },
timelineCursor: { epoch: "epoch-1", seq: 40, anchorSeq: 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 },
timelineCursor: { epoch: "epoch-1", seq: 235, anchorSeq: 235 },
};
const newerLive: StreamItem = {
...makeAssistantItem("newer live", "newer-live"),
timelineCursor: { epoch: "epoch-1", seq: 245 },
timelineCursor: { epoch: "epoch-1", seq: 245, anchorSeq: 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 },
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 40 },
}),
]);
});
@@ -745,7 +745,7 @@ describe("processTimelineResponse", () => {
}).item,
} as AgentStreamEventPayload,
timestamp: new Date(2000),
timelineCursor: { epoch: "epoch-1", seq: 2 },
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 2 },
},
],
{ source: "canonical" },
@@ -775,7 +775,7 @@ describe("processTimelineResponse", () => {
expect(getAgentToolCalls([...result.tail, ...result.head])).toEqual([
expect.objectContaining({
timelineCursor: { epoch: "epoch-1", seq: 2 },
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 1 },
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 },
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 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 },
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 1 },
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 },
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 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 },
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 1 },
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 },
timelineCursor: { epoch: "epoch-1", seq: 101, anchorSeq: 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 });
expect(assistants[0]?.timelineCursor).toEqual({ epoch: "epoch-1", seq: 101, anchorSeq: 100 });
});
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 },
timelineCursor: { epoch: "epoch-1", seq: 101, anchorSeq: 101 },
},
{
event: makeAssistantTimelineEvent("after tool", messageId),
timestamp: new Date(2102),
timelineCursor: { epoch: "epoch-1", seq: 102 },
timelineCursor: { epoch: "epoch-1", seq: 102, anchorSeq: 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 },
timelineCursor: { epoch: "epoch-1", seq: 101, anchorSeq: 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 });
expect(assistants[0]?.timelineCursor).toEqual({ epoch: "epoch-1", seq: 101, anchorSeq: 100 });
});
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 },
timelineCursor: { epoch: "epoch-1", seq: 101, anchorSeq: 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 },
timelineCursor: { epoch: "epoch-1", seq: 51, anchorSeq: 51 },
});
});
@@ -2808,7 +2808,7 @@ describe("processTimelineResponse", () => {
id: "newest",
text: "newest",
timestamp: new Date(1000),
timelineCursor: { epoch: "epoch-1", seq: 100 },
timelineCursor: { epoch: "epoch-1", seq: 100, anchorSeq: 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 },
timelineCursor: { epoch: "epoch-1", seq: 1, anchorSeq: 1 },
},
{
kind: "user_message",
id: "newest",
text: "newest",
timestamp: new Date(100_000),
timelineCursor: { epoch: "epoch-1", seq: 100 },
timelineCursor: { epoch: "epoch-1", seq: 100, anchorSeq: 100 },
},
];
@@ -2935,7 +2935,7 @@ describe("processTimelineResponse", () => {
id: "newest",
text: "newest",
timestamp: new Date(100_000),
timelineCursor: { epoch: "epoch-1", seq: 100 },
timelineCursor: { epoch: "epoch-1", seq: 100, anchorSeq: 100 },
},
...(lane === "tail" ? [pending] : []),
],
@@ -2976,9 +2976,13 @@ describe("processTimelineResponse", () => {
{
text: "local pending prompt",
messageId: "canonical-message",
timelineCursor: { epoch: "epoch-1", seq: 1 },
timelineCursor: { epoch: "epoch-1", seq: 1, anchorSeq: 1 },
},
{
text: "newest",
messageId: undefined,
timelineCursor: { epoch: "epoch-1", seq: 100, anchorSeq: 100 },
},
{ text: "newest", messageId: undefined, timelineCursor: { epoch: "epoch-1", seq: 100 } },
],
head: [],
acknowledgedClientMessageIds: [clientMessageId],
@@ -2992,7 +2996,7 @@ describe("processTimelineResponse", () => {
{
event: makeToolCallTimelineEvent("call-1"),
timestamp: new Date(500),
timelineCursor: { epoch: "epoch-1", seq: 500 },
timelineCursor: { epoch: "epoch-1", seq: 500, anchorSeq: 500 },
},
],
{ source: "canonical" },
@@ -3038,7 +3042,7 @@ describe("processTimelineResponse", () => {
{
callId: "call-1",
status: "completed",
timelineCursor: { epoch: "epoch-1", seq: 500 },
timelineCursor: { epoch: "epoch-1", seq: 500, anchorSeq: 1 },
},
]);
});
@@ -3050,7 +3054,7 @@ describe("processTimelineResponse", () => {
...makeAssistantItem("projected response", "loaded-assistant"),
messageId: "assistant-message",
timestamp,
timelineCursor: { epoch: "epoch-1", seq: 500 },
timelineCursor: { epoch: "epoch-1", seq: 500, anchorSeq: 500 },
},
];
const result = processTimelineResponse({
@@ -3100,7 +3104,7 @@ describe("processTimelineResponse", () => {
id: "loaded-assistant",
text: "projected response",
messageId: "assistant-message",
timelineCursor: { epoch: "epoch-1", seq: 500 },
timelineCursor: { epoch: "epoch-1", seq: 500, anchorSeq: 1 },
},
]);
});
@@ -3112,7 +3116,7 @@ describe("processTimelineResponse", () => {
id: "current-200",
text: "current-200",
timestamp: new Date(3200),
timelineCursor: { epoch: "epoch-1", seq: 200 },
timelineCursor: { epoch: "epoch-1", seq: 200, anchorSeq: 200 },
},
];
const existingCursor: TimelineCursor = {
@@ -3219,7 +3223,7 @@ describe("processTimelineResponse", () => {
const currentTail = [
{
...makeAssistantItem("newer chunk", "assistant-newer"),
timelineCursor: { epoch: "epoch-1", seq: 3 },
timelineCursor: { epoch: "epoch-1", seq: 3, anchorSeq: 3 },
},
];
const existingCursor: TimelineCursor = {
@@ -3246,7 +3250,7 @@ describe("processTimelineResponse", () => {
expect(result.tail[0]).toEqual(
expect.objectContaining({
id: "assistant-newer",
timelineCursor: { epoch: "epoch-1", seq: 3 },
timelineCursor: { epoch: "epoch-1", seq: 3, anchorSeq: 3 },
}),
);
expect(result.cursor).toEqual({
@@ -3686,7 +3690,7 @@ describe("processAgentStreamEvent", () => {
expect.objectContaining({
kind: "assistant_message",
text: "[System Error] failed",
timelineCursor: { epoch: "timeline-1", seq: 42 },
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 42 },
}),
]);
});
@@ -3933,7 +3937,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 },
timelineCursor: { epoch: "epoch-1", seq: 51, anchorSeq: 51 },
});
expect(result.cursorChanged).toBe(false);
expect(result.cursor).toBeNull();
@@ -3968,7 +3972,7 @@ describe("processAgentStreamEvent", () => {
clientMessageId: "client-message-1",
messageId: "provider-message-1",
text: "submitted before bootstrap",
timelineCursor: { epoch: "epoch-1", seq: 51 },
timelineCursor: { epoch: "epoch-1", seq: 51, anchorSeq: 51 },
}),
]);
});
@@ -4559,6 +4563,279 @@ 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" },
@@ -4816,4 +5093,30 @@ 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,7 +1,13 @@
import type { AgentMetric, AgentTimelineItem } from "@getpaseo/protocol/agent-types";
import type { AgentStreamEventPayload } from "@getpaseo/protocol/messages";
import { selectAgentTimelineState, useSessionStore } from "@/stores/session-store";
import type { AssistantMessageItem, StreamItem, TodoEntry } from "@/types/stream";
import {
advanceTimelinePosition,
type AssistantMessageItem,
type StreamItem,
type TimelinePosition,
type TodoEntry,
} from "@/types/stream";
import type { TurnLivenessTransition } from "@/timeline/turn-liveness";
import { stampTimelineTurnMetrics } from "@/timeline/turn-metrics";
import {
@@ -34,6 +40,7 @@ export interface TimelineCursor {
epoch: string;
startSeq: number;
endSeq: number;
activeSegmentStartSeq?: number;
retainedRanges?: TimelineLoadedRange[];
}
@@ -72,6 +79,64 @@ 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,
@@ -100,6 +165,9 @@ function mergeTimelineCoverage(
epoch: current.epoch,
startSeq: contiguous.startSeq,
endSeq: contiguous.endSeq,
...(current.activeSegmentStartSeq !== undefined
? { activeSegmentStartSeq: current.activeSegmentStartSeq }
: {}),
...(retainedRanges.length > 0 ? { retainedRanges } : {}),
};
}
@@ -108,7 +176,8 @@ function timelineCursorEquals(left: TimelineCursor, right: TimelineCursor): bool
if (
left.epoch !== right.epoch ||
left.startSeq !== right.startSeq ||
left.endSeq !== right.endSeq
left.endSeq !== right.endSeq ||
(left.activeSegmentStartSeq ?? 0) !== (right.activeSegmentStartSeq ?? 0)
) {
return false;
}
@@ -152,6 +221,8 @@ export interface ProcessTimelineResponseInput {
hasNewer: boolean;
hasOlder: boolean;
mergeWindow?: boolean;
retirements?: TimelineRetirement[];
activeSegmentStartSeq?: number;
};
currentTail: StreamItem[];
currentHead: StreamItem[];
@@ -396,7 +467,7 @@ function mergeTimelineWindow(args: {
toHydratedEvents: (units: TimelineUnit[]) => Array<{
event: AgentStreamEventPayload;
timestamp: Date;
timelineCursor: { epoch: string; seq: number };
timelineCursor: TimelinePosition;
}>;
}): TimelinePathResult {
const { timelineUnits, payload, currentTail, currentHead, currentCursor, toHydratedEvents } =
@@ -760,7 +831,7 @@ function replaceLiveAssistantWithProjectedText(params: {
head: StreamItem[];
event: AgentStreamEventPayload;
timestamp: Date;
timelineCursor: { epoch: string; seq: number };
timelineCursor: TimelinePosition;
}): StreamItem[] | null {
const { head, event, timestamp, timelineCursor } = params;
if (event.type !== "timeline" || event.item.type !== "assistant_message") {
@@ -779,7 +850,7 @@ function replaceLiveAssistantWithProjectedText(params: {
...current,
text: event.item.text,
timestamp,
timelineCursor,
...advanceTimelinePosition(current.timelineCursor, timelineCursor),
};
return next;
}
@@ -829,7 +900,7 @@ function reconcileOverlappingProjectedAssistant(params: {
...(messageId !== undefined ? { messageId } : {}),
text: projectedText,
timestamp: unit.timestamp,
timelineCursor: { epoch: params.epoch, seq: unit.seqEnd },
timelineCursor: { epoch: params.epoch, seq: unit.seqEnd, anchorSeq: unit.seq },
};
const replaceMatch = (items: StreamItem[], index: number) => {
const next = [...items];
@@ -946,8 +1017,8 @@ function applyCanonicalForwardUnit(params: {
unit: TimelineUnit;
epoch: string;
}): { tail: StreamItem[]; head: StreamItem[]; acknowledgedClientMessageIds: string[] } {
const { event, timestamp, seqEnd } = params.unit;
const timelineCursor = { epoch: params.epoch, seq: seqEnd };
const { event, timestamp, seq, seqEnd } = params.unit;
const timelineCursor: TimelinePosition = { epoch: params.epoch, seq: seqEnd, anchorSeq: seq };
if (event.type === "timeline" && event.item.type === "user_message") {
const applied = applyStreamEvent({
tail: params.tail,
@@ -1146,10 +1217,10 @@ function applyAcceptedTimelinePage(input: {
});
}
const olderTail = hydrateStreamState(
acceptedUnits.map(({ event, timestamp, seqEnd }) => ({
acceptedUnits.map(({ event, timestamp, seq, seqEnd }) => ({
event,
timestamp,
timelineCursor: { epoch: payload.epoch, seq: seqEnd },
timelineCursor: { epoch: payload.epoch, seq: seqEnd, anchorSeq: seq },
})),
{
source: "canonical",
@@ -1181,7 +1252,12 @@ function applyTimelineIncrementalPath(args: {
let cursorChanged = false;
const sideEffects: TimelineReducerSideEffect[] = [];
if (timelineUnits.length === 0 && payload.direction !== "before") {
// A forward page of retirements alone still advances the loaded end.
if (
timelineUnits.length === 0 &&
payload.direction !== "before" &&
(payload.retirements?.length ?? 0) === 0
) {
return {
tail: currentTail,
head: currentHead,
@@ -1234,13 +1310,62 @@ 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,
@@ -1254,8 +1379,8 @@ export function processTimelineResponse(
if (payload.error) {
return {
commit: "apply",
tail: currentTail,
head: currentHead,
tail: input.currentTail,
head: input.currentHead,
cursor: currentCursor,
cursorChanged: false,
older: "unchanged",
@@ -1267,6 +1392,13 @@ 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
// ------------------------------------------------------------------
@@ -1292,12 +1424,12 @@ export function processTimelineResponse(
): Array<{
event: AgentStreamEventPayload;
timestamp: Date;
timelineCursor: { epoch: string; seq: number };
timelineCursor: TimelinePosition;
}> =>
units.map(({ event, timestamp, seqEnd }) => ({
units.map(({ event, timestamp, seq, seqEnd }) => ({
event,
timestamp,
timelineCursor: { epoch: payload.epoch, seq: seqEnd },
timelineCursor: { epoch: payload.epoch, seq: seqEnd, anchorSeq: seq },
}));
// ------------------------------------------------------------------
@@ -1384,8 +1516,12 @@ export function processTimelineResponse(
const nextTail = stampTimelineTurnMetrics(timelineResult.tail, payload.epoch, pageEntries);
const nextHead = stampTimelineTurnMetrics(timelineResult.head, payload.epoch, pageEntries);
const nextCursor = timelineResult.cursor;
const cursorChanged = timelineResult.cursorChanged;
const { cursor: nextCursor, cursorChanged } = mergeResponseActiveSegmentCursor(
timelineResult.cursor,
timelineResult.cursorChanged,
currentCursor,
payload.activeSegmentStartSeq,
);
sideEffects.push(...timelineResult.sideEffects);
// ------------------------------------------------------------------
@@ -1432,7 +1568,7 @@ export function processTimelineResponse(
// ---------------------------------------------------------------------------
export interface ProcessAgentStreamEventInput {
event: AgentStreamEventPayload;
event: AgentStreamEventPayload | TimelineRewindEvent;
seq: number | undefined;
epoch: string | undefined;
currentTail: StreamItem[];
@@ -1455,7 +1591,7 @@ export interface ProcessAgentStreamEventOutput {
}
export interface AgentStreamReducerEvent {
event: AgentStreamEventPayload;
event: AgentStreamEventPayload | TimelineRewindEvent;
seq: number | undefined;
epoch: string | undefined;
timestamp: Date;
@@ -1573,11 +1709,70 @@ 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,
@@ -1596,7 +1791,7 @@ export function processAgentStreamEvent(
});
const timelineCursor =
event.type === "timeline" && seq !== undefined && epoch !== undefined
? { epoch, seq }
? { epoch, seq, anchorSeq: seq }
: undefined;
// ------------------------------------------------------------------
// Apply stream event to tail/head
@@ -1645,14 +1840,23 @@ 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: sequencing.nextTimelineCursor,
cursorChanged: sequencing.cursorChanged,
cursor: nextTimelineCursor,
cursorChanged,
acknowledgedClientMessageIds: streamResult.acknowledgedClientMessageIds ?? [],
...(sequencing.shouldApplyStreamEvent && event.type === "timeline" && event.item.type === "todo"
? { taskSnapshot: event.item.items }
@@ -1910,6 +2114,10 @@ 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 ||
@@ -237,6 +237,13 @@ 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,
@@ -457,8 +464,14 @@ 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.
*/
export type TimelineResponseOutcome = "applied" | "stale";
export interface ViewedTimelineOwner extends ViewedTimelineSync {
applyTimelineResponse(payload: TimelineResponsePayload): void;
applyTimelineResponse(payload: TimelineResponsePayload): TimelineResponseOutcome;
/**
* 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
@@ -468,6 +481,37 @@ 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;
@@ -477,6 +521,7 @@ export function createViewedTimelineOwner(input: {
ports: ViewedTimelineOwnerPorts;
}): ViewedTimelineOwner {
const forcedTailReplacements = new Set<string>();
const retirements = createRetirementHighWater();
const sync = createViewedTimelineSync({
...input.ports,
fetchLatestTail: async (agentId) => {
@@ -517,6 +562,8 @@ export function createViewedTimelineOwner(input: {
return {
...sync,
applyTimelineResponse(receivedPayload) {
if (retirements.servedBefore(receivedPayload)) return "stale";
retirements.notePage(receivedPayload);
const payload = consumeForcedTimelineTailReplacement(receivedPayload, forcedTailReplacements);
const accepted = applyAuthoritativeTimelineResponse({
serverId: input.serverId,
@@ -526,8 +573,12 @@ export function createViewedTimelineOwner(input: {
drainQueuedAgentMessage: input.drainQueuedAgentMessage,
});
if (accepted) input.replica.timelineUpdated(payload.agentId);
return "applied";
},
applyStreamEvent(agentId, event) {
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;
+7 -3
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 };
const timelineCursor = { epoch: "epoch-1", seq: 42, anchorSeq: 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 },
timelineCursor: { epoch: "epoch-1", seq: 42, anchorSeq: 42 },
},
);
@@ -1902,7 +1902,11 @@ 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 });
assert.deepStrictEqual(userMessage.timelineCursor, {
epoch: "epoch-1",
seq: 42,
anchorSeq: 42,
});
assert.deepStrictEqual(userMessage.images, [image]);
assert.deepStrictEqual(userMessage.attachments, [attachment]);
});
+108 -15
View File
@@ -4,6 +4,7 @@ import type {
AgentProvider,
AgentTimelineItem,
JsonValue,
ProviderSwitchContextSummary,
ToolCallDetail,
} from "@getpaseo/protocol/agent-types";
import { timelineItemIdentity } from "@getpaseo/protocol/timeline-identity";
@@ -89,9 +90,25 @@ export type StreamItem =
| TodoListItem
| NotificationItem
| CompactionItem
| ProviderSwitchItem
| PluginTimelineStreamItem
| TurnSummaryItem;
export interface ProviderSwitchItem {
kind: "provider_switch";
id: 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 type UserMessageImageAttachment = AttachmentMetadata;
export interface UserMessageItem {
@@ -266,7 +283,7 @@ function produceUserMessage(
...presentation,
clientMessageId: incoming.clientMessageId ?? existing.clientMessageId,
messageId: incoming.messageId ?? existing.messageId,
timelineCursor: incoming.timelineCursor ?? existing.timelineCursor,
...advanceTimelinePosition(existing.timelineCursor, incoming.timelineCursor),
});
if (
existing.id === merged.id &&
@@ -482,7 +499,7 @@ function mergeRetainedLifecycleItem(tail: StreamItem[], retained: StreamItem): S
const next = [...tail];
next[tailIndex] = {
...existing,
timelineCursor: retained.timelineCursor,
...advanceTimelinePosition(existing.timelineCursor, retained.timelineCursor),
timestamp: retained.timestamp,
items: retained.items,
};
@@ -499,7 +516,7 @@ function mergeRetainedLifecycleItem(tail: StreamItem[], retained: StreamItem): S
const next = [...tail];
next[tailIndex] = {
...existing,
timelineCursor: retained.timelineCursor,
...advanceTimelinePosition(existing.timelineCursor, retained.timelineCursor),
status: "completed",
trigger: retained.trigger ?? existing.trigger,
preTokens: retained.preTokens ?? existing.preTokens,
@@ -519,7 +536,10 @@ function replaceTimelineIdentityItem(
const existing = items[index];
if (index < 0 || !existing || existing.kind !== "plugin") return null;
const next = [...items];
next[index] = retained;
next[index] = {
...retained,
...advanceTimelinePosition(existing.timelineCursor, retained.timelineCursor),
};
return next;
}
@@ -610,7 +630,11 @@ function preserveReplacementHead(
: `${tailAssistant.text}${liveAssistant.text}`;
const head = [
...unreconciledHead.slice(0, liveAssistantIndex),
{ ...liveAssistant, text },
{
...liveAssistant,
text,
...advanceTimelinePosition(tailAssistant.timelineCursor, liveAssistant.timelineCursor),
},
...unreconciledHead.slice(liveAssistantIndex + 1),
];
return {
@@ -625,7 +649,13 @@ function preserveReplacementHead(
const head = [
...unreconciledHead.slice(0, liveAssistantIndex),
{ ...liveAssistant, text: tailAssistant.text },
{
...liveAssistant,
text: tailAssistant.text,
...(liveAssistant.timelineCursor
? advanceTimelinePosition(tailAssistant.timelineCursor, liveAssistant.timelineCursor)
: {}),
},
...unreconciledHead.slice(liveAssistantIndex + 1),
];
return {
@@ -724,7 +754,27 @@ 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";
@@ -983,7 +1033,7 @@ function appendAssistantMessage(
...last,
text: `${last.text}${chunk}`,
timestamp,
...(timelineCursor ? { timelineCursor } : {}),
...advanceTimelinePosition(last.timelineCursor, timelineCursor),
};
return [...state.slice(0, -1), updated];
}
@@ -1001,7 +1051,7 @@ function appendAssistantMessage(
...secondLast,
text: `${secondLast.text}${chunk}`,
timestamp,
...(timelineCursor ? { timelineCursor } : {}),
...advanceTimelinePosition(secondLast.timelineCursor, timelineCursor),
};
return [...state.slice(0, -2), updated, last];
}
@@ -1039,7 +1089,7 @@ function appendThought(
if (last && last.kind === "thought" && last.turnId === turnId) {
const updated: ThoughtItem = {
...last,
...(timelineCursor ? { timelineCursor } : {}),
...advanceTimelinePosition(last.timelineCursor, timelineCursor),
text: `${last.text}${chunk}`,
timestamp,
status: "loading",
@@ -1219,7 +1269,7 @@ export function mergeAgentToolCallItem(
return {
...existing,
...(timelineCursor ? { timelineCursor } : {}),
...advanceTimelinePosition(existing.timelineCursor, timelineCursor),
timestamp,
payload: {
source: "agent",
@@ -1325,7 +1375,11 @@ function appendPluginTimelineItem(
const existing = state[existingIndex];
if (!existing || existing.kind !== "plugin") return state;
const next = [...state];
next[existingIndex] = { ...nextItem, id: existing.id };
next[existingIndex] = {
...nextItem,
id: existing.id,
...advanceTimelinePosition(existing.timelineCursor, timelineCursor),
};
return next;
}
@@ -1356,7 +1410,7 @@ function appendTodoList(
const next = [...state];
next[previousIndex] = {
...previous,
...(timelineCursor ? { timelineCursor } : {}),
...advanceTimelinePosition(previous.timelineCursor, timelineCursor),
items: normalizedItems,
timestamp,
};
@@ -1375,7 +1429,7 @@ function appendTodoList(
const next = [...state];
next[next.length - 1] = {
...lastItem,
...(timelineCursor ? { timelineCursor } : {}),
...advanceTimelinePosition(lastItem.timelineCursor, timelineCursor),
items: normalizedItems,
activity: { type: "created", count: normalizedItems.length },
timestamp,
@@ -1520,7 +1574,7 @@ function reduceTimelineCompaction(
if (loadingIdx >= 0 && existing && existing.kind === "compaction") {
const updated: CompactionItem = {
...existing,
...(timelineCursor ? { timelineCursor } : {}),
...advanceTimelinePosition(existing.timelineCursor, timelineCursor),
status: "completed",
trigger: item.trigger ?? existing.trigger,
preTokens: item.preTokens ?? existing.preTokens,
@@ -1543,6 +1597,40 @@ 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,
);
if (state.some((existing) => existing.kind === "provider_switch" && existing.id === switchId)) {
return state;
}
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,
};
return [...state, marker];
}
function reduceTimelineEvent(
state: StreamItem[],
event: Extract<AgentStreamEventPayload, { type: "timeline" }>,
@@ -1614,6 +1702,8 @@ 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:
@@ -1645,7 +1735,10 @@ export function reduceStreamUpdate(
),
event,
);
return event.item.type === "reasoning" ? updated : finalizeActiveThoughts(updated);
const stamped = event.turnMetrics?.length
? stampCompletedTurnMetrics(updated, event.turnMetrics, event.turnId)
: updated;
return event.item.type === "reasoning" ? stamped : finalizeActiveThoughts(stamped);
}
case "turn_completed":
return stampCompletedTurnMetrics(finalizeActiveThoughts(state), event.metrics, event.turnId);
+1
View File
@@ -517,6 +517,7 @@ export const HOST_SECTION_SLUGS = [
"connections",
"pair-device",
"agents",
"agent-profiles",
"metadata",
"voice",
"workspaces",
+3
View File
@@ -47,5 +47,8 @@
"typescript": "^5.2.2",
"vitest": "^4.1.6",
"zx": "^8.8.5"
},
"engines": {
"node": ">=22.16.0"
}
}
@@ -146,6 +146,10 @@ 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") {
+5 -1
View File
@@ -408,7 +408,6 @@ 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));
@@ -439,6 +438,11 @@ 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();

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