Compare commits

...
Author SHA1 Message Date
Mohamed Boudra 15071640ce test(server): reap crash-test terminal processes before teardown 2026-11-17 06:59:38 +01:00
Mohamed Boudra efd7c5cc53 fix(server): preserve PR checks while GitHub polling is paused 2026-11-17 06:27:56 +01:00
Mohamed Boudra 7931027162 fix(server): isolate PR membership state from forge metadata 2026-11-17 06:19:56 +01:00
Mohamed Boudra 220d4cb546 fix(server): share ranked PR resolution with batched polling 2026-11-17 05:56:16 +01:00
Mohamed Boudra 9e4806e615 fix(server): defer terminal PR reads and follow forge pagination 2026-11-17 05:39:54 +01:00
Mohamed Boudra 45e2869ad8 fix(server): preserve PR state when membership reads fail 2026-11-17 05:23:39 +01:00
Mohamed Boudra 35d0edb67b fix(server): isolate and cache terminal PR commit reads
Keep membership out of metadata polls and request only terminal commit IDs in newest-first batches. Failed candidates remain retryable and do not prevent complete workspaces or other matching candidates from updating.
2026-11-17 05:11:19 +01:00
Mohamed Boudra 9dc32bb549 fix(server): narrow absent PR state before projecting workspace payload 2026-11-17 04:47:09 +01:00
Mohamed Boudra fedb40d112 fix(server): require membership in the pull request own commits
Exclude inherited base commits using forge commit lists. Carry membership evidence in the server snapshot so auto-archive uses the same rule without Git subprocesses or network fetches. Preserve GitHub batching and cache terminal commit reads.
2026-11-17 04:39:03 +01:00
Mohamed Boudra 7e5ea17d6c fix(server): match terminal pull requests by workspace commit ancestry
Branch-name fallback attached historical closed requests to reused workspaces. Share containment between forge lookup and auto-archive so remote branch updates remain eligible without accepting unrelated requests. Fetch missing Git objects without consuming the batched GitHub API budget or moving refs.
2026-11-17 04:12:29 +01:00
ce09360241 fix(server): agents archived while not loaded get the archive time as their last update (#9926)
* fix(server): move updatedAt when archiving an agent that is only in storage

Archiving a loaded agent sets its updatedAt to the archive time
(markRecordArchived). Archiving an agent that is only in storage, which
is also how a parent's archive reaches its children, kept the old
updatedAt. Lists sorted by updated_at, such as History, then left a
just-archived agent where its last turn put it, sometimes days back, and
clients paging such a list by time never reached it.

archiveSnapshotUnlocked now records the archive time as updatedAt too.

Co-authored-by: RoundRedDot <roundreddot@gmail.com>

* fix(server): keep updatedAt from moving back when an archive is restored

Archiving a stored-only agent now sets updatedAt to the archive time.
When the archive time is earlier than the record's updatedAt, as when a
failed send or resume puts an agent's original archive back after
unarchiving it, updatedAt stays where it is. Clients drop agent updates
that are older than the one they hold, so moving it back left them
showing the agent active.

Co-authored-by: luke <luopeihuan@gmail.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server): keep updatedAt from moving back when a loaded agent's archive is restored

The rule that archiving never moves updatedAt backwards now lives in
buildArchivedAgentRecord, which both archive paths use. A failed send
that resumed the agent before a later loading step failed puts its
original archive back through the loaded path, which had the same
backwards move.

The workspace archive stamp test now uses stamps taken after the
agents' activity, as real archive stamps are.

Co-authored-by: luke <luopeihuan@gmail.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(server): require the archive time when building an archived agent

buildArchivedAgentRecord no longer accepts an archive that leaves
updatedAt unset, the gap #9920 came through, and its tests now assert
the rule: a later archive time moves updatedAt, an earlier one keeps it.

Co-authored-by: luke <luopeihuan@gmail.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: luke <luopeihuan@gmail.com>
Co-authored-by: RoundRedDot <roundreddot@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-17 02:55:35 +00:00
paseo-bot[bot]andClaude Opus 5.5 8f3752ecb9 test(app): wait for a label filter row to be laid out before measuring it (#9922)
The workspace-labels journey measured the Urgent filter row right after
opening the label filter page. While the page is still coming in, the
row has no box yet, and the measuring helper threw inside expect.poll,
which ends the poll instead of retrying it. An element with no box now
counts as not settled, and the helper returns the box it settled on
instead of measuring a second time.

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 00:36:12 +00:00
73c22f7917 Keep desktop workspaces reachable when sidebar navigation overflows (#9903)
* fix(app): keep desktop workspaces reachable when sidebar navigation overflows

Apply the mobile cap from #8727 to DesktopSidebar: the navigation rows
scroll inside a viewport capped at half the sidebar, so plugin rows no
longer push the Workspaces list out of a short window. The viewport sits
outside the titlebar drag area and opts out of app regions, since
Electron does not clip app-region rects to scroll viewports.

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

* fix(app): keep the sidebar drag strip on Windows and Linux

Moving the desktop navigation rows into a scroll viewport left the
sidebar's drag overlay in an empty container when the window controls
sit top-right, so Windows and Linux lost every window-drag surface in
the sidebar. The strip above the navigation now carries the drag
overlay there, and the rows start flush below it.

Refs #9872

Co-authored-by: Alex Tong <alex.tong@pentatonic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(app): share the window-content marker from the drag-region module

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

* refactor(app): share one nav scroller between the mobile and desktop sidebars

The desktop sidebar's capped nav viewport was a plain ScrollView on every
platform, so on tablets it did not join the overlay's close swipe the way
the mobile nav block and the workspace list do. Both sidebars now render
SidebarNavScroll, which owns the 50% cap, the native gesture-handler
branch linked to the close gesture, the divider, and the web
window-content marker.

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

* fix(app): drop the empty nav divider and drag strip when every top item is hidden

With every top navigation item turned off, the desktop sidebar now starts
at the Workspaces section again, as on main: no 1px divider and no 8px
drag strip above it.

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

---------

Co-authored-by: Alex Tong <alex.tong@pentatonic.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-16 23:59:03 +00:00
paseo-bot[bot]andClaude Opus 5.5 038a9ca00d fix(opencode): clear a question that a new message replaces (#9891)
With the default send setting, a message sent while an OpenCode agent
waits on a question steers the turn, and Paseo rejects the question in
OpenCode. The OpenCode session dropped the question from its own list
without reporting it resolved, so the agent manager and the app kept
showing it. Answering or dismissing it then failed with "No pending
permission request", and the prompt could not be closed.

The session now reports permission_resolved whenever OpenCode accepts a
reply, rejection, or answer, as the other providers do.

Fixes #9879

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-16 19:03:40 +00:00
paseo-bot[bot]andClaude Opus 5.5 3a7e216b7d test(server): read the latest event when checking a removed file on macOS (#9898)
macOS FSEvents can replay the file's pre-subscription write as a create
after the observer starts. The test read the first event for the path,
so it stayed on that create after the delete arrived in a later batch.

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-16 18:45:26 +00:00
paseo-bot[bot]andClaude Opus 5.5 6ef188416f test(e2e): start the plugin modal settle check once the sheet is in view (#9889)
The compact sheet holds below the viewport for a few frames before it
slides up. On a slow runner two settle reads 100 ms apart can both land
in that hold. Waiting for the title to enter the viewport first means the
settle check only starts once the slide has begun.

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-16 18:04:29 +00:00
791bbd3596 fix(app): keep preview tab identities unique across split panes (#9888)
* fix(app): keep preview tab identities unique across split panes

Reserve existing pane and sheet IDs when allocating a new instance, including tabs opened by reconciliation. Keep menu-hosted sheet identities stable across layout changes.

Repair duplicate IDs in saved layouts without discarding tabs, state, or pane focus. Resolve file navigation by target rather than an ID retained from a previous preview.

* fix(app): open a listed subagent as its own agent tab

A subagent opened in place of the compact subagent list got a random
instance id, so "Open as tab" created a tab that no longer carried the
subagent's agent tab id. The in-place sheet now starts from the
subagent's own tab id, still checked against occupied ids and kept
stable across layout updates.

Co-authored-by: Kosmo CHE <108672813+KosmoCHE@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Kosmo CHE <kosmoche@gmail.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Kosmo CHE <108672813+KosmoCHE@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 18:04:19 +00:00
Angus Buick b95f1bbf31 fix(app): draw the Add host text fields as inputs again (#9864) (#9865)
AdaptiveTextInput wraps its input with withUnistyles, and the pairing link and direct connection modals wrapped AdaptiveTextInput a second time. On web each wrapper is a display: contents element whose style lands on its direct child, so the outer style landed on the inner wrapper and the input lost its border, background and padding.

Drop the outer wrapper, AdaptiveTextInput already themes the placeholder colour. Also give the host password field a placeholder and focus it when pairing asks for a password.
2026-11-16 16:58:48 +00:00
paseo-bot[bot]andClaude Opus 5.5 c2a24ae81e test(e2e): wait for a plugin modal sheet to settle before using the pointer (#9884)
On compact layouts the sheet holds below the viewport and then slides up,
so the Horizontal tab hover could resolve its point mid-slide and the wheel
landed on the rows below the tabs. openExample now waits for the title to
stop moving.

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-16 15:48:36 +00:00
paseo-bot[bot] 6eb94611b3 test(e2e): wait for the isolated daemon itself, not any listener on its port (#9863)
* test(e2e): wait for the isolated daemon itself, not any listener on its port

The helper reserves a port, releases it, and starts the daemon on it. If
another process takes the port in between, the daemon exits with
EADDRINUSE, but the readiness probe already succeeded against the other
listener. The worker fixture then reported the daemon as started and its
seed client retried a dead endpoint until the 60s fixture timeout.

Readiness now requires /api/status on the port to report this daemon's
server id, so the probe keeps waiting, sees the EADDRINUSE exit, and the
existing retry moves to a fresh port.

* test(e2e): authenticate the readiness probe with the daemon's local credential

A password with spaces cannot travel as an HTTP bearer, so the status
probe of a password-protected daemon stayed 401. The daemon writes a
local credential into its home before listening and /api/status accepts
it, as the CLI's local status does.

---------

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-16 15:03:02 +00:00
Okan YILDIRIM a8cadae0ee fix(app): keep saved hosts when one entry can't be read (#9847)
The host registry was parsed with a strict array schema, so one host or
connection this build couldn't read failed the whole array. The loader then
removed @paseo:daemon-registry, and every saved host and password with it.
That happens after a downgrade, or once a newer build saves a connection kind
this build doesn't know.

- Hosts and connections are read one at a time. One this build can't read
  is skipped, and the other hosts load.
- Skipped entries are written back on every save, so the build that wrote
  them still finds them. Removing a host also drops what this build couldn't
  read for it.
- A value that isn't a JSON array is copied to
  @paseo:daemon-registry:unreadable instead of being removed.
- The stored-password migration still moves a connection password to its
  host when that host also has an unreadable connection.
2026-11-16 14:01:03 +00:00
5a78c1cd16 Let idle cleanup release Codex chats opened only to read history (#9859)
A Codex session opened to read history reads the thread and disposes its
app-server right away, but canStopRuntime() vetoed it because it had no
client. Idle cleanup then kept every such chat loaded in the daemon.

Closes #9804

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Spencer Shulem <1703265+Spshulem@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 13:01:00 +00:00
paseo-bot[bot]anddaysun-k 8522d18ed8 Keep Claude signed in when model discovery runs during a token refresh (#9855)
* Let Claude model discovery finish a token refresh instead of killing it

Model discovery stopped waiting after 5 s by aborting the SDK query and
tree-killing the CLI. A CLI that is still refreshing an expired OAuth
token at that moment has already rotated the refresh token, so the kill
leaves only the revoked token on disk and logs the user out.

The 5 s limit now only bounds the wait. A CLI that has not answered gets
its input ended and exits on its own; it is tree-killed only after a
60 s grace period or when the daemon shuts down.

Fixes #9314

* fix(server): let Claude model discovery finish a token refresh after it answers

Claude Code answers the model list before its startup token refresh has
saved the rotated refresh token. Discovery killed the CLI right after the
answer, so a refresh still in flight left the revoked token on disk and
every later Claude session failed until /login. Discovery now ends the
CLI's input and lets it exit on its own whether or not it answered, with
the existing grace period and shutdown kill as the bound.

Co-authored-by: daysun-k <8309193+daysun-k@users.noreply.github.com>

---------

Co-authored-by: daysun-k <8309193+daysun-k@users.noreply.github.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-16 12:04:46 +00:00
paseo-bot[bot]andClaude Opus 5.5 be92e85a4e fix(server): return only the newest reply as the last message after a restart (#9846)
After a daemon restart, an agent's timeline is rebuilt from provider
history, and those rows have no turn id. A reply the agent starts on its
own, such as Claude waking after a background subagent, follows the
previous reply with no user message between them, so the last assistant
message lookup joined the two and wait results and finish notifications
returned the old reply with the new one appended.

The timeline projection already treats a message id change as a new
message. Share that rule with the lookup, so both decide which rows are
chunks of one message the same way.

Closes #9814

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-16 11:02:51 +00:00
Mohamed Boudra 3d30aaec42 Allow plugins to append agent instructions (#9781)
* feat(plugins): append agent instructions on session open

Recompute plugin instructions for each launch so changes apply on reopen without changing saved agent configuration.

* test(providers): verify plugin instructions on reopen

* fix(codex): refresh instructions from restored collaboration mode

A resumed thread can retain its prior collaboration instructions when the mode catalog is unavailable. Rebuild those instructions from the current launch before the next turn.

* fix(plugins): keep launch instructions out of agent records

Provider persistence handles can contain launch configuration. Strip transient instructions before saving and projecting handles.

* fix(codex): preserve built-in collaboration instructions

Pass agent instructions through the thread configuration so Codex can apply its own Plan and Default mode instructions.

* fix(opencode): preserve instructions when reading history

History-only opens do not apply current plugin contributions, so they must not clear the native session instruction entry.

* fix(codex): retain instructions after rewinding

A rewind forks the native thread, which does not inherit its parent launch instructions. Pass the current instructions to the fork.

* Deliver updated instructions to Codex threads

* Cover Codex snapshots after rewind

* Persist provider state when reopening agents

* Limit resume persistence refresh to providers that need it
2026-11-16 17:10:14 +07:00
a302e65c85 fix(omp): show model names with slashes and underscores in full (#9836)
OMP model labels were built as `${provider}/${name}` and then cut at the
last `/`, so a free-text name such as "... ~60-70 tok/s on 0.2.10, 52/56)"
showed as "56)". Underscores were rewritten to spaces ("IQ3_S" -> "IQ3 S"),
and a colon inside the name cut everything before it.

Pi had the same bug, fixed in #9823. Move that label rule into a shared
model-label module and use it for both providers: free-text names are
kept, path-like names are shortened to their last segment, and a
"Vendor: " prefix is dropped only when it is a prefix.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Rahul Sharma <19687913+rms523@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 09:54:34 +00:00
paseo-bot[bot] d49991318f fix(server): see same-size edits saved in the tick a file was staged (#9854)
The private index snapshot behind index and All changes comparisons was a
fresh copy, newer than every entry, so Git skipped its same-timestamp
content check and a same-size save made right after staging read as
unchanged. The copy now keeps the source index's mtime, rounded down to
the second.

Closes #9827

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-16 09:48:23 +00:00
33259746db Stop timed-out watcher setups from rescanning large repos every 5 minutes (#9828)
* fix(server): abort timed-out watcher setups and back off their retries

A watcher subscription that missed WORKSPACE_GIT_WATCHER_SUBSCRIBE_TIMEOUT_MS
was abandoned but its startup scan kept walking the tree to completion, and
recovery retried every five minutes forever, repeating the full scan each
time. On a CPU-starved host that kept dozens of directories rescanning.

- FileObserver.subscribe accepts an abort signal that stops the startup scan
  and rejects; WorkspaceGit aborts setups at the deadline and on dispose.
- Consecutive setup timeouts extend the recovery delay past the 5-minute
  ladder cap, doubling up to one hour; an accepted subscription resets it.
  Degraded polling keeps its 5-60 s cadence meanwhile.

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

* fix(file-observer): keep an aborted observation's backend from starting

Aborting a subscription closes its observation, which can happen while
start() is still reading the root. The backend then started after its close
had finished, and the native backend opened a root watcher that nothing
would close.

Co-authored-by: Spencer Shulem <1703265+Spshulem@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(file-observer): abort a subscription mid-scan in the abort test

The test aborted before the backend started, so it passed with the abort
listener removed. A tree past the Linux directory limit makes a scan that
keeps walking fail on the limit instead of rejecting with the reason.

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

---------

Co-authored-by: Spencer Shulem <spshulem@gmail.com>
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: Spencer Shulem <1703265+Spshulem@users.noreply.github.com>
2026-11-16 09:10:01 +00:00
Mohamed Boudra 41c294c785 Queue agent messages until the current turn ends (#9757)
* fix(server): queue agent messages until the current turn ends

Steering refusal could replace a running turn and cancel compaction. Hold agent-originated messages and notifications together until the recipient settles, retaining explicit interruption and acknowledging finish subscriptions only after dispatch succeeds.

* fix(server): wake queued delivery at turn and permission checkpoints

A pending follow-up must not hide the permission needed to finish the current turn. Wake ready batches on recipient state changes, let completion waits report permission checkpoints, and preserve admission order and session-mode boundaries when busy dispatches retry.

* fix(server): publish autonomous readiness after run settlement

Idle snapshots emitted while the autonomous run record still existed could not wake queued delivery. Publish terminal state after clearing that run, and keep already debounced busy retries ready for the next turn boundary.

* fix(server): apply queued modes only after run admission

Preparing a later mode group could change the running turn before busy admission rejected it. Carry the requested mode into the reserved run and apply it immediately before provider startup, leaving earlier and concurrently started turns untouched.

* fix(server): keep later mode groups queued until turn end

Dispatching every mode group at once prepared later modes against the preceding turn. Keep later groups pending and reject busy sends before changing mode, leaving mode validation outside run startup.

* fix(server): deliver provider commands during queued turns

Offer waiting messages individually through the provider-owned out-of-band path while a recipient runs. Recognized commands retain their existing behavior, while ordinary messages keep waiting without starting their dispatch observers.

* fix(server): offer queued commands once while running

Remember provider declines so timer retries do not repeat side effects or reinterpret a waiting message after provider state changes.

* fix(server): defer commands that request a session mode

An explicit mode belongs to a later turn. Keep those commands on the normal idle dispatch path so an out-of-band offer cannot ignore the requested mode or change the running turn.
2026-11-16 16:02:47 +07:00
Mohamed Boudra e19980a6c9 Dismiss chat errors and identify timed-out requests (#9837)
* fix(app): dismiss chat errors and identify timed-out requests

* test(client): assert subscription timeout codes

* refactor(app): keep toast errors on the existing string boundary

* test(app): remove redundant toast duration coverage
2026-11-16 15:06:24 +07:00
paseo-bot[bot] fa8ba1bd3b test(terminal): wait for the live worker's socket before reaping (#9835)
The reaper signals a worker only after its socket accepts. The two
"cannot be opened for a moment" tests spawned a listening worker and
reaped without waiting for the listen, so on a loaded runner the reaper
found no socket, left the worker alive, and the test failed after
waitUntilGone's 5s deadline. Spawn the worker through a helper that
resolves once the socket is listening, as the other socket tests in
this file already do.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-16 06:46:25 +00:00
Mohamed Boudra e7e1b44ec8 chore(release): reconcile 0.16.0 metadata into main (#9833) 2026-11-16 13:10:33 +07:00
paseo-bot[bot]andClaude Opus 5.5 ee3a3ba8c5 test(app): pick a new port when an isolated daemon loses its reserved one (#9815)
The isolated host daemon helper reserves a port, releases it, and passes
it to the daemon. Another process can bind it in between, and the daemon
exits with EADDRINUSE. That failed a Playwright worker's own daemon in
the e2eWorker fixture. The first start now reserves a fresh port and
starts again when the daemon reports EADDRINUSE; restart() keeps the
endpoint the app already knows.

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-16 06:03:13 +00:00
d15190803a Show Pi model names with slashes and underscores in full (#9823)
* fix(pi): keep slashes and underscores in model display names

Pi model labels were built as `${provider}/${name}` and then cut at the
last `/`, so a free-text name such as "... ~60-70 tok/s, 52/56)" was shown
as "56)". Underscores were also rewritten to spaces ("IQ3_S" -> "IQ3 S").
The compact model trigger in the app repeated the last-`/` cut.

Build the Pi label from the model's own `name`/`id`: shorten only
path-like values with no whitespace (OpenRouter reports names like
"google/gemini-2.5-flash-lite"), and keep free-text names intact. The
compact trigger now strips only a leading provider namespace.

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

* test(pi): cover model labels through the catalog and drop stale ACP copies

acp-agent.test.ts still imported transformPiModels, which the Pi label
fix removed, so its modelTransformer test and a stale copy of the old
Pi label tests failed. The modelTransformer test now supplies its own
transformer, and the Pi label cases run through fetchCatalog with the
reported model names instead of an exported helper.

Co-authored-by: Rahul Sharma <19687913+rms523@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(pi): keep colons inside free-text model names

The vendor-prefix strip cut a free-text Pi name at its first ": ", so
"Qwen3 IQ3_S (tail skip: on, 52/56)" showed as "on, 52/56)". Strip only
when the text before ": " has no parenthesis or comma, which keeps
OpenRouter's "Vendor: Model" names shortened.

Co-authored-by: Rahul Sharma <19687913+rms523@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Rahul Sharma <19687913+rms523@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-16 04:55:28 +00:00
Josh BendavidandClaude Opus 5.5 ade3817a45 fix(server): fall back to the next socket directory when the bind is refused (#9214)
A PASEO_HOME on AFS passes the socket directory checks, then refuses the
Unix socket bind with EPERM, and the terminal worker failed to start. The
worker now binds each eligible candidate in turn and moves on when the
filesystem refuses the socket (EPERM, EACCES, EOPNOTSUPP, ENOTSUP). Other
listen errors still fail the start.

Fixes #9213

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 03:56:04 +00:00
146 changed files with 6478 additions and 1056 deletions
+86 -29
View File
@@ -1,45 +1,102 @@
# Changelog
## 0.16.0-beta.2 - 2026-11-11
## 0.16.0 - 2026-11-16
- **Background tasks:** Paseo now shows the background tasks an agent is running, such as shells and monitors, above the composer, with a Stop button for each. Works with Claude Code, Codex and OpenCode v2. ([#6220](https://github.com/getpaseo/paseo/pull/6220), [#9162](https://github.com/getpaseo/paseo/pull/9162) by [@fxlelouarn](https://github.com/fxlelouarn))
- **Plugin sidebar views:** A plugin can replace the sidebar's content with its own layout of workspaces, agents, projects and terminals across every connected host. Pick the view per device under Settings → Sidebar; Paseo's sidebar header and footer stay in place. ([#8906](https://github.com/getpaseo/paseo/pull/8906))
- **Plugin composer controls:** Plugins can add their own controls to the composer, and read and set its prompt, attachments, provider, model, mode and thinking. They can also put the cursor in any agent's composer, add items to New workspace, and store their own 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))
- **Faster diff loading:** Opening Changes shows the file tree right away while file contents load. Large diffs arrive in batches, so the rest of the app keeps responding while they load, and diffs take priority over the daemon's 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))
- **Polish:** The chat stays still when a turn ends, and returning to a chat that has not changed shows it as it is with no refresh. Tool rows show their final title and icon from the first frame, the context window popover opens with usage already loaded, and sidebar hover cards open one at a time. ([#8944](https://github.com/getpaseo/paseo/pull/8944), [#9175](https://github.com/getpaseo/paseo/pull/9175), [#9242](https://github.com/getpaseo/paseo/pull/9242), [#9248](https://github.com/getpaseo/paseo/pull/9248), [#9212](https://github.com/getpaseo/paseo/pull/9212), [#9071](https://github.com/getpaseo/paseo/pull/9071))
- **Rebuilt mobile chat timeline:** The chat timeline on iOS and Android was rebuilt. Expanding or collapsing a turn summary, todo card or tool-call group keeps the line you tapped in place, and on Android so do Show more, Show less and plan cards. ([#8717](https://github.com/getpaseo/paseo/pull/8717), [#9085](https://github.com/getpaseo/paseo/pull/9085))
- **Keyboard shortcuts on mobile:** With a keyboard connected, iPad and Android now run the same shortcuts as desktop, including your custom bindings. Shortcut hints and Settings → Shortcuts appear when a keyboard is detected. Shortcuts also work in narrow desktop and browser windows. ([#8625](https://github.com/getpaseo/paseo/pull/8625) by [@jeroenfrenken](https://github.com/jeroenfrenken), [@lstroud](https://github.com/lstroud))
- **Touch-sized tablet controls:** On iPad and other touch-screen devices, the wide layout now has touch-sized buttons, rows and bars. The composer toolbar folds its controls into the model menu when space runs out, and swiping right on the workspace reveals a collapsed sidebar as an overlay. ([#8748](https://github.com/getpaseo/paseo/pull/8748), [#8885](https://github.com/getpaseo/paseo/pull/8885), [#8891](https://github.com/getpaseo/paseo/pull/8891), [#8909](https://github.com/getpaseo/paseo/pull/8909), [#9151](https://github.com/getpaseo/paseo/pull/9151), [#9238](https://github.com/getpaseo/paseo/pull/9238), [#8739](https://github.com/getpaseo/paseo/pull/8739) by [@zeyugao](https://github.com/zeyugao))
- **Undo workspace archive:** Archiving a workspace in the app now shows a "Workspace archived" toast for six seconds. Undo, or Cmd/Ctrl+Z, restores the workspace with its tabs and agents. On desktop, sidebar workspace rows also get an archive button on hover. ([#8904](https://github.com/getpaseo/paseo/pull/8904), [#9104](https://github.com/getpaseo/paseo/pull/9104))
- **Fewer reconnects on return:** Returning to the app keeps a working connection, including one in the middle of a large response, and reconnects once when it has to. On a host with several saved connections, Paseo stays on the one that works. ([#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))
- **Background tasks:** See and stop background tasks above the composer for Claude Code, Codex and OpenCode v2. ([#6220](https://github.com/getpaseo/paseo/pull/6220), [#9162](https://github.com/getpaseo/paseo/pull/9162), [#9635](https://github.com/getpaseo/paseo/pull/9635) by [@fxlelouarn](https://github.com/fxlelouarn))
- **Built-in plugin gallery:** Browse, search and install plugins without leaving Paseo. Manage their settings and updates from the same page. ([#9752](https://github.com/getpaseo/paseo/pull/9752))
- **Command center tabs:** Switch between Workspaces, Files and Actions, with recent workspaces shown first. Search now includes archived workspaces and matches agent titles within their workspace. ([#9689](https://github.com/getpaseo/paseo/pull/9689))
- **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))
- **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))
- **Faster composer menus:** Command and file suggestions open sooner in large lists and stay against the composer as it changes size. ([#9657](https://github.com/getpaseo/paseo/pull/9657), [#9647](https://github.com/getpaseo/paseo/pull/9647), [#9642](https://github.com/getpaseo/paseo/pull/9642))
- **Keyboard shortcuts on mobile:** A connected keyboard gives iPad and Android the same shortcuts as desktop, including custom bindings. Shift+Tab in the iPad composer switches mode without typing a tab. ([#8625](https://github.com/getpaseo/paseo/pull/8625), [#9561](https://github.com/getpaseo/paseo/pull/9561) by [@jeroenfrenken](https://github.com/jeroenfrenken), [@lstroud](https://github.com/lstroud))
- **Touch-sized tablet controls:** Wide layouts on touch devices have larger buttons and rows. The composer folds controls into the model menu when space runs out. ([#8748](https://github.com/getpaseo/paseo/pull/8748), [#8885](https://github.com/getpaseo/paseo/pull/8885), [#8891](https://github.com/getpaseo/paseo/pull/8891), [#8909](https://github.com/getpaseo/paseo/pull/8909), [#9151](https://github.com/getpaseo/paseo/pull/9151), [#9238](https://github.com/getpaseo/paseo/pull/9238), [#8739](https://github.com/getpaseo/paseo/pull/8739) by [@zeyugao](https://github.com/zeyugao))
- **Undo workspace archive:** Restore an archived workspace with Undo or Cmd/Ctrl+Z during the six-second toast. Paseo checks for unsaved files and unpushed commits before removing a worktree. ([#8904](https://github.com/getpaseo/paseo/pull/8904), [#9104](https://github.com/getpaseo/paseo/pull/9104), [#9625](https://github.com/getpaseo/paseo/pull/9625), [#9753](https://github.com/getpaseo/paseo/pull/9753) by [@ragokan](https://github.com/ragokan))
### Added
- Added a Change base picker in Changes for worktree workspaces, so diffs, the commit list and Git actions can use another branch ([#8642](https://github.com/getpaseo/paseo/pull/8642), [#8934](https://github.com/getpaseo/paseo/pull/8934) by [@Myasuka](https://github.com/Myasuka))
- Added links for issue and pull request references such as `#123` and `owner/repo#123` in agent replies, plans, the pull request panel and file previews, for GitHub, GitLab, Gitea, Forgejo and Codeberg ([#8636](https://github.com/getpaseo/paseo/pull/8636))
- Added iPhone Duo layout support: workspace actions sit in the system vertical bar, and the sidebar and workspace split on either side 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 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: an agent or plugin can create a helper with `background: true` that opens no tab, sends no notification and stays out of the sidebar and default agent lists ([#8683](https://github.com/getpaseo/paseo/pull/8683))
- 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))
- Added plugin badges to sidebar workspace rows ([#7645](https://github.com/getpaseo/paseo/pull/7645) by [@jtomaszewski](https://github.com/jtomaszewski))
- Added a Download button for files without a preview ([#9640](https://github.com/getpaseo/paseo/pull/9640))
- Added Copilot premium-request usage and remaining quota to Usage ([#8489](https://github.com/getpaseo/paseo/pull/8489) by [@thisisryanswift](https://github.com/thisisryanswift))
### Changed
- Changed opening a workspace to restore the tab you left instead of jumping to the agent that needs attention ([#8935](https://github.com/getpaseo/paseo/pull/8935))
- Changed question cards so picking an option no longer advances automatically; continue with Next or Submit ([#8525](https://github.com/getpaseo/paseo/pull/8525))
- Changed the slash command menu to show loading and error states with Retry, and to stop selecting `/exit` by default ([#8905](https://github.com/getpaseo/paseo/pull/8905))
- Changed the workspace header and tabs to switch to compact controls when Explorer or a split pane narrows the workspace ([#8740](https://github.com/getpaseo/paseo/pull/8740), [#9088](https://github.com/getpaseo/paseo/pull/9088) by [@zeyugao](https://github.com/zeyugao))
- Changed question cards to wait for Next or Submit after you select an option ([#8525](https://github.com/getpaseo/paseo/pull/8525))
- Changed the slash command menu to stop selecting `/exit` by default ([#8905](https://github.com/getpaseo/paseo/pull/8905))
- Changed workspace header controls to fit narrow split panes ([#8740](https://github.com/getpaseo/paseo/pull/8740), [#9088](https://github.com/getpaseo/paseo/pull/9088) by [@zeyugao](https://github.com/zeyugao))
- Changed sending a message to a Pi agent whose process has exited to fail immediately with an instruction to reload the agent ([#8718](https://github.com/getpaseo/paseo/pull/8718))
- Changed Rename workspace in the sidebar on desktop and wide web layouts to edit the title in place instead of opening a dialog ([#9280](https://github.com/getpaseo/paseo/pull/9280))
- Changed What's new and the website changelog to show a release's highlights first, with the full list behind Show all changes ([#9281](https://github.com/getpaseo/paseo/pull/9281))
- Changed What's new to show highlights first, with the full list behind Show all changes ([#9281](https://github.com/getpaseo/paseo/pull/9281))
- Changed Claude Bypass to approve execution requests from ask rules and hooks while keeping questions and plan review interactive ([#9760](https://github.com/getpaseo/paseo/pull/9760))
- Changed Claude permission cards to show the reason supplied by the provider ([#3950](https://github.com/getpaseo/paseo/pull/3950) by [@codebutler](https://github.com/codebutler))
- Changed the pull request pane so Activity can be resized or collapsed to give checks more space ([#9656](https://github.com/getpaseo/paseo/pull/9656))
- Changed macOS desktop tab shortcuts to Cmd+Shift+[ and Cmd+Shift+] ([#7692](https://github.com/getpaseo/paseo/pull/7692) by [@jtomaszewski](https://github.com/jtomaszewski))
- Changed Cmd/Ctrl+N on New workspace to open the project chooser without leaving the draft ([#9741](https://github.com/getpaseo/paseo/pull/9741))
- Changed mobile Settings navigation to restore the sidebar where you left it ([#9641](https://github.com/getpaseo/paseo/pull/9641))
### Fixed
- Fixed long tool details hiding their collapse header or preventing scrolling through their output ([#9770](https://github.com/getpaseo/paseo/pull/9770))
- Fixed image previews briefly showing an error or a stretched image while loading ([#9698](https://github.com/getpaseo/paseo/pull/9698))
- Fixed web and desktop chats jumping to the beginning when older history became virtualized ([#9664](https://github.com/getpaseo/paseo/pull/9664) by [@luoph](https://github.com/luoph))
- Fixed older chat history requiring another mouse-wheel movement after reaching the top ([#9570](https://github.com/getpaseo/paseo/pull/9570))
- Fixed losing code indentation and line breaks when copying a selection across part of a code block ([#9515](https://github.com/getpaseo/paseo/pull/9515) by [@michaelmwu](https://github.com/michaelmwu))
- Fixed overlapping axis titles and clipped labels in Mermaid XY charts ([#9483](https://github.com/getpaseo/paseo/pull/9483) by [@FluidXin](https://github.com/FluidXin))
- Fixed the iOS command menu staying open after tapping a command ([#9755](https://github.com/getpaseo/paseo/pull/9755))
- Fixed retrying an edited agent draft after a failed start ([#9534](https://github.com/getpaseo/paseo/pull/9534) by [@michaelmwu](https://github.com/michaelmwu))
- Fixed model profile buttons ignoring taps on Android tablets ([#9526](https://github.com/getpaseo/paseo/pull/9526) by [@moevis](https://github.com/moevis))
- Fixed Settings losing scroll position and edits after appearance changes ([#9605](https://github.com/getpaseo/paseo/pull/9605))
- Fixed unreadable selected rows in light plugin themes and barely visible highlights in Pure Black ([#9579](https://github.com/getpaseo/paseo/pull/9579) by [@nathansgreen](https://github.com/nathansgreen))
- Fixed missing keyboard focus rings on header and toolbar icon buttons on web and desktop ([#9745](https://github.com/getpaseo/paseo/pull/9745) by [@junjzhang](https://github.com/junjzhang))
- Fixed sidebar rows flashing in the wrong position after a drag on iOS and Android ([#9681](https://github.com/getpaseo/paseo/pull/9681))
- Fixed desktop startup reporting failure while its daemon was still starting ([#9043](https://github.com/getpaseo/paseo/pull/9043) by [@magiclaw](https://github.com/magiclaw))
- Fixed typed characters being lost while web and desktop terminals restored their screen ([#9533](https://github.com/getpaseo/paseo/pull/9533))
- Fixed physical arrow keys failing in Android terminals and dropping the next typed character ([#9407](https://github.com/getpaseo/paseo/pull/9407) by [@moevis](https://github.com/moevis))
- Fixed non-Git workspaces missing Archive workspace in the command center ([#9777](https://github.com/getpaseo/paseo/pull/9777) by [@andheiberg](https://github.com/andheiberg))
- Fixed workspace scripts disappearing when a later configuration read timed out ([#9477](https://github.com/getpaseo/paseo/pull/9477) by [@dinhphieu](https://github.com/dinhphieu))
- Fixed sidebar Usage hiding an account after its usage refresh failed ([#9594](https://github.com/getpaseo/paseo/pull/9594))
- Fixed closed agents staying unread when their provider session no longer existed ([#9737](https://github.com/getpaseo/paseo/pull/9737) by [@luoph](https://github.com/luoph))
- Fixed completion notifications showing an older reply after an autonomous agent turn ([#9793](https://github.com/getpaseo/paseo/pull/9793))
- Fixed interrupting messages failing with "already has an active run" ([#9537](https://github.com/getpaseo/paseo/pull/9537) by [@michaelmwu](https://github.com/michaelmwu))
- Fixed message retries being refused after a failure before delivery to the provider ([#9580](https://github.com/getpaseo/paseo/pull/9580) by [@tmad4000](https://github.com/tmad4000))
- Fixed newly reopened agents losing their provider process on the next idle-cleanup sweep ([#8857](https://github.com/getpaseo/paseo/pull/8857) by [@fdkevin0](https://github.com/fdkevin0))
- Fixed Claude session crons and /loop wakeups being lost to idle runtime cleanup ([#9744](https://github.com/getpaseo/paseo/pull/9744) by [@KronixDev](https://github.com/KronixDev))
- Fixed forking from a reply when a tool started before it and finished afterward ([#9627](https://github.com/getpaseo/paseo/pull/9627) by [@ragokan](https://github.com/ragokan))
- Fixed large Codex history pages stopping history loading when their individual items still fit ([#9432](https://github.com/getpaseo/paseo/pull/9432) by [@RockStone](https://github.com/RockStone))
- Fixed OpenCode sessions failing to reconnect after a daemon restart when OpenCode used Bun ([#9653](https://github.com/getpaseo/paseo/pull/9653) by [@quickwind](https://github.com/quickwind))
- Fixed provider refresh retaining OpenCode v1 after an upgrade to v2 ([#9593](https://github.com/getpaseo/paseo/pull/9593) by [@tkfka1](https://github.com/tkfka1))
- Fixed OpenCode v2 failing to discover plugin tools available only to its session ([#9426](https://github.com/getpaseo/paseo/pull/9426) by [@dptsolutions](https://github.com/dptsolutions))
- Fixed ACP models sharing the wrong thinking levels when the provider supplied levels per model ([#9717](https://github.com/getpaseo/paseo/pull/9717) by [@AlfredRR](https://github.com/AlfredRR), [@doskoi](https://github.com/doskoi))
- Fixed failed ACP tools without output preventing conversation history from loading ([#9467](https://github.com/getpaseo/paseo/pull/9467) by [@Myasuka](https://github.com/Myasuka))
- Fixed Pi and OMP tool calls with null optional arguments appearing as unknown tools ([#9506](https://github.com/getpaseo/paseo/pull/9506) by [@papag00se](https://github.com/papag00se))
- Fixed imported OMP sessions saving a file path instead of their session ID ([#8854](https://github.com/getpaseo/paseo/pull/8854) by [@LiebeLee](https://github.com/LiebeLee))
- Fixed cross-host child agents losing their caller's mode when both used the same provider ([#9512](https://github.com/getpaseo/paseo/pull/9512) by [@ortschun](https://github.com/ortschun))
- Fixed plugin child agents changing from failed or canceled to completed when their session closed ([#8563](https://github.com/getpaseo/paseo/pull/8563) by [@hadan8977](https://github.com/hadan8977))
- Fixed CLI commands acting on a different agent whose title matched a missing full agent ID ([#9680](https://github.com/getpaseo/paseo/pull/9680), [#9731](https://github.com/getpaseo/paseo/pull/9731) by [@ese111](https://github.com/ese111))
- Fixed archive, detach and reload failing for agents omitted from the CLI listing ([#9726](https://github.com/getpaseo/paseo/pull/9726) by [@xunWhale](https://github.com/xunWhale))
- Fixed `paseo agent wait` exiting successfully when no agent matched the ID ([#9782](https://github.com/getpaseo/paseo/pull/9782) by [@Eapp1e](https://github.com/Eapp1e))
- Fixed voice mode failing to start when speech input and output both used OpenAI ([#9779](https://github.com/getpaseo/paseo/pull/9779) by [@Huyvux12](https://github.com/Huyvux12))
- Fixed dictation hiding a stream error behind a 30-second delivery timeout ([#9784](https://github.com/getpaseo/paseo/pull/9784) by [@tieo](https://github.com/tieo))
- Fixed plugin providers rejecting Review attachments in All mode ([#9590](https://github.com/getpaseo/paseo/pull/9590) by [@ese111](https://github.com/ese111))
- Fixed plugin timeline writes accepting kinds that the app could not show ([#7677](https://github.com/getpaseo/paseo/pull/7677) by [@ragokan](https://github.com/ragokan))
- Fixed the chat moving when a turn ended ([#8944](https://github.com/getpaseo/paseo/pull/8944), [#9175](https://github.com/getpaseo/paseo/pull/9175))
- Fixed Claude and OpenCode tool rows changing their title and icon as arguments arrived ([#9248](https://github.com/getpaseo/paseo/pull/9248))
- Fixed the context window popover opening before usage was loaded ([#9212](https://github.com/getpaseo/paseo/pull/9212))
- Fixed sidebar hover cards opening together ([#9071](https://github.com/getpaseo/paseo/pull/9071))
- Fixed the working indicator disappearing when returning to a chat whose agent finished while you were away ([#9170](https://github.com/getpaseo/paseo/pull/9170))
- Fixed chats with short collapsed turns opening with empty space until you scrolled ([#8358](https://github.com/getpaseo/paseo/pull/8358), [#9083](https://github.com/getpaseo/paseo/pull/9083))
- Fixed Collapse turns hiding an earlier reply inside a later turn's summary line after an idle Claude, Codex or OpenCode agent was resumed ([#9098](https://github.com/getpaseo/paseo/pull/9098))
- Fixed the missing space between a prompt and the reply or collapsed-turn summary line below it ([#9009](https://github.com/getpaseo/paseo/pull/9009))
- Fixed a long user message showing without its fade and Show more for one frame when a chat opened ([#9302](https://github.com/getpaseo/paseo/pull/9302))
- Fixed Markdown tables showing as literal pipes when written directly below a paragraph with no blank line ([#8485](https://github.com/getpaseo/paseo/pull/8485) by [@ragokan](https://github.com/ragokan), [@suk-6](https://github.com/suk-6), [@thsrite](https://github.com/thsrite))
- Fixed linked badge images that share a line with text rendering as full-width blocks on web and desktop ([#8530](https://github.com/getpaseo/paseo/pull/8530))
- Fixed View diagram opening fullscreen instead of returning to the inline Mermaid diagram after View source ([#8932](https://github.com/getpaseo/paseo/pull/8932) by [@luoph](https://github.com/luoph))
@@ -47,21 +104,16 @@
- Fixed unsent composer text and attachments being deleted when an agent tab was closed ([#9079](https://github.com/getpaseo/paseo/pull/9079))
- Fixed pasting text with hyperlinks into the composer dropping the link URLs; links now paste as Markdown ([#8972](https://github.com/getpaseo/paseo/pull/8972))
- Fixed the composer losing focus after clicking Send with a mouse ([#9015](https://github.com/getpaseo/paseo/pull/9015))
- Fixed the composer resting 50pt above the bottom edge on iPhone ([#8823](https://github.com/getpaseo/paseo/pull/8823) by [@zeyugao](https://github.com/zeyugao))
- Fixed Add host sending you to Settings from the sidebar and New workspace ([#8512](https://github.com/getpaseo/paseo/pull/8512))
- Fixed a failed agent's red dot and Failed grouping staying in the sidebar after opening the agent or choosing Mark as read ([#8831](https://github.com/getpaseo/paseo/pull/8831))
- Fixed a workspace's unread indicator staying on after it was cleared while the agent's runtime was closed ([#9087](https://github.com/getpaseo/paseo/pull/9087))
- Fixed unarchiving a workspace not restoring the agents that were archived with it ([#9210](https://github.com/getpaseo/paseo/pull/9210))
- Fixed the context window popover closing by itself whenever the chat scrolled during a streaming reply ([#8742](https://github.com/getpaseo/paseo/pull/8742) by [@3ae3ae](https://github.com/3ae3ae))
- Fixed the sidebar usage summary updating only when Usage was opened ([#7806](https://github.com/getpaseo/paseo/pull/7806) by [@ragokan](https://github.com/ragokan))
- Fixed tooltips and menus above their trigger briefly covering it on Android when their content grew after opening ([#9247](https://github.com/getpaseo/paseo/pull/9247))
- Fixed History showing "Could not load history" after reloading the web app on the History screen ([#9029](https://github.com/getpaseo/paseo/pull/9029))
- Fixed section links in an HTML file preview replacing the preview with the Paseo app instead of scrolling within the file ([#8559](https://github.com/getpaseo/paseo/pull/8559) by [@3ae3ae](https://github.com/3ae3ae))
- Fixed Files Refresh leaving a newly created file hidden when its folder was collapsed during the refresh ([#8582](https://github.com/getpaseo/paseo/pull/8582) by [@hadan8977](https://github.com/hadan8977))
- Fixed the branch switcher showing "No branches found" while branches are still loading or after the request fails ([#8938](https://github.com/getpaseo/paseo/pull/8938))
- Fixed commit history showing a doubled slash, no rename status and no diff for a file moved up a directory ([#8509](https://github.com/getpaseo/paseo/pull/8509) by [@hadan8977](https://github.com/hadan8977))
- Fixed a merged pull request disappearing from its workspace when the checkout was behind the pull request's head
- Fixed workspace Git watchers staying in fallback polling after a watcher setup timeout
- Fixed abandoned connections staying open for up to 45 seconds after the web or desktop app reconnected ([#9067](https://github.com/getpaseo/paseo/pull/9067))
- Fixed a connection routed through another host closing with "The receiving client cannot keep up with host output" while fetching a very large timeline ([#9109](https://github.com/getpaseo/paseo/pull/9109))
- Fixed a connected host staying in error after it was updated to a supported version ([#8423](https://github.com/getpaseo/paseo/pull/8423) by [@DAnaeto](https://github.com/DAnaeto))
@@ -123,16 +175,21 @@
- Fixed a plugin the daemon terminated for an invalid message staying listed with no exit reported ([#9285](https://github.com/getpaseo/paseo/pull/9285) by [@Brandon168](https://github.com/Brandon168))
- Fixed ACP provider plugins dropping the token usage an agent reports in its prompt response ([#9396](https://github.com/getpaseo/paseo/pull/9396) by [@Myasuka](https://github.com/Myasuka))
- Fixed the published `@getpaseo/*` npm packages declaring no license; they now declare Apache-2.0 ([#7816](https://github.com/getpaseo/paseo/pull/7816) by [@mdlawson](https://github.com/mdlawson), [@ragokan](https://github.com/ragokan))
- Fixed forking from an earlier reply failing with "This checkpoint changed after it was created" after a plugin updated one of its timeline cards ([#8746](https://github.com/getpaseo/paseo/pull/8746) by [@monarchmaisuriya](https://github.com/monarchmaisuriya))
- Fixed Collapse turns leaving a turn open, or folding to an earlier reply, when a plugin renders the final reply ([#8811](https://github.com/getpaseo/paseo/pull/8811) by [@geoqiao](https://github.com/geoqiao))
- Fixed plugin screens showing "This plugin surface is unavailable" while the plugin catalog is still loading after an app reload ([#8123](https://github.com/getpaseo/paseo/pull/8123) by [@vs-tahir](https://github.com/vs-tahir))
- Fixed the Workspaces list being pushed out of the mobile sidebar on short screens when plugins add many navigation items ([#8727](https://github.com/getpaseo/paseo/pull/8727) by [@jaredwang](https://github.com/jaredwang))
- Fixed timeline plugins not receiving the sender, event and original text on agent-message tool calls ([#8492](https://github.com/getpaseo/paseo/pull/8492) by [@RRD-dev](https://github.com/RRD-dev), [@luoph](https://github.com/luoph))
- Fixed plugin RPCs failing when their input or output schema uses a transform ([#8550](https://github.com/getpaseo/paseo/pull/8550))
### Breaking
- Removed the deprecated `agent.turn.after.timeline` SDK field, which always returned an empty list ([#9573](https://github.com/getpaseo/paseo/pull/9573) by [@jtomaszewski](https://github.com/jtomaszewski))
### Notes
- Background tasks, the Change base picker, archive undo, background agents, plugin subscriptions and fx need both the host and the app on this version
- Update both the host and app to use the plugin gallery, background tasks, Change base, archive undo, background agents, plugin subscriptions and fx
- Plugin authors reading `agent.turn.after.timeline` must use `timeline.refetch({ direction: "tail", limit: 1, wholeTurns: true })` and filter entries by `event.turnId`
- Archive undo restores the workspace, not uncommitted files removed with its worktree
## 0.15.4 - 2026-11-10
+86 -29
View File
@@ -1,45 +1,102 @@
# Changelog
## 0.16.0-beta.2 - 2026-11-11
## 0.16.0 - 2026-11-16
- **后台任务**:Paseo 现在会在 Composer 上方显示 Agent 正在运行的后台任务,例如 shell 和监视器,每项都带“停止”按钮。支持 Claude Code、Codex 和 OpenCode v2。 ([#6220](https://github.com/getpaseo/paseo/pull/6220), [#9162](https://github.com/getpaseo/paseo/pull/9162),贡献者:[@fxlelouarn](https://github.com/fxlelouarn))
- **插件侧边栏视图**:插件可以用自己的布局替换侧边栏内容,展示所有已连接主机上的工作区、Agent、项目和终端。在“设置 → 侧边栏”中为每台设备选择视图;Paseo 的侧边栏页眉和页脚保持不变。 ([#8906](https://github.com/getpaseo/paseo/pull/8906))
- **插件 Composer 控件**:插件可以向 Composer 添加自己的控件,并读取和设置其中的提示词、附件、Provider、模型、模式和思考强度。插件还可以把光标放到任意 Agent 的 Composer 中、向“新建工作区”添加条目,并在 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))
- **更快的 diff 加载**:打开“更改”时会立即显示文件树,文件内容随后加载。大型 diff 分批到达,加载期间应用的其他部分照常响应,并且 diff 优先于 daemon 的后台 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))
- **细节打磨**:一轮对话结束时聊天保持不动,返回没有变化的聊天时直接显示原样,无需刷新。工具行从第一帧起就显示最终标题和图标,上下文窗口浮层打开时用量已加载完成,侧边栏悬停卡片一次只打开一个。 ([#8944](https://github.com/getpaseo/paseo/pull/8944), [#9175](https://github.com/getpaseo/paseo/pull/9175), [#9242](https://github.com/getpaseo/paseo/pull/9242), [#9248](https://github.com/getpaseo/paseo/pull/9248), [#9212](https://github.com/getpaseo/paseo/pull/9212), [#9071](https://github.com/getpaseo/paseo/pull/9071))
- **重建移动端聊天时间线**:iOS 和 Android 上的聊天时间线已重建。展开或折叠轮次摘要、待办卡片或工具调用组时,你点按的那一行保持原位;在 Android 上,“显示更多”“收起”和计划卡片也是如此。 ([#8717](https://github.com/getpaseo/paseo/pull/8717), [#9085](https://github.com/getpaseo/paseo/pull/9085))
- **移动端键盘快捷键**:连接键盘后,iPad 和 Android 现在可使用与桌面端相同的快捷键,包括你自定义的绑定。检测到键盘时会显示快捷键提示和“设置 → 快捷键”。在较窄的桌面端和浏览器窗口中快捷键同样可用。 ([#8625](https://github.com/getpaseo/paseo/pull/8625),贡献者:[@jeroenfrenken](https://github.com/jeroenfrenken)、[@lstroud](https://github.com/lstroud))
- **适合触控的平板控件**:在 iPad 和其他触屏设备上,宽屏布局现在使用适合触控尺寸的按钮、行和栏。Composer 工具栏在空间不足时会把控件收进模型菜单;在工作区上向右滑动,可将已折叠的侧边栏以浮层方式显示。 ([#8748](https://github.com/getpaseo/paseo/pull/8748), [#8885](https://github.com/getpaseo/paseo/pull/8885), [#8891](https://github.com/getpaseo/paseo/pull/8891), [#8909](https://github.com/getpaseo/paseo/pull/8909), [#9151](https://github.com/getpaseo/paseo/pull/9151), [#9238](https://github.com/getpaseo/paseo/pull/9238), [#8739](https://github.com/getpaseo/paseo/pull/8739),贡献者:[@zeyugao](https://github.com/zeyugao))
- **撤销工作区归档**:在应用中归档工作区时,现在会显示“Workspace 已归档”提示,持续六秒。点击“撤销”或按 Cmd/Ctrl+Z 可恢复该工作区及其标签页和 Agent。在桌面端,侧边栏的工作区行在悬停时还会显示归档按钮。 ([#8904](https://github.com/getpaseo/paseo/pull/8904), [#9104](https://github.com/getpaseo/paseo/pull/9104))
- **返回时更少重连**:返回应用时会保留仍可用的连接,包括正在传输大型响应的连接,只在必要时重连一次。主机保存了多个连接时,Paseo 会留在可用的那个连接上。 ([#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))
- **后台任务**:在 Composer 上方查看并停止 Claude Code、Codex 和 OpenCode v2 的后台任务。 ([#6220](https://github.com/getpaseo/paseo/pull/6220), [#9162](https://github.com/getpaseo/paseo/pull/9162), [#9635](https://github.com/getpaseo/paseo/pull/9635),贡献者:[@fxlelouarn](https://github.com/fxlelouarn))
- **内置插件库**:无需离开 Paseo,即可浏览、搜索和安装插件,并在同一页面管理插件设置和更新。 ([#9752](https://github.com/getpaseo/paseo/pull/9752))
- **命令中心标签页**:在工作区、文件和操作之间切换,最近使用的工作区优先显示。搜索现在包含已归档工作区,还可匹配工作区内的 Agent 标题。 ([#9689](https://github.com/getpaseo/paseo/pull/9689))
- **插件侧边栏视图**:插件可以用自己的布局替换侧边栏,展示已连接主机上的工作区和 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))
- **返回应用时更少提示**:返回没有变化的聊天时,不再闪现“正在更新消息”。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))
- **更快的 Composer 菜单**:大型列表中的命令和文件建议更快打开,并随 Composer 尺寸变化保持贴合。 ([#9657](https://github.com/getpaseo/paseo/pull/9657), [#9647](https://github.com/getpaseo/paseo/pull/9647), [#9642](https://github.com/getpaseo/paseo/pull/9642))
- **移动端键盘快捷键**:连接键盘后,iPad 和 Android 可使用与桌面端相同的快捷键,包括自定义绑定。在 iPad Composer 中按 Shift+Tab 会切换模式,不再输入制表符。 ([#8625](https://github.com/getpaseo/paseo/pull/8625), [#9561](https://github.com/getpaseo/paseo/pull/9561),贡献者:[@jeroenfrenken](https://github.com/jeroenfrenken), [@lstroud](https://github.com/lstroud))
- **适合触控的平板控件**:触屏设备上的宽屏布局使用更大的按钮和行。空间不足时,Composer 会将控件收进模型菜单。 ([#8748](https://github.com/getpaseo/paseo/pull/8748), [#8885](https://github.com/getpaseo/paseo/pull/8885), [#8891](https://github.com/getpaseo/paseo/pull/8891), [#8909](https://github.com/getpaseo/paseo/pull/8909), [#9151](https://github.com/getpaseo/paseo/pull/9151), [#9238](https://github.com/getpaseo/paseo/pull/9238), [#8739](https://github.com/getpaseo/paseo/pull/8739),贡献者:[@zeyugao](https://github.com/zeyugao))
- **撤销工作区归档**:在六秒提示期间,点击“撤销”或按 Cmd/Ctrl+Z 可恢复已归档的工作区。Paseo 在移除 worktree 前会检查未保存的文件和未推送的提交。 ([#8904](https://github.com/getpaseo/paseo/pull/8904), [#9104](https://github.com/getpaseo/paseo/pull/9104), [#9625](https://github.com/getpaseo/paseo/pull/9625), [#9753](https://github.com/getpaseo/paseo/pull/9753),贡献者:[@ragokan](https://github.com/ragokan))
### 新增
- 在“更改”中为 worktree 工作区新增基准分支选择器(Change base),diff、提交列表和 Git 操作可改用其他分支 ([#8642](https://github.com/getpaseo/paseo/pull/8642), [#8934](https://github.com/getpaseo/paseo/pull/8934),贡献者:[@Myasuka](https://github.com/Myasuka))
- 新增 Issue 和 PR 引用链接:Agent 回复、计划、PR 面板和文件预览中的 `#123`、`owner/repo#123` 等引用会链接到 GitHub、GitLab、Gitea、Forgejo 或 Codeberg ([#8636](https://github.com/getpaseo/paseo/pull/8636))
- 新增 iPhone Duo 布局支持:工作区操作位于系统竖向栏中,侧边栏和工作区分列折痕两侧 ([#8741](https://github.com/getpaseo/paseo/pull/8741), [#8901](https://github.com/getpaseo/paseo/pull/8901),贡献者:[@zeyugao](https://github.com/zeyugao))
- 为 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 或插件可通过 `background: true` 创建辅助 Agent,它不打开标签页、不发送通知,也不出现在侧边栏和默认 Agent 列表中 ([#8683](https://github.com/getpaseo/paseo/pull/8683))
- 新增后台 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))
- 为侧边栏工作区行新增插件徽章 ([#7645](https://github.com/getpaseo/paseo/pull/7645),贡献者:[@jtomaszewski](https://github.com/jtomaszewski))
- 为无法预览的文件新增“下载”按钮 ([#9640](https://github.com/getpaseo/paseo/pull/9640))
- 在用量中新增 Copilot 高级请求用量和剩余额度 ([#8489](https://github.com/getpaseo/paseo/pull/8489),贡献者:[@thisisryanswift](https://github.com/thisisryanswift))
### 变更
- 打开工作区时恢复你离开时的标签页,不再跳转到需要关注的 Agent ([#8935](https://github.com/getpaseo/paseo/pull/8935))
- 问题卡片中选择选项后不再自动前进;请用“下一步”或“提交”继续 ([#8525](https://github.com/getpaseo/paseo/pull/8525))
- 斜杠命令菜单现在显示加载和错误状态并提供“重试”,且不再默认选中 `/exit` ([#8905](https://github.com/getpaseo/paseo/pull/8905))
- 文件浏览器(Explorer)或分屏使工作区变窄时,工作区页眉和标签页改用紧凑控件 ([#8740](https://github.com/getpaseo/paseo/pull/8740), [#9088](https://github.com/getpaseo/paseo/pull/9088),贡献者:[@zeyugao](https://github.com/zeyugao))
- 问题卡片在选择选项后等待点击“下一步”或“提交” ([#8525](https://github.com/getpaseo/paseo/pull/8525))
- 斜杠命令菜单不再默认选中 `/exit` ([#8905](https://github.com/getpaseo/paseo/pull/8905))
- 调整工作区页眉控件以适应较窄的分屏窗格 ([#8740](https://github.com/getpaseo/paseo/pull/8740), [#9088](https://github.com/getpaseo/paseo/pull/9088),贡献者:[@zeyugao](https://github.com/zeyugao))
- 向进程已退出的 Pi Agent 发送消息时立即失败,并提示重新加载该 Agent ([#8718](https://github.com/getpaseo/paseo/pull/8718))
- 在桌面端和宽屏网页布局中,侧边栏的“重命名 workspace”改为在原处编辑标题,不再打开对话框 ([#9280](https://github.com/getpaseo/paseo/pull/9280))
- “更新内容”和网站更新日志改为先显示每个版本的亮点,完整列表收在“显示全部变更”之后 ([#9281](https://github.com/getpaseo/paseo/pull/9281))
- “更新内容”先显示亮点,完整列表收在“显示全部变更”之后 ([#9281](https://github.com/getpaseo/paseo/pull/9281))
- Claude Bypass 现在批准来自 ask 规则和钩子的执行请求,提问和计划审核仍保留交互 ([#9760](https://github.com/getpaseo/paseo/pull/9760))
- Claude 权限卡片现在显示 Provider 提供的原因 ([#3950](https://github.com/getpaseo/paseo/pull/3950),贡献者:[@codebutler](https://github.com/codebutler))
- PR 窗格中的“活动”可调整大小或折叠,为检查结果留出更多空间 ([#9656](https://github.com/getpaseo/paseo/pull/9656))
- macOS 桌面端的标签页切换快捷键改为 Cmd+Shift+[ 和 Cmd+Shift+] ([#7692](https://github.com/getpaseo/paseo/pull/7692),贡献者:[@jtomaszewski](https://github.com/jtomaszewski))
- 在“新建工作区”按 Cmd/Ctrl+N 会打开项目选择器,同时保留草稿 ([#9741](https://github.com/getpaseo/paseo/pull/9741))
- 移动端设置导航现在恢复侧边栏之前的位置 ([#9641](https://github.com/getpaseo/paseo/pull/9641))
### 修复
- 修复较长的工具详情隐藏折叠标题或无法滚动查看输出的问题 ([#9770](https://github.com/getpaseo/paseo/pull/9770))
- 修复图片预览加载时短暂显示错误或拉伸图片的问题 ([#9698](https://github.com/getpaseo/paseo/pull/9698))
- 修复网页端和桌面端聊天在较早历史记录进入虚拟化后跳到开头的问题 ([#9664](https://github.com/getpaseo/paseo/pull/9664),贡献者:[@luoph](https://github.com/luoph))
- 修复滚动到顶部后仍需再次滚动鼠标滚轮才能加载更早聊天记录的问题 ([#9570](https://github.com/getpaseo/paseo/pull/9570))
- 修复跨越部分代码块复制选区时丢失缩进和换行的问题 ([#9515](https://github.com/getpaseo/paseo/pull/9515),贡献者:[@michaelmwu](https://github.com/michaelmwu))
- 修复 Mermaid XY 图表的轴标题重叠和标签被裁切的问题 ([#9483](https://github.com/getpaseo/paseo/pull/9483),贡献者:[@FluidXin](https://github.com/FluidXin))
- 修复 iOS 上点击命令后命令菜单仍保持打开的问题 ([#9755](https://github.com/getpaseo/paseo/pull/9755))
- 修复 Agent 启动失败后无法重试已编辑草稿的问题 ([#9534](https://github.com/getpaseo/paseo/pull/9534),贡献者:[@michaelmwu](https://github.com/michaelmwu))
- 修复 Android 平板上模型配置按钮不响应点按的问题 ([#9526](https://github.com/getpaseo/paseo/pull/9526),贡献者:[@moevis](https://github.com/moevis))
- 修复更改外观后设置页面丢失滚动位置和编辑内容的问题 ([#9605](https://github.com/getpaseo/paseo/pull/9605))
- 修复浅色插件主题中选中行难以阅读、Pure Black 中高亮几乎不可见的问题 ([#9579](https://github.com/getpaseo/paseo/pull/9579),贡献者:[@nathansgreen](https://github.com/nathansgreen))
- 修复网页端和桌面端页眉及工具栏图标按钮缺少键盘焦点框的问题 ([#9745](https://github.com/getpaseo/paseo/pull/9745),贡献者:[@junjzhang](https://github.com/junjzhang))
- 修复 iOS 和 Android 上拖动后侧边栏行短暂出现在错误位置的问题 ([#9681](https://github.com/getpaseo/paseo/pull/9681))
- 修复桌面端在 daemon 仍启动时报告启动失败的问题 ([#9043](https://github.com/getpaseo/paseo/pull/9043),贡献者:[@magiclaw](https://github.com/magiclaw))
- 修复网页端和桌面端终端恢复画面时丢失输入字符的问题 ([#9533](https://github.com/getpaseo/paseo/pull/9533))
- 修复 Android 终端中实体方向键失效并丢失下一个输入字符的问题 ([#9407](https://github.com/getpaseo/paseo/pull/9407),贡献者:[@moevis](https://github.com/moevis))
- 修复非 Git 工作区在命令中心缺少“归档工作区”的问题 ([#9777](https://github.com/getpaseo/paseo/pull/9777),贡献者:[@andheiberg](https://github.com/andheiberg))
- 修复后续配置读取超时后工作区脚本消失的问题 ([#9477](https://github.com/getpaseo/paseo/pull/9477),贡献者:[@dinhphieu](https://github.com/dinhphieu))
- 修复账号用量刷新失败后侧边栏用量隐藏该账号的问题 ([#9594](https://github.com/getpaseo/paseo/pull/9594))
- 修复 Provider 会话已不存在时,已关闭 Agent 仍保持未读的问题 ([#9737](https://github.com/getpaseo/paseo/pull/9737),贡献者:[@luoph](https://github.com/luoph))
- 修复 Agent 自主运行一轮后完成通知显示旧回复的问题 ([#9793](https://github.com/getpaseo/paseo/pull/9793))
- 修复中断消息因“already has an active run”而失败的问题 ([#9537](https://github.com/getpaseo/paseo/pull/9537),贡献者:[@michaelmwu](https://github.com/michaelmwu))
- 修复消息在交给 Provider 前失败后无法重试的问题 ([#9580](https://github.com/getpaseo/paseo/pull/9580),贡献者:[@tmad4000](https://github.com/tmad4000))
- 修复刚重新打开的 Agent 在下一次空闲清理时失去 Provider 进程的问题 ([#8857](https://github.com/getpaseo/paseo/pull/8857),贡献者:[@fdkevin0](https://github.com/fdkevin0))
- 修复空闲运行时清理导致 Claude 会话 cron 和 /loop 唤醒丢失的问题 ([#9744](https://github.com/getpaseo/paseo/pull/9744),贡献者:[@KronixDev](https://github.com/KronixDev))
- 修复工具在回复之前开始、之后结束时无法从该回复分叉的问题 ([#9627](https://github.com/getpaseo/paseo/pull/9627),贡献者:[@ragokan](https://github.com/ragokan))
- 修复大型 Codex 历史页面在单个条目仍符合大小限制时阻断历史加载的问题 ([#9432](https://github.com/getpaseo/paseo/pull/9432),贡献者:[@RockStone](https://github.com/RockStone))
- 修复 OpenCode 使用 Bun 时,daemon 重启后会话无法重新连接的问题 ([#9653](https://github.com/getpaseo/paseo/pull/9653),贡献者:[@quickwind](https://github.com/quickwind))
- 修复 OpenCode 升级到 v2 后刷新 Provider 仍保留 v1 的问题 ([#9593](https://github.com/getpaseo/paseo/pull/9593),贡献者:[@tkfka1](https://github.com/tkfka1))
- 修复 OpenCode v2 无法发现仅对其会话可用的插件工具的问题 ([#9426](https://github.com/getpaseo/paseo/pull/9426),贡献者:[@dptsolutions](https://github.com/dptsolutions))
- 修复 ACP Provider 按模型提供思考等级时,模型共用错误等级的问题 ([#9717](https://github.com/getpaseo/paseo/pull/9717),贡献者:[@AlfredRR](https://github.com/AlfredRR), [@doskoi](https://github.com/doskoi))
- 修复没有输出的失败 ACP 工具阻止对话历史加载的问题 ([#9467](https://github.com/getpaseo/paseo/pull/9467),贡献者:[@Myasuka](https://github.com/Myasuka))
- 修复带有 null 可选参数的 Pi 和 OMP 工具调用显示为未知工具的问题 ([#9506](https://github.com/getpaseo/paseo/pull/9506),贡献者:[@papag00se](https://github.com/papag00se))
- 修复导入 OMP 会话时保存文件路径而非会话 ID 的问题 ([#8854](https://github.com/getpaseo/paseo/pull/8854),贡献者:[@LiebeLee](https://github.com/LiebeLee))
- 修复跨主机子 Agent 与调用者使用相同 Provider 时丢失调用者模式的问题 ([#9512](https://github.com/getpaseo/paseo/pull/9512),贡献者:[@ortschun](https://github.com/ortschun))
- 修复插件子 Agent 在会话关闭时从失败或已取消变为已完成的问题 ([#8563](https://github.com/getpaseo/paseo/pull/8563),贡献者:[@hadan8977](https://github.com/hadan8977))
- 修复完整 Agent ID 不存在时,CLI 命令误操作标题与该 ID 相同的其他 Agent 的问题 ([#9680](https://github.com/getpaseo/paseo/pull/9680), [#9731](https://github.com/getpaseo/paseo/pull/9731),贡献者:[@ese111](https://github.com/ese111))
- 修复无法归档、分离或重新加载未出现在 CLI 列表中的 Agent 的问题 ([#9726](https://github.com/getpaseo/paseo/pull/9726),贡献者:[@xunWhale](https://github.com/xunWhale))
- 修复 `paseo agent wait` 在没有 Agent 匹配 ID 时仍成功退出的问题 ([#9782](https://github.com/getpaseo/paseo/pull/9782),贡献者:[@Eapp1e](https://github.com/Eapp1e))
- 修复语音输入和输出都使用 OpenAI 时无法启动语音模式的问题 ([#9779](https://github.com/getpaseo/paseo/pull/9779),贡献者:[@Huyvux12](https://github.com/Huyvux12))
- 修复听写流错误被 30 秒交付超时掩盖的问题 ([#9784](https://github.com/getpaseo/paseo/pull/9784),贡献者:[@tieo](https://github.com/tieo))
- 修复插件 Provider 在 All 模式下拒绝 Review 附件的问题 ([#9590](https://github.com/getpaseo/paseo/pull/9590),贡献者:[@ese111](https://github.com/ese111))
- 修复插件时间线写入接受应用无法显示的类型的问题 ([#7677](https://github.com/getpaseo/paseo/pull/7677),贡献者:[@ragokan](https://github.com/ragokan))
- 修复一轮结束时聊天位置移动的问题 ([#8944](https://github.com/getpaseo/paseo/pull/8944), [#9175](https://github.com/getpaseo/paseo/pull/9175))
- 修复 Claude 和 OpenCode 工具行随参数到达而更改标题和图标的问题 ([#9248](https://github.com/getpaseo/paseo/pull/9248))
- 修复用量加载前上下文窗口浮层提前打开的问题 ([#9212](https://github.com/getpaseo/paseo/pull/9212))
- 修复多个侧边栏悬停卡片同时打开的问题 ([#9071](https://github.com/getpaseo/paseo/pull/9071))
- 修复 Agent 在你离开期间完成后,返回聊天时工作指示器消失的问题 ([#9170](https://github.com/getpaseo/paseo/pull/9170))
- 修复包含较短折叠轮次的聊天打开时留有空白、需滚动后才填满的问题 ([#8358](https://github.com/getpaseo/paseo/pull/8358), [#9083](https://github.com/getpaseo/paseo/pull/9083))
- 修复空闲的 Claude、Codex 或 OpenCode Agent 恢复后,“折叠轮次”把较早的回复藏进后一轮摘要行的问题 ([#9098](https://github.com/getpaseo/paseo/pull/9098))
- 修复提示词与其下方的回复或折叠轮次摘要行之间缺少间距的问题 ([#9009](https://github.com/getpaseo/paseo/pull/9009))
- 修复聊天打开时,较长的用户消息有一帧不显示渐隐效果和“展开”的问题 ([#9302](https://github.com/getpaseo/paseo/pull/9302))
- 修复紧跟在段落之后、中间没有空行的 Markdown 表格显示为原始竖线的问题 ([#8485](https://github.com/getpaseo/paseo/pull/8485),贡献者:[@ragokan](https://github.com/ragokan)、[@suk-6](https://github.com/suk-6)、[@thsrite](https://github.com/thsrite))
- 修复网页版和桌面端中与文字同行的带链接徽章图片被渲染成整行宽度的问题 ([#8530](https://github.com/getpaseo/paseo/pull/8530))
- 修复“查看源码”后点击“查看图表”会打开全屏、而不是回到内联 Mermaid 图表的问题 ([#8932](https://github.com/getpaseo/paseo/pull/8932),贡献者:[@luoph](https://github.com/luoph))
@@ -47,21 +104,16 @@
- 修复关闭 Agent 标签页时未发送的 Composer 文本和附件被删除的问题 ([#9079](https://github.com/getpaseo/paseo/pull/9079))
- 修复向 Composer 粘贴带超链接的文本时丢失链接地址的问题;链接现在以 Markdown 形式粘贴 ([#8972](https://github.com/getpaseo/paseo/pull/8972))
- 修复用鼠标点击“发送”后 Composer 失去焦点的问题 ([#9015](https://github.com/getpaseo/paseo/pull/9015))
- 修复 iPhone 上 Composer 停在距底部边缘 50pt 处的问题 ([#8823](https://github.com/getpaseo/paseo/pull/8823),贡献者:[@zeyugao](https://github.com/zeyugao))
- 修复从侧边栏和“新建工作区”点击“添加主机”会跳转到“设置”的问题 ([#8512](https://github.com/getpaseo/paseo/pull/8512))
- 修复打开失败的 Agent 或选择 Mark as read 后,其红点和“失败”分组仍留在侧边栏的问题 ([#8831](https://github.com/getpaseo/paseo/pull/8831))
- 修复在 Agent 运行时已关闭的情况下清除未读后,工作区的未读指示仍然亮着的问题 ([#9087](https://github.com/getpaseo/paseo/pull/9087))
- 修复取消归档工作区时未恢复随之归档的 Agent 的问题 ([#9210](https://github.com/getpaseo/paseo/pull/9210))
- 修复流式回复期间聊天一滚动上下文窗口浮层就自行关闭的问题 ([#8742](https://github.com/getpaseo/paseo/pull/8742),贡献者:[@3ae3ae](https://github.com/3ae3ae))
- 修复侧边栏用量摘要只在打开“使用情况”时才更新的问题 ([#7806](https://github.com/getpaseo/paseo/pull/7806),贡献者:[@ragokan](https://github.com/ragokan))
- 修复 Android 上位于触发元素上方的提示和菜单在打开后内容变多时短暂盖住触发元素的问题 ([#9247](https://github.com/getpaseo/paseo/pull/9247))
- 修复在“历史”页面刷新网页版后显示“无法加载历史”的问题 ([#9029](https://github.com/getpaseo/paseo/pull/9029))
- 修复 HTML 文件预览中的章节链接把预览替换成 Paseo 应用、而不是在文件内滚动的问题 ([#8559](https://github.com/getpaseo/paseo/pull/8559),贡献者:[@3ae3ae](https://github.com/3ae3ae))
- 修复“文件”刷新期间文件夹处于折叠状态时,新建的文件一直不显示的问题 ([#8582](https://github.com/getpaseo/paseo/pull/8582),贡献者:[@hadan8977](https://github.com/hadan8977))
- 修复分支仍在加载或请求失败时,分支切换器显示“没有找到分支。”的问题 ([#8938](https://github.com/getpaseo/paseo/pull/8938))
- 修复文件被移到上一级目录时,提交历史显示双斜杠、没有重命名状态也没有 diff 的问题 ([#8509](https://github.com/getpaseo/paseo/pull/8509),贡献者:[@hadan8977](https://github.com/hadan8977))
- 修复检出落后于 PR 头部时,已合并的 PR 从其工作区中消失的问题
- 修复工作区 Git 监视器在设置超时后一直停留在回退轮询的问题
- 修复网页版或桌面端重连后,被放弃的连接最多保持打开 45 秒的问题 ([#9067](https://github.com/getpaseo/paseo/pull/9067))
- 修复通过另一台主机路由的连接在获取超大时间线时以“The receiving client cannot keep up with host output”关闭的问题 ([#9109](https://github.com/getpaseo/paseo/pull/9109))
- 修复已连接的主机在更新到受支持的版本后仍停留在错误状态的问题 ([#8423](https://github.com/getpaseo/paseo/pull/8423),贡献者:[@DAnaeto](https://github.com/DAnaeto))
@@ -123,16 +175,21 @@
- 修复 daemon 因无效消息终止插件后,该插件仍留在列表中且未报告退出的问题 ([#9285](https://github.com/getpaseo/paseo/pull/9285),贡献者:[@Brandon168](https://github.com/Brandon168))
- 修复 ACP Provider 插件丢弃 Agent 在提示词响应中报告的 token 用量的问题 ([#9396](https://github.com/getpaseo/paseo/pull/9396),贡献者:[@Myasuka](https://github.com/Myasuka))
- 修复已发布的 `@getpaseo/*` npm 包未声明许可证的问题;现在声明为 Apache-2.0 ([#7816](https://github.com/getpaseo/paseo/pull/7816),贡献者:[@mdlawson](https://github.com/mdlawson)、[@ragokan](https://github.com/ragokan))
- 修复插件更新了自己的某张时间线卡片后,从较早的回复分叉因“This checkpoint changed after it was created”失败的问题 ([#8746](https://github.com/getpaseo/paseo/pull/8746),贡献者:[@monarchmaisuriya](https://github.com/monarchmaisuriya))
- 修复由插件渲染最终回复时,“折叠轮次”让轮次保持展开或折叠到较早回复的问题 ([#8811](https://github.com/getpaseo/paseo/pull/8811),贡献者:[@geoqiao](https://github.com/geoqiao))
- 修复应用刷新后插件目录仍在加载时,插件页面显示“This plugin surface is unavailable”的问题 ([#8123](https://github.com/getpaseo/paseo/pull/8123),贡献者:[@vs-tahir](https://github.com/vs-tahir))
- 修复插件添加了许多导航项时,矮屏上的工作区列表被挤出移动端侧边栏的问题 ([#8727](https://github.com/getpaseo/paseo/pull/8727),贡献者:[@jaredwang](https://github.com/jaredwang))
- 修复时间线插件在 Agent 消息工具调用上收不到发送方、事件和原始文本的问题 ([#8492](https://github.com/getpaseo/paseo/pull/8492),贡献者:[@RRD-dev](https://github.com/RRD-dev)、[@luoph](https://github.com/luoph))
- 修复输入或输出 schema 使用 transform 时插件 RPC 失败的问题 ([#8550](https://github.com/getpaseo/paseo/pull/8550))
### 破坏性变更
- 移除已弃用且始终返回空列表的 `agent.turn.after.timeline` SDK 字段 ([#9573](https://github.com/getpaseo/paseo/pull/9573),贡献者:[@jtomaszewski](https://github.com/jtomaszewski))
### 说明
- 后台任务、基准分支选择器、归档撤销、后台 Agent、插件订阅和 fx 需要主机和应用都更新到此版本
- 使用插件库、后台任务、Change base、归档撤销、后台 Agent、插件订阅和 fx 时,请同时更新主机和应用
- 读取 `agent.turn.after.timeline` 的插件作者必须改用 `timeline.refetch({ direction: "tail", limit: 1, wholeTurns: true })`,并按 `event.turnId` 筛选条目
- 归档撤销会恢复工作区,但不会恢复随 worktree 一起移除的未提交文件
## 0.15.4 - 2026-11-10
+3 -2
View File
@@ -150,12 +150,13 @@ Users can also detach an existing subagent from the subagents track. Detach is d
`notifyOnFinish` defaults to `true` for agent-scoped creation and prompt follow-ups because most delegated work needs to report back to the creating agent. Set it to `false` for explicit reporting or no completion callback.
Agent-originated messages and automatic notifications share a recipient-daemon delivery module. A queued receipt acknowledges admission before provider dispatch, allowing a child to report and finish in the same two-second quiet window. Human prompts dispatch directly. Conflicting explicit interruption or session-mode choices retain separate ordered dispatches.
Agent-originated messages and automatic notifications share a recipient-daemon delivery module. A queued receipt acknowledges admission before provider dispatch. Idle recipients retain the two-second quiet window. While a recipient has a running or starting turn (including compaction), messages stay queued across quiet windows and are delivered together after that turn settles, including failure or cancellation. A ready batch is released when the daemon observes the recipient settle; the two-second timer also retries it. Agent callers using `steer`, including the default, wait for the turn to end; only explicit `interrupt` replaces a running turn. An explicit interrupt or a command the provider accepts out of band runs before earlier queued messages. Those messages stay queued and are delivered after the running or replacement turn ends. Human prompts dispatch directly with their existing behavior. Conflicting session-mode choices retain separate ordered dispatches.
The pending message window is in memory. Clean shutdown flushes it before closing agents; an abrupt
crash can lose queued prompts. A durable send receipt remains pending until actual dispatch
acknowledgment, so a lost window never becomes a completed receipt. Completion waits cover queued
admission within their original timeout and cancellation scope.
admission within their original timeout and cancellation scope, and return permission checkpoints
while messages are waiting.
Finish notification intent has a separate daemon-owned lifetime. The finish-subscriptions module
persists caller, child, host, and ownership policy through an injectable store; its JSON adapter uses
+10
View File
@@ -590,6 +590,16 @@ bookkeeping may scan opaque row sizes during a deferred write, never during host
before a requested cache row can paint. The row store is not encrypted. A cached timeline can contain
source code, prompts, and tool output; encrypted-at-rest storage is a separate security decision.
### Saved hosts
**AsyncStorage key:** `@paseo:daemon-registry`, an array of host profiles.
Every app build on a device shares this key, including an older build after a downgrade and a newer
one that saves a connection kind this build doesn't know. The key holds every saved host and its
password, so never remove it. Read each host and connection on its own, skip the ones this build
can't read, and write them back on every save. A value that isn't a JSON array is copied to
`@paseo:daemon-registry:unreadable` before the next save overwrites it.
### Draft Store
**AsyncStorage key:** `paseo-drafts` (version 2)
+1 -1
View File
@@ -6,7 +6,7 @@ Do not replace the Linux implementation with `fs.watch({ recursive: true })`. No
Closing an observation must remain safe after its root is renamed or removed. Workspace archive removes owned worktrees while releasing observation references, so teardown cannot assume the watched path still exists.
`unsubscribe()` is an awaited barrier. Once it resolves, no scan, reconciliation, queued event, native handle, or callback may remain. `updateIgnore()` is the equivalent barrier for excluded paths: events queued below a newly excluded root cannot be delivered after it resolves. Treat path disappearance while scanning, attaching, or receiving a watcher error as rename/archive churn. Surface permission and resource errors so WorkspaceGit can enter bounded polling.
`unsubscribe()` is an awaited barrier. Once it resolves, no scan, reconciliation, queued event, native handle, or callback may remain. `updateIgnore()` is the equivalent barrier for excluded paths: events queued below a newly excluded root cannot be delivered after it resolves. Treat path disappearance while scanning, attaching, or receiving a watcher error as rename/archive churn. Surface permission and resource errors so WorkspaceGit can enter bounded polling. `subscribe()` accepts an abort signal; aborting it before it resolves stops the startup scan and rejects. WorkspaceGit aborts every subscription that misses its setup deadline, because an abandoned scan otherwise keeps walking the tree. A timed-out directory retries on the recovery ladder (30 seconds doubling to five minutes), and each consecutive timeout keeps doubling the delay up to one hour. Under sustained CPU load the next scan misses the deadline too, and each attempt repeats the full scan. An accepted subscription resets the timeout streak. Degraded polling keeps its own cadence throughout.
Linux topology repair is trailing-debounced and scoped to the renamed path. A file rename needs one classification stat; a new or moved directory scans only its subtree. Full-tree scans are reserved for startup and ignore-set replacement. A subscription reports changes after `subscribe()` resolves, not the files that already existed. macOS FSEvents can still replay writes made moments before the stream started. Consumers read their initial state after `subscribe()` resolves; WorkspaceGit re-reads its checkout once observation setup completes, because its first refresh runs in parallel with setup. The Linux startup scan therefore emits nothing; only a scoped reconciliation of new topology reports files found before their directory's watcher was installed. Startup creates made every cold diff compute and discard a first revision. Benchmark startup cost with pre-populated trees.
+19 -6
View File
@@ -97,12 +97,25 @@ Register the adapter in `defaultForgeRegistry` with:
- `matchesHost` from manifest `cloudHosts`
- `probeHost` when self-hosted/Enterprise detection is supported
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
observed open-to-merged transition and a fresh exact match between checkout HEAD
and the PR head, along with the existing workspace safety checks.
Current change-request lookup prefers an open request for the branch and repository.
A closed or merged request belongs to a workspace only when its checkout commit
is in the forge's PR/MR commit list. Commits inherited from the base do not count.
Display and auto-archive share this rule, preserving squash-merged requests and
requests updated remotely while rejecting a fresh workspace on their base commit.
A rewritten or newly advanced checkout no longer matches the terminal request.
Commit membership stays in the server snapshot; clients receive the selected
request without its commit list. Archive uses that same evidence after refreshing
the workspace. It still requires an observed open-to-merged transition and the
workspace safety checks; being behind alone does not block it.
Containment spawns no Git commands and fetches no Git objects. GitHub loads only terminal
commit IDs in a separate batch under the same rate budget, newest page first,
and remembers pages by PR head. Open requests need no membership read. GitLab,
Gitea, and legacy GitHub cache successful terminal commit lists by request head;
failed reads stay retryable and reject the lookup, preserving its previous snapshot. A failed
GitHub commit batch does not block workspaces whose status is already complete.
Missing membership evidence leaves the workspace active.
Keep checkout HEAD in adapter cache and poll identities so checkout changes
refresh the facts used by archive eligibility.
+1
View File
@@ -29,6 +29,7 @@ The worker writes `$PASEO_HOME/terminal-worker/<pid>.json` (owner-only) with its
- Workers never query their own birth time or command line. Readers accept legacy identity fields but ignore them. Daemons through 0.15.1 report new records unreadable and cannot adopt them.
- Windows terminal programs have no recorded birth time and terminal lifecycle operations never launch PowerShell. Linux and macOS retain program birth-time checks through `ps` with `LC_ALL=C`; Linux also walks sessions to find surviving jobs.
- Unix socket paths have a byte budget (103 on macOS, 107 on Linux). Long dev homes use an owner-only fallback under `$TMPDIR/paseo-<uid>/` or `/tmp/paseo-<uid>/`. An existing directory must be a real `0700` directory owned by you; a shared root is never chmodded.
- A home on a filesystem that refuses Unix sockets (AFS, some network mounts) passes those checks and then fails the bind with `EPERM`, `EACCES`, `EOPNOTSUPP` or `ENOTSUP`. The worker moves on to the next directory on those codes only; any other listen error fails the start. The record carries the path the worker bound, so nothing else recomputes it.
- A kill cleanup that cannot confirm every process gone writes `closing-<recordId>.json` beside the worker record. The worker rewrites its own record whenever a terminal starts or exits, so the kill intent has to live in a file it never writes. A closing record is never adopted; the next stop or start retries it.
- An unreadable record of either kind makes `daemon status` and a kill restart fail with its path: a kill cleanup that met it could not check what it names, and leaves nothing else behind. A read that fails with `EPERM`, `EBUSY` or `EACCES` is retried for 250ms first: on Windows, opening a record while the worker renames its new copy over it fails that way for a moment.
@@ -0,0 +1,5 @@
- Background tasks: See and stop background tasks above the composer for Claude Code, Codex and OpenCode v2.
- Built-in plugin gallery: Browse, search and install plugins without leaving Paseo. Manage their settings and updates from the same page.
- Command center tabs: Switch between Workspaces, Files and Actions, with recent workspaces shown first. Search now includes archived workspaces and matches agent titles within their workspace.
Full notes: https://paseo.sh/changelog
@@ -0,0 +1,5 @@
- Background tasks: See and stop background tasks above the composer for Claude Code, Codex and OpenCode v2.
- Built-in plugin gallery: Browse, search and install plugins without leaving Paseo. Manage their settings and updates from the same page.
- Command center tabs: Switch between Workspaces, Files and Actions, with recent workspaces shown first. Search now includes archived workspaces and matches agent titles within their workspace.
Full notes: https://paseo.sh/changelog
@@ -0,0 +1,5 @@
- Background tasks: See and stop background tasks above the composer for Claude Code, Codex and OpenCode v2.
- Built-in plugin gallery: Browse, search and install plugins without leaving Paseo. Manage their settings and updates from the same page.
- Command center tabs: Switch between Workspaces, Files and Actions, with recent workspaces shown first. Search now includes archived workspaces and matches agent titles within their workspace.
Full notes: https://paseo.sh/changelog
@@ -0,0 +1,5 @@
- Background tasks: See and stop background tasks above the composer for Claude Code, Codex and OpenCode v2.
- Built-in plugin gallery: Browse, search and install plugins without leaving Paseo. Manage their settings and updates from the same page.
- Command center tabs: Switch between Workspaces, Files and Actions, with recent workspaces shown first. Search now includes archived workspaces and matches agent titles within their workspace.
Full notes: https://paseo.sh/changelog
+1 -1
View File
@@ -1 +1 @@
sha256-e6BNeOJvy1uyDe/XW9hdr7NBgJ+t9tlNum5oLNefREI=
sha256-alhf4ULeJ7n8sfgnxsX8Ugw40GB7jz0u9R/3/MOveIw=
+28 -28
View File
@@ -1,12 +1,12 @@
{
"name": "paseo",
"version": "0.16.0-beta.2",
"version": "0.16.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "paseo",
"version": "0.16.0-beta.2",
"version": "0.16.0",
"hasInstallScript": true,
"license": "Apache-2.0",
"workspaces": [
@@ -37468,7 +37468,7 @@
},
"packages/app": {
"name": "@getpaseo/app",
"version": "0.16.0-beta.2",
"version": "0.16.0",
"dependencies": {
"@codemirror/commands": "6.10.4",
"@codemirror/language": "6.12.4",
@@ -39637,13 +39637,13 @@
},
"packages/cli": {
"name": "@getpaseo/cli",
"version": "0.16.0-beta.2",
"version": "0.16.0",
"license": "Apache-2.0",
"dependencies": {
"@clack/prompts": "^1.0.0",
"@getpaseo/client": "0.16.0-beta.2",
"@getpaseo/protocol": "0.16.0-beta.2",
"@getpaseo/server": "0.16.0-beta.2",
"@getpaseo/client": "0.16.0",
"@getpaseo/protocol": "0.16.0",
"@getpaseo/server": "0.16.0",
"chalk": "^5.3.0",
"commander": "^12.0.0",
"mime-types": "^2.1.35",
@@ -39890,11 +39890,11 @@
},
"packages/client": {
"name": "@getpaseo/client",
"version": "0.16.0-beta.2",
"version": "0.16.0",
"license": "Apache-2.0",
"dependencies": {
"@getpaseo/protocol": "0.16.0-beta.2",
"@getpaseo/relay": "0.16.0-beta.2",
"@getpaseo/protocol": "0.16.0",
"@getpaseo/relay": "0.16.0",
"ws": "^8.20.0",
"zod": "^4.4.3"
},
@@ -39906,7 +39906,7 @@
},
"packages/desktop": {
"name": "@getpaseo/desktop",
"version": "0.16.0-beta.2",
"version": "0.16.0",
"license": "Apache-2.0",
"dependencies": {
"@getpaseo/cli": "*",
@@ -40149,7 +40149,7 @@
},
"packages/expo-two-way-audio": {
"name": "@getpaseo/expo-two-way-audio",
"version": "0.16.0-beta.2",
"version": "0.16.0",
"license": "MIT",
"devDependencies": {
"@types/jest": "^29.5.14",
@@ -40195,7 +40195,7 @@
},
"packages/highlight": {
"name": "@getpaseo/highlight",
"version": "0.16.0-beta.2",
"version": "0.16.0",
"license": "Apache-2.0",
"dependencies": {
"@codemirror/language": "6.12.4",
@@ -40225,7 +40225,7 @@
},
"packages/plugin": {
"name": "@getpaseo/plugin",
"version": "0.16.0-beta.2",
"version": "0.16.0",
"license": "Apache-2.0",
"dependencies": {
"@agentclientprotocol/sdk": "^1.4.0",
@@ -40233,8 +40233,8 @@
"use-sync-external-store": "^1.6.0"
},
"devDependencies": {
"@getpaseo/client": "0.16.0-beta.2",
"@getpaseo/protocol": "0.16.0-beta.2",
"@getpaseo/client": "0.16.0",
"@getpaseo/protocol": "0.16.0",
"@types/node": "^20.9.0",
"@types/react": "~19.2.0",
"react": "19.2.3",
@@ -40244,8 +40244,8 @@
"zod": "^4.4.3"
},
"peerDependencies": {
"@getpaseo/client": "0.16.0-beta.2",
"@getpaseo/protocol": "0.16.0-beta.2",
"@getpaseo/client": "0.16.0",
"@getpaseo/protocol": "0.16.0",
"react": ">=19.1.0 <20",
"react-native": ">=0.81.5",
"zod": "^4.4.3"
@@ -40267,7 +40267,7 @@
},
"packages/protocol": {
"name": "@getpaseo/protocol",
"version": "0.16.0-beta.2",
"version": "0.16.0",
"license": "Apache-2.0",
"dependencies": {
"semver": "^7.8.5",
@@ -40295,7 +40295,7 @@
},
"packages/relay": {
"name": "@getpaseo/relay",
"version": "0.16.0-beta.2",
"version": "0.16.0",
"license": "Apache-2.0",
"dependencies": {
"@noble/ciphers": "^2.4.0",
@@ -40517,17 +40517,17 @@
},
"packages/server": {
"name": "@getpaseo/server",
"version": "0.16.0-beta.2",
"version": "0.16.0",
"license": "Apache-2.0",
"dependencies": {
"@agentclientprotocol/sdk": "^0.17.1",
"@anthropic-ai/claude-agent-sdk": "0.3.246",
"@anthropic-ai/sdk": "^0.104.2",
"@getpaseo/client": "0.16.0-beta.2",
"@getpaseo/highlight": "0.16.0-beta.2",
"@getpaseo/plugin": "0.16.0-beta.2",
"@getpaseo/protocol": "0.16.0-beta.2",
"@getpaseo/relay": "0.16.0-beta.2",
"@getpaseo/client": "0.16.0",
"@getpaseo/highlight": "0.16.0",
"@getpaseo/plugin": "0.16.0",
"@getpaseo/protocol": "0.16.0",
"@getpaseo/relay": "0.16.0",
"@isaacs/ttlcache": "^2.1.4",
"@modelcontextprotocol/sdk": "1.29.0",
"@opencode-ai/sdk": "1.14.46",
@@ -41474,7 +41474,7 @@
},
"packages/website": {
"name": "@getpaseo/website",
"version": "0.16.0-beta.2",
"version": "0.16.0",
"dependencies": {
"@cloudflare/vite-plugin": "^1.29.1",
"@cloudflare/workers-types": "^4.20260317.1",
@@ -43084,7 +43084,7 @@
},
"plugins": {
"name": "@getpaseo/builtin-plugins",
"version": "0.16.0-beta.2",
"version": "0.16.0",
"dependencies": {
"@getpaseo/plugin": "*",
"zod": "^4.4.3"
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "paseo",
"version": "0.16.0-beta.2",
"version": "0.16.0",
"private": true,
"description": "Paseo: voice-controlled development environment for local AI coding agents",
"keywords": [
@@ -2,10 +2,16 @@ import { copyPluginExample } from "../support/helpers/plugin-fixture";
import { expect, test as base, type Page } from "../support/fixtures";
import { gotoAppShell } from "../support/helpers/app";
import { connectNewWorkspaceDaemonClient } from "../support/helpers/new-workspace";
import { waitForSettledPosition } from "../support/helpers/sheet-layout";
async function openExample(page: Page, example: string) {
await page.getByRole("button", { name: `Open ${example}`, exact: true }).click();
await expect(page.getByText(`Modal example: ${example}`, { exact: true })).toBeVisible();
const title = page.getByText(`Modal example: ${example}`, { exact: true });
// A compact sheet holds below the viewport and then slides up, so a pointer placed before it
// stops lands on whatever slides under it. The settle check starts once the slide has begun;
// two equal reads during the hold would otherwise count as settled.
await expect(title).toBeInViewport();
await waitForSettledPosition(title);
}
async function closeExample(page: Page) {
@@ -208,6 +208,35 @@ test.describe("Plugin sidebar items", () => {
});
});
test("a short desktop sidebar keeps workspaces usable while navigation scrolls", async ({
page,
}) => {
await page.setViewportSize({ width: 1280, height: 480 });
await gotoAppShell(page);
await expect(botRow(page, "status")).toBeAttached();
const workspace = visibleTestId(page, `sidebar-workspace-row-${getServerId()}:${workspaceId}`);
await expect(workspace).toBeInViewport({ ratio: 1 });
await expect(botRow(page, "status")).not.toBeInViewport();
await test.step("navigation stays within half the sidebar", async () => {
const nav = await boxOf(visibleTestId(page, "sidebar-nav-scroll"));
expect(nav.height).toBeLessThanOrEqual(480 / 2 + 1);
});
await test.step("scrolling navigation reaches its last row without moving workspaces", async () => {
const before = await boxOf(workspace);
await visibleTestId(page, "sidebar-global-new-workspace").hover();
await page.mouse.wheel(0, 800);
await expect(botRow(page, "status")).toBeInViewport({ ratio: 1 });
await expect(workspace).toBeInViewport({ ratio: 1 });
expect((await boxOf(workspace)).y).toBe(before.y);
await qaScreenshot(page, "desktop-short-sidebar-nav-scrolled");
await botRow(page, "status").click();
await expect(page.getByText("Bot status details", { exact: true })).toBeVisible();
await page.getByRole("button", { name: "Close bot status", exact: true }).click();
});
});
test("a restored plugin screen waits for its catalog before rendering", async ({ page }) => {
await page.setViewportSize(WIDE);
await gotoWorkspace(page, workspaceId);
@@ -0,0 +1,106 @@
import { expect, type Page } from "@playwright/test";
import { test } from "../support/fixtures";
import { gotoAppShell, openSettings } from "../support/helpers/app";
import { renameHostFromSettings } from "../support/helpers/hosts";
import { getServerId } from "../support/helpers/server-id";
import { openHostSection, selectSettingsHost } from "../support/helpers/settings";
const REGISTRY_KEY = "@paseo:daemon-registry";
const SEED_NONCE_KEY = "@paseo:e2e-seed-nonce";
const DISABLE_DEFAULT_SEED_ONCE_KEY = "@paseo:e2e-disable-default-seed-once";
// What a build with a connection kind this one doesn't know leaves in the registry: an extra
// connection on a host this build can reach, and a host reached only through it.
const UNKNOWN_CONNECTION = { id: "future:garage", type: "futureKind", address: "garage" };
const UNKNOWN_HOST = {
serverId: "srv_e2e_unknown_connection_host",
label: "Unknown connection host",
connections: [{ id: "future:roof", type: "futureKind", address: "roof" }],
preferredConnectionId: "future:roof",
};
const OFFLINE_HOST = {
serverId: "srv_e2e_saved_offline_host",
label: "Saved offline host",
password: "e2e-fake-password",
connections: [{ id: "direct:127.0.0.1:59999", type: "directTcp", endpoint: "127.0.0.1:59999" }],
preferredConnectionId: "direct:127.0.0.1:59999",
};
interface StoredHost {
serverId: string;
label?: string;
password?: string;
connections: unknown[];
}
async function addUnreadableEntriesAndReload(page: Page): Promise<void> {
await page.evaluate(
({ keys, primaryServerId, unknownConnection, offlineHost, unknownHost }) => {
const nonce = localStorage.getItem(keys.nonce);
if (!nonce) {
throw new Error("Expected the e2e seed nonce before overriding the host registry.");
}
const registry: StoredHost[] = JSON.parse(localStorage.getItem(keys.registry) ?? "[]");
registry
.find((host) => host.serverId === primaryServerId)
?.connections.push(unknownConnection);
registry.push(offlineHost, unknownHost);
localStorage.setItem(keys.registry, JSON.stringify(registry));
localStorage.setItem(keys.disableSeedOnce, nonce);
},
{
keys: {
registry: REGISTRY_KEY,
nonce: SEED_NONCE_KEY,
disableSeedOnce: DISABLE_DEFAULT_SEED_ONCE_KEY,
},
primaryServerId: getServerId(),
unknownConnection: UNKNOWN_CONNECTION,
offlineHost: OFFLINE_HOST,
unknownHost: UNKNOWN_HOST,
},
);
await page.reload();
}
async function readStoredRegistry(page: Page): Promise<StoredHost[] | null> {
return page.evaluate((key) => JSON.parse(localStorage.getItem(key) ?? "null"), REGISTRY_KEY);
}
async function readStoredHost(page: Page, serverId: string): Promise<StoredHost | undefined> {
return (await readStoredRegistry(page))?.find((host) => host.serverId === serverId);
}
test("saved hosts survive a registry entry this build can't read, and saving keeps it", async ({
page,
}) => {
await gotoAppShell(page);
await addUnreadableEntriesAndReload(page);
await test.step("both readable hosts are listed", async () => {
await page.getByTestId("sidebar-hosts-trigger").click();
await expect(page.getByTestId(`sidebar-host-row-${getServerId()}`)).toBeVisible();
await expect(page.getByTestId(`sidebar-host-row-${OFFLINE_HOST.serverId}`)).toBeVisible();
await expect(page.getByTestId(`sidebar-host-row-${UNKNOWN_HOST.serverId}`)).toHaveCount(0);
await page.keyboard.press("Escape");
});
await test.step("renaming a host keeps its password and the entries it can't read", async () => {
await openSettings(page);
await selectSettingsHost(page, OFFLINE_HOST.serverId);
await openHostSection(page, OFFLINE_HOST.serverId, "host");
await renameHostFromSettings(page, "Renamed offline host");
await expect
.poll(() => readStoredHost(page, OFFLINE_HOST.serverId))
.toMatchObject({ label: "Renamed offline host", password: OFFLINE_HOST.password });
const stored = await readStoredRegistry(page);
expect(stored?.map((host) => host.serverId)).toEqual([
getServerId(),
OFFLINE_HOST.serverId,
UNKNOWN_HOST.serverId,
]);
expect(stored?.[0]?.connections).toContainEqual(UNKNOWN_CONNECTION);
expect(stored?.[2]).toEqual(UNKNOWN_HOST);
});
});
@@ -33,6 +33,8 @@ import {
expectNoHostPasswordControls,
removeHostFromHostPage,
addDirectHostFromSettings,
expectAddHostFieldDrawnAsInput,
selectHostConnectionType,
expectHostOnlineWithoutError,
expectIdleAgentRelease,
editRestartRecoveryPrompt,
@@ -307,6 +309,24 @@ async function closeAddHostAndChangeTheme(page: import("@playwright/test").Page)
await page.keyboard.press("Control+Alt+t");
}
test("Add host draws its text fields as bordered inputs", async ({ page }) => {
await gotoAppShell(page);
await test.step("the pairing link field", async () => {
await openSidebarAddHost(page);
await selectHostConnectionType(page, "relay");
await expectAddHostFieldDrawnAsInput(page, "pair-link-input");
await page.getByTestId("pair-link-cancel").click();
});
await test.step("the direct connection fields", async () => {
await selectHostConnectionType(page, "direct");
await expectAddHostFieldDrawnAsInput(page, "direct-host-input");
await expectAddHostFieldDrawnAsInput(page, "direct-port-input");
await expectAddHostFieldDrawnAsInput(page, "direct-password-input");
});
});
test("sidebar Add host completes without navigating", async ({ page }) => {
await gotoAppShell(page);
await expect(page).toHaveURL(/\/open-project$/);
@@ -110,6 +110,7 @@ test.describe("Sidebar items in Appearance settings", () => {
await test.step("the sidebar starts in the default order", async () => {
await expectSidebarOrder(page, ["new-workspace", "history", "search", "schedules"]);
await expect(page.locator('[data-testid="sidebar-nav-separator"]:visible')).toHaveCount(1);
});
await test.step("the Sidebar section lists every item in the same order", async () => {
@@ -195,6 +196,9 @@ test.describe("Sidebar items in Appearance settings", () => {
await expectSidebarItemHidden(page, "history");
await expectSidebarItemHidden(page, "search");
await expectSidebarItemHidden(page, "schedules");
// Nothing is left above the Workspaces section: no drag strip, no empty divider.
await expect(page.locator('[data-testid="sidebar-nav-drag-strip"]:visible')).toHaveCount(0);
await expect(page.locator('[data-testid="sidebar-nav-separator"]:visible')).toHaveCount(0);
});
});
@@ -73,35 +73,36 @@ function labelRow(page: import("@playwright/test").Page, name: string) {
return page.getByTestId(`workspace-label-picker-row-${name}`);
}
async function box(locator: import("@playwright/test").Locator) {
const measured = await locator.boundingBox();
if (!measured) throw new Error("expected a visible element to measure");
return measured;
}
async function size(locator: import("@playwright/test").Locator) {
await settled(locator);
const { width, height } = await box(locator);
const { width, height } = await settled(locator);
return { width, height };
}
/**
* Waits until an element stops moving.
* Waits until an element is on screen and stops moving, and returns where it settled.
*
* The flyout scales in and the sidebar behind it re-lays out as the filter changes, so a rail
* measured mid-animation is not a rail — and a measurement built from two `boundingBox()` calls
* would take its two halves from two different frames.
* would take its two halves from two different frames. A row that has not been laid out yet has
* no box at all; that is not settled either, so the poll keeps waiting instead of failing.
*/
async function settled(locator: import("@playwright/test").Locator) {
let previous = "";
const last: { box: Awaited<ReturnType<typeof locator.boundingBox>>; key: string | null } = {
box: null,
key: null,
};
await expect
.poll(async () => {
const current = JSON.stringify(await box(locator));
const stable = current === previous;
previous = current;
const current = await locator.boundingBox();
const key = current ? JSON.stringify(current) : null;
const stable = key !== null && key === last.key;
last.box = current;
last.key = key;
return stable;
})
.toBe(true);
if (!last.box) throw new Error("a settled element has a box");
return last.box;
}
async function expectAssigned(
@@ -6,7 +6,7 @@ import {
type ChildProcess,
type SpawnOptions,
} from "node:child_process";
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import net from "node:net";
import { tmpdir } from "node:os";
import path from "node:path";
@@ -59,7 +59,17 @@ export async function getAvailableHostDaemonPort(): Promise<number> {
return port;
}
async function waitForServer(port: number, child: ChildProcess): Promise<void> {
/**
* Resolves once this daemon answers on its port. An open TCP port is not
* enough: the port is released before the daemon binds it, and whatever takes
* it in between also accepts connections while the daemon exits with
* EADDRINUSE. Only the daemon's own status reports its server id.
*/
async function waitForServer(
port: number,
child: ChildProcess,
identity: { serverId: string; paseoHome: string },
): Promise<void> {
const deadline = Date.now() + 90_000;
let lastError: unknown = null;
@@ -70,22 +80,13 @@ async function waitForServer(port: number, child: ChildProcess): Promise<void> {
);
}
try {
await new Promise<void>((resolve, reject) => {
const socket = net.connect(port, "127.0.0.1", () => {
socket.end();
resolve();
});
socket.setTimeout(1_000, () => {
socket.destroy();
reject(new Error(`Connection timed out to isolated daemon port ${port}`));
});
socket.on("error", reject);
});
return;
const serverId = await readServerId(port, identity.paseoHome);
if (serverId === identity.serverId) return;
lastError = new Error(`Port ${port} is served by ${serverId}, not ${identity.serverId}`);
} catch (error) {
lastError = error;
await new Promise((resolve) => setTimeout(resolve, 100));
}
await new Promise((resolve) => setTimeout(resolve, 100));
}
throw new Error(
@@ -95,6 +96,25 @@ async function waitForServer(port: number, child: ChildProcess): Promise<void> {
);
}
/**
* Reads the server id from the daemon's status route. The route needs a bearer
* on a password-protected daemon; the daemon accepts the local credential it
* writes into its home before listening, as the CLI does for local status.
*/
async function readServerId(port: number, paseoHome: string): Promise<string> {
const localCredential = await readFile(path.join(paseoHome, "local-credential"), "utf8").then(
(token) => token.trim(),
() => null,
);
const response = await fetch(`http://127.0.0.1:${port}/api/status`, {
headers: localCredential ? { authorization: `Bearer ${localCredential}` } : {},
signal: AbortSignal.timeout(1_000),
});
if (!response.ok) throw new Error(`Status request to port ${port} returned ${response.status}`);
const status = (await response.json()) as { serverId?: unknown };
return String(status.serverId);
}
function withMutableRelay(
config: NonNullable<IsolatedHostDaemonOptions["config"]>,
relay: NonNullable<IsolatedHostDaemonOptions["mutableRelay"]>,
@@ -121,7 +141,7 @@ export async function startIsolatedHostDaemon(
serverId: string,
options: IsolatedHostDaemonOptions = {},
): Promise<IsolatedHostDaemon> {
const port = await getAvailableHostDaemonPort();
let port = await getAvailableHostDaemonPort();
const metroPort = process.env.E2E_METRO_PORT;
if (!metroPort) throw new Error("E2E_METRO_PORT is required to start an isolated host daemon");
@@ -221,7 +241,7 @@ export async function startIsolatedHostDaemon(
});
try {
await waitForServer(port, spawned);
await waitForServer(port, spawned, { serverId, paseoHome });
return spawned;
} catch (error) {
throw new Error(
@@ -231,8 +251,25 @@ export async function startIsolatedHostDaemon(
}
};
// The reserved port is released before the daemon binds it, so another
// process can take it in between. Only the first start picks a new port:
// restart() keeps the endpoint the app already knows.
const startOnFreePort = async (): Promise<void> => {
for (let attempt = 1; ; attempt += 1) {
try {
await spawnDaemon();
return;
} catch (error) {
const lostPort = error instanceof Error && error.message.includes("EADDRINUSE");
if (!lostPort || attempt === 3) throw error;
await stopDaemon();
port = await getAvailableHostDaemonPort();
}
}
};
try {
await spawnDaemon();
await startOnFreePort();
} catch (error) {
await stopDaemon();
if (!options.preserveHome) {
@@ -223,6 +223,14 @@ export async function addDirectHostFromSettings(
await expect(page.getByTestId("add-host-modal")).toHaveCount(0, { timeout: 30_000 });
}
export async function expectAddHostFieldDrawnAsInput(page: Page, testId: string): Promise<void> {
const field = page.getByTestId(testId);
await expect(field).toBeVisible();
await expect(field).toHaveCSS("border-top-width", "1px");
await expect(field).not.toHaveCSS("padding-left", "0px");
await expect(field).not.toHaveCSS("background-color", "rgba(0, 0, 0, 0)");
}
export async function toggleHostAdvanced(page: Page): Promise<void> {
await page.getByTestId("direct-host-advanced-toggle").click();
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/app",
"version": "0.16.0-beta.2",
"version": "0.16.0",
"private": true,
"main": "index.ts",
"scripts": {
@@ -17,6 +17,13 @@ import { isNative } from "@/constants/platform";
* On macOS, Electron handles edge resize natively.
*/
/**
* Marks a scroll viewport as window content: it and its descendants emit no window
* regions, because Electron does not clip app-region rects to scroll viewports.
* See the `[data-window-content]` rule in public/index.html.
*/
export const WINDOW_CONTENT_DATASET = { "window-content": "" };
export const titlebarDragSurfaceStyle: React.CSSProperties = {
cursor: "default",
// @ts-expect-error — WebkitAppRegion is not in CSSProperties
+89 -43
View File
@@ -9,7 +9,16 @@ import {
type LucideIcon,
} from "lucide-react-native";
import { useTranslation } from "react-i18next";
import { memo, useCallback, useEffect, useMemo, useRef, useState, type RefObject } from "react";
import {
memo,
useCallback,
useEffect,
useMemo,
useRef,
useState,
type ReactNode,
type RefObject,
} from "react";
import {
Pressable,
ScrollView,
@@ -19,12 +28,19 @@ import {
View,
type LayoutChangeEvent,
} from "react-native";
import { Gesture, ScrollView as GHScrollView } from "react-native-gesture-handler";
import {
Gesture,
type GestureType,
ScrollView as GHScrollView,
} from "react-native-gesture-handler";
import Animated, { runOnJS, useAnimatedStyle, useSharedValue } from "react-native-reanimated";
import { scheduleOnRN } from "react-native-worklets";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { StyleSheet, useUnistyles } from "react-native-unistyles";
import { TitlebarDragRegion } from "@/components/desktop/titlebar-drag-region";
import {
TitlebarDragRegion,
WINDOW_CONTENT_DATASET,
} from "@/components/desktop/titlebar-drag-region";
import { SidebarCloseButton } from "@/components/headers/sidebar-close-button";
import {
resolveDesktopSidebarInsetLeft,
@@ -39,7 +55,7 @@ import { HostPicker } from "@/components/hosts/host-picker";
import { SidebarDisplayPreferencesMenu } from "@/components/sidebar/display-preferences/menu";
import { SidebarSeparator } from "@/components/sidebar/sidebar-separator";
import { SidebarToastRegion } from "@/components/sidebar/sidebar-toast-region";
import { SidebarNavRows } from "@/components/sidebar/sidebar-nav-rows";
import { SidebarNavRows, useVisibleSidebarNavItems } from "@/components/sidebar/sidebar-nav-rows";
import { SidebarFooterIconHighlight } from "@/components/sidebar/sidebar-footer-icon-highlight";
import { SidebarHelpMenu } from "@/components/sidebar/sidebar-help-menu";
import { SidebarFooterOverflowMenu } from "@/components/sidebar/sidebar-footer-overflow-menu";
@@ -622,29 +638,7 @@ function MobileSidebar({
>
<View style={styles.sidebarContent} pointerEvents="auto">
<WindowChromeSafeArea placement="below" />
{platformIsNative ? (
<GHScrollView
// Same contract as the workspace list: vertical drags scroll the nav
// block, a clear horizontal intent still activates the close pan.
simultaneousHandlers={closeGestureRef}
style={styles.mobileNavScroll}
showsVerticalScrollIndicator={false}
alwaysBounceVertical={false}
testID="sidebar-nav-scroll"
>
{navRows}
</GHScrollView>
) : (
<ScrollView
style={styles.mobileNavScroll}
showsVerticalScrollIndicator={false}
alwaysBounceVertical={false}
testID="sidebar-nav-scroll"
>
{navRows}
</ScrollView>
)}
<SidebarSeparator />
<SidebarNavScroll closeGestureRef={closeGestureRef}>{navRows}</SidebarNavScroll>
<SidebarViewSlot dismiss={handleWorkspacePress}>
<SidebarToastRegion active={active}>
@@ -689,6 +683,47 @@ function MobileSidebar({
);
}
interface SidebarNavScrollProps {
closeGestureRef: RefObject<GestureType | undefined>;
/** Web only: the viewport emits no window regions (see WINDOW_CONTENT_DATASET). */
windowContent?: boolean;
children: ReactNode;
}
// The capped, scrolling nav block shared by the mobile and desktop sidebars, with the
// divider below it. The divider is a sibling because Unistyles does not patch the
// gesture-handler ScrollView.
function SidebarNavScroll({ closeGestureRef, windowContent, children }: SidebarNavScrollProps) {
return (
<>
{platformIsNative ? (
<GHScrollView
// Same contract as the workspace list: vertical drags scroll the nav
// block, a clear horizontal intent still activates the close pan.
simultaneousHandlers={closeGestureRef}
style={styles.navScroll}
showsVerticalScrollIndicator={false}
alwaysBounceVertical={false}
testID="sidebar-nav-scroll"
>
{children}
</GHScrollView>
) : (
<ScrollView
dataSet={windowContent ? WINDOW_CONTENT_DATASET : undefined}
style={styles.navScroll}
showsVerticalScrollIndicator={false}
alwaysBounceVertical={false}
testID="sidebar-nav-scroll"
>
{children}
</ScrollView>
)}
<SidebarSeparator testID="sidebar-nav-separator" />
</>
);
}
function DesktopSidebar({
theme,
workspaceGroups,
@@ -809,12 +844,14 @@ function DesktopSidebar({
],
[insetsTop, insets.bottom, insets.left, overlay, divisionLayout],
);
// Below the window controls' row, or in the top band's place, the first row starts flush.
const inTopBand = useTopBand() !== null;
const sidebarHeaderGroupStyle = useMemo(
() => [styles.sidebarHeaderGroup, (ownsTopLeft || inTopBand) && styles.sidebarHeaderGroupFlush],
[ownsTopLeft, inTopBand],
);
// Windows and Linux draw their window controls top-right, so the sidebar has no chrome
// row there. The strip above the scrolling rows is then its window drag surface.
const showsChromeRow = ownsTopLeft || Boolean(DEV_BUILD_LABEL);
// With every top item hidden the sidebar starts at the Workspaces section, as before the
// nav scroller existed: no strip above it and no divider below it.
const hasNavRows = useVisibleSidebarNavItems().length > 0;
const showsDragStrip = hasNavRows && !showsChromeRow && !inTopBand;
return (
<MobilePanelOverlay
panel="agent-list"
@@ -825,7 +862,7 @@ function DesktopSidebar({
<Animated.View style={desktopSidebarStyle}>
<View style={desktopSidebarBorderStyle}>
<View style={styles.sidebarDragArea}>
{ownsTopLeft || DEV_BUILD_LABEL ? (
{showsChromeRow ? (
<View style={styles.desktopChromeRow}>
<TitlebarDragRegion />
{DEV_BUILD_LABEL ? (
@@ -842,11 +879,21 @@ function DesktopSidebar({
</View>
) : null}
</View>
) : (
<TitlebarDragRegion />
)}
<SidebarNavRows style={sidebarHeaderGroupStyle} onBeforeNavigate={closeSidebar} />
) : null}
{showsDragStrip ? (
<View style={styles.desktopDragStrip} testID="sidebar-nav-drag-strip">
<TitlebarDragRegion />
</View>
) : null}
</View>
{/* The drag overlay stays above this viewport: Electron does not clip
app-region rects to scroll viewports, so a scrolled-out row would
still claim its no-drag rect. */}
{hasNavRows ? (
<SidebarNavScroll closeGestureRef={closeGestureRef} windowContent>
<SidebarNavRows style={styles.sidebarHeaderGroup} onBeforeNavigate={closeSidebar} />
</SidebarNavScroll>
) : null}
<SidebarViewSlot dismiss={closeSidebar}>
<SidebarToastRegion active={active}>
@@ -935,19 +982,18 @@ const staticStyles = RNStyleSheet.create({
});
const styles = StyleSheet.create((theme) => ({
// The rows start flush: the chrome row, drag strip, or top band above them gives the inset.
sidebarHeaderGroup: {
paddingTop: theme.spacing[2],
gap: 2,
paddingBottom: theme.spacing[1.5],
borderBottomWidth: 1,
borderBottomColor: theme.colors.border,
},
sidebarHeaderGroupFlush: {
paddingTop: 0,
desktopDragStrip: {
position: "relative",
height: theme.spacing[2],
},
// The nav block caps at half the sidebar; a long item list scrolls inside the
// cap instead of crowding the workspace list off a short screen.
mobileNavScroll: {
navScroll: {
flexGrow: 0,
flexShrink: 1,
maxHeight: "50%",
@@ -35,14 +35,19 @@ interface SidebarNavRowsProps extends SidebarNavRowProps {
firstRowTrailing?: ReactNode;
}
/** The top-level items the user keeps visible, in display order. */
export function useVisibleSidebarNavItems() {
const { items } = useSidebarNavItems("header");
return useMemo(() => items.filter((item) => item.visible), [items]);
}
/**
* Top-level sidebar navigation, ordered and filtered by the user's
* `sidebarNavItems` preference. Renders nothing — not even the bordered group
* wrapper — when every item is hidden and there is no `firstRowTrailing`.
*/
export function SidebarNavRows({ style, onBeforeNavigate, firstRowTrailing }: SidebarNavRowsProps) {
const { items } = useSidebarNavItems("header");
const visibleItems = useMemo(() => items.filter((item) => item.visible), [items]);
const visibleItems = useVisibleSidebarNavItems();
const groupRef = useRef<View | null>(null);
if (visibleItems.length === 0 && !firstRowTrailing) return null;
@@ -31,6 +31,7 @@ import {
toolbarSlot,
type ToolbarGlyphs,
} from "@/components/ui/control-geometry";
import { shortModelLabel } from "./utils";
const SNAP_POINTS = ["80%", "90%"];
const MODEL_LIST_TOP_INSET = 4;
@@ -66,11 +67,6 @@ interface CompactModelSheetProps {
children: ReactNode;
}
function shortModelLabel(label: string): string {
const separatorIndex = label.lastIndexOf("/");
return separatorIndex === -1 ? label : label.slice(separatorIndex + 1);
}
function resolveModelSheetProfileActions(
onCreateProfile: ((seed: AgentProfileSeed) => void) | undefined,
onEditProfile: ((profileId: string) => void) | undefined,
@@ -4,6 +4,7 @@ import {
getAgentControlHintKey,
normalizeModelId,
resolveAgentModelSelection,
shortModelLabel,
} from "./utils";
describe("getAgentControlHintKey", () => {
@@ -251,3 +252,19 @@ describe("resolveAgentModelSelection", () => {
expect(selection.displayThinking).toBe("Max");
});
});
describe("shortModelLabel", () => {
it("drops a provider namespace", () => {
expect(shortModelLabel("openrouter/gpt-5.5")).toBe("gpt-5.5");
expect(shortModelLabel("openrouter/google/gemini-2.5-flash")).toBe("gemini-2.5-flash");
});
it("keeps slashes inside a display name", () => {
expect(shortModelLabel("DeepSeek V4.1 Flash (~6-7 tok/s, 56/56)")).toBe(
"DeepSeek V4.1 Flash (~6-7 tok/s, 56/56)",
);
expect(shortModelLabel("llama-swap/DeepSeek V4.1 Flash (56/56)")).toBe(
"DeepSeek V4.1 Flash (56/56)",
);
});
});
@@ -35,6 +35,12 @@ export function normalizeModelId(modelId: string | null | undefined): string | n
return normalized;
}
// Drops a provider namespace ("openrouter/gpt-5.5" -> "gpt-5.5") for the compact trigger.
// A namespace segment has no spaces, so slashes inside a display name ("52/56") survive.
export function shortModelLabel(label: string): string {
return label.replace(/^(?:[^\s/]+\/)+(?=\S)/, "");
}
export function getFeatureHighlightColor(featureId: string): FeatureHighlightColor {
switch (featureId) {
case FAST_MODE_FEATURE_ID:
@@ -431,7 +431,7 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
<View style={styles.portRow}>
<View style={hostFieldStyle}>
<Text style={styles.label}>{t("pairing.direct.fields.host")}</Text>
<ThemedAdaptiveTextInput
<AdaptiveTextInput
testID="direct-host-input"
nativeID="direct-host-input"
accessibilityLabel={t("pairing.direct.fields.host")}
@@ -449,7 +449,7 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
</View>
<View style={portFieldStyle}>
<Text style={styles.label}>{t("pairing.direct.fields.port")}</Text>
<ThemedAdaptiveTextInput
<AdaptiveTextInput
testID="direct-port-input"
nativeID="direct-port-input"
accessibilityLabel={t("pairing.direct.fields.port")}
@@ -491,7 +491,7 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
<View style={styles.field}>
<Text style={styles.label}>{t("pairing.direct.fields.password")}</Text>
<View style={styles.passwordRow}>
<ThemedAdaptiveTextInput
<AdaptiveTextInput
testID="direct-password-input"
nativeID="direct-password-input"
accessibilityLabel={t("pairing.direct.fields.password")}
@@ -539,7 +539,7 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
<Text style={styles.advancedText}>{t("pairing.direct.advanced.label")}</Text>
</PressHighlight>
{isAdvancedOpen ? (
<ThemedAdaptiveTextInput
<AdaptiveTextInput
testID="direct-host-uri-input"
nativeID="direct-host-uri-input"
accessibilityLabel={t("pairing.direct.fields.connectionUri")}
@@ -598,7 +598,3 @@ const ThemedChevronRight = withUnistyles(ChevronRight, (theme) => ({
const ThemedEye = withUnistyles(Eye, (theme) => ({ color: theme.colors.foregroundMuted }));
const ThemedEyeOff = withUnistyles(EyeOff, (theme) => ({ color: theme.colors.foregroundMuted }));
const ThemedAdaptiveTextInput = withUnistyles(AdaptiveTextInput, (theme) => ({
placeholderTextColor: theme.colors.foregroundMuted,
}));
@@ -212,7 +212,7 @@ function PairLinkModalContent({
<View style={styles.field}>
<Text style={styles.label}>{t("pairing.link.label")}</Text>
<ThemedAdaptiveTextInput
<AdaptiveTextInput
ref={inputRef}
initialValue={initialUrl}
testID="pair-link-input"
@@ -234,11 +234,13 @@ function PairLinkModalContent({
<Text style={styles.label}>
{t("pairing.hostPassword.title", { host: parsedHostLabel(offerUrlRef.current) })}
</Text>
<ThemedAdaptiveTextInput
<AdaptiveTextInput
testID="pair-link-password-input"
resetKey={`pair-link-password-${passwordResetKey}`}
accessibilityLabel={t("pairing.hostPassword.label")}
placeholder={t("pairing.hostPassword.label")}
onChangeText={setPassword}
autoFocus
secureTextEntry
style={styles.input}
/>
@@ -275,7 +277,3 @@ function PairLinkModalContent({
}
const ThemedLink = withUnistyles(Link, (theme) => ({ color: theme.colors.accentForeground }));
const ThemedAdaptiveTextInput = withUnistyles(AdaptiveTextInput, (theme) => ({
placeholderTextColor: theme.colors.foregroundMuted,
}));
+1 -1
View File
@@ -762,7 +762,7 @@ function ChatAgentContent({
});
const reportAttentionError = useCallback(
(error: unknown) => {
toastApi.show(String(error), { variant: "error", durationMs: null });
toastApi.error(toErrorMessage(error));
},
[toastApi],
);
@@ -2256,6 +2256,59 @@ describe("HostRuntimeController", () => {
});
});
const REGISTRY_KEY = "@paseo:daemon-registry";
const futureConnection = { id: "future:1", type: "futureKind", address: "future.example.com" };
const directA: HostConnection = {
id: "direct:lan-a:6767",
type: "directTcp",
endpoint: "lan-a:6767",
};
const directB: HostConnection = {
id: "direct:lan-b:6767",
type: "directTcp",
endpoint: "lan-b:6767",
};
// What a build with a connection kind this one doesn't know leaves behind: an extra connection
// on a host this build can reach, and a host reached only through it.
const storedWithUnreadableEntries = [
{
...makeHost({ serverId: "srv_a", password: "secret-a" }),
connections: [futureConnection, directA],
},
makeHost({ serverId: "srv_b", password: "secret-b", connections: [directB] }),
{ serverId: "srv_future", label: "future host", connections: [futureConnection] },
];
async function bootWithRegistry(registry: string): Promise<{
store: HostRuntimeStore;
storage: HostRuntimeStorage;
}> {
const storage = createMemoryHostRuntimeStorage({
[REGISTRY_KEY]: registry,
"@paseo:e2e": "1",
});
const store = new HostRuntimeStore({
storage,
deps: {
createClient: () => new FakeDaemonClient() as unknown as DaemonClient,
connectToDaemon: async ({ host }) => ({
client: makeConnectedProbeClient(5) as unknown as DaemonClient,
serverId: host.serverId,
hostname: host.label ?? null,
}),
getClientId: async () => "cid_test_runtime",
},
revokePushNotifications: async () => undefined,
});
await store.boot();
return { store, storage };
}
async function readRegistry(storage: HostRuntimeStorage): Promise<unknown> {
const raw = await storage.getItem(REGISTRY_KEY);
return raw === null ? null : JSON.parse(raw);
}
describe("HostRuntimeStore", () => {
function gatewayRecoveryFixture() {
const parent = new FakeDaemonClient();
@@ -2686,6 +2739,98 @@ describe("HostRuntimeStore", () => {
session.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));
expect(store.getHosts().map((host) => [host.serverId, host.password])).toEqual([
["srv_a", "secret-a"],
["srv_b", "secret-b"],
]);
expect(store.getHosts()[0]?.connections.map((connection) => connection.id)).toEqual([
directA.id,
]);
expect(await readRegistry(storage)).toEqual(storedWithUnreadableEntries);
store.syncHosts([]);
});
it("keeps the entries it can't read when it saves the registry", async () => {
const { store, storage } = await bootWithRegistry(JSON.stringify(storedWithUnreadableEntries));
await store.renameHost("srv_b", "renamed");
expect(await readRegistry(storage)).toMatchObject([
{
serverId: "srv_a",
password: "secret-a",
connections: [{ id: directA.id }, futureConnection],
},
{ serverId: "srv_b", password: "secret-b", label: "renamed" },
storedWithUnreadableEntries[2],
]);
store.syncHosts([]);
});
it("moves a stored connection password to its host and keeps the connection it can't read", async () => {
const { store, storage } = await bootWithRegistry(
JSON.stringify([
{
serverId: "srv_legacy",
connections: [
{ type: "directTcp", endpoint: "lan-a:6767", password: "old-secret" },
futureConnection,
],
},
]),
);
expect(store.getHosts().map((host) => [host.serverId, host.password])).toEqual([
["srv_legacy", "old-secret"],
]);
await vi.waitFor(async () =>
expect(await readRegistry(storage)).toMatchObject([
{ serverId: "srv_legacy", password: "old-secret" },
]),
);
expect(await readRegistry(storage)).toMatchObject([
{ connections: [{ ...directA, useTls: false }, futureConnection] },
]);
const [written] = (await readRegistry(storage)) as Array<{ connections: unknown[] }>;
expect(written?.connections[0]).not.toHaveProperty("password");
store.syncHosts([]);
});
it("forgets an entry it can't read once that host is paired again and removed", async () => {
const { store, storage } = await bootWithRegistry(
JSON.stringify([{ serverId: "srv_future", connections: [futureConnection] }]),
);
expect(store.getHosts()).toEqual([]);
await store.upsertDirectConnection({ serverId: "srv_future", endpoint: directA.endpoint });
await vi.waitFor(async () =>
expect(await readRegistry(storage)).toMatchObject([
{ serverId: "srv_future", connections: [{ id: directA.id }] },
]),
);
await store.removeHost("srv_future");
expect(await readRegistry(storage)).toEqual([]);
store.syncHosts([]);
});
it("copies a registry that isn't JSON aside instead of deleting it", async () => {
const { store, storage } = await bootWithRegistry("{not json");
expect(store.getHosts()).toEqual([]);
expect(await storage.getItem(`${REGISTRY_KEY}:unreadable`)).toBe("{not json");
expect(await storage.getItem(REGISTRY_KEY)).toBe("{not json");
store.syncHosts([]);
});
it("marks the host registry loaded after boot reads storage", async () => {
const previousOverride = process.env.EXPO_PUBLIC_LOCAL_DAEMON;
process.env.EXPO_PUBLIC_LOCAL_DAEMON = "not-an-endpoint";
+37 -28
View File
@@ -17,14 +17,16 @@ import {
import {
connectionFromListen,
createRemoteSshHostConnection,
normalizeStoredHostProfile,
forgetUnreadableHost,
pinRelayProtectedSecurityInProfiles,
readHostRegistry,
upsertHostConnectionInProfiles,
registryHasConnection,
relayConnectionFromOffer,
StoredHostRegistrySchema,
writeHostRegistry,
type HostConnection,
type HostProfile,
type UnreadableHostEntries,
} from "@/types/host-connection";
import { defaultHostAppearance, type HostBadgeDisplay, type HostColor } from "@/hosts/appearance";
import {
@@ -43,7 +45,7 @@ import { isWeb } from "@/constants/platform";
import { connectToDaemon, getConnectionAuthFailureReason } from "@/utils/test-daemon-connection";
import { getOrCreateClientId } from "@/utils/client-id";
import { z } from "zod";
import { readValidatedJson, readValidatedString } from "@/storage/validated-storage";
import { readValidatedString } from "@/storage/validated-storage";
import {
selectBestConnection,
type ConnectionCandidate,
@@ -1692,6 +1694,7 @@ export class HostRuntimeStore {
private hostListVersion = 0;
private hostRegistryLoaded = false;
private hosts: HostProfile[] = [];
private unreadableHosts: UnreadableHostEntries = { hosts: [], connectionsByServerId: new Map() };
private hostAppearanceMutationTail: Promise<void> = Promise.resolve();
private hostRegistryStatus: HostRegistryStatus = "loading";
private deps: HostRuntimeControllerDeps;
@@ -1799,32 +1802,17 @@ export class HostRuntimeStore {
let shouldPersistHosts = false;
let profiles: HostProfile[] = [];
try {
const stored = await readValidatedJson(
this.storage,
REGISTRY_STORAGE_KEY,
StoredHostRegistrySchema,
);
const stored = await this.readStoredRegistry();
if (stored) {
const normalizedProfiles: HostProfile[] = [];
for (const entry of stored) {
const profile = normalizeStoredHostProfile(entry);
if (!profile) {
await this.storage.removeItem(REGISTRY_STORAGE_KEY);
normalizedProfiles.length = 0;
break;
}
// COMPAT(connectionPassword): added in v0.9.1, remove after 2027-03-24 with stored-password migration.
if (
entry.connections.some(
(connection) => connection.type === "directTcp" && connection.password,
)
) {
shouldPersistHosts = true;
}
normalizedProfiles.push(profile);
// An entry this build can't read skips only that host or connection, and stays stored.
const registry = readHostRegistry(stored);
this.unreadableHosts = registry.unreadable;
// COMPAT(connectionPassword): added in v0.9.1, remove after 2027-03-24 with stored-password migration.
if (registry.movedConnectionPassword) {
shouldPersistHosts = true;
}
profiles = normalizedProfiles.filter((entry) => !isPlaceholderServerId(entry.serverId));
if (profiles.length !== normalizedProfiles.length) {
profiles = registry.hosts.filter((entry) => !isPlaceholderServerId(entry.serverId));
if (profiles.length !== registry.hosts.length) {
shouldPersistHosts = true;
}
}
@@ -2320,6 +2308,7 @@ export class HostRuntimeStore {
async removeHost(serverId: string): Promise<void> {
await this.revokePushNotifications({ client: this.getClient(serverId), serverId });
const remaining = this.hosts.filter((daemon) => daemon.serverId !== serverId);
this.unreadableHosts = forgetUnreadableHost(this.unreadableHosts, serverId);
this.setHostsAndSync(remaining);
await this.persistHosts();
}
@@ -2408,7 +2397,27 @@ export class HostRuntimeStore {
}
private async persistHosts(hosts = this.hosts): Promise<void> {
await this.storage.setItem(REGISTRY_STORAGE_KEY, JSON.stringify(hosts));
await this.storage.setItem(
REGISTRY_STORAGE_KEY,
JSON.stringify(writeHostRegistry(hosts, this.unreadableHosts)),
);
}
/**
* Reads the stored registry without removing it. A value that isn't a JSON array is copied to
* `<key>:unreadable` first, because the next save overwrites the key.
*/
private async readStoredRegistry(): Promise<unknown[] | null> {
const raw = await this.storage.getItem(REGISTRY_STORAGE_KEY);
if (raw === null) return null;
try {
const value: unknown = JSON.parse(raw);
if (Array.isArray(value)) return value;
} catch {
// Not JSON: copied aside below.
}
await this.storage.setItem(`${REGISTRY_STORAGE_KEY}:unreadable`, raw);
return null;
}
private emitHostList(): void {
@@ -21,8 +21,7 @@ import {
import { useLocalDaemonServerId } from "@/hooks/use-is-local-daemon";
import { PairDeviceModal } from "@/desktop/components/pair-device-modal";
import { buildSettingsHostSectionRoute } from "@/utils/host-routes";
const WINDOW_CONTENT_DATASET = { "window-content": "" };
import { WINDOW_CONTENT_DATASET } from "@/components/desktop/titlebar-drag-region";
export function OpenProjectScreen() {
const { t } = useTranslation();
@@ -106,6 +106,79 @@ describe("workspace-pane-state", () => {
});
});
it("does not locate a file by an id retained from a previous target", () => {
const layout: WorkspaceLayout = {
root: {
kind: "pane",
pane: {
id: "main",
tabIds: ["file_/repo/a.ts", "agent_agent-a"],
focusedTabId: "agent_agent-a",
},
},
focusedPaneId: "main",
};
const tabs = [
createTab("file_/repo/a.ts", { kind: "file", path: "/repo/b.ts" }),
createTab("agent_agent-a", { kind: "agent", agentId: "agent-a" }),
];
const target: WorkspaceTab["target"] = { kind: "file", path: "/repo/a.ts" };
expect(resolveSideFileOpenPlacement({ layout, sourcePaneId: "main", tabs, target })).toEqual({
kind: "split-side-pane",
paneId: "main",
});
expect(deriveWorkspacePaneState({ layout, tabs, preferredTarget: target }).activeTabId).toBe(
"agent_agent-a",
);
});
it("matches a retained file instance when only the requested line range differs", () => {
const pane = {
id: "main",
tabIds: ["retained-file", "agent_agent-a"],
focusedTabId: "agent_agent-a",
};
const layout: WorkspaceLayout = { root: { kind: "pane", pane }, focusedPaneId: "main" };
const tabs = [
createTab("retained-file", { kind: "file", path: "/repo/a.ts", lineStart: 2 }),
createTab("agent_agent-a", { kind: "agent", agentId: "agent-a" }),
];
const target: WorkspaceTab["target"] = {
kind: "file",
path: "/repo/a.ts",
lineStart: 12,
lineEnd: 20,
};
expect(resolveSideFileOpenPlacement({ layout, sourcePaneId: "main", tabs, target })).toEqual({
kind: "open-in-source",
});
expect(deriveWorkspacePaneState({ layout, tabs, preferredTarget: target }).activeTabId).toBe(
"retained-file",
);
});
it("prefers an exact file navigation target over another instance of the same resource", () => {
const pane = {
id: "main",
tabIds: ["first", "second"],
focusedTabId: "first",
};
const tabs = [
createTab("first", { kind: "file", path: "/repo/a.ts", lineStart: 2 }),
createTab("second", { kind: "file", path: "/repo/a.ts", lineStart: 12 }),
];
expect(
deriveWorkspacePaneState({
pane,
tabs,
preferredTarget: { kind: "file", path: "/repo/a.ts", lineStart: 12 },
}).activeTabId,
).toBe("second");
});
it("resolves side file opens to an existing file tab", () => {
const layout: WorkspaceLayout = {
root: {
@@ -5,12 +5,9 @@ import {
} from "@/stores/workspace-layout-store";
import type { WorkspaceTab, WorkspaceTabTarget } from "@/workspace-tabs/model";
import type { WorkspaceTabDescriptor } from "@/screens/workspace/workspace-tabs-types";
import {
buildDeterministicWorkspaceTabId,
normalizeWorkspaceTabTarget,
workspaceTabTargetsEqual,
} from "@/workspace-tabs/identity";
import { normalizeWorkspaceTabTarget, workspaceTabTargetsEqual } from "@/workspace-tabs/identity";
import { findAdjacentPane } from "@/utils/split-navigation";
import { panelResourceKey } from "@/panels/panel-manifest";
export interface WorkspaceDerivedTab {
descriptor: WorkspaceTabDescriptor;
@@ -124,8 +121,10 @@ function getActiveTabId(input: {
}
const matchingTab =
input.tabs.find((tab) => workspaceTabTargetsEqual(tab.descriptor.target, preferredTarget)) ??
null;
return matchingTab?.descriptor.tabId ?? buildDeterministicWorkspaceTabId(preferredTarget);
input.tabs.find(
(tab) => panelResourceKey(tab.descriptor.target) === panelResourceKey(preferredTarget),
);
return matchingTab?.descriptor.tabId ?? null;
})();
if (preferredTabId && input.openTabIds.has(preferredTabId)) {
@@ -211,10 +210,8 @@ export function resolveSideFileOpenPlacement(input: {
tabs: WorkspaceTab[];
target: WorkspaceTabTarget;
}): WorkspaceSideFileOpenPlacement {
const targetTabId = buildDeterministicWorkspaceTabId(input.target);
const existingTab = input.tabs.find(
(tab) => tab.tabId === targetTabId || workspaceTabTargetsEqual(tab.target, input.target),
);
const targetKey = panelResourceKey(input.target);
const existingTab = input.tabs.find((tab) => panelResourceKey(tab.target) === targetKey);
if (existingTab) {
return { kind: "open-in-source" };
}
@@ -3,7 +3,7 @@ import type { JsonValue } from "@getpaseo/protocol/agent-types";
import type { WorkspaceTab, WorkspaceTabTarget } from "@/workspace-tabs/model";
import { MIN_SPLIT_SIZE } from "@/stores/workspace-layout-constants";
import { panelResourceKey, panelSupportsHost } from "@/panels/panel-manifest";
import { defaultWorkspaceLayoutIds } from "@/stores/workspace-layout-ids";
import { allocateWorkspaceTabId, defaultWorkspaceLayoutIds } from "@/stores/workspace-layout-ids";
import type { WorkspaceLayoutNodeIdPrefix } from "@/stores/workspace-layout-ids";
import {
buildDeterministicWorkspaceTabId,
@@ -137,6 +137,8 @@ interface OpenTabInLayoutInput {
placement: WorkspaceTabPlacement;
/** Required so a new caller cannot silently opt out of Explorer placement rules. */
explorerSidebarPaneId: string | null;
/** Live sheets share the workspace's panel-instance namespace with its tabs. */
reservedTabIds?: ReadonlySet<string>;
}
interface CreateTabInLayoutInput extends OpenTabInLayoutInput {
@@ -261,6 +263,7 @@ interface ReorderPaneTabsInLayoutInput {
export interface WorkspaceTabReconcileState {
layout: WorkspaceLayout;
reservedTabIds?: ReadonlySet<string>;
pinnedAgentIds?: ReadonlySet<string> | null;
hiddenAgentIds?: ReadonlySet<string> | null;
explorerSidebarPaneId: string | null;
@@ -398,15 +401,11 @@ function normalizeWorkspaceTabs(input: unknown): WorkspaceTab[] {
if (!Array.isArray(input)) {
return [];
}
// Preserve colliding entries until the whole layout can assign each an identity.
const next: WorkspaceTab[] = [];
const seen = new Set<string>();
for (const value of input) {
const tab = normalizeWorkspaceTab(value);
if (!tab || seen.has(tab.tabId)) {
continue;
}
seen.add(tab.tabId);
next.push(tab);
if (tab) next.push(tab);
}
return next;
}
@@ -1022,13 +1021,65 @@ function insertSplitInternal(input: InsertSplitInternalInput): InsertSplitIntern
};
}
function repairDuplicateTabIds(root: SplitNodeInternal): {
root: SplitNodeInternal;
ambiguousIds: ReadonlySet<string>;
} {
const keepers = new Map<string, WorkspaceTab>();
const ambiguousIds = new Set<string>();
for (const tab of collectAllTabs(root)) {
const keeper = keepers.get(tab.tabId);
if (!keeper) {
keepers.set(tab.tabId, tab);
continue;
}
ambiguousIds.add(tab.tabId);
if (
buildDeterministicWorkspaceTabId(tab.target) === tab.tabId &&
buildDeterministicWorkspaceTabId(keeper.target) !== keeper.tabId
) {
keepers.set(tab.tabId, tab);
}
}
if (ambiguousIds.size === 0) return { root, ambiguousIds };
// Reserve every original id before assigning replacements, including hidden panes.
const occupiedIds = new Set(keepers.keys());
function repair(node: SplitNodeInternal): SplitNodeInternal {
if (node.kind === "group") {
return { ...node, group: { ...node.group, children: node.group.children.map(repair) } };
}
const focusedCandidates = node.pane.tabs.filter((tab) => tab.tabId === node.pane.focusedTabId);
const focusedTab =
focusedCandidates.find((tab) => keepers.get(tab.tabId) === tab) ?? focusedCandidates[0];
let focusedTabId = node.pane.focusedTabId;
const tabs = node.pane.tabs.map((tab) => {
if (keepers.get(tab.tabId) === tab) return tab;
const tabId = allocateWorkspaceTabId(
buildDeterministicWorkspaceTabId(tab.target),
occupiedIds,
);
occupiedIds.add(tabId);
if (tab === focusedTab) focusedTabId = tabId;
return { ...tab, tabId };
});
return {
...node,
pane: { ...node.pane, tabs, tabIds: tabs.map((tab) => tab.tabId), focusedTabId },
};
}
return { root: repair(root), ambiguousIds };
}
export function normalizeLayout(layout: unknown): WorkspaceLayout {
if (!layout || typeof layout !== "object") {
return createDefaultLayout();
}
const rawLayout = layout as WorkspaceLayout;
const root = normalizeNode(rawLayout.root) ?? asInternalNode(createDefaultLayout().root);
const { root, ambiguousIds } = repairDuplicateTabIds(
normalizeNode(rawLayout.root) ?? asInternalNode(createDefaultLayout().root),
);
const focusedPaneId =
rawLayout.focusedPaneId === null ? null : trimNonEmpty(rawLayout.focusedPaneId);
const resolvedFocusedPaneId =
@@ -1047,7 +1098,16 @@ export function normalizeLayout(layout: unknown): WorkspaceLayout {
openTabIds: new Set(collectAllTabs(root).map((tab) => tab.tabId)),
});
return parentTabIdByTabId ? { ...normalizedLayout, parentTabIdByTabId } : normalizedLayout;
if (parentTabIdByTabId) {
// A duplicated id cannot identify either end of a parent relationship unambiguously.
for (const [childId, parentId] of Object.entries(parentTabIdByTabId)) {
if (ambiguousIds.has(childId) || ambiguousIds.has(parentId))
delete parentTabIdByTabId[childId];
}
if (Object.keys(parentTabIdByTabId).length > 0)
return { ...normalizedLayout, parentTabIdByTabId };
}
return normalizedLayout;
}
export function findPaneById(root: SplitNode, paneId: string | null | undefined): SplitPane | null {
@@ -1364,7 +1424,9 @@ function insertNewTabIntoPane(
return null;
}
const tabId = input.createTabId();
const occupiedIds = new Set(input.reservedTabIds);
for (const tab of collectAllTabs(layout.root)) occupiedIds.add(tab.tabId);
const tabId = allocateWorkspaceTabId(input.createTabId(), occupiedIds);
const nextTab: WorkspaceTab = {
tabId,
target: input.target,
@@ -2284,6 +2346,7 @@ function openEntityTabWithoutFocusing(input: {
layout: WorkspaceLayout;
target: WorkspaceTabTarget;
explorerSidebarPaneId: string | null;
reservedTabIds: ReadonlySet<string> | undefined;
}): WorkspaceLayout {
return (
insertNewTabIntoPane({
@@ -2292,6 +2355,7 @@ function openEntityTabWithoutFocusing(input: {
now: Date.now(),
placement: AMBIENT_PLACEMENT,
explorerSidebarPaneId: input.explorerSidebarPaneId,
reservedTabIds: input.reservedTabIds,
createTabId: () => buildDeterministicWorkspaceTabId(input.target),
focus: false,
})?.layout ?? input.layout
@@ -2382,6 +2446,7 @@ function addMissingEntityTabs(input: {
hasActivePendingTerminalCreate: boolean;
hasActivePendingDraftCreate: boolean;
explorerSidebarPaneId: string | null;
reservedTabIds: ReadonlySet<string> | undefined;
}): WorkspaceLayout {
const {
autoOpenAgentIds,
@@ -2412,6 +2477,7 @@ function addMissingEntityTabs(input: {
layout: nextLayout,
target: { kind: "agent", agentId },
explorerSidebarPaneId,
reservedTabIds: input.reservedTabIds,
});
currentAgentIds.add(agentId);
}
@@ -2426,6 +2492,7 @@ function addMissingEntityTabs(input: {
layout: nextLayout,
target: { kind: "terminal", terminalId },
explorerSidebarPaneId,
reservedTabIds: input.reservedTabIds,
});
currentTerminalIds.add(terminalId);
}
@@ -2525,6 +2592,7 @@ export function reconcileWorkspaceTabs(
hasActivePendingTerminalCreate: snapshot.hasActivePendingTerminalCreate ?? false,
hasActivePendingDraftCreate: snapshot.hasActivePendingDraftCreate ?? false,
explorerSidebarPaneId: state.explorerSidebarPaneId,
reservedTabIds: state.reservedTabIds,
});
if (reconciledFocusedTabId) {
@@ -11,6 +11,22 @@ function createRandomIdValue(): string {
: `${Date.now()}-${Math.random().toString(16).slice(2)}`;
}
export function createWorkspaceTabInstanceId(): string {
return `tab_${createRandomIdValue()}`;
}
/** A resource-derived id may still belong to a preview slot showing another target. */
export function allocateWorkspaceTabId(
preferredId: string,
occupiedIds: ReadonlySet<string>,
): string {
let tabId = preferredId;
for (let suffix = 2; occupiedIds.has(tabId); suffix += 1) {
tabId = `${preferredId}:${suffix}`;
}
return tabId;
}
export const defaultWorkspaceLayoutIds: WorkspaceLayoutIdSource = {
createNodeId: (prefix) => `${prefix}_${createRandomIdValue()}`,
createFocusRestorationToken: () => `workspace-focus-${createRandomIdValue()}`,
@@ -59,6 +59,84 @@ it("skips unchanged reconciliations and immediately saves real layout changes",
);
});
it("hydrates a saved preview collision and persists the repaired identities", async () => {
const workspaceKey = "server:workspace";
const duplicateId = "file_a.ts";
const values = new Map([
[
"workspace-layout-state",
JSON.stringify({
version: 2,
state: {
layoutByWorkspace: {
[workspaceKey]: {
root: {
kind: "group",
group: {
id: "split",
direction: "horizontal",
sizes: [0.5, 0.5],
children: [
{ id: "main", path: "b.ts" },
{ id: "right", path: "a.ts" },
].map(({ id, path }) => ({
kind: "pane",
pane: {
id,
tabIds: [duplicateId],
focusedTabId: duplicateId,
tabs: [{ tabId: duplicateId, target: { kind: "file", path }, createdAt: 1 }],
},
})),
},
},
focusedPaneId: "right",
},
},
},
}),
],
]);
const storage: StateStorage = {
getItem: (name) => values.get(name) ?? null,
setItem: (name, value) => {
values.set(name, value);
},
removeItem: (name) => {
values.delete(name);
},
};
const store = createWorkspaceLayoutStore(undefined, storage);
await store.persist.rehydrate();
const layout = store.getState().layoutByWorkspace[workspaceKey];
const tabs = collectAllTabs(layout.root);
expect(tabs.filter((tab) => tab.target.kind === "file").map((tab) => tab.tabId)).toEqual([
"file_b.ts",
"file_a.ts",
]);
expect(
deriveWorkspacePaneState({ layout, tabs, paneId: "main" }).activeTab?.descriptor.target,
).toEqual({
kind: "file",
path: "b.ts",
});
expect(
deriveWorkspacePaneState({ layout, tabs, paneId: "right" }).activeTab?.descriptor.target,
).toEqual({
kind: "file",
path: "a.ts",
});
store.getState().focusTab(workspaceKey, "file_b.ts");
expect(store.getState().layoutByWorkspace[workspaceKey].focusedPaneId).toBe("main");
const reloaded = createWorkspaceLayoutStore(undefined, storage);
await reloaded.persist.rehydrate();
expect(reloaded.getState().layoutByWorkspace[workspaceKey]).toEqual(
store.getState().layoutByWorkspace[workspaceKey],
);
});
it("keeps the saved layout when the shell publishes its layout mode before hydration", async () => {
const values = new Map<string, string>();
const storage: StateStorage = {
@@ -906,6 +906,91 @@ describe("workspace-layout-store actions", () => {
).toEqual(override);
});
it("keeps reused file tabs unique and focuses the matching split pane", () => {
const workspaceKey = createWorkspaceKey();
const store = workspaceLayoutStore.getState();
const firstTabId = store.openTab({
workspaceKey,
target: { kind: "file", path: "src/a.ts" },
intent: "reveal",
})!;
store.replaceTab(workspaceKey, firstTabId, { kind: "file", path: "src/b.ts" });
const rightPaneId = store.splitPaneEmpty(workspaceKey, {
targetPaneId: "main",
position: "right",
});
if (!rightPaneId) throw new Error("Expected a right split pane");
const rightTabId = store.openTab({
workspaceKey,
target: { kind: "file", path: "src/a.ts" },
intent: "reveal",
placement: { mode: "pane", paneId: rightPaneId },
})!;
store.openTab({
workspaceKey,
target: { kind: "file", path: "src/b.ts" },
intent: "reveal",
});
store.focusTab(workspaceKey, rightTabId);
const layout = workspaceLayoutStore.getState().layoutByWorkspace[workspaceKey];
const fileTabs = collectAllTabs(layout.root).filter((tab) => tab.target.kind === "file");
expect({
fileTabCount: fileTabs.length,
uniqueFileTabCount: new Set(fileTabs.map((tab) => tab.tabId)).size,
fileTargets: fileTabs.map((tab) => tab.target),
focusedPaneId: layout.focusedPaneId,
}).toEqual({
fileTabCount: 2,
uniqueFileTabCount: 2,
fileTargets: [
{ kind: "file", path: "src/b.ts" },
{ kind: "file", path: "src/a.ts" },
],
focusedPaneId: rightPaneId,
});
});
it("allocates distinct ids across retained tabs, sheets, and background opens", () => {
const workspaceKey = createWorkspaceKey();
const layoutStore = createWorkspaceLayoutStore(workspaceLayoutIds);
const store = layoutStore.getState();
const fileTabId = store.openTab({
workspaceKey,
target: { kind: "file", path: "src/a.ts" },
intent: "reveal",
})!;
store.replaceTab(workspaceKey, fileTabId, { kind: "file", path: "src/b.ts" });
layoutStore.setState({ layoutMode: "compact" });
const sheetTabId = store.openTab({
workspaceKey,
target: { kind: "file", path: "src/a.ts" },
intent: "reveal",
})!;
const selectedSheet = selectSheetTab(layoutStore.getState(), {
workspaceKey,
target: { kind: "file", path: "src/a.ts" },
});
expect(selectedSheet?.tab.tabId).toBe(sheetTabId);
const backgroundTabId = store.openTab({
workspaceKey,
target: { kind: "file", path: "src/a.ts" },
intent: "background",
})!;
expect(new Set([fileTabId, sheetTabId, backgroundTabId]).size).toBe(3);
expect(layoutStore.getState().sheetsByWorkspace[workspaceKey]).toHaveLength(1);
expect(
collectAllTabs(layoutStore.getState().layoutByWorkspace[workspaceKey].root)
.filter((tab) => tab.target.kind === "file")
.map((tab) => tab.target),
).toEqual([
{ kind: "file", path: "src/b.ts" },
{ kind: "file", path: "src/a.ts" },
]);
});
it("keeps the tab instance when a panel receives a same-kind replacement", () => {
const workspaceKey = createWorkspaceKey();
const store = workspaceLayoutStore.getState();
@@ -3200,6 +3285,75 @@ describe("workspace-layout-store actions", () => {
]);
});
it("repairs persisted duplicate ids without losing tabs, pane focus, or unambiguous parents", () => {
const file = (tabId: string, path: string) => ({
tabId,
target: { kind: "file", path },
createdAt: 1,
state: { treeVisible: true, treeWidth: 280 },
});
const leftTabs = [file("file_a.ts", "b.ts"), file("file_a.ts", "c.ts")];
const rightTabs = [
file("file_a.ts", "a.ts"),
file("file_b.ts", "b.ts"),
file("file_b.ts:2", "b.ts"),
file("child", "child.ts"),
file("parent", "parent.ts"),
];
const layout = normalizeLayout({
root: {
kind: "group",
group: {
id: "root",
direction: "horizontal",
sizes: [0.4, 0.6],
children: [
{
kind: "pane",
pane: {
id: "main",
tabs: leftTabs,
tabIds: leftTabs.map((tab) => tab.tabId),
focusedTabId: "file_a.ts",
},
},
{
kind: "pane",
pane: {
id: "right",
tabs: rightTabs,
tabIds: rightTabs.map((tab) => tab.tabId),
focusedTabId: "file_a.ts",
hidden: true,
},
},
],
},
},
focusedPaneId: "main",
parentTabIdByTabId: {
"file_a.ts": "parent",
"file_b.ts": "file_a.ts",
child: "parent",
},
});
const tabs = collectAllTabs(layout.root);
expect(tabs).toHaveLength(7);
expect(new Set(tabs.map((tab) => tab.tabId)).size).toBe(7);
expect(tabs[0]).toEqual({ ...leftTabs[0], tabId: "file_b.ts:3" });
expect(tabs[1]).toEqual({ ...leftTabs[1], tabId: "file_c.ts" });
expect(tabs.slice(2)).toEqual(rightTabs);
expect(findPaneById(layout.root, "main")?.tabIds).toEqual(["file_b.ts:3", "file_c.ts"]);
expect(findPaneById(layout.root, "main")?.focusedTabId).toBe("file_b.ts:3");
expect(findPaneById(layout.root, "right")).toMatchObject({
hidden: true,
focusedTabId: "file_a.ts",
});
expect(layout.parentTabIdByTabId).toEqual({ child: "parent" });
expect(normalizeLayout(layout)).toEqual(layout);
});
it("hydrates duplicate Changes and Pull request instances without collapsing their ids or state", () => {
const tabs = [
{
@@ -5110,6 +5264,50 @@ describe("compact workspace sheet", () => {
expect(sheetTargets(store)).toEqual([fileTarget, nextTarget]);
});
it("reserves a retargeted sheet's id when reconciling a new root agent tab", () => {
seedAgents([
{ id: "root", parentAgentId: null, workspaceId: "sheet-ws" },
{ id: "child-a", parentAgentId: "root", workspaceId: "sheet-ws" },
{ id: "child-b", parentAgentId: "root", workspaceId: "sheet-ws" },
]);
const store = createCompactStore();
store.getState().openTab({
workspaceKey,
target: { kind: "agent", agentId: "child-a" },
intent: "reveal",
});
const sheetId = requireTopSheet(store).tab.tabId;
store.getState().replaceTab(workspaceKey, sheetId, { kind: "agent", agentId: "child-b" });
seedAgents([
{ id: "root", parentAgentId: null, workspaceId: "sheet-ws" },
{ id: "child-a", parentAgentId: null, workspaceId: "sheet-ws" },
{ id: "child-b", parentAgentId: "root", workspaceId: "sheet-ws" },
]);
store.getState().reconcileTabs(workspaceKey, {
agentsHydrated: true,
terminalsHydrated: true,
activeAgentIds: ["root", "child-a", "child-b"],
autoOpenAgentIds: ["child-a"],
knownTerminalIds: ["term-1"],
standaloneTerminalIds: ["term-1"],
});
const tab = collectAllTabs(store.getState().layoutByWorkspace[workspaceKey].root).find(
(candidate) => candidate.target.kind === "agent" && candidate.target.agentId === "child-a",
);
if (!tab) throw new Error("Expected the root agent's tab");
expect(tab.tabId).not.toBe(sheetId);
store.getState().closeTab(workspaceKey, tab.tabId);
expect(requireTopSheet(store).tab).toMatchObject({
tabId: sheetId,
target: { kind: "agent", agentId: "child-b" },
});
expect(
collectAllTabs(store.getState().layoutByWorkspace[workspaceKey].root),
).not.toContainEqual(tab);
});
it("closes the sheet when its agent stops being a subagent, leaving one tab for it", () => {
seedAgents([
{ id: "root", parentAgentId: null, workspaceId: "sheet-ws" },
@@ -7,6 +7,8 @@ import { WorkspaceLayoutPersistedStateSchema } from "./workspace-layout-storage"
import type { JsonValue } from "@getpaseo/protocol/agent-types";
import type { WorkspaceTab, WorkspaceTabTarget } from "@/workspace-tabs/model";
import {
allocateWorkspaceTabId,
createWorkspaceTabInstanceId,
defaultWorkspaceLayoutIds,
type WorkspaceLayoutIdSource,
} from "@/stores/workspace-layout-ids";
@@ -431,14 +433,6 @@ function trimNonEmpty(value: string | null | undefined): string | null {
return trimmed.length > 0 ? trimmed : null;
}
function createWorkspaceTabInstanceId(): string {
const value =
typeof globalThis.crypto?.randomUUID === "function"
? globalThis.crypto.randomUUID()
: `${Date.now()}-${Math.random().toString(16).slice(2)}`;
return `tab_${value}`;
}
function addAgentIdToWorkspaceSet(
state: Record<string, Set<string>>,
workspaceKey: string,
@@ -531,7 +525,10 @@ export function selectExplorerSidebarPaneId(
*/
export function selectSheetTab(
state: Pick<WorkspaceLayoutStore, "layoutMode" | "layoutByWorkspace" | "sheetsByWorkspace">,
input: Pick<OpenWorkspaceTabInput, "workspaceKey" | "target" | "parentTabId">,
input: Pick<OpenWorkspaceTabInput, "workspaceKey" | "target" | "parentTabId"> & {
/** A host outside the sheet stack owns its instance identity. */
preferredTabId?: string;
},
): SheetTab | null {
const workspaceKey = trimNonEmpty(input.workspaceKey);
const target = normalizeWorkspaceTabTarget(input.target);
@@ -539,9 +536,14 @@ export function selectSheetTab(
const policy = resolveSheetPolicy(state, workspaceKey, target, "reveal");
if (!policy) return null;
return placeTargetInSheet({
kept: undefined,
occupiedTabIds: collectWorkspaceTabIds(state, workspaceKey),
kept: input.preferredTabId
? undefined
: getSheets(state, workspaceKey).find(
(sheet) => panelResourceKey(sheet.tab.target) === panelResourceKey(target),
),
target,
intent: "reveal",
createTabId: () => input.preferredTabId ?? buildDeterministicWorkspaceTabId(target),
policy,
parentTabId: resolveOpenParentTabId(state, workspaceKey, input.parentTabId),
state: undefined,
@@ -638,6 +640,7 @@ function getOpenTabPlacement(
layout: WorkspaceLayout;
placement: WorkspaceTabPlacement;
explorerSidebarPaneId: string | null;
reservedTabIds: Set<string>;
} {
const layout = getWorkspaceLayout(state.layoutByWorkspace, workspaceKey);
const explorerSidebarPaneId = resolveExplorerSidebarPaneId(
@@ -670,6 +673,7 @@ function getOpenTabPlacement(
layout,
placement: resolvedPlacement,
explorerSidebarPaneId,
reservedTabIds: new Set(getSheets(state, workspaceKey).map((sheet) => sheet.tab.tabId)),
};
}
@@ -815,11 +819,23 @@ function resolveOpenParentTabId(
return findSheet(state, workspaceKey, parentTabId)?.parentTabId ?? parentTabId;
}
function collectWorkspaceTabIds(
state: Pick<WorkspaceLayoutStore, "layoutByWorkspace" | "sheetsByWorkspace">,
workspaceKey: string,
): Set<string> {
const layout = state.layoutByWorkspace[workspaceKey];
return new Set([
...(layout ? collectAllTabs(layout.root).map((tab) => tab.tabId) : []),
...getSheets(state, workspaceKey).map((sheet) => sheet.tab.tabId),
]);
}
function placeTargetInSheet(input: {
occupiedTabIds: ReadonlySet<string>;
/** The sheet whose tab the target keeps, if any. */
kept: SheetTab | undefined;
target: WorkspaceTabTarget;
intent: WorkspaceTabOpenIntent;
createTabId: () => string;
policy: CompactSheetPolicy;
parentTabId: string | null;
state: JsonValue | undefined;
@@ -829,10 +845,7 @@ function placeTargetInSheet(input: {
}
return {
tab: {
tabId:
input.intent === "reveal"
? buildDeterministicWorkspaceTabId(input.target)
: createWorkspaceTabInstanceId(),
tabId: allocateWorkspaceTabId(input.createTabId(), input.occupiedTabIds),
target: input.target,
createdAt: Date.now(),
...(input.state !== undefined ? { state: input.state } : {}),
@@ -853,6 +866,7 @@ function promoteSheetToTab(
): { tabId: string; patch: Partial<WorkspaceLayoutStore> } | null {
const { tab } = sheet;
const placement = getOpenTabPlacement(state, workspaceKey, tab.target, FOCUSED_PANE_PLACEMENT);
placement.reservedTabIds.delete(tab.tabId);
const input = {
...placement,
target: tab.target,
@@ -1122,9 +1136,13 @@ export function createWorkspaceLayoutStore(
const sheets = getSheets(get(), normalizedWorkspaceKey);
const { keptIndex } = sheetPlacement;
const sheet = placeTargetInSheet({
occupiedTabIds: collectWorkspaceTabIds(get(), normalizedWorkspaceKey),
kept: keptIndex === null ? undefined : sheets[keptIndex],
target: normalizedTarget,
intent: input.intent,
createTabId: () =>
input.intent === "reveal"
? buildDeterministicWorkspaceTabId(normalizedTarget)
: createWorkspaceTabInstanceId(),
policy: sheetPlacement.policy,
parentTabId,
state: input.state,
@@ -1706,9 +1724,14 @@ export function createWorkspaceLayoutStore(
explorerSidebarPaneId,
rawLayout.focusedPaneId,
);
const sheets = getSheets(state, normalizedWorkspaceKey);
const fittingSheets = sheets.filter(
(sheet) => !sheetAgentNoLongerFits(normalizedWorkspaceKey, sheet, snapshot),
);
const nextState = reconcileWorkspaceTabs(
{
layout: currentLayout,
reservedTabIds: new Set(fittingSheets.map((sheet) => sheet.tab.tabId)),
pinnedAgentIds: state.pinnedAgentIdsByWorkspace[normalizedWorkspaceKey] ?? null,
hiddenAgentIds: state.hiddenAgentIdsByWorkspace[normalizedWorkspaceKey] ?? null,
explorerSidebarPaneId,
@@ -1730,10 +1753,6 @@ export function createWorkspaceLayoutStore(
);
}
}
const sheets = getSheets(state, normalizedWorkspaceKey);
const fittingSheets = sheets.filter(
(sheet) => !sheetAgentNoLongerFits(normalizedWorkspaceKey, sheet, snapshot),
);
const sheetAgentGone = fittingSheets.length !== sheets.length;
if (
state.layoutByWorkspace[normalizedWorkspaceKey] &&
@@ -138,6 +138,88 @@ describe("useSubagentSheetTab", () => {
expect(result.current?.tab.tabId).toBe(tabId);
});
it("keeps an open menu sheet's id when an unrelated reused tab disappears", () => {
const row = seedParentWithChild();
const store = useWorkspaceLayoutStore.getState();
const reusedId = store.openTab({
workspaceKey,
target: { kind: "agent", agentId: "child" },
intent: "reveal",
asTab: true,
});
if (!reusedId) throw new Error("Expected a child tab");
store.replaceTab(workspaceKey, reusedId, { kind: "agent", agentId: "other" });
store.setLayoutMode("compact");
const { result } = renderHook(() => useSubagentSheetTab(workspaceKey, "parent-tab")(row));
const sheetId = result.current?.tab.tabId;
expect(result.current?.tab.target).toEqual({ kind: "agent", agentId: "child" });
expect(sheetId).not.toBe(reusedId);
act(() => {
store.reconcileTabs(workspaceKey, {
agentsHydrated: true,
terminalsHydrated: true,
activeAgentIds: ["parent", "child"],
autoOpenAgentIds: [],
knownTerminalIds: [],
standaloneTerminalIds: [],
});
});
expect(store.getWorkspaceTabs(workspaceKey).map((tab) => tab.tabId)).not.toContain(reusedId);
expect(result.current?.tab.tabId).toBe(sheetId);
expect(result.current?.tab.target).toEqual({ kind: "agent", agentId: "child" });
});
it("promotes a menu sheet to the subagent's own tab", () => {
const row = seedParentWithChild();
const store = useWorkspaceLayoutStore.getState();
store.setLayoutMode("compact");
const { result } = renderHook(() => useSubagentSheetTab(workspaceKey, "parent-tab")(row));
const sheet = result.current;
if (!sheet) throw new Error("Expected a menu sheet");
let promotedId: string | null = null;
act(() => {
promotedId = store.openTabInFront(workspaceKey, sheet);
});
expect(promotedId).toBe("agent_child");
expect(
store.getWorkspaceTabs(workspaceKey).filter((tab) => tab.target.kind === "agent"),
).toEqual([
expect.objectContaining({
tabId: "agent_child",
target: { kind: "agent", agentId: "child" },
}),
]);
});
it("does not reuse a menu id retained by a promoted tab showing another target", () => {
const row = seedParentWithChild();
const store = useWorkspaceLayoutStore.getState();
store.setLayoutMode("compact");
const { result } = renderHook(() => useSubagentSheetTab(workspaceKey, "parent-tab")(row));
const sheet = result.current;
if (!sheet) throw new Error("Expected a menu sheet");
act(() => {
store.openTabInFront(workspaceKey, sheet);
});
expect(result.current).toBeNull();
act(() => {
store.replaceTab(workspaceKey, sheet.tab.tabId, { kind: "agent", agentId: "other" });
});
expect(result.current?.tab.target).toEqual({ kind: "agent", agentId: "child" });
expect(result.current?.tab.tabId).not.toBe(sheet.tab.tabId);
expect(
store.getWorkspaceTabs(workspaceKey).filter((tab) => tab.target.kind === "agent"),
).toEqual([
expect.objectContaining({
tabId: sheet.tab.tabId,
target: { kind: "agent", agentId: "other" },
}),
]);
});
it("hands a re-rendered row the same sheet", () => {
const row = seedParentWithChild();
useWorkspaceLayoutStore.getState().setLayoutMode("compact");
+10 -3
View File
@@ -4,6 +4,7 @@ import {
useWorkspaceLayoutStore,
type SheetTab,
} from "@/stores/workspace-layout-store";
import { buildDeterministicWorkspaceTabId } from "@/workspace-tabs/identity";
import type { WorkspaceTabTarget } from "@/workspace-tabs/model";
import type { SubagentRow } from "./select";
@@ -32,6 +33,9 @@ export function useSubagentSheetTab(
const sheets = useWorkspaceLayoutStore((state) =>
workspaceKey ? state.sheetsByWorkspace[workspaceKey] : undefined,
);
// Menu pages never enter the sheet stack. Each starts from the subagent's own tab id, so opening
// it as a tab lands on that id, and keeps the id it was given across layout updates.
const tabIds = useMemo(() => new Map<string, string>(), []);
return useMemo(() => {
// One answer per row until the state it reads changes, so a re-render of the list hands an
// open sheet the same tab rather than a fresh one.
@@ -43,16 +47,19 @@ export function useSubagentSheetTab(
layoutByWorkspace: layout ? { [workspaceKey]: layout } : {},
sheetsByWorkspace: sheets ? { [workspaceKey]: sheets } : {},
};
const key = `${row.kind}:${row.id}`;
const key = JSON.stringify([workspaceKey, parentTabId, row.kind, row.id]);
const known = answers.get(key);
if (known !== undefined) return known;
const target = subagentRowTarget(row);
const sheet = selectSheetTab(state, {
workspaceKey,
target: subagentRowTarget(row),
target,
parentTabId,
preferredTabId: tabIds.get(key) ?? buildDeterministicWorkspaceTabId(target),
});
if (sheet) tabIds.set(key, sheet.tab.tabId);
answers.set(key, sheet);
return sheet;
};
}, [layout, layoutMode, parentTabId, sheets, workspaceKey]);
}, [layout, layoutMode, parentTabId, sheets, tabIds, workspaceKey]);
}
@@ -5,9 +5,11 @@ import {
normalizeStoredHostProfile,
orderHostsLocalFirst,
pinRelayProtectedSecurityInProfiles,
readHostRegistry,
relayConnectionFromOffer,
resolveActiveHostServerId,
upsertHostConnectionInProfiles,
writeHostRegistry,
type HostConnection,
type HostProfile,
} from "./host-connection";
@@ -87,6 +89,25 @@ describe("normalizeStoredHostProfile", () => {
expect(profile?.connections[0]).not.toHaveProperty("password");
});
it("drops a connection kind this build doesn't know and keeps the host", () => {
const profile = normalizeStoredHostProfile({
serverId: "srv_mixed",
password: "secret",
connections: [
{ id: "future:1", type: "futureKind", address: "future.example.com" },
{ id: "direct:lan:6767", type: "directTcp", endpoint: "lan:6767", futureField: true },
{ id: "direct:remote:6767", type: "directTcp", endpoint: "remote:6767" },
],
preferredConnectionId: "direct:remote:6767",
});
expect(profile?.password).toBe("secret");
expect(profile?.connections).toEqual([
{ id: "direct:remote:6767", type: "directTcp", endpoint: "remote:6767", useTls: false },
]);
expect(profile?.preferredConnectionId).toBe("direct:remote:6767");
});
it("preserves legacy relay ids when TLS is absent", () => {
const profile = normalizeStoredHostProfile({
serverId: "srv_relay",
@@ -177,6 +198,59 @@ describe("normalizeStoredHostProfile", () => {
});
});
describe("readHostRegistry and writeHostRegistry", () => {
const direct: HostConnection = {
id: "direct:lan:6767",
type: "directTcp",
endpoint: "lan:6767",
useTls: false,
};
const future = { id: "future:1", type: "futureKind", address: "future.example.com" };
it("writes back every entry it could not read", () => {
const unreadableHost = { serverId: "srv_future", connections: [future] };
const hostWithFutureField = { serverId: "srv_field", connections: [direct], futureField: 1 };
const stored = [
{ ...makeHost("srv_a"), connections: [direct, future] },
unreadableHost,
hostWithFutureField,
"not a host",
];
const { hosts, unreadable } = readHostRegistry(stored);
expect(hosts.map((host) => host.serverId)).toEqual(["srv_a"]);
expect(hosts[0]?.connections).toEqual([direct]);
expect(writeHostRegistry(hosts, unreadable)).toEqual([
{ ...hosts[0], connections: [direct, future] },
unreadableHost,
hostWithFutureField,
"not a host",
]);
});
it("writes a host saved again by this build in place of the entry it could not read", () => {
const { hosts, unreadable } = readHostRegistry([{ serverId: "srv_a", connections: [future] }]);
expect(hosts).toEqual([]);
const saved = { ...makeHost("srv_a"), connections: [direct] };
expect(writeHostRegistry([saved], unreadable)).toEqual([saved]);
});
it("moves a stored direct TCP password to its host next to a connection it can't read", () => {
const registry = readHostRegistry([
{
serverId: "srv_legacy",
connections: [future, { type: "directTcp", endpoint: "lan:6767", password: "old-secret" }],
},
]);
expect(registry.movedConnectionPassword).toBe(true);
expect(registry.hosts[0]?.password).toBe("old-secret");
expect(registry.hosts[0]?.connections).toEqual([direct]);
});
});
describe("createRemoteSshHostConnection", () => {
it("keeps optional SSH settings absent", () => {
expect(createRemoteSshHostConnection({ host: "build-box" })).toEqual({
+102 -13
View File
@@ -522,12 +522,12 @@ const StoredHostProfileSchema = z.strictObject({
label: z.string().optional(),
appearance: HostAppearanceSchema.optional(),
lifecycle: z.strictObject({}).optional(),
connections: z.array(StoredHostConnectionSchema).min(1),
// Read one by one, so a connection kind another build wrote skips only that connection.
connections: z.array(z.unknown()).min(1),
preferredConnectionId: z.string().nullable().optional(),
createdAt: z.string().datetime({ offset: true }).optional(),
updatedAt: z.string().datetime({ offset: true }).optional(),
});
export const StoredHostRegistrySchema = z.array(StoredHostProfileSchema);
type StoredHostConnection = z.infer<typeof StoredHostConnectionSchema>;
function normalizeStoredConnection(connection: StoredHostConnection): HostConnection | null {
@@ -590,20 +590,37 @@ function normalizeStoredConnection(connection: StoredHostConnection): HostConnec
}
export function normalizeStoredHostProfile(entry: unknown): HostProfile | null {
return readStoredHost(entry)?.profile ?? null;
}
interface StoredHostRead {
profile: HostProfile;
unreadableConnections: unknown[];
movedConnectionPassword: boolean;
}
function readStoredHost(entry: unknown): StoredHostRead | null {
const result = StoredHostProfileSchema.safeParse(entry);
if (!result.success) {
return null;
}
const record = result.data;
const serverId = record.serverId;
const storedConnections: StoredHostConnection[] = [];
const unreadableConnections: unknown[] = [];
for (const stored of record.connections) {
const parsed = StoredHostConnectionSchema.safeParse(stored);
if (parsed.success) storedConnections.push(parsed.data);
else unreadableConnections.push(stored);
}
// COMPAT(connectionPassword): added in v0.9.1, remove after 2027-03-24 once stored direct passwords have migrated.
const legacyPassword = record.connections.find(
const legacyPassword = storedConnections.find(
(connection) => connection.type === "directTcp" && connection.password,
);
const password =
record.password ?? (legacyPassword?.type === "directTcp" ? legacyPassword.password : undefined);
const connections = record.connections
const connections = storedConnections
.map((connection) => normalizeStoredConnection(connection))
.filter((connection): connection is HostConnection => connection !== null);
if (connections.length === 0) {
@@ -620,18 +637,90 @@ export function normalizeStoredHostProfile(entry: unknown): HostProfile | null {
: (connections[0]?.id ?? null);
return {
serverId,
...(password ? { password } : {}),
label,
appearance: record.appearance ?? defaultHostAppearance(),
lifecycle: defaultLifecycle(),
connections,
preferredConnectionId,
createdAt: record.createdAt ?? now,
updatedAt: record.updatedAt ?? now,
profile: {
serverId,
...(password ? { password } : {}),
label,
appearance: record.appearance ?? defaultHostAppearance(),
lifecycle: defaultLifecycle(),
connections,
preferredConnectionId,
createdAt: record.createdAt ?? now,
updatedAt: record.updatedAt ?? now,
},
unreadableConnections,
movedConnectionPassword: legacyPassword !== undefined,
};
}
/**
* Stored registry entries this build can't read, such as a connection kind added by a newer
* build. `writeHostRegistry` writes them back so that build still finds them.
*/
export interface UnreadableHostEntries {
hosts: unknown[];
connectionsByServerId: Map<string, unknown[]>;
}
export function readHostRegistry(stored: unknown[]): {
hosts: HostProfile[];
unreadable: UnreadableHostEntries;
// COMPAT(connectionPassword): added in v0.9.1, remove after 2027-03-24 with stored-password migration.
movedConnectionPassword: boolean;
} {
const hosts: HostProfile[] = [];
const unreadable: UnreadableHostEntries = { hosts: [], connectionsByServerId: new Map() };
let movedConnectionPassword = false;
for (const entry of stored) {
const read = readStoredHost(entry);
if (!read) {
unreadable.hosts.push(entry);
continue;
}
hosts.push(read.profile);
if (read.unreadableConnections.length > 0) {
unreadable.connectionsByServerId.set(read.profile.serverId, read.unreadableConnections);
}
movedConnectionPassword ||= read.movedConnectionPassword;
}
return { hosts, unreadable, movedConnectionPassword };
}
export function writeHostRegistry(
hosts: HostProfile[],
unreadable: UnreadableHostEntries,
): unknown[] {
const savedServerIds = new Set(hosts.map((host) => host.serverId));
const written: unknown[] = hosts.map((host) => {
const kept = unreadable.connectionsByServerId.get(host.serverId);
return kept ? { ...host, connections: [...host.connections, ...kept] } : host;
});
for (const entry of unreadable.hosts) {
// A host this build saved again replaces the entry it couldn't read.
const serverId = readStoredServerId(entry);
if (serverId === null || !savedServerIds.has(serverId)) written.push(entry);
}
return written;
}
/** Drops the entries this build couldn't read for a host you removed. */
export function forgetUnreadableHost(
unreadable: UnreadableHostEntries,
serverId: string,
): UnreadableHostEntries {
const connectionsByServerId = new Map(unreadable.connectionsByServerId);
connectionsByServerId.delete(serverId);
return {
hosts: unreadable.hosts.filter((entry) => readStoredServerId(entry) !== serverId),
connectionsByServerId,
};
}
function readStoredServerId(entry: unknown): string | null {
if (typeof entry !== "object" || entry === null || !("serverId" in entry)) return null;
return typeof entry.serverId === "string" ? entry.serverId.trim() : null;
}
export function hostHasConnection(host: HostProfile, connection: HostConnection): boolean {
return host.connections.some((existing) => hostConnectionEquals(existing, connection));
}
+4 -4
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/cli",
"version": "0.16.0-beta.2",
"version": "0.16.0",
"description": "Paseo CLI - control your AI coding agents from the command line",
"license": "Apache-2.0",
"bin": {
@@ -29,9 +29,9 @@
},
"dependencies": {
"@clack/prompts": "^1.0.0",
"@getpaseo/client": "0.16.0-beta.2",
"@getpaseo/protocol": "0.16.0-beta.2",
"@getpaseo/server": "0.16.0-beta.2",
"@getpaseo/client": "0.16.0",
"@getpaseo/protocol": "0.16.0",
"@getpaseo/server": "0.16.0",
"chalk": "^5.3.0",
"commander": "^12.0.0",
"mime-types": "^2.1.35",
+2 -2
View File
@@ -47,7 +47,7 @@ export function addSendOptions(cmd: Command): Command {
.addOption(
new Option(
"--behavior <behavior>",
"Active-turn behavior (agent default: steer; otherwise: interrupt)",
"Active-turn behavior (agent default: steer waits for turn end; otherwise: interrupt)",
).choices(["interrupt", "steer"]),
)
.option("--no-wait", "Return immediately without waiting for completion");
@@ -218,7 +218,7 @@ export async function runSendCommand(
status: receipt.deliveryStatus ?? "sent",
message:
receipt.deliveryStatus === "queued"
? "Message queued for delivery after two quiet seconds"
? "Message queued for delivery after two quiet seconds and the current turn ends, unless interrupt was requested"
: "Message sent, not waiting for completion",
},
schema: agentSendSchema,
+3 -3
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/client",
"version": "0.16.0-beta.2",
"version": "0.16.0",
"description": "Paseo client SDK package",
"license": "Apache-2.0",
"files": [
@@ -49,8 +49,8 @@
"measure:diff-materialization": "tsx scripts/measure-diff-materialization.ts"
},
"dependencies": {
"@getpaseo/protocol": "0.16.0-beta.2",
"@getpaseo/relay": "0.16.0-beta.2",
"@getpaseo/protocol": "0.16.0",
"@getpaseo/relay": "0.16.0",
"ws": "^8.20.0",
"zod": "^4.4.3"
},
+1 -1
View File
@@ -449,7 +449,7 @@ test("a timed-out subscription rejects and cannot replay on reconnect", async ()
h.open();
await connecting;
const observation = h.client.observeAgents({ timeout: 10 });
await expect(observation.ready).rejects.toThrow(/timed out|timeout/i);
await expect(observation.ready).rejects.toMatchObject({ code: "DAEMON_REQUEST_TIMEOUT" });
await observation.release();
const reconnecting = h.client.connect();
h.open();
+50 -12
View File
@@ -1492,7 +1492,7 @@ test("keeps the transport connected when a session RPC ping times out", async ()
await connectPromise;
expect(client.getConnectionState().status).toBe("connected");
await expect(client.ping({ timeoutMs: 1 })).rejects.toThrow("Timeout waiting for message");
await expect(client.ping({ timeoutMs: 1 })).rejects.toThrow("No response to ping after");
expect(client.getConnectionState().status).toBe("connected");
});
@@ -1541,7 +1541,9 @@ test("bounds the wait for push token revocation", async () => {
await connectPromise;
const revocation = client.unregisterPushToken("ExponentPushToken[test-device]");
const rejection = expect(revocation).rejects.toThrow("Timeout waiting for message (2000ms)");
const rejection = expect(revocation).rejects.toThrow(
"No response to push.unregister.request after 2000ms",
);
await vi.advanceTimersByTimeAsync(1_999);
expect(client.getConnectionState().status).toBe("connected");
@@ -1550,6 +1552,30 @@ test("bounds the wait for push token revocation", async () => {
expect(client.getConnectionState().status).toBe("connected");
});
test("identifies the request when marking an agent as read times out", async () => {
useHeartbeatClock();
const transport = createMockTransport();
const client = new DaemonClient({
url: "ws://test",
clientId: "clsk_attention_timeout",
reconnect: { enabled: false },
transportFactory: () => transport.transport,
});
clients.push(client);
const connected = client.connect();
transport.triggerOpen();
await connected;
const outcome = client.clearAgentAttention("agent-1").catch((error: unknown) => error);
await vi.advanceTimersByTimeAsync(60_000);
expect(await outcome).toMatchObject({
name: "DaemonConnectionError",
code: "DAEMON_REQUEST_TIMEOUT",
message: "No response to clear_agent_attention after 60000ms",
});
expect(client.isConnected).toBe(true);
});
test("defaults session RPC waiters to sixty seconds", async () => {
useHeartbeatClock();
const logger = createMockLogger();
@@ -1594,7 +1620,7 @@ test("defaults session RPC waiters to sixty seconds", async () => {
expect(settled).toBe(false);
await vi.advanceTimersByTimeAsync(1);
await expect(responsePromise).rejects.toThrow("Timeout waiting for message (60000ms)");
await expect(responsePromise).rejects.toThrow("No response to fetch_agent_request after 60000ms");
});
test("honors explicit fetchAgent timeout below the session RPC default", async () => {
@@ -1642,7 +1668,7 @@ test("honors explicit fetchAgent timeout below the session RPC default", async (
expect(settled).toBe(false);
await vi.advanceTimersByTimeAsync(1);
await expect(responsePromise).rejects.toThrow("Timeout waiting for message (5000ms)");
await expect(responsePromise).rejects.toThrow("No response to fetch_agent_request after 5000ms");
});
test("preserves legacy fetchAgent id overload", async () => {
@@ -1806,7 +1832,9 @@ test("honors explicit fetchAgentTimeline timeout below the session RPC default",
expect(settled).toBe(false);
await vi.advanceTimersByTimeAsync(1);
await expect(responsePromise).rejects.toThrow("Timeout waiting for message (2000ms)");
await expect(responsePromise).rejects.toThrow(
"No response to fetch_agent_timeline_request after 2000ms",
);
});
test("lists the full agent prompt index", async () => {
@@ -1899,7 +1927,7 @@ test("honors explicit fetchAgents timeout below the session RPC default", async
expect(settled).toBe(false);
await vi.advanceTimersByTimeAsync(1);
await expect(responsePromise).rejects.toThrow("Timeout waiting for message (1200ms)");
await expect(responsePromise).rejects.toThrow("No response to fetch_agents_request after 1200ms");
});
test("honors explicit shutdownServer timeout below the session RPC default", async () => {
@@ -1945,7 +1973,9 @@ test("honors explicit shutdownServer timeout below the session RPC default", asy
expect(settled).toBe(false);
await vi.advanceTimersByTimeAsync(1);
await expect(responsePromise).rejects.toThrow("Timeout waiting for message (1500ms)");
await expect(responsePromise).rejects.toThrow(
"No response to shutdown_server_request after 1500ms",
);
});
test("honors explicit getDaemonStatus timeout below the session RPC default", async () => {
@@ -1991,7 +2021,9 @@ test("honors explicit getDaemonStatus timeout below the session RPC default", as
expect(settled).toBe(false);
await vi.advanceTimersByTimeAsync(1);
await expect(responsePromise).rejects.toThrow("Timeout waiting for message (1500ms)");
await expect(responsePromise).rejects.toThrow(
"No response to daemon.get_status.request after 1500ms",
);
});
test("honors explicit getDaemonPairingOffer timeout below the session RPC default", async () => {
@@ -2037,7 +2069,9 @@ test("honors explicit getDaemonPairingOffer timeout below the session RPC defaul
expect(settled).toBe(false);
await vi.advanceTimersByTimeAsync(1);
await expect(responsePromise).rejects.toThrow("Timeout waiting for message (1500ms)");
await expect(responsePromise).rejects.toThrow(
"No response to daemon.get_pairing_offer.request after 1500ms",
);
});
test("gates config reload on the daemon capability", async () => {
@@ -2443,7 +2477,9 @@ test("keeps enable and disable inside the session RPC deadline", async () => {
expect(settled).toBe(false);
await vi.advanceTimersByTimeAsync(1);
await expect(pending).rejects.toThrow("Timeout waiting for message (60000ms)");
await expect(pending).rejects.toThrow(
`No response to plugin.${action}.request after 60000ms`,
);
}
} finally {
vi.useRealTimers();
@@ -8619,7 +8655,9 @@ test("usage request timeout detaches its update listener", async () => {
const result = client.listUsageReports({ requestId: "timeout-usage" }, (report) =>
updates.push(report),
);
const rejected = expect(result).rejects.toThrow("Timeout waiting for message (60000ms)");
const rejected = expect(result).rejects.toThrow(
"No response to usage.list_reports.request after 60000ms",
);
await vi.advanceTimersByTimeAsync(60_001);
await rejected;
mock.triggerMessage(
@@ -9403,7 +9441,7 @@ test("RPC deadlines remain active while a preceding frame waits for drain", asyn
blocked = true;
const first = client.sendHostFrame("route", new Uint8Array([1]));
try {
await expect(client.ping({ timeoutMs: 20 })).rejects.toThrow("Timeout waiting for message");
await expect(client.ping({ timeoutMs: 20 })).rejects.toThrow("No response to ping after");
expect(client.isConnected).toBe(true);
} finally {
drain();
+6 -3
View File
@@ -483,7 +483,7 @@ export interface SendMessageOptions {
sourceAgentServerId?: string;
sessionMode?: string;
messageId?: string;
/** What happens when the agent is mid-turn. The daemon interrupts the turn when omitted. */
/** Agent sources wait for turn end unless interrupt is explicit. Human sources default to interrupt. */
activeTurnBehavior?: ActiveTurnBehavior;
images?: Array<{ data: string; mimeType: string }>;
attachments?: SendAgentMessageRequest["attachments"];
@@ -1023,6 +1023,7 @@ interface WaitHandle<T> {
interface WaitOptions {
skipQueue?: boolean;
requestId?: string;
requestType?: SessionInboundMessage["type"];
}
interface CorrelatedResponseIdentity {
@@ -2359,7 +2360,7 @@ export class DaemonClient {
return { kind: "ok", value };
},
timeout,
{ ...params.options, requestId: params.requestId },
{ ...params.options, requestId: params.requestId, requestType: params.message.type },
);
// The response deadline still applies while the transport waits for drain.
@@ -8107,7 +8108,9 @@ export class DaemonClient {
): WaitHandle<T> {
// Capture stack trace at call site, not inside setTimeout
const timeoutError = new DaemonConnectionError(
`Timeout waiting for message (${timeout}ms)`,
options?.requestType
? `No response to ${options.requestType} after ${timeout}ms`
: `Timeout waiting for message (${timeout}ms)`,
"DAEMON_REQUEST_TIMEOUT",
);
@@ -0,0 +1,64 @@
import type { Page } from "@playwright/test";
import { test, expect } from "../../app/e2e/support/fixtures";
import { gotoAppShell } from "../../app/e2e/support/helpers/app";
// Windows and Linux draw their window controls top-right, so the desktop sidebar has no
// chrome row of its own. Its window-drag surface is the strip above the navigation rows.
const CUSTOM_CHROME_HOSTS = [
{ platform: "linux", windowChromeMode: "custom-linux" },
{ platform: "win32", windowChromeMode: "custom-windows" },
] as const;
async function installDesktopHost(
page: Page,
host: (typeof CUSTOM_CHROME_HOSTS)[number],
): Promise<void> {
await page.addInitScript((desktopHost) => {
window.paseoDesktop = {
...desktopHost,
events: { on: () => () => {} },
invoke: async (command: string) => {
if (command === "get_desktop_settings") {
return {
releaseChannel: "stable",
daemon: { manageBuiltInDaemon: true, keepRunningAfterQuit: true },
};
}
return null;
},
};
}, host);
}
async function sidebarDragGeometry(page: Page) {
const navScroll = page.locator('[data-testid="sidebar-nav-scroll"]:visible').first();
await expect(navScroll).toBeVisible();
return navScroll.evaluate((node) => {
const nav = node.getBoundingClientRect();
const dragRegions = [];
for (const element of document.querySelectorAll<HTMLElement>("*")) {
if (getComputedStyle(element).getPropertyValue("-webkit-app-region") !== "drag") continue;
const rect = element.getBoundingClientRect();
const overSidebar = rect.left < nav.right && rect.right > nav.left;
if (overSidebar && rect.height > 0) dragRegions.push({ top: rect.top, bottom: rect.bottom });
}
return { navTop: nav.top, navBottom: nav.bottom, dragRegions };
});
}
for (const host of CUSTOM_CHROME_HOSTS) {
test.describe(`Desktop sidebar on ${host.platform}`, () => {
test.use({ viewport: { width: 1280, height: 480 } });
test("keeps a window drag strip above the scrolling navigation", async ({ page }) => {
await installDesktopHost(page, host);
await gotoAppShell(page);
const geometry = await sidebarDragGeometry(page);
expect(geometry.dragRegions).not.toEqual([]);
for (const region of geometry.dragRegions) {
expect(region.bottom).toBeLessThanOrEqual(geometry.navTop + 1);
}
});
});
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/desktop",
"version": "0.16.0-beta.2",
"version": "0.16.0",
"private": true,
"description": "Paseo desktop app (Electron wrapper)",
"homepage": "https://paseo.sh",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/expo-two-way-audio",
"version": "0.16.0-beta.2",
"version": "0.16.0",
"description": "Native module for two way audio streaming",
"keywords": [
"ExpoTwoWayAudio",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/highlight",
"version": "0.16.0-beta.2",
"version": "0.16.0",
"license": "Apache-2.0",
"files": [
"dist",
+5 -5
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/plugin",
"version": "0.16.0-beta.2",
"version": "0.16.0",
"description": "Paseo plugin SDK package",
"license": "Apache-2.0",
"files": [
@@ -78,8 +78,8 @@
"use-sync-external-store": "^1.6.0"
},
"devDependencies": {
"@getpaseo/client": "0.16.0-beta.2",
"@getpaseo/protocol": "0.16.0-beta.2",
"@getpaseo/client": "0.16.0",
"@getpaseo/protocol": "0.16.0",
"@types/node": "^20.9.0",
"@types/react": "~19.2.0",
"react": "19.2.3",
@@ -89,8 +89,8 @@
"zod": "^4.4.3"
},
"peerDependencies": {
"@getpaseo/client": "0.16.0-beta.2",
"@getpaseo/protocol": "0.16.0-beta.2",
"@getpaseo/client": "0.16.0",
"@getpaseo/protocol": "0.16.0",
"react": ">=19.1.0 <20",
"react-native": ">=0.81.5",
"zod": "^4.4.3"
+2
View File
@@ -88,6 +88,8 @@ export interface PluginSessionOpenRequest {
readonly background: boolean;
readonly labels: Readonly<Record<string, string>>;
readonly metadata: Readonly<Record<string, JsonValue>>;
/** Instructions appended for this open; not saved on the agent. */
appendSystemPrompt?: string[];
tools: AgentToolDefinition[];
env: Record<string, string>;
mcpServers: NonNullable<AgentSessionConfig["mcpServers"]>;
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/protocol",
"version": "0.16.0-beta.2",
"version": "0.16.0",
"description": "Paseo shared protocol schemas and wire types",
"license": "Apache-2.0",
"files": [
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/relay",
"version": "0.16.0-beta.2",
"version": "0.16.0",
"description": "Paseo relay for bridging daemon and client connections",
"license": "Apache-2.0",
"files": [
+6 -6
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/server",
"version": "0.16.0-beta.2",
"version": "0.16.0",
"description": "Paseo backend server",
"license": "Apache-2.0",
"files": [
@@ -109,11 +109,11 @@
"@agentclientprotocol/sdk": "^0.17.1",
"@anthropic-ai/claude-agent-sdk": "0.3.246",
"@anthropic-ai/sdk": "^0.104.2",
"@getpaseo/client": "0.16.0-beta.2",
"@getpaseo/highlight": "0.16.0-beta.2",
"@getpaseo/plugin": "0.16.0-beta.2",
"@getpaseo/protocol": "0.16.0-beta.2",
"@getpaseo/relay": "0.16.0-beta.2",
"@getpaseo/client": "0.16.0",
"@getpaseo/highlight": "0.16.0",
"@getpaseo/plugin": "0.16.0",
"@getpaseo/protocol": "0.16.0",
"@getpaseo/relay": "0.16.0",
"@isaacs/ttlcache": "^2.1.4",
"@modelcontextprotocol/sdk": "1.29.0",
"@opencode-ai/sdk": "1.14.46",
@@ -14,18 +14,19 @@ const BASE_RECORD: StoredAgentRecord = {
config: null,
};
const ARCHIVE = {
archivedAt: "2025-01-03T00:00:00.000Z",
updatedAt: "2025-01-03T00:00:00.000Z",
};
test("archives a stored agent without changing terminal statuses", () => {
const statuses: Array<StoredAgentRecord["lastStatus"]> = ["idle", "error", "closed"];
for (const status of statuses) {
const archived = buildArchivedAgentRecord(
{ ...BASE_RECORD, lastStatus: status },
{ archivedAt: "2025-01-03T00:00:00.000Z" },
);
const archived = buildArchivedAgentRecord({ ...BASE_RECORD, lastStatus: status }, ARCHIVE);
expect(archived.lastStatus).toBe(status);
expect(archived.archivedAt).toBe("2025-01-03T00:00:00.000Z");
expect(archived.updatedAt).toBe(BASE_RECORD.updatedAt);
}
});
@@ -33,10 +34,7 @@ test("archives busy stored agents as idle", () => {
const statuses: Array<StoredAgentRecord["lastStatus"]> = ["initializing", "running"];
for (const status of statuses) {
const archived = buildArchivedAgentRecord(
{ ...BASE_RECORD, lastStatus: status },
{ archivedAt: "2025-01-03T00:00:00.000Z" },
);
const archived = buildArchivedAgentRecord({ ...BASE_RECORD, lastStatus: status }, ARCHIVE);
expect(archived.lastStatus).toBe("idle");
}
@@ -50,7 +48,7 @@ test("clears persisted attention when archiving", () => {
attentionReason: "finished",
attentionTimestamp: "2025-01-02T12:00:00.000Z",
},
{ archivedAt: "2025-01-03T00:00:00.000Z" },
ARCHIVE,
);
expect(archived).toMatchObject({
@@ -60,11 +58,19 @@ test("clears persisted attention when archiving", () => {
});
});
test("can stamp updatedAt to the archive timestamp", () => {
const archived = buildArchivedAgentRecord(BASE_RECORD, {
archivedAt: "2025-01-03T00:00:00.000Z",
updatedAt: "2025-01-03T00:00:00.000Z",
});
test("moves updatedAt to the archive time", () => {
const archived = buildArchivedAgentRecord(BASE_RECORD, ARCHIVE);
expect(archived.updatedAt).toBe("2025-01-03T00:00:00.000Z");
});
test("keeps a later updatedAt when the archive time is earlier", () => {
// Putting an original archive back after a failed unarchive must not move updatedAt backwards.
const archived = buildArchivedAgentRecord(
{ ...BASE_RECORD, updatedAt: "2025-01-04T00:00:00.000Z" },
ARCHIVE,
);
expect(archived.archivedAt).toBe("2025-01-03T00:00:00.000Z");
expect(archived.updatedAt).toBe("2025-01-04T00:00:00.000Z");
});
@@ -3,19 +3,19 @@ import type { StoredAgentRecord } from "./agent-storage.js";
export type ArchivedStoredAgentRecord = StoredAgentRecord & { archivedAt: string };
interface BuildArchivedAgentRecordOptions {
archivedAt?: string;
updatedAt?: string;
archivedAt: string;
/** When this archive happened. Re-archiving keeps the original archivedAt but still records it. */
updatedAt: string;
}
export function buildArchivedAgentRecord(
record: StoredAgentRecord,
options?: BuildArchivedAgentRecordOptions,
options: BuildArchivedAgentRecordOptions,
): ArchivedStoredAgentRecord {
const archivedAt = options?.archivedAt ?? new Date().toISOString();
return {
...record,
archivedAt,
updatedAt: options?.updatedAt ?? record.updatedAt,
archivedAt: options.archivedAt,
updatedAt: latestTimestamp(record.updatedAt, options.updatedAt),
lastStatus: normalizeArchivedStatus(record.lastStatus),
requiresAttention: false,
attentionReason: null,
@@ -23,6 +23,13 @@ export function buildArchivedAgentRecord(
};
}
// Archiving is the agent's latest change. An earlier archive time (an original archive put back
// after a failed unarchive) keeps the newer updatedAt, since clients drop an agent update that is
// older than the one they hold.
function latestTimestamp(current: string, archiveTime: string): string {
return Date.parse(archiveTime) > Date.parse(current) ? archiveTime : current;
}
function normalizeArchivedStatus(
status: StoredAgentRecord["lastStatus"],
): StoredAgentRecord["lastStatus"] {
@@ -26,7 +26,8 @@ import { buildStoredAgentPayload, toAgentPayload } from "./agent-projections.js"
import type { ProviderOptions } from "@getpaseo/protocol/agent-types";
import { projectTimelineRows } from "./timeline-projection.js";
import { getOpenAgentTabLabel, PARENT_AGENT_ID_LABEL } from "@getpaseo/protocol/agent-labels";
import { startAgentRun } from "./agent-prompt.js";
import { createAgentMessageDelivery } from "./agent-messages/index.js";
import { AgentTurnBusyError, sendPreparedPromptToAgent, startAgentRun } from "./agent-prompt.js";
import { StaleProviderSessionError } from "./stale-provider-session-error.js";
import { ensureAgentLoaded, ensureUnarchivedAgentLoaded } from "./agent-loading.js";
import type { StoredAgentRecord } from "./agent-storage.js";
@@ -673,6 +674,48 @@ async function startAndSteerThroughManager(
return { manager, agentId: agent.id, workdir };
}
test("OpenCode persistence excludes launch-only instructions from storage and clients", async () => {
const workdir = mkdtempSync(join(tmpdir(), "agent-plugin-persistence-"));
const harness = new V2Harness();
harness.info.location.directory = workdir;
const storage = new AgentStorage(join(workdir, "agents"), logger);
const client = new OpenCodeV2AgentClient({ logger, runtime: harness.runtime });
const manager = new AgentManager({
clients: { opencode: client },
registry: storage,
logger,
appendSystemPrompt: "Daemon instruction",
pluginLifecycle: {
emit: () => {},
before: async (name, request) =>
name === "agent.open.before"
? { ...request, appendSystemPrompt: ["Plugin instruction"] }
: request,
},
});
const agent = await manager.createAgent({ provider: "opencode", cwd: workdir }, undefined, {
workspaceId: undefined,
});
try {
expect(harness.instructions.get("paseo")).toBe("Daemon instruction\n\nPlugin instruction");
await manager.flush();
const record = await storage.get(agent.id);
expect(record?.persistence?.metadata).not.toHaveProperty("pluginAppendSystemPrompt");
expect(record?.persistence?.metadata).not.toHaveProperty("daemonAppendSystemPrompt");
const live = manager.getAgent(agent.id)!;
expect(toAgentPayload(live).persistence?.metadata).not.toHaveProperty(
"pluginAppendSystemPrompt",
);
expect(toAgentPayload(live).persistence?.metadata).not.toHaveProperty(
"daemonAppendSystemPrompt",
);
} finally {
await manager.closeAgent(agent.id);
await client.shutdown();
rmSync(workdir, { recursive: true, force: true });
}
});
test("stops an OpenCode execution already active when its conversation is reopened", async () => {
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-opencode-resume-"));
onTestFinished(() => rmSync(workdir, { recursive: true, force: true }));
@@ -6451,6 +6494,114 @@ test("archiveSnapshot dispatches archived state for stored-only agents", async (
expect(last.lifecycle).toBe("closed");
});
test("archiveSnapshot moves a stored-only agent's updatedAt to its archive time, as a live archive does", async () => {
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-archive-snapshot-updated-at-"));
const storage = new AgentStorage(join(workdir, "agents"), logger);
const manager = new AgentManager({
clients: { codex: new TestAgentClient() },
registry: storage,
logger,
});
const created = await manager.createAgent(
{ provider: "codex", cwd: workdir, title: "Stored archive updatedAt" },
undefined,
{ workspaceId: undefined },
);
await manager.closeAgent(created.id);
const before = await storage.get(created.id);
expect(before?.updatedAt).toEqual(expect.any(String));
// Later than anything the agent did: lists sorted by updated_at put it first, as they do
// for an agent archived while loaded.
const archivedAt = new Date(Date.parse(before!.updatedAt) + 60_000).toISOString();
const archived = await manager.archiveSnapshot(created.id, archivedAt);
expect(archived.updatedAt).toBe(archivedAt);
expect((await storage.get(created.id))?.updatedAt).toBe(archivedAt);
});
test("archiveSnapshot restoring an earlier archive time keeps updatedAt at the unarchive", async () => {
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-archive-snapshot-restore-"));
const storage = new AgentStorage(join(workdir, "agents"), logger);
const manager = new AgentManager({
clients: { codex: new TestAgentClient() },
registry: storage,
logger,
});
const created = await manager.createAgent(
{ provider: "codex", cwd: workdir, title: "Restore archive updatedAt" },
undefined,
{ workspaceId: undefined },
);
await manager.closeAgent(created.id);
const originalArchivedAt = (await manager.archiveSnapshot(created.id, new Date().toISOString()))
.archivedAt!;
await new Promise((resolve) => setTimeout(resolve, 5));
await manager.unarchiveSnapshot(created.id);
const unarchivedAt = (await storage.get(created.id))!.updatedAt;
const events: ManagedAgent[] = [];
manager.subscribe(
(event) => {
if (event.type === "agent_state" && event.agent.id === created.id) {
events.push(event.agent);
}
},
{ agentId: created.id, replayState: false },
);
// A send that could not load the agent puts its original archive back.
await manager.archiveSnapshot(created.id, originalArchivedAt);
// Clients keep the newer of two updates, so an older updatedAt would leave them showing it active.
const stored = await storage.get(created.id);
expect(stored?.archivedAt).toBe(originalArchivedAt);
expect(stored?.updatedAt).toBe(unarchivedAt);
expect(events.at(-1)?.updatedAt.toISOString()).toBe(unarchivedAt);
});
test("archiveSnapshot restoring an earlier archive time on a loaded agent keeps updatedAt at the unarchive", async () => {
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-archive-snapshot-restore-loaded-"));
const storage = new AgentStorage(join(workdir, "agents"), logger);
const manager = new AgentManager({
clients: { codex: new TestAgentClient() },
registry: storage,
logger,
});
const created = await manager.createAgent(
{ provider: "codex", cwd: workdir, title: "Restore loaded archive updatedAt" },
undefined,
{ workspaceId: undefined },
);
const { archivedAt: originalArchivedAt } = await manager.archiveAgent(created.id);
await new Promise((resolve) => setTimeout(resolve, 5));
await manager.unarchiveSnapshot(created.id);
const unarchivedAt = Date.parse((await storage.get(created.id))!.updatedAt);
// The send resumed the agent before a later loading step failed, so it is still loaded.
await ensureAgentLoaded(created.id, { agentManager: manager, agentStorage: storage, logger });
expect(manager.getAgent(created.id)).not.toBeNull();
const events: ManagedAgent[] = [];
manager.subscribe(
(event) => {
if (event.type === "agent_state" && event.agent.id === created.id) {
events.push(event.agent);
}
},
{ agentId: created.id, replayState: false },
);
await manager.archiveSnapshot(created.id, originalArchivedAt);
const stored = await storage.get(created.id);
expect(stored?.archivedAt).toBe(originalArchivedAt);
expect(Date.parse(stored!.updatedAt)).toBeGreaterThanOrEqual(unarchivedAt);
expect(events.at(-1)?.updatedAt.getTime()).toBeGreaterThanOrEqual(unarchivedAt);
});
test("markAgentUnread restores error attention on a read errored agent", async () => {
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-mark-unread-error-"));
const storage = new AgentStorage(join(workdir, "agents"), logger);
@@ -12345,11 +12496,18 @@ test("authoritative timeline records a daemon-handled submitted prompt before it
test("tryRunOutOfBand gives providers the command another agent sent, not its envelope", async () => {
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-agent-out-of-band-"));
const seenPrompts: AgentPromptInput[] = [];
const acceptanceOrder: string[] = [];
class SlashCommandSession extends TestAgentSession {
override tryHandleOutOfBand(prompt: AgentPromptInput) {
seenPrompts.push(prompt);
return prompt === "/handled" ? { run: async () => {} } : null;
return prompt === "/handled"
? {
run: async () => {
acceptanceOrder.push("run");
},
}
: null;
}
}
const client = new (class extends TestAgentClient {
@@ -12364,12 +12522,22 @@ test("tryRunOutOfBand gives providers the command another agent sent, not its en
try {
const fromAgent = prepareAgentMessage("/handled", { kind: "agent-message", agentId: "sender" });
expect(await manager.tryRunOutOfBand(agent.id, fromAgent.prompt)).toBe(true);
expect(
await manager.tryRunOutOfBand(agent.id, fromAgent.prompt, undefined, () => {
acceptanceOrder.push("accepted");
}),
).toBe(true);
await vi.waitFor(() => expect(acceptanceOrder).toEqual(["accepted", "run"]));
expect(seenPrompts).toEqual(["/handled"]);
// A human who pastes an envelope gets it quoted, and it stays a plain prompt.
const pasted = prepareAgentMessage(String(fromAgent.prompt));
expect(await manager.tryRunOutOfBand(agent.id, pasted.prompt)).toBe(false);
expect(
await manager.tryRunOutOfBand(agent.id, pasted.prompt, undefined, () => {
acceptanceOrder.push("unexpected");
}),
).toBe(false);
expect(acceptanceOrder).toEqual(["accepted", "run"]);
expect(seenPrompts.at(-1)).toBe(pasted.prompt);
} finally {
await manager.closeAgent(agent.id);
@@ -13532,6 +13700,33 @@ test("the last assistant message is the newest turn's reply, not joined to the p
}
});
test("the last assistant message read from rebuilt history is the newest reply, not joined to the one before it", async () => {
// Rows replayed from provider history have no turn id. A reply the agent starts on its own,
// such as Claude waking after a background subagent, follows the previous reply with no user
// message between them; only their message ids tell them apart.
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-history-last-reply-"));
const codex = fakeCodexEmitting({
historyItems: [
{ type: "user_message", text: "Start a background task.", messageId: "user-1" },
{ type: "assistant_message", text: "Started it, ", messageId: "message-1" },
{ type: "assistant_message", text: "I will report back.", messageId: "message-1" },
{ type: "assistant_message", text: "The task finished.", messageId: "message-2" },
],
});
const manager = new AgentManager({ clients: { codex }, logger });
const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
workspaceId: undefined,
});
try {
await manager.hydrateTimelineFromProvider(agent.id, { force: true });
expect(await manager.getLastAssistantMessage(agent.id)).toBe("The task finished.");
} finally {
await manager.closeAgent(agent.id);
rmSync(workdir, { recursive: true, force: true });
}
});
test("reads the last durable assistant response without loading a stored-only child", async () => {
const store = new RecordingTimelineStore();
await store.appendCommitted("stored-child", {
@@ -14519,14 +14714,16 @@ test("workspace archive preserves a loaded history agent stamp and stamps cascad
labels: { [PARENT_AGENT_ID_LABEL]: parent.id },
workspaceId: undefined,
});
const stamp = "2026-11-09T00:00:00.000Z";
// Archive stamps are taken when the archive happens, so they follow the agents' activity.
const stamp = new Date(Date.now() + 60_000).toISOString();
const laterStamp = new Date(Date.now() + 120_000).toISOString();
await manager.archiveAgent(parent.id, stamp);
expect((await storage.get(parent.id))?.archivedAt).toBe(stamp);
expect((await storage.get(child.id))?.archivedAt).toBe(stamp);
await ensureAgentLoaded(parent.id, { agentManager: manager, agentStorage: storage, logger });
await manager.archiveAgent(parent.id, "2026-11-09T01:00:00.000Z");
await manager.archiveAgent(parent.id, laterStamp);
expect((await storage.get(parent.id))?.archivedAt).toBe(stamp);
expect((await storage.get(parent.id))?.updatedAt).toBe("2026-11-09T01:00:00.000Z");
expect((await storage.get(parent.id))?.updatedAt).toBe(laterStamp);
} finally {
await storage.flush();
rmSync(workdir, { recursive: true, force: true });
@@ -14568,3 +14765,309 @@ test("idle cleanup gives a newly restored runtime a fresh idle window while keep
expect((await h.sweep({ now: h.later(61) })).collected).toHaveLength(1);
expect(h.closes).toBe(closesBeforeRestore + 1);
});
test.each([
["supported", "turn_completed"],
["supported", "turn_canceled"],
["supported", "turn_failed"],
["unsupported", "turn_completed"],
["unsupported", "turn_canceled"],
["unsupported", "turn_failed"],
] as const)(
"queued delivery after %s provider %s never steers or interrupts",
async (support, ending) => {
const workdir = mkdtempSync(join(tmpdir(), "agent-queued-terminal-"));
const session =
support === "supported"
? new SteeringTestSession({ provider: "codex", cwd: workdir })
: new UnsupportedSteeringSession({ provider: "codex", cwd: workdir });
const client = new (class extends TestAgentClient {
override async createSession(): Promise<AgentSession> {
return session;
}
})();
const manager = new AgentManager({ clients: { codex: client }, logger });
const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
workspaceId: undefined,
});
let tick = () => {};
const delivery = createAgentMessageDelivery({
isRunning: (id) => manager.hasInFlightRun(id),
subscribe: (notify) =>
manager.subscribe(
(event) => {
if (event.type === "agent_state") notify(event.agent.id);
},
{ replayState: false },
),
schedule: (_delay, callback) => {
tick = callback;
return () => {};
},
dispatch: async (request) =>
(
await startAgentRun(manager, agent.id, request.prompt, logger, {
idleOnly: request.idleOnly,
replaceRunning: true,
activeTurnBehavior: request.activeTurnBehavior,
})
).disposition,
onError: (error) => {
throw error;
},
});
const providerStarted = new Promise<void>((resolve) => {
const unsubscribe = session.subscribe((event) => {
if (event.type === "turn_started") {
unsubscribe();
resolve();
}
});
});
try {
await startAgentRun(manager, agent.id, "original", logger);
await manager.waitForAgentRunStart(agent.id);
const receipt = delivery.enqueue({
recipientId: agent.id,
prompt: "queued",
source: { kind: "agent-message", agentId: "child" },
});
tick();
expect(session.startCount).toBe(1);
expect(session.interruptCount).toBe(0);
const turnId = support === "supported" ? "active-turn-1" : "unsupported-turn-1";
await providerStarted;
session.pushEvent({
type: ending,
provider: "codex",
turnId,
...(ending === "turn_failed" ? { error: "test failure" } : {}),
} as AgentStreamEvent);
await receipt.dispatched;
await manager.waitForAgentRunStart(agent.id);
expect(session.startCount).toBe(2);
expect(session.interruptCount).toBe(0);
} finally {
await delivery.close();
await manager.closeAgent(agent.id);
rmSync(workdir, { recursive: true, force: true });
}
},
);
test.each(["turn_completed", "turn_failed", "turn_canceled"] as const)(
"an autonomous %s publishes readiness after settling its run",
async (ending) => {
const workdir = mkdtempSync(join(tmpdir(), "agent-autonomous-delivery-"));
const session = new SteeringTestSession({ provider: "codex", cwd: workdir });
const client = new (class extends TestAgentClient {
override async createSession(): Promise<AgentSession> {
return session;
}
})();
const manager = new AgentManager({ clients: { codex: client }, logger });
const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
workspaceId: undefined,
});
let tick = () => {};
const settledStates: boolean[] = [];
const delivery = createAgentMessageDelivery({
isRunning: (id) => manager.hasInFlightRun(id),
subscribe: (notify) =>
manager.subscribe(
(event) => {
if (event.type !== "agent_state") return;
if (event.agent.lifecycle !== "running")
settledStates.push(manager.hasInFlightRun(agent.id));
notify(event.agent.id);
},
{ agentId: agent.id, replayState: false },
),
schedule: (_delay, callback) => {
tick = callback;
return () => {};
},
dispatch: async (request) =>
(
await startAgentRun(manager, agent.id, request.prompt, logger, {
idleOnly: request.idleOnly,
})
).disposition,
onError: (error) => {
throw error;
},
});
try {
session.pushEvent({ type: "turn_started", provider: "codex", turnId: "autonomous" });
await vi.waitFor(() => expect(manager.hasInFlightRun(agent.id)).toBe(true));
delivery.enqueue({
recipientId: agent.id,
prompt: "queued report",
source: { kind: "agent-message", agentId: "child" },
});
tick();
expect(session.startCount).toBe(0);
session.pushEvent({
type: ending,
provider: "codex",
turnId: "autonomous",
...(ending === "turn_failed" ? { error: "test failure" } : {}),
} as AgentStreamEvent);
await new Promise<void>((resolve) => setImmediate(resolve));
expect(settledStates).toEqual([false]);
expect(session.startCount).toBe(1);
} finally {
await delivery.close();
await manager.closeAgent(agent.id);
rmSync(workdir, { recursive: true, force: true });
}
},
);
test("an idle-only prompt rejects a busy recipient before changing its mode", async () => {
const workdir = mkdtempSync(join(tmpdir(), "agent-queued-mode-"));
class ModeSession extends SteeringTestSession {
mode = "plan";
applied: string[] = [];
startedModes: string[] = [];
override async setMode(mode?: string) {
if (!mode) throw new Error("Mode required");
this.mode = mode;
this.applied.push(mode);
}
override async getCurrentMode() {
return this.mode;
}
override async startTurn(prompt: AgentPromptInput) {
this.startedModes.push(this.mode);
return super.startTurn(prompt);
}
}
const session = new ModeSession({ provider: "codex", cwd: workdir });
const client = new (class extends TestAgentClient {
override async createSession(): Promise<AgentSession> {
return session;
}
})();
const storage = new AgentStorage(join(workdir, "agents"), logger);
const manager = new AgentManager({ clients: { codex: client }, registry: storage, logger });
const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
workspaceId: undefined,
});
await manager.setAgentMode(agent.id, "plan");
session.applied.length = 0;
const providerStarted = new Promise<void>((resolve) => {
const unsubscribe = session.subscribe((event) => {
if (event.type === "turn_started") {
unsubscribe();
resolve();
}
});
});
const startOther = async () => {
await startAgentRun(manager, agent.id, "other turn", logger);
await manager.waitForAgentRunStart(agent.id);
};
try {
await startOther();
await expect(
sendPreparedPromptToAgent({
agentManager: manager,
agentStorage: storage,
agentId: agent.id,
prompt: "queued follow-up",
sessionMode: "full-access",
idleOnly: true,
logger,
}),
).rejects.toBeInstanceOf(AgentTurnBusyError);
expect(session.mode).toBe("plan");
expect(session.applied).toEqual([]);
expect(session.startedModes).toEqual(["plan"]);
await providerStarted;
session.pushEvent({ type: "turn_completed", provider: "codex", turnId: "active-turn-1" });
await vi.waitFor(() => expect(manager.hasInFlightRun(agent.id)).toBe(false));
await sendPreparedPromptToAgent({
agentManager: manager,
agentStorage: storage,
agentId: agent.id,
prompt: "queued follow-up",
sessionMode: "full-access",
idleOnly: true,
logger,
});
await manager.waitForAgentRunStart(agent.id);
expect(session.mode).toBe("full-access");
expect(session.applied).toEqual(["full-access"]);
expect(session.startedModes).toEqual(["plan", "full-access"]);
} finally {
await manager.closeAgent(agent.id);
rmSync(workdir, { recursive: true, force: true });
}
});
test("plugin instructions are recomputed for each launch without changing saved config", async () => {
const workdir = mkdtempSync(join(tmpdir(), "agent-plugin-prompt-"));
const storage = new AgentStorage(join(workdir, "agents"), logger);
const client = new TestAgentClient();
let additions = ["Plugin one", "Plugin two"];
const manager = new AgentManager({
clients: { codex: client },
registry: storage,
logger,
appendSystemPrompt: "Daemon",
pluginLifecycle: {
emit: () => {},
before: async (name, request) =>
name === "agent.open.before" ? { ...request, appendSystemPrompt: additions } : request,
},
});
const snapshot = await manager.createAgent(
{ provider: "codex", cwd: workdir, systemPrompt: "Saved" },
undefined,
{ workspaceId: undefined },
);
expect(client.createdConfigs[0]).toMatchObject({
systemPrompt: "Saved",
daemonAppendSystemPrompt: "Daemon",
pluginAppendSystemPrompt: ["Plugin one", "Plugin two"],
});
expect(snapshot.config.systemPrompt).toBe("Saved");
expect((await storage.get(snapshot.id))?.config?.systemPrompt).toBe("Saved");
const handle: AgentPersistenceHandle = {
provider: "codex",
sessionId: "prompt-session",
metadata: { provider: "codex", cwd: workdir, systemPrompt: "Saved" },
};
await manager.closeAgent(snapshot.id);
await manager.resumeAgentFromPersistence(
handle,
{ cwd: workdir, systemPrompt: "Saved" },
snapshot.id,
);
expect(client.resumeOverrides.at(-1)?.pluginAppendSystemPrompt).toEqual([
"Plugin one",
"Plugin two",
]);
additions = ["Changed"];
await manager.closeAgent(snapshot.id);
await manager.resumeAgentFromPersistence(
handle,
{ cwd: workdir, systemPrompt: "Saved" },
snapshot.id,
);
expect(client.resumeOverrides.at(-1)?.pluginAppendSystemPrompt).toEqual(["Changed"]);
additions = ["Refreshed"];
await manager.reloadAgentSession(snapshot.id);
expect(client.resumeOverrides.at(-1)?.pluginAppendSystemPrompt).toEqual(["Refreshed"]);
additions = [];
await manager.closeAgent(snapshot.id);
await manager.resumeAgentFromPersistence(
handle,
{ cwd: workdir, systemPrompt: "Saved" },
snapshot.id,
);
expect(client.resumeOverrides.at(-1)?.systemPrompt).toBe("Saved");
expect(client.resumeOverrides.at(-1)?.daemonAppendSystemPrompt).toBe("Daemon");
expect((await storage.get(snapshot.id))?.config?.systemPrompt).toBe("Saved");
});
@@ -3,7 +3,7 @@ import { ProviderOptionsValidationError } from "./provider-options.js";
import type { AgentToolResult } from "@getpaseo/plugin/server";
import type { RuntimeCleanupCandidate } from "./idle-runtime-cleanup/index.js";
import { AgentNotFoundError, ensureAgentLoaded } from "./agent-loading.js";
import { projectTimelineRows } from "./timeline-projection.js";
import { continuesAssistantMessage, projectTimelineRows } from "./timeline-projection.js";
import type { PluginLifecycle } from "../plugins/lifecycle/index.js";
import { describeHookAgent, publishAgentStream } from "../plugins/lifecycle/index.js";
import { applyRecordPatch } from "../record-patch.js";
@@ -634,7 +634,12 @@ function normalizePersistenceForConfig(
if (!handle) {
return null;
}
const { mcpServers: _launchMcpServers, ...metadata } = handle.metadata ?? {};
const {
mcpServers: _launchMcpServers,
pluginAppendSystemPrompt: _pluginAppendSystemPrompt,
daemonAppendSystemPrompt: _daemonAppendSystemPrompt,
...metadata
} = handle.metadata ?? {};
return {
...handle,
metadata: {
@@ -1117,6 +1122,10 @@ export class AgentManager {
return new Date(nextMs).toISOString();
}
hasPendingPermissions(agentId: string): boolean {
return (this.agents.get(agentId)?.pendingPermissions.size ?? 0) > 0;
}
hasInFlightRun(agentId: string): boolean {
const agent = this.agents.get(agentId);
if (!agent) {
@@ -1727,7 +1736,10 @@ export class AgentManager {
...(record ? { metadata: record.metadata, attention: extractAttention(record) } : {}),
workspaceId,
launchEnv,
persistence: handle,
persistence:
purpose === "interactive" && session.persistenceUpdatedOnResume
? (session.describePersistence() ?? handle)
: handle,
restoring: true,
});
}
@@ -2338,7 +2350,7 @@ export class AgentManager {
private async persistArchivedRecord(
record: StoredAgentRecord,
options: { archivedAt: string; updatedAt?: string },
options: { archivedAt: string; updatedAt: string },
): Promise<ArchivedStoredAgentRecord> {
const archivedRecord = buildArchivedAgentRecord(record, options);
await this.requireRegistry().upsert(archivedRecord);
@@ -2858,7 +2870,11 @@ export class AgentManager {
throw new Error(`Agent not found: ${agentId}`);
}
const nextRecord = await this.persistArchivedRecord(record, { archivedAt });
// Archiving is the agent's latest change, as markRecordArchived records it for a loaded agent.
const nextRecord = await this.persistArchivedRecord(record, {
archivedAt,
updatedAt: archivedAt,
});
await this.syncNativeArchiveState(record.provider, record.persistence, "archive");
@@ -3030,6 +3046,7 @@ export class AgentManager {
agentId: string,
prompt: AgentPromptInput,
options?: AgentRunOptions,
onAccepted?: () => void,
): Promise<boolean> {
if (this.collectingRuntimes.has(agentId) || !this.agents.has(agentId)) {
await this.waitForAgentClose(agentId);
@@ -3049,6 +3066,7 @@ export class AgentManager {
if (!handler) {
return false;
}
onAccepted?.();
this.touchUpdatedAt(agent);
if (options?.clientMessageId) {
this.recordSubmittedPrompt(agent, prompt, options.clientMessageId, "accepted");
@@ -4058,24 +4076,16 @@ export class AgentManager {
private getLastAssistantMessageSegmentFromTimeline(
timeline: readonly Pick<AgentTimelineRow, "item" | "turnId">[],
): { text: string; startsAtBeginning: boolean } | null {
// Collect the last contiguous assistant messages of one turn (Claude streams chunks).
// A turn the provider starts on its own has no user message before its reply.
// Collect the chunks of the last assistant message (Claude streams chunks). A turn the
// provider starts on its own has no user message before its reply.
const chunks: string[] = [];
let replyTurnId: string | undefined;
let startsAtBeginning = false;
for (let i = timeline.length - 1; i >= 0; i--) {
const { item, turnId } = timeline[i];
if (item.type !== "assistant_message") {
if (chunks.length) {
break;
}
continue;
}
if (chunks.length === 0) {
replyTurnId = turnId;
} else if (turnId !== replyTurnId) {
const { item } = timeline[i];
if (chunks.length > 0 && !continuesAssistantMessage(timeline[i], timeline[i + 1])) {
break;
}
if (item.type !== "assistant_message") continue;
chunks.push(item.text);
startsAtBeginning = i === 0;
}
@@ -5121,6 +5131,9 @@ export class AgentManager {
this.runs.settleTerminalRun(agent.id, eventTurnId);
if (isForegroundEvent) {
this.finalizeForegroundTurn(agent, eventTurnId);
} else if (terminalDisposition !== "stale" && !agent.activeForegroundTurnId) {
// Publish autonomous readiness only after the tracked run has settled.
this.emitState(agent);
}
}
@@ -5390,7 +5403,6 @@ export class AgentManager {
!agent.pendingReplacement
) {
(agent as ActiveManagedAgent).lifecycle = "idle";
this.emitState(agent);
}
void this.refreshRuntimeInfo(agent);
}
@@ -5431,9 +5443,6 @@ export class AgentManager {
options,
);
this.resolvePendingPermissionsForAgent(agent, event.provider, options, "Turn failed");
if (!isForegroundEvent && !agent.activeForegroundTurnId) {
this.emitState(agent);
}
}
private onStreamTurnCanceled(params: {
@@ -5467,9 +5476,6 @@ export class AgentManager {
}
agent.lastError = undefined;
this.resolvePendingPermissionsForAgent(agent, event.provider, options, "Interrupted");
if (!isForegroundEvent && !agent.activeForegroundTurnId) {
this.emitState(agent);
}
}
private onStreamTurnStarted(params: {
@@ -6179,6 +6185,7 @@ export class AgentManager {
// A plugin changing during this open must still make the resulting session stale.
const generation = this.sessionOpenGeneration;
this.detachPluginTools(agentId);
let appendSystemPrompt: string[] | undefined;
let mcpServers: AgentSessionConfig["mcpServers"];
let mcpServerOwners: Record<string, string> | undefined;
if (this.pluginLifecycle) {
@@ -6200,12 +6207,14 @@ export class AgentManager {
env = transformed.env;
if (request.purpose === "interactive") {
this.attachedPluginTools.set(agentId, transformed.tools as AttachedAgentTool[]);
appendSystemPrompt = transformed.appendSystemPrompt;
mcpServers = transformed.mcpServers;
mcpServerOwners = transformed.mcpServerOwners;
}
}
const context: AgentLaunchContext = {
agentId,
...pluginPromptContext(appendSystemPrompt),
mcpServers,
mcpServerOwners,
env: {
@@ -6252,6 +6261,7 @@ export class AgentManager {
throw new Error(`MCP server '${name}' from plugin ${owner} collides with ${existingOwner}`);
}
}
launchConfig = { ...launchConfig, pluginAppendSystemPrompt: launchContext.appendSystemPrompt };
const merged =
Object.keys(launchContext.mcpServers ?? {}).length > 0
? {
@@ -6389,3 +6399,9 @@ export function commandMayHaveChangedExternalState(command: string): boolean {
/\bgit\s+fetch\b/.test(normalized)
);
}
function pluginPromptContext(
appendSystemPrompt: string[] | undefined,
): Pick<AgentLaunchContext, "appendSystemPrompt"> {
return appendSystemPrompt?.length ? { appendSystemPrompt } : {};
}
@@ -1,3 +1,4 @@
import { AgentTurnBusyError } from "../agent-prompt.js";
import { expect, test } from "vitest";
import { createAgentMessageDelivery, parseAgentMessages } from "./index.js";
import type { AgentPromptInput } from "../agent-sdk-types.js";
@@ -117,7 +118,6 @@ test("explicit interrupt and conflicting session modes retain ordered dispatch b
const delivery = createAgentMessageDelivery({
dispatch: async (request) => {
sent.push(request);
request.onDispatch("steered");
return "steered";
},
onError: (error) => {
@@ -313,3 +313,555 @@ test("runtime safety sees queued messages until provider dispatch settles", asyn
await delivery.close();
expect(delivery.hasPending("parent")).toBe(false);
});
test("messages wait across quiet windows and batch after the recipient turn ends", async () => {
const clock = createClock();
let running = true;
const sent: Array<readonly string[]> = [];
const delivery = createAgentMessageDelivery({
schedule: clock.schedule,
isRunning: () => running,
dispatch: async (request) => {
sent.push(request.messageIds);
return "turn_started";
},
onError: (error) => {
throw error;
},
});
const source = { kind: "agent-message" as const, agentId: "child" };
const report = delivery.enqueue({
recipientId: "parent",
messageId: "report",
source,
prompt: "report",
});
clock.advance(2000);
await Promise.resolve();
expect(sent).toEqual([]);
clock.advance(13000);
const finish = delivery.enqueue({
recipientId: "parent",
messageId: "finish",
source: { kind: "agent-notification", agentId: "child", event: "finished" },
prompt: "finished",
activeTurnBehavior: "steer",
});
clock.advance(2000);
await Promise.resolve();
expect(sent).toEqual([]);
running = false;
clock.advance(2000);
await Promise.all([report.dispatched, finish.dispatched]);
expect(sent).toEqual([["report", "finish"]]);
await delivery.close();
});
test("a turn starting during dispatch preparation keeps receipts queued and joins later arrivals", async () => {
const clock = createClock();
let busy = true;
const sent: Array<readonly string[]> = [];
const delivery = createAgentMessageDelivery({
schedule: clock.schedule,
dispatch: async (request) => {
if (busy) throw new AgentTurnBusyError("concurrent turn");
sent.push(request.messageIds);
return "turn_started";
},
onError: (error) => {
throw error;
},
});
const message = {
recipientId: "parent",
source: { kind: "agent-message" as const, agentId: "child" },
prompt: "report",
};
const first = delivery.enqueue({ ...message, messageId: "first" });
clock.advance(2000);
await new Promise<void>((resolve) => setImmediate(resolve));
expect(delivery.hasPending("parent")).toBe(true);
const second = delivery.enqueue({ ...message, messageId: "second" });
busy = false;
clock.advance(2000);
await Promise.all([first.dispatched, second.dispatched]);
expect(sent).toEqual([["first", "second"]]);
await delivery.close();
});
test("explicit interrupt bypasses a running turn while ordinary messages keep waiting", async () => {
const clock = createClock();
const sent: Array<readonly string[]> = [];
const delivery = createAgentMessageDelivery({
schedule: clock.schedule,
isRunning: () => true,
dispatch: async (request) => {
sent.push(request.messageIds);
return "turn_started";
},
onError: (error) => {
throw error;
},
});
const message = {
recipientId: "parent",
source: { kind: "agent-message" as const, agentId: "child" },
prompt: "report",
};
delivery.enqueue({ ...message, messageId: "wait" });
const interrupt = delivery.enqueue({
...message,
messageId: "interrupt",
activeTurnBehavior: "interrupt",
});
clock.advance(2000);
await interrupt.dispatched;
expect(sent).toEqual([["interrupt"]]);
expect(delivery.hasPending("parent")).toBe(true);
await delivery.close();
expect(sent).toEqual([["interrupt"], ["wait"]]);
});
test("shutdown flushes a dispatch that discovered a concurrent turn during preparation", async () => {
const clock = createClock();
let release!: () => void;
const preparing = new Promise<void>((resolve) => {
release = resolve;
});
const modes: boolean[] = [];
const delivery = createAgentMessageDelivery({
schedule: clock.schedule,
dispatch: async (request) => {
modes.push(request.idleOnly);
if (request.idleOnly) {
await preparing;
throw new AgentTurnBusyError("busy");
}
return "turn_started";
},
onError: () => {},
});
const receipt = delivery.enqueue({
recipientId: "parent",
prompt: "report",
source: { kind: "agent-message", agentId: "child" },
});
clock.advance(2000);
await new Promise<void>((resolve) => setImmediate(resolve));
const closing = delivery.close();
release();
await closing;
await expect(receipt.dispatched).resolves.toBe("turn_started");
expect(modes).toEqual([true, false]);
});
test("conflicting modes dispatch on separate turn ends without changing the active turn mode", async () => {
const clock = createClock();
let busy = false;
let mode = "initial";
let wake!: (recipientId: string) => void;
const sent: Array<{ ids: readonly string[]; mode?: string }> = [];
const delivery = createAgentMessageDelivery({
schedule: clock.schedule,
isRunning: () => busy,
subscribe: (listener) => {
wake = listener;
return () => {};
},
dispatch: async (request) => {
// Mode preparation precedes run admission in the real dispatcher.
mode = request.sessionMode ?? mode;
if (busy) throw new AgentTurnBusyError("concurrent turn");
sent.push({ ids: request.messageIds, mode });
busy = true;
return "turn_started";
},
onError: (error) => {
throw error;
},
});
const message = {
recipientId: "parent",
source: { kind: "agent-message" as const, agentId: "child" },
prompt: "message",
};
const a = delivery.enqueue({ ...message, messageId: "A", sessionMode: "plan" });
const b = delivery.enqueue({ ...message, messageId: "B", sessionMode: "default" });
clock.advance(2000);
await a.dispatched;
await new Promise<void>((resolve) => setImmediate(resolve));
expect(mode).toBe("plan");
expect(sent).toEqual([{ ids: ["A"], mode: "plan" }]);
busy = false;
wake("parent");
await b.dispatched;
expect(mode).toBe("default");
expect(sent).toEqual([
{ ids: ["A"], mode: "plan" },
{ ids: ["B"], mode: "default" },
]);
await delivery.close();
});
test("interrupts retain separate mode choices while the recipient is busy", async () => {
const clock = createClock();
const sent: Array<{ ids: readonly string[]; mode?: string }> = [];
const delivery = createAgentMessageDelivery({
schedule: clock.schedule,
isRunning: () => true,
dispatch: async (request) => {
sent.push({ ids: request.messageIds, mode: request.sessionMode });
return "turn_started";
},
onError: (error) => {
throw error;
},
});
const message = {
recipientId: "parent",
source: { kind: "agent-message" as const, agentId: "child" },
prompt: "message",
activeTurnBehavior: "interrupt" as const,
};
const a = delivery.enqueue({ ...message, messageId: "A", sessionMode: "plan" });
const b = delivery.enqueue({ ...message, messageId: "B", sessionMode: "default" });
clock.advance(2000);
await Promise.all([a.dispatched, b.dispatched]);
expect(sent).toEqual([
{ ids: ["A"], mode: "plan" },
{ ids: ["B"], mode: "default" },
]);
await delivery.close();
});
test("a settled-turn event releases a ready batch without waiting for the next timer sample", async () => {
const clock = createClock();
let running = true;
let settled: (id: string) => void = () => {};
let subscribed = true;
const sent: string[] = [];
const delivery = createAgentMessageDelivery({
schedule: clock.schedule,
isRunning: () => running,
subscribe: (listener) => {
settled = listener;
return () => {
subscribed = false;
};
},
dispatch: async (request) => {
sent.push(request.recipientId);
return "turn_started";
},
onError: (error) => {
throw error;
},
});
delivery.enqueue({
recipientId: "parent",
prompt: "report",
source: { kind: "agent-message", agentId: "child" },
});
clock.advance(2000);
expect(sent).toEqual([]);
running = false;
settled("parent");
await new Promise<void>((resolve) => setImmediate(resolve));
expect(sent).toEqual(["parent"]);
running = true;
await delivery.close();
expect(subscribed).toBe(false);
});
test.each([false, true])(
"completion waits report permission checkpoints without draining messages (initial: %s)",
async (initial) => {
const clock = createClock();
let permission = initial;
let changed: (id: string) => void = () => {};
let reported = false;
let sent = 0;
const delivery = createAgentMessageDelivery({
schedule: clock.schedule,
isRunning: () => true,
hasPendingPermission: () => permission,
subscribe: (listener) => {
changed = listener;
return () => {};
},
dispatch: async () => {
sent++;
return "turn_started";
},
onError: (error) => {
throw error;
},
});
delivery.enqueue({
recipientId: "child",
prompt: "follow up",
source: { kind: "agent-message", agentId: "parent" },
});
const wait = delivery.waitForDispatch("child", new AbortController().signal).then(() => {
reported = true;
return undefined;
});
permission = true;
changed("child");
await new Promise<void>((resolve) => setImmediate(resolve));
expect(reported).toBe(true);
expect(sent).toBe(0);
expect(delivery.hasPending("child")).toBe(true);
await wait;
await delivery.close();
},
);
test("a busy admission retry stays ready for the next settled-turn event", async () => {
const clock = createClock();
let running = false;
let raced = true;
let notify: (id: string) => void = () => {};
const sent: string[] = [];
const delivery = createAgentMessageDelivery({
schedule: clock.schedule,
isRunning: () => running,
subscribe: (listener) => {
notify = listener;
return () => {};
},
dispatch: async (request) => {
if (raced) {
running = true;
throw new AgentTurnBusyError("next turn started");
}
sent.push(request.recipientId);
return "turn_started";
},
onError: (error) => {
throw error;
},
});
delivery.enqueue({
recipientId: "parent",
prompt: "report",
source: { kind: "agent-message", agentId: "child" },
});
clock.advance(2000);
await new Promise<void>((resolve) => setImmediate(resolve));
raced = false;
running = false;
notify("parent");
await new Promise<void>((resolve) => setImmediate(resolve));
expect(sent).toEqual(["parent"]);
await delivery.close();
});
test("out-of-band acceptance owns callbacks and receipts; a failed attempt does not block waiting messages", async () => {
const clock = createClock();
let running = true;
let wake!: (recipientId: string) => void;
const callbacks: string[] = [];
const sent: string[] = [];
const errors: unknown[] = [];
const failure = new Error("recipient could not load");
const delivery = createAgentMessageDelivery({
schedule: clock.schedule,
isRunning: () => running,
subscribe: (listener) => {
wake = listener;
return () => {};
},
tryRunOutOfBand: async (request, onAccepted) => {
const text = parseAgentMessages(String(request.prompt))[0]!.text;
if (text === "failure") throw failure;
if (text !== "/handled") return false;
onAccepted();
callbacks.push("command ran");
return true;
},
dispatch: async (request) => {
sent.push(...parseAgentMessages(String(request.prompt)).map((message) => message.text));
return "turn_started";
},
onError: (error) => {
errors.push(error);
},
});
const message = {
recipientId: "parent",
source: { kind: "agent-message" as const, agentId: "child" },
};
const ordinary = delivery.enqueue({
...message,
prompt: "ordinary",
beforeDispatch: () => {
callbacks.push("ordinary");
},
});
const failed = delivery.enqueue({
...message,
prompt: "failure",
beforeDispatch: () => {
callbacks.push("failure");
},
});
const command = delivery.enqueue({
...message,
prompt: "/handled",
beforeDispatch: () => {
callbacks.push("command accepted");
},
onDispatch: (disposition) => {
callbacks.push(disposition);
},
});
clock.advance(2000);
await expect(failed.dispatched).rejects.toBe(failure);
await expect(command.dispatched).resolves.toBe("out_of_band");
expect(errors).toEqual([failure]);
expect(callbacks).toEqual(["command accepted", "command ran", "out_of_band"]);
expect(sent).toEqual([]);
running = false;
wake("parent");
await ordinary.dispatched;
expect(callbacks.at(-1)).toBe("ordinary");
expect(sent).toEqual(["ordinary"]);
await delivery.close();
});
test("shutdown waits for an in-flight out-of-band attempt and drains its unhandled message", async () => {
const clock = createClock();
let release!: () => void;
let attempted!: () => void;
const started = new Promise<void>((resolve) => {
attempted = resolve;
});
const gate = new Promise<void>((resolve) => {
release = resolve;
});
const dispatched: boolean[] = [];
const delivery = createAgentMessageDelivery({
schedule: clock.schedule,
isRunning: () => true,
tryRunOutOfBand: async () => {
attempted();
await gate;
return false;
},
dispatch: async (request) => {
dispatched.push(request.idleOnly);
return "turn_started";
},
onError: (error) => {
throw error;
},
});
const receipt = delivery.enqueue({
recipientId: "parent",
prompt: "ordinary",
source: { kind: "agent-message", agentId: "child" },
});
clock.advance(2000);
await started;
const closing = delivery.close();
release();
await closing;
await expect(receipt.dispatched).resolves.toBe("turn_started");
expect(dispatched).toEqual([false]);
});
test("a declined out-of-band message is offered once across running-turn retries", async () => {
const clock = createClock();
let running = true;
let accepts = false;
let offers = 0;
let dispatched = 0;
let wake!: (recipientId: string) => void;
const delivery = createAgentMessageDelivery({
schedule: clock.schedule,
isRunning: () => running,
subscribe: (listener) => {
wake = listener;
return () => {};
},
tryRunOutOfBand: async (_request, onAccepted) => {
offers++;
if (accepts) onAccepted();
return accepts;
},
dispatch: async () => {
dispatched++;
return "turn_started";
},
onError: (error) => {
throw error;
},
});
const receipt = delivery.enqueue({
recipientId: "parent",
prompt: "message",
source: { kind: "agent-message", agentId: "child" },
});
clock.advance(2000);
await new Promise<void>((resolve) => setImmediate(resolve));
expect(offers).toBe(1);
// A later provider state change does not reinterpret a declined message.
accepts = true;
for (let retry = 0; retry < 3; retry++) {
clock.advance(2000);
await new Promise<void>((resolve) => setImmediate(resolve));
}
expect(offers).toBe(1);
expect(dispatched).toBe(0);
running = false;
wake("parent");
await receipt.dispatched;
expect(dispatched).toBe(1);
await delivery.close();
});
test("a command with an explicit mode waits for turn end without an out-of-band offer", async () => {
const clock = createClock();
let running = true;
let offers = 0;
let wake!: (recipientId: string) => void;
const dispatched: Array<{ prompt: AgentPromptInput; sessionMode?: string }> = [];
const delivery = createAgentMessageDelivery({
schedule: clock.schedule,
isRunning: () => running,
subscribe: (listener) => {
wake = listener;
return () => {};
},
tryRunOutOfBand: async (_request, onAccepted) => {
offers++;
onAccepted();
return true;
},
dispatch: async (request) => {
dispatched.push(request);
return "out_of_band";
},
onError: (error) => {
throw error;
},
});
const receipt = delivery.enqueue({
recipientId: "parent",
prompt: "/handled",
sessionMode: "plan",
source: { kind: "agent-message", agentId: "child" },
});
clock.advance(2000);
await new Promise<void>((resolve) => setImmediate(resolve));
expect(offers).toBe(0);
expect(dispatched).toEqual([]);
running = false;
wake("parent");
await receipt.dispatched;
expect(dispatched).toHaveLength(1);
expect(dispatched[0]!.sessionMode).toBe("plan");
expect(parseAgentMessages(String(dispatched[0]!.prompt))![0]!.text).toBe("/handled");
await delivery.close();
});
@@ -1,4 +1,4 @@
import type { PromptDispatchDisposition } from "../agent-prompt.js";
import { AgentTurnBusyError, type PromptDispatchDisposition } from "../agent-prompt.js";
import { randomUUID } from "node:crypto";
import type { AgentPromptInput, AgentPromptContentBlock } from "../agent-sdk-types.js";
import { prepareAgentMessage, type AgentPromptSource } from "./envelope.js";
@@ -21,6 +21,8 @@ interface Receipt {
dispatched: Promise<PromptDispatchDisposition>;
}
interface Admitted extends Message {
sequence: number;
outOfBandDeclined: boolean;
receipt: Receipt;
resolve(disposition: PromptDispatchDisposition): void;
reject(error: unknown): void;
@@ -30,12 +32,18 @@ interface DispatchRequest {
messageIds: readonly string[];
prompt: AgentPromptInput;
activeTurnBehavior: "steer" | "interrupt";
idleOnly: boolean;
sessionMode?: string;
clearPendingPermissions: boolean;
unarchive: boolean;
onDispatch(disposition: PromptDispatchDisposition): void;
}
interface Dependencies {
/** Includes admitted starts and provider turns, including compaction. */
isRunning?: (recipientId: string) => boolean;
hasPendingPermission?: (recipientId: string) => boolean;
/** Notify when recipient state changes; admission still checks whether it is idle. */
subscribe?: (listener: (recipientId: string) => void) => () => void;
tryRunOutOfBand?(request: DispatchRequest, onAccepted: () => void): Promise<boolean>;
dispatch(request: DispatchRequest): Promise<PromptDispatchDisposition>;
onError(error: unknown, request: DispatchRequest): void;
/** Return a cancellation function. Production uses the daemon's event loop. */
@@ -47,7 +55,7 @@ export interface AgentMessageDelivery {
hasPending(recipientId: string): boolean;
/** Stop admission, flush pending messages, and await provider dispatch acknowledgments. */
close(): Promise<void>;
/** Existing completion waits include agent messages admitted before the wait. */
/** Completion waits include admitted messages, but return at permission checkpoints. */
waitForDispatch(recipientId: string, signal: AbortSignal): Promise<void>;
}
@@ -59,12 +67,14 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
const timer = setTimeout(callback, delayMs);
return () => clearTimeout(timer);
});
const pending = new Map<string, { messages: Admitted[]; cancel(): void }>();
const pending = new Map<string, { messages: Admitted[]; ready: boolean; cancel(): void }>();
const dispatching = new Map<string, Promise<void>>();
const receipts = new Map<string, Set<Receipt>>();
let sequence = 0;
let closed = false;
let closing: Promise<void> | undefined;
function dispatch(recipientId: string, messages: Admitted[]): void {
function requestFor(recipientId: string, messages: Admitted[]): DispatchRequest {
const prompts = messages.map(
(message) =>
prepareAgentMessage(message.prompt, message.source, message.receipt.messageId).prompt,
@@ -74,39 +84,55 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
: prompts.flatMap((entry): AgentPromptContentBlock[] =>
typeof entry === "string" ? [{ type: "text", text: entry }] : entry,
);
const request: DispatchRequest = {
return {
recipientId,
idleOnly: !closed && messages[0]!.activeTurnBehavior !== "interrupt",
messageIds: messages.map((message) => message.receipt.messageId),
prompt,
activeTurnBehavior: messages[0]!.activeTurnBehavior ?? "steer",
sessionMode: messages.find((message) => message.sessionMode)?.sessionMode,
clearPendingPermissions: messages.some((message) => message.clearPendingPermissions),
unarchive: messages.some((message) => message.unarchive !== false),
onDispatch: (disposition) => {
};
}
function dispatch(recipientId: string, messages: Admitted[]): void {
const request = requestFor(recipientId, messages);
queueDispatch(recipientId, async () => {
try {
for (const message of messages) message.beforeDispatch?.();
let disposition: PromptDispatchDisposition;
try {
disposition = await dependencies.dispatch(request);
} catch (error) {
if (!(error instanceof AgentTurnBusyError) || !closed) throw error;
// Shutdown drains admitted messages before closing the recipients.
disposition = await dependencies.dispatch({ ...request, idleOnly: false });
}
for (const message of messages) {
try {
message.onDispatch?.(disposition);
} catch (error) {
dependencies.onError(error, request);
}
message.resolve(disposition);
}
},
};
return undefined;
} catch (error) {
if (error instanceof AgentTurnBusyError && !closed) {
requeue(recipientId, messages);
return;
}
for (const message of messages) message.reject(error);
dependencies.onError(error, request);
throw error;
}
});
}
function queueDispatch(recipientId: string, operation: () => Promise<void>): void {
const previous = dispatching.get(recipientId) ?? Promise.resolve();
const dispatched = previous
.catch(() => undefined)
.then(async () => {
try {
for (const message of messages) message.beforeDispatch?.();
const disposition = await dependencies.dispatch(request);
for (const message of messages) message.resolve(disposition);
return undefined;
} catch (error) {
for (const message of messages) message.reject(error);
dependencies.onError(error, request);
throw error;
}
});
const dispatched = previous.catch(() => undefined).then(operation);
dispatching.set(recipientId, dispatched);
void dispatched
.finally(() => {
@@ -115,30 +141,121 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
.catch(() => undefined);
}
function requeue(recipientId: string, messages: Admitted[]): void {
const entry = pending.get(recipientId) ?? {
messages: [],
ready: true,
cancel: () => {},
};
entry.cancel();
entry.messages.push(...messages);
entry.messages.sort((a, b) => a.sequence - b.sequence);
entry.cancel = schedule(2000, () => flush(recipientId));
pending.set(recipientId, entry);
}
function flush(recipientId: string): void {
const entry = pending.get(recipientId);
if (!entry) return;
pending.delete(recipientId);
entry.ready = true;
entry.cancel();
if (!closed && dependencies.isRunning?.(recipientId)) {
const interrupts = entry.messages.filter(
(message) => message.activeTurnBehavior === "interrupt",
);
entry.messages = entry.messages.filter(
(message) => message.activeTurnBehavior !== "interrupt",
);
if (interrupts.length) dispatchGroups(recipientId, interrupts);
if (entry.messages.length && dependencies.tryRunOutOfBand) {
pending.delete(recipientId);
offerOutOfBand(recipientId, entry.messages);
} else if (entry.messages.length) {
entry.cancel = schedule(2000, () => flush(recipientId));
} else {
pending.delete(recipientId);
}
return;
}
pending.delete(recipientId);
dispatchGroups(recipientId, entry.messages);
}
function offerOutOfBand(recipientId: string, messages: Admitted[]): void {
queueDispatch(recipientId, async () => {
const waiting: Admitted[] = [];
for (const message of messages) {
if (
message.outOfBandDeclined ||
message.sessionMode !== undefined ||
closed ||
!dependencies.isRunning?.(recipientId)
) {
waiting.push(message);
continue;
}
const request = requestFor(recipientId, [message]);
try {
const accepted = await dependencies.tryRunOutOfBand!(request, () =>
message.beforeDispatch?.(),
);
if (!accepted) {
message.outOfBandDeclined = true;
waiting.push(message);
continue;
}
try {
message.onDispatch?.("out_of_band");
} catch (error) {
dependencies.onError(error, request);
}
message.resolve("out_of_band");
} catch (error) {
message.reject(error);
dependencies.onError(error, request);
}
}
if (waiting.length) requeue(recipientId, waiting);
if (closed || (pending.get(recipientId)?.ready && !dependencies.isRunning?.(recipientId)))
flush(recipientId);
});
}
function dispatchGroups(recipientId: string, messages: Admitted[]): void {
const groups: Admitted[][] = [];
let group: Admitted[] = [];
let mode: string | undefined;
for (const message of entry.messages) {
for (const message of messages) {
// Explicitly conflicting send options require separate, ordered dispatches.
if (
group.length &&
((message.activeTurnBehavior ?? "steer") !== (group[0]!.activeTurnBehavior ?? "steer") ||
(mode && message.sessionMode && mode !== message.sessionMode))
) {
dispatch(recipientId, group);
groups.push(group);
group = [];
mode = undefined;
}
group.push(message);
mode ??= message.sessionMode;
}
if (group.length) dispatch(recipientId, group);
if (group.length) groups.push(group);
let started = false;
for (const batch of groups) {
if (!closed && started && batch[0]!.activeTurnBehavior !== "interrupt") {
requeue(recipientId, batch);
} else {
dispatch(recipientId, batch);
started = true;
}
}
}
const unsubscribe = dependencies.subscribe?.((recipientId) => {
if (pending.get(recipientId)?.ready && !dependencies.isRunning?.(recipientId))
flush(recipientId);
});
return {
hasPending: (recipientId) => pending.has(recipientId) || dispatching.has(recipientId),
enqueue(message) {
@@ -155,17 +272,47 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
messageId: message.messageId ?? randomUUID(),
dispatched,
};
const entry = pending.get(message.recipientId) ?? { messages: [], cancel: () => {} };
const owned = receipts.get(message.recipientId) ?? new Set<Receipt>();
owned.add(receipt);
receipts.set(message.recipientId, owned);
void dispatched
.finally(() => {
owned.delete(receipt);
if (!owned.size) receipts.delete(message.recipientId);
})
.catch(() => undefined);
const entry = pending.get(message.recipientId) ?? {
messages: [],
ready: false,
cancel: () => {},
};
entry.cancel();
entry.messages.push({ ...message, receipt, resolve, reject });
entry.ready = false;
entry.messages.push({
...message,
receipt,
resolve,
reject,
sequence: sequence++,
outOfBandDeclined: false,
});
entry.cancel = schedule(2000, () => flush(message.recipientId));
pending.set(message.recipientId, entry);
return receipt;
},
async waitForDispatch(recipientId, signal) {
signal.throwIfAborted();
const admitted =
pending.get(recipientId)?.messages.map((message) => message.receipt.dispatched) ?? [];
const admitted = Array.from(receipts.get(recipientId) ?? [], (receipt) => receipt.dispatched);
let unsubscribePermission: (() => void) | undefined;
const permission = new Promise<void>((resolve) => {
const check = () => {
if (dependencies.hasPendingPermission?.(recipientId)) resolve();
};
unsubscribePermission = dependencies.subscribe?.((agentId) => {
if (agentId === recipientId) check();
});
check();
});
let aborted!: () => void;
const cancellation = new Promise<never>((_resolve, reject) => {
aborted = () => reject(new DOMException("Wait aborted", "AbortError"));
@@ -175,17 +322,22 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
await Promise.race([
Promise.all([dispatching.get(recipientId), ...admitted]),
cancellation,
permission,
]);
} finally {
signal.removeEventListener("abort", aborted);
unsubscribePermission?.();
}
},
close() {
if (closing) return closing;
closed = true;
unsubscribe?.();
for (const recipientId of pending.keys()) flush(recipientId);
// Each failure is reported and rejects its receipts; shutdown still drains other recipients.
closing = Promise.allSettled(dispatching.values()).then(() => undefined);
closing = Promise.allSettled(
[...receipts.values()].flatMap((owned) => [...owned].map((receipt) => receipt.dispatched)),
).then(() => undefined);
return closing;
},
};
@@ -337,6 +337,7 @@ describe("toAgentPayload", () => {
nativeHandle: { id: "native" } as unknown,
metadata: {
restored: new Date("2025-03-01T00:00:00.000Z"),
paseoInstructionReceipt: { threadId: "persist-99", digest: "internal-digest" },
empty: {},
mcpServers: {
hub: {
@@ -387,6 +388,8 @@ describe("toAgentPayload", () => {
sessionId: "persist-stored",
metadata: {
conversationId: "conversation-stored",
pluginAppendSystemPrompt: ["plugin instruction"],
daemonAppendSystemPrompt: "daemon instruction",
mcpServers: {
hub: {
type: "http",
@@ -402,6 +405,8 @@ describe("toAgentPayload", () => {
expect(record.persistence?.metadata).toEqual({
conversationId: "conversation-stored",
pluginAppendSystemPrompt: ["plugin instruction"],
daemonAppendSystemPrompt: "daemon instruction",
mcpServers: {
hub: {
type: "http",
@@ -495,6 +495,9 @@ function projectPersistenceHandleForWire(
return projected;
}
delete projected.metadata.mcpServers;
delete projected.metadata.pluginAppendSystemPrompt;
delete projected.metadata.daemonAppendSystemPrompt;
delete projected.metadata.paseoInstructionReceipt;
if (Object.keys(projected.metadata).length === 0) {
delete projected.metadata;
}
@@ -23,7 +23,10 @@ export type AgentRunController = Pick<
reloadAgentSession(agentId: string): Promise<unknown>;
};
export class AgentTurnBusyError extends Error {}
export interface StartAgentRunOptions {
idleOnly?: boolean;
/** Called after selecting the run, before consuming its events. */
onDispatch?: (disposition: PromptDispatchDisposition) => void;
replaceRunning?: boolean;
@@ -136,7 +139,12 @@ async function startAgentRunInner(
options?: StartAgentRunOptions,
): Promise<{ disposition: PromptDispatchDisposition }> {
const snapshot = agentManager.getAgent(agentId);
const steered = await steerOrReplaceActiveRun(agentManager, agentId, prompt, options);
const steered = options?.idleOnly
? null
: await steerOrReplaceActiveRun(agentManager, agentId, prompt, options);
if (options?.idleOnly && agentManager.hasInFlightRun(agentId)) {
throw new AgentTurnBusyError(`Agent ${agentId} is running`);
}
if (steered?.disposition === "steered") {
options?.onDispatch?.("steered");
return steered;
@@ -210,6 +218,7 @@ export async function unarchiveAgentState(
}
export interface SendPromptToAgentParams {
idleOnly?: boolean;
/** Awaited after the agent is loaded and its mode is set, before the prompt is handed to a run. */
beforeDispatch?: () => Promise<void>;
onDispatch?: StartAgentRunOptions["onDispatch"];
@@ -355,13 +364,17 @@ export async function sendPreparedPromptToAgent(
throw error;
}
if (params.idleOnly && params.agentManager.hasInFlightRun(params.agentId)) {
throw new AgentTurnBusyError(`Agent ${params.agentId} is running`);
}
if (params.sessionMode) {
await params.agentManager.setAgentMode(params.agentId, params.sessionMode);
}
await params.beforeDispatch?.();
return await startAgentRun(params.agentManager, params.agentId, params.prompt, params.logger, {
replaceRunning: true,
replaceRunning: !params.idleOnly,
idleOnly: params.idleOnly,
onDispatch: params.onDispatch,
activeTurnBehavior: params.activeTurnBehavior,
clearPendingPermissions: params.clearPendingPermissions,
@@ -621,6 +621,8 @@ export interface AgentSessionConfig {
* persisted into agent config so daemon setting changes apply cleanly.
*/
daemonAppendSystemPrompt?: string;
/** Plugin instructions for this launch; never persisted. */
pluginAppendSystemPrompt?: string[];
modeId?: string;
model?: string;
thinkingOptionId?: string;
@@ -636,6 +638,8 @@ export interface AgentSessionConfig {
}
export interface AgentLaunchContext {
/** Launch-only instructions contributed by plugins. */
appendSystemPrompt?: string[];
/** Launch-only plugin MCP servers and their owners; never persisted. */
mcpServers?: Record<string, McpServerConfig>;
mcpServerOwners?: Record<string, string>;
@@ -688,6 +692,8 @@ export interface AgentUsageSession {
}
export interface AgentSession {
/** Persist the session's current handle immediately after an interactive resume. */
readonly persistenceUpdatedOnResume?: boolean;
usageSession?(): AgentUsageSession | null;
readonly provider: AgentProvider;
readonly id: string | null;
@@ -498,3 +498,26 @@ test("finish recovery protects callers before durable intent has loaded", async
expect(recovered.hasPendingForCaller("parent")).toBe(true);
expect(recovered.hasPendingForCaller("unrelated")).toBe(false);
});
test("an undispatched follow-up does not block the running child's permission notification", async () => {
const state = await scenario();
await state.service.register(intent);
await until(() => state.observation.waits.length === 1);
await state.service.register(intent, true);
const result = outcome("running");
result.status = "permission";
result.final!.pendingPermissions = [
{
id: "approval",
provider: "codex",
name: "Bash",
kind: "tool",
input: { command: "run tests" },
} as NonNullable<typeof result.final>["pendingPermissions"][number],
];
state.observation.waits[0]!.result.resolve(result);
await until(() => state.delivery.prompts.length === 1);
expect(state.delivery.prompts[0]).toContain("needs permission");
expect(state.delivery.prompts[0]).toContain("approval");
expect(await state.store.list()).toHaveLength(2);
});
@@ -267,7 +267,9 @@ export function createFinishSubscriptions(deps: Dependencies): FinishSubscriptio
continue;
}
if (signal.aborted) return;
await decisions(group);
// A queued follow-up cannot start until the current permission is answered.
// Its pending registration must not hold the running turn's checkpoint.
if (pending.status !== "permission" || watch.pending) await decisions(group);
if (signal.aborted) return;
if (await suppressed(record, pending)) {
await remove(watch);
@@ -298,7 +298,7 @@ export function createHostResolver(input: {
status: agent.status,
guidance:
receipt.deliveryStatus === "queued"
? "Queued for delivery after two quiet seconds. You will get notified when the prompted agent finishes, errors, or needs permission unless notifyOnFinish is false."
? "Queued for delivery after two quiet seconds and the current turn ends, unless interrupt was requested. You will get notified when the prompted agent finishes, errors, or needs permission unless notifyOnFinish is false."
: "Dispatch acknowledged. Observe completion using get_agent_status/get_agent_activity or SDK/RPC subscriptions and wait APIs.",
});
},
@@ -172,11 +172,12 @@ function registeredTool(
async function invokeToolWithParsedInput(
tool: RegisteredMcpToolWithHandler,
input: Record<string, unknown>,
awaitDispatch = true,
) {
const parsed = await tool.inputSchema.safeParseAsync(input);
expect(parsed.success).toBe(true);
const response = await tool.handler(parsed.data);
if (response.structuredContent.deliveryStatus === "queued") {
if (awaitDispatch && response.structuredContent.deliveryStatus === "queued") {
await toolDeliveries
.get(tool)!
.waitForDispatch(input.agentId as string, new AbortController().signal);
@@ -274,6 +275,7 @@ function buildAgentManagerSpies() {
effectiveOptionsFor: (_provider: string, own?: Record<string, unknown>) => own ?? {},
reloadStalePluginSession: async () => {},
hasInFlightRun: vi.fn().mockReturnValue(false),
hasPendingPermissions: () => false,
steerOrReplaceActiveTurn: async () => ({ status: "inactive" as const }),
tryRunOutOfBand: vi.fn().mockReturnValue(false),
subscribe: vi.fn().mockReturnValue(() => {}),
@@ -623,6 +625,12 @@ class FakeBrowserToolsBroker {
}
class BoundaryAgentManagerFake {
subscribe() {
return () => {};
}
hasPendingPermissions() {
return false;
}
public getPluginTools(): [] {
return [];
}
@@ -877,8 +885,9 @@ function createPaseoWorktreeForMcpTest(options: {
async function createAgentMcpServer(
options: Parameters<typeof createAgentMcpServerWithDependencies>[0],
subscriptionStore?: FinishSubscriptionStore,
schedule?: (delayMs: number, callback: () => void) => () => void,
) {
const messages = createTestAgentMessages(options);
const messages = createTestAgentMessages({ ...options, schedule });
const records = new Map<string, FinishSubscription>();
const subscriptions = createFinishSubscriptions({
store: subscriptionStore ?? {
@@ -3677,15 +3686,15 @@ class HeldTurnAgentClient implements AgentClient {
describe("send_agent_prompt MCP tool", () => {
it.each([
{ agentScoped: true, behavior: undefined, available: true, steered: true },
{ agentScoped: true, behavior: "interrupt", available: true, steered: false },
{ agentScoped: true, behavior: "steer", available: true, steered: true },
{ agentScoped: false, behavior: undefined, available: true, steered: false },
{ agentScoped: false, behavior: "steer", available: true, steered: true },
{ agentScoped: true, behavior: undefined, available: false, steered: false },
{ agentScoped: true, behavior: undefined, available: true },
{ agentScoped: true, behavior: "interrupt", available: true },
{ agentScoped: true, behavior: "steer", available: true },
{ agentScoped: false, behavior: undefined, available: true },
{ agentScoped: false, behavior: "steer", available: true },
{ agentScoped: true, behavior: undefined, available: false },
] as const)(
"dispatches behavior $behavior for agent-scoped=$agentScoped, steering available=$available",
async ({ agentScoped, behavior, available, steered }) => {
async ({ agentScoped, behavior, available }) => {
const workdir = await mkdtemp(join(tmpdir(), "mcp-send-behavior-"));
const storage = new AgentStorage(join(workdir, "agents"), logger);
const client = new HeldTurnAgentClient("codex", true, {
@@ -3717,18 +3726,33 @@ describe("send_agent_prompt MCP tool", () => {
notifyOnFinish: false,
});
const originalTurn = manager.getAgent(child.id)!.activeTurnId;
const response = await invokeToolWithParsedInput(tool, {
agentId: child.id,
prompt: "New message",
notifyOnFinish: false,
...(behavior ? { activeTurnBehavior: behavior } : {}),
});
const queued = agentScoped && behavior !== "interrupt";
const steered = !agentScoped && behavior === "steer";
const response = await invokeToolWithParsedInput(
tool,
{
agentId: child.id,
prompt: "New message",
notifyOnFinish: false,
...(behavior ? { activeTurnBehavior: behavior } : {}),
},
!queued,
);
expect(response.structuredContent).toMatchObject({
success: true,
...(agentScoped
? { deliveryStatus: "queued" }
: { disposition: steered ? "steered" : "turn_started" }),
});
if (queued) {
expect(client.sessions[1]!.prompts).toHaveLength(1);
expect(client.sessions[1]!.steeredPrompts).toEqual([]);
expect(manager.getAgent(child.id)!.activeTurnId).toBe(originalTurn);
client.sessions[1]!.finishTurn();
await serverDeliveries
.get(server)!
.waitForDispatch(child.id, new AbortController().signal);
}
expect(client.sessions[1]!.prompts).toHaveLength(steered ? 1 : 2);
expect(client.sessions[1]!.steeredPrompts).toHaveLength(steered ? 1 : 0);
expect(manager.getAgent(child.id)!.activeTurnId === originalTurn).toBe(steered);
@@ -3740,18 +3764,16 @@ describe("send_agent_prompt MCP tool", () => {
it.each([
{ rejected: false, priorNotification: false },
{ rejected: true, priorNotification: false },
{ rejected: false, priorNotification: true },
{ rejected: true, priorNotification: false },
{ rejected: true, priorNotification: true },
])(
"buffers completion until steer acknowledgement (rejected: $rejected, prior notification: $priorNotification)",
"keeps completion tied to queued dispatch acknowledgement (rejected: $rejected, prior notification: $priorNotification)",
async ({ rejected, priorNotification }) => {
const workdir = await mkdtemp(join(tmpdir(), "mcp-send-behavior-"));
const workdir = await mkdtemp(join(tmpdir(), "mcp-queued-ack-"));
const storage = new AgentStorage(join(workdir, "agents"), logger);
const client = new HeldTurnAgentClient("codex", true, {
steerResult: "accepted",
finishDuringSteer: true,
rejectSteer: rejected,
});
const options: HeldTurnOptions = {};
const client = new HeldTurnAgentClient("codex", true, options);
const manager = new AgentManager({ clients: { codex: client }, registry: storage, logger });
let mcpClient: Client | undefined;
try {
@@ -3773,104 +3795,47 @@ describe("send_agent_prompt MCP tool", () => {
logger,
});
mcpClient = await connectInMemoryMcpClient(server);
const send = (input: Record<string, unknown>) =>
sendMcpAndAwaitDispatch(mcpClient!, server, input);
await send({
await sendMcpAndAwaitDispatch(mcpClient, server, {
agentId: child.id,
prompt: "Original work",
notifyOnFinish: priorNotification,
});
const sending = send({
agentId: child.id,
prompt: "New message",
notifyOnFinish: true,
const session = client.sessions[1]!;
const release = session.holdTurnStart();
options.finishTurnsDuringStart = true;
if (rejected) session.rejectNextTurnStart(new Error("Start rejected"));
const response = await mcpClient.callTool({
name: "send_agent_prompt",
arguments: { agentId: child.id, prompt: "New message", notifyOnFinish: true },
});
if (rejected) {
await expect(sending).rejects.toThrow("Steer rejected");
// Flush asynchronous notification work before checking that a rejected
// dispatch did not notify. Then prove a later successful send still can.
await new Promise((resolve) => setTimeout(resolve, 50));
expect(client.sessions[0]!.prompts).toHaveLength(0);
await send({
agentId: child.id,
prompt: "Retry after rejection",
expect(response.structuredContent).toMatchObject({
success: true,
deliveryStatus: "queued",
});
const dispatch = serverDeliveries
.get(server)!
.waitForDispatch(child.id, new AbortController().signal);
const rejectedDispatch = rejected
? expect(dispatch).rejects.toThrow("Start rejected")
: null;
expect(client.sessions[0]!.prompts).toHaveLength(0);
session.finishTurn();
await vi.waitFor(() => expect(session.prompts).toHaveLength(2));
expect(client.sessions[0]!.prompts).toHaveLength(0);
release();
if (rejectedDispatch) await rejectedDispatch;
else await dispatch;
if (!rejected || priorNotification) {
await vi.waitFor(() => expect(client.sessions[0]!.prompts).toHaveLength(1), {
timeout: 5000,
});
expect(parseAgentMessage(client.sessions[0]!.prompts[0])).toMatchObject({
source: { kind: "agent-notification", agentId: child.id, event: "finished" },
});
client.sessions[1]!.finishTurn();
} else {
const response = await sending;
expect(response.structuredContent).toMatchObject({
success: true,
deliveryStatus: "queued",
});
}
await vi.waitFor(() => expect(client.sessions[0]!.prompts).toHaveLength(1));
expect(parseAgentMessage(client.sessions[0]!.prompts[0])).toMatchObject({
source: { kind: "agent-notification", agentId: child.id, event: "finished" },
});
} finally {
await mcpClient?.close();
await removeAgentStateDir(manager, storage, workdir);
}
},
);
it.each([false, true])(
"preserves the original notification after rejection (completion during send: %s)",
async (finishDuringSteer) => {
const workdir = await mkdtemp(join(tmpdir(), "mcp-send-behavior-"));
const storage = new AgentStorage(join(workdir, "agents"), logger);
const client = new HeldTurnAgentClient("codex", true, {
steerResult: "accepted",
finishDuringSteer,
rejectSteer: true,
});
const manager = new AgentManager({ clients: { codex: client }, registry: storage, logger });
let mcpClient: Client | undefined;
try {
const parent = await manager.createAgent(
{ provider: "codex", cwd: existingCwd },
undefined,
{
workspaceId: "wks_parent",
},
);
const child = await manager.createAgent(
{ provider: "codex", cwd: existingCwd },
undefined,
{
workspaceId: "wks_parent",
},
);
const server = await createAgentMcpServer({
agentManager: manager,
agentStorage: storage,
callerAgentId: parent.id,
providerSnapshotManager: createOpenCodeManager().manager,
logger,
});
mcpClient = await connectInMemoryMcpClient(server);
const send = (input: Record<string, unknown>) =>
sendMcpAndAwaitDispatch(mcpClient!, server, input);
await send({
agentId: child.id,
prompt: "Original work",
notifyOnFinish: true,
});
const sending = send({
agentId: child.id,
prompt: "New message",
notifyOnFinish: true,
});
await expect(sending).rejects.toThrow("Steer rejected");
if (!finishDuringSteer) {
await new Promise((resolve) => setTimeout(resolve, 50));
await serverSubscriptions.get(server)!.close();
expect(client.sessions[0]!.prompts).toHaveLength(0);
client.sessions[1]!.finishTurn();
}
await vi.waitFor(() => expect(client.sessions[0]!.prompts).toHaveLength(1));
expect(parseAgentMessage(client.sessions[0]!.prompts[0])).toMatchObject({
source: { kind: "agent-notification", agentId: child.id, event: "finished" },
});
} finally {
await mcpClient?.close();
await removeAgentStateDir(manager, storage, workdir);
@@ -4012,7 +3977,7 @@ describe("send_agent_prompt MCP tool", () => {
const response = await tool.handler(parsed.data as Record<string, unknown>);
expect(response.structuredContent).toMatchObject({ deliveryStatus: "queued" });
expect(spies.agentManager.subscribe).not.toHaveBeenCalled();
expect(serverSubscriptionRecords.get(server)!.size).toBe(1);
await serverDeliveries
.get(server)!
.waitForDispatch("child-agent", new AbortController().signal);
@@ -4053,7 +4018,7 @@ describe("send_agent_prompt MCP tool", () => {
await tool.handler(parsed.data as Record<string, unknown>);
expect(spies.agentManager.subscribe).not.toHaveBeenCalled();
expect(serverSubscriptionRecords.get(server)!.size).toBe(0);
expect(spies.agentManager.waitForAgentEvent).not.toHaveBeenCalled();
});
@@ -4096,7 +4061,7 @@ describe("send_agent_prompt MCP tool", () => {
notifyOnFinish: false,
});
expect(spies.agentManager.subscribe).not.toHaveBeenCalled();
expect(serverSubscriptionRecords.get(server)!.size).toBe(0);
expect(spies.agentManager.waitForAgentEvent).not.toHaveBeenCalled();
});
@@ -4220,11 +4185,15 @@ describe("send_agent_prompt MCP tool", () => {
notifyOnFinish: false,
});
if (scenario !== "startup_failure") {
const response = await invokeToolWithParsedInput(tool, {
agentId: child.id,
prompt: "/side-command",
activeTurnBehavior: scenario === "out_of_band_interrupt" ? "interrupt" : "steer",
});
const response = await invokeToolWithParsedInput(
tool,
{
agentId: child.id,
prompt: "/side-command",
activeTurnBehavior: scenario === "out_of_band_interrupt" ? "interrupt" : "steer",
},
scenario !== "out_of_band",
);
expect(response.structuredContent).toMatchObject({
success: true,
deliveryStatus: "queued",
@@ -4236,6 +4205,9 @@ describe("send_agent_prompt MCP tool", () => {
});
expect(parentClient.sessions[0]!.prompts).toHaveLength(0);
childClient.sessions[0]!.finishTurn("Ongoing task done");
await serverDeliveries
.get(server)!
.waitForDispatch(child.id, new AbortController().signal);
await vi.waitFor(() => {
expect(parentClient.sessions[0]!.prompts).toHaveLength(1);
expect(parentClient.sessions[0]!.prompts[0]).toContain("finished.");
@@ -4243,7 +4215,11 @@ describe("send_agent_prompt MCP tool", () => {
} else {
childClient.sessions[0]!.rejectNextTurnStart(new Error("Requested turn could not start"));
await expect(
invokeToolWithParsedInput(tool, { agentId: child.id, prompt: "Replacement task" }),
invokeToolWithParsedInput(tool, {
agentId: child.id,
prompt: "Replacement task",
activeTurnBehavior: "interrupt",
}),
).rejects.toThrow("Requested turn could not start");
// A later real turn must not inherit a subscription from the rejected dispatch.
await invokeToolWithParsedInput(tool, {
@@ -4354,6 +4330,7 @@ describe("send_agent_prompt MCP tool", () => {
const sent = await invokeToolWithParsedInput(registeredTool(server, "send_agent_prompt"), {
agentId: childId,
prompt: "Stop and reply instead",
activeTurnBehavior: "interrupt",
});
expect(sent.structuredContent).toMatchObject({
success: true,
@@ -4517,7 +4494,7 @@ describe("send_agent_prompt MCP tool to an OMP child", () => {
const logger = createTestLogger();
const existingCwd = process.cwd();
async function setupOmpChild() {
async function setupOmpChild(schedule?: (delayMs: number, callback: () => void) => () => void) {
const workdir = await mkdtemp(join(tmpdir(), "mcp-omp-child-"));
const storage = new AgentStorage(join(workdir, "agents"), logger);
const parentClient = new HeldTurnAgentClient("claude", false);
@@ -4545,13 +4522,17 @@ describe("send_agent_prompt MCP tool to an OMP child", () => {
undefined,
{ workspaceId: "wks_parent" },
);
const server = await createAgentMcpServer({
agentManager,
agentStorage: storage,
callerAgentId: parent.id,
providerSnapshotManager: createOpenCodeManager().manager,
logger,
});
const server = await createAgentMcpServer(
{
agentManager,
agentStorage: storage,
callerAgentId: parent.id,
providerSnapshotManager: createOpenCodeManager().manager,
logger,
},
undefined,
schedule,
);
return {
agentManager,
storage,
@@ -4581,37 +4562,63 @@ describe("send_agent_prompt MCP tool to an OMP child", () => {
{ command: "follow-up", streamingBehavior: "followUp" },
{ command: "steer", streamingBehavior: "steer" },
] as const)(
"delivers /$command into a turn OMP started on its own, without aborting it",
"delivers /$command to a running OMP child while ordinary messages in the same quiet window wait",
async ({ command, streamingBehavior }) => {
const { agentManager, storage, workdir, parentClient, ompSession, childId, tool } =
await setupOmpChild();
let flush!: () => void;
const { agentManager, storage, workdir, ompSession, childId, tool } = await setupOmpChild(
(_delay, callback) => {
flush = callback;
return () => {};
},
);
try {
ompSession.beginTurn();
ompSession.streamAssistantText("background job finished, working on it");
await vi.waitFor(() => {
expect(agentManager.getAgent(childId)?.activeTurnId).toMatch(/^autonomous-/);
});
const response = await invokeToolWithParsedInput(tool, {
agentId: childId,
prompt: `/${command} then summarize the logs`,
});
expect(response.structuredContent).toMatchObject({
success: true,
deliveryStatus: "queued",
status: "running",
const activeTurnId = agentManager.getAgent(childId)?.activeTurnId;
const delivery = toolDeliveries.get(tool)!;
let ordinaryBeforeDispatch = 0;
const ordinary = delivery.enqueue({
recipientId: childId,
source: { kind: "agent-message", agentId: "parent" },
prompt: "ordinary follow-up",
beforeDispatch: () => {
ordinaryBeforeDispatch++;
},
});
const response = await invokeToolWithParsedInput(
tool,
{
agentId: childId,
prompt: `/${command} then summarize the logs`,
},
false,
);
flush();
await vi.waitFor(() => {
expect(ompSession.prompts).toEqual([
{ message: "then summarize the logs", imageCount: 0, streamingBehavior },
]);
});
expect(ordinaryBeforeDispatch).toBe(0);
expect(agentManager.getAgent(childId)?.activeTurnId).toBe(activeTurnId);
expect(response.structuredContent).toMatchObject({
success: true,
deliveryStatus: "queued",
status: "running",
});
expect(ompSession.abortRequested).toBe(false);
expect(agentManager.getAgent(childId)?.lifecycle).toBe("running");
ompSession.finishTurn();
await expectOneFinishNotification(agentManager, parentClient, childId);
await ordinary.dispatched;
expect(ordinaryBeforeDispatch).toBe(1);
expect(ompSession.prompts).toHaveLength(2);
expect(ompSession.prompts[1]!.message).toContain("ordinary follow-up");
ompSession.beginTurn();
ompSession.finishTurn();
} finally {
await removeAgentStateDir(agentManager, storage, workdir);
}
@@ -1949,7 +1949,11 @@ function mapSessionConfig(
return {
cwd: config.cwd,
env: createProviderEnv({ baseEnv: {}, overlays: [launchContext?.env] }),
systemPrompt: combineSystemPrompts(config.systemPrompt, config.daemonAppendSystemPrompt),
systemPrompt: combineSystemPrompts(
config.systemPrompt,
config.daemonAppendSystemPrompt,
...(config.pluginAppendSystemPrompt ?? []),
),
mcpServers: { ...config.mcpServers },
toolPolicy: config.toolPolicy
? { preapproved: config.toolPolicy.preapproved.map((grant) => ({ ...grant })) }
@@ -1968,8 +1972,9 @@ function mapSessionConfig(
function combineSystemPrompts(
systemPrompt: string | undefined,
daemonPrompt: string | undefined,
...pluginPrompts: string[]
): string | undefined {
const parts = [systemPrompt, daemonPrompt].filter(
const parts = [systemPrompt, daemonPrompt, ...pluginPrompts].filter(
(value): value is string => typeof value === "string" && value.trim().length > 0,
);
return parts.length > 0 ? parts.join("\n\n") : undefined;
@@ -448,6 +448,9 @@ export function wrapSessionProvider(provider: AgentProvider, inner: AgentSession
get initialTimeline() {
return inner.initialTimeline;
},
get persistenceUpdatedOnResume() {
return inner.persistenceUpdatedOnResume;
},
get controls() {
return inner.controls;
},
@@ -51,7 +51,6 @@ import {
} from "./copilot-acp-agent.js";
import { GenericACPAgentClient } from "./generic-acp-agent.js";
import { parseKiroExtensionCommands } from "./kiro-acp-agent.js";
import { transformPiModels } from "./pi/agent.js";
import type { AgentStreamEvent } from "../agent-sdk-types.js";
import type {
AgentCapabilityFlags,
@@ -2260,7 +2259,12 @@ describe("ACPAgentClient modelTransformer", () => {
provider: "pi",
logger: createTestLogger(),
defaultCommand: ["test-acp"],
modelTransformer: transformPiModels,
modelTransformer: (models) =>
models.map((model) => ({
...model,
label: model.label.split("/").at(-1) ?? model.label,
description: model.id,
})),
});
await expect(
@@ -2914,60 +2918,6 @@ describe("ACP providers advertise session listing", () => {
});
});
describe("transformPiModels", () => {
test("keeps slash-free labels unchanged", () => {
expect(
transformPiModels([
{
provider: "pi",
id: "gpt-4.1-mini",
label: "GPT 4.1 Mini",
description: "Fast",
},
]),
).toEqual([
{
provider: "pi",
id: "gpt-4.1-mini",
label: "GPT 4.1 Mini",
description: "Fast",
},
]);
});
test("uses the last path segment as label and preserves existing descriptions", () => {
expect(
transformPiModels([
{
provider: "pi",
id: "openrouter/openai/gpt-4.1-mini",
label: "openrouter/openai/gpt-4.1-mini",
description: undefined,
},
{
provider: "pi",
id: "anthropic/claude-sonnet-4",
label: "anthropic/claude-sonnet-4",
description: "Balanced",
},
]),
).toEqual([
{
provider: "pi",
id: "openrouter/openai/gpt-4.1-mini",
label: "gpt-4.1-mini",
description: "openrouter/openai/gpt-4.1-mini",
},
{
provider: "pi",
id: "anthropic/claude-sonnet-4",
label: "claude-sonnet-4",
description: "Balanced",
},
]);
});
});
describe("ACPAgentSession slash commands", () => {
test("returns immediately for ACP sessions that do not wait for async command discovery", async () => {
const session = new ACPAgentSession(
@@ -153,6 +153,56 @@ describe("Claude SDK env", () => {
}
});
test("resume uses current plugin instructions and excludes them from persistence", async () => {
const prompts: unknown[] = [];
const queryFactory = ({ options }: ClaudeQueryInput) => {
prompts.push(options.systemPrompt);
return createQueryMock([
{
type: "system",
subtype: "init",
session_id: "persisted-session",
permissionMode: "default",
model: "opus",
},
{ type: "assistant", message: { content: "done" } },
{
type: "result",
subtype: "success",
usage: { input_tokens: 1, cache_read_input_tokens: 0, output_tokens: 1 },
total_cost_usd: 0,
},
]);
};
const client = new ClaudeAgentClient({
logger: createTestLogger(),
queryFactory,
resolveBinary: async () => "/test/claude/bin",
});
const first = await client.createSession({
provider: "claude",
cwd: process.cwd(),
pluginAppendSystemPrompt: ["Plugin instructions"],
});
await first.run("first");
const handle = first.describePersistence()!;
expect(handle.metadata).not.toHaveProperty("pluginAppendSystemPrompt");
await first.close();
const resumed = await client.resumeSession(handle, {
cwd: process.cwd(),
pluginAppendSystemPrompt: undefined,
});
try {
await resumed.run("after disable");
expect(prompts).toEqual([
{ type: "preset", preset: "claude_code", append: "Plugin instructions" },
{ type: "preset", preset: "claude_code", append: "" },
]);
} finally {
await resumed.close();
}
});
test("forwards launch-context env through Claude resume env", async () => {
let capturedEnv: Record<string, string | undefined> | undefined;
const launchContext: AgentLaunchContext = {
@@ -83,7 +83,7 @@ import {
type ClaudeProviderOptions,
} from "./options.js";
import { renderPromptAttachmentAsText } from "../../prompt-attachments.js";
import { discoverClaudeModels } from "./model-discovery.js";
import { discoverClaudeModels, killExitingClaudeModelDiscoveries } from "./model-discovery.js";
import { claudeQuery, type ClaudeOptions, type ClaudeQueryFactory } from "./query.js";
import {
findSteeredMessageParent,
@@ -1751,6 +1751,10 @@ export class ClaudeAgentClient implements AgentClient {
};
}
async shutdown(): Promise<void> {
await killExitingClaudeModelDiscoveries();
}
async resolveDefaultModeId({ env: launchEnv }: ResolveAgentDefaultModeInput): Promise<string> {
return claudeModeCatalog(this.buildProviderEnv(launchEnv)).defaultModeId;
}
@@ -3044,7 +3048,11 @@ class ClaudeAgentSession implements AgentSession {
if (!this.claudeSessionId) {
return null;
}
const { providerOptions: _providerOptions, ...persistedConfig } = this.config;
const {
providerOptions: _providerOptions,
pluginAppendSystemPrompt: _pluginAppendSystemPrompt,
...persistedConfig
} = this.config;
this.persistence = {
provider: "claude",
sessionId: this.claudeSessionId,
@@ -3712,7 +3720,11 @@ class ClaudeAgentSession implements AgentSession {
private buildAppendedSystemPrompt(): string {
return (
composeSystemPromptParts(this.config.systemPrompt, this.config.daemonAppendSystemPrompt) ?? ""
composeSystemPromptParts(
this.config.systemPrompt,
this.config.daemonAppendSystemPrompt,
...(this.config.pluginAppendSystemPrompt ?? []),
) ?? ""
);
}
@@ -6,6 +6,10 @@ import type { ProviderRuntimeSettings } from "../../provider-launch-config.js";
import { terminateWithTreeKill } from "../../../../utils/tree-kill.js";
import { claudeQuery, type ClaudeQueryInput, type ClaudeQueryContext } from "./query.js";
const DISCOVERY_WAIT_MS = 5_000;
// Long enough for the CLI to finish an OAuth token refresh it started before the wait ended.
const DISCOVERY_EXIT_GRACE_MS = 60_000;
interface ClaudeModelDiscoveryOptions {
resolveBinary: () => Promise<string>;
runtimeSettings?: ProviderRuntimeSettings;
@@ -18,19 +22,24 @@ type OpenDiscoveryQuery = (
context: ClaudeQueryContext,
) => Pick<Query, "supportedModels" | "close">;
type DiscoveryQuery = ReturnType<OpenDiscoveryQuery>;
// Discovery processes left to exit on their own after their caller stopped waiting.
const exitingDiscoveries = new Map<ChildProcess, () => Promise<void>>();
// The curated catalog survives a failed or slow probe. This process never receives
// a prompt and must not persist a session or launch user MCP servers/hooks.
export async function discoverClaudeModels(
options: ClaudeModelDiscoveryOptions,
openQuery: OpenDiscoveryQuery = claudeQuery,
): Promise<ModelInfo[]> {
const controller = new AbortController();
const waitController = new AbortController();
const signal = options.signal
? AbortSignal.any([options.signal, controller.signal])
: controller.signal;
? AbortSignal.any([options.signal, waitController.signal])
: waitController.signal;
const timer = setTimeout(
() => controller.abort(new Error("Claude model discovery timed out")),
5_000,
() => waitController.abort(new Error("Claude model discovery timed out")),
DISCOVERY_WAIT_MS,
);
let endInput!: () => void;
const ended = new Promise<void>((resolve) => {
@@ -46,7 +55,7 @@ export async function discoverClaudeModels(
};
},
};
let query: ReturnType<OpenDiscoveryQuery> | undefined;
let query: DiscoveryQuery | undefined;
let child: ChildProcess | undefined;
try {
signal.throwIfAborted();
@@ -64,7 +73,8 @@ export async function discoverClaudeModels(
strictMcpConfig: true,
settingSources: ["user"],
settings: { disableAllHooks: true },
abortController: controller,
// No abortController: the SDK kills the process when it aborts, and the end of
// the wait must not.
},
},
{
@@ -78,12 +88,56 @@ export async function discoverClaudeModels(
} finally {
clearTimeout(timer);
endInput();
try {
query?.close();
} finally {
if (child) {
await terminateWithTreeKill(child, { gracefulTimeoutMs: 200, forceTimeoutMs: 200 });
}
if (query && child && !hasExited(child)) {
// The CLI may be refreshing an expired OAuth token, even after it has answered.
// Claude Code rotates the refresh token before saving the new pair, so killing it now
// leaves a revoked token on disk and logs the user out (#9314). With its input ended
// it exits once that work is done; the grace period and daemon shutdown bound the wait.
letDiscoveryExit(query, child);
} else {
await retireDiscovery(query, child);
}
}
}
/** Kills discovery processes still exiting after their wait ended. Called on daemon shutdown. */
export async function killExitingClaudeModelDiscoveries(): Promise<void> {
await Promise.all(Array.from(exitingDiscoveries.values(), (kill) => kill()));
}
function letDiscoveryExit(query: DiscoveryQuery, child: ChildProcess): void {
function forget(): void {
clearTimeout(graceTimer);
child.off("exit", onExit);
exitingDiscoveries.delete(child);
}
function onExit(): void {
forget();
query.close();
}
async function kill(): Promise<void> {
forget();
await retireDiscovery(query, child);
}
const graceTimer = setTimeout(() => void kill(), DISCOVERY_EXIT_GRACE_MS);
graceTimer.unref();
child.once("exit", onExit);
exitingDiscoveries.set(child, kill);
}
async function retireDiscovery(
query: DiscoveryQuery | undefined,
child: ChildProcess | undefined,
): Promise<void> {
try {
query?.close();
} finally {
if (child) {
await terminateWithTreeKill(child, { gracefulTimeoutMs: 200, forceTimeoutMs: 200 });
}
}
}
function hasExited(child: ChildProcess): boolean {
return child.exitCode !== null || child.signalCode !== null;
}
@@ -1,3 +1,4 @@
import { ChildProcess } from "node:child_process";
import * as fs from "node:fs/promises";
import * as os from "node:os";
import * as path from "node:path";
@@ -1173,4 +1174,127 @@ describe("Claude model discovery process", () => {
await expect(result).rejects.toBe(failure);
expect(closed).toBe(true);
});
describe("when the CLI is still starting up at the deadline", () => {
// Without a pid, terminateWithTreeKill signals the child directly instead of a real tree.
class StartingClaudeProcess extends ChildProcess {
readonly signals: string[] = [];
override kill(signal?: NodeJS.Signals | number): boolean {
this.signals.push(String(signal));
this.emit("exit", null, signal);
return true;
}
exitOnItsOwn(): void {
this.emit("exit", 0, null);
}
}
interface StalledDiscoveryState {
closed: boolean;
inputEnded: boolean;
}
async function recordInputEnd(
prompt: AsyncIterable<unknown>,
state: StalledDiscoveryState,
): Promise<void> {
await prompt[Symbol.asyncIterator]().next();
state.inputEnded = true;
}
// By default the CLI never answers: an expired OAuth token is refreshed first.
function startStalledDiscovery(
supportedModels: () => Promise<ModelInfo[]> = () => new Promise<ModelInfo[]>(() => {}),
) {
const child = new StartingClaudeProcess();
const state: StalledDiscoveryState = { closed: false, inputEnded: false };
const result = discoverClaudeModels(
{ resolveBinary: async () => "/claude", env: {} },
(input, context) => {
if (typeof input.prompt === "string") throw new Error("unexpected inference prompt");
void recordInputEnd(input.prompt, state);
context.onChildProcess?.(child);
return {
supportedModels,
close: () => {
state.closed = true;
},
};
},
);
return { child, state, result };
}
afterEach(() => {
vi.useRealTimers();
});
it("stops waiting at the limit but lets the CLI finish instead of killing it", async () => {
vi.useFakeTimers();
const { child, state, result } = startStalledDiscovery();
const settled = expect(result).rejects.toThrow("Claude model discovery timed out");
await vi.advanceTimersByTimeAsync(5_000);
await settled;
expect(state.inputEnded).toBe(true);
expect(child.signals).toEqual([]);
expect(state.closed).toBe(false);
await vi.advanceTimersByTimeAsync(59_999);
expect(child.signals).toEqual([]);
await vi.advanceTimersByTimeAsync(1);
expect(child.signals).toEqual(["SIGTERM"]);
expect(state.closed).toBe(true);
});
async function answerAtOnce(): Promise<ModelInfo[]> {
return [];
}
it("lets the CLI finish after it answers instead of killing it", async () => {
// The CLI answers supportedModels() before its startup token refresh has saved the
// rotated refresh token, so a kill right after the answer also logs the user out.
vi.useFakeTimers();
const { child, state, result } = startStalledDiscovery(answerAtOnce);
await expect(result).resolves.toEqual([]);
await vi.advanceTimersByTimeAsync(0);
expect(state.inputEnded).toBe(true);
expect(child.signals).toEqual([]);
await vi.advanceTimersByTimeAsync(1_000);
child.exitOnItsOwn();
expect(state.closed).toBe(true);
await vi.advanceTimersByTimeAsync(120_000);
expect(child.signals).toEqual([]);
});
it("never signals a CLI that exits on its own during the grace period", async () => {
vi.useFakeTimers();
const { child, state, result } = startStalledDiscovery();
const settled = expect(result).rejects.toThrow("Claude model discovery timed out");
await vi.advanceTimersByTimeAsync(5_000);
await settled;
await vi.advanceTimersByTimeAsync(2_000);
child.exitOnItsOwn();
expect(state.closed).toBe(true);
await vi.advanceTimersByTimeAsync(120_000);
expect(child.signals).toEqual([]);
});
it("tree-kills a still-running CLI when the daemon shuts down", async () => {
vi.useFakeTimers();
const { child, state, result } = startStalledDiscovery();
const settled = expect(result).rejects.toThrow("Claude model discovery timed out");
await vi.advanceTimersByTimeAsync(5_000);
await settled;
expect(child.signals).toEqual([]);
await new ClaudeAgentClient({ logger: createTestLogger() }).shutdown();
expect(child.signals).toEqual(["SIGTERM"]);
expect(state.closed).toBe(true);
});
});
});
@@ -22,6 +22,18 @@ function isCodexInstalled(): boolean {
}
}
function supportsInstructionSnapshots(): boolean {
try {
const match = execFileSync("codex", ["--version"], { encoding: "utf8" }).match(
/(\d+)\.(\d+)\.(\d+)/,
);
if (!match) return false;
return Number(match[1]) > 0 || Number(match[2]) >= 121;
} catch {
return false;
}
}
function sse(events: unknown[]): string {
return events
.map((event) => {
@@ -133,7 +145,7 @@ async function startMockResponsesServer(sequence: string[]): Promise<{
}> {
const requestBodies: string[] = [];
let index = 0;
const server = createServer((req, res) => {
const server = createServer({ maxHeaderSize: 1024 * 1024 }, (req, res) => {
const chunks: Buffer[] = [];
req.on("data", (chunk) => chunks.push(Buffer.from(chunk)));
req.on("end", () => {
@@ -221,6 +233,85 @@ function waitForEvent<TEvent extends AgentStreamEvent>(params: {
}
describe("Codex app-server provider (local e2e)", () => {
test.runIf(supportsInstructionSnapshots())(
"delivers changed and removed instructions to the model across process restarts",
async () => {
const artifactDir = path.resolve(process.cwd(), "../../.artifacts");
mkdirSync(artifactDir, { recursive: true });
const cwd = mkdtempSync(path.join(artifactDir, "codex-snapshot-cwd-"));
const codexHome = mkdtempSync(path.join(artifactDir, "codex-snapshot-home-"));
const server = await startMockResponsesServer([]);
const client = new CodexAppServerAgentClient(createTestLogger());
const base = { provider: "codex" as const, cwd, modeId: "auto", model: "mock-model" };
const launch = { env: { CODEX_HOME: codexHome } };
const run = async (session: Awaited<ReturnType<typeof client.createSession>>) => {
const finished = waitForEvent({
session,
timeoutMs: 20_000,
label: "turn completion",
predicate: (
event,
): event is Extract<
AgentStreamEvent,
{ type: "turn_completed" | "turn_failed" | "turn_canceled" }
> =>
event.type === "turn_completed" ||
event.type === "turn_failed" ||
event.type === "turn_canceled",
});
await session.startTurn("continue");
const result = await finished;
if (result.type !== "turn_completed") throw new Error(JSON.stringify(result));
const handle = session.describePersistence();
if (!handle) throw new Error("Expected persisted Codex thread");
await session.close();
return handle;
};
try {
writeMockCodexConfig(codexHome, server.url);
let handle = await run(
await client.createSession(
{ ...base, pluginAppendSystemPrompt: ["old snapshot"] },
launch,
),
);
expect(server.requestBodies.at(-1)).toContain("old snapshot");
expect(server.requestBodies.at(-1)).not.toContain("paseo_instruction_snapshot");
handle = await run(
await client.resumeSession(
handle,
{ ...base, pluginAppendSystemPrompt: ["new snapshot"] },
launch,
),
);
expect(server.requestBodies.at(-1)).toContain("new snapshot");
expect(server.requestBodies.at(-1)?.match(/paseo_instruction_snapshot/g)).toHaveLength(2);
handle = await run(
await client.resumeSession(
handle,
{ ...base, pluginAppendSystemPrompt: ["new snapshot"] },
launch,
),
);
expect(server.requestBodies.at(-1)?.match(/paseo_instruction_snapshot/g)).toHaveLength(2);
await run(
await client.resumeSession(
handle,
{ ...base, pluginAppendSystemPrompt: undefined },
launch,
),
);
expect(server.requestBodies.at(-1)).toContain('\\"instructions\\":\\"\\"');
expect(server.requestBodies.at(-1)?.match(/paseo_instruction_snapshot/g)).toHaveLength(4);
} finally {
await server.close();
rmSync(cwd, { recursive: true, force: true });
rmSync(codexHome, { recursive: true, force: true });
}
},
60_000,
);
test.runIf(isCodexInstalled())(
"concurrent import scans initialize successfully in a fresh shared Codex home",
async () => {
@@ -7,6 +7,7 @@ import { tmpdir } from "node:os";
import path from "node:path";
import { PassThrough } from "node:stream";
import { fileURLToPath } from "node:url";
import { CodexInstructionSnapshot } from "./codex/instruction-snapshot.js";
import type {
AgentClient,
@@ -100,6 +101,7 @@ import {
import { createTestLogger } from "../../../test-utils/test-logger.js";
import { asInternals as castInternals, createStub } from "../../test-utils/class-mocks.js";
import { AgentManager } from "../agent-manager.js";
import { AgentStorage } from "../agent-storage.js";
import { buildProviderRegistry } from "../provider-registry.js";
interface CollaborationModeRecord {
@@ -173,6 +175,9 @@ function createSession(
) as CodexTestSession;
session.connectionState = "connected";
session.currentThreadId = "test-thread";
castInternals<{ instructionSnapshot: { recordNewThread(id: string): void } }>(
session,
).instructionSnapshot.recordNewThread("test-thread");
session.activeForegroundTurnId = "test-turn";
return session;
}
@@ -683,7 +688,7 @@ function codexAgentItem(text: string) {
// An AgentManager over a real Codex provider whose every spawn gets a fresh fake
// app-server serving `threads` from thread/read.
function createReopenableCodexAgent(threads: Record<string, unknown[]>) {
function createReopenableCodexAgent(threads: Record<string, unknown[]>, registry?: AgentStorage) {
const appServers: FakeCodexAppServer[] = [];
const provider = new CodexAppServerAgentClient(createTestLogger(), undefined, {
appServerProcess: createFakeCodexAppServerProcess(() => {
@@ -715,7 +720,11 @@ function createReopenableCodexAgent(threads: Record<string, unknown[]>) {
},
resumeSession: (...args) => provider.resumeSession(...args),
};
const manager = new AgentManager({ clients: { codex: client }, logger: createTestLogger() });
const manager = new AgentManager({
clients: { codex: client },
registry,
logger: createTestLogger(),
});
const agentId = "00000000-0000-4000-8000-000000000001";
const handle = { provider: "codex", sessionId: "saved-thread" };
const config = createConfig({ cwd: process.cwd() });
@@ -728,6 +737,9 @@ function createReopenableCodexAgent(threads: Record<string, unknown[]>) {
return {
manager,
agentId,
handle,
config,
appServers,
latestAppServer: () => appServers[appServers.length - 1],
threadMethods: (index: number) =>
appServers[index]
@@ -1406,6 +1418,216 @@ describe("Codex app-server provider", () => {
}
});
test("reopening drops disabled plugin instructions and starts with fresh collaboration settings", async () => {
const modes = {
data: [
{
name: "Code",
mode: "default",
model: null,
reasoning_effort: null,
},
],
};
const firstServer = createFakeCodexAppServer({ "collaborationMode/list": () => modes });
const first = await createProviderWithFakeAppServer(firstServer).createSession(
createConfig({ pluginAppendSystemPrompt: ["Plugin instructions"] }),
);
await first.startTurn("first");
const firstTurn = await firstServer.waitForTurnStart();
expect(
firstServer.requests().find((request) => request.method === "thread/start")?.params,
).toMatchObject({ developerInstructions: "Plugin instructions" });
expect(firstTurn).toMatchObject({
collaborationMode: {
settings: { developer_instructions: null },
},
});
const started = waitForNextEvent(first, "thread_started");
firstServer.startsTurn({ threadId: "thread-1" });
await started;
const handle = first.describePersistence()!;
expect(handle.metadata).not.toHaveProperty("pluginAppendSystemPrompt");
await first.close();
const secondServer = createFakeCodexAppServer({ "collaborationMode/list": () => modes });
const resumed = await createProviderWithFakeAppServer(secondServer).resumeSession(handle, {
pluginAppendSystemPrompt: undefined,
});
try {
const resume = secondServer.requests().find((request) => request.method === "thread/resume");
expect(resume?.params).not.toHaveProperty("developerInstructions");
await resumed.startTurn("after disable");
const secondTurn = await secondServer.waitForTurnStart();
expect(secondTurn).not.toHaveProperty("developerInstructions");
expect(secondTurn).toMatchObject({
collaborationMode: { settings: { developer_instructions: null } },
});
firstServer.assertNoErrors();
secondServer.assertNoErrors();
} finally {
await resumed.close();
}
});
test("reopen injects current instructions once, including an explicit empty snapshot", async () => {
const handlers = {
initialize: () => ({ userAgent: "codex/0.165.0" }),
"thread/inject_items": () => ({}),
};
const firstServer = createFakeCodexAppServer(handlers);
const first = await createProviderWithFakeAppServer(firstServer).createSession(
createConfig({ pluginAppendSystemPrompt: ["Old plugin"] }),
);
await first.startTurn("first");
const started = waitForNextEvent(first, "thread_started");
firstServer.startsTurn({ threadId: "thread-1" });
await started;
expect(
firstServer.requests().filter((request) => request.method === "thread/inject_items"),
).toEqual([]);
const original = first.describePersistence()!;
expect(original.metadata).toHaveProperty("paseoInstructionReceipt");
await first.close();
const changedServer = createFakeCodexAppServer(handlers);
const changed = await createProviderWithFakeAppServer(changedServer).resumeSession(original, {
pluginAppendSystemPrompt: ["New plugin"],
});
const injected = changedServer
.requests()
.filter((request) => request.method === "thread/inject_items");
expect(injected).toHaveLength(1);
expect(JSON.stringify(injected[0]?.params)).toContain("New plugin");
const changedHandle = changed.describePersistence()!;
expect(changedHandle.metadata?.paseoInstructionReceipt).not.toEqual(
original.metadata?.paseoInstructionReceipt,
);
await changed.close();
const sameServer = createFakeCodexAppServer(handlers);
const same = await createProviderWithFakeAppServer(sameServer).resumeSession(changedHandle, {
pluginAppendSystemPrompt: ["New plugin"],
});
expect(
sameServer.requests().filter((request) => request.method === "thread/inject_items"),
).toEqual([]);
await same.close();
const emptyServer = createFakeCodexAppServer(handlers);
const empty = await createProviderWithFakeAppServer(emptyServer).resumeSession(changedHandle, {
pluginAppendSystemPrompt: undefined,
});
const removal = emptyServer
.requests()
.filter((request) => request.method === "thread/inject_items");
expect(removal).toHaveLength(1);
expect(JSON.stringify(removal[0]?.params)).toContain('\\"instructions\\":\\"\\"');
await empty.close();
});
test("requires a compatible Codex version before creating a thread with plugin instructions", async () => {
const appServer = createFakeCodexAppServer({
initialize: () => ({ userAgent: "codex/0.120.0" }),
});
await expect(
createProviderWithFakeAppServer(appServer).createSession(
createConfig({ pluginAppendSystemPrompt: ["Plugin instructions"] }),
),
).rejects.toThrow("Update Codex to 0.121.0 or newer");
});
test("retries an instruction snapshot when injection fails", async () => {
const snapshot = new CodexInstructionSnapshot("current", undefined);
const request = vi
.fn()
.mockRejectedValueOnce(new Error("connection lost"))
.mockResolvedValue({});
await expect(snapshot.apply("thread-1", request, true)).rejects.toThrow("connection lost");
expect(snapshot.describe("thread-1")).toBeUndefined();
await snapshot.apply("thread-1", request, true);
expect(snapshot.describe("thread-1")).toEqual({
threadId: "thread-1",
digest: expect.any(String),
});
await snapshot.apply("thread-1", request, true);
expect(request).toHaveBeenCalledTimes(2);
});
test("keeps built-in Plan instructions while sending plugin instructions to the thread", async () => {
const appServer = createFakeCodexAppServer({
"collaborationMode/list": () => ({
data: [
{ name: "Plan", mode: "plan", model: null, reasoning_effort: "medium" },
{ name: "Default", mode: "default", model: null, reasoning_effort: null },
],
}),
});
const session = await createProviderWithFakeAppServer(appServer).createSession(
createConfig({
pluginAppendSystemPrompt: ["Plugin instructions"],
providerOptions: { plan_mode: true },
}),
);
try {
await session.startTurn("make a plan");
const start = appServer.requests().find((request) => request.method === "thread/start");
expect(start?.params).toMatchObject({ developerInstructions: "Plugin instructions" });
expect(await appServer.waitForTurnStart()).toMatchObject({
collaborationMode: { mode: "plan", settings: { developer_instructions: null } },
});
expect(
appServer.requests().find((request) => request.method === "turn/start")?.params,
).not.toHaveProperty("developerInstructions");
appServer.assertNoErrors();
} finally {
await session.close();
}
});
test.each([
{ instructions: undefined, expected: undefined },
{ instructions: ["Current plugin"], expected: "Current plugin" },
])(
"rebuilds restored instructions with an unavailable collaboration catalog: $expected",
async ({ instructions, expected }) => {
const appServer = createFakeCodexAppServer({
"collaborationMode/list": () => ({ data: [] }),
"thread/resume": () => ({
thread: { id: "saved-thread" },
collaborationMode: {
mode: "default",
settings: {
model: "gpt-5.4",
reasoning_effort: "medium",
developer_instructions: "Old plugin",
},
},
}),
});
const session = await createProviderWithFakeAppServer(appServer).resumeSession(
{ sessionId: "saved-thread" },
{ pluginAppendSystemPrompt: instructions },
);
try {
const resume = appServer.requests().find((request) => request.method === "thread/resume");
if (expected) expect(resume?.params).toMatchObject({ developerInstructions: expected });
else expect(resume?.params).not.toHaveProperty("developerInstructions");
await session.startTurn("after reopen");
const turn = await appServer.waitForTurnStart();
expect(turn).toMatchObject({
collaborationMode: {
mode: "default",
settings: { model: "gpt-5.4", developer_instructions: null },
},
});
appServer.assertNoErrors();
} finally {
await session.close();
}
},
);
test("keeps the default effort when a session without one is resumed after a restart", async () => {
const beforeRestart = createFakeCodexAppServer();
const firstSession = await createProviderWithFakeAppServer(beforeRestart).createSession(
@@ -2215,6 +2437,36 @@ describe("Codex app-server provider", () => {
appServer.assertNoErrors();
});
test("lets idle cleanup release a session opened only to read its history", async () => {
let spawns = 0;
const appServer = createFakeCodexAppServer({
"thread/resume": () =>
Promise.reject(new Error(archivedThreadErrorMessage("archived-thread-id"))),
"thread/read": () => ({ thread: { turns: [] } }),
});
const provider = new CodexAppServerAgentClient(createTestLogger(), undefined, {
appServerProcess: createFakeCodexAppServerProcess(() => {
spawns += 1;
return appServer.child;
}),
});
const internals = castInternals<{
goalsEnabledPromise: Promise<boolean> | null;
autoReviewEnabledPromise: Promise<boolean> | null;
}>(provider);
internals.goalsEnabledPromise = Promise.resolve(false);
internals.autoReviewEnabledPromise = Promise.resolve(false);
const session = await provider.resumeSession(archivedThreadHandle(), undefined, undefined, {
purpose: "history",
});
expect(await session.canStopRuntime!()).toBe(true);
expect(spawns).toBe(1);
await session.close();
appServer.assertNoErrors();
});
test("unarchives Codex when an active Paseo agent resumes an archived thread", async () => {
const threadRequests: string[] = [];
let resumeAttempts = 0;
@@ -2285,7 +2537,12 @@ describe("Codex app-server provider", () => {
]);
// Background terminal observation is independent of conversation history loading.
const historyMethods = (index: number) =>
codex.threadMethods(index).filter((method) => method !== "thread/backgroundTerminals/list");
codex
.threadMethods(index)
.filter(
(method) =>
method !== "thread/backgroundTerminals/list" && method !== "thread/inject_items",
);
expect(historyMethods(0)).toEqual([
"thread/loaded/list",
"thread/resume",
@@ -2299,6 +2556,34 @@ describe("Codex app-server provider", () => {
}
});
test("persists an acknowledged instruction snapshot before a turn on repeated opens", async () => {
const artifactDir = path.resolve(process.cwd(), "../../.artifacts");
mkdirSync(artifactDir, { recursive: true });
const dir = await mkdtemp(path.join(artifactDir, "codex-receipt-"));
const storage = new AgentStorage(dir, createTestLogger());
const codex = createReopenableCodexAgent({}, storage);
try {
let handle = codex.handle;
for (let i = 0; i < 3; i++) {
await codex.manager.resumeAgentFromPersistence(handle, codex.config, codex.agentId);
await storage.flush();
const saved = await storage.get(codex.agentId);
expect(saved?.persistence?.metadata?.paseoInstructionReceipt).toEqual(expect.any(Object));
handle = saved!.persistence!;
await codex.manager.closeAgent(codex.agentId);
}
expect(
codex.appServers
.flatMap((server) => server.requests())
.filter((request) => request.method === "thread/inject_items"),
).toHaveLength(1);
} finally {
if (codex.manager.getAgent(codex.agentId)) await codex.manager.closeAgent(codex.agentId);
await storage.flush();
rmSync(dir, { recursive: true, force: true });
}
});
test("rewinds an agent reopened without reading its Codex history", async () => {
const firstTurn = {
id: "turn-1",
@@ -2818,6 +3103,9 @@ describe("Codex app-server provider", () => {
const session = new CodexAppServerAgentSession(
createConfig({
cwd: "/workspace/project",
systemPrompt: "Agent instructions",
daemonAppendSystemPrompt: "Daemon instructions",
pluginAppendSystemPrompt: ["Plugin instructions"],
mcpServers: {
paseo: { type: "http", url: "http://127.0.0.1:6767/mcp/agents?callerAgentId=agent-1" },
},
@@ -2849,6 +3137,24 @@ describe("Codex app-server provider", () => {
await session.revertConversation({ messageId: "codex-first" });
const forkRequest = appServer.requests().find((request) => request.method === "thread/fork");
expect(forkRequest?.params).toMatchObject({
developerInstructions: "Agent instructions\n\nDaemon instructions\n\nPlugin instructions",
});
const rewindRequests = appServer
.requests()
.filter((request) =>
["thread/fork", "thread/rollback", "thread/inject_items"].includes(
String(request.method),
),
);
expect(rewindRequests.map((request) => request.method)).toEqual(
historyMode === "legacy"
? ["thread/fork", "thread/rollback", "thread/inject_items"]
: ["thread/fork", "thread/inject_items"],
);
expect(rewindRequests.at(-1)?.params).toMatchObject({ threadId: "forked-thread" });
expect(JSON.stringify(rewindRequests.at(-1)?.params)).toContain("Plugin instructions");
const forkConfigs = appServer
.requests()
.filter((request) => request.method === "thread/fork")
@@ -55,7 +55,8 @@ import path from "node:path";
import { isDeepStrictEqual } from "node:util";
import { z } from "zod";
import { renderPromptAttachmentAsText } from "../prompt-attachments.js";
import { composeSystemPromptParts } from "../system-prompt.js";
import { composeAgentSystemPrompt } from "../system-prompt.js";
import { CodexInstructionSnapshot } from "./codex/instruction-snapshot.js";
import { CodexAsyncQuestions, codexAsyncQuestionToTimeline } from "./codex/async-questions.js";
import {
fileChangesToPreview,
@@ -3591,9 +3592,12 @@ interface ConsumedRootCompaction {
export class CodexAppServerAgentSession implements AgentSession {
readonly provider = CODEX_PROVIDER;
readonly capabilities = CODEX_APP_SERVER_CAPABILITIES;
readonly persistenceUpdatedOnResume = true;
private readonly logger: Logger;
private readonly config: AgentSessionConfig;
private readonly instructionSnapshot: CodexInstructionSnapshot;
private supportsInstructionSnapshots = false;
private readonly asyncQuestions: CodexAsyncQuestions;
private readonly codexHome: string;
private currentMode: string;
@@ -3706,6 +3710,13 @@ export class CodexAppServerAgentSession implements AgentSession {
reasoning_effort?: string | null;
developer_instructions?: string | null;
}> = [];
private restoredCollaborationMode: {
name: string;
mode: string;
model: string;
reasoning_effort: string | null;
developer_instructions?: never;
} | null = null;
private resolvedCollaborationMode: {
mode: string;
settings: Record<string, unknown>;
@@ -3751,6 +3762,10 @@ export class CodexAppServerAgentSession implements AgentSession {
this.providerOptions =
validateProviderOptions("codex", CodexProviderOptionsSchema, config.providerOptions) ?? {};
this.config = config;
this.instructionSnapshot = new CodexInstructionSnapshot(
composeAgentSystemPrompt(config),
resumeHandle?.metadata?.paseoInstructionReceipt,
);
this.harnessEnvironment = deps.environment ?? buildCodexAppServerEnv();
this.asyncQuestions = new CodexAsyncQuestions(resumeHandle?.metadata?.asyncQuestions);
this.codexHome = deps.codexHome ?? resolveCodexHomeDir(process.env);
@@ -3837,9 +3852,17 @@ export class CodexAppServerAgentSession implements AgentSession {
this.registerRequestHandlers();
try {
this.threadRollbackAvailable = codexServerHasThreadRollback(
toObjectRecord(initialized)?.userAgent,
);
const userAgent = toObjectRecord(initialized)?.userAgent;
this.threadRollbackAvailable = codexServerHasThreadRollback(userAgent);
this.supportsInstructionSnapshots =
typeof userAgent === "string" && codexVersionAtLeast(userAgent, [0, 121, 0]);
if (
!this.currentThreadId &&
this.config.pluginAppendSystemPrompt?.length &&
!this.supportsInstructionSnapshots
) {
throw new Error("Update Codex to 0.121.0 or newer to apply agent instruction updates.");
}
this.speedModels =
CodexModelListResponseSchema.parse(await client.request("model/list", {})).data ?? [];
@@ -4037,18 +4060,17 @@ export class CodexAppServerAgentSession implements AgentSession {
settings: Record<string, unknown>;
name: string;
} | null {
const match = this.findCollaborationMode(this.planModeEnabled ? "plan" : "code");
const match =
this.findCollaborationMode(this.planModeEnabled ? "plan" : "code") ??
this.restoredCollaborationMode;
if (!match) return null;
const settings: Record<string, unknown> = {};
if (match.model) settings.model = match.model;
if (match.reasoning_effort) settings.reasoning_effort = match.reasoning_effort;
const developerInstructions = composeSystemPromptParts(
match.developer_instructions,
this.config.systemPrompt,
this.config.daemonAppendSystemPrompt,
);
if (developerInstructions) settings.developer_instructions = developerInstructions;
// Codex applies thread instructions separately. Null asks it to supply the
// built-in collaboration mode instructions instead of replacing them.
settings.developer_instructions = match.developer_instructions ?? null;
if (this.config.model) settings.model = this.config.model;
const thinkingOptionId = normalizeCodexThinkingOptionId(this.config.thinkingOptionId);
if (thinkingOptionId) settings.reasoning_effort = thinkingOptionId;
@@ -4308,10 +4330,7 @@ export class CodexAppServerAgentSession implements AgentSession {
// the unnamespaced key emitted by earlier Paseo versions.
params.modelProvider = this.deps.customCodexConfig.model_provider;
}
const developerInstructions = composeSystemPromptParts(
this.config.systemPrompt,
this.config.daemonAppendSystemPrompt,
);
const developerInstructions = composeAgentSystemPrompt(this.config);
if (developerInstructions) {
params.developerInstructions = developerInstructions;
}
@@ -4322,11 +4341,11 @@ export class CodexAppServerAgentSession implements AgentSession {
try {
const loaded = toObjectRecord(await this.client.request("thread/loaded/list", {}));
const ids = Array.isArray(loaded?.data) ? loaded.data : [];
if (ids.includes(this.currentThreadId)) {
return;
if (!ids.includes(this.currentThreadId)) {
const response = await this.client.request("thread/resume", params);
this.rememberResolvedSandboxPolicy(response);
this.rememberRestoredCollaborationMode(response);
}
const response = await this.client.request("thread/resume", params);
this.rememberResolvedSandboxPolicy(response);
} catch (error) {
const threadId = this.currentThreadId;
const message = error instanceof Error ? error.message : String(error);
@@ -4340,12 +4359,34 @@ export class CodexAppServerAgentSession implements AgentSession {
}
const response = await this.client.request("thread/resume", params);
this.rememberResolvedSandboxPolicy(response);
this.rememberRestoredCollaborationMode(response);
this.logger.info({ threadId }, "Unarchived Codex thread to restore active Paseo agent");
return;
} else {
this.logger.warn({ error, threadId }, "Failed to resume persisted Codex thread");
throw new Error(`Failed to resume Codex thread ${threadId}: ${message}`, { cause: error });
}
this.logger.warn({ error, threadId }, "Failed to resume persisted Codex thread");
throw new Error(`Failed to resume Codex thread ${threadId}: ${message}`, { cause: error });
}
await this.instructionSnapshot.apply(
this.currentThreadId,
this.client.request.bind(this.client),
this.supportsInstructionSnapshots,
);
}
private rememberRestoredCollaborationMode(response: unknown): void {
const mode = toObjectRecord(toObjectRecord(response)?.collaborationMode);
const settings = toObjectRecord(mode?.settings);
if (typeof mode?.mode !== "string" || typeof settings?.model !== "string") return;
// The resumed mode can contain instructions from a previous launch. Keep its
// identity and model, and let Codex restore the built-in mode instructions.
this.restoredCollaborationMode = {
name: mode.mode,
mode: mode.mode,
model: settings.model,
reasoning_effort:
typeof settings.reasoning_effort === "string" ? settings.reasoning_effort : null,
};
this.refreshResolvedCollaborationMode();
}
private parseSlashCommandInput(text: string): { commandName: string; args?: string } | null {
@@ -4461,13 +4502,7 @@ export class CodexAppServerAgentSession implements AgentSession {
if (options?.outputSchema) {
params.outputSchema = normalizeCodexOutputSchema(options.outputSchema);
}
const developerInstructions = composeSystemPromptParts(
this.config.systemPrompt,
this.config.daemonAppendSystemPrompt,
);
if (developerInstructions) {
params.developerInstructions = developerInstructions;
}
const developerInstructions = composeAgentSystemPrompt(this.config);
const codexConfig = this.buildCodexInnerConfig();
if (codexConfig) {
params.config = codexConfig;
@@ -5226,6 +5261,9 @@ export class CodexAppServerAgentSession implements AgentSession {
systemPrompt: this.config.systemPrompt,
mcpServers: this.config.mcpServers,
asyncQuestions: this.asyncQuestions.serialize(),
...(this.instructionSnapshot.describe(threadId)
? { paseoInstructionReceipt: this.instructionSnapshot.describe(threadId) }
: {}),
},
};
}
@@ -5256,9 +5294,15 @@ export class CodexAppServerAgentSession implements AgentSession {
model: this.config.model ?? null,
serviceTier: this.serviceTier,
config: this.buildCodexInnerConfig(),
developerInstructions: composeAgentSystemPrompt(this.config),
userMessageTurns: this.codexUserMessageTurns(),
threadRollbackAvailable: this.threadRollbackAvailable,
setThreadId: async (threadId) => {
await this.instructionSnapshot.apply(
threadId,
this.client!.request.bind(this.client),
this.supportsInstructionSnapshots,
);
this.currentThreadId = threadId;
// Codex writes a forked thread's rollout when it forks it, even before any turn.
this.savedThreadId = threadId;
@@ -5341,6 +5385,8 @@ export class CodexAppServerAgentSession implements AgentSession {
}
async canStopRuntime(): Promise<boolean> {
// A history session released its app-server once it read the thread, so nothing runs.
if (this.connectionState === "history-ready") return true;
if (
!this.client ||
this.client.hasPendingRequests() ||
@@ -5792,6 +5838,7 @@ export class CodexAppServerAgentSession implements AgentSession {
this.cachedRuntimeInfo = null;
}
this.currentThreadId = threadId;
this.instructionSnapshot.recordNewThread(threadId);
}
private buildThreadStartRequest(model: string): {
@@ -5803,10 +5850,7 @@ export class CodexAppServerAgentSession implements AgentSession {
const approvalPolicy = this.hasWorkflowModeOverride ? preset.approvalPolicy : undefined;
const sandbox = this.hasWorkflowModeOverride ? preset.sandbox : undefined;
const innerConfig = this.buildCodexInnerConfig();
const developerInstructions = composeSystemPromptParts(
this.config.systemPrompt,
this.config.daemonAppendSystemPrompt,
);
const developerInstructions = composeAgentSystemPrompt(this.config);
const params: Record<string, unknown> = {
model,
cwd: this.config.cwd ?? null,
@@ -0,0 +1,69 @@
import { createHash } from "node:crypto";
import { CodexAppServerRpcError } from "./app-server-transport.js";
/** The receipt records only which snapshot was delivered to a particular native thread. */
interface InstructionReceipt {
threadId: string;
digest: string;
}
function readReceipt(value: unknown): InstructionReceipt | null {
if (!value || typeof value !== "object") return null;
const receipt = value as Record<string, unknown>;
if (typeof receipt.threadId !== "string" || typeof receipt.digest !== "string") return null;
if (!/^[a-f0-9]{64}$/.test(receipt.digest)) return null;
return { threadId: receipt.threadId, digest: receipt.digest };
}
export class CodexInstructionSnapshot {
private receipt: InstructionReceipt | null;
private readonly digest: string;
constructor(
private readonly instructions: string | undefined,
receipt: unknown,
) {
this.receipt = readReceipt(receipt);
this.digest = createHash("sha256")
.update(JSON.stringify({ version: 1, instructions: instructions ?? "" }))
.digest("hex");
}
/** A new thread receives its first snapshot through thread/start. */
recordNewThread(threadId: string): void {
this.receipt = { threadId, digest: this.digest };
}
describe(threadId: string): InstructionReceipt | undefined {
return this.receipt?.threadId === threadId ? { ...this.receipt } : undefined;
}
async apply(
threadId: string,
request: (method: string, params: unknown) => Promise<unknown>,
supported: boolean,
): Promise<void> {
if (this.receipt?.threadId === threadId && this.receipt.digest === this.digest) return;
if (!supported)
throw new Error("Update Codex to 0.121.0 or newer to apply agent instruction updates.");
const snapshot = JSON.stringify({ version: 1, instructions: this.instructions ?? "" });
const text =
"This is the complete current set of Paseo-supplied instructions. It supersedes all earlier Paseo-supplied instructions in the conversation, including earlier snapshots. An empty instruction string means there are no current Paseo-supplied instructions. Provider and collaboration instructions remain in effect.\n\n<paseo_instruction_snapshot>" +
snapshot +
"</paseo_instruction_snapshot>";
try {
await request("thread/inject_items", {
threadId,
items: [{ type: "message", role: "developer", content: [{ type: "input_text", text }] }],
});
} catch (error) {
if (error instanceof CodexAppServerRpcError && error.code === -32601) {
throw new Error("Update Codex to 0.121.0 or newer to apply agent instruction updates.", {
cause: error,
});
}
throw error;
}
this.receipt = { threadId, digest: this.digest };
}
}
@@ -49,6 +49,7 @@ export async function revertCodexConversation(input: {
model?: string | null;
serviceTier?: string | null;
config?: Record<string, unknown> | null;
developerInstructions?: string;
userMessageTurns: CodexUserMessageTurnIndex;
threadRollbackAvailable: boolean;
setThreadId: (threadId: string) => void | Promise<void>;
@@ -76,6 +77,7 @@ export async function revertCodexConversation(input: {
model: input.model ?? null,
serviceTier: input.serviceTier ?? null,
...(input.config ? { config: input.config } : {}),
...(input.developerInstructions ? { developerInstructions: input.developerInstructions } : {}),
// Paseo re-reads the rewound thread through paged history, not the fork reply.
excludeTurns: true,
persistExtendedHistory: true,
@@ -171,7 +171,7 @@ export function createFakeCodexAppServer(
const child = createCodexAppServerChildProcess();
const recordedRollbacks: JsonObject[] = [];
const responseHandlers: Record<string, FakeCodexAppServerHandler> = {
initialize: () => ({}),
initialize: () => ({ userAgent: "codex/0.150.0" }),
"collaborationMode/list": () => ({ data: [] }),
"config/read": () => ({ config: {} }),
getUserSavedConfig: () => ({ config: {} }),
@@ -189,6 +189,7 @@ export function createFakeCodexAppServer(
"thread/loaded/list": () => ({ data: [] }),
"thread/backgroundTerminals/list": () => ({ data: [], nextCursor: null }),
"thread/resume": () => ({}),
"thread/inject_items": () => ({}),
"turn/start": () => ({}),
"thread/fork": (params) => ({
thread: {
@@ -0,0 +1,21 @@
// Drops an upstream "Vendor: " prefix ("OpenAI: GPT-5.5"). A colon inside parentheses or after a
// comma belongs to the model name ("DeepSeek V4 (ctx: 128k)"), so it is kept.
function stripVendorPrefix(label: string): string {
const vendorSeparatorIndex = label.indexOf(": ");
if (vendorSeparatorIndex === -1 || /[(),]/.test(label.slice(0, vendorSeparatorIndex))) {
return label;
}
return label.slice(vendorSeparatorIndex + 2).trim();
}
// The label Pi and OMP show for a model from their catalogs. A model name is either a path
// ("google/gemini_2.5-flash", as OpenRouter reports it) or free text that can contain slashes
// and underscores ("IQ3_S ... 52/56"). Only paths are shortened.
export function modelDisplayLabel(model: { id: string; name?: string }): string {
const text = model.name?.trim().replace(/\s+/g, " ") || model.id.trim();
if (/\s/.test(text)) {
return stripVendorPrefix(text);
}
const lastSegment = text.split("/").findLast((segment) => segment.length > 0) ?? text;
return stripVendorPrefix(lastSegment.replace(/_+/g, " "));
}
@@ -1855,3 +1855,69 @@ test("closing OMP during image conversion rejects its pending start", async () =
await session.close();
await rejected;
});
describe("OMP catalog model labels", () => {
test.each([
{
name: "keeps slashes and underscores inside a free-text model name",
model: {
provider: "llama-swap",
id: "s-q3fn(p-t)",
name: "Qwen3.8 Flash Next IQ3_S, prior + tail skip (fastest, ~60-70 tok/s on 0.2.10, 52/56)",
},
label: "Qwen3.8 Flash Next IQ3_S, prior + tail skip (fastest, ~60-70 tok/s on 0.2.10, 52/56)",
},
{
name: "keeps a free-text name that ends in a slash-separated word",
model: {
provider: "llama-swap",
id: "ds-strata-6",
name: "DeepSeek V4.1 Flash 2.25bpw via Strata (full 6 experts, untested, ~5-6 tok/s)",
},
label: "DeepSeek V4.1 Flash 2.25bpw via Strata (full 6 experts, untested, ~5-6 tok/s)",
},
{
name: "keeps a colon inside a free-text model name",
model: {
provider: "llama-swap",
id: "qwen3-tail",
name: "Qwen3 IQ3_S (tail skip: on, 52/56)",
},
label: "Qwen3 IQ3_S (tail skip: on, 52/56)",
},
{
name: "keeps an OMP catalog name as it is",
model: {
provider: "openrouter",
id: "anthropic/claude-opus-4.1:batch",
name: "Claude Opus 4.1 (batch)",
},
label: "Claude Opus 4.1 (batch)",
},
{
name: "drops the vendor prefix from an upstream model name",
model: { provider: "openrouter", id: "openai/gpt-5.5", name: "OpenAI: GPT-5.5" },
label: "GPT-5.5",
},
{
name: "falls back to the last segment of a path-like id",
model: { provider: "pioneer", id: "canada-quant/glm_5.2" },
label: "glm 5.2",
},
])("$name", async ({ model, label }) => {
const runtime = new FakeOmp();
runtime.queueSessionSetup((session) => {
session.models = [model];
});
const client = new OmpAgentClient({ logger: createTestLogger(), runtime });
const catalog = await client.fetchCatalog({
scope: "workspace",
cwd: "/workspace/project",
force: false,
});
expect(catalog.models.map((entry) => entry.label)).toEqual([label]);
expect(catalog.models[0]?.id).toBe(`${model.provider}/${model.id}`);
});
});
@@ -15,7 +15,6 @@ import {
type AgentLaunchContext,
type AgentMetadata,
type AgentMode,
type AgentModelDefinition,
type AgentPermissionRequest,
type AgentPermissionResponse,
type AgentProviderNotice,
@@ -252,36 +251,6 @@ interface OmpSlashCommandInvocation {
type AutoCompactMode = boolean | "toggle" | "unknown";
function normalizeOmpModelLabel(label: string): string {
const normalizedLabel = label.trim().replace(/[_\s]+/g, " ");
const vendorSeparatorIndex = normalizedLabel.indexOf(": ");
if (vendorSeparatorIndex === -1) {
return normalizedLabel;
}
return normalizedLabel.slice(vendorSeparatorIndex + 2).trim();
}
export function transformOmpModels(models: AgentModelDefinition[]): AgentModelDefinition[] {
return models.map((model) => {
if (!model.label.includes("/")) {
return model;
}
const segments = model.label.split("/").filter((segment) => segment.length > 0);
const rawLabel = segments.at(-1);
if (!rawLabel) {
return model;
}
return {
...model,
label: normalizeOmpModelLabel(rawLabel),
description: model.description ?? model.label,
};
});
}
function isOmpThinkingLevel(value: string | null | undefined): value is OmpThinkingLevel {
return (
value === "off" ||
@@ -466,6 +435,7 @@ function buildResumeStartInput(input: {
systemPrompt: composeSystemPromptParts(
input.resumeConfig.config.systemPrompt,
input.resumeConfig.config.daemonAppendSystemPrompt,
...(input.resumeConfig.config.pluginAppendSystemPrompt ?? []),
),
};
}
@@ -2370,7 +2340,11 @@ export class OmpAgentClient implements AgentClient {
noSession: config.internal === true,
modeId: launchMode.modeId,
extraArgs: launchMode.extraArgs,
systemPrompt: composeSystemPromptParts(config.systemPrompt, config.daemonAppendSystemPrompt),
systemPrompt: composeSystemPromptParts(
config.systemPrompt,
config.daemonAppendSystemPrompt,
...(config.pluginAppendSystemPrompt ?? []),
),
env: launchContext?.env,
};
const runtimeSession = await this.resolveRuntime(config.providerOptions).startSession(
@@ -2571,13 +2545,11 @@ export class OmpAgentClient implements AgentClient {
});
if (!runtimeSession) throw new Error("OMP catalog runtime did not start");
const catalogSession = runtimeSession;
const models = transformOmpModels(
(
await runProviderRefreshActivity(context, "get_available_models", () =>
catalogSession.getAvailableModels(null),
)
).map((model) => mapOmpModel(model, this.provider)),
);
const models = (
await runProviderRefreshActivity(context, "get_available_models", () =>
catalogSession.getAvailableModels(null),
)
).map((model) => mapOmpModel(model, this.provider));
return { models, modes: [...OMP_MODES] };
} finally {
context?.signal.removeEventListener("abort", handleAbort);
@@ -164,7 +164,7 @@ describe("mapOmpModel thinking options", () => {
expect(result.provider).toBe("omp");
expect(result.id).toBe("pioneer/canada-quant/glm-5.2");
expect(result.label).toBe("pioneer/GLM-5.2");
expect(result.label).toBe("GLM-5.2");
expect(result.metadata).toEqual({ provider: "pioneer", modelId: "canada-quant/glm-5.2" });
});
});
@@ -3,6 +3,7 @@ import type {
AgentProvider,
AgentSelectOption,
} from "../../agent-sdk-types.js";
import { modelDisplayLabel } from "../model-label.js";
import type { OmpModel, OmpThinkingLevel } from "./rpc-types.js";
export const DEFAULT_OMP_THINKING_LEVEL: OmpThinkingLevel = "medium";
@@ -43,7 +44,7 @@ export function mapOmpModel(model: OmpModel, provider: AgentProvider): AgentMode
return {
provider,
id: `${model.provider}/${model.id}`,
label: `${model.provider}/${model.name ?? model.id}`,
label: modelDisplayLabel(model),
description: `${model.provider}/${model.id}`,
metadata: {
provider: model.provider,
@@ -2477,6 +2477,42 @@ describe("OpenCode adapter startTurn error handling", () => {
await session.close();
});
test("reports a question rejected by a human steer as resolved", async () => {
const { parent: session, openCode } = await createParentSession("ses_steer_question");
openCode.sessionPromptAsyncEvents = [];
const events: AgentStreamEvent[] = [];
session.subscribe((event) => events.push(event));
const { turnId } = await session.startTurn("first");
openCode.emitEvent({
type: "question.asked",
properties: {
id: "question-steer",
sessionID: "ses_steer_question",
questions: [{ question: "Which color?", header: "Color", options: [] }],
},
});
await vi.waitFor(() => expect(session.getPendingPermissions()).toHaveLength(1));
await expect(
session.steerActiveTurn?.("never mind", {
expectedTurnId: turnId,
clearPendingPermissions: true,
}),
).resolves.toEqual({ status: "accepted" });
expect(openCode.calls.questionReject).toContainEqual(
expect.objectContaining({ requestID: "question-steer" }),
);
expect(events).toContainEqual(
expect.objectContaining({
type: "permission_resolved",
requestId: "question-steer",
resolution: expect.objectContaining({ behavior: "deny" }),
}),
);
await session.close();
});
test("keeps multiple native steers correlated in admission order", async () => {
const { parent: session, openCode } = await createParentSession("ses_native_steer_fifo");
openCode.sessionPromptAsyncEvents = [];
@@ -30,6 +30,7 @@ import {
type AgentDraftControls,
type AgentOptionControl,
type AgentLaunchContext,
type AgentResumeSessionOptions,
type AgentMode,
type AgentModelDefinition,
type AgentPermissionAction,
@@ -1521,6 +1522,7 @@ export class OpenCodeAgentClient implements AgentClient {
handle: AgentPersistenceHandle,
overrides?: Partial<AgentSessionConfig>,
launchContext?: AgentLaunchContext,
_options?: AgentResumeSessionOptions,
): Promise<AgentSession> {
const metadata = (handle.metadata ?? {}) as Partial<AgentSessionConfig>;
const cwd = overrides?.cwd ?? metadata.cwd;
@@ -3692,6 +3694,7 @@ class OpenCodeAgentSession implements AgentSession {
const systemPrompt = composeSystemPromptParts(
this.config.systemPrompt,
this.config.daemonAppendSystemPrompt,
...(this.config.pluginAppendSystemPrompt ?? []),
);
const model = this.parseModel(this.config.model);
const effectiveMode = resolveOpenCodeRuntimeAgentId(this.currentMode);
@@ -4029,6 +4032,7 @@ class OpenCodeAgentSession implements AgentSession {
const systemPrompt = composeSystemPromptParts(
this.config.systemPrompt,
this.config.daemonAppendSystemPrompt,
...(this.config.pluginAppendSystemPrompt ?? []),
);
const promptResponse = await this.client.session.promptAsync({
sessionID: this.sessionId,
@@ -5045,22 +5049,24 @@ class OpenCodeAgentSession implements AgentSession {
answers,
});
}
this.pendingPermissions.delete(requestId);
this.pendingPermissionDirectories.delete(requestId);
return;
} else {
const reply = resolveOpenCodePermissionReply(response);
await this.client.permission.reply({
requestID: requestId,
directory,
reply,
message: response.behavior === "deny" ? response.message : undefined,
});
}
const reply = resolveOpenCodePermissionReply(response);
await this.client.permission.reply({
requestID: requestId,
directory,
reply,
message: response.behavior === "deny" ? response.message : undefined,
});
this.pendingPermissions.delete(requestId);
this.pendingPermissionDirectories.delete(requestId);
this.notifySubscribers({
type: "permission_resolved",
provider: "opencode",
requestId,
resolution: response,
});
}
describePersistence(): AgentPersistenceHandle | null {
@@ -4,6 +4,7 @@ import type {
AgentSessionConfig,
AgentLaunchContext,
AgentCreateSessionOptions,
AgentResumeSessionOptions,
AgentPersistenceHandle,
FetchCatalogOptions,
ProviderRefreshContext,
@@ -149,9 +150,10 @@ export class OpenCodeRuntimeClient implements AgentClient {
handle: AgentPersistenceHandle,
config?: Partial<AgentSessionConfig>,
launch?: AgentLaunchContext,
options?: AgentResumeSessionOptions,
) {
const client = await this.client();
const session = await client.resumeSession(handle, config, launch);
const session = await client.resumeSession(handle, config, launch, options);
return client === this.legacy ? session : withOpenCodeRuntimeNotice(session, 2, handle);
}
async fetchCatalog(options: FetchCatalogOptions, context?: ProviderRefreshContext) {
@@ -28,6 +28,7 @@ export class V2Harness {
readonly prompts: string[] = [];
readonly environments: Array<{ sessionID: string; variables: Record<string, string> }> = [];
readonly mcpAdds: string[] = [];
readonly instructions = new Map<string, string>();
releases = 0;
active = false;
activeReads = 0;
@@ -153,7 +154,17 @@ export class V2Harness {
environment: async (input) => {
this.environments.push(input);
},
instructions: { entry: { list: unexpected, put: unexpected, remove: unexpected } },
instructions: {
entry: {
list: async () => [...this.instructions].map(([key, value]) => ({ key, value })),
put: async ({ key, value }) => {
this.instructions.set(key, String(value));
},
remove: async ({ key }) => {
this.instructions.delete(key);
},
},
},
prompt: async (input, options) => {
const before = this.executions.length;
await this.prompt(input, options);
@@ -17,6 +17,54 @@ function terminalEvents(events: AgentStreamEvent[]) {
}
describe("OpenCode v2 session lifecycle", () => {
test("reopening replaces and removes plugin instructions", async () => {
const harness = new V2Harness();
const client = new OpenCodeV2AgentClient({
logger: createTestLogger(),
runtime: harness.runtime,
});
const created = await client.createSession({
provider: "opencode",
cwd: "/tmp/project",
pluginAppendSystemPrompt: ["first"],
});
expect(harness.instructions.get("paseo")).toBe("first");
const handle = created.describePersistence()!;
await created.close();
const resumed = await client.resumeSession(handle, {
cwd: "/tmp/project",
pluginAppendSystemPrompt: ["changed"],
});
expect(harness.instructions.get("paseo")).toBe("changed");
await resumed.close();
const cleared = await client.resumeSession(handle, {
cwd: "/tmp/project",
pluginAppendSystemPrompt: undefined,
});
expect(harness.instructions.has("paseo")).toBe(false);
await cleared.close();
});
test("opening history does not change an existing session instruction", async () => {
const harness = new V2Harness();
harness.instructions.set("paseo", "Existing plugin instruction");
const client = new OpenCodeV2AgentClient({
logger: createTestLogger(),
runtime: harness.runtime,
});
const session = await client.resumeSession(
{ provider: "opencode", sessionId: "session", metadata: { cwd: "/tmp/project" } },
{ cwd: "/tmp/project" },
undefined,
{ purpose: "history" },
);
try {
expect(harness.instructions.get("paseo")).toBe("Existing plugin instruction");
} finally {
await session.close();
}
});
test("refreshes the existing location before reading a forced catalog", async () => {
const harness = new V2Harness();
const refreshed: string[] = [];
@@ -17,6 +17,7 @@ import type {
AgentCapabilityFlags,
AgentClient,
AgentCreateSessionOptions,
AgentResumeSessionOptions,
AgentDraftControls,
AgentLaunchContext,
AgentPersistenceHandle,
@@ -131,6 +132,7 @@ export class OpenCodeV2AgentClient implements AgentClient {
handle: AgentPersistenceHandle,
overrides?: Partial<AgentSessionConfig>,
launch?: AgentLaunchContext,
options?: AgentResumeSessionOptions,
): Promise<AgentSession> {
const cwd = overrides?.cwd ?? handle.metadata?.cwd;
if (typeof cwd !== "string")
@@ -151,7 +153,14 @@ export class OpenCodeV2AgentClient implements AgentClient {
sessionID: handle.nativeHandle ?? handle.sessionId,
});
await applyResumeOverrides(connection.client, info, overrides);
return await this.attach(connection, info, config, launch, true);
return await this.attach(
connection,
info,
config,
launch,
true,
options?.purpose === "history",
);
} catch (error) {
await connection.release();
throw error;
@@ -163,6 +172,7 @@ export class OpenCodeV2AgentClient implements AgentClient {
config: AgentSessionConfig,
launch: AgentLaunchContext | undefined,
persist: boolean,
historyOnly = false,
) {
const acquire = () =>
this.runtime.acquire(
@@ -209,6 +219,7 @@ export class OpenCodeV2AgentClient implements AgentClient {
bindChild,
acquire,
moved,
historyOnly,
);
try {
await session.initialize(
@@ -75,6 +75,7 @@ export class OpenCodeV2Session implements AgentSession {
bindChild?: (id: string) => void,
private readonly acquire?: () => Promise<V2Connection>,
private readonly moved?: (connection: V2Connection) => void,
private readonly historyOnly = false,
) {
this.background = new OpenCodeBackgroundInventory({
id: info.id,
@@ -193,16 +194,24 @@ export class OpenCodeV2Session implements AgentSession {
});
await this.awaitMcp(server);
}
if (this.historyOnly) return;
const system = composeSystemPromptParts(
this.config.systemPrompt,
this.config.daemonAppendSystemPrompt,
...(this.config.pluginAppendSystemPrompt ?? []),
);
if (system)
if (system) {
await this.client.session.instructions.entry.put({
sessionID: this.id,
key: "paseo",
value: system,
});
} else {
const entries = await this.client.session.instructions.entry.list({ sessionID: this.id });
if (entries.some((entry) => entry.key === "paseo")) {
await this.client.session.instructions.entry.remove({ sessionID: this.id, key: "paseo" });
}
}
}
private async startStream() {
let ready!: () => void;

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