Compare commits

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

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

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

A turn's final event now ends the run even when the timeline fails
to write it. Before this change the error escaped handleStreamEvent
before settleTerminalRun, so the agent stayed running and its waiters
hung. The durable store makes that write fallible, and shutdown made
it fail: settled() rejected after close.
2026-11-25 16:31:24 +01:00
Mohamed Boudra c228a3acac test(website): wait for hydration before submitting a plugin search
`openPlugins` waits only for the server-rendered heading. On WebKit, Enter
could land before hydration attached the search form's handler, so nothing
navigated and the page stayed on /plugins. The two tests that submit right
after opening the directory now wait for hydration first; `openPlugins` itself
stays as it is because a no-JavaScript test uses it.
2026-11-25 16:31:17 +01:00
Mohamed Boudra 1b6308502f fix(timeline): serve an empty older page before a retired first turn
After a rewind of the first prompt and a new turn, a `before` page whose
cursor fell in the retired prefix found no active row before the cursor. The
whole-turn loop then read the row at index -1 and threw, and ordinary paging
returned the first later row's seq as the start, past the page's end.
2026-11-25 16:20:34 +01:00
Mohamed Boudra 9e3107fcb7 test(opencode): read v2 children through the timeline-backed store
The child tests merged from main build a `ProviderSubagentStore` with no
timeline and read `list()` synchronously. On this branch the store keeps
children in the agent's timeline, so it takes one and its reads resolve
asynchronously. Each `apply` queues on the parent's timeline before its first
await, so an awaited `list` observes every event emitted before it.
2026-11-25 16:20:34 +01:00
Mohamed Boudra 5033ad0249 Merge origin/main into plan-provider-switch-sqlite-timelines
Conflicts resolved by keeping both intents:
- turn-boundary: main reads the reply through getAssistantReply (plugin
  cards); this branch narrows the fork cursor to epoch and seq.
- codex rewind: this branch's fork-and-verify flow, with main's
  threadDeveloperInstructions() for the developer instructions.
- agent-manager: this branch's ProviderHistoryReconcile type next to
  main's Omit<..., "signal"> query options.
