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
149 changed files with 4539 additions and 2050 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
-1
View File
@@ -36,7 +36,6 @@ At the start of non-trivial work, list `docs/` and skim anything relevant to the
| [docs/floating-panels.md](docs/floating-panels.md) | Anchored popovers — Portal/Modal escape for Android, lifecycle gates, keyboard-shared-value, status-bar offset, the flash |
| [docs/keyboard-shortcuts.md](docs/keyboard-shortcuts.md) | The binding table, per-platform key sources, badges vs routing, iOS `UIKeyCommand` limits |
| [docs/menus.md](docs/menus.md) | The menu engine — popover vs sheet, submenu pages, hover intent, when a decision earns a submenu |
| [docs/drag-reorder.md](docs/drag-reorder.md) | Drag to reorder — `DraggableList` and its handle, the scroll view that must host the drag, grip placement, testing on a phone |
| [docs/expo-router.md](docs/expo-router.md) | Expo Router route ownership, startup restore, and native blank-screen gotchas |
| [docs/notifications.md](docs/notifications.md) | Notification tap ownership, native replay and acknowledgement, startup handoff, and payload QA |
| [docs/file-icons.md](docs/file-icons.md) | Material icon theme integration for the file explorer |
-34
View File
@@ -1,34 +0,0 @@
# Drag to reorder
A list the user can reorder renders through `DraggableList` from `@/components/draggable-list`. Each row puts a `DraggableListHandle` where its grip is drawn. The Usage cards (`packages/app/src/usage/list.tsx`, `packages/app/src/usage/card.tsx`) and the agent profile roster (`packages/app/src/agent-profiles/settings/`) are the reference.
| Platform | How a drag starts |
| -------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| Web | dnd-kit pointer drag. With `useDragHandle`, only the handle starts it, and the handle reorders by keyboard. Without it, the whole row starts it. |
| Native | Hold the handle for 180 ms without moving more than 4 px. The list then owns the touch until the finger lifts. |
## The scroll view must host the drag
On native, the hold calls `drag()`, which calls `useContentDrag().setActive(true)` from `@/components/ui/content-drag` on the nearest scroll view. That scroll view stops scrolling until the drag ends. If no scroll view up the tree hosts content drags, `setActive` does nothing. The page scroll then takes the touch as soon as the finger moves past the touch slop, before the list's own pan activates. The row never moves, and the page scrolls instead.
These scroll views host content drags:
- `ScrollView` from `@/components/ui/scroll-view`, inside and outside a sheet.
- `PageLayout`, for a settings page or any other full page.
If you put a reorderable list in another scroll view, such as a third-party keyboard-aware one, wrap it with `withContentDrag` from `@/components/ui/content-drag`. `packages/app/src/components/page-layout/index.tsx` shows the pattern. A plain `ScrollView` from `react-native` breaks the drag.
Inside a sheet, the `ScrollView` also registers the drag gesture with the sheet, so the sheet's pan-to-close waits for it.
## Where the grip goes
The grip hangs in the row's leading padding, absolutely positioned over the full row height. The row's content keeps the same left rail as rows that cannot be reordered, and the grip does not take a column. On a pointer device the grip shows on hover, focus, or while dragging. On touch and compact layouts it always shows, because there is no hover.
## Test with a page that scrolls
A list that fits on the screen does not show the bug, because the page has nothing to scroll. Test on a phone with enough rows that the page scrolls. Then check both directions:
1. Hold the grip and drag a row past two others. The new order is saved.
2. Swipe quickly on a row body. The page scrolls and the order stays the same.
On an Android emulator, `adb shell input swipe` does not hold still long enough to arm the drag. Send `input motionevent DOWN`, wait 500 ms, then send `MOVE` events and `UP`.
+1 -1
View File
@@ -465,7 +465,7 @@ in a tab. An overlay opened from that content and calling `useSafeAreaInsets()`
gets that 0 and draws over the navigation bar.
- A Gorhom sheet reads the inset inside its children, which render in the app's sheet host. See
`SheetVisibleFrame` (used by `CompactSheetBody` and `ComboboxSheetFrame`) and `MenuSheetScrollView`.
`CompactSheetBody`, `MenuSheetScrollView` and `ComboboxSheetFrame`.
- An RN `Modal` passes the call site's context straight through, so wrap its content in
`WindowSafeArea` from `@/window-layout` and read the inset below that. It provides the insets of
the whole window, published by `WindowLayoutProvider`. Do not put a `SafeAreaProvider` inside the
+60 -2
View File
@@ -462,13 +462,56 @@ 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.
Workspace records decide ownership, including explicit non-ownership after recovery. Without a record,
@@ -487,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.
@@ -586,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,121 +0,0 @@
import type { Locator, Page } from "@playwright/test";
import { expect, test } from "../support/fixtures";
import { gotoAppShell } from "../support/helpers/app";
import { getServerId } from "../support/helpers/server-id";
import { seedWorkspace } from "../support/helpers/seed-client";
import { selectSidebarStatusGrouping } from "../support/helpers/sidebar";
import { waitForSidebarHydration } from "../support/helpers/workspace-ui";
// Cmd on macOS, Ctrl on Windows and Linux: the platform primary modifier the app binds as `mod`.
const MOD = "ControlOrMeta";
type SeededProject = Awaited<ReturnType<typeof seedWorkspace>>;
async function seedProjectWithWorkspaces(count: number) {
const project = await seedWorkspace({ repoPrefix: "sidebar-selection-" });
const workspaceIds = [project.workspaceId];
for (let index = 1; index < count; index += 1) {
const created = await project.client.createWorkspace({
source: { kind: "directory", path: project.repoPath, projectId: project.projectId },
title: `Selection workspace ${index}`,
});
if (!created.workspace) throw new Error(created.error ?? "Failed to seed a workspace");
workspaceIds.push(created.workspace.id);
}
return { project, workspaceIds };
}
/** The seeded rows, in the order the sidebar shows them. */
async function rowsInSidebarOrder(page: Page, workspaceIds: readonly string[]) {
const testIds = workspaceIds.map((id) => `sidebar-workspace-row-${getServerId()}:${id}`);
const rows = page.locator(testIds.map((testId) => `[data-testid="${testId}"]`).join(", "));
await expect(rows).toHaveCount(workspaceIds.length);
const ordered = await rows.evaluateAll((elements) =>
elements.map((element) => element.getAttribute("data-testid") ?? ""),
);
return ordered.map((testId) => page.getByTestId(testId));
}
async function expectChecked(rows: readonly Locator[], checked: readonly boolean[]) {
for (const [index, row] of rows.entries()) {
await expect(row).toHaveAttribute("aria-checked", String(checked[index]));
}
}
async function expectSelectedCount(page: Page, count: number) {
await expect(page.getByTestId("workspace-selection-count")).toHaveText(`${count} selected`);
}
async function exitSelection(page: Page) {
await page.getByTestId("workspace-selection-exit").click();
await expect(page.getByTestId("workspace-selection-toast")).toHaveCount(0);
}
/**
* Walks the Finder click matrix on four rows, starting with the first row open: a modifier click
* from normal mode selects only the clicked row, Cmd/Ctrl+click toggles, Shift+click extends and
* shrinks a range from the anchor, and plain clicks keep toggling while select mode is on.
*/
async function exerciseClickMatrix(page: Page, rows: readonly Locator[]) {
const [first, second, third, fourth] = rows;
await first.click();
await expect(first).toHaveAttribute("aria-selected", "true");
const openWorkspaceUrl = page.url();
await third.click({ modifiers: [MOD] });
await expectSelectedCount(page, 1);
await expectChecked(rows, [false, false, true, false]);
await fourth.click({ modifiers: [MOD] });
await expectChecked(rows, [false, false, true, true]);
await third.click({ modifiers: [MOD] });
await expectChecked(rows, [false, false, false, true]);
await second.click();
await expectChecked(rows, [false, true, false, true]);
expect(page.url()).toBe(openWorkspaceUrl);
await exitSelection(page);
await second.click({ modifiers: ["Shift"] });
await expectSelectedCount(page, 1);
await expectChecked(rows, [false, true, false, false]);
await fourth.click({ modifiers: ["Shift"] });
await expectChecked(rows, [false, true, true, true]);
await third.click({ modifiers: ["Shift"] });
await expectChecked(rows, [false, true, true, false]);
await first.click({ modifiers: ["Shift"] });
await expectChecked(rows, [true, true, false, false]);
await fourth.click({ modifiers: [MOD] });
await third.click({ modifiers: ["Shift"] });
await expectChecked(rows, [true, true, true, true]);
expect(page.url()).toBe(openWorkspaceUrl);
await exitSelection(page);
}
test.describe("sidebar workspace selection clicks", () => {
let seeded: { project: SeededProject; workspaceIds: string[] } | null = null;
test.afterEach(async () => {
await seeded?.project.cleanup();
seeded = null;
});
test("Cmd/Ctrl+click and Shift+click select like Finder in project grouping", async ({
page,
}) => {
seeded = await seedProjectWithWorkspaces(4);
await gotoAppShell(page);
await waitForSidebarHydration(page);
await exerciseClickMatrix(page, await rowsInSidebarOrder(page, seeded.workspaceIds));
});
test("Cmd/Ctrl+click and Shift+click select like Finder in status grouping", async ({ page }) => {
seeded = await seedProjectWithWorkspaces(4);
await gotoAppShell(page);
await waitForSidebarHydration(page);
await selectSidebarStatusGrouping(page);
await exerciseClickMatrix(page, await rowsInSidebarOrder(page, seeded.workspaceIds));
});
});
@@ -153,25 +153,3 @@ On iPad, replacing the field a second time appends text. For this Settings journ
native clipboard Paste menu, then continue the assertions manually. Dismiss the password keyboard
with Done to submit when the Connect button is below the keyboard. The welcome pairing regression
runs end to end without these adjustments.
## Sheet footer keyboard safe-area clearance
`footer-keyboard.android.sh` records the **Add project** sheet on an Android device or emulator
across repeated keyboard open/dismiss transitions, then runs `assert-sheet-footer-keyboard.mjs`
over every recorded frame. Configure three-button navigation, `show_ime_with_hard_keyboard=1`, and
a visible soft keyboard (such as Gboard) on the test device before running so the script does not
mutate device settings. The assertion checks both settled positions against the navigation bar
height and fails if any frame drops the **Open project** button into the navigation bar or
overshoots above its open-keyboard position.
```sh
ANDROID_SERIAL=emulator-5554 \
packages/app/e2e/mobile/modal-sheet/footer-keyboard.android.sh
```
You can also validate an existing screen recording directly (optionally passing pixel tolerance and
navigation bar height in pixels):
```sh
node packages/app/e2e/mobile/modal-sheet/assert-sheet-footer-keyboard.mjs /path/to/recording.mp4 4 96
```
@@ -1,173 +0,0 @@
import { execFileSync, spawnSync } from "node:child_process";
import process from "node:process";
const [, , videoPath, toleranceArg = "4", navBarHeightArg = "0"] = process.argv;
if (!videoPath) {
throw new Error(
"Usage: node assert-sheet-footer-keyboard.mjs <screenrecord.mp4> [pixel-tolerance] [nav-bar-height-px]",
);
}
const tolerance = Number(toleranceArg);
if (!Number.isFinite(tolerance) || tolerance < 0) {
throw new Error(`Invalid pixel tolerance: ${toleranceArg}`);
}
const navBarHeight = Number(navBarHeightArg);
if (!Number.isFinite(navBarHeight) || navBarHeight < 0) {
throw new Error(`Invalid navigation bar height: ${navBarHeightArg}`);
}
function probeDimensions(filePath) {
const output = execFileSync(
"ffprobe",
[
"-v",
"error",
"-select_streams",
"v:0",
"-show_entries",
"stream=width,height",
"-of",
"csv=s=x:p=0",
filePath,
],
{ encoding: "utf8" },
).trim();
const [width, height] = output.split("x").map(Number);
if (!width || !height) {
throw new Error(`Unable to read video dimensions for ${filePath}: ${output}`);
}
return { width, height };
}
function measureButtonBottomPerFrame(filePath, width, height) {
const centerX = Math.floor(width / 2);
// Decode only the 1px vertical centerline so full-rate recordings fit comfortably in memory.
const result = spawnSync(
"ffmpeg",
[
"-v",
"error",
"-i",
filePath,
"-vf",
`format=rgb24,crop=1:${height}:${centerX}:0`,
"-vsync",
"0",
"-f",
"rawvideo",
"-pix_fmt",
"rgb24",
"-",
],
{ maxBuffer: 64 * 1024 * 1024 },
);
if (result.status !== 0) {
throw new Error(`ffmpeg failed (${result.status}): ${result.stderr?.toString("utf8") ?? ""}`);
}
const buffer = result.stdout;
const frameSize = height * 3;
const frameCount = Math.floor(buffer.length / frameSize);
// Restrict vertical scan below the search field so its green focus ring is excluded.
const scanTop = Math.floor(height * 0.42);
const bottoms = [];
for (let frame = 0; frame < frameCount; frame += 1) {
const frameOffset = frame * frameSize;
let maxY = null;
for (let y = scanTop; y < height; y += 1) {
const offset = frameOffset + y * 3;
const r = buffer[offset];
const g = buffer[offset + 1];
const b = buffer[offset + 2];
// Matches the green primary "Open project" button (both enabled and disabled states).
if (g > 50 && g > r + 15 && g > b + 10) {
maxY = y;
}
}
bottoms.push(maxY);
}
return bottoms;
}
function findSettledValue(values, minRunLength) {
let runValue = null;
let runLength = 0;
for (const value of values) {
if (value !== null && runValue !== null && Math.abs(value - runValue) <= 2) {
runLength += 1;
if (runLength >= minRunLength) return runValue;
} else {
runValue = value;
runLength = value === null ? 0 : 1;
}
}
return null;
}
const { width, height } = probeDimensions(videoPath);
const bottoms = measureButtonBottomPerFrame(videoPath, width, height);
const visibleFrames = bottoms
.map((bottom, frame) => ({ frame, bottom }))
.filter((entry) => entry.bottom !== null);
if (visibleFrames.length < 10) {
throw new Error(
`Expected at least 10 frames with the Open project footer button visible, found ${visibleFrames.length}`,
);
}
// Identify settled resting (keyboard closed, lower on screen) and open (keyboard shown, higher on
// screen) positions by finding stable runs separated by at least 200px of keyboard height.
const minBottom = Math.min(...visibleFrames.map((entry) => entry.bottom));
const maxBottom = Math.max(...visibleFrames.map((entry) => entry.bottom));
const midpoint = (minBottom + maxBottom) / 2;
const closedSettled = findSettledValue(
bottoms.map((y) => (y !== null && y > midpoint ? y : null)),
15,
);
const openSettled = findSettledValue(
bottoms.map((y) => (y !== null && y < midpoint ? y : null)),
15,
);
if (closedSettled === null || openSettled === null || closedSettled - openSettled < 200) {
throw new Error(
`Recording did not capture settled keyboard-closed (${closedSettled}) and keyboard-open (${openSettled}) states`,
);
}
const maxAllowedBottom =
navBarHeight > 0
? Math.min(closedSettled + tolerance, height - navBarHeight)
: closedSettled + tolerance;
const belowNavViolations = visibleFrames.filter((entry) => entry.bottom > maxAllowedBottom);
const overshootViolations = visibleFrames.filter((entry) => entry.bottom < openSettled - tolerance);
if (belowNavViolations.length > 0 || overshootViolations.length > 0) {
const summary = [
`Sheet footer keyboard transition jank detected in ${videoPath}:`,
` settled closed bottom=${closedSettled}px (gap=${height - closedSettled}px), settled open bottom=${openSettled}px (gap=${height - openSettled}px), maxAllowedBottom=${maxAllowedBottom}px`,
];
if (belowNavViolations.length > 0) {
const worst = Math.max(...belowNavViolations.map((entry) => entry.bottom));
summary.push(
` dropped below safe-area clearance on ${belowNavViolations.length} frames (first=f${belowNavViolations[0].frame}, last=f${belowNavViolations.at(-1).frame}, worst bottom=${worst}px, excess=+${worst - maxAllowedBottom}px)`,
);
}
if (overshootViolations.length > 0) {
const worst = Math.min(...overshootViolations.map((entry) => entry.bottom));
summary.push(
` overshot above open keyboard position on ${overshootViolations.length} frames (first=f${overshootViolations[0].frame}, worst bottom=${worst}px, overshoot=-${openSettled - worst}px)`,
);
}
throw new Error(summary.join("\n"));
}
process.stdout.write(
`Sheet footer stayed within bounds across ${bottoms.length} frames (${visibleFrames.length} visible): closed=${closedSettled}px, open=${openSettled}px, maxAllowed=${maxAllowedBottom}px, 0 nav-bar overlap frames, 0 overshoot frames\n`,
);
@@ -1,54 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
# Verifies that the Add project bottom sheet footer never flashes behind the Android system
# navigation bar on keyboard dismiss or overshoots upward on keyboard open.
#
# Prerequisites (configured on the test device before running):
# - Three-button navigation bar enabled (for example:
# `adb shell cmd overlay enable com.android.internal.systemui.navbar.threebutton`).
# - Software keyboard enabled when a hardware keyboard is attached (`show_ime_with_hard_keyboard=1`)
# and a visible soft keyboard (such as Gboard) selected as the active IME.
# - The Add project sheet already open with a connected host so the Open project footer button is
# visible.
# - `ffmpeg` and `ffprobe` on PATH.
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SERIAL="${ANDROID_SERIAL:-$(adb devices | awk '/\tdevice$/ {print $1; exit}')}"
OUT_DIR="${SHEET_FOOTER_QA_DIR:-/tmp/paseo-sheet-footer-qa}"
VIDEO_PATH="$OUT_DIR/sheet-footer-keyboard.mp4"
if [ -z "$SERIAL" ]; then
echo "No Android device attached. Set ANDROID_SERIAL or start an emulator." >&2
exit 1
fi
mkdir -p "$OUT_DIR"
# Derive tap coordinates and 3-button navigation bar height (48dp) from the active display metrics.
SIZE_LINE="$(adb -s "$SERIAL" shell wm size | tail -n 1 | tr -d '\r')"
DIMENSIONS="${SIZE_LINE##* }"
WIDTH="${DIMENSIONS%x*}"
HEIGHT="${DIMENSIONS#*x}"
DENSITY_LINE="$(adb -s "$SERIAL" shell wm density | tail -n 1 | tr -d '\r')"
DENSITY="${DENSITY_LINE##* }"
NAV_BAR_PX="${SHEET_FOOTER_NAV_BAR_PX:-$((48 * DENSITY / 160))}"
SEARCH_X=$((WIDTH / 2))
SEARCH_Y=$((HEIGHT * 34 / 100))
adb -s "$SERIAL" shell rm -f /sdcard/sheet-footer-keyboard.mp4
adb -s "$SERIAL" shell screenrecord --time-limit 9 --bit-rate 8000000 /sdcard/sheet-footer-keyboard.mp4 &
REC_PID=$!
sleep 0.8
adb -s "$SERIAL" shell input tap "$SEARCH_X" "$SEARCH_Y"
sleep 1.8
adb -s "$SERIAL" shell input keyevent 4
sleep 1.8
adb -s "$SERIAL" shell input tap "$SEARCH_X" "$SEARCH_Y"
sleep 1.8
adb -s "$SERIAL" shell input keyevent 4
wait "$REC_PID" || true
adb -s "$SERIAL" pull /sdcard/sheet-footer-keyboard.mp4 "$VIDEO_PATH" >/dev/null
node "$SCRIPT_DIR/assert-sheet-footer-keyboard.mjs" "$VIDEO_PATH" 4 "$NAV_BAR_PX"
@@ -17,12 +17,7 @@ import type { ProviderSnapshotEntry } from "@getpaseo/protocol/agent-types";
import type { AgentProfile } from "@getpaseo/protocol/messages";
import { DraggableListHandle } from "@/components/draggable-list";
import { useOpenKebabMenuVisibility } from "@/components/sidebar/use-open-kebab-menu-visibility";
import {
bySizing,
ICON_BUTTON_SIZES,
mapLayout,
TOUCH_TARGET,
} from "@/components/ui/control-geometry";
import { bySizing, TOUCH_TARGET } from "@/components/ui/control-geometry";
import {
DropdownMenu,
DropdownMenuContent,
@@ -46,16 +41,11 @@ import { buildAgentProfileRosterSummary } from "../internal/profile-summary";
/** Shared column & rail geometry consumed by both RosterTableHeader and AgentProfileRow. */
export const ROSTER_COL_PROFILE_WIDTH = 184;
export const ROSTER_COL_RUNTIME_WIDTH = 248;
export const ROSTER_GRIP_WIDTH = bySizing({ touch: 28, pointer: 20 });
export const ROSTER_TRAILING_WIDTH = bySizing({ touch: TOUCH_TARGET + 14, pointer: 42 });
const ROW_MIN_HEIGHT = bySizing({ touch: TOUCH_TARGET + 16, pointer: 56 });
const KEBAB_GLYPH_SIZE = ICON_SIZE.sm;
// The kebab's hitbox is larger than its glyph; it overhangs the row so the glyph sits on the
// card's trailing rail and the hitbox does not make the row taller.
const KEBAB_HITBOX_OVERHANG = bySizing({
touch: (ICON_BUTTON_SIZES.small.touch - KEBAB_GLYPH_SIZE) / 2,
pointer: (ICON_BUTTON_SIZES.small.pointer - KEBAB_GLYPH_SIZE) / 2,
});
const GRIP_HANDLE_HEIGHT = bySizing({ touch: TOUCH_TARGET, pointer: 28 });
const ThemedGripVertical = withUnistyles(GripVertical);
const ThemedMoreVertical = withUnistyles(MoreVertical);
@@ -140,7 +130,7 @@ function AgentProfileRowMenu({
label={t("settings.host.agentProfiles.profileActions", { name: profileName })}
testID={`agent-profile-menu-${profileId}`}
>
<ThemedMoreVertical size={KEBAB_GLYPH_SIZE} uniProps={mutedIconColorMapping} />
<ThemedMoreVertical size={ICON_SIZE.sm} uniProps={mutedIconColorMapping} />
</ToolbarButton>
<DropdownMenuContent side="bottom" align="end" width={180}>
<DropdownMenuItem
@@ -241,9 +231,16 @@ function AgentProfileRowContent({
<Text style={styles.nameText} numberOfLines={1}>
{profile.name}
</Text>
<Text style={styles.stackedSpecText} numberOfLines={1}>
{fullSummary}
</Text>
<View style={styles.stackedSpecLine}>
<AgentProfileGlyph
provider={profile.provider}
serverId={serverId}
size={ICON_SIZE.xs}
/>
<Text style={styles.stackedSpecText} numberOfLines={1}>
{fullSummary}
</Text>
</View>
{profile.notes ? (
<Text
style={styles.stackedNotesText}
@@ -375,8 +372,8 @@ export function AgentProfileRow({
[dragging, isFirst, isHovered, menuProps.open, selected],
);
const gripStyle = useMemo(
() => (showRowAffordances ? styles.grip : [styles.grip, styles.affordanceHidden]),
const gripVisibilityStyle = useMemo(
() => [styles.gripSlot, !showRowAffordances && styles.affordanceHidden],
[showRowAffordances],
);
const kebabVisibilityStyle = useMemo(
@@ -402,6 +399,22 @@ export function AgentProfileRow({
{selected ? <View style={styles.selectedIndicator} pointerEvents="none" /> : null}
{reorderable ? (
<View style={gripVisibilityStyle} pointerEvents={showRowAffordances ? "auto" : "none"}>
<DraggableListHandle
accessibilityLabel={t("settings.host.agentProfiles.reorderProfile", {
name: profile.name,
})}
style={styles.gripHandle}
testID={`agent-profile-drag-${profile.id}`}
>
<ThemedGripVertical size={ICON_SIZE.sm} uniProps={extraMutedIconColorMapping} />
</DraggableListHandle>
</View>
) : (
<View style={isStacked ? styles.gripSpacerCompact : styles.gripSlot} />
)}
<AgentProfileRowContent
serverId={serverId}
profile={profile}
@@ -412,8 +425,7 @@ export function AgentProfileRow({
isStacked={isStacked}
/>
{/* A stacked row opens on tap like the wide one; the kebab alone ends it, on the trailing rail. */}
<View style={isStacked ? styles.trailingStacked : styles.trailing}>
<View style={styles.trailing}>
<View style={kebabVisibilityStyle} pointerEvents={showRowAffordances ? "auto" : "none"}>
<AgentProfileRowMenu
profileId={profile.id}
@@ -430,27 +442,13 @@ export function AgentProfileRow({
onRemove={handleRemove}
/>
</View>
{isStacked ? null : (
<View style={[styles.chevron, styles.passThrough]} {...HIDDEN_FROM_ASSISTIVE_TECH}>
<ThemedChevronRight
size={ICON_SIZE.sm}
uniProps={isHovered || selected ? foregroundIconColorMapping : mutedIconColorMapping}
/>
</View>
)}
<View style={[styles.chevron, styles.passThrough]} {...HIDDEN_FROM_ASSISTIVE_TECH}>
<ThemedChevronRight
size={ICON_SIZE.sm}
uniProps={isHovered || selected ? foregroundIconColorMapping : mutedIconColorMapping}
/>
</View>
</View>
{reorderable ? (
<DraggableListHandle
accessibilityLabel={t("settings.host.agentProfiles.reorderProfile", {
name: profile.name,
})}
style={gripStyle}
testID={`agent-profile-drag-${profile.id}`}
>
<ThemedGripVertical size={ICON_SIZE.sm} uniProps={extraMutedIconColorMapping} />
</DraggableListHandle>
) : null}
</View>
);
}
@@ -462,7 +460,8 @@ const styles = StyleSheet.create((theme) => ({
alignItems: "center",
minHeight: ROW_MIN_HEIGHT,
paddingVertical: theme.spacing[3],
paddingHorizontal: theme.spacing[4],
paddingLeft: theme.spacing[2],
paddingRight: theme.spacing[4],
gap: theme.spacing[2],
},
rowHovered: {
@@ -492,15 +491,19 @@ const styles = StyleSheet.create((theme) => ({
passThrough: {
pointerEvents: "none",
},
// The grip hangs in the row's leading padding, as on a Usage card, so the icon tile sits on the
// card's rail with or without it and revealing it on hover moves nothing. It takes the padding's
// full height so a finger finds it.
grip: {
position: "absolute",
left: 0,
top: 0,
bottom: 0,
width: theme.spacing[4],
gripSlot: {
width: ROSTER_GRIP_WIDTH,
alignItems: "center",
justifyContent: "center",
flexShrink: 0,
},
gripSpacerCompact: {
width: theme.spacing[2],
flexShrink: 0,
},
gripHandle: {
width: ROSTER_GRIP_WIDTH,
height: GRIP_HANDLE_HEIGHT,
alignItems: "center",
justifyContent: "center",
},
@@ -582,6 +585,12 @@ const styles = StyleSheet.create((theme) => ({
minWidth: 0,
gap: theme.spacing[0.5],
},
stackedSpecLine: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[1.5],
minWidth: 0,
},
stackedSpecText: {
flexShrink: 1,
color: theme.colors.foregroundMuted,
@@ -600,11 +609,6 @@ const styles = StyleSheet.create((theme) => ({
gap: theme.spacing[1],
flexShrink: 0,
},
trailingStacked: {
flexShrink: 0,
marginRight: mapLayout(KEBAB_HITBOX_OVERHANG, (overhang) => -overhang),
marginVertical: mapLayout(KEBAB_HITBOX_OVERHANG, (overhang) => -overhang),
},
kebabSlot: {
alignItems: "center",
justifyContent: "center",
@@ -44,6 +44,7 @@ import {
AgentProfileRow,
ROSTER_COL_PROFILE_WIDTH,
ROSTER_COL_RUNTIME_WIDTH,
ROSTER_GRIP_WIDTH,
ROSTER_TRAILING_WIDTH,
} from "./agent-profile-row";
@@ -89,6 +90,7 @@ function RosterTableHeader(): ReactElement {
const { t } = useTranslation();
return (
<View style={styles.tableHeader}>
<View style={styles.tableHeaderGripSpacer} />
<View style={styles.tableHeaderColumns}>
<Text style={[styles.tableHeaderText, styles.colProfileHeader]} numberOfLines={1}>
{t("settings.host.agentProfiles.columns.profile")}
@@ -1028,11 +1030,16 @@ const styles = StyleSheet.create((theme) => ({
flexDirection: "row",
alignItems: "center",
paddingVertical: theme.spacing[2],
paddingHorizontal: theme.spacing[4],
paddingLeft: theme.spacing[2],
paddingRight: theme.spacing[4],
gap: theme.spacing[2],
borderBottomWidth: theme.borderWidth[1],
borderBottomColor: theme.colors.border,
},
tableHeaderGripSpacer: {
width: ROSTER_GRIP_WIDTH,
flexShrink: 0,
},
tableHeaderColumns: {
flex: 1,
minWidth: 0,
@@ -0,0 +1,48 @@
import { describe, expect, it } from "vitest";
import { getCompactSheetSafeAreaPadding } from "@/components/adaptive-modal-sheet-layout";
describe("getCompactSheetSafeAreaPadding", () => {
it("assigns safe clearance to the footer independently of decorative padding", () => {
expect(
getCompactSheetSafeAreaPadding({
isCompact: true,
isKeyboardVisible: false,
hasFooter: true,
safeAreaBottom: 34,
}),
).toEqual({ footerPaddingBottom: 34 });
});
it("assigns safe clearance to the body only without a footer", () => {
expect(
getCompactSheetSafeAreaPadding({
isCompact: true,
isKeyboardVisible: false,
hasFooter: false,
safeAreaBottom: 34,
}),
).toEqual({ contentPaddingBottom: 34 });
});
it("does not add a safe-area band above the compact keyboard", () => {
expect(
getCompactSheetSafeAreaPadding({
isCompact: true,
isKeyboardVisible: true,
hasFooter: false,
safeAreaBottom: 34,
}),
).toEqual({});
});
it("does not inset desktop sheets", () => {
expect(
getCompactSheetSafeAreaPadding({
isCompact: false,
isKeyboardVisible: false,
hasFooter: false,
safeAreaBottom: 34,
}),
).toEqual({});
});
});
@@ -0,0 +1,28 @@
export interface CompactSheetSafeAreaPaddingInput {
isCompact: boolean;
isKeyboardVisible: boolean;
hasFooter: boolean;
safeAreaBottom: number;
}
export interface CompactSheetSafeAreaPadding {
contentPaddingBottom?: number;
footerPaddingBottom?: number;
}
export function getCompactSheetSafeAreaPadding({
isCompact,
isKeyboardVisible,
hasFooter,
safeAreaBottom,
}: CompactSheetSafeAreaPaddingInput): CompactSheetSafeAreaPadding {
if (!isCompact || isKeyboardVisible || safeAreaBottom <= 0) {
return {};
}
if (hasFooter) {
return { footerPaddingBottom: safeAreaBottom };
}
return { contentPaddingBottom: safeAreaBottom };
}
@@ -20,11 +20,12 @@ import {
IsolatedBottomSheetModal,
SheetVisibleFrame,
type ContextBridge,
useBottomSheetSafeAreaPaddingStyle,
useIsolatedBottomSheetVisibility,
} from "@/components/ui/isolated-bottom-sheet-modal";
import { getCompactSheetSafeAreaPadding } from "@/components/adaptive-modal-sheet-layout";
import { ScrollView } from "@/components/ui/scroll-view";
import { isWeb } from "@/constants/platform";
import { useKeyboardVisibility } from "@/hooks/use-keyboard-visibility";
import { SafeAreaInsetsContext, useSafeAreaInsets } from "react-native-safe-area-context";
import { AdaptiveTextInput } from "@/components/adaptive-text-input";
import { useDismissibleOverlay } from "@/components/ui/overlay-dismissal";
@@ -609,9 +610,8 @@ export interface SheetKeyboard {
}
/**
* The compact sheet's body. It renders on the far side of the sheet's portal so `SheetVisibleFrame`
* and `useBottomSheetSafeAreaPaddingStyle` read the screen's bottom inset, not the one left where
* the sheet was opened: inside a sheet tab, none is.
* The compact sheet's body. It renders on the far side of the sheet's portal so it reads the
* screen's bottom inset, not the one left where the sheet was opened: inside a sheet tab, none is.
*/
function CompactSheetBody({
header,
@@ -619,6 +619,7 @@ function CompactSheetBody({
onClose,
testID,
footer,
isKeyboardVisible,
scrollable,
bodyStyle,
contentStyle,
@@ -629,18 +630,32 @@ function CompactSheetBody({
onClose: () => void;
testID?: string;
footer: ReactNode;
isKeyboardVisible: boolean;
scrollable: boolean;
bodyStyle?: StyleProp<ViewStyle>;
contentStyle?: StyleProp<ViewStyle>;
children: ReactNode;
}) {
// Safe-area clearance is owned on the UI thread in lockstep with `SheetVisibleFrame`'s keyboard
// height: `SheetVisibleFrame` pads the frame whenever a footer or non-scrollable body is shown,
// while a scrollable body without a footer pads its scroll content so items scroll behind the
// system bar and still clear it at rest.
const bodyClearanceStyle = useBottomSheetSafeAreaPaddingStyle(scrollable && !footer);
const insets = useSafeAreaInsets();
const { contentPaddingBottom = 0, footerPaddingBottom = 0 } = getCompactSheetSafeAreaPadding({
isCompact: true,
isKeyboardVisible,
hasFooter: Boolean(footer),
safeAreaBottom: insets.bottom,
});
// Safe-area clearance is a separate layer: it must not replace the caller's
// padding (including an explicit zero), and the footer owns it when present.
const bodyClearanceStyle = { paddingBottom: contentPaddingBottom };
const footerClearanceStyle = useMemo(
() => ({ paddingBottom: footerPaddingBottom }),
[footerPaddingBottom],
);
const footerView = useMemo(
() => (footer ? <View style={footerClearanceStyle}>{footer}</View> : null),
[footer, footerClearanceStyle],
);
return (
<SheetVisibleFrame footer={footer} safeAreaInset={scrollable ? "footer" : "frame"}>
<SheetVisibleFrame footer={footerView}>
{header ? (
<SheetHeaderView
header={header}
@@ -657,12 +672,12 @@ function CompactSheetBody({
keyboardShouldPersistTaps="handled"
showsVerticalScrollIndicator={false}
>
<Animated.View style={[SCROLL_CONTENT_GROW, bodyClearanceStyle]}>
<View style={[styles.contentGrow, bodyClearanceStyle]}>
<SheetContent style={[styles.contentGrow, contentStyle]}>{children}</SheetContent>
</Animated.View>
</View>
</ScrollView>
) : (
<View style={styles.compactStaticContent}>
<View style={[styles.compactStaticContent, bodyClearanceStyle]}>
<SheetContent style={[styles.compactStaticContent, contentStyle]}>
{children}
</SheetContent>
@@ -695,6 +710,7 @@ export function AdaptiveModalSheet({
}: AdaptiveModalSheetProps) {
const { t } = useTranslation();
const isMobile = useIsCompactFormFactor();
const isKeyboardVisible = useKeyboardVisibility(visible);
const resolvedSnapPoints = useMemo(() => snapPoints ?? ["65%", "90%"], [snapPoints]);
const isSheet = isMobile || !isWeb;
// The sheet registers itself; the desktop dialog does not use it.
@@ -812,6 +828,7 @@ export function AdaptiveModalSheet({
onClose={onClose}
testID={testID}
footer={footerView}
isKeyboardVisible={isKeyboardVisible}
scrollable={scrollable}
bodyStyle={bodyStyle}
contentStyle={contentStyle}
@@ -15,7 +15,7 @@ import DraggableFlatList, {
} from "react-native-draggable-flatlist";
import type { GestureType } from "react-native-gesture-handler";
import { useUnistyles } from "react-native-unistyles";
import { useContentDrag } from "@/components/ui/content-drag";
import { useContentDrag } from "@/components/ui/scroll-view";
import { createDragHold } from "./drag-reorder/drag-hold";
import { movedItemKey } from "./drag-reorder/native-drop";
import type {
@@ -8,15 +8,10 @@ import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { BackHeader } from "@/components/headers/back-header";
import { MenuHeader } from "@/components/headers/menu-header";
import { PressHighlight } from "@/components/ui/press-highlight";
import { withContentDrag } from "@/components/ui/content-drag";
import { useIsCompactFormFactor } from "@/constants/layout";
import { ICON_SIZE, SPACING, type Theme } from "@/styles/theme";
// Rows on a page drag to reorder, so the page stops scrolling while a drag holds the touch.
const PageScrollView =
Platform.OS === "android"
? withContentDrag(KeyboardAwareScrollView)
: withContentDrag(ScrollView);
const PageScrollView = Platform.OS === "android" ? KeyboardAwareScrollView : ScrollView;
interface PageLayoutProps {
title?: string;
@@ -66,16 +66,12 @@ function heightOf(testID: string): number {
return element(testID).getBoundingClientRect().height;
}
function textNode(rowTestID: string, text: string): HTMLElement {
const found = [...element(rowTestID).querySelectorAll("div")].find(
(node) => node.textContent === text && node.children.length === 0,
);
if (!found) throw new Error(`No text ${text}`);
return found;
}
function titleFontSize(rowTestID: string, label: string): number {
return Number.parseFloat(getComputedStyle(textNode(rowTestID, label)).fontSize);
const title = [...element(rowTestID).querySelectorAll("div")].find(
(node) => node.textContent === label && node.children.length === 0,
);
if (!title) throw new Error(`No title ${label}`);
return Number.parseFloat(getComputedStyle(title).fontSize);
}
describe("settings row density", () => {
@@ -104,52 +100,4 @@ describe("settings row density", () => {
titleFontSize("card-row", "Card row"),
);
});
it("keeps a row with a long summary one line tall on a phone-width card", () => {
container = document.createElement("div");
// A 393pt phone less the sheet's side padding.
container.style.width = "360px";
document.body.appendChild(container);
root = createRoot(container);
act(() =>
root?.render(
<SettingsCard>
<SettingsRow label="Text only" testID="text-row" />
<SettingsCollapsibleRow
label="Customize settings"
summary="Auto mode · Medium · 2 features · Add a note for when to use it"
testID="long-summary"
>
<SettingsRow label="Nested" />
</SettingsCollapsibleRow>
</SettingsCard>,
),
);
expect(heightOf("long-summary-toggle")).toBe(heightOf("text-row"));
});
it("keeps a short summary beside the chevron on a wide card", () => {
container = document.createElement("div");
container.style.width = "680px";
document.body.appendChild(container);
root = createRoot(container);
act(() =>
root?.render(
<SettingsCard>
<SettingsDetailRow
label="Speech to text"
summary="Local"
onPress={openNothing}
testID="short-summary"
/>
</SettingsCard>,
),
);
const row = element("short-summary").getBoundingClientRect();
const summary = textNode("short-summary", "Local").getBoundingClientRect();
// The summary's margin, the chevron and the row's padding: about 40px.
expect(row.right - summary.right).toBeLessThan(48);
});
});
@@ -88,13 +88,9 @@ export function SettingsRowHeader({
const hovered = pointerOver && !disabled;
const rowStyle = useMemo(() => [layout.row, hovered && styles.hovered], [hovered, layout]);
const chevronStyle = useMemo(
() => [styles.chevron, expanded && styles.chevronExpanded, styles.passThrough],
() => [styles.chevron, expanded && styles.chevronExpanded],
[expanded],
);
// A hint can be a sentence, so a hinted row gives the room to the label column and caps the
// summary. A label alone keeps its one-line width and the summary truncates in what is left.
const hinted = Boolean(hint || hintStatus);
const contentStyle = hinted ? settingsStyles.rowContent : styles.labelContent;
return (
<View
style={rowStyle}
@@ -117,7 +113,7 @@ export function SettingsRowHeader({
{leading}
</View>
) : null}
<View style={[contentStyle, styles.passThrough]}>
<View style={[settingsStyles.rowContent, styles.passThrough]}>
<View style={labelAccessory ? styles.labelRow : undefined} {...HIDDEN_FROM_ASSISTIVE_TECH}>
<Text style={layout.title}>{label}</Text>
{labelAccessory}
@@ -132,15 +128,28 @@ export function SettingsRowHeader({
<ControlSizeProvider size={layout.controlSize}>{control}</ControlSizeProvider>
</View>
) : null}
<RowTrailing hinted={hinted} external={external} hovered={hovered} summary={summary} />
{external || disabled ? null : (
<View style={chevronStyle} {...HIDDEN_FROM_ASSISTIVE_TECH}>
<ThemedChevron
size={ICON_SIZE.sm}
uniProps={hovered ? hoveredIconColorMapping : mutedIconColorMapping}
/>
</View>
)}
<View style={[styles.trailing, styles.passThrough]} {...HIDDEN_FROM_ASSISTIVE_TECH}>
{external ? (
// Drawn the same as a section header's docs link, so the two read as one thing.
<ExternalLinkLabel hovered={hovered}>{summary}</ExternalLinkLabel>
) : (
<>
{summary ? (
<Text style={styles.summary} numberOfLines={1}>
{summary}
</Text>
) : null}
{disabled ? null : (
<View style={chevronStyle}>
<ThemedChevron
size={ICON_SIZE.sm}
uniProps={hovered ? hoveredIconColorMapping : mutedIconColorMapping}
/>
</View>
)}
</>
)}
</View>
</View>
);
}
@@ -151,32 +160,6 @@ const HIDDEN_FROM_ASSISTIVE_TECH = {
"aria-hidden": true,
} as const;
/** The summary before the chevron, or the external link label in its place. */
function RowTrailing({
hinted,
external,
hovered,
summary,
}: {
hinted: boolean;
external: boolean;
hovered: boolean;
summary: string | undefined;
}) {
const style = hinted ? styles.hintedTrailing : styles.labelTrailing;
return (
<View style={[style, styles.passThrough]} {...HIDDEN_FROM_ASSISTIVE_TECH}>
{/* Drawn the same as a section header's docs link, so the two read as one thing. */}
{external ? <ExternalLinkLabel hovered={hovered}>{summary}</ExternalLinkLabel> : null}
{!external && summary ? (
<Text style={styles.summary} numberOfLines={1}>
{summary}
</Text>
) : null}
</View>
);
}
/**
* The hint with its status mark. The line keeps the hint's own height in every status, so a row
* does not move when its value arrives or its work starts. A long error is cut to the line; the
@@ -239,30 +222,10 @@ const styles = StyleSheet.create((theme) => ({
passThrough: {
pointerEvents: "none",
},
// The label keeps its one-line width and takes the free space; the summary truncates in what is
// left. Any shrink, even a fraction of a pixel, would wrap the label, so it does not shrink. The
// cap lets a long label wrap before it pushes the chevron off the row. Past the cap, the auto
// margin takes the rest of the row, so the control, summary and chevron stay together at the end.
labelContent: {
flexGrow: 1,
flexShrink: 0,
maxWidth: "75%",
paddingRight: theme.spacing[3],
marginRight: "auto",
},
labelTrailing: {
trailing: {
flexDirection: "row",
alignItems: "center",
flexShrink: 1,
minWidth: 0,
},
// A hinted row's column grows from zero width, so an unbounded summary would squeeze it to
// nothing and wrap the label one glyph per line. The summary keeps at most half the row.
hintedTrailing: {
flexDirection: "row",
alignItems: "center",
flexShrink: 1,
maxWidth: "50%",
},
hintLine: {
flexDirection: "row",
@@ -106,11 +106,11 @@ import {
selectSidebarGroupVisibility,
} from "@/components/sidebar/sidebar-group-visibility";
import {
isShiftPressEvent,
registerSidebarVisibleWorkspaceKeysReader,
useIsSidebarSelectionMode,
useIsWorkspaceBulkSelected,
useSidebarSelectionStore,
useWorkspaceSelectionPress,
} from "@/sidebar-selection";
import { useLimitedSidebarGroup } from "@/components/sidebar/use-limited-sidebar-group";
import {
@@ -1117,11 +1117,35 @@ function WorkspaceRowInner({
selected,
});
const { onPress: handleRowPress, onPressIn: handleRowPressIn } = useWorkspaceSelectionPress({
workspaceKey: workspace.workspaceKey,
onNavigate: handleNavigatePress,
onPressIn: interaction.handlePressIn,
});
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(
@@ -12,7 +12,7 @@ import {
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";
@@ -74,11 +74,11 @@ import { SidebarGroupToggleRow } from "@/components/sidebar/sidebar-group-toggle
import { selectSidebarGroupVisibility } from "@/components/sidebar/sidebar-group-visibility";
import { useLimitedSidebarGroup } from "@/components/sidebar/use-limited-sidebar-group";
import {
isShiftPressEvent,
registerSidebarVisibleWorkspaceKeysReader,
useIsSidebarSelectionMode,
useIsWorkspaceBulkSelected,
useSidebarSelectionStore,
useWorkspaceSelectionPress,
} from "@/sidebar-selection";
import type { ToggleSidebarWorkspacePin } from "@/hooks/use-sidebar-workspace-pin";
import { DraggableList, type DraggableRenderItemInfo } from "@/components/draggable-list";
@@ -936,11 +936,35 @@ function StatusWorkspaceRowInnerContent({
selected,
});
const { onPress: handleRowPress, onPressIn: handleRowPressIn } = useWorkspaceSelectionPress({
workspaceKey: workspace.workspaceKey,
onNavigate: handleNavigatePress,
onPressIn: startDragPress,
});
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
+16 -6
View File
@@ -25,6 +25,7 @@ import {
} from "react-native";
import { createPortal } from "react-dom";
import { useTranslation } from "react-i18next";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import type { EditingTextInputHandle } from "@/components/ui/text-input";
import { StyleSheet, useUnistyles } from "react-native-unistyles";
import { useIsCompactFormFactor } from "@/constants/layout";
@@ -1139,22 +1140,31 @@ function MobileComboboxSheet(props: MobileBodyProps): ReactElement {
}
/**
* Rendered on the far side of the sheet's portal so `SheetVisibleFrame` clears the screen's
* bottom inset in lockstep with the keyboard, not the inset left where the combobox was opened.
* Rendered on the far side of the sheet's portal so it clears the screen's bottom inset, not the
* one left where the combobox was opened: inside a sheet tab, none is.
*/
function ComboboxSheetFrame({ footer, children }: { footer?: ReactNode; children: ReactNode }) {
const { bottom: safeAreaBottom } = useSafeAreaInsets();
const frameStyle = useMemo(
() => [styles.mobileSheetFrame, { paddingBottom: footer ? 0 : safeAreaBottom }],
[footer, safeAreaBottom],
);
const footerStyle = useMemo(
() => [styles.footer, { paddingBottom: safeAreaBottom }],
[safeAreaBottom],
);
const footerView = useMemo(
() =>
footer ? (
<View style={styles.footer} dataSet={FOOTER_DATASET}>
<View style={footerStyle} dataSet={FOOTER_DATASET}>
{footer}
</View>
) : undefined,
[footer],
[footer, footerStyle],
);
return (
<SheetVisibleFrame footer={footerView} safeAreaInset="frame">
<View style={styles.mobileSheetFrame}>{children}</View>
<SheetVisibleFrame footer={footerView}>
<View style={frameStyle}>{children}</View>
</SheetVisibleFrame>
);
}
@@ -1,106 +0,0 @@
import React, { act, Children, useCallback, type ReactNode } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, describe, expect, it } from "vitest";
import { useContentDrag, withContentDrag } from "./content-drag";
let root: Root | null = null;
let container: HTMLDivElement | null = null;
afterEach(() => {
act(() => root?.unmount());
container?.remove();
root = null;
container = null;
});
interface FakeScrollProps {
scrollEnabled?: boolean;
children?: ReactNode;
}
/** Stands in for a scroll view: it reports the props a native scroll view would act on. */
function FakeScroll({ scrollEnabled, children }: FakeScrollProps) {
return (
<div
data-testid="scroll"
data-scroll-enabled={String(scrollEnabled)}
data-child-count={Children.toArray(children).length}
>
{children}
</div>
);
}
const DragHostScroll = withContentDrag<FakeScrollProps, unknown>(FakeScroll);
/** A row that holds a drag the way a draggable list does: active from press until release. */
function DragRow() {
const { setActive } = useContentDrag();
const arm = useCallback(() => setActive(true), [setActive]);
const release = useCallback(() => setActive(false), [setActive]);
return (
<>
<button type="button" data-testid="arm" onClick={arm} />
<button type="button" data-testid="release" onClick={release} />
</>
);
}
function mount(node: React.ReactElement) {
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
act(() => root?.render(node));
}
function scroll(): HTMLElement {
const found = document.querySelector('[data-testid="scroll"]');
if (!(found instanceof HTMLElement)) throw new Error("No scroll view rendered");
return found;
}
function press(testID: string) {
const button = document.querySelector(`[data-testid="${testID}"]`);
if (!(button instanceof HTMLElement)) throw new Error(`No ${testID}`);
act(() => button.click());
}
describe("withContentDrag", () => {
it("stops the scroll while a child drag holds the touch, and resumes after", () => {
mount(
<DragHostScroll>
<DragRow />
</DragHostScroll>,
);
expect(scroll().dataset.scrollEnabled).toBe("true");
press("arm");
expect(scroll().dataset.scrollEnabled).toBe("false");
press("release");
expect(scroll().dataset.scrollEnabled).toBe("true");
});
it("keeps a scroll view the caller disabled disabled after the drag", () => {
mount(
<DragHostScroll scrollEnabled={false}>
<DragRow />
</DragHostScroll>,
);
press("arm");
press("release");
expect(scroll().dataset.scrollEnabled).toBe("false");
});
it("passes the children through as given, so sticky header indices still count them", () => {
mount(
<DragHostScroll>
<div>Intro</div>
<div>Section header</div>
<DragRow />
</DragHostScroll>,
);
expect(scroll().dataset.childCount).toBe("3");
});
});
@@ -1,64 +0,0 @@
import {
createContext,
forwardRef,
useContext,
useMemo,
useState,
type ComponentType,
type Ref,
} from "react";
import type { AttachSheetContentDrag } from "./bottom-sheet-scope";
/**
* What a child that drags inside a scroll view needs to keep the touch: `setActive(true)` stops
* the scroll until the drag ends, so the scroll view cannot take the finger once the drag has
* armed. Inside a sheet the child also registers its drag gesture through `attach` so the sheet's
* pan waits for it; outside a sheet there is no `attach`. Outside any scroll view that hosts
* content drags, `setActive` does nothing.
*/
export interface ContentDrag {
attach: AttachSheetContentDrag | undefined;
setActive: (active: boolean) => void;
}
const ContentDragContext = createContext<ContentDrag | null>(null);
const NO_CONTENT_DRAG: ContentDrag = { attach: undefined, setActive: () => {} };
export function useContentDrag(): ContentDrag {
return useContext(ContentDragContext) ?? NO_CONTENT_DRAG;
}
function useNoAttach(): AttachSheetContentDrag | undefined {
return undefined;
}
/**
* Makes a scroll view host content drags: it stops scrolling while a child drag is active. Without
* it, a vertical drag in a row of a scrolling page is taken by the page scroll once the finger
* moves past the touch slop, before the row's drag gesture can activate. A sheet's scroll view
* passes `useAttach` so its children can also register their gesture with the sheet.
*
* The context wraps the scroll view rather than its content, so the scroll view receives its
* children as given: `stickyHeaderIndices` counts them.
*/
export function withContentDrag<P extends { scrollEnabled?: boolean }, T>(
Scroll: ComponentType<P & { ref?: Ref<T> }>,
useAttach: () => AttachSheetContentDrag | undefined = useNoAttach,
) {
return forwardRef<T, P>(function ContentDragScrollView(props, ref) {
const attach = useAttach();
const [dragging, setDragging] = useState(false);
const contentDrag = useMemo(() => ({ attach, setActive: setDragging }), [attach]);
// Overriding one prop of `P` keeps it a `P`; TypeScript cannot prove that for a generic.
const scrollProps = {
...props,
scrollEnabled: !dragging && props.scrollEnabled !== false,
} as P;
return (
<ContentDragContext.Provider value={contentDrag}>
<Scroll {...scrollProps} ref={ref} />
</ContentDragContext.Provider>
);
});
}
@@ -150,17 +150,17 @@ export function ContextMenuTrigger({
);
const propsOnLongPress = props.onLongPress;
const handleNativeLongPress = useCallback(
const handleLongPress = useCallback(
(event: GestureResponderEvent) => {
if (isWeb) {
propsOnLongPress?.(event);
return;
}
openAtEvent(event);
propsOnLongPress?.(event);
},
[propsOnLongPress, openAtEvent],
);
// The web menu opens on right-click, not long press. Any onLongPress makes react-native-web cancel
// the click that ends a held press, and only a later press-in clears that, which Ctrl+click never
// gets. So on web, pass the caller's onLongPress through and nothing else.
const handleLongPress = isWeb ? propsOnLongPress : handleNativeLongPress;
const handleContextMenu = useCallback(
(event: unknown) => {
@@ -212,6 +212,6 @@ export function useIsolatedBottomSheetVisibility({
};
}
export { SheetVisibleFrame, useBottomSheetSafeAreaPaddingStyle } from "./visible-frame";
export { SheetVisibleFrame } from "./visible-frame";
export { systemBackPress } from "./back-press";
export { SheetHostScope } from "./host-scope";
@@ -1,8 +1,5 @@
import { describe, expect, it } from "vitest";
import {
getBottomSheetSafeAreaPaddingBottom,
getBottomSheetVisibleContentHeight,
} from "./visible-frame-layout";
import { getBottomSheetVisibleContentHeight } from "./visible-frame-layout";
describe("getBottomSheetVisibleContentHeight", () => {
it("stops subtracting the retained keyboard height after the keyboard hides", () => {
@@ -16,120 +13,6 @@ describe("getBottomSheetVisibleContentHeight", () => {
expect(getBottomSheetVisibleContentHeight({ ...layout, isKeyboardVisible: true })).toBe(418);
expect(getBottomSheetVisibleContentHeight({ ...layout, isKeyboardVisible: false })).toBe(762);
});
it("ignores non-positive keyboard heights", () => {
const layout = {
containerHeight: 874,
contentPosition: 88,
handleHeight: 24,
keyboardHeight: -10,
isKeyboardVisible: true,
};
expect(getBottomSheetVisibleContentHeight(layout)).toBe(762);
});
});
describe("getBottomSheetSafeAreaPaddingBottom", () => {
it("keeps full safe-area clearance while the keyboard is hidden, even with retained keyboard height", () => {
expect(
getBottomSheetSafeAreaPaddingBottom({
keyboardHeight: 344,
isKeyboardVisible: false,
safeAreaBottom: 48,
}),
).toBe(48);
});
it("keeps full safe-area clearance during Gorhom's first-open frame before heightWithinContainer is populated", () => {
expect(
getBottomSheetSafeAreaPaddingBottom({
keyboardHeight: 0,
isKeyboardVisible: true,
safeAreaBottom: 48,
}),
).toBe(48);
});
it("drops safe-area clearance to 0 when the keyboard height covers the bottom safe area", () => {
expect(
getBottomSheetSafeAreaPaddingBottom({
keyboardHeight: 344,
isKeyboardVisible: true,
safeAreaBottom: 48,
}),
).toBe(0);
});
it("preserves remaining safe-area clearance when keyboard height is smaller than the bottom inset", () => {
expect(
getBottomSheetSafeAreaPaddingBottom({
keyboardHeight: 20,
isKeyboardVisible: true,
safeAreaBottom: 48,
}),
).toBe(28);
});
it("returns 0 when there is no bottom safe-area inset", () => {
expect(
getBottomSheetSafeAreaPaddingBottom({
keyboardHeight: 0,
isKeyboardVisible: false,
safeAreaBottom: 0,
}),
).toBe(0);
});
it("holds the invariant that visible frame height + paddingBottom never places the footer inside the bottom safe area across keyboard open/close transitions", () => {
const containerHeight = 1608;
const contentPosition = 161;
const handleHeight = 48;
const safeAreaBottom = 96;
const restingContentBottom = containerHeight - safeAreaBottom;
// Sequence matching real Android/iOS Gorhom keyboard transitions:
// 1. Resting closed
// 2. First open intermediate state (status=SHOWN before heightWithinContainer updates)
// 3. Open settled (heightWithinContainer = 598)
// 4. Close (status=HIDDEN while heightWithinContainer retains 598)
// 5. Partial accessory bar (heightWithinContainer = 40 < safeAreaBottom)
const transitions = [
{ isKeyboardVisible: false, keyboardHeight: 0, expectedContentBottom: restingContentBottom },
{ isKeyboardVisible: true, keyboardHeight: 0, expectedContentBottom: restingContentBottom },
{
isKeyboardVisible: true,
keyboardHeight: 598,
expectedContentBottom: containerHeight - 598,
},
{
isKeyboardVisible: false,
keyboardHeight: 598,
expectedContentBottom: restingContentBottom,
},
{ isKeyboardVisible: true, keyboardHeight: 40, expectedContentBottom: restingContentBottom },
];
for (const step of transitions) {
const height = getBottomSheetVisibleContentHeight({
containerHeight,
contentPosition,
handleHeight,
keyboardHeight: step.keyboardHeight,
isKeyboardVisible: step.isKeyboardVisible,
});
const paddingBottom = getBottomSheetSafeAreaPaddingBottom({
keyboardHeight: step.keyboardHeight,
isKeyboardVisible: step.isKeyboardVisible,
safeAreaBottom,
});
// Inside a border-box frame at `contentPosition + handleHeight`, the bottom of the footer
// sits at `contentPosition + handleHeight + height - paddingBottom`.
const footerBottomY = contentPosition + handleHeight + height - paddingBottom;
expect(footerBottomY).toBe(step.expectedContentBottom);
expect(footerBottomY).toBeLessThanOrEqual(restingContentBottom);
}
});
});
// Below the lowest snap the frame must travel with the sheet, not shrink to the screen edge.
@@ -1,4 +1,4 @@
export interface BottomSheetVisibleContentHeightInput {
interface BottomSheetVisibleContentHeightInput {
containerHeight: number;
contentPosition: number;
lowestDetentPosition?: number;
@@ -7,28 +7,6 @@ export interface BottomSheetVisibleContentHeightInput {
isKeyboardVisible: boolean;
}
export interface BottomSheetSafeAreaPaddingInput {
keyboardHeight: number;
isKeyboardVisible: boolean;
safeAreaBottom: number;
}
/**
* Effective keyboard height inside the sheet container.
*
* Gorhom retains `heightWithinContainer` after the keyboard hides, and on first show `status`
* flips to `SHOWN` before its reaction writes `heightWithinContainer`. Treating both states as 0
* keeps frame height and safe-area clearance in lockstep.
*/
export function getBottomSheetEffectiveKeyboardHeight(
keyboardHeight: number,
isKeyboardVisible: boolean,
): number {
"worklet";
if (!isKeyboardVisible || keyboardHeight <= 0) return 0;
return keyboardHeight;
}
export function getBottomSheetVisibleContentHeight({
containerHeight,
contentPosition,
@@ -40,29 +18,8 @@ export function getBottomSheetVisibleContentHeight({
"worklet";
if (containerHeight < 0 || handleHeight < 0) return 0;
const position = Math.min(contentPosition, lowestDetentPosition ?? contentPosition);
const effectiveKeyboardHeight = getBottomSheetEffectiveKeyboardHeight(
keyboardHeight,
isKeyboardVisible,
return Math.max(
0,
containerHeight - position - handleHeight - (isKeyboardVisible ? keyboardHeight : 0),
);
return Math.max(0, containerHeight - position - handleHeight - effectiveKeyboardHeight);
}
/**
* Bottom safe-area clearance derived from the same keyboard inset subtracted from
* `SheetVisibleFrame`'s height so both update in one UI-thread commit.
*
* Invariant: `effectiveKeyboardHeight + paddingBottom >= safeAreaBottom`.
*/
export function getBottomSheetSafeAreaPaddingBottom({
keyboardHeight,
isKeyboardVisible,
safeAreaBottom,
}: BottomSheetSafeAreaPaddingInput): number {
"worklet";
if (safeAreaBottom <= 0) return 0;
const effectiveKeyboardHeight = getBottomSheetEffectiveKeyboardHeight(
keyboardHeight,
isKeyboardVisible,
);
return Math.max(0, safeAreaBottom - effectiveKeyboardHeight);
}
@@ -2,63 +2,21 @@ import type { ReactNode } from "react";
import { View, StyleSheet } from "react-native";
import { KEYBOARD_STATUS, useBottomSheetInternal } from "@gorhom/bottom-sheet";
import Animated, { useAnimatedStyle } from "react-native-reanimated";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import {
getBottomSheetSafeAreaPaddingBottom,
getBottomSheetVisibleContentHeight,
} from "./visible-frame-layout";
import { getBottomSheetVisibleContentHeight } from "./visible-frame-layout";
/**
* UI-thread bottom safe-area padding synchronized with Gorhom's keyboard state.
* Use this for scrollable sheet bodies without a footer so content scrolls behind the system
* navigation bar while still clearing it at rest and dropping the padding in lockstep with
* `SheetVisibleFrame` when the keyboard opens or closes.
*/
export function useBottomSheetSafeAreaPaddingStyle(enabled = true) {
const { bottom: safeAreaBottom } = useSafeAreaInsets();
const { animatedKeyboardState } = useBottomSheetInternal();
return useAnimatedStyle(() => {
const keyboard = animatedKeyboardState.get();
return {
paddingBottom: enabled
? getBottomSheetSafeAreaPaddingBottom({
keyboardHeight: keyboard.heightWithinContainer,
isKeyboardVisible: keyboard.status === KEYBOARD_STATUS.SHOWN,
safeAreaBottom,
})
: 0,
};
}, [animatedKeyboardState, enabled, safeAreaBottom]);
}
/**
* Fixed-detent sheet content. The footer shares the sheet's translation below its lowest snap,
* and frame height + bottom safe-area clearance update together in one UI-thread commit so the
* footer never flashes behind the system navigation bar on keyboard show/hide.
*/
/** Fixed-detent sheet content. The footer shares the sheet's translation below its lowest snap. */
export function SheetVisibleFrame({
children,
footer,
safeAreaInset = "footer",
}: {
children: ReactNode;
footer?: ReactNode;
/**
* Where bottom safe-area clearance is applied:
* - `"footer"` (default): pads the frame whenever `footer` is present.
* - `"frame"`: always pads the frame, with or without a footer.
* - `"none"`: caller owns safe-area clearance.
*/
safeAreaInset?: "footer" | "frame" | "none";
}) {
const { bottom: safeAreaBottom } = useSafeAreaInsets();
const { animatedDetentsState, animatedKeyboardState, animatedLayoutState, animatedPosition } =
useBottomSheetInternal();
const padFrame = safeAreaInset === "frame" || (safeAreaInset === "footer" && Boolean(footer));
const visibleStyle = useAnimatedStyle(() => {
const { containerHeight, handleHeight } = animatedLayoutState.get();
const keyboard = animatedKeyboardState.get();
const isKeyboardVisible = keyboard.status === KEYBOARD_STATUS.SHOWN;
return {
height: getBottomSheetVisibleContentHeight({
containerHeight,
@@ -66,24 +24,10 @@ export function SheetVisibleFrame({
contentPosition: animatedPosition.get(),
lowestDetentPosition: animatedDetentsState.get().detents?.[0],
keyboardHeight: keyboard.heightWithinContainer,
isKeyboardVisible,
isKeyboardVisible: keyboard.status === KEYBOARD_STATUS.SHOWN,
}),
paddingBottom: padFrame
? getBottomSheetSafeAreaPaddingBottom({
keyboardHeight: keyboard.heightWithinContainer,
isKeyboardVisible,
safeAreaBottom,
})
: 0,
};
}, [
animatedDetentsState,
animatedKeyboardState,
animatedLayoutState,
animatedPosition,
padFrame,
safeAreaBottom,
]);
}, [animatedDetentsState, animatedKeyboardState, animatedLayoutState, animatedPosition]);
return (
<Animated.View style={[styles.frame, visibleStyle]}>
<View style={styles.body}>{children}</View>
+43 -10
View File
@@ -1,4 +1,4 @@
import { forwardRef, type Ref } from "react";
import { createContext, forwardRef, useContext, useMemo, useState, type Ref } from "react";
import {
ScrollView as NativeScrollView,
FlatList as NativeFlatList,
@@ -12,13 +12,15 @@ import {
type NativeViewGestureHandlerProps,
} from "react-native-gesture-handler";
import { isNative } from "@/constants/platform";
import { useAttachSheetContentDrag, useIsInsideBottomSheet } from "./bottom-sheet-scope";
import { withContentDrag } from "./content-drag";
import {
useAttachSheetContentDrag,
useIsInsideBottomSheet,
type AttachSheetContentDrag,
} from "./bottom-sheet-scope";
// Both libraries forward to the RN FlatList and ScrollView instances. Their published ref types
// Both libraries forward to the RN FlatList instance. Their published ref types
// disagree about getScrollResponder (Gorhom) and include the component function
// in the instance intersection (RNGH); keep that type discrepancy at this boundary.
const SheetScroll = BottomSheetScrollView as unknown as typeof NativeScrollView;
const SheetFlatList = BottomSheetFlatList as unknown as typeof NativeFlatList;
const HorizontalFlatList = GestureFlatList as unknown as <Item>(
props: FlatListProps<Item> & NativeViewGestureHandlerProps & { ref?: Ref<NativeFlatList<Item>> },
@@ -28,7 +30,7 @@ const HorizontalFlatList = GestureFlatList as unknown as <Item>(
export const ScrollView = forwardRef<NativeScrollView, ScrollViewProps>(
function ScrollView(props, ref) {
const inSheet = useIsInsideBottomSheet();
if (!inSheet) return <PageScrollView {...props} ref={ref} />;
if (!inSheet) return <NativeScrollView {...props} ref={ref} />;
if (props.horizontal) {
return isNative ? (
<GestureScrollView {...props} ref={ref} disallowInterruption />
@@ -40,11 +42,42 @@ export const ScrollView = forwardRef<NativeScrollView, ScrollViewProps>(
},
);
const PageScrollView = withContentDrag<ScrollViewProps, NativeScrollView>(NativeScrollView);
/**
* What a child that drags inside a sheet needs to keep the touch: it registers its drag gesture
* through `attach` so the sheet's pan waits for it, and `setActive(true)` stops the sheet's
* scroll until the drag ends. Outside a sheet scroll there is no `attach` and `setActive` does
* nothing.
*/
export interface ContentDrag {
attach: AttachSheetContentDrag | undefined;
setActive: (active: boolean) => void;
}
const SheetScrollView = withContentDrag<ScrollViewProps, NativeScrollView>(
SheetScroll,
useAttachSheetContentDrag,
const ContentDragContext = createContext<ContentDrag | null>(null);
const NO_CONTENT_DRAG: ContentDrag = { attach: undefined, setActive: () => {} };
export function useContentDrag(): ContentDrag {
return useContext(ContentDragContext) ?? NO_CONTENT_DRAG;
}
const SheetScrollView = forwardRef<NativeScrollView, ScrollViewProps>(
function SheetScrollView(props, ref) {
const attach = useAttachSheetContentDrag();
const [dragging, setDragging] = useState(false);
const contentDrag = useMemo(() => ({ attach, setActive: setDragging }), [attach]);
return (
<BottomSheetScrollView
{...props}
scrollEnabled={!dragging && props.scrollEnabled !== false}
ref={ref}
>
<ContentDragContext.Provider value={contentDrag}>
{props.children}
</ContentDragContext.Provider>
</BottomSheetScrollView>
);
},
);
function SheetAwareFlatList<Item>(props: FlatListProps<Item>, ref: Ref<NativeFlatList<Item>>) {
@@ -0,0 +1,21 @@
import { useSyncExternalStore } from "react";
import { KeyboardController, KeyboardEvents } from "react-native-keyboard-controller";
const subscribe = (onStoreChange: () => void) => {
const subscriptions = (["keyboardWillShow", "keyboardDidHide"] as const).map((event) =>
KeyboardEvents.addListener(event, onStoreChange),
);
return () => {
for (const subscription of subscriptions) {
subscription.remove();
}
};
};
export function useKeyboardVisibility(enabled = true): boolean {
return useSyncExternalStore(
subscribe,
() => (enabled ? KeyboardController.isVisible() : false),
() => false,
);
}
@@ -0,0 +1,3 @@
export function useKeyboardVisibility(_enabled = true): boolean {
return false;
}
+1 -2
View File
@@ -14,5 +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 { readPressModifiers } from "./internal/press-modifiers";
export type { PressModifiers } from "./internal/press-modifiers";
export { isShiftKeyDown } from "./internal/shift-modifier";
@@ -1,111 +0,0 @@
import { getShortcutOs } from "@/utils/shortcut-platform";
export type HeldModifierKey = "Shift" | "Meta" | "Control";
export interface HeldModifierKeyEvent {
key: string;
code?: string;
shiftKey: boolean;
metaKey: boolean;
ctrlKey: boolean;
}
export interface HeldModifierTracker {
isDown(key: HeldModifierKey): boolean;
handleKeyDown(event: HeldModifierKeyEvent): void;
handleKeyUp(event: HeldModifierKeyEvent): void;
reset(): void;
}
const MODIFIER_FLAGS = {
Shift: "shiftKey",
Meta: "metaKey",
Control: "ctrlKey",
} as const satisfies Record<HeldModifierKey, keyof HeldModifierKeyEvent>;
const MODIFIER_KEYS = Object.keys(MODIFIER_FLAGS) as HeldModifierKey[];
/**
* Tracks which physical modifier keys are held across DOM and native hardware keyboard streams so
* press handlers that omit modifier flags (native GestureResponderEvent, touch-synthesized clicks)
* can still observe Shift+tap or Cmd+tap from a hardware keyboard.
*/
export function createHeldModifierTracker(): HeldModifierTracker {
const pressedCodes: Record<HeldModifierKey, Set<string>> = {
Shift: new Set(),
Meta: new Set(),
Control: new Set(),
};
// A key reported without a modifier's flag means that modifier's key-up was swallowed.
const clearReleased = (event: HeldModifierKeyEvent) => {
for (const modifier of MODIFIER_KEYS) {
if (event.key !== modifier && !event[MODIFIER_FLAGS[modifier]]) {
pressedCodes[modifier].clear();
}
}
};
return {
isDown: (key) => pressedCodes[key].size > 0,
handleKeyDown(event) {
const modifier = MODIFIER_KEYS.find((key) => key === event.key);
if (modifier) {
pressedCodes[modifier].add(event.code || modifier);
}
clearReleased(event);
},
handleKeyUp(event) {
const modifier = MODIFIER_KEYS.find((key) => key === event.key);
if (modifier) {
pressedCodes[modifier].delete(event.code || modifier);
if (!event[MODIFIER_FLAGS[modifier]]) {
pressedCodes[modifier].clear();
}
}
clearReleased(event);
},
reset() {
for (const modifier of MODIFIER_KEYS) {
pressedCodes[modifier].clear();
}
},
};
}
export const heldModifiers = createHeldModifierTracker();
/**
* Modifiers that accompanied a pointer press. `mod` is the platform primary modifier the shortcut
* layer binds as `mod`: Cmd on macOS/iOS/iPadOS, Ctrl on Windows, Linux and Android. Ctrl on macOS
* is the secondary click, so it never counts as `mod` there.
*/
export interface PressModifiers {
shift: boolean;
mod: boolean;
}
interface PressModifierContext {
isMac: boolean;
held: Pick<HeldModifierTracker, "isDown">;
}
export function readPressModifiers(
event: unknown,
context: PressModifierContext = { isMac: getShortcutOs() === "mac", held: heldModifiers },
): PressModifiers {
const modKey: HeldModifierKey = context.isMac ? "Meta" : "Control";
return {
shift: hasPressFlag(event, "shiftKey") || context.held.isDown("Shift"),
mod: hasPressFlag(event, MODIFIER_FLAGS[modKey]) || context.held.isDown(modKey),
};
}
function hasPressFlag(event: unknown, flag: "shiftKey" | "metaKey" | "ctrlKey"): boolean {
if (typeof event !== "object" || event === null) return false;
if (Reflect.get(event, flag) === true) return true;
const nativeEvent = Reflect.get(event, "nativeEvent");
return (
typeof nativeEvent === "object" &&
nativeEvent !== null &&
Reflect.get(nativeEvent, flag) === true
);
}
@@ -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();
}
@@ -300,111 +300,49 @@ describe("hardware source adapter", () => {
});
});
function modifierKey(
key: string,
code: string,
flags: { shiftKey?: boolean; metaKey?: boolean; ctrlKey?: boolean } = {},
) {
return { key, code, shiftKey: false, metaKey: false, ctrlKey: false, ...flags };
}
describe("held modifier tracking", () => {
describe("shift modifier tracking", () => {
it("tracks left/right Shift holds, self-heals on non-shifted keys, and resets on blur", async () => {
const { createHeldModifierTracker } = await import("./internal/press-modifiers");
const tracker = createHeldModifierTracker();
expect(tracker.isDown("Shift")).toBe(false);
const { createShiftModifierTracker } = await import("./internal/shift-modifier");
const tracker = createShiftModifierTracker();
expect(tracker.isDown()).toBe(false);
tracker.handleKeyDown(modifierKey("Shift", "ShiftLeft", { shiftKey: true }));
expect(tracker.isDown("Shift")).toBe(true);
tracker.handleKeyDown({ key: "Shift", code: "ShiftLeft", shiftKey: true });
expect(tracker.isDown()).toBe(true);
tracker.handleKeyDown(modifierKey("Shift", "ShiftRight", { shiftKey: true }));
tracker.handleKeyUp(modifierKey("Shift", "ShiftLeft", { shiftKey: true }));
expect(tracker.isDown("Shift")).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(modifierKey("Shift", "ShiftRight"));
expect(tracker.isDown("Shift")).toBe(false);
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(modifierKey("Shift", "ShiftLeft", { shiftKey: true }));
expect(tracker.isDown("Shift")).toBe(true);
tracker.handleKeyDown(modifierKey("a", "KeyA"));
expect(tracker.isDown("Shift")).toBe(false);
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(modifierKey("Shift", "ShiftLeft", { shiftKey: true }));
expect(tracker.isDown("Shift")).toBe(true);
tracker.handleKeyDown({ key: "Shift", code: "ShiftLeft", shiftKey: true });
expect(tracker.isDown()).toBe(true);
tracker.reset();
expect(tracker.isDown("Shift")).toBe(false);
expect(tracker.isDown()).toBe(false);
});
it("tracks Cmd and Ctrl holds independently of Shift", async () => {
const { createHeldModifierTracker } = await import("./internal/press-modifiers");
const tracker = createHeldModifierTracker();
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);
tracker.handleKeyDown(modifierKey("Meta", "MetaLeft", { metaKey: true }));
tracker.handleKeyDown(modifierKey("Shift", "ShiftLeft", { metaKey: true, shiftKey: true }));
expect([tracker.isDown("Meta"), tracker.isDown("Shift"), tracker.isDown("Control")]).toEqual([
true,
true,
false,
]);
shiftModifier.handleKeyDown({ key: "Shift", code: "ShiftLeft", shiftKey: true });
expect(isShiftKeyDown()).toBe(true);
tracker.handleKeyUp(modifierKey("Shift", "ShiftLeft", { metaKey: true }));
expect([tracker.isDown("Meta"), tracker.isDown("Shift")]).toEqual([true, false]);
// A key reported without the Meta flag means its key-up was swallowed.
tracker.handleKeyDown(modifierKey("a", "KeyA"));
expect(tracker.isDown("Meta")).toBe(false);
tracker.handleKeyDown(modifierKey("Control", "ControlRight", { ctrlKey: true }));
expect(tracker.isDown("Control")).toBe(true);
tracker.handleKeyUp(modifierKey("Control", "ControlRight"));
expect(tracker.isDown("Control")).toBe(false);
});
});
describe("press modifiers", () => {
it("reads Shift and the platform primary modifier from a pointer press", async () => {
const { createHeldModifierTracker, readPressModifiers } =
await import("./internal/press-modifiers");
const held = createHeldModifierTracker();
const mac = { isMac: true, held };
const other = { isMac: false, held };
expect(readPressModifiers({ shiftKey: true }, mac)).toEqual({ shift: true, mod: false });
expect(readPressModifiers({ nativeEvent: { shiftKey: true } }, other)).toEqual({
shift: true,
mod: false,
});
expect(readPressModifiers({ metaKey: true }, mac)).toEqual({ shift: false, mod: true });
expect(readPressModifiers({ ctrlKey: true }, other)).toEqual({ shift: false, mod: true });
// Ctrl+click is the secondary click on macOS, and Windows/Linux have no Cmd.
expect(readPressModifiers({ ctrlKey: true }, mac)).toEqual({ shift: false, mod: false });
expect(readPressModifiers({ metaKey: true }, other)).toEqual({ shift: false, mod: false });
expect(readPressModifiers(null, mac)).toEqual({ shift: false, mod: false });
});
it("falls back to held hardware keys when a native press omits modifiers", async () => {
const { createHeldModifierTracker, readPressModifiers } =
await import("./internal/press-modifiers");
const held = createHeldModifierTracker();
const responderEvent = { nativeEvent: { locationX: 12, locationY: 8 } };
held.handleKeyDown(modifierKey("Meta", "MetaLeft", { metaKey: true }));
expect(readPressModifiers(responderEvent, { isMac: true, held })).toEqual({
shift: false,
mod: true,
});
expect(readPressModifiers(responderEvent, { isMac: false, held })).toEqual({
shift: false,
mod: false,
});
held.reset();
held.handleKeyDown(modifierKey("Shift", "ShiftLeft", { shiftKey: true }));
expect(readPressModifiers(responderEvent, { isMac: true, held })).toEqual({
shift: true,
mod: false,
});
shiftModifier.handleKeyUp({ key: "Shift", code: "ShiftLeft", shiftKey: false });
expect(isShiftKeyDown()).toBe(false);
} finally {
shiftModifier.reset();
}
});
});
+5 -5
View File
@@ -1,7 +1,7 @@
import { usesDesktopBindings } from "./internal/conventions";
import { createKeyboardPipeline } from "./internal/pipeline";
import { overlays } from "./internal/overlays";
import { heldModifiers } from "./internal/press-modifiers";
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";
@@ -251,12 +251,12 @@ export function useKeyboardShortcuts({
);
const handleKeyDown = useStableEvent((input: KeyboardSourceInput) => {
heldModifiers.handleKeyDown(input.event);
shiftModifier.handleKeyDown(input.event);
return pipeline.keyDown(input);
});
const handleKeyUp = useStableEvent((event: KeyboardInputEvent) => {
heldModifiers.handleKeyUp(event);
shiftModifier.handleKeyUp(event);
const key = event.key ?? "";
if (key === badgeModifierKey) {
setBadgeModifierDown(false);
@@ -264,7 +264,7 @@ export function useKeyboardShortcuts({
});
const handleBlur = useStableEvent(() => {
heldModifiers.reset();
shiftModifier.reset();
resetModifiers();
});
@@ -282,7 +282,7 @@ export function useKeyboardShortcuts({
});
return () => {
detach();
heldModifiers.reset();
shiftModifier.reset();
pipeline.dispose();
};
}, [enabled, pipeline, handleKeyDown, handleKeyUp, handleBlur]);
+1 -1
View File
@@ -1,3 +1,4 @@
export { isShiftPressEvent } from "./internal/selection-state";
export {
registerSidebarVisibleWorkspaceKeysReader,
useIsSidebarSelectionMode,
@@ -5,4 +6,3 @@ export {
useSidebarSelectionStore,
} from "./internal/selection-store";
export { SidebarSelectionHost } from "./internal/sidebar-selection-host";
export { useWorkspaceSelectionPress } from "./internal/workspace-selection-press";
@@ -3,6 +3,7 @@ import {
enterWorkspaceSelection,
exitWorkspaceSelection,
INITIAL_WORKSPACE_SELECTION_STATE,
isShiftPressEvent,
reconcileWorkspaceSelection,
selectWorkspaceRange,
toggleWorkspaceSelection,
@@ -50,35 +51,6 @@ describe("sidebar workspace selection state", () => {
expect([...backward.selectedKeys].sort()).toEqual(["ws-2", "ws-3", "ws-4"]);
});
it("replaces the previous Shift range so a closer Shift+click shrinks it, like Finder", () => {
const visible = ["ws-1", "ws-2", "ws-3", "ws-4", "ws-5", "ws-6"];
let state = enterWorkspaceSelection("ws-1");
state = toggleWorkspaceSelection(state, "ws-3");
state = selectWorkspaceRange(state, "ws-6", visible);
expect([...state.selectedKeys].sort()).toEqual(["ws-1", "ws-3", "ws-4", "ws-5", "ws-6"]);
state = selectWorkspaceRange(state, "ws-4", visible);
expect([...state.selectedKeys].sort()).toEqual(["ws-1", "ws-3", "ws-4"]);
// Crossing over the anchor flips the range without dropping the earlier pick.
state = selectWorkspaceRange(state, "ws-2", visible);
expect([...state.selectedKeys].sort()).toEqual(["ws-1", "ws-2", "ws-3"]);
expect(state.anchorKey).toBe("ws-3");
});
it("commits the Shift range once a toggle moves the anchor", () => {
const visible = ["ws-1", "ws-2", "ws-3", "ws-4", "ws-5", "ws-6"];
let state = enterWorkspaceSelection("ws-1");
state = selectWorkspaceRange(state, "ws-3", visible);
state = toggleWorkspaceSelection(state, "ws-5");
// The new anchor is ws-5; shrinking its range must keep ws-1..ws-3.
state = selectWorkspaceRange(state, "ws-6", visible);
state = selectWorkspaceRange(state, "ws-5", visible);
expect([...state.selectedKeys].sort()).toEqual(["ws-1", "ws-2", "ws-3", "ws-5"]);
});
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",
@@ -106,4 +78,16 @@ describe("sidebar workspace selection state", () => {
it("resets completely on exit", () => {
expect(exitWorkspaceSelection()).toBe(INITIAL_WORKSPACE_SELECTION_STATE);
});
it("detects Shift on direct, nativeEvent, or hardware modifier payloads", () => {
expect(isShiftPressEvent({ shiftKey: true })).toBe(true);
expect(isShiftPressEvent({ nativeEvent: { shiftKey: true } })).toBe(true);
expect(isShiftPressEvent({ shiftKey: false, nativeEvent: { shiftKey: false } })).toBe(false);
expect(isShiftPressEvent(null)).toBe(false);
// Native GestureResponderEvent omits shiftKey; falls back to hardware Shift state.
const nativeResponderEvent = { nativeEvent: { locationX: 12, locationY: 8 } };
expect(isShiftPressEvent(nativeResponderEvent, () => false)).toBe(false);
expect(isShiftPressEvent(nativeResponderEvent, () => true)).toBe(true);
});
});
@@ -1,13 +1,9 @@
import { isShiftKeyDown } from "@/keyboard";
export interface WorkspaceSelectionState {
active: boolean;
selectedKeys: ReadonlySet<string>;
anchorKey: string | null;
/**
* Selection as it stood before the current run of Shift+clicks from `anchorKey`. Each Shift+click
* rebuilds the selection from this base, so a closer Shift+click shrinks the range like Finder.
* Null until the first Shift+click after the anchor moves.
*/
rangeBaseKeys: ReadonlySet<string> | null;
}
const EMPTY_KEYS: ReadonlySet<string> = new Set();
@@ -16,7 +12,6 @@ export const INITIAL_WORKSPACE_SELECTION_STATE: WorkspaceSelectionState = {
active: false,
selectedKeys: EMPTY_KEYS,
anchorKey: null,
rangeBaseKeys: null,
};
export function enterWorkspaceSelection(workspaceKey: string): WorkspaceSelectionState {
@@ -24,7 +19,6 @@ export function enterWorkspaceSelection(workspaceKey: string): WorkspaceSelectio
active: true,
selectedKeys: new Set([workspaceKey]),
anchorKey: workspaceKey,
rangeBaseKeys: null,
};
}
@@ -43,7 +37,6 @@ export function toggleWorkspaceSelection(
active: true,
selectedKeys: next,
anchorKey: workspaceKey,
rangeBaseKeys: null,
};
}
@@ -55,18 +48,23 @@ export function selectWorkspaceRange(
if (!state.active) {
return enterWorkspaceSelection(targetKey);
}
const anchorIndex = state.anchorKey ? orderedVisibleKeys.indexOf(state.anchorKey) : -1;
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, rangeBaseKeys: null };
return { active: true, selectedKeys: next, anchorKey: targetKey };
}
const rangeBaseKeys = state.rangeBaseKeys ?? state.selectedKeys;
const start = Math.min(anchorIndex, targetIndex);
const end = Math.max(anchorIndex, targetIndex);
const next = new Set(rangeBaseKeys);
const next = new Set(state.selectedKeys);
for (let index = start; index <= end; index += 1) {
const key = orderedVisibleKeys[index];
if (key !== undefined) {
@@ -77,7 +75,6 @@ export function selectWorkspaceRange(
active: true,
selectedKeys: next,
anchorKey: state.anchorKey,
rangeBaseKeys,
};
}
@@ -87,34 +84,46 @@ export function reconcileWorkspaceSelection(
): WorkspaceSelectionState {
if (!state.active) return state;
const selectedKeys = keepAvailableKeys(state.selectedKeys, availableKeys);
const rangeBaseKeys = state.rangeBaseKeys
? keepAvailableKeys(state.rangeBaseKeys, availableKeys)
: null;
const anchorKey = state.anchorKey && availableKeys.has(state.anchorKey) ? state.anchorKey : null;
if (
selectedKeys === state.selectedKeys &&
rangeBaseKeys === state.rangeBaseKeys &&
anchorKey === state.anchorKey
) {
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, anchorKey, rangeBaseKeys };
}
function keepAvailableKeys(
keys: ReadonlySet<string>,
availableKeys: ReadonlySet<string>,
): ReadonlySet<string> {
for (const key of keys) {
if (!availableKeys.has(key)) {
return new Set([...keys].filter((candidate) => availableKeys.has(candidate)));
}
}
return keys;
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();
}
@@ -29,8 +29,7 @@ export function registerSidebarVisibleWorkspaceKeysReader(reader: VisibleKeysRea
interface SidebarSelectionStoreState extends WorkspaceSelectionState {
isArchiving: boolean;
enter: (workspaceKey: string) => void;
/** Shift+click selects a range from the anchor; any other press toggles the workspace. */
pressWorkspace: (workspaceKey: string, options: { range: boolean }) => void;
pressWorkspace: (workspaceKey: string, options: { shiftKey: boolean }) => void;
reconcile: (availableKeys: ReadonlySet<string>) => void;
setArchiving: (archiving: boolean) => void;
exit: () => void;
@@ -44,10 +43,10 @@ export const useSidebarSelectionStore = create<SidebarSelectionStoreState>((set)
...enterWorkspaceSelection(workspaceKey),
isArchiving: false,
})),
pressWorkspace: (workspaceKey, { range }) =>
pressWorkspace: (workspaceKey, { shiftKey }) =>
set((state) => {
if (state.isArchiving) return state;
const next = range
const next = shiftKey
? selectWorkspaceRange(state, workspaceKey, visibleKeysReader())
: toggleWorkspaceSelection(state, workspaceKey);
return next === state ? state : { ...next };
@@ -5,7 +5,6 @@ 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 { userEvent } from "vitest/browser";
import { SidebarToastRegion } from "@/components/sidebar/sidebar-toast-region";
import { SidebarWorkspaceContextMenu } from "@/components/sidebar/sidebar-workspace-menu";
import { ToastProvider, useToast } from "@/contexts/toast-context";
@@ -18,16 +17,14 @@ import {
useKeyboardActionDispatcher,
} from "@/keyboard/keyboard-action-dispatcher-context";
import { useKeyboardActionHandler } from "@/hooks/use-keyboard-action-handler";
import { useLongPressDragInteraction } from "@/components/sidebar/use-long-press-drag-interaction";
import {
isShiftPressEvent,
registerSidebarVisibleWorkspaceKeysReader,
SidebarSelectionHost,
useIsSidebarSelectionMode,
useIsWorkspaceBulkSelected,
useSidebarSelectionStore,
useWorkspaceSelectionPress,
} from "@/sidebar-selection";
import { getShortcutOs } from "@/utils/shortcut-platform";
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
@@ -90,23 +87,19 @@ function SidebarToastProbe() {
}
const noop = () => {};
let navigatedKeys: string[] = [];
const rowLongPressRefs = new Map<string, { current: boolean }>();
function SelectableRowProbe({ entry }: { entry: SidebarWorkspaceEntry }) {
const isSelectionMode = useIsSidebarSelectionMode();
const isBulkSelected = useIsWorkspaceBulkSelected(entry.workspaceKey);
const handleNavigate = useCallback(() => {
navigatedKeys.push(entry.workspaceKey);
}, [entry.workspaceKey]);
// The row's gesture state, wired the way sidebar rows wire it.
const interaction = useLongPressDragInteraction({ drag: noop, menuController: null });
rowLongPressRefs.set(entry.workspaceKey, interaction.didLongPressRef);
const { onPress, onPressIn } = useWorkspaceSelectionPress({
workspaceKey: entry.workspaceKey,
onNavigate: handleNavigate,
onPressIn: interaction.handlePressIn,
});
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}
@@ -117,8 +110,7 @@ function SelectableRowProbe({ entry }: { entry: SidebarWorkspaceEntry }) {
accessibilityRole={isSelectionMode ? "checkbox" : "button"}
aria-checked={isSelectionMode ? isBulkSelected : undefined}
highlightStyle={undefined}
onPress={onPress}
onPressIn={onPressIn}
onPress={handlePress}
testID={`sidebar-workspace-row-${entry.workspaceKey}`}
>
<Text>{entry.name}</Text>
@@ -133,8 +125,6 @@ function mountHost(entries: readonly SidebarWorkspaceEntry[]) {
);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
container = document.createElement("div");
// Give the sidebar room so the floating selection bar sits below the rows instead of on them.
container.style.cssText = "display:flex;flex-direction:column;width:320px;height:640px;";
document.body.appendChild(container);
root = createRoot(container);
act(() => {
@@ -165,8 +155,6 @@ afterEach(() => {
capturedDispatcher = null;
capturedSidebarToast = null;
fallbackArchiveCount = 0;
navigatedKeys = [];
rowLongPressRefs.clear();
act(() => {
useSidebarSelectionStore.getState().exit();
});
@@ -178,113 +166,6 @@ afterEach(() => {
container = null;
});
function row(id: string): HTMLElement {
const element = document.querySelector<HTMLElement>(
`[data-testid="sidebar-workspace-row-srv:${id}"]`,
);
if (!element) throw new Error(`Row ${id} is not mounted`);
return element;
}
function selectedIds(): string[] {
const state = useSidebarSelectionStore.getState();
if (!state.active) return [];
return [...state.selectedKeys].map((key) => key.replace("srv:", "")).sort();
}
function markGestureCanceled(id: string) {
const ref = rowLongPressRefs.get(`srv:${id}`);
if (!ref) throw new Error(`Row ${id} is not mounted`);
ref.current = true;
}
/** Holds the primary mouse button on a row past the long-press delay, then releases it. */
async function slowClick(element: HTMLElement) {
const box = element.getBoundingClientRect();
const init = {
bubbles: true,
cancelable: true,
button: 0,
clientX: box.left + box.width / 2,
clientY: box.top + box.height / 2,
};
element.dispatchEvent(new MouseEvent("mousedown", { ...init, buttons: 1 }));
await new Promise((resolve) => setTimeout(resolve, 700));
element.dispatchEvent(new MouseEvent("mouseup", init));
element.dispatchEvent(new MouseEvent("click", init));
}
// Cmd on macOS, Ctrl on Windows and Linux, matching the shortcut layer's `mod`.
const MOD_KEY = getShortcutOs() === "mac" ? "Meta" : "Control";
describe("sidebar workspace row presses", () => {
it("enters select mode on the Cmd/Ctrl+clicked row alone and toggles rows without navigating", async () => {
mountHost(["a", "b", "c", "d"].map(makeEntry));
await userEvent.click(row("a"));
expect(navigatedKeys).toEqual(["srv:a"]);
expect(useSidebarSelectionStore.getState().active).toBe(false);
await userEvent.click(row("c"), { modifiers: [MOD_KEY] });
expect(selectedIds()).toEqual(["c"]);
await userEvent.click(row("b"), { modifiers: [MOD_KEY] });
await userEvent.click(row("d"), { modifiers: [MOD_KEY] });
expect(selectedIds()).toEqual(["b", "c", "d"]);
await userEvent.click(row("c"), { modifiers: [MOD_KEY] });
expect(selectedIds()).toEqual(["b", "d"]);
// Plain clicks keep toggling while select mode is on.
await userEvent.click(row("a"));
expect(selectedIds()).toEqual(["a", "b", "d"]);
expect(navigatedKeys).toEqual(["srv:a"]);
});
it("selects on the first modifier or select-mode click after an earlier gesture ended as a long press", async () => {
mountHost(["a", "b"].map(makeEntry));
// A scroll, swipe, drag, or long-press menu leaves the flag set without firing onPress.
// Ctrl+click on Windows/Linux gets no press-in on web, so nothing clears it first.
markGestureCanceled("a");
await userEvent.click(row("a"), { modifiers: [MOD_KEY] });
expect(selectedIds()).toEqual(["a"]);
markGestureCanceled("b");
await userEvent.click(row("b"));
expect(selectedIds()).toEqual(["a", "b"]);
});
it("opens a row on a slow click and still selects it on the next Cmd/Ctrl+click", async () => {
mountHost(["a", "b"].map(makeEntry));
await act(() => slowClick(row("a")));
expect(navigatedKeys).toEqual(["srv:a"]);
await userEvent.click(row("a"), { modifiers: [MOD_KEY] });
expect(selectedIds()).toEqual(["a"]);
});
it("enters select mode on the Shift+clicked row alone, then extends and shrinks the range", async () => {
mountHost(["a", "b", "c", "d", "e", "f"].map(makeEntry));
await userEvent.click(row("b"), { modifiers: ["Shift"] });
expect(selectedIds()).toEqual(["b"]);
await userEvent.click(row("e"), { modifiers: ["Shift"] });
expect(selectedIds()).toEqual(["b", "c", "d", "e"]);
await userEvent.click(row("c"), { modifiers: ["Shift"] });
expect(selectedIds()).toEqual(["b", "c"]);
// Cmd/Ctrl+click moves the anchor; the next Shift range grows from there and keeps b..c.
await userEvent.click(row("f"), { modifiers: [MOD_KEY] });
await userEvent.click(row("e"), { modifiers: ["Shift"] });
expect(selectedIds()).toEqual(["b", "c", "e", "f"]);
expect(navigatedKeys).toEqual([]);
});
});
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")]);
@@ -292,14 +173,14 @@ describe("SidebarSelectionHost", () => {
// Enter select mode via Shift+click on "a", then plain-click "c" without Shift.
act(() => {
useSidebarSelectionStore.getState().pressWorkspace("srv:a", { range: true });
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", { range: false });
useSidebarSelectionStore.getState().pressWorkspace("srv:c", { shiftKey: false });
});
expect(document.querySelector('[data-testid="workspace-selection-count"]')?.textContent).toBe(
"2 selected",
@@ -320,8 +201,8 @@ describe("SidebarSelectionHost", () => {
// Re-enter with Shift+click, then Shift+click "c" for a range of 3, and exit with Escape.
act(() => {
useSidebarSelectionStore.getState().pressWorkspace("srv:a", { range: true });
useSidebarSelectionStore.getState().pressWorkspace("srv:c", { range: true });
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",
@@ -365,7 +246,7 @@ describe("SidebarSelectionHost", () => {
// Enter select mode then deselect the only row -> 0 selected.
act(() => {
useSidebarSelectionStore.getState().enter("srv:a");
useSidebarSelectionStore.getState().pressWorkspace("srv:a", { range: false });
useSidebarSelectionStore.getState().pressWorkspace("srv:a", { shiftKey: false });
});
expect(document.querySelector('[data-testid="workspace-selection-count"]')?.textContent).toBe(
"0 selected",
@@ -1,59 +0,0 @@
import { useCallback } from "react";
import type { GestureResponderEvent } from "react-native";
import { readPressModifiers } from "@/keyboard";
import { useSidebarSelectionStore } from "./selection-store";
interface WorkspaceSelectionPressInput {
workspaceKey: string;
/** The row's normal press: open the workspace. */
onNavigate: () => void;
/** The row's normal press-in: start the long-press drag gesture. */
onPressIn?: (event: GestureResponderEvent) => void;
}
/**
* Routes a sidebar workspace row press between navigation and select mode, Finder-style:
* Shift+click selects a range, Cmd+click (Ctrl+click off macOS) toggles one row, and either one
* enters select mode on the clicked row alone. In select mode every press selects, so touch and
* mouse users can keep tapping without a modifier.
*
* Selecting presses never consult the row's long-press flag. They never arm the long-press
* gesture, a native long press already cancels the press, and react-native-web gives Ctrl+click
* no press-in, so a flag left by an earlier scroll or swipe would swallow the click.
*/
export function useWorkspaceSelectionPress({
workspaceKey,
onNavigate,
onPressIn,
}: WorkspaceSelectionPressInput) {
const handlePress = useCallback(
(event: GestureResponderEvent) => {
const modifiers = readPressModifiers(event);
const store = useSidebarSelectionStore.getState();
if (!store.active && !modifiers.shift && !modifiers.mod) {
onNavigate();
return;
}
event.preventDefault?.();
store.pressWorkspace(workspaceKey, { range: modifiers.shift });
},
[onNavigate, workspaceKey],
);
const handlePressIn = useCallback(
(event: GestureResponderEvent) => {
const modifiers = readPressModifiers(event);
if (modifiers.shift || modifiers.mod) {
// Keep the browser from extending a text selection or starting a drag on modifier clicks.
event.preventDefault?.();
return;
}
if (!useSidebarSelectionStore.getState().active) {
onPressIn?.(event);
}
},
[onPressIn],
);
return { onPress: handlePress, onPressIn: handlePressIn };
}
+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,4 +1,4 @@
import type { PluginSessionsRuntime } from "../plugins/agent-tools.js";
import type { AttachedAgentTool, PluginSessionsRuntime } from "../plugins/agent-tools.js";
import { createIdleRuntimeCleanup } from "./idle-runtime-cleanup/index.js";
import {
prepareAgentMessage,
@@ -7,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";
@@ -23,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";
@@ -16268,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);
});
@@ -3,7 +3,7 @@ import type {
PluginSessionsRuntime,
SessionOpenAgentFacts,
} from "../plugins/agent-tools.js";
import { ProviderOptionsValidationError } from "./provider-options.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";
@@ -1721,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`.
@@ -6644,6 +6645,7 @@ export class AgentManager {
let appendSystemPrompt: string[] | undefined;
let mcpServers: AgentSessionConfig["mcpServers"];
let mcpServerOwners: Record<string, string> | undefined;
let wrap: AgentLaunchContext["wrap"];
if (this.pluginSessions) {
const request = {
agentId,
@@ -6661,14 +6663,18 @@ export class AgentManager {
};
const transformed = await this.pluginSessions.openSession(request);
env = transformed.env;
wrap = transformed.wrap;
if (request.purpose === "interactive") {
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,
@@ -6855,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({
@@ -36,10 +36,23 @@ import { importSessionFromPersistence } from "../../../provider-session-import.j
import type { OpenCodeBridge } from "../bridge.js";
import { resolveOpenCodeHomeDir } from "../paths.js";
import { V2Runtime, type V2Connection } from "./runtime.js";
import { V2Runtime, type V2Connection, type V2DedicatedLaunch } from "./runtime.js";
import type { OpenCodeServiceSelection } from "./service-selection.js";
import { modelRef, modesFromV2, modelsFromV2 } from "./mapping.js";
/**
* A wrapped launch gets a server of its own, started behind the wrap with the launch's environment,
* so it never shares a server that runs outside its wrap.
*/
function dedicatedLaunch(launch: AgentLaunchContext | undefined): V2DedicatedLaunch | undefined {
return launch?.wrap ? { wrap: launch.wrap, env: launch.env } : undefined;
}
interface ResumeTarget {
handle: AgentPersistenceHandle;
overrides: Partial<AgentSessionConfig> | undefined;
launch: AgentLaunchContext | undefined;
historyOnly: boolean;
}
interface PreparedLaunch {
launch: AgentLaunchContext | undefined;
/** The complete shell environment, when the launch sets one. */
@@ -116,7 +129,7 @@ export class OpenCodeV2AgentClient implements AgentClient {
): Promise<AgentSession> {
const prepared = await this.prepareLaunch(config, launch, false);
try {
const connection = await this.runtime.acquire();
const connection = await this.runtime.acquire({ dedicated: dedicatedLaunch(launch) });
try {
const info = await connection.client.session.create({
location: { directory: config.cwd },
@@ -146,6 +159,21 @@ export class OpenCodeV2AgentClient implements AgentClient {
overrides?: Partial<AgentSessionConfig>,
launch?: AgentLaunchContext,
options?: AgentResumeSessionOptions,
): Promise<AgentSession> {
return this.resumeOn(
async () => {
// A live connection may run outside this launch's wrap, so a wrapped resume starts its own.
const live = launch?.wrap
? undefined
: this.connections.get(handle.nativeHandle ?? handle.sessionId)?.retain();
return live ?? (await this.runtime.acquire({ dedicated: dedicatedLaunch(launch) }));
},
{ handle, overrides, launch, historyOnly: options?.purpose === "history" },
);
}
private async resumeOn(
connect: () => Promise<V2Connection>,
{ handle, overrides, launch, historyOnly }: ResumeTarget,
): Promise<AgentSession> {
const cwd = overrides?.cwd ?? handle.metadata?.cwd;
if (typeof cwd !== "string")
@@ -156,12 +184,9 @@ export class OpenCodeV2AgentClient implements AgentClient {
provider: "opencode",
cwd,
};
const historyOnly = options?.purpose === "history";
const prepared = await this.prepareLaunch(config, launch, historyOnly);
try {
const connection =
this.connections.get(handle.nativeHandle ?? handle.sessionId)?.retain() ??
(await this.runtime.acquire());
const connection = await connect();
try {
const info = await connection.client.session.get({
sessionID: handle.nativeHandle ?? handle.sessionId,
@@ -197,6 +222,7 @@ export class OpenCodeV2AgentClient implements AgentClient {
servers,
cwd: config.cwd,
env: environment ?? createProviderEnv({ runtimeSettings: this.options.settings }),
wrap: launch?.wrap,
});
return { launch, environment, mcp };
}
@@ -257,7 +283,7 @@ export class OpenCodeV2AgentClient implements AgentClient {
mcp,
unbind: releaseBindings,
bindChild,
acquire: () => this.runtime.acquire(),
acquire: () => this.runtime.acquire({ dedicated: dedicatedLaunch(launch) }),
moved,
historyOnly,
});
@@ -312,14 +338,24 @@ export class OpenCodeV2AgentClient implements AgentClient {
}
}
async importSession(input: ImportProviderSessionInput, context: ImportProviderSessionContext) {
const connection = await this.runtime.acquire();
// The lookup and the resume share one connection, so a wrapped import never starts a server
// outside its wrap.
const connection = await this.runtime.acquire({
dedicated: dedicatedLaunch(context.launchContext),
});
try {
const info = await connection.client.session.get({ sessionID: input.providerHandleId });
return await importSessionFromPersistence({
provider: "opencode",
request: input,
context,
resumeSession: this.resumeSession.bind(this),
resumeSession: (handle, overrides, launch) =>
this.resumeOn(async () => connection.retain(), {
handle,
overrides,
launch,
historyOnly: false,
}),
config: {
title: info.title,
modeId: info.agent,
@@ -75,3 +75,76 @@ test("reports a bridge port change that has not been applied", async () => {
await rm(root, { recursive: true, force: true });
}
});
test("a wrapped caller gets its own helper behind the wrap, and other callers keep the shared one", async () => {
const root = await mkdtemp(path.join(tmpdir(), "paseo-opencode-wrap-"));
const script = path.join(root, "server.cjs");
const launcher = path.join(root, "launcher.cjs");
const record = path.join(root, "argv.json");
await writeFile(
script,
`
const http = require('node:http');
const server = http.createServer((_request, response) => {
response.writeHead(200, { 'content-type': 'application/json' });
response.end(JSON.stringify({ version: '2.0.10', pid: process.pid, urls: [], paths: { tmp: '/tmp' } }));
});
server.listen(0, '127.0.0.1', () => console.log('server listening on http://127.0.0.1:' + server.address().port));
`,
);
await writeFile(
launcher,
`
const [, , ...argv] = process.argv;
// A launcher that needs its profile from the open hook's environment.
if (!process.env.SANDBOX_PROFILE) process.exit(17);
require('node:fs').writeFileSync(${JSON.stringify(record)}, JSON.stringify({ argv, profile: process.env.SANDBOX_PROFILE }));
const child = require('node:child_process').spawn(argv[1], argv.slice(2), { stdio: 'inherit' });
child.on('exit', (code) => process.exit(code ?? 1));
`,
);
const runtime = new V2Runtime({
logger: createTestLogger(),
selection: { kind: "owned" },
settings: { command: { mode: "replace", argv: [process.execPath, script] } },
});
try {
const shared = await runtime.acquire();
const wrapped = await runtime.acquire({
dedicated: {
wrap: [process.execPath, launcher, "--profile"],
env: { SANDBOX_PROFILE: "agent" },
},
});
const sharedAgain = await runtime.acquire();
const sharedPid = (await shared.client.server.info()).pid;
expect((await wrapped.client.server.info()).pid).not.toBe(sharedPid);
expect((await sharedAgain.client.server.info()).pid).toBe(sharedPid);
const launched = JSON.parse(await readFile(record, "utf8"));
expect(launched.profile).toBe("agent");
expect(launched.argv.slice(0, 4)).toEqual(["--profile", process.execPath, script, "serve"]);
await wrapped.release();
await expect(wrapped.exited).resolves.toBeInstanceOf(Error);
await shared.release();
await sharedAgain.release();
} finally {
await runtime.shutdown();
await rm(root, { recursive: true, force: true });
}
}, 15_000);
test("refuses to wrap a configured existing server", async () => {
const runtime = new V2Runtime({
logger: createTestLogger(),
selection: { kind: "explicit", server: { url: "http://127.0.0.1:1" } },
});
try {
await expect(
runtime.acquire({ dedicated: { wrap: ["/opt/sandbox/bin/run"], env: {} } }),
).rejects.toThrow("cannot start it behind a launch wrap");
} finally {
await runtime.shutdown();
}
});
@@ -5,6 +5,7 @@ import type { V2Api } from "./api.js";
import { randomBytes } from "node:crypto";
import { mkdir } from "node:fs/promises";
import type { Logger } from "pino";
import type { LaunchWrap } from "../../../../../utils/launch-wrap.js";
import { spawnProcess } from "../../../../../utils/spawn.js";
import { terminateWithTreeKill } from "../../../../../utils/tree-kill.js";
import {
@@ -59,9 +60,17 @@ export interface V2RuntimeOptions {
bridge?: OpenCodeBridge;
}
/** A server started for one caller alone, behind its wrap and with its launch environment. */
export interface V2DedicatedLaunch {
wrap: LaunchWrap;
env: Record<string, string> | undefined;
}
export interface V2RuntimeAcquireOptions {
fresh?: boolean;
signal?: AbortSignal;
/** Start a server for this caller alone. Other callers never share it. */
dedicated?: V2DedicatedLaunch;
}
// The runtime owns a credential for each subprocess; sessions only receive its authenticated client.
@@ -92,8 +101,9 @@ export class V2Runtime {
this.assertBridgePort();
const selection = await raceProviderRefreshAbort(input.signal, this.selection);
if (selection.kind === "explicit") this.assertExplicitConfiguration();
this.current ??= this.startTracked();
const pending = this.current;
const pending = input.dedicated
? this.startTracked(input.dedicated)
: (this.current ??= this.startTracked());
let generation: Generation;
try {
generation = await raceProviderRefreshAbort(input.signal, pending);
@@ -179,8 +189,8 @@ export class V2Runtime {
this.current = null;
}
private startTracked(): Promise<Generation> {
const pending = this.start();
private startTracked(dedicated?: V2DedicatedLaunch): Promise<Generation> {
const pending = this.start(dedicated);
this.starts.add(pending);
void pending.then(
(generation) =>
@@ -197,9 +207,14 @@ export class V2Runtime {
return pending;
}
private async start(): Promise<Generation> {
private async start(dedicated: V2DedicatedLaunch | undefined): Promise<Generation> {
const selection = await this.selection;
if (selection.kind !== "owned") {
if (dedicated && selection.kind === "explicit")
throw new Error(
"OpenCode is configured to use an existing server, so Paseo cannot start it behind a launch wrap",
);
// A discovered server is only a preference; a wrapped caller gets a server Paseo starts.
if (selection.kind !== "owned" && !dedicated) {
const generation: Generation = {
...(await connectSharedService(selection, this.options)),
users: 0,
@@ -220,6 +235,7 @@ export class V2Runtime {
const configured = {
...(inheritedConfig ? { OPENCODE_CONFIG_CONTENT: inheritedConfig } : {}),
...settings?.env,
...dedicated?.env,
};
const bridge = this.options.bridge;
const plugin = bridge
@@ -240,6 +256,7 @@ export class V2Runtime {
cwd,
detached: globalThis.process.platform !== "win32",
stdio: ["ignore", "pipe", "pipe"],
wrap: dedicated?.wrap,
...createProviderEnvSpec({
runtimeSettings: settings,
overlays: [{ ...decorated, OPENCODE_PASSWORD: password }],
@@ -1,5 +1,6 @@
import type { McpServerConfig } from "../../../agent-sdk-types.js";
import { connectMcpServer, type McpClientConnection } from "../../../mcp-client-connection.js";
import type { LaunchWrap } from "../../../../../utils/launch-wrap.js";
import type { PaseoToolResult } from "../../../tools/types.js";
import type { OpenCodeBridgeMcpTool } from "../bridge.js";
@@ -22,6 +23,8 @@ interface ConnectSessionMcpInput {
cwd: string;
/** The agent's complete launch environment, which stdio servers inherit. */
env: NodeJS.ProcessEnv;
/** The agent's wrap, which stdio servers run behind. */
wrap?: LaunchWrap;
}
/**
@@ -44,6 +47,7 @@ export class SessionMcp {
config,
cwd: input.cwd,
env: input.env,
wrap: input.wrap,
clientName: "paseo-opencode",
});
return { name, connection };
@@ -498,6 +498,7 @@ function buildResumeStartInput(input: {
return {
cwd: input.processCwd,
env: input.launchContext?.env,
wrap: input.launchContext?.wrap,
session: input.sessionFile,
thinkingOptionId: normalizePiThinkingOption(input.resumeConfig.thinkingOptionId) ?? undefined,
mcpConfigPath: input.mcpConfigFile?.path,
@@ -2660,11 +2661,13 @@ export class PiRpcAgentClient implements AgentClient {
): Promise<AgentSession> {
const providerOptions = PiProviderOptionsSchema.parse(config.providerOptions ?? {});
const runtime = this.resolveRuntime(providerOptions.rpcTimeoutMs);
const mcpEnv = {
...this.runtimeSettings?.env,
...launchContext?.env,
};
const mcp = await this.prepareMcpInjection(config.cwd, config.mcpServers, mcpEnv, runtime);
const { env, wrap } = launchContext ?? {};
const mcpEnv = { ...this.runtimeSettings?.env, ...env };
const mcp = await this.prepareMcpInjection(
{ cwd: config.cwd, env: mcpEnv, wrap },
config.mcpServers,
runtime,
);
const mcpConfigFile = mcp?.kind === "adapter" ? mcp.configFile : null;
const paseoExtension = createPiPaseoExtensionFile({
systemPrompt: composeAgentSystemPrompt(config),
@@ -2677,7 +2680,8 @@ export class PiRpcAgentClient implements AgentClient {
model: config.model,
thinkingOptionId: normalizePiThinkingOption(config.thinkingOptionId) ?? undefined,
noSession: config.internal === true,
env: launchContext?.env,
env,
wrap,
mcpConfigPath: mcpConfigFile?.path,
extensionPaths: paseoExtension ? [paseoExtension.path] : undefined,
});
@@ -2729,9 +2733,8 @@ export class PiRpcAgentClient implements AgentClient {
...launchContext?.env,
};
const mcp = await this.prepareMcpInjection(
processCwd,
{ cwd: processCwd, env: mcpEnv, wrap: launchContext?.wrap },
resumeConfig.config.mcpServers,
mcpEnv,
runtime,
);
const mcpConfigFile = mcp?.kind === "adapter" ? mcp.configFile : null;
@@ -2930,16 +2933,17 @@ export class PiRpcAgentClient implements AgentClient {
return this.runtime ?? createRuntime(this.logger, this.runtimeSettings, rpcTimeoutMs);
}
/** `probe` starts the Pi process that detects MCP support, as the agent's own process starts. */
private async prepareMcpInjection(
cwd: string,
probe: Pick<PiStartSessionInput, "cwd" | "env" | "wrap">,
servers: Record<string, McpServerConfig> | undefined,
env: Record<string, string> | undefined,
runtime: PiRuntime,
): Promise<PiMcpInjection | null> {
if (!servers || Object.keys(servers).length === 0) {
return null;
}
const mcpSupport = await this.detectMcpSupport(cwd, env, runtime);
const { env } = probe;
const mcpSupport = await this.detectMcpSupport(probe, runtime);
if (mcpSupport === "builtin") {
return { kind: "builtin", servers: toPiBuiltinMcpServers(servers) };
}
@@ -2953,12 +2957,11 @@ export class PiRpcAgentClient implements AgentClient {
}
private async detectMcpSupport(
cwd: string,
env: Record<string, string> | undefined,
probe: Pick<PiStartSessionInput, "cwd" | "env" | "wrap">,
runtime: PiRuntime,
): Promise<PiMcpInjection["kind"] | null> {
const runtimeSession = await runtime.startSession({ cwd, env }).catch((error) => {
this.logger.debug({ err: error, cwd }, "Pi MCP probe failed to start");
const runtimeSession = await runtime.startSession(probe).catch((error) => {
this.logger.debug({ err: error, cwd: probe.cwd }, "Pi MCP probe failed to start");
return null;
});
if (!runtimeSession) {
@@ -2971,7 +2974,7 @@ export class PiRpcAgentClient implements AgentClient {
}
return commands.some(isPiBuiltinMcpCommand) ? "builtin" : null;
} catch (error) {
this.logger.debug({ err: error, cwd }, "Pi MCP probe failed");
this.logger.debug({ err: error, cwd: probe.cwd }, "Pi MCP probe failed");
return null;
} finally {
await runtimeSession.close().catch(() => undefined);
@@ -1,4 +1,5 @@
import { mkdir, mkdtemp, writeFile, readFile, rm } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import type { ChildProcessWithoutNullStreams } from "node:child_process";
import { EventEmitter } from "node:events";
@@ -167,6 +168,63 @@ describe("PiCliRuntime", () => {
]);
});
test("starts Pi behind the session's launch wrap and talks to it through the wrap", async () => {
const root = await mkdtemp(path.join(os.tmpdir(), "pi-launch-wrap-"));
try {
const fakePi = path.join(root, "fake-pi.mjs");
await writeFile(
fakePi,
[
'import { createInterface } from "node:readline";',
'createInterface({ input: process.stdin }).on("line", (line) => {',
" const command = JSON.parse(line);",
' const data = { sessionId: "wrapped", argv: process.argv.slice(2) };',
' process.stdout.write(JSON.stringify({ type: "response", id: command.id, command: command.type, success: true, data }) + "\\n");',
"});",
"",
].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 PiCliRuntime({
logger: pino({ level: "silent" }),
command: [process.execPath, fakePi],
});
const session = await runtime.startSession({
cwd: root,
wrap: [process.execPath, launcher],
});
try {
await expect(session.getState()).resolves.toMatchObject({
sessionId: "wrapped",
argv: ["--mode", "rpc"],
});
expect(JSON.parse(await readFile(path.join(root, "wrapped.json"), "utf8"))).toEqual([
process.execPath,
fakePi,
"--mode",
"rpc",
]);
} finally {
await session.close();
}
} finally {
await rm(root, { recursive: true, force: true });
}
});
test("passes an MCP config path to Pi", async () => {
const child = createPiChild();
replyToCommands(child, () => ({}));

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