Compare commits

..
Author SHA1 Message Date
Mohamed Boudra 6fba37f964 fix(agents): share launchAgent rollback on provider switch and test wrap rejection 2026-11-26 03:00:05 +01:00
Mohamed Boudra 4a705540e2 fix(agents): roll back plugin session open on failed provider switch 2026-11-26 02:51:57 +01:00
Mohamed Boudra ade9951393 fix(server): let waitForFinish follow provider switches from target startup through first-turn admission 2026-11-26 02:49:21 +01:00
Mohamed Boudra af7d18f08e fix(server): track provider-switch reservation separately from pending runs so waitForAgentEvent follows replacement 2026-11-26 02:49:21 +01:00
Mohamed Boudra 2ba6f0f3d4 fix(app): open live-agent mobile model browser at current provider and restore web overlay focus after commit 2026-11-26 02:49:20 +01:00
Mohamed Boudra b8f78ce288 test(server): stub assertSettingsMutationAllowedDuringSwitch in session config setter tests 2026-11-26 02:49:20 +01:00
Mohamed Boudra b5cb229e7f fix(app): decouple failed startup settings hold from draft actions 2026-11-26 02:49:20 +01:00
Mohamed Boudra e53ccc2510 fix(app): add explicit retry/discard recovery for failed startup settings and keep live edits independent 2026-11-26 02:49:20 +01:00
Mohamed Boudra 0a8865178e fix(app): keep automatic queue drain paused after failed startup settings until dismissed 2026-11-26 02:49:20 +01:00
Mohamed Boudra 5a847719d1 fix(app): await atomic startup settings application before draining queued follow-up 2026-11-26 02:49:20 +01:00
Mohamed Boudra f4abc198f8 fix(agents): guard untagged settings edits from switchAgentProvider entry 2026-11-26 02:49:20 +01:00
Mohamed Boudra 4cc532cb32 fix(agents): reject legacy settings edits without expectedProvider during an active switch 2026-11-26 02:49:20 +01:00
Mohamed Boudra 076da38c44 fix(protocol,server,app): enforce expectedProvider ownership on settings mutations during switch 2026-11-26 02:49:20 +01:00
Mohamed Boudra 774110243e fix(agents,app): read handoff after lock, forward startup edits, and surface queued switch errors 2026-11-26 02:49:20 +01:00
Mohamed Boudra ed37f6f5a4 fix(app): settle only the sent staged provider draft on switch reply 2026-11-26 02:49:20 +01:00
Mohamed Boudra bfc2f5cb3a fix(agents): serialize provider switch admission through first turn start 2026-11-26 02:49:20 +01:00
Mohamed Boudra a060e03751 fix(agents): handle post-commit switch replay, staged option edits, and prior-handle resume 2026-11-26 02:49:19 +01:00
Mohamed Boudra fa7b6d1a27 fix(ci): fix lucide test stub, non-array prompt guards, and rewind lock order 2026-11-26 02:49:19 +01:00
Mohamed Boudra 3c194a988d fix(agents): address provider-switching review findings 2026-11-26 02:49:19 +01:00
Mohamed Boudra 15098efcf2 test(client): include timeline_provider_switches in hello capabilities assertion 2026-11-26 02:49:19 +01:00
Mohamed Boudra c9823293b0 feat(agents): support provider switching within a chat 2026-11-26 02:49:19 +01:00
Mohamed Boudra 5fd6783c19 fix(agents): forward history option through createAgentInternal 2026-11-26 02:47:09 +01:00
Mohamed Boudra 4719186fbb 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-26 02:46:04 +01:00
Mohamed Boudra cd2bfa91a8 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-26 02:46:04 +01:00
Mohamed Boudra b26f19accd 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-26 02:46:04 +01:00
Mohamed Boudra 8aba8bde08 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-26 02:46:04 +01:00
Mohamed Boudra 29c448ac96 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-26 02:45:19 +01:00
Mohamed Boudra e03503c0de 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-26 02:45:19 +01:00
Mohamed Boudra 16c8a188e0 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-26 02:45:19 +01:00
Mohamed Boudra 325a65acac 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-26 02:45:19 +01:00
Mohamed Boudra 3c5654d2ab 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-26 02:45:19 +01:00
Mohamed Boudra e531eb1f1a chore(nix): update npm dependency hash for the Node 22.16 types 2026-11-26 02:45:19 +01:00
Mohamed Boudra a462c43de2 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-26 02:45:18 +01:00
Mohamed Boudra 511306bd25 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-26 02:44:45 +01:00
Mohamed Boudra eed84c01f1 test(agents): prove a run's caller hears a turn whose record failed 2026-11-26 02:44:45 +01:00
Mohamed Boudra 6d21e28e06 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-26 02:44:45 +01:00
Mohamed Boudra 4b42ae6c17 Merge remote-tracking branch 'origin/main' into plan-provider-switch-sqlite-timelines
# Conflicts:
#	packages/server/src/server/agent/agent-manager.ts
#	packages/server/src/server/agent/providers/opencode/v2/agent.test.ts
2026-11-26 02:42:27 +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 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
322 changed files with 23080 additions and 15455 deletions
-2
View File
@@ -342,8 +342,6 @@ jobs:
run: |
npm run test:unit --workspace=@getpaseo/server -- \
src/server/file-observer \
src/server/workspace-reconciliation-observation.test.ts \
src/utils/checkout-git-identity.test.ts \
src/server/workspace-git-service.observation.test.ts \
src/server/workspace-git-service.observation.integration.test.ts \
--bail=1
+3 -3
View File
@@ -38,9 +38,9 @@ on:
- "true"
- "false"
rollout_hours:
description: "Rollout duration in hours: a 5% canary hold, then a ramp to 100%. Use 0 to admit everyone at once."
description: "Linear rollout duration in hours. Use 0 for instant rollout."
required: false
default: "18"
default: "36"
type: string
concurrency:
@@ -51,7 +51,7 @@ env:
SOURCE_TAG: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.tag || github.ref_name }}
CHECKOUT_REF: ${{ github.event_name == 'workflow_dispatch' && (github.event.inputs.checkout_ref || github.ref_name) || github.ref_name }}
SHOULD_PUBLISH: ${{ github.event_name != 'workflow_dispatch' || github.event.inputs.publish != 'false' }}
ROLLOUT_HOURS: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.rollout_hours || '18' }}
ROLLOUT_HOURS: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.rollout_hours || '36' }}
DESKTOP_PACKAGE_PATH: "packages/desktop"
jobs:
+1
View File
@@ -55,6 +55,7 @@ At the start of non-trivial work, list `docs/` and skim anything relevant to the
| [docs/permissions.md](docs/permissions.md) | Semantic daemon permissions, principals, credentials, pairing invitations, and Hub authority |
| [docs/terminal-performance.md](docs/terminal-performance.md) | Terminal latency pipeline, coalescing/backpressure invariants, benchmark + perf spec usage |
| [docs/terminal-rendering.md](docs/terminal-rendering.md) | Native terminal view: xterm owns the grid, cluster placement, emoji widths, mixed-direction limits, render regression |
| [docs/timeline-sync.md](docs/timeline-sync.md) | Owned agent history, rewind retirements, live stream vs authoritative fetch, paged catch-up, client replica |
| [docs/agent-stream-performance.md](docs/agent-stream-performance.md) | Assistant text pipeline — coalescing window, paced reveal, why arrival lumps are smoothed at render |
| [docs/agent-stream-disclosure.md](docs/agent-stream-disclosure.md) | Expand/collapse in the chat timeline — hold contract, native anchor sequence, frame spacing, render-window cost |
| [docs/markdown-renderer.md](docs/markdown-renderer.md) | Shared Markdown engine, the vendored library fork, native selection, links, images and library constraints |
+7 -16
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
@@ -183,7 +183,7 @@ caller, child, and host into one watch.
Bootstrap restores these watches after repairing stale running records to `closed` and before opening
ingress. Reading a closed child's result does not load its provider. A finish notification reports that
the child has settled (see below); the parent decides whether its task is complete. A child chosen for restart
the child's run has settled; the parent decides whether its task is complete. A child chosen for restart
recovery is observed only after its resume was sent, so the parent never hears that it was closed
in between. Archived or deleted parents suppress delivery;
parent-owned creation watches also stop
@@ -196,18 +196,6 @@ outstanding intent. A crash after successful dispatch but before removal commits
notification. Clean shutdown can also flush an already queued callback while retaining its intent,
so that callback can repeat after restart. This is an at-least-once wakeup, without turn attribution or exactly-once delivery.
A turn end is not always a settled child. When the child ends its turn with work that will start its
next turn by itself, the caller gets one `message` notice ("ended its turn but is still working") and
the subscription keeps following the child. That work is a running turn, queued messages, a pending
provider wake-up (`AgentSession.hasPendingWakeup`: Claude background tasks, task notifications, and
one-shot wake-ups), or the child's own outstanding finish subscriptions as a caller. Heartbeats,
recurring crons, change-request watches, and other daemon background items never count: they are
external triggers, not work the caller is waiting for. While following, turn ends and work changes stay
silent until nothing is pending, which sends `finished` and removes the subscription. `followingSince`
is stored before the notice is sent, so restarts resume following without repeating it, and following
ends after 24 hours with an "is still working" notice. Remote children and providers without the probe
report their first turn end as `finished`.
Permission requests are notification checkpoints, not the end of that subscription. The caller is notified again after a permission response when the child finishes, errors, or requests another permission.
The permission notification includes the normalized request plus the child and request IDs, so the caller can inspect it and respond without fetching agent status.
A watched child that closes before its finish event also notifies the caller so delegated work cannot disappear silently during archive or workspace teardown.
@@ -268,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.
@@ -364,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`
-1
View File
@@ -10,7 +10,6 @@ Authoritative terminology. UI label wins. Don't invent synonyms; use what's here
- **Agent** — See **Agent session**. UI still says "Agent" / "New Agent" in places, but moving toward **Agent session** as the canonical term. Code: `AgentSnapshotPayload` (`packages/protocol/src/messages.ts:608`). Forbidden: "Task", "Job", "Run".
- **Daemon** — Local Paseo server process; identified by `serverId`. UI: "Daemon" (system contexts only). Code: `serverId` in `ServerInfoStatusPayloadSchema` (`packages/protocol/src/messages.ts:1936`), `DaemonClient` (`packages/client/src/daemon-client.ts`).
- **Host** — Client-side connection profile pointing at a daemon; bundles one or more `HostConnection`s. UI: "Host" / "Add host" / "Switch host". Code: `HostProfile` (`packages/app/src/types/host-connection.ts:37`). Forbidden: "Connection" (means `HostConnection`, not host).
- **Device** — A computer or phone running a Paseo client. Open **Devices** in a host’s settings to connect another device.
- **Host badge** — The item on a sidebar workspace row's meta row naming which host that workspace lives on. Three things gate it, and they compose as a lattice rather than competing: the sidebar must span more than one host (automatic), **Show → Host** in the sidebar's display preferences must be on (global, all hosts at once), and then that host's own display mode decides _how_ it draws — **Name** / **Icon only** / **Hidden**. Name, color, and display mode are per-host, per-device, and live client-side on `HostProfile.appearance`; nothing about it reaches the daemon. Never add a fourth way to hide it. UI: the "Appearance" group on a host's settings page, and the "Show" submenu in the sidebar's display preferences. Code: `selectHostBadges` (`packages/app/src/hosts/appearance.ts`) takes the first two as its `enabled` input; `WorkspaceMetaRow` (`packages/app/src/components/sidebar/workspace-meta-row/index.tsx`) draws it. Don't confuse with **Status pill**, which reports state rather than identity.
- **Project host entry** — One row in a project for a single (project, daemon) pair, aggregating that daemon's workspaces in the project. Internal. Code: `ProjectHostEntry` (`packages/app/src/utils/projects.ts:11`). Don't introduce "Checkout" as a synonym.
- **Placement** — One workspace's stable foreign-key relationship to its project plus its git checkout snapshot. Internal. An explicit creation `projectId` is authoritative when active.
+1 -4
View File
@@ -225,10 +225,7 @@ aborts the shared refresh signal at the deadline, and when it stops. Shutdown wa
probes to settle before it shuts down provider clients, so a probe cannot start provider work,
such as an OpenCode server, after its client has cleaned up. Providers name active catalog operations and
finish subprocess, server, or session cleanup before rejecting. Timeout errors list the operations
that were still active when the deadline expired. A plugin provider's connection is shared with its
running sessions, so the bridge cannot close it at the deadline; it sends `request.cancel` for the
abandoned request instead, and the provider stops that request's work
([provider guide](../public-docs/plugins/providers.md#stop-a-request-paseo-cancels)).
that were still active when the deadline expired.
Catalogue results stay cached by identity until a refresh or a change to that provider's configuration.
Providers change their model lists on the server without a CLI update, so the daemon refreshes
+31 -93
View File
@@ -48,7 +48,7 @@ the shipped source.
The user decides when the changes on `main` warrant a release and how much risk it takes:
1. **Direct stable release** for a low-risk batch of polish and bug fixes. Stable desktop updates
start with a 5% canary and ramp over 18 hours (see [Staged rollout](#staged-rollout-stable-channel)), and store
already ramp over 36 hours (see [Staged rollout](#staged-rollout-stable-channel)), and store
review often takes about a day, with no guaranteed timing.
2. **Beta flow**, the default for changes that need testing. Release candidates on the `beta`
channel. Each beta folds into the series' single changelog entry, publishes npm only on the
@@ -324,33 +324,11 @@ Use the beta path when you need to:
## Staged rollout (stable channel)
A stable desktop release reaches automatic updates in stages, so a bad release reaches few installs before you stop it. Each install decides locally from two fields in the release manifests, `releaseDate` and `rolloutHours`. No server tracks installs.
Stable desktop releases go out via a linear time-based rollout for automatic update checks: 0% admitted when the updater manifests appear, 100% admitted 36 hours later, linear ramp in between. Manual checks bypass the rollout so a user can install immediately when they click **Check**. Beta releases bypass the rollout entirely — beta users always receive updates immediately.
| Stage | Rule |
| -------------- | -------------------------------------------------------------------------------------------------------- |
| Canary | For the first 8 hours, 5% of installs are admitted. |
| Ramp | From 8 hours to `rolloutHours` (18 by default), admission rises in a straight line from 5% to 100%. |
| Check interval | An install asks GitHub for the latest release at most once every 6 hours. |
| Cooldown | After an install updates, it skips paced releases for 72 hours. |
| Staged update | An install that holds a downloaded update keeps it and does not download the paced release that follows. |
The rollout is driven by a `rolloutHours` field stamped into the GitHub Release manifests (`latest-mac.yml`, `latest-linux.yml`, `latest.yml`) by the `finalize-rollout` job in `desktop-release.yml`.
A paced release is a stable release with `rolloutHours` above 0. When `rolloutHours` is under 16, the canary hold is half of `rolloutHours`.
Every release places each install at a new position in the rollout, so the canary group changes with each release. With one or two releases per day, an install updates at most once every 72 hours and skips the releases in between.
These paths skip the stages:
- A manual check (**Check**) always asks GitHub and always offers the latest release.
- A release with `rolloutHours: 0` is an emergency release. Every install takes it at its next check, during a cooldown too, and it replaces a staged update.
- The beta channel has no stages. A beta install takes each release at its next check.
The **Notify** update mode follows the same stages and prompts instead of downloading. **Off** makes no automatic requests.
`packages/desktop/src/features/app-update-rollout.ts` owns the curve. `app-update-pacing.ts` owns the check interval and the cooldown, and `app-update-service.ts` owns the staged update.
### How a release is published
The `finalize-rollout` job in `desktop-release.yml` stamps `releaseDate` and `rolloutHours` into the GitHub Release manifests (`latest-mac.yml`, `latest-linux.yml`, `latest.yml`). Desktop release builds publish in two phases:
Desktop release builds now publish in two phases:
- The GitHub Release stays a draft while platform build jobs upload the installers/packages (`.dmg`, `.zip`, `.exe`, `.AppImage`, etc.).
- The final job merges and stamps every channel manifest, uploads them with the final `releaseDate` and `rolloutHours`, then publishes the GitHub Release.
@@ -360,20 +338,20 @@ Drafts do not appear in GitHub's releases feed. Updater clients continue to see
### Default behavior
Follow the [standard stable release procedure](#standard-release-stable). The tag push starts
the desktop release workflow, which sets an 18-hour rollout when it publishes the release.
the desktop release workflow, which sets a 36-hour rollout when it publishes the release.
The `rollout_hours` input on `desktop-release.yml` is read only on `workflow_dispatch`. Tag-push runs always use 18. To get any other rollout duration on a fresh release, use the post-publish flip below.
The `rollout_hours` input on `desktop-release.yml` is **only read on `workflow_dispatch`** — tag-push runs always default to 36. To get any other rollout duration on a fresh release, use the post-publish flip below.
### Emergency release (rollout_hours=0)
### Instant-admit release (rollout_hours=0)
Follow the [standard stable release procedure](#standard-release-stable). Wait for Desktop
Release to publish, then update the manifests to admit everyone at once.
Release to publish, then update the manifests to admit everyone immediately.
```bash
# 1. Wait for Desktop Release to publish the GitHub Release.
gh run watch <desktop-release-run-id> --exit-status
# 2. Flip the published manifests to an emergency release.
# 2. Flip the published manifests to instant admit.
gh workflow run desktop-rollout.yml \
-f tag=v0.1.64 \
-f rollout_hours=0
@@ -381,13 +359,23 @@ gh workflow run desktop-rollout.yml \
Dispatch only after `finalize-rollout` has published the release. Until then the release is a draft, and a draft has no tag: `desktop-rollout.yml` looks the release up by tag and fails with `release not found`. The concurrency group `desktop-rollout-<tag>` that the two workflows share orders them only once both are queued; it does not hold an early dispatch until the draft is published.
The first public manifests carry `rolloutHours=18` for the minutes between publish and the flip. An install sees the flip at its next check, which is up to 6 hours after its previous one. In automatic mode it then downloads the release and installs it when the app quits.
The first public manifests carry `rolloutHours=36` for the minutes between publish and the flip. The renderer polls every 30 minutes, so active stable users pick up the new manifest on their next check.
### Adjusting an already-published release
To change the rollout duration on a release that already shipped, use the `desktop-rollout.yml` workflow. It edits the manifests in place on the GitHub release without rebuilding anything. It rewrites only `rolloutHours`. `releaseDate` is preserved, so the rollout clock keeps running from the original publish time.
To change the rollout duration on a release that's already shipped — e.g. flip a hotfix to instant admit, or slow a release down — use the dedicated `desktop-rollout.yml` workflow. It edits the manifests in place on the GitHub release without rebuilding anything. It only rewrites `rolloutHours`; `releaseDate` is preserved, so the rollout clock keeps ticking from the original publish time.
To slow a rollout down, for example to 72 hours since the original release:
**Hotfix (instant admit) on an already-shipped release:**
```bash
gh workflow run desktop-rollout.yml \
-f tag=v0.1.42 \
-f rollout_hours=0
```
`rollout_hours=0` admits 100% of stable users on their next update check (within ~30 min for active clients).
**Slow a rollout down** (e.g. extend total duration to 72h since the original release):
```bash
gh workflow run desktop-rollout.yml \
@@ -395,59 +383,13 @@ gh workflow run desktop-rollout.yml \
-f rollout_hours=72
```
`rollout_hours` is the total duration since the original release date. If `v0.1.42` was published 2 hours ago and you set `rollout_hours=72`, the ramp finishes 70 hours from now.
A longer rollout does not stop a release. The canary group still updates. To stop a release, [halt it](#halt-a-release).
`rollout_hours` is **total duration since the original release date**, not "extend by N more hours from now." If `v0.1.42` was published 2h ago and you set `rollout_hours=72`, the ramp finishes 70h from now.
The dispatch is idempotent and shares the `desktop-rollout-<tag>` concurrency group with `desktop-release.yml`'s `finalize-rollout` job, so it serializes safely against an in-flight tag-push pipeline targeting the same release.
### Halt a release
Stable installs and the download page follow the release that GitHub marks as latest. To stop a release, mark the last good release as latest:
```bash
# v0.1.41 is the last good release.
gh release edit v0.1.41 --latest
# Prints v0.1.41 when the halt is in effect.
gh api repos/getpaseo/paseo/releases/latest --jq .tag_name
```
The halt applies to every stable install from its next check, including installs older than the staged rollout:
- An install that has not downloaded the halted release no longer sees it.
- An install that downloaded it asks GitHub again before it installs at quit, and drops the download.
- An install that already runs the halted release stays on it, because the app never downgrades. [Ship a fix](#fix-a-bad-release).
A halt does not reach the beta channel. Beta installs read the release list by date and still take the halted release.
To resume a halted release, run `gh release edit v0.1.42 --latest` with its tag.
### Fix a bad release
1. [Halt](#halt-a-release) the bad release.
2. Ship the fix as the next patch with the [standard stable release procedure](#standard-release-stable).
3. After Desktop Release publishes the fix, make sure that GitHub marks it as latest:
```bash
gh api repos/getpaseo/paseo/releases/latest --jq .tag_name
```
If the command prints another tag, run `gh release edit <fix-tag> --latest`.
4. Flip the fix to an [emergency release](#emergency-release-rollout_hours0):
```bash
gh workflow run desktop-rollout.yml \
-f tag=<fix-tag> \
-f rollout_hours=0
```
Do not leave the fix as a paced release. The installs that took the bad release are in their 72-hour cooldown and skip a paced release. An install that holds the bad release as a staged update, and did not check during the halt, keeps it when a paced release follows. An emergency release reaches both.
### Custom ramp on a manually-dispatched build
`desktop-release.yml` accepts `rollout_hours` only on `workflow_dispatch`, which is the path used to rebuild an existing tag (retry a failed release, force a rebuild on a different ref). On that path, you can stamp a different ramp directly:
`desktop-release.yml` accepts `rollout_hours` only on `workflow_dispatch`, which is the path used to **rebuild an existing tag** (retry a failed release, force a rebuild on a different ref). When you go that route, you can stamp a non-default ramp directly:
```bash
gh workflow run desktop-release.yml \
@@ -455,18 +397,14 @@ gh workflow run desktop-release.yml \
-f rollout_hours=6
```
For a fresh release with a custom ramp, follow the [emergency release procedure](#emergency-release-rollout_hours0)
For a fresh release with a custom ramp, follow the [instant-admit procedure](#instant-admit-release-rollout_hours0)
and set `rollout_hours` to your chosen duration.
### Releasing during an active rollout
If you ship N+1 while N is still ramping, N+1 starts a new rollout from its own publish time, and the rollout of N ends because installs no longer see its manifests.
If you ship N+1 while N is still ramping, N+1 starts a fresh rollout from its own publish timestamp. N's rollout effectively ends — the newer manifest supersedes it. Rollout-aware clients revalidate the manifest for up to five seconds before installing a downloaded update on quit. If N+1 has replaced N but the client is not admitted to N+1 yet, it skips the downloaded N and waits rather than installing two updates in succession. If revalidation times out, the app exits without installing the cached update.
An install that holds N as a staged update keeps N when N+1 is a paced release, and installs N when the app quits. It then waits out its cooldown before it takes a later paced release. The hold covers only paced patch releases that the install saw one after the other. If the install missed a release, it evaluates the newest release instead: it replaces N when it is admitted, and drops N when it is not.
A minor or major release always ends the hold. The version numbers do not show whether a fix shipped between `0.17.4` and `0.18.0`, so the install treats `0.18.0` as if it missed a release.
Before an install at quit, the app asks GitHub for the latest release for up to five seconds. If that check does not finish in time, the app exits without installing the staged update.
If N+1 is a hotfix for a bug in N, dispatch `desktop-rollout.yml -f tag=v0.1.<N+1> -f rollout_hours=0` after N+1 publishes so the users who already got N reach the fix fast.
### macOS system floor
@@ -479,10 +417,10 @@ macOS 13 maps to Darwin 22. The two values use different version domains; do not
### Limitations
- A release cannot be recalled from an install that runs it. `allowDowngrade` is `false`. [Halt](#halt-a-release) the release to protect the other installs, then [ship a fix](#fix-a-bad-release).
- An emergency release reaches a running install at its next check, up to 6 hours after its previous one. A manual check sees it at once.
- Installs older than the canary and cooldown build have neither. They ramp in a straight line over `rolloutHours` and check every 30 minutes. Installs older than the staged rollout ignore `rolloutHours` and update at once.
- The app window starts every automatic check. A release whose window does not load cannot update itself, and its users must download a new build from the website. Smoke the packaged app before you publish.
- **No pause / kill switch.** To stop new admissions, ship a superseding release. Clients revalidate on quit and will not install the superseded download, but a client that already completed installation cannot be recalled; ship a hotfix `+1` patch.
- **No rollback.** `allowDowngrade = false`. Bad release = ship a hotfix.
- **Bootstrap caveat.** Clients running a build older than the rollout feature ignore `rolloutHours` and admit immediately. Rollout protection only applies to clients running the rollout-aware version or later.
- **Up to ~30 min automatic admission latency.** Renderer polls every 30 minutes, so a stable user may take up to that long to be evaluated against the rollout window. Clicking **Check** is manual and bypasses rollout admission.
## Mobile builds (EAS)
+72 -28
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
@@ -202,23 +258,10 @@ owner wraps cached preparation, network catch-up, accepted timeline application,
behind one interface. React supplies transport and projection operations without selecting a cache
path or issuing a separate persistence notification.
The viewed-timeline owner also owns how long a transcript stays in memory. An active agent's
transcript stays resident while its chat is hidden, so switching back to it needs no fetch. An
archived agent's transcript stays resident only while its chat is shown, for example when it is
opened from History. When an agent is archived, or the active list drops it because its workspace
was archived, the owner releases the transcript unless the chat is shown. It also releases the
transcript when the chat stops being shown. A released chat leaves the opened chats. When it is
shown again, it reads the replica cache and catches up again. A history page, live event, or cache
read that arrives after the release is dropped.
The active-list reconciliation does not release transcripts itself. An archived agent's fresh
history response can arrive before the active-list response that omits it, while the chat is
open in History. Clearing history there would discard rows the user is reading.
An agent counts as archived when the active list omits it, when its row has an archive timestamp,
or when the workspace list omits its workspace. The workspace check matters because a workspace
archive can complete while one of its agents keeps a row with no archive timestamp. Until a list
first hydrates, it marks no agent as archived. Deleting the agent clears the transcript.
Active-agent list reconciliation does not own transcript lifetime. An archived agent's fresh
history response can arrive before the active-list response that omits it. Clearing history there
would discard accepted rows while the viewed owner still considers them synchronized. Entity
deletion clears the transcript; list membership changes do not.
Removing the host from the registry is the destructive boundary: it stops the runtime and clears the
session and host-scoped setup state together.
@@ -358,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.
@@ -374,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-6XXAVBTH6rIdg5eQ9cUeUwV22ikVqTtdWo7i9DYO+/M=
sha256-IAhKhkolW4xvFvMaAEFdhYvPAhTm2azsqbGMKCKL3q0=
+20 -2
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": {
@@ -40625,7 +40631,6 @@
"p-limit": "^7.3.0",
"p-memoize": "^8.0.0",
"p-throttle": "^8.1.0",
"parse5": "^7.3.0",
"pino": "^10.2.0",
"pino-pretty": "^13.1.3",
"qrcode": "^1.5.4",
@@ -40647,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",
@@ -40655,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": {
@@ -41102,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();
}
@@ -45,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([]);
@@ -69,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",
+5 -3
View File
@@ -15,7 +15,7 @@ import {
closeRelayPairing,
emptyHome,
loadingScreen,
expectTailscaleSwitchDisabled,
openTailscaleDocsFromSetup,
paseoToolsSwitch,
pickTheme,
projectSuggestion,
@@ -403,10 +403,12 @@ test("setup choices carry over to Settings and the phone step pairs over relay",
await continueSetup(page);
});
await test.step("Phone shows a disabled Tailscale switch and pairs over relay", async () => {
await test.step("Phone offers Tailscale docs and pairs over relay in its own modal", async () => {
await expectSetupStep(page, "Take your agents with you");
await page.screenshot({ path: testInfo.outputPath("5-phone.png") });
await expectTailscaleSwitchDisabled(page);
expect(await openTailscaleDocsFromSetup(page)).toBe(
"https://paseo.sh/docs/connectivity#tailscale",
);
const pairing = await openRelayPairingFromSetup(page);
await expect(pairing.getByText("Enable relay?", { exact: true })).toBeVisible();
await enableRelayAndExpectOffer(page);
@@ -1,24 +1,7 @@
import { gotoAppShell, openSettings } from "../support/helpers/app";
import {
addDirectHostFromSettings,
openSettingsHostSection,
selectSettingsHost,
} from "../support/helpers/settings";
import { test } from "../support/fixtures";
import { startTailscaleTestDaemon } from "../support/helpers/tailscale-daemon";
import { startIsolatedHostDaemon } from "../support/helpers/isolated-host-daemon";
import {
expectPairingOffer,
cancelTailscaleTurnOff,
confirmTailscaleTurnOff,
connectThroughTailscale,
disableTailscale,
enableTailscale,
expectTailscaleAddress,
expectTailscaleRowLoadsOn,
openSetupMobileStep,
slowConnectionToHost,
expectTailscaleUpdateRequired,
expectCompletePairingQr,
expectRelayConsent,
openPairDeviceModal,
@@ -54,59 +37,3 @@ test("keeps the pairing QR code inside its compact tile", async ({ page }, testI
await daemon.close();
}
});
test("asks for a host update when Tailscale controls are unavailable", async ({ page }) => {
const daemon = await startIsolatedHostDaemon("pair-device-browser-old-host", {
publishedVersion: "0.13.0-beta.2",
});
try {
await gotoAppShell(page);
await openSettings(page);
await addDirectHostFromSettings(page, { host: "127.0.0.1", port: daemon.port });
await selectSettingsHost(page, daemon.serverId);
await openSettingsHostSection(page, daemon.serverId, "devices");
await expectTailscaleUpdateRequired(page);
} finally {
await daemon.close();
}
});
test("turns Tailscale on and off from Devices, asking first over Tailscale", async ({
page,
baseURL,
}, testInfo) => {
test.skip(process.platform !== "linux", "Uses a second IPv4 loopback address");
// The journey opens Devices or the setup six times, two of them over a slowed connection.
test.setTimeout(120_000);
if (!baseURL) throw new Error("Expected the app base URL");
const daemon = await startTailscaleTestDaemon(baseURL);
try {
await preparePairingHost(page, daemon);
await enableTailscale(page);
await expectTailscaleAddress(page, daemon.tailscaleAddress);
await page.screenshot({ path: testInfo.outputPath("devices.png") });
await test.step("While its status loads, the row never shows Tailscale off", async () => {
const address = daemon.tailscaleAddress;
await expectTailscaleRowLoadsOn(page, address, () => preparePairingHost(page, daemon));
await expectTailscaleRowLoadsOn(page, address, () => openSetupMobileStep(page, daemon));
const restoreSpeed = await slowConnectionToHost(page, daemon.port, 300);
await expectTailscaleRowLoadsOn(page, address, () => openSetupMobileStep(page, daemon));
await expectTailscaleRowLoadsOn(page, address, () => preparePairingHost(page, daemon));
restoreSpeed();
});
await disableTailscale(page, daemon.tailscaleAddress);
await test.step("Over Tailscale, turning it off asks first and Cancel changes nothing", async () => {
await enableTailscale(page);
await connectThroughTailscale(page, daemon);
await cancelTailscaleTurnOff(page, daemon.tailscaleAddress);
});
await test.step("Confirming turns it off and cuts this connection", async () => {
await confirmTailscaleTurnOff(page, daemon.tailscaleAddress);
});
} finally {
await daemon.close();
}
});
@@ -0,0 +1,509 @@
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 browserSheet = page.getByTestId("agent-controls-model-browser-sheet");
const browserViewport = page.getByTestId("agent-controls-model-browser-viewport");
await expect(browserViewport).toBeVisible({ timeout: 30_000 });
const backButton = browserSheet.getByTestId("sheet-header-back");
if (await backButton.isVisible()) {
await backButton.click();
}
await browserViewport.getByTestId(`model-provider-${DIRECT_PROVIDER.id}`).click();
await browserViewport
.getByTestId(`model-row-${DIRECT_PROVIDER.id}-${DIRECT_PROVIDER.modelId}`)
.click();
await expect(browserViewport).toHaveCount(0, { timeout: 30_000 });
// Dismiss the outer agent-controls sheet so the composer and banner are ready to submit.
await page.getByRole("button", { name: "Close", exact: true }).last().click();
await expect(page.getByTestId("agent-controls-model")).toHaveCount(0, { timeout: 30_000 });
await expect(page.getByTestId("staged-provider-switch-banner")).toBeVisible({ timeout: 30_000 });
}
async function rewindConversation(page: Page, userMessage: Locator, prompt: string): Promise<void> {
await userMessage.getByText(prompt, { exact: true }).hover();
await userMessage.getByRole("button", { name: "Rewind to this message", exact: true }).click();
await page.getByRole("menuitem", { name: "Rewind conversation", exact: true }).click();
}
test.describe.serial("Provider switching in chat", () => {
let pluginClient: PluginInstallDaemonClient;
let pluginFixture: Awaited<ReturnType<typeof copyPluginExample>>;
let previousPluginsEnabled: boolean | undefined;
test.beforeAll(async () => {
pluginClient = await connectDaemonClient<PluginInstallDaemonClient>({
clientIdPrefix: "provider-switching-e2e",
});
pluginFixture = await copyPluginExample("provider-direct");
previousPluginsEnabled = (await pluginClient.getDaemonConfig()).config.pluginsEnabled;
await pluginClient.patchDaemonConfig({ pluginsEnabled: true });
await pluginClient.installDirectoryPlugin(pluginFixture.directory);
await expect.poll(() => hasDirectProvider(pluginClient), { timeout: 30_000 }).toBe(true);
});
test.afterAll(async () => {
await pluginClient?.removePlugin(DIRECT_PROVIDER.pluginId).catch(() => undefined);
await pluginClient
?.patchDaemonConfig({ pluginsEnabled: previousPluginsEnabled })
.catch(() => undefined);
await pluginClient?.close().catch(() => undefined);
await pluginFixture?.cleanup().catch(() => undefined);
});
test("stages, cancels, switches providers, inspects marker, scopes rewind, and survives reload", async ({
page,
}) => {
test.setTimeout(150_000);
await page.setViewportSize({ width: 1280, height: 800 });
const preSwitchPrompt = "First prompt on Mock before switching.";
const postSwitchPrompt = "Follow up on Direct provider after switching.";
const postRewindPrompt = "Continue on Direct provider after rewinding.";
const workspace = await seedMockAgentWorkspace({
repoPrefix: "provider-switch-desktop-",
title: "Provider switch desktop",
model: "e2e-fast-stream",
modeId: "load-test",
});
try {
await openAgentRoute(page, workspace);
await expectComposerVisible(page);
await expectComposerMode(page, "Load test");
const initialUrl = page.url();
await completeMockTurn(page, workspace, preSwitchPrompt);
await test.step("staging updates only draft state and Cancel restores the live provider", async () => {
await stageDirectProviderDesktop(page);
await expectComposerModel(page, DIRECT_PROVIDER.modelLabel);
await expectComposerMode(page, DIRECT_PROVIDER.modeLabel);
await expect(page.getByTestId("staged-provider-switch-banner")).toContainText(
DIRECT_PROVIDER.label,
);
await expectWorkspaceAgentConfiguration(workspace, {
id: workspace.agentId,
provider: "mock",
model: "e2e-fast-stream",
modeId: "load-test",
});
// Editing a staged provider option must keep all staged option controls visible.
const conciseToggle = page.getByRole("button", { name: /Concise responses/i }).first();
const voiceSelect = page.getByRole("button", { name: /Voice/i }).first();
await expect(conciseToggle).toBeVisible();
await expect(voiceSelect).toBeVisible();
await conciseToggle.click();
await expect(conciseToggle).toBeVisible();
await expect(voiceSelect).toBeVisible();
await expectNoHorizontalOverflow(page);
await captureQaScreenshot(page, "desktop-staged-switch.png");
await page.getByTestId("cancel-staged-provider-switch").click();
await expect(page.getByTestId("staged-provider-switch-banner")).toHaveCount(0);
await expectComposerMode(page, "Load test");
// Returning to the live provider by choosing a different model clears the staged switch
// and applies the newly chosen model directly to the live provider.
await stageDirectProviderDesktop(page);
await openModelPicker(page);
const picker = page.getByTestId("combobox-desktop-container");
const backButton = picker.getByTestId("sheet-header-back");
if (await backButton.isVisible()) {
await backButton.click();
}
await drillIntoProvider(page, "mock");
await selectModelRow(page, { provider: "mock", modelId: "one-minute-stream" });
await expect(page.getByTestId("staged-provider-switch-banner")).toHaveCount(0);
await expectComposerModel(page, "One minute stream");
await expectWorkspaceAgentConfiguration(workspace, {
id: workspace.agentId,
provider: "mock",
model: "one-minute-stream",
modeId: "load-test",
});
});
await test.step("submitting commits the switch in place with clean user display text and inspectable marker", async () => {
await stageDirectProviderDesktop(page);
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();
}
@@ -1,4 +1,4 @@
// Start on Settings > Host > Devices with relay enabled in the Android app.
// Start on Settings > Host > Pair device with relay enabled in the Android app.
// node packages/app/e2e/mobile/pair-device/android.mjs <agent-device-session>
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
@@ -13,7 +13,11 @@ function ad(...args) {
});
}
ad("press", 'label="Relay"', "--settle");
ad(
"press",
'label="Pair a device, Scan a QR code or copy a link to connect your phone to this host"',
"--settle",
);
ad("wait", "text", "Pairing QR code", "10000");
const { data } = JSON.parse(ad("snapshot", "-i", "--json"));
const sheet = data.nodes.find((node) => node.label === "Bottom Sheet");
@@ -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,5 +1,4 @@
import { promisify } from "node:util";
import { once } from "node:events";
import {
spawn,
execFile,
@@ -12,7 +11,6 @@ import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import net from "node:net";
import { tmpdir } from "node:os";
import path from "node:path";
import { WebSocket } from "ws";
import { withDisabledE2ESpeechEnv } from "./speech-env";
import { killProcessTree, spawnTsx } from "./spawn-node";
@@ -66,14 +64,12 @@ export async function getAvailableHostDaemonPort(): Promise<number> {
* Resolves once this daemon answers on its port. An open TCP port is not
* enough: the port is released before the daemon binds it, and whatever takes
* it in between also accepts connections while the daemon exits with
* EADDRINUSE. Only the daemon's own status reports its server id. Published
* daemons can serve status before they accept WebSocket upgrades.
* EADDRINUSE. Only the daemon's own status reports its server id.
*/
async function waitForServer(
port: number,
child: ChildProcess,
identity: { serverId: string; paseoHome: string },
published: boolean,
): Promise<void> {
const deadline = Date.now() + 90_000;
let lastError: unknown = null;
@@ -86,10 +82,7 @@ async function waitForServer(
}
try {
const serverId = await readServerId(port, identity.paseoHome);
if (serverId === identity.serverId) {
if (published) await checkWebSocketUpgrade(port);
return;
}
if (serverId === identity.serverId) return;
lastError = new Error(`Port ${port} is served by ${serverId}, not ${identity.serverId}`);
} catch (error) {
lastError = error;
@@ -104,12 +97,6 @@ async function waitForServer(
);
}
async function checkWebSocketUpgrade(port: number): Promise<void> {
const socket = new WebSocket(`ws://127.0.0.1:${port}/ws`, { handshakeTimeout: 1_000 });
await once(socket, "open");
socket.close();
}
/**
* Reads the server id from the daemon's status route. The route needs a bearer
* on a password-protected daemon; the daemon accepts the local credential it
@@ -259,7 +246,7 @@ export async function startIsolatedHostDaemon(
});
try {
await waitForServer(port, spawned, { serverId, paseoHome }, Boolean(publishedPackageRoot));
await waitForServer(port, spawned, { serverId, paseoHome });
return spawned;
} catch (error) {
throw new Error(
+15 -4
View File
@@ -161,7 +161,7 @@ export async function finishSetup(page: Page): Promise<void> {
/** Opens the Phone step's Relay row: the pair device modal, over setup. */
export async function openRelayPairingFromSetup(page: Page): Promise<Locator> {
await setupModal(page).getByRole("button", { name: "Relay", exact: true }).click();
const pairing = page.getByTestId("devices-relay-pairing");
const pairing = page.getByTestId("onboarding-pair-device-card");
await expect(pairing).toBeVisible();
return pairing;
}
@@ -171,9 +171,20 @@ export async function closeRelayPairing(pairing: Locator): Promise<void> {
await expect(pairing).toHaveCount(0);
}
export async function expectTailscaleSwitchDisabled(page: Page): Promise<void> {
const setup = setupModal(page);
await expect(setup.getByRole("switch", { name: "Tailscale", exact: true })).toBeDisabled();
/** Clicks the Phone step's Tailscale row and returns the docs page it opened. */
export async function openTailscaleDocsFromSetup(page: Page): Promise<string> {
await page
.context()
.route("https://paseo.sh/**", (route) =>
route.fulfill({ contentType: "text/html", body: "<title>Paseo docs</title>" }),
);
const popup = page.waitForEvent("popup");
await setupModal(page).getByRole("link", { name: "Tailscale, Docs", exact: true }).click();
const docs = await popup;
await docs.waitForLoadState("domcontentloaded");
const url = docs.url();
await docs.close();
return url;
}
export interface SetupHost {
+18 -295
View File
@@ -9,8 +9,6 @@ import {
selectSettingsHost,
} from "./settings";
import { expectAppRoute } from "./route-assertions";
import { wsRoutePatternForPort } from "./daemon-port";
import { goToSetupStep, showSetupAgainFromSettings } from "./onboarding";
import { buildSettingsHostSectionRoute } from "@/utils/host-routes";
interface PairingHostInput {
@@ -62,33 +60,9 @@ export async function prepareLocalPairingHost(
await preparePairingHost(page, daemon, additionalHosts);
}
type PairingHost =
| Pick<IsolatedHostDaemon, "serverId" | "port">
| Pick<OutdatedDaemon, "serverId" | "endpoint">;
export async function preparePairingHost(
page: Page,
daemon: PairingHost,
additionalHosts: PairingHostInput[] = [],
): Promise<void> {
await openAppOnPairingHost(page, daemon, additionalHosts);
await openSettings(page);
await openSettingsHost(page, daemon.serverId);
await expect(page.getByTestId("devices-relay")).toHaveCount(0);
await openSettingsHostSection(page, daemon.serverId, "devices");
await expect(page.getByTestId("devices-relay")).toBeVisible();
}
/** Loads the app afresh with `daemon` as its first host, then opens the setup's Mobile step. */
export async function openSetupMobileStep(page: Page, daemon: PairingHost): Promise<void> {
await openAppOnPairingHost(page, daemon);
await showSetupAgainFromSettings(page);
await goToSetupStep(page, "Mobile");
}
async function openAppOnPairingHost(
page: Page,
daemon: PairingHost,
daemon: IsolatedHostDaemon | OutdatedDaemon,
additionalHosts: PairingHostInput[] = [],
): Promise<void> {
await seedSavedSettingsHosts(page, [
@@ -100,271 +74,20 @@ async function openAppOnPairingHost(
...additionalHosts,
]);
await gotoAppShell(page);
}
export async function enableTailscale(page: Page): Promise<void> {
const toggle = page.getByRole("switch", { name: "Tailscale", exact: true });
await expect(toggle).toBeEnabled();
await expect(toggle).not.toBeChecked();
await toggle.click();
await expect(toggle).toBeChecked();
}
export async function expectTailscaleAddress(page: Page, address: string): Promise<void> {
const row = tailscaleAddressRow(page, address);
await expect(row).toBeVisible();
await expect(
row.getByText("On a phone with Tailscale, add a host at this address"),
).toBeVisible();
await expect(row.getByRole("button", { name: "Copy", exact: true })).toBeVisible();
const response = await fetch(`http://${address}/api/health`);
expect(response.ok).toBe(true);
}
/** The switch shows off as soon as it is tapped; the host stops listening when its answer lands. */
async function expectHostUnreachableAt(address: string): Promise<void> {
await expect
.poll(() =>
fetch(`http://${address}/api/health`).then(
() => "reachable",
() => "unreachable",
),
)
.toBe("unreachable");
}
function tailscaleAddressRow(page: Page, address: string) {
return page.getByTestId("devices-tailscale-address").filter({ hasText: address });
}
export async function disableTailscale(page: Page, address: string): Promise<void> {
const toggle = page.getByRole("switch", { name: "Tailscale", exact: true });
await expect(toggle).toBeEnabled();
await toggle.click();
await expect(toggle).not.toBeChecked();
await expect(tailscaleAddressRow(page, address)).toHaveCount(0);
await expectHostUnreachableAt(address);
}
/** Reopens the host over its Tailscale address, as a phone on the tailnet would reach it. */
export async function connectThroughTailscale(
page: Page,
daemon: { serverId: string; tailscaleAddress: string },
): Promise<void> {
await preparePairingHost(page, { serverId: daemon.serverId, endpoint: daemon.tailscaleAddress });
await expectTailscaleAddress(page, daemon.tailscaleAddress);
}
const TURN_OFF_QUESTION =
"Turn off Tailscale?\n\nThis device is connected through Tailscale and will lose its connection to the host.";
/**
* Taps the switch off over the Tailscale connection and cancels the question. Every state the row
* commits from the tap to after Cancel must still show Tailscale on with its address: nothing
* changes until the user confirms.
*/
export async function cancelTailscaleTurnOff(page: Page, address: string): Promise<void> {
const row = await recordTailscaleRow(page);
const question = answerNextDialog(page, "dismiss");
await page.getByRole("switch", { name: "Tailscale", exact: true }).click();
expect(await question).toBe(TURN_OFF_QUESTION);
await page.waitForTimeout(500);
expect(new Set((await row()).map((state) => `${state.value} ${state.address}`))).toEqual(
new Set(["on true"]),
);
await expect(page.getByRole("switch", { name: "Tailscale", exact: true })).toBeChecked();
await expect(tailscaleAddressRow(page, address)).toBeVisible();
expect((await fetch(`http://${address}/api/health`)).ok).toBe(true);
}
/**
* Confirms turning Tailscale off over the Tailscale connection, which cuts this app off the host.
* Without the host the row shows no value at all, on or off.
*/
export async function confirmTailscaleTurnOff(page: Page, address: string): Promise<void> {
const question = answerNextDialog(page, "accept");
await page.getByRole("switch", { name: "Tailscale", exact: true }).click();
expect(await question).toBe(TURN_OFF_QUESTION);
await expect(page.getByText("Host is not connected", { exact: true })).toBeVisible();
await expect(page.getByRole("switch", { name: "Tailscale", exact: true })).toHaveCount(0);
await expectHostUnreachableAt(address);
}
function answerNextDialog(page: Page, answer: "accept" | "dismiss"): Promise<string> {
return new Promise((resolve) => {
page.once("dialog", async (dialog) => {
resolve(dialog.message());
await (answer === "accept" ? dialog.accept() : dialog.dismiss());
});
});
}
interface TailscaleRowState {
/** `none` while the row shows no value yet. */
value: "on" | "off" | "none";
address: boolean;
hint: string;
labelTop: number;
hintTop: number;
}
/**
* Records every state the Tailscale row commits, painted or not: from now on in this page, and
* from the first paint of every page load after it. Recording again starts a new record.
*/
async function recordTailscaleRow(page: Page): Promise<() => Promise<TailscaleRowState[]>> {
const record = () => {
const host = window as unknown as {
tailscaleRow?: { states: unknown[]; last: string; sample(): void };
};
if (host.tailscaleRow) {
host.tailscaleRow.states = [];
host.tailscaleRow.last = "";
host.tailscaleRow.sample();
return;
}
const isVisibleText = (element: Element, text?: string) =>
element.childElementCount === 0 &&
(text === undefined
? (element.textContent ?? "").trim() !== ""
: element.textContent === text) &&
element.getBoundingClientRect().height > 0;
const readValue = (toggle: Element | null) => {
if (!toggle) return "none";
return toggle.getAttribute("aria-checked") === "true" ? "on" : "off";
};
const read = () => {
const label = [...document.querySelectorAll("div, span")].find((element) =>
isVisibleText(element, "Tailscale"),
);
if (!label) return null;
let row: Element = label;
while (row.parentElement && !(row as HTMLElement).innerText.includes("\n")) {
row = row.parentElement;
}
const hint = [...row.querySelectorAll("div, span")].find(
(element) => element !== label && isVisibleText(element),
);
const toggle = document.querySelector('[role="switch"][aria-label="Tailscale"]');
return {
value: readValue(toggle),
address: document.querySelector('[data-testid="devices-tailscale-address"]') !== null,
hint: hint?.textContent ?? "",
labelTop: Math.round(label.getBoundingClientRect().top),
hintTop: Math.round(hint?.getBoundingClientRect().top ?? -1),
};
};
const recorder = {
states: [] as unknown[],
last: "",
sample() {
const state = read();
const key = JSON.stringify(state);
if (state && key !== recorder.last) recorder.states.push(state);
recorder.last = key;
},
};
host.tailscaleRow = recorder;
new MutationObserver(() => recorder.sample()).observe(document, {
subtree: true,
childList: true,
characterData: true,
attributes: true,
});
};
await page.addInitScript(record);
await page.evaluate(record);
return () =>
page.evaluate(
() =>
(window as unknown as { tailscaleRow: { states: TailscaleRowState[] } }).tailscaleRow
.states,
);
}
/**
* Runs `open`, which first shows the Tailscale row of a host with Tailscale on, and checks the row
* from its first state to its last: it starts with no value, never shows Tailscale off, and its
* label and hint keep their text and place until it settles on, with the address below.
*/
export async function expectTailscaleRowLoadsOn(
page: Page,
address: string,
open: () => Promise<void>,
): Promise<void> {
const row = await recordTailscaleRow(page);
await open();
await expect(page.getByRole("switch", { name: "Tailscale", exact: true })).toBeChecked();
await expect(tailscaleAddressRow(page, address)).toBeVisible();
const states = await row();
expect(states[0]?.value).toBe("none");
expect(states.filter((state) => state.value === "off")).toEqual([]);
expect(
new Set(states.map(({ hint, labelTop, hintTop }) => `${hint} ${labelTop} ${hintTop}`)).size,
).toBe(1);
expect(states.at(-1)).toMatchObject({ value: "on", address: true });
}
/**
* Holds every message between the app and the host on `port` for `ms` in each direction, as on a
* slow network. The returned function brings the connection back to full speed.
*/
export async function slowConnectionToHost(
page: Page,
port: number,
ms: number,
): Promise<() => void> {
let delay = ms;
await page.routeWebSocket(wsRoutePatternForPort(String(port)), (app) => {
const host = app.connectToServer();
app.onMessage(
deliverInOrderAfter(
() => delay,
(message) => host.send(message),
),
);
host.onMessage(
deliverInOrderAfter(
() => delay,
(message) => app.send(message),
),
);
});
return () => {
delay = 0;
};
}
function deliverInOrderAfter(
delay: () => number,
deliver: (message: string | Buffer) => void,
): (message: string | Buffer) => void {
const queue: { at: number; message: string | Buffer }[] = [];
let timer: ReturnType<typeof setTimeout> | null = null;
const flush = () => {
timer = null;
while (queue[0] && queue[0].at <= Date.now()) deliver(queue.shift()!.message);
if (queue[0]) timer = setTimeout(flush, queue[0].at - Date.now());
};
return (message) => {
queue.push({ at: Math.max(Date.now() + delay(), queue.at(-1)?.at ?? 0), message });
if (!timer) flush();
};
}
export async function expectTailscaleUpdateRequired(page: Page): Promise<void> {
await expect(page.getByRole("switch", { name: "Tailscale", exact: true })).toBeDisabled();
await expect(page.getByText("Update this host to use Tailscale", { exact: true })).toBeVisible();
await expect(page.getByRole("link", { name: "How to update", exact: true })).toBeVisible();
await openSettings(page);
await openSettingsHost(page, daemon.serverId);
await expect(page.getByTestId("host-page-pair-device-row")).toHaveCount(0);
await openSettingsHostSection(page, daemon.serverId, "pair-device");
await expect(page.getByTestId("host-page-pair-device-row")).toBeVisible();
}
export async function openPairDeviceModal(page: Page): Promise<void> {
await page.getByRole("button", { name: "Relay", exact: true }).click();
await expect(page.getByTestId("devices-relay-pairing")).toBeVisible();
await page.getByRole("button", { name: /Pair a device/ }).click();
await expect(page.getByTestId("host-page-pair-device-card")).toBeVisible();
}
export async function expectRelayConsent(page: Page): Promise<void> {
const modal = page.getByTestId("devices-relay-pairing");
const modal = page.getByTestId("host-page-pair-device-card");
await expect(modal.getByText("Enable relay?", { exact: true })).toBeVisible();
await expect(modal.getByText(/end-to-end encrypted/)).toBeVisible();
await expect(modal.getByRole("link", { name: "Read how Paseo relay works" })).toBeVisible();
@@ -376,7 +99,7 @@ export async function expectRelayConsent(page: Page): Promise<void> {
export async function declineRelay(page: Page): Promise<void> {
await page.getByRole("button", { name: "Not now", exact: true }).click();
await expect(page.getByTestId("devices-relay-pairing")).toHaveCount(0);
await expect(page.getByTestId("host-page-pair-device-card")).toHaveCount(0);
}
export async function enableRelayAndExpectOffer(page: Page): Promise<void> {
@@ -401,10 +124,10 @@ export async function expectPairingOffer(page: Page): Promise<void> {
export async function closePairDeviceModal(page: Page): Promise<void> {
await page
.getByTestId("devices-relay-pairing")
.getByTestId("host-page-pair-device-card")
.getByRole("button", { name: "Close", exact: true })
.click();
await expect(page.getByTestId("devices-relay-pairing")).toHaveCount(0);
await expect(page.getByTestId("host-page-pair-device-card")).toHaveCount(0);
}
export async function reloadAndOpenPairDevice(page: Page): Promise<void> {
@@ -422,7 +145,7 @@ export async function enableRelayAndExpectFailure(
expectedError = "Relay is controlled by a daemon launch override",
): Promise<void> {
await page.getByRole("button", { name: "Enable relay", exact: true }).click();
const modal = page.getByTestId("devices-relay-pairing");
const modal = page.getByTestId("host-page-pair-device-card");
await expect(modal.getByRole("alert")).toContainText(expectedError);
await expect(modal.getByRole("button", { name: "Retry", exact: true })).toBeEnabled();
await expect(modal.getByRole("textbox", { name: "Pairing link" })).toHaveCount(0);
@@ -432,7 +155,7 @@ export async function retryRelayAndExpectFailure(
page: Page,
expectedError = "Relay is controlled by a daemon launch override",
): Promise<void> {
const modal = page.getByTestId("devices-relay-pairing");
const modal = page.getByTestId("host-page-pair-device-card");
await modal.getByRole("button", { name: "Retry", exact: true }).click();
await expect(modal.getByRole("alert")).toContainText(expectedError);
await expect(modal.getByRole("button", { name: "Retry", exact: true })).toBeEnabled();
@@ -450,7 +173,7 @@ export async function openPairDeviceFromHome(page: Page): Promise<void> {
}
export async function expectRelayUpdateRequired(page: Page): Promise<void> {
const modal = page.getByTestId("devices-relay-pairing");
const modal = page.getByTestId("host-page-pair-device-card");
await expect(
modal.getByText("Update the host to enable relay from Paseo Desktop."),
).toBeVisible();
@@ -472,15 +195,15 @@ export function observePairingOfferRequests(page: Page, daemon: OutdatedDaemon):
}
export async function expectPairingDisconnected(page: Page): Promise<void> {
const modal = page.getByTestId("devices-relay-pairing");
const modal = page.getByTestId("host-page-pair-device-card");
await expect(modal.getByRole("alert")).toContainText("Host is not connected");
await expect(modal.getByRole("button", { name: "Retry", exact: true })).toBeVisible();
}
export async function switchPairDeviceToHost(page: Page, serverId: string): Promise<void> {
await selectSettingsHost(page, serverId);
await expectAppRoute(page, buildSettingsHostSectionRoute(serverId, "devices"));
await expect(page.getByTestId("devices-relay")).toBeVisible();
await expectAppRoute(page, buildSettingsHostSectionRoute(serverId, "pair-device"));
await expect(page.getByTestId("host-page-pair-device-row")).toBeVisible();
}
export async function openRelaySecurityDocs(page: Page): Promise<void> {
+1 -1
View File
@@ -66,7 +66,7 @@ export type SettingsSection = keyof typeof SECTION_LABELS;
type HostSection =
| "projects"
| "connections"
| "devices"
| "pair-device"
| "agents"
| "metadata"
| "voice"
@@ -1,33 +0,0 @@
import { once } from "node:events";
import path from "node:path";
import { z } from "zod";
import { killProcessTree, spawnTsx } from "./spawn-node";
const readySchema = z.object({ port: z.number(), serverId: z.string() });
export async function startTailscaleTestDaemon(origin: string) {
const entrypoint = path.resolve(
__dirname,
"../../../../server/src/server/test-utils/tailscale-daemon.ts",
);
const child = spawnTsx(entrypoint, [origin], {
stdio: ["ignore", "inherit", "inherit", "ipc"],
});
const signal = AbortSignal.timeout(30_000);
try {
const ready = await Promise.race([
once(child, "message", { signal }).then(([message]) => readySchema.parse(message)),
once(child, "exit", { signal }).then(([code]) => {
throw new Error(`Tailscale test daemon exited before startup with code ${code}`);
}),
]);
return {
...ready,
tailscaleAddress: `127.0.0.2:${ready.port}`,
close: () => killProcessTree(child),
};
} catch (error) {
await killProcessTree(child);
throw error;
}
}
@@ -23,7 +23,15 @@ export interface DraftAgentProfileControls {
}
export type AgentProfileApplyTarget =
| { kind: "agent"; agentId: string; availableModeIds: readonly string[] | null }
| {
kind: "agent";
agentId: string;
availableModeIds: readonly string[] | null;
currentProvider?: string | null;
isSwitchInFlight?: () => boolean;
onApplySameProvider?: () => void;
onStageProviderSwitch?: (profile: MaterializedAgentProfile) => void;
}
| { kind: "draft"; controls: DraftAgentProfileControls };
/** Everything the model picker renders for one profile. It never sees the profile itself. */
@@ -139,6 +147,16 @@ export function useAgentProfilePicker(
return;
}
if (
target.onStageProviderSwitch &&
(target.isSwitchInFlight?.() ||
(target.currentProvider && resolved.provider !== target.currentProvider))
) {
target.onStageProviderSwitch(resolved);
return;
}
target.onApplySameProvider?.();
const reconciled = reconcileMaterializedProfileMode(resolved, target.availableModeIds);
if (!reconciled) {
return;
@@ -148,7 +166,11 @@ export function useAgentProfilePicker(
return;
}
void client
.applyAgentConfig(target.agentId, toAgentConfigApply(reconciled))
.applyAgentConfig(
target.agentId,
toAgentConfigApply(reconciled),
target.currentProvider ? { expectedProvider: target.currentProvider } : undefined,
)
.then((notice) => showProviderNoticeToast(toast, notice))
.catch((error) => {
console.warn("[useAgentProfilePicker] applyAgentConfig failed", error);
@@ -56,6 +56,7 @@ export function ChatFind({
agentId,
serverId,
epoch,
rewindSeq,
items,
viewportRef,
revealLoadedMessage,
@@ -95,8 +96,8 @@ export function ChatFind({
);
const state = useSyncExternalStore(model.subscribe, model.getSnapshot, model.getSnapshot);
useEffect(() => {
model.updateHistory(epoch, items);
}, [model, epoch, items]);
model.updateHistory(epoch, items, rewindSeq);
}, [model, epoch, items, rewindSeq]);
useEffect(() => () => model.close(), [model]);
useEffect(() => {
if (!active) model.close();
@@ -18,7 +18,7 @@ function message(seq: number, text = "target"): StreamItem {
kind: "assistant_message",
text,
timestamp: new Date(0),
timelineCursor: { epoch: "epoch", seq },
timelineCursor: { epoch: "epoch", seq, anchorSeq: seq },
};
}
@@ -39,7 +39,7 @@ it("loads an older location and searches a response merged across suppressed tas
source.map((item, index) => ({
event: { type: "timeline" as const, provider: "claude" as const, item },
timestamp: new Date(0),
timelineCursor: { epoch: "epoch", seq: index + 1 },
timelineCursor: { epoch: "epoch", seq: index + 1, anchorSeq: index + 1 },
})),
{ source: "canonical" },
);
@@ -55,7 +55,7 @@ it("loads an older location and searches a response merged across suppressed tas
},
async load(_epoch, seq) {
loaded.push(seq);
model.updateHistory("epoch", history);
model.updateHistory("epoch", history, null);
},
async reveal(_id, _query, occurrence) {
revealed.push(occurrence);
@@ -64,7 +64,7 @@ it("loads an older location and searches a response merged across suppressed tas
clear() {},
});
try {
model.updateHistory("epoch", []);
model.updateHistory("epoch", [], null);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
@@ -99,7 +99,7 @@ it("skips a source-only candidate and highlights a displayed match", async () =>
clear() {},
});
try {
model.updateHistory("epoch", [message(1), message(2)]);
model.updateHistory("epoch", [message(1), message(2)], null);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().selectedItemId).toBe("row-2");
@@ -129,7 +129,7 @@ it("ignores replies after closing and does not navigate", async () => {
},
clear() {},
});
model.updateHistory("epoch", [message(1)]);
model.updateHistory("epoch", [message(1)], null);
model.open();
model.setQuery("target");
await expect.poll(() => calls).toEqual(["search"]);
@@ -155,7 +155,7 @@ it("retains a failed search for retry and distinguishes failure from zero matche
};
const model = new ChatFindModel(operations);
try {
model.updateHistory("epoch", []);
model.updateHistory("epoch", [], null);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().phase).toBe("error");
@@ -185,7 +185,7 @@ it("reports a failed timeline load as a connection failure", async () => {
clear() {},
});
try {
model.updateHistory("epoch", []);
model.updateHistory("epoch", [], null);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().phase).toBe("error");
@@ -207,24 +207,160 @@ it("reports a search result that outlived its epoch as a changed history", async
clear() {},
});
try {
model.updateHistory("epoch", [message(1)]);
model.updateHistory("epoch", [message(1)], null);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
model.updateHistory("epoch-2", [message(1)]);
model.updateHistory("epoch-2", [message(1)], null);
expect(model.getSnapshot()).toMatchObject({ phase: "error", failure: "historyChanged" });
} finally {
model.close();
}
});
it("reports results that a rewind took messages from as a changed history", async () => {
const model = new ChatFindModel({
async search() {
return response([{ seq: 2, role: "assistant" }]);
},
async load() {},
async reveal() {
return { count: 1, occurrence: 0 };
},
clear() {},
});
try {
model.updateHistory("epoch", [message(1), message(2)], null);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
expect(model.getSnapshot()).toMatchObject({ selectedItemId: "row-2", count: 1 });
// Another client rewinds the turn holding the match; the epoch stays.
model.updateHistory("epoch", [message(1)], 3);
expect(model.getSnapshot()).toMatchObject({
phase: "error",
failure: "historyChanged",
selectedItemId: null,
});
} finally {
model.close();
}
});
it("stops a search still receiving pages when a rewind lands between them", async () => {
let pages = 0;
let releaseSecondPage!: () => void;
const secondPage = new Promise<void>((resolve) => {
releaseSecondPage = resolve;
});
const model = new ChatFindModel({
async search(_query, cursor) {
pages += 1;
if (cursor === undefined)
return { ...response([{ seq: 2, role: "assistant" }]), nextCursor: 2 };
await secondPage;
return response([{ seq: 1, role: "assistant" }]);
},
async load() {},
async reveal() {
return { count: 1, occurrence: 0 };
},
clear() {},
});
try {
model.updateHistory("epoch", [message(1), message(2)], null);
model.open();
model.setQuery("target");
await expect.poll(() => pages).toBe(2);
model.updateHistory("epoch", [message(1)], 3);
releaseSecondPage();
await expect.poll(() => model.getSnapshot().failure).toBe("historyChanged");
expect(model.getSnapshot()).toMatchObject({ phase: "error", selectedItemId: null });
} finally {
model.close();
}
});
it.each([
["Next", "next"],
["Previous", "previous"],
] as const)("reports a rewind after %s as a changed history", async (_label, step) => {
const model = new ChatFindModel({
async search() {
return response([
{ seq: 1, role: "assistant" },
{ seq: 2, role: "assistant" },
]);
},
async load() {},
async reveal() {
return { count: 1, occurrence: 0 };
},
clear() {},
});
try {
model.updateHistory("epoch", [message(1), message(2)], null);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
model[step]();
await expect.poll(() => model.getSnapshot().selectedItemId).toBe("row-2");
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
model.updateHistory("epoch", [message(1)], 3);
expect(model.getSnapshot()).toMatchObject({
phase: "error",
failure: "historyChanged",
selectedItemId: null,
});
} finally {
model.close();
}
});
it("stops a pending Next when a rewind lands before it reveals", async () => {
let reveals = 0;
let revealSecond!: () => void;
const secondReveal = new Promise<void>((resolve) => {
revealSecond = resolve;
});
const model = new ChatFindModel({
async search() {
return response([
{ seq: 1, role: "assistant" },
{ seq: 2, role: "assistant" },
]);
},
async load() {},
async reveal() {
reveals += 1;
if (reveals > 1) await secondReveal;
return { count: 1, occurrence: 0 };
},
clear() {},
});
try {
model.updateHistory("epoch", [message(1), message(2)], null);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
model.next();
await expect.poll(() => reveals).toBe(2);
model.updateHistory("epoch", [message(1)], 3);
revealSecond();
await expect.poll(() => model.getSnapshot().failure).toBe("historyChanged");
expect(model.getSnapshot()).toMatchObject({ phase: "error", selectedItemId: null });
} finally {
model.close();
}
});
it("can load a search location before the initial chat history has arrived", async () => {
const model = new ChatFindModel({
async search() {
return response([{ seq: 1, role: "assistant" }]);
},
async load() {
model.updateHistory("epoch", [message(1)]);
model.updateHistory("epoch", [message(1)], null);
},
async reveal() {
return { count: 1, occurrence: 0 };
@@ -232,7 +368,7 @@ it("can load a search location before the initial chat history has arrived", asy
clear() {},
});
try {
model.updateHistory(null, []);
model.updateHistory(null, [], null);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
@@ -260,7 +396,7 @@ it("reports the position across the whole chat and corrects it with rendered cou
clear() {},
});
try {
model.updateHistory("epoch", [message(1), message(2)]);
model.updateHistory("epoch", [message(1), message(2)], null);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
@@ -297,7 +433,7 @@ it("counts one match per message from a host that reports no counts", async () =
clear() {},
});
try {
model.updateHistory("epoch", [message(1), message(2)]);
model.updateHistory("epoch", [message(1), message(2)], null);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
@@ -76,6 +76,10 @@ export class ChatFindModel {
private items: StreamItem[] = [];
private epoch: string | null = null;
private resultEpoch: string | null = null;
/** The latest rewind applied to the history. A rewind keeps the epoch and retires messages. */
private rewindSeq: number | null = null;
/** The latest rewind when the current result set's search started; undefined until a search starts. */
private searchedRewindSeq: number | null | undefined = undefined;
private locations: Location[] = [];
private resolved = new Map<Location, Target>();
private current = -1;
@@ -113,6 +117,7 @@ export class ChatFindModel {
this.cancel();
this.locations = [];
this.resultEpoch = null;
this.searchedRewindSeq = undefined;
this.resolved.clear();
this.current = -1;
this.inMessage = { occurrence: 0, count: 0 };
@@ -144,6 +149,7 @@ export class ChatFindModel {
});
}
private async search(signal: AbortSignal) {
this.searchedRewindSeq = this.rewindSeq;
try {
let cursor: number | undefined;
do {
@@ -168,15 +174,14 @@ export class ChatFindModel {
this.fail(error, signal);
}
}
updateHistory(epoch: string | null, items: StreamItem[]) {
if (
this.resultEpoch !== null &&
epoch !== null &&
epoch !== this.resultEpoch &&
this.state.open
) {
/** `rewindSeq` is the sequence number of the latest rewind applied to this history. */
updateHistory(epoch: string | null, items: StreamItem[], rewindSeq: number | null) {
const replaced = this.resultEpoch !== null && epoch !== null && epoch !== this.resultEpoch;
const rewound = this.searchedRewindSeq !== undefined && rewindSeq !== this.searchedRewindSeq;
if ((replaced || rewound) && this.state.open) {
this.fail(new ChatFindFailureError("historyChanged"), this.abort.signal);
}
this.rewindSeq = rewindSeq;
this.epoch = epoch;
this.items = items;
this.historyListeners.forEach((listener) => listener());
@@ -9,6 +9,8 @@ export interface ChatFindProps {
agentId: string;
serverId: string;
epoch: string | null;
/** The sequence number of the latest rewind applied to this history, if any. */
rewindSeq: number | null;
items: StreamItem[];
viewportRef: RefObject<StreamViewportHandle | null>;
revealLoadedMessage(messageId: string): boolean;
@@ -139,7 +139,7 @@ describe("useChatOutline", () => {
kind: "user_message",
text: "live prompt",
timestamp: new Date(seq),
timelineCursor: { epoch: "epoch-1", seq },
timelineCursor: { epoch: "epoch-1", seq, anchorSeq: seq },
});
rerender({ tail: [loadedPrompt(2)] });
await waitFor(() => expect(runtime.listAgentTimelinePrompts).toHaveBeenCalledTimes(2));
@@ -198,7 +198,7 @@ describe("useChatOutline", () => {
kind: "assistant_message",
text: "chunk",
timestamp: new Date(),
timelineCursor: { epoch: "epoch-1", seq: 2 },
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 2 },
},
],
timelineEpoch: "epoch-1",
@@ -219,7 +219,7 @@ describe("useChatOutline", () => {
kind: "user_message",
text: "Replaced conversation",
timestamp: new Date(2),
timelineCursor: { epoch: "epoch-2", seq: 1 },
timelineCursor: { epoch: "epoch-2", seq: 1, anchorSeq: 1 },
},
],
timelineEpoch: "epoch-2",
@@ -275,7 +275,7 @@ describe("useChatOutline", () => {
kind: "user_message" as const,
text: "prompt",
timestamp: new Date(1),
timelineCursor: { epoch: "epoch-1", seq: 1 },
timelineCursor: { epoch: "epoch-1", seq: 1, anchorSeq: 1 },
},
];
const { result, rerender } = renderHook(
@@ -326,7 +326,7 @@ describe("useChatOutline", () => {
kind: "user_message" as const,
text: "prompt",
timestamp: new Date(1),
timelineCursor: { epoch: "epoch-1", seq: 1 },
timelineCursor: { epoch: "epoch-1", seq: 1, anchorSeq: 1 },
};
const { result, rerender } = renderHook(
({ tail, mountedHistoryMessageIds }) =>
@@ -381,7 +381,7 @@ describe("useChatOutline", () => {
kind: "user_message" as const,
text: "prompt",
timestamp: new Date(2),
timelineCursor: { epoch: "epoch-1", seq: 2 },
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 2 },
};
const revealLoadedMessage = vi.fn();
revealLoadedMessage.mockReturnValue(false);
@@ -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;
@@ -1,8 +1,8 @@
import { Redirect, useLocalSearchParams } from "expo-router";
import { useLocalSearchParams } from "expo-router";
import { useMemo } from "react";
import { HostRouteBootstrapBoundary } from "@/components/host-route-bootstrap-boundary";
import SettingsScreen from "@/screens/settings-screen";
import { buildSettingsHostSectionRoute, normalizeHostSectionSlug } from "@/utils/host-routes";
import { normalizeHostSectionSlug } from "@/utils/host-routes";
export default function SettingsHostSectionRoute() {
const params = useLocalSearchParams<{ serverId?: string; hostSection?: string }>();
@@ -11,10 +11,6 @@ export default function SettingsHostSectionRoute() {
const section = normalizeHostSectionSlug(rawSection) ?? "connections";
const view = useMemo(() => ({ kind: "host" as const, serverId, section }), [serverId, section]);
if (rawSection === "pair-device" && serverId) {
return <Redirect href={buildSettingsHostSectionRoute(serverId, "devices")} />;
}
return (
<HostRouteBootstrapBoundary>
<SettingsScreen view={view} />
@@ -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}>
+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;
@@ -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<
@@ -1,7 +1,9 @@
import { useCallback, useMemo, useState, type ReactNode } from "react";
import { Children, isValidElement, useCallback, useMemo, useState, type ReactNode } from "react";
import { View } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { isWeb } from "@/constants/platform";
import { SettingsRowChildren } from "./row-children";
import { settingsStyles } from "@/styles/settings";
import { NestedSettingsRows } from "./row-density";
import { SettingsRowHeader } from "./row-header";
interface SettingsCollapsibleRowProps {
@@ -46,7 +48,27 @@ export function SettingsCollapsibleRow({
webAccessibilityProps={webExpandedProps}
testID={testID ? `${testID}-toggle` : undefined}
/>
{expanded ? <SettingsRowChildren>{children}</SettingsRowChildren> : null}
{expanded ? (
<View style={styles.children}>
<NestedSettingsRows>
{Children.toArray(children).map((child, index) => (
<View
key={isValidElement(child) ? child.key : index}
style={settingsStyles.rowBorder}
>
{child}
</View>
))}
</NestedSettingsRows>
</View>
) : null}
</View>
);
}
const styles = StyleSheet.create((theme) => ({
// The revealed rows keep the card's rails; the tint is what groups them under their header.
children: {
backgroundColor: theme.colors.surface0,
},
}));
+19 -32
View File
@@ -25,10 +25,7 @@ import { DropdownTrigger } from "@/components/ui/dropdown-trigger";
import { useIsCompactFormFactor } from "@/constants/layout";
import { settingsStyles } from "@/styles/settings";
import { ControlSizeProvider } from "@/components/ui/control-size";
import { ExternalLink, type ExternalLinkProps } from "@/components/ui/external-link";
import { useSettingsRowLayout } from "./row-density";
import { SettingsRowTitle } from "./row-label";
export { SettingsRowChildren } from "./row-children";
export { SettingsGroup } from "./headings/settings-group";
export { SettingsSection } from "./headings/settings-section";
export { SettingsCollapsibleRow } from "./collapsible-row";
@@ -39,16 +36,11 @@ export { SettingsBackLink, SettingsDetailHeader } from "./detail-header";
export { SettingsInfoTip } from "./headings/settings-info-tip";
export { MenuSettingsRows } from "./row-density";
/**
* What app screens can add to a plugin-facing row: an accessory beside the label, such as an info
* tip, an icon before the label, and a link to a page outside the app under the hint.
*/
/** What app screens can add to a plugin-facing row: an accessory beside the label, such as an info tip. */
interface AppRowExtras {
labelAccessory?: ReactNode;
/** An icon before the label, such as the thing the row is about. */
leading?: ReactNode;
/** A page outside the app that helps with this row, drawn under the hint as "Label ↗". */
link?: Pick<ExternalLinkProps, "href" | "label" | "accessibilityLabel">;
}
interface AppSettingsRowProps extends Omit<SettingsRowProps, "hint">, AppRowExtras {
@@ -75,7 +67,6 @@ export function SettingsRow({
leading,
labelAccessory,
hint,
link,
error,
children,
testID,
@@ -83,17 +74,20 @@ export function SettingsRow({
const compact = useIsCompactFormFactor();
const layout = useSettingsRowLayout();
const rowStyle = useMemo(() => [layout.row, compact && styles.compactRow], [compact, layout]);
const accessoryTitleStyle = useMemo(() => [layout.title, styles.accessoryLabel], [layout]);
return (
<View style={rowStyle} testID={testID}>
{leading ? <View style={styles.leading}>{leading}</View> : null}
<View style={styles.label}>
<SettingsRowTitle label={label} accessory={labelAccessory} />
{typeof hint === "string" ? <Text style={layout.hint}>{hint}</Text> : hint}
{link ? (
<View style={styles.link}>
<ExternalLink {...link} />
{labelAccessory ? (
<View style={styles.labelRow}>
<Text style={accessoryTitleStyle}>{label}</Text>
{labelAccessory}
</View>
) : null}
) : (
<Text style={layout.title}>{label}</Text>
)}
{typeof hint === "string" ? <Text style={layout.hint}>{hint}</Text> : hint}
{error ? (
<Text accessibilityRole="alert" style={settingsStyles.rowError}>
{error}
@@ -109,15 +103,7 @@ export function SettingsRow({
);
}
/** A switch row. App screens may pass `null` while the value is not known yet; see `Switch`. */
export function SettingsSwitch({
value,
onValueChange,
disabled,
...row
}: Omit<SettingsSwitchProps, "onValueChange" | "value"> &
Partial<Pick<SettingsSwitchProps, "onValueChange">> &
AppRowExtras & { value: boolean | null }) {
export function SettingsSwitch({ value, onValueChange, disabled, ...row }: SettingsSwitchProps) {
return (
<SettingsRow {...row}>
<Switch
@@ -218,12 +204,7 @@ export function SettingsInput({
);
}
export function SettingsAction({
actionLabel,
onPress,
disabled,
...row
}: SettingsActionProps & AppRowExtras) {
export function SettingsAction({ actionLabel, onPress, disabled, ...row }: SettingsActionProps) {
return (
<SettingsRow {...row}>
<Button variant="outline" onPress={onPress} disabled={disabled}>
@@ -240,7 +221,13 @@ const styles = StyleSheet.create((theme) => ({
// The same leading slot as `SettingsRowHeader`, so icons and labels share rails across row kinds.
leading: { marginRight: theme.spacing[3], alignItems: "center", justifyContent: "center" },
label: { flexGrow: 1, flexShrink: 1, flexBasis: 160, marginRight: theme.spacing[3] },
link: { alignItems: "flex-start", marginTop: theme.spacing[1] },
labelRow: {
flexDirection: "row",
flexWrap: "wrap",
alignItems: "center",
gap: theme.spacing[2],
},
accessoryLabel: { flexShrink: 1, minWidth: 0 },
control: { flexShrink: 1, maxWidth: "100%" },
input: { minWidth: 180 },
}));
@@ -1,30 +0,0 @@
import { Children, isValidElement, type ReactNode } from "react";
import { View } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { settingsStyles } from "@/styles/settings";
import { NestedSettingsRows } from "./row-density";
/**
* Rows that belong to the row above them, such as the rows an expanded row reveals or the details
* a switch turns on. They sit in the same card on a tinted band, laid out as nested rows.
*/
export function SettingsRowChildren({ children }: { children: ReactNode }) {
return (
<View style={styles.band}>
<NestedSettingsRows>
{Children.toArray(children).map((child, index) => (
<View key={isValidElement(child) ? child.key : index} style={settingsStyles.rowBorder}>
{child}
</View>
))}
</NestedSettingsRows>
</View>
);
}
const styles = StyleSheet.create((theme) => ({
// The rows keep the card's rails; the tint is what groups them under the row above.
band: {
backgroundColor: theme.colors.surface0,
},
}));
@@ -11,7 +11,6 @@ import { SkeletonPulse, useSkeletonPulse } from "@/components/ui/skeleton";
import { settingsStyles } from "@/styles/settings";
import { ICON_SIZE, type Theme } from "@/styles/theme";
import { useSettingsRowLayout, type SettingsRowLayout } from "./row-density";
import { SettingsRowTitle } from "./row-label";
const ThemedChevron = withUnistyles(ChevronRight);
const ThemedLoadingSpinner = withUnistyles(LoadingSpinner);
@@ -119,8 +118,9 @@ export function SettingsRowHeader({
</View>
) : null}
<View style={[contentStyle, styles.passThrough]}>
<View {...HIDDEN_FROM_ASSISTIVE_TECH}>
<SettingsRowTitle label={label} accessory={labelAccessory} />
<View style={labelAccessory ? styles.labelRow : undefined} {...HIDDEN_FROM_ASSISTIVE_TECH}>
<Text style={layout.title}>{label}</Text>
{labelAccessory}
</View>
{hintStatus ? (
<RowHintLine hint={hint} status={hintStatus} hintStyle={layout.hint} />
@@ -293,6 +293,7 @@ const styles = StyleSheet.create((theme) => ({
borderRadius: theme.borderRadius.sm,
backgroundColor: theme.colors.surface2,
},
labelRow: { flexDirection: "row", alignItems: "center", gap: theme.spacing[2] },
summary: {
flexShrink: 1,
color: theme.colors.foregroundMuted,
@@ -1,34 +0,0 @@
import { useMemo, type ReactNode } from "react";
import { Text, View } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { useSettingsRowLayout } from "./row-density";
/**
* A row's label line: the label, and beside it an accessory such as a badge or an info tip. Rows
* with inline controls and rows that lead somewhere both draw it, so their labels and hints keep
* the same distances whether or not a row carries an accessory.
*/
export function SettingsRowTitle({ label, accessory }: { label: string; accessory?: ReactNode }) {
const layout = useSettingsRowLayout();
const titleStyle = useMemo(() => [layout.title, styles.title], [layout]);
if (!accessory) return <Text style={layout.title}>{label}</Text>;
return (
<View style={styles.line}>
<Text style={titleStyle}>{label}</Text>
<View style={styles.accessory}>{accessory}</View>
</View>
);
}
const styles = StyleSheet.create((theme) => ({
line: {
flexDirection: "row",
flexWrap: "wrap",
alignItems: "center",
gap: theme.spacing[2],
},
title: { flexShrink: 1, minWidth: 0 },
// An accessory is taller than the label's line. It hangs into the row's padding instead, so the
// label and hint keep the distances of a row without one.
accessory: { marginVertical: -theme.spacing[1] },
}));
+3 -17
View File
@@ -1,7 +1,6 @@
import { useCallback, useMemo } from "react";
import {
Pressable,
View,
type GestureResponderEvent,
type StyleProp,
type ViewStyle,
@@ -20,11 +19,7 @@ import { useIsCompactFormFactor } from "@/constants/layout";
import type { Theme } from "@/styles/theme";
interface SwitchProps {
/**
* `null` while the value is not known yet, such as while it loads from a host. The switch's space
* stays reserved and empty, so the switch takes it when the value arrives and nothing moves.
*/
value: boolean | null;
value: boolean;
onValueChange?: (value: boolean) => void;
disabled?: boolean;
accessibilityLabel?: string;
@@ -114,7 +109,7 @@ export function Switch({
const handlePress = useCallback(
(event: GestureResponderEvent) => {
event.stopPropagation();
if (disabled || value === null) return;
if (disabled) return;
onValueChange?.(!value);
},
[disabled, onValueChange, value],
@@ -124,10 +119,7 @@ export function Switch({
const isCompact = useIsCompactFormFactor();
const geometry = useMemo(() => switchGeometryForLayout(size, isCompact), [size, isCompact]);
const accessibilityState = useMemo(
() => ({ checked: value === true, disabled }),
[value, disabled],
);
const accessibilityState = useMemo(() => ({ checked: value, disabled }), [value, disabled]);
const pressableStyle = useMemo(
() => [
styles.switchControl,
@@ -142,12 +134,6 @@ export function Switch({
],
[disabled, geometry.hitHeight, geometry.trackHeight, style],
);
const unknownStyle = useMemo(
() => [{ width: geometry.trackWidth, minHeight: geometry.trackHeight }, style],
[geometry.trackWidth, geometry.trackHeight, style],
);
if (value === null) return <View style={unknownStyle} testID={testID} />;
return (
<Pressable
+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 | Promise<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.submission.accept(input.agentId, clientMessageId);
await input.onProviderSwitchCommitted?.(result.agent);
return;
}
await input.client.sendAgentMessage(input.agentId, input.text, {
messageId: clientMessageId,
...(input.activeTurnBehavior ? { activeTurnBehavior: input.activeTurnBehavior } : {}),
@@ -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) {
await input.onProviderSwitchCommitted?.(error.agent);
}
throw error;
}
}
@@ -16,12 +16,21 @@ import { formatThinkingOptionLabel } from "@/agent-controls/labels";
import { CombinedModelSelector } from "@/components/combined-model-selector";
import {
buildProviderSelectorProviders,
buildSelectableProviderSelectorProviders,
buildSelectorProvider,
type ProviderSelectorProvider,
} from "@/provider-selection/provider-selection";
import { filterSelectableModels } from "@/provider-selection/model-catalog";
import { useSessionStore } from "@/stores/session-store";
import { useProvidersSnapshot } from "@/hooks/use-providers-snapshot";
import { useDraftProviderOptions } from "@/hooks/use-draft-provider-options";
import {
clearStagedProviderSwitch,
isStagedProviderSwitchInFlight,
type StagedProviderSwitch,
useStagedProviderSwitch,
useStagedProviderSwitchStore,
} from "@/composer/provider-switch";
import { resolveProviderDefinition } from "@/utils/provider-definitions";
import { mergeProviderPreferences, useFormPreferences } from "@/hooks/use-form-preferences";
import {
@@ -102,6 +111,7 @@ import {
type AgentProfilePicker,
type AgentProfileSeed,
type DraftAgentProfileControls,
type MaterializedAgentProfile,
} from "@/agent-profiles";
import { buildSettingsHostSectionRoute } from "@/utils/host-routes";
@@ -138,6 +148,7 @@ interface ControlledAgentControlsProps {
modeControl?: AgentModeControlValue | null;
modelSelectorServerId?: string | null;
isCompactLayout?: boolean;
openModelBrowserAtProviders?: boolean;
}
export interface DraftAgentControlsProps {
@@ -451,6 +462,7 @@ function ControlledAgentControls({
modeControl,
modelSelectorServerId = null,
isCompactLayout,
openModelBrowserAtProviders,
}: ControlledAgentControlsProps) {
const { t } = useTranslation();
const isCompactFormFactor = useIsCompactFormFactor();
@@ -710,6 +722,7 @@ function ControlledAgentControls({
showLabels={presentation.showModelLabel}
modelSelectorServerId={modelSelectorServerId}
canSwitchProvider={Boolean(onSelectProviderAndModel)}
openModelBrowserAtProviders={openModelBrowserAtProviders}
/>
)}
{!isCompact ? (
@@ -907,6 +920,7 @@ interface SheetAgentControlsContentProps extends AgentControlsContentProps {
displayThinking: string | null;
handleSheetModelSelect: (providerId: string, modelId: string) => void;
canSwitchProvider: boolean;
openModelBrowserAtProviders?: boolean;
}
function SheetAgentControlsContent(props: SheetAgentControlsContentProps) {
@@ -939,6 +953,7 @@ function SheetAgentControlsContent(props: SheetAgentControlsContentProps) {
showLabels,
modelSelectorServerId,
canSwitchProvider,
openModelBrowserAtProviders,
} = props;
const sheetControls = (
@@ -988,6 +1003,7 @@ function SheetAgentControlsContent(props: SheetAgentControlsContentProps) {
glyphs={glyphs}
showLabels={showLabels}
canSwitchProvider={canSwitchProvider}
openModelBrowserAtProviders={openModelBrowserAtProviders}
>
{sheetControls}
</CompactModelSheet>
@@ -1006,6 +1022,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,
@@ -1013,15 +1171,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,
@@ -1031,24 +1196,35 @@ export const AgentControls = memo(function AgentControls({
refetchIfStale: refetchSnapshotIfStale,
} = useProvidersSnapshot(serverId, { cwd: agent?.cwd });
const stagedProvider = activeStagedSwitch ? activeStagedSwitch.provider : null;
const effectiveProvider = stagedProvider ?? agent?.provider;
const stagedProviderRef = useRef<AgentProvider | null>(stagedProvider);
stagedProviderRef.current = stagedProvider;
const snapshotSelectedEntry = useMemo(
() => resolveProviderSnapshotEntry(snapshotEntries, agent?.provider),
[snapshotEntries, agent?.provider],
() => resolveProviderSnapshotEntry(snapshotEntries, effectiveProvider),
[snapshotEntries, effectiveProvider],
);
const models = filterSelectableModels(snapshotSelectedEntry?.models ?? null);
const selectedProviderIsLoading = snapshotSelectedEntry?.status === "loading";
const agentProviderDefinitions = useMemo(
() => buildAgentProviderDefinitions(agent?.provider, snapshotEntries),
[agent?.provider, snapshotEntries],
() => buildAgentProviderDefinitions(effectiveProvider, snapshotEntries),
[effectiveProvider, snapshotEntries],
);
const agentProviderModels = useMemo(
() => buildAgentProviderModels(agent?.provider, models),
[agent?.provider, models],
() => buildAgentProviderModels(effectiveProvider, models),
[effectiveProvider, models],
);
const agentModelSelectorProviders = useMemo(() => {
if (supportsProviderSwitching && snapshotEntries && snapshotEntries.length > 0) {
const selectable = buildSelectableProviderSelectorProviders(snapshotEntries, {
selectedProvider: effectiveProvider ?? null,
});
if (selectable.length > 0) return selectable;
}
if (snapshotSelectedEntry) {
return [buildSelectorProvider(snapshotSelectedEntry)];
}
@@ -1056,14 +1232,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[]>(() => {
@@ -1080,13 +1261,71 @@ export const AgentControls = memo(function AgentControls({
const agentProvider = agent?.provider;
const activeModelId = modelSelection.activeModelId;
const handleSelectModel = useCallback(
const stagedModeOptions = useMemo<AgentMode[]>(() => {
if (!activeStagedSwitch || !snapshotSelectedEntry?.modes) return [];
return snapshotSelectedEntry.modes.map((mode) => ({
id: mode.id,
label: mode.label,
description: mode.description ?? "",
}));
}, [activeStagedSwitch, snapshotSelectedEntry?.modes]);
const handleSelectStagedMode = useCallback(
(modeId: string) => {
useStagedProviderSwitchStore.getState().patch(serverId, agentId, (current) => ({
...current,
modeId,
}));
},
[agentId, serverId],
);
const modeControl = useMemo<AgentModeControlValue | null>(() => {
if (!activeStagedSwitch) return liveModeControl;
if (stagedModeOptions.length === 0) return null;
return {
provider: activeStagedSwitch.provider,
providerDefinitions: agentProviderDefinitions,
modeOptions: stagedModeOptions,
selectedModeId:
activeStagedSwitch.modeId ??
snapshotSelectedEntry?.defaultModeId ??
stagedModeOptions[0]?.id ??
null,
onSelectMode: handleSelectStagedMode,
disabled: !client,
};
}, [
activeStagedSwitch,
agentProviderDefinitions,
client,
handleSelectStagedMode,
liveModeControl,
snapshotSelectedEntry?.defaultModeId,
stagedModeOptions,
]);
const commandCenterModes = toCommandCenterModes(modeControl);
const modeProviderDefinitions = getModeProviderDefinitions(modeControl);
const getStagedProvider = useCallback(() => stagedProviderRef.current, []);
const stagedDraftOptions = useDraftProviderOptions(
buildStagedDraftOptionsParams({
serverId,
agentCwd: agent?.cwd,
activeStagedSwitch,
getProvider: getStagedProvider,
modelId: modelSelection.activeModelId,
thinkingOptionId: modelSelection.selectedThinkingId,
}),
);
const applyLiveModel = useCallback(
async (modelId: string) => {
if (!client || !agentProvider) {
return;
}
try {
await client.setAgentModel(agentId, modelId);
await client.setAgentModel(agentId, modelId, { expectedProvider: agentProvider });
await updatePreferences((current) =>
mergeProviderPreferences({
preferences: current,
@@ -1101,21 +1340,147 @@ export const AgentControls = memo(function AgentControls({
},
[agentId, agentProvider, client, toast, updatePreferences],
);
const handleSelectCommandCenterModel = useCallback(
(_provider: AgentProvider, modelId: string) => handleSelectModel(modelId),
[handleSelectModel],
const handleSelectModel = useCallback(
async (modelId: string) => {
if (activeStagedSwitch) {
const nextModel = models?.find((candidate) => candidate.id === modelId);
const preferredThinking =
preferences.providerPreferences?.[activeStagedSwitch.provider]?.thinkingByModel?.[
modelId
];
const nextThinking =
preferredThinking ??
nextModel?.defaultThinkingOptionId ??
nextModel?.thinkingOptions?.[0]?.id ??
null;
useStagedProviderSwitchStore.getState().patch(serverId, agentId, (current) => ({
...current,
model: modelId,
thinkingOptionId: nextThinking,
}));
return;
}
await applyLiveModel(modelId);
},
[
activeStagedSwitch,
agentId,
applyLiveModel,
models,
preferences.providerPreferences,
serverId,
],
);
// A running agent is one provider's process, so only that provider's profiles
// can apply to it.
const profileProviders = useMemo(() => (agentProvider ? [agentProvider] : []), [agentProvider]);
const handleSelectProviderAndModel = useCallback(
(nextProvider: string, modelId: string) => {
if (!agentProvider) return;
if (nextProvider === agentProvider && !isStagedProviderSwitchInFlight(serverId, agentId)) {
clearStagedProviderSwitch(serverId, agentId);
const liveModelId = agent?.runtimeModelId ?? agent?.model ?? null;
if (modelId && modelId !== liveModelId) {
void applyLiveModel(modelId);
}
return;
}
if (!supportsProviderSwitching) return;
useStagedProviderSwitchStore.getState().stage(
serverId,
agentId,
buildStagedProviderSwitchDraft({
nextProvider,
modelId,
snapshotEntries,
providerPreferences: preferences.providerPreferences,
}),
);
},
[
agent?.model,
agent?.runtimeModelId,
agentId,
agentProvider,
applyLiveModel,
preferences.providerPreferences,
serverId,
snapshotEntries,
supportsProviderSwitching,
],
);
const handleSelectCommandCenterModel = useCallback(
(provider: AgentProvider, modelId: string) => {
if (supportsProviderSwitching) {
handleSelectProviderAndModel(provider, modelId);
return;
}
void handleSelectModel(modelId);
},
[handleSelectModel, handleSelectProviderAndModel, supportsProviderSwitching],
);
const handleStageAgentProfileSwitch = useCallback(
(resolved: MaterializedAgentProfile) => {
if (!supportsProviderSwitching) return;
const nextEntry = resolveProviderSnapshotEntry(snapshotEntries, resolved.provider);
const modeIds = resolveSnapshotModeIds(nextEntry);
const validModeId =
resolved.modeId && (!modeIds || modeIds.includes(resolved.modeId))
? resolved.modeId
: (nextEntry?.defaultModeId ?? nextEntry?.modes?.[0]?.id ?? null);
useStagedProviderSwitchStore.getState().stage(serverId, agentId, {
provider: resolved.provider,
model: resolved.modelId ?? null,
modeId: validModeId,
thinkingOptionId: resolved.thinkingOptionId ?? null,
providerOptions: resolved.options ? { ...resolved.options } : {},
});
stagedDraftOptions.applyProfile({
provider: resolved.provider,
options: resolved.options ?? {},
});
},
[agentId, serverId, snapshotEntries, stagedDraftOptions, supportsProviderSwitching],
);
const handleClearStagedSwitchOnProfile = useCallback(() => {
clearStagedProviderSwitch(serverId, agentId);
}, [agentId, serverId]);
const profileProviders = useMemo(() => {
if (supportsProviderSwitching) {
return agentModelSelectorProviders.map((entry) => entry.id);
}
return agentProvider ? [agentProvider] : [];
}, [agentModelSelectorProviders, agentProvider, supportsProviderSwitching]);
const liveSnapshotEntry = useMemo(
() => resolveProviderSnapshotEntry(snapshotEntries, agentProvider),
[snapshotEntries, agentProvider],
);
const profileModeIds = useMemo(
() => resolveSnapshotModeIds(snapshotSelectedEntry),
[snapshotSelectedEntry],
() => resolveSnapshotModeIds(liveSnapshotEntry),
[liveSnapshotEntry],
);
const profileTarget = useMemo<AgentProfileApplyTarget>(
() => ({ kind: "agent", agentId, availableModeIds: profileModeIds }),
[agentId, profileModeIds],
() => ({
kind: "agent",
agentId,
availableModeIds: profileModeIds,
currentProvider: agentProvider,
isSwitchInFlight: () => isStagedProviderSwitchInFlight(serverId, agentId),
onApplySameProvider: handleClearStagedSwitchOnProfile,
onStageProviderSwitch: supportsProviderSwitching ? handleStageAgentProfileSwitch : undefined,
}),
[
agentId,
agentProvider,
handleClearStagedSwitchOnProfile,
handleStageAgentProfileSwitch,
profileModeIds,
serverId,
supportsProviderSwitching,
],
);
const agentProfiles = useAgentProfilePicker({
serverId,
@@ -1128,6 +1493,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;
}
@@ -1148,18 +1520,35 @@ export const AgentControls = memo(function AgentControls({
});
}
void client
.setAgentThinkingOption(agentId, thinkingOptionId)
.setAgentThinkingOption(agentId, thinkingOptionId, { expectedProvider: agentProvider })
.then((notice) => showProviderNoticeToast(toast, notice))
.catch((error) => {
console.warn("[AgentControls] setAgentThinkingOption failed", error);
toast.error(toErrorMessage(error));
});
},
[activeModelId, agentId, agentProvider, client, toast, updatePreferences],
[
activeModelId,
activeStagedSwitch,
agentId,
agentProvider,
client,
serverId,
toast,
updatePreferences,
],
);
const handleSetOption = useCallback(
(key: string, value: unknown) => {
if (activeStagedSwitch) {
stagedDraftOptions.setOption(key, value);
useStagedProviderSwitchStore.getState().patch(serverId, agentId, (current) => ({
...current,
providerOptions: { ...current.providerOptions, [key]: value },
}));
return;
}
if (!client || !agentProvider) {
return;
}
@@ -1176,15 +1565,36 @@ export const AgentControls = memo(function AgentControls({
).catch((error) => {
console.warn("[AgentControls] persist option preference failed", error);
});
void client.setAgentOptions(agentId, { [key]: value }).catch((error) => {
console.warn("[AgentControls] setAgentOptions failed", error);
toast.error(toErrorMessage(error));
});
void client
.setAgentOptions(agentId, { [key]: value }, { expectedProvider: agentProvider })
.catch((error) => {
console.warn("[AgentControls] setAgentOptions failed", error);
toast.error(toErrorMessage(error));
});
},
[agentId, agentProvider, client, toast, updatePreferences],
[
activeStagedSwitch,
agentId,
agentProvider,
client,
serverId,
stagedDraftOptions,
toast,
updatePreferences,
],
);
const agentOptionControls = useAgentOptionControls(agent, handleSetOption);
const liveOptionControls = useAgentOptionControls(agent, handleSetOption);
const agentOptionControls = useMemo<ComposerOptionControls>(
() =>
resolveAgentOptionControlsForComposer({
activeStagedSwitch,
stagedControls: stagedDraftOptions.optionControls,
liveOptionControls,
onSetOption: handleSetOption,
}),
[activeStagedSwitch, handleSetOption, liveOptionControls, stagedDraftOptions.optionControls],
);
// The agent's composer exists apart from this component; while this is mounted, prompt
// commands go through the input the user is typing in.
@@ -1208,12 +1618,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,
},
@@ -1232,7 +1642,7 @@ export const AgentControls = memo(function AgentControls({
client,
agentId,
agentModelSelectorProviders,
agentProvider,
effectiveProvider,
commandCenterModes,
handleSelectCommandCenterModel,
handleSelectThinkingOption,
@@ -1252,8 +1662,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) => {
@@ -1266,6 +1676,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}
@@ -1273,21 +1695,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}
@@ -1521,6 +1939,7 @@ export function DraftAgentControls({
modeControl={modeControl}
modelSelectorServerId={modelSelectorServerId}
isCompactLayout={isCompactLayout}
openModelBrowserAtProviders
/>
</>
) : null}
@@ -282,7 +282,7 @@ export function useLiveAgentModeControl(
console.warn("[AgentModeControl] persist mode preference failed", error);
});
void client
.setAgentMode(agentId, modeId)
.setAgentMode(agentId, modeId, { expectedProvider: slice.provider })
.then((notice) => showProviderNoticeToast(toast, notice))
.catch((error) => {
console.warn("[AgentModeControl] setAgentMode failed", error);
@@ -13,17 +13,17 @@ describe("model sheet opening", () => {
it("starts drafts at providers even when only one provider is available", () => {
expect(
resolveModelSheetOpening({
canSwitchProvider: true,
openAtProviders: true,
providers: [codex],
selectedProvider: "codex",
}),
).toEqual({ kind: "all" });
});
it("opens a running agent directly at its fixed provider", () => {
it("opens a running agent directly at its current provider even when other providers are available", () => {
expect(
resolveModelSheetOpening({
canSwitchProvider: false,
openAtProviders: false,
providers: [claude, codex],
selectedProvider: "codex",
}),
@@ -33,7 +33,7 @@ describe("model sheet opening", () => {
it("falls back to the only provider while live state catches up", () => {
expect(
resolveModelSheetOpening({
canSwitchProvider: false,
openAtProviders: false,
providers: [codex],
selectedProvider: "",
}),
@@ -2,15 +2,16 @@ import type { ModelBrowserView } from "@/components/model-browser-view";
import type { ProviderSelectorProvider } from "@/provider-selection/provider-selection";
export function resolveModelSheetOpening({
canSwitchProvider,
openAtProviders,
providers,
selectedProvider,
}: {
canSwitchProvider: boolean;
/** Drafts open at the provider list; live agents open directly at their active provider. */
openAtProviders: boolean;
providers: ProviderSelectorProvider[];
selectedProvider: string;
}): ModelBrowserView {
if (canSwitchProvider) return { kind: "all" };
if (openAtProviders) return { kind: "all" };
const provider = providers.find((entry) => entry.id === selectedProvider) ?? providers[0] ?? null;
return provider
@@ -68,6 +68,8 @@ interface CompactModelSheetProps {
/** False when the toolbar is too narrow for labels: the trigger shows the provider glyph only. */
showLabels: boolean;
canSwitchProvider: boolean;
/** Drafts open the model browser at the all-providers list; live agents open at their active provider. */
openModelBrowserAtProviders?: boolean;
/** Carries the composer's contexts into the sheets, which draw away from it. */
contextBridge?: ContextBridge | null;
children: ReactNode;
@@ -160,6 +162,7 @@ export function CompactModelSheet({
glyphs,
showLabels,
canSwitchProvider,
openModelBrowserAtProviders = false,
contextBridge = null,
children,
}: CompactModelSheetProps) {
@@ -239,7 +242,7 @@ export function CompactModelSheet({
const openModelBrowser = useCallback(() => {
Keyboard.dismiss();
const destination = resolveModelSheetOpening({
canSwitchProvider,
openAtProviders: openModelBrowserAtProviders,
providers: availableProviders,
selectedProvider,
});
@@ -249,7 +252,7 @@ export function CompactModelSheet({
modelBrowser.drillDown(destination.providerId, destination.providerLabel);
}
setIsModelBrowserOpen(true);
}, [availableProviders, canSwitchProvider, modelBrowser, selectedProvider]);
}, [availableProviders, modelBrowser, openModelBrowserAtProviders, selectedProvider]);
const closeModelBrowser = useCallback(() => {
setIsModelBrowserOpen(false);
+225 -31
View File
@@ -9,6 +9,20 @@ import { useStore } from "zustand";
import { getHostRuntimeStore } from "@/runtime/host-runtime";
import { LoadingSpinner } from "@/components/ui/loading-spinner";
import { Alert } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import {
beginStagedProviderSwitch,
clearStagedProviderSwitch,
endStagedProviderSwitch,
getStagedProviderSwitch,
isStagedProviderSwitchInFlight,
settleCommittedProviderSwitch,
useFailedStartupSettings,
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 +62,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 +313,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,10 +1379,56 @@ 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 failedStartupSettings = useFailedStartupSettings(serverId, agentId);
const stagedSwitch =
supportsProviderSwitching &&
rawStagedSwitch &&
agentState.provider &&
rawStagedSwitch.provider !== agentState.provider
? rawStagedSwitch
: null;
const { entries: providerSnapshotEntries } = useProvidersSnapshot(serverId, { cwd });
const stagedProviderLabel = stagedSwitch
? resolveProviderLabel(stagedSwitch.provider, providerSnapshotEntries)
: null;
useEffect(() => {
if (
rawStagedSwitch &&
agentState.provider &&
rawStagedSwitch.provider === agentState.provider &&
!isStagedProviderSwitchInFlight(serverId, agentId)
) {
clearStagedProviderSwitch(serverId, agentId);
}
}, [agentId, agentState.provider, rawStagedSwitch, serverId]);
const handleCancelStagedSwitch = useCallback(() => {
clearStagedProviderSwitch(serverId, agentId);
setSendError(null);
useSessionStore.getState().setQueuedSendError(serverId, agentId, null);
}, [agentId, serverId]);
const handleRetryFailedStartupSettings = useCallback(() => {
setSendError(null);
void getHostRuntimeStore().recoverFailedStartupSettings(serverId, agentId, "retry");
}, [agentId, serverId]);
const handleDismissFailedStartupSettings = useCallback(() => {
setSendError(null);
void getHostRuntimeStore().recoverFailedStartupSettings(serverId, agentId, "discard");
}, [agentId, serverId]);
const queuedMessagesRaw = useSessionStore((state) =>
state.sessions[serverId]?.queuedMessages?.get(agentId),
);
const queuedSendError = useSessionStore(
(state) => state.sessions[serverId]?.queuedSendErrors?.get(agentId) ?? null,
);
const queuedMessages = queuedMessagesRaw ?? EMPTY_ARRAY;
const setQueuedMessages = useSessionStore((state) => state.setQueuedMessages);
@@ -1709,25 +1783,62 @@ function ComposerContentImpl({
if (!client) {
throw new Error(t("workspace.terminal.hostDisconnected"));
}
await dispatchComposerAgentMessage({
client,
agentId: targetAgentId,
text,
attachments: sendAttachments,
attachmentSubmitFormat: resolveComposerAttachmentSubmitFormat({
supportsForgeAttachments: supportsForgeSearch,
}),
encodeImages,
submission: createMessageSubmissionWriter(serverId),
activeTurnBehavior,
activeTurnId:
activeTurnBehavior === "steer"
? (selectAgentTurnPresentation(
useSessionStore.getState().sessions[serverId],
targetAgentId,
).turnId ?? undefined)
: undefined,
});
const sessionState = useSessionStore.getState().sessions[serverId];
const liveProvider = sessionState?.agents.get(targetAgentId)?.provider;
const canSwitch = sessionState?.serverInfo?.features?.providerSwitching === true;
const pendingSwitch = canSwitch ? getStagedProviderSwitch(serverId, targetAgentId) : null;
const stagedProviderSwitch =
pendingSwitch && pendingSwitch.provider !== liveProvider ? pendingSwitch : null;
useSessionStore.getState().setQueuedSendError(serverId, targetAgentId, null);
if (stagedProviderSwitch) {
beginStagedProviderSwitch(serverId, targetAgentId);
}
try {
await dispatchComposerAgentMessage({
client,
agentId: targetAgentId,
text,
attachments: sendAttachments,
attachmentSubmitFormat: resolveComposerAttachmentSubmitFormat({
supportsForgeAttachments: supportsForgeSearch,
}),
encodeImages,
submission: createMessageSubmissionWriter(serverId),
stagedProviderSwitch,
onProviderSwitchCommitted: async (agent) => {
if (agent) {
getHostRuntimeStore().tryAcceptAgentSnapshot(
serverId,
normalizeAgentSnapshot(agent, serverId),
);
}
if (stagedProviderSwitch) {
const settled = await settleCommittedProviderSwitch({
serverId,
agentId: targetAgentId,
sentDraft: stagedProviderSwitch,
committedProvider: agent?.provider ?? null,
client,
});
if (!settled.applied) {
setSendError(settled.errorMessage);
}
}
},
activeTurnBehavior,
activeTurnId:
activeTurnBehavior === "steer"
? (selectAgentTurnPresentation(
useSessionStore.getState().sessions[serverId],
targetAgentId,
).turnId ?? undefined)
: undefined,
});
} finally {
if (stagedProviderSwitch) {
endStagedProviderSwitch(serverId, targetAgentId);
}
}
onAttentionPromptSend?.();
};
}, [appSettings.sendBehavior, client, onAttentionPromptSend, serverId, supportsForgeSearch, t]);
@@ -1803,7 +1914,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 +1956,7 @@ function ComposerContentImpl({
queueMessage,
setSelectedAttachments,
replaceUserInput,
stagedSwitch,
submitBehavior,
submitMessage,
t,
@@ -2079,15 +2191,17 @@ function ComposerContentImpl({
queue: queueWriter,
});
if (!result) return;
useSessionStore.getState().setQueuedSendError(serverId, agentId, null);
replaceUserInput(result.text);
setSelectedAttachments(result.attachments);
},
[agentId, queueWriter, replaceUserInput, setSelectedAttachments],
[agentId, queueWriter, replaceUserInput, serverId, setSelectedAttachments],
);
const handleSendQueuedNow = useCallback(
async (id: string) => {
if (!sendAgentMessageRef.current && !onSubmitMessageRef.current) return;
useSessionStore.getState().setQueuedSendError(serverId, agentId, null);
// Reuse the regular send path; server-side send atomically interrupts any active run.
const result = await sendQueuedComposerMessageNow({
agentId,
@@ -2101,7 +2215,7 @@ function ComposerContentImpl({
setSendError(result.errorMessage);
}
},
[agentId, queueWriter, submitMessage, t],
[agentId, queueWriter, serverId, submitMessage, t],
);
const handleQueue = useCallback(
@@ -2554,18 +2668,71 @@ function ComposerContentImpl({
// Focusing the composer on a touch screen raises the on-screen keyboard over the conversation.
const messageInputAutoFocus = autoFocus && isDesktopWebBreakpoint && hasFinePointer;
const submitLoadingPressHandler = isAgentRunning ? handleCancelAgent : undefined;
const displayError = externalError || sendError;
const displayError =
externalError || sendError || failedStartupSettings?.errorMessage || queuedSendError;
const sendErrorNode = useMemo(
() =>
displayError ? (
<Alert variant="error" size="sm" description={displayError} testID="composer-error" />
<Alert variant="error" size="sm" description={displayError} testID="composer-error">
{failedStartupSettings ? (
<>
<Button
variant="secondary"
size="sm"
onPress={handleRetryFailedStartupSettings}
testID="retry-failed-startup-settings"
>
{t("common.actions.retry")}
</Button>
<Button
variant="ghost"
size="sm"
onPress={handleDismissFailedStartupSettings}
testID="dismiss-failed-startup-settings"
>
{t("common.actions.dismiss")}
</Button>
</>
) : null}
</Alert>
) : null,
[displayError],
[
displayError,
failedStartupSettings,
handleDismissFailedStartupSettings,
handleRetryFailedStartupSettings,
t,
],
);
const githubEmptyText = githubSearchResultsQuery.isFetching
? t("composer.github.searching")
: t("composer.github.noResults");
const stagedSwitchBannerNode = useMemo(() => {
if (!stagedSwitch || !stagedProviderLabel) 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 +2758,7 @@ function ComposerContentImpl({
>
<View style={inputAreaContentStyle}>
{isFullscreen ? null : queueList}
{isFullscreen ? null : stagedSwitchBannerNode}
{!isFullscreen && sendErrorNode}
<ComposerAutocompleteBinding
@@ -2846,9 +3014,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,19 @@
export {
applyFailedStartupSettings,
beginStagedProviderSwitch,
clearStagedProviderSwitch,
discardFailedStartupSettings,
endStagedProviderSwitch,
getFailedStartupSettings,
getStagedProviderSwitch,
isStagedProviderSwitchInFlight,
settleCommittedProviderSwitch,
settleStagedProviderSwitch,
useFailedStartupSettings,
useStagedProviderSwitch,
useStagedProviderSwitchStore,
type FailedStartupSettings,
type LiveAgentSettingsWriter,
type SettleCommittedProviderSwitchResult,
type StagedProviderSwitch,
} from "./store";
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,86 @@
import { beforeEach, describe, expect, it } from "vitest";
import {
clearStagedProviderSwitch,
getStagedProviderSwitch,
settleStagedProviderSwitch,
useStagedProviderSwitchStore,
} from "./index";
describe("staged provider switch store", () => {
beforeEach(() => {
useStagedProviderSwitchStore.setState({ stagedByKey: new Map() });
});
it("stages, patches, and clears per server and agent", () => {
const store = useStagedProviderSwitchStore.getState();
store.stage("srv-1", "agent-1", {
provider: "codex",
model: "gpt-5.4",
thinkingOptionId: "high",
modeId: "auto",
providerOptions: { fast_mode: true },
});
store.stage("srv-1", "agent-2", {
provider: "opencode",
model: null,
thinkingOptionId: null,
modeId: null,
providerOptions: {},
});
expect(getStagedProviderSwitch("srv-1", "agent-1")).toEqual({
provider: "codex",
model: "gpt-5.4",
thinkingOptionId: "high",
modeId: "auto",
providerOptions: { fast_mode: true },
});
store.patch("srv-1", "agent-1", (current) => ({
...current,
thinkingOptionId: "medium",
}));
expect(getStagedProviderSwitch("srv-1", "agent-1")?.thinkingOptionId).toBe("medium");
clearStagedProviderSwitch("srv-1", "agent-1");
expect(getStagedProviderSwitch("srv-1", "agent-1")).toBeNull();
expect(getStagedProviderSwitch("srv-1", "agent-2")?.provider).toBe("opencode");
store.clearForServer("srv-1");
expect(getStagedProviderSwitch("srv-1", "agent-2")).toBeNull();
});
it("settles only the draft that was sent and preserves any newer selection or edit", () => {
const store = useStagedProviderSwitchStore.getState();
store.stage("srv-1", "agent-1", {
provider: "codex",
model: "gpt-5.4",
thinkingOptionId: null,
modeId: null,
providerOptions: {},
});
const sentDraft = getStagedProviderSwitch("srv-1", "agent-1")!;
// User chooses Copilot before Codex reply returns -> settling Codex draft preserves Copilot.
store.stage("srv-1", "agent-1", {
provider: "copilot",
model: "gpt-5",
thinkingOptionId: null,
modeId: null,
providerOptions: {},
});
settleStagedProviderSwitch("srv-1", "agent-1", sentDraft);
const copilotDraft = getStagedProviderSwitch("srv-1", "agent-1")!;
expect(copilotDraft.provider).toBe("copilot");
// Patching the draft also produces a newer revision that settling the older reference preserves.
store.patch("srv-1", "agent-1", (current) => ({ ...current, thinkingOptionId: "high" }));
settleStagedProviderSwitch("srv-1", "agent-1", copilotDraft);
const patchedCopilot = getStagedProviderSwitch("srv-1", "agent-1")!;
expect(patchedCopilot.thinkingOptionId).toBe("high");
// Settling the current draft clears it cleanly.
settleStagedProviderSwitch("srv-1", "agent-1", patchedCopilot);
expect(getStagedProviderSwitch("srv-1", "agent-1")).toBeNull();
});
});
@@ -0,0 +1,401 @@
import { create } from "zustand";
import type { AgentProvider, ProviderOptions } from "@getpaseo/protocol/agent-types";
import type { AgentConfigApply } from "@getpaseo/protocol/messages";
export interface StagedProviderSwitch {
provider: AgentProvider;
model: string | null;
thinkingOptionId: string | null;
modeId: string | null;
providerOptions: ProviderOptions;
}
function stagedKey(serverId: string, agentId: string): string {
return `${serverId}:${agentId}`;
}
export interface LiveAgentSettingsWriter {
applyAgentConfig?: (
agentId: string,
config: AgentConfigApply,
options?: { expectedProvider?: AgentProvider },
) => Promise<unknown>;
setAgentModel?: (
agentId: string,
modelId: string | null,
options?: { expectedProvider?: AgentProvider },
) => Promise<unknown>;
setAgentMode?: (
agentId: string,
modeId: string,
options?: { expectedProvider?: AgentProvider },
) => Promise<unknown>;
setAgentThinkingOption?: (
agentId: string,
thinkingOptionId: string,
options?: { expectedProvider?: AgentProvider },
) => Promise<unknown>;
setAgentOptions?: (
agentId: string,
options: ProviderOptions,
mutationOptions?: { expectedProvider?: AgentProvider },
) => Promise<unknown>;
}
export interface FailedStartupSettings {
provider: AgentProvider;
bundle: AgentConfigApply;
errorMessage: string;
}
export type SettleCommittedProviderSwitchResult =
| { applied: true }
| { applied: false; errorMessage: string };
interface StagedProviderSwitchState {
stagedByKey: Map<string, StagedProviderSwitch>;
inFlightByKey: Map<string, number>;
failedStartupSettingsByKey: Map<string, FailedStartupSettings>;
stage: (serverId: string, agentId: string, draft: StagedProviderSwitch) => void;
patch: (
serverId: string,
agentId: string,
updater: (current: StagedProviderSwitch) => StagedProviderSwitch,
) => void;
beginSwitch: (serverId: string, agentId: string) => void;
endSwitch: (serverId: string, agentId: string) => void;
setFailedStartupSettings: (
serverId: string,
agentId: string,
failed: FailedStartupSettings | null,
) => void;
settle: (serverId: string, agentId: string, sentDraft: StagedProviderSwitch) => void;
clear: (serverId: string, agentId: string) => void;
clearForServer: (serverId: string) => void;
}
export const useStagedProviderSwitchStore = create<StagedProviderSwitchState>((set) => ({
stagedByKey: new Map(),
inFlightByKey: new Map(),
failedStartupSettingsByKey: new Map(),
stage: (serverId, agentId, draft) =>
set((state) => {
const next = new Map(state.stagedByKey);
next.set(stagedKey(serverId, agentId), draft);
return { stagedByKey: next };
}),
patch: (serverId, agentId, updater) =>
set((state) => {
const key = stagedKey(serverId, agentId);
const current = state.stagedByKey.get(key);
if (!current) return state;
const updated = updater(current);
if (updated === current) return state;
const next = new Map(state.stagedByKey);
next.set(key, updated);
return { stagedByKey: next };
}),
beginSwitch: (serverId, agentId) =>
set((state) => {
const key = stagedKey(serverId, agentId);
const next = new Map(state.inFlightByKey);
next.set(key, (next.get(key) ?? 0) + 1);
return { inFlightByKey: next };
}),
endSwitch: (serverId, agentId) =>
set((state) => {
const key = stagedKey(serverId, agentId);
const count = state.inFlightByKey.get(key) ?? 0;
if (count <= 0) return state;
const next = new Map(state.inFlightByKey);
if (count === 1) {
next.delete(key);
} else {
next.set(key, count - 1);
}
return { inFlightByKey: next };
}),
setFailedStartupSettings: (serverId, agentId, failed) =>
set((state) => {
const key = stagedKey(serverId, agentId);
const next = new Map(state.failedStartupSettingsByKey);
if (failed === null) {
if (!next.has(key)) return state;
next.delete(key);
} else {
next.set(key, failed);
}
return { failedStartupSettingsByKey: next };
}),
settle: (serverId, agentId, sentDraft) =>
set((state) => {
const key = stagedKey(serverId, agentId);
const current = state.stagedByKey.get(key);
if (!current || current !== sentDraft) return state;
const next = new Map(state.stagedByKey);
next.delete(key);
return { stagedByKey: next };
}),
clear: (serverId, agentId) =>
set((state) => {
const key = stagedKey(serverId, agentId);
if (!state.stagedByKey.has(key)) return state;
const next = new Map(state.stagedByKey);
next.delete(key);
return { stagedByKey: next };
}),
clearForServer: (serverId) =>
set((state) => {
const prefix = `${serverId}:`;
let changed = false;
const next = new Map(state.stagedByKey);
for (const key of next.keys()) {
if (key.startsWith(prefix)) {
next.delete(key);
changed = true;
}
}
const nextInFlight = new Map(state.inFlightByKey);
for (const key of nextInFlight.keys()) {
if (key.startsWith(prefix)) {
nextInFlight.delete(key);
changed = true;
}
}
const nextFailed = new Map(state.failedStartupSettingsByKey);
for (const key of nextFailed.keys()) {
if (key.startsWith(prefix)) {
nextFailed.delete(key);
changed = true;
}
}
return changed
? {
stagedByKey: next,
inFlightByKey: nextInFlight,
failedStartupSettingsByKey: nextFailed,
}
: state;
}),
}));
export function getStagedProviderSwitch(
serverId: string,
agentId: string,
): StagedProviderSwitch | null {
return (
useStagedProviderSwitchStore.getState().stagedByKey.get(stagedKey(serverId, agentId)) ?? null
);
}
export function beginStagedProviderSwitch(serverId: string, agentId: string): void {
useStagedProviderSwitchStore.getState().beginSwitch(serverId, agentId);
}
export function endStagedProviderSwitch(serverId: string, agentId: string): void {
useStagedProviderSwitchStore.getState().endSwitch(serverId, agentId);
}
export function isStagedProviderSwitchInFlight(serverId: string, agentId: string): boolean {
return (
(useStagedProviderSwitchStore.getState().inFlightByKey.get(stagedKey(serverId, agentId)) ?? 0) >
0
);
}
export function getFailedStartupSettings(
serverId: string,
agentId: string,
): FailedStartupSettings | null {
return (
useStagedProviderSwitchStore
.getState()
.failedStartupSettingsByKey.get(stagedKey(serverId, agentId)) ?? null
);
}
export function useFailedStartupSettings(
serverId: string,
agentId: string,
): FailedStartupSettings | null {
return useStagedProviderSwitchStore(
(state) => state.failedStartupSettingsByKey.get(stagedKey(serverId, agentId)) ?? null,
);
}
export function discardFailedStartupSettings(serverId: string, agentId: string): void {
useStagedProviderSwitchStore.getState().setFailedStartupSettings(serverId, agentId, null);
}
export function settleStagedProviderSwitch(
serverId: string,
agentId: string,
sentDraft: StagedProviderSwitch,
): void {
useStagedProviderSwitchStore.getState().settle(serverId, agentId, sentDraft);
}
function diffProviderOptions(
sent: ProviderOptions,
edited: ProviderOptions,
): ProviderOptions | null {
const patch: ProviderOptions = {};
let hasDiff = false;
for (const [key, value] of Object.entries(edited)) {
if (sent[key] !== value) {
patch[key] = value;
hasDiff = true;
}
}
return hasDiff ? patch : null;
}
function buildEditedSettingsBundle(
sentDraft: StagedProviderSwitch,
editedDraft: StagedProviderSwitch,
): AgentConfigApply | null {
const config: AgentConfigApply = {};
let hasChanges = false;
if (editedDraft.model !== sentDraft.model) {
config.modelId = editedDraft.model;
hasChanges = true;
}
if (editedDraft.modeId !== sentDraft.modeId && editedDraft.modeId !== null) {
config.modeId = editedDraft.modeId;
hasChanges = true;
}
if (
editedDraft.thinkingOptionId !== sentDraft.thinkingOptionId &&
editedDraft.thinkingOptionId !== null
) {
config.thinkingOptionId = editedDraft.thinkingOptionId;
hasChanges = true;
}
const optionsPatch = diffProviderOptions(sentDraft.providerOptions, editedDraft.providerOptions);
if (optionsPatch) {
config.options = optionsPatch;
hasChanges = true;
}
return hasChanges ? config : null;
}
async function applyEditedDraftSettingsToLiveAgent(
agentId: string,
bundle: AgentConfigApply,
expectedProvider: AgentProvider,
client: LiveAgentSettingsWriter,
): Promise<void> {
const providerGuard = { expectedProvider };
if (client.applyAgentConfig) {
await client.applyAgentConfig(agentId, bundle, providerGuard);
return;
}
if (bundle.modelId !== undefined && client.setAgentModel) {
await client.setAgentModel(agentId, bundle.modelId, providerGuard);
}
if (bundle.modeId !== undefined && client.setAgentMode) {
await client.setAgentMode(agentId, bundle.modeId, providerGuard);
}
if (
bundle.thinkingOptionId !== undefined &&
bundle.thinkingOptionId !== null &&
client.setAgentThinkingOption
) {
await client.setAgentThinkingOption(agentId, bundle.thinkingOptionId, providerGuard);
}
if (bundle.options && client.setAgentOptions) {
await client.setAgentOptions(agentId, bundle.options, providerGuard);
}
}
/**
* Settles the staged draft captured by a committed switch and awaits any edited settings
* for the provider that just became live before callers release queued follow-up prompts.
* - Untouched draft: cleared.
* - Newer draft targeting a different provider: preserved for the next switch.
* - Newer draft editing settings of the provider that just became live: applied atomically
* (via `applyAgentConfig` when available, else sequential setters) before settling the draft.
* If the daemon rejects an edit, the draft is kept intact and `{ applied: false, errorMessage }`
* is returned so callers surface the error and hold any queued follow-up prompt.
*/
export async function settleCommittedProviderSwitch(input: {
serverId: string;
agentId: string;
sentDraft: StagedProviderSwitch;
committedProvider?: AgentProvider | null;
client?: LiveAgentSettingsWriter | null;
}): Promise<SettleCommittedProviderSwitchResult> {
const { serverId, agentId, sentDraft, committedProvider, client } = input;
const store = useStagedProviderSwitchStore.getState();
store.settle(serverId, agentId, sentDraft);
const remaining = getStagedProviderSwitch(serverId, agentId);
const liveProvider = committedProvider ?? sentDraft.provider;
if (!remaining || remaining.provider !== liveProvider) {
return { applied: true };
}
const bundle = buildEditedSettingsBundle(sentDraft, remaining);
if (!bundle || !client) {
store.settle(serverId, agentId, remaining);
return { applied: true };
}
try {
await applyEditedDraftSettingsToLiveAgent(agentId, bundle, liveProvider, client);
store.settle(serverId, agentId, remaining);
return { applied: true };
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
store.settle(serverId, agentId, remaining);
store.setFailedStartupSettings(serverId, agentId, {
provider: liveProvider,
bundle,
errorMessage,
});
console.warn("[ProviderSwitch] failed to forward edited settings after switch", error);
return { applied: false, errorMessage };
}
}
/** Retries applying previously failed startup settings for a committed provider switch. */
export async function applyFailedStartupSettings(input: {
serverId: string;
agentId: string;
client: LiveAgentSettingsWriter;
}): Promise<SettleCommittedProviderSwitchResult> {
const { serverId, agentId, client } = input;
const failed = getFailedStartupSettings(serverId, agentId);
if (!failed) {
return { applied: true };
}
const store = useStagedProviderSwitchStore.getState();
try {
await applyEditedDraftSettingsToLiveAgent(agentId, failed.bundle, failed.provider, client);
store.setFailedStartupSettings(serverId, agentId, null);
return { applied: true };
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
store.setFailedStartupSettings(serverId, agentId, { ...failed, errorMessage });
console.warn("[ProviderSwitch] failed to retry startup settings", error);
return { applied: false, errorMessage };
}
}
export function clearStagedProviderSwitch(serverId: string, agentId: string): void {
useStagedProviderSwitchStore.getState().clear(serverId, agentId);
}
export function useStagedProviderSwitch(
serverId: string,
agentId: string,
): StagedProviderSwitch | null {
return useStagedProviderSwitchStore(
(state) => state.stagedByKey.get(stagedKey(serverId, agentId)) ?? null,
);
}
@@ -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;
@@ -1,7 +1,7 @@
import { useMemo } from "react";
import { useTranslation } from "react-i18next";
import { AdaptiveModalSheet, type SheetHeader } from "@/components/adaptive-modal-sheet";
import { PairDeviceSection } from "@/devices/pair-device-section";
import { PairDeviceSection } from "@/desktop/components/pair-device-section";
export interface PairDeviceModalProps {
serverId: string;
@@ -23,7 +23,7 @@ import {
const RELAY_DOCS_URL = "https://paseo.sh/docs/security";
export const CONNECTIVITY_DOCS_URL = "https://paseo.sh/docs/connectivity";
const TAILSCALE_DOCS_URL = `${CONNECTIVITY_DOCS_URL}#tailscale`;
export const TAILSCALE_DOCS_URL = `${CONNECTIVITY_DOCS_URL}#tailscale`;
const FLEX_ONE_STYLE = { flex: 1 } as const;
const ThemedLoadingSpinner = withUnistyles(LoadingSpinner);
const ThemedShieldCheck = withUnistyles(ShieldCheck);
@@ -11,13 +11,8 @@ import { i18n } from "@/i18n/i18next";
const DESKTOP_SETTINGS_QUERY_KEY = ["desktop-settings"] as const;
export type DesktopUpdateMode = "automatic" | "notify" | "off";
export interface DesktopSettings {
releaseChannel: ReleaseChannel;
updates: {
mode: DesktopUpdateMode;
};
notifications: {
playSound: boolean;
};
@@ -29,16 +24,12 @@ export interface DesktopSettings {
export interface DesktopSettingsPatch {
releaseChannel?: ReleaseChannel;
updates?: Partial<DesktopSettings["updates"]>;
notifications?: Partial<DesktopSettings["notifications"]>;
daemon?: Partial<DesktopSettings["daemon"]>;
}
export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = {
releaseChannel: "stable",
updates: {
mode: "automatic",
},
notifications: {
playSound: true,
},
@@ -158,24 +149,13 @@ export async function migrateLegacyDesktopSettings(input: {
await invokeDesktopCommand("migrate_legacy_desktop_settings", input);
}
function parseUpdateMode(value: unknown): DesktopUpdateMode {
if (value === "automatic" || value === "notify" || value === "off") {
return value;
}
return DEFAULT_DESKTOP_SETTINGS.updates.mode;
}
function parseDesktopSettings(raw: unknown): DesktopSettings {
const record = isRecord(raw) ? raw : {};
const updates = isRecord(record.updates) ? record.updates : {};
const notifications = isRecord(record.notifications) ? record.notifications : {};
const daemon = isRecord(record.daemon) ? record.daemon : {};
return {
releaseChannel: record.releaseChannel === "beta" ? "beta" : "stable",
updates: {
mode: parseUpdateMode(updates.mode),
},
notifications: {
playSound:
typeof notifications.playSound === "boolean"
@@ -201,10 +181,6 @@ function mergeDesktopSettings(
): DesktopSettings {
return {
releaseChannel: updates.releaseChannel ?? current.releaseChannel,
updates: {
...current.updates,
...updates.updates,
},
notifications: {
...current.notifications,
...updates.notifications,
@@ -219,7 +195,6 @@ function mergeDesktopSettings(
function normalizePatch(updates: DesktopSettingsPatch): Record<string, unknown> {
return {
...(updates.releaseChannel ? { releaseChannel: updates.releaseChannel } : {}),
...(updates.updates ? { updates: updates.updates } : {}),
...(updates.notifications ? { notifications: updates.notifications } : {}),
...(updates.daemon ? { daemon: updates.daemon } : {}),
};
@@ -128,43 +128,6 @@ describe("desktop app updater — check", () => {
});
});
it("reports 'available' when an update is available to download without auto-downloading", async () => {
const { updater, port } = createUpdater({ now: () => 42 });
port.nextCheckResult(
buildFakeCheckResult({
hasUpdate: true,
readyToInstall: false,
downloading: false,
latestVersion: "1.2.3",
}),
);
await updater.checkForUpdates({ releaseChannel: "stable" });
expect(updater.getSnapshot()).toMatchObject({
status: "available",
availableUpdate: { latestVersion: "1.2.3", readyToInstall: false, downloading: false },
lastCheckedAt: 42,
});
});
it("tracks download progress updates and clears them once install completes", async () => {
const { updater, port } = createUpdater();
port.nextInstallResult(buildFakeInstallResult({ installed: true }));
updater.setDownloadProgress({
version: "1.2.3",
percent: 42.4,
transferred: 42,
total: 100,
bytesPerSecond: 10,
});
expect(updater.getSnapshot().downloadProgress?.percent).toBe(42.4);
await updater.installUpdate({ releaseChannel: "stable" });
expect(updater.getSnapshot().downloadProgress).toBeNull();
});
it("reports 'up-to-date' when the check resolves with no update", async () => {
const { updater, port } = createUpdater();
port.nextCheckResult(buildFakeCheckResult({ hasUpdate: false, readyToInstall: false }));
@@ -377,55 +340,6 @@ describe("desktop app updater — install", () => {
expect(updater.getSnapshot().status).toBe("up-to-date");
});
it("moves to 'error' instead of 'up-to-date' when the install returns an errorMessage", async () => {
const { updater, port } = createUpdater();
port.nextInstallResult(
buildFakeInstallResult({
installed: false,
message: "Update failed: ECONNRESET",
errorMessage: "ECONNRESET",
}),
);
await updater.installUpdate({ releaseChannel: "stable" });
expect(updater.getSnapshot()).toMatchObject({
status: "error",
errorMessage: "ECONNRESET",
downloadProgress: null,
isInstalling: false,
});
});
it("ignores duplicate install requests and silent checks while an install is in progress", async () => {
const { updater, port } = createUpdater();
let resolveInstall!: (result: ReturnType<typeof buildFakeInstallResult>) => void;
port.installDesktopAppUpdate = async (input) => {
port.recordedInstalls.push(input);
return new Promise((resolve) => {
resolveInstall = resolve;
});
};
const firstInstall = updater.installUpdate({ releaseChannel: "stable" });
const secondInstall = await updater.installUpdate({ releaseChannel: "stable" });
const silentCheck = await updater.checkForUpdates({
releaseChannel: "stable",
intent: "automatic",
silent: true,
});
expect(secondInstall).toBeNull();
expect(silentCheck).toBeNull();
expect(port.recordedInstalls).toHaveLength(1);
expect(port.recordedChecks).toHaveLength(0);
expect(updater.getSnapshot().status).toBe("installing");
resolveInstall(buildFakeInstallResult({ installed: true }));
await firstInstall;
expect(updater.getSnapshot().status).toBe("installed");
});
it("reports the install error and moves to 'error' when the install throws", async () => {
const { updater, port, reportedInstallErrors } = createUpdater();
const error = new Error("install failed");
@@ -548,47 +462,6 @@ describe("formatStatusText", () => {
).toBe("Restart now");
});
it("formats download-available and live download progress status text", () => {
expect(
formatStatusText({
status: "available",
availableUpdate: buildFakeCheckResult({
hasUpdate: true,
readyToInstall: false,
downloading: false,
latestVersion: "1.2.3",
}),
installMessage: null,
lastCheckedAt: 42,
formatVersion,
formatLastCheckedAt,
}),
).toBe("Update available: v1.2.3. Last checked at time-42.");
expect(
formatStatusText({
status: "installing",
availableUpdate: buildFakeCheckResult({
hasUpdate: true,
readyToInstall: false,
downloading: false,
latestVersion: "1.2.3",
}),
downloadProgress: {
version: "1.2.3",
percent: 64.6,
transferred: 65,
total: 100,
bytesPerSecond: 10,
},
installMessage: null,
lastCheckedAt: null,
formatVersion,
formatLastCheckedAt,
}),
).toBe("Downloading v1.2.3... 65%");
});
it("uses the active app language for local status wrappers", async () => {
await i18n.changeLanguage("zh-CN");
try {
@@ -1,7 +1,6 @@
import type {
DesktopAppUpdateCheckResult,
DesktopAppUpdateCheckIntent,
DesktopAppUpdateDownloadProgress,
DesktopAppUpdateInstallResult,
DesktopReleaseChannel,
} from "@/desktop/updates/desktop-updates";
@@ -22,7 +21,6 @@ export const PENDING_RECHECK_MS = 10_000;
export interface DesktopAppUpdaterSnapshot {
status: DesktopAppUpdateStatus;
availableUpdate: DesktopAppUpdateCheckResult | null;
downloadProgress: DesktopAppUpdateDownloadProgress | null;
errorMessage: string | null;
installMessage: string | null;
lastCheckedAt: number | null;
@@ -55,7 +53,6 @@ export interface DesktopAppUpdaterDeps {
export interface DesktopAppUpdater {
getSnapshot(): DesktopAppUpdaterSnapshot;
subscribe(listener: () => void): () => void;
setDownloadProgress(progress: DesktopAppUpdateDownloadProgress | null): void;
checkForUpdates(options?: {
releaseChannel: DesktopReleaseChannel;
intent?: DesktopAppUpdateCheckIntent;
@@ -69,7 +66,6 @@ export interface DesktopAppUpdater {
interface InternalState {
status: DesktopAppUpdateStatus;
availableUpdate: DesktopAppUpdateCheckResult | null;
downloadProgress: DesktopAppUpdateDownloadProgress | null;
errorMessage: string | null;
installMessage: string | null;
lastCheckedAt: number | null;
@@ -80,7 +76,6 @@ interface InternalState {
const INITIAL_STATE: InternalState = {
status: "idle",
availableUpdate: null,
downloadProgress: null,
errorMessage: null,
installMessage: null,
lastCheckedAt: null,
@@ -92,7 +87,6 @@ function buildSnapshot(state: InternalState): DesktopAppUpdaterSnapshot {
return {
status: state.status,
availableUpdate: state.availableUpdate,
downloadProgress: state.downloadProgress,
errorMessage: state.errorMessage,
installMessage: state.installMessage,
lastCheckedAt: state.lastCheckedAt,
@@ -108,113 +102,9 @@ function getErrorMessage(error: unknown): string {
return String(error);
}
function formatInstallingStatusText(input: {
availableUpdate: DesktopAppUpdateCheckResult | null;
downloadProgress: DesktopAppUpdateDownloadProgress | null;
formatVersion: (version: string | null | undefined) => string;
}): string {
const { availableUpdate, downloadProgress, formatVersion } = input;
if (downloadProgress == null) {
return i18n.t("desktop.updates.status.installing");
}
const percent = Math.round(downloadProgress.percent);
const version = downloadProgress.version ?? availableUpdate?.latestVersion;
if (version) {
return i18n.t("desktop.updates.status.downloadingVersionProgress", {
version: formatVersion(version),
percent,
});
}
return i18n.t("desktop.updates.status.downloadingProgress", { percent });
}
function formatPendingStatusText(input: {
availableUpdate: DesktopAppUpdateCheckResult | null;
downloadProgress: DesktopAppUpdateDownloadProgress | null;
lastCheckedAt: number | null;
formatVersion: (version: string | null | undefined) => string;
formatLastCheckedAt: (timestamp: number) => string;
}): string {
const { availableUpdate, downloadProgress, lastCheckedAt, formatVersion, formatLastCheckedAt } =
input;
const time = lastCheckedAt != null ? formatLastCheckedAt(lastCheckedAt) : undefined;
if (availableUpdate?.latestVersion) {
const version = formatVersion(availableUpdate.latestVersion);
if (downloadProgress != null) {
return i18n.t(
time !== undefined
? "desktop.updates.status.pendingWithVersionProgressAndLastChecked"
: "desktop.updates.status.pendingWithVersionProgress",
{ version, percent: Math.round(downloadProgress.percent), time },
);
}
return i18n.t(
time !== undefined
? "desktop.updates.status.pendingWithVersionAndLastChecked"
: "desktop.updates.status.pendingWithVersion",
{ version, time },
);
}
if (time !== undefined) {
return i18n.t("desktop.updates.status.pendingWithLastChecked", { time });
}
return i18n.t("desktop.updates.status.pending");
}
function formatAvailableStatusText(input: {
availableUpdate: DesktopAppUpdateCheckResult | null;
lastCheckedAt: number | null;
formatVersion: (version: string | null | undefined) => string;
formatLastCheckedAt: (timestamp: number) => string;
}): string {
const { availableUpdate, lastCheckedAt, formatVersion, formatLastCheckedAt } = input;
const time = lastCheckedAt != null ? formatLastCheckedAt(lastCheckedAt) : undefined;
const isDownloadRequired =
availableUpdate?.hasUpdate === true && availableUpdate.readyToInstall === false;
if (availableUpdate?.latestVersion) {
const version = formatVersion(availableUpdate.latestVersion);
if (isDownloadRequired) {
return i18n.t(
time !== undefined
? "desktop.updates.status.downloadAvailableWithVersionAndLastChecked"
: "desktop.updates.status.downloadAvailableWithVersion",
{ version, time },
);
}
return i18n.t(
time !== undefined
? "desktop.updates.status.availableWithVersionAndLastChecked"
: "desktop.updates.status.availableWithVersion",
{ version, time },
);
}
if (isDownloadRequired) {
return time !== undefined
? i18n.t("desktop.updates.status.downloadAvailableWithLastChecked", { time })
: i18n.t("desktop.updates.status.downloadAvailable");
}
return time !== undefined
? i18n.t("desktop.updates.status.availableWithLastChecked", { time })
: i18n.t("desktop.updates.status.available");
}
function resolveCheckOutcome(result: DesktopAppUpdateCheckResult): {
status: DesktopAppUpdateStatus;
availableUpdate: DesktopAppUpdateCheckResult | null;
} {
if (result.readyToInstall || (result.hasUpdate && !result.downloading)) {
return { status: "available", availableUpdate: result };
}
if (result.hasUpdate) {
return { status: "pending", availableUpdate: result };
}
return { status: "up-to-date", availableUpdate: null };
}
export function formatStatusText(input: {
status: DesktopAppUpdateStatus;
availableUpdate: DesktopAppUpdateCheckResult | null;
downloadProgress?: DesktopAppUpdateDownloadProgress | null;
installMessage: string | null;
lastCheckedAt: number | null;
formatVersion: (version: string | null | undefined) => string;
@@ -223,45 +113,79 @@ export function formatStatusText(input: {
const {
status,
availableUpdate,
downloadProgress = null,
installMessage,
lastCheckedAt,
formatVersion,
formatLastCheckedAt,
} = input;
if (status === "checking") return i18n.t("desktop.updates.status.checking");
if (status === "checking") {
return i18n.t("desktop.updates.status.checking");
}
if (status === "installing") {
return formatInstallingStatusText({ availableUpdate, downloadProgress, formatVersion });
return i18n.t("desktop.updates.status.installing");
}
if (status === "up-to-date") {
return lastCheckedAt != null
? i18n.t("desktop.updates.status.upToDateWithLastChecked", {
time: formatLastCheckedAt(lastCheckedAt),
})
: i18n.t("desktop.updates.status.upToDate");
if (lastCheckedAt != null) {
return i18n.t("desktop.updates.status.upToDateWithLastChecked", {
time: formatLastCheckedAt(lastCheckedAt),
});
}
return i18n.t("desktop.updates.status.upToDate");
}
if (status === "pending") {
return formatPendingStatusText({
availableUpdate,
downloadProgress,
lastCheckedAt,
formatVersion,
formatLastCheckedAt,
});
if (availableUpdate?.latestVersion) {
return i18n.t(
lastCheckedAt != null
? "desktop.updates.status.pendingWithVersionAndLastChecked"
: "desktop.updates.status.pendingWithVersion",
{
version: formatVersion(availableUpdate.latestVersion),
time: lastCheckedAt != null ? formatLastCheckedAt(lastCheckedAt) : undefined,
},
);
}
if (lastCheckedAt != null) {
return i18n.t("desktop.updates.status.pendingWithLastChecked", {
time: formatLastCheckedAt(lastCheckedAt),
});
}
return i18n.t("desktop.updates.status.pending");
}
if (status === "available") {
return formatAvailableStatusText({
availableUpdate,
lastCheckedAt,
formatVersion,
formatLastCheckedAt,
});
if (availableUpdate?.latestVersion) {
return i18n.t(
lastCheckedAt != null
? "desktop.updates.status.availableWithVersionAndLastChecked"
: "desktop.updates.status.availableWithVersion",
{
version: formatVersion(availableUpdate.latestVersion),
time: lastCheckedAt != null ? formatLastCheckedAt(lastCheckedAt) : undefined,
},
);
}
if (lastCheckedAt != null) {
return i18n.t("desktop.updates.status.availableWithLastChecked", {
time: formatLastCheckedAt(lastCheckedAt),
});
}
return i18n.t("desktop.updates.status.available");
}
if (status === "installed") {
return installMessage ?? i18n.t("desktop.updates.status.installed");
}
if (status === "error") return i18n.t("desktop.updates.status.failed");
if (status === "error") {
return i18n.t("desktop.updates.status.failed");
}
return i18n.t("desktop.updates.status.idle");
}
@@ -278,16 +202,6 @@ export function createDesktopAppUpdater(deps: DesktopAppUpdaterDeps): DesktopApp
}
}
function setDownloadProgress(progress: DesktopAppUpdateDownloadProgress | null): void {
if (progress === null && state.downloadProgress === null) {
return;
}
commit({
...state,
downloadProgress: progress,
});
}
async function checkForUpdates(options?: {
releaseChannel: DesktopReleaseChannel;
intent?: DesktopAppUpdateCheckIntent;
@@ -297,7 +211,7 @@ export function createDesktopAppUpdater(deps: DesktopAppUpdaterDeps): DesktopApp
return null;
}
const { releaseChannel, intent = "manual", silent = false } = options;
if (silent && (state.status === "checking" || state.isInstalling)) {
if (silent && state.status === "checking") {
return null;
}
@@ -327,7 +241,6 @@ export function createDesktopAppUpdater(deps: DesktopAppUpdaterDeps): DesktopApp
...state,
status: "error",
availableUpdate: null,
downloadProgress: null,
errorMessage: result.errorMessage,
installMessage: null,
lastCheckedAt: nextLastCheckedAt,
@@ -335,13 +248,24 @@ export function createDesktopAppUpdater(deps: DesktopAppUpdaterDeps): DesktopApp
return result;
}
const outcome = resolveCheckOutcome(result);
let nextStatus: DesktopAppUpdateStatus;
let nextAvailable: DesktopAppUpdateCheckResult | null;
if (result.readyToInstall) {
nextStatus = "available";
nextAvailable = result;
} else if (result.hasUpdate) {
nextStatus = "pending";
nextAvailable = result;
} else {
nextStatus = "up-to-date";
nextAvailable = null;
}
commit({
...state,
status: outcome.status,
availableUpdate: outcome.availableUpdate,
downloadProgress: outcome.status === "pending" ? state.downloadProgress : null,
status: nextStatus,
availableUpdate: nextAvailable,
errorMessage: null,
installMessage: null,
lastCheckedAt: nextLastCheckedAt,
@@ -360,7 +284,6 @@ export function createDesktopAppUpdater(deps: DesktopAppUpdaterDeps): DesktopApp
commit({
...state,
status: "error",
downloadProgress: null,
errorMessage: message,
lastCheckedAt: intent === "manual" ? deps.now() : state.lastCheckedAt,
});
@@ -372,10 +295,6 @@ export function createDesktopAppUpdater(deps: DesktopAppUpdaterDeps): DesktopApp
async function installUpdate(options: {
releaseChannel: DesktopReleaseChannel;
}): Promise<DesktopAppUpdateInstallResult | null> {
if (state.isInstalling) {
return null;
}
commit({
...state,
status: "installing",
@@ -388,23 +307,10 @@ export function createDesktopAppUpdater(deps: DesktopAppUpdaterDeps): DesktopApp
releaseChannel: options.releaseChannel,
});
const nextLastCheckedAt = deps.now();
if (!result.installed && result.errorMessage) {
commit({
...state,
status: "error",
downloadProgress: null,
errorMessage: result.errorMessage,
installMessage: null,
lastCheckedAt: nextLastCheckedAt,
isInstalling: false,
});
return result;
}
commit({
...state,
status: result.installed ? "installed" : "up-to-date",
availableUpdate: null,
downloadProgress: null,
installMessage: result.message,
lastCheckedAt: nextLastCheckedAt,
isInstalling: false,
@@ -420,7 +326,6 @@ export function createDesktopAppUpdater(deps: DesktopAppUpdaterDeps): DesktopApp
commit({
...state,
status: "error",
downloadProgress: null,
errorMessage: message,
isInstalling: false,
});
@@ -436,7 +341,6 @@ export function createDesktopAppUpdater(deps: DesktopAppUpdaterDeps): DesktopApp
listeners.delete(listener);
};
},
setDownloadProgress,
checkForUpdates,
installUpdate,
};
@@ -1,21 +1,11 @@
import { isElectronRuntime } from "@/desktop/host";
import { listenToDesktopEvent, type DesktopEventUnlisten } from "@/desktop/electron/events";
import { invokeDesktopCommand } from "@/desktop/electron/invoke";
import { isWeb } from "@/constants/platform";
import { i18n } from "@/i18n/i18next";
export interface DesktopAppUpdateDownloadProgress {
version: string | null;
percent: number;
transferred: number;
total: number;
bytesPerSecond: number;
}
export interface DesktopAppUpdateCheckResult {
hasUpdate: boolean;
readyToInstall: boolean;
downloading: boolean;
currentVersion: string | null;
latestVersion: string | null;
body: string | null;
@@ -27,7 +17,6 @@ export interface DesktopAppUpdateInstallResult {
installed: boolean;
version: string | null;
message: string;
errorMessage?: string | null;
}
export interface DesktopRuntimeInfo {
@@ -126,13 +115,9 @@ export async function checkDesktopAppUpdate({
throw new Error("Unexpected response while checking desktop updates.");
}
const hasUpdate = result.hasUpdate === true;
const readyToInstall = result.readyToInstall === true;
return {
hasUpdate,
readyToInstall,
downloading:
typeof result.downloading === "boolean" ? result.downloading : hasUpdate && !readyToInstall,
hasUpdate: result.hasUpdate === true,
readyToInstall: result.readyToInstall === true,
currentVersion: toStringOrNull(result.currentVersion),
latestVersion: toStringOrNull(result.latestVersion),
body: toStringOrNull(result.body),
@@ -141,36 +126,6 @@ export async function checkDesktopAppUpdate({
};
}
export function parseDesktopAppUpdateDownloadProgress(
raw: unknown,
): DesktopAppUpdateDownloadProgress | null {
if (!isRecord(raw)) {
return null;
}
const percent = toNumberOr(Number.NaN, raw.percent);
if (!Number.isFinite(percent)) {
return null;
}
return {
version: toStringOrNull(raw.version),
percent: Math.max(0, Math.min(100, percent)),
transferred: toNumberOr(0, raw.transferred),
total: toNumberOr(0, raw.total),
bytesPerSecond: toNumberOr(0, raw.bytesPerSecond),
};
}
export async function subscribeDesktopAppUpdateDownloadProgress(
handler: (progress: DesktopAppUpdateDownloadProgress | null) => void,
): Promise<DesktopEventUnlisten> {
if (!shouldShowDesktopUpdateSection()) {
return () => {};
}
return listenToDesktopEvent<unknown>("app-update-download-progress", (payload) => {
handler(payload === null ? null : parseDesktopAppUpdateDownloadProgress(payload));
});
}
export async function installDesktopAppUpdate({
releaseChannel,
}: {
@@ -181,12 +136,10 @@ export async function installDesktopAppUpdate({
throw new Error("Unexpected response while installing desktop update.");
}
const errorMessage = toStringOrNull(result.errorMessage);
return {
installed: result.installed === true,
version: toStringOrNull(result.version),
message: toStringOrNull(result.message) ?? i18n.t("desktop.updates.status.installed"),
...(errorMessage ? { errorMessage } : {}),
};
}
@@ -76,50 +76,6 @@ describe("resolveUpdateCalloutDescriptor", () => {
expect(descriptor?.dismissalKey).toBe("desktop-update:installing:1.2.3");
});
it("labels the callout as Download when the update has not been downloaded yet", () => {
const descriptor = resolveUpdateCalloutDescriptor(
input({ availableUpdate: { latestVersion: "1.2.3", readyToInstall: false } }),
);
expect(descriptor?.title).toBe("Update available");
expect(descriptor?.body).toEqual({
kind: "available",
versionLabel: "v1.2.3",
readyToInstall: false,
});
expect(descriptor?.actions).toEqual([
{ role: "changelog", label: "What's new" },
{ role: "install", label: "Download", variant: "primary", disabled: false },
]);
});
it("shows download progress while downloading an update", () => {
const descriptor = resolveUpdateCalloutDescriptor(
input({
status: "installing",
isInstalling: true,
downloadProgress: {
version: "1.2.3",
percent: 42.2,
transferred: 42,
total: 100,
bytesPerSecond: 10,
},
}),
);
expect(descriptor?.title).toBe("Downloading update");
expect(descriptor?.body).toEqual({
kind: "downloading",
versionLabel: "v1.2.3",
percent: 42,
});
expect(descriptor?.actions).toEqual([
{ role: "changelog", label: "What's new" },
{ role: "install", label: "Downloading...", variant: "primary", disabled: true },
]);
});
it("shows a retry action and surfaces the error message on error", () => {
const descriptor = resolveUpdateCalloutDescriptor(
input({ status: "error", errorMessage: "Download failed", availableUpdate: null }),
@@ -1,10 +1,8 @@
import type { DesktopAppUpdateStatus } from "@/desktop/updates/use-desktop-app-updater";
import type { DesktopAppUpdateDownloadProgress } from "@/desktop/updates/desktop-updates";
import { i18n } from "@/i18n/i18next";
export type UpdateCalloutBody =
| { kind: "available"; versionLabel: string | null; readyToInstall?: boolean }
| { kind: "downloading"; versionLabel: string | null; percent: number }
| { kind: "available"; versionLabel: string | null }
| { kind: "installing" }
| { kind: "error"; message: string };
@@ -33,8 +31,7 @@ export interface ResolveUpdateCalloutInput {
isDesktopApp: boolean;
status: DesktopAppUpdateStatus;
isInstalling: boolean;
availableUpdate: { latestVersion?: string | null; readyToInstall?: boolean } | null;
downloadProgress?: DesktopAppUpdateDownloadProgress | null;
availableUpdate: { latestVersion?: string | null } | null;
errorMessage: string | null;
}
@@ -43,59 +40,6 @@ function formatVersionLabel(latestVersion: string | null | undefined): string |
return `v${latestVersion.replace(/^v/i, "")}`;
}
function resolveCalloutPresentation(input: {
isError: boolean;
isInstalling: boolean;
readyToInstall: boolean;
latestVersion: string | null;
downloadProgress: DesktopAppUpdateDownloadProgress | null | undefined;
errorMessage: string | null;
}): { title: string; body: UpdateCalloutBody } {
if (input.isInstalling && input.downloadProgress != null) {
return {
title: i18n.t("desktop.updates.callout.downloadingTitle"),
body: {
kind: "downloading",
versionLabel: formatVersionLabel(input.latestVersion),
percent: Math.round(input.downloadProgress.percent),
},
};
}
if (input.isInstalling) {
return {
title: i18n.t("desktop.updates.callout.installingTitle"),
body: { kind: "installing" },
};
}
if (input.isError) {
return {
title: i18n.t("desktop.updates.callout.failedTitle"),
body: {
kind: "error",
message: input.errorMessage ?? i18n.t("desktop.updates.callout.genericError"),
},
};
}
const versionLabel = formatVersionLabel(input.latestVersion);
return {
title: i18n.t("desktop.updates.callout.availableTitle"),
body: input.readyToInstall
? { kind: "available", versionLabel }
: { kind: "available", versionLabel, readyToInstall: false },
};
}
function resolveInstallActionLabel(input: {
isDownloading: boolean;
isInstalling: boolean;
readyToInstall: boolean;
}): string {
if (input.isDownloading) return i18n.t("desktop.updates.callout.downloadingAction");
if (input.isInstalling) return i18n.t("desktop.updates.callout.installingAction");
if (input.readyToInstall) return i18n.t("desktop.updates.callout.installAndRestart");
return i18n.t("desktop.updates.callout.downloadAndRestart");
}
export function resolveUpdateCalloutDescriptor(
input: ResolveUpdateCalloutInput,
): UpdateCalloutDescriptor | null {
@@ -106,22 +50,26 @@ export function resolveUpdateCalloutDescriptor(
const isError = input.status === "error";
const isInstalling = input.isInstalling;
const isDownloading = isInstalling && input.downloadProgress != null;
const isAvailable = !isInstalling && !isError;
const readyToInstall = input.availableUpdate?.readyToInstall !== false;
const latestVersion =
input.availableUpdate?.latestVersion ?? input.downloadProgress?.version ?? null;
const latestVersion = input.availableUpdate?.latestVersion ?? null;
const dismissalKey = `desktop-update:${input.status}:${latestVersion ?? "unknown"}`;
const { title, body } = resolveCalloutPresentation({
isError,
isInstalling,
readyToInstall,
latestVersion,
downloadProgress: input.downloadProgress,
errorMessage: input.errorMessage,
});
let title: string;
let body: UpdateCalloutBody;
if (isInstalling) {
title = i18n.t("desktop.updates.callout.installingTitle");
body = { kind: "installing" };
} else if (isError) {
title = i18n.t("desktop.updates.callout.failedTitle");
body = {
kind: "error",
message: input.errorMessage ?? i18n.t("desktop.updates.callout.genericError"),
};
} else {
title = i18n.t("desktop.updates.callout.availableTitle");
body = { kind: "available", versionLabel: formatVersionLabel(latestVersion) };
}
const actions: UpdateCalloutActionDescriptor[] = [
{ role: "changelog", label: i18n.t("desktop.updates.callout.whatsNew") },
@@ -131,7 +79,9 @@ export function resolveUpdateCalloutDescriptor(
} else {
actions.push({
role: "install",
label: resolveInstallActionLabel({ isDownloading, isInstalling, readyToInstall }),
label: isInstalling
? i18n.t("desktop.updates.callout.installingAction")
: i18n.t("desktop.updates.callout.installAndRestart"),
variant: "primary",
disabled: isInstalling,
});
@@ -34,12 +34,9 @@ type InstallOutcome =
function buildCheckResult(
overrides: Partial<DesktopAppUpdateCheckResult> = {},
): DesktopAppUpdateCheckResult {
const hasUpdate = overrides.hasUpdate ?? false;
const readyToInstall = overrides.readyToInstall ?? false;
return {
hasUpdate,
readyToInstall,
downloading: overrides.downloading ?? (hasUpdate && !readyToInstall),
hasUpdate: false,
readyToInstall: false,
currentVersion: null,
latestVersion: null,
body: null,
@@ -1,8 +1,7 @@
import { Gift } from "lucide-react-native";
import { type ReactNode, useEffect, useMemo, useRef } from "react";
import { View } from "react-native";
import { type ReactNode, useEffect, useRef } from "react";
import { useTranslation } from "react-i18next";
import { StyleSheet, useUnistyles } from "react-native-unistyles";
import { useUnistyles } from "react-native-unistyles";
import {
type SidebarCalloutAction,
SidebarCalloutDescriptionText,
@@ -20,24 +19,9 @@ import { openChangelog } from "@/changelog";
const CHECK_INTERVAL_MS = 30 * 60 * 1000;
function renderBody(body: UpdateCalloutBody, t: ReturnType<typeof useTranslation>["t"]): ReactNode {
if (body.kind === "downloading") {
return (
<UpdateDownloadingDescription
versionLabel={body.versionLabel ?? undefined}
percent={body.percent}
t={t}
/>
);
}
if (body.kind === "installing") return t("desktop.updates.callout.installingDescription");
if (body.kind === "error") return body.message;
return (
<UpdateAvailableDescription
versionLabel={body.versionLabel ?? undefined}
readyToInstall={body.readyToInstall !== false}
t={t}
/>
);
return <UpdateAvailableDescription versionLabel={body.versionLabel ?? undefined} t={t} />;
}
function materializeActions(
@@ -58,11 +42,8 @@ export function UpdateCalloutSource() {
const { theme } = useUnistyles();
const {
isDesktopApp,
updateMode,
isLoadingSettings,
status,
availableUpdate,
downloadProgress,
errorMessage,
checkForUpdates,
installUpdate,
@@ -77,7 +58,7 @@ export function UpdateCalloutSource() {
void checkForUpdates();
});
useEffect(() => {
if (!isDesktopApp || isLoadingSettings || updateMode === "off") return;
if (!isDesktopApp) return;
void checkForUpdates({ intent: "automatic", silent: true });
@@ -90,7 +71,7 @@ export function UpdateCalloutSource() {
clearInterval(intervalRef.current);
}
};
}, [isDesktopApp, isLoadingSettings, updateMode, checkForUpdates]);
}, [isDesktopApp, checkForUpdates]);
useEffect(() => {
const descriptor = resolveUpdateCalloutDescriptor({
@@ -98,7 +79,6 @@ export function UpdateCalloutSource() {
status,
isInstalling,
availableUpdate,
downloadProgress,
errorMessage,
});
if (!descriptor) return;
@@ -123,7 +103,6 @@ export function UpdateCalloutSource() {
}, [
availableUpdate,
callouts,
downloadProgress,
errorMessage,
install,
isDesktopApp,
@@ -138,94 +117,23 @@ export function UpdateCalloutSource() {
return null;
}
function formatAvailableSummary(
t: ReturnType<typeof useTranslation>["t"],
versionLabel: string | undefined,
readyToInstall: boolean,
): string {
if (readyToInstall) {
return versionLabel
? t("desktop.updates.callout.versionReady", { version: versionLabel })
: t("desktop.updates.callout.newVersionReady");
}
return versionLabel
? t("desktop.updates.callout.versionAvailable", { version: versionLabel })
: t("desktop.updates.callout.newVersionAvailable");
}
function UpdateAvailableDescription({
versionLabel,
readyToInstall,
t,
}: {
versionLabel?: string;
readyToInstall: boolean;
t: ReturnType<typeof useTranslation>["t"];
}) {
const summary = formatAvailableSummary(t, versionLabel, readyToInstall);
return (
<>
<SidebarCalloutDescriptionText>{summary}</SidebarCalloutDescriptionText>
<SidebarCalloutDescriptionText>
{versionLabel
? t("desktop.updates.callout.versionReady", { version: versionLabel })
: t("desktop.updates.callout.newVersionReady")}
</SidebarCalloutDescriptionText>
<SidebarCalloutDescriptionText>
{t("desktop.updates.callout.restartWarning")}
</SidebarCalloutDescriptionText>
</>
);
}
function UpdateDownloadingDescription({
versionLabel,
percent,
t,
}: {
versionLabel?: string;
percent: number;
t: ReturnType<typeof useTranslation>["t"];
}) {
const clampedPercent = Math.max(0, Math.min(100, percent));
const accessibilityValue = useMemo(
() => ({ min: 0, max: 100, now: clampedPercent }),
[clampedPercent],
);
const progressFillStyle = useMemo(
() => [styles.progressFill, { width: `${clampedPercent}%` as const }],
[clampedPercent],
);
return (
<View style={styles.progressContainer}>
<SidebarCalloutDescriptionText>
{versionLabel
? t("desktop.updates.callout.downloadingVersionDescription", {
version: versionLabel,
percent: clampedPercent,
})
: t("desktop.updates.callout.downloadingDescription", { percent: clampedPercent })}
</SidebarCalloutDescriptionText>
<View
style={styles.progressTrack}
accessibilityRole="progressbar"
accessibilityValue={accessibilityValue}
>
<View style={progressFillStyle} />
</View>
</View>
);
}
const styles = StyleSheet.create((theme) => ({
progressContainer: {
gap: theme.spacing[2],
},
progressTrack: {
height: 4,
borderRadius: theme.borderRadius.full,
backgroundColor: theme.colors.surface3,
overflow: "hidden",
},
progressFill: {
height: "100%",
borderRadius: theme.borderRadius.full,
backgroundColor: theme.colors.accent,
},
}));
@@ -1,94 +1,30 @@
import { useCallback, useEffect, useSyncExternalStore } from "react";
import { useCallback, useEffect, useMemo, useSyncExternalStore } from "react";
import {
checkDesktopAppUpdate,
formatVersionWithPrefix,
installDesktopAppUpdate,
shouldShowDesktopUpdateSection,
subscribeDesktopAppUpdateDownloadProgress,
type DesktopAppUpdateCheckResult,
type DesktopAppUpdateCheckIntent,
type DesktopAppUpdateDownloadProgress,
type DesktopAppUpdateInstallResult,
} from "@/desktop/updates/desktop-updates";
import { useDesktopSettings, type DesktopUpdateMode } from "@/desktop/settings/desktop-settings";
import { useDesktopSettings } from "@/desktop/settings/desktop-settings";
import { useDesktopIpcErrorReporter } from "@/desktop/hooks/desktop-ipc-error";
import {
PENDING_RECHECK_MS,
createDesktopAppUpdater,
formatStatusText,
type DesktopAppUpdater,
type DesktopAppUpdaterErrorReport,
type DesktopAppUpdateStatus,
} from "@/desktop/updates/desktop-app-updater";
import { formatMessageTimestamp } from "@/utils/time";
export type { DesktopAppUpdateStatus };
let activeInstallErrorReporter: ((report: DesktopAppUpdaterErrorReport) => void) | null = null;
let sharedDesktopAppUpdater: DesktopAppUpdater | null = null;
let progressSubscriptionCount = 0;
let progressUnsubscribe: (() => void) | null = null;
function getSharedDesktopAppUpdater(): DesktopAppUpdater {
if (!sharedDesktopAppUpdater) {
sharedDesktopAppUpdater = createDesktopAppUpdater({
port: {
checkDesktopAppUpdate,
installDesktopAppUpdate,
},
now: () => Date.now(),
reportInstallError: (report) => {
activeInstallErrorReporter?.(report);
},
});
}
return sharedDesktopAppUpdater;
}
function retainDownloadProgressSubscription(updater: DesktopAppUpdater): () => void {
progressSubscriptionCount += 1;
if (progressSubscriptionCount === 1) {
let active = true;
const teardown = () => {
active = false;
};
progressUnsubscribe = teardown;
void subscribeDesktopAppUpdateDownloadProgress((progress) => {
if (active) {
updater.setDownloadProgress(progress);
}
})
.then((cleanup) => {
if (active) {
progressUnsubscribe = () => {
active = false;
cleanup();
};
} else {
cleanup();
}
return undefined;
})
.catch(() => undefined);
}
return () => {
progressSubscriptionCount = Math.max(0, progressSubscriptionCount - 1);
if (progressSubscriptionCount === 0) {
progressUnsubscribe?.();
progressUnsubscribe = null;
}
};
}
export interface UseDesktopAppUpdaterReturn {
isDesktopApp: boolean;
updateMode: DesktopUpdateMode;
isLoadingSettings: boolean;
status: DesktopAppUpdateStatus;
statusText: string;
availableUpdate: DesktopAppUpdateCheckResult | null;
downloadProgress: DesktopAppUpdateDownloadProgress | null;
errorMessage: string | null;
lastCheckedAt: number | null;
isChecking: boolean;
@@ -102,15 +38,22 @@ export interface UseDesktopAppUpdaterReturn {
export function useDesktopAppUpdater(): UseDesktopAppUpdaterReturn {
const isDesktopApp = shouldShowDesktopUpdateSection();
const { settings: desktopSettings, isLoading: isLoadingSettings } = useDesktopSettings();
const { settings: desktopSettings } = useDesktopSettings();
const releaseChannel = desktopSettings.releaseChannel;
const updateMode = desktopSettings.updates.mode;
const reportError = useDesktopIpcErrorReporter();
const updater = getSharedDesktopAppUpdater();
useEffect(() => {
activeInstallErrorReporter = reportError;
}, [reportError]);
const updater = useMemo(
() =>
createDesktopAppUpdater({
port: {
checkDesktopAppUpdate,
installDesktopAppUpdate,
},
now: () => Date.now(),
reportInstallError: reportError,
}),
[reportError],
);
const snapshot = useSyncExternalStore(
updater.subscribe,
@@ -141,20 +84,13 @@ export function useDesktopAppUpdater(): UseDesktopAppUpdaterReturn {
useEffect(() => {
if (!isDesktopApp) {
return undefined;
}
return retainDownloadProgressSubscription(updater);
}, [isDesktopApp, updater]);
useEffect(() => {
if (!isDesktopApp || isLoadingSettings || updateMode === "off") {
return;
}
void checkForUpdates({ intent: "automatic", silent: true });
}, [checkForUpdates, isDesktopApp, isLoadingSettings, updateMode]);
}, [checkForUpdates, isDesktopApp]);
useEffect(() => {
if (!isDesktopApp || snapshot.status !== "pending" || updateMode === "off") {
if (!isDesktopApp || snapshot.status !== "pending") {
return undefined;
}
@@ -165,24 +101,20 @@ export function useDesktopAppUpdater(): UseDesktopAppUpdaterReturn {
return () => {
clearInterval(intervalId);
};
}, [checkForUpdates, isDesktopApp, snapshot.status, updateMode]);
}, [checkForUpdates, isDesktopApp, snapshot.status]);
return {
isDesktopApp,
updateMode,
isLoadingSettings,
status: snapshot.status,
statusText: formatStatusText({
status: snapshot.status,
availableUpdate: snapshot.availableUpdate,
downloadProgress: snapshot.downloadProgress,
installMessage: snapshot.installMessage,
lastCheckedAt: snapshot.lastCheckedAt,
formatVersion: formatVersionWithPrefix,
formatLastCheckedAt: (timestamp) => formatMessageTimestamp(new Date(timestamp)),
}),
availableUpdate: snapshot.availableUpdate,
downloadProgress: snapshot.downloadProgress,
errorMessage: snapshot.errorMessage,
lastCheckedAt: snapshot.lastCheckedAt,
isChecking: snapshot.isChecking,
-2
View File
@@ -1,2 +0,0 @@
export { PairDeviceModal } from "./pair-device-modal";
export { WaysToConnect } from "./ways-to-connect";
@@ -1,36 +0,0 @@
import { describe, expect, it } from "vitest";
import type { TailscaleStatus } from "@getpaseo/protocol/messages";
import { i18n } from "@/i18n/i18next";
import { describeTailscale } from "./tailscale-hint";
// Statuses as the host reports them; see `createDaemonListeners` in the server's listeners.ts.
const off: TailscaleStatus = { ip: "100.101.102.103", address: null, state: "off" };
describe("the Tailscale row's hint", () => {
it("says why Tailscale stays off when the host listens on a socket", () => {
const socketHint = "Off, because this host listens on a local socket";
expect(describeTailscale({ ...off, lockedBy: "main", mainIsSocket: true }, i18n.t)).toBe(
socketHint,
);
expect(describeTailscale({ ...off, lockedBy: "launch", mainIsSocket: true }, i18n.t)).toBe(
socketHint,
);
});
it("keeps the hint of every other state", () => {
const hint = (status: TailscaleStatus) => describeTailscale(status, i18n.t);
expect(hint(off)).toBe("Direct over your tailnet, enter an address");
expect(hint({ ip: null, address: null, state: "unavailable", lockedBy: "launch" })).toBe(
"Tailscale is not running on this host",
);
expect(hint({ ...off, state: "waiting", address: "100.101.102.103:6767" })).toBe(
"Waiting for Tailscale to start on this host",
);
expect(hint({ ...off, state: "on", address: "100.101.102.103:6767", lockedBy: "main" })).toBe(
"Always on, because this host already accepts Tailscale connections",
);
expect(hint({ ...off, lockedBy: "launch" })).toBe(
"Controlled by the command that starts this host",
);
});
});
@@ -1,13 +0,0 @@
import type { TailscaleStatus } from "@getpaseo/protocol/messages";
import type { TFunction } from "i18next";
/** The line under the Tailscale label for each state the host reports, most specific first. */
export function describeTailscale(status: TailscaleStatus, t: TFunction): string {
if (status.state === "unavailable") return t("devices.tailscale.unavailable");
if (status.state === "waiting") return t("devices.tailscale.waiting");
// A socket is why Tailscale cannot be on, even when the launch command also fixes the address.
if (status.mainIsSocket) return t("devices.tailscale.socket");
if (status.lockedBy === "launch") return t("devices.tailscale.launch");
if (status.lockedBy === "main") return t("devices.tailscale.alwaysOn");
return t("devices.tailscale.hint");
}
-202
View File
@@ -1,202 +0,0 @@
import { useCallback, useMemo } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import { SettingsAction, SettingsRowChildren, SettingsSwitch } from "@/components/settings";
import { useToast } from "@/contexts/toast-context";
import { useFetchQuery } from "@/data/query";
import { useHostRuntimeClient, useHostRuntimeSnapshot } from "@/runtime/host-runtime";
import { useSessionStore } from "@/stores/session-store";
import { confirmDialog } from "@/utils/confirm-dialog";
import { copyToClipboard } from "@/utils/copy-to-clipboard";
import { describeTailscale } from "./tailscale-hint";
const UPDATES_DOCS_URL = "https://paseo.sh/docs/updates";
const TAILSCALE_DOWNLOAD_URL = "https://tailscale.com/download";
// A product name, the same in every language.
const LABEL = "Tailscale";
type HostClient = NonNullable<ReturnType<typeof useHostRuntimeClient>>;
/**
* Turns Tailscale on or off for a host and shows the address a phone on the tailnet adds. Renders
* as a row inside a `SettingsCard`; when Tailscale is on, the address is a nested row under it.
*/
export function TailscaleRow({ serverId }: { serverId: string }) {
const { t } = useTranslation();
const client = useHostRuntimeClient(serverId);
const connection = useHostRuntimeSnapshot(serverId)?.connectionStatus;
const serverInfo = useSessionStore((state) => state.sessions[serverId]?.serverInfo);
const updateLink = useMemo(
() => ({ href: UPDATES_DOCS_URL, label: t("devices.tailscale.updateDocs") }),
[t],
);
// COMPAT(tailscale): added in v0.16.0, remove after 2027-05-25 once daemon floor >= v0.16.0.
if (serverInfo && serverInfo.features?.tailscale !== true) {
return (
<SettingsSwitch
label={LABEL}
hint={t("devices.tailscale.update")}
link={updateLink}
value={false}
disabled
/>
);
}
if (client && connection === "online" && serverInfo) {
return <TailscaleControl serverId={serverId} client={client} />;
}
// Without the host the row shows no value: the switch's space stays empty. A host the app has
// reached before keeps its server info, so while the app retries it still reads as disconnected.
const lost = connection === "offline" || connection === "error" || Boolean(serverInfo);
return (
<SettingsSwitch
label={LABEL}
hint={t(lost ? "workspace.terminal.hostDisconnected" : "devices.tailscale.hint")}
value={null}
/>
);
}
function TailscaleControl({ serverId, client }: { serverId: string; client: HostClient }) {
const { t } = useTranslation();
const tailscale = useTailscale(serverId, client);
const { status } = tailscale;
const installLink = useMemo(
() => ({ href: TAILSCALE_DOWNLOAD_URL, label: t("devices.tailscale.install") }),
[t],
);
return (
<>
<SettingsSwitch
label={LABEL}
hint={status ? describeTailscale(status, t) : t("devices.tailscale.hint")}
link={status?.state === "unavailable" ? installLink : undefined}
error={tailscale.error}
value={tailscale.value}
disabled={!status || status.state === "unavailable" || Boolean(status.lockedBy)}
onValueChange={tailscale.setEnabled}
/>
{tailscale.address ? <TailscaleAddress address={tailscale.address} /> : null}
</>
);
}
function TailscaleAddress({ address }: { address: string }) {
const { t } = useTranslation();
const toast = useToast();
const copy = useCallback(() => {
void copyToClipboard(address)
.then(() => toast.copied())
.catch(() => toast.error(t("common.errors.error")));
}, [address, t, toast]);
return (
<SettingsRowChildren>
<SettingsAction
label={address}
hint={t("devices.tailscale.address")}
actionLabel={t("common.actions.copy")}
onPress={copy}
testID="devices-tailscale-address"
/>
</SettingsRowChildren>
);
}
interface TailscaleChange {
enabled: boolean;
confirmed: boolean;
}
/**
* The host's Tailscale state and the one way to change it. While a change is in flight the switch
* already shows where it is going, so a tap answers at once; the host's answer then settles it.
* Turning Tailscale off over the connection it would cut asks first, and nothing changes on screen
* until the user confirms.
*/
function useTailscale(serverId: string, client: HostClient) {
const { t } = useTranslation();
const queryClient = useQueryClient();
const queryKey = useMemo(() => ["tailscale-status", serverId], [serverId]);
const query = useFetchQuery({
queryKey,
queryFn: async () => {
const { tailscale } = await client.getDaemonStatus({ includeProviders: false });
if (!tailscale) throw new Error("Host did not report Tailscale status");
return tailscale;
},
// Tailscale can come up after the host does; polling moves "waiting" to "on" on its own.
refetchInterval: 2_000,
staleTimeMs: 0,
dataShape: "value",
});
const change = useMutation({
mutationFn: async ({ enabled, confirmed }: TailscaleChange) => {
await queryClient.cancelQueries({ queryKey });
return client.setTailscaleEnabled(enabled, confirmed);
},
onSuccess: (result) => queryClient.setQueryData(queryKey, result.tailscale),
});
const status = query.data;
const pending = change.isPending ? change.variables.enabled : undefined;
const on = status?.state === "on" || status?.state === "waiting";
// Not known until the host first answers.
const value = pending ?? (status ? on : null);
const { mutate } = change;
const confirmTurnOff = useCallback(
() =>
confirmDialog({
title: t("devices.tailscale.confirmTitle"),
message: t("devices.tailscale.confirmMessage"),
confirmLabel: t("devices.tailscale.confirmAction"),
cancelLabel: t("common.actions.cancel"),
destructive: true,
}),
[t],
);
const turnOffConfirmed = useCallback(async () => {
if (await confirmTurnOff()) mutate({ enabled: false, confirmed: true });
}, [confirmTurnOff, mutate]);
const disconnects = status?.disconnectsCurrentConnection === true;
const setEnabled = useCallback(
(enabled: boolean) => {
if (!enabled && disconnects) {
void turnOffConfirmed();
return;
}
mutate(
{ enabled, confirmed: false },
{
// The status was stale: the host would cut this connection after all. Its answer has
// already put the row back to on, so the question is asked over what is true.
onSuccess: (result) => {
if (result.confirmationRequired) void turnOffConfirmed();
},
},
);
},
[disconnects, mutate, turnOffConfirmed],
);
let error: string | undefined;
if (change.isError) {
error = t(
change.variables.enabled ? "devices.tailscale.turnOnError" : "devices.tailscale.turnOffError",
);
} else if (query.isError && !status) {
error = t("devices.tailscale.statusError");
}
return {
status,
value,
error,
// A tap is ignored until the host answers the one before it.
setEnabled: change.isPending ? undefined : setEnabled,
address: status?.state === "on" && value ? status.address : null,
};
}
@@ -1,51 +0,0 @@
import { useCallback, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { SettingsCard, SettingsDetailRow, SettingsSection } from "@/components/settings";
import { StatusBadge } from "@/components/ui/status-badge";
import { PairDeviceModal } from "./pair-device-modal";
import { CONNECTIVITY_DOCS_URL } from "./pair-device-section";
import { TailscaleRow } from "./tailscale-row";
/**
* The ways another device can connect to a host: Relay, which pairs through a QR code in a sheet,
* and Tailscale, a switch and an address. Settings and the setup's phone step show this same block.
*/
export function WaysToConnect({ serverId }: { serverId: string }) {
const { t } = useTranslation();
const [pairing, setPairing] = useState(false);
const openPairing = useCallback(() => setPairing(true), []);
const closePairing = useCallback(() => setPairing(false), []);
const recommended = useMemo(
() => <StatusBadge size="xs" variant="success" label={t("devices.recommended")} />,
[t],
);
const docsLink = useMemo(
() => ({
href: CONNECTIVITY_DOCS_URL,
label: t("devices.docs"),
accessibilityLabel: t("devices.docsAccessibility"),
}),
[t],
);
return (
<SettingsSection title={t("devices.waysToConnect")} link={docsLink}>
<SettingsCard>
<SettingsDetailRow
label={t("devices.relay.title")}
labelAccessory={recommended}
hint={t("devices.relay.hint")}
onPress={openPairing}
testID="devices-relay"
/>
<TailscaleRow serverId={serverId} />
</SettingsCard>
<PairDeviceModal
serverId={serverId}
visible={pairing}
onClose={closePairing}
testID="devices-relay-pairing"
/>
</SettingsSection>
);
}
@@ -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"),
},
],
@@ -32,9 +32,6 @@ export interface FakeDesktopBridge extends DesktopSettingsBridge {
const DEFAULT_DESKTOP: DesktopSettings = {
releaseChannel: "stable",
updates: {
mode: "automatic",
},
notifications: {
playSound: true,
},
@@ -656,7 +656,6 @@ describe("loadSettingsFromStorage", () => {
isElectron: true,
settings: {
releaseChannel: "beta",
updates: { mode: "automatic" },
notifications: { playSound: true },
daemon: { manageBuiltInDaemon: false, keepRunningAfterQuit: true },
},
+21 -62
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: "فشل في إغلاق الوكيل",
},
@@ -1550,8 +1563,6 @@ export const ar: TranslationResources = {
status: {
checking: "جارٍ التحقق من وجود تحديثات للتطبيق...",
installing: "جارٍ تثبيت تحديث التطبيق...",
downloadingVersionProgress: "جارٍ تنزيل {{version}}... {{percent}}%",
downloadingProgress: "جارٍ تنزيل تحديث التطبيق... {{percent}}%",
upToDate: "التطبيق محدث.",
upToDateWithLastChecked: "Up to date. Last checked at {{time}}.",
pending: "سنخبرك عندما يصبح التحديث جاهزًا.",
@@ -1559,14 +1570,6 @@ export const ar: TranslationResources = {
pendingWithVersion: "تم العثور على تحديث: {{version}}. جارٍ التنزيل...",
pendingWithVersionAndLastChecked:
"تم العثور على تحديث: {{version}}. جارٍ التنزيل... آخر فحص في {{time}}.",
pendingWithVersionProgress: "تم العثور على تحديث: {{version}}. جارٍ التنزيل... {{percent}}%",
pendingWithVersionProgressAndLastChecked:
"تم العثور على تحديث: {{version}}. جارٍ التنزيل... {{percent}}% آخر فحص في {{time}}.",
downloadAvailableWithVersion: "التحديث متاح: {{version}}",
downloadAvailableWithVersionAndLastChecked:
"التحديث متاح: {{version}}. آخر فحص في {{time}}.",
downloadAvailable: "يتوفر تحديث للتطبيق.",
downloadAvailableWithLastChecked: "يتوفر تحديث للتطبيق. آخر فحص في {{time}}.",
availableWithVersion: "التحديث جاهز:{{version}}",
availableWithVersionAndLastChecked: "التحديث جاهز:{{version}}. آخر فحص في {{time}}.",
available: "تحديث التطبيق جاهز للتثبيت.",
@@ -1577,21 +1580,14 @@ export const ar: TranslationResources = {
},
installError: "غير قادر على تثبيت تحديث تطبيق سطح المكتب.",
callout: {
downloadingTitle: "جارٍ تنزيل التحديث",
installingTitle: "تثبيت التحديث",
failedTitle: "فشل التحديث",
availableTitle: "التحديث متاح",
genericError: "حدث خطأ ما.",
whatsNew: "ما هو الجديد",
downloadingAction: "جارٍ التنزيل...",
installingAction: "جارٍ التثبيت...",
downloadAndRestart: "تنزيل",
installAndRestart: "التثبيت وإعادة التشغيل",
downloadingVersionDescription: "جارٍ تنزيل {{version}}... {{percent}}%",
downloadingDescription: "جارٍ تنزيل التحديث... {{percent}}%",
installingDescription: "التثبيت وإعادة التشغيل...",
versionAvailable: "{{version}} متاح للتنزيل.",
newVersionAvailable: "يتوفر إصدار جديد للتنزيل.",
versionReady: "{{version}}جاهز للتثبيت.",
newVersionReady: "إصدار جديد جاهز للتثبيت.",
restartWarning: "ستؤدي ترقية التطبيق إلى إيقاف تشغيل الوكلاء وإغلاق الجلسات الطرفية.",
@@ -1808,6 +1804,12 @@ export const ar: TranslationResources = {
"يتيح لك تطبيق الجوال الأصلي كامل الميزات التحكم في أي كمبيوتر يعمل عليه Paseo من هاتفك",
appStore: "App Store",
googlePlay: "Google Play",
connectTitle: "اختر طريقة الاتصال",
connectDocs: "الوثائق",
openConnectDocs: "افتح وثائق الاتصال",
recommended: "موصى به",
relay: { title: "التتابع", hint: "مشفّر من طرف إلى طرف، امسح رمز QR" },
tailscale: { title: "Tailscale", hint: "يتطلب بعض الإعداد" },
},
},
},
@@ -1886,32 +1888,6 @@ export const ar: TranslationResources = {
hostDisconnected: "Host غير متصل",
},
},
devices: {
title: "الأجهزة",
waysToConnect: "طرق الاتصال",
docs: "الوثائق",
docsAccessibility: "افتح وثائق الاتصال",
recommended: "موصى به",
relay: { title: "التتابع", hint: "مشفّر من طرف إلى طرف، امسح رمز QR" },
tailscale: {
hint: "اتصال مباشر عبر شبكة tailnet الخاصة بك، أدخل عنوانًا",
unavailable: "Tailscale لا يعمل على هذا المضيف",
install: "احصل على Tailscale",
waiting: "في انتظار بدء Tailscale على هذا المضيف",
alwaysOn: "مفعّل دائمًا، لأن هذا المضيف يقبل اتصالات Tailscale بالفعل",
socket: "متوقف، لأن هذا المضيف يستمع على مقبس محلي",
launch: "يتحكم فيه الأمر الذي يشغّل هذا المضيف",
update: "حدّث هذا المضيف لاستخدام Tailscale",
updateDocs: "طريقة التحديث",
address: "على هاتف متصل بـ Tailscale، أضف مضيفًا بهذا العنوان",
statusError: "تعذّر التحقق من Tailscale",
turnOnError: "تعذّر تشغيل Tailscale",
turnOffError: "تعذّر إيقاف Tailscale",
confirmTitle: "إيقاف Tailscale؟",
confirmMessage: "هذا الجهاز متصل عبر Tailscale وسيفقد اتصاله بالمضيف.",
confirmAction: "إيقاف",
},
},
pairing: {
hostPassword: {
title: "كلمة المرور لـ {{host}}",
@@ -2693,28 +2669,9 @@ export const ar: TranslationResources = {
stable: "Stable",
beta: "Beta",
},
autoUpdate: {
label: "التحديثات التلقائية",
options: {
automatic: "تلقائي",
notify: "إشعار",
off: "إيقاف",
},
descriptions: {
automatic: "التحقق من التحديثات وتنزيلها في الخلفية",
notify: "التحقق من التحديثات وتنزيلها فقط عند اختيارك",
off: "عدم التحقق تلقائيًا. يتم التحقق فقط عند النقر على فحص",
},
},
updates: {
label: "تحديثات التطبيق",
readyToInstall: "جاهز للتثبيت:{{version}}",
downloadTitle: "تنزيل تحديث سطح المكتب",
downloadMessage: "سيؤدي هذا إلى تنزيل تحديث Paseo وتثبيته على هذا الكمبيوتر",
downloadConfirm: "تنزيل وتثبيت",
download: "تنزيل",
downloadTo: "تنزيل {{version}}",
downloading: "جارٍ التنزيل...",
installTitle: "تثبيت تحديث سطح المكتب",
installMessage: "يؤدي هذا إلى تحديث Paseo على هذا الكمبيوتر",
installConfirm: "تثبيت التحديث",
@@ -2985,7 +2942,9 @@ export const ar: TranslationResources = {
timeout: "نفذ الوقت",
},
pairDevices: {
title: "إقران الأجهزة",
rowTitle: "إقران جهاز",
rowHint: "امسح رمز QR ضوئيًا أو انسخ رابطًا لتوصيل هاتفك بهذا المضيف",
},
skills: {
...en.settings.host.skills,
+21 -63
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",
},
@@ -1577,8 +1590,6 @@ export const en = {
status: {
checking: "Checking for app updates...",
installing: "Installing app update...",
downloadingVersionProgress: "Downloading {{version}}... {{percent}}%",
downloadingProgress: "Downloading app update... {{percent}}%",
upToDate: "App is up to date.",
upToDateWithLastChecked: "Up to date. Last checked at {{time}}.",
pending: "We'll let you know when the update is ready.",
@@ -1587,14 +1598,6 @@ export const en = {
pendingWithVersion: "Update found: {{version}}. Downloading...",
pendingWithVersionAndLastChecked:
"Update found: {{version}}. Downloading... Last checked at {{time}}.",
pendingWithVersionProgress: "Update found: {{version}}. Downloading... {{percent}}%",
pendingWithVersionProgressAndLastChecked:
"Update found: {{version}}. Downloading... {{percent}}% Last checked at {{time}}.",
downloadAvailableWithVersion: "Update available: {{version}}",
downloadAvailableWithVersionAndLastChecked:
"Update available: {{version}}. Last checked at {{time}}.",
downloadAvailable: "An app update is available.",
downloadAvailableWithLastChecked: "An app update is available. Last checked at {{time}}.",
availableWithVersion: "Update ready: {{version}}",
availableWithVersionAndLastChecked: "Update ready: {{version}}. Last checked at {{time}}.",
available: "An app update is ready to install.",
@@ -1605,21 +1608,14 @@ export const en = {
},
installError: "Unable to install the desktop app update.",
callout: {
downloadingTitle: "Downloading update",
installingTitle: "Installing update",
failedTitle: "Update failed",
availableTitle: "Update available",
genericError: "Something went wrong.",
whatsNew: "What's new",
downloadingAction: "Downloading...",
installingAction: "Installing...",
downloadAndRestart: "Download",
installAndRestart: "Install & restart",
downloadingVersionDescription: "Downloading {{version}}... {{percent}}%",
downloadingDescription: "Downloading update... {{percent}}%",
installingDescription: "Installing and restarting...",
versionAvailable: "{{version}} is available to download.",
newVersionAvailable: "A new version is available to download.",
versionReady: "{{version}} is ready to install.",
newVersionReady: "A new version is ready to install.",
restartWarning: "Upgrading the app will stop running agents and close terminal sessions.",
@@ -1837,6 +1833,12 @@ export const en = {
"The fully featured native mobile app allows you to control any Paseo computer from your phone",
appStore: "App Store",
googlePlay: "Google Play",
connectTitle: "Choose how to connect",
connectDocs: "Docs",
openConnectDocs: "Open connectivity documentation",
recommended: "Recommended",
relay: { title: "Relay", hint: "End-to-end encrypted, scan a QR code" },
tailscale: { title: "Tailscale", hint: "Requires some setup" },
},
},
},
@@ -1915,33 +1917,6 @@ export const en = {
hostDisconnected: "Host is not connected",
},
},
devices: {
title: "Devices",
waysToConnect: "Ways to connect",
docs: "Docs",
docsAccessibility: "Open connectivity documentation",
recommended: "Recommended",
relay: { title: "Relay", hint: "End-to-end encrypted, scan a QR code" },
tailscale: {
hint: "Direct over your tailnet, enter an address",
unavailable: "Tailscale is not running on this host",
install: "Get Tailscale",
waiting: "Waiting for Tailscale to start on this host",
alwaysOn: "Always on, because this host already accepts Tailscale connections",
socket: "Off, because this host listens on a local socket",
launch: "Controlled by the command that starts this host",
update: "Update this host to use Tailscale",
updateDocs: "How to update",
address: "On a phone with Tailscale, add a host at this address",
statusError: "Could not check Tailscale",
turnOnError: "Could not turn on Tailscale",
turnOffError: "Could not turn off Tailscale",
confirmTitle: "Turn off Tailscale?",
confirmMessage:
"This device is connected through Tailscale and will lose its connection to the host.",
confirmAction: "Turn off",
},
},
pairing: {
hostPassword: {
title: "Password for {{host}}",
@@ -2790,28 +2765,9 @@ export const en = {
stable: "Stable",
beta: "Beta",
},
autoUpdate: {
label: "Automatic updates",
options: {
automatic: "Auto",
notify: "Notify",
off: "Off",
},
descriptions: {
automatic: "Check and download updates in the background",
notify: "Check for updates, but only download when you choose",
off: "Never check automatically. Only check when you click Check",
},
},
updates: {
label: "App updates",
readyToInstall: "Ready to install: {{version}}",
downloadTitle: "Download desktop update",
downloadMessage: "This downloads and installs the Paseo update on this computer",
downloadConfirm: "Download & install",
download: "Download",
downloadTo: "Download {{version}}",
downloading: "Downloading...",
installTitle: "Install desktop update",
installMessage: "This updates Paseo on this computer",
installConfirm: "Install update",
@@ -3081,7 +3037,9 @@ export const en = {
timeout: "Timeout",
},
pairDevices: {
title: "Pair devices",
rowTitle: "Pair a device",
rowHint: "Scan a QR code or copy a link to connect your phone to this host",
},
skills: {
sectionTitle: "Orchestration skills",
+21 -65
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",
},
@@ -1587,8 +1600,6 @@ export const es: TranslationResources = {
status: {
checking: "Buscando actualizaciones de la aplicación...",
installing: "Instalando actualización de la aplicación...",
downloadingVersionProgress: "Descargando {{version}}... {{percent}}%",
downloadingProgress: "Descargando actualización de la aplicación... {{percent}}%",
upToDate: "La aplicación está actualizada.",
upToDateWithLastChecked: "Up to date. Last checked at {{time}}.",
pending: "Le avisaremos cuando la actualización esté lista.",
@@ -1597,16 +1608,6 @@ export const es: TranslationResources = {
pendingWithVersion: "Actualización encontrada: {{version}}. Descargando...",
pendingWithVersionAndLastChecked:
"Actualización encontrada: {{version}}. Descargando... Última comprobación a las {{time}}.",
pendingWithVersionProgress:
"Actualización encontrada: {{version}}. Descargando... {{percent}}%",
pendingWithVersionProgressAndLastChecked:
"Actualización encontrada: {{version}}. Descargando... {{percent}}% Última comprobación a las {{time}}.",
downloadAvailableWithVersion: "Actualización disponible: {{version}}",
downloadAvailableWithVersionAndLastChecked:
"Actualización disponible: {{version}}. Última comprobación a las {{time}}.",
downloadAvailable: "Hay una actualización de la aplicación disponible.",
downloadAvailableWithLastChecked:
"Hay una actualización de la aplicación disponible. Última comprobación a las {{time}}.",
availableWithVersion: "Actualización lista:{{version}}",
availableWithVersionAndLastChecked:
"Actualización lista:{{version}}. Última comprobación a las {{time}}.",
@@ -1619,21 +1620,14 @@ export const es: TranslationResources = {
},
installError: "No se puede instalar la actualización de la aplicación de escritorio.",
callout: {
downloadingTitle: "Descargando actualización",
installingTitle: "Instalando actualización",
failedTitle: "La actualización falló",
availableTitle: "Actualización disponible",
genericError: "Algo salió mal.",
whatsNew: "Qué hay de nuevo",
downloadingAction: "Descargando...",
installingAction: "Instalando...",
downloadAndRestart: "Descargar",
installAndRestart: "Instalar y reiniciar",
downloadingVersionDescription: "Descargando {{version}}... {{percent}}%",
downloadingDescription: "Descargando actualización... {{percent}}%",
installingDescription: "Instalando y reiniciando...",
versionAvailable: "{{version}} está disponible para descargar.",
newVersionAvailable: "Una nueva versión está disponible para descargar.",
versionReady: "{{version}}está listo para instalar.",
newVersionReady: "Una nueva versión está lista para instalar.",
restartWarning:
@@ -1858,6 +1852,12 @@ export const es: TranslationResources = {
"La app móvil nativa completa te permite controlar cualquier ordenador con Paseo desde tu teléfono",
appStore: "App Store",
googlePlay: "Google Play",
connectTitle: "Elige cómo conectarte",
connectDocs: "Docs",
openConnectDocs: "Abrir la documentación de conectividad",
recommended: "Recomendado",
relay: { title: "Relé", hint: "Cifrado de extremo a extremo, escanea un código QR" },
tailscale: { title: "Tailscale", hint: "Requiere algo de configuración" },
},
},
},
@@ -1936,33 +1936,6 @@ export const es: TranslationResources = {
hostDisconnected: "Hostno está conectado",
},
},
devices: {
title: "Dispositivos",
waysToConnect: "Formas de conectarse",
docs: "Docs",
docsAccessibility: "Abrir la documentación de conectividad",
recommended: "Recomendado",
relay: { title: "Relé", hint: "Cifrado de extremo a extremo, escanea un código QR" },
tailscale: {
hint: "Conexión directa por tu tailnet, introduce una dirección",
unavailable: "Tailscale no se está ejecutando en este host",
install: "Obtener Tailscale",
waiting: "Esperando a que Tailscale se inicie en este host",
alwaysOn: "Siempre activado, porque este host ya acepta conexiones de Tailscale",
socket: "Desactivado, porque este host escucha en un socket local",
launch: "Lo controla el comando que inicia este host",
update: "Actualiza este host para usar Tailscale",
updateDocs: "Cómo actualizar",
address: "En un teléfono con Tailscale, añade un host con esta dirección",
statusError: "No se pudo comprobar Tailscale",
turnOnError: "No se pudo activar Tailscale",
turnOffError: "No se pudo desactivar Tailscale",
confirmTitle: "¿Desactivar Tailscale?",
confirmMessage:
"Este dispositivo está conectado mediante Tailscale y perderá la conexión con el host.",
confirmAction: "Desactivar",
},
},
pairing: {
hostPassword: {
title: "Contraseña de {{host}}",
@@ -2717,28 +2690,9 @@ export const es: TranslationResources = {
stable: "Stable",
beta: "Beta",
},
autoUpdate: {
label: "Actualizaciones automáticas",
options: {
automatic: "Auto",
notify: "Notificar",
off: "Desactivado",
},
descriptions: {
automatic: "Buscar y descargar actualizaciones en segundo plano",
notify: "Buscar actualizaciones, pero descargar solo cuando lo elijas",
off: "No buscar automáticamente. Solo buscar al hacer clic en Comprobar",
},
},
updates: {
label: "Actualizaciones de aplicaciones",
readyToInstall: "Listo para instalar:{{version}}",
downloadTitle: "Descargar actualización de escritorio",
downloadMessage: "Esto descarga e instala la actualización de Paseo en esta computadora.",
downloadConfirm: "Descargar e instalar",
download: "Descargar",
downloadTo: "Descargar {{version}}",
downloading: "Descargando...",
installTitle: "Instalar actualización de escritorio",
installMessage: "Esto actualizaPaseoen esta computadora.",
installConfirm: "Instalar actualización",
@@ -3012,7 +2966,9 @@ export const es: TranslationResources = {
timeout: "Se acabó el tiempo",
},
pairDevices: {
title: "Emparejar dispositivos",
rowTitle: "Emparejar un dispositivo",
rowHint: "Escanee un códigoQRo copie un enlace para conectar su teléfono a este host",
},
skills: {
...en.settings.host.skills,
+21 -64
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",
},
@@ -1580,8 +1593,6 @@ export const fr: TranslationResources = {
status: {
checking: "Recherche de mises à jour de l’application…",
installing: "Installation de la mise à jour de l’application…",
downloadingVersionProgress: "Téléchargement de {{version}}… {{percent}} %",
downloadingProgress: "Téléchargement de la mise à jour… {{percent}} %",
upToDate: "L’application est à jour.",
upToDateWithLastChecked: "À jour. Dernière vérification à {{time}}.",
pending: "Nous vous préviendrons quand la mise à jour sera prête.",
@@ -1590,16 +1601,6 @@ export const fr: TranslationResources = {
pendingWithVersion: "Mise à jour trouvée : {{version}}. Téléchargement…",
pendingWithVersionAndLastChecked:
"Mise à jour trouvée : {{version}}. Téléchargement… Dernière vérification à {{time}}.",
pendingWithVersionProgress:
"Mise à jour trouvée : {{version}}. Téléchargement… {{percent}} %",
pendingWithVersionProgressAndLastChecked:
"Mise à jour trouvée : {{version}}. Téléchargement… {{percent}} % Dernière vérification à {{time}}.",
downloadAvailableWithVersion: "Mise à jour disponible : {{version}}",
downloadAvailableWithVersionAndLastChecked:
"Mise à jour disponible : {{version}}. Dernière vérification à {{time}}.",
downloadAvailable: "Une mise à jour de l’application est disponible.",
downloadAvailableWithLastChecked:
"Une mise à jour de l’application est disponible. Dernière vérification à {{time}}.",
availableWithVersion: "Mise à jour prête : {{version}}",
availableWithVersionAndLastChecked:
"Mise à jour prête : {{version}}. Dernière vérification à {{time}}.",
@@ -1612,21 +1613,14 @@ export const fr: TranslationResources = {
},
installError: "Impossible d’installer la mise à jour de l’application de bureau.",
callout: {
downloadingTitle: "Téléchargement de la mise à jour",
installingTitle: "Installation de la mise à jour",
failedTitle: "Échec de la mise à jour",
availableTitle: "Mise à jour disponible",
genericError: "Une erreur s’est produite.",
whatsNew: "Nouveautés",
downloadingAction: "Téléchargement…",
installingAction: "Installation…",
downloadAndRestart: "Télécharger",
installAndRestart: "Installer et redémarrer",
downloadingVersionDescription: "Téléchargement de {{version}}… {{percent}} %",
downloadingDescription: "Téléchargement de la mise à jour… {{percent}} %",
installingDescription: "Installation et redémarrage…",
versionAvailable: "La version {{version}} est disponible au téléchargement.",
newVersionAvailable: "Une nouvelle version est disponible au téléchargement.",
versionReady: "La version {{version}} est prête à être installée.",
newVersionReady: "Une nouvelle version est prête à être installée.",
restartWarning:
@@ -1856,6 +1850,12 @@ export const fr: TranslationResources = {
"L'application mobile native complète vous permet de contrôler n'importe quel ordinateur Paseo depuis votre téléphone",
appStore: "App Store",
googlePlay: "Google Play",
connectTitle: "Choisissez comment vous connecter",
connectDocs: "Docs",
openConnectDocs: "Ouvrir la documentation sur la connectivité",
recommended: "Recommandé",
relay: { title: "Relais", hint: "Chiffré de bout en bout, scannez un QR code" },
tailscale: { title: "Tailscale", hint: "Demande un peu de configuration" },
},
},
},
@@ -1934,32 +1934,6 @@ export const fr: TranslationResources = {
hostDisconnected: "L’hôte n’est pas connecté",
},
},
devices: {
title: "Appareils",
waysToConnect: "Moyens de connexion",
docs: "Docs",
docsAccessibility: "Ouvrir la documentation sur la connectivité",
recommended: "Recommandé",
relay: { title: "Relais", hint: "Chiffré de bout en bout, scannez un QR code" },
tailscale: {
hint: "Connexion directe via votre tailnet, saisissez une adresse",
unavailable: "Tailscale ne fonctionne pas sur cet hôte",
install: "Obtenir Tailscale",
waiting: "En attente du démarrage de Tailscale sur cet hôte",
alwaysOn: "Toujours activé, car cet hôte accepte déjà les connexions Tailscale",
socket: "Désactivé, car cet hôte écoute sur un socket local",
launch: "Contrôlé par la commande qui démarre cet hôte",
update: "Mettez cet hôte à jour pour utiliser Tailscale",
updateDocs: "Comment mettre à jour",
address: "Sur un téléphone avec Tailscale, ajoutez un hôte à cette adresse",
statusError: "Impossible de vérifier Tailscale",
turnOnError: "Impossible d’activer Tailscale",
turnOffError: "Impossible de désactiver Tailscale",
confirmTitle: "Désactiver Tailscale ?",
confirmMessage: "Cet appareil est connecté via Tailscale et perdra sa connexion à l’hôte.",
confirmAction: "Désactiver",
},
},
pairing: {
hostPassword: {
title: "Mot de passe pour {{host}}",
@@ -2716,28 +2690,9 @@ export const fr: TranslationResources = {
stable: "Stable",
beta: "Bêta",
},
autoUpdate: {
label: "Mises à jour automatiques",
options: {
automatic: "Auto",
notify: "Notifier",
off: "Désactivé",
},
descriptions: {
automatic: "Vérifier et télécharger les mises à jour en arrière-plan",
notify: "Vérifier les mises à jour, mais ne télécharger que lorsque vous choisissez",
off: "Ne jamais vérifier automatiquement. Vérifier uniquement sur clic sur Vérifier",
},
},
updates: {
label: "Mises à jour de l’application",
readyToInstall: "Prête à installer : {{version}}",
downloadTitle: "Télécharger la mise à jour de l’app de bureau",
downloadMessage: "La mise à jour de Paseo sera téléchargée et installée sur cet ordinateur",
downloadConfirm: "Télécharger et installer",
download: "Télécharger",
downloadTo: "Télécharger {{version}}",
downloading: "Téléchargement…",
installTitle: "Installer la mise à jour de l’app de bureau",
installMessage: "Paseo sera mis à jour sur cet ordinateur",
installConfirm: "Installer la mise à jour",
@@ -3013,7 +2968,9 @@ export const fr: TranslationResources = {
timeout: "Délai dépassé",
},
pairDevices: {
title: "Associer des appareils",
rowTitle: "Associer un appareil",
rowHint: "Scannez un QR code ou copiez un lien pour connecter votre téléphone à cet hôte",
},
skills: {
...en.settings.host.skills,
+21 -63
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: "エージェントを閉じられませんでした",
},
@@ -1565,8 +1578,6 @@ export const ja: TranslationResources = {
status: {
checking: "アプリの更新を確認中...",
installing: "アプリの更新をインストール中...",
downloadingVersionProgress: "{{version}} をダウンロード中... {{percent}}%",
downloadingProgress: "アプリの更新をダウンロード中... {{percent}}%",
upToDate: "アプリは最新です。",
upToDateWithLastChecked: "最新の状態です。最終確認: {{time}}。",
pending: "更新の準備ができたらお知らせします。",
@@ -1574,15 +1585,6 @@ export const ja: TranslationResources = {
pendingWithVersion: "更新が見つかりました: {{version}}。ダウンロード中...",
pendingWithVersionAndLastChecked:
"更新が見つかりました: {{version}}。ダウンロード中... 最終確認: {{time}}。",
pendingWithVersionProgress:
"更新が見つかりました: {{version}}。ダウンロード中... {{percent}}%",
pendingWithVersionProgressAndLastChecked:
"更新が見つかりました: {{version}}。ダウンロード中... {{percent}}% 最終確認: {{time}}。",
downloadAvailableWithVersion: "利用可能な更新: {{version}}",
downloadAvailableWithVersionAndLastChecked:
"利用可能な更新: {{version}}。最終確認: {{time}}。",
downloadAvailable: "アプリの更新が利用可能です。",
downloadAvailableWithLastChecked: "アプリの更新が利用可能です。最終確認: {{time}}。",
availableWithVersion: "更新の準備ができました: {{version}}",
availableWithVersionAndLastChecked:
"更新の準備ができました: {{version}}。最終確認: {{time}}。",
@@ -1594,21 +1596,14 @@ export const ja: TranslationResources = {
},
installError: "デスクトップアプリの更新をインストールできません。",
callout: {
downloadingTitle: "更新をダウンロード中",
installingTitle: "更新をインストール中",
failedTitle: "更新に失敗しました",
availableTitle: "更新が利用可能",
genericError: "問題が発生しました。",
whatsNew: "新機能",
downloadingAction: "ダウンロード中...",
installingAction: "インストール中...",
downloadAndRestart: "ダウンロード",
installAndRestart: "インストールして再起動",
downloadingVersionDescription: "{{version}} をダウンロード中... {{percent}}%",
downloadingDescription: "更新をダウンロード中... {{percent}}%",
installingDescription: "インストールして再起動中...",
versionAvailable: "{{version}} をダウンロードできます。",
newVersionAvailable: "新しいバージョンをダウンロードできます。",
versionReady: "{{version}}のインストール準備ができました。",
newVersionReady: "新しいバージョンのインストール準備ができました。",
restartWarning:
@@ -1829,6 +1824,12 @@ export const ja: TranslationResources = {
"フル機能のネイティブモバイルアプリで、スマートフォンからどの Paseo コンピューターでも操作できます",
appStore: "App Store",
googlePlay: "Google Play",
connectTitle: "接続方法を選択",
connectDocs: "ドキュメント",
openConnectDocs: "接続のドキュメントを開く",
recommended: "おすすめ",
relay: { title: "リレー", hint: "エンドツーエンド暗号化、QR コードをスキャン" },
tailscale: { title: "Tailscale", hint: "少し設定が必要です" },
},
},
},
@@ -1907,32 +1908,6 @@ export const ja: TranslationResources = {
hostDisconnected: "ホストが接続されていません",
},
},
devices: {
title: "デバイス",
waysToConnect: "接続方法",
docs: "ドキュメント",
docsAccessibility: "接続のドキュメントを開く",
recommended: "おすすめ",
relay: { title: "リレー", hint: "エンドツーエンド暗号化、QR コードをスキャン" },
tailscale: {
hint: "tailnet 経由で直接接続、アドレスを入力",
unavailable: "このホストで Tailscale が動作していません",
install: "Tailscale を入手",
waiting: "このホストで Tailscale が起動するのを待っています",
alwaysOn: "常にオン。このホストはすでに Tailscale からの接続を受け付けています",
socket: "オフ。このホストはローカルソケットで待ち受けています",
launch: "このホストを起動するコマンドで制御されています",
update: "Tailscale を使うにはこのホストを更新してください",
updateDocs: "更新方法",
address: "Tailscale を使うスマートフォンで、このアドレスのホストを追加してください",
statusError: "Tailscale を確認できませんでした",
turnOnError: "Tailscale をオンにできませんでした",
turnOffError: "Tailscale をオフにできませんでした",
confirmTitle: "Tailscale をオフにしますか?",
confirmMessage: "このデバイスは Tailscale 経由で接続しているため、ホストとの接続が切れます。",
confirmAction: "オフにする",
},
},
pairing: {
hostPassword: {
title: "{{host}} のパスワード",
@@ -2682,28 +2657,9 @@ export const ja: TranslationResources = {
stable: "安定版",
beta: "ベータ",
},
autoUpdate: {
label: "自動更新",
options: {
automatic: "自動",
notify: "通知のみ",
off: "オフ",
},
descriptions: {
automatic: "バックグラウンドで更新を確認してダウンロードします",
notify: "更新を確認しますが、選択したときだけダウンロードします",
off: "自動で更新を確認しません。「確認」をクリックしたときだけ確認します",
},
},
updates: {
label: "アプリの更新",
readyToInstall: "インストール準備完了: {{version}}",
downloadTitle: "デスクトップの更新をダウンロード",
downloadMessage: "このコンピューターにPaseoの更新をダウンロードしてインストールします",
downloadConfirm: "ダウンロードしてインストール",
download: "ダウンロード",
downloadTo: "{{version}}をダウンロード",
downloading: "ダウンロード中...",
installTitle: "デスクトップの更新をインストール",
installMessage: "このコンピューターのPaseoを更新します",
installConfirm: "更新をインストール",
@@ -2978,7 +2934,9 @@ export const ja: TranslationResources = {
timeout: "タイムアウト",
},
pairDevices: {
title: "デバイスをペアリング",
rowTitle: "デバイスをペアリング",
rowHint: "QRコードをスキャンするかリンクをコピーしてスマートフォンをこのホストに接続",
},
skills: {
...en.settings.host.skills,
+21 -63
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: "에이전트를 닫지 못했습니다",
},
@@ -1556,8 +1569,6 @@ export const ko: TranslationResources = {
status: {
checking: "앱 업데이트 확인 중...",
installing: "앱 업데이트 설치 중...",
downloadingVersionProgress: "{{version}} 다운로드 중... {{percent}}%",
downloadingProgress: "앱 업데이트 다운로드 중... {{percent}}%",
upToDate: "앱이 최신 상태입니다.",
upToDateWithLastChecked: "최신 상태입니다. 마지막 확인: {{time}}.",
pending: "업데이트가 준비되면 알려드리겠습니다.",
@@ -1566,15 +1577,6 @@ export const ko: TranslationResources = {
pendingWithVersion: "업데이트 발견: {{version}}. 다운로드 중...",
pendingWithVersionAndLastChecked:
"업데이트 발견: {{version}}. 다운로드 중... {{time}}에서 마지막으로 확인했습니다.",
pendingWithVersionProgress: "업데이트 발견: {{version}}. 다운로드 중... {{percent}}%",
pendingWithVersionProgressAndLastChecked:
"업데이트 발견: {{version}}. 다운로드 중... {{percent}}% {{time}}에서 마지막으로 확인했습니다.",
downloadAvailableWithVersion: "사용 가능한 업데이트: {{version}}",
downloadAvailableWithVersionAndLastChecked:
"사용 가능한 업데이트: {{version}}. {{time}}에서 마지막으로 확인했습니다.",
downloadAvailable: "사용 가능한 앱 업데이트가 있습니다.",
downloadAvailableWithLastChecked:
"사용 가능한 앱 업데이트가 있습니다. {{time}}에서 마지막으로 확인했습니다.",
availableWithVersion: "업데이트 준비됨: {{version}}",
availableWithVersionAndLastChecked:
"업데이트 준비됨: {{version}}. {{time}}에서 마지막으로 확인했습니다.",
@@ -1587,21 +1589,14 @@ export const ko: TranslationResources = {
},
installError: "데스크톱 앱 업데이트를 설치할 수 없습니다.",
callout: {
downloadingTitle: "업데이트 다운로드 중",
installingTitle: "업데이트 설치 중",
failedTitle: "업데이트 실패",
availableTitle: "업데이트 사용 가능",
genericError: "문제가 발생했습니다.",
whatsNew: "새로운 기능",
downloadingAction: "다운로드 중...",
installingAction: "설치 중...",
downloadAndRestart: "다운로드",
installAndRestart: "설치 후 재시작",
downloadingVersionDescription: "{{version}} 다운로드 중... {{percent}}%",
downloadingDescription: "업데이트 다운로드 중... {{percent}}%",
installingDescription: "설치 후 재시작 중...",
versionAvailable: "{{version}} 버전을 다운로드할 수 있습니다.",
newVersionAvailable: "새 버전을 다운로드할 수 있습니다.",
versionReady: "{{version}} 설치가 준비되었습니다.",
newVersionReady: "새 버전 설치가 준비되었습니다.",
restartWarning: "앱을 업그레이드하면 실행 중인 에이전트가 중지되고 터미널 세션이 닫힙니다.",
@@ -1820,6 +1815,12 @@ export const ko: TranslationResources = {
"모든 기능을 갖춘 네이티브 모바일 앱으로 휴대폰에서 어떤 Paseo 컴퓨터든 제어할 수 있습니다",
appStore: "App Store",
googlePlay: "Google Play",
connectTitle: "연결 방법 선택",
connectDocs: "문서",
openConnectDocs: "연결 문서 열기",
recommended: "권장",
relay: { title: "릴레이", hint: "엔드투엔드 암호화, QR 코드를 스캔하세요" },
tailscale: { title: "Tailscale", hint: "약간의 설정이 필요합니다" },
},
},
},
@@ -1898,32 +1899,6 @@ export const ko: TranslationResources = {
hostDisconnected: "호스트가 연결되어 있지 않습니다",
},
},
devices: {
title: "기기",
waysToConnect: "연결 방법",
docs: "문서",
docsAccessibility: "연결 문서 열기",
recommended: "권장",
relay: { title: "릴레이", hint: "엔드투엔드 암호화, QR 코드를 스캔하세요" },
tailscale: {
hint: "tailnet으로 직접 연결, 주소 입력",
unavailable: "이 호스트에서 Tailscale이 실행 중이 아닙니다",
install: "Tailscale 받기",
waiting: "이 호스트에서 Tailscale이 시작되기를 기다리는 중",
alwaysOn: "항상 켜짐. 이 호스트가 이미 Tailscale 연결을 받고 있습니다",
socket: "꺼짐. 이 호스트가 로컬 소켓에서 수신 대기 중입니다",
launch: "이 호스트를 시작하는 명령이 제어합니다",
update: "Tailscale을 사용하려면 이 호스트를 업데이트하세요",
updateDocs: "업데이트 방법",
address: "Tailscale을 사용하는 휴대전화에서 이 주소로 호스트를 추가하세요",
statusError: "Tailscale을 확인하지 못했습니다",
turnOnError: "Tailscale을 켜지 못했습니다",
turnOffError: "Tailscale을 끄지 못했습니다",
confirmTitle: "Tailscale을 끌까요?",
confirmMessage: "이 기기는 Tailscale로 연결되어 있어 호스트와의 연결이 끊깁니다.",
confirmAction: "끄기",
},
},
pairing: {
hostPassword: {
title: "{{host}}의 비밀번호",
@@ -2672,28 +2647,9 @@ export const ko: TranslationResources = {
stable: "안정",
beta: "베타",
},
autoUpdate: {
label: "자동 업데이트",
options: {
automatic: "자동",
notify: "알림만",
off: "끄기",
},
descriptions: {
automatic: "백그라운드에서 업데이트를 확인하고 다운로드합니다",
notify: "업데이트를 확인하지만 선택할 때만 다운로드합니다",
off: "자동으로 확인하지 않습니다. 확인 버튼을 누를 때만 확인합니다",
},
},
updates: {
label: "앱 업데이트",
readyToInstall: "설치 준비됨: {{version}}",
downloadTitle: "데스크톱 업데이트 다운로드",
downloadMessage: "이 컴퓨터에 Paseo 업데이트를 다운로드하고 설치합니다",
downloadConfirm: "다운로드 및 설치",
download: "다운로드",
downloadTo: "{{version}} 다운로드",
downloading: "다운로드 중...",
installTitle: "데스크톱 업데이트 설치",
installMessage: "이 컴퓨터의 Paseo를 업데이트합니다",
installConfirm: "업데이트 설치",
@@ -2964,7 +2920,9 @@ export const ko: TranslationResources = {
timeout: "시간 초과",
},
pairDevices: {
title: "기기 페어링",
rowTitle: "기기 페어링",
rowHint: "QR 코드를 스캔하거나 링크를 복사하여 휴대폰을 이 호스트에 연결하세요",
},
skills: {
...en.settings.host.skills,
+21 -64
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",
},
@@ -1577,8 +1590,6 @@ export const ptBR: TranslationResources = {
status: {
checking: "Verificando atualizações do app...",
installing: "Instalando atualização do app...",
downloadingVersionProgress: "Baixando {{version}}... {{percent}}%",
downloadingProgress: "Baixando atualização do app... {{percent}}%",
upToDate: "O app está atualizado.",
upToDateWithLastChecked: "Atualizado. Última verificação às {{time}}.",
pending: "Avisaremos quando a atualização estiver pronta.",
@@ -1587,15 +1598,6 @@ export const ptBR: TranslationResources = {
pendingWithVersion: "Atualização encontrada: {{version}}. Baixando...",
pendingWithVersionAndLastChecked:
"Atualização encontrada: {{version}}. Baixando... Última verificação às {{time}}.",
pendingWithVersionProgress: "Atualização encontrada: {{version}}. Baixando... {{percent}}%",
pendingWithVersionProgressAndLastChecked:
"Atualização encontrada: {{version}}. Baixando... {{percent}}% Última verificação às {{time}}.",
downloadAvailableWithVersion: "Atualização disponível: {{version}}",
downloadAvailableWithVersionAndLastChecked:
"Atualização disponível: {{version}}. Última verificação às {{time}}.",
downloadAvailable: "Há uma atualização do app disponível.",
downloadAvailableWithLastChecked:
"Há uma atualização do app disponível. Última verificação às {{time}}.",
availableWithVersion: "Atualização pronta: {{version}}",
availableWithVersionAndLastChecked:
"Atualização pronta: {{version}}. Última verificação às {{time}}.",
@@ -1608,21 +1610,14 @@ export const ptBR: TranslationResources = {
},
installError: "Não foi possível instalar a atualização do app desktop.",
callout: {
downloadingTitle: "Baixando atualização",
installingTitle: "Instalando atualização",
failedTitle: "Falha na atualização",
availableTitle: "Atualização disponível",
genericError: "Algo deu errado.",
whatsNew: "Novidades",
downloadingAction: "Baixando...",
installingAction: "Instalando...",
downloadAndRestart: "Baixar",
installAndRestart: "Instalar e reiniciar",
downloadingVersionDescription: "Baixando {{version}}... {{percent}}%",
downloadingDescription: "Baixando atualização... {{percent}}%",
installingDescription: "Instalando e reiniciando...",
versionAvailable: "{{version}} está disponível para download.",
newVersionAvailable: "Uma nova versão está disponível para download.",
versionReady: "{{version}} está pronta para instalar.",
newVersionReady: "Uma nova versão está pronta para instalar.",
restartWarning:
@@ -1842,6 +1837,12 @@ export const ptBR: TranslationResources = {
"O app móvel nativo completo permite controlar qualquer computador com Paseo pelo seu celular",
appStore: "App Store",
googlePlay: "Google Play",
connectTitle: "Escolha como se conectar",
connectDocs: "Docs",
openConnectDocs: "Abrir documentação de conectividade",
recommended: "Recomendado",
relay: { title: "Relay", hint: "Criptografia de ponta a ponta, escaneie um código QR" },
tailscale: { title: "Tailscale", hint: "Requer alguma configuração" },
},
},
},
@@ -1920,33 +1921,6 @@ export const ptBR: TranslationResources = {
hostDisconnected: "Host não está conectado",
},
},
devices: {
title: "Dispositivos",
waysToConnect: "Formas de conexão",
docs: "Docs",
docsAccessibility: "Abrir documentação de conectividade",
recommended: "Recomendado",
relay: { title: "Relay", hint: "Criptografia de ponta a ponta, escaneie um código QR" },
tailscale: {
hint: "Conexão direta pela sua tailnet, digite um endereço",
unavailable: "O Tailscale não está em execução neste host",
install: "Baixar o Tailscale",
waiting: "Aguardando o Tailscale iniciar neste host",
alwaysOn: "Sempre ativado, porque este host já aceita conexões do Tailscale",
socket: "Desativado, porque este host escuta em um socket local",
launch: "Controlado pelo comando que inicia este host",
update: "Atualize este host para usar o Tailscale",
updateDocs: "Como atualizar",
address: "Em um celular com Tailscale, adicione um host com este endereço",
statusError: "Não foi possível verificar o Tailscale",
turnOnError: "Não foi possível ativar o Tailscale",
turnOffError: "Não foi possível desativar o Tailscale",
confirmTitle: "Desativar o Tailscale?",
confirmMessage:
"Este dispositivo está conectado pelo Tailscale e perderá a conexão com o host.",
confirmAction: "Desativar",
},
},
pairing: {
hostPassword: {
title: "Senha de {{host}}",
@@ -2698,28 +2672,9 @@ export const ptBR: TranslationResources = {
stable: "Stable",
beta: "Beta",
},
autoUpdate: {
label: "Atualizações automáticas",
options: {
automatic: "Auto",
notify: "Notificar",
off: "Desativado",
},
descriptions: {
automatic: "Verificar e baixar atualizações em segundo plano",
notify: "Verificar atualizações, mas baixar apenas quando você escolher",
off: "Nunca verificar automaticamente. Verificar apenas ao clicar em Verificar",
},
},
updates: {
label: "Atualizações do app",
readyToInstall: "Pronta para instalar: {{version}}",
downloadTitle: "Baixar atualização desktop",
downloadMessage: "Isso baixa e instala a atualização do Paseo neste computador",
downloadConfirm: "Baixar e instalar",
download: "Baixar",
downloadTo: "Baixar {{version}}",
downloading: "Baixando...",
installTitle: "Instalar atualização desktop",
installMessage: "Isso atualiza o Paseo neste computador",
installConfirm: "Instalar atualização",
@@ -2992,7 +2947,9 @@ export const ptBR: TranslationResources = {
timeout: "Timeout",
},
pairDevices: {
title: "Parear dispositivos",
rowTitle: "Parear um dispositivo",
rowHint: "Escaneie um QR code ou copie um link para conectar seu celular a este host",
},
skills: {
...en.settings.host.skills,
+22 -63
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: "Не удалось закрыть агента",
},
@@ -1571,8 +1584,6 @@ export const ru: TranslationResources = {
status: {
checking: "Проверка обновлений приложения...",
installing: "Установка обновления приложения...",
downloadingVersionProgress: "Загрузка {{version}}... {{percent}}%",
downloadingProgress: "Загрузка обновления приложения... {{percent}}%",
upToDate: "Установлена последняя версия приложения.",
upToDateWithLastChecked:
"Установлена последняя версия приложения. Последняя проверка: {{time}}.",
@@ -1582,15 +1593,6 @@ export const ru: TranslationResources = {
pendingWithVersion: "Найдено обновление: {{version}}. Загрузка...",
pendingWithVersionAndLastChecked:
"Найдено обновление: {{version}}. Загрузка... Последняя проверка в {{time}}.",
pendingWithVersionProgress: "Найдено обновление: {{version}}. Загрузка... {{percent}}%",
pendingWithVersionProgressAndLastChecked:
"Найдено обновление: {{version}}. Загрузка... {{percent}}% Последняя проверка в {{time}}.",
downloadAvailableWithVersion: "Доступно обновление: {{version}}",
downloadAvailableWithVersionAndLastChecked:
"Доступно обновление: {{version}}. Последняя проверка: {{time}}.",
downloadAvailable: "Доступно обновление приложения.",
downloadAvailableWithLastChecked:
"Доступно обновление приложения. Последняя проверка: {{time}}.",
availableWithVersion: "Обновление готово: {{version}}",
availableWithVersionAndLastChecked:
"Обновление готово: {{version}}. Последняя проверка: {{time}}.",
@@ -1603,21 +1605,14 @@ export const ru: TranslationResources = {
},
installError: "Не удалось установить обновление настольного приложения.",
callout: {
downloadingTitle: "Загрузка обновления",
installingTitle: "Установка обновления",
failedTitle: "Обновление не выполнено",
availableTitle: "Доступно обновление",
genericError: "Что-то пошло не так.",
whatsNew: "Что нового",
downloadingAction: "Загрузка...",
installingAction: "Установка...",
downloadAndRestart: "Скачать",
installAndRestart: "Установить и перезапустить",
downloadingVersionDescription: "Загрузка {{version}}... {{percent}}%",
downloadingDescription: "Загрузка обновления... {{percent}}%",
installingDescription: "Установка и перезапуск...",
versionAvailable: "Версия {{version}} доступна для загрузки.",
newVersionAvailable: "Новая версия доступна для загрузки.",
versionReady: "Версия {{version}} готова к установке.",
newVersionReady: "Новая версия готова к установке.",
restartWarning:
@@ -1842,6 +1837,12 @@ export const ru: TranslationResources = {
"Полнофункциональное нативное мобильное приложение позволяет управлять любым компьютером с Paseo с телефона",
appStore: "App Store",
googlePlay: "Google Play",
connectTitle: "Выберите способ подключения",
connectDocs: "Документация",
openConnectDocs: "Открыть документацию по подключению",
recommended: "Рекомендуется",
relay: { title: "Ретранслятор", hint: "Сквозное шифрование, отсканируйте QR-код" },
tailscale: { title: "Tailscale", hint: "Требует небольшой настройки" },
},
},
},
@@ -1920,32 +1921,6 @@ export const ru: TranslationResources = {
hostDisconnected: "Хост не подключён",
},
},
devices: {
title: "Устройства",
waysToConnect: "Способы подключения",
docs: "Документация",
docsAccessibility: "Открыть документацию по подключению",
recommended: "Рекомендуется",
relay: { title: "Ретранслятор", hint: "Сквозное шифрование, отсканируйте QR-код" },
tailscale: {
hint: "Прямое подключение через ваш tailnet, по адресу",
unavailable: "Tailscale не запущен на этом хосте",
install: "Скачать Tailscale",
waiting: "Ожидаем запуска Tailscale на этом хосте",
alwaysOn: "Всегда включено, так как хост уже принимает подключения Tailscale",
socket: "Выключено, так как хост слушает локальный сокет",
launch: "Управляется командой, которая запускает этот хост",
update: "Обновите этот хост, чтобы использовать Tailscale",
updateDocs: "Как обновить",
address: "На телефоне с Tailscale добавьте хост с этим адресом",
statusError: "Не удалось проверить Tailscale",
turnOnError: "Не удалось включить Tailscale",
turnOffError: "Не удалось выключить Tailscale",
confirmTitle: "Выключить Tailscale?",
confirmMessage: "Это устройство подключено через Tailscale и потеряет соединение с хостом.",
confirmAction: "Выключить",
},
},
pairing: {
hostPassword: {
title: "Пароль для {{host}}",
@@ -2704,28 +2679,9 @@ export const ru: TranslationResources = {
stable: "Стабильный",
beta: "Бета",
},
autoUpdate: {
label: "Автообновления",
options: {
automatic: "Авто",
notify: "Уведомлять",
off: "Выкл.",
},
descriptions: {
automatic: "Проверять и загружать обновления в фоновом режиме",
notify: "Проверять обновления, но загружать только по вашему выбору",
off: "Не проверять автоматически. Проверять только по нажатию кнопки Проверить",
},
},
updates: {
label: "Обновления приложения",
readyToInstall: "Версия {{version}} готова к установке",
downloadTitle: "Загрузить обновление настольного приложения",
downloadMessage: "Это загрузит и установит обновление Paseo на этом компьютере.",
downloadConfirm: "Загрузить и установить",
download: "Загрузить",
downloadTo: "Загрузить {{version}}",
downloading: "Загрузка...",
installTitle: "Установить обновление настольного приложения",
installMessage: "Это обновит Paseo на этом компьютере.",
installConfirm: "Установить обновление",
@@ -2999,7 +2955,10 @@ export const ru: TranslationResources = {
timeout: "Время ожидания истекло",
},
pairDevices: {
title: "Подключение устройств",
rowTitle: "Подключить устройство",
rowHint:
"Отсканируйте QR-код или скопируйте ссылку, чтобы подключить телефон к этому хосту.",
},
skills: {
sectionTitle: "Навыки оркестрации",
+21 -62
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 失败",
},
@@ -1537,8 +1550,6 @@ export const zhCN: TranslationResources = {
status: {
checking: "正在检查 app 更新...",
installing: "正在安装 app 更新...",
downloadingVersionProgress: "正在下载 {{version}}... {{percent}}%",
downloadingProgress: "正在下载 app 更新... {{percent}}%",
upToDate: "App 已是最新版本。",
upToDateWithLastChecked: "已是最新版本。上次检查时间:{{time}}。",
pending: "更新准备好后会通知你。",
@@ -1546,14 +1557,6 @@ export const zhCN: TranslationResources = {
pendingWithVersion: "发现更新:{{version}}。正在下载...",
pendingWithVersionAndLastChecked:
"发现更新:{{version}}。正在下载... 上次检查时间:{{time}}。",
pendingWithVersionProgress: "发现更新:{{version}}。正在下载... {{percent}}%",
pendingWithVersionProgressAndLastChecked:
"发现更新:{{version}}。正在下载... {{percent}}% 上次检查时间:{{time}}。",
downloadAvailableWithVersion: "有可用更新:{{version}}",
downloadAvailableWithVersionAndLastChecked:
"有可用更新:{{version}}。上次检查时间:{{time}}。",
downloadAvailable: "有 app 更新可用。",
downloadAvailableWithLastChecked: "有 app 更新可用。上次检查时间:{{time}}。",
availableWithVersion: "更新已就绪:{{version}}",
availableWithVersionAndLastChecked: "更新已就绪:{{version}}。上次检查时间:{{time}}。",
available: "有 app 更新可安装。",
@@ -1564,21 +1567,14 @@ export const zhCN: TranslationResources = {
},
installError: "无法安装 desktop app 更新。",
callout: {
downloadingTitle: "正在下载更新",
installingTitle: "正在安装更新",
failedTitle: "更新失败",
availableTitle: "有可用更新",
genericError: "出了点问题。",
whatsNew: "更新内容",
downloadingAction: "正在下载...",
installingAction: "正在安装...",
downloadAndRestart: "下载",
installAndRestart: "安装并重启",
downloadingVersionDescription: "正在下载 {{version}}... {{percent}}%",
downloadingDescription: "正在下载更新... {{percent}}%",
installingDescription: "正在安装并重启...",
versionAvailable: "{{version}} 可供下载。",
newVersionAvailable: "有新版本可供下载。",
versionReady: "{{version}} 已准备好安装。",
newVersionReady: "新版本已准备好安装。",
restartWarning: "升级 app 会停止正在运行的 agents,并关闭 terminal 会话。",
@@ -1790,6 +1786,12 @@ export const zhCN: TranslationResources = {
description: "功能完整的原生移动应用让你可以在手机上控制任意一台 Paseo 电脑",
appStore: "App Store",
googlePlay: "Google Play",
connectTitle: "选择连接方式",
connectDocs: "文档",
openConnectDocs: "打开连接文档",
recommended: "推荐",
relay: { title: "中继", hint: "端到端加密,扫描二维码" },
tailscale: { title: "Tailscale", hint: "需要一些设置" },
},
},
},
@@ -1868,32 +1870,6 @@ export const zhCN: TranslationResources = {
hostDisconnected: "Host 未连接",
},
},
devices: {
title: "设备",
waysToConnect: "连接方式",
docs: "文档",
docsAccessibility: "打开连接文档",
recommended: "推荐",
relay: { title: "中继", hint: "端到端加密,扫描二维码" },
tailscale: {
hint: "通过你的 tailnet 直连,输入地址即可",
unavailable: "此主机未运行 Tailscale",
install: "获取 Tailscale",
waiting: "正在等待此主机上的 Tailscale 启动",
alwaysOn: "始终开启,因为此主机已接受 Tailscale 连接",
socket: "已关闭,因为此主机监听的是本地套接字",
launch: "由启动此主机的命令控制",
update: "更新此主机以使用 Tailscale",
updateDocs: "如何更新",
address: "在已连接 Tailscale 的手机上,用此地址添加主机",
statusError: "无法检查 Tailscale",
turnOnError: "无法开启 Tailscale",
turnOffError: "无法关闭 Tailscale",
confirmTitle: "关闭 Tailscale?",
confirmMessage: "此设备通过 Tailscale 连接,关闭后将与主机断开连接。",
confirmAction: "关闭",
},
},
pairing: {
hostPassword: {
title: "{{host}} 的密码",
@@ -2630,28 +2606,9 @@ export const zhCN: TranslationResources = {
stable: "Stable",
beta: "Beta",
},
autoUpdate: {
label: "自动更新",
options: {
automatic: "自动",
notify: "仅通知",
off: "关闭",
},
descriptions: {
automatic: "在后台检查并下载更新",
notify: "检查更新,但仅在你选择时才下载",
off: "从不自动检查,仅在点击检查时检查更新",
},
},
updates: {
label: "应用更新",
readyToInstall: "可安装:{{version}}",
downloadTitle: "下载桌面版更新",
downloadMessage: "这会在此电脑上下载并安装 Paseo 更新",
downloadConfirm: "下载并安装",
download: "下载",
downloadTo: "下载 {{version}}",
downloading: "正在下载...",
installTitle: "安装桌面版更新",
installMessage: "这会更新此电脑上的 Paseo",
installConfirm: "安装更新",
@@ -2919,7 +2876,9 @@ export const zhCN: TranslationResources = {
timeout: "超时",
},
pairDevices: {
title: "配对设备",
rowTitle: "配对设备",
rowHint: "扫描二维码或复制链接,将手机连接到这个 Host",
},
skills: {
...en.settings.host.skills,
@@ -224,8 +224,9 @@ export function useOverlayRegistration({
activeRef.current && typeof window !== "undefined" && typeof document !== "undefined";
if (!shouldRegister) {
const shouldRestoreFocus = !activeRef.current;
const removeEntry = removeEntryRef.current ?? detachedRemoveEntryRef.current;
if (registeredRef.current || shouldRestoreFocus) {
removeEntryRef.current?.({ restoreFocus: shouldRestoreFocus });
removeEntry?.({ restoreFocus: shouldRestoreFocus });
}
registeredRef.current = false;
if (shouldRestoreFocus) {
@@ -268,8 +269,14 @@ export function useOverlayRegistration({
[syncRegistration],
);
// Run `active` transitions in layout effects (after React's `resetAfterCommit`), so closing a
// fading overlay restores focus after React's commit-time selection restoration instead of
// having `resetAfterCommit` pull focus back into the still-mounted closing dialog.
useLayoutEffect(() => {
syncRegistration();
}, [active, syncRegistration]);
useLayoutEffect(() => {
return () => {
const removeEntry = removeEntryRef.current ?? detachedRemoveEntryRef.current;
removeEntry?.();
@@ -277,7 +284,7 @@ export function useOverlayRegistration({
detachedRemoveEntryRef.current = null;
registeredRef.current = false;
};
}, [active, syncRegistration]);
}, [syncRegistration]);
return setScope;
}
@@ -74,6 +74,74 @@ describe("useOverlayRegistration in the browser", () => {
expect(openerFocusCalls).toBe(1);
});
it("restores focus to the non-first opener button when a fading upper overlay closes over a lower overlay", async () => {
function StackedHarness({ upperActive }: { upperActive: boolean }) {
const setLowerScope = useOverlayRegistration({
keys: ["Escape"],
active: true,
layer: 10,
onKeyDown: () => false,
});
const setUpperScope = useOverlayRegistration({
keys: ["Escape"],
active: upperActive,
layer: 30,
onKeyDown: () => false,
});
return (
<>
<div
data-testid="lower-scope"
ref={setLowerScope as RefCallback<HTMLDivElement>}
tabIndex={-1}
>
<button data-testid="lower-first" type="button">
Back
</button>
<button data-testid="lower-second" type="button">
Settings
</button>
</div>
<div
data-testid="upper-scope"
ref={setUpperScope as RefCallback<HTMLDivElement>}
tabIndex={-1}
>
<button data-testid="upper-close" type="button">
Close
</button>
</div>
</>
);
}
flushSync(() => {
root.render(<StackedHarness upperActive={false} />);
});
await nextFrame();
const lowerSecond = document.querySelector<HTMLButtonElement>('[data-testid="lower-second"]');
expect(lowerSecond).toBeTruthy();
lowerSecond?.focus();
expect(document.activeElement).toBe(lowerSecond);
flushSync(() => {
root.render(<StackedHarness upperActive />);
});
await nextFrame();
const upperClose = document.querySelector<HTMLButtonElement>('[data-testid="upper-close"]');
expect(document.activeElement).toBe(upperClose);
// Keep upper-scope mounted while closing (mirrors AdaptiveModalSheet's web fade-out).
flushSync(() => {
root.render(<StackedHarness upperActive={false} />);
});
await nextFrame();
expect(document.activeElement).toBe(lowerSecond);
});
});
describe("hasOpenDomPopover", () => {
@@ -1,11 +1,17 @@
import { useCallback } from "react";
import { useCallback, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { View } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { AppleIcon } from "@/components/icons/apple-icon";
import { GooglePlayIcon } from "@/components/icons/google-play-icon";
import { SettingsCard, SettingsDetailRow, SettingsSection } from "@/components/settings";
import { Button } from "@/components/ui/button";
import { WaysToConnect } from "@/devices";
import { StatusBadge } from "@/components/ui/status-badge";
import { PairDeviceModal } from "@/desktop/components/pair-device-modal";
import {
CONNECTIVITY_DOCS_URL,
TAILSCALE_DOCS_URL,
} from "@/desktop/components/pair-device-section";
import { ICON_SIZE } from "@/styles/theme";
import { openExternalUrl } from "@/utils/open-external-url";
@@ -20,11 +26,33 @@ function openUrl(url: string) {
void openExternalUrl(url).catch(console.error);
}
/** Get the app, then connect it the same ways the host's Devices settings offer. */
/** Get the app, then connect it: the relay pairs in a modal, Tailscale is a docs page away. */
export function PhoneStep({ serverId }: { serverId: string }) {
const { t } = useTranslation();
const [isPairing, setIsPairing] = useState(false);
const openAppStore = useCallback(() => openUrl(APP_STORE_URL), []);
const openPlayStore = useCallback(() => openUrl(PLAY_STORE_URL), []);
const openTailscaleDocs = useCallback(() => openUrl(TAILSCALE_DOCS_URL), []);
const openPairing = useCallback(() => setIsPairing(true), []);
const closePairing = useCallback(() => setIsPairing(false), []);
const recommendedBadge = useMemo(
() => (
<StatusBadge
size="xs"
variant="success"
label={t("onboarding.setup.steps.phone.recommended")}
/>
),
[t],
);
const docsLink = useMemo(
() => ({
href: CONNECTIVITY_DOCS_URL,
label: t("onboarding.setup.steps.phone.connectDocs"),
accessibilityLabel: t("onboarding.setup.steps.phone.openConnectDocs"),
}),
[t],
);
return (
<View style={styles.container}>
@@ -36,7 +64,31 @@ export function PhoneStep({ serverId }: { serverId: string }) {
{t("onboarding.setup.steps.phone.googlePlay")}
</Button>
</View>
<WaysToConnect serverId={serverId} />
<SettingsSection title={t("onboarding.setup.steps.phone.connectTitle")} link={docsLink}>
<SettingsCard>
<SettingsDetailRow
label={t("onboarding.setup.steps.phone.relay.title")}
labelAccessory={recommendedBadge}
hint={t("onboarding.setup.steps.phone.relay.hint")}
onPress={openPairing}
testID="onboarding-phone-relay"
/>
<SettingsDetailRow
label={t("onboarding.setup.steps.phone.tailscale.title")}
hint={t("onboarding.setup.steps.phone.tailscale.hint")}
summary={t("onboarding.setup.steps.phone.connectDocs")}
onPress={openTailscaleDocs}
external
testID="onboarding-phone-tailscale"
/>
</SettingsCard>
</SettingsSection>
<PairDeviceModal
serverId={serverId}
visible={isPairing}
onClose={closePairing}
testID="onboarding-pair-device-card"
/>
</View>
);
}
@@ -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;
}
@@ -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: [],
@@ -201,9 +201,15 @@ export class AgentStoreProjection {
useDraftStore.getState().clearDraftInput({
draftKey: buildDraftStoreKey({ serverId: this.serverId, agentId }),
});
// Leaving the active list does not release the transcript: an archived chat open in
// History stays readable. The viewed timeline owner releases it once nobody shows it.
useSessionStore.getState().releaseAgentTimeline(this.serverId, agentId);
// Only entity deletion destroys the transcript. A filtered active-list
// response can arrive after a fresh history response for an archived agent.
const store = useSessionStore.getState();
const removeKey = withoutAgent(agentId);
store.setAgentTimelineCursor(this.serverId, removeKey);
store.setAgentTimelineUnsettledTurn(this.serverId, agentId, null);
store.setAgentAuthoritativeHistoryApplied(this.serverId, agentId, false);
store.setAgentStreamTail(this.serverId, removeKey);
store.clearAgentStreamHead(this.serverId, agentId);
}
archive(agentId: string, archivedAt: string): Agent | null {
+144 -24
View File
@@ -83,8 +83,18 @@ import {
} from "@/desktop/browser/automation/handler";
import { schedulesQueryBaseKey } from "@/schedules/aggregated-schedules";
import { dispatchComposerAgentMessage, sendQueuedComposerMessageNow } from "@/composer/actions";
import {
applyFailedStartupSettings,
beginStagedProviderSwitch,
discardFailedStartupSettings,
endStagedProviderSwitch,
getFailedStartupSettings,
getStagedProviderSwitch,
settleCommittedProviderSwitch,
} from "@/composer/provider-switch";
import { createMessageSubmissionWriter } from "@/composer/submission/writer";
import { resolveComposerAttachmentSubmitFormat } from "@/composer/attachments/submit";
import { normalizeAgentSnapshot } from "@/utils/agent-snapshots";
import { encodeImages } from "@/utils/encode-images";
import { DirectorySync, type RefreshAgentDirectoryResult } from "@/runtime/directory-sync";
import { ReplicaCache } from "@/runtime/replica-cache";
@@ -255,6 +265,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;
@@ -1917,6 +1928,7 @@ export class HostRuntimeStore {
private lastOnlineEpochByServer = new Map<string, number>();
private connectionStatusStartedAtByServer = new Map<string, number>();
private queuedAgentDrainInFlight = new Set<string>();
private queuedAgentDrainPending = new Set<string>();
private directorySyncByServer = new Map<string, DirectorySync>();
private nextCancellationRequestId = 0;
private timelineReplicaByServer = new Map<string, TimelineReplica>();
@@ -2881,9 +2893,58 @@ export class HostRuntimeStore {
}
}
private resumeIdleQueueIfReady(serverId: string, agentId: string): void {
const latestSession = useSessionStore.getState().sessions[serverId];
const latestAgent = latestSession?.agents.get(agentId);
const remainingQueue = latestSession?.queuedMessages.get(agentId);
if (
latestAgent?.status === "idle" &&
remainingQueue &&
remainingQueue.length > 0 &&
latestSession?.initializingAgents.get(agentId) !== true
) {
this.drainQueuedAgentMessage(serverId, agentId);
}
}
/**
* Explicitly retries or discards startup settings that failed after a provider switch,
* then resumes automatic draining if the chat is idle with queued messages.
*/
async recoverFailedStartupSettings(
serverId: string,
agentId: string,
action: "retry" | "discard",
): Promise<boolean> {
if (action === "discard") {
discardFailedStartupSettings(serverId, agentId);
useSessionStore.getState().setQueuedSendError(serverId, agentId, null);
this.resumeIdleQueueIfReady(serverId, agentId);
return true;
}
const client = useSessionStore.getState().sessions[serverId]?.client;
if (!client) {
return false;
}
const result = await applyFailedStartupSettings({ serverId, agentId, client });
if (!result.applied) {
useSessionStore.getState().setQueuedSendError(serverId, agentId, result.errorMessage);
return false;
}
useSessionStore.getState().setQueuedSendError(serverId, agentId, null);
this.resumeIdleQueueIfReady(serverId, agentId);
return true;
}
drainQueuedAgentMessage(serverId: string, agentId: string): void {
if (getFailedStartupSettings(serverId, agentId)) {
return;
}
const drainKey = `${serverId}:${agentId}`;
if (this.queuedAgentDrainInFlight.has(drainKey)) return;
if (this.queuedAgentDrainInFlight.has(drainKey)) {
this.queuedAgentDrainPending.add(drainKey);
return;
}
const store = useSessionStore.getState();
const session = store.sessions[serverId];
const queue = session?.queuedMessages.get(agentId);
@@ -2892,7 +2953,11 @@ export class HostRuntimeStore {
return;
}
this.queuedAgentDrainInFlight.add(drainKey);
this.queuedAgentDrainPending.delete(drainKey);
useSessionStore.getState().setQueuedSendError(serverId, agentId, null);
const next = queue[0];
let drainSent = false;
let drainBlockedBySettingsError: string | null = null;
void sendQueuedComposerMessageNow({
agentId,
messageId: next.id,
@@ -2902,28 +2967,69 @@ export class HostRuntimeStore {
write: (update) => useSessionStore.getState().setQueuedMessages(serverId, update),
},
submitMessage: async ({ text, attachments }) => {
const supportsForgeAttachments =
useSessionStore.getState().sessions[serverId]?.serverInfo?.features?.forgeSearch === true;
await dispatchComposerAgentMessage({
client,
agentId,
text,
attachments,
attachmentSubmitFormat: resolveComposerAttachmentSubmitFormat({
supportsForgeAttachments,
}),
encodeImages,
submission: createMessageSubmissionWriter(serverId),
// The queue drains when the agent goes idle, but the agent can start a turn of its own
// in that same moment (a wake-up after background work). Steering folds the message
// into that turn instead of interrupting it; with no turn running, the daemon starts
// a normal one.
activeTurnBehavior: "steer",
});
const currentSession = useSessionStore.getState().sessions[serverId];
const supportsForgeAttachments = currentSession?.serverInfo?.features?.forgeSearch === true;
const supportsProviderSwitching =
currentSession?.serverInfo?.features?.providerSwitching === true;
const liveProvider = currentSession?.agents.get(agentId)?.provider;
const rawStagedSwitch = supportsProviderSwitching
? getStagedProviderSwitch(serverId, agentId)
: null;
const stagedProviderSwitch =
rawStagedSwitch && rawStagedSwitch.provider !== liveProvider ? rawStagedSwitch : null;
if (stagedProviderSwitch) {
beginStagedProviderSwitch(serverId, agentId);
}
try {
await dispatchComposerAgentMessage({
client,
agentId,
text,
attachments,
attachmentSubmitFormat: resolveComposerAttachmentSubmitFormat({
supportsForgeAttachments,
}),
encodeImages,
submission: createMessageSubmissionWriter(serverId),
stagedProviderSwitch,
onProviderSwitchCommitted: async (agent) => {
if (agent) {
this.tryAcceptAgentSnapshot(serverId, normalizeAgentSnapshot(agent, serverId));
}
if (stagedProviderSwitch) {
const settled = await settleCommittedProviderSwitch({
serverId,
agentId,
sentDraft: stagedProviderSwitch,
committedProvider: agent?.provider ?? null,
client,
});
if (!settled.applied) {
drainBlockedBySettingsError = settled.errorMessage;
}
}
},
// The queue drains when the agent goes idle, but the agent can start a turn of its own
// in that same moment (a wake-up after background work). Steering folds the message
// into that turn instead of interrupting it; with no turn running, the daemon starts
// a normal one.
activeTurnBehavior: "steer",
});
} finally {
if (stagedProviderSwitch) {
endStagedProviderSwitch(serverId, agentId);
}
}
},
})
.then((result) => {
if (result.status === "failed") {
if (result.status === "submitted") {
drainSent = drainBlockedBySettingsError === null;
useSessionStore
.getState()
.setQueuedSendError(serverId, agentId, drainBlockedBySettingsError);
} else if (result.status === "failed") {
useSessionStore.getState().setQueuedSendError(serverId, agentId, result.errorMessage);
console.error("[HostRuntime] failed to drain queued agent message", {
serverId,
agentId,
@@ -2934,6 +3040,9 @@ export class HostRuntimeStore {
})
.finally(() => {
this.queuedAgentDrainInFlight.delete(drainKey);
const hadPendingDrain = this.queuedAgentDrainPending.delete(drainKey);
if (!drainSent || !hadPendingDrain) return;
this.resumeIdleQueueIfReady(serverId, agentId);
});
}
@@ -2959,6 +3068,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 +3241,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(

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