Compare commits

...
Author SHA1 Message Date
Mohamed Boudra 73af0870d7 fix(timeline): keep idle text streams and item updates together
Adjacent idle text shares a display turn across coalescer windows. Resolve tool and plugin updates inside timeline ingestion, after checking retirement and before publishing the committed association.
2026-11-18 15:07:34 +01:00
Mohamed Boudra bd1a8925df fix(timeline): keep idle plugin item updates together
Identify deltas of one provider item through live admission so a snapshot sent while idle retains its turn. Test OMP without requiring its executable on the runner.
2026-11-18 15:02:19 +01:00
Mohamed Boudra 5bc12c4ec7 fix(timeline): keep finished replies visible after a background wake
Give root live rows explicit turn membership so an idle notice cannot join two completed replies. Preserve the turn attached to an existing tool or plugin item when it is updated.
2026-11-18 15:02:19 +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 0e67045c4b Keep Hub daemons connected after execution permissions change (#10113)
* Use current Hub permissions when reconnecting a daemon

* Back off when the Hub repeatedly rejects session permissions

* Show the permission recovery commands in Hub status
2026-11-18 19:24:41 +07:00
Mohamed Boudra 50b2c7f9d9 Give every natively supported provider a docs page (#10114)
Supported providers is now an index: one list of natively supported providers and one list of ACP agents from the in-app catalog. Each natively supported provider has a setup page under /docs/supported-providers/, and the docs sidebar shows those pages as one collapsible item. /docs/claude-code, /docs/codex, and /docs/muse-code redirect to the new location.

Also adds landing pages for fx and Hoplite, lists fx in the 0.16.0 changelog highlights, lists every docs page in llms.txt, and gives the plugin sidebar views page its frontmatter.
2026-11-18 19:15:14 +07:00
Mohamed Boudra f346e72691 fix(app): let the sidebar list scroll its last row clear of a toast (#10096)
The sidebar toast floats over the list's end, so at full scroll it covered the
last row. The list now ends with a spacer the height of the toast while one
shows. The spacer sits below every row, so growing it moves nothing. It shrinks
over the toast's fade, so a list scrolled into that space settles back with the
toast instead of snapping.

Unlike the permanent room removed in #9667, the space exists only while a toast
is up, so the list keeps its normal end the rest of the time.
2026-11-18 19:03:10 +07:00
paseo-bot[bot] a030e905e8 test(app): enter a workspace row afresh until its kebab shows (#10103)
The workspace-labels journey hovered a row once and then waited for its
kebab. The kebab mounts only while the row holds hover, and hover only
arrives on pointerenter, so a row that lost hover under a parked pointer
never showed it again and the click waited out the 3-minute test timeout.

openWorkspaceSidebarKebab now moves the pointer off the row and hovers it
again until the kebab is visible, and the labels journey uses it instead
of its own copy.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-18 12:00:38 +00:00
2a10550a02 Paste copied reply text as displayed in plain-text targets (#10079)
* fix(app): preserve literal text in selection copy

* fix(app): keep literal angle brackets in copied selection HTML

Unwrapping a recognized URL left displayed text such as
`<http://localhost:3000>` in the Markdown that feeds text/html. Turndown
does not escape `<`, so the clipboard renderer turned it into an
autolink and dropped the brackets. Escape `<` in the Markdown flavor.

Describe the renderer/copy link contract in docs/markdown-renderer.md
instead of restating the code.

Co-authored-by: Dan Berindei <dan.berindei@gmail.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(app): keep recognized web links and table pipes in rich and plain copy

Unwrapping recognized links in the shared copy DOM removed them from
both clipboard flavors, so a copied `#12` lost its forge URL in rich
paste. The renderer now marks recognized links with their own
attribute: text/plain carries them as the text the reply showed, and
text/html keeps them as links when they point to a web page. Workspace
paths stay plain text in both.

text/plain still emits tables as GFM syntax, so keep the cell-pipe
escape in both flavors.

Co-authored-by: Dan Berindei <dan.berindei@gmail.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(app): copy recognized Windows drive paths as text in rich paste

The rich-paste link check accepted any URI scheme, so `C:\repo\x.ts`
kept a link with an unopenable `C:` href. Keep recognized links in
text/html only for http and https URLs.

Co-authored-by: Dan Berindei <dan.berindei@gmail.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(app): keep split line-start Markdown literal in copied selection HTML

Selecting from the `#` in `**C#**` to the end of the paragraph left `#`
and ` for ...` as separate text nodes after unwrapping, so Turndown did
not escape the heading marker and rich paste showed a heading. Merge the
text nodes before serializing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Dan Berindei <dan.berindei@gmail.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 11:56:06 +00:00
Mohamed Boudra 32bdb9e7af Keep a finished reply visible when a notification arrives between turns (#10092)
* Keep a finished reply visible when Claude starts a turn after a background command

When a background command finishes while Claude is idle, Claude Code sends the
task notification first and opens its own turn after it. The notification row
was stored with no turn id. A row with no turn id joins the turn before it to
the turn after it, so under Collapse turns the app showed both turns as one and
folded the finished reply behind the summary row.

The Claude provider now keeps a task notification that arrives between turns
and emits it inside the turn Claude starts for it, so the row carries that
turn's id. A notification no turn follows is emitted as before: when Claude
reports idle (a command the user stopped), before the user's next message, and
on close.

Rows already stored without a turn id are not changed.

Refs #10030.

* Show a stopped background command's notification at once

A stopped background command starts no Claude turn. While a background
subagent is alive Claude also sends no idle, so the held row stayed hidden
until the subagent finished and then took the subagent's wake-up turn id.

Only task notifications Claude reacts to (completed or failed) wait for a
turn now. A stopped one is emitted right away, as before.

Refs #10030.

* Keep a row that belongs to no turn out of the turns around it

A turn starts with the user's message or the provider's own turn start
(Claude's init). A background command's notification that arrives
between turns starts nothing, so the daemon writes it with no turn ID.

The shared turn rule read a missing ID as legacy history and let the
row continue both neighbours. The reply before it and the turn after
it then read as one turn, and Collapse turns folded the first reply.

Now a row with no turn ID never continues a row that has one, so it
cannot join two turns. History with no IDs at all keeps the trigger
rule. The app's fold and the daemon's whole-turn paging share the rule.

This replaces the earlier Claude provider hold, which had to guess from
the notification's status whether Claude would start a turn for it.

Refs #10030

* Give a background task's notification the turn it starts

A background task's notification that arrives while no turn runs starts
a turn. Claude's next run belongs to it unless Claude announces another
start first: a later notification starts the next turn, and a queued
command (the user's message, a scheduled wake-up) starts its own. When
Claude does not respond, the notification is a turn in itself.

So a reply Claude writes for a finished background command shares the
notification's turn, and the reply before it stays in its own turn and
stays visible under Collapse turns. A stopped command's row shows at
once as its own turn, and the agent stays idle.

Claude sends no frame for a Monitor event, so a run it starts for one
belongs to the last notification before it.

This replaces the shared turn-rule change, which drew the notification
as a turn between the two.

Refs #10030

* Keep a subagent's own job notification out of the main session's turns

A background job a subagent started reports to that subagent, and
Claude starts no main-session run for it. Its notification gave the
next main-session run a new turn, so when it arrived between a main
command's notification and Claude's reply to it, the reply was drawn
in a different turn from the notification it answered.

Refs #10030
2026-11-18 18:51:31 +07:00
Dhruv Singalandfactory-droid[bot] a3c41ecc1d fix(omp): follow thinking level changes OMP makes on its own (#9841)
When OMP changed the thinking level itself, for example on `/switch @role`
with a role that carries a level, Paseo dropped the `thinking_level_changed`
event because the OMP runtime schema did not list it. The thinking selector
and `runtimeInfo.thinkingOptionId` kept the old level while OMP ran the new
one.

Parse the event and update the session's level, preferring OMP's
`configured` selector (for example "auto") over the effective level, the
same way the Pi provider handles it (#6741).

Closes #8249

Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
2026-11-18 10:48:22 +00:00
Mohamed Boudra 62fc15d77a feat(agents): show and stop heartbeats alongside background tasks (#10097) 2026-11-18 17:10:21 +07:00
Mohamed Boudra 59ca1f5f77 Replace Desktop's own daemon on update after Desktop relaunches (#10067)
An in-app update and the startup version check again use the desktopManaged flag in paseo.pid, while Manage built-in daemon is on. A daemon that an earlier Desktop session launched is now replaced on update. A daemon that the user started through the CLI is still never stopped automatically.

Closes #6385.
2026-11-18 16:05:12 +07:00
Mohamed Boudra 017f0d8b0d feat(cli): include labels and workspace IDs in agent listings (#10076)
Let scripts group a worker’s agents by label and workspace from a single listing.
2026-11-18 16:01:26 +07:00
Mohamed Boudra f1f2509c12 Keep Android composer taps working after zooming a chat image (#10057)
* fix(android): keep composer taps working after pinching an image

React Native counted two touches at the start of a pinch but received a native takeover cancellation for just one. Typing could then claim the responder and consume the first toolbar tap. Cancel the active contacts when the gesture handler takes over.

* docs(android): describe the chat image fixture for the pinch regression
2026-11-18 15:52:41 +07:00
Okan YILDIRIM 4f2fbe18af fix(archive): bound worktree teardown and stream its output (#9852)
Give worktree teardown commands a shared one-minute deadline. Projects can override it with `worktree.teardownTimeoutMs` in `paseo.json`. Drain output so successful teardowns can exceed the old 1 MiB buffer. Bound the output retained for diagnostics.

At the deadline, try to terminate the command, close its output streams, and keep the worktree on disk. An exit status of zero in response to the stop signal still counts as a timeout.

Closes #9857.

Co-authored-by: Okan YILDIRIM <63511519+ragokan@users.noreply.github.com>
2026-11-18 13:10:41 +07:00
paseo-bot[bot]andOkan YILDIRIM f81bc2b5a3 Keep the prompt and whole reply when an empty chat reconnects mid-reply (#9723)
Recover missing timeline rows when a chat was empty before disconnect and live reply rows arrive before history catch-up. Keep the replica cache at schema version 1.

Closes #9650.
Supersedes #9626.

Co-authored-by: Okan YILDIRIM <63511519+ragokan@users.noreply.github.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-18 12:59:03 +07:00
Monarch MaisuriyaandClaude Opus 5.5 3815e72359 fix(desktop): refuse browser screenshots with no painted pixels (#9807)
Viewport and full-page browser screenshots wait for a frame with non-transparent pixels. When the page does not paint within the existing capture budget, the tool returns screenshot_no_frame.

Fixes #9810.

Co-authored-by: monarchmaisuriya <monarchmaisuriya7600@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 12:47:31 +07:00
paseo-bot[bot]andmgranderath 871c714b46 Create worktrees in large repos without scanning every ignored file (#10020)
List ignored directories as single entries and only search inside them
when a .worktreeinclude pattern matches the directory or names a path
inside it. A bare .env no longer selects node_modules/pkg/.env.

Verified with real Git and isolated daemon workspace creation on Linux.
With 300,000 ignored files, Git trace2 recorded over 6,000 directory
visits before the fix and fewer than five after. The workspace copied
the root .env. The lifecycle test also verified rollback when copying
fails.

Closes #10004

Co-authored-by: mgranderath <22001111+mgranderath@users.noreply.github.com>
2026-11-18 12:26:35 +07:00
Mohamed Boudra f510b3edb7 Tell plugin agents to develop in a directory plugin, never a Git or npm installation (#10061)
* Tell plugin agents to develop in a directory plugin, never a Git or npm installation

paseo plugin update replaces a Git or npm installation and remove deletes it,
so edits and commits made in Paseo's managed copy are lost. The paseo-plugin
skill now says to clone the source outside the daemon home and install that
directory, and to move any work out of a managed copy before update or remove.

Refs #7904

* Rewrite the plugin development guidance as plain steps

* Keep settings, runtime ID, and build output when moving a plugin to a local folder
2026-11-18 12:05:21 +07:00
paseo-bot[bot]andClaude Opus 5.5 a75c2b4635 Keep background workspaces out of the dock badge and favicon (#9983)
* Keep background workspaces out of the dock badge and favicon

A workspace created with `--background` is hidden from the sidebar, but an
agent finishing in it still counted toward the macOS dock badge and turned
the web favicon to attention, pointing at something the user cannot see.

The dock badge now skips background workspaces, and the favicon skips
agents whose workspace is background, the same way both already skipped
background agents. The favicon selector also rescans when the workspace
map changes, so an agent synced before its workspace is dropped once the
workspace arrives.

Closes #9975

* Count background workspaces in the badge while Show background is on

The sidebar shows background workspaces when Show background is on, so
the dock badge and favicon now count them in that case too. They follow
the same setting the sidebar reads.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 04:55:46 +00:00
Mohamed Boudra 91e7293773 Hide historical PR badges on the default branch (#10053)
Hide closed and merged requests on the origin repository’s default branch. Keep branch-based status matching for feature workspaces.

Closes #9908.
2026-11-18 11:08:44 +07:00
paseo-bot[bot]andClaude Opus 5.5 63a33ac3fd Let plugin screens use the plugin state hooks (#10049)
* Let plugin screens use the plugin state hooks

A plugin screen opened from the Command Center or the sidebar showed
"Plugin failed: Plugin state hooks must run inside a plugin host" as soon
as it called useWorkspaces, useAgents or another state hook. Every plugin
host paired the installation provider with its own state provider, and
the screen host and the plugin settings host did not.

The installation provider now supplies the state source for the
installation's host, so every surface rendered under it can read state,
and the hosts no longer wrap a second provider of their own.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Keep a sidebar view's cross-host state in its hooks

A sidebar view renders once across every connected host and builds an
unscoped state source for that. After the installation provider took
over the state source, the environment provider dropped the view's own
source, so its hooks read state scoped to one host. The installation
provider now takes the surface's source when one is passed and falls
back to the installation's host.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 04:01:21 +00:00
paseo-bot[bot]andClaude Opus 5.5 a5edd91f91 Delete a stopped terminal worker's copy on Windows (#10039)
* fix(terminal): delete a stopped worker's copy on Windows

Windows keeps a just-exited worker's files open for a moment, so the
single rm in pruneTerminalWorkerRuntimes failed and left the copy until
the next daemon start. Retry the delete for up to 5.5s.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(terminal): bound the Windows retry of a worker copy delete

rm's maxRetries repeats at every directory level, so a file that stays
locked deep in node-pty would hold daemon start and stop far past the
intended window. Retry one rm per attempt for up to 3s instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 03:26:42 +00:00
paseo-bot[bot]andClaude Opus 5.5 e44edf5b35 Keep the sidebar's projects when the app renders while restoring hosts (#10042)
* fix(app): publish restored hosts together with their directory sync

A component that rendered while the host registry restored the project
icon cache saw the host but found no directory sync for it, so its
directory demand was dropped and the sidebar stayed on No projects yet
for the session. Hosts are now published in the same step that creates
their runtimes.

Fixes #9996

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(app): publish restored hosts through setHostsAndSync

Every host-list change now goes through the one method that assigns the
hosts, creates their runtimes, and notifies listeners in a single step.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 03:16:36 +00:00
Mohamed BoudraandOkan YILDIRIM 59d6018dac Preserve commits when archiving workspaces (#10009)
* fix(workspaces): preserve commits when archiving worktrees

A removed worktree can be the only reference to its HEAD. Keep that commit before deletion and record the checkout so detached workspaces restore at the same commit.

Co-authored-by: Okan YILDIRIM <63511519+ragokan@users.noreply.github.com>

* fix(workspaces): restore saved checkouts through one git path

Keep existing archive and deletion behavior when Git cannot read a worktree HEAD, and record every readable checkout for a common restore path.

* fix(workspaces): preserve git HEAD identity through restore

Record Git’s full HEAD ref or commit so restore can pass branch and detached checkouts to Git without guessing from a short name.

* fix(workspaces): scope saved HEAD to each archive

An archive with no readable checkout must not retain the HEAD saved by an earlier archive.

* test(workspaces): verify detached checkout after restore

Update the browser journey for detached restore and allow the daemon restart test enough time on Windows runners.

---------

Co-authored-by: Okan YILDIRIM <63511519+ragokan@users.noreply.github.com>
2026-11-18 10:10:45 +07:00
paseo-bot[bot]andClaude Opus 5.5 b24eab785b Reload the desktop window when its renderer exits (#10035)
* Reload the desktop window when its renderer exits

When the renderer process of the main window exits without a clean
shutdown (killed by an out-of-memory killer, crashed, or out of memory),
Electron keeps the window frame but shows nothing until the user presses
Ctrl+R. The main process had no handler for render-process-gone, so it
neither recovered nor logged the exit.

The window now reloads itself and logs the exit reason to main.log. If
the renderer exits three times within a minute, it stops reloading and
logs that, so a page that crashes on load does not restart in a loop.

Fixes #9999

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Leave a renderer exit before the first page commits to Chromium

Before the window's first navigation commits, Chromium finishes it in a
new renderer by itself. Reloading at that point aborted the initial
loadURL with ERR_ABORTED, which fails desktop startup. Skip the reload
while the window has no committed URL.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 02:04:06 +00:00
1821ac3f93 Let a steered message wait out a Claude compaction instead of cancelling it (#10028)
* Let a steer wait out a Claude compaction instead of cancelling it

While Claude compacted, the Claude session answered every steer with
"unavailable". The agent manager reads that as "replace the turn", so
it interrupted the turn and Claude Code printed "Compaction canceled.".
Claude Code already holds a `next`-priority message until compaction
finishes, so the session now accepts the steer during compaction.

Co-authored-by: NightMachinery <36224762+NightMachinery@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Steer only while the compaction is still running in the real Claude test

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: NightMachinery <36224762+NightMachinery@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 01:06:23 +00:00
a1088a787d Report background work from get_agent_status and list_agents (#10022)
The MCP agent tools serialized live agents without the background work
summary that the WebSocket snapshot carries, so a parent agent saw an
idle worker with a running background shell as plain idle. Both tools now
add the same summary the session adds, omitted when the agent has none.

Co-authored-by: Orcun Simsek <1612171+ortschun@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 22:54:59 +00:00
JIHUN LEEandClaude Opus 5.5 576d0320c8 Keep Android text at the window's density on Samsung DeX (#9995)
React Native 0.86 converts between px and dp with the density of the
phone's built-in display, while Fabric lays out at the window's density.
In a DeX window (240 dpi on a 360 dpi phone) every text box came out at
two thirds of the height its text needed, so the text was clipped.

Backport the rule from react/react-native#59087: right after React
Native reads the display (when it creates the root view and on each
configuration change), restore the window's density and keep only the
display's size. Remove once the app runs React Native 0.89 or later
with useWindowDensityForDisplayMetricsAndroid on.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 21:08:05 +00:00
paseo-bot[bot]andClaude Opus 5.5 c8e3d67e29 Wait for each plugin content subscription id before checking its release (#10012)
The plugin-buttons journey reads the details' event subscription id to
check that closing, crashing and disabling the content releases it. The
id arrives with the daemon's subscription response, after the details
render. The first open already waited for it; the reopens read it as
soon as the cached summary showed, so the id could still be empty and
the release poll then waited for an id that never exists.

Every read now waits for a non-empty id.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 18:01:24 +00:00
95f2c7d16a Keep a Claude agent's process and background work when its effort level changes (#10008)
Changing the thinking level of a running Claude agent marked its query for a
restart. The next turn, mode change or model change then retired the Claude
process, which ended every background shell, workflow and subagent it ran with
"connection lost".

A move between two effort levels now goes to the running query through
applyFlagSettings({ effortLevel }), as Fast mode already does, and marks no
restart. Switching thinking off, to ultracode or back to the default still
restarts, because those change how the query is launched. If the running
process does not take the change, the old restart path runs, so the change is
never lost.


Row: app-built-from-one-set
Paseo: c6210e21-fc13-4dfa-adfc-43a050c7d75a

Co-authored-by: gilad-rubin <6134299+gilad-rubin@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 16:57:22 +00:00
paseo-bot[bot]andClaude Opus 5.5 2c2385f362 Create the workspace in the caller's directory when --path is relative (#10010)
* Create the workspace in the caller's directory when --path is relative

`paseo workspace create --path .` adopted the daemon's working directory
instead of the directory the command ran in. The CLI sent the relative
path unchanged, and the daemon resolved it against its own cwd. The CLI
now resolves a relative --path against the caller's directory before it
sends the request, as it already does when --path is omitted. Absolute
POSIX and Windows paths pass through unchanged so a remote daemon on
another operating system still gets the path as written.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Leave a home-relative --path for the daemon to expand

Resolving every non-absolute --path against the caller's directory turned
`--path=~/repo` (and a quoted "~/repo") into `<cwd>/~/repo`. Before this
change the daemon expanded the leading ~ itself. `~` and `~/…` now pass
through unchanged again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Send a relative --path to an explicit daemon endpoint as written

The CLI already resolves caller paths only for a local daemon and sends
them unchanged to an explicit --host endpoint (resolveRepositoryDirectory,
project create). workspace create, and paseo run, which builds its
workspace source through it, now follow the same rule instead of turning
a relative path into a path on the caller's machine for a remote daemon.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 15:51:43 +00:00
paseo-bot[bot]andDominic Anaeto 7f0fe57c48 Settle a stuck agent run after a repeated cancel (#9774)
A force-cancel finalizes turn X in the daemon while the provider keeps
running it, so the next run can be bound to the same X. handleStreamEvent
dropped every terminal for a finalized turn id, including the synthetic
turn_canceled that cancelAgentRunNow dispatches for the tracked run and
the provider's own terminal. The run never settled, cancelAgentRunNow
waited on it forever, and every later cancel, reload and send queued
behind it until the daemon restarted.

A terminal for the tracked run's own turn id is no longer dropped.

Fixes #6355
Supersedes #8405

Co-authored-by: Dominic Anaeto <dominic.anaeto@gmail.com>
2026-11-17 15:08:26 +00:00
paseo-bot[bot]andClaude Opus 5.5 94f2df6263 Keep the Import Session list in place when Load more fetches the next page (#9974)
Tapping Load more emptied the list until the larger page arrived: the sheet
showed "Loading sessions...", unmounted the virtualized list, and brought it
back scrolled to the top. The sessions queries set keepPreviousData, but
useQueries gives a changed key a new observer with no previous data, so the
placeholder was always empty. The placeholder is now the cached page that
Load more grew from, for the same scope, search, and provider.

The compact import-session journey flaked on this in CI: its scroll helper
resolved a row, the list was replaced before the helper ran, and the walk
up from the detached row found no scroller. The helper now scrolls the list
itself, and the journey checks that Load more keeps the reader down the
list.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 12:00:55 +00:00
paseo-bot[bot]andpanta82 02124454bc Keep failed downloads inside the app on web and desktop (#9937)
On web and desktop, Download over a direct connection now fetches the file and saves it from a blob instead of navigating the window to the host URL. A rejected or unreachable download shows an error in the download toast and the app stays on the workspace. The daemon's HTTP CORS check uses the same origin rule as the WebSocket upgrade.

Closes #9895

Co-authored-by: panta82 <4291324+panta82@users.noreply.github.com>
2026-11-17 08:04:50 +00: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
318 changed files with 15974 additions and 3796 deletions
+1 -1
View File
@@ -23,6 +23,7 @@
- **Plugin sidebar views:** Plugins can replace the sidebar with their own workspace and agent layout across connected hosts. Choose a view per device in Settings → Sidebar. ([#8906](https://github.com/getpaseo/paseo/pull/8906))
- **Plugin composer controls:** Plugins can add composer controls, edit drafts and attachments, and change agent settings. They can also add New workspace items and save metadata on agents and workspaces. ([#8744](https://github.com/getpaseo/paseo/pull/8744), [#9209](https://github.com/getpaseo/paseo/pull/9209), [#9207](https://github.com/getpaseo/paseo/pull/9207), [#9734](https://github.com/getpaseo/paseo/pull/9734) by [@michaelmwu](https://github.com/michaelmwu))
- **Arrange Usage cards:** Drag provider cards into your preferred order and turn off cards you do not want in the sidebar summary. Choose the host from Usage settings. ([#9660](https://github.com/getpaseo/paseo/pull/9660), [#9740](https://github.com/getpaseo/paseo/pull/9740), [#9748](https://github.com/getpaseo/paseo/pull/9748), [#9780](https://github.com/getpaseo/paseo/pull/9780))
- **fx provider:** Run [fx](https://paseo.sh/docs/supported-providers/fx), the coding agent from Vercel Labs, in Paseo. Add it from the provider catalog in Settings → Hosts → Providers. ([#9160](https://github.com/getpaseo/paseo/pull/9160))
- **Quieter app reopening:** Returning to an unchanged chat no longer flashes “Updating messages.” Paseo keeps healthy connections open and recovers dropped connections when you return. After reconnecting, an up-to-date chat no longer shows an extra update toast. ([#9242](https://github.com/getpaseo/paseo/pull/9242), [#8651](https://github.com/getpaseo/paseo/pull/8651), [#9086](https://github.com/getpaseo/paseo/pull/9086), [#8855](https://github.com/getpaseo/paseo/pull/8855), [#9116](https://github.com/getpaseo/paseo/pull/9116), [#9558](https://github.com/getpaseo/paseo/pull/9558) by [@adamcstephens](https://github.com/adamcstephens))
- **Rebuilt mobile chat:** Expanding turn summaries, todo cards and tool groups keeps your reading position on iOS and Android. Sending during a scroll moves to the new prompt. ([#8717](https://github.com/getpaseo/paseo/pull/8717), [#9085](https://github.com/getpaseo/paseo/pull/9085), [#9806](https://github.com/getpaseo/paseo/pull/9806), [#9693](https://github.com/getpaseo/paseo/pull/9693))
- **Faster diff loading:** Changes shows the file tree before file contents finish loading. Large diffs load in batches and take priority over background worktree scans. ([#8907](https://github.com/getpaseo/paseo/pull/8907), [#9241](https://github.com/getpaseo/paseo/pull/9241), [#9243](https://github.com/getpaseo/paseo/pull/9243), [#9584](https://github.com/getpaseo/paseo/pull/9584))
@@ -36,7 +37,6 @@
- Added a Change base picker for worktree diffs, commits and Git actions ([#8642](https://github.com/getpaseo/paseo/pull/8642), [#8934](https://github.com/getpaseo/paseo/pull/8934) by [@Myasuka](https://github.com/Myasuka))
- Added issue and pull request links that resolve SSH aliases and fork parent repositories ([#8636](https://github.com/getpaseo/paseo/pull/8636), [#9576](https://github.com/getpaseo/paseo/pull/9576))
- Added an iPhone Duo layout with the sidebar and workspace on opposite sides of the fold ([#8741](https://github.com/getpaseo/paseo/pull/8741), [#8901](https://github.com/getpaseo/paseo/pull/8901) by [@zeyugao](https://github.com/zeyugao))
- Added fx as a provider you can add from the provider catalog in Settings → Hosts → Providers ([#9160](https://github.com/getpaseo/paseo/pull/9160))
- Added background agents that stay out of tabs, notifications and default agent lists ([#8683](https://github.com/getpaseo/paseo/pull/8683))
- Added syntax highlighting for Terraform and HCL files (`.tf`, `.tfvars`, `.hcl`) ([#9106](https://github.com/getpaseo/paseo/pull/9106))
- Added `PASEO_WORKSPACE_ID` to each agent's environment so an agent can identify, rename or archive its own workspace ([#8939](https://github.com/getpaseo/paseo/pull/8939) by [@DTTerastar](https://github.com/DTTerastar))
+1 -1
View File
@@ -23,6 +23,7 @@
- **插件侧边栏视图**:插件可以用自己的布局替换侧边栏,展示已连接主机上的工作区和 Agent。在“设置 → 侧边栏”中为每台设备选择视图。 ([#8906](https://github.com/getpaseo/paseo/pull/8906))
- **插件 Composer 控件**:插件可以添加 Composer 控件、编辑草稿和附件,以及更改 Agent 设置。插件还可以添加“新建工作区”条目,并在 Agent 和工作区上保存元数据。 ([#8744](https://github.com/getpaseo/paseo/pull/8744), [#9209](https://github.com/getpaseo/paseo/pull/9209), [#9207](https://github.com/getpaseo/paseo/pull/9207), [#9734](https://github.com/getpaseo/paseo/pull/9734),贡献者:[@michaelmwu](https://github.com/michaelmwu))
- **排列用量卡片**:拖动 Provider 卡片来调整顺序,并关闭不想在侧边栏摘要中显示的卡片。在用量设置中选择主机。 ([#9660](https://github.com/getpaseo/paseo/pull/9660), [#9740](https://github.com/getpaseo/paseo/pull/9740), [#9748](https://github.com/getpaseo/paseo/pull/9748), [#9780](https://github.com/getpaseo/paseo/pull/9780))
- **fx Provider**:在 Paseo 中运行 Vercel Labs 的编程 Agent [fx](https://paseo.sh/zh-CN/docs/supported-providers/fx)。在“设置 → Hosts → 提供方”的 Provider 目录中添加。 ([#9160](https://github.com/getpaseo/paseo/pull/9160))
- **返回应用时更少提示**:返回没有变化的聊天时,不再闪现“正在更新消息”。Paseo 会保留可用的连接,并在你返回时恢复断开的连接。重连后,已是最新状态的聊天也不再显示额外的更新提示。 ([#9242](https://github.com/getpaseo/paseo/pull/9242), [#8651](https://github.com/getpaseo/paseo/pull/8651), [#9086](https://github.com/getpaseo/paseo/pull/9086), [#8855](https://github.com/getpaseo/paseo/pull/8855), [#9116](https://github.com/getpaseo/paseo/pull/9116), [#9558](https://github.com/getpaseo/paseo/pull/9558),贡献者:[@adamcstephens](https://github.com/adamcstephens))
- **重建移动端聊天**:在 iOS 和 Android 上展开轮次摘要、待办卡片和工具组时,阅读位置保持不变。滚动期间发送消息会移到新提示词处。 ([#8717](https://github.com/getpaseo/paseo/pull/8717), [#9085](https://github.com/getpaseo/paseo/pull/9085), [#9806](https://github.com/getpaseo/paseo/pull/9806), [#9693](https://github.com/getpaseo/paseo/pull/9693))
- **更快的 diff 加载**:“更改”在文件内容加载完成前先显示文件树。大型 diff 分批加载,且优先于后台 worktree 扫描。 ([#8907](https://github.com/getpaseo/paseo/pull/8907), [#9241](https://github.com/getpaseo/paseo/pull/9241), [#9243](https://github.com/getpaseo/paseo/pull/9243), [#9584](https://github.com/getpaseo/paseo/pull/9584))
@@ -36,7 +37,6 @@
- 为 worktree 的 diff、提交和 Git 操作新增基准分支选择器(Change base) ([#8642](https://github.com/getpaseo/paseo/pull/8642), [#8934](https://github.com/getpaseo/paseo/pull/8934),贡献者:[@Myasuka](https://github.com/Myasuka))
- 新增可解析 SSH 别名和 fork 上游仓库的 Issue 和 PR 链接 ([#8636](https://github.com/getpaseo/paseo/pull/8636), [#9576](https://github.com/getpaseo/paseo/pull/9576))
- 新增 iPhone Duo 布局,侧边栏和工作区分列折痕两侧 ([#8741](https://github.com/getpaseo/paseo/pull/8741), [#8901](https://github.com/getpaseo/paseo/pull/8901),贡献者:[@zeyugao](https://github.com/zeyugao))
- 新增 fx Provider,可在“设置 → Hosts → 提供方”的 Provider 目录中添加 ([#9160](https://github.com/getpaseo/paseo/pull/9160))
- 新增后台 Agent,不占用标签页、不发送通知,也不出现在默认 Agent 列表中 ([#8683](https://github.com/getpaseo/paseo/pull/8683))
- 新增 Terraform 和 HCL 文件(`.tf`、`.tfvars`、`.hcl`)的语法高亮 ([#9106](https://github.com/getpaseo/paseo/pull/9106))
- 在每个 Agent 的环境中新增 `PASEO_WORKSPACE_ID`,Agent 可据此识别、重命名或归档自己的工作区 ([#8939](https://github.com/getpaseo/paseo/pull/8939),贡献者:[@DTTerastar](https://github.com/DTTerastar))
+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 -2
View File
@@ -91,8 +91,12 @@ You need at least one agent CLI installed and configured with your credentials:
- [GitHub Copilot](https://github.com/features/copilot/cli/)
- [OpenCode](https://github.com/anomalyco/opencode)
- [Pi](https://pi.dev)
- [Antigravity](https://paseo.sh/docs/supported-providers#antigravity)
- [Muse Code](https://paseo.sh/docs/muse-code)
- [Antigravity](https://paseo.sh/docs/supported-providers/antigravity)
- [Muse Code](https://paseo.sh/docs/supported-providers/muse-code)
- [fx](https://paseo.sh/docs/supported-providers/fx)
- [Hoplite](https://paseo.sh/docs/supported-providers/hoplite)
Paseo also runs Cursor, Gemini CLI, and many other agents. See [Supported providers](https://paseo.sh/docs/supported-providers) for the full list and setup steps.
### Desktop app (recommended)
+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
+8
View File
@@ -121,6 +121,14 @@ from `packages/app/android`:
These check terminal arrow ownership, held-key repeats and modifiers, and ordinary text-field editing.
Run the display density regression tests the same way:
```bash
./gradlew :paseo-display-metrics:connectedDebugAndroidTest --no-daemon --max-workers=2 -Dorg.gradle.parallel=false
```
These check that React Native sizes text at the window's density when the window is on another display, such as Samsung DeX.
### Diagnostic logs without ADB
In a dogfood build, open Android's Files app → Downloads → **Paseo diagnostics** and share all
+2 -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 |
@@ -506,5 +507,5 @@ Agent and terminal environments are unchanged. System proxy settings and SOCKS-o
## Deployment models
1. **Local daemon** (default): `paseo daemon start` on `127.0.0.1:6767`
2. **Managed desktop**: Electron uses the server package’s local-instance lifecycle capability for sanitized launch, published readiness, and captured-PID stop. Only a matching `{pid, startedAt}` from a spawn in the current Desktop session authorizes automatic stop or binary replacement. Preexisting instances, including legacy `desktopManaged` records, are attach-only. Keep-running survivors attach in the next session. Explicit attached Stop requires a confirmation naming the captured home/PID. Ordinary Restart uses the worker RPC on every app platform.
2. **Managed desktop**: Electron uses the server package’s local-instance lifecycle capability for sanitized launch, published readiness, and captured-PID stop. Only Desktop's own launch writes `desktopManaged: true` to `paseo.pid`. The CLI launch path removes the flag. While Desktop manages the built-in daemon, an app update or a version mismatch replaces any `desktopManaged` daemon, including one that an earlier Desktop session left running. Bundled CLIs before v0.9.0 exported the flag, so a daemon that one of them started also carries it and is replaced. Quit, Settings, and host removal stop only a daemon that the current session launched, matched by `{pid, startedAt}`. A daemon that the user started through the CLI is attach-only. Explicit attached Stop requires a confirmation naming the captured home/PID. Ordinary Restart uses the worker RPC on every app platform.
3. **Remote + relay**: Daemon behind firewall, relay bridges with E2E encryption
+4 -1
View File
@@ -117,7 +117,10 @@ There is no renderer prep/restore handshake or lifetime background-throttling ov
Screenshot capture temporarily enables frame production inside the shared serialized queue,
restores the previous throttling policy on success or failure, and retains a 5-second capture budget.
The browser tool takes one viewport frame through Electron's frame subscription and releases the
subscription on completion or cancellation. A resized resident guest can produce fresh pixels
subscription on completion or cancellation. Guest pages have a transparent base background, so a page
that has painted nothing yet (a dev server hiding `body` until its JS boots) produces frames where
every pixel is transparent. Both screenshot paths skip those frames and return `screenshot_no_frame`
when the capture budget expires without a painted one. A resized resident guest can produce fresh pixels
while `capturePage()` leaves its surface-copy request pending; waiting for animation frames or
retrying the copy does not repair that state. Full-page screenshots retain the CDP path with layout
metrics and screenshot clip.
+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`
+4 -2
View File
@@ -99,8 +99,10 @@ Register the adapter in `defaultForgeRegistry` with:
Current change-request lookup matches the branch and repository for both open and
terminal requests. Prefer an open request, then a terminal request at the local
HEAD, then the most recently updated terminal request. A reused branch can show
its previous request until a new one opens. Auto-archive separately requires an
HEAD, then the most recently updated terminal request. When the forge identifies
the checkout's branch as the origin repository's default branch, only open
requests are eligible. A reused feature branch can show its previous request
until a new one opens. Auto-archive separately requires an
observed open-to-merged transition and a fresh exact match between checkout HEAD
and the PR head, along with the existing workspace safety checks.
+1 -1
View File
@@ -24,7 +24,7 @@ Math and video are disabled. Task lists and admonitions are enabled; task checkb
Mermaid fences use the existing isolated diagram runtime and fullscreen viewer. Web dispatches them through the library’s code-block override. Native has no block-renderer hook, so the renderer extracts only Mermaid fences and places the existing WebView host between library-rendered segments. This is the only block exception; see [native selection limitations](native-text-selection.md) for diagram grouping and leading inline images. Streaming keeps the last valid diagram visible while the next revision renders.
Native code blocks use the library's copy control and compiled grammars. Web code blocks use `HighlightedCodeBlock` through the library's `renderers.codeBlock` override. The patch also keeps the library's block spacing around the web code block override, preserves web list numbering and link titles, marks pending parses with `aria-busy` so Find waits for rendered text, and carries link syntax through native and web tap events. Web inline code inside a link inherits only the link colour; its code font, size and background stay intact. Keep link variants colour-only: native pills replace text runs and prevent paths from wrapping; Android pills also use the surrounding block’s font size. The package patch is tracked by [upstream PR #997](https://github.com/software-mansion/enriched-markdown/pull/997); remove the patch when the pinned release includes it.
Native code blocks use the library's copy control and compiled grammars. Web code blocks use `HighlightedCodeBlock` through the library's `renderers.codeBlock` override. Selection copy has to tell links Paseo recognized in the text (paths, forge references, code spans) from links in the Markdown, so the web link renderer marks the recognized ones. Plain-text paste carries them as the text the reply showed, and rich paste keeps them as links only when they point to an `http` or `https` URL. Authored links and parser autolinks such as a bare `www.example.com` copy as links. The patch also keeps the library's block spacing around the web code block override, preserves web list numbering and link titles, marks pending parses with `aria-busy` so Find waits for rendered text, and carries link syntax through native and web tap events. Web inline code inside a link inherits only the link colour; its code font, size and background stay intact. Keep link variants colour-only: native pills replace text runs and prevent paths from wrapping; Android pills also use the surrounding block’s font size. The package patch is tracked by [upstream PR #997](https://github.com/software-mansion/enriched-markdown/pull/997); remove the patch when the pinned release includes it.
The package patch also keeps overflowing native horizontal blocks in control of their drags: Android claims parent interception at touch-down and releases it for vertical drags so the chat list can scroll; iOS keeps its scroll recognizer active for outward drags at the leading edge. This prevents compact sidebar pans from taking block scrolling without changing sidebar swipes on prose or non-overflowing blocks. Native changes require a client rebuild.
+15
View File
@@ -49,6 +49,21 @@ restarting the process. It writes snapshots and native failure state under
production package. This needs a native rebuild when the Unistyles patch changes; a Metro
reload cannot update it.
To check the first Android composer tap after pinch-to-zoom, install the rebuilt
APK and connect it to a chat whose latest assistant message contains a visible
Markdown image. For example, put `picture.png` in the agent workspace and have
the assistant reply with `![Test image](picture.png)`. Set `CHAT_URL` to the
chat's Paseo deep link and run from the repository root:
```bash
agent-device test packages/app/e2e/mobile/composer-keyboard/lightbox-pinch.android.ad \
--platform android --serial emulator-5554 -e APP_ID=sh.paseo -e "CHAT_URL=$CHAT_URL"
```
Use `APP_ID=sh.paseo.debug` for a development build. If the image has different
alt text, pass it with `-e IMAGE_LABEL="..."`. The test pinches the image, closes
it, types in the composer, and checks that a single Attach tap opens Upload file.
For Android keyboard continuity, run the current checkout in the app, open an idle terminal
with an empty prompt, hide its keyboard, and run:
+1 -1
View File
@@ -129,7 +129,7 @@ availability and a diagnostic after the daemon resolves the executable. Configur
environment, or enablement overrides under `agents.providers.muse`. Omit `extends` to keep
the bundled integration; an entry with `extends` shadows it with a custom provider. See
[provider contributions](#contribute-a-provider) for the contract and
[Muse Code](../public-docs/muse-code.md) for setup, per-agent options, and version limitations.
[Muse Code](../public-docs/supported-providers/muse-code.md) for setup, per-agent options, and version limitations.
## Install from a registry
+2 -2
View File
@@ -19,8 +19,8 @@ provider icon map. You do not need a core manifest entry or provider factory.
| Provider | Transport | Setup and limitations |
| ----------- | ------------------------------------------ | ---------------------------------------------------------------- |
| Antigravity | Installed `agy` CLI | [Antigravity](../public-docs/supported-providers.md#antigravity) |
| Muse Code | MSP over one `muse serve` host per session | [Muse Code](../public-docs/muse-code.md) |
| Antigravity | Installed `agy` CLI | [Antigravity](../public-docs/supported-providers/antigravity.md) |
| Muse Code | MSP over one `muse serve` host per session | [Muse Code](../public-docs/supported-providers/muse-code.md) |
## Provider-native session options
+74 -14
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:
@@ -49,9 +82,17 @@ Large unbounded timeline responses can exceed relay frame limits, so catch-up us
Page limits are projected-item targets. A tool call lifecycle is one projected item even if it spans many source sequence numbers, and assistant/reasoning chunks are merged before counting. The response carries `seqStart`, `seqEnd`, `sourceSeqRanges`, and `collapsed` so clients can advance sequence cursors without rendering delta rows.
When live delivery detects a sequence gap, the app fetches `direction: "after"`. If the daemon
responds with `hasNewer: true`, the app immediately fetches the next page from `endCursor`. Gap
recovery is complete only when `hasNewer: false`.
When live delivery detects a sequence gap, the app fetches `direction: "after"` its end cursor. If
the daemon responds with `hasNewer: true`, the app immediately fetches the next page from
`endCursor`. Gap recovery is complete only when `hasNewer: false`.
A chat that was empty when it last caught up has no end cursor to compare a live row against. Such a
row starts coverage only if it is the epoch's first row, seq 1. A later row means the chat missed the
rows before it, such as a prompt sent while the app was offline, so the app drops it and recovers
after seq 0. Coverage started at that later row would make the resume page look already applied, and
the chat and its replica cache would keep only the end of the reply. A recovery that waits behind a
running catch-up starts after whatever that catch-up applied, because the app applies a forward page
row by row and an older cursor repeats rows.
Initialization timeouts guard lack of catch-up progress, not the full multi-page sync. A successful page that queues the next `after` page refreshes the watchdog.
@@ -160,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.
@@ -173,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
@@ -337,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.
@@ -353,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`
+2
View File
@@ -7,6 +7,7 @@ const withAndroidProfileable = require("./plugins/with-android-profileable");
const withFdroidAutolinking = require("./plugins/with-fdroid-autolinking");
const withPasteInput = require("./plugins/with-paste-input");
const withAndroidScroll = require("./modules/paseo-scroll/app.plugin");
const withAndroidDisplayMetrics = require("./modules/paseo-display-metrics/app.plugin");
const { getNativeReleaseVersion } = require("./native-release-version");
const appVariant = process.env.APP_VARIANT ?? "production";
const isFdroidBuild = process.env.PASEO_FDROID_BUILD === "1";
@@ -146,6 +147,7 @@ export default {
"expo-router",
withPasteInput,
withAndroidScroll,
withAndroidDisplayMetrics,
[withAndroidAsyncStorageSize, 64],
...buildProfile.cameraPlugins,
withAndroidOptionalCamera,
@@ -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();
}
@@ -527,7 +527,17 @@ async function expectHiddenStreamingSubmissionOrderAfterWorkspaceEviction(
expect(gate.getClientRequestCount("agent.timeline.set_subscription.request")).toBe(
subscriptionRequests,
);
const requestsBeforeRelease = rememberTimelineRequestCounts(gate, target.agentId);
gate.releaseHeldAgentStreamEvent("turn_started");
// The chat never saw the hidden prompt's live row, so the reply's first row is a gap.
// The chat recovers the missing rows once, while its workspace is still evicted.
await expect
.poll(() => gate.getTimelineRequestCount("after", target.agentId))
.toBe(requestsBeforeRelease.after + 1);
await gate.waitForServerMessage(
"fetch_agent_timeline_response",
gate.getClientRequestCount("fetch_agent_timeline_request"),
);
const requestsBeforeReturn = rememberTimelineRequestCounts(gate, target.agentId);
await waitForWorkspaceInSidebar(page, {
serverId: getServerId(),
@@ -14,6 +14,8 @@ import {
answerFreshnessCheck,
commitTimelineTurnsWhileDisconnected,
disconnectViewedTimeline,
expectEmptyChatSynced,
expectPromptAndWholeReply,
expectResumeAnsweredWithoutFetch,
expectResumeOverflowFallsBackToOneTail,
hideTabAndReturn,
@@ -22,7 +24,11 @@ import {
restoreUnchangedViewedTimeline,
restoreViewedTimelineHoldingCatchUp,
restoreViewedTimelineWithHeldResponse,
restoreViewedTimelineWithLiveRowsFirst,
reopenWithFreshnessCheckUnanswered,
seedStreamingReplyAgent,
sendPromptWhileDisconnected,
stopStreamingReply,
waitForResumeAnswer,
reopenAppWatchingForUpdatingToast,
watchForUpdatingToast,
@@ -147,4 +153,27 @@ test.describe("Agent timeline resume", () => {
await agent.cleanup();
}
});
test("an empty chat that reconnects mid-reply keeps the prompt and the whole reply", async ({
page,
}) => {
test.setTimeout(120_000);
const gate = await installDaemonWebSocketGate(page);
const agent = await seedStreamingReplyAgent();
try {
await openAgentTimeline(page, agent);
await expectEmptyChatSynced(page, gate);
await disconnectViewedTimeline(page, gate);
await sendPromptWhileDisconnected(agent);
await restoreViewedTimelineWithLiveRowsFirst(gate);
const reply = await stopStreamingReply(agent);
await expectPromptAndWholeReply(page, agent, reply);
await page.reload();
await expectPromptAndWholeReply(page, agent, reply);
} finally {
gate.restore();
await agent.cleanup();
}
});
});
@@ -72,14 +72,12 @@ const ASSISTANT_MARKDOWN = [
"| Current \\| active | ~~obsolete~~ | ready |",
].join("\n");
const EXPECTED_WHOLE_SELECTION_MARKDOWN = ASSISTANT_MARKDOWN.replace(
// text/plain carries the selection as displayed, so an inline code span the renderer
// linked copies without its destination.
const EXPECTED_WHOLE_SELECTION_TEXT = ASSISTANT_MARKDOWN.replace(
"www.example.com stays",
"[www.example.com](http://www.example.com) stays",
)
.replace(
"`https://example.com/generated` stays",
"[`https://example.com/generated`](https://example.com/generated) stays",
)
.replace(`${CROSS_STRUCTURE_MARKDOWN}\n\n`, "")
.replace(
"<https://autolink.example.com>",
@@ -422,7 +420,7 @@ test("copying an assistant selection preserves Markdown structure and links", as
await copySelection(page);
const clipboard = await readRichClipboard(page);
expect(clipboard.plainText).toBe(EXPECTED_WHOLE_SELECTION_MARKDOWN);
expect(clipboard.plainText).toBe(EXPECTED_WHOLE_SELECTION_TEXT);
expect(clipboard.html).not.toContain("<ul>");
expect(clipboard.html).not.toContain("<li>");
expect(clipboard.html).toContain("<div>- ");
@@ -688,6 +686,77 @@ test("copying an assistant selection preserves Markdown structure and links", as
}
});
test("pasting an assistant selection preserves literal underscores and authored links", async ({
context,
page,
}) => {
const agent = await seedMockAgentWorkspace({
repoPrefix: "assistant-selection-paste-",
title: "Assistant selection paste",
initialPrompt: "Render the paste fixture.",
featureValues: {
mockAssistantResponse:
"Keep \\_literal\\_ and `https://example.com/generated` beside [the docs](https://example.com/docs).",
},
});
try {
await allowRichClipboard(context);
await agent.client.waitForAgentUpsert(
agent.agentId,
(snapshot) => snapshot.status === "idle",
30_000,
);
await openAgentRoute(page, agent);
const message = assistantMessageBlocks(page);
await expect(message.locator('a[href="https://example.com/generated"]')).toHaveText(
"https://example.com/generated",
);
await selectAssistantTextRange(page, "Keep _literal_", "the docs.");
await copySelection(page);
await page.evaluate(() => {
const fields = document.createElement("div");
fields.style.cssText =
"position: fixed; bottom: 0; left: 0; z-index: 10000; background: white";
const plainText = document.createElement("textarea");
plainText.setAttribute("aria-label", "Plain text paste");
const richText = document.createElement("div");
richText.contentEditable = "true";
richText.setAttribute("role", "textbox");
richText.setAttribute("aria-label", "Rich text paste");
fields.append(plainText, richText);
document.body.append(fields);
});
const plainText = page.getByRole("textbox", { name: "Plain text paste" });
await plainText.focus();
await page.keyboard.press("ControlOrMeta+v");
await expect(plainText).toHaveValue(
"Keep _literal_ and `https://example.com/generated` beside [the docs](https://example.com/docs).",
);
const richText = page.getByRole("textbox", { name: "Rich text paste" });
await richText.focus();
await page.keyboard.press("ControlOrMeta+v");
await expect(richText).toHaveText(
"Keep _literal_ and https://example.com/generated beside the docs.",
);
await expect(richText.locator("code")).toHaveText("https://example.com/generated");
await expect(richText.getByRole("link")).toHaveCount(2);
await expect(
richText.getByRole("link", { name: "https://example.com/generated" }),
).toHaveAttribute("href", "https://example.com/generated");
await expect(richText.getByRole("link", { name: "the docs" })).toHaveAttribute(
"href",
"https://example.com/docs",
);
} finally {
await agent.cleanup();
}
});
test("copying a selection across an assistant image keeps its Markdown source and alt text", async ({
context,
page,
@@ -466,12 +466,12 @@ test("downloads a file over direct TCP with its original filename and bytes", as
await gotoWorkspace(page, workspace.workspaceId);
await openFileExplorer(page);
const daemonRequest = page.waitForRequest("**/api/files/download?*");
const downloaded = await downloadFileFromExplorer(page, fileName);
const url = new URL(downloaded.url());
expect(url.protocol).toBe("http:");
expect(url.port).toBe(getE2EDaemonPort());
expect(url.pathname).toBe("/api/files/download");
expect(url.searchParams.get("token")).toBeTruthy();
const requestUrl = new URL((await daemonRequest).url());
expect(requestUrl.port).toBe(getE2EDaemonPort());
expect(requestUrl.searchParams.get("token")).toBeTruthy();
expect(new URL(downloaded.url()).protocol).toBe("blob:");
expect(downloaded.suggestedFilename()).toBe(fileName);
const savedFile = testInfo.outputPath(fileName);
await downloaded.saveAs(savedFile);
@@ -479,6 +479,45 @@ test("downloads a file over direct TCP with its original filename and bytes", as
expect(await readFile(savedFile)).toEqual(source);
});
test("keeps the app open and shows the error when the host rejects a download", async ({
page,
}, testInfo) => {
const fileName = "removed-during-download.bin";
const filePath = path.join(workspace.workspaceDirectory, fileName);
const source = Buffer.from([0, 1, 2, 255]);
await writeFile(filePath, source);
await gotoWorkspace(page, workspace.workspaceId);
await openFileExplorer(page);
const workspaceUrl = page.url();
// The file disappears after the token is issued, so the real daemon answers 404.
await page.route(
"**/api/files/download?*",
async (route) => {
await rm(filePath);
await route.continue();
},
{ times: 1 },
);
await page
.getByTestId("file-explorer-tree-scroll")
.getByText(fileName, { exact: true })
.click({ button: "right" });
await page.getByRole("menuitem", { name: "Download", exact: true }).click();
await expect(
page.getByText("Failed to download file (HTTP 404).", { exact: true }),
).toBeVisible();
expect(page.url()).toBe(workspaceUrl);
await writeFile(filePath, source);
const downloaded = await downloadFileFromExplorer(page, fileName);
const savedFile = testInfo.outputPath(fileName);
await downloaded.saveAs(savedFile);
expect(await readFile(savedFile)).toEqual(source);
expect(page.url()).toBe(workspaceUrl);
});
test("downloads an unsupported binary from its preview with original filename and bytes", async ({
page,
}, testInfo) => {
@@ -362,6 +362,16 @@ test.describe("Plugin sidebar items", () => {
});
});
test("a plugin screen reads workspaces through the state hooks", async ({ page }) => {
await page.setViewportSize(WIDE);
await gotoWorkspace(page, workspaceId);
await expect(headerRow(page, SHOWCASE_PLUGIN_ID, "deploys")).toBeVisible({ timeout: 30_000 });
await runCommand(page, "Open plugin workspaces");
await expect(screenTitle(page)).toHaveText("Workspaces");
await expect(page.getByText(`Workspace ${workspaceId}`, { exact: true })).toBeVisible();
await expect(page.getByText("Plugin failed", { exact: false })).toHaveCount(0);
});
test("a header row's shortcut hint presses the row", async ({ page }) => {
await page.setViewportSize(WIDE);
await gotoWorkspace(page, workspaceId);
@@ -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();
}
+13 -2
View File
@@ -705,7 +705,7 @@ test("a scheduled heartbeat opens a separate turn without reopening the previous
});
const schedules = agent.client as unknown as Pick<
DaemonClient,
"scheduleCreate" | "scheduleRunOnce" | "scheduleDelete"
"scheduleCreate" | "scheduleRunOnce" | "scheduleDelete" | "scheduleList"
>;
let scheduleId: string | undefined;
try {
@@ -743,7 +743,18 @@ test("a scheduled heartbeat opens a separate turn without reopening the previous
await expect(summaries).toHaveCount(2);
await expect.poll(() => rowsBetweenLatestSummaryAndReply(page)).toBe(0);
await expect(page.getByRole("button", { name: /^Worked for/ })).toHaveCount(2);
await page.screenshot({ path: "/tmp/heartbeat-turn-footer.png" });
const tasks = page.getByRole("button", { name: "1 background task", exact: true });
await expect(page.getByTestId("workspace-status-indicator-running").first()).toBeVisible();
await expect(page.getByRole("button", { name: "Stop agent", exact: true })).toHaveCount(0);
await tasks.click();
const panel = page.getByTestId("background-work-panel");
await expect(panel).toContainText("Heartbeat");
await panel.getByRole("button", { name: "Stop Check the completed work" }).click();
await expect(tasks).toHaveCount(0);
await expect(page.getByTestId("workspace-status-indicator-running")).toHaveCount(0);
const remaining = await schedules.scheduleList();
expect(remaining.error).toBeNull();
expect(remaining.schedules.map((schedule) => schedule.id)).not.toContain(scheduleId);
} finally {
if (scheduleId) await schedules.scheduleDelete({ id: scheduleId });
await agent.cleanup();
@@ -23,6 +23,8 @@ import {
outlastUndoWindow,
pressArchiveShortcut,
pressUndoShortcut,
readSidebarListLayout,
recordLastRowBottomPerFrame,
resizeSidebarToMinimum,
rowArchiveButton,
rowKebab,
@@ -121,7 +123,7 @@ test.describe("Workspace archive undo", () => {
expect(shortcutBox.x - (labelBox.x + labelBox.width)).toBeLessThanOrEqual(8.5);
});
test("a long list ends just below its last row, and the toast over it moves no row", async ({
test("a long list scrolls its last row clear of the toast, and settles back smoothly after it", async ({
page,
}) => {
await page.clock.install({ time: Date.now() });
@@ -136,18 +138,35 @@ test.describe("Workspace archive undo", () => {
const worktree = await seedWorktree(page, "archive-toast-long-list");
const resting = await scrollSidebarListToEnd(page);
expect(resting.listBottom - resting.rowBottoms.at(-1)!).toBeLessThan(resting.rowHeight);
const restingEndGap = resting.listBottom - resting.rowBottoms.at(-1)!;
expect(restingEndGap).toBeLessThan(resting.rowHeight);
await archiveFromRowButton(page, worktree.workspaceId);
await page.mouse.move(0, 0);
const withToast = await scrollSidebarListToEnd(page);
const toastBox = await archivedToast(page).boundingBox();
if (!toastBox) throw new Error("Toast is not laid out");
expect(toastBox.y + toastBox.height).toBeLessThanOrEqual(withToast.listBottom);
// The list keeps its usual end gap, measured from the toast's top instead of its own bottom.
await expect
.poll(async () => {
const layout = await scrollSidebarListToEnd(page);
return Math.round(toastBox.y - layout.rowBottoms.at(-1)!);
})
.toBe(Math.round(restingEndGap));
const frames = recordLastRowBottomPerFrame(page, 40);
await outlastUndoWindow(page);
const bottoms = await frames;
await expect(archivedToast(page)).toHaveCount(0);
expect(await scrollSidebarListToEnd(page)).toEqual(withToast);
// Without scrolling again, the list ends just below its last row once more.
const settled = await readSidebarListLayout(page);
expect(settled.listBottom - settled.rowBottoms.at(-1)!).toBeCloseTo(restingEndGap, 0);
// The rows travel down by the toast's height over several frames, never in one jump.
const travel = bottoms.at(-1)! - bottoms[0]!;
expect(travel).toBeGreaterThan(toastBox.height);
const steps = bottoms.slice(1).map((bottom, index) => bottom - bottoms[index]!);
expect(Math.min(...steps)).toBeGreaterThanOrEqual(0);
expect(Math.max(...steps)).toBeLessThan(travel / 2);
} finally {
for (const projectId of fillerProjectIds) {
await client.removeProject(projectId).catch(() => undefined);
@@ -3,6 +3,7 @@ import { gotoAppShell } from "../support/helpers/app";
import { getServerId } from "../support/helpers/server-id";
import { seedWorkspace } from "../support/helpers/seed-client";
import { waitForSidebarHydration } from "../support/helpers/workspace-ui";
import { openWorkspaceSidebarKebab } from "../support/helpers/sidebar";
import { daemonWsRoutePattern } from "../support/helpers/daemon-port";
interface SessionEnvelope {
@@ -114,11 +115,7 @@ async function expectAssigned(
}
async function openWorkspaceLabels(page: import("@playwright/test").Page, workspaceId: string) {
const serverId = getServerId();
const row = page.getByTestId(`sidebar-workspace-row-${serverId}:${workspaceId}`).first();
await expect(row).toBeVisible({ timeout: 30_000 });
await row.hover();
await page.getByTestId(`sidebar-workspace-kebab-${serverId}:${workspaceId}`).first().click();
const serverId = await openWorkspaceSidebarKebab(page, workspaceId);
await page.getByTestId(`sidebar-workspace-menu-labels-${serverId}:${workspaceId}`).click();
await expect(page.getByTestId("workspace-label-picker-create")).toBeVisible();
}
@@ -361,6 +361,10 @@ test.describe("Worktree restore", () => {
cwd: backingWorktree.workspaceDirectory,
stdio: "pipe",
});
const originalHead = execFileSync("git", ["rev-parse", "HEAD"], {
cwd: backingWorktree.workspaceDirectory,
encoding: "utf8",
}).trim();
const created = await worktreeClient.createWorkspace({
source: { kind: "directory", path: backingWorktree.workspaceDirectory },
title: "Sample workspace",
@@ -389,10 +393,7 @@ test.describe("Worktree restore", () => {
await page.getByTestId(`agent-row-${getServerId()}-${agent.id}`).click();
await expect(page.getByText("Workspace archived", { exact: true })).toBeVisible();
await expect(
page.getByText(
"Restore Sample workspace to return to its agents. A new branch will start from the saved base or the repository default.",
{ exact: true },
),
page.getByText("Restore Sample workspace to return to its agents.", { exact: true }),
).toBeVisible();
await captureBranchlessRestoreStep(page, "01-restore-workspace.png");
@@ -409,17 +410,13 @@ test.describe("Worktree restore", () => {
cwd: backingWorktree.workspaceDirectory,
encoding: "utf8",
}).trim();
const defaultHead = execFileSync("git", ["rev-parse", "main"], {
cwd: tempRepo.path,
encoding: "utf8",
}).trim();
expect(restoredHead).toBe(defaultHead);
expect(restoredHead).toBe(originalHead);
expect(
execFileSync("git", ["branch", "--show-current"], {
cwd: backingWorktree.workspaceDirectory,
encoding: "utf8",
}).trim(),
).toMatch(/^restored\//);
).toBe("");
});
test("restore failure stays visible and permits a successful retry", async ({ page }) => {
@@ -0,0 +1,15 @@
# CHAT_URL opens a connected chat containing a visible Markdown image with alt text IMAGE_LABEL.
context platform=android timeout=120000 retries=0
env APP_ID=sh.paseo.debug
env IMAGE_LABEL="Test image"
open "${APP_ID}" "${CHAT_URL}"
wait "label=\"${IMAGE_LABEL}\"" 30000
press "label=\"${IMAGE_LABEL}\""
wait "label=\"Close image\"" 5000
gesture pinch 1.7
press "label=\"Close image\""
press "editable=true"
type "pinch regression"
press "role=\"button\" label=\"Add attachment\""
wait "label=\"Upload file\"" 3000
@@ -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,
};
}
@@ -97,18 +97,15 @@ export class ImportSessionFlow {
await target.scrollIntoViewIfNeeded();
await expect(target).toBeInViewport();
}
/**
* Scrolls the virtualized list, the only one that leaves rows unmounted. A row handle is no way
* in: the list unmounts rows as it scrolls, and a detached row has no scroller above it.
*/
private async scrollList(forward: boolean) {
await this.page
.locator('[data-testid^="import-session-session-"]')
.first()
.evaluate((row, advance) => {
let element = row.parentElement;
while (element && !["auto", "scroll"].includes(getComputedStyle(element).overflowY))
element = element.parentElement;
if (!element) throw new Error("Import list has no scroll owner");
element.scrollTop = advance ? element.scrollTop + element.clientHeight * 0.8 : 0;
element.dispatchEvent(new Event("scroll"));
}, forward);
await this.page.getByTestId("import-session-list").evaluate((list, advance) => {
list.scrollTop = advance ? list.scrollTop + list.clientHeight * 0.8 : 0;
list.dispatchEvent(new Event("scroll"));
}, forward);
}
async search(query: string) {
await this.page.getByTestId("import-session-search").fill(query);
@@ -120,11 +117,18 @@ export class ImportSessionFlow {
await this.page.getByTestId("import-session-search").fill("");
await expect(this.page.getByTestId("import-session-load-more")).toBeVisible();
}
/** Load more keeps the reader down the list instead of sending them back to the top. */
async loadMore() {
await this.page.getByTestId("import-session-load-more").click();
const loadMore = this.page.getByTestId("import-session-load-more");
const topRow = this.page.getByTestId((await this.rowIds())[0]!);
await expect(topRow).toBeInViewport();
await loadMore.click();
// The next page is the last and short, so the button leaves once it lands.
await expect(loadMore).toHaveCount(0);
await expect(this.page.getByText("Loading sessions...", { exact: true })).toHaveCount(0);
await expect(topRow).not.toBeInViewport();
await this.revealSession("fixture-root-20");
await expect(this.page.getByText("Root session 20", { exact: true })).toBeInViewport();
await expect(this.page.getByTestId("import-session-load-more")).toHaveCount(0);
}
async retryProvider(provider: string, label: string) {
await this.expectProviderError(label);
@@ -198,6 +198,14 @@ async function expectDetails(page: Page) {
await expect(page.getByText("All systems operational", { exact: true })).toBeInViewport();
}
// The details render before the daemon answers their event subscription, and reopened
// details show the cached summary at once, so wait for the subscription id to arrive.
async function readContentObservation(page: Page): Promise<string> {
const observation = page.getByLabel("Content observation", { exact: true });
await expect(observation).not.toHaveText("");
return (await observation.textContent())!;
}
function workspaceMenuRow(page: Page, title: string): Locator {
return compactWorkspaceMenu(page).getByRole("menuitem", { name: title, exact: true });
}
@@ -354,14 +362,12 @@ export async function withButtonShowcase(
test.step("closing and crashing content release its owner while sibling buttons and app remain live", async () => {
await press(page, "Header status");
await expectDetails(page);
const observation = page.getByLabel("Content observation", { exact: true });
await expect(observation).not.toHaveText("");
const first = (await observation.textContent())!;
const first = await readContentObservation(page);
await press(page, "Close deployment details");
await expect.poll(() => released.has(first)).toBe(true);
await press(page, "Composer status");
await expectDetails(page);
const second = (await observation.textContent())!;
const second = await readContentObservation(page);
expect(second).not.toBe(first);
await workspace.client.renameProject(workspace.projectId, "Observer control");
await expect(page.getByText("Observed updates: 1", { exact: true })).toBeVisible();
@@ -373,7 +379,7 @@ export async function withButtonShowcase(
await page.keyboard.press("Escape");
await press(page, "Header status");
await expectDetails(page);
const recovered = (await observation.textContent())!;
const recovered = await readContentObservation(page);
expect([first, second]).not.toContain(recovered);
await showcase.setTitle("Healthy app after button failure");
await expect(page.getByTestId("workspace-header-title")).toHaveText(
@@ -687,9 +693,7 @@ export async function withButtonShowcase(
page,
page.getByRole("button", { name: "Close deployment details", exact: true }),
);
const observation = page.getByLabel("Content observation", { exact: true });
await expect(observation).not.toHaveText("");
const owner = (await observation.textContent())!;
const owner = await readContentObservation(page);
await showcase.disable();
await expect.poll(() => released.has(owner)).toBe(true);
await expect(
@@ -15,8 +15,18 @@ export const COMPACT = { width: 390, height: 844 };
/** A plugin written against the current API: a screen, header and footer items, a command. */
const SHOWCASE_SOURCE = `import React from "react";
import { Pressable, Text, View } from "react-native";
import { useWorkspaces } from "@getpaseo/plugin/client";
import { SidebarRow } from "@getpaseo/plugin/client/ui";
function WorkspacesScreen({ theme }) {
const workspaces = useWorkspaces();
return (
<View style={{ flex: 1, padding: 24, gap: 8 }}>
{workspaces.map((ref) => <Text key={ref.id} style={{ color: theme.colors.foreground }}>{"Workspace " + ref.id}</Text>)}
</View>
);
}
function DeploysScreen({ theme }) {
return <View style={{ flex: 1, padding: 24 }}><Text style={{ color: theme.colors.foreground }}>Deploys screen body</Text></View>;
}
@@ -63,11 +73,13 @@ function Broken() {
export default function contribute(client) {
client.addScreen({ id: "deploys", title: "Deploys", Component: DeploysScreen });
client.addScreen({ id: "workspaces", title: "Workspaces", Component: WorkspacesScreen });
client.addSidebarHeaderItem({ id: "deploys", title: "Deploys", Component: DeploysItem });
client.addSidebarHeaderItem({ id: "broken", title: "Broken header", Component: Broken });
client.addSidebarFooterItem({ id: "sync", title: "Sync", Component: SyncItem });
client.addSidebarFooterItem({ id: "broken", title: "Broken footer", Component: Broken });
client.addCommandCenterItem({ id: "open-deploys", title: "Open deploys", icon: "Rocket", context: "global", onSelect: (ctx) => ctx.openScreen({ screenId: "deploys" }) });
client.addCommandCenterItem({ id: "open-workspaces", title: "Open plugin workspaces", icon: "List", context: "global", onSelect: (ctx) => ctx.openScreen({ screenId: "workspaces" }) });
return () => {};
}
`;
+16 -5
View File
@@ -190,14 +190,25 @@ export async function selectWorkspaceInSidebar(page: Page, workspaceId: string):
await row.click();
}
async function openWorkspaceSidebarKebab(page: Page, workspaceId: string) {
/**
* Opens a workspace row's kebab menu the way a pointer does: enter the row, then press the kebab
* it reveals.
*
* The kebab only mounts while the row holds hover, and hover only arrives on pointerenter. A row
* that re-renders or shifts under a parked pointer drops that hover with no new pointerenter to
* restore it, so each attempt leaves the row and enters it again instead of waiting on a kebab
* that a still pointer cannot bring back.
*/
export async function openWorkspaceSidebarKebab(page: Page, workspaceId: string) {
const serverId = getServerId();
const row = page.getByTestId(`sidebar-workspace-row-${serverId}:${workspaceId}`);
await expect(row).toBeVisible({ timeout: 30_000 });
await row.hover();
const kebab = page.getByTestId(`sidebar-workspace-kebab-${serverId}:${workspaceId}`);
await expect(kebab).toBeVisible({ timeout: 10_000 });
await expect(row).toBeVisible({ timeout: 30_000 });
await expect(async () => {
await page.mouse.move(0, 0);
await row.hover();
await expect(kebab).toBeVisible({ timeout: 2_000 });
}).toPass({ timeout: 15_000 });
await kebab.click();
return serverId;
@@ -1,5 +1,6 @@
import { expect, type Page } from "@playwright/test";
import type { installDaemonWebSocketGate } from "./daemon-websocket-gate";
import { seedMockAgentWorkspace, type MockAgentWorkspace } from "./mock-agent";
import { readReplicaCache } from "./replica-cache-storage";
import type { LongTimelineAgent } from "./timeline-pagination";
import {
@@ -241,3 +242,100 @@ export async function restoreUnchangedViewedTimeline(
gate.restore();
await expectReconnectingToastGone(page);
}
export interface StreamingReplyAgent extends MockAgentWorkspace {
prompt: string;
}
/**
* A mock agent with no history whose reply streams one word every 100 ms. At 2,000 words the
* reply outlasts the test's timeout, so it is still streaming however long the app takes to
* reconnect. The test ends the turn with {@link stopStreamingReply}.
*/
export async function seedStreamingReplyAgent(): Promise<StreamingReplyAgent> {
const reply = Array.from({ length: 2_000 }, (_unused, index) => `word${index}`).join(" ");
const agent = await seedMockAgentWorkspace({
repoPrefix: "reply-reconnect-",
title: "Reply through reconnect",
featureValues: {
mockStreamingAssistantResponse: reply,
mockStreamingAssistantIntervalMs: 100,
},
});
return {
...agent,
prompt: "stream through a reconnect",
cleanup: async () => {
await agent.client.cancelAgent(agent.agentId).catch(() => undefined);
await agent.cleanup();
},
};
}
interface TimelineReader {
fetchAgentTimeline(
agentId: string,
request: { direction: "tail"; limit: number },
): Promise<{ entries: Array<{ item: { type: string; text?: string } }> }>;
}
async function readDaemonReply(agent: StreamingReplyAgent): Promise<string> {
const timeline = await (agent.client as unknown as TimelineReader).fetchAgentTimeline(
agent.agentId,
{ direction: "tail", limit: 0 },
);
return timeline.entries
.map(({ item }) => (item.type === "assistant_message" ? (item.text ?? "") : ""))
.join("");
}
/** Waits for the empty chat's first catch-up, so the chat is synced with no range. */
export async function expectEmptyChatSynced(page: Page, gate: DaemonWebSocketGate): Promise<void> {
await gate.waitForServerMessage(TIMELINE_RESPONSE);
await expect(page.getByTestId("agent-chat-scroll").filter({ visible: true })).toHaveCount(1, {
timeout: 30_000,
});
}
/** Another client sends the prompt, and the reply starts, while the chat is away. */
export async function sendPromptWhileDisconnected(agent: StreamingReplyAgent): Promise<void> {
await agent.client.sendAgentMessage(agent.agentId, agent.prompt);
await expect.poll(() => readDaemonReply(agent), { timeout: 30_000 }).toContain("word10");
}
/** Reconnects with live reply chunks reaching the chat before the catch-up page that holds them. */
export async function restoreViewedTimelineWithLiveRowsFirst(
gate: DaemonWebSocketGate,
): Promise<void> {
gate.holdNextClientRequest(TIMELINE_REQUEST);
const chunksBeforeReconnect = gate.getAgentStreamItemCount("assistant_message");
gate.restore();
await gate.waitForHeldClientRequest();
await gate.waitForAgentStreamItem("assistant_message", chunksBeforeReconnect + 5);
gate.releaseHeldClientRequest();
}
/** Stops the turn and returns the reply as the daemon recorded it. */
export async function stopStreamingReply(agent: StreamingReplyAgent): Promise<string> {
await agent.client.cancelAgent(agent.agentId);
await agent.client.waitForFinish(agent.agentId, 30_000);
const reply = (await readDaemonReply(agent)).trim();
expect(reply).toMatch(/^word0 word1 word2 .* word10 /);
return reply;
}
export async function expectPromptAndWholeReply(
page: Page,
agent: StreamingReplyAgent,
reply: string,
): Promise<void> {
const chat = page.getByTestId("agent-chat-scroll").filter({ visible: true }).first();
await expect(chat.getByText(agent.prompt, { exact: true })).toBeVisible({ timeout: 30_000 });
await expect
.poll(
async () =>
(await chat.getByTestId("assistant-message").allInnerTexts()).map((text) => text.trim()),
{ timeout: 30_000 },
)
.toEqual([reply]);
}
@@ -175,13 +175,19 @@ export interface SidebarListLayout {
rowHeight: number;
}
const SIDEBAR_LIST = "sidebar-project-workspace-list-scroll";
/** Scrolls the sidebar's workspace list to its end and reads where its rows sit. */
export async function scrollSidebarListToEnd(page: Page): Promise<SidebarListLayout> {
const list = page.getByTestId("sidebar-project-workspace-list-scroll");
await list.evaluate((element) => {
await page.getByTestId(SIDEBAR_LIST).evaluate((element) => {
element.scrollTop = element.scrollHeight;
});
return list.evaluate((element) => {
return readSidebarListLayout(page);
}
/** Reads where the sidebar list's rows sit, without scrolling it. */
export async function readSidebarListLayout(page: Page): Promise<SidebarListLayout> {
return page.getByTestId(SIDEBAR_LIST).evaluate((element) => {
const visible = element.getBoundingClientRect();
const rows = Array.from(
element.querySelectorAll<HTMLElement>(
@@ -197,3 +203,26 @@ export async function scrollSidebarListToEnd(page: Page): Promise<SidebarListLay
};
});
}
/**
* Starts recording the bottom edge of the sidebar list's last row once per painted frame.
* Resolves with one value per frame after `frameCount` frames.
*/
export function recordLastRowBottomPerFrame(page: Page, frameCount: number): Promise<number[]> {
return page.getByTestId(SIDEBAR_LIST).evaluate(
(element, count) =>
new Promise<number[]>((resolve) => {
const bottoms: number[] = [];
const sample = () => {
const rows = element.querySelectorAll<HTMLElement>(
'[data-testid^="sidebar-workspace-row-"],[data-testid^="sidebar-project-row-"]',
);
bottoms.push(Math.max(...Array.from(rows, (row) => row.getBoundingClientRect().bottom)));
if (bottoms.length >= count) resolve(bottoms);
else requestAnimationFrame(sample);
};
requestAnimationFrame(sample);
}),
frameCount,
);
}
@@ -0,0 +1,2 @@
/android/.cxx/
/android/build/
@@ -0,0 +1,23 @@
apply plugin: 'com.android.library'
group = 'sh.paseo.displaymetrics'
version = '0.1.0'
def expoModulesCorePlugin = new File(project(":expo-modules-core").projectDir.absolutePath, "ExpoModulesCorePlugin.gradle")
apply from: expoModulesCorePlugin
applyKotlinExpoModulesCorePlugin()
useCoreDependencies()
useDefaultAndroidSdkVersions()
android {
namespace "sh.paseo.displaymetrics"
defaultConfig {
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
}
dependencies {
implementation "com.facebook.react:react-android"
androidTestImplementation 'androidx.test:runner:1.6.2'
androidTestImplementation 'androidx.test.ext:junit:1.2.1'
}
@@ -0,0 +1,86 @@
package sh.paseo.displaymetrics
import android.util.DisplayMetrics
import android.util.TypedValue
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import com.facebook.react.uimanager.DisplayMetricsHolder
import com.facebook.react.uimanager.PixelUtil
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertSame
import org.junit.Assert.assertThrows
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class PaseoDisplayMetricsTest {
private lateinit var display: DisplayMetrics
@Before
fun readDisplayLikeReactNative() {
DisplayMetricsHolder.initDisplayMetrics(InstrumentationRegistry.getInstrumentation().targetContext)
display = DisplayMetricsHolder.getScreenDisplayMetrics()
}
@After
fun forgetDisplay() {
DisplayMetricsHolder.setScreenDisplayMetrics(null)
}
@Test
fun reservesRoomForTextAtTheWindowDensity() {
// A DeX window at two thirds of the phone's density (240 dpi on a 360 dpi phone). React Native
// reads the font scale from the window but the density from the phone's display.
val window = windowAt(display.densityDpi * 2 / 3)
DisplayMetricsHolder.setScreenDisplayMetrics(
DisplayMetrics().apply {
setTo(display)
scaledDensity = window.scaledDensity
},
)
assertTrue(reservedTextPx(window) < drawnTextPx())
PaseoDisplayMetrics.syncWithWindow(window)
assertEquals(drawnTextPx(), reservedTextPx(window), 0.01f)
assertEquals(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 16f, window), drawnTextPx(), 0.01f)
val synced = DisplayMetricsHolder.getScreenDisplayMetrics()
assertEquals(window.densityDpi, synced.densityDpi)
assertEquals(display.widthPixels, synced.widthPixels)
assertEquals(display.heightPixels, synced.heightPixels)
}
@Test
fun leavesTheBuiltInDisplayAlone() {
PaseoDisplayMetrics.syncWithWindow(windowAt(display.densityDpi))
assertSame(display, DisplayMetricsHolder.getScreenDisplayMetrics())
}
@Test
fun waitsForReactNativeToReadTheDisplay() {
DisplayMetricsHolder.setScreenDisplayMetrics(null)
PaseoDisplayMetrics.syncWithWindow(windowAt(display.densityDpi / 2))
assertThrows(IllegalStateException::class.java) { DisplayMetricsHolder.getScreenDisplayMetrics() }
}
private fun windowAt(densityDpi: Int): DisplayMetrics =
DisplayMetrics().apply {
setTo(display)
this.densityDpi = densityDpi
density = densityDpi.toFloat() / DisplayMetrics.DENSITY_DEFAULT
scaledDensity = density * display.scaledDensity / display.density
}
/** A 16sp font as React Native draws it, in pixels. */
private fun drawnTextPx(): Float = PixelUtil.toPixelFromSP(16f)
/** The box React Native lays out for that font, once the window renders it in pixels. */
private fun reservedTextPx(window: DisplayMetrics): Float =
PixelUtil.toDIPFromPixel(drawnTextPx()) * window.density
}
@@ -0,0 +1,43 @@
package sh.paseo.displaymetrics
import android.app.Activity
import android.util.DisplayMetrics
import com.facebook.react.uimanager.DisplayMetricsHolder
/**
* React Native 0.86 converts between px and dp, and so sizes text, with the density of the
* device's built-in display, because `DisplayMetricsHolder` reads `Display.getRealMetrics()`.
* Fabric lays out at the window's density. On a display with another density, such as a Samsung
* DeX monitor, text boxes come out too small and clip their text.
*
* Backports react/react-native#59087 (`useWindowDensityForDisplayMetricsAndroid`): keep the
* window's density and take only the size from the display. Remove once the app runs React Native
* 0.89 or later with that flag on.
*/
object PaseoDisplayMetrics {
/** Call right after React Native reads the display, which it does again on each configuration change. */
@JvmStatic
fun syncWithWindow(activity: Activity) {
syncWithWindow(activity.resources.displayMetrics)
}
@JvmStatic
fun syncWithWindow(window: DisplayMetrics) {
val screen =
try {
DisplayMetricsHolder.getScreenDisplayMetrics()
} catch (_: IllegalStateException) {
// React Native hasn't read the display yet, so there is nothing to correct.
return
}
if (screen.densityDpi == window.densityDpi) return
DisplayMetricsHolder.setScreenDisplayMetrics(
DisplayMetrics().apply {
setTo(screen)
density = window.density
densityDpi = window.densityDpi
},
)
}
}
@@ -0,0 +1,35 @@
const { withMainActivity } = require("expo/config-plugins");
const ACTIVITY_CLASS = "class MainActivity : ReactActivity() {";
const SYNC = "sh.paseo.displaymetrics.PaseoDisplayMetrics.syncWithWindow(this)";
// React Native re-reads the built-in display's density when it creates the root view and on every
// configuration change, so the window's density has to be restored right after each `super` call.
const OVERRIDES = `
override fun onContentChanged() {
super.onContentChanged()
${SYNC}
}
override fun onConfigurationChanged(newConfig: android.content.res.Configuration) {
super.onConfigurationChanged(newConfig)
${SYNC}
}
`;
function configureDisplayMetricsActivity(contents) {
if (contents.includes(SYNC)) return contents;
if (
!contents.includes(ACTIVITY_CLASS) ||
/override fun on(ContentChanged|ConfigurationChanged)\(/.test(contents)
) {
throw new Error("Could not keep React Native text at the window's density in MainActivity");
}
return contents.replace(ACTIVITY_CLASS, `${ACTIVITY_CLASS}${OVERRIDES}`);
}
module.exports = (config) =>
withMainActivity(config, (mod) => {
mod.modResults.contents = configureDisplayMetricsActivity(mod.modResults.contents);
return mod;
});
module.exports.configureDisplayMetricsActivity = configureDisplayMetricsActivity;
@@ -0,0 +1,29 @@
import { describe, expect, it } from "vitest";
const { configureDisplayMetricsActivity } = require("./app.plugin");
const SYNC = "sh.paseo.displaymetrics.PaseoDisplayMetrics.syncWithWindow(this)";
describe("Android display metrics", () => {
it("restores the window's density after React Native reads the display", () => {
const source = "class MainActivity : ReactActivity() {\n}";
const result = configureDisplayMetricsActivity(source);
expect(result).toContain(`super.onContentChanged()\n ${SYNC}`);
expect(result).toContain(`super.onConfigurationChanged(newConfig)\n ${SYNC}`);
expect(configureDisplayMetricsActivity(result)).toBe(result);
});
it("fails prebuild when the template no longer has a place for the overrides", () => {
expect(() => configureDisplayMetricsActivity("changed template")).toThrow(
"Could not keep React Native text at the window's density",
);
});
it("fails prebuild rather than replace another plugin's configuration handler", () => {
const source =
"class MainActivity : ReactActivity() {\n override fun onConfigurationChanged(newConfig: Configuration) {}\n}";
expect(() => configureDisplayMetricsActivity(source)).toThrow(
"Could not keep React Native text at the window's density",
);
});
});
@@ -0,0 +1,6 @@
{
"platforms": ["android"],
"android": {
"modules": []
}
}
@@ -0,0 +1,5 @@
{
"name": "paseo-display-metrics",
"version": "0.1.0",
"private": true
}
@@ -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}
@@ -851,6 +851,94 @@ it("copies a selection inside semantic inline code without Markdown escaping", (
);
});
it("keeps intraword underscores in prose unescaped", () => {
const message = mountFixture();
message.innerHTML = "<p>Set max_retries and snake_case before the call.</p>";
const paragraph = fixtureElement(message, "p");
expect(createAssistantSelectionClipboardContent(selectNodeContents(paragraph))?.plainText).toBe(
"Set max_retries and snake_case before the call.",
);
});
it("copies literal paired underscores raw in text/plain and escaped in text/html", () => {
const message = mountFixture();
message.innerHTML = "<p>literal _word_ stays literal</p>";
const paragraph = fixtureElement(message, "p");
const content = createAssistantSelectionClipboardContent(selectNodeContents(paragraph));
expect(content?.plainText).toBe("literal _word_ stays literal");
expect(content?.html).toContain("literal _word_ stays literal");
});
it("copies a path the renderer recognized as text, and an authored link as a link", () => {
const message = mountFixture();
message.innerHTML =
'<p>See <a href="src/index.ts" data-paseo-markdown-recognized-link="true">src/index.ts</a> and <a href="https://example.test/doc">the doc</a>.</p>';
const content = createAssistantSelectionClipboardContent(selectNodeContents(message));
expect(content?.plainText).toBe("See src/index.ts and [the doc](https://example.test/doc).");
expect(content?.html).not.toContain('href="src/index.ts"');
});
it("copies a recognized inline-code path without its link", () => {
const message = mountFixture();
message.innerHTML =
'<p>Edited <a href="src/app.tsx" data-paseo-markdown-recognized-link="true"><code>src/app.tsx</code></a> today.</p>';
const content = createAssistantSelectionClipboardContent(selectNodeContents(message));
expect(content?.plainText).toBe("Edited `src/app.tsx` today.");
expect(content?.html).not.toContain('href="src/app.tsx"');
});
it("copies a recognized web link as its text in text/plain and as a link in text/html", () => {
const message = mountFixture();
message.innerHTML =
'<p>Fixed in <a href="https://github.com/o/r/issues/12" data-paseo-markdown-recognized-link="true">#12</a> today.</p>';
const content = createAssistantSelectionClipboardContent(selectNodeContents(message));
expect(content?.plainText).toBe("Fixed in #12 today.");
expect(content?.html).toContain('<a href="https://github.com/o/r/issues/12">#12</a>');
});
it("copies a recognized Windows drive path as text in both clipboard flavors", () => {
const message = mountFixture();
message.innerHTML =
'<p>Open <a href="C:%5Crepo%5Csrc%5Cx.ts" data-paseo-markdown-recognized-link="true">C:\\repo\\src\\x.ts</a> now.</p>';
const content = createAssistantSelectionClipboardContent(selectNodeContents(message));
expect(content?.plainText).toBe("Open C:\\repo\\src\\x.ts now.");
expect(content?.html).not.toContain("<a ");
});
it("keeps literal angle brackets around a URL in text/html", () => {
const message = mountFixture();
message.innerHTML = "<p>Open &lt;http://localhost:3000&gt; before the call.</p>";
const content = createAssistantSelectionClipboardContent(selectNodeContents(message));
expect(content?.plainText).toBe("Open <http://localhost:3000> before the call.");
expect(content?.html).toContain("<p>Open &lt;http://localhost:3000&gt; before the call.</p>");
});
it("keeps a heading marker split across inline elements literal in text/html", () => {
const message = mountFixture();
message.innerHTML = "<p>Use <strong>C#</strong> for the service layer.</p>";
const paragraph = fixtureElement(message, "p");
const range = document.createRange();
range.setStart(textNode(fixtureElement(message, "strong")), 1);
range.setEnd(paragraph.lastChild!, paragraph.lastChild!.textContent!.length);
const selection = window.getSelection()!;
selection.removeAllRanges();
selection.addRange(range);
const content = createAssistantSelectionClipboardContent(selection);
expect(content?.plainText).toBe("# for the service layer.");
expect(content?.html).toContain("<p># for the service layer.</p>");
});
it("keeps table cell pipes escaped in text/plain table syntax and literal in text/html", () => {
const message = mountFixture();
message.innerHTML =
"<table><thead><tr><th>Header | label</th></tr></thead><tbody><tr><td>Value | detail</td></tr></tbody></table>";
const content = createAssistantSelectionClipboardContent(selectNodeContents(message));
expect(content?.plainText).toContain("Header \\| label");
expect(content?.plainText).toContain("Value \\| detail");
expect(content?.html).toContain("<th>Header | label</th>");
expect(content?.html).toContain("<td>Value | detail</td>");
});
it("copies a workspace image path instead of its temporary display URL", () => {
const message = mountFixture();
const sources = JSON.stringify({ "blob:preview": "assets/chart.png" });
@@ -2,7 +2,7 @@ import TurndownService from "turndown";
import { gfm } from "turndown-plugin-gfm";
import {
createCodeClipboardContent,
createMarkdownClipboardContent,
createSelectionClipboardContent,
type MarkdownClipboardContent,
} from "@/utils/rich-clipboard";
import {
@@ -15,6 +15,7 @@ import {
MARKDOWN_COPY_LIST_START_ATTRIBUTE,
MARKDOWN_COPY_SRC_ATTRIBUTE,
MARKDOWN_COPY_TAG_ATTRIBUTE,
MARKDOWN_COPY_RECOGNIZED_LINK_ATTRIBUTE,
MARKDOWN_COPY_UNWRAP_ATTRIBUTE,
TRAILING_CODE_LINE_BREAKS,
} from "./markup";
@@ -56,40 +57,68 @@ function copySemanticAttributes(original: Element, copy: Element): void {
}
}
const turndown = new TurndownService({
bulletListMarker: "-",
codeBlockStyle: "fenced",
emDelimiter: "_",
strongDelimiter: "**",
});
turndown.use(gfm);
turndown.addRule("escapedGfmTableCell", {
filter: ["th", "td"],
replacement: (content, node) => {
const index = node.parentNode ? Array.from(node.parentNode.childNodes).indexOf(node) : 0;
const prefix = index === 0 ? "| " : " ";
return `${prefix}${content.replace(/\|/g, "\\|")} |`;
},
});
turndown.addRule("gfmStrikethrough", {
filter: ["del", "s"],
replacement: (content) => `~~${content}~~`,
});
turndown.addRule("compactListItem", {
filter: "li",
replacement: (content, node, options) => {
const item = content
.replace(/^\n+/, "")
.replace(/\n+$/, "\n")
// Every non-empty line, so indented code lines stay inside the item.
.replace(/\n(?=[^\n])/g, "\n ");
const parent = node.parentElement;
if (parent?.nodeName !== "OL") {
return `${options.bulletListMarker} ${item}\n`;
}
return `${node.getAttribute("value")}. ${item}\n`;
},
});
function createTurndown(flavor: "markdown" | "plain"): TurndownService {
const turndown = new TurndownService({
bulletListMarker: "-",
codeBlockStyle: "fenced",
emDelimiter: "_",
strongDelimiter: "**",
});
turndown.use(gfm);
// text/plain still carries tables as GFM syntax, so a cell's pipe stays escaped there.
turndown.addRule("escapedGfmTableCell", {
filter: ["th", "td"],
replacement: (content, node) => {
const index = node.parentNode ? Array.from(node.parentNode.childNodes).indexOf(node) : 0;
const prefix = index === 0 ? "| " : " ";
return `${prefix}${content.replace(/\|/g, "\\|")} |`;
},
});
// A link Paseo recognized pastes as the text the reply showed. Rich paste keeps it as a
// link when it points to a web page, such as a forge reference.
turndown.addRule("recognizedLink", {
filter: (node) =>
node.nodeName === "A" &&
node.hasAttribute(MARKDOWN_COPY_RECOGNIZED_LINK_ATTRIBUTE) &&
(flavor === "plain" || !isWebUrl(node.getAttribute("href") ?? "")),
replacement: (content) => content,
});
if (flavor === "markdown") {
// Turndown leaves `<` unescaped, so displayed text such as `<http://localhost>`
// would render back into text/html as an autolink.
const escapeMarkdown = turndown.escape.bind(turndown);
turndown.escape = (text) => escapeMarkdown(text).replace(/</g, "\\<");
} else {
turndown.escape = (text) => text;
}
turndown.addRule("gfmStrikethrough", {
filter: ["del", "s"],
replacement: (content) => `~~${content}~~`,
});
turndown.addRule("compactListItem", {
filter: "li",
replacement: (content, node, options) => {
const item = content
.replace(/^\n+/, "")
.replace(/\n+$/, "\n")
// Every non-empty line, so indented code lines stay inside the item.
.replace(/\n(?=[^\n])/g, "\n ");
const parent = node.parentElement;
if (parent?.nodeName !== "OL") {
return `${options.bulletListMarker} ${item}\n`;
}
return `${node.getAttribute("value")}. ${item}\n`;
},
});
return turndown;
}
function isWebUrl(href: string): boolean {
return /^https?:\/\//i.test(href);
}
const markdownTurndown = createTurndown("markdown");
const plainTurndown = createTurndown("plain");
export function createAssistantSelectionClipboardContent(
selection: Selection | null,
@@ -117,11 +146,15 @@ export function createAssistantSelectionClipboardContent(
}
restoreMarkdownElements(container);
const markdown = turndown.turndown(container.innerHTML).trim();
const markdown = markdownTurndown.turndown(container).trim();
if (!markdown) {
return null;
}
const content = createMarkdownClipboardContent(markdown);
// text/plain carries unescaped Markdown: a plain target shows backslashes literally.
// text/html is rendered from escaped Markdown, so literal Markdown characters stay
// literal in a rich target.
const plainText = plainTurndown.turndown(container).trim();
const content = createSelectionClipboardContent(markdown, plainText);
return { ...content, html: flattenClipboardListMarkup(content.html) };
}
@@ -651,13 +684,15 @@ function restoreMarkdownElements(container: HTMLElement): void {
for (const element of presentational.toReversed()) {
element.replaceWith(...element.childNodes);
}
// Turndown escapes line-start Markdown per text node, so text split by an unwrapped
// element, such as `#` and ` for`, has to be one node to keep `# for` literal.
container.normalize();
}
/**
* Each item carries its number before Turndown re-parses the HTML. Until then every
* child of the list is one item, including a partly selected item demoted to a `p`.
* The parser splits a `p` that holds a code block into several siblings, so counting
* siblings afterwards numbers the next item too high.
* Assign item numbers before passing the DOM to Turndown. A partly selected item
* still takes its original list position when copied as a paragraph, so the following
* items keep their numbers.
*/
function numberOrderedListItems(list: Element, start: number): void {
Array.from(list.children).forEach((child, index) => {
@@ -2,6 +2,8 @@ export const MARKDOWN_COPY_TAG_ATTRIBUTE = "data-paseo-markdown-tag";
export const MARKDOWN_COPY_IGNORE_ATTRIBUTE = "data-paseo-markdown-ignore";
export const MARKDOWN_COPY_LIST_MARKER_ATTRIBUTE = "data-paseo-markdown-list-marker";
export const MARKDOWN_COPY_UNWRAP_ATTRIBUTE = "data-paseo-markdown-unwrap";
/** A link Paseo recognized in the reply text, as opposed to one the Markdown wrote. */
export const MARKDOWN_COPY_RECOGNIZED_LINK_ATTRIBUTE = "data-paseo-markdown-recognized-link";
export const MARKDOWN_COPY_LIST_START_ATTRIBUTE = "data-paseo-markdown-list-start";
export const MARKDOWN_COPY_LANGUAGE_ATTRIBUTE = "data-paseo-markdown-language";
export const MARKDOWN_COPY_ALIGN_ATTRIBUTE = "data-paseo-markdown-align";
+2 -2
View File
@@ -10,8 +10,8 @@ import { createHostBackgroundWorkModel } from "./host";
import { backgroundWorkText } from "./presentation";
export { createHostBackgroundWorkModel } from "./host";
function kindKey(kind: string): "shell" | "monitor" | "other" {
if (kind === "shell" || kind === "monitor") return kind;
function kindKey(kind: string): "shell" | "monitor" | "heartbeat" | "other" {
if (kind === "shell" || kind === "monitor" || kind === "heartbeat") return kind;
return "other";
}
@@ -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}>
@@ -17,6 +17,11 @@ export function nextPageLimit(limit: number): number {
return PAGE_LIMITS.find((candidate) => candidate > limit) ?? limit;
}
/** The page Load more grew this limit from, or null for the first page. */
export function previousPageLimit(limit: number): number | null {
return PAGE_LIMITS.findLast((candidate) => candidate < limit) ?? null;
}
export function requiresImportSessionsHostUpgrade(input: {
supportsSnapshot: boolean;
workspaceId?: string | null;
@@ -1172,6 +1172,44 @@ describe("ImportSessionSheet", () => {
});
});
it("keeps the loaded list in place while Load more fetches the next page", async () => {
let releaseNextPage: () => void = () => undefined;
const nextPage = new Promise<void>((resolve) => {
releaseNextPage = resolve;
});
const fetchRecentProviderSessions = vi.fn(async (options: { limit?: number } | undefined) => {
if (options?.limit !== 15) await nextPage;
return {
requestId: "recent-provider-sessions",
entries: createPageOfEntries(options?.limit === 15 ? 15 : 20),
};
});
renderSheet(createRecentSessionsClient(fetchRecentProviderSessions, vi.fn()), {
cwd: null,
snapshot: { supportsSnapshot: true, entries: [createSnapshotEntry("claude")] },
});
fireEvent.click(await screen.findByTestId("import-session-load-more"));
// The list the user scrolled to Load more is the one they keep: replacing it would drop
// them back at the top, behind a loading state, until the larger page lands.
const list = screen.getByTestId("import-session-list");
await waitFor(() => {
expect(fetchRecentProviderSessions).toHaveBeenCalledWith({
providers: ["claude"],
limit: 45,
});
});
expect(screen.getByTestId("import-session-list")).toBe(list);
expect(screen.queryByText("Loading sessions...")).toBeNull();
releaseNextPage();
await waitFor(() => {
expect(screen.queryByTestId("import-session-load-more")).toBeNull();
});
expect(screen.getByTestId("import-session-list")).toBe(list);
});
it("stops the refresh spinner and retries only the failed provider", async () => {
const fetchRecentProviderSessions = vi.fn(
async (options: { providers?: string[] } | undefined) => {
@@ -1,6 +1,6 @@
import React, { type ReactNode, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Pressable, type PressableStateCallbackType, Text, View } from "react-native";
import { keepPreviousData, useMutation, useQueries, useQueryClient } from "@tanstack/react-query";
import { useMutation, useQueries, useQueryClient, type QueryClient } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import type {
DaemonClient,
@@ -40,6 +40,7 @@ import {
resolveDirectoryLabel,
nextPageLimit,
PER_PROVIDER_LIMIT,
previousPageLimit,
type ProviderErrorRow,
resolveImportTarget,
resolveProvidersToFetch,
@@ -100,11 +101,12 @@ interface SessionsQueryConfig {
// Query's default retry would keep the header spinner turning and pile up
// in-flight daemon requests behind a dead provider (#2512).
retry: false;
placeholderData: typeof keepPreviousData;
placeholderData: () => RecentSessionsResponse | undefined;
queryFn: () => Promise<RecentSessionsResponse>;
}
function buildSessionsQueriesConfig(args: {
queryClient: QueryClient;
providersToFetch: AgentProvider[] | null;
visible: boolean;
client: RecentProviderSessionsClient | null;
@@ -113,14 +115,24 @@ function buildSessionsQueriesConfig(args: {
limit: number;
hostDisconnectedMessage?: string;
}): SessionsQueryConfig[] {
const { providersToFetch, visible, client, cwd, query, limit, hostDisconnectedMessage } = args;
const { queryClient, providersToFetch, visible, client, cwd, query, limit } = args;
const { hostDisconnectedMessage } = args;
if (providersToFetch === null) return [];
const enabled = visible && Boolean(client);
const previousLimit = previousPageLimit(limit);
return providersToFetch.map((provider) => ({
queryKey: buildSessionsQueryKey({ cwd, query, limit, provider }),
enabled,
retry: false as const,
placeholderData: keepPreviousData,
// While Load more fetches the next page, keep showing the page it grew from. React Query's
// keepPreviousData cannot do this here: useQueries gives a changed key a new observer, which
// has no previous data, so the rows would vanish and the list would remount at the top.
placeholderData: () =>
previousLimit === null
? undefined
: queryClient.getQueryData<RecentSessionsResponse>(
buildSessionsQueryKey({ cwd, query, limit: previousLimit, provider }),
),
queryFn: async () => {
if (!client) {
throw new Error(hostDisconnectedMessage ?? i18n.t("workspace.terminal.hostDisconnected"));
@@ -522,6 +534,7 @@ export function ImportSessionSheet({
const queriesConfig = useMemo(
() =>
buildSessionsQueriesConfig({
queryClient,
providersToFetch,
visible,
client,
@@ -530,7 +543,7 @@ export function ImportSessionSheet({
limit: pageLimit,
hostDisconnectedMessage: t("workspace.terminal.hostDisconnected"),
}),
[providersToFetch, visible, client, scopeCwd, query, pageLimit, t],
[queryClient, providersToFetch, visible, client, scopeCwd, query, pageLimit, t],
);
const queries = useQueries({ queries: queriesConfig });
@@ -13,7 +13,7 @@ import { decodeMarkdownImage, getMarkdownImageStatus } from "./image-decoding";
import { describe, expect, it } from "vitest";
import { darkTheme, lightTheme } from "@/styles/theme";
import { createMarkdownStyles } from "./styles";
import { prepareMarkdownSource, PENDING_MARKDOWN_IMAGE } from "./source";
import { isRecognizedLink, prepareMarkdownSource, PENDING_MARKDOWN_IMAGE } from "./source";
import { normalizeMarkdownHtml } from "./html";
it("recognizes complete known commands in inline code", () => {
@@ -38,6 +38,13 @@ it("resolves authored root-relative links only when the target is a known comman
expect(matchCommandLink("https://example.com/code-review", "markdown", names)).toBeNull();
});
it("treats only a parsed path or code span as a link the author did not write", () => {
expect(isRecognizedLink({ sourceType: "text" })).toBe(true);
expect(isRecognizedLink({ sourceType: "inline-code" })).toBe(true);
expect(isRecognizedLink({ sourceType: "markdown" })).toBe(false);
expect(isRecognizedLink({})).toBe(false);
});
describe("shared Markdown source adaptation", () => {
it("keeps paragraphs, fences and quotes together for the library", () => {
const source = "First paragraph.\n\nSecond paragraph.\n\n```ts\nconst n = 1;\n```\n\n> Quote";
@@ -0,0 +1,61 @@
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, expect, it } from "vitest";
import { i18n } from "@/i18n/i18next";
import { WEB_RENDERERS } from "./renderers.web";
const Link = WEB_RENDERERS.link;
const LINK_TEXT = "src/index.ts";
let root: Root;
let container: HTMLDivElement;
beforeEach(async () => {
await i18n.changeLanguage("en");
container = document.createElement("div");
document.body.append(container);
root = createRoot(container);
});
afterEach(() => {
act(() => root.unmount());
container.remove();
});
function anchorPropsFor(url: string) {
return { href: url };
}
function renderAnchor(link: { url: string; sourceType?: "markdown" | "text" | "inline-code" }) {
if (!Link) {
throw new Error("Expected a web link renderer");
}
const anchorProps = anchorPropsFor(link.url);
const client = new QueryClient();
act(() =>
root.render(
<QueryClientProvider client={client}>
<Link link={link} anchorProps={anchorProps}>
{LINK_TEXT}
</Link>
</QueryClientProvider>,
),
);
const anchor = container.querySelector("a");
if (!anchor) {
throw new Error("Expected a rendered link");
}
return anchor;
}
it("marks a link it recognized from a path for selection copy", () => {
const anchor = renderAnchor({ url: LINK_TEXT, sourceType: "text" });
expect(anchor.getAttribute("href")).toBe(LINK_TEXT);
expect(anchor.getAttribute("data-paseo-markdown-recognized-link")).toBe("true");
});
it("leaves an authored link wrapped", () => {
const anchor = renderAnchor({ url: "https://example.test/doc", sourceType: "markdown" });
expect(anchor.hasAttribute("data-paseo-markdown-recognized-link")).toBe(false);
});
@@ -7,12 +7,13 @@ import type {
} from "react-native-enriched-markdown";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { useFileLink } from "@/assistant-file-links";
import { MARKDOWN_COPY_RECOGNIZED_LINK_ATTRIBUTE } from "@/assistant-selection-copy/markup";
import { useForgeShorthand } from "@/git/forge-shorthand";
import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";
import { HighlightedCodeBlock } from "@/components/highlighted-code-block";
import type { Theme } from "@/styles/theme";
import { MermaidFence } from "./fence/mermaid";
import { markdownLinkSource } from "./source";
import { isRecognizedLink, markdownLinkSource } from "./source";
const ThemedCodeBlock = withUnistyles(HighlightedCodeBlock);
const codeStyle = (theme: Theme) => ({
@@ -50,9 +51,18 @@ function WebLink({ link, anchorProps, children }: LinkRendererProps) {
}),
[anchorProps.style, hovered],
);
// Selection copy pastes a link Paseo recognized as the text the reply showed.
const recognized = isRecognizedLink(link);
const copyAnchorProps = useMemo(
() =>
recognized
? { ...anchorProps, [MARKDOWN_COPY_RECOGNIZED_LINK_ATTRIBUTE]: "true" }
: anchorProps,
[anchorProps, recognized],
);
const anchor = (
<a
{...anchorProps}
{...copyAnchorProps}
href={forgeUrl ?? anchorProps.href}
style={anchorStyle}
onMouseEnter={handleMouseEnter}
+11 -1
View File
@@ -111,15 +111,25 @@ function collectInlineCodePaths(
return paths;
}
type LinkSourceType = "markdown" | "text" | "inline-code";
export function markdownLinkSource(
url: string,
sourceType?: "markdown" | "text" | "inline-code",
sourceType?: LinkSourceType,
): AssistantFileLinkSource {
if (sourceType === "inline-code") return { href: url, text: url, sourceType };
if (sourceType === "text") return { href: url, text: url, markup: "linkify" };
return { href: url, text: url };
}
/**
* Link recognition classifies matches as `text` or `inline-code`. The renderer
* classifies parser autolinks such as `www.example.com` as `markdown`.
*/
export function isRecognizedLink(link: { sourceType?: LinkSourceType }): boolean {
return link.sourceType === "text" || link.sourceType === "inline-code";
}
// Generated by scripts/generate-markdown-image-placeholder.mjs; reserves the image box.
export const PENDING_MARKDOWN_IMAGE =
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAoAAAAKACAYAAAAMzckjAAAACXBIWXMAAAsTAAALEwEAmpwYAAAKBklEQVR42u3dXWscVRgH8ElFLK032tiCN1nSEiiowdKAn8DY2rR+AG965Qt4Y24Sm91kd5tN1ogQaGzzFfIl43Nki+s4u+m+ZWfC7weH0M6Z2QPn5s8zc87JMgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgKvm/Px8YXd3d7Hdbi/Ns6UxxHAWzAgAwIxE4LrebDafxd/f9/b2TkvSujGep2lsZggAYIr29/c/iZDVKlHwy7dmryIIAEA2hcpfo9Folzj89YdAlUAAgEml174VCH//tBjrhhkDAMgmXvDxn2/+4t+von0dbXmOC0CW6/X6ehpL/9iiUtnNLAwBAMgmef27mK+ypfCXlac6uZ4fX6fTuWXmAADGD4C1fMCKCtzdsowvjaUgoNbMHADA+AFwuSBgLRsfAIAAmL/vRrSVVqu1mipy0a4JgAAAVzAAbm9v34nrP0a/17l7/oz25PT09H0BEADgigTAnZ2d+3H9eNg2LXHvb9E+FAABACoeAFPl76Lw13f/r9mUtmoRAAEA5hQAe69933nD5uj/UAAEAKhoAOwt+Pgr1+cwFoB8Hn9vx159j+Lvm9xzfhEAAQCqGwBXCvp80d8n/u957vofAiAAQEUDYCz+WC3oczv3nMe5I9tOBEAAgOpWAP93Wkh67fv2+tnZ2Xtp9W+uz74ACABQ3QB4Le3zl+uTvvl73qv8vSh4xvcCIABAhVcB1+v1jRFWAb+OZ3x60RnE0b6Lvj+kFhXFZ3Hu75IACABQkgCYTvgoeM07aAuYx4N+7+jo6GZc/3nI/T9tbm7eFAABAEpwEkg64SOubw6r/EUl79tswCbQW1tbH8XikPZFATL1SX0FQACAEpwFnMJd2uQ57fMX7SjaSVrwkb75G/baNwW6uP5yhI2kX/buEQABAOYcAEd2Qfh7Edd2BoXA2Gx6VQAEAKhQABwU/tLJIrGwZC37d5HJWv60kd7r4K4ACABQkQCYwl88rz3gW8G1fP+o9n1ZFAIFQACACgTAUcPfKCFQAAQAKFkAHDf8vWsIFAABAEoUAId98xftwQjjejAoBHY6nXtmDgCgBAFwWuGvPwSmqmHB874ycwAAcw6A0w5/b8Ur40f5Z8Yr4vtmDgBgjgFwVuHPSSAAACUMgJMu+BAAAQAqFABnHf4EQACAEgXAywh/AiAAQEkC4GWFPwEQAKAEAfAyw58ACAAw5wB42eFPAAQAmE3AquUDVrvdvluG8Ncb372CAFgzcwAA4wesxXzAqtfr62UIf73xfVNwFNwtMwcAML6FCFXdXIXtVQS79fSqNdpn0Q4LqnBv0ikdUS1cmkVLv52e32g0TnK/e5jGbNoAALKJqmxPC6p7pWwx1idmDABg8gB4PcJVswLhb+/4+PgDMwYAMKVvAaO1yhz+0hjNFADAFKXqWnx3txHf3XVLFPwO02tflT8AgNlaSCtt02KMg4ODWlrpGyFsZVYLPoYsBPnYgg8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOBK+hsMQ7RDjzvGwwAAAABJRU5ErkJggg==";
@@ -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()
@@ -86,6 +86,7 @@ import {
} from "@/components/ui/dropdown-menu";
import { ProjectLeadingVisual } from "@/components/sidebar/project-leading-visual";
import { useToast } from "@/contexts/toast-context";
import { SidebarToastClearance } from "@/components/sidebar/sidebar-toast-region";
import { getForgePresentation, normalizeForge } from "@/git/forge";
import { hasVisibleOrderChanged, mergeWithRemainder } from "@/utils/sidebar-reorder";
import { confirmDialog } from "@/utils/confirm-dialog";
@@ -2551,6 +2552,7 @@ function ProjectModeList({
: null}
{sidebarFilterEmpty ? <SidebarFilterEmptyState /> : projectBody}
{listFooterComponent}
<SidebarToastClearance />
</>
);
@@ -2592,8 +2594,7 @@ const styles = StyleSheet.create((theme) => ({
// Optical inset: aligns the visible Pinned/Workspaces glyph edge with the
// Schedules icon across the divider; their layout boxes have different insets.
paddingTop: 2,
// The sidebar toast floats over the list's end. Keep this padding the same whether or not
// a toast shows: changing it moves the rows when the toast leaves.
// Room for the sidebar toast comes from SidebarToastClearance at the end of the content.
paddingBottom: theme.spacing[4],
},
projectListContainer: {
@@ -34,6 +34,7 @@ import {
CircleX,
} from "lucide-react-native";
import { useToast } from "@/contexts/toast-context";
import { SidebarToastClearance } from "@/components/sidebar/sidebar-toast-region";
import { useSidebarWorkspaceRename } from "@/workspace-rename";
import { useWorkspaceClipboardActions } from "@/hooks/use-workspace-clipboard-actions";
import { redirectIfArchivingActiveWorkspace } from "@/utils/sidebar-workspace-archive-redirect";
@@ -270,6 +271,7 @@ export function SidebarStatusWorkspaceList({
onToggleWorkspacePin={onToggleWorkspacePin}
/>
)}
<SidebarToastClearance />
</>
);
@@ -1089,8 +1091,7 @@ const styles = StyleSheet.create((theme) => ({
paddingHorizontal: theme.spacing[2],
// Keep status mode's Pinned/Workspaces boundary identical to project mode.
paddingTop: 2,
// The sidebar toast floats over the list's end. Keep this padding the same whether or not
// a toast shows: changing it moves the rows when the toast leaves.
// Room for the sidebar toast comes from SidebarToastClearance at the end of the content.
paddingBottom: theme.spacing[4],
},
pinnedSection: {
@@ -1,9 +1,31 @@
import { useEffect, useMemo, useRef, type ReactNode } from "react";
import {
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useRef,
type ReactNode,
} from "react";
import { View } from "react-native";
import Animated, {
useAnimatedStyle,
useSharedValue,
withTiming,
type SharedValue,
} from "react-native-reanimated";
import { StyleSheet } from "react-native-unistyles";
import { ToastViewport, useToastHost, type ToastApi } from "@/components/toast-host";
import { TOAST_FADE_MS, ToastViewport, useToastHost, type ToastApi } from "@/components/toast-host";
import { ToastApiProvider, useToast } from "@/contexts/toast-context";
interface SidebarToastCoverage {
toastVisible: boolean;
/** Distance from the region's bottom edge to the toast's top edge, as last laid out. */
height: SharedValue<number>;
}
const SidebarToastCoverageContext = createContext<SidebarToastCoverage | null>(null);
/**
* Shows toasts raised by the sidebar's list over its bottom edge, just above the footer.
*
@@ -15,6 +37,8 @@ export function SidebarToastRegion({ active, children }: { active: boolean; chil
const appToast = useToast();
const { api: sidebarToast, toast, dismiss } = useToastHost();
const activeRef = useRef(active);
const coverageHeight = useSharedValue(0);
const toastVisible = toast !== null;
useEffect(() => {
activeRef.current = active;
@@ -35,14 +59,58 @@ export function SidebarToastRegion({ active, children }: { active: boolean; chil
};
}, [appToast, sidebarToast]);
const coverage = useMemo<SidebarToastCoverage>(
() => ({ toastVisible, height: coverageHeight }),
[toastVisible, coverageHeight],
);
const handleCoverageChange = useCallback(
(height: number) => {
coverageHeight.value = height;
},
[coverageHeight],
);
return (
<View style={styles.region}>
<ToastApiProvider api={api}>{children}</ToastApiProvider>
<ToastViewport toast={toast} onDismiss={dismiss} placement="sidebar" />
<SidebarToastCoverageContext.Provider value={coverage}>
<ToastApiProvider api={api}>{children}</ToastApiProvider>
</SidebarToastCoverageContext.Provider>
<ToastViewport
toast={toast}
onDismiss={dismiss}
placement="sidebar"
onBottomCoverageChange={handleCoverageChange}
/>
</View>
);
}
/**
* Space at the end of a sidebar list that matches the toast covering it, so the last row can
* scroll clear of the toast. It sits below every row, so growing it moves nothing. It shrinks
* with the toast's fade, so a list scrolled to its end settles back with the toast instead of
* jumping.
*/
export function SidebarToastClearance() {
const coverage = useContext(SidebarToastCoverageContext);
return coverage ? <AnimatedClearance coverage={coverage} /> : null;
}
function AnimatedClearance({ coverage }: { coverage: SidebarToastCoverage }) {
const { toastVisible, height } = coverage;
const style = useAnimatedStyle(() => ({
height: withTiming(toastVisible ? height.value : 0, { duration: TOAST_FADE_MS }),
}));
return (
<Animated.View
style={style}
pointerEvents="none"
testID="sidebar-toast-clearance"
aria-hidden
/>
);
}
const styles = StyleSheet.create({
region: {
position: "relative",
+27 -6
View File
@@ -4,7 +4,14 @@ import {
} from "@/components/floating-header";
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import { createPortal } from "react-dom";
import { Platform, StyleSheet as NativeStyleSheet, Text, ToastAndroid, View } from "react-native";
import {
Platform,
StyleSheet as NativeStyleSheet,
Text,
ToastAndroid,
View,
type LayoutChangeEvent,
} from "react-native";
import Animated, { FadeIn, FadeOut } from "react-native-reanimated";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
@@ -57,8 +64,11 @@ type ToastViewportPlacement = "app-shell" | "panel" | "sidebar";
const DEFAULT_DURATION_MS = 2200;
const noopDismiss: DismissToast = () => {};
const TOAST_MAX_WIDTH = 480;
const toastEntering = FadeIn.duration(140);
const toastExiting = FadeOut.duration(140);
/** How long a toast takes to fade in or out. */
export const TOAST_FADE_MS = 140;
const SIDEBAR_TOAST_INSET = SPACING[2];
const toastEntering = FadeIn.duration(TOAST_FADE_MS);
const toastExiting = FadeOut.duration(TOAST_FADE_MS);
const ThemedCheckCircle = withUnistyles(CheckCircle2);
const ThemedInfo = withUnistyles(Info);
const ThemedWarning = withUnistyles(AlertTriangle);
@@ -148,10 +158,13 @@ export function ToastViewport({
toast,
onDismiss,
placement = "app-shell",
onBottomCoverageChange,
}: {
toast: ToastState | null;
onDismiss: () => void;
placement?: ToastViewportPlacement;
/** Sidebar placement: reports the distance from the region's bottom edge to the toast's top. */
onBottomCoverageChange?: (coverage: number) => void;
}) {
const insets = useSafeAreaInsets();
const isMobile = useIsCompactFormFactor();
@@ -206,6 +219,13 @@ export function ToastViewport({
return clearTimer;
}, [clearTimer, durationMs, scheduleDismiss, toastId]);
const handleSidebarLayout = useCallback(
(event: LayoutChangeEvent) => {
onBottomCoverageChange?.(event.nativeEvent.layout.height + SIDEBAR_TOAST_INSET);
},
[onBottomCoverageChange],
);
const panelClearance = useFloatingHeaderOverlayClearance();
const headerHeight = isMobile ? HEADER_INNER_HEIGHT_MOBILE : HEADER_INNER_HEIGHT;
const headerTopPadding = isMobile ? HEADER_TOP_PADDING_MOBILE : 0;
@@ -227,6 +247,7 @@ export function ToastViewport({
}
pointerEvents="box-none"
collapsable={false}
onLayout={placement === "sidebar" ? handleSidebarLayout : undefined}
>
<View
style={placement === "sidebar" ? styles.sidebarWidthBoundary : styles.widthBoundary}
@@ -307,9 +328,9 @@ const animatedStyles = NativeStyleSheet.create({
},
sidebarContainer: {
position: "absolute",
left: SPACING[2],
right: SPACING[2],
bottom: SPACING[2],
left: SIDEBAR_TOAST_INSET,
right: SIDEBAR_TOAST_INSET,
bottom: SIDEBAR_TOAST_INSET,
zIndex: OVERLAY_Z.toast,
alignItems: "center",
},
@@ -385,6 +385,16 @@ function SessionProviderInternal({ children, serverId, client }: SessionProvider
console.warn("[Session] timeline replacement refresh failed", { serverId, error });
});
};
const onRewind = (message: SessionOutboundMessage) => {
if (message.type !== "agent.timeline.rewind") return;
const { agentId, epoch, seq, retireFromSeq } = message.payload;
sync.applyStreamEvent(agentId, {
event: { type: "rewind", retireFromSeq },
seq,
epoch,
timestamp: new Date(),
});
};
const sync = getHostRuntimeStore().createViewedTimelineOwner(serverId, {
canCheckFreshness: () =>
client.getLastServerInfoMessage()?.features?.timelineFreshnessCheck === true,
@@ -395,6 +405,7 @@ function SessionProviderInternal({ children, serverId, client }: SessionProvider
update: (message) => {
if (message.type === "agent_stream") onStream(message);
else if (message.type === "agent.timeline.replacement") onReplacement(message);
else if (message.type === "agent.timeline.rewind") onRewind(message);
},
});
return observation;
+1 -10
View File
@@ -1,7 +1,4 @@
import { PluginClientStateProvider } from "@getpaseo/plugin/client/host";
import type { PluginFilePanelProps } from "@getpaseo/plugin/client";
import { useMemo } from "react";
import { createPluginClientStateSource } from "@/plugins/client-state/source";
import { PluginInstallationProvider } from "@/plugins/installation-provider";
import { SurfaceErrorBoundary } from "@/plugins/surface-error-boundary";
import type { PluginFilePanel } from "./panels";
@@ -11,17 +8,11 @@ export function PluginFilePanelHost({
...props
}: PluginFilePanelProps & { panel: PluginFilePanel }) {
const { plugin, contribution } = panel;
const stateSource = useMemo(
() => createPluginClientStateSource(plugin.serverId),
[plugin.serverId],
);
const Component = contribution.Component;
return (
<SurfaceErrorBoundary installation={plugin} Surface={Component} key={panel.id}>
<PluginInstallationProvider plugin={plugin}>
<PluginClientStateProvider source={stateSource}>
<Component {...props} />
</PluginClientStateProvider>
<Component {...props} />
</PluginInstallationProvider>
</SurfaceErrorBoundary>
);
@@ -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"),
},
],
+11 -2
View File
@@ -6,6 +6,7 @@ import { createMacDockBadgeCountSelector } from "@/utils/desktop-badge-state";
import { createFaviconStatusSelector, type FaviconStatus } from "@/utils/favicon-status";
import { isNative } from "@/constants/platform";
import { useSessionStore } from "@/stores/session-store";
import { useSidebarViewStore } from "@/stores/sidebar-view-store";
import { useHosts } from "@/runtime/host-runtime";
type ColorScheme = "dark" | "light";
@@ -85,8 +86,16 @@ export function useFaviconStatus() {
// The favicon reads the whole fleet, so it has to keep every host's directory loading even
// though it no longer subscribes to the agent maps.
useAllDirectoryDemand({ serverIds, enabled: !isNative });
const selectFaviconStatus = useMemo(createFaviconStatusSelector, []);
const selectMacDockBadgeCount = useMemo(createMacDockBadgeCountSelector, []);
// Background workspaces count exactly when the sidebar shows them.
const showBackground = useSidebarViewStore((state) => state.showBackground);
const selectFaviconStatus = useMemo(
() => createFaviconStatusSelector({ showBackground }),
[showBackground],
);
const selectMacDockBadgeCount = useMemo(
() => createMacDockBadgeCountSelector({ showBackground }),
[showBackground],
);
const status = useSessionStore(selectFaviconStatus);
const dockBadgeCount = useSessionStore(selectMacDockBadgeCount);
const [colorScheme, setColorScheme] = useState<ColorScheme>(getSystemColorScheme);
+5 -2
View File
@@ -394,6 +394,7 @@ export const ar: TranslationResources = {
otherPlaceholder: "آخر...",
},
backgroundWork: {
heartbeat: "نبضة دورية",
pillOne: "مهمة واحدة في الخلفية",
pillMany: "{{count}} مهمة في الخلفية",
notRunning: "لم يعد قيد التشغيل",
@@ -484,8 +485,7 @@ export const ar: TranslationResources = {
archivedTitle: "مساحة العمل مؤرشفة",
restoreDescription:
"استعد {{workspaceName}} للعودة إلى وكلائها. ستستخدم شجرة العمل الفرع {{branch}}.",
restoreWithoutBranchDescription:
"استعد {{workspaceName}} للعودة إلى وكلائها. سيبدأ فرع جديد من الفرع الأساسي المحفوظ أو الفرع الافتراضي للمستودع.",
restoreWithoutBranchDescription: "استعد {{workspaceName}} للعودة إلى وكلائها.",
unarchiveDescription: "{{workspaceName}} مؤرشفة. ألغِ أرشفتها لفتحها مجددًا.",
restoreAction: "استعادة",
unarchiveAction: "إلغاء الأرشفة",
@@ -731,6 +731,8 @@ export const ar: TranslationResources = {
resumeCommandUnavailable: "أمر الاستئناف غير متوفر",
reloadingAgent: "وكيل إعادة التحميل...",
reloadedAgent: "وكيل إعادة تحميل",
reloadedAgentHistoryDiverged:
"تمت إعادة تحميل الوكيل، لكن سجل المزوّد لا يطابق هذه المحادثة، لذا لم تتم مزامنته",
failedToReloadAgent: "فشل في إعادة تحميل الوكيل",
failedToCloseAgent: "فشل في إغلاق الوكيل",
},
@@ -2017,6 +2019,7 @@ export const ar: TranslationResources = {
hostUnavailable: "مضيف التنزيل غير متاح.",
cancelled: "تم إلغاء التنزيل.",
failed: "فشل تنزيل الملف.",
httpFailed: "فشل تنزيل الملف (HTTP {{status}}).",
shareFile: "مشاركة الملف",
shareFileNamed: "مشاركة{{fileName}}",
},
+5 -2
View File
@@ -393,6 +393,7 @@ export const en = {
otherPlaceholder: "Other...",
},
backgroundWork: {
heartbeat: "Heartbeat",
pillOne: "1 background task",
pillMany: "{{count}} background tasks",
notRunning: "No longer running",
@@ -483,8 +484,7 @@ export const en = {
archivedTitle: "Workspace archived",
restoreDescription:
"Restore {{workspaceName}} to return to its agents. Its worktree will use branch {{branch}}.",
restoreWithoutBranchDescription:
"Restore {{workspaceName}} to return to its agents. A new branch will start from the saved base or the repository default.",
restoreWithoutBranchDescription: "Restore {{workspaceName}} to return to its agents.",
unarchiveDescription: "{{workspaceName}} is archived. Unarchive it to open it again.",
restoreAction: "Restore",
unarchiveAction: "Unarchive",
@@ -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",
},
@@ -2045,6 +2047,7 @@ export const en = {
hostUnavailable: "Download host is unavailable.",
cancelled: "Download was cancelled.",
failed: "Failed to download file.",
httpFailed: "Failed to download file (HTTP {{status}}).",
shareFile: "Share file",
shareFileNamed: "Share {{fileName}}",
},
+5 -2
View File
@@ -399,6 +399,7 @@ export const es: TranslationResources = {
otherPlaceholder: "Otro...",
},
backgroundWork: {
heartbeat: "Latido",
pillOne: "1 tarea en segundo plano",
pillMany: "{{count}} tareas en segundo plano",
notRunning: "Ya no está en ejecución",
@@ -489,8 +490,7 @@ export const es: TranslationResources = {
archivedTitle: "Espacio de trabajo archivado",
restoreDescription:
"Restaura {{workspaceName}} para volver a sus agentes. Su worktree usará la rama {{branch}}.",
restoreWithoutBranchDescription:
"Restaura {{workspaceName}} para volver a sus agentes. Se creará una rama nueva desde la base guardada o la rama predeterminada del repositorio.",
restoreWithoutBranchDescription: "Restaura {{workspaceName}} para volver a sus agentes.",
unarchiveDescription:
"{{workspaceName}} está archivado. Desarchívalo para volver a abrirlo.",
restoreAction: "Restaurar",
@@ -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",
},
@@ -2066,6 +2068,7 @@ export const es: TranslationResources = {
hostUnavailable: "El host de descarga no está disponible.",
cancelled: "La descarga fue cancelada.",
failed: "No se pudo descargar el archivo.",
httpFailed: "No se pudo descargar el archivo (HTTP {{status}}).",
shareFile: "compartir archivo",
shareFileNamed: "Compartir{{fileName}}",
},
+5 -2
View File
@@ -399,6 +399,7 @@ export const fr: TranslationResources = {
otherPlaceholder: "Autre…",
},
backgroundWork: {
heartbeat: "Battement périodique",
pillOne: "1 tâche en arrière-plan",
pillMany: "{{count}} tâches en arrière-plan",
notRunning: "N’est plus en cours",
@@ -489,8 +490,7 @@ export const fr: TranslationResources = {
archivedTitle: "Espace de travail archivé",
restoreDescription:
"Restaurez {{workspaceName}} pour retrouver ses agents. Son worktree utilisera la branche {{branch}}.",
restoreWithoutBranchDescription:
"Restaurez {{workspaceName}} pour retrouver ses agents. Une nouvelle branche partira de la base enregistrée ou de la branche par défaut du dépôt.",
restoreWithoutBranchDescription: "Restaurez {{workspaceName}} pour retrouver ses agents.",
unarchiveDescription: "{{workspaceName}} est archivé. Désarchivez-le pour le rouvrir.",
restoreAction: "Restaurer",
unarchiveAction: "Désarchiver",
@@ -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",
},
@@ -2065,6 +2067,7 @@ export const fr: TranslationResources = {
hostUnavailable: "L’hôte de téléchargement est indisponible.",
cancelled: "Téléchargement annulé.",
failed: "Impossible de télécharger le fichier.",
httpFailed: "Impossible de télécharger le fichier (HTTP {{status}}).",
shareFile: "Partager le fichier",
shareFileNamed: "Partager {{fileName}}",
},
+5 -2
View File
@@ -399,6 +399,7 @@ export const ja: TranslationResources = {
otherPlaceholder: "その他...",
},
backgroundWork: {
heartbeat: "ハートビート",
pillOne: "バックグラウンドタスク1件",
pillMany: "バックグラウンドタスク{{count}}件",
notRunning: "実行は終了しました",
@@ -489,8 +490,7 @@ export const ja: TranslationResources = {
archivedTitle: "ワークスペースはアーカイブ済みです",
restoreDescription:
"{{workspaceName}} を復元してエージェントに戻ります。worktree ではブランチ {{branch}} を使用します。",
restoreWithoutBranchDescription:
"{{workspaceName}} を復元してエージェントに戻ります。保存されたベース、またはリポジトリのデフォルトブランチから新しいブランチを作成します。",
restoreWithoutBranchDescription: "{{workspaceName}} を復元してエージェントに戻ります。",
unarchiveDescription:
"{{workspaceName}} はアーカイブされています。再度開くにはアーカイブを解除してください。",
restoreAction: "復元",
@@ -738,6 +738,8 @@ export const ja: TranslationResources = {
resumeCommandUnavailable: "再開コマンドが利用できません",
reloadingAgent: "エージェントを再読み込み中...",
reloadedAgent: "エージェントを再読み込みしました",
reloadedAgentHistoryDiverged:
"エージェントを再読み込みしましたが、プロバイダーの履歴がこのチャットと一致しないため同期しませんでした",
failedToReloadAgent: "エージェントの再読み込みに失敗しました",
failedToCloseAgent: "エージェントを閉じられませんでした",
},
@@ -2038,6 +2040,7 @@ export const ja: TranslationResources = {
hostUnavailable: "ダウンロードホストが利用できません。",
cancelled: "ダウンロードがキャンセルされました。",
failed: "ファイルのダウンロードに失敗しました。",
httpFailed: "ファイルのダウンロードに失敗しました (HTTP {{status}}).",
shareFile: "ファイルを共有",
shareFileNamed: "{{fileName}}を共有",
},
+5 -2
View File
@@ -395,6 +395,7 @@ export const ko: TranslationResources = {
otherPlaceholder: "기타...",
},
backgroundWork: {
heartbeat: "하트비트",
pillOne: "백그라운드 작업 1개",
pillMany: "백그라운드 작업 {{count}}개",
notRunning: "더 이상 실행 중이 아님",
@@ -485,8 +486,7 @@ export const ko: TranslationResources = {
archivedTitle: "워크스페이스가 보관되었습니다",
restoreDescription:
"{{workspaceName}}를 복원하여 에이전트로 돌아갑니다. 워크트리는 {{branch}} 브랜치를 사용합니다.",
restoreWithoutBranchDescription:
"{{workspaceName}}를 복원하여 에이전트로 돌아갑니다. 저장된 기반 브랜치 또는 저장소 기본 브랜치에서 새 브랜치를 만듭니다.",
restoreWithoutBranchDescription: "{{workspaceName}}를 복원하여 에이전트로 돌아갑니다.",
unarchiveDescription: "{{workspaceName}}가 보관되었습니다. 다시 열려면 보관을 취소하세요.",
restoreAction: "복원",
unarchiveAction: "보관 취소",
@@ -733,6 +733,8 @@ export const ko: TranslationResources = {
resumeCommandUnavailable: "재개 명령을 사용할 수 없습니다",
reloadingAgent: "에이전트 다시 로드 중...",
reloadedAgent: "에이전트를 다시 로드했습니다",
reloadedAgentHistoryDiverged:
"에이전트를 다시 로드했지만 제공자 기록이 이 채팅과 일치하지 않아 동기화하지 않았습니다",
failedToReloadAgent: "에이전트를 다시 로드하지 못했습니다",
failedToCloseAgent: "에이전트를 닫지 못했습니다",
},
@@ -2028,6 +2030,7 @@ export const ko: TranslationResources = {
hostUnavailable: "다운로드 호스트를 사용할 수 없습니다.",
cancelled: "다운로드가 취소되었습니다.",
failed: "파일을 다운로드하지 못했습니다.",
httpFailed: "파일을 다운로드하지 못했습니다 (HTTP {{status}}).",
shareFile: "파일 공유",
shareFileNamed: "{{fileName}} 공유",
},
+5 -2
View File
@@ -398,6 +398,7 @@ export const ptBR: TranslationResources = {
otherPlaceholder: "Outro...",
},
backgroundWork: {
heartbeat: "Batimento",
pillOne: "1 tarefa em segundo plano",
pillMany: "{{count}} tarefas em segundo plano",
notRunning: "Não está mais em execução",
@@ -488,8 +489,7 @@ export const ptBR: TranslationResources = {
archivedTitle: "Workspace arquivado",
restoreDescription:
"Restaure {{workspaceName}} para voltar aos seus agentes. A worktree usará a branch {{branch}}.",
restoreWithoutBranchDescription:
"Restaure {{workspaceName}} para voltar aos seus agentes. Uma nova branch partirá da base salva ou da branch padrão do repositório.",
restoreWithoutBranchDescription: "Restaure {{workspaceName}} para voltar aos seus agentes.",
unarchiveDescription:
"{{workspaceName}} está arquivado. Desarquive-o para abri-lo novamente.",
restoreAction: "Restaurar",
@@ -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",
},
@@ -2051,6 +2053,7 @@ export const ptBR: TranslationResources = {
hostUnavailable: "Host de download indisponível.",
cancelled: "Download cancelado.",
failed: "Falha ao baixar arquivo.",
httpFailed: "Falha ao baixar arquivo (HTTP {{status}}).",
shareFile: "Compartilhar arquivo",
shareFileNamed: "Compartilhar {{fileName}}",
},
+5 -1
View File
@@ -398,6 +398,7 @@ export const ru: TranslationResources = {
otherPlaceholder: "Другой ответ...",
},
backgroundWork: {
heartbeat: "Периодический сигнал",
pillOne: "1 фоновая задача",
pillMany: "Фоновые задачи: {{count}}",
notRunning: "Больше не выполняется",
@@ -489,7 +490,7 @@ export const ru: TranslationResources = {
restoreDescription:
"Восстановите «{{workspaceName}}», чтобы вернуться к его агентам. Worktree будет использовать ветку {{branch}}.",
restoreWithoutBranchDescription:
"Восстановите «{{workspaceName}}», чтобы вернуться к его агентам. Новая ветка будет создана от сохранённой базовой или ветки репозитория по умолчанию.",
"Восстановите «{{workspaceName}}», чтобы вернуться к его агентам.",
unarchiveDescription:
"Рабочее пространство «{{workspaceName}}» находится в архиве. Разархивируйте его, чтобы снова открыть.",
restoreAction: "Восстановить",
@@ -738,6 +739,8 @@ export const ru: TranslationResources = {
resumeCommandUnavailable: "Команда возобновления недоступна",
reloadingAgent: "Перезагрузка агента...",
reloadedAgent: "Агент перезагружен",
reloadedAgentHistoryDiverged:
"Агент перезагружен, но история провайдера не совпадает с этим чатом, поэтому она не синхронизирована",
failedToReloadAgent: "Не удалось перезагрузить агента",
failedToCloseAgent: "Не удалось закрыть агента",
},
@@ -2051,6 +2054,7 @@ export const ru: TranslationResources = {
hostUnavailable: "Хост загрузки недоступен.",
cancelled: "Загрузка отменена.",
failed: "Не удалось загрузить файл.",
httpFailed: "Не удалось загрузить файл (HTTP {{status}}).",
shareFile: "Поделиться файлом",
shareFileNamed: "Поделиться {{fileName}}",
},
+5 -2
View File
@@ -394,6 +394,7 @@ export const zhCN: TranslationResources = {
otherPlaceholder: "其他...",
},
backgroundWork: {
heartbeat: "心跳",
pillOne: "1 个后台任务",
pillMany: "{{count}} 个后台任务",
notRunning: "已不再运行",
@@ -484,8 +485,7 @@ export const zhCN: TranslationResources = {
archivedTitle: "Workspace 已归档",
restoreDescription:
"恢复 {{workspaceName}} 以返回其中的代理。worktree 将使用分支 {{branch}}。",
restoreWithoutBranchDescription:
"恢复 {{workspaceName}} 以返回其中的代理。新分支将从保存的基准分支或仓库默认分支创建。",
restoreWithoutBranchDescription: "恢复 {{workspaceName}} 以返回其中的代理。",
unarchiveDescription: "{{workspaceName}} 已归档。取消归档以重新打开。",
restoreAction: "恢复",
unarchiveAction: "取消归档",
@@ -731,6 +731,8 @@ export const zhCN: TranslationResources = {
resumeCommandUnavailable: "恢复命令不可用",
reloadingAgent: "正在重新加载 Agent...",
reloadedAgent: "已重新加载 Agent",
reloadedAgentHistoryDiverged:
"已重新加载 Agent,但提供方的历史记录与此对话不一致,因此未同步",
failedToReloadAgent: "重新加载 Agent 失败",
failedToCloseAgent: "关闭 Agent 失败",
},
@@ -1994,6 +1996,7 @@ export const zhCN: TranslationResources = {
hostUnavailable: "下载 Host 不可用。",
cancelled: "下载已取消。",
failed: "下载文件失败。",
httpFailed: "下载文件失败 (HTTP {{status}}).",
shareFile: "共享文件",
shareFileNamed: "共享 {{fileName}}",
},
@@ -1,5 +1,5 @@
import { PluginTranslationRuntime } from "@getpaseo/plugin/client/host";
import { usePaseo, useRpc } from "@getpaseo/plugin/client";
import { usePaseo, useRpc, useWorkspace, useWorkspaces } from "@getpaseo/plugin/client";
import { defineRpc } from "@getpaseo/plugin";
import { createPaseoApi, type PaseoApi } from "@getpaseo/client";
import { DaemonClient } from "@getpaseo/client/internal/daemon-client";
@@ -8,7 +8,11 @@ import React from "react";
import { renderToStaticMarkup } from "react-dom/server";
import { expect, it } from "vitest";
import { z } from "zod";
import type { PluginWorkspaceSnapshot } from "@getpaseo/plugin";
import type { PluginClientStateSource } from "@getpaseo/plugin/client/host";
import type { ToastApi } from "@/components/toast-host";
import { PluginInstallationProvider } from "./installation-provider";
import { PluginEnvironmentProvider } from "./popover";
import type { InstalledPlugin } from "./types";
const status = defineRpc({
@@ -89,3 +93,53 @@ it("gives every surface the installation's client and RPCs on its first frame",
plugin.lifetime.abort();
await plugin.paseo.dispose();
});
it("lets every surface read state through the plugin state hooks", async () => {
const plugin = installation([]);
function Surface() {
return <span>{useWorkspaces().length} workspaces</span>;
}
const markup = renderToStaticMarkup(
<PluginInstallationProvider plugin={plugin}>
<Surface />
</PluginInstallationProvider>,
);
expect(markup).toBe("<span>0 workspaces</span>");
plugin.lifetime.abort();
await plugin.paseo.dispose();
});
function pluginEnvironment(plugin: InstalledPlugin, state: PluginClientStateSource) {
return { installation: plugin, state, toast: {} as ToastApi };
}
it("lets a surface read the state source its host passes", async () => {
const plugin = installation([]);
// A sidebar view spans every connected host, so its source is not the installation's host.
const workspace = { id: "ws-on-another-host" } as PluginWorkspaceSnapshot;
const state: PluginClientStateSource = {
subscribe: () => () => undefined,
getWorkspace: () => workspace,
getAgent: () => null,
getProject: () => null,
getTerminal: () => null,
getSnapshot: () => ({ workspaces: [], agents: [], projects: [], terminals: [] }),
};
function Surface() {
return <span>{useWorkspace("ws-on-another-host")?.id}</span>;
}
const environment = pluginEnvironment(plugin, state);
const markup = renderToStaticMarkup(
<PluginEnvironmentProvider environment={environment}>
<Surface />
</PluginEnvironmentProvider>,
);
expect(markup).toBe("<span>ws-on-another-host</span>");
plugin.lifetime.abort();
await plugin.paseo.dispose();
});
@@ -2,29 +2,42 @@ import { getPluginClientApi } from "./client-state/api";
import { QueryClientProvider } from "@tanstack/react-query";
import {
PaseoApiProvider,
PluginClientStateProvider,
PluginComposersProvider,
PluginRpcProvider,
PluginTranslationProvider,
type PluginClientStateSource,
} from "@getpaseo/plugin/client/host";
import React, { type ReactNode } from "react";
import React, { useMemo, type ReactNode } from "react";
import { createPluginClientStateSource } from "./client-state/source";
import { pluginComposersSource } from "./composer-items/source";
import type { InstalledPlugin } from "./types";
/** Every plugin surface renders under its installation: one query cache, one Paseo client, RPCs. */
/**
* Every plugin surface renders under its installation: one query cache, one Paseo client, RPCs,
* and the state the plugin state hooks read. That state is scoped to the installation's host
* unless the surface passes its own, as a sidebar view does to span every connected host.
*/
export function PluginInstallationProvider({
plugin,
state: surfaceState,
children,
}: {
plugin: InstalledPlugin;
state?: PluginClientStateSource;
children: ReactNode;
}) {
const state = useMemo(
() => surfaceState ?? createPluginClientStateSource(plugin.serverId),
[plugin.serverId, surfaceState],
);
return (
<QueryClientProvider client={plugin.queryClient}>
<PaseoApiProvider paseo={getPluginClientApi(plugin).paseo}>
<PluginRpcProvider invoke={plugin.invoke} subscribe={plugin.subscribe}>
<PluginTranslationProvider runtime={plugin.i18n}>
<PluginComposersProvider source={pluginComposersSource(plugin)}>
{children}
<PluginClientStateProvider source={state}>{children}</PluginClientStateProvider>
</PluginComposersProvider>
</PluginTranslationProvider>
</PluginRpcProvider>
+2 -3
View File
@@ -1,4 +1,3 @@
import { PluginClientStateProvider } from "@getpaseo/plugin/client/host";
import type { ReactNode } from "react";
import { View } from "react-native";
import { StyleSheet } from "react-native-unistyles";
@@ -30,8 +29,8 @@ export function PluginEnvironmentProvider({
}: PluginEnvironmentProviderProps) {
return (
<ToastApiProvider api={environment.toast}>
<PluginInstallationProvider plugin={environment.installation}>
<PluginClientStateProvider source={environment.state}>{children}</PluginClientStateProvider>
<PluginInstallationProvider plugin={environment.installation} state={environment.state}>
{children}
</PluginInstallationProvider>
</ToastApiProvider>
);
+1 -6
View File
@@ -1,4 +1,3 @@
import { PluginClientStateProvider } from "@getpaseo/plugin/client/host";
import type { PluginTimelineItemProps } from "@getpaseo/plugin/client";
import type { PluginTheme } from "@getpaseo/plugin";
import React, { type ComponentType, useMemo } from "react";
@@ -8,7 +7,6 @@ import { useIsCompactFormFactor } from "@/constants/layout";
import { useHostRuntimeClient, useHosts } from "@/runtime/host-runtime";
import type { Theme } from "@/styles/theme";
import type { PluginTimelineStreamItem } from "@/types/stream";
import { createPluginClientStateSource } from "../client-state/source";
import { useInstalledPlugin } from "../registry";
import { PluginInstallationProvider } from "../installation-provider";
import { SurfaceErrorBoundary } from "../surface-error-boundary";
@@ -59,7 +57,6 @@ function PluginTimelineItemBody({
const hostLabel = hosts.find((host) => host.serverId === serverId)?.label ?? serverId;
const host = useMemo(() => ({ id: serverId, label: hostLabel }), [hostLabel, serverId]);
const layout = useMemo(() => ({ compact, platform: resolvePluginPlatform() }), [compact]);
const stateSource = useMemo(() => createPluginClientStateSource(serverId), [serverId]);
if (!plugin || !renderer || !parsed || !client) {
return <TimelineItemUnavailable />;
@@ -82,9 +79,7 @@ function PluginTimelineItemBody({
return (
<SurfaceErrorBoundary installation={plugin} resetKey={item.data} Surface={Component}>
<PluginInstallationProvider plugin={plugin}>
<PluginClientStateProvider source={stateSource}>
<Component {...props} />
</PluginClientStateProvider>
<Component {...props} />
</PluginInstallationProvider>
</SurfaceErrorBoundary>
);
@@ -5,7 +5,6 @@ import type {
PluginTab,
} from "@getpaseo/plugin/client";
import type { PluginTheme } from "@getpaseo/plugin";
import { PluginClientStateProvider } from "@getpaseo/plugin/client/host";
import { CircleAlert } from "lucide-react-native";
import { useMemo, useState } from "react";
import { Text, View } from "react-native";
@@ -20,7 +19,6 @@ import { useWorkspaceExists } from "@/stores/session-store-hooks";
import type { Theme } from "@/styles/theme";
import { normalizeWorkspaceOpaqueId } from "@/utils/workspace-identity";
import { usePluginHostNavigation } from "../host-navigation";
import { createPluginClientStateSource } from "../client-state/source";
import { toPluginTheme } from "../theme";
import { pluginIconComponent } from "../icons";
import { useInstalledPlugin } from "../registry";
@@ -67,7 +65,6 @@ function PluginPanelBody({ theme }: { theme: PluginTheme }) {
const hostLabel = hosts.find((host) => host.serverId === serverId)?.label ?? serverId;
const host = useMemo(() => ({ id: serverId, label: hostLabel }), [hostLabel, serverId]);
const layout = useMemo(() => ({ compact, platform: resolvePluginPlatform() }), [compact]);
const stateSource = useMemo(() => createPluginClientStateSource(serverId), [serverId]);
const navigation = usePluginHostNavigation(serverId);
if (!plugin || !contribution || !workspaceExists) {
@@ -123,9 +120,7 @@ function PluginPanelBody({ theme }: { theme: PluginTheme }) {
Surface={Surface}
key={`${serverId}/${target.pluginId}/${target.panelId}/${target.context}`}
>
<PluginInstallationProvider plugin={plugin}>
<PluginClientStateProvider source={stateSource}>{panel}</PluginClientStateProvider>
</PluginInstallationProvider>
<PluginInstallationProvider plugin={plugin}>{panel}</PluginInstallationProvider>
</SurfaceErrorBoundary>
);
}
@@ -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: [],
+48 -1
View File
@@ -2739,6 +2739,52 @@ describe("HostRuntimeStore", () => {
session.clearSession(host.serverId);
});
it("loads the directory for a consumer that sees a restored host before the registry finishes loading", async () => {
const host = makeHost({
connections: [{ id: "direct:lan:6767", type: "directTcp", endpoint: "lan:6767" }],
});
const fakeClient = new FakeDaemonClient();
fakeClient.setConnectionState({ status: "connected" });
const store = new HostRuntimeStore({
storage: createMemoryHostRuntimeStorage({
[REGISTRY_KEY]: JSON.stringify([host]),
"@paseo:e2e": "1",
}),
deps: {
createClient: () => fakeClient as unknown as DaemonClient,
connectToDaemon: async ({ host: hostProfile }) => ({
client: fakeClient as unknown as DaemonClient,
serverId: hostProfile.serverId,
hostname: hostProfile.label ?? null,
}),
getClientId: async () => "cid_test_runtime",
},
});
// A component renders on every tick while the registry loads, and acquires directory
// demand for each host it reads, as the sidebar does on its first render.
const registry = { loading: true };
const boot = store.boot().finally(() => {
registry.loading = false;
});
let releaseDemand: (() => void) | null = null;
while (registry.loading && !releaseDemand) {
if (store.getHosts().some((candidate) => candidate.serverId === host.serverId)) {
releaseDemand = store.acquireDirectoryDemand(host.serverId);
}
await Promise.resolve();
}
await boot;
expect(releaseDemand).not.toBeNull();
await waitForHostOnline(store, host.serverId);
await vi.waitFor(() => expect(fakeClient.fetchAgentsCalls).toHaveLength(1));
releaseDemand?.();
store.syncHosts([]);
useSessionStore.getState().clearSession(host.serverId);
});
it("keeps readable hosts when the registry holds entries this build can't read", async () => {
const { store, storage } = await bootWithRegistry(JSON.stringify(storedWithUnreadableEntries));
@@ -2863,7 +2909,8 @@ describe("HostRuntimeStore", () => {
await registryLoaded;
expect(store.isHostRegistryLoaded()).toBe(true);
expect(hostListNotifications).toBe(2);
// Publishing the restored hosts, the registry turning ready, and the registry loading.
expect(hostListNotifications).toBe(3);
} finally {
if (previousOverride === undefined) {
delete process.env.EXPO_PUBLIC_LOCAL_DAEMON;
+13 -7
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;
@@ -1816,11 +1817,9 @@ export class HostRuntimeStore {
shouldPersistHosts = true;
}
}
this.hosts = profiles;
this.replicaCache.setHosts(profiles.map((profile) => profile.serverId));
projectIconCache.setHosts(profiles.map((profile) => profile.serverId));
await projectIconCache.restore();
this.syncHosts(profiles);
this.setHostsAndSync(profiles);
for (const profile of profiles) {
void this.directorySyncByServer
.get(profile.serverId)
@@ -2883,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),
};
@@ -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"),
@@ -90,6 +90,7 @@ interface StartInput {
token?: ReturnType<typeof createTokenRequest>;
reader?: ReturnType<typeof createFileReader>;
saver?: ReturnType<typeof createFileSaver>;
fetchFile?: typeof fetch;
}
async function startDownload(input: StartInput): Promise<Download | undefined> {
@@ -108,6 +109,7 @@ async function startDownload(input: StartInput): Promise<Download | undefined> {
requestFileDownloadToken: token.request,
readFile: reader.read,
saveFile: saver.save,
fetchFile: input.fetchFile ?? (async () => new Response(FILE_BYTES)),
});
const { activeDownloadId, downloads } = useDownloadStore.getState();
return activeDownloadId ? downloads.get(activeDownloadId) : undefined;
@@ -203,6 +205,57 @@ describe("download store transport selection", () => {
expect(saver.savedFiles).toEqual([]);
});
it("fails with the HTTP status when a proxy in front of the host rejects the download", async () => {
const requests: Array<RequestInit | undefined> = [];
const download = await startDownload({
profile: profileWith([localTcpConnection]),
activeConnectionId: localTcpConnection.id,
fetchFile: async (_url, init) => {
requests.push(init);
return new Response("<h1>401 Authorization Required</h1>", {
status: 401,
headers: { "WWW-Authenticate": 'Basic realm="Paseo"' },
});
},
});
expect(download).toMatchObject({
status: "error",
message: i18n.t("downloads.httpFailed", { status: 401 }),
});
expect(requests).toEqual([{ credentials: "include", redirect: "error" }]);
});
it("fails with a readable message when the download request cannot reach the host", async () => {
const download = await startDownload({
profile: profileWith([localTcpConnection]),
activeConnectionId: localTcpConnection.id,
fetchFile: async () => {
throw new TypeError("Failed to fetch");
},
});
expect(download).toMatchObject({ status: "error", message: i18n.t("downloads.failed") });
});
it("fails with a readable message when the connection drops while the file is downloading", async () => {
const saver = createFileSaver();
const download = await startDownload({
profile: profileWith([localTcpConnection]),
activeConnectionId: localTcpConnection.id,
fetchFile: async () =>
new Response(
new ReadableStream({
start: (controller) => controller.error(new TypeError("network error")),
}),
),
saver,
});
expect(download).toMatchObject({ status: "error", message: i18n.t("downloads.failed") });
expect(saver.savedFiles).toEqual([]);
});
it("fails the download and saves nothing when the session read fails", async () => {
const reader = createFileReader(async () => {
throw new Error("Connection lost");
+39 -34
View File
@@ -4,7 +4,6 @@ import * as LegacyFileSystem from "expo-file-system/legacy";
import * as Sharing from "expo-sharing";
import type { HostProfile } from "@/types/host-connection";
import { buildDaemonWebSocketUrl } from "@/utils/daemon-endpoints";
import { openExternalUrl } from "@/utils/open-external-url";
import { isWeb } from "@/constants/platform";
import { i18n } from "@/i18n/i18next";
@@ -59,6 +58,7 @@ interface DownloadState {
/** Reads the whole file over the session socket; used when no direct HTTP endpoint is active. */
readFile: (path: string, maxBytes: number) => Promise<{ bytes: Uint8Array; size: number }>;
saveFile?: typeof saveDownloadedBytes;
fetchFile?: typeof fetch;
}) => Promise<void>;
updateProgress: (id: string, progress: DownloadProgress) => void;
@@ -86,6 +86,7 @@ export const useDownloadStore = create<DownloadState>()((set, get) => ({
requestFileDownloadToken,
readFile,
saveFile = saveDownloadedBytes,
fetchFile = fetch,
}) => {
const id = generateDownloadId();
const download: Download = {
@@ -144,14 +145,11 @@ export const useDownloadStore = create<DownloadState>()((set, get) => ({
throw new Error(i18n.t("downloads.hostUnavailable"));
}
const downloadUrl = buildDownloadUrl(
downloadTarget.baseUrl,
tokenResponse.token,
isWeb ? downloadTarget.authCredentials : null,
);
const downloadUrl = buildDownloadUrl(downloadTarget.baseUrl, tokenResponse.token);
if (isWeb) {
triggerBrowserDownload(downloadUrl, resolvedFileName);
const file = await fetchDownload(fetchFile, downloadUrl);
saveBrowserFile(file, resolvedFileName);
get().completeDownload(id);
return;
}
@@ -198,11 +196,6 @@ export const useDownloadStore = create<DownloadState>()((set, get) => ({
await shareSavedFile(result.uri, tokenResponse.mimeType, resolvedFileName);
} catch (error) {
const message = error instanceof Error ? error.message : i18n.t("downloads.failed");
if (isWeb) {
console.warn("[DownloadStore] Download failed:", message);
get().failDownload(id, message);
return;
}
get().failDownload(id, message);
}
},
@@ -283,7 +276,6 @@ function findMostRecentDownloadId(downloads: Map<string, Download>): string | nu
interface DownloadTarget {
baseUrl: string | null;
authHeader: string | null;
authCredentials: { username: string; password: string } | null;
}
/**
@@ -306,7 +298,7 @@ function resolveDaemonDownloadTarget(
buildDaemonWebSocketUrl(connection.endpoint, { useTls: connection.useTls ?? false }),
);
} catch {
return { baseUrl: null, authHeader: null, authCredentials: null };
return { baseUrl: null, authHeader: null };
}
if (parsed.protocol === "ws:") {
@@ -332,23 +324,41 @@ function resolveDaemonDownloadTarget(
? `Basic ${btoa(`${authCredentials.username}:${authCredentials.password}`)}`
: null;
return { baseUrl, authHeader, authCredentials };
return { baseUrl, authHeader };
}
function buildDownloadUrl(
baseUrl: string,
token: string,
authCredentials: { username: string; password: string } | null,
): string {
function buildDownloadUrl(baseUrl: string, token: string): string {
const url = new URL("/api/files/download", baseUrl);
url.searchParams.set("token", token);
if (authCredentials) {
url.username = authCredentials.username;
url.password = authCredentials.password;
}
return url.toString();
}
/**
* Fetches the file instead of navigating to it. The app runs on another origin than the host
* (paseo://app on desktop), so a link to the download URL navigates the whole window, and any
* response that is not the file (a proxy's 401 page, a 404) replaces the app.
*/
async function fetchDownload(fetchFile: typeof fetch, url: string): Promise<Blob> {
let response: Response;
try {
// Send the same cookies the host's WebSocket handshake sends, so a proxy in front of the
// host lets the download through. Refuse redirects: a proxy that redirects to a login page
// would otherwise be saved as the file.
response = await fetchFile(url, { credentials: "include", redirect: "error" });
} catch {
throw new Error(i18n.t("downloads.failed"));
}
if (!response.ok) {
throw new Error(i18n.t("downloads.httpFailed", { status: response.status }));
}
try {
// The body streams after the headers, so the connection can still drop here.
return await response.blob();
} catch {
throw new Error(i18n.t("downloads.failed"));
}
}
/**
* Saves bytes read over the session. Web and Electron hand them to the browser's download
* manager and return `null`; native writes the file and returns its URI for the share sheet.
@@ -361,12 +371,7 @@ async function saveDownloadedBytes({
if (isWeb) {
const buffer = new ArrayBuffer(bytes.byteLength);
new Uint8Array(buffer).set(bytes);
const url = URL.createObjectURL(
new Blob([buffer], { type: mimeType ?? "application/octet-stream" }),
);
triggerBrowserDownload(url, fileName);
// The browser may still be reading the blob while its save prompt is open.
setTimeout(() => URL.revokeObjectURL(url), 60_000);
saveBrowserFile(new Blob([buffer], { type: mimeType ?? "application/octet-stream" }), fileName);
return null;
}
// Resolve and write in one tick so two downloads of the same name cannot pick the same path.
@@ -390,14 +395,12 @@ async function shareSavedFile(
}
}
function triggerBrowserDownload(url: string, fileName: string) {
function saveBrowserFile(file: Blob, fileName: string) {
if (typeof document === "undefined") {
if (typeof window !== "undefined") {
void openExternalUrl(url);
}
return;
}
const url = URL.createObjectURL(file);
const link = document.createElement("a");
link.href = url;
link.download = fileName;
@@ -405,6 +408,8 @@ function triggerBrowserDownload(url: string, fileName: string) {
document.body.appendChild(link);
link.click();
link.remove();
// The browser may still be reading the blob while its save prompt is open.
setTimeout(() => URL.revokeObjectURL(url), 60_000);
}
function resolveDownloadTargetFile(fileName: string): FSFile {
+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];
+545 -1
View File
@@ -6,6 +6,7 @@ import {
type SqliteValue,
} from "@/runtime/replica-cache/row-store-sqlite";
import { afterEach, describe, expect, it } from "vitest";
import type { AgentTimelineItem } from "@getpaseo/protocol/agent-types";
import type { AgentStreamEventPayload } from "@getpaseo/protocol/messages";
import type { CachedTimeline } from "@/runtime/replica-cache";
import {
@@ -17,6 +18,8 @@ import {
} from "@/stores/session-store";
import { useCreateFlowStore, type PendingCreateAttempt } from "@/stores/create-flow-store";
import type { StreamItem } from "@/types/stream";
import type { AgentStreamReducerEvent } from "./session-stream-reducers";
import type { ProjectedTimelineForwardFetchPlan } from "./timeline-sync-plan";
import { reduceTurnLiveness, type TurnLivenessTransition } from "./turn-liveness";
import {
createTimelineReplica,
@@ -36,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 },
};
}
@@ -576,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);
@@ -1379,6 +1611,318 @@ describe("create handoff lifetime", () => {
});
});
describe("a chat that was empty when it went offline", () => {
const EPOCH = "epoch-1";
const PROMPT = "stream through a reconnect";
const THOUGHT = "Thinking before the reply.";
const TURN_ID = "turn-1";
const TIMESTAMP = "2026-10-31T10:00:00.000Z";
/** The daemon's timeline: one row per flushed chunk, read back as projected pages. */
class DaemonTimeline {
private readonly rows: Array<{ seq: number; item: AgentTimelineItem }> = [];
record(timelineItem: AgentTimelineItem): AgentStreamReducerEvent {
const seq = this.rows.length + 1;
this.rows.push({ seq, item: timelineItem });
return {
event: { type: "timeline", provider: "mock", turnId: TURN_ID, item: timelineItem },
seq,
epoch: EPOCH,
timestamp: new Date(TIMESTAMP),
};
}
page(request: ProjectedTimelineForwardFetchPlan): TimelineResponsePayload {
const maxSeq = this.rows.at(-1)?.seq ?? 0;
const after = request.direction === "after" ? request.cursor.seq : 0;
const entries = this.projected().filter((entry) => entry.seqEnd > after);
const first = entries[0];
const startSeq = request.direction === "after" ? after + 1 : first?.seqStart;
return {
requestId: `${request.direction}-${after}`,
agentId: AGENT_ID,
agent: null,
direction: request.direction,
projection: "projected",
reset: false,
epoch: EPOCH,
window: { minSeq: this.rows[0]?.seq ?? 0, maxSeq, nextSeq: maxSeq + 1 },
startCursor: first && startSeq !== undefined ? { epoch: EPOCH, seq: startSeq } : null,
endCursor: first ? { epoch: EPOCH, seq: maxSeq } : null,
entries,
error: null,
hasNewer: false,
hasOlder: after > 0,
staleCursor: false,
gap: false,
};
}
/** Contiguous reply and thought chunks read back as one row, like the daemon's projection. */
private projected(): TimelineResponsePayload["entries"] {
const entries: TimelineResponsePayload["entries"] = [];
for (const { seq, item: row } of this.rows) {
const previous = entries.at(-1);
const continues =
previous !== undefined &&
((row.type === "assistant_message" &&
previous.item.type === "assistant_message" &&
previous.item.messageId === row.messageId) ||
(row.type === "reasoning" && previous.item.type === "reasoning"));
if (
continues &&
(previous.item.type === "assistant_message" || previous.item.type === "reasoning") &&
(row.type === "assistant_message" || row.type === "reasoning")
) {
previous.item = { ...previous.item, text: `${previous.item.text}${row.text}` };
previous.seqEnd = seq;
previous.sourceSeqRanges = [{ startSeq: previous.seqStart, endSeq: seq }];
previous.collapsed = [
row.type === "assistant_message" ? "assistant_merge" : "reasoning_merge",
];
continue;
}
entries.push({
provider: "mock",
item: row,
timestamp: TIMESTAMP,
seqStart: seq,
seqEnd: seq,
sourceSeqRanges: [{ startSeq: seq, endSeq: seq }],
collapsed: [],
turnId: TURN_ID,
});
}
return entries;
}
}
interface PendingFetch {
request: ProjectedTimelineForwardFetchPlan;
/** Delivers a page the way the host runtime does: queued live chunks first, then the page. */
deliver(page: TimelineResponsePayload): void;
}
function openChat(storage: TimelineReplicaStorage) {
const fetches: PendingFetch[] = [];
const errors: unknown[] = [];
const fetch = (request: ProjectedTimelineForwardFetchPlan) =>
new Promise<{ hasNewer: boolean; endCursor: { epoch: string; seq: number } | null }>(
(resolve) => {
fetches.push({
request,
deliver: (page) => {
owner.flushStreamAgent(AGENT_ID);
owner.applyTimelineResponse(page);
resolve({ hasNewer: page.hasNewer, endCursor: page.endCursor });
},
});
},
);
const replica = createTimelineReplica({
serverId: SERVER_ID,
storage,
prepareAgent: async () => undefined,
});
const owner = createViewedTimelineOwner({
serverId: SERVER_ID,
replica,
replaceDemandedAgentIds: () => undefined,
drainQueuedAgentMessage: () => undefined,
applyTurnLiveness: () => undefined,
ports: {
canCheckFreshness: () => true,
observe: () => ({ ready: Promise.resolve(), release: async () => undefined }),
readCursor: (agentId) => {
const timeline = selectAgentTimelineState(
useSessionStore.getState().sessions[SERVER_ID],
agentId,
);
return timeline.status === "synced" && timeline.range
? { epoch: timeline.range.epoch, endSeq: timeline.range.endSeq }
: undefined;
},
fetchPage: (_agentId, request) => fetch(request),
fetchLatestTail: () =>
fetch({ direction: "tail", limit: 40, projection: "projected", wholeTurns: true }),
reportError: (error) => errors.push(error),
},
});
owner.setConnected(true);
owner.replaceVisibleAgentIds("test", [AGENT_ID]);
return {
owner,
async nextFetch(): Promise<PendingFetch> {
await expect.poll(() => fetches.length).toBeGreaterThan(0);
return fetches.shift()!;
},
live(event: AgentStreamReducerEvent): void {
owner.applyStreamEvent(AGENT_ID, event);
owner.flushStreamAgent(AGENT_ID);
},
/** Answers every catch-up the chat still asks for until it reports itself current. */
async settle(daemon: DaemonTimeline): Promise<void> {
for (let turn = 0; turn < 20; turn += 1) {
await new Promise((resolve) => setTimeout(resolve, 0));
expect(errors).toEqual([]);
const next = fetches.shift();
if (next) next.deliver(daemon.page(next.request));
else if (owner.getAgentTimelineStatus(AGENT_ID) === "ready") return;
}
throw new Error("The chat never caught up");
},
};
}
function rows(): Array<{ kind: StreamItem["kind"]; text: string }> {
const session = useSessionStore.getState().sessions[SERVER_ID];
return [
...(session?.agentStreamTail.get(AGENT_ID) ?? []),
...(session?.agentStreamHead.get(AGENT_ID) ?? []),
].map((entry) => ({
kind: entry.kind,
text: "text" in entry && typeof entry.text === "string" ? entry.text : "",
}));
}
const reply = (words: number) =>
Array.from({ length: words }, (_unused, index) => `word${index}`).join(" ");
const chunk = (index: number) => `${index === 0 ? "" : " "}word${index}`;
const replyChunk = (index: number): AgentTimelineItem => ({
type: "assistant_message",
text: chunk(index),
messageId: "reply-1",
});
/**
* Opens the chat while its timeline is empty, then drops the connection while the prompt,
* an optional thought and the first three reply chunks are recorded.
*/
async function goOfflineWhileTheReplyStarts(input: {
reasoning: boolean;
storage: TimelineReplicaStorage;
}) {
useSessionStore.getState().initializeSession(SERVER_ID, null);
const daemon = new DaemonTimeline();
const chat = openChat(input.storage);
const opened = await chat.nextFetch();
opened.deliver(daemon.page(opened.request));
expect(
selectAgentTimelineState(useSessionStore.getState().sessions[SERVER_ID], AGENT_ID),
).toEqual({ status: "synced", items: [], range: null, older: "none", newer: "none" });
chat.owner.setConnected(false);
daemon.record({ type: "user_message", text: PROMPT, messageId: "prompt-1" });
if (input.reasoning) daemon.record({ type: "reasoning", text: THOUGHT });
for (const index of [0, 1, 2]) daemon.record(replyChunk(index));
chat.owner.setConnected(true);
const catchUp = await chat.nextFetch();
return { daemon, chat, catchUp };
}
function expectedRows(reasoning: boolean, words: number) {
return [
{ kind: "user_message", text: PROMPT },
...(reasoning ? [{ kind: "thought", text: THOUGHT }] : []),
{ kind: "assistant_message", text: reply(words) },
];
}
/** A saved range that starts after the prompt claims history the chat never received. */
function expectCoverageFromTheFirstRow(commits: CachedTimeline[]): void {
expect(commits.map((commit) => commit.range?.startSeq ?? 1)).toEqual(commits.map(() => 1));
}
it.each([true, false])(
"keeps the prompt and the whole reply when live chunks arrive before a page that holds them (reasoning=%s)",
async (reasoning) => {
const commits: CachedTimeline[] = [];
const { daemon, chat, catchUp } = await goOfflineWhileTheReplyStarts({
reasoning,
storage: {
readTimeline: async () => undefined,
commitTimeline: (_serverId, _agentId, timeline) => commits.push(timeline),
},
});
try {
chat.live(daemon.record(replyChunk(3)));
chat.live(daemon.record(replyChunk(4)));
catchUp.deliver(daemon.page(catchUp.request));
chat.live(daemon.record(replyChunk(5)));
await chat.settle(daemon);
expect(rows()).toEqual(expectedRows(reasoning, 6));
expectCoverageFromTheFirstRow(commits);
} finally {
chat.owner.dispose();
}
// The saved chat paints the same rows after a reload.
const saved = commits.at(-1);
useSessionStore.getState().clearSession(SERVER_ID);
useSessionStore.getState().initializeSession(SERVER_ID, null);
const reopened = createOwner({
readTimeline: async () => saved,
commitTimeline: () => undefined,
});
try {
reopened.replaceVisibleAgentIds("test", [AGENT_ID]);
await expect.poll(rows).toEqual(expectedRows(reasoning, 6));
} finally {
reopened.dispose();
}
},
);
it("keeps the prompt when the page already holds a chunk the chat has not seen live", async () => {
const commits: CachedTimeline[] = [];
const { daemon, chat, catchUp } = await goOfflineWhileTheReplyStarts({
reasoning: true,
storage: {
readTimeline: async () => undefined,
commitTimeline: (_serverId, _agentId, timeline) => commits.push(timeline),
},
});
try {
chat.live(daemon.record(replyChunk(3)));
const notYetLive = daemon.record(replyChunk(4));
catchUp.deliver(daemon.page(catchUp.request));
chat.live(notYetLive);
chat.live(daemon.record(replyChunk(5)));
await chat.settle(daemon);
expect(rows()).toEqual(expectedRows(true, 6));
expectCoverageFromTheFirstRow(commits);
} finally {
chat.owner.dispose();
}
});
it("finishes the reply when its last chunks arrive while an older page is in flight", async () => {
const commits: CachedTimeline[] = [];
const { daemon, chat, catchUp } = await goOfflineWhileTheReplyStarts({
reasoning: true,
storage: {
readTimeline: async () => undefined,
commitTimeline: (_serverId, _agentId, timeline) => commits.push(timeline),
},
});
try {
const olderPage = daemon.page(catchUp.request);
chat.live(daemon.record(replyChunk(3)));
chat.live(daemon.record(replyChunk(4)));
catchUp.deliver(olderPage);
await chat.settle(daemon);
expect(rows()).toEqual(expectedRows(true, 5));
expectCoverageFromTheFirstRow(commits);
} finally {
chat.owner.dispose();
}
});
});
function createSqliteCache() {
const database = new DatabaseSync(":memory:");
let beforeRead = async () => {};
@@ -53,6 +53,7 @@ it.each([false, true])(
(hasAuthoritativeBaseline) => {
let head: StreamItem[] = [];
let tail: StreamItem[] = [];
let cursor: TimelineCursor | undefined;
for (const [index, turnId] of ["turn-1", "turn-2"].entries()) {
const result = processAgentStreamEvent({
event: {
@@ -65,12 +66,13 @@ it.each([false, true])(
epoch: "epoch-1",
currentTail: tail,
currentHead: head,
currentCursor: undefined,
currentCursor: cursor,
timestamp: new Date(1000),
hasAuthoritativeBaseline,
});
head = result.head;
tail = result.tail;
cursor = result.cursor ?? cursor;
}
expect([...tail, ...head]).toMatchObject([
{ kind: "thought", text: "turn-1", turnId: "turn-1" },
@@ -396,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({
@@ -404,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];
@@ -454,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 },
@@ -482,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({
@@ -571,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 },
}),
]);
});
@@ -743,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" },
@@ -773,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" }),
}),
@@ -794,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" },
@@ -829,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 }],
}),
]);
@@ -845,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" },
@@ -877,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,
@@ -916,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,
@@ -944,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", () => {
@@ -961,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" },
@@ -1017,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,
@@ -1036,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", () => {
@@ -1058,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({
@@ -1121,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 },
});
});
@@ -2806,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"),
],
@@ -2848,7 +2850,7 @@ describe("processTimelineResponse", () => {
],
currentTail: [],
currentHead: [],
currentCursor: undefined,
currentCursor: { epoch: "epoch-1", startSeq: 60, endSeq: 79 },
});
expect(getAssistantTexts([...live.tail, ...live.head])).toEqual([
"First paragraph.\n\nSecond paragraph.",
@@ -2884,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 },
},
];
@@ -2933,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] : []),
],
@@ -2974,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],
@@ -2990,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" },
@@ -3036,7 +3042,7 @@ describe("processTimelineResponse", () => {
{
callId: "call-1",
status: "completed",
timelineCursor: { epoch: "epoch-1", seq: 500 },
timelineCursor: { epoch: "epoch-1", seq: 500, anchorSeq: 1 },
},
]);
});
@@ -3048,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({
@@ -3098,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 },
},
]);
});
@@ -3110,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 = {
@@ -3217,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 = {
@@ -3244,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({
@@ -3677,13 +3683,14 @@ describe("processAgentStreamEvent", () => {
event: makeAssistantTimelineEvent("[System Error] failed"),
epoch: "timeline-1",
seq: 42,
currentCursor: { epoch: "timeline-1", startSeq: 1, endSeq: 41 },
});
expect(result.head).toEqual([
expect.objectContaining({
kind: "assistant_message",
text: "[System Error] failed",
timelineCursor: { epoch: "timeline-1", seq: 42 },
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 42 },
}),
]);
});
@@ -3897,6 +3904,24 @@ describe("processAgentStreamEvent", () => {
});
});
it("catches up from the first row when a chat that was empty receives a later row", () => {
const result = processAgentStreamEvent({
...baseStreamInput,
event: makeTimelineEvent("word3"),
seq: 6,
epoch: "epoch-1",
currentCursor: undefined,
});
expect(result).toMatchObject({
head: [],
changedHead: false,
cursor: null,
cursorChanged: false,
sideEffects: [{ type: "catch_up", cursor: { epoch: "epoch-1", endSeq: 0 } }],
});
});
it("renders a live row over painted items without creating an authoritative cursor", () => {
const result = processAgentStreamEvent({
...baseStreamInput,
@@ -3912,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();
@@ -3947,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 },
}),
]);
});
@@ -4087,7 +4112,7 @@ describe("processAgentStreamEvents", () => {
],
currentTail: [],
currentHead: [],
currentCursor: undefined,
currentCursor: { epoch: "epoch-1", startSeq: 1, endSeq: 237 },
});
expect(result.changedTail).toBe(false);
@@ -4261,6 +4286,7 @@ describe("processAgentStreamEvents", () => {
currentTail: [],
currentHead: [],
currentCursor: undefined,
hasAuthoritativeBaseline: false,
timestamp: new Date("2026-05-02T10:00:00.186Z"),
});
@@ -4462,7 +4488,7 @@ describe("createAgentStreamReducerQueue", () => {
const scheduler = createManualScheduler();
let currentTail: StreamItem[] = [];
let currentHead: StreamItem[] = [];
let currentCursor: TimelineCursor | undefined;
let currentCursor: TimelineCursor | undefined = { epoch: "epoch-1", startSeq: 1, endSeq: 1 };
const queue = createAgentStreamReducerQueue({
getSnapshot: () => ({
@@ -4505,7 +4531,7 @@ describe("createAgentStreamReducerQueue", () => {
expect(getAssistantTexts(currentHead)).toEqual(["This is a paragraph continues."]);
expect(currentCursor).toEqual({
epoch: "epoch-1",
startSeq: 2,
startSeq: 1,
endSeq: 4,
});
});
@@ -4536,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[];
@@ -289,7 +354,10 @@ function classifySessionTimelineSeq({
seq: number;
}): SessionTimelineSeqDecision {
if (!cursor) {
return "init";
// A synced chat without coverage was empty when it last caught up. Only an epoch's
// first row can start coverage; a later row means rows before it were missed, for
// example while offline, and a cursor started there would hide them from catch-up.
return seq === 1 ? "init" : "gap";
}
if (cursor.epoch !== epoch) {
return "drop_epoch";
@@ -391,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 } =
@@ -755,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") {
@@ -774,7 +842,7 @@ function replaceLiveAssistantWithProjectedText(params: {
...current,
text: event.item.text,
timestamp,
timelineCursor,
...advanceTimelinePosition(current.timelineCursor, timelineCursor),
};
return next;
}
@@ -824,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];
@@ -941,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,
@@ -1141,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",
@@ -1176,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,
@@ -1234,8 +1307,6 @@ export function processTimelineResponse(
): ProcessTimelineResponseOutput {
const {
payload,
currentTail,
currentHead,
currentCursor,
isInitializing,
hasActiveInitDeferred,
@@ -1249,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",
@@ -1262,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
// ------------------------------------------------------------------
@@ -1286,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 },
}));
// ------------------------------------------------------------------
@@ -1426,7 +1504,7 @@ export function processTimelineResponse(
// ---------------------------------------------------------------------------
export interface ProcessAgentStreamEventInput {
event: AgentStreamEventPayload;
event: AgentStreamEventPayload | TimelineRewindEvent;
seq: number | undefined;
epoch: string | undefined;
currentTail: StreamItem[];
@@ -1449,7 +1527,7 @@ export interface ProcessAgentStreamEventOutput {
}
export interface AgentStreamReducerEvent {
event: AgentStreamEventPayload;
event: AgentStreamEventPayload | TimelineRewindEvent;
seq: number | undefined;
epoch: string | undefined;
timestamp: Date;
@@ -1543,14 +1621,14 @@ function processTimelineSequencingGate(input: {
return {
...base,
shouldApplyStreamEvent: false,
sideEffects: currentCursor
? [
{
type: "catch_up",
cursor: { epoch: currentCursor.epoch, endSeq: currentCursor.endSeq },
},
]
: [],
sideEffects: [
{
type: "catch_up",
cursor: currentCursor
? { epoch: currentCursor.epoch, endSeq: currentCursor.endSeq }
: { epoch, endSeq: 0 },
},
],
};
}
if (decision === "drop_epoch" && seq === 1) {
@@ -1567,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,
@@ -1590,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
@@ -1904,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 ||

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