Compare commits

...
Author SHA1 Message Date
Mohamed Boudra bd4e817951 fix(plugins): start a Windows bare name directly when the caller passes shell: false
The PATH lookup that finds a .cmd shim ran statSync for every bare name, including git with
shell: false, so a daemon Git refresh did synchronous IO on Windows. An explicit shell: false
now starts the name directly, as on main, and Windows searches PATH itself. The daemon's
git --version probe passes shell: false like its other git commands.
2026-11-25 18:39:14 +01:00
Mohamed Boudra 9f999bd570 test(plugins): classify the internal windows-command entry as server-only 2026-11-25 18:16:38 +01:00
Mohamed Boudra bf10ea8732 fix(plugins): keep a caller's windowsVerbatimArguments on a direct Windows launch
spawnProcess set the flag from its own invocation after the caller's options, so a plugin
that passed windowsVerbatimArguments: true with its own cmd.exe line got Node's quoting.
2026-11-25 18:14:39 +01:00
Mohamed Boudra a8528ad3d2 fix(plugins): start the cmd.exe a Windows caller names
A plugin that passed shell: "D:\Tools\cmd.exe" got the child's ComSpec instead. Only
shell: true and the builtin and script launches now use ComSpec.
2026-11-25 18:09:01 +01:00
Mohamed Boudra 2c661fb076 test(plugins): run the launch wrap reload case in server integration CI
agent-tools.e2e.test.ts is in no CI script, so the case that a plugin reload changing only the
wrap reopens the idle session never ran. The integration run now selects it by name.
2026-11-25 18:04:16 +01:00
Mohamed Boudra 531f6e549d refactor(plugins): share one qntm cmd.exe dialect between process launches and terminals
The SDK process functions and the daemon's terminals each had their own cmd.exe escaper, and
the SDK's quote-region tracker let a set variable such as %PATH% expand inside a quoted
argument to a .cmd or .bat launcher.

Both now build the line with windowsCommandLine and start cmd.exe /d /s /c "<line>" with
verbatim arguments. An argument without a cmd.exe metacharacter stays as given, so builtins
and %1 readers get it unchanged. Any other argument is quoted and caret-escaped the qntm way
(cross-spawn's escape.js), so cmd.exe never sees a quoted region and never expands %NAME%.
A batch script that reads an argument with a quote again gets it escaped twice.

A bare name is found on PATH with PATHEXT without changing the daemon's working directory:
a program starts directly, a .cmd or .bat shim goes through cmd.exe, and an unknown name
goes through cmd.exe as a builtin. A shell other than cmd.exe gets the arguments as given.
Terminals keep turning a prompt's line breaks into spaces; the SDK still refuses them.
2026-11-25 18:01:57 +01:00
Mohamed Boudra e32564f2bc fix(plugins): reopen a session when a plugin reload changes its launch wrap
A plugin refresh compared env, instructions, MCP servers and tools, not
the launch wrap. A reloaded sandbox plugin that changed its wrap left
live sessions running the old one, and a later plugin reused its
recorded output with the old wrap. The wrap now chains between plugins
like env, so it counts for reuse and for a stale launch.

The agent manager wrap tests now fake the plugin sessions runtime: a
refused wrap discards the open, and the running session keeps its tools.
2026-11-25 17:47:16 +01:00
Mohamed Boudra 0258d6752e fix(plugins): quote =, comma and semicolon for a Windows .cmd launch
A batch script splits its arguments at =, comma and semicolon outside
quotes, so a launcher that reads %~1 got --profile=restricted as two
arguments. Quote them for a script; %* forwarders still pass the
argument through unchanged.
2026-11-25 17:37:33 +01:00
Mohamed Boudra de5f139d33 test(plugins): exit the %~1 reader script with 0 on Windows
`set /p` without input exits with errorlevel 1, so execCommand reported the
reader script as failed even though it printed its arguments.
2026-11-25 17:37:33 +01:00
Mohamed Boudra 372c1ba949 fix(plugins): keep plain Windows arguments as given for cmd.exe builtins and %1 readers
Quoting and escaping every argument broke three existing Windows contracts
in server tests. `echo hello` printed `"hello"`, a build script that writes
`%1` wrote the quotes, and a port script that reads `%~1` got `^"` escapes
it cannot remove. A plain argument now stays as given. An argument with
whitespace, a quote, or no text sits inside real cmd.exe quotes, which
`%~1` and the program both remove. A .cmd or .bat target also quotes an
argument with cmd.exe syntax, because the script reads it again for `%*`.
Only text that literal quotes leave outside a quoted region is escaped.
2026-11-25 17:37:33 +01:00
Mohamed Boudra 4dc1730a62 fix(plugins): quote for cmd.exe only when cmd.exe parses a Windows launch
A Windows caller that named its own shell, such as Git Bash, got cmd.exe
escapes in its arguments and a line-break refusal that only cmd.exe needs.
Bash then printed `^"hello^"` for `hello`. A shell the caller names now gets
the command and arguments as given, as it already does on Linux and macOS.
2026-11-25 17:37:33 +01:00
Mohamed Boudra 2581f2af45 fix(plugins): refuse a line break in a Windows cmd.exe launch argument
cmd.exe ends a command at a line break whatever the quoting, so a
multiline argument to a .cmd launch wrap or a bare command name was cut
short, and the text after the break ran as a second command. The SDK now
refuses such an argument before cmd.exe starts. A streamed worktree setup
or teardown command that cannot start now fails as a command, with its
error in stderr, instead of rejecting outside the setup error.
2026-11-25 17:37:33 +01:00
Mohamed Boudra 6973c48d7e test(plugins): check ACP interrupts and skill examples the same way on Windows
Windows ends an ACP child at once, so the overlapping-interrupt test no
longer times the POSIX SIGTERM grace period. It already checks that the
child is gone when both interrupts finish. The skill examples test reads
SKILL.md with the CRLF line endings of a Windows checkout.
2026-11-25 17:37:32 +01:00
Mohamed Boudra 9dd0cbc146 fix(plugins): deliver arguments to Windows commands and .cmd launch wraps unchanged
On real Windows, cmd.exe changed arguments that the SDK passed through it.
`a & b` arrived as `a ^& b`, `"quoted"` lost its quotes, and `%PATH%`
expanded. A .cmd launcher in `C:\Program Files (x86)` could not start,
because its path gained `^(x86^)`. Each argument is now quoted for the
program and every cmd.exe metacharacter is escaped, twice for a .cmd or
.bat file that forwards its arguments with `%*`. The executable path keeps
plain quotes.
2026-11-25 17:37:32 +01:00
Mohamed Boudra f088fa5049 test(plugins): run the plugin SDK and .cmd launch wraps on real Windows
The plugin SDK tests ran only on Ubuntu, so cmd.exe never saw a launch wrap.
A Windows job now runs them, with real .cmd launcher tests for arguments
that cmd.exe reads as syntax. The terminal and worktree wrap test uses a .cmd
launcher in a directory with spaces and parentheses on Windows. The plugin
configuration e2e suite joins the integration run, which it was missing from.
2026-11-25 17:37:32 +01:00
Mohamed Boudra 5dcd1e1e57 fix(opencode): resume a wrapped legacy child session on a server behind its wrap
A legacy OpenCode child session resumed on its parent's registered server, even
when the open selected a wrap, so it ran with the parent's isolation. A wrapped
resume now starts its own server behind the wrap, as v2 does.
2026-11-25 17:37:32 +01:00
Mohamed Boudra 7ba54499d9 fix(opencode): start a wrapped v2 server with the open hook's environment
A wrapped OpenCode v2 session got a dedicated server behind its wrap, but the
server and its launcher started without the hook's env, so a launcher that
reads its profile from that env failed. The runtime now takes a dedicated
launch with both the wrap and the env, as the legacy server manager does.
Session shells still receive the env through the session environment.
2026-11-25 17:37:32 +01:00
Mohamed Boudra cbd5b7a73b fix(opencode): read an imported session behind the import's launch wrap
Importing an OpenCode session read it on the shared server before resuming it
behind the wrap, so a wrapped import with no shared server running started one
outside the wrap. The v2 runtime now looks up and resumes the session on one
wrapped connection, and the legacy runtime reads it on a dedicated server
behind the wrap.
2026-11-25 17:37:32 +01:00
Mohamed Boudra 8e88ce3a56 fix(terminals): send the script ownership change that lands as a terminal snapshot finishes
A terminal subscription coalesces refreshes with a pending flag, but it cleared
the in-flight refresh in a later microtask. A script runtime registered in that
gap set the flag after the last check, so clients kept isScript: false for a
running script. The refresh now clears itself in the same step as its last
check. The extra await in the plugin terminal.create.before wrapper moved
script registration into that gap, which made the Windows integration test fail.
2026-11-25 17:37:32 +01:00
Mohamed Boudra fb59e58ef1 feat(plugins): every built-in provider starts its harness behind a launch wrap
Claude, ACP and custom ACP providers, Pi, OMP, and OpenCode now honor an
agent.open.before wrap alongside Codex and plugin providers, so
supportsLaunchWrap is true for every provider that starts a local harness.

- spawnProcess({ wrap }) in the plugin SDK and applyLaunchWrap in the server
  own the wrapped argv; pty terminals, MCP stdio servers, and worktree
  commands share applyLaunchWrap.
- The wrap also covers stdio MCP servers Paseo hosts for the session and
  terminals an ACP agent asks Paseo to run.
- A wrapped OpenCode session starts a dedicated server behind its wrap (legacy
  and v2 runtimes); an explicitly configured external server fails the open.
- Docs cover provider coverage, what the wrap covers, and the temp directory
  a launcher must keep visible.
- The workspace script ownership e2e test asserts on the started terminal id.
2026-11-25 17:37:32 +01:00
Mohamed Boudra 825fa04467 test(terminals): give script ownership the same 10s wait as the rest of the test
The first wait used the 1s default. On a slow Windows runner the observed
terminal list reports script ownership later than that. The assertion now
prints the observed terminals when it fails.
2026-11-25 17:37:32 +01:00
Mohamed Boudra 8338e77f46 fix(plugins): keep empty launcher arguments on Windows and stop lifecycle hooks at the deadline
A `.cmd` or `.bat` launch dropped an empty argument because cmd.exe saw only
whitespace; it is now quoted as `""` and keeps its position.

Teardown waited for a pending command.run.before hook past its deadline and
then started the command. Hook preparation now races the teardown deadline
and setup's cancel signal, and an aborted preparation never starts the
command.
2026-11-25 17:37:32 +01:00
Mohamed Boudra e5d81304f7 docs(plugins): say where a wrapped harness starts and how to pass the agent's directory 2026-11-25 17:37:32 +01:00
6b0fbfc640 refactor(plugins): one launch wrap for agents, terminals, and worktree commands
terminal.create.before and command.run.before now change only env and a
launch wrap, the same PluginLaunchWrap agent.open.before returns. Paseo
starts the terminal as [...wrap, command, ...args] (the default shell
when there is no command) and a setup or teardown command's shell as
[...wrap, shell, ...shellArgs]. The first hook's wrap wins; a different
one fails the operation. command, args, and the command text are
read-only, so a plugin cannot rewrite what runs.

The terminal wrap is applied in the daemon before the worker, so the
terminal worker protocol is unchanged. resolveDefaultTerminalShell moves
to its own module so the daemon does not load node-pty.

Co-authored-by: CL Kao <clkao@datarecce.io>
Co-authored-by: Josh Bendavid <Josh.Bendavid@cern.ch>
2026-11-25 17:37:32 +01:00
Josh Bendavid b4e4803df2 feat(plugins): hooks for terminal creation and worktree commands, with the workspace id
Applied from getpaseo/paseo#8691 (head 416d70614) onto main.
2026-11-25 17:37:32 +01:00
CL KaoandClaude Opus 5.5 3153f6f94a test(plugins): pin launch-wrap tests to the registration and to spawn attempts
- The Antigravity wrapped-launch test builds its launch from the provider
  registration's own command, as the daemon does, and asserts the exact
  argv, so dropping --disable-telemetry from the registration fails it.
- The ACP missing-launcher test counts every spawn attempt through Node's
  child_process diagnostics channel, so a second attempt with the missing
  launcher or a bare retry fails it.
- Drop the daemon-access sentence from the launch wrap limits.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 17:37:32 +01:00
CL KaoandClaude Opus 5.5 ecf8c812cd fix(plugins): keep the wrap prepend internal and test Windows launchers through a seam
- Inline the wrap prepend in the ACP shim and Codex instead of exporting
  applyLaunchWrap from @getpaseo/plugin/server; the author surface and
  boundaries.test.ts stay as upstream.
- spawnProcess and execCommand now share resolveSpawnInvocation, which
  takes the platform. A unit test proves a Windows script wrapper runs
  through cmd.exe with each argument quoted whole, without mocking
  child_process or patching process.platform.
- A wrapped Codex refresh whose provider command is a Windows script
  spawns through the production spawnProcess, with the provider command
  passed to the wrapper as an argument.
- The wrap fixtures in the ACP and Antigravity tests run as Node through
  process.execPath, so they also run on Windows.
- The provider protocol rejects an empty wrap executable.
- The provider registry and plugin clients set supportsLaunchWrap where
  they build the client.
- Docs name the launch wrap in the hook summaries and point provider
  authors at ProviderRegistration.launchWrap.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 17:37:32 +01:00
CL KaoandClaude Opus 5.5 ab4bd6d59d fix(plugins): start Windows script launch wraps through cmd.exe
applyLaunchWrap rejected a Windows .cmd or .bat file on either side of the
wrap, and it did so at spawn time, after a refresh had already closed the
running session. Both wrapped paths spawn through spawnProcess, which runs a
command-script launcher through cmd.exe with each argument quoted, and the
provider command is only an argument to the wrapper. Drop the rejection from
applyLaunchWrap and from the manager's admission check.

Document the wrap in the public hook reference (with
its zh-CN translation), state the Windows launcher rule where the wrap
contract lives, and name wrap in the open-hook diagnostic.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 17:37:22 +01:00
CL KaoandClaude Opus 5.5 2547edefcc feat(plugins): let an open hook wrap the provider's launch command
An agent.open.before result can carry `wrap: [executable, ...args]`. A
supporting provider starts that session's harness as
`[...wrap, command, ...args]`, one direct argv exec with the final hook env.
This lets one sandbox plugin confine every provider that supports wrapping,
instead of one wrapper provider per real provider.

Support is a static provider property, published as optional `launchWrap` on
the provider snapshot entry so an agent.create.before hook can read it with
paseo.providers.snapshot(). Codex and providers that extend it declare it in
the provider contract; plugin providers declare
ProviderRegistration.launchWrap, which runAcpProvider sets for a command.
The declaration travels in the registration metadata, so a provider reports
it before its first connection.

The open fails closed:
- buildLaunchContext rejects a wrapped open with LaunchWrapUnsupportedError
  (code launch_wrap_unsupported) before anything starts when the provider
  does not declare support, when a plugin connection lacks
  session.launch_wrap, or for a Windows command-script wrapper;
- a later hook may omit or repeat the wrap, a different one fails the open;
- the wrap executable must be absolute;
- a missing launcher fails the spawn and is never retried bare;
- a host without this change rejects the unknown `wrap` key.

The wrap is launch-only: history opens keep it, plugin session reopens
reuse it, and it is never stored on the agent.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 17:37:12 +01:00
5c82a2e999 Keep a reloaded plugin's agent tools working for a busy agent (#10106)
* fix(server): keep a restarted plugin's agent tools on live sessions

A plugin restart (reload, update) gives the plugin a new instance id.
Tools attached to an open session are stamped with the old one, so
getPluginTools filters them out and the agent MCP neither lists nor
serves them ("Tool ... not found"). They came back only when the session
reopened, which happens before a prompt to an idle agent; messages to a
busy agent are steered or replace the run on the stale session, so a
busy agent could go without its plugin tools for as long as it stayed
busy.

The agent MCP now reattaches them before it builds a request's catalog:
AgentManager remembers the request a session opened with, and for
plugins whose instance changed it replays agent.open.before to those
plugins only and keeps only the tools they return. Env and MCP server
changes still wait for the reopen, which is unchanged.

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

* fix(server): keep stopped plugins eligible and guard tool replays

- A plugin that is stopped or mid-restart during an MCP request keeps its old
  attachment, so a later request retries it instead of losing its tools.
- A reopen waits for an in-flight replay, so the replay cannot overwrite the
  reopen's tool definitions inside the plugin process.
- Refreshed tools that collide with a Paseo tool or another plugin's tool are
  dropped for that plugin instead of breaking the agent's whole catalog.

* fix(server): retry a plugin whose tool replay failed

A failed replay is left out of the result like a stopped plugin, so the
agent's next MCP request retries it instead of dropping its tools until the
session reopens. The reopen race test now waits for the replay to reach its
gate before it starts the reopen.

* fix(server): replay a restarted plugin's open once per instance, as refresh

A replay whose hook threw or timed out ran again on every agent MCP
request, so each Paseo tool call waited on the broken plugin. The
runtime now remembers the instance that failed and replays it only
after the next restart.

The replay now arrives with reason "refresh", like the idle reopen the
same restart causes, so plugins no longer see "create" again.

An open waits until no replay is pending before it detaches, and a
replay that outlives its session detaches only the plugins it replayed.

Co-authored-by: Tom Gringauz <17593920+tomgrin10@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server): keep no replay failure record for a closed agent

The replay takes the agent's record when it starts and writes a failure
into that record. Closing the agent drops it, so a replay that fails
afterwards no longer leaves an entry behind.

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

* docs(plugins): say native-tool agents keep launch-time tools until the reopen

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

* fix(server): reserve provider-disabled Paseo tool names in a tool replay

A replayed plugin tool named after a Paseo tool that the agent's provider
disables was accepted, and every later agent MCP request then failed on
the plugin collision check. The replay now builds its reserved names with
an all-enabled policy, the same names that check reserves.

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

* fix(server): reopen only sessions a plugin change affects

A plugin reload bumped one global session-open generation, so every live
agent reopened at its next idle prompt. The reopen closes the provider
session, cancels its subagents and clears background work, even for agents
the plugin never touched.

SessionAttachments now owns what each agent.open.before plugin contributed
to each live session. A refresh reruns only the plugins whose instance
changed, swaps their tools in place, and marks the session stale only when
its launch would differ. This replaces the AgentManager maps, the runtime's
failed-replay record, and the global generation. Native-tool providers
resolve plugin tools by name at call time, so their calls reach the new
instance.

* fix(server): compare plugin refreshes with the running launch

A plugin refresh decided staleness against the last refresh with a sticky
flag, so reverting a tool edit still reopened the session. A failed reopen
also deleted the session's plugin record while the old provider session kept
running, which left it without any plugin tools.

SessionAttachments now keeps the contributions the session launched with as
the baseline and works out staleness against it on every refresh. A failed
rerun or collision is kept on that plugin's contribution. A failed open keeps
the running session's record and marks its plugins for reattach on the next
refresh.

A launch-time native catalog entry now resolves the tool by plugin id and
name, so a different plugin that took the name is never called.

* fix(server): make a plugin open the baseline only once its launch takes over

A reopen whose plugin hooks succeed can still fail launch validation: a
plugin tool that takes a Paseo tool name, or an MCP server on a provider
without MCP support. The open had already replaced the session's record, so
the session lost its plugin tools, or kept a record for a launch that never
ran, and the next idle prompt did not retry.

An interactive open now stays pending until registerSession reports that the
provider launch took over. A launch that fails before then discards the
pending open, and the still-running session keeps its record. Its plugins
attach their tools again on the next refresh, and each idle prompt retries
the reopen.

* fix(server): discard a reload's plugin open on every pre-takeover rejection

resolveProviderLaunchConfig rejects a plugin MCP server that takes a saved
server name after the open is staged, and nothing discarded the staged open.
The reload now resolves and validates its launch config in one scope that
discards the staged open on any rejection, so the running session keeps its
plugin tools and the next idle prompt retries the reopen.

* fix(server): keep a tool name with its owner when a refresh replays every plugin

After a rejected reopen, every plugin replays on the next refresh, and the
collision check gave a contested name to whichever plugin sorted first. A name
now stays with the plugin that has it in the session's record, as long as that
plugin still returns the tool.

* fix(server): rerun a refreshed plugin callback with the agent's current metadata

A plugin reload used to reopen every session, so its callback saw the agent's
current title, workspace, labels, and metadata. A refresh now replays the
recorded open request instead, so a hook that filters on metadata set after
launch kept returning nothing. The refresh now overlays those agent fields,
which plugins cannot change, on the recorded request.

* fix(server): replay the plugin chain in order, hold refreshes over a plugin restart, and roll back every failed launch's plugin open

- A cached plugin contribution is reused only when its instance and the env and instructions it received still match; otherwise the plugin reruns in open order and the composed launch is compared with the running one.
- A plugin reload or source update publishes one settled change: a session refresh waits for the restart instead of reading the stop as removal.
- Create, resume, import, and reopen share one launch boundary: the pending plugin open commits when registerSession admits the agent and is discarded when the launch throws before that.

* fix(server): decide a plugin reopen from the same launch the open builds

The open and the refresh now compose the launch with one function. The staleness check compares which plugin provides each tool, so a native-tool catalog bound to a removed plugin reopens, and a proposed launch with an MCP server name collision counts as changed, so the reopen reports it.

* fix(server): reserve only Paseo's own tool names when a plugin refresh checks collisions

The agent's catalog also lists its plugin tools, so a later plugin rerun by an earlier plugin's edit saw its own tool as taken and lost it. The session owner settles names between plugins from its record. The hooks reference now says an MCP server name collision fails the reopen without hiding tools.

* fix(plugins): let a refreshed plugin's running tool calls finish

The plugin process detached the session's tools at the start of every agent.open.before, which aborted calls already running. Attaching replaces the definitions for later calls; the daemon still detaches before an open that replaces the provider session.

---------

Co-authored-by: Tom Gringauz <17593920+tomgrin10@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: paseo-bot[bot] <paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Mohamed Boudra <boudra.moha@gmail.com>
2026-11-25 16:51:40 +01:00
Mohamed Boudra 60943dde1c Return focus to the prompt after choosing a New Workspace field (#10632)
* fix(app): return focus to the composer after choosing a New Workspace field

A closing picker restored focus to whatever had focus when it opened. Opening
the project picker by clicking its trigger left focus on the trigger after a
keyboard pick, and every later Cmd/Ctrl+N pick captured the trigger again, so
the user had to click back into the prompt.

The New Workspace form now passes the composer as the restore target for its
pickers. The overlay accepts any handle with focus() as a restore target, so
the composer's own retrying focus can be used instead of a raw DOM element.

* fix(app): keep focus on the field when the terminal profile takes no prompt

A terminal profile without a prompt shows a read-only command preview, so there
is nothing to type into. Its pickers now fall back to returning focus to the
field that opened them instead of losing focus to the preview.
2026-11-25 22:14:42 +07:00
Mohamed Boudra e52bb6e3c4 Select multiple sidebar workspaces to archive together (#10798)
* feat(app): select multiple sidebar workspaces to archive together

Let users enter workspace select mode from Shift+click/tap or the row menu, toggle additional rows with plain clicks without holding Shift, extend ranges with Shift+click, and archive all selected workspaces in one batch with a single worktree warning and undo toast.

Tracks live hardware Shift state in the keyboard pipeline (clearing on blur and AppState backgrounding) so Shift+tap and Shift+click also work on native tablets with hardware keyboards where Pressable responder events omit shiftKey. Adds an action layout variant on ToastCard so pill controls inside action toasts share concentric padding and radius.

* fix(app): preserve batch undo and selection ownership during bulk archive

Keep workspace.archive bound for the full lifetime of sidebar select mode so pressing it at 0 selected or during a worktree check does not fall through to archive the open workspace.

On partial archive failures, update the open UndoWindow toast in place with error styling and the failure message instead of calling toast.error, so Undo and Cmd/Ctrl+Z remain available for succeeded workspaces and their layout state is not purged early.

Guard isArchiving cleanup with a per-attempt token so an earlier batch cannot unlock a newer batch's worktree check, and read the active workspace lazily at redirect time rather than capturing it at submission.

* fix(app): stack sidebar selection bar below toasts and protect newer undo

Keep the sidebar selection bar visible alongside active transient toasts (such as Undo or error toasts) by rendering both slots in ToastViewport's sidebar stack instead of hiding the persistent bar while a transient toast is open.

Route late archive errors from a superseded batch to the app-level toast when a newer batch holds an open Undo window, so an older failure does not replace the active Undo toast or purge the newer batch's layout state.

* fix(app): toggle focused sidebar workspace checkboxes with Space on web

React Native Web's Pressable activates Space only for role='button', not role='checkbox'. Handle Space on focused checkbox rows in SidebarWorkspaceContextMenu so keyboard users can toggle rows in either sidebar grouping.

* fix(app): ignore repeated Space keydown on focused workspace checkboxes

* fix(app): keep Escape owned by select mode during worktree checks
2026-11-25 22:11:10 +07:00
158 changed files with 8395 additions and 899 deletions
+23
View File
@@ -131,6 +131,29 @@ jobs:
if: ${{ !cancelled() && steps.install.outcome == 'success' && (needs.changes.outputs.full != 'false' || needs.changes.outputs.sdk != 'false') }}
run: npm run typecheck:examples --workspace=@getpaseo/client
# Plugin process launches and launch wraps quote for cmd.exe, which only real Windows checks.
sdk-tests-windows:
name: sdk-tests (windows-latest)
needs: changes
if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.sdk != 'false') }}
runs-on: windows-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: "22"
cache: "npm"
- name: Install dependencies
run: node scripts/npm-retry.mjs ci
- name: Build plugin SDK
run: npm run build:relay && npm run build:client && npm run build:plugin
- name: Run plugin SDK tests
run: npm run test --workspace=@getpaseo/plugin
# The locked Playwright installers do not support ubuntu-latest's Ubuntu 26.04.
typecheck:
name: typecheck
+64 -2
View File
@@ -462,8 +462,55 @@ Server entries register async handlers with `server.addHook(name, handler)`, ret
function. Names follow `subject.operation.position`, ending in `before` or `after`. Waiting is a per-hook
registry property, independent of position. The [hooks reference](../public-docs/plugins/hooks.md)
owns payloads, ordering, failure behavior, and examples. `agent.create.before` edits saved
configuration; `agent.open.before` contributes launch-only `env`, `tools`, and `mcpServers` on
every open. Executable tool definitions stay in the plugin process; only metadata crosses the boundary.
configuration; `agent.open.before` contributes launch-only `env`, `tools`, `mcpServers`, and a
[launch wrap](#launch-wrap) on every open. Executable tool definitions stay in the plugin process; only metadata crosses the boundary.
`packages/server/src/server/plugins/session-attachments.ts` records what each plugin contributed to
each live session. A plugin start, stop, or reload reruns only that plugin's callback per session,
swaps its tools in place, and reopens a session only when its launch would differ. A reopen closes
the provider process, so a reload must not reopen agents the plugin does not change.
### Launch wrap
An `agent.open.before` result can carry `wrap: [executable, ...args]`. The provider then starts that
session's harness as `[...wrap, command, ...args]` with the final hook env. It starts with no shell,
except Windows script launchers, which go through cmd.exe like any provider launcher
(`spawnProcess` quotes each argument). An argument with spaces stays one element. `executable` must
be an absolute path.
The wrap is never saved on the agent; every open asks the hooks again, and a plugin session reopen
reuses the wrap it opened with.
- **Support is a provider property.** The provider snapshot entry carries `launchWrap: true` when the
provider can apply a wrap. Read it in `agent.create.before` with `paseo.providers.snapshot()`; an
absent field means unsupported, which is also what a host without this feature reports. Core
providers declare it in the provider contract table in `provider-registry.ts`; every core provider
that starts a local harness declares it, and custom ACP providers and providers that extend a core
one inherit it. A plugin provider declares `ProviderRegistration.launchWrap`;
`runAcpProvider({ command })` sets it, a connector declares it itself (Muse Code does). The declaration travels with the
registration metadata, so it is in the snapshot before the provider first connects.
- **One wrap per open.** A later hook, in the same plugin or a later one, may omit the wrap or return
the same value. A different value fails the open.
- **Fail closed.** `buildLaunchContext` admits a wrapped open before any session harness starts. It
throws `LaunchWrapUnsupportedError` (`code: "launch_wrap_unsupported"`) when the provider does not
declare support, or when a plugin provider's live connection lacks `session.launch_wrap`. A host
that predates `wrap` rejects the key: the hook result schema is strict. A missing launcher fails the
spawn; nothing retries the bare command.
Once an open selects a wrap, a supported provider runs that session's harness through it or fails
before starting the harness. Every provider starts through `spawnProcess({ wrap })`, which owns the
argv and Windows launcher handling; `applyLaunchWrap` covers the launches that do not go through it
(pty terminals, MCP stdio transports, worktree commands). The wrap also covers what Paseo starts for
the session: stdio MCP servers Paseo hosts for the agent (OMP, OpenCode v2), Pi's MCP probe, and ACP
client terminals. OpenCode shares one server between sessions, so a wrapped session gets a dedicated
server instead; an explicitly configured external OpenCode server cannot be wrapped and the open
fails. The guarantee does not cover:
1. Paseo's host terminal tools (`create_terminal`, `send_terminal_keys`) run outside the wrap.
2. Work before the open hook runs unwrapped: draft command and control discovery, and the catalog
lookup during create when no model is set.
3. Host-side operations run unwrapped: availability and capability probes (the ACP connection's
initialize probe included), catalog and session listing, version and update commands, usage
queries, and Codex native archive and unarchive.
4. Losing the plugin that chose the wrap is not covered: a later open without it runs unwrapped.
Worktree placement is resolved before Git source planning, so a hook can change the branch and base
without undoing fetched refs. Restores use the recorded destination and bypass creation hooks.
@@ -483,6 +530,17 @@ change requests; `remove` and `restore` fall back to built-in Git when the plugi
[worktree managers reference](../public-docs/plugins/reference.md#worktree-managers) and
`plugin-examples/worktrunk`.
`terminal.create.before` runs in `withTerminalCreateHook`, which wraps the daemon's one terminal manager, so every creation path is covered and adopted terminals are not; callers pass an `origin` to name the source. `command.run.before` runs inside the setup and teardown runners through `commandRunHook`. Setup and archive dependencies take `lifecycle` as a required field so a new caller cannot skip the hook by omission; pass `null` only where no plugins run.
Both hooks change only `env` and a [launch wrap](#launch-wrap); `keepSelectedWrap` in the lifecycle
module applies the one-wrap rule to all three wrap hooks. The terminal wrap becomes the terminal's
`command` and `args` in `withTerminalCreateHook`, so the terminal worker protocol does not change and
no previous-version adapter is needed. A default-shell terminal resolves the shell there through
`default-terminal-shell.ts`, which stays apart from `terminal.ts` so the daemon does not load node-pty.
The wrapped shell starts without Paseo's shell integration, which is why a wrapped script does not
report command completion. A setup or teardown wrap goes in front of the
`buildStringCommandShellInvocation` argv.
Emit from the operation owner, not a client subscription. Provider history replay must not trigger
live hooks. Notifications must not be awaited inside agent mutations: a handler can send a prompt
or answer a permission through its own daemon session. Awaiting it there deadlocks that command.
@@ -582,6 +640,10 @@ persistence. Re-read credentials and provider-owned configuration on `session.op
daemon launch from `connect` and the per-session env and MCP servers from `session.open`. There is
no provider reload input.
Declare `ProviderRegistration.launchWrap: true` when every session spawns its own harness and can
run it as `[...config.wrap, command, ...args]`; offer `session.launch_wrap` on the connection. See
[Launch wrap](#launch-wrap). `runAcpProvider({ command })` does both.
For an ACP command, register `runAcpProvider({ id, label, command })` from
`@getpaseo/plugin/server/acp`. The shim builds the standard row for each ACP tool `kind`
(`acp-internal/tool-call-detail.ts`). Its transformer hooks cover narrow vendor differences; do not translate the
@@ -1,6 +1,7 @@
import { expect, test } from "../support/fixtures";
import { gotoAppShell } from "../support/helpers/app";
import {
chooseProjectWithKeyboard,
connectNewWorkspaceDaemonClient,
expectNewWorkspaceControlsEnabled,
expectNewWorkspaceProjectSelected,
@@ -176,6 +177,33 @@ test.describe("New workspace entry points", () => {
}
});
test("choosing a project returns focus to the composer, even when the picker was opened by clicking it", async ({
page,
}) => {
const projectA: SeededWorkspace = await seedWorkspace({ repoPrefix: "entry-focus-a-" });
const projectB: SeededWorkspace = await seedWorkspace({ repoPrefix: "entry-focus-b-" });
try {
await gotoAppShell(page);
await waitForSidebarHydration(page);
await openGlobalNewWorkspaceComposer(page);
const composer = page.getByRole("textbox", { name: "Message agent..." });
await page.getByTestId("new-workspace-project-picker-trigger").click();
await chooseProjectWithKeyboard(page, projectB.projectDisplayName);
await expectNewWorkspaceProjectSelected(page, projectB.projectDisplayName);
await expect(composer).toBeFocused();
await page.keyboard.press("Control+N");
await chooseProjectWithKeyboard(page, projectA.projectDisplayName);
await expectNewWorkspaceProjectSelected(page, projectA.projectDisplayName);
await expect(composer).toBeFocused();
} finally {
await projectA.cleanup();
await projectB.cleanup();
}
});
test("keeps the in-progress form when the remembered workspace is archived elsewhere", async ({
page,
}) => {
@@ -2,6 +2,7 @@ import { expect, test, type Page } from "../support/fixtures";
import { gotoAppShell } from "../support/helpers/app";
import { waitForSidebarHydration } from "../support/helpers/workspace-ui";
import {
chooseProjectWithKeyboard,
expectNewWorkspaceDraft,
fillNewWorkspaceDraft,
openNewWorkspaceComposer,
@@ -109,6 +110,27 @@ test.describe("New workspace: launching a terminal", () => {
});
});
test("with a profile that takes no prompt, choosing a project keeps focus on the Project field", async ({
page,
}) => {
await gotoAppShell(page);
await waitForSidebarHydration(page);
await openNewWorkspaceComposer(page, {
projectKey: workspace.projectKey,
projectDisplayName: workspace.projectDisplayName,
});
await selectLaunchOption(page, BARE_PROFILE.id);
await expect(terminalPromptInput(page)).toHaveCount(0);
// The read-only command preview has nothing to type into, so the picker
// hands focus back to the field that opened it.
const projectTrigger = page.getByTestId("new-workspace-project-picker-trigger");
await projectTrigger.focus();
await page.keyboard.press("Enter");
await chooseProjectWithKeyboard(page, workspace.projectDisplayName);
await expect(projectTrigger).toBeFocused();
});
test("switching terminal profiles restores the prompt and its fullscreen affordance", async ({
page,
}) => {
@@ -243,6 +243,14 @@ export async function openNewWorkspaceProjectPickerWithShortcut(
await expect(searchInput).toBeFocused();
}
export async function chooseProjectWithKeyboard(page: Page, projectName: string): Promise<void> {
const searchInput = page.getByPlaceholder("Search projects");
await expect(searchInput).toBeFocused({ timeout: 30_000 });
await page.keyboard.type(projectName);
await page.keyboard.press("Enter");
await expect(searchInput).toBeHidden({ timeout: 10_000 });
}
export async function expectNewWorkspaceProjectSelected(
page: Page,
projectDisplayName: string,
@@ -232,6 +232,7 @@ export interface HostPickerProps {
open: boolean;
onOpenChange: (open: boolean) => void;
anchorRef: React.RefObject<View | null>;
restoreFocusRef?: ComboboxProps["restoreFocusRef"];
includeAllHost?: boolean;
includeAddHost?: boolean;
onAddHost?: () => void;
@@ -254,6 +255,7 @@ export function HostPicker({
open,
onOpenChange,
anchorRef,
restoreFocusRef,
includeAllHost,
includeAddHost,
onAddHost,
@@ -404,6 +406,7 @@ export function HostPicker({
open={open}
onOpenChange={onOpenChange}
anchorRef={anchorRef}
restoreFocusRef={restoreFocusRef}
desktopPlacement={desktopPlacement}
desktopMinWidth={desktopMinWidth}
/>
@@ -55,6 +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 { SidebarSelectionHost } from "@/sidebar-selection";
import { SidebarNavRows, useVisibleSidebarNavItems } from "@/components/sidebar/sidebar-nav-rows";
import { SidebarFooterIconHighlight } from "@/components/sidebar/sidebar-footer-icon-highlight";
import { SidebarHelpMenu } from "@/components/sidebar/sidebar-help-menu";
@@ -667,6 +668,7 @@ function MobileSidebar({
listHeaderComponent={workspacesSectionHeaderElement}
/>
)}
<SidebarSelectionHost active={active} workspaceEntriesByKey={workspaceEntriesByKey} />
</SidebarToastRegion>
</SidebarViewSlot>
@@ -922,6 +924,7 @@ function DesktopSidebar({
listHeaderComponent={workspacesSectionHeaderElement}
/>
)}
<SidebarSelectionHost active={active} workspaceEntriesByKey={workspaceEntriesByKey} />
</SidebarToastRegion>
</SidebarViewSlot>
@@ -101,7 +101,17 @@ import {
import { useLongPressDragInteraction } from "@/components/sidebar/use-long-press-drag-interaction";
import { SidebarSectionHeader } from "@/components/sidebar/sidebar-section-header";
import { SidebarGroupToggleRow } from "@/components/sidebar/sidebar-group-toggle-row";
import { createWorkspaceVisibilityPolicy } from "@/components/sidebar/sidebar-group-visibility";
import {
createWorkspaceVisibilityPolicy,
selectSidebarGroupVisibility,
} from "@/components/sidebar/sidebar-group-visibility";
import {
isShiftPressEvent,
registerSidebarVisibleWorkspaceKeysReader,
useIsSidebarSelectionMode,
useIsWorkspaceBulkSelected,
useSidebarSelectionStore,
} from "@/sidebar-selection";
import { useLimitedSidebarGroup } from "@/components/sidebar/use-limited-sidebar-group";
import {
SidebarWorkspaceRowFrame,
@@ -284,6 +294,7 @@ interface WorkspaceRowInnerProps {
archiveLabel?: string;
archiveStatus?: "idle" | "pending" | "success";
archivePendingLabel?: string;
onSelectWorkspace?: () => void;
onArchive?: () => void;
onCopyBranchName?: () => void;
onCopyPath?: () => void;
@@ -607,12 +618,14 @@ function WorkspaceRowRightGroup({
isHovered,
isTouchPlatform,
isCreating,
isSelectionMode,
showShortcutBadge,
shortcutNumber,
archiveLabel,
archiveStatus,
archivePendingLabel,
archiveShortcutKeys,
onSelectWorkspace,
onArchive,
onMarkAsRead,
onMarkAsUnread,
@@ -627,12 +640,14 @@ function WorkspaceRowRightGroup({
isHovered: boolean;
isTouchPlatform: boolean;
isCreating: boolean;
isSelectionMode: boolean;
showShortcutBadge: boolean;
shortcutNumber: number | null;
archiveLabel?: string;
archiveStatus?: "idle" | "pending" | "success";
archivePendingLabel?: string;
archiveShortcutKeys?: ShortcutKey[][] | null;
onSelectWorkspace?: () => void;
onArchive?: () => void;
onMarkAsRead?: () => void;
onMarkAsUnread?: () => void;
@@ -660,6 +675,7 @@ function WorkspaceRowRightGroup({
isHovered,
isTouchPlatform,
showShortcut,
isSelectionMode,
});
const kebab = useOpenKebabMenuVisibility(showKebabInSlot);
@@ -695,6 +711,7 @@ function WorkspaceRowRightGroup({
onRename={onRename}
onMarkAsRead={onMarkAsRead}
onMarkAsUnread={onMarkAsUnread}
onSelectWorkspace={onSelectWorkspace}
onArchive={onArchive}
archiveLabel={archiveLabel}
archiveStatus={archiveStatus}
@@ -1065,6 +1082,7 @@ function WorkspaceRowInner({
archiveLabel,
archiveStatus = "idle",
archivePendingLabel,
onSelectWorkspace,
onArchive,
onCopyBranchName,
onCopyPath,
@@ -1079,6 +1097,8 @@ function WorkspaceRowInner({
}: WorkspaceRowInnerProps) {
const isCompact = useIsCompactFormFactor();
const [isHighlighted, setIsHighlighted] = useState(false);
const isSelectionMode = useIsSidebarSelectionMode();
const isBulkSelected = useIsWorkspaceBulkSelected(workspace.workspaceKey);
const isTouchPlatform = platformIsNative || isCompact;
const interaction = useLongPressDragInteraction({
drag,
@@ -1091,30 +1111,75 @@ function WorkspaceRowInner({
...dragAttributes
} = dragHandleProps?.attributes ?? {};
const { onPress: handlePress, feedback } = useWorkspaceRowPress({
const { onPress: handleNavigatePress, feedback } = useWorkspaceRowPress({
didLongPressRef: interaction.didLongPressRef,
onPress,
selected,
});
const accessibilityState = useMemo(() => ({ selected }), [selected]);
const handleRowPress = useCallback(
(event: GestureResponderEvent) => {
const shiftKey = isShiftPressEvent(event);
if (isSelectionMode || shiftKey) {
if (interaction.didLongPressRef.current) {
interaction.didLongPressRef.current = false;
return;
}
event.preventDefault?.();
useSidebarSelectionStore.getState().pressWorkspace(workspace.workspaceKey, { shiftKey });
return;
}
handleNavigatePress();
},
[handleNavigatePress, interaction.didLongPressRef, isSelectionMode, workspace.workspaceKey],
);
const handleRowPressIn = useCallback(
(event: GestureResponderEvent) => {
if (isShiftPressEvent(event)) {
event.preventDefault?.();
return;
}
if (!isSelectionMode) {
interaction.handlePressIn(event);
}
},
[interaction, isSelectionMode],
);
const rowSelected = isSelectionMode ? isBulkSelected : selected;
const accessibilityState = useMemo(
() => (isSelectionMode ? { checked: isBulkSelected } : { selected }),
[isSelectionMode, isBulkSelected, selected],
);
const isEditingTitle = titleEditor !== null;
const disableDrag = isEditingTitle || isSelectionMode;
return (
<SidebarWorkspaceRowFrame
workspace={workspace}
isDragging={isDragging}
isEditingTitle={isEditingTitle}
isSelectionMode={isSelectionMode}
>
{({ isHovered, contextMenuOpen, onContextMenuOpenChange, hoverHandlers }) => {
const isDesktop = !isTouchPlatform;
const serviceSummary = isDesktop ? selectWorkspaceServiceSummary(workspace.scripts) : null;
const workspaceRowStyle = getProjectWorkspaceRowStyle({ isDragging, selected, isHovered });
const backdrop = getSidebarRowBackdrop({ isDragging, isHighlighted, selected, isHovered });
const workspaceRowStyle = getProjectWorkspaceRowStyle({
isDragging,
selected: rowSelected,
isHovered,
});
const backdrop = getSidebarRowBackdrop({
isDragging,
isHighlighted,
selected: rowSelected,
isHovered,
});
return (
<View
{...dragAttributes}
{...(isEditingTitle ? null : dragHandleProps?.listeners)}
{...(disableDrag ? null : dragHandleProps?.listeners)}
ref={dragHandleProps?.setActivatorNodeRef as unknown as Ref<View>}
style={styles.workspaceRowContainer}
{...hoverHandlers}
@@ -1131,6 +1196,7 @@ function WorkspaceRowInner({
onRename={onRename}
onMarkAsRead={onMarkAsRead}
onMarkAsUnread={onMarkAsUnread}
onSelectWorkspace={onSelectWorkspace}
onArchive={onArchive}
archiveLabel={archiveLabel}
archiveStatus={archiveStatus}
@@ -1140,17 +1206,18 @@ function WorkspaceRowInner({
onTogglePin={onTogglePin}
openInFileManagerPath={workspace.workspaceDirectory}
disabled={isArchiving}
enabled={!isEditingTitle}
aria-selected={selected}
accessibilityRole="button"
enabled={!isEditingTitle && !isSelectionMode}
aria-selected={isSelectionMode ? undefined : selected}
aria-checked={isSelectionMode ? isBulkSelected : undefined}
accessibilityRole={isSelectionMode ? "checkbox" : "button"}
accessibilityState={accessibilityState}
style={workspaceRowStyle}
highlightStyle={isEditingTitle ? undefined : styles.workspaceRowPressed}
onHighlightChange={setIsHighlighted}
onPressIn={isEditingTitle ? undefined : interaction.handlePressIn}
onTouchMove={isEditingTitle ? undefined : interaction.handleTouchMove}
onPressOut={isEditingTitle ? undefined : interaction.handlePressOut}
onPress={isEditingTitle ? undefined : handlePress}
onPressIn={isEditingTitle ? undefined : handleRowPressIn}
onTouchMove={disableDrag ? undefined : interaction.handleTouchMove}
onPressOut={disableDrag ? undefined : interaction.handlePressOut}
onPress={isEditingTitle ? undefined : handleRowPress}
testID={`sidebar-workspace-row-${workspace.workspaceKey}`}
>
<SidebarWorkspaceRowContent
@@ -1163,6 +1230,8 @@ function WorkspaceRowInner({
isHovered={isHovered}
isLoading={isArchiving || isCreating}
isCreating={isCreating}
isSelectionMode={isSelectionMode}
isBulkSelected={isBulkSelected}
shortcutNumber={shortcutNumber}
showShortcutBadge={showShortcutBadge}
reserveIdleStatusIndicatorSpace={reserveIdleStatusIndicatorSpace}
@@ -1174,12 +1243,14 @@ function WorkspaceRowInner({
isHovered={isHovered}
isTouchPlatform={isTouchPlatform}
isCreating={isCreating}
isSelectionMode={isSelectionMode}
showShortcutBadge={showShortcutBadge}
shortcutNumber={shortcutNumber}
archiveLabel={archiveLabel}
archiveStatus={archiveStatus}
archivePendingLabel={archivePendingLabel}
archiveShortcutKeys={archiveShortcutKeys}
onSelectWorkspace={onSelectWorkspace}
onArchive={onArchive}
onCopyBranchName={onCopyBranchName}
onCopyPath={onCopyPath}
@@ -1265,6 +1336,10 @@ function WorkspaceRowWithMenu({
archiveController.archive();
}, [archiveController, isArchiving]);
const handleSelectWorkspace = useCallback(() => {
useSidebarSelectionStore.getState().enter(workspace.workspaceKey);
}, [workspace.workspaceKey]);
const clipboard = useWorkspaceClipboardActions();
const handleCopyPath = useCallback(() => {
clipboard.copyPath(workspace);
@@ -1317,6 +1392,7 @@ function WorkspaceRowWithMenu({
archiveLabel={t("sidebar.workspace.actions.archive")}
archiveStatus={isArchiving ? "pending" : "idle"}
archivePendingLabel={t("sidebar.workspace.actions.archiving")}
onSelectWorkspace={handleSelectWorkspace}
onArchive={handleArchive}
onCopyBranchName={canCopyBranchName ? handleCopyBranchName : undefined}
onCopyPath={handleCopyPath}
@@ -2199,6 +2275,62 @@ function ProjectModeList({
selection: selectionEnabled ? activeWorkspaceSelection : null,
expanded: pinnedChatsExpanded,
});
const visibleOrderInputRef = useRef({
pinnedCollapsed,
leadingPinnedChat,
visiblePinnedChats,
unpinnedProjects,
collapsedProjectKeys,
expandedProjectKeys,
selectionEnabled,
activeWorkspaceSelection,
workspaceEntriesByKey,
});
visibleOrderInputRef.current = {
pinnedCollapsed,
leadingPinnedChat,
visiblePinnedChats,
unpinnedProjects,
collapsedProjectKeys,
expandedProjectKeys,
selectionEnabled,
activeWorkspaceSelection,
workspaceEntriesByKey,
};
useEffect(() => {
return registerSidebarVisibleWorkspaceKeysReader(() => {
const current = visibleOrderInputRef.current;
const keys: string[] = [];
if (!current.pinnedCollapsed) {
if (current.leadingPinnedChat) keys.push(current.leadingPinnedChat.workspaceKey);
for (const item of current.visiblePinnedChats) {
keys.push(item.workspaceKey);
}
}
const policy = createWorkspaceVisibilityPolicy<SidebarWorkspacePlacement>(
current.workspaceEntriesByKey,
);
const selection = current.selectionEnabled ? current.activeWorkspaceSelection : null;
for (const project of current.unpinnedProjects) {
if (current.collapsedProjectKeys.has(project.viewKey) || project.workspaces.length === 0) {
continue;
}
const { leadingItem, visibleItems } = selectSidebarGroupVisibility({
items: project.workspaces,
selection,
expanded: current.expandedProjectKeys.has(project.viewKey),
policy,
});
if (leadingItem) keys.push(leadingItem.workspaceKey);
for (const item of visibleItems) {
keys.push(item.workspaceKey);
}
}
return keys;
});
}, []);
const nativeScrollGestureProps = useMemo(
() =>
parentGestureRef
@@ -3,14 +3,16 @@ import { PressHighlight as Pressable } from "@/components/ui/press-highlight";
import {
memo,
useCallback,
useEffect,
useMemo,
useRef,
useState,
type MutableRefObject,
type ReactNode,
type Ref,
} from "react";
import { useTranslation } from "react-i18next";
import { View, Text, ScrollView } from "react-native";
import { View, Text, ScrollView, type GestureResponderEvent } from "react-native";
import { NestableScrollContainer } from "react-native-draggable-flatlist";
import type { GestureType } from "react-native-gesture-handler";
import { navigateToWorkspace } from "@/stores/navigation-active-workspace-store";
@@ -69,7 +71,15 @@ import {
} from "@/components/sidebar/sidebar-workspace-menu";
import { SidebarSectionHeader } from "@/components/sidebar/sidebar-section-header";
import { SidebarGroupToggleRow } from "@/components/sidebar/sidebar-group-toggle-row";
import { selectSidebarGroupVisibility } from "@/components/sidebar/sidebar-group-visibility";
import { useLimitedSidebarGroup } from "@/components/sidebar/use-limited-sidebar-group";
import {
isShiftPressEvent,
registerSidebarVisibleWorkspaceKeysReader,
useIsSidebarSelectionMode,
useIsWorkspaceBulkSelected,
useSidebarSelectionStore,
} from "@/sidebar-selection";
import type { ToggleSidebarWorkspacePin } from "@/hooks/use-sidebar-workspace-pin";
import { DraggableList, type DraggableRenderItemInfo } from "@/components/draggable-list";
import type { DraggableListDragHandleProps } from "@/components/draggable-list.types";
@@ -154,6 +164,14 @@ export function SidebarStatusWorkspaceList({
() => setPinnedWorkspacesExpanded((current) => !current),
[],
);
const [expandedGroupKeys, setExpandedGroupKeys] = useState<ReadonlySet<string>>(() => new Set());
const toggleGroupWorkspacesExpanded = useCallback((groupKey: string) => {
setExpandedGroupKeys((current) => {
const next = new Set(current);
if (!next.delete(groupKey)) next.add(groupKey);
return next;
});
}, []);
const {
leadingItem: leadingPinnedWorkspace,
visibleItems: visiblePinnedWorkspaces,
@@ -164,6 +182,56 @@ export function SidebarStatusWorkspaceList({
expanded: pinnedWorkspacesExpanded,
});
const visibleOrderInputRef = useRef({
pinnedCollapsed,
leadingPinnedWorkspace,
visiblePinnedWorkspaces,
groups,
collapsedWorkspaceGroupKeys,
expandedGroupKeys,
activeWorkspaceSelection,
});
visibleOrderInputRef.current = {
pinnedCollapsed,
leadingPinnedWorkspace,
visiblePinnedWorkspaces,
groups,
collapsedWorkspaceGroupKeys,
expandedGroupKeys,
activeWorkspaceSelection,
};
useEffect(() => {
return registerSidebarVisibleWorkspaceKeysReader(() => {
const current = visibleOrderInputRef.current;
const keys: string[] = [];
if (!current.pinnedCollapsed) {
if (current.leadingPinnedWorkspace) {
keys.push(current.leadingPinnedWorkspace.workspaceKey);
}
for (const item of current.visiblePinnedWorkspaces) {
keys.push(item.workspaceKey);
}
}
for (const group of current.groups) {
if (current.collapsedWorkspaceGroupKeys.has(group.key) || group.rows.length === 0) {
continue;
}
const { leadingItem, visibleItems } = selectSidebarGroupVisibility({
items: group.rows,
selection: current.activeWorkspaceSelection,
expanded: current.expandedGroupKeys.has(group.key),
policy: STATUS_GROUP_VISIBILITY,
});
if (leadingItem) keys.push(leadingItem.workspaceKey);
for (const item of visibleItems) {
keys.push(item.workspaceKey);
}
}
return keys;
});
}, []);
const statusShortcutIndex = showShortcutBadges
? shortcutIndexByWorkspaceKey
: EMPTY_SHORTCUT_INDEX;
@@ -262,6 +330,8 @@ export function SidebarStatusWorkspaceList({
<StatusGroupList
groups={groups}
collapsedWorkspaceGroupKeys={collapsedWorkspaceGroupKeys}
expandedGroupKeys={expandedGroupKeys}
onToggleGroupWorkspacesExpanded={toggleGroupWorkspacesExpanded}
projectIconByProjectViewKey={projectIconByProjectViewKey}
shortcutIndex={statusShortcutIndex}
showShortcutBadges={showShortcutBadges}
@@ -303,6 +373,8 @@ export function SidebarStatusWorkspaceList({
function StatusGroupList({
groups,
collapsedWorkspaceGroupKeys,
expandedGroupKeys,
onToggleGroupWorkspacesExpanded,
projectIconByProjectViewKey,
shortcutIndex,
showShortcutBadges,
@@ -313,6 +385,8 @@ function StatusGroupList({
}: {
groups: SidebarWorkspaceGroup[];
collapsedWorkspaceGroupKeys: ReadonlySet<string>;
expandedGroupKeys: ReadonlySet<string>;
onToggleGroupWorkspacesExpanded: (groupKey: string) => void;
projectIconByProjectViewKey: ReadonlyMap<string, string | null>;
shortcutIndex: Map<string, number>;
showShortcutBadges: boolean;
@@ -328,6 +402,8 @@ function StatusGroupList({
key={group.key}
group={group}
collapsed={collapsedWorkspaceGroupKeys.has(group.key)}
workspacesExpanded={expandedGroupKeys.has(group.key)}
onToggleWorkspacesExpanded={onToggleGroupWorkspacesExpanded}
projectIconByProjectViewKey={projectIconByProjectViewKey}
shortcutIndex={shortcutIndex}
showShortcutBadges={showShortcutBadges}
@@ -349,6 +425,8 @@ const STATUS_GROUP_VISIBILITY = {
function StatusGroupRows({
group,
collapsed,
workspacesExpanded,
onToggleWorkspacesExpanded,
projectIconByProjectViewKey,
shortcutIndex,
showShortcutBadges,
@@ -359,6 +437,8 @@ function StatusGroupRows({
}: {
group: SidebarWorkspaceGroup;
collapsed: boolean;
workspacesExpanded: boolean;
onToggleWorkspacesExpanded: (groupKey: string) => void;
projectIconByProjectViewKey: ReadonlyMap<string, string | null>;
shortcutIndex: Map<string, number>;
showShortcutBadges: boolean;
@@ -368,10 +448,9 @@ function StatusGroupRows({
onToggleWorkspacePin: ToggleSidebarWorkspacePin;
}) {
const activeWorkspaceSelection = useActiveWorkspaceSelection();
const [workspacesExpanded, setWorkspacesExpanded] = useState(false);
const toggleWorkspacesExpanded = useCallback(
() => setWorkspacesExpanded((current) => !current),
[],
() => onToggleWorkspacesExpanded(group.key),
[group.key, onToggleWorkspacesExpanded],
);
const {
leadingItem: leadingWorkspace,
@@ -669,6 +748,10 @@ function StatusWorkspaceRowWithMenu({
archiveController.archive();
}, [archiveController, isArchiving]);
const handleSelectWorkspace = useCallback(() => {
useSidebarSelectionStore.getState().enter(workspace.workspaceKey);
}, [workspace.workspaceKey]);
const clipboard = useWorkspaceClipboardActions();
const handleCopyPath = useCallback(() => {
clipboard.copyPath(workspace);
@@ -716,6 +799,7 @@ function StatusWorkspaceRowWithMenu({
archiveLabel={t("sidebar.workspace.actions.archive")}
archiveStatus={isArchiving ? "pending" : "idle"}
archivePendingLabel={t("sidebar.workspace.actions.archiving")}
onSelectWorkspace={handleSelectWorkspace}
onArchive={handleArchive}
onCopyBranchName={workspace.projectKind === "git" ? handleCopyBranchName : undefined}
onCopyPath={handleCopyPath}
@@ -750,6 +834,7 @@ interface StatusWorkspaceRowInnerProps {
archiveLabel?: string;
archiveStatus?: "idle" | "pending" | "success";
archivePendingLabel?: string;
onSelectWorkspace?: () => void;
onArchive?: () => void;
onCopyBranchName?: () => void;
onCopyPath?: () => void;
@@ -799,6 +884,7 @@ function StatusWorkspaceRowInnerContent({
archiveLabel,
archiveStatus = "idle",
archivePendingLabel,
onSelectWorkspace,
onArchive,
onCopyBranchName,
onCopyPath,
@@ -820,6 +906,8 @@ function StatusWorkspaceRowInnerContent({
const isCompact = useIsCompactFormFactor();
const isTouchPlatform = platformIsNative || isCompact;
const [isHighlighted, setIsHighlighted] = useState(false);
const isSelectionMode = useIsSidebarSelectionMode();
const isBulkSelected = useIsWorkspaceBulkSelected(workspace.workspaceKey);
const trailing = useSidebarWorkspaceTrailing();
const {
role: _dragRole,
@@ -831,23 +919,59 @@ function StatusWorkspaceRowInnerContent({
const isDesktop = !isTouchPlatform;
const serviceSummary = isDesktop ? selectWorkspaceServiceSummary(workspace.scripts) : null;
const accessibilityState = useMemo(() => ({ selected }), [selected]);
const rowSelected = isSelectionMode ? isBulkSelected : selected;
const accessibilityState = useMemo(
() => (isSelectionMode ? { checked: isBulkSelected } : { selected }),
[isSelectionMode, isBulkSelected, selected],
);
const isEditingTitle = titleEditor !== null;
const disableDrag = isEditingTitle || isSelectionMode;
const didLongPressRef = dragInteraction?.didLongPressRef;
const startDragPress = dragInteraction?.handlePressIn;
const moveDragPress = dragInteraction?.handleTouchMove;
const endDragPress = dragInteraction?.handlePressOut;
const { onPress: handlePress, feedback } = useWorkspaceRowPress({
const { onPress: handleNavigatePress, feedback } = useWorkspaceRowPress({
didLongPressRef,
onPress,
selected,
});
const handleRowPress = useCallback(
(event: GestureResponderEvent) => {
const shiftKey = isShiftPressEvent(event);
if (isSelectionMode || shiftKey) {
if (didLongPressRef?.current) {
didLongPressRef.current = false;
return;
}
event.preventDefault?.();
useSidebarSelectionStore.getState().pressWorkspace(workspace.workspaceKey, { shiftKey });
return;
}
handleNavigatePress();
},
[didLongPressRef, handleNavigatePress, isSelectionMode, workspace.workspaceKey],
);
const handleRowPressIn = useCallback(
(event: GestureResponderEvent) => {
if (isShiftPressEvent(event)) {
event.preventDefault?.();
return;
}
if (!isSelectionMode) {
startDragPress?.(event);
}
},
[isSelectionMode, startDragPress],
);
return (
<SidebarWorkspaceRowFrame
workspace={workspace}
isDragging={isDragging}
isEditingTitle={isEditingTitle}
isSelectionMode={isSelectionMode}
>
{({ isHovered, contextMenuOpen, onContextMenuOpenChange, hoverHandlers }) => {
const showShortcut = showShortcutBadge && shortcutNumber !== null;
@@ -865,18 +989,24 @@ function StatusWorkspaceRowInnerContent({
isHovered,
isTouchPlatform,
showShortcut,
isSelectionMode,
});
const workspaceRowStyle = getStatusWorkspaceRowStyle({
selected,
selected: rowSelected,
isHovered,
inStatusGroup,
isDragging,
});
const backdrop = getSidebarRowBackdrop({ isDragging, isHighlighted, selected, isHovered });
const backdrop = getSidebarRowBackdrop({
isDragging,
isHighlighted,
selected: rowSelected,
isHovered,
});
return (
<View
{...dragAttributes}
{...(isEditingTitle ? null : dragHandleProps?.listeners)}
{...(disableDrag ? null : dragHandleProps?.listeners)}
ref={dragHandleProps?.setActivatorNodeRef as unknown as Ref<View>}
style={styles.workspaceRowContainer}
{...hoverHandlers}
@@ -894,6 +1024,7 @@ function StatusWorkspaceRowInnerContent({
onRename={onRename}
onMarkAsRead={onMarkAsRead}
onMarkAsUnread={onMarkAsUnread}
onSelectWorkspace={onSelectWorkspace}
onArchive={onArchive}
archiveLabel={archiveLabel}
archiveStatus={archiveStatus}
@@ -903,16 +1034,18 @@ function StatusWorkspaceRowInnerContent({
onTogglePin={onTogglePin}
openInFileManagerPath={workspace.workspaceDirectory}
disabled={isArchiving}
enabled={!isEditingTitle}
accessibilityRole="button"
enabled={!isEditingTitle && !isSelectionMode}
aria-selected={isSelectionMode ? undefined : selected}
aria-checked={isSelectionMode ? isBulkSelected : undefined}
accessibilityRole={isSelectionMode ? "checkbox" : "button"}
accessibilityState={accessibilityState}
style={workspaceRowStyle}
highlightStyle={isEditingTitle ? undefined : styles.workspaceRowPressed}
onHighlightChange={setIsHighlighted}
onPressIn={isEditingTitle ? undefined : startDragPress}
onTouchMove={isEditingTitle ? undefined : moveDragPress}
onPressOut={isEditingTitle ? undefined : endDragPress}
onPress={isEditingTitle ? undefined : handlePress}
onPressIn={isEditingTitle ? undefined : handleRowPressIn}
onTouchMove={disableDrag ? undefined : moveDragPress}
onPressOut={disableDrag ? undefined : endDragPress}
onPress={isEditingTitle ? undefined : handleRowPress}
testID={`sidebar-workspace-row-${workspace.workspaceKey}`}
>
<SidebarWorkspaceRowContent
@@ -924,6 +1057,8 @@ function StatusWorkspaceRowInnerContent({
backdrop={backdrop}
isHovered={isHovered}
isLoading={isArchiving}
isSelectionMode={isSelectionMode}
isBulkSelected={isBulkSelected}
shortcutNumber={shortcutNumber}
showShortcutBadge={showShortcutBadge}
reserveIdleStatusIndicatorSpace={reserveIdleStatusIndicatorSpace}
@@ -946,6 +1081,7 @@ function StatusWorkspaceRowInnerContent({
onRename={onRename}
onMarkAsRead={onMarkAsRead}
onMarkAsUnread={onMarkAsUnread}
onSelectWorkspace={onSelectWorkspace}
onArchive={onArchive}
archiveLabel={archiveLabel}
archiveStatus={archiveStatus}
@@ -979,6 +1115,7 @@ function StatusWorkspaceActionSlot({
onRename,
onMarkAsRead,
onMarkAsUnread,
onSelectWorkspace,
onArchive,
archiveLabel,
archiveStatus,
@@ -1000,6 +1137,7 @@ function StatusWorkspaceActionSlot({
onRename?: () => void;
onMarkAsRead?: () => void;
onMarkAsUnread?: () => void;
onSelectWorkspace?: () => void;
onArchive?: () => void;
archiveLabel?: string;
archiveStatus?: "idle" | "pending" | "success";
@@ -1034,6 +1172,7 @@ function StatusWorkspaceActionSlot({
onRename={onRename}
onMarkAsRead={onMarkAsRead}
onMarkAsUnread={onMarkAsUnread}
onSelectWorkspace={onSelectWorkspace}
onArchive={onArchive}
archiveLabel={archiveLabel}
archiveStatus={archiveStatus}
@@ -5,6 +5,7 @@ import {
useEffect,
useMemo,
useRef,
useState,
type ReactNode,
} from "react";
import { View } from "react-native";
@@ -15,7 +16,13 @@ import Animated, {
type SharedValue,
} from "react-native-reanimated";
import { StyleSheet } from "react-native-unistyles";
import { TOAST_FADE_MS, ToastViewport, useToastHost, type ToastApi } from "@/components/toast-host";
import {
TOAST_FADE_MS,
ToastViewport,
useToastHost,
type ToastApi,
type ToastState,
} from "@/components/toast-host";
import { ToastApiProvider, useToast } from "@/contexts/toast-context";
interface SidebarToastCoverage {
@@ -25,6 +32,10 @@ interface SidebarToastCoverage {
}
const SidebarToastCoverageContext = createContext<SidebarToastCoverage | null>(null);
const SidebarPersistentToastContext = createContext<((toast: ToastState | null) => void) | null>(
null,
);
const SidebarAppToastContext = createContext<ToastApi | null>(null);
/**
* Shows toasts raised by the sidebar's list over its bottom edge, just above the footer.
@@ -36,9 +47,10 @@ const SidebarToastCoverageContext = createContext<SidebarToastCoverage | null>(n
export function SidebarToastRegion({ active, children }: { active: boolean; children: ReactNode }) {
const appToast = useToast();
const { api: sidebarToast, toast, dismiss } = useToastHost();
const [persistentToast, setPersistentToast] = useState<ToastState | null>(null);
const activeRef = useRef(active);
const coverageHeight = useSharedValue(0);
const toastVisible = toast !== null;
const toastVisible = toast !== null || persistentToast !== null;
useEffect(() => {
activeRef.current = active;
@@ -72,19 +84,48 @@ export function SidebarToastRegion({ active, children }: { active: boolean; chil
return (
<View style={styles.region}>
<SidebarToastCoverageContext.Provider value={coverage}>
<ToastApiProvider api={api}>{children}</ToastApiProvider>
</SidebarToastCoverageContext.Provider>
<ToastViewport
toast={toast}
onDismiss={dismiss}
placement="sidebar"
onBottomCoverageChange={handleCoverageChange}
/>
<ToastApiProvider api={api}>
<SidebarAppToastContext.Provider value={appToast}>
<SidebarPersistentToastContext.Provider value={setPersistentToast}>
<SidebarToastCoverageContext.Provider value={coverage}>
{children}
</SidebarToastCoverageContext.Provider>
</SidebarPersistentToastContext.Provider>
</SidebarAppToastContext.Provider>
<ToastViewport
toast={toast}
persistentToast={persistentToast}
onDismiss={dismiss}
placement="sidebar"
onBottomCoverageChange={handleCoverageChange}
/>
</ToastApiProvider>
</View>
);
}
/** Returns the enclosing app-level toast API so sidebar callers can report errors without displacing an active sidebar undo toast. */
export function useSidebarAppToast(): ToastApi {
const fallbackToast = useToast();
return useContext(SidebarAppToastContext) ?? fallbackToast;
}
/**
* Displays a persistent toast in the enclosing `SidebarToastRegion`, stacked below any active
* transient toast so controls stay reachable while a previous toast is up.
*/
export function useSidebarPersistentToast(toast: ToastState | null): void {
const setPersistentToast = useContext(SidebarPersistentToastContext);
useEffect(() => {
setPersistentToast?.(toast);
}, [setPersistentToast, toast]);
useEffect(() => {
return () => {
setPersistentToast?.(null);
};
}, [setPersistentToast]);
}
/**
* Space at the end of a sidebar list that matches the toast covering it, so the last row can
* scroll clear of the toast. It sits below every row, so growing it moves nothing. It shrinks
@@ -1,9 +1,10 @@
import { useMemo, type ComponentProps, type PropsWithChildren, type ReactNode } from "react";
import { useTranslation } from "react-i18next";
import type { PressableStateCallbackType } from "react-native";
import type { GestureResponderEvent, PressableStateCallbackType } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import {
Archive,
CheckSquare,
Circle,
CircleCheck,
Copy,
@@ -56,6 +57,7 @@ const foregroundMutedColorMapping = (theme: Theme) => ({
const ThemedMoreVertical = withUnistyles(MoreVertical);
const ThemedCopy = withUnistyles(Copy);
const ThemedArchive = withUnistyles(Archive);
const ThemedCheckSquare = withUnistyles(CheckSquare);
const ThemedCircle = withUnistyles(Circle);
const ThemedPencil = withUnistyles(Pencil);
const ThemedCircleCheck = withUnistyles(CircleCheck);
@@ -69,6 +71,7 @@ const markAsReadLeadingIcon = (
<ThemedCircleCheck size={14} uniProps={foregroundMutedColorMapping} />
);
const markAsUnreadLeadingIcon = <ThemedCircle size={14} uniProps={foregroundMutedColorMapping} />;
const selectLeadingIcon = <ThemedCheckSquare size={14} uniProps={foregroundMutedColorMapping} />;
const archiveLeadingIcon = <ThemedArchive size={14} uniProps={foregroundMutedColorMapping} />;
const pinLeadingIcon = <ThemedPin size={14} uniProps={foregroundMutedColorMapping} />;
const unpinLeadingIcon = <ThemedPinOff size={14} uniProps={foregroundMutedColorMapping} />;
@@ -124,6 +127,7 @@ export interface SidebarWorkspaceMenuProps {
onRename?: () => void;
onMarkAsRead?: () => void;
onMarkAsUnread?: () => void;
onSelectWorkspace?: () => void;
onArchive: () => void;
archiveLabel?: string;
archiveStatus?: "idle" | "pending" | "success";
@@ -172,6 +176,7 @@ function SidebarWorkspaceMenuItems({
onRename,
onMarkAsRead,
onMarkAsUnread,
onSelectWorkspace,
onArchive,
archiveLabel,
archiveStatus,
@@ -267,6 +272,16 @@ function SidebarWorkspaceMenuItems({
path={openInFileManagerPath}
testID={`sidebar-workspace-menu-open-folder-${workspaceKey}`}
/>
{onSelectWorkspace ? (
<WorkspaceMenuItem
surface={surface}
testID={`sidebar-workspace-menu-select-${workspaceKey}`}
leading={selectLeadingIcon}
onSelect={onSelectWorkspace}
>
{t("sidebar.workspace.actions.select")}
</WorkspaceMenuItem>
) : null}
{onArchive ? (
<WorkspaceMenuItem
surface={surface}
@@ -294,6 +309,7 @@ export function SidebarWorkspaceMenu({
onRename,
onMarkAsRead,
onMarkAsUnread,
onSelectWorkspace,
onArchive,
archiveLabel,
archiveStatus,
@@ -340,6 +356,7 @@ export function SidebarWorkspaceMenu({
onRename={onRename}
onMarkAsRead={onMarkAsRead}
onMarkAsUnread={onMarkAsUnread}
onSelectWorkspace={onSelectWorkspace}
onArchive={onArchive}
archiveLabel={archiveLabel}
archiveStatus={archiveStatus}
@@ -373,6 +390,7 @@ export function SidebarWorkspaceContextMenu({
onRename,
onMarkAsRead,
onMarkAsUnread,
onSelectWorkspace,
onArchive,
archiveLabel,
archiveStatus,
@@ -426,11 +444,37 @@ export function SidebarWorkspaceContextMenu({
[workspace],
);
const pages = useWorkspaceLabelMenuPages(workspaceTarget);
const checkboxSpaceKeyProps = useMemo(() => {
if (!isWeb || triggerProps.accessibilityRole !== "checkbox" || !triggerProps.onPress) {
return {};
}
const onPress = triggerProps.onPress;
return {
// React Native Web's Pressable activates Space only for role="button", not checkbox.
onKeyDown: (event: {
key?: string;
repeat?: boolean;
target?: unknown;
currentTarget?: unknown;
preventDefault?: () => void;
}) => {
if (triggerProps.disabled) return;
if (event.target !== event.currentTarget) return;
if (event.key === " " || event.key === "Spacebar") {
event.preventDefault?.();
if (!event.repeat) {
onPress(event as unknown as GestureResponderEvent);
}
}
},
};
}, [triggerProps.accessibilityRole, triggerProps.disabled, triggerProps.onPress]);
return (
<ContextMenu open={contextMenuOpen} onOpenChange={onContextMenuOpenChange}>
<ContextMenuTrigger
{...triggerProps}
{...checkboxSpaceKeyProps}
enabledOnMobile={false}
accessibilityLabel={accessibilityLabel ?? rowAccessibilityLabel}
highlightStyle={highlightStyle}
@@ -454,6 +498,7 @@ export function SidebarWorkspaceContextMenu({
onRename={onRename}
onMarkAsRead={onMarkAsRead}
onMarkAsUnread={onMarkAsUnread}
onSelectWorkspace={onSelectWorkspace}
onArchive={onArchive}
archiveLabel={archiveLabel}
archiveStatus={archiveStatus}
@@ -1,7 +1,8 @@
import { memo, useMemo, useCallback, useState, type ReactNode } from "react";
import { Text, View, type ViewStyle } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { CircleAlert, Folder, FolderGit2, Monitor } from "lucide-react-native";
import { Check, CircleAlert, Folder, FolderGit2, Monitor } from "lucide-react-native";
import { bySizing } from "@/components/ui/control-geometry";
import { ProjectStatusIndicator } from "@/components/sidebar/project-leading-visual";
import type { SidebarSurfaceBackdrop } from "@/styles/surface-backdrop";
import {
@@ -40,19 +41,26 @@ const needsInputColorMapping = (theme: Theme) => ({
color: theme.colors.surface0,
fill: getStatusDotColor({ theme, bucket: "needs_input" }) ?? undefined,
});
const checkedIconMapping = (theme: Theme) => ({
color: theme.colors.accentForeground,
});
const ThemedCheck = withUnistyles(Check);
const ThemedCircleAlert = withUnistyles(CircleAlert);
export function SidebarWorkspaceRowFrame({
workspace,
isDragging = false,
isEditingTitle = false,
isSelectionMode = false,
children,
}: {
workspace: SidebarWorkspaceEntry;
isDragging?: boolean;
/** Hover would fade the kebab in over the title being edited and open the hover card. */
isEditingTitle?: boolean;
/** Hover cards would cover neighbouring rows while the user clicks through a selection. */
isSelectionMode?: boolean;
children: (input: {
isHovered: boolean;
contextMenuOpen: boolean;
@@ -80,7 +88,7 @@ export function SidebarWorkspaceRowFrame({
workspace={workspace}
prHint={workspace.prHint}
isDragging={isDragging}
disabled={contextMenuOpen || isEditingTitle}
disabled={contextMenuOpen || isEditingTitle || isSelectionMode}
>
{children({
isHovered: isHovered && !contextMenuOpen && !isDragging && !isEditingTitle,
@@ -102,6 +110,8 @@ export const SidebarWorkspaceRowContent = memo(function SidebarWorkspaceRowConte
isHovered,
isLoading,
isCreating = false,
isSelectionMode = false,
isBulkSelected = false,
shortcutNumber = null,
showShortcutBadge = false,
reserveIdleStatusIndicatorSpace = true,
@@ -119,6 +129,8 @@ export const SidebarWorkspaceRowContent = memo(function SidebarWorkspaceRowConte
isHovered: boolean;
isLoading: boolean;
isCreating?: boolean;
isSelectionMode?: boolean;
isBulkSelected?: boolean;
shortcutNumber?: number | null;
showShortcutBadge?: boolean;
/** Keep the empty leading slot when the workspace has no active status. */
@@ -137,33 +149,44 @@ export const SidebarWorkspaceRowContent = memo(function SidebarWorkspaceRowConte
const workspaceBranchTextStyle = useMemo(
() => [
styles.workspaceBranchText,
isHovered && styles.workspaceBranchTextHovered,
(isHovered || isBulkSelected) && styles.workspaceBranchTextHovered,
isCreating && styles.workspaceBranchTextCreating,
],
[isHovered, isCreating],
[isHovered, isBulkSelected, isCreating],
);
let leadingVisual: ReactNode;
if (isSelectionMode) {
leadingVisual = (
<WorkspaceSelectionCheckbox checked={isBulkSelected} workspaceKey={workspace.workspaceKey} />
);
} else if (leadingProjectName) {
leadingVisual = (
<ProjectStatusIndicator
iconDataUri={leadingProjectIconDataUri}
displayName={leadingProjectName}
projectViewKey={workspace.projectViewKey}
statusBucket={workspace.statusBucket}
backdrop={backdrop}
loading={isLoading}
testID={`sidebar-row-project-icon-${workspace.workspaceKey}`}
/>
);
} else {
leadingVisual = (
<WorkspaceStatusIndicator
bucket={workspace.statusBucket}
workspaceKind={workspace.workspaceKind}
loading={isLoading}
reserveIdleSpace={reserveIdleStatusIndicatorSpace}
/>
);
}
return (
<View style={styles.workspaceRowContent}>
<View style={styles.workspaceRowMain}>
{leadingProjectName ? (
<ProjectStatusIndicator
iconDataUri={leadingProjectIconDataUri}
displayName={leadingProjectName}
projectViewKey={workspace.projectViewKey}
statusBucket={workspace.statusBucket}
backdrop={backdrop}
loading={isLoading}
testID={`sidebar-row-project-icon-${workspace.workspaceKey}`}
/>
) : (
<WorkspaceStatusIndicator
bucket={workspace.statusBucket}
workspaceKind={workspace.workspaceKind}
loading={isLoading}
reserveIdleSpace={reserveIdleStatusIndicatorSpace}
/>
)}
{leadingVisual}
<View style={styles.workspaceContentColumn}>
<View style={styles.workspaceTitleRow}>
{titleEditor ? (
@@ -191,7 +214,7 @@ export const SidebarWorkspaceRowContent = memo(function SidebarWorkspaceRowConte
/>
</View>
</View>
{showShortcutBadge && shortcutNumber !== null ? (
{!isSelectionMode && showShortcutBadge && shortcutNumber !== null ? (
<View style={styles.shortcutBadgeOverlay} pointerEvents="none">
<SidebarWorkspaceShortcutBadge number={shortcutNumber} />
</View>
@@ -200,6 +223,22 @@ export const SidebarWorkspaceRowContent = memo(function SidebarWorkspaceRowConte
);
});
function WorkspaceSelectionCheckbox({
checked,
workspaceKey,
}: {
checked: boolean;
workspaceKey: string;
}) {
return (
<View style={styles.workspaceStatusDot} testID={`sidebar-workspace-checkbox-${workspaceKey}`}>
<View style={checked ? styles.selectionCheckboxChecked : styles.selectionCheckbox}>
{checked ? <ThemedCheck size={11} strokeWidth={2.5} uniProps={checkedIconMapping} /> : null}
</View>
</View>
);
}
function WorkspaceStatusIndicator({
bucket,
workspaceKind,
@@ -382,6 +421,7 @@ export function resolveTrailingActionVisibility({
isHovered,
isTouchPlatform,
showShortcut,
isSelectionMode = false,
}: {
workspace: SidebarWorkspaceEntry;
trailing: SidebarWorkspaceTrailing;
@@ -389,6 +429,7 @@ export function resolveTrailingActionVisibility({
isHovered: boolean;
isTouchPlatform: boolean;
showShortcut: boolean;
isSelectionMode?: boolean;
}): {
trailingPresentation: SidebarWorkspaceTrailingPresentation;
showKebab: boolean;
@@ -398,10 +439,11 @@ export function resolveTrailingActionVisibility({
reserveSlotWidth: boolean;
} {
const hasTrailing = hasSidebarWorkspaceTrailing({ workspace, trailing });
const showKebab = Boolean(hasArchiveAction && (isHovered || isTouchPlatform)) && !showShortcut;
const allowRowActions = hasArchiveAction && !isSelectionMode;
const showKebab = Boolean(allowRowActions && (isHovered || isTouchPlatform)) && !showShortcut;
// Touch permanently replaces the stats with the menu. Only temporary shortcut hints
// conceal content while retaining its width, so desktop rows do not shift.
const hasContent = hasTrailing && !(hasArchiveAction && isTouchPlatform);
const hasContent = hasTrailing && !(allowRowActions && isTouchPlatform);
let trailingPresentation: SidebarWorkspaceTrailingPresentation = "absent";
if (hasContent) trailingPresentation = showShortcut ? "hidden" : "visible";
return {
@@ -414,12 +456,12 @@ export function resolveTrailingActionVisibility({
// row — over an unhovered one the gradient fades to the wrong color. That is also why
// touch, which shows the kebab without ever hovering, never gets one.
showScrim: showKebab && isHovered,
renderSlot: hasArchiveAction || hasTrailing,
renderSlot: allowRowActions || hasTrailing,
// The slot only holds width for something that permanently sits in it. Trailing content
// does; the kebab only does on touch, where there is no hover for it to appear on and so
// no scrim to let it overlay the title. Everywhere else the width goes back to the title
// and the kebab fades in over its tail.
reserveSlotWidth: hasContent || (hasArchiveAction && isTouchPlatform),
reserveSlotWidth: hasContent || (allowRowActions && isTouchPlatform),
};
}
@@ -536,6 +578,25 @@ const styles = StyleSheet.create((theme) => ({
alignItems: "center",
justifyContent: "center",
},
selectionCheckbox: {
width: bySizing({ touch: 18, pointer: 15 }),
height: bySizing({ touch: 18, pointer: 15 }),
borderRadius: theme.borderRadius.sm,
borderWidth: 1.5,
borderColor: theme.colors.borderAccent,
alignItems: "center",
justifyContent: "center",
},
selectionCheckboxChecked: {
width: bySizing({ touch: 18, pointer: 15 }),
height: bySizing({ touch: 18, pointer: 15 }),
borderRadius: theme.borderRadius.sm,
borderWidth: 1.5,
borderColor: theme.colors.accent,
backgroundColor: theme.colors.accent,
alignItems: "center",
justifyContent: "center",
},
statusDotOverlay: {
position: "absolute",
right: 0,
+85 -15
View File
@@ -16,6 +16,7 @@ import Animated, { FadeIn, FadeOut } from "react-native-reanimated";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { SPACING, type Theme } from "@/styles/theme";
import { CONTROL_HEIGHTS, mapLayout } from "@/components/ui/control-geometry";
import { useTranslation } from "react-i18next";
import { useIsCompactFormFactor } from "@/constants/layout";
import { isWeb } from "@/constants/platform";
@@ -28,10 +29,16 @@ import {
} from "@/constants/layout";
export type ToastVariant = "default" | "info" | "success" | "warning" | "error";
/**
* `action` tightens vertical and trailing insets around `size="sm"` pill controls and uses a
* concentric corner radius (`controlHeight / 2 + inset`) so buttons nest evenly in the shell.
*/
export type ToastLayout = "default" | "action";
export interface ToastShowOptions {
icon?: ReactNode;
variant?: ToastVariant;
layout?: ToastLayout;
durationMs?: number | null;
nativeAndroid?: boolean;
testID?: string;
@@ -45,6 +52,7 @@ export interface ToastState {
nativeMessage: string | null;
icon?: ReactNode;
variant: ToastVariant;
layout?: ToastLayout;
durationMs: number | null;
testID?: string;
onDismiss?: () => void;
@@ -73,6 +81,11 @@ const TOAST_MAX_WIDTH = 480;
/** How long a toast takes to fade in or out. */
export const TOAST_FADE_MS = 140;
const SIDEBAR_TOAST_INSET = SPACING[2];
const ACTION_TOAST_INSET = SPACING[1.5];
const ACTION_TOAST_RADIUS = mapLayout(
CONTROL_HEIGHTS.sm,
(height) => height / 2 + ACTION_TOAST_INSET,
);
const toastEntering = FadeIn.duration(TOAST_FADE_MS);
const toastExiting = FadeOut.duration(TOAST_FADE_MS);
const ThemedCheckCircle = withUnistyles(CheckCircle2);
@@ -136,6 +149,7 @@ export function useToastHost(): {
nativeMessage,
icon: options?.icon,
variant,
layout: options?.layout,
durationMs,
testID: options?.testID,
onDismiss: options?.onDismiss,
@@ -163,11 +177,14 @@ export function useToastHost(): {
export function ToastViewport({
toast,
persistentToast = null,
onDismiss,
placement = "app-shell",
onBottomCoverageChange,
}: {
toast: ToastState | null;
/** Sidebar placement: persistent bar (such as select mode) that stays visible below transient toasts. */
persistentToast?: ToastState | null;
/** Called with the ID of the toast that timed out. */
onDismiss: (id: number) => void;
placement?: ToastViewportPlacement;
@@ -232,7 +249,10 @@ export function ToastViewport({
const handleSidebarLayout = useCallback(
(event: LayoutChangeEvent) => {
onBottomCoverageChange?.(event.nativeEvent.layout.height + SIDEBAR_TOAST_INSET);
const height = event.nativeEvent.layout.height;
if (height > 0) {
onBottomCoverageChange?.(height + SIDEBAR_TOAST_INSET);
}
},
[onBottomCoverageChange],
);
@@ -243,28 +263,41 @@ export function ToastViewport({
const topOffset =
placement === "app-shell" ? insets.top + headerTopPadding + headerHeight : panelClearance;
if (placement === "sidebar") {
return (
<View
style={animatedStyles.sidebarContainer}
pointerEvents="box-none"
collapsable={false}
onLayout={handleSidebarLayout}
>
<SidebarToastSlot
toast={toast}
onPointerEnter={pauseDismiss}
onPointerLeave={resumeDismiss}
/>
<SidebarToastSlot
toast={persistentToast}
onPointerEnter={noopDismiss}
onPointerLeave={noopDismiss}
/>
</View>
);
}
// Keep the bottom anchor and its contents together while the native exit retains the view.
const content = toast ? (
<Animated.View
entering={toastEntering}
exiting={toastExiting}
style={
placement === "sidebar"
? animatedStyles.sidebarContainer
: [
animatedStyles.container,
{ top: topOffset + (placement === "app-shell" ? SPACING[2] : SPACING[3]) },
]
}
style={[
animatedStyles.container,
{ top: topOffset + (placement === "app-shell" ? SPACING[2] : SPACING[3]) },
]}
pointerEvents="box-none"
collapsable={false}
onLayout={placement === "sidebar" ? handleSidebarLayout : undefined}
>
<View
style={placement === "sidebar" ? styles.sidebarWidthBoundary : styles.widthBoundary}
pointerEvents="box-none"
collapsable={false}
>
<View style={styles.widthBoundary} pointerEvents="box-none" collapsable={false}>
<View
style={animatedStyles.surface}
testID={toast.testID ?? "app-toast"}
@@ -283,6 +316,35 @@ export function ToastViewport({
return placement === "panel" ? <FloatingHeaderOverlay>{content}</FloatingHeaderOverlay> : content;
}
function SidebarToastSlot({
toast,
onPointerEnter,
onPointerLeave,
}: {
toast: ToastState | null;
onPointerEnter: () => void;
onPointerLeave: () => void;
}) {
if (!toast) return null;
return (
<Animated.View
entering={toastEntering}
exiting={toastExiting}
style={styles.sidebarWidthBoundary}
pointerEvents="box-none"
collapsable={false}
>
<View
style={animatedStyles.surface}
testID={toast.testID ?? "app-toast"}
accessibilityRole="alert"
>
<ToastCard toast={toast} onPointerEnter={onPointerEnter} onPointerLeave={onPointerLeave} />
</View>
</Animated.View>
);
}
function ToastCard({
toast,
onPointerEnter,
@@ -310,6 +372,7 @@ function ToastCard({
onPointerLeave={onPointerLeave}
style={[
styles.toast,
toast.layout === "action" ? styles.toastAction : null,
toast.variant === "info" ? styles.toastInfo : null,
toast.variant === "warning" ? styles.toastWarning : null,
toast.variant === "error" ? styles.toastError : null,
@@ -344,6 +407,7 @@ const animatedStyles = NativeStyleSheet.create({
bottom: SIDEBAR_TOAST_INSET,
zIndex: OVERLAY_Z.toast,
alignItems: "center",
gap: SIDEBAR_TOAST_INSET,
},
surface: { alignSelf: "center", maxWidth: "100%" },
});
@@ -372,6 +436,12 @@ const styles = StyleSheet.create((theme) => ({
paddingHorizontal: theme.spacing[3],
...theme.shadow.md,
},
toastAction: {
borderRadius: ACTION_TOAST_RADIUS,
paddingVertical: theme.spacing[1.5],
paddingLeft: theme.spacing[3.5],
paddingRight: theme.spacing[1.5],
},
toastInfo: {
borderColor: theme.colors.palette.blue[300],
},
@@ -146,6 +146,8 @@ export interface ComboboxProps {
/** When true, selecting an option does not close the picker (multi-select mode). */
keepOpenOnSelect?: boolean;
anchorRef: React.RefObject<View | null>;
/** Where focus goes when the picker closes. Defaults to whatever had focus when it opened. */
restoreFocusRef?: React.RefObject<unknown>;
children?: ReactNode;
}
@@ -1437,6 +1439,7 @@ export function Combobox({
footer,
keepOpenOnSelect = false,
anchorRef,
restoreFocusRef,
children,
}: ComboboxProps): ReactElement | null {
const { t } = useTranslation();
@@ -1728,6 +1731,7 @@ export function Combobox({
layer: floatingLayer,
keys: ["Escape", "Enter", "ArrowUp", "ArrowDown"],
onKeyDown: (event) => (isDesktopKey(event.key) ? handleDesktopKey(event.key, event) : false),
restoreFocusRef,
});
const effectiveSearchPlaceholder = searchPlaceholder ?? resolvedPlaceholder;
@@ -146,3 +146,41 @@ export async function confirmRiskyWorktreeArchive(
destructive: true,
});
}
export async function confirmRiskyBulkWorktreeArchive(
input: {
totalCount: number;
riskyWorkspaces: readonly WorktreeArchiveConfirmationInput[];
},
labels: WorktreeArchiveWarningLabels = DEFAULT_WORKTREE_ARCHIVE_WARNING_LABELS,
): Promise<boolean> {
const lines: string[] = [];
let singleRisky: WorktreeArchiveConfirmationInput | null = null;
for (const workspace of input.riskyWorkspaces) {
const reasons = buildWorktreeArchiveRiskReasons(workspace, labels);
if (reasons.length === 0) continue;
singleRisky = workspace;
lines.push(
i18n.t("workspace.git.actions.archiveWarning.bulkWorkspaceReason", {
workspaceName: workspace.workspaceName,
reason: reasons.join(", "),
}),
);
}
if (lines.length === 0) {
return true;
}
if (input.totalCount === 1 && singleRisky) {
return await confirmRiskyWorktreeArchive(singleRisky, labels);
}
return await confirmDialog({
title: i18n.t("workspace.git.actions.archiveWarning.bulkTitle", {
count: input.totalCount,
}),
message: lines.join("\n"),
confirmLabel: labels.confirm,
cancelLabel: labels.cancel,
destructive: true,
});
}
+9
View File
@@ -960,6 +960,8 @@ export const ar: TranslationResources = {
},
archiveWarning: {
title: 'الأرشيف "{{workspaceName}}"؟',
bulkTitle: "أرشفة {{count}} مساحات عمل؟",
bulkWorkspaceReason: "{{workspaceName}}: {{reason}}",
confirm: "أرشيف",
cancel: "يلغي",
uncommittedChanges: "تغييرات غير ملتزم بها",
@@ -1369,6 +1371,7 @@ export const ar: TranslationResources = {
rename: "إعادة تسمية مساحة العمل",
pin: "تثبيت في الأعلى",
unpin: "إلغاء التثبيت",
select: "تحديد",
archive: "أرشيف",
archiveWorkspace: "أرشفة مساحة العمل",
hideFromSidebar: "إخفاء من الشريط الجانبي",
@@ -1387,6 +1390,10 @@ export const ar: TranslationResources = {
submit: "إعادة تسمية",
invalidBranchName: "اسم الفرع غير صالح",
},
selection: {
count: "تم تحديد {{count}}",
exit: "إنهاء التحديد",
},
toasts: {
workspacePathUnavailable: "مسار Workspace غير متوفر",
pathCopied: "تم نسخ المسار",
@@ -1394,7 +1401,9 @@ export const ar: TranslationResources = {
hostDisconnected: "Host غير متصل",
hideFailed: "فشل في إخفاء مساحة العمل",
archiveFailed: "فشل في أرشفة مساحة العمل",
archiveMultipleFailed: "فشل في أرشفة {{count}} مساحات عمل",
archived: "تمت أرشفة مساحة العمل",
archivedCount: "تمت أرشفة {{count}} مساحات عمل",
undoArchive: "تراجع",
undoArchiveFailed: "تعذّر التراجع عن الأرشفة",
},
+9
View File
@@ -971,6 +971,8 @@ export const en = {
},
archiveWarning: {
title: 'Archive "{{workspaceName}}"?',
bulkTitle: "Archive {{count}} workspaces?",
bulkWorkspaceReason: "{{workspaceName}}: {{reason}}",
confirm: "Archive",
cancel: "Cancel",
uncommittedChanges: "Uncommitted changes",
@@ -1380,6 +1382,7 @@ export const en = {
rename: "Rename workspace",
pin: "Pin to top",
unpin: "Unpin",
select: "Select",
archive: "Archive",
archiveWorkspace: "Archive workspace",
hideFromSidebar: "Hide from sidebar",
@@ -1398,6 +1401,10 @@ export const en = {
submit: "Rename",
invalidBranchName: "Invalid branch name",
},
selection: {
count: "{{count}} selected",
exit: "Exit selection",
},
toasts: {
workspacePathUnavailable: "Workspace path not available",
pathCopied: "Path copied",
@@ -1405,7 +1412,9 @@ export const en = {
hostDisconnected: "Host is not connected",
hideFailed: "Failed to hide workspace",
archiveFailed: "Failed to archive workspace",
archiveMultipleFailed: "Failed to archive {{count}} workspaces",
archived: "Workspace archived",
archivedCount: "{{count}} workspaces archived",
undoArchive: "Undo",
undoArchiveFailed: "Couldn't undo the archive",
},
+9
View File
@@ -994,6 +994,8 @@ export const es: TranslationResources = {
},
archiveWarning: {
title: '¿Archivo "{{workspaceName}}"?',
bulkTitle: "¿Archivar {{count}} espacios de trabajo?",
bulkWorkspaceReason: "{{workspaceName}}: {{reason}}",
confirm: "Archivo",
cancel: "Cancelar",
uncommittedChanges: "Cambios no confirmados",
@@ -1406,6 +1408,7 @@ export const es: TranslationResources = {
rename: "Cambiar nombre del espacio de trabajo",
pin: "Anclar arriba",
unpin: "Desanclar",
select: "Seleccionar",
archive: "Archivo",
archiveWorkspace: "Archivar espacio de trabajo",
hideFromSidebar: "Ocultar de la barra lateral",
@@ -1424,6 +1427,10 @@ export const es: TranslationResources = {
submit: "Rebautizar",
invalidBranchName: "Nombre de sucursal no válido",
},
selection: {
count: "{{count}} seleccionados",
exit: "Salir de la selección",
},
toasts: {
workspacePathUnavailable: "RutaWorkspaceno disponible",
pathCopied: "Ruta copiada",
@@ -1431,7 +1438,9 @@ export const es: TranslationResources = {
hostDisconnected: "Hostno está conectado",
hideFailed: "No se pudo ocultar el espacio de trabajo",
archiveFailed: "No se pudo archivar el espacio de trabajo",
archiveMultipleFailed: "No se pudieron archivar {{count}} espacios de trabajo",
archived: "Espacio de trabajo archivado",
archivedCount: "{{count}} espacios de trabajo archivados",
undoArchive: "Deshacer",
undoArchiveFailed: "No se pudo deshacer el archivado",
},
+9
View File
@@ -986,6 +986,8 @@ export const fr: TranslationResources = {
},
archiveWarning: {
title: "Archiver « {{workspaceName}} » ?",
bulkTitle: "Archiver {{count}} espaces de travail ?",
bulkWorkspaceReason: "{{workspaceName}} : {{reason}}",
confirm: "Archiver",
cancel: "Annuler",
uncommittedChanges: "Modifications non commitées",
@@ -1399,6 +1401,7 @@ export const fr: TranslationResources = {
rename: "Renommer l’espace de travail",
pin: "Épingler en haut",
unpin: "Désépingler",
select: "Sélectionner",
archive: "Archiver",
archiveWorkspace: "Archiver l’espace de travail",
hideFromSidebar: "Masquer de la barre latérale",
@@ -1417,6 +1420,10 @@ export const fr: TranslationResources = {
submit: "Renommer",
invalidBranchName: "Nom de branche invalide",
},
selection: {
count: "{{count}} sélectionnés",
exit: "Quitter la sélection",
},
toasts: {
workspacePathUnavailable: "Chemin de l’espace de travail indisponible",
pathCopied: "Chemin copié",
@@ -1424,7 +1431,9 @@ export const fr: TranslationResources = {
hostDisconnected: "L’hôte n’est pas connecté",
hideFailed: "Impossible de masquer l’espace de travail",
archiveFailed: "Impossible d’archiver l’espace de travail",
archiveMultipleFailed: "Impossible d’archiver {{count}} espaces de travail",
archived: "Espace de travail archivé",
archivedCount: "{{count}} espaces de travail archivés",
undoArchive: "Annuler",
undoArchiveFailed: "Impossible d’annuler l’archivage",
},
+9
View File
@@ -974,6 +974,8 @@ export const ja: TranslationResources = {
},
archiveWarning: {
title: '"{{workspaceName}}"をアーカイブしますか?',
bulkTitle: "{{count}}件のワークスペースをアーカイブしますか?",
bulkWorkspaceReason: "{{workspaceName}}:{{reason}}",
confirm: "アーカイブ",
cancel: "キャンセル",
uncommittedChanges: "未コミットの変更",
@@ -1384,6 +1386,7 @@ export const ja: TranslationResources = {
rename: "ワークスペースの名前を変更",
pin: "上部に固定",
unpin: "固定解除",
select: "選択",
archive: "アーカイブ",
archiveWorkspace: "ワークスペースをアーカイブ",
hideFromSidebar: "サイドバーから非表示",
@@ -1402,6 +1405,10 @@ export const ja: TranslationResources = {
submit: "名前を変更",
invalidBranchName: "無効なブランチ名",
},
selection: {
count: "{{count}}件選択中",
exit: "選択を終了",
},
toasts: {
workspacePathUnavailable: "ワークスペースパスが利用できません",
pathCopied: "パスをコピーしました",
@@ -1409,7 +1416,9 @@ export const ja: TranslationResources = {
hostDisconnected: "ホストが接続されていません",
hideFailed: "ワークスペースの非表示に失敗しました",
archiveFailed: "ワークスペースのアーカイブに失敗しました",
archiveMultipleFailed: "{{count}}件のワークスペースのアーカイブに失敗しました",
archived: "ワークスペースをアーカイブしました",
archivedCount: "{{count}}件のワークスペースをアーカイブしました",
undoArchive: "元に戻す",
undoArchiveFailed: "アーカイブを元に戻せませんでした",
},
+9
View File
@@ -967,6 +967,8 @@ export const ko: TranslationResources = {
},
archiveWarning: {
title: '"{{workspaceName}}"를 보관하시겠습니까?',
bulkTitle: "워크스페이스 {{count}}개를 보관하시겠습니까?",
bulkWorkspaceReason: "{{workspaceName}}: {{reason}}",
confirm: "보관",
cancel: "취소",
uncommittedChanges: "커밋되지 않은 변경 사항",
@@ -1376,6 +1378,7 @@ export const ko: TranslationResources = {
rename: "워크스페이스 이름 변경",
pin: "상단에 고정",
unpin: "고정 해제",
select: "선택",
archive: "보관",
archiveWorkspace: "워크스페이스 보관",
hideFromSidebar: "사이드바에서 숨기기",
@@ -1394,6 +1397,10 @@ export const ko: TranslationResources = {
submit: "이름 변경",
invalidBranchName: "잘못된 브랜치 이름",
},
selection: {
count: "{{count}}개 선택됨",
exit: "선택 종료",
},
toasts: {
workspacePathUnavailable: "워크스페이스 경로를 사용할 수 없습니다",
pathCopied: "경로가 복사되었습니다",
@@ -1401,7 +1408,9 @@ export const ko: TranslationResources = {
hostDisconnected: "호스트가 연결되어 있지 않습니다",
hideFailed: "워크스페이스를 숨기지 못했습니다",
archiveFailed: "워크스페이스를 보관하지 못했습니다.",
archiveMultipleFailed: "워크스페이스 {{count}}개를 보관하지 못했습니다",
archived: "워크스페이스를 보관했습니다",
archivedCount: "워크스페이스 {{count}}개를 보관했습니다",
undoArchive: "실행 취소",
undoArchiveFailed: "보관을 취소하지 못했습니다",
},
+9
View File
@@ -984,6 +984,8 @@ export const ptBR: TranslationResources = {
},
archiveWarning: {
title: 'Arquivar "{{workspaceName}}"?',
bulkTitle: "Arquivar {{count}} workspaces?",
bulkWorkspaceReason: "{{workspaceName}}: {{reason}}",
confirm: "Arquivar",
cancel: "Cancelar",
uncommittedChanges: "Alterações sem commit",
@@ -1396,6 +1398,7 @@ export const ptBR: TranslationResources = {
rename: "Renomear workspace",
pin: "Fixar no topo",
unpin: "Desafixar",
select: "Selecionar",
archive: "Arquivar",
archiveWorkspace: "Arquivar workspace",
hideFromSidebar: "Ocultar da barra lateral",
@@ -1414,6 +1417,10 @@ export const ptBR: TranslationResources = {
submit: "Renomear",
invalidBranchName: "Nome de branch inválido",
},
selection: {
count: "{{count}} selecionados",
exit: "Sair da seleção",
},
toasts: {
workspacePathUnavailable: "Caminho do workspace indisponível",
pathCopied: "Caminho copiado",
@@ -1421,7 +1428,9 @@ export const ptBR: TranslationResources = {
hostDisconnected: "Host não está conectado",
hideFailed: "Falha ao ocultar workspace",
archiveFailed: "Falha ao arquivar workspace",
archiveMultipleFailed: "Falha ao arquivar {{count}} workspaces",
archived: "Workspace arquivado",
archivedCount: "{{count}} workspaces arquivados",
undoArchive: "Desfazer",
undoArchiveFailed: "Não foi possível desfazer o arquivamento",
},
+9
View File
@@ -979,6 +979,8 @@ export const ru: TranslationResources = {
},
archiveWarning: {
title: "Архивировать «{{workspaceName}}»?",
bulkTitle: "Архивировать рабочие пространства ({{count}})?",
bulkWorkspaceReason: "{{workspaceName}}: {{reason}}",
confirm: "Архивировать",
cancel: "Отмена",
uncommittedChanges: "Незафиксированные изменения",
@@ -1389,6 +1391,7 @@ export const ru: TranslationResources = {
rename: "Переименовать рабочее пространство",
pin: "Закрепить вверху",
unpin: "Открепить",
select: "Выбрать",
archive: "Архивировать",
archiveWorkspace: "Архивировать рабочее пространство",
hideFromSidebar: "Скрыть на боковой панели",
@@ -1407,6 +1410,10 @@ export const ru: TranslationResources = {
submit: "Переименовать",
invalidBranchName: "Недопустимое имя ветки",
},
selection: {
count: "Выбрано: {{count}}",
exit: "Выйти из выбора",
},
toasts: {
workspacePathUnavailable: "Путь к рабочему пространству недоступен",
pathCopied: "Путь скопирован",
@@ -1414,7 +1421,9 @@ export const ru: TranslationResources = {
hostDisconnected: "Хост не подключён",
hideFailed: "Не удалось скрыть рабочее пространство",
archiveFailed: "Не удалось архивировать рабочее пространство",
archiveMultipleFailed: "Не удалось архивировать рабочие пространства ({{count}})",
archived: "Рабочее пространство архивировано",
archivedCount: "Архивировано рабочих пространств: {{count}}",
undoArchive: "Отменить",
undoArchiveFailed: "Не удалось отменить архивацию",
},
+9
View File
@@ -952,6 +952,8 @@ export const zhCN: TranslationResources = {
},
archiveWarning: {
title: "归档「{{workspaceName}}」?",
bulkTitle: "归档 {{count}} 个工作区?",
bulkWorkspaceReason: "{{workspaceName}}:{{reason}}",
confirm: "归档",
cancel: "取消",
uncommittedChanges: "未 commit 的变更",
@@ -1359,6 +1361,7 @@ export const zhCN: TranslationResources = {
rename: "重命名 workspace",
pin: "置顶",
unpin: "取消置顶",
select: "选择",
archive: "归档",
archiveWorkspace: "归档工作区",
hideFromSidebar: "从侧边栏隐藏",
@@ -1376,6 +1379,10 @@ export const zhCN: TranslationResources = {
submit: "重命名",
invalidBranchName: "无效的分支名称",
},
selection: {
count: "已选 {{count}} 项",
exit: "退出选择",
},
toasts: {
workspacePathUnavailable: "Workspace 路径不可用",
pathCopied: "路径已复制",
@@ -1383,7 +1390,9 @@ export const zhCN: TranslationResources = {
hostDisconnected: "Host 未连接",
hideFailed: "隐藏 workspace 失败",
archiveFailed: "归档工作区失败",
archiveMultipleFailed: "归档 {{count}} 个工作区失败",
archived: "工作区已归档",
archivedCount: "已归档 {{count}} 个工作区",
undoArchive: "撤销",
undoArchiveFailed: "无法撤销归档",
},
+1
View File
@@ -14,3 +14,4 @@ export type { HardwareKeyboardEvent } from "./internal/sources/hardware";
export { usesDesktopBindings, supportsConfigurableComposerSendKeys } from "./internal/conventions";
export type { BrowserKeyboardPolicy } from "./internal/sources/electron-browser";
export { useHardwareKeyboardPresent } from "./availability";
export { isShiftKeyDown } from "./internal/shift-modifier";
@@ -9,6 +9,10 @@ export interface OverlayRegistration {
*/
keys: readonly string[];
onKeyDown(event: KeyboardInputEvent): boolean;
/**
* Where focus goes when the overlay closes: an element, or any handle with `focus()`. Defaults
* to whatever had focus when the overlay opened.
*/
restoreFocusRef?: RefObject<unknown>;
manageFocus?: boolean;
}
@@ -3,12 +3,29 @@ import { overlays, type OverlayEntry, type KeyboardInputEvent } from "./overlays
import type { OverlayRegistration } from "./overlay-contract";
type WebOverlayKeyHandler = (event: KeyboardInputEvent) => boolean;
/** A DOM element, or a component handle that knows how to focus itself (such as a text input). */
interface FocusTarget {
focus(): void;
}
function isFocusTarget(value: unknown): value is FocusTarget {
return (
typeof value === "object" &&
value !== null &&
typeof (value as Partial<FocusTarget>).focus === "function"
);
}
function canRestoreFocusTo(target: FocusTarget): boolean {
return !(target instanceof HTMLElement) || document.contains(target);
}
interface WebOverlayEntry {
getLayer: () => number;
getKeys: () => readonly string[];
getScope: () => HTMLElement | null;
getKeyHandler: () => WebOverlayKeyHandler;
restoreFocus: HTMLElement | null;
restoreFocus: FocusTarget | null;
manageFocus: boolean;
}
@@ -156,7 +173,7 @@ function addWebOverlay(entry: WebOverlayEntry): (options?: RemoveWebOverlayOptio
entry.manageFocus &&
options?.restoreFocus !== false &&
entry.restoreFocus &&
document.contains(entry.restoreFocus)
canRestoreFocusTo(entry.restoreFocus)
) {
entry.restoreFocus.focus();
}
@@ -181,7 +198,7 @@ export function useOverlayRegistration({
keysRef.current = keys;
const layerRef = useRef(layer);
const keyHandlerRef = useRef(onKeyDown);
const capturedRestoreFocusRef = useRef<HTMLElement | null>(null);
const capturedRestoreFocusRef = useRef<FocusTarget | null>(null);
const removeEntryRef = useRef<((options?: RemoveWebOverlayOptions) => void) | null>(null);
const detachedRemoveEntryRef = useRef<((options?: RemoveWebOverlayOptions) => void) | null>(null);
const registeredRef = useRef(false);
@@ -193,7 +210,7 @@ export function useOverlayRegistration({
keyHandlerRef.current = onKeyDown;
if (active && !wasActiveRef.current && typeof document !== "undefined") {
const requestedRestoreTarget = preferredRestoreFocusRef?.current;
if (requestedRestoreTarget instanceof HTMLElement) {
if (isFocusTarget(requestedRestoreTarget)) {
capturedRestoreFocusRef.current = requestedRestoreTarget;
} else {
capturedRestoreFocusRef.current =
@@ -0,0 +1,51 @@
export interface ShiftModifierKeyEvent {
key: string;
code?: string;
shiftKey: boolean;
}
export interface ShiftModifierTracker {
isDown(): boolean;
handleKeyDown(event: ShiftModifierKeyEvent): void;
handleKeyUp(event: ShiftModifierKeyEvent): void;
reset(): void;
}
/**
* Tracks whether a physical Shift key is currently held across DOM and native
* hardware keyboard streams so touch/pointer press handlers that omit
* `shiftKey` (native GestureResponderEvent, touch-synthesized clicks) can still
* observe Shift+tap and Shift+click.
*/
export function createShiftModifierTracker(): ShiftModifierTracker {
const pressedCodes = new Set<string>();
return {
isDown: () => pressedCodes.size > 0,
handleKeyDown(event) {
if (event.key === "Shift") {
pressedCodes.add(event.code || "Shift");
} else if (!event.shiftKey && pressedCodes.size > 0) {
pressedCodes.clear();
}
},
handleKeyUp(event) {
if (event.key === "Shift") {
pressedCodes.delete(event.code || "Shift");
if (!event.shiftKey) {
pressedCodes.clear();
}
} else if (!event.shiftKey && pressedCodes.size > 0) {
pressedCodes.clear();
}
},
reset() {
pressedCodes.clear();
},
};
}
export const shiftModifier = createShiftModifierTracker();
export function isShiftKeyDown(): boolean {
return shiftModifier.isDown();
}
@@ -1,3 +1,4 @@
import { AppState } from "react-native";
import type { KeyboardPolicyInput, KeyboardSourceHandlers } from "./contract";
import {
setHardwareKeyboardClaimedShortcuts,
@@ -7,6 +8,14 @@ import {
import { createHardwareKeyboardSource } from "./native";
const hardwareKeyboard = createHardwareKeyboardSource({
subscribe: subscribeHardwareKeyboard,
subscribeBlur: (onBlur) => {
const subscription = AppState.addEventListener("change", (nextState) => {
if (nextState !== "active") {
onBlur();
}
});
return () => subscription.remove();
},
setOverlayKeys: setHardwareKeyboardOverlayKeys,
setClaimedShortcuts: setHardwareKeyboardClaimedShortcuts,
});
@@ -9,6 +9,7 @@ import {
import type { ClaimedShortcut, HardwareKeyboardEvent } from "./hardware";
interface HardwareKeySource {
subscribe(handler: (event: HardwareKeyboardEvent) => void): () => void;
subscribeBlur?(handler: () => void): () => void;
setOverlayKeys(keys: readonly string[]): void;
setClaimedShortcuts(shortcuts: readonly ClaimedShortcut[]): void;
}
@@ -78,7 +79,9 @@ export function createHardwareKeyboardSource(source: HardwareKeySource) {
nativeKeyboardInput(event, focusSurfaces.resolve(handlers.commandCenterOpen())),
);
});
const unsubscribeBlur = source.subscribeBlur?.(() => handlers.blur()) ?? (() => {});
return () => {
unsubscribeBlur();
unsubscribeHardware();
unsubscribeFocus();
unsubscribeCommandCenter();
@@ -269,4 +269,80 @@ describe("hardware source adapter", () => {
expect(claimed).toEqual([]);
releaseFinal();
});
it("forwards native blur events and unsubscribes on detach", async () => {
const { createHardwareKeyboardSource } = await import("./internal/sources/native");
const blurListeners = new Set<() => void>();
let blurCalls = 0;
const detach = createHardwareKeyboardSource({
subscribe: () => () => {},
subscribeBlur(listener) {
blurListeners.add(listener);
return () => {
blurListeners.delete(listener);
};
},
setOverlayKeys() {},
setClaimedShortcuts() {},
}).attach({
keyDown() {},
keyUp() {},
blur() {
blurCalls += 1;
},
commandCenterOpen: () => false,
subscribeCommandCenter: () => () => {},
});
for (const listener of blurListeners) listener();
expect(blurCalls).toBe(1);
detach();
expect(blurListeners.size).toBe(0);
});
});
describe("shift modifier tracking", () => {
it("tracks left/right Shift holds, self-heals on non-shifted keys, and resets on blur", async () => {
const { createShiftModifierTracker } = await import("./internal/shift-modifier");
const tracker = createShiftModifierTracker();
expect(tracker.isDown()).toBe(false);
tracker.handleKeyDown({ key: "Shift", code: "ShiftLeft", shiftKey: true });
expect(tracker.isDown()).toBe(true);
tracker.handleKeyDown({ key: "Shift", code: "ShiftRight", shiftKey: true });
tracker.handleKeyUp({ key: "Shift", code: "ShiftLeft", shiftKey: true });
expect(tracker.isDown()).toBe(true);
tracker.handleKeyUp({ key: "Shift", code: "ShiftRight", shiftKey: false });
expect(tracker.isDown()).toBe(false);
// Self-heals if a Shift key-up was swallowed by the OS.
tracker.handleKeyDown({ key: "Shift", code: "ShiftLeft", shiftKey: true });
expect(tracker.isDown()).toBe(true);
tracker.handleKeyDown({ key: "a", code: "KeyA", shiftKey: false });
expect(tracker.isDown()).toBe(false);
// Clears on blur / backgrounding.
tracker.handleKeyDown({ key: "Shift", code: "ShiftLeft", shiftKey: true });
expect(tracker.isDown()).toBe(true);
tracker.reset();
expect(tracker.isDown()).toBe(false);
});
it("exposes live hardware Shift state through isShiftKeyDown", async () => {
const { shiftModifier } = await import("./internal/shift-modifier");
const { isShiftKeyDown } = await import("./index");
try {
shiftModifier.reset();
expect(isShiftKeyDown()).toBe(false);
shiftModifier.handleKeyDown({ key: "Shift", code: "ShiftLeft", shiftKey: true });
expect(isShiftKeyDown()).toBe(true);
shiftModifier.handleKeyUp({ key: "Shift", code: "ShiftLeft", shiftKey: false });
expect(isShiftKeyDown()).toBe(false);
} finally {
shiftModifier.reset();
}
});
});
+16 -3
View File
@@ -1,6 +1,7 @@
import { usesDesktopBindings } from "./internal/conventions";
import { createKeyboardPipeline } from "./internal/pipeline";
import { overlays } from "./internal/overlays";
import { shiftModifier } from "./internal/shift-modifier";
import { attachKeyboardSources, publishKeyboardPolicy } from "./internal/sources";
import type { KeyboardSourceInput } from "./internal/sources/contract";
import type { KeyboardInputEvent } from "./internal/overlays";
@@ -249,19 +250,30 @@ export function useKeyboardShortcuts({
[getContext, getBindings, isCapturing, dispatchMatch, beforeResolve, chordChanged],
);
const handleKeyDown = useStableEvent((input: KeyboardSourceInput) => {
shiftModifier.handleKeyDown(input.event);
return pipeline.keyDown(input);
});
const handleKeyUp = useStableEvent((event: KeyboardInputEvent) => {
shiftModifier.handleKeyUp(event);
const key = event.key ?? "";
if (key === badgeModifierKey) {
setBadgeModifierDown(false);
}
});
const handleBlur = useStableEvent(() => {
shiftModifier.reset();
resetModifiers();
});
useEffect(() => {
if (!enabled) return;
const detach = attachKeyboardSources({
keyDown: pipeline.keyDown,
keyDown: handleKeyDown,
keyUp: handleKeyUp,
blur: resetModifiers,
blur: handleBlur,
commandCenterOpen: () => useKeyboardShortcutsStore.getState().commandCenterOpen,
subscribeCommandCenter: (listener) =>
useKeyboardShortcutsStore.subscribe((state, previous) => {
@@ -270,7 +282,8 @@ export function useKeyboardShortcuts({
});
return () => {
detach();
shiftModifier.reset();
pipeline.dispose();
};
}, [enabled, pipeline, handleKeyUp, resetModifiers]);
}, [enabled, pipeline, handleKeyDown, handleKeyUp, handleBlur]);
}
@@ -1578,9 +1578,18 @@ export function NewWorkspaceScreen({
? t("newWorkspace.refPicker.searching")
: t("newWorkspace.refPicker.noMatchingRefs");
// The prompt is where the user types; when a field's picker closes, focus returns there rather
// than to whatever had focus when the picker opened. A terminal profile that takes no prompt
// shows a read-only command preview, so its pickers keep returning focus to their field.
const composerFocusRef = useRef<{ focus: () => void } | null>(null);
const handleComposerFocusInput = useCallback((focus: () => void) => {
composerFocusRef.current = { focus };
}, []);
const formStack = useNewWorkspaceForm({
isCompact,
isPending,
restoreFocusRef: terminalTakesPrompt ? composerFocusRef : undefined,
pluginItems: (
<PluginNewWorkspaceItems serverId={selectedServerId} screen={pluginScreen} setup={setup} />
),
@@ -1682,6 +1691,7 @@ export function NewWorkspaceScreen({
clearDraft={noopClearDraft}
autoFocus={terminalTakesPrompt}
autoFocusKey={launchFocusKey}
onFocusInput={handleComposerFocusInput}
error={errorMessage}
/>
) : (
@@ -1712,6 +1722,7 @@ export function NewWorkspaceScreen({
clearDraft={handleClearDraft}
autoFocus
autoFocusKey={launchFocusKey}
onFocusInput={handleComposerFocusInput}
commandDraft={composerState?.commandDraft}
agentControls={agentControlsWithDisabled}
error={errorMessage}
@@ -67,6 +67,11 @@ export interface NewWorkspaceFormProps {
isPending: boolean;
/** Plugin fields, drawn after the base ref. */
pluginItems: ReactNode;
/**
* Where focus goes when a field's picker closes, so the user keeps typing the prompt. Without
* one, focus returns to the field that opened the picker.
*/
restoreFocusRef?: RefObject<unknown>;
project: PickerControl & {
options: ComboboxOption[];
projectByOptionId: Map<string, HostProjectListItem>;
@@ -373,7 +378,17 @@ function useRefPicker(base: NewWorkspaceFormProps["base"], isPending: boolean) {
*/
export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement {
const { t } = useTranslation();
const { isCompact, isPending, pluginItems, project, host, isolation, base, launch } = props;
const {
isCompact,
isPending,
pluginItems,
restoreFocusRef,
project,
host,
isolation,
base,
launch,
} = props;
const variant: FieldTriggerVariant = isCompact ? "field" : "badge";
const projectPicker = useProjectPicker(project, isPending);
const isolationPicker = useIsolationPicker({
@@ -432,6 +447,7 @@ export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement
open={host.openState}
onOpenChange={host.onOpenChange}
anchorRef={host.anchorRef}
restoreFocusRef={restoreFocusRef}
includeAddHost
onAddHost={host.onAddHost}
addHostTestID="new-workspace-host-picker-add-host"
@@ -525,6 +541,7 @@ export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement
desktopPlacement="bottom-start"
desktopMinWidth={360}
anchorRef={project.anchorRef}
restoreFocusRef={restoreFocusRef}
emptyText="No projects available."
renderOption={projectPicker.renderOption}
footer={projectPicker.footer}
@@ -539,6 +556,7 @@ export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement
searchable={false}
desktopPlacement="bottom-start"
anchorRef={isolation.anchorRef}
restoreFocusRef={restoreFocusRef}
desktopMinWidth={280}
renderOption={isolationPicker.renderOption}
/>
@@ -555,6 +573,7 @@ export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement
desktopPlacement="bottom-start"
desktopMinWidth={440}
anchorRef={base.anchorRef}
restoreFocusRef={restoreFocusRef}
emptyText={base.emptyText}
toolbar={refPicker.toolbar}
renderOption={refPicker.renderOption}
@@ -571,6 +590,7 @@ export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement
desktopPlacement="bottom-start"
desktopMinWidth={360}
anchorRef={worktreePicker.anchorRef}
restoreFocusRef={restoreFocusRef}
emptyText={t("newWorkspace.worktreePicker.empty")}
renderOption={worktreePicker.renderOption}
/>
@@ -0,0 +1,8 @@
export { isShiftPressEvent } from "./internal/selection-state";
export {
registerSidebarVisibleWorkspaceKeysReader,
useIsSidebarSelectionMode,
useIsWorkspaceBulkSelected,
useSidebarSelectionStore,
} from "./internal/selection-store";
export { SidebarSelectionHost } from "./internal/sidebar-selection-host";
@@ -0,0 +1,280 @@
import { describe, expect, it, vi } from "vitest";
import type { ToastApi } from "@/components/toast-host";
import type { SidebarWorkspaceEntry } from "@/hooks/use-sidebar-workspaces-list";
import {
archiveSelectedWorkspaces,
type BulkArchiveClient,
type BulkArchiveWorkspacesDeps,
} from "./archive-selected";
function makeEntry(
overrides: Partial<SidebarWorkspaceEntry> & { workspaceId: string },
): SidebarWorkspaceEntry {
return {
workspaceKey: `srv:${overrides.workspaceId}`,
serverId: "srv",
projectViewKey: "prj-view",
projectName: "Repo",
projectRootPath: "/repo",
workspaceDirectory: `/repo/${overrides.workspaceId}`,
workspaceDirectoryLabel: overrides.workspaceId,
projectKind: "git",
workspaceKind: "local_checkout",
name: overrides.workspaceId,
title: null,
currentBranch: overrides.workspaceId,
statusBucket: "done",
statusEnteredAt: null,
archivingAt: null,
diffStat: null,
prHint: null,
pinnedAt: null,
background: false,
labels: [],
scripts: [],
hasRunningScripts: false,
archiveHasUncommittedChanges: null,
archiveUnpushedCommitCount: null,
...overrides,
};
}
function createFakeToast(): { toast: ToastApi; errors: string[] } {
const errors: string[] = [];
return {
errors,
toast: {
show: () => () => {},
copied: () => {},
error: (message) => errors.push(message),
},
};
}
function createFakeClient(): BulkArchiveClient {
return {
archiveWorkspace: async () => ({ error: null }),
undoWorkspaceArchive: async () => {},
getCheckoutStatus: async () =>
({
isGit: true,
isDirty: false,
aheadOfOrigin: 0,
}) as Awaited<ReturnType<BulkArchiveClient["getCheckoutStatus"]>>,
};
}
describe("archiveSelectedWorkspaces", () => {
it("archives multiple workspaces with one undo batch and redirects active workspace first", async () => {
const order: string[] = [];
const client = createFakeClient();
const { toast, errors } = createFakeToast();
const confirmRiskyBulkArchive = vi.fn(async () => true);
const deps: BulkArchiveWorkspacesDeps = {
getClient: () => client,
supportsUndo: () => true,
readWorktreeRisk: async () => ({ isDirty: false, aheadOfOrigin: 0 }),
confirmRiskyBulkArchive,
archiveWithUndo: async (input) => {
order.push(
`archive:${input.entries.map((entry) => entry.workspace.workspaceId).join(",")}`,
);
return { failures: [], showPartialFailure: () => false };
},
archiveWithoutUndo: async () => "archived",
hasActiveUndo: () => false,
purgeWorkspaceState: vi.fn(),
redirectActiveWorkspace: (workspace) => {
order.push(`redirect:${workspace.workspaceId}`);
},
};
const ok = await archiveSelectedWorkspaces({
workspaces: [makeEntry({ workspaceId: "w1" }), makeEntry({ workspaceId: "w2" })],
toast,
onArchiveStarted: () => order.push("exit-selection"),
deps,
});
expect(ok).toBe(true);
expect(errors).toEqual([]);
expect(order).toEqual(["redirect:w1", "redirect:w2", "exit-selection", "archive:w1,w2"]);
expect(confirmRiskyBulkArchive).not.toHaveBeenCalled();
});
it("keeps select mode open when the user cancels a risky worktree confirmation", async () => {
const client = createFakeClient();
const { toast, errors } = createFakeToast();
const onArchiveStarted = vi.fn();
const archiveWithUndo = vi.fn(async () => ({
failures: [],
showPartialFailure: () => false,
}));
const confirmRiskyBulkArchive = vi.fn(async () => false);
const ok = await archiveSelectedWorkspaces({
workspaces: [
makeEntry({ workspaceId: "w1", workspaceKind: "worktree", name: "feat-wip" }),
makeEntry({ workspaceId: "w2", workspaceKind: "local_checkout", name: "main" }),
],
toast,
onArchiveStarted,
deps: {
getClient: () => client,
supportsUndo: () => true,
readWorktreeRisk: async () => ({ isDirty: true, aheadOfOrigin: 1 }),
confirmRiskyBulkArchive,
archiveWithUndo,
archiveWithoutUndo: async () => "archived",
hasActiveUndo: () => false,
purgeWorkspaceState: vi.fn(),
redirectActiveWorkspace: vi.fn(),
},
});
expect(ok).toBe(false);
expect(errors).toEqual([]);
expect(confirmRiskyBulkArchive).toHaveBeenCalledWith({
totalCount: 2,
riskyWorkspaces: [
{
workspaceName: "feat-wip",
diffStat: null,
isDirty: true,
aheadOfOrigin: 1,
},
],
});
expect(onArchiveStarted).not.toHaveBeenCalled();
expect(archiveWithUndo).not.toHaveBeenCalled();
});
it("shows a disconnect error and aborts before archiving when any host is offline", async () => {
const { toast, errors } = createFakeToast();
const onArchiveStarted = vi.fn();
const ok = await archiveSelectedWorkspaces({
workspaces: [makeEntry({ workspaceId: "w1" })],
toast,
onArchiveStarted,
deps: {
getClient: () => null,
supportsUndo: () => true,
readWorktreeRisk: vi.fn(),
confirmRiskyBulkArchive: vi.fn(),
archiveWithUndo: vi.fn(),
archiveWithoutUndo: vi.fn(),
hasActiveUndo: () => false,
purgeWorkspaceState: vi.fn(),
redirectActiveWorkspace: vi.fn(),
},
});
expect(ok).toBe(false);
expect(errors).toEqual(["Host is not connected"]);
expect(onArchiveStarted).not.toHaveBeenCalled();
});
it("reports multi-workspace failures when more than one archive fails", async () => {
const client = createFakeClient();
const { toast, errors } = createFakeToast();
const ok = await archiveSelectedWorkspaces({
workspaces: [makeEntry({ workspaceId: "w1" }), makeEntry({ workspaceId: "w2" })],
toast,
onArchiveStarted: vi.fn(),
deps: {
getClient: () => client,
supportsUndo: () => true,
readWorktreeRisk: vi.fn(),
confirmRiskyBulkArchive: vi.fn(),
archiveWithUndo: async () => ({
failures: [
{ workspace: { serverId: "srv", workspaceId: "w1" }, error: new Error("boom 1") },
{ workspace: { serverId: "srv", workspaceId: "w2" }, error: new Error("boom 2") },
],
showPartialFailure: () => false,
}),
archiveWithoutUndo: vi.fn(),
hasActiveUndo: () => false,
purgeWorkspaceState: vi.fn(),
redirectActiveWorkspace: vi.fn(),
},
});
expect(ok).toBe(false);
expect(errors).toEqual(["Failed to archive 2 workspaces"]);
});
it("keeps Undo open via showPartialFailure instead of replacing it with toast.error on partial failure", async () => {
const client = createFakeClient();
const { toast, errors } = createFakeToast();
const partialErrors: string[] = [];
const ok = await archiveSelectedWorkspaces({
workspaces: [makeEntry({ workspaceId: "w1" }), makeEntry({ workspaceId: "w2" })],
toast,
onArchiveStarted: vi.fn(),
deps: {
getClient: () => client,
supportsUndo: () => true,
readWorktreeRisk: vi.fn(),
confirmRiskyBulkArchive: vi.fn(),
archiveWithUndo: async () => ({
failures: [
{ workspace: { serverId: "srv", workspaceId: "w2" }, error: new Error("Host offline") },
],
showPartialFailure: (message) => {
partialErrors.push(message);
return true;
},
}),
archiveWithoutUndo: vi.fn(),
hasActiveUndo: () => false,
purgeWorkspaceState: vi.fn(),
redirectActiveWorkspace: vi.fn(),
},
});
expect(ok).toBe(false);
expect(partialErrors).toEqual(["Host offline"]);
expect(errors).toEqual([]);
});
it("routes a late failure from a superseded batch to fallbackErrorToast so a newer batch keeps its Undo", async () => {
const client = createFakeClient();
const sidebar = createFakeToast();
const app = createFakeToast();
const ok = await archiveSelectedWorkspaces({
workspaces: [makeEntry({ workspaceId: "w1" })],
toast: sidebar.toast,
fallbackErrorToast: app.toast,
onArchiveStarted: vi.fn(),
deps: {
getClient: () => client,
supportsUndo: () => true,
readWorktreeRisk: vi.fn(),
confirmRiskyBulkArchive: vi.fn(),
archiveWithUndo: async () => ({
failures: [
{
workspace: { serverId: "srv", workspaceId: "w1" },
error: new Error("Host timed out"),
},
],
// This batch's own undo window was closed when a newer batch superseded it.
showPartialFailure: () => false,
}),
archiveWithoutUndo: vi.fn(),
hasActiveUndo: () => true,
purgeWorkspaceState: vi.fn(),
redirectActiveWorkspace: vi.fn(),
},
});
expect(ok).toBe(false);
expect(sidebar.errors).toEqual([]);
expect(app.errors).toEqual(["Host timed out"]);
});
});
@@ -0,0 +1,197 @@
import type { ToastApi } from "@/components/toast-host";
import type { CheckoutStatusClient } from "@/git/checkout-status-cache";
import {
confirmRiskyBulkWorktreeArchive,
readWorktreeArchiveRisk,
type WorktreeArchiveConfirmationInput,
} from "@/git/worktree-archive-warning";
import type { SidebarWorkspaceEntry } from "@/hooks/use-sidebar-workspaces-list";
import { i18n } from "@/i18n/i18next";
import { getHostRuntimeStore } from "@/runtime/host-runtime";
import type { ActiveWorkspaceSelection } from "@/stores/navigation-active-workspace-store";
import { useWorkspaceLayoutStore } from "@/stores/workspace-layout-store";
import { redirectIfArchivingActiveWorkspace } from "@/utils/sidebar-workspace-archive-redirect";
import { buildWorkspaceTabPersistenceKey } from "@/workspace-tabs/model";
import {
archiveWorkspacesWithUndo,
hasUndoableWorkspaceArchive,
supportsWorkspaceArchiveUndo,
type UndoableWorkspaceArchiveClient,
} from "@/workspace/archive-undo";
import {
archiveWorkspaceOptimistically,
type WorkspaceArchiveTarget,
} from "@/workspace/workspace-archive";
export interface BulkArchiveClient extends UndoableWorkspaceArchiveClient, CheckoutStatusClient {}
export interface BulkArchiveWorkspacesDeps {
getClient: (serverId: string) => BulkArchiveClient | null;
supportsUndo: (serverId: string) => boolean;
readWorktreeRisk: typeof readWorktreeArchiveRisk;
confirmRiskyBulkArchive: typeof confirmRiskyBulkWorktreeArchive;
archiveWithUndo: typeof archiveWorkspacesWithUndo;
archiveWithoutUndo: typeof archiveWorkspaceOptimistically;
hasActiveUndo: () => boolean;
purgeWorkspaceState: (workspace: WorkspaceArchiveTarget) => void;
redirectActiveWorkspace: (workspace: WorkspaceArchiveTarget) => void;
}
function defaultPurgeWorkspaceState(workspace: WorkspaceArchiveTarget): void {
const workspaceKey = buildWorkspaceTabPersistenceKey(workspace);
if (workspaceKey) {
useWorkspaceLayoutStore.getState().purgeWorkspace(workspaceKey);
}
}
export function createDefaultBulkArchiveDeps(
getActiveWorkspaceSelection: () => ActiveWorkspaceSelection | null,
): BulkArchiveWorkspacesDeps {
return {
getClient: (serverId) => getHostRuntimeStore().getClient(serverId),
supportsUndo: supportsWorkspaceArchiveUndo,
readWorktreeRisk: readWorktreeArchiveRisk,
confirmRiskyBulkArchive: confirmRiskyBulkWorktreeArchive,
archiveWithUndo: archiveWorkspacesWithUndo,
archiveWithoutUndo: archiveWorkspaceOptimistically,
hasActiveUndo: hasUndoableWorkspaceArchive,
purgeWorkspaceState: defaultPurgeWorkspaceState,
redirectActiveWorkspace: (workspace) => {
redirectIfArchivingActiveWorkspace({
serverId: workspace.serverId,
workspaceId: workspace.workspaceId,
activeWorkspaceSelection: getActiveWorkspaceSelection(),
});
},
};
}
function formatArchiveFailureMessage(failures: ReadonlyArray<{ error: unknown }>): string {
if (failures.length > 1) {
return i18n.t("sidebar.workspace.toasts.archiveMultipleFailed", { count: failures.length });
}
const error = failures[0]?.error;
return error instanceof Error ? error.message : i18n.t("sidebar.workspace.toasts.archiveFailed");
}
interface ResolvedWorkspaceTarget {
entry: SidebarWorkspaceEntry;
client: BulkArchiveClient;
}
export async function archiveSelectedWorkspaces(input: {
workspaces: readonly SidebarWorkspaceEntry[];
toast: ToastApi;
fallbackErrorToast?: ToastApi;
onArchiveStarted: () => void;
deps: BulkArchiveWorkspacesDeps;
}): Promise<boolean> {
const { workspaces, toast, fallbackErrorToast, onArchiveStarted, deps } = input;
if (workspaces.length === 0) return false;
const resolved: ResolvedWorkspaceTarget[] = [];
for (const entry of workspaces) {
const client = deps.getClient(entry.serverId);
if (!client) {
toast.error(i18n.t("sidebar.workspace.toasts.hostDisconnected"));
return false;
}
resolved.push({ entry, client });
}
const riskyWorkspaces: WorktreeArchiveConfirmationInput[] = [];
const worktrees = resolved.filter((item) => item.entry.workspaceKind === "worktree");
if (worktrees.length > 0) {
try {
const risks = await Promise.all(
worktrees.map(async ({ entry, client }) => {
const risk = await deps.readWorktreeRisk(client, entry.workspaceDirectory);
return {
workspaceName: entry.name,
diffStat: entry.diffStat,
isDirty: risk.isDirty,
aheadOfOrigin: risk.aheadOfOrigin,
} satisfies WorktreeArchiveConfirmationInput;
}),
);
riskyWorkspaces.push(...risks);
} catch (error) {
toast.error(
error instanceof Error ? error.message : i18n.t("sidebar.workspace.toasts.archiveFailed"),
);
return false;
}
}
if (riskyWorkspaces.length > 0) {
const confirmed = await deps.confirmRiskyBulkArchive({
totalCount: resolved.length,
riskyWorkspaces,
});
if (!confirmed) {
return false;
}
}
// Redirect before optimistic removal hides the active workspace from the session store.
for (const { entry } of resolved) {
deps.redirectActiveWorkspace({ serverId: entry.serverId, workspaceId: entry.workspaceId });
}
onArchiveStarted();
const undoable: ResolvedWorkspaceTarget[] = [];
const legacy: ResolvedWorkspaceTarget[] = [];
for (const item of resolved) {
if (deps.supportsUndo(item.entry.serverId)) {
undoable.push(item);
} else {
legacy.push(item);
}
}
const failures: Array<{ error: unknown }> = [];
let showPartialFailure: (message: string) => boolean = () => false;
await Promise.all([
undoable.length > 0
? (async () => {
const result = await deps.archiveWithUndo({
entries: undoable.map(({ entry, client }) => {
const workspace = { serverId: entry.serverId, workspaceId: entry.workspaceId };
return {
client,
workspace,
onArchiveCommitted: () => deps.purgeWorkspaceState(workspace),
};
}),
toast,
});
failures.push(...result.failures);
showPartialFailure = result.showPartialFailure;
})()
: Promise.resolve(),
// COMPAT(workspaceArchiveUndo): hosts before v0.15.3 cannot undo; remove after 2027-05-06.
...legacy.map(async ({ entry, client }) => {
const workspace = { serverId: entry.serverId, workspaceId: entry.workspaceId };
try {
await deps.archiveWithoutUndo({ client, workspace });
deps.purgeWorkspaceState(workspace);
} catch (error) {
failures.push({ error });
}
}),
]);
if (failures.length > 0) {
const errorMessage = formatArchiveFailureMessage(failures);
if (!showPartialFailure(errorMessage)) {
// If a newer batch now owns the sidebar Undo toast, surface this older failure on the
// app-level toast instead of displacing the active Undo window and purging its layouts.
const errorToast = deps.hasActiveUndo() ? (fallbackErrorToast ?? toast) : toast;
errorToast.error(errorMessage);
}
}
return failures.length === 0;
}
@@ -0,0 +1,93 @@
import { describe, expect, it } from "vitest";
import {
enterWorkspaceSelection,
exitWorkspaceSelection,
INITIAL_WORKSPACE_SELECTION_STATE,
isShiftPressEvent,
reconcileWorkspaceSelection,
selectWorkspaceRange,
toggleWorkspaceSelection,
} from "./selection-state";
describe("sidebar workspace selection state", () => {
it("enters selection with the clicked workspace as anchor", () => {
const state = enterWorkspaceSelection("ws-2");
expect({
active: state.active,
selected: [...state.selectedKeys],
anchorKey: state.anchorKey,
}).toEqual({
active: true,
selected: ["ws-2"],
anchorKey: "ws-2",
});
});
it("toggles workspaces on plain click without needing Shift", () => {
let state = enterWorkspaceSelection("ws-1");
state = toggleWorkspaceSelection(state, "ws-3");
expect([...state.selectedKeys]).toEqual(["ws-1", "ws-3"]);
expect(state.anchorKey).toBe("ws-3");
state = toggleWorkspaceSelection(state, "ws-1");
expect([...state.selectedKeys]).toEqual(["ws-3"]);
expect(state.anchorKey).toBe("ws-1");
state = toggleWorkspaceSelection(state, "ws-3");
expect(state.active).toBe(true);
expect([...state.selectedKeys]).toEqual([]);
});
it("selects an inclusive range on Shift+click in either direction while keeping prior picks", () => {
const visible = ["ws-1", "ws-2", "ws-3", "ws-4", "ws-5"];
let state = enterWorkspaceSelection("ws-1");
state = toggleWorkspaceSelection(state, "ws-3");
state = selectWorkspaceRange(state, "ws-5", visible);
expect([...state.selectedKeys]).toEqual(["ws-1", "ws-3", "ws-4", "ws-5"]);
expect(state.anchorKey).toBe("ws-3");
const backward = selectWorkspaceRange(enterWorkspaceSelection("ws-4"), "ws-2", visible);
expect([...backward.selectedKeys].sort()).toEqual(["ws-2", "ws-3", "ws-4"]);
});
it("falls back to adding the target when the anchor is no longer in the visible list", () => {
const state = selectWorkspaceRange(enterWorkspaceSelection("ws-hidden"), "ws-2", [
"ws-1",
"ws-2",
]);
expect([...state.selectedKeys]).toEqual(["ws-hidden", "ws-2"]);
expect(state.anchorKey).toBe("ws-2");
});
it("reconciles removed workspaces and clears a missing anchor", () => {
let state = enterWorkspaceSelection("ws-1");
state = toggleWorkspaceSelection(state, "ws-2");
const reconciled = reconcileWorkspaceSelection(state, new Set(["ws-1"]));
expect({
active: reconciled.active,
selected: [...reconciled.selectedKeys],
anchorKey: reconciled.anchorKey,
}).toEqual({
active: true,
selected: ["ws-1"],
anchorKey: null,
});
});
it("resets completely on exit", () => {
expect(exitWorkspaceSelection()).toBe(INITIAL_WORKSPACE_SELECTION_STATE);
});
it("detects Shift on direct, nativeEvent, or hardware modifier payloads", () => {
expect(isShiftPressEvent({ shiftKey: true })).toBe(true);
expect(isShiftPressEvent({ nativeEvent: { shiftKey: true } })).toBe(true);
expect(isShiftPressEvent({ shiftKey: false, nativeEvent: { shiftKey: false } })).toBe(false);
expect(isShiftPressEvent(null)).toBe(false);
// Native GestureResponderEvent omits shiftKey; falls back to hardware Shift state.
const nativeResponderEvent = { nativeEvent: { locationX: 12, locationY: 8 } };
expect(isShiftPressEvent(nativeResponderEvent, () => false)).toBe(false);
expect(isShiftPressEvent(nativeResponderEvent, () => true)).toBe(true);
});
});
@@ -0,0 +1,129 @@
import { isShiftKeyDown } from "@/keyboard";
export interface WorkspaceSelectionState {
active: boolean;
selectedKeys: ReadonlySet<string>;
anchorKey: string | null;
}
const EMPTY_KEYS: ReadonlySet<string> = new Set();
export const INITIAL_WORKSPACE_SELECTION_STATE: WorkspaceSelectionState = {
active: false,
selectedKeys: EMPTY_KEYS,
anchorKey: null,
};
export function enterWorkspaceSelection(workspaceKey: string): WorkspaceSelectionState {
return {
active: true,
selectedKeys: new Set([workspaceKey]),
anchorKey: workspaceKey,
};
}
export function toggleWorkspaceSelection(
state: WorkspaceSelectionState,
workspaceKey: string,
): WorkspaceSelectionState {
if (!state.active) {
return enterWorkspaceSelection(workspaceKey);
}
const next = new Set(state.selectedKeys);
if (!next.delete(workspaceKey)) {
next.add(workspaceKey);
}
return {
active: true,
selectedKeys: next,
anchorKey: workspaceKey,
};
}
export function selectWorkspaceRange(
state: WorkspaceSelectionState,
targetKey: string,
orderedVisibleKeys: readonly string[],
): WorkspaceSelectionState {
if (!state.active) {
return enterWorkspaceSelection(targetKey);
}
if (!state.anchorKey) {
const next = new Set(state.selectedKeys);
next.add(targetKey);
return { active: true, selectedKeys: next, anchorKey: targetKey };
}
const anchorIndex = orderedVisibleKeys.indexOf(state.anchorKey);
const targetIndex = orderedVisibleKeys.indexOf(targetKey);
if (anchorIndex < 0 || targetIndex < 0) {
const next = new Set(state.selectedKeys);
next.add(targetKey);
return { active: true, selectedKeys: next, anchorKey: targetKey };
}
const start = Math.min(anchorIndex, targetIndex);
const end = Math.max(anchorIndex, targetIndex);
const next = new Set(state.selectedKeys);
for (let index = start; index <= end; index += 1) {
const key = orderedVisibleKeys[index];
if (key !== undefined) {
next.add(key);
}
}
return {
active: true,
selectedKeys: next,
anchorKey: state.anchorKey,
};
}
export function reconcileWorkspaceSelection(
state: WorkspaceSelectionState,
availableKeys: ReadonlySet<string>,
): WorkspaceSelectionState {
if (!state.active) return state;
let changed = false;
const next = new Set<string>();
for (const key of state.selectedKeys) {
if (availableKeys.has(key)) {
next.add(key);
} else {
changed = true;
}
}
const nextAnchor = state.anchorKey && availableKeys.has(state.anchorKey) ? state.anchorKey : null;
if (!changed && nextAnchor === state.anchorKey) {
return state;
}
return {
active: true,
selectedKeys: changed ? next : state.selectedKeys,
anchorKey: nextAnchor,
};
}
export function exitWorkspaceSelection(): WorkspaceSelectionState {
return INITIAL_WORKSPACE_SELECTION_STATE;
}
export function isShiftPressEvent(
event: unknown,
isHardwareShiftDown: () => boolean = isShiftKeyDown,
): boolean {
if (typeof event === "object" && event !== null) {
if (Reflect.get(event, "shiftKey") === true) return true;
const nativeEvent = Reflect.get(event, "nativeEvent");
if (
typeof nativeEvent === "object" &&
nativeEvent !== null &&
Reflect.get(nativeEvent, "shiftKey") === true
) {
return true;
}
}
return isHardwareShiftDown();
}
@@ -0,0 +1,82 @@
import { create } from "zustand";
import {
enterWorkspaceSelection,
exitWorkspaceSelection,
INITIAL_WORKSPACE_SELECTION_STATE,
reconcileWorkspaceSelection,
selectWorkspaceRange,
toggleWorkspaceSelection,
type WorkspaceSelectionState,
} from "./selection-state";
type VisibleKeysReader = () => readonly string[];
let visibleKeysReader: VisibleKeysReader = () => [];
/**
* Registers a synchronous reader for the currently rendered sidebar workspace order so Shift+click
* range selection walks only rows on screen without causing re-renders when the order changes.
*/
export function registerSidebarVisibleWorkspaceKeysReader(reader: VisibleKeysReader): () => void {
visibleKeysReader = reader;
return () => {
if (visibleKeysReader === reader) {
visibleKeysReader = () => [];
}
};
}
interface SidebarSelectionStoreState extends WorkspaceSelectionState {
isArchiving: boolean;
enter: (workspaceKey: string) => void;
pressWorkspace: (workspaceKey: string, options: { shiftKey: boolean }) => void;
reconcile: (availableKeys: ReadonlySet<string>) => void;
setArchiving: (archiving: boolean) => void;
exit: () => void;
}
export const useSidebarSelectionStore = create<SidebarSelectionStoreState>((set) => ({
...INITIAL_WORKSPACE_SELECTION_STATE,
isArchiving: false,
enter: (workspaceKey) =>
set(() => ({
...enterWorkspaceSelection(workspaceKey),
isArchiving: false,
})),
pressWorkspace: (workspaceKey, { shiftKey }) =>
set((state) => {
if (state.isArchiving) return state;
const next = shiftKey
? selectWorkspaceRange(state, workspaceKey, visibleKeysReader())
: toggleWorkspaceSelection(state, workspaceKey);
return next === state ? state : { ...next };
}),
reconcile: (availableKeys) =>
set((state) => {
const next = reconcileWorkspaceSelection(state, availableKeys);
return next === state ? state : { ...next };
}),
setArchiving: (isArchiving) => set({ isArchiving }),
exit: () =>
set((state) =>
state.active || state.isArchiving
? { ...exitWorkspaceSelection(), isArchiving: false }
: state,
),
}));
export function useIsSidebarSelectionMode(): boolean {
return useSidebarSelectionStore((state) => state.active);
}
export function useIsWorkspaceBulkSelected(workspaceKey: string): boolean {
return useSidebarSelectionStore((state) => state.active && state.selectedKeys.has(workspaceKey));
}
export function useSidebarSelectionCount(): number {
return useSidebarSelectionStore((state) => (state.active ? state.selectedKeys.size : 0));
}
export function useSidebarSelectionArchiving(): boolean {
return useSidebarSelectionStore((state) => state.isArchiving);
}
@@ -0,0 +1,355 @@
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import React, { act, useCallback } from "react";
import { createRoot, type Root } from "react-dom/client";
import { I18nextProvider } from "react-i18next";
import { Text } from "react-native";
import { SafeAreaProvider } from "react-native-safe-area-context";
import { afterEach, describe, expect, it } from "vitest";
import { SidebarToastRegion } from "@/components/sidebar/sidebar-toast-region";
import { SidebarWorkspaceContextMenu } from "@/components/sidebar/sidebar-workspace-menu";
import { ToastProvider, useToast } from "@/contexts/toast-context";
import type { ToastApi } from "@/components/toast-host";
import type { SidebarWorkspaceEntry } from "@/hooks/use-sidebar-workspaces-list";
import { i18n } from "@/i18n/i18next";
import { dispatchTopOverlayKeyDown } from "@/keyboard";
import {
KeyboardActionDispatcherProvider,
useKeyboardActionDispatcher,
} from "@/keyboard/keyboard-action-dispatcher-context";
import { useKeyboardActionHandler } from "@/hooks/use-keyboard-action-handler";
import {
isShiftPressEvent,
registerSidebarVisibleWorkspaceKeysReader,
SidebarSelectionHost,
useIsSidebarSelectionMode,
useIsWorkspaceBulkSelected,
useSidebarSelectionStore,
} from "@/sidebar-selection";
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
let root: Root | null = null;
let container: HTMLDivElement | null = null;
let releaseVisibleKeys: (() => void) | null = null;
function makeEntry(id: string): SidebarWorkspaceEntry {
return {
workspaceKey: `srv:${id}`,
workspaceId: id,
serverId: "srv",
projectViewKey: "prj-view",
projectName: "Repo",
projectRootPath: "/repo",
workspaceDirectory: `/repo/${id}`,
workspaceDirectoryLabel: id,
projectKind: "git",
workspaceKind: "local_checkout",
name: id,
title: null,
currentBranch: id,
statusBucket: "done",
statusEnteredAt: null,
archivingAt: null,
diffStat: null,
prHint: null,
pinnedAt: null,
background: false,
labels: [],
scripts: [],
hasRunningScripts: false,
archiveHasUncommittedChanges: null,
archiveUnpushedCommitCount: null,
};
}
let capturedDispatcher: ReturnType<typeof useKeyboardActionDispatcher> | null = null;
let capturedSidebarToast: ToastApi | null = null;
let fallbackArchiveCount = 0;
function FallbackArchiveProbe() {
capturedDispatcher = useKeyboardActionDispatcher();
useKeyboardActionHandler({
handlerId: "test-global-workspace-archive-fallback",
actions: ["workspace.archive"],
enabled: true,
priority: 0,
handle: () => {
fallbackArchiveCount += 1;
return true;
},
});
return null;
}
function SidebarToastProbe() {
capturedSidebarToast = useToast();
return null;
}
const noop = () => {};
function SelectableRowProbe({ entry }: { entry: SidebarWorkspaceEntry }) {
const isSelectionMode = useIsSidebarSelectionMode();
const isBulkSelected = useIsWorkspaceBulkSelected(entry.workspaceKey);
const handlePress = useCallback(
(event: unknown) => {
const shiftKey = isShiftPressEvent(event);
if (isSelectionMode || shiftKey) {
useSidebarSelectionStore.getState().pressWorkspace(entry.workspaceKey, { shiftKey });
}
},
[entry.workspaceKey, isSelectionMode],
);
return (
<SidebarWorkspaceContextMenu
contextMenuOpen={false}
onContextMenuOpenChange={noop}
workspace={entry}
workspaceKey={entry.workspaceKey}
enabled={!isSelectionMode}
accessibilityRole={isSelectionMode ? "checkbox" : "button"}
aria-checked={isSelectionMode ? isBulkSelected : undefined}
highlightStyle={undefined}
onPress={handlePress}
testID={`sidebar-workspace-row-${entry.workspaceKey}`}
>
<Text>{entry.name}</Text>
</SidebarWorkspaceContextMenu>
);
}
function mountHost(entries: readonly SidebarWorkspaceEntry[]) {
const entriesByKey = new Map(entries.map((entry) => [entry.workspaceKey, entry]));
releaseVisibleKeys = registerSidebarVisibleWorkspaceKeysReader(() =>
entries.map((entry) => entry.workspaceKey),
);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
act(() => {
root?.render(
<QueryClientProvider client={queryClient}>
<I18nextProvider i18n={i18n}>
<SafeAreaProvider>
<KeyboardActionDispatcherProvider>
<FallbackArchiveProbe />
<ToastProvider>
<SidebarToastRegion active>
<SidebarToastProbe />
{entries.map((entry) => (
<SelectableRowProbe key={entry.workspaceKey} entry={entry} />
))}
<SidebarSelectionHost active workspaceEntriesByKey={entriesByKey} />
</SidebarToastRegion>
</ToastProvider>
</KeyboardActionDispatcherProvider>
</SafeAreaProvider>
</I18nextProvider>
</QueryClientProvider>,
);
});
}
afterEach(() => {
capturedDispatcher = null;
capturedSidebarToast = null;
fallbackArchiveCount = 0;
act(() => {
useSidebarSelectionStore.getState().exit();
});
releaseVisibleKeys?.();
releaseVisibleKeys = null;
act(() => root?.unmount());
container?.remove();
root = null;
container = null;
});
describe("SidebarSelectionHost", () => {
it("shows a persistent sidebar toast while selecting, updates without Shift, and exits via button or Escape", async () => {
mountHost([makeEntry("a"), makeEntry("b"), makeEntry("c")]);
expect(document.querySelector('[data-testid="workspace-selection-toast"]')).toBeNull();
// Enter select mode via Shift+click on "a", then plain-click "c" without Shift.
act(() => {
useSidebarSelectionStore.getState().pressWorkspace("srv:a", { shiftKey: true });
});
expect(document.querySelector('[data-testid="workspace-selection-count"]')?.textContent).toBe(
"1 selected",
);
act(() => {
useSidebarSelectionStore.getState().pressWorkspace("srv:c", { shiftKey: false });
});
expect(document.querySelector('[data-testid="workspace-selection-count"]')?.textContent).toBe(
"2 selected",
);
// Clicking the Exit button leaves select mode and fades the persistent toast out.
const exitButton = document.querySelector<HTMLElement>(
'[data-testid="workspace-selection-exit"]',
);
expect(exitButton).not.toBeNull();
act(() => {
exitButton?.click();
});
expect(useSidebarSelectionStore.getState().active).toBe(false);
await expect
.poll(() => document.querySelector('[data-testid="workspace-selection-toast"]'))
.toBeNull();
// Re-enter with Shift+click, then Shift+click "c" for a range of 3, and exit with Escape.
act(() => {
useSidebarSelectionStore.getState().pressWorkspace("srv:a", { shiftKey: true });
useSidebarSelectionStore.getState().pressWorkspace("srv:c", { shiftKey: true });
});
expect(document.querySelector('[data-testid="workspace-selection-count"]')?.textContent).toBe(
"3 selected",
);
let prevented = false;
act(() => {
const handled = dispatchTopOverlayKeyDown({
key: "Escape",
code: "Escape",
altKey: false,
ctrlKey: false,
metaKey: false,
shiftKey: false,
repeat: false,
preventDefault: () => {
prevented = true;
},
stopPropagation: () => {},
});
expect(handled).toBe(true);
});
expect(prevented).toBe(true);
expect(useSidebarSelectionStore.getState().active).toBe(false);
await expect
.poll(() => document.querySelector('[data-testid="workspace-selection-toast"]'))
.toBeNull();
});
it("consumes workspace.archive while in select mode even with zero rows selected or while archiving", () => {
mountHost([makeEntry("a"), makeEntry("b")]);
// Outside select mode, the global fallback receives workspace.archive.
act(() => {
expect(capturedDispatcher?.dispatch({ id: "workspace.archive", scope: "sidebar" })).toBe(
true,
);
});
expect(fallbackArchiveCount).toBe(1);
// Enter select mode then deselect the only row -> 0 selected.
act(() => {
useSidebarSelectionStore.getState().enter("srv:a");
useSidebarSelectionStore.getState().pressWorkspace("srv:a", { shiftKey: false });
});
expect(document.querySelector('[data-testid="workspace-selection-count"]')?.textContent).toBe(
"0 selected",
);
// The archive shortcut must be absorbed by select mode rather than archiving the open workspace.
act(() => {
expect(capturedDispatcher?.dispatch({ id: "workspace.archive", scope: "sidebar" })).toBe(
true,
);
});
expect(fallbackArchiveCount).toBe(1);
// Same while a worktree safety check is in progress (both archive shortcut and Escape stay owned).
act(() => {
useSidebarSelectionStore.getState().enter("srv:a");
useSidebarSelectionStore.getState().setArchiving(true);
});
act(() => {
expect(capturedDispatcher?.dispatch({ id: "workspace.archive", scope: "sidebar" })).toBe(
true,
);
expect(
dispatchTopOverlayKeyDown({
key: "Escape",
code: "Escape",
altKey: false,
ctrlKey: false,
metaKey: false,
shiftKey: false,
repeat: false,
preventDefault: () => {},
stopPropagation: () => {},
}),
).toBe(true);
});
expect(fallbackArchiveCount).toBe(1);
expect(useSidebarSelectionStore.getState().active).toBe(true);
});
it("keeps the selection bar visible when an Undo toast is already displayed in the sidebar", () => {
mountHost([makeEntry("a"), makeEntry("b")]);
let dismissUndo: (() => void) | undefined;
act(() => {
dismissUndo = capturedSidebarToast?.show("Workspace archived", {
durationMs: 6000,
testID: "workspace-archived-toast",
});
});
expect(document.querySelector('[data-testid="workspace-archived-toast"]')).not.toBeNull();
act(() => {
useSidebarSelectionStore.getState().enter("srv:a");
});
// Both the Undo toast and the selection bar (count, Archive, Exit) must remain visible.
expect(document.querySelector('[data-testid="workspace-archived-toast"]')).not.toBeNull();
expect(document.querySelector('[data-testid="workspace-selection-toast"]')).not.toBeNull();
expect(document.querySelector('[data-testid="workspace-selection-count"]')?.textContent).toBe(
"1 selected",
);
expect(document.querySelector('[data-testid="workspace-selection-archive"]')).not.toBeNull();
expect(document.querySelector('[data-testid="workspace-selection-exit"]')).not.toBeNull();
act(() => {
dismissUndo?.();
});
});
it("toggles focused workspace checkboxes when pressing Space in select mode", () => {
mountHost([makeEntry("a"), makeEntry("b")]);
act(() => {
useSidebarSelectionStore.getState().enter("srv:a");
});
const rowB = document.querySelector<HTMLElement>('[data-testid="sidebar-workspace-row-srv:b"]');
expect(rowB?.getAttribute("role")).toBe("checkbox");
expect(rowB?.getAttribute("aria-checked")).toBe("false");
act(() => {
rowB?.focus();
rowB?.dispatchEvent(
new KeyboardEvent("keydown", { key: " ", bubbles: true, cancelable: true }),
);
rowB?.dispatchEvent(
new KeyboardEvent("keydown", { key: " ", repeat: true, bubbles: true, cancelable: true }),
);
});
expect(rowB?.getAttribute("aria-checked")).toBe("true");
expect(document.querySelector('[data-testid="workspace-selection-count"]')?.textContent).toBe(
"2 selected",
);
act(() => {
rowB?.dispatchEvent(
new KeyboardEvent("keydown", { key: " ", bubbles: true, cancelable: true }),
);
});
expect(rowB?.getAttribute("aria-checked")).toBe("false");
expect(document.querySelector('[data-testid="workspace-selection-count"]')?.textContent).toBe(
"1 selected",
);
});
});
@@ -0,0 +1,157 @@
import { useCallback, useEffect, useMemo, useRef } from "react";
import {
useSidebarAppToast,
useSidebarPersistentToast,
} from "@/components/sidebar/sidebar-toast-region";
import type { ToastState } from "@/components/toast-host";
import { useToast } from "@/contexts/toast-context";
import { useKeyboardActionHandler } from "@/hooks/use-keyboard-action-handler";
import type { SidebarWorkspaceEntry } from "@/hooks/use-sidebar-workspaces-list";
import { useOverlayRegistration } from "@/keyboard";
import type { KeyboardActionId } from "@/keyboard/keyboard-action-dispatcher";
import { useActiveWorkspaceSelection } from "@/stores/navigation-active-workspace-store";
import { archiveSelectedWorkspaces, createDefaultBulkArchiveDeps } from "./archive-selected";
import {
useIsSidebarSelectionMode,
useSidebarSelectionArchiving,
useSidebarSelectionCount,
useSidebarSelectionStore,
} from "./selection-store";
import { WorkspaceSelectionToast } from "./workspace-selection-toast";
const SELECTION_TOAST_ID = -1;
const ESCAPE_OVERLAY_KEYS = ["Escape"] as const;
const WORKSPACE_ARCHIVE_ACTIONS: readonly KeyboardActionId[] = ["workspace.archive"];
/**
* Coordinates sidebar workspace select mode: reconciles removed workspaces, binds Escape and
* the archive shortcut, and keeps the persistent selection bar up in `SidebarToastRegion`.
*/
export function SidebarSelectionHost({
active,
workspaceEntriesByKey,
}: {
active: boolean;
workspaceEntriesByKey: ReadonlyMap<string, SidebarWorkspaceEntry>;
}): null {
const toast = useToast();
const appToast = useSidebarAppToast();
const activeWorkspaceSelection = useActiveWorkspaceSelection();
const selectionMode = useIsSidebarSelectionMode();
const selectedCount = useSidebarSelectionCount();
const isArchiving = useSidebarSelectionArchiving();
const entriesRef = useRef(workspaceEntriesByKey);
entriesRef.current = workspaceEntriesByKey;
const activeSelectionRef = useRef(activeWorkspaceSelection);
activeSelectionRef.current = activeWorkspaceSelection;
const archiveAttemptRef = useRef(0);
useEffect(() => {
if (!selectionMode) return;
useSidebarSelectionStore.getState().reconcile(new Set(workspaceEntriesByKey.keys()));
}, [selectionMode, workspaceEntriesByKey]);
useEffect(() => {
if (active) return;
const state = useSidebarSelectionStore.getState();
if (state.active && !state.isArchiving) {
state.exit();
}
}, [active]);
const handleExit = useCallback(() => {
const state = useSidebarSelectionStore.getState();
if (state.isArchiving) return;
state.exit();
}, []);
const handleArchiveSelected = useCallback(() => {
const store = useSidebarSelectionStore.getState();
if (!store.active || store.isArchiving || store.selectedKeys.size === 0) return;
const entries: SidebarWorkspaceEntry[] = [];
for (const key of store.selectedKeys) {
const entry = entriesRef.current.get(key);
if (entry && entry.archivingAt === null) {
entries.push(entry);
}
}
if (entries.length === 0) {
store.exit();
return;
}
const attemptId = archiveAttemptRef.current + 1;
archiveAttemptRef.current = attemptId;
store.setArchiving(true);
void archiveSelectedWorkspaces({
workspaces: entries,
toast,
fallbackErrorToast: appToast,
onArchiveStarted: () => {
useSidebarSelectionStore.getState().exit();
},
deps: createDefaultBulkArchiveDeps(() => activeSelectionRef.current),
}).finally(() => {
if (archiveAttemptRef.current !== attemptId) return;
const current = useSidebarSelectionStore.getState();
if (current.isArchiving) {
current.setArchiving(false);
}
});
}, [appToast, toast]);
useOverlayRegistration({
keys: ESCAPE_OVERLAY_KEYS,
// Keep Escape owned while select mode is active (including during worktree checks) so it
// never falls through to interrupt a running agent in the open workspace; any higher-layer
// confirmation dialog still receives Escape first.
active: selectionMode && active,
layer: 0,
manageFocus: false,
onKeyDown: (event) => {
if (event.key !== "Escape") return false;
event.preventDefault();
handleExit();
return true;
},
});
useKeyboardActionHandler({
handlerId: "sidebar-selection-archive",
actions: WORKSPACE_ARCHIVE_ACTIONS,
// Keep ownership of workspace.archive for the entire lifetime of select mode so pressing it
// at 0 selected or during a worktree check never falls through to archive the open workspace.
enabled: selectionMode && active,
priority: 10,
handle: () => {
handleArchiveSelected();
return true;
},
});
const persistentToast = useMemo<ToastState | null>(() => {
if (!selectionMode || !active) return null;
return {
id: SELECTION_TOAST_ID,
content: (
<WorkspaceSelectionToast
selectedCount={selectedCount}
isArchiving={isArchiving}
onArchive={handleArchiveSelected}
onExit={handleExit}
/>
),
nativeMessage: null,
variant: "default",
layout: "action",
durationMs: null,
testID: "workspace-selection-toast",
};
}, [active, handleArchiveSelected, handleExit, isArchiving, selectedCount, selectionMode]);
useSidebarPersistentToast(persistentToast);
return null;
}
@@ -0,0 +1,83 @@
import { X } from "lucide-react-native";
import { useTranslation } from "react-i18next";
import { Text, View } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { Button } from "@/components/ui/button";
import { CONTROL_HEIGHTS } from "@/components/ui/control-geometry";
import { DensityIcon } from "@/components/ui/density-icon";
import { ToolbarButton } from "@/components/ui/pane-content-toolbar";
import type { ShortcutKey } from "@/utils/format-shortcut";
const EXIT_SHORTCUT_CHORD: ShortcutKey[][] = [["Esc"]];
export function WorkspaceSelectionToast({
selectedCount,
isArchiving,
onArchive,
onExit,
}: {
selectedCount: number;
isArchiving: boolean;
onArchive: () => void;
onExit: () => void;
}) {
const { t } = useTranslation();
const exitLabel = t("sidebar.workspace.selection.exit");
return (
<View style={styles.row}>
<Text style={styles.message} numberOfLines={1} testID="workspace-selection-count">
{t("sidebar.workspace.selection.count", { count: selectedCount })}
</Text>
<View style={styles.actions}>
<Button
size="sm"
onPress={onArchive}
disabled={selectedCount === 0}
loading={isArchiving}
testID="workspace-selection-archive"
>
{t("sidebar.workspace.actions.archive")}
</Button>
<ToolbarButton
round
tooltipSide="top"
label={exitLabel}
shortcut={EXIT_SHORTCUT_CHORD}
onPress={onExit}
disabled={isArchiving}
style={styles.exitButton}
testID="workspace-selection-exit"
>
<DensityIcon icon={X} size="sm" color="foregroundMuted" />
</ToolbarButton>
</View>
</View>
);
}
const styles = StyleSheet.create((theme) => ({
row: {
flexDirection: "row",
flexWrap: "wrap",
alignItems: "center",
gap: theme.spacing[3],
},
message: {
flexShrink: 1,
color: theme.colors.foreground,
fontSize: theme.fontSize.base,
fontWeight: theme.fontWeight.normal,
},
actions: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[1],
},
// Matches the Archive button's sm pill height so the circular hover fill sits concentrically
// in the action toast's trailing corner.
exitButton: {
width: CONTROL_HEIGHTS.sm,
height: CONTROL_HEIGHTS.sm,
},
}));
@@ -1,7 +1,12 @@
export {
archiveWorkspaceWithUndo,
archiveWorkspacesWithUndo,
hasUndoableWorkspaceArchive,
undoLatestWorkspaceArchive,
type UndoableWorkspaceArchiveClient,
type UndoableWorkspaceArchiveEntryInput,
type WorkspaceArchiveBatchFailure,
type WorkspaceArchiveBatchResult,
} from "./internal/undo-window";
export { WorkspaceArchiveUndoShortcutHost } from "./internal/undo-shortcut-host";
export { supportsWorkspaceArchiveUndo } from "./internal/capability";
@@ -8,6 +8,7 @@ import { useSessionStore, type WorkspaceDescriptor } from "@/stores/session-stor
import { seedSessionHosts } from "@/test/seed-session";
import {
archiveWorkspaceWithUndo,
archiveWorkspacesWithUndo,
undoLatestWorkspaceArchive,
type UndoableWorkspaceArchiveClient,
} from "@/workspace/archive-undo";
@@ -82,6 +83,9 @@ function createToastHost() {
get shownTestID() {
return shown?.options?.testID ?? null;
},
get shownVariant() {
return shown?.options?.variant ?? null;
},
timeOut: () => shown?.dismiss(),
};
}
@@ -299,3 +303,166 @@ describe("archiveWorkspaceWithUndo", () => {
}).toEqual({ toast: null, undone: false, row: workspace("a") });
});
});
describe("archiveWorkspacesWithUndo", () => {
it("hides every workspace in the batch and undoes all of them together", async () => {
const host = createClient();
const toast = createToastHost();
const committed: string[] = [];
const batch = archiveWorkspacesWithUndo({
entries: [
{
client: host.client,
workspace: { serverId: SERVER_ID, workspaceId: "a" },
onArchiveCommitted: () => committed.push("a"),
},
{
client: host.client,
workspace: { serverId: SERVER_ID, workspaceId: "b" },
onArchiveCommitted: () => committed.push("b"),
},
],
toast: toast.api,
});
expect(storedWorkspace("a")).toBeUndefined();
expect(storedWorkspace("b")).toBeUndefined();
expect(toast.shownTestID).toBe("workspace-archived-toast");
expect(undoLatestWorkspaceArchive()).toBe(true);
expect({
a: storedWorkspace("a"),
b: storedWorkspace("b"),
undoA: host.undoRequested("a"),
undoB: host.undoRequested("b"),
toast: toast.shownTestID,
}).toEqual({
a: workspace("a"),
b: workspace("b"),
undoA: true,
undoB: true,
toast: null,
});
host.finishArchive("a", { canceled: true });
host.finishArchive("b", { canceled: true });
await expect(batch.then((result) => result.failures)).resolves.toEqual([]);
host.finishUndo("a");
host.finishUndo("b");
expect(committed).toEqual([]);
});
it("commits every workspace in the batch when the toast times out", async () => {
const host = createClient();
const toast = createToastHost();
const committed: string[] = [];
const batch = archiveWorkspacesWithUndo({
entries: [
{
client: host.client,
workspace: { serverId: SERVER_ID, workspaceId: "a" },
onArchiveCommitted: () => committed.push("a"),
},
{
client: host.client,
workspace: { serverId: SERVER_ID, workspaceId: "b" },
onArchiveCommitted: () => committed.push("b"),
},
],
toast: toast.api,
});
host.finishArchive("a");
host.finishArchive("b");
await expect(batch.then((result) => result.failures)).resolves.toEqual([]);
expect(committed).toEqual([]);
toast.timeOut();
expect(committed).toEqual(["a", "b"]);
});
it("restores only the failed workspace on partial failure and keeps undo open when surfacing the error", async () => {
const host = createClient();
const toast = createToastHost();
const committed: string[] = [];
const batch = archiveWorkspacesWithUndo({
entries: [
{
client: host.client,
workspace: { serverId: SERVER_ID, workspaceId: "a" },
onArchiveCommitted: () => committed.push("a"),
},
{
client: host.client,
workspace: { serverId: SERVER_ID, workspaceId: "b" },
onArchiveCommitted: () => committed.push("b"),
},
],
toast: toast.api,
});
host.finishArchive("a");
host.finishArchive("b", { error: "busy" });
const { failures, showPartialFailure } = await batch;
expect(failures).toHaveLength(1);
expect(failures[0]?.workspace.workspaceId).toBe("b");
expect(storedWorkspace("a")).toBeUndefined();
expect(storedWorkspace("b")).toEqual(workspace("b"));
// Updating the toast with the partial-failure error must not dismiss Undo or commit "a".
expect(showPartialFailure("busy")).toBe(true);
expect({
toast: toast.shownTestID,
variant: toast.shownVariant,
committed,
}).toEqual({
toast: "workspace-archived-toast",
variant: "error",
committed: [],
});
expect(undoLatestWorkspaceArchive()).toBe(true);
expect({ undoA: host.undoRequested("a"), undoB: host.undoRequested("b") }).toEqual({
undoA: true,
undoB: false,
});
expect(committed).toEqual([]);
});
it("commits surviving workspaces once a partial-failure undo toast times out", async () => {
const host = createClient();
const toast = createToastHost();
const committed: string[] = [];
const batch = archiveWorkspacesWithUndo({
entries: [
{
client: host.client,
workspace: { serverId: SERVER_ID, workspaceId: "a" },
onArchiveCommitted: () => committed.push("a"),
},
{
client: host.client,
workspace: { serverId: SERVER_ID, workspaceId: "b" },
onArchiveCommitted: () => committed.push("b"),
},
],
toast: toast.api,
});
host.finishArchive("a");
host.finishArchive("b", { error: "busy" });
const { showPartialFailure } = await batch;
expect(showPartialFailure("busy")).toBe(true);
expect(committed).toEqual([]);
toast.timeOut();
expect(committed).toEqual(["a"]);
expect(undoLatestWorkspaceArchive()).toBe(false);
});
});
@@ -17,18 +17,28 @@ export interface UndoableWorkspaceArchiveClient {
undoWorkspaceArchive: (workspaceId: string) => Promise<void>;
}
interface UndoWindowInput {
export interface UndoableWorkspaceArchiveEntryInput {
client: UndoableWorkspaceArchiveClient;
workspace: WorkspaceArchiveTarget;
toast: ToastApi;
hidden: WorkspaceDescriptor | null;
onArchiveCommitted: () => void;
}
interface UndoWindowEntry extends UndoableWorkspaceArchiveEntryInput {
hidden: WorkspaceDescriptor | null;
archived: boolean;
failed: boolean;
committed: boolean;
}
interface UndoWindowInput {
entries: UndoWindowEntry[];
toast: ToastApi;
}
let latest: UndoWindow | null = null;
/**
* One archive's chance to be undone. It opens when the row hides and closes when its toast
* One archive batch's chance to be undone. It opens when the row(s) hide and closes when its toast
* leaves the screen (timeout, replaced by another toast, or undo).
*
* - `open`: undo is offered.
@@ -37,40 +47,78 @@ let latest: UndoWindow | null = null;
*/
class UndoWindow {
phase: "open" | "closed" | "undone" = "open";
private archived = false;
private readonly dismissToast: DismissToast;
private dismissToast: DismissToast = () => {};
private toastToken: object | null = null;
constructor(private readonly input: UndoWindowInput) {
this.dismissToast = input.toast.show(<WorkspaceArchivedToast onUndo={this.undo} />, {
durationMs: WORKSPACE_ARCHIVE_UNDO_WINDOW_MS,
testID: "workspace-archived-toast",
onDismiss: this.close,
});
this.showToast({ variant: "default" });
}
/** The host finished the archive. It commits now if undo is no longer offered. */
archiveFinished(): void {
this.archived = true;
if (this.phase === "closed") this.commit();
private showToast(options: { message?: string; variant: "default" | "error" }): void {
const token = {};
this.toastToken = token;
const remainingCount = this.input.entries.filter((entry) => !entry.failed).length;
this.dismissToast = this.input.toast.show(
<WorkspaceArchivedToast
count={remainingCount}
message={options.message}
onUndo={this.undo}
/>,
{
variant: options.variant,
layout: "action",
durationMs: WORKSPACE_ARCHIVE_UNDO_WINDOW_MS,
testID: "workspace-archived-toast",
onDismiss: () => {
// Replacing our own toast in place (for example to surface a partial failure) must not
// close the undo window or purge surviving workspaces.
if (this.toastToken !== token) return;
this.close();
},
},
);
}
/** The archive failed on the host, so there is nothing left to undo. */
archiveFailed(): void {
this.close();
this.dismissToast();
/**
* Surfaces a partial-failure message on the active undo toast without dismissing Undo for the
* workspaces that did archive. Returns false once the window is closed, undone, or superseded.
*/
showPartialFailure(message: string): boolean {
if (this.phase !== "open" || latest !== this) return false;
this.showToast({ message, variant: "error" });
return true;
}
/** The host finished archiving this entry. It commits now if undo is no longer offered. */
entryFinished(entry: UndoWindowEntry): void {
entry.archived = true;
if (this.phase === "closed") this.commitEntry(entry);
}
/** The archive failed on the host. Dismisses the toast once every entry has failed. */
entryFailed(entry: UndoWindowEntry): void {
entry.failed = true;
if (this.input.entries.every((item) => item.failed)) {
this.close();
this.dismissToast();
}
}
readonly close = (): void => {
if (this.phase !== "open") return;
this.phase = "closed";
this.release();
if (this.archived) this.commit();
for (const entry of this.input.entries) {
if (entry.archived) this.commitEntry(entry);
}
};
/** Commits unless the workspace is back by now, for example restored from another client. */
private commit(): void {
if (isWorkspaceListed(this.input.workspace)) return;
this.input.onArchiveCommitted();
private commitEntry(entry: UndoWindowEntry): void {
if (entry.committed || entry.failed) return;
if (isWorkspaceListed(entry.workspace)) return;
entry.committed = true;
entry.onArchiveCommitted();
}
readonly undo = (): boolean => {
@@ -78,10 +126,19 @@ class UndoWindow {
this.phase = "undone";
this.release();
this.dismissToast();
void undoWorkspaceArchiveOptimistically(this.input).catch((error: unknown) => {
console.warn("[workspace-archive-undo] undo failed", error);
this.input.toast.error(i18n.t("sidebar.workspace.toasts.undoArchiveFailed"));
});
const undoable = this.input.entries.filter((entry) => !entry.failed);
void (async () => {
const results = await Promise.allSettled(
undoable.map((entry) => undoWorkspaceArchiveOptimistically(entry)),
);
const failed = results.filter(
(result): result is PromiseRejectedResult => result.status === "rejected",
);
if (failed.length > 0) {
console.warn("[workspace-archive-undo] undo failed", failed[0]?.reason);
this.input.toast.error(i18n.t("sidebar.workspace.toasts.undoArchiveFailed"));
}
})();
return true;
};
@@ -90,6 +147,75 @@ class UndoWindow {
}
}
export interface WorkspaceArchiveBatchFailure {
workspace: WorkspaceArchiveTarget;
error: unknown;
}
export interface WorkspaceArchiveBatchResult {
failures: WorkspaceArchiveBatchFailure[];
/**
* Updates this batch's live undo toast to show a partial-failure error while keeping Undo active
* for the workspaces that succeeded. Returns false if the undo window is no longer open.
*/
showPartialFailure: (message: string) => boolean;
}
/**
* Archives one or more workspaces together and offers one undo until the toast goes away.
*
* `onArchiveCommitted` runs per workspace once that archive both finished on the host and can no
* longer be undone, and only if the workspace is still gone then. Returns failures for any
* workspace whose archive failed while not undone; those rows are already restored.
*/
export async function archiveWorkspacesWithUndo(input: {
entries: readonly UndoableWorkspaceArchiveEntryInput[];
toast: ToastApi;
}): Promise<WorkspaceArchiveBatchResult> {
if (input.entries.length === 0) {
return { failures: [], showPartialFailure: () => false };
}
const started = input.entries.map((entry) => {
const archive = beginOptimisticWorkspaceArchive(entry);
const windowEntry: UndoWindowEntry = {
...entry,
hidden: archive.hidden,
archived: false,
failed: false,
committed: false,
};
return { windowEntry, done: archive.done };
});
const window = new UndoWindow({
entries: started.map((item) => item.windowEntry),
toast: input.toast,
});
latest = window;
const failures: WorkspaceArchiveBatchFailure[] = [];
await Promise.all(
started.map(async ({ windowEntry, done }) => {
let outcome: Awaited<typeof done>;
try {
outcome = await done;
} catch (error) {
if (window.phase === "undone") return;
window.entryFailed(windowEntry);
failures.push({ workspace: windowEntry.workspace, error });
return;
}
if (outcome === "archived") window.entryFinished(windowEntry);
}),
);
return {
failures,
showPartialFailure: (message) => window.showPartialFailure(message),
};
}
/**
* Archives a workspace and offers to undo it until the toast goes away.
*
@@ -104,19 +230,19 @@ export async function archiveWorkspaceWithUndo(input: {
toast: ToastApi;
onArchiveCommitted: () => void;
}): Promise<void> {
const archive = beginOptimisticWorkspaceArchive(input);
const window = new UndoWindow({ ...input, hidden: archive.hidden });
latest = window;
let outcome: Awaited<typeof archive.done>;
try {
outcome = await archive.done;
} catch (error) {
if (window.phase === "undone") return;
window.archiveFailed();
throw error;
const { failures } = await archiveWorkspacesWithUndo({
entries: [
{
client: input.client,
workspace: input.workspace,
onArchiveCommitted: input.onArchiveCommitted,
},
],
toast: input.toast,
});
if (failures[0]) {
throw failures[0].error;
}
if (outcome === "archived") window.archiveFinished();
}
/** Undoes the most recent archive while its toast is up. Returns false when there is none. */
@@ -6,17 +6,30 @@ import { Button } from "@/components/ui/button";
import { Shortcut } from "@/components/ui/shortcut";
import { useShortcutKeys } from "@/hooks/use-shortcut-keys";
export function WorkspaceArchivedToast({ onUndo }: { onUndo: () => void }) {
export function WorkspaceArchivedToast({
count = 1,
message: customMessage,
onUndo,
}: {
count?: number;
message?: string;
onUndo: () => void;
}) {
const { t } = useTranslation();
const undoKeys = useShortcutKeys("undo-archive-workspace");
const undoShortcut = useMemo(
() => (undoKeys ? <Shortcut chord={undoKeys} style={styles.shortcut} /> : null),
[undoKeys],
);
const message =
customMessage ??
(count === 1
? t("sidebar.workspace.toasts.archived")
: t("sidebar.workspace.toasts.archivedCount", { count }));
return (
<View style={styles.row}>
<Text style={styles.message}>{t("sidebar.workspace.toasts.archived")}</Text>
<Text style={styles.message}>{message}</Text>
<Button
size="sm"
onPress={onUndo}
@@ -34,7 +47,7 @@ const styles = StyleSheet.create((theme) => ({
flexDirection: "row",
flexWrap: "wrap",
alignItems: "center",
gap: theme.spacing[2],
gap: theme.spacing[3],
},
// Cancels the badge's own inset, which would otherwise add to the button's gap.
shortcut: {
@@ -44,6 +44,7 @@ export const EyeOff = StubIcon;
export const File = StubIcon;
export const FileText = StubIcon;
export const Folder = StubIcon;
export const FolderOpen = StubIcon;
export const FolderPlus = StubIcon;
export const FolderTree = StubIcon;
export const Gift = StubIcon;
@@ -107,6 +108,7 @@ export const SquareSlash = StubIcon;
export const SquareTerminal = StubIcon;
export const Star = StubIcon;
export const Sun = StubIcon;
export const Tag = StubIcon;
export const Terminal = StubIcon;
export const Trash2 = StubIcon;
export const TriangleAlert = StubIcon;
+5
View File
@@ -58,6 +58,11 @@
"types": "./dist/server/lifecycle.d.ts",
"source": "./src/server/lifecycle.ts",
"default": "./dist/server/lifecycle.js"
},
"./internal/windows-command": {
"types": "./dist/server/process-internal/windows-command.d.ts",
"source": "./src/server/process-internal/windows-command.ts",
"default": "./dist/server/process-internal/windows-command.js"
}
},
"publishConfig": {
+34 -1
View File
@@ -14,6 +14,7 @@ const entries = {
"./server/usage": "server",
"./server/acp": "server",
"./internal/lifecycle": "server",
"./internal/windows-command": "server",
"./client": "client",
"./client/host": "client",
"./client/ui": "client",
@@ -392,7 +393,7 @@ describe("lifecycle hook SDK types", () => {
it("infers payloads and replacement requests and requires async handlers and new names", () => {
expect(
typeErrors(`
import type { PluginServerContext, PluginHooks, PluginHookPayload, PluginHookResult } from "@getpaseo/plugin/server";
import type { PluginServerContext, PluginHooks, PluginHookPayload, PluginHookResult, PluginLaunchWrap } from "@getpaseo/plugin/server";
import type { AgentTimelineItem } from "@getpaseo/protocol/agent-types";
export default function contribute(server: PluginServerContext) {
server.addHook("worktree.create.before", async ({ request }) => {
@@ -427,6 +428,38 @@ describe("lifecycle hook SDK types", () => {
const { metadata, ...withoutMetadata } = request;
return withoutMetadata;
});
server.addHook("agent.create.before", async ({ request }) => {
const workspace: string | null = request.workspaceId;
// @ts-expect-error The agent's workspace is read-only.
request.workspaceId = "wks_other";
});
// Results built before workspaceId existed still typecheck; the daemon keeps the id.
server.addHook("agent.create.before", async ({ request }) => ({ config: request.config, env: request.env }));
server.before("agent.create", ({ request }) => ({ config: request.config, env: request.env }));
server.addHook("terminal.create.before", async ({ request }) => {
const source: "client" | "agent" | "script" | "worktree" = request.source;
const input: string | null = request.input;
const program: string | null = request.command;
// @ts-expect-error The terminal's workspace is read-only.
request.workspaceId = "wks_other";
// @ts-expect-error The terminal's program is read-only; return a wrap instead.
request.command = "/usr/bin/other";
const wrap: PluginLaunchWrap = ["/usr/bin/sandbox", "--workspace", request.workspaceId];
return { ...request, env: { A: "1" }, wrap };
});
server.addHook("command.run.before", async ({ request }) => {
const workspace: string | null = request.workspaceId;
const purpose: "setup" | "teardown" = request.purpose;
// @ts-expect-error A command's purpose is read-only.
request.purpose = "setup";
// @ts-expect-error The configured command is read-only; return a wrap instead.
request.command = "wrapper " + request.command;
return { ...request, wrap: ["/usr/bin/sandbox"] };
});
server.addHook("agent.open.before", async ({ request }) => ({
...request,
wrap: ["/usr/bin/sandbox", "--workspace", request.workspaceId ?? "none"],
}));
server.addHook("agent.turn.after", async (event, { paseo, signal }) => {
const { agent, outcome } = event;
const kind: "completed" | "failed" | "canceled" = outcome.kind;
@@ -86,6 +86,8 @@ export async function createAcpProviderConnection(
emit: () => undefined,
});
const supportedCapabilities: ProviderCapability[] = [...ADAPTER_CAPABILITIES];
// A connector stream has no process of its own to wrap.
if (options.command) supportedCapabilities.push("session.launch_wrap");
if (probe.agentCapabilities.promptCapabilities?.image) {
supportedCapabilities.push("prompt.image");
}
@@ -333,6 +335,7 @@ async function openSession(
boundarySessionId: input.sessionId,
cwd: input.config.cwd,
env: input.config.env,
wrap: input.config.wrap,
emit: state.emit,
onRetired: () => retireSession(state, input.sessionId),
});
@@ -375,6 +378,7 @@ interface StartRuntimeOptions {
boundarySessionId: string;
cwd?: string;
env: Readonly<Record<string, string>>;
wrap?: readonly [string, ...string[]];
emit(event: ProviderEvent): void;
onRetired?: () => void;
}
@@ -498,6 +502,7 @@ class AcpRuntime {
env: process.env,
};
child = spawnProcess(launch.command, launch.args, {
wrap: options.wrap,
cwd: options.cwd,
env: { ...launch.env, ...options.env },
stdio: "pipe",
@@ -511,6 +516,7 @@ class AcpRuntime {
>[1];
stream = ndJsonStream(output, input);
} else {
if (options.wrap) throw new Error("An ACP connector cannot run behind a launch wrap");
const owned = ownConnectorStream(await options.options.connector());
stream = owned.stream;
closeConnector = owned.close;
+188 -3
View File
@@ -1,3 +1,5 @@
import type { ChildProcess } from "node:child_process";
import diagnosticsChannel from "node:diagnostics_channel";
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
@@ -6166,7 +6168,6 @@ describe("deferTurnOnRunningTools", () => {
);
const childPid = Number((await readFile(pidFile, "utf8")).trim());
const startedAt = Date.now();
await Promise.all([
connection.send({
type: "session.interrupt",
@@ -6188,8 +6189,8 @@ describe("deferTurnOnRunningTools", () => {
(event) => event.type === "request.completed" && event.requestId === "int-2",
);
// Both interrupts waited for the 250ms SIGTERM exit, and process is now dead.
expect(Date.now() - startedAt).toBeGreaterThanOrEqual(200);
// Both interrupts waited for the process to exit. On POSIX it lives 250ms past SIGTERM, so an
// interrupt that returned early would find it alive; Windows ends it at once.
expect(() => process.kill(childPid, 0)).toThrow();
// Canceled turn and session.closed were each emitted exactly once.
@@ -7125,3 +7126,187 @@ describe("ACP tool call rows", () => {
}
});
});
describe("runAcpProvider launch wrap", () => {
async function wrapFixture(): Promise<{
agent: string;
launchLog: string;
/** The wrap that runs the recording launcher as Node, tagged so the agent can tell. */
wrap: (tag: string) => [string, ...string[]];
launches: () => Promise<Array<{ argv: string[]; token: string | null }>>;
agentStarts: () => Promise<string[]>;
}> {
const directory = await mkdtemp(path.join(tmpdir(), "paseo-acp-wrap-"));
temporaryDirectories.push(directory);
const launchLog = path.join(directory, "launches.jsonl");
const agentLog = path.join(directory, "agent.log");
const launcher = path.join(directory, "launcher.cjs");
// Consumes two arguments of its own (log path, tag), records what it saw, then runs the rest.
await writeFile(
launcher,
`const { appendFileSync } = require("node:fs");
const { spawn } = require("node:child_process");
const [log, tag, command, ...args] = process.argv.slice(2);
appendFileSync(log, JSON.stringify({ argv: process.argv.slice(2), token: process.env.SESSION_TOKEN ?? null }) + "\\n");
const child = spawn(command, args, { stdio: "inherit", env: { ...process.env, WRAPPED_BY: tag } });
process.on("SIGTERM", () => child.kill("SIGTERM"));
child.on("exit", (code) => process.exit(code ?? 1));
`,
"utf8",
);
const agent = path.join(directory, "agent.cjs");
await writeFile(
agent,
`const { appendFileSync } = require("node:fs");
const record = (event) => appendFileSync(${JSON.stringify(agentLog)}, event + ":" + (process.env.WRAPPED_BY ?? "bare") + "\\n");
const readline = require("node:readline");
const lines = readline.createInterface({ input: process.stdin });
const send = (message) => process.stdout.write(JSON.stringify(message) + "\\n");
lines.on("line", (line) => {
const message = JSON.parse(line);
if (message.method === "initialize") { record("init"); send({ jsonrpc: "2.0", id: message.id, result: { protocolVersion: message.params.protocolVersion, agentCapabilities: {} } }); }
else if (message.method === "session/new") { record("new"); send({ jsonrpc: "2.0", id: message.id, result: { sessionId: "native-" + Math.random(), modes: null, configOptions: [] } }); }
});`,
"utf8",
);
const readLines = async (file: string) =>
(await readFile(file, "utf8").catch(() => "")).split("\n").filter(Boolean);
return {
agent,
launchLog,
wrap: (tag) => [process.execPath, launcher, launchLog, tag],
launches: async () => (await readLines(launchLog)).map((line) => JSON.parse(line)),
agentStarts: async () => await readLines(agentLog),
};
}
function wrappedOpen(
sessionId: string,
wrap: readonly [string, ...string[]] | undefined,
): Extract<ProviderInput, { type: "session.open" }> {
const input = openInput();
return {
...input,
requestId: `open-${sessionId}`,
sessionId,
config: { ...input.config, env: { SESSION_TOKEN: sessionId }, ...(wrap ? { wrap } : {}) },
};
}
async function connectWrapped(command: readonly [string, ...string[]]) {
const registration = runAcpProvider({ id: "wrap-acp", label: "Wrap ACP", command });
expect(registration.launchWrap).toBe(true);
const connection = await registration.connect({
versions: [1],
capabilities: ["prompt.message", "session.launch_wrap"],
});
const events: ProviderEvent[] = [];
connection.onEvent((event) => events.push(event));
return { connection, events };
}
it("spawns the session as [...wrap, command, ...args] with the session env", async () => {
const fixture = await wrapFixture();
const { launchLog } = fixture;
const { connection, events } = await connectWrapped([process.execPath, fixture.agent]);
expect(connection.capabilities).toContain("session.launch_wrap");
try {
await connection.send(wrappedOpen("one", fixture.wrap("sandbox")));
await waitForEvent(events, (event) => event.type === "session.ready");
expect(await fixture.launches()).toEqual([
{ argv: [launchLog, "sandbox", process.execPath, fixture.agent], token: "one" },
]);
expect(await fixture.agentStarts()).toEqual(["init:bare", "init:sandbox", "new:sandbox"]);
} finally {
await connection.close();
}
});
it("passes wrap and command arguments that contain spaces as single argv elements", async () => {
const fixture = await wrapFixture();
const { launchLog } = fixture;
const { connection, events } = await connectWrapped([
process.execPath,
fixture.agent,
"--profile name with spaces",
]);
try {
await connection.send(wrappedOpen("one", fixture.wrap("tag with spaces")));
await waitForEvent(events, (event) => event.type === "session.ready");
expect((await fixture.launches())[0]?.argv).toEqual([
launchLog,
"tag with spaces",
process.execPath,
fixture.agent,
"--profile name with spaces",
]);
} finally {
await connection.close();
}
});
it("wraps only the session that selected a wrap on a shared connection", async () => {
const fixture = await wrapFixture();
const { launchLog } = fixture;
const { connection, events } = await connectWrapped([process.execPath, fixture.agent]);
try {
await connection.send(wrappedOpen("wrapped", fixture.wrap("sandbox")));
await connection.send(wrappedOpen("bare", undefined));
await waitForEvent(
events,
(event) => event.type === "session.ready" && event.sessionId === "wrapped",
);
await waitForEvent(
events,
(event) => event.type === "session.ready" && event.sessionId === "bare",
);
expect(await fixture.launches()).toEqual([
{ argv: [launchLog, "sandbox", process.execPath, fixture.agent], token: "wrapped" },
]);
expect(
(await fixture.agentStarts()).filter((line) => line.startsWith("new:")).sort(),
).toEqual(["new:bare", "new:sandbox"]);
} finally {
await connection.close();
}
});
it("fails the open when the launcher is missing and never starts the bare command", async () => {
const fixture = await wrapFixture();
const missing = path.join(path.dirname(fixture.agent), "missing-launcher");
const { connection, events } = await connectWrapped([process.execPath, fixture.agent]);
// Node publishes every spawn attempt, a failed one included, before it fills in the fields.
const spawned: ChildProcess[] = [];
const onSpawn = (message: unknown) =>
spawned.push((message as { process: ChildProcess }).process);
diagnosticsChannel.subscribe("child_process", onSpawn);
try {
await connection.send(wrappedOpen("one", [missing, "--profile", "a b"]));
expect(await waitForEvent(events, (event) => event.type === "request.failed")).toMatchObject({
requestId: "open-one",
error: { message: expect.stringMatching(/ENOENT/u) },
});
expect(spawned.map((child) => child.spawnargs)).toEqual([
[missing, "--profile", "a b", process.execPath, fixture.agent],
]);
// The only start of the agent is the connection's capability probe, before the open.
expect(await fixture.agentStarts()).toEqual(["init:bare"]);
expect(events.some((event) => event.type === "session.opened")).toBe(false);
} finally {
diagnosticsChannel.unsubscribe("child_process", onSpawn);
await connection.close();
}
});
it("does not offer launch wrap through a connector", async () => {
const { connector } = connectorHarness();
const registration = runAcpProvider({ id: "connector-acp", label: "Connector", connector });
expect(registration).not.toHaveProperty("launchWrap");
const connection = await registration.connect({
versions: [1],
capabilities: ["prompt.message", "session.launch_wrap"],
});
expect(connection.capabilities).not.toContain("session.launch_wrap");
await connection.close();
});
});
+2
View File
@@ -181,6 +181,8 @@ export function runAcpProvider(options: RunAcpProviderOptions): ProviderRegistra
description: options.description,
icon: options.icon,
command: options.command,
// Each command-based session spawns its own process, so it can run behind that session's wrap.
...(hasCommand ? { launchWrap: true } : {}),
connect(request) {
return createAcpProviderConnection(options, request);
},
+4
View File
@@ -23,6 +23,9 @@ export type {
PluginHookWorkspace,
PluginHookWorktree,
PluginWorktreeCreateRequest,
PluginLaunchWrap,
PluginTerminalCreateRequest,
PluginCommandRunRequest,
PluginHookAgent,
PluginSessionOpenRequest,
PluginTurnOutcome,
@@ -32,6 +35,7 @@ export type {
} from "./lifecycle.js";
export { spawnProcess, execCommand, terminateProcess } from "./process.js";
export type { SpawnProcessOptions } from "./process.js";
export { defineAgentTool } from "./agent-tools.js";
export type { AgentToolDefinition, AgentToolResult, AgentToolContext } from "./agent-tools.js";
+63 -2
View File
@@ -68,6 +68,49 @@ export type PluginWorktreeCreateRequest = {
}
);
/**
* A launcher Paseo starts a process behind: the process runs as `[...wrap, command, ...args]`.
* The executable is an absolute path on the daemon host. Each element is one argument; no shell
* parses them, except that Windows runs a `.cmd` or `.bat` executable through cmd.exe. A later
* hook may omit the wrap or return the same one; a different wrap fails the operation.
*/
export type PluginLaunchWrap = readonly [executable: string, ...args: string[]];
/** A terminal Paseo is about to create in a workspace. */
export interface PluginTerminalCreateRequest {
readonly workspaceId: string;
readonly cwd: string;
/**
* `agent`: an agent's Paseo tool. `script`: a `paseo.json` script or service. `worktree`: a
* `paseo.json` worktree terminal. `client`: everything else (the app, CLI, SDK, plugins).
*/
readonly source: "client" | "agent" | "script" | "worktree";
readonly name: string | null;
/** The program the terminal starts, or `null` for the user's default shell. */
readonly command: string | null;
readonly args: readonly string[];
/** What Paseo types into the shell once it starts: the command of a script or worktree terminal. */
readonly input: string | null;
/** Environment overrides for the terminal; excludes the daemon's inherited environment. */
env: Record<string, string>;
/** Start the terminal as `[...wrap, command, ...args]`; with no `command`, the default shell. */
wrap?: PluginLaunchWrap;
}
/** A `paseo.json` worktree setup or teardown command Paseo is about to run. */
export interface PluginCommandRunRequest {
/** Null when a worktree is archived by path and no workspace record remains. */
readonly workspaceId: string | null;
readonly cwd: string;
readonly purpose: "setup" | "teardown";
/** The command as written in `paseo.json`. Paseo runs it through a shell. */
readonly command: string;
/** Environment overrides for the command; excludes the daemon's inherited environment. */
env: Record<string, string>;
/** Start the command's shell as `[...wrap, shell, ...shellArgs]`. */
wrap?: PluginLaunchWrap;
}
export interface PluginHookAgent {
id: string;
workspaceId: string | null;
@@ -98,6 +141,12 @@ export interface PluginSessionOpenRequest {
tools: AgentToolDefinition[];
env: Record<string, string>;
mcpServers: NonNullable<AgentSessionConfig["mcpServers"]>;
/**
* Start the provider's harness as `[...wrap, command, ...args]`. Only a provider whose snapshot
* entry has `launchWrap: true` applies it; any other provider fails the open. Not saved on the
* agent.
*/
wrap?: PluginLaunchWrap;
}
export type PluginTurnOutcome =
@@ -138,18 +187,28 @@ export interface PluginHookRequests {
env?: Record<string, string>;
/** Stored on the new agent. Always present in the payload; return it changed to change it. */
metadata?: Record<string, JsonValue>;
/** The workspace the agent is created in, which `config.cwd` alone does not identify. */
readonly workspaceId: string | null;
};
"agent.open.before": PluginSessionOpenRequest;
"workspace.create.before": Omit<WorkspaceCreateRequest, "type" | "requestId">;
"terminal.create.before": PluginTerminalCreateRequest;
"command.run.before": PluginCommandRunRequest;
}
/** What a hook may return. An omitted `metadata` stays as it was. */
type PluginHookRequestResults = Omit<PluginHookRequests, "agent.open.before"> & {
/** What a hook may return. An omitted `metadata` or `workspaceId` stays as it was. */
type PluginHookRequestResults = Omit<
PluginHookRequests,
"agent.open.before" | "agent.create.before"
> & {
// Read-only fields added after the first SDK stay optional in a result; omitted means unchanged.
"agent.open.before": Omit<PluginSessionOpenRequest, "metadata" | "background"> & {
readonly background?: boolean;
metadata?: Readonly<Record<string, JsonValue>>;
};
"agent.create.before": Omit<PluginHookRequests["agent.create.before"], "workspaceId"> & {
readonly workspaceId?: string | null;
};
};
export type PluginHooks = {
@@ -217,6 +276,8 @@ export const pluginHookRegistry = {
"agent.turn.after": { waits: false },
"agent.permission.before": { waits: false },
"agent.permission.after": { waits: false },
"terminal.create.before": { waits: true },
"command.run.before": { waits: true },
} as const satisfies Record<keyof PluginHooks, { waits: boolean }>;
// COMPAT(pluginHookNames): added in v0.14, remove after 2027-04-30
@@ -1,117 +1,92 @@
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { afterEach, describe, expect, test } from "vitest";
import { quoteWindowsArgument, quoteWindowsCommand } from "./windows-command.js";
import { findWindowsCommand, quoteWindowsCommand, windowsCommandLine } from "./windows-command.js";
const program = { commandScript: false } as const;
const script = { commandScript: true } as const;
describe("quoteWindowsCommand", () => {
const originalPlatform = process.platform;
function setPlatform(value: string) {
Object.defineProperty(process, "platform", { value, writable: true });
}
afterEach(() => {
setPlatform(originalPlatform);
});
test("quotes a Windows path with spaces", () => {
setPlatform("win32");
test("quotes a path with spaces and keeps cmd.exe syntax in it as text", () => {
expect(quoteWindowsCommand("C:\\Program Files\\Anthropic\\claude.exe")).toBe(
'"C:\\Program Files\\Anthropic\\claude.exe"',
);
});
test("does not double-quote an already-quoted path", () => {
setPlatform("win32");
expect(quoteWindowsCommand('"C:\\Program Files\\Anthropic\\claude.exe"')).toBe(
'"C:\\Program Files\\Anthropic\\claude.exe"',
expect(quoteWindowsCommand("C:\\Program Files (x86)\\Tool & Co\\run.cmd")).toBe(
'"C:\\Program Files (x86)\\Tool & Co\\run.cmd"',
);
});
test("returns the command unchanged when there are no spaces", () => {
setPlatform("win32");
test("leaves a plain or already quoted path as given", () => {
expect(quoteWindowsCommand("C:\\nvm4w\\nodejs\\codex")).toBe("C:\\nvm4w\\nodejs\\codex");
});
test("escapes ampersands", () => {
setPlatform("win32");
expect(quoteWindowsCommand("feature&bugfix")).toBe("feature^&bugfix");
});
test("escapes pipes", () => {
setPlatform("win32");
expect(quoteWindowsCommand("feature|bugfix")).toBe("feature^|bugfix");
});
test("does not double percent signs", () => {
setPlatform("win32");
// cmd.exe only collapses %% → % inside batch files; on the command line
// it stays literal, which corrupts git --format atoms etc.
expect(quoteWindowsCommand("100%")).toBe("100%");
});
test("preserves git --format atoms verbatim", () => {
setPlatform("win32");
expect(quoteWindowsCommand("--format=%(refname)%09%(committerdate:unix)")).toBe(
"--format=%^(refname^)%09%^(committerdate:unix^)",
);
});
test("escapes carets", () => {
setPlatform("win32");
expect(quoteWindowsCommand("feature^bugfix")).toBe("feature^^bugfix");
});
test("escapes multiple metacharacters", () => {
setPlatform("win32");
expect(quoteWindowsCommand("build&(test|deploy)!<output>")).toBe(
"build^&^(test^|deploy^)^!^<output^>",
);
});
test("quotes commands with spaces after escaping metacharacters", () => {
setPlatform("win32");
expect(quoteWindowsCommand("C:\\Program Files\\My Tool&Stuff\\run 100%.cmd")).toBe(
'"C:\\Program Files\\My Tool^&Stuff\\run 100%.cmd"',
);
});
test("returns the command unchanged on non-Windows platforms", () => {
setPlatform("darwin");
expect(quoteWindowsCommand("/usr/local/bin/claude code")).toBe("/usr/local/bin/claude code");
expect(quoteWindowsCommand('"C:\\Program Files\\x.exe"')).toBe('"C:\\Program Files\\x.exe"');
});
});
describe("quoteWindowsArgument", () => {
const originalPlatform = process.platform;
function setPlatform(value: string) {
Object.defineProperty(process, "platform", { value, writable: true });
}
afterEach(() => {
setPlatform(originalPlatform);
});
test("quotes a Windows argument with spaces", () => {
setPlatform("win32");
expect(quoteWindowsArgument("C:\\Program Files\\Anthropic\\cli.js")).toBe(
'"C:\\Program Files\\Anthropic\\cli.js"',
describe("windowsCommandLine", () => {
test("passes an argument without a cmd.exe metacharacter as given", () => {
expect(windowsCommandLine("echo", ["hello", "--flag", "feature/x", "C:\\dir"], program)).toBe(
'"echo hello --flag feature/x C:\\dir"',
);
});
test("does not double-quote an already-quoted argument", () => {
setPlatform("win32");
expect(quoteWindowsArgument('"C:\\Program Files\\Anthropic\\cli.js"')).toBe(
'"C:\\Program Files\\Anthropic\\cli.js"',
test("quotes and caret-escapes every other argument once, the qntm way", () => {
expect(windowsCommandLine("node", ["feature&bugfix", "work profile", ""], program)).toBe(
'"node ^"feature^&bugfix^" ^"work^ profile^" ^"^""',
);
// A caret before each `%` keeps cmd.exe from reading a variable name, inside the quotes too.
expect(windowsCommandLine("node", ["%PATH%", "100% of %PATH%"], program)).toBe(
'"node ^"^%PATH^%^" ^"100^%^ of^ ^%PATH^%^""',
);
// Backslashes before the closing quote double, as the program's argv parser expects.
expect(windowsCommandLine("node", ["C:\\path with space\\"], program)).toBe(
'"node ^"C:\\path^ with^ space\\\\^""',
);
});
test("returns the argument unchanged when there are no spaces", () => {
setPlatform("win32");
expect(quoteWindowsArgument("--version")).toBe("--version");
test("quotes =, comma and semicolon, where a batch script splits its arguments", () => {
expect(windowsCommandLine("run.cmd", ["--profile=restricted", "a,b;c"], script)).toBe(
'"run.cmd ^"--profile=restricted^" ^"a^,b^;c^""',
);
});
test("returns the argument unchanged on non-Windows platforms", () => {
setPlatform("darwin");
expect(quoteWindowsArgument("/usr/local/bin/claude code")).toBe("/usr/local/bin/claude code");
test("escapes an argument with a quote twice for a batch script, which reads it again", () => {
expect(windowsCommandLine("node", ['say "hi"'], program)).toBe('"node ^"say^ \\^"hi\\^"^""');
expect(windowsCommandLine("run.cmd", ['say "hi"', "a & b"], script)).toBe(
'"run.cmd ^^^"say^^^ \\^^^"hi\\^^^"^^^" ^"a^ ^&^ b^""',
);
});
test("quotes the command path at the start of the line", () => {
expect(windowsCommandLine("C:\\Program Files (x86)\\run.cmd", ["acp"], script)).toBe(
'""C:\\Program Files (x86)\\run.cmd" acp"',
);
});
test("refuses a line break, which ends a cmd.exe command whatever the quoting", () => {
for (const argument of ["line one\nline two", "line one\r\n& calc"]) {
expect(() => windowsCommandLine("run.cmd", ["--", argument], script)).toThrow(
"cmd.exe cannot pass an argument with a line break to run.cmd",
);
}
});
});
describe("findWindowsCommand", () => {
const roots: string[] = [];
afterEach(async () => {
await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));
});
test("finds a bare name on PATH with each PATHEXT extension, whatever the env key case", async () => {
const empty = await mkdtemp(path.join(os.tmpdir(), "windows-command-empty-"));
const tools = await mkdtemp(path.join(os.tmpdir(), "windows-command-tools-"));
roots.push(empty, tools);
await writeFile(path.join(tools, "agent.CMD"), "");
const env = { Path: `${empty};${tools}`, PathExt: ".EXE;.CMD" };
expect(findWindowsCommand("agent", env)).toBe(path.join(tools, "agent.CMD"));
expect(findWindowsCommand("echo", env)).toBeUndefined();
expect(findWindowsCommand("agent.cmd", env)).toBeUndefined();
expect(findWindowsCommand(path.join(tools, "agent"), env)).toBeUndefined();
});
});
@@ -1,46 +1,100 @@
import { extname } from "node:path";
import { statSync } from "node:fs";
import { extname, join } from "node:path";
export function isWindowsCommandScript(executablePath: string): boolean {
/**
* How Paseo starts a program through cmd.exe on Windows: `cmd.exe /d /s /c "<line>"`, with the line
* passed verbatim. The SDK process functions and the daemon's terminals share this one dialect.
*/
export function isWindowsCommandScript(
executablePath: string,
platform: NodeJS.Platform = process.platform,
): boolean {
const extension = extname(executablePath).toLowerCase();
return process.platform === "win32" && (extension === ".cmd" || extension === ".bat");
}
function escapeWindowsCmdValue(value: string): string {
if (process.platform !== "win32") return value;
const isQuoted = value.startsWith('"') && value.endsWith('"');
const unquoted = isQuoted ? value.slice(1, -1) : value;
// Do NOT double `%` here. cmd.exe only collapses `%%` → `%` inside batch
// files; on the command line / `cmd /c "..."` `%%` stays literal, which
// breaks args like git's `--format=%(refname)` (git treats `%%` as the
// escape for a literal `%`, so the format atoms become literals).
const escaped = unquoted.replace(/([&|^<>()!])/g, "^$1");
if (isQuoted || /[\s"]/u.test(unquoted)) {
const quoted = escaped
.replace(/(\\*)"/g, (_match, slashes: string) => `${slashes}${slashes}\\"`)
.replace(/\\+$/u, (slashes) => `${slashes}${slashes}`);
return `"${quoted}"`;
}
return escaped;
return platform === "win32" && (extension === ".cmd" || extension === ".bat");
}
/**
* When spawning with `shell: true` on Windows, the command is passed to
* `cmd.exe /d /s /c "command args"`. The `/s` strips outer quotes, so a
* command path with spaces (e.g. `C:\Program Files\...`) is split at the
* space. Wrapping it in quotes produces the correct `"C:\Program Files\..." args`.
* Find a bare command name the way cmd.exe would on `PATH`, trying each `PATHEXT` extension. The
* current directory is not searched. Returns undefined for a name with a path or an extension, and
* for a name that is not on `PATH`, such as a cmd.exe builtin.
*/
export function findWindowsCommand(name: string, env: NodeJS.ProcessEnv): string | undefined {
if (name.includes("/") || name.includes("\\") || extname(name)) return undefined;
const extensions = (readEnv(env, "PATHEXT") ?? ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean);
for (const directory of (readEnv(env, "PATH") ?? "").split(";").filter(Boolean)) {
for (const extension of extensions) {
const candidate = join(directory, name + extension);
if (statSync(candidate, { throwIfNoEntry: false })?.isFile()) return candidate;
}
}
return undefined;
}
/** The cmd.exe that runs a command line: the child's `ComSpec`, else the daemon's. */
export function windowsCommandShell(env: NodeJS.ProcessEnv): string {
return readEnv(env, "ComSpec") ?? readEnv(process.env, "ComSpec") ?? "cmd.exe";
}
// Windows environment names ignore case, and a copied env object keeps whatever case it had.
function readEnv(env: NodeJS.ProcessEnv, name: string): string | undefined {
const key = Object.keys(env).find((candidate) => candidate.toLowerCase() === name.toLowerCase());
return key === undefined ? undefined : env[key] || undefined;
}
// The cmd.exe metacharacters, as cross-spawn's `lib/util/escape.js` lists them.
const CMD_METACHARACTERS = /([()\][%!^"`<>&|;, *?])/g;
// A batch script also splits its arguments at `=` and tab.
const NEEDS_ESCAPE = /[()\][%!^"`<>&|;, *?=\t]/u;
/**
* Escape one argument for a `cmd.exe /c` line by the qntm algorithm (https://qntm.org/cmd), the
* one cross-spawn's `lib/util/escape.js` implements: quote it for the program's own argv parser,
* then put a `^` before every cmd.exe metacharacter, the added quotes included. cmd.exe then sees
* no quoted region, so a `%NAME%` never expands, and the program gets the argument unchanged.
* `twice` escapes again for a batch script that reads the argument a second time.
*/
function escapeCmdArgument(argument: string, twice: boolean): string {
const quoted = `"${argument.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\*)$/, "$1$1")}"`;
const escaped = quoted.replace(CMD_METACHARACTERS, "^$1");
return twice ? escaped.replace(CMD_METACHARACTERS, "^$1") : escaped;
}
/**
* Quote the program path for the start of a cmd.exe line. Inside the quotes cmd.exe reads `&`, `(`
* and `)` as text, so a path such as `C:\Program Files (x86)\...` starts.
*/
export function quoteWindowsCommand(command: string): string {
return escapeWindowsCmdValue(command);
if (command.startsWith('"') && command.endsWith('"')) return command;
if (command === "" || /[\s()!^"<>&|%;,=]/u.test(command)) return `"${command}"`;
return command;
}
/**
* `spawn(..., { shell: true })` on Windows also passes argv through `cmd.exe`.
* Any argument containing spaces must be quoted or it will be split before the
* child process sees it.
* The quoted line for `cmd.exe /d /s /c <line>` that starts `command` with `args`.
*
* - An argument without a metacharacter needs no escape and stays as given, so cmd.exe builtins
* and batch scripts that read `%1` get it unchanged.
* - Any other argument is escaped once. A batch script that reads it as `%~1` gets it without the
* quotes, and one that forwards it with `%*` hands the program the quoted argument, where cmd.exe
* reads every metacharacter as text.
* - For a batch script (`commandScript`), an argument with a `"` is escaped twice. Its quotes
* would otherwise open and close regions when the script reads it again, and leave the
* arguments after it outside the quotes.
*
* cmd.exe ends a command at a line break whatever the quoting, so an argument with one throws.
*/
export function quoteWindowsArgument(argument: string): string {
return escapeWindowsCmdValue(argument);
export function windowsCommandLine(
command: string,
args: readonly string[],
{ commandScript }: { commandScript: boolean },
): string {
const escaped = args.map((argument) => {
if (/[\r\n]/u.test(argument)) {
throw new Error(`cmd.exe cannot pass an argument with a line break to ${command}`);
}
if (argument !== "" && !NEEDS_ESCAPE.test(argument)) return argument;
return escapeCmdArgument(argument, commandScript && argument.includes('"'));
});
return `"${[quoteWindowsCommand(command), ...escaped].join(" ")}"`;
}
+299 -2
View File
@@ -3,6 +3,7 @@ import os from "node:os";
import path from "node:path";
import { afterEach, expect, test } from "vitest";
import { execCommand, spawnProcess } from "./index.js";
import { resolveSpawnInvocation } from "./process.js";
const roots: string[] = [];
afterEach(async () => {
@@ -26,8 +27,8 @@ const argumentsToPreserve = [
"feature^bugfix",
];
// A bare extensionless command selects the Windows shell; an absolute node.exe path would
// skip that path. The real child checks quoting through the public process capabilities.
// A real child checks quoting through the public process capabilities. On Windows the bare name
// resolves on PATH to node.exe, which starts directly.
test("execCommand delivers shell arguments to the real child unchanged", async () => {
const script = await writeArgumentReader();
const { stdout } = await execCommand("node", [script, ...argumentsToPreserve]);
@@ -51,3 +52,299 @@ test("spawnProcess delivers shell arguments to the real child unchanged", async
});
expect(JSON.parse(stdout)).toEqual(argumentsToPreserve);
});
// A Windows environment with an empty PATH, so a bare name is never found on the test host.
const windowsEnv = { ComSpec: "C:\\Windows\\System32\\cmd.exe", PATH: "" };
function onWindows(command: string, args: string[], shell?: boolean | string) {
return resolveSpawnInvocation(command, args, shell, "win32", windowsEnv);
}
// A launch wrap prepends a Windows script wrapper to the provider launch; spawnProcess starts it as
// one verbatim cmd.exe line.
test("a Windows script launch wrap starts as one verbatim cmd.exe line", () => {
const wrapped = [
"C:\\Program Files\\Sandbox\\run.cmd",
"--profile",
"work profile",
"",
"C:\\tools\\agy.cmd",
"acp",
];
expect(onWindows(wrapped[0]!, wrapped.slice(1))).toEqual({
command: "C:\\Windows\\System32\\cmd.exe",
args: [
"/d",
"/s",
"/c",
'""C:\\Program Files\\Sandbox\\run.cmd" --profile ^"work^ profile^" ^"^" C:\\tools\\agy.cmd acp"',
],
shell: false,
windowsVerbatimArguments: true,
});
expect(resolveSpawnInvocation(wrapped[0]!, wrapped.slice(1), undefined, "linux")).toEqual({
command: wrapped[0],
args: wrapped.slice(1),
shell: false,
});
});
// cmd.exe ends a command at a line break, and the text after it would run as a second command.
test("a Windows cmd.exe launch refuses an argument with a line break before it starts", () => {
for (const argument of ["line one\nline two", "line one\r\n& calc"]) {
expect(() => onWindows("C:\\Sandbox\\run.cmd", ["--", argument])).toThrow(
"cmd.exe cannot pass an argument with a line break to C:\\Sandbox\\run.cmd",
);
expect(() => onWindows("codex", [argument])).toThrow(
"cmd.exe cannot pass an argument with a line break to codex",
);
}
expect(onWindows("C:\\tools\\node.exe", ["a\nb"]).args).toEqual(["a\nb"]);
expect(resolveSpawnInvocation("/usr/bin/sandbox", ["a\nb"], undefined, "linux").args).toEqual([
"a\nb",
]);
});
// Only cmd.exe reads cmd.exe quoting. A shell the caller names parses the line by its own rules.
test("a Windows launch quotes for cmd.exe only when cmd.exe parses the command line", () => {
// `shell: true` runs the child's ComSpec; a cmd.exe the caller names runs as named.
for (const [shell, cmd] of [
[true, windowsEnv.ComSpec],
["cmd.exe", "cmd.exe"],
["D:\\Tools\\CMD.EXE", "D:\\Tools\\CMD.EXE"],
] as const) {
expect(onWindows("echo", ["hello", "a & b"], shell)).toEqual({
command: cmd,
args: ["/d", "/s", "/c", '"echo hello ^"a^ ^&^ b^""'],
shell: false,
windowsVerbatimArguments: true,
});
}
for (const shell of ["bash.exe", "C:\\Program Files\\Git\\bin\\bash.exe", "pwsh"]) {
expect(onWindows("echo", ["'a & b'", "line\nbreak"], shell)).toEqual({
command: "echo",
args: ["'a & b'", "line\nbreak"],
shell,
});
}
// A program starts directly, and `shell: false` keeps a bare name that is not on PATH direct.
expect(onWindows("C:\\tools\\node.exe", ["a & b"])).toEqual({
command: "C:\\tools\\node.exe",
args: ["a & b"],
shell: false,
});
expect(onWindows("missing", ["a & b"], false)).toEqual({
command: "missing",
args: ["a & b"],
shell: false,
});
});
// The daemon runs git with `shell: false` on hot paths that must not block on synchronous IO, so
// an explicit `shell: false` starts a bare name directly and leaves the PATH search to Windows.
test("a Windows bare name searches PATH for a script only when the caller allows a shell", async () => {
const directory = await mkdtemp(path.join(os.tmpdir(), "plugin-path-shim-"));
roots.push(directory);
await writeFile(path.join(directory, "tool.CMD"), "");
const env = { ...windowsEnv, PATH: directory };
expect(resolveSpawnInvocation("tool", ["a & b"], false, "win32", env)).toEqual({
command: "tool",
args: ["a & b"],
shell: false,
});
expect(resolveSpawnInvocation("tool", ["a & b"], undefined, "win32", env)).toEqual({
command: windowsEnv.ComSpec,
args: ["/d", "/s", "/c", `"${path.join(directory, "tool.CMD")} ^"a^ ^&^ b^""`],
shell: false,
windowsVerbatimArguments: true,
});
});
// Real Git Bash on Windows: the arguments reach Bash as given, without cmd.exe escapes.
test.runIf(process.platform === "win32")(
"execCommand passes arguments as given to a Windows shell other than cmd.exe",
async () => {
const bash = path.join(
process.env.ProgramFiles ?? "C:\\Program Files",
"Git",
"bin",
"bash.exe",
);
const { stdout } = await execCommand("printf", ["'%s|'", "hello", "'a & b'"], {
shell: bash,
});
expect(stdout).toBe("hello|a & b|");
},
);
// A launch wrap starts its executable with the command and its arguments after the wrap's own.
// The caller's shell choice belongs to the unwrapped command, so a wrap ignores it.
test("spawnProcess starts a wrap's executable with the command after the wrap arguments", async () => {
const launcher = await writeArgumentReader();
const child = spawnProcess("harness", ["--flag", ...argumentsToPreserve], {
wrap: [process.execPath, launcher, "--sandbox profile"],
shell: true,
stdio: "pipe",
});
let stdout = "";
child.stdout.setEncoding("utf8");
child.stdout.on("data", (chunk: string) => {
stdout += chunk;
});
await new Promise<void>((resolve, reject) => {
child.once("error", reject);
child.once("close", (code) => {
if (code === 0) resolve();
else reject(new Error(`Launcher exited with ${code}`));
});
});
expect(JSON.parse(stdout)).toEqual([
"--sandbox profile",
"harness",
"--flag",
...argumentsToPreserve,
]);
});
// Arguments that cmd.exe reads as syntax unless they are escaped for it. A `.cmd` launcher reads
// its arguments a second time when it forwards them with `%*`.
const commandScriptArguments = [
...argumentsToPreserve,
'say "hi"',
'"quoted"',
"",
"a & b",
"(parenthesized) arg",
"100% done",
"%PATH%",
"!bang!",
"C:\\path with space\\",
'mixed "a & b" quote',
"--profile=restricted",
"a,b;c",
// cmd.exe expands a set variable inside a quoted region, so this checks that none opens.
"value with %PATH% inside",
'quote "then %PATH%" & more',
];
async function writeCommandScriptLauncher(): Promise<string> {
const reader = await writeArgumentReader();
const directory = await mkdtemp(path.join(os.tmpdir(), "plugin wrap (x86) & launcher "));
roots.push(directory);
const launcher = path.join(directory, "sandbox run.cmd");
await writeFile(launcher, `@"${process.execPath}" "${reader}" %*\r\n`);
return launcher;
}
async function readStdout(child: ReturnType<typeof spawnProcess>): Promise<string> {
let stdout = "";
child.stdout?.setEncoding("utf8");
child.stdout?.on("data", (chunk: string) => {
stdout += chunk;
});
await new Promise<void>((resolve, reject) => {
child.once("error", reject);
child.once("close", (code) => {
if (code === 0) resolve();
else reject(new Error(`Child exited with ${code}`));
});
});
return stdout;
}
// Real cmd.exe: a `.cmd` launch wrap in a directory with spaces and cmd.exe syntax forwards the
// harness command and every argument to the program it starts, unchanged.
test.runIf(process.platform === "win32")(
"a .cmd launch wrap forwards the command and its arguments unchanged on Windows",
async () => {
const launcher = await writeCommandScriptLauncher();
const child = spawnProcess("harness", commandScriptArguments, {
wrap: [launcher, "--sandbox profile", 'say "hi"', ""],
stdio: "pipe",
});
expect(JSON.parse(await readStdout(child))).toEqual([
"--sandbox profile",
'say "hi"',
"",
"harness",
...commandScriptArguments,
]);
},
);
test.runIf(process.platform === "win32")(
"execCommand runs a .cmd script with its arguments unchanged on Windows",
async () => {
const launcher = await writeCommandScriptLauncher();
const { stdout } = await execCommand(launcher, commandScriptArguments);
expect(JSON.parse(stdout)).toEqual(commandScriptArguments);
},
);
// Real cmd.exe: a script that reads `%~1` gets each argument as given, without escapes.
test.runIf(process.platform === "win32")(
"a .cmd script that reads its arguments one by one gets each one as given on Windows",
async () => {
const directory = await mkdtemp(path.join(os.tmpdir(), "plugin script reader "));
roots.push(directory);
const script = path.join(directory, "read.cmd");
// `set /p` without input exits 1, so the script exits 0 on its own.
await writeFile(
script,
'@echo off\r\n<nul set /p "=%~1|%~2|%~3|%~4|%~5|%~6|%~7|%~8|%~9"\r\nexit /b 0\r\n',
);
const { stdout } = await execCommand(script, [
"plain",
"with space",
"feature&bugfix",
"100%",
"--profile=restricted",
"a,b",
"a;b",
"value with %PATH% inside",
"",
]);
expect(stdout).toBe(
"plain|with space|feature&bugfix|100%|--profile=restricted|a,b|a;b|value with %PATH% inside|",
);
},
);
// Real cmd.exe: a bare name is found on PATH like cmd.exe finds it. A `.cmd` shim that forwards
// `%*`, as npm writes them, passes every argument on unchanged; a program starts directly.
test.runIf(process.platform === "win32")(
"a bare command name found on PATH gets its arguments unchanged on Windows",
async () => {
const reader = await writeArgumentReader();
const directory = await mkdtemp(path.join(os.tmpdir(), "plugin bare shim "));
roots.push(directory);
await writeFile(
path.join(directory, "paseo-forward.cmd"),
`@"${process.execPath}" "${reader}" %*\r\n`,
);
// Windows env names ignore case, so drop the inherited `Path` before setting the new one.
const inherited = Object.entries(process.env).filter(([key]) => key.toLowerCase() !== "path");
const env = {
...Object.fromEntries(inherited),
PATH: `${directory};${process.env.PATH ?? ""}`,
};
const shim = await execCommand("paseo-forward", commandScriptArguments, { env });
expect(JSON.parse(shim.stdout)).toEqual(commandScriptArguments);
const program = await execCommand("node", [reader, ...commandScriptArguments], { env });
expect(JSON.parse(program.stdout)).toEqual(commandScriptArguments);
},
);
// Real cmd.exe: a caller that formats its own cmd.exe line asks Node to pass it verbatim.
test.runIf(process.platform === "win32")(
"spawnProcess passes a caller's verbatim cmd.exe line unchanged on Windows",
async () => {
const reader = await writeArgumentReader();
const child = spawnProcess(
process.env.ComSpec ?? "cmd.exe",
["/d", "/s", "/c", `""${process.execPath}" "${reader}" "a b" c"`],
{ shell: false, windowsVerbatimArguments: true, stdio: "pipe" },
);
expect(JSON.parse(await readStdout(child))).toEqual(["a b", "c"]);
},
);
+89 -31
View File
@@ -8,10 +8,12 @@ import {
import { extname } from "node:path";
import { promisify } from "node:util";
import {
findWindowsCommand,
isWindowsCommandScript,
quoteWindowsArgument,
quoteWindowsCommand,
windowsCommandLine,
windowsCommandShell,
} from "./process-internal/windows-command.js";
import type { PluginLaunchWrap } from "./lifecycle.js";
const execFileAsync = promisify(execFile);
export interface ExecCommandOptions {
env?: NodeJS.ProcessEnv;
@@ -20,6 +22,10 @@ export interface ExecCommandOptions {
killSignal?: NodeJS.Signals;
timeout?: number;
maxBuffer?: number;
/**
* `true` runs the command through cmd.exe on Windows, quoted for it. A shell named here other
* than cmd.exe gets the command and arguments as given, on every platform; quote for it.
*/
shell?: boolean | string;
signal?: AbortSignal;
}
@@ -27,47 +33,96 @@ interface ExecCommandResult {
stdout: string;
stderr: string;
}
function hasPathSeparator(value: string): boolean {
return value.includes("/") || value.includes("\\");
export interface SpawnInvocation {
command: string;
args: string[];
shell: boolean | string;
/** The args are one cmd.exe line that Node must pass as given. */
windowsVerbatimArguments?: boolean;
}
function shouldUseWindowsShell(
function namesCmd(shell: boolean | string | undefined): boolean {
return (
shell === true || (typeof shell === "string" && /^(?:.*[\\/])?cmd(?:\.exe)?$/iu.test(shell))
);
}
/**
* How `spawnProcess` and `execCommand` start `command` on `platform`.
*
* On Windows a bare name is first found on `PATH`, as cmd.exe would find it, unless the caller
* passes `shell: false`. A program then starts directly. A `.cmd` or `.bat` script, a name that is not on `PATH` (a cmd.exe builtin), or a
* `shell: true` launch runs as `cmd.exe /d /s /c "..."`, quoted by `windowsCommandLine`. A shell
* the caller names other than cmd.exe gets the command and arguments as given.
*/
export function resolveSpawnInvocation(
command: string,
requestedShell?: boolean | string,
): boolean | string {
if (isWindowsCommandScript(command)) {
return true;
args: readonly string[],
requestedShell: boolean | string | undefined,
platform: NodeJS.Platform = process.platform,
env: NodeJS.ProcessEnv = process.env,
): SpawnInvocation {
if (platform !== "win32") return { command, args: [...args], shell: requestedShell ?? false };
if (typeof requestedShell === "string" && !namesCmd(requestedShell)) {
return { command, args: [...args], shell: requestedShell };
}
if (requestedShell !== undefined) {
return requestedShell;
const bareName = !/[\\/]/u.test(command) && !extname(command);
// `shell: false` starts a bare name directly, and Windows searches PATH without blocking Node.
const found = bareName && requestedShell !== false ? findWindowsCommand(command, env) : undefined;
const target = found ?? command;
const commandScript = isWindowsCommandScript(target, platform);
// Only cmd.exe knows a builtin, so a bare name off `PATH` goes to it unless the caller said no shell.
const builtin = bareName && !found && requestedShell === undefined;
if (!commandScript && !namesCmd(requestedShell) && !builtin) {
return { command: target, args: [...args], shell: false };
}
return process.platform === "win32" && !hasPathSeparator(command) && !extname(command);
// A cmd.exe the caller names runs the line; otherwise the child's ComSpec does.
return {
command: typeof requestedShell === "string" ? requestedShell : windowsCommandShell(env),
args: ["/d", "/s", "/c", windowsCommandLine(target, args, { commandScript })],
shell: false,
windowsVerbatimArguments: true,
};
}
export interface SpawnProcessOptions extends SpawnOptions {
/**
* Start `[...wrap, command, ...args]`: the wrap's executable runs the command. `shell` is then
* ignored; the wrap's executable runs through cmd.exe only when it is a `.cmd` or `.bat` file.
*/
wrap?: PluginLaunchWrap;
}
/** Launch a CLI with Windows command-script handling and argv quoting. The caller owns env. */
export function spawnProcess(
command: string,
args: string[],
options: SpawnOptions & { stdio: "pipe" },
options: SpawnProcessOptions & { stdio: "pipe" },
): ChildProcessWithoutNullStreams;
export function spawnProcess(command: string, args: string[], options?: SpawnOptions): ChildProcess;
export function spawnProcess(
command: string,
args: string[],
options?: SpawnOptions,
options?: SpawnProcessOptions,
): ChildProcess;
export function spawnProcess(
command: string,
args: string[],
options?: SpawnProcessOptions,
): ChildProcess {
const spawnOptions = options ?? {};
const isWindows = process.platform === "win32";
const shell = shouldUseWindowsShell(command, spawnOptions.shell);
const { wrap, ...spawnOptions } = options ?? {};
const env = options?.env ?? process.env;
const invocation = wrap
? resolveSpawnInvocation(wrap[0], [...wrap.slice(1), command, ...args], false, undefined, env)
: resolveSpawnInvocation(command, args, spawnOptions.shell, undefined, env);
const shouldQuoteForShell = isWindows && shell !== false;
const resolvedCommand = shouldQuoteForShell ? quoteWindowsCommand(command) : command;
const resolvedArgs = shouldQuoteForShell ? args.map(quoteWindowsArgument) : args;
return spawn(resolvedCommand, resolvedArgs, {
return spawn(invocation.command, invocation.args, {
...spawnOptions,
env: options?.env,
shell,
shell: invocation.shell,
// Paseo's own cmd.exe line is verbatim; a direct launch keeps the caller's choice.
windowsVerbatimArguments:
invocation.windowsVerbatimArguments ?? spawnOptions.windowsVerbatimArguments,
signal: options?.signal,
windowsHide: true,
});
@@ -78,13 +133,15 @@ export async function execCommand(
args: string[],
options?: ExecCommandOptions,
): Promise<ExecCommandResult> {
const isWindows = process.platform === "win32";
const shell = shouldUseWindowsShell(command, options?.shell);
const shouldQuoteForShell = isWindows && shell !== false;
const resolvedCommand = shouldQuoteForShell ? quoteWindowsCommand(command) : command;
const resolvedArgs = shouldQuoteForShell ? args.map(quoteWindowsArgument) : args;
const invocation = resolveSpawnInvocation(
command,
args,
options?.shell,
undefined,
options?.env ?? process.env,
);
return execFileAsync(resolvedCommand, resolvedArgs, {
return execFileAsync(invocation.command, invocation.args, {
cwd: options?.cwd,
env: options?.env,
encoding: options?.encoding ?? "utf8",
@@ -92,7 +149,8 @@ export async function execCommand(
killSignal: options?.killSignal,
timeout: options?.timeout,
maxBuffer: options?.maxBuffer,
shell,
shell: invocation.shell,
windowsVerbatimArguments: invocation.windowsVerbatimArguments,
windowsHide: true,
}) as Promise<ExecCommandResult>;
}
@@ -3,6 +3,7 @@ import {
ProviderEventSchema,
ProviderInputSchema,
negotiateProviderCapabilities,
requireProviderCapabilities,
type ProviderEvent,
type ProviderInput,
type ProviderMetric,
@@ -125,3 +126,38 @@ describe("Provider metrics", () => {
).toBe(false);
});
});
describe("Provider launch wrap", () => {
const open = (wrap?: readonly [string, ...string[]]): ProviderInput =>
ProviderInputSchema.parse({
type: "session.open",
requestId: "open",
sessionId: "session-1",
history: "skip",
config: {
cwd: "/workspace",
env: {},
mcpServers: {},
settings: {},
persist: true,
...(wrap ? { wrap } : {}),
},
});
it("requires session.launch_wrap only for an open that carries a wrap", () => {
expect(() => requireProviderCapabilities([], open(["/bin/sandbox", "a b"]))).toThrow(
"session.launch_wrap",
);
expect(() =>
requireProviderCapabilities(["session.launch_wrap"], open(["/bin/sandbox"])),
).not.toThrow();
expect(() => requireProviderCapabilities([], open())).not.toThrow();
});
it("keeps each wrap element whole and rejects an empty wrap", () => {
expect(open(["/bin/sandbox", "a b"])).toMatchObject({
config: { wrap: ["/bin/sandbox", "a b"] },
});
expect(() => open([] as unknown as [string])).toThrow();
});
});
+11
View File
@@ -12,6 +12,7 @@ export const PROVIDER_CAPABILITIES = [
"session.can_stop_runtime",
"session.archive",
"session.configure",
"session.launch_wrap",
"session.list",
"session.metrics",
"session.persistence",
@@ -34,6 +35,12 @@ export interface ProviderRegistration {
getCatalogCacheKey?(options: ProviderCatalogOptions): Promise<string | undefined>;
/** Default executable and arguments; the daemon resolves overrides before status/connect. */
command?: readonly [string, ...string[]];
/**
* Sessions can run behind an `agent.open.before` wrap: the connection offers `session.launch_wrap`
* and spawns each session as `[...config.wrap, command, ...args]`. Paseo publishes it on the
* provider snapshot before the first connection.
*/
launchWrap?: boolean;
status?(request: ProviderStatusRequest): Promise<ProviderStatus>;
id: string;
label: string;
@@ -212,6 +219,8 @@ export interface ProviderSessionConfig {
providerOptions?: Readonly<Record<string, unknown>>;
title?: string;
persist: boolean;
/** Spawn the session as `[...wrap, command, ...args]`. Sent only with `session.launch_wrap`. */
wrap?: readonly [string, ...string[]];
}
export interface ProviderConfigChanges {
@@ -804,6 +813,7 @@ export function requiredProviderCapabilities(input: ProviderInput): readonly Pro
const capabilities: ProviderCapability[] = [];
if (input.persistence) capabilities.push("session.persistence");
if (input.config.toolPolicy) capabilities.push("permission.tool_policy");
if (input.config.wrap) capabilities.push("session.launch_wrap");
return capabilities;
}
case "session.prompt":
@@ -907,6 +917,7 @@ const sessionConfigSchema = z
providerOptions: z.record(z.string(), z.unknown()).optional(),
title: z.string().optional(),
persist: z.boolean(),
wrap: z.tuple([z.string().min(1)], z.string()).optional(),
})
.strict();
const externalResourceSchema = z
+5 -1
View File
@@ -5,7 +5,11 @@ import ts from "typescript";
import { describe, expect, it } from "vitest";
const repository = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../..");
const skill = readFileSync(path.join(repository, "skills/paseo-plugin/SKILL.md"), "utf8");
// A Windows checkout writes CRLF line endings.
const skill = readFileSync(
path.join(repository, "skills/paseo-plugin/SKILL.md"),
"utf8",
).replaceAll("\r\n", "\n");
const pluginRoot = path.join(repository, "plugin-examples/skill-example");
interface SkillExample {
+2
View File
@@ -136,6 +136,8 @@ export interface ProviderSnapshotEntry {
/** The page that helps users set up and troubleshoot this provider. */
docsUrl?: string;
defaultModeId?: string | null;
/** The provider can run a session behind an `agent.open.before` wrap. Absent means it cannot. */
launchWrap?: boolean;
}
export interface AgentFeatureToggle {
@@ -50,6 +50,12 @@ describe("provider snapshot message schemas", () => {
expect(parsed.source).toBe("custom");
});
test("keeps launch-wrap support and leaves it absent when not reported", () => {
const entry = { provider: "codex", status: "loading", label: "Codex" };
expect(ProviderSnapshotEntrySchema.parse({ ...entry, launchWrap: true }).launchWrap).toBe(true);
expect(ProviderSnapshotEntrySchema.parse(entry)).not.toHaveProperty("launchWrap");
});
test("defaults missing enabled state in providers snapshot response entries", () => {
const parsed = GetProvidersSnapshotResponseMessageSchema.parse({
type: "get_providers_snapshot_response",
+1
View File
@@ -432,6 +432,7 @@ export const ProviderSnapshotEntrySchema = z.object({
iconSvg: z.string().optional(),
docsUrl: z.string().optional(),
defaultModeId: z.string().nullable().optional(),
launchWrap: z.boolean().optional(),
});
export const CompactProviderSnapshotModelSchema = AgentModelDefinitionSchema.omit({
+1 -1
View File
@@ -90,7 +90,7 @@
"speech:transcribe:local": "tsx scripts/transcribe-local-wav.ts",
"test": "npm run test:unit && npm run test:integration",
"test:unit": "vitest run --fileParallelism --exclude \"**/*.e2e.test.ts\"",
"test:integration": "vitest run --fileParallelism --maxWorkers=3 src/server/git-filename-diffs.e2e.test.ts src/server/daemon-e2e/checkout-diff-content.e2e.test.ts src/server/daemon-e2e/create-agent-mode.e2e.test.ts src/server/daemon-e2e/filesystem.e2e.test.ts src/server/daemon-e2e/file-download.e2e.test.ts src/server/daemon-e2e/cli-logs-follow.e2e.test.ts src/server/creation/creation.e2e.test.ts src/server/daemon-e2e/creation-status.e2e.test.ts src/server/daemon-e2e/persisted-creation-caller.e2e.test.ts src/server/daemon-e2e/terminal-workspace-sdk.e2e.test.ts src/server/daemon-e2e/terminal-worker-lifecycle.e2e.test.ts src/server/workspace-create-worktree-source.e2e.test.ts src/server/daemon-e2e/models.e2e.test.ts src/server/daemon-e2e/live-preferences.e2e.test.ts src/server/daemon-e2e/oversized-message.e2e.test.ts src/server/agent/model-catalog.e2e.test.ts src/server/plugins/plugin-paseo-api.e2e.test.ts src/server/plugins/usage-sources.e2e.test.ts src/server/plugins/lifecycle.e2e.test.ts src/server/plugins/worktree-manager.e2e.test.ts src/server/connected-hosts/hosts.e2e.test.ts src/server/owned-subscriptions.e2e.test.ts && vitest run --fileParallelism --maxWorkers=3 src/server/agent/providers/omp/history.e2e.test.ts src/server/daemon-e2e/git-operations.e2e.test.ts src/server/session.create-agent-worktree-autoarchive.e2e.test.ts src/server/agent/providers/opencode-bridge.local.e2e.test.ts src/server/daemon-e2e/relay-transport.e2e.test.ts src/server/agent/agent-mcp.e2e.test.ts -t \"agent MCP protocol negotiation|merges into|creates a worktree and auto-archives both|versioned runtime|oversized attachments|connected hosts|password-protected daemon refuses|replays selected OMP history\"",
"test:integration": "vitest run --fileParallelism --maxWorkers=3 src/server/git-filename-diffs.e2e.test.ts src/server/daemon-e2e/checkout-diff-content.e2e.test.ts src/server/daemon-e2e/create-agent-mode.e2e.test.ts src/server/daemon-e2e/filesystem.e2e.test.ts src/server/daemon-e2e/file-download.e2e.test.ts src/server/daemon-e2e/cli-logs-follow.e2e.test.ts src/server/creation/creation.e2e.test.ts src/server/daemon-e2e/creation-status.e2e.test.ts src/server/daemon-e2e/persisted-creation-caller.e2e.test.ts src/server/daemon-e2e/terminal-workspace-sdk.e2e.test.ts src/server/daemon-e2e/terminal-worker-lifecycle.e2e.test.ts src/server/workspace-create-worktree-source.e2e.test.ts src/server/daemon-e2e/models.e2e.test.ts src/server/daemon-e2e/live-preferences.e2e.test.ts src/server/daemon-e2e/oversized-message.e2e.test.ts src/server/agent/model-catalog.e2e.test.ts src/server/plugins/plugin-paseo-api.e2e.test.ts src/server/plugins/usage-sources.e2e.test.ts src/server/plugins/lifecycle.e2e.test.ts src/server/plugins/agent-configuration.e2e.test.ts src/server/plugins/worktree-manager.e2e.test.ts src/server/connected-hosts/hosts.e2e.test.ts src/server/owned-subscriptions.e2e.test.ts && vitest run --fileParallelism --maxWorkers=3 src/server/agent/providers/omp/history.e2e.test.ts src/server/daemon-e2e/git-operations.e2e.test.ts src/server/session.create-agent-worktree-autoarchive.e2e.test.ts src/server/agent/providers/opencode-bridge.local.e2e.test.ts src/server/daemon-e2e/relay-transport.e2e.test.ts src/server/agent/agent-mcp.e2e.test.ts src/server/plugins/agent-tools.e2e.test.ts -t \"agent MCP protocol negotiation|merges into|creates a worktree and auto-archives both|versioned runtime|oversized attachments|connected hosts|password-protected daemon refuses|replays selected OMP history|changes the launch wrap\"",
"test:hub-cli-contract": "vitest run --maxWorkers=1 src/server/hub/hub-cli-contract.test.ts",
"test:integration:all": "npm run test:e2e",
"test:integration:real": "vitest run real.e2e.test.ts",
@@ -1,3 +1,4 @@
import type { AttachedAgentTool, PluginSessionsRuntime } from "../plugins/agent-tools.js";
import { createIdleRuntimeCleanup } from "./idle-runtime-cleanup/index.js";
import {
prepareAgentMessage,
@@ -6,7 +7,7 @@ import {
} from "./agent-messages/index.js";
import { expect, test, vi, onTestFinished } from "vitest";
import { spawn } from "node:child_process";
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { tmpdir } from "node:os";
import { randomUUID } from "node:crypto";
@@ -22,7 +23,11 @@ import {
import { AgentStorage, parseStoredAgentRecord } from "./agent-storage.js";
import { AgentTurnStartCanceledError } from "./agent-sdk-types.js";
import { ForegroundPromptStart } from "./agent-run-state.js";
import { CodexAppServerAgentSession } from "./providers/codex-app-server-agent.js";
import {
CodexAppServerAgentClient,
CodexAppServerAgentSession,
} from "./providers/codex-app-server-agent.js";
import { spawnProcess } from "../../utils/spawn.js";
import { createFakeCodexAppServer } from "./providers/codex/test-utils/fake-app-server.js";
import { InMemoryAgentTimelineStore } from "./agent-timeline-store.js";
import { limitAgentTimelineItemContent } from "./agent-timeline-content.js";
@@ -679,6 +684,24 @@ async function startAndSteerThroughManager(
return { manager, agentId: agent.id, workdir };
}
/** Plugin sessions whose only plugin appends the given instructions to every open. */
function instructionPluginSessions(instructions: () => string[]): PluginSessionsRuntime {
return {
openSession: async (request) => ({
...request,
appendSystemPrompt: instructions(),
tools: [],
mcpServerOwners: {},
}),
sessionLaunched: () => {},
sessionLaunchFailed: () => {},
refreshSession: async () => ({ stale: false }),
sessionTools: () => [],
closeSession: () => {},
callTool: async () => ({ isError: true, text: "No plugin tools" }),
};
}
test("OpenCode persistence excludes launch-only instructions from storage and clients", async () => {
const workdir = mkdtempSync(join(tmpdir(), "agent-plugin-persistence-"));
const harness = new V2Harness();
@@ -690,13 +713,7 @@ test("OpenCode persistence excludes launch-only instructions from storage and cl
registry: storage,
logger,
appendSystemPrompt: "Daemon instruction",
pluginLifecycle: {
emit: () => {},
before: async (name, request) =>
name === "agent.open.before"
? { ...request, appendSystemPrompt: ["Plugin instruction"] }
: request,
},
pluginSessions: instructionPluginSessions(() => ["Plugin instruction"]),
});
const agent = await manager.createAgent({ provider: "opencode", cwd: workdir }, undefined, {
workspaceId: undefined,
@@ -16144,11 +16161,7 @@ test("plugin instructions are recomputed for each launch without changing saved
registry: storage,
logger,
appendSystemPrompt: "Daemon",
pluginLifecycle: {
emit: () => {},
before: async (name, request) =>
name === "agent.open.before" ? { ...request, appendSystemPrompt: additions } : request,
},
pluginSessions: instructionPluginSessions(() => additions),
});
const snapshot = await manager.createAgent(
{ provider: "codex", cwd: workdir, systemPrompt: "Saved" },
@@ -16259,3 +16272,232 @@ test("importProviderSession keeps the stats the provider reported with its histo
["assistant_message", null],
]);
});
class LaunchWrapRecordingClient extends TestAgentClient {
readonly sessions: CloseRecordingTestAgentSession[] = [];
readonly launchContexts: Array<AgentLaunchContext | undefined> = [];
calls = { create: 0, resume: 0, import: 0 };
constructor(supportsLaunchWrap: boolean) {
super("codex");
if (supportsLaunchWrap) this.supportsLaunchWrap = true;
}
supportsLaunchWrap?: boolean;
override async createSession(
config: AgentSessionConfig,
launchContext?: AgentLaunchContext,
): Promise<AgentSession> {
this.calls.create += 1;
this.launchContexts.push(launchContext);
const session = new CloseRecordingTestAgentSession(config);
this.sessions.push(session);
return session;
}
override async resumeSession(
handle: AgentPersistenceHandle,
config?: Partial<AgentSessionConfig>,
launchContext?: AgentLaunchContext,
): Promise<AgentSession> {
this.calls.resume += 1;
this.launchContexts.push(launchContext);
return await super.resumeSession(handle, config, launchContext);
}
async importSession(input: ImportProviderSessionInput, context: ImportProviderSessionContext) {
this.calls.import += 1;
return {
session: new TestAgentSession(context.config),
config: context.storedConfig,
persistence: { provider: this.provider, sessionId: input.providerHandleId },
timeline: [],
};
}
}
type TestLaunchWrap = [string, ...string[]];
/**
* A session-open plugin that selects `wrap()` and attaches one tool while it does. Like the real runtime, an open's
* tools take over only once its launch does, and a failed launch leaves the running session's tools.
*/
function launchWrapPluginSessions(wrap: () => TestLaunchWrap | undefined) {
const pending = new Map<string, AttachedAgentTool[]>();
const running = new Map<string, AttachedAgentTool[]>();
const failedLaunches: string[] = [];
const sessions: PluginSessionsRuntime = {
openSession: async (request) => {
const selected = wrap();
const tools: AttachedAgentTool[] = selected
? [
{
name: "sandbox_status",
description: "Report the sandbox",
inputSchema: {},
pluginId: "sandbox",
pluginInstanceId: "sandbox-1",
},
]
: [];
if (request.purpose === "interactive") pending.set(request.agentId, tools);
return { ...request, ...(selected ? { wrap: selected } : {}), tools, mcpServerOwners: {} };
},
sessionLaunched: (agentId) => {
const tools = pending.get(agentId);
pending.delete(agentId);
if (tools) running.set(agentId, tools);
},
sessionLaunchFailed: (agentId) => {
pending.delete(agentId);
failedLaunches.push(agentId);
},
refreshSession: async () => ({ stale: false }),
sessionTools: (agentId) => running.get(agentId) ?? [],
closeSession: (agentId) => {
pending.delete(agentId);
running.delete(agentId);
},
callTool: async () => ({ isError: true, text: "No plugin tools" }),
};
return { sessions, failedLaunches };
}
function createLaunchWrapManager(client: LaunchWrapRecordingClient) {
const workdir = mkdtempSync(join(tmpdir(), "agent-launch-wrap-"));
onTestFinished(() => rmSync(workdir, { recursive: true, force: true }));
const storage = new AgentStorage(join(workdir, "agents"), logger);
const hook: { wrap: TestLaunchWrap | undefined } = { wrap: undefined };
const { sessions, failedLaunches } = launchWrapPluginSessions(() => hook.wrap);
const manager = new AgentManager({
clients: { codex: client },
registry: storage,
logger,
pluginSessions: sessions,
});
return { manager, storage, workdir, failedLaunches, hook };
}
test("a wrapped open rejects on every path for a provider that does not apply wraps", async () => {
const client = new LaunchWrapRecordingClient(false);
const { manager, storage, workdir, failedLaunches, hook } = createLaunchWrapManager(client);
const created = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
workspaceId: undefined,
});
const existing = client.sessions[0]!;
hook.wrap = ["/opt/sandbox/bin/run", "--profile", "a b"];
const calls = { ...client.calls };
const unsupported = { code: "launch_wrap_unsupported", provider: "codex" };
await expect(
manager.createAgent({ provider: "codex", cwd: workdir }, undefined, { workspaceId: undefined }),
).rejects.toMatchObject(unsupported);
await expect(
manager.resumeAgentFromPersistence({ provider: "codex", sessionId: "saved" }, { cwd: workdir }),
).rejects.toMatchObject(unsupported);
await expect(
manager.importProviderSession({
provider: "codex",
providerHandleId: "native",
cwd: workdir,
workspaceId: "import",
}),
).rejects.toMatchObject(unsupported);
await expect(manager.reloadAgentSession(created.id)).rejects.toMatchObject(unsupported);
expect(client.calls).toEqual(calls);
expect(existing.closed).toBe(false);
expect(manager.getAgent(created.id)?.session).toBe(existing);
// Each refused open is discarded, so the running session keeps the tools it launched with.
expect(failedLaunches).toHaveLength(4);
expect(failedLaunches.at(-1)).toBe(created.id);
expect(manager.getPluginTools(created.id)).toEqual([]);
await manager.flush();
expect(JSON.stringify(await storage.get(created.id))).not.toContain("/opt/sandbox");
await manager.closeAgent(created.id);
});
test("a supporting provider receives the wrap at launch and the record never stores it", async () => {
const client = new LaunchWrapRecordingClient(true);
const { manager, storage, workdir, hook } = createLaunchWrapManager(client);
hook.wrap = ["/opt/sandbox/bin/run", "--profile", "a b"];
const created = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
workspaceId: undefined,
});
expect(client.launchContexts[0]?.wrap).toEqual(["/opt/sandbox/bin/run", "--profile", "a b"]);
await manager.flush();
expect(JSON.stringify(await storage.get(created.id))).not.toContain("/opt/sandbox");
await manager.closeAgent(created.id);
});
// Records its argv, then answers as the Codex app server, so the provider command is only an
// argument: a Windows script name there must reach the wrapper as is.
const RECORDING_CODEX_APP_SERVER = `
const { appendFileSync } = require("node:fs");
const [log, ...rest] = process.argv.slice(2);
appendFileSync(log, JSON.stringify(rest) + "\\n");
const results = {
"collaborationMode/list": { data: [] },
"config/read": { config: {} },
getUserSavedConfig: { config: {} },
"model/list": { data: [{ id: "gpt-5.4", isDefault: true, defaultReasoningEffort: "medium" }] },
"skills/list": { data: [] },
"thread/start": { thread: { id: "thread-1" } },
"thread/resume": { thread: { id: "thread-1" } },
"thread/loaded/list": { data: [] },
"thread/backgroundTerminals/list": { data: [], nextCursor: null },
};
let buffer = "";
process.stdin.on("data", (chunk) => {
buffer += chunk.toString();
for (let index = buffer.indexOf("\\n"); index !== -1; index = buffer.indexOf("\\n")) {
const line = buffer.slice(0, index).trim();
buffer = buffer.slice(index + 1);
if (!line) continue;
const message = JSON.parse(line);
if (message.id === undefined || !message.method) continue;
process.stdout.write(JSON.stringify({ id: message.id, result: results[message.method] ?? {} }) + "\\n");
}
});
`;
test("a wrapped refresh passes a Windows script provider command to the wrapper through the real spawn", async () => {
const workdir = mkdtempSync(join(tmpdir(), "agent-launch-wrap-refresh-"));
onTestFinished(() => rmSync(workdir, { recursive: true, force: true }));
const launcher = join(workdir, "recording-app-server.cjs");
const launches = join(workdir, "launches.jsonl");
writeFileSync(launcher, RECORDING_CODEX_APP_SERVER);
// The version probes run `node --version`; sessions spawn through the production spawnProcess.
const codex = new CodexAppServerAgentClient(
logger,
{ command: { mode: "replace", argv: [process.execPath] } },
{
appServerProcess: {
resolvePrefix: async () => ({ command: "C:\\codex\\codex.cmd", args: [] }),
spawn: ({ command, args, options }) => spawnProcess(command, args, options),
},
},
);
const client: AgentClient = Object.assign(codex, { supportsLaunchWrap: true });
const manager = new AgentManager({
clients: { codex: client },
logger,
pluginSessions: launchWrapPluginSessions(() => [process.execPath, launcher, launches]).sessions,
});
const created = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
workspaceId: undefined,
});
await manager.reloadAgentSession(created.id);
const argv = readFileSync(launches, "utf8")
.trim()
.split("\n")
.map((line) => JSON.parse(line) as string[]);
expect(argv).toHaveLength(2);
for (const launched of argv)
expect(launched.slice(0, 2)).toEqual(["C:\\codex\\codex.cmd", "app-server"]);
expect(manager.getAgent(created.id)?.lifecycle).not.toBe("error");
await manager.closeAgent(created.id);
});
+202 -72
View File
@@ -1,5 +1,9 @@
import type { AttachedAgentTool, PluginAgentToolsRuntime } from "../plugins/agent-tools.js";
import { ProviderOptionsValidationError } from "./provider-options.js";
import type {
AttachedAgentTool,
PluginSessionsRuntime,
SessionOpenAgentFacts,
} from "../plugins/agent-tools.js";
import { LaunchWrapUnsupportedError, 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";
@@ -203,6 +207,26 @@ async function assertUsableWorkingDirectory(cwd: string): Promise<void> {
}
}
interface ResumeAgentOptions {
createdAt?: Date;
updatedAt?: Date;
lastUserMessageAt?: Date | null;
labels?: Record<string, string>;
metadata?: AgentMetadata;
workspaceId?: string;
owner?: AgentOwner;
background?: boolean;
attention?: AttentionState;
}
interface PluginToolCall {
pluginId: string;
toolName: string;
agentId: string;
input: unknown;
signal?: AbortSignal;
}
interface StopAgentBackgroundWorkOptions {
agentId: string;
itemId: string;
@@ -399,7 +423,7 @@ export interface AgentManagerOptions {
terminalManager?: TerminalManager | null;
mcpBaseUrl?: string;
mcpAuthToken?: string;
pluginAgentTools?: PluginAgentToolsRuntime;
pluginSessions?: PluginSessionsRuntime;
paseoToolsEnabled?: boolean;
paseoToolCatalogFactory?: PaseoToolCatalogFactory;
resolvePaseoToolPolicy?: (provider: AgentProvider) => ProviderPaseoToolsPolicy | undefined;
@@ -937,10 +961,7 @@ export class AgentManager {
private readonly agentStreamCoalescer: AgentStreamCoalescer;
private mcpBaseUrl: string | null;
private readonly mcpAuthToken: string | null;
private sessionOpenGeneration = 0;
private readonly sessionOpenGenerations = new Map<string, number>();
private readonly attachedPluginTools = new Map<string, AttachedAgentTool[]>();
private readonly pluginAgentTools: PluginAgentToolsRuntime | undefined;
private readonly pluginSessions: PluginSessionsRuntime | undefined;
private paseoToolsEnabled = true;
private paseoToolCatalogFactory: PaseoToolCatalogFactory | null = null;
private readonly paseoToolPolicies = new Map<string, ProviderPaseoToolsPolicy | undefined>();
@@ -958,7 +979,7 @@ export class AgentManager {
constructor(options: AgentManagerOptions) {
this.pluginLifecycle = options.pluginLifecycle;
this.pluginAgentTools = options.pluginAgentTools;
this.pluginSessions = options.pluginSessions;
this.timelineStore = options.timelineStore ?? new InMemoryAgentTimelineStore();
this.idFactory = options.idFactory ?? (() => randomUUID());
this.registry = options?.registry;
@@ -1063,47 +1084,75 @@ export class AgentManager {
this.paseoToolCatalogFactory = factory;
}
invalidatePluginSessions(): void {
this.sessionOpenGeneration++;
}
/**
* Reopens an idle agent whose plugin attachment changed in a way the running provider session cannot pick up:
* env, instructions, MCP servers, or tool definitions. A plugin change that leaves the agent's launch as it was
* keeps the session, with its background work and subagents.
*/
async reloadStalePluginSession(agentId: string): Promise<void> {
if (!this.needsPluginSessionReload(agentId)) return;
if (!(await this.needsPluginSessionReload(agentId))) return;
await this.trackAgentRegistrationOperation(
this.runLifecycleMutation(agentId, async () => {
if (!this.needsPluginSessionReload(agentId)) return;
if (!(await this.needsPluginSessionReload(agentId))) return;
await this.reloadAgentSessionInternal(agentId);
}),
);
}
private needsPluginSessionReload(agentId: string): boolean {
private async needsPluginSessionReload(agentId: string): Promise<boolean> {
const agent = this.getAgent(agentId);
return (
agent !== null &&
agent.lifecycle !== "closed" &&
this.sessionOpenGenerations.get(agentId) !== this.sessionOpenGeneration &&
!this.hasInFlightRun(agentId)
);
if (!agent || agent.lifecycle === "closed" || this.hasInFlightRun(agentId)) return false;
return (await this.refreshPluginTools(agentId)).stale;
}
getPluginTools(agentId: string): readonly AttachedAgentTool[] {
return (this.attachedPluginTools.get(agentId) ?? []).filter((tool) =>
this.pluginAgentTools?.isToolPluginAvailable(tool.pluginId, tool.pluginInstanceId),
);
return this.pluginSessions?.sessionTools(agentId) ?? [];
}
async executePluginTool(
tool: AttachedAgentTool,
agentId: string,
input: unknown,
signal?: AbortSignal,
): Promise<AgentToolResult> {
/**
* Brings a live session's plugin tools up to date with the running plugins. A plugin restart gives it a new
* instance; only that plugin's open is rerun for the session, without reopening it or interrupting its turn.
*/
async refreshPluginTools(agentId: string): Promise<{ stale: boolean }> {
if (!this.pluginSessions) return { stale: false };
return this.pluginSessions.refreshSession(agentId, {
reservedToolNames: () => this.reservedAgentToolNames(agentId),
agentFacts: () => this.pluginOpenAgentFacts(agentId),
});
}
/** The agent fields a reopen would put in its plugin open request. */
private async pluginOpenAgentFacts(agentId: string): Promise<SessionOpenAgentFacts> {
const agent = this.requireAgent(agentId);
return {
workspaceId: agent.workspaceId ?? null,
title: await this.resolveInitialPersistedTitle(agentId, agent.config, null),
background: agent.background === true,
...agentEntityData(agent),
};
}
/**
* Resolves the plugin's current instance of the tool at call time, so a launch-time catalog reaches a restarted
* plugin and never a different plugin that took the name.
*/
async executePluginTool({
pluginId,
toolName,
agentId,
input,
signal,
}: PluginToolCall): Promise<AgentToolResult> {
const agent = this.getAgent(agentId);
if (!agent || agent.lifecycle === "closed") throw new Error(`Agent is not live: ${agentId}`);
if (!this.pluginAgentTools) throw new Error("Plugin tools are unavailable");
if (!this.pluginSessions) throw new Error("Plugin tools are unavailable");
await this.refreshPluginTools(agentId);
const tool = this.getPluginTools(agentId).find(
(entry) => entry.pluginId === pluginId && entry.name === toolName,
);
if (!tool) return { isError: true, text: `Plugin tool is not available: ${toolName}` };
const record = await this.registry?.get(agentId);
return this.pluginAgentTools.callTool(
return this.pluginSessions.callTool(
tool.pluginId,
tool.pluginInstanceId,
describeHookAgent({ ...agent, title: record?.title ?? agent.config.title }),
@@ -1113,10 +1162,22 @@ export class AgentManager {
);
}
/**
* Paseo's own tool names for the agent, including the ones its provider disables. The catalog also lists the
* agent's plugin tools; the plugin session owner settles those names between plugins itself.
*/
private async reservedAgentToolNames(agentId: string): Promise<ReadonlySet<string>> {
if (!this.paseoToolCatalogFactory) return new Set();
const pluginToolNames = new Set(this.getPluginTools(agentId).map((tool) => tool.name));
const catalog = await this.paseoToolCatalogFactory({
callerAgentId: agentId,
paseoToolPolicy: {},
});
return new Set([...catalog.tools.keys()].filter((name) => !pluginToolNames.has(name)));
}
private detachPluginTools(agentId: string): void {
this.attachedPluginTools.delete(agentId);
this.sessionOpenGenerations.delete(agentId);
this.pluginAgentTools?.detachTools(agentId);
this.pluginSessions?.closeSession(agentId);
}
getPaseoToolPolicy(agentId: string): ProviderPaseoToolsPolicy | undefined {
@@ -1637,7 +1698,17 @@ export class AgentManager {
);
}
private async createAgentInternal(
private createAgentInternal(
config: AgentSessionConfig,
resolvedAgentId: string,
options: CreateAgentOptions,
): Promise<ManagedAgent> {
return this.launchAgent(resolvedAgentId, () =>
this.createAgentSession(config, resolvedAgentId, options),
);
}
private async createAgentSession(
config: AgentSessionConfig,
resolvedAgentId: string,
options: CreateAgentOptions,
@@ -1650,6 +1721,7 @@ export class AgentManager {
config: sent,
env: options.env,
metadata: options.metadata ?? {},
workspaceId: options.workspaceId ?? null,
});
// COMPAT(featureValues): added in v0.15.0, remove after 2027-05-01. A plugin written
// against the previous SDK edits `config.featureValues`.
@@ -1758,7 +1830,19 @@ export class AgentManager {
);
}
private async resumeAgentFromPersistenceInternal(
private resumeAgentFromPersistenceInternal(
handle: AgentPersistenceHandle,
overrides: Partial<AgentSessionConfig> | undefined,
agentId: string,
options?: ResumeAgentOptions,
resumeOptions?: AgentResumeSessionOptions,
): Promise<ManagedAgent> {
return this.launchAgent(agentId, () =>
this.resumeAgentSession(handle, overrides, agentId, options, resumeOptions),
);
}
private async resumeAgentSession(
handle: AgentPersistenceHandle,
overrides?: Partial<AgentSessionConfig>,
agentId?: string,
@@ -1864,18 +1948,23 @@ export class AgentManager {
workspaceId: string;
labels?: Record<string, string>;
}): Promise<ManagedAgent> {
return this.trackAgentRegistrationOperation(this.importProviderSessionInternal(input));
const resolvedAgentId = validateAgentId(this.idFactory(), "importProviderSession");
return this.trackAgentRegistrationOperation(
this.launchAgent(resolvedAgentId, () => this.importAgentSession(input, resolvedAgentId)),
);
}
private async importProviderSessionInternal(input: {
provider: AgentProvider;
providerHandleId: string;
cwd: string;
workspaceId: string;
labels?: Record<string, string>;
}): Promise<ManagedAgent> {
private async importAgentSession(
input: {
provider: AgentProvider;
providerHandleId: string;
cwd: string;
workspaceId: string;
labels?: Record<string, string>;
},
resolvedAgentId: string,
): Promise<ManagedAgent> {
this.assertAcceptingAgentRegistrations();
const resolvedAgentId = validateAgentId(this.idFactory(), "importProviderSession");
this.requireEnabledProvider(input.provider);
const client = await this.requireAvailableClient({ provider: input.provider });
@@ -1971,7 +2060,29 @@ export class AgentManager {
);
}
private async reloadAgentSessionInternal(
private reloadAgentSessionInternal(
agentId: string,
overrides?: Partial<AgentSessionConfig>,
options?: { rehydrateFromDisk?: boolean },
): Promise<ManagedAgent> {
return this.launchAgent(agentId, () => this.reopenAgentSession(agentId, overrides, options));
}
/**
* Runs one provider launch: create, resume, import, or reopen. Its plugin open takes over the session once
* `registerSession` admits the agent. A launch that fails before then discards that open, so a session still
* running keeps its plugin tools.
*/
private async launchAgent<T>(agentId: string, launch: () => Promise<T>): Promise<T> {
try {
return await launch();
} catch (error) {
this.pluginSessions?.sessionLaunchFailed(agentId);
throw error;
}
}
private async reopenAgentSession(
agentId: string,
overrides?: Partial<AgentSessionConfig>,
options?: { rehydrateFromDisk?: boolean },
@@ -2019,13 +2130,11 @@ export class AgentManager {
metadata: existing.metadata,
},
);
const providerLaunchConfig = this.resolveProviderLaunchConfig(launchConfig, launchContext);
if (
Object.keys(stripInternalPaseoMcpServer(providerLaunchConfig).mcpServers ?? {}).length > 0 &&
existing.session.capabilities.supportsMcpServers !== true
) {
throw this.unsupportedMcpError(providerLaunchConfig, launchContext);
}
const providerLaunchConfig = this.resolveReloadLaunchConfig(
existing,
launchConfig,
launchContext,
);
let session: AgentSession | undefined;
let closedExisting: ManagedAgentClosed | undefined;
@@ -2089,7 +2198,8 @@ export class AgentManager {
throw error;
} finally {
if (!handedToRegistration) {
this.detachPluginTools(agentId);
// The closed agent drops its plugin record; a launch that never closed it leaves the rollback to launchAgent.
if (closedExisting) this.detachPluginTools(agentId);
if (hadPreviousPaseoToolPolicy) {
this.paseoToolPolicies.set(agentId, previousPaseoToolPolicy);
} else {
@@ -2102,6 +2212,23 @@ export class AgentManager {
}
}
/** Validates a reload's launch before it closes the running session. */
private resolveReloadLaunchConfig(
existing: ActiveManagedAgent,
launchConfig: AgentSessionConfig,
launchContext: AgentLaunchContext,
): AgentSessionConfig {
const providerLaunchConfig = this.resolveProviderLaunchConfig(launchConfig, launchContext);
const mcpServers = stripInternalPaseoMcpServer(providerLaunchConfig).mcpServers ?? {};
if (
Object.keys(mcpServers).length > 0 &&
existing.session.capabilities.supportsMcpServers !== true
) {
throw this.unsupportedMcpError(providerLaunchConfig, launchContext);
}
return providerLaunchConfig;
}
private async closeReloadedSession(session: AgentSession, agentId: string): Promise<void> {
let operation = this.reloadedSessionCloses.get(session);
if (!operation) {
@@ -4619,6 +4746,8 @@ export class AgentManager {
this.runtimeCleanupIdentities.set(session, Object.freeze({ openedAt: Date.now() }));
this.agents.set(resolvedAgentId, managed);
registered = true;
// The agent now runs this launch, so its plugin open describes the running session.
this.pluginSessions?.sessionLaunched(resolvedAgentId);
// Initialize previousStatus to track transitions
this.previousStatuses.set(resolvedAgentId, managed.lifecycle);
if (session.initialTimeline?.length) {
@@ -6513,13 +6642,11 @@ export class AgentManager {
metadata?: AgentMetadata;
},
): Promise<AgentLaunchContext> {
// 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) {
let wrap: AgentLaunchContext["wrap"];
if (this.pluginSessions) {
const request = {
agentId,
provider: client.provider,
@@ -6534,17 +6661,20 @@ export class AgentManager {
tools: [],
mcpServers: {},
};
const transformed = await this.pluginLifecycle.before("agent.open.before", request);
const transformed = await this.pluginSessions.openSession(request);
env = transformed.env;
wrap = transformed.wrap;
if (request.purpose === "interactive") {
this.attachedPluginTools.set(agentId, transformed.tools as AttachedAgentTool[]);
appendSystemPrompt = transformed.appendSystemPrompt;
mcpServers = transformed.mcpServers;
mcpServerOwners = transformed.mcpServerOwners;
}
// launchAgent discards this open when the wrap is refused, so a running session keeps its tools.
if (wrap) await requireLaunchWrap(client);
}
const context: AgentLaunchContext = {
agentId,
wrap,
...pluginPromptContext(appendSystemPrompt),
mcpServers,
mcpServerOwners,
@@ -6561,18 +6691,13 @@ export class AgentManager {
this.paseoToolCatalogFactory &&
(useNativeTools || this.getPluginTools(agentId).length > 0)
) {
try {
const catalog = await this.paseoToolCatalogFactory({
callerAgentId: agentId,
paseoToolPolicy,
});
if (useNativeTools) context.paseoTools = catalog;
} catch (error) {
this.detachPluginTools(agentId);
throw error;
}
// Building the catalog checks the plugin tools against Paseo's own names.
const catalog = await this.paseoToolCatalogFactory({
callerAgentId: agentId,
paseoToolPolicy,
});
if (useNativeTools) context.paseoTools = catalog;
}
this.sessionOpenGenerations.set(agentId, generation);
return context;
}
@@ -6736,3 +6861,8 @@ function pluginPromptContext(
): Pick<AgentLaunchContext, "appendSystemPrompt"> {
return appendSystemPrompt?.length ? { appendSystemPrompt } : {};
}
async function requireLaunchWrap(client: AgentClient): Promise<void> {
if (client.supportsLaunchWrap !== true) throw new LaunchWrapUnsupportedError(client.provider);
await client.requireLaunchWrap?.();
}
@@ -147,6 +147,7 @@ export interface ProviderSnapshotEntry {
/** The page that helps users set up and troubleshoot this provider. */
docsUrl?: string;
defaultModeId?: string | null;
launchWrap?: boolean;
}
export interface AgentCreateConfigParent {
@@ -677,6 +678,8 @@ export interface AgentLaunchContext {
mcpServerOwners?: Record<string, string>;
agentId?: string;
env?: Record<string, string>;
/** Spawn the harness as `[...wrap, command, ...args]`. Selected by a plugin hook; never persisted. */
wrap?: readonly [string, ...string[]];
/**
* Runtime-only internal Paseo tools. This must never be persisted into
* AgentSessionConfig; providers may adapt it to their native tool surface.
@@ -884,6 +887,10 @@ export interface AgentClient {
>;
readonly provider: AgentProvider;
readonly capabilities: AgentCapabilityFlags;
/** Sessions honor `AgentLaunchContext.wrap`. The provider registry sets it from the provider contract. */
supportsLaunchWrap?: boolean;
/** Throw unless the live provider runtime can apply a wrap. Plugin providers connect to learn it. */
requireLaunchWrap?(): Promise<void>;
/**
* Create the agent with `config.providerOptions` (defaults already merged in). Emit nothing
* about options while creating. If the agent ended up different from the options, say so in the
@@ -1,3 +1,4 @@
import type { PluginLifecycle } from "../plugins/lifecycle/index.js";
import type { CreatePaseoWorktreeInput } from "../paseo-worktree-service.js";
import { randomUUID } from "node:crypto";
import type pino from "pino";
@@ -47,6 +48,7 @@ interface CreateAgentLifecycleDispatchDependencies {
clearWorkspaceArchiving: (workspaceIds: Iterable<string>) => void;
killTerminalsForWorkspace: (workspaceId: string) => Promise<void>;
logger: pino.Logger;
lifecycle: Pick<PluginLifecycle, "before"> | null;
}
export interface LifecycleRegistration {
@@ -192,6 +194,7 @@ export class CreateAgentLifecycleDispatch {
await archiveByScope(
{
lifecycle: this.dependencies.lifecycle,
paseoHome: this.dependencies.paseoHome,
paseoWorktreesBaseRoot: this.dependencies.worktreesRoot,
worktreeManagers: this.dependencies.worktreeManagers,
@@ -8,6 +8,7 @@ import {
import { CallToolResultSchema, type Tool } from "@modelcontextprotocol/sdk/types.js";
import type { McpServerConfig } from "./agent-sdk-types.js";
import type { PaseoToolResult } from "./tools/types.js";
import { applyLaunchWrap, type LaunchWrap } from "../../utils/launch-wrap.js";
const SERVER_TIMEOUT_MS = 10_000;
const TERMINATE_TIMEOUT_MS = 2_000;
@@ -36,6 +37,8 @@ export interface ConnectMcpServerInput {
cwd: string;
/** Complete environment for a stdio server; the server's own `env` overlays it. */
env: NodeJS.ProcessEnv;
/** Start a stdio server as `[...wrap, command, ...args]`. */
wrap?: LaunchWrap;
clientName: string;
}
@@ -165,11 +168,12 @@ async function withDeadline<T>(
}
}
function createTransport({ config, cwd, env }: ConnectMcpServerInput) {
function createTransport({ config, cwd, env, wrap }: ConnectMcpServerInput) {
if (config.type === "stdio") {
const launch = applyLaunchWrap({ command: config.command, args: config.args ?? [] }, wrap);
return new StdioClientTransport({
command: config.command,
args: config.args,
command: launch.command,
args: launch.args,
cwd,
env: definedEnvironment({ ...env, ...config.env }),
stderr: "ignore",
@@ -8,6 +8,7 @@ import { execFileSync } from "node:child_process";
import { fileURLToPath } from "node:url";
import { runAcpProvider, type AcpStreamMessage } from "@getpaseo/plugin/server/acp";
import type {
ProviderCapability,
ProviderConnection,
ProviderLaunch,
ProviderEvent,
@@ -313,6 +314,7 @@ function createRewindProviderHarness(
reuseAnswerId?: boolean;
forkOnRevert?: boolean;
handleInput?: ProviderHarnessOptions["handleInput"];
extraCapabilities?: ProviderCapability[];
} = {},
) {
const nativeMessages: string[] = [];
@@ -324,6 +326,7 @@ function createRewindProviderHarness(
"session.revert.conversation",
"session.revert.files",
"session.revert.both",
...(options.extraCapabilities ?? []),
],
async handleInput(input, emit) {
if (await options.handleInput?.(input, emit)) return true;
@@ -3680,3 +3683,54 @@ test("bounds settings wait when Stop is queued behind an unanswered steer", asyn
await plugins.shutdown();
}
});
test("a declared launch wrap still needs session.launch_wrap on the live connection", async () => {
const harness = createProviderHarness();
const registry = new PluginAgentClientRegistry(createTestLogger());
registry.replace([{ ...harness.registration, launchWrap: true }]);
expect(registry.definitions()[harness.registration.id]?.supportsLaunchWrap).toBe(true);
const client = registry.clients()[harness.registration.id]!;
expect(client.supportsLaunchWrap).toBe(true);
await expect(client.requireLaunchWrap?.()).rejects.toMatchObject({
code: "launch_wrap_unsupported",
});
await expect(
client.createSession(
{ provider: harness.registration.id, cwd: tmpdir() },
{ wrap: ["/opt/sandbox/bin/run"] },
),
).rejects.toThrow("session.launch_wrap");
expect(harness.inputs.some((input) => input.type === "session.open")).toBe(false);
await registry.shutdown();
});
test("a provider that declares no launch wrap is not marked as supporting it", () => {
const harness = createProviderHarness();
const registry = new PluginAgentClientRegistry(createTestLogger());
registry.replace([harness.registration]);
expect(registry.definitions()[harness.registration.id]?.supportsLaunchWrap).toBe(false);
expect(registry.clients()[harness.registration.id]!.supportsLaunchWrap).toBe(false);
});
test("a plugin session reopen sends the wrap the session opened with", async () => {
const harness = createRewindProviderHarness({ extraCapabilities: ["session.launch_wrap"] });
const registry = new PluginAgentClientRegistry(createTestLogger());
registry.replace([{ ...harness.registration, launchWrap: true }]);
const client = registry.clients()[harness.registration.id]!;
await expect(client.requireLaunchWrap?.()).resolves.toBeUndefined();
const wrap: [string, ...string[]] = ["/opt/sandbox/bin/run", "--profile", "a b"];
const session = await client.createSession(
{ provider: harness.registration.id, cwd: tmpdir() },
{ wrap },
);
await session.run("A");
await session.revertConversation!({ messageId: "user-A" });
const opens = harness.inputs.filter((input) => input.type === "session.open");
expect(opens.length).toBeGreaterThanOrEqual(2);
for (const open of opens) expect(open.config.wrap).toEqual(wrap);
await session.close();
await registry.shutdown();
});
@@ -81,6 +81,7 @@ import {
formatProviderDiagnostic,
type DiagnosticEntry,
} from "./providers/diagnostic-utils.js";
import { LaunchWrapUnsupportedError } from "./provider-options.js";
import type { RegisteredProviderDefinition } from "./provider-registry.js";
import { runProviderTurn } from "./providers/provider-runner.js";
import { StaleProviderSessionError } from "./stale-provider-session-error.js";
@@ -296,6 +297,11 @@ class ProviderRuntime {
return this.connection?.capabilities ?? [];
}
/** The live connection's capabilities, connecting first when no connection exists yet. */
async connectedCapabilities(): Promise<readonly string[]> {
return (await this.getConnection()).capabilities;
}
get isClosed(): boolean {
return this.closed;
}
@@ -1052,6 +1058,7 @@ function createPluginProviderDefinition(
defaultModeId: null,
modes: [],
supportsExactMcpPreapproval: true,
supportsLaunchWrap: registration.launchWrap === true,
createClient,
};
}
@@ -1070,10 +1077,12 @@ class PluginAgentClient implements AgentClient {
readonly getCatalogCacheKey?: AgentClient["getCatalogCacheKey"];
readonly installation?: AgentClientInstallation;
readonly supportsLaunchWrap: boolean;
constructor(registration: ProviderRegistration, runtimeSettings?: ProviderRuntimeSettings) {
this.provider = registration.id;
this.label = registration.label;
this.supportsLaunchWrap = registration.launchWrap === true;
this.runtime = new ProviderRuntime(registration, runtimeSettings);
if (registration.getCatalogCacheKey)
this.getCatalogCacheKey = (options) => this.runtime.catalogCacheKey(options);
@@ -1101,6 +1110,15 @@ class PluginAgentClient implements AgentClient {
return agentCapabilities(this.runtime.negotiatedCapabilities);
}
async requireLaunchWrap(): Promise<void> {
if (!(await this.runtime.connectedCapabilities()).includes("session.launch_wrap")) {
throw new LaunchWrapUnsupportedError(
this.provider,
`Provider '${this.provider}' declares launch wrap support, but its connection does not offer session.launch_wrap`,
);
}
}
async createSession(
config: AgentSessionConfig,
launchContext?: AgentLaunchContext,
@@ -2143,6 +2161,7 @@ function mapSessionConfig(
providerOptions: config.providerOptions,
title: config.title ?? undefined,
persist,
...(launchContext?.wrap ? { wrap: launchContext.wrap } : {}),
};
}
@@ -37,6 +37,18 @@ export class ToolPolicyUnsupportedError extends Error {
}
}
export class LaunchWrapUnsupportedError extends Error {
readonly code = "launch_wrap_unsupported" as const;
constructor(
readonly provider: string,
reason?: string,
) {
super(reason ?? `Provider '${provider}' cannot run a session behind a launch wrap`);
this.name = "LaunchWrapUnsupportedError";
}
}
export function validateProviderOptions<T extends ProviderOptions>(
provider: string,
schema: z.ZodType<T>,
@@ -645,6 +645,32 @@ test("new provider extending codex archives and unarchives its native sessions",
]);
});
test("launch-wrap support comes from the provider contract and follows extends", () => {
const registry = buildProviderRegistry(logger, {
isDev: true,
providerOverrides: {
"my-claude": { extends: "claude", label: "My Claude" },
"my-acp": { extends: "acp", label: "My ACP", command: ["my-acp", "--acp"] },
},
});
const support = Object.fromEntries(
Object.keys(registry).map((id) => [id, registry[id].createClient(logger).supportsLaunchWrap]),
);
expect(support).toEqual({
claude: true,
codex: true,
copilot: true,
opencode: true,
pi: true,
omp: true,
mock: false,
"mock-slow": false,
"my-claude": true,
"my-acp": true,
});
});
test("built-in OMP override keeps the real OMP adapter enabled and launchable", async () => {
const omp = new FakeOmp(["custom-omp"]);
const registry = buildProviderRegistry(logger, {
@@ -78,6 +78,7 @@ export interface ProviderDefinition extends AgentProviderDefinition {
*/
derivedFromProviderId: string | null;
supportsExactMcpPreapproval: boolean;
supportsLaunchWrap: boolean;
applyToolPolicy: (
config: AgentSessionConfig,
toolPolicy: ToolPolicy | undefined,
@@ -101,6 +102,7 @@ export interface RegisteredProviderDefinition extends AgentProviderDefinition {
requiresConfiguration?: boolean;
iconSvg?: string;
supportsExactMcpPreapproval: boolean;
supportsLaunchWrap: boolean;
createClient: (logger: Logger, runtimeSettings?: ProviderRuntimeSettings) => AgentClient;
}
@@ -148,25 +150,38 @@ interface ResolvedProvider {
interface ProviderContract {
supportsExactMcpPreapproval: boolean;
/** Sessions spawn their harness behind an `agent.open.before` wrap. */
supportsLaunchWrap?: boolean;
applyToolPolicy?: (provider: string, toolPolicy: ToolPolicy) => ToolPolicy;
}
// Every built-in provider that starts a local harness honors a wrap; the mock providers start none.
const PROVIDER_CONTRACTS: Record<string, ProviderContract> = {
claude: { supportsExactMcpPreapproval: true },
codex: { supportsExactMcpPreapproval: true },
opencode: { supportsExactMcpPreapproval: true },
claude: { supportsExactMcpPreapproval: true, supportsLaunchWrap: true },
codex: { supportsExactMcpPreapproval: true, supportsLaunchWrap: true },
copilot: { supportsExactMcpPreapproval: false, supportsLaunchWrap: true },
opencode: { supportsExactMcpPreapproval: true, supportsLaunchWrap: true },
pi: { supportsExactMcpPreapproval: false, supportsLaunchWrap: true },
omp: { supportsExactMcpPreapproval: false, supportsLaunchWrap: true },
};
const UNSUPPORTED_PROVIDER_CONTRACT: ProviderContract = {
supportsExactMcpPreapproval: false,
};
// A user-defined ACP provider is a local command, which starts behind the wrap.
const CUSTOM_ACP_PROVIDER_CONTRACT: ProviderContract = {
supportsExactMcpPreapproval: false,
supportsLaunchWrap: true,
};
const HUB_E2E_PROVIDER_ID = "hub-e2e";
const HUB_E2E_MCP_SERVER = "hub";
const HUB_E2E_TOOL_NAME = /^[A-Za-z0-9][A-Za-z0-9_.-]*$/u;
// The cross-repository Hub harness owns this synthetic provider ID. It exercises the production
// registry path without extending exact-preapproval support to user-defined ACP providers.
const HUB_E2E_PROVIDER_CONTRACT: ProviderContract = {
...CUSTOM_ACP_PROVIDER_CONTRACT,
supportsExactMcpPreapproval: true,
applyToolPolicy: (provider, toolPolicy) => {
for (const grant of toolPolicy.preapproved) {
@@ -498,6 +513,7 @@ function wrapClientProvider(
additionalModels: ProviderProfileModel[],
profileModelsAreAdditive: boolean,
configuredOptions: ProviderOptions | undefined,
supportsLaunchWrap: boolean,
): AgentClient {
const listImportableSessions = inner.listImportableSessions?.bind(inner);
const importSession = inner.importSession?.bind(inner);
@@ -517,6 +533,7 @@ function wrapClientProvider(
get capabilities() {
return inner.capabilities;
},
supportsLaunchWrap,
shutdown: inner.shutdown?.bind(inner),
createSession: async (config, launchContext, options) =>
wrapSessionProvider(
@@ -626,6 +643,7 @@ function wrapClientProvider(
? async (handle) => await unarchiveNativeSession({ ...handle, provider: inner.provider })
: undefined,
resolveUsageLaunch: inner.resolveUsageLaunch?.bind(inner),
requireLaunchWrap: inner.requireLaunchWrap?.bind(inner),
getCatalogCacheKey: inner.getCatalogCacheKey?.bind(inner),
isAvailable: (signal, options) => inner.isAvailable(signal, options),
getDiagnostic: inner.getDiagnostic?.bind(inner),
@@ -670,6 +688,7 @@ function createRegistryEntry(
enabled: resolved.enabled,
derivedFromProviderId: resolved.derivedFromProviderId,
supportsExactMcpPreapproval: resolved.contract.supportsExactMcpPreapproval,
supportsLaunchWrap: resolved.contract.supportsLaunchWrap === true,
applyToolPolicy: (config, toolPolicy) => {
if (toolPolicy && !resolved.contract.supportsExactMcpPreapproval) {
throw new ToolPolicyUnsupportedError(provider);
@@ -747,6 +766,7 @@ function createResolvedProviderClient(
additionalModels,
resolved.profileModelsAreAdditive,
resolved.providerOptions,
resolved.contract.supportsLaunchWrap === true,
);
}
@@ -880,7 +900,7 @@ function addDerivedProviders(
contract:
providerId === HUB_E2E_PROVIDER_ID
? HUB_E2E_PROVIDER_CONTRACT
: UNSUPPORTED_PROVIDER_CONTRACT,
: CUSTOM_ACP_PROVIDER_CONTRACT,
});
continue;
}
@@ -962,6 +982,7 @@ export function buildProviderRegistry(
createClient: definition.createClient,
contract: {
supportsExactMcpPreapproval: definition.supportsExactMcpPreapproval,
supportsLaunchWrap: definition.supportsLaunchWrap,
},
}),
);
@@ -542,6 +542,23 @@ describe("ProviderSnapshotManager public surface", () => {
}
});
test("loading entries already report launch-wrap support, before any discovery", () => {
const manager = new ProviderSnapshotManager({
logger: createTestLogger(),
providerOverrides: { "my-codex": { extends: "codex", label: "My Codex" } },
});
try {
const snapshot = manager.getSnapshot("/tmp/project").records.map(({ entry }) => entry);
const byProvider = (provider: string) =>
snapshot.find((entry) => entry.provider === provider);
expect(byProvider("codex")).toMatchObject({ status: "loading", launchWrap: true });
expect(byProvider("my-codex")).toMatchObject({ status: "loading", launchWrap: true });
expect(byProvider("claude")).toMatchObject({ status: "loading", launchWrap: true });
} finally {
manager.destroy();
}
});
test("providerOverrides with enabled:false marks the provider as unavailable without probing", async () => {
const isAvailable = vi.fn(async () => true);
const fetchCatalog = vi.fn(async () => ({
@@ -1044,6 +1044,7 @@ export class ProviderSnapshotManager {
iconSvg: definition.iconSvg,
docsUrl: definition.docsUrl,
defaultModeId: definition.defaultModeId ?? null,
...(definition.supportsLaunchWrap ? { launchWrap: true } : {}),
}),
});
}
@@ -5864,3 +5864,64 @@ describe("custom ACP provider with configured models", () => {
expect((await created.getRuntimeInfo()).model).toBe("advertised-default");
});
});
describe("ACPAgentSession launch wrap against an ACP agent", () => {
const fakeAgentPath = fileURLToPath(new URL("./test-utils/fake-acp-agent.mjs", import.meta.url));
test("starts the agent and its terminals behind the session's wrap", async () => {
const root = await mkdtemp(path.join(tmpdir(), "paseo-acp-wrap-"));
const record = path.join(root, "launches.jsonl");
const launcher = path.join(root, "launcher.cjs");
await writeFile(
launcher,
`
const [, , ...argv] = process.argv;
require("node:fs").appendFileSync(${JSON.stringify(record)}, JSON.stringify(argv) + "\\n");
const child = require("node:child_process").spawn(argv[0], argv.slice(1), { stdio: "inherit" });
child.on("exit", (code) => process.exit(code ?? 1));
`,
);
const session = new ACPAgentSession(
{ provider: "acp", cwd: root },
{
provider: "acp",
logger: createTestLogger(),
defaultCommand: [process.execPath, fakeAgentPath, "{}"],
defaultModes: [],
capabilities: {
supportsStreaming: true,
supportsSessionPersistence: true,
supportsDynamicModes: true,
supportsMcpServers: true,
supportsReasoningStream: true,
supportsToolInvocations: true,
},
wrap: [process.execPath, launcher],
},
);
try {
await session.initializeNewSession();
const { terminalId } = await session.createTerminal({
sessionId: "session-1",
command: process.execPath,
args: ["-e", "process.exit(0)"],
cwd: root,
});
await expect(
session.waitForTerminalExit({ sessionId: "session-1", terminalId }),
).resolves.toMatchObject({ exitCode: 0 });
const launches = (await readFile(record, "utf8"))
.trim()
.split("\n")
.map((line) => JSON.parse(line));
expect(launches).toEqual([
[process.execPath, fakeAgentPath, "{}"],
[process.execPath, "-e", "process.exit(0)"],
]);
} finally {
await session.close();
await rm(root, { recursive: true, force: true });
}
});
});
@@ -548,6 +548,8 @@ interface ACPAgentSessionOptions {
configuredModelIds?: readonly string[];
agentId?: string;
launchEnv?: Record<string, string>;
/** Start the agent, and every terminal it asks for, as `[...wrap, command, ...args]`. */
wrap?: AgentLaunchContext["wrap"];
waitForInitialCommands?: boolean;
initialCommandsWaitTimeoutMs?: number;
terminateProcess?: ProcessTerminator;
@@ -1152,6 +1154,7 @@ export class ACPAgentClient implements AgentClient {
configuredModelIds: options?.configuredModelIds,
agentId: launchContext?.agentId,
launchEnv: launchContext?.env,
wrap: launchContext?.wrap,
extensionCommandsParser: this.extensionCommandsParser,
waitForInitialCommands: this.waitForInitialCommands,
initialCommandsWaitTimeoutMs: this.initialCommandsWaitTimeoutMs,
@@ -1212,6 +1215,7 @@ export class ACPAgentClient implements AgentClient {
configuredModelIds: options?.configuredModelIds,
agentId: launchContext?.agentId,
launchEnv: launchContext?.env,
wrap: launchContext?.wrap,
extensionCommandsParser: this.extensionCommandsParser,
waitForInitialCommands: this.waitForInitialCommands,
initialCommandsWaitTimeoutMs: this.initialCommandsWaitTimeoutMs,
@@ -1951,6 +1955,7 @@ export class ACPAgentSession implements AgentSession, ACPClient {
) => Promise<void>;
private readonly agentId?: string;
private readonly launchEnv?: Record<string, string>;
private readonly wrap?: AgentLaunchContext["wrap"];
private readonly usageProvider?: string;
private readonly usageSessionKey = randomUUID();
private readonly harnessEnvironment: Record<string, string>;
@@ -2023,6 +2028,7 @@ export class ACPAgentSession implements AgentSession, ACPClient {
this.availableModes = options.defaultModes;
this.agentId = options.agentId;
this.launchEnv = options.launchEnv;
this.wrap = options.wrap;
this.usageProvider = options.usageProvider;
this.harnessEnvironment = createProviderEnv({
runtimeSettings: options.runtimeSettings,
@@ -3117,7 +3123,9 @@ export class ACPAgentSession implements AgentSession, ACPClient {
terminalCommand.shell === false
? [this.launchEnv, env, createStringCommandShellEnvOverlay()]
: [this.launchEnv, env];
// A terminal runs commands for the agent, so it runs behind the agent's wrap too.
const child = spawnProcess(terminalCommand.command, terminalCommand.args, {
wrap: this.wrap,
cwd: params.cwd ?? this.config.cwd,
...createProviderEnvSpec({
runtimeSettings: this.runtimeSettings,
@@ -3222,6 +3230,7 @@ export class ACPAgentSession implements AgentSession, ACPClient {
const command = prefix.command;
const args = [...prefix.args, ...this.defaultCommand.slice(1)];
const child = spawnProcess(command, args, {
wrap: this.wrap,
cwd: await this.resolveProcessCwd(),
...createProviderEnvSpec({
runtimeSettings: this.runtimeSettings,
@@ -1,4 +1,7 @@
import { EventEmitter } from "node:events";
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { PassThrough } from "node:stream";
import type { ChildProcess } from "node:child_process";
import {
@@ -173,4 +176,49 @@ describe("Claude spawn override", () => {
expect(launchArgs?.join(" ")).not.toContain("secret-token");
expect(launchArgs).not.toContain("--mcp-config");
});
test("starts Claude Code behind the session's launch wrap", async () => {
const root = await mkdtemp(path.join(os.tmpdir(), "claude-launch-wrap-"));
const launcher = path.join(root, "launcher.mjs");
await writeFile(launcher, "process.stdout.write(JSON.stringify(process.argv.slice(2)));\n");
let capturedOptions: Options | undefined;
const client = new ClaudeAgentClient({
logger: createTestLogger(),
queryFactory: ({ options }: ClaudeQueryInput) => {
capturedOptions = options;
return createQueryMock([]);
},
resolveBinary: async () => "/test/claude/bin",
resolveVersion: async () => "2.1.326",
});
const session = await client.createSession(
{ provider: "claude", cwd: root },
{ wrap: [process.execPath, launcher, "--sandbox"] },
);
try {
await (session as unknown as { ensureQuery(): Promise<unknown> }).ensureQuery();
const child = capturedOptions?.spawnClaudeCodeProcess?.({
command: "/test/claude/bin",
args: ["--output-format", "stream-json"],
cwd: root,
env: {},
signal: new AbortController().signal,
}) as ChildProcess | undefined;
if (!child?.stdout) throw new Error("Claude Code was not spawned");
let stdout = "";
child.stdout.on("data", (chunk: Buffer) => {
stdout += chunk.toString("utf8");
});
await new Promise((resolve) => child.once("close", resolve));
expect(JSON.parse(stdout)).toEqual([
"--sandbox",
"/test/claude/bin",
"--output-format",
"stream-json",
]);
} finally {
await session.close();
await rm(root, { recursive: true, force: true });
}
});
});
@@ -515,6 +515,7 @@ interface ClaudeAgentSessionOptions {
handle?: AgentPersistenceHandle;
agentId?: string;
launchEnv?: Record<string, string>;
wrap?: AgentLaunchContext["wrap"];
persistSession?: boolean;
logger: Logger;
queryFactory?: ClaudeQueryFactory;
@@ -1713,6 +1714,7 @@ export class ClaudeAgentClient implements AgentClient {
runtimeSettings: this.runtimeSettings,
agentId: launchContext?.agentId,
launchEnv: launchContext?.env,
wrap: launchContext?.wrap,
persistSession: options?.persistSession,
logger: this.logger,
queryFactory: this.queryFactory,
@@ -1745,6 +1747,7 @@ export class ClaudeAgentClient implements AgentClient {
handle,
agentId: launchContext?.agentId,
launchEnv: launchContext?.env,
wrap: launchContext?.wrap,
logger: this.logger,
queryFactory: this.queryFactory,
resolveBinary: this.resolveBinary,
@@ -2457,6 +2460,7 @@ class ClaudeAgentSession implements AgentSession {
private readonly config: ClaudeAgentConfig;
private readonly launchEnv?: Record<string, string>;
private readonly wrap?: AgentLaunchContext["wrap"];
private readonly agentId?: string;
private readonly defaults?: { agents?: Record<string, AgentDefinition> };
private readonly runtimeSettings?: ProviderRuntimeSettings;
@@ -2596,6 +2600,7 @@ class ClaudeAgentSession implements AgentSession {
this.config = config;
assertClaudeThinkingOptionSupported(config.model, config.thinkingOptionId);
this.launchEnv = options.launchEnv;
this.wrap = options.wrap;
this.agentId = options.agentId;
this.defaults = options.defaults;
this.runtimeSettings = options.runtimeSettings;
@@ -3887,6 +3892,7 @@ class ClaudeAgentSession implements AgentSession {
{
runtimeSettings: this.runtimeSettings,
launchEnv: this.launchEnv,
wrap: this.wrap,
queryFactory: this.queryFactory,
onChildProcess: (child) => {
this.childProcess = child;
@@ -7,6 +7,7 @@ import {
} from "../../provider-launch-config.js";
import { buildSelfNodeCommand, createExternalProcessEnv } from "../../../paseo-env.js";
import { execCommand, spawnProcess } from "../../../../utils/spawn.js";
import type { AgentLaunchContext } from "../../agent-sdk-types.js";
// Keep the raw SDK query import in this module only. Claude process launch behavior
// must stay shared between production and tests so Windows .cmd/.bat handling cannot
@@ -19,6 +20,8 @@ export type ClaudeQueryFactory = (input: ClaudeQueryInput) => Query;
export interface ClaudeQueryContext {
runtimeSettings?: ProviderRuntimeSettings;
launchEnv?: Record<string, string>;
/** Start Claude Code as `[...wrap, command, ...args]`. */
wrap?: AgentLaunchContext["wrap"];
queryFactory?: ClaudeQueryFactory;
/** Called with the spawned child process so the caller can tree-kill it on close. */
onChildProcess?: (child: ChildProcess) => void;
@@ -90,7 +93,7 @@ function applyRuntimeSettingsToClaudeOptions(
options: ClaudeOptions,
context: ClaudeQueryContext,
): ClaudeOptions {
const { runtimeSettings, onChildProcess } = context;
const { runtimeSettings, onChildProcess, wrap } = context;
return {
...options,
spawnClaudeCodeProcess: (spawnOptions) => {
@@ -109,6 +112,7 @@ function applyRuntimeSettingsToClaudeOptions(
const command = selfNodeCommand?.command ?? resolved.command;
const args = selfNodeCommand?.args ?? resolved.args;
const child = spawnProcess(command, args, {
wrap,
cwd: spawnOptions.cwd,
...(selfNodeCommand
? { env: selfNodeCommand.env, envMode: "internal" as const }
@@ -1,3 +1,4 @@
import { spawnProcess } from "../../../utils/spawn.js";
import { describe, expect, test, vi } from "vitest";
import { CodexAppServerAgentClient } from "./codex-app-server-agent.js";
@@ -80,4 +81,35 @@ describe("CodexAppServerAgentClient spawn error handling", () => {
process.off("uncaughtException", onUncaught);
}
});
test("a missing launch wrap fails the open and never starts the bare codex command", async () => {
const spawned: Array<{ command: string; args: string[]; wrap?: readonly string[] }> = [];
const client = new CodexAppServerAgentClient(logger, undefined, {
appServerProcess: {
resolvePrefix: async () => ({ command: process.execPath, args: ["codex.js"] }),
spawn: ({ command, args, options }) => {
spawned.push({ command, args, wrap: options.wrap });
return spawnProcess(command, args, options);
},
},
});
// Skip the host-side version probes; they are not session spawns.
Object.assign(client, {
goalsEnabledPromise: Promise.resolve(false),
autoReviewEnabledPromise: Promise.resolve(false),
});
await expect(
client.createSession(
{ provider: "codex", cwd: "/tmp/codex-wrap" },
{ wrap: ["/nonexistent/launch-wrap-that-does-not-exist", "--flag"] },
),
).rejects.toThrow(/ENOENT/u);
expect(spawned).toEqual([
{
command: process.execPath,
args: ["codex.js", "app-server"],
wrap: ["/nonexistent/launch-wrap-that-does-not-exist", "--flag"],
},
]);
});
});
@@ -2492,6 +2492,60 @@ describe("Codex app-server provider", () => {
appServer.assertNoErrors();
});
test.each(["interactive", "history"] as const)(
"spawns a wrapped %s resume through the launch wrap",
async (purpose) => {
const spawned: Array<{ command: string; args: string[]; wrap?: readonly string[] }> = [];
let resumes = 0;
// History reads the archived thread; an interactive resume unarchives it and resumes again.
const appServer = createFakeCodexAppServer({
"thread/loaded/list": () => ({ data: [] }),
"thread/resume": () =>
resumes++ === 0
? Promise.reject(new Error(archivedThreadErrorMessage("archived-thread-id")))
: { thread: { id: "archived-thread-id" } },
"thread/unarchive": () => ({ thread: { id: "archived-thread-id" } }),
"thread/read": () => ({ thread: { turns: [] } }),
});
const provider = new CodexAppServerAgentClient(createTestLogger(), undefined, {
appServerProcess: {
resolvePrefix: async () => ({
command: "/opt/codex/bin/codex",
args: ["--profile", "x"],
}),
spawn: ({ command, args, options }) => {
spawned.push({ command, args, wrap: options.wrap });
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,
{ wrap: ["/opt/sandbox/bin/run", "--profile", "a b"] },
{ purpose },
);
expect(spawned.length).toBeGreaterThan(0);
for (const input of spawned) {
expect(input).toEqual({
command: "/opt/codex/bin/codex",
args: ["--profile", "x", "app-server"],
wrap: ["/opt/sandbox/bin/run", "--profile", "a b"],
});
}
await session.close();
appServer.assertNoErrors();
},
);
test("unarchives Codex when an active Paseo agent resumes an archived thread", async () => {
const threadRequests: string[] = [];
let resumeAttempts = 0;
@@ -8272,6 +8272,7 @@ export class CodexAppServerAgentClient implements AgentClient {
environment: Record<string, string>;
goalsEnabled?: boolean;
agentId?: string;
wrap?: AgentLaunchContext["wrap"];
}): Promise<() => ChildProcessWithoutNullStreams> {
const processPort = this.deps.appServerProcess ?? defaultCodexAppServerProcess;
const launchPrefix = await processPort.resolvePrefix({ runtimeSettings: this.runtimeSettings });
@@ -8285,14 +8286,17 @@ export class CodexAppServerAgentClient implements AgentClient {
agentId: options.agentId,
provider: CODEX_PROVIDER,
launchPrefix,
wrap: options.wrap,
goalsEnabled: options.goalsEnabled === true,
},
"provider.codex.spawn",
);
// Every spawn from this closure, including reconnects and startup retries, carries the wrap.
const child = processPort.spawn({
command: launchPrefix.command,
args,
options: {
wrap: options.wrap,
detached: process.platform !== "win32",
stdio: ["pipe", "pipe", "pipe"],
baseEnv: options.environment,
@@ -8339,6 +8343,7 @@ export class CodexAppServerAgentClient implements AgentClient {
environment,
goalsEnabled,
agentId: launchContext?.agentId,
wrap: launchContext?.wrap,
});
const session = new CodexAppServerAgentSession(
sessionConfig,
@@ -8376,6 +8381,7 @@ export class CodexAppServerAgentClient implements AgentClient {
environment,
goalsEnabled,
agentId: launchContext?.agentId,
wrap: launchContext?.wrap,
});
const session = new CodexAppServerAgentSession(
merged,
@@ -23,6 +23,8 @@ export interface JsonlRpcLaunch {
args: string[];
cwd: string;
env?: Record<string, string>;
/** Start the process as `[...wrap, command, ...args]`. */
wrap?: readonly [string, ...string[]];
}
interface JsonlRpcResponse {
@@ -64,6 +66,7 @@ function assertChildWithPipes(
function spawnJsonlRpcProcess(launch: JsonlRpcLaunch): ChildProcessWithoutNullStreams {
const child = spawnProcess(launch.command, launch.args, {
wrap: launch.wrap,
cwd: launch.cwd,
envOverlay: launch.env,
stdio: ["pipe", "pipe", "pipe"],
@@ -433,6 +433,7 @@ function buildResumeStartInput(input: {
cwd: input.resumeConfig.cwd,
protocolMode: "rpc-ui",
env: input.launchContext?.env,
wrap: input.launchContext?.wrap,
session: input.sessionFile,
thinkingOptionId: normalizeOmpThinkingOption(input.resumeConfig.thinkingOptionId) ?? undefined,
...(input.launchMode.modeId ? { modeId: input.launchMode.modeId } : {}),
@@ -2356,15 +2357,18 @@ export class OmpAgentClient implements AgentClient {
runtimeSession: OmpRuntimeSession,
catalog: PaseoToolCatalog | undefined,
config: AgentSessionConfig,
launchEnv?: NodeJS.ProcessEnv,
launch: Pick<OmpStartSessionInput, "env" | "wrap">,
): Promise<OmpHostToolRouter | undefined> {
if (!catalog && !config.mcpServers) {
return;
}
const bridge = await OmpMcpBridge.connect(config.mcpServers, config.cwd, this.logger, {
...process.env,
...this.runtimeSettings?.env,
...launchEnv,
// Paseo starts stdio MCP servers for OMP, so they run behind the agent's wrap as OMP does.
const bridge = await OmpMcpBridge.connect({
servers: config.mcpServers,
cwd: config.cwd,
logger: this.logger,
env: { ...process.env, ...this.runtimeSettings?.env, ...launch.env },
wrap: launch.wrap,
});
const router = new OmpHostToolRouter({ runtimeSession, catalog, bridge, logger: this.logger });
try {
@@ -2407,6 +2411,7 @@ export class OmpAgentClient implements AgentClient {
...(config.pluginAppendSystemPrompt ?? []),
),
env: launchContext?.env,
wrap: launchContext?.wrap,
};
const runtimeSession = await this.resolveRuntime(config.providerOptions).startSession(
startInput,
@@ -2417,7 +2422,7 @@ export class OmpAgentClient implements AgentClient {
runtimeSession,
launchContext?.paseoTools,
config,
startInput.env,
startInput,
);
const initialState = await this.restoreFastMode(
runtimeSession,
@@ -2487,7 +2492,7 @@ export class OmpAgentClient implements AgentClient {
runtimeSession,
launchContext?.paseoTools,
resumeConfig.config,
startInput.env,
startInput,
);
const resumedState = await this.applyResumeModel(runtimeSession, resumeConfig.model);
const config = {
@@ -2566,7 +2571,7 @@ export class OmpAgentClient implements AgentClient {
next,
launchContext?.paseoTools,
config,
startInput.env,
startInput,
);
const state = await next.getState();
await this.restoreFastMode(next, config, state);
@@ -1,5 +1,8 @@
import type { ChildProcessWithoutNullStreams } from "node:child_process";
import { EventEmitter } from "node:events";
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { PassThrough } from "node:stream";
import pino from "pino";
import { describe, expect, test, vi } from "vitest";
@@ -121,6 +124,54 @@ function withoutRequestId(command: Record<string, unknown>): Record<string, unkn
}
describe("OMP CLI runtime", () => {
test("starts OMP behind the session's launch wrap and negotiates through the wrap", async () => {
const root = await mkdtemp(path.join(os.tmpdir(), "omp-launch-wrap-"));
try {
const fakeOmp = path.join(root, "fake-omp.mjs");
await writeFile(
fakeOmp,
[
'import { createInterface } from "node:readline";',
'const ready = { type: "ready", protocolVersion: 1, supportedProtocolVersions: [1], maxFrameBytes: 1048576, maxReassembledFrameBytes: 67108864 };',
'process.stdout.write(JSON.stringify(ready) + "\\n");',
'createInterface({ input: process.stdin }).on("line", () => undefined);',
"",
].join("\n"),
);
const launcher = path.join(root, "launcher.mjs");
await writeFile(
launcher,
[
'import { spawn } from "node:child_process";',
'import { writeFileSync } from "node:fs";',
"const [command, ...args] = process.argv.slice(2);",
'writeFileSync(new URL("./wrapped.json", import.meta.url), JSON.stringify([command, ...args]));',
'const child = spawn(command, args, { stdio: "inherit" });',
'child.on("exit", (code) => process.exit(code ?? 1));',
"",
].join("\n"),
);
const runtime = new OmpCliRuntime({
logger: pino({ level: "silent" }),
command: [process.execPath, fakeOmp],
});
const session = await runtime.startSession({
cwd: root,
wrap: [process.execPath, launcher],
});
try {
expect(
JSON.parse(await readFile(path.join(root, "wrapped.json"), "utf8")).slice(0, 2),
).toEqual([process.execPath, fakeOmp]);
} finally {
await session.close();
}
} finally {
await rm(root, { recursive: true, force: true });
}
});
test("steer waits for OMP's response and surfaces rejection", async () => {
const child = createOmpChild();
let pending: Record<string, unknown> | null = null;
@@ -83,6 +83,7 @@ export class OmpCliRuntime implements OmpRuntime {
args,
cwd: launch.cwd,
env: launch.env,
wrap: launch.wrap,
};
const spawn = this.spawnProcess;
const processOptions = {
@@ -22,12 +22,15 @@ export class OmpMcpBridge {
private readonly connections: McpClientConnection[] = [];
private closed = false;
static async connect(
servers: Record<string, McpServerConfig> | undefined,
cwd: string,
logger: Logger,
env: NodeJS.ProcessEnv,
): Promise<OmpMcpBridge> {
static async connect(input: {
servers: Record<string, McpServerConfig> | undefined;
cwd: string;
logger: Logger;
env: NodeJS.ProcessEnv;
/** Start each stdio server as `[...wrap, command, ...args]`. */
wrap?: readonly [string, ...string[]];
}): Promise<OmpMcpBridge> {
const { servers, cwd, logger, env, wrap } = input;
const bridge = new OmpMcpBridge();
const connections = await Promise.all(
Object.entries(servers ?? {}).map(async ([serverName, config]) => {
@@ -36,6 +39,7 @@ export class OmpMcpBridge {
config,
cwd,
env,
wrap,
clientName: "paseo-omp-mcp",
});
return { serverName, connection };
@@ -18,6 +18,8 @@ export interface OmpRuntimeLaunch {
cwd: string;
argv: string[];
env?: Record<string, string>;
/** Start OMP as `[...wrap, ...argv]`. */
wrap?: readonly [string, ...string[]];
protocolMode?: "rpc" | "rpc-ui";
model?: string;
thinkingOptionId?: string;
@@ -32,6 +34,8 @@ export interface OmpStartSessionInput {
cwd: string;
signal?: AbortSignal;
env?: Record<string, string>;
/** The agent's launch wrap; every OMP process started for the agent runs behind it. */
wrap?: readonly [string, ...string[]];
protocolMode?: "rpc" | "rpc-ui";
model?: string;
thinkingOptionId?: string;
@@ -114,6 +118,7 @@ export function buildOmpLaunch(input: {
...input.session.env,
}
: undefined,
wrap: input.session.wrap,
model: input.session.model,
thinkingOptionId: input.session.thinkingOptionId,
protocolMode,
@@ -4563,6 +4563,47 @@ describe("OpenCode persisted sessions", () => {
]);
});
test("importSession reads a wrapped session on a server started behind the wrap", async () => {
const runtime = new TestOpenCodeHarness();
const metadataClient = new TestOpenCodeClient();
const resumedClient = new TestOpenCodeClient();
const cwd = "/workspace/repo";
const selectedSession = {
id: "ses_selected",
directory: cwd,
title: "Selected session",
time: { created: 2000, updated: 3000 },
};
metadataClient.sessionGetResponse = { data: selectedSession };
metadataClient.sessionMessagesResponse = { data: [] };
resumedClient.sessionGetResponse = { data: selectedSession };
resumedClient.sessionMessagesResponse = { data: [] };
runtime.enqueueClient(metadataClient);
runtime.enqueueClient(resumedClient);
const client = new OpenCodeAgentClient(createTestLogger(), undefined, {
serverManager: runtime,
createClient: runtime.createClient,
});
const wrap = ["/opt/sandbox/bin/run", "--profile", "import"] as const;
const imported = await client.importSession(
{ providerHandleId: "ses_selected", cwd },
{
config: { provider: "opencode", cwd },
storedConfig: { provider: "opencode", cwd },
launchContext: { env: { PASEO_AGENT_ID: "imported" }, wrap },
},
);
await imported.session.close();
expect(runtime.acquisitions.map((acquisition) => [acquisition.kind, acquisition.wrap])).toEqual(
[
["dedicated", wrap],
["dedicated", wrap],
],
);
});
test("listImportableSessions matches Windows cwd paths with forward slashes", async () => {
const runtime = new TestOpenCodeHarness();
const openCodeClient = new TestOpenCodeClient();
@@ -4749,6 +4790,52 @@ describe("OpenCode provider subagent contract", () => {
]);
});
test("resumes a wrapped child on its own server behind the wrap, not the parent's server", async () => {
const runtime = new TestOpenCodeHarness();
const parentClient = new TestOpenCodeClient();
const childClient = new TestOpenCodeClient();
parentClient.sessionCreateResponse = { data: { id: "ses_parent_wrapped" } };
runtime.enqueueClient(parentClient);
runtime.enqueueClient(childClient);
const client = new OpenCodeAgentClient(createTestLogger(), undefined, {
serverManager: runtime,
createClient: runtime.createClient,
});
const parent = await client.createSession(
{ provider: "opencode", cwd: "/workspace/repo" },
{ env: { PASEO_AGENT_ID: "parent-agent" } },
);
parentClient.emitEvent({
type: "session.created",
properties: {
info: { id: "ses_child_wrapped", parentID: "ses_parent_wrapped", title: "Live child" },
},
});
await Promise.resolve();
await Promise.resolve();
const wrap = ["/opt/sandbox/bin/run", "--profile", "child"] as const;
const child = await client.resumeSession(
{
provider: "opencode",
sessionId: "ses_child_wrapped",
nativeHandle: "ses_child_wrapped",
metadata: { cwd: "/workspace/repo" },
},
undefined,
{ env: { PASEO_AGENT_ID: "child-agent" }, wrap },
);
await child.close();
await parent.close();
expect(runtime.acquisitions.map((acquisition) => [acquisition.kind, acquisition.wrap])).toEqual(
[
["dedicated", undefined],
["dedicated", wrap],
],
);
});
test("synthesizes an autonomous turn for adopted child timeline events", async () => {
const { child, childClient, parent } = await createAdoptedChildSession();
const completed = createTestDeferred<void>();
@@ -79,6 +79,7 @@ import {
} from "../provider-launch-config.js";
import { withTimeout } from "../../../utils/promise-timeout.js";
import { execCommand } from "../../../utils/spawn.js";
import type { LaunchWrap } from "../../../utils/launch-wrap.js";
import { mapOpencodeToolCall } from "./opencode/tool-call-mapper.js";
import {
OPENCODE_EVENT_STREAM_READY_TIMEOUT_MS,
@@ -1537,7 +1538,10 @@ export class OpenCodeAgentClient implements AgentClient {
cwd,
};
const openCodeConfig = this.assertConfig(config);
const registeredServerUrl = getOpenCodeChildSessionServerUrl(handle.sessionId);
// A registered parent server runs outside this launch's wrap, so a wrapped resume starts its own.
const registeredServerUrl = launchContext?.wrap
? undefined
: getOpenCodeChildSessionServerUrl(handle.sessionId);
const registeredAcquisition = registeredServerUrl
? this.serverManager.acquireExisting(registeredServerUrl)
: null;
@@ -1617,14 +1621,25 @@ export class OpenCodeAgentClient implements AgentClient {
config: OpenCodeAgentConfig,
launchContext?: AgentLaunchContext,
): Promise<OpenCodeServerAcquisition> {
if (!this.bridge || requiresDedicatedOpenCodeServer(config, launchContext)) {
return launchContext?.env
? this.serverManager.acquireDedicated(launchContext.env)
: this.serverManager.acquireCurrent();
if (launchContext?.wrap)
return this.acquireWrappedServer(launchContext.wrap, launchContext.env);
if (
launchContext?.env &&
(!this.bridge || requiresDedicatedOpenCodeServer(config, launchContext))
) {
return this.serverManager.acquireDedicated({ env: launchContext.env });
}
return this.serverManager.acquireCurrent();
}
/** A wrapped session gets its own server, so it never shares one that runs outside its wrap. */
private acquireWrappedServer(
wrap: LaunchWrap,
env: Record<string, string> = {},
): Promise<OpenCodeServerAcquisition> {
return this.serverManager.acquireDedicated({ env, wrap });
}
private bindBridgeSession(
sessionId: string,
launchContext?: AgentLaunchContext,
@@ -1712,7 +1727,11 @@ export class OpenCodeAgentClient implements AgentClient {
}
async importSession(input: ImportProviderSessionInput, context: ImportProviderSessionContext) {
const acquisition = await this.serverManager.acquireCurrent();
const wrap = context.launchContext?.wrap;
// A wrapped import reads the session behind its wrap too, so it never starts a server outside it.
const acquisition = wrap
? await this.acquireWrappedServer(wrap, context.launchContext?.env)
: await this.serverManager.acquireCurrent();
const { url } = acquisition.server;
const client = this.createOpenCodeClient({
baseUrl: url,
@@ -115,6 +115,44 @@ describe("OpenCode bridge adapter", () => {
await customEnv.close();
await customMcp.close();
});
test("starts a wrapped session on its own server behind the wrap", async () => {
const paseoHome = await mkdtemp(path.join(os.tmpdir(), "paseo-opencode-adapter-"));
const bridge = new OpenCodeBridge({ paseoHome, logger: createTestLogger() });
await bridge.start();
cleanups.push(async () => {
await bridge.close();
await rm(paseoHome, { recursive: true, force: true });
});
const runtime = new TestOpenCodeHarness();
const wrappedClient = new TestOpenCodeClient();
const sharedClient = new TestOpenCodeClient();
wrappedClient.sessionCreateResponse = { data: { id: "ses_wrapped" } };
sharedClient.sessionCreateResponse = { data: { id: "ses_shared" } };
runtime.enqueueClient(wrappedClient);
runtime.enqueueClient(sharedClient);
const client = new OpenCodeAgentClient(createTestLogger(), undefined, {
serverManager: runtime,
createClient: runtime.createClient,
bridge,
});
const wrapped = await client.createSession(
{ provider: "opencode", cwd: "/workspace/one" },
{ env: { PASEO_AGENT_ID: "one" }, wrap: ["/opt/sandbox/bin/run", "--profile", "a b"] },
);
const shared = await client.createSession(
{ provider: "opencode", cwd: "/workspace/two" },
{ env: { PASEO_AGENT_ID: "two" } },
);
expect(runtime.acquisitions.map(({ kind, wrap }) => ({ kind, wrap }))).toEqual([
{ kind: "dedicated", wrap: ["/opt/sandbox/bin/run", "--profile", "a b"] },
{ kind: "current", wrap: undefined },
]);
await wrapped.close();
await shared.close();
});
});
async function readBridgeContext(bridge: OpenCodeBridge, sessionId: string): Promise<unknown> {
@@ -296,7 +296,7 @@ describe("OpenCodeServerManager generations", () => {
runtime.processForPort(4473).announceListening();
const currentAcquisition = await currentStart;
const dedicatedStart = manager.acquireDedicated({ TEST_ENV: "custom" });
const dedicatedStart = manager.acquireDedicated({ env: { TEST_ENV: "custom" } });
await runtime.settle();
await currentAcquisition.release();
@@ -311,10 +311,29 @@ describe("OpenCodeServerManager generations", () => {
expect(runtime.terminatedPorts).toEqual([4473, 4474]);
});
test("a dedicated server starts behind its session's wrap and the shared server does not", async () => {
const { manager, runtime } = createTestManager([4477, 4478]);
const shared = await manager.acquireCurrent();
const wrapped = await manager.acquireDedicated({
env: { PASEO_AGENT_ID: "wrapped" },
wrap: ["/opt/sandbox/bin/run", "--profile", "a b"],
});
expect(runtime.spawnCalls.map(({ args, options }) => ({ args, wrap: options.wrap }))).toEqual([
{ args: ["serve", "--port", "4477"], wrap: undefined },
{ args: ["serve", "--port", "4478"], wrap: ["/opt/sandbox/bin/run", "--profile", "a b"] },
]);
await shared.release();
await wrapped.release();
});
test("acquireExisting keeps a retired dedicated server alive until every reference releases", async () => {
const { manager, runtime } = createTestManager([4475]);
const dedicatedAcquisition = await manager.acquireDedicated({ PASEO_AGENT_ID: "parent" });
const dedicatedAcquisition = await manager.acquireDedicated({
env: { PASEO_AGENT_ID: "parent" },
});
const existingAcquisition = manager.acquireExisting(dedicatedAcquisition.server.url);
expect(existingAcquisition?.server.url).toBe("http://127.0.0.1:4475");
@@ -329,7 +348,7 @@ describe("OpenCodeServerManager generations", () => {
test("acquireExisting returns null for unknown or dead server urls", async () => {
const { manager, runtime } = createTestManager([4476]);
const acquisition = await manager.acquireDedicated({ PASEO_AGENT_ID: "parent" });
const acquisition = await manager.acquireDedicated({ env: { PASEO_AGENT_ID: "parent" } });
const url = acquisition.server.url;
expect(manager.acquireExisting("http://127.0.0.1:9999")).toBe(null);
@@ -7,6 +7,7 @@ import path from "node:path";
import type { Logger } from "pino";
import { findExecutable } from "../../../../executable-resolution/executable-resolution.js";
import type { LaunchWrap } from "../../../../utils/launch-wrap.js";
import { spawnProcess, type SpawnProcessOptions } from "../../../../utils/spawn.js";
import { terminateWithTreeKill, type ProcessTerminator } from "../../../../utils/tree-kill.js";
import type { ManagedProcessRegistry } from "../../../managed-processes/managed-processes.js";
@@ -36,10 +37,16 @@ export interface OpenCodeServerAcquisition {
release: () => Promise<void>;
}
/** How a session's own server starts: the session's environment, behind the session's wrap. */
export interface OpenCodeDedicatedLaunch {
env: Record<string, string>;
wrap?: LaunchWrap;
}
export interface OpenCodeServerManagerLike {
acquireCurrent(signal?: AbortSignal): Promise<OpenCodeServerAcquisition>;
acquireNew(signal?: AbortSignal): Promise<OpenCodeServerAcquisition>;
acquireDedicated(env: Record<string, string>): Promise<OpenCodeServerAcquisition>;
acquireDedicated(launch: OpenCodeDedicatedLaunch): Promise<OpenCodeServerAcquisition>;
acquireExisting(url: string): OpenCodeServerAcquisition | null;
shutdown(): Promise<void>;
}
@@ -180,8 +187,8 @@ export class OpenCodeServerManager implements OpenCodeServerManagerLike {
return this.acquireServer(server);
}
async acquireDedicated(env: Record<string, string>): Promise<OpenCodeServerAcquisition> {
const server = await this.startServer({ launchEnv: env, epoch: this.epoch });
async acquireDedicated(launch: OpenCodeDedicatedLaunch): Promise<OpenCodeServerAcquisition> {
const server = await this.startServer({ launch, epoch: this.epoch });
server.retired = true;
this.retiredServers.add(server);
const acquisition = this.acquireServer(server);
@@ -325,7 +332,7 @@ export class OpenCodeServerManager implements OpenCodeServerManagerLike {
}
private startServer(options: {
launchEnv?: Record<string, string>;
launch?: OpenCodeDedicatedLaunch;
epoch: number;
}): Promise<OpenCodeServerGeneration> {
const start = this.spawnServer(options);
@@ -336,10 +343,10 @@ export class OpenCodeServerManager implements OpenCodeServerManagerLike {
}
private async spawnServer(options: {
launchEnv?: Record<string, string>;
launch?: OpenCodeDedicatedLaunch;
epoch: number;
}): Promise<OpenCodeServerGeneration> {
const { launchEnv } = options;
const launchEnv = options.launch?.env;
const port = await this.portAllocator();
const url = `http://127.0.0.1:${port}`;
const launchPrefix = await this.resolveCommandPrefix();
@@ -370,6 +377,7 @@ export class OpenCodeServerManager implements OpenCodeServerManagerLike {
detached: process.platform !== "win32",
stdio: ["ignore", "pipe", "pipe"],
baseEnv: environment,
wrap: options.launch?.wrap,
});
const managedProcessRecord = this.recordManagedServerProcess({
process: serverProcess,
@@ -404,7 +412,7 @@ export class OpenCodeServerManager implements OpenCodeServerManagerLike {
managedProcessRecord,
};
this.logger.info(
{ ...generationLogContext(server), dedicated: launchEnv !== undefined },
{ ...generationLogContext(server), dedicated: options.launch !== undefined },
"OpenCode server generation started",
);
void managedProcessRecord.then((record) => {
@@ -1,4 +1,8 @@
import type { OpenCodeServerAcquisition, OpenCodeServerManagerLike } from "./server-manager.js";
import type {
OpenCodeDedicatedLaunch,
OpenCodeServerAcquisition,
OpenCodeServerManagerLike,
} from "./server-manager.js";
const events = {
ready: async () => undefined,
@@ -24,8 +28,8 @@ export class TestOpenCodeServerManager implements OpenCodeServerManagerLike {
return this.recordAcquisition({ kind: "new" });
}
async acquireDedicated(env: Record<string, string>): Promise<OpenCodeServerAcquisition> {
return this.recordAcquisition({ kind: "dedicated", env });
async acquireDedicated(launch: OpenCodeDedicatedLaunch): Promise<OpenCodeServerAcquisition> {
return this.recordAcquisition({ kind: "dedicated", env: launch.env });
}
acquireExisting(url: string): OpenCodeServerAcquisition | null {
@@ -1,7 +1,11 @@
import type { OpencodeClient } from "@opencode-ai/sdk/v2/client";
import type { OpenCodeEventSourceInput } from "../event-consumer.js";
import type { OpenCodeServerAcquisition, OpenCodeServerManagerLike } from "../server-manager.js";
import type {
OpenCodeDedicatedLaunch,
OpenCodeServerAcquisition,
OpenCodeServerManagerLike,
} from "../server-manager.js";
interface OpenCodeResponse {
data?: unknown;
@@ -13,6 +17,7 @@ export class TestOpenCodeHarness implements OpenCodeServerManagerLike {
readonly acquisitions: Array<{
kind: "current" | "new" | "dedicated" | "existing";
env?: Record<string, string>;
wrap?: OpenCodeDedicatedLaunch["wrap"];
url?: string;
releaseCount: number;
}> = [];
@@ -51,8 +56,8 @@ export class TestOpenCodeHarness implements OpenCodeServerManagerLike {
return this.recordAcquisition({ kind: "new" });
}
async acquireDedicated(env: Record<string, string>): Promise<OpenCodeServerAcquisition> {
return this.recordAcquisition({ kind: "dedicated", env });
async acquireDedicated(launch: OpenCodeDedicatedLaunch): Promise<OpenCodeServerAcquisition> {
return this.recordAcquisition({ kind: "dedicated", env: launch.env, wrap: launch.wrap });
}
acquireExisting(url: string): OpenCodeServerAcquisition | null {
@@ -62,12 +67,14 @@ export class TestOpenCodeHarness implements OpenCodeServerManagerLike {
private recordAcquisition(input: {
kind: "current" | "new" | "dedicated" | "existing";
env?: Record<string, string>;
wrap?: OpenCodeDedicatedLaunch["wrap"];
url?: string;
}): OpenCodeServerAcquisition {
const acquisition = {
kind: input.kind,
releaseCount: 0,
...(input.env ? { env: input.env } : {}),
...(input.wrap ? { wrap: input.wrap } : {}),
...(input.url ? { url: input.url } : {}),
};
this.acquisitions.push(acquisition);
@@ -6,6 +6,7 @@ import { describe, expect, test } from "vitest";
import { createTestLogger } from "../../../../../test-utils/test-logger.js";
import type { AgentStreamEvent } from "../../../agent-sdk-types.js";
import { ProviderSubagentStore } from "../../../provider-subagents/store.js";
import type { V2RuntimeAcquireOptions } from "./runtime.js";
import { OpenCodeV2AgentClient } from "./agent.js";
import { V2Harness } from "../test-utils/v2-harness.js";
import type { V2Api } from "./api.js";
@@ -1270,6 +1271,72 @@ describe("OpenCode v2 session lifecycle", () => {
}
});
test("asks the runtime for a server behind the wrap and the launch environment when creating and resuming", async () => {
const servers = [new V2Harness(), new V2Harness()];
const requests: unknown[] = [];
const runtime = {
acquire: async (input?: V2RuntimeAcquireOptions) => {
requests.push(input?.dedicated);
const server = servers[requests.length - 1];
if (!server) throw new Error("No OpenCode test server left");
return server.connection;
},
shutdown: async () => undefined,
};
const client = new OpenCodeV2AgentClient({ logger: createTestLogger(), runtime });
const wrap = ["/opt/sandbox/bin/run", "--profile", "a b"] as const;
const env = { SANDBOX_PROFILE: "agent" };
const created = await client.createSession(
{ provider: "opencode", cwd: "/tmp/project" },
{ agentId: "agent", wrap, env },
);
try {
// The created session's connection is live, and a wrapped resume still asks for its own.
const resumed = await client.resumeSession(
{
provider: "opencode",
sessionId: "session",
nativeHandle: "session",
metadata: { cwd: "/tmp/project" },
},
undefined,
{ agentId: "agent", wrap, env },
{ purpose: "history" },
);
await resumed.close();
expect(requests).toEqual([
{ wrap, env },
{ wrap, env },
]);
} finally {
await created.close();
}
});
test("imports a wrapped session through one wrapped server, from the first session lookup", async () => {
const server = new V2Harness();
// Import restores the session's agent.
server.api.session.switchAgent = async () => undefined;
const requests: unknown[] = [];
const runtime = {
acquire: async (input?: V2RuntimeAcquireOptions) => {
requests.push(input?.dedicated);
return server.connection;
},
shutdown: async () => undefined,
};
const client = new OpenCodeV2AgentClient({ logger: createTestLogger(), runtime });
const wrap = ["/opt/sandbox/bin/run", "--profile", "import"] as const;
const env = { SANDBOX_PROFILE: "import" };
const config = { provider: "opencode", cwd: "/tmp/project" } as const;
const imported = await client.importSession(
{ providerHandleId: "session", cwd: "/tmp/project" },
{ config, storedConfig: config, launchContext: { agentId: "agent", wrap, env } },
);
await imported.session.close();
expect(requests).toEqual([{ wrap, env }]);
});
test("rejects MCP servers without the Paseo bridge before creating an OpenCode session", async () => {
const harness = new V2Harness();
const client = new OpenCodeV2AgentClient({

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