Main's new plugin-card tests gain the anchorSeq this branch's cursors carry.
2026-11-25 16:00:06 +01:00
Mohamed Boudra 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
287 changed files with 13870 additions and 11625 deletions
-23
View File
@@ -131,29 +131,6 @@ jobs:
if: ${{ !cancelled() && steps.install.outcome == 'success' && (needs.changes.outputs.full != 'false' || needs.changes.outputs.sdk != 'false') }}
run: npm run typecheck:examples --workspace=@getpaseo/client
# Plugin process launches and launch wraps quote for cmd.exe, which only real Windows checks.
sdk-tests-windows:
name: sdk-tests (windows-latest)
needs: changes
if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.sdk != 'false') }}
runs-on: windows-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: "22"
cache: "npm"
- name: Install dependencies
run: node scripts/npm-retry.mjs ci
- name: Build plugin SDK
run: npm run build:relay && npm run build:client && npm run build:plugin
- name: Run plugin SDK tests
run: npm run test --workspace=@getpaseo/plugin
# The locked Playwright installers do not support ubuntu-latest's Ubuntu 26.04.
typecheck:
name: typecheck
+1
View File
@@ -54,6 +54,7 @@ At the start of non-trivial work, list `docs/` and skim anything relevant to the
| [docs/permissions.md](docs/permissions.md) | Semantic daemon permissions, principals, credentials, pairing invitations, and Hub authority |
| [docs/terminal-performance.md](docs/terminal-performance.md) | Terminal latency pipeline, coalescing/backpressure invariants, benchmark + perf spec usage |
| [docs/terminal-rendering.md](docs/terminal-rendering.md) | Native terminal view: xterm owns the grid, cluster placement, emoji widths, mixed-direction limits, render regression |
| [docs/timeline-sync.md](docs/timeline-sync.md) | Owned agent history, rewind retirements, live stream vs authoritative fetch, paged catch-up, client replica |
| [docs/agent-stream-performance.md](docs/agent-stream-performance.md) | Assistant text pipeline — coalescing window, paced reveal, why arrival lumps are smoothed at render |
| [docs/agent-stream-disclosure.md](docs/agent-stream-disclosure.md) | Expand/collapse in the chat timeline — hold contract, native anchor sequence, frame spacing, render-window cost |
| [docs/markdown-renderer.md](docs/markdown-renderer.md) | Shared Markdown engine, the vendored library fork, native selection, links, images and library constraints |
+6 -3
View File
@@ -39,8 +39,8 @@ An unarchived agent may be `closed` without being deleted or archived. Closing r
processes and subscriptions while retaining its Paseo identity, persistence handle, timeline,
workspace, labels, title, usage, attention, timestamps, and parent relationship. Opening or prompting
the agent runs through `ensureAgentLoaded()`, which resumes the durable provider session under the
same Paseo agent ID. Provider history is not appended again when the canonical timeline is already
primed.
same Paseo agent ID. Resume does not read provider history when the agent already has a timeline;
see [owned history](timeline-sync.md#owned-history).
Reload releases the old runtime before resuming its durable session: an idle provider process can
still own an exclusive writer. A close failure retains that runtime for cleanup and blocks the
@@ -256,7 +256,8 @@ lifecycle is separate from public workspace visibility and is not a public creat
Archive is a **soft delete**: the agent record stays on disk with `archivedAt` set, the runtime is closed, and the agent disappears from active lists. Archive is **global** — it lives on the server and propagates to every connected client.
Archive sets `archivedAt`, invokes the provider's native archive hook, and cascades to managed
children.
children. The timeline and the provider children stay, so an archived chat reads them without its
provider; deleting the agent removes them.
`create_agent_request` can opt an agent into `autoArchive`. In that mode the daemon archives the agent after the first terminal turn event (`turn_completed`, `turn_failed`, or `turn_canceled`). When the agent owns an isolated workspace, auto-archive archives that workspace too; the managed worktree is removed when its final workspace reference is gone.
@@ -352,6 +353,8 @@ Workspace status is an aggregate activity signal computed **per `workspaceId`**.
Running provider-native subagents contribute `running` to the workspace owned by their parent agent. Their completed, failed, and canceled states stay in the parent's subagents track.
Only the parent's current runtime makes a provider child running. A child's stored status is the last report about it, and that report can come from provider history or from a runtime an earlier daemon ran, so a stored `running` child does not make the workspace running or keep the parent's runtime alive. It counts again once the live session reports it running. Closing a runtime cancels the children that runtime reported running; children it never reported keep their stored status.
A finished or failed workspace can be marked unread after it has been reviewed. The daemon restores
attention on its newest eligible workspace-root agent, `error` for an agent whose lifecycle is
`error` and `finished` otherwise, without sending a new notification. Opening a workspace restores
+3 -1
View File
@@ -94,6 +94,7 @@ workspace for a directory clears it. The store lives in memory and resets on dae
| `server/directory-sync/` | Daemon-global latest-state sequences for projects, workspaces, and agents |
| `server/workspace-labels/` | Host-local label catalog, assignment mutations, and explicit subscriptions |
| `server/agent/agent-manager.ts` | Agent lifecycle state machine, timeline tracking, subscriber management |
| `server/agent/timeline/` | Owned agent history, provider children, rewind retirements, behind a backend |
| `server/agent/agent-storage.ts` | File-backed JSON persistence at `$PASEO_HOME/agents/` |
| `server/agent/tools/` | Transport-neutral catalog for workspaces, agents, permissions, and automation |
| `server/agent/mcp-server.ts` | Thin MCP adapter that registers the Paseo tool catalog with the MCP SDK |
@@ -402,7 +403,7 @@ initializing → idle ⇄ running
client-side dedup; the default fetch page is 200 items.
- Timeline row `timestamp` values are canonical daemon-owned timestamps. Providers may supply original replay timestamps, but clients must not guess timestamp trust or hide time UI based on local clock heuristics.
- Events stream to connected clients in real time; correctness is backed by authoritative timeline fetches and paged-to-completion catch-up.
- Agent state persists to `$PASEO_HOME/agents/{cwd-with-dashes}/{agent-id}.json`. Timeline rows are runtime memory; provider history is the durable transcript authority and resumed agents rebuild from it. That storage path is derived from `cwd`, not from workspace id.
- Agent state persists to `$PASEO_HOME/agents/{cwd-with-dashes}/{agent-id}.json`. That storage path is derived from `cwd`, not from workspace id. Timeline rows persist in the daemon database, `$PASEO_HOME/paseo.db`. They are the transcript authority after the first import of provider history. See [owned history](timeline-sync.md#owned-history).
## Right-sidebar boundary: directory-backed vs workspace-owned
@@ -478,6 +479,7 @@ Providers that can accept native tool definitions should set `supportsNativePase
```
$PASEO_HOME/
├── agents/{cwd-with-dashes}/{agent-id}.json # Agent record
├── paseo.db # Daemon database (SQLite): agent timelines
├── projects/projects.json # Project registry
├── projects/workspaces.json # Workspace registry
├── projects/icons/ # Custom project icon images
+41 -1
View File
@@ -34,7 +34,7 @@ Workspace archive runs lifecycle teardown from the exact `cwd` but removes only
`worktreeRoot` after its last active reference disappears. Worktree recovery recreates that backing
checkout from `mainRepoRoot`, then restores the relative path from `worktreeRoot` to `cwd`.
Paseo uses **file-based JSON persistence** instead of a traditional database. All data is validated at runtime with Zod schemas. Most stores write atomically (write to temp file, then rename); a few still use plain `writeFile` — see each section. There is no schema-versioning/migration framework — schemas rely on optional fields with defaults for forward compatibility, with a small amount of inline normalization in `persisted-config.ts` for legacy provider/speech entries.
Paseo persists most stores as JSON files, and agent timelines in the [daemon database](#daemon-database). JSON data is validated at runtime with Zod schemas. Most JSON stores write atomically (write to temp file, then rename); a few still use plain `writeFile` — see each section. JSON stores have no schema-versioning/migration framework — schemas rely on optional fields with defaults for forward compatibility, with a small amount of inline normalization in `persisted-config.ts` for legacy provider/speech entries.
All server-side stores live under `$PASEO_HOME` (defaults to `~/.paseo`).
@@ -53,6 +53,7 @@ $PASEO_HOME/
├── daemon-keypair.json # E2EE keypair for relay (mode 0600)
├── paseo.pid # Daemon PID lock file
├── local-credential # Per-run local client credential (mode 0600)
├── paseo.db # Daemon database (SQLite, with -wal and -shm files)
├── daemon.log # Default log file (path configurable)
├── agents/
│ └── {sanitized-cwd}/
@@ -181,6 +182,45 @@ Terminal activity contributes to the workspace status bucket **per `workspaceId`
---
## Daemon database
`$PASEO_HOME/paseo.db` is one SQLite file that the daemon opens at startup with `node:sqlite`
(`packages/server/src/server/database/`). Agent timelines are its only store today. Each store is a
`SchemaModule`: its own table-name prefix and an append-only list of migrations.
- **Migrations.** Startup runs every module's pending migrations in one transaction, so a failed
migration leaves the file as it was. `schema_versions` records each module's version and
`min_reader_version`. Mark a migration `breaking` when an older daemon cannot read the result,
for example a dropped or renamed column. An older daemon then refuses to start with
`DatabaseSchemaTooNewError`. Additive migrations leave older daemons working, and they ignore
modules they do not know. This matters because the app and the daemon update separately, and a
user can run an older daemon on the same `$PASEO_HOME`.
- **Failure.** A file that SQLite cannot open stops the daemon with `DatabaseOpenError`, which
names the path. The daemon does not delete or recreate the file.
- **Access.** The file holds every prompt and reply, so the daemon sets it and its `-wal` and `-shm`
files to mode `0600` on every open. SQLite gives the WAL files it creates the mode of the database
file.
- **Durability.** The database uses WAL with `synchronous = NORMAL`. A power loss can drop the
last commits but does not corrupt the file.
- **Checkpoints.** A checkpoint syncs the file to disk and takes up to 100 ms. SQLite's
auto-checkpoint runs it on the committing thread, which stalled the event loop during streaming.
The daemon turns it off and checkpoints from a worker thread with its own connection. If the
worker exits, the daemon turns auto-checkpoint back on.
- **Transactions.** `write` and `read` callbacks are synchronous, so a transaction never spans an
`await` and transactions never interleave.
- **Node.** `node:sqlite` needs Node 22.16 or later. Node 22 prints an experimental warning once,
when the daemon opens the database.
### Agent timelines
`AgentTimeline` owns each agent's history, and its SQLite backend stores the projected rows, the
source ranges, retirements, the open rewind, and provider children in `timeline_*` tables. The text
of a streamed assistant or reasoning message is stored as one chunk per source event, beside its
row, so a chunk never rewrites the message. An earlier file store rewrote the whole transcript on
every update. See [owned history](timeline-sync.md#owned-history).
---
## 2. Daemon Configuration
**Path:** `$PASEO_HOME/config.json`
+2 -64
View File
@@ -462,55 +462,8 @@ Server entries register async handlers with `server.addHook(name, handler)`, ret
function. Names follow `subject.operation.position`, ending in `before` or `after`. Waiting is a per-hook
registry property, independent of position. The [hooks reference](../public-docs/plugins/hooks.md)
owns payloads, ordering, failure behavior, and examples. `agent.create.before` edits saved
configuration; `agent.open.before` contributes launch-only `env`, `tools`, `mcpServers`, and a
[launch wrap](#launch-wrap) on every open. Executable tool definitions stay in the plugin process; only metadata crosses the boundary.
`packages/server/src/server/plugins/session-attachments.ts` records what each plugin contributed to
each live session. A plugin start, stop, or reload reruns only that plugin's callback per session,
swaps its tools in place, and reopens a session only when its launch would differ. A reopen closes
the provider process, so a reload must not reopen agents the plugin does not change.
### Launch wrap
An `agent.open.before` result can carry `wrap: [executable, ...args]`. The provider then starts that
session's harness as `[...wrap, command, ...args]` with the final hook env. It starts with no shell,
except Windows script launchers, which go through cmd.exe like any provider launcher
(`spawnProcess` quotes each argument). An argument with spaces stays one element. `executable` must
be an absolute path.
The wrap is never saved on the agent; every open asks the hooks again, and a plugin session reopen
reuses the wrap it opened with.
- **Support is a provider property.** The provider snapshot entry carries `launchWrap: true` when the
provider can apply a wrap. Read it in `agent.create.before` with `paseo.providers.snapshot()`; an
absent field means unsupported, which is also what a host without this feature reports. Core
providers declare it in the provider contract table in `provider-registry.ts`; every core provider
that starts a local harness declares it, and custom ACP providers and providers that extend a core
one inherit it. A plugin provider declares `ProviderRegistration.launchWrap`;
`runAcpProvider({ command })` sets it, a connector declares it itself (Muse Code does). The declaration travels with the
registration metadata, so it is in the snapshot before the provider first connects.
- **One wrap per open.** A later hook, in the same plugin or a later one, may omit the wrap or return
the same value. A different value fails the open.
- **Fail closed.** `buildLaunchContext` admits a wrapped open before any session harness starts. It
throws `LaunchWrapUnsupportedError` (`code: "launch_wrap_unsupported"`) when the provider does not
declare support, or when a plugin provider's live connection lacks `session.launch_wrap`. A host
that predates `wrap` rejects the key: the hook result schema is strict. A missing launcher fails the
spawn; nothing retries the bare command.
Once an open selects a wrap, a supported provider runs that session's harness through it or fails
before starting the harness. Every provider starts through `spawnProcess({ wrap })`, which owns the
argv and Windows launcher handling; `applyLaunchWrap` covers the launches that do not go through it
(pty terminals, MCP stdio transports, worktree commands). The wrap also covers what Paseo starts for
the session: stdio MCP servers Paseo hosts for the agent (OMP, OpenCode v2), Pi's MCP probe, and ACP
client terminals. OpenCode shares one server between sessions, so a wrapped session gets a dedicated
server instead; an explicitly configured external OpenCode server cannot be wrapped and the open
fails. The guarantee does not cover:
1. Paseo's host terminal tools (`create_terminal`, `send_terminal_keys`) run outside the wrap.
2. Work before the open hook runs unwrapped: draft command and control discovery, and the catalog
lookup during create when no model is set.
3. Host-side operations run unwrapped: availability and capability probes (the ACP connection's
initialize probe included), catalog and session listing, version and update commands, usage
queries, and Codex native archive and unarchive.
4. Losing the plugin that chose the wrap is not covered: a later open without it runs unwrapped.
configuration; `agent.open.before` contributes launch-only `env`, `tools`, and `mcpServers` on
every open. Executable tool definitions stay in the plugin process; only metadata crosses the boundary.
Worktree placement is resolved before Git source planning, so a hook can change the branch and base
without undoing fetched refs. Restores use the recorded destination and bypass creation hooks.
@@ -530,17 +483,6 @@ change requests; `remove` and `restore` fall back to built-in Git when the plugi
[worktree managers reference](../public-docs/plugins/reference.md#worktree-managers) and
`plugin-examples/worktrunk`.
`terminal.create.before` runs in `withTerminalCreateHook`, which wraps the daemon's one terminal manager, so every creation path is covered and adopted terminals are not; callers pass an `origin` to name the source. `command.run.before` runs inside the setup and teardown runners through `commandRunHook`. Setup and archive dependencies take `lifecycle` as a required field so a new caller cannot skip the hook by omission; pass `null` only where no plugins run.
Both hooks change only `env` and a [launch wrap](#launch-wrap); `keepSelectedWrap` in the lifecycle
module applies the one-wrap rule to all three wrap hooks. The terminal wrap becomes the terminal's
`command` and `args` in `withTerminalCreateHook`, so the terminal worker protocol does not change and
no previous-version adapter is needed. A default-shell terminal resolves the shell there through
`default-terminal-shell.ts`, which stays apart from `terminal.ts` so the daemon does not load node-pty.
The wrapped shell starts without Paseo's shell integration, which is why a wrapped script does not
report command completion. A setup or teardown wrap goes in front of the
`buildStringCommandShellInvocation` argv.
Emit from the operation owner, not a client subscription. Provider history replay must not trigger
live hooks. Notifications must not be awaited inside agent mutations: a handler can send a prompt
or answer a permission through its own daemon session. Awaiting it there deadlocks that command.
@@ -640,10 +582,6 @@ persistence. Re-read credentials and provider-owned configuration on `session.op
daemon launch from `connect` and the per-session env and MCP servers from `session.open`. There is
no provider reload input.
Declare `ProviderRegistration.launchWrap: true` when every session spawns its own harness and can
run it as `[...config.wrap, command, ...args]`; offer `session.launch_wrap` on the connection. See
[Launch wrap](#launch-wrap). `runAcpProvider({ command })` does both.
For an ACP command, register `runAcpProvider({ id, label, command })` from
`@getpaseo/plugin/server/acp`. The shim builds the standard row for each ACP tool `kind`
(`acp-internal/tool-call-detail.ts`). Its transformer hooks cover narrow vendor differences; do not translate the
+68 -11
View File
@@ -5,15 +5,9 @@ Agent chat delivery has two paths:
1. **Live stream** — `agent_stream` WebSocket messages for immediacy. These may be delta-shaped lifecycle updates.
2. **Authoritative history** — `fetch_agent_timeline_request` for correctness. This always returns full projected timeline items, never lifecycle deltas.
The daemon retains projected items in memory. Each source event advances the stream sequence,
then replaces the previous tool state or merges into the current text item. Intermediate payloads
are never retained for history or catch-up. Provider history is the durable transcript authority
and rebuilds the projection when an agent resumes.
Pagination bounds each read, not total resident history. Active and idle agents retain their
projected transcript; archive releases it and later history reads rebuild it from the provider.
Streaming overhead must remain proportional to the retained transcript. Cumulative text snapshots
must be released after their deltas have been consumed.
Pagination bounds each read, not total resident history. Streaming overhead must remain
proportional to the retained transcript. Cumulative text snapshots must be released after their
deltas have been consumed.
The invariants are:
@@ -32,6 +26,50 @@ bounded item is used for runtime timeline rows and live stream events. Provider
applies the same rule so reopening an agent cannot restore an oversized payload. Fetches apply it
again to assistant and reasoning rows the projection merges from many chunks.
## Owned history
The daemon owns each agent's history in `AgentTimeline`
(`packages/server/src/server/agent/timeline/`): one ordered history per agent, with each provider
child's descriptor and history in a child scope of the same agent. Each source event advances the
stream sequence, then replaces the previous tool state or merges into the current text item.
Intermediate payloads are never retained for history or catch-up.
History is append-only: rewind, import, reload and archive never delete or rewrite a row. Only
deleting the agent, or a provider removing one of its own children, deletes history.
- **Rewind** retires a range of rows. They leave the conversation and stay stored, in the same
epoch. See [Rewind retires rows](#rewind-retires-rows).
- **Provider history** is imported only into an agent that has no history. After that, resume
does not read it. Reload agent and Unarchive require the provider history to start with the
same prompt IDs and text in order. They then append whole new turns, starting at the next
prompt. Existing replies, including partial replies, stay as recorded. If the prompts differ,
for example because the provider stored expanded attachment text, the chat stays unchanged and
Paseo reports a mismatch. A provider child Paseo already holds, listed or retired, is never imported again.
- **Archive and reload** keep the history and the provider children. An archived chat reads them
without its provider. Opening a stored agent that has no provider session to resume starts its
first session on the same history.
- **Delete** removes the agent's history and every child's, retired ones included, before the
agent record. If the history cannot be removed, the request fails and the agent stays listed. The
user can keep using it and delete it again.
`epoch` is the stored history's identity, minted once when the history is created.
`AgentTimeline` serializes every operation of one agent, child scopes included, and keeps its
state in an `AgentTimelineBackend`: the sequence, the rows and retirements, prompt identities, the
open rewind, and the children. The backend contract suite is `agent-timeline.test.ts`, run over
`TIMELINE_CONTRACT_BACKENDS` in `timeline/testing.ts`. The daemon uses the SQLite backend in the
[daemon database](data-model.md#daemon-database). History, retirements, the open rewind, and
provider children survive a daemon restart in the same epoch, so clients keep their cursors. A
closed or archived agent holds no history in memory. Each fetch reads the page from the database
and starts no provider. An internal agent, such as the one that writes a commit message, keeps its
history in a memory backend instead, so it leaves nothing on disk. The memory backend also serves
tests.
An open rewind is stored with the history. Resuming an agent whose history holds one settles it
before the agent takes prompts: a recorded provider cut is committed, and an unknown outcome is
judged from the resumed provider history. When that history proves nothing, the rewind stays open
and the agent refuses prompts with the unknown-outcome error.
## Presence is not delivery
Client heartbeat reports presence:
@@ -168,7 +206,7 @@ or retry backoff. This cannot keep a mobile socket alive after the operating sys
bookkeeping without replacing timeline arrays, preserving an upward-scrolled viewport.
- When the page overlaps or is adjacent to the local end cursor, only projected items newer than
that cursor are applied. Already-covered rows are not replayed.
- A true middle gap, epoch change, or rewind atomically replaces stale canonical history with the
- A true middle gap or epoch change atomically replaces stale canonical history with the
latest tail. The replacement reconciles positioned live rows beyond its coverage and unresolved
local submissions; it never retains two discontiguous canonical ranges.
@@ -181,6 +219,24 @@ history replay. The pending approval UI can hide that tool from presentation, bu
must retain its position. Creating a new history card on rejection places it after the prompt that
rejected it; changing steer-event ordering would also put new assistant output before that prompt.
## Rewind retires rows
A conversation rewind commits a retirement `{ seq, retireFromSeq }`: active rows anchored in
`[retireFromSeq, seq)` leave the conversation, and `seq` is the retirement's own position in the
sequence. The provider children spawned by retired tool calls, and their descendants, are retired
in the same commit. They leave the listing, keep their history, and drop late provider events.
Clients learn of a retirement live through `agent.timeline.rewind`, and on pages through
`retirements`, which lists the retirements whose `seq` lies inside the page's span. The client
drops the rows it holds in that range; rows without a timeline position are unechoed local sends
and stay. Retired ranges and the retirement's `seq` count as covered, so forward cursors advance
through them. Tail, before and prompt-jump pages are served from active rows, so one served before
a retirement the client already applied is stale and is refetched (`viewed-timeline-sync.ts`).
Clients without `timeline_rewind_operations` cannot drop retired rows. For them the session derives
a wire epoch that changes with each retirement, so they take the destructive replacement they
always took on rewind. The shim is tagged `COMPAT(timelineRewindOperations)`.
## Provider child history
Child transcripts use the same projected-page reconciliation as the main conversation. The client
@@ -345,7 +401,7 @@ the draft-create handoff is the one boundary that also permits the legacy canoni
arrived first. Generic reducers and consumers do not reimplement message identity matching.
Ordinary bootstrap, same-epoch reset, and catch-up replacement preserve unmatched locally submitted
rows because a provider may never echo them. A known epoch change or rewind replaces history and
rows because a provider may never echo them. A known epoch change replaces history and
drops acknowledged local rows omitted by the new canonical epoch; every transaction not yet
acknowledged by the provider, and no other local row, crosses that destructive boundary. A cold
reset without an existing epoch is destructive because the client has no continuity anchor.
@@ -361,6 +417,7 @@ canonical assistant prefix, it stays in the head lane. No row may be returned in
## Relevant code
- Server owned history: `packages/server/src/server/agent/timeline/`
- Server live stream forwarding: `packages/server/src/server/session.ts`
- App sync planning: `packages/app/src/timeline/timeline-sync-plan.ts`
- App viewed-agent synchronization: `packages/app/src/timeline/viewed-timeline-sync.ts`
+1 -1
View File
@@ -1 +1 @@
sha256-TAVzJzziWDAapQkG4TLkLzOlodkdFNKSl3y/Tm9HB28=
sha256-IAhKhkolW4xvFvMaAEFdhYvPAhTm2azsqbGMKCKL3q0=
+20 -1
View File
@@ -45,6 +45,9 @@
"react-dom": "19.2.3",
"typescript": "^5.9.3",
"ws": "^8.20.0"
},
"engines": {
"node": ">=22.16.0"
}
},
"node_modules/@0no-co/graphql.web": {
@@ -39719,6 +39722,9 @@
"typescript": "^5.2.2",
"vitest": "^4.1.6",
"zx": "^8.8.5"
},
"engines": {
"node": ">=22.16.0"
}
},
"packages/cli/node_modules/@vitest/expect": {
@@ -40646,7 +40652,7 @@
"@playwright/test": "^1.56.1",
"@types/express": "^4.17.20",
"@types/markdown-it": "^14.2.0",
"@types/node": "^20.9.0",
"@types/node": "^22.16.0",
"@types/qrcode": "^1.5.6",
"@types/uuid": "^9.0.7",
"@types/ws": "^8.5.8",
@@ -40654,6 +40660,9 @@
"cross-env": "^10.1.0",
"tsx": "^4.6.0",
"vitest": "^4.1.6"
},
"engines": {
"node": ">=22.16.0"
}
},
"packages/server/node_modules/@esbuild/aix-ppc64": {
@@ -41101,6 +41110,16 @@
"@types/mdurl": "^2"
}
},
"packages/server/node_modules/@types/node": {
"version": "22.20.5",
"resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.5.tgz",
"integrity": "sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==",
"dev": true,
"license": "MIT",
"dependencies": {
"undici-types": "~6.21.0"
}
},
"packages/server/node_modules/@vitest/expect": {
"version": "4.1.6",
"resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.6.tgz",
+3
View File
@@ -169,5 +169,8 @@
"tiny-async-pool": {
"semver@^5": "5.7.2"
}
},
"engines": {
"node": ">=22.16.0"
}
}
@@ -13,6 +13,13 @@ import {
import { expectNearBottom, scrollChatAwayFromBottom } from "../support/helpers/agent-bottom-anchor";
import { holdRewindCompletion } from "../support/helpers/agent-timeline-gate";
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
import { userScrollsTimelineToHistoryStart } from "../support/helpers/timeline-pagination";
import {
closeWorkspaceAgentTab,
fetchAgentArchivedAt,
primeAdditionalPage,
resetSeededPageState,
} from "../support/helpers/archive-tab";
async function completeSubmittedTurn(
page: Page,
@@ -48,26 +55,102 @@ async function expectTurnCompletesNormally(
await expectAgentIdle(page);
}
async function openAgentOnAnotherClient(
page: Page,
agent: Awaited<ReturnType<typeof seedMockAgentWorkspace>>,
): Promise<void> {
await primeAdditionalPage(page);
await resetSeededPageState(page);
await openAgentRoute(page, agent);
await expectComposerVisible(page);
}
/** The prompts the chat shows, in order, each exactly once. */
async function expectPrompts(page: Page, prompts: string[]): Promise<void> {
const messages = page.getByTestId("user-message");
await expect(messages).toHaveCount(prompts.length);
await expect(messages).toContainText(prompts);
}
async function reloadAgentFromTabMenu(page: Page, agentId: string): Promise<void> {
const tabId = `workspace-tab-agent_${agentId}`;
await page.getByTestId(tabId).filter({ visible: true }).first().click({ button: "right" });
await page.getByTestId(`workspace-tab-context-agent_${agentId}-reload-agent`).click();
}
async function archiveAgentByClosingTab(
page: Page,
agent: Awaited<ReturnType<typeof seedMockAgentWorkspace>>,
): Promise<void> {
await closeWorkspaceAgentTab(page, agent.agentId);
await expect.poll(() => fetchAgentArchivedAt(agent.client, agent.agentId)).not.toBeNull();
}
async function unarchiveAgent(page: Page): Promise<void> {
await page.getByRole("button", { name: "Unarchive", exact: true }).click();
await expect(page.getByText("This agent is archived", { exact: true })).toHaveCount(0, {
timeout: 30_000,
});
}
async function expectToast(page: Page, message: string): Promise<void> {
await expect(page.getByTestId("app-toast-message")).toHaveText(message, { timeout: 30_000 });
}
// The mock provider's resumed session holds no history, so it never matches what Paseo shows.
const UNSYNCED_RELOAD =
"Reloaded agent, but the provider's history doesn't match this chat, so it wasn't synced";
/** The prompts of the whole conversation, after scrolling up through its older pages. */
async function expectConversationPrompts(page: Page, prompts: string[]): Promise<void> {
const messages = page.getByTestId("user-message");
await expect
.poll(async () => {
await userScrollsTimelineToHistoryStart(page);
return await messages.count();
})
.toBe(prompts.length);
await expect(messages).toContainText(prompts);
}
// A row React remounts loses this attribute; one that stays mounted keeps it.
async function markMounted(row: Locator): Promise<void> {
await row.evaluate((element) => element.setAttribute("data-e2e-mounted", "before-rewind"));
}
async function expectStillMounted(row: Locator): Promise<void> {
await expect(row).toHaveAttribute("data-e2e-mounted", "before-rewind");
}
test.describe("Agent message rewind", () => {
test("rewinds a submitted prompt without replaying history and preserves a human draft", async ({
test("rewinds a prompt in place on every open client and keeps a human draft", async ({
page,
}) => {
test.setTimeout(90_000);
test.setTimeout(150_000);
const retainedPrompt = "Keep this completed turn after rewind.";
const rewoundPrompt = "Remove this completed turn after rewind.";
const nextPrompt = "Continue after the rewind.";
const preservedDraft = "Keep this human draft after rewind.";
const agent = await seedMockAgentWorkspace({
repoPrefix: "message-rewind-roundtrip-",
title: "Message rewind roundtrip",
model: "ten-second-stream",
});
const otherClient = await page.context().newPage();
try {
const rewindCompletion = await holdRewindCompletion(page, agent.agentId);
await openAgentRoute(page, agent);
await expectComposerVisible(page);
await completeSubmittedTurn(page, agent, retainedPrompt);
const retainedMessage = await completeSubmittedTurn(page, agent, retainedPrompt);
const userMessage = await completeSubmittedTurn(page, agent, rewoundPrompt);
await test.step("a second client opens the same chat", async () => {
await openAgentOnAnotherClient(otherClient, agent);
await expectPrompts(otherClient, [retainedPrompt, rewoundPrompt]);
});
await markMounted(retainedMessage);
await scrollChatAwayFromBottom(page, {
deltaY: -900,
minDistanceFromBottom: 300,
@@ -76,19 +159,92 @@ test.describe("Agent message rewind", () => {
await blurComposerInput(page);
rewindCompletion.clearTimelineStreamCount();
const rewind = rewindConversation(page, userMessage, rewoundPrompt);
await rewindCompletion.waitForDelayedResponse();
await expect(page.getByTestId("rewind-menu-conversation")).toBeDisabled();
expect(rewindCompletion.timelineStreamCount()).toBe(0);
rewindCompletion.release();
await rewind;
await test.step("the rewind stays pending until the daemon answers", async () => {
const rewind = rewindConversation(page, userMessage, rewoundPrompt);
await rewindCompletion.waitForDelayedResponse();
await expect(page.getByTestId("rewind-menu-conversation")).toBeDisabled();
expect(rewindCompletion.timelineStreamCount()).toBe(0);
rewindCompletion.release();
await rewind;
});
await expect(page.getByTestId("user-message").filter({ hasText: rewoundPrompt })).toHaveCount(
0,
);
await expectComposerDraft(page, preservedDraft);
await expectComposerNotFocused(page);
await expectNearBottom(page);
await test.step("the rewound turn leaves without reloading the chat", async () => {
await expectPrompts(page, [retainedPrompt]);
await expectStillMounted(retainedMessage);
expect(rewindCompletion.timelineFetchCount()).toBe(0);
await expectComposerDraft(page, preservedDraft);
await expectComposerNotFocused(page);
await expectNearBottom(page);
await expectPrompts(otherClient, [retainedPrompt]);
});
await test.step("the next prompt appears once on both clients", async () => {
await completeSubmittedTurn(otherClient, agent, nextPrompt);
await expectPrompts(otherClient, [retainedPrompt, nextPrompt]);
await expectPrompts(page, [retainedPrompt, nextPrompt]);
});
await test.step("a reconnecting client loads the rewound conversation", async () => {
await otherClient.reload();
await expectPrompts(otherClient, [retainedPrompt, nextPrompt]);
});
} finally {
await otherClient.close();
await agent.cleanup();
}
});
test("keeps the rewound conversation through Reload agent, archive and unarchive", async ({
page,
}) => {
test.setTimeout(150_000);
const keptPrompt = "Keep this turn through reload and archive.";
const rewoundPrompt = "Rewind this turn before reloading.";
const nextPrompt = "Continue after the rewind, then reload.";
const agent = await seedMockAgentWorkspace({
repoPrefix: "message-rewind-reload-archive-",
title: "Message rewind reload archive",
model: "ten-second-stream",
});
try {
await openAgentRoute(page, agent);
await expectComposerVisible(page);
await completeSubmittedTurn(page, agent, keptPrompt);
const rewound = await completeSubmittedTurn(page, agent, rewoundPrompt);
await rewindConversation(page, rewound, rewoundPrompt);
await expectPrompts(page, [keptPrompt]);
await completeSubmittedTurn(page, agent, nextPrompt);
await expectPrompts(page, [keptPrompt, nextPrompt]);
await test.step("Reload agent keeps the chat and says the provider's history was not synced", async () => {
await reloadAgentFromTabMenu(page, agent.agentId);
await expectToast(page, UNSYNCED_RELOAD);
await expectPrompts(page, [keptPrompt, nextPrompt]);
await expectComposerVisible(page);
});
await test.step("the archived chat shows the rewound conversation", async () => {
await archiveAgentByClosingTab(page, agent);
await openAgentRoute(page, agent);
await expect(page.getByText("This agent is archived", { exact: true })).toBeVisible({
timeout: 30_000,
});
await expectConversationPrompts(page, [keptPrompt, nextPrompt]);
});
await test.step("unarchiving keeps the rewound conversation", async () => {
await unarchiveAgent(page);
await expectToast(page, UNSYNCED_RELOAD);
await expectComposerVisible(page);
await expectConversationPrompts(page, [keptPrompt, nextPrompt]);
});
await test.step("a reconnecting client loads the same conversation", async () => {
await page.reload();
await expectComposerVisible(page);
await expectConversationPrompts(page, [keptPrompt, nextPrompt]);
});
} finally {
await agent.cleanup();
}
@@ -1,7 +1,6 @@
import { expect, test } from "../support/fixtures";
import { gotoAppShell } from "../support/helpers/app";
import {
chooseProjectWithKeyboard,
connectNewWorkspaceDaemonClient,
expectNewWorkspaceControlsEnabled,
expectNewWorkspaceProjectSelected,
@@ -177,33 +176,6 @@ test.describe("New workspace entry points", () => {
}
});
test("choosing a project returns focus to the composer, even when the picker was opened by clicking it", async ({
page,
}) => {
const projectA: SeededWorkspace = await seedWorkspace({ repoPrefix: "entry-focus-a-" });
const projectB: SeededWorkspace = await seedWorkspace({ repoPrefix: "entry-focus-b-" });
try {
await gotoAppShell(page);
await waitForSidebarHydration(page);
await openGlobalNewWorkspaceComposer(page);
const composer = page.getByRole("textbox", { name: "Message agent..." });
await page.getByTestId("new-workspace-project-picker-trigger").click();
await chooseProjectWithKeyboard(page, projectB.projectDisplayName);
await expectNewWorkspaceProjectSelected(page, projectB.projectDisplayName);
await expect(composer).toBeFocused();
await page.keyboard.press("Control+N");
await chooseProjectWithKeyboard(page, projectA.projectDisplayName);
await expectNewWorkspaceProjectSelected(page, projectA.projectDisplayName);
await expect(composer).toBeFocused();
} finally {
await projectA.cleanup();
await projectB.cleanup();
}
});
test("keeps the in-progress form when the remembered workspace is archived elsewhere", async ({
page,
}) => {
@@ -2,7 +2,6 @@ import { expect, test, type Page } from "../support/fixtures";
import { gotoAppShell } from "../support/helpers/app";
import { waitForSidebarHydration } from "../support/helpers/workspace-ui";
import {
chooseProjectWithKeyboard,
expectNewWorkspaceDraft,
fillNewWorkspaceDraft,
openNewWorkspaceComposer,
@@ -110,27 +109,6 @@ test.describe("New workspace: launching a terminal", () => {
});
});
test("with a profile that takes no prompt, choosing a project keeps focus on the Project field", async ({
page,
}) => {
await gotoAppShell(page);
await waitForSidebarHydration(page);
await openNewWorkspaceComposer(page, {
projectKey: workspace.projectKey,
projectDisplayName: workspace.projectDisplayName,
});
await selectLaunchOption(page, BARE_PROFILE.id);
await expect(terminalPromptInput(page)).toHaveCount(0);
// The read-only command preview has nothing to type into, so the picker
// hands focus back to the field that opened it.
const projectTrigger = page.getByTestId("new-workspace-project-picker-trigger");
await projectTrigger.focus();
await page.keyboard.press("Enter");
await chooseProjectWithKeyboard(page, workspace.projectDisplayName);
await expect(projectTrigger).toBeFocused();
});
test("switching terminal profiles restores the prompt and its fullscreen affordance", async ({
page,
}) => {
@@ -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();
}
@@ -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,
};
}
@@ -243,14 +243,6 @@ export async function openNewWorkspaceProjectPickerWithShortcut(
await expect(searchInput).toBeFocused();
}
export async function chooseProjectWithKeyboard(page: Page, projectName: string): Promise<void> {
const searchInput = page.getByPlaceholder("Search projects");
await expect(searchInput).toBeFocused({ timeout: 30_000 });
await page.keyboard.type(projectName);
await page.keyboard.press("Enter");
await expect(searchInput).toBeHidden({ timeout: 10_000 });
}
export async function expectNewWorkspaceProjectSelected(
page: Page,
projectDisplayName: string,
@@ -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"));
@@ -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",
+5
View File
@@ -408,6 +408,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,
);
@@ -1166,6 +1170,7 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
agentId={agentId}
serverId={resolvedServerId}
epoch={timelineEpoch}
rewindSeq={timelineRewindSeq}
items={findItems}
viewportRef={viewportRef}
revealLoadedMessage={revealLoadedMessage}
@@ -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}>
@@ -232,7 +232,6 @@ export interface HostPickerProps {
open: boolean;
onOpenChange: (open: boolean) => void;
anchorRef: React.RefObject<View | null>;
restoreFocusRef?: ComboboxProps["restoreFocusRef"];
includeAllHost?: boolean;
includeAddHost?: boolean;
onAddHost?: () => void;
@@ -255,7 +254,6 @@ export function HostPicker({
open,
onOpenChange,
anchorRef,
restoreFocusRef,
includeAllHost,
includeAddHost,
onAddHost,
@@ -406,7 +404,6 @@ export function HostPicker({
open={open}
onOpenChange={onOpenChange}
anchorRef={anchorRef}
restoreFocusRef={restoreFocusRef}
desktopPlacement={desktopPlacement}
desktopMinWidth={desktopMinWidth}
/>
@@ -55,7 +55,6 @@ import { HostPicker } from "@/components/hosts/host-picker";
import { SidebarDisplayPreferencesMenu } from "@/components/sidebar/display-preferences/menu";
import { SidebarSeparator } from "@/components/sidebar/sidebar-separator";
import { SidebarToastRegion } from "@/components/sidebar/sidebar-toast-region";
import { SidebarSelectionHost } from "@/sidebar-selection";
import { SidebarNavRows, useVisibleSidebarNavItems } from "@/components/sidebar/sidebar-nav-rows";
import { SidebarFooterIconHighlight } from "@/components/sidebar/sidebar-footer-icon-highlight";
import { SidebarHelpMenu } from "@/components/sidebar/sidebar-help-menu";
@@ -668,7 +667,6 @@ function MobileSidebar({
listHeaderComponent={workspacesSectionHeaderElement}
/>
)}
<SidebarSelectionHost active={active} workspaceEntriesByKey={workspaceEntriesByKey} />
</SidebarToastRegion>
</SidebarViewSlot>
@@ -924,7 +922,6 @@ function DesktopSidebar({
listHeaderComponent={workspacesSectionHeaderElement}
/>
)}
<SidebarSelectionHost active={active} workspaceEntriesByKey={workspaceEntriesByKey} />
</SidebarToastRegion>
</SidebarViewSlot>
@@ -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()
@@ -101,17 +101,7 @@ import {
import { useLongPressDragInteraction } from "@/components/sidebar/use-long-press-drag-interaction";
import { SidebarSectionHeader } from "@/components/sidebar/sidebar-section-header";
import { SidebarGroupToggleRow } from "@/components/sidebar/sidebar-group-toggle-row";
import {
createWorkspaceVisibilityPolicy,
selectSidebarGroupVisibility,
} from "@/components/sidebar/sidebar-group-visibility";
import {
isShiftPressEvent,
registerSidebarVisibleWorkspaceKeysReader,
useIsSidebarSelectionMode,
useIsWorkspaceBulkSelected,
useSidebarSelectionStore,
} from "@/sidebar-selection";
import { createWorkspaceVisibilityPolicy } from "@/components/sidebar/sidebar-group-visibility";
import { useLimitedSidebarGroup } from "@/components/sidebar/use-limited-sidebar-group";
import {
SidebarWorkspaceRowFrame,
@@ -294,7 +284,6 @@ interface WorkspaceRowInnerProps {
archiveLabel?: string;
archiveStatus?: "idle" | "pending" | "success";
archivePendingLabel?: string;
onSelectWorkspace?: () => void;
onArchive?: () => void;
onCopyBranchName?: () => void;
onCopyPath?: () => void;
@@ -618,14 +607,12 @@ function WorkspaceRowRightGroup({
isHovered,
isTouchPlatform,
isCreating,
isSelectionMode,
showShortcutBadge,
shortcutNumber,
archiveLabel,
archiveStatus,
archivePendingLabel,
archiveShortcutKeys,
onSelectWorkspace,
onArchive,
onMarkAsRead,
onMarkAsUnread,
@@ -640,14 +627,12 @@ function WorkspaceRowRightGroup({
isHovered: boolean;
isTouchPlatform: boolean;
isCreating: boolean;
isSelectionMode: boolean;
showShortcutBadge: boolean;
shortcutNumber: number | null;
archiveLabel?: string;
archiveStatus?: "idle" | "pending" | "success";
archivePendingLabel?: string;
archiveShortcutKeys?: ShortcutKey[][] | null;
onSelectWorkspace?: () => void;
onArchive?: () => void;
onMarkAsRead?: () => void;
onMarkAsUnread?: () => void;
@@ -675,7 +660,6 @@ function WorkspaceRowRightGroup({
isHovered,
isTouchPlatform,
showShortcut,
isSelectionMode,
});
const kebab = useOpenKebabMenuVisibility(showKebabInSlot);
@@ -711,7 +695,6 @@ function WorkspaceRowRightGroup({
onRename={onRename}
onMarkAsRead={onMarkAsRead}
onMarkAsUnread={onMarkAsUnread}
onSelectWorkspace={onSelectWorkspace}
onArchive={onArchive}
archiveLabel={archiveLabel}
archiveStatus={archiveStatus}
@@ -1082,7 +1065,6 @@ function WorkspaceRowInner({
archiveLabel,
archiveStatus = "idle",
archivePendingLabel,
onSelectWorkspace,
onArchive,
onCopyBranchName,
onCopyPath,
@@ -1097,8 +1079,6 @@ function WorkspaceRowInner({
}: WorkspaceRowInnerProps) {
const isCompact = useIsCompactFormFactor();
const [isHighlighted, setIsHighlighted] = useState(false);
const isSelectionMode = useIsSidebarSelectionMode();
const isBulkSelected = useIsWorkspaceBulkSelected(workspace.workspaceKey);
const isTouchPlatform = platformIsNative || isCompact;
const interaction = useLongPressDragInteraction({
drag,
@@ -1111,75 +1091,30 @@ function WorkspaceRowInner({
...dragAttributes
} = dragHandleProps?.attributes ?? {};
const { onPress: handleNavigatePress, feedback } = useWorkspaceRowPress({
const { onPress: handlePress, feedback } = useWorkspaceRowPress({
didLongPressRef: interaction.didLongPressRef,
onPress,
selected,
});
const handleRowPress = useCallback(
(event: GestureResponderEvent) => {
const shiftKey = isShiftPressEvent(event);
if (isSelectionMode || shiftKey) {
if (interaction.didLongPressRef.current) {
interaction.didLongPressRef.current = false;
return;
}
event.preventDefault?.();
useSidebarSelectionStore.getState().pressWorkspace(workspace.workspaceKey, { shiftKey });
return;
}
handleNavigatePress();
},
[handleNavigatePress, interaction.didLongPressRef, isSelectionMode, workspace.workspaceKey],
);
const handleRowPressIn = useCallback(
(event: GestureResponderEvent) => {
if (isShiftPressEvent(event)) {
event.preventDefault?.();
return;
}
if (!isSelectionMode) {
interaction.handlePressIn(event);
}
},
[interaction, isSelectionMode],
);
const rowSelected = isSelectionMode ? isBulkSelected : selected;
const accessibilityState = useMemo(
() => (isSelectionMode ? { checked: isBulkSelected } : { selected }),
[isSelectionMode, isBulkSelected, selected],
);
const accessibilityState = useMemo(() => ({ selected }), [selected]);
const isEditingTitle = titleEditor !== null;
const disableDrag = isEditingTitle || isSelectionMode;
return (
<SidebarWorkspaceRowFrame
workspace={workspace}
isDragging={isDragging}
isEditingTitle={isEditingTitle}
isSelectionMode={isSelectionMode}
>
{({ isHovered, contextMenuOpen, onContextMenuOpenChange, hoverHandlers }) => {
const isDesktop = !isTouchPlatform;
const serviceSummary = isDesktop ? selectWorkspaceServiceSummary(workspace.scripts) : null;
const workspaceRowStyle = getProjectWorkspaceRowStyle({
isDragging,
selected: rowSelected,
isHovered,
});
const backdrop = getSidebarRowBackdrop({
isDragging,
isHighlighted,
selected: rowSelected,
isHovered,
});
const workspaceRowStyle = getProjectWorkspaceRowStyle({ isDragging, selected, isHovered });
const backdrop = getSidebarRowBackdrop({ isDragging, isHighlighted, selected, isHovered });
return (
<View
{...dragAttributes}
{...(disableDrag ? null : dragHandleProps?.listeners)}
{...(isEditingTitle ? null : dragHandleProps?.listeners)}
ref={dragHandleProps?.setActivatorNodeRef as unknown as Ref<View>}
style={styles.workspaceRowContainer}
{...hoverHandlers}
@@ -1196,7 +1131,6 @@ function WorkspaceRowInner({
onRename={onRename}
onMarkAsRead={onMarkAsRead}
onMarkAsUnread={onMarkAsUnread}
onSelectWorkspace={onSelectWorkspace}
onArchive={onArchive}
archiveLabel={archiveLabel}
archiveStatus={archiveStatus}
@@ -1206,18 +1140,17 @@ function WorkspaceRowInner({
onTogglePin={onTogglePin}
openInFileManagerPath={workspace.workspaceDirectory}
disabled={isArchiving}
enabled={!isEditingTitle && !isSelectionMode}
aria-selected={isSelectionMode ? undefined : selected}
aria-checked={isSelectionMode ? isBulkSelected : undefined}
accessibilityRole={isSelectionMode ? "checkbox" : "button"}
enabled={!isEditingTitle}
aria-selected={selected}
accessibilityRole="button"
accessibilityState={accessibilityState}
style={workspaceRowStyle}
highlightStyle={isEditingTitle ? undefined : styles.workspaceRowPressed}
onHighlightChange={setIsHighlighted}
onPressIn={isEditingTitle ? undefined : handleRowPressIn}
onTouchMove={disableDrag ? undefined : interaction.handleTouchMove}
onPressOut={disableDrag ? undefined : interaction.handlePressOut}
onPress={isEditingTitle ? undefined : handleRowPress}
onPressIn={isEditingTitle ? undefined : interaction.handlePressIn}
onTouchMove={isEditingTitle ? undefined : interaction.handleTouchMove}
onPressOut={isEditingTitle ? undefined : interaction.handlePressOut}
onPress={isEditingTitle ? undefined : handlePress}
testID={`sidebar-workspace-row-${workspace.workspaceKey}`}
>
<SidebarWorkspaceRowContent
@@ -1230,8 +1163,6 @@ function WorkspaceRowInner({
isHovered={isHovered}
isLoading={isArchiving || isCreating}
isCreating={isCreating}
isSelectionMode={isSelectionMode}
isBulkSelected={isBulkSelected}
shortcutNumber={shortcutNumber}
showShortcutBadge={showShortcutBadge}
reserveIdleStatusIndicatorSpace={reserveIdleStatusIndicatorSpace}
@@ -1243,14 +1174,12 @@ function WorkspaceRowInner({
isHovered={isHovered}
isTouchPlatform={isTouchPlatform}
isCreating={isCreating}
isSelectionMode={isSelectionMode}
showShortcutBadge={showShortcutBadge}
shortcutNumber={shortcutNumber}
archiveLabel={archiveLabel}
archiveStatus={archiveStatus}
archivePendingLabel={archivePendingLabel}
archiveShortcutKeys={archiveShortcutKeys}
onSelectWorkspace={onSelectWorkspace}
onArchive={onArchive}
onCopyBranchName={onCopyBranchName}
onCopyPath={onCopyPath}
@@ -1336,10 +1265,6 @@ function WorkspaceRowWithMenu({
archiveController.archive();
}, [archiveController, isArchiving]);
const handleSelectWorkspace = useCallback(() => {
useSidebarSelectionStore.getState().enter(workspace.workspaceKey);
}, [workspace.workspaceKey]);
const clipboard = useWorkspaceClipboardActions();
const handleCopyPath = useCallback(() => {
clipboard.copyPath(workspace);
@@ -1392,7 +1317,6 @@ function WorkspaceRowWithMenu({
archiveLabel={t("sidebar.workspace.actions.archive")}
archiveStatus={isArchiving ? "pending" : "idle"}
archivePendingLabel={t("sidebar.workspace.actions.archiving")}
onSelectWorkspace={handleSelectWorkspace}
onArchive={handleArchive}
onCopyBranchName={canCopyBranchName ? handleCopyBranchName : undefined}
onCopyPath={handleCopyPath}
@@ -2275,62 +2199,6 @@ function ProjectModeList({
selection: selectionEnabled ? activeWorkspaceSelection : null,
expanded: pinnedChatsExpanded,
});
const visibleOrderInputRef = useRef({
pinnedCollapsed,
leadingPinnedChat,
visiblePinnedChats,
unpinnedProjects,
collapsedProjectKeys,
expandedProjectKeys,
selectionEnabled,
activeWorkspaceSelection,
workspaceEntriesByKey,
});
visibleOrderInputRef.current = {
pinnedCollapsed,
leadingPinnedChat,
visiblePinnedChats,
unpinnedProjects,
collapsedProjectKeys,
expandedProjectKeys,
selectionEnabled,
activeWorkspaceSelection,
workspaceEntriesByKey,
};
useEffect(() => {
return registerSidebarVisibleWorkspaceKeysReader(() => {
const current = visibleOrderInputRef.current;
const keys: string[] = [];
if (!current.pinnedCollapsed) {
if (current.leadingPinnedChat) keys.push(current.leadingPinnedChat.workspaceKey);
for (const item of current.visiblePinnedChats) {
keys.push(item.workspaceKey);
}
}
const policy = createWorkspaceVisibilityPolicy<SidebarWorkspacePlacement>(
current.workspaceEntriesByKey,
);
const selection = current.selectionEnabled ? current.activeWorkspaceSelection : null;
for (const project of current.unpinnedProjects) {
if (current.collapsedProjectKeys.has(project.viewKey) || project.workspaces.length === 0) {
continue;
}
const { leadingItem, visibleItems } = selectSidebarGroupVisibility({
items: project.workspaces,
selection,
expanded: current.expandedProjectKeys.has(project.viewKey),
policy,
});
if (leadingItem) keys.push(leadingItem.workspaceKey);
for (const item of visibleItems) {
keys.push(item.workspaceKey);
}
}
return keys;
});
}, []);
const nativeScrollGestureProps = useMemo(
() =>
parentGestureRef
@@ -3,16 +3,14 @@ import { PressHighlight as Pressable } from "@/components/ui/press-highlight";
import {
memo,
useCallback,
useEffect,
useMemo,
useRef,
useState,
type MutableRefObject,
type ReactNode,
type Ref,
} from "react";
import { useTranslation } from "react-i18next";
import { View, Text, ScrollView, type GestureResponderEvent } from "react-native";
import { View, Text, ScrollView } from "react-native";
import { NestableScrollContainer } from "react-native-draggable-flatlist";
import type { GestureType } from "react-native-gesture-handler";
import { navigateToWorkspace } from "@/stores/navigation-active-workspace-store";
@@ -71,15 +69,7 @@ import {
} from "@/components/sidebar/sidebar-workspace-menu";
import { SidebarSectionHeader } from "@/components/sidebar/sidebar-section-header";
import { SidebarGroupToggleRow } from "@/components/sidebar/sidebar-group-toggle-row";
import { selectSidebarGroupVisibility } from "@/components/sidebar/sidebar-group-visibility";
import { useLimitedSidebarGroup } from "@/components/sidebar/use-limited-sidebar-group";
import {
isShiftPressEvent,
registerSidebarVisibleWorkspaceKeysReader,
useIsSidebarSelectionMode,
useIsWorkspaceBulkSelected,
useSidebarSelectionStore,
} from "@/sidebar-selection";
import type { ToggleSidebarWorkspacePin } from "@/hooks/use-sidebar-workspace-pin";
import { DraggableList, type DraggableRenderItemInfo } from "@/components/draggable-list";
import type { DraggableListDragHandleProps } from "@/components/draggable-list.types";
@@ -164,14 +154,6 @@ export function SidebarStatusWorkspaceList({
() => setPinnedWorkspacesExpanded((current) => !current),
[],
);
const [expandedGroupKeys, setExpandedGroupKeys] = useState<ReadonlySet<string>>(() => new Set());
const toggleGroupWorkspacesExpanded = useCallback((groupKey: string) => {
setExpandedGroupKeys((current) => {
const next = new Set(current);
if (!next.delete(groupKey)) next.add(groupKey);
return next;
});
}, []);
const {
leadingItem: leadingPinnedWorkspace,
visibleItems: visiblePinnedWorkspaces,
@@ -182,56 +164,6 @@ export function SidebarStatusWorkspaceList({
expanded: pinnedWorkspacesExpanded,
});
const visibleOrderInputRef = useRef({
pinnedCollapsed,
leadingPinnedWorkspace,
visiblePinnedWorkspaces,
groups,
collapsedWorkspaceGroupKeys,
expandedGroupKeys,
activeWorkspaceSelection,
});
visibleOrderInputRef.current = {
pinnedCollapsed,
leadingPinnedWorkspace,
visiblePinnedWorkspaces,
groups,
collapsedWorkspaceGroupKeys,
expandedGroupKeys,
activeWorkspaceSelection,
};
useEffect(() => {
return registerSidebarVisibleWorkspaceKeysReader(() => {
const current = visibleOrderInputRef.current;
const keys: string[] = [];
if (!current.pinnedCollapsed) {
if (current.leadingPinnedWorkspace) {
keys.push(current.leadingPinnedWorkspace.workspaceKey);
}
for (const item of current.visiblePinnedWorkspaces) {
keys.push(item.workspaceKey);
}
}
for (const group of current.groups) {
if (current.collapsedWorkspaceGroupKeys.has(group.key) || group.rows.length === 0) {
continue;
}
const { leadingItem, visibleItems } = selectSidebarGroupVisibility({
items: group.rows,
selection: current.activeWorkspaceSelection,
expanded: current.expandedGroupKeys.has(group.key),
policy: STATUS_GROUP_VISIBILITY,
});
if (leadingItem) keys.push(leadingItem.workspaceKey);
for (const item of visibleItems) {
keys.push(item.workspaceKey);
}
}
return keys;
});
}, []);
const statusShortcutIndex = showShortcutBadges
? shortcutIndexByWorkspaceKey
: EMPTY_SHORTCUT_INDEX;
@@ -330,8 +262,6 @@ export function SidebarStatusWorkspaceList({
<StatusGroupList
groups={groups}
collapsedWorkspaceGroupKeys={collapsedWorkspaceGroupKeys}
expandedGroupKeys={expandedGroupKeys}
onToggleGroupWorkspacesExpanded={toggleGroupWorkspacesExpanded}
projectIconByProjectViewKey={projectIconByProjectViewKey}
shortcutIndex={statusShortcutIndex}
showShortcutBadges={showShortcutBadges}
@@ -373,8 +303,6 @@ export function SidebarStatusWorkspaceList({
function StatusGroupList({
groups,
collapsedWorkspaceGroupKeys,
expandedGroupKeys,
onToggleGroupWorkspacesExpanded,
projectIconByProjectViewKey,
shortcutIndex,
showShortcutBadges,
@@ -385,8 +313,6 @@ function StatusGroupList({
}: {
groups: SidebarWorkspaceGroup[];
collapsedWorkspaceGroupKeys: ReadonlySet<string>;
expandedGroupKeys: ReadonlySet<string>;
onToggleGroupWorkspacesExpanded: (groupKey: string) => void;
projectIconByProjectViewKey: ReadonlyMap<string, string | null>;
shortcutIndex: Map<string, number>;
showShortcutBadges: boolean;
@@ -402,8 +328,6 @@ function StatusGroupList({
key={group.key}
group={group}
collapsed={collapsedWorkspaceGroupKeys.has(group.key)}
workspacesExpanded={expandedGroupKeys.has(group.key)}
onToggleWorkspacesExpanded={onToggleGroupWorkspacesExpanded}
projectIconByProjectViewKey={projectIconByProjectViewKey}
shortcutIndex={shortcutIndex}
showShortcutBadges={showShortcutBadges}
@@ -425,8 +349,6 @@ const STATUS_GROUP_VISIBILITY = {
function StatusGroupRows({
group,
collapsed,
workspacesExpanded,
onToggleWorkspacesExpanded,
projectIconByProjectViewKey,
shortcutIndex,
showShortcutBadges,
@@ -437,8 +359,6 @@ function StatusGroupRows({
}: {
group: SidebarWorkspaceGroup;
collapsed: boolean;
workspacesExpanded: boolean;
onToggleWorkspacesExpanded: (groupKey: string) => void;
projectIconByProjectViewKey: ReadonlyMap<string, string | null>;
shortcutIndex: Map<string, number>;
showShortcutBadges: boolean;
@@ -448,9 +368,10 @@ function StatusGroupRows({
onToggleWorkspacePin: ToggleSidebarWorkspacePin;
}) {
const activeWorkspaceSelection = useActiveWorkspaceSelection();
const [workspacesExpanded, setWorkspacesExpanded] = useState(false);
const toggleWorkspacesExpanded = useCallback(
() => onToggleWorkspacesExpanded(group.key),
[group.key, onToggleWorkspacesExpanded],
() => setWorkspacesExpanded((current) => !current),
[],
);
const {
leadingItem: leadingWorkspace,
@@ -748,10 +669,6 @@ function StatusWorkspaceRowWithMenu({
archiveController.archive();
}, [archiveController, isArchiving]);
const handleSelectWorkspace = useCallback(() => {
useSidebarSelectionStore.getState().enter(workspace.workspaceKey);
}, [workspace.workspaceKey]);
const clipboard = useWorkspaceClipboardActions();
const handleCopyPath = useCallback(() => {
clipboard.copyPath(workspace);
@@ -799,7 +716,6 @@ function StatusWorkspaceRowWithMenu({
archiveLabel={t("sidebar.workspace.actions.archive")}
archiveStatus={isArchiving ? "pending" : "idle"}
archivePendingLabel={t("sidebar.workspace.actions.archiving")}
onSelectWorkspace={handleSelectWorkspace}
onArchive={handleArchive}
onCopyBranchName={workspace.projectKind === "git" ? handleCopyBranchName : undefined}
onCopyPath={handleCopyPath}
@@ -834,7 +750,6 @@ interface StatusWorkspaceRowInnerProps {
archiveLabel?: string;
archiveStatus?: "idle" | "pending" | "success";
archivePendingLabel?: string;
onSelectWorkspace?: () => void;
onArchive?: () => void;
onCopyBranchName?: () => void;
onCopyPath?: () => void;
@@ -884,7 +799,6 @@ function StatusWorkspaceRowInnerContent({
archiveLabel,
archiveStatus = "idle",
archivePendingLabel,
onSelectWorkspace,
onArchive,
onCopyBranchName,
onCopyPath,
@@ -906,8 +820,6 @@ function StatusWorkspaceRowInnerContent({
const isCompact = useIsCompactFormFactor();
const isTouchPlatform = platformIsNative || isCompact;
const [isHighlighted, setIsHighlighted] = useState(false);
const isSelectionMode = useIsSidebarSelectionMode();
const isBulkSelected = useIsWorkspaceBulkSelected(workspace.workspaceKey);
const trailing = useSidebarWorkspaceTrailing();
const {
role: _dragRole,
@@ -919,59 +831,23 @@ function StatusWorkspaceRowInnerContent({
const isDesktop = !isTouchPlatform;
const serviceSummary = isDesktop ? selectWorkspaceServiceSummary(workspace.scripts) : null;
const rowSelected = isSelectionMode ? isBulkSelected : selected;
const accessibilityState = useMemo(
() => (isSelectionMode ? { checked: isBulkSelected } : { selected }),
[isSelectionMode, isBulkSelected, selected],
);
const accessibilityState = useMemo(() => ({ selected }), [selected]);
const isEditingTitle = titleEditor !== null;
const disableDrag = isEditingTitle || isSelectionMode;
const didLongPressRef = dragInteraction?.didLongPressRef;
const startDragPress = dragInteraction?.handlePressIn;
const moveDragPress = dragInteraction?.handleTouchMove;
const endDragPress = dragInteraction?.handlePressOut;
const { onPress: handleNavigatePress, feedback } = useWorkspaceRowPress({
const { onPress: handlePress, feedback } = useWorkspaceRowPress({
didLongPressRef,
onPress,
selected,
});
const handleRowPress = useCallback(
(event: GestureResponderEvent) => {
const shiftKey = isShiftPressEvent(event);
if (isSelectionMode || shiftKey) {
if (didLongPressRef?.current) {
didLongPressRef.current = false;
return;
}
event.preventDefault?.();
useSidebarSelectionStore.getState().pressWorkspace(workspace.workspaceKey, { shiftKey });
return;
}
handleNavigatePress();
},
[didLongPressRef, handleNavigatePress, isSelectionMode, workspace.workspaceKey],
);
const handleRowPressIn = useCallback(
(event: GestureResponderEvent) => {
if (isShiftPressEvent(event)) {
event.preventDefault?.();
return;
}
if (!isSelectionMode) {
startDragPress?.(event);
}
},
[isSelectionMode, startDragPress],
);
return (
<SidebarWorkspaceRowFrame
workspace={workspace}
isDragging={isDragging}
isEditingTitle={isEditingTitle}
isSelectionMode={isSelectionMode}
>
{({ isHovered, contextMenuOpen, onContextMenuOpenChange, hoverHandlers }) => {
const showShortcut = showShortcutBadge && shortcutNumber !== null;
@@ -989,24 +865,18 @@ function StatusWorkspaceRowInnerContent({
isHovered,
isTouchPlatform,
showShortcut,
isSelectionMode,
});
const workspaceRowStyle = getStatusWorkspaceRowStyle({
selected: rowSelected,
selected,
isHovered,
inStatusGroup,
isDragging,
});
const backdrop = getSidebarRowBackdrop({
isDragging,
isHighlighted,
selected: rowSelected,
isHovered,
});
const backdrop = getSidebarRowBackdrop({ isDragging, isHighlighted, selected, isHovered });
return (
<View
{...dragAttributes}
{...(disableDrag ? null : dragHandleProps?.listeners)}
{...(isEditingTitle ? null : dragHandleProps?.listeners)}
ref={dragHandleProps?.setActivatorNodeRef as unknown as Ref<View>}
style={styles.workspaceRowContainer}
{...hoverHandlers}
@@ -1024,7 +894,6 @@ function StatusWorkspaceRowInnerContent({
onRename={onRename}
onMarkAsRead={onMarkAsRead}
onMarkAsUnread={onMarkAsUnread}
onSelectWorkspace={onSelectWorkspace}
onArchive={onArchive}
archiveLabel={archiveLabel}
archiveStatus={archiveStatus}
@@ -1034,18 +903,16 @@ function StatusWorkspaceRowInnerContent({
onTogglePin={onTogglePin}
openInFileManagerPath={workspace.workspaceDirectory}
disabled={isArchiving}
enabled={!isEditingTitle && !isSelectionMode}
aria-selected={isSelectionMode ? undefined : selected}
aria-checked={isSelectionMode ? isBulkSelected : undefined}
accessibilityRole={isSelectionMode ? "checkbox" : "button"}
enabled={!isEditingTitle}
accessibilityRole="button"
accessibilityState={accessibilityState}
style={workspaceRowStyle}
highlightStyle={isEditingTitle ? undefined : styles.workspaceRowPressed}
onHighlightChange={setIsHighlighted}
onPressIn={isEditingTitle ? undefined : handleRowPressIn}
onTouchMove={disableDrag ? undefined : moveDragPress}
onPressOut={disableDrag ? undefined : endDragPress}
onPress={isEditingTitle ? undefined : handleRowPress}
onPressIn={isEditingTitle ? undefined : startDragPress}
onTouchMove={isEditingTitle ? undefined : moveDragPress}
onPressOut={isEditingTitle ? undefined : endDragPress}
onPress={isEditingTitle ? undefined : handlePress}
testID={`sidebar-workspace-row-${workspace.workspaceKey}`}
>
<SidebarWorkspaceRowContent
@@ -1057,8 +924,6 @@ function StatusWorkspaceRowInnerContent({
backdrop={backdrop}
isHovered={isHovered}
isLoading={isArchiving}
isSelectionMode={isSelectionMode}
isBulkSelected={isBulkSelected}
shortcutNumber={shortcutNumber}
showShortcutBadge={showShortcutBadge}
reserveIdleStatusIndicatorSpace={reserveIdleStatusIndicatorSpace}
@@ -1081,7 +946,6 @@ function StatusWorkspaceRowInnerContent({
onRename={onRename}
onMarkAsRead={onMarkAsRead}
onMarkAsUnread={onMarkAsUnread}
onSelectWorkspace={onSelectWorkspace}
onArchive={onArchive}
archiveLabel={archiveLabel}
archiveStatus={archiveStatus}
@@ -1115,7 +979,6 @@ function StatusWorkspaceActionSlot({
onRename,
onMarkAsRead,
onMarkAsUnread,
onSelectWorkspace,
onArchive,
archiveLabel,
archiveStatus,
@@ -1137,7 +1000,6 @@ function StatusWorkspaceActionSlot({
onRename?: () => void;
onMarkAsRead?: () => void;
onMarkAsUnread?: () => void;
onSelectWorkspace?: () => void;
onArchive?: () => void;
archiveLabel?: string;
archiveStatus?: "idle" | "pending" | "success";
@@ -1172,7 +1034,6 @@ function StatusWorkspaceActionSlot({
onRename={onRename}
onMarkAsRead={onMarkAsRead}
onMarkAsUnread={onMarkAsUnread}
onSelectWorkspace={onSelectWorkspace}
onArchive={onArchive}
archiveLabel={archiveLabel}
archiveStatus={archiveStatus}
@@ -5,7 +5,6 @@ import {
useEffect,
useMemo,
useRef,
useState,
type ReactNode,
} from "react";
import { View } from "react-native";
@@ -16,13 +15,7 @@ import Animated, {
type SharedValue,
} from "react-native-reanimated";
import { StyleSheet } from "react-native-unistyles";
import {
TOAST_FADE_MS,
ToastViewport,
useToastHost,
type ToastApi,
type ToastState,
} from "@/components/toast-host";
import { TOAST_FADE_MS, ToastViewport, useToastHost, type ToastApi } from "@/components/toast-host";
import { ToastApiProvider, useToast } from "@/contexts/toast-context";
interface SidebarToastCoverage {
@@ -32,10 +25,6 @@ interface SidebarToastCoverage {
}
const SidebarToastCoverageContext = createContext<SidebarToastCoverage | null>(null);
const SidebarPersistentToastContext = createContext<((toast: ToastState | null) => void) | null>(
null,
);
const SidebarAppToastContext = createContext<ToastApi | null>(null);
/**
* Shows toasts raised by the sidebar's list over its bottom edge, just above the footer.
@@ -47,10 +36,9 @@ const SidebarAppToastContext = createContext<ToastApi | null>(null);
export function SidebarToastRegion({ active, children }: { active: boolean; children: ReactNode }) {
const appToast = useToast();
const { api: sidebarToast, toast, dismiss } = useToastHost();
const [persistentToast, setPersistentToast] = useState<ToastState | null>(null);
const activeRef = useRef(active);
const coverageHeight = useSharedValue(0);
const toastVisible = toast !== null || persistentToast !== null;
const toastVisible = toast !== null;
useEffect(() => {
activeRef.current = active;
@@ -84,48 +72,19 @@ export function SidebarToastRegion({ active, children }: { active: boolean; chil
return (
<View style={styles.region}>
<ToastApiProvider api={api}>
<SidebarAppToastContext.Provider value={appToast}>
<SidebarPersistentToastContext.Provider value={setPersistentToast}>
<SidebarToastCoverageContext.Provider value={coverage}>
{children}
</SidebarToastCoverageContext.Provider>
</SidebarPersistentToastContext.Provider>
</SidebarAppToastContext.Provider>
<ToastViewport
toast={toast}
persistentToast={persistentToast}
onDismiss={dismiss}
placement="sidebar"
onBottomCoverageChange={handleCoverageChange}
/>
</ToastApiProvider>
<SidebarToastCoverageContext.Provider value={coverage}>
<ToastApiProvider api={api}>{children}</ToastApiProvider>
</SidebarToastCoverageContext.Provider>
<ToastViewport
toast={toast}
onDismiss={dismiss}
placement="sidebar"
onBottomCoverageChange={handleCoverageChange}
/>
</View>
);
}
/** Returns the enclosing app-level toast API so sidebar callers can report errors without displacing an active sidebar undo toast. */
export function useSidebarAppToast(): ToastApi {
const fallbackToast = useToast();
return useContext(SidebarAppToastContext) ?? fallbackToast;
}
/**
* Displays a persistent toast in the enclosing `SidebarToastRegion`, stacked below any active
* transient toast so controls stay reachable while a previous toast is up.
*/
export function useSidebarPersistentToast(toast: ToastState | null): void {
const setPersistentToast = useContext(SidebarPersistentToastContext);
useEffect(() => {
setPersistentToast?.(toast);
}, [setPersistentToast, toast]);
useEffect(() => {
return () => {
setPersistentToast?.(null);
};
}, [setPersistentToast]);
}
/**
* Space at the end of a sidebar list that matches the toast covering it, so the last row can
* scroll clear of the toast. It sits below every row, so growing it moves nothing. It shrinks
@@ -1,10 +1,9 @@
import { useMemo, type ComponentProps, type PropsWithChildren, type ReactNode } from "react";
import { useTranslation } from "react-i18next";
import type { GestureResponderEvent, PressableStateCallbackType } from "react-native";
import type { PressableStateCallbackType } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import {
Archive,
CheckSquare,
Circle,
CircleCheck,
Copy,
@@ -57,7 +56,6 @@ const foregroundMutedColorMapping = (theme: Theme) => ({
const ThemedMoreVertical = withUnistyles(MoreVertical);
const ThemedCopy = withUnistyles(Copy);
const ThemedArchive = withUnistyles(Archive);
const ThemedCheckSquare = withUnistyles(CheckSquare);
const ThemedCircle = withUnistyles(Circle);
const ThemedPencil = withUnistyles(Pencil);
const ThemedCircleCheck = withUnistyles(CircleCheck);
@@ -71,7 +69,6 @@ const markAsReadLeadingIcon = (
<ThemedCircleCheck size={14} uniProps={foregroundMutedColorMapping} />
);
const markAsUnreadLeadingIcon = <ThemedCircle size={14} uniProps={foregroundMutedColorMapping} />;
const selectLeadingIcon = <ThemedCheckSquare size={14} uniProps={foregroundMutedColorMapping} />;
const archiveLeadingIcon = <ThemedArchive size={14} uniProps={foregroundMutedColorMapping} />;
const pinLeadingIcon = <ThemedPin size={14} uniProps={foregroundMutedColorMapping} />;
const unpinLeadingIcon = <ThemedPinOff size={14} uniProps={foregroundMutedColorMapping} />;
@@ -127,7 +124,6 @@ export interface SidebarWorkspaceMenuProps {
onRename?: () => void;
onMarkAsRead?: () => void;
onMarkAsUnread?: () => void;
onSelectWorkspace?: () => void;
onArchive: () => void;
archiveLabel?: string;
archiveStatus?: "idle" | "pending" | "success";
@@ -176,7 +172,6 @@ function SidebarWorkspaceMenuItems({
onRename,
onMarkAsRead,
onMarkAsUnread,
onSelectWorkspace,
onArchive,
archiveLabel,
archiveStatus,
@@ -272,16 +267,6 @@ function SidebarWorkspaceMenuItems({
path={openInFileManagerPath}
testID={`sidebar-workspace-menu-open-folder-${workspaceKey}`}
/>
{onSelectWorkspace ? (
<WorkspaceMenuItem
surface={surface}
testID={`sidebar-workspace-menu-select-${workspaceKey}`}
leading={selectLeadingIcon}
onSelect={onSelectWorkspace}
>
{t("sidebar.workspace.actions.select")}
</WorkspaceMenuItem>
) : null}
{onArchive ? (
<WorkspaceMenuItem
surface={surface}
@@ -309,7 +294,6 @@ export function SidebarWorkspaceMenu({
onRename,
onMarkAsRead,
onMarkAsUnread,
onSelectWorkspace,
onArchive,
archiveLabel,
archiveStatus,
@@ -356,7 +340,6 @@ export function SidebarWorkspaceMenu({
onRename={onRename}
onMarkAsRead={onMarkAsRead}
onMarkAsUnread={onMarkAsUnread}
onSelectWorkspace={onSelectWorkspace}
onArchive={onArchive}
archiveLabel={archiveLabel}
archiveStatus={archiveStatus}
@@ -390,7 +373,6 @@ export function SidebarWorkspaceContextMenu({
onRename,
onMarkAsRead,
onMarkAsUnread,
onSelectWorkspace,
onArchive,
archiveLabel,
archiveStatus,
@@ -444,37 +426,11 @@ export function SidebarWorkspaceContextMenu({
[workspace],
);
const pages = useWorkspaceLabelMenuPages(workspaceTarget);
const checkboxSpaceKeyProps = useMemo(() => {
if (!isWeb || triggerProps.accessibilityRole !== "checkbox" || !triggerProps.onPress) {
return {};
}
const onPress = triggerProps.onPress;
return {
// React Native Web's Pressable activates Space only for role="button", not checkbox.
onKeyDown: (event: {
key?: string;
repeat?: boolean;
target?: unknown;
currentTarget?: unknown;
preventDefault?: () => void;
}) => {
if (triggerProps.disabled) return;
if (event.target !== event.currentTarget) return;
if (event.key === " " || event.key === "Spacebar") {
event.preventDefault?.();
if (!event.repeat) {
onPress(event as unknown as GestureResponderEvent);
}
}
},
};
}, [triggerProps.accessibilityRole, triggerProps.disabled, triggerProps.onPress]);
return (
<ContextMenu open={contextMenuOpen} onOpenChange={onContextMenuOpenChange}>
<ContextMenuTrigger
{...triggerProps}
{...checkboxSpaceKeyProps}
enabledOnMobile={false}
accessibilityLabel={accessibilityLabel ?? rowAccessibilityLabel}
highlightStyle={highlightStyle}
@@ -498,7 +454,6 @@ export function SidebarWorkspaceContextMenu({
onRename={onRename}
onMarkAsRead={onMarkAsRead}
onMarkAsUnread={onMarkAsUnread}
onSelectWorkspace={onSelectWorkspace}
onArchive={onArchive}
archiveLabel={archiveLabel}
archiveStatus={archiveStatus}
@@ -1,8 +1,7 @@
import { memo, useMemo, useCallback, useState, type ReactNode } from "react";
import { Text, View, type ViewStyle } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { Check, CircleAlert, Folder, FolderGit2, Monitor } from "lucide-react-native";
import { bySizing } from "@/components/ui/control-geometry";
import { CircleAlert, Folder, FolderGit2, Monitor } from "lucide-react-native";
import { ProjectStatusIndicator } from "@/components/sidebar/project-leading-visual";
import type { SidebarSurfaceBackdrop } from "@/styles/surface-backdrop";
import {
@@ -41,26 +40,19 @@ const needsInputColorMapping = (theme: Theme) => ({
color: theme.colors.surface0,
fill: getStatusDotColor({ theme, bucket: "needs_input" }) ?? undefined,
});
const checkedIconMapping = (theme: Theme) => ({
color: theme.colors.accentForeground,
});
const ThemedCheck = withUnistyles(Check);
const ThemedCircleAlert = withUnistyles(CircleAlert);
export function SidebarWorkspaceRowFrame({
workspace,
isDragging = false,
isEditingTitle = false,
isSelectionMode = false,
children,
}: {
workspace: SidebarWorkspaceEntry;
isDragging?: boolean;
/** Hover would fade the kebab in over the title being edited and open the hover card. */
isEditingTitle?: boolean;
/** Hover cards would cover neighbouring rows while the user clicks through a selection. */
isSelectionMode?: boolean;
children: (input: {
isHovered: boolean;
contextMenuOpen: boolean;
@@ -88,7 +80,7 @@ export function SidebarWorkspaceRowFrame({
workspace={workspace}
prHint={workspace.prHint}
isDragging={isDragging}
disabled={contextMenuOpen || isEditingTitle || isSelectionMode}
disabled={contextMenuOpen || isEditingTitle}
>
{children({
isHovered: isHovered && !contextMenuOpen && !isDragging && !isEditingTitle,
@@ -110,8 +102,6 @@ export const SidebarWorkspaceRowContent = memo(function SidebarWorkspaceRowConte
isHovered,
isLoading,
isCreating = false,
isSelectionMode = false,
isBulkSelected = false,
shortcutNumber = null,
showShortcutBadge = false,
reserveIdleStatusIndicatorSpace = true,
@@ -129,8 +119,6 @@ export const SidebarWorkspaceRowContent = memo(function SidebarWorkspaceRowConte
isHovered: boolean;
isLoading: boolean;
isCreating?: boolean;
isSelectionMode?: boolean;
isBulkSelected?: boolean;
shortcutNumber?: number | null;
showShortcutBadge?: boolean;
/** Keep the empty leading slot when the workspace has no active status. */
@@ -149,44 +137,33 @@ export const SidebarWorkspaceRowContent = memo(function SidebarWorkspaceRowConte
const workspaceBranchTextStyle = useMemo(
() => [
styles.workspaceBranchText,
(isHovered || isBulkSelected) && styles.workspaceBranchTextHovered,
isHovered && styles.workspaceBranchTextHovered,
isCreating && styles.workspaceBranchTextCreating,
],
[isHovered, isBulkSelected, isCreating],
[isHovered, isCreating],
);
let leadingVisual: ReactNode;
if (isSelectionMode) {
leadingVisual = (
<WorkspaceSelectionCheckbox checked={isBulkSelected} workspaceKey={workspace.workspaceKey} />
);
} else if (leadingProjectName) {
leadingVisual = (
<ProjectStatusIndicator
iconDataUri={leadingProjectIconDataUri}
displayName={leadingProjectName}
projectViewKey={workspace.projectViewKey}
statusBucket={workspace.statusBucket}
backdrop={backdrop}
loading={isLoading}
testID={`sidebar-row-project-icon-${workspace.workspaceKey}`}
/>
);
} else {
leadingVisual = (
<WorkspaceStatusIndicator
bucket={workspace.statusBucket}
workspaceKind={workspace.workspaceKind}
loading={isLoading}
reserveIdleSpace={reserveIdleStatusIndicatorSpace}
/>
);
}
return (
<View style={styles.workspaceRowContent}>
<View style={styles.workspaceRowMain}>
{leadingVisual}
{leadingProjectName ? (
<ProjectStatusIndicator
iconDataUri={leadingProjectIconDataUri}
displayName={leadingProjectName}
projectViewKey={workspace.projectViewKey}
statusBucket={workspace.statusBucket}
backdrop={backdrop}
loading={isLoading}
testID={`sidebar-row-project-icon-${workspace.workspaceKey}`}
/>
) : (
<WorkspaceStatusIndicator
bucket={workspace.statusBucket}
workspaceKind={workspace.workspaceKind}
loading={isLoading}
reserveIdleSpace={reserveIdleStatusIndicatorSpace}
/>
)}
<View style={styles.workspaceContentColumn}>
<View style={styles.workspaceTitleRow}>
{titleEditor ? (
@@ -214,7 +191,7 @@ export const SidebarWorkspaceRowContent = memo(function SidebarWorkspaceRowConte
/>
</View>
</View>
{!isSelectionMode && showShortcutBadge && shortcutNumber !== null ? (
{showShortcutBadge && shortcutNumber !== null ? (
<View style={styles.shortcutBadgeOverlay} pointerEvents="none">
<SidebarWorkspaceShortcutBadge number={shortcutNumber} />
</View>
@@ -223,22 +200,6 @@ export const SidebarWorkspaceRowContent = memo(function SidebarWorkspaceRowConte
);
});
function WorkspaceSelectionCheckbox({
checked,
workspaceKey,
}: {
checked: boolean;
workspaceKey: string;
}) {
return (
<View style={styles.workspaceStatusDot} testID={`sidebar-workspace-checkbox-${workspaceKey}`}>
<View style={checked ? styles.selectionCheckboxChecked : styles.selectionCheckbox}>
{checked ? <ThemedCheck size={11} strokeWidth={2.5} uniProps={checkedIconMapping} /> : null}
</View>
</View>
);
}
function WorkspaceStatusIndicator({
bucket,
workspaceKind,
@@ -421,7 +382,6 @@ export function resolveTrailingActionVisibility({
isHovered,
isTouchPlatform,
showShortcut,
isSelectionMode = false,
}: {
workspace: SidebarWorkspaceEntry;
trailing: SidebarWorkspaceTrailing;
@@ -429,7 +389,6 @@ export function resolveTrailingActionVisibility({
isHovered: boolean;
isTouchPlatform: boolean;
showShortcut: boolean;
isSelectionMode?: boolean;
}): {
trailingPresentation: SidebarWorkspaceTrailingPresentation;
showKebab: boolean;
@@ -439,11 +398,10 @@ export function resolveTrailingActionVisibility({
reserveSlotWidth: boolean;
} {
const hasTrailing = hasSidebarWorkspaceTrailing({ workspace, trailing });
const allowRowActions = hasArchiveAction && !isSelectionMode;
const showKebab = Boolean(allowRowActions && (isHovered || isTouchPlatform)) && !showShortcut;
const showKebab = Boolean(hasArchiveAction && (isHovered || isTouchPlatform)) && !showShortcut;
// Touch permanently replaces the stats with the menu. Only temporary shortcut hints
// conceal content while retaining its width, so desktop rows do not shift.
const hasContent = hasTrailing && !(allowRowActions && isTouchPlatform);
const hasContent = hasTrailing && !(hasArchiveAction && isTouchPlatform);
let trailingPresentation: SidebarWorkspaceTrailingPresentation = "absent";
if (hasContent) trailingPresentation = showShortcut ? "hidden" : "visible";
return {
@@ -456,12 +414,12 @@ export function resolveTrailingActionVisibility({
// row — over an unhovered one the gradient fades to the wrong color. That is also why
// touch, which shows the kebab without ever hovering, never gets one.
showScrim: showKebab && isHovered,
renderSlot: allowRowActions || hasTrailing,
renderSlot: hasArchiveAction || hasTrailing,
// The slot only holds width for something that permanently sits in it. Trailing content
// does; the kebab only does on touch, where there is no hover for it to appear on and so
// no scrim to let it overlay the title. Everywhere else the width goes back to the title
// and the kebab fades in over its tail.
reserveSlotWidth: hasContent || (allowRowActions && isTouchPlatform),
reserveSlotWidth: hasContent || (hasArchiveAction && isTouchPlatform),
};
}
@@ -578,25 +536,6 @@ const styles = StyleSheet.create((theme) => ({
alignItems: "center",
justifyContent: "center",
},
selectionCheckbox: {
width: bySizing({ touch: 18, pointer: 15 }),
height: bySizing({ touch: 18, pointer: 15 }),
borderRadius: theme.borderRadius.sm,
borderWidth: 1.5,
borderColor: theme.colors.borderAccent,
alignItems: "center",
justifyContent: "center",
},
selectionCheckboxChecked: {
width: bySizing({ touch: 18, pointer: 15 }),
height: bySizing({ touch: 18, pointer: 15 }),
borderRadius: theme.borderRadius.sm,
borderWidth: 1.5,
borderColor: theme.colors.accent,
backgroundColor: theme.colors.accent,
alignItems: "center",
justifyContent: "center",
},
statusDotOverlay: {
position: "absolute",
right: 0,
+15 -85
View File
@@ -16,7 +16,6 @@ import Animated, { FadeIn, FadeOut } from "react-native-reanimated";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { SPACING, type Theme } from "@/styles/theme";
import { CONTROL_HEIGHTS, mapLayout } from "@/components/ui/control-geometry";
import { useTranslation } from "react-i18next";
import { useIsCompactFormFactor } from "@/constants/layout";
import { isWeb } from "@/constants/platform";
@@ -29,16 +28,10 @@ import {
} from "@/constants/layout";
export type ToastVariant = "default" | "info" | "success" | "warning" | "error";
/**
* `action` tightens vertical and trailing insets around `size="sm"` pill controls and uses a
* concentric corner radius (`controlHeight / 2 + inset`) so buttons nest evenly in the shell.
*/
export type ToastLayout = "default" | "action";
export interface ToastShowOptions {
icon?: ReactNode;
variant?: ToastVariant;
layout?: ToastLayout;
durationMs?: number | null;
nativeAndroid?: boolean;
testID?: string;
@@ -52,7 +45,6 @@ export interface ToastState {
nativeMessage: string | null;
icon?: ReactNode;
variant: ToastVariant;
layout?: ToastLayout;
durationMs: number | null;
testID?: string;
onDismiss?: () => void;
@@ -81,11 +73,6 @@ const TOAST_MAX_WIDTH = 480;
/** How long a toast takes to fade in or out. */
export const TOAST_FADE_MS = 140;
const SIDEBAR_TOAST_INSET = SPACING[2];
const ACTION_TOAST_INSET = SPACING[1.5];
const ACTION_TOAST_RADIUS = mapLayout(
CONTROL_HEIGHTS.sm,
(height) => height / 2 + ACTION_TOAST_INSET,
);
const toastEntering = FadeIn.duration(TOAST_FADE_MS);
const toastExiting = FadeOut.duration(TOAST_FADE_MS);
const ThemedCheckCircle = withUnistyles(CheckCircle2);
@@ -149,7 +136,6 @@ export function useToastHost(): {
nativeMessage,
icon: options?.icon,
variant,
layout: options?.layout,
durationMs,
testID: options?.testID,
onDismiss: options?.onDismiss,
@@ -177,14 +163,11 @@ export function useToastHost(): {
export function ToastViewport({
toast,
persistentToast = null,
onDismiss,
placement = "app-shell",
onBottomCoverageChange,
}: {
toast: ToastState | null;
/** Sidebar placement: persistent bar (such as select mode) that stays visible below transient toasts. */
persistentToast?: ToastState | null;
/** Called with the ID of the toast that timed out. */
onDismiss: (id: number) => void;
placement?: ToastViewportPlacement;
@@ -249,10 +232,7 @@ export function ToastViewport({
const handleSidebarLayout = useCallback(
(event: LayoutChangeEvent) => {
const height = event.nativeEvent.layout.height;
if (height > 0) {
onBottomCoverageChange?.(height + SIDEBAR_TOAST_INSET);
}
onBottomCoverageChange?.(event.nativeEvent.layout.height + SIDEBAR_TOAST_INSET);
},
[onBottomCoverageChange],
);
@@ -263,41 +243,28 @@ export function ToastViewport({
const topOffset =
placement === "app-shell" ? insets.top + headerTopPadding + headerHeight : panelClearance;
if (placement === "sidebar") {
return (
<View
style={animatedStyles.sidebarContainer}
pointerEvents="box-none"
collapsable={false}
onLayout={handleSidebarLayout}
>
<SidebarToastSlot
toast={toast}
onPointerEnter={pauseDismiss}
onPointerLeave={resumeDismiss}
/>
<SidebarToastSlot
toast={persistentToast}
onPointerEnter={noopDismiss}
onPointerLeave={noopDismiss}
/>
</View>
);
}
// Keep the bottom anchor and its contents together while the native exit retains the view.
const content = toast ? (
<Animated.View
entering={toastEntering}
exiting={toastExiting}
style={[
animatedStyles.container,
{ top: topOffset + (placement === "app-shell" ? SPACING[2] : SPACING[3]) },
]}
style={
placement === "sidebar"
? animatedStyles.sidebarContainer
: [
animatedStyles.container,
{ top: topOffset + (placement === "app-shell" ? SPACING[2] : SPACING[3]) },
]
}
pointerEvents="box-none"
collapsable={false}
onLayout={placement === "sidebar" ? handleSidebarLayout : undefined}
>
<View style={styles.widthBoundary} pointerEvents="box-none" collapsable={false}>
<View
style={placement === "sidebar" ? styles.sidebarWidthBoundary : styles.widthBoundary}
pointerEvents="box-none"
collapsable={false}
>
<View
style={animatedStyles.surface}
testID={toast.testID ?? "app-toast"}
@@ -316,35 +283,6 @@ export function ToastViewport({
return placement === "panel" ? <FloatingHeaderOverlay>{content}</FloatingHeaderOverlay> : content;
}
function SidebarToastSlot({
toast,
onPointerEnter,
onPointerLeave,
}: {
toast: ToastState | null;
onPointerEnter: () => void;
onPointerLeave: () => void;
}) {
if (!toast) return null;
return (
<Animated.View
entering={toastEntering}
exiting={toastExiting}
style={styles.sidebarWidthBoundary}
pointerEvents="box-none"
collapsable={false}
>
<View
style={animatedStyles.surface}
testID={toast.testID ?? "app-toast"}
accessibilityRole="alert"
>
<ToastCard toast={toast} onPointerEnter={onPointerEnter} onPointerLeave={onPointerLeave} />
</View>
</Animated.View>
);
}
function ToastCard({
toast,
onPointerEnter,
@@ -372,7 +310,6 @@ function ToastCard({
onPointerLeave={onPointerLeave}
style={[
styles.toast,
toast.layout === "action" ? styles.toastAction : null,
toast.variant === "info" ? styles.toastInfo : null,
toast.variant === "warning" ? styles.toastWarning : null,
toast.variant === "error" ? styles.toastError : null,
@@ -407,7 +344,6 @@ const animatedStyles = NativeStyleSheet.create({
bottom: SIDEBAR_TOAST_INSET,
zIndex: OVERLAY_Z.toast,
alignItems: "center",
gap: SIDEBAR_TOAST_INSET,
},
surface: { alignSelf: "center", maxWidth: "100%" },
});
@@ -436,12 +372,6 @@ const styles = StyleSheet.create((theme) => ({
paddingHorizontal: theme.spacing[3],
...theme.shadow.md,
},
toastAction: {
borderRadius: ACTION_TOAST_RADIUS,
paddingVertical: theme.spacing[1.5],
paddingLeft: theme.spacing[3.5],
paddingRight: theme.spacing[1.5],
},
toastInfo: {
borderColor: theme.colors.palette.blue[300],
},
@@ -146,8 +146,6 @@ export interface ComboboxProps {
/** When true, selecting an option does not close the picker (multi-select mode). */
keepOpenOnSelect?: boolean;
anchorRef: React.RefObject<View | null>;
/** Where focus goes when the picker closes. Defaults to whatever had focus when it opened. */
restoreFocusRef?: React.RefObject<unknown>;
children?: ReactNode;
}
@@ -1439,7 +1437,6 @@ export function Combobox({
footer,
keepOpenOnSelect = false,
anchorRef,
restoreFocusRef,
children,
}: ComboboxProps): ReactElement | null {
const { t } = useTranslation();
@@ -1731,7 +1728,6 @@ export function Combobox({
layer: floatingLayer,
keys: ["Escape", "Enter", "ArrowUp", "ArrowDown"],
onKeyDown: (event) => (isDesktopKey(event.key) ? handleDesktopKey(event.key, event) : false),
restoreFocusRef,
});
const effectiveSearchPlaceholder = searchPlaceholder ?? resolvedPlaceholder;
@@ -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;
@@ -146,41 +146,3 @@ export async function confirmRiskyWorktreeArchive(
destructive: true,
});
}
export async function confirmRiskyBulkWorktreeArchive(
input: {
totalCount: number;
riskyWorkspaces: readonly WorktreeArchiveConfirmationInput[];
},
labels: WorktreeArchiveWarningLabels = DEFAULT_WORKTREE_ARCHIVE_WARNING_LABELS,
): Promise<boolean> {
const lines: string[] = [];
let singleRisky: WorktreeArchiveConfirmationInput | null = null;
for (const workspace of input.riskyWorkspaces) {
const reasons = buildWorktreeArchiveRiskReasons(workspace, labels);
if (reasons.length === 0) continue;
singleRisky = workspace;
lines.push(
i18n.t("workspace.git.actions.archiveWarning.bulkWorkspaceReason", {
workspaceName: workspace.workspaceName,
reason: reasons.join(", "),
}),
);
}
if (lines.length === 0) {
return true;
}
if (input.totalCount === 1 && singleRisky) {
return await confirmRiskyWorktreeArchive(singleRisky, labels);
}
return await confirmDialog({
title: i18n.t("workspace.git.actions.archiveWarning.bulkTitle", {
count: input.totalCount,
}),
message: lines.join("\n"),
confirmLabel: labels.confirm,
cancelLabel: labels.cancel,
destructive: true,
});
}
@@ -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"),
},
],
+2 -9
View File
@@ -741,6 +741,8 @@ export const ar: TranslationResources = {
resumeCommandUnavailable: "أمر الاستئناف غير متوفر",
reloadingAgent: "وكيل إعادة التحميل...",
reloadedAgent: "وكيل إعادة تحميل",
reloadedAgentHistoryDiverged:
"تمت إعادة تحميل الوكيل، لكن سجل المزوّد لا يطابق هذه المحادثة، لذا لم تتم مزامنته",
failedToReloadAgent: "فشل في إعادة تحميل الوكيل",
failedToCloseAgent: "فشل في إغلاق الوكيل",
},
@@ -960,8 +962,6 @@ export const ar: TranslationResources = {
},
archiveWarning: {
title: 'الأرشيف "{{workspaceName}}"؟',
bulkTitle: "أرشفة {{count}} مساحات عمل؟",
bulkWorkspaceReason: "{{workspaceName}}: {{reason}}",
confirm: "أرشيف",
cancel: "يلغي",
uncommittedChanges: "تغييرات غير ملتزم بها",
@@ -1371,7 +1371,6 @@ export const ar: TranslationResources = {
rename: "إعادة تسمية مساحة العمل",
pin: "تثبيت في الأعلى",
unpin: "إلغاء التثبيت",
select: "تحديد",
archive: "أرشيف",
archiveWorkspace: "أرشفة مساحة العمل",
hideFromSidebar: "إخفاء من الشريط الجانبي",
@@ -1390,10 +1389,6 @@ export const ar: TranslationResources = {
submit: "إعادة تسمية",
invalidBranchName: "اسم الفرع غير صالح",
},
selection: {
count: "تم تحديد {{count}}",
exit: "إنهاء التحديد",
},
toasts: {
workspacePathUnavailable: "مسار Workspace غير متوفر",
pathCopied: "تم نسخ المسار",
@@ -1401,9 +1396,7 @@ export const ar: TranslationResources = {
hostDisconnected: "Host غير متصل",
hideFailed: "فشل في إخفاء مساحة العمل",
archiveFailed: "فشل في أرشفة مساحة العمل",
archiveMultipleFailed: "فشل في أرشفة {{count}} مساحات عمل",
archived: "تمت أرشفة مساحة العمل",
archivedCount: "تمت أرشفة {{count}} مساحات عمل",
undoArchive: "تراجع",
undoArchiveFailed: "تعذّر التراجع عن الأرشفة",
},
+2 -9
View File
@@ -740,6 +740,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",
},
@@ -971,8 +973,6 @@ export const en = {
},
archiveWarning: {
title: 'Archive "{{workspaceName}}"?',
bulkTitle: "Archive {{count}} workspaces?",
bulkWorkspaceReason: "{{workspaceName}}: {{reason}}",
confirm: "Archive",
cancel: "Cancel",
uncommittedChanges: "Uncommitted changes",
@@ -1382,7 +1382,6 @@ export const en = {
rename: "Rename workspace",
pin: "Pin to top",
unpin: "Unpin",
select: "Select",
archive: "Archive",
archiveWorkspace: "Archive workspace",
hideFromSidebar: "Hide from sidebar",
@@ -1401,10 +1400,6 @@ export const en = {
submit: "Rename",
invalidBranchName: "Invalid branch name",
},
selection: {
count: "{{count}} selected",
exit: "Exit selection",
},
toasts: {
workspacePathUnavailable: "Workspace path not available",
pathCopied: "Path copied",
@@ -1412,9 +1407,7 @@ export const en = {
hostDisconnected: "Host is not connected",
hideFailed: "Failed to hide workspace",
archiveFailed: "Failed to archive workspace",
archiveMultipleFailed: "Failed to archive {{count}} workspaces",
archived: "Workspace archived",
archivedCount: "{{count}} workspaces archived",
undoArchive: "Undo",
undoArchiveFailed: "Couldn't undo the archive",
},
+2 -9
View File
@@ -748,6 +748,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",
},
@@ -994,8 +996,6 @@ export const es: TranslationResources = {
},
archiveWarning: {
title: '¿Archivo "{{workspaceName}}"?',
bulkTitle: "¿Archivar {{count}} espacios de trabajo?",
bulkWorkspaceReason: "{{workspaceName}}: {{reason}}",
confirm: "Archivo",
cancel: "Cancelar",
uncommittedChanges: "Cambios no confirmados",
@@ -1408,7 +1408,6 @@ export const es: TranslationResources = {
rename: "Cambiar nombre del espacio de trabajo",
pin: "Anclar arriba",
unpin: "Desanclar",
select: "Seleccionar",
archive: "Archivo",
archiveWorkspace: "Archivar espacio de trabajo",
hideFromSidebar: "Ocultar de la barra lateral",
@@ -1427,10 +1426,6 @@ export const es: TranslationResources = {
submit: "Rebautizar",
invalidBranchName: "Nombre de sucursal no válido",
},
selection: {
count: "{{count}} seleccionados",
exit: "Salir de la selección",
},
toasts: {
workspacePathUnavailable: "RutaWorkspaceno disponible",
pathCopied: "Ruta copiada",
@@ -1438,9 +1433,7 @@ export const es: TranslationResources = {
hostDisconnected: "Hostno está conectado",
hideFailed: "No se pudo ocultar el espacio de trabajo",
archiveFailed: "No se pudo archivar el espacio de trabajo",
archiveMultipleFailed: "No se pudieron archivar {{count}} espacios de trabajo",
archived: "Espacio de trabajo archivado",
archivedCount: "{{count}} espacios de trabajo archivados",
undoArchive: "Deshacer",
undoArchiveFailed: "No se pudo deshacer el archivado",
},
+2 -9
View File
@@ -748,6 +748,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",
},
@@ -986,8 +988,6 @@ export const fr: TranslationResources = {
},
archiveWarning: {
title: "Archiver « {{workspaceName}} » ?",
bulkTitle: "Archiver {{count}} espaces de travail ?",
bulkWorkspaceReason: "{{workspaceName}} : {{reason}}",
confirm: "Archiver",
cancel: "Annuler",
uncommittedChanges: "Modifications non commitées",
@@ -1401,7 +1401,6 @@ export const fr: TranslationResources = {
rename: "Renommer l’espace de travail",
pin: "Épingler en haut",
unpin: "Désépingler",
select: "Sélectionner",
archive: "Archiver",
archiveWorkspace: "Archiver l’espace de travail",
hideFromSidebar: "Masquer de la barre latérale",
@@ -1420,10 +1419,6 @@ export const fr: TranslationResources = {
submit: "Renommer",
invalidBranchName: "Nom de branche invalide",
},
selection: {
count: "{{count}} sélectionnés",
exit: "Quitter la sélection",
},
toasts: {
workspacePathUnavailable: "Chemin de l’espace de travail indisponible",
pathCopied: "Chemin copié",
@@ -1431,9 +1426,7 @@ export const fr: TranslationResources = {
hostDisconnected: "L’hôte n’est pas connecté",
hideFailed: "Impossible de masquer l’espace de travail",
archiveFailed: "Impossible d’archiver l’espace de travail",
archiveMultipleFailed: "Impossible d’archiver {{count}} espaces de travail",
archived: "Espace de travail archivé",
archivedCount: "{{count}} espaces de travail archivés",
undoArchive: "Annuler",
undoArchiveFailed: "Impossible d’annuler l’archivage",
},
+2 -9
View File
@@ -748,6 +748,8 @@ export const ja: TranslationResources = {
resumeCommandUnavailable: "再開コマンドが利用できません",
reloadingAgent: "エージェントを再読み込み中...",
reloadedAgent: "エージェントを再読み込みしました",
reloadedAgentHistoryDiverged:
"エージェントを再読み込みしましたが、プロバイダーの履歴がこのチャットと一致しないため同期しませんでした",
failedToReloadAgent: "エージェントの再読み込みに失敗しました",
failedToCloseAgent: "エージェントを閉じられませんでした",
},
@@ -974,8 +976,6 @@ export const ja: TranslationResources = {
},
archiveWarning: {
title: '"{{workspaceName}}"をアーカイブしますか?',
bulkTitle: "{{count}}件のワークスペースをアーカイブしますか?",
bulkWorkspaceReason: "{{workspaceName}}:{{reason}}",
confirm: "アーカイブ",
cancel: "キャンセル",
uncommittedChanges: "未コミットの変更",
@@ -1386,7 +1386,6 @@ export const ja: TranslationResources = {
rename: "ワークスペースの名前を変更",
pin: "上部に固定",
unpin: "固定解除",
select: "選択",
archive: "アーカイブ",
archiveWorkspace: "ワークスペースをアーカイブ",
hideFromSidebar: "サイドバーから非表示",
@@ -1405,10 +1404,6 @@ export const ja: TranslationResources = {
submit: "名前を変更",
invalidBranchName: "無効なブランチ名",
},
selection: {
count: "{{count}}件選択中",
exit: "選択を終了",
},
toasts: {
workspacePathUnavailable: "ワークスペースパスが利用できません",
pathCopied: "パスをコピーしました",
@@ -1416,9 +1411,7 @@ export const ja: TranslationResources = {
hostDisconnected: "ホストが接続されていません",
hideFailed: "ワークスペースの非表示に失敗しました",
archiveFailed: "ワークスペースのアーカイブに失敗しました",
archiveMultipleFailed: "{{count}}件のワークスペースのアーカイブに失敗しました",
archived: "ワークスペースをアーカイブしました",
archivedCount: "{{count}}件のワークスペースをアーカイブしました",
undoArchive: "元に戻す",
undoArchiveFailed: "アーカイブを元に戻せませんでした",
},
+2 -9
View File
@@ -743,6 +743,8 @@ export const ko: TranslationResources = {
resumeCommandUnavailable: "재개 명령을 사용할 수 없습니다",
reloadingAgent: "에이전트 다시 로드 중...",
reloadedAgent: "에이전트를 다시 로드했습니다",
reloadedAgentHistoryDiverged:
"에이전트를 다시 로드했지만 제공자 기록이 이 채팅과 일치하지 않아 동기화하지 않았습니다",
failedToReloadAgent: "에이전트를 다시 로드하지 못했습니다",
failedToCloseAgent: "에이전트를 닫지 못했습니다",
},
@@ -967,8 +969,6 @@ export const ko: TranslationResources = {
},
archiveWarning: {
title: '"{{workspaceName}}"를 보관하시겠습니까?',
bulkTitle: "워크스페이스 {{count}}개를 보관하시겠습니까?",
bulkWorkspaceReason: "{{workspaceName}}: {{reason}}",
confirm: "보관",
cancel: "취소",
uncommittedChanges: "커밋되지 않은 변경 사항",
@@ -1378,7 +1378,6 @@ export const ko: TranslationResources = {
rename: "워크스페이스 이름 변경",
pin: "상단에 고정",
unpin: "고정 해제",
select: "선택",
archive: "보관",
archiveWorkspace: "워크스페이스 보관",
hideFromSidebar: "사이드바에서 숨기기",
@@ -1397,10 +1396,6 @@ export const ko: TranslationResources = {
submit: "이름 변경",
invalidBranchName: "잘못된 브랜치 이름",
},
selection: {
count: "{{count}}개 선택됨",
exit: "선택 종료",
},
toasts: {
workspacePathUnavailable: "워크스페이스 경로를 사용할 수 없습니다",
pathCopied: "경로가 복사되었습니다",
@@ -1408,9 +1403,7 @@ export const ko: TranslationResources = {
hostDisconnected: "호스트가 연결되어 있지 않습니다",
hideFailed: "워크스페이스를 숨기지 못했습니다",
archiveFailed: "워크스페이스를 보관하지 못했습니다.",
archiveMultipleFailed: "워크스페이스 {{count}}개를 보관하지 못했습니다",
archived: "워크스페이스를 보관했습니다",
archivedCount: "워크스페이스 {{count}}개를 보관했습니다",
undoArchive: "실행 취소",
undoArchiveFailed: "보관을 취소하지 못했습니다",
},
+2 -9
View File
@@ -746,6 +746,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",
},
@@ -984,8 +986,6 @@ export const ptBR: TranslationResources = {
},
archiveWarning: {
title: 'Arquivar "{{workspaceName}}"?',
bulkTitle: "Arquivar {{count}} workspaces?",
bulkWorkspaceReason: "{{workspaceName}}: {{reason}}",
confirm: "Arquivar",
cancel: "Cancelar",
uncommittedChanges: "Alterações sem commit",
@@ -1398,7 +1398,6 @@ export const ptBR: TranslationResources = {
rename: "Renomear workspace",
pin: "Fixar no topo",
unpin: "Desafixar",
select: "Selecionar",
archive: "Arquivar",
archiveWorkspace: "Arquivar workspace",
hideFromSidebar: "Ocultar da barra lateral",
@@ -1417,10 +1416,6 @@ export const ptBR: TranslationResources = {
submit: "Renomear",
invalidBranchName: "Nome de branch inválido",
},
selection: {
count: "{{count}} selecionados",
exit: "Sair da seleção",
},
toasts: {
workspacePathUnavailable: "Caminho do workspace indisponível",
pathCopied: "Caminho copiado",
@@ -1428,9 +1423,7 @@ export const ptBR: TranslationResources = {
hostDisconnected: "Host não está conectado",
hideFailed: "Falha ao ocultar workspace",
archiveFailed: "Falha ao arquivar workspace",
archiveMultipleFailed: "Falha ao arquivar {{count}} workspaces",
archived: "Workspace arquivado",
archivedCount: "{{count}} workspaces arquivados",
undoArchive: "Desfazer",
undoArchiveFailed: "Não foi possível desfazer o arquivamento",
},
+2 -9
View File
@@ -749,6 +749,8 @@ export const ru: TranslationResources = {
resumeCommandUnavailable: "Команда возобновления недоступна",
reloadingAgent: "Перезагрузка агента...",
reloadedAgent: "Агент перезагружен",
reloadedAgentHistoryDiverged:
"Агент перезагружен, но история провайдера не совпадает с этим чатом, поэтому она не синхронизирована",
failedToReloadAgent: "Не удалось перезагрузить агента",
failedToCloseAgent: "Не удалось закрыть агента",
},
@@ -979,8 +981,6 @@ export const ru: TranslationResources = {
},
archiveWarning: {
title: "Архивировать «{{workspaceName}}»?",
bulkTitle: "Архивировать рабочие пространства ({{count}})?",
bulkWorkspaceReason: "{{workspaceName}}: {{reason}}",
confirm: "Архивировать",
cancel: "Отмена",
uncommittedChanges: "Незафиксированные изменения",
@@ -1391,7 +1391,6 @@ export const ru: TranslationResources = {
rename: "Переименовать рабочее пространство",
pin: "Закрепить вверху",
unpin: "Открепить",
select: "Выбрать",
archive: "Архивировать",
archiveWorkspace: "Архивировать рабочее пространство",
hideFromSidebar: "Скрыть на боковой панели",
@@ -1410,10 +1409,6 @@ export const ru: TranslationResources = {
submit: "Переименовать",
invalidBranchName: "Недопустимое имя ветки",
},
selection: {
count: "Выбрано: {{count}}",
exit: "Выйти из выбора",
},
toasts: {
workspacePathUnavailable: "Путь к рабочему пространству недоступен",
pathCopied: "Путь скопирован",
@@ -1421,9 +1416,7 @@ export const ru: TranslationResources = {
hostDisconnected: "Хост не подключён",
hideFailed: "Не удалось скрыть рабочее пространство",
archiveFailed: "Не удалось архивировать рабочее пространство",
archiveMultipleFailed: "Не удалось архивировать рабочие пространства ({{count}})",
archived: "Рабочее пространство архивировано",
archivedCount: "Архивировано рабочих пространств: {{count}}",
undoArchive: "Отменить",
undoArchiveFailed: "Не удалось отменить архивацию",
},
+2 -9
View File
@@ -741,6 +741,8 @@ export const zhCN: TranslationResources = {
resumeCommandUnavailable: "恢复命令不可用",
reloadingAgent: "正在重新加载 Agent...",
reloadedAgent: "已重新加载 Agent",
reloadedAgentHistoryDiverged:
"已重新加载 Agent,但提供方的历史记录与此对话不一致,因此未同步",
failedToReloadAgent: "重新加载 Agent 失败",
failedToCloseAgent: "关闭 Agent 失败",
},
@@ -952,8 +954,6 @@ export const zhCN: TranslationResources = {
},
archiveWarning: {
title: "归档「{{workspaceName}}」?",
bulkTitle: "归档 {{count}} 个工作区?",
bulkWorkspaceReason: "{{workspaceName}}:{{reason}}",
confirm: "归档",
cancel: "取消",
uncommittedChanges: "未 commit 的变更",
@@ -1361,7 +1361,6 @@ export const zhCN: TranslationResources = {
rename: "重命名 workspace",
pin: "置顶",
unpin: "取消置顶",
select: "选择",
archive: "归档",
archiveWorkspace: "归档工作区",
hideFromSidebar: "从侧边栏隐藏",
@@ -1379,10 +1378,6 @@ export const zhCN: TranslationResources = {
submit: "重命名",
invalidBranchName: "无效的分支名称",
},
selection: {
count: "已选 {{count}} 项",
exit: "退出选择",
},
toasts: {
workspacePathUnavailable: "Workspace 路径不可用",
pathCopied: "路径已复制",
@@ -1390,9 +1385,7 @@ export const zhCN: TranslationResources = {
hostDisconnected: "Host 未连接",
hideFailed: "隐藏 workspace 失败",
archiveFailed: "归档工作区失败",
archiveMultipleFailed: "归档 {{count}} 个工作区失败",
archived: "工作区已归档",
archivedCount: "已归档 {{count}} 个工作区",
undoArchive: "撤销",
undoArchiveFailed: "无法撤销归档",
},
-1
View File
@@ -14,4 +14,3 @@ export type { HardwareKeyboardEvent } from "./internal/sources/hardware";
export { usesDesktopBindings, supportsConfigurableComposerSendKeys } from "./internal/conventions";
export type { BrowserKeyboardPolicy } from "./internal/sources/electron-browser";
export { useHardwareKeyboardPresent } from "./availability";
export { isShiftKeyDown } from "./internal/shift-modifier";
@@ -9,10 +9,6 @@ export interface OverlayRegistration {
*/
keys: readonly string[];
onKeyDown(event: KeyboardInputEvent): boolean;
/**
* Where focus goes when the overlay closes: an element, or any handle with `focus()`. Defaults
* to whatever had focus when the overlay opened.
*/
restoreFocusRef?: RefObject<unknown>;
manageFocus?: boolean;
}
@@ -3,29 +3,12 @@ import { overlays, type OverlayEntry, type KeyboardInputEvent } from "./overlays
import type { OverlayRegistration } from "./overlay-contract";
type WebOverlayKeyHandler = (event: KeyboardInputEvent) => boolean;
/** A DOM element, or a component handle that knows how to focus itself (such as a text input). */
interface FocusTarget {
focus(): void;
}
function isFocusTarget(value: unknown): value is FocusTarget {
return (
typeof value === "object" &&
value !== null &&
typeof (value as Partial<FocusTarget>).focus === "function"
);
}
function canRestoreFocusTo(target: FocusTarget): boolean {
return !(target instanceof HTMLElement) || document.contains(target);
}
interface WebOverlayEntry {
getLayer: () => number;
getKeys: () => readonly string[];
getScope: () => HTMLElement | null;
getKeyHandler: () => WebOverlayKeyHandler;
restoreFocus: FocusTarget | null;
restoreFocus: HTMLElement | null;
manageFocus: boolean;
}
@@ -173,7 +156,7 @@ function addWebOverlay(entry: WebOverlayEntry): (options?: RemoveWebOverlayOptio
entry.manageFocus &&
options?.restoreFocus !== false &&
entry.restoreFocus &&
canRestoreFocusTo(entry.restoreFocus)
document.contains(entry.restoreFocus)
) {
entry.restoreFocus.focus();
}
@@ -198,7 +181,7 @@ export function useOverlayRegistration({
keysRef.current = keys;
const layerRef = useRef(layer);
const keyHandlerRef = useRef(onKeyDown);
const capturedRestoreFocusRef = useRef<FocusTarget | null>(null);
const capturedRestoreFocusRef = useRef<HTMLElement | null>(null);
const removeEntryRef = useRef<((options?: RemoveWebOverlayOptions) => void) | null>(null);
const detachedRemoveEntryRef = useRef<((options?: RemoveWebOverlayOptions) => void) | null>(null);
const registeredRef = useRef(false);
@@ -210,7 +193,7 @@ export function useOverlayRegistration({
keyHandlerRef.current = onKeyDown;
if (active && !wasActiveRef.current && typeof document !== "undefined") {
const requestedRestoreTarget = preferredRestoreFocusRef?.current;
if (isFocusTarget(requestedRestoreTarget)) {
if (requestedRestoreTarget instanceof HTMLElement) {
capturedRestoreFocusRef.current = requestedRestoreTarget;
} else {
capturedRestoreFocusRef.current =
@@ -1,51 +0,0 @@
export interface ShiftModifierKeyEvent {
key: string;
code?: string;
shiftKey: boolean;
}
export interface ShiftModifierTracker {
isDown(): boolean;
handleKeyDown(event: ShiftModifierKeyEvent): void;
handleKeyUp(event: ShiftModifierKeyEvent): void;
reset(): void;
}
/**
* Tracks whether a physical Shift key is currently held across DOM and native
* hardware keyboard streams so touch/pointer press handlers that omit
* `shiftKey` (native GestureResponderEvent, touch-synthesized clicks) can still
* observe Shift+tap and Shift+click.
*/
export function createShiftModifierTracker(): ShiftModifierTracker {
const pressedCodes = new Set<string>();
return {
isDown: () => pressedCodes.size > 0,
handleKeyDown(event) {
if (event.key === "Shift") {
pressedCodes.add(event.code || "Shift");
} else if (!event.shiftKey && pressedCodes.size > 0) {
pressedCodes.clear();
}
},
handleKeyUp(event) {
if (event.key === "Shift") {
pressedCodes.delete(event.code || "Shift");
if (!event.shiftKey) {
pressedCodes.clear();
}
} else if (!event.shiftKey && pressedCodes.size > 0) {
pressedCodes.clear();
}
},
reset() {
pressedCodes.clear();
},
};
}
export const shiftModifier = createShiftModifierTracker();
export function isShiftKeyDown(): boolean {
return shiftModifier.isDown();
}
@@ -1,4 +1,3 @@
import { AppState } from "react-native";
import type { KeyboardPolicyInput, KeyboardSourceHandlers } from "./contract";
import {
setHardwareKeyboardClaimedShortcuts,
@@ -8,14 +7,6 @@ import {
import { createHardwareKeyboardSource } from "./native";
const hardwareKeyboard = createHardwareKeyboardSource({
subscribe: subscribeHardwareKeyboard,
subscribeBlur: (onBlur) => {
const subscription = AppState.addEventListener("change", (nextState) => {
if (nextState !== "active") {
onBlur();
}
});
return () => subscription.remove();
},
setOverlayKeys: setHardwareKeyboardOverlayKeys,
setClaimedShortcuts: setHardwareKeyboardClaimedShortcuts,
});
@@ -9,7 +9,6 @@ import {
import type { ClaimedShortcut, HardwareKeyboardEvent } from "./hardware";
interface HardwareKeySource {
subscribe(handler: (event: HardwareKeyboardEvent) => void): () => void;
subscribeBlur?(handler: () => void): () => void;
setOverlayKeys(keys: readonly string[]): void;
setClaimedShortcuts(shortcuts: readonly ClaimedShortcut[]): void;
}
@@ -79,9 +78,7 @@ export function createHardwareKeyboardSource(source: HardwareKeySource) {
nativeKeyboardInput(event, focusSurfaces.resolve(handlers.commandCenterOpen())),
);
});
const unsubscribeBlur = source.subscribeBlur?.(() => handlers.blur()) ?? (() => {});
return () => {
unsubscribeBlur();
unsubscribeHardware();
unsubscribeFocus();
unsubscribeCommandCenter();
@@ -269,80 +269,4 @@ describe("hardware source adapter", () => {
expect(claimed).toEqual([]);
releaseFinal();
});
it("forwards native blur events and unsubscribes on detach", async () => {
const { createHardwareKeyboardSource } = await import("./internal/sources/native");
const blurListeners = new Set<() => void>();
let blurCalls = 0;
const detach = createHardwareKeyboardSource({
subscribe: () => () => {},
subscribeBlur(listener) {
blurListeners.add(listener);
return () => {
blurListeners.delete(listener);
};
},
setOverlayKeys() {},
setClaimedShortcuts() {},
}).attach({
keyDown() {},
keyUp() {},
blur() {
blurCalls += 1;
},
commandCenterOpen: () => false,
subscribeCommandCenter: () => () => {},
});
for (const listener of blurListeners) listener();
expect(blurCalls).toBe(1);
detach();
expect(blurListeners.size).toBe(0);
});
});
describe("shift modifier tracking", () => {
it("tracks left/right Shift holds, self-heals on non-shifted keys, and resets on blur", async () => {
const { createShiftModifierTracker } = await import("./internal/shift-modifier");
const tracker = createShiftModifierTracker();
expect(tracker.isDown()).toBe(false);
tracker.handleKeyDown({ key: "Shift", code: "ShiftLeft", shiftKey: true });
expect(tracker.isDown()).toBe(true);
tracker.handleKeyDown({ key: "Shift", code: "ShiftRight", shiftKey: true });
tracker.handleKeyUp({ key: "Shift", code: "ShiftLeft", shiftKey: true });
expect(tracker.isDown()).toBe(true);
tracker.handleKeyUp({ key: "Shift", code: "ShiftRight", shiftKey: false });
expect(tracker.isDown()).toBe(false);
// Self-heals if a Shift key-up was swallowed by the OS.
tracker.handleKeyDown({ key: "Shift", code: "ShiftLeft", shiftKey: true });
expect(tracker.isDown()).toBe(true);
tracker.handleKeyDown({ key: "a", code: "KeyA", shiftKey: false });
expect(tracker.isDown()).toBe(false);
// Clears on blur / backgrounding.
tracker.handleKeyDown({ key: "Shift", code: "ShiftLeft", shiftKey: true });
expect(tracker.isDown()).toBe(true);
tracker.reset();
expect(tracker.isDown()).toBe(false);
});
it("exposes live hardware Shift state through isShiftKeyDown", async () => {
const { shiftModifier } = await import("./internal/shift-modifier");
const { isShiftKeyDown } = await import("./index");
try {
shiftModifier.reset();
expect(isShiftKeyDown()).toBe(false);
shiftModifier.handleKeyDown({ key: "Shift", code: "ShiftLeft", shiftKey: true });
expect(isShiftKeyDown()).toBe(true);
shiftModifier.handleKeyUp({ key: "Shift", code: "ShiftLeft", shiftKey: false });
expect(isShiftKeyDown()).toBe(false);
} finally {
shiftModifier.reset();
}
});
});
+3 -16
View File
@@ -1,7 +1,6 @@
import { usesDesktopBindings } from "./internal/conventions";
import { createKeyboardPipeline } from "./internal/pipeline";
import { overlays } from "./internal/overlays";
import { shiftModifier } from "./internal/shift-modifier";
import { attachKeyboardSources, publishKeyboardPolicy } from "./internal/sources";
import type { KeyboardSourceInput } from "./internal/sources/contract";
import type { KeyboardInputEvent } from "./internal/overlays";
@@ -250,30 +249,19 @@ export function useKeyboardShortcuts({
[getContext, getBindings, isCapturing, dispatchMatch, beforeResolve, chordChanged],
);
const handleKeyDown = useStableEvent((input: KeyboardSourceInput) => {
shiftModifier.handleKeyDown(input.event);
return pipeline.keyDown(input);
});
const handleKeyUp = useStableEvent((event: KeyboardInputEvent) => {
shiftModifier.handleKeyUp(event);
const key = event.key ?? "";
if (key === badgeModifierKey) {
setBadgeModifierDown(false);
}
});
const handleBlur = useStableEvent(() => {
shiftModifier.reset();
resetModifiers();
});
useEffect(() => {
if (!enabled) return;
const detach = attachKeyboardSources({
keyDown: handleKeyDown,
keyDown: pipeline.keyDown,
keyUp: handleKeyUp,
blur: handleBlur,
blur: resetModifiers,
commandCenterOpen: () => useKeyboardShortcutsStore.getState().commandCenterOpen,
subscribeCommandCenter: (listener) =>
useKeyboardShortcutsStore.subscribe((state, previous) => {
@@ -282,8 +270,7 @@ export function useKeyboardShortcuts({
});
return () => {
detach();
shiftModifier.reset();
pipeline.dispose();
};
}, [enabled, pipeline, handleKeyDown, handleKeyUp, handleBlur]);
}, [enabled, pipeline, handleKeyUp, resetModifiers]);
}
@@ -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",
},
]);
@@ -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: [],
+12 -4
View File
@@ -255,6 +255,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;
@@ -3128,12 +3129,19 @@ export class HostRuntimeStore {
const directory = this.directorySyncByServer.get(serverId);
if (!directory) throw new Error(`Unknown host runtime for serverId ${serverId}`);
const owner = useSessionStore.getState().sessions[serverId]?.viewedTimelineSync;
const page = await directory.fetchTimeline(agentId, request);
if (owner && useSessionStore.getState().sessions[serverId]?.viewedTimelineSync === owner) {
// A page served before a rewind this client applied is asked for again. Seqs only grow within
// an epoch, so the next page includes the rewind unless another one landed meanwhile.
for (let attempt = 1; ; attempt += 1) {
const page = await directory.fetchTimeline(agentId, request);
if (!owner || useSessionStore.getState().sessions[serverId]?.viewedTimelineSync !== owner) {
return page;
}
owner.flushStreamAgent(agentId);
owner.applyTimelineResponse(page);
if (owner.applyTimelineResponse(page) === "applied") return page;
if (attempt === MAX_STALE_TIMELINE_PAGE_ATTEMPTS) {
throw new Error(`Timeline page for ${agentId} stayed behind a rewind`);
}
}
return page;
}
createViewedTimelineOwner(
@@ -189,7 +189,7 @@ function timelineItem(text = "Cached"): StreamItem {
id: "message-1",
text,
timestamp: new Date("2026-07-18T08:02:00.000Z"),
timelineCursor: { epoch: "epoch-1", seq: 12 },
timelineCursor: { epoch: "epoch-1", seq: 12, anchorSeq: 12 },
};
}
@@ -840,7 +840,7 @@ describe("ReplicaCache", () => {
version: 1,
data: { passed: 4, failed: 0 },
timestamp: new Date("2026-07-18T08:02:00.000Z"),
timelineCursor: { epoch: "epoch-1", seq: 12 },
timelineCursor: { epoch: "epoch-1", seq: 12, anchorSeq: 12 },
};
writer.commitTimeline(SERVER_ID, "agent-1", {
agentId: "agent-1",
@@ -885,6 +885,32 @@ describe("ReplicaCache", () => {
expect(await createCache(storage).readTimeline(SERVER_ID, "agent-1")).toBeUndefined();
});
it("keeps where each cached row started, and refetches a timeline cached without it", async () => {
const storage = new MemoryStorage();
const writer = createCache(storage);
const updatedAfterItStarted: StreamItem = {
...timelineItem(),
timelineCursor: { epoch: "epoch-1", seq: 12, anchorSeq: 9 },
};
writer.commitTimeline(SERVER_ID, "agent-1", { ...timeline(), items: [updatedAfterItStarted] });
await writer.flush();
expect((await createCache(storage).readTimeline(SERVER_ID, "agent-1"))?.items).toEqual([
updatedAfterItStarted,
]);
const row = requireTimelineRow(storage);
const payload = JSON.parse(row.payload) as {
items: Array<{ timelineCursor?: Record<string, unknown> }>;
};
delete payload.items[0]?.timelineCursor?.anchorSeq;
storage.rows.set(`${row.serverId}:${row.kind}:${row.id}`, {
...row,
payload: JSON.stringify(payload),
});
expect(await createCache(storage).readTimeline(SERVER_ID, "agent-1")).toBeUndefined();
});
it("refetches old cached Markdown fragments instead of offering them as whole messages", async () => {
const storage = new MemoryStorage();
const writer = createCache(storage);
@@ -1355,7 +1381,7 @@ it("retains semantic agent messages across disk-cache reconstruction", async ()
kind: "tool_call",
id: "delivery",
timestamp: new Date(1),
timelineCursor: { epoch: "epoch-1", seq: 12 },
timelineCursor: { epoch: "epoch-1", seq: 12, anchorSeq: 12 },
payload: {
source: "agent",
data: {
@@ -22,6 +22,7 @@ import {
isUnreconciledLocalUserMessage,
type AgentToolCallData,
type StreamItem,
type TimelinePosition,
} from "@/types/stream";
import type { UnsettledTurn } from "@/timeline/turn-liveness";
import { normalizeAgentSnapshot } from "@/utils/agent-snapshots";
@@ -82,7 +83,15 @@ const IsoDateSchema = z.iso.datetime();
const TimelinePositionSchema = z.strictObject({
epoch: z.string(),
seq: z.number().int().nonnegative(),
// COMPAT(timelineRewindOperations): absent on caches written before rows were anchored, added in
// v0.14.1, remove after 2027-05-10. Such a cache is not restored; the chat loads its tail instead.
anchorSeq: z.number().int().nonnegative().optional(),
});
type StoredTimelinePosition = z.infer<typeof TimelinePositionSchema>;
function isAnchored(position: StoredTimelinePosition | undefined): boolean {
return position === undefined || position.anchorSeq !== undefined;
}
const PluginTimelineDataSchema: z.ZodType<PluginTimelineData> = z.lazy(() =>
z.union([
z.null(),
@@ -423,6 +432,10 @@ function deserializeTimeline(stored: StoredTimeline | null): CachedTimeline | nu
if (!stored) {
return null;
}
// A rewind retires rows by anchor, so an unanchored row could not be retired.
if (!stored.items.every((item) => isAnchored(item.timelineCursor))) {
return null;
}
return {
agentId: stored.agentId,
items: stored.items.map(deserializeTimelineItem),
@@ -539,11 +552,20 @@ function serializeTimelineItem(item: StreamItem): StoredTimelineItem | null {
}
}
function anchoredPosition(position: StoredTimelinePosition | undefined): {
timelineCursor?: TimelinePosition;
} {
if (!position || position.anchorSeq === undefined) return {};
return {
timelineCursor: { epoch: position.epoch, seq: position.seq, anchorSeq: position.anchorSeq },
};
}
function deserializeTimelineItem(item: StoredTimelineItem): StreamItem {
if (item.kind === "plugin") {
return {
id: item.id,
...(item.timelineCursor ? { timelineCursor: item.timelineCursor } : {}),
...anchoredPosition(item.timelineCursor),
...(item.turnId ? { turnId: item.turnId } : {}),
timestamp: new Date(item.timestamp),
kind: item.kind,
@@ -562,7 +584,7 @@ function deserializeBuiltinTimelineItem(
): StreamItem {
const base = {
id: item.id,
...(item.timelineCursor ? { timelineCursor: item.timelineCursor } : {}),
...anchoredPosition(item.timelineCursor),
...(item.turnId ? { turnId: item.turnId } : {}),
timestamp: new Date(item.timestamp),
};
@@ -1578,18 +1578,9 @@ export function NewWorkspaceScreen({
? t("newWorkspace.refPicker.searching")
: t("newWorkspace.refPicker.noMatchingRefs");
// The prompt is where the user types; when a field's picker closes, focus returns there rather
// than to whatever had focus when the picker opened. A terminal profile that takes no prompt
// shows a read-only command preview, so its pickers keep returning focus to their field.
const composerFocusRef = useRef<{ focus: () => void } | null>(null);
const handleComposerFocusInput = useCallback((focus: () => void) => {
composerFocusRef.current = { focus };
}, []);
const formStack = useNewWorkspaceForm({
isCompact,
isPending,
restoreFocusRef: terminalTakesPrompt ? composerFocusRef : undefined,
pluginItems: (
<PluginNewWorkspaceItems serverId={selectedServerId} screen={pluginScreen} setup={setup} />
),
@@ -1691,7 +1682,6 @@ export function NewWorkspaceScreen({
clearDraft={noopClearDraft}
autoFocus={terminalTakesPrompt}
autoFocusKey={launchFocusKey}
onFocusInput={handleComposerFocusInput}
error={errorMessage}
/>
) : (
@@ -1722,7 +1712,6 @@ export function NewWorkspaceScreen({
clearDraft={handleClearDraft}
autoFocus
autoFocusKey={launchFocusKey}
onFocusInput={handleComposerFocusInput}
commandDraft={composerState?.commandDraft}
agentControls={agentControlsWithDisabled}
error={errorMessage}
@@ -67,11 +67,6 @@ export interface NewWorkspaceFormProps {
isPending: boolean;
/** Plugin fields, drawn after the base ref. */
pluginItems: ReactNode;
/**
* Where focus goes when a field's picker closes, so the user keeps typing the prompt. Without
* one, focus returns to the field that opened the picker.
*/
restoreFocusRef?: RefObject<unknown>;
project: PickerControl & {
options: ComboboxOption[];
projectByOptionId: Map<string, HostProjectListItem>;
@@ -378,17 +373,7 @@ function useRefPicker(base: NewWorkspaceFormProps["base"], isPending: boolean) {
*/
export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement {
const { t } = useTranslation();
const {
isCompact,
isPending,
pluginItems,
restoreFocusRef,
project,
host,
isolation,
base,
launch,
} = props;
const { isCompact, isPending, pluginItems, project, host, isolation, base, launch } = props;
const variant: FieldTriggerVariant = isCompact ? "field" : "badge";
const projectPicker = useProjectPicker(project, isPending);
const isolationPicker = useIsolationPicker({
@@ -447,7 +432,6 @@ export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement
open={host.openState}
onOpenChange={host.onOpenChange}
anchorRef={host.anchorRef}
restoreFocusRef={restoreFocusRef}
includeAddHost
onAddHost={host.onAddHost}
addHostTestID="new-workspace-host-picker-add-host"
@@ -541,7 +525,6 @@ export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement
desktopPlacement="bottom-start"
desktopMinWidth={360}
anchorRef={project.anchorRef}
restoreFocusRef={restoreFocusRef}
emptyText="No projects available."
renderOption={projectPicker.renderOption}
footer={projectPicker.footer}
@@ -556,7 +539,6 @@ export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement
searchable={false}
desktopPlacement="bottom-start"
anchorRef={isolation.anchorRef}
restoreFocusRef={restoreFocusRef}
desktopMinWidth={280}
renderOption={isolationPicker.renderOption}
/>
@@ -573,7 +555,6 @@ export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement
desktopPlacement="bottom-start"
desktopMinWidth={440}
anchorRef={base.anchorRef}
restoreFocusRef={restoreFocusRef}
emptyText={base.emptyText}
toolbar={refPicker.toolbar}
renderOption={refPicker.renderOption}
@@ -590,7 +571,6 @@ export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement
desktopPlacement="bottom-start"
desktopMinWidth={360}
anchorRef={worktreePicker.anchorRef}
restoreFocusRef={restoreFocusRef}
emptyText={t("newWorkspace.worktreePicker.empty")}
renderOption={worktreePicker.renderOption}
/>
@@ -2188,11 +2188,10 @@ function WorkspaceScreenContent({
toast.show(t("workspace.tabs.toasts.reloadingAgent"), { durationMs: null });
try {
await client.refreshAgent(agentId);
// Send the existing cursor so the server detects the new epoch and
// returns reset:true. Without a cursor, the server returns reset:false
// and the client takes the incremental path, where new-epoch rows are
// dropped against the stale cursor.
const refreshed = await client.refreshAgent(agentId);
// Send the existing cursor: Reload agent keeps the history, so the server
// returns only the rows it added. When the history was imported again
// under a new epoch, the cursor reads as stale and the server resets.
const sessionState = useSessionStore.getState().sessions[normalizedServerId];
const currentCursor = sessionState?.agentTimelineCursor.get(agentId);
await getHostRuntimeStore().fetchAgentTimeline(normalizedServerId, agentId, {
@@ -2201,7 +2200,13 @@ function WorkspaceScreenContent({
? { cursor: { epoch: currentCursor.epoch, seq: currentCursor.endSeq } }
: {}),
});
toast.show(t("workspace.tabs.toasts.reloadedAgent"), { variant: "success" });
if (refreshed.historyDiverged) {
toast.show(t("workspace.tabs.toasts.reloadedAgentHistoryDiverged"), {
variant: "warning",
});
} else {
toast.show(t("workspace.tabs.toasts.reloadedAgent"), { variant: "success" });
}
} catch (error) {
toast.error(
error instanceof Error ? error.message : t("workspace.tabs.toasts.failedToReloadAgent"),
@@ -1,8 +0,0 @@
export { isShiftPressEvent } from "./internal/selection-state";
export {
registerSidebarVisibleWorkspaceKeysReader,
useIsSidebarSelectionMode,
useIsWorkspaceBulkSelected,
useSidebarSelectionStore,
} from "./internal/selection-store";
export { SidebarSelectionHost } from "./internal/sidebar-selection-host";
@@ -1,280 +0,0 @@
import { describe, expect, it, vi } from "vitest";
import type { ToastApi } from "@/components/toast-host";
import type { SidebarWorkspaceEntry } from "@/hooks/use-sidebar-workspaces-list";
import {
archiveSelectedWorkspaces,
type BulkArchiveClient,
type BulkArchiveWorkspacesDeps,
} from "./archive-selected";
function makeEntry(
overrides: Partial<SidebarWorkspaceEntry> & { workspaceId: string },
): SidebarWorkspaceEntry {
return {
workspaceKey: `srv:${overrides.workspaceId}`,
serverId: "srv",
projectViewKey: "prj-view",
projectName: "Repo",
projectRootPath: "/repo",
workspaceDirectory: `/repo/${overrides.workspaceId}`,
workspaceDirectoryLabel: overrides.workspaceId,
projectKind: "git",
workspaceKind: "local_checkout",
name: overrides.workspaceId,
title: null,
currentBranch: overrides.workspaceId,
statusBucket: "done",
statusEnteredAt: null,
archivingAt: null,
diffStat: null,
prHint: null,
pinnedAt: null,
background: false,
labels: [],
scripts: [],
hasRunningScripts: false,
archiveHasUncommittedChanges: null,
archiveUnpushedCommitCount: null,
...overrides,
};
}
function createFakeToast(): { toast: ToastApi; errors: string[] } {
const errors: string[] = [];
return {
errors,
toast: {
show: () => () => {},
copied: () => {},
error: (message) => errors.push(message),
},
};
}
function createFakeClient(): BulkArchiveClient {
return {
archiveWorkspace: async () => ({ error: null }),
undoWorkspaceArchive: async () => {},
getCheckoutStatus: async () =>
({
isGit: true,
isDirty: false,
aheadOfOrigin: 0,
}) as Awaited<ReturnType<BulkArchiveClient["getCheckoutStatus"]>>,
};
}
describe("archiveSelectedWorkspaces", () => {
it("archives multiple workspaces with one undo batch and redirects active workspace first", async () => {
const order: string[] = [];
const client = createFakeClient();
const { toast, errors } = createFakeToast();
const confirmRiskyBulkArchive = vi.fn(async () => true);
const deps: BulkArchiveWorkspacesDeps = {
getClient: () => client,
supportsUndo: () => true,
readWorktreeRisk: async () => ({ isDirty: false, aheadOfOrigin: 0 }),
confirmRiskyBulkArchive,
archiveWithUndo: async (input) => {
order.push(
`archive:${input.entries.map((entry) => entry.workspace.workspaceId).join(",")}`,
);
return { failures: [], showPartialFailure: () => false };
},
archiveWithoutUndo: async () => "archived",
hasActiveUndo: () => false,
purgeWorkspaceState: vi.fn(),
redirectActiveWorkspace: (workspace) => {
order.push(`redirect:${workspace.workspaceId}`);
},
};
const ok = await archiveSelectedWorkspaces({
workspaces: [makeEntry({ workspaceId: "w1" }), makeEntry({ workspaceId: "w2" })],
toast,
onArchiveStarted: () => order.push("exit-selection"),
deps,
});
expect(ok).toBe(true);
expect(errors).toEqual([]);
expect(order).toEqual(["redirect:w1", "redirect:w2", "exit-selection", "archive:w1,w2"]);
expect(confirmRiskyBulkArchive).not.toHaveBeenCalled();
});
it("keeps select mode open when the user cancels a risky worktree confirmation", async () => {
const client = createFakeClient();
const { toast, errors } = createFakeToast();
const onArchiveStarted = vi.fn();
const archiveWithUndo = vi.fn(async () => ({
failures: [],
showPartialFailure: () => false,
}));
const confirmRiskyBulkArchive = vi.fn(async () => false);
const ok = await archiveSelectedWorkspaces({
workspaces: [
makeEntry({ workspaceId: "w1", workspaceKind: "worktree", name: "feat-wip" }),
makeEntry({ workspaceId: "w2", workspaceKind: "local_checkout", name: "main" }),
],
toast,
onArchiveStarted,
deps: {
getClient: () => client,
supportsUndo: () => true,
readWorktreeRisk: async () => ({ isDirty: true, aheadOfOrigin: 1 }),
confirmRiskyBulkArchive,
archiveWithUndo,
archiveWithoutUndo: async () => "archived",
hasActiveUndo: () => false,
purgeWorkspaceState: vi.fn(),
redirectActiveWorkspace: vi.fn(),
},
});
expect(ok).toBe(false);
expect(errors).toEqual([]);
expect(confirmRiskyBulkArchive).toHaveBeenCalledWith({
totalCount: 2,
riskyWorkspaces: [
{
workspaceName: "feat-wip",
diffStat: null,
isDirty: true,
aheadOfOrigin: 1,
},
],
});
expect(onArchiveStarted).not.toHaveBeenCalled();
expect(archiveWithUndo).not.toHaveBeenCalled();
});
it("shows a disconnect error and aborts before archiving when any host is offline", async () => {
const { toast, errors } = createFakeToast();
const onArchiveStarted = vi.fn();
const ok = await archiveSelectedWorkspaces({
workspaces: [makeEntry({ workspaceId: "w1" })],
toast,
onArchiveStarted,
deps: {
getClient: () => null,
supportsUndo: () => true,
readWorktreeRisk: vi.fn(),
confirmRiskyBulkArchive: vi.fn(),
archiveWithUndo: vi.fn(),
archiveWithoutUndo: vi.fn(),
hasActiveUndo: () => false,
purgeWorkspaceState: vi.fn(),
redirectActiveWorkspace: vi.fn(),
},
});
expect(ok).toBe(false);
expect(errors).toEqual(["Host is not connected"]);
expect(onArchiveStarted).not.toHaveBeenCalled();
});
it("reports multi-workspace failures when more than one archive fails", async () => {
const client = createFakeClient();
const { toast, errors } = createFakeToast();
const ok = await archiveSelectedWorkspaces({
workspaces: [makeEntry({ workspaceId: "w1" }), makeEntry({ workspaceId: "w2" })],
toast,
onArchiveStarted: vi.fn(),
deps: {
getClient: () => client,
supportsUndo: () => true,
readWorktreeRisk: vi.fn(),
confirmRiskyBulkArchive: vi.fn(),
archiveWithUndo: async () => ({
failures: [
{ workspace: { serverId: "srv", workspaceId: "w1" }, error: new Error("boom 1") },
{ workspace: { serverId: "srv", workspaceId: "w2" }, error: new Error("boom 2") },
],
showPartialFailure: () => false,
}),
archiveWithoutUndo: vi.fn(),
hasActiveUndo: () => false,
purgeWorkspaceState: vi.fn(),
redirectActiveWorkspace: vi.fn(),
},
});
expect(ok).toBe(false);
expect(errors).toEqual(["Failed to archive 2 workspaces"]);
});
it("keeps Undo open via showPartialFailure instead of replacing it with toast.error on partial failure", async () => {
const client = createFakeClient();
const { toast, errors } = createFakeToast();
const partialErrors: string[] = [];
const ok = await archiveSelectedWorkspaces({
workspaces: [makeEntry({ workspaceId: "w1" }), makeEntry({ workspaceId: "w2" })],
toast,
onArchiveStarted: vi.fn(),
deps: {
getClient: () => client,
supportsUndo: () => true,
readWorktreeRisk: vi.fn(),
confirmRiskyBulkArchive: vi.fn(),
archiveWithUndo: async () => ({
failures: [
{ workspace: { serverId: "srv", workspaceId: "w2" }, error: new Error("Host offline") },
],
showPartialFailure: (message) => {
partialErrors.push(message);
return true;
},
}),
archiveWithoutUndo: vi.fn(),
hasActiveUndo: () => false,
purgeWorkspaceState: vi.fn(),
redirectActiveWorkspace: vi.fn(),
},
});
expect(ok).toBe(false);
expect(partialErrors).toEqual(["Host offline"]);
expect(errors).toEqual([]);
});
it("routes a late failure from a superseded batch to fallbackErrorToast so a newer batch keeps its Undo", async () => {
const client = createFakeClient();
const sidebar = createFakeToast();
const app = createFakeToast();
const ok = await archiveSelectedWorkspaces({
workspaces: [makeEntry({ workspaceId: "w1" })],
toast: sidebar.toast,
fallbackErrorToast: app.toast,
onArchiveStarted: vi.fn(),
deps: {
getClient: () => client,
supportsUndo: () => true,
readWorktreeRisk: vi.fn(),
confirmRiskyBulkArchive: vi.fn(),
archiveWithUndo: async () => ({
failures: [
{
workspace: { serverId: "srv", workspaceId: "w1" },
error: new Error("Host timed out"),
},
],
// This batch's own undo window was closed when a newer batch superseded it.
showPartialFailure: () => false,
}),
archiveWithoutUndo: vi.fn(),
hasActiveUndo: () => true,
purgeWorkspaceState: vi.fn(),
redirectActiveWorkspace: vi.fn(),
},
});
expect(ok).toBe(false);
expect(sidebar.errors).toEqual([]);
expect(app.errors).toEqual(["Host timed out"]);
});
});
@@ -1,197 +0,0 @@
import type { ToastApi } from "@/components/toast-host";
import type { CheckoutStatusClient } from "@/git/checkout-status-cache";
import {
confirmRiskyBulkWorktreeArchive,
readWorktreeArchiveRisk,
type WorktreeArchiveConfirmationInput,
} from "@/git/worktree-archive-warning";
import type { SidebarWorkspaceEntry } from "@/hooks/use-sidebar-workspaces-list";
import { i18n } from "@/i18n/i18next";
import { getHostRuntimeStore } from "@/runtime/host-runtime";
import type { ActiveWorkspaceSelection } from "@/stores/navigation-active-workspace-store";
import { useWorkspaceLayoutStore } from "@/stores/workspace-layout-store";
import { redirectIfArchivingActiveWorkspace } from "@/utils/sidebar-workspace-archive-redirect";
import { buildWorkspaceTabPersistenceKey } from "@/workspace-tabs/model";
import {
archiveWorkspacesWithUndo,
hasUndoableWorkspaceArchive,
supportsWorkspaceArchiveUndo,
type UndoableWorkspaceArchiveClient,
} from "@/workspace/archive-undo";
import {
archiveWorkspaceOptimistically,
type WorkspaceArchiveTarget,
} from "@/workspace/workspace-archive";
export interface BulkArchiveClient extends UndoableWorkspaceArchiveClient, CheckoutStatusClient {}
export interface BulkArchiveWorkspacesDeps {
getClient: (serverId: string) => BulkArchiveClient | null;
supportsUndo: (serverId: string) => boolean;
readWorktreeRisk: typeof readWorktreeArchiveRisk;
confirmRiskyBulkArchive: typeof confirmRiskyBulkWorktreeArchive;
archiveWithUndo: typeof archiveWorkspacesWithUndo;
archiveWithoutUndo: typeof archiveWorkspaceOptimistically;
hasActiveUndo: () => boolean;
purgeWorkspaceState: (workspace: WorkspaceArchiveTarget) => void;
redirectActiveWorkspace: (workspace: WorkspaceArchiveTarget) => void;
}
function defaultPurgeWorkspaceState(workspace: WorkspaceArchiveTarget): void {
const workspaceKey = buildWorkspaceTabPersistenceKey(workspace);
if (workspaceKey) {
useWorkspaceLayoutStore.getState().purgeWorkspace(workspaceKey);
}
}
export function createDefaultBulkArchiveDeps(
getActiveWorkspaceSelection: () => ActiveWorkspaceSelection | null,
): BulkArchiveWorkspacesDeps {
return {
getClient: (serverId) => getHostRuntimeStore().getClient(serverId),
supportsUndo: supportsWorkspaceArchiveUndo,
readWorktreeRisk: readWorktreeArchiveRisk,
confirmRiskyBulkArchive: confirmRiskyBulkWorktreeArchive,
archiveWithUndo: archiveWorkspacesWithUndo,
archiveWithoutUndo: archiveWorkspaceOptimistically,
hasActiveUndo: hasUndoableWorkspaceArchive,
purgeWorkspaceState: defaultPurgeWorkspaceState,
redirectActiveWorkspace: (workspace) => {
redirectIfArchivingActiveWorkspace({
serverId: workspace.serverId,
workspaceId: workspace.workspaceId,
activeWorkspaceSelection: getActiveWorkspaceSelection(),
});
},
};
}
function formatArchiveFailureMessage(failures: ReadonlyArray<{ error: unknown }>): string {
if (failures.length > 1) {
return i18n.t("sidebar.workspace.toasts.archiveMultipleFailed", { count: failures.length });
}
const error = failures[0]?.error;
return error instanceof Error ? error.message : i18n.t("sidebar.workspace.toasts.archiveFailed");
}
interface ResolvedWorkspaceTarget {
entry: SidebarWorkspaceEntry;
client: BulkArchiveClient;
}
export async function archiveSelectedWorkspaces(input: {
workspaces: readonly SidebarWorkspaceEntry[];
toast: ToastApi;
fallbackErrorToast?: ToastApi;
onArchiveStarted: () => void;
deps: BulkArchiveWorkspacesDeps;
}): Promise<boolean> {
const { workspaces, toast, fallbackErrorToast, onArchiveStarted, deps } = input;
if (workspaces.length === 0) return false;
const resolved: ResolvedWorkspaceTarget[] = [];
for (const entry of workspaces) {
const client = deps.getClient(entry.serverId);
if (!client) {
toast.error(i18n.t("sidebar.workspace.toasts.hostDisconnected"));
return false;
}
resolved.push({ entry, client });
}
const riskyWorkspaces: WorktreeArchiveConfirmationInput[] = [];
const worktrees = resolved.filter((item) => item.entry.workspaceKind === "worktree");
if (worktrees.length > 0) {
try {
const risks = await Promise.all(
worktrees.map(async ({ entry, client }) => {
const risk = await deps.readWorktreeRisk(client, entry.workspaceDirectory);
return {
workspaceName: entry.name,
diffStat: entry.diffStat,
isDirty: risk.isDirty,
aheadOfOrigin: risk.aheadOfOrigin,
} satisfies WorktreeArchiveConfirmationInput;
}),
);
riskyWorkspaces.push(...risks);
} catch (error) {
toast.error(
error instanceof Error ? error.message : i18n.t("sidebar.workspace.toasts.archiveFailed"),
);
return false;
}
}
if (riskyWorkspaces.length > 0) {
const confirmed = await deps.confirmRiskyBulkArchive({
totalCount: resolved.length,
riskyWorkspaces,
});
if (!confirmed) {
return false;
}
}
// Redirect before optimistic removal hides the active workspace from the session store.
for (const { entry } of resolved) {
deps.redirectActiveWorkspace({ serverId: entry.serverId, workspaceId: entry.workspaceId });
}
onArchiveStarted();
const undoable: ResolvedWorkspaceTarget[] = [];
const legacy: ResolvedWorkspaceTarget[] = [];
for (const item of resolved) {
if (deps.supportsUndo(item.entry.serverId)) {
undoable.push(item);
} else {
legacy.push(item);
}
}
const failures: Array<{ error: unknown }> = [];
let showPartialFailure: (message: string) => boolean = () => false;
await Promise.all([
undoable.length > 0
? (async () => {
const result = await deps.archiveWithUndo({
entries: undoable.map(({ entry, client }) => {
const workspace = { serverId: entry.serverId, workspaceId: entry.workspaceId };
return {
client,
workspace,
onArchiveCommitted: () => deps.purgeWorkspaceState(workspace),
};
}),
toast,
});
failures.push(...result.failures);
showPartialFailure = result.showPartialFailure;
})()
: Promise.resolve(),
// COMPAT(workspaceArchiveUndo): hosts before v0.15.3 cannot undo; remove after 2027-05-06.
...legacy.map(async ({ entry, client }) => {
const workspace = { serverId: entry.serverId, workspaceId: entry.workspaceId };
try {
await deps.archiveWithoutUndo({ client, workspace });
deps.purgeWorkspaceState(workspace);
} catch (error) {
failures.push({ error });
}
}),
]);
if (failures.length > 0) {
const errorMessage = formatArchiveFailureMessage(failures);
if (!showPartialFailure(errorMessage)) {
// If a newer batch now owns the sidebar Undo toast, surface this older failure on the
// app-level toast instead of displacing the active Undo window and purging its layouts.
const errorToast = deps.hasActiveUndo() ? (fallbackErrorToast ?? toast) : toast;
errorToast.error(errorMessage);
}
}
return failures.length === 0;
}
@@ -1,93 +0,0 @@
import { describe, expect, it } from "vitest";
import {
enterWorkspaceSelection,
exitWorkspaceSelection,
INITIAL_WORKSPACE_SELECTION_STATE,
isShiftPressEvent,
reconcileWorkspaceSelection,
selectWorkspaceRange,
toggleWorkspaceSelection,
} from "./selection-state";
describe("sidebar workspace selection state", () => {
it("enters selection with the clicked workspace as anchor", () => {
const state = enterWorkspaceSelection("ws-2");
expect({
active: state.active,
selected: [...state.selectedKeys],
anchorKey: state.anchorKey,
}).toEqual({
active: true,
selected: ["ws-2"],
anchorKey: "ws-2",
});
});
it("toggles workspaces on plain click without needing Shift", () => {
let state = enterWorkspaceSelection("ws-1");
state = toggleWorkspaceSelection(state, "ws-3");
expect([...state.selectedKeys]).toEqual(["ws-1", "ws-3"]);
expect(state.anchorKey).toBe("ws-3");
state = toggleWorkspaceSelection(state, "ws-1");
expect([...state.selectedKeys]).toEqual(["ws-3"]);
expect(state.anchorKey).toBe("ws-1");
state = toggleWorkspaceSelection(state, "ws-3");
expect(state.active).toBe(true);
expect([...state.selectedKeys]).toEqual([]);
});
it("selects an inclusive range on Shift+click in either direction while keeping prior picks", () => {
const visible = ["ws-1", "ws-2", "ws-3", "ws-4", "ws-5"];
let state = enterWorkspaceSelection("ws-1");
state = toggleWorkspaceSelection(state, "ws-3");
state = selectWorkspaceRange(state, "ws-5", visible);
expect([...state.selectedKeys]).toEqual(["ws-1", "ws-3", "ws-4", "ws-5"]);
expect(state.anchorKey).toBe("ws-3");
const backward = selectWorkspaceRange(enterWorkspaceSelection("ws-4"), "ws-2", visible);
expect([...backward.selectedKeys].sort()).toEqual(["ws-2", "ws-3", "ws-4"]);
});
it("falls back to adding the target when the anchor is no longer in the visible list", () => {
const state = selectWorkspaceRange(enterWorkspaceSelection("ws-hidden"), "ws-2", [
"ws-1",
"ws-2",
]);
expect([...state.selectedKeys]).toEqual(["ws-hidden", "ws-2"]);
expect(state.anchorKey).toBe("ws-2");
});
it("reconciles removed workspaces and clears a missing anchor", () => {
let state = enterWorkspaceSelection("ws-1");
state = toggleWorkspaceSelection(state, "ws-2");
const reconciled = reconcileWorkspaceSelection(state, new Set(["ws-1"]));
expect({
active: reconciled.active,
selected: [...reconciled.selectedKeys],
anchorKey: reconciled.anchorKey,
}).toEqual({
active: true,
selected: ["ws-1"],
anchorKey: null,
});
});
it("resets completely on exit", () => {
expect(exitWorkspaceSelection()).toBe(INITIAL_WORKSPACE_SELECTION_STATE);
});
it("detects Shift on direct, nativeEvent, or hardware modifier payloads", () => {
expect(isShiftPressEvent({ shiftKey: true })).toBe(true);
expect(isShiftPressEvent({ nativeEvent: { shiftKey: true } })).toBe(true);
expect(isShiftPressEvent({ shiftKey: false, nativeEvent: { shiftKey: false } })).toBe(false);
expect(isShiftPressEvent(null)).toBe(false);
// Native GestureResponderEvent omits shiftKey; falls back to hardware Shift state.
const nativeResponderEvent = { nativeEvent: { locationX: 12, locationY: 8 } };
expect(isShiftPressEvent(nativeResponderEvent, () => false)).toBe(false);
expect(isShiftPressEvent(nativeResponderEvent, () => true)).toBe(true);
});
});
@@ -1,129 +0,0 @@
import { isShiftKeyDown } from "@/keyboard";
export interface WorkspaceSelectionState {
active: boolean;
selectedKeys: ReadonlySet<string>;
anchorKey: string | null;
}
const EMPTY_KEYS: ReadonlySet<string> = new Set();
export const INITIAL_WORKSPACE_SELECTION_STATE: WorkspaceSelectionState = {
active: false,
selectedKeys: EMPTY_KEYS,
anchorKey: null,
};
export function enterWorkspaceSelection(workspaceKey: string): WorkspaceSelectionState {
return {
active: true,
selectedKeys: new Set([workspaceKey]),
anchorKey: workspaceKey,
};
}
export function toggleWorkspaceSelection(
state: WorkspaceSelectionState,
workspaceKey: string,
): WorkspaceSelectionState {
if (!state.active) {
return enterWorkspaceSelection(workspaceKey);
}
const next = new Set(state.selectedKeys);
if (!next.delete(workspaceKey)) {
next.add(workspaceKey);
}
return {
active: true,
selectedKeys: next,
anchorKey: workspaceKey,
};
}
export function selectWorkspaceRange(
state: WorkspaceSelectionState,
targetKey: string,
orderedVisibleKeys: readonly string[],
): WorkspaceSelectionState {
if (!state.active) {
return enterWorkspaceSelection(targetKey);
}
if (!state.anchorKey) {
const next = new Set(state.selectedKeys);
next.add(targetKey);
return { active: true, selectedKeys: next, anchorKey: targetKey };
}
const anchorIndex = orderedVisibleKeys.indexOf(state.anchorKey);
const targetIndex = orderedVisibleKeys.indexOf(targetKey);
if (anchorIndex < 0 || targetIndex < 0) {
const next = new Set(state.selectedKeys);
next.add(targetKey);
return { active: true, selectedKeys: next, anchorKey: targetKey };
}
const start = Math.min(anchorIndex, targetIndex);
const end = Math.max(anchorIndex, targetIndex);
const next = new Set(state.selectedKeys);
for (let index = start; index <= end; index += 1) {
const key = orderedVisibleKeys[index];
if (key !== undefined) {
next.add(key);
}
}
return {
active: true,
selectedKeys: next,
anchorKey: state.anchorKey,
};
}
export function reconcileWorkspaceSelection(
state: WorkspaceSelectionState,
availableKeys: ReadonlySet<string>,
): WorkspaceSelectionState {
if (!state.active) return state;
let changed = false;
const next = new Set<string>();
for (const key of state.selectedKeys) {
if (availableKeys.has(key)) {
next.add(key);
} else {
changed = true;
}
}
const nextAnchor = state.anchorKey && availableKeys.has(state.anchorKey) ? state.anchorKey : null;
if (!changed && nextAnchor === state.anchorKey) {
return state;
}
return {
active: true,
selectedKeys: changed ? next : state.selectedKeys,
anchorKey: nextAnchor,
};
}
export function exitWorkspaceSelection(): WorkspaceSelectionState {
return INITIAL_WORKSPACE_SELECTION_STATE;
}
export function isShiftPressEvent(
event: unknown,
isHardwareShiftDown: () => boolean = isShiftKeyDown,
): boolean {
if (typeof event === "object" && event !== null) {
if (Reflect.get(event, "shiftKey") === true) return true;
const nativeEvent = Reflect.get(event, "nativeEvent");
if (
typeof nativeEvent === "object" &&
nativeEvent !== null &&
Reflect.get(nativeEvent, "shiftKey") === true
) {
return true;
}
}
return isHardwareShiftDown();
}
@@ -1,82 +0,0 @@
import { create } from "zustand";
import {
enterWorkspaceSelection,
exitWorkspaceSelection,
INITIAL_WORKSPACE_SELECTION_STATE,
reconcileWorkspaceSelection,
selectWorkspaceRange,
toggleWorkspaceSelection,
type WorkspaceSelectionState,
} from "./selection-state";
type VisibleKeysReader = () => readonly string[];
let visibleKeysReader: VisibleKeysReader = () => [];
/**
* Registers a synchronous reader for the currently rendered sidebar workspace order so Shift+click
* range selection walks only rows on screen without causing re-renders when the order changes.
*/
export function registerSidebarVisibleWorkspaceKeysReader(reader: VisibleKeysReader): () => void {
visibleKeysReader = reader;
return () => {
if (visibleKeysReader === reader) {
visibleKeysReader = () => [];
}
};
}
interface SidebarSelectionStoreState extends WorkspaceSelectionState {
isArchiving: boolean;
enter: (workspaceKey: string) => void;
pressWorkspace: (workspaceKey: string, options: { shiftKey: boolean }) => void;
reconcile: (availableKeys: ReadonlySet<string>) => void;
setArchiving: (archiving: boolean) => void;
exit: () => void;
}
export const useSidebarSelectionStore = create<SidebarSelectionStoreState>((set) => ({
...INITIAL_WORKSPACE_SELECTION_STATE,
isArchiving: false,
enter: (workspaceKey) =>
set(() => ({
...enterWorkspaceSelection(workspaceKey),
isArchiving: false,
})),
pressWorkspace: (workspaceKey, { shiftKey }) =>
set((state) => {
if (state.isArchiving) return state;
const next = shiftKey
? selectWorkspaceRange(state, workspaceKey, visibleKeysReader())
: toggleWorkspaceSelection(state, workspaceKey);
return next === state ? state : { ...next };
}),
reconcile: (availableKeys) =>
set((state) => {
const next = reconcileWorkspaceSelection(state, availableKeys);
return next === state ? state : { ...next };
}),
setArchiving: (isArchiving) => set({ isArchiving }),
exit: () =>
set((state) =>
state.active || state.isArchiving
? { ...exitWorkspaceSelection(), isArchiving: false }
: state,
),
}));
export function useIsSidebarSelectionMode(): boolean {
return useSidebarSelectionStore((state) => state.active);
}
export function useIsWorkspaceBulkSelected(workspaceKey: string): boolean {
return useSidebarSelectionStore((state) => state.active && state.selectedKeys.has(workspaceKey));
}
export function useSidebarSelectionCount(): number {
return useSidebarSelectionStore((state) => (state.active ? state.selectedKeys.size : 0));
}
export function useSidebarSelectionArchiving(): boolean {
return useSidebarSelectionStore((state) => state.isArchiving);
}
@@ -1,355 +0,0 @@
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import React, { act, useCallback } from "react";
import { createRoot, type Root } from "react-dom/client";
import { I18nextProvider } from "react-i18next";
import { Text } from "react-native";
import { SafeAreaProvider } from "react-native-safe-area-context";
import { afterEach, describe, expect, it } from "vitest";
import { SidebarToastRegion } from "@/components/sidebar/sidebar-toast-region";
import { SidebarWorkspaceContextMenu } from "@/components/sidebar/sidebar-workspace-menu";
import { ToastProvider, useToast } from "@/contexts/toast-context";
import type { ToastApi } from "@/components/toast-host";
import type { SidebarWorkspaceEntry } from "@/hooks/use-sidebar-workspaces-list";
import { i18n } from "@/i18n/i18next";
import { dispatchTopOverlayKeyDown } from "@/keyboard";
import {
KeyboardActionDispatcherProvider,
useKeyboardActionDispatcher,
} from "@/keyboard/keyboard-action-dispatcher-context";
import { useKeyboardActionHandler } from "@/hooks/use-keyboard-action-handler";
import {
isShiftPressEvent,
registerSidebarVisibleWorkspaceKeysReader,
SidebarSelectionHost,
useIsSidebarSelectionMode,
useIsWorkspaceBulkSelected,
useSidebarSelectionStore,
} from "@/sidebar-selection";
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
let root: Root | null = null;
let container: HTMLDivElement | null = null;
let releaseVisibleKeys: (() => void) | null = null;
function makeEntry(id: string): SidebarWorkspaceEntry {
return {
workspaceKey: `srv:${id}`,
workspaceId: id,
serverId: "srv",
projectViewKey: "prj-view",
projectName: "Repo",
projectRootPath: "/repo",
workspaceDirectory: `/repo/${id}`,
workspaceDirectoryLabel: id,
projectKind: "git",
workspaceKind: "local_checkout",
name: id,
title: null,
currentBranch: id,
statusBucket: "done",
statusEnteredAt: null,
archivingAt: null,
diffStat: null,
prHint: null,
pinnedAt: null,
background: false,
labels: [],
scripts: [],
hasRunningScripts: false,
archiveHasUncommittedChanges: null,
archiveUnpushedCommitCount: null,
};
}
let capturedDispatcher: ReturnType<typeof useKeyboardActionDispatcher> | null = null;
let capturedSidebarToast: ToastApi | null = null;
let fallbackArchiveCount = 0;
function FallbackArchiveProbe() {
capturedDispatcher = useKeyboardActionDispatcher();
useKeyboardActionHandler({
handlerId: "test-global-workspace-archive-fallback",
actions: ["workspace.archive"],
enabled: true,
priority: 0,
handle: () => {
fallbackArchiveCount += 1;
return true;
},
});
return null;
}
function SidebarToastProbe() {
capturedSidebarToast = useToast();
return null;
}
const noop = () => {};
function SelectableRowProbe({ entry }: { entry: SidebarWorkspaceEntry }) {
const isSelectionMode = useIsSidebarSelectionMode();
const isBulkSelected = useIsWorkspaceBulkSelected(entry.workspaceKey);
const handlePress = useCallback(
(event: unknown) => {
const shiftKey = isShiftPressEvent(event);
if (isSelectionMode || shiftKey) {
useSidebarSelectionStore.getState().pressWorkspace(entry.workspaceKey, { shiftKey });
}
},
[entry.workspaceKey, isSelectionMode],
);
return (
<SidebarWorkspaceContextMenu
contextMenuOpen={false}
onContextMenuOpenChange={noop}
workspace={entry}
workspaceKey={entry.workspaceKey}
enabled={!isSelectionMode}
accessibilityRole={isSelectionMode ? "checkbox" : "button"}
aria-checked={isSelectionMode ? isBulkSelected : undefined}
highlightStyle={undefined}
onPress={handlePress}
testID={`sidebar-workspace-row-${entry.workspaceKey}`}
>
<Text>{entry.name}</Text>
</SidebarWorkspaceContextMenu>
);
}
function mountHost(entries: readonly SidebarWorkspaceEntry[]) {
const entriesByKey = new Map(entries.map((entry) => [entry.workspaceKey, entry]));
releaseVisibleKeys = registerSidebarVisibleWorkspaceKeysReader(() =>
entries.map((entry) => entry.workspaceKey),
);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
act(() => {
root?.render(
<QueryClientProvider client={queryClient}>
<I18nextProvider i18n={i18n}>
<SafeAreaProvider>
<KeyboardActionDispatcherProvider>
<FallbackArchiveProbe />
<ToastProvider>
<SidebarToastRegion active>
<SidebarToastProbe />
{entries.map((entry) => (
<SelectableRowProbe key={entry.workspaceKey} entry={entry} />
))}
<SidebarSelectionHost active workspaceEntriesByKey={entriesByKey} />
</SidebarToastRegion>
</ToastProvider>
</KeyboardActionDispatcherProvider>
</SafeAreaProvider>
</I18nextProvider>
</QueryClientProvider>,
);
});
}
afterEach(() => {
capturedDispatcher = null;
capturedSidebarToast = null;
fallbackArchiveCount = 0;
act(() => {
useSidebarSelectionStore.getState().exit();
});
releaseVisibleKeys?.();
releaseVisibleKeys = null;
act(() => root?.unmount());
container?.remove();
root = null;
container = null;
});
describe("SidebarSelectionHost", () => {
it("shows a persistent sidebar toast while selecting, updates without Shift, and exits via button or Escape", async () => {
mountHost([makeEntry("a"), makeEntry("b"), makeEntry("c")]);
expect(document.querySelector('[data-testid="workspace-selection-toast"]')).toBeNull();
// Enter select mode via Shift+click on "a", then plain-click "c" without Shift.
act(() => {
useSidebarSelectionStore.getState().pressWorkspace("srv:a", { shiftKey: true });
});
expect(document.querySelector('[data-testid="workspace-selection-count"]')?.textContent).toBe(
"1 selected",
);
act(() => {
useSidebarSelectionStore.getState().pressWorkspace("srv:c", { shiftKey: false });
});
expect(document.querySelector('[data-testid="workspace-selection-count"]')?.textContent).toBe(
"2 selected",
);
// Clicking the Exit button leaves select mode and fades the persistent toast out.
const exitButton = document.querySelector<HTMLElement>(
'[data-testid="workspace-selection-exit"]',
);
expect(exitButton).not.toBeNull();
act(() => {
exitButton?.click();
});
expect(useSidebarSelectionStore.getState().active).toBe(false);
await expect
.poll(() => document.querySelector('[data-testid="workspace-selection-toast"]'))
.toBeNull();
// Re-enter with Shift+click, then Shift+click "c" for a range of 3, and exit with Escape.
act(() => {
useSidebarSelectionStore.getState().pressWorkspace("srv:a", { shiftKey: true });
useSidebarSelectionStore.getState().pressWorkspace("srv:c", { shiftKey: true });
});
expect(document.querySelector('[data-testid="workspace-selection-count"]')?.textContent).toBe(
"3 selected",
);
let prevented = false;
act(() => {
const handled = dispatchTopOverlayKeyDown({
key: "Escape",
code: "Escape",
altKey: false,
ctrlKey: false,
metaKey: false,
shiftKey: false,
repeat: false,
preventDefault: () => {
prevented = true;
},
stopPropagation: () => {},
});
expect(handled).toBe(true);
});
expect(prevented).toBe(true);
expect(useSidebarSelectionStore.getState().active).toBe(false);
await expect
.poll(() => document.querySelector('[data-testid="workspace-selection-toast"]'))
.toBeNull();
});
it("consumes workspace.archive while in select mode even with zero rows selected or while archiving", () => {
mountHost([makeEntry("a"), makeEntry("b")]);
// Outside select mode, the global fallback receives workspace.archive.
act(() => {
expect(capturedDispatcher?.dispatch({ id: "workspace.archive", scope: "sidebar" })).toBe(
true,
);
});
expect(fallbackArchiveCount).toBe(1);
// Enter select mode then deselect the only row -> 0 selected.
act(() => {
useSidebarSelectionStore.getState().enter("srv:a");
useSidebarSelectionStore.getState().pressWorkspace("srv:a", { shiftKey: false });
});
expect(document.querySelector('[data-testid="workspace-selection-count"]')?.textContent).toBe(
"0 selected",
);
// The archive shortcut must be absorbed by select mode rather than archiving the open workspace.
act(() => {
expect(capturedDispatcher?.dispatch({ id: "workspace.archive", scope: "sidebar" })).toBe(
true,
);
});
expect(fallbackArchiveCount).toBe(1);
// Same while a worktree safety check is in progress (both archive shortcut and Escape stay owned).
act(() => {
useSidebarSelectionStore.getState().enter("srv:a");
useSidebarSelectionStore.getState().setArchiving(true);
});
act(() => {
expect(capturedDispatcher?.dispatch({ id: "workspace.archive", scope: "sidebar" })).toBe(
true,
);
expect(
dispatchTopOverlayKeyDown({
key: "Escape",
code: "Escape",
altKey: false,
ctrlKey: false,
metaKey: false,
shiftKey: false,
repeat: false,
preventDefault: () => {},
stopPropagation: () => {},
}),
).toBe(true);
});
expect(fallbackArchiveCount).toBe(1);
expect(useSidebarSelectionStore.getState().active).toBe(true);
});
it("keeps the selection bar visible when an Undo toast is already displayed in the sidebar", () => {
mountHost([makeEntry("a"), makeEntry("b")]);
let dismissUndo: (() => void) | undefined;
act(() => {
dismissUndo = capturedSidebarToast?.show("Workspace archived", {
durationMs: 6000,
testID: "workspace-archived-toast",
});
});
expect(document.querySelector('[data-testid="workspace-archived-toast"]')).not.toBeNull();
act(() => {
useSidebarSelectionStore.getState().enter("srv:a");
});
// Both the Undo toast and the selection bar (count, Archive, Exit) must remain visible.
expect(document.querySelector('[data-testid="workspace-archived-toast"]')).not.toBeNull();
expect(document.querySelector('[data-testid="workspace-selection-toast"]')).not.toBeNull();
expect(document.querySelector('[data-testid="workspace-selection-count"]')?.textContent).toBe(
"1 selected",
);
expect(document.querySelector('[data-testid="workspace-selection-archive"]')).not.toBeNull();
expect(document.querySelector('[data-testid="workspace-selection-exit"]')).not.toBeNull();
act(() => {
dismissUndo?.();
});
});
it("toggles focused workspace checkboxes when pressing Space in select mode", () => {
mountHost([makeEntry("a"), makeEntry("b")]);
act(() => {
useSidebarSelectionStore.getState().enter("srv:a");
});
const rowB = document.querySelector<HTMLElement>('[data-testid="sidebar-workspace-row-srv:b"]');
expect(rowB?.getAttribute("role")).toBe("checkbox");
expect(rowB?.getAttribute("aria-checked")).toBe("false");
act(() => {
rowB?.focus();
rowB?.dispatchEvent(
new KeyboardEvent("keydown", { key: " ", bubbles: true, cancelable: true }),
);
rowB?.dispatchEvent(
new KeyboardEvent("keydown", { key: " ", repeat: true, bubbles: true, cancelable: true }),
);
});
expect(rowB?.getAttribute("aria-checked")).toBe("true");
expect(document.querySelector('[data-testid="workspace-selection-count"]')?.textContent).toBe(
"2 selected",
);
act(() => {
rowB?.dispatchEvent(
new KeyboardEvent("keydown", { key: " ", bubbles: true, cancelable: true }),
);
});
expect(rowB?.getAttribute("aria-checked")).toBe("false");
expect(document.querySelector('[data-testid="workspace-selection-count"]')?.textContent).toBe(
"1 selected",
);
});
});
@@ -1,157 +0,0 @@
import { useCallback, useEffect, useMemo, useRef } from "react";
import {
useSidebarAppToast,
useSidebarPersistentToast,
} from "@/components/sidebar/sidebar-toast-region";
import type { ToastState } from "@/components/toast-host";
import { useToast } from "@/contexts/toast-context";
import { useKeyboardActionHandler } from "@/hooks/use-keyboard-action-handler";
import type { SidebarWorkspaceEntry } from "@/hooks/use-sidebar-workspaces-list";
import { useOverlayRegistration } from "@/keyboard";
import type { KeyboardActionId } from "@/keyboard/keyboard-action-dispatcher";
import { useActiveWorkspaceSelection } from "@/stores/navigation-active-workspace-store";
import { archiveSelectedWorkspaces, createDefaultBulkArchiveDeps } from "./archive-selected";
import {
useIsSidebarSelectionMode,
useSidebarSelectionArchiving,
useSidebarSelectionCount,
useSidebarSelectionStore,
} from "./selection-store";
import { WorkspaceSelectionToast } from "./workspace-selection-toast";
const SELECTION_TOAST_ID = -1;
const ESCAPE_OVERLAY_KEYS = ["Escape"] as const;
const WORKSPACE_ARCHIVE_ACTIONS: readonly KeyboardActionId[] = ["workspace.archive"];
/**
* Coordinates sidebar workspace select mode: reconciles removed workspaces, binds Escape and
* the archive shortcut, and keeps the persistent selection bar up in `SidebarToastRegion`.
*/
export function SidebarSelectionHost({
active,
workspaceEntriesByKey,
}: {
active: boolean;
workspaceEntriesByKey: ReadonlyMap<string, SidebarWorkspaceEntry>;
}): null {
const toast = useToast();
const appToast = useSidebarAppToast();
const activeWorkspaceSelection = useActiveWorkspaceSelection();
const selectionMode = useIsSidebarSelectionMode();
const selectedCount = useSidebarSelectionCount();
const isArchiving = useSidebarSelectionArchiving();
const entriesRef = useRef(workspaceEntriesByKey);
entriesRef.current = workspaceEntriesByKey;
const activeSelectionRef = useRef(activeWorkspaceSelection);
activeSelectionRef.current = activeWorkspaceSelection;
const archiveAttemptRef = useRef(0);
useEffect(() => {
if (!selectionMode) return;
useSidebarSelectionStore.getState().reconcile(new Set(workspaceEntriesByKey.keys()));
}, [selectionMode, workspaceEntriesByKey]);
useEffect(() => {
if (active) return;
const state = useSidebarSelectionStore.getState();
if (state.active && !state.isArchiving) {
state.exit();
}
}, [active]);
const handleExit = useCallback(() => {
const state = useSidebarSelectionStore.getState();
if (state.isArchiving) return;
state.exit();
}, []);
const handleArchiveSelected = useCallback(() => {
const store = useSidebarSelectionStore.getState();
if (!store.active || store.isArchiving || store.selectedKeys.size === 0) return;
const entries: SidebarWorkspaceEntry[] = [];
for (const key of store.selectedKeys) {
const entry = entriesRef.current.get(key);
if (entry && entry.archivingAt === null) {
entries.push(entry);
}
}
if (entries.length === 0) {
store.exit();
return;
}
const attemptId = archiveAttemptRef.current + 1;
archiveAttemptRef.current = attemptId;
store.setArchiving(true);
void archiveSelectedWorkspaces({
workspaces: entries,
toast,
fallbackErrorToast: appToast,
onArchiveStarted: () => {
useSidebarSelectionStore.getState().exit();
},
deps: createDefaultBulkArchiveDeps(() => activeSelectionRef.current),
}).finally(() => {
if (archiveAttemptRef.current !== attemptId) return;
const current = useSidebarSelectionStore.getState();
if (current.isArchiving) {
current.setArchiving(false);
}
});
}, [appToast, toast]);
useOverlayRegistration({
keys: ESCAPE_OVERLAY_KEYS,
// Keep Escape owned while select mode is active (including during worktree checks) so it
// never falls through to interrupt a running agent in the open workspace; any higher-layer
// confirmation dialog still receives Escape first.
active: selectionMode && active,
layer: 0,
manageFocus: false,
onKeyDown: (event) => {
if (event.key !== "Escape") return false;
event.preventDefault();
handleExit();
return true;
},
});
useKeyboardActionHandler({
handlerId: "sidebar-selection-archive",
actions: WORKSPACE_ARCHIVE_ACTIONS,
// Keep ownership of workspace.archive for the entire lifetime of select mode so pressing it
// at 0 selected or during a worktree check never falls through to archive the open workspace.
enabled: selectionMode && active,
priority: 10,
handle: () => {
handleArchiveSelected();
return true;
},
});
const persistentToast = useMemo<ToastState | null>(() => {
if (!selectionMode || !active) return null;
return {
id: SELECTION_TOAST_ID,
content: (
<WorkspaceSelectionToast
selectedCount={selectedCount}
isArchiving={isArchiving}
onArchive={handleArchiveSelected}
onExit={handleExit}
/>
),
nativeMessage: null,
variant: "default",
layout: "action",
durationMs: null,
testID: "workspace-selection-toast",
};
}, [active, handleArchiveSelected, handleExit, isArchiving, selectedCount, selectionMode]);
useSidebarPersistentToast(persistentToast);
return null;
}
@@ -1,83 +0,0 @@
import { X } from "lucide-react-native";
import { useTranslation } from "react-i18next";
import { Text, View } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { Button } from "@/components/ui/button";
import { CONTROL_HEIGHTS } from "@/components/ui/control-geometry";
import { DensityIcon } from "@/components/ui/density-icon";
import { ToolbarButton } from "@/components/ui/pane-content-toolbar";
import type { ShortcutKey } from "@/utils/format-shortcut";
const EXIT_SHORTCUT_CHORD: ShortcutKey[][] = [["Esc"]];
export function WorkspaceSelectionToast({
selectedCount,
isArchiving,
onArchive,
onExit,
}: {
selectedCount: number;
isArchiving: boolean;
onArchive: () => void;
onExit: () => void;
}) {
const { t } = useTranslation();
const exitLabel = t("sidebar.workspace.selection.exit");
return (
<View style={styles.row}>
<Text style={styles.message} numberOfLines={1} testID="workspace-selection-count">
{t("sidebar.workspace.selection.count", { count: selectedCount })}
</Text>
<View style={styles.actions}>
<Button
size="sm"
onPress={onArchive}
disabled={selectedCount === 0}
loading={isArchiving}
testID="workspace-selection-archive"
>
{t("sidebar.workspace.actions.archive")}
</Button>
<ToolbarButton
round
tooltipSide="top"
label={exitLabel}
shortcut={EXIT_SHORTCUT_CHORD}
onPress={onExit}
disabled={isArchiving}
style={styles.exitButton}
testID="workspace-selection-exit"
>
<DensityIcon icon={X} size="sm" color="foregroundMuted" />
</ToolbarButton>
</View>
</View>
);
}
const styles = StyleSheet.create((theme) => ({
row: {
flexDirection: "row",
flexWrap: "wrap",
alignItems: "center",
gap: theme.spacing[3],
},
message: {
flexShrink: 1,
color: theme.colors.foreground,
fontSize: theme.fontSize.base,
fontWeight: theme.fontWeight.normal,
},
actions: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[1],
},
// Matches the Archive button's sm pill height so the circular hover fill sits concentrically
// in the action toast's trailing corner.
exitButton: {
width: CONTROL_HEIGHTS.sm,
height: CONTROL_HEIGHTS.sm,
},
}));
+32
View File
@@ -324,6 +324,12 @@ export interface AgentTimelineCursorState {
}>;
}
/** The latest conversation rewind applied to an agent's history, by its sequence number. */
export interface AgentTimelineRewind {
epoch: string;
seq: number;
}
export type AgentTimelineState =
| { status: "cold" }
| { status: "painted"; items: StreamItem[] }
@@ -498,6 +504,7 @@ export interface SessionState {
agentTimelineUnsettledTurn: Map<string, UnsettledTurn>;
agentTimelineHasOlder: Map<string, boolean>;
agentTimelineHasNewer: Map<string, boolean>;
agentTimelineLatestRewind: Map<string, AgentTimelineRewind>;
agentTimelineOlderFetchInFlight: Map<string, boolean>;
historySyncGeneration: number;
agentHistorySyncGeneration: Map<string, number>;
@@ -617,6 +624,12 @@ interface SessionStoreActions {
serverId: string,
state: Map<string, boolean> | ((prev: Map<string, boolean>) => Map<string, boolean>),
) => void;
/** Records a rewind applied to the agent's history; an older one of the same history is ignored. */
recordAgentTimelineRewind: (
serverId: string,
agentId: string,
rewind: AgentTimelineRewind,
) => void;
setAgentTimelineOlderFetchInFlight: (
serverId: string,
state: Map<string, boolean> | ((prev: Map<string, boolean>) => Map<string, boolean>),
@@ -753,6 +766,7 @@ function createInitialSessionState(
agentTimelineUnsettledTurn: new Map(),
agentTimelineHasOlder: new Map(),
agentTimelineHasNewer: new Map(),
agentTimelineLatestRewind: new Map(),
agentTimelineOlderFetchInFlight: new Map(),
historySyncGeneration: 0,
agentHistorySyncGeneration: new Map(),
@@ -1401,6 +1415,24 @@ export const useSessionStore = create<SessionStore>()(
});
},
recordAgentTimelineRewind: (serverId, agentId, rewind) => {
set((prev) => {
const session = prev.sessions[serverId];
if (!session) return prev;
const current = session.agentTimelineLatestRewind.get(agentId);
if (current && current.epoch === rewind.epoch && current.seq >= rewind.seq) return prev;
const next = new Map(session.agentTimelineLatestRewind);
next.set(agentId, rewind);
return {
...prev,
sessions: {
...prev.sessions,
[serverId]: { ...session, agentTimelineLatestRewind: next },
},
};
});
},
setAgentTimelineOlderFetchInFlight: (serverId, state) => {
set((prev) => {
const session = prev.sessions[serverId];
+230 -1
View File
@@ -39,7 +39,7 @@ function item(id: string, text: string, seq: number): StreamItem {
id,
text,
timestamp: new Date("2026-08-26T10:00:00.000Z"),
timelineCursor: { epoch: "epoch-1", seq },
timelineCursor: { epoch: "epoch-1", seq, anchorSeq: seq },
};
}
@@ -579,6 +579,235 @@ describe("viewed timeline persistence", () => {
});
});
describe("conversation rewind through the owner", () => {
const page = {
requestId: "page-1",
agentId: AGENT_ID,
agent: null,
direction: "tail",
projection: "projected",
reset: false,
epoch: "epoch-1",
error: null,
hasNewer: false,
hasOlder: false,
staleCursor: false,
gap: false,
} as const;
function entry(seq: number, type: "user_message" | "assistant_message", text: string) {
return {
seqStart: seq,
seqEnd: seq,
sourceSeqRanges: [{ startSeq: seq, endSeq: seq }],
collapsed: [],
provider: "codex",
item: { type, text },
timestamp: `2026-08-26T10:00:0${seq}.000Z`,
};
}
function texts(items: readonly StreamItem[]): string[] {
return items.flatMap((row) =>
row.kind === "user_message" || row.kind === "assistant_message" ? [row.text] : [],
);
}
function viewed(): string[] {
const session = useSessionStore.getState().sessions[SERVER_ID];
const timeline = selectAgentTimelineState(session, AGENT_ID);
const tail = timeline.status === "cold" ? [] : timeline.items;
return texts([...tail, ...(session?.agentStreamHead.get(AGENT_ID) ?? [])]);
}
function latestRewind() {
return useSessionStore.getState().sessions[SERVER_ID]?.agentTimelineLatestRewind.get(AGENT_ID);
}
it("retires B from the viewed and persisted timeline without refetching", () => {
useSessionStore.getState().initializeSession(SERVER_ID, null);
const commits: CachedTimeline[] = [];
const owner = createOwner({
readTimeline: async () => undefined,
commitTimeline: (_serverId, _agentId, timeline) => commits.push(timeline),
});
owner.applyTimelineResponse({
...page,
window: { minSeq: 1, maxSeq: 4, nextSeq: 5 },
startCursor: { epoch: "epoch-1", seq: 1 },
endCursor: { epoch: "epoch-1", seq: 4 },
entries: [
entry(1, "user_message", "A"),
entry(2, "assistant_message", "reply A"),
entry(3, "user_message", "B"),
entry(4, "assistant_message", "reply B"),
],
});
owner.applyStreamEvent(AGENT_ID, {
event: { type: "rewind", retireFromSeq: 3 },
seq: 5,
epoch: "epoch-1",
timestamp: new Date("2026-08-26T10:00:05.000Z"),
});
owner.applyStreamEvent(AGENT_ID, {
event: {
type: "timeline",
provider: "codex",
item: { type: "user_message", text: "C", messageId: "c" },
} as AgentStreamEventPayload,
seq: 6,
epoch: "epoch-1",
timestamp: new Date("2026-08-26T10:00:06.000Z"),
});
owner.flushStreamAgent(AGENT_ID);
expect(viewed()).toEqual(["A", "reply A", "C"]);
expect(texts(commits.at(-1)?.items ?? [])).toEqual(["A", "reply A", "C"]);
expect(commits.at(-1)?.range).toMatchObject({ epoch: "epoch-1", endSeq: 6 });
expect(latestRewind()).toEqual({ epoch: "epoch-1", seq: 5 });
owner.dispose();
});
it("brings a second client that loads after the rewind to the same conversation", () => {
useSessionStore.getState().initializeSession(SERVER_ID, null);
const owner = createOwner({ readTimeline: async () => undefined, commitTimeline: () => {} });
owner.applyTimelineResponse({
...page,
window: { minSeq: 1, maxSeq: 6, nextSeq: 7 },
startCursor: { epoch: "epoch-1", seq: 1 },
endCursor: { epoch: "epoch-1", seq: 6 },
entries: [
entry(1, "user_message", "A"),
entry(2, "assistant_message", "reply A"),
entry(6, "user_message", "C"),
],
retirements: [{ seq: 5, retireFromSeq: 3 }],
});
expect(viewed()).toEqual(["A", "reply A", "C"]);
expect(latestRewind()).toEqual({ epoch: "epoch-1", seq: 5 });
owner.dispose();
});
function liveRewindOfB(owner: ViewedTimelineOwner, retirement: { seq: number }): void {
owner.applyStreamEvent(AGENT_ID, {
event: { type: "rewind", retireFromSeq: 3 },
seq: retirement.seq,
epoch: "epoch-1",
timestamp: new Date("2026-08-26T10:00:06.000Z"),
});
owner.applyStreamEvent(AGENT_ID, {
event: {
type: "timeline",
provider: "codex",
item: { type: "user_message", text: "C", messageId: "c" },
} as AgentStreamEventPayload,
seq: retirement.seq + 1,
epoch: "epoch-1",
timestamp: new Date("2026-08-26T10:00:07.000Z"),
});
owner.flushStreamAgent(AGENT_ID);
}
/** A, reply A, B, reply B as a page served before B was rewound. */
const pageServedBeforeTheRewind: Parameters<ViewedTimelineOwner["applyTimelineResponse"]>[0] = {
...page,
direction: "before",
hasOlder: false,
window: { minSeq: 1, maxSeq: 5, nextSeq: 6 },
startCursor: { epoch: "epoch-1", seq: 1 },
endCursor: { epoch: "epoch-1", seq: 4 },
entries: [
entry(1, "user_message", "A"),
entry(2, "assistant_message", "reply A"),
entry(3, "user_message", "B"),
entry(4, "assistant_message", "reply B"),
],
};
function loadTheEndOfB(owner: ViewedTimelineOwner): void {
owner.applyTimelineResponse({
...page,
hasOlder: true,
window: { minSeq: 1, maxSeq: 5, nextSeq: 6 },
startCursor: { epoch: "epoch-1", seq: 5 },
endCursor: { epoch: "epoch-1", seq: 5 },
entries: [entry(5, "assistant_message", "more of B")],
});
}
it("refuses an older page served before the rewind and takes the one served after it", () => {
useSessionStore.getState().initializeSession(SERVER_ID, null);
const owner = createOwner({ readTimeline: async () => undefined, commitTimeline: () => {} });
loadTheEndOfB(owner);
liveRewindOfB(owner, { seq: 6 });
expect(viewed()).toEqual(["C"]);
const outcome = owner.applyTimelineResponse(pageServedBeforeTheRewind);
expect(viewed()).toEqual(["C"]);
expect(outcome).toBe("stale");
owner.applyTimelineResponse({
...pageServedBeforeTheRewind,
window: { minSeq: 1, maxSeq: 7, nextSeq: 8 },
// Retired rows count as covered, so the page reaches the loaded start.
endCursor: { epoch: "epoch-1", seq: 4 },
entries: [entry(1, "user_message", "A"), entry(2, "assistant_message", "reply A")],
});
expect(viewed()).toEqual(["A", "reply A", "C"]);
owner.dispose();
});
it("refuses a prompt jump window served before the rewind", () => {
useSessionStore.getState().initializeSession(SERVER_ID, null);
const owner = createOwner({ readTimeline: async () => undefined, commitTimeline: () => {} });
loadTheEndOfB(owner);
liveRewindOfB(owner, { seq: 6 });
const outcome = owner.applyTimelineResponse({
...pageServedBeforeTheRewind,
mergeWindow: true,
});
expect(viewed()).toEqual(["C"]);
expect(outcome).toBe("stale");
owner.dispose();
});
it("refuses a first page served before a rewind that reached the chat while it loaded", () => {
useSessionStore.getState().initializeSession(SERVER_ID, null);
const owner = createOwner({ readTimeline: async () => undefined, commitTimeline: () => {} });
liveRewindOfB(owner, { seq: 5 });
const outcome = owner.applyTimelineResponse({
...pageServedBeforeTheRewind,
direction: "tail",
window: { minSeq: 1, maxSeq: 4, nextSeq: 5 },
});
expect(viewed()).toEqual(["C"]);
expect(outcome).toBe("stale");
owner.applyTimelineResponse({
...page,
window: { minSeq: 1, maxSeq: 6, nextSeq: 7 },
startCursor: { epoch: "epoch-1", seq: 1 },
endCursor: { epoch: "epoch-1", seq: 6 },
entries: [
entry(1, "user_message", "A"),
entry(2, "assistant_message", "reply A"),
{
...entry(6, "user_message", "C"),
item: { type: "user_message", text: "C", messageId: "c" },
},
],
retirements: [{ seq: 5, retireFromSeq: 3 }],
});
expect(viewed()).toEqual(["A", "reply A", "C"]);
owner.dispose();
});
});
describe("turn boundaries", () => {
it("commits a turn's final reply before the turn stops running", () => {
useSessionStore.getState().initializeSession(SERVER_ID, null);
@@ -398,7 +398,7 @@ describe("processTimelineResponse", () => {
messageId: "provider-message",
text: "local prompt",
timestamp: new Date(1000),
timelineCursor: { epoch: "epoch-1", seq: 1 },
timelineCursor: { epoch: "epoch-1", seq: 1, anchorSeq: 1 },
turnId: "turn-1",
});
const hello = createUserMessage({
@@ -406,7 +406,7 @@ describe("processTimelineResponse", () => {
clientMessageId: "hello-client",
text: "hello",
timestamp: new Date(1500),
timelineCursor: { epoch: "epoch-1", seq: 2 },
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 2 },
turnId: "turn-1",
});
const currentTail = [canonical, makeAssistantItem("existing tail", "existing-tail"), hello];
@@ -456,7 +456,7 @@ describe("processTimelineResponse", () => {
id: "stale-history",
text: "stale history",
timestamp: new Date(1040),
timelineCursor: { epoch: "epoch-1", seq: 40 },
timelineCursor: { epoch: "epoch-1", seq: 40, anchorSeq: 40 },
},
],
currentCursor: { epoch: "epoch-1", startSeq: 1, endSeq: 40 },
@@ -484,11 +484,11 @@ describe("processTimelineResponse", () => {
const unresolved = makeSubmittedUserMessage("unresolved prompt", "client-unresolved");
const coveredLive: StreamItem = {
...makeAssistantItem("covered live", "covered-live"),
timelineCursor: { epoch: "epoch-1", seq: 235 },
timelineCursor: { epoch: "epoch-1", seq: 235, anchorSeq: 235 },
};
const newerLive: StreamItem = {
...makeAssistantItem("newer live", "newer-live"),
timelineCursor: { epoch: "epoch-1", seq: 245 },
timelineCursor: { epoch: "epoch-1", seq: 245, anchorSeq: 245 },
};
const result = processTimelineResponse({
@@ -573,7 +573,7 @@ describe("processTimelineResponse", () => {
expect.objectContaining({
kind: "assistant_message",
text: "[System Error] failed",
timelineCursor: { epoch: "timeline-1", seq: 42 },
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 40 },
}),
]);
});
@@ -745,7 +745,7 @@ describe("processTimelineResponse", () => {
}).item,
} as AgentStreamEventPayload,
timestamp: new Date(2000),
timelineCursor: { epoch: "epoch-1", seq: 2 },
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 2 },
},
],
{ source: "canonical" },
@@ -775,7 +775,7 @@ describe("processTimelineResponse", () => {
expect(getAgentToolCalls([...result.tail, ...result.head])).toEqual([
expect.objectContaining({
timelineCursor: { epoch: "epoch-1", seq: 2 },
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 1 },
payload: expect.objectContaining({
data: expect.objectContaining({ callId, status: "completed" }),
}),
@@ -796,7 +796,7 @@ describe("processTimelineResponse", () => {
},
} as AgentStreamEventPayload,
timestamp: new Date(2000),
timelineCursor: { epoch: "epoch-1", seq: 2 },
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 2 },
},
],
{ source: "canonical" },
@@ -831,7 +831,7 @@ describe("processTimelineResponse", () => {
expect([...result.tail, ...result.head].filter((item) => item.kind === "todo_list")).toEqual([
expect.objectContaining({
timelineCursor: { epoch: "epoch-1", seq: 2 },
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 1 },
items: [{ text: "Verify hydration", completed: true }],
}),
]);
@@ -847,7 +847,7 @@ describe("processTimelineResponse", () => {
item: { type: "compaction", status: "completed", trigger: "auto", preTokens: 1200 },
} as AgentStreamEventPayload,
timestamp: new Date(2000),
timelineCursor: { epoch: "epoch-1", seq: 2 },
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 2 },
},
],
{ source: "canonical" },
@@ -879,7 +879,7 @@ describe("processTimelineResponse", () => {
expect([...result.tail, ...result.head].filter((item) => item.kind === "compaction")).toEqual([
expect.objectContaining({
timelineCursor: { epoch: "epoch-1", seq: 2 },
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 1 },
status: "completed",
trigger: "auto",
preTokens: 1200,
@@ -918,7 +918,7 @@ describe("processTimelineResponse", () => {
messageId: "assistant-live",
text: " continuation",
timestamp: new Date(2001),
timelineCursor: { epoch: "epoch-1", seq: 101 },
timelineCursor: { epoch: "epoch-1", seq: 101, anchorSeq: 101 },
},
],
isInitializing: true,
@@ -946,7 +946,7 @@ describe("processTimelineResponse", () => {
);
expect(assistants).toHaveLength(1);
expect(assistants[0]?.text).toBe("canonical prefix continuation");
expect(assistants[0]?.timelineCursor).toEqual({ epoch: "epoch-1", seq: 101 });
expect(assistants[0]?.timelineCursor).toEqual({ epoch: "epoch-1", seq: 101, anchorSeq: 100 });
});
it("keeps assistant segments separate when a live tool sits between them", () => {
@@ -963,12 +963,12 @@ describe("processTimelineResponse", () => {
}).item,
} as AgentStreamEventPayload,
timestamp: new Date(2101),
timelineCursor: { epoch: "epoch-1", seq: 101 },
timelineCursor: { epoch: "epoch-1", seq: 101, anchorSeq: 101 },
},
{
event: makeAssistantTimelineEvent("after tool", messageId),
timestamp: new Date(2102),
timelineCursor: { epoch: "epoch-1", seq: 102 },
timelineCursor: { epoch: "epoch-1", seq: 102, anchorSeq: 102 },
},
],
{ source: "canonical" },
@@ -1019,7 +1019,7 @@ describe("processTimelineResponse", () => {
id: "assistant-live",
text: "canonical prefix continuation",
timestamp: new Date(2001),
timelineCursor: { epoch: "epoch-1", seq: 101 },
timelineCursor: { epoch: "epoch-1", seq: 101, anchorSeq: 101 },
},
],
isInitializing: true,
@@ -1038,7 +1038,7 @@ describe("processTimelineResponse", () => {
);
expect(assistants).toHaveLength(1);
expect(assistants[0]?.text).toBe("canonical prefix continuation");
expect(assistants[0]?.timelineCursor).toEqual({ epoch: "epoch-1", seq: 101 });
expect(assistants[0]?.timelineCursor).toEqual({ epoch: "epoch-1", seq: 101, anchorSeq: 100 });
});
it("keeps a canonical live user row newer than the bootstrap page", () => {
@@ -1060,7 +1060,7 @@ describe("processTimelineResponse", () => {
});
expect(live.head[0]).toMatchObject({
kind: "user_message",
timelineCursor: { epoch: "epoch-1", seq: 101 },
timelineCursor: { epoch: "epoch-1", seq: 101, anchorSeq: 101 },
});
const result = processTimelineResponse({
@@ -1123,7 +1123,7 @@ describe("processTimelineResponse", () => {
kind: "user_message",
clientMessageId: "client-message-1",
messageId: "provider-message-1",
timelineCursor: { epoch: "epoch-1", seq: 51 },
timelineCursor: { epoch: "epoch-1", seq: 51, anchorSeq: 51 },
});
});
@@ -2808,7 +2808,7 @@ describe("processTimelineResponse", () => {
id: "newest",
text: "newest",
timestamp: new Date(1000),
timelineCursor: { epoch: "epoch-1", seq: 100 },
timelineCursor: { epoch: "epoch-1", seq: 100, anchorSeq: 100 },
},
makeSubmittedUserMessage("pending submission", "pending-submission"),
],
@@ -2886,14 +2886,14 @@ describe("processTimelineResponse", () => {
id: "oldest",
text: "oldest",
timestamp: new Date(1000),
timelineCursor: { epoch: "epoch-1", seq: 1 },
timelineCursor: { epoch: "epoch-1", seq: 1, anchorSeq: 1 },
},
{
kind: "user_message",
id: "newest",
text: "newest",
timestamp: new Date(100_000),
timelineCursor: { epoch: "epoch-1", seq: 100 },
timelineCursor: { epoch: "epoch-1", seq: 100, anchorSeq: 100 },
},
];
@@ -2935,7 +2935,7 @@ describe("processTimelineResponse", () => {
id: "newest",
text: "newest",
timestamp: new Date(100_000),
timelineCursor: { epoch: "epoch-1", seq: 100 },
timelineCursor: { epoch: "epoch-1", seq: 100, anchorSeq: 100 },
},
...(lane === "tail" ? [pending] : []),
],
@@ -2976,9 +2976,13 @@ describe("processTimelineResponse", () => {
{
text: "local pending prompt",
messageId: "canonical-message",
timelineCursor: { epoch: "epoch-1", seq: 1 },
timelineCursor: { epoch: "epoch-1", seq: 1, anchorSeq: 1 },
},
{
text: "newest",
messageId: undefined,
timelineCursor: { epoch: "epoch-1", seq: 100, anchorSeq: 100 },
},
{ text: "newest", messageId: undefined, timelineCursor: { epoch: "epoch-1", seq: 100 } },
],
head: [],
acknowledgedClientMessageIds: [clientMessageId],
@@ -2992,7 +2996,7 @@ describe("processTimelineResponse", () => {
{
event: makeToolCallTimelineEvent("call-1"),
timestamp: new Date(500),
timelineCursor: { epoch: "epoch-1", seq: 500 },
timelineCursor: { epoch: "epoch-1", seq: 500, anchorSeq: 500 },
},
],
{ source: "canonical" },
@@ -3038,7 +3042,7 @@ describe("processTimelineResponse", () => {
{
callId: "call-1",
status: "completed",
timelineCursor: { epoch: "epoch-1", seq: 500 },
timelineCursor: { epoch: "epoch-1", seq: 500, anchorSeq: 1 },
},
]);
});
@@ -3050,7 +3054,7 @@ describe("processTimelineResponse", () => {
...makeAssistantItem("projected response", "loaded-assistant"),
messageId: "assistant-message",
timestamp,
timelineCursor: { epoch: "epoch-1", seq: 500 },
timelineCursor: { epoch: "epoch-1", seq: 500, anchorSeq: 500 },
},
];
const result = processTimelineResponse({
@@ -3100,7 +3104,7 @@ describe("processTimelineResponse", () => {
id: "loaded-assistant",
text: "projected response",
messageId: "assistant-message",
timelineCursor: { epoch: "epoch-1", seq: 500 },
timelineCursor: { epoch: "epoch-1", seq: 500, anchorSeq: 1 },
},
]);
});
@@ -3112,7 +3116,7 @@ describe("processTimelineResponse", () => {
id: "current-200",
text: "current-200",
timestamp: new Date(3200),
timelineCursor: { epoch: "epoch-1", seq: 200 },
timelineCursor: { epoch: "epoch-1", seq: 200, anchorSeq: 200 },
},
];
const existingCursor: TimelineCursor = {
@@ -3219,7 +3223,7 @@ describe("processTimelineResponse", () => {
const currentTail = [
{
...makeAssistantItem("newer chunk", "assistant-newer"),
timelineCursor: { epoch: "epoch-1", seq: 3 },
timelineCursor: { epoch: "epoch-1", seq: 3, anchorSeq: 3 },
},
];
const existingCursor: TimelineCursor = {
@@ -3246,7 +3250,7 @@ describe("processTimelineResponse", () => {
expect(result.tail[0]).toEqual(
expect.objectContaining({
id: "assistant-newer",
timelineCursor: { epoch: "epoch-1", seq: 3 },
timelineCursor: { epoch: "epoch-1", seq: 3, anchorSeq: 3 },
}),
);
expect(result.cursor).toEqual({
@@ -3686,7 +3690,7 @@ describe("processAgentStreamEvent", () => {
expect.objectContaining({
kind: "assistant_message",
text: "[System Error] failed",
timelineCursor: { epoch: "timeline-1", seq: 42 },
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 42 },
}),
]);
});
@@ -3933,7 +3937,7 @@ describe("processAgentStreamEvent", () => {
expect(getUserTexts(result.head)).toEqual(["live before bootstrap"]);
expect(result.head[0]).toMatchObject({
kind: "user_message",
timelineCursor: { epoch: "epoch-1", seq: 51 },
timelineCursor: { epoch: "epoch-1", seq: 51, anchorSeq: 51 },
});
expect(result.cursorChanged).toBe(false);
expect(result.cursor).toBeNull();
@@ -3968,7 +3972,7 @@ describe("processAgentStreamEvent", () => {
clientMessageId: "client-message-1",
messageId: "provider-message-1",
text: "submitted before bootstrap",
timelineCursor: { epoch: "epoch-1", seq: 51 },
timelineCursor: { epoch: "epoch-1", seq: 51, anchorSeq: 51 },
}),
]);
});
@@ -4559,6 +4563,279 @@ describe("createAgentStreamReducerQueue", () => {
});
});
// ---------------------------------------------------------------------------
// Conversation rewind: A, B, rewind B, C
// ---------------------------------------------------------------------------
describe("conversation rewind", () => {
const rewindB = { seq: 5, retireFromSeq: 3 };
function loadAB(): { tail: StreamItem[]; head: StreamItem[]; cursor: TimelineCursor } {
const result = processTimelineResponse({
...baseTimelineInput,
isInitializing: true,
hasActiveInitDeferred: true,
payload: {
...baseTimelineInput.payload,
direction: "tail",
window: { minSeq: 1, maxSeq: 4, nextSeq: 5 },
startCursor: { seq: 1 },
endCursor: { seq: 4 },
entries: [
makeTimelineEntry(1, "A", "user_message"),
makeTimelineEntry(2, "reply A"),
makeTimelineEntry(3, "B", "user_message"),
makeTimelineEntry(4, "reply B"),
],
},
});
if (!result.cursor) throw new Error("expected a loaded range");
return { tail: result.tail, head: result.head, cursor: result.cursor };
}
function live(
state: { tail: StreamItem[]; head: StreamItem[]; cursor: TimelineCursor },
events: AgentStreamReducerEvent[],
) {
const result = processAgentStreamEvents({
events,
currentTail: state.tail,
currentHead: state.head,
currentCursor: state.cursor,
hasAuthoritativeBaseline: true,
});
return {
tail: result.tail,
head: result.head,
cursor: result.cursor ?? state.cursor,
sideEffects: result.sideEffects,
};
}
function rewindEvent(retirement: { seq: number; retireFromSeq: number }) {
return {
event: { type: "rewind" as const, retireFromSeq: retirement.retireFromSeq },
seq: retirement.seq,
epoch: "epoch-1",
timestamp: new Date(1000 + retirement.seq),
};
}
const promptC = [
makeStreamReducerEvent(makeTimelineEvent("C", "user_message"), 6),
makeStreamReducerEvent(makeTimelineEvent("reply C"), 7),
];
function conversation(state: { tail: StreamItem[]; head: StreamItem[] }) {
return [...state.tail, ...state.head].map((item) =>
item.kind === "user_message" || item.kind === "assistant_message" ? item.text : item.kind,
);
}
it("retires B in place, keeps A mounted, and shows C once", () => {
const loaded = loadAB();
const [promptA, replyA] = loaded.tail;
const rewound = live(loaded, [rewindEvent(rewindB), ...promptC]);
expect(conversation(rewound)).toEqual(["A", "reply A", "C", "reply C"]);
expect(rewound.tail[0]).toBe(promptA);
expect(rewound.tail[1]).toBe(replyA);
expect(rewound.cursor).toMatchObject({ epoch: "epoch-1", startSeq: 1, endSeq: 7 });
expect(rewound.sideEffects).toEqual([]);
});
it("ignores a duplicate rewind so C is not retired", () => {
const rewound = live(loadAB(), [rewindEvent(rewindB), ...promptC]);
const replayed = live(rewound, [rewindEvent(rewindB)]);
expect(conversation(replayed)).toEqual(["A", "reply A", "C", "reply C"]);
expect(replayed.cursor.endSeq).toBe(7);
});
it("does not let an old page resurrect B after the rewind applied", () => {
const rewound = live(loadAB(), [rewindEvent(rewindB), ...promptC]);
const stale = processTimelineResponse({
...baseTimelineInput,
currentTail: rewound.tail,
currentHead: rewound.head,
currentCursor: rewound.cursor,
payload: {
...baseTimelineInput.payload,
direction: "after",
window: { minSeq: 1, maxSeq: 4, nextSeq: 5 },
startCursor: { seq: 3 },
endCursor: { seq: 4 },
entries: [makeTimelineEntry(3, "B", "user_message"), makeTimelineEntry(4, "reply B")],
},
});
expect(conversation(stale)).toEqual(["A", "reply A", "C", "reply C"]);
expect(stale.cursorChanged).toBe(false);
});
it("drops a late live delivery for the retired range", () => {
const rewound = live(loadAB(), [rewindEvent(rewindB)]);
const late = live(rewound, [makeStreamReducerEvent(makeTimelineEvent("late B"), 4)]);
expect(conversation(late)).toEqual(["A", "reply A"]);
});
it("catches up through a page that only carries the retirement", () => {
const loaded = loadAB();
const caughtUp = processTimelineResponse({
...baseTimelineInput,
currentTail: loaded.tail,
currentHead: loaded.head,
currentCursor: loaded.cursor,
payload: {
...baseTimelineInput.payload,
direction: "after",
window: { minSeq: 1, maxSeq: 5, nextSeq: 6 },
startCursor: { seq: 5 },
endCursor: { seq: 5 },
entries: [],
retirements: [rewindB],
},
});
if (!caughtUp.cursor) throw new Error("expected a loaded range");
expect(conversation(caughtUp)).toEqual(["A", "reply A"]);
expect(caughtUp.cursor.endSeq).toBe(5);
expect(caughtUp.sideEffects).not.toContainEqual(expect.objectContaining({ type: "catch_up" }));
const continued = live({ ...caughtUp, cursor: caughtUp.cursor }, promptC);
expect(conversation(continued)).toEqual(["A", "reply A", "C", "reply C"]);
});
it("converges after reconnect from a resume page that crosses the rewind", () => {
const loaded = loadAB();
const resumed = processTimelineResponse({
...baseTimelineInput,
currentTail: loaded.tail,
currentHead: loaded.head,
currentCursor: loaded.cursor,
payload: {
...baseTimelineInput.payload,
direction: "tail",
window: { minSeq: 1, maxSeq: 7, nextSeq: 8 },
startCursor: { seq: 1 },
endCursor: { seq: 7 },
entries: [
makeTimelineEntry(1, "A", "user_message"),
makeTimelineEntry(2, "reply A"),
makeTimelineEntry(6, "C", "user_message"),
makeTimelineEntry(7, "reply C"),
],
retirements: [rewindB],
},
});
expect(conversation(resumed)).toEqual(["A", "reply A", "C", "reply C"]);
expect(resumed.tail[0]).toBe(loaded.tail[0]);
expect(resumed.cursor).toMatchObject({ endSeq: 7 });
});
it("recovers a rewind that skips past the loaded end", () => {
const loaded = loadAB();
const gapped = live(loaded, [rewindEvent({ seq: 9, retireFromSeq: 3 })]);
expect(conversation(gapped)).toEqual(["A", "reply A", "B", "reply B"]);
expect(gapped.sideEffects).toEqual([
{ type: "catch_up", cursor: { epoch: "epoch-1", endSeq: 4 } },
]);
});
it("keeps an A row whose late update carries a seq inside B's range", () => {
const loaded = loadAB();
const [promptA, replyA, ...rest] = loaded.tail;
const lateTool = hydrateStreamState(
[
{
event: makeToolCallTimelineEvent("call-a"),
timestamp: new Date(1002),
timelineCursor: { epoch: "epoch-1", seq: 4, anchorSeq: 2 },
},
],
{ source: "canonical" },
);
const state = { ...loaded, tail: [promptA, replyA, ...lateTool, ...rest] };
const rewound = live(state, [rewindEvent(rewindB)]);
expect(conversation(rewound)).toEqual(["A", "reply A", "tool_call"]);
});
it("keeps a tool that started before B when B's prompt is not loaded and the tool updated after B", () => {
const toolA = {
...makeToolCallTimelineEntry(2, "call-a", "completed", {
type: "read",
filePath: "/tmp/a.ts",
}),
seqEnd: 6,
sourceSeqRanges: [
{ startSeq: 2, endSeq: 2 },
{ startSeq: 6, endSeq: 6 },
],
};
const loaded = processTimelineResponse({
...baseTimelineInput,
isInitializing: true,
hasActiveInitDeferred: true,
payload: {
...baseTimelineInput.payload,
direction: "tail",
window: { minSeq: 1, maxSeq: 6, nextSeq: 7 },
startCursor: { seq: 1 },
endCursor: { seq: 6 },
entries: [makeTimelineEntry(1, "A", "user_message"), toolA],
},
});
if (!loaded.cursor) throw new Error("expected a loaded range");
const rewound = live({ tail: loaded.tail, head: loaded.head, cursor: loaded.cursor }, [
rewindEvent({ seq: 7, retireFromSeq: 3 }),
]);
expect(conversation(rewound)).toEqual(["A", "tool_call"]);
});
it("keeps C from the live overlay when the first page brings the retirement C followed", () => {
const overlay = processAgentStreamEvents({
events: [rewindEvent(rewindB), ...promptC],
currentTail: [],
currentHead: [],
currentCursor: undefined,
hasAuthoritativeBaseline: false,
});
const initialized = processTimelineResponse({
...baseTimelineInput,
isInitializing: true,
hasActiveInitDeferred: true,
currentTail: overlay.tail,
currentHead: overlay.head,
payload: {
...baseTimelineInput.payload,
direction: "tail",
window: { minSeq: 1, maxSeq: 5, nextSeq: 6 },
startCursor: { seq: 1 },
endCursor: { seq: 5 },
entries: [makeTimelineEntry(1, "A", "user_message"), makeTimelineEntry(2, "reply A")],
retirements: [rewindB],
},
});
expect(conversation(initialized)).toEqual(["A", "reply A", "C", "reply C"]);
});
});
describe("turn metrics", () => {
const metrics = [
{ label: "Model", value: "opus" },
@@ -4816,4 +5093,30 @@ describe("turn metrics", () => {
expect(repeated.tail).toBe(first.tail);
});
it("stamps turn metrics carried on a live timeline event appended by reload", () => {
const result = processAgentStreamEvents({
events: [
makeStreamReducerEvent(makeTimelineEvent("question", "user_message"), 1),
makeStreamReducerEvent(
{
type: "timeline",
provider: "claude",
item: { type: "assistant_message", text: "Appended reply." },
turnMetrics: metrics,
},
2,
),
],
currentTail: [],
currentHead: [],
currentCursor: { epoch: "epoch-1", startSeq: 0, endSeq: 0 },
hasAuthoritativeBaseline: true,
});
expect(metricsByKind([...result.tail, ...result.head])).toEqual([
{ kind: "user_message", turnMetrics: undefined },
{ kind: "assistant_message", turnMetrics: metrics },
]);
});
});
@@ -1,7 +1,13 @@
import type { AgentMetric, AgentTimelineItem } from "@getpaseo/protocol/agent-types";
import type { AgentStreamEventPayload } from "@getpaseo/protocol/messages";
import { selectAgentTimelineState, useSessionStore } from "@/stores/session-store";
import type { AssistantMessageItem, StreamItem, TodoEntry } from "@/types/stream";
import {
advanceTimelinePosition,
type AssistantMessageItem,
type StreamItem,
type TimelinePosition,
type TodoEntry,
} from "@/types/stream";
import type { TurnLivenessTransition } from "@/timeline/turn-liveness";
import { stampTimelineTurnMetrics } from "@/timeline/turn-metrics";
import {
@@ -72,6 +78,64 @@ interface TimelineSeqRange {
endSeq: number;
}
/** A conversation rewind took the rows anchored in `[retireFromSeq, seq)` out of the conversation. */
export interface TimelineRetirement {
seq: number;
retireFromSeq: number;
}
/** The live form of a retirement; it is sequenced with the stream events around it. */
export interface TimelineRewindEvent {
type: "rewind";
retireFromSeq: number;
}
/**
* Drops the rows a retirement took out of the conversation: those anchored in
* `[retireFromSeq, seq)`. Anchors do not move on update, so an earlier row updated after the
* rewound prompt stays, and a row that started after the retirement stays. Items without a
* timeline position are local sends the daemon has not echoed and stay.
*/
function retireRewoundStreamItems(input: {
tail: StreamItem[];
head: StreamItem[];
epoch: string;
retirement: TimelineRetirement;
}): { tail: StreamItem[]; head: StreamItem[] } {
const { tail, head, epoch, retirement } = input;
const isRetired = (item: StreamItem) => {
const position = item.timelineCursor;
return (
position?.epoch === epoch &&
position.anchorSeq >= retirement.retireFromSeq &&
position.anchorSeq < retirement.seq
);
};
const nextTail = tail.filter((item) => !isRetired(item));
const nextHead = head.filter((item) => !isRetired(item));
return {
tail: nextTail.length === tail.length ? tail : nextTail,
head: nextHead.length === head.length ? head : nextHead,
};
}
/**
* Applies a page's retirements to what this client holds. The page's own entries are already
* active. Applying a retirement twice changes nothing, since its range is bounded.
*/
function retireForPage(input: {
payload: ProcessTimelineResponseInput["payload"];
tail: StreamItem[];
head: StreamItem[];
}): { tail: StreamItem[]; head: StreamItem[] } {
const { payload } = input;
let held = { tail: input.tail, head: input.head };
for (const retirement of payload.retirements ?? []) {
held = retireRewoundStreamItems({ ...held, epoch: payload.epoch, retirement });
}
return held;
}
function mergeTimelineCoverage(
current: TimelineCursor,
added: TimelineLoadedRange,
@@ -152,6 +216,7 @@ export interface ProcessTimelineResponseInput {
hasNewer: boolean;
hasOlder: boolean;
mergeWindow?: boolean;
retirements?: TimelineRetirement[];
};
currentTail: StreamItem[];
currentHead: StreamItem[];
@@ -396,7 +461,7 @@ function mergeTimelineWindow(args: {
toHydratedEvents: (units: TimelineUnit[]) => Array<{
event: AgentStreamEventPayload;
timestamp: Date;
timelineCursor: { epoch: string; seq: number };
timelineCursor: TimelinePosition;
}>;
}): TimelinePathResult {
const { timelineUnits, payload, currentTail, currentHead, currentCursor, toHydratedEvents } =
@@ -760,7 +825,7 @@ function replaceLiveAssistantWithProjectedText(params: {
head: StreamItem[];
event: AgentStreamEventPayload;
timestamp: Date;
timelineCursor: { epoch: string; seq: number };
timelineCursor: TimelinePosition;
}): StreamItem[] | null {
const { head, event, timestamp, timelineCursor } = params;
if (event.type !== "timeline" || event.item.type !== "assistant_message") {
@@ -779,7 +844,7 @@ function replaceLiveAssistantWithProjectedText(params: {
...current,
text: event.item.text,
timestamp,
timelineCursor,
...advanceTimelinePosition(current.timelineCursor, timelineCursor),
};
return next;
}
@@ -829,7 +894,7 @@ function reconcileOverlappingProjectedAssistant(params: {
...(messageId !== undefined ? { messageId } : {}),
text: projectedText,
timestamp: unit.timestamp,
timelineCursor: { epoch: params.epoch, seq: unit.seqEnd },
timelineCursor: { epoch: params.epoch, seq: unit.seqEnd, anchorSeq: unit.seq },
};
const replaceMatch = (items: StreamItem[], index: number) => {
const next = [...items];
@@ -946,8 +1011,8 @@ function applyCanonicalForwardUnit(params: {
unit: TimelineUnit;
epoch: string;
}): { tail: StreamItem[]; head: StreamItem[]; acknowledgedClientMessageIds: string[] } {
const { event, timestamp, seqEnd } = params.unit;
const timelineCursor = { epoch: params.epoch, seq: seqEnd };
const { event, timestamp, seq, seqEnd } = params.unit;
const timelineCursor: TimelinePosition = { epoch: params.epoch, seq: seqEnd, anchorSeq: seq };
if (event.type === "timeline" && event.item.type === "user_message") {
const applied = applyStreamEvent({
tail: params.tail,
@@ -1146,10 +1211,10 @@ function applyAcceptedTimelinePage(input: {
});
}
const olderTail = hydrateStreamState(
acceptedUnits.map(({ event, timestamp, seqEnd }) => ({
acceptedUnits.map(({ event, timestamp, seq, seqEnd }) => ({
event,
timestamp,
timelineCursor: { epoch: payload.epoch, seq: seqEnd },
timelineCursor: { epoch: payload.epoch, seq: seqEnd, anchorSeq: seq },
})),
{
source: "canonical",
@@ -1181,7 +1246,12 @@ function applyTimelineIncrementalPath(args: {
let cursorChanged = false;
const sideEffects: TimelineReducerSideEffect[] = [];
if (timelineUnits.length === 0 && payload.direction !== "before") {
// A forward page of retirements alone still advances the loaded end.
if (
timelineUnits.length === 0 &&
payload.direction !== "before" &&
(payload.retirements?.length ?? 0) === 0
) {
return {
tail: currentTail,
head: currentHead,
@@ -1239,8 +1309,6 @@ export function processTimelineResponse(
): ProcessTimelineResponseOutput {
const {
payload,
currentTail,
currentHead,
currentCursor,
isInitializing,
hasActiveInitDeferred,
@@ -1254,8 +1322,8 @@ export function processTimelineResponse(
if (payload.error) {
return {
commit: "apply",
tail: currentTail,
head: currentHead,
tail: input.currentTail,
head: input.currentHead,
cursor: currentCursor,
cursorChanged: false,
older: "unchanged",
@@ -1267,6 +1335,13 @@ export function processTimelineResponse(
};
}
// Entries are already free of retired rows; the retirements apply to what this client holds.
const { tail: currentTail, head: currentHead } = retireForPage({
payload,
tail: input.currentTail,
head: input.currentHead,
});
// ------------------------------------------------------------------
// Convert entries to timeline units
// ------------------------------------------------------------------
@@ -1292,12 +1367,12 @@ export function processTimelineResponse(
): Array<{
event: AgentStreamEventPayload;
timestamp: Date;
timelineCursor: { epoch: string; seq: number };
timelineCursor: TimelinePosition;
}> =>
units.map(({ event, timestamp, seqEnd }) => ({
units.map(({ event, timestamp, seq, seqEnd }) => ({
event,
timestamp,
timelineCursor: { epoch: payload.epoch, seq: seqEnd },
timelineCursor: { epoch: payload.epoch, seq: seqEnd, anchorSeq: seq },
}));
// ------------------------------------------------------------------
@@ -1432,7 +1507,7 @@ export function processTimelineResponse(
// ---------------------------------------------------------------------------
export interface ProcessAgentStreamEventInput {
event: AgentStreamEventPayload;
event: AgentStreamEventPayload | TimelineRewindEvent;
seq: number | undefined;
epoch: string | undefined;
currentTail: StreamItem[];
@@ -1455,7 +1530,7 @@ export interface ProcessAgentStreamEventOutput {
}
export interface AgentStreamReducerEvent {
event: AgentStreamEventPayload;
event: AgentStreamEventPayload | TimelineRewindEvent;
seq: number | undefined;
epoch: string | undefined;
timestamp: Date;
@@ -1573,11 +1648,70 @@ function processTimelineSequencingGate(input: {
};
}
/**
* Applies a live rewind in sequence with the stream. One that does not follow the loaded end is
* stale (already applied, or older than a page this client took) or leaves a gap to catch up.
*/
function processTimelineRewind(
input: ProcessAgentStreamEventInput & { event: TimelineRewindEvent },
): ProcessAgentStreamEventOutput {
const { event, seq, epoch, currentTail, currentHead, currentCursor } = input;
const unchanged: ProcessAgentStreamEventOutput = {
tail: currentTail,
head: currentHead,
changedTail: false,
changedHead: false,
cursor: null,
cursorChanged: false,
acknowledgedClientMessageIds: [],
sideEffects: [],
};
if (seq === undefined || epoch === undefined) return unchanged;
const decision =
input.hasAuthoritativeBaseline === false
? "overlay"
: classifySessionTimelineSeq({
cursor: currentCursor
? { epoch: currentCursor.epoch, endSeq: currentCursor.endSeq }
: null,
epoch,
seq,
});
if (decision === "gap" && currentCursor) {
return {
...unchanged,
sideEffects: [
{ type: "catch_up", cursor: { epoch: currentCursor.epoch, endSeq: currentCursor.endSeq } },
],
};
}
if (decision !== "accept" && decision !== "init" && decision !== "overlay") return unchanged;
const retired = retireRewoundStreamItems({
tail: currentTail,
head: currentHead,
epoch,
retirement: { seq, retireFromSeq: event.retireFromSeq },
});
let cursor: TimelineCursor | null = null;
if (decision === "accept" && currentCursor) cursor = { ...currentCursor, endSeq: seq };
if (decision === "init") cursor = { epoch, startSeq: seq, endSeq: seq };
return {
...unchanged,
tail: retired.tail,
head: retired.head,
changedTail: retired.tail !== currentTail,
changedHead: retired.head !== currentHead,
cursor,
cursorChanged: cursor !== null,
};
}
export function processAgentStreamEvent(
input: ProcessAgentStreamEventInput,
): ProcessAgentStreamEventOutput {
const event = input.event;
if (event.type === "rewind") return processTimelineRewind({ ...input, event });
const {
event,
seq,
epoch,
currentTail,
@@ -1596,7 +1730,7 @@ export function processAgentStreamEvent(
});
const timelineCursor =
event.type === "timeline" && seq !== undefined && epoch !== undefined
? { epoch, seq }
? { epoch, seq, anchorSeq: seq }
: undefined;
// ------------------------------------------------------------------
// Apply stream event to tail/head
@@ -1910,6 +2044,10 @@ export function createSessionAgentStreamReducerQueue(
};
},
commit: (agentId, result, events) => {
for (const { event, seq, epoch } of events) {
if (event.type !== "rewind" || seq === undefined || epoch === undefined) continue;
useSessionStore.getState().recordAgentTimelineRewind(serverId, agentId, { epoch, seq });
}
if (
result.changedTail ||
result.changedHead ||
@@ -237,6 +237,13 @@ function commitProcessedTimeline(input: {
const agentId = payload.agentId;
const store = useSessionStore.getState();
if (result.commit !== "discard") {
const latestRewindSeq = Math.max(...(payload.retirements ?? []).map(({ seq }) => seq));
if (Number.isFinite(latestRewindSeq)) {
store.recordAgentTimelineRewind(serverId, agentId, {
epoch: payload.epoch,
seq: latestRewindSeq,
});
}
store.applyAgentTimelineResponseState(serverId, agentId, {
items: result.tail,
head: result.head,
@@ -457,8 +464,14 @@ export type ViewedTimelineOwnerPorts = Omit<
| "applyCurrentTimeline"
>;
/**
* `stale`: the page was served before a rewind this client already applied, so it can hold rows
* that rewind retired. Nothing was applied; request the page again.
*/
export type TimelineResponseOutcome = "applied" | "stale";
export interface ViewedTimelineOwner extends ViewedTimelineSync {
applyTimelineResponse(payload: TimelineResponsePayload): void;
applyTimelineResponse(payload: TimelineResponsePayload): TimelineResponseOutcome;
/**
* Accepts one live stream event. Content is coalesced to the next frame; a turn boundary
* commits the turn's queued content before its liveness changes, so the view never shows
@@ -468,6 +481,37 @@ export interface ViewedTimelineOwner extends ViewedTimelineSync {
flushStreamAgent(agentId: string): void;
}
/**
* The latest retirement each chat has seen, live or on a page. Tail, older and prompt-jump pages
* are served from active rows at one moment; one served before that retirement can still hold the
* rows it retired, and has no retirement to drop them with. Forward pages are sequenced against
* the loaded end instead, so they are never stale here.
*/
function createRetirementHighWater() {
const latest = new Map<string, { epoch: string; seq: number }>();
function note(agentId: string, retirement: { epoch: string; seq: number }): void {
const current = latest.get(agentId);
if (current?.epoch === retirement.epoch && current.seq >= retirement.seq) return;
latest.set(agentId, retirement);
}
return {
note,
notePage(payload: TimelineResponsePayload): void {
for (const retirement of payload.retirements ?? []) {
note(payload.agentId, { epoch: payload.epoch, seq: retirement.seq });
}
},
servedBefore(payload: TimelineResponsePayload): boolean {
const known = latest.get(payload.agentId);
return (
payload.direction !== "after" &&
known?.epoch === payload.epoch &&
payload.window.maxSeq < known.seq
);
},
};
}
export function createViewedTimelineOwner(input: {
serverId: string;
replica: TimelineReplica;
@@ -477,6 +521,7 @@ export function createViewedTimelineOwner(input: {
ports: ViewedTimelineOwnerPorts;
}): ViewedTimelineOwner {
const forcedTailReplacements = new Set<string>();
const retirements = createRetirementHighWater();
const sync = createViewedTimelineSync({
...input.ports,
fetchLatestTail: async (agentId) => {
@@ -517,6 +562,8 @@ export function createViewedTimelineOwner(input: {
return {
...sync,
applyTimelineResponse(receivedPayload) {
if (retirements.servedBefore(receivedPayload)) return "stale";
retirements.notePage(receivedPayload);
const payload = consumeForcedTimelineTailReplacement(receivedPayload, forcedTailReplacements);
const accepted = applyAuthoritativeTimelineResponse({
serverId: input.serverId,
@@ -526,8 +573,12 @@ export function createViewedTimelineOwner(input: {
drainQueuedAgentMessage: input.drainQueuedAgentMessage,
});
if (accepted) input.replica.timelineUpdated(payload.agentId);
return "applied";
},
applyStreamEvent(agentId, event) {
if (event.event.type === "rewind" && event.epoch !== undefined && event.seq !== undefined) {
retirements.note(agentId, { epoch: event.epoch, seq: event.seq });
}
streamQueue.enqueue(agentId, event);
const turnLiveness = deriveAgentStreamTurnLiveness([event]);
if (turnLiveness.length === 0) return;
+7 -3
View File
@@ -1009,7 +1009,7 @@ describe("stream reducer canonical tool calls", () => {
});
it("keeps the timeline position on the whole assistant message", () => {
const timelineCursor = { epoch: "epoch-1", seq: 42 };
const timelineCursor = { epoch: "epoch-1", seq: 42, anchorSeq: 42 };
const result = applyStreamEvent({
tail: [],
head: [],
@@ -1890,7 +1890,7 @@ describe("turn lifecycle events", () => {
new Date("2025-01-01T15:03:11Z"),
{
source: "canonical",
timelineCursor: { epoch: "epoch-1", seq: 42 },
timelineCursor: { epoch: "epoch-1", seq: 42, anchorSeq: 42 },
},
);
@@ -1902,7 +1902,11 @@ describe("turn lifecycle events", () => {
assert.strictEqual(userMessage.messageId, "provider-owned-canonical");
assert.strictEqual(userMessage.text, "Analyze this");
assert.strictEqual(userMessage.timestamp.getTime(), submittedTimestamp.getTime());
assert.deepStrictEqual(userMessage.timelineCursor, { epoch: "epoch-1", seq: 42 });
assert.deepStrictEqual(userMessage.timelineCursor, {
epoch: "epoch-1",
seq: 42,
anchorSeq: 42,
});
assert.deepStrictEqual(userMessage.images, [image]);
assert.deepStrictEqual(userMessage.attachments, [attachment]);
});
+55 -15
View File
@@ -266,7 +266,7 @@ function produceUserMessage(
...presentation,
clientMessageId: incoming.clientMessageId ?? existing.clientMessageId,
messageId: incoming.messageId ?? existing.messageId,
timelineCursor: incoming.timelineCursor ?? existing.timelineCursor,
...advanceTimelinePosition(existing.timelineCursor, incoming.timelineCursor),
});
if (
existing.id === merged.id &&
@@ -482,7 +482,7 @@ function mergeRetainedLifecycleItem(tail: StreamItem[], retained: StreamItem): S
const next = [...tail];
next[tailIndex] = {
...existing,
timelineCursor: retained.timelineCursor,
...advanceTimelinePosition(existing.timelineCursor, retained.timelineCursor),
timestamp: retained.timestamp,
items: retained.items,
};
@@ -499,7 +499,7 @@ function mergeRetainedLifecycleItem(tail: StreamItem[], retained: StreamItem): S
const next = [...tail];
next[tailIndex] = {
...existing,
timelineCursor: retained.timelineCursor,
...advanceTimelinePosition(existing.timelineCursor, retained.timelineCursor),
status: "completed",
trigger: retained.trigger ?? existing.trigger,
preTokens: retained.preTokens ?? existing.preTokens,
@@ -519,7 +519,10 @@ function replaceTimelineIdentityItem(
const existing = items[index];
if (index < 0 || !existing || existing.kind !== "plugin") return null;
const next = [...items];
next[index] = retained;
next[index] = {
...retained,
...advanceTimelinePosition(existing.timelineCursor, retained.timelineCursor),
};
return next;
}
@@ -610,7 +613,11 @@ function preserveReplacementHead(
: `${tailAssistant.text}${liveAssistant.text}`;
const head = [
...unreconciledHead.slice(0, liveAssistantIndex),
{ ...liveAssistant, text },
{
...liveAssistant,
text,
...advanceTimelinePosition(tailAssistant.timelineCursor, liveAssistant.timelineCursor),
},
...unreconciledHead.slice(liveAssistantIndex + 1),
];
return {
@@ -625,7 +632,13 @@ function preserveReplacementHead(
const head = [
...unreconciledHead.slice(0, liveAssistantIndex),
{ ...liveAssistant, text: tailAssistant.text },
{
...liveAssistant,
text: tailAssistant.text,
...(liveAssistant.timelineCursor
? advanceTimelinePosition(tailAssistant.timelineCursor, liveAssistant.timelineCursor)
: {}),
},
...unreconciledHead.slice(liveAssistantIndex + 1),
];
return {
@@ -724,7 +737,27 @@ export interface AssistantMessageItem {
export interface TimelinePosition {
epoch: string;
/** The latest seq that changed this row. */
seq: number;
/** The seq the row started at. Updates never move it; rewinds retire rows by it. */
anchorSeq: number;
}
/**
* The position of a row after an update: it moves to the update's seq and stays anchored where it
* started. Without an incoming position the row keeps the one it has.
*/
export function advanceTimelinePosition(
existing: TimelinePosition | undefined,
incoming: TimelinePosition | undefined,
): { timelineCursor?: TimelinePosition } {
if (!incoming) return existing ? { timelineCursor: existing } : {};
if (!existing || existing.epoch !== incoming.epoch) return { timelineCursor: incoming };
const anchorSeq = Math.min(existing.anchorSeq, incoming.anchorSeq);
if (existing.seq === incoming.seq && existing.anchorSeq === anchorSeq) {
return { timelineCursor: existing };
}
return { timelineCursor: { ...incoming, anchorSeq } };
}
export type ThoughtStatus = "loading" | "ready";
@@ -983,7 +1016,7 @@ function appendAssistantMessage(
...last,
text: `${last.text}${chunk}`,
timestamp,
...(timelineCursor ? { timelineCursor } : {}),
...advanceTimelinePosition(last.timelineCursor, timelineCursor),
};
return [...state.slice(0, -1), updated];
}
@@ -1001,7 +1034,7 @@ function appendAssistantMessage(
...secondLast,
text: `${secondLast.text}${chunk}`,
timestamp,
...(timelineCursor ? { timelineCursor } : {}),
...advanceTimelinePosition(secondLast.timelineCursor, timelineCursor),
};
return [...state.slice(0, -2), updated, last];
}
@@ -1039,7 +1072,7 @@ function appendThought(
if (last && last.kind === "thought" && last.turnId === turnId) {
const updated: ThoughtItem = {
...last,
...(timelineCursor ? { timelineCursor } : {}),
...advanceTimelinePosition(last.timelineCursor, timelineCursor),
text: `${last.text}${chunk}`,
timestamp,
status: "loading",
@@ -1219,7 +1252,7 @@ export function mergeAgentToolCallItem(
return {
...existing,
...(timelineCursor ? { timelineCursor } : {}),
...advanceTimelinePosition(existing.timelineCursor, timelineCursor),
timestamp,
payload: {
source: "agent",
@@ -1325,7 +1358,11 @@ function appendPluginTimelineItem(
const existing = state[existingIndex];
if (!existing || existing.kind !== "plugin") return state;
const next = [...state];
next[existingIndex] = { ...nextItem, id: existing.id };
next[existingIndex] = {
...nextItem,
id: existing.id,
...advanceTimelinePosition(existing.timelineCursor, timelineCursor),
};
return next;
}
@@ -1356,7 +1393,7 @@ function appendTodoList(
const next = [...state];
next[previousIndex] = {
...previous,
...(timelineCursor ? { timelineCursor } : {}),
...advanceTimelinePosition(previous.timelineCursor, timelineCursor),
items: normalizedItems,
timestamp,
};
@@ -1375,7 +1412,7 @@ function appendTodoList(
const next = [...state];
next[next.length - 1] = {
...lastItem,
...(timelineCursor ? { timelineCursor } : {}),
...advanceTimelinePosition(lastItem.timelineCursor, timelineCursor),
items: normalizedItems,
activity: { type: "created", count: normalizedItems.length },
timestamp,
@@ -1520,7 +1557,7 @@ function reduceTimelineCompaction(
if (loadingIdx >= 0 && existing && existing.kind === "compaction") {
const updated: CompactionItem = {
...existing,
...(timelineCursor ? { timelineCursor } : {}),
...advanceTimelinePosition(existing.timelineCursor, timelineCursor),
status: "completed",
trigger: item.trigger ?? existing.trigger,
preTokens: item.preTokens ?? existing.preTokens,
@@ -1645,7 +1682,10 @@ export function reduceStreamUpdate(
),
event,
);
return event.item.type === "reasoning" ? updated : finalizeActiveThoughts(updated);
const stamped = event.turnMetrics?.length
? stampCompletedTurnMetrics(updated, event.turnMetrics, event.turnId)
: updated;
return event.item.type === "reasoning" ? stamped : finalizeActiveThoughts(stamped);
}
case "turn_completed":
return stampCompletedTurnMetrics(finalizeActiveThoughts(state), event.metrics, event.turnId);
@@ -1,12 +1,7 @@
export {
archiveWorkspaceWithUndo,
archiveWorkspacesWithUndo,
hasUndoableWorkspaceArchive,
undoLatestWorkspaceArchive,
type UndoableWorkspaceArchiveClient,
type UndoableWorkspaceArchiveEntryInput,
type WorkspaceArchiveBatchFailure,
type WorkspaceArchiveBatchResult,
} from "./internal/undo-window";
export { WorkspaceArchiveUndoShortcutHost } from "./internal/undo-shortcut-host";
export { supportsWorkspaceArchiveUndo } from "./internal/capability";
@@ -8,7 +8,6 @@ import { useSessionStore, type WorkspaceDescriptor } from "@/stores/session-stor
import { seedSessionHosts } from "@/test/seed-session";
import {
archiveWorkspaceWithUndo,
archiveWorkspacesWithUndo,
undoLatestWorkspaceArchive,
type UndoableWorkspaceArchiveClient,
} from "@/workspace/archive-undo";
@@ -83,9 +82,6 @@ function createToastHost() {
get shownTestID() {
return shown?.options?.testID ?? null;
},
get shownVariant() {
return shown?.options?.variant ?? null;
},
timeOut: () => shown?.dismiss(),
};
}
@@ -303,166 +299,3 @@ describe("archiveWorkspaceWithUndo", () => {
}).toEqual({ toast: null, undone: false, row: workspace("a") });
});
});
describe("archiveWorkspacesWithUndo", () => {
it("hides every workspace in the batch and undoes all of them together", async () => {
const host = createClient();
const toast = createToastHost();
const committed: string[] = [];
const batch = archiveWorkspacesWithUndo({
entries: [
{
client: host.client,
workspace: { serverId: SERVER_ID, workspaceId: "a" },
onArchiveCommitted: () => committed.push("a"),
},
{
client: host.client,
workspace: { serverId: SERVER_ID, workspaceId: "b" },
onArchiveCommitted: () => committed.push("b"),
},
],
toast: toast.api,
});
expect(storedWorkspace("a")).toBeUndefined();
expect(storedWorkspace("b")).toBeUndefined();
expect(toast.shownTestID).toBe("workspace-archived-toast");
expect(undoLatestWorkspaceArchive()).toBe(true);
expect({
a: storedWorkspace("a"),
b: storedWorkspace("b"),
undoA: host.undoRequested("a"),
undoB: host.undoRequested("b"),
toast: toast.shownTestID,
}).toEqual({
a: workspace("a"),
b: workspace("b"),
undoA: true,
undoB: true,
toast: null,
});
host.finishArchive("a", { canceled: true });
host.finishArchive("b", { canceled: true });
await expect(batch.then((result) => result.failures)).resolves.toEqual([]);
host.finishUndo("a");
host.finishUndo("b");
expect(committed).toEqual([]);
});
it("commits every workspace in the batch when the toast times out", async () => {
const host = createClient();
const toast = createToastHost();
const committed: string[] = [];
const batch = archiveWorkspacesWithUndo({
entries: [
{
client: host.client,
workspace: { serverId: SERVER_ID, workspaceId: "a" },
onArchiveCommitted: () => committed.push("a"),
},
{
client: host.client,
workspace: { serverId: SERVER_ID, workspaceId: "b" },
onArchiveCommitted: () => committed.push("b"),
},
],
toast: toast.api,
});
host.finishArchive("a");
host.finishArchive("b");
await expect(batch.then((result) => result.failures)).resolves.toEqual([]);
expect(committed).toEqual([]);
toast.timeOut();
expect(committed).toEqual(["a", "b"]);
});
it("restores only the failed workspace on partial failure and keeps undo open when surfacing the error", async () => {
const host = createClient();
const toast = createToastHost();
const committed: string[] = [];
const batch = archiveWorkspacesWithUndo({
entries: [
{
client: host.client,
workspace: { serverId: SERVER_ID, workspaceId: "a" },
onArchiveCommitted: () => committed.push("a"),
},
{
client: host.client,
workspace: { serverId: SERVER_ID, workspaceId: "b" },
onArchiveCommitted: () => committed.push("b"),
},
],
toast: toast.api,
});
host.finishArchive("a");
host.finishArchive("b", { error: "busy" });
const { failures, showPartialFailure } = await batch;
expect(failures).toHaveLength(1);
expect(failures[0]?.workspace.workspaceId).toBe("b");
expect(storedWorkspace("a")).toBeUndefined();
expect(storedWorkspace("b")).toEqual(workspace("b"));
// Updating the toast with the partial-failure error must not dismiss Undo or commit "a".
expect(showPartialFailure("busy")).toBe(true);
expect({
toast: toast.shownTestID,
variant: toast.shownVariant,
committed,
}).toEqual({
toast: "workspace-archived-toast",
variant: "error",
committed: [],
});
expect(undoLatestWorkspaceArchive()).toBe(true);
expect({ undoA: host.undoRequested("a"), undoB: host.undoRequested("b") }).toEqual({
undoA: true,
undoB: false,
});
expect(committed).toEqual([]);
});
it("commits surviving workspaces once a partial-failure undo toast times out", async () => {
const host = createClient();
const toast = createToastHost();
const committed: string[] = [];
const batch = archiveWorkspacesWithUndo({
entries: [
{
client: host.client,
workspace: { serverId: SERVER_ID, workspaceId: "a" },
onArchiveCommitted: () => committed.push("a"),
},
{
client: host.client,
workspace: { serverId: SERVER_ID, workspaceId: "b" },
onArchiveCommitted: () => committed.push("b"),
},
],
toast: toast.api,
});
host.finishArchive("a");
host.finishArchive("b", { error: "busy" });
const { showPartialFailure } = await batch;
expect(showPartialFailure("busy")).toBe(true);
expect(committed).toEqual([]);
toast.timeOut();
expect(committed).toEqual(["a"]);
expect(undoLatestWorkspaceArchive()).toBe(false);
});
});
@@ -17,28 +17,18 @@ export interface UndoableWorkspaceArchiveClient {
undoWorkspaceArchive: (workspaceId: string) => Promise<void>;
}
export interface UndoableWorkspaceArchiveEntryInput {
interface UndoWindowInput {
client: UndoableWorkspaceArchiveClient;
workspace: WorkspaceArchiveTarget;
onArchiveCommitted: () => void;
}
interface UndoWindowEntry extends UndoableWorkspaceArchiveEntryInput {
hidden: WorkspaceDescriptor | null;
archived: boolean;
failed: boolean;
committed: boolean;
}
interface UndoWindowInput {
entries: UndoWindowEntry[];
toast: ToastApi;
hidden: WorkspaceDescriptor | null;
onArchiveCommitted: () => void;
}
let latest: UndoWindow | null = null;
/**
* One archive batch's chance to be undone. It opens when the row(s) hide and closes when its toast
* One archive's chance to be undone. It opens when the row hides and closes when its toast
* leaves the screen (timeout, replaced by another toast, or undo).
*
* - `open`: undo is offered.
@@ -47,78 +37,40 @@ let latest: UndoWindow | null = null;
*/
class UndoWindow {
phase: "open" | "closed" | "undone" = "open";
private dismissToast: DismissToast = () => {};
private toastToken: object | null = null;
private archived = false;
private readonly dismissToast: DismissToast;
constructor(private readonly input: UndoWindowInput) {
this.showToast({ variant: "default" });
this.dismissToast = input.toast.show(<WorkspaceArchivedToast onUndo={this.undo} />, {
durationMs: WORKSPACE_ARCHIVE_UNDO_WINDOW_MS,
testID: "workspace-archived-toast",
onDismiss: this.close,
});
}
private showToast(options: { message?: string; variant: "default" | "error" }): void {
const token = {};
this.toastToken = token;
const remainingCount = this.input.entries.filter((entry) => !entry.failed).length;
this.dismissToast = this.input.toast.show(
<WorkspaceArchivedToast
count={remainingCount}
message={options.message}
onUndo={this.undo}
/>,
{
variant: options.variant,
layout: "action",
durationMs: WORKSPACE_ARCHIVE_UNDO_WINDOW_MS,
testID: "workspace-archived-toast",
onDismiss: () => {
// Replacing our own toast in place (for example to surface a partial failure) must not
// close the undo window or purge surviving workspaces.
if (this.toastToken !== token) return;
this.close();
},
},
);
/** The host finished the archive. It commits now if undo is no longer offered. */
archiveFinished(): void {
this.archived = true;
if (this.phase === "closed") this.commit();
}
/**
* Surfaces a partial-failure message on the active undo toast without dismissing Undo for the
* workspaces that did archive. Returns false once the window is closed, undone, or superseded.
*/
showPartialFailure(message: string): boolean {
if (this.phase !== "open" || latest !== this) return false;
this.showToast({ message, variant: "error" });
return true;
}
/** The host finished archiving this entry. It commits now if undo is no longer offered. */
entryFinished(entry: UndoWindowEntry): void {
entry.archived = true;
if (this.phase === "closed") this.commitEntry(entry);
}
/** The archive failed on the host. Dismisses the toast once every entry has failed. */
entryFailed(entry: UndoWindowEntry): void {
entry.failed = true;
if (this.input.entries.every((item) => item.failed)) {
this.close();
this.dismissToast();
}
/** The archive failed on the host, so there is nothing left to undo. */
archiveFailed(): void {
this.close();
this.dismissToast();
}
readonly close = (): void => {
if (this.phase !== "open") return;
this.phase = "closed";
this.release();
for (const entry of this.input.entries) {
if (entry.archived) this.commitEntry(entry);
}
if (this.archived) this.commit();
};
/** Commits unless the workspace is back by now, for example restored from another client. */
private commitEntry(entry: UndoWindowEntry): void {
if (entry.committed || entry.failed) return;
if (isWorkspaceListed(entry.workspace)) return;
entry.committed = true;
entry.onArchiveCommitted();
private commit(): void {
if (isWorkspaceListed(this.input.workspace)) return;
this.input.onArchiveCommitted();
}
readonly undo = (): boolean => {
@@ -126,19 +78,10 @@ class UndoWindow {
this.phase = "undone";
this.release();
this.dismissToast();
const undoable = this.input.entries.filter((entry) => !entry.failed);
void (async () => {
const results = await Promise.allSettled(
undoable.map((entry) => undoWorkspaceArchiveOptimistically(entry)),
);
const failed = results.filter(
(result): result is PromiseRejectedResult => result.status === "rejected",
);
if (failed.length > 0) {
console.warn("[workspace-archive-undo] undo failed", failed[0]?.reason);
this.input.toast.error(i18n.t("sidebar.workspace.toasts.undoArchiveFailed"));
}
})();
void undoWorkspaceArchiveOptimistically(this.input).catch((error: unknown) => {
console.warn("[workspace-archive-undo] undo failed", error);
this.input.toast.error(i18n.t("sidebar.workspace.toasts.undoArchiveFailed"));
});
return true;
};
@@ -147,75 +90,6 @@ class UndoWindow {
}
}
export interface WorkspaceArchiveBatchFailure {
workspace: WorkspaceArchiveTarget;
error: unknown;
}
export interface WorkspaceArchiveBatchResult {
failures: WorkspaceArchiveBatchFailure[];
/**
* Updates this batch's live undo toast to show a partial-failure error while keeping Undo active
* for the workspaces that succeeded. Returns false if the undo window is no longer open.
*/
showPartialFailure: (message: string) => boolean;
}
/**
* Archives one or more workspaces together and offers one undo until the toast goes away.
*
* `onArchiveCommitted` runs per workspace once that archive both finished on the host and can no
* longer be undone, and only if the workspace is still gone then. Returns failures for any
* workspace whose archive failed while not undone; those rows are already restored.
*/
export async function archiveWorkspacesWithUndo(input: {
entries: readonly UndoableWorkspaceArchiveEntryInput[];
toast: ToastApi;
}): Promise<WorkspaceArchiveBatchResult> {
if (input.entries.length === 0) {
return { failures: [], showPartialFailure: () => false };
}
const started = input.entries.map((entry) => {
const archive = beginOptimisticWorkspaceArchive(entry);
const windowEntry: UndoWindowEntry = {
...entry,
hidden: archive.hidden,
archived: false,
failed: false,
committed: false,
};
return { windowEntry, done: archive.done };
});
const window = new UndoWindow({
entries: started.map((item) => item.windowEntry),
toast: input.toast,
});
latest = window;
const failures: WorkspaceArchiveBatchFailure[] = [];
await Promise.all(
started.map(async ({ windowEntry, done }) => {
let outcome: Awaited<typeof done>;
try {
outcome = await done;
} catch (error) {
if (window.phase === "undone") return;
window.entryFailed(windowEntry);
failures.push({ workspace: windowEntry.workspace, error });
return;
}
if (outcome === "archived") window.entryFinished(windowEntry);
}),
);
return {
failures,
showPartialFailure: (message) => window.showPartialFailure(message),
};
}
/**
* Archives a workspace and offers to undo it until the toast goes away.
*
@@ -230,19 +104,19 @@ export async function archiveWorkspaceWithUndo(input: {
toast: ToastApi;
onArchiveCommitted: () => void;
}): Promise<void> {
const { failures } = await archiveWorkspacesWithUndo({
entries: [
{
client: input.client,
workspace: input.workspace,
onArchiveCommitted: input.onArchiveCommitted,
},
],
toast: input.toast,
});
if (failures[0]) {
throw failures[0].error;
const archive = beginOptimisticWorkspaceArchive(input);
const window = new UndoWindow({ ...input, hidden: archive.hidden });
latest = window;
let outcome: Awaited<typeof archive.done>;
try {
outcome = await archive.done;
} catch (error) {
if (window.phase === "undone") return;
window.archiveFailed();
throw error;
}
if (outcome === "archived") window.archiveFinished();
}
/** Undoes the most recent archive while its toast is up. Returns false when there is none. */
@@ -6,30 +6,17 @@ import { Button } from "@/components/ui/button";
import { Shortcut } from "@/components/ui/shortcut";
import { useShortcutKeys } from "@/hooks/use-shortcut-keys";
export function WorkspaceArchivedToast({
count = 1,
message: customMessage,
onUndo,
}: {
count?: number;
message?: string;
onUndo: () => void;
}) {
export function WorkspaceArchivedToast({ onUndo }: { onUndo: () => void }) {
const { t } = useTranslation();
const undoKeys = useShortcutKeys("undo-archive-workspace");
const undoShortcut = useMemo(
() => (undoKeys ? <Shortcut chord={undoKeys} style={styles.shortcut} /> : null),
[undoKeys],
);
const message =
customMessage ??
(count === 1
? t("sidebar.workspace.toasts.archived")
: t("sidebar.workspace.toasts.archivedCount", { count }));
return (
<View style={styles.row}>
<Text style={styles.message}>{message}</Text>
<Text style={styles.message}>{t("sidebar.workspace.toasts.archived")}</Text>
<Button
size="sm"
onPress={onUndo}
@@ -47,7 +34,7 @@ const styles = StyleSheet.create((theme) => ({
flexDirection: "row",
flexWrap: "wrap",
alignItems: "center",
gap: theme.spacing[3],
gap: theme.spacing[2],
},
// Cancels the badge's own inset, which would otherwise add to the button's gap.
shortcut: {
@@ -44,7 +44,6 @@ export const EyeOff = StubIcon;
export const File = StubIcon;
export const FileText = StubIcon;
export const Folder = StubIcon;
export const FolderOpen = StubIcon;
export const FolderPlus = StubIcon;
export const FolderTree = StubIcon;
export const Gift = StubIcon;
@@ -108,7 +107,6 @@ export const SquareSlash = StubIcon;
export const SquareTerminal = StubIcon;
export const Star = StubIcon;
export const Sun = StubIcon;
export const Tag = StubIcon;
export const Terminal = StubIcon;
export const Trash2 = StubIcon;
export const TriangleAlert = StubIcon;
+3
View File
@@ -47,5 +47,8 @@
"typescript": "^5.2.2",
"vitest": "^4.1.6",
"zx": "^8.8.5"
},
"engines": {
"node": ">=22.16.0"
}
}
@@ -146,6 +146,10 @@ export async function runAttachCommand(
const unsubscribe = client.subscribeAgentTimeline(resolvedId, (message) => {
if (message.type === "agent.timeline.replacement") {
console.log("\n[Timeline replaced; earlier output is no longer current]");
} else if (message.type === "agent.timeline.rewind") {
console.log(
"\n[Conversation rewound; output since the rewound message is no longer current]",
);
} else if (message.type === "agent.timeline.subscription_restored") {
console.log("\n[Reconnected; live output resumed. Events may have been missed.]");
} else if (message.type === "agent.timeline.error") {
+5 -1
View File
@@ -408,7 +408,6 @@ async function runFollowMode({
} catch (error) {
console.warn("Warning: failed to fetch existing timeline", error);
}
// Apply filter to existing items
if (options.filter) {
existingItems = existingItems.filter((item) => matchesFilter(item, options.filter));
@@ -439,6 +438,11 @@ async function runFollowMode({
notice("\n[Timeline replaced; earlier output is no longer current]");
return;
}
if (message.type === "agent.timeline.rewind") {
writer.end();
notice("\n[Conversation rewound; output since the rewound message is no longer current]");
return;
}
if (message.type === "agent.timeline.error") {
writer.end();
@@ -210,7 +210,12 @@ try {
console.log("Foreground SIGINT reached the supervisor. The worker and ACP processes exited.");
daemon = await startSupervisor();
const restoredIdle = (await daemon.client.fetchAgentTimeline(idle.id)).agent;
// The stored timeline is served without reopening the agent.
const storedIdle = (await daemon.client.fetchAgentTimeline(idle.id)).agent;
assert.equal(storedIdle?.status, "closed");
assert.equal(storedIdle?.requiresAttention, false);
await daemon.client.refreshAgent(idle.id);
const restoredIdle = (await daemon.client.fetchAgent(idle.id))?.agent;
assert.equal(restoredIdle?.status, "idle");
assert.equal(restoredIdle?.requiresAttention, false);
await waitFor(async () => {
+31
View File
@@ -211,6 +211,37 @@ test("SDK subscribers receive timeline replacement instead of silently losing hi
}
});
test("SDK subscribers receive a conversation rewind as a retired range", async () => {
const { createPaseoApi } = await import("./index");
const h = connection();
const received: unknown[] = [];
try {
const ready = h.client.connect();
h.open();
await ready;
const off = createPaseoApi(h.client)
.agents.ref("agent")
.timeline.subscribe((event) => received.push(event));
await off.ready;
h.receive({
type: "agent.timeline.rewind",
payload: {
agentId: "agent",
epoch: "epoch-1",
seq: 12,
retireFromSeq: 7,
subscriptionId: off.subscriptionId,
},
});
expect(received).toEqual([
{ agentId: "agent", event: { type: "rewind", epoch: "epoch-1", seq: 12, retireFromSeq: 7 } },
]);
off();
} finally {
await h.client.close();
}
});
test("local listeners create no demand before or after reconnect", async () => {
const h = connection();
try {
+1
View File
@@ -141,6 +141,7 @@ export const DEFAULT_CLIENT_CAPABILITIES = {
[CLIENT_CAPS.compactProviderSnapshots]: true,
[CLIENT_CAPS.providerSnapshotReferences]: true,
[CLIENT_CAPS.timelineReplacementInvalidation]: true,
[CLIENT_CAPS.timelineRewindOperations]: true,
[CLIENT_CAPS.timelineNotifications]: true,
[CLIENT_CAPS.pluginTimelineItems]: true,
[CLIENT_CAPS.workspaceSetupBlocked]: true,
+3 -1
View File
@@ -246,7 +246,9 @@ export class LegacySubscriptions {
);
case "agent.timeline.set_subscription.request":
return (
(message.type === "agent_stream" || message.type === "agent.timeline.replacement") &&
(message.type === "agent_stream" ||
message.type === "agent.timeline.replacement" ||
message.type === "agent.timeline.rewind") &&
(query.agentIds as string[]).includes(message.payload.agentId)
);
case "session.events.set_subscription.request":
@@ -1132,6 +1132,7 @@ test("advertises client capabilities in hello", async () => {
all_providers: true,
selective_agent_timeline: true,
timeline_replacement_invalidation: true,
timeline_rewind_operations: true,
provider_snapshot_references: true,
explicit_event_subscriptions: true,
owned_subscriptions: true,
+21 -1
View File
@@ -346,6 +346,14 @@ export type PaseoAgentTimelineEvent =
agentId: string;
event: { type: "replacement"; epoch: string };
}
| {
/**
* A conversation rewind removed the rows anchored in `[retireFromSeq, seq)` from the active
* history. Rows after `seq` belong to the rewound conversation.
*/
agentId: string;
event: { type: "rewind"; epoch: string; seq: number; retireFromSeq: number };
}
| {
agentId: string;
subscriptionId: string;
@@ -367,7 +375,9 @@ export interface PaseoAgentTimelineHandle {
* Delivers live events only. After reconnect, subscription_restored precedes
* subsequent updates. History may have been missed; use refetch() to request
* the range you need. No history is fetched automatically. A replacement event
* invalidates the previous epoch. Subscription errors release this observation.
* invalidates the previous epoch. A rewind event removes `[retireFromSeq, seq)`
* from the active history without changing the epoch. Subscription errors
* release this observation.
* Await the returned unsubscribe function's `ready` promise before starting
* work that must be observed. It rejects if establishment fails.
*/
@@ -1047,6 +1057,16 @@ function createAgentHandleFactory(
agentId: id,
event: { type: "replacement", epoch: message.payload.epoch },
});
case "agent.timeline.rewind":
return handler({
agentId: id,
event: {
type: "rewind",
epoch: message.payload.epoch,
seq: message.payload.seq,
retireFromSeq: message.payload.retireFromSeq,
},
});
}
}),
},
@@ -3,7 +3,7 @@ import type { OwnedSubscription, TimelineSubscription } from "../connection/inde
type TimelineUpdate = Extract<
SessionOutboundMessage,
{ type: "agent_stream" | "agent.timeline.replacement" }
{ type: "agent_stream" | "agent.timeline.replacement" | "agent.timeline.rewind" }
>;
/** Local SDK lifecycle messages; these are not additional wire RPCs. */
@@ -59,7 +59,11 @@ export function subscribeTimeline(
});
},
update: (message) => {
if (message.type === "agent_stream" || message.type === "agent.timeline.replacement")
if (
message.type === "agent_stream" ||
message.type === "agent.timeline.replacement" ||
message.type === "agent.timeline.rewind"
)
notify(message);
},
error: fail,
-5
View File
@@ -58,11 +58,6 @@
"types": "./dist/server/lifecycle.d.ts",
"source": "./src/server/lifecycle.ts",
"default": "./dist/server/lifecycle.js"
},
"./internal/windows-command": {
"types": "./dist/server/process-internal/windows-command.d.ts",
"source": "./src/server/process-internal/windows-command.ts",
"default": "./dist/server/process-internal/windows-command.js"
}
},
"publishConfig": {
+1 -34
View File
@@ -14,7 +14,6 @@ const entries = {
"./server/usage": "server",
"./server/acp": "server",
"./internal/lifecycle": "server",
"./internal/windows-command": "server",
"./client": "client",
"./client/host": "client",
"./client/ui": "client",
@@ -393,7 +392,7 @@ describe("lifecycle hook SDK types", () => {
it("infers payloads and replacement requests and requires async handlers and new names", () => {
expect(
typeErrors(`
import type { PluginServerContext, PluginHooks, PluginHookPayload, PluginHookResult, PluginLaunchWrap } from "@getpaseo/plugin/server";
import type { PluginServerContext, PluginHooks, PluginHookPayload, PluginHookResult } from "@getpaseo/plugin/server";
import type { AgentTimelineItem } from "@getpaseo/protocol/agent-types";
export default function contribute(server: PluginServerContext) {
server.addHook("worktree.create.before", async ({ request }) => {
@@ -428,38 +427,6 @@ describe("lifecycle hook SDK types", () => {
const { metadata, ...withoutMetadata } = request;
return withoutMetadata;
});
server.addHook("agent.create.before", async ({ request }) => {
const workspace: string | null = request.workspaceId;
// @ts-expect-error The agent's workspace is read-only.
request.workspaceId = "wks_other";
});
// Results built before workspaceId existed still typecheck; the daemon keeps the id.
server.addHook("agent.create.before", async ({ request }) => ({ config: request.config, env: request.env }));
server.before("agent.create", ({ request }) => ({ config: request.config, env: request.env }));
server.addHook("terminal.create.before", async ({ request }) => {
const source: "client" | "agent" | "script" | "worktree" = request.source;
const input: string | null = request.input;
const program: string | null = request.command;
// @ts-expect-error The terminal's workspace is read-only.
request.workspaceId = "wks_other";
// @ts-expect-error The terminal's program is read-only; return a wrap instead.
request.command = "/usr/bin/other";
const wrap: PluginLaunchWrap = ["/usr/bin/sandbox", "--workspace", request.workspaceId];
return { ...request, env: { A: "1" }, wrap };
});
server.addHook("command.run.before", async ({ request }) => {
const workspace: string | null = request.workspaceId;
const purpose: "setup" | "teardown" = request.purpose;
// @ts-expect-error A command's purpose is read-only.
request.purpose = "setup";
// @ts-expect-error The configured command is read-only; return a wrap instead.
request.command = "wrapper " + request.command;
return { ...request, wrap: ["/usr/bin/sandbox"] };
});
server.addHook("agent.open.before", async ({ request }) => ({
...request,
wrap: ["/usr/bin/sandbox", "--workspace", request.workspaceId ?? "none"],
}));
server.addHook("agent.turn.after", async (event, { paseo, signal }) => {
const { agent, outcome } = event;
const kind: "completed" | "failed" | "canceled" = outcome.kind;
@@ -86,8 +86,6 @@ export async function createAcpProviderConnection(
emit: () => undefined,
});
const supportedCapabilities: ProviderCapability[] = [...ADAPTER_CAPABILITIES];
// A connector stream has no process of its own to wrap.
if (options.command) supportedCapabilities.push("session.launch_wrap");
if (probe.agentCapabilities.promptCapabilities?.image) {
supportedCapabilities.push("prompt.image");
}
@@ -335,7 +333,6 @@ async function openSession(
boundarySessionId: input.sessionId,
cwd: input.config.cwd,
env: input.config.env,
wrap: input.config.wrap,
emit: state.emit,
onRetired: () => retireSession(state, input.sessionId),
});
@@ -378,7 +375,6 @@ interface StartRuntimeOptions {
boundarySessionId: string;
cwd?: string;
env: Readonly<Record<string, string>>;
wrap?: readonly [string, ...string[]];
emit(event: ProviderEvent): void;
onRetired?: () => void;
}
@@ -502,7 +498,6 @@ class AcpRuntime {
env: process.env,
};
child = spawnProcess(launch.command, launch.args, {
wrap: options.wrap,
cwd: options.cwd,
env: { ...launch.env, ...options.env },
stdio: "pipe",
@@ -516,7 +511,6 @@ class AcpRuntime {
>[1];
stream = ndJsonStream(output, input);
} else {
if (options.wrap) throw new Error("An ACP connector cannot run behind a launch wrap");
const owned = ownConnectorStream(await options.options.connector());
stream = owned.stream;
closeConnector = owned.close;

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