Compare commits

..
Author SHA1 Message Date
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
213 changed files with 9053 additions and 4955 deletions
-21
View File
@@ -1,26 +1,5 @@
# Changelog
## 0.16.2 - 2026-11-18
### Fixed
- Fixed Collapse turns hiding a finished reply when Claude answers a later background task notification ([#10092](https://github.com/getpaseo/paseo/pull/10092))
- Fixed detached worktree commits getting lost when archiving a workspace ([#10009](https://github.com/getpaseo/paseo/pull/10009) by [@ragokan](https://github.com/ragokan))
- Fixed Desktop updates leaving an older daemon running when an earlier Desktop session started it ([#10067](https://github.com/getpaseo/paseo/pull/10067))
- Fixed daemons losing their Hub connection after execution permissions changed ([#10113](https://github.com/getpaseo/paseo/pull/10113))
- Fixed saved hosts disappearing when one stored entry could not be read ([#9847](https://github.com/getpaseo/paseo/pull/9847) by [@ragokan](https://github.com/ragokan))
- Fixed worktree creation timing out while scanning large ignored folders that `.worktreeinclude` does not name ([#10020](https://github.com/getpaseo/paseo/pull/10020) by [@mgranderath](https://github.com/mgranderath))
- Fixed Steer cancelling a Claude compaction in progress ([#10028](https://github.com/getpaseo/paseo/pull/10028) by [@NightMachinery](https://github.com/NightMachinery))
- Fixed agents getting stuck after a second Stop when the provider reused the cancelled turn ID ([#9774](https://github.com/getpaseo/paseo/pull/9774) by [@DAnaeto](https://github.com/DAnaeto))
- Fixed Desktop staying blank after its renderer exited unexpectedly ([#10035](https://github.com/getpaseo/paseo/pull/10035))
- Fixed failed file downloads taking over the app window on web and Desktop ([#9937](https://github.com/getpaseo/paseo/pull/9937) by [@panta82](https://github.com/panta82))
- Fixed Import Session losing its scroll position when you select Load more ([#9974](https://github.com/getpaseo/paseo/pull/9974))
- Fixed terminals failing to open when the home filesystem refuses Unix sockets, such as on AFS ([#9214](https://github.com/getpaseo/paseo/pull/9214) by [@bendavid](https://github.com/bendavid))
- Fixed timed-out Git watchers repeatedly rescanning large repositories ([#9828](https://github.com/getpaseo/paseo/pull/9828) by [@Spshulem](https://github.com/Spshulem))
- Fixed `paseo workspace create --path .` using the local daemon's directory instead of the caller's ([#10010](https://github.com/getpaseo/paseo/pull/10010))
- Fixed MCP agent status and list responses omitting background work for idle agents ([#10022](https://github.com/getpaseo/paseo/pull/10022) by [@ortschun](https://github.com/ortschun))
- Fixed the thinking selector showing an old level after OMP changes it ([#9841](https://github.com/getpaseo/paseo/pull/9841) by [@dsingal0](https://github.com/dsingal0))
## 0.16.1 - 2026-11-17
### Fixed
-21
View File
@@ -1,26 +1,5 @@
# Changelog
## 0.16.2 - 2026-11-18
### 修复
- 修复启用“折叠轮次”时,Claude 回复后续后台任务通知导致上一条已完成的回复被折叠的问题 ([#10092](https://github.com/getpaseo/paseo/pull/10092))
- 修复归档工作区时丢失分离 HEAD 的 worktree 提交的问题 ([#10009](https://github.com/getpaseo/paseo/pull/10009),贡献者:[@ragokan](https://github.com/ragokan))
- 修复 Desktop 更新后,由上一次 Desktop 会话启动的旧版 daemon 仍在运行的问题 ([#10067](https://github.com/getpaseo/paseo/pull/10067))
- 修复更改执行权限后 daemon 与 Hub 断开连接的问题 ([#10113](https://github.com/getpaseo/paseo/pull/10113))
- 修复一条已保存的主机记录无法读取时,其他主机也消失的问题 ([#9847](https://github.com/getpaseo/paseo/pull/9847),贡献者:[@ragokan](https://github.com/ragokan))
- 修复创建 worktree 时,扫描 `.worktreeinclude` 未指定的大型忽略目录导致超时的问题 ([#10020](https://github.com/getpaseo/paseo/pull/10020),贡献者:[@mgranderath](https://github.com/mgranderath))
- 修复发送引导消息时取消 Claude 正在进行的上下文压缩的问题 ([#10028](https://github.com/getpaseo/paseo/pull/10028),贡献者:[@NightMachinery](https://github.com/NightMachinery))
- 修复 Provider 重用已取消的轮次 ID 时,再次停止导致 Agent 卡住的问题 ([#9774](https://github.com/getpaseo/paseo/pull/9774),贡献者:[@DAnaeto](https://github.com/DAnaeto))
- 修复 Desktop 渲染进程意外退出后窗口一直空白的问题 ([#10035](https://github.com/getpaseo/paseo/pull/10035))
- 修复 Web 和 Desktop 上文件下载失败时,错误页面占据应用窗口的问题 ([#9937](https://github.com/getpaseo/paseo/pull/9937),贡献者:[@panta82](https://github.com/panta82))
- 修复在“导入会话”中选择“加载更多”时丢失滚动位置的问题 ([#9974](https://github.com/getpaseo/paseo/pull/9974))
- 修复主目录所在的文件系统拒绝 Unix 套接字时无法打开终端的问题,例如 AFS ([#9214](https://github.com/getpaseo/paseo/pull/9214),贡献者:[@bendavid](https://github.com/bendavid))
- 修复 Git 监视器设置超时后反复扫描大型仓库的问题 ([#9828](https://github.com/getpaseo/paseo/pull/9828),贡献者:[@Spshulem](https://github.com/Spshulem))
- 修复 `paseo workspace create --path .` 使用本地 daemon 的目录而非命令所在目录的问题 ([#10010](https://github.com/getpaseo/paseo/pull/10010))
- 修复针对空闲 Agent 查询 MCP 状态或列表时漏报后台任务的问题 ([#10022](https://github.com/getpaseo/paseo/pull/10022),贡献者:[@ortschun](https://github.com/ortschun))
- 修复 OMP 更改思考级别后,选择器仍显示旧级别的问题 ([#9841](https://github.com/getpaseo/paseo/pull/9841),贡献者:[@dsingal0](https://github.com/dsingal0))
## 0.16.1 - 2026-11-17
### 修复
+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, 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
@@ -240,7 +240,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.
@@ -336,6 +337,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
+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 |
+8
View File
@@ -180,6 +180,14 @@ Terminal activity contributes to the workspace status bucket **per `workspaceId`
---
## Runtime-only Agent Timelines
Agent timelines are not written to `$PASEO_HOME`. `AgentTimeline` owns each agent's history behind
a backend, and the only backend is in memory, so a daemon restart loses it and the next resume
imports provider history. See [owned history](timeline-sync.md#owned-history).
---
## 2. Daemon Configuration
**Path:** `$PASEO_HOME/config.json`
+2 -2
View File
@@ -50,8 +50,8 @@ or without a control.
reject. A key the running session cannot apply (one the provider reads only when it opens) is
rejected too, so a stored option always describes what runs. Claude reads most options when it
starts its query, and replacing a started query would end its background work, so after the
first prompt only Fast and Ultracode can change. Codex fixes its approval policy and sandbox
when the thread starts, so it applies only `service_tier` and `plan_mode` live. A session with no
first prompt only Fast can change. Codex fixes its approval policy and sandbox when the thread
starts, so it applies only `service_tier` and `plan_mode` live. A session with no
`applyOptions` rejects every patch; the daemon enforces this. The provider returns the options
it ended up with when they differ from the request. The daemon stores the patch and that
result in one step after the call resolves. Throwing rejects the whole patch and none of it is
+63 -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,45 @@ 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. Deleting the agent deletes its history and every child's, retired ones
included.
`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 only backend keeps everything in
memory, so a daemon restart loses the owned history: the next resume imports provider history into
a new epoch, and clients take the destructive reset below. Rewinds retired before the restart come
back if the provider history still holds them. Retained history costs memory for every loaded,
closed or archived agent until the daemon exits or the agent is deleted.
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 +201,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 +214,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 +396,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 +412,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,8 +0,0 @@
Fixed
- Fixed Collapse turns hiding a finished reply when Claude answers a later background task notification
- Fixed detached worktree commits getting lost when archiving a workspace
- Fixed Desktop updates leaving an older daemon running when an earlier Desktop session started it
- Fixed daemons losing their Hub connection after execution permissions changed
- Fixed saved hosts disappearing when one stored entry could not be read
Full notes: https://paseo.sh/changelog
@@ -1,8 +0,0 @@
Fixed
- Fixed Collapse turns hiding a finished reply when Claude answers a later background task notification
- Fixed detached worktree commits getting lost when archiving a workspace
- Fixed Desktop updates leaving an older daemon running when an earlier Desktop session started it
- Fixed daemons losing their Hub connection after execution permissions changed
- Fixed saved hosts disappearing when one stored entry could not be read
Full notes: https://paseo.sh/changelog
@@ -1,8 +0,0 @@
Fixed
- Fixed Collapse turns hiding a finished reply when Claude answers a later background task notification
- Fixed detached worktree commits getting lost when archiving a workspace
- Fixed Desktop updates leaving an older daemon running when an earlier Desktop session started it
- Fixed daemons losing their Hub connection after execution permissions changed
- Fixed saved hosts disappearing when one stored entry could not be read
Full notes: https://paseo.sh/changelog
@@ -1,8 +0,0 @@
Fixed
- Fixed Collapse turns hiding a finished reply when Claude answers a later background task notification
- Fixed detached worktree commits getting lost when archiving a workspace
- Fixed Desktop updates leaving an older daemon running when an earlier Desktop session started it
- Fixed daemons losing their Hub connection after execution permissions changed
- Fixed saved hosts disappearing when one stored entry could not be read
Full notes: https://paseo.sh/changelog
+1 -1
View File
@@ -1 +1 @@
sha256-yLTaVMgu3tc/dgngJ7RP0htJcWE0ZtQ4mouypevyv0s=
sha256-k7+5S/4tyAmHdZmUdhpuZ7GOc7hp9cG8wUBFdJI32ng=
+28 -28
View File
@@ -1,12 +1,12 @@
{
"name": "paseo",
"version": "0.16.2",
"version": "0.16.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "paseo",
"version": "0.16.2",
"version": "0.16.1",
"hasInstallScript": true,
"license": "Apache-2.0",
"workspaces": [
@@ -37468,7 +37468,7 @@
},
"packages/app": {
"name": "@getpaseo/app",
"version": "0.16.2",
"version": "0.16.1",
"dependencies": {
"@codemirror/commands": "6.10.4",
"@codemirror/language": "6.12.4",
@@ -39637,13 +39637,13 @@
},
"packages/cli": {
"name": "@getpaseo/cli",
"version": "0.16.2",
"version": "0.16.1",
"license": "Apache-2.0",
"dependencies": {
"@clack/prompts": "^1.0.0",
"@getpaseo/client": "0.16.2",
"@getpaseo/protocol": "0.16.2",
"@getpaseo/server": "0.16.2",
"@getpaseo/client": "0.16.1",
"@getpaseo/protocol": "0.16.1",
"@getpaseo/server": "0.16.1",
"chalk": "^5.3.0",
"commander": "^12.0.0",
"mime-types": "^2.1.35",
@@ -39890,11 +39890,11 @@
},
"packages/client": {
"name": "@getpaseo/client",
"version": "0.16.2",
"version": "0.16.1",
"license": "Apache-2.0",
"dependencies": {
"@getpaseo/protocol": "0.16.2",
"@getpaseo/relay": "0.16.2",
"@getpaseo/protocol": "0.16.1",
"@getpaseo/relay": "0.16.1",
"ws": "^8.20.0",
"zod": "^4.4.3"
},
@@ -39906,7 +39906,7 @@
},
"packages/desktop": {
"name": "@getpaseo/desktop",
"version": "0.16.2",
"version": "0.16.1",
"license": "Apache-2.0",
"dependencies": {
"@getpaseo/cli": "*",
@@ -40149,7 +40149,7 @@
},
"packages/expo-two-way-audio": {
"name": "@getpaseo/expo-two-way-audio",
"version": "0.16.2",
"version": "0.16.1",
"license": "MIT",
"devDependencies": {
"@types/jest": "^29.5.14",
@@ -40195,7 +40195,7 @@
},
"packages/highlight": {
"name": "@getpaseo/highlight",
"version": "0.16.2",
"version": "0.16.1",
"license": "Apache-2.0",
"dependencies": {
"@codemirror/language": "6.12.4",
@@ -40225,7 +40225,7 @@
},
"packages/plugin": {
"name": "@getpaseo/plugin",
"version": "0.16.2",
"version": "0.16.1",
"license": "Apache-2.0",
"dependencies": {
"@agentclientprotocol/sdk": "^1.4.0",
@@ -40233,8 +40233,8 @@
"use-sync-external-store": "^1.6.0"
},
"devDependencies": {
"@getpaseo/client": "0.16.2",
"@getpaseo/protocol": "0.16.2",
"@getpaseo/client": "0.16.1",
"@getpaseo/protocol": "0.16.1",
"@types/node": "^20.9.0",
"@types/react": "~19.2.0",
"react": "19.2.3",
@@ -40244,8 +40244,8 @@
"zod": "^4.4.3"
},
"peerDependencies": {
"@getpaseo/client": "0.16.2",
"@getpaseo/protocol": "0.16.2",
"@getpaseo/client": "0.16.1",
"@getpaseo/protocol": "0.16.1",
"react": ">=19.1.0 <20",
"react-native": ">=0.81.5",
"zod": "^4.4.3"
@@ -40267,7 +40267,7 @@
},
"packages/protocol": {
"name": "@getpaseo/protocol",
"version": "0.16.2",
"version": "0.16.1",
"license": "Apache-2.0",
"dependencies": {
"semver": "^7.8.5",
@@ -40295,7 +40295,7 @@
},
"packages/relay": {
"name": "@getpaseo/relay",
"version": "0.16.2",
"version": "0.16.1",
"license": "Apache-2.0",
"dependencies": {
"@noble/ciphers": "^2.4.0",
@@ -40517,17 +40517,17 @@
},
"packages/server": {
"name": "@getpaseo/server",
"version": "0.16.2",
"version": "0.16.1",
"license": "Apache-2.0",
"dependencies": {
"@agentclientprotocol/sdk": "^0.17.1",
"@anthropic-ai/claude-agent-sdk": "0.3.326",
"@anthropic-ai/sdk": "^0.104.2",
"@getpaseo/client": "0.16.2",
"@getpaseo/highlight": "0.16.2",
"@getpaseo/plugin": "0.16.2",
"@getpaseo/protocol": "0.16.2",
"@getpaseo/relay": "0.16.2",
"@getpaseo/client": "0.16.1",
"@getpaseo/highlight": "0.16.1",
"@getpaseo/plugin": "0.16.1",
"@getpaseo/protocol": "0.16.1",
"@getpaseo/relay": "0.16.1",
"@isaacs/ttlcache": "^2.1.4",
"@modelcontextprotocol/sdk": "1.29.0",
"@opencode-ai/sdk": "1.14.46",
@@ -41474,7 +41474,7 @@
},
"packages/website": {
"name": "@getpaseo/website",
"version": "0.16.2",
"version": "0.16.1",
"dependencies": {
"@cloudflare/vite-plugin": "^1.29.1",
"@cloudflare/workers-types": "^4.20260317.1",
@@ -43084,7 +43084,7 @@
},
"plugins": {
"name": "@getpaseo/builtin-plugins",
"version": "0.16.2",
"version": "0.16.1",
"dependencies": {
"@getpaseo/plugin": "*",
"zod": "^4.4.3"
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "paseo",
"version": "0.16.2",
"version": "0.16.1",
"private": true,
"description": "Paseo: voice-controlled development environment for local AI coding agents",
"keywords": [
@@ -11,6 +11,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,
@@ -46,26 +53,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,
@@ -73,18 +156,91 @@ test.describe("Agent message rewind", () => {
await fillComposerDraft(page, preservedDraft);
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 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 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();
}
@@ -215,14 +215,14 @@ 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 submitMessage(page, replacementPrompt);
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());
@@ -232,7 +232,7 @@ test.describe("Rewind sheet", () => {
await selectRewindOption(page, "Rewind files");
await expect(page.getByTestId("rewind-menu-content")).toHaveCount(0);
await expectComposerDraft(page, "");
await expectUserMessageCount(page, 2);
await expectUserMessageCount(page, 1);
const preservedDraft = "Keep this human draft after rewind.";
await fillComposerDraft(page, preservedDraft);
@@ -243,7 +243,7 @@ test.describe("Rewind sheet", () => {
await selectRewindOption(page, "Rewind files");
await expect(page.getByTestId("rewind-menu-content")).toHaveCount(0);
await expectComposerDraft(page, preservedDraft);
await expectUserMessageCount(page, 2);
await expectUserMessageCount(page, 1);
await fillComposerDraft(page, "");
await composerLocator(page).evaluate((element) => element.blur());
@@ -253,7 +253,7 @@ test.describe("Rewind sheet", () => {
await selectRewindOption(page, "Rewind conversation and files");
await expect(page.getByTestId("rewind-menu-content")).toHaveCount(0);
await expectComposerDraft(page, replacementPrompt);
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,
};
}
@@ -56,20 +56,11 @@ function inFlightTurn(page: Page) {
return page.getByTestId("turn-working-indicator");
}
/**
* Presses a fork trigger until its menu shows.
*
* The in-flight turn's trigger sits below text that is still streaming in. While the chat is
* shorter than the viewport, each new line moves the trigger down. A line that arrives between
* the press and the release moves the trigger away from the pointer, so the press opens nothing,
* and the next press lands on the trigger where it is now.
*/
async function openForkMenu(page: Page, trigger: ReturnType<Page["getByRole"]>): Promise<void> {
const forkInNewTab = page.getByRole("menuitem", { name: "Fork in a new tab" });
await expect(async () => {
await trigger.click({ timeout: 5_000 });
await expect(forkInNewTab).toBeVisible({ timeout: 5_000 });
}).toPass({ timeout: 30_000 });
await trigger.click();
await expect(page.getByRole("menuitem", { name: "Fork in a new tab" })).toBeVisible({
timeout: 10_000,
});
}
export async function openMostRecentAssistantForkMenu(page: Page): Promise<void> {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/app",
"version": "0.16.2",
"version": "0.16.1",
"private": true,
"main": "index.ts",
"scripts": {
@@ -30,25 +30,6 @@ function answer(
}
describe("draft options model", () => {
it("retains an Ultracode option only after the current host advertises it", () => {
const model = openDraftOptions({ provider: "claude" });
const legacy = { provider: "claude", cwd: "/repo", thinkingOptionId: "ultracode" };
model.applyResolved(answer("claude", "old-host", {}, []));
expect(model.retainResolvedOption("ultracode", "old-host")).toBeUndefined();
expect(draftControlsRequest(model.getState(), legacy)).toEqual(legacy);
model.applyResolved(
answer("claude", "new-host", { ultracode: true }, [
{ type: "toggle", key: "ultracode", label: "Ultracode" },
]),
);
expect(model.retainResolvedOption("ultracode", "old-host")).toBeUndefined();
expect(model.retainResolvedOption("ultracode", "new-host")).toEqual({ ultracode: true });
expect(
draftControlsRequest(model.getState(), { ...legacy, thinkingOptionId: "high" }),
).toMatchObject({ thinkingOptionId: "high", providerOptions: { ultracode: true } });
});
it("draws a legacy Fast profile as the Fast tier the daemon resolved", () => {
const model = openDraftOptions({ provider: "codex", seed: { service_tier: "fast" } });
model.applyResolved(answer("codex", "k1", { service_tier: "priority" }));
@@ -47,7 +47,6 @@ export interface DraftOptionsModel {
applyProfile: (profile: { provider: string; options: ProviderOptions }) => void;
setRemembered: (remembered: ProviderOptions) => void;
setOption: (key: string, value: unknown) => void;
retainResolvedOption: (key: string, requestKey: string) => ProviderOptions | undefined;
applyResolved: (resolved: ResolvedDraftOptions) => void;
}
@@ -113,17 +112,6 @@ export function openDraftOptions(input: {
: { ...current, edits: { ...current.edits, [key]: value } },
);
},
retainResolvedOption: (key, requestKey) => {
const resolved = state.resolved;
if (resolved?.requestKey !== requestKey || key in state.edits) return undefined;
const value = resolved.options[key];
if (value === undefined || !resolved.controls.some((control) => control.key === key)) {
return undefined;
}
const patch = { [key]: value };
publish((current) => ({ ...current, edits: { ...current.edits, ...patch } }));
return patch;
},
applyResolved: (resolved) =>
publish((current) => ({
...current,
@@ -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(
@@ -1,7 +1,13 @@
import type { StreamItem, TimelinePosition } from "@/types/stream";
import 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 && item.timelineCursor) {
return {
boundaryCursor: item.timelineCursor,
boundaryCursor: { epoch: item.timelineCursor.epoch, seq: item.timelineCursor.seq },
...(item.messageId ? { boundaryMessageId: item.messageId } : {}),
};
}
@@ -140,7 +140,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"));
+5
View File
@@ -411,6 +411,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,
);
@@ -1167,6 +1171,7 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
agentId={agentId}
serverId={resolvedServerId}
epoch={timelineEpoch}
rewindSeq={timelineRewindSeq}
items={findItems}
viewportRef={viewportRef}
revealLoadedMessage={revealLoadedMessage}
@@ -6,6 +6,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";
@@ -18,6 +19,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);
@@ -26,12 +28,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}>
File diff suppressed because one or more lines are too long
@@ -215,32 +215,6 @@ describe("Mermaid sandbox runtime", () => {
expect(widths).toEqual([240, 350, 900]);
});
/**
* Agents often write a label that starts with a mention or holds an email address. Mermaid 11
* read the text up to the "@" as an edge id, so these diagrams failed to parse.
*/
it.each([
"flowchart LR\n F[@mention in any workspace] --> G[Look up token]",
"flowchart LR\n A[ops@example.com] --> B",
"flowchart LR\n A -->|@user approves| B",
"graph TD\n A(@x) --> B{@x?}",
])("renders a flowchart whose label contains an @: %s", async (source) => {
const frame = await mountRuntime();
const result = await render(frame, { revision: 1, source });
expect(result).toMatchObject({ type: "rendered", revision: 1, source });
});
it("still renders a flowchart edge id", async () => {
const frame = await mountRuntime();
const source = "flowchart LR\n A[Start] e1@--> B[End]";
const result = await render(frame, { revision: 1, source });
expect(result).toMatchObject({ type: "rendered", revision: 1, source });
});
it("coalesces queued input and never reports an obsolete result", async () => {
const frame = await mountRuntime();
const obsoleteSource = `flowchart TD\n${Array.from({ length: 250 }, (_, index) => `A${index} --> A${index + 1}`).join("\n")}`;
@@ -1,103 +0,0 @@
// @vitest-environment jsdom
import type { ReactNode } from "react";
import { cleanup, renderHook, waitFor } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { afterEach, beforeEach, expect, it } from "vitest";
import type { FileReadResult } from "@getpaseo/client/internal/daemon-client";
import { __setAttachmentStoreForTests } from "@/attachments/store";
import type { AttachmentStore } from "@/attachments/types";
import { useMarkdownSource, type MarkdownImageContext } from "./images";
import { PENDING_MARKDOWN_IMAGE } from "./source";
const memoryStore: AttachmentStore = {
storageType: "web-indexeddb",
async save(input) {
return {
id: input.id ?? "att_chart",
mimeType: input.mimeType ?? "image/png",
storageType: "web-indexeddb",
storageKey: input.id ?? "att_chart",
fileName: input.fileName,
createdAt: 1,
};
},
async encodeBase64() {
return "";
},
async resolvePreviewUrl() {
return "blob:chart";
},
async releasePreviewUrl() {},
async delete() {},
async garbageCollect() {},
};
function createHostFiles() {
const reads: { cwd: string; path: string }[] = [];
return {
reads,
async readFile(cwd: string, path: string): Promise<FileReadResult> {
reads.push({ cwd, path });
return {
kind: "image",
path,
mime: "image/png",
size: 4,
modifiedAt: "2026-11-18T00:00:00.000Z",
bytes: new Uint8Array([1, 2, 3, 4]),
};
},
};
}
beforeEach(() => {
__setAttachmentStoreForTests(memoryStore);
});
afterEach(() => {
cleanup();
__setAttachmentStoreForTests(null);
});
function renderMarkdownSource(text: string, initialProps: MarkdownImageContext) {
// No retries: a failed read settles at once. For a host's Markdown this is the state once the
// retries have run out on a host that is slow to connect.
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
const wrapper = ({ children }: { children: ReactNode }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
);
const rendered = renderHook((props: MarkdownImageContext) => useMarkdownSource(text, props), {
wrapper,
initialProps,
});
return { ...rendered, queryClient };
}
it("waits for the host's client before reading a workspace image", async () => {
const context = { serverId: "srv_test", workspaceRoot: "/repo" };
const { result, rerender, queryClient } = renderMarkdownSource("![Chart](chart.png)", {
...context,
client: null,
});
await waitFor(() => {
expect(queryClient.isFetching()).toBe(0);
expect(result.current.markdown.replace(PENDING_MARKDOWN_IMAGE, "pending")).toBe(
"![Chart](<pending>)",
);
});
const files = createHostFiles();
rerender({ ...context, client: files });
await waitFor(() => expect(result.current.imageSources).toEqual({ "blob:chart": "chart.png" }));
expect(files.reads).toEqual([{ cwd: "/repo", path: "chart.png" }]);
});
it("shows the alt text of a file image in Markdown that belongs to no host", async () => {
const { result } = renderMarkdownSource("![Chart](/tmp/chart.png)", {});
await waitFor(() =>
expect(result.current.markdown.replace(PENDING_MARKDOWN_IMAGE, "pending")).toBe("Chart"),
);
});
@@ -81,10 +81,7 @@ export function useMarkdownSource(
const results = useFetchQueries(
acquisitions.map((acquisition, index) => ({
queryKey: ["markdownImage", acquisition?.key ?? sources[index]],
// A host that hasn't connected yet has no client. Its images stay pending until it does: the
// key doesn't change when the client arrives, so a read that already failed would not run
// again. Markdown with no host has no client to wait for and falls back to its alt text.
enabled: acquisition !== null && (context.client != null || !context.serverId),
enabled: acquisition !== null,
immutableWhen: () => true,
dataShape: "value",
gcTime: 0,
@@ -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;
@@ -35,7 +36,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()
@@ -21,7 +21,7 @@ import { highlightDiffLines } from "@/utils/diff-highlight";
import { hasMeaningfulToolCallDetail } from "@/utils/tool-call-detail-state";
import { inlineUnistylesStyle } from "@/styles/unistyles-inline-style";
import { CODE_SURFACE_DATASET } from "@/styles/code-surface";
import { highlightToKeyedLines } from "@/utils/highlight-cache";
import { extensionFromPath, highlightToKeyedLines } from "@/utils/highlight-cache";
import { HighlightedLines } from "./highlighted-content";
import { DiffViewer } from "./diff-viewer";
import { getCodeInsets } from "./code-insets";
@@ -226,7 +226,7 @@ function ScrollableTextSection({
startLine,
}: ScrollableContentProps) {
const keyedLines = useMemo(
() => highlightToKeyedLines(content, filePath ?? null),
() => (filePath ? highlightToKeyedLines(content, extensionFromPath(filePath)) : null),
[content, filePath],
);
const body = (
@@ -82,10 +82,10 @@ describe("ComposerControls", () => {
expect(trigger.textContent).not.toContain("Large");
});
it("keeps the toolbar toggle name and flips it on press", () => {
it("flips a toggle on press in the toolbar", () => {
const onChange = vi.fn();
renderControls([{ ...base, type: "toggle", value: true, onChange }]);
fireEvent.click(screen.getByRole("button", { name: /^Context$/ }));
fireEvent.click(screen.getByRole("button", { name: "Context" }));
expect(onChange).toHaveBeenCalledWith(false);
});
@@ -94,12 +94,6 @@ describe("ComposerControls", () => {
expect(screen.getByRole("button", { name: "Context" }).textContent).toContain("On");
});
it("keeps the provider's tooltip for a toolbar toggle", () => {
const tooltip = "Fast is enabled but does not apply to this model.";
renderControls([{ ...base, type: "toggle", value: true, tooltip, onChange: () => undefined }]);
expect(screen.getByRole("button", { name: tooltip })).toBeDefined();
});
it("gives a sheet row's value the row's width, so a short value is not truncated", () => {
const toast = createToast();
render(
@@ -163,8 +157,6 @@ describe("ComposerControls", () => {
});
const FAST_ON = { fast_mode: true };
const ULTRACODE_ON = { ultracode: true };
const ignoreOption = () => undefined;
describe("provider option controls", () => {
const fastMode: AgentOptionControl = {
@@ -181,11 +173,7 @@ describe("provider option controls", () => {
onSetOption: (key: string, value: unknown) => void;
}) {
const optionControls = React.useMemo(
() => ({
controls: [fastMode, { key: "ultracode", label: "Ultracode", type: "toggle" as const }],
options,
onSetOption,
}),
() => ({ controls: [fastMode], options, onSetOption }),
[onSetOption, options],
);
const items = useAgentControlItems({
@@ -209,9 +197,4 @@ describe("provider option controls", () => {
fireEvent.click(screen.getByTestId("agent-feature-fast_mode"));
expect(writes).toEqual([["fast_mode", false]]);
});
it("announces the state of a provider toggle with no custom tooltip", () => {
render(<OptionControls options={ULTRACODE_ON} onSetOption={ignoreOption} />);
expect(screen.getByRole("button", { name: "Ultracode: On" })).toBeDefined();
});
});
@@ -28,7 +28,7 @@ interface ComposerControlBase {
title: string;
icon: AgentControlIcon;
/** Tints the icon; muted when absent. */
highlight?: "blue" | "green" | "purple" | "yellow";
highlight?: "blue" | "green" | "yellow";
/** Defaults to the title, or to "title: choice" on an icon-only select. */
tooltip?: string;
/** Defaults to the tooltip. */
@@ -393,7 +393,6 @@ function ComposerControlSlot({
const styles = StyleSheet.create((theme) => ({
fieldIcon: { color: theme.colors.foregroundMuted },
blue: { color: theme.colors.palette.blue[400] },
purple: { color: theme.colors.palette.purple[500] },
green: { color: theme.colors.palette.green[400] },
yellow: { color: theme.colors.palette.yellow[400] },
tooltipText: {
@@ -33,8 +33,6 @@ function getFeatureHighlight(
function toFeatureItem(
control: AgentOptionControl,
optionControls: ComposerOptionControls,
surface: ComposerControlSurface,
t: TFunction,
): ComposerControlItem {
const { options, onSetOption } = optionControls;
const base = {
@@ -45,15 +43,11 @@ function toFeatureItem(
testID: `agent-feature-${control.key}`,
};
if (control.type === "toggle") {
const enabled = readToggleOption(control, options);
const stateLabel = enabled ? t("agentControls.features.on") : t("agentControls.features.off");
return {
...base,
type: "toggle",
tooltip:
control.tooltip ??
(surface === "toolbar" ? `${control.label}: ${stateLabel}` : control.label),
value: enabled,
tooltip: getControlTooltip(control),
value: readToggleOption(control, options),
onChange: (value) => onSetOption(control.key, value),
};
}
@@ -98,11 +92,9 @@ export function useAgentControlItems({
const features = useMemo(
() =>
optionControls
? optionControls.controls.map((control) =>
toFeatureItem(control, optionControls, surface, t),
)
? optionControls.controls.map((control) => toFeatureItem(control, optionControls))
: [],
[optionControls, surface, t],
[optionControls],
);
return { thinking: thinkingItem, features };
}
@@ -1316,7 +1316,8 @@ export function DraftAgentControls({
return toThinkingControlOptions(thinkingOptions);
}, [thinkingOptions]);
const effectiveSelectedThinkingOption = selectedThinkingOptionId || mappedThinkingOptions[0]?.id;
const effectiveSelectedThinkingOption =
selectedThinkingOptionId || mappedThinkingOptions[0]?.id || undefined;
const modelOptions = useMemo<AgentControlOption[]>(
() =>
@@ -20,7 +20,6 @@ describe("feature metadata helpers", () => {
expect(getFeatureHighlightColor("fast_mode")).toBe("yellow");
expect(getFeatureHighlightColor("service_tier")).toBe("yellow");
expect(getFeatureHighlightColor("plan_mode")).toBe("blue");
expect(getFeatureHighlightColor("ultracode")).toBe("purple");
expect(getFeatureHighlightColor("other")).toBe("default");
});
});
@@ -8,7 +8,7 @@ import {
} from "@/agent-controls/policy";
export type ExplainedAgentControl = "mode" | "model" | "thinking";
export type FeatureHighlightColor = "blue" | "default" | "green" | "purple" | "yellow";
export type FeatureHighlightColor = "blue" | "default" | "green" | "yellow";
export type AgentControlHintKey =
| "agentControls.hints.thinking"
| "agentControls.hints.model"
@@ -48,8 +48,6 @@ export function getFeatureHighlightColor(featureId: string): FeatureHighlightCol
return "yellow";
case "auto_accept":
return "green";
case "ultracode":
return "purple";
case PLAN_MODE_FEATURE_ID:
return "blue";
default:
+2 -20
View File
@@ -22,7 +22,6 @@ import {
resolveEffectiveComposerThinkingOptionId,
type ProviderSelectionState,
} from "@/provider-selection/provider-selection";
import { findThinkingOptionReplacement } from "@/provider-selection/resolve-agent-form";
import { useDraftStore, type DraftInput } from "@/stores/draft-store";
import { AfterPaintPublication } from "@/composer/after-paint-publication";
import { useShallow } from "zustand/shallow";
@@ -294,7 +293,6 @@ export function useAgentInputDraft(input: UseAgentInputDraftInput): AgentInputDr
options: draftOptions,
shownOptions: draftShownOptions,
setOption: setDraftOption,
retainLegacyUltracode,
applyProfile: applyProfileOptions,
} = useDraftProviderOptions({
serverId: formState.selectedServerId,
@@ -314,11 +312,6 @@ export function useAgentInputDraft(input: UseAgentInputDraftInput): AgentInputDr
},
[applyProfileOptions, formState],
);
const setDraftThinking = useCallback(
(thinkingOptionId: string) =>
formState.setThinkingOptionFromUser(thinkingOptionId, retainLegacyUltracode()),
[formState, retainLegacyUltracode],
);
const commandDraft = useMemo(
() =>
@@ -337,18 +330,8 @@ export function useAgentInputDraft(input: UseAgentInputDraftInput): AgentInputDr
return null;
}
// COMPAT(claudeUltracodePreference): added in v0.17.0, remove after 2027-05-18.
const draftForm = {
...formState,
selectedThinkingOptionId:
findThinkingOptionReplacement(
formState.availableThinkingOptions,
formState.selectedThinkingOptionId,
) ?? formState.selectedThinkingOptionId,
setThinkingOptionFromUser: setDraftThinking,
};
return {
...draftForm,
...formState,
workingDir,
effectiveModeId,
effectiveModelId,
@@ -356,7 +339,7 @@ export function useAgentInputDraft(input: UseAgentInputDraftInput): AgentInputDr
providerOptions: draftOptions,
metadata,
agentControls: buildDraftAgentControls({
formState: draftForm,
formState,
optionControls: draftOptionControls,
options: draftShownOptions,
onSetOption: setDraftOption,
@@ -377,7 +360,6 @@ export function useAgentInputDraft(input: UseAgentInputDraftInput): AgentInputDr
draftOptions,
draftShownOptions,
setDraftOption,
setDraftThinking,
applyDraftAgentProfile,
formState,
metadata,
@@ -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;
@@ -4,7 +4,6 @@ import type {
AgentMode,
AgentModelDefinition,
AgentProvider,
ProviderOptions,
ProviderSnapshotEntry,
} from "@getpaseo/protocol/agent-types";
import { buildProviderDefinitions } from "@/utils/provider-definitions";
@@ -59,7 +58,7 @@ export interface UseAgentFormStateResult {
selectedModel: string;
setModelFromUser: (modelId: string) => void;
selectedThinkingOptionId: string;
setThinkingOptionFromUser: (thinkingOptionId: string, retainedOptions?: ProviderOptions) => void;
setThinkingOptionFromUser: (thinkingOptionId: string) => void;
workingDir: string;
providerDefinitions: AgentProviderDefinition[];
providerDefinitionMap: Map<AgentProvider, AgentProviderDefinition>;
@@ -420,7 +419,7 @@ export function useAgentFormState(options: UseAgentFormStateOptions): UseAgentFo
);
const setThinkingOptionFromUser = useCallback(
(thinkingOptionId: string, retainedOptions?: ProviderOptions) => {
(thinkingOptionId: string) => {
dispatch({ type: "SET_THINKING_OPTION_FROM_USER", thinkingOptionId });
const { provider, model: modelId } = formStore.getState().form;
if (provider && modelId) {
@@ -432,7 +431,6 @@ export function useAgentFormState(options: UseAgentFormStateOptions): UseAgentFo
thinkingByModel: {
[modelId]: thinkingOptionId,
},
options: retainedOptions,
},
}),
);
@@ -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"),
},
],
@@ -69,14 +69,6 @@ export function useDraftProviderOptions(input: {
[draftConfig, serverId],
);
const requestKey = JSON.stringify(queryKey);
// COMPAT(claudeUltracodePreference): added in v0.17.0, remove after 2027-05-18.
const retainLegacyUltracode = useCallback(
() =>
thinkingOptionId === "ultracode"
? model.retainResolvedOption("ultracode", requestKey)
: undefined,
[model, requestKey, thinkingOptionId],
);
const { data } = useFetchQuery({
queryKey,
@@ -137,7 +129,6 @@ export function useDraftProviderOptions(input: {
options: ownOptions,
shownOptions,
setOption,
retainLegacyUltracode,
applyProfile: model.applyProfile,
};
}
+2
View File
@@ -731,6 +731,8 @@ export const ar: TranslationResources = {
resumeCommandUnavailable: "أمر الاستئناف غير متوفر",
reloadingAgent: "وكيل إعادة التحميل...",
reloadedAgent: "وكيل إعادة تحميل",
reloadedAgentHistoryDiverged:
"تمت إعادة تحميل الوكيل، لكن سجل المزوّد لا يطابق هذه المحادثة، لذا لم تتم مزامنته",
failedToReloadAgent: "فشل في إعادة تحميل الوكيل",
failedToCloseAgent: "فشل في إغلاق الوكيل",
},
+2
View File
@@ -730,6 +730,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",
},
+2
View File
@@ -738,6 +738,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",
},
+2
View File
@@ -738,6 +738,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",
},
+2
View File
@@ -738,6 +738,8 @@ export const ja: TranslationResources = {
resumeCommandUnavailable: "再開コマンドが利用できません",
reloadingAgent: "エージェントを再読み込み中...",
reloadedAgent: "エージェントを再読み込みしました",
reloadedAgentHistoryDiverged:
"エージェントを再読み込みしましたが、プロバイダーの履歴がこのチャットと一致しないため同期しませんでした",
failedToReloadAgent: "エージェントの再読み込みに失敗しました",
failedToCloseAgent: "エージェントを閉じられませんでした",
},
+2
View File
@@ -733,6 +733,8 @@ export const ko: TranslationResources = {
resumeCommandUnavailable: "재개 명령을 사용할 수 없습니다",
reloadingAgent: "에이전트 다시 로드 중...",
reloadedAgent: "에이전트를 다시 로드했습니다",
reloadedAgentHistoryDiverged:
"에이전트를 다시 로드했지만 제공자 기록이 이 채팅과 일치하지 않아 동기화하지 않았습니다",
failedToReloadAgent: "에이전트를 다시 로드하지 못했습니다",
failedToCloseAgent: "에이전트를 닫지 못했습니다",
},
+2
View File
@@ -736,6 +736,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",
},
+2
View File
@@ -739,6 +739,8 @@ export const ru: TranslationResources = {
resumeCommandUnavailable: "Команда возобновления недоступна",
reloadingAgent: "Перезагрузка агента...",
reloadedAgent: "Агент перезагружен",
reloadedAgentHistoryDiverged:
"Агент перезагружен, но история провайдера не совпадает с этим чатом, поэтому она не синхронизирована",
failedToReloadAgent: "Не удалось перезагрузить агента",
failedToCloseAgent: "Не удалось закрыть агента",
},
+2
View File
@@ -731,6 +731,8 @@ export const zhCN: TranslationResources = {
resumeCommandUnavailable: "恢复命令不可用",
reloadingAgent: "正在重新加载 Agent...",
reloadedAgent: "已重新加载 Agent",
reloadedAgentHistoryDiverged:
"已重新加载 Agent,但提供方的历史记录与此对话不一致,因此未同步",
failedToReloadAgent: "重新加载 Agent 失败",
failedToCloseAgent: "关闭 Agent 失败",
},
@@ -167,14 +167,6 @@ function resolvePreferredThinkingOptionId(input: {
return "";
}
// COMPAT(claudeUltracodePreference): added in v0.17.0, remove after 2027-05-18.
export function findThinkingOptionReplacement(
options: NonNullable<AgentModelDefinition["thinkingOptions"]>,
legacyId: string,
): string | undefined {
return options.find((option) => option.metadata?.replacesThinkingOptionId === legacyId)?.id;
}
export function resolveThinkingOptionId(args: {
availableModels: AgentModelDefinition[] | null;
modelId: string;
@@ -191,9 +183,6 @@ export function resolveThinkingOptionId(args: {
) {
return normalizedThinkingOptionId;
}
if (findThinkingOptionReplacement(thinkingOptions, normalizedThinkingOptionId)) {
return normalizedThinkingOptionId;
}
return effectiveModel?.defaultThinkingOptionId ?? thinkingOptions[0]?.id ?? "";
}
@@ -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
@@ -246,6 +246,7 @@ const PROBE_STEADY_MS = 10_000;
const PROBE_MAX_BACKOFF_MS = 30_000;
const PROBE_INACTIVE_WHILE_ONLINE_MS = 120_000;
const ADAPTIVE_SWITCH_THRESHOLD_MS = 40;
const MAX_STALE_TIMELINE_PAGE_ATTEMPTS = 3;
const ADAPTIVE_SWITCH_CONSECUTIVE_PROBES = 3;
const CONFIGURED_OVERRIDE_BOOTSTRAP_RETRY_MS = 1_000;
@@ -2881,12 +2882,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(
@@ -184,7 +184,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 },
};
}
@@ -804,7 +804,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",
@@ -849,6 +849,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);
@@ -1212,7 +1238,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: {
@@ -20,6 +20,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";
@@ -80,7 +81,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(),
@@ -415,6 +424,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),
@@ -529,11 +542,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,
@@ -552,7 +574,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),
};
@@ -96,7 +96,6 @@ function scheduleOnHost(input: {
serverName: string;
cwd: string;
model: string;
provider?: string;
thinkingOptionId?: string | null;
cadence?: ScheduleSummary["cadence"];
}): TestSchedule {
@@ -110,7 +109,7 @@ function scheduleOnHost(input: {
target: {
type: "new-agent",
config: {
provider: input.provider ?? "mock",
provider: "mock",
cwd: input.cwd,
model: input.model,
modeId: "load-test",
@@ -187,56 +186,6 @@ function applyPreferences(form: ReturnType<typeof open>, preferences: FormPrefer
}
describe("schedule form model", () => {
it("keeps Ultra Code available in the schedule effort picker", () => {
const model = "claude-opus-4-8";
const form = open({
mode: "edit",
schedule: scheduleOnHost({
serverId: "host-a",
serverName: "Host A",
cwd: "/repo/a",
provider: "claude",
model,
thinkingOptionId: "ultracode",
}),
defaults: { serverId: null, projectTargets: PROJECT_TARGETS, preferences: {} },
});
form.applyProviderSnapshot("host-a", {
...providerSnapshot([]),
entries: [
{
provider: "claude",
status: "ready",
enabled: true,
models: [
{
provider: "claude",
id: model,
label: "Opus 4.8",
thinkingOptions: [
{ id: "high", label: "High" },
{
id: "xhigh",
label: "Extra high",
metadata: { replacesThinkingOptionId: "ultracode" },
},
],
},
],
},
],
});
expect(form.getState().selectedThinkingOptionId).toBe("ultracode");
expect(form.getState().availableThinkingOptions.map((option) => option.id)).toContain(
"ultracode",
);
form.setThinking("high");
expect(form.getState().selectedThinkingOptionId).toBe("high");
expect(form.getState().availableThinkingOptions.map((option) => option.id)).toContain(
"ultracode",
);
});
it("opens edit from the schedule host snapshot and completes that host resolution", () => {
const previous = open({
mode: "edit",
@@ -14,7 +14,6 @@ import {
import { filterSelectableModels, findModelByReference } from "@/provider-selection/model-catalog";
import {
buildProviderDefinitionMapForStatuses,
findThinkingOptionReplacement,
INITIAL_USER_MODIFIED,
RESOLVABLE_PROVIDER_STATUSES,
resolveDefaultModelId,
@@ -274,14 +273,7 @@ function resolveThinkingOptions(
modelId: string,
): NonNullable<AgentModelDefinition["thinkingOptions"]> {
const model = resolveEffectiveModel(resolveAvailableModels(entries, provider), modelId);
const options = model?.thinkingOptions ?? [];
// COMPAT(claudeUltracodePreference): added in v0.17.0, remove after 2027-05-18
// once schedules edit the Ultracode option independently.
// Schedules still use a single effort field.
return findThinkingOptionReplacement(options, "ultracode") &&
!options.some((option) => option.id === "ultracode")
? [...options, { id: "ultracode", label: "Ultra Code" }]
: options;
return model?.thinkingOptions ?? [];
}
function resolveModelDisplay(input: {
@@ -2215,11 +2215,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, {
@@ -2228,7 +2227,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"),
+32
View File
@@ -318,6 +318,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[] }
@@ -492,6 +498,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>;
@@ -611,6 +618,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>),
@@ -747,6 +760,7 @@ function createInitialSessionState(
agentTimelineUnsettledTurn: new Map(),
agentTimelineHasOlder: new Map(),
agentTimelineHasNewer: new Map(),
agentTimelineLatestRewind: new Map(),
agentTimelineOlderFetchInFlight: new Map(),
historySyncGeneration: 0,
agentHistorySyncGeneration: new Map(),
@@ -1388,6 +1402,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 },
}),
]);
});
@@ -4558,3 +4562,276 @@ describe("createAgentStreamReducerQueue", () => {
expect(scheduler.size).toBe(0);
});
});
// ---------------------------------------------------------------------------
// 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"]);
});
});
@@ -1,7 +1,13 @@
import type { 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 {
applyStreamEvent,
@@ -71,6 +77,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,
@@ -150,6 +214,7 @@ export interface ProcessTimelineResponseInput {
hasNewer: boolean;
hasOlder: boolean;
mergeWindow?: boolean;
retirements?: TimelineRetirement[];
};
currentTail: StreamItem[];
currentHead: StreamItem[];
@@ -394,7 +459,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 } =
@@ -758,7 +823,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") {
@@ -777,7 +842,7 @@ function replaceLiveAssistantWithProjectedText(params: {
...current,
text: event.item.text,
timestamp,
timelineCursor,
...advanceTimelinePosition(current.timelineCursor, timelineCursor),
};
return next;
}
@@ -827,7 +892,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];
@@ -944,8 +1009,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,
@@ -1144,10 +1209,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",
@@ -1179,7 +1244,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,
@@ -1237,8 +1307,6 @@ export function processTimelineResponse(
): ProcessTimelineResponseOutput {
const {
payload,
currentTail,
currentHead,
currentCursor,
isInitializing,
hasActiveInitDeferred,
@@ -1252,8 +1320,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",
@@ -1265,6 +1333,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
// ------------------------------------------------------------------
@@ -1289,12 +1364,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 },
}));
// ------------------------------------------------------------------
@@ -1429,7 +1504,7 @@ export function processTimelineResponse(
// ---------------------------------------------------------------------------
export interface ProcessAgentStreamEventInput {
event: AgentStreamEventPayload;
event: AgentStreamEventPayload | TimelineRewindEvent;
seq: number | undefined;
epoch: string | undefined;
currentTail: StreamItem[];
@@ -1452,7 +1527,7 @@ export interface ProcessAgentStreamEventOutput {
}
export interface AgentStreamReducerEvent {
event: AgentStreamEventPayload;
event: AgentStreamEventPayload | TimelineRewindEvent;
seq: number | undefined;
epoch: string | undefined;
timestamp: Date;
@@ -1570,11 +1645,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,
@@ -1593,7 +1727,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
@@ -1907,6 +2041,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]);
});
+51 -14
View File
@@ -264,7 +264,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 &&
@@ -480,7 +480,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,
};
@@ -497,7 +497,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,
@@ -517,7 +517,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;
}
@@ -608,7 +611,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 {
@@ -623,7 +630,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 {
@@ -720,7 +733,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";
@@ -966,7 +999,7 @@ function appendAssistantMessage(
...last,
text: `${last.text}${chunk}`,
timestamp,
...(timelineCursor ? { timelineCursor } : {}),
...advanceTimelinePosition(last.timelineCursor, timelineCursor),
};
return [...state.slice(0, -1), updated];
}
@@ -984,7 +1017,7 @@ function appendAssistantMessage(
...secondLast,
text: `${secondLast.text}${chunk}`,
timestamp,
...(timelineCursor ? { timelineCursor } : {}),
...advanceTimelinePosition(secondLast.timelineCursor, timelineCursor),
};
return [...state.slice(0, -2), updated, last];
}
@@ -1022,7 +1055,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",
@@ -1202,7 +1235,7 @@ export function mergeAgentToolCallItem(
return {
...existing,
...(timelineCursor ? { timelineCursor } : {}),
...advanceTimelinePosition(existing.timelineCursor, timelineCursor),
timestamp,
payload: {
source: "agent",
@@ -1308,7 +1341,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;
}
@@ -1339,7 +1376,7 @@ function appendTodoList(
const next = [...state];
next[previousIndex] = {
...previous,
...(timelineCursor ? { timelineCursor } : {}),
...advanceTimelinePosition(previous.timelineCursor, timelineCursor),
items: normalizedItems,
timestamp,
};
@@ -1358,7 +1395,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,
@@ -1503,7 +1540,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,
@@ -26,16 +26,6 @@ describe("highlightDiffLines", () => {
expect(add?.tokens?.some((token) => token.style === "keyword")).toBe(true);
});
it("highlights a Dockerfile diff using the filename", () => {
const diff = buildLineDiff("FROM alpine:3.21", "FROM alpine:3.22");
const result = highlightDiffLines(diff, "/repo/docker/Dockerfile");
expect(result.find((line) => line.type === "add")?.tokens).toContainEqual({
text: "FROM",
style: "keyword",
});
});
it("highlights a Codex-style unified diff with bare @@ headers (no line ranges)", () => {
const unified = ["@@", "-const x = 1;", "+const x = 2;", " const y = 3;"].join("\n");
const result = highlightDiffLines(parseUnifiedDiff(unified), "/repo/a.ts");
+6 -5
View File
@@ -1,5 +1,5 @@
import { isLanguageSupported, type HighlightToken } from "@getpaseo/highlight";
import { tokenizeToLines } from "@/utils/highlight-cache";
import { extensionFromPath, tokenizeToLines } from "@/utils/highlight-cache";
import type { DiffLine } from "@/utils/tool-call-parsers";
// The leading diff marker glyph for a line. The code on the line is the content
@@ -30,7 +30,7 @@ function diffLineCode(line: DiffLine): string {
}
// Attach syntax-highlight tokens to each diff line. Language comes from the file
// path. We reconstruct the old and new document text from the
// path (extension only). We reconstruct the old and new document text from the
// diff lines by position — counting context/remove into "old" and context/add
// into "new" — so this works regardless of whether the source diff carried real
// `@@ -n,m +n,m @@` line ranges (Codex emits bare `@@`). Each document is
@@ -41,10 +41,11 @@ export function highlightDiffLines(
diffLines: DiffLine[],
filePath: string | null | undefined,
): DiffLine[] {
const ext = extensionFromPath(filePath);
// Gate on real grammar support: an unsupported language would tokenize to a
// single style-less token per line, which would shadow the word-level change
// segments the diff already computes. Better to keep those.
if (!filePath || diffLines.length === 0 || !isLanguageSupported(filePath)) {
if (!ext || diffLines.length === 0 || !isLanguageSupported(`x.${ext}`)) {
return diffLines;
}
@@ -71,8 +72,8 @@ export function highlightDiffLines(
return { oldIndex: -1, newIndex: -1 };
});
const oldTokens = oldCode.length > 0 ? tokenizeToLines(oldCode.join("\n"), filePath) : null;
const newTokens = newCode.length > 0 ? tokenizeToLines(newCode.join("\n"), filePath) : null;
const oldTokens = oldCode.length > 0 ? tokenizeToLines(oldCode.join("\n"), ext) : null;
const newTokens = newCode.length > 0 ? tokenizeToLines(newCode.join("\n"), ext) : null;
if (!oldTokens && !newTokens) {
return diffLines;
}
+23 -2
View File
@@ -1,5 +1,26 @@
import { describe, expect, it } from "vitest";
import { highlightToKeyedLines, MAX_HIGHLIGHT_CHARS, tokenizeToLines } from "./highlight-cache";
import {
extensionFromPath,
highlightToKeyedLines,
MAX_HIGHLIGHT_CHARS,
tokenizeToLines,
} from "./highlight-cache";
describe("extensionFromPath", () => {
it("extracts a lowercased extension regardless of absolute/relative path", () => {
expect(extensionFromPath("/repo/src/Index.TS")).toBe("ts");
expect(extensionFromPath("src/index.ts")).toBe("ts");
expect(extensionFromPath("a.b/c.tsx")).toBe("tsx");
});
it("returns null for paths without a usable extension", () => {
expect(extensionFromPath(null)).toBeNull();
expect(extensionFromPath(undefined)).toBeNull();
expect(extensionFromPath("Makefile")).toBeNull();
expect(extensionFromPath(".gitignore")).toBeNull();
expect(extensionFromPath("trailingdot.")).toBeNull();
});
});
describe("tokenizeToLines", () => {
it("returns one token array per line for a supported language", () => {
@@ -9,7 +30,7 @@ describe("tokenizeToLines", () => {
expect(lines?.[0].some((token) => token.style === "keyword")).toBe(true);
});
it("returns null when there is no filename", () => {
it("returns null when there is no extension", () => {
expect(tokenizeToLines("whatever", null)).toBeNull();
});
+20 -9
View File
@@ -3,7 +3,7 @@ import { highlightCode, type HighlightToken } from "@getpaseo/highlight";
// Shared, theme-independent tokenization + cache for syntax highlighting.
// Used by markdown code blocks, file preview, and tool-call detail blocks
// (Edit diff / Write / Read). Colors are applied at render time, so the cache
// key is just (filename, code) and one entry serves both light and dark.
// key is just (extension, code) and one entry serves both light and dark.
export interface KeyedToken {
key: string;
@@ -44,17 +44,18 @@ class LRUCache<K, V> {
const tokenizationCache = new LRUCache<string, HighlightToken[][]>(200);
// Tokenize `code` to per-line tokens, cached. Returns null when the filename is absent,
// the input exceeds the size cap, or parsing throws.
export function tokenizeToLines(code: string, filename: string | null): HighlightToken[][] | null {
if (!filename) return null;
// Tokenize `code` to per-line tokens, cached. Returns null when the language is
// unsupported, the input is over the size cap, or parsing throws — callers then
// render plain text.
export function tokenizeToLines(code: string, ext: string | null): HighlightToken[][] | null {
if (!ext) return null;
if (code.length > MAX_HIGHLIGHT_CHARS) return null;
const cacheKey = `${filename.length}:${filename}${code}`;
const cacheKey = `${ext}:${code}`;
const cached = tokenizationCache.get(cacheKey);
if (cached) return cached;
let lines: HighlightToken[][];
try {
lines = highlightCode(code, filename);
lines = highlightCode(code, `x.${ext}`);
} catch {
return null;
}
@@ -72,7 +73,17 @@ function toKeyedLine(tokens: HighlightToken[], lineIndex: number): KeyedLine {
};
}
export function highlightToKeyedLines(code: string, filename: string | null): KeyedLine[] | null {
const lines = tokenizeToLines(code, filename);
export function highlightToKeyedLines(code: string, ext: string | null): KeyedLine[] | null {
const lines = tokenizeToLines(code, ext);
return lines ? lines.map(toKeyedLine) : null;
}
// Extension for grammar selection from a file path. We only need the suffix —
// absolute vs relative paths are equivalent here.
export function extensionFromPath(filePath: string | null | undefined): string | null {
if (!filePath) return null;
const name = filePath.split(/[\\/]/).pop() ?? filePath;
const dot = name.lastIndexOf(".");
if (dot <= 0 || dot === name.length - 1) return null;
return name.slice(dot + 1).toLowerCase();
}
@@ -92,11 +92,7 @@ const pinnedTheme = {
const testTheme = {
...lightTheme,
...pinnedTheme,
colors: {
...lightTheme.colors,
...pinnedTheme.colors,
palette: { ...lightTheme.colors.palette, ...pinnedTheme.colors.palette },
},
colors: { ...lightTheme.colors, ...pinnedTheme.colors },
};
type StyleFactory<T> = (theme: typeof testTheme) => T;
+4 -4
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/cli",
"version": "0.16.2",
"version": "0.16.1",
"description": "Paseo CLI - control your AI coding agents from the command line",
"license": "Apache-2.0",
"bin": {
@@ -29,9 +29,9 @@
},
"dependencies": {
"@clack/prompts": "^1.0.0",
"@getpaseo/client": "0.16.2",
"@getpaseo/protocol": "0.16.2",
"@getpaseo/server": "0.16.2",
"@getpaseo/client": "0.16.1",
"@getpaseo/protocol": "0.16.1",
"@getpaseo/server": "0.16.1",
"chalk": "^5.3.0",
"commander": "^12.0.0",
"mime-types": "^2.1.35",
@@ -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();
+3 -3
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/client",
"version": "0.16.2",
"version": "0.16.1",
"description": "Paseo client SDK package",
"license": "Apache-2.0",
"files": [
@@ -49,8 +49,8 @@
"measure:diff-materialization": "tsx scripts/measure-diff-materialization.ts"
},
"dependencies": {
"@getpaseo/protocol": "0.16.2",
"@getpaseo/relay": "0.16.2",
"@getpaseo/protocol": "0.16.1",
"@getpaseo/relay": "0.16.1",
"ws": "^8.20.0",
"zod": "^4.4.3"
},
+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
@@ -140,6 +140,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":
@@ -1130,6 +1130,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,
-24
View File
@@ -368,29 +368,6 @@ async function waitForGuestActiveElement(client, browserId, elementId) {
return false;
}
// A wait whose condition never matches must say which condition expired, not blame the host.
async function verifyExpiredWaitNamesItsCondition(client, targetUrl) {
const created = await callBrowserTool(client, "browser_new_tab", { url: targetUrl });
const browserId = created.browserId;
assert(typeof browserId === "string", "browser_new_tab returned no browserId for the wait page");
try {
await callBrowserTool(client, "browser_wait", { browserId, text: "Bridge target" });
// The page title is not body text, so this wait expires.
const response = await client.callTool({
name: "browser_wait",
args: { browserId, text: "Desktop browser target", timeoutMs: 1_000 },
});
const text = response.content?.[0]?.text;
assert(
response.structuredContent?.ok === false &&
text === "Timed out waiting for browser text: Desktop browser target",
`browser_wait did not name its expired condition: ${JSON.stringify(response.content)}`,
);
} finally {
await callBrowserTool(client, "browser_close_tab", { browserId });
}
}
// A page whose Content Security Policy omits 'unsafe-eval' refuses eval(); the tools must still work.
async function verifyEvaluateOnPageWithoutUnsafeEval(client, targetUrl) {
const created = await callBrowserTool(client, "browser_new_tab", {
@@ -814,7 +791,6 @@ async function runRegression({
await verifyReactFormFill((name, args) => callBrowserTool(client, name, args), targetUrl);
await verifyEvaluateOnPageWithoutUnsafeEval(client, targetUrl);
await verifyExpiredWaitNamesItsCondition(client, targetUrl);
const created = await callBrowserTool(client, "browser_new_tab", { url: targetUrl });
const browserId = created.browserId;
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/desktop",
"version": "0.16.2",
"version": "0.16.1",
"private": true,
"description": "Paseo desktop app (Electron wrapper)",
"homepage": "https://paseo.sh",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/expo-two-way-audio",
"version": "0.16.2",
"version": "0.16.1",
"description": "Native module for two way audio streaming",
"keywords": [
"ExpoTwoWayAudio",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/highlight",
"version": "0.16.2",
"version": "0.16.1",
"license": "Apache-2.0",
"files": [
"dist",
@@ -34,21 +34,6 @@ describe("highlightCode", () => {
expect(stringToken?.style).toBe("string");
});
it.each(["scripts/build.sh", "build.bash", "build.zsh"])("highlights shell in %s", (path) => {
const lines = highlightCode('export MESSAGE="hello"', path);
expect(lines[0]).toContainEqual({ text: "export", style: "keyword" });
expect(lines[0]).toContainEqual({ text: '"hello"', style: "string" });
});
it.each(["Dockerfile", "docker/Dockerfile", "C:\\docker\\Dockerfile", "build.dockerfile"])(
"highlights Docker instructions in %s",
(path) => {
const lines = highlightCode("FROM alpine\n# Build stage", path);
expect(lines[0]).toContainEqual({ text: "FROM", style: "keyword" });
expect(lines[1]).toEqual([{ text: "# Build stage", style: "comment" }]);
},
);
it("highlights Swift code", () => {
const code = 'struct Greeter {\n let message = "hello"\n}';
const result = highlightCode(code, "test.swift");
@@ -39,8 +39,6 @@ describe("isLanguageSupported", () => {
it("returns false for files without extensions", () => {
expect(isLanguageSupported("Makefile")).toBe(false);
expect(isLanguageSupported("src/ts")).toBe(false);
expect(isLanguageSupported("bin/bash")).toBe(false);
});
it("handles nested paths", () => {
+1 -21
View File
@@ -1,7 +1,5 @@
import { defineLanguageFacet, Language, StreamLanguage } from "@codemirror/language";
import { dart } from "@codemirror/legacy-modes/mode/clike";
import { dockerFile } from "@codemirror/legacy-modes/mode/dockerfile";
import { shell } from "@codemirror/legacy-modes/mode/shell";
import { swift } from "@codemirror/legacy-modes/mode/swift";
import { parser as jsParser } from "@lezer/javascript";
import { parser as jsonParser } from "@lezer/json";
@@ -30,9 +28,6 @@ function language(parser: Parser): Language {
return new Language(defineLanguageFacet(), parser);
}
const shellLanguage = StreamLanguage.define(shell);
const dockerfileLanguage = StreamLanguage.define(dockerFile);
const languagesByExtension: Record<string, Language> = {
// JavaScript/TypeScript
js: language(jsParser),
@@ -80,12 +75,6 @@ const languagesByExtension: Record<string, Language> = {
yml: language(yamlParser),
// Rust
rs: language(rustParser),
// Shell
sh: shellLanguage,
bash: shellLanguage,
zsh: shellLanguage,
// Docker
dockerfile: dockerfileLanguage,
// Swift
swift: StreamLanguage.define(swift),
// Dart
@@ -107,16 +96,7 @@ const languagesByExtension: Record<string, Language> = {
};
export function getLanguageForFile(filename: string): Language | null {
const basename = filename.slice(
Math.max(filename.lastIndexOf("/"), filename.lastIndexOf("\\")) + 1,
);
if (basename.toLowerCase() === "dockerfile") return dockerfileLanguage;
const dot = basename.lastIndexOf(".");
// Callers also pass bare language keys for code fences.
if (dot === -1 && basename !== filename) return null;
const ext = basename.slice(dot + 1).toLowerCase();
const ext = filename.split(".").pop()?.toLowerCase();
if (!ext) return null;
return languagesByExtension[ext] ?? null;
}
+5 -5
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/plugin",
"version": "0.16.2",
"version": "0.16.1",
"description": "Paseo plugin SDK package",
"license": "Apache-2.0",
"files": [
@@ -78,8 +78,8 @@
"use-sync-external-store": "^1.6.0"
},
"devDependencies": {
"@getpaseo/client": "0.16.2",
"@getpaseo/protocol": "0.16.2",
"@getpaseo/client": "0.16.1",
"@getpaseo/protocol": "0.16.1",
"@types/node": "^20.9.0",
"@types/react": "~19.2.0",
"react": "19.2.3",
@@ -89,8 +89,8 @@
"zod": "^4.4.3"
},
"peerDependencies": {
"@getpaseo/client": "0.16.2",
"@getpaseo/protocol": "0.16.2",
"@getpaseo/client": "0.16.1",
"@getpaseo/protocol": "0.16.1",
"react": ">=19.1.0 <20",
"react-native": ">=0.81.5",
"zod": "^4.4.3"
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/protocol",
"version": "0.16.2",
"version": "0.16.1",
"description": "Paseo shared protocol schemas and wire types",
"license": "Apache-2.0",
"files": [
@@ -39,6 +39,9 @@ export const CLIENT_CAPS = {
// COMPAT(timelineReplacementInvalidation): added in v0.5.0, remove legacy
// reconstructed timeline replay after 2027-02-21 once the client floor supports invalidation.
timelineReplacementInvalidation: "timeline_replacement_invalidation",
// COMPAT(timelineRewindOperations): added in v0.14.1, remove after 2027-05-10 once the client
// floor applies rewinds. Clients without it see a rewound history under a derived epoch.
timelineRewindOperations: "timeline_rewind_operations",
// COMPAT(timelineNotifications): added in v0.7.2. The daemon omits notification
// timeline items for older clients whose strict timeline union rejects them.
// Remove after 2027-03-03 once the supported client floor is >= v0.7.2.
+28
View File
@@ -4017,6 +4017,9 @@ export const ServerInfoStatusPayloadSchema = z
"terminal-grapheme-widths": z.boolean().optional(),
// COMPAT(rewind): added in v0.1.X, drop the gate when floor >= v0.1.X.
rewind: z.boolean().optional(),
// COMPAT(timelineRewindOperations): added in v0.14.1, remove gate after 2027-05-10.
// A conversation rewind arrives as `agent.timeline.rewind`, not a replacement.
timelineRewindOperations: z.boolean().optional(),
// COMPAT(agentTimelinePromptIndex): added in v0.2.X, drop the gate when floor >= v0.2.X.
agentTimelinePromptIndex: z.boolean().optional(),
// COMPAT(agentHistorySearch): added in v0.3.0, remove gate after 2027-02-07.
@@ -4214,6 +4217,8 @@ export const AgentResumedStatusPayloadSchema = z
export const AgentRefreshedStatusPayloadSchema = z
.object({
status: z.literal("agent_refreshed"),
/** The provider's history differs from the kept history, which Reload agent did not change. */
historyDiverged: z.boolean().optional(),
})
.extend(AgentStatusWithTimelineSchema.shape);
@@ -5072,6 +5077,12 @@ export const AgentTimelineEntryPayloadSchema = z.object({
collapsed: z.array(z.enum(["assistant_merge", "reasoning_merge", "tool_lifecycle", "identity"])),
});
/** Active rows anchored in `[retireFromSeq, seq)` left the conversation. `seq` is the retirement's own. */
export const AgentTimelineRetirementSchema = z.object({
seq: z.number().int().nonnegative(),
retireFromSeq: z.number().int().nonnegative(),
});
export const FetchAgentTimelineResponseMessageSchema = z.object({
type: z.literal("fetch_agent_timeline_response"),
payload: z.object({
@@ -5095,6 +5106,9 @@ export const FetchAgentTimelineResponseMessageSchema = z.object({
hasNewer: z.boolean(),
mergeWindow: z.boolean().optional(),
entries: z.array(AgentTimelineEntryPayloadSchema),
// COMPAT(timelineRewindOperations): added in v0.14.1. Retirements whose seq lies in the page's
// span; apply them before the entries. Sent only to clients with the capability.
retirements: z.array(AgentTimelineRetirementSchema).optional(),
error: z.string().nullable(),
}),
});
@@ -5108,6 +5122,18 @@ export const AgentTimelineReplacementMessageSchema = z.object({
}),
});
/** A conversation rewind retired active rows. Apply it when `seq` follows the loaded end. */
export const AgentTimelineRewindMessageSchema = z.object({
type: z.literal("agent.timeline.rewind"),
payload: z.object({
subscriptionId: z.string().optional(),
agentId: z.string(),
epoch: z.string(),
seq: z.number().int().nonnegative(),
retireFromSeq: z.number().int().nonnegative(),
}),
});
export const AgentTimelineSearchResponseMessageSchema = z.object({
type: z.literal("agent.timeline.search.response"),
payload: z.object({
@@ -7511,6 +7537,7 @@ export const SessionOutboundMessageSchema = z.discriminatedUnion("type", [
FetchAgentResponseMessageSchema,
FetchAgentTimelineResponseMessageSchema,
AgentTimelineReplacementMessageSchema,
AgentTimelineRewindMessageSchema,
AgentTimelineSearchResponseMessageSchema,
AgentTimelineListPromptsResponseMessageSchema,
ProviderSubagentListResponseMessageSchema,
@@ -8181,6 +8208,7 @@ export const WSHelloMessageSchema = z.object({
[CLIENT_CAPS.compactProviderSnapshots]: z.boolean().optional(),
[CLIENT_CAPS.providerSnapshotReferences]: z.boolean().optional(),
[CLIENT_CAPS.timelineReplacementInvalidation]: z.boolean().optional(),
[CLIENT_CAPS.timelineRewindOperations]: z.boolean().optional(),
[CLIENT_CAPS.timelineNotifications]: z.boolean().optional(),
[CLIENT_CAPS.backgroundAgents]: z.boolean().optional(),
[CLIENT_CAPS.browserHost]: BrowserAutomationHostCapabilitySchema.optional(),

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