diff --git a/.claude/skills/store-screenshots/SKILL.md b/.claude/skills/store-screenshots/SKILL.md new file mode 100644 index 0000000000..f0c319dd05 --- /dev/null +++ b/.claude/skills/store-screenshots/SKILL.md @@ -0,0 +1,19 @@ +--- +name: store-screenshots +description: Refresh the App Store and Google Play screenshots for phones and tablets. Use when the user says "store screenshots", "app store screenshots", "play store screenshots", "iPad screenshots", "recapture the screenshots", or wants the store panels changed. +user-invocable: true +--- + +# Store screenshots + +Follow `assets/store-screenshots/README.md`. It owns the panels, the creative direction, the render command and the recapture steps. Change copy, crops and layout in `assets/store-screenshots/render.mjs`, not in the exports. + +Working rules: + +- Capture at native density: `--pixel-density 3` on the iPhone 16 Pro Max, `--pixel-density 2` on the iPad Pro 13-inch. The default is 1x, which is too soft for the store. +- Every headline wraps to two lines and every subline fits on one. The renderer enforces this; rewrite the copy rather than shrink the type. +- Use SF Pro. Never substitute another font. +- Open `output/preview.png` and a full-size panel from each store before you report a render. Show the user the preview. +- Do not upload screenshots to a store, a PR, or anywhere public, and do not commit, unless the user asks. +- Stage the demo host on its own port and pick a free Metro port. Do not restart the main daemons. +- When you learn something the next capture needs, fix the README rather than this skill. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e632cb4b96..285ff8e072 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -3,7 +3,7 @@ name: CI on: push: branches: [main] - # Every base branch, so stacked PRs and PRs into `next` get the same checks. + # Every base branch, so stacked PRs and PRs into any base get the same checks. pull_request: merge_group: workflow_dispatch: @@ -133,11 +133,12 @@ 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 + # The locked Playwright installers do not support ubuntu-latest's Ubuntu 26.04. typecheck: name: typecheck needs: changes if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.quality != 'false') }} - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 steps: - uses: actions/checkout@v4 @@ -280,10 +281,10 @@ jobs: # otherwise has no server-test coverage. Scoped to the observer/watcher suites to # bound runtime. server-tests-macos: - name: server-tests (macos-14, file observation) + name: server-tests (macos-latest, file observation) needs: changes if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.server != 'false') }} - runs-on: macos-14 + runs-on: macos-latest steps: - uses: actions/checkout@v4 @@ -395,7 +396,7 @@ jobs: name: app-tests needs: changes if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.app != 'false') }} - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 steps: - uses: actions/checkout@v4 @@ -417,19 +418,11 @@ jobs: - name: Run app unit tests run: npm run test --workspace=@getpaseo/app - - uses: actions/setup-java@v4 - with: - distribution: temurin - java-version: "21" - - - name: Run Android module tests - run: npm run test:android --workspace=@getpaseo/app - playwright-1: name: playwright (shard 1/8) needs: changes if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.browser != 'false') }} - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 env: PLAYWRIGHT_SHARD: "1/8" PLAYWRIGHT_ARTIFACT: "1" @@ -485,7 +478,7 @@ jobs: name: playwright (shard 2/8) needs: changes if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.browser != 'false') }} - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 env: PLAYWRIGHT_SHARD: "2/8" PLAYWRIGHT_ARTIFACT: "2" @@ -495,7 +488,7 @@ jobs: name: playwright (shard 3/8) needs: changes if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.browser != 'false') }} - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 env: PLAYWRIGHT_SHARD: "3/8" PLAYWRIGHT_ARTIFACT: "3" @@ -505,7 +498,7 @@ jobs: name: playwright (shard 4/8) needs: changes if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.browser != 'false') }} - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 env: PLAYWRIGHT_SHARD: "4/8" PLAYWRIGHT_ARTIFACT: "4" @@ -515,7 +508,7 @@ jobs: name: playwright (shard 5/8) needs: changes if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.browser != 'false') }} - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 env: PLAYWRIGHT_SHARD: "5/8" PLAYWRIGHT_ARTIFACT: "5" @@ -525,7 +518,7 @@ jobs: name: playwright (shard 6/8) needs: changes if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.browser != 'false') }} - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 env: PLAYWRIGHT_SHARD: "6/8" PLAYWRIGHT_ARTIFACT: "6" @@ -535,7 +528,7 @@ jobs: name: playwright (shard 7/8) needs: changes if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.browser != 'false') }} - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 env: PLAYWRIGHT_SHARD: "7/8" PLAYWRIGHT_ARTIFACT: "7" @@ -545,7 +538,7 @@ jobs: name: playwright (shard 8/8) needs: changes if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.browser != 'false') }} - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 env: PLAYWRIGHT_SHARD: "8/8" PLAYWRIGHT_ARTIFACT: "8" diff --git a/.github/workflows/desktop-release.yml b/.github/workflows/desktop-release.yml index d81c036e62..26be12291b 100644 --- a/.github/workflows/desktop-release.yml +++ b/.github/workflows/desktop-release.yml @@ -100,10 +100,10 @@ jobs: fail-fast: false matrix: include: - - runner: macos-14 + - runner: macos-latest electron_arch: arm64 node_heap_mb: 4096 - - runner: macos-15-intel + - runner: macos-26-intel electron_arch: x64 node_heap_mb: 8192 permissions: diff --git a/.github/workflows/nix.yml b/.github/workflows/nix.yml index f37a8b0cdf..b653564793 100644 --- a/.github/workflows/nix.yml +++ b/.github/workflows/nix.yml @@ -101,7 +101,7 @@ jobs: run: nix build .#desktop -o result-desktop build-desktop-darwin: - runs-on: macos-14 + runs-on: macos-latest steps: - uses: actions/checkout@v4 diff --git a/.oxlintrc.json b/.oxlintrc.json index f5078649c9..c82b517844 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -85,6 +85,176 @@ "max-nested-callbacks": ["error", { "max": 3 }] }, "overrides": [ + // Exceptions name individual APIs in individual modules; new APIs still fail in these files. + // TODO entries are runtime debt, not startup exemptions. Do not add directory-wide exceptions. + { + "files": ["packages/server/src/**/*.{ts,tsx,mts,cts,js,jsx,mjs,cjs}"], + "rules": { + "paseo/no-sync-io": [ + "error", + { + "allow": { + // TODO: literal executableExists is a synchronous public capability; move its callers and Windows existence predicates to async together. + "executable-resolution/executable-resolution.ts": ["existsSync"], + // TODO: winget enumeration shares synchronous existence predicates with literal lookup; convert the executable-resolution boundary together. + "executable-resolution/windows.ts": ["readdirSync"], + // TODO: live file-change classification is a synchronous event mapper; move the probe to async event ingestion. + "server/agent/providers/claude/agent.ts": ["existsSync"], + // TODO: new-session construction still resolves its project directory synchronously; move preparation before construction. + "server/agent/providers/claude/project-dir.ts": ["realpathSync"], + // TODO: live subagent output is read by a synchronous event mapper; add bounded async loading at ingestion. + "server/agent/providers/claude/subagents/workflow-output.ts": [ + "closeSync", + "openSync", + "readSync" + ], + // TODO: diagnostics probes provider-owned auth/session storage; convert alongside provider discovery and readiness. + "server/agent/providers/omp/agent.ts": ["existsSync"], + // TODO: synchronous provider configuration discovery; move discovery into async launch preparation. + "server/agent/providers/omp/provider-config.ts": ["existsSync"], + // TODO: synchronous session-root selection is shared by descriptor builders; migrate callers with explicit readiness. + "server/agent/providers/omp/session-descriptor.ts": ["existsSync"], + // TODO: launch directory creation shares the server generation/start state machine; audit concurrent rotation before adding an await. + "server/agent/providers/opencode/server-manager.ts": ["mkdirSync"], + // TODO: launch preparation owns MCP config merge, extension generation and synchronous cleanup; migrate lifecycle and diagnostics together. + "server/agent/providers/pi/agent.ts": [ + "existsSync", + "mkdtempSync", + "readFileSync", + "rmSync", + "writeFileSync" + ], + // Provider child process: Pi loads this extension outside the daemon; it reads child-agent status there. + "server/agent/providers/pi/extensions/pi-subagents/index.ts": ["readFileSync"], + // Startup/shutdown only: remove stale Unix listening sockets before bind and during disposal. + "server/bootstrap.ts": ["existsSync", "unlinkSync"], + // Startup configuration resolution: detect the bundled app distribution before the daemon listens. + "server/config.ts": ["existsSync"], + // Startup identity: load or create the daemon keypair before accepting connections. + "server/daemon-keypair.ts": ["existsSync", "readFileSync"], + // Fatal exit diagnostics: synchronously flush the exit reason when the worker is about to terminate. + "server/daemon-worker.ts": ["appendFileSync", "mkdirSync"], + // Startup host identity: memoized scutil lookup is warmed before listening; later callers use the cache. + "server/host-name.ts": ["execFileSync"], + // TODO: relationship persistence is atomic with enrollment/revocation state transitions; serialize those transitions before async writes. + "server/hub/relationship-controller.ts": [ + "existsSync", + "readFileSync", + "renameSync", + "rmSync" + ], + // Local client bootstrap: reads the local credential and pid lock to select/authenticate a daemon connection. + "server/local-credential.ts": ["readFileSync"], + // Startup logger construction: create the log directory before opening the logging destination. + "server/logger.ts": ["mkdirSync"], + // TODO: runtime skill commands resolve their bundled source through a synchronous targets capability; migrate the capability and controller together. + "server/orchestration-skills/internal/paths.ts": ["existsSync"], + // Module initialization: the package version is resolved once and cached at import. + "server/package-version.ts": ["existsSync", "readFileSync"], + // Startup config and exported synchronous configuration API; runtime DaemonConfigStore uses the async load/save capabilities. + "server/persisted-config.ts": ["existsSync", "readFileSync"], + // Startup pid identity: read and memoize the Linux boot id for the daemon lock. + "server/pid-lock.ts": ["readFileSync"], + // Startup builtin loader construction: select the bundled plugin root before loading plugins. + "server/plugins/builtin/index.ts": ["existsSync"], + // Build child process: plugin graph traversal and esbuild preparation run in the isolated compiler process. + "server/plugins/compiler-build.ts": ["existsSync", "readFileSync", "realpathSync"], + // Build child process: select the esbuild binary for the isolated plugin compiler. + "server/plugins/compiler-esbuild.ts": ["existsSync"], + // Build child process: TypeScript resolution and source reads run in the isolated plugin compiler. + "server/plugins/compiler-imports.ts": ["readFileSync", "realpathSync"], + // TODO: plugin install/update/remove commits sources.json synchronously; preserve record/write ordering with an async mutation queue. + "server/plugins/managed-source.ts": ["existsSync", "readFileSync"], + // TODO: shared synchronous persistence supports startup identity plus Hub/plugin/push runtime writers; migrate those owners before removing these exports. + "server/private-files.ts": [ + "chmodSync", + "mkdirSync", + "realpathSync", + "renameSync", + "rmSync", + "writeFileSync" + ], + // TODO: constructor load plus runtime renew/revoke/prune use synchronous persistence; introduce ordered async mutations and readiness. + "server/push/token-store.ts": ["existsSync", "readFileSync"], + // Startup identity: load or create the server id before accepting connections. + "server/server-id.ts": ["existsSync", "readFileSync"], + // Listener lifecycle only: unlink the Unix socket before binding or after stopping the proxy. + "server/service-proxy.ts": ["existsSync", "unlinkSync"], + // TODO: self-update origin validation exposes synchronous package-root and realpath checks; migrate validation and its runtime interface together. + "server/session/daemon/install-origin.ts": ["existsSync", "readFileSync"], + // TODO: npm self-update inspection probes the reported install path; move the probe into bounded async installation inspection. + "server/session/daemon/npm-global-cli.ts": ["lstatSync"], + // Speech child process: model-file validation runs in the worker-backed local speech provider. + "server/speech/providers/local/sherpa/sherpa-offline-recognizer.ts": ["existsSync"], + // Speech child process: native addon discovery and patchelf run outside the daemon. + "server/speech/providers/local/sherpa/sherpa-onnx-node-loader.ts": [ + "existsSync", + "spawnSync" + ], + // Speech child process: model-file validation runs in the worker-backed local speech provider. + "server/speech/providers/local/sherpa/sherpa-tts.ts": ["existsSync"], + // TODO: static request selection and index injection need bounded async serving with response/error ownership; keep this as a separate request-path conversion. + "server/web-ui.ts": ["readFileSync", "statSync"], + // Startup registry hydration: check persisted workspace directories before the runtime reconciliation service starts. + "server/workspace-registry-bootstrap.ts": ["statSync"], + // Terminal child process: hook config installation/removal is owned by terminal creation and teardown in the worker. + "terminal/agent-hooks/agent-hook-installer.ts": [ + "existsSync", + "readFileSync", + "rmSync" + ], + // Terminal child process: launcher readiness and PTY record ownership run outside the daemon. + "terminal/terminal-worker-process.ts": [ + "chmodSync", + "closeSync", + "existsSync", + "openSync", + "rmSync", + "writeSync" + ], + // Worker startup only: choose and secure the local listening socket before accepting a controller. + "terminal/terminal-worker-socket-path.ts": ["lstatSync", "mkdirSync"], + // Startup only: build an independent worker installation before launching; Electron ASAR sources require plain fs reads. + "terminal/terminal-worker-runtime.ts": [ + "chmodSync", + "existsSync", + "mkdirSync", + "readdirSync", + "readFileSync", + "renameSync", + "rmSync", + "statSync", + "writeFileSync" + ], + // TODO: CLI shim lookup moved out of terminal.ts; migrate the executable-resolution boundary together. + "terminal/paseo-cli-path.ts": ["existsSync"], + // Node loader thread: TypeScript terminal-worker resolution runs in the loader, outside the daemon event loop. + "terminal/terminal-ts-loader.mjs": ["existsSync"], + // Terminal child process: executable preparation and shell integration run in the worker-backed terminal manager. + "terminal/terminal.ts": [ + "accessSync", + "chmodSync", + "existsSync", + "mkdirSync", + "readFileSync", + "statSync" + ], + // TODO: legacy realpath helpers still serve install-origin validation and other synchronous consumers; migrate remaining callers before removing them. + "utils/path.ts": ["realpathSync"] + } + } + ] + } + }, + { + "files": [ + "packages/server/src/**/*.{test,spec,fixture}.{ts,tsx,mts,cts,js,jsx,mjs,cjs}", + "packages/server/src/**/test-utils/**", + "packages/server/src/server/daemon-e2e/**", + "packages/server/src/server/agent/providers/pi/extensions/*-test.ts" + ], + "rules": { "paseo/no-sync-io": "off" } + }, { "files": [ "plugins/*-provider/server/**/*.ts", diff --git a/CHANGELOG.md b/CHANGELOG.md index 98d1c76900..6ee9a07b36 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,145 @@ # Changelog +## 0.15.0-beta.1 - 2026-11-01 + +Daemon restarts now keep terminal programs running and automatically resume interrupted agents in their existing conversations. + +Mobile terminals have native rendering and draggable text-selection handles. Reconnecting restores up to 10,000 lines of terminal history. + +Worktree setup can copy ignored files and use plugin-defined locations before agents start. + +### Added + +- Insert known agent commands from replies into the Composer draft ([#8371](https://github.com/getpaseo/paseo/pull/8371)) +- Reuse running OpenCode v2 services ([#7435](https://github.com/getpaseo/paseo/pull/7435) by [@mcowger](https://github.com/mcowger)) +- Kept terminal programs running across daemon restarts, crashes and supported updates ([#7644](https://github.com/getpaseo/paseo/pull/7644), [#8155](https://github.com/getpaseo/paseo/pull/8155) by [@sebastianarena](https://github.com/sebastianarena)) +- Automatically resume interrupted agents in their existing conversations after a host restart ([#8127](https://github.com/getpaseo/paseo/pull/8127) by [@coolwindX](https://github.com/coolwindX), [@suntianc](https://github.com/suntianc)) +- Added draggable terminal text-selection handles on iOS and Android ([#8348](https://github.com/getpaseo/paseo/pull/8348)) +- Let phones and tablets rotate with the system orientation setting ([#8256](https://github.com/getpaseo/paseo/pull/8256) by [@magiclaw](https://github.com/magiclaw), [@yzim](https://github.com/yzim)) +- Copy ignored files selected by `.worktreeinclude` into new worktrees before setup and agents start ([#8100](https://github.com/getpaseo/paseo/pull/8100) by [@cprecioso](https://github.com/cprecioso)) +- Added daemon-wide support for `HTTP_PROXY`, `HTTPS_PROXY` and `NO_PROXY` ([#8177](https://github.com/getpaseo/paseo/pull/8177)) +- Fetch usage only while displayed, with a host setting to disable usage checks entirely ([#8181](https://github.com/getpaseo/paseo/pull/8181)) + +### Improved + +- Replaced mobile terminal text rendering to align CJK characters, emoji, styled text and the cursor with terminal columns ([#8336](https://github.com/getpaseo/paseo/pull/8336), [#8375](https://github.com/getpaseo/paseo/pull/8375)) +- Restore the configured terminal scrollback on reconnect, up to 10,000 retained lines ([#8282](https://github.com/getpaseo/paseo/pull/8282) by [@DrakenKor](https://github.com/DrakenKor), [@lennartschoch](https://github.com/lennartschoch)) +- Load paginated Codex histories when importing or reopening sessions ([#8171](https://github.com/getpaseo/paseo/pull/8171) by [@dundunHa](https://github.com/dundunHa), [@hr95savage](https://github.com/hr95savage)) +- Stopped rereading and retaining an unused copy of Codex history when reopening a cached chat ([#8132](https://github.com/getpaseo/paseo/pull/8132)) +- Split large daemon responses across relay frames instead of disconnecting at the frame limit ([#8302](https://github.com/getpaseo/paseo/pull/8302)) +- Truncate oversized chat entries before sending them to the app, including large tool results and embedded data ([#8274](https://github.com/getpaseo/paseo/pull/8274)) +- Show subagent activity in its own panel instead of duplicating it inside the parent’s tool card ([#8276](https://github.com/getpaseo/paseo/pull/8276)) +- Show exact usage reset times alongside more precise countdowns ([#8162](https://github.com/getpaseo/paseo/pull/8162)) + +### Plugins + +- Fixed discarded messages returning after rewinding plugin conversations ([#8368](https://github.com/getpaseo/paseo/pull/8368) by [@mcowger](https://github.com/mcowger), [@omercnet](https://github.com/omercnet)) +- Reduced plugin downloads with smaller client bundles and a cache reused across reconnects and app launches ([#8040](https://github.com/getpaseo/paseo/pull/8040), [#8076](https://github.com/getpaseo/paseo/pull/8076) by [@luoph](https://github.com/luoph), [@RRD-dev](https://github.com/RRD-dev)) +- Preserved plugin screens and local state during temporary host disconnections ([#8105](https://github.com/getpaseo/paseo/pull/8105) by [@luoph](https://github.com/luoph), [@RRD-dev](https://github.com/RRD-dev)) +- Let plugins choose worktree locations and creation options through `worktree.create.before` ([#8117](https://github.com/getpaseo/paseo/pull/8117) by [@mcowger](https://github.com/mcowger)) +- Added `server.addHook` with an awaited `worktree.create.after` hook before workspace setup and agents start ([#8081](https://github.com/getpaseo/paseo/pull/8081)) +- Released redundant plugin streaming snapshots instead of retaining them for the session’s lifetime ([#7675](https://github.com/getpaseo/paseo/pull/7675) by [@suntianc](https://github.com/suntianc)) + +### Fixed + +- Fixed rewinding Claude conversations to messages sent during an active turn ([#8372](https://github.com/getpaseo/paseo/pull/8372) by [@tieo](https://github.com/tieo)) +- Fixed duplicate rows and missing replies when resuming Claude subagents after reopening a session ([#8408](https://github.com/getpaseo/paseo/pull/8408) by [@luoph](https://github.com/luoph), [@RRD-dev](https://github.com/RRD-dev)) +- Fixed Codex agents created without a prompt failing after their runtime reopens ([#8393](https://github.com/getpaseo/paseo/pull/8393) by [@babo-jeonguk](https://github.com/babo-jeonguk)) +- Fixed newly running agents appearing as finished immediately after creation ([#8396](https://github.com/getpaseo/paseo/pull/8396) by [@luoph](https://github.com/luoph)) +- Fixed ACP startup exits waiting for a timeout instead of reporting the process error ([#8384](https://github.com/getpaseo/paseo/pull/8384) by [@Peanut-HZM](https://github.com/Peanut-HZM)) +- Fixed skills missing from new ACP agents when commands arrive in multiple batches ([#8387](https://github.com/getpaseo/paseo/pull/8387) by [@Peanut-HZM](https://github.com/Peanut-HZM)) +- Fixed sidebar titles and statuses stopping updates after directory subscriptions are released ([#8403](https://github.com/getpaseo/paseo/pull/8403) by [@ragokan](https://github.com/ragokan)) +- Kept the open workspace visible in collapsed sidebar groups ([#8395](https://github.com/getpaseo/paseo/pull/8395) by [@0xroylee](https://github.com/0xroylee)) +- Fixed relative chat links opening missing files instead of files in nested repositories ([#8361](https://github.com/getpaseo/paseo/pull/8361) by [@apple-ouyang](https://github.com/apple-ouyang)) +- Accepted host:port and pasted URLs in the Direct connection Host field ([#8223](https://github.com/getpaseo/paseo/pull/8223) by [@DaydreamCoding](https://github.com/DaydreamCoding)) +- Fixed terminal Ctrl+V paste over plain HTTP on non-Mac keyboards ([#8230](https://github.com/getpaseo/paseo/pull/8230) by [@DaydreamCoding](https://github.com/DaydreamCoding)) +- Stopped failed history loads from repeatedly reopening the provider, with Retry available in the chat ([#8278](https://github.com/getpaseo/paseo/pull/8278)) +- Fixed Claude settings files being discarded when Paseo adds its own launch settings ([#8148](https://github.com/getpaseo/paseo/pull/8148) by [@yayugu](https://github.com/yayugu)) +- Fixed steering messages replacing a turn that was still starting and losing its original prompt ([#6192](https://github.com/getpaseo/paseo/pull/6192)) +- Fixed Pi tool-result images missing during streaming and after reopening the chat ([#8280](https://github.com/getpaseo/paseo/pull/8280) by [@duyiliu](https://github.com/duyiliu)) +- Fixed completed `edxeth/pi-subagents` children remaining marked as working ([#8176](https://github.com/getpaseo/paseo/pull/8176) by [@Zeno2019](https://github.com/Zeno2019)) +- Fixed Claude background subagent status after reopening a conversation ([#6259](https://github.com/getpaseo/paseo/pull/6259)) +- Fixed reused plugin subagents showing their previous completed status during new work ([#8080](https://github.com/getpaseo/paseo/pull/8080) by [@bccy](https://github.com/bccy)) +- Fixed custom Codex providers with reserved names such as `ollama` ([#6954](https://github.com/getpaseo/paseo/pull/6954) by [@mr860819](https://github.com/mr860819)) +- Fixed the MiniMax Code catalog command failing to select an executable ([#8201](https://github.com/getpaseo/paseo/pull/8201) by [@Peanut-HZM](https://github.com/Peanut-HZM)) +- Fixed Android keeping the wrong layout after folding or unfolding while backgrounded ([#8285](https://github.com/getpaseo/paseo/pull/8285)) +- Fixed Android workspace layouts and header fades retaining their old size after rotation ([#8349](https://github.com/getpaseo/paseo/pull/8349), [#8377](https://github.com/getpaseo/paseo/pull/8377)) +- Fixed deleted agents leaving unclosable tabs in another window ([#8248](https://github.com/getpaseo/paseo/pull/8248) by [@loganmeyer](https://github.com/loganmeyer)) +- Fixed transcript text retaining old theme colors after the theme changes while the window is hidden ([#8199](https://github.com/getpaseo/paseo/pull/8199) by [@Nurshot](https://github.com/Nurshot), [@dansabin](https://github.com/dansabin)) +- Fixed web menus snapping back to their loading size after content arrives ([#8180](https://github.com/getpaseo/paseo/pull/8180) by [@babo-jeonguk](https://github.com/babo-jeonguk)) +- Fixed split dividers drifting ahead of or behind the pointer while dragging ([#6011](https://github.com/getpaseo/paseo/pull/6011)) +- Fixed delayed native filesystem watcher startup leaving Git updates unobserved ([#8107](https://github.com/getpaseo/paseo/pull/8107)) +- Fixed bundled skill arguments being passed incorrectly to Codex and Pi ([#8252](https://github.com/getpaseo/paseo/pull/8252) by [@AspireOne](https://github.com/AspireOne)) + +### Notes + +- The first upgrade from 0.14.0 still closes terminals; terminal preservation starts once the new daemon is installed, and Windows desktop app upgrades still close them +- Automatic agent recovery is on by default and sends `Resume working.`; change the prompt or disable it in Host settings → Agents +- Before downgrading to 0.14.0, restore a backed-up `config.json` or remove the saved agent-resume and usage-check settings + +## 0.14.0 - 2026-10-29 + +Plugins can now add tools to individual agents and configure their MCP servers when sessions open. + +Completed conversation turns can be collapsed into summaries and expanded to read the full exchange. + +Voice settings now let you configure speech providers and download local models with one tap, including SenseVoice and Whisper for Chinese dictation. Voice mode is now opt-in. + +### Added + +- Let plugins give tools to specific agents ([#7938](https://github.com/getpaseo/paseo/pull/7938)) +- Added Chat display settings that group tool calls or collapse completed conversation turns ([#7785](https://github.com/getpaseo/paseo/pull/7785), [#7990](https://github.com/getpaseo/paseo/pull/7990), [#8026](https://github.com/getpaseo/paseo/pull/8026), [#8042](https://github.com/getpaseo/paseo/pull/8042), [#8109](https://github.com/getpaseo/paseo/pull/8109) by [@akaready](https://github.com/akaready), [@Dey11](https://github.com/Dey11), [@Sebeb](https://github.com/Sebeb), [@Waishnav](https://github.com/Waishnav)) +- Let plugins add MCP servers whenever an agent session opens ([#7983](https://github.com/getpaseo/paseo/pull/7983)) +- Added downloadable local speech models in Voice settings, including SenseVoice and Whisper for Chinese dictation ([#7295](https://github.com/getpaseo/paseo/pull/7295)) +- Added a choice of Enter or ⌘/Ctrl+Enter to send messages ([#5503](https://github.com/getpaseo/paseo/pull/5503) by [@lukelabonte](https://github.com/lukelabonte)) +- Added sent-message recall with Up and Down in an empty web or desktop Composer ([#7710](https://github.com/getpaseo/paseo/pull/7710)) +- Added long-press Send to queue a message or send it immediately ([#7897](https://github.com/getpaseo/paseo/pull/7897) by [@bjspi](https://github.com/bjspi)) +- Added project-specific editor choices, including Xcode on macOS ([#7898](https://github.com/getpaseo/paseo/pull/7898) by [@kinoroy](https://github.com/kinoroy)) + +### Improved + +- Release eligible agent runtimes after one idle hour, resuming the saved session on the next prompt ([#7782](https://github.com/getpaseo/paseo/pull/7782)) +- Added a link back to the parent in subagent panes ([#7784](https://github.com/getpaseo/paseo/pull/7784)) +- Opened subagents in place of the subagent list on phones, with Back returning to the list ([#8093](https://github.com/getpaseo/paseo/pull/8093)) +- Added clickable links and selectable descriptions to question cards ([#7419](https://github.com/getpaseo/paseo/pull/7419) by [@NoSync](https://github.com/NoSync)) +- Kept large Import session lists responsive on web ([#7872](https://github.com/getpaseo/paseo/pull/7872) by [@royenheart](https://github.com/royenheart)) +- Enlarged project and workspace menu buttons on phones ([#7928](https://github.com/getpaseo/paseo/pull/7928)) +- Stopped hidden chats from rendering incoming text updates ([#7901](https://github.com/getpaseo/paseo/pull/7901)) +- Reduced stalls when highlighting and wrapping large diffs ([#8006](https://github.com/getpaseo/paseo/pull/8006), [#7945](https://github.com/getpaseo/paseo/pull/7945)) +- Reduced daemon stalls when opening and paging large Claude and OMP histories ([#7789](https://github.com/getpaseo/paseo/pull/7789), [#7940](https://github.com/getpaseo/paseo/pull/7940), [#7948](https://github.com/getpaseo/paseo/pull/7948), [#7958](https://github.com/getpaseo/paseo/pull/7958) by [@ragokan](https://github.com/ragokan)) +- Reduced daemon stalls during plugin builds, image processing and config reloads ([#7967](https://github.com/getpaseo/paseo/pull/7967), [#7954](https://github.com/getpaseo/paseo/pull/7954), [#7959](https://github.com/getpaseo/paseo/pull/7959)) +- Reduced blocking filesystem work during workspace and project refreshes ([#7941](https://github.com/getpaseo/paseo/pull/7941), [#7943](https://github.com/getpaseo/paseo/pull/7943), [#7944](https://github.com/getpaseo/paseo/pull/7944)) + +### Fixed + +- Fixed terminal glyph corruption when shared WebGL texture atlases change ([#8013](https://github.com/getpaseo/paseo/pull/8013) by [@donghyeonan](https://github.com/donghyeonan)) +- Fixed restored workspaces with no open chat staying on Loading workspace at launch on phones ([#7918](https://github.com/getpaseo/paseo/pull/7918)) +- Fixed restored agent tabs appearing in unrelated workspaces ([#7956](https://github.com/getpaseo/paseo/pull/7956) by [@odoo-mvds](https://github.com/odoo-mvds)) +- Fixed background Git fetches opening credential prompts ([#8019](https://github.com/getpaseo/paseo/pull/8019)) +- Fixed failed SSH tunnels crashing callers with an unhandled EPIPE ([#7876](https://github.com/getpaseo/paseo/pull/7876)) +- Fixed brief Windows file locks preventing atomic saves ([#7955](https://github.com/getpaseo/paseo/pull/7955)) +- Fixed large ACP terminal output blocking daemon requests ([#7953](https://github.com/getpaseo/paseo/pull/7953) by [@bbtfr](https://github.com/bbtfr)) +- Fixed messages sent during Pi manual compaction failing instead of waiting ([#7848](https://github.com/getpaseo/paseo/pull/7848) by [@itssimon](https://github.com/itssimon)) +- Fixed late tool updates creating duplicate rows during overlapping turns ([#8010](https://github.com/getpaseo/paseo/pull/8010) by [@luoph](https://github.com/luoph)) +- Fixed plugin ACP reasoning appearing inside assistant replies when message IDs match ([#7272](https://github.com/getpaseo/paseo/pull/7272) by [@cncolder](https://github.com/cncolder)) +- Fixed outside-folder links replacing Files with an access error ([#7726](https://github.com/getpaseo/paseo/pull/7726) by [@jtomaszewski](https://github.com/jtomaszewski)) +- Fixed command suggestions overlapping a growing Composer on phones ([#7910](https://github.com/getpaseo/paseo/pull/7910)) +- Fixed bare Markdown URLs losing ports or stopping at colons in paths ([#7859](https://github.com/getpaseo/paseo/pull/7859) by [@mariotaku](https://github.com/mariotaku)) +- Fixed inline code sizing inside emphasis, links and headings ([#7889](https://github.com/getpaseo/paseo/pull/7889), [#8088](https://github.com/getpaseo/paseo/pull/8088)) +- Fixed compact navigation sizes and a cramped Settings detail pane in docked windows 600–719 wide ([#8052](https://github.com/getpaseo/paseo/pull/8052) by [@zeyugao](https://github.com/zeyugao)) +- Fixed Settings losing the selected host or sidebar scroll position between sections ([#7893](https://github.com/getpaseo/paseo/pull/7893), [#7899](https://github.com/getpaseo/paseo/pull/7899) by [@bingqilinweimaotai](https://github.com/bingqilinweimaotai), [@wangnan0916](https://github.com/wangnan0916)) +- Fixed OpenCode v2 subagent rows missing model and token details ([#7799](https://github.com/getpaseo/paseo/pull/7799) by [@Davnn1](https://github.com/Davnn1)) +- Fixed file-link tooltips staying over the preview after leaving a chat ([#7842](https://github.com/getpaseo/paseo/pull/7842)) +- Fixed model discovery errors touching the model picker edges ([#8039](https://github.com/getpaseo/paseo/pull/8039) by [@ilteoood](https://github.com/ilteoood)) +- Fixed model selectors staying open over Settings ([#7783](https://github.com/getpaseo/paseo/pull/7783) by [@ragokan](https://github.com/ragokan)) + +### Notes + +- Voice mode now defaults to off; enable it in Voice settings +- If environment variables select OpenAI speech, move keys and endpoints stored only in legacy `providers.openai` into Voice settings +- Before downgrading to 0.13.2, restore a backed-up `config.json` or convert speech credentials and idle-cleanup settings saved by 0.14.0 +- Install the optional [Claude Code entrypoint plugin](https://paseo.sh/plugins/getpaseo/claude-code-entrypoint-env) to launch Claude sessions with `CLAUDE_CODE_ENTRYPOINT=Paseo`, a community workaround for subscription limits draining faster ([#7976](https://github.com/getpaseo/paseo/pull/7976), [#8164](https://github.com/getpaseo/paseo/pull/8164) by [@david828019-oss](https://github.com/david828019-oss)) + ## 0.13.2 - 2026-10-26 ### Fixed diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.md index 421da176dd..532ed24887 100644 --- a/CHANGELOG.zh-CN.md +++ b/CHANGELOG.zh-CN.md @@ -1,4 +1,144 @@ -# 更新日志 +# Changelog + +## 0.15.0-beta.1 - 2026-11-01 + +daemon 重启后,终端中的程序继续运行,被中断的 Agent 会自动在原有会话中恢复工作。 + +移动端终端采用原生渲染,并提供可拖动的文本选择手柄。重新连接时最多恢复 10,000 行终端历史。 + +worktree 初始化支持复制被忽略的文件,并在 Agent 启动前使用插件指定的位置。 + +### 新增 + +- 点击回复中的已知 Agent 命令,将其插入 Composer 草稿 ([#8371](https://github.com/getpaseo/paseo/pull/8371)) +- 复用已运行的 OpenCode v2 服务 ([#7435](https://github.com/getpaseo/paseo/pull/7435),贡献者:[@mcowger](https://github.com/mcowger)) +- 让终端中的程序在 daemon 重启、崩溃和支持的更新过程中继续运行 ([#7644](https://github.com/getpaseo/paseo/pull/7644), [#8155](https://github.com/getpaseo/paseo/pull/8155),贡献者:[@sebastianarena](https://github.com/sebastianarena)) +- 主机重启后,自动在原有会话中恢复被中断的 Agent ([#8127](https://github.com/getpaseo/paseo/pull/8127),贡献者:[@coolwindX](https://github.com/coolwindX), [@suntianc](https://github.com/suntianc)) +- 在 iOS 和 Android 终端中新增可拖动的文本选择手柄 ([#8348](https://github.com/getpaseo/paseo/pull/8348)) +- 让手机和平板遵循系统屏幕旋转设置 ([#8256](https://github.com/getpaseo/paseo/pull/8256),贡献者:[@magiclaw](https://github.com/magiclaw), [@yzim](https://github.com/yzim)) +- 通过 `.worktreeinclude` 选择要复制到新 worktree 的被忽略文件,在初始化和 Agent 启动前完成复制 ([#8100](https://github.com/getpaseo/paseo/pull/8100),贡献者:[@cprecioso](https://github.com/cprecioso)) +- 让 daemon 的网络请求支持 `HTTP_PROXY`、`HTTPS_PROXY` 和 `NO_PROXY` ([#8177](https://github.com/getpaseo/paseo/pull/8177)) +- 仅在显示用量时查询用量,并提供主机设置以完全关闭用量查询 ([#8181](https://github.com/getpaseo/paseo/pull/8181)) + +### 改进 + +- 更换移动端终端文本渲染方式,让中日韩字符、表情符号、带样式文本和光标对齐终端列 ([#8336](https://github.com/getpaseo/paseo/pull/8336), [#8375](https://github.com/getpaseo/paseo/pull/8375)) +- 重新连接时恢复设置指定的终端回滚历史,最多保留 10,000 行 ([#8282](https://github.com/getpaseo/paseo/pull/8282),贡献者:[@DrakenKor](https://github.com/DrakenKor), [@lennartschoch](https://github.com/lennartschoch)) +- 导入或重新打开 Codex 会话时加载分页历史 ([#8171](https://github.com/getpaseo/paseo/pull/8171),贡献者:[@dundunHa](https://github.com/dundunHa), [@hr95savage](https://github.com/hr95savage)) +- 重新打开已有缓存的 Codex 聊天时,不再重复读取并保留未使用的历史副本 ([#8132](https://github.com/getpaseo/paseo/pull/8132)) +- 将 daemon 的大型响应拆分为多个 relay 帧,避免达到单帧限制时断开连接 ([#8302](https://github.com/getpaseo/paseo/pull/8302)) +- 向应用发送聊天条目前截断超大内容,包括大型工具结果和内嵌数据 ([#8274](https://github.com/getpaseo/paseo/pull/8274)) +- 在子 Agent 自己的面板中显示活动,不再在父 Agent 的工具卡片中重复显示 ([#8276](https://github.com/getpaseo/paseo/pull/8276)) +- 在更精确的倒计时旁显示用量限制的具体重置时间 ([#8162](https://github.com/getpaseo/paseo/pull/8162)) + +### 插件 + +- 修复了插件会话回退后已丢弃的消息重新出现的问题 ([#8368](https://github.com/getpaseo/paseo/pull/8368),贡献者:[@mcowger](https://github.com/mcowger), [@omercnet](https://github.com/omercnet)) +- 通过缩小客户端代码包并在重连和应用启动时复用缓存,减少插件下载量 ([#8040](https://github.com/getpaseo/paseo/pull/8040), [#8076](https://github.com/getpaseo/paseo/pull/8076),贡献者:[@luoph](https://github.com/luoph), [@RRD-dev](https://github.com/RRD-dev)) +- 在主机暂时断开连接期间保留插件页面和本地状态 ([#8105](https://github.com/getpaseo/paseo/pull/8105),贡献者:[@luoph](https://github.com/luoph), [@RRD-dev](https://github.com/RRD-dev)) +- 让插件通过 `worktree.create.before` 指定 worktree 的位置和创建选项 ([#8117](https://github.com/getpaseo/paseo/pull/8117),贡献者:[@mcowger](https://github.com/mcowger)) +- 新增 `server.addHook`,并在工作区初始化和 Agent 启动前等待 `worktree.create.after` hook 完成 ([#8081](https://github.com/getpaseo/paseo/pull/8081)) +- 释放多余的插件流式快照,不再将其保留到会话结束 ([#7675](https://github.com/getpaseo/paseo/pull/7675),贡献者:[@suntianc](https://github.com/suntianc)) + +### 修复 + +- 修复了无法将 Claude 会话回退到运行过程中发送的消息的问题 ([#8372](https://github.com/getpaseo/paseo/pull/8372),贡献者:[@tieo](https://github.com/tieo)) +- 修复了重新打开会话后恢复 Claude 子 Agent 时出现重复行和回复缺失的问题 ([#8408](https://github.com/getpaseo/paseo/pull/8408),贡献者:[@luoph](https://github.com/luoph), [@RRD-dev](https://github.com/RRD-dev)) +- 修复了未发送提示词的 Codex Agent 在运行时重新打开后无法使用的问题 ([#8393](https://github.com/getpaseo/paseo/pull/8393),贡献者:[@babo-jeonguk](https://github.com/babo-jeonguk)) +- 修复了刚开始运行的 Agent 在创建后立即显示为已完成的问题 ([#8396](https://github.com/getpaseo/paseo/pull/8396),贡献者:[@luoph](https://github.com/luoph)) +- 修复了 ACP 启动进程退出后仍等待超时而未及时报告错误的问题 ([#8384](https://github.com/getpaseo/paseo/pull/8384),贡献者:[@Peanut-HZM](https://github.com/Peanut-HZM)) +- 修复了命令分批到达时新 ACP Agent 的技能列表不完整的问题 ([#8387](https://github.com/getpaseo/paseo/pull/8387),贡献者:[@Peanut-HZM](https://github.com/Peanut-HZM)) +- 修复了目录订阅释放后侧栏标题和状态停止更新的问题 ([#8403](https://github.com/getpaseo/paseo/pull/8403),贡献者:[@ragokan](https://github.com/ragokan)) +- 在折叠的侧栏分组中保持当前工作区可见 ([#8395](https://github.com/getpaseo/paseo/pull/8395),贡献者:[@0xroylee](https://github.com/0xroylee)) +- 修复了聊天中的相对链接未打开嵌套仓库中的文件而指向不存在文件的问题 ([#8361](https://github.com/getpaseo/paseo/pull/8361),贡献者:[@apple-ouyang](https://github.com/apple-ouyang)) +- 在直接连接的主机字段中支持 host:port 和粘贴的 URL ([#8223](https://github.com/getpaseo/paseo/pull/8223),贡献者:[@DaydreamCoding](https://github.com/DaydreamCoding)) +- 修复了非 Mac 键盘通过普通 HTTP 访问网页终端时 Ctrl+V 无法粘贴的问题 ([#8230](https://github.com/getpaseo/paseo/pull/8230),贡献者:[@DaydreamCoding](https://github.com/DaydreamCoding)) +- 停止在历史加载失败后反复重新打开 Provider,可在聊天中手动重试 ([#8278](https://github.com/getpaseo/paseo/pull/8278)) +- 修复了 Paseo 添加自身启动设置时丢弃 Claude 设置文件的问题 ([#8148](https://github.com/getpaseo/paseo/pull/8148),贡献者:[@yayugu](https://github.com/yayugu)) +- 修复了引导消息替换尚在启动的轮次并丢失原始提示词的问题 ([#6192](https://github.com/getpaseo/paseo/pull/6192)) +- 修复了 Pi 工具结果中的图片在流式输出和重新打开聊天后缺失的问题 ([#8280](https://github.com/getpaseo/paseo/pull/8280),贡献者:[@duyiliu](https://github.com/duyiliu)) +- 修复了 `edxeth/pi-subagents` 子 Agent 完成后仍显示为工作中的问题 ([#8176](https://github.com/getpaseo/paseo/pull/8176),贡献者:[@Zeno2019](https://github.com/Zeno2019)) +- 修复了重新打开会话后的 Claude 后台子 Agent 状态 ([#6259](https://github.com/getpaseo/paseo/pull/6259)) +- 修复了复用的插件子 Agent 开始新任务时仍显示上次已完成状态的问题 ([#8080](https://github.com/getpaseo/paseo/pull/8080),贡献者:[@bccy](https://github.com/bccy)) +- 修复了使用 `ollama` 等保留名称的自定义 Codex Provider ([#6954](https://github.com/getpaseo/paseo/pull/6954),贡献者:[@mr860819](https://github.com/mr860819)) +- 修复了 MiniMax Code 目录命令无法选定可执行文件的问题 ([#8201](https://github.com/getpaseo/paseo/pull/8201),贡献者:[@Peanut-HZM](https://github.com/Peanut-HZM)) +- 修复了 Android 应用在后台折叠或展开后保留错误布局的问题 ([#8285](https://github.com/getpaseo/paseo/pull/8285)) +- 修复了 Android 屏幕旋转后工作区布局和顶栏渐变保留旧尺寸的问题 ([#8349](https://github.com/getpaseo/paseo/pull/8349), [#8377](https://github.com/getpaseo/paseo/pull/8377)) +- 修复了删除 Agent 后,另一个窗口留下无法关闭的标签页的问题 ([#8248](https://github.com/getpaseo/paseo/pull/8248),贡献者:[@loganmeyer](https://github.com/loganmeyer)) +- 修复了窗口隐藏期间切换主题后,聊天文本保留旧主题颜色的问题 ([#8199](https://github.com/getpaseo/paseo/pull/8199),贡献者:[@Nurshot](https://github.com/Nurshot), [@dansabin](https://github.com/dansabin)) +- 修复了网页菜单加载内容后跳回加载时尺寸的问题 ([#8180](https://github.com/getpaseo/paseo/pull/8180),贡献者:[@babo-jeonguk](https://github.com/babo-jeonguk)) +- 修复了拖动分隔线时,分隔线偏离指针的问题 ([#6011](https://github.com/getpaseo/paseo/pull/6011)) +- 修复了原生文件监听器启动延迟导致 Git 更新未被监听的问题 ([#8107](https://github.com/getpaseo/paseo/pull/8107)) +- 修复了内置 skill 参数未正确传递给 Codex 和 Pi 的问题 ([#8252](https://github.com/getpaseo/paseo/pull/8252),贡献者:[@AspireOne](https://github.com/AspireOne)) + +### 说明 + +- 首次从 0.14.0 升级时仍会关闭终端;安装新 daemon 后才支持保留终端,Windows 桌面应用升级仍会关闭终端 +- Agent 自动恢复默认开启,并发送 `Resume working.`;可在主机设置 → Agent 中修改提示词或关闭此功能 +- 降级到 0.14.0 前,请恢复备份的 `config.json`,或删除已保存的 Agent 恢复和用量查询设置 + +## 0.14.0 - 2026-10-29 + +插件现在可以为单个 Agent 添加工具,并在会话打开时配置其 MCP 服务器。 + +已完成的对话轮次可以折叠为摘要,也可以展开查看完整对话。 + +语音设置现在支持配置语音服务商并一键下载本地模型,包括可用于中文听写的 SenseVoice 和 Whisper。语音模式现在需要主动开启。 + +### 新增 + +- 插件现在可以为特定 Agent 提供工具 ([#7938](https://github.com/getpaseo/paseo/pull/7938)) +- 新增“聊天显示”设置,可将工具调用分组或折叠已完成的对话轮次 ([#7785](https://github.com/getpaseo/paseo/pull/7785), [#7990](https://github.com/getpaseo/paseo/pull/7990), [#8026](https://github.com/getpaseo/paseo/pull/8026), [#8042](https://github.com/getpaseo/paseo/pull/8042), [#8109](https://github.com/getpaseo/paseo/pull/8109) by [@akaready](https://github.com/akaready), [@Dey11](https://github.com/Dey11), [@Sebeb](https://github.com/Sebeb), [@Waishnav](https://github.com/Waishnav)) +- 插件现在可以在每次打开 Agent 会话时添加 MCP 服务器 ([#7983](https://github.com/getpaseo/paseo/pull/7983)) +- 语音设置新增可下载的本地语音模型,支持使用 SenseVoice 和 Whisper 进行中文听写 ([#7295](https://github.com/getpaseo/paseo/pull/7295)) +- 新增 Enter 或 ⌘/Ctrl+Enter 发送消息的快捷键选项 ([#5503](https://github.com/getpaseo/paseo/pull/5503) by [@lukelabonte](https://github.com/lukelabonte)) +- 新增在网页和桌面端的空 Composer 中按上下键回顾已发送消息 ([#7710](https://github.com/getpaseo/paseo/pull/7710)) +- 新增长按发送按钮排队发送或立即发送消息 ([#7897](https://github.com/getpaseo/paseo/pull/7897) by [@bjspi](https://github.com/bjspi)) +- 新增按项目记忆编辑器的功能,macOS 支持 Xcode ([#7898](https://github.com/getpaseo/paseo/pull/7898) by [@kinoroy](https://github.com/kinoroy)) + +### 改进 + +- 符合条件的 Agent 运行时空闲一小时后释放,下次发送提示词时恢复已保存的会话 ([#7782](https://github.com/getpaseo/paseo/pull/7782)) +- 在子 Agent 窗格中新增返回父 Agent 的链接 ([#7784](https://github.com/getpaseo/paseo/pull/7784)) +- 在手机上从子 Agent 列表打开子 Agent 时直接替换列表,点按“返回”可回到列表 ([#8093](https://github.com/getpaseo/paseo/pull/8093)) +- 问题卡片新增可点击链接和可选中的描述文本 ([#7419](https://github.com/getpaseo/paseo/pull/7419) by [@NoSync](https://github.com/NoSync)) +- 减少网页端长会话导入列表的操作卡顿 ([#7872](https://github.com/getpaseo/paseo/pull/7872) by [@royenheart](https://github.com/royenheart)) +- 增大手机上项目和工作区菜单按钮的点击区域 ([#7928](https://github.com/getpaseo/paseo/pull/7928)) +- 隐藏的聊天不再渲染收到的文本更新 ([#7901](https://github.com/getpaseo/paseo/pull/7901)) +- 减少大型 diff 高亮和自动换行时的卡顿 ([#8006](https://github.com/getpaseo/paseo/pull/8006), [#7945](https://github.com/getpaseo/paseo/pull/7945)) +- 减少打开和分页加载大型 Claude 和 OMP 历史时的 daemon 卡顿 ([#7789](https://github.com/getpaseo/paseo/pull/7789), [#7940](https://github.com/getpaseo/paseo/pull/7940), [#7948](https://github.com/getpaseo/paseo/pull/7948), [#7958](https://github.com/getpaseo/paseo/pull/7958) by [@ragokan](https://github.com/ragokan)) +- 减少插件构建、图片处理和重新加载配置时的 daemon 卡顿 ([#7967](https://github.com/getpaseo/paseo/pull/7967), [#7954](https://github.com/getpaseo/paseo/pull/7954), [#7959](https://github.com/getpaseo/paseo/pull/7959)) +- 减少刷新工作区和项目时由文件系统操作造成的阻塞 ([#7941](https://github.com/getpaseo/paseo/pull/7941), [#7943](https://github.com/getpaseo/paseo/pull/7943), [#7944](https://github.com/getpaseo/paseo/pull/7944)) + +### 修复 + +- 修复共享 WebGL 纹理图集变化时终端字符显示错误的问题 ([#8013](https://github.com/getpaseo/paseo/pull/8013) by [@donghyeonan](https://github.com/donghyeonan)) +- 修复手机启动时没有打开聊天的已恢复工作区停留在加载状态的问题 ([#7918](https://github.com/getpaseo/paseo/pull/7918)) +- 修复已恢复的 Agent 标签出现在无关工作区中的问题 ([#7956](https://github.com/getpaseo/paseo/pull/7956) by [@odoo-mvds](https://github.com/odoo-mvds)) +- 修复后台 Git 拉取弹出凭据提示的问题 ([#8019](https://github.com/getpaseo/paseo/pull/8019)) +- 修复 SSH 隧道失败时未处理的 EPIPE 导致调用方崩溃的问题 ([#7876](https://github.com/getpaseo/paseo/pull/7876)) +- 修复 Windows 短暂文件锁导致原子保存失败的问题 ([#7955](https://github.com/getpaseo/paseo/pull/7955)) +- 修复 ACP 终端产生大量输出时阻塞 daemon 的问题 ([#7953](https://github.com/getpaseo/paseo/pull/7953) by [@bbtfr](https://github.com/bbtfr)) +- 修复 Pi 手动压缩上下文期间发送消息直接失败而不等待的问题 ([#7848](https://github.com/getpaseo/paseo/pull/7848) by [@itssimon](https://github.com/itssimon)) +- 修复轮次重叠时较晚的工具更新产生重复行的问题 ([#8010](https://github.com/getpaseo/paseo/pull/8010) by [@luoph](https://github.com/luoph)) +- 修复插件 ACP 推理和回复的消息 ID 相同时,推理内容混入回复的问题 ([#7272](https://github.com/getpaseo/paseo/pull/7272) by [@cncolder](https://github.com/cncolder)) +- 修复工作区外的文件夹链接使 Files 显示访问错误的问题 ([#7726](https://github.com/getpaseo/paseo/pull/7726) by [@jtomaszewski](https://github.com/jtomaszewski)) +- 修复手机上命令建议与不断增高的 Composer 重叠的问题 ([#7910](https://github.com/getpaseo/paseo/pull/7910)) +- 修复 Markdown 裸链接丢失端口或在路径冒号处截断的问题 ([#7859](https://github.com/getpaseo/paseo/pull/7859) by [@mariotaku](https://github.com/mariotaku)) +- 修复强调、链接和标题中行内代码的字号问题 ([#7889](https://github.com/getpaseo/paseo/pull/7889), [#8088](https://github.com/getpaseo/paseo/pull/8088)) +- 修复宽度 600–719 的停靠布局使用紧凑导航尺寸、设置详情面板过窄的问题 ([#8052](https://github.com/getpaseo/paseo/pull/8052) by [@zeyugao](https://github.com/zeyugao)) +- 修复切换设置页面时丢失已选主机或侧栏滚动位置的问题 ([#7893](https://github.com/getpaseo/paseo/pull/7893), [#7899](https://github.com/getpaseo/paseo/pull/7899) by [@bingqilinweimaotai](https://github.com/bingqilinweimaotai), [@wangnan0916](https://github.com/wangnan0916)) +- 修复 OpenCode v2 子 Agent 行缺少模型和 token 详情的问题 ([#7799](https://github.com/getpaseo/paseo/pull/7799) by [@Davnn1](https://github.com/Davnn1)) +- 修复离开聊天后文件链接提示仍遮挡预览的问题 ([#7842](https://github.com/getpaseo/paseo/pull/7842)) +- 修复模型发现错误信息紧贴模型选择器边缘的问题 ([#8039](https://github.com/getpaseo/paseo/pull/8039) by [@ilteoood](https://github.com/ilteoood)) +- 修复模型选择器在打开设置后仍然显示的问题 ([#7783](https://github.com/getpaseo/paseo/pull/7783) by [@ragokan](https://github.com/ragokan)) + +### 说明 + +- 语音模式默认关闭,可在语音设置中启用 +- 如果通过环境变量选择 OpenAI 语音,请将仅保存在旧版 `providers.openai` 中的密钥和服务地址移至语音设置 +- 降级至 0.13.2 前,请恢复备份的 `config.json` 或转换 0.14.0 保存的语音凭据和空闲清理设置 +- 安装可选的 [Claude Code entrypoint 插件](https://paseo.sh/plugins/getpaseo/claude-code-entrypoint-env),即可使用 `CLAUDE_CODE_ENTRYPOINT=Paseo` 启动 Claude 会话;这是针对订阅额度消耗过快问题的社区变通方案 ([#7976](https://github.com/getpaseo/paseo/pull/7976), [#8164](https://github.com/getpaseo/paseo/pull/8164) by [@david828019-oss](https://github.com/david828019-oss)) ## 0.13.2 - 2026-10-26 diff --git a/CLAUDE.md b/CLAUDE.md index 3f1731597c..71682af7e9 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -52,6 +52,7 @@ At the start of non-trivial work, list `docs/` and skim anything relevant to the | [docs/connected-hosts.md](docs/connected-hosts.md) | Daemon-owned host registrations, routed SDK scopes, identity and authority boundaries | | [docs/permissions.md](docs/permissions.md) | Semantic daemon permissions, principals, credentials, pairing invitations, and Hub authority | | [docs/terminal-performance.md](docs/terminal-performance.md) | Terminal latency pipeline, coalescing/backpressure invariants, benchmark + perf spec usage | +| [docs/terminal-rendering.md](docs/terminal-rendering.md) | Native terminal view: xterm owns the grid, cluster placement, emoji widths, mixed-direction limits, render regression | | [docs/agent-stream-performance.md](docs/agent-stream-performance.md) | Assistant text pipeline — coalescing window, paced reveal, why arrival lumps are smoothed at render | | [docs/markdown-renderer.md](docs/markdown-renderer.md) | Shared Markdown engine, native selection, links, images and library constraints | | [docs/native-text-selection.md](docs/native-text-selection.md) | Native diagram grouping, selection boundaries and leading inline image limitations | @@ -66,6 +67,7 @@ At the start of non-trivial work, list `docs/` and skim anything relevant to the | [docs/android.md](docs/android.md) | App variants, local/cloud builds, EAS workflows, version codes, F-Droid source builds and store metadata | | [docs/docker.md](docs/docker.md) | Running the daemon and bundled web UI in Docker, volumes, agent images, security | | [docs/release.md](docs/release.md) | Release playbook, draft releases, completion checklist | +| [docs/terminal-worker.md](docs/terminal-worker.md) | Terminal worker process model, socket/record/secret, protocol-bump rule and draining, the worker's file copy, Windows desktop | | [docs/terminal-activity.md](docs/terminal-activity.md) | Terminal activity indicators — source-agnostic tracker, agent hook reporting, adding a new hook provider | | [SECURITY.md](SECURITY.md) | Relay threat model, E2E encryption, DNS rebinding, agent auth | | [public-docs/hub/security.md](public-docs/hub/security.md) | Public Hub guide — trust boundaries, untrusted triggers, provider controls, and output authority | @@ -116,10 +118,9 @@ See [docs/development.md](docs/development.md) for full setup, build sync requir ## Release branches -When the user says "this goes to next", create or -retarget the PR to `next` and preserve that destination through delivery. Follow -[release branch discipline](docs/release.md#release-branch-discipline) for creating -and updating `next`, integrating it after a release, and releasing a hotfix from a tag. +Merge normal PRs into `main`, including while a beta soaks or a release is being finalized. Each +release builds in a short-lived release workspace from `origin/main` or a release tag; see +[release base and source](docs/release.md#release-base-and-source). ## Critical rules diff --git a/assets/store-screenshots/.gitignore b/assets/store-screenshots/.gitignore new file mode 100644 index 0000000000..22908c2c7d --- /dev/null +++ b/assets/store-screenshots/.gitignore @@ -0,0 +1 @@ +output/preview.png diff --git a/assets/store-screenshots/README.md b/assets/store-screenshots/README.md new file mode 100644 index 0000000000..fc37d98bd8 --- /dev/null +++ b/assets/store-screenshots/README.md @@ -0,0 +1,102 @@ +# Store screenshots + +Five panels for the App Store and Google Play, in phone and tablet sets, made from native captures of the real app. Both sets tell the same story with the same copy; only the capture, the device frame and the callouts change. + +| # | Headline | Capture | Phone callout | Tablet callout | +| --- | --------------------------------------- | ---------------------------------------------------------------------- | -------------------------------------------- | ------------------------------------- | +| 1 | Run many coding agents at once | Sidebar grouped by status: Needs input, Ready to review, Working, Done | — (agent marks in the background) | — (agent marks in the background) | +| 2 | Your full dev environment on your phone | Agent chat: reasoning, tool calls, final summary | — | — (Changes pane open beside the chat) | +| 3 | Ask an agent to change the app itself | A chat asking for a plugin, the turn collapsed, the new Deploys pill | The plugin's Preview deploys sheet | The plugin's Deploys popover | +| 4 | Review the diff before you merge | `daemon-client.ts` diff with removed and added lines | Jump to file: four changed files with counts | — (the full-width diff reads as is) | +| 5 | A real terminal in every workspace | `git status` and a vitest run in the same worktree | The passing test tree | The passing test tree | + +On tablets, panel 2 says "on your tablet" and panel 3 calls the popover a panel. A scene overrides its copy per device in `render.mjs`. + +## Creative direction + +The panels follow paseo.sh: + +- **Canvas:** the site's `#101615` background. +- **Type:** centred SF Pro headlines in sentence case, with no closing period. Every headline wraps to exactly two lines. +- **Sublines:** one plain grey sentence on one line that says what you can do. The renderer fails if a headline or subline wraps differently, because the device is placed from that fixed text height. +- **Agent marks:** panel 1 scatters faded, rotated, monochrome marks of the agents featured on the homepage behind the device. They are rendered from `packages/website/src/components/agent-icons.tsx`, so they follow the site. +- **Device:** dark-mode captures in a plain black frame; the iPhone frame has a Dynamic Island. The device starts a fixed gap below the text and runs just off the bottom edge, so a taller canvas gets a larger device instead of a larger gap. A canvas too narrow for that, like a 3:4 iPad on Google's 9:16 tablet canvas, shows the whole device at full width with the text and device centred. +- **Callouts:** a callout lifts one region of a capture out of the device, larger than the device around it, so the detail reads at store thumbnail size. On tablets, place callouts over empty screen so they do not hide the context they explain. + +Everything on screen is real app UI showing one story. The hero agent adds jitter to the reconnect backoff in this repository. Its diff, test run and terminal come from a real worktree. The other workspaces fill the sidebar's status groups. + +Panel 3 shows a real plugin. `demo/preview-deploys/` is a trusted local plugin that adds a Deploys composer pill; its popover opens as a sheet on phones and as a popover on tablets. The deploys it lists are sample data. The demo host installs it, and a scripted agent in the "Build a preview deploys plugin" workspace plays the turn that writes it. + +## Files + +- `raw/iphone/`: native 1320 × 2868 captures from an iPhone 16 Pro Max simulator. `files.png` and `plugin-sheet.png` are the sources for the Jump to file and Preview deploys callouts. +- `raw/ipad/`: native 2064 × 2752 captures from an iPad Pro 13-inch (M4) simulator. `plugin-sheet.png` is the source for the Deploys popover callout. +- `render.mjs`: the layout, copy and callout crops. Edit `SCENES`, `DEVICES` and `STORES` there. +- `demo/`: the staged demo host the captures come from. +- `output/apple/`: 1320 × 2868 for the iPhone 6.9-inch slot. +- `output/google/`: 1440 × 2560 (9:16) phone screenshots, reusing the iPhone captures. +- `output/apple-ipad/`: 2064 × 2752 for the iPad 13-inch slot. +- `output/google-tablet/`: 1800 × 3200 (9:16) tablet screenshots, reusing the iPad captures. +- `output/preview.png`: contact sheet with one row per store, for review only. It is ignored by Git; do not upload it to a store. + +All exports are opaque RGB PNGs. + +## Render + +```sh +SF_FONT_DIR=/path/to/fonts node assets/store-screenshots/render.mjs +``` + +`SF_FONT_DIR` must hold `SFNS.ttf` copied from a Mac's `/System/Library/Fonts`. On macOS the renderer finds it without the variable. SF Pro is not redistributable, so it is not in the repository. The renderer fails rather than fall back to another font. + +Each capture and callout is resized with Lanczos to the exact pixels it fills, and the page renders at device scale 1. Do not render at a higher scale and downsample: Chrome's image downscaling is what made earlier exports look soft and aliased. + +Open `output/preview.png` and at least one full-size panel per store before you call a render done. The line guard catches wrapping, not a callout that covers the wrong thing. + +Callout crops are in native capture pixels. To find them, overlay a 100 px grid on the capture with sharp and read the coordinates off it. + +## Recapture + +1. Stage the demo host. It runs an in-process daemon on port 7791 with scripted Claude Code and Codex clients, a local clone of this repository as the `paseo` project, real worktrees, and a terminal in the hero worktree: + + ```sh + npx tsx assets/store-screenshots/demo/stage.mts + ``` + + Each run re-clones the repository into the demo home, so stale worktrees from an earlier run do not block it. The hero agent is paced so it reports a realistic "Worked for" time. Wait for `READY` in its output. + +2. Start Metro against it on a free port. When the simulator runs on another Mac, forward Metro and the daemon to it. Other agents may already hold a Metro port; pick another one rather than stopping theirs. + + ```sh + EXPO_PUBLIC_LOCAL_DAEMON=127.0.0.1:7791 npm run start:expo --workspace=@getpaseo/app -- --port + ssh -o ExitOnForwardFailure=yes -R :127.0.0.1: -R 7791:127.0.0.1:7791 + ``` + +3. On the simulator, install and open the dev client (`sh.paseo.debug`) at `http://127.0.0.1:`. Use an iPhone 16 Pro Max for the phone set and an iPad Pro 13-inch (M4) in portrait for the tablet set. + - Set dark appearance and override the status bar to 9:41 with full battery and signal (`xcrun simctl status_bar override`). + - On first launch, accept the open-in-app dialog, decline notifications, turn off the dev client's Tools button, and close any error toast. `agent-device react-native dismiss-overlay` clears overlays. + - Name the host "MacBook Pro" and set the sidebar badge to Hidden. + - Group the sidebar by status. + - If you reset the simulator, reinstall the dev client. + +4. Capture the sidebar first. Opening a "Ready to review" workspace marks it done. Select a Working row before you capture. + +5. Capture every screen at native density. `agent-device screenshot` defaults to 1x, which is too soft for the store: + + ```sh + agent-device screenshot /tmp/sidebar.png --pixel-density 3 --session store # iPhone: 1320 × 2868 + agent-device screenshot /tmp/sidebar.png --pixel-density 2 --session store # iPad: 2064 × 2752 + ``` + + - **Chat:** expand the tool-call group and scroll to the bottom. On iPad, open Explorer → Changes beside the chat. + - **Diff:** on iPhone, Explorer → Changes, then use Jump to file to reach `daemon-client.ts`. On iPad, collapse the sidebar, open a Diff tab from the main area's **+** menu and scroll to the `daemon-client.ts` hunks. + - **Terminal:** the second workspace tab. Type the commands with `npm run cli -- terminal send-keys --host 127.0.0.1:7791 "" Enter` instead of the simulator keyboard, then dismiss the software keyboard. + - **Plugin:** the "Build a preview deploys plugin" workspace with the turn collapsed, then tap **Deploys** for `plugin-sheet.png`. After editing the plugin, reload it with `npm run cli -- plugin reload --host 127.0.0.1:7791 preview-deploys`. + +6. Copy the captures into `raw/iphone/` or `raw/ipad/` under the names `render.mjs` uses, render, and check the preview. + +## Publish + +The stable release uploads these exports to the App Store and Google Play, and F-Droid reads the Google ones from the repo. See [Store screenshots](../../docs/release.md#store-screenshots). The Android metadata holds links to the Google exports, and every render rewrites them, so commit the links with the exports. + +Dimensions are checked against [Apple's screenshot specifications](https://developer.apple.com/help/app-store-connect/reference/app-information/screenshot-specifications/) and [Google Play's preview asset requirements](https://support.google.com/googleplay/android-developer/answer/9866151?hl=en). diff --git a/assets/store-screenshots/demo/change/apply.mjs b/assets/store-screenshots/demo/change/apply.mjs new file mode 100644 index 0000000000..ae5efe295b --- /dev/null +++ b/assets/store-screenshots/demo/change/apply.mjs @@ -0,0 +1,84 @@ +// Applies the demo change to a checkout of the Paseo repository. +import { copyFileSync, readFileSync, writeFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const here = path.dirname(fileURLToPath(import.meta.url)); +const repo = process.argv[2]; +const client = path.join(repo, "packages/client/src"); + +copyFileSync( + path.join(here, "reconnect-delay.ts"), + path.join(client, "connection/reconnect-delay.ts"), +); +copyFileSync( + path.join(here, "reconnect-delay.test.ts"), + path.join(client, "connection/reconnect-delay.test.ts"), +); + +function edit(file, pairs) { + let text = readFileSync(file, "utf8"); + for (const [from, to] of pairs) { + if (!text.includes(from)) throw new Error(`Missing anchor in ${file}: ${from.slice(0, 60)}`); + text = text.replace(from, to); + } + writeFileSync(file, text); +} + +edit(path.join(client, "daemon-client.ts"), [ + [ + `import { CreationClient } from "./creation/index.js";\n`, + `import { CreationClient } from "./creation/index.js";\nimport { getReconnectDelayMs } from "./connection/reconnect-delay.js";\n`, + ], + [ + ` private reconnectAttempt = 0;\n`, + ` private reconnectAttempt = 0;\n private nextReconnectDelay: { attempt: number; delayMs: number } | null = null;\n`, + ], + [ + ` nextRetryAt: new Date( + Date.now() + + Math.min( + (this.config.reconnect?.baseDelayMs ?? DEFAULT_RECONNECT_BASE_DELAY_MS) * + 2 ** this.reconnectAttempt, + this.config.reconnect?.maxDelayMs ?? DEFAULT_RECONNECT_MAX_DELAY_MS, + ), + ).toISOString(), +`, + ` nextRetryAt: new Date(Date.now() + this.getNextReconnectDelayMs()).toISOString(), +`, + ], + [ + ` private armReconnectTimer(): void { + const attempt = this.reconnectAttempt; + const baseDelay = this.config.reconnect?.baseDelayMs ?? DEFAULT_RECONNECT_BASE_DELAY_MS; + const maxDelay = this.config.reconnect?.maxDelayMs ?? DEFAULT_RECONNECT_MAX_DELAY_MS; + const delay = Math.min(baseDelay * 2 ** attempt, maxDelay); +`, + ` // The countdown and the timer must agree, so each attempt draws its jitter once. + private getNextReconnectDelayMs(): number { + const attempt = this.reconnectAttempt; + if (this.nextReconnectDelay?.attempt !== attempt) { + this.nextReconnectDelay = { + attempt, + delayMs: getReconnectDelayMs(attempt, { + baseDelayMs: this.config.reconnect?.baseDelayMs ?? DEFAULT_RECONNECT_BASE_DELAY_MS, + maxDelayMs: this.config.reconnect?.maxDelayMs ?? DEFAULT_RECONNECT_MAX_DELAY_MS, + }), + }; + } + return this.nextReconnectDelay.delayMs; + } + + private armReconnectTimer(): void { + const attempt = this.reconnectAttempt; + const delay = this.getNextReconnectDelayMs(); +`, + ], +]); + +edit(path.join(repo, "CHANGELOG.md"), [ + [ + `# Changelog\n\n`, + `# Changelog\n\n## Unreleased\n\n### Fixed\n\n- Spread reconnect attempts after a relay restart instead of retrying every client at once\n\n`, + ], +]); diff --git a/assets/store-screenshots/demo/change/reconnect-delay.test.ts b/assets/store-screenshots/demo/change/reconnect-delay.test.ts new file mode 100644 index 0000000000..3b5367784c --- /dev/null +++ b/assets/store-screenshots/demo/change/reconnect-delay.test.ts @@ -0,0 +1,29 @@ +import { describe, expect, it } from "vitest"; +import { getReconnectDelayMs } from "./reconnect-delay"; + +const options = { baseDelayMs: 1500, maxDelayMs: 30_000 }; + +describe("getReconnectDelayMs", () => { + it("doubles the ceiling on each attempt", () => { + const top = () => 1; + expect(getReconnectDelayMs(0, options, top)).toBe(1500); + expect(getReconnectDelayMs(1, options, top)).toBe(3000); + expect(getReconnectDelayMs(2, options, top)).toBe(6000); + }); + + it("never waits longer than the max delay", () => { + expect(getReconnectDelayMs(12, options, () => 1)).toBe(30_000); + }); + + it("spreads retries between half and the full ceiling", () => { + expect(getReconnectDelayMs(3, options, () => 0)).toBe(6000); + expect(getReconnectDelayMs(3, options, () => 0.5)).toBe(9000); + expect(getReconnectDelayMs(3, options, () => 1)).toBe(12_000); + }); + + it("keeps the first retry under two seconds", () => { + for (let i = 0; i < 100; i += 1) { + expect(getReconnectDelayMs(0, options)).toBeLessThanOrEqual(1500); + } + }); +}); diff --git a/assets/store-screenshots/demo/change/reconnect-delay.ts b/assets/store-screenshots/demo/change/reconnect-delay.ts new file mode 100644 index 0000000000..88de867aa6 --- /dev/null +++ b/assets/store-screenshots/demo/change/reconnect-delay.ts @@ -0,0 +1,18 @@ +export interface ReconnectDelayOptions { + baseDelayMs: number; + maxDelayMs: number; +} + +/** + * Exponential backoff with equal jitter. Half of each delay is fixed and half + * is random, so a relay restart spreads reconnects out instead of every client + * retrying on the same tick. + */ +export function getReconnectDelayMs( + attempt: number, + options: ReconnectDelayOptions, + random: () => number = Math.random, +): number { + const ceiling = Math.min(options.baseDelayMs * 2 ** attempt, options.maxDelayMs); + return Math.round(ceiling / 2 + random() * (ceiling / 2)); +} diff --git a/assets/store-screenshots/demo/preview-deploys/index.client.tsx b/assets/store-screenshots/demo/preview-deploys/index.client.tsx new file mode 100644 index 0000000000..72ab9a709a --- /dev/null +++ b/assets/store-screenshots/demo/preview-deploys/index.client.tsx @@ -0,0 +1,204 @@ +// The plugin the demo agent "builds" in the store screenshots: a Deploys pill on +// every composer that opens the latest preview deploy for each branch. The +// deploys are fixed sample data; the UI is a real plugin surface. +import type { + PluginButtonContentProps, + PluginButtonRegistration, + PluginClientContext, +} from "@getpaseo/plugin/client"; +import { useMemo } from "react"; +import { Text, View } from "react-native"; + +type DeployStatus = "ready" | "building" | "failed"; + +interface Deploy { + branch: string; + status: DeployStatus; + detail: string; + age: string; + progress?: number; +} + +const DEPLOYS: Deploy[] = [ + { branch: "fix/reconnect-jitter", status: "ready", detail: "Built in 48s", age: "2m" }, + { + branch: "perf/provider-snapshot-cache", + status: "building", + detail: "Bundling app", + age: "now", + progress: 0.64, + }, + { branch: "feat/remember-terminal", status: "ready", detail: "Built in 51s", age: "18m" }, + { + branch: "i18n/ko-settings", + status: "failed", + detail: "Missing key settings.notifications", + age: "26m", + }, +]; + +function DeploysSheet({ theme, layout }: PluginButtonContentProps) { + const mono = layout.platform === "ios" ? "Menlo" : "monospace"; + const styles = useMemo( + () => ({ + // Popovers on tablets and desktop are narrow by default; give the + // branch names room. Phones show the sheet at full width. + body: { gap: 14, width: layout.compact ? undefined : 400 }, + production: { + padding: 14, + gap: 6, + borderRadius: 12, + backgroundColor: theme.colors.surface2, + }, + productionTop: { flexDirection: "row" as const, alignItems: "center" as const, gap: 8 }, + label: { color: theme.colors.foregroundMuted, fontSize: 13 }, + version: { color: theme.colors.foreground, fontSize: 22, fontWeight: "600" as const }, + live: { color: theme.colors.statusSuccess, fontSize: 13, fontWeight: "600" as const }, + heading: { color: theme.colors.foregroundMuted, fontSize: 13, marginTop: 4 }, + list: { + borderRadius: 12, + borderWidth: 1, + borderColor: theme.colors.border, + overflow: "hidden" as const, + }, + row: { + flexDirection: "row" as const, + alignItems: "center" as const, + gap: 12, + paddingVertical: 12, + paddingHorizontal: 14, + }, + divider: { height: 1, backgroundColor: theme.colors.border }, + text: { flex: 1, gap: 4 }, + branch: { color: theme.colors.foreground, fontSize: 14, fontFamily: mono }, + detail: { color: theme.colors.foregroundMuted, fontSize: 13 }, + failed: { color: theme.colors.statusDanger, fontSize: 13 }, + age: { color: theme.colors.foregroundMuted, fontSize: 13 }, + track: { + height: 4, + marginTop: 4, + borderRadius: 2, + backgroundColor: theme.colors.surface2, + overflow: "hidden" as const, + }, + }), + [theme, mono, layout.compact], + ); + const dotColor: Record = { + ready: theme.colors.statusSuccess, + building: theme.colors.statusWarning, + failed: theme.colors.statusDanger, + }; + + return ( + + + + + Live + Production · main + + v0.14.0-beta.1 + Deployed 3h ago + + Previews + + {DEPLOYS.map((deploy, index) => ( + + {index > 0 ? : null} + + + + + {deploy.branch} + + + {deploy.detail} + + {deploy.progress !== undefined ? ( + + ) : null} + + {deploy.age} + + + ))} + + + ); +} + +function Progress({ value, track, color }: { value: number; track: object; color: string }) { + const fill = useMemo( + () => ({ width: `${value * 100}%` as const, height: 4, backgroundColor: color }), + [value, color], + ); + return ( + + + + ); +} + +function Dot({ color }: { color: string }) { + const style = useMemo( + () => ({ width: 8, height: 8, borderRadius: 4, backgroundColor: color }), + [color], + ); + return ; +} + +export default function contribute(client: PluginClientContext) { + const pills = new Map(); + const lifetime = new AbortController(); + const register = (agent: { id: string; workspaceId?: string | null }) => { + if (lifetime.signal.aborted || !agent.workspaceId) return; + pills.get(agent.id)?.remove(); + pills.set( + agent.id, + client.addComposerPill({ + id: "deploys", + workspaceId: agent.workspaceId, + agentId: agent.id, + button: { + title: "Preview deploys", + icon: "Rocket", + label: "Deploys", + behavior: { kind: "popover", Content: DeploysSheet }, + }, + }), + ); + }; + void client.paseo.agents + .list({ subscribe: {}, signal: lifetime.signal }) + .then(({ subscription }) => { + subscription.subscribe({ + snapshot: ({ entries }) => { + for (const pill of pills.values()) pill.remove(); + pills.clear(); + for (const { agent } of entries) register(agent); + }, + update: (message) => { + if (message.type !== "agent_update") return; + const update = message.payload; + if (update.kind === "remove") { + pills.get(update.agentId)?.remove(); + pills.delete(update.agentId); + } else register(update.agent); + }, + }); + return undefined; + }) + .catch((error) => { + if (!lifetime.signal.aborted) console.error("Agent observation failed", error); + }); + return () => { + lifetime.abort(); + for (const pill of pills.values()) pill.remove(); + pills.clear(); + }; +} diff --git a/assets/store-screenshots/demo/preview-deploys/paseo-plugin.json b/assets/store-screenshots/demo/preview-deploys/paseo-plugin.json new file mode 100644 index 0000000000..0da849e8f7 --- /dev/null +++ b/assets/store-screenshots/demo/preview-deploys/paseo-plugin.json @@ -0,0 +1,4 @@ +{ + "id": "preview-deploys", + "requirements": { "paseo": ">=0.8.0" } +} diff --git a/assets/store-screenshots/demo/scripted-agents.mts b/assets/store-screenshots/demo/scripted-agents.mts new file mode 100644 index 0000000000..603017f323 --- /dev/null +++ b/assets/store-screenshots/demo/scripted-agents.mts @@ -0,0 +1,281 @@ +// Scripted Claude Code and Codex clients for staging store screenshots. +// Each agent replays a fixed conversation through the real daemon, so the app +// renders real timeline rows, permission prompts, and running states. +import { randomUUID } from "node:crypto"; +import type { + AgentCapabilityFlags, + AgentClient, + AgentMode, + AgentModelDefinition, + AgentPermissionRequest, + AgentPermissionResponse, + AgentPersistenceHandle, + AgentPromptInput, + AgentRunResult, + AgentSession, + AgentSessionConfig, + AgentStreamEvent, + AgentTimelineItem, + ToolCallDetail, +} from "../../../packages/server/src/server/agent/agent-sdk-types.js"; +import { getAgentProviderDefinition } from "@getpaseo/protocol/provider-manifest"; + +export type ScriptStep = + | { kind: "say"; text: string } + | { kind: "think"; text: string } + | { kind: "tool"; name: string; detail: ToolCallDetail } + | { kind: "todo"; items: { text: string; completed: boolean }[] } + | { kind: "wait"; ms: number } + | { kind: "running-tool"; name: string; detail: ToolCallDetail } + | { kind: "ask"; name: string; title: string; detail: ToolCallDetail }; + +export interface AgentScript { + /** Matched against the start of the prompt that opens the turn. */ + prompt: string; + steps: ScriptStep[]; + /** Leave the turn open after the last step. */ + keepRunning?: boolean; + /** Pause between steps, so "Worked for" reflects a believable duration. */ + stepDelayMs?: number; +} + +const CAPABILITIES: AgentCapabilityFlags = { + supportsStreaming: true, + supportsSessionPersistence: true, + supportsDynamicModes: false, + supportsMcpServers: false, + supportsReasoningStream: true, + supportsToolInvocations: true, + supportsRewindConversation: false, + supportsRewindFiles: false, + supportsRewindBoth: false, +}; + +const MODELS: Record = { + claude: [ + { + provider: "claude", + id: "claude-opus-5-5", + label: "Opus 5.5", + isDefault: true, + thinkingOptions: [ + { id: "medium", label: "Medium", isDefault: true }, + { id: "high", label: "High" }, + ], + defaultThinkingOptionId: "medium", + }, + { provider: "claude", id: "claude-sonnet-5-5", label: "Sonnet 5.5" }, + ], + codex: [ + { + provider: "codex", + id: "gpt-5.6-sol", + label: "GPT-5.6-Sol", + isDefault: true, + thinkingOptions: [ + { id: "medium", label: "Medium", isDefault: true }, + { id: "high", label: "High" }, + ], + defaultThinkingOptionId: "medium", + }, + ], +}; + +function promptText(prompt: AgentPromptInput): string { + if (typeof prompt === "string") return prompt; + return prompt + .map((block) => ("text" in block && typeof block.text === "string" ? block.text : "")) + .join(""); +} + +class ScriptedSession implements AgentSession { + readonly capabilities = CAPABILITIES; + readonly id = randomUUID(); + private readonly listeners = new Set<(event: AgentStreamEvent) => void>(); + private readonly history: AgentStreamEvent[] = []; + private pending: AgentPermissionRequest[] = []; + private activeTurnId: string | null = null; + + constructor( + readonly provider: string, + private readonly config: AgentSessionConfig, + private readonly scripts: AgentScript[], + ) {} + + private emit(event: AgentStreamEvent): void { + const tagged = this.activeTurnId ? { ...event, turnId: this.activeTurnId } : event; + this.history.push(tagged); + for (const listener of this.listeners) listener(tagged); + } + + private timeline(item: AgentTimelineItem): void { + this.emit({ type: "timeline", provider: this.provider, item }); + } + + async run(): Promise { + return { sessionId: this.id, finalText: "", timeline: [] }; + } + + async startTurn(prompt: AgentPromptInput): Promise<{ turnId: string }> { + const turnId = randomUUID(); + this.activeTurnId = turnId; + const text = promptText(prompt); + const script = this.scripts.find((candidate) => text.startsWith(candidate.prompt)); + setTimeout(() => void this.play(text, script), 50); + return { turnId }; + } + + private async play(text: string, script: AgentScript | undefined): Promise { + this.emit({ type: "turn_started", provider: this.provider }); + this.timeline({ type: "user_message", text, messageId: randomUUID() }); + const delay = script?.stepDelayMs ?? 400; + for (const step of script?.steps ?? [{ kind: "say", text: "Done." } as const]) { + await new Promise((resolve) => setTimeout(resolve, step.kind === "wait" ? step.ms : delay)); + this.playStep(step); + if (step.kind === "ask") return; + } + if (script?.keepRunning) return; + this.emit({ + type: "turn_completed", + provider: this.provider, + usage: { inputTokens: 48_210, outputTokens: 3_904 }, + }); + this.activeTurnId = null; + } + + private playStep(step: ScriptStep): void { + switch (step.kind) { + case "say": + this.timeline({ type: "assistant_message", text: step.text, messageId: randomUUID() }); + return; + case "think": + this.timeline({ type: "reasoning", text: step.text }); + return; + case "todo": + this.timeline({ type: "todo", items: step.items }); + return; + case "wait": + return; + case "tool": + case "running-tool": { + const callId = randomUUID(); + this.timeline({ + type: "tool_call", + callId, + name: step.name, + status: "running", + error: null, + detail: step.detail, + }); + if (step.kind === "tool") { + this.timeline({ + type: "tool_call", + callId, + name: step.name, + status: "completed", + error: null, + detail: step.detail, + }); + } + return; + } + case "ask": { + const request: AgentPermissionRequest = { + id: randomUUID(), + provider: this.provider, + name: step.name, + kind: "tool", + title: step.title, + detail: step.detail, + }; + this.pending = [request]; + this.emit({ type: "permission_requested", provider: this.provider, request }); + } + } + } + + subscribe(callback: (event: AgentStreamEvent) => void): () => void { + this.listeners.add(callback); + return () => this.listeners.delete(callback); + } + + async *streamHistory(): AsyncGenerator { + yield* this.history; + } + + async getRuntimeInfo() { + return { + provider: this.provider, + sessionId: this.id, + model: this.config.model ?? MODELS[this.provider]?.[0]?.id ?? null, + thinkingOptionId: this.config.thinkingOptionId ?? "medium", + modeId: this.config.modeId ?? null, + }; + } + + async getAvailableModes(): Promise { + return getAgentProviderDefinition(this.provider).modes; + } + + async getCurrentMode(): Promise { + return this.config.modeId ?? null; + } + + async setMode(): Promise {} + + getPendingPermissions(): AgentPermissionRequest[] { + return this.pending; + } + + async respondToPermission(requestId: string, resolution: AgentPermissionResponse) { + this.pending = []; + this.emit({ type: "permission_resolved", provider: this.provider, requestId, resolution }); + } + + describePersistence(): AgentPersistenceHandle { + return { provider: this.provider, sessionId: this.id }; + } + + async interrupt(): Promise { + if (!this.activeTurnId) return; + this.emit({ type: "turn_canceled", provider: this.provider, reason: "Interrupted" }); + this.activeTurnId = null; + } + + async close(): Promise {} +} + +export class ScriptedAgentClient implements AgentClient { + readonly capabilities = CAPABILITIES; + + constructor( + readonly provider: string, + private readonly scripts: AgentScript[], + ) {} + + async createSession(config: AgentSessionConfig): Promise { + return new ScriptedSession(this.provider, config, this.scripts); + } + + async resumeSession( + _handle: AgentPersistenceHandle, + overrides?: Partial, + ): Promise { + return new ScriptedSession( + this.provider, + { provider: this.provider, cwd: overrides?.cwd ?? process.cwd(), ...overrides }, + this.scripts, + ); + } + + async fetchCatalog() { + return { + models: MODELS[this.provider] ?? [], + modes: getAgentProviderDefinition(this.provider).modes, + }; + } + + async isAvailable(): Promise { + return true; + } +} diff --git a/assets/store-screenshots/demo/stage.mts b/assets/store-screenshots/demo/stage.mts new file mode 100644 index 0000000000..3c6a3cadf0 --- /dev/null +++ b/assets/store-screenshots/demo/stage.mts @@ -0,0 +1,556 @@ +// Stages the demo host used for store screenshots. +// +// npx tsx assets/store-screenshots/demo/stage.mts +// +// Starts an in-process daemon on DEMO_PORT (default 7791) with scripted Claude +// Code and Codex clients, adds a local clone of this repository as the `paseo` +// project, cuts real worktrees, applies a real change to the hero worktree, and +// opens a terminal there. Leave it running while you capture. +import { execFileSync, execSync } from "node:child_process"; +import { existsSync } from "node:fs"; +import { mkdir, readFile, rm, symlink, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { createTestPaseoDaemon } from "../../../packages/server/src/server/test-utils/paseo-daemon.js"; +import { DaemonClient } from "../../../packages/server/src/server/test-utils/daemon-client.js"; +import { type AgentScript, ScriptedAgentClient } from "./scripted-agents.mjs"; + +const here = path.dirname(fileURLToPath(import.meta.url)); +const repoRoot = path.resolve(here, "../../.."); +const demoRoot = path.join(repoRoot, ".dev/store-capture/demo"); +const codeRoot = path.join(demoRoot, "code"); +const pluginDir = path.join(here, "preview-deploys"); +const port = Number(process.env.DEMO_PORT ?? 7791); +const minute = 60_000; + +const claudeScripts: AgentScript[] = []; +const codexScripts: AgentScript[] = []; + +function git(cwd: string, ...args: string[]): string { + return execFileSync("git", ["-c", "user.name=Mo", "-c", "user.email=mo@paseo.sh", ...args], { + cwd, + encoding: "utf8", + }); +} + +function run(cwd: string, command: string): string { + return execSync(command, { cwd, encoding: "utf8", env: { ...process.env, FORCE_COLOR: "0" } }); +} + +async function prepareRepos(): Promise { + // A fresh clone each run: worktrees from an earlier run stay registered in it. + // Worktree setup (npm ci, builds) is dropped so new worktrees open instantly. + const paseo = path.join(codeRoot, "paseo"); + await rm(paseo, { recursive: true, force: true }); + await mkdir(codeRoot, { recursive: true }); + execFileSync("git", ["clone", "-q", "--local", repoRoot, paseo]); + git(paseo, "checkout", "-q", "-B", "main"); + git(paseo, "remote", "remove", "origin"); + const config = JSON.parse(await readFile(path.join(paseo, "paseo.json"), "utf8")); + delete config.worktree; + await writeFile(path.join(paseo, "paseo.json"), `${JSON.stringify(config, null, 2)}\n`); + git(paseo, "commit", "-qam", "chore: skip worktree setup in demo"); + const dotfiles = path.join(codeRoot, "dotfiles"); + if (!existsSync(dotfiles)) { + await mkdir(dotfiles, { recursive: true }); + await writeFile(path.join(dotfiles, "tmux.conf"), "set -g mouse on\nset -g base-index 1\n"); + await writeFile(path.join(dotfiles, "zshrc"), "export EDITOR=nvim\nalias g=git\n"); + git(dotfiles, "init", "-q", "-b", "main"); + git(dotfiles, "add", "."); + git(dotfiles, "commit", "-qm", "Initial dotfiles"); + } +} + +async function main(): Promise { + await prepareRepos(); + const home = path.join(demoRoot, "home"); + await rm(home, { recursive: true, force: true }); + await mkdir(home, { recursive: true }); + + const daemon = await createTestPaseoDaemon({ + agentClients: { + claude: new ScriptedAgentClient("claude", claudeScripts), + codex: new ScriptedAgentClient("codex", codexScripts), + }, + listen: "127.0.0.1", + listenPort: port, + paseoHomeRoot: home, + mcpEnabled: false, + cleanup: false, + pluginsEnabled: true, + plugins: { + "preview-deploys": { source: "directory", path: pluginDir, enabled: true }, + }, + }); + const client = new DaemonClient({ + url: `ws://127.0.0.1:${daemon.port}/ws`, + appVersion: "0.14.0", + }); + await client.connect(); + await client.fetchAgents({ subscribe: {} }); + + const paseo = await client.addProject(path.join(codeRoot, "paseo")); + const dotfiles = await client.addProject(path.join(codeRoot, "dotfiles")); + const paseoProjectId = paseo.project!.projectId; + + async function worktree(title: string, branchName: string) { + const result = await client.createWorkspace({ + title, + source: { + kind: "worktree", + projectId: paseoProjectId, + action: "branch-off", + baseBranch: "main", + branchName, + }, + }); + if (!result.workspace) throw new Error(`No workspace for ${title}: ${JSON.stringify(result)}`); + return result.workspace; + } + + async function agent(input: { + provider: "claude" | "codex"; + workspace: { id: string; workspaceDirectory?: string | null }; + cwd: string; + title: string; + script: AgentScript; + }) { + (input.provider === "claude" ? claudeScripts : codexScripts).push(input.script); + return client.createAgent({ + provider: input.provider, + cwd: input.cwd, + workspaceId: input.workspace.id, + title: input.title, + initialPrompt: input.script.prompt, + }); + } + + const pause = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); + + // Done: finished earlier and already read. + const release = await worktree("Release v0.14.0-beta.1", "release/0.14.0-beta.1"); + const releaseAgent = await agent({ + provider: "codex", + workspace: release, + cwd: release.workspaceDirectory!, + title: "Release v0.14.0-beta.1", + script: { + prompt: "Cut 0.14.0-beta.1 from main and draft the release notes.", + steps: [ + { + kind: "tool", + name: "shell", + detail: { + type: "shell", + command: "npm run release:beta", + output: "Tagged v0.14.0-beta.1\n", + exitCode: 0, + }, + }, + { + kind: "say", + text: "Tagged `v0.14.0-beta.1` and drafted the release notes. CI is building the desktop and mobile artifacts.", + }, + ], + }, + }); + const dotfilesWorkspace = ( + await client.createWorkspace({ + title: "Add a tmux status line", + source: { + kind: "directory", + path: path.join(codeRoot, "dotfiles"), + projectId: dotfiles.project!.projectId, + }, + }) + ).workspace!; + const tmuxAgent = await agent({ + provider: "claude", + workspace: dotfilesWorkspace, + cwd: path.join(codeRoot, "dotfiles"), + title: "Add a tmux status line", + script: { + prompt: "Add a minimal tmux status line with the session name and battery.", + steps: [ + { + kind: "tool", + name: "Edit", + detail: { + type: "edit", + filePath: "tmux.conf", + oldString: "", + newString: "set -g status-right '#S · #{battery_percentage}'", + }, + }, + { + kind: "say", + text: "Added a status line with the session name on the left and battery on the right.", + }, + ], + }, + }); + await pause(3000); + await client.clearAgentAttention([releaseAgent.id, tmuxAgent.id]); + + // Working: turns that stay open while you capture. + const ipad = await worktree( + "Keep the composer above the iPad keyboard", + "fix/ipad-keyboard-inset", + ); + await agent({ + provider: "codex", + workspace: ipad, + cwd: ipad.workspaceDirectory!, + title: "Keep the composer above the iPad keyboard", + script: { + prompt: + "On iPad with a hardware keyboard attached, the composer jumps up as if the software keyboard were open. Find out why and fix it.", + keepRunning: true, + steps: [ + { + kind: "tool", + name: "shell", + detail: { + type: "shell", + command: 'rg -n "keyboardHeight" packages/app/src', + output: + "packages/app/src/keyboard/shift/internal/provider.ts:41: const keyboardHeight = useSharedValue(0);\n", + exitCode: 0, + }, + }, + { + kind: "tool", + name: "read", + detail: { + type: "read", + filePath: "packages/app/src/keyboard/shift/internal/provider.ts", + }, + }, + { + kind: "say", + text: "The shift provider trusts the keyboard frame event. With a hardware keyboard, iPadOS still reports the shortcuts bar as a keyboard frame, so we lift the composer by its full height. Checking the frame against the screen bottom next.", + }, + { + kind: "running-tool", + name: "shell", + detail: { type: "shell", command: "npx vitest run packages/app/src/keyboard" }, + }, + ], + }, + }); + const snapshots = await worktree( + "Cache provider snapshots on disk", + "perf/provider-snapshot-cache", + ); + await agent({ + provider: "claude", + workspace: snapshots, + cwd: snapshots.workspaceDirectory!, + title: "Cache provider snapshots on disk", + script: { + prompt: + "Cold start spends about two seconds probing providers. Cache the last provider snapshot on disk and refresh it in the background.", + keepRunning: true, + steps: [ + { + kind: "todo", + items: [ + { text: "Find where snapshots are built", completed: true }, + { text: "Persist the last snapshot per host", completed: false }, + { text: "Refresh in the background after boot", completed: false }, + ], + }, + { + kind: "tool", + name: "Read", + detail: { + type: "read", + filePath: "packages/server/src/server/agent/provider-snapshot-manager.ts", + }, + }, + { + kind: "running-tool", + name: "Edit", + detail: { + type: "edit", + filePath: "packages/server/src/server/agent/provider-snapshot-manager.ts", + }, + }, + ], + }, + }); + + // Needs input: waiting on a permission. + const korean = await worktree("Korean translations for Settings", "i18n/ko-settings"); + await agent({ + provider: "claude", + workspace: korean, + cwd: korean.workspaceDirectory!, + title: "Korean translations for Settings", + script: { + prompt: "Translate the new Settings strings into Korean and open a PR.", + steps: [ + { + kind: "tool", + name: "Read", + detail: { type: "read", filePath: "packages/app/src/i18n/resources/en.ts" }, + }, + { + kind: "tool", + name: "Edit", + detail: { type: "edit", filePath: "packages/app/src/i18n/resources/ko.ts" }, + }, + { + kind: "tool", + name: "Bash", + detail: { + type: "shell", + command: "npm run test --workspace=@getpaseo/app -- i18n", + output: "Test Files 3 passed (3)\n Tests 41 passed (41)\n", + exitCode: 0, + }, + }, + { kind: "say", text: "Translated 18 strings. I'll push the branch so I can open the PR." }, + { + kind: "ask", + name: "Bash", + title: "Bash", + detail: { type: "shell", command: "git push -u origin i18n/ko-settings" }, + }, + ], + }, + }); + + // Ready to review: a second finished agent. + const terminals = await worktree( + "Remember the last terminal per workspace", + "feat/remember-terminal", + ); + await agent({ + provider: "codex", + workspace: terminals, + cwd: terminals.workspaceDirectory!, + title: "Remember the last terminal per workspace", + script: { + prompt: + "When I switch back to a workspace, open the terminal I was using last instead of the first one.", + steps: [ + { + kind: "tool", + name: "shell", + detail: { + type: "shell", + command: 'rg -n "activeTerminalId" packages/app/src', + output: "", + exitCode: 0, + }, + }, + { + kind: "say", + text: "Workspaces now remember their last focused terminal and reopen it when you switch back. The choice is stored per host, so it survives restarts.", + }, + ], + }, + }); + + // Plugin: the agent "built" the preview-deploys plugin this daemon runs. + const plugin = await worktree("Build a preview deploys plugin", "plugins/preview-deploys"); + const pluginSource = (file: string) => run(pluginDir, `cat ${file}`); + await agent({ + provider: "claude", + workspace: plugin, + cwd: plugin.workspaceDirectory!, + title: "Build a preview deploys plugin", + script: { + prompt: "Build me a plugin that shows our preview deploys right next to the composer.", + stepDelayMs: 6_000, + steps: [ + { kind: "tool", name: "Read", detail: { type: "read", filePath: "docs/plugins.md" } }, + { + kind: "tool", + name: "Write", + detail: { + type: "write", + filePath: "plugins/preview-deploys/paseo-plugin.json", + content: pluginSource("paseo-plugin.json"), + }, + }, + { + kind: "tool", + name: "Write", + detail: { + type: "write", + filePath: "plugins/preview-deploys/index.client.tsx", + content: pluginSource("index.client.tsx"), + }, + }, + { + kind: "tool", + name: "Bash", + detail: { + type: "shell", + command: "paseo plugin install ./plugins/preview-deploys", + output: "Installed preview-deploys\n", + exitCode: 0, + }, + }, + { + kind: "say", + text: "Done. **Deploys** now sits above the composer in every workspace. Tap it to see production and the latest preview for each branch, with build progress and failures.", + }, + ], + }, + }); + + // Hero: Claude finished a real change in a real worktree. + const jitter = await worktree("Add jitter to reconnect backoff", "fix/reconnect-jitter"); + const cwd = jitter.workspaceDirectory!; + await symlink(path.join(repoRoot, "node_modules"), path.join(cwd, "node_modules")); + execFileSync("node", [path.join(here, "change/apply.mjs"), cwd]); + const clientDiff = git(cwd, "diff", "--", "packages/client/src/daemon-client.ts"); + const vitest = run( + cwd, + "npx vitest run packages/client/src/connection/reconnect-delay.test.ts", + ).replace(/^ RUN .*\n/m, ""); + const readExcerpt = run(cwd, "sed -n '7067,7086p' packages/client/src/daemon-client.ts"); + await agent({ + provider: "claude", + workspace: jitter, + cwd, + title: "Add jitter to reconnect backoff", + script: { + prompt: + 'When the relay restarts, every phone reconnects at the same moment and we get a spike. Add jitter to the reconnect backoff, keep the 30s cap, and make sure the "Retrying in" countdown still matches the real delay.', + stepDelayMs: 7_000, + steps: [ + { + kind: "tool", + name: "Grep", + detail: { + type: "search", + toolName: "grep", + query: "reconnectAttempt", + filePaths: ["packages/client/src/daemon-client.ts"], + numFiles: 1, + numMatches: 9, + mode: "files_with_matches", + }, + }, + { + kind: "tool", + name: "Read", + detail: { + type: "read", + filePath: "packages/client/src/daemon-client.ts", + offset: 7040, + limit: 60, + content: readExcerpt, + }, + }, + { + kind: "say", + text: "The delay is calculated twice: once for `nextRetryAt`, which drives the countdown, and again when the timer is armed. Both use plain doubling, so every client retries on the same schedule. If I add randomness in both places the countdown will be wrong, so I'll draw the jitter once per attempt and share it.", + }, + { + kind: "tool", + name: "Write", + detail: { + type: "write", + filePath: "packages/client/src/connection/reconnect-delay.ts", + content: run(cwd, "cat packages/client/src/connection/reconnect-delay.ts"), + }, + }, + { + kind: "tool", + name: "Edit", + detail: { + type: "edit", + filePath: "packages/client/src/daemon-client.ts", + unifiedDiff: clientDiff, + }, + }, + { + kind: "tool", + name: "Write", + detail: { + type: "write", + filePath: "packages/client/src/connection/reconnect-delay.test.ts", + content: run(cwd, "cat packages/client/src/connection/reconnect-delay.test.ts"), + }, + }, + { + kind: "tool", + name: "Bash", + detail: { + type: "shell", + command: "npx vitest run packages/client/src/connection/reconnect-delay.test.ts", + output: vitest, + exitCode: 0, + }, + }, + { + kind: "tool", + name: "Edit", + detail: { + type: "edit", + filePath: "CHANGELOG.md", + unifiedDiff: git(cwd, "diff", "--", "CHANGELOG.md"), + }, + }, + { + kind: "say", + text: [ + "Reconnects now back off with jitter.", + "", + "- `getReconnectDelayMs` picks a delay between half and the full backoff, still capped at 30s.", + '- `DaemonClient` draws the delay once per attempt, so the "Retrying in" countdown matches the actual retry.', + "- Four new tests cover the doubling, the cap, the jitter range, and a quick first retry.", + "", + "Tests pass. After a relay restart, clients now spread their reconnects across the backoff window instead of arriving together.", + ].join("\n"), + }, + ], + }, + }); + + const terminal = await client.createTerminal(cwd, "zsh", undefined, { + workspaceId: jitter.id, + command: "bash", + args: ["--rcfile", path.join(here, "terminal-rc.sh"), "-i"], + }); + const terminalId = terminal.terminal?.id; + if (terminalId) { + await pause(1500); + for (const line of [ + "git status --short", + "cd packages/client", + "npx vitest run reconnect --reporter=tree", + ]) { + client.sendTerminalInput(terminalId, { type: "input", data: `${line}\r` }); + await pause(4000); + } + } + + console.log(`READY port=${daemon.port} home=${daemon.paseoHome}`); + await writeFile( + path.join(demoRoot, "state.json"), + JSON.stringify( + { port: daemon.port, home: daemon.paseoHome, hero: { workspaceId: jitter.id, cwd } }, + null, + 2, + ), + ); + const stop = async () => { + await client.close(); + await daemon.close(); + process.exit(0); + }; + process.on("SIGTERM", stop); + process.on("SIGINT", stop); + void minute; +} + +main().catch((error) => { + console.error(error); + process.exit(1); +}); diff --git a/assets/store-screenshots/demo/terminal-rc.sh b/assets/store-screenshots/demo/terminal-rc.sh new file mode 100644 index 0000000000..ab33d79466 --- /dev/null +++ b/assets/store-screenshots/demo/terminal-rc.sh @@ -0,0 +1,19 @@ +# Shell profile for the demo terminal: a Pure-style two-line prompt that fits a +# phone-width terminal, and vitest output without the absolute checkout path +# or the long timing breakdown. Vitest drops its colors when piped, so the +# wrapper puts its usual green checks and grey timings back. +export FORCE_COLOR=1 +__where() { local top; top=$(git rev-parse --show-toplevel 2>/dev/null); printf '~/paseo%s' "${PWD#"$top"}"; } +__branch() { git branch --show-current 2>/dev/null; } +__dirty() { [ -n "$(git status --porcelain 2>/dev/null)" ] && printf '*'; } +PROMPT_COMMAND='printf "\e]0;zsh\a"' +PS1='\n\[\e[34m\]$(__where)\[\e[0m\] \[\e[90m\]$(__branch)$(__dirty)\[\e[0m\]\n\[\e[35m\]❯\[\e[0m\] ' +npx() { + command npx "$@" 2>&1 | sed -E \ + -e '1{/^$/d}' -e '/ RUN /d' -e '/Start at/d' -e 's/ \(transform.*\)//' \ + -e $'s/✓/\e[32m✓\e[0m/' \ + -e $'s/ ([0-9]+ms)$/ \e[90m\\1\e[0m/' \ + -e $'s/ (\\([0-9]+( tests)?\\))/ \e[90m\\1\e[0m/' \ + -e $'s/([0-9]+ passed)/\e[1;32m\\1\e[0m/' +} +clear diff --git a/assets/store-screenshots/output/apple-ipad/01-sidebar.png b/assets/store-screenshots/output/apple-ipad/01-sidebar.png new file mode 100644 index 0000000000..03f1d8ed61 Binary files /dev/null and b/assets/store-screenshots/output/apple-ipad/01-sidebar.png differ diff --git a/assets/store-screenshots/output/apple-ipad/02-chat.png b/assets/store-screenshots/output/apple-ipad/02-chat.png new file mode 100644 index 0000000000..1c56073112 Binary files /dev/null and b/assets/store-screenshots/output/apple-ipad/02-chat.png differ diff --git a/assets/store-screenshots/output/apple-ipad/03-plugins.png b/assets/store-screenshots/output/apple-ipad/03-plugins.png new file mode 100644 index 0000000000..87063634d3 Binary files /dev/null and b/assets/store-screenshots/output/apple-ipad/03-plugins.png differ diff --git a/assets/store-screenshots/output/apple-ipad/04-review.png b/assets/store-screenshots/output/apple-ipad/04-review.png new file mode 100644 index 0000000000..80e8cf8a52 Binary files /dev/null and b/assets/store-screenshots/output/apple-ipad/04-review.png differ diff --git a/assets/store-screenshots/output/apple-ipad/05-terminal.png b/assets/store-screenshots/output/apple-ipad/05-terminal.png new file mode 100644 index 0000000000..01b8d93c2a Binary files /dev/null and b/assets/store-screenshots/output/apple-ipad/05-terminal.png differ diff --git a/assets/store-screenshots/output/apple/01-sidebar.png b/assets/store-screenshots/output/apple/01-sidebar.png new file mode 100644 index 0000000000..f2a7ab849c Binary files /dev/null and b/assets/store-screenshots/output/apple/01-sidebar.png differ diff --git a/assets/store-screenshots/output/apple/02-chat.png b/assets/store-screenshots/output/apple/02-chat.png new file mode 100644 index 0000000000..b9afa6607d Binary files /dev/null and b/assets/store-screenshots/output/apple/02-chat.png differ diff --git a/assets/store-screenshots/output/apple/03-plugins.png b/assets/store-screenshots/output/apple/03-plugins.png new file mode 100644 index 0000000000..6f74f4ce53 Binary files /dev/null and b/assets/store-screenshots/output/apple/03-plugins.png differ diff --git a/assets/store-screenshots/output/apple/04-review.png b/assets/store-screenshots/output/apple/04-review.png new file mode 100644 index 0000000000..9b34d6cce0 Binary files /dev/null and b/assets/store-screenshots/output/apple/04-review.png differ diff --git a/assets/store-screenshots/output/apple/05-terminal.png b/assets/store-screenshots/output/apple/05-terminal.png new file mode 100644 index 0000000000..fae3170671 Binary files /dev/null and b/assets/store-screenshots/output/apple/05-terminal.png differ diff --git a/assets/store-screenshots/output/google-tablet/01-sidebar.png b/assets/store-screenshots/output/google-tablet/01-sidebar.png new file mode 100644 index 0000000000..8560682610 Binary files /dev/null and b/assets/store-screenshots/output/google-tablet/01-sidebar.png differ diff --git a/assets/store-screenshots/output/google-tablet/02-chat.png b/assets/store-screenshots/output/google-tablet/02-chat.png new file mode 100644 index 0000000000..a8f2342ab3 Binary files /dev/null and b/assets/store-screenshots/output/google-tablet/02-chat.png differ diff --git a/assets/store-screenshots/output/google-tablet/03-plugins.png b/assets/store-screenshots/output/google-tablet/03-plugins.png new file mode 100644 index 0000000000..3fe70263ca Binary files /dev/null and b/assets/store-screenshots/output/google-tablet/03-plugins.png differ diff --git a/assets/store-screenshots/output/google-tablet/04-review.png b/assets/store-screenshots/output/google-tablet/04-review.png new file mode 100644 index 0000000000..ae54bfa798 Binary files /dev/null and b/assets/store-screenshots/output/google-tablet/04-review.png differ diff --git a/assets/store-screenshots/output/google-tablet/05-terminal.png b/assets/store-screenshots/output/google-tablet/05-terminal.png new file mode 100644 index 0000000000..9921c839dd Binary files /dev/null and b/assets/store-screenshots/output/google-tablet/05-terminal.png differ diff --git a/assets/store-screenshots/output/google/01-sidebar.png b/assets/store-screenshots/output/google/01-sidebar.png new file mode 100644 index 0000000000..abed766b66 Binary files /dev/null and b/assets/store-screenshots/output/google/01-sidebar.png differ diff --git a/assets/store-screenshots/output/google/02-chat.png b/assets/store-screenshots/output/google/02-chat.png new file mode 100644 index 0000000000..bd42e5df49 Binary files /dev/null and b/assets/store-screenshots/output/google/02-chat.png differ diff --git a/assets/store-screenshots/output/google/03-plugins.png b/assets/store-screenshots/output/google/03-plugins.png new file mode 100644 index 0000000000..e26ecb407e Binary files /dev/null and b/assets/store-screenshots/output/google/03-plugins.png differ diff --git a/assets/store-screenshots/output/google/04-review.png b/assets/store-screenshots/output/google/04-review.png new file mode 100644 index 0000000000..38e9287c6a Binary files /dev/null and b/assets/store-screenshots/output/google/04-review.png differ diff --git a/assets/store-screenshots/output/google/05-terminal.png b/assets/store-screenshots/output/google/05-terminal.png new file mode 100644 index 0000000000..1445744fcb Binary files /dev/null and b/assets/store-screenshots/output/google/05-terminal.png differ diff --git a/assets/store-screenshots/raw/ipad/chat.png b/assets/store-screenshots/raw/ipad/chat.png new file mode 100644 index 0000000000..f8abc88b6c Binary files /dev/null and b/assets/store-screenshots/raw/ipad/chat.png differ diff --git a/assets/store-screenshots/raw/ipad/diff.png b/assets/store-screenshots/raw/ipad/diff.png new file mode 100644 index 0000000000..030946b7ae Binary files /dev/null and b/assets/store-screenshots/raw/ipad/diff.png differ diff --git a/assets/store-screenshots/raw/ipad/plugin-sheet.png b/assets/store-screenshots/raw/ipad/plugin-sheet.png new file mode 100644 index 0000000000..2550f0eecd Binary files /dev/null and b/assets/store-screenshots/raw/ipad/plugin-sheet.png differ diff --git a/assets/store-screenshots/raw/ipad/plugin.png b/assets/store-screenshots/raw/ipad/plugin.png new file mode 100644 index 0000000000..1fd3fbe2d8 Binary files /dev/null and b/assets/store-screenshots/raw/ipad/plugin.png differ diff --git a/assets/store-screenshots/raw/ipad/sidebar.png b/assets/store-screenshots/raw/ipad/sidebar.png new file mode 100644 index 0000000000..f348372425 Binary files /dev/null and b/assets/store-screenshots/raw/ipad/sidebar.png differ diff --git a/assets/store-screenshots/raw/ipad/terminal.png b/assets/store-screenshots/raw/ipad/terminal.png new file mode 100644 index 0000000000..3c65d7aabf Binary files /dev/null and b/assets/store-screenshots/raw/ipad/terminal.png differ diff --git a/assets/store-screenshots/raw/iphone/chat.png b/assets/store-screenshots/raw/iphone/chat.png new file mode 100644 index 0000000000..5ba23b3282 Binary files /dev/null and b/assets/store-screenshots/raw/iphone/chat.png differ diff --git a/assets/store-screenshots/raw/iphone/diff.png b/assets/store-screenshots/raw/iphone/diff.png new file mode 100644 index 0000000000..eab57a68d5 Binary files /dev/null and b/assets/store-screenshots/raw/iphone/diff.png differ diff --git a/assets/store-screenshots/raw/iphone/files.png b/assets/store-screenshots/raw/iphone/files.png new file mode 100644 index 0000000000..d2ebaf96b2 Binary files /dev/null and b/assets/store-screenshots/raw/iphone/files.png differ diff --git a/assets/store-screenshots/raw/iphone/plugin-sheet.png b/assets/store-screenshots/raw/iphone/plugin-sheet.png new file mode 100644 index 0000000000..012e3877ea Binary files /dev/null and b/assets/store-screenshots/raw/iphone/plugin-sheet.png differ diff --git a/assets/store-screenshots/raw/iphone/plugin.png b/assets/store-screenshots/raw/iphone/plugin.png new file mode 100644 index 0000000000..95beb12d67 Binary files /dev/null and b/assets/store-screenshots/raw/iphone/plugin.png differ diff --git a/assets/store-screenshots/raw/iphone/sidebar.png b/assets/store-screenshots/raw/iphone/sidebar.png new file mode 100644 index 0000000000..d0601f3f2f Binary files /dev/null and b/assets/store-screenshots/raw/iphone/sidebar.png differ diff --git a/assets/store-screenshots/raw/iphone/terminal.png b/assets/store-screenshots/raw/iphone/terminal.png new file mode 100644 index 0000000000..b96b192e17 Binary files /dev/null and b/assets/store-screenshots/raw/iphone/terminal.png differ diff --git a/assets/store-screenshots/render.mjs b/assets/store-screenshots/render.mjs new file mode 100644 index 0000000000..6695eac559 --- /dev/null +++ b/assets/store-screenshots/render.mjs @@ -0,0 +1,413 @@ +// Renders the App Store and Google Play screenshots from the native captures in +// raw/. Every image is resized with Lanczos to the exact pixel size it occupies +// on the canvas, and the page renders at device scale 1, so the browser never +// resamples a capture. +// +// node assets/store-screenshots/render.mjs +// +// SF Pro is not redistributable. On macOS it comes from /System/Library/Fonts; +// elsewhere point SF_FONT_DIR at a folder holding SFNS.ttf copied from a Mac. + +import { existsSync } from "node:fs"; +import { mkdir, mkdtemp, rm, symlink, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { build } from "esbuild"; +import { chromium } from "playwright"; +import { createElement } from "react"; +import { renderToStaticMarkup } from "react-dom/server"; +import sharp from "sharp"; + +const root = path.dirname(fileURLToPath(import.meta.url)); +const repo = path.resolve(root, "../.."); +const raw = (device, name) => path.join(root, "raw", device, `${name}.png`); +const output = path.join(root, "output"); +const androidImages = path.join(repo, "fastlane/metadata/android/en-US/images"); + +// Native captures per device: iPhone 16 Pro Max at 3x and iPad Pro 13-inch at +// 2x. The frame's screen radius and Dynamic Island are in capture pixels. +const DEVICES = { + iphone: { + capture: { width: 1320, height: 2868 }, + radius: 186, + bezel: 22, + island: { width: 378, height: 112, top: 33 }, + }, + ipad: { capture: { width: 2064, height: 2752 }, radius: 44, bezel: 30, island: null }, +}; + +// Every title wraps to two lines and every subline fits on one; the renderer +// fails otherwise, because the device is placed from that fixed text height. +// +// Each scene names its capture per device, and a device entry may override the +// title or subline where the copy depends on the form factor. +// +// A callout lifts a region of a capture out of the device. `crop` is in native +// capture pixels, `zoom` is its size relative to the device screen (capped to +// the canvas width), and the callout is centred on the spot the crop comes +// from, moved by `shift` native pixels down the screen. +const SCENES = [ + { + id: "sidebar", + backdrop: "agents", + title: "Run many coding agents at once", + body: "See which agents are working and which need you.", + iphone: { capture: "sidebar" }, + ipad: { capture: "sidebar" }, + }, + { + id: "chat", + title: "Your full dev environment on your phone", + body: "Start agents and follow every edit and command.", + iphone: { capture: "chat" }, + ipad: { capture: "chat", title: "Your full dev environment on your tablet" }, + }, + { + id: "plugins", + title: "Ask an agent to change the app itself", + body: "This Deploys sheet is a plugin an agent wrote.", + iphone: { + capture: "plugin", + callout: { from: "plugin-sheet", crop: [0, 1340, 1320, 1400], zoom: 1.04, shift: -1400 }, + }, + ipad: { + capture: "plugin", + body: "This Deploys panel is a plugin an agent wrote.", + callout: { from: "plugin-sheet", crop: [670, 1486, 844, 970], zoom: 1.3, shift: -900 }, + }, + }, + { + id: "review", + title: "Review the diff before you merge", + body: "Every file the agent changed, on its own branch.", + iphone: { + capture: "diff", + callout: { from: "files", crop: [0, 1060, 1320, 870], zoom: 1.26, shift: 110 }, + }, + ipad: { capture: "diff" }, + }, + { + id: "terminal", + title: "A real terminal in every workspace", + body: "Run the tests yourself, on your own machine.", + iphone: { + capture: "terminal", + callout: { from: "terminal", crop: [0, 950, 1320, 460], zoom: 1.35, shift: 110 }, + }, + ipad: { + capture: "terminal", + callout: { from: "terminal", crop: [596, 640, 1010, 412], zoom: 1.35, shift: 650 }, + }, + }, +]; + +// `textTop` is where the text starts when the device is sized by the canvas +// height. A canvas too narrow for that, like a tablet on 9:16, sizes the device +// by its width and centres the text and device instead. +const STORES = { + apple: { + device: "iphone", + width: 1320, + height: 2868, + textTop: 230, + titleSize: 100, + bodySize: 46, + textWidth: 1120, + }, + google: { + device: "iphone", + androidScreenshots: "phoneScreenshots", + width: 1440, + height: 2560, + textTop: 150, + titleSize: 96, + bodySize: 44, + textWidth: 1200, + }, + "apple-ipad": { + device: "ipad", + width: 2064, + height: 2752, + textTop: 200, + titleSize: 124, + bodySize: 56, + textWidth: 1400, + }, + "google-tablet": { + device: "ipad", + androidScreenshots: "tenInchScreenshots", + width: 1800, + height: 3200, + textTop: 200, + titleSize: 136, + bodySize: 60, + textWidth: 1560, + }, +}; + +const TITLE_LINE = 1.06; +const BODY_LINE = 1.3; +const BODY_GAP = 30; +// The device starts this far below the text and runs BLEED off the bottom. +const GAP = 140; +const BLEED = 40; +const MARGIN = 56; +const COLORS = { canvas: "#101615", title: "#ffffff", body: "rgba(255, 255, 255, 0.58)" }; + +function findFont() { + const dirs = [process.env.SF_FONT_DIR, "/System/Library/Fonts", "/Library/Fonts"].filter(Boolean); + for (const dir of dirs) { + const file = path.join(dir, "SFNS.ttf"); + if (existsSync(file)) return file; + } + throw new Error("SF Pro not found. Set SF_FONT_DIR to a folder containing SFNS.ttf from macOS."); +} + +// The device fills the canvas from GAP below the text to just past the bottom +// edge, so a taller canvas gets a larger device rather than a larger gap. When +// that would be wider than the canvas, the device takes the full width and the +// text and the whole device sit centred, still GAP apart. +function deviceLayout(store, device) { + const { capture, bezel } = device; + const textHeight = 2 * store.titleSize * TITLE_LINE + BODY_GAP + store.bodySize * BODY_LINE; + const tallest = store.height + BLEED - (store.textTop + textHeight + GAP) - 2 * bezel; + const widest = store.width - 2 * MARGIN - 2 * bezel; + const screenWidth = Math.min(Math.round((tallest * capture.width) / capture.height), widest); + const screenHeight = Math.round((screenWidth * capture.height) / capture.width); + const scale = screenWidth / capture.width; + const width = screenWidth + 2 * bezel; + const height = screenHeight + 2 * bezel; + const textTop = + screenWidth < widest + ? store.height + BLEED - height - GAP - textHeight + : (store.height - height - GAP - textHeight) / 2; + const island = device.island && { + width: Math.round(device.island.width * scale), + height: Math.round(device.island.height * scale), + top: Math.round(device.island.top * scale), + }; + return { + textTop: Math.round(textTop), + left: Math.round((store.width - width) / 2), + top: Math.round(textTop + textHeight + GAP), + width, + height, + bezel, + screenWidth, + screenHeight, + scale, + radius: Math.round(device.radius * scale), + island, + }; +} + +function calloutLayout(callout, frame, store) { + const [cropX, cropY, cropWidth, cropHeight] = callout.crop; + const scale = Math.min(frame.scale * callout.zoom, (store.width - 2 * MARGIN) / cropWidth); + const width = Math.round(cropWidth * scale); + const height = Math.round(cropHeight * scale); + const centreX = frame.left + frame.bezel + (cropX + cropWidth / 2) * frame.scale; + const centreY = frame.top + frame.bezel + (cropY + cropHeight / 2 + callout.shift) * frame.scale; + const clamp = (value, max) => Math.round(Math.min(Math.max(value, MARGIN), max - MARGIN)); + return { + width, + height, + left: clamp(centreX - width / 2, store.width - width), + top: clamp(centreY - height / 2, store.height - height), + }; +} + +async function resize(source, crop, width, height, file) { + let image = sharp(source); + if (crop) image = image.extract({ left: crop[0], top: crop[1], width: crop[2], height: crop[3] }); + await image.resize(width, height, { kernel: "lanczos3" }).png().toFile(file); + return pathToFileURL(file).href; +} + +// Agent marks scattered behind the first panel, from the homepage's featured +// agents. Each entry is [mark, centre x, centre y, size, rotation], with the +// centre as a fraction of the canvas and the size as a fraction of its width. +const AGENT_MARKS = [ + ["ClaudeCodeIcon", 0.11, 0.075, 0.12, -14], + ["CodexIcon", 0.89, 0.1, 0.13, 12], + ["PiIcon", 0.07, 0.34, 0.1, 10], + ["OmpIcon", 0.93, 0.37, 0.11, -10], + ["OpenCodeIcon", 0.08, 0.6, 0.11, -8], + ["CursorIcon", 0.92, 0.63, 0.1, 16], + ["MuseCodeIcon", 0.07, 0.85, 0.11, 14], + ["AntigravityIcon", 0.92, 0.88, 0.12, -12], +]; + +async function loadAgentMarks(work) { + const bundle = path.join(work, "agent-icons.mjs"); + await build({ + entryPoints: [path.join(repo, "packages/website/src/components/agent-icons.tsx")], + outfile: bundle, + bundle: true, + format: "esm", + platform: "node", + jsx: "automatic", + }); + const icons = await import(pathToFileURL(bundle).href); + return Object.fromEntries( + AGENT_MARKS.map(([name]) => [name, renderToStaticMarkup(createElement(icons[name]))]), + ); +} + +function backdrop(store, marks) { + return AGENT_MARKS.map(([name, x, y, size, rotation]) => { + const side = Math.round(size * store.width); + const left = Math.round(x * store.width - side / 2); + const top = Math.round(y * store.height - side / 2); + return `
${marks[name]}
`; + }).join(""); +} + +function page({ store, shot, frame, screen, callout, calloutImage, font, marks }) { + const behind = shot.backdrop === "agents" ? backdrop(store, marks) : ""; + const { island } = frame; + const notch = island + ? `
` + : ""; + const lifted = callout + ? `` + : ""; + return ` + + +${behind} +

${shot.title}

${shot.body}

+
${notch}
+${lifted}`; +} + +async function renderStore(browser, name, store, font, marks, work) { + const dir = path.join(output, name); + await mkdir(dir, { recursive: true }); + const view = await browser.newPage({ + viewport: { width: store.width, height: store.height }, + deviceScaleFactor: 1, + }); + const device = DEVICES[store.device]; + const frame = deviceLayout(store, device); + const files = []; + for (const [index, scene] of SCENES.entries()) { + const stem = `${name}-${scene.id}`; + const shot = { ...scene, ...scene[store.device] }; + const screen = await resize( + raw(store.device, shot.capture), + null, + frame.screenWidth, + frame.screenHeight, + path.join(work, `${stem}-screen.png`), + ); + const callout = shot.callout ? calloutLayout(shot.callout, frame, store) : null; + const calloutImage = callout + ? await resize( + raw(store.device, shot.callout.from), + shot.callout.crop, + callout.width, + callout.height, + path.join(work, `${stem}-callout.png`), + ) + : null; + const html = path.join(work, `${stem}.html`); + await writeFile(html, page({ store, shot, frame, screen, callout, calloutImage, font, marks })); + await view.goto(pathToFileURL(html).href); + await view.evaluate(async () => { + await document.fonts.ready; + await Promise.all(Array.from(document.images, (image) => image.decode())); + }); + await expectLines(view, "h1", 2, `${stem} title`); + await expectLines(view, "p", 1, `${stem} subline`); + const file = path.join(dir, `${String(index + 1).padStart(2, "0")}-${scene.id}.png`); + await sharp(await view.screenshot()) + .removeAlpha() + .png() + .toFile(file); + files.push(file); + console.log(path.relative(repo, file)); + } + await view.close(); + return files; +} + +async function expectLines(view, selector, expected, label) { + const lines = await view.$eval(selector, (element) => + Math.round(element.clientHeight / parseFloat(getComputedStyle(element).lineHeight)), + ); + if (lines !== expected) throw new Error(`${label} wraps to ${lines} lines, expected ${expected}`); +} + +// Google Play and F-Droid read their screenshots from the Android metadata, +// which holds links to these renders. Rewriting the links on every render keeps +// added, removed and renamed panels in step with the App Store. +async function linkAndroidScreenshots(folder, files) { + const dir = path.join(androidImages, folder); + await rm(dir, { recursive: true, force: true }); + await mkdir(dir, { recursive: true }); + for (const [index, file] of files.entries()) { + await symlink(path.relative(dir, file), path.join(dir, `${index + 1}.png`)); + } +} + +async function renderPreview(rows) { + const tile = 440; + const gap = 40; + const resized = []; + let top = gap; + let width = 0; + for (const files of rows) { + let left = gap; + let rowHeight = 0; + for (const file of files) { + const meta = await sharp(file).metadata(); + const height = Math.round((meta.height * tile) / meta.width); + const input = await sharp(file).resize(tile, height, { kernel: "lanczos3" }).toBuffer(); + resized.push({ input, left, top }); + left += tile + gap; + rowHeight = Math.max(rowHeight, height); + } + width = Math.max(width, left); + top += rowHeight + gap; + } + const file = path.join(output, "preview.png"); + await sharp({ create: { width, height: top, channels: 3, background: "#070a09" } }) + .composite(resized) + .png() + .toFile(file); + console.log(path.relative(repo, file)); +} + +const font = findFont(); +const work = await mkdtemp(path.join(os.tmpdir(), "paseo-store-")); +const browser = await chromium.launch({ headless: true }); +try { + const marks = await loadAgentMarks(work); + const rows = []; + for (const [name, store] of Object.entries(STORES)) { + const files = await renderStore(browser, name, store, font, marks, work); + if (store.androidScreenshots) await linkAndroidScreenshots(store.androidScreenshots, files); + rows.push(files); + } + await renderPreview(rows); +} finally { + await browser.close(); + await rm(work, { recursive: true, force: true }); +} diff --git a/docs/agent-lifecycle.md b/docs/agent-lifecycle.md index 719b0b5468..2c2ce29403 100644 --- a/docs/agent-lifecycle.md +++ b/docs/agent-lifecycle.md @@ -12,6 +12,26 @@ initializing → idle → running → idle (or error → closed) Each live agent in `AgentManager` carries a `lastStatus` of `initializing`, `idle`, `running`, or `error`. `closed` is the persisted, resumable state for an agent record that has no live provider runtime. State transitions persist to disk and stream to subscribed clients via WebSocket. +## Daemon restart recovery + +Hosts resume interrupted agents by default after graceful shutdown or a crash. The daemon +reopens the saved provider conversation and settings, then sends `Resume working.`. Change +`agents.resumePrompt` or disable `agents.resumeOnStartup` in host config or Host settings → Agents. +Disabling recovery consumes pending intent; enabling it later does not revive old work. + +Only agents recorded as running qualify. Idle and initializing agents stay inactive. Archived +agents or workspaces, private helpers and Hub-owned executions retain their own lifecycle. +Explicit creation environment overrides are saved with the agent and reapplied when reopening. + +Startup chooses candidates before anything else reads or repairs persisted running state, then +opens connections and resumes every candidate in the background. A provider that is slow to reopen +holds back only its own agent; a failed reopen is logged. Graceful shutdown records intent before +closing runtimes. + +This is best-effort continuation. A crash between saving intent and dispatching a prompt can lose +or repeat a continuation. Provider resume owns conversation restoration; there is no recovery retry +loop or exactly-once turn guarantee. + ## Runtime residency An unarchived agent may be `closed` without being deleted or archived. Closing releases its provider @@ -139,8 +159,10 @@ caller, child, and host into one watch. Bootstrap restores these watches after repairing stale running records to `closed` and before opening ingress. Reading a closed child's result does not load its provider. A finish notification reports that -the child's run has settled; the parent decides whether its task is complete. Recovery never resumes -child work. Archived or deleted parents suppress delivery; parent-owned creation watches also stop +the child's run has settled; the parent decides whether its task is complete. A child chosen for restart +recovery is observed only after its resume was sent, so the parent never hears that it was closed +in between. Archived or deleted parents suppress delivery; +parent-owned creation watches also stop reporting after detachment. Intent remains stored until the parent's notification dispatch is acknowledged. Dispatch failure @@ -288,7 +310,7 @@ parentAgentId === thisAgent.id AND !archivedAt - **Provider subagents** are child executions owned by Claude, Codex, or OpenCode. They are not inserted into `AgentManager` as managed agents. Providers emit a separate descriptor and timeline stream through `agent.provider_subagents.*`; the client keeps that state outside the normal agent store and merges only the presentation rows into the track. A descriptor's optional `parentSubagentId` identifies its direct provider-subagent parent; an absent value identifies a direct child of the managed agent. -Clicking either kind opens a workspace tab. On compact layouts it opens in a [sheet](explorer-sidebar.md#sheets) over the subagents list instead; the sheet hides the composer and shows the agent's model and thinking as one line in its place (`PaneSubtitle`, the row provider subagents already use), and a Paseo subagent's sheet offers **Open as tab** (the full-screen glyph in the header) to get the composer back. A Paseo subagent tab is a normal interactive agent pane. A provider subagent tab is a read-only timeline pane with no composer, archive, detach, rewind, or fork actions. It shows its own direct children in a subagents track. Every subagent pane links back to its parent (`packages/app/src/subagents/parent/`): a pill above the composer when there is one, a parent box in the composer's place when there is not. Both panes use `AgentStreamView`, so message, reasoning, tool-call, and layout rendering stay identical. +Clicking either kind opens a workspace tab. On compact layouts it opens in a [sheet](explorer-sidebar.md#sheets) instead, replacing the subagents list in place (Back returns to the list); the sheet hides the composer and shows the agent's model and thinking as one line in its place (`PaneSubtitle`, the row provider subagents already use), and a Paseo subagent's sheet offers **Open as tab** (the full-screen glyph in the header) to get the composer back. A Paseo subagent tab is a normal interactive agent pane. A provider subagent tab is a read-only timeline pane with no composer, archive, detach, rewind, or fork actions. It shows its own direct children in a subagents track. Every subagent pane links back to its parent (`packages/app/src/subagents/parent/`): a pill above the composer when there is one, a parent box in the composer's place when there is not. Both panes use `AgentStreamView`, so message, reasoning, tool-call, and layout rendering stay identical. Provider timelines use the same structural timeline item format but deliberately have a separate lifecycle and transport. A provider thread/session identifier is not a Paseo agent identifier, and closing its tab is always layout-only. diff --git a/docs/android.md b/docs/android.md index 5a59eedaa4..17bafd6b24 100644 --- a/docs/android.md +++ b/docs/android.md @@ -61,6 +61,18 @@ Gradle auto-fetches the platform/build-tools it needs once licenses are accepted ## Local build + install +The `react-native-svg@15.15.4` patch prevents header fades retaining their old painted size after +rotation. Rebuild native Android after changing it; Metro reloads cannot update this code. Keep the +resize hunks until upstream invalidates descendant geometry on canvas resize. Its instrumentation +regression renders real gradient pixels across growing and shrinking layouts, including a nested +group. From `packages/app/android`, run it on your selected emulator: + +```bash +ANDROID_SERIAL=emulator-5562 ./gradlew :react-native-svg:connectedDebugAndroidTest \ + -Pandroid.testInstrumentationRunnerArguments.class=com.horcrux.svg.SvgResizeTest \ + --no-daemon --max-workers=2 -Dorg.gradle.parallel=false +``` + The locked `expo-modules-core@57.0.23` needs the patch installed by `npm install`. It backports [Expo's Activity-result launcher fix](https://github.com/expo/expo/pull/49634): changing @@ -98,7 +110,7 @@ The older `android`, `android:development`, and `ios` commands remain aliases fo `android:production` still builds and installs a release through Expo; use `build:apk` when you need an artifact. `android:clear` removes the generated Android project. -Run `npm run test:android --workspace=@getpaseo/app` to prebuild Android and run native module unit tests. The app CI job runs this command with the Android toolchain. +Run `npm run test:android --workspace=@getpaseo/app` explicitly with a local Android toolchain to prebuild Android and run native module unit tests. Ordinary CI does not prebuild Android or run these tests. ### Diagnostic logs without ADB @@ -215,7 +227,8 @@ fastlane/metadata/android/ │ ├── images/ │ │ ├── icon.png (512x512) │ │ ├── featureGraphic.png (1024x500) -│ │ └── phoneScreenshots/ (1.png, 2.png, ...) +│ │ ├── phoneScreenshots/ (1.png, 2.png, ... linked to the store renders) +│ │ └── tenInchScreenshots/ (1.png, 2.png, ... linked to the store renders) │ └── changelogs/ (generated — see below) ├── ja/ └── zh-CN/ @@ -223,6 +236,8 @@ fastlane/metadata/android/ Locale directories generally match `packages/app/src/i18n/locales.ts`, but note that `en` becomes `en-US`. +Google Play reads its screenshots from the same folders; see [Store screenshots](release.md#store-screenshots). + F-Droid changelogs are generated from `CHANGELOG.md`. Run `npm run fdroid:changelogs`; `npm run fdroid:changelogs:check` verifies without writing. It is wired into the npm `version` lifecycle, so a release picks it up automatically and `git add -A` stages the result. One changelog must be generated per-ABI-split, so each version will create **four** identical version-coded entries. F-Droid caps changelogs at 500 characters, so the generator strips some content and adds a link to the full notes. diff --git a/docs/architecture.md b/docs/architecture.md index 29f9c7f817..a7ad69c14d 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -66,6 +66,9 @@ WebSocket message schemas. Shared configuration schemas belong in protocol leaf retaining the daemon's runtime and wire-schema allocations. The server export tests guard these dependency trees with tree-shaking disabled to match unbundled production imports. +Terminals do not live in the daemon process: their PTYs run in a detached terminal worker that +survives daemon restarts, crashes and upgrades. See [terminal-worker.md](terminal-worker.md). + Project identity is daemon-global rather than session-owned. After registry bootstrap, the daemon's project Git observer keeps one non-recursive watch on each lexically equivalent active project root and listens only for the root `.git` entry, with a slow rescan as a missed-event fallback. It runs @@ -490,6 +493,16 @@ The supervisor alone publishes its ready worker's endpoint in `paseo.pid`, clear Worker restart retains supervisor arguments/environment and rereads the configuration file. Updating a package and observing its new worker version do not refresh the running supervisor code; the launcher owns full-process replacement. See [CLI lifecycle contracts](../public-docs/cli.md#daemon-management). +## Outbound networking + +The daemon and its plugin processes honor `HTTPS_PROXY`, `HTTP_PROXY`, and `NO_PROXY` +(including lowercase forms, which take precedence). Fetch and relay, Hub, and connected-host WebSockets +share this policy. Loopback (`localhost`, `127.0.0.1`, `::1`) always goes direct. +A proxy without a scheme uses HTTP. Invalid values and unsupported proxy schemes +are treated as unset, with one warning naming the variable in `daemon.log`. +Agent and terminal environments are unchanged. System proxy settings and SOCKS-only +`ALL_PROXY` configurations are not supported. + ## Deployment models 1. **Local daemon** (default): `paseo daemon start` on `127.0.0.1:6767` diff --git a/docs/connected-hosts.md b/docs/connected-hosts.md index 20c86c1295..7e8b67ee62 100644 --- a/docs/connected-hosts.md +++ b/docs/connected-hosts.md @@ -74,7 +74,10 @@ registrations remain inspectable; a changed destination requires explicit identi Both daemons advertise `connectedHosts`; the shared link additionally requires `hostMultiplexing`. A completes capability and pinned-identity checks on each physical recovery before admitting channels. There is no local fallback. An older daemon continues to serve existing local -operations; requesting this feature gives update guidance. +operations; requesting this feature gives update guidance. The registry retries an older destination +with capped backoff, so it comes online once updated. Self, duplicate, changed-identity, and +authentication failures stay in `error` until an update changes the connection, `enabled`, or +`replaceIdentity`, or A restarts. Disposing a routed API releases its observations and session. It does not remove the saved host or affect sibling API scopes. Disposing the origin cascades to its derived scopes. Observations restore diff --git a/docs/custom-providers.md b/docs/custom-providers.md index a6c6cefbdc..1d6d67d453 100644 --- a/docs/custom-providers.md +++ b/docs/custom-providers.md @@ -65,6 +65,7 @@ per-agent examples and provider-specific keys. ## Table of Contents - [Extending a built-in provider](#extending-a-built-in-provider) +- [OpenCode with an existing v2 server](#opencode-with-an-existing-v2-server) - [Z.AI (Zhipu) coding plan](#zai-zhipu-coding-plan) - [Alibaba Cloud (Qwen) coding plan](#alibaba-cloud-qwen-coding-plan) - [Codex with a custom OpenAI-compatible endpoint](#codex-with-a-custom-openai-compatible-endpoint) @@ -107,6 +108,35 @@ See [Codex with a custom OpenAI-compatible endpoint](#codex-with-a-custom-openai --- +## OpenCode with an existing v2 server + +Paseo first uses an explicitly configured server, then a healthy locally registered OpenCode v2 service, then starts its own helper. It never stops a reused service. To select a server explicitly, set its URL in the provider environment: + +```json +{ + "agents": { + "providers": { + "opencode": { + "env": { + "PASEO_OPENCODE_SERVER_URL": "http://127.0.0.1:4096", + "PASEO_OPENCODE_SERVER_PASSWORD": "" + } + } + } + } +} +``` + +`PASEO_OPENCODE_SERVER_URL` must be an absolute `http` or `https` URL. Omit `PASEO_OPENCODE_SERVER_PASSWORD` when the server has no authentication; when set, Paseo authenticates with HTTP Basic auth as `opencode`. + +A configured URL takes precedence even when unreachable; Paseo reports the connection error. The local service registration supplies its own authentication. For a discovered local service, Paseo installs its bridge package in OpenCode's watched global plugin directory without changing the existing configuration. Refresh reads the existing service's catalogs without starting another server. + +An explicitly configured server needs the bridge installed separately. Connect once and start a session: the setup error gives the local package directory. Copy that directory to the server's OpenCode global `plugins` directory, then retry. For a server on another machine, set `PASEO_OPENCODE_BRIDGE_PORT` in the Paseo OpenCode provider environment before starting Paseo, and set `PASEO_OPENCODE_BRIDGE_URL` to the URL the OpenCode server can use to reach that port. For example, an SSH reverse tunnel can expose the Paseo loopback port on the OpenCode host. The bridge token is exchanged through the OpenCode connection and is not written into the plugin package. + +OpenCode's custom MCP registrations are shared by all sessions in a location. Paseo rejects custom MCP servers and per-agent process environment overrides on a reused server rather than applying them to other sessions or ignoring them. Session identity is applied to each session's shell environment. A Paseo-owned helper supports custom process and MCP settings; it is selected when there is no explicit URL or healthy registered service. + +--- + ## Z.AI (Zhipu) coding plan [Z.AI](https://z.ai) is a Chinese AI company (Zhipu AI) that offers an Anthropic-compatible API endpoint. Their GLM Coding Plan provides flat-rate access to GLM models through Claude Code's Anthropic API protocol. These are **not** Anthropic Claude models — they are Zhipu's own GLM models exposed through an Anthropic-compatible API. @@ -232,7 +262,7 @@ For pay-as-you-go, use `ANTHROPIC_API_KEY` with a standard Model Studio key (`sk Codex talks to OpenAI's Responses API by default. Custom providers that extend `"codex"` can point Codex at any OpenAI-compatible endpoint (OpenRouter, LiteLLM, vLLM, llama.cpp server, an internal gateway, etc.) by setting `OPENAI_BASE_URL` and `OPENAI_API_KEY` in the provider `env`. -Paseo passes those variables through to the Codex app-server process **and** maps them into Codex's thread config under `model_provider` / `model_providers`, because Codex reads provider routing from config rather than from `OPENAI_BASE_URL` alone. +Paseo passes those variables through to the Codex app-server process **and** maps them into Codex's thread config under `model_provider` / `model_providers`, because Codex reads provider routing from config rather than from `OPENAI_BASE_URL` alone. The generated Codex provider key is `paseo:`, so a Paseo provider such as `ollama` does not override a Codex built-in. Existing custom sessions created with a non-built-in provider key remain available in Import session. Native Codex conversations using a built-in key stay separate from a custom provider of the same name. ### Setup @@ -260,9 +290,9 @@ Paseo passes those variables through to the Codex app-server process **and** map Under the hood, for each custom Codex provider Paseo injects this into Codex's config: ```toml -model_provider = "my-codex" +model_provider = "paseo:my-codex" -[model_providers.my-codex] +[model_providers."paseo:my-codex"] name = "My Codex" base_url = "https://custom-relay.example.com/v1" wire_api = "responses" diff --git a/docs/design.md b/docs/design.md index fe60cdc53b..a336b80a64 100644 --- a/docs/design.md +++ b/docs/design.md @@ -150,18 +150,20 @@ One row off the rail makes the whole card look unconsidered. Compact-first. The small case is designed; the large case adds chrome around it. -The list+detail pattern is canonical and reused across surfaces. The settings shell (`packages/app/src/screens/settings-screen.tsx`) and the projects screen (`packages/app/src/screens/projects-screen.tsx`) implement it identically: +Use `md: 600` for both the compact/wide layout boundary and responsive density, in logical points on native and CSS pixels on web. Do not add a separate density breakpoint. Measured content constraints remain independent: composer controls use `COMPACT_CONTENT_WIDTH` (500), so a narrow pane can keep compact controls inside a wide window. + +The settings shell (`packages/app/src/screens/settings-screen.tsx`) and the projects screen (`packages/app/src/screens/projects-screen.tsx`) share the canonical list+detail navigation pattern: - On compact: full-screen list with `` at the top. Tapping a row pushes a full-screen detail with its own `` that returns to the list. -- On desktop: a 320px sidebar on the left holds the list with `surfaceSidebar` background. The content pane on the right holds the selected detail with ``, ``, and ``. +- On wide layouts: a sidebar on the left holds the list with `surfaceSidebar` background. The content pane on the right holds the selected detail with ``, ``, and ``. The branching is one `useIsCompactFormFactor()` check at the top of the screen component. The list and the detail are the same components in both layouts; only the framing changes. The workspace screen (`packages/app/src/screens/workspace/workspace-screen.tsx`) follows a different but parallel rule: tabs collapse on compact, panes split on desktop. The sidebar (`packages/app/src/components/left-sidebar.tsx`) is overlaid on compact and pinned on desktop. -On a narrow desktop route, app navigation yields to the rendered content topology when the remaining width cannot preserve its center target: Settings keeps its 320px list + 400px detail split, and a workspace Explorer keeps its current visible width plus a 400px center pane. That is a topology decision at the app container, not a second compact breakpoint. Temporary width clamps are render-only; widening restores the user's saved sidebar widths. +On a narrow window using the wide layout, app navigation yields when the remaining width cannot accommodate the content topology. Settings prefers a 720px split (320px list + 400px detail); its list shrinks first to keep forms readable without reducing the detail below 400px. Explorer reserves at least 240px plus a 360px workspace. These are local space budgets, not compact breakpoints. The app sidebar shrinks from its preferred 320px toward a 200px minimum to leave a 400px center target; its preferred width fits at 720px. Temporary width clamps are render-only; widening restores the user's saved sidebar widths. -Electron window controls are top-corner obstructions, not a compact-layout condition. Rendered surfaces declare which top corners they physically occupy; only those corners receive clearance. Full-window overlays redeclare both corners. A focused split pane owns both corners; if focus restoration temporarily exposes the full split tree, the split boundary reserves one top strip instead of assigning a control rectangle to an arbitrarily narrow leaf. The 720px desktop breakpoint preserves the default 320px sidebar and target 400px center width when the Explorer is closed; it is product policy, not an obstruction gate. +Electron window controls are top-corner obstructions, not a compact-layout condition. Rendered surfaces declare which top corners they physically occupy; only those corners receive clearance. Full-window overlays redeclare both corners. A focused split pane owns both corners; if focus restoration temporarily exposes the full split tree, the split boundary reserves one top strip instead of assigning a control rectangle to an arbitrarily narrow leaf. Windows and Linux controls are fixed window chrome, outside scrolling header content. A tab rail that reaches them ends at their obstruction and shows the shared overflow fade. On macOS, the Explorer toggle occupies a fixed top-right window slot so opening and closing Explorer does not move the pointer target. diff --git a/docs/development.md b/docs/development.md index 7eb92375ab..873f9cabb9 100644 --- a/docs/development.md +++ b/docs/development.md @@ -273,6 +273,26 @@ Playwright dispatch lateness. Set `PASEO_PROFILE_TYPING_KEYS`, `PASEO_PROFILE_TY `PASEO_PROFILE_CPU_PATH` and `PASEO_PROFILE_TRACE_PATH` captures run separately after the latency measurements so profiling overhead does not contaminate them. +For diff layout, two benchmarks share one corpus +(`packages/app/src/git/diff-document/benchmark-corpus.ts`: a real source file, a changelog with +600-character lines, generated code with ligature punctuation, and JSON). The node bench runs the +shared document model with the web and native measurers replaced by counters, so it reports how +many strings each backend would have to shape, which is the cost that survives the move to canvas +or Skia: + +```bash +cd packages/app && npx vitest bench --project unit src/git/diff-document/model.bench.ts +``` + +The browser benchmark opens the same corpus as a working diff, toggles line wrap from the toolbar, +and reports pointer-down to painted latency, the longest main-thread task, and the `DiffDocument` +React commit time for cold and warm toggles, then scroll frame times in both modes: + +```bash +cd packages/app && PASEO_DIFF_PERF_E2E=1 npx playwright test --project=browser \ + e2e/browser/diff-performance.spec.ts -g "toggling line wrap" +``` + Set `PASEO_PROFILE_TYPING_SCENARIO=height-growth` to alternate `Shift+Enter` and printable input. That report includes input and composer height changes plus React work grouped into composer, stream, and ancestor/root scopes. Ancestor/root timings include descendant work because the Profiler @@ -542,6 +562,39 @@ patch every build the consumers use: Metro resolves the `react-native` field of (`src/*.ts` for `react-native-svg`), while Node and Vitest resolve `main`/`module` (`lib/commonjs`, `lib/module`). Patching only `lib/` leaves the app bundle unfixed. +## Dependency overrides and workspace tooling + +Root `package.json` `overrides` pin one Expo SDK across the tree (`expo`, `expo-router`, +`react-native`, …). npm does not apply those overrides to packages it places under a +workspace's own `node_modules`. When `expo-module-scripts` was declared in +`packages/expo-two-way-audio`, npm nested it there and its `jest-expo` peer `expo@*` resolved to +a second, newer Expo SDK and React Native: 200+ duplicate packages nothing imported (#7730). +Declare tooling that peer-depends on `expo` or `react-native` in the root `devDependencies`, +where the overrides apply; workspace scripts still find the binary through the root +`node_modules/.bin`. + +## Dependency signature audit + +The `quality` CI job runs `npm audit signatures`. It verifies every lockfile package's registry +signature and, for packages published with provenance, fetches +`/-/npm/v1/attestations/@` from the registry. Cloudflare caches that document +for a year. An edge that cached it in the seconds before the registry attached the publish +attestation keeps serving a document with only the provenance bundle, and npm fails with: + +``` +npm error code EMISSINGSIGNATUREKEY +npm error @ has attestations but no corresponding public key(s) can be found +``` + +The same package's registry signature verified a moment earlier with the same keys, so the +key list is intact. The failure names one package, repeats only for that package, and depends +on the Azure region the runner landed in, because each region maps to one Cloudflare colo. A +rerun passes only by landing elsewhere. + +To confirm, fetch the URL from several runners and compare `content-length`, the `cf-ray` colo +suffix, and the number of `attestations` entries (#7730 has the probe). To fix, remove or +replace that version in the lockfile and report the URL to npm so they purge it. + ## ACP provider catalog versions The in-app ACP provider catalog pins package-runner entries (`npx`, `npm exec`, diff --git a/docs/explorer-sidebar.md b/docs/explorer-sidebar.md index a1778b47b8..b63095e7a0 100644 --- a/docs/explorer-sidebar.md +++ b/docs/explorer-sidebar.md @@ -33,25 +33,36 @@ keeps only agents and terminals. A panel kind opts in with `compactSheet` in its (`packages/app/src/panels/panel-manifest.ts`), and the layout store's `openTab` decides between sheet and tab, so callers open targets the same way on every layout. Each such sheet holds one ordinary `WorkspaceTab` (`SheetTab` in the store) and is an `IsolatedBottomSheetModal` like every -other sheet in the app, so it sits on the one app-wide stack: a sheet opened from any sheet, a -subagent chosen from the subagents list included, lands on top of it, and closing the top sheet -(drag, Close, backdrop, or Android Back) uncovers the one below. The list stays open under the -sheet it opened; see [menus.md](menus.md#selecting-an-item-on-ios) for the row contract. +other sheet in the app, so it sits on the one app-wide stack: a sheet opened from any sheet lands on +top of it, and closing the top sheet (drag, Close, backdrop, or Android Back) uncovers the one below. + +A subagent chosen from the subagents list is the exception. It opens as a page of the list's own +sheet and replaces the list in place: Back returns to the list, Close ends both, and Open parent +closes the list, landing on the pane the list was opened from. The store's `selectSheetTab` describes +the `SheetTab` a reveal would show without opening it, so the page never enters `sheetsByWorkspace`. +See [menus.md](menus.md#a-page-that-fills-the-sheet) for the page contract. The store keeps `sheetsByWorkspace` in opening order and never reorders it, because moving a sheet remounts its panel. Revealing a target that already has a sheet uncovers that sheet by closing the ones above it, except ones holding unsaved work, which stay where they are. Opening a sheet as a tab dismisses the sheets above it, since the tab would sit under them. The stack is not persisted. -Sheets are modal and cover both compact sidebars as well as the workspace. A sheet's header is its drag -handle, because the panel scrolls on its own and content panning would fight it. Its trailing rail -holds icon buttons only (`SheetHeaderIconButton`): Open as tab is the full-screen glyph beside -Close, so the title keeps its width. Compact sheets use the app overlay host: a workspace-local -host sits behind the app-level left sidebar. The workspace environment bridge preserves existing -editing sessions, caches, file-link resolution and supported navigation context without moving -their providers. Keep this capability at the workspace boundary; new sheet callers must not -assemble provider internals. Wide layouts retain local hosting and pane geometry. Both hosts -forward the same Gorhom modal queue; neither creates another stack. See +Both kinds render the same `SheetPane` (`packages/app/src/screens/workspace/sheet-pane/`): the +header (icon, title, Back when there is a list to return to, Open as tab, Close), the pane, its +bottom inset, and its focus. Only the container differs, a workspace sheet in `sheet-tabs.tsx` or a +menu page in `sheet-pane/page.tsx`, so a fix to what a sheet shows lands in one place. The +container owns Android Back; the pane never subscribes to it. + +Sheets are modal and cover both compact sidebars as well as the workspace. The header drags the +sheet through `SheetDragArea`, because the panel scrolls on its own and content panning would fight +it. Its trailing rail holds icon buttons only (`SheetHeaderIconButton`): Open as tab is the +full-screen glyph beside Close, so the title keeps its width. Compact sheets use the app overlay +host: a workspace-local host sits behind the app-level left sidebar. The sheet pane bridge +(`useSheetPaneBridge`) preserves existing editing sessions, caches, file-link resolution and +supported navigation context without moving their providers. Keep this capability at the workspace +boundary; new sheet callers must not assemble provider internals. Wide layouts retain local hosting +and pane geometry. Both hosts forward the same Gorhom modal queue; neither creates another stack. +See [floating-panels.md Gotcha 7](floating-panels.md#gotcha-7--a-sheet-cannot-read-context-from-its-call-site). A sheet holding unsaved work is never implicitly displaced; only its guarded close removes it. diff --git a/docs/floating-panels.md b/docs/floating-panels.md index f17c59c7c2..4616a03815 100644 --- a/docs/floating-panels.md +++ b/docs/floating-panels.md @@ -410,6 +410,19 @@ bridges the menu's two contexts; the rest pass `null`. Wrapping providers _around_ the modal does nothing. They land on the wrong side. +## Gotcha 8 — Read safe-area insets where the overlay draws + +A compact sheet tab's body (`SheetBottomInset` in `adaptive-modal-sheet.tsx`) pads the bottom +inset and gives its content a bottom inset of 0, so the composer dock sits the same in a sheet as +in a tab. An overlay opened from that content and calling `useSafeAreaInsets()` at its call site +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 + `CompactSheetBody`, `MenuSheetScrollView` and `ComboboxSheetFrame`. +- An RN `Modal` passes the call site's context straight through, so put a `SafeAreaProvider` + inside it and read the inset below that. The modal is its own window, and the provider measures + it. See `attachment-lightbox.tsx`. + ## Recipe for a new anchored panel Before you write a new one, ask: diff --git a/docs/glossary.md b/docs/glossary.md index d2c871f74b..c7fd1398c5 100644 --- a/docs/glossary.md +++ b/docs/glossary.md @@ -22,7 +22,7 @@ Authoritative terminology. UI label wins. Don't invent synonyms; use what's here - **Sidebar items** — The configurable entries of the app sidebar, in two sections. Header: the rows at the head of the sidebar — New workspace, History, Search, Schedules, and plugin header items. Footer: the full-width rows between Add project and the footer icon row — Usage and plugin footer items. Add project and the icon row (Hosts, Help and support, Settings) are fixed and are not sidebar items. A plugin item may render several rows, such as one per bot; it is still one item that moves and hides as a block. Each section's order and visibility is one per-device preference (`AppSettings.sidebarNavItems`, `AppSettings.sidebarFooterItems`); every item may be off. UI: the Header and Footer cards on the Sidebar settings page. Code: `packages/app/src/sidebar-nav/model.ts` resolves a section, and the sidebar (`components/sidebar/sidebar-nav-rows.tsx`, the footer in `components/left-sidebar.tsx`) and the settings page (`screens/settings/sidebar/sidebar-nav-section.tsx`) read it through `useSidebarNavItems(section)`. Never hardcode one of these entries or add a second place that decides which ones show. Don't confuse with **Explorer sidebar**. - **Explorer sidebar** — The dedicated navigation dock containing the Files and Changes trees. UI: "Explorer sidebar". Code: `packages/app/src/workspace-tabs/explorer-sidebar.ts`; persisted pane identifiers retain the `explorer` spelling. See [explorer-sidebar.md](explorer-sidebar.md). - **Sheet** — Any bottom sheet; there is one kind and one app-wide stack, so a sheet opened from a sheet lands on top of it and closing it uncovers the one below. Code: `IsolatedBottomSheetModal` (`packages/app/src/components/ui/isolated-bottom-sheet-modal`). Forbidden: "Workspace sheet", "modal sheet" as a distinct kind. See [floating-panels.md](floating-panels.md). -- **Sheet tab** — A compact-layout sheet holding one file or subagent tab over the workspace without adding it to the tab switcher. UI action: "Open as tab". Code: `SheetTab` and `sheetsByWorkspace` in `packages/app/src/stores/workspace-layout-store.ts`, `SheetTabs` (`packages/app/src/screens/workspace/sheet-tabs.tsx`). See [explorer-sidebar.md](explorer-sidebar.md#sheets). +- **Sheet tab** — A compact-layout sheet holding one file or subagent tab over the workspace without adding it to the tab switcher. A subagent chosen from the subagents list shows as a page of the list's sheet instead of a sheet of its own. UI action: "Open as tab". Code: `SheetTab` and `sheetsByWorkspace` in `packages/app/src/stores/workspace-layout-store.ts`, `SheetPane` (`packages/app/src/screens/workspace/sheet-pane/`). See [explorer-sidebar.md](explorer-sidebar.md#sheets). - **Side pane** — An ordinary right-side workspace pane used for content opened beside the user's work. It closes and participates in workspace splits like every other main-host pane. See [explorer-sidebar.md](explorer-sidebar.md#side-pane). Forbidden: "Side panel". - **Directory-backed surface** — A right-sidebar surface whose content is determined by the workspace's `cwd`, so two workspaces on the same directory see identical content: git diff/status, forge change-request info, file preview/explorer contents. Keyed by `(serverId, cwd)`, never `workspaceId`. See [architecture.md](architecture.md#right-sidebar-boundary-directory-backed-vs-workspace-owned). - **Workspace-owned state** — Per-workspace state that never leaks to a same-`cwd` sibling: tabs, agents, terminals, panes, title, plus review drafts, diff-mode overrides, composer attachments, and file-explorer open/expand state. Keyed by `workspaceId` (`cwd` only as a fallback for old payloads). See [architecture.md](architecture.md#right-sidebar-boundary-directory-backed-vs-workspace-owned). @@ -34,9 +34,11 @@ Authoritative terminology. UI label wins. Don't invent synonyms; use what's here - **Agent profile** — A named launch bundle: provider, model, mode, thinking option, feature values, and free-text notes. Applying one writes those values into the **Agent controls** and is then forgotten — there is no selected profile, no default profile, and no drift tracking. The notes are written for orchestrating agents and are what the `list_profiles` MCP tool surfaces. Stored host-wide in daemon config as `agentProfiles`. UI: "Agent profiles". Code: `AgentProfile` (`packages/protocol/src/messages.ts:161`). Carries no system prompt, because a per-agent system prompt can only be set at creation. Forbidden: "Favourite", which this replaced. - **Terminal profile** — A named shell command a terminal can launch. Stored host-wide in daemon config as `terminalProfiles`. UI: "Terminal profiles". Code: `TerminalProfile` (`packages/protocol/src/messages.ts:135`), `resolveTerminalProfiles` (`packages/protocol/src/terminal-profiles.ts`). Also selectable as a New Workspace launch target, where the alternative is the chat agent. - **Provider** — Agent backend (Claude Code, Codex, Copilot, OpenCode, Pi, Oh My Pi). UI: "Provider". Code: `ProviderSnapshotEntry` (`packages/protocol/src/messages.ts:198`). +- **Hook** — A plugin lifecycle handler registered with `server.addHook`, named `subject.operation.position` with `before` or `after`; each hook declares whether Paseo waits. See [hooks](../public-docs/plugins/hooks.md). - **Usage source** — Plugin registration that discovers accounts and fetches plan usage. Code: `UsageSourceRegistration` (`packages/plugin/src/server/usage.ts`). - **Report ID** — Stable daemon-composed identity for one source account: `:`. The source owns the account key; clients treat the whole ID as opaque. Code: `UsageReportEntry.id` (`packages/protocol/src/messages.ts`). - **Usage report** — A source's normalized usage for one account, including status and optional windows, balances, and details. Its entry carries the Report ID, account label, and fetch time. Each report renders as one card in the Usage modal, in host Settings, and in an agent's context window details (a hover card on desktop web, a tooltip on native wide screens, a sheet on compact ones), which show only the account that agent runs under, without pins. The hover card and the sheet have Refresh; the native tooltip takes no presses. Code: `UsageReport` (`packages/plugin/src/server/usage.ts`), `UsageCard` (`packages/app/src/usage/card.tsx`), `AgentUsage` (`packages/app/src/usage/agent-usage.tsx`). +- **Check usage** — Host-wide switch in Usage Settings, on by default. Turning it off stops login discovery and vendor requests on that host for every device. Usage shows an off state with **Turn on**; the sidebar summary and agent usage sections disappear. - **Usage (sidebar item)** — The sidebar footer item showing each pinned window's source icon and percent, hidden while no pinned window has data (the footer's Usage icon remains available); both entry points open the Usage modal over the current screen: a dialog on wide layouts, a bottom sheet on compact ones. Usage has no route of its own. Off until the user turns on **Summary in sidebar** (Usage Settings) or the Usage row in Settings > Sidebar; window rows pin only while it is on, and saved pins come back when it is turned on again. A pin is `{ sourceId, windowId }` and shows once per account of that source. Pins and the used/remaining choice are one per-device preference (`AppSettings.usage`) that every usage surface follows. It reads the active workspace's host, else the first connected host with usage sources. Code: `packages/app/src/usage/sidebar-item.tsx`, `usage/usage-modal.tsx`, `usage/pinned.ts`, `usage/preferences.ts`. - **Model** — A specific LLM offered by a provider. UI: "Model" / "Select model". Code: `AgentModelDefinition` (`packages/protocol/src/messages.ts:187`). - **Tab** — UI surface representing one session inside a workspace. Not a conceptual unit; use **Agent session** when talking about the model. Code: `WorkspaceTabDescriptor` (`packages/app/src/screens/workspace/workspace-tabs-types.ts`). diff --git a/docs/menus.md b/docs/menus.md index 9dc3e26cae..590def2b33 100644 --- a/docs/menus.md +++ b/docs/menus.md @@ -52,10 +52,12 @@ is another, with its own icons and hover-revealed actions — but both hand the and take `closeOnSelect` to say whether choosing them ends the surface. A row that owns its press outright leaves the surface open behind whatever it opened, and skips the iOS wait. -A row whose result opens a sheet passes `closeOnSelect={false}`: the sheet stacks over the menu -sheet and uncovers it on close, so the menu is where the user lands next. A row that opens a tab +A row whose result opens a sheet opens it as a page of the menu's own sheet, never as a second +sheet over it: the row names a [fill page](#a-page-that-fills-the-sheet) with `opensPage`, the page +replaces the list in place, Back returns to the list, and Close ends both. A row that opens a tab closes, because the tab replaces the pane the menu belongs to. The subagents track asks the layout -store which one a row is (`useSubagentOpensInSheet`), since the answer changes with the layout. +store which sheet tab a row would show (`useSubagentSheetTab`), since the answer changes with the +layout; a row with none opens its tab. ## Pages @@ -101,6 +103,23 @@ The sheet keeps `keyboardBehavior="interactive"`. `extend` grows a sheet to its point, and with `enableDynamicSizing` that point is the content's own height — a short page does not grow, and the keyboard comes up over the field you are typing into. +## A page that fills the sheet + +A page can carry its own content instead of rows: `{ id, fill: true, content }`. Only the sheet +renders one. It takes the full-sheet snap point (`FULL_SHEET_SNAP_POINTS`) instead of sizing to +content, and the sheet stops panning on content drags, because the page scrolls on its own and a +drag would fight that scroll. The page's header drags the sheet instead, through `SheetDragArea`. + +The content renders on the far side of the sheet's portal, so it brings its own context bridge, +built where the page is defined. Sheet tabs are the one user: `useSheetPanePage` turns a `SheetTab` +into a fill page around the same `SheetPane` the workspace's own sheets render. See +[explorer-sidebar.md](explorer-sidebar.md#sheets). + +Back pops one page. The header's Back and Android Back both call `goBack`, which answers `false` at +the root so the sheet closes instead. A page whose definition disappears while it is open, such as +a subagent archived from elsewhere, is pruned from the path, and the sheet falls back to the page +that opened it. + ## Hover intent A flyout **overlaps its parent by 5pt** rather than sitting beside it. With a gap there is a strip @@ -181,15 +200,17 @@ its own. ## Gotchas -- **Released height.** Reanimated's web entering animation leaves an inline height snapshot on - the surface. `AnchoredSurface` clears it, and a `revision` prop re-clears it when content - identity changes — a pushed page taller than the one it replaced is clipped without that. -- **Animate only once placed.** The same snapshot carries top/left, and Reanimated writes it back - 750ms after mount. `AnchoredSurface` remounts the surface when its position resolves so the - entering animation never ends at the off-screen measuring position; on a slow machine that - write moved the open menu back off-screen. +- **Web enters without Reanimated.** For a custom keyframe, Reanimated's web path snapshots the + surface's rect when the animation ends and writes it back as inline top/left/width/height 750ms + after the start. Whatever moved or resized the surface in between was undone: content that + grew once its data arrived left the menu clipped, or hanging over its anchor, until it moved + again. `AnchoredSurface` plays the same keyframes through the Web Animations API on web, which + leaves no inline style; native keeps the Reanimated `Keyframe`. +- **Animate only once placed.** `AnchoredSurface` remounts the surface when its position resolves, + so the entering animation runs at the final position rather than ending unseen at the + off-screen measuring position. - **Sheets size to content.** `enableDynamicSizing`, not fixed snap points. A pushed page is - rarely the height of the page before it. + rarely the height of the page before it. A fill page is the one exception. - **The sheet's content is teleported out of the menu's subtree**, so `MenuSheetSurface` rebuilds both menu contexts through the sheet's `contextBridge`. Providing them around the modal puts them on the wrong side of the portal and every item inside throws. Gotcha 7 in diff --git a/docs/mobile-testing.md b/docs/mobile-testing.md index 169803c0eb..903244e3d9 100644 --- a/docs/mobile-testing.md +++ b/docs/mobile-testing.md @@ -35,6 +35,20 @@ PASEO_MOBILE_E2E_METRO_PORT=62093 npm run test:e2e:mobile [native-terminal-basic.ios.ad](../packages/app/e2e/mobile/agent-device/native-terminal-basic.ios.ad) and [native-terminal-basic.android.ad](../packages/app/e2e/mobile/agent-device/native-terminal-basic.android.ad) are the smallest examples. Each opens a fresh terminal, types a command at zero delay, submits it, and asserts its distinct output. The app must be connected to a daemon with an active workspace. +For Android background fold recovery, install the release APK on a foldable AVD, open a +connected workspace, close the keyboard, and run: + +```bash +ANDROID_SERIAL=emulator-5574 node packages/app/e2e/mobile/fold/android.mjs +``` + +The AVD must expose `CLOSED` and `OPENED` device states. The test backgrounds the app, +changes posture, resumes immediately, and asserts compact/wide workspace controls without +restarting the process. It writes snapshots and native failure state under +`.dev/agent-device-artifacts/android-fold`. Set `PASEO_MOBILE_APP_ID=sh.paseo` for a +production package. This needs a native rebuild when the Unistyles patch changes; a Metro +reload cannot update it. + For Android keyboard continuity, run the current checkout in the app, open an idle terminal with an empty prompt, hide its keyboard, and run: diff --git a/docs/plugins.md b/docs/plugins.md index 9cab47214e..ffae136cc6 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -99,6 +99,10 @@ Built-in plugins ship from `plugins//`, with `paseo-plugin.json`, `index.ser `packages/server/src/server/plugins/builtin/index.ts`; the workspace, build copy, and CI checks cover that registry. Unlisted directories do not load. +The `worktree-include` built-in copies gitignored files selected by +[`.worktreeinclude`](../public-docs/worktrees.md#copy-local-files-with-worktreeinclude) +before setup and agents, through `worktree.create.after`. + Desktop packaging ships the entire built-in plugin directory as an external resource, including declarations. The external esbuild compiler cannot read Electron's `app.asar` filesystem, and packaging dependencies excludes `.d.ts` files needed for import validation. @@ -333,11 +337,10 @@ export default function contribute(client: PluginClientContext) { } ``` -The contribution function must return cleanup. Server cleanup may be async; Paseo waits for it when -the plugin is reloaded, disabled, removed, disconnected, or shut down. Cleanup is for resources -created by plugin code. Paseo removes registered contributions, unmounts surfaces, clears query -state, rejects pending RPCs, closes the plugin's daemon session, and stops the subprocess. Cleanup -errors are logged and do not interrupt host teardown. +The contribution function must return cleanup for resources created by plugin code. Server cleanup +may be async; Paseo waits for it when stopping the server plugin. Cleanup errors are logged and do +not interrupt host teardown. Client installation retention and disposal follow the public +[hosts and lifecycle contract](../public-docs/plugins/reference.md#hosts-and-lifecycle). Paseo owns the route, screen header, icon validation, close action, theme DTO, layout facts, and render error boundary. The contributed component owns the complete body below the header. @@ -382,6 +385,15 @@ grace. During daemon startup, plugin sessions may connect while application WebS paused; the daemon accepts clients only after configured plugins have settled and the initial catalog is complete. +The app retains client bundles per host in its file cache (IndexedDB on web), keyed by plugin ID +and the daemon's SHA-256. A cold client verifies stored contents before advertising their hashes; +missing or corrupt files request full bundles. Only the latest catalog's bundles remain. Hashing +uses Expo's native async digest on mobile, avoiding a JavaScript hash loop on Hermes; reading and +passing the bundle string still costs memory and time once per client lifetime. +Persistence runs after catalog reconstruction without delaying installation. One write runs at a +time; while storage is busy, only the newest pending catalog is kept. A failed write leaves the +in-memory bundles usable, and a later catalog retries persistence. + When the same plugin contribution exists on multiple hosts, Paseo shows it once in the sidebar and adds a host picker to the screen header. The selected host supplies the bundle, RPC transport, and query cache. Explicit SDK targets follow the [host API contract](../public-docs/plugins/reference.md#discover-hosts-and-target-another-host). @@ -428,17 +440,22 @@ The [public reference](../public-docs/plugins/reference.md#icons) owns the autho ## Lifecycle hooks -Server entries register lifecycle observers with `server.on()` and request transforms with -`server.before()`. The [public reference](../public-docs/plugins/reference.md#lifecycle-hooks) -owns callback shapes, ordering, and failure behavior. `plugin-examples/lifecycle-logger` registers all -eleven hooks; `plugin-examples/lifecycle-actions` demonstrates common automation callbacks. -Session-open hooks also [attach tools to individual agents](../public-docs/plugins/reference.md#attach-tools-to-agents), -as shown in `plugin-examples/agent-tools`. The agent manager stamps their metadata per session; -executable definitions stay in the plugin process. +Server entries register async handlers with `server.addHook(name, handler)`, returning a cleanup +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. + +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, +ownership checks prefer the marker-verified worktree root over the legacy +path shape: a plugin can place a worktree several directories below the default worktrees root. Emit from the operation owner, not a client subscription. Provider history replay must not trigger -live hooks. Observers must not be awaited inside agent mutations: a callback can send a prompt or -answer a permission through its own daemon session. Awaiting it there deadlocks that command. +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. ## Contribute a provider @@ -533,7 +550,7 @@ string is never inline SVG or a URL. Register a usage source from `index.server.ts` with `server.registerUsageSource()`. Import `UsageSourceRegistration` and normalization helpers from `@getpaseo/plugin/server/usage`. The plugin owns account discovery, harness labels, and credential-store reads; the daemon owns account grouping and the fetch cache. Agent popovers use only the agent's own login. The host-wide Usage modal falls back across an account's logins; any success shows usage only, and all failures show every login's labeled error and remedy. Follow the [usage source discovery contract](../public-docs/plugins/reference.md#usage-sources). The resolved launch environment crosses into the trusted, unsandboxed plugin subprocess for session discovery. Usage queries never run lifecycle hooks. Inputs are validated in the plugin process and remain daemon-side. `icon` uses the same SVG file rules as provider icons. -The daemon calls discovery for `usage.list_reports`; the client gates this RPC on `server_info.features.usageSources`. The old `provider.usage.list` RPC maps discovered reports for older clients. +When the host’s **Check usage** switch is off, the daemon rejects usage requests before discovery, without reading logins or calling vendors. Otherwise, the daemon calls discovery for `usage.list_reports`; the client gates this RPC on `server_info.features.usageSources`. The old `provider.usage.list` RPC maps discovered reports for older clients. ## Contribute sidebar items @@ -609,7 +626,10 @@ Request observation with `client.paseo.agents.list({ subscribe: {} })` and consu demand. Provider and project `subscribe()` calls establish their own demand. On capable daemons, each list-and-subscribe call has its own server ID, even for the same query. Older daemons retain [shared delivery behavior](protocol-compatibility.md#owned-observations). Handle snapshots -also run after reconnect; replace your view before applying its subsequent updates. The installation +also run after reconnect; replace your view before applying its subsequent updates. An installation +stays loaded during a dropped connection while the app retains its `DaemonClient` object. An +unchanged installation does not rerun setup on reconnect, so refresh state from those snapshots +rather than from setup. Switching connections replaces the client object and reinstalls plugins. The installation owns every observation created through its API and releases them on unload, including setup failure. Mounted surfaces and command invocations have shorter API lifetimes. diff --git a/docs/protocol-compatibility.md b/docs/protocol-compatibility.md index e5ba1db2a3..0fa4fed63d 100644 --- a/docs/protocol-compatibility.md +++ b/docs/protocol-compatibility.md @@ -2,7 +2,7 @@ The app and the daemon are separate products that ship separately. A user updates the app from an app store or a desktop auto-update; they update the daemon when they feel like it. Every combination happens in the wild: new app against an old daemon, old app against a new daemon, and both sides months apart. -In development both sides are always the same version, which is why this is the constraint contributors miss most often. +Development can have the same version drift: an app reload picks up new code while a long-running daemon keeps its loaded version. Check the connected daemon version when diagnosing behavior that crosses this boundary. Two contracts follow from it. @@ -38,7 +38,7 @@ The app checks for the capability and either runs the feature or tells the user - **No defensive branches spread through the feature.** Detection happens in one place, and everything downstream reads a clean shape. - Capability flags live in `features` on the `server_info` message (`packages/protocol/src/messages.ts`, the `server_info` schema). -Existing functionality keeps working across versions because of the protocol contract. Gating a new feature never substitutes for that. +Existing functionality keeps working across versions. Never gate an established request on a new enhancement: negotiate the optional enhancement at the client boundary and preserve the existing request for older hosts. Whole-turn pagination can require a capability; reading conversation history cannot. ## Client capability ownership @@ -52,6 +52,47 @@ On capable daemons, connecting creates no timeline or event demand. Client subsc release it on unsubscribe, and restore it after reconnect. Raw message observers inspect traffic without requesting streams. Application caches and which agents are visible remain caller-owned. +## Terminal ANSI replay + +Terminal replay intentionally drops JSON-era apps, an exception to the general cross-version policy: +use app v0.1.81 or newer. Earlier apps omit `restore` and reject ANSI Restore (`0x05`), so they show +only subsequent live output, without the existing screen or history. + +`terminal_chunked_replay` is SDK-owned delivery behavior. The daemon sends new binary opcodes only to a source +advertising the capability. The SDK keeps the established subscribe request against older +ANSI hosts and normalizes their single Restore frame into begin/data/end. `observeTerminal` defaults +to an explicit full snapshot: omitting restore on an ANSI-era host selects its discarded JSON path. +Explicit caller restore modes and history counts pass through unchanged. JSON snapshot +wire declarations remain accepted, but JSON snapshot frames have no rendering runtime. +Terminals require `terminal-restore-modes`; older hosts show an update message without attaching. + +## Binary chunking + +`binary_chunking_v1` in hello and optional `server_info.features.binaryChunkingV1` +negotiate connection-scoped framing. Application serializers and routed envelopes use +the same boundary. Small messages and handshakes keep their existing representation. +Older peers retain existing frame limits. + +The reserved binary opcode `0x31` is followed by version `1`, original kind +(`0` text, `1` binary), and START/END flag bits `0`/`1`. Remaining bytes are an +unchanged slice. There is no total length or chunk count; a future receiver can +consume slices incrementally. Today the receiver buffers up to the existing +100 MiB logical limit and decodes UTF-8 only after END. Transfers cannot interleave. +Disconnect clears partial state and negotiation. + +The lower transport supplies its plaintext frame budget, including encryption +overhead. The sender waits for drain between chunks while ordinary messages keep +the existing delivery path. Slow-client protections count messages queued behind +an active transfer as well as bytes already in the socket. +The framing module never selects an encryption construction. + +Native uploads retain the platform's existing queue limits. React Native's +WebSocket does not report its queued bytes, so the client cannot wait for native +drain. Android's installed OkHttp transport closes when a send would put more +than 16 MiB in its queue. The native transport disables outbound chunking, including +on routed channels, and retains its existing single-frame admission errors. +Inbound chunking remains enabled; daemon-to-native responses use the daemon's paced writes. + ## Owned observations `owned_subscriptions` and `server_info.features.ownedSubscriptions` negotiate the source-owned diff --git a/docs/providers.md b/docs/providers.md index 1a43558ae3..60fb75a785 100644 --- a/docs/providers.md +++ b/docs/providers.md @@ -89,7 +89,7 @@ OMP supports native Paseo host tools. The adapter registers the full caller-scop Pi RPC extension UI dialog requests (`select`, `input`, `editor`, `confirm`) are bridged into Paseo question permissions and answered with `extension_ui_response`. Pi extensions such as `ask_user` may chain dialogs: for example, a `select` can be followed by an optional-comment `input`. When an `ask_user` tool call declares `allowComment: true`, Paseo presents the selection and optional comment as one question permission, answers Pi's initial `select` immediately, then auto-answers the follow-up optional `input` with the comment the user already supplied (or an empty string). Preserve placeholders and optional/skip semantics for standalone optional inputs so the app can still distinguish "skip this optional input" from "cancel the whole dialog." Fire-and-forget extension UI requests such as notifications are intentionally ignored by the provider adapter unless Paseo grows first-class UI for them. -OpenCode adapters target v1.14.46 and v2.0.10. V2 rejects binaries older than the tested 2.0.10 SDK at runtime selection. Runtime selection uses the configured command and environment. A recognized version is cached until provider configuration reload; a failed, timed-out, or unrecognized probe retains the v1 path and retries detection on the next operation. Load v2 code and materialize its plugin only after positive v2 selection; v1 sessions remain undecorated. Keep upstream SDK types inside the version-specific adapter. OpenCode owns storage migration; a missing native session must fail resume rather than create a replacement. V2 has no native archive/unarchive operation: archiving affects Paseo only. V1 retains native archiving. +OpenCode adapters target v1.14.46 and v2.0.10. V2 rejects versions older than 2.0.10. Paseo selects an explicit server, then a healthy local registered service, then its own helper. It never stops a reused service. A local service loads the Paseo bridge from its watched plugin directory; sessions bind their own bridge credentials through OpenCode RPC. See [OpenCode with an existing v2 server](custom-providers.md#opencode-with-an-existing-v2-server) for setup and isolation limits. Load v2 code and materialize its plugin only after positive v2 selection; v1 sessions remain undecorated. Keep upstream SDK types inside the version-specific adapter. OpenCode owns storage migration; a missing native session must fail resume rather than create a replacement. V2 has no native archive/unarchive operation: archiving affects Paseo only. V1 retains native archiving. Use OpenCode v2 execution events to trigger turn completion, with active-state and durable-log reconciliation after admission, reconnect, and while a turn remains active. Do not use `session.wait`: a healthy turn exceeding Node's HTTP headers deadline produces a transport error while OpenCode keeps working. The live event feed has no replay, and shutdown interruption preserves the previous idle outcome, so the session snapshot alone cannot recover missed execution events. Quiet streams are healthy: v2 heartbeats are SSE comments, not application events. @@ -507,6 +507,8 @@ interface AgentSession { } ``` +`describePersistence()` returns a handle only once a new provider process could resume it. Reload, idle runtime collection and daemon restart resume whatever handle the agent stored; a stored agent without one starts a new session instead. When there is no handle, `AgentManager` stores `getRuntimeInfo().sessionId` as one, so that ID follows the same rule. Codex, for example, starts a thread when the agent is created but writes its rollout only at its first turn, and `thread/resume` fails for it until then, so its adapter reports neither ID before Codex announces that turn. + `setMode` and `setThinkingOption` may return an `AgentProviderNotice` when the provider knows the change needs user-facing context. For example, providers that stage changes until the next turn should return an `info` notice while a turn is already running. The app renders the notice generically as a toast; provider-specific lifecycle behavior stays in the provider implementation. ### Steps diff --git a/docs/release.md b/docs/release.md index 83a419b8ce..328c189f7b 100644 --- a/docs/release.md +++ b/docs/release.md @@ -6,10 +6,10 @@ All workspaces share one version and release together. A release has exactly two steps. The agent does the first, the user authorizes the second. -**Preparation** (local, reversible — agent does this): +**Preparation** (reversible — agent does this): - format, lint, typecheck all green -- resolve the release source to one commit and confirm that commit's existing CI is green +- resolve the [release base](#release-base-and-source), get the [release inventory](#release-inventory) approved when one applies, and confirm CI for the resulting release source is green - classify the diff from the previous stable to the release source as patch or minor, then show the target version and rationale to the user - draft the changelog, show it to the user, wait for review @@ -17,9 +17,10 @@ A release has exactly two steps. The agent does the first, the user authorizes t **Go-ahead** (user says "go ahead"): -- commit the approved release inputs locally -- run the release, which publishes npm and pushes the prepared branch and tag +- commit the approved release inputs locally on the release branch +- run the release, which publishes npm and pushes the release branch and tag - create the release heartbeat immediately and babysit it to completion +- [reconcile `main`](#reconcile-main) with what shipped Rules that apply to both steps: @@ -27,56 +28,128 @@ Rules that apply to both steps: - No code changes bundled into the changelog commit or the release commit. Code shims live in their own commit, reviewed on their own merits. - A sanity-check finding is information, not a directive. The agent surfaces it; the user decides. - Invoking a release skill is intent to start the flow, not blanket authorization to publish. +- An approval the user already gave covers what it names, such as an explicit PR selection or authorization to release autonomously. Do not ask for it again. - If the user asks for a release preview, show the prospective changelog/release contents and answer questions, but do not commit, tag, publish, or run release commands until they explicitly authorize the release. -## Release source and CI +## Main stays open -The default release source is `origin/main`. Fetch `origin`, then record the -resolved commit. The default release checkout is a clean local `main` whose -`HEAD` equals `origin/main`. +Merge normal PRs into `main` at any time, including while a beta soaks or a release is being +finalized. Each release builds in a short-lived release workspace, and its published tag records +the shipped source. -An explicit user instruction can select another ref, such as a hotfix commit or -tag. Resolve that ref once and apply every source, diff, and CI check to that -commit instead of `origin/main`. +## Choosing a path -Before making release-preparation commits, confirm the existing CI run for the -resolved commit is green. Pending CI is watched to completion. Release -preparation then stays local through the changelog, any explicitly requested ACP -catalog update, lockfile preparation, and the version commit. After approval, -commit the prepared inputs locally and run the release command. Its branch and -tag push is the one remote release batch and starts CI for the complete release -commit. +The user decides when the changes on `main` warrant a release and how much risk it takes: -## Release branch discipline +1. **Direct stable release** for a low-risk batch of polish and bug fixes. Stable desktop updates + already ramp over 36 hours (see [Staged rollout](#staged-rollout-stable-channel)), and store + review often takes about a day, with no guaranteed timing. +2. **Beta flow**, the default for changes that need testing. Release candidates on the `beta` + channel. Each beta folds into the series' single changelog entry, publishes npm only on the + explicit `beta` dist-tag, and stays behind the Stable/Beta switch on `/download`. -While you finalize a release on `main`, use a temporary `next` branch for work intended for the following -release. This applies to both beta and stable releases. +A beta follows these defaults, which the user can explicitly override: -- Create each new `next` from freshly fetched `origin/main`. Reuse it while active. -- "This goes to next" means create the PR against `next` or retarget an existing - PR, and keep that destination through delivery. -- Keep `next` current by merging `origin/main` into it as release fixes land. - Avoid rebasing this shared branch because agents and open PRs depend on its history. -- After the release ships, bring `next` up to date and open a `next` → `main` PR. - Pass CI and merge without squashing away the individual PR commits needed for - the changelog. Retarget remaining PRs based on `next` to `main` and delete the integrated - `next`. Create it fresh when needed again. +- Soak a beta at least 24 hours before promotion. Soak longer for risky or breaking changes, or + while feedback is open. Changes added in a later beta get their own soak; earlier soak time does + not count for them. +- A follow-up beta carries regressions, fixes, and polish for what that beta delivers. Unrelated + work on `main` and pre-existing bugs wait for a later release unless the user explicitly selects + them. +- Promotion ships the tested beta's product content unchanged and does not pull from `main`. + Adding a product change needs the user's explicit selection and a new beta, which soaks again. +- During a soak, ship urgent stable regressions and compatibility or provider model updates as a + [stable hotfix](#release-base-and-source) from the latest stable tag. The beta keeps its own + pace. -**Setup still needed:** PR checks run for every base branch, but CI, Docker, and Nix -push runs target only `main`, and GitHub permits only squash merges. Enable -required-check protection for `next`, CI on its pushes, and merge commits for the -integration PR. Handle PR -base changes (`edited` events) so retargeting runs checks against the new base; -GitHub's default PR events do not cover this. Deployment triggers stay unchanged. +npm dist-tags are independent pointers: -### Hotfix from a release tag +- A beta release publishes with `--tag beta` and moves only `beta`; `latest` remains on the + newest stable. +- A stable release publishes to `latest`. Move `beta` to it as well when the stable version is + newer than the version `beta` points to, which covers promotions and direct stable releases, so + `@getpaseo/cli@beta` users never sit behind stable. A stable hotfix on an older line leaves + `beta` on the active newer beta. -If `main` contains changes you do not want to release, branch from the affected -release tag and cherry-pick only the required fixes. Run CI on that branch, then -use the normal release flow with it as the explicit source, choosing a new patch -or beta version. Ensure the fixes and changelog also reach `main` and any active -`next`, preserving newer development and version changes there. This is a -short-lived hotfix branch, not another maintained release track. +## Release base and source + +The release base is the tag or commit a release workspace starts from. The release source is the +base plus any approved cherry-picks, and every source, diff, and CI check uses it. + +| Release | Base | Changes on top | +| -------------------------------------------------------- | ------------------------------------------------------------ | ---------------------------- | +| Starting release: first beta of a line, or direct stable | `origin/main`, captured once | None | +| Follow-up beta | The selected published beta tag, normally the series' latest | Approved commits from `main` | +| Promotion | The beta tag being promoted | None by default | +| Stable hotfix | The latest appropriate stable tag | Approved commits from `main` | + +An explicit user instruction can select another base. + +1. Fetch `origin` with tags and resolve the base to one commit. +2. Create the release workspace through Paseo MCP on a new branch from the base, named + `release/vX.Y.Z` or `release/vX.Y.Z-beta.N` for the version being cut. Run the release from + this workspace: `release:push` pushes `HEAD` to the current branch. +3. Cherry-pick the approved commits in their `main` order with `git cherry-pick -x`, so each + commit records the `main` commit it came from. Include the prerequisites the inventory listed. + Resolve conflicts within the approved changes and report how. A resolution that needs new + behavior is a scope addition: surface it for selection. +4. Confirm CI for the release source. When the source is a commit whose CI already passed (the + captured `origin/main`, or the beta tag being promoted), use that run and watch pending CI to + completion. Otherwise push the release branch and run `gh workflow run ci.yml --ref `, + because CI push runs target only `main`. +5. Keep the changelog, any explicitly requested ACP catalog update, lockfile preparation, and the + version commit local until the go-ahead. The release command pushes the release branch and tag + as one batch, and the tag push starts the release workflows. Then run + `gh workflow run ci.yml --ref ` so CI covers the complete release commit. +6. [Reconcile `main`](#reconcile-main). + +A stable hotfix can take the version a patch beta line would promote to, such as `0.13.3` +shipping while `0.13.3-beta.2` soaks. Never republish or reuse a shipped version. Continue the line +as the next unused patch beta, `0.13.4-beta.1`, from the tested beta tag. No `version:all:*` mode +computes that from a prerelease, so follow the [manual steps](#manual-step-by-step) with +`npm version 0.13.4-beta.1 --include-workspace-root --message "chore(release): cut %s"` and +`npm run release:publish:beta`. Record the tested beta tag as its source so its soak still counts +for the unchanged content. + +## Release inventory + +When the user asks for a follow-up beta or a promotion, list what `main` has that the base does +not, then get the batch approved. There is no release label or queue. + +1. Find the commits on `origin/main` whose patches are not in the base tag: + + ```bash + git log --cherry-pick --right-only --no-merges --format='%h %s' ...origin/main + ``` + + Patch equivalence recognizes commits already cherry-picked into the tag, so trust the tag + content over PR state or branch names. + +2. Present a short include/defer list. Link each PR and give one plain reason. List separately the + prerequisites an included PR depends on and anything that adds scope beyond what the beta + delivers. For each fix that shipped in a stable hotfix after the beta's base, confirm the beta + preserves its behavior, directly or through a superseding change. List the missing ones for + explicit selection; adding one to a promotion needs a new beta. +3. Wait for the user to approve the batch, unless an explicit selection or autonomous + authorization they already gave covers it. + +For a promotion, every item defaults to defer. + +## Reconcile main + +After the release push, open a PR into `main` that brings in what shipped and keeps newer +development on `main`: + +- The shipped `CHANGELOG.md` and `CHANGELOG.zh-CN.md` entries, exactly as tagged. A beta or + promotion entry replaces the series entry on `main`. A stable hotfix on an older line goes + below any newer entries. +- The shipped version in every `package.json` and `package-lock.json`, unless `main` already + carries a newer version, plus the F-Droid changelog files a stable release generates. +- No claims about unshipped work: a shipped entry describes only the tagged content, and notes + `main` holds for changes that have not shipped stay out of it. + +Delete the release branch once the PR merges. The tag is the record of shipped source; Paseo +maintains no release track besides `main`. ## ACP catalog updates @@ -91,21 +164,6 @@ ACP catalog work enters a release through an explicit user request: The release authorization covers the requested ACP commit. It ships in the same release push as the changelog and version commit. -## Two paths - -There are two supported release paths: - -1. **Direct stable release**: you are ready to ship the resolved release source to everyone immediately (default `origin/main`). -2. **Beta flow**: release candidates on the `beta` channel. Each beta folds into the series' single changelog entry, publishes npm only on the explicit `beta` dist-tag, and stays behind the Stable/Beta switch on `/download`. - -Paseo has one linear release track even though npm dist-tags are independent -pointers. The npm invariant is: - -- A beta release moves only `beta`; `latest` remains on the newest stable. -- A stable release moves both `latest` and `beta` to that stable version. This - keeps users who install `@getpaseo/cli@beta` on the newest Paseo release after - a beta is promoted or superseded by a direct stable release. - ## Release version decision Every fresh release starts by classifying the full diff from the previous @@ -133,7 +191,7 @@ as described in **Fixing a failed release build**. Before running any stable release command: -- Make sure the resolved release source passed CI, the approved release inputs are committed locally on the intended branch, and the working tree is clean. +- Make sure the release source passed CI, the approved release inputs are committed locally on the release branch, and the working tree is clean. - **Run `npm run format`, `npm run lint`, and `npm run typecheck` and commit any resulting changes BEFORE you start any `release:*` command.** `release:check` runs `npm install --workspaces --include-workspace-root` as part of `release:prepare`, which can mutate `package-lock.json` (e.g. churning `"dev": true` markers on optional deps). The next step, `version:all:*`, runs `npm version` which aborts when the working tree is dirty. If this happens mid-flight you have to commit the lockfile churn before retrying — and the pre-commit format hook will reject a lockfile-only commit because oxfmt internally skips `package-lock.json` while lefthook's glob still matches it. Avoid the whole mess by running format/lint/typecheck first, then `release:prepare` once on its own to absorb any lockfile churn into a normal commit, then start the release. - Do not use a release command as a substitute for checking whether the current commit is actually ready. @@ -145,9 +203,9 @@ npm run release:minor This bumps the version across all workspaces, runs checks, publishes to npm, and pushes the branch + tag. The tag push triggers `Desktop Release`, `Android APK Release`, `Docker`, and `Release Notes Sync` on GitHub Actions. The workflows create the GitHub Release as a draft while builds and release-note sync run. EAS picks up the same tag via the EAS GitHub app and starts the iOS + Android store builds in parallel (see "Mobile builds (EAS)" below) — there is no mobile-release workflow under `.github/workflows`. -After the stable release succeeds, move npm's `beta` pointer to the new stable -version for every published package. This changes dist-tags only; do not -republish the packages: +After the stable release succeeds, check `npm view @getpaseo/cli dist-tags`. When the new stable +is newer than `beta`, move `beta` to it for every published package. This changes dist-tags only; +do not republish the packages: ```bash PASEO_VERSION=$(node -p "require('./package.json').version") @@ -156,8 +214,8 @@ for package in highlight relay protocol client plugin server cli; do done ``` -Verify both npm tags now resolve to `PASEO_VERSION` before considering the -stable release complete. +Verify `latest` resolves to `PASEO_VERSION`, and `beta` resolves to `PASEO_VERSION` or the +active newer beta, before considering the stable release complete. The Docker workflow builds images from the checked-out source tree on pull requests and on `main` as non-publishing checks. Stable `vX.Y.Z` tag pushes publish `ghcr.io/getpaseo/paseo:X.Y.Z` and `ghcr.io/getpaseo/paseo:latest`; beta `vX.Y.Z-beta.N` tag pushes publish only `ghcr.io/getpaseo/paseo:X.Y.Z-beta.N` and never move `latest`. @@ -175,7 +233,7 @@ npm run version:all:patch npm run version:all:minor npm run release:publish # Publish to npm npm run release:push # Push HEAD + tag (triggers CI workflows) -# Then move npm's beta dist-tag to this stable version using the command above. +# Then move npm's beta dist-tag to this stable version when it is newer than beta (see above). ``` ## Beta flow @@ -305,8 +363,8 @@ macOS 13 maps to Darwin 22. The two values use different version domains; do not iOS and Android store builds are not in `.github/workflows`. They are triggered by the EAS GitHub app the moment the `v*` tag is pushed: -- **Android (Play Store)** — EAS builds with profile `production` and auto-submits to the Play Store via `eas submit` (EAS-managed credentials, no Fastlane). -- **iOS (TestFlight + App Store)** — EAS builds with profile `production`, uploads once through a `testflight` job, distributes the build to the `Paseo Beta` external group with Beta App Review submission, and a Fastlane lane submits that same build for App Store review. +- **Android (Play Store)** — EAS builds with profile `production` and auto-submits to the Play Store via `eas submit` (EAS-managed credentials). A Fastlane lane then replaces the store screenshots. +- **iOS (TestFlight + App Store)** — EAS builds with profile `production`, uploads once through a `testflight` job, distributes the build to the `Paseo Beta` external group with Beta App Review submission, and a Fastlane lane uploads the store screenshots and submits that same build for App Store review. - **Android APK (GitHub Release asset)** — separate, via `.github/workflows/android-apk-release.yml`. This is the only Android-related workflow that lives in this repo. EAS uses the local app version source. `packages/app/app.config.js` derives the native version from the package version. Android `versionCode` is `major * 1_000_000 + minor * 1_000 + patch`. iOS reserves 1,000 build slots per app version: beta `N` uses slot `N`, and stable uses slot `999`. For example, `0.2.6-beta.2` appears in App Store Connect as version `0.2.6` build `2006002`; stable uses build `2006999`. Rebuilding the same tag produces the same native build number; if a store has already accepted a binary and you need a different binary, cut the next beta or patch instead of relying on EAS remote auto-increment. @@ -317,6 +375,17 @@ Stable iOS releases use one binary for two Apple review paths: Beta App Review f There is no mobile-release workflow under `.github/workflows`. The EAS GitHub app reads the workflows under `packages/app/.eas/workflows` and handles tag triggering directly. +### Store screenshots + +Each stable release publishes the screenshots committed under `assets/store-screenshots/output/` (see [its README](../assets/store-screenshots/README.md) for how they are made). To change the store screenshots, re-render and commit them before you tag. + +- **App Store:** `submit_review` uploads `output/apple/` and `output/apple-ipad/` to the version it submits, replacing that version's `en-US` screenshots. Apple ties screenshots to an app version, so a version that is already live keeps the ones it shipped with. `Resubmit iOS for App Store review` uploads them again. + - When `submit_review` fails with `appStoreVersions … is not in valid state`, the reason is in the API error's `meta.associatedErrors`, which fastlane does not print. Read it with a `POST /v1/reviewSubmissionItems` against the version. A required age-rating question that Apple added, such as `socialMedia`, fails this way; answer it under App Information > Age Rating in App Store Connect, then resubmit. +- **Google Play:** `upload_android_screenshots` runs `fastlane android upload_screenshots` after `submit_android`. It replaces only the `en-US` phone and 10-inch tablet screenshots, never the listing text or changelogs, and skips images whose checksum already matches. The lane stages only `en-US`: supply uploads every locale folder in one edit, and Play rejects F-Droid locales such as `ja`, which fails the whole edit. `Upload Google Play screenshots` reruns the step for the current release without a rebuild. +- **F-Droid:** reads the same files as Google Play. `fastlane/metadata/android/en-US/images/phoneScreenshots/` and `tenInchScreenshots/` hold symlinks to the Google renders. `render.mjs` rewrites them on every render, so added or renamed panels reach Google Play and F-Droid as well. + +Fastlane cannot use the Play key Expo stores for `eas submit`. The Play lane reads its own copy of the same service-account key from the `GOOGLE_PLAY_JSON_KEY` file secret in the EAS `production` environment, and that service account needs the Play Console permission **Manage store presence**. + ### Watching mobile builds from the terminal Use the EAS CLI from `packages/app/`: @@ -359,6 +428,7 @@ For the `Release Mobile` EAS workflow, these jobs must pass: - `submit_ios_for_review` — iOS build submitted for App Store review via Fastlane - `build_android` — Android store binary built - `submit_android` — Android binary submitted to the Play Store +- `upload_android_screenshots` — Google Play screenshots replaced from the repo Do not treat `build_ios: SUCCESS` or `distribute_ios: SUCCESS` as a completed iOS release. `submit_ios_for_review: FAILURE` means the iOS release is blocked even if the build is visible in TestFlight. @@ -477,7 +547,7 @@ git tag -f android-v0.1.28 HEAD && git push origin android-v0.1.28 --force git tag -f v0.1.29-beta.2 HEAD && git push origin v0.1.29-beta.2 --force ``` -This ensures the checkout ref matches the actual code on `main` with the fix included. +This ensures the checkout ref matches the code you want built, with the fix included. - `vX.Y.Z` or `vX.Y.Z-beta.N` rebuilds the full tagged release - `desktop-vX.Y.Z` rebuilds desktop for all desktop platforms only @@ -620,7 +690,7 @@ Rules: This returns every distinct GitHub login that authored or co-authored a commit in the PR. Use those logins for attribution. Fall back to `gh pr view N --json author` only if the commits command returns nothing (which should not happen for merged PRs). - When listing PR numbers, `git log --format='%H %s' v.. | grep -E '\(#[0-9]+\)$'` pulls the PR number out of squash commit subjects. + When listing PR numbers, `git log --cherry-pick --right-only --no-merges --format='%H %s' v... | grep -E '\(#[0-9]+\)$'` pulls the PR number out of squash commit subjects and skips commits the previous stable already shipped as cherry-picks. ## Changelog ordering @@ -652,11 +722,11 @@ Every entry covers `previous stable release → release source`: first beta, lat ### Beta release -- [ ] The resolved release source is the intended commit (default `origin/main`) and its existing CI is green +- [ ] The release base and changes match the [release base table](#release-base-and-source) and any approved [inventory](#release-inventory), and CI for the release source is green - [ ] Every PR in the release range has been opened, and its full description and every linked issue have been read before drafting the changelog - [ ] Fold this beta into the series' single `CHANGELOG.md` entry (heading `## X.Y.Z-beta.N - YYYY-MM-DD`, previous stable → release source), review it against the changelog policy, get approval, and commit it with its [`CHANGELOG.zh-CN.md` translation](#changelog-translations) before cutting the release - [ ] The diff from the previous stable to the resolved release source is classified as patch or minor, with the target version and rationale approved -- [ ] Release preparation stayed local until the approved release command pushed the complete branch and tag +- [ ] The changelog, ACP, lockfile, and version commits stayed local until the approved release command pushed the release branch and tag - [ ] `npm run release:beta:patch`, `npm run release:beta:minor`, or `npm run release:beta:next` completes successfully - [ ] Every GitHub Actions run for the complete release commit and tag is green - [ ] npm shows the version under the `beta` dist-tag, not `latest` @@ -667,22 +737,24 @@ Every entry covers `previous stable release → release source`: first beta, lat - [ ] GitHub `Docker` workflow is green and the versioned beta image is published without moving `latest` - [ ] GitHub `Release Notes Sync` mirrored the beta entry into the prerelease body - [ ] EAS `Release iOS Beta` completed its build, TestFlight distribution, external beta group, and Beta App Review path +- [ ] The [reconcile PR](#reconcile-main) brought the shipped changelog entries and version into `main` - [ ] The release heartbeat was created after the tag push and deleted only after every item above passed ### Stable release (or promotion) - [ ] Run the pre-release sanity check (see above) and address any findings - [ ] The diff from the previous stable to the resolved release source is classified as patch or minor, with the target version and rationale approved -- [ ] The resolved release source is the intended commit (default `origin/main`) and its existing CI is green +- [ ] The release base and changes match the [release base table](#release-base-and-source) and any approved [inventory](#release-inventory), and CI for the release source is green +- [ ] A promotion ships the tested beta's product content after its soak, unless the user explicitly overrode either default - [ ] Every PR in the release range has been opened, and its full description and every linked issue have been read before drafting the changelog - [ ] Ensure the approved release inputs are committed locally and the git worktree is clean before running any release command - [ ] Ensure local `npm run typecheck` passes on that exact commit before running any release command - [ ] Update `CHANGELOG.md` with user-facing release notes (features, fixes — not refactors). Promotion renames the series' `## X.Y.Z-beta.N` entry to `## X.Y.Z - YYYY-MM-DD` and re-checks it covers the full release. Commit the matching [`CHANGELOG.zh-CN.md` entry](#changelog-translations) with it - [ ] Verify the changelog heading follows strict `## X.Y.Z - YYYY-MM-DD` format -- [ ] Release preparation stayed local until the approved release command pushed the complete branch and tag +- [ ] The changelog, ACP, lockfile, and version commits stayed local until the approved release command pushed the release branch and tag - [ ] `npm run release:patch`, `npm run release:minor`, or `npm run release:promote` completes successfully - [ ] Every GitHub Actions run for the complete release commit and tag is green -- [ ] Move npm's `beta` dist-tag to the new stable version for every published package and verify both `latest` and `beta` resolve to it +- [ ] `latest` resolves to the new stable, and `beta` resolves to it too unless an active newer beta holds `beta` - [ ] The GitHub Release was published only after the three stable manifests were uploaded, and it has the changelog body and every expected macOS, Linux, Windows, and Android APK asset - [ ] GitHub `Desktop Release` workflow for the `v*` tag is green - [ ] The GitHub Release contains `latest-mac.yml`, `latest-linux.yml`, and `latest.yml` @@ -696,4 +768,5 @@ Every entry covers `previous stable release → release source`: first beta, lat - [ ] EAS iOS `submit_ios_for_review` succeeds, putting the build into App Store review - [ ] EAS Android `build_android` completes for the same tag - [ ] EAS Android `submit_android` succeeds, putting the build on its Play Store track +- [ ] The [reconcile PR](#reconcile-main) brought the shipped changelog entries and version into `main` - [ ] The release heartbeat was created after the tag push and deleted only after every item above passed diff --git a/docs/terminal-performance.md b/docs/terminal-performance.md index 3bb7c4d71c..c757d004ec 100644 --- a/docs/terminal-performance.md +++ b/docs/terminal-performance.md @@ -6,9 +6,9 @@ How terminal output stays low-latency, what the invariants are, and how to measu ``` pty (node-pty, forked worker process) - → headless xterm parse (worker, snapshot fidelity) - → TerminalOutputCoalescer (worker, ≤1 IPC message per 5ms per terminal) - → process.send IPC → daemon main process + → headless xterm parse (worker, ANSI replay fidelity) + → TerminalOutputCoalescer (worker, ≤1 socket frame per 5ms per terminal) + → framed local socket → daemon main process → TerminalOutputCoalescer (per client stream, terminal-session-controller.ts) → binary ws frame (2-byte header + raw bytes) → client decode (daemon-client.ts) → stream router → emulator runtime @@ -19,11 +19,15 @@ Terminal frames share the daemon main event loop with all agent traffic. The `ev ## Invariants (the easy-to-break ones) +- **Replay is incremental across the daemon and SDK.** Capable clients request their configured history, bounded by [worker retention](terminal-worker.md#process-model). Older apps retain their own 200-row request. Explicit SDK history demand is unchanged against older ANSI hosts, which apply their existing 500-row ceiling. Begin resets once, chunks keep a streaming UTF-8 decoder/parser, and each renderer suppresses generated replies while parsing replay. Never concatenate capable replay chunks to feed the renderer. +- **Replay serialization reads xterm directly.** The [worker](terminal-worker.md#process-model) uses its existing buffer; text capture translates only the requested rows, and readiness scans row strings. Do not rebuild a full cell-object grid. Serialization still allocates a whole ANSI string and UTF-8 bytes before bounded delivery; chunking does not bound those allocations. - **Coalescers are leading+trailing throttles.** The first chunk after an idle window flushes immediately (synchronously); only sustained bursts wait for the trailing timer. Reverting to trailing-only adds a full window (~5ms) to every keystroke echo. -- **Output coalescing happens in the worker, before IPC.** One `process.send` per pty chunk was a main-loop flood under build output. Non-output messages (snapshot/snapshotReady/titleChange/exit) must flush the coalescer first so ordering is preserved. +- **Output coalescing happens in the worker, before IPC.** One socket frame per pty chunk was a main-loop flood under build output. Non-output messages (snapshotReady/titleChange/exit) must flush the coalescer first so ordering is preserved. +- **Replay delivery is isolated per viewer.** Live worker output never waits for app delivery. Each daemon stream owns its bounded live tail and revision deduplication; a slow or failed replay cannot pause another viewer of the same terminal. +- **Replay geometry belongs to the parser queue.** Native measurements and web fits must leave the captured dimensions intact through every chunk's commit. Apply the latest measured size after replay, before live bytes; clear, replacement and disposal must release that geometry ownership. A layout effect must not resize the renderer directly during replay. - **Coalesced output carries the LAST chunk's revision.** Snapshot replay dedup (`replayTerminalOutputAfterSnapshot`) skips buffered output with `revision <= replayRevision`; a merged batch with a lower revision would be wrongly skipped (lost output). -- **The input-mode tracker runs once per process boundary, not per hop.** The worker owns the authoritative tracker; the daemon caches the replay preamble from `getTerminalState` responses and `snapshotReady` messages. Do not reintroduce a per-chunk `feed()` on the daemon main loop. -- **Snapshot catch-up is backpressure-gated.** A stream falls back to a full snapshot only when `outputBytesSinceSnapshot > MAX_TERMINAL_OUTPUT_FRAME_BYTES` (256KB) **and** the client transport reports `bufferedAmount > MAX_CLIENT_BUFFERED_BYTES` (4MB). A client that keeps draining streams continuously, no matter how much output is produced. Before this gate existed, every 256KB of build output dropped a frame and forced a full JSON cell-grid snapshot (~200k objects across IPC) — the historical source of spiky lag and GC hitches. +- **The input-mode tracker runs once per process boundary, not per hop.** The worker commits its authoritative tracker with xterm parsing before publishing the corresponding revision; the daemon caches current modes from ordered worker events and adoption. A replay response carries capture-time modes for its viewer; it must not overwrite the shared cache after newer live output. Apply that viewer's preamble before its buffered live bytes. Do not reintroduce a per-chunk `feed()` on the daemon main loop. +- **Snapshot catch-up is backpressure-gated.** After more than 256 KiB of output, a stream catches up only when its transport reports more than 4 MiB queued, or exposes no backpressure reading. A draining client streams continuously. Pressure recovery sends at most 500 recent history rows plus the screen, preserving smaller explicit demands including zero; even a live-only subscription needs this resynchronization. It does not change the subscription's configured demand: later attach/reconnect restores still request the full configured history. The recent window avoids repeatedly serializing all retained history for a slow viewer. - **Plugin daemon sessions report IPC queue bytes.** Their virtual socket increments `bufferedAmount` before `process.send` and decrements it only in the send callback. Text and binary frames share that ordered queue, so the normal snapshot catch-up and physical high-water gates remain valid for server-side plugin SDK traffic. - **Client output writes are not serialized per frame.** The emulator runtime drains contiguous plain writes straight into xterm (which buffers internally). Only barrier ops (`clear`, `snapshot`, `suppressInput` writes) wait — behind a zero-length sentinel write — so resets can't interleave with in-flight output. - **Find preserves the inspected xterm viewport, including at the live bottom.** Keep its output anchor inside the existing batched write path. Serializing output to preserve a search result would add terminal latency. diff --git a/docs/terminal-rendering.md b/docs/terminal-rendering.md new file mode 100644 index 0000000000..4c418595fc --- /dev/null +++ b/docs/terminal-rendering.md @@ -0,0 +1,75 @@ +# Terminal rendering + +Web and Electron draw terminals with xterm.js. iOS and Android keep an `@xterm/headless` buffer in JS and draw it with the `PaseoTerminal` native view in `packages/app/modules/paseo-terminal`: CoreText on iOS, `Canvas.drawTextRun` on Android. `src/terminal/native-renderer/terminal-frame.ts` turns the visible buffer into frames, and both native views take the same props. + +## xterm owns the grid + +xterm decides which column every cell occupies. The native views never let text advance move a cell. Each row is shaped once, one run per font face, so Hangul jamo, ligatures, combining marks, conjuncts and fallback fonts see their neighbours. Each shaped cluster is then drawn at its first cell's column, centred in the columns it owns, and scaled down when its glyphs are wider. Cursor, selection, hit-testing and copy all use xterm's columns, so they stay correct whatever the font does. + +A cluster is the run of cells the shaper merged, and it is drawn once from the shaped row. xterm usually keeps a conjunct in one cell (see [Character widths](#character-widths)), but a colour change inside it leaves `क्` and `ष` in separate cells that still shape together. Drawing part of a cluster on its own reshapes it: the conjunct comes apart into `क्` with a visible virama. So colour and selection never split a cluster. A cluster whose cells differ in colour is drawn once per colour, clipped to that colour's columns. + +Android also groups cells with `android.icu.text.BreakIterator`, because Minikin's advances and cursor boundaries alone split some clusters that span cells. Grouping only merges whole cells, so a conjunct xterm keeps in one cell cannot be split by the OS. Grapheme rules follow the OS ICU version, and we accept that to avoid bundling approximately 14 MB of ICU4J data. Before the buffers used grapheme widths, Android 10 (API 29) split `स्ते` across its two cells. This renderer does not guarantee identical shaping across OS versions. + +`TerminalRowLayoutTest.kt` is the Android regression test. It draws the rows of `grapheme-rows.json` and compares each with its grapheme clusters drawn one at a time, and with a wrong clustering that must not match. `terminal-frame.test.ts` checks that those rows are what xterm produces and that the clusters are UAX #29 grapheme clusters. Run it with `./gradlew :paseo-terminal:connectedDebugAndroidTest` from `packages/app/android`, with `ANDROID_SERIAL` set. + +The view reports ready only after it has measured its grid size. The pane attaches with that size, so the daemon replays the terminal at the client's size. Before this, the replay arrived at the PTY's old size, the resize came after it, and the shell's redraw landed on the wrong rows. + +## Character widths + +The daemon, native and web buffers all load `@xterm/addon-unicode-graphemes`: the daemon through `packages/server/src/terminal/headless-terminal.ts`, native in `createNativeHeadlessTerminal`, web in `terminal-emulator-runtime.ts`. Each emoji cluster takes one two-column cell, including VS16 (`❤️`), skin tones (`👋🏽`), flags (`🇰🇷`) and ZWJ sequences (`👨‍👩‍👧`). That is the width colour-emoji fonts draw at. Under xterm's default Unicode 6 table `😀` got one column, and the native views scaled it to half size to fit. + +Every buffer must use the same table. The daemon answers cursor-position reports (`CSI 6n`) from its buffer, and a client re-parses the daemon's ANSI replay with its own table. A disagreement moves the cursor and the later cells of any row that holds a disputed cluster: after replay from a Unicode 6 daemon, the cursor that followed `A😀😀😀B` lands inside the third emoji. + +Daemons that use grapheme widths advertise `server_info.features["terminal-grapheme-widths"]`. `terminal-pane.tsx` reads it once and passes `characterWidths` to the emulator. Against an older daemon the app keeps each renderer's previous table: xterm's default on native, Unicode 11 on web. An older app against a newer daemon cannot match it, because every client shares the daemon's one buffer. A terminal kept by a worker from an unreleased pre-grapheme build keeps that worker's table until it exits. + +The table follows Unicode grapheme clusters, as Node's `string-width` does for Ink-based agent TUIs. Indic conjuncts follow the same rule: `क्ष` and `स्ते` take one column, and the native views scale them down to fit it. Shells measure with the C library's `wcwidth` instead. glibc counts `❤️` as one column, `👋🏽` as four and `क्ष` as two, so a line editor that measures those disagrees with the terminal. + +Use `@xterm/addon-unicode-graphemes` 0.5.0-beta.330 or later. Earlier versions read their width table from the wrong offset when Node decodes it into a pooled `Buffer`, which gives wrong widths or a load error depending on earlier allocations. `headless-terminal.test.ts` forces that case in a fresh process. + +## Ink outside the row + +Marks stacked above or below a letter, Arabic letter tails and some fallback glyphs ink into the rows next to theirs. Neither view clips a row to its own bounds, because a row clip also cuts marks and Arabic dots. Rows draw top to bottom, so a later row's cell backgrounds cover the ink that reaches into it. + +Android redraws every row on each frame, so overhanging ink cannot go stale. Its row `RenderNode`s are created with `setClipToBounds(false)`. The default would clip only unselected rows, because selected rows are drawn straight onto the view's canvas. + +iOS repaints only the rows that changed. Each `TerminalRowLayout` records how far its glyphs ink above and below the row. A changed row invalidates its old and new ink extent, and `draw(_:)` redraws every row whose ink extent meets the dirty rect. Invalidating only the row's own rect left an erased row's marks in the row next to it, erased a neighbour's marks when a row was rewritten, and showed or hid overhang depending on which rows changed together. + +## Mixed-direction text + +Rows draw left to right in logical order on both platforms. Terminal bidi escape modes are not implemented. On iOS the row needs both the `kCTWritingDirection` override and an LTR paragraph base direction. Without the base direction, bidi rule L1 moves trailing spaces ahead of a row that starts with Arabic or Hebrew, and the whole row shifts. + +Arabic still gets the contextual form its logical neighbours select, but in left-to-right order, so letters join on the wrong side. Correct visual Arabic needs implicit bidi per row: reorder RTL runs for display and map cursor, selection and hit-testing through the visual-to-logical index. That changes which column a character appears in, so it has to be decided as product behaviour first. Shaping alone cannot fix it. + +## Render regression + +The scripts live in `packages/app/e2e/mobile/terminal-rendering`. Run them from `packages/app` on the daemon's host, starting from an idle, focused terminal with an empty prompt. + +`render.mjs` prints a mixed-script fixture, screenshots it with agent-device, and checks the geometry with `check.mjs`. The check rebuilds the expected buffer with `@xterm/headless` and measures the grid from a ruler row. It checks that: + +- every grapheme cluster has ink inside its own columns, and blank cells stay blank; +- on the accent rows, every cell is drawn in its own colour, including cells inside one cluster; +- the cursor is drawn after the text; +- every row is exposed as `terminal-row-`; +- selecting one cell of a conjunct highlights only that cell. + +On iOS the screenshot is taken at 3 pixels per point (`PASEO_TERMINAL_RENDERING_PIXEL_DENSITY`), because the simulator's default is one pixel per point and a glyph is then about 12 pixels. Focus the terminal before a run: with the simulator's hardware keyboard connected the key bar shows without a focused input, and `type` fails. In a debug build, the dev client's floating gear button covers the right end of the first row, so ruler cells there fail. + +```bash +PLATFORM=android ANDROID_SERIAL=emulator-5554 node e2e/mobile/terminal-rendering/render.mjs +PLATFORM=ios IOS_DEVICE="iPhone 17" node e2e/mobile/terminal-rendering/render.mjs +``` + +Geometry passes when a cell holds the wrong glyph. `identity.mjs` judges each cluster of a `render.mjs` run against pango's rendering of the same characters in the device's fonts. The reference is cut at the edges of the cluster's columns, placed as the renderer places it, because glyphs such as Devanagari letters ink past their advance and the device cuts them there too. A shape passes when its coverage correlates with its own reference at 0.6 or more, and no other cluster of the corpus matches it better. Box and block characters are judged against their Unicode definition. Shades are judged by even density over a 4×4 grid, because the device and pango fall back to different shade fonts. Clusters that pango draws without ink are reported as unjudged instead: flags on both platforms and Apple Color Emoji. The `rect` and `swap` controls fill every cluster with white, or judge each one against another cluster. Both must fail every cluster, which shows the oracle refuses ink that is present but wrong. An Arabic letter is compared with all four of its positional forms, so the oracle shows the right letter is drawn, not that it has the right form. Ink that a neighbouring row draws into a cluster's cells counts as that cluster's ink. On iOS the tail of `م` in the Arabic row reaches one pixel into the `न` below it, so `न` fails although both rows are drawn correctly. + +```bash +FONTCONFIG_FILE=fonts.conf node e2e/mobile/terminal-rendering/identity.mjs [none|rect|swap] +``` + +`fonts.conf` points fontconfig at the device's font files and lists, for `monospace`, the terminal font followed by the device's fallbacks for Hangul, Arabic, Devanagari, CJK, emoji and symbols: + +- **Android:** pull the fonts from `/system/fonts` with `adb pull`. The terminal font is Droid Sans Mono. +- **iOS:** copy the simulator runtime's fonts from `RuntimeRoot/System/Library/Fonts`. The terminal font is Menlo. PingFang stores its outlines in Apple's `hvgl` table, which FreeType cannot draw, so the CJK references come from Apple SD Gothic Neo instead. `語` then scores below the threshold although the device draws it correctly. + +`overhang.mjs` prints rows whose marks reach the rows next to them. In one update it writes into two rows that hold a neighbour's marks and erases two rows whose marks reach a blank row. The marks must be drawn before the update, stay drawn in the written rows, and leave no ink behind the erased rows. Run it like `render.mjs`. + +`reattach.mjs` checks the restore size. It changes the PTY size by opening the keyboard (`RESIZE=keyboard`) or folding an Android foldable (`RESIZE=fold`), relaunches the app, and compares the client's rows with `paseo terminal capture`. A trial where no terminal rows appear, for example after a launch crash, counts as never attached and fails the run. diff --git a/docs/terminal-worker.md b/docs/terminal-worker.md new file mode 100644 index 0000000000..be9321fb4f --- /dev/null +++ b/docs/terminal-worker.md @@ -0,0 +1,83 @@ +# Terminal worker + +Every terminal's PTY lives in the terminal worker, a process separate from the daemon. The worker outlives the daemon, so restarts, crashes and upgrades keep terminals running. This doc covers what the code can't tell you: why the process model is shaped this way, the rules nothing enforces, and the known limits. + +## Process model + +``` +supervisor (paseo.pid) ──► daemon worker ──► launcher ──► terminal worker ──► PTY programs + exits (re-parented to init) +``` + +- The daemon starts the worker through a launcher (`terminal-worker-process.ts --launch`). The launcher spawns the worker `detached`, waits for `ready` on fd 3, prints the pid and exits, so the worker is re-parented and leaves the daemon's process tree. The supervisor's forced kill uses `tree-kill`, which walks parent pids: a worker that stayed a child, even detached, would die with a hung daemon. +- The worker talks to one daemon at a time over a local socket (named pipe on Windows). Losing the daemon means "no controller", not exit: PTYs keep running, events are dropped, and the headless terminal keeps the screen for the next daemon's `listTerminals`. +- A socket disconnect triggers reconnection to the same worker and a screen replay. Only confirmed process death retires its sessions; the next terminal creation shares one replacement launch. Dead-worker cleanup stays scoped to that worker, so a healthy draining peer keeps running. Shutdown and detach suppress recovery. +- The worker exits on its own when it has no controller and no terminals, on `shutdown`, on SIGTERM (killing its terminals), and when its record disappears (a deleted `$PASEO_HOME`: nobody can ever reach it again). +- Its stderr goes to `$PASEO_HOME/terminal-worker.log`. No pipe to the daemon survives the daemon. + +The worker retains a fixed 10,000 history rows plus the screen in its existing xterm. Replay uses `@xterm/addon-serialize` 0.14 against headless xterm 6; no second cell grid or lifetime byte log is retained. The serializer boundary owns cursor position, visibility and explicit program-selected presentation; the addon alone does not preserve all three. An unset program style leaves each client’s configured cursor defaults intact. Standard modes come from the serializer; the existing input-mode tracker retains protocol modes such as Kitty and Win32 input. Commit that tracker with parsed output so replay bytes and metadata describe the same cut. + +Which triggers keep terminals and which close them is owned by the stop reason (`keepTerminals`) that flows from the request through the supervisor to `stop()`. The kill side always ends in the reaper (`terminal-worker-reaper.ts`), the only path that signals terminal processes outside a connected daemon. + +## Record, socket and secret + +The worker writes `$PASEO_HOME/terminal-worker/.json` (owner-only) with its identity (birth time + command line carrying `--paseo-terminal-worker `), protocol version, socket path, a random secret, the copy it runs from, and each terminal program's pid and birth time. + +- The first frame on the socket must be `hello` with the secret; anything else closes the connection. Anyone who connects can type into every shell, so the record is `0600`, the unix socket `0600` in a `0700` directory. +- Unix socket paths have a byte budget (103 on macOS, 107 on Linux). Dev homes under worktrees blow it, so `terminal-worker-socket-path.ts` tries `$PASEO_HOME/terminal-worker/sock/`, then `$TMPDIR/paseo-/`, then `/tmp/paseo-/`, and accepts an existing directory only if it is a real `0700` directory owned by you. It never chmods a shared root. +- Cleanup signals a process only when its birth time matches the record. Birth times come from `ps -o lstart` with `LC_ALL=C` (it follows `LC_TIME` otherwise) and from `Win32_Process.CreationDate`. A missing birth time is "unknown", never matched by command text: a shell that ran `exec` keeps its pid and birth time but not its argv. +- A kill cleanup that cannot confirm every process gone writes `closing-.json` beside the worker record. The worker rewrites its own record whenever a terminal starts or exits, so the kill intent has to live in a file it never writes. A closing record is never adopted; the next stop or start retries it. +- An unreadable record of either kind makes `daemon status` and a kill restart fail with its path: a kill cleanup that met it could not check what it names, and leaves nothing else behind. A read that fails with `EPERM`, `EBUSY` or `EACCES` is retried for 250ms first: on Windows, opening a record while the worker renames its new copy over it fails that way for a moment. + +## Protocol versions + +`TERMINAL_WORKER_PROTOCOL_VERSION` (`terminal-worker-protocol.ts`) is bumped whenever a request, response or event changes shape. A daemon classifies each live worker at start: + +| Worker reports | Daemon does | +| ---------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | +| its own version | adopts it | +| one version older | adopts it to drain: it keeps its terminals, takes no new ones, and is let go after its last terminal exits | +| two or more older | shuts it down; its terminals close (logged) | +| newer, or a version it cannot read | leaves it running, undriven; `list_terminals` and `create_terminal` answer `rpc_error` `terminal_worker_incompatible`, and `paseo daemon status` prints why | + +Never more than two workers run. A new worker launches only when none is current, none is incompatible and fewer than two run. The count comes from the records, so an unreachable or unidentified worker counts, and so does one a cleanup could not confirm gone. When two run, the daemon starts with no current worker, and the first terminal created after one of them exits launches it. + +**The frozen envelope never changes across versions:** the frame format (4-byte length + `v8.serialize`), `hello`/`helloAck`, the `listTerminals` info fields and `shutdown`. That is what lets any daemon close any worker: a kill stop sends `shutdown` to a newer worker it cannot otherwise drive. Protocol 5 hard cuts unreleased protocols 1 through 4, including the acknowledgement-based replay contract: those workers are obsolete and close. For future versions, keep a previous-version adapter so the draining worker can still be driven, and drop the adapter for the version before that. + +Tests stand up other versions with `PASEO_TERMINAL_WORKER_PROTOCOL_OVERRIDE`, read by the worker. It is test-only. + +## Display replay + +The worker keeps the headless xterm model and generates ANSI. A replay request emits begin metadata (dimensions, retained history, revision and input modes), at most 64 KiB per data chunk, and end. Live output keeps flowing independently during replay. Capture is synchronous with PTY callbacks; flush the output coalescer before the cut so a later batch never includes bytes already in replay. Retained-history metadata counts the worker history before the request limit. + +ConPTY renders a console rather than forwarding every program escape sequence unchanged. A program write callback does not establish that its hidden cursor move or input modes reached the worker. Test exact ANSI fidelity at the serializer boundary; PTY integration compares the initial replay plus committed observed output at the capture cut, including startup modes. + +The worker paces replay writes on its local socket; the daemon synchronously queues each event into the application's bounded transport. App network delivery does not extend the worker's request deadline. There is no per-chunk acknowledgement or second replay delivery queue in the daemon. The physical application transport owns its 64 MiB high-water close, so a backed-up app cannot hold worker capture open. Each daemon viewer still holds at most 4 MiB of live output during capture, then drops revisions already present in the worker replay. Capture failure and tail overflow affect only that viewer; PTYs and healthy viewers keep running. + +Live traffic that fills the shared worker socket beyond 4 MiB disconnects the stalled controller. Reconnection adopts the surviving sessions and requests fresh replay for existing streams. Readiness does not require a revision: adoption announces readiness without one, while the replay capture supplies the revision used for deduplication. + +The SDK advertises `terminal_chunked_replay` only because it decodes begin/data/end. Capable clients receive these events directly; the daemon collects one Restore frame only for older ANSI clients. The SDK normalizes an older host's single Restore into the same lifecycle. Capture stays a worker request; bootstrap readiness uses `hasOutput`, not a transported grid. + +## Running from its own copy + +A worker outlives the installation that started it. An npm or desktop update replaces that installation's files, and the next terminal the old worker creates would load node-pty's `spawn-helper` and the zsh integration from paths that no longer exist. So a built daemon does not launch the worker from its install: + +- `npm run build` bundles the worker with esbuild (`packages/server/scripts/build-terminal-worker.mjs`) into `dist/server/terminal-worker/` with its `shell-integration/` beside it. Only node-pty stays external. A package loaded through a module-local `createRequire` is invisible to esbuild and would be missing at run time; `terminal-worker-runtime.test.ts` fails if the bundle loads anything but built-ins and node-pty. +- Before launching, the daemon copies the bundle, the shell integration and node-pty (this platform's native build only) into `$PASEO_HOME/terminal-worker/-/` and launches from there. The hash covers the bundle and node-pty, so a local rebuild of the same version gets its own copy. +- A copy is deleted once no record names it: after a draining worker exits, after a kill cleanup, and at daemon start. The daemon and the reaper delete copies, never the worker itself, so a worker exiting cannot remove a copy a new worker is about to launch from. +- Dev (`.ts` source) launches from source and copies nothing. + +Each create carries the controlling daemon's environment and Paseo CLI path (`baseEnv`, `paseoCliPath`), so a terminal opened after an upgrade gets the new installation's `PASEO_CLI` while older terminals keep theirs. + +## Desktop + +Desktop app updates and version-mismatch restarts stop the daemon with "keep terminals" on macOS and Linux, through `daemon stop --keep-terminals` (the shutdown RPC; SIGTERM always means "stop and close"). A daemon that predates the feature cannot keep terminals: the CLI refuses before sending anything, and desktop logs that and stops it with its terminals closed. + +On Windows every desktop stop closes terminals. In the desktop app the worker runs as `Paseo.exe` with `ELECTRON_RUN_AS_NODE`, and a surviving one would lock the install folder the NSIS update replaces. Restarts, crashes and npm self-updates keep terminals on Windows too. + +## Known limits + +- On macOS `ps` has no session id, so a HUP-ignoring child of a shell that had already exited before cleanup started (re-parented to launchd) is not found. Linux reaches it through the session; a program that `exec`s keeps its entry on every OS. +- On Linux, a member of a gone shell's session is signaled only if its environment carries that terminal's `PASEO_TERMINAL_ID`. A job that scrubbed its environment (`env -i`) is reported as unconfirmed, with its pid, and never signaled. +- The agent-hook activity URL is baked into each shell when it starts. If the daemon's listen address changes across a restart, older shells report to the old address. +- Restoring terminals after a reboot is out of scope: records from an earlier boot are retired without signaling anything. diff --git a/docs/timeline-sync.md b/docs/timeline-sync.md index 118ad628ce..3d6af249bf 100644 --- a/docs/timeline-sync.md +++ b/docs/timeline-sync.md @@ -10,16 +10,27 @@ then replaces the previous tool state or merges into the current text item. Inte are never retained for history or catch-up. Provider history is the durable transcript authority and rebuilds the projection when an agent resumes. +Pagination bounds each read, not total resident history. Active and idle agents retain their +projected transcript; archive releases it and later history reads rebuild it from the provider. +Streaming overhead must remain proportional to the retained transcript. Cumulative text snapshots +must be released after their deltas have been consumed. + The invariants are: > A continuously subscribed client applies every committed row in order. Opening or resuming an -> agent establishes the daemon's current tail in one bounded request, with older history reachable +> agent establishes the daemon's current tail in one complete-turn request, with older history reachable > through backward pagination. -Tool output is bounded before it enters either delivery path. Canonical shell tool output is sliced -to 64 KiB, and the same bounded item is used for runtime timeline rows and live stream events. -Provider history hydration applies the same rule so reopening an agent cannot restore an oversized -tool payload. +Every item is bounded before it enters either delivery path, because a timeline page is one +WebSocket message and the daemon closes a socket whose outbound buffer passes 64 MiB. Tool calls get +64 KiB and other items 256 KiB. Over budget, the largest strings are cut to a shared length with a +`…[truncated 12.3 MB]` marker, and an oversized `data:` URL is replaced by the marker. Strings up +to 1 KiB stay whole, so ids and paths survive. Arrays drop their trailing elements without a marker +element, so typed arrays still match the wire schema. Limiting an item twice gives the same item. The +budget does not bound wide objects or multi-byte text. The same +bounded item is used for runtime timeline rows and live stream events. Provider history hydration +applies the same rule so reopening an agent cannot restore an oversized payload. Fetches apply it +again to assistant and reasoning rows the projection merges from many chunks. ## Presence is not delivery @@ -44,7 +55,21 @@ recovery is complete only when `hasNewer: false`. Initialization timeouts guard lack of catch-up progress, not the full multi-page sync. A successful page that queues the next `after` page refreshes the watchdog. -Opening or resuming an agent fetches one bounded latest tail page. Older history remains +Opening or resuming an agent fetches the latest available turns with a soft target of 40 +projected items. Backward pages and prompt-jump windows also include whole turns, including +all currently available rows of an active run. There is no per-turn cap: a large run can +exceed the target. Local history mounting uses the same boundaries so revealing older rows +does not change the collapse state of a turn already displayed. + +`wholeTurns` is a preference negotiated once at the client fetch boundary. Hosts advertising +`features.wholeTurnTimeline` receive it; other hosts receive the existing item-based request. +Reading history remains available on older hosts, whose pages can still split turns. Forward +catch-up stays incremental, but its reset snapshot honors a supported whole-turn request. +Source coverage still includes interleaved tool updates. + +Canonical IDs define runs. With missing IDs, human prompts, heartbeats and typed received +agent messages each start a fallback turn. This deterministic fallback is shared by paging +and presentation; it cannot recover historical batching or steering. Older history remains user-driven by scrolling upward. A failed catch-up or subscription reconcile retries on its own, doubling from 1s to a 30s ceiling. @@ -149,12 +174,13 @@ range describes those exact items: `startSeq` drives older pagination and `endSe catch-up. The owner requests `after endSeq`, and requests `before startSeq` when the user loads older history. Code outside the owner does not distinguish cached and network timelines. -The first resume request is bounded. If it reports more newer history, fetch one latest bounded tail +The first resume request is bounded. If it reports more newer history, fetch one latest complete-turn tail instead of replaying every missed page. Live gap recovery still pages forward until current. -If the canonical window exceeds the cache item limit, contains a discontiguous retained range, has a +If the canonical window exceeds the cache item target, contains a discontiguous retained range, has a live head, or includes presentation data the cache cannot encode losslessly, persistence drops the -range and keeps a display-only tail. Never slice items while retaining the pre-slice range; that +range and keeps a display-only tail of complete available turns. The item target is soft; +the byte budget still evicts entire cache rows. Never slice items while retaining the pre-slice range; that falsely certifies discarded source rows. A display-only row paints without granting synchronization authority, so the owner uses the ordinary bounded `tail` bootstrap. @@ -238,11 +264,11 @@ foreground control ownership remains a separate daemon concern. Cancellation req with that record rather than in a React component, so an old request cannot clear a newer one. Submissions remain a separate pre-turn registry and retire on canonical acknowledgement. -Canonical turns and visible responses are different boundaries. Agent-originated prompts and lifecycle -notifications project into tool rows, so they do not create a human-message boundary. Legacy system -prompts, including schedule injections, remain hidden. One visible response can span several canonical -turns; layout and copy group that response together while lifecycle, timing, tool sequences, and exact -fork positions retain the canonical `turnId` boundaries. +Every canonical run owns a visible turn, including heartbeats and agent notifications. +Notifications delivered during a run stay inside it; batched notifications share the run +that starts or accepts them. Received messages retain sender attribution, while lifecycle +notifications remain visible events. Collapse, timing and locally mounted history share +these boundaries. Agent-message XML belongs to the daemon's `agent/agent-messages` boundary. Prompt delivery encodes provenance; acceptance, provider echoes, import, and replay share its projection. The delivery ID is diff --git a/docs/unistyles.md b/docs/unistyles.md index 3daae333df..6be82f70b0 100644 --- a/docs/unistyles.md +++ b/docs/unistyles.md @@ -358,6 +358,14 @@ export to `src`, but browser and Electron Metro resolve its `browser` export to `lib/module`; CommonJS consumers use `lib/commonjs`. A source-only patch leaves Electron running the old code. +The adaptive-theme patch keeps `colorScheme` reads off the media-query lists +owned by Unistyles' change listeners. Chromium defers their events while a window +is hidden; reading `matches` on those same lists can consume the pending change. +CSS variables then follow the OS theme while `withUnistyles` props retain the old +colors. Keep this patch until upstream reads the scheme through separate lists. +The desktop browser E2E checks both transition directions in an isolated Electron +process, because Playwright's focus emulation prevents real hidden-page behavior. + Register every dependency patch in `scripts/postinstall-patches.mjs`. A file in `patches/` is inert unless that script knows which installed package activates it. diff --git a/fastlane/metadata/android/en-US/changelogs/140001.txt b/fastlane/metadata/android/en-US/changelogs/140001.txt new file mode 100644 index 0000000000..32cf0aa48b --- /dev/null +++ b/fastlane/metadata/android/en-US/changelogs/140001.txt @@ -0,0 +1,10 @@ +Plugins can now add tools to individual agents and configure their MCP servers when sessions open. + +Completed conversation turns can be collapsed into summaries and expanded to read the full exchange. + +Voice settings now let you configure speech providers and download local models with one tap, including SenseVoice and Whisper for Chinese dictation. Voice mode is now opt-in. + +Added +- Let plugins give tools to specific agents + +Full notes: https://paseo.sh/changelog diff --git a/fastlane/metadata/android/en-US/changelogs/140002.txt b/fastlane/metadata/android/en-US/changelogs/140002.txt new file mode 100644 index 0000000000..32cf0aa48b --- /dev/null +++ b/fastlane/metadata/android/en-US/changelogs/140002.txt @@ -0,0 +1,10 @@ +Plugins can now add tools to individual agents and configure their MCP servers when sessions open. + +Completed conversation turns can be collapsed into summaries and expanded to read the full exchange. + +Voice settings now let you configure speech providers and download local models with one tap, including SenseVoice and Whisper for Chinese dictation. Voice mode is now opt-in. + +Added +- Let plugins give tools to specific agents + +Full notes: https://paseo.sh/changelog diff --git a/fastlane/metadata/android/en-US/changelogs/140003.txt b/fastlane/metadata/android/en-US/changelogs/140003.txt new file mode 100644 index 0000000000..32cf0aa48b --- /dev/null +++ b/fastlane/metadata/android/en-US/changelogs/140003.txt @@ -0,0 +1,10 @@ +Plugins can now add tools to individual agents and configure their MCP servers when sessions open. + +Completed conversation turns can be collapsed into summaries and expanded to read the full exchange. + +Voice settings now let you configure speech providers and download local models with one tap, including SenseVoice and Whisper for Chinese dictation. Voice mode is now opt-in. + +Added +- Let plugins give tools to specific agents + +Full notes: https://paseo.sh/changelog diff --git a/fastlane/metadata/android/en-US/changelogs/140004.txt b/fastlane/metadata/android/en-US/changelogs/140004.txt new file mode 100644 index 0000000000..32cf0aa48b --- /dev/null +++ b/fastlane/metadata/android/en-US/changelogs/140004.txt @@ -0,0 +1,10 @@ +Plugins can now add tools to individual agents and configure their MCP servers when sessions open. + +Completed conversation turns can be collapsed into summaries and expanded to read the full exchange. + +Voice settings now let you configure speech providers and download local models with one tap, including SenseVoice and Whisper for Chinese dictation. Voice mode is now opt-in. + +Added +- Let plugins give tools to specific agents + +Full notes: https://paseo.sh/changelog diff --git a/fastlane/metadata/android/en-US/images/phoneScreenshots/1.png b/fastlane/metadata/android/en-US/images/phoneScreenshots/1.png index 9f633ca58f..ca3a9fa2a8 120000 --- a/fastlane/metadata/android/en-US/images/phoneScreenshots/1.png +++ b/fastlane/metadata/android/en-US/images/phoneScreenshots/1.png @@ -1 +1 @@ -../../../../../../packages/website/public/phone-1.png \ No newline at end of file +../../../../../../assets/store-screenshots/output/google/01-sidebar.png \ No newline at end of file diff --git a/fastlane/metadata/android/en-US/images/phoneScreenshots/2.png b/fastlane/metadata/android/en-US/images/phoneScreenshots/2.png index 6d2fbd14d7..a0748cf426 120000 --- a/fastlane/metadata/android/en-US/images/phoneScreenshots/2.png +++ b/fastlane/metadata/android/en-US/images/phoneScreenshots/2.png @@ -1 +1 @@ -../../../../../../packages/website/public/phone-2.png \ No newline at end of file +../../../../../../assets/store-screenshots/output/google/02-chat.png \ No newline at end of file diff --git a/fastlane/metadata/android/en-US/images/phoneScreenshots/3.png b/fastlane/metadata/android/en-US/images/phoneScreenshots/3.png index e23c27ced5..0e7dba6b41 120000 --- a/fastlane/metadata/android/en-US/images/phoneScreenshots/3.png +++ b/fastlane/metadata/android/en-US/images/phoneScreenshots/3.png @@ -1 +1 @@ -../../../../../../packages/website/public/phone-3.png \ No newline at end of file +../../../../../../assets/store-screenshots/output/google/03-plugins.png \ No newline at end of file diff --git a/fastlane/metadata/android/en-US/images/phoneScreenshots/4.png b/fastlane/metadata/android/en-US/images/phoneScreenshots/4.png new file mode 120000 index 0000000000..e89becb9bc --- /dev/null +++ b/fastlane/metadata/android/en-US/images/phoneScreenshots/4.png @@ -0,0 +1 @@ +../../../../../../assets/store-screenshots/output/google/04-review.png \ No newline at end of file diff --git a/fastlane/metadata/android/en-US/images/phoneScreenshots/5.png b/fastlane/metadata/android/en-US/images/phoneScreenshots/5.png new file mode 120000 index 0000000000..c067990032 --- /dev/null +++ b/fastlane/metadata/android/en-US/images/phoneScreenshots/5.png @@ -0,0 +1 @@ +../../../../../../assets/store-screenshots/output/google/05-terminal.png \ No newline at end of file diff --git a/fastlane/metadata/android/en-US/images/tenInchScreenshots/1.png b/fastlane/metadata/android/en-US/images/tenInchScreenshots/1.png new file mode 120000 index 0000000000..401053965e --- /dev/null +++ b/fastlane/metadata/android/en-US/images/tenInchScreenshots/1.png @@ -0,0 +1 @@ +../../../../../../assets/store-screenshots/output/google-tablet/01-sidebar.png \ No newline at end of file diff --git a/fastlane/metadata/android/en-US/images/tenInchScreenshots/2.png b/fastlane/metadata/android/en-US/images/tenInchScreenshots/2.png new file mode 120000 index 0000000000..2454381850 --- /dev/null +++ b/fastlane/metadata/android/en-US/images/tenInchScreenshots/2.png @@ -0,0 +1 @@ +../../../../../../assets/store-screenshots/output/google-tablet/02-chat.png \ No newline at end of file diff --git a/fastlane/metadata/android/en-US/images/tenInchScreenshots/3.png b/fastlane/metadata/android/en-US/images/tenInchScreenshots/3.png new file mode 120000 index 0000000000..1b31012051 --- /dev/null +++ b/fastlane/metadata/android/en-US/images/tenInchScreenshots/3.png @@ -0,0 +1 @@ +../../../../../../assets/store-screenshots/output/google-tablet/03-plugins.png \ No newline at end of file diff --git a/fastlane/metadata/android/en-US/images/tenInchScreenshots/4.png b/fastlane/metadata/android/en-US/images/tenInchScreenshots/4.png new file mode 120000 index 0000000000..13d8545d92 --- /dev/null +++ b/fastlane/metadata/android/en-US/images/tenInchScreenshots/4.png @@ -0,0 +1 @@ +../../../../../../assets/store-screenshots/output/google-tablet/04-review.png \ No newline at end of file diff --git a/fastlane/metadata/android/en-US/images/tenInchScreenshots/5.png b/fastlane/metadata/android/en-US/images/tenInchScreenshots/5.png new file mode 120000 index 0000000000..b0905beafc --- /dev/null +++ b/fastlane/metadata/android/en-US/images/tenInchScreenshots/5.png @@ -0,0 +1 @@ +../../../../../../assets/store-screenshots/output/google-tablet/05-terminal.png \ No newline at end of file diff --git a/nix/desktop-package.nix b/nix/desktop-package.nix index 00ed6cd926..48cbd9bbb7 100644 --- a/nix/desktop-package.nix +++ b/nix/desktop-package.nix @@ -127,7 +127,7 @@ buildNpmPackage { # The Nix output is not a distributable DMG, so leave it unsigned and # disable the hardened runtime that requires a matching signature. CSC_IDENTITY_AUTO_DISCOVERY=false \ - ../../node_modules/.bin/electron-builder \ + npm exec --offline -- electron-builder \ --config electron-builder.yml \ --dir \ --mac \ diff --git a/nix/npm-deps.hash b/nix/npm-deps.hash index 3e19f893c2..7e151568f6 100644 --- a/nix/npm-deps.hash +++ b/nix/npm-deps.hash @@ -1 +1 @@ -sha256-eNiKmiZ3XXZMRZRSoGxUbMn2RtY6AX079vUatBYM+qE= +sha256-KN/AVZV/o0TleLLpmggSrdJqjFDJ/NJYVHiC54xb4jQ= diff --git a/package-lock.json b/package-lock.json index 847bd24eb7..dbb64e68a4 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "paseo", - "version": "0.13.2", + "version": "0.15.0-beta.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "paseo", - "version": "0.13.2", + "version": "0.15.0-beta.1", "hasInstallScript": true, "license": "Apache-2.0", "workspaces": [ @@ -30,6 +30,7 @@ "concurrently": "^9.2.1", "cross-env": "^10.1.0", "electron": "44.2.0", + "expo-module-scripts": "^5.0.8", "get-port-cli": "^3.0.0", "js-yaml": "^4.1.1", "knip": "^5.82.1", @@ -980,7 +981,7 @@ "version": "7.8.4", "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-async-generators/-/plugin-syntax-async-generators-7.8.4.tgz", "integrity": "sha512-tycmZxkGfZaxhMRbXlPXuVFpdWlXpir2W4AMhSJgRKzk/eDlIXOhb2LHWoLpDF7TEHylV5zNhykX6KAgHJmTNw==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@babel/helper-plugin-utils": "^7.8.0" @@ -993,7 +994,7 @@ "version": "7.8.3", "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-bigint/-/plugin-syntax-bigint-7.8.3.tgz", "integrity": "sha512-wnTnFlG+YxQm3vDxpGE57Pj0srRU4sHE/mDkt1qv2YJJSeUAec2ma4WLUnUPeKjyrfntVwe/N6dCXpU+zL3Npg==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@babel/helper-plugin-utils": "^7.8.0" @@ -1006,7 +1007,7 @@ "version": "7.12.13", "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-class-properties/-/plugin-syntax-class-properties-7.12.13.tgz", "integrity": "sha512-fm4idjKla0YahUNgFNLCB0qySdsoPiZP3iQE3rky0mBUtMZ23yDJ9SJdg6dXTSDnulOVqiF3Hgr9nbXvXTQZYA==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@babel/helper-plugin-utils": "^7.12.13" @@ -1019,7 +1020,7 @@ "version": "7.14.5", "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-class-static-block/-/plugin-syntax-class-static-block-7.14.5.tgz", "integrity": "sha512-b+YyPmr6ldyNnM6sqYeMWE+bgJcJpO6yS4QD7ymxgH34GBPNDM/THBh8iunyvKIZztiwLH4CJZ0RxTk9emgpjw==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@babel/helper-plugin-utils": "^7.14.5" @@ -1108,7 +1109,7 @@ "version": "7.28.6", "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-import-attributes/-/plugin-syntax-import-attributes-7.28.6.tgz", "integrity": "sha512-jiLC0ma9XkQT3TKJ9uYvlakm66Pamywo+qwL+oL8HJOvc6TWdZXVfhqJr8CCzbSGUAbDOzlGHJC1U+vRfLQDvw==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@babel/helper-plugin-utils": "^7.28.6" @@ -1124,7 +1125,7 @@ "version": "7.10.4", "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-import-meta/-/plugin-syntax-import-meta-7.10.4.tgz", "integrity": "sha512-Yqfm+XDx0+Prh3VSeEQCPU81yC+JWZ2pDPFSS4ZdpfZhp4MkFMaDC1UqseovEKwSUpnIL7+vK+Clp7bfh0iD7g==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@babel/helper-plugin-utils": "^7.10.4" @@ -1137,7 +1138,7 @@ "version": "7.8.3", "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-json-strings/-/plugin-syntax-json-strings-7.8.3.tgz", "integrity": "sha512-lY6kdGpWHvjoe2vk4WrAapEuBR69EMxZl+RoGRhrFGNYVK8mOPAW8VfbT/ZgrFbXlDNiiaxQnAtgVCZ6jv30EA==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@babel/helper-plugin-utils": "^7.8.0" @@ -1165,7 +1166,7 @@ "version": "7.10.4", "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-logical-assignment-operators/-/plugin-syntax-logical-assignment-operators-7.10.4.tgz", "integrity": "sha512-d8waShlpFDinQ5MtvGU9xDAOzKH47+FFoney2baFIoMr952hKOLp1HR7VszoZvOsV/4+RRszNY7D17ba0te0ig==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@babel/helper-plugin-utils": "^7.10.4" @@ -1190,7 +1191,7 @@ "version": "7.10.4", "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-numeric-separator/-/plugin-syntax-numeric-separator-7.10.4.tgz", "integrity": "sha512-9H6YdfkcK/uOnY/K7/aA2xpzaAgkQn37yzWUMRK7OaPOqOpGS1+n0H5hxT9AUw9EsSjPW8SVyMJwYRtWs3X3ug==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@babel/helper-plugin-utils": "^7.10.4" @@ -1203,7 +1204,7 @@ "version": "7.8.3", "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-object-rest-spread/-/plugin-syntax-object-rest-spread-7.8.3.tgz", "integrity": "sha512-XoqMijGZb9y3y2XskN+P1wUGiVwWZ5JmoDRwx5+3GmEplNyVM2s2Dg8ILFQm8rWM48orGy5YpI5Bl8U1y7ydlA==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@babel/helper-plugin-utils": "^7.8.0" @@ -1216,7 +1217,7 @@ "version": "7.8.3", "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-optional-catch-binding/-/plugin-syntax-optional-catch-binding-7.8.3.tgz", "integrity": "sha512-6VPD0Pc1lpTqw0aKoeRTMiB+kWhAoT24PA+ksWSBrFtl5SIRVpZlwN3NNPQjehA2E/91FV3RjLWoVTglWcSV3Q==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@babel/helper-plugin-utils": "^7.8.0" @@ -1241,7 +1242,7 @@ "version": "7.14.5", "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-private-property-in-object/-/plugin-syntax-private-property-in-object-7.14.5.tgz", "integrity": "sha512-0wVnp9dxJ72ZUJDV27ZfbSj6iHLoytYZmh3rFcxNnvsJF3ktkzLDZPy/mA17HGsaQT3/DQsWYX1f1QGWkCoVUg==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@babel/helper-plugin-utils": "^7.14.5" @@ -1257,7 +1258,7 @@ "version": "7.14.5", "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-top-level-await/-/plugin-syntax-top-level-await-7.14.5.tgz", "integrity": "sha512-hx++upLv5U1rgYfwe1xBQUhRmU41NEvpUvrp8jkrSCdvGSnM5/qdRMtylJ6PG5OFkBaHkbTAKTnd3/YyESRHFw==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@babel/helper-plugin-utils": "^7.14.5" @@ -2510,6 +2511,14 @@ "node": ">=6.9.0" } }, + "node_modules/@bcoe/v8-coverage": { + "version": "0.2.3", + "resolved": "https://registry.npmjs.org/@bcoe/v8-coverage/-/v8-coverage-0.2.3.tgz", + "integrity": "sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw==", + "devOptional": true, + "license": "MIT", + "peer": true + }, "node_modules/@blazediff/core": { "version": "1.9.1", "resolved": "https://registry.npmjs.org/@blazediff/core/-/core-1.9.1.tgz", @@ -2779,58 +2788,6 @@ "@jridgewell/sourcemap-codec": "^1.4.10" } }, - "node_modules/@develar/schema-utils": { - "version": "2.6.5", - "resolved": "https://registry.npmjs.org/@develar/schema-utils/-/schema-utils-2.6.5.tgz", - "integrity": "sha512-0cp4PsWQ/9avqTVMCtZ+GirikIA36ikvjtHweU4/j8yLtgObI0+JUPhYFScgwlteveGB1rt3Cm8UhN04XayDig==", - "dev": true, - "license": "MIT", - "dependencies": { - "ajv": "^6.12.0", - "ajv-keywords": "^3.4.1" - }, - "engines": { - "node": ">= 8.9.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/webpack" - } - }, - "node_modules/@develar/schema-utils/node_modules/ajv": { - "version": "6.14.0", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.14.0.tgz", - "integrity": "sha512-IWrosm/yrn43eiKqkfkHis7QioDleaXQHdDVPKg0FSwwd/DuvyX79TZnFOnYpB7dcsFAMmtFztZuXPDvSePkFw==", - "dev": true, - "license": "MIT", - "dependencies": { - "fast-deep-equal": "^3.1.1", - "fast-json-stable-stringify": "^2.0.0", - "json-schema-traverse": "^0.4.1", - "uri-js": "^4.2.2" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/epoberezkin" - } - }, - "node_modules/@develar/schema-utils/node_modules/ajv-keywords": { - "version": "3.5.2", - "resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-3.5.2.tgz", - "integrity": "sha512-5p6WTN0DdTGVQk6VjcEju19IgaHudalcfabD7yhDGeA6bcQnmL+CpveLJq/3hvfwd1aof6L386Ougkx6RfyMIQ==", - "dev": true, - "license": "MIT", - "peerDependencies": { - "ajv": "^6.9.1" - } - }, - "node_modules/@develar/schema-utils/node_modules/json-schema-traverse": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", - "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", - "dev": true, - "license": "MIT" - }, "node_modules/@dnd-kit/accessibility": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/@dnd-kit/accessibility/-/accessibility-3.1.1.tgz", @@ -2884,6 +2841,17 @@ "react": ">=16.8.0" } }, + "node_modules/@dual-bundle/import-meta-resolve": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@dual-bundle/import-meta-resolve/-/import-meta-resolve-4.2.1.tgz", + "integrity": "sha512-id+7YRUgoUX6CgV0DtuhirQWodeeA7Lf4i2x71JS/vtA5pRb/hIGWlw+G6MeXvsM+MXrz0VAydTGElX1rAfgPg==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/JounQin" + } + }, "node_modules/@egjs/hammerjs": { "version": "2.0.17", "resolved": "https://registry.npmjs.org/@egjs/hammerjs/-/hammerjs-2.0.17.tgz", @@ -3111,84 +3079,6 @@ "url": "https://github.com/sponsors/gjtorikian/" } }, - "node_modules/@electron/rebuild": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/@electron/rebuild/-/rebuild-4.0.3.tgz", - "integrity": "sha512-u9vpTHRMkOYCs/1FLiSVAFZ7FbjsXK+bQuzviJZa+lG7BHZl1nz52/IcGvwa3sk80/fc3llutBkbCq10Vh8WQA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@malept/cross-spawn-promise": "^2.0.0", - "debug": "^4.1.1", - "detect-libc": "^2.0.1", - "got": "^11.7.0", - "graceful-fs": "^4.2.11", - "node-abi": "^4.2.0", - "node-api-version": "^0.2.1", - "node-gyp": "^11.2.0", - "ora": "^5.1.0", - "read-binary-file-arch": "^1.0.6", - "semver": "^7.3.5", - "tar": "^7.5.6", - "yargs": "^17.0.1" - }, - "bin": { - "electron-rebuild": "lib/cli.js" - }, - "engines": { - "node": ">=22.12.0" - } - }, - "node_modules/@electron/rebuild/node_modules/chownr": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/chownr/-/chownr-3.0.0.tgz", - "integrity": "sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g==", - "dev": true, - "license": "BlueOak-1.0.0", - "engines": { - "node": ">=18" - } - }, - "node_modules/@electron/rebuild/node_modules/minizlib": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-3.1.0.tgz", - "integrity": "sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw==", - "dev": true, - "license": "MIT", - "dependencies": { - "minipass": "^7.1.2" - }, - "engines": { - "node": ">= 18" - } - }, - "node_modules/@electron/rebuild/node_modules/tar": { - "version": "7.5.12", - "resolved": "https://registry.npmjs.org/tar/-/tar-7.5.12.tgz", - "integrity": "sha512-9TsuLcdhOn4XztcQqhNyq1KOwOOED/3k58JAvtULiYqbO8B/0IBAAIE1hj0Svmm58k27TmcigyDI0deMlgG3uw==", - "dev": true, - "license": "BlueOak-1.0.0", - "dependencies": { - "@isaacs/fs-minipass": "^4.0.0", - "chownr": "^3.0.0", - "minipass": "^7.1.2", - "minizlib": "^3.1.0", - "yallist": "^5.0.0" - }, - "engines": { - "node": ">=18" - } - }, - "node_modules/@electron/rebuild/node_modules/yallist": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-5.0.0.tgz", - "integrity": "sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw==", - "dev": true, - "license": "BlueOak-1.0.0", - "engines": { - "node": ">=18" - } - }, "node_modules/@electron/universal": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/@electron/universal/-/universal-2.0.3.tgz", @@ -3239,6 +3129,45 @@ "url": "https://github.com/sponsors/isaacs" } }, + "node_modules/@electron/windows-sign": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/@electron/windows-sign/-/windows-sign-1.2.2.tgz", + "integrity": "sha512-dfZeox66AvdPtb2lD8OsIIQh12Tp0GNCRUDfBHIKGpbmopZto2/A8nSpYYLoedPIHpqkeblZ/k8OV0Gy7PYuyQ==", + "dev": true, + "license": "BSD-2-Clause", + "optional": true, + "peer": true, + "dependencies": { + "cross-dirname": "^0.1.0", + "debug": "^4.3.4", + "fs-extra": "^11.1.1", + "minimist": "^1.2.8", + "postject": "^1.0.0-alpha.6" + }, + "bin": { + "electron-windows-sign": "bin/electron-windows-sign.js" + }, + "engines": { + "node": ">=14.14" + } + }, + "node_modules/@electron/windows-sign/node_modules/fs-extra": { + "version": "11.4.1", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.4.1.tgz", + "integrity": "sha512-KYAb4c9BJQI6QqGKthV68OHe0badztdXJWKo0WtBA9IuCFPTKvE5ZdUBglP833aMjhaSPNO4A5j/EkzZtGlKjA==", + "dev": true, + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "graceful-fs": "^4.2.0", + "jsonfile": "^6.0.1", + "universalify": "^2.0.0" + }, + "engines": { + "node": ">=14.14" + } + }, "node_modules/@emnapi/core": { "version": "1.8.1", "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.8.1.tgz", @@ -5537,14 +5466,6 @@ "react-native": "*" } }, - "node_modules/@expo/log-box-utils": { - "version": "58.0.2", - "resolved": "https://registry.npmjs.org/@expo/log-box-utils/-/log-box-utils-58.0.2.tgz", - "integrity": "sha512-My8Lwe9FU/yDwwzqwi5LN2rzzDcJqIAZKrD9f0XHZEKz/FQnWJYdt1rsV7+RwqMGeGq2XsxTCVT1ggTCOvumxw==", - "dev": true, - "license": "MIT", - "peer": true - }, "node_modules/@expo/logger": { "version": "1.0.221", "resolved": "https://registry.npmjs.org/@expo/logger/-/logger-1.0.221.tgz", @@ -5899,36 +5820,6 @@ "node": "^20.19.4 || ^22.13.0 || ^24.3.0 || >= 25.0.0" } }, - "node_modules/@expo/modules-macros-win32-arm64": { - "version": "0.20.0", - "resolved": "https://registry.npmjs.org/@expo/modules-macros-win32-arm64/-/modules-macros-win32-arm64-0.20.0.tgz", - "integrity": "sha512-7B57gc7+TeygPcK8fLYlEhJbbvaPh+JBzex11YIYZrSzbFhz7Q+Z37fSdAfp4EsfCswJNcX0S6wpkgSlVNefVw==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "peer": true - }, - "node_modules/@expo/modules-macros-win32-x64": { - "version": "0.20.0", - "resolved": "https://registry.npmjs.org/@expo/modules-macros-win32-x64/-/modules-macros-win32-x64-0.20.0.tgz", - "integrity": "sha512-BM5a2U2tCyHzmtiSEY70KPsts82Mfy1bHSZ7AUbg6z9LcnxuThxJlcH85/SV5eFbhrPfgDBAG/WAncyZCvKvyA==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "peer": true - }, "node_modules/@expo/multipart-body-parser": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/@expo/multipart-body-parser/-/multipart-body-parser-2.0.0.tgz", @@ -6216,14 +6107,6 @@ "node-forge": "^1.2.1" } }, - "node_modules/@expo/platforms": { - "version": "58.0.1", - "resolved": "https://registry.npmjs.org/@expo/platforms/-/platforms-58.0.1.tgz", - "integrity": "sha512-KtLrtAvpShq16l9lTxd2fZSjULxcGxXrJTHA31iUVqrc+Af7aTAJW4ZB3yQBgi/w+kSb6BB/CG9RXI0ohbMm6g==", - "dev": true, - "license": "MIT", - "peer": true - }, "node_modules/@expo/plist": { "version": "0.2.0", "resolved": "https://registry.npmjs.org/@expo/plist/-/plist-0.2.0.tgz", @@ -7569,7 +7452,7 @@ "version": "1.1.0", "resolved": "https://registry.npmjs.org/@istanbuljs/load-nyc-config/-/load-nyc-config-1.1.0.tgz", "integrity": "sha512-VjeHSlIzpv/NyD3N0YuHfXOPDIixcA1q2ZV98wsMqcYlPmv2n3Yb2lYP9XMElnaFVXg5A7YLTeLu6V84uQDjmQ==", - "dev": true, + "devOptional": true, "license": "ISC", "dependencies": { "camelcase": "^5.3.1", @@ -7586,7 +7469,7 @@ "version": "5.3.1", "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==", - "dev": true, + "devOptional": true, "license": "MIT", "engines": { "node": ">=6" @@ -7596,7 +7479,7 @@ "version": "4.1.0", "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "locate-path": "^5.0.0", @@ -7610,7 +7493,7 @@ "version": "3.14.2", "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.2.tgz", "integrity": "sha512-PMSmkqxr106Xa156c2M265Z+FTrPl+oxd/rgOQy2tijQeK5TxQ43psO1ZCwhVOSdnn+RzkzlRz/eY4BgJBYVpg==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "argparse": "^1.0.7", @@ -7624,7 +7507,7 @@ "version": "5.0.0", "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "p-locate": "^4.1.0" @@ -7637,7 +7520,7 @@ "version": "2.3.0", "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "p-try": "^2.0.0" @@ -7653,7 +7536,7 @@ "version": "4.1.0", "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "p-limit": "^2.2.0" @@ -7666,7 +7549,7 @@ "version": "0.1.3", "resolved": "https://registry.npmjs.org/@istanbuljs/schema/-/schema-0.1.3.tgz", "integrity": "sha512-ZXRY4jNvVgSVQ8DL3LTcakaAtXwTVUxE81hslsyD2AtoXW/wVob10HkOJ1X/pAlcI7D+2YoZKg5do8G/w6RYgA==", - "dev": true, + "devOptional": true, "license": "MIT", "engines": { "node": ">=8" @@ -7676,7 +7559,7 @@ "version": "29.7.0", "resolved": "https://registry.npmjs.org/@jest/console/-/console-29.7.0.tgz", "integrity": "sha512-5Ni4CU7XHQi32IJ398EEP4RrB8eV09sXP2ROqD4bksHrnTree52PsxvX8tpL8LvTZ3pFzXyPbNQReSN41CAhOg==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@jest/types": "^29.6.3", @@ -7694,12 +7577,72 @@ "version": "3.0.0", "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", - "dev": true, + "devOptional": true, "license": "MIT", "engines": { "node": ">=8" } }, + "node_modules/@jest/core": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/@jest/core/-/core-29.7.0.tgz", + "integrity": "sha512-n7aeXWKMnGtDA48y8TLWJPJmLmmZ642Ceo78cYWEpiD7FzDgmNDV/GCVRorPABdXLJZ/9wzzgZAlHjXjxDHGsg==", + "devOptional": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@jest/console": "^29.7.0", + "@jest/reporters": "^29.7.0", + "@jest/test-result": "^29.7.0", + "@jest/transform": "^29.7.0", + "@jest/types": "^29.6.3", + "@types/node": "*", + "ansi-escapes": "^4.2.1", + "chalk": "^4.0.0", + "ci-info": "^3.2.0", + "exit": "^0.1.2", + "graceful-fs": "^4.2.9", + "jest-changed-files": "^29.7.0", + "jest-config": "^29.7.0", + "jest-haste-map": "^29.7.0", + "jest-message-util": "^29.7.0", + "jest-regex-util": "^29.6.3", + "jest-resolve": "^29.7.0", + "jest-resolve-dependencies": "^29.7.0", + "jest-runner": "^29.7.0", + "jest-runtime": "^29.7.0", + "jest-snapshot": "^29.7.0", + "jest-util": "^29.7.0", + "jest-validate": "^29.7.0", + "jest-watcher": "^29.7.0", + "micromatch": "^4.0.4", + "pretty-format": "^29.7.0", + "slash": "^3.0.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "peerDependencies": { + "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" + }, + "peerDependenciesMeta": { + "node-notifier": { + "optional": true + } + } + }, + "node_modules/@jest/core/node_modules/slash": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", + "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", + "devOptional": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=8" + } + }, "node_modules/@jest/create-cache-key-function": { "version": "29.7.0", "resolved": "https://registry.npmjs.org/@jest/create-cache-key-function/-/create-cache-key-function-29.7.0.tgz", @@ -7714,10 +7657,10 @@ } }, "node_modules/@jest/diff-sequences": { - "version": "30.4.0", - "resolved": "https://registry.npmjs.org/@jest/diff-sequences/-/diff-sequences-30.4.0.tgz", - "integrity": "sha512-zOpzlfUs45l6u7jm39qr87JCHUDsaeCtvL+kQe/Vn9jSnRB4/5IPXISm0h9I1vZW/o00Kn4UTJ2MOlhnUGwv3g==", - "dev": true, + "version": "30.5.0", + "resolved": "https://registry.npmjs.org/@jest/diff-sequences/-/diff-sequences-30.5.0.tgz", + "integrity": "sha512-OsqBjHXCn8cadasoAZBP6nWYvMsRhpMzGXTpxJ5aO04NlbdhIz+FVe3q49l0AwVhsz/cEmIpBes6gAFl1/dWQg==", + "devOptional": true, "license": "MIT", "engines": { "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" @@ -7727,7 +7670,7 @@ "version": "29.7.0", "resolved": "https://registry.npmjs.org/@jest/environment/-/environment-29.7.0.tgz", "integrity": "sha512-aQIfHDq33ExsN4jP1NWGXhxgQ/wixs60gDiKO+XVMd8Mn0NWPWgc34ZQDTb2jKaUWQ7MuwoitXAsN2XVXNMpAw==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@jest/fake-timers": "^29.7.0", @@ -7743,7 +7686,7 @@ "version": "29.7.0", "resolved": "https://registry.npmjs.org/@jest/expect/-/expect-29.7.0.tgz", "integrity": "sha512-8uMeAMycttpva3P1lBHB8VciS9V0XAr3GymPpipdyQXbBcuhkLQOSe8E/p92RyAdToS6ZD1tFkX+CkhoECE0dQ==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "expect": "^29.7.0", @@ -7757,7 +7700,7 @@ "version": "29.7.0", "resolved": "https://registry.npmjs.org/@jest/expect-utils/-/expect-utils-29.7.0.tgz", "integrity": "sha512-GlsNBWiFQFCVi9QVSx7f5AgMeLxe9YCCs5PuP2O2LdjDAA8Jh9eX7lA1Jq/xdXw3Wb3hyvlFNfZIfcRetSzYcA==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "jest-get-type": "^29.6.3" @@ -7770,7 +7713,7 @@ "version": "29.7.0", "resolved": "https://registry.npmjs.org/@jest/fake-timers/-/fake-timers-29.7.0.tgz", "integrity": "sha512-q4DH1Ha4TTFPdxLsqDXK1d3+ioSL7yL5oCMJZgDYm6i+6CygW5E5xVr/D1HdsGxjt1ZWSfUAs9OxSB/BNelWrQ==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@jest/types": "^29.6.3", @@ -7785,10 +7728,10 @@ } }, "node_modules/@jest/get-type": { - "version": "30.1.0", - "resolved": "https://registry.npmjs.org/@jest/get-type/-/get-type-30.1.0.tgz", - "integrity": "sha512-eMbZE2hUnx1WV0pmURZY9XoXPkUYjpc55mb0CrhtdWLtzMQPFvu/rZkTLZFTsdaVQa+Tr4eWAteqcUzoawq/uA==", - "dev": true, + "version": "30.5.0", + "resolved": "https://registry.npmjs.org/@jest/get-type/-/get-type-30.5.0.tgz", + "integrity": "sha512-9/2VUPitAjmBzbvDvqrxmvB7BzWsBW0WmkkojX1ODuxX1NLGxx9gfaZpHB0z8DtJ9uhGNmZG/VXBhf8uO0OV8Q==", + "devOptional": true, "license": "MIT", "engines": { "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" @@ -7798,7 +7741,7 @@ "version": "29.7.0", "resolved": "https://registry.npmjs.org/@jest/globals/-/globals-29.7.0.tgz", "integrity": "sha512-mpiz3dutLbkW2MNFubUGUEVLkTGiqW6yLVTA+JbP6fI6J5iL9Y0Nlg8k95pcF8ctKwCS7WVxteBs29hhfAotzQ==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@jest/environment": "^29.7.0", @@ -7810,6 +7753,171 @@ "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, + "node_modules/@jest/react-is-18": { + "name": "react-is", + "version": "18.3.1", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.3.1.tgz", + "integrity": "sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/@jest/react-is-19": { + "name": "react-is", + "version": "19.3.1", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-19.3.1.tgz", + "integrity": "sha512-RRieF6IyxQBkcK6pP8xOHprLTPW6QjRkbGdImtqNme+/hYVwCZkLQLdlZGOhUqXwkS9IEynaGvPJtv6XB/cz0Q==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/@jest/reporters": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/@jest/reporters/-/reporters-29.7.0.tgz", + "integrity": "sha512-DApq0KJbJOEzAFYjHADNNxAE3KbhxQB1y5Kplb5Waqw6zVbuWatSnMjE5gs8FUgEPmNsnZA3NCWl9NG0ia04Pg==", + "devOptional": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@bcoe/v8-coverage": "^0.2.3", + "@jest/console": "^29.7.0", + "@jest/test-result": "^29.7.0", + "@jest/transform": "^29.7.0", + "@jest/types": "^29.6.3", + "@jridgewell/trace-mapping": "^0.3.18", + "@types/node": "*", + "chalk": "^4.0.0", + "collect-v8-coverage": "^1.0.0", + "exit": "^0.1.2", + "glob": "^7.1.3", + "graceful-fs": "^4.2.9", + "istanbul-lib-coverage": "^3.0.0", + "istanbul-lib-instrument": "^6.0.0", + "istanbul-lib-report": "^3.0.0", + "istanbul-lib-source-maps": "^4.0.0", + "istanbul-reports": "^3.1.3", + "jest-message-util": "^29.7.0", + "jest-util": "^29.7.0", + "jest-worker": "^29.7.0", + "slash": "^3.0.0", + "string-length": "^4.0.1", + "strip-ansi": "^6.0.0", + "v8-to-istanbul": "^9.0.1" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "peerDependencies": { + "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" + }, + "peerDependenciesMeta": { + "node-notifier": { + "optional": true + } + } + }, + "node_modules/@jest/reporters/node_modules/brace-expansion": { + "version": "1.1.21", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.21.tgz", + "integrity": "sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw==", + "devOptional": true, + "license": "MIT", + "peer": true, + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/@jest/reporters/node_modules/char-regex": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/char-regex/-/char-regex-1.0.2.tgz", + "integrity": "sha512-kWWXztvZ5SBQV+eRgKFeh8q5sLuZY2+8WUIzlxWVTg+oGwY14qylx1KbKzHd8P6ZYkAg0xyIDU9JMHhyJMZ1jw==", + "devOptional": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=10" + } + }, + "node_modules/@jest/reporters/node_modules/glob": { + "version": "7.2.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", + "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", + "deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me", + "devOptional": true, + "license": "ISC", + "peer": true, + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.1.1", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/@jest/reporters/node_modules/istanbul-lib-instrument": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/istanbul-lib-instrument/-/istanbul-lib-instrument-6.0.3.tgz", + "integrity": "sha512-Vtgk7L/R2JHyyGW07spoFlB8/lpjiOLTjMdms6AFMraYt3BaJauod/NGrfnVG/y4Ix1JEuMRPDPEj2ua+zz1/Q==", + "devOptional": true, + "license": "BSD-3-Clause", + "peer": true, + "dependencies": { + "@babel/core": "^7.23.9", + "@babel/parser": "^7.23.9", + "@istanbuljs/schema": "^0.1.3", + "istanbul-lib-coverage": "^3.2.0", + "semver": "^7.5.4" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/@jest/reporters/node_modules/minimatch": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", + "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", + "devOptional": true, + "license": "ISC", + "peer": true, + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/@jest/reporters/node_modules/slash": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", + "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", + "devOptional": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/@jest/reporters/node_modules/string-length": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/string-length/-/string-length-4.0.2.tgz", + "integrity": "sha512-+l6rNN5fYHNhZZy41RXsYptCjA2Igmq4EG7kZAYFQI1E1VTXarr6ZPXBg6eq7Y6eK4FEhY6AJlyuFIb/v/S0VQ==", + "devOptional": true, + "license": "MIT", + "peer": true, + "dependencies": { + "char-regex": "^1.0.2", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + } + }, "node_modules/@jest/schemas": { "version": "29.6.3", "resolved": "https://registry.npmjs.org/@jest/schemas/-/schemas-29.6.3.tgz", @@ -7822,11 +7930,27 @@ "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, + "node_modules/@jest/source-map": { + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/@jest/source-map/-/source-map-29.6.3.tgz", + "integrity": "sha512-MHjT95QuipcPrpLM+8JMSzFx6eHp5Bm+4XeFDJlwsvVBjmKNiIAvasGK2fxz2WbGRlnvqehFbh07MMa7n3YJnw==", + "devOptional": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@jridgewell/trace-mapping": "^0.3.18", + "callsites": "^3.0.0", + "graceful-fs": "^4.2.9" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, "node_modules/@jest/test-result": { "version": "29.7.0", "resolved": "https://registry.npmjs.org/@jest/test-result/-/test-result-29.7.0.tgz", "integrity": "sha512-Fdx+tv6x1zlkJPcWXmMDAG2HBnaR9XPSd5aDWQVsfrZmLVT3lU1cwyxLgRmXR9yrq4NBoEm9BMsfgFzTQAbJYA==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@jest/console": "^29.7.0", @@ -7838,11 +7962,39 @@ "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, + "node_modules/@jest/test-sequencer": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/@jest/test-sequencer/-/test-sequencer-29.7.0.tgz", + "integrity": "sha512-GQwJ5WZVrKnOJuiYiAF52UNUJXgTZx1NHjFSEB0qEMmSZKAkdMoIzw/Cj6x6NF4AvV23AUqDpFzQkN/eYCYTxw==", + "devOptional": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@jest/test-result": "^29.7.0", + "graceful-fs": "^4.2.9", + "jest-haste-map": "^29.7.0", + "slash": "^3.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/test-sequencer/node_modules/slash": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", + "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", + "devOptional": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=8" + } + }, "node_modules/@jest/transform": { "version": "29.7.0", "resolved": "https://registry.npmjs.org/@jest/transform/-/transform-29.7.0.tgz", "integrity": "sha512-ok/BTPFzFKVMwO5eOHRrvnBVHdRy9IrsrW1GpMaQ9MCnilNLXQKmAX8s1YXDFaai9xJpac2ySzV0YeRRECr2Vw==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@babel/core": "^7.11.6", @@ -7869,14 +8021,14 @@ "version": "3.0.7", "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", - "dev": true, + "devOptional": true, "license": "ISC" }, "node_modules/@jest/transform/node_modules/slash": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", - "dev": true, + "devOptional": true, "license": "MIT", "engines": { "node": ">=8" @@ -7886,7 +8038,7 @@ "version": "4.0.2", "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-4.0.2.tgz", "integrity": "sha512-7KxauUdBmSdWnmpaGFg+ppNjKF8uNLry8LyzjauQDOVONfFLNKrKvQOxZ/VuTIcS/gge/YNahf5RIIQWTSarlg==", - "dev": true, + "devOptional": true, "license": "ISC", "dependencies": { "imurmurhash": "^0.1.4", @@ -8892,225 +9044,6 @@ "node": ">=12.4.0" } }, - "node_modules/@noxcturnal/noxcturnal-darwin-arm64": { - "version": "0.1.5", - "resolved": "https://registry.npmjs.org/@noxcturnal/noxcturnal-darwin-arm64/-/noxcturnal-darwin-arm64-0.1.5.tgz", - "integrity": "sha512-hQgDaWxKYln83Uk1Hh4Liju9AvGoYh4aLd4A1ou3lGn5hxzhW2uO+z3mERtWk6BMGVazvi/yUXtp9x3IlaWyhA==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "peer": true, - "engines": { - "node": ">=18" - } - }, - "node_modules/@noxcturnal/noxcturnal-darwin-x64": { - "version": "0.1.5", - "resolved": "https://registry.npmjs.org/@noxcturnal/noxcturnal-darwin-x64/-/noxcturnal-darwin-x64-0.1.5.tgz", - "integrity": "sha512-I57zR8QF7Xam+4nGD5UoIODsw0VjkVyn51iDBL3CMaDR5Lh1OxXwKZMYKtv3CtQl+RSDsMfmXBEqGYLE8lIPHg==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "peer": true, - "engines": { - "node": ">=18" - } - }, - "node_modules/@noxcturnal/noxcturnal-linux-arm64-gnu": { - "version": "0.1.5", - "resolved": "https://registry.npmjs.org/@noxcturnal/noxcturnal-linux-arm64-gnu/-/noxcturnal-linux-arm64-gnu-0.1.5.tgz", - "integrity": "sha512-gVH4XJPh8RdrdjjlU0dKeielQt/FXfvqhr8IEWEf3VeNtQs8l2rPzFPdqS0uwLWQYHLBGgB0LkuOil1KKYx1gQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "peer": true, - "engines": { - "node": ">=18" - } - }, - "node_modules/@noxcturnal/noxcturnal-linux-arm64-musl": { - "version": "0.1.5", - "resolved": "https://registry.npmjs.org/@noxcturnal/noxcturnal-linux-arm64-musl/-/noxcturnal-linux-arm64-musl-0.1.5.tgz", - "integrity": "sha512-rzQ075fcHZ+ebsELussRjnW8WBMy1RuLdS8wSqBGhdVlPR7/NaSyoWkNxnVDT8sEO26xjqGoW/o/08ghBzr/zA==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "peer": true, - "engines": { - "node": ">=18" - } - }, - "node_modules/@noxcturnal/noxcturnal-linux-x64-gnu": { - "version": "0.1.5", - "resolved": "https://registry.npmjs.org/@noxcturnal/noxcturnal-linux-x64-gnu/-/noxcturnal-linux-x64-gnu-0.1.5.tgz", - "integrity": "sha512-X5O0lXMrv8HGOGoXDB1PG0Hjt7Rl+MJA+seR2NecQvUAAw2gzDvF/unCV5sqTAVeHfXhBHEFGkLenHZSD44efg==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "peer": true, - "engines": { - "node": ">=18" - } - }, - "node_modules/@noxcturnal/noxcturnal-linux-x64-musl": { - "version": "0.1.5", - "resolved": "https://registry.npmjs.org/@noxcturnal/noxcturnal-linux-x64-musl/-/noxcturnal-linux-x64-musl-0.1.5.tgz", - "integrity": "sha512-fkQIQHRxqldNXVmjxfeCvGOiLhLU9SLBw1As02pMA2xjyiZfiXcUn4SUrZ92ciGnyCS8/XMbx+nZSxgEc3qDPw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "peer": true, - "engines": { - "node": ">=18" - } - }, - "node_modules/@noxcturnal/noxcturnal-win32-arm64-msvc": { - "version": "0.1.5", - "resolved": "https://registry.npmjs.org/@noxcturnal/noxcturnal-win32-arm64-msvc/-/noxcturnal-win32-arm64-msvc-0.1.5.tgz", - "integrity": "sha512-baeH5m/vM1nf0J2UkW8cfgiVogpM0gRO9b4PZWknXQPbv5+k+0N5sGOYl/UAO2q72qYb3Xbiu7eD8c4A2kR2SA==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "peer": true, - "engines": { - "node": ">=18" - } - }, - "node_modules/@noxcturnal/noxcturnal-win32-x64-msvc": { - "version": "0.1.5", - "resolved": "https://registry.npmjs.org/@noxcturnal/noxcturnal-win32-x64-msvc/-/noxcturnal-win32-x64-msvc-0.1.5.tgz", - "integrity": "sha512-2faDMzom8pCG/s/uR4Czh1atz4KohI85AaSmA2vtAuVnCq+nLL4Viys3A5vUlNz9MNBmTNFxzXyF2Z5HtfxXLg==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "peer": true, - "engines": { - "node": ">=18" - } - }, - "node_modules/@npmcli/agent": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/@npmcli/agent/-/agent-3.0.0.tgz", - "integrity": "sha512-S79NdEgDQd/NGCay6TCoVzXSj74skRZIKJcpJjC5lOq34SZzyI6MqtiiWoiVWoVrTcGjNeC4ipbh1VIHlpfF5Q==", - "dev": true, - "license": "ISC", - "dependencies": { - "agent-base": "^7.1.0", - "http-proxy-agent": "^7.0.0", - "https-proxy-agent": "^7.0.1", - "lru-cache": "^10.0.1", - "socks-proxy-agent": "^8.0.3" - }, - "engines": { - "node": "^18.17.0 || >=20.5.0" - } - }, - "node_modules/@npmcli/agent/node_modules/agent-base": { - "version": "7.1.4", - "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", - "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 14" - } - }, - "node_modules/@npmcli/agent/node_modules/http-proxy-agent": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz", - "integrity": "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==", - "dev": true, - "license": "MIT", - "dependencies": { - "agent-base": "^7.1.0", - "debug": "^4.3.4" - }, - "engines": { - "node": ">= 14" - } - }, - "node_modules/@npmcli/agent/node_modules/https-proxy-agent": { - "version": "7.0.6", - "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", - "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", - "dev": true, - "license": "MIT", - "dependencies": { - "agent-base": "^7.1.2", - "debug": "4" - }, - "engines": { - "node": ">= 14" - } - }, - "node_modules/@npmcli/agent/node_modules/lru-cache": { - "version": "10.4.3", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz", - "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==", - "dev": true, - "license": "ISC" - }, - "node_modules/@npmcli/fs": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/@npmcli/fs/-/fs-4.0.0.tgz", - "integrity": "sha512-/xGlezI6xfGO9NwuJlnwz/K14qD1kCSAGtacBHnGzeAIuJGazcp45KP5NuyARXoKb7cwulAGWVsbeSxdG/cb0Q==", - "dev": true, - "license": "ISC", - "dependencies": { - "semver": "^7.3.5" - }, - "engines": { - "node": "^18.17.0 || >=20.5.0" - } - }, "node_modules/@oclif/core": { "version": "1.26.2", "resolved": "https://registry.npmjs.org/@oclif/core/-/core-1.26.2.tgz", @@ -9387,17 +9320,6 @@ "node": ">=8.0.0" } }, - "node_modules/@oxc-project/types": { - "version": "0.154.0", - "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.154.0.tgz", - "integrity": "sha512-KYOUGQFlLWR+s4QMV2Q9ko38TZm7EdO87Qm7rvZLqk/webse/cDjtyxKhg/47l0byCbs/k46LT8qc4PKjAikzA==", - "dev": true, - "license": "MIT", - "peer": true, - "funding": { - "url": "https://github.com/sponsors/oxc-project" - } - }, "node_modules/@oxc-resolver/binding-android-arm-eabi": { "version": "11.19.1", "resolved": "https://registry.npmjs.org/@oxc-resolver/binding-android-arm-eabi/-/binding-android-arm-eabi-11.19.1.tgz", @@ -10411,6 +10333,61 @@ "node": "^20.19.0 || >=22.12.0" } }, + "node_modules/@peculiar/asn1-schema": { + "version": "2.11.1", + "resolved": "https://registry.npmjs.org/@peculiar/asn1-schema/-/asn1-schema-2.11.1.tgz", + "integrity": "sha512-jaU9OaCcbZUdyXx9hMETZB9xoNmxTGjOGFqd3cOwKFkpKnyKd9WxF3uqj4PvX4cyOMP9bSdHg5YyML2qtx/d/g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@peculiar/utils": "^2.0.2", + "asn1js": "^3.0.10", + "tslib": "^2.8.1" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/@peculiar/json-schema": { + "version": "1.1.12", + "resolved": "https://registry.npmjs.org/@peculiar/json-schema/-/json-schema-1.1.12.tgz", + "integrity": "sha512-coUfuoMeIB7B8/NMekxaDzLhaYmp0HZNPEjYRm9goRou8UZIC3z21s0sL9AWoCw4EG876QyO3kYrc61WNF9B/w==", + "dev": true, + "license": "MIT", + "dependencies": { + "tslib": "^2.0.0" + }, + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/@peculiar/utils": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/@peculiar/utils/-/utils-2.0.3.tgz", + "integrity": "sha512-+oL3HPFRIZ1St2K50lWCXiioIgSoxzz7R1J3uF6neO2yl1sgmpgY6XXJH4BdpoDkMWznQTeYF6oWNDZLCdQ4eQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "tslib": "^2.8.1" + } + }, + "node_modules/@peculiar/webcrypto": { + "version": "1.7.2", + "resolved": "https://registry.npmjs.org/@peculiar/webcrypto/-/webcrypto-1.7.2.tgz", + "integrity": "sha512-ktTSACRJ5WdpfjHjFT2EWJQQPacGv1cPCDfEbdmpAHOxdFiYqPe4lfnXGA3D8Dg9/0kHPYSvyRlgujIOVlTdvQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@peculiar/asn1-schema": "^2.7.0", + "@peculiar/json-schema": "^1.1.12", + "@peculiar/utils": "^2.0.2", + "tslib": "^2.8.1", + "webcrypto-core": "^1.9.2" + }, + "engines": { + "node": ">=14.18.0" + } + }, "node_modules/@pinojs/redact": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/@pinojs/redact/-/redact-0.4.0.tgz", @@ -10429,13 +10406,13 @@ } }, "node_modules/@pkgr/core": { - "version": "0.2.9", - "resolved": "https://registry.npmjs.org/@pkgr/core/-/core-0.2.9.tgz", - "integrity": "sha512-QNqXyfVS2wm9hweSYD2O7F0G06uurj9kZ96TRQE5Y9hU7+tgdZwIkbAKc5Ocy1HxEY2kuDQa6cQ1WRs/O5LFKA==", + "version": "0.3.6", + "resolved": "https://registry.npmjs.org/@pkgr/core/-/core-0.3.6.tgz", + "integrity": "sha512-SEeaJLb3qBNF/OaXnaR1NmmBbFYk1zC0ZH/52fATcRPLFg/p791YrcyFFy44Bo9sLaGuSuLp5Q6axbb/O+v/RA==", "dev": true, "license": "MIT", "engines": { - "node": "^12.20.0 || ^14.18.0 || >=16.0.0" + "node": "^14.18.0 || >=16.0.0" }, "funding": { "url": "https://opencollective.com/pkgr" @@ -11020,17 +10997,6 @@ "react-native": ">=0.57" } }, - "node_modules/@react-native/asset-utils": { - "version": "0.88.0", - "resolved": "https://registry.npmjs.org/@react-native/asset-utils/-/asset-utils-0.88.0.tgz", - "integrity": "sha512-Bj1DxQt5f4OrjdlgSVkZT37Z3hx5hUIN5AUDSqL/e99vgtTcqj5vnm067epZL1EF/QiqsniZO8Q1GSkItOakDg==", - "dev": true, - "license": "MIT", - "peer": true, - "engines": { - "node": "^22.13.0 || ^24.3.0 || >= 26.0.0" - } - }, "node_modules/@react-native/assets-registry": { "version": "0.86.3", "resolved": "https://registry.npmjs.org/@react-native/assets-registry/-/assets-registry-0.86.3.tgz", @@ -12073,7 +12039,7 @@ "version": "3.0.1", "resolved": "https://registry.npmjs.org/@sinonjs/commons/-/commons-3.0.1.tgz", "integrity": "sha512-K3mCHKQ9sVh8o1C9cxkwxaOmXoAMlDxC1mYyHrjqOWEcBjYr76t96zL2zlj5dUGZ3HSw240X1qgH3Mjf1yJWpQ==", - "dev": true, + "devOptional": true, "license": "BSD-3-Clause", "dependencies": { "type-detect": "4.0.8" @@ -12083,7 +12049,7 @@ "version": "10.3.0", "resolved": "https://registry.npmjs.org/@sinonjs/fake-timers/-/fake-timers-10.3.0.tgz", "integrity": "sha512-V4BG07kuYSUkTCSBHG8G8TNhM+F19jXFWnQtzj+we8DrkpSBCee9Z3Ms8yiGer/dlmhe35/Xdgyo3/0rQKg7YA==", - "dev": true, + "devOptional": true, "license": "BSD-3-Clause", "dependencies": { "@sinonjs/commons": "^3.0.0" @@ -12556,6 +12522,151 @@ } } }, + "node_modules/@testing-library/react-native": { + "version": "13.3.3", + "resolved": "https://registry.npmjs.org/@testing-library/react-native/-/react-native-13.3.3.tgz", + "integrity": "sha512-k6Mjsd9dbZgvY4Bl7P1NIpePQNi+dfYtlJ5voi9KQlynxSyQkfOgJmYGCYmw/aSgH/rUcFvG8u5gd4npzgRDyg==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "jest-matcher-utils": "^30.0.5", + "picocolors": "^1.1.1", + "pretty-format": "^30.0.5", + "redent": "^3.0.0" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "jest": ">=29.0.0", + "react": ">=18.2.0", + "react-native": ">=0.71", + "react-test-renderer": ">=18.2.0" + }, + "peerDependenciesMeta": { + "jest": { + "optional": true + } + } + }, + "node_modules/@testing-library/react-native/node_modules/@jest/schemas": { + "version": "30.5.0", + "resolved": "https://registry.npmjs.org/@jest/schemas/-/schemas-30.5.0.tgz", + "integrity": "sha512-/hunigyNpc4RCjC0VaW3f5RCUZVM2+WQ65qP7z083Gmvac7or2LI50XVNOtE4YPgBpV0yxYiAgorAPGniCoJmg==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "@sinclair/typebox": "^0.34.0" + }, + "engines": { + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" + } + }, + "node_modules/@testing-library/react-native/node_modules/@sinclair/typebox": { + "version": "0.34.52", + "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.34.52.tgz", + "integrity": "sha512-XiMQh7qqVlxZzcVD+kkGMNGMzcTrDMLWI7S4x7z1MkCkbDPrekpZXEUK0eZqZFMuHQg2a2DZOcDIh9o5v3Gonw==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/@testing-library/react-native/node_modules/ansi-styles": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz", + "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==", + "devOptional": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/@testing-library/react-native/node_modules/indent-string": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-4.0.0.tgz", + "integrity": "sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==", + "devOptional": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/@testing-library/react-native/node_modules/jest-diff": { + "version": "30.5.2", + "resolved": "https://registry.npmjs.org/jest-diff/-/jest-diff-30.5.2.tgz", + "integrity": "sha512-rBtHnI6BWTiWj3lM7fOLVfChx7R9B0u9VV3PRHawKs79x6ZjW1QoSrKenaigNGWlvhtoi2BqvDbABDie+Os3xQ==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "@jest/diff-sequences": "30.5.0", + "@jest/get-type": "30.5.0", + "chalk": "^4.1.2", + "pretty-format": "30.5.1" + }, + "engines": { + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" + } + }, + "node_modules/@testing-library/react-native/node_modules/jest-matcher-utils": { + "version": "30.5.2", + "resolved": "https://registry.npmjs.org/jest-matcher-utils/-/jest-matcher-utils-30.5.2.tgz", + "integrity": "sha512-lFkB365PTIHOhPzwrb9T6gvlDnPpOZ7/c3ewOKKB7bzztqjVrtlyRL2MkyfJXpyY2u2SKw001JKrTx14fBUFcQ==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "@jest/get-type": "30.5.0", + "chalk": "^4.1.2", + "jest-diff": "30.5.2", + "pretty-format": "30.5.1" + }, + "engines": { + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" + } + }, + "node_modules/@testing-library/react-native/node_modules/pretty-format": { + "version": "30.5.1", + "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-30.5.1.tgz", + "integrity": "sha512-byhRAPguVKMQIj4kjJwJ5lAskVhfuiSdiYl/aLTWpgkGEmic2jYhJh1yE9ih8Ox44Xg9ccCT11/S6QrzSJuNrg==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "@jest/react-is-18": "npm:react-is@^18.3.1", + "@jest/react-is-19": "npm:react-is@^19.2.5", + "@jest/schemas": "30.5.0", + "ansi-styles": "^5.2.0" + }, + "engines": { + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" + } + }, + "node_modules/@testing-library/react-native/node_modules/redent": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/redent/-/redent-3.0.0.tgz", + "integrity": "sha512-6tDA8g98We0zd0GvVeMT9arEOnTw9qM03L9cJXaCjrip1OO764RDBLBfrB4cwzNGDj5OA5ioymC9GkizgWJDUg==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "indent-string": "^4.0.0", + "strip-indent": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/@testing-library/react-native/node_modules/strip-indent": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/strip-indent/-/strip-indent-3.0.0.tgz", + "integrity": "sha512-laJTa3Jb+VQpaC6DseHhF7dXVqHTfJPCRDaEbid/drOhgitgYku/letMUqOXFoWV0zIIUbjpdH2t+tYj4bQMRQ==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "min-indent": "^1.0.0" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/@tootallnate/once": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/@tootallnate/once/-/once-2.0.0.tgz", @@ -12623,7 +12734,7 @@ "version": "7.20.5", "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz", "integrity": "sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@babel/parser": "^7.20.7", @@ -12637,7 +12748,7 @@ "version": "7.27.0", "resolved": "https://registry.npmjs.org/@types/babel__generator/-/babel__generator-7.27.0.tgz", "integrity": "sha512-ufFd2Xi92OAVPYsy+P4n7/U7e68fex0+Ee8gSG9KX7eo084CWiQ4sdxktvdl0bOPupXtVJPY19zk6EwWqUQ8lg==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@babel/types": "^7.0.0" @@ -12647,7 +12758,7 @@ "version": "7.4.4", "resolved": "https://registry.npmjs.org/@types/babel__template/-/babel__template-7.4.4.tgz", "integrity": "sha512-h/NUaSyG5EyxBIp8YRxo4RMe2/qQgvyowRwVMzhYhBCONbW8PUsg4lkFMrhgZhUe5z3L3MiLDuvyJ/CaPa2A8A==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@babel/parser": "^7.1.0", @@ -12658,7 +12769,7 @@ "version": "7.28.0", "resolved": "https://registry.npmjs.org/@types/babel__traverse/-/babel__traverse-7.28.0.tgz", "integrity": "sha512-8PvcXf70gTDZBgt9ptxJ8elBeBjcLOAcOtoO/mPJjtji1+CdGbHgm77om1GrsPxsiE+uXIpNSK64UYaIwQXd4Q==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@babel/types": "^7.28.2" @@ -13065,7 +13176,7 @@ "version": "4.1.9", "resolved": "https://registry.npmjs.org/@types/graceful-fs/-/graceful-fs-4.1.9.tgz", "integrity": "sha512-olP3sd1qOEe5dXTSaFvQG+02VdRXcdytWLAZsAq1PecU8uqQAhkrnbli7DagjtXKW/Bl7YJbUsa8MPcuc8LHEQ==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@types/node": "*" @@ -13248,18 +13359,6 @@ "dev": true, "license": "MIT" }, - "node_modules/@types/plist": { - "version": "3.0.5", - "resolved": "https://registry.npmjs.org/@types/plist/-/plist-3.0.5.tgz", - "integrity": "sha512-E6OCaRmAe4WDmWNsL/9RMqdkkzDCY1etutkflWk4c+AcjDU07Pcz1fQwTX0TQz+Pxqn9i4L1TU3UFpjnrcDgxA==", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "@types/node": "*", - "xmlbuilder": ">=11.0.1" - } - }, "node_modules/@types/prop-types": { "version": "15.7.15", "resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.15.tgz", @@ -13373,7 +13472,7 @@ "version": "2.0.3", "resolved": "https://registry.npmjs.org/@types/stack-utils/-/stack-utils-2.0.3.tgz", "integrity": "sha512-9aEbYZ3TbYMznPdcdr3SmIrLXwC/AKZXQeCf9Pgao5CKb8CyHuEX5jzWPTkvregvhRJHcpRO6BFoGW9ycaOkYw==", - "dev": true, + "devOptional": true, "license": "MIT" }, "node_modules/@types/tough-cookie": { @@ -13410,14 +13509,6 @@ "dev": true, "license": "MIT" }, - "node_modules/@types/verror": { - "version": "1.10.11", - "resolved": "https://registry.npmjs.org/@types/verror/-/verror-1.10.11.tgz", - "integrity": "sha512-RlDm9K7+o5stv0Co8i8ZRGxDbrTxhJtgjqjFyVh/tXQyl/rYtTKlnTvZ88oSTeYREWurwx20Js4kTuKCsFkUtg==", - "dev": true, - "license": "MIT", - "optional": true - }, "node_modules/@types/ws": { "version": "8.18.1", "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz", @@ -13443,6 +13534,288 @@ "integrity": "sha512-I4q9QU9MQv4oEOz4tAHJtNz1cwuLxn2F3xcc2iV5WdqLPpUnj30aUuxt1mAxYTG+oe8CZMV/+6rU4S4gRDzqtQ==", "license": "MIT" }, + "node_modules/@typescript-eslint/eslint-plugin": { + "version": "8.72.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.72.1.tgz", + "integrity": "sha512-5CokTWXpmbylfFabsbvHC0CAw3XLaGnoa+nFJX5FR592h/LoZsENUE6p/rg5xvkKrFEXz6pYmgI29AgXc2N3BQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@eslint-community/regexpp": "^4.12.2", + "@typescript-eslint/scope-manager": "8.72.1", + "@typescript-eslint/type-utils": "8.72.1", + "@typescript-eslint/utils": "8.72.1", + "@typescript-eslint/visitor-keys": "8.72.1", + "ignore": "^7.0.5", + "natural-compare": "^1.4.0", + "ts-api-utils": "^2.5.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "@typescript-eslint/parser": "^8.72.1", + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/eslint-plugin/node_modules/ignore": { + "version": "7.0.14", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.14.tgz", + "integrity": "sha512-wCBiZ77u1tuWde6G/nfOtLaCTYcFDU5yCzARzK10y+rLhzYoL7a7yEemcopcc2Mzow7gZOIjnV2ym1NYmdiJOQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/@typescript-eslint/parser": { + "version": "8.72.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.72.1.tgz", + "integrity": "sha512-ZGwZP4OCfyA0AQTpEAMWz+rtX01DRhQWW5hB0ucKDEIX5U7jdmPSaMx94rQfaPAQzIYz2BimOgKOJtjfpRFQ9g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/scope-manager": "8.72.1", + "@typescript-eslint/types": "8.72.1", + "@typescript-eslint/typescript-estree": "8.72.1", + "@typescript-eslint/visitor-keys": "8.72.1", + "debug": "^4.4.3" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/project-service": { + "version": "8.72.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.72.1.tgz", + "integrity": "sha512-fAuVMkwdO/huI8nyo/WKnNKf6Gag93S56Rh3Ts5mGcavwSdaN8tRg1gCeIGX8PF+nzp1BjGfO4gHhGzW1J6jTg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/tsconfig-utils": "^8.72.1", + "@typescript-eslint/types": "^8.72.1", + "debug": "^4.4.3" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/scope-manager": { + "version": "8.72.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.72.1.tgz", + "integrity": "sha512-lC/t6eMCZZQAAKZEYGL6RDVSuFehpdmMT6h+nJIjIa6oylN/PwDgDVtEIbB7O9xFfZYtZAYLoLlDNWKJhtF+uQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/types": "8.72.1", + "@typescript-eslint/visitor-keys": "8.72.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@typescript-eslint/tsconfig-utils": { + "version": "8.72.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.72.1.tgz", + "integrity": "sha512-e4D5R5vpeAEPBxT2BAzsFQL3sbwyeeeo5+aczgNSRK1V734jE7pTqaGFU+fXapWEQwnZbpFaTn32+Z8DwS6OTg==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/type-utils": { + "version": "8.72.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.72.1.tgz", + "integrity": "sha512-iY2wlmyrXJmx4yxUGP3aYCFF3cA/6ShddOKmLU2dx7LnEykbAM8WThlxZEfd1NddqceF6eJmZUayxx9oKIYNlg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/types": "8.72.1", + "@typescript-eslint/typescript-estree": "8.72.1", + "@typescript-eslint/utils": "8.72.1", + "debug": "^4.4.3", + "ts-api-utils": "^2.5.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/types": { + "version": "8.72.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.72.1.tgz", + "integrity": "sha512-LmE5IhQet1BWOWEXqBrVtBPsMAOQ6Nzk35d+WLh3mk4EUF33sqlfxjio1MdYeSvKSG5skactKKuixBIKXhL4Rw==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@typescript-eslint/typescript-estree": { + "version": "8.72.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.72.1.tgz", + "integrity": "sha512-DAlUoUV93hIvrtIQLwCbmZQYVZwOMhiHJrOVUUIWicFZaIYjTRqlY3I/NZevfkLmSqkNHRu2qYDcq9lrn16oOQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/project-service": "8.72.1", + "@typescript-eslint/tsconfig-utils": "8.72.1", + "@typescript-eslint/types": "8.72.1", + "@typescript-eslint/visitor-keys": "8.72.1", + "debug": "^4.4.3", + "minimatch": "^10.2.2", + "semver": "^7.7.3", + "tinyglobby": "^0.2.15", + "ts-api-utils": "^2.5.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/typescript-estree/node_modules/balanced-match": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", + "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/@typescript-eslint/typescript-estree/node_modules/brace-expansion": { + "version": "5.0.12", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz", + "integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^4.0.2" + }, + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/@typescript-eslint/typescript-estree/node_modules/minimatch": { + "version": "10.2.6", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz", + "integrity": "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "brace-expansion": "^5.0.8" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/@typescript-eslint/utils": { + "version": "8.72.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.72.1.tgz", + "integrity": "sha512-5v5liypurJBFHCBNqh/RjsymAD+VWcE0djuGY/BUqp5fC3Qn+luWDEksjuTtWjPn6i5zQlUtkZCRG/CYG0yCkA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@eslint-community/eslint-utils": "^4.9.1", + "@typescript-eslint/scope-manager": "8.72.1", + "@typescript-eslint/types": "8.72.1", + "@typescript-eslint/typescript-estree": "8.72.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/visitor-keys": { + "version": "8.72.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.72.1.tgz", + "integrity": "sha512-SB8xqipSzZHUePCCLNeYxqnxq83X61/qzNhjQGbTfjxGZIeOEP7tBgWYX05Tcd6CgE02WdTJnh5b8kMZJ/+bnQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/types": "8.72.1", + "eslint-visitor-keys": "^5.0.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-5.0.1.tgz", + "integrity": "sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, "node_modules/@typescript/native-preview": { "version": "7.0.0-dev.20260423.1", "resolved": "https://registry.npmjs.org/@typescript/native-preview/-/native-preview-7.0.0-dev.20260423.1.tgz", @@ -14236,10 +14609,52 @@ "node": ">=10.0.0" } }, + "node_modules/@xterm/addon-image": { + "version": "0.10.0-beta.331", + "resolved": "https://registry.npmjs.org/@xterm/addon-image/-/addon-image-0.10.0-beta.331.tgz", + "integrity": "sha512-ShBTb3QF0ul/i55lfRdJpcu0hlA4aJdqRdzzHdOCws2WUzSsG0SCfMhLjzaoO1dVUGNj2Z7PNLqiXnlyqOinbg==", + "license": "MIT", + "peerDependencies": { + "@xterm/xterm": "^6.1.0-beta.336" + } + }, + "node_modules/@xterm/addon-serialize": { + "version": "0.14.0", + "resolved": "https://registry.npmjs.org/@xterm/addon-serialize/-/addon-serialize-0.14.0.tgz", + "integrity": "sha512-uteyTU1EkrQa2Ux6P/uFl2fzmXI46jy5uoQMKEOM0fKTyiW7cSn0WrFenHm5vO5uEXX/GpwW/FgILvv3r0WbkA==", + "license": "MIT" + }, + "node_modules/@xterm/addon-unicode-graphemes": { + "version": "0.5.0-beta.330", + "resolved": "https://registry.npmjs.org/@xterm/addon-unicode-graphemes/-/addon-unicode-graphemes-0.5.0-beta.330.tgz", + "integrity": "sha512-Zoiv/8tmku4LcU7bEL6zer+DNN6p6F8VCkyviSmbDxpA/W9zSnWDiD/ZpwFDQqegwjSptGzBNMhW2Os1sa+lUw==", + "license": "MIT", + "peerDependencies": { + "@xterm/xterm": "^6.1.0-beta.336" + } + }, + "node_modules/@xterm/addon-webgl": { + "version": "0.20.0-beta.329", + "resolved": "https://registry.npmjs.org/@xterm/addon-webgl/-/addon-webgl-0.20.0-beta.329.tgz", + "integrity": "sha512-bwqMma7X4cCBfwmWqKuhxNLkIXKW0lJTapaQ0g/9Kq7n6D6VCL4dYQCQ6DoeHv27ncJD4WzeoDTCEeSn0cspfg==", + "license": "MIT", + "peerDependencies": { + "@xterm/xterm": "^6.1.0-beta.336" + } + }, "node_modules/@xterm/headless": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/@xterm/headless/-/headless-6.0.0.tgz", - "integrity": "sha512-5Yj1QINYCyzrZtf8OFIHi47iQtI+0qYFPHmouEfG8dHNxbZ9Tb9YGSuLcsEwj9Z+OL75GJqPyJbyoFer80a2Hw==", + "version": "6.1.0-beta.334", + "resolved": "https://registry.npmjs.org/@xterm/headless/-/headless-6.1.0-beta.334.tgz", + "integrity": "sha512-QkwuIeP9dXlk/eOsAbqX8AvtS/W8EhRo6dkl2YYZr+jWAWSfDDMi+zPlegWUflSdsRKMURMvzvvkVZr6GztK4g==", + "license": "MIT", + "workspaces": [ + "addons/*" + ] + }, + "node_modules/@xterm/xterm": { + "version": "6.1.0-beta.336", + "resolved": "https://registry.npmjs.org/@xterm/xterm/-/xterm-6.1.0-beta.336.tgz", + "integrity": "sha512-QrvZZsffXsLW4Z3sba9GqimLvVwlb8b3W1NwZ+l6DdRnpH5pg5cFGWg2ceIburmfaGQ07YJHNekwxxlTcHZ3BA==", "license": "MIT", "workspaces": [ "addons/*" @@ -14252,13 +14667,6 @@ "dev": true, "license": "BSD-2-Clause" }, - "node_modules/7zip-bin": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/7zip-bin/-/7zip-bin-5.2.0.tgz", - "integrity": "sha512-ukTPVhqG4jNzMro2qA9HSCSSVJN3aN7tlb+hfqYCt3ER0yWroeA2VR38MNrOHLQ/cVj+DaIMad0kFCtWWowh/A==", - "dev": true, - "license": "MIT" - }, "node_modules/abab": { "version": "2.0.6", "resolved": "https://registry.npmjs.org/abab/-/abab-2.0.6.tgz", @@ -14520,7 +14928,7 @@ "version": "3.1.3", "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==", - "dev": true, + "devOptional": true, "license": "ISC", "dependencies": { "normalize-path": "^3.0.0", @@ -14534,7 +14942,7 @@ "version": "2.3.1", "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", - "dev": true, + "devOptional": true, "license": "MIT", "engines": { "node": ">=8.6" @@ -14543,276 +14951,6 @@ "url": "https://github.com/sponsors/jonschlinkert" } }, - "node_modules/app-builder-bin": { - "version": "5.0.0-alpha.12", - "resolved": "https://registry.npmjs.org/app-builder-bin/-/app-builder-bin-5.0.0-alpha.12.tgz", - "integrity": "sha512-j87o0j6LqPL3QRr8yid6c+Tt5gC7xNfYo6uQIQkorAC6MpeayVMZrEDzKmJJ/Hlv7EnOQpaRm53k6ktDYZyB6w==", - "dev": true, - "license": "MIT" - }, - "node_modules/app-builder-lib": { - "version": "26.8.1", - "resolved": "https://registry.npmjs.org/app-builder-lib/-/app-builder-lib-26.8.1.tgz", - "integrity": "sha512-p0Im/Dx5C4tmz8QEE1Yn4MkuPC8PrnlRneMhWJj7BBXQfNTJUshM/bp3lusdEsDbvvfJZpXWnYesgSLvwtM2Zw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@develar/schema-utils": "~2.6.5", - "@electron/asar": "3.4.1", - "@electron/fuses": "^1.8.0", - "@electron/get": "^3.0.0", - "@electron/notarize": "2.5.0", - "@electron/osx-sign": "1.3.3", - "@electron/rebuild": "^4.0.3", - "@electron/universal": "2.0.3", - "@malept/flatpak-bundler": "^0.4.0", - "@types/fs-extra": "9.0.13", - "async-exit-hook": "^2.0.1", - "builder-util": "26.8.1", - "builder-util-runtime": "9.5.1", - "chromium-pickle-js": "^0.2.0", - "ci-info": "4.3.1", - "debug": "^4.3.4", - "dotenv": "^16.4.5", - "dotenv-expand": "^11.0.6", - "ejs": "^3.1.8", - "electron-publish": "26.8.1", - "fs-extra": "^10.1.0", - "hosted-git-info": "^4.1.0", - "isbinaryfile": "^5.0.0", - "jiti": "^2.4.2", - "js-yaml": "^4.1.0", - "json5": "^2.2.3", - "lazy-val": "^1.0.5", - "minimatch": "^10.0.3", - "plist": "3.1.0", - "proper-lockfile": "^4.1.2", - "resedit": "^1.7.0", - "semver": "~7.7.3", - "tar": "^7.5.7", - "temp-file": "^3.4.0", - "tiny-async-pool": "1.3.0", - "which": "^5.0.0" - }, - "engines": { - "node": ">=14.0.0" - }, - "peerDependencies": { - "dmg-builder": "26.8.1", - "electron-builder-squirrel-windows": "26.8.1" - } - }, - "node_modules/app-builder-lib/node_modules/@electron/get": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/@electron/get/-/get-3.1.0.tgz", - "integrity": "sha512-F+nKc0xW+kVbBRhFzaMgPy3KwmuNTYX1fx6+FxxoSnNgwYX6LD7AKBTWkU0MQ6IBoe7dz069CNkR673sPAgkCQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "debug": "^4.1.1", - "env-paths": "^2.2.0", - "fs-extra": "^8.1.0", - "got": "^11.8.5", - "progress": "^2.0.3", - "semver": "^6.2.0", - "sumchecker": "^3.0.1" - }, - "engines": { - "node": ">=14" - }, - "optionalDependencies": { - "global-agent": "^3.0.0" - } - }, - "node_modules/app-builder-lib/node_modules/@electron/get/node_modules/fs-extra": { - "version": "8.1.0", - "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-8.1.0.tgz", - "integrity": "sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g==", - "dev": true, - "license": "MIT", - "dependencies": { - "graceful-fs": "^4.2.0", - "jsonfile": "^4.0.0", - "universalify": "^0.1.0" - }, - "engines": { - "node": ">=6 <7 || >=8" - } - }, - "node_modules/app-builder-lib/node_modules/@electron/get/node_modules/semver": { - "version": "6.3.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", - "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", - "dev": true, - "license": "ISC", - "bin": { - "semver": "bin/semver.js" - } - }, - "node_modules/app-builder-lib/node_modules/balanced-match": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", - "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", - "dev": true, - "license": "MIT", - "engines": { - "node": "18 || 20 || >=22" - } - }, - "node_modules/app-builder-lib/node_modules/brace-expansion": { - "version": "5.0.4", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.4.tgz", - "integrity": "sha512-h+DEnpVvxmfVefa4jFbCf5HdH5YMDXRsmKflpf1pILZWRFlTbJpxeU55nJl4Smt5HQaGzg1o6RHFPJaOqnmBDg==", - "dev": true, - "license": "MIT", - "dependencies": { - "balanced-match": "^4.0.2" - }, - "engines": { - "node": "18 || 20 || >=22" - } - }, - "node_modules/app-builder-lib/node_modules/chownr": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/chownr/-/chownr-3.0.0.tgz", - "integrity": "sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g==", - "dev": true, - "license": "BlueOak-1.0.0", - "engines": { - "node": ">=18" - } - }, - "node_modules/app-builder-lib/node_modules/ci-info": { - "version": "4.3.1", - "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-4.3.1.tgz", - "integrity": "sha512-Wdy2Igu8OcBpI2pZePZ5oWjPC38tmDVx5WKUXKwlLYkA0ozo85sLsLvkBbBn/sZaSCMFOGZJ14fvW9t5/d7kdA==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/sibiraj-s" - } - ], - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/app-builder-lib/node_modules/dotenv": { - "version": "16.6.1", - "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.6.1.tgz", - "integrity": "sha512-uBq4egWHTcTt33a72vpSG0z3HnPuIl6NqYcTrKEg2azoEyl2hpW0zqlxysq2pK9HlDIHyHyakeYaYnSAwd8bow==", - "dev": true, - "license": "BSD-2-Clause", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://dotenvx.com" - } - }, - "node_modules/app-builder-lib/node_modules/isexe": { - "version": "3.1.5", - "resolved": "https://registry.npmjs.org/isexe/-/isexe-3.1.5.tgz", - "integrity": "sha512-6B3tLtFqtQS4ekarvLVMZ+X+VlvQekbe4taUkf/rhVO3d/h0M2rfARm/pXLcPEsjjMsFgrFgSrhQIxcSVrBz8w==", - "dev": true, - "license": "BlueOak-1.0.0", - "engines": { - "node": ">=18" - } - }, - "node_modules/app-builder-lib/node_modules/jsonfile": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-4.0.0.tgz", - "integrity": "sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg==", - "dev": true, - "license": "MIT", - "optionalDependencies": { - "graceful-fs": "^4.1.6" - } - }, - "node_modules/app-builder-lib/node_modules/minimatch": { - "version": "10.2.4", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.4.tgz", - "integrity": "sha512-oRjTw/97aTBN0RHbYCdtF1MQfvusSIBQM0IZEgzl6426+8jSC0nF1a/GmnVLpfB9yyr6g6FTqWqiZVbxrtaCIg==", - "dev": true, - "license": "BlueOak-1.0.0", - "dependencies": { - "brace-expansion": "^5.0.2" - }, - "engines": { - "node": "18 || 20 || >=22" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/app-builder-lib/node_modules/minizlib": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-3.1.0.tgz", - "integrity": "sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw==", - "dev": true, - "license": "MIT", - "dependencies": { - "minipass": "^7.1.2" - }, - "engines": { - "node": ">= 18" - } - }, - "node_modules/app-builder-lib/node_modules/tar": { - "version": "7.5.12", - "resolved": "https://registry.npmjs.org/tar/-/tar-7.5.12.tgz", - "integrity": "sha512-9TsuLcdhOn4XztcQqhNyq1KOwOOED/3k58JAvtULiYqbO8B/0IBAAIE1hj0Svmm58k27TmcigyDI0deMlgG3uw==", - "dev": true, - "license": "BlueOak-1.0.0", - "dependencies": { - "@isaacs/fs-minipass": "^4.0.0", - "chownr": "^3.0.0", - "minipass": "^7.1.2", - "minizlib": "^3.1.0", - "yallist": "^5.0.0" - }, - "engines": { - "node": ">=18" - } - }, - "node_modules/app-builder-lib/node_modules/universalify": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.2.tgz", - "integrity": "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 4.0.0" - } - }, - "node_modules/app-builder-lib/node_modules/which": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/which/-/which-5.0.0.tgz", - "integrity": "sha512-JEdGzHwwkrbWoGOlIHqQ5gtprKGOenpDHpxE9zVR1bWbOtYRyPPHMe9FaP6x61CmNaTThSkb0DAJte5jD+DmzQ==", - "dev": true, - "license": "ISC", - "dependencies": { - "isexe": "^3.1.1" - }, - "bin": { - "node-which": "bin/which.js" - }, - "engines": { - "node": "^18.17.0 || >=20.5.0" - } - }, - "node_modules/app-builder-lib/node_modules/yallist": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-5.0.0.tgz", - "integrity": "sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw==", - "dev": true, - "license": "BlueOak-1.0.0", - "engines": { - "node": ">=18" - } - }, "node_modules/arg": { "version": "5.0.2", "resolved": "https://registry.npmjs.org/arg/-/arg-5.0.2.tgz", @@ -15052,15 +15190,19 @@ "safer-buffer": "~2.1.0" } }, - "node_modules/assert-plus": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/assert-plus/-/assert-plus-1.0.0.tgz", - "integrity": "sha512-NfJ4UzBCcQGLDlQq7nHxH+tv3kyZ0hHQqF5BO6J7tNJeP5do1llPr8dZ8zHonfhAu0PHAdMkSo+8o0wxg9lZWw==", + "node_modules/asn1js": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/asn1js/-/asn1js-3.1.0.tgz", + "integrity": "sha512-HWYi1THkOqguCiO+vwj09ZkQFD2kKEsejYHAYCtX0D80WVdoDnvRc9IukXX/jeb0T9NRWJnRtqwdbHltnFjwXA==", "dev": true, - "license": "MIT", - "optional": true, + "license": "BSD-3-Clause", + "dependencies": { + "pvtsutils": "^1.3.6", + "pvutils": "^1.2.0", + "tslib": "^2.8.1" + }, "engines": { - "node": ">=0.8" + "node": ">=12.0.0" } }, "node_modules/assertion-error": { @@ -15165,6 +15307,13 @@ "integrity": "sha512-aDczADvlvTGajTDjcjpJMqRkOF6Qdz3YbPZm/PyW6tKPkx2hlYBzxMhEywM/tU72HrVZjgl5VCdRuMlA7pZ8Gw==", "license": "MIT" }, + "node_modules/aws4": { + "version": "1.13.2", + "resolved": "https://registry.npmjs.org/aws4/-/aws4-1.13.2.tgz", + "integrity": "sha512-lHe62zvbTB5eEABUVi/AwVh0ZKY9rMMDhmm+eeyuuUQbQ3+J+fONVQOZyj+DdrvD4BY33uYniyRJ4UJIaSKAfw==", + "dev": true, + "license": "MIT" + }, "node_modules/axios": { "version": "1.13.6", "resolved": "https://registry.npmjs.org/axios/-/axios-1.13.6.tgz", @@ -15208,7 +15357,7 @@ "version": "29.7.0", "resolved": "https://registry.npmjs.org/babel-jest/-/babel-jest-29.7.0.tgz", "integrity": "sha512-BrvGY3xZSwEcCzKvKsCi2GgHqDqsYkOP4/by5xCgIwGXQxIEh+8ew3gmrE1y7XRR6LHZIj6yLYnUi/mm2KXKBg==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@jest/transform": "^29.7.0", @@ -15230,7 +15379,7 @@ "version": "3.0.0", "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", - "dev": true, + "devOptional": true, "license": "MIT", "engines": { "node": ">=8" @@ -15250,7 +15399,7 @@ "version": "6.1.1", "resolved": "https://registry.npmjs.org/babel-plugin-istanbul/-/babel-plugin-istanbul-6.1.1.tgz", "integrity": "sha512-Y1IQok9821cC9onCx5otgFfRm7Lm+I+wwxOx738M/WLPZ9Q42m4IG5W0FNX8WLL2gYMZo3JkuXIH2DOpWM+qwA==", - "dev": true, + "devOptional": true, "license": "BSD-3-Clause", "dependencies": { "@babel/helper-plugin-utils": "^7.0.0", @@ -15267,7 +15416,7 @@ "version": "29.6.3", "resolved": "https://registry.npmjs.org/babel-plugin-jest-hoist/-/babel-plugin-jest-hoist-29.6.3.tgz", "integrity": "sha512-ESAc/RJvGTFEzRwOTT4+lNDk/GNHMkKbNzsvT0qKRfDyyYTskxB5rnU2njIDYVxXCBHHEI1c0YwHob3WaYujOg==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@babel/template": "^7.3.3", @@ -15365,7 +15514,7 @@ "version": "1.2.0", "resolved": "https://registry.npmjs.org/babel-preset-current-node-syntax/-/babel-preset-current-node-syntax-1.2.0.tgz", "integrity": "sha512-E/VlAEzRrsLEb2+dv8yp3bo4scof3l9nR4lrld+Iy5NyVqgVYUJnDAmunkhPMisRI32Qc4iRiz425d8vM++2fg==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@babel/plugin-syntax-async-generators": "^7.8.4", @@ -15436,7 +15585,7 @@ "version": "29.6.3", "resolved": "https://registry.npmjs.org/babel-preset-jest/-/babel-preset-jest-29.6.3.tgz", "integrity": "sha512-0B3bhxR6snWXJZtR/RliHTDPRgn1sNHOR0yVtq/IiQFyuOVjFS+wuio/R4gSNkyYmKmJB4wGZv2NZanmKmTnNA==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "babel-plugin-jest-hoist": "^29.6.3", @@ -15469,7 +15618,7 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", - "dev": true, + "devOptional": true, "license": "MIT" }, "node_modules/barcode-detector": { @@ -15607,6 +15756,13 @@ "integrity": "sha512-F1+K8EbfOZE49dtoPtmxUQrpXaBIl3ICvasLh+nJta0xkz+9kF/7uet9fLnwKqhDrmj6g+6K3Tw9yQPUg2ka5g==", "license": "MIT" }, + "node_modules/bluebird": { + "version": "3.7.2", + "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.7.2.tgz", + "integrity": "sha512-XpNj6GDQzdfW+r2Wnn7xiSAd7TM3jzkxGXBGTtWKuSXv1xUV+azxAm8jdWZN06QTQk+2N2XB9jRDkvbmQmcRtg==", + "dev": true, + "license": "MIT" + }, "node_modules/body-parser": { "version": "1.20.4", "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.4.tgz", @@ -15808,31 +15964,6 @@ "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", "license": "MIT" }, - "node_modules/builder-util": { - "version": "26.8.1", - "resolved": "https://registry.npmjs.org/builder-util/-/builder-util-26.8.1.tgz", - "integrity": "sha512-pm1lTYbGyc90DHgCDO7eo8Rl4EqKLciayNbZqGziqnH9jrlKe8ZANGdityLZU+pJh16dfzjAx2xQq9McuIPEtw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/debug": "^4.1.6", - "7zip-bin": "~5.2.0", - "app-builder-bin": "5.0.0-alpha.12", - "builder-util-runtime": "9.5.1", - "chalk": "^4.1.2", - "cross-spawn": "^7.0.6", - "debug": "^4.3.4", - "fs-extra": "^10.1.0", - "http-proxy-agent": "^7.0.0", - "https-proxy-agent": "^7.0.0", - "js-yaml": "^4.1.0", - "sanitize-filename": "^1.6.3", - "source-map-support": "^0.5.19", - "stat-mode": "^1.0.0", - "temp-file": "^3.4.0", - "tiny-async-pool": "1.3.0" - } - }, "node_modules/builder-util-runtime": { "version": "9.5.1", "resolved": "https://registry.npmjs.org/builder-util-runtime/-/builder-util-runtime-9.5.1.tgz", @@ -15846,44 +15977,6 @@ "node": ">=12.0.0" } }, - "node_modules/builder-util/node_modules/agent-base": { - "version": "7.1.4", - "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", - "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 14" - } - }, - "node_modules/builder-util/node_modules/http-proxy-agent": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz", - "integrity": "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==", - "dev": true, - "license": "MIT", - "dependencies": { - "agent-base": "^7.1.0", - "debug": "^4.3.4" - }, - "engines": { - "node": ">= 14" - } - }, - "node_modules/builder-util/node_modules/https-proxy-agent": { - "version": "7.0.6", - "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", - "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", - "dev": true, - "license": "MIT", - "dependencies": { - "agent-base": "^7.1.2", - "debug": "4" - }, - "engines": { - "node": ">= 14" - } - }, "node_modules/bunyan": { "version": "1.8.15", "resolved": "https://registry.npmjs.org/bunyan/-/bunyan-1.8.15.tgz", @@ -15912,98 +16005,14 @@ "node": ">= 0.8" } }, - "node_modules/cacache": { - "version": "19.0.1", - "resolved": "https://registry.npmjs.org/cacache/-/cacache-19.0.1.tgz", - "integrity": "sha512-hdsUxulXCi5STId78vRVYEtDAjq99ICAUktLTeTYsLoTE6Z8dS0c8pWNCxwdrk9YfJeobDZc2Y186hD/5ZQgFQ==", + "node_modules/bytestreamjs": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/bytestreamjs/-/bytestreamjs-2.0.1.tgz", + "integrity": "sha512-U1Z/ob71V/bXfVABvNr/Kumf5VyeQRBEm6Txb0PQ6S7V5GpBM3w4Cbqz/xPDicR5tN0uvDifng8C+5qECeGwyQ==", "dev": true, - "license": "ISC", - "dependencies": { - "@npmcli/fs": "^4.0.0", - "fs-minipass": "^3.0.0", - "glob": "^10.2.2", - "lru-cache": "^10.0.1", - "minipass": "^7.0.3", - "minipass-collect": "^2.0.1", - "minipass-flush": "^1.0.5", - "minipass-pipeline": "^1.2.4", - "p-map": "^7.0.2", - "ssri": "^12.0.0", - "tar": "^7.4.3", - "unique-filename": "^4.0.0" - }, + "license": "BSD-3-Clause", "engines": { - "node": "^18.17.0 || >=20.5.0" - } - }, - "node_modules/cacache/node_modules/chownr": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/chownr/-/chownr-3.0.0.tgz", - "integrity": "sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g==", - "dev": true, - "license": "BlueOak-1.0.0", - "engines": { - "node": ">=18" - } - }, - "node_modules/cacache/node_modules/fs-minipass": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/fs-minipass/-/fs-minipass-3.0.3.tgz", - "integrity": "sha512-XUBA9XClHbnJWSfBzjkm6RvPsyg3sryZt06BEQoXcF7EK/xpGaQYJgQKDJSUH5SGZ76Y7pFx1QBnXz09rU5Fbw==", - "dev": true, - "license": "ISC", - "dependencies": { - "minipass": "^7.0.3" - }, - "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" - } - }, - "node_modules/cacache/node_modules/lru-cache": { - "version": "10.4.3", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz", - "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==", - "dev": true, - "license": "ISC" - }, - "node_modules/cacache/node_modules/minizlib": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-3.1.0.tgz", - "integrity": "sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw==", - "dev": true, - "license": "MIT", - "dependencies": { - "minipass": "^7.1.2" - }, - "engines": { - "node": ">= 18" - } - }, - "node_modules/cacache/node_modules/tar": { - "version": "7.5.12", - "resolved": "https://registry.npmjs.org/tar/-/tar-7.5.12.tgz", - "integrity": "sha512-9TsuLcdhOn4XztcQqhNyq1KOwOOED/3k58JAvtULiYqbO8B/0IBAAIE1hj0Svmm58k27TmcigyDI0deMlgG3uw==", - "dev": true, - "license": "BlueOak-1.0.0", - "dependencies": { - "@isaacs/fs-minipass": "^4.0.0", - "chownr": "^3.0.0", - "minipass": "^7.1.2", - "minizlib": "^3.1.0", - "yallist": "^5.0.0" - }, - "engines": { - "node": ">=18" - } - }, - "node_modules/cacache/node_modules/yallist": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-5.0.0.tgz", - "integrity": "sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw==", - "dev": true, - "license": "BlueOak-1.0.0", - "engines": { - "node": ">=18" + "node": ">=6.0.0" } }, "node_modules/cacheable-lookup": { @@ -16103,7 +16112,7 @@ "version": "3.1.0", "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", - "dev": true, + "devOptional": true, "license": "MIT", "engines": { "node": ">=6" @@ -16378,6 +16387,14 @@ "node": ">=8" } }, + "node_modules/cjs-module-lexer": { + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/cjs-module-lexer/-/cjs-module-lexer-1.4.3.tgz", + "integrity": "sha512-9z8TZaGM1pfswYeXrUpzPrkx8UnWYdhJclsiYMm6x/w5+nN+8Tf/LnAgfLGQCm59qAOxU8WwHEq2vNwF6i4j+Q==", + "devOptional": true, + "license": "MIT", + "peer": true + }, "node_modules/clean-stack": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/clean-stack/-/clean-stack-3.0.1.tgz", @@ -16432,40 +16449,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/cli-truncate": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/cli-truncate/-/cli-truncate-2.1.0.tgz", - "integrity": "sha512-n8fOixwDD6b/ObinzTrp1ZKFzbgvKZvuz/TvejnLn1aQfC6r52XEx85FmuC+3HI+JM7coBRXUvNqEU2PHVrHpg==", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "slice-ansi": "^3.0.0", - "string-width": "^4.2.0" - }, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/cli-truncate/node_modules/slice-ansi": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-3.0.0.tgz", - "integrity": "sha512-pSyv7bSTC7ig9Dcgbw9AuRNUb5k5V6oDudjZoMBSr13qpLBG7tB+zgCkARjq7xIUgdz5P1Qe8u+rSGdouOOIyQ==", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "ansi-styles": "^4.0.0", - "astral-regex": "^2.0.0", - "is-fullwidth-code-point": "^3.0.0" - }, - "engines": { - "node": ">=8" - } - }, "node_modules/client-only": { "version": "0.0.1", "resolved": "https://registry.npmjs.org/client-only/-/client-only-0.0.1.tgz", @@ -16508,11 +16491,23 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/co": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/co/-/co-4.6.0.tgz", + "integrity": "sha512-QVb0dM5HvG+uaxitm8wONl7jltx8dqhfU33DcqtOZcLSVIKSDDLDi7+0LbAKiyI8hD9u42m2YxXSkMGWThaecQ==", + "devOptional": true, + "license": "MIT", + "peer": true, + "engines": { + "iojs": ">= 1.0.0", + "node": ">= 0.12.0" + } + }, "node_modules/collect-v8-coverage": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/collect-v8-coverage/-/collect-v8-coverage-1.0.3.tgz", "integrity": "sha512-1L5aqIkwPfiodaMgQunkF1zRhNqifHBmtbbbxcr6yVxxBnliw4TDOW6NxpO8DJLgJ16OT+Y4ztZqP6p/FtXnAw==", - "dev": true, + "devOptional": true, "license": "MIT" }, "node_modules/color": { @@ -16677,7 +16672,7 @@ "version": "0.0.1", "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", - "dev": true, + "devOptional": true, "license": "MIT" }, "node_modules/concurrently": { @@ -16839,41 +16834,27 @@ "layout-base": "^1.0.0" } }, - "node_modules/crc": { - "version": "3.8.0", - "resolved": "https://registry.npmjs.org/crc/-/crc-3.8.0.tgz", - "integrity": "sha512-iX3mfgcTMIq3ZKLIsVFAbv7+Mc10kxabAGQb8HvjA1o3T1PIYprbakQ65d3I+2HGHt6nSKkM9PYjgoJO2KcFBQ==", - "dev": true, + "node_modules/create-jest": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/create-jest/-/create-jest-29.7.0.tgz", + "integrity": "sha512-Adz2bdH0Vq3F53KEMJOoftQFutWCukm6J24wbPWRO4k1kMY7gS7ds/uoJkNuV8wDCtWWnuwGcJwpWcih+zEW1Q==", + "devOptional": true, "license": "MIT", - "optional": true, + "peer": true, "dependencies": { - "buffer": "^5.1.0" - } - }, - "node_modules/crc/node_modules/buffer": { - "version": "5.7.1", - "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", - "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT", - "optional": true, - "dependencies": { - "base64-js": "^1.3.1", - "ieee754": "^1.1.13" + "@jest/types": "^29.6.3", + "chalk": "^4.0.0", + "exit": "^0.1.2", + "graceful-fs": "^4.2.9", + "jest-config": "^29.7.0", + "jest-util": "^29.7.0", + "prompts": "^2.0.1" + }, + "bin": { + "create-jest": "bin/create-jest.js" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, "node_modules/create-require": { @@ -16889,6 +16870,15 @@ "integrity": "sha512-VQ2MBenTq1fWZUH9DJNGti7kKv6EeAuYr3cLwxUWhIu1baTaXh4Ib5W2CqHVqib4/MqbYGJqiL3Zb8GJZr3l4g==", "license": "MIT" }, + "node_modules/cross-dirname": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/cross-dirname/-/cross-dirname-0.1.0.tgz", + "integrity": "sha512-+R08/oI0nl3vfPcqftZRpytksBXDzOUveBq/NBVx0sUp1axwzPQrKinNx5yd5sxPu8j1wIy8AfnVQ+5eFdha6Q==", + "dev": true, + "license": "MIT", + "optional": true, + "peer": true + }, "node_modules/cross-env": { "version": "10.1.0", "resolved": "https://registry.npmjs.org/cross-env/-/cross-env-10.1.0.tgz", @@ -17797,6 +17787,22 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/dedent": { + "version": "1.7.2", + "resolved": "https://registry.npmjs.org/dedent/-/dedent-1.7.2.tgz", + "integrity": "sha512-WzMx3mW98SN+zn3hgemf4OzdmyNhhhKz5Ay0pUfQiMQ3e1g+xmTJWp/pKdwKVXhdSkAEGIIzqeuWrL3mV/AXbA==", + "devOptional": true, + "license": "MIT", + "peer": true, + "peerDependencies": { + "babel-plugin-macros": "^3.1.0" + }, + "peerDependenciesMeta": { + "babel-plugin-macros": { + "optional": true + } + } + }, "node_modules/deep-is": { "version": "0.1.4", "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz", @@ -17964,6 +17970,17 @@ "node": ">=8" } }, + "node_modules/detect-newline": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/detect-newline/-/detect-newline-3.1.0.tgz", + "integrity": "sha512-TLz+x/vEXm/Y7P7wn1EJFNLxYpUD4TgMosxY6fAVJUnJMbupHBOncxyWUG9OpTaH9EBD7uFI5LfEgmMOc54DsA==", + "devOptional": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=8" + } + }, "node_modules/detect-node": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/detect-node/-/detect-node-2.1.0.tgz", @@ -18004,7 +18021,7 @@ "version": "29.6.3", "resolved": "https://registry.npmjs.org/diff-sequences/-/diff-sequences-29.6.3.tgz", "integrity": "sha512-EjePK1srD3P08o2j4f0ExnylqRs5B9tJjcp9t1krH2qRi8CCdsYfwe9JgSLurFBWwq4uOlipzfk5fHNvwFKr8Q==", - "dev": true, + "devOptional": true, "license": "MIT", "engines": { "node": "^14.15.0 || ^16.10.0 || >=18.0.0" @@ -18064,76 +18081,6 @@ "node": ">=8" } }, - "node_modules/dmg-builder": { - "version": "26.8.1", - "resolved": "https://registry.npmjs.org/dmg-builder/-/dmg-builder-26.8.1.tgz", - "integrity": "sha512-glMJgnTreo8CFINujtAhCgN96QAqApDMZ8Vl1r8f0QT8QprvC1UCltV4CcWj20YoIyLZx6IUskaJZ0NV8fokcg==", - "dev": true, - "license": "MIT", - "dependencies": { - "app-builder-lib": "26.8.1", - "builder-util": "26.8.1", - "fs-extra": "^10.1.0", - "iconv-lite": "^0.6.2", - "js-yaml": "^4.1.0" - }, - "optionalDependencies": { - "dmg-license": "^1.0.11" - } - }, - "node_modules/dmg-license": { - "version": "1.0.11", - "resolved": "https://registry.npmjs.org/dmg-license/-/dmg-license-1.0.11.tgz", - "integrity": "sha512-ZdzmqwKmECOWJpqefloC5OJy1+WZBBse5+MR88z9g9Zn4VY+WYUkAyojmhzJckH5YbbZGcYIuGAkY5/Ys5OM2Q==", - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "dependencies": { - "@types/plist": "^3.0.1", - "@types/verror": "^1.10.3", - "ajv": "^6.10.0", - "crc": "^3.8.0", - "iconv-corefoundation": "^1.1.7", - "plist": "^3.0.4", - "smart-buffer": "^4.0.2", - "verror": "^1.10.0" - }, - "bin": { - "dmg-license": "bin/dmg-license.js" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/dmg-license/node_modules/ajv": { - "version": "6.14.0", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.14.0.tgz", - "integrity": "sha512-IWrosm/yrn43eiKqkfkHis7QioDleaXQHdDVPKg0FSwwd/DuvyX79TZnFOnYpB7dcsFAMmtFztZuXPDvSePkFw==", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "fast-deep-equal": "^3.1.1", - "fast-json-stable-stringify": "^2.0.0", - "json-schema-traverse": "^0.4.1", - "uri-js": "^4.2.2" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/epoberezkin" - } - }, - "node_modules/dmg-license/node_modules/json-schema-traverse": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", - "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", - "dev": true, - "license": "MIT", - "optional": true - }, "node_modules/dnssd-advertise": { "version": "1.1.6", "resolved": "https://registry.npmjs.org/dnssd-advertise/-/dnssd-advertise-1.1.6.tgz", @@ -18325,6 +18272,16 @@ "node": ">= 0.4" } }, + "node_modules/duplexer2": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/duplexer2/-/duplexer2-0.1.4.tgz", + "integrity": "sha512-asLFVfWWtJ90ZyOUHMqk7/S2w2guQKxUI2itj3d92ADHhxUSbCMGi1f1cBcJ7xM1To+pE/Khbwo1yuNbMEPKeA==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "readable-stream": "^2.0.2" + } + }, "node_modules/eas-cli": { "version": "16.32.0", "resolved": "https://registry.npmjs.org/eas-cli/-/eas-cli-16.32.0.tgz", @@ -18645,48 +18602,6 @@ "node": ">= 22.12.0" } }, - "node_modules/electron-builder": { - "version": "26.8.1", - "resolved": "https://registry.npmjs.org/electron-builder/-/electron-builder-26.8.1.tgz", - "integrity": "sha512-uWhx1r74NGpCagG0ULs/P9Nqv2nsoo+7eo4fLUOB8L8MdWltq9odW/uuLXMFCDGnPafknYLZgjNX0ZIFRzOQAw==", - "dev": true, - "license": "MIT", - "dependencies": { - "app-builder-lib": "26.8.1", - "builder-util": "26.8.1", - "builder-util-runtime": "9.5.1", - "chalk": "^4.1.2", - "ci-info": "^4.2.0", - "dmg-builder": "26.8.1", - "fs-extra": "^10.1.0", - "lazy-val": "^1.0.5", - "simple-update-notifier": "2.0.0", - "yargs": "^17.6.2" - }, - "bin": { - "electron-builder": "cli.js", - "install-app-deps": "install-app-deps.js" - }, - "engines": { - "node": ">=14.0.0" - } - }, - "node_modules/electron-builder/node_modules/ci-info": { - "version": "4.4.0", - "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-4.4.0.tgz", - "integrity": "sha512-77PSwercCZU2Fc4sX94eF8k8Pxte6JAwL4/ICZLFjJLqegs7kCuAsqqj/70NQF6TvDpgFjkubQB2FW2ZZddvQg==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/sibiraj-s" - } - ], - "license": "MIT", - "engines": { - "node": ">=8" - } - }, "node_modules/electron-log": { "version": "5.4.3", "resolved": "https://registry.npmjs.org/electron-log/-/electron-log-5.4.3.tgz", @@ -18696,36 +18611,6 @@ "node": ">= 14" } }, - "node_modules/electron-publish": { - "version": "26.8.1", - "resolved": "https://registry.npmjs.org/electron-publish/-/electron-publish-26.8.1.tgz", - "integrity": "sha512-q+jrSTIh/Cv4eGZa7oVR+grEJo/FoLMYBAnSL5GCtqwUpr1T+VgKB/dn1pnzxIxqD8S/jP1yilT9VrwCqINR4w==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/fs-extra": "^9.0.11", - "builder-util": "26.8.1", - "builder-util-runtime": "9.5.1", - "chalk": "^4.1.2", - "form-data": "^4.0.5", - "fs-extra": "^10.1.0", - "lazy-val": "^1.0.5", - "mime": "^2.5.2" - } - }, - "node_modules/electron-publish/node_modules/mime": { - "version": "2.6.0", - "resolved": "https://registry.npmjs.org/mime/-/mime-2.6.0.tgz", - "integrity": "sha512-USPkMeET31rOMiarsBNIHZKLGgvKc/LrjofAnBlOttf5ajRvqiRA8QsenbcooctK6d6Ts6aqZXBA+XbkKthiQg==", - "dev": true, - "license": "MIT", - "bin": { - "mime": "cli.js" - }, - "engines": { - "node": ">=4.0.0" - } - }, "node_modules/electron-to-chromium": { "version": "1.5.307", "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.307.tgz", @@ -18748,6 +18633,66 @@ "tiny-typed-emitter": "^2.1.0" } }, + "node_modules/electron-winstaller": { + "version": "5.4.0", + "resolved": "https://registry.npmjs.org/electron-winstaller/-/electron-winstaller-5.4.0.tgz", + "integrity": "sha512-bO3y10YikuUwUuDUQRM4KfwNkKhnpVO7IPdbsrejwN9/AABJzzTQ4GeHwyzNSrVO+tEH3/Np255a3sVZpZDjvg==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@electron/asar": "^3.2.1", + "debug": "^4.1.1", + "fs-extra": "^7.0.1", + "lodash": "^4.17.21", + "temp": "^0.9.0" + }, + "engines": { + "node": ">=8.0.0" + }, + "optionalDependencies": { + "@electron/windows-sign": "^1.1.2" + } + }, + "node_modules/electron-winstaller/node_modules/fs-extra": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-7.0.1.tgz", + "integrity": "sha512-YJDaCJZEnBmcbw13fvdAM9AwNOJwOzrE4pqMqBq5nFiEqXUqHwlK4B+3pUw6JNvfSPtX05xFHtYy/1ni01eGCw==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "graceful-fs": "^4.1.2", + "jsonfile": "^4.0.0", + "universalify": "^0.1.0" + }, + "engines": { + "node": ">=6 <7 || >=8" + } + }, + "node_modules/electron-winstaller/node_modules/jsonfile": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-4.0.0.tgz", + "integrity": "sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg==", + "dev": true, + "license": "MIT", + "peer": true, + "optionalDependencies": { + "graceful-fs": "^4.1.6" + } + }, + "node_modules/electron-winstaller/node_modules/universalify": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.2.tgz", + "integrity": "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">= 4.0.0" + } + }, "node_modules/electron/node_modules/@types/node": { "version": "24.13.3", "resolved": "https://registry.npmjs.org/@types/node/-/node-24.13.3.tgz", @@ -18769,7 +18714,7 @@ "version": "0.13.1", "resolved": "https://registry.npmjs.org/emittery/-/emittery-0.13.1.tgz", "integrity": "sha512-DeWwawk6r5yR9jFgnDKYt4sLS0LmHJJi3ZOnb5/JdbYwj3nW+FxQnHIjhBKz8YLC7oRNPVM9NQ47I3CVx34eqQ==", - "dev": true, + "devOptional": true, "license": "MIT", "engines": { "node": ">=12" @@ -18869,7 +18814,7 @@ "version": "1.3.4", "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.4.tgz", "integrity": "sha512-sqQamAnR14VgCr1A618A3sGrygcpK+HEbenA/HiEAkkUwcZIIB/tgWqHFxWgOyDh4nB4JCRimh79dR5Ywc9MDQ==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "is-arrayish": "^0.2.1" @@ -19189,7 +19134,6 @@ "dev": true, "license": "BSD-3-Clause", "optional": true, - "peer": true, "engines": { "node": ">=0.10.0" } @@ -19270,6 +19214,60 @@ "eslint": ">=6.0.0" } }, + "node_modules/eslint-config-prettier": { + "version": "9.1.2", + "resolved": "https://registry.npmjs.org/eslint-config-prettier/-/eslint-config-prettier-9.1.2.tgz", + "integrity": "sha512-iI1f+D2ViGn+uvv5HuHVUamg8ll4tN+JRHGc6IJi4TP9Kl976C57fzPXgseXNs8v0iA8aSJpHsTWjDb9QJamGQ==", + "dev": true, + "license": "MIT", + "bin": { + "eslint-config-prettier": "bin/cli.js" + }, + "peerDependencies": { + "eslint": ">=7.0.0" + } + }, + "node_modules/eslint-config-universe": { + "version": "15.2.0", + "resolved": "https://registry.npmjs.org/eslint-config-universe/-/eslint-config-universe-15.2.0.tgz", + "integrity": "sha512-n2662q/mM+2pTFVz7ELosqhN+/nbR75Ut/4vLme40kKSHHe0oPbPMxgPqyYrASlANuSDP4aAJ71rRviDMCZTxg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/eslint-plugin": "^8.59.0", + "@typescript-eslint/parser": "^8.59.0", + "eslint-config-prettier": "^9.1.0", + "eslint-plugin-import": "^2.31.0", + "eslint-plugin-n": "^17.17.0", + "eslint-plugin-node": "^11.1.0", + "eslint-plugin-prettier": "^5.2.6", + "eslint-plugin-react": "^7.37.5", + "eslint-plugin-react-hooks": "^7.0.0", + "globals": "^16.0.0" + }, + "peerDependencies": { + "eslint": ">=8.10", + "prettier": ">=3" + }, + "peerDependenciesMeta": { + "prettier": { + "optional": true + } + } + }, + "node_modules/eslint-config-universe/node_modules/globals": { + "version": "16.5.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-16.5.0.tgz", + "integrity": "sha512-c/c15i26VrJ4IRt5Z89DnIzCGDn9EcebibhAOjw5ibqEHsE1wLUgkPn9RDmNcUKyU87GeaL633nyJ+pplFR2ZQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/eslint-import-resolver-node": { "version": "0.3.9", "resolved": "https://registry.npmjs.org/eslint-import-resolver-node/-/eslint-import-resolver-node-0.3.9.tgz", @@ -19547,9 +19545,9 @@ } }, "node_modules/eslint-plugin-node/node_modules/brace-expansion": { - "version": "1.1.12", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz", - "integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==", + "version": "1.1.21", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.21.tgz", + "integrity": "sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw==", "dev": true, "license": "MIT", "dependencies": { @@ -19581,14 +19579,14 @@ } }, "node_modules/eslint-plugin-prettier": { - "version": "5.5.5", - "resolved": "https://registry.npmjs.org/eslint-plugin-prettier/-/eslint-plugin-prettier-5.5.5.tgz", - "integrity": "sha512-hscXkbqUZ2sPithAuLm5MXL+Wph+U7wHngPBv9OMWwlP8iaflyxpjTYZkmdgB4/vPIhemRlBEoLrH7UC1n7aUw==", + "version": "5.5.7", + "resolved": "https://registry.npmjs.org/eslint-plugin-prettier/-/eslint-plugin-prettier-5.5.7.tgz", + "integrity": "sha512-WjHyn3GrFd+ZR0rzsLiM4zJZ35PZMOE0SUIxzGmnWNG0126yNfJKJzObmmkYDwHJfGlkz3PSlzyG9ez/LJntwg==", "dev": true, "license": "MIT", "dependencies": { "prettier-linter-helpers": "^1.0.1", - "synckit": "^0.11.12" + "synckit": "^0.12.3" }, "engines": { "node": "^14.18.0 || >=16.0.0" @@ -19644,6 +19642,43 @@ "eslint": "^3 || ^4 || ^5 || ^6 || ^7 || ^8 || ^9.7" } }, + "node_modules/eslint-plugin-react-hooks": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/eslint-plugin-react-hooks/-/eslint-plugin-react-hooks-7.1.1.tgz", + "integrity": "sha512-f2I7Gw6JbvCexzIInuSbZpfdQ44D7iqdWX01FKLvrPgqxoE7oMj8clOfto8U6vYiz4yd5oKu39rRSVOe1zRu0g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/core": "^7.24.4", + "@babel/parser": "^7.24.4", + "hermes-parser": "^0.25.1", + "zod": "^3.25.0 || ^4.0.0", + "zod-validation-error": "^3.5.0 || ^4.0.0" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "eslint": "^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0-0 || ^9.0.0 || ^10.0.0" + } + }, + "node_modules/eslint-plugin-react-hooks/node_modules/hermes-estree": { + "version": "0.25.1", + "resolved": "https://registry.npmjs.org/hermes-estree/-/hermes-estree-0.25.1.tgz", + "integrity": "sha512-0wUoCcLp+5Ev5pDW2OriHC2MJCbwLwuRx+gAqMTOkGKJJiBCLjtrvy4PWUGn6MIVefecRpzoOZ/UV6iGdOr+Cw==", + "dev": true, + "license": "MIT" + }, + "node_modules/eslint-plugin-react-hooks/node_modules/hermes-parser": { + "version": "0.25.1", + "resolved": "https://registry.npmjs.org/hermes-parser/-/hermes-parser-0.25.1.tgz", + "integrity": "sha512-6pEjquH3rqaI6cYAXYPcz9MS4rY6R4ngRgrgfDshRptUZIc3lw0MCIJIGDj9++mfySOuPTHB4nrSW99BCvOPIA==", + "dev": true, + "license": "MIT", + "dependencies": { + "hermes-estree": "0.25.1" + } + }, "node_modules/eslint-plugin-react/node_modules/brace-expansion": { "version": "1.1.12", "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz", @@ -19841,7 +19876,7 @@ "version": "4.0.1", "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", - "dev": true, + "devOptional": true, "license": "BSD-2-Clause", "bin": { "esparse": "bin/esparse.js", @@ -19990,11 +20025,54 @@ "dev": true, "license": "MIT" }, + "node_modules/execa": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/execa/-/execa-5.1.1.tgz", + "integrity": "sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg==", + "devOptional": true, + "license": "MIT", + "peer": true, + "dependencies": { + "cross-spawn": "^7.0.3", + "get-stream": "^6.0.0", + "human-signals": "^2.1.0", + "is-stream": "^2.0.0", + "merge-stream": "^2.0.0", + "npm-run-path": "^4.0.1", + "onetime": "^5.1.2", + "signal-exit": "^3.0.3", + "strip-final-newline": "^2.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sindresorhus/execa?sponsor=1" + } + }, + "node_modules/execa/node_modules/signal-exit": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", + "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", + "devOptional": true, + "license": "ISC", + "peer": true + }, + "node_modules/exit": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/exit/-/exit-0.1.2.tgz", + "integrity": "sha512-Zk/eNKV2zbjpKzrsQ+n1G6poVbErQxJ0LBOJXaKZ1EViLzH+hrLu9cdXI4zw9dBQJslwBEpbQ2P1oS7nDxs6jQ==", + "devOptional": true, + "peer": true, + "engines": { + "node": ">= 0.8.0" + } + }, "node_modules/expect": { "version": "29.7.0", "resolved": "https://registry.npmjs.org/expect/-/expect-29.7.0.tgz", "integrity": "sha512-2Zks0hf1VLFYI1kbh0I5jP3KHHyCHpkfyHBzsSXRFgl/Bg9mWYfMW8oD+PdMPlEwy5HNsR9JutYy6pMeOh61nw==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@jest/expect-utils": "^29.7.0", @@ -20246,6 +20324,131 @@ "react-native": "*" } }, + "node_modules/expo-module-scripts": { + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/expo-module-scripts/-/expo-module-scripts-5.0.8.tgz", + "integrity": "sha512-3YkAic3E6QGQuNEIchq6/0GGSBwR2C70AhDUF7VI7/N3THwUpeqZrX20FxHKN95/wclHs1ljrGvRX+2YTgXxiw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/cli": "^7.23.4", + "@babel/plugin-transform-export-namespace-from": "^7.23.4", + "@babel/preset-env": "^7.23.8", + "@babel/preset-typescript": "^7.23.3", + "@expo/npm-proofread": "^1.0.1", + "@testing-library/react-native": "^13.2.0", + "@tsconfig/node18": "^18.2.2", + "@types/jest": "^29.2.1", + "babel-plugin-dynamic-import-node": "^2.3.3", + "babel-preset-expo": "~54.0.7", + "commander": "^12.1.0", + "eslint-config-universe": "^15.0.3", + "glob": "^13.0.0", + "jest-expo": "~54.0.13", + "jest-snapshot-prettier": "npm:prettier@^2", + "jest-watch-typeahead": "2.2.1", + "resolve-workspace-root": "^2.0.0", + "ts-jest": "~29.0.4", + "typescript": "^5.9.2" + }, + "bin": { + "expo-module": "bin/expo-module.js" + } + }, + "node_modules/expo-module-scripts/node_modules/balanced-match": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", + "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/expo-module-scripts/node_modules/brace-expansion": { + "version": "5.0.12", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz", + "integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^4.0.2" + }, + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/expo-module-scripts/node_modules/commander": { + "version": "12.1.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-12.1.0.tgz", + "integrity": "sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/expo-module-scripts/node_modules/glob": { + "version": "13.0.6", + "resolved": "https://registry.npmjs.org/glob/-/glob-13.0.6.tgz", + "integrity": "sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "minimatch": "^10.2.2", + "minipass": "^7.1.3", + "path-scurry": "^2.0.2" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/expo-module-scripts/node_modules/lru-cache": { + "version": "11.5.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz", + "integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/expo-module-scripts/node_modules/minimatch": { + "version": "10.2.6", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz", + "integrity": "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "brace-expansion": "^5.0.8" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/expo-module-scripts/node_modules/path-scurry": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-2.0.2.tgz", + "integrity": "sha512-3O/iVVsJAPsOnpwWIeD+d6z/7PmqApyQePUtCndjatj/9I5LylHvt5qluFaBT3I5h3r1ejfR056c+FCv+NnNXg==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "lru-cache": "^11.0.0", + "minipass": "^7.1.2" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, "node_modules/expo-modules-autolinking": { "version": "57.0.16", "resolved": "https://registry.npmjs.org/expo-modules-autolinking/-/expo-modules-autolinking-57.0.16.tgz", @@ -20303,18 +20506,6 @@ "react-native": "*" } }, - "node_modules/expo-modules-macros": { - "version": "0.20.0", - "resolved": "https://registry.npmjs.org/expo-modules-macros/-/expo-modules-macros-0.20.0.tgz", - "integrity": "sha512-Ekgb5c9LQPM9CPnmDZdeWcOa1eBbCDUGrgdN5lIFNH2GWDUf9doeAOK7IqQOOVviamy37eIp5FW+N1zyrIwzoA==", - "dev": true, - "license": "MIT", - "peer": true, - "optionalDependencies": { - "@expo/modules-macros-win32-arm64": "0.20.0", - "@expo/modules-macros-win32-x64": "0.20.0" - } - }, "node_modules/expo-router": { "version": "57.0.28", "resolved": "https://registry.npmjs.org/expo-router/-/expo-router-57.0.28.tgz", @@ -20857,17 +21048,6 @@ "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==", "license": "MIT" }, - "node_modules/extsprintf": { - "version": "1.4.1", - "resolved": "https://registry.npmjs.org/extsprintf/-/extsprintf-1.4.1.tgz", - "integrity": "sha512-Wrk35e8ydCKDj/ArClo1VrPVmN8zph5V4AtHwIuHhvMXsKf73UT3BOD+azBIW+3wOJ4FhEH7zyaJCFvChjYvMA==", - "dev": true, - "engines": [ - "node >=0.6.0" - ], - "license": "MIT", - "optional": true - }, "node_modules/fake-indexeddb": { "version": "6.2.5", "resolved": "https://registry.npmjs.org/fake-indexeddb/-/fake-indexeddb-6.2.5.tgz", @@ -20947,7 +21127,7 @@ "version": "2.1.0", "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", - "dev": true, + "devOptional": true, "license": "MIT" }, "node_modules/fast-levenshtein": { @@ -21293,31 +21473,6 @@ "integrity": "sha512-3PYnM29RFXwvAN6Pc/scUfkI7RwhQ/xqyLUyPNlXUp9S40zI8nup9tUSrTLSVnWGBN38FNiGWbwZOB6uR4OGdw==", "license": "MIT" }, - "node_modules/flow-estree": { - "version": "0.331.0", - "resolved": "https://registry.npmjs.org/flow-estree/-/flow-estree-0.331.0.tgz", - "integrity": "sha512-FVLYkSL/ITb/QXBEQvNWPjPooRGswuUtGOwrH+puSlMDneNkxy640+FZsk/TfKL+b7Wbw/Fg9FTUv2bMQDpj2w==", - "dev": true, - "license": "MIT", - "peer": true, - "engines": { - "node": ">=18" - } - }, - "node_modules/flow-parser": { - "version": "0.331.0", - "resolved": "https://registry.npmjs.org/flow-parser/-/flow-parser-0.331.0.tgz", - "integrity": "sha512-vEZcHIlnKeN8JSVtYFczj8sWJfHIJOkz+YG00O/oul/Bete+t1ZhTi+O6JRRLFYvGW+yJkZ0YgL16iStnbkUqQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "flow-estree": "0.331.0" - }, - "engines": { - "node": ">=0.4.0" - } - }, "node_modules/follow-redirects": { "version": "1.15.11", "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.11.tgz", @@ -21507,7 +21662,7 @@ "version": "1.0.0", "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==", - "dev": true, + "devOptional": true, "license": "ISC" }, "node_modules/fsevents": { @@ -21629,7 +21784,7 @@ "version": "0.1.0", "resolved": "https://registry.npmjs.org/get-package-type/-/get-package-type-0.1.0.tgz", "integrity": "sha512-pjzuKtY64GYfWizNAJ0fr9VqttZkNiK2iS430LtIHzjBEr6bX8Am2zm4sW4Ro5wjWW5cAlRL1qAMTcXbjNAO2Q==", - "dev": true, + "devOptional": true, "license": "MIT", "engines": { "node": ">=8.0.0" @@ -21681,6 +21836,20 @@ "node": ">= 0.4" } }, + "node_modules/get-stream": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-6.0.1.tgz", + "integrity": "sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg==", + "devOptional": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/get-symbol-description": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/get-symbol-description/-/get-symbol-description-1.1.0.tgz", @@ -22394,6 +22563,14 @@ "node": ">=12" } }, + "node_modules/html-escaper": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz", + "integrity": "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==", + "devOptional": true, + "license": "MIT", + "peer": true + }, "node_modules/html-parse-stringify": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/html-parse-stringify/-/html-parse-stringify-3.0.1.tgz", @@ -22525,6 +22702,17 @@ "node": ">= 6" } }, + "node_modules/human-signals": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-2.1.0.tgz", + "integrity": "sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw==", + "devOptional": true, + "license": "Apache-2.0", + "peer": true, + "engines": { + "node": ">=10.17.0" + } + }, "node_modules/hyperlinker": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/hyperlinker/-/hyperlinker-1.0.0.tgz", @@ -22569,32 +22757,6 @@ } } }, - "node_modules/iconv-corefoundation": { - "version": "1.1.7", - "resolved": "https://registry.npmjs.org/iconv-corefoundation/-/iconv-corefoundation-1.1.7.tgz", - "integrity": "sha512-T10qvkw0zz4wnm560lOEg0PovVqUXuOFhhHAkixw8/sycy7TJt7v/RrkEKEQnAw2viPSJu6iAkErxnzR0g8PpQ==", - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "dependencies": { - "cli-truncate": "^2.1.0", - "node-addon-api": "^1.6.3" - }, - "engines": { - "node": "^8.11.2 || >=10" - } - }, - "node_modules/iconv-corefoundation/node_modules/node-addon-api": { - "version": "1.7.2", - "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-1.7.2.tgz", - "integrity": "sha512-ibPK3iA+vaY1eEjESkQkM0BbCqFOaZMiXRTtdB0u7b4djtY6JnsjvPdUHVMg6xQt3B8fpTTWHI9A+ADjM9frzg==", - "dev": true, - "license": "MIT", - "optional": true - }, "node_modules/iconv-lite": { "version": "0.6.3", "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz", @@ -22671,6 +22833,27 @@ "node": ">=4" } }, + "node_modules/import-local": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/import-local/-/import-local-3.2.0.tgz", + "integrity": "sha512-2SPlun1JUPWoM6t3F0dw0FkCF/jWY8kttcY4f599GLTSjh2OCuuhdTkJQsEcZzBqbXZGKMK2OqW1oZsjtf/gQA==", + "devOptional": true, + "license": "MIT", + "peer": true, + "dependencies": { + "pkg-dir": "^4.2.0", + "resolve-cwd": "^3.0.0" + }, + "bin": { + "import-local-fixture": "fixtures/cli.js" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/import-meta-resolve": { "version": "4.2.0", "resolved": "https://registry.npmjs.org/import-meta-resolve/-/import-meta-resolve-4.2.0.tgz", @@ -22685,7 +22868,7 @@ "version": "0.1.4", "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==", - "dev": true, + "devOptional": true, "license": "MIT", "engines": { "node": ">=0.8.19" @@ -22709,7 +22892,7 @@ "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==", "deprecated": "This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.", - "dev": true, + "devOptional": true, "license": "ISC", "dependencies": { "once": "^1.3.0", @@ -22847,7 +23030,7 @@ "version": "0.2.1", "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz", "integrity": "sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg==", - "dev": true, + "devOptional": true, "license": "MIT" }, "node_modules/is-async-function": { @@ -23057,6 +23240,17 @@ "node": ">=8" } }, + "node_modules/is-generator-fn": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-generator-fn/-/is-generator-fn-2.1.0.tgz", + "integrity": "sha512-cTIB4yPYL/Grw0EaSzASzg6bBy9gqCofvWN8okThAYIxKJZC+udlRAmGbM0XLeniEJSs8uEgHPGuHSe1XsOLSQ==", + "devOptional": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=6" + } + }, "node_modules/is-generator-function": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/is-generator-function/-/is-generator-function-1.1.2.tgz", @@ -23247,7 +23441,7 @@ "version": "2.0.1", "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz", "integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==", - "dev": true, + "devOptional": true, "license": "MIT", "engines": { "node": ">=8" @@ -23417,7 +23611,7 @@ "version": "3.2.2", "resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-3.2.2.tgz", "integrity": "sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg==", - "dev": true, + "devOptional": true, "license": "BSD-3-Clause", "engines": { "node": ">=8" @@ -23427,7 +23621,7 @@ "version": "5.2.1", "resolved": "https://registry.npmjs.org/istanbul-lib-instrument/-/istanbul-lib-instrument-5.2.1.tgz", "integrity": "sha512-pzqtp31nLv/XFOzXGuvhCb8qhjmTVo5vjVk19XE4CRlSWz0KoeJ3bw9XsA7nOp9YBf4qHjwBxkDzKcME/J29Yg==", - "dev": true, + "devOptional": true, "license": "BSD-3-Clause", "dependencies": { "@babel/core": "^7.12.3", @@ -23444,12 +23638,101 @@ "version": "6.3.1", "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", - "dev": true, + "devOptional": true, "license": "ISC", "bin": { "semver": "bin/semver.js" } }, + "node_modules/istanbul-lib-report": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-3.0.1.tgz", + "integrity": "sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw==", + "devOptional": true, + "license": "BSD-3-Clause", + "peer": true, + "dependencies": { + "istanbul-lib-coverage": "^3.0.0", + "make-dir": "^4.0.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/istanbul-lib-report/node_modules/make-dir": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-4.0.0.tgz", + "integrity": "sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==", + "devOptional": true, + "license": "MIT", + "peer": true, + "dependencies": { + "semver": "^7.5.3" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/istanbul-lib-report/node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "devOptional": true, + "license": "MIT", + "peer": true, + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/istanbul-lib-source-maps": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/istanbul-lib-source-maps/-/istanbul-lib-source-maps-4.0.1.tgz", + "integrity": "sha512-n3s8EwkdFIJCG3BPKBYvskgXGoy88ARzvegkitk60NxRdwltLOTaH7CUiMRXvwYorl0Q712iEjcWB+fK/MrWVw==", + "devOptional": true, + "license": "BSD-3-Clause", + "peer": true, + "dependencies": { + "debug": "^4.1.1", + "istanbul-lib-coverage": "^3.0.0", + "source-map": "^0.6.1" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/istanbul-lib-source-maps/node_modules/source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "devOptional": true, + "license": "BSD-3-Clause", + "peer": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/istanbul-reports": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-3.2.0.tgz", + "integrity": "sha512-HGYWWS/ehqTV3xN10i23tkPkpH46MLCIMFNCaaKNavAXTF1RkqxawEPtnjnGZ6XKSInBKkiOA5BKS+aZiY3AvA==", + "devOptional": true, + "license": "BSD-3-Clause", + "peer": true, + "dependencies": { + "html-escaper": "^2.0.0", + "istanbul-lib-report": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/iterator.prototype": { "version": "1.1.5", "resolved": "https://registry.npmjs.org/iterator.prototype/-/iterator.prototype-1.1.5.tgz", @@ -23502,11 +23785,273 @@ "node": ">=10" } }, + "node_modules/jest": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest/-/jest-29.7.0.tgz", + "integrity": "sha512-NIy3oAFp9shda19hy4HK0HRTWKtPJmGdnvywu01nOqNC2vZg+Z+fvJDxpMQA88eb2I9EcafcdjYgsDthnYTvGw==", + "devOptional": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@jest/core": "^29.7.0", + "@jest/types": "^29.6.3", + "import-local": "^3.0.2", + "jest-cli": "^29.7.0" + }, + "bin": { + "jest": "bin/jest.js" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "peerDependencies": { + "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" + }, + "peerDependenciesMeta": { + "node-notifier": { + "optional": true + } + } + }, + "node_modules/jest-changed-files": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-changed-files/-/jest-changed-files-29.7.0.tgz", + "integrity": "sha512-fEArFiwf1BpQ+4bXSprcDc3/x4HSzL4al2tozwVpDFpsxALjLYdyiIK4e5Vz66GQJIbXJ82+35PtysofptNX2w==", + "devOptional": true, + "license": "MIT", + "peer": true, + "dependencies": { + "execa": "^5.0.0", + "jest-util": "^29.7.0", + "p-limit": "^3.1.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-circus": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-circus/-/jest-circus-29.7.0.tgz", + "integrity": "sha512-3E1nCMgipcTkCocFwM90XXQab9bS+GMsjdpmPrlelaxwD93Ad8iVEjX/vvHPdLPnFf+L40u+5+iutRdA1N9myw==", + "devOptional": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@jest/environment": "^29.7.0", + "@jest/expect": "^29.7.0", + "@jest/test-result": "^29.7.0", + "@jest/types": "^29.6.3", + "@types/node": "*", + "chalk": "^4.0.0", + "co": "^4.6.0", + "dedent": "^1.0.0", + "is-generator-fn": "^2.0.0", + "jest-each": "^29.7.0", + "jest-matcher-utils": "^29.7.0", + "jest-message-util": "^29.7.0", + "jest-runtime": "^29.7.0", + "jest-snapshot": "^29.7.0", + "jest-util": "^29.7.0", + "p-limit": "^3.1.0", + "pretty-format": "^29.7.0", + "pure-rand": "^6.0.0", + "slash": "^3.0.0", + "stack-utils": "^2.0.3" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-circus/node_modules/pure-rand": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/pure-rand/-/pure-rand-6.1.0.tgz", + "integrity": "sha512-bVWawvoZoBYpp6yIoQtQXHZjmz35RSVHnUOTefl8Vcjr8snTPY1wnpSPMWekcFwbxI6gtmT7rSYPFvz71ldiOA==", + "devOptional": true, + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/dubzzz" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fast-check" + } + ], + "license": "MIT", + "peer": true + }, + "node_modules/jest-circus/node_modules/slash": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", + "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", + "devOptional": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/jest-cli": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-cli/-/jest-cli-29.7.0.tgz", + "integrity": "sha512-OVVobw2IubN/GSYsxETi+gOe7Ka59EFMR/twOU3Jb2GnKKeMGJB5SGUUrEz3SFVmJASUdZUzy83sLNNQ2gZslg==", + "devOptional": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@jest/core": "^29.7.0", + "@jest/test-result": "^29.7.0", + "@jest/types": "^29.6.3", + "chalk": "^4.0.0", + "create-jest": "^29.7.0", + "exit": "^0.1.2", + "import-local": "^3.0.2", + "jest-config": "^29.7.0", + "jest-util": "^29.7.0", + "jest-validate": "^29.7.0", + "yargs": "^17.3.1" + }, + "bin": { + "jest": "bin/jest.js" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "peerDependencies": { + "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" + }, + "peerDependenciesMeta": { + "node-notifier": { + "optional": true + } + } + }, + "node_modules/jest-config": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-config/-/jest-config-29.7.0.tgz", + "integrity": "sha512-uXbpfeQ7R6TZBqI3/TxCU4q4ttk3u0PJeC+E0zbfSoSjq6bJ7buBPxzQPL0ifrkY4DNu4JUdk0ImlBUYi840eQ==", + "devOptional": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@babel/core": "^7.11.6", + "@jest/test-sequencer": "^29.7.0", + "@jest/types": "^29.6.3", + "babel-jest": "^29.7.0", + "chalk": "^4.0.0", + "ci-info": "^3.2.0", + "deepmerge": "^4.2.2", + "glob": "^7.1.3", + "graceful-fs": "^4.2.9", + "jest-circus": "^29.7.0", + "jest-environment-node": "^29.7.0", + "jest-get-type": "^29.6.3", + "jest-regex-util": "^29.6.3", + "jest-resolve": "^29.7.0", + "jest-runner": "^29.7.0", + "jest-util": "^29.7.0", + "jest-validate": "^29.7.0", + "micromatch": "^4.0.4", + "parse-json": "^5.2.0", + "pretty-format": "^29.7.0", + "slash": "^3.0.0", + "strip-json-comments": "^3.1.1" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "peerDependencies": { + "@types/node": "*", + "ts-node": ">=9.0.0" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "ts-node": { + "optional": true + } + } + }, + "node_modules/jest-config/node_modules/brace-expansion": { + "version": "1.1.21", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.21.tgz", + "integrity": "sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw==", + "devOptional": true, + "license": "MIT", + "peer": true, + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/jest-config/node_modules/glob": { + "version": "7.2.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", + "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", + "deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me", + "devOptional": true, + "license": "ISC", + "peer": true, + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.1.1", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/jest-config/node_modules/minimatch": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", + "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", + "devOptional": true, + "license": "ISC", + "peer": true, + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/jest-config/node_modules/slash": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", + "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", + "devOptional": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/jest-config/node_modules/strip-json-comments": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", + "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", + "devOptional": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/jest-diff": { "version": "29.7.0", "resolved": "https://registry.npmjs.org/jest-diff/-/jest-diff-29.7.0.tgz", "integrity": "sha512-LMIgiIrhigmPrs03JHpxUh2yISK3vLFPkAodPeo0+BuF7wA2FoQbkEg1u8gBYBThncu7e1oEDUfIXVuTqLRUjw==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "chalk": "^4.0.0", @@ -23518,6 +24063,38 @@ "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, + "node_modules/jest-docblock": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-docblock/-/jest-docblock-29.7.0.tgz", + "integrity": "sha512-q617Auw3A612guyaFgsbFeYpNP5t2aoUNLwBUbc/0kD1R4t9ixDbyFTHd1nok4epoVFpr7PmeWHrhvuV3XaJ4g==", + "devOptional": true, + "license": "MIT", + "peer": true, + "dependencies": { + "detect-newline": "^3.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-each": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-each/-/jest-each-29.7.0.tgz", + "integrity": "sha512-gns+Er14+ZrEoC5fhOfYCY1LOHHr0TI+rQUHZS8Ttw2l7gl+80eHc/gFf2Ktkw0+SIACDTeWvpFcv3B04VembQ==", + "devOptional": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@jest/types": "^29.6.3", + "chalk": "^4.0.0", + "jest-get-type": "^29.6.3", + "jest-util": "^29.7.0", + "pretty-format": "^29.7.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, "node_modules/jest-environment-jsdom": { "version": "29.7.0", "resolved": "https://registry.npmjs.org/jest-environment-jsdom/-/jest-environment-jsdom-29.7.0.tgz", @@ -23546,6 +24123,358 @@ } } }, + "node_modules/jest-environment-node": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-environment-node/-/jest-environment-node-29.7.0.tgz", + "integrity": "sha512-DOSwCRqXirTOyheM+4d5YZOrWcdu0LNZ87ewUoywbcb2XR4wKgqiG8vNeYwhjFMbEkfju7wx2GYH0P2gevGvFw==", + "devOptional": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@jest/environment": "^29.7.0", + "@jest/fake-timers": "^29.7.0", + "@jest/types": "^29.6.3", + "@types/node": "*", + "jest-mock": "^29.7.0", + "jest-util": "^29.7.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-expo": { + "version": "54.0.18", + "resolved": "https://registry.npmjs.org/jest-expo/-/jest-expo-54.0.18.tgz", + "integrity": "sha512-couPPatkifK3v0WZW7zu1HZW5HyxY+1cY69LKHPawwbZTuIvf5wk4SYHtoUrGa/nAM2jW/YiXDLWfociEHJPvw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@expo/config": "~12.0.14", + "@expo/json-file": "^10.0.16", + "@jest/create-cache-key-function": "^29.2.1", + "@jest/globals": "^29.2.1", + "babel-jest": "^29.2.1", + "jest-environment-jsdom": "^29.2.1", + "jest-snapshot": "^29.2.1", + "jest-watch-select-projects": "^2.0.0", + "jest-watch-typeahead": "2.2.1", + "json5": "^2.2.3", + "lodash": "^4.17.19", + "react-test-renderer": "19.1.0", + "server-only": "^0.0.1", + "stacktrace-js": "^2.0.2" + }, + "bin": { + "jest": "bin/jest.js" + }, + "peerDependencies": { + "expo": "*", + "react-native": "*", + "react-server-dom-webpack": "~19.0.4 || ~19.1.5 || ~19.2.4" + }, + "peerDependenciesMeta": { + "react-server-dom-webpack": { + "optional": true + } + } + }, + "node_modules/jest-expo/node_modules/@expo/config": { + "version": "12.0.14", + "resolved": "https://registry.npmjs.org/@expo/config/-/config-12.0.14.tgz", + "integrity": "sha512-3dfbBd9LnPDgyylhCgkOsaG8Adg52uOVOTQYH5lf23a/t8M5eQpXKCvzUarrf62B78057n2NnkiofK9TfPgvzw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "~7.10.4", + "@expo/config-plugins": "~54.0.5", + "@expo/config-types": "^54.0.10", + "@expo/json-file": "^10.0.16", + "deepmerge": "^4.3.1", + "getenv": "^2.0.0", + "glob": "^13.0.0", + "require-from-string": "^2.0.2", + "resolve-from": "^5.0.0", + "resolve-workspace-root": "^2.0.0", + "semver": "^7.6.0", + "slugify": "^1.3.4", + "sucrase": "~3.35.1" + } + }, + "node_modules/jest-expo/node_modules/@expo/config-plugins": { + "version": "54.0.6", + "resolved": "https://registry.npmjs.org/@expo/config-plugins/-/config-plugins-54.0.6.tgz", + "integrity": "sha512-RKKhe3HSCTEmU2PBl4lu0BtV68TOz7qjPRXQBkBOUeYe83vIno1N63viDOiHIf7wxZ1ALxvsyEu3QWlCICnfWw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@expo/config-types": "^54.0.10", + "@expo/json-file": "~10.0.16", + "@expo/plist": "^0.4.9", + "@expo/sdk-runtime-versions": "^1.0.0", + "chalk": "^4.1.2", + "debug": "^4.3.5", + "getenv": "^2.0.0", + "glob": "^13.0.0", + "resolve-from": "^5.0.0", + "semver": "^7.5.4", + "slash": "^3.0.0", + "slugify": "^1.6.6", + "xcode": "^4.0.0", + "xml2js": "0.6.0" + } + }, + "node_modules/jest-expo/node_modules/@expo/config-plugins/node_modules/@babel/code-frame": { + "version": "7.10.4", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.10.4.tgz", + "integrity": "sha512-vG6SvB6oYEhvgisZNFRmRCUkLz11c7rp+tbNTynGqc6mS1d5ATd/sGyV6W0KZZnXRKMTzZDRgQT3Ou9jhpAfUg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/highlight": "^7.10.4" + } + }, + "node_modules/jest-expo/node_modules/@expo/config-plugins/node_modules/@expo/json-file": { + "version": "10.0.16", + "resolved": "https://registry.npmjs.org/@expo/json-file/-/json-file-10.0.16.tgz", + "integrity": "sha512-fcVkWEj+hLuP2yt5W0aw6LmDRqSPWDLUSxOMcmFeV+algmIF59sQVKCwB9btjQLd4V6x9N0pISkQEkBubUHrCw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "~7.10.4", + "json5": "^2.2.3" + } + }, + "node_modules/jest-expo/node_modules/@expo/config-types": { + "version": "54.0.10", + "resolved": "https://registry.npmjs.org/@expo/config-types/-/config-types-54.0.10.tgz", + "integrity": "sha512-/J16SC2an1LdtCZ67xhSkGXpALYUVUNyZws7v+PVsFZxClYehDSoKLqyRaGkpHlYrCc08bS0RF5E0JV6g50psA==", + "dev": true, + "license": "MIT" + }, + "node_modules/jest-expo/node_modules/@expo/config/node_modules/@babel/code-frame": { + "version": "7.10.4", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.10.4.tgz", + "integrity": "sha512-vG6SvB6oYEhvgisZNFRmRCUkLz11c7rp+tbNTynGqc6mS1d5ATd/sGyV6W0KZZnXRKMTzZDRgQT3Ou9jhpAfUg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/highlight": "^7.10.4" + } + }, + "node_modules/jest-expo/node_modules/@expo/json-file": { + "version": "10.2.0", + "resolved": "https://registry.npmjs.org/@expo/json-file/-/json-file-10.2.0.tgz", + "integrity": "sha512-S6XzKe3R9GQeHiUPXc3xJjOv2VJhOEwFYf7xdC2z2cUqt3kZJ9mSO877sNQloVdnW/SUCtPY3bexlM7nwq+CAQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.20.0", + "json5": "^2.2.3" + } + }, + "node_modules/jest-expo/node_modules/@expo/plist": { + "version": "0.4.9", + "resolved": "https://registry.npmjs.org/@expo/plist/-/plist-0.4.9.tgz", + "integrity": "sha512-MPVpmKGfnQEnrCzgxuXcmPP/y/t6AVm+DcSb2Myp21LKWv1N3l8uFxMggesfF4ixAxkRlGmMMx9GyDC9M+XklQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@xmldom/xmldom": "^0.8.8", + "base64-js": "^1.2.3", + "xmlbuilder": "^15.1.1" + } + }, + "node_modules/jest-expo/node_modules/@xmldom/xmldom": { + "version": "0.8.15", + "resolved": "https://registry.npmjs.org/@xmldom/xmldom/-/xmldom-0.8.15.tgz", + "integrity": "sha512-/5NV/vDALVFDXgLmfsy9TRCBlKwO2LNBFzpzvb9iIj+jR+eSc6DLYYvVOdivT/jm7MtU6TebYuRmzEOI7w40UA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/jest-expo/node_modules/balanced-match": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", + "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/jest-expo/node_modules/brace-expansion": { + "version": "5.0.12", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz", + "integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^4.0.2" + }, + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/jest-expo/node_modules/commander": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/commander/-/commander-4.1.1.tgz", + "integrity": "sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 6" + } + }, + "node_modules/jest-expo/node_modules/getenv": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/getenv/-/getenv-2.0.0.tgz", + "integrity": "sha512-VilgtJj/ALgGY77fiLam5iD336eSWi96Q15JSAG1zi8NRBysm3LXKdGnHb4m5cuyxvOLQQKWpBZAT6ni4FI2iQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/jest-expo/node_modules/glob": { + "version": "13.0.6", + "resolved": "https://registry.npmjs.org/glob/-/glob-13.0.6.tgz", + "integrity": "sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "minimatch": "^10.2.2", + "minipass": "^7.1.3", + "path-scurry": "^2.0.2" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/jest-expo/node_modules/lru-cache": { + "version": "11.5.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz", + "integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/jest-expo/node_modules/minimatch": { + "version": "10.2.6", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz", + "integrity": "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "brace-expansion": "^5.0.8" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/jest-expo/node_modules/path-scurry": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-2.0.2.tgz", + "integrity": "sha512-3O/iVVsJAPsOnpwWIeD+d6z/7PmqApyQePUtCndjatj/9I5LylHvt5qluFaBT3I5h3r1ejfR056c+FCv+NnNXg==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "lru-cache": "^11.0.0", + "minipass": "^7.1.2" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/jest-expo/node_modules/react-test-renderer": { + "version": "19.1.0", + "resolved": "https://registry.npmjs.org/react-test-renderer/-/react-test-renderer-19.1.0.tgz", + "integrity": "sha512-jXkSl3CpvPYEF+p/eGDLB4sPoDX8pKkYvRl9+rR8HxLY0X04vW7hCm1/0zHoUSjPZ3bDa+wXWNTDVIw/R8aDVw==", + "dev": true, + "license": "MIT", + "dependencies": { + "react-is": "^19.1.0", + "scheduler": "^0.26.0" + }, + "peerDependencies": { + "react": "^19.1.0" + } + }, + "node_modules/jest-expo/node_modules/scheduler": { + "version": "0.26.0", + "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.26.0.tgz", + "integrity": "sha512-NlHwttCI/l5gCPR3D1nNXtWABUmBwvZpEQiD4IXSbIDq8BzLIK/7Ir5gTFSGZDUu37K5cMNp0hFtzO38sC7gWA==", + "dev": true, + "license": "MIT" + }, + "node_modules/jest-expo/node_modules/slash": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", + "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/jest-expo/node_modules/sucrase": { + "version": "3.35.1", + "resolved": "https://registry.npmjs.org/sucrase/-/sucrase-3.35.1.tgz", + "integrity": "sha512-DhuTmvZWux4H1UOnWMB3sk0sbaCVOoQZjv8u1rDoTV0HTdGem9hkAZtl4JZy8P2z4Bg0nT+YMeOFyVr4zcG5Tw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.2", + "commander": "^4.0.0", + "lines-and-columns": "^1.1.6", + "mz": "^2.7.0", + "pirates": "^4.0.1", + "tinyglobby": "^0.2.11", + "ts-interface-checker": "^0.1.9" + }, + "bin": { + "sucrase": "bin/sucrase", + "sucrase-node": "bin/sucrase-node" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/jest-expo/node_modules/xcode": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/xcode/-/xcode-4.0.0.tgz", + "integrity": "sha512-dDaoWzc9EP2fp9FS9PVZUkyvFxY4y1TOV9pcKaKLk++Ei/qb97XDFEVP7GnW7Osii/TzVABJ0jq2F+9/lq0TVA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "simple-plist": "^1.3.1" + }, + "engines": { + "node": ">=14.17.0" + } + }, + "node_modules/jest-expo/node_modules/xmlbuilder": { + "version": "15.1.1", + "resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-15.1.1.tgz", + "integrity": "sha512-yMqGBqtXyeN1e3TGYvgNgDVZ3j84W4cwkOXQswghol6APgZWaff9lnbvN7MHYJOiXsvGPXtjTYJEiC9J2wv9Eg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8.0" + } + }, "node_modules/jest-get-type": { "version": "29.6.3", "resolved": "https://registry.npmjs.org/jest-get-type/-/jest-get-type-29.6.3.tgz", @@ -23559,7 +24488,7 @@ "version": "29.7.0", "resolved": "https://registry.npmjs.org/jest-haste-map/-/jest-haste-map-29.7.0.tgz", "integrity": "sha512-fP8u2pyfqx0K1rGn1R9pyE0/KTn+G7PxktWidOBTqFPLYX0b9ksaMFkhK5vrS3DVun09pckLdlx90QthlW7AmA==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@jest/types": "^29.6.3", @@ -23581,11 +24510,26 @@ "fsevents": "^2.3.2" } }, + "node_modules/jest-leak-detector": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-leak-detector/-/jest-leak-detector-29.7.0.tgz", + "integrity": "sha512-kYA8IJcSYtST2BY9I+SMC32nDpBT3J2NvWJx8+JCuCdl/CR1I4EKUJROiP8XtCcxqgTTBGJNdbB1A8XRKbTetw==", + "devOptional": true, + "license": "MIT", + "peer": true, + "dependencies": { + "jest-get-type": "^29.6.3", + "pretty-format": "^29.7.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, "node_modules/jest-matcher-utils": { "version": "29.7.0", "resolved": "https://registry.npmjs.org/jest-matcher-utils/-/jest-matcher-utils-29.7.0.tgz", "integrity": "sha512-sBkD+Xi9DtcChsI3L3u0+N0opgPYnCRPtGcQYrgXmR+hmt/fYfWAL0xRXYU8eWOdfuLgBe0YCW3AFtnRLagq/g==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "chalk": "^4.0.0", @@ -23601,7 +24545,7 @@ "version": "29.7.0", "resolved": "https://registry.npmjs.org/jest-message-util/-/jest-message-util-29.7.0.tgz", "integrity": "sha512-GBEV4GRADeP+qtB2+6u61stea8mGcOT4mCtrYISZwfu9/ISHFJ/5zOMXYbpBE9RsS5+Gb63DW4FgmnKJ79Kf6w==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@babel/code-frame": "^7.12.13", @@ -23622,7 +24566,7 @@ "version": "3.0.0", "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", - "dev": true, + "devOptional": true, "license": "MIT", "engines": { "node": ">=8" @@ -23632,7 +24576,7 @@ "version": "29.7.0", "resolved": "https://registry.npmjs.org/jest-mock/-/jest-mock-29.7.0.tgz", "integrity": "sha512-ITOMZn+UkYS4ZFh83xYAOzWStloNzJFO2s8DWrE4lhtGD+AorgnbkiKERe4wQVBydIGPx059g6riW5Btp6Llnw==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@jest/types": "^29.6.3", @@ -23643,21 +24587,251 @@ "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, + "node_modules/jest-pnp-resolver": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/jest-pnp-resolver/-/jest-pnp-resolver-1.2.3.tgz", + "integrity": "sha512-+3NpwQEnRoIBtx4fyhblQDPgJI0H1IEIkX7ShLUjPGA7TtUTvI1oiKi3SR4oBR0hQhQR80l4WAe5RrXBwWMA8w==", + "devOptional": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=6" + }, + "peerDependencies": { + "jest-resolve": "*" + }, + "peerDependenciesMeta": { + "jest-resolve": { + "optional": true + } + } + }, "node_modules/jest-regex-util": { "version": "29.6.3", "resolved": "https://registry.npmjs.org/jest-regex-util/-/jest-regex-util-29.6.3.tgz", "integrity": "sha512-KJJBsRCyyLNWCNBOvZyRDnAIfUiRJ8v+hOBQYGn8gDyF3UegwiP4gwRR3/SDa42g1YbVycTidUF3rKjyLFDWbg==", - "dev": true, + "devOptional": true, "license": "MIT", "engines": { "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, + "node_modules/jest-resolve": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-resolve/-/jest-resolve-29.7.0.tgz", + "integrity": "sha512-IOVhZSrg+UvVAshDSDtHyFCCBUl/Q3AAJv8iZ6ZjnZ74xzvwuzLXid9IIIPgTnY62SJjfuupMKZsZQRsCvxEgA==", + "devOptional": true, + "license": "MIT", + "peer": true, + "dependencies": { + "chalk": "^4.0.0", + "graceful-fs": "^4.2.9", + "jest-haste-map": "^29.7.0", + "jest-pnp-resolver": "^1.2.2", + "jest-util": "^29.7.0", + "jest-validate": "^29.7.0", + "resolve": "^1.20.0", + "resolve.exports": "^2.0.0", + "slash": "^3.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-resolve-dependencies": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-resolve-dependencies/-/jest-resolve-dependencies-29.7.0.tgz", + "integrity": "sha512-un0zD/6qxJ+S0et7WxeI3H5XSe9lTBBR7bOHCHXkKR6luG5mwDDlIzVQ0V5cZCuoTgEdcdwzTghYkTWfubi+nA==", + "devOptional": true, + "license": "MIT", + "peer": true, + "dependencies": { + "jest-regex-util": "^29.6.3", + "jest-snapshot": "^29.7.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-resolve/node_modules/slash": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", + "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", + "devOptional": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/jest-runner": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-runner/-/jest-runner-29.7.0.tgz", + "integrity": "sha512-fsc4N6cPCAahybGBfTRcq5wFR6fpLznMg47sY5aDpsoejOcVYFb07AHuSnR0liMcPTgBsA3ZJL6kFOjPdoNipQ==", + "devOptional": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@jest/console": "^29.7.0", + "@jest/environment": "^29.7.0", + "@jest/test-result": "^29.7.0", + "@jest/transform": "^29.7.0", + "@jest/types": "^29.6.3", + "@types/node": "*", + "chalk": "^4.0.0", + "emittery": "^0.13.1", + "graceful-fs": "^4.2.9", + "jest-docblock": "^29.7.0", + "jest-environment-node": "^29.7.0", + "jest-haste-map": "^29.7.0", + "jest-leak-detector": "^29.7.0", + "jest-message-util": "^29.7.0", + "jest-resolve": "^29.7.0", + "jest-runtime": "^29.7.0", + "jest-util": "^29.7.0", + "jest-watcher": "^29.7.0", + "jest-worker": "^29.7.0", + "p-limit": "^3.1.0", + "source-map-support": "0.5.13" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-runner/node_modules/source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "devOptional": true, + "license": "BSD-3-Clause", + "peer": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/jest-runner/node_modules/source-map-support": { + "version": "0.5.13", + "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.13.tgz", + "integrity": "sha512-SHSKFHadjVA5oR4PPqhtAVdcBWwRYVd6g6cAXnIbRiIwc2EhPrTuKUBdSLvlEKyIP3GCf89fltvcZiP9MMFA1w==", + "devOptional": true, + "license": "MIT", + "peer": true, + "dependencies": { + "buffer-from": "^1.0.0", + "source-map": "^0.6.0" + } + }, + "node_modules/jest-runtime": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-runtime/-/jest-runtime-29.7.0.tgz", + "integrity": "sha512-gUnLjgwdGqW7B4LvOIkbKs9WGbn+QLqRQQ9juC6HndeDiezIwhDP+mhMwHWCEcfQ5RUXa6OPnFF8BJh5xegwwQ==", + "devOptional": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@jest/environment": "^29.7.0", + "@jest/fake-timers": "^29.7.0", + "@jest/globals": "^29.7.0", + "@jest/source-map": "^29.6.3", + "@jest/test-result": "^29.7.0", + "@jest/transform": "^29.7.0", + "@jest/types": "^29.6.3", + "@types/node": "*", + "chalk": "^4.0.0", + "cjs-module-lexer": "^1.0.0", + "collect-v8-coverage": "^1.0.0", + "glob": "^7.1.3", + "graceful-fs": "^4.2.9", + "jest-haste-map": "^29.7.0", + "jest-message-util": "^29.7.0", + "jest-mock": "^29.7.0", + "jest-regex-util": "^29.6.3", + "jest-resolve": "^29.7.0", + "jest-snapshot": "^29.7.0", + "jest-util": "^29.7.0", + "slash": "^3.0.0", + "strip-bom": "^4.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-runtime/node_modules/brace-expansion": { + "version": "1.1.21", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.21.tgz", + "integrity": "sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw==", + "devOptional": true, + "license": "MIT", + "peer": true, + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/jest-runtime/node_modules/glob": { + "version": "7.2.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", + "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", + "deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me", + "devOptional": true, + "license": "ISC", + "peer": true, + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.1.1", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/jest-runtime/node_modules/minimatch": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", + "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", + "devOptional": true, + "license": "ISC", + "peer": true, + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/jest-runtime/node_modules/slash": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", + "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", + "devOptional": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/jest-runtime/node_modules/strip-bom": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-4.0.0.tgz", + "integrity": "sha512-3xurFv5tEgii33Zi8Jtp55wEIILR9eh34FAW00PZf+JnSsTmV/ioewSgQl97JHvgjoRGwPShsWm+IdrxB35d0w==", + "devOptional": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=8" + } + }, "node_modules/jest-snapshot": { "version": "29.7.0", "resolved": "https://registry.npmjs.org/jest-snapshot/-/jest-snapshot-29.7.0.tgz", "integrity": "sha512-Rm0BMWtxBcioHr1/OX5YCP8Uov4riHvKPknOGs804Zg9JGZgmIBkbtlxJC/7Z4msKYVbIJtfU+tKb8xlYNfdkw==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@babel/core": "^7.11.6", @@ -23868,7 +25042,7 @@ "version": "29.7.0", "resolved": "https://registry.npmjs.org/jest-watcher/-/jest-watcher-29.7.0.tgz", "integrity": "sha512-49Fg7WXkU3Vl2h6LbLtMQ/HyB6rXSIX7SqvBLQmssRBGN9I0PNvPmAmCWSOY6SOvrjhI/F7/bGAv9RtnsPA03g==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@jest/test-result": "^29.7.0", @@ -23888,7 +25062,7 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/char-regex/-/char-regex-1.0.2.tgz", "integrity": "sha512-kWWXztvZ5SBQV+eRgKFeh8q5sLuZY2+8WUIzlxWVTg+oGwY14qylx1KbKzHd8P6ZYkAg0xyIDU9JMHhyJMZ1jw==", - "dev": true, + "devOptional": true, "license": "MIT", "engines": { "node": ">=10" @@ -23898,7 +25072,7 @@ "version": "4.0.2", "resolved": "https://registry.npmjs.org/string-length/-/string-length-4.0.2.tgz", "integrity": "sha512-+l6rNN5fYHNhZZy41RXsYptCjA2Igmq4EG7kZAYFQI1E1VTXarr6ZPXBg6eq7Y6eK4FEhY6AJlyuFIb/v/S0VQ==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "char-regex": "^1.0.2", @@ -24172,7 +25346,7 @@ "version": "2.3.1", "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz", "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==", - "dev": true, + "devOptional": true, "license": "MIT" }, "node_modules/json-schema": { @@ -24967,7 +26141,7 @@ "version": "1.2.4", "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz", "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==", - "dev": true, + "devOptional": true, "license": "MIT" }, "node_modules/linkify-it": { @@ -25182,49 +26356,6 @@ "dev": true, "license": "ISC" }, - "node_modules/make-fetch-happen": { - "version": "14.0.3", - "resolved": "https://registry.npmjs.org/make-fetch-happen/-/make-fetch-happen-14.0.3.tgz", - "integrity": "sha512-QMjGbFTP0blj97EeidG5hk/QhKQ3T4ICckQGLgz38QF7Vgbk6e6FTARN8KhKxyBbWn8R0HU+bnw8aSoFPD4qtQ==", - "dev": true, - "license": "ISC", - "dependencies": { - "@npmcli/agent": "^3.0.0", - "cacache": "^19.0.1", - "http-cache-semantics": "^4.1.1", - "minipass": "^7.0.2", - "minipass-fetch": "^4.0.0", - "minipass-flush": "^1.0.5", - "minipass-pipeline": "^1.2.4", - "negotiator": "^1.0.0", - "proc-log": "^5.0.0", - "promise-retry": "^2.0.1", - "ssri": "^12.0.0" - }, - "engines": { - "node": "^18.17.0 || >=20.5.0" - } - }, - "node_modules/make-fetch-happen/node_modules/negotiator": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz", - "integrity": "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/make-fetch-happen/node_modules/proc-log": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/proc-log/-/proc-log-5.0.0.tgz", - "integrity": "sha512-Azwzvl90HaF0aCz1JrDdXQykFakSSNPaPoiZ9fm5qJIMHioDZEi7OAdRwSm6rSoPtY3Qutnm3L7ogmg3dc+wbQ==", - "dev": true, - "license": "ISC", - "engines": { - "node": "^18.17.0 || >=20.5.0" - } - }, "node_modules/makeerror": { "version": "1.0.12", "resolved": "https://registry.npmjs.org/makeerror/-/makeerror-1.0.12.tgz", @@ -27300,7 +28431,7 @@ "version": "2.1.0", "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==", - "dev": true, + "devOptional": true, "license": "MIT", "engines": { "node": ">=6" @@ -27332,7 +28463,7 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/min-indent/-/min-indent-1.0.1.tgz", "integrity": "sha512-I9jwMn07Sy/IwOj3zVkVik2JTvgpaykDZEigL6Rx6N9LbMywwUSMtxET+7lVoDLLd3O3IXwJwvuuns8UB/HeAg==", - "dev": true, + "devOptional": true, "license": "MIT", "engines": { "node": ">=4" @@ -27425,115 +28556,6 @@ "node": ">=16 || 14 >=14.17" } }, - "node_modules/minipass-collect": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/minipass-collect/-/minipass-collect-2.0.1.tgz", - "integrity": "sha512-D7V8PO9oaz7PWGLbCACuI1qEOsq7UKfLotx/C0Aet43fCUB/wfQ7DYeq2oR/svFJGYDHPr38SHATeaj/ZoKHKw==", - "dev": true, - "license": "ISC", - "dependencies": { - "minipass": "^7.0.3" - }, - "engines": { - "node": ">=16 || 14 >=14.17" - } - }, - "node_modules/minipass-fetch": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/minipass-fetch/-/minipass-fetch-4.0.1.tgz", - "integrity": "sha512-j7U11C5HXigVuutxebFadoYBbd7VSdZWggSe64NVdvWNBqGAiXPL2QVCehjmw7lY1oF9gOllYbORh+hiNgfPgQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "minipass": "^7.0.3", - "minipass-sized": "^1.0.3", - "minizlib": "^3.0.1" - }, - "engines": { - "node": "^18.17.0 || >=20.5.0" - }, - "optionalDependencies": { - "encoding": "^0.1.13" - } - }, - "node_modules/minipass-flush": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/minipass-flush/-/minipass-flush-1.0.5.tgz", - "integrity": "sha512-JmQSYYpPUqX5Jyn1mXaRwOda1uQ8HP5KAT/oDSLCzt1BYRhQU0/hDtsB1ufZfEEzMZ9aAVmsBw8+FWsIXlClWw==", - "dev": true, - "license": "ISC", - "dependencies": { - "minipass": "^3.0.0" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/minipass-flush/node_modules/minipass": { - "version": "3.3.6", - "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz", - "integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==", - "dev": true, - "license": "ISC", - "dependencies": { - "yallist": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/minipass-pipeline": { - "version": "1.2.4", - "resolved": "https://registry.npmjs.org/minipass-pipeline/-/minipass-pipeline-1.2.4.tgz", - "integrity": "sha512-xuIq7cIOt09RPRJ19gdi4b+RiNvDFYe5JH+ggNvBqGqpQXcru3PcRmOZuHBKWK1Txf9+cQ+HMVN4d6z46LZP7A==", - "dev": true, - "license": "ISC", - "dependencies": { - "minipass": "^3.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/minipass-pipeline/node_modules/minipass": { - "version": "3.3.6", - "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz", - "integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==", - "dev": true, - "license": "ISC", - "dependencies": { - "yallist": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/minipass-sized": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/minipass-sized/-/minipass-sized-1.0.3.tgz", - "integrity": "sha512-MbkQQ2CTiBMlA2Dm/5cY+9SWFEN8pzzOXi6rlM5Xxq0Yqbda5ZQy9sU75a673FE9ZK0Zsbr6Y5iP6u9nktfg2g==", - "dev": true, - "license": "ISC", - "dependencies": { - "minipass": "^3.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/minipass-sized/node_modules/minipass": { - "version": "3.3.6", - "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz", - "integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==", - "dev": true, - "license": "ISC", - "dependencies": { - "yallist": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, "node_modules/minizlib": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-3.0.1.tgz", @@ -27823,7 +28845,7 @@ "version": "1.4.0", "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==", - "dev": true, + "devOptional": true, "license": "MIT" }, "node_modules/natural-orderby": { @@ -27944,31 +28966,6 @@ "node": ">= 6.13.0" } }, - "node_modules/node-gyp": { - "version": "11.5.0", - "resolved": "https://registry.npmjs.org/node-gyp/-/node-gyp-11.5.0.tgz", - "integrity": "sha512-ra7Kvlhxn5V9Slyus0ygMa2h+UqExPqUIkfk7Pc8QTLT956JLSy51uWFwHtIYy0vI8cB4BDhc/S03+880My/LQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "env-paths": "^2.2.0", - "exponential-backoff": "^3.1.1", - "graceful-fs": "^4.2.6", - "make-fetch-happen": "^14.0.3", - "nopt": "^8.0.0", - "proc-log": "^5.0.0", - "semver": "^7.3.5", - "tar": "^7.4.3", - "tinyglobby": "^0.2.12", - "which": "^5.0.0" - }, - "bin": { - "node-gyp": "bin/node-gyp.js" - }, - "engines": { - "node": "^18.17.0 || >=20.5.0" - } - }, "node_modules/node-gyp-build": { "version": "4.8.4", "resolved": "https://registry.npmjs.org/node-gyp-build/-/node-gyp-build-4.8.4.tgz", @@ -27996,92 +28993,6 @@ "node-gyp-build-optional-packages-test": "build-test.js" } }, - "node_modules/node-gyp/node_modules/chownr": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/chownr/-/chownr-3.0.0.tgz", - "integrity": "sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g==", - "dev": true, - "license": "BlueOak-1.0.0", - "engines": { - "node": ">=18" - } - }, - "node_modules/node-gyp/node_modules/isexe": { - "version": "3.1.5", - "resolved": "https://registry.npmjs.org/isexe/-/isexe-3.1.5.tgz", - "integrity": "sha512-6B3tLtFqtQS4ekarvLVMZ+X+VlvQekbe4taUkf/rhVO3d/h0M2rfARm/pXLcPEsjjMsFgrFgSrhQIxcSVrBz8w==", - "dev": true, - "license": "BlueOak-1.0.0", - "engines": { - "node": ">=18" - } - }, - "node_modules/node-gyp/node_modules/minizlib": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-3.1.0.tgz", - "integrity": "sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw==", - "dev": true, - "license": "MIT", - "dependencies": { - "minipass": "^7.1.2" - }, - "engines": { - "node": ">= 18" - } - }, - "node_modules/node-gyp/node_modules/proc-log": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/proc-log/-/proc-log-5.0.0.tgz", - "integrity": "sha512-Azwzvl90HaF0aCz1JrDdXQykFakSSNPaPoiZ9fm5qJIMHioDZEi7OAdRwSm6rSoPtY3Qutnm3L7ogmg3dc+wbQ==", - "dev": true, - "license": "ISC", - "engines": { - "node": "^18.17.0 || >=20.5.0" - } - }, - "node_modules/node-gyp/node_modules/tar": { - "version": "7.5.12", - "resolved": "https://registry.npmjs.org/tar/-/tar-7.5.12.tgz", - "integrity": "sha512-9TsuLcdhOn4XztcQqhNyq1KOwOOED/3k58JAvtULiYqbO8B/0IBAAIE1hj0Svmm58k27TmcigyDI0deMlgG3uw==", - "dev": true, - "license": "BlueOak-1.0.0", - "dependencies": { - "@isaacs/fs-minipass": "^4.0.0", - "chownr": "^3.0.0", - "minipass": "^7.1.2", - "minizlib": "^3.1.0", - "yallist": "^5.0.0" - }, - "engines": { - "node": ">=18" - } - }, - "node_modules/node-gyp/node_modules/which": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/which/-/which-5.0.0.tgz", - "integrity": "sha512-JEdGzHwwkrbWoGOlIHqQ5gtprKGOenpDHpxE9zVR1bWbOtYRyPPHMe9FaP6x61CmNaTThSkb0DAJte5jD+DmzQ==", - "dev": true, - "license": "ISC", - "dependencies": { - "isexe": "^3.1.1" - }, - "bin": { - "node-which": "bin/which.js" - }, - "engines": { - "node": "^18.17.0 || >=20.5.0" - } - }, - "node_modules/node-gyp/node_modules/yallist": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-5.0.0.tgz", - "integrity": "sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw==", - "dev": true, - "license": "BlueOak-1.0.0", - "engines": { - "node": ">=18" - } - }, "node_modules/node-int64": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/node-int64/-/node-int64-0.4.0.tgz", @@ -28154,7 +29065,7 @@ "version": "3.0.0", "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", - "dev": true, + "devOptional": true, "license": "MIT", "engines": { "node": ">=0.10.0" @@ -28173,31 +29084,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/noxcturnal": { - "version": "0.1.5", - "resolved": "https://registry.npmjs.org/noxcturnal/-/noxcturnal-0.1.5.tgz", - "integrity": "sha512-X/HQXJP/xn7LVQ4z1E4La0NHSl5UHdtJPG6ky4r2/Xgb7k79nGDJgBXk7I5f1V2vInWjlSCM14oSB0cUxwZS/Q==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@babel/code-frame": "^7.20.0", - "@oxc-project/types": "0.154.0" - }, - "engines": { - "node": ">=18" - }, - "optionalDependencies": { - "@noxcturnal/noxcturnal-darwin-arm64": "0.1.5", - "@noxcturnal/noxcturnal-darwin-x64": "0.1.5", - "@noxcturnal/noxcturnal-linux-arm64-gnu": "0.1.5", - "@noxcturnal/noxcturnal-linux-arm64-musl": "0.1.5", - "@noxcturnal/noxcturnal-linux-x64-gnu": "0.1.5", - "@noxcturnal/noxcturnal-linux-x64-musl": "0.1.5", - "@noxcturnal/noxcturnal-win32-arm64-msvc": "0.1.5", - "@noxcturnal/noxcturnal-win32-x64-msvc": "0.1.5" - } - }, "node_modules/npm-package-arg": { "version": "11.0.3", "resolved": "https://registry.npmjs.org/npm-package-arg/-/npm-package-arg-11.0.3.tgz", @@ -28231,6 +29117,20 @@ "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==", "license": "ISC" }, + "node_modules/npm-run-path": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-4.0.1.tgz", + "integrity": "sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==", + "devOptional": true, + "license": "MIT", + "peer": true, + "dependencies": { + "path-key": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/nth-check": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/nth-check/-/nth-check-2.1.1.tgz", @@ -28453,7 +29353,7 @@ "version": "5.1.2", "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz", "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "mimic-fn": "^2.1.0" @@ -28728,7 +29628,7 @@ "version": "3.1.0", "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "yocto-queue": "^0.1.0" @@ -28756,19 +29656,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/p-map": { - "version": "7.0.4", - "resolved": "https://registry.npmjs.org/p-map/-/p-map-7.0.4.tgz", - "integrity": "sha512-tkAQEw8ysMzmkhgw8k+1U/iPhWNhykKnSk4Rd5zLoPJCuJaGRPo6YposrZgaxHKzDHdDWWZvE/Sk7hsL2X/CpQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/p-memoize": { "version": "8.0.0", "resolved": "https://registry.npmjs.org/p-memoize/-/p-memoize-8.0.0.tgz", @@ -28880,7 +29767,7 @@ "version": "5.2.0", "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz", "integrity": "sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@babel/code-frame": "^7.0.0", @@ -29015,7 +29902,7 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==", - "dev": true, + "devOptional": true, "license": "MIT", "engines": { "node": ">=0.10.0" @@ -29190,7 +30077,7 @@ "version": "4.0.7", "resolved": "https://registry.npmjs.org/pirates/-/pirates-4.0.7.tgz", "integrity": "sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA==", - "dev": true, + "devOptional": true, "license": "MIT", "engines": { "node": ">= 6" @@ -29209,7 +30096,7 @@ "version": "4.2.0", "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-4.2.0.tgz", "integrity": "sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "find-up": "^4.0.0" @@ -29222,7 +30109,7 @@ "version": "4.1.0", "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "locate-path": "^5.0.0", @@ -29236,7 +30123,7 @@ "version": "5.0.0", "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "p-locate": "^4.1.0" @@ -29249,7 +30136,7 @@ "version": "2.3.0", "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "p-try": "^2.0.0" @@ -29265,7 +30152,7 @@ "version": "4.1.0", "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "p-limit": "^2.2.0" @@ -29274,6 +30161,40 @@ "node": ">=8" } }, + "node_modules/pkijs": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/pkijs/-/pkijs-3.4.3.tgz", + "integrity": "sha512-V9kOzaItwDgqlryhXysQsAXUEKi5O7kqWUaP3dXI7MLvkPqWWMb4wVb1QAtmEDCKI+XIAINsZoNKMFF7sZb1eg==", + "dev": true, + "license": "BSD-3-Clause", + "workspaces": [ + "website" + ], + "dependencies": { + "@noble/hashes": "1.8.0", + "asn1js": "^3.0.6", + "bytestreamjs": "^2.0.1", + "pvtsutils": "^1.3.6", + "pvutils": "^1.1.3", + "tslib": "^2.8.1" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/pkijs/node_modules/@noble/hashes": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz", + "integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, "node_modules/playwright": { "version": "1.58.2", "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.58.2.tgz", @@ -29423,6 +30344,36 @@ "integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==", "license": "MIT" }, + "node_modules/postject": { + "version": "1.0.0-alpha.6", + "resolved": "https://registry.npmjs.org/postject/-/postject-1.0.0-alpha.6.tgz", + "integrity": "sha512-b9Eb8h2eVqNE8edvKdwqkrY6O7kAwmI8kcnBv1NScolYJbo59XUF0noFq+lxbC1yN20bmC0WBEbDC5H/7ASb0A==", + "dev": true, + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "commander": "^9.4.0" + }, + "bin": { + "postject": "dist/cli.js" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/postject/node_modules/commander": { + "version": "9.5.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-9.5.0.tgz", + "integrity": "sha512-KRs7WVDKg86PWiuAqhDrAQnTXZKraVcCc6vFdL14qrZ/DcWwuRo7VoiYXalXO7S5GKpqYiVEwCbgFDfxNHKJBQ==", + "dev": true, + "license": "MIT", + "optional": true, + "peer": true, + "engines": { + "node": "^12.20.0 || >=14" + } + }, "node_modules/prelude-ls": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", @@ -29694,6 +30645,26 @@ ], "license": "MIT" }, + "node_modules/pvtsutils": { + "version": "1.3.6", + "resolved": "https://registry.npmjs.org/pvtsutils/-/pvtsutils-1.3.6.tgz", + "integrity": "sha512-PLgQXQ6H2FWCaeRak8vvk1GW462lMxB5s3Jm673N82zI4vqtVUPuZdffdZbPDFRoU8kAhItWFtPCWiPpp4/EDg==", + "dev": true, + "license": "MIT", + "dependencies": { + "tslib": "^2.8.1" + } + }, + "node_modules/pvutils": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/pvutils/-/pvutils-1.2.0.tgz", + "integrity": "sha512-BbubeCEyTuQjVMakvJQ/Sxbc93F2pwmbsxONT/ZRrwU7Ua38d8unYTwXpTVLAKJ4BDuH9IGztCjQcd/N/39Dvg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=16.0.0" + } + }, "node_modules/qrcode": { "version": "1.5.4", "resolved": "https://registry.npmjs.org/qrcode/-/qrcode-1.5.4.tgz", @@ -30085,25 +31056,9 @@ } }, "node_modules/react-is": { - "version": "19.2.4", - "resolved": "https://registry.npmjs.org/react-is/-/react-is-19.2.4.tgz", - "integrity": "sha512-W+EWGn2v0ApPKgKKCy/7s7WHXkboGcsrXE+2joLyVxkbyVQfO3MUEaUQDHoSmb8TFFrSKYa9mw64WZHNHSDzYA==", - "license": "MIT" - }, - "node_modules/react-is-18": { - "name": "react-is", - "version": "18.3.1", - "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.3.1.tgz", - "integrity": "sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg==", - "dev": true, - "license": "MIT" - }, - "node_modules/react-is-19": { - "name": "react-is", - "version": "19.2.7", - "resolved": "https://registry.npmjs.org/react-is/-/react-is-19.2.7.tgz", - "integrity": "sha512-kZFnouyVv7eP/Phmrlo9FK+zcAdriZJvzxXHF1Sl1P377WSGe2G/JxVolhTrB/jeV47lKImhNUsijjHAAbcl/A==", - "dev": true, + "version": "19.3.1", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-19.3.1.tgz", + "integrity": "sha512-RRieF6IyxQBkcK6pP8xOHprLTPW6QjRkbGdImtqNme+/hYVwCZkLQLdlZGOhUqXwkS9IEynaGvPJtv6XB/cz0Q==", "license": "MIT" }, "node_modules/react-markdown": { @@ -30651,6 +31606,21 @@ } } }, + "node_modules/react-test-renderer": { + "version": "19.3.1", + "resolved": "https://registry.npmjs.org/react-test-renderer/-/react-test-renderer-19.3.1.tgz", + "integrity": "sha512-YcNewwmnZMd0wTb2nkb4hQ58NmX/u1hW2OJsNpen8CnV+jNkmEjYd1R6wJrOMSgb8bIF5HAJv4iL+S3PwNptOA==", + "devOptional": true, + "license": "MIT", + "peer": true, + "dependencies": { + "react-is": "^19.3.1", + "scheduler": "^0.28.0" + }, + "peerDependencies": { + "react": "^19.3.1" + } + }, "node_modules/read-binary-file-arch": { "version": "1.0.6", "resolved": "https://registry.npmjs.org/read-binary-file-arch/-/read-binary-file-arch-1.0.6.tgz", @@ -31181,6 +32151,20 @@ "dev": true, "license": "MIT" }, + "node_modules/resolve-cwd": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/resolve-cwd/-/resolve-cwd-3.0.0.tgz", + "integrity": "sha512-OrZaX2Mb+rJCpH/6CpSqt9xFVpN++x01XnN2ie9g6P5/3xelLAkXWVADpdz1IHD/KFfEXyE6V0U01OQ3UO2rEg==", + "devOptional": true, + "license": "MIT", + "peer": true, + "dependencies": { + "resolve-from": "^5.0.0" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/resolve-from": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz", @@ -31206,6 +32190,17 @@ "integrity": "sha512-nR23LHAvaI6aHtMg6RWoaHpdR4D881Nydkzi2CixINyg9T00KgaJdJI6Vwty+Ps8WLxZHuxsS0BseWjxSA4C+w==", "license": "MIT" }, + "node_modules/resolve.exports": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/resolve.exports/-/resolve.exports-2.0.4.tgz", + "integrity": "sha512-zepuGL0ulf+nt+XaFrlKeaiTJeyPFPLLY62+ncq1/VTHBdt3HsfXOH60priZ6tnXQozdGcDeIF5JVTanvIcYWQ==", + "devOptional": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=10" + } + }, "node_modules/responselike": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/responselike/-/responselike-2.0.1.tgz", @@ -31261,6 +32256,70 @@ "node": ">=0.10.0" } }, + "node_modules/rimraf": { + "version": "2.6.3", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.6.3.tgz", + "integrity": "sha512-mwqeW5XsA2qAejG46gYdENaxXjx9onRNCfn7L0duuP4hCuTIi/QO7PDK07KJfp1d+izWPrzEJDcSqBa0OZQriA==", + "deprecated": "Rimraf versions prior to v4 are no longer supported", + "dev": true, + "license": "ISC", + "peer": true, + "dependencies": { + "glob": "^7.1.3" + }, + "bin": { + "rimraf": "bin.js" + } + }, + "node_modules/rimraf/node_modules/brace-expansion": { + "version": "1.1.21", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.21.tgz", + "integrity": "sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/rimraf/node_modules/glob": { + "version": "7.2.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", + "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", + "deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me", + "dev": true, + "license": "ISC", + "peer": true, + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.1.1", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/rimraf/node_modules/minimatch": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", + "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", + "dev": true, + "license": "ISC", + "peer": true, + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, "node_modules/roarr": { "version": "2.15.4", "resolved": "https://registry.npmjs.org/roarr/-/roarr-2.15.4.tgz", @@ -31583,11 +32642,12 @@ } }, "node_modules/scheduler": { - "version": "0.26.0", - "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.26.0.tgz", - "integrity": "sha512-NlHwttCI/l5gCPR3D1nNXtWABUmBwvZpEQiD4IXSbIDq8BzLIK/7Ir5gTFSGZDUu37K5cMNp0hFtzO38sC7gWA==", - "dev": true, - "license": "MIT" + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.28.0.tgz", + "integrity": "sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==", + "devOptional": true, + "license": "MIT", + "peer": true }, "node_modules/secure-json-parse": { "version": "4.1.0", @@ -32224,17 +33284,6 @@ "node": ">=8.0.0" } }, - "node_modules/smart-buffer": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/smart-buffer/-/smart-buffer-4.2.0.tgz", - "integrity": "sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 6.0.0", - "npm": ">= 3.0.0" - } - }, "node_modules/smol-toml": { "version": "1.6.0", "resolved": "https://registry.npmjs.org/smol-toml/-/smol-toml-1.6.0.tgz", @@ -32248,46 +33297,6 @@ "url": "https://github.com/sponsors/cyyynthia" } }, - "node_modules/socks": { - "version": "2.8.7", - "resolved": "https://registry.npmjs.org/socks/-/socks-2.8.7.tgz", - "integrity": "sha512-HLpt+uLy/pxB+bum/9DzAgiKS8CX1EvbWxI4zlmgGCExImLdiad2iCwXT5Z4c9c3Eq8rP2318mPW2c+QbtjK8A==", - "dev": true, - "license": "MIT", - "dependencies": { - "ip-address": "^10.0.1", - "smart-buffer": "^4.2.0" - }, - "engines": { - "node": ">= 10.0.0", - "npm": ">= 3.0.0" - } - }, - "node_modules/socks-proxy-agent": { - "version": "8.0.5", - "resolved": "https://registry.npmjs.org/socks-proxy-agent/-/socks-proxy-agent-8.0.5.tgz", - "integrity": "sha512-HehCEsotFqbPW9sJ8WVYB6UbmIMv7kUUORIF2Nncq4VQvBfNBLibW9YZR5dlYCSUhwcD628pRllm7n+E+YTzJw==", - "dev": true, - "license": "MIT", - "dependencies": { - "agent-base": "^7.1.2", - "debug": "^4.3.4", - "socks": "^2.8.3" - }, - "engines": { - "node": ">= 14" - } - }, - "node_modules/socks-proxy-agent/node_modules/agent-base": { - "version": "7.1.4", - "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", - "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 14" - } - }, "node_modules/sonic-boom": { "version": "4.2.1", "resolved": "https://registry.npmjs.org/sonic-boom/-/sonic-boom-4.2.1.tgz", @@ -32416,19 +33425,6 @@ "node": ">=20.16.0" } }, - "node_modules/ssri": { - "version": "12.0.0", - "resolved": "https://registry.npmjs.org/ssri/-/ssri-12.0.0.tgz", - "integrity": "sha512-S7iGNosepx9RadX82oimUkvr0Ct7IjJbEbs4mJcTxst8um95J3sDYU1RBEOvdu6oL1Wek2ODI5i4MAw+dZ6cAQ==", - "dev": true, - "license": "ISC", - "dependencies": { - "minipass": "^7.0.3" - }, - "engines": { - "node": "^18.17.0 || >=20.5.0" - } - }, "node_modules/stable-hash": { "version": "0.0.5", "resolved": "https://registry.npmjs.org/stable-hash/-/stable-hash-0.0.5.tgz", @@ -32450,7 +33446,7 @@ "version": "2.0.6", "resolved": "https://registry.npmjs.org/stack-utils/-/stack-utils-2.0.6.tgz", "integrity": "sha512-XlkWvfIm6RmsWtNJx+uqtKLS8eqFbxUg0ZzLXqY0caEy9l7hruX8IpiDnjsLavoBgqCCR71TqWO8MaXYheJ3RQ==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "escape-string-regexp": "^2.0.0" @@ -32463,7 +33459,7 @@ "version": "2.0.0", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-2.0.0.tgz", "integrity": "sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w==", - "dev": true, + "devOptional": true, "license": "MIT", "engines": { "node": ">=8" @@ -32863,6 +33859,17 @@ "node": ">=4" } }, + "node_modules/strip-final-newline": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-2.0.0.tgz", + "integrity": "sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA==", + "devOptional": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=6" + } + }, "node_modules/strip-indent": { "version": "4.1.1", "resolved": "https://registry.npmjs.org/strip-indent/-/strip-indent-4.1.1.tgz", @@ -33047,13 +34054,14 @@ "license": "MIT" }, "node_modules/synckit": { - "version": "0.11.12", - "resolved": "https://registry.npmjs.org/synckit/-/synckit-0.11.12.tgz", - "integrity": "sha512-Bh7QjT8/SuKUIfObSXNHNSK6WHo6J1tHCqJsuaFDP7gP0fkzSfTxI8y85JrppZ0h8l0maIgc2tfuZQ6/t3GtnQ==", + "version": "0.12.3", + "resolved": "https://registry.npmjs.org/synckit/-/synckit-0.12.3.tgz", + "integrity": "sha512-U+/AXT6LWsxnj2vz9HeUuPWBNgdWxjyIEjEPdbJARC9txmgPzo2VEdqnFo4hHaNyMPtycyVJrSaQYeQv/PoyyA==", "dev": true, "license": "MIT", "dependencies": { - "@pkgr/core": "^0.2.9" + "@dual-bundle/import-meta-resolve": "^4.2.1", + "@pkgr/core": "^0.3.6" }, "engines": { "node": "^14.18.0 || >=16.0.0" @@ -33163,6 +34171,21 @@ "node": ">=8" } }, + "node_modules/temp": { + "version": "0.9.4", + "resolved": "https://registry.npmjs.org/temp/-/temp-0.9.4.tgz", + "integrity": "sha512-yYrrsWnrXMcdsnu/7YMYAofM1ktpL5By7vZhf15CrXijWWrEYZks5AXBudalfSWJLlnen/QUJUB5aoB0kqZUGA==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "mkdirp": "^0.5.1", + "rimraf": "~2.6.2" + }, + "engines": { + "node": ">=6.0.0" + } + }, "node_modules/temp-dir": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/temp-dir/-/temp-dir-2.0.0.tgz", @@ -33184,6 +34207,20 @@ "fs-extra": "^10.0.0" } }, + "node_modules/temp/node_modules/mkdirp": { + "version": "0.5.6", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.6.tgz", + "integrity": "sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "minimist": "^1.2.6" + }, + "bin": { + "mkdirp": "bin/cmd.js" + } + }, "node_modules/terminal-link": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/terminal-link/-/terminal-link-2.1.1.tgz", @@ -33228,7 +34265,7 @@ "version": "6.0.0", "resolved": "https://registry.npmjs.org/test-exclude/-/test-exclude-6.0.0.tgz", "integrity": "sha512-cAGWPIyOHU6zlmg88jwm7VRyXnMN7iV68OGAbYDk/Mh/xC/pzVPlQtY6ngoIH/5/tciuhGfvESU8GrHrcxD56w==", - "dev": true, + "devOptional": true, "license": "ISC", "dependencies": { "@istanbuljs/schema": "^0.1.2", @@ -33243,7 +34280,7 @@ "version": "1.1.12", "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz", "integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "balanced-match": "^1.0.0", @@ -33255,7 +34292,7 @@ "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", "deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me", - "dev": true, + "devOptional": true, "license": "ISC", "dependencies": { "fs.realpath": "^1.0.0", @@ -33276,7 +34313,7 @@ "version": "3.1.5", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", - "dev": true, + "devOptional": true, "license": "ISC", "dependencies": { "brace-expansion": "^1.1.7" @@ -33579,6 +34616,19 @@ "integrity": "sha512-FPAhNPFMrkwz76P7cdjdmiShwMynZYN6SgOujD1urY4oNm80Ou9oMdmbR45LotcKOXoy7wSmHkRFE6Mxbrhefw==", "license": "MIT" }, + "node_modules/ts-api-utils": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.5.0.tgz", + "integrity": "sha512-OJ/ibxhPlqrMM0UiNHJ/0CKQkoKF243/AEmplt3qpRgkW8VG7IfOS41h7V8TjITqdByHzrjcS/2si+y4lIh8NA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18.12" + }, + "peerDependencies": { + "typescript": ">=4.8.4" + } + }, "node_modules/ts-declaration-location": { "version": "1.0.7", "resolved": "https://registry.npmjs.org/ts-declaration-location/-/ts-declaration-location-1.0.7.tgz", @@ -33868,7 +34918,7 @@ "version": "4.0.8", "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz", "integrity": "sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==", - "dev": true, + "devOptional": true, "license": "MIT", "engines": { "node": ">=4" @@ -34153,32 +35203,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/unique-filename": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/unique-filename/-/unique-filename-4.0.0.tgz", - "integrity": "sha512-XSnEewXmQ+veP7xX2dS5Q4yZAvO40cBN2MWkJ7D/6sW4Dg6wYBNwM1Vrnz1FhH5AdeLIlUXRI9e28z1YZi71NQ==", - "dev": true, - "license": "ISC", - "dependencies": { - "unique-slug": "^5.0.0" - }, - "engines": { - "node": "^18.17.0 || >=20.5.0" - } - }, - "node_modules/unique-slug": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/unique-slug/-/unique-slug-5.0.0.tgz", - "integrity": "sha512-9OdaqO5kwqR+1kVgHAhsp5vPNU0hnxRa26rBFNfNgM7M6pNtgzeBn3s/xbyCQL3dcjzOatcef6UUHpB/6MaETg==", - "dev": true, - "license": "ISC", - "dependencies": { - "imurmurhash": "^0.1.4" - }, - "engines": { - "node": "^18.17.0 || >=20.5.0" - } - }, "node_modules/unique-string": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/unique-string/-/unique-string-2.0.0.tgz", @@ -34362,6 +35386,35 @@ "mkdirp": "bin/cmd.js" } }, + "node_modules/unzipper": { + "version": "0.12.5", + "resolved": "https://registry.npmjs.org/unzipper/-/unzipper-0.12.5.tgz", + "integrity": "sha512-tXYOi9R57Uj/2Z25SOs5RRSzq886MBQj2gY8dPL+xl/kv6s6SvByoKfAtvfVeEuhntWDgjd2o9p2lb4TVPAz0A==", + "dev": true, + "license": "MIT", + "dependencies": { + "bluebird": "~3.7.2", + "duplexer2": "~0.1.4", + "fs-extra": "11.3.1", + "graceful-fs": "^4.2.2", + "node-int64": "^0.4.0" + } + }, + "node_modules/unzipper/node_modules/fs-extra": { + "version": "11.3.1", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.3.1.tgz", + "integrity": "sha512-eXvGGwZ5CL17ZSwHWd3bbgk7UUpF6IFHtP57NYYakPvHOs8GDgDe5KJI36jIJzDkJ6eJjuzRA8eBQb6SkKue0g==", + "dev": true, + "license": "MIT", + "dependencies": { + "graceful-fs": "^4.2.0", + "jsonfile": "^6.0.1", + "universalify": "^2.0.0" + }, + "engines": { + "node": ">=14.14" + } + }, "node_modules/update-browserslist-db": { "version": "1.2.3", "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz", @@ -34517,6 +35570,22 @@ "dev": true, "license": "MIT" }, + "node_modules/v8-to-istanbul": { + "version": "9.3.0", + "resolved": "https://registry.npmjs.org/v8-to-istanbul/-/v8-to-istanbul-9.3.0.tgz", + "integrity": "sha512-kiGUalWN+rgBJ/1OHZsBtU4rXZOfj/7rKQxULKlIzwzQSvMJUUNgPwJEEh7gU6xEVxC0ahoOBvN2YI8GH6FNgA==", + "devOptional": true, + "license": "ISC", + "peer": true, + "dependencies": { + "@jridgewell/trace-mapping": "^0.3.12", + "@types/istanbul-lib-coverage": "^2.0.1", + "convert-source-map": "^2.0.0" + }, + "engines": { + "node": ">=10.12.0" + } + }, "node_modules/validate-npm-package-license": { "version": "3.0.4", "resolved": "https://registry.npmjs.org/validate-npm-package-license/-/validate-npm-package-license-3.0.4.tgz", @@ -34559,22 +35628,6 @@ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0.0 || ^19.0.0-rc" } }, - "node_modules/verror": { - "version": "1.10.1", - "resolved": "https://registry.npmjs.org/verror/-/verror-1.10.1.tgz", - "integrity": "sha512-veufcmxri4e3XSrT0xwfUR7kguIkaxBeosDg00yDWhk49wdwkSUrvvsm7nc75e1PUyvIeZj6nS8VQRYz2/S4Xg==", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "assert-plus": "^1.0.0", - "core-util-is": "1.0.2", - "extsprintf": "^1.2.0" - }, - "engines": { - "node": ">=0.6.0" - } - }, "node_modules/vfile": { "version": "6.0.3", "resolved": "https://registry.npmjs.org/vfile/-/vfile-6.0.3.tgz", @@ -34982,6 +36035,20 @@ "url": "https://github.com/sponsors/wooorm" } }, + "node_modules/webcrypto-core": { + "version": "1.9.2", + "resolved": "https://registry.npmjs.org/webcrypto-core/-/webcrypto-core-1.9.2.tgz", + "integrity": "sha512-gsXecm82UQNlTBURJGuqOWy1Ww08S3kZUcr3aOJS02Pk0xLtkfeUAVC0u0xhgdonFme80edSJUIJyuvL/7250Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@peculiar/asn1-schema": "^2.7.0", + "@peculiar/json-schema": "^1.1.12", + "@peculiar/utils": "^2.0.2", + "asn1js": "^3.0.10", + "tslib": "^2.8.1" + } + }, "node_modules/webidl-conversions": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", @@ -35517,7 +36584,7 @@ "version": "0.1.0", "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", - "dev": true, + "devOptional": true, "license": "MIT", "engines": { "node": ">=10" @@ -35695,7 +36762,7 @@ }, "packages/app": { "name": "@getpaseo/app", - "version": "0.13.2", + "version": "0.15.0-beta.1", "dependencies": { "@codemirror/commands": "6.10.4", "@codemirror/language": "6.12.4", @@ -35725,13 +36792,14 @@ "@tanstack/react-virtual": "^3.13.21", "@xterm/addon-clipboard": "^0.3.0-beta.213", "@xterm/addon-fit": "^0.12.0-beta.213", - "@xterm/addon-image": "^0.10.0-beta.213", + "@xterm/addon-image": "0.10.0-beta.331", "@xterm/addon-ligatures": "^0.11.0-beta.213", "@xterm/addon-search": "^0.17.0-beta.213", + "@xterm/addon-unicode-graphemes": "0.5.0-beta.330", "@xterm/addon-unicode11": "^0.10.0-beta.213", "@xterm/addon-web-links": "^0.13.0-beta.213", - "@xterm/addon-webgl": "^0.20.0-beta.212", - "@xterm/xterm": "^6.1.0-beta.213", + "@xterm/addon-webgl": "0.20.0-beta.329", + "@xterm/xterm": "6.1.0-beta.336", "buffer": "^6.0.3", "expo": "~57.0.30", "expo-asset": "~57.0.20", @@ -35808,7 +36876,8 @@ "@types/ws": "^8.18.1", "@vitest/browser": "^4.1.7", "@vitest/browser-playwright": "^4.1.7", - "@xterm/headless": "^6.1.0-beta.213", + "@xterm/addon-serialize": "0.14.0", + "@xterm/headless": "6.1.0-beta.334", "babel-preset-expo": "~57.0.16", "dotenv": "^17.2.3", "eas-cli": "^16.24.1", @@ -36587,15 +37656,6 @@ "@xterm/xterm": "^6.1.0-beta.213" } }, - "packages/app/node_modules/@xterm/addon-image": { - "version": "0.10.0-beta.213", - "resolved": "https://registry.npmjs.org/@xterm/addon-image/-/addon-image-0.10.0-beta.213.tgz", - "integrity": "sha512-L3QxLkj8g8TioVea9p1oVze52Jr75rRZPPLm1tgZl0X2EGJGFHnQzE3QRsgmYWI7R5j3kwwi3MRAkOAgvOK8uA==", - "license": "MIT", - "peerDependencies": { - "@xterm/xterm": "^6.1.0-beta.213" - } - }, "packages/app/node_modules/@xterm/addon-ligatures": { "version": "0.11.0-beta.213", "resolved": "https://registry.npmjs.org/@xterm/addon-ligatures/-/addon-ligatures-0.11.0-beta.213.tgz", @@ -36639,34 +37699,6 @@ "@xterm/xterm": "^6.1.0-beta.213" } }, - "packages/app/node_modules/@xterm/addon-webgl": { - "version": "0.20.0-beta.212", - "resolved": "https://registry.npmjs.org/@xterm/addon-webgl/-/addon-webgl-0.20.0-beta.212.tgz", - "integrity": "sha512-RzaTYeukTXTJth+Sl7FzCmb8AqiyDrNWNnqG+/300qJbfHYfCMmBlBVZ0yCTSZIWMdgFbgkhmnmBN7Yzs6xoBA==", - "license": "MIT", - "peerDependencies": { - "@xterm/xterm": "^6.1.0-beta.213" - } - }, - "packages/app/node_modules/@xterm/headless": { - "version": "6.1.0-beta.213", - "resolved": "https://registry.npmjs.org/@xterm/headless/-/headless-6.1.0-beta.213.tgz", - "integrity": "sha512-D08E4Bl0HRhYZRL2o5PxD4FNQN9qXpI8QSw3CkKrsym5dtTRAqsynVYE8V8echQrxfb+EpR0CB5reM7tEGZ/fA==", - "dev": true, - "license": "MIT", - "workspaces": [ - "addons/*" - ] - }, - "packages/app/node_modules/@xterm/xterm": { - "version": "6.1.0-beta.213", - "resolved": "https://registry.npmjs.org/@xterm/xterm/-/xterm-6.1.0-beta.213.tgz", - "integrity": "sha512-bq5nJkgoZDSg6Ma4zgiQ7jlooGNo7U+HDa6vnhx43yXsVEK2laIF7R08bMYAuU0B+C9xX0gwSrcsW18GxjUoJQ==", - "license": "MIT", - "workspaces": [ - "addons/*" - ] - }, "packages/app/node_modules/babel-plugin-syntax-hermes-parser": { "version": "0.36.1", "resolved": "https://registry.npmjs.org/babel-plugin-syntax-hermes-parser/-/babel-plugin-syntax-hermes-parser-0.36.1.tgz", @@ -37103,43 +38135,6 @@ "typescript": ">=4.8.4 <6.1.0" } }, - "packages/app/node_modules/eslint-config-expo/node_modules/eslint-plugin-react-hooks": { - "version": "7.1.1", - "resolved": "https://registry.npmjs.org/eslint-plugin-react-hooks/-/eslint-plugin-react-hooks-7.1.1.tgz", - "integrity": "sha512-f2I7Gw6JbvCexzIInuSbZpfdQ44D7iqdWX01FKLvrPgqxoE7oMj8clOfto8U6vYiz4yd5oKu39rRSVOe1zRu0g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/core": "^7.24.4", - "@babel/parser": "^7.24.4", - "hermes-parser": "^0.25.1", - "zod": "^3.25.0 || ^4.0.0", - "zod-validation-error": "^3.5.0 || ^4.0.0" - }, - "engines": { - "node": ">=18" - }, - "peerDependencies": { - "eslint": "^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0-0 || ^9.0.0 || ^10.0.0" - } - }, - "packages/app/node_modules/eslint-config-expo/node_modules/hermes-estree": { - "version": "0.25.1", - "resolved": "https://registry.npmjs.org/hermes-estree/-/hermes-estree-0.25.1.tgz", - "integrity": "sha512-0wUoCcLp+5Ev5pDW2OriHC2MJCbwLwuRx+gAqMTOkGKJJiBCLjtrvy4PWUGn6MIVefecRpzoOZ/UV6iGdOr+Cw==", - "dev": true, - "license": "MIT" - }, - "packages/app/node_modules/eslint-config-expo/node_modules/hermes-parser": { - "version": "0.25.1", - "resolved": "https://registry.npmjs.org/hermes-parser/-/hermes-parser-0.25.1.tgz", - "integrity": "sha512-6pEjquH3rqaI6cYAXYPcz9MS4rY6R4ngRgrgfDshRptUZIc3lw0MCIJIGDj9++mfySOuPTHB4nrSW99BCvOPIA==", - "dev": true, - "license": "MIT", - "dependencies": { - "hermes-estree": "0.25.1" - } - }, "packages/app/node_modules/eslint-config-expo/node_modules/ignore": { "version": "7.0.12", "resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.12.tgz", @@ -37150,19 +38145,6 @@ "node": ">= 4" } }, - "packages/app/node_modules/eslint-config-expo/node_modules/ts-api-utils": { - "version": "2.5.0", - "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.5.0.tgz", - "integrity": "sha512-OJ/ibxhPlqrMM0UiNHJ/0CKQkoKF243/AEmplt3qpRgkW8VG7IfOS41h7V8TjITqdByHzrjcS/2si+y4lIh8NA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18.12" - }, - "peerDependencies": { - "typescript": ">=4.8.4" - } - }, "packages/app/node_modules/eslint-plugin-expo": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/eslint-plugin-expo/-/eslint-plugin-expo-1.2.1.tgz", @@ -37272,19 +38254,6 @@ "typescript": ">=4.8.4 <6.1.0" } }, - "packages/app/node_modules/eslint-plugin-expo/node_modules/ts-api-utils": { - "version": "2.5.0", - "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.5.0.tgz", - "integrity": "sha512-OJ/ibxhPlqrMM0UiNHJ/0CKQkoKF243/AEmplt3qpRgkW8VG7IfOS41h7V8TjITqdByHzrjcS/2si+y4lIh8NA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18.12" - }, - "peerDependencies": { - "typescript": ">=4.8.4" - } - }, "packages/app/node_modules/eslint-visitor-keys": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-5.0.1.tgz", @@ -37961,12 +38930,12 @@ }, "packages/cli": { "name": "@getpaseo/cli", - "version": "0.13.2", + "version": "0.15.0-beta.1", "dependencies": { "@clack/prompts": "^1.0.0", - "@getpaseo/client": "0.13.2", - "@getpaseo/protocol": "0.13.2", - "@getpaseo/server": "0.13.2", + "@getpaseo/client": "0.15.0-beta.1", + "@getpaseo/protocol": "0.15.0-beta.1", + "@getpaseo/server": "0.15.0-beta.1", "chalk": "^5.3.0", "commander": "^12.0.0", "mime-types": "^2.1.35", @@ -38213,10 +39182,10 @@ }, "packages/client": { "name": "@getpaseo/client", - "version": "0.13.2", + "version": "0.15.0-beta.1", "dependencies": { - "@getpaseo/protocol": "0.13.2", - "@getpaseo/relay": "0.13.2", + "@getpaseo/protocol": "0.15.0-beta.1", + "@getpaseo/relay": "0.15.0-beta.1", "ws": "^8.20.0", "zod": "^4.4.3" }, @@ -38228,7 +39197,7 @@ }, "packages/desktop": { "name": "@getpaseo/desktop", - "version": "0.13.2", + "version": "0.15.0-beta.1", "license": "Apache-2.0", "dependencies": { "@getpaseo/cli": "*", @@ -38243,13 +39212,94 @@ "@types/node": "24.6.0", "@types/ws": "^8.5.14", "electron": "44.2.0", - "electron-builder": "26.8.1", + "electron-builder": "26.18.0", "typescript": "5.9.3", "unzip-crx-3": "^0.2.0", "vitest": "^4.1.6", "wait-on": "8.0.5" } }, + "packages/desktop/node_modules/@electron/get": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@electron/get/-/get-3.1.0.tgz", + "integrity": "sha512-F+nKc0xW+kVbBRhFzaMgPy3KwmuNTYX1fx6+FxxoSnNgwYX6LD7AKBTWkU0MQ6IBoe7dz069CNkR673sPAgkCQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "debug": "^4.1.1", + "env-paths": "^2.2.0", + "fs-extra": "^8.1.0", + "got": "^11.8.5", + "progress": "^2.0.3", + "semver": "^6.2.0", + "sumchecker": "^3.0.1" + }, + "engines": { + "node": ">=14" + }, + "optionalDependencies": { + "global-agent": "^3.0.0" + } + }, + "packages/desktop/node_modules/@electron/get/node_modules/fs-extra": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-8.1.0.tgz", + "integrity": "sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g==", + "dev": true, + "license": "MIT", + "dependencies": { + "graceful-fs": "^4.2.0", + "jsonfile": "^4.0.0", + "universalify": "^0.1.0" + }, + "engines": { + "node": ">=6 <7 || >=8" + } + }, + "packages/desktop/node_modules/@electron/get/node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "packages/desktop/node_modules/@electron/rebuild": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@electron/rebuild/-/rebuild-4.2.1.tgz", + "integrity": "sha512-IS4pG3BysRrCLJ8xTAfvg+IQDbiUoAzdJy2SfjcYKnLDy5DpCdjnPdhS5Zf5UMfrkB24xu0KC+TqcOxg+eG+6w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@malept/cross-spawn-promise": "^2.0.0", + "debug": "^4.1.1", + "node-abi": "^4.2.0", + "node-api-version": "^0.2.1", + "node-gyp": "^12.2.0", + "read-binary-file-arch": "^1.0.6" + }, + "bin": { + "electron-rebuild": "lib/cli.js" + }, + "engines": { + "node": ">=22.12.0" + } + }, + "packages/desktop/node_modules/@noble/hashes": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz", + "integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, "packages/desktop/node_modules/@types/node": { "version": "24.6.0", "resolved": "https://registry.npmjs.org/@types/node/-/node-24.6.0.tgz", @@ -38346,6 +39396,482 @@ "url": "https://opencollective.com/vitest" } }, + "packages/desktop/node_modules/abbrev": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-4.0.0.tgz", + "integrity": "sha512-a1wflyaL0tHtJSmLSOVybYhy22vRih4eduhhrkcjgrWGnRfrZtovJ2FRjxuTtkkj47O/baf0R86QU5OuYpz8fA==", + "dev": true, + "license": "ISC", + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "packages/desktop/node_modules/agent-base": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", + "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 14" + } + }, + "packages/desktop/node_modules/ajv": { + "version": "8.20.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz", + "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "packages/desktop/node_modules/app-builder-lib": { + "version": "26.18.0", + "resolved": "https://registry.npmjs.org/app-builder-lib/-/app-builder-lib-26.18.0.tgz", + "integrity": "sha512-lx+KkuCSZHcbECf4R3IAcC9VOFk0+cMUwljO63s5y8yqS1Lw0sRGmjPaWsPwP3zv3ohZYbMhUvjXeiQXXZhJXA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@electron/asar": "3.4.1", + "@electron/fuses": "^1.8.0", + "@electron/get": "^3.0.0", + "@electron/notarize": "2.5.0", + "@electron/osx-sign": "1.3.3", + "@electron/rebuild": "^4.2.1", + "@electron/universal": "2.0.3", + "@malept/flatpak-bundler": "^0.4.0", + "@noble/hashes": "^1.8.0", + "@peculiar/webcrypto": "^1.7.1", + "@types/fs-extra": "9.0.13", + "ajv": "^8.18.0", + "asn1js": "^3.0.10", + "async-exit-hook": "^2.0.1", + "builder-util": "26.16.0", + "builder-util-runtime": "9.7.0", + "chromium-pickle-js": "^0.2.0", + "ci-info": "4.3.1", + "debug": "^4.3.4", + "dotenv": "^16.4.5", + "dotenv-expand": "^11.0.6", + "ejs": "^3.1.8", + "electron-publish": "26.18.0", + "fs-extra": "^10.1.0", + "hosted-git-info": "^4.1.0", + "isbinaryfile": "^5.0.0", + "jiti": "^2.4.2", + "js-yaml": "^4.1.0", + "json5": "^2.2.3", + "lazy-val": "^1.0.5", + "minimatch": "^10.2.5", + "pkijs": "^3.4.0", + "plist": "3.1.0", + "proper-lockfile": "^4.1.2", + "resedit": "^1.7.0", + "semver": "~7.7.3", + "tar": "^7.5.7", + "temp-file": "^3.4.0", + "tiny-async-pool": "1.3.0", + "unzipper": "^0.12.3", + "which": "^5.0.0" + }, + "engines": { + "node": ">=14.0.0" + }, + "peerDependencies": { + "dmg-builder": "26.18.0", + "electron-builder-squirrel-windows": "26.18.0" + } + }, + "packages/desktop/node_modules/app-builder-lib/node_modules/ci-info": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-4.3.1.tgz", + "integrity": "sha512-Wdy2Igu8OcBpI2pZePZ5oWjPC38tmDVx5WKUXKwlLYkA0ozo85sLsLvkBbBn/sZaSCMFOGZJ14fvW9t5/d7kdA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/sibiraj-s" + } + ], + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "packages/desktop/node_modules/balanced-match": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", + "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "18 || 20 || >=22" + } + }, + "packages/desktop/node_modules/brace-expansion": { + "version": "5.0.12", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz", + "integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^4.0.2" + }, + "engines": { + "node": "20 || >=22" + } + }, + "packages/desktop/node_modules/builder-util": { + "version": "26.16.0", + "resolved": "https://registry.npmjs.org/builder-util/-/builder-util-26.16.0.tgz", + "integrity": "sha512-RLyJhB7Si3YkzKR9ubQslWuXW3Vhs3CGe1i+SeixBZ0qTd1mk3XBmssvY22TlB6CS5blyko8Gu1JzpYk8UkYAg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/debug": "^4.1.6", + "builder-util-runtime": "9.7.0", + "chalk": "^4.1.2", + "cross-spawn": "^7.0.6", + "debug": "^4.3.4", + "fs-extra": "^10.1.0", + "http-proxy-agent": "^7.0.0", + "https-proxy-agent": "^7.0.0", + "js-yaml": "^4.1.0", + "sanitize-filename": "^1.6.3", + "source-map-support": "^0.5.19", + "stat-mode": "^1.0.0", + "temp-file": "^3.4.0", + "tiny-async-pool": "1.3.0" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "packages/desktop/node_modules/builder-util-runtime": { + "version": "9.7.0", + "resolved": "https://registry.npmjs.org/builder-util-runtime/-/builder-util-runtime-9.7.0.tgz", + "integrity": "sha512-g/kR520giAFYkSXTzcmF3kqQq7wi8F6N6SzeDgZrqTBN+VHdmgWOyTdD1yD7AATDId/yXLvuP34CxW46/BwCdw==", + "dev": true, + "license": "MIT", + "dependencies": { + "debug": "^4.3.4", + "sax": "^1.2.4" + }, + "engines": { + "node": ">=12.0.0" + } + }, + "packages/desktop/node_modules/chownr": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/chownr/-/chownr-3.0.0.tgz", + "integrity": "sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=18" + } + }, + "packages/desktop/node_modules/ci-info": { + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-4.4.0.tgz", + "integrity": "sha512-77PSwercCZU2Fc4sX94eF8k8Pxte6JAwL4/ICZLFjJLqegs7kCuAsqqj/70NQF6TvDpgFjkubQB2FW2ZZddvQg==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/sibiraj-s" + } + ], + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "packages/desktop/node_modules/dmg-builder": { + "version": "26.18.0", + "resolved": "https://registry.npmjs.org/dmg-builder/-/dmg-builder-26.18.0.tgz", + "integrity": "sha512-ozCGC54wi2C1RkS2v69y9lQxvoQ1Coh+iT8CmWiyY8y1ZuOKVvuNson2Hd+HEOs9+EZNNsOBbzKgQZ4SNqWd0w==", + "dev": true, + "license": "MIT", + "dependencies": { + "app-builder-lib": "26.18.0", + "builder-util": "26.16.0", + "fs-extra": "^10.1.0", + "js-yaml": "^4.1.0" + } + }, + "packages/desktop/node_modules/dotenv": { + "version": "16.6.1", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.6.1.tgz", + "integrity": "sha512-uBq4egWHTcTt33a72vpSG0z3HnPuIl6NqYcTrKEg2azoEyl2hpW0zqlxysq2pK9HlDIHyHyakeYaYnSAwd8bow==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://dotenvx.com" + } + }, + "packages/desktop/node_modules/electron-builder": { + "version": "26.18.0", + "resolved": "https://registry.npmjs.org/electron-builder/-/electron-builder-26.18.0.tgz", + "integrity": "sha512-ASgIuQnOq4RuD8jMhS9hI0LS3EMRT1I/M5R6utqifB/BHN80IcCjBdt+DED+NmNPvmBgEtrlExXZitNdA7kXOg==", + "dev": true, + "license": "MIT", + "dependencies": { + "app-builder-lib": "26.18.0", + "builder-util": "26.16.0", + "builder-util-runtime": "9.7.0", + "chalk": "^4.1.2", + "ci-info": "^4.2.0", + "dmg-builder": "26.18.0", + "fs-extra": "^10.1.0", + "lazy-val": "^1.0.5", + "simple-update-notifier": "2.0.0", + "yargs": "^17.6.2" + }, + "bin": { + "electron-builder": "cli.js", + "install-app-deps": "install-app-deps.js" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "packages/desktop/node_modules/electron-builder-squirrel-windows": { + "version": "26.18.0", + "resolved": "https://registry.npmjs.org/electron-builder-squirrel-windows/-/electron-builder-squirrel-windows-26.18.0.tgz", + "integrity": "sha512-a2elgTipboXNIsxqS1HOmHMGp4Pd3LJgIZOdIFTOskBSawvxKyZWYWQ1d7KKA4CtINSchYCYEKzhxRqiKZev9Q==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "app-builder-lib": "26.18.0", + "builder-util": "26.16.0", + "electron-winstaller": "5.4.0" + } + }, + "packages/desktop/node_modules/electron-publish": { + "version": "26.18.0", + "resolved": "https://registry.npmjs.org/electron-publish/-/electron-publish-26.18.0.tgz", + "integrity": "sha512-MagnqaZSALSWjcdKu5HEVhYUZD/2BDL3q7XzrqWwub6gf/UfD3ItMgmthVDv9w5y9E0gH1C3JWqKaXwf6f4ROg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/fs-extra": "^9.0.11", + "aws4": "^1.13.2", + "builder-util": "26.16.0", + "builder-util-runtime": "9.7.0", + "chalk": "^4.1.2", + "form-data": "^4.0.5", + "fs-extra": "^10.1.0", + "lazy-val": "^1.0.5", + "mime": "^2.5.2" + } + }, + "packages/desktop/node_modules/http-proxy-agent": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz", + "integrity": "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==", + "dev": true, + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.0", + "debug": "^4.3.4" + }, + "engines": { + "node": ">= 14" + } + }, + "packages/desktop/node_modules/https-proxy-agent": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", + "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", + "dev": true, + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.2", + "debug": "4" + }, + "engines": { + "node": ">= 14" + } + }, + "packages/desktop/node_modules/isexe": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-3.1.5.tgz", + "integrity": "sha512-6B3tLtFqtQS4ekarvLVMZ+X+VlvQekbe4taUkf/rhVO3d/h0M2rfARm/pXLcPEsjjMsFgrFgSrhQIxcSVrBz8w==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=18" + } + }, + "packages/desktop/node_modules/jsonfile": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-4.0.0.tgz", + "integrity": "sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg==", + "dev": true, + "license": "MIT", + "optionalDependencies": { + "graceful-fs": "^4.1.6" + } + }, + "packages/desktop/node_modules/mime": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-2.6.0.tgz", + "integrity": "sha512-USPkMeET31rOMiarsBNIHZKLGgvKc/LrjofAnBlOttf5ajRvqiRA8QsenbcooctK6d6Ts6aqZXBA+XbkKthiQg==", + "dev": true, + "license": "MIT", + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=4.0.0" + } + }, + "packages/desktop/node_modules/minimatch": { + "version": "10.2.6", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz", + "integrity": "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "brace-expansion": "^5.0.8" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "packages/desktop/node_modules/minizlib": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-3.1.0.tgz", + "integrity": "sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw==", + "dev": true, + "license": "MIT", + "dependencies": { + "minipass": "^7.1.2" + }, + "engines": { + "node": ">= 18" + } + }, + "packages/desktop/node_modules/node-gyp": { + "version": "12.4.0", + "resolved": "https://registry.npmjs.org/node-gyp/-/node-gyp-12.4.0.tgz", + "integrity": "sha512-OMcPNvqTCFUnNaBlmdgq+lfNqY7gTiSmNRDjY3uAXRyudeKZEZxu3CLtjMQrx4zZxCX2b/mpNqTtwuCJgXhHkw==", + "dev": true, + "license": "MIT", + "dependencies": { + "env-paths": "^2.2.0", + "exponential-backoff": "^3.1.1", + "graceful-fs": "^4.2.6", + "nopt": "^9.0.0", + "proc-log": "^6.0.0", + "semver": "^7.3.5", + "tar": "^7.5.4", + "tinyglobby": "^0.2.12", + "undici": "^6.25.0", + "which": "^6.0.0" + }, + "bin": { + "node-gyp": "bin/node-gyp.js" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "packages/desktop/node_modules/node-gyp/node_modules/isexe": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-4.0.0.tgz", + "integrity": "sha512-FFUtZMpoZ8RqHS3XeXEmHWLA4thH+ZxCv2lOiPIn1Xc7CxrqhWzNSDzD+/chS/zbYezmiwWLdQC09JdQKmthOw==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=20" + } + }, + "packages/desktop/node_modules/node-gyp/node_modules/which": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/which/-/which-6.0.1.tgz", + "integrity": "sha512-oGLe46MIrCRqX7ytPUf66EAYvdeMIZYn3WaocqqKZAxrBpkqHfL/qvTyJ/bTk5+AqHCjXmrv3CEWgy368zhRUg==", + "dev": true, + "license": "ISC", + "dependencies": { + "isexe": "^4.0.0" + }, + "bin": { + "node-which": "bin/which.js" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "packages/desktop/node_modules/nopt": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/nopt/-/nopt-9.0.0.tgz", + "integrity": "sha512-Zhq3a+yFKrYwSBluL4H9XP3m3y5uvQkB/09CwDruCiRmR/UJYnn9W4R48ry0uGC70aeTPKLynBtscP9efFFcPw==", + "dev": true, + "license": "ISC", + "dependencies": { + "abbrev": "^4.0.0" + }, + "bin": { + "nopt": "bin/nopt.js" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "packages/desktop/node_modules/proc-log": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/proc-log/-/proc-log-6.1.0.tgz", + "integrity": "sha512-iG+GYldRf2BQ0UDUAd6JQ/RwzaQy6mXmsk/IzlYyal4A4SNFw54MeH4/tLkF4I5WoWG9SQwuqWzS99jaFQHBuQ==", + "dev": true, + "license": "ISC", + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "packages/desktop/node_modules/tar": { + "version": "7.5.22", + "resolved": "https://registry.npmjs.org/tar/-/tar-7.5.22.tgz", + "integrity": "sha512-MFO/QzvtAOmJbkhOaCTvbGcFN9L9b+JunIsDwaKljSOdcLMea3NJ1k9Usz/rjdfSXTq4dfzfeS7W4p4YOAAHeA==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "@isaacs/fs-minipass": "^4.0.0", + "chownr": "^3.0.0", + "minipass": "^7.1.2", + "minizlib": "^3.1.0", + "yallist": "^5.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "packages/desktop/node_modules/undici": { + "version": "6.29.1", + "resolved": "https://registry.npmjs.org/undici/-/undici-6.29.1.tgz", + "integrity": "sha512-EvRlUt/QqAEvXdQeRMYUfwOQsfzpDztykrG2owGEE/rBOBoYv9uF39ZzsNDh4lTFHhTr2XOZjKkYgueD12ZmGA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18.17" + } + }, "packages/desktop/node_modules/undici-types": { "version": "7.13.0", "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.13.0.tgz", @@ -38353,6 +39879,16 @@ "dev": true, "license": "MIT" }, + "packages/desktop/node_modules/universalify": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.2.tgz", + "integrity": "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 4.0.0" + } + }, "packages/desktop/node_modules/vitest": { "version": "4.1.6", "resolved": "https://registry.npmjs.org/vitest/-/vitest-4.1.6.tgz", @@ -38470,14 +40006,39 @@ } } }, + "packages/desktop/node_modules/which": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/which/-/which-5.0.0.tgz", + "integrity": "sha512-JEdGzHwwkrbWoGOlIHqQ5gtprKGOenpDHpxE9zVR1bWbOtYRyPPHMe9FaP6x61CmNaTThSkb0DAJte5jD+DmzQ==", + "dev": true, + "license": "ISC", + "dependencies": { + "isexe": "^3.1.1" + }, + "bin": { + "node-which": "bin/which.js" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "packages/desktop/node_modules/yallist": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-5.0.0.tgz", + "integrity": "sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=18" + } + }, "packages/expo-two-way-audio": { "name": "@getpaseo/expo-two-way-audio", - "version": "0.13.2", + "version": "0.15.0-beta.1", "license": "MIT", "devDependencies": { "@types/jest": "^29.5.14", "@types/react": "^18.0.25", - "expo-module-scripts": "^5.0.8", "expo-modules-core": "^2.0.4" }, "peerDependencies": { @@ -38486,1234 +40047,6 @@ "react-native": "*" } }, - "packages/expo-two-way-audio/node_modules/@expo/code-signing-certificates": { - "version": "0.0.7", - "resolved": "https://registry.npmjs.org/@expo/code-signing-certificates/-/code-signing-certificates-0.0.7.tgz", - "integrity": "sha512-zP0tnfqrFFRL8INtOaQ6XwEYfdIpIH9vrEo7y0bHQGQa50z4/QWXE5CI4nRUHxqFW4MVWOwXFg1hom1aAZHNkQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "node-forge": "^1.4.0" - }, - "engines": { - "node": ">=22.13.0" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/config": { - "version": "12.0.13", - "resolved": "https://registry.npmjs.org/@expo/config/-/config-12.0.13.tgz", - "integrity": "sha512-Cu52arBa4vSaupIWsF0h7F/Cg//N374nYb7HAxV0I4KceKA7x2UXpYaHOL7EEYYvp7tZdThBjvGpVmr8ScIvaQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/code-frame": "~7.10.4", - "@expo/config-plugins": "~54.0.4", - "@expo/config-types": "^54.0.10", - "@expo/json-file": "^10.0.8", - "deepmerge": "^4.3.1", - "getenv": "^2.0.0", - "glob": "^13.0.0", - "require-from-string": "^2.0.2", - "resolve-from": "^5.0.0", - "resolve-workspace-root": "^2.0.0", - "semver": "^7.6.0", - "slugify": "^1.3.4", - "sucrase": "~3.35.1" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/config-plugins": { - "version": "54.0.4", - "resolved": "https://registry.npmjs.org/@expo/config-plugins/-/config-plugins-54.0.4.tgz", - "integrity": "sha512-g2yXGICdoOw5i3LkQSDxl2Q5AlQCrG7oniu0pCPPO+UxGb7He4AFqSvPSy8HpRUj55io17hT62FTjYRD+d6j3Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "@expo/config-types": "^54.0.10", - "@expo/json-file": "~10.0.8", - "@expo/plist": "^0.4.8", - "@expo/sdk-runtime-versions": "^1.0.0", - "chalk": "^4.1.2", - "debug": "^4.3.5", - "getenv": "^2.0.0", - "glob": "^13.0.0", - "resolve-from": "^5.0.0", - "semver": "^7.5.4", - "slash": "^3.0.0", - "slugify": "^1.6.6", - "xcode": "^3.0.1", - "xml2js": "0.6.0" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/config-plugins/node_modules/@babel/code-frame": { - "version": "7.10.4", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.10.4.tgz", - "integrity": "sha512-vG6SvB6oYEhvgisZNFRmRCUkLz11c7rp+tbNTynGqc6mS1d5ATd/sGyV6W0KZZnXRKMTzZDRgQT3Ou9jhpAfUg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/highlight": "^7.10.4" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/config-plugins/node_modules/@expo/json-file": { - "version": "10.0.16", - "resolved": "https://registry.npmjs.org/@expo/json-file/-/json-file-10.0.16.tgz", - "integrity": "sha512-fcVkWEj+hLuP2yt5W0aw6LmDRqSPWDLUSxOMcmFeV+algmIF59sQVKCwB9btjQLd4V6x9N0pISkQEkBubUHrCw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/code-frame": "~7.10.4", - "json5": "^2.2.3" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/config-types": { - "version": "54.0.10", - "resolved": "https://registry.npmjs.org/@expo/config-types/-/config-types-54.0.10.tgz", - "integrity": "sha512-/J16SC2an1LdtCZ67xhSkGXpALYUVUNyZws7v+PVsFZxClYehDSoKLqyRaGkpHlYrCc08bS0RF5E0JV6g50psA==", - "dev": true, - "license": "MIT" - }, - "packages/expo-two-way-audio/node_modules/@expo/config/node_modules/@babel/code-frame": { - "version": "7.10.4", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.10.4.tgz", - "integrity": "sha512-vG6SvB6oYEhvgisZNFRmRCUkLz11c7rp+tbNTynGqc6mS1d5ATd/sGyV6W0KZZnXRKMTzZDRgQT3Ou9jhpAfUg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/highlight": "^7.10.4" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/devtools": { - "version": "58.0.2", - "resolved": "https://registry.npmjs.org/@expo/devtools/-/devtools-58.0.2.tgz", - "integrity": "sha512-WBj/K+vv8JPSmY70ennL04YYOHkpEsGGkfuVY9lfv4XO7Qhbt5qz4q6W7maME194I5oGcimRMigUFfWNkBe90w==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "chalk": "^4.1.2" - }, - "peerDependencies": { - "expo": "*", - "react": "*", - "react-native": "*" - }, - "peerDependenciesMeta": { - "expo": { - "optional": true - }, - "react": { - "optional": true - }, - "react-native": { - "optional": true - } - } - }, - "packages/expo-two-way-audio/node_modules/@expo/dom-webview": { - "version": "58.0.2", - "resolved": "https://registry.npmjs.org/@expo/dom-webview/-/dom-webview-58.0.2.tgz", - "integrity": "sha512-bLkREoP7qL3rEuzxP60xG+TjdPoGjbnZfxkvYo5imJxGWfKMOf7x962W06Pu+WWAr4gcDRk16iA+Clg8D0zjCg==", - "dev": true, - "license": "MIT", - "peer": true, - "peerDependencies": { - "expo": "*", - "react": "*", - "react-native": "*" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/env": { - "version": "2.5.2", - "resolved": "https://registry.npmjs.org/@expo/env/-/env-2.5.2.tgz", - "integrity": "sha512-z8kCvBVJpd2S20a+Ab1otQgz8sJLeR7CXDTsuAMcNbYFsK10Fdhfb7rx9Ys1vvlbijnY55eZhQvJACajc1IjBQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "chalk": "^4.0.0", - "debug": "^4.3.4", - "getenv": "^2.0.0" - }, - "engines": { - "node": ">=20.12.0" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/fingerprint": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@expo/fingerprint/-/fingerprint-0.21.5.tgz", - "integrity": "sha512-4ngc+aPgMK56sYc47tfabmoaNdP7OvPBOH7QPgN3riSYM0Ev+KwsGRDius5jBBwjCI9ADp7IpjJEK9xlRYjjvA==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@expo/env": "^2.5.2", - "@expo/spawn-async": "^1.8.0", - "arg": "^5.0.2", - "chalk": "^4.1.2", - "debug": "^4.3.4", - "getenv": "^2.0.0", - "glob": "^13.0.0", - "ignore": "^5.3.1", - "minimatch": "^10.2.2", - "resolve-from": "^5.0.0", - "semver": "^7.7.4" - }, - "bin": { - "fingerprint": "bin/cli.js" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/fingerprint/node_modules/ignore": { - "version": "5.3.2", - "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz", - "integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==", - "dev": true, - "license": "MIT", - "peer": true, - "engines": { - "node": ">= 4" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/image-utils": { - "version": "0.12.5", - "resolved": "https://registry.npmjs.org/@expo/image-utils/-/image-utils-0.12.5.tgz", - "integrity": "sha512-nsFYd7GfDdwZa+S+p+EkVCkh7UKKNf0kfUXDQ53HbyMmNFD3psb5JYwU/2N+uZG5wOEfKGfQ5u7pk/wn2gMlBA==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@expo/require-utils": "^58.0.4", - "@expo/spawn-async": "^1.8.0", - "chalk": "^4.0.0", - "getenv": "^2.0.0", - "jimp-compact": "0.16.1", - "parse-png": "^2.1.0", - "semver": "^7.7.4" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/image-utils/node_modules/@expo/require-utils": { - "version": "58.0.4", - "resolved": "https://registry.npmjs.org/@expo/require-utils/-/require-utils-58.0.4.tgz", - "integrity": "sha512-DvjS5NCitXYcad2Woe1EMHJKcbhTbE77HX0BgOQGL2LFHE3q2H0n8kCWDPBOCVJ63Drap3c35nwoJwF5TQL7Tw==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@babel/code-frame": "^7.20.0", - "@babel/core": "^7.25.2", - "@babel/plugin-transform-modules-commonjs": "^7.24.8" - }, - "peerDependencies": { - "typescript": "^5.0.0 || ^5.0.0-0 || ^6.0.0 || ^7.0.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "packages/expo-two-way-audio/node_modules/@expo/inline-modules": { - "version": "0.2.6", - "resolved": "https://registry.npmjs.org/@expo/inline-modules/-/inline-modules-0.2.6.tgz", - "integrity": "sha512-S8PK3wx6ogwunoQ7pqdPbklQGtXloeWTAOzWJ9yIL7xHFxvnI/Ryj0phA3KEGCMlaKZjaCP1h/3s7n/ueErRgQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@expo/config-plugins": "~58.0.9" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/inline-modules/node_modules/@expo/config-plugins": { - "version": "58.0.9", - "resolved": "https://registry.npmjs.org/@expo/config-plugins/-/config-plugins-58.0.9.tgz", - "integrity": "sha512-HyP7V1QgDxeHcOEh4qQH7cfK7cI7wNp0y9lszAu98SRYCshhDbwB9gWpFfnpX1GQUtgiqG4Hvgh1z3ntcGwAjw==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@expo/config-types": "^58.0.3", - "@expo/json-file": "~11.2.1", - "@expo/plist": "^0.10.1", - "@expo/require-utils": "^58.0.4", - "@expo/sdk-runtime-versions": "^1.0.1", - "chalk": "^4.1.2", - "debug": "^4.3.5", - "getenv": "^2.0.0", - "glob": "^13.0.0", - "semver": "^7.7.4", - "slugify": "^1.6.6", - "xcode": "^3.0.1", - "xml2js": "0.6.0" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/inline-modules/node_modules/@expo/config-types": { - "version": "58.0.3", - "resolved": "https://registry.npmjs.org/@expo/config-types/-/config-types-58.0.3.tgz", - "integrity": "sha512-wyfrwkTT/hQHzwyqkXkngKxoOa8L6ovsTP4h/UukS1mTmssee5et6HOPoN5RtawdJPnm5JO28f//C/wXlpka8Q==", - "dev": true, - "license": "MIT", - "peer": true - }, - "packages/expo-two-way-audio/node_modules/@expo/inline-modules/node_modules/@expo/json-file": { - "version": "11.2.1", - "resolved": "https://registry.npmjs.org/@expo/json-file/-/json-file-11.2.1.tgz", - "integrity": "sha512-UPhKoFCj8BcwgLB1rKQ1CuR/REITnZLiqxHEHOeH1tPsdXcHGtUDh0P5bLbr7oU0nKVdtJ5rzyKx8jniMQdESQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@babel/code-frame": "^7.20.0", - "json5": "^2.2.3" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/inline-modules/node_modules/@expo/plist": { - "version": "0.10.1", - "resolved": "https://registry.npmjs.org/@expo/plist/-/plist-0.10.1.tgz", - "integrity": "sha512-nuNOqj+r/hGJbZ1Ax3jUpZaOB8UAMHUrISALJEUKaCieTflYj7224EqFWmMpriCGk9wXS1gH+9GGVnSj0tWzuQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@xmldom/xmldom": "^0.8.8", - "base64-js": "^1.5.1", - "xmlbuilder": "^15.1.1" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/inline-modules/node_modules/@expo/require-utils": { - "version": "58.0.4", - "resolved": "https://registry.npmjs.org/@expo/require-utils/-/require-utils-58.0.4.tgz", - "integrity": "sha512-DvjS5NCitXYcad2Woe1EMHJKcbhTbE77HX0BgOQGL2LFHE3q2H0n8kCWDPBOCVJ63Drap3c35nwoJwF5TQL7Tw==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@babel/code-frame": "^7.20.0", - "@babel/core": "^7.25.2", - "@babel/plugin-transform-modules-commonjs": "^7.24.8" - }, - "peerDependencies": { - "typescript": "^5.0.0 || ^5.0.0-0 || ^6.0.0 || ^7.0.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "packages/expo-two-way-audio/node_modules/@expo/json-file": { - "version": "10.2.0", - "resolved": "https://registry.npmjs.org/@expo/json-file/-/json-file-10.2.0.tgz", - "integrity": "sha512-S6XzKe3R9GQeHiUPXc3xJjOv2VJhOEwFYf7xdC2z2cUqt3kZJ9mSO877sNQloVdnW/SUCtPY3bexlM7nwq+CAQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/code-frame": "^7.20.0", - "json5": "^2.2.3" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/local-build-cache-provider": { - "version": "58.0.6", - "resolved": "https://registry.npmjs.org/@expo/local-build-cache-provider/-/local-build-cache-provider-58.0.6.tgz", - "integrity": "sha512-AJk3pslFNlwRMbUbfvxhu6CPA9U7A+JPb88VS/uWkG/S/QMJL90Iw4sPVfG4BOKfRUNkB8ipl432Dr4txjSMKw==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@expo/config": "~58.0.6", - "chalk": "^4.1.2" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/local-build-cache-provider/node_modules/@expo/config": { - "version": "58.0.6", - "resolved": "https://registry.npmjs.org/@expo/config/-/config-58.0.6.tgz", - "integrity": "sha512-PT1qv4s/R5A/NxXb4efGlFsYF5Consi7F8xSsJBAN090EGDr6U1EDQGOijFqzDc3JA2epD8zjKLJLOVB9YOewg==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@expo/config-plugins": "~58.0.9", - "@expo/config-types": "^58.0.3", - "@expo/json-file": "^11.2.1", - "@expo/platforms": "^58.0.1", - "@expo/require-utils": "^58.0.4", - "deepmerge": "^4.3.1", - "getenv": "^2.0.0", - "glob": "^13.0.0", - "resolve-workspace-root": "^2.0.0", - "semver": "^7.7.4", - "slugify": "^1.3.4" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/local-build-cache-provider/node_modules/@expo/config-plugins": { - "version": "58.0.9", - "resolved": "https://registry.npmjs.org/@expo/config-plugins/-/config-plugins-58.0.9.tgz", - "integrity": "sha512-HyP7V1QgDxeHcOEh4qQH7cfK7cI7wNp0y9lszAu98SRYCshhDbwB9gWpFfnpX1GQUtgiqG4Hvgh1z3ntcGwAjw==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@expo/config-types": "^58.0.3", - "@expo/json-file": "~11.2.1", - "@expo/plist": "^0.10.1", - "@expo/require-utils": "^58.0.4", - "@expo/sdk-runtime-versions": "^1.0.1", - "chalk": "^4.1.2", - "debug": "^4.3.5", - "getenv": "^2.0.0", - "glob": "^13.0.0", - "semver": "^7.7.4", - "slugify": "^1.6.6", - "xcode": "^3.0.1", - "xml2js": "0.6.0" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/local-build-cache-provider/node_modules/@expo/config-types": { - "version": "58.0.3", - "resolved": "https://registry.npmjs.org/@expo/config-types/-/config-types-58.0.3.tgz", - "integrity": "sha512-wyfrwkTT/hQHzwyqkXkngKxoOa8L6ovsTP4h/UukS1mTmssee5et6HOPoN5RtawdJPnm5JO28f//C/wXlpka8Q==", - "dev": true, - "license": "MIT", - "peer": true - }, - "packages/expo-two-way-audio/node_modules/@expo/local-build-cache-provider/node_modules/@expo/json-file": { - "version": "11.2.1", - "resolved": "https://registry.npmjs.org/@expo/json-file/-/json-file-11.2.1.tgz", - "integrity": "sha512-UPhKoFCj8BcwgLB1rKQ1CuR/REITnZLiqxHEHOeH1tPsdXcHGtUDh0P5bLbr7oU0nKVdtJ5rzyKx8jniMQdESQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@babel/code-frame": "^7.20.0", - "json5": "^2.2.3" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/local-build-cache-provider/node_modules/@expo/plist": { - "version": "0.10.1", - "resolved": "https://registry.npmjs.org/@expo/plist/-/plist-0.10.1.tgz", - "integrity": "sha512-nuNOqj+r/hGJbZ1Ax3jUpZaOB8UAMHUrISALJEUKaCieTflYj7224EqFWmMpriCGk9wXS1gH+9GGVnSj0tWzuQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@xmldom/xmldom": "^0.8.8", - "base64-js": "^1.5.1", - "xmlbuilder": "^15.1.1" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/local-build-cache-provider/node_modules/@expo/require-utils": { - "version": "58.0.4", - "resolved": "https://registry.npmjs.org/@expo/require-utils/-/require-utils-58.0.4.tgz", - "integrity": "sha512-DvjS5NCitXYcad2Woe1EMHJKcbhTbE77HX0BgOQGL2LFHE3q2H0n8kCWDPBOCVJ63Drap3c35nwoJwF5TQL7Tw==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@babel/code-frame": "^7.20.0", - "@babel/core": "^7.25.2", - "@babel/plugin-transform-modules-commonjs": "^7.24.8" - }, - "peerDependencies": { - "typescript": "^5.0.0 || ^5.0.0-0 || ^6.0.0 || ^7.0.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "packages/expo-two-way-audio/node_modules/@expo/log-box": { - "version": "58.0.12", - "resolved": "https://registry.npmjs.org/@expo/log-box/-/log-box-58.0.12.tgz", - "integrity": "sha512-IzDYoFY2iUsmSDvl1V7YUM7UkCPDyMVS4e4a38c2LnFc1A3WGMUiQh+vsHLYTPKjIelu4r7/u4V7Gxtfa0oJgA==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@expo/dom-webview": "^58.0.2", - "@expo/log-box-utils": "^58.0.2", - "anser": "^1.4.9", - "stacktrace-parser": "^0.1.10" - }, - "peerDependencies": { - "@expo/dom-webview": "^58.0.2", - "expo": "*", - "react": "*", - "react-native": "*" - }, - "peerDependenciesMeta": { - "expo": { - "optional": true - } - } - }, - "packages/expo-two-way-audio/node_modules/@expo/metro": { - "version": "58.0.0", - "resolved": "https://registry.npmjs.org/@expo/metro/-/metro-58.0.0.tgz", - "integrity": "sha512-PMD640ihB0C3Oqm0AnDVJ/8qF2cKbRUEqGuSOr4tM/OTb9ktxsQqsiSSSeaOEgdCZBq20AxRS0d6WHNhhH2P+g==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "metro": "0.87.1", - "metro-babel-transformer": "0.87.1", - "metro-cache": "0.87.1", - "metro-cache-key": "0.87.1", - "metro-config": "0.87.1", - "metro-core": "0.87.1", - "metro-file-map": "0.87.1", - "metro-minify-terser": "0.87.1", - "metro-resolver": "0.87.1", - "metro-runtime": "0.87.1", - "metro-source-map": "0.87.1", - "metro-symbolicate": "0.87.1", - "metro-transform-plugins": "0.87.1", - "metro-transform-worker": "0.87.1" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/metro-config": { - "version": "58.0.14", - "resolved": "https://registry.npmjs.org/@expo/metro-config/-/metro-config-58.0.14.tgz", - "integrity": "sha512-UDUMAJwYGEzaB26ejMLG/IOVzwKDbHzoODBf3FZeRS94kk9jDf1dWE1VMX6bLBLoiflxXwqrMWiH0Fvz3gZ9YQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@babel/code-frame": "^7.20.0", - "@babel/core": "^7.20.0", - "@babel/generator": "^7.20.5", - "@expo/config": "~58.0.6", - "@expo/env": "~2.5.2", - "@expo/json-file": "~11.2.1", - "@expo/metro": "~58.0.0", - "@expo/platforms": "^58.0.1", - "@expo/require-utils": "^58.0.4", - "@expo/spawn-async": "^1.8.0", - "@jridgewell/gen-mapping": "^0.3.13", - "@jridgewell/remapping": "^2.3.5", - "@jridgewell/sourcemap-codec": "^1.5.5", - "@jridgewell/trace-mapping": "^0.3.31", - "@react-native/js-polyfills": "0.88.0", - "2g": "^1.0.1", - "browserslist": "^4.25.0", - "chalk": "^4.1.0", - "debug": "^4.3.2", - "getenv": "^2.0.0", - "glob": "^13.0.0", - "hermes-parser": "^0.36.0", - "jsc-safe-url": "^0.2.4", - "lightningcss": "^1.30.1", - "noxcturnal": "^0.1.0", - "picomatch": "^4.0.4", - "postcss": "^8.5.23", - "resolve-from": "^5.0.0" - }, - "peerDependencies": { - "expo": "*" - }, - "peerDependenciesMeta": { - "expo": { - "optional": true - } - } - }, - "packages/expo-two-way-audio/node_modules/@expo/metro-config/node_modules/@expo/config": { - "version": "58.0.6", - "resolved": "https://registry.npmjs.org/@expo/config/-/config-58.0.6.tgz", - "integrity": "sha512-PT1qv4s/R5A/NxXb4efGlFsYF5Consi7F8xSsJBAN090EGDr6U1EDQGOijFqzDc3JA2epD8zjKLJLOVB9YOewg==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@expo/config-plugins": "~58.0.9", - "@expo/config-types": "^58.0.3", - "@expo/json-file": "^11.2.1", - "@expo/platforms": "^58.0.1", - "@expo/require-utils": "^58.0.4", - "deepmerge": "^4.3.1", - "getenv": "^2.0.0", - "glob": "^13.0.0", - "resolve-workspace-root": "^2.0.0", - "semver": "^7.7.4", - "slugify": "^1.3.4" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/metro-config/node_modules/@expo/config-plugins": { - "version": "58.0.9", - "resolved": "https://registry.npmjs.org/@expo/config-plugins/-/config-plugins-58.0.9.tgz", - "integrity": "sha512-HyP7V1QgDxeHcOEh4qQH7cfK7cI7wNp0y9lszAu98SRYCshhDbwB9gWpFfnpX1GQUtgiqG4Hvgh1z3ntcGwAjw==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@expo/config-types": "^58.0.3", - "@expo/json-file": "~11.2.1", - "@expo/plist": "^0.10.1", - "@expo/require-utils": "^58.0.4", - "@expo/sdk-runtime-versions": "^1.0.1", - "chalk": "^4.1.2", - "debug": "^4.3.5", - "getenv": "^2.0.0", - "glob": "^13.0.0", - "semver": "^7.7.4", - "slugify": "^1.6.6", - "xcode": "^3.0.1", - "xml2js": "0.6.0" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/metro-config/node_modules/@expo/config-types": { - "version": "58.0.3", - "resolved": "https://registry.npmjs.org/@expo/config-types/-/config-types-58.0.3.tgz", - "integrity": "sha512-wyfrwkTT/hQHzwyqkXkngKxoOa8L6ovsTP4h/UukS1mTmssee5et6HOPoN5RtawdJPnm5JO28f//C/wXlpka8Q==", - "dev": true, - "license": "MIT", - "peer": true - }, - "packages/expo-two-way-audio/node_modules/@expo/metro-config/node_modules/@expo/json-file": { - "version": "11.2.1", - "resolved": "https://registry.npmjs.org/@expo/json-file/-/json-file-11.2.1.tgz", - "integrity": "sha512-UPhKoFCj8BcwgLB1rKQ1CuR/REITnZLiqxHEHOeH1tPsdXcHGtUDh0P5bLbr7oU0nKVdtJ5rzyKx8jniMQdESQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@babel/code-frame": "^7.20.0", - "json5": "^2.2.3" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/metro-config/node_modules/@expo/plist": { - "version": "0.10.1", - "resolved": "https://registry.npmjs.org/@expo/plist/-/plist-0.10.1.tgz", - "integrity": "sha512-nuNOqj+r/hGJbZ1Ax3jUpZaOB8UAMHUrISALJEUKaCieTflYj7224EqFWmMpriCGk9wXS1gH+9GGVnSj0tWzuQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@xmldom/xmldom": "^0.8.8", - "base64-js": "^1.5.1", - "xmlbuilder": "^15.1.1" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/metro-config/node_modules/@expo/require-utils": { - "version": "58.0.4", - "resolved": "https://registry.npmjs.org/@expo/require-utils/-/require-utils-58.0.4.tgz", - "integrity": "sha512-DvjS5NCitXYcad2Woe1EMHJKcbhTbE77HX0BgOQGL2LFHE3q2H0n8kCWDPBOCVJ63Drap3c35nwoJwF5TQL7Tw==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@babel/code-frame": "^7.20.0", - "@babel/core": "^7.25.2", - "@babel/plugin-transform-modules-commonjs": "^7.24.8" - }, - "peerDependencies": { - "typescript": "^5.0.0 || ^5.0.0-0 || ^6.0.0 || ^7.0.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "packages/expo-two-way-audio/node_modules/@expo/metro-config/node_modules/2g": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/2g/-/2g-1.0.1.tgz", - "integrity": "sha512-+uViadKOS/wwR4pFu5g8TPn3QHpKqoX19JHCnp8k/3cLpImdcXozwvZA6Q/5PeW3AcU8neL8faaMidBcv7o8CA==", - "dev": true, - "license": "MIT", - "peer": true, - "bin": { - "2g": "bin/cli.js" - }, - "peerDependencies": { - "typescript": ">=5.8.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "packages/expo-two-way-audio/node_modules/@expo/metro-config/node_modules/hermes-estree": { - "version": "0.36.1", - "resolved": "https://registry.npmjs.org/hermes-estree/-/hermes-estree-0.36.1.tgz", - "integrity": "sha512-guv1nQ6IJ7S83NRFPWc3SA7IBZrdNC9kapwOq6uXvF4wP+sDCgjzQbKPCoyYmoyZRzztF/n/c36l/rccCZSiCw==", - "dev": true, - "license": "MIT", - "peer": true - }, - "packages/expo-two-way-audio/node_modules/@expo/metro-config/node_modules/hermes-parser": { - "version": "0.36.1", - "resolved": "https://registry.npmjs.org/hermes-parser/-/hermes-parser-0.36.1.tgz", - "integrity": "sha512-GApNk4zLHi2UWoWZZkx7LNCOSzLSc5lB55pZ/PhK7ycFeg7u5LcF88p/WbpIi1XUDtE0MpHE3uRR3u3KB7TjSQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "hermes-estree": "0.36.1" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/metro-file-map": { - "version": "58.0.5", - "resolved": "https://registry.npmjs.org/@expo/metro-file-map/-/metro-file-map-58.0.5.tgz", - "integrity": "sha512-Y2w8qKklLffZie28In4WF6f6e8nIJOhU0mZ5UaQdCiITVQm2a5teNdIDudEPkBsh8ItlvyHZt9n42PN2onRbkQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "2g": "^1.0.1", - "debug": "^4.3.4", - "fb-watchman": "^2.0.2", - "invariant": "^2.2.4", - "jest-worker": "^29.7.0", - "walker": "^1.0.8" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/metro-file-map/node_modules/2g": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/2g/-/2g-1.0.1.tgz", - "integrity": "sha512-+uViadKOS/wwR4pFu5g8TPn3QHpKqoX19JHCnp8k/3cLpImdcXozwvZA6Q/5PeW3AcU8neL8faaMidBcv7o8CA==", - "dev": true, - "license": "MIT", - "peer": true, - "bin": { - "2g": "bin/cli.js" - }, - "peerDependencies": { - "typescript": ">=5.8.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "packages/expo-two-way-audio/node_modules/@expo/osascript": { - "version": "2.8.1", - "resolved": "https://registry.npmjs.org/@expo/osascript/-/osascript-2.8.1.tgz", - "integrity": "sha512-SCi+6q6uOkGhiAn6AIP/OPFgaIq/iKD2oYpnAOg2rShHStJ8ey7wyT127RbOaZXmlcY/62rHOX1WiiMnD8u/BA==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@expo/spawn-async": "^1.8.0" - }, - "engines": { - "node": ">=12" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/package-manager": { - "version": "1.14.2", - "resolved": "https://registry.npmjs.org/@expo/package-manager/-/package-manager-1.14.2.tgz", - "integrity": "sha512-sftl0eRVVCarI6grMdjAB3jX2pX1Mt3cdSnajlXS4QyeDkaKRM/ntBy6dcagj1VL0+cEfEqctlyvinmlZdNubg==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@expo/json-file": "^11.2.1", - "@expo/spawn-async": "^1.8.0", - "chalk": "^4.0.0", - "npm-package-arg": "^11.0.0", - "ora": "^3.4.0", - "resolve-workspace-root": "^2.0.0" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/package-manager/node_modules/@expo/json-file": { - "version": "11.2.1", - "resolved": "https://registry.npmjs.org/@expo/json-file/-/json-file-11.2.1.tgz", - "integrity": "sha512-UPhKoFCj8BcwgLB1rKQ1CuR/REITnZLiqxHEHOeH1tPsdXcHGtUDh0P5bLbr7oU0nKVdtJ5rzyKx8jniMQdESQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@babel/code-frame": "^7.20.0", - "json5": "^2.2.3" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/plist": { - "version": "0.4.9", - "resolved": "https://registry.npmjs.org/@expo/plist/-/plist-0.4.9.tgz", - "integrity": "sha512-MPVpmKGfnQEnrCzgxuXcmPP/y/t6AVm+DcSb2Myp21LKWv1N3l8uFxMggesfF4ixAxkRlGmMMx9GyDC9M+XklQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@xmldom/xmldom": "^0.8.8", - "base64-js": "^1.2.3", - "xmlbuilder": "^15.1.1" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/prebuild-config": { - "version": "58.0.14", - "resolved": "https://registry.npmjs.org/@expo/prebuild-config/-/prebuild-config-58.0.14.tgz", - "integrity": "sha512-2wVzVDfXjRB3LzUbW5shOM/A+6eUUCfR+2bpZiWRBBZBtZP2HA5Zq1YgCio1tDqMGAHf2NQQDhvy/Rz1U6aC3A==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@expo/config": "~58.0.6", - "@expo/config-plugins": "~58.0.9", - "@expo/config-types": "^58.0.3", - "@expo/image-utils": "^0.12.5", - "@expo/json-file": "^11.2.1", - "@react-native/normalize-colors": "0.88.0", - "debug": "^4.3.1", - "expo-modules-autolinking": "~58.0.13", - "resolve-from": "^5.0.0", - "semver": "^7.7.4" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/prebuild-config/node_modules/@expo/config": { - "version": "58.0.6", - "resolved": "https://registry.npmjs.org/@expo/config/-/config-58.0.6.tgz", - "integrity": "sha512-PT1qv4s/R5A/NxXb4efGlFsYF5Consi7F8xSsJBAN090EGDr6U1EDQGOijFqzDc3JA2epD8zjKLJLOVB9YOewg==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@expo/config-plugins": "~58.0.9", - "@expo/config-types": "^58.0.3", - "@expo/json-file": "^11.2.1", - "@expo/platforms": "^58.0.1", - "@expo/require-utils": "^58.0.4", - "deepmerge": "^4.3.1", - "getenv": "^2.0.0", - "glob": "^13.0.0", - "resolve-workspace-root": "^2.0.0", - "semver": "^7.7.4", - "slugify": "^1.3.4" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/prebuild-config/node_modules/@expo/config-plugins": { - "version": "58.0.9", - "resolved": "https://registry.npmjs.org/@expo/config-plugins/-/config-plugins-58.0.9.tgz", - "integrity": "sha512-HyP7V1QgDxeHcOEh4qQH7cfK7cI7wNp0y9lszAu98SRYCshhDbwB9gWpFfnpX1GQUtgiqG4Hvgh1z3ntcGwAjw==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@expo/config-types": "^58.0.3", - "@expo/json-file": "~11.2.1", - "@expo/plist": "^0.10.1", - "@expo/require-utils": "^58.0.4", - "@expo/sdk-runtime-versions": "^1.0.1", - "chalk": "^4.1.2", - "debug": "^4.3.5", - "getenv": "^2.0.0", - "glob": "^13.0.0", - "semver": "^7.7.4", - "slugify": "^1.6.6", - "xcode": "^3.0.1", - "xml2js": "0.6.0" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/prebuild-config/node_modules/@expo/config-types": { - "version": "58.0.3", - "resolved": "https://registry.npmjs.org/@expo/config-types/-/config-types-58.0.3.tgz", - "integrity": "sha512-wyfrwkTT/hQHzwyqkXkngKxoOa8L6ovsTP4h/UukS1mTmssee5et6HOPoN5RtawdJPnm5JO28f//C/wXlpka8Q==", - "dev": true, - "license": "MIT", - "peer": true - }, - "packages/expo-two-way-audio/node_modules/@expo/prebuild-config/node_modules/@expo/json-file": { - "version": "11.2.1", - "resolved": "https://registry.npmjs.org/@expo/json-file/-/json-file-11.2.1.tgz", - "integrity": "sha512-UPhKoFCj8BcwgLB1rKQ1CuR/REITnZLiqxHEHOeH1tPsdXcHGtUDh0P5bLbr7oU0nKVdtJ5rzyKx8jniMQdESQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@babel/code-frame": "^7.20.0", - "json5": "^2.2.3" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/prebuild-config/node_modules/@expo/plist": { - "version": "0.10.1", - "resolved": "https://registry.npmjs.org/@expo/plist/-/plist-0.10.1.tgz", - "integrity": "sha512-nuNOqj+r/hGJbZ1Ax3jUpZaOB8UAMHUrISALJEUKaCieTflYj7224EqFWmMpriCGk9wXS1gH+9GGVnSj0tWzuQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@xmldom/xmldom": "^0.8.8", - "base64-js": "^1.5.1", - "xmlbuilder": "^15.1.1" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/prebuild-config/node_modules/@expo/require-utils": { - "version": "58.0.4", - "resolved": "https://registry.npmjs.org/@expo/require-utils/-/require-utils-58.0.4.tgz", - "integrity": "sha512-DvjS5NCitXYcad2Woe1EMHJKcbhTbE77HX0BgOQGL2LFHE3q2H0n8kCWDPBOCVJ63Drap3c35nwoJwF5TQL7Tw==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@babel/code-frame": "^7.20.0", - "@babel/core": "^7.25.2", - "@babel/plugin-transform-modules-commonjs": "^7.24.8" - }, - "peerDependencies": { - "typescript": "^5.0.0 || ^5.0.0-0 || ^6.0.0 || ^7.0.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "packages/expo-two-way-audio/node_modules/@expo/schema-utils": { - "version": "58.0.2", - "resolved": "https://registry.npmjs.org/@expo/schema-utils/-/schema-utils-58.0.2.tgz", - "integrity": "sha512-w28y8SG+5ZTdDdmH2ZnCQk9wHVwGzI9NqX5V4urJUFEnxbm7I129fJRkb8RIAJmMA1WKU5h3ONmranV473uaXQ==", - "dev": true, - "license": "MIT", - "peer": true - }, - "packages/expo-two-way-audio/node_modules/@expo/sdk-runtime-versions": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/@expo/sdk-runtime-versions/-/sdk-runtime-versions-1.0.1.tgz", - "integrity": "sha512-kvisefkhxu8Fm/4M8G6DEqUaigrXfrSOm2lFw7hsk/nq0zchcp6B4wSk8rlheHY8FRi5iHxKtoVMGY/3M6h04A==", - "dev": true, - "license": "MIT" - }, - "packages/expo-two-way-audio/node_modules/@expo/spawn-async": { - "version": "1.8.0", - "resolved": "https://registry.npmjs.org/@expo/spawn-async/-/spawn-async-1.8.0.tgz", - "integrity": "sha512-eb9xxd/LbuEGSdua4NumCu/McVB9EM+F/JxB9pWgnERw4HQ9XyTNH1KapG6oqLWR8TuRK2LQfzJlmNi94CVobw==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "cross-spawn": "^7.0.6" - }, - "engines": { - "node": ">=12" - } - }, - "packages/expo-two-way-audio/node_modules/@jest/schemas": { - "version": "30.4.1", - "resolved": "https://registry.npmjs.org/@jest/schemas/-/schemas-30.4.1.tgz", - "integrity": "sha512-i6b4qw5qnP8c5FEeBJg/uZQ4ddrkN6Ca8qISJh0pr7a5hfn3h3v5x60BEbOC7OYAGZNMs1LfFLwnW2CuK8F57Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "@sinclair/typebox": "^0.34.0" - }, - "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" - } - }, - "packages/expo-two-way-audio/node_modules/@react-native/babel-plugin-codegen": { - "version": "0.88.0", - "resolved": "https://registry.npmjs.org/@react-native/babel-plugin-codegen/-/babel-plugin-codegen-0.88.0.tgz", - "integrity": "sha512-leGEnCcS7Q0hTxvzvhNtr8zGQpI1gfWqXjzC4UedsFmNMv6kIo4s70o0XbtM30ZXbpfWe4BcSC8NKWuak5sI4A==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@babel/traverse": "^7.29.0", - "@react-native/codegen": "0.88.0" - }, - "engines": { - "node": "^22.13.0 || ^24.3.0 || >= 26.0.0" - } - }, - "packages/expo-two-way-audio/node_modules/@react-native/babel-preset": { - "version": "0.88.0", - "resolved": "https://registry.npmjs.org/@react-native/babel-preset/-/babel-preset-0.88.0.tgz", - "integrity": "sha512-iMfAHhFGNegnReSY6CYaWHncvyDwHq8olRs0zp9nRRApMAoCiLyfo1dwL/f39qt/MreD6xIqUs9SrTPYWobY6g==", - "dev": true, - "license": "MIT", - "optional": true, - "peer": true, - "dependencies": { - "@babel/core": "^7.25.2", - "@babel/plugin-proposal-export-default-from": "^7.24.7", - "@babel/plugin-syntax-dynamic-import": "^7.8.3", - "@babel/plugin-syntax-export-default-from": "^7.24.7", - "@babel/plugin-syntax-nullish-coalescing-operator": "^7.8.3", - "@babel/plugin-syntax-optional-chaining": "^7.8.3", - "@babel/plugin-transform-async-generator-functions": "^7.25.4", - "@babel/plugin-transform-async-to-generator": "^7.24.7", - "@babel/plugin-transform-block-scoping": "^7.25.0", - "@babel/plugin-transform-class-properties": "^7.25.4", - "@babel/plugin-transform-classes": "^7.25.4", - "@babel/plugin-transform-destructuring": "^7.24.8", - "@babel/plugin-transform-flow-strip-types": "^7.25.2", - "@babel/plugin-transform-for-of": "^7.24.7", - "@babel/plugin-transform-modules-commonjs": "^7.24.8", - "@babel/plugin-transform-named-capturing-groups-regex": "^7.24.7", - "@babel/plugin-transform-nullish-coalescing-operator": "^7.24.7", - "@babel/plugin-transform-optional-catch-binding": "^7.24.7", - "@babel/plugin-transform-optional-chaining": "^7.24.8", - "@babel/plugin-transform-private-methods": "^7.24.7", - "@babel/plugin-transform-private-property-in-object": "^7.24.7", - "@babel/plugin-transform-react-display-name": "^7.24.7", - "@babel/plugin-transform-react-jsx": "^7.25.2", - "@babel/plugin-transform-react-jsx-self": "^7.24.7", - "@babel/plugin-transform-react-jsx-source": "^7.24.7", - "@babel/plugin-transform-regenerator": "^7.24.7", - "@babel/plugin-transform-runtime": "^7.24.7", - "@babel/plugin-transform-typescript": "^7.25.2", - "@babel/plugin-transform-unicode-regex": "^7.24.7", - "@react-native/babel-plugin-codegen": "0.88.0", - "babel-plugin-transform-flow-enums": "^0.0.2", - "flow-parser": "0.327.0", - "react-refresh": "^0.14.0" - }, - "engines": { - "node": "^22.13.0 || ^24.3.0 || >= 26.0.0" - }, - "peerDependencies": { - "@babel/core": "*" - } - }, - "packages/expo-two-way-audio/node_modules/@react-native/babel-preset/node_modules/flow-parser": { - "version": "0.327.0", - "resolved": "https://registry.npmjs.org/flow-parser/-/flow-parser-0.327.0.tgz", - "integrity": "sha512-/MYZ5hXWf5ozpbdfUDmazMgQXviLxWEiRLH3MppEGDdW0itRVqmB5UaU7QX+SBCDNiq+gEesSVn8nlxmPDyDkw==", - "dev": true, - "license": "MIT", - "optional": true, - "peer": true, - "dependencies": { - "flow-estree": "0.327.0" - }, - "engines": { - "node": ">=0.4.0" - } - }, - "packages/expo-two-way-audio/node_modules/@react-native/codegen": { - "version": "0.88.0", - "resolved": "https://registry.npmjs.org/@react-native/codegen/-/codegen-0.88.0.tgz", - "integrity": "sha512-SAGg+XfzsrPiYTscbKa9bo2/H2ei2TjyxW8RTMq2Ps661kRK3AnmpMGVfrEFshEMr3FGEbuQIvj86X98kaXlRA==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@babel/core": "^7.25.2", - "@babel/parser": "^7.29.0", - "flow-parser": "0.327.0", - "invariant": "^2.2.4", - "nullthrows": "^1.1.1", - "tinyglobby": "^0.2.15", - "yargs": "^17.6.2" - }, - "engines": { - "node": "^22.13.0 || ^24.3.0 || >= 26.0.0" - }, - "peerDependencies": { - "@babel/core": "*" - } - }, - "packages/expo-two-way-audio/node_modules/@react-native/codegen/node_modules/flow-parser": { - "version": "0.327.0", - "resolved": "https://registry.npmjs.org/flow-parser/-/flow-parser-0.327.0.tgz", - "integrity": "sha512-/MYZ5hXWf5ozpbdfUDmazMgQXviLxWEiRLH3MppEGDdW0itRVqmB5UaU7QX+SBCDNiq+gEesSVn8nlxmPDyDkw==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "flow-estree": "0.327.0" - }, - "engines": { - "node": ">=0.4.0" - } - }, - "packages/expo-two-way-audio/node_modules/@react-native/community-cli-plugin": { - "version": "0.88.0", - "resolved": "https://registry.npmjs.org/@react-native/community-cli-plugin/-/community-cli-plugin-0.88.0.tgz", - "integrity": "sha512-WrQdXbjVt1gwAay8ZzYtpOi9ly99ksJ0VMYFdVcMe6nq3vtiRgqKRpHgCdN6ySIbtr5o+aJ+Vr7OTDY98ec/Ow==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@react-native/asset-utils": "0.88.0", - "@react-native/dev-middleware": "0.88.0", - "commander": "^12.0.0", - "debug": "^4.4.0", - "invariant": "^2.2.4", - "metro": "^0.87.1", - "semver": "^7.1.3" - }, - "engines": { - "node": "^22.13.0 || ^24.3.0 || >= 26.0.0" - }, - "peerDependencies": { - "@react-native-community/cli": "*", - "@react-native/metro-config": "0.88.0" - }, - "peerDependenciesMeta": { - "@react-native-community/cli": { - "optional": true - }, - "@react-native/metro-config": { - "optional": true - } - } - }, - "packages/expo-two-way-audio/node_modules/@react-native/debugger-frontend": { - "version": "0.88.0", - "resolved": "https://registry.npmjs.org/@react-native/debugger-frontend/-/debugger-frontend-0.88.0.tgz", - "integrity": "sha512-v5cnBaaWhDRPcQv8EC20zj53jOAKH7u2wnzzXS4JTNu+diPC+cA2+kC7rq3eKI5vGhlAcG2kDPoViRuC0AY0oA==", - "dev": true, - "license": "BSD-3-Clause", - "peer": true, - "engines": { - "node": "^22.13.0 || ^24.3.0 || >= 26.0.0" - } - }, - "packages/expo-two-way-audio/node_modules/@react-native/debugger-shell": { - "version": "0.88.0", - "resolved": "https://registry.npmjs.org/@react-native/debugger-shell/-/debugger-shell-0.88.0.tgz", - "integrity": "sha512-p82zT8ZKNx7nIm/8zf8pi55sxm5KQBm8td47kzoJysTdqHLyPsRMUvDXtvCJIWadHSv7RJ6t/yiCc+IoImLBtw==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "cross-spawn": "^7.0.6", - "debug": "^4.4.0", - "fb-dotslash": "0.5.8" - }, - "engines": { - "node": "^22.13.0 || ^24.3.0 || >= 26.0.0" - } - }, - "packages/expo-two-way-audio/node_modules/@react-native/dev-middleware": { - "version": "0.88.0", - "resolved": "https://registry.npmjs.org/@react-native/dev-middleware/-/dev-middleware-0.88.0.tgz", - "integrity": "sha512-sHLxVHOwfkF672ZzMepNh4d3IKbrZy3qXDKWSwN5LC5VJkzzZ5FdmSPP4N/CCn2pcKJ4oSqvojXwN4De3Xk92A==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@isaacs/ttlcache": "^1.4.1", - "@react-native/debugger-frontend": "0.88.0", - "@react-native/debugger-shell": "0.88.0", - "connect": "^3.6.5", - "debug": "^4.4.0", - "invariant": "^2.2.4", - "nullthrows": "^1.1.1", - "open": "^8.4.2", - "serve-static": "^1.16.2", - "ws": "^7.5.10" - }, - "engines": { - "node": "^22.13.0 || ^24.3.0 || >= 26.0.0" - } - }, - "packages/expo-two-way-audio/node_modules/@react-native/dev-middleware/node_modules/ws": { - "version": "7.5.13", - "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.13.tgz", - "integrity": "sha512-rsKI6xDBFVf4r/x8XyChGK04QR/XHroxs/jUcoWvtEZM8TPU/X/uIY9B1CsSzYws9ZJb/6bbBu7dPhFW00CAoA==", - "dev": true, - "license": "MIT", - "peer": true, - "engines": { - "node": ">=8.3.0" - }, - "peerDependencies": { - "bufferutil": "^4.0.1", - "utf-8-validate": "^5.0.2" - }, - "peerDependenciesMeta": { - "bufferutil": { - "optional": true - }, - "utf-8-validate": { - "optional": true - } - } - }, - "packages/expo-two-way-audio/node_modules/@react-native/gradle-plugin": { - "version": "0.88.0", - "resolved": "https://registry.npmjs.org/@react-native/gradle-plugin/-/gradle-plugin-0.88.0.tgz", - "integrity": "sha512-4jPSKslOfJj8NKY/jv9qmWkxZYmqPyamoS3Vs0JOFxw9t4PM6L/ea0fUsjNV0LxC9zJlvWilPJOCTOf7h8wlyw==", - "dev": true, - "license": "MIT", - "peer": true, - "engines": { - "node": "^22.13.0 || ^24.3.0 || >= 26.0.0" - } - }, - "packages/expo-two-way-audio/node_modules/@react-native/js-polyfills": { - "version": "0.88.0", - "resolved": "https://registry.npmjs.org/@react-native/js-polyfills/-/js-polyfills-0.88.0.tgz", - "integrity": "sha512-Iq6v4+EWdOLv0M1+BpADQJBVfInl6FkABXCIBSi0FbvHahEYT+Y4UJ7Cm96p18gbEN1VKzqz3nbBbwLA6bx0rQ==", - "dev": true, - "license": "MIT", - "peer": true, - "engines": { - "node": "^22.13.0 || ^24.3.0 || >= 26.0.0" - } - }, - "packages/expo-two-way-audio/node_modules/@react-native/metro-babel-transformer": { - "version": "0.88.0", - "resolved": "https://registry.npmjs.org/@react-native/metro-babel-transformer/-/metro-babel-transformer-0.88.0.tgz", - "integrity": "sha512-xsUfzXrqKXeD7sBja7hkyBG32AGIwWJ3IEZ+UcNMRTR/sucnXXZ6Do40qXoeY52YC8b9//J+p51JIp2CC0DZKA==", - "dev": true, - "license": "MIT", - "optional": true, - "peer": true, - "dependencies": { - "@babel/core": "^7.25.2", - "@react-native/babel-preset": "0.88.0", - "flow-parser": "0.327.0", - "nullthrows": "^1.1.1" - }, - "engines": { - "node": "^22.13.0 || ^24.3.0 || >= 26.0.0" - }, - "peerDependencies": { - "@babel/core": "*" - } - }, - "packages/expo-two-way-audio/node_modules/@react-native/metro-babel-transformer/node_modules/flow-parser": { - "version": "0.327.0", - "resolved": "https://registry.npmjs.org/flow-parser/-/flow-parser-0.327.0.tgz", - "integrity": "sha512-/MYZ5hXWf5ozpbdfUDmazMgQXviLxWEiRLH3MppEGDdW0itRVqmB5UaU7QX+SBCDNiq+gEesSVn8nlxmPDyDkw==", - "dev": true, - "license": "MIT", - "optional": true, - "peer": true, - "dependencies": { - "flow-estree": "0.327.0" - }, - "engines": { - "node": ">=0.4.0" - } - }, - "packages/expo-two-way-audio/node_modules/@react-native/metro-config": { - "version": "0.88.0", - "resolved": "https://registry.npmjs.org/@react-native/metro-config/-/metro-config-0.88.0.tgz", - "integrity": "sha512-iPV2HNXlPs7xQDBJJGIjkH0x2psZwJeRIEpfSqxgqLaO5eEfE2Ccicfz2OBHBcIC5jKGGa4IoI/e26zMNDuTMQ==", - "dev": true, - "license": "MIT", - "optional": true, - "peer": true, - "dependencies": { - "@react-native/js-polyfills": "0.88.0", - "@react-native/metro-babel-transformer": "0.88.0", - "metro-config": "^0.87.1", - "metro-runtime": "^0.87.1" - }, - "engines": { - "node": "^22.13.0 || ^24.3.0 || >= 26.0.0" - } - }, - "packages/expo-two-way-audio/node_modules/@react-native/normalize-colors": { - "version": "0.88.0", - "resolved": "https://registry.npmjs.org/@react-native/normalize-colors/-/normalize-colors-0.88.0.tgz", - "integrity": "sha512-eZCu3tGAQCfvMCPQJVY4dmoMX8ZZYBvqIGHX7lwOYyzNK+Dl8e5ky7ZoXub1Rq75oSrQXNNmSP2CDjNNXXZpFQ==", - "dev": true, - "license": "MIT", - "peer": true - }, - "packages/expo-two-way-audio/node_modules/@sinclair/typebox": { - "version": "0.34.49", - "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.34.49.tgz", - "integrity": "sha512-brySQQs7Jtn0joV8Xh9ZV/hZb9Ozb0pmazDIASBkYKCjXrXU3mpcFahmK/z4YDhGkQvP9mWJbVyahdtU5wQA+A==", - "dev": true, - "license": "MIT" - }, "packages/expo-two-way-audio/node_modules/@types/react": { "version": "18.3.28", "resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.28.tgz", @@ -39725,1390 +40058,6 @@ "csstype": "^3.2.2" } }, - "packages/expo-two-way-audio/node_modules/@typescript-eslint/scope-manager": { - "version": "8.61.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.61.1.tgz", - "integrity": "sha512-L2bdIeoQS8FlKAvONAr20w6OcLXeB+qiDKbAooS9A0Ben+iSIkBef0FxqwKWYqt5sa0i4KJtxVyVmhMylKzF5w==", - "dev": true, - "license": "MIT", - "dependencies": { - "@typescript-eslint/types": "8.61.1", - "@typescript-eslint/visitor-keys": "8.61.1" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - } - }, - "packages/expo-two-way-audio/node_modules/@typescript-eslint/types": { - "version": "8.61.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.61.1.tgz", - "integrity": "sha512-G+CRlPqLv7Bz1IZVs03x5K59F1veqL0EJUROAdGhKsEq8qOiRiZbI+HUojPq5l0fEGOKModD9br6lObhB8zkoA==", - "dev": true, - "license": "MIT", - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - } - }, - "packages/expo-two-way-audio/node_modules/@typescript-eslint/visitor-keys": { - "version": "8.61.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.61.1.tgz", - "integrity": "sha512-6fJ9MHWtK14C1DSkiMlHUSOmrVebL7150xZJBlJiL62jjhIA4JmOq6flwBgDxIdBKKdoiZRel+dfPD5MLfny3w==", - "dev": true, - "license": "MIT", - "dependencies": { - "@typescript-eslint/types": "8.61.1", - "eslint-visitor-keys": "^5.0.0" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - } - }, - "packages/expo-two-way-audio/node_modules/@xmldom/xmldom": { - "version": "0.8.13", - "resolved": "https://registry.npmjs.org/@xmldom/xmldom/-/xmldom-0.8.13.tgz", - "integrity": "sha512-KRYzxepc14G/CEpEGc3Yn+JKaAeT63smlDr+vjB8jRfgTBBI9wRj/nkQEO+ucV8p8I9bfKLWp37uHgFrbntPvw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=10.0.0" - } - }, - "packages/expo-two-way-audio/node_modules/agent-base": { - "version": "7.1.4", - "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", - "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", - "dev": true, - "license": "MIT", - "peer": true, - "engines": { - "node": ">= 14" - } - }, - "packages/expo-two-way-audio/node_modules/ansi-styles": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz", - "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/ansi-styles?sponsor=1" - } - }, - "packages/expo-two-way-audio/node_modules/babel-plugin-react-native-web": { - "version": "0.21.4", - "resolved": "https://registry.npmjs.org/babel-plugin-react-native-web/-/babel-plugin-react-native-web-0.21.4.tgz", - "integrity": "sha512-FSclsDTGi5EcvpbW3TM7s8GLWwQqo5wI9zQqJr2m0IoJRenSkp1+bVvdeZXTNznI5Ms9Bry7DLBR+C5Shb9gtw==", - "dev": true, - "license": "MIT", - "peer": true - }, - "packages/expo-two-way-audio/node_modules/babel-plugin-syntax-hermes-parser": { - "version": "0.36.1", - "resolved": "https://registry.npmjs.org/babel-plugin-syntax-hermes-parser/-/babel-plugin-syntax-hermes-parser-0.36.1.tgz", - "integrity": "sha512-ycduwJbvdvIMmVvlAZqGggS+pm5Eu4Bk9pcV9Sm2Z4PJNRVsKkv0g7vHj+LeuC1gHTeF67sJXFOq61IlqCa2hA==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "hermes-parser": "0.36.1" - } - }, - "packages/expo-two-way-audio/node_modules/babel-plugin-syntax-hermes-parser/node_modules/hermes-estree": { - "version": "0.36.1", - "resolved": "https://registry.npmjs.org/hermes-estree/-/hermes-estree-0.36.1.tgz", - "integrity": "sha512-guv1nQ6IJ7S83NRFPWc3SA7IBZrdNC9kapwOq6uXvF4wP+sDCgjzQbKPCoyYmoyZRzztF/n/c36l/rccCZSiCw==", - "dev": true, - "license": "MIT", - "peer": true - }, - "packages/expo-two-way-audio/node_modules/babel-plugin-syntax-hermes-parser/node_modules/hermes-parser": { - "version": "0.36.1", - "resolved": "https://registry.npmjs.org/hermes-parser/-/hermes-parser-0.36.1.tgz", - "integrity": "sha512-GApNk4zLHi2UWoWZZkx7LNCOSzLSc5lB55pZ/PhK7ycFeg7u5LcF88p/WbpIi1XUDtE0MpHE3uRR3u3KB7TjSQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "hermes-estree": "0.36.1" - } - }, - "packages/expo-two-way-audio/node_modules/balanced-match": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", - "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", - "dev": true, - "license": "MIT", - "engines": { - "node": "18 || 20 || >=22" - } - }, - "packages/expo-two-way-audio/node_modules/brace-expansion": { - "version": "5.0.6", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.6.tgz", - "integrity": "sha512-kLpxurY4Z4r9sgMsyG0Z9uzsBlgiU/EFKhj/h91/8yHu0edo7XuixOIH3VcJ8kkxs6/jPzoI6U9Vj3WqbMQ94g==", - "dev": true, - "license": "MIT", - "dependencies": { - "balanced-match": "^4.0.2" - }, - "engines": { - "node": "18 || 20 || >=22" - } - }, - "packages/expo-two-way-audio/node_modules/cli-cursor": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-2.1.0.tgz", - "integrity": "sha512-8lgKz8LmCRYZZQDpRyT2m5rKJ08TnU4tR9FFFW2rxpxR1FzWi4PQ/NfyODchAatHaUgnSPVcx/R5w6NuTBzFiw==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "restore-cursor": "^2.0.0" - }, - "engines": { - "node": ">=4" - } - }, - "packages/expo-two-way-audio/node_modules/color-convert": { - "version": "1.9.3", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", - "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "color-name": "1.1.3" - } - }, - "packages/expo-two-way-audio/node_modules/color-name": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", - "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==", - "dev": true, - "license": "MIT", - "peer": true - }, - "packages/expo-two-way-audio/node_modules/commander": { - "version": "12.1.0", - "resolved": "https://registry.npmjs.org/commander/-/commander-12.1.0.tgz", - "integrity": "sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" - } - }, - "packages/expo-two-way-audio/node_modules/content-type": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", - "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", - "dev": true, - "license": "MIT", - "peer": true, - "engines": { - "node": ">=18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "packages/expo-two-way-audio/node_modules/escape-string-regexp": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", - "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", - "dev": true, - "license": "MIT", - "peer": true, - "engines": { - "node": ">=0.8.0" - } - }, - "packages/expo-two-way-audio/node_modules/eslint-config-prettier": { - "version": "9.1.2", - "resolved": "https://registry.npmjs.org/eslint-config-prettier/-/eslint-config-prettier-9.1.2.tgz", - "integrity": "sha512-iI1f+D2ViGn+uvv5HuHVUamg8ll4tN+JRHGc6IJi4TP9Kl976C57fzPXgseXNs8v0iA8aSJpHsTWjDb9QJamGQ==", - "dev": true, - "license": "MIT", - "bin": { - "eslint-config-prettier": "bin/cli.js" - }, - "peerDependencies": { - "eslint": ">=7.0.0" - } - }, - "packages/expo-two-way-audio/node_modules/eslint-config-universe": { - "version": "15.2.0", - "resolved": "https://registry.npmjs.org/eslint-config-universe/-/eslint-config-universe-15.2.0.tgz", - "integrity": "sha512-n2662q/mM+2pTFVz7ELosqhN+/nbR75Ut/4vLme40kKSHHe0oPbPMxgPqyYrASlANuSDP4aAJ71rRviDMCZTxg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@typescript-eslint/eslint-plugin": "^8.59.0", - "@typescript-eslint/parser": "^8.59.0", - "eslint-config-prettier": "^9.1.0", - "eslint-plugin-import": "^2.31.0", - "eslint-plugin-n": "^17.17.0", - "eslint-plugin-node": "^11.1.0", - "eslint-plugin-prettier": "^5.2.6", - "eslint-plugin-react": "^7.37.5", - "eslint-plugin-react-hooks": "^7.0.0", - "globals": "^16.0.0" - }, - "peerDependencies": { - "eslint": ">=8.10", - "prettier": ">=3" - }, - "peerDependenciesMeta": { - "prettier": { - "optional": true - } - } - }, - "packages/expo-two-way-audio/node_modules/eslint-config-universe/node_modules/@typescript-eslint/eslint-plugin": { - "version": "8.61.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.61.1.tgz", - "integrity": "sha512-ZPlVl3PB3et/59Ne0fv/sci6ZXz4T4Hp4nTJ56i/Y0gR89ARb+KphojTq6j+56E5PIezmOIOOWyY+aWQFd+IkQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@eslint-community/regexpp": "^4.12.2", - "@typescript-eslint/scope-manager": "8.61.1", - "@typescript-eslint/type-utils": "8.61.1", - "@typescript-eslint/utils": "8.61.1", - "@typescript-eslint/visitor-keys": "8.61.1", - "ignore": "^7.0.5", - "natural-compare": "^1.4.0", - "ts-api-utils": "^2.5.0" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependencies": { - "@typescript-eslint/parser": "^8.61.1", - "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", - "typescript": ">=4.8.4 <6.1.0" - } - }, - "packages/expo-two-way-audio/node_modules/eslint-config-universe/node_modules/@typescript-eslint/parser": { - "version": "8.61.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.61.1.tgz", - "integrity": "sha512-PJ5vePq5/ognBbrIcoC5+SHO5dfpeLPzP9FpLkzWrguoYQEeeSjlJpVwOpo1JRSTEi7dRcwNy4h4dzV70PqHcg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@typescript-eslint/scope-manager": "8.61.1", - "@typescript-eslint/types": "8.61.1", - "@typescript-eslint/typescript-estree": "8.61.1", - "@typescript-eslint/visitor-keys": "8.61.1", - "debug": "^4.4.3" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependencies": { - "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", - "typescript": ">=4.8.4 <6.1.0" - } - }, - "packages/expo-two-way-audio/node_modules/eslint-config-universe/node_modules/@typescript-eslint/project-service": { - "version": "8.61.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.61.1.tgz", - "integrity": "sha512-PrC4JYGmR241lYnfhmKGTXkFqv8+ymbTFgSAY0fVXpY82/QkMw5TZPl+vGzuDDU2QYJk9fIDOBTntF+yDv9LEA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@typescript-eslint/tsconfig-utils": "^8.61.1", - "@typescript-eslint/types": "^8.61.1", - "debug": "^4.4.3" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependencies": { - "typescript": ">=4.8.4 <6.1.0" - } - }, - "packages/expo-two-way-audio/node_modules/eslint-config-universe/node_modules/@typescript-eslint/tsconfig-utils": { - "version": "8.61.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.61.1.tgz", - "integrity": "sha512-UN/H4di+OO7EWx2ovME+8t31YO+KVnK0RRKEHR3kOt21/Ay8BOq3M1OMvWs5vNiqcFCYGYoxK3MXPZzmMUE+yg==", - "dev": true, - "license": "MIT", - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependencies": { - "typescript": ">=4.8.4 <6.1.0" - } - }, - "packages/expo-two-way-audio/node_modules/eslint-config-universe/node_modules/@typescript-eslint/type-utils": { - "version": "8.61.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.61.1.tgz", - "integrity": "sha512-GYRicKmVK0C4fsKgaACaknOUAq9Oa2kwsjnpFhFcS/5p4Ht5IP9OVLbgIgcK4SRk92nVHFluurg1lumD9dBcLw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@typescript-eslint/types": "8.61.1", - "@typescript-eslint/typescript-estree": "8.61.1", - "@typescript-eslint/utils": "8.61.1", - "debug": "^4.4.3", - "ts-api-utils": "^2.5.0" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependencies": { - "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", - "typescript": ">=4.8.4 <6.1.0" - } - }, - "packages/expo-two-way-audio/node_modules/eslint-config-universe/node_modules/@typescript-eslint/typescript-estree": { - "version": "8.61.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.61.1.tgz", - "integrity": "sha512-u+oQD3BqYWPc8YV9Zab4vaJElJuwOLPRc10Jm1o/qS+6Qwen14HCWwx0Seo4LnSn2wxea2Ik8DxPt2/FHmuhrg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@typescript-eslint/project-service": "8.61.1", - "@typescript-eslint/tsconfig-utils": "8.61.1", - "@typescript-eslint/types": "8.61.1", - "@typescript-eslint/visitor-keys": "8.61.1", - "debug": "^4.4.3", - "minimatch": "^10.2.2", - "semver": "^7.7.3", - "tinyglobby": "^0.2.15", - "ts-api-utils": "^2.5.0" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependencies": { - "typescript": ">=4.8.4 <6.1.0" - } - }, - "packages/expo-two-way-audio/node_modules/eslint-config-universe/node_modules/@typescript-eslint/utils": { - "version": "8.61.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.61.1.tgz", - "integrity": "sha512-1+P/3Dj6jvtybE1q0HQ6yBt/gq+oKJyLdEv4HdnqasaEXRSYCAsD59mXEVQnM/ULNdQxbX77tdG4jPRjIS6knA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@eslint-community/eslint-utils": "^4.9.1", - "@typescript-eslint/scope-manager": "8.61.1", - "@typescript-eslint/types": "8.61.1", - "@typescript-eslint/typescript-estree": "8.61.1" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependencies": { - "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", - "typescript": ">=4.8.4 <6.1.0" - } - }, - "packages/expo-two-way-audio/node_modules/eslint-config-universe/node_modules/ts-api-utils": { - "version": "2.5.0", - "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.5.0.tgz", - "integrity": "sha512-OJ/ibxhPlqrMM0UiNHJ/0CKQkoKF243/AEmplt3qpRgkW8VG7IfOS41h7V8TjITqdByHzrjcS/2si+y4lIh8NA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18.12" - }, - "peerDependencies": { - "typescript": ">=4.8.4" - } - }, - "packages/expo-two-way-audio/node_modules/eslint-plugin-react-hooks": { - "version": "7.1.1", - "resolved": "https://registry.npmjs.org/eslint-plugin-react-hooks/-/eslint-plugin-react-hooks-7.1.1.tgz", - "integrity": "sha512-f2I7Gw6JbvCexzIInuSbZpfdQ44D7iqdWX01FKLvrPgqxoE7oMj8clOfto8U6vYiz4yd5oKu39rRSVOe1zRu0g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/core": "^7.24.4", - "@babel/parser": "^7.24.4", - "hermes-parser": "^0.25.1", - "zod": "^3.25.0 || ^4.0.0", - "zod-validation-error": "^3.5.0 || ^4.0.0" - }, - "engines": { - "node": ">=18" - }, - "peerDependencies": { - "eslint": "^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0-0 || ^9.0.0 || ^10.0.0" - } - }, - "packages/expo-two-way-audio/node_modules/eslint-visitor-keys": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-5.0.1.tgz", - "integrity": "sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": "^20.19.0 || ^22.13.0 || >=24" - }, - "funding": { - "url": "https://opencollective.com/eslint" - } - }, - "packages/expo-two-way-audio/node_modules/expo-asset": { - "version": "58.0.16", - "resolved": "https://registry.npmjs.org/expo-asset/-/expo-asset-58.0.16.tgz", - "integrity": "sha512-beR3uusLA+rFo+6Ug0L7FPR4b6y/37VwtYW2Jig/i+3Co+oyYCTnvVuFPWhb05W9TOZRxdHUEI569fVKIgtYAA==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@expo/image-utils": "^0.12.5", - "expo-constants": "~58.0.12" - }, - "peerDependencies": { - "expo": "*", - "react": "*", - "react-native": "*" - } - }, - "packages/expo-two-way-audio/node_modules/expo-constants": { - "version": "58.0.12", - "resolved": "https://registry.npmjs.org/expo-constants/-/expo-constants-58.0.12.tgz", - "integrity": "sha512-d3/dsps32nU4m6YJQbXQ1dIfn58GxfmJjTnZ0WtnhdSHTdG/oVsOakLqYRlX/FaLUKkQOSHXMf7hyCx+2a/HSQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@expo/env": "~2.5.2", - "@expo/require-utils": "^58.0.4" - }, - "peerDependencies": { - "expo": "*", - "react-native": "*" - } - }, - "packages/expo-two-way-audio/node_modules/expo-constants/node_modules/@expo/require-utils": { - "version": "58.0.4", - "resolved": "https://registry.npmjs.org/@expo/require-utils/-/require-utils-58.0.4.tgz", - "integrity": "sha512-DvjS5NCitXYcad2Woe1EMHJKcbhTbE77HX0BgOQGL2LFHE3q2H0n8kCWDPBOCVJ63Drap3c35nwoJwF5TQL7Tw==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@babel/code-frame": "^7.20.0", - "@babel/core": "^7.25.2", - "@babel/plugin-transform-modules-commonjs": "^7.24.8" - }, - "peerDependencies": { - "typescript": "^5.0.0 || ^5.0.0-0 || ^6.0.0 || ^7.0.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "packages/expo-two-way-audio/node_modules/expo-file-system": { - "version": "58.0.9", - "resolved": "https://registry.npmjs.org/expo-file-system/-/expo-file-system-58.0.9.tgz", - "integrity": "sha512-JT0km3Wa+wDz/7Rli8ifreoMnmk68ulf/uaWzRA26xm/4K+jGTY+cDhnboRmpmXUCBkED6uqxWmNoXjaVU9VUw==", - "dev": true, - "license": "MIT", - "peer": true, - "peerDependencies": { - "expo": "*", - "react-native": "*" - } - }, - "packages/expo-two-way-audio/node_modules/expo-font": { - "version": "58.0.8", - "resolved": "https://registry.npmjs.org/expo-font/-/expo-font-58.0.8.tgz", - "integrity": "sha512-i9HKj/ljdmmjLamYQEkI4wXJB9+ap7AG5CpCqK/bgwwy45y5T8+1lpNbYgRXE7aQgmDjPpzd09wX6dOZkHfrxg==", - "dev": true, - "license": "MIT", - "peer": true, - "peerDependencies": { - "expo": "*", - "react": "*", - "react-native": "*" - } - }, - "packages/expo-two-way-audio/node_modules/expo-keep-awake": { - "version": "58.0.3", - "resolved": "https://registry.npmjs.org/expo-keep-awake/-/expo-keep-awake-58.0.3.tgz", - "integrity": "sha512-wLRF+XeVsD/Rt/ZyX+A0mk1brdf8vefWizNAPzqV5eOCgkj23LCRZdN8gUi5X8UwyR8UJ7Y7Dzdz4YDGB/4c9Q==", - "dev": true, - "license": "MIT", - "peer": true, - "peerDependencies": { - "expo": "*", - "react": "*" - } - }, - "packages/expo-two-way-audio/node_modules/expo-module-scripts": { - "version": "5.0.8", - "resolved": "https://registry.npmjs.org/expo-module-scripts/-/expo-module-scripts-5.0.8.tgz", - "integrity": "sha512-3YkAic3E6QGQuNEIchq6/0GGSBwR2C70AhDUF7VI7/N3THwUpeqZrX20FxHKN95/wclHs1ljrGvRX+2YTgXxiw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/cli": "^7.23.4", - "@babel/plugin-transform-export-namespace-from": "^7.23.4", - "@babel/preset-env": "^7.23.8", - "@babel/preset-typescript": "^7.23.3", - "@expo/npm-proofread": "^1.0.1", - "@testing-library/react-native": "^13.2.0", - "@tsconfig/node18": "^18.2.2", - "@types/jest": "^29.2.1", - "babel-plugin-dynamic-import-node": "^2.3.3", - "babel-preset-expo": "~54.0.7", - "commander": "^12.1.0", - "eslint-config-universe": "^15.0.3", - "glob": "^13.0.0", - "jest-expo": "~54.0.13", - "jest-snapshot-prettier": "npm:prettier@^2", - "jest-watch-typeahead": "2.2.1", - "resolve-workspace-root": "^2.0.0", - "ts-jest": "~29.0.4", - "typescript": "^5.9.2" - }, - "bin": { - "expo-module": "bin/expo-module.js" - } - }, - "packages/expo-two-way-audio/node_modules/expo-module-scripts/node_modules/@expo/config-plugins": { - "version": "58.0.9", - "resolved": "https://registry.npmjs.org/@expo/config-plugins/-/config-plugins-58.0.9.tgz", - "integrity": "sha512-HyP7V1QgDxeHcOEh4qQH7cfK7cI7wNp0y9lszAu98SRYCshhDbwB9gWpFfnpX1GQUtgiqG4Hvgh1z3ntcGwAjw==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@expo/config-types": "^58.0.3", - "@expo/json-file": "~11.2.1", - "@expo/plist": "^0.10.1", - "@expo/require-utils": "^58.0.4", - "@expo/sdk-runtime-versions": "^1.0.1", - "chalk": "^4.1.2", - "debug": "^4.3.5", - "getenv": "^2.0.0", - "glob": "^13.0.0", - "semver": "^7.7.4", - "slugify": "^1.6.6", - "xcode": "^3.0.1", - "xml2js": "0.6.0" - } - }, - "packages/expo-two-way-audio/node_modules/expo-module-scripts/node_modules/@expo/config-plugins/node_modules/@expo/json-file": { - "version": "11.2.1", - "resolved": "https://registry.npmjs.org/@expo/json-file/-/json-file-11.2.1.tgz", - "integrity": "sha512-UPhKoFCj8BcwgLB1rKQ1CuR/REITnZLiqxHEHOeH1tPsdXcHGtUDh0P5bLbr7oU0nKVdtJ5rzyKx8jniMQdESQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@babel/code-frame": "^7.20.0", - "json5": "^2.2.3" - } - }, - "packages/expo-two-way-audio/node_modules/expo-module-scripts/node_modules/@expo/config-plugins/node_modules/@expo/require-utils": { - "version": "58.0.4", - "resolved": "https://registry.npmjs.org/@expo/require-utils/-/require-utils-58.0.4.tgz", - "integrity": "sha512-DvjS5NCitXYcad2Woe1EMHJKcbhTbE77HX0BgOQGL2LFHE3q2H0n8kCWDPBOCVJ63Drap3c35nwoJwF5TQL7Tw==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@babel/code-frame": "^7.20.0", - "@babel/core": "^7.25.2", - "@babel/plugin-transform-modules-commonjs": "^7.24.8" - }, - "peerDependencies": { - "typescript": "^5.0.0 || ^5.0.0-0 || ^6.0.0 || ^7.0.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "packages/expo-two-way-audio/node_modules/expo-module-scripts/node_modules/@expo/config-types": { - "version": "58.0.3", - "resolved": "https://registry.npmjs.org/@expo/config-types/-/config-types-58.0.3.tgz", - "integrity": "sha512-wyfrwkTT/hQHzwyqkXkngKxoOa8L6ovsTP4h/UukS1mTmssee5et6HOPoN5RtawdJPnm5JO28f//C/wXlpka8Q==", - "dev": true, - "license": "MIT", - "peer": true - }, - "packages/expo-two-way-audio/node_modules/expo-module-scripts/node_modules/@expo/metro-runtime": { - "version": "58.0.14", - "resolved": "https://registry.npmjs.org/@expo/metro-runtime/-/metro-runtime-58.0.14.tgz", - "integrity": "sha512-IIvTo+RpN5jZVuYspQdECsxQ03VGWjZnGS6wtr9U7DERBpykUe+ZSHDZ1hsrvQ7HAucsVoKr9np0xAscGEuXtg==", - "dev": true, - "license": "MIT", - "optional": true, - "peer": true, - "dependencies": { - "@expo/log-box": "^58.0.12", - "anser": "^1.4.9", - "pretty-format": "^29.7.0", - "stacktrace-parser": "^0.1.10", - "whatwg-fetch": "^3.0.0" - }, - "peerDependencies": { - "@expo/log-box": "^58.0.12", - "expo": "*", - "react": "*", - "react-dom": "*", - "react-native": "*" - }, - "peerDependenciesMeta": { - "react-dom": { - "optional": true - } - } - }, - "packages/expo-two-way-audio/node_modules/expo-module-scripts/node_modules/@expo/metro-runtime/node_modules/pretty-format": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-29.7.0.tgz", - "integrity": "sha512-Pdlw/oPxN+aXdmM9R00JVC9WVFoCLTKJvDVLgmJ+qAffBMxsV85l/Lu7sNx4zSzPyoL2euImuEwHhOXdEgNFZQ==", - "dev": true, - "license": "MIT", - "optional": true, - "peer": true, - "dependencies": { - "@jest/schemas": "^29.6.3", - "ansi-styles": "^5.0.0", - "react-is": "^18.0.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "packages/expo-two-way-audio/node_modules/expo-module-scripts/node_modules/@expo/plist": { - "version": "0.10.1", - "resolved": "https://registry.npmjs.org/@expo/plist/-/plist-0.10.1.tgz", - "integrity": "sha512-nuNOqj+r/hGJbZ1Ax3jUpZaOB8UAMHUrISALJEUKaCieTflYj7224EqFWmMpriCGk9wXS1gH+9GGVnSj0tWzuQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@xmldom/xmldom": "^0.8.8", - "base64-js": "^1.5.1", - "xmlbuilder": "^15.1.1" - } - }, - "packages/expo-two-way-audio/node_modules/expo-module-scripts/node_modules/@jest/schemas": { - "version": "29.6.3", - "resolved": "https://registry.npmjs.org/@jest/schemas/-/schemas-29.6.3.tgz", - "integrity": "sha512-mo5j5X+jIZmJQveBKeS/clAueipV7KgiX1vMgCxam1RNYiqE1w62n0/tJJnHtjW8ZHcQco5gY85jA3mi0L+nSA==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@sinclair/typebox": "^0.27.8" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "packages/expo-two-way-audio/node_modules/expo-module-scripts/node_modules/@react-native/virtualized-lists": { - "version": "0.88.0", - "resolved": "https://registry.npmjs.org/@react-native/virtualized-lists/-/virtualized-lists-0.88.0.tgz", - "integrity": "sha512-zpZIOAbobdS93edwHkNUdGDzvElNeQJqukRERRPns3/ucPvuMd2G4fYpmVJSVjhxtGCcLLB1PFndLYYfwaYoBQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "invariant": "^2.2.4", - "nullthrows": "^1.1.1" - }, - "engines": { - "node": "^22.13.0 || ^24.3.0 || >= 26.0.0" - }, - "peerDependencies": { - "@types/react": "^19.2.0", - "react": "*", - "react-native": "0.88.0" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - } - } - }, - "packages/expo-two-way-audio/node_modules/expo-module-scripts/node_modules/@sinclair/typebox": { - "version": "0.27.12", - "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.27.12.tgz", - "integrity": "sha512-hhyNJ+nbR6ZR7pToHvllEFun9TL0sbL+tk/ON75lo+Xas054uez98qRbsuNt7MBCyZKK4+8Yli/OAGZhmfBZ/g==", - "dev": true, - "license": "MIT", - "peer": true - }, - "packages/expo-two-way-audio/node_modules/expo-module-scripts/node_modules/@testing-library/react-native": { - "version": "13.3.3", - "resolved": "https://registry.npmjs.org/@testing-library/react-native/-/react-native-13.3.3.tgz", - "integrity": "sha512-k6Mjsd9dbZgvY4Bl7P1NIpePQNi+dfYtlJ5voi9KQlynxSyQkfOgJmYGCYmw/aSgH/rUcFvG8u5gd4npzgRDyg==", - "dev": true, - "license": "MIT", - "dependencies": { - "jest-matcher-utils": "^30.0.5", - "picocolors": "^1.1.1", - "pretty-format": "^30.0.5", - "redent": "^3.0.0" - }, - "engines": { - "node": ">=18" - }, - "peerDependencies": { - "jest": ">=29.0.0", - "react": ">=18.2.0", - "react-native": ">=0.71", - "react-test-renderer": ">=18.2.0" - }, - "peerDependenciesMeta": { - "jest": { - "optional": true - } - } - }, - "packages/expo-two-way-audio/node_modules/expo-module-scripts/node_modules/@types/react": { - "version": "19.3.0", - "resolved": "https://registry.npmjs.org/@types/react/-/react-19.3.0.tgz", - "integrity": "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==", - "dev": true, - "license": "MIT", - "optional": true, - "peer": true, - "dependencies": { - "csstype": "^3.2.2" - } - }, - "packages/expo-two-way-audio/node_modules/expo-module-scripts/node_modules/expo": { - "version": "58.0.14", - "resolved": "https://registry.npmjs.org/expo/-/expo-58.0.14.tgz", - "integrity": "sha512-M05O++KRgG4NA6kQ9AP60kbN8xqHJ6S8uTXdtkeiwcGVIYzdu2kaUXJyraVturvePO/Mf4PWa0C9+JggrHITwA==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@babel/runtime": "^7.20.0", - "@expo/cli": "^58.1.11", - "@expo/config": "~58.0.6", - "@expo/config-plugins": "~58.0.9", - "@expo/devtools": "~58.0.2", - "@expo/dom-webview": "~58.0.2", - "@expo/fingerprint": "^0.21.5", - "@expo/local-build-cache-provider": "^58.0.6", - "@expo/log-box": "^58.0.12", - "@expo/log-box-utils": "^58.0.2", - "@expo/metro": "~58.0.0", - "@expo/metro-config": "~58.0.14", - "@ungap/structured-clone": "^1.3.0", - "babel-preset-expo": "~58.0.17", - "expo-asset": "~58.0.16", - "expo-constants": "~58.0.12", - "expo-file-system": "~58.0.9", - "expo-font": "~58.0.8", - "expo-keep-awake": "~58.0.3", - "expo-modules-autolinking": "~58.0.13", - "expo-modules-core": "~58.0.22", - "pretty-format": "^29.7.0", - "react-refresh": "^0.14.2", - "whatwg-url-minimum": "^0.2.0" - }, - "bin": { - "expo": "bin/cli", - "expo-modules-autolinking": "bin/autolinking", - "fingerprint": "bin/fingerprint" - }, - "engines": { - "node": "^22.13.0 || ^24.3.0 || ^26.0.0 || >=27.0.0" - }, - "peerDependencies": { - "@expo/dom-webview": "*", - "@expo/metro-runtime": "*", - "react": "*", - "react-dom": "*", - "react-native": "*", - "react-native-web": "*", - "react-native-webview": "*" - }, - "peerDependenciesMeta": { - "@expo/dom-webview": { - "optional": true - }, - "@expo/metro-runtime": { - "optional": true - }, - "react-dom": { - "optional": true - }, - "react-native-web": { - "optional": true - }, - "react-native-webview": { - "optional": true - } - } - }, - "packages/expo-two-way-audio/node_modules/expo-module-scripts/node_modules/expo-modules-core": { - "version": "58.0.22", - "resolved": "https://registry.npmjs.org/expo-modules-core/-/expo-modules-core-58.0.22.tgz", - "integrity": "sha512-T3YJYziFkF4JlGDpX4zCl91oIxz1Skq5sp1LFVO+GL/BARSIXk013QWGdRZrvt+wMxoVaql5dpOdPdP5q2+0jQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "expo-modules-jsi": "~58.0.15", - "expo-modules-macros": "0.20.0", - "invariant": "^2.2.4" - }, - "peerDependencies": { - "react": "*", - "react-native": "*", - "react-native-worklets": ">=0.13.0" - }, - "peerDependenciesMeta": { - "react-native-worklets": { - "optional": true - } - } - }, - "packages/expo-two-way-audio/node_modules/expo-module-scripts/node_modules/expo/node_modules/@expo/cli": { - "version": "58.1.11", - "resolved": "https://registry.npmjs.org/@expo/cli/-/cli-58.1.11.tgz", - "integrity": "sha512-wkFTSLXXYqLkRT5oy4DnLuTOtbFIu3qTiXHSHkFSqUBTHiE92y3bOIwM3UN7Y1ys18qVJge8lXjezaEfsHmijQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@expo/code-signing-certificates": "^0.0.7", - "@expo/config": "~58.0.6", - "@expo/config-plugins": "~58.0.9", - "@expo/devcert": "^1.2.2", - "@expo/env": "~2.5.2", - "@expo/image-utils": "^0.12.5", - "@expo/inline-modules": "^0.2.6", - "@expo/json-file": "^11.2.1", - "@expo/log-box": "^58.0.12", - "@expo/log-box-utils": "^58.0.2", - "@expo/metro": "~58.0.0", - "@expo/metro-config": "58.0.14", - "@expo/metro-file-map": "^58.0.5", - "@expo/osascript": "^2.8.1", - "@expo/package-manager": "^1.14.2", - "@expo/platforms": "^58.0.1", - "@expo/plist": "^0.10.1", - "@expo/prebuild-config": "^58.0.14", - "@expo/require-utils": "^58.0.4", - "@expo/router-server": "^58.0.14", - "@expo/schema-utils": "^58.0.2", - "@expo/spawn-async": "^1.8.0", - "@expo/ws-tunnel": "^2.0.1", - "@expo/xcpretty": "^4.4.6", - "@react-native/asset-utils": "0.88.0", - "@react-native/dev-middleware": "0.88.0", - "@react-native/js-polyfills": "0.88.0", - "2g": "^1.0.1", - "accepts": "^1.3.8", - "agent-cli-detector": "0.1.7", - "arg": "^5.0.2", - "bplist-creator": "0.1.0", - "bplist-parser": "^0.3.1", - "chalk": "^4.0.0", - "ci-info": "^3.3.0", - "compression": "^1.7.4", - "connect": "^3.7.0", - "dnssd-advertise": "^1.1.6", - "expo-server": "^58.0.5", - "fetch-nodeshim": "^0.4.10", - "getenv": "^2.0.0", - "glob": "^13.0.0", - "lan-network": "^0.2.1", - "multitars": "^1.0.2", - "node-forge": "^1.4.0", - "npm-package-arg": "^11.0.0", - "ora": "^3.4.0", - "picomatch": "^4.0.4", - "pretty-format": "^29.7.0", - "progress": "^2.0.3", - "prompts": "^2.3.2", - "resolve-from": "^5.0.0", - "sandbox-cli-detector": "^0.2.0", - "semver": "^7.7.4", - "send": "^0.19.0", - "slugify": "^1.3.4", - "stacktrace-parser": "^0.1.10", - "structured-headers": "^0.4.1", - "terminal-link": "^2.1.1", - "toqr": "^0.1.1", - "wrap-ansi": "^7.0.0", - "ws": "^8.12.1", - "zod": "^3.25.76" - }, - "bin": { - "expo-internal": "bin/cli.js" - }, - "peerDependencies": { - "expo": "*", - "expo-router": "*", - "react-native": "*" - }, - "peerDependenciesMeta": { - "expo-router": { - "optional": true - }, - "react-native": { - "optional": true - } - } - }, - "packages/expo-two-way-audio/node_modules/expo-module-scripts/node_modules/expo/node_modules/@expo/cli/node_modules/@expo/router-server": { - "version": "58.0.14", - "resolved": "https://registry.npmjs.org/@expo/router-server/-/router-server-58.0.14.tgz", - "integrity": "sha512-RSzQYMA+Tv2eTemhjhzpx8+hL+pMC30JTVqAWrk5AZwht+OgaKZar/gHmj4iJf7n3rq+GG6KujrkKF9xAXLz2w==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "debug": "^4.3.4" - }, - "peerDependencies": { - "@expo/metro-runtime": "^58.0.14", - "expo": "*", - "expo-constants": "^58.0.12", - "expo-font": "^58.0.8", - "expo-router": "*", - "expo-server": "^58.0.5", - "react": "*", - "react-dom": "*", - "react-server-dom-webpack": "~19.0.1 || ~19.1.2 || ~19.2.1 || ~19.3.0" - }, - "peerDependenciesMeta": { - "@expo/metro-runtime": { - "optional": true - }, - "expo-router": { - "optional": true - }, - "react-dom": { - "optional": true - }, - "react-server-dom-webpack": { - "optional": true - } - } - }, - "packages/expo-two-way-audio/node_modules/expo-module-scripts/node_modules/expo/node_modules/@expo/config": { - "version": "58.0.6", - "resolved": "https://registry.npmjs.org/@expo/config/-/config-58.0.6.tgz", - "integrity": "sha512-PT1qv4s/R5A/NxXb4efGlFsYF5Consi7F8xSsJBAN090EGDr6U1EDQGOijFqzDc3JA2epD8zjKLJLOVB9YOewg==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@expo/config-plugins": "~58.0.9", - "@expo/config-types": "^58.0.3", - "@expo/json-file": "^11.2.1", - "@expo/platforms": "^58.0.1", - "@expo/require-utils": "^58.0.4", - "deepmerge": "^4.3.1", - "getenv": "^2.0.0", - "glob": "^13.0.0", - "resolve-workspace-root": "^2.0.0", - "semver": "^7.7.4", - "slugify": "^1.3.4" - } - }, - "packages/expo-two-way-audio/node_modules/expo-module-scripts/node_modules/expo/node_modules/@expo/json-file": { - "version": "11.2.1", - "resolved": "https://registry.npmjs.org/@expo/json-file/-/json-file-11.2.1.tgz", - "integrity": "sha512-UPhKoFCj8BcwgLB1rKQ1CuR/REITnZLiqxHEHOeH1tPsdXcHGtUDh0P5bLbr7oU0nKVdtJ5rzyKx8jniMQdESQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@babel/code-frame": "^7.20.0", - "json5": "^2.2.3" - } - }, - "packages/expo-two-way-audio/node_modules/expo-module-scripts/node_modules/expo/node_modules/@expo/require-utils": { - "version": "58.0.4", - "resolved": "https://registry.npmjs.org/@expo/require-utils/-/require-utils-58.0.4.tgz", - "integrity": "sha512-DvjS5NCitXYcad2Woe1EMHJKcbhTbE77HX0BgOQGL2LFHE3q2H0n8kCWDPBOCVJ63Drap3c35nwoJwF5TQL7Tw==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@babel/code-frame": "^7.20.0", - "@babel/core": "^7.25.2", - "@babel/plugin-transform-modules-commonjs": "^7.24.8" - }, - "peerDependencies": { - "typescript": "^5.0.0 || ^5.0.0-0 || ^6.0.0 || ^7.0.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "packages/expo-two-way-audio/node_modules/expo-module-scripts/node_modules/expo/node_modules/2g": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/2g/-/2g-1.0.1.tgz", - "integrity": "sha512-+uViadKOS/wwR4pFu5g8TPn3QHpKqoX19JHCnp8k/3cLpImdcXozwvZA6Q/5PeW3AcU8neL8faaMidBcv7o8CA==", - "dev": true, - "license": "MIT", - "peer": true, - "bin": { - "2g": "bin/cli.js" - }, - "peerDependencies": { - "typescript": ">=5.8.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "packages/expo-two-way-audio/node_modules/expo-module-scripts/node_modules/expo/node_modules/babel-preset-expo": { - "version": "58.0.17", - "resolved": "https://registry.npmjs.org/babel-preset-expo/-/babel-preset-expo-58.0.17.tgz", - "integrity": "sha512-Rrqc/Z5Idc4bG2/PrEh725t3kvuAc7jUKCJ+wZVU9KXk2bKSdqAniXxQa8aph9aHdv4h5sGKLpMXMaMNz/4+Og==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@babel/generator": "^7.20.5", - "@babel/helper-module-imports": "^7.25.9", - "@babel/plugin-proposal-decorators": "^7.12.9", - "@babel/plugin-proposal-export-default-from": "^7.24.7", - "@babel/plugin-syntax-dynamic-import": "^7.8.3", - "@babel/plugin-syntax-export-default-from": "^7.24.7", - "@babel/plugin-syntax-nullish-coalescing-operator": "^7.8.3", - "@babel/plugin-syntax-optional-chaining": "^7.8.3", - "@babel/plugin-transform-async-generator-functions": "^7.25.4", - "@babel/plugin-transform-async-to-generator": "^7.24.7", - "@babel/plugin-transform-block-scoping": "^7.25.0", - "@babel/plugin-transform-class-properties": "^7.25.4", - "@babel/plugin-transform-class-static-block": "^7.27.1", - "@babel/plugin-transform-classes": "^7.25.4", - "@babel/plugin-transform-destructuring": "^7.24.8", - "@babel/plugin-transform-export-namespace-from": "^7.25.9", - "@babel/plugin-transform-flow-strip-types": "^7.25.2", - "@babel/plugin-transform-for-of": "^7.24.7", - "@babel/plugin-transform-logical-assignment-operators": "^7.24.7", - "@babel/plugin-transform-modules-commonjs": "^7.24.8", - "@babel/plugin-transform-named-capturing-groups-regex": "^7.24.7", - "@babel/plugin-transform-nullish-coalescing-operator": "^7.24.7", - "@babel/plugin-transform-object-rest-spread": "^7.24.7", - "@babel/plugin-transform-optional-catch-binding": "^7.24.7", - "@babel/plugin-transform-optional-chaining": "^7.24.8", - "@babel/plugin-transform-parameters": "^7.24.7", - "@babel/plugin-transform-private-methods": "^7.24.7", - "@babel/plugin-transform-private-property-in-object": "^7.24.7", - "@babel/plugin-transform-react-display-name": "^7.24.7", - "@babel/plugin-transform-react-jsx": "^7.28.6", - "@babel/plugin-transform-react-jsx-development": "^7.27.1", - "@babel/plugin-transform-react-pure-annotations": "^7.27.1", - "@babel/plugin-transform-runtime": "^7.24.7", - "@babel/plugin-transform-typescript": "^7.25.2", - "@babel/plugin-transform-unicode-regex": "^7.24.7", - "@babel/preset-typescript": "^7.23.0", - "@react-native/babel-plugin-codegen": "0.88.0", - "babel-plugin-react-compiler": "^1.0.0", - "babel-plugin-react-native-web": "~0.21.4", - "babel-plugin-syntax-hermes-parser": "^0.36.0", - "babel-plugin-transform-flow-enums": "^0.0.2", - "debug": "^4.3.4" - }, - "peerDependencies": { - "@babel/runtime": "^7.20.0", - "expo": "*", - "expo-widgets": "^58.0.20", - "react-refresh": ">=0.14.0 <1.0.0" - }, - "peerDependenciesMeta": { - "@babel/runtime": { - "optional": true - }, - "expo": { - "optional": true - }, - "expo-widgets": { - "optional": true - } - } - }, - "packages/expo-two-way-audio/node_modules/expo-module-scripts/node_modules/expo/node_modules/pretty-format": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-29.7.0.tgz", - "integrity": "sha512-Pdlw/oPxN+aXdmM9R00JVC9WVFoCLTKJvDVLgmJ+qAffBMxsV85l/Lu7sNx4zSzPyoL2euImuEwHhOXdEgNFZQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@jest/schemas": "^29.6.3", - "ansi-styles": "^5.0.0", - "react-is": "^18.0.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "packages/expo-two-way-audio/node_modules/expo-module-scripts/node_modules/flow-parser": { - "version": "0.327.0", - "resolved": "https://registry.npmjs.org/flow-parser/-/flow-parser-0.327.0.tgz", - "integrity": "sha512-/MYZ5hXWf5ozpbdfUDmazMgQXviLxWEiRLH3MppEGDdW0itRVqmB5UaU7QX+SBCDNiq+gEesSVn8nlxmPDyDkw==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "flow-estree": "0.327.0" - }, - "engines": { - "node": ">=0.4.0" - } - }, - "packages/expo-two-way-audio/node_modules/expo-module-scripts/node_modules/jest-expo": { - "version": "54.0.17", - "resolved": "https://registry.npmjs.org/jest-expo/-/jest-expo-54.0.17.tgz", - "integrity": "sha512-LyIhrsP4xvHEEcR1R024u/LBj3uPpAgB+UljgV+YXWkEHjprnr0KpE4tROsMNYCVTM1pPlAnPuoBmn5gnAN9KA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@expo/config": "~12.0.13", - "@expo/json-file": "^10.0.8", - "@jest/create-cache-key-function": "^29.2.1", - "@jest/globals": "^29.2.1", - "babel-jest": "^29.2.1", - "jest-environment-jsdom": "^29.2.1", - "jest-snapshot": "^29.2.1", - "jest-watch-select-projects": "^2.0.0", - "jest-watch-typeahead": "2.2.1", - "json5": "^2.2.3", - "lodash": "^4.17.19", - "react-test-renderer": "19.1.0", - "server-only": "^0.0.1", - "stacktrace-js": "^2.0.2" - }, - "bin": { - "jest": "bin/jest.js" - }, - "peerDependencies": { - "expo": "*", - "react-native": "*", - "react-server-dom-webpack": "~19.0.4 || ~19.1.5 || ~19.2.4" - }, - "peerDependenciesMeta": { - "react-server-dom-webpack": { - "optional": true - } - } - }, - "packages/expo-two-way-audio/node_modules/expo-module-scripts/node_modules/react-is": { - "version": "18.3.1", - "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.3.1.tgz", - "integrity": "sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg==", - "dev": true, - "license": "MIT", - "peer": true - }, - "packages/expo-two-way-audio/node_modules/expo-module-scripts/node_modules/react-native": { - "version": "0.88.0", - "resolved": "https://registry.npmjs.org/react-native/-/react-native-0.88.0.tgz", - "integrity": "sha512-v/wee0nYWcammMYBnSat/e3WY/5iaf9YQOMcBrfKT/wPApPPlHp94hgZovBtwhMuthR01yc/8cGn0FpFTE/C4A==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@react-native/asset-utils": "0.88.0", - "@react-native/codegen": "0.88.0", - "@react-native/community-cli-plugin": "0.88.0", - "@react-native/gradle-plugin": "0.88.0", - "@react-native/normalize-colors": "0.88.0", - "@react-native/virtualized-lists": "0.88.0", - "anser": "^1.4.9", - "ansi-regex": "^5.0.0", - "base64-js": "^1.5.1", - "flow-enums-runtime": "^0.0.6", - "flow-parser": "0.327.0", - "hermes-compiler": "260318099.0.4", - "invariant": "^2.2.4", - "memoize-one": "^5.0.0", - "metro-runtime": "^0.87.1", - "metro-source-map": "^0.87.1", - "nullthrows": "^1.1.1", - "pretty-format": "^29.7.0", - "promise": "^8.3.0", - "react-devtools-core": "^6.1.5", - "react-refresh": "^0.14.0", - "regenerator-runtime": "^0.13.2", - "scheduler": "0.28.0", - "semver": "^7.1.3", - "stacktrace-parser": "^0.1.10", - "tinyglobby": "^0.2.15", - "whatwg-fetch": "^3.0.0", - "ws": "^7.5.10", - "yargs": "^17.6.2" - }, - "bin": { - "react-native": "cli.js" - }, - "engines": { - "node": "^22.13.0 || ^24.3.0 || >= 26.0.0" - }, - "peerDependencies": { - "@types/react": "^19.1.1", - "react": "^19.3.0" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - } - } - }, - "packages/expo-two-way-audio/node_modules/expo-module-scripts/node_modules/react-native/node_modules/pretty-format": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-29.7.0.tgz", - "integrity": "sha512-Pdlw/oPxN+aXdmM9R00JVC9WVFoCLTKJvDVLgmJ+qAffBMxsV85l/Lu7sNx4zSzPyoL2euImuEwHhOXdEgNFZQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@jest/schemas": "^29.6.3", - "ansi-styles": "^5.0.0", - "react-is": "^18.0.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "packages/expo-two-way-audio/node_modules/expo-module-scripts/node_modules/react-native/node_modules/ws": { - "version": "7.5.13", - "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.13.tgz", - "integrity": "sha512-rsKI6xDBFVf4r/x8XyChGK04QR/XHroxs/jUcoWvtEZM8TPU/X/uIY9B1CsSzYws9ZJb/6bbBu7dPhFW00CAoA==", - "dev": true, - "license": "MIT", - "peer": true, - "engines": { - "node": ">=8.3.0" - }, - "peerDependencies": { - "bufferutil": "^4.0.1", - "utf-8-validate": "^5.0.2" - }, - "peerDependenciesMeta": { - "bufferutil": { - "optional": true - }, - "utf-8-validate": { - "optional": true - } - } - }, - "packages/expo-two-way-audio/node_modules/expo-module-scripts/node_modules/scheduler": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.28.0.tgz", - "integrity": "sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==", - "dev": true, - "license": "MIT", - "peer": true - }, - "packages/expo-two-way-audio/node_modules/expo-modules-autolinking": { - "version": "58.0.13", - "resolved": "https://registry.npmjs.org/expo-modules-autolinking/-/expo-modules-autolinking-58.0.13.tgz", - "integrity": "sha512-uzLFoTnAKabUdITvzRqWTvFkZsOdRPEXj7AEMAuBEhA2kGhqaBDa2EOWqPXVay0QJVoZuIQaEEgPGAXN1dPuYg==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@expo/platforms": "^58.0.1", - "@expo/require-utils": "^58.0.4", - "@expo/spawn-async": "^1.8.0", - "chalk": "^4.1.0", - "commander": "^7.2.0" - }, - "bin": { - "expo-modules-autolinking": "bin/expo-modules-autolinking.js" - } - }, - "packages/expo-two-way-audio/node_modules/expo-modules-autolinking/node_modules/@expo/require-utils": { - "version": "58.0.4", - "resolved": "https://registry.npmjs.org/@expo/require-utils/-/require-utils-58.0.4.tgz", - "integrity": "sha512-DvjS5NCitXYcad2Woe1EMHJKcbhTbE77HX0BgOQGL2LFHE3q2H0n8kCWDPBOCVJ63Drap3c35nwoJwF5TQL7Tw==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@babel/code-frame": "^7.20.0", - "@babel/core": "^7.25.2", - "@babel/plugin-transform-modules-commonjs": "^7.24.8" - }, - "peerDependencies": { - "typescript": "^5.0.0 || ^5.0.0-0 || ^6.0.0 || ^7.0.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "packages/expo-two-way-audio/node_modules/expo-modules-autolinking/node_modules/commander": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/commander/-/commander-7.2.0.tgz", - "integrity": "sha512-QrWXB+ZQSVPmIWIhtEO9H+gwHaMGYiF5ChvoJ+K9ZGHG/sVsa6yiesAD1GC/x46sET00Xlwo1u49RVVVzvcSkw==", - "dev": true, - "license": "MIT", - "peer": true, - "engines": { - "node": ">= 10" - } - }, "packages/expo-two-way-audio/node_modules/expo-modules-core": { "version": "2.5.0", "resolved": "https://registry.npmjs.org/expo-modules-core/-/expo-modules-core-2.5.0.tgz", @@ -41119,770 +40068,6 @@ "invariant": "^2.2.4" } }, - "packages/expo-two-way-audio/node_modules/expo-modules-jsi": { - "version": "58.0.15", - "resolved": "https://registry.npmjs.org/expo-modules-jsi/-/expo-modules-jsi-58.0.15.tgz", - "integrity": "sha512-PsjYgL4KWtvBqWH242r0wbP99VjgHkHCpkPCekO7nzb+ulkDNyrNnhysxa0TcNpfRTNLetmCUaLs9t4CcoquZQ==", - "dev": true, - "license": "MIT", - "peer": true, - "peerDependencies": { - "react-native": "*" - } - }, - "packages/expo-two-way-audio/node_modules/expo-server": { - "version": "58.0.5", - "resolved": "https://registry.npmjs.org/expo-server/-/expo-server-58.0.5.tgz", - "integrity": "sha512-FHYecxfGOuAhacHcanR6qCN8Cln9S+FFulcYetLu3ddDg55ohuCsMZ9U4Egzwdm+A2o6N+MdSoJKquBC5F9NIg==", - "dev": true, - "license": "MIT", - "peer": true, - "engines": { - "node": "^22.13.0 || ^24.3.0 || ^26.0.0 || >=27.0.0" - } - }, - "packages/expo-two-way-audio/node_modules/flow-estree": { - "version": "0.327.0", - "resolved": "https://registry.npmjs.org/flow-estree/-/flow-estree-0.327.0.tgz", - "integrity": "sha512-f9vK751YUzD0qaHSpKc5/qQM6gqOlgGS+4ZRqTNcZOpVqn3mC55yEQ6dUG2K1eaVm5FbKkz9CFWe6XNvrkQFQg==", - "dev": true, - "license": "MIT", - "peer": true, - "engines": { - "node": ">=18" - } - }, - "packages/expo-two-way-audio/node_modules/getenv": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/getenv/-/getenv-2.0.0.tgz", - "integrity": "sha512-VilgtJj/ALgGY77fiLam5iD336eSWi96Q15JSAG1zi8NRBysm3LXKdGnHb4m5cuyxvOLQQKWpBZAT6ni4FI2iQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "packages/expo-two-way-audio/node_modules/glob": { - "version": "13.0.6", - "resolved": "https://registry.npmjs.org/glob/-/glob-13.0.6.tgz", - "integrity": "sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw==", - "dev": true, - "license": "BlueOak-1.0.0", - "dependencies": { - "minimatch": "^10.2.2", - "minipass": "^7.1.3", - "path-scurry": "^2.0.2" - }, - "engines": { - "node": "18 || 20 || >=22" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "packages/expo-two-way-audio/node_modules/globals": { - "version": "16.5.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-16.5.0.tgz", - "integrity": "sha512-c/c15i26VrJ4IRt5Z89DnIzCGDn9EcebibhAOjw5ibqEHsE1wLUgkPn9RDmNcUKyU87GeaL633nyJ+pplFR2ZQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "packages/expo-two-way-audio/node_modules/has-flag": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", - "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==", - "dev": true, - "license": "MIT", - "peer": true, - "engines": { - "node": ">=4" - } - }, - "packages/expo-two-way-audio/node_modules/hermes-compiler": { - "version": "260318099.0.4", - "resolved": "https://registry.npmjs.org/hermes-compiler/-/hermes-compiler-260318099.0.4.tgz", - "integrity": "sha512-8odcPFkPC82HlqCl0C5QI9mBN4rEAT+IAo55sJhzwKw//K3qZloiv3ex6J2O8CuBbhdmkJozfidNsset2KH25w==", - "dev": true, - "license": "MIT", - "peer": true - }, - "packages/expo-two-way-audio/node_modules/hermes-estree": { - "version": "0.25.1", - "resolved": "https://registry.npmjs.org/hermes-estree/-/hermes-estree-0.25.1.tgz", - "integrity": "sha512-0wUoCcLp+5Ev5pDW2OriHC2MJCbwLwuRx+gAqMTOkGKJJiBCLjtrvy4PWUGn6MIVefecRpzoOZ/UV6iGdOr+Cw==", - "dev": true, - "license": "MIT" - }, - "packages/expo-two-way-audio/node_modules/hermes-parser": { - "version": "0.25.1", - "resolved": "https://registry.npmjs.org/hermes-parser/-/hermes-parser-0.25.1.tgz", - "integrity": "sha512-6pEjquH3rqaI6cYAXYPcz9MS4rY6R4ngRgrgfDshRptUZIc3lw0MCIJIGDj9++mfySOuPTHB4nrSW99BCvOPIA==", - "dev": true, - "license": "MIT", - "dependencies": { - "hermes-estree": "0.25.1" - } - }, - "packages/expo-two-way-audio/node_modules/https-proxy-agent": { - "version": "7.0.6", - "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", - "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "agent-base": "^7.1.2", - "debug": "4" - }, - "engines": { - "node": ">= 14" - } - }, - "packages/expo-two-way-audio/node_modules/ignore": { - "version": "7.0.5", - "resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.5.tgz", - "integrity": "sha512-Hs59xBNfUIunMFgWAbGX5cq6893IbWg4KnrjbYwX3tx0ztorVgTDA6B2sxf8ejHJ4wz8BqGUMYlnzNBer5NvGg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 4" - } - }, - "packages/expo-two-way-audio/node_modules/indent-string": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-4.0.0.tgz", - "integrity": "sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "packages/expo-two-way-audio/node_modules/jest-diff": { - "version": "30.4.1", - "resolved": "https://registry.npmjs.org/jest-diff/-/jest-diff-30.4.1.tgz", - "integrity": "sha512-CRpFK0RtLriVDGcPPAnR6HMVI8bSR2jnUIgralhauzYQZIb4RH9AtEInTuQr65LmmGggGcRT6HIASxwqsVsmlA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/diff-sequences": "30.4.0", - "@jest/get-type": "30.1.0", - "chalk": "^4.1.2", - "pretty-format": "30.4.1" - }, - "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" - } - }, - "packages/expo-two-way-audio/node_modules/jest-matcher-utils": { - "version": "30.4.1", - "resolved": "https://registry.npmjs.org/jest-matcher-utils/-/jest-matcher-utils-30.4.1.tgz", - "integrity": "sha512-zvYfX5CaeEkFrrLS9suWe9rvJrm9J1Iv3ua8kIBv9GEPzcnsfBf0bob37la7s67fs0nlBC3EuvkOLnXQKxtx4A==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/get-type": "30.1.0", - "chalk": "^4.1.2", - "jest-diff": "30.4.1", - "pretty-format": "30.4.1" - }, - "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" - } - }, - "packages/expo-two-way-audio/node_modules/log-symbols": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/log-symbols/-/log-symbols-2.2.0.tgz", - "integrity": "sha512-VeIAFslyIerEJLXHziedo2basKbMKtTw3vfn5IzG0XTjhAVEJyNHnL2p7vc+wBDSdQuUpNw3M2u6xb9QsAY5Eg==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "chalk": "^2.0.1" - }, - "engines": { - "node": ">=4" - } - }, - "packages/expo-two-way-audio/node_modules/log-symbols/node_modules/ansi-styles": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", - "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "color-convert": "^1.9.0" - }, - "engines": { - "node": ">=4" - } - }, - "packages/expo-two-way-audio/node_modules/log-symbols/node_modules/chalk": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", - "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" - }, - "engines": { - "node": ">=4" - } - }, - "packages/expo-two-way-audio/node_modules/lru-cache": { - "version": "11.5.1", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.1.tgz", - "integrity": "sha512-RPimw/7aMdv2oqRrxKwvZXcPfwBrn/JZ2xYcY9Hus/6LaS3VOAKVWKWgNLCFSiOm1ESXinjsDlidVU7JlnCN2A==", - "dev": true, - "license": "BlueOak-1.0.0", - "engines": { - "node": "20 || >=22" - } - }, - "packages/expo-two-way-audio/node_modules/metro": { - "version": "0.87.1", - "resolved": "https://registry.npmjs.org/metro/-/metro-0.87.1.tgz", - "integrity": "sha512-1oyLU9elM7hPAsKIqKooEekwxiuWr27+MZBhUROPhzcbXhMDxK64GPF/hCXwBZVp1F89ODavCrBmJtLx9WtBoQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@babel/code-frame": "^7.29.0", - "@babel/core": "^7.25.2", - "@babel/generator": "^7.29.1", - "@babel/parser": "^7.29.0", - "@babel/template": "^7.28.6", - "@babel/traverse": "^7.29.0", - "@babel/types": "^7.29.0", - "accepts": "^2.0.0", - "connect": "^3.6.5", - "debug": "^4.4.0", - "error-stack-parser": "^2.0.6", - "flow-enums-runtime": "^0.0.6", - "flow-parser": "0.331.0", - "graceful-fs": "^4.2.4", - "invariant": "^2.2.4", - "jest-worker": "^29.7.0", - "jsc-safe-url": "^0.2.2", - "lodash.throttle": "^4.1.1", - "metro-babel-transformer": "0.87.1", - "metro-cache": "0.87.1", - "metro-cache-key": "0.87.1", - "metro-config": "0.87.1", - "metro-core": "0.87.1", - "metro-file-map": "0.87.1", - "metro-resolver": "0.87.1", - "metro-runtime": "0.87.1", - "metro-source-map": "0.87.1", - "metro-symbolicate": "0.87.1", - "metro-transform-plugins": "0.87.1", - "metro-transform-worker": "0.87.1", - "mime-types": "^3.0.1", - "nullthrows": "^1.1.1", - "serialize-error": "^2.1.0", - "source-map": "^0.5.6", - "throat": "^5.0.0", - "ws": "^7.5.10", - "yargs": "^17.6.2" - }, - "bin": { - "metro": "src/cli.js" - }, - "engines": { - "node": "^22.13.0 || ^24.3.0 || >= 26.0.0" - } - }, - "packages/expo-two-way-audio/node_modules/metro-babel-transformer": { - "version": "0.87.1", - "resolved": "https://registry.npmjs.org/metro-babel-transformer/-/metro-babel-transformer-0.87.1.tgz", - "integrity": "sha512-orvRIGpb0yK1yMbk5YP3dhVKjmoxUkRB9fdltGJxNppEqus/1tFpNuf9KnGFR3Qjg0izoUrJ4z6WgoBvdkXPrA==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@babel/core": "^7.25.2", - "flow-enums-runtime": "^0.0.6", - "flow-parser": "0.331.0", - "metro-cache-key": "0.87.1", - "nullthrows": "^1.1.1" - }, - "engines": { - "node": "^22.13.0 || ^24.3.0 || >= 26.0.0" - } - }, - "packages/expo-two-way-audio/node_modules/metro-cache": { - "version": "0.87.1", - "resolved": "https://registry.npmjs.org/metro-cache/-/metro-cache-0.87.1.tgz", - "integrity": "sha512-juNPaj0Xi5tkLp8imXqvbSnEIijwKG36m7OiFFVJMqEkiURwAjkMFVek3/xpix1+LVQqO7kjVp3PvuvIM61mKQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "exponential-backoff": "^3.1.1", - "flow-enums-runtime": "^0.0.6", - "https-proxy-agent": "^7.0.5", - "metro-core": "0.87.1" - }, - "engines": { - "node": "^22.13.0 || ^24.3.0 || >= 26.0.0" - } - }, - "packages/expo-two-way-audio/node_modules/metro-cache-key": { - "version": "0.87.1", - "resolved": "https://registry.npmjs.org/metro-cache-key/-/metro-cache-key-0.87.1.tgz", - "integrity": "sha512-scqVVPMA2c+RVO12I3wyMDp5xCkRPLsyrcG4Qc3xfU5JR0EW/0sz2tjty+5UjMUtG09uiM1KYQ8HjWg7OQXHtw==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "flow-enums-runtime": "^0.0.6" - }, - "engines": { - "node": "^22.13.0 || ^24.3.0 || >= 26.0.0" - } - }, - "packages/expo-two-way-audio/node_modules/metro-config": { - "version": "0.87.1", - "resolved": "https://registry.npmjs.org/metro-config/-/metro-config-0.87.1.tgz", - "integrity": "sha512-NmkDlc/qZAdo5gTkVTuO2AKE/khemRKRH5IA+SKfqUBJigI5GqZ5TOXhmEokhlkAqzjt8dyzKhzI6FHvXoXaTQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "connect": "^3.6.5", - "flow-enums-runtime": "^0.0.6", - "jest-validate": "^29.7.0", - "metro": "0.87.1", - "metro-cache": "0.87.1", - "metro-core": "0.87.1", - "metro-runtime": "0.87.1" - }, - "engines": { - "node": "^22.13.0 || ^24.3.0 || >= 26.0.0" - } - }, - "packages/expo-two-way-audio/node_modules/metro-core": { - "version": "0.87.1", - "resolved": "https://registry.npmjs.org/metro-core/-/metro-core-0.87.1.tgz", - "integrity": "sha512-xizzky/4+c/Mkznege8OW05j7bSdM39VPoEps61Se4+hf32UQujmbvLvIE9+UnP6kNEPVomk0Fw8NsBK9iRQmw==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "flow-enums-runtime": "^0.0.6", - "lodash.throttle": "^4.1.1", - "metro-resolver": "0.87.1" - }, - "engines": { - "node": "^22.13.0 || ^24.3.0 || >= 26.0.0" - } - }, - "packages/expo-two-way-audio/node_modules/metro-file-map": { - "version": "0.87.1", - "resolved": "https://registry.npmjs.org/metro-file-map/-/metro-file-map-0.87.1.tgz", - "integrity": "sha512-9sPuNCojC3pS4vj+ZPY7FXmHGpdJeckXuKXQrDAfJvZc60AF8owRFTkI8XdwlwrmPIB2w++KraK9FMEXvC4wJw==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "debug": "^4.4.0", - "fb-watchman": "^2.0.0", - "flow-enums-runtime": "^0.0.6", - "graceful-fs": "^4.2.4", - "invariant": "^2.2.4", - "jest-worker": "^29.7.0", - "micromatch": "^4.0.4", - "nullthrows": "^1.1.1" - }, - "engines": { - "node": "^22.13.0 || ^24.3.0 || >= 26.0.0" - } - }, - "packages/expo-two-way-audio/node_modules/metro-minify-terser": { - "version": "0.87.1", - "resolved": "https://registry.npmjs.org/metro-minify-terser/-/metro-minify-terser-0.87.1.tgz", - "integrity": "sha512-YK4k1oO1wV48hfE+Nbw2rJCnAgeabzrgT/xH5ha5n9gbK4p3HYFC898cERUiyTl9vRh58CNTiXRc88f7y6PfKg==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "flow-enums-runtime": "^0.0.6", - "terser": "^5.15.0" - }, - "engines": { - "node": "^22.13.0 || ^24.3.0 || >= 26.0.0" - } - }, - "packages/expo-two-way-audio/node_modules/metro-resolver": { - "version": "0.87.1", - "resolved": "https://registry.npmjs.org/metro-resolver/-/metro-resolver-0.87.1.tgz", - "integrity": "sha512-FXH/brY69wT6sPxaSW8BhMmDGD/6irmBr/cL4rUi+VWwqR3pbvdcfUOfyjcHucgQ7pe5IW3xJY21eHKLVKNumQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "flow-enums-runtime": "^0.0.6" - }, - "engines": { - "node": "^22.13.0 || ^24.3.0 || >= 26.0.0" - } - }, - "packages/expo-two-way-audio/node_modules/metro-runtime": { - "version": "0.87.1", - "resolved": "https://registry.npmjs.org/metro-runtime/-/metro-runtime-0.87.1.tgz", - "integrity": "sha512-kjeuSvInsM6OzBjkCQsWxnkrKZFMKtnkCl38oXWRI9lDGs2L9hGs9Tak9sQYJ9h3gtDujneB7wZio+irgqJKDw==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@babel/runtime": "^7.25.0", - "flow-enums-runtime": "^0.0.6" - }, - "engines": { - "node": "^22.13.0 || ^24.3.0 || >= 26.0.0" - } - }, - "packages/expo-two-way-audio/node_modules/metro-source-map": { - "version": "0.87.1", - "resolved": "https://registry.npmjs.org/metro-source-map/-/metro-source-map-0.87.1.tgz", - "integrity": "sha512-Bqpm0PBGdy53pigIJb4HRF7QxD2pUOdgSmVh/4AWbP635kSCv+Y6ltVxUZgSnzS/QbSmzyCGijmRPlXMj2/qHw==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@babel/traverse": "^7.29.0", - "@babel/types": "^7.29.0", - "flow-enums-runtime": "^0.0.6", - "invariant": "^2.2.4", - "metro-symbolicate": "0.87.1", - "nullthrows": "^1.1.1", - "ob1": "0.87.1", - "source-map": "^0.5.6", - "vlq": "^1.0.0" - }, - "engines": { - "node": "^22.13.0 || ^24.3.0 || >= 26.0.0" - } - }, - "packages/expo-two-way-audio/node_modules/metro-symbolicate": { - "version": "0.87.1", - "resolved": "https://registry.npmjs.org/metro-symbolicate/-/metro-symbolicate-0.87.1.tgz", - "integrity": "sha512-rcGvwabrg0lbXGRGRKl14PY3My3+dkno2jZYhdJEuH2DmjTtTkV5bYwgto4JtV/Lbe+sXE6GO1UGg654430uow==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "flow-enums-runtime": "^0.0.6", - "invariant": "^2.2.4", - "metro-source-map": "0.87.1", - "nullthrows": "^1.1.1", - "source-map": "^0.5.6", - "vlq": "^1.0.0" - }, - "bin": { - "metro-symbolicate": "src/index.js" - }, - "engines": { - "node": "^22.13.0 || ^24.3.0 || >= 26.0.0" - } - }, - "packages/expo-two-way-audio/node_modules/metro-transform-plugins": { - "version": "0.87.1", - "resolved": "https://registry.npmjs.org/metro-transform-plugins/-/metro-transform-plugins-0.87.1.tgz", - "integrity": "sha512-qMiJ/x+VfqumFJJSefKS6nj8uojzC29b2/aK8vlMuFABIqGjDucICEOXd2Yt6k/XMFAgAcaJvShUOT0HLyYaPw==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@babel/core": "^7.25.2", - "@babel/generator": "^7.29.1", - "@babel/template": "^7.28.6", - "@babel/traverse": "^7.29.0", - "flow-enums-runtime": "^0.0.6", - "nullthrows": "^1.1.1" - }, - "engines": { - "node": "^22.13.0 || ^24.3.0 || >= 26.0.0" - } - }, - "packages/expo-two-way-audio/node_modules/metro-transform-worker": { - "version": "0.87.1", - "resolved": "https://registry.npmjs.org/metro-transform-worker/-/metro-transform-worker-0.87.1.tgz", - "integrity": "sha512-VOzs3OV405FuOLYdAhqA2wsn1F9lvueDVxMDLvCKaQ44U+yknIqphJ9eMjjsGwLDZiJq9sW3DMLhjD27JxQgqQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@babel/core": "^7.25.2", - "@babel/generator": "^7.29.1", - "@babel/parser": "^7.29.0", - "@babel/types": "^7.29.0", - "flow-enums-runtime": "^0.0.6", - "metro": "0.87.1", - "metro-babel-transformer": "0.87.1", - "metro-cache": "0.87.1", - "metro-cache-key": "0.87.1", - "metro-minify-terser": "0.87.1", - "metro-source-map": "0.87.1", - "metro-transform-plugins": "0.87.1", - "nullthrows": "^1.1.1" - }, - "engines": { - "node": "^22.13.0 || ^24.3.0 || >= 26.0.0" - } - }, - "packages/expo-two-way-audio/node_modules/metro/node_modules/accepts": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz", - "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "mime-types": "^3.0.0", - "negotiator": "^1.0.0" - }, - "engines": { - "node": ">= 0.6" - } - }, - "packages/expo-two-way-audio/node_modules/metro/node_modules/ws": { - "version": "7.5.13", - "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.13.tgz", - "integrity": "sha512-rsKI6xDBFVf4r/x8XyChGK04QR/XHroxs/jUcoWvtEZM8TPU/X/uIY9B1CsSzYws9ZJb/6bbBu7dPhFW00CAoA==", - "dev": true, - "license": "MIT", - "peer": true, - "engines": { - "node": ">=8.3.0" - }, - "peerDependencies": { - "bufferutil": "^4.0.1", - "utf-8-validate": "^5.0.2" - }, - "peerDependenciesMeta": { - "bufferutil": { - "optional": true - }, - "utf-8-validate": { - "optional": true - } - } - }, - "packages/expo-two-way-audio/node_modules/mime-types": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz", - "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "mime-db": "^1.54.0" - }, - "engines": { - "node": ">=18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "packages/expo-two-way-audio/node_modules/mimic-fn": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-1.2.0.tgz", - "integrity": "sha512-jf84uxzwiuiIVKiOLpfYk7N46TSy8ubTonmneY9vrpHNAnp0QBt2BxWV9dO3/j+BoVAb+a5G6YDPW3M5HOdMWQ==", - "dev": true, - "license": "MIT", - "peer": true, - "engines": { - "node": ">=4" - } - }, - "packages/expo-two-way-audio/node_modules/minimatch": { - "version": "10.2.5", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.5.tgz", - "integrity": "sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==", - "dev": true, - "license": "BlueOak-1.0.0", - "dependencies": { - "brace-expansion": "^5.0.5" - }, - "engines": { - "node": "18 || 20 || >=22" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "packages/expo-two-way-audio/node_modules/negotiator": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.1.0.tgz", - "integrity": "sha512-NMPBRMJgiQHjbd8phG3Vebdx4kZ1H121rbl5IkMqeOsahptB9BKo/d7oJ3zTXqTgagn2bWlNSXkh0QUGM31RYg==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "content-type": "^2.1.0" - }, - "engines": { - "node": ">=18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "packages/expo-two-way-audio/node_modules/node-forge": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/node-forge/-/node-forge-1.4.0.tgz", - "integrity": "sha512-LarFH0+6VfriEhqMMcLX2F7SwSXeWwnEAJEsYm5QKWchiVYVvJyV9v7UDvUv+w5HO23ZpQTXDv/GxdDdMyOuoQ==", - "dev": true, - "license": "(BSD-3-Clause OR GPL-2.0)", - "peer": true, - "engines": { - "node": ">= 6.13.0" - } - }, - "packages/expo-two-way-audio/node_modules/ob1": { - "version": "0.87.1", - "resolved": "https://registry.npmjs.org/ob1/-/ob1-0.87.1.tgz", - "integrity": "sha512-i8iA8uij0g1YQzS8uOJPSRCgwDjO9warIHUAu1Fqj877Wc3wlfxDYBioYWgKTBF2+URVJttyDWSEpmd99nlvtQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "flow-enums-runtime": "^0.0.6" - }, - "engines": { - "node": "^22.13.0 || ^24.3.0 || >= 26.0.0" - } - }, - "packages/expo-two-way-audio/node_modules/onetime": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/onetime/-/onetime-2.0.1.tgz", - "integrity": "sha512-oyyPpiMaKARvvcgip+JV+7zci5L8D1W9RZIz2l1o08AM3pfspitVWnPt3mzHcBPp12oYMTy0pqrFs/C+m3EwsQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "mimic-fn": "^1.0.0" - }, - "engines": { - "node": ">=4" - } - }, - "packages/expo-two-way-audio/node_modules/open": { - "version": "8.4.2", - "resolved": "https://registry.npmjs.org/open/-/open-8.4.2.tgz", - "integrity": "sha512-7x81NCL719oNbsq/3mh+hVrAWmFuEYUqrq/Iw3kUzH8ReypT9QQ0BLoJS7/G9k6N81XjW4qHWtjWwe/9eLy1EQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "define-lazy-prop": "^2.0.0", - "is-docker": "^2.1.1", - "is-wsl": "^2.2.0" - }, - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "packages/expo-two-way-audio/node_modules/ora": { - "version": "3.4.0", - "resolved": "https://registry.npmjs.org/ora/-/ora-3.4.0.tgz", - "integrity": "sha512-eNwHudNbO1folBP3JsZ19v9azXWtQZjICdr3Q0TDPIaeBQ3mXLrh54wM+er0+hSp+dWKf+Z8KM58CYzEyIYxYg==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "chalk": "^2.4.2", - "cli-cursor": "^2.1.0", - "cli-spinners": "^2.0.0", - "log-symbols": "^2.2.0", - "strip-ansi": "^5.2.0", - "wcwidth": "^1.0.1" - }, - "engines": { - "node": ">=6" - } - }, - "packages/expo-two-way-audio/node_modules/ora/node_modules/ansi-styles": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", - "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "color-convert": "^1.9.0" - }, - "engines": { - "node": ">=4" - } - }, - "packages/expo-two-way-audio/node_modules/ora/node_modules/chalk": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", - "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" - }, - "engines": { - "node": ">=4" - } - }, - "packages/expo-two-way-audio/node_modules/path-scurry": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-2.0.2.tgz", - "integrity": "sha512-3O/iVVsJAPsOnpwWIeD+d6z/7PmqApyQePUtCndjatj/9I5LylHvt5qluFaBT3I5h3r1ejfR056c+FCv+NnNXg==", - "dev": true, - "license": "BlueOak-1.0.0", - "dependencies": { - "lru-cache": "^11.0.0", - "minipass": "^7.1.2" - }, - "engines": { - "node": "18 || 20 || >=22" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "packages/expo-two-way-audio/node_modules/pretty-format": { - "version": "30.4.1", - "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-30.4.1.tgz", - "integrity": "sha512-K6KiKMHTL4jjX4u3Kir2EW07nRfcqVTXIImx50wbjHQTcZPgg+gjVeNTIT3l3L1Rd4UefxfogquC9J37SoFyyw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/schemas": "30.4.1", - "ansi-styles": "^5.2.0", - "react-is-18": "npm:react-is@^18.3.1", - "react-is-19": "npm:react-is@^19.2.5" - }, - "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" - } - }, "packages/expo-two-way-audio/node_modules/react": { "version": "19.3.1", "resolved": "https://registry.npmjs.org/react/-/react-19.3.1.tgz", @@ -41893,205 +40078,9 @@ "node": ">=0.10.0" } }, - "packages/expo-two-way-audio/node_modules/react-refresh": { - "version": "0.14.2", - "resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.14.2.tgz", - "integrity": "sha512-jCvmsr+1IUSMUyzOkRcvnVbX3ZYC6g9TDrDbFuFmRDq7PD4yaGbLKNQL6k2jnArV8hjYxh7hVhAZB6s9HDGpZA==", - "dev": true, - "license": "MIT", - "peer": true, - "engines": { - "node": ">=0.10.0" - } - }, - "packages/expo-two-way-audio/node_modules/react-test-renderer": { - "version": "19.1.0", - "resolved": "https://registry.npmjs.org/react-test-renderer/-/react-test-renderer-19.1.0.tgz", - "integrity": "sha512-jXkSl3CpvPYEF+p/eGDLB4sPoDX8pKkYvRl9+rR8HxLY0X04vW7hCm1/0zHoUSjPZ3bDa+wXWNTDVIw/R8aDVw==", - "dev": true, - "license": "MIT", - "dependencies": { - "react-is": "^19.1.0", - "scheduler": "^0.26.0" - }, - "peerDependencies": { - "react": "^19.1.0" - } - }, - "packages/expo-two-way-audio/node_modules/redent": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/redent/-/redent-3.0.0.tgz", - "integrity": "sha512-6tDA8g98We0zd0GvVeMT9arEOnTw9qM03L9cJXaCjrip1OO764RDBLBfrB4cwzNGDj5OA5ioymC9GkizgWJDUg==", - "dev": true, - "license": "MIT", - "dependencies": { - "indent-string": "^4.0.0", - "strip-indent": "^3.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "packages/expo-two-way-audio/node_modules/restore-cursor": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-2.0.0.tgz", - "integrity": "sha512-6IzJLuGi4+R14vwagDHX+JrXmPVtPpn4mffDJ1UdR7/Edm87fl6yi8mMBIVvFtJaNTUvjughmW4hwLhRG7gC1Q==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "onetime": "^2.0.0", - "signal-exit": "^3.0.2" - }, - "engines": { - "node": ">=4" - } - }, - "packages/expo-two-way-audio/node_modules/signal-exit": { - "version": "3.0.7", - "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", - "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", - "dev": true, - "license": "ISC", - "peer": true - }, - "packages/expo-two-way-audio/node_modules/slash": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", - "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "packages/expo-two-way-audio/node_modules/source-map": { - "version": "0.5.7", - "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", - "integrity": "sha512-LbrmJOMUSdEVxIKvdcJzQC+nQhe8FUZQTXQy6+I75skNgn3OoQ0DZA8YnFa7gp8tqtL3KPf1kmo0R5DoApeSGQ==", - "dev": true, - "license": "BSD-3-Clause", - "peer": true, - "engines": { - "node": ">=0.10.0" - } - }, - "packages/expo-two-way-audio/node_modules/strip-ansi": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", - "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "ansi-regex": "^4.1.0" - }, - "engines": { - "node": ">=6" - } - }, - "packages/expo-two-way-audio/node_modules/strip-ansi/node_modules/ansi-regex": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.1.tgz", - "integrity": "sha512-ILlv4k/3f6vfQ4OoP2AGvirOktlQ98ZEL1k9FaQjxa3L1abBgbuTDAdPOpvbGncC0BTVQrl+OM8xZGK6tWXt7g==", - "dev": true, - "license": "MIT", - "peer": true, - "engines": { - "node": ">=6" - } - }, - "packages/expo-two-way-audio/node_modules/strip-indent": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/strip-indent/-/strip-indent-3.0.0.tgz", - "integrity": "sha512-laJTa3Jb+VQpaC6DseHhF7dXVqHTfJPCRDaEbid/drOhgitgYku/letMUqOXFoWV0zIIUbjpdH2t+tYj4bQMRQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "min-indent": "^1.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "packages/expo-two-way-audio/node_modules/sucrase": { - "version": "3.35.1", - "resolved": "https://registry.npmjs.org/sucrase/-/sucrase-3.35.1.tgz", - "integrity": "sha512-DhuTmvZWux4H1UOnWMB3sk0sbaCVOoQZjv8u1rDoTV0HTdGem9hkAZtl4JZy8P2z4Bg0nT+YMeOFyVr4zcG5Tw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/gen-mapping": "^0.3.2", - "commander": "^4.0.0", - "lines-and-columns": "^1.1.6", - "mz": "^2.7.0", - "pirates": "^4.0.1", - "tinyglobby": "^0.2.11", - "ts-interface-checker": "^0.1.9" - }, - "bin": { - "sucrase": "bin/sucrase", - "sucrase-node": "bin/sucrase-node" - }, - "engines": { - "node": ">=16 || 14 >=14.17" - } - }, - "packages/expo-two-way-audio/node_modules/sucrase/node_modules/commander": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/commander/-/commander-4.1.1.tgz", - "integrity": "sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 6" - } - }, - "packages/expo-two-way-audio/node_modules/supports-color": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", - "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "has-flag": "^3.0.0" - }, - "engines": { - "node": ">=4" - } - }, - "packages/expo-two-way-audio/node_modules/whatwg-url-minimum": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/whatwg-url-minimum/-/whatwg-url-minimum-0.2.0.tgz", - "integrity": "sha512-BtjXU1caNcCFfETP2DhqSeVPfRDl2MTUitI107RE34rJXjR/izfUtR5IoTFOK1WqjNLXbbeqaCH/mQAOLjpc8g==", - "dev": true, - "license": "MIT", - "peer": true - }, - "packages/expo-two-way-audio/node_modules/xmlbuilder": { - "version": "15.1.1", - "resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-15.1.1.tgz", - "integrity": "sha512-yMqGBqtXyeN1e3TGYvgNgDVZ3j84W4cwkOXQswghol6APgZWaff9lnbvN7MHYJOiXsvGPXtjTYJEiC9J2wv9Eg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8.0" - } - }, - "packages/expo-two-way-audio/node_modules/zod": { - "version": "3.25.76", - "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz", - "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==", - "dev": true, - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/colinhacks" - } - }, "packages/highlight": { "name": "@getpaseo/highlight", - "version": "0.13.2", + "version": "0.15.0-beta.1", "dependencies": { "@codemirror/language": "6.12.4", "@codemirror/legacy-modes": "^6.5.3", @@ -42120,15 +40109,15 @@ }, "packages/plugin": { "name": "@getpaseo/plugin", - "version": "0.13.2", + "version": "0.15.0-beta.1", "dependencies": { "@agentclientprotocol/sdk": "^1.4.0", "i18next": "^26.3.0", "use-sync-external-store": "^1.6.0" }, "devDependencies": { - "@getpaseo/client": "0.13.2", - "@getpaseo/protocol": "0.13.2", + "@getpaseo/client": "0.15.0-beta.1", + "@getpaseo/protocol": "0.15.0-beta.1", "@types/node": "^20.9.0", "@types/react": "~19.2.0", "react": "19.2.3", @@ -42138,8 +40127,8 @@ "zod": "^4.4.3" }, "peerDependencies": { - "@getpaseo/client": "0.13.2", - "@getpaseo/protocol": "0.13.2", + "@getpaseo/client": "0.15.0-beta.1", + "@getpaseo/protocol": "0.15.0-beta.1", "react": ">=19.1.0 <20", "react-native": ">=0.81.5", "zod": "^4.4.3" @@ -42161,7 +40150,7 @@ }, "packages/protocol": { "name": "@getpaseo/protocol", - "version": "0.13.2", + "version": "0.15.0-beta.1", "dependencies": { "semver": "^7.8.5", "zod": "^4.4.3" @@ -42188,7 +40177,7 @@ }, "packages/relay": { "name": "@getpaseo/relay", - "version": "0.13.2", + "version": "0.15.0-beta.1", "dependencies": { "@noble/ciphers": "^2.4.0", "@noble/curves": "^2.4.0", @@ -42409,21 +40398,23 @@ }, "packages/server": { "name": "@getpaseo/server", - "version": "0.13.2", + "version": "0.15.0-beta.1", "dependencies": { "@agentclientprotocol/sdk": "^0.17.1", "@anthropic-ai/claude-agent-sdk": "0.3.246", "@anthropic-ai/sdk": "^0.104.2", - "@getpaseo/client": "0.13.2", - "@getpaseo/highlight": "0.13.2", - "@getpaseo/plugin": "0.13.2", - "@getpaseo/protocol": "0.13.2", - "@getpaseo/relay": "0.13.2", + "@getpaseo/client": "0.15.0-beta.1", + "@getpaseo/highlight": "0.15.0-beta.1", + "@getpaseo/plugin": "0.15.0-beta.1", + "@getpaseo/protocol": "0.15.0-beta.1", + "@getpaseo/relay": "0.15.0-beta.1", "@isaacs/ttlcache": "^2.1.4", "@modelcontextprotocol/sdk": "1.29.0", "@opencode-ai/sdk": "1.14.46", "@opencode/client": "2.0.10", - "@xterm/headless": "^6.0.0", + "@xterm/addon-serialize": "0.14.0", + "@xterm/addon-unicode-graphemes": "0.5.0-beta.330", + "@xterm/headless": "6.1.0-beta.334", "ai": "5.0.78", "ajv": "^8.20.0", "bcryptjs": "^3.0.3", @@ -42431,6 +40422,7 @@ "esbuild": "^0.25.12", "express": "^4.18.2", "fast-deep-equal": "^3.1.3", + "https-proxy-agent": "^7.0.6", "lru-cache": "^11.5.1", "markdown-it": "^10.0.0", "mnemonic-id": "^3.2.7", @@ -42448,6 +40440,7 @@ "strip-ansi": "^7.1.2", "tree-kill": "^1.2.2", "typescript": "^5.9.3", + "undici": "^7.24.8", "uuid": "^9.0.1", "which": "^5.0.0", "ws": "^8.14.2", @@ -43021,6 +41014,15 @@ "url": "https://opencollective.com/vitest" } }, + "packages/server/node_modules/agent-base": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", + "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", + "license": "MIT", + "engines": { + "node": ">= 14" + } + }, "packages/server/node_modules/ajv": { "version": "8.20.0", "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz", @@ -43090,6 +41092,19 @@ "@esbuild/win32-x64": "0.25.12" } }, + "packages/server/node_modules/https-proxy-agent": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", + "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.2", + "debug": "4" + }, + "engines": { + "node": ">= 14" + } + }, "packages/server/node_modules/isexe": { "version": "3.1.5", "resolved": "https://registry.npmjs.org/isexe/-/isexe-3.1.5.tgz", @@ -43339,7 +41354,7 @@ }, "packages/website": { "name": "@getpaseo/website", - "version": "0.13.2", + "version": "0.15.0-beta.1", "dependencies": { "@cloudflare/vite-plugin": "^1.29.1", "@cloudflare/workers-types": "^4.20260317.1", @@ -44949,7 +42964,7 @@ }, "plugins": { "name": "@getpaseo/builtin-plugins", - "version": "0.13.2", + "version": "0.15.0-beta.1", "dependencies": { "@getpaseo/plugin": "*", "zod": "^4.4.3" diff --git a/package.json b/package.json index beeff7c613..cbcb507539 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "paseo", - "version": "0.13.2", + "version": "0.15.0-beta.1", "private": true, "description": "Paseo: voice-controlled development environment for local AI coding agents", "keywords": [ @@ -131,6 +131,7 @@ "concurrently": "^9.2.1", "cross-env": "^10.1.0", "electron": "44.2.0", + "expo-module-scripts": "^5.0.8", "get-port-cli": "^3.0.0", "js-yaml": "^4.1.1", "knip": "^5.82.1", diff --git a/packages/app/.eas/workflows/release-mobile.yml b/packages/app/.eas/workflows/release-mobile.yml index 26790ef22f..e57260898c 100644 --- a/packages/app/.eas/workflows/release-mobile.yml +++ b/packages/app/.eas/workflows/release-mobile.yml @@ -42,6 +42,20 @@ jobs: build_id: ${{ needs.build_android.outputs.build_id }} profile: production + upload_android_screenshots: + name: Upload Google Play screenshots + needs: [build_android, submit_android] + environment: production + runs_on: macos-medium + steps: + - uses: eas/checkout + - name: Install fastlane + run: bundle install + - name: Upload screenshots + run: | + export ANDROID_VERSION_CODE="${{ needs.build_android.outputs.app_build_version }}" + bundle exec fastlane android upload_screenshots + submit_ios_for_review: name: Submit iOS for App Store review needs: [build_ios, distribute_ios] diff --git a/packages/app/.eas/workflows/upload-android-screenshots.yml b/packages/app/.eas/workflows/upload-android-screenshots.yml new file mode 100644 index 0000000000..dbd2fdddca --- /dev/null +++ b/packages/app/.eas/workflows/upload-android-screenshots.yml @@ -0,0 +1,27 @@ +name: Upload Google Play screenshots + +# Standalone re-trigger for the release workflow's Google Play screenshot step. +# Replaces the en-US phone and tablet screenshots with the committed renders, +# without rebuilding or resubmitting the app. + +on: + workflow_dispatch: + inputs: + android_version_code: + type: string + required: false + description: "versionCode of the production release to attach the change to, e.g. 14000. Leave empty when the production track has a single release." + +jobs: + upload_android_screenshots: + name: Upload Google Play screenshots + environment: production + runs_on: macos-medium + steps: + - uses: eas/checkout + - name: Install fastlane + run: bundle install + - name: Upload screenshots + run: | + export ANDROID_VERSION_CODE="${{ inputs.android_version_code }}" + bundle exec fastlane android upload_screenshots diff --git a/packages/app/app.config.js b/packages/app/app.config.js index 7ddfc95029..eb7907e5ce 100644 --- a/packages/app/app.config.js +++ b/packages/app/app.config.js @@ -102,7 +102,7 @@ export default { name: variant.name, slug: "voice-mobile", version: nativeReleaseVersion.appVersion, - orientation: "portrait", + orientation: "default", icon: "./assets/images/icon.png", scheme: "paseo", userInterfaceStyle: "automatic", diff --git a/packages/app/app.config.test.ts b/packages/app/app.config.test.ts index b98258ff9a..d0de16bd03 100644 --- a/packages/app/app.config.test.ts +++ b/packages/app/app.config.test.ts @@ -59,3 +59,38 @@ describe("Android app config", () => { 30_000, ); }); + +it("follows system rotation on Android", async () => { + const manifest = await resolveAndroidManifest(); + const activity = manifest.application[0].activity.find( + (entry: ManifestEntry) => entry.$["android:name"] === ".MainActivity", + ); + expect(activity.$["android:screenOrientation"]).toBe("unspecified"); +}, 30_000); + +it("allows all orientations on iPhone and iPad", async () => { + const { mkdtemp, rm } = await import("node:fs/promises"); + const { tmpdir } = await import("node:os"); + const { join } = await import("node:path"); + const root = await mkdtemp(join(tmpdir(), "paseo-ios-config-")); + try { + const { exp } = await getPrebuildConfigAsync(__dirname, { platforms: ["ios"] }); + await compileModsAsync(exp, { + projectRoot: root, + introspect: true, + platforms: ["ios"], + assertMissingModProviders: false, + }); + const plist = exp._internal.modResults.ios.infoPlist; + const orientations = [ + "UIInterfaceOrientationPortrait", + "UIInterfaceOrientationPortraitUpsideDown", + "UIInterfaceOrientationLandscapeLeft", + "UIInterfaceOrientationLandscapeRight", + ]; + expect(plist.UISupportedInterfaceOrientations).toEqual(orientations); + expect(plist["UISupportedInterfaceOrientations~ipad"]).toEqual(orientations); + } finally { + await rm(root, { recursive: true, force: true }); + } +}, 30_000); diff --git a/packages/app/e2e/browser/agent-message-submission.spec.ts b/packages/app/e2e/browser/agent-message-submission.spec.ts index 0009188b34..dcf872f8be 100644 --- a/packages/app/e2e/browser/agent-message-submission.spec.ts +++ b/packages/app/e2e/browser/agent-message-submission.spec.ts @@ -53,6 +53,7 @@ import { import { expectInFlightForkAvailable } from "../support/helpers/assistant-fork"; import { scrollTimelineToNewestLoadedEdge, + userScrollsTimelineToHistoryStart, scrollTimelineUntilOlderHistoryIsReachable, } from "../support/helpers/timeline-pagination"; import { @@ -986,7 +987,7 @@ test.describe("Agent message submission", () => { } }); - test("keeps one prompt when its provider echo crosses the bounded tail", async ({ + test("keeps one prompt when a delayed provider echo belongs to a large whole turn", async ({ page, }, testInfo) => { const workspace = await seedWorkspace({ @@ -1003,8 +1004,10 @@ test.describe("Agent message submission", () => { await expectVisibleAgentSurfacesIdle(page); await page.reload(); - await expect(submittedPrompt).toHaveCount(0); - await scrollTimelineUntilOlderHistoryIsReachable(page, prompt); + // The complete turn arrives on reload; scrolling mounts its oldest rows + // without requiring another page or an increase in total content height. + await userScrollsTimelineToHistoryStart(page); + await expect(submittedPrompt).toBeVisible(); await expect(submittedPrompt).toHaveCount(1); await expect(submittedPrompt).toHaveAttribute("aria-busy", "false"); } finally { diff --git a/packages/app/e2e/browser/agent-timeline-pagination.spec.ts b/packages/app/e2e/browser/agent-timeline-pagination.spec.ts index f2772b0b1b..57ee050fa4 100644 --- a/packages/app/e2e/browser/agent-timeline-pagination.spec.ts +++ b/packages/app/e2e/browser/agent-timeline-pagination.spec.ts @@ -27,6 +27,10 @@ import { seedRealisticOlderTimeline, sendLiveTurnBeforeHydration, expectTimelineViewportAnchoredAfterPrepend, + expectToolCallGroupPositionPreserved, + rememberToolCallGroupPosition, + seedItemPagedToolGroupTimeline, + useChatDisplay, userNavigatesTimelineToHistoryStartWithKeyboard, userScrollsTimelineToHistoryStart, } from "../support/helpers/timeline-pagination"; @@ -100,6 +104,32 @@ test.describe("Agent timeline pagination", () => { } }); + // Hosts paged by items can end a page inside a tool run. The older page extends the group + // the reader is on, which changes the row hosting it; the reader must stay with that group + // rather than land at history start and drain every older page. + test("keeps the reading position when an older item page extends the tool-call group being read", async ({ + page, + }) => { + test.setTimeout(120_000); + await useChatDisplay(page, "collapseToolCalls"); + const agent = await seedItemPagedToolGroupTimeline(); + try { + const history = await holdOlderHistoryPages(page, agent, { itemPagedHost: true }); + await openAgentTimeline(page, agent); + await expectTimelinePromptVisible(page, agent.newestPrompt); + + await userScrollsTimelineToHistoryStart(page); + await history.expectRequestedPages(1); + const reading = await rememberToolCallGroupPosition(page, agent.loadedCommands); + + history.releasePage(1); + await expectToolCallGroupPositionPreserved(page, agent.totalCommands, reading); + await history.expectSettledWithRequestedPages(1); + } finally { + await agent.cleanup(); + } + }); + test("loads older history when the user navigates to history start with the keyboard", async ({ page, }) => { diff --git a/packages/app/e2e/browser/assistant-file-link-tooltip.spec.ts b/packages/app/e2e/browser/assistant-file-link-tooltip.spec.ts index 69cccc52dd..09a9434995 100644 --- a/packages/app/e2e/browser/assistant-file-link-tooltip.spec.ts +++ b/packages/app/e2e/browser/assistant-file-link-tooltip.spec.ts @@ -1,4 +1,5 @@ -import { writeFile } from "node:fs/promises"; +import { execFileSync } from "node:child_process"; +import { mkdir, writeFile } from "node:fs/promises"; import path from "node:path"; import { test, expect, type Page } from "../support/fixtures"; import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent"; @@ -67,3 +68,54 @@ test("opening an assistant file link dismisses its tooltip over the file tab", a await agent.cleanup(); } }); + +async function readLinkedGuide(page: Page, linkName: string, content: string): Promise { + await page.getByRole("link", { name: linkName, exact: true }).click(); + await expect(page.getByTestId("markdown-preview-frame").filter({ visible: true })).toContainText( + content, + ); +} + +async function returnToNestedLinks(page: Page): Promise { + await page.getByRole("button", { name: "Nested file links", exact: true }).click(); + await expect(page.getByRole("link", { name: "nested guide", exact: true })).toBeVisible(); +} + +test("assistant directory paths find nested files and preserve exact workspace paths", async ({ + page, +}, testInfo) => { + testInfo.setTimeout(120_000); + const agent = await seedMockAgentWorkspace({ + repoPrefix: "nested-file-link-", + title: "Nested file links", + featureValues: { + mockStreamingAssistantResponse: + "Read [nested guide](schema/x.md), [exact guide](schema/exact.md), and [missing guide](schema/missing.md).", + mockStreamingAssistantIntervalMs: 5, + }, + }); + try { + await mkdir(path.join(agent.cwd, "repo-a/schema"), { recursive: true }); + execFileSync("git", ["init", "-b", "main"], { cwd: path.join(agent.cwd, "repo-a") }); + await writeFile( + path.join(agent.cwd, "repo-a/schema/x.md"), + "# Nested file content\n\nDetails\n", + ); + await mkdir(path.join(agent.cwd, "schema"), { recursive: true }); + await writeFile(path.join(agent.cwd, "schema/exact.md"), "# Exact file content\n"); + await writeFile(path.join(agent.cwd, "repo-a/schema/exact.md"), "# Wrong nested content\n"); + await openAgentRoute(page, agent); + await agent.client.sendAgentMessage(agent.agentId, "Show the file links."); + await agent.client.waitForFinish(agent.agentId, 30_000); + + await expect(page.getByRole("textbox", { name: "Message agent..." }).first()).toBeEnabled(); + await readLinkedGuide(page, "nested guide", "Nested file content"); + await returnToNestedLinks(page); + await readLinkedGuide(page, "exact guide", "Exact file content"); + await returnToNestedLinks(page); + await page.getByRole("link", { name: "missing guide", exact: true }).click(); + await expect(page.getByText("File not found", { exact: true })).toBeVisible(); + } finally { + await agent.cleanup(); + } +}); diff --git a/packages/app/e2e/browser/compact-workspace-sheet.spec.ts b/packages/app/e2e/browser/compact-workspace-sheet.spec.ts index 77d995eda7..5b68663862 100644 --- a/packages/app/e2e/browser/compact-workspace-sheet.spec.ts +++ b/packages/app/e2e/browser/compact-workspace-sheet.spec.ts @@ -5,12 +5,16 @@ import { expectComposerVisible } from "../support/helpers/composer"; import { installDaemonWebSocketGate } from "../support/helpers/daemon-websocket-gate"; import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent"; import { + expectSubagentRowGone, expectSubagentRowVisible, openSubagentFromCompactTrack, seedSubagent, } from "../support/helpers/subagents"; import { + backToList, closeSheet, + expectNoSheetOpen, + expectOneSheetOpen, expectOpenTabCount, openSheetAsTab, expectDeclinedDiscardPrompt, @@ -52,6 +56,10 @@ test("compact opens files and subagents in a sheet, leaving the tabs for agents" { client: workspace.client, repoPath: workspace.cwd, workspaceId: workspace.workspaceId }, { parentId: workspace.agentId, title: "Sheet child" }, ); + const grandchild = await seedSubagent( + { client: workspace.client, repoPath: workspace.cwd, workspaceId: workspace.workspaceId }, + { parentId: child.id, title: "Sheet grandchild" }, + ); await openAgentRoute(page, { workspaceId: workspace.workspaceId, agentId: workspace.agentId }); await expectOpenTabCount(page, 1); @@ -79,12 +87,14 @@ test("compact opens files and subagents in a sheet, leaving the tabs for agents" await tapSheetBackdrop(page); }); - await test.step("a subagent opens in a sheet over the subagents list", async () => { + await test.step("a subagent opens in place of the subagents list", async () => { await openSubagentFromCompactTrack(page, child.id); const childSheet = sheet(page, child.title); await expect(childSheet).toBeVisible(); await expectSheetAtSnap(page, child.title); + await expectSubagentRowGone(page, child.id); + await expectOneSheetOpen(page); await expect(childSheet.getByRole("textbox", { name: "Message agent..." })).toHaveCount(0); // The composer's model, thinking, and mode stand in for it, resolved the same way. An idle // seeded agent has no context usage yet. @@ -94,23 +104,51 @@ test("compact opens files and subagents in a sheet, leaving the tabs for agents" await expectOpenTabCount(page, 1); }); - await test.step("closing the subagent's sheet uncovers the list", async () => { - await closeSheet(page, child.title); + await test.step("Back returns the sheet to the list", async () => { + await backToList(page, child.title); await expectSubagentRowVisible(page, child.id); + await expectOneSheetOpen(page); + }); + + await test.step("Close closes the list with the subagent", async () => { + await page.getByTestId(`subagents-track-row-${child.id}`).click(); + await closeSheet(page, child.title); + await expectSubagentRowGone(page, child.id); + await expectNoSheetOpen(page); }); await test.step("the parent box in a subagent's sheet closes it onto the parent", async () => { - await page.getByTestId(`subagents-track-row-${child.id}`).click(); + await openSubagentFromCompactTrack(page, child.id); const childSheet = sheet(page, child.title); await expectSheetAtSnap(page, child.title); await expect(childSheet.getByTestId("composer-parent-agent-pill")).toHaveCount(0); await childSheet.getByTestId("parent-agent-callout-open").click(); await expect(childSheet).toHaveCount(0); + await expectNoSheetOpen(page); + await expectOpenTabCount(page, 1); + }); + + await test.step("a nested subagent's parent box lands on its parent's sheet", async () => { + await openSubagentFromCompactTrack(page, child.id); + const childSheet = sheet(page, child.title); + await openSubagentFromCompactTrack(page, grandchild.id, childSheet); + const grandchildSheet = sheet(page, grandchild.title); + await expectSheetAtSnap(page, grandchild.title); + await expect(grandchildSheet.getByTestId("parent-agent-callout")).toContainText(child.title); + + await grandchildSheet.getByTestId("parent-agent-callout-open").click(); + await expect(grandchildSheet).toHaveCount(0); + await expect(childSheet).toBeVisible(); + await expectOneSheetOpen(page); + + await childSheet.getByTestId("parent-agent-callout-open").click(); + await expect(childSheet).toHaveCount(0); + await expectNoSheetOpen(page); await expectOpenTabCount(page, 1); }); await test.step("Open as tab promotes the subagent to a full tab and ends the list", async () => { - await page.getByTestId(`subagents-track-row-${child.id}`).click(); + await openSubagentFromCompactTrack(page, child.id); await expectSheetAtSnap(page, child.title); await openSheetAsTab(page, child.title); await expect(page.getByTestId(`subagents-track-row-${child.id}`)).toHaveCount(0); @@ -123,7 +161,7 @@ test("compact opens files and subagents in a sheet, leaving the tabs for agents" await expect(page.getByTestId(`subagents-track-row-${child.id}`)).toHaveCount(0); }); - await test.step("once its tab closes, the subagent reopens in a sheet that keeps the list", async () => { + await test.step("once its tab closes, the subagent reopens in place of the list", async () => { await page .getByRole("button", { name: /Switch tabs/ }) .filter({ visible: true }) @@ -141,7 +179,7 @@ test("compact opens files and subagents in a sheet, leaving the tabs for agents" await openSubagentFromCompactTrack(page, child.id); await expectSheetAtSnap(page, child.title); - await closeSheet(page, child.title); + await backToList(page, child.title); await expectSubagentRowVisible(page, child.id); await tapSheetBackdrop(page); await expect(page.getByRole("button", { name: "Bottom sheet backdrop" })).toHaveCount(0); diff --git a/packages/app/e2e/browser/composer-autocomplete.spec.ts b/packages/app/e2e/browser/composer-autocomplete.spec.ts index d83046d8b2..f40b51304b 100644 --- a/packages/app/e2e/browser/composer-autocomplete.spec.ts +++ b/packages/app/e2e/browser/composer-autocomplete.spec.ts @@ -1,5 +1,9 @@ import { expect, test, type Page } from "../support/fixtures"; -import { composerLocator, expectComposerVisible } from "../support/helpers/composer"; +import { + attachFileFromMenu, + composerLocator, + expectComposerVisible, +} from "../support/helpers/composer"; import { openAgentRoute, seedMockAgentWorkspace, @@ -365,6 +369,56 @@ function expectPopoverDoesNotDisappearAfterFirstVisible(frames: PopoverFrame[]): } test.describe("Composer autocomplete", () => { + test("inserts suggested commands from assistant messages without sending", async ({ page }) => { + const requests = recordCommandRequestsByAgentId(page); + const session = await seedMockAgentWorkspace({ + repoPrefix: "suggested-command-", + title: "Suggested commands", + initialPrompt: "Suggest `/mock` without running it", + featureValues: { mockAssistantResponse: "Try `/mock` or [Run mock](/mock)." }, + }); + try { + await openAgentRoute(page, session); + const message = page.getByTestId("assistant-message").filter({ hasText: "Run mock" }); + await expect(message).toBeVisible(); + await expect(page.getByTestId("user-message").getByRole("link")).toHaveCount(0); + await expect.poll(() => requests.length).toBe(1); + await attachFileFromMenu(page, { + name: "note.txt", + mimeType: "text/plain", + buffer: Buffer.from("attachment"), + }); + await expect(page.getByTestId("composer-file-attachment-pill")).toContainText("note.txt"); + await message.getByRole("link", { name: "/mock", exact: true }).click(); + await expect(composerLocator(page)).toHaveValue("/mock "); + await expect( + page.getByTestId("composer-autocomplete-popover").filter({ visible: true }), + ).toHaveCount(0); + await expect(composerLocator(page)).toBeFocused(); + await message.getByRole("link", { name: "Run mock" }).click(); + await expect(composerLocator(page)).toHaveValue("/mock /mock "); + await expect( + page.getByTestId("composer-autocomplete-popover").filter({ visible: true }), + ).toHaveCount(0); + await expect(composerLocator(page)).toBeFocused(); + await expect(page.getByTestId("composer-file-attachment-pill")).toContainText("note.txt"); + await composerLocator(page).fill("draft"); + await composerLocator(page).evaluate((element: HTMLTextAreaElement) => + element.setSelectionRange(0, 0), + ); + await message.getByRole("link", { name: "/mock", exact: true }).click(); + await composerLocator(page).pressSequentially("argument"); + await expect(composerLocator(page)).toHaveValue("draft /mock argument"); + await composerLocator(page).fill("/"); + await expect( + page.getByTestId("composer-autocomplete-popover").filter({ visible: true }), + ).toContainText("/mock"); + expect(requests).toHaveLength(1); + } finally { + await session.cleanup(); + } + }); + test("keeps New workspace off the running-agent command list before a project is chosen", async ({ page, }) => { diff --git a/packages/app/e2e/browser/composer-diff-stat.spec.ts b/packages/app/e2e/browser/composer-diff-stat.spec.ts index 9b80222432..959567f58b 100644 --- a/packages/app/e2e/browser/composer-diff-stat.spec.ts +++ b/packages/app/e2e/browser/composer-diff-stat.spec.ts @@ -18,7 +18,7 @@ function visibleMainPane(page: Page) { } function composerChangesPill(page: Page) { - return page.getByTestId("composer-diff-stat-pill"); + return page.getByRole("button", { name: "Open Changes tab", exact: true }); } async function revealComposerChangesInExplorer(page: Page) { @@ -498,6 +498,7 @@ test.describe("send review feedback", () => { test("only open tabs in this workspace appear in compact and wide recipient menus", async ({ page, }) => { + test.setTimeout(120000); const workspace = await seedChangedAgent("review-feedback-multiple-"); const other = await seedChangedAgent("review-feedback-other-"); try { diff --git a/packages/app/e2e/browser/composer-recall.spec.ts b/packages/app/e2e/browser/composer-recall.spec.ts index 368d23409c..a58a8ff59e 100644 --- a/packages/app/e2e/browser/composer-recall.spec.ts +++ b/packages/app/e2e/browser/composer-recall.spec.ts @@ -3,7 +3,7 @@ import { composerLocator, expectComposerDraft, expectComposerVisible, - submitMessage, + fillComposerDraft, typeIntoFocusedComposer, } from "../support/helpers/composer"; import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent"; @@ -12,8 +12,14 @@ function userMessages(page: Page) { return page.getByTestId("user-message"); } +async function sendDraftWhenReady(page: Page) { + await expect(page.getByRole("button", { name: "Send message", exact: true })).toBeEnabled(); + await pressInComposer(page, "Enter"); +} + async function sendAndWaitForMessage(page: Page, text: string, expectedCount: number) { - await submitMessage(page, text); + await fillComposerDraft(page, text); + await sendDraftWhenReady(page); await expect(userMessages(page)).toHaveCount(expectedCount, { timeout: 30_000 }); await expectComposerDraft(page, ""); } @@ -49,7 +55,7 @@ test.describe("Composer recall", () => { await pressInComposer(page, "ArrowUp"); await expectComposerDraft(page, "add tests for login"); - await pressInComposer(page, "Enter"); + await sendDraftWhenReady(page); await expect(userMessages(page)).toHaveCount(3, { timeout: 30_000 }); await expect(userMessages(page).last()).toContainText("add tests for login"); } finally { diff --git a/packages/app/e2e/browser/daemon-lifecycle.spec.ts b/packages/app/e2e/browser/daemon-lifecycle.spec.ts index bded30cb81..23f6f5b2ff 100644 --- a/packages/app/e2e/browser/daemon-lifecycle.spec.ts +++ b/packages/app/e2e/browser/daemon-lifecycle.spec.ts @@ -1,14 +1,23 @@ import { randomUUID } from "node:crypto"; -import { mkdtemp, writeFile } from "node:fs/promises"; +import { mkdtemp, writeFile, rm } from "node:fs/promises"; +import { existsSync } from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; -import { expect, test } from "../support/fixtures"; +import { expect, test, daemonTest as cleanupTest } from "../support/fixtures"; import { startIsolatedHostDaemon } from "../support/helpers/isolated-host-daemon"; import { openDaemonOverview, restartDaemonInSettings, expectDaemonRestartComplete, + expectDaemonRestartFailed, + plantUnclosableTerminalProgram, readWorkerPid, + openLongLivedTerminal, + listTerminalIds, + suspendDaemonProcess, + resumeDaemonProcess, + daemonProcessCanWrite, + readTerminalProcessIds, } from "../support/helpers/daemon-lifecycle"; test("settings restart waits for a replacement worker while retaining the supervisor", async ({ @@ -29,6 +38,57 @@ test("settings restart waits for a replacement worker while retaining the superv } }); +test("settings restart keeps a terminal", async ({ page }) => { + const daemon = await startIsolatedHostDaemon(randomUUID()); + try { + const terminalId = await openLongLivedTerminal(daemon); + const previousWorker = await readWorkerPid(daemon); + await openDaemonOverview(page, daemon); + await restartDaemonInSettings(page); + await expectDaemonRestartComplete(page); + expect(await readWorkerPid(daemon)).not.toBe(previousWorker); + expect(await listTerminalIds(daemon)).toContain(terminalId); + } finally { + await daemon.close(); + } +}); + +test("settings restart and close terminals closes the terminal", async ({ page }) => { + const daemon = await startIsolatedHostDaemon(randomUUID()); + try { + await openLongLivedTerminal(daemon); + const previousWorker = await readWorkerPid(daemon); + await openDaemonOverview(page, daemon); + await restartDaemonInSettings(page, { closeTerminals: true }); + await expectDaemonRestartComplete(page); + expect(await readWorkerPid(daemon)).not.toBe(previousWorker); + expect(await listTerminalIds(daemon)).toEqual([]); + } finally { + await daemon.close(); + } +}); + +test("settings restart and close terminals shows the processes it could not close", async ({ + page, +}, testInfo) => { + test.skip(process.platform === "win32", "The unclosable program is a POSIX zombie"); + const daemon = await startIsolatedHostDaemon(randomUUID()); + let program: Awaited> | null = null; + try { + program = await plantUnclosableTerminalProgram(daemon); + await openDaemonOverview(page, daemon); + await restartDaemonInSettings(page, { closeTerminals: true }); + await expectDaemonRestartFailed(page, `pid ${program.pid}`); + await page.screenshot({ + path: testInfo.outputPath("restart-cleanup-failed.png"), + fullPage: true, + }); + } finally { + program?.release(); + await daemon.close(); + } +}); + test("settings restart replaces the worker when a provider CLI answers --version slowly", async ({ page, }) => { @@ -64,3 +124,51 @@ async function createHomeWithSlowProvider(versionDelayMs: number): Promise { + cleanupTest.skip(process.platform === "win32", "POSIX stopped-process failure injection"); + const daemon = await startIsolatedHostDaemon(randomUUID()); + const workerPid = await readWorkerPid(daemon); + try { + suspendDaemonProcess(workerPid); + await daemon.close(); + resumeDaemonProcess(workerPid); + await expect.poll(() => daemonProcessCanWrite(workerPid)).toBe(false); + expect(existsSync(daemon.paseoHome)).toBe(false); + } finally { + resumeDaemonProcess(workerPid); + await daemon.close(); + await rm(daemon.paseoHome, { recursive: true, force: true }); + } + }, +); + +cleanupTest( + "isolated cleanup force-stops a frozen supervisor and its detached terminal writers", + async () => { + cleanupTest.skip(process.platform === "win32", "POSIX stopped-process failure injection"); + const daemon = await startIsolatedHostDaemon(randomUUID()); + const supervisorPid = daemon.getPid()!; + const workerPid = await readWorkerPid(daemon); + try { + await openLongLivedTerminal(daemon); + const terminalProcesses = await readTerminalProcessIds(daemon); + expect(terminalProcesses.length).toBeGreaterThanOrEqual(2); + suspendDaemonProcess(supervisorPid); + await daemon.close(); + const writerStates = await Promise.all( + [supervisorPid, workerPid, ...terminalProcesses].map(daemonProcessCanWrite), + ); + expect(writerStates).toEqual(Array(terminalProcesses.length + 2).fill(false)); + expect(existsSync(daemon.paseoHome)).toBe(false); + } finally { + resumeDaemonProcess(supervisorPid); + await daemon.close(); + } + }, +); diff --git a/packages/app/e2e/browser/diff-performance.spec.ts b/packages/app/e2e/browser/diff-performance.spec.ts index c11c82f279..0358b6359e 100644 --- a/packages/app/e2e/browser/diff-performance.spec.ts +++ b/packages/app/e2e/browser/diff-performance.spec.ts @@ -1,6 +1,7 @@ import { writeFile } from "node:fs/promises"; import path from "node:path"; import type { CDPSession, Locator, Page, TestInfo } from "@playwright/test"; +import { pullRequestCorpus } from "../../src/git/diff-document/benchmark-corpus"; import { buildHostWorkspaceRoute } from "../../src/utils/host-routes"; import { test, expect } from "../support/fixtures"; import { getServerId } from "../support/helpers/server-id"; @@ -296,8 +297,187 @@ diffPerfDescribe("Diff canvas performance", () => { await repo.cleanup().catch(() => undefined); } }); + test("toggling line wrap on a pull-request-sized diff", async ({ page }, testInfo) => { + test.setTimeout(300_000); + const corpus = await createPullRequestCorpusRepository(); + const client = await connectSeedClient(); + + try { + const created = await client.createWorkspace({ + source: { kind: "directory", path: corpus.repo.path }, + }); + if (!created.workspace) { + throw new Error(created.error ?? "Failed to create wrap performance workspace"); + } + + await configureUnwrappedUnifiedDiff(page); + await instrumentDiffLatency(page); + await page.setViewportSize({ width: 1400, height: 900 }); + await page.goto(buildHostWorkspaceRoute(getServerId(), created.workspace.id)); + await waitForWorkspaceTabsVisible(page); + const openStartedAt = performance.now(); + await openChangesPanel(page, 90_000); + await expect(page.getByTestId("git-diff-canvas")).toBeVisible({ timeout: 30_000 }); + const open = { + readyMs: Math.round(performance.now() - openStartedAt), + ...(await readDiffDocumentRenders(page)), + }; + + const toggles: WrapToggleMeasurement[] = []; + for (const name of [ + "wrap on (cold)", + "wrap off (cold)", + "wrap on (warm)", + "wrap off (warm)", + ]) { + toggles.push(await measureWrapToggle(page, name)); + } + const unwrappedScroll = await continuouslyScrollCanvas(page); + toggles.push(await measureWrapToggle(page, "wrap on (warm, scrolled)")); + const wrappedScroll = await continuouslyScrollCanvas(page); + + const report = { + scenario: "wrap-toggle", + sourceFiles: corpus.fileCount, + sourceLines: corpus.lineCount, + open, + toggles, + scroll: { + unwrapped: summarizeScroll(unwrappedScroll), + wrapped: summarizeScroll(wrappedScroll), + }, + }; + await attachPerformanceReport(testInfo, report); + console.log(`[perf] Wrap toggle: ${JSON.stringify(report)}`); + + const [wrapOn, wrapOff] = toggles; + expect(wrapOn!.scrollHeightAfter).toBeGreaterThan(wrapOn!.scrollHeightBefore); + expect(wrapOff!.scrollHeightAfter).toBe(wrapOn!.scrollHeightBefore); + } finally { + await client.close().catch(() => undefined); + await corpus.repo.cleanup().catch(() => undefined); + } + }); }); +interface WrapToggleMeasurement { + name: string; + /** Pointer down on the toolbar button to two painted frames after the document resized. */ + latencyMs: number; + scrollHeightBefore: number; + scrollHeightAfter: number; + longestTaskMs: number; + longTaskTotalMs: number; + diffDocumentCommits: number; + diffDocumentRenderMs: number; +} + +interface LongTask { + startTime: number; + duration: number; +} + +interface DiffLatencyScope { + __PASEO_RENDER_PROFILE_ENABLED__?: boolean; + __PASEO_RENDER_PROFILE__?: Array<{ id: string; actualDuration: number }>; + __PASEO_RESET_RENDER_PROFILE__?: () => void; + __PASEO_LONG_TASKS__?: LongTask[]; + __PASEO_WRAP_TOGGLE_AT__?: number; +} + +async function createPullRequestCorpusRepository() { + const files = pullRequestCorpus(); + const repo = await createTempGitRepo("diff-wrap-perf-", { + files: files.map((file) => ({ path: file.path, content: "baseline\n" })), + }); + for (const file of files) { + await writeFile(path.join(repo.path, file.path), `${file.lines.join("\n")}\n`); + } + return { + repo, + fileCount: files.length, + lineCount: files.reduce((count, file) => count + file.lines.length, 0), + }; +} + +async function instrumentDiffLatency(page: Page): Promise { + await page.addInitScript(() => { + const scope = globalThis as typeof globalThis & DiffLatencyScope; + scope.__PASEO_RENDER_PROFILE_ENABLED__ = true; + scope.__PASEO_LONG_TASKS__ = []; + new PerformanceObserver((list) => { + for (const entry of list.getEntries()) { + scope.__PASEO_LONG_TASKS__?.push({ startTime: entry.startTime, duration: entry.duration }); + } + }).observe({ type: "longtask", buffered: true }); + }); +} + +async function readDiffDocumentRenders( + page: Page, +): Promise<{ diffDocumentCommits: number; diffDocumentRenderMs: number }> { + return page.evaluate(() => { + const scope = globalThis as typeof globalThis & DiffLatencyScope; + const samples = (scope.__PASEO_RENDER_PROFILE__ ?? []).filter( + (sample) => sample.id === "DiffDocument", + ); + return { + diffDocumentCommits: samples.length, + diffDocumentRenderMs: Math.round( + samples.reduce((total, sample) => total + sample.actualDuration, 0), + ), + }; + }); +} + +async function measureWrapToggle(page: Page, name: string): Promise { + const scroll = page.getByTestId("git-diff-scroll"); + const scrollHeightBefore = await scroll.evaluate((element) => element.scrollHeight); + await page.evaluate(() => { + const scope = globalThis as typeof globalThis & DiffLatencyScope; + scope.__PASEO_RESET_RENDER_PROFILE__?.(); + scope.__PASEO_LONG_TASKS__ = []; + scope.__PASEO_WRAP_TOGGLE_AT__ = undefined; + document.addEventListener( + "pointerdown", + () => { + scope.__PASEO_WRAP_TOGGLE_AT__ = performance.now(); + }, + { capture: true, once: true }, + ); + }); + await page.getByTestId("changes-toggle-wrap-lines").click(); + const measured = await scroll.evaluate(async (element, before) => { + const scope = globalThis as typeof globalThis & DiffLatencyScope; + const deadline = performance.now() + 240_000; + while (element.scrollHeight === before && performance.now() < deadline) { + await new Promise((resolve) => setTimeout(resolve, 5)); + } + await new Promise((resolve) => + requestAnimationFrame(() => requestAnimationFrame(() => resolve())), + ); + const doneAt = performance.now(); + // Long task entries are delivered after the task ends; give the observer a turn. + await new Promise((resolve) => setTimeout(resolve, 50)); + const startedAt = scope.__PASEO_WRAP_TOGGLE_AT__ ?? doneAt; + const longTasks = (scope.__PASEO_LONG_TASKS__ ?? []).filter( + (task) => task.startTime + task.duration >= startedAt && task.startTime <= doneAt, + ); + return { + latencyMs: Math.round(doneAt - startedAt), + scrollHeightAfter: element.scrollHeight, + longestTaskMs: Math.round(Math.max(0, ...longTasks.map((task) => task.duration))), + longTaskTotalMs: Math.round(longTasks.reduce((total, task) => total + task.duration, 0)), + }; + }, scrollHeightBefore); + return { name, scrollHeightBefore, ...measured, ...(await readDiffDocumentRenders(page)) }; +} + +function summarizeScroll(report: Awaited>) { + const { frameSignatures: _frameSignatures, ...summary } = report; + return summary; +} + async function measureAdditionalPerformanceScenario( page: Page, cdp: CDPSession, diff --git a/packages/app/e2e/browser/folder-links.spec.ts b/packages/app/e2e/browser/folder-links.spec.ts index a893fbcb68..358c579357 100644 --- a/packages/app/e2e/browser/folder-links.spec.ts +++ b/packages/app/e2e/browser/folder-links.spec.ts @@ -81,6 +81,8 @@ for (const folder of [ "docs/guides", "docs/guides/", "docs/指南", + "examples/next.js/", + "examples/next.js", ]) { test(`chat folder link opens folder contents: ${folder}`, async ({ page }) => { const session = await seedMockAgentWorkspace({ @@ -92,6 +94,9 @@ for (const folder of [ try { await mkdir(path.join(session.cwd, folder), { recursive: true }); await writeFile(path.join(session.cwd, folder, "guide.md"), "# Folder link destination\n"); + const competingFile = path.join(session.cwd, "repo-a", folder.replace(/\/$/, "")); + await mkdir(path.dirname(competingFile), { recursive: true }); + await writeFile(competingFile, "This is a file, not the requested folder.\n"); await session.client.waitForFinish(session.agentId, 30_000); await page.addInitScript(() => { localStorage.setItem( diff --git a/packages/app/e2e/browser/new-workspace-composer-draft.spec.ts b/packages/app/e2e/browser/new-workspace-composer-draft.spec.ts index 906efcfb42..01fd4638eb 100644 --- a/packages/app/e2e/browser/new-workspace-composer-draft.spec.ts +++ b/packages/app/e2e/browser/new-workspace-composer-draft.spec.ts @@ -1,3 +1,4 @@ +import { chooseModel, startWithoutRememberedModel } from "../support/helpers/model-memory"; import { composerLocator, enterComposerFullscreen, @@ -97,6 +98,7 @@ test.describe("New workspace composer draft", () => { const project = await seedWorkspace({ repoPrefix: "new-workspace-submitted-draft-" }); try { + await startWithoutRememberedModel(page); await gotoAppShell(page); await waitForSidebarHydration(page); await openNewWorkspaceComposer(page, { @@ -104,6 +106,7 @@ test.describe("New workspace composer draft", () => { projectDisplayName: project.projectDisplayName, }); + await chooseModel(page, "mock", "Ten second stream"); const composer = page.getByRole("textbox", { name: "Message agent..." }); const createButton = page.getByTestId("workspace-create-submit"); await expect(composer).toBeEditable({ timeout: 30_000 }); diff --git a/packages/app/e2e/browser/owned-subscriptions-old-daemon.spec.ts b/packages/app/e2e/browser/owned-subscriptions-old-daemon.spec.ts index 17f4db2e85..5f1f36e409 100644 --- a/packages/app/e2e/browser/owned-subscriptions-old-daemon.spec.ts +++ b/packages/app/e2e/browser/owned-subscriptions-old-daemon.spec.ts @@ -1,29 +1,90 @@ import { randomUUID } from "node:crypto"; -import { submitMessage, expectComposerEditable } from "../support/helpers/composer"; import { focusTerminalSurface, typeInTerminal, getTerminalBufferText, } from "../support/helpers/terminal-perf"; import { buildHostWorkspaceRoute } from "../../src/utils/host-routes"; -import { metroTest as test, expect } from "../support/fixtures"; +import { metroTest as test, expect, type Page } from "../support/fixtures"; import { buildCreateAgentPreferences, buildSeededHost } from "../support/helpers/daemon-registry"; import { startIsolatedHostDaemon } from "../support/helpers/isolated-host-daemon"; import type { MockAgentWorkspace } from "../support/helpers/mock-agent"; import { seedWorkspace } from "../support/helpers/seed-client"; import { - expectTimelinePromptVisible, + expectFoldedTurnAtReadingPosition, + expectOldestLoadedTurnPartial, holdOlderHistoryPages, openAgentTimeline, - scrollThroughOlderHistoryPages, + expectTimelinePromptVisible, + userScrollsTimelineToHistoryStart, } from "../support/helpers/timeline-pagination"; -test("does not repeat an assistant block when the current app paginates a published 0.2.5 daemon", async ({ +interface PublishedDaemonAgent { + serverId: string; + daemon: Awaited>; + agent: MockAgentWorkspace; + /** Register the host in the browser and apply app settings before the first load. */ + seedBrowser(page: Page, appSettings?: Record): Promise; + close(): Promise; +} + +async function startPublishedDaemonAgent(options: { + publishedVersion: string; + serverIdPrefix: string; + repoPrefix: string; + title: string; +}): Promise { + const serverId = `${options.serverIdPrefix}${randomUUID().replaceAll("-", "").slice(0, 12)}`; + const daemon = await startIsolatedHostDaemon(serverId, { + publishedVersion: options.publishedVersion, + }); + const workspace = await seedWorkspace({ repoPrefix: options.repoPrefix, port: daemon.port }); + const createdAgent = await workspace.client.createAgent({ + provider: "mock", + cwd: workspace.repoPath, + workspaceId: workspace.workspaceId, + title: options.title, + modeId: "load-test", + model: "ten-second-stream", + }); + const agent: MockAgentWorkspace = { + agentId: createdAgent.id, + workspaceId: workspace.workspaceId, + cwd: workspace.repoPath, + client: workspace.client, + cleanup: workspace.cleanup, + }; + return { + serverId, + daemon, + agent, + async seedBrowser(page, appSettings) { + const host = buildSeededHost({ + serverId, + endpoint: `127.0.0.1:${daemon.port}`, + nowIso: new Date().toISOString(), + }); + await page.addInitScript( + ({ seededHost, preferences, settings }) => { + localStorage.setItem("@paseo:e2e", "1"); + localStorage.setItem("@paseo:daemon-registry", JSON.stringify([seededHost])); + localStorage.setItem("@paseo:create-agent-preferences", JSON.stringify(preferences)); + if (settings) localStorage.setItem("@paseo:app-settings", JSON.stringify(settings)); + }, + { seededHost: host, preferences: buildCreateAgentPreferences(), settings: appSettings }, + ); + }, + async close() { + await agent.cleanup(); + await daemon.close(); + }, + }; +} + +test("loads history across browser reconnection while retaining old-daemon connections and terminals", async ({ page, }) => { test.setTimeout(120_000); - const serverId = `srv_old_pagination_${randomUUID().replaceAll("-", "").slice(0, 12)}`; - const daemon = await startIsolatedHostDaemon(serverId, { publishedVersion: "0.2.5" }); const observationSockets = new Set(); page.on("websocket", (socket) => { socket.on("framesent", ({ payload }) => { @@ -37,104 +98,84 @@ test("does not repeat an assistant block when the current app paginates a publis observationSockets.add(socket); }); }); - const workspace = await seedWorkspace({ + const published = await startPublishedDaemonAgent({ + publishedVersion: "0.2.5", + serverIdPrefix: "srv_old_pagination_", repoPrefix: "timeline-old-daemon-pagination-", - port: daemon.port, - }); - const createdAgent = await workspace.client.createAgent({ - provider: "mock", - cwd: workspace.repoPath, - workspaceId: workspace.workspaceId, title: "Published daemon pagination regression", - modeId: "load-test", - model: "ten-second-stream", }); - const agent: MockAgentWorkspace = { - agentId: createdAgent.id, - workspaceId: workspace.workspaceId, - cwd: workspace.repoPath, - client: workspace.client, - cleanup: workspace.cleanup, - }; + const { agent, serverId } = published; try { - for (let index = 0; index < 40; index += 1) { - await agent.client.sendAgentMessage( - agent.agentId, - `timeline-pagination-older-turn-${index}: emit 1 coalesced agent stream updates`, - ); - await agent.client.waitForFinish(agent.agentId, 15_000); - } - await agent.client.sendAgentMessage(agent.agentId, "build a realistic long mock timeline"); - await agent.client.waitForFinish(agent.agentId, 20_000); - for (let index = 0; index < 20; index += 1) { - await agent.client.sendAgentMessage( - agent.agentId, - `timeline-pagination-turn-${index}: emit 1 coalesced agent stream updates`, - ); - await agent.client.waitForFinish(agent.agentId, 15_000); - } + await agent.client.sendAgentMessage(agent.agentId, "emit 1 coalesced agent stream updates"); + await agent.client.waitForFinish(agent.agentId, 15_000); + await published.seedBrowser(page); - const host = buildSeededHost({ - serverId, - endpoint: `127.0.0.1:${daemon.port}`, - nowIso: new Date().toISOString(), - }); - await page.addInitScript( - ({ seededHost, preferences }) => { - localStorage.setItem("@paseo:e2e", "1"); - localStorage.setItem("@paseo:daemon-registry", JSON.stringify([seededHost])); - localStorage.setItem("@paseo:create-agent-preferences", JSON.stringify(preferences)); - }, - { seededHost: host, preferences: buildCreateAgentPreferences() }, - ); - - const history = await holdOlderHistoryPages(page, agent, daemon.port); await openAgentTimeline(page, agent, serverId); - await expectTimelinePromptVisible( - page, - "timeline-pagination-turn-19: emit 1 coalesced agent stream updates", - ); - await scrollThroughOlderHistoryPages(page, 3, history); - - history.expectRepeatedEntries(); - await history.expectOwnedTextRendered("Now I have a clearer picture."); + await expectTimelinePromptVisible(page, "emit 1 coalesced agent stream updates"); expect(observationSockets.size).toBe(1); - await test.step("send a live turn after reconnecting the old daemon", async () => { - await daemon.restart(); - await expect.poll(() => observationSockets.size, { timeout: 30_000 }).toBe(2); - await expectComposerEditable(page); - await submitMessage( - page, - "compatibility-after-reconnect: emit 1 coalesced agent stream updates", - ); - await expectTimelinePromptVisible( - page, - "compatibility-after-reconnect: emit 1 coalesced agent stream updates", - ); - // The browser and the seed client reconnect independently after the restart. - await agent.client.connect(); - await agent.client.waitForFinish(agent.agentId, 20_000); - await page.screenshot({ path: test.info().outputPath("old-daemon-live-reconnect.png") }); + await test.step("reconnect the browser and reload the old daemon history", async () => { + observationSockets.clear(); + await page.reload(); + await expectTimelinePromptVisible(page, "emit 1 coalesced agent stream updates"); + await expect.poll(() => observationSockets.size).toBe(1); }); await test.step("open a terminal and receive its output", async () => { const terminal = await agent.client.createTerminal(agent.cwd, "Compatibility terminal"); expect(terminal.error).toBeNull(); const terminalId = terminal.terminal!.id; - const route = buildHostWorkspaceRoute(serverId, workspace.workspaceId); + const route = buildHostWorkspaceRoute(serverId, agent.workspaceId); await page.goto(`${route}?open=${encodeURIComponent(`terminal:${terminalId}`)}`); await focusTerminalSurface(page); await typeInTerminal(page, "printf 'compatibility-%s\\n' terminal-output\n"); await expect .poll(() => getTerminalBufferText(page), { timeout: 15_000 }) .toContain("compatibility-terminal-output"); - await page.screenshot({ path: test.info().outputPath("old-daemon-terminal.png") }); await agent.client.killTerminal(terminalId); }); } finally { - await agent.cleanup(); - await daemon.close(); + await published.close(); + } +}); + +// Hosts without whole-turn pages split turns across item pages. The oldest loaded turn +// starts mid-turn and only folds once the next page completes it; the reader must stay +// with that turn instead of landing at history start and draining every older page. +test("keeps the reader on the turn that folds when an older item page completes it", async ({ + page, +}) => { + test.setTimeout(240_000); + const published = await startPublishedDaemonAgent({ + publishedVersion: "0.13.0-beta.2", + serverIdPrefix: "srv_old_fold_", + repoPrefix: "timeline-old-daemon-fold-", + title: "Published daemon folded turn pagination", + }); + const { agent, serverId } = published; + const prompts = Array.from({ length: 5 }, (_, index) => `Realistic turn ${index}: inspect it`); + + try { + for (const prompt of prompts) { + await agent.client.sendAgentMessage(agent.agentId, prompt); + await agent.client.waitForFinish(agent.agentId, 30_000); + } + await published.seedBrowser(page, { chatDisplay: "collapseTurns" }); + const history = await holdOlderHistoryPages(page, agent, { + daemonPort: published.daemon.port, + }); + await openAgentTimeline(page, agent, serverId); + await expectTimelinePromptVisible(page, prompts.at(-1)!); + + await userScrollsTimelineToHistoryStart(page); + await history.expectRequestedPages(1); + const partialTurnPrompt = await expectOldestLoadedTurnPartial(page, prompts); + + history.releasePage(1); + await expectFoldedTurnAtReadingPosition(page, partialTurnPrompt); + await history.expectSettledWithRequestedPages(1); + } finally { + await published.close(); } }); diff --git a/packages/app/e2e/browser/plugin-host-ui.spec.ts b/packages/app/e2e/browser/plugin-host-ui.spec.ts index a195f30aa2..b63728ff73 100644 --- a/packages/app/e2e/browser/plugin-host-ui.spec.ts +++ b/packages/app/e2e/browser/plugin-host-ui.spec.ts @@ -1,3 +1,13 @@ +import { + withRetainedPlugin, + editRetainedDraft, + expectRetainedDraft, + expectStoredPluginTitle, + hideRetainedPreferences, + showRetainedPreferences, + expectChangedPlugin, + expectRemovedPlugin, +} from "../support/helpers/plugin-reconnect"; import { verifyPluginTranslations } from "../support/helpers/plugin-translations"; import { pluginRequirements } from "../support/helpers/plugin-fixture"; import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; @@ -188,3 +198,51 @@ test("plugin content and host labels follow app language without losing an open test.setTimeout(180_000); await verifyPluginTranslations(page, info); }); + +test("retains plugin state offline and reconciles settings, changed code and removal", async ({ + page, +}) => { + test.setTimeout(180_000); + await withRetainedPlugin(page, async (probe) => { + await probe.open(); + await editRetainedDraft(page, "Connected draft", 0); + + await test.step("local plugin UI remains mounted and usable while disconnected", async () => { + await probe.disconnect(); + await expectRetainedDraft(page, "Connected draft", 1); + await editRetainedDraft(page, "Offline draft", 1); + await probe.changeStoredTitle("Saved by another client"); + await expectStoredPluginTitle(page, "Agent monitor"); + await probe.reconnect(); + await expectStoredPluginTitle(page, "Saved by another client"); + await expectRetainedDraft(page, "Offline draft", 2); + }); + + await test.step("inactive settings refresh without replacing the installation", async () => { + await hideRetainedPreferences(page); + await probe.disconnect(); + await probe.changeStoredTitle("Saved while preferences hidden"); + await probe.reconnect(); + await showRetainedPreferences(page); + await expectStoredPluginTitle(page, "Saved while preferences hidden"); + await expectRetainedDraft(page, "Offline draft", 2); + }); + + await test.step("changed code replaces the retained installation after reconnect", async () => { + await probe.disconnect(); + await probe.changeCode(); + await expectRetainedDraft(page, "Offline draft", 2); + await probe.reconnect(); + await expectChangedPlugin(page); + await editRetainedDraft(page, "New code draft", 0); + }); + + await test.step("removal is reconciled after reconnect", async () => { + await probe.disconnect(); + await probe.remove(); + await expectRetainedDraft(page, "New code draft", 1); + await probe.reconnect(); + await expectRemovedPlugin(page); + }); + }); +}); diff --git a/packages/app/e2e/browser/plugin-timeline.spec.ts b/packages/app/e2e/browser/plugin-timeline.spec.ts index 166e6b9881..d75653298e 100644 --- a/packages/app/e2e/browser/plugin-timeline.spec.ts +++ b/packages/app/e2e/browser/plugin-timeline.spec.ts @@ -1,4 +1,5 @@ import { test } from "../support/fixtures"; +import { installDaemonWebSocketGate } from "../support/helpers/daemon-websocket-gate"; import { withTimelinePlugin, viewInlineThinkingExample, @@ -6,6 +7,8 @@ import { interactWithStreamingCard, expectWholeCompletedCard, expectBothConsecutiveTools, + trackPluginChatRecovery, + reconnectPluginChat, } from "../support/helpers/plugin-timeline"; for (const width of [1100, 390]) { @@ -13,13 +16,24 @@ for (const width of [1100, 390]) { page, }, info) => { await page.setViewportSize({ width, height: 900 }); + const gate = await installDaemonWebSocketGate(page); await withTimelinePlugin(page, info, "assistant", async (agent) => { await requestPluginTimeline(agent); await interactWithStreamingCard(page); await agent.client.waitForFinish(agent.agentId, 30_000); await expectWholeCompletedCard(page); // Local state is checked during growth; the viewport remounts on the history handoff. + const recovery = trackPluginChatRecovery(page); + gate.holdTimelineResponses(agent.agentId); await page.reload({ waitUntil: "domcontentloaded" }); + await gate.waitForHeldTimelineResponse(); + await recovery.expectCatalogWithoutRetransmission(); + gate.releaseHeldTimelineResponses(); + await expectWholeCompletedCard(page); + await recovery.expectRecoveredWithoutRetransmission(); + recovery.reset(); + await reconnectPluginChat(page, gate); + await recovery.expectRecoveredWithoutRetransmission(); await expectWholeCompletedCard(page); }); }); diff --git a/packages/app/e2e/browser/projects-settings.spec.ts b/packages/app/e2e/browser/projects-settings.spec.ts index 0612d5ce07..0732ec6732 100644 --- a/packages/app/e2e/browser/projects-settings.spec.ts +++ b/packages/app/e2e/browser/projects-settings.spec.ts @@ -204,19 +204,26 @@ test.describe("Projects settings", () => { }) => { const repo = await createTempGitRepo("projects-settings-empty-"); const client = await connectSeedClient(); - let projectId: string | null = null; + let projectViewKey: string | null = null; try { await gotoAppShell(page); - projectId = await addProjectFromSidebar(page, repo.path); - await openProjectSettingsFromSidebar(page, projectId); + projectViewKey = await addProjectFromSidebar(page, repo.path); + await openProjectSettingsFromSidebar(page, projectViewKey); await expectProjectSettingsFormVisible(page); await expect(page.getByTestId("project-settings-back-button")).not.toBeVisible(); } finally { - if (projectId) { - await client.removeProject(projectId).catch(() => undefined); + if (projectViewKey) { + const project = (await client.listProjects()).projects.find( + (entry) => entry.projectKey === projectViewKey, + ); + expect(project).toBeDefined(); + await client.removeProject(project!.projectId); + expect( + (await client.listProjects()).projects.map((entry) => entry.projectKey), + ).not.toContain(projectViewKey); } await client.close().catch(() => undefined); await repo.cleanup().catch(() => undefined); diff --git a/packages/app/e2e/browser/provider-settings-refresh.spec.ts b/packages/app/e2e/browser/provider-settings-refresh.spec.ts index 961b518435..6c9739e894 100644 --- a/packages/app/e2e/browser/provider-settings-refresh.spec.ts +++ b/packages/app/e2e/browser/provider-settings-refresh.spec.ts @@ -1,5 +1,7 @@ +import path from "node:path"; import type { Locator } from "@playwright/test"; import { expect, test, type Page } from "../support/fixtures"; +import { clickNewChat, gotoWorkspace } from "../support/helpers/launcher"; import { expectComposerVisible } from "../support/helpers/composer"; import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent"; @@ -214,3 +216,66 @@ test.describe("provider settings overlay stack", () => { } }); }); + +async function openTimedOutProvider(page: Page, workspaceId: string, width: number) { + await gotoWorkspace(page, workspaceId); + await clickNewChat(page); + await expectComposerVisible(page); + await page.setViewportSize({ width, height: 900 }); + await page.getByRole("button", { name: /Select model/ }).click(); + if (width < 600) { + await page.getByTestId("agent-controls-model").click(); + } else { + await page.getByRole("button", { name: "Back", exact: true }).click(); + } + await page.getByTestId("model-provider-picker-timeout").click(); + await expect(page.getByText(/Timed out refreshing Pi timeout/)).toBeVisible(); +} + +async function expectErrorHasSideGutters(page: Page) { + const error = page.getByText(/Timed out refreshing Pi timeout/); + const bounds = await error.evaluate((element) => { + const text = element.getBoundingClientRect(); + const state = element.parentElement!.getBoundingClientRect(); + return { left: text.left - state.left, right: state.right - text.right }; + }); + expect(bounds.left, "error text stays inside the empty state's left edge").toBeGreaterThan(0); + expect(bounds.right, "error text stays inside the empty state's right edge").toBeGreaterThan(0); + await expect(page.getByRole("button", { name: "Retry", exact: true })).toBeVisible(); +} + +test.use({ + e2eDaemonConfig: { + version: 1, + agents: { + catalogRefreshTimeoutMs: 2000, + providers: { + "picker-timeout": { + extends: "pi", + label: "Pi timeout", + enabled: true, + command: [ + process.execPath, + path.resolve("e2e/fixtures/fake-pi-rpc.mjs"), + "--stall-model-discovery", + ], + }, + }, + }, + }, +}); + +test.describe("model discovery timeout", () => { + for (const width of [1200, 390]) { + test(`keeps a wrapped discovery error away from both picker edges at ${width}px`, async ({ + page, + withWorkspace, + }, testInfo) => { + await page.setViewportSize({ width: 1200, height: 900 }); + const workspace = await withWorkspace({ prefix: "model-error-spacing-" }); + await openTimedOutProvider(page, workspace.workspaceId, width); + await page.screenshot({ path: testInfo.outputPath("model-error.png") }); + await expectErrorHasSideGutters(page); + }); + } +}); diff --git a/packages/app/e2e/browser/settings-host-page.spec.ts b/packages/app/e2e/browser/settings-host-page.spec.ts index 76e5b331e6..f9b358a307 100644 --- a/packages/app/e2e/browser/settings-host-page.spec.ts +++ b/packages/app/e2e/browser/settings-host-page.spec.ts @@ -30,6 +30,10 @@ import { addDirectHostFromSettings, expectHostOnlineWithoutError, expectIdleAgentRelease, + editRestartRecoveryPrompt, + expectRestartRecoveryEnabled, + expectRestartRecoveryPrompt, + setRestartRecoveryEnabled, setIdleAgentRelease, } from "../support/helpers/settings"; @@ -252,3 +256,20 @@ test.describe("Settings host page", () => { await expectHostActionCards(page, serverId); }); }); + +test("restart recovery host controls persist the opt-out and custom prompt", async ({ page }) => { + const serverId = getServerId(); + await gotoAppShell(page); + await openSettings(page); + await openSettingsHost(page, serverId); + await openHostSection(page, serverId, "agents"); + await expectRestartRecoveryEnabled(page, true); + await expectRestartRecoveryPrompt(page, "Resume working."); + await editRestartRecoveryPrompt(page, "Continue the interrupted work."); + await setRestartRecoveryEnabled(page, false); + await page.reload(); + await expectRestartRecoveryEnabled(page, false); + await setRestartRecoveryEnabled(page, true); + await expectRestartRecoveryPrompt(page, "Continue the interrupted work."); + await editRestartRecoveryPrompt(page, "Resume working."); +}); diff --git a/packages/app/e2e/browser/settings-navigation.spec.ts b/packages/app/e2e/browser/settings-navigation.spec.ts index 4d7afbd4b9..aa381f1348 100644 --- a/packages/app/e2e/browser/settings-navigation.spec.ts +++ b/packages/app/e2e/browser/settings-navigation.spec.ts @@ -38,6 +38,9 @@ import { fillDirectHostUri, expectDirectHostFormValues, expectDirectHostSslEnabled, + expectDirectHostSslDisabled, + fillDirectHostAddress, + toggleDirectHostSsl, expectDirectHostUriValue, expectDirectHostUriHidden, expectDiagnosticsContent, @@ -284,6 +287,16 @@ test.describe("Settings sidebar navigation", () => { await expectAddHostMethodOptions(page); await selectHostConnectionType(page, "direct"); + await fillDirectHostAddress(page, "example.paseo.test", "7443"); + await expectDirectHostSslDisabled(page); + await toggleDirectHostSsl(page); + await expectDirectHostSslEnabled(page); + await toggleHostAdvanced(page); + await expectDirectHostUriValue(page, "tcp://example.paseo.test:7443?ssl=true"); + await toggleHostAdvanced(page); + await toggleDirectHostSsl(page); + await expectDirectHostSslDisabled(page); + await toggleHostAdvanced(page); await fillDirectHostUri(page, "tcp://example.paseo.test:7443?ssl=true&password=shared-secret"); await toggleHostAdvanced(page); @@ -479,3 +492,76 @@ test.describe("Settings — compact master-detail", () => { await expect(page.getByTestId("welcome-direct-connection")).toBeVisible(); }); }); + +async function measureDockedNavigation(page: import("@playwright/test").Page, width: number) { + await page.setViewportSize({ width, height: 951 }); + const history = page.getByRole("button", { name: /^History/ }).filter({ visible: true }); + const settings = page + .getByRole("button", { name: "Settings", exact: true }) + .filter({ visible: true }); + await expect(history).toBeVisible(); + await expect(settings).toBeVisible(); + return { + width, + history: await history.evaluate((el) => el.getBoundingClientRect().height), + settings: await settings.evaluate((el) => el.getBoundingClientRect().height), + }; +} + +async function measureSettingsSplit(page: import("@playwright/test").Page, width: number) { + await page.setViewportSize({ width, height: 951 }); + const sidebar = page.getByTestId("settings-sidebar"); + const detail = page.getByTestId("settings-detail-pane"); + await expect(sidebar).toBeVisible(); + await expect(detail).toBeVisible(); + return { + width, + sidebar: await sidebar.evaluate((el) => el.getBoundingClientRect().width), + detail: await detail.evaluate((el) => el.getBoundingClientRect().width), + }; +} + +async function expectConsistentDockedNavigation(page: import("@playwright/test").Page) { + const wide = await measureDockedNavigation(page, 951); + for (const width of [600, 669, 719, 720]) { + const narrow = await measureDockedNavigation(page, width); + expect + .soft(narrow.history, `History keeps its wide-layout density at ${width}`) + .toBeCloseTo(wide.history, 0); + expect + .soft(narrow.settings, `Settings keeps its wide-layout density at ${width}`) + .toBeCloseTo(wide.settings, 0); + } +} + +async function expectSettingsDetailKeepsReadingWidth(page: import("@playwright/test").Page) { + const reference = await measureSettingsSplit(page, 720); + for (const width of [600, 669, 719]) { + const narrow = await measureSettingsSplit(page, width); + expect + .soft(narrow.detail, `Settings preserves its detail budget at ${width}`) + .toBeGreaterThanOrEqual(reference.detail); + expect + .soft(narrow.sidebar, `Settings navigation yields width at ${width}`) + .toBeLessThan(reference.sidebar); + } + const wide = await measureSettingsSplit(page, 951); + expect(wide.sidebar).toBeCloseTo(reference.sidebar, 0); + expect(wide.detail).toBeGreaterThan(reference.detail); +} + +test("docked navigation keeps its density and Settings preserves reading width", async ({ + page, + withWorkspace, +}) => { + const workspace = await withWorkspace({ prefix: "narrow-wide-layout-" }); + await gotoWorkspace(page, workspace.workspaceId); + await expectConsistentDockedNavigation(page); + await openSettings(page); + await openSettingsSection(page, "appearance"); + await expectAppearanceContent(page); + await expectSettingsDetailKeepsReadingWidth(page); + await page.setViewportSize({ width: 599, height: 951 }); + await expectSettingsSidebarHidden(page); + await expectAppearanceContent(page); +}); diff --git a/packages/app/e2e/browser/sidebar-reorder.spec.ts b/packages/app/e2e/browser/sidebar-reorder.spec.ts index 03ffe9f7db..cf885a1d14 100644 --- a/packages/app/e2e/browser/sidebar-reorder.spec.ts +++ b/packages/app/e2e/browser/sidebar-reorder.spec.ts @@ -53,11 +53,18 @@ async function quickDragFirstRowAfterSecond( await page.mouse.move(source.x, source.y + 7); await expect(trailingScrim).toHaveCount(0); await page.mouse.move(target.x, target.y, { steps: 4 }); - await page.mouse.up(); + await finishSidebarDrag(page); await expect.poll(() => rowTestIds(rows)).toEqual([before[1], before[0]]); } +async function finishSidebarDrag(page: Page): Promise { + await page.mouse.up(); + // dnd-kit's pointer sensor keeps its document click blocker for 50 ms after drop. + // Row order updates before that blocker is removed; wait before the next user action. + await page.waitForTimeout(60); +} + async function dragWithoutReordering(rows: Locator): Promise { const before = await rowTestIds(rows); const source = await visibleBoundingBox(rows.nth(0)); @@ -66,7 +73,7 @@ async function dragWithoutReordering(rows: Locator): Promise { await page.mouse.move(source.x + source.width / 2, source.y + source.height / 2); await page.mouse.down(); await page.mouse.move(target.x + target.width / 2, target.y + target.height / 2, { steps: 5 }); - await page.mouse.up(); + await finishSidebarDrag(page); await expect.poll(() => rowTestIds(rows)).toEqual(before); } @@ -419,3 +426,81 @@ test("Manual restores pre-beta order and keeps drag order across sorting and rel await seed.cleanup(); } }); + +function workspaceRows(page: Page, ids: string[]) { + return page.locator( + ids.map((id) => `[data-testid="sidebar-workspace-row-${getServerId()}:${id}"]`).join(", "), + ); +} + +async function openWorkspaceRow(page: Page, workspaceId: string) { + await page.getByTestId(`sidebar-workspace-row-${getServerId()}:${workspaceId}`).click(); + await expect(page).toHaveURL(new RegExp(`/workspace/${workspaceId}`)); +} + +test("collapsed groups lead with the open workspace instead of hiding it behind Show more", async ({ + page, +}) => { + test.setTimeout(120_000); + const { seed, ids } = await seedCompactProject(); + try { + await gotoAppShell(page); + await waitForSidebarHydration(page); + await selectWorkspaceSort(page, "Created"); + const { rows, group } = compactProjectRows(page, seed); + await expectWorkspaceOrder(rows, ids.slice(0, 7)); + await revealWorkspaces(group, "Show more"); + await openWorkspaceRow(page, ids[9]!); + await expectWorkspaceOrder(rows, ids); + await revealWorkspaces(group, "Show less"); + await expectWorkspaceOrder(rows, [ids[9]!, ...ids.slice(0, 7)]); + await expect( + page.getByTestId(`sidebar-workspace-row-${getServerId()}:${ids[9]!}`), + ).toHaveAttribute("aria-selected", "true"); + await reconnectSidebar(page); + await expectWorkspaceOrder(rows, [ids[9]!, ...ids.slice(0, 7)]); + await expect( + page.getByTestId(`sidebar-workspace-row-${getServerId()}:${ids[9]!}`), + ).toHaveAttribute("aria-selected", "true"); + await openWorkspaceRow(page, ids[2]!); + await expectWorkspaceOrder(rows, ids.slice(0, 7)); + await expect( + page.getByTestId(`sidebar-workspace-row-${getServerId()}:${ids[2]!}`), + ).toHaveAttribute("aria-selected", "true"); + } finally { + await seed.cleanup(); + } +}); + +test("a Manual drag in a collapsed group keeps the open workspace's saved place", async ({ + page, +}) => { + test.setTimeout(120_000); + const { seed, ids } = await seedCompactProject(); + try { + await gotoAppShell(page); + await waitForSidebarHydration(page); + const projectKey = projectEquivalenceViewKey(seed.projectKey); + await restorePreBetaOrder( + page, + projectKey, + ids.map((id) => `${getServerId()}:${id}`), + ); + await selectWorkspaceSort(page, "Manual"); + const rows = workspaceRows(page, ids); + const toggle = page.getByTestId(`sidebar-project-show-more-${projectKey}`); + await expectWorkspaceOrder(rows, ids.slice(0, 7)); + await toggle.click(); + await openWorkspaceRow(page, ids[9]!); + await toggle.click(); + await expectWorkspaceOrder(rows, [ids[9]!, ...ids.slice(0, 7)]); + await quickDragFirstRowAfterSecond(workspaceRows(page, [ids[0]!, ids[1]!]), pressWorkspaceRow); + await expectWorkspaceOrder(rows, [ids[9]!, ids[1]!, ids[0]!, ...ids.slice(2, 7)]); + await reconnectSidebar(page); + await expectWorkspaceOrder(rows, [ids[9]!, ids[1]!, ids[0]!, ...ids.slice(2, 7)]); + await toggle.click(); + await expectWorkspaceOrder(rows, [ids[1]!, ids[0]!, ...ids.slice(2)]); + } finally { + await seed.cleanup(); + } +}); diff --git a/packages/app/e2e/browser/split-pane-drag-tracking.spec.ts b/packages/app/e2e/browser/split-pane-drag-tracking.spec.ts new file mode 100644 index 0000000000..90420c6fd9 --- /dev/null +++ b/packages/app/e2e/browser/split-pane-drag-tracking.spec.ts @@ -0,0 +1,134 @@ +import { expect, type Locator, type Page } from "@playwright/test"; +import { test } from "../support/fixtures"; +import { runWorkspaceActionFromCommandCenter } from "../support/helpers/command-center-workspace-actions"; +import { createCreationScenario } from "../support/helpers/creation"; +import { clickNewChat, gotoWorkspace } from "../support/helpers/launcher"; +import { seedWorkspace } from "../support/helpers/seed-client"; +import { waitForWorkspaceTabsVisible } from "../support/helpers/workspace-tabs"; + +const DRAG_DISTANCE = -40; +const TOLERANCE_PX = 2; + +function splitDividers(page: Page): Locator { + return page.getByTestId("workspace-split-resize-handle").filter({ visible: true }); +} + +async function dividerX(divider: Locator): Promise { + const box = await divider.boundingBox(); + if (!box) throw new Error("Divider has no bounding box"); + return box.x; +} + +async function dragDivider(divider: Locator, deltaX: number): Promise { + const page = divider.page(); + const box = await divider.boundingBox(); + if (!box) throw new Error("Divider has no bounding box"); + const x = box.x + box.width / 2; + const y = box.y + box.height / 2; + await page.mouse.move(x, y); + await page.mouse.down(); + await page.mouse.move(x + deltaX, y, { steps: 8 }); + await page.mouse.up(); +} + +async function dragDividerWithTouch(divider: Locator, deltaX: number): Promise { + const page = divider.page(); + const box = await divider.boundingBox(); + if (!box) throw new Error("Divider has no bounding box"); + const x = box.x + box.width / 2; + const y = box.y + box.height / 2; + const input = await page.context().newCDPSession(page); + try { + await input.send("Input.dispatchTouchEvent", { type: "touchStart", touchPoints: [{ x, y }] }); + for (let step = 1; step <= 8; step++) { + await input.send("Input.dispatchTouchEvent", { + type: "touchMove", + touchPoints: [{ x: x + (deltaX * step) / 8, y }], + }); + } + await input.send("Input.dispatchTouchEvent", { type: "touchEnd", touchPoints: [] }); + } finally { + await input.detach(); + } +} + +async function splitIntoFourPanes(page: Page): Promise { + for (const expectedDividers of [1, 2, 3]) { + await runWorkspaceActionFromCommandCenter(page, "Split pane right"); + await expect(splitDividers(page)).toHaveCount(expectedDividers); + } +} + +async function expectDividersTrackPointer( + page: Page, + distance = DRAG_DISTANCE, + drag = dragDivider, +): Promise { + for (const index of [0, 1, 2]) { + const divider = splitDividers(page).nth(index); + const before = await dividerX(divider); + await drag(divider, distance); + await expect + .poll(async () => Math.abs((await dividerX(divider)) - before - distance), { + message: `divider ${index + 1} should stay under the pointer`, + }) + .toBeLessThanOrEqual(TOLERANCE_PX); + } +} + +for (const hasTouch of [false, true]) { + test.describe(`Split pane drag tracking (${hasTouch ? "coarse" : "fine"} pointer)`, () => { + test.use({ hasTouch }); + + test("a divider moves as far as the pointer in the main row", async ({ page }) => { + await page.setViewportSize({ width: 1600, height: 900 }); + const workspace = await seedWorkspace({ repoPrefix: "split-drag-tracking-" }); + try { + await gotoWorkspace(page, workspace.workspaceId); + await waitForWorkspaceTabsVisible(page); + await clickNewChat(page); + await splitIntoFourPanes(page); + await expectDividersTrackPointer( + page, + DRAG_DISTANCE, + hasTouch ? dragDividerWithTouch : dragDivider, + ); + } finally { + await workspace.cleanup(); + } + }); + + test("dividers track the pointer after app creation, Explorer changes and reload", async ({ + page, + }) => { + await page.setViewportSize({ width: 1600, height: 900 }); + const creation = await createCreationScenario(page); + try { + await creation.openWorkspaceForm("local"); + await creation.submitPrompt("Reply briefly.", "Create"); + await creation.expectAssistantReply(); + await waitForWorkspaceTabsVisible(page); + await splitIntoFourPanes(page); + await expectDividersTrackPointer(page); + await page + .getByTestId("workspace-explorer-toggle") + .filter({ visible: true }) + .first() + .click(); + await expect(page.getByTestId("workspace-explorer-sidebar")).toBeVisible(); + await expectDividersTrackPointer(page, -DRAG_DISTANCE); + await page + .getByTestId("workspace-explorer-toggle") + .filter({ visible: true }) + .first() + .click(); + await expect(page.getByTestId("workspace-explorer-sidebar")).not.toBeVisible(); + await page.reload(); + await expect(splitDividers(page)).toHaveCount(3); + await expectDividersTrackPointer(page); + } finally { + await creation.cleanup(); + } + }); + }); +} diff --git a/packages/app/e2e/browser/terminal-retained-tab-stream.spec.ts b/packages/app/e2e/browser/terminal-retained-tab-stream.spec.ts index c3481110f7..d0dbe9be23 100644 --- a/packages/app/e2e/browser/terminal-retained-tab-stream.spec.ts +++ b/packages/app/e2e/browser/terminal-retained-tab-stream.spec.ts @@ -1,5 +1,10 @@ import type { Page } from "@playwright/test"; import { expect, test } from "../support/fixtures"; +import { + expectTerminalCursor, + getTerminalBufferText, + waitForTerminalContent, +} from "../support/helpers/terminal-perf"; import { TerminalE2EHarness } from "../support/helpers/terminal-dsl"; interface AttachOverlayProbeWindow extends Window { @@ -59,4 +64,65 @@ test.describe("retained terminal tab streams", () => { expect(await terminalAttachOverlayWasSeen(page)).toBe(false); }); + + for (const { count, retainedMarker } of [ + { count: 3000, retainedMarker: "history-0001界🙂" }, + { count: 12050, retainedMarker: "history-3000界🙂" }, + ]) { + test(`reattach restores retained styled Unicode history from ${count} lines`, async ({ + page, + }) => { + await page.addInitScript(() => { + const key = "@paseo:app-settings"; + const settings = JSON.parse(localStorage.getItem(key) ?? "{}"); + localStorage.setItem(key, JSON.stringify({ ...settings, terminalScrollbackLines: 10000 })); + }); + const terminal = await harness.createTerminal({ + name: `history-${count}`, + command: "/bin/sh", + args: [ + "-lc", + `i=1; while [ $i -le ${count} ]; do printf '\\033[31mhistory-%04d界🙂 payload-abcdefghijklmnopqrstuvwxyz0123456789\\033[0m\\n' $i; i=$((i+1)); done; sleep 120`, + ], + }); + const last = `history-${String(count).padStart(4, "0")}界🙂`; + await harness.openTerminal(page, { terminalId: terminal.id }); + await waitForTerminalContent(page, (text) => text.includes(last), 10000); + expect(await getTerminalBufferText(page)).toContain(retainedMarker); + await page.reload(); + await waitForTerminalContent(page, (text) => text.includes(last), 10000); + const restored = await getTerminalBufferText(page); + expect(restored).toContain(retainedMarker); + expect(restored.match(/history-\d{4,5}/g)?.length).toBeGreaterThanOrEqual( + Math.min(count, 10000), + ); + if (count > 10000) expect(restored).not.toContain("history-0001界🙂"); + }); + } + for (const input of [ + { name: "client blinking bar", presentation: "", shape: "bar" as const, blinking: true }, + { + name: "program blinking underline", + presentation: "\x1b[3 q", + shape: "underline" as const, + blinking: true, + }, + ]) { + test(`reattach preserves the ${input.name} cursor`, async ({ page }) => { + const terminal = await harness.createTerminal({ + name: "cursor-presentation", + command: process.execPath, + args: [ + "-e", + `process.stdout.write(${JSON.stringify(input.presentation + "CURSOR-READY\r\n")});setInterval(()=>{},1000)`, + ], + }); + await harness.openTerminal(page, { terminalId: terminal.id }); + await waitForTerminalContent(page, (text) => text.includes("CURSOR-READY"), 10000); + await expectTerminalCursor(page, input); + await page.reload(); + await waitForTerminalContent(page, (text) => text.includes("CURSOR-READY"), 10000); + await expectTerminalCursor(page, input); + }); + } }); diff --git a/packages/app/e2e/browser/tool-call-overview-sheet.spec.ts b/packages/app/e2e/browser/tool-call-overview-sheet.spec.ts index 42831fad8a..0b3a068e63 100644 --- a/packages/app/e2e/browser/tool-call-overview-sheet.spec.ts +++ b/packages/app/e2e/browser/tool-call-overview-sheet.spec.ts @@ -1,8 +1,15 @@ -import type { Page } from "@playwright/test"; +import type { Locator, Page } from "@playwright/test"; import { test, expect } from "../support/fixtures"; +import { scrollChatAwayFromBottom } from "../support/helpers/agent-bottom-anchor"; +import { gateSecondToolCall } from "../support/helpers/tool-call-gate"; import { expectComposerVisible } from "../support/helpers/composer"; import { daemonWsRoutePattern } from "../support/helpers/daemon-port"; import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent"; +import { + readReactRenders, + recordReactRenders, + resetReactRenders, +} from "../support/helpers/react-renders"; type WebSocketMessage = string | Buffer; @@ -115,23 +122,27 @@ async function holdStreamAfterFirstCompletedToolCall(page: Page, agentId: string }); }); + function appendCompletedCalls(extraCompletedCalls: number) { + if (extraCompletedCalls > 0 && (!firstCallId || !firstCompletedMessage)) { + throw new Error("Expected the first completed tool call before release"); + } + for (let index = 0; index < extraCompletedCalls; index += 1) { + sendToPage?.( + cloneToolCallWithId( + firstCompletedMessage as WebSocketMessage, + `${firstCallId}:${sequenceOffset + index}`, + sequenceOffset + index + 1, + ), + ); + } + sequenceOffset += extraCompletedCalls; + } return { waitForFirstCompleted: () => firstCompleted, + appendCompletedCalls, release(extraCompletedCalls = 0) { isHolding = false; - if (extraCompletedCalls > 0 && (!firstCallId || !firstCompletedMessage)) { - throw new Error("Expected the first completed tool call before release"); - } - for (let index = 0; index < extraCompletedCalls; index += 1) { - sendToPage?.( - cloneToolCallWithId( - firstCompletedMessage as WebSocketMessage, - `${firstCallId}:${index}`, - index + 1, - ), - ); - } - sequenceOffset = extraCompletedCalls; + appendCompletedCalls(extraCompletedCalls); for (const message of heldMessages.splice(0)) { sendToPage?.(shiftTimelineSequence(message, sequenceOffset)); } @@ -139,17 +150,24 @@ async function holdStreamAfterFirstCompletedToolCall(page: Page, agentId: string }; } -async function configureOverviewToolCalls(page: Page): Promise { - await page.addInitScript(() => { +type OverviewChatDisplay = "collapseToolCalls" | "collapseTurns"; + +// Expand thinking keeps reasoning out of tool call runs, so the first tool call starts alone. +async function configureOverviewToolCalls(page: Page, chatDisplay: OverviewChatDisplay) { + await page.addInitScript((display) => { localStorage.setItem( "@paseo:app-settings", - JSON.stringify({ chatDisplay: "collapseToolCalls" }), + JSON.stringify({ chatDisplay: display, autoExpandReasoning: true }), ); - }); + }, chatDisplay); } -async function createOverviewAgent(page: Page, title: string) { - await configureOverviewToolCalls(page); +async function createOverviewAgent( + page: Page, + title: string, + chatDisplay: OverviewChatDisplay = "collapseToolCalls", +) { + await configureOverviewToolCalls(page, chatDisplay); return seedMockAgentWorkspace({ repoPrefix: "tool-call-overview-sheet-", title, @@ -204,6 +222,36 @@ function readScrollMetrics(root: HTMLElement) { }; } +const FIRST_CALL_DETAILS = "export function ConversationList()"; + +function firstToolCall(page: Page): Locator { + return page.getByTestId("tool-call-badge").filter({ hasText: "conversation-list.tsx" }).first(); +} + +async function openToolDetails(badge: Locator): Promise { + await badge.getByRole("button").first().click(); +} + +async function timelineRowOf(locator: Locator) { + const row = await locator.locator("xpath=ancestor::*[@data-history-row-id][1]").elementHandle(); + if (!row) throw new Error("Expected the locator inside a timeline row"); + return row; +} + +/** Whether the locator renders inside this exact row node, i.e. the row was not remounted. */ +async function isInsideRow( + locator: Locator, + row: Awaited>, +): Promise { + return locator.evaluate((node, previousRow) => previousRow.contains(node), row); +} + +async function topOf(row: Locator): Promise { + const box = await row.boundingBox(); + if (!box) throw new Error("Expected a visible timeline row"); + return box.y; +} + test.describe("compact overview tool calls", () => { test.use({ viewport: COMPACT_VIEWPORT, hasTouch: true }); @@ -219,8 +267,16 @@ test.describe("compact overview tool calls", () => { await agent.client.sendAgentMessage(agent.agentId, "Exercise the overview tool-call sheet."); await gate.waitForFirstCompleted(); + const single = firstToolCall(page); + await expect(single).toBeVisible(); + await expect(page.getByTestId("tool-call-group")).toHaveCount(0); + await openToolDetails(single); + await expect(page.getByTestId("tool-call-sheet-close")).toBeVisible(); + await page.getByTestId("tool-call-sheet-close").click(); + gate.appendCompletedCalls(1); const group = page.getByTestId("tool-call-group").first(); await expect(group).toBeVisible(); + await expect(page.getByTestId("tool-call-group-sheet")).toBeHidden(); await group.click(); const sheet = page.getByTestId("tool-call-group-sheet"); @@ -261,27 +317,86 @@ test.describe("compact overview tool calls", () => { }); }); -test("keeps overview tool calls inline on desktop", async ({ page }) => { +for (const display of ["collapseToolCalls", "collapseTurns"] as const) { + test(`keeps an opened lone tool call open when it becomes a group (${display})`, async ({ + page, + }) => { + test.setTimeout(120_000); + const agent = await createOverviewAgent(page, "Desktop overview tool calls", display); + await recordReactRenders(page); + try { + const gate = await gateSecondToolCall(page, agent.agentId); + await openOverviewAgent(page, agent); + await agent.client.sendAgentMessage(agent.agentId, "Exercise desktop overview tool calls."); + await gate.waitForFirstCompleted(); + const lone = firstToolCall(page); + const group = page.getByTestId("tool-call-group").first(); + const details = page.getByText(FIRST_CALL_DETAILS); + + await test.step("a lone tool call shows as itself", async () => { + await expect(lone).toBeVisible(); + await expect(group).toHaveCount(0); + }); + + await gate.waitForSecondRunning(); + await test.step("opening it re-renders that tool call and nothing else", async () => { + await resetReactRenders(page); + await openToolDetails(lone); + await expect(details).toBeVisible(); + const renders = await readReactRenders(page); + expect(renders.AgentStreamView ?? 0).toBe(0); + expect(renders.StreamRowContent ?? 0).toBe(0); + expect(renders.ToolCall).toBe(1); + }); + + await test.step("the second call forms an open group around the opened call", async () => { + // Reading above the tail, the row holds still; at the tail the new rows push it up. + await scrollChatAwayFromBottom(page, { deltaY: -160, minDistanceFromBottom: 72 }); + const loneTop = await topOf(lone); + const loneRow = await timelineRowOf(lone); + await resetReactRenders(page); + gate.releaseSecondRunning(); + await expect(group.getByTestId("tool-call-badge")).toHaveCount(2); + await expect(group.getByText(FIRST_CALL_DETAILS)).toBeVisible(); + expect(await isInsideRow(group, loneRow)).toBe(true); + expect(Math.abs((await topOf(group)) - loneTop)).toBeLessThanOrEqual(2); + expect((await readReactRenders(page)).AgentStreamView).toBeGreaterThan(0); + await expect(page.getByTestId("tool-call-group-sheet")).toHaveCount(0); + }); + + await test.step("closing and reopening the group keeps the call open", async () => { + await openToolDetails(group); + await expect(group.getByTestId("tool-call-badge")).toHaveCount(0); + await expect(details).toHaveCount(0); + await openToolDetails(group); + await expect(group.getByTestId("tool-call-badge")).toHaveCount(2); + await expect(group.getByText(FIRST_CALL_DETAILS)).toBeVisible(); + }); + } finally { + await agent.cleanup(); + } + }); +} + +test("forms a closed group when the lone tool call was left closed", async ({ page }) => { test.setTimeout(120_000); - const agent = await createOverviewAgent(page, "Desktop overview tool calls"); - + const agent = await createOverviewAgent(page, "Closed desktop overview tool calls"); try { - const gate = await holdStreamAfterFirstCompletedToolCall(page, agent.agentId); + const gate = await gateSecondToolCall(page, agent.agentId); await openOverviewAgent(page, agent); - await agent.client.sendAgentMessage(agent.agentId, "Exercise desktop overview tool calls."); + await agent.client.sendAgentMessage(agent.agentId, "Leave the first tool call closed."); await gate.waitForFirstCompleted(); + const lone = firstToolCall(page); const group = page.getByTestId("tool-call-group").first(); + await expect(lone).toBeVisible(); + await expect(group).toHaveCount(0); + + await gate.waitForSecondRunning(); + const loneTop = await topOf(lone); + gate.releaseSecondRunning(); await expect(group).toBeVisible(); - - // Keep streaming layout changes out of the pointer-down/pointer-up interval. - const header = group.getByRole("button").first(); - await header.click(); - await expect(group.getByTestId("tool-call-badge").first()).toBeVisible(); - await expect(page.getByTestId("tool-call-group-sheet")).toHaveCount(0); - - gate.release(1); - await expect.poll(() => group.getByTestId("tool-call-badge").count()).toBeGreaterThanOrEqual(2); - await expect(page.getByTestId("tool-call-group-sheet")).toHaveCount(0); + await expect(group.getByTestId("tool-call-badge")).toHaveCount(0); + expect(Math.abs((await topOf(group)) - loneTop)).toBeLessThanOrEqual(2); } finally { await agent.cleanup(); } diff --git a/packages/app/e2e/browser/tool-call-shimmer.spec.ts b/packages/app/e2e/browser/tool-call-shimmer.spec.ts index 40dde0aa99..c37255d35e 100644 --- a/packages/app/e2e/browser/tool-call-shimmer.spec.ts +++ b/packages/app/e2e/browser/tool-call-shimmer.spec.ts @@ -1,11 +1,9 @@ -import type { Locator, Page } from "@playwright/test"; +import type { Locator } from "@playwright/test"; import { test, expect } from "../support/fixtures"; -import { daemonWsRoutePattern } from "../support/helpers/daemon-port"; +import { gateSecondToolCall } from "../support/helpers/tool-call-gate"; import { expectComposerVisible } from "../support/helpers/composer"; import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent"; -type WebSocketMessage = string | Buffer; - interface ShimmerEvidence { animationDuration: string; endPx: number; @@ -14,127 +12,6 @@ interface ShimmerEvidence { startPx: number; } -function parseSessionMessage(message: WebSocketMessage): Record | null { - const raw = typeof message === "string" ? message : message.toString("utf8"); - try { - const envelope = JSON.parse(raw) as { type?: unknown; message?: unknown }; - return envelope.type === "session" && envelope.message && typeof envelope.message === "object" - ? (envelope.message as Record) - : null; - } catch { - return null; - } -} - -function getToolCallStatus( - message: WebSocketMessage, - agentId: string, -): { callId: string; status: string } | null { - const sessionMessage = parseSessionMessage(message); - if (sessionMessage?.type !== "agent_stream") { - return null; - } - const payload = sessionMessage.payload as Record | undefined; - if (payload?.agentId !== agentId) { - return null; - } - const event = payload.event as Record | undefined; - const item = event?.item as Record | undefined; - return event?.type === "timeline" && - item?.type === "tool_call" && - typeof item.callId === "string" && - typeof item.status === "string" - ? { callId: item.callId, status: item.status } - : null; -} - -function replaceToolCallStatus(message: WebSocketMessage, status: string): string { - const raw = typeof message === "string" ? message : message.toString("utf8"); - const envelope = JSON.parse(raw) as { - message?: { payload?: { event?: { item?: { status?: string } } } }; - }; - const item = envelope.message?.payload?.event?.item; - if (!item) { - throw new Error("Expected a tool-call session message"); - } - item.status = status; - return JSON.stringify(envelope); -} - -async function gateSecondToolCall(page: Page, agentId: string) { - let firstCallId: string | null = null; - let secondCallId: string | null = null; - let secondRunningMessage: WebSocketMessage | null = null; - let pauseAfterSecondRunning = false; - let releaseSecondRequested = false; - let forwardSecondRunning: (() => void) | null = null; - let resolveFirstCompleted!: () => void; - let resolveSecondRunning!: () => void; - const firstCompleted = new Promise((resolve) => { - resolveFirstCompleted = resolve; - }); - const secondRunning = new Promise((resolve) => { - resolveSecondRunning = resolve; - }); - - await page.routeWebSocket(daemonWsRoutePattern(), (ws) => { - const server = ws.connectToServer(); - forwardSecondRunning = () => { - if (secondRunningMessage) { - ws.send(secondRunningMessage); - secondRunningMessage = null; - } - }; - ws.onMessage((message) => server.send(message)); - server.onMessage((message) => { - if (pauseAfterSecondRunning) { - return; - } - - const toolCall = getToolCallStatus(message, agentId); - if (!toolCall) { - ws.send(message); - return; - } - - if (!firstCallId) { - firstCallId = toolCall.callId; - } - if (toolCall.callId === firstCallId) { - ws.send(message); - if (toolCall.status === "completed") { - resolveFirstCompleted(); - } - return; - } - - secondCallId ??= toolCall.callId; - if (toolCall.callId === secondCallId) { - const transformedMessage = - toolCall.status === "completed" ? replaceToolCallStatus(message, "running") : message; - secondRunningMessage = transformedMessage; - pauseAfterSecondRunning = true; - resolveSecondRunning(); - if (releaseSecondRequested) { - forwardSecondRunning?.(); - } - return; - } - - ws.send(message); - }); - }); - - return { - waitForFirstCompleted: () => firstCompleted, - waitForSecondRunning: () => secondRunning, - releaseSecondRunning() { - releaseSecondRequested = true; - forwardSecondRunning?.(); - }, - }; -} - async function readShimmerEvidence(locator: Locator): Promise { return locator.evaluate((root) => { const shimmer = Array.from(root.querySelectorAll("*")).find((element) => diff --git a/packages/app/e2e/browser/turn-collapse.spec.ts b/packages/app/e2e/browser/turn-collapse.spec.ts index 1deb050fa8..d990e33009 100644 --- a/packages/app/e2e/browser/turn-collapse.spec.ts +++ b/packages/app/e2e/browser/turn-collapse.spec.ts @@ -1,8 +1,29 @@ -import type { Page } from "@playwright/test"; +import type { DaemonClient } from "@getpaseo/client/internal/daemon-client"; +import path from "node:path"; +import { + holdOlderHistoryPages, + userScrollsTimelineToHistoryStart, +} from "../support/helpers/timeline-pagination"; +import { getActiveTabTestId } from "../support/helpers/launcher"; +import type { Page, Locator } from "@playwright/test"; import { test, expect } from "../support/fixtures"; import { expectComposerVisible } from "../support/helpers/composer"; import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent"; +test.use({ + e2eDaemonConfig: { + version: 1, + agents: { + providers: { + codex: { + enabled: true, + command: [process.execPath, path.resolve("e2e/fixtures/catalog-codex.mjs")], + }, + }, + }, + }, +}); + type ChatDisplay = "full" | "collapseToolCalls" | "collapseTurns"; async function useChatDisplay(page: Page, chatDisplay: ChatDisplay): Promise { @@ -19,7 +40,10 @@ async function seedAnsweredAgent(title: string) { initialPrompt: "Why does the chat stop following new output?", }); await agent.client.waitForFinish(agent.agentId, 30_000); - await agent.client.sendAgentMessage(agent.agentId, "Make the fix and run the burst script."); + await agent.client.sendAgentMessage( + agent.agentId, + "Make the fix and run the burst script.\n" + "Keep the previous response visible.\n".repeat(40), + ); await agent.client.waitForFinish(agent.agentId, 30_000); return agent; } @@ -36,17 +60,84 @@ async function rowsBetweenLatestSummaryAndReply(page: Page): Promise { }); } +async function groupedToolsInsideLatestTurn(page: Page): Promise { + return page.evaluate(() => { + const rows = [...document.querySelectorAll("[data-message-id]")]; + const start = rows.findLastIndex((row) => row.querySelector("[data-testid=turn-summary]")); + const end = rows.findLastIndex((row) => row.querySelector("[data-testid=assistant-message]")); + return rows + .slice(start + 1, end) + .flatMap((row) => + [...row.querySelectorAll("[data-testid=tool-call-group]")].map( + (group) => group.textContent ?? "", + ), + ); + }); +} + +async function expectCompactMessageToggle(prompt: Locator, label: string) { + const button = prompt.getByRole("button", { name: label, exact: true }); + const text = prompt.getByText(label, { exact: true }); + await expect + .poll( + async () => { + const control = (await button.boundingBox())!; + const glyphs = (await text.boundingBox())!; + return control.height - glyphs.height; + }, + { message: "The inline toggle adds no vertical space beyond its text" }, + ) + .toBe(0); +} + +async function expandAndCollapseLongPrompt(page: Page) { + const prompt = page.getByTestId("user-message").last(); + const before = await prompt.boundingBox(); + const text = prompt.locator('[data-message-text="true"]'); + const messageLeft = (await text.boundingBox())!.x; + await expect + .poll(async () => (await prompt.getByText("Show more", { exact: true }).boundingBox())!.x) + .toBe(messageLeft); + await expectCompactMessageToggle(prompt, "Show more"); + await prompt.getByRole("button", { name: "Show more", exact: true }).click(); + await expect(prompt.getByRole("button", { name: "Show less", exact: true })).toBeVisible(); + await expect + .poll(async () => (await prompt.getByText("Show less", { exact: true }).boundingBox())!.x) + .toBe(messageLeft); + await expect + .poll(async () => (await prompt.boundingBox())?.height ?? 0) + .toBeGreaterThan(before!.height); + await expectCompactMessageToggle(prompt, "Show less"); + await prompt.getByRole("button", { name: "Show less", exact: true }).click(); + await expect.poll(async () => (await prompt.boundingBox())?.height ?? 0).toBe(before!.height); + await prompt.scrollIntoViewIfNeeded(); + const bounds = (await prompt.boundingBox())!; + const body = (await text.boundingBox())!; + await page.screenshot({ + path: "/tmp/message-toggle-aligned.png", + clip: { + x: body.x - 16, + y: bounds.y, + width: bounds.x + bounds.width - body.x + 16, + height: bounds.height, + }, + }); +} + test.describe("Turn collapse", () => { test("folds each answered turn behind a summary line that opens it", async ({ page }) => { test.setTimeout(120_000); + await page.setViewportSize({ width: 1280, height: 1000 }); await useChatDisplay(page, "collapseTurns"); const agent = await seedAnsweredAgent("Turn collapse"); try { await openAgentRoute(page, agent); await expectComposerVisible(page); + await expandAndCollapseLongPrompt(page); + const summary = page.getByTestId("turn-summary").last().getByRole("button"); - await expect(summary).toHaveText(/^Wrote \d+ messages?, edited 1 file/); + await expect(summary).toHaveText(/^Edited 1 file/); // Text chunks that stream back to back merge into one message, so the reply holds // at least the stream's last chunk. await expect(page.getByTestId("assistant-message").last()).toHaveText( @@ -57,6 +148,9 @@ test.describe("Turn collapse", () => { await summary.click(); await expect.poll(() => rowsBetweenLatestSummaryAndReply(page)).toBeGreaterThan(0); await expect(summary).toBeInViewport(); + await summary.evaluate((element) => element.scrollIntoView({ block: "start" })); + await page.screenshot({ path: "/tmp/turn-rail-aligned.png" }); + await expect.poll(() => groupedToolsInsideLatestTurn(page)).toEqual([]); await summary.click(); await expect.poll(() => rowsBetweenLatestSummaryAndReply(page)).toBe(0); @@ -65,3 +159,455 @@ test.describe("Turn collapse", () => { } }); }); + +test("received messages show their sender and open that agent", async ({ page }) => { + await page.addInitScript(() => + localStorage.setItem("@paseo:app-settings", JSON.stringify({ theme: "dark" })), + ); + const recipient = await seedMockAgentWorkspace({ + repoPrefix: "sender-attribution-", + title: "Implementation", + }); + try { + const sender = await recipient.client.createAgent({ + provider: "codex", + cwd: recipient.cwd, + workspaceId: recipient.workspaceId, + title: "Reviewer", + model: "gpt-6.1-sol", + modeId: "full-access", + }); + await recipient.client.sendAgentMessage( + recipient.agentId, + "I reviewed the turn-grouping changes. Heartbeats now keep their own timing footer, and the previous response stays visible.", + { sourceAgentId: sender.id }, + ); + await openAgentRoute(page, recipient); + await expectComposerVisible(page); + const attribution = page.getByRole("button", { name: "Sent by Reviewer", exact: true }); + await expect(attribution).toBeVisible(); + await expect(page.getByTestId("user-message").filter({ has: attribution })).toContainText( + "I reviewed the turn-grouping changes.", + ); + const labelColor = await attribution + .getByText("Sent by Reviewer", { exact: true }) + .evaluate((element) => getComputedStyle(element).color); + await expect(attribution.locator("svg")).toHaveCSS("fill", labelColor); + await expectSenderAlignedWithBubble(attribution); + await attribution.scrollIntoViewIfNeeded(); + await page.screenshot({ path: "/tmp/sender-attribution.png" }); + await attribution.click(); + await expect.poll(() => getActiveTabTestId(page)).toContain(sender.id); + } finally { + await recipient.cleanup(); + } +}); + +test("long sender attribution stays on one line in compact chat", async ({ page }, testInfo) => { + await page.setViewportSize({ width: 390, height: 844 }); + await page.addInitScript(() => + localStorage.setItem("@paseo:app-settings", JSON.stringify({ theme: "dark" })), + ); + const recipient = await seedMockAgentWorkspace({ + repoPrefix: "compact-attribution-", + title: "Implementation", + }); + try { + const title = "Reviewer checking the compact chat timeline and sender attribution"; + const sender = await recipient.client.createAgent({ + provider: "codex", + cwd: recipient.cwd, + workspaceId: recipient.workspaceId, + title, + model: "gpt-6.1-sol", + modeId: "full-access", + }); + await recipient.client.sendAgentMessage( + recipient.agentId, + "The sender label stays on one line, even when the agent has a long name.", + { sourceAgentId: sender.id }, + ); + await openAgentRoute(page, recipient); + await expectComposerVisible(page); + const attribution = page.getByRole("button", { name: `Sent by ${title}`, exact: true }); + await expect(attribution).toBeVisible(); + await expectSenderTruncatedWithinMessage(attribution, title); + await expectSenderAlignedWithBubble(attribution); + await attribution.scrollIntoViewIfNeeded(); + await page.screenshot({ path: testInfo.outputPath("sender-compact-390.png") }); + await page.setViewportSize({ width: 320, height: 740 }); + await expectSenderTruncatedWithinMessage(attribution, title); + await expectSenderAlignedWithBubble(attribution); + await page.screenshot({ path: testInfo.outputPath("sender-compact-320.png") }); + } finally { + await recipient.cleanup(); + } +}); + +interface MessagePreviewWatch { + /** Frames after the watch started on which the fade or "Show more" control was missing. */ + framesWithoutClip: number[]; + /** Frames on which the fade was a different DOM node than when the watch started. */ + framesRemounted: number[]; +} + +declare global { + interface Window { + __paseoMessagePreviewWatch?: { stop(): MessagePreviewWatch }; + } +} + +async function seedReceivedReviewWithToolTurn() { + const recipient = await seedMockAgentWorkspace({ + repoPrefix: "preview-clip-", + title: "Implementation", + }); + const sender = await recipient.client.createAgent({ + provider: "mock", + cwd: recipient.cwd, + workspaceId: recipient.workspaceId, + title: "Reviewer", + modeId: "load-test", + model: "e2e-fast-stream", + }); + // Long enough to clip behind the preview fade; the instruction makes the recipient run tools. + await recipient.client.sendAgentMessage( + recipient.agentId, + "Review complete: the regression is red on the baseline and green with the fix.\n" + + "Keep the previous response visible while the reader scrolls.\n".repeat(30) + + "Now emit 7 tool agent stream updates", + { sourceAgentId: sender.id }, + ); + return recipient; +} + +/** Samples the received message's bubble on every animation frame until stopped. */ +async function watchReceivedMessagePreview(page: Page, senderLabel: string): Promise { + await page.evaluate((label) => { + const findBubble = () => + [...document.querySelectorAll("[data-testid=user-message]")].find((row) => + row.textContent?.includes(label), + ) ?? null; + const initialFade = findBubble()?.querySelector("svg") ?? null; + if (!initialFade) throw new Error(`No faded bubble for ${label}`); + const framesWithoutClip: number[] = []; + const framesRemounted: number[] = []; + let frame = 0; + let running = true; + const sample = () => { + if (!running) return; + const bubble = findBubble(); + const fade = bubble?.querySelector("svg") ?? null; + if (!fade || !bubble?.textContent?.includes("Show more")) framesWithoutClip.push(frame); + else if (fade !== initialFade) framesRemounted.push(frame); + frame += 1; + requestAnimationFrame(sample); + }; + requestAnimationFrame(sample); + window.__paseoMessagePreviewWatch = { + stop() { + running = false; + return { framesWithoutClip, framesRemounted }; + }, + }; + }, senderLabel); +} + +async function expectReceivedMessagePreviewUndisturbed(page: Page): Promise { + // Give the opened turn's layout a few frames to settle before judging. + await page.evaluate( + () => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))), + ); + const watch = await page.evaluate(() => window.__paseoMessagePreviewWatch!.stop()); + expect( + watch.framesWithoutClip, + "the preview fade and Show more control stay on every frame", + ).toEqual([]); + expect(watch.framesRemounted, "the preview keeps its DOM node (no remount)").toEqual([]); +} + +// Opening a turn must not rebuild its host row: the preview above the summary loses its +// measured height when remounted, which drops the fade and "Show more" for a frame. +test("opening a turn keeps the received message above it clipped on every frame", async ({ + page, +}) => { + await useChatDisplay(page, "collapseTurns"); + const recipient = await seedReceivedReviewWithToolTurn(); + try { + await openAgentRoute(page, recipient); + await expectComposerVisible(page); + await expect(page.getByText("Completed 7 commands", { exact: true })).toBeVisible({ + timeout: 30_000, + }); + const bubble = page + .getByTestId("user-message") + .filter({ has: page.getByRole("button", { name: "Sent by Reviewer", exact: true }) }); + await expect(bubble.getByRole("button", { name: "Show more", exact: true })).toBeVisible(); + await bubble.scrollIntoViewIfNeeded(); + + await watchReceivedMessagePreview(page, "Sent by Reviewer"); + await page + .getByTestId("turn-summary") + .getByRole("button", { name: "Ran 7 commands", exact: true }) + .click(); + await expect(page.getByText("echo stress-6", { exact: true })).toBeVisible(); + await expectReceivedMessagePreviewUndisturbed(page); + } finally { + await recipient.cleanup(); + } +}); + +async function expectSenderTruncatedWithinMessage(attribution: Locator, title: string) { + const label = attribution.getByText(`Sent by ${title}`, { exact: true }); + await expect(label).toHaveCSS("white-space", "nowrap"); + await expect(label).toHaveCSS("text-overflow", "ellipsis"); + const bounds = await label.evaluate((element) => ({ + textWidth: element.scrollWidth, + visibleWidth: element.clientWidth, + right: element.getBoundingClientRect().right, + viewportWidth: document.documentElement.clientWidth, + })); + expect(bounds.textWidth).toBeGreaterThan(bounds.visibleWidth); + expect(bounds.right).toBeLessThanOrEqual(bounds.viewportWidth); +} + +async function expectSenderAlignedWithBubble(attribution: Locator) { + const edges = await attribution.evaluate((button) => { + const bubble = button.nextElementSibling; + const label = button.querySelector('[dir="auto"]'); + if (!bubble || !label) throw new Error("Sender label or message bubble missing"); + return { + labelRight: label.getBoundingClientRect().right, + bubbleRight: bubble.getBoundingClientRect().right, + }; + }); + expect( + Math.abs(edges.labelRight - edges.bubbleRight), + "sender and bubble share the right edge", + ).toBeLessThanOrEqual(1); +} + +async function seedWholeTurnHistory() { + const agent = await seedMockAgentWorkspace({ + repoPrefix: "whole-turn-history-", + title: "Whole turns", + model: "e2e-fast-stream", + }); + for (const prompt of [ + ...Array.from( + { length: 25 }, + (_, index) => `Short ${index}: emit 1 coalesced agent stream updates`, + ), + "Older long turn: emit 60 tool agent stream updates", + "Latest long turn: emit 120 tool agent stream updates", + ]) { + await agent.client.sendAgentMessage(agent.agentId, prompt); + await agent.client.waitForFinish(agent.agentId, 15_000); + } + return agent; +} + +test("loads complete long turns and preserves expansion while revealing older history", async ({ + page, +}) => { + test.setTimeout(120_000); + await useChatDisplay(page, "collapseTurns"); + const agent = await seedWholeTurnHistory(); + try { + const history = await holdOlderHistoryPages(page, agent); + await openAgentRoute(page, agent); + await expectComposerVisible(page); + const latest = page + .getByTestId("turn-summary") + .getByRole("button", { name: "Ran 120 commands", exact: true }); + await expect(latest).toBeVisible(); + await expect.poll(() => rowsBetweenLatestSummaryAndReply(page)).toBe(0); + await latest.click(); + await expect.poll(() => rowsBetweenLatestSummaryAndReply(page)).toBe(120); + await userScrollsTimelineToHistoryStart(page); + await history.expectRequestedPages(1); + history.releasePage(1); + await expect( + page + .getByTestId("turn-summary") + .getByRole("button", { name: "Ran 60 commands", exact: true }), + ).toBeVisible(); + await expect.poll(() => rowsBetweenLatestSummaryAndReply(page)).toBe(120); + history.expectNoRepeatedEntries(); + await latest.scrollIntoViewIfNeeded(); + await latest.click(); + await expect.poll(() => rowsBetweenLatestSummaryAndReply(page)).toBe(0); + } finally { + await agent.cleanup(); + } +}); + +async function useThinkingDisplay( + page: Page, + autoExpandReasoning: boolean, + chatDisplay: ChatDisplay, +) { + await page.addInitScript( + (settings) => { + localStorage.setItem( + "@paseo:app-settings", + JSON.stringify({ + ...settings, + chatDisplay: sessionStorage.getItem("e2e-chat-display") ?? settings.chatDisplay, + }), + ); + }, + { autoExpandReasoning, chatDisplay }, + ); +} + +for (const autoExpandReasoning of [false, true]) { + test(`reasoning follows Expand thinking (${autoExpandReasoning}) when opening its turn`, async ({ + page, + }) => { + await page.setViewportSize({ width: 1280, height: 1000 }); + await useThinkingDisplay(page, autoExpandReasoning, "collapseToolCalls"); + const agent = await seedMockAgentWorkspace({ + repoPrefix: "thinking-group-", + title: "Thinking with tools", + model: "ten-second-stream", + initialPrompt: "Inspect the scroll container", + }); + try { + await agent.client.waitForFinish(agent.agentId, 30_000); + await openAgentRoute(page, agent); + await expectComposerVisible(page); + const reasoning = page + .getByText(/Need to find the scroll container, the layout effect/) + .filter({ visible: true }) + .first(); + await expectThinkingPresentation(page, autoExpandReasoning); + await switchToCollapsedTurns(page); + await expectComposerVisible(page); + const summary = page.getByTestId("turn-summary").last().getByRole("button"); + await expect(summary).toBeVisible(); + await expect(summary).not.toContainText(/thought/i); + await expect(reasoning).toHaveCount(0); + await summary.click(); + await expect(reasoning).toHaveCount(autoExpandReasoning ? 1 : 0); + await expect.poll(() => groupedToolsInsideLatestTurn(page)).toEqual([]); + await openOneToolOutput(page); + await summary.click(); + await expect(reasoning).toHaveCount(0); + } finally { + await agent.cleanup(); + } + }); +} + +async function openOneToolOutput(page: Page) { + const output = page.getByText(/\[burst\] tick 1 userIsAtBottom=true/).filter({ visible: true }); + await expect(output).toHaveCount(0); + const command = page + .getByTestId("tool-call-badge") + .filter({ hasText: "node scripts/simulate-stream-burst.mjs" }) + .first(); + await command.getByRole("button").first().click(); + await expect(output.first()).toBeVisible(); + await command.getByRole("button").first().click(); + await expect(output).toHaveCount(0); +} + +async function expectThinkingPresentation(page: Page, autoExpandReasoning: boolean) { + const reasoning = page + .getByText(/Need to find the scroll container, the layout effect/) + .filter({ visible: true }) + .first(); + if (autoExpandReasoning) { + await expect(reasoning).toBeVisible(); + await expect(page.getByTestId("tool-call-group").filter({ hasText: /thought/ })).toHaveCount(0); + } else { + await expect(reasoning).toHaveCount(0); + const group = page + .getByTestId("tool-call-group") + .filter({ hasText: /read 1 file/i, visible: true }) + .last(); + await expect(group).toContainText(/read 1 file/i); + await expect(group.getByRole("button").first()).not.toContainText(/thought/i); + await group.getByRole("button").first().click(); + // Expand thinking is off: the group opens its rows, but the thought row stays closed + // until the reader opens it. + const thought = group + .getByTestId("tool-call-badge") + .filter({ hasText: /^Thinking/ }) + .first(); + await expect(thought).toBeVisible(); + await expect(reasoning).toHaveCount(0); + // A press right after the group opens occasionally does not register; retry until the + // thought row opens. + await expect(async () => { + await thought.getByRole("button").first().click(); + await expect(reasoning).toBeVisible({ timeout: 2_000 }); + }).toPass(); + } +} + +async function switchToCollapsedTurns(page: Page) { + await page.evaluate(() => { + sessionStorage.setItem("e2e-chat-display", "collapseTurns"); + }); + await page.reload(); +} + +test("a scheduled heartbeat opens a separate turn without reopening the previous response", async ({ + page, +}) => { + test.setTimeout(90_000); + await useChatDisplay(page, "collapseTurns"); + const agent = await seedMockAgentWorkspace({ + repoPrefix: "heartbeat-turn-", + title: "Heartbeat turns", + model: "ten-second-stream", + initialPrompt: "Inspect the scroll container", + }); + const schedules = agent.client as unknown as Pick< + DaemonClient, + "scheduleCreate" | "scheduleRunOnce" | "scheduleDelete" + >; + let scheduleId: string | undefined; + try { + await agent.client.waitForFinish(agent.agentId, 30_000); + await openAgentRoute(page, agent); + await expectComposerVisible(page); + const summaries = page.getByTestId("turn-summary"); + await expect(summaries).toHaveCount(1); + const previousSummary = await summaries.first().innerText(); + const previousReplyId = await page + .getByTestId("assistant-message") + .last() + .evaluate((element) => element.closest("[data-message-id]")!.getAttribute("data-message-id")); + const created = await schedules.scheduleCreate({ + name: "Check the completed work", + prompt: "Inspect the scroll container again", + cadence: { type: "cron", expression: "0 0 1 1 *" }, + target: { type: "self", agentId: agent.agentId }, + runOnCreate: false, + }); + expect(created.error).toBeNull(); + scheduleId = created.schedule!.id; + const fired = await schedules.scheduleRunOnce({ id: scheduleId }); + expect(fired.error).toBeNull(); + await expect( + page.getByTestId("tool-call-badge").filter({ hasText: /^Heartbeat/ }), + ).toBeVisible(); + await expect(summaries.first()).toHaveText(previousSummary); + const previousReply = page + .locator(`[data-message-id="${previousReplyId}"]`) + .getByTestId("assistant-message"); + await expect(previousReply).toBeVisible(); + await expect(previousReply).toContainText("(end of synthetic stream)"); + await agent.client.waitForFinish(agent.agentId, 30_000); + await expect(summaries).toHaveCount(2); + await expect.poll(() => rowsBetweenLatestSummaryAndReply(page)).toBe(0); + await expect(page.getByRole("button", { name: /^Worked for/ })).toHaveCount(2); + await page.screenshot({ path: "/tmp/heartbeat-turn-footer.png" }); + } finally { + if (scheduleId) await schedules.scheduleDelete({ id: scheduleId }); + await agent.cleanup(); + } +}); diff --git a/packages/app/e2e/browser/usage-modal.spec.ts b/packages/app/e2e/browser/usage-modal.spec.ts index 1d98f6c591..6835e01bcb 100644 --- a/packages/app/e2e/browser/usage-modal.spec.ts +++ b/packages/app/e2e/browser/usage-modal.spec.ts @@ -717,15 +717,15 @@ test("open usage clocks advance without refreshing or reopening", async ({ page await openCompactUsageWithClock(page, now); const card = page.getByTestId("usage-report-login-journey:account"); await expect(card.getByTestId("usage-freshness")).toHaveText("Updated just now"); - await expect(card.getByText("resets 30m", { exact: false }).first()).toBeVisible(); + await expect(card.getByText("resets in 30m", { exact: false }).first()).toBeVisible(); // The shared minute clock is wall-aligned, and the daemon timestamps use real time. // After two browser minutes the latest displayed tick is one or two minutes old. await advanceUsageClock(page, 120_000); await expect(card.getByTestId("usage-freshness")).toHaveText(/^Updated [12]m ago$/); - await expect(card.getByText(/resets (28|29)m/).first()).toBeVisible(); - await expect(card.getByText(/runs out (28|29)m/)).toBeVisible(); + await expect(card.getByText(/resets in (28|29)m/).first()).toBeVisible(); + await expect(card.getByText(/runs out in (28|29)m/)).toBeVisible(); await expect(card.getByTestId("provider-usage-balance-credits-reset")).toHaveText( - /^resets (28|29)m$/, + /^resets in (28|29)m\s·\s/, ); } finally { await login.cleanup(); diff --git a/packages/app/e2e/browser/usage-off.spec.ts b/packages/app/e2e/browser/usage-off.spec.ts new file mode 100644 index 0000000000..a0114c8e33 --- /dev/null +++ b/packages/app/e2e/browser/usage-off.spec.ts @@ -0,0 +1,69 @@ +import { expect, test } from "../support/fixtures"; +import { gotoAppShell } from "../support/helpers/app"; +import { seedSidebarFooterPreferences } from "../support/helpers/sidebar-nav-settings"; +import { installUsageReportsFixture } from "../support/helpers/usage-reports"; +import { + claudeAndCodexReports, + openUsageFromIcon, + openUsageOptions, + closeUsageOptions, + closeUsage, + expectNoUsageItem, + expectPinnedUsage, +} from "../support/helpers/usage-sidebar-item"; + +test("Check usage applies to the host and Turn on restores cards", async ({ + page, + e2eWorkerClient, +}) => { + test.setTimeout(180_000); + const previous = (await e2eWorkerClient.getDaemonConfig()).config.usage ?? { enabled: true }; + try { + const usage = await installUsageReportsFixture(page, { + lists: [() => claudeAndCodexReports()], + }); + await page.setViewportSize({ width: 1440, height: 1000 }); + await seedSidebarFooterPreferences(page, [{ key: "usage", visible: true }]); + await gotoAppShell(page); + await expectPinnedUsage(page, ["31% 5h", "54% wk", "7% 5h", "12% wk"]); + await openUsageFromIcon(page); + await usage.waitForListRequests(1); + await openUsageOptions(page); + await page.getByRole("switch", { name: "Check usage", exact: true }).click(); + await closeUsageOptions(page); + await expect(page.getByRole("button", { name: "Turn on", exact: true })).toBeVisible(); + await expect(page.getByRole("button", { name: "Refresh all", exact: true })).toHaveCount(0); + expect((await e2eWorkerClient.getDaemonConfig()).config.usage).toEqual({ enabled: false }); + await expectNoUsageItem(page); + const before = usage.listRequests().length; + await closeUsage(page); + await page.reload(); + await openUsageFromIcon(page); + await expect(page.getByRole("button", { name: "Turn on", exact: true })).toBeVisible(); + expect(usage.listRequests()).toHaveLength(before); + await page.getByRole("button", { name: "Turn on", exact: true }).click(); + await expect(page.getByText("Claude", { exact: true })).toBeVisible(); + expect((await e2eWorkerClient.getDaemonConfig()).config.usage).toEqual({ enabled: true }); + // A separate client changes the policy, as another device would. + await e2eWorkerClient.patchDaemonConfig({ usage: { enabled: false } }); + await expect(page.getByRole("button", { name: "Turn on", exact: true })).toBeVisible(); + await e2eWorkerClient.patchDaemonConfig({ usage: { enabled: true } }); + await expect(page.getByText("Claude", { exact: true })).toBeVisible(); + } finally { + await e2eWorkerClient.patchDaemonConfig({ usage: previous }); + } +}); + +test("older hosts keep usage without a Check usage switch", async ({ page }) => { + test.setTimeout(180_000); + await installUsageReportsFixture(page, { + usageSettingSupported: false, + lists: [() => claudeAndCodexReports()], + }); + await page.setViewportSize({ width: 1440, height: 1000 }); + await gotoAppShell(page); + await openUsageFromIcon(page); + await expect(page.getByText("Claude", { exact: true })).toBeVisible(); + await openUsageOptions(page); + await expect(page.getByRole("switch", { name: "Check usage", exact: true })).toHaveCount(0); +}); diff --git a/packages/app/e2e/browser/usage-sidebar-item.spec.ts b/packages/app/e2e/browser/usage-sidebar-item.spec.ts index 27fac6691c..9151403904 100644 --- a/packages/app/e2e/browser/usage-sidebar-item.spec.ts +++ b/packages/app/e2e/browser/usage-sidebar-item.spec.ts @@ -441,3 +441,31 @@ test("released hosts supply source logos through the client conversion", async ( ).toHaveAttribute("d", codexPath); await qaScreenshot(page, "released-host-usage-modal"); }); + +test("hidden usage sends no requests until opened", async ({ page }) => { + test.setTimeout(180_000); + const usage = await installUsageReportsFixture(page, { lists: [() => claudeAndCodexReports()] }); + await page.setViewportSize(WIDE); + await gotoAppShell(page); + await expectNoUsageItem(page); + await expect(page.getByRole("button", { name: "Usage", exact: true })).toBeVisible({ + timeout: 90_000, + }); + await openSidebarNavSettings(page); + await expectFooterItemSetting(page, "usage", false); + await leaveSettings(page); + expect(usage.listRequests()).toHaveLength(0); + await openUsageFromIcon(page); + await usage.waitForListRequests(1); + expect(usage.listRequests()).toHaveLength(1); +}); + +test("visible usage summary requests reports on load", async ({ page }) => { + test.setTimeout(180_000); + const usage = await installUsageReportsFixture(page, { lists: [() => claudeAndCodexReports()] }); + await seedSidebarFooterPreferences(page, [{ key: "usage", visible: true }]); + await page.setViewportSize(WIDE); + await gotoAppShell(page); + await expectPinnedUsage(page, ["31% 5h", "54% wk", "7% 5h", "12% wk"]); + expect(usage.listRequests()).toHaveLength(1); +}); diff --git a/packages/app/e2e/browser/workspace-relative-navigation.spec.ts b/packages/app/e2e/browser/workspace-relative-navigation.spec.ts index 909672c489..5066411c78 100644 --- a/packages/app/e2e/browser/workspace-relative-navigation.spec.ts +++ b/packages/app/e2e/browser/workspace-relative-navigation.spec.ts @@ -70,25 +70,31 @@ test("previous and next traverse every visible workspace while digit shortcuts s workspaceId: order[8], }); }); - await test.step("hidden Done rows remain shortcut targets without expanding the project", async () => { - await expectHiddenWorkspaceShortcuts(page, order); + await test.step("collapsed groups keep shortcut targets selected without expanding", async () => { + await expectCollapsedWorkspaceShortcuts(page, order); }); } finally { await project.cleanup(); } }); -async function expectHiddenWorkspaceShortcuts(page: Page, order: string[]) { +async function expectCollapsedWorkspaceShortcuts(page: Page, order: string[]) { await page.getByLabel("Show less", { exact: true }).click(); const rows = page.getByRole("button", { name: /^Workspace \d{2}$/ }); - await expect(rows).toHaveCount(7); + await expect(rows).toHaveCount(8); + await expectSidebarWorkspaceSelected({ page, serverId: getServerId(), workspaceId: order[8] }); await switchWorkspaceViaSidebar({ page, serverId: getServerId(), workspaceId: order[0] }); + await expect(rows).toHaveCount(7); await page.keyboard.press("Alt+9"); await expect(page).toHaveURL(new RegExp(`/workspace/${order[8]}$`)); + await expectSidebarWorkspaceSelected({ page, serverId: getServerId(), workspaceId: order[8] }); + await expect(rows).toHaveCount(8); + await page.keyboard.press("Alt+]"); + await expect(page).toHaveURL(new RegExp(`/workspace/${order[9]}$`)); + await expectSidebarWorkspaceSelected({ page, serverId: getServerId(), workspaceId: order[9] }); + await expect(rows).toHaveCount(8); await expect(page.getByTestId(`sidebar-workspace-row-${getServerId()}:${order[8]}`)).toHaveCount( 0, ); - await page.keyboard.press("Alt+]"); - await expect(page).toHaveURL(new RegExp(`/workspace/${order[9]}$`)); - await expect(rows).toHaveCount(7); + await expect(page.getByLabel("Show more", { exact: true })).toBeVisible(); } diff --git a/packages/app/e2e/fixtures/fake-pi-rpc.mjs b/packages/app/e2e/fixtures/fake-pi-rpc.mjs index b6d156ddfc..372e29c44b 100644 --- a/packages/app/e2e/fixtures/fake-pi-rpc.mjs +++ b/packages/app/e2e/fixtures/fake-pi-rpc.mjs @@ -6,6 +6,7 @@ for await (const line of lines) { const command = JSON.parse(line); let data = {}; if (command.type === "get_available_models") { + if (process.argv.includes("--stall-model-discovery")) continue; data = { models: [ { diff --git a/packages/app/e2e/mobile/agent-device/native-user-message-preview-preconditions.md b/packages/app/e2e/mobile/agent-device/native-user-message-preview-preconditions.md new file mode 100644 index 0000000000..9985a3f544 --- /dev/null +++ b/packages/app/e2e/mobile/agent-device/native-user-message-preview-preconditions.md @@ -0,0 +1,14 @@ +# Native user message preview + +Open a chat with a user message containing 16 newline-separated lines of +`Preview line N`, with N from 1 to 16. Scroll the message into view on a +phone-sized Android emulator or iOS simulator. Its text must exceed the 240-point preview cap, +while its expanded bubble and toggle fit in the chat viewport. Close any other +expanded messages so the toggle labels identify this message. + +Replay `native-user-message-preview.android.ad` or +`native-user-message-preview.ios.ad` through the existing mobile runner or +agent-device. It checks that a clipped message offers Show more and +that two expand/collapse round trips keep both controls reachable. Before the +fix, the first Show more assertion fails because native layout reports the +capped height as the full content height. diff --git a/packages/app/e2e/mobile/agent-device/native-user-message-preview.android.ad b/packages/app/e2e/mobile/agent-device/native-user-message-preview.android.ad new file mode 100644 index 0000000000..45630217bb --- /dev/null +++ b/packages/app/e2e/mobile/agent-device/native-user-message-preview.android.ad @@ -0,0 +1,14 @@ +context platform=android timeout=60000 retries=0 +env APP_ID=sh.paseo.debug + +open "${APP_ID}" +wait "role=\"button\" label=\"Show more\"" 10000 +press "role=\"button\" label=\"Show more\"" +wait "role=\"button\" label=\"Show less\"" 10000 +press "role=\"button\" label=\"Show less\"" +wait "role=\"button\" label=\"Show more\"" 10000 +press "role=\"button\" label=\"Show more\"" +wait "role=\"button\" label=\"Show less\"" 10000 +press "role=\"button\" label=\"Show less\"" +wait "role=\"button\" label=\"Show more\"" 10000 +close diff --git a/packages/app/e2e/mobile/agent-device/native-user-message-preview.ios.ad b/packages/app/e2e/mobile/agent-device/native-user-message-preview.ios.ad new file mode 100644 index 0000000000..d19d7dd8aa --- /dev/null +++ b/packages/app/e2e/mobile/agent-device/native-user-message-preview.ios.ad @@ -0,0 +1,14 @@ +context platform=ios timeout=60000 retries=0 +env APP_ID=sh.paseo.debug + +open "${APP_ID}" +wait "role=\"button\" label=\"Show more\"" 10000 +press "role=\"button\" label=\"Show more\"" +wait "role=\"button\" label=\"Show less\"" 10000 +press "role=\"button\" label=\"Show less\"" +wait "role=\"button\" label=\"Show more\"" 10000 +press "role=\"button\" label=\"Show more\"" +wait "role=\"button\" label=\"Show less\"" 10000 +press "role=\"button\" label=\"Show less\"" +wait "role=\"button\" label=\"Show more\"" 10000 +close diff --git a/packages/app/e2e/mobile/fold/android.mjs b/packages/app/e2e/mobile/fold/android.mjs new file mode 100644 index 0000000000..93f23dc111 --- /dev/null +++ b/packages/app/e2e/mobile/fold/android.mjs @@ -0,0 +1,104 @@ +// Run a release build with a connected workspace open and the keyboard hidden. +// ANDROID_SERIAL=emulator-5574 node packages/app/e2e/mobile/fold/android.mjs +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { mkdirSync, writeFileSync } from "node:fs"; +import { resolve } from "node:path"; +import { setTimeout as delay } from "node:timers/promises"; + +const serial = process.env.ANDROID_SERIAL; +assert(serial, "Set ANDROID_SERIAL to a booted Android foldable emulator"); +const appId = process.env.PASEO_MOBILE_APP_ID ?? "sh.paseo.debug"; +const session = "android-fold"; +const artifacts = resolve(".dev/agent-device-artifacts/android-fold"); +const env = { + ...process.env, + AGENT_DEVICE_STATE_DIR: resolve(".dev/agent-device-android-fold"), +}; +mkdirSync(artifacts, { recursive: true }); + +function run(binary, args) { + return execFileSync(binary, args, { env, encoding: "utf8", timeout: 60_000 }); +} +function adb(...args) { + return run("adb", ["-s", serial, ...args]); +} +function ad(...args) { + return run("agent-device", [...args, "--session", session]); +} +function pid() { + return adb("shell", "pidof", appId).trim(); +} +function open() { + ad("open", appId, "--platform", "android", "--serial", serial, "--no-test-ime"); +} +function stateId(name) { + const states = adb("shell", "cmd", "device_state", "print-states"); + const match = states.match(new RegExp(`identifier=(\\d+), name='${name}'`)); + assert(match, `Emulator must expose the ${name} posture: ${states}`); + return match[1]; +} + +async function expectLayout(posture) { + const compact = posture === "CLOSED"; + const expectedId = compact ? "workspace-tab-switcher-trigger" : "workspace-tabs-scroll"; + const unexpectedId = compact ? "workspace-tabs-scroll" : "workspace-tab-switcher-trigger"; + const deadline = Date.now() + 15_000; + let nodes = []; + do { + let data; + try { + ({ data } = JSON.parse(ad("snapshot", "-i", "--json"))); + } catch (error) { + // During display handoff Android briefly has no capturable app window. + if (!error.stdout?.includes("insufficient foreground app content")) throw error; + await delay(200); + continue; + } + assert.equal(data.appBundleId, appId, "Snapshot must belong to Paseo"); + nodes = data.nodes; + if ( + nodes.some((node) => node.identifier === expectedId) && + !nodes.some((node) => node.identifier === unexpectedId) + ) { + writeFileSync(resolve(artifacts, `${posture}.json`), JSON.stringify(data, null, 2)); + console.log(`PASS: ${posture} uses ${compact ? "compact" : "wide"} workspace controls`); + return; + } + await delay(200); + } while (Date.now() < deadline); + writeFileSync(resolve(artifacts, `${posture}-failure.json`), JSON.stringify(nodes, null, 2)); + writeFileSync( + resolve(artifacts, "native-failure.txt"), + adb("shell", "dumpsys", "activity", "top"), + ); + assert.fail(`${posture}: expected ${expectedId}, without ${unexpectedId}`); +} + +const closed = stateId("CLOSED"); +const opened = stateId("OPENED"); +const initialState = adb("shell", "cmd", "device_state", "state").match( + /Committed state: DeviceState\{identifier=(\d+)/, +)?.[1]; +assert(initialState, "Could not read the initial fold state"); + +try { + adb("shell", "cmd", "device_state", "state", opened); + open(); + await expectLayout("OPENED"); + const initialPid = pid(); + for (const [posture, id] of [ + ["CLOSED", closed], + ["OPENED", opened], + ]) { + adb("shell", "input", "keyevent", "KEYCODE_HOME"); + adb("shell", "cmd", "device_state", "state", id); + // Resume immediately: waiting for configuration delivery hides the regression. + open(); + await expectLayout(posture); + assert.equal(pid(), initialPid, "Fold/resume must preserve the app process"); + } +} finally { + adb("shell", "cmd", "device_state", "state", initialState); + ad("close"); +} diff --git a/packages/app/e2e/mobile/markdown-formatting/README.md b/packages/app/e2e/mobile/markdown-formatting/README.md index c2ab0ddc65..28cdb87c6b 100644 --- a/packages/app/e2e/mobile/markdown-formatting/README.md +++ b/packages/app/e2e/mobile/markdown-formatting/README.md @@ -12,6 +12,22 @@ point and Metro workflow in [status-ring](../status-ring/README.md), importing `MarkdownFormattingRegression` from `./e2e/mobile/markdown-formatting/native`. Open the same Metro URL in a browser to compare web. Restore `index.ts` afterward. +With this fixture open in an Android Agent Device session, run: + +```sh +node packages/app/e2e/mobile/markdown-formatting/android.mjs +``` + +The runner switches to paragraphs with long inline code at a fixed 300 dp width. +It compares the native Markdown host’s bottom with its last TextView’s bottom, +then repeats in compact mode and after restoring regular text. More than one +pixel of surplus fails. Keep the whole fixture visible: clipped accessibility +bounds cannot establish measurement parity. + +`scripts/postinstall-patches.test.mjs` regenerates both platforms’ props and +compares them with the shipped headers. This catches missing C++ fields in the +measurement path, which the Kotlin tests cannot exercise. + The package patch contains `InlineCodeFormattingTest`, which exercises actual Android spans in Robolectric native graphics mode, covering draw and measurement, span order, code inside paragraph/heading sizes, bold/italic composition, and diff --git a/packages/app/e2e/mobile/markdown-formatting/android.mjs b/packages/app/e2e/mobile/markdown-formatting/android.mjs new file mode 100644 index 0000000000..c015edcb3a --- /dev/null +++ b/packages/app/e2e/mobile/markdown-formatting/android.mjs @@ -0,0 +1,60 @@ +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; + +const session = process.argv[2]; +assert(session, "Pass an Android agent-device session serving native.tsx"); +function ad(...args) { + return execFileSync("agent-device", ["--session", session, ...args], { + encoding: "utf8", + timeout: 60_000, + }); +} + +function assertMeasurementParity(mode) { + const snapshot = JSON.parse(ad("snapshot", "--raw", "--json")); + assert.equal(snapshot.success, true); + const nodes = snapshot.data.nodes; + let last = nodes.find((node) => node.label?.endsWith("End of measurement fixture.")); + assert(last?.rect, "The last paragraph must be visible, including its bottom"); + // EnrichedMarkdownText exposes paragraph accessibility nodes inside its TextView; + // EnrichedMarkdown exposes the TextViews themselves. Measure the native child. + let host = nodes.find((node) => node.index === last.parentIndex); + if (host?.type === "android.widget.TextView") { + last = host; + host = nodes.find((node) => node.index === last.parentIndex); + } + assert.equal(host?.type, "android.widget.FrameLayout"); + const viewport = nodes.find((node) => node.type === "android.widget.ScrollView"); + const footer = nodes.find((node) => node.label === "End of Markdown host"); + assert(viewport?.rect && footer?.rect, "The fixture and footer must be visible"); + assert( + host.rect.y >= viewport.rect.y && + footer.rect.y + footer.rect.height <= viewport.rect.y + viewport.rect.height, + "The whole fixture must fit in the viewport; clipped bounds cannot prove parity", + ); + const hostBottom = host.rect.y + host.rect.height; + const childBottom = last.rect.y + last.rect.height; + console.log( + JSON.stringify({ + mode, + host: host.rect, + lastChild: last.rect, + surplus: hostBottom - childBottom, + }), + ); + assert( + Math.abs(hostBottom - childBottom) <= 1, + `Markdown reserves blank space in ${mode}: host bottom ${hostBottom}, last child bottom ${childBottom}`, + ); +} + +ad("press", 'label="Show wrapping fixture"'); +ad("wait", "text", "End of Markdown host", "10000"); +assertMeasurementParity("regular"); +ad("press", 'label="Use compact text"'); +ad("wait", "text", "Use regular text", "10000"); +assertMeasurementParity("compact"); +ad("press", 'label="Use regular text"'); +ad("wait", "text", "Use compact text", "10000"); +assertMeasurementParity("regular restored"); +console.log("PASS Android Markdown host measurement matches its last child"); diff --git a/packages/app/e2e/mobile/markdown-formatting/native.tsx b/packages/app/e2e/mobile/markdown-formatting/native.tsx index d5d9a64aa0..e28f8a9900 100644 --- a/packages/app/e2e/mobile/markdown-formatting/native.tsx +++ b/packages/app/e2e/mobile/markdown-formatting/native.tsx @@ -1,6 +1,6 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { useCallback, useState } from "react"; -import { Button, ScrollView, Text } from "react-native"; +import { Button, ScrollView, Text, View } from "react-native"; import { StyleSheet } from "react-native-unistyles"; import { GestureHandlerRootView } from "react-native-gesture-handler"; import { MarkdownRenderer } from "@/components/markdown/renderer"; @@ -10,6 +10,7 @@ const styles = StyleSheet.create((theme) => ({ scroll: { backgroundColor: theme.colors.surface0 }, content: { padding: 32, paddingTop: 60 }, title: { color: theme.colors.foreground }, + wrapping: { width: 300 }, })); const queryClient = new QueryClient(); @@ -32,7 +33,15 @@ const source = [ "Normal **bold** and *italic* prose.", ].join("\n\n"); +const wrappingSource = [ + "Measurement parity. Take a repo with a gitignored `.env` in the main checkout and a `.worktreeinclude` containing `.env`.", + "Every creation path goes through `createPaseoWorktreeWorkflow` in `worktree-session.ts:341`, before `createAgent` in `creation/index.ts:160-174` starts.", + "The built-in plugin lives in `plugins/worktree-include/index.server.ts` and copies `paseo.json` beside `.worktreeinclude`. End of measurement fixture.", +].join("\n\n"); + export default function MarkdownFormattingRegression() { + const [wrapping, setWrapping] = useState(false); + const toggleWrapping = useCallback(() => setWrapping((value) => !value), []); const [compact, setCompact] = useState(false); const toggleCompact = useCallback(() => setCompact((value) => !value), []); return ( @@ -44,7 +53,14 @@ export default function MarkdownFormattingRegression() { title={compact ? "Use regular text" : "Use compact text"} onPress={toggleCompact} /> - + + ) : null} + + ); +} + +export function MessageSender({ + sender, + serverId, +}: { + sender: AgentMessage["sender"]; + serverId?: string; +}) { + const { t } = useTranslation(); + const host = sender.serverId ?? serverId; + const agent = useSessionStore((state) => { + const session = host ? state.sessions[host] : undefined; + return session?.agents.get(sender.id) ?? session?.agentDetails.get(sender.id); + }); + const ProviderIcon = useProviderIcon(agent?.provider ?? "", host); + const renderProviderIcon = useCallback( + (color: string) => , + [ProviderIcon], + ); + const openSender = useCallback(() => { + if (host) navigateToAgent({ serverId: host, agentId: sender.id }); + }, [host, sender.id]); + return ( + + ); +} + +const styles = StyleSheet.create((theme) => ({ + body: { flexShrink: 0 }, + sender: { paddingRight: 0, borderRightWidth: 0, maxWidth: "100%" }, + senderText: { flexShrink: 1 }, + toggle: { alignSelf: "flex-start", paddingHorizontal: 0, minHeight: 0, borderWidth: 0 }, + expandedToggle: { marginTop: theme.spacing[2] }, + fade: { position: "absolute", bottom: 0, left: 0, right: 0, height: theme.spacing[12] }, +})); diff --git a/packages/app/src/composer/draft/input-draft.live.test.tsx b/packages/app/src/composer/draft/input-draft.live.test.tsx index 8bc31bb176..82de9d3d73 100644 --- a/packages/app/src/composer/draft/input-draft.live.test.tsx +++ b/packages/app/src/composer/draft/input-draft.live.test.tsx @@ -2,7 +2,7 @@ import React, { act } from "react"; import { createRoot, type Root } from "react-dom/client"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; -import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { useDraftStore } from "@/stores/draft-store"; import type { AttachmentMetadata, ComposerAttachment } from "@/attachments/types"; import { createWorkspaceFileAttachment } from "@/attachments/workspace-file"; @@ -126,17 +126,13 @@ afterEach(async () => { }); }); -let useAgentInputDraft: typeof import("./input-draft").useAgentInputDraft; type DraftRecordForTest = ReturnType["drafts"][string]; -beforeAll(async () => { - Object.defineProperty(globalThis, "IS_REACT_ACT_ENVIRONMENT", { - value: true, - configurable: true, - }); - - ({ useAgentInputDraft } = await import("./input-draft")); +Object.defineProperty(globalThis, "IS_REACT_ACT_ENVIRONMENT", { + value: true, + configurable: true, }); +const { useAgentInputDraft } = await import("./input-draft"); describe("useAgentInputDraft live contract", () => { beforeEach(() => { diff --git a/packages/app/src/composer/draft/input-draft.ts b/packages/app/src/composer/draft/input-draft.ts index c14db9a119..2eb606a7f7 100644 --- a/packages/app/src/composer/draft/input-draft.ts +++ b/packages/app/src/composer/draft/input-draft.ts @@ -2,7 +2,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import type { UserComposerAttachment } from "@/attachments/types"; import type { TextReplacement } from "@/composer/types"; import type { DraftAgentControlsProps } from "@/composer/agent-controls"; -import type { DraftCommandTarget } from "@/hooks/use-agent-commands-query"; +import type { DraftCommandTarget } from "@/agent-commands"; import { useAgentFormState, type CreateAgentInitialValues, diff --git a/packages/app/src/composer/draft/workspace-tab.tsx b/packages/app/src/composer/draft/workspace-tab.tsx index d00b6f7790..c4ef45cb3f 100644 --- a/packages/app/src/composer/draft/workspace-tab.tsx +++ b/packages/app/src/composer/draft/workspace-tab.tsx @@ -41,7 +41,7 @@ import { useWorkspaceAttachmentsStore, } from "@/attachments/workspace-attachments-store"; import type { UserMessageImageAttachment } from "@/types/stream"; -import { COMPACT_FORM_FACTOR_WIDTH, useIsCompactFormFactor } from "@/constants/layout"; +import { COMPACT_CONTENT_WIDTH, useIsCompactFormFactor } from "@/constants/layout"; import { isWeb } from "@/constants/platform"; import { buildWorkspaceTabPersistenceKey, @@ -390,7 +390,7 @@ export function WorkspaceDraftAgentTab({ const editingSession = useComposerEditingSession("chat"); const isComposerFullscreen = useComposerFullscreen(editingSession); const { onLayout: onInputAreaLayout, isBelow: isCompactComposerLayout } = useContainerWidthBelow( - COMPACT_FORM_FACTOR_WIDTH, + COMPACT_CONTENT_WIDTH, { initialIsBelow: isCompactFormFactor }, ); const workspaceAttachmentScopeKey = useWorkspaceAttachmentScopeKey({ diff --git a/packages/app/src/composer/editing-session/index.test.ts b/packages/app/src/composer/editing-session/index.test.ts index 31c3765426..7dfcb0d438 100644 --- a/packages/app/src/composer/editing-session/index.test.ts +++ b/packages/app/src/composer/editing-session/index.test.ts @@ -2,6 +2,31 @@ import { describe, expect, it } from "vitest"; import { ComposerEditingSession, ComposerEditingSessions } from "./index"; describe("composer editing session", () => { + it("appends commands to the current editor buffer and focuses it", () => { + const session = new ComposerEditingSession(); + let text = "draft typed since publication"; + let focuses = 0; + let selection = { start: 0, end: 0 }; + const detach = session.attachEditor({ + getText: () => text, + replaceText: (next, nextSelection) => { + text = next; + selection = nextSelection; + }, + focus: () => { + focuses += 1; + }, + }); + session.insertCommand("/review"); + expect(selection).toEqual({ start: text.length, end: text.length }); + session.insertCommand("/test"); + expect(text).toBe("draft typed since publication /review /test "); + expect(focuses).toBe(2); + expect(selection).toEqual({ start: text.length, end: text.length }); + detach(); + session.insertCommand("/ignored"); + expect(text).toBe("draft typed since publication /review /test "); + }); it("publishes fullscreen changes once per transition", () => { const session = new ComposerEditingSession(); const changes: boolean[] = []; diff --git a/packages/app/src/composer/editing-session/index.tsx b/packages/app/src/composer/editing-session/index.tsx index 4776b5af3d..237b15251a 100644 --- a/packages/app/src/composer/editing-session/index.tsx +++ b/packages/app/src/composer/editing-session/index.tsx @@ -30,10 +30,29 @@ export interface ComposerRetainedEditor { */ export class ComposerEditingSession { private fullscreen = false; + private editor: { + getText(): string; + replaceText(text: string, selection: ComposerSelection): void; + focus(): void; + } | null = null; private retained: ComposerRetainedEditor | null = null; private listeners = new Set<() => void>(); constructor(private readonly onChange?: () => void) {} getFullscreen = () => this.fullscreen; + attachEditor(editor: NonNullable) { + this.editor = editor; + return () => { + if (this.editor === editor) this.editor = null; + }; + } + insertCommand(command: string) { + const editor = this.editor; + if (!editor) return; + const text = editor.getText(); + const nextText = `${text}${text && !/\s$/.test(text) ? " " : ""}${command} `; + editor.replaceText(nextText, { start: nextText.length, end: nextText.length }); + editor.focus(); + } /** Called by the unmounting editor; the next mount of this session takes it. */ retainEditor(retained: ComposerRetainedEditor) { this.retained = retained; diff --git a/packages/app/src/composer/index.tsx b/packages/app/src/composer/index.tsx index b7088ddeef..d6b4bae63f 100644 --- a/packages/app/src/composer/index.tsx +++ b/packages/app/src/composer/index.tsx @@ -71,7 +71,7 @@ import { } from "./input/input"; import type { ImageAttachment, MessagePayload, TextReplacement } from "./types"; import { ICON_SIZE, type Theme } from "@/styles/theme"; -import type { DraftCommandTarget } from "@/hooks/use-agent-commands-query"; +import type { DraftCommandTarget } from "@/agent-commands"; import { encodeImages } from "@/utils/encode-images"; import { focusWithRetries } from "@/utils/web-focus"; import { diff --git a/packages/app/src/composer/input/input.tsx b/packages/app/src/composer/input/input.tsx index 16acede7e5..8cb8cd4c32 100644 --- a/packages/app/src/composer/input/input.tsx +++ b/packages/app/src/composer/input/input.tsx @@ -1407,6 +1407,16 @@ export const MessageInput = forwardRef( [onChangeText, updateComposerHeightForText, updateLiveTextPresence], ); + useLayoutEffect( + () => + editingSession.attachEditor({ + getText: () => textInputRef.current?.getText() ?? valueRef.current, + replaceText, + focus: () => textInputRef.current?.focus(), + }), + [editingSession, replaceText], + ); + useImperativeHandle(ref, () => ({ focus: () => { textInputRef.current?.focus(); diff --git a/packages/app/src/composer/tracks.tsx b/packages/app/src/composer/tracks.tsx index 4e06266058..341e7dc8e0 100644 --- a/packages/app/src/composer/tracks.tsx +++ b/packages/app/src/composer/tracks.tsx @@ -8,6 +8,8 @@ import { MenuSurface, MenuTrigger, useMenuContext, + useMenuDepth, + type MenuPageDefinition, type MenuTriggerState, } from "@/components/ui/menu"; import { StatusRing } from "@/components/status-ring"; @@ -61,6 +63,8 @@ export interface ComposerTrackPillProps { accessibilityLabel?: string; /** Panel body. Rendered into a popover on wide screens and a sheet on compact ones. */ children: ReactNode; + /** Pages a row can open in place of the list (`ComposerTrackRow` `opensPage`). */ + pages?: readonly MenuPageDefinition[]; } /** @@ -85,6 +89,7 @@ export function ComposerTrackPill({ testID, accessibilityLabel, children, + pages, }: ComposerTrackPillProps): ReactElement { return ( @@ -98,6 +103,7 @@ export function ComposerTrackPill({ align="start" offset={PANEL_OFFSET} sheetTitle={panelTitle} + pages={pages} minWidth={PANEL_MIN_WIDTH} maxWidth={PANEL_MAX_WIDTH} maxHeight={PANEL_MAX_HEIGHT} @@ -199,6 +205,11 @@ export interface ComposerTrackRowProps { * lands inside the panel is not. */ closeOnSelect?: boolean; + /** + * A page of the panel this row opens in place of the list, instead of running `onPress`. The + * panel stays open: Back returns to the list. + */ + opensPage?: string; disabled?: boolean; accessibilityLabel?: string; testID?: string; @@ -220,18 +231,23 @@ export function ComposerTrackRow({ children, onPress, closeOnSelect = true, + opensPage, disabled = false, accessibilityLabel, testID, }: ComposerTrackRowProps): ReactElement { - const { selectItem } = useMenuContext("ComposerTrackRow"); + const { selectItem, openSub } = useMenuContext("ComposerTrackRow"); + const depth = useMenuDepth(); const [hovered, setHovered] = useState(false); const handlePointerEnter = useCallback(() => setHovered(true), []); const handlePointerLeave = useCallback(() => setHovered(false), []); - const handleSelect = useCallback( - () => selectItem(onPress, closeOnSelect), - [closeOnSelect, onPress, selectItem], - ); + const handleSelect = useCallback(() => { + if (opensPage) { + selectItem(() => openSub({ id: opensPage, depth }), false); + return; + } + selectItem(onPress, closeOnSelect); + }, [closeOnSelect, depth, onPress, openSub, opensPage, selectItem]); const itemDataSet = useMemo( () => ({ menuItem: "true", menuDisabled: disabled ? "true" : "false" }), @@ -251,7 +267,7 @@ export function ComposerTrackRow({ [hovered, renderRow], ); - if (!onPress) { + if (!onPress && !opensPage) { return {renderRow(false)}; } diff --git a/packages/app/src/constants/layout.ts b/packages/app/src/constants/layout.ts index 96aee0e828..739be45ee9 100644 --- a/packages/app/src/constants/layout.ts +++ b/packages/app/src/constants/layout.ts @@ -11,10 +11,11 @@ export const HEADER_INNER_HEIGHT_MOBILE = 56; export const WORKSPACE_SECONDARY_HEADER_HEIGHT = 36; export const HEADER_TOP_PADDING_MOBILE = 8; -export const COMPACT_FORM_FACTOR_WIDTH = 500; +// Measured composer width; independent of the window's compact/wide breakpoint. +export const COMPACT_CONTENT_WIDTH = 500; -// Settings uses the canonical desktop list + detail layout. Its sidebar and -// detail target must fit together before it can share width with app navigation. +// Settings navigation can shrink below its preferred width to preserve the detail +// minimum. Both targets must fit before Settings shares width with app navigation. export const SETTINGS_DESKTOP_SIDEBAR_WIDTH = 320; export const SETTINGS_DESKTOP_DETAIL_MIN_WIDTH = 400; export const SETTINGS_DESKTOP_SPLIT_MIN_WIDTH = @@ -33,7 +34,7 @@ export { getIsElectronMac as getIsElectronRuntimeMac, } from "./platform"; -/** Below 600 points, sidebars overlay the workspace. Medium and wider layouts dock them. */ +/** Below md (600 points), sidebars overlay the workspace; wider layouts can dock them. */ export function isCompactBreakpoint(breakpoint: string | undefined): boolean { return breakpoint === "xs" || breakpoint === "sm"; } diff --git a/packages/app/src/contexts/session-context.tsx b/packages/app/src/contexts/session-context.tsx index bccd4d3ee0..89c32c0bd5 100644 --- a/packages/app/src/contexts/session-context.tsx +++ b/packages/app/src/contexts/session-context.tsx @@ -455,10 +455,6 @@ function SessionProviderInternal({ children, serverId, client }: SessionProvider reportError: (error) => { console.warn("[Session] viewed timeline synchronization failed", { serverId, error }); }, - schedule: (task, delayMs) => { - const timeout = setTimeout(task, delayMs); - return () => clearTimeout(timeout); - }, }); viewedTimelineSyncRef.current = sync; setViewedTimelineSync(serverId, sync); diff --git a/packages/app/src/data/acp-provider-catalog.ts b/packages/app/src/data/acp-provider-catalog.ts index f0210f1402..46b7d81a2d 100644 --- a/packages/app/src/data/acp-provider-catalog.ts +++ b/packages/app/src/data/acp-provider-catalog.ts @@ -292,7 +292,10 @@ const CATALOG_DATA = [ version: "0.6.13", iconId: "minimax-code", installLink: "https://agent.minimax.io", - command: ["npx", "-y", "@minimax-ai/code@0.6.13", "acp"], + // `-p ` names the package and `mcode` names its binary. Without the + // explicit binary, npx resolves the executable from the unscoped package + // name (`code`), which this package does not publish. + command: ["npx", "-y", "-p", "@minimax-ai/code@0.6.13", "mcode", "acp"], }, { id: "minion-code", diff --git a/packages/app/src/data/providers-snapshot.ts b/packages/app/src/data/providers-snapshot.ts index 68b389fe15..87c62f81ca 100644 --- a/packages/app/src/data/providers-snapshot.ts +++ b/packages/app/src/data/providers-snapshot.ts @@ -8,7 +8,7 @@ import { } from "./provider-snapshot-cache"; import { queryClient as singletonQueryClient } from "./query-client"; import { replaceProviderSnapshotIcons } from "@/data/provider-icons"; -import { agentCommandsQueryRoot } from "@/hooks/agent-commands-query"; +import { agentCommandsQueryRoot } from "@/agent-commands/cache"; import type { AgentProvider } from "@getpaseo/protocol/agent-types"; import { normalizeWorkspacePath } from "@/utils/workspace-identity"; diff --git a/packages/app/src/data/push-router.ts b/packages/app/src/data/push-router.ts index 75ac313169..cc32f8f8e3 100644 --- a/packages/app/src/data/push-router.ts +++ b/packages/app/src/data/push-router.ts @@ -1,11 +1,12 @@ import type { OwnedSubscription } from "@getpaseo/client"; +import type { ProviderSnapshotEntry } from "@getpaseo/protocol/agent-types"; import type { Query, QueryCacheNotifyEvent, QueryClient, QueryKey } from "@tanstack/react-query"; import type { ListTerminalsResponse, MutableDaemonConfig, SessionOutboundMessage, } from "@getpaseo/protocol/messages"; -import { agentCommandsQueryRoot } from "@/hooks/agent-commands-query"; +import { invalidateCommandsForProviderChange } from "@/agent-commands/cache"; import { shareCheckoutDiff } from "@/git/diff-sharing"; import { orderCheckoutDiffFiles } from "@/git/diff-order"; import { daemonConfigQueryKey } from "@/data/daemon-config"; @@ -186,10 +187,10 @@ export async function applyProvidersSnapshotUpdate(input: { const snapshot = { ...input.message.payload, requestId: "providers_snapshot_update" }; const cwd = normalizeProvidersSnapshotCwd(snapshot.cwd); const queryKey = providersSnapshotQueryKey(input.serverId, cwd); - const previous = input.queryClient.getQueryData<{ snapshotHash?: string }>(queryKey); + const previous = input.queryClient.getQueryData<{ entries: ProviderSnapshotEntry[] }>(queryKey); let announcement: typeof snapshot | undefined = snapshot; void input.queryClient.cancelQueries({ queryKey, exact: true }); - await input.queryClient.fetchQuery({ + const current = await input.queryClient.fetchQuery({ queryKey, staleTime: 0, structuralSharing: false, @@ -205,12 +206,13 @@ export async function applyProvidersSnapshotUpdate(input: { }); }, }); - if (!snapshot.snapshotHash || previous?.snapshotHash !== snapshot.snapshotHash) { - void input.queryClient.invalidateQueries({ - queryKey: agentCommandsQueryRoot(input.serverId), - exact: false, - }); - } + void invalidateCommandsForProviderChange({ + queryClient: input.queryClient, + serverId: input.serverId, + cwd, + previous: previous?.entries, + current: current.entries, + }); } export function mountServerDataPushRouter(input: PushRouterInput): () => void { diff --git a/packages/app/src/data/query.ts b/packages/app/src/data/query.ts index 2a645f8666..e2b25d7b29 100644 --- a/packages/app/src/data/query.ts +++ b/packages/app/src/data/query.ts @@ -27,7 +27,7 @@ type ReplicaQueryInput type FetchQueryInput = Omit< UseQueryOptions, - "initialData" | "placeholderData" | "queryFn" | "refetchOnMount" | "staleTime" + "initialData" | "placeholderData" | "queryFn" | "staleTime" > & { dataShape: "list" | "value"; queryFn: QueryFnOption; @@ -113,7 +113,7 @@ export function fetchQueryOptions< dataShape, }, }, - refetchOnMount: immutableWhen ? true : "always", + refetchOnMount: options.refetchOnMount ?? (immutableWhen ? true : "always"), staleTime: immutableWhen ? (query) => query.state.data !== undefined && immutableWhen(query.state.data) ? Infinity : 0 diff --git a/packages/app/src/git/checkout-status-cache.test.ts b/packages/app/src/git/checkout-status-cache.test.ts index 026ec9d43a..bbfeb6d758 100644 --- a/packages/app/src/git/checkout-status-cache.test.ts +++ b/packages/app/src/git/checkout-status-cache.test.ts @@ -16,7 +16,7 @@ import { resolveWorkingDiffComparison, selectWorkingDiffComparison, } from "@/git/working-diff-comparison"; -import { draftAgentCommandsQueryKey } from "@/hooks/agent-commands-query"; +import { draftAgentCommandsQueryKey } from "@/agent-commands/cache"; import { applyCheckoutStatusUpdateFromEvent, ensureCheckoutStatus, diff --git a/packages/app/src/git/checkout-status-cache.ts b/packages/app/src/git/checkout-status-cache.ts index ca5cbb3a7a..4aaa650c70 100644 --- a/packages/app/src/git/checkout-status-cache.ts +++ b/packages/app/src/git/checkout-status-cache.ts @@ -8,7 +8,7 @@ import { invalidatePrPaneTimelineForCheckout, } from "@/git/query-keys"; import { type CheckoutPrStatusPayload, normalizeCheckoutPrStatusPayload } from "@/git/pr-status"; -import { resetDraftAgentCommandsForCheckout } from "@/hooks/agent-commands-query"; +import { resetDraftAgentCommandsForCheckout } from "@/agent-commands/cache"; export type CheckoutStatusPayload = CheckoutStatusResponse["payload"]; export type { CheckoutPrStatusPayload } from "@/git/pr-status"; diff --git a/packages/app/src/git/diff-document/benchmark-corpus.ts b/packages/app/src/git/diff-document/benchmark-corpus.ts new file mode 100644 index 0000000000..469d437e8d --- /dev/null +++ b/packages/app/src/git/diff-document/benchmark-corpus.ts @@ -0,0 +1,65 @@ +import { readFileSync } from "node:fs"; +import path from "node:path"; + +/** + * The diff shapes the layout benchmarks measure, shared by the node bench + * (`model.bench.ts`) and the browser benchmark (`e2e/browser/diff-performance.spec.ts`) + * so both report against the same text. + */ +export interface BenchmarkCorpusFile { + path: string; + lines: string[]; +} + +function repeatToLength(unit: string, length: number): string { + return unit.repeat(Math.ceil(length / unit.length)).slice(0, length); +} + +/** A real source file: short lines, a few with ligature punctuation. */ +export function realCodeCorpusFile(): BenchmarkCorpusFile { + const source = readFileSync(path.resolve(__dirname, "../diff-pane.tsx"), "utf8"); + return { path: "packages/app/src/git/diff-pane.tsx", lines: source.split("\n") }; +} + +/** The CHANGELOG shape that once froze the renderer: 42 lines, longest ~600 characters. */ +export function changelogCorpusFile(): BenchmarkCorpusFile { + const sentence = + "- Fixed an issue where the diff viewer re-measured every line -> on toggle, which made wrapping painfully slow. "; + return { + path: "CHANGELOG.md", + lines: Array.from({ length: 42 }, (_, index) => + repeatToLength(sentence, 200 + ((index * 97) % 398)), + ), + }; +} + +/** Generated TypeScript: ligature punctuation on every line, every tenth line long. */ +export function generatedCodeCorpusFile(lineCount: number): BenchmarkCorpusFile { + return { + path: "src/generated.ts", + lines: Array.from({ length: lineCount }, (_, index) => { + const base = `const handler${index} = async (event) => items.filter((item) => item.id !== ${index} && item.kind === "selected");`; + return index % 10 === 9 ? repeatToLength(`${base} // `, 320) : base; + }), + }; +} + +/** Serialized data: no ligatures, every line wraps several times. */ +export function jsonCorpusFile(lineCount: number): BenchmarkCorpusFile { + return { + path: "fixtures/data.json", + lines: Array.from({ length: lineCount }, (_, index) => + repeatToLength(`{"id": ${index}, "label": "row ${index}", "tags": ["alpha", "beta"]}, `, 300), + ), + }; +} + +/** A pull-request-sized working diff: one of each shape above. */ +export function pullRequestCorpus(): BenchmarkCorpusFile[] { + return [ + realCodeCorpusFile(), + changelogCorpusFile(), + generatedCodeCorpusFile(1200), + jsonCorpusFile(300), + ]; +} diff --git a/packages/app/src/git/diff-document/model.bench.ts b/packages/app/src/git/diff-document/model.bench.ts new file mode 100644 index 0000000000..2fb25d502a --- /dev/null +++ b/packages/app/src/git/diff-document/model.bench.ts @@ -0,0 +1,317 @@ +import type { ParsedDiffFile } from "@getpaseo/protocol/messages"; +import { bench, describe } from "vitest"; +import { + changelogCorpusFile, + generatedCodeCorpusFile, + jsonCorpusFile, + pullRequestCorpus, + realCodeCorpusFile, + type BenchmarkCorpusFile, +} from "./benchmark-corpus"; +import { buildDiffDocumentModel } from "./model"; +import { + createAdditiveAdvances, + createChunkedAdvanceMeasurer, + createChunkedWidthMeasurer, + createMeasuredAdvances, + requiresShaping, +} from "./text-measurement"; +import type { BuildDiffDocumentModelInput, TextMeasurer } from "./types"; + +// The pure layout work the diff surface does when a diff opens or line wrap is +// toggled, without a browser or Skia. Counts are the backend-independent cost +// owners (how many strings a shaper has to see), timings are the JS overhead +// around them: +// npx vitest bench --project unit src/git/diff-document/model.bench.ts + +const DESKTOP_VIEWPORT = { width: 1400, height: 900 }; +const PHONE_VIEWPORT = { width: 390, height: 800 }; +const CELL_WIDTH = 7.8; + +interface MeasurementStats { + /** Whole strings handed to the backend. */ + calls: number; + /** Characters inside those strings; canvas and Skia cost scales with this. */ + characters: number; +} + +interface Backend { + measurer: TextMeasurer; + stats: MeasurementStats; +} + +function monospaceWidth(text: string): number { + let width = 0; + for (const character of text) width += character.charCodeAt(0) > 0x2e7f ? 2 : 1; + return width * CELL_WIDTH; +} + +function countingMeasure(stats: MeasurementStats): (text: string) => number { + return (text) => { + stats.calls += 1; + stats.characters += text.length; + return monospaceWidth(text); + }; +} + +/** Previous web backend, retained to isolate the cost of width-only probes. */ +function webBackendWithoutWidthProbe(): Backend { + const stats: MeasurementStats = { calls: 0, characters: 0 }; + const measure = countingMeasure(stats); + return { stats, measurer: { measure, measureAdvances: createMeasuredAdvances(measure) } }; +} + +/** + * `createWebTextMeasurer` in surface.web.tsx, with canvas replaced by a counter. + * Width-only probes shape one string per chunk, like the native measurer; the + * widths are the same sums, in the same order, as the last cumulative advance. + */ +function webBackend(): Backend { + const stats: MeasurementStats = { calls: 0, characters: 0 }; + const measure = countingMeasure(stats); + const additive = createAdditiveAdvances(measure); + return { + stats, + measurer: { + measure, + measureAdvances: createMeasuredAdvances(measure), + measureWidth: createChunkedWidthMeasurer((graphemes) => { + const text = graphemes.join(""); + return requiresShaping(text) ? measure(text) : (additive(graphemes).at(-1) ?? 0); + }), + }, + }; +} + +/** `createNativeTextMeasurer` in text.native.ts, with Skia replaced by a counter. */ +function nativeBackend(): Backend { + const stats: MeasurementStats = { calls: 0, characters: 0 }; + const widths = new Map(); + const additive = (graphemes: readonly string[]) => { + let advance = 0; + return graphemes.map((grapheme) => { + let width = widths.get(grapheme); + if (width === undefined) { + stats.calls += 1; + stats.characters += grapheme.length; + width = monospaceWidth(grapheme); + widths.set(grapheme, width); + } + return (advance += width); + }); + }; + const shape = countingMeasure(stats); + return { + stats, + measurer: { + measure(text) { + return requiresShaping(text) ? shape(text) : (additive([...text]).at(-1) ?? 0); + }, + measureWidth: createChunkedWidthMeasurer((graphemes) => { + const text = graphemes.join(""); + return requiresShaping(text) ? shape(text) : (additive(graphemes).at(-1) ?? 0); + }), + measureAdvances: createChunkedAdvanceMeasurer({ + requiresShaping, + measureAdditive: additive, + measureShaped(graphemes) { + shape(graphemes.join("")); + let advance = 0; + return graphemes.map((grapheme) => (advance += monospaceWidth(grapheme))); + }, + }), + }, + }; +} + +function addedFile(file: BenchmarkCorpusFile): ParsedDiffFile { + return { + path: file.path, + isNew: true, + isDeleted: false, + additions: file.lines.length, + deletions: 0, + hunks: [ + { + oldStart: 0, + oldCount: 0, + newStart: 1, + newCount: file.lines.length, + lines: file.lines.map((content) => ({ + type: "add" as const, + content, + tokens: [{ text: content, style: null }], + })), + }, + ], + }; +} + +interface Scenario { + name: string; + files: ParsedDiffFile[]; +} + +const SCENARIOS: Scenario[] = [ + { name: "real code (diff-pane.tsx)", files: [addedFile(realCodeCorpusFile())] }, + { name: "changelog (42 long prose lines)", files: [addedFile(changelogCorpusFile())] }, + { name: "generated code (1200 lines)", files: [addedFile(generatedCodeCorpusFile(1200))] }, + { name: "json (300 lines x 300 chars)", files: [addedFile(jsonCorpusFile(300))] }, + { name: "pull request (all of the above)", files: pullRequestCorpus().map(addedFile) }, +]; + +function input( + scenario: Scenario, + options: { + wrapLines: boolean; + viewport: { width: number; height: number }; + measureText: TextMeasurer; + }, +): BuildDiffDocumentModelInput { + return { + files: scenario.files, + collapsedFilePaths: new Set(), + layout: "unified", + wrapLines: options.wrapLines, + viewportWidth: options.viewport.width, + typography: { family: "monospace", size: 13, lineHeight: 20 }, + measureText: options.measureText, + palette: { + surface: "#000", + headerSurface: "#111", + border: "#222", + foreground: "#fff", + foregroundMuted: "#aaa", + addition: "green", + deletion: "red", + additionBackground: "#010", + deletionBackground: "#100", + emptyBackground: "#111", + selection: "blue", + headerActiveSurface: "#222", + headerBorder: "#333", + statusSuccess: "green", + statusDanger: "red", + statusWarning: "orange", + syntax: {}, + }, + labels: { binary: "Binary", tooLarge: "Too large" }, + // What the surfaces pass at scrollTop 0: five viewports tall. + materializationWindow: { top: 0, height: options.viewport.height * 5 }, + }; +} + +interface Variant { + name: string; + wrapLines: boolean; + viewport: { width: number; height: number }; + backend: () => Backend; +} + +const VARIANTS: Variant[] = [ + { + name: "unwrapped desktop | web", + wrapLines: false, + viewport: DESKTOP_VIEWPORT, + backend: webBackend, + }, + { + name: "wrapped desktop | web", + wrapLines: true, + viewport: DESKTOP_VIEWPORT, + backend: webBackend, + }, + { + name: "wrapped desktop | web without width probe", + wrapLines: true, + viewport: DESKTOP_VIEWPORT, + backend: webBackendWithoutWidthProbe, + }, + { + name: "wrapped phone | web", + wrapLines: true, + viewport: PHONE_VIEWPORT, + backend: webBackend, + }, + { + name: "unwrapped desktop | native", + wrapLines: false, + viewport: DESKTOP_VIEWPORT, + backend: nativeBackend, + }, + { + name: "wrapped desktop | native", + wrapLines: true, + viewport: DESKTOP_VIEWPORT, + backend: nativeBackend, + }, + { + name: "wrapped phone | native", + wrapLines: true, + viewport: PHONE_VIEWPORT, + backend: nativeBackend, + }, +]; + +function countModel(scenario: Scenario, variant: Variant) { + const { measurer, stats } = variant.backend(); + const started = performance.now(); + const model = buildDiffDocumentModel( + input(scenario, { + wrapLines: variant.wrapLines, + viewport: variant.viewport, + measureText: measurer, + }), + ); + const elapsedMs = performance.now() - started; + let materializedCells = 0; + let fragments = 0; + let graphemes = 0; + for (const row of model.rows) { + if (row.kind !== "line") continue; + for (const cell of row.cells) { + if (!cell || cell.fragments.length === 0) continue; + materializedCells += 1; + fragments += cell.fragments.length; + for (const fragment of cell.fragments) graphemes += fragment.graphemes.length; + } + } + const sourceLines = scenario.files.reduce( + (count, file) => count + file.hunks.reduce((total, hunk) => total + hunk.lines.length, 0), + 0, + ); + return { + sourceLines, + materializedCells, + fragments, + graphemeObjects: graphemes, + measureCalls: stats.calls, + measuredCharacters: stats.characters, + coldMs: Number(elapsedMs.toFixed(1)), + }; +} + +const report: Record> = {}; +for (const scenario of SCENARIOS) { + for (const variant of VARIANTS) { + report[`${scenario.name} | ${variant.name}`] = countModel(scenario, variant); + } +} +console.table(report); + +for (const scenario of SCENARIOS) { + describe(scenario.name, () => { + for (const variant of VARIANTS) { + if (variant.backend === nativeBackend) continue; + bench(variant.name, () => { + buildDiffDocumentModel( + input(scenario, { + wrapLines: variant.wrapLines, + viewport: variant.viewport, + measureText: variant.backend().measurer, + }), + ); + }); + } + }); +} diff --git a/packages/app/src/git/diff-document/model.test.ts b/packages/app/src/git/diff-document/model.test.ts index ace965c1ce..9b55a242db 100644 --- a/packages/app/src/git/diff-document/model.test.ts +++ b/packages/app/src/git/diff-document/model.test.ts @@ -10,7 +10,7 @@ import { resolveRelayoutScrollTop, shouldApplyRelayoutScroll, } from "./model"; -import type { BuildDiffDocumentModelInput, TextMeasurer } from "./types"; +import type { BuildDiffDocumentModelInput, DiffCell, TextMeasurer } from "./types"; const measurer: TextMeasurer = { measure: (text) => Array.from(text).length * 10 }; @@ -639,17 +639,119 @@ describe("diff document model", () => { expect(firstLineCells(last, "b.ts")).toBe(firstLineCells(first, "b.ts")); }); - it("keeps wrapped geometry fully measured", () => { + it("replaces estimated wrapped heights through reuse and preserves the scroll anchor", () => { + const changed = fileWithChangedLine("x".repeat(100)); + const files = [changed, file("later.ts")]; + // Deliberately inaccurate M width makes the estimate differ from exact layout. + const measureText = { + measure: (text: string) => (text === "M" ? 5 : Array.from(text).length * 10), + }; + const options = input({ files, measureText }); + const first = buildDiffDocumentModel({ + ...options, + materializationWindow: { top: 30, height: 1 }, + }); + const eager = buildDiffDocumentModel(options); + const exact = buildDiffDocumentModel({ ...options, reuseFrom: [first] }); + expect(first.height).not.toBe(eager.height); + expect(exact.rows).toEqual(eager.rows); + expect(exact.height).toBe(eager.height); + expect(firstLineCells(exact, changed.path)).toBe(firstLineCells(first, changed.path)); + const scrollTop = first.files[1]!.bodyTop + 3; + const nextScrollTop = resolveRelayoutScrollTop(first, exact, scrollTop); + expect(nextScrollTop).toBe(exact.files[1]!.bodyTop + 3); + expect(captureScrollAnchor(exact, nextScrollTop)).toEqual( + captureScrollAnchor(first, scrollTop), + ); + }); + + it("preserves the wrapped source offset when resize leaves the anchor outside the window", () => { + const source = file(); + source.hunks[0]!.lines = Array.from({ length: 200 }, () => ({ + type: "add" as const, + content: "x".repeat(200), + })); + const options = input({ files: [source], viewportWidth: 500 }); + const before = buildDiffDocumentModel(options); + const scrollTop = before.rows[100]!.top + 36; + const anchor = captureScrollAnchor(before, scrollTop)!; + expect(anchor).toMatchObject({ kind: "text", cellOffset: 90 }); + const resizedOptions = { ...options, viewportWidth: 180 }; + const estimated = buildDiffDocumentModel({ + ...resizedOptions, + materializationWindow: { + top: Math.floor(scrollTop / 800) * 800 - 800, + height: 2000, + }, + }); + const estimatedRow = estimated.rows[100]!; + expect(estimatedRow.kind === "line" && estimatedRow.cells[0]?.fragments).toEqual([]); + const restored = resolveRelayoutScrollTop(before, estimated, scrollTop); + const recaptured = captureScrollAnchor(estimated, restored)!; + expect(recaptured).toMatchObject({ kind: "text", cellOffset: 78 }); + + const materialized = buildDiffDocumentModel({ + ...resizedOptions, + materializationWindow: { top: restored - 800, height: 2000 }, + reuseFrom: [estimated], + }); + const eager = buildDiffDocumentModel(resizedOptions); + const expected = resolveRelayoutScrollTop(before, eager, scrollTop); + expect(expected).toBe(28_938); + expect(Math.abs(restored - expected)).toBeLessThan(before.lineHeight); + expect(resolveRelayoutScrollTop(estimated, materialized, restored)).toBe(expected); + }); + + it("materializes the relayout anchor even when off-screen height estimates are inaccurate", () => { + const source = file(); + source.hunks[0]!.lines = Array.from({ length: 200 }, () => ({ + type: "add" as const, + content: "x".repeat(200), + })); + const options = input({ files: [source], viewportWidth: 500 }); + const before = buildDiffDocumentModel(options); + const scrollTop = before.rows[100]!.top + 38; + const anchor = captureScrollAnchor(before, scrollTop)!; + const resizedOptions = { + ...options, + viewportWidth: 180, + measureText: { measure: (text: string) => (text === "M" ? 5 : text.length * 10) }, + }; + const resized = buildDiffDocumentModel({ + ...resizedOptions, + materializationWindow: { top: scrollTop - 800, height: 2000 }, + materializationAnchor: anchor, + }); + const row = resized.rows[100]!; + expect(row.kind === "line" && row.cells[0]!.fragments.length).toBeGreaterThan(0); + const restored = resolveRelayoutScrollTop(before, resized, scrollTop); + const materialized = buildDiffDocumentModel({ + ...resizedOptions, + materializationWindow: { top: restored - 800, height: 2000 }, + materializationAnchor: captureScrollAnchor(resized, restored), + reuseFrom: [resized], + }); + const nextScrollTop = resolveRelayoutScrollTop(resized, materialized, restored); + const nextAnchor = captureScrollAnchor(materialized, nextScrollTop); + // Offset 90 belongs to the fragment beginning at 78 after narrowing. + expect(nextAnchor).toMatchObject({ kind: "text", cellOffset: 78, viewportDelta: -2 }); + expect(nextScrollTop).toBe(resolveScrollAnchor(materialized, anchor)); + }); + + it("materializes wrapped text only inside the window", () => { const model = buildDiffDocumentModel( input({ files: [file("a.ts"), file("b.ts")], wrapLines: true, - materializationWindow: { top: 0, height: FILE_HEADER_HEIGHT }, + materializationWindow: { top: FILE_HEADER_HEIGHT, height: 1 }, }), ); expect(measuredFragments(model, "a.ts")).toBeGreaterThan(0); - expect(measuredFragments(model, "b.ts")).toBeGreaterThan(0); + expect(measuredFragments(model, "b.ts")).toBe(0); + expect( + model.rows.filter((row) => row.kind === "line" && row.cells.some(hasFragments)), + ).toHaveLength(1); }); }); @@ -798,3 +900,7 @@ function reviewActionsWithEditor( onDeleteComment() {}, }; } + +function hasFragments(cell: DiffCell | null): boolean { + return cell !== null && cell.fragments.length > 0; +} diff --git a/packages/app/src/git/diff-document/model.ts b/packages/app/src/git/diff-document/model.ts index fb2b9a04f0..67efe06c2b 100644 --- a/packages/app/src/git/diff-document/model.ts +++ b/packages/app/src/git/diff-document/model.ts @@ -154,27 +154,38 @@ function appendReusableFileRows(candidate: { }): FileRowsResult { const reusedRows = candidate.model.rows.slice(candidate.file.rowStart, candidate.file.rowEnd); const retainsRowGeometry = - !candidate.input.wrapLines && candidate.model.reviewGeometryKey === candidate.reviewGeometryKey && candidate.file.top === candidate.fileTop && candidate.file.fileIndex === candidate.fileIndex && candidate.file.rowStart === candidate.rows.length; let top = candidate.bodyTop; for (const reusedRow of reusedRows) { - let nextRow = retainsRowGeometry ? reusedRow : repositionReusedRow(reusedRow, candidate, top); + let nextRow = + retainsRowGeometry && reusedRow.top === top + ? reusedRow + : repositionReusedRow(reusedRow, candidate, top); if ( nextRow.kind === "line" && - intersectsMaterializationWindow(candidate.input, top, top + nextRow.height) && + (intersectsMaterializationWindow(candidate.input, top, top + nextRow.height) || + containsMaterializationAnchor(candidate.input, candidate.file.path, nextRow.cells)) && nextRow.cells.some((cell) => cell && cell.fragments.length === 0) ) { + const cells = materializeCells( + nextRow.cells, + candidate.file.file, + candidate.file.gutterWidth, + candidate.input, + ); nextRow = { ...nextRow, - cells: materializeCells( - nextRow.cells, - candidate.file.file, - candidate.file.gutterWidth, - candidate.input, - ), + cells, + height: + Math.max( + candidate.input.typography.lineHeight, + ...cells.map( + (cell) => (cell?.fragments.length ?? 1) * candidate.input.typography.lineHeight, + ), + ) + nextRow.reviewHeight, }; } candidate.rows.push(nextRow); @@ -240,6 +251,7 @@ function appendNewFileRows(candidate: { const lines = geometryLines( lineSources(candidate.file, candidate.input.layout, false), candidate.input, + candidate.gutterWidth, ); const fileBottom = candidate.bodyTop + @@ -252,8 +264,8 @@ function appendNewFileRows(candidate: { let maximumHorizontalOverflow = 0; for (const line of lines) { const shouldMaterialize = - candidate.input.wrapLines || - intersectsMaterializationWindow(candidate.input, top, top + line.height); + intersectsMaterializationWindow(candidate.input, top, top + line.height) || + containsMaterializationAnchor(candidate.input, candidate.file.path, line.cells); const cells = shouldMaterialize ? materializeCells(line.cells, candidate.file, candidate.gutterWidth, candidate.input) : line.cells; @@ -275,7 +287,7 @@ function appendNewFileRows(candidate: { candidate.input.typography.lineHeight, ...cells.map((cell) => (cell?.fragments.length ?? 1) * candidate.input.typography.lineHeight), ); - const height = textHeight + line.reviewHeight; + const height = shouldMaterialize ? textHeight + line.reviewHeight : line.height; candidate.rows.push({ kind: "line", index: candidate.rows.length, @@ -412,13 +424,14 @@ function cellSource(line: SplitDiffDisplayLine | null, includeTokens: boolean): }; } -function geometryCell(source: CellSource): DiffCell { +function geometryCell(source: CellSource, estimatedWrapColumns: number): DiffCell { return { type: source.type, content: source.content, lineNumber: source.lineNumber, tokens: [], fragments: [], + estimatedWrapColumns, reviewTarget: source.reviewTarget, sourceIdentity: source.sourceIdentity, }; @@ -427,20 +440,87 @@ function geometryCell(source: CellSource): DiffCell { function geometryLines( sources: Array<[CellSource] | [CellSource | null, CellSource | null]>, input: BuildDiffDocumentModelInput, + gutterWidth: number, ): GeometryLine[] { + const characterWidth = input.wrapLines ? input.measureText.measure("M") : 0; return sources.map((sourceCells) => { + const columns = input.wrapLines + ? Math.max( + 1, + Math.floor( + (input.viewportWidth / sourceCells.length - gutterWidth - CODE_HORIZONTAL_PADDING) / + characterWidth, + ), + ) + : Infinity; const cells = sourceCells.map((source) => - source ? geometryCell(source) : null, + source ? geometryCell(source, columns) : null, ) as DiffLineRow["cells"]; const reviewHeight = reviewHeightForCells(cells, input); return { cells, reviewHeight, - height: input.typography.lineHeight + reviewHeight, + // Unseen wrapped rows use a monospace estimate; materialization replaces + // it with the exact fragment count without changing source identity. + height: + input.typography.lineHeight * + Math.max( + 1, + ...cells.map((cell) => { + return cell && input.wrapLines + ? Math.ceil(estimatedDisplayOffset(cell.content) / columns) + : 1; + }), + ) + + reviewHeight, }; }); } +// Use the same tab expansion and column count for estimated heights and anchors. +function estimatedDisplayOffset(text: string): number { + return text.length + (text.match(/\t/g)?.length ?? 0) * 3; +} + +function estimatedVisualLine(cell: DiffCell, sourceOffset: number): number { + return Math.floor( + estimatedDisplayOffset(cell.content.slice(0, sourceOffset)) / + (cell.estimatedWrapColumns ?? Infinity), + ); +} + +function estimatedFragment(cell: DiffCell, visualIndex: number, lineHeight: number) { + const columns = cell.estimatedWrapColumns ?? Infinity; + const lastIndex = Math.max(0, Math.ceil(estimatedDisplayOffset(cell.content) / columns) - 1); + const index = Math.min(visualIndex, lastIndex); + const displayOffset = index === 0 ? 0 : index * columns; + let start = Math.min(displayOffset, cell.content.length); + if (cell.content.includes("\t")) { + let offset = 0; + start = 0; + while (start < cell.content.length && offset < displayOffset) { + offset += cell.content[start] === "\t" ? 4 : 1; + start += 1; + } + } + return { start, top: index * lineHeight }; +} + +// A resize can move the anchor outside the old window. Measure that row in the +// same pass: estimated columns cannot identify exact shaped-text fragments. +function containsMaterializationAnchor( + input: BuildDiffDocumentModelInput, + path: string, + cells: DiffLineRow["cells"], +): boolean { + const anchor = input.materializationAnchor; + return ( + anchor?.kind === "text" && + anchor.path === path && + cells.some((cell) => cell && sameSourceIdentity(cell.sourceIdentity, anchor.sourceIdentity)) + ); +} + function intersectsMaterializationWindow( input: BuildDiffDocumentModelInput, fileTop: number, @@ -795,17 +875,27 @@ export function captureScrollAnchor( } const textY = Math.max(0, Math.min(scrollTop - row.top, row.height - row.reviewHeight)); const visualIndex = Math.max(0, Math.floor(textY / model.lineHeight)); - let cellIndex = row.cells.findIndex((cell) => Boolean(cell?.fragments[visualIndex])); + let cellIndex = row.cells.findIndex( + (cell) => + cell && + (cell.fragments.length > 0 + ? Boolean(cell.fragments[visualIndex]) + : estimatedFragment(cell, visualIndex, model.lineHeight).top === + visualIndex * model.lineHeight), + ); if (cellIndex < 0) cellIndex = row.cells.findIndex((cell) => cell !== null); const cell = row.cells[cellIndex]; if (!cell) return { kind: "header", path: file.path, viewportDelta: row.top - scrollTop }; - const fragment = cell.fragments[Math.min(cell.fragments.length - 1, visualIndex)]; - const anchorY = row.top + (fragment?.top ?? 0); + const fragment = + cell.fragments.length > 0 + ? cell.fragments[Math.min(cell.fragments.length - 1, visualIndex)]! + : estimatedFragment(cell, visualIndex, model.lineHeight); + const anchorY = row.top + fragment.top; return { kind: "text", path: file.path, sourceIdentity: cell.sourceIdentity, - cellOffset: fragment?.start ?? 0, + cellOffset: fragment.start, viewportDelta: anchorY - scrollTop, }; } @@ -831,8 +921,10 @@ export function resolveScrollAnchor(model: DiffDocumentModel, anchor: DiffScroll const fragment = cell.fragments.find( (candidate) => candidate.start <= anchor.cellOffset && anchor.cellOffset < candidate.end, - ) ?? cell.fragments.at(-1); - return Math.max(0, row.top + (fragment?.top ?? 0) - anchor.viewportDelta); + ) ?? + cell.fragments.at(-1) ?? + estimatedFragment(cell, estimatedVisualLine(cell, anchor.cellOffset), model.lineHeight); + return Math.max(0, row.top + fragment.top - anchor.viewportDelta); } export function resolveRelayoutScrollTop( diff --git a/packages/app/src/git/diff-document/surface.native.tsx b/packages/app/src/git/diff-document/surface.native.tsx index 2063198712..00a47437cd 100644 --- a/packages/app/src/git/diff-document/surface.native.tsx +++ b/packages/app/src/git/diff-document/surface.native.tsx @@ -38,6 +38,7 @@ import { } from "./horizontal-offsets"; import { buildDiffDocumentModel, + captureScrollAnchor, resolveRelayoutScrollTop, retainReusableModels, shouldApplyRelayoutScroll, @@ -138,6 +139,9 @@ export function DiffSurface(props: DiffSurfaceProps) { tooLarge: t("workspace.git.diff.tooLarge"), }, materializationWindow: diffMaterializationWindow(fileWindowTop, viewport.height), + materializationAnchor: previousModelRef.current + ? captureScrollAnchor(previousModelRef.current, scrollTop.get()) + : null, reuseFrom, }); reusableModelRef.current = { @@ -148,6 +152,7 @@ export function DiffSurface(props: DiffSurfaceProps) { }, [ measurement, fileWindowTop, + scrollTop, props.collapsedFilePaths, props.displayPreferences.layout, props.displayPreferences.wrapLines, diff --git a/packages/app/src/git/diff-document/surface.web.tsx b/packages/app/src/git/diff-document/surface.web.tsx index 97801b708f..393f6dfcd7 100644 --- a/packages/app/src/git/diff-document/surface.web.tsx +++ b/packages/app/src/git/diff-document/surface.web.tsx @@ -28,10 +28,20 @@ import { } from "./hit-testing"; import { retainHorizontalOffsetMapForPaths } from "./horizontal-offsets"; import { HorizontalScroll } from "./horizontal-scroll.web"; -import { buildDiffDocumentModel, FILE_HEADER_HEIGHT, resolveRelayoutScrollTop } from "./model"; +import { + buildDiffDocumentModel, + captureScrollAnchor, + FILE_HEADER_HEIGHT, + resolveRelayoutScrollTop, +} from "./model"; import { paintWebFileHeader, paintWebViewport } from "./paint.web"; import { hasPointerDragStarted } from "./pointer-gesture"; -import { createMeasuredAdvances } from "./text-measurement"; +import { + createMeasuredAdvances, + createAdditiveAdvances, + createChunkedWidthMeasurer, + requiresShaping, +} from "./text-measurement"; import { retainDiffViewport } from "./viewport"; import type { DiffHit, @@ -183,6 +193,9 @@ export function DiffSurface(props: DiffSurfaceProps) { tooLarge: t("workspace.git.diff.tooLarge"), }, materializationWindow: diffMaterializationWindow(fileWindowTop, viewport.height), + materializationAnchor: previousModelRef.current + ? captureScrollAnchor(previousModelRef.current, scrollTopRef.current) + : null, }); return next; }, [ @@ -1166,5 +1179,13 @@ function createWebTextMeasurer(typography: DiffTypography): TextMeasurer { }; // Canvas exposes no glyph coverage, so `requiresShaping` alone decides which // runs a shaper has to see -- there is no `glyphIds` to fall back on. - return { measure, measureAdvances: createMeasuredAdvances((text) => measure(text)) }; + const additive = createAdditiveAdvances(measure); + return { + measure, + measureAdvances: createMeasuredAdvances(measure), + measureWidth: createChunkedWidthMeasurer((graphemes) => { + const text = graphemes.join(""); + return requiresShaping(text) ? measure(text) : (additive(graphemes).at(-1) ?? 0); + }), + }; } diff --git a/packages/app/src/git/diff-document/types.ts b/packages/app/src/git/diff-document/types.ts index 4ac8125445..d98880eb8c 100644 --- a/packages/app/src/git/diff-document/types.ts +++ b/packages/app/src/git/diff-document/types.ts @@ -112,6 +112,8 @@ export interface DiffCell { lineNumber: number | null; tokens: DiffTokenRun[]; fragments: DiffFragment[]; + /** Monospace columns per visual line until this cell is measured. */ + estimatedWrapColumns?: number; reviewTarget: ReviewableDiffTarget | null; sourceIdentity: DiffSourceIdentity; } @@ -185,6 +187,8 @@ export interface BuildDiffDocumentModelInput { reviewActions?: InlineReviewActions; labels: { binary: string; tooLarge: string }; materializationWindow?: { top: number; height: number }; + /** Also measure the anchored row so relayout can restore its exact fragment. */ + materializationAnchor?: DiffScrollAnchor | null; /** A geometry-compatible model whose unchanged file measurements may be reused. */ reuseFrom?: readonly DiffDocumentModel[]; } diff --git a/packages/app/src/git/diff-document/workspace-cache.test.ts b/packages/app/src/git/diff-document/workspace-cache.test.ts index ddf9972a46..a264d417ca 100644 --- a/packages/app/src/git/diff-document/workspace-cache.test.ts +++ b/packages/app/src/git/diff-document/workspace-cache.test.ts @@ -95,6 +95,37 @@ describe("diff document workspace cache", () => { expect(stats.calls).toBe(0); }); + it("materializes a new anchor when the viewport window is unchanged", () => { + const cache = createDiffDocumentWorkspaceCache(); + const source = diffFile(); + source.hunks[0]!.lines = Array.from({ length: 100 }, () => ({ + type: "add" as const, + content: "x".repeat(200), + })); + const { measureText } = countingMeasurer(); + const input = modelInput([source], measureText, { + wrapLines: true, + materializationWindow: { top: 30, height: 54 }, + }); + const first = cache.buildModel(input); + const anchored = cache.buildModel({ + ...input, + materializationAnchor: { + kind: "text", + path: source.path, + sourceIdentity: { hunkIndex: 0, lineIndex: 50, side: "new" }, + cellOffset: 90, + viewportDelta: -2, + }, + }); + const firstRow = first.rows[50]!; + const anchoredRow = anchored.rows[50]!; + expect(firstRow.kind === "line" && firstRow.cells[0]!.fragments.length).toBe(0); + expect(anchoredRow.kind === "line" && anchoredRow.cells[0]!.fragments.length).toBeGreaterThan( + 0, + ); + }); + it("retains text cells for unchanged files when another file changes", () => { const cache = createDiffDocumentWorkspaceCache(); const { measureText } = countingMeasurer(); diff --git a/packages/app/src/git/diff-document/workspace-cache.tsx b/packages/app/src/git/diff-document/workspace-cache.tsx index 5b9921e31d..dac4d96c2e 100644 --- a/packages/app/src/git/diff-document/workspace-cache.tsx +++ b/packages/app/src/git/diff-document/workspace-cache.tsx @@ -128,7 +128,9 @@ function exactModelKey(input: Omit): s const materializationWindow = input.materializationWindow ? [input.materializationWindow.top, input.materializationWindow.height] : null; - return JSON.stringify([collapsedFilePaths, reviewGeometry, materializationWindow]); + const anchor = input.materializationAnchor; + const anchoredRow = anchor?.kind === "text" ? [anchor.path, anchor.sourceIdentity] : null; + return JSON.stringify([collapsedFilePaths, reviewGeometry, materializationWindow, anchoredRow]); } function typographyKey(typography: DiffTypography): string { diff --git a/packages/app/src/hooks/use-acp-provider-catalog.test.ts b/packages/app/src/hooks/use-acp-provider-catalog.test.ts index a30b27ce8f..41806de307 100644 --- a/packages/app/src/hooks/use-acp-provider-catalog.test.ts +++ b/packages/app/src/hooks/use-acp-provider-catalog.test.ts @@ -62,7 +62,9 @@ describe("ACP provider catalog", () => { expect(findProvider("minimax-code")).toMatchObject({ title: "MiniMax Code", version: "0.6.13", - command: ["npx", "-y", "@minimax-ai/code@0.6.13", "acp"], + // The package publishes `mcode`, not `code`, so npx needs the package and + // the binary named separately. + command: ["npx", "-y", "-p", "@minimax-ai/code@0.6.13", "mcode", "acp"], }); expect(findProvider("minimax-code").iconSvg).toContain(" { - const module = await import("./use-agent-history"); - fetchAgentHistoryBatch = module.fetchAgentHistoryBatch; - fetchAgentHistoryPage = module.fetchAgentHistoryPage; - collectAgentHistoryHostErrors = module.collectAgentHistoryHostErrors; -}); +const { fetchAgentHistoryBatch, fetchAgentHistoryPage, collectAgentHistoryHostErrors } = + await import("./use-agent-history"); type FetchAgentHistory = DaemonClient["fetchAgentHistory"]; type FetchAgentHistoryResult = Awaited>; diff --git a/packages/app/src/hooks/use-agent-initialization.test.ts b/packages/app/src/hooks/use-agent-initialization.test.ts index f2726fba02..e517021b6b 100644 --- a/packages/app/src/hooks/use-agent-initialization.test.ts +++ b/packages/app/src/hooks/use-agent-initialization.test.ts @@ -78,6 +78,7 @@ describe("ensureAgentIsInitialized", () => { cursor: { epoch: "epoch-1", seq: 42 }, limit: TIMELINE_FETCH_PAGE_SIZE, projection: "projected", + wholeTurns: true, }, }, ]); @@ -105,6 +106,7 @@ describe("ensureAgentIsInitialized", () => { direction: "tail", limit: TIMELINE_FETCH_PAGE_SIZE, projection: "projected", + wholeTurns: true, }, }, ]); @@ -148,6 +150,7 @@ describe("ensureAgentIsInitialized", () => { direction: "tail", limit: TIMELINE_FETCH_PAGE_SIZE, projection: "projected", + wholeTurns: true, }, }, ]); @@ -192,6 +195,7 @@ describe("ensureAgentIsInitialized", () => { cursor: { epoch: "epoch-1", seq: 12 }, limit: TIMELINE_FETCH_PAGE_SIZE, projection: "projected", + wholeTurns: true, }, }, ]); @@ -283,6 +287,7 @@ describe("refreshAgent", () => { direction: "tail", limit: TIMELINE_FETCH_PAGE_SIZE, projection: "projected", + wholeTurns: true, }, }, ]); diff --git a/packages/app/src/hooks/use-agent-screen-state-machine.test.ts b/packages/app/src/hooks/use-agent-screen-state-machine.test.ts index 19caef4f8b..68102ed131 100644 --- a/packages/app/src/hooks/use-agent-screen-state-machine.test.ts +++ b/packages/app/src/hooks/use-agent-screen-state-machine.test.ts @@ -422,6 +422,23 @@ describe("deriveAgentScreenViewState", () => { expect(result.memory.lastReadyAgent).toBeNull(); }); + it.each(["error", "retrying"] as const)("shows archived history sync %s", (status) => { + const result = deriveAgentScreenViewState({ + input: { + ...createBaseInput(), + agent: createAgent("agent-1"), + isArchived: true, + hasHydratedHistoryBefore: true, + visibilityCatchUpStatus: status, + }, + memory: createBaseMemory(), + }); + expect(expectReadyState(result.state).sync).toEqual({ + status: "sync_error", + isRetrying: status === "retrying", + }); + }); + it("renders an archived agent before provider history is initialized", () => { const result = deriveAgentScreenViewState({ input: { diff --git a/packages/app/src/hooks/use-agent-screen-state-machine.ts b/packages/app/src/hooks/use-agent-screen-state-machine.ts index 591fd1abb1..e0cc75ee06 100644 --- a/packages/app/src/hooks/use-agent-screen-state-machine.ts +++ b/packages/app/src/hooks/use-agent-screen-state-machine.ts @@ -175,10 +175,14 @@ function resolveAgentScreenSync(args: { hadInitialSyncFailure: boolean; }): AgentScreenReadySyncState { const { input, hadInitialSyncFailure } = args; - if (input.isArchived) { + if ( + input.isArchived && + input.visibilityCatchUpStatus !== "error" && + input.visibilityCatchUpStatus !== "retrying" + ) { return { status: "idle" }; } - if (!input.isConnected) { + if (!input.isConnected && !input.isArchived) { return { status: "reconnecting" }; } if (input.missingAgentState.kind === "error") { diff --git a/packages/app/src/hooks/use-load-older-agent-history.test.ts b/packages/app/src/hooks/use-load-older-agent-history.test.ts index 1da68b4edf..3259631992 100644 --- a/packages/app/src/hooks/use-load-older-agent-history.test.ts +++ b/packages/app/src/hooks/use-load-older-agent-history.test.ts @@ -152,6 +152,7 @@ describe("loadOlderAgentHistory", () => { cursor: { epoch: "epoch-1", seq: 10 }, limit: TIMELINE_FETCH_PAGE_SIZE, projection: "projected", + wholeTurns: true, }, }, ]); diff --git a/packages/app/src/hooks/use-providers-snapshot.test.ts b/packages/app/src/hooks/use-providers-snapshot.test.ts index 2f3c90b340..0c730cddbd 100644 --- a/packages/app/src/hooks/use-providers-snapshot.test.ts +++ b/packages/app/src/hooks/use-providers-snapshot.test.ts @@ -1,4 +1,4 @@ -import { QueryClient } from "@tanstack/react-query"; +import { QueryClient, QueryObserver } from "@tanstack/react-query"; import { beforeEach, describe, expect, it } from "vitest"; import type { DaemonClient } from "@getpaseo/client/internal/daemon-client"; @@ -8,7 +8,7 @@ import { expandProviderSnapshot, } from "@getpaseo/protocol/provider-snapshot-codec"; import type { CachedProviderSnapshot, ProviderSnapshotCache } from "@/data/provider-snapshot-cache"; -import { draftAgentCommandsQueryKey } from "@/hooks/agent-commands-query"; +import { draftAgentCommandsQueryKey, sessionAgentCommandsQueryKey } from "@/agent-commands/cache"; import { providerSnapshotIcons } from "@/data/provider-icons"; import { applyProvidersSnapshotUpdate, type ProvidersSnapshotUpdate } from "@/data/push-router"; import { @@ -363,6 +363,153 @@ describe("applyProvidersSnapshotUpdate", () => { }; } + it("refreshes active commands only when their provider changes after discovery", async () => { + const key = sessionAgentCommandsQueryKey({ serverId, agentId: "agent-1" }); + let requests = 0; + const observer = new QueryObserver(queryClient, { + queryKey: key, + queryFn: async () => { + requests++; + return [{ name: "review" }]; + }, + staleTime: Infinity, + meta: { agentCommandProvider: "codex", agentCommandCwd: "/repo-a" }, + }); + const unsubscribe = observer.subscribe(() => {}); + await observer.refetch({ cancelRefetch: false }); + expect(requests).toBe(1); + const codex = codexEntry("ready", [readyCodexModel]); + const other = { provider: "claude", status: "loading", enabled: true } as ProviderSnapshotEntry; + await applyProvidersSnapshotUpdate({ + client: createClient(), + serverId, + queryClient, + message: updateMessage([codexEntry("loading"), other], "/repo-a"), + }); + expect(requests).toBe(1); + await applyProvidersSnapshotUpdate({ + client: createClient(), + serverId, + queryClient, + message: updateMessage([codex, other], "/repo-a"), + }); + expect(requests).toBe(1); + await applyProvidersSnapshotUpdate({ + client: createClient(), + serverId, + queryClient, + message: updateMessage([codex, { ...other, status: "ready" }], "/repo-a"), + }); + expect(requests).toBe(1); + await applyProvidersSnapshotUpdate({ + client: createClient(), + serverId, + queryClient, + message: updateMessage( + [ + { ...codex, fetchedAt: "2026-01-01T00:00:02.000Z" }, + { ...other, status: "ready" }, + ], + "/repo-a", + ), + }); + expect(requests).toBe(1); + queryClient.setQueryData( + providersSnapshotQueryKey(serverId, "/repo-b"), + providersSnapshot([codex]), + ); + await applyProvidersSnapshotUpdate({ + client: createClient(), + serverId, + queryClient, + message: updateMessage( + [codexEntry("ready", [{ ...readyCodexModel, label: "Other checkout" }])], + "/repo-b", + ), + }); + expect(requests).toBe(1); + await applyProvidersSnapshotUpdate({ + client: createClient(), + serverId, + queryClient, + message: updateMessage( + [ + codexEntry("ready", [{ ...readyCodexModel, label: "Updated" }]), + { ...other, status: "ready" }, + ], + "/repo-a", + ), + }); + await observer.refetch({ cancelRefetch: false }); + expect(requests).toBe(2); + unsubscribe(); + queryClient.clear(); + }); + + it("retries a failed command discovery when its provider first becomes ready", async () => { + const key = sessionAgentCommandsQueryKey({ serverId, agentId: "agent-1" }); + let ready = false; + let requests = 0; + const observer = new QueryObserver(queryClient, { + queryKey: key, + queryFn: async () => { + requests++; + if (!ready) throw new Error("provider unavailable"); + return [{ name: "review" }]; + }, + retry: false, + meta: { agentCommandProvider: "codex", agentCommandCwd: "/repo-a" }, + }); + const unsubscribe = observer.subscribe(() => {}); + await observer.refetch({ cancelRefetch: false }); + expect(observer.getCurrentResult().isError).toBe(true); + ready = true; + await applyProvidersSnapshotUpdate({ + client: createClient(), + serverId, + queryClient, + message: updateMessage([codexEntry("ready", [readyCodexModel])], "/repo-a"), + }); + await observer.refetch({ cancelRefetch: false }); + expect(requests).toBe(2); + expect(observer.getCurrentResult().data).toEqual([{ name: "review" }]); + unsubscribe(); + queryClient.clear(); + }); + + it("refreshes again when its provider changes during an active refresh", async () => { + const key = sessionAgentCommandsQueryKey({ serverId, agentId: "agent-1" }); + queryClient.setQueryData(key, [{ name: "old" }]); + let requests = 0; + const waiting = new Promise<{ name: string }[]>(() => {}); + const observer = new QueryObserver(queryClient, { + queryKey: key, + queryFn: async () => (++requests === 1 ? waiting : [{ name: "new" }]), + staleTime: Infinity, + meta: { agentCommandProvider: "codex", agentCommandCwd: "/repo-a" }, + }); + const unsubscribe = observer.subscribe(() => {}); + queryClient.setQueryData( + providersSnapshotQueryKey(serverId, "/repo-a"), + providersSnapshot([codexEntry("ready", [readyCodexModel])]), + ); + const send = (label: string) => + applyProvidersSnapshotUpdate({ + client: createClient(), + serverId, + queryClient, + message: updateMessage([codexEntry("ready", [{ ...readyCodexModel, label }])], "/repo-a"), + }); + await send("First change"); + expect(requests).toBe(1); + await send("Second change"); + expect(requests).toBe(2); + await observer.refetch({ cancelRefetch: false }); + expect(observer.getCurrentResult().data).toEqual([{ name: "new" }]); + unsubscribe(); + queryClient.clear(); + }); + it("routes updates to the home query cache when the message carries no cwd", async () => { await applyProvidersSnapshotUpdate({ client: createClient(), @@ -455,6 +602,10 @@ describe("applyProvidersSnapshotUpdate", () => { draftConfig: { provider: "codex", cwd: "/repo-a" }, }); queryClient.setQueryData(commandsKey, [{ name: "compact", description: "", argumentHint: "" }]); + queryClient.setQueryData( + providersSnapshotQueryKey(serverId, "/repo-a"), + providersSnapshot([codexEntry("ready")]), + ); await applyProvidersSnapshotUpdate({ client: createClient(), diff --git a/packages/app/src/hosts/host-chooser.tsx b/packages/app/src/hosts/host-chooser.tsx index 5e4d7f053c..3d807ba3a1 100644 --- a/packages/app/src/hosts/host-chooser.tsx +++ b/packages/app/src/hosts/host-chooser.tsx @@ -1,13 +1,7 @@ +import { Modal } from "@/components/ui/modal"; import { usePanelStore } from "@/stores/panel-store"; import { createElement, useCallback, useEffect, useMemo, useRef, useState } from "react"; -import { - Modal, - Pressable, - ScrollView, - Text, - View, - type PressableStateCallbackType, -} from "react-native"; +import { Pressable, ScrollView, Text, View, type PressableStateCallbackType } from "react-native"; import { EditingTextInput as TextInput, type EditingTextInputHandle, diff --git a/packages/app/src/i18n/resources.test.ts b/packages/app/src/i18n/resources.test.ts index 18ba3f041e..b73b2c4fec 100644 --- a/packages/app/src/i18n/resources.test.ts +++ b/packages/app/src/i18n/resources.test.ts @@ -832,7 +832,6 @@ describe("translation resources", () => { expect(en.common.placeholders.search).toBe("Search..."); expect(en.common.empty.noResults).toBe("No results found"); expect(en.common.empty.noOptionsMatchSearch).toBe("No options match your search."); - expect(en.toolCallDetails.subAgentActivity).toBe("Sub-agent activity"); expect(en.panels.file.failedToLoadPreview).toBe("Failed to load file preview"); }); diff --git a/packages/app/src/i18n/resources/ar.ts b/packages/app/src/i18n/resources/ar.ts index 6bfc30095c..8d7c2a2950 100644 --- a/packages/app/src/i18n/resources/ar.ts +++ b/packages/app/src/i18n/resources/ar.ts @@ -67,6 +67,7 @@ export const ar: TranslationResources = { daemonClientUnavailable: "عميل Daemon غير متوفر", daemonClientDisconnected: "تم قطع اتصال عميل Daemon", noFileFound: "لم يتم العثور على ملف لـ{{token}}", + folderOutsideWorkspace: "{{path}} خارج مساحة العمل هذه", unexpectedDictationError: "حدث خطأ غير متوقع أثناء معالجة الإملاء.", }, connectionStatus: { @@ -616,6 +617,7 @@ export const ar: TranslationResources = { terminal: { hostDisconnected: "Host غير متصل", updateHost: "حدّث المضيف لاستخدام عارض الطرفية الأصلي.", + restoreRequiresUpdate: "حدّث المضيف لعرض الطرفيات.", unableToSubscribe: "غير قادر على الاشتراك في المحطة", fileUploaded: "تم رفع الملف", pasteFileFailed: "تعذر لصق الملف: {{reason}}", @@ -1913,7 +1915,6 @@ export const ar: TranslationResources = { parent: { backToParent: "العودة إلى الوكيل الأصلي", backTo: "العودة إلى {{label}}", - parent: "الأصل", parentAgent: "الوكيل الأصلي", openParent: "فتح الوكيل الأصلي", }, @@ -2013,17 +2014,17 @@ export const ar: TranslationResources = { toolCallDetails: { error: "خطأ", empty: "لا توجد تفاصيل إضافية متاحة", - subAgentActivity: "نشاط الوكيل الفرعي", input: "مدخل", output: "الإخراج", }, turnSummary: { - messages: { - one: "كتب {{count}} رسالة", - other: "كتب {{count}} رسائل", - }, + details: "عرض تفاصيل الجولة", + sentBy: "أرسلها {{name}}", + showMore: "عرض المزيد", + showLess: "عرض أقل", }, toolCallGroup: { + thought: "فكّر", editedFiles: { one: "حرّر {{count}} ملفًا", other: "حرّر {{count}} ملفات", @@ -2091,6 +2092,11 @@ export const ar: TranslationResources = { }, }, providerUsage: { + checkUsage: "التحقق من الاستخدام", + checkUsageHint: "ينطبق على {{host}} على جميع الأجهزة", + off: "التحقق من الاستخدام متوقف على {{host}}.", + turnOn: "تشغيل", + options: "الإعدادات", refreshFailed: "تعذّر تحديث الاستخدام", noHosts: "لا توجد مضيفات متصلة", @@ -2156,6 +2162,7 @@ export const ar: TranslationResources = { minutes_few: "{{value}} دقائق", minutes_many: "{{value}} دقيقة", minutes_other: "{{value}} دقيقة", + pair: "{{first}} و{{second}}", }, timing: { lastUpdated: "آخر تحديث {{relativeTime}}", @@ -2163,6 +2170,8 @@ export const ar: TranslationResources = { resetTimePassed: "مضى وقت إعادة التعيين", resettingNow: "تتم إعادة التعيين الآن", resetsIn: "تتم إعادة التعيين خلال {{duration}}", + resetsAtWeekday: "{{weekday}} {{time}}", + resetsAtDate: "{{date}}، {{time}}", runsOutNow: "ينفد الآن", runsOutIn: "ينفد خلال {{duration}}", justNow: "الآن", @@ -2777,6 +2786,14 @@ export const ar: TranslationResources = { }, agents: { unavailable: "Connect to this host to manage agents", + resumeOnStartup: { + title: "استئناف الوكلاء بعد إعادة التشغيل", + info: "إعادة فتح الوكلاء الذين كانوا يعملون عند توقف المضيف وإرسال طلب الاستئناف. ينطبق ذلك بعد إعادة التشغيل العادية والتعطّل.", + hint: "متابعة العمل المنقطع تلقائيًا.", + prompt: "طلب الاستئناف", + edit: "تحرير", + editAccessibilityLabel: "تعديل الطلب", + }, idleRuntimeCleanup: { title: "تحرير الوكلاء الخاملين", hint: "تحرير الذاكرة بعد ساعة من الخمول.", @@ -2872,6 +2889,10 @@ export const ar: TranslationResources = { requestFailedTitle: "خطأ", requestFailedMessage: "فشل في إرسال طلب إعادة التشغيل. يقوم Paseo بإعادة الاتصال تلقائيًا - حاول مرة أخرى بمجرد ظهور المضيف على أنه متصل بالإنترنت.", + closeTerminals: "إعادة التشغيل وإغلاق الطرفيات", + closeTerminalsHint: "يعيد التشغيل ويغلق أيضًا كل الطرفيات المفتوحة على هذا المضيف.", + closeTerminalsConfirmMessage: + "سيُعاد تشغيل الخدمة وتُغلق كل طرفياتها، مما ينهي البرامج التي تعمل فيها. سيعيد التطبيق الاتصال تلقائيًا.", dialogFailedMessage: "غير قادر على فتح مربع حوار تأكيد إعادة التشغيل.", }, update: { diff --git a/packages/app/src/i18n/resources/en.ts b/packages/app/src/i18n/resources/en.ts index ff1e80d88b..1f61a83f12 100644 --- a/packages/app/src/i18n/resources/en.ts +++ b/packages/app/src/i18n/resources/en.ts @@ -63,6 +63,7 @@ export const en = { daemonClientUnavailable: "Daemon client unavailable", daemonClientDisconnected: "Daemon client is disconnected", noFileFound: "No file found for {{token}}", + folderOutsideWorkspace: "{{path}} is outside this workspace", unexpectedDictationError: "An unexpected error occurred while handling dictation.", }, connectionStatus: { @@ -613,6 +614,7 @@ export const en = { terminal: { hostDisconnected: "Host is not connected", updateHost: "Update the host to use the native terminal renderer.", + restoreRequiresUpdate: "Update the host to view terminals.", unableToSubscribe: "Unable to subscribe to terminal", fileUploaded: "File uploaded", pasteFileFailed: "Failed to paste file: {{reason}}", @@ -1938,7 +1940,6 @@ export const en = { parent: { backToParent: "Back to parent", backTo: "Back to {{label}}", - parent: "Parent", parentAgent: "Parent agent", openParent: "Open parent", }, @@ -2038,17 +2039,17 @@ export const en = { toolCallDetails: { error: "Error", empty: "No additional details available", - subAgentActivity: "Sub-agent activity", input: "Input", output: "Output", }, turnSummary: { - messages: { - one: "wrote {{count}} message", - other: "wrote {{count}} messages", - }, + details: "View turn details", + sentBy: "Sent by {{name}}", + showMore: "Show more", + showLess: "Show less", }, toolCallGroup: { + thought: "Thought", editedFiles: { one: "edited {{count}} file", other: "edited {{count}} files", @@ -2116,6 +2117,11 @@ export const en = { }, }, providerUsage: { + checkUsage: "Check usage", + checkUsageHint: "Applies to {{host}} on every device", + off: "Usage is off on {{host}}.", + turnOn: "Turn on", + options: "Settings", refreshFailed: "Unable to refresh usage", noHosts: "No connected hosts", @@ -2163,15 +2169,18 @@ export const en = { days: "{{value}}d", hours: "{{value}}h", minutes: "{{value}}m", + pair: "{{first}} {{second}}", }, timing: { lastUpdated: "Last updated {{relativeTime}}", noSuccessfulUpdate: "No successful update", resetTimePassed: "Reset time passed", resettingNow: "resetting now", - resetsIn: "resets {{duration}}", + resetsIn: "resets in {{duration}}", + resetsAtWeekday: "{{weekday}} {{time}}", + resetsAtDate: "{{date}}, {{time}}", runsOutNow: "runs out now", - runsOutIn: "runs out {{duration}}", + runsOutIn: "runs out in {{duration}}", justNow: "just now", daysAgo: "{{value}}d ago", hoursAgo: "{{value}}h ago", @@ -2869,6 +2878,14 @@ export const en = { }, agents: { unavailable: "Connect to this host to manage agents", + resumeOnStartup: { + title: "Resume agents after restart", + info: "Reopen agents that were working when the host stopped and send the resume prompt. Applies after graceful restarts and crashes.", + hint: "Continue interrupted work automatically.", + prompt: "Resume prompt", + edit: "Edit", + editAccessibilityLabel: "Edit prompt", + }, idleRuntimeCleanup: { title: "Release idle agents", hint: "Free up memory after an hour of inactivity.", @@ -2965,6 +2982,10 @@ export const en = { requestFailedTitle: "Error", requestFailedMessage: "Failed to send the restart request. Paseo reconnects automatically-try again once the host shows as online.", + closeTerminals: "Restart and close terminals", + closeTerminalsHint: "Restart and also close every terminal running on this host.", + closeTerminalsConfirmMessage: + "This will restart the daemon and close every terminal on it, ending the programs running in them. The app will reconnect automatically.", dialogFailedMessage: "Unable to open the restart confirmation dialog.", }, update: { diff --git a/packages/app/src/i18n/resources/es.ts b/packages/app/src/i18n/resources/es.ts index 8784adefb5..7e5a1d41e6 100644 --- a/packages/app/src/i18n/resources/es.ts +++ b/packages/app/src/i18n/resources/es.ts @@ -68,6 +68,7 @@ export const es: TranslationResources = { daemonClientUnavailable: "ClienteDaemonno disponible", daemonClientDisconnected: "El clienteDaemonestá desconectado", noFileFound: "No se encontró ningún archivo para{{token}}", + folderOutsideWorkspace: "{{path}} está fuera de este espacio de trabajo", unexpectedDictationError: "Se produjo un error inesperado al manejar el dictado.", }, connectionStatus: { @@ -622,6 +623,7 @@ export const es: TranslationResources = { terminal: { hostDisconnected: "Hostno está conectado", updateHost: "Actualiza el host para usar el renderizador de terminal nativo.", + restoreRequiresUpdate: "Actualiza el host para ver las terminales.", unableToSubscribe: "No se puede suscribir al terminal", fileUploaded: "Archivo subido", pasteFileFailed: "No se pudo pegar el archivo: {{reason}}", @@ -1961,7 +1963,6 @@ export const es: TranslationResources = { parent: { backToParent: "Volver al padre", backTo: "Volver a {{label}}", - parent: "Padre", parentAgent: "Agente padre", openParent: "Abrir padre", }, @@ -2061,17 +2062,17 @@ export const es: TranslationResources = { toolCallDetails: { error: "Error", empty: "No hay detalles adicionales disponibles", - subAgentActivity: "Actividad de subagente", input: "Aporte", output: "Producción", }, turnSummary: { - messages: { - one: "escribió {{count}} mensaje", - other: "escribió {{count}} mensajes", - }, + details: "Ver detalles del turno", + sentBy: "Enviado por {{name}}", + showMore: "Mostrar más", + showLess: "Mostrar menos", }, toolCallGroup: { + thought: "Razonó", editedFiles: { one: "editó {{count}} archivo", other: "editó {{count}} archivos", @@ -2139,6 +2140,11 @@ export const es: TranslationResources = { }, }, providerUsage: { + checkUsage: "Consultar uso", + checkUsageHint: "Se aplica a {{host}} en todos los dispositivos", + off: "El uso está desactivado en {{host}}.", + turnOn: "Activar", + options: "Configuración", refreshFailed: "No se pudo actualizar el uso", noHosts: "No hay hosts conectados", @@ -2186,6 +2192,7 @@ export const es: TranslationResources = { days: "{{value}} d", hours: "{{value}} h", minutes: "{{value}} min", + pair: "{{first}} {{second}}", }, timing: { lastUpdated: "Última actualización {{relativeTime}}", @@ -2193,6 +2200,8 @@ export const es: TranslationResources = { resetTimePassed: "Pasó la hora de restablecimiento", resettingNow: "se restablece ahora", resetsIn: "se restablece en {{duration}}", + resetsAtWeekday: "{{weekday}} {{time}}", + resetsAtDate: "{{date}}, {{time}}", runsOutNow: "se agota ahora", runsOutIn: "se agota en {{duration}}", justNow: "ahora mismo", @@ -2799,6 +2808,14 @@ export const es: TranslationResources = { }, agents: { unavailable: "Connect to this host to manage agents", + resumeOnStartup: { + title: "Reanudar agentes tras reiniciar", + info: "Vuelve a abrir los agentes que estaban trabajando cuando se detuvo el host y envía el mensaje de reanudación. Se aplica tras reinicios normales y fallos.", + hint: "Continuar automáticamente el trabajo interrumpido.", + prompt: "Mensaje de reanudación", + edit: "Editar", + editAccessibilityLabel: "Editar mensaje", + }, idleRuntimeCleanup: { title: "Liberar agentes inactivos", hint: "Libera memoria tras una hora de inactividad.", @@ -2896,6 +2913,11 @@ export const es: TranslationResources = { requestFailedTitle: "Error", requestFailedMessage: "No se pudo enviar la solicitud de reinicio.Paseose vuelve a conectar automáticamente; inténtelo nuevamente una vez que el host se muestre en línea.", + closeTerminals: "Reiniciar y cerrar terminales", + closeTerminalsHint: + "Reinicia y además cierra todas las terminales abiertas en este host.", + closeTerminalsConfirmMessage: + "Esto reiniciará el daemon y cerrará todas sus terminales, terminando los programas que se ejecutan en ellas. La app se reconectará automáticamente.", dialogFailedMessage: "No se puede abrir el cuadro de diálogo de confirmación de reinicio.", }, diff --git a/packages/app/src/i18n/resources/fr.ts b/packages/app/src/i18n/resources/fr.ts index bbafc03dda..551f4a4158 100644 --- a/packages/app/src/i18n/resources/fr.ts +++ b/packages/app/src/i18n/resources/fr.ts @@ -68,6 +68,7 @@ export const fr: TranslationResources = { daemonClientUnavailable: "Client du daemon indisponible", daemonClientDisconnected: "Le client du daemon est déconnecté", noFileFound: "Aucun fichier trouvé pour {{token}}", + folderOutsideWorkspace: "{{path}} se trouve en dehors de cet espace de travail", unexpectedDictationError: "Une erreur inattendue s’est produite pendant la dictée.", }, connectionStatus: { @@ -622,6 +623,7 @@ export const fr: TranslationResources = { terminal: { hostDisconnected: "L’hôte n’est pas connecté", updateHost: "Mettez à jour l’hôte pour utiliser le rendu natif du terminal.", + restoreRequiresUpdate: "Mettez à jour l’hôte pour afficher les terminaux.", unableToSubscribe: "Impossible de s’abonner au terminal", fileUploaded: "Fichier envoyé", pasteFileFailed: "Impossible de coller le fichier : {{reason}}", @@ -1959,7 +1961,6 @@ export const fr: TranslationResources = { parent: { backToParent: "Retour au parent", backTo: "Retour à {{label}}", - parent: "Parent", parentAgent: "Agent parent", openParent: "Ouvrir le parent", }, @@ -2060,17 +2061,17 @@ export const fr: TranslationResources = { toolCallDetails: { error: "Erreur", empty: "Aucun détail supplémentaire disponible", - subAgentActivity: "Activité du sous-agent", input: "Entrée", output: "Sortie", }, turnSummary: { - messages: { - one: "{{count}} message écrit", - other: "{{count}} messages écrits", - }, + details: "Voir les détails du tour", + sentBy: "Envoyé par {{name}}", + showMore: "Afficher plus", + showLess: "Afficher moins", }, toolCallGroup: { + thought: "Réfléchi", editedFiles: { one: "{{count}} fichier modifié", other: "{{count}} fichiers modifiés", @@ -2139,6 +2140,11 @@ export const fr: TranslationResources = { }, }, providerUsage: { + checkUsage: "Vérifier l’utilisation", + checkUsageHint: "S’applique à {{host}} sur tous les appareils", + off: "L’utilisation est désactivée sur {{host}}.", + turnOn: "Activer", + options: "Paramètres", refreshFailed: "Impossible d’actualiser l’utilisation", noHosts: "Aucun hôte connecté", @@ -2186,6 +2192,7 @@ export const fr: TranslationResources = { days: "{{value}} j", hours: "{{value}} h", minutes: "{{value}} min", + pair: "{{first}} {{second}}", }, timing: { lastUpdated: "Dernière mise à jour {{relativeTime}}", @@ -2193,6 +2200,8 @@ export const fr: TranslationResources = { resetTimePassed: "Heure de réinitialisation dépassée", resettingNow: "réinitialisation en cours", resetsIn: "se réinitialise dans {{duration}}", + resetsAtWeekday: "{{weekday}} {{time}}", + resetsAtDate: "{{date}}, {{time}}", runsOutNow: "s’épuise maintenant", runsOutIn: "s’épuise dans {{duration}}", justNow: "à l’instant", @@ -2802,6 +2811,14 @@ export const fr: TranslationResources = { }, agents: { unavailable: "Connectez-vous à cet hôte pour gérer les agents", + resumeOnStartup: { + title: "Reprendre les agents après un redémarrage", + info: "Rouvre les agents qui travaillaient lorsque l’hôte s’est arrêté et envoie le message de reprise. S’applique après un redémarrage normal ou un plantage.", + hint: "Continuer automatiquement le travail interrompu.", + prompt: "Message de reprise", + edit: "Modifier", + editAccessibilityLabel: "Modifier le message", + }, idleRuntimeCleanup: { title: "Libérer les agents inactifs", hint: "Libère de la mémoire après une heure d’inactivité.", @@ -2901,6 +2918,10 @@ export const fr: TranslationResources = { requestFailedTitle: "Erreur", requestFailedMessage: "Impossible d’envoyer la demande de redémarrage. Paseo se reconnecte automatiquement : réessayez quand l’hôte apparaît en ligne.", + closeTerminals: "Redémarrer et fermer les terminaux", + closeTerminalsHint: "Redémarre et ferme aussi tous les terminaux ouverts sur cet hôte.", + closeTerminalsConfirmMessage: + "Le daemon va redémarrer et fermer tous ses terminaux, ce qui arrêtera les programmes qui y tournent. L'app se reconnectera automatiquement.", dialogFailedMessage: "Impossible d’ouvrir la boîte de dialogue de confirmation du redémarrage.", }, diff --git a/packages/app/src/i18n/resources/ja.ts b/packages/app/src/i18n/resources/ja.ts index e7dcc5b5e7..4b1b8b6f64 100644 --- a/packages/app/src/i18n/resources/ja.ts +++ b/packages/app/src/i18n/resources/ja.ts @@ -68,6 +68,7 @@ export const ja: TranslationResources = { daemonClientUnavailable: "デーモンクライアントが利用できません", daemonClientDisconnected: "デーモンクライアントが切断されています", noFileFound: "{{token}}のファイルが見つかりません", + folderOutsideWorkspace: "{{path}} はこのワークスペースの外にあります", unexpectedDictationError: "音声入力処理中に予期しないエラーが発生しました。", }, connectionStatus: { @@ -622,6 +623,7 @@ export const ja: TranslationResources = { terminal: { hostDisconnected: "ホストが接続されていません", updateHost: "ネイティブターミナルを使用するにはホストを更新してください。", + restoreRequiresUpdate: "ターミナルを表示するにはホストを更新してください。", unableToSubscribe: "ターミナルに接続できません", fileUploaded: "ファイルをアップロードしました", pasteFileFailed: "ファイルを貼り付けられませんでした: {{reason}}", @@ -1932,7 +1934,6 @@ export const ja: TranslationResources = { parent: { backToParent: "親に戻る", backTo: "{{label}} に戻る", - parent: "親", parentAgent: "親エージェント", openParent: "親を開く", }, @@ -2033,17 +2034,17 @@ export const ja: TranslationResources = { toolCallDetails: { error: "エラー", empty: "追加の詳細はありません", - subAgentActivity: "サブエージェントアクティビティ", input: "入力", output: "出力", }, turnSummary: { - messages: { - one: "{{count}}件のメッセージを送信", - other: "{{count}}件のメッセージを送信", - }, + details: "ターンの詳細を表示", + sentBy: "{{name}} から送信", + showMore: "もっと見る", + showLess: "折りたたむ", }, toolCallGroup: { + thought: "思考", editedFiles: { one: "{{count}}個のファイルを編集", other: "{{count}}個のファイルを編集", @@ -2112,6 +2113,11 @@ export const ja: TranslationResources = { }, }, providerUsage: { + checkUsage: "使用状況を確認", + checkUsageHint: "すべてのデバイスで {{host}} に適用", + off: "{{host}} の使用状況確認はオフです。", + turnOn: "オンにする", + options: "設定", refreshFailed: "使用状況を更新できません", noHosts: "接続中のホストがありません", @@ -2159,6 +2165,7 @@ export const ja: TranslationResources = { days: "{{value}}日", hours: "{{value}}時間", minutes: "{{value}}分", + pair: "{{first}}{{second}}", }, timing: { lastUpdated: "最終更新: {{relativeTime}}", @@ -2166,6 +2173,8 @@ export const ja: TranslationResources = { resetTimePassed: "リセット時刻を過ぎています", resettingNow: "まもなくリセット", resetsIn: "{{duration}}後にリセット", + resetsAtWeekday: "{{weekday}} {{time}}", + resetsAtDate: "{{date}} {{time}}", runsOutNow: "まもなく上限に到達", runsOutIn: "{{duration}}後に上限に到達", justNow: "たった今", @@ -2766,6 +2775,14 @@ export const ja: TranslationResources = { }, agents: { unavailable: "エージェントを管理するにはこのホストに接続してください", + resumeOnStartup: { + title: "再起動後にエージェントを再開", + info: "ホストの停止時に作業中だったエージェントを開き直し、再開メッセージを送信します。通常の再起動とクラッシュの両方に適用されます。", + hint: "中断された作業を自動的に続行します。", + prompt: "再開メッセージ", + edit: "編集", + editAccessibilityLabel: "メッセージを編集", + }, idleRuntimeCleanup: { title: "アイドル状態のエージェントを解放", hint: "1 時間のアイドル状態の後にメモリを解放します。", @@ -2864,6 +2881,10 @@ export const ja: TranslationResources = { requestFailedTitle: "エラー", requestFailedMessage: "再起動リクエストの送信に失敗しました。Paseoは自動的に再接続します。ホストがオンラインになったら再試行してください。", + closeTerminals: "再起動してターミナルを閉じる", + closeTerminalsHint: "再起動し、このホストのすべてのターミナルも閉じます。", + closeTerminalsConfirmMessage: + "デーモンを再起動し、すべてのターミナルを閉じます。ターミナルで実行中のプログラムは終了します。アプリは自動的に再接続します。", dialogFailedMessage: "再起動確認ダイアログを開けませんでした。", }, update: { diff --git a/packages/app/src/i18n/resources/ko.ts b/packages/app/src/i18n/resources/ko.ts index d8d1fbc787..b9e33b4eba 100644 --- a/packages/app/src/i18n/resources/ko.ts +++ b/packages/app/src/i18n/resources/ko.ts @@ -67,6 +67,7 @@ export const ko: TranslationResources = { daemonClientUnavailable: "데몬 클라이언트를 사용할 수 없습니다", daemonClientDisconnected: "데몬 클라이언트 연결이 끊어졌습니다", noFileFound: "{{token}}에 해당하는 파일을 찾을 수 없습니다", + folderOutsideWorkspace: "{{path}}은(는) 이 워크스페이스 밖에 있습니다", unexpectedDictationError: "받아쓰기를 처리하는 중 예기치 않은 오류가 발생했습니다.", }, connectionStatus: { @@ -617,6 +618,7 @@ export const ko: TranslationResources = { terminal: { hostDisconnected: "호스트가 연결되어 있지 않습니다", updateHost: "기본 터미널 렌더러를 사용하도록 호스트를 업데이트합니다.", + restoreRequiresUpdate: "터미널을 보려면 호스트를 업데이트하세요.", unableToSubscribe: "터미널을 구독할 수 없습니다", fileUploaded: "파일을 업로드했습니다", pasteFileFailed: "파일을 붙여넣지 못했습니다: {{reason}}", @@ -1923,7 +1925,6 @@ export const ko: TranslationResources = { parent: { backToParent: "상위 에이전트로 돌아가기", backTo: "{{label}}(으)로 돌아가기", - parent: "상위", parentAgent: "상위 에이전트", openParent: "상위 에이전트 열기", }, @@ -2023,17 +2024,17 @@ export const ko: TranslationResources = { toolCallDetails: { error: "오류", empty: "추가 세부 정보가 없습니다", - subAgentActivity: "서브에이전트 활동", input: "입력", output: "출력", }, turnSummary: { - messages: { - one: "{{count}} 메시지를 작성했습니다.", - other: "{{count}} 메시지를 작성했습니다.", - }, + details: "턴 세부 정보 보기", + sentBy: "{{name}}이(가) 보냄", + showMore: "더 보기", + showLess: "접기", }, toolCallGroup: { + thought: "생각함", editedFiles: { one: "{{count}} 파일을 편집했습니다.", other: "{{count}} 파일을 편집했습니다.", @@ -2101,6 +2102,11 @@ export const ko: TranslationResources = { }, }, providerUsage: { + checkUsage: "사용량 확인", + checkUsageHint: "모든 기기에서 {{host}}에 적용", + off: "{{host}}의 사용량 확인이 꺼져 있습니다.", + turnOn: "켜기", + options: "설정", refreshFailed: "사용량을 새로 고칠 수 없습니다", noHosts: "연결된 호스트가 없습니다", @@ -2148,6 +2154,7 @@ export const ko: TranslationResources = { days: "{{value}}일", hours: "{{value}}시간", minutes: "{{value}}분", + pair: "{{first}} {{second}}", }, timing: { lastUpdated: "마지막 업데이트: {{relativeTime}}", @@ -2155,6 +2162,8 @@ export const ko: TranslationResources = { resetTimePassed: "초기화 시간이 지났습니다", resettingNow: "지금 재설정 중", resetsIn: "{{duration}} 후 재설정", + resetsAtWeekday: "{{weekday}} {{time}}", + resetsAtDate: "{{date}} {{time}}", runsOutNow: "지금 한도에 도달", runsOutIn: "{{duration}} 후 한도에 도달", justNow: "방금", @@ -2754,6 +2763,14 @@ export const ko: TranslationResources = { }, agents: { unavailable: "에이전트를 관리하려면 이 호스트에 연결하세요", + resumeOnStartup: { + title: "재시작 후 에이전트 재개", + info: "호스트가 중지될 때 작업 중이던 에이전트를 다시 열고 재개 메시지를 보냅니다. 정상 재시작과 비정상 종료 후 모두 적용됩니다.", + hint: "중단된 작업을 자동으로 계속합니다.", + prompt: "재개 메시지", + edit: "편집", + editAccessibilityLabel: "메시지 편집", + }, idleRuntimeCleanup: { title: "유휴 에이전트 해제", hint: "1시간 동안 활동이 없으면 메모리를 확보합니다.", @@ -2851,6 +2868,10 @@ export const ko: TranslationResources = { requestFailedTitle: "오류", requestFailedMessage: "재시작 요청을 보내지 못했습니다. Paseo가 자동으로 다시 연결하므로 호스트가 온라인으로 표시되면 다시 시도하세요.", + closeTerminals: "재시작하고 터미널 닫기", + closeTerminalsHint: "재시작하면서 이 호스트의 모든 터미널도 닫습니다.", + closeTerminalsConfirmMessage: + "데몬을 재시작하고 모든 터미널을 닫습니다. 터미널에서 실행 중인 프로그램은 종료됩니다. 앱은 자동으로 다시 연결됩니다.", dialogFailedMessage: "재시작 확인 대화 상자를 열 수 없습니다.", }, update: { diff --git a/packages/app/src/i18n/resources/pt-BR.ts b/packages/app/src/i18n/resources/pt-BR.ts index 1c024dc64a..2fa6c30c8e 100644 --- a/packages/app/src/i18n/resources/pt-BR.ts +++ b/packages/app/src/i18n/resources/pt-BR.ts @@ -68,6 +68,7 @@ export const ptBR: TranslationResources = { daemonClientUnavailable: "Cliente do daemon indisponível", daemonClientDisconnected: "O cliente do daemon está desconectado", noFileFound: "Nenhum arquivo encontrado para {{token}}", + folderOutsideWorkspace: "{{path}} está fora deste workspace", unexpectedDictationError: "Ocorreu um erro inesperado ao processar o ditado.", }, connectionStatus: { @@ -621,6 +622,7 @@ export const ptBR: TranslationResources = { terminal: { hostDisconnected: "Host não está conectado", updateHost: "Atualize o host para usar o renderizador de terminal nativo.", + restoreRequiresUpdate: "Atualize o host para visualizar os terminais.", unableToSubscribe: "Não foi possível assinar o terminal", fileUploaded: "Arquivo enviado", pasteFileFailed: "Falha ao colar o arquivo: {{reason}}", @@ -1946,7 +1948,6 @@ export const ptBR: TranslationResources = { parent: { backToParent: "Voltar ao pai", backTo: "Voltar para {{label}}", - parent: "Pai", parentAgent: "Agente pai", openParent: "Abrir pai", }, @@ -2046,17 +2047,17 @@ export const ptBR: TranslationResources = { toolCallDetails: { error: "Erro", empty: "Nenhum detalhe adicional disponível", - subAgentActivity: "Atividade do subagente", input: "Entrada", output: "Saída", }, turnSummary: { - messages: { - one: "escreveu {{count}} mensagem", - other: "escreveu {{count}} mensagens", - }, + details: "Ver detalhes do turno", + sentBy: "Enviado por {{name}}", + showMore: "Mostrar mais", + showLess: "Mostrar menos", }, toolCallGroup: { + thought: "Pensou", editedFiles: { one: "editou {{count}} arquivo", other: "editou {{count}} arquivos", @@ -2124,6 +2125,11 @@ export const ptBR: TranslationResources = { }, }, providerUsage: { + checkUsage: "Consultar uso", + checkUsageHint: "Aplica-se a {{host}} em todos os dispositivos", + off: "O uso está desativado em {{host}}.", + turnOn: "Ativar", + options: "Configurações", refreshFailed: "Não foi possível atualizar o uso", noHosts: "Nenhum host conectado", @@ -2171,6 +2177,7 @@ export const ptBR: TranslationResources = { days: "{{value}} d", hours: "{{value}} h", minutes: "{{value}} min", + pair: "{{first}} {{second}}", }, timing: { lastUpdated: "Última atualização {{relativeTime}}", @@ -2178,6 +2185,8 @@ export const ptBR: TranslationResources = { resetTimePassed: "O horário de redefinição passou", resettingNow: "redefinindo agora", resetsIn: "redefine em {{duration}}", + resetsAtWeekday: "{{weekday}} {{time}}", + resetsAtDate: "{{date}}, {{time}}", runsOutNow: "esgota agora", runsOutIn: "esgota em {{duration}}", justNow: "agora mesmo", @@ -2781,6 +2790,14 @@ export const ptBR: TranslationResources = { }, agents: { unavailable: "Conecte-se a este host para gerenciar agentes", + resumeOnStartup: { + title: "Retomar agentes após reiniciar", + info: "Reabre os agentes que estavam trabalhando quando o host parou e envia a mensagem de retomada. Aplica-se após reinicializações normais e falhas.", + hint: "Continuar automaticamente o trabalho interrompido.", + prompt: "Mensagem de retomada", + edit: "Editar", + editAccessibilityLabel: "Editar mensagem", + }, idleRuntimeCleanup: { title: "Liberar agentes ociosos", hint: "Libera memória após uma hora de inatividade.", @@ -2879,6 +2896,10 @@ export const ptBR: TranslationResources = { requestFailedTitle: "Erro", requestFailedMessage: "Falha ao enviar a solicitação de reinício. O Paseo reconecta automaticamente. Tente novamente quando o host aparecer como online.", + closeTerminals: "Reiniciar e fechar terminais", + closeTerminalsHint: "Reinicia e também fecha todos os terminais abertos neste host.", + closeTerminalsConfirmMessage: + "Isso reiniciará o daemon e fechará todos os terminais dele, encerrando os programas que rodam neles. O app vai se reconectar automaticamente.", dialogFailedMessage: "Não foi possível abrir o diálogo de confirmação de reinício.", }, update: { diff --git a/packages/app/src/i18n/resources/ru.ts b/packages/app/src/i18n/resources/ru.ts index 093ac68c36..9a6eb5b0e2 100644 --- a/packages/app/src/i18n/resources/ru.ts +++ b/packages/app/src/i18n/resources/ru.ts @@ -68,6 +68,7 @@ export const ru: TranslationResources = { daemonClientUnavailable: "Daemon клиента недоступен", daemonClientDisconnected: "Daemon клиента отключен", noFileFound: "Файл для {{token}} не найден", + folderOutsideWorkspace: "{{path}} находится вне этого рабочего пространства", unexpectedDictationError: "При обработке диктовки произошла непредвиденная ошибка.", }, connectionStatus: { @@ -623,6 +624,7 @@ export const ru: TranslationResources = { terminal: { hostDisconnected: "Хост не подключён", updateHost: "Обновите хост, чтобы использовать нативный рендерер терминала.", + restoreRequiresUpdate: "Обновите хост, чтобы просматривать терминалы.", unableToSubscribe: "Не удалось подключиться к терминалу", fileUploaded: "Файл загружен", pasteFileFailed: "Не удалось вставить файл: {{reason}}", @@ -1945,7 +1947,6 @@ export const ru: TranslationResources = { parent: { backToParent: "Назад к родителю", backTo: "Назад к {{label}}", - parent: "Родитель", parentAgent: "Родительский агент", openParent: "Открыть родителя", }, @@ -2046,17 +2047,17 @@ export const ru: TranslationResources = { toolCallDetails: { error: "Ошибка", empty: "Дополнительные сведения отсутствуют", - subAgentActivity: "Активность субагента", input: "Входные данные", output: "Выходные данные", }, turnSummary: { - messages: { - one: "написано {{count}} сообщение", - other: "написаны сообщения ({{count}})", - }, + details: "Показать подробности хода", + sentBy: "Отправлено агентом {{name}}", + showMore: "Показать больше", + showLess: "Свернуть", }, toolCallGroup: { + thought: "Обдумал", editedFiles: { one: "изменён {{count}} файл", other: "изменены файлы ({{count}})", @@ -2124,6 +2125,11 @@ export const ru: TranslationResources = { }, }, providerUsage: { + checkUsage: "Проверять использование", + checkUsageHint: "Применяется к {{host}} на всех устройствах", + off: "Проверка использования отключена на {{host}}.", + turnOn: "Включить", + options: "Настройки", refreshFailed: "Не удалось обновить использование", noHosts: "Нет подключённых хостов", @@ -2171,6 +2177,7 @@ export const ru: TranslationResources = { days: "{{value}} дн.", hours: "{{value}} ч", minutes: "{{value}} мин", + pair: "{{first}} {{second}}", }, timing: { lastUpdated: "Последнее обновление {{relativeTime}}", @@ -2178,6 +2185,8 @@ export const ru: TranslationResources = { resetTimePassed: "Время сброса прошло", resettingNow: "сброс сейчас", resetsIn: "сброс через {{duration}}", + resetsAtWeekday: "{{weekday}} {{time}}", + resetsAtDate: "{{date}}, {{time}}", runsOutNow: "закончится сейчас", runsOutIn: "закончится через {{duration}}", justNow: "только что", @@ -2791,6 +2800,14 @@ export const ru: TranslationResources = { }, agents: { unavailable: "Подключитесь к этому хосту, чтобы управлять агентами", + resumeOnStartup: { + title: "Возобновлять агентов после перезапуска", + info: "Открывает агентов, которые работали при остановке хоста, и отправляет сообщение для продолжения. Применяется после обычного перезапуска и сбоя.", + hint: "Автоматически продолжать прерванную работу.", + prompt: "Сообщение для продолжения", + edit: "Редактировать", + editAccessibilityLabel: "Изменить сообщение", + }, idleRuntimeCleanup: { title: "Освобождать неактивных агентов", hint: "Освобождает память после часа бездействия.", @@ -2889,6 +2906,10 @@ export const ru: TranslationResources = { requestFailedTitle: "Ошибка", requestFailedMessage: "Не удалось отправить запрос на перезапуск. Paseo переподключается автоматически. Повторите попытку, когда хост появится в сети.", + closeTerminals: "Перезапустить и закрыть терминалы", + closeTerminalsHint: "Перезапускает демон и закрывает все терминалы на этом хосте.", + closeTerminalsConfirmMessage: + "Демон будет перезапущен, а все его терминалы закрыты вместе с запущенными в них программами. Приложение переподключится автоматически.", dialogFailedMessage: "Не удалось открыть диалог подтверждения перезапуска.", }, update: { diff --git a/packages/app/src/i18n/resources/zh-CN.ts b/packages/app/src/i18n/resources/zh-CN.ts index 8ca178f206..553d8212b4 100644 --- a/packages/app/src/i18n/resources/zh-CN.ts +++ b/packages/app/src/i18n/resources/zh-CN.ts @@ -67,6 +67,7 @@ export const zhCN: TranslationResources = { daemonClientUnavailable: "Daemon client 不可用", daemonClientDisconnected: "Daemon client 已断开连接", noFileFound: "未找到 {{token}} 对应的文件", + folderOutsideWorkspace: "{{path}} 不在此工作区内", unexpectedDictationError: "处理听写时发生意外错误。", }, connectionStatus: { @@ -616,6 +617,7 @@ export const zhCN: TranslationResources = { terminal: { hostDisconnected: "Host 未连接", updateHost: "请更新主机以使用原生终端渲染器。", + restoreRequiresUpdate: "更新主机以查看终端。", unableToSubscribe: "无法订阅 Terminal", fileUploaded: "文件已上传", pasteFileFailed: "无法粘贴文件:{{reason}}", @@ -1891,7 +1893,6 @@ export const zhCN: TranslationResources = { parent: { backToParent: "返回父代理", backTo: "返回 {{label}}", - parent: "父代理", parentAgent: "父代理", openParent: "打开父代理", }, @@ -1991,17 +1992,17 @@ export const zhCN: TranslationResources = { toolCallDetails: { error: "错误", empty: "没有可用的更多详情", - subAgentActivity: "Sub-agent 活动", input: "输入", output: "输出", }, turnSummary: { - messages: { - one: "写了 {{count}} 条消息", - other: "写了 {{count}} 条消息", - }, + details: "查看轮次详情", + sentBy: "由 {{name}} 发送", + showMore: "展开", + showLess: "收起", }, toolCallGroup: { + thought: "已思考", editedFiles: { one: "编辑了 {{count}} 个文件", other: "编辑了 {{count}} 个文件", @@ -2069,6 +2070,11 @@ export const zhCN: TranslationResources = { }, }, providerUsage: { + checkUsage: "检查用量", + checkUsageHint: "在所有设备上应用于 {{host}}", + off: "{{host}} 的用量检查已关闭。", + turnOn: "开启", + options: "设置", refreshFailed: "无法刷新用量", noHosts: "没有已连接的主机", @@ -2116,6 +2122,7 @@ export const zhCN: TranslationResources = { days: "{{value}}天", hours: "{{value}}小时", minutes: "{{value}}分钟", + pair: "{{first}}{{second}}", }, timing: { lastUpdated: "上次更新于 {{relativeTime}}", @@ -2123,6 +2130,8 @@ export const zhCN: TranslationResources = { resetTimePassed: "重置时间已过", resettingNow: "正在重置", resetsIn: "将在 {{duration}}后重置", + resetsAtWeekday: "{{weekday}} {{time}}", + resetsAtDate: "{{date}} {{time}}", runsOutNow: "即将用尽", runsOutIn: "将在 {{duration}}后用尽", justNow: "刚刚", @@ -2712,6 +2721,14 @@ export const zhCN: TranslationResources = { }, agents: { unavailable: "连接到这个 Host 以管理 Agent", + resumeOnStartup: { + title: "重启后恢复智能体", + info: "重新打开主机停止时正在工作的智能体,并发送恢复提示。适用于正常重启和崩溃后的恢复。", + hint: "自动继续被中断的工作。", + prompt: "恢复提示", + edit: "编辑", + editAccessibilityLabel: "编辑提示", + }, idleRuntimeCleanup: { title: "释放空闲 Agent", hint: "空闲一小时后释放内存。", @@ -2803,6 +2820,10 @@ export const zhCN: TranslationResources = { offlineMessage: "这个 Host 已离线。Paseo 会自动重连,请等它恢复在线后再重启。", requestFailedTitle: "错误", requestFailedMessage: "发送重启请求失败。Paseo 会自动重连,请在 Host 显示在线后重试。", + closeTerminals: "重启并关闭终端", + closeTerminalsHint: "重启的同时关闭此主机上的所有终端。", + closeTerminalsConfirmMessage: + "这将重启守护进程并关闭其所有终端,终端中运行的程序会被结束。应用会自动重新连接。", dialogFailedMessage: "无法打开重启确认对话框。", }, update: { diff --git a/packages/app/src/panels/agent-panel.tsx b/packages/app/src/panels/agent-panel.tsx index 8139459b2b..147ab7b260 100644 --- a/packages/app/src/panels/agent-panel.tsx +++ b/packages/app/src/panels/agent-panel.tsx @@ -28,6 +28,7 @@ import { FileDropZone } from "@/components/file-drop/file-drop-zone"; import { useRetainedPanelActive } from "@/components/retained-panel"; import { RetainedChatContent } from "./retained-chat-content"; import { Composer } from "@/composer"; +import { AgentCommandsProvider } from "@/agent-commands"; import { useComposerEditingSession, useComposerFullscreen, @@ -44,7 +45,7 @@ import { useAgentDescriptor } from "@/agent-presentation"; import { useToastHost, type ToastApi, type ToastState } from "@/components/toast-host"; import type { WorkspaceComposerAttachment } from "@/attachments/types"; import { useWorkspaceAttachmentScopeKey } from "@/attachments/workspace-attachments-store"; -import { COMPACT_FORM_FACTOR_WIDTH, useIsCompactFormFactor } from "@/constants/layout"; +import { COMPACT_CONTENT_WIDTH, useIsCompactFormFactor } from "@/constants/layout"; import { isNative, isWeb } from "@/constants/platform"; import { useAgentAttentionClear } from "@/hooks/use-agent-attention-clear"; import { useAgentInputDraft, type AgentInputDraft } from "@/composer/draft/input-draft"; @@ -1255,7 +1256,7 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({ ); - return ( + const content = ( ); + return wrapAgentCommandProvider({ + enabled: showsComposer && hasActiveComposer, + serverId, + agentId, + editingSession: composerEditingSession, + children: content, + }); }); +function wrapAgentCommandProvider({ + enabled, + serverId, + agentId, + editingSession, + children, +}: { + enabled: boolean; + serverId: string; + agentId: string; + editingSession: ComposerEditingSession; + children: ReactNode; +}) { + return ( + + {children} + + ); +} + function ChatSurface({ children, disabled, @@ -1512,7 +1545,7 @@ function ActiveAgentComposer({ }) { const isCompactFormFactor = useIsCompactFormFactor(); const { onLayout: onInputAreaLayout, isBelow: isCompactComposerLayout } = useContainerWidthBelow( - COMPACT_FORM_FACTOR_WIDTH, + COMPACT_CONTENT_WIDTH, { initialIsBelow: isCompactFormFactor }, ); const paneContext = usePaneContext(); diff --git a/packages/app/src/panels/agent-tracks.tsx b/packages/app/src/panels/agent-tracks.tsx index f7c724133a..6984633bcc 100644 --- a/packages/app/src/panels/agent-tracks.tsx +++ b/packages/app/src/panels/agent-tracks.tsx @@ -13,7 +13,7 @@ import { type ArchiveFinishedStatus, useArchiveSubagent, useDetachSubagent, - useSubagentOpensInSheet, + useSubagentSheetTab, type SubagentRow, } from "@/subagents"; import { ParentAgentPill } from "@/subagents/parent"; @@ -100,7 +100,7 @@ export const AgentTracks = memo(function AgentTracks({ }, [openSubagentTarget], ); - const opensInSheet = useSubagentOpensInSheet(workspaceKey); + const sheetTabFor = useSubagentSheetTab(workspaceKey, tabId); const handleOpenChanges = useCallback(() => { if (!workspaceKey) { return; @@ -134,7 +134,7 @@ export const AgentTracks = memo(function AgentTracks({ rows={subagentRows} onOpenSubagent={handleOpenSubagent} onOpenProviderSubagent={handleOpenProviderSubagent} - opensInSheet={opensInSheet} + sheetTabFor={sheetTabFor} onArchiveSubagent={archiveSubagent} onArchiveFinished={onArchiveFinished} archiveFinishedStatus={archiveFinishedStatus} diff --git a/packages/app/src/panels/provider-subagent-panel.tsx b/packages/app/src/panels/provider-subagent-panel.tsx index e36f7880ca..99a38c2f8b 100644 --- a/packages/app/src/panels/provider-subagent-panel.tsx +++ b/packages/app/src/panels/provider-subagent-panel.tsx @@ -16,9 +16,10 @@ import { usePaneContext } from "@/panels/pane-context"; import { PaneSubtitle } from "@/panels/pane-subtitle"; import { definePanel, type PanelDescriptor } from "@/panels/panel-registry"; import { useSessionStore } from "@/stores/session-store"; +import type { SheetTab } from "@/stores/workspace-layout-store"; import { ParentAgentCallout } from "@/subagents/parent"; import { type SubagentRow, useSubagentsForParent } from "@/subagents/select"; -import { useSubagentOpensInSheet } from "@/subagents/opens-in-sheet"; +import { useSubagentSheetTab } from "@/subagents/sheet-tab"; import { SubagentsTrack } from "@/subagents/track"; import { providerSubagentKey, @@ -51,12 +52,12 @@ function ProviderSubagentChildTrack({ serverId, rows, onOpenProviderSubagent, - opensInSheet, + sheetTabFor, }: { serverId: string; rows: ReturnType; onOpenProviderSubagent: (parentAgentId: string, subagentId: string) => void; - opensInSheet: (row: SubagentRow) => boolean; + sheetTabFor: (row: SubagentRow) => SheetTab | null; }) { if (rows.length === 0) return null; return ( @@ -66,7 +67,7 @@ function ProviderSubagentChildTrack({ rows={rows} onOpenSubagent={NOOP_SUBAGENT} onOpenProviderSubagent={onOpenProviderSubagent} - opensInSheet={opensInSheet} + sheetTabFor={sheetTabFor} onArchiveSubagent={NOOP_SUBAGENT} /> @@ -116,7 +117,7 @@ function useProviderSubagentDescriptor( function ProviderSubagentPanel() { const { t } = useTranslation(); - const { serverId, workspaceId, target, openFileInWorkspace, openTab } = usePaneContext(); + const { serverId, workspaceId, tabId, target, openFileInWorkspace, openTab } = usePaneContext(); invariant(target.kind === "provider_subagent", "ProviderSubagentPanel requires provider target"); const key = providerSubagentKey(serverId, target.parentAgentId, target.subagentId); const streamId = `provider:${encodeURIComponent(target.parentAgentId)}:${encodeURIComponent(target.subagentId)}`; @@ -144,8 +145,9 @@ function ProviderSubagentPanel() { providerParentSubagentId: target.subagentId, }); const childTrackClearance = resolveChildTrackClearance(childRows.length, isCompact); - const opensInSheet = useSubagentOpensInSheet( + const sheetTabFor = useSubagentSheetTab( buildWorkspaceTabPersistenceKey({ serverId, workspaceId }), + tabId, ); const openProviderChild = useCallback( (parentAgentId: string, subagentId: string) => { @@ -274,7 +276,7 @@ function ProviderSubagentPanel() { serverId={serverId} rows={childRows} onOpenProviderSubagent={openProviderChild} - opensInSheet={opensInSheet} + sheetTabFor={sheetTabFor} />
diff --git a/packages/app/src/panels/retained-chat-content.browser.test.tsx b/packages/app/src/panels/retained-chat-content.browser.test.tsx index 57977dd462..3ffeb1bfef 100644 --- a/packages/app/src/panels/retained-chat-content.browser.test.tsx +++ b/packages/app/src/panels/retained-chat-content.browser.test.tsx @@ -34,11 +34,24 @@ import { import type { ContextBridge } from "@/components/ui/isolated-bottom-sheet-modal"; import { render as renderEnvironment } from "@testing-library/react"; -import { useWorkspaceSheetEnvironment } from "@/screens/workspace/workspace-sheet-environment"; +import { + SheetPaneHostProvider, + useSheetPaneBridge, + type SheetPaneHost, +} from "@/screens/workspace/sheet-pane"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { useAssistantFileLinkActions, type InlinePathTarget } from "@/assistant-file-links"; Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }); +const SHEET_PANE_HOST: SheetPaneHost = { + workspaceKey: "host:workspace", + serverId: "host", + workspaceId: "workspace", + isWorkspaceFocused: true, + buildContent: () => { + throw new Error("The environment probe builds no pane content"); + }, +}; let root: Root; let container: HTMLDivElement; beforeEach(() => { @@ -155,14 +168,21 @@ describe("workspace sheet environment", () => { }, [name]); return null; } - function Capture() { - bridge = useWorkspaceSheetEnvironment(); + function CaptureBridge() { + bridge = useSheetPaneBridge(); return ( ); } + function Capture() { + return ( + + + + ); + } function Source({ workspaceRoot, active }: { workspaceRoot: string; active: boolean }) { const onOpenFile = useCallback( (target: InlinePathTarget) => { diff --git a/packages/app/src/plugins/catalog-sync-model.test.ts b/packages/app/src/plugins/catalog-sync-model.test.ts new file mode 100644 index 0000000000..98a8a3cf37 --- /dev/null +++ b/packages/app/src/plugins/catalog-sync-model.test.ts @@ -0,0 +1,424 @@ +import appPackage from "../../package.json"; +import { afterEach, expect, it } from "vitest"; +import { QueryObserver } from "@tanstack/react-query"; +import { DaemonClient } from "@getpaseo/client/internal/daemon-client"; +import type { SessionOutboundMessage } from "@getpaseo/protocol/messages"; +import { settingsRpc } from "@getpaseo/plugin"; +import { syncPluginCatalog } from "./catalog-sync-model"; +import { createPluginHosts } from "./hosts"; +import { PluginRegistry } from "./registry"; +import { pluginSettingsKey } from "./settings/query"; +import type { InstalledPlugin } from "./types"; + +const audio = { play: async () => 0 }; +const rpc = settingsRpc("preferences"); +type Catalog = Awaited>; +type Observation = ReturnType; +type Observer = Parameters[0]; + +class SettingsStore { + private revision = 1; + private values = { label: "original" }; + reads = 0; + + read() { + this.reads++; + return { status: "ready", revision: String(this.revision), values: this.values } as const; + } + + write(input: unknown) { + const write = rpc.write.input.parse(input); + if (write.revision !== String(this.revision)) { + return { status: "conflict", error: "Settings changed" } as const; + } + const values = write.values; + if (typeof values !== "object" || values === null || !("label" in values)) { + throw new Error("Expected settings values"); + } + if (typeof values.label !== "string") throw new Error("Expected label"); + this.values = { label: values.label }; + this.revision++; + return { status: "saved", revision: String(this.revision), values: this.values } as const; + } +} + +/** In-memory daemon port; it delivers owned snapshots and stops updates on release. */ +class CatalogClient extends DaemonClient { + catalog = catalog("one"); + fetches = 0; + releases = 0; + events: Parameters[0] = []; + private readonly observers = new Set(); + + constructor(readonly settings = new SettingsStore()) { + super({ url: "ws://unused.test", clientId: "catalog-sync-test" }); + } + + override async getPluginCatalog(): Promise { + this.fetches++; + return this.catalog; + } + + override observeEvents(events: Parameters[0]): Observation { + this.events = events; + const snapshot = { requestId: "events", subscriptionId: "catalog" }; + const subscribers = new Set(); + return { + subscriptionId: snapshot.subscriptionId, + ready: Promise.resolve(snapshot), + subscribe: (observer) => { + subscribers.add(observer); + this.observers.add(observer); + observer.snapshot(snapshot); + return () => { + subscribers.delete(observer); + this.observers.delete(observer); + }; + }, + release: async () => { + this.releases++; + for (const observer of subscribers) this.observers.delete(observer); + subscribers.clear(); + }, + }; + } + + override async invokePluginRpc(_pluginId: string, method: string, input: unknown) { + if (method === rpc.read.name) return this.settings.read(); + if (method === rpc.write.name) return this.settings.write(input); + throw new Error(`Unexpected RPC: ${method}`); + } + + update(message: SessionOutboundMessage) { + for (const observer of this.observers) observer.update(message); + } + + snapshot() { + for (const observer of this.observers) { + observer.snapshot({ requestId: "reconnect", subscriptionId: "catalog" }); + } + } +} + +function catalog(marker: string): Catalog { + return [ + { + id: "reports", + requirements: { paseo: `>=${appPackage.version}` }, + clientBundle: `(function() { return { default: function(plugin) { + plugin.addTimelineTransformer({ + id: "report", query: { itemType: "tool_call" }, + transform() { return ${JSON.stringify(marker)} ? { items: [] } : undefined; } + }); + return function() { plugin.openSettings("cleanup"); }; + } }; })`, + }, + ]; +} + +const cleanups: Array<() => void> = []; +afterEach(() => { + for (const cleanup of cleanups.splice(0).toReversed()) cleanup(); +}); + +function harness() { + let evaluations = 0; + let disposals = 0; + const registry = new PluginRegistry({ + localeSource: { getLocale: () => "en", subscribe: () => () => {} }, + version: appPackage.version, + createRuntime(installation) { + evaluations++; + return { + hosts: createPluginHosts( + { + getHosts: () => [], + getSnapshot: () => null, + subscribeAll: () => () => {}, + subscribeHostList: () => () => {}, + }, + installation.lifetime.signal, + ), + paseo: installation.paseo, + i18n: installation.i18n, + rpc: async () => { + throw new Error("Unexpected runtime RPC"); + }, + openSettings: () => { + disposals++; + }, + openScreen() {}, + openSurface() {}, + async playAudio() {}, + openPanel() {}, + addComposerPill: () => ({ update() {}, remove() {} }), + addHeaderButton: () => ({ update() {}, remove() {} }), + }; + }, + }); + const client = new CatalogClient(); + cleanups.push(() => { + registry.removeHost("host"); + registry.removeHost("other"); + }); + function sync(options: Partial[0]> = {}) { + const stop = syncPluginCatalog({ + serverId: "host", + client, + audio, + connected: true, + supported: true, + registry, + ...options, + }); + cleanups.push(stop); + return stop; + } + function installed(serverId = "host") { + const plugin = registry.getSnapshot().find((entry) => entry.serverId === serverId); + if (!plugin) throw new Error(`Missing installation: ${serverId}`); + return plugin; + } + return { + registry, + client, + sync, + installed, + evaluations: () => evaluations, + disposals: () => disposals, + }; +} + +async function connected() { + const h = harness(); + const stop = h.sync(); + await expect.poll(() => h.registry.getSnapshot().length).toBe(1); + return { ...h, stop }; +} + +function settingsQuery(plugin: InstalledPlugin) { + return { + queryKey: pluginSettingsKey("preferences"), + queryFn: async () => rpc.read.output.parse(await plugin.invoke(rpc.read.name, {})), + // The replica policy used by useSettings deliberately disables automatic refetches. + gcTime: Infinity, + staleTime: Infinity, + refetchOnMount: false, + refetchOnReconnect: false, + refetchOnWindowFocus: false, + retry: false, + } as const; +} + +it("retains installations and timeline transforms while disconnected", async () => { + const h = await connected(); + const plugin = h.installed(); + const snapshot = h.registry.getSnapshot(); + const transformers = plugin.timelineTransformers; + h.stop(); + h.sync({ connected: false }); + h.client.update({ + type: "status", + payload: { status: "plugin_catalog_changed", pluginId: "reports" }, + }); + expect(h.registry.getSnapshot()).toBe(snapshot); + expect(h.installed().timelineTransformers).toBe(transformers); + expect(plugin.lifetime.signal.aborted).toBe(false); + expect(h.disposals()).toBe(0); + expect(h.client.fetches).toBe(1); + expect(h.client.events).toEqual([ + "status.plugin_catalog_changed", + "status.plugin_settings_changed", + ]); +}); + +it.each(["mounted", "unmounted"])( + "refreshes %s settings and revisions after another client saves offline", + async (surface) => { + const h = await connected(); + const plugin = h.installed(); + const snapshot = h.registry.getSnapshot(); + const options = settingsQuery(plugin); + const original = await plugin.queryClient.fetchQuery(options); + const observer = new QueryObserver(plugin.queryClient, options); + const unsubscribe = observer.subscribe(() => {}); + cleanups.push(unsubscribe); + if (surface === "unmounted") unsubscribe(); + plugin.queryClient.setQueryData(["attachment-search"], "retained"); + const otherClient = new CatalogClient(); + h.registry.installCatalog("other", otherClient.catalog, { client: otherClient, audio }); + const otherPlugin = h.installed("other"); + await otherPlugin.queryClient.fetchQuery(settingsQuery(otherPlugin)); + // Another host publishes new presentation snapshots without replacing the owning lifetime. + const beforeReconnect = h.registry.getSnapshot(); + const retainedInstallation = h.installed(); + + h.stop(); + h.sync({ connected: false }); + const clientB = new CatalogClient(h.client.settings); + expect( + await clientB.invokePluginRpc("reports", rpc.write.name, { + revision: original.revision, + values: { label: "client B" }, + }), + ).toEqual({ status: "saved", revision: "2", values: { label: "client B" } }); + expect(plugin.queryClient.getQueryData(options.queryKey)).toEqual(original); + h.sync(); + + await expect + .poll(() => plugin.queryClient.getQueryData(options.queryKey)) + .toEqual({ + status: "ready", + revision: "2", + values: { label: "client B" }, + }); + const refreshed = await plugin.queryClient.fetchQuery(options); + expect( + await plugin.invoke(rpc.write.name, { + revision: refreshed.revision, + values: { label: "client A" }, + }), + ).toEqual({ status: "saved", revision: "3", values: { label: "client A" } }); + expect(h.registry.getSnapshot()).toBe(beforeReconnect); + expect(h.installed()).toBe(retainedInstallation); + expect(h.installed().lifetime).toBe(plugin.lifetime); + expect(h.installed().queryClient).toBe(plugin.queryClient); + expect(h.installed().timelineTransformers).toBe(snapshot[0].timelineTransformers); + expect(plugin.queryClient.getQueryData(["attachment-search"])).toBe("retained"); + expect(otherClient.settings.reads).toBe(1); + expect(otherPlugin.queryClient.getQueryState(options.queryKey)?.isInvalidated).toBe(false); + expect(otherPlugin.queryClient.getQueryData(options.queryKey)).toEqual(original); + expect(h.evaluations()).toBe(2); + expect(h.disposals()).toBe(0); + }, +); + +it("replaces changed bundles on reconnect and disposes the old installation", async () => { + const h = await connected(); + const plugin = h.installed(); + plugin.queryClient.setQueryData(["attachment-search"], "old"); + h.stop(); + h.client.catalog = catalog("two"); + h.sync(); + await expect.poll(() => h.installed() === plugin).toBe(false); + expect(plugin.lifetime.signal.aborted).toBe(true); + expect(plugin.queryClient.getQueryCache().getAll()).toEqual([]); + expect(h.installed().timelineTransformers.map((entry) => entry.id)).toEqual(["report"]); + expect(h.evaluations()).toBe(2); + expect(h.disposals()).toBe(1); +}); + +it("replaces an explicitly reloaded bundle even when its source is unchanged", async () => { + const h = await connected(); + const plugin = h.installed(); + h.client.update({ + type: "status", + payload: { status: "plugin_catalog_changed", pluginId: "reports" }, + }); + await expect.poll(() => h.installed() === plugin).toBe(false); + expect(h.disposals()).toBe(1); + expect(h.evaluations()).toBe(2); +}); + +it.each(["unsupported", "no audio"])("disposes plugins when %s", async (reason) => { + const h = await connected(); + const plugin = h.installed(); + h.stop(); + h.sync({ supported: reason !== "unsupported", audio: reason === "no audio" ? null : audio }); + expect(h.registry.getSnapshot()).toEqual([]); + expect(plugin.lifetime.signal.aborted).toBe(true); + expect(h.disposals()).toBe(1); +}); + +it("refreshes settings on a replayed subscription snapshot without reinstalling", async () => { + const h = await connected(); + const plugin = h.installed(); + const options = settingsQuery(plugin); + await plugin.queryClient.fetchQuery(options); + h.client.settings.write({ revision: "1", values: { label: "replayed" } }); + h.client.snapshot(); + await expect + .poll(() => plugin.queryClient.getQueryData(options.queryKey)) + .toEqual({ + status: "ready", + revision: "2", + values: { label: "replayed" }, + }); + expect(h.installed()).toBe(plugin); + expect(h.evaluations()).toBe(1); +}); + +it("invalidates only the named settings on its host for a live notification", async () => { + const h = await connected(); + const plugin = h.installed(); + const options = settingsQuery(plugin); + await plugin.queryClient.fetchQuery(options); + const observer = new QueryObserver(plugin.queryClient, options); + cleanups.push(observer.subscribe(() => {})); + plugin.queryClient.setQueryData(pluginSettingsKey("other-settings"), "unchanged"); + const other = new CatalogClient(); + h.registry.installCatalog("other", other.catalog, { client: other, audio }); + await h.installed("other").queryClient.fetchQuery(settingsQuery(h.installed("other"))); + + const beforeNotification = h.registry.getSnapshot(); + const retainedInstallation = h.installed(); + h.client.settings.write({ revision: "1", values: { label: "live" } }); + h.client.update({ + type: "status", + payload: { + status: "plugin_settings_changed", + pluginId: "reports", + settingsId: "preferences", + }, + }); + + await expect + .poll(() => plugin.queryClient.getQueryData(options.queryKey)) + .toEqual({ + status: "ready", + revision: "2", + values: { label: "live" }, + }); + expect(plugin.queryClient.getQueryState(pluginSettingsKey("other-settings"))?.isInvalidated).toBe( + false, + ); + expect(other.settings.reads).toBe(1); + expect(h.registry.getSnapshot()).toBe(beforeNotification); + expect(h.installed()).toBe(retainedInstallation); + expect(h.installed().lifetime).toBe(plugin.lifetime); + expect(h.installed().queryClient).toBe(plugin.queryClient); + expect(h.evaluations()).toBe(2); + expect(h.client.fetches).toBe(1); +}); + +it("ignores an in-flight catalog snapshot after disconnect", async () => { + const h = await connected(); + const plugin = h.installed(); + await plugin.queryClient.fetchQuery(settingsQuery(plugin)); + const snapshot = h.registry.getSnapshot(); + h.stop(); + let resolveCatalog: (value: Catalog) => void = () => {}; + const pending = new Promise((resolve) => { + resolveCatalog = resolve; + }); + let fetching: () => void = () => {}; + const started = new Promise((resolve) => { + fetching = resolve; + }); + class PendingClient extends CatalogClient { + override getPluginCatalog() { + fetching(); + return pending; + } + } + const stop = h.sync({ client: new PendingClient(h.client.settings) }); + await started; + stop(); + resolveCatalog(catalog("late")); + await pending; + // Drain the catalog continuation through a subsequently queued task. + await new Promise((resolve) => setTimeout(resolve, 0)); + expect(h.registry.getSnapshot()).toBe(snapshot); + expect(h.client.settings.reads).toBe(1); + expect(h.evaluations()).toBe(1); +}); diff --git a/packages/app/src/plugins/catalog-sync-model.ts b/packages/app/src/plugins/catalog-sync-model.ts new file mode 100644 index 0000000000..6571294a68 --- /dev/null +++ b/packages/app/src/plugins/catalog-sync-model.ts @@ -0,0 +1,93 @@ +import type { AudioEngine } from "@/audio"; +import type { DaemonClient } from "@getpaseo/client/internal/daemon-client"; +import type { PluginRegistry } from "./registry"; +import { pluginSettingsKey, pluginSettingsPrefix } from "./settings/query"; + +interface CatalogSyncInput { + serverId: string; + client: DaemonClient; + audio: Pick | null; + connected: boolean; + supported: boolean; + registry: Pick; +} + +export function syncPluginCatalog({ + serverId, + client, + audio, + connected, + supported, + registry, +}: CatalogSyncInput): () => void { + if (!supported || !audio) { + registry.removeHost(serverId); + return () => {}; + } + // A dropped socket reconnects on the same client, so installations keep rendering offline. + if (!connected) return () => {}; + const installationOptions = { client, audio }; + let cancelled = false; + let refreshQueue = Promise.resolve(); + function refresh(replacePluginId?: string) { + refreshQueue = refreshQueue.then(() => + client + .getPluginCatalog() + .then((catalog) => { + if (!cancelled) { + registry.installCatalog(serverId, catalog, { ...installationOptions, replacePluginId }); + } + return undefined; + }) + .catch((error) => { + if (!cancelled) { + console.warn(`[Plugins] Failed to load catalog for ${serverId}`, error); + } + return undefined; + }), + ); + return refreshQueue; + } + const observation = client.observeEvents([ + "status.plugin_catalog_changed", + "status.plugin_settings_changed", + ]); + observation.subscribe({ + snapshot: () => { + void refresh().then(() => { + if (cancelled) return undefined; + // Retained replicas miss offline writes and do not refetch when a screen mounts. + for (const plugin of registry.getSnapshot()) { + if (plugin.serverId !== serverId) continue; + void plugin.queryClient.invalidateQueries({ + queryKey: pluginSettingsPrefix, + refetchType: "all", + }); + } + return undefined; + }); + }, + update: (message) => { + if (message.type !== "status") return; + if (message.payload.status === "plugin_settings_changed") { + const { pluginId, settingsId } = message.payload; + if (typeof settingsId === "string") { + const plugin = registry + .getSnapshot() + .find((item) => item.serverId === serverId && item.id === pluginId); + void plugin?.queryClient.invalidateQueries({ queryKey: pluginSettingsKey(settingsId) }); + } + } + if (message.payload.status === "plugin_catalog_changed") { + const pluginId = message.payload.pluginId; + if (typeof pluginId === "string") void refresh(pluginId); + } + }, + }); + return () => { + cancelled = true; + void observation + .release() + .catch((error) => console.warn("[Plugins] Failed to release catalog", error)); + }; +} diff --git a/packages/app/src/plugins/catalog-sync.tsx b/packages/app/src/plugins/catalog-sync.tsx index 0eedfde3ab..6dc11b72b8 100644 --- a/packages/app/src/plugins/catalog-sync.tsx +++ b/packages/app/src/plugins/catalog-sync.tsx @@ -1,10 +1,10 @@ import { useVoiceAudioEngineOptional } from "@/contexts/voice-context"; -import { pluginSettingsKey } from "./settings/use-settings"; import { useEffect } from "react"; import type { DaemonClient } from "@getpaseo/client/internal/daemon-client"; import { useHostFeature } from "@/runtime/host-features"; import { useHostRuntimeIsConnected } from "@/runtime/host-runtime"; import { pluginRegistry } from "./registry"; +import { syncPluginCatalog } from "./catalog-sync-model"; export function PluginCatalogSync({ serverId, @@ -17,72 +17,18 @@ export function PluginCatalogSync({ const connected = useHostRuntimeIsConnected(serverId); const supported = useHostFeature(serverId, "plugins"); - useEffect(() => { - let cancelled = false; - let refreshQueue = Promise.resolve(); - if (!supported || !audio) { - pluginRegistry.removeHost(serverId); - return; - } - if (!connected) { - pluginRegistry.removeHost(serverId); - return; - } - const refresh = (replacePluginId?: string) => { - refreshQueue = refreshQueue.then(() => - client - .getPluginCatalog() - .then((catalog) => { - if (!cancelled) { - pluginRegistry.installCatalog(serverId, catalog, { - replacePluginId, - client, - audio, - }); - } - return undefined; - }) - .catch((error) => { - if (!cancelled) { - console.warn(`[Plugins] Failed to load catalog for ${serverId}`, error); - } - return undefined; - }), - ); - return refreshQueue; - }; - const observation = client.observeEvents([ - "status.plugin_catalog_changed", - "status.plugin_settings_changed", - ]); - observation.subscribe({ - snapshot: () => { - void refresh(); - }, - update: (message) => { - if (message.type !== "status") return; - if (message.payload.status === "plugin_settings_changed") { - const { pluginId, settingsId } = message.payload; - if (typeof settingsId === "string") { - const plugin = pluginRegistry - .getSnapshot() - .find((item) => item.serverId === serverId && item.id === pluginId); - void plugin?.queryClient.invalidateQueries({ queryKey: pluginSettingsKey(settingsId) }); - } - } - if (message.payload.status === "plugin_catalog_changed") { - const pluginId = message.payload.pluginId; - if (typeof pluginId === "string") void refresh(pluginId); - } - }, - }); - return () => { - cancelled = true; - void observation - .release() - .catch((error) => console.warn("[Plugins] Failed to release catalog", error)); - }; - }, [audio, client, connected, serverId, supported]); + useEffect( + () => + syncPluginCatalog({ + serverId, + client, + audio, + connected, + supported, + registry: pluginRegistry, + }), + [audio, client, connected, serverId, supported], + ); useEffect(() => () => pluginRegistry.removeHost(serverId), [serverId]); return null; diff --git a/packages/app/src/plugins/client-bundles/index.ts b/packages/app/src/plugins/client-bundles/index.ts new file mode 100644 index 0000000000..06580dd222 --- /dev/null +++ b/packages/app/src/plugins/client-bundles/index.ts @@ -0,0 +1,32 @@ +import * as FileSystem from "expo-file-system/legacy"; +import { CryptoDigestAlgorithm, digestStringAsync, randomUUID } from "expo-crypto"; +import { createPluginClientBundleStore } from "./store"; + +export function createHostPluginClientBundleStore(serverId: string) { + const directory = `${FileSystem.cacheDirectory}plugin-client-bundles/${encodeURIComponent(serverId)}/`; + const ensureDirectory = async () => { + if (!FileSystem.cacheDirectory) throw new Error("Plugin bundle cache directory unavailable"); + await FileSystem.makeDirectoryAsync(directory, { intermediates: true }); + }; + return createPluginClientBundleStore( + { + async list() { + await ensureDirectory(); + return FileSystem.readDirectoryAsync(directory); + }, + read: (name) => FileSystem.readAsStringAsync(`${directory}${name}`), + async writeAtomic(name, contents) { + await ensureDirectory(); + const temporary = `${directory}${randomUUID()}.tmp`; + try { + await FileSystem.writeAsStringAsync(temporary, contents); + await FileSystem.moveAsync({ from: temporary, to: `${directory}${name}` }); + } finally { + await FileSystem.deleteAsync(temporary, { idempotent: true }); + } + }, + remove: (name) => FileSystem.deleteAsync(`${directory}${name}`, { idempotent: true }), + }, + (contents) => digestStringAsync(CryptoDigestAlgorithm.SHA256, contents), + ); +} diff --git a/packages/app/src/plugins/client-bundles/index.web.ts b/packages/app/src/plugins/client-bundles/index.web.ts new file mode 100644 index 0000000000..6e67778089 --- /dev/null +++ b/packages/app/src/plugins/client-bundles/index.web.ts @@ -0,0 +1,62 @@ +import { createPluginClientBundleStore } from "./store"; + +const DATABASE_NAME = "paseo-plugin-client-bundles"; +const STORE_NAME = "bundles"; +let opening: Promise | undefined; + +function openDatabase(): Promise { + opening ??= new Promise((resolve, reject) => { + const request = indexedDB.open(DATABASE_NAME, 1); + request.addEventListener("upgradeneeded", () => request.result.createObjectStore(STORE_NAME)); + request.addEventListener("success", () => resolve(request.result)); + request.addEventListener("error", () => reject(request.error)); + }).catch((error) => { + opening = undefined; + throw error; + }); + return opening; +} + +export function createHostPluginClientBundleStore(serverId: string) { + const prefix = `${encodeURIComponent(serverId)}/`; + const range = () => IDBKeyRange.bound(prefix, `${prefix}\uffff`); + async function run( + mode: IDBTransactionMode, + operation: (store: IDBObjectStore) => IDBRequest, + ): Promise { + const database = await openDatabase(); + return new Promise((resolve, reject) => { + const transaction = database.transaction(STORE_NAME, mode); + const request = operation(transaction.objectStore(STORE_NAME)); + transaction.addEventListener("complete", () => resolve(request.result)); + transaction.addEventListener("abort", () => reject(transaction.error)); + transaction.addEventListener("error", () => reject(transaction.error)); + }); + } + return createPluginClientBundleStore( + { + async list() { + return (await run("readonly", (store) => store.getAllKeys(range()))) + .filter((key): key is string => typeof key === "string") + .map((key) => key.slice(prefix.length)); + }, + async read(name) { + const result: unknown = await run("readonly", (store) => store.get(`${prefix}${name}`)); + if (typeof result !== "string") throw new Error("Missing plugin client bundle"); + return result; + }, + async writeAtomic(name, contents) { + await run("readwrite", (store) => store.put(contents, `${prefix}${name}`)); + }, + async remove(name) { + await run("readwrite", (store) => store.delete(`${prefix}${name}`)); + }, + }, + async (contents) => { + const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(contents)); + return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join( + "", + ); + }, + ); +} diff --git a/packages/app/src/plugins/client-bundles/storage.browser.test.ts b/packages/app/src/plugins/client-bundles/storage.browser.test.ts new file mode 100644 index 0000000000..9acd7e0c52 --- /dev/null +++ b/packages/app/src/plugins/client-bundles/storage.browser.test.ts @@ -0,0 +1,36 @@ +import { expect, test } from "vitest"; +import { createHostPluginClientBundleStore } from "./index.web"; + +async function sha256(contents: string) { + const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(contents)); + return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join(""); +} + +test("browser bundles survive a fresh store and remain isolated by host", async () => { + const first = createHostPluginClientBundleStore("bundle-test-host-a"); + const second = createHostPluginClientBundleStore("bundle-test-host-b"); + const clientBundle = "bundle".repeat(250_000); + const entry = { + id: "same-plugin", + clientBundle, + clientBundleHash: await sha256(clientBundle), + }; + const otherCode = "other host code"; + const other = { + id: entry.id, + clientBundle: otherCode, + clientBundleHash: await sha256(otherCode), + }; + try { + await first.replace([entry]); + await second.replace([other]); + expect(await createHostPluginClientBundleStore("bundle-test-host-a").load()).toEqual([entry]); + expect(await createHostPluginClientBundleStore("bundle-test-host-b").load()).toEqual([other]); + await first.replace([]); + expect(await createHostPluginClientBundleStore("bundle-test-host-a").load()).toEqual([]); + expect(await second.load()).toEqual([other]); + } finally { + await first.replace([]); + await second.replace([]); + } +}); diff --git a/packages/app/src/plugins/client-bundles/store.test.ts b/packages/app/src/plugins/client-bundles/store.test.ts new file mode 100644 index 0000000000..c3332c6b0e --- /dev/null +++ b/packages/app/src/plugins/client-bundles/store.test.ts @@ -0,0 +1,179 @@ +import { createHash } from "node:crypto"; +import { DaemonClient } from "@getpaseo/client/internal/daemon-client"; +import { expect, test } from "vitest"; +import { createPluginClientBundleStore, type PluginBundleFiles } from "./store"; + +const sha256 = async (contents: string) => createHash("sha256").update(contents).digest("hex"); + +class BundleFiles implements PluginBundleFiles { + readonly contents = new Map(); + readonly writes: string[] = []; + async list() { + return [...this.contents.keys()]; + } + async read(name: string) { + const contents = this.contents.get(name); + if (contents === undefined) throw new Error("File disappeared"); + return contents; + } + async writeAtomic(name: string, contents: string) { + this.writes.push(name); + this.contents.set(name, contents); + } + async remove(name: string) { + this.contents.delete(name); + } +} + +async function bundle(id: string, clientBundle: string) { + return { id, clientBundle, clientBundleHash: await sha256(clientBundle) }; +} + +test("a cold store loads verified bundles and prunes versions missing from the latest catalog", async () => { + const files = new BundleFiles(); + const old = await bundle("changed", "old"); + const kept = await bundle("kept", "Unicode: 折叠屏 🐚"); + await createPluginClientBundleStore(files, sha256).replace([old, kept]); + const cold = createPluginClientBundleStore(files, sha256); + expect(await cold.load()).toEqual([old, kept]); + const changed = await bundle("changed", "new"); + await cold.replace([kept, changed]); + expect(files.contents.size).toBe(2); + expect(await createPluginClientBundleStore(files, sha256).load()).toEqual([kept, changed]); + expect(files.writes).toHaveLength(3); + await cold.replace([]); + expect(files.contents.size).toBe(0); +}); + +test("same-length corruption, truncated files and unreadable files are not advertised", async () => { + const files = new BundleFiles(); + const entries = await Promise.all([ + bundle("same-length", "good"), + bundle("truncated", "long"), + bundle("missing", "lost"), + ]); + await createPluginClientBundleStore(files, sha256).replace(entries); + const names = [...files.contents.keys()]; + files.contents.set(names[0]!, "evil"); + files.contents.set(names[1]!, "lo"); + // The directory entry still exists while reading the file fails. + const unreadable: PluginBundleFiles = { + list: () => files.list(), + read: (name) => + name === names[2] ? Promise.reject(new Error("Unreadable")) : files.read(name), + writeAtomic: (name, contents) => files.writeAtomic(name, contents), + remove: (name) => files.remove(name), + }; + const cold = createPluginClientBundleStore(unreadable, sha256); + expect(await cold.load()).toEqual([]); + await cold.replace(entries); + expect(await createPluginClientBundleStore(files, sha256).load()).toEqual(entries); +}); + +test("an interrupted atomic write leaves the prior catalog available for a cold reader", async () => { + const files = new BundleFiles(); + const previous = await bundle("plugin", "previous"); + await createPluginClientBundleStore(files, sha256).replace([previous]); + const failing: PluginBundleFiles = { + list: () => files.list(), + read: (name) => files.read(name), + remove: (name) => files.remove(name), + writeAtomic: async () => { + throw new Error("Disk full"); + }, + }; + await expect( + createPluginClientBundleStore(failing, sha256).replace([await bundle("plugin", "next")]), + ).rejects.toThrow("Disk full"); + expect(await createPluginClientBundleStore(files, sha256).load()).toEqual([previous]); +}); + +// Exercise the app store through a fresh platform-agnostic client, using its transport port. +test.each(["valid", "corrupt", "missing"])( + "cold catalog uses a %s persisted bundle correctly", + async (state) => { + const files = new BundleFiles(); + const entry = await bundle("plugin", "good code"); + await createPluginClientBundleStore(files, sha256).replace([entry]); + if (state === "corrupt") files.contents.set([...files.contents.keys()][0]!, "evil code"); + if (state === "missing") files.contents.clear(); + let open = () => {}; + let receive: (data: unknown, binary: boolean) => void = () => {}; + const requests: Record[] = []; + const client = new DaemonClient({ + url: "ws://test", + clientId: "plugin-cache-test", + reconnect: { enabled: false }, + createPluginClientBundleStore: () => createPluginClientBundleStore(files, sha256), + transportFactory: () => ({ + send(data) { + if (typeof data !== "string") return; + const frame = JSON.parse(data); + if (frame.type !== "session") return; + const request = frame.message; + if (request.type !== "plugin.catalog.get.request") return; + requests.push(request); + const { clientBundle: _code, ...reference } = entry; + receive( + JSON.stringify({ + type: "session", + message: { + type: "plugin.catalog.get.response", + payload: { + requestId: request.requestId, + plugins: [request.cachedClientBundles ? reference : entry], + }, + }, + }), + false, + ); + }, + close() {}, + onOpen(handler) { + open = handler; + return () => {}; + }, + onMessage(handler) { + receive = handler; + return () => {}; + }, + onClose() { + return () => {}; + }, + onError() { + return () => {}; + }, + }), + }); + try { + const connecting = client.connect(); + open(); + receive( + JSON.stringify({ + type: "session", + message: { + type: "status", + payload: { + status: "server_info", + serverId: "cache-host", + hostname: null, + version: null, + features: { plugins: true }, + }, + }, + }), + false, + ); + await connecting; + expect(await client.getPluginCatalog()).toEqual([entry]); + if (state === "valid") + expect(requests[0]?.cachedClientBundles).toEqual([ + { id: entry.id, clientBundleHash: entry.clientBundleHash }, + ]); + else expect(requests[0]).not.toHaveProperty("cachedClientBundles"); + await expect.poll(() => createPluginClientBundleStore(files, sha256).load()).toEqual([entry]); + } finally { + await client.close(); + } + }, +); diff --git a/packages/app/src/plugins/client-bundles/store.ts b/packages/app/src/plugins/client-bundles/store.ts new file mode 100644 index 0000000000..4a120c2c2a --- /dev/null +++ b/packages/app/src/plugins/client-bundles/store.ts @@ -0,0 +1,56 @@ +import type { + PluginClientBundle, + PluginClientBundleStore, +} from "@getpaseo/client/internal/daemon-client"; + +/** Each adapter is scoped to one host. Writes publish a complete file/record atomically. */ +export interface PluginBundleFiles { + list(): Promise; + read(name: string): Promise; + writeAtomic(name: string, contents: string): Promise; + remove(name: string): Promise; +} + +export function createPluginClientBundleStore( + files: PluginBundleFiles, + sha256: (contents: string) => Promise, +): PluginClientBundleStore { + const verified = new Set(); + const filename = (bundle: PluginClientBundle) => + `${encodeURIComponent(bundle.id)}.${bundle.clientBundleHash}.js`; + return { + async load() { + const bundles: PluginClientBundle[] = []; + for (const name of await files.list()) { + try { + const match = /^(.*)\.([a-f0-9]{64})\.js$/.exec(name); + if (!match) continue; + const id = decodeURIComponent(match[1]!); + const clientBundleHash = match[2]!; + const clientBundle = await files.read(name); + if ((await sha256(clientBundle)) !== clientBundleHash) continue; + verified.add(name); + bundles.push({ id, clientBundleHash, clientBundle }); + } catch { + // Missing, unreadable or corrupt files are cache misses, never executable code. + } + } + return bundles; + }, + async replace(bundles) { + const retained = new Set(); + for (const bundle of bundles) { + const name = filename(bundle); + retained.add(name); + if (verified.has(name)) continue; + await files.writeAtomic(name, bundle.clientBundle); + verified.add(name); + } + for (const name of await files.list()) { + if (retained.has(name)) continue; + await files.remove(name); + verified.delete(name); + } + }, + }; +} diff --git a/packages/app/src/plugins/registry-lifecycle.test.ts b/packages/app/src/plugins/registry-lifecycle.test.ts index 18330dc949..d2d02cb568 100644 --- a/packages/app/src/plugins/registry-lifecycle.test.ts +++ b/packages/app/src/plugins/registry-lifecycle.test.ts @@ -219,7 +219,10 @@ test("locale snapshots preserve installation state and observations, then releas expect(after.paseo).toBe(before.paseo); expect(after.surfaces[0].Component).toBe(before.surfaces[0].Component); expect(h.open).toEqual(new Set(["notes"])); + const translatedSnapshot = h.plugins.getSnapshot(); h.plugins.installCatalog("host", [translated], { client: h.client, audio }); + expect(h.plugins.getSnapshot()).toBe(translatedSnapshot); + expect(h.plugins.getSnapshot()[0].locale).toBe("zh-CN"); expect(h.plugins.getSnapshot()[0].i18n).toBe(before.i18n); h.plugins.removeHost("host"); expect(listeners.size).toBe(0); diff --git a/packages/app/src/plugins/registry.test.ts b/packages/app/src/plugins/registry.test.ts index 9e8d246a95..4d3877161f 100644 --- a/packages/app/src/plugins/registry.test.ts +++ b/packages/app/src/plugins/registry.test.ts @@ -27,12 +27,12 @@ const pluginRegistry = { installCatalog( serverId: string, catalog: Parameters[1], - options: { replacePluginId?: string } = {}, + options: { replacePluginId?: string; client?: DaemonClient } = {}, ) { return registry.installCatalog( serverId, catalog.map((entry) => ({ ...entry, requirements: { paseo: `>=${appPackage.version}` } })), - { ...options, client: daemonClient, audio }, + { client: daemonClient, ...options, audio }, ); }, }; @@ -118,6 +118,37 @@ describe("PluginRegistry", () => { expect(second?.queryClient.getQueryData(["counter"])).toBe(3); }); + it("keeps the snapshot when the same catalog is installed again", () => { + const clientBundle = timelineBundle("one"); + pluginRegistry.installCatalog("host-a", [{ id: "reports", clientBundle }]); + const snapshot = pluginRegistry.getSnapshot(); + const transformers = snapshot[0]?.timelineTransformers; + const listener = vi.fn(); + const unsubscribe = pluginRegistry.subscribe(listener); + + pluginRegistry.installCatalog("host-a", [{ id: "reports", clientBundle }]); + unsubscribe(); + + expect(pluginRegistry.getSnapshot()).toBe(snapshot); + expect(pluginRegistry.getSnapshot()[0]?.timelineTransformers).toBe(transformers); + expect(listener).not.toHaveBeenCalled(); + }); + + it("reinstalls an unchanged bundle for a new host client", () => { + const clientBundle = bundle("one"); + pluginRegistry.installCatalog("host-a", [{ id: "example", clientBundle }]); + const first = pluginRegistry.getSnapshot()[0]; + + pluginRegistry.installCatalog("host-a", [{ id: "example", clientBundle }], { + client: {} as DaemonClient, + }); + + const second = pluginRegistry.getSnapshot()[0]; + expect(second).not.toBe(first); + expect(first?.lifetime.signal.aborted).toBe(true); + expect(Reflect.get(globalThis, "__pluginCleanups")).toBe(1); + }); + it("replaces the query cache when the plugin bundle changes", () => { pluginRegistry.installCatalog("host-a", [{ id: "example", clientBundle: bundle("one") }]); const first = pluginRegistry.getSnapshot()[0]; diff --git a/packages/app/src/plugins/registry.ts b/packages/app/src/plugins/registry.ts index adbdabc93c..cfe4f7212a 100644 --- a/packages/app/src/plugins/registry.ts +++ b/packages/app/src/plugins/registry.ts @@ -19,6 +19,8 @@ export class PluginRegistry { private snapshot: InstalledPlugin[] = []; private readonly disposed = new WeakSet(); private readonly evaluationErrors = new Map(); + /** The client each host's installations were bound to; their Paseo API and RPCs call it. */ + private readonly clientByHost = new Map(); constructor( private readonly dependencies: { @@ -49,10 +51,15 @@ export class PluginRegistry { }, ): boolean { const previous = this.byHost.get(serverId) ?? []; + const previousErrors = this.hostEvaluationErrors(serverId); + // Installations call the client they were created with, so a new client replaces them all. + const sameClient = this.clientByHost.get(serverId) === options.client; + this.clientByHost.set(serverId, options.client); const previousTimelineBundles = previous .filter((plugin) => plugin.timelineTransformers.length > 0) .map((plugin) => `${plugin.id}\0${plugin.clientBundle}`); const preserved = catalog.flatMap((entry) => { + if (!sameClient) return []; const existing = previous.find( (plugin) => plugin.id !== options.replacePluginId && @@ -146,13 +153,13 @@ export class PluginRegistry { } } this.byHost.set(serverId, installed); - if ( - installed.length !== catalog.length || - installed.length !== previous.length || - installed.some((plugin, index) => plugin !== previous[index]) - ) { - this.publish(); - } + // An unchanged catalog keeps the snapshot, so timeline projections cached against the + // installed transformers stay valid across a reconnect. + const unchanged = + installed.length === previous.length && + installed.every((plugin, index) => plugin === previous[index]) && + this.hostEvaluationErrors(serverId) === previousErrors; + if (!unchanged) this.publish(); const installedTimelineBundles = installed .filter((plugin) => plugin.timelineTransformers.length > 0) .map((plugin) => `${plugin.id}\0${plugin.clientBundle}`); @@ -170,9 +177,17 @@ export class PluginRegistry { if (key.startsWith(`${serverId}/`)) this.evaluationErrors.delete(key); } this.byHost.delete(serverId); + this.clientByHost.delete(serverId); this.publish(); } + private hostEvaluationErrors(serverId: string): string { + const prefix = `${serverId}/`; + return JSON.stringify( + [...this.evaluationErrors].filter(([key]) => key.startsWith(prefix)).sort(), + ); + } + private dispose(plugin: InstalledPlugin): void { if (this.disposed.has(plugin)) return; this.disposed.add(plugin); diff --git a/packages/app/src/plugins/settings/query.ts b/packages/app/src/plugins/settings/query.ts new file mode 100644 index 0000000000..db06d58320 --- /dev/null +++ b/packages/app/src/plugins/settings/query.ts @@ -0,0 +1,2 @@ +export const pluginSettingsPrefix = ["plugin-settings"] as const; +export const pluginSettingsKey = (id: string) => [...pluginSettingsPrefix, id] as const; diff --git a/packages/app/src/plugins/settings/use-settings.ts b/packages/app/src/plugins/settings/use-settings.ts index 0cefc1878f..decf4bfe05 100644 --- a/packages/app/src/plugins/settings/use-settings.ts +++ b/packages/app/src/plugins/settings/use-settings.ts @@ -6,8 +6,8 @@ import { type SettingsDefinition } from "@getpaseo/plugin"; import { settingsRpc } from "@getpaseo/plugin"; import { useReplicaQuery } from "@/data/query"; import { z, type ZodType } from "zod"; +import { pluginSettingsKey } from "./query"; -export const pluginSettingsKey = (id: string) => ["plugin-settings", id] as const; function message(error: unknown): string { if (error instanceof z.ZodError) return error.issues.map((issue) => issue.message).join("\n"); return error instanceof Error ? error.message : String(error); diff --git a/packages/app/src/provider-selection/provider-selection.ts b/packages/app/src/provider-selection/provider-selection.ts index e0313c6623..54d75f1da2 100644 --- a/packages/app/src/provider-selection/provider-selection.ts +++ b/packages/app/src/provider-selection/provider-selection.ts @@ -5,7 +5,7 @@ import type { ProviderSnapshotEntry, } from "@getpaseo/protocol/agent-types"; import type { AgentProviderDefinition } from "@getpaseo/protocol/provider-manifest"; -import type { DraftCommandTarget } from "@/hooks/use-agent-commands-query"; +import type { DraftCommandTarget } from "@/agent-commands"; import { i18n } from "@/i18n/i18next"; import { compareMatchScores, scoreTextFields } from "@getpaseo/protocol/search/text-match"; import { filterSelectableModels } from "./model-catalog"; diff --git a/packages/app/src/runtime/directory-sync/index.test.ts b/packages/app/src/runtime/directory-sync/index.test.ts index 6fae0a7e92..e4db5dfb71 100644 --- a/packages/app/src/runtime/directory-sync/index.test.ts +++ b/packages/app/src/runtime/directory-sync/index.test.ts @@ -16,7 +16,8 @@ import { normalizeWorkspaceDescriptor, useSessionStore, } from "@/stores/session-store"; -import { normalizeAgentSnapshot } from "@/utils/agent-snapshots"; +import { normalizeAgentSnapshot, projectAgentSnapshot } from "@/utils/agent-snapshots"; +import { deriveProjectPlacementFromCwd } from "@/utils/project-placement"; import { selectWorkspaceDirectoryServerIds } from "@/stores/session-store-hooks/selectors"; import { useWorkspaceLabels } from "@/workspace-labels"; import type { DirectoryReplicaMutation } from "@/runtime/replica-cache"; @@ -41,12 +42,15 @@ class FakeDirectoryClient { supportsWorkspaceLabels = false; listWorkspaceLabelsCalls = 0; fetchAgentsCalls = 0; + observeAgentsCalls = 0; lastAgentOptions: unknown; fetchWorkspacesCalls = 0; + observeWorkspacesCalls = 0; lastWorkspaceOptions: unknown; listProjectsCalls = 0; lastProjectOptions: unknown; projectResult: ProjectListResult | null = null; + readonly listSnapshots: Promise[] = []; private pendingAgentFetch: Promise | null = null; private pendingWorkspaceFetch: Promise | null = null; private pendingProjectFetch: Promise | null = null; @@ -151,15 +155,22 @@ class FakeDirectoryClient { } observeAgents(options: Parameters[0]) { - return subscriptionFixture(this.fetchAgents({ ...options, subscribe: {} }), (receive) => - this.on("agent_update", receive), + this.observeAgentsCalls += 1; + const subscription = subscriptionFixture( + this.fetchAgents({ ...options, subscribe: {} }), + (receive) => this.on("agent_update", receive), ); + this.listSnapshots.push(subscription.ready); + return subscription; } observeWorkspaces(options: Parameters[0]) { - return subscriptionFixture(this.fetchWorkspaces(options), (receive) => + this.observeWorkspacesCalls += 1; + const subscription = subscriptionFixture(this.fetchWorkspaces(options), (receive) => this.on("workspace_update", receive), ); + this.listSnapshots.push(subscription.ready); + return subscription; } observeEvents(events: readonly SessionOutboundMessage["type"][]) { @@ -592,6 +603,83 @@ describe("DirectorySync session readiness", () => { directory.dispose(); }); + it.each([ + ["full", "before"], + ["full", "after"], + ["route", "before"], + ["route", "after"], + ] as const)( + "restores live directory updates when %s demand returns %s refresh completion", + async (demand, timing) => { + const serverId = `released-directory-${demand}-${timing}`; + const { client, directory } = createDirectory(serverId); + const store = useSessionStore.getState(); + store.initializeSession(serverId, client as unknown as DaemonClient, 1); + store.updateSessionServerInfo(serverId, { + serverId, + hostname: null, + version: "test", + features: { workspaceMultiplicity: true, projectList: true }, + }); + const source = {}; + function setDemand(demanded: boolean): void { + if (demand === "full") directory.setDemand(source, demanded); + else directory.setAgentRouteDemand(demanded ? ["agent-1"] : []); + } + const releaseProjects = client.holdProjectFetch(); + const projects: ProjectListResult = { requestId: "projects", projects: [] }; + + try { + setDemand(true); + const refresh = directory.refreshDemand(); + await expect + .poll(() => [client.observeAgentsCalls, client.observeWorkspacesCalls]) + .toEqual([1, 1]); + + await Promise.all(client.listSnapshots); + setDemand(false); + if (timing === "before") setDemand(true); + releaseProjects(projects); + await refresh; + if (timing === "after") setDemand(true); + + await expect + .poll(() => [client.observeAgentsCalls, client.observeWorkspacesCalls]) + .toEqual([2, 2]); + client.emit({ + type: "agent_update", + payload: { + kind: "upsert", + agent: { + ...projectAgentSnapshot(createAgent(serverId, "agent-1")), + title: "Live title", + }, + project: deriveProjectPlacementFromCwd("/repo"), + }, + }); + client.emit({ + type: "workspace_update", + payload: { + kind: "upsert", + workspace: { ...createWorkspaceEntry("workspace-1"), name: "Live workspace" }, + }, + }); + + await expect + .poll(() => { + const session = useSessionStore.getState().sessions[serverId]; + return [ + session.agents.get("agent-1")?.title, + session.workspaces.get("workspace-1")?.name, + ]; + }) + .toEqual(["Live title", "Live workspace"]); + } finally { + directory.dispose(); + } + }, + ); + it("publishes cached directory data before the authoritative request completes", async () => { const serverId = "cached-directory"; serverIds.add(serverId); diff --git a/packages/app/src/runtime/directory-sync/index.ts b/packages/app/src/runtime/directory-sync/index.ts index b59440d782..1ffb4fae5f 100644 --- a/packages/app/src/runtime/directory-sync/index.ts +++ b/packages/app/src/runtime/directory-sync/index.ts @@ -160,6 +160,7 @@ export class DirectorySync { private readonly fullDemandSources = new Set(); private readonly scriptStatusDemand = new Map(); private demandRefresh: Promise | null = null; + private subscriptionGeneration = 0; private satisfiedDemandSource: DirectorySourceToken | null = null; private cursors: DirectoryCheckpoint = {}; @@ -262,6 +263,7 @@ export class DirectorySync { } private releaseSubscriptions(): void { + this.subscriptionGeneration += 1; for (const subscription of [ this.agentSubscription, this.workspaceSubscription, @@ -362,6 +364,7 @@ export class DirectorySync { this.observeDirectoryEvents(); this.observeScriptStatusEvents(); const source = this.connection.source; + const subscriptionGeneration = this.subscriptionGeneration; if ( !force && this.satisfiedDemandSource?.clientGeneration === source.clientGeneration && @@ -378,17 +381,19 @@ export class DirectorySync { ]).then(() => undefined); this.demandRefresh = refresh .then(() => { - this.satisfiedDemandSource = source; + if (this.subscriptionGeneration === subscriptionGeneration) { + this.satisfiedDemandSource = source; + } return undefined; }) .finally(() => { this.demandRefresh = null; const current = this.connection.source; - if ( - this.hasDemand() && - (current.clientGeneration !== source.clientGeneration || - current.connectionEpoch !== source.connectionEpoch) - ) { + const sourceChanged = + current.clientGeneration !== source.clientGeneration || + current.connectionEpoch !== source.connectionEpoch; + const subscriptionsReleased = this.subscriptionGeneration !== subscriptionGeneration; + if (this.hasDemand() && (sourceChanged || subscriptionsReleased)) { void this.requestDemandRefresh().catch(() => undefined); } }); diff --git a/packages/app/src/runtime/host-runtime.ts b/packages/app/src/runtime/host-runtime.ts index bb953220cb..0c7c9f4660 100644 --- a/packages/app/src/runtime/host-runtime.ts +++ b/packages/app/src/runtime/host-runtime.ts @@ -1,3 +1,4 @@ +import { createHostPluginClientBundleStore } from "@/plugins/client-bundles"; import { watchdog } from "@/watchdog"; import { createHostChannelTransport } from "@getpaseo/client/internal/hosts"; import type { OwnedSubscription } from "@getpaseo/client"; @@ -589,6 +590,7 @@ function createDefaultDeps( capabilities: appCapabilities, trace: createPerformanceTrace({ host: host.serverId, connection: connection.id }), providerSnapshots: "wire", + createPluginClientBundleStore: createHostPluginClientBundleStore, ...(host.password ? { password: host.password } : {}), localCredential: () => readDesktopManagedLocalCredential(connection), } satisfies Omit; @@ -668,6 +670,7 @@ function createDefaultDeps( ), reconnect: { enabled: false }, appVersion: resolveAppVersion() ?? undefined, + createPluginClientBundleStore: createHostPluginClientBundleStore, }); try { await client.connect(); @@ -684,6 +687,7 @@ function createDefaultDeps( ...(timeoutMs !== undefined ? { timeoutMs } : {}), capabilities: appCapabilities, trace: createPerformanceTrace({ host: host.serverId, connection: connection.id }), + createPluginClientBundleStore: createHostPluginClientBundleStore, }); }, getClientId: () => getOrCreateClientId(), diff --git a/packages/app/src/runtime/replica-cache/index.test.ts b/packages/app/src/runtime/replica-cache/index.test.ts index eaad715a52..d91d8e7ba4 100644 --- a/packages/app/src/runtime/replica-cache/index.test.ts +++ b/packages/app/src/runtime/replica-cache/index.test.ts @@ -306,6 +306,21 @@ async function expectLegacyWorkspaceRefresh({ } describe("ReplicaCache", () => { + it("persists the complete newest turn beyond the cache item target", async () => { + const storage = new MemoryStorage(); + const writer = createCache(storage); + const items = Array.from({ length: 60 }, (_, index) => ({ + ...timelineItem(`item-${index}`), + id: `item-${index}`, + turnId: "long-run", + })); + writer.commitTimeline(SERVER_ID, "agent-1", { ...timeline(), items }); + await writer.flush(); + const restored = await createCache(storage).readTimeline(SERVER_ID, "agent-1"); + expect(restored?.items.map((item) => item.id)).toEqual(items.map((item) => item.id)); + expect(restored?.range).toBeNull(); + }); + it("preserves workspace sorting timestamps across cache reopen", async () => { const storage = new MemoryStorage(); const writer = createCache(storage); diff --git a/packages/app/src/runtime/replica-cache/index.ts b/packages/app/src/runtime/replica-cache/index.ts index 59578e65d7..9ad604c8eb 100644 --- a/packages/app/src/runtime/replica-cache/index.ts +++ b/packages/app/src/runtime/replica-cache/index.ts @@ -1,3 +1,4 @@ +import { findMountedWindowStart } from "@/agent-stream/history-window"; import { z } from "zod"; import { AgentStatusSchema, @@ -766,7 +767,14 @@ function serializeTimeline(timeline: CachedTimeline): StoredTimeline | null { const canonicalItems = timeline.items.filter( (item) => item.kind !== "user_message" || !isUnreconciledLocalUserMessage(item), ); - const items = canonicalItems.map(serializeTimelineItem).filter((item) => item !== null); + const start = findMountedWindowStart({ + items: canonicalItems, + minMountedCount: MAX_TIMELINE_ITEMS, + }); + const items = canonicalItems + .slice(start) + .map(serializeTimelineItem) + .filter((item) => item !== null); const range = timeline.range; const canPersistCoverage = range !== null && @@ -783,7 +791,7 @@ function serializeTimeline(timeline: CachedTimeline): StoredTimeline | null { canonicalItems.some((item) => item.timelineCursor?.seq === range.endSeq); return { agentId: timeline.agentId, - items: items.slice(-MAX_TIMELINE_ITEMS), + items, range: canPersistCoverage ? { epoch: range.epoch, startSeq: range.startSeq, endSeq: range.endSeq } : null, diff --git a/packages/app/src/screens/settings-screen.tsx b/packages/app/src/screens/settings-screen.tsx index b45b745212..78425bf20d 100644 --- a/packages/app/src/screens/settings-screen.tsx +++ b/packages/app/src/screens/settings-screen.tsx @@ -122,7 +122,11 @@ import { MetadataGenerationPage } from "@/screens/settings/metadata-generation-p import { HostVoicePage } from "@/screens/settings/voice/voice-page"; import ProjectsScreen from "@/screens/projects-screen"; import ProjectSettingsScreen from "@/screens/project-settings-screen"; -import { SETTINGS_DESKTOP_SIDEBAR_WIDTH, useIsCompactFormFactor } from "@/constants/layout"; +import { + SETTINGS_DESKTOP_DETAIL_MIN_WIDTH, + SETTINGS_DESKTOP_SIDEBAR_WIDTH, + useIsCompactFormFactor, +} from "@/constants/layout"; import { densityIconBox, densityIconSize } from "@/styles/density"; import { useLocalDaemonServerId } from "@/hooks/use-is-local-daemon"; import { @@ -1544,12 +1548,14 @@ const desktopStyles = StyleSheet.create({ }, contentPane: { flex: 1, + minWidth: SETTINGS_DESKTOP_DETAIL_MIN_WIDTH, }, }); const sidebarStyles = StyleSheet.create((theme) => ({ desktopContainer: { width: SETTINGS_DESKTOP_SIDEBAR_WIDTH, + flexShrink: 1, borderRightWidth: 1, borderRightColor: theme.colors.border, backgroundColor: theme.colors.surfaceSidebar, diff --git a/packages/app/src/screens/settings/daemon-lifecycle.test.ts b/packages/app/src/screens/settings/daemon-lifecycle.test.ts index c50006534a..d73222d9b9 100644 --- a/packages/app/src/screens/settings/daemon-lifecycle.test.ts +++ b/packages/app/src/screens/settings/daemon-lifecycle.test.ts @@ -12,6 +12,69 @@ test("settings restart completes when a replacement worker is observed without a expect(pid).toBe(11); }); +test("settings restart keeps terminals by default and closes them only when asked", async () => { + let pid = 10; + const requests: Array<{ killTerminals: boolean }> = []; + const deps = { + getStatus: async () => ({ pid, version: "1.0.0", serverId: "daemon" }), + restartServer: async (_reason: string, options: { killTerminals: boolean }) => { + requests.push(options); + pid += 1; + }, + }; + await restartDaemonFromSettings("daemon", "settings", deps); + await restartDaemonFromSettings("daemon", "settings", deps, { killTerminals: true }); + expect(requests).toEqual([{ killTerminals: false }, { killTerminals: true }]); +}); + +test("a close-terminals restart completes when the replacement reports every terminal closed", async () => { + let pid = 10; + await restartDaemonFromSettings( + "daemon", + "settings", + { + getStatus: async () => ({ + pid, + version: "1.0.0", + serverId: "daemon", + terminalCleanupUnconfirmed: [], + }), + restartServer: async () => { + pid = 11; + }, + }, + { killTerminals: true }, + ); + expect(pid).toBe(11); +}); + +test("a close-terminals restart fails with the processes the replacement could not confirm closed", async () => { + let pid = 10; + const leftover = { + pid: 4242, + role: "terminal program", + reason: "still alive", + detail: "survived SIGKILL", + }; + const deps = { + getStatus: async () => ({ + pid, + version: "1.0.0", + serverId: "daemon", + terminalCleanupUnconfirmed: pid === 10 ? [] : [leftover], + }), + restartServer: async () => { + pid += 1; + }, + }; + + await expect( + restartDaemonFromSettings("daemon", "settings", deps, { killTerminals: true }), + ).rejects.toThrow("pid 4242 (terminal program): still alive (survived SIGKILL)"); + // Keeping terminals asks nothing of the cleanup, so a leftover does not fail it. + await restartDaemonFromSettings("daemon", "settings", deps); +}); + test("a status permission failure prevents the restart request", async () => { let restarted = false; await expect( diff --git a/packages/app/src/screens/settings/daemon-lifecycle.ts b/packages/app/src/screens/settings/daemon-lifecycle.ts index c4e9d83f5a..e848d26af8 100644 --- a/packages/app/src/screens/settings/daemon-lifecycle.ts +++ b/packages/app/src/screens/settings/daemon-lifecycle.ts @@ -1,35 +1,61 @@ +interface UnconfirmedTerminalProcess { + pid: number; + role: string; + reason: string; + detail: string; +} interface WorkerStatus { pid: number; serverId: string; version: string | null; + // Absent on daemons without terminalsSurviveRestart, which have no terminal cleanup to report. + terminalCleanupUnconfirmed?: UnconfirmedTerminalProcess[]; } interface StatusReader { getStatus: () => Promise; } export interface SettingsDaemonRestartDeps extends StatusReader { - restartServer: (reason: string) => Promise; + restartServer: (reason: string, options: { killTerminals: boolean }) => Promise; } -/** Acknowledgment starts the wait; only a different ready worker completes it. */ +/** + * Acknowledgment starts the wait; only a different ready worker completes it. Terminals survive + * the restart unless `killTerminals` is set (daemons advertising terminalsSurviveRestart); then + * the replacement must also report every terminal process gone. + */ export async function restartDaemonFromSettings( hostServerId: string, reason: string, deps: SettingsDaemonRestartDeps, + options: { killTerminals: boolean } = { killTerminals: false }, ): Promise { const previous = await readSelectedWorker(hostServerId, deps); let acknowledged = false; try { - await deps.restartServer(reason); + await deps.restartServer(reason, options); acknowledged = true; } catch (error) { if (!isReconnectFailure(error)) throw error; } + let replacement: WorkerStatus; try { - await observeReplacement(previous, deps); + replacement = await observeReplacement(previous, deps); } catch (error) { throw new Error(`Restart acknowledged: ${acknowledged}. ${String(error)}`, { cause: error }); } + const unconfirmed = replacement.terminalCleanupUnconfirmed ?? []; + if (options.killTerminals && unconfirmed.length > 0) { + throw new Error( + [ + "The daemon restarted, but closing its terminals was not confirmed; these processes may still be running:", + ...unconfirmed.map( + (entry) => `pid ${entry.pid} (${entry.role}): ${entry.reason} (${entry.detail})`, + ), + "Stopping the daemon retries the cleanup.", + ].join("\n"), + ); + } } export async function updateDaemonFromSettings( diff --git a/packages/app/src/screens/settings/host-page.tsx b/packages/app/src/screens/settings/host-page.tsx index 0fb6fb5aa9..879ef2fe95 100644 --- a/packages/app/src/screens/settings/host-page.tsx +++ b/packages/app/src/screens/settings/host-page.tsx @@ -65,6 +65,7 @@ import { ICON_SIZE } from "@/styles/theme"; import type { Theme } from "@/styles/theme"; import { useProviderIcon } from "@/components/provider-icons"; import { BrowserToolsOptInCard } from "./browser-tools-card"; +import { RestartRecoveryCard } from "./restart-recovery-card"; import { IdleRuntimeCleanupCard } from "./idle-runtime-cleanup-card"; import { restartDaemonFromSettings, updateDaemonFromSettings } from "./daemon-lifecycle"; @@ -292,6 +293,7 @@ export function HostAgentsPage({ serverId }: { serverId: string }) { + ) : ( @@ -565,7 +567,15 @@ function RestartDaemonCard({ host }: { host: HostProfile }) { const isConnected = useHostRuntimeIsConnected(host.serverId); const runtime = getHostRuntimeStore(); const [isRestarting, setIsRestarting] = useState(false); + // Rendered in the card, not an Alert.alert: react-native-web's Alert is a no-op, and a failed + // close-terminals restart must name the processes left running until the user retries. + const [restartError, setRestartError] = useState(null); const isMountedRef = useRef(true); + // COMPAT(terminalsSurviveRestart): added in v0.12.0, remove gate after 2027-04-21. + const terminalsSurviveRestart = useSessionStore( + (state) => + state.sessions[host.serverId]?.serverInfo?.features?.terminalsSurviveRestart === true, + ); useEffect(() => { return () => { @@ -578,71 +588,80 @@ function RestartDaemonCard({ host }: { host: HostProfile }) { [host.serverId, runtime], ); - const waitForDaemonRestart = useCallback( - async (request: Promise) => { - try { - await request; - } catch (error) { - Alert.alert( - t("settings.host.daemon.restart.requestFailedTitle"), - error instanceof Error ? error.message : String(error), - ); - } finally { - if (isMountedRef.current) setIsRestarting(false); + const waitForDaemonRestart = useCallback(async (request: Promise) => { + try { + await request; + } catch (error) { + console.error("[HostPage] Daemon restart failed", error); + if (isMountedRef.current) { + setRestartError(error instanceof Error ? error.message : String(error)); } + } finally { + if (isMountedRef.current) setIsRestarting(false); + } + }, []); + + const startRestart = useCallback( + (killTerminals: boolean) => { + if (!daemonClient) { + Alert.alert( + t("settings.host.daemon.restart.unavailableTitle"), + t("settings.host.daemon.restart.unavailableMessage"), + ); + return; + } + if (!isHostConnected()) { + Alert.alert( + t("settings.host.daemon.restart.offlineTitle"), + t("settings.host.daemon.restart.offlineMessage"), + ); + return; + } + + void confirmDialog({ + title: t("settings.host.daemon.restart.confirmTitle", { name: host.label }), + message: killTerminals + ? t("settings.host.daemon.restart.closeTerminalsConfirmMessage") + : t("settings.host.daemon.restart.confirmMessage"), + confirmLabel: killTerminals + ? t("settings.host.daemon.restart.closeTerminals") + : t("settings.host.daemon.restart.confirm"), + cancelLabel: t("common.actions.cancel"), + destructive: true, + }) + .then((confirmed) => { + if (!confirmed) return; + setRestartError(null); + setIsRestarting(true); + const restartRequest = restartDaemonFromSettings( + host.serverId, + `settings_daemon_restart_${host.serverId}`, + { + restartServer: (reason, options) => + daemonClient.restartServer(reason, undefined, options), + getStatus: async () => ({ + ...(await daemonClient.getDaemonStatus()), + serverId: daemonClient.getLastServerInfoMessage()?.serverId ?? "", + version: daemonClient.getLastServerInfoMessage()?.version ?? null, + }), + }, + { killTerminals }, + ); + void waitForDaemonRestart(restartRequest); + return; + }) + .catch((error) => { + console.error(`[HostPage] Failed to open restart confirmation for ${host.label}`, error); + if (isMountedRef.current) { + setRestartError(t("settings.host.daemon.restart.dialogFailedMessage")); + } + }); }, - [t], + [daemonClient, host.label, host.serverId, isHostConnected, t, waitForDaemonRestart], ); - const handleRestart = useCallback(() => { - if (!daemonClient) { - Alert.alert( - t("settings.host.daemon.restart.unavailableTitle"), - t("settings.host.daemon.restart.unavailableMessage"), - ); - return; - } - if (!isHostConnected()) { - Alert.alert( - t("settings.host.daemon.restart.offlineTitle"), - t("settings.host.daemon.restart.offlineMessage"), - ); - return; - } - - void confirmDialog({ - title: t("settings.host.daemon.restart.confirmTitle", { name: host.label }), - message: t("settings.host.daemon.restart.confirmMessage"), - confirmLabel: t("settings.host.daemon.restart.confirm"), - cancelLabel: t("common.actions.cancel"), - destructive: true, - }) - .then((confirmed) => { - if (!confirmed) return; - setIsRestarting(true); - const restartRequest = restartDaemonFromSettings( - host.serverId, - `settings_daemon_restart_${host.serverId}`, - { - restartServer: (reason) => daemonClient.restartServer(reason), - getStatus: async () => ({ - ...(await daemonClient.getDaemonStatus()), - serverId: daemonClient.getLastServerInfoMessage()?.serverId ?? "", - version: daemonClient.getLastServerInfoMessage()?.version ?? null, - }), - }, - ); - void waitForDaemonRestart(restartRequest); - return; - }) - .catch((error) => { - console.error(`[HostPage] Failed to open restart confirmation for ${host.label}`, error); - Alert.alert( - t("settings.host.daemon.restart.requestFailedTitle"), - t("settings.host.daemon.restart.dialogFailedMessage"), - ); - }); - }, [daemonClient, host.label, host.serverId, isHostConnected, t, waitForDaemonRestart]); + const handleRestart = useCallback(() => startRestart(false), [startRestart]); + const handleRestartAndCloseTerminals = useCallback(() => startRestart(true), [startRestart]); return ( @@ -664,6 +683,35 @@ function RestartDaemonCard({ host }: { host: HostProfile }) { : t("settings.host.daemon.restart.confirm")} + {terminalsSurviveRestart ? ( + + + + {t("settings.host.daemon.restart.closeTerminalsHint")} + + + + + ) : null} + {restartError ? ( + + + + ) : null} ); } @@ -848,7 +896,7 @@ function UpdateDaemonCard({ host }: { host: HostProfile }) { /> ) : null} {updateState.status === "failed" ? ( - + ({ })); const styles = StyleSheet.create((theme) => ({ - updateFailure: { + cardAlert: { marginHorizontal: theme.spacing[4], marginBottom: theme.spacing[4], }, diff --git a/packages/app/src/screens/settings/restart-recovery-card.tsx b/packages/app/src/screens/settings/restart-recovery-card.tsx new file mode 100644 index 0000000000..9fa8a872b0 --- /dev/null +++ b/packages/app/src/screens/settings/restart-recovery-card.tsx @@ -0,0 +1,199 @@ +import { useCallback, useMemo, useState } from "react"; +import { Text, View } from "react-native"; +import { useMutation } from "@tanstack/react-query"; +import { useTranslation } from "react-i18next"; +import { StyleSheet } from "react-native-unistyles"; +import { AdaptiveModalSheet, type SheetHeader } from "@/components/adaptive-modal-sheet"; +import { SettingsTextAreaCard } from "@/components/settings-textarea"; +import { SettingsInfoTip } from "@/components/settings/headings/settings-info-tip"; +import { Button } from "@/components/ui/button"; +import { Switch } from "@/components/ui/switch"; +import { useDaemonConfig } from "@/hooks/use-daemon-config"; +import { useHostFeature } from "@/runtime/host-features"; +import { useHostRuntimeIsConnected } from "@/runtime/host-runtime"; +import { settingsStyles } from "@/styles/settings"; + +const DEFAULT_RESUME_PROMPT = "Resume working."; + +// COMPAT(restartRecovery): added in v0.14.0, remove gate after 2027-04-28. +export function RestartRecoveryCard({ serverId }: { serverId: string }) { + const { t } = useTranslation(); + const isConnected = useHostRuntimeIsConnected(serverId); + const isSupported = useHostFeature(serverId, "resumeOnStartupSetting"); + const { config, patchConfig } = useDaemonConfig(serverId); + const [isEditing, setIsEditing] = useState(false); + const mutation = useMutation({ + mutationFn: async (next: { resumeOnStartup?: boolean; resumePrompt?: string }) => { + const result = await patchConfig(next); + if (!result) { + throw new Error(t("workspace.terminal.hostDisconnected")); + } + return result; + }, + }); + + const handleValueChange = useCallback( + (next: boolean) => { + mutation.mutate({ resumeOnStartup: next }); + }, + [mutation], + ); + + const handleOpen = useCallback(() => { + mutation.reset(); + setIsEditing(true); + }, [mutation]); + + const handleClose = useCallback(() => { + if (mutation.isPending) return; + mutation.reset(); + setIsEditing(false); + }, [mutation]); + + const handleSave = useCallback( + (prompt: string) => { + mutation.mutate({ resumePrompt: prompt }, { onSuccess: () => setIsEditing(false) }); + }, + [mutation], + ); + + if (!isConnected || !isSupported || !config) return null; + + const isEnabled = config.resumeOnStartup !== false; + + return ( + <> + + + + + + {t("settings.host.agents.resumeOnStartup.title")} + + + + + {t("settings.host.agents.resumeOnStartup.hint")} + + {mutation.error && !isEditing ? ( + + {mutation.error.message} + + ) : null} + + + + + + + + + {isEditing ? ( + + ) : null} + + ); +} + +function ResumePromptSheet({ + initialPrompt, + isSaving, + error, + onSave, + onClose, +}: { + initialPrompt: string; + isSaving: boolean; + error: string | null; + onSave: (prompt: string) => void; + onClose: () => void; +}) { + const { t } = useTranslation(); + const [draft, setDraft] = useState(initialPrompt); + const header = useMemo( + () => ({ title: t("settings.host.agents.resumeOnStartup.prompt") }), + [t], + ); + const canSave = draft !== initialPrompt && draft.trim().length > 0 && !isSaving; + + const handleSave = useCallback(() => onSave(draft), [draft, onSave]); + + return ( + + + {error ? ( + + {error} + + ) : null} + + + + + + ); +} + +const styles = StyleSheet.create((theme) => ({ + titleRow: { + flexDirection: "row", + alignItems: "center", + gap: theme.spacing[2], + }, + trailing: { + flexDirection: "row", + alignItems: "center", + gap: theme.spacing[3], + }, + sheetActions: { + flexDirection: "row", + justifyContent: "flex-end", + gap: theme.spacing[2], + }, +})); diff --git a/packages/app/src/screens/workspace/sheet-pane/host.tsx b/packages/app/src/screens/workspace/sheet-pane/host.tsx new file mode 100644 index 0000000000..3f8e60783a --- /dev/null +++ b/packages/app/src/screens/workspace/sheet-pane/host.tsx @@ -0,0 +1,84 @@ +import React, { createContext, useCallback, useContext, type ReactNode } from "react"; +import invariant from "tiny-invariant"; +import { NavigationContext, NavigationRouteContext } from "expo-router/react-navigation"; +import { useAssistantFileLinkEnvironmentBridge } from "@/assistant-file-links"; +import { useComposerEditingEnvironmentBridge } from "@/composer/editing-session"; +import { RetainedPanelActivity, useRetainedPanelActive } from "@/components/retained-panel"; +import type { ContextBridge } from "@/components/ui/isolated-bottom-sheet-modal"; +import { useDiffDocumentWorkspaceCacheBridge } from "@/git/diff-document/workspace-cache"; +import { HostRouteProvider, useHostRouteServerId } from "@/navigation/host-route-context"; +import type { WorkspacePaneContentModel } from "@/screens/workspace/workspace-pane-content"; +import type { WorkspaceTabDescriptor } from "@/screens/workspace/workspace-tabs-types"; + +/** What a sheet pane needs from the workspace it shows a tab of. */ +export interface SheetPaneHost { + workspaceKey: string; + serverId: string; + workspaceId: string; + isWorkspaceFocused: boolean; + /** The pane content for a sheet's tab. Closing the tab from inside it runs `closeCurrentTab`. */ + buildContent: ( + tab: WorkspaceTabDescriptor, + closeCurrentTab: () => void, + ) => WorkspacePaneContentModel; +} + +const SheetPaneHostContext = createContext(null); + +/** `null` while there is no workspace to show sheets for. */ +export function SheetPaneHostProvider({ + value, + children, +}: { + value: SheetPaneHost | null; + children: ReactNode; +}) { + return {children}; +} + +/** The host of the workspace the caller is in, or null while there is none. */ +export function useSheetPaneHostIfAny(): SheetPaneHost | null { + return useContext(SheetPaneHostContext); +} + +export function useSheetPaneHost(): SheetPaneHost { + const host = useSheetPaneHostIfAny(); + invariant(host, "SheetPaneHostProvider is required"); + return host; +} + +/** + * Carries a sheet pane's environment across the portal into the app overlay host: the workspace + * host, and the environment of the built-in panels. Pane identity is supplied by the pane itself. + */ +export function useSheetPaneBridge(): ContextBridge { + const host = useSheetPaneHost(); + const editing = useComposerEditingEnvironmentBridge(); + const cache = useDiffDocumentWorkspaceCacheBridge(); + const files = useAssistantFileLinkEnvironmentBridge(); + const active = useRetainedPanelActive(); + const serverId = useHostRouteServerId(); + const navigation = useContext(NavigationContext); + const route = useContext(NavigationRouteContext); + return useCallback( + (children) => { + const content = editing(cache(files(children))); + return ( + + + + + {serverId ? ( + {content} + ) : ( + content + )} + + + + + ); + }, + [host, editing, cache, files, active, serverId, navigation, route], + ); +} diff --git a/packages/app/src/screens/workspace/sheet-pane/index.ts b/packages/app/src/screens/workspace/sheet-pane/index.ts new file mode 100644 index 0000000000..1e6f6d1c40 --- /dev/null +++ b/packages/app/src/screens/workspace/sheet-pane/index.ts @@ -0,0 +1,16 @@ +/** + * A workspace tab shown in a sheet. One pane — header, body, bottom inset, focus — behind every + * sheet container: the workspace's sheet tabs, and pages of a menu that shows a sheet in place. + * + * See docs/explorer-sidebar.md. + */ + +export { + SheetPaneHostProvider, + useSheetPaneBridge, + useSheetPaneHost, + useSheetPaneHostIfAny, + type SheetPaneHost, +} from "./host"; +export { SheetPane, useLeaveSheet, type SheetPaneProps } from "./sheet-pane"; +export { useSheetPanePage } from "./page"; diff --git a/packages/app/src/screens/workspace/sheet-pane/page.tsx b/packages/app/src/screens/workspace/sheet-pane/page.tsx new file mode 100644 index 0000000000..1b076510b9 --- /dev/null +++ b/packages/app/src/screens/workspace/sheet-pane/page.tsx @@ -0,0 +1,38 @@ +import { useCallback } from "react"; +import { useMenuContext, type MenuFillPageDefinition } from "@/components/ui/menu"; +import { usePaneContext } from "@/panels/pane-context"; +import type { SheetTab } from "@/stores/workspace-layout-store"; +import type { WorkspaceTabTarget } from "@/workspace-tabs/model"; +import { useSheetPaneBridge } from "./host"; +import { SheetPane } from "./sheet-pane"; + +/** + * Shows sheet tabs as pages of a menu opened from a pane, so a row's sheet replaces the list it + * was chosen from instead of stacking a second sheet over it. Back returns to the list; Close + * closes the menu, which uncovers the pane the menu was opened from. + */ +export function useSheetPanePage(): (sheet: SheetTab) => MenuFillPageDefinition { + const bridge = useSheetPaneBridge(); + const { target: opener } = usePaneContext(); + return useCallback( + (sheet) => ({ + id: sheet.tab.tabId, + fill: true, + content: bridge( + // Keyed like the detached container, so the panel's descriptor hook stays fixed per page. + , + ), + }), + [bridge, opener], + ); +} + +function MenuSheetPane({ sheet, opener }: { sheet: SheetTab; opener: WorkspaceTabTarget }) { + const { setOpen, goBack } = useMenuContext("MenuSheetPane"); + const close = useCallback(() => setOpen(false), [setOpen]); + return ; +} diff --git a/packages/app/src/screens/workspace/sheet-pane/sheet-pane.tsx b/packages/app/src/screens/workspace/sheet-pane/sheet-pane.tsx new file mode 100644 index 0000000000..7b93f84746 --- /dev/null +++ b/packages/app/src/screens/workspace/sheet-pane/sheet-pane.tsx @@ -0,0 +1,207 @@ +import { + createContext, + useCallback, + useContext, + useEffect, + useLayoutEffect, + useMemo, + type ComponentType, +} from "react"; +import { View } from "react-native"; +import { useTranslation } from "react-i18next"; +import { StyleSheet, withUnistyles } from "react-native-unistyles"; +import { Maximize2 } from "lucide-react-native"; +import { + SheetBottomInset, + SheetDragArea, + SheetHeaderIconButton, + SheetHeaderView, + type SheetHeader, +} from "@/components/adaptive-modal-sheet"; +import type { PanelIconProps } from "@/panels/panel-registry"; +import { getPanelRegistration } from "@/panels/panel-registry"; +import { getHostRuntimeStore } from "@/runtime/host-runtime"; +import { useSessionStore } from "@/stores/session-store"; +import type { WorkspaceTabDescriptor } from "@/screens/workspace/workspace-tabs-types"; +import { WorkspacePaneContent } from "@/screens/workspace/workspace-pane-content"; +import { useWorkspaceLayoutStore, type SheetTab } from "@/stores/workspace-layout-store"; +import { workspaceTabTargetsEqual } from "@/workspace-tabs/identity"; +import type { WorkspaceTabTarget } from "@/workspace-tabs/model"; +import { useSheetPaneHost } from "./host"; + +function PanelIcon({ + icon: Icon, + size, + color, +}: { icon: ComponentType } & PanelIconProps) { + return ; +} + +const ThemedPanelIcon = withUnistyles(PanelIcon, (theme) => ({ + color: theme.colors.foregroundMuted, +})); + +export interface SheetPaneProps { + sheet: SheetTab; + /** Closes the sheet, everything it was chosen from included. */ + onClose: () => void; + /** Steps back to the list the sheet was chosen from, when there is one. */ + onBack?: () => void; + /** The pane closing the sheet uncovers, when the container knows it. */ + opener?: WorkspaceTabTarget | null; + /** Only the top sheet's pane is focused; a covered one stays as live as the pane under it. */ + isTop: boolean; +} + +interface SheetPaneExit { + close: () => void; + opener: WorkspaceTabTarget | null; +} + +const SheetPaneExitContext = createContext(null); + +/** + * A tab shown in a sheet: its header (icon, title, Back, Open as tab, Close), which drags the + * sheet, over its pane. Every sheet container renders this; only the container differs. + */ +export function SheetPane({ sheet, onClose, onBack, opener = null, isTop }: SheetPaneProps) { + const { t } = useTranslation(); + const host = useSheetPaneHost(); + const { tab } = sheet; + const registration = getPanelRegistration(tab.target.kind); + if (!registration) { + throw new Error(`No panel registration for kind: ${tab.target.kind}`); + } + const descriptor = registration.useDescriptor(tab.target as never, { + serverId: host.serverId, + workspaceId: host.workspaceId, + tabId: tab.tabId, + }); + + const openTabInFront = useWorkspaceLayoutStore((state) => state.openTabInFront); + const { workspaceKey } = host; + const handleOpenAsTab = useCallback( + () => openTabInFront(workspaceKey, sheet), + [openTabInFront, sheet, workspaceKey], + ); + const header = useMemo( + () => ({ + title: descriptor.label, + leading: , + back: onBack ? { onPress: onBack } : undefined, + // The sheet is for looking; the full-screen glyph takes the tab out of the sheet and into + // the switcher, where it gets its composer back. + actions: sheet.policy.openAsTab ? ( + + ) : undefined, + }), + [descriptor.icon, descriptor.label, handleOpenAsTab, onBack, sheet.policy.openAsTab, t], + ); + + const tabDescriptor = useMemo( + () => ({ + key: tab.tabId, + tabId: tab.tabId, + kind: tab.target.kind, + target: tab.target, + state: tab.state, + }), + [tab], + ); + const { buildContent } = host; + const content = useMemo( + () => buildContent(tabDescriptor, onClose), + [buildContent, onClose, tabDescriptor], + ); + const exit = useMemo(() => ({ close: onClose, opener }), [onClose, opener]); + const isPaneFocused = isTop && host.isWorkspaceFocused; + useViewedSheetAgent({ + sourceId: `${workspaceKey}:sheet:${tab.tabId}`, + serverId: host.serverId, + agentId: isPaneFocused && tab.target.kind === "agent" ? tab.target.agentId : null, + }); + + return ( + + + {/* The body scrolls on its own, so the header is where the sheet drags from. */} + + + + + + + + + ); +} + +/** + * The agent of the sheet on top is viewed, alongside the pane under it: its timeline catches up + * and stays live. The workspace only publishes the agents of its panes. + */ +function useViewedSheetAgent({ + sourceId, + serverId, + agentId, +}: { + sourceId: string; + serverId: string; + agentId: string | null; +}) { + const viewedTimelineSync = useSessionStore( + (state) => state.sessions[serverId]?.viewedTimelineSync ?? null, + ); + useEffect(() => { + if (!agentId) return; + void getHostRuntimeStore() + .prepareAgentTimeline(serverId, agentId) + .catch(() => undefined); + }, [agentId, serverId]); + useLayoutEffect(() => { + if (!agentId || !viewedTimelineSync) return; + viewedTimelineSync.replaceVisibleAgentIds(sourceId, [agentId]); + return () => viewedTimelineSync.replaceVisibleAgentIds(sourceId, []); + }, [agentId, sourceId, viewedTimelineSync]); +} + +/** + * Leaves the sheet the calling pane is shown in, if any, on the way to `destination`. Answers + * whether closing the sheet already lands there, so the caller navigates only when it does not. + */ +export function useLeaveSheet(): (destination: WorkspaceTabTarget) => boolean { + const exit = useContext(SheetPaneExitContext); + return useCallback( + (destination) => { + if (!exit) return false; + exit.close(); + return exit.opener !== null && workspaceTabTargetsEqual(exit.opener, destination); + }, + [exit], + ); +} + +const styles = StyleSheet.create({ + pane: { + flex: 1, + minHeight: 0, + }, + body: { + flex: 1, + minHeight: 0, + }, +}); diff --git a/packages/app/src/screens/workspace/sheet-tabs.tsx b/packages/app/src/screens/workspace/sheet-tabs.tsx index e7c8005233..30bebaac66 100644 --- a/packages/app/src/screens/workspace/sheet-tabs.tsx +++ b/packages/app/src/screens/workspace/sheet-tabs.tsx @@ -1,131 +1,62 @@ -import type { BottomSheetHandleProps } from "@gorhom/bottom-sheet"; import { useIsFocused } from "expo-router/react-navigation"; +import { useCallback, useEffect, useRef } from "react"; import { - type ComponentType, - type FC, - useCallback, - useEffect, - useMemo, - useRef, - useState, -} from "react"; -import { View } from "react-native"; -import { useTranslation } from "react-i18next"; -import { useSafeAreaInsets } from "react-native-safe-area-context"; -import { StyleSheet, withUnistyles } from "react-native-unistyles"; -import { useStore } from "zustand"; -import { createStore } from "zustand/vanilla"; -import { Maximize2 } from "lucide-react-native"; -import { + FULL_SHEET_SNAP_POINTS, SheetBackground, SheetHandle, - SheetHeaderIconButton, - SheetHeaderView, - type SheetHeader, } from "@/components/adaptive-modal-sheet"; import { IsolatedBottomSheetModal, type IsolatedBottomSheetModalRef, systemBackPress, } from "@/components/ui/isolated-bottom-sheet-modal"; -import type { PanelIconProps } from "@/panels/panel-registry"; -import { getPanelRegistration } from "@/panels/panel-registry"; -import { ensurePanelsRegistered } from "@/panels/register-panels"; -import type { WorkspaceTabDescriptor } from "@/screens/workspace/workspace-tabs-types"; import { - WorkspacePaneContent, - type WorkspacePaneContentModel, -} from "@/screens/workspace/workspace-pane-content"; + SheetPane, + useSheetPaneBridge, + useSheetPaneHost, + useSheetPaneHostIfAny, +} from "@/screens/workspace/sheet-pane"; import { useWorkspaceLayoutStore, type SheetTab } from "@/stores/workspace-layout-store"; -import { useWorkspaceSheetEnvironment } from "./workspace-sheet-environment"; -const SNAP_POINTS = ["92%"]; const NO_SHEETS: readonly SheetTab[] = []; -function PanelIcon({ - icon: Icon, - size, - color, -}: { icon: ComponentType } & PanelIconProps) { - return ; -} - -const ThemedPanelIcon = withUnistyles(PanelIcon, (theme) => ({ - color: theme.colors.foregroundMuted, -})); - -interface SheetTabHandleValue { - header: SheetHeader; - onClose: () => void; -} - -/** - * The sheet's handle, showing its header. Gorhom takes `handleComponent` as a component type and - * renders it on the far side of the portal: a new function per render would remount the header on - * every change, and no context from here reaches it. So each sheet gets one handle component for - * its lifetime, which reads the header through a store the sheet keeps current. - */ -function useSheetTabHandle(value: SheetTabHandleValue): FC { - const [store] = useState(() => createStore(() => value)); - useEffect(() => store.setState(value, true), [store, value]); - const [Handle] = useState( - () => - function SheetTabHandle(props: BottomSheetHandleProps) { - const { header, onClose } = useStore(store); - return ( - - - - ); - }, - ); - return Handle; -} - export interface SheetTabsProps { - workspaceKey: string | null; - serverId: string; - workspaceId: string; - isWorkspaceFocused: boolean; - buildContent: (tab: WorkspaceTabDescriptor) => WorkspacePaneContentModel; /** The workspace's ordinary tab close, including its unsaved-changes guard. */ onCloseTab: (tabId: string) => Promise; } -interface SheetTabSheetProps extends Omit { +interface SheetTabSheetProps { sheet: SheetTab; - /** Only the top sheet's pane is focused and answers Android Back; the ones below wait their turn. */ + /** Only the top sheet answers Android Back; the ones below wait their turn. */ isTop: boolean; /** Runs the guarded close and resolves to whether the tab is still open. */ onClose: (tabId: string) => Promise; - onOpenAsTab: (tabId: string) => void; } /** * The workspace's sheet tabs, one sheet each, on the app-wide sheet stack. Their environment - * crosses into the app overlay host so compact sheets cover both sidebars, and a - * sheet opened from any other sheet (a subagent chosen from the subagents list, say) lands on top of - * it and uncovers it on close. The shared sheet parts (`SheetBackground`, `SheetHandle`, - * `SheetHeaderView`) keep them looking and dragging like every other sheet. + * crosses into the app overlay host so compact sheets cover both sidebars, and a sheet opened + * from another one lands on top of it and uncovers it on close. */ -export function SheetTabs({ workspaceKey, onCloseTab, ...rest }: SheetTabsProps) { - const sheets = useWorkspaceLayoutStore((state) => - workspaceKey ? (state.sheetsByWorkspace[workspaceKey] ?? NO_SHEETS) : NO_SHEETS, - ); - const openSheetAsTab = useWorkspaceLayoutStore((state) => state.openSheetAsTab); - const handleOpenAsTab = useCallback( - (tabId: string) => { - if (workspaceKey) openSheetAsTab(workspaceKey, tabId); - }, - [openSheetAsTab, workspaceKey], +export function SheetTabs({ onCloseTab }: SheetTabsProps) { + const host = useSheetPaneHostIfAny(); + return host ? ( + + ) : null; +} + +function WorkspaceSheetTabs({ + workspaceKey, + onCloseTab, +}: SheetTabsProps & { workspaceKey: string }) { + const sheets = useWorkspaceLayoutStore( + (state) => state.sheetsByWorkspace[workspaceKey] ?? NO_SHEETS, ); const handleClose = useCallback( async (tabId: string) => { await onCloseTab(tabId); // A declined unsaved-changes prompt leaves the tab in its sheet. - const open = workspaceKey - ? useWorkspaceLayoutStore.getState().sheetsByWorkspace[workspaceKey] - : undefined; + const open = useWorkspaceLayoutStore.getState().sheetsByWorkspace[workspaceKey]; return open?.some((sheet) => sheet.tab.tabId === tabId) ?? false; }, [onCloseTab, workspaceKey], @@ -136,42 +67,21 @@ export function SheetTabs({ workspaceKey, onCloseTab, ...rest }: SheetTabsProps) ))} ); } -function SheetTabSheet({ - sheet, - isTop, - serverId, - workspaceId, - isWorkspaceFocused, - buildContent, - onClose, - onOpenAsTab, -}: SheetTabSheetProps) { - const { t } = useTranslation(); +function SheetTabSheet({ sheet, isTop, onClose }: SheetTabSheetProps) { const { tab } = sheet; const sheetRef = useRef(null); const isScreenFocused = useIsFocused(); - const contextBridge = useWorkspaceSheetEnvironment(); - ensurePanelsRegistered(); - const registration = getPanelRegistration(tab.target.kind); - if (!registration) { - throw new Error(`No panel registration for kind: ${tab.target.kind}`); - } - const descriptor = registration.useDescriptor(tab.target as never, { - serverId, - workspaceId, - tabId: tab.tabId, - }); + const { isWorkspaceFocused } = useSheetPaneHost(); + const contextBridge = useSheetPaneBridge(); // The sheet lives as long as its store entry: it presents on mount, and unmounting takes it off // the stack, which uncovers the sheet below. Gorhom slides an unmounting sheet down and still @@ -209,105 +119,23 @@ function SheetTabSheet({ }); }, [close, ownsBackPress]); - const handleOpenAsTab = useCallback(() => onOpenAsTab(tab.tabId), [onOpenAsTab, tab.tabId]); - const header = useMemo( - () => ({ - title: descriptor.label, - leading: , - // The sheet is for looking; the full-screen glyph takes the tab out of the sheet and into - // the switcher, where it gets its composer back. - actions: sheet.policy.openAsTab ? ( - - ) : undefined, - }), - [descriptor.icon, descriptor.label, handleOpenAsTab, sheet.policy.openAsTab, t], - ); - const handleValue = useMemo( - () => ({ header, onClose: close }), - [close, header], - ); - // The header is the sheet's handle: the panel scrolls on its own, so dragging the content would - // fight it, and the header is where people reach to pull the sheet down. - const SheetTabHandle = useSheetTabHandle(handleValue); - return ( - {/* A covered sheet stays as live as the pane under it; only focus follows the top sheet. */} - + ); } - -function SheetTabBody({ - tab, - label, - isPaneFocused, - isWorkspaceFocused, - buildContent, -}: { - tab: SheetTab["tab"]; - label: string; - /** Only the top sheet's pane is focused; the ones below are covered. */ - isPaneFocused: boolean; - isWorkspaceFocused: boolean; - buildContent: (tab: WorkspaceTabDescriptor) => WorkspacePaneContentModel; -}) { - const tabDescriptor = useMemo( - () => ({ - key: tab.tabId, - tabId: tab.tabId, - kind: tab.target.kind, - target: tab.target, - state: tab.state, - }), - [tab], - ); - const content = useMemo(() => buildContent(tabDescriptor), [buildContent, tabDescriptor]); - // The sheet reaches the bottom of the screen, so it owns the system navigation inset. - const { bottom: bottomInset } = useSafeAreaInsets(); - const contentStyle = useMemo( - () => [styles.content, { paddingBottom: bottomInset }], - [bottomInset], - ); - - return ( - - - - ); -} - -const styles = StyleSheet.create({ - content: { - flex: 1, - minHeight: 0, - }, -}); diff --git a/packages/app/src/screens/workspace/visible-agent-ids.test.ts b/packages/app/src/screens/workspace/visible-agent-ids.test.ts index 1378d6cc20..37f470bb3f 100644 --- a/packages/app/src/screens/workspace/visible-agent-ids.test.ts +++ b/packages/app/src/screens/workspace/visible-agent-ids.test.ts @@ -111,28 +111,6 @@ test("pane retargeting replaces the viewed agent and duplicate panes collapse to }).toEqual({ duplicate: ["agent-a"], retargeted: ["agent-a", "agent-b"] }); }); -test("the agent shown in the workspace sheet is viewed alongside the pane under it", () => { - const layout: WorkspaceLayout = { - focusedPaneId: "main", - root: { kind: "pane", pane: { id: "main", tabIds: ["a"], focusedTabId: "a" } }, - }; - const tabs: WorkspaceTab[] = [ - { tabId: "a", target: { kind: "agent", agentId: "agent-a" }, createdAt: 1 }, - ]; - const sheetTab: WorkspaceTab = { - tabId: "sheet", - target: { kind: "agent", agentId: "agent-child" }, - createdAt: 2, - }; - - expect( - selectVisibleAgentIds({ layout, tabs, sheetTab, routeFocused: true, focusedPaneOnly: true }), - ).toEqual(["agent-a", "agent-child"]); - expect( - selectVisibleAgentIds({ layout, tabs, sheetTab, routeFocused: false, focusedPaneOnly: true }), - ).toEqual([]); -}); - test("single-pane tablet includes its visible Explorer agent without including other splits", () => { const layout: WorkspaceLayout = { focusedPaneId: "main", diff --git a/packages/app/src/screens/workspace/visible-agent-ids.ts b/packages/app/src/screens/workspace/visible-agent-ids.ts index 8643e84940..95a5ec84f8 100644 --- a/packages/app/src/screens/workspace/visible-agent-ids.ts +++ b/packages/app/src/screens/workspace/visible-agent-ids.ts @@ -6,8 +6,6 @@ import { deriveWorkspacePaneState } from "./workspace-pane-state"; export function selectVisibleAgentIds(input: { layout: WorkspaceLayout | null; tabs: WorkspaceTab[]; - /** The workspace sheet's tab, shown over the panes. */ - sheetTab?: WorkspaceTab | null; routeFocused: boolean; focusedPaneOnly: boolean; explorerPaneId?: string | null; @@ -29,7 +27,6 @@ export function selectVisibleAgentIds(input: { .target; return target ? [target] : []; }); - if (input.sheetTab) targets.push(input.sheetTab.target); return [ ...new Set(targets.flatMap((target) => (target.kind === "agent" ? [target.agentId] : []))), ].sort(); @@ -38,7 +35,6 @@ export function selectVisibleAgentIds(input: { export function useVisibleAgentIds(input: { layout: WorkspaceLayout | null; tabs: WorkspaceTab[]; - sheetTab: WorkspaceTab | null; routeFocused: boolean; focusedPaneOnly: boolean; explorerPaneId?: string | null; diff --git a/packages/app/src/screens/workspace/workspace-pane-content.test.tsx b/packages/app/src/screens/workspace/workspace-pane-content.test.tsx index 84ec2634b9..6726c4d686 100644 --- a/packages/app/src/screens/workspace/workspace-pane-content.test.tsx +++ b/packages/app/src/screens/workspace/workspace-pane-content.test.tsx @@ -11,18 +11,7 @@ import { } from "@/screens/workspace/workspace-pane-content"; import type { WorkspaceTabDescriptor } from "@/screens/workspace/workspace-tabs-types"; import { usePaneContext, usePaneFocus, type PaneContextValue } from "@/panels/pane-context"; - -vi.mock("@/panels/register-panels", () => ({ - ensurePanelsRegistered: vi.fn(), -})); - -vi.mock("@/panels/panel-registry", () => ({ - getPanelRegistration: () => ({ - kind: "agent", - component: ProbePanel, - useDescriptor: vi.fn(), - }), -})); +import { definePanel, registerPanel } from "@/panels/panel-registry"; interface ProbeSnapshot { paneContextValue: PaneContextValue; @@ -48,6 +37,18 @@ function ProbePanel() { return null; } +// The workspace screen registers the real panels; this probe stands in for each kind the tests open. +for (const kind of ["agent", "draft"] as const) { + registerPanel( + definePanel(kind, { + component: ProbePanel, + useDescriptor: () => { + throw new Error("The probe panel has no descriptor"); + }, + }), + ); +} + const agentTab: WorkspaceTabDescriptor = { key: "agent_agent-a", tabId: "agent_agent-a", diff --git a/packages/app/src/screens/workspace/workspace-pane-content.tsx b/packages/app/src/screens/workspace/workspace-pane-content.tsx index 21476a85a4..95368240e9 100644 --- a/packages/app/src/screens/workspace/workspace-pane-content.tsx +++ b/packages/app/src/screens/workspace/workspace-pane-content.tsx @@ -9,7 +9,6 @@ import { } from "@/panels/pane-context"; import { useStableEvent } from "@/hooks/use-stable-event"; import { getPanelRegistration } from "@/panels/panel-registry"; -import { ensurePanelsRegistered } from "@/panels/register-panels"; import type { WorkspaceTabDescriptor } from "@/screens/workspace/workspace-tabs-types"; import { RenderProfile } from "@/utils/render-profiler"; import type { WorkspaceFileOpenRequest } from "@/workspace/file-open"; @@ -56,7 +55,6 @@ export function buildWorkspacePaneContentModel({ onOpenWorkspaceFile, onOpenImportSheet, }: BuildWorkspacePaneContentModelInput): WorkspacePaneContentModel { - ensurePanelsRegistered(); const registration = getPanelRegistration(tab.kind); invariant(registration, `No panel registration for kind: ${tab.kind}`); return { diff --git a/packages/app/src/screens/workspace/workspace-screen.tsx b/packages/app/src/screens/workspace/workspace-screen.tsx index 3617c074e2..dd806e1fa1 100644 --- a/packages/app/src/screens/workspace/workspace-screen.tsx +++ b/packages/app/src/screens/workspace/workspace-screen.tsx @@ -1,3 +1,4 @@ +import { planTimelineTailFetch } from "@/timeline/timeline-sync-plan"; import { useHostFeature } from "@/runtime/host-features"; import { AssistantFileLinkResolverProvider, @@ -63,6 +64,7 @@ import { WorkspaceScriptsButton } from "@/screens/workspace/scripts"; import { ImportSessionSheet } from "@/components/import-session-sheet"; import { useNavigateToImportedAgent } from "@/hooks/use-import-session"; import { useToast } from "@/contexts/toast-context"; +import { useOpenOutsideWorkspaceFolder } from "@/workspace/open-in-file-manager/outside-folder"; import { getOrCreateClientId } from "@/utils/client-id"; import { selectIsAgentListOpen, usePanelStore } from "@/stores/panel-store"; import { toggleDesktopSidebarsWithCheckoutIntent } from "@/utils/desktop-sidebar-toggle"; @@ -125,7 +127,6 @@ import { useWorkspaceSetupStore, } from "@/stores/workspace-setup-store"; import { useWorkspace } from "@/stores/session-store-hooks"; -import { useWorkspaceTerminalSessionRetention } from "@/terminal/hooks/use-workspace-terminal-session-retention"; import type { CheckoutStatusPayload } from "@/git/use-status-query"; import { confirmDialog } from "@/utils/confirm-dialog"; import { useArchiveAgent } from "@/hooks/use-archive-agent"; @@ -178,6 +179,8 @@ import { type WorkspacePaneContentModel, } from "@/screens/workspace/workspace-pane-content"; import { useMountedTabSet } from "@/screens/workspace/use-mounted-tab-set"; +import { ensurePanelsRegistered } from "@/panels/register-panels"; +import { SheetPaneHostProvider, type SheetPaneHost } from "@/screens/workspace/sheet-pane"; import { SheetTabs } from "@/screens/workspace/sheet-tabs"; import type { PaneHost } from "@/panels/panel-manifest"; import { WorkspaceFocusProvider } from "@/workspace/focus"; @@ -419,6 +422,10 @@ export const WorkspaceScreen = memo(function WorkspaceScreen({ workspaceId, isRouteFocused, }: WorkspaceScreenProps) { + // Every reader of the panel registry renders inside the workspace screen, so it registers the + // panels before any of them renders. A reader importing the registration instead would import + // every panel, and the panels render readers. + ensurePanelsRegistered(); const navigationFocused = useIsFocused(); useEffect(() => { traceInstant("paseo.workspace.mount", { serverId, workspaceId }); @@ -762,13 +769,17 @@ function WorkspaceScreenGateFrame({ children }: { children: ReactNode }) { function WorkspaceContentProviders({ children, workspaceKey, + sheetPaneHost, }: { children: ReactNode; workspaceKey: string | null; + sheetPaneHost: SheetPaneHost | null; }) { return ( - {children} + + {children} + ); } @@ -869,13 +880,6 @@ function shouldShowWorkspaceScreenHeader(input: { return !input.isFocusModeEnabled || input.isMobile; } -function buildWorkspaceTerminalScopeKey(serverId: string, workspaceId: string): string | null { - if (!serverId || !workspaceId) { - return null; - } - return `${serverId}:${workspaceId}`; -} - /** * A pane the user acted inside owns the tab: it opens there, and an existing tab * moves there. No pane means the open has no opinion beyond the focused pane. @@ -1054,14 +1058,6 @@ function WorkspaceScreenContent({ const { handleRetryHost, handleManageHost, handleDismissMissingWorkspace } = useWorkspaceRouteActions(normalizedServerId); - const workspaceTerminalScopeKey = useMemo( - () => buildWorkspaceTerminalScopeKey(normalizedServerId, normalizedWorkspaceId), - [normalizedServerId, normalizedWorkspaceId], - ); - useWorkspaceTerminalSessionRetention({ - scopeKey: workspaceTerminalScopeKey, - }); - const client = useHostRuntimeClient(normalizedServerId); const isConnected = useHostRuntimeIsConnected(normalizedServerId); const supportsProvidersSnapshot = useSessionStore( @@ -1340,10 +1336,6 @@ function WorkspaceScreenContent({ const sheets = useWorkspaceLayoutStore((state) => persistenceKey ? (state.sheetsByWorkspace[persistenceKey] ?? NO_SHEETS) : NO_SHEETS, ); - // Only the top sheet is on screen. - const sheetTab = useWorkspaceLayoutStore((state) => - persistenceKey ? (state.sheetsByWorkspace[persistenceKey]?.at(-1)?.tab ?? null) : null, - ); const unpinWorkspaceAgent = useWorkspaceLayoutStore((state) => state.unpinAgent); const hideWorkspaceAgent = useWorkspaceLayoutStore((state) => state.hideAgent); const setWorkspaceTabState = useWorkspaceLayoutStore((state) => state.setTabState); @@ -1415,7 +1407,6 @@ function WorkspaceScreenContent({ const visibleAgentIds = useVisibleAgentIds({ layout: workspaceLayout, tabs: uiTabs, - sheetTab, routeFocused: isRouteFocused, focusedPaneOnly: syncFocusedPaneOnly, explorerPaneId: explorerSidebarPaneId, @@ -2179,8 +2170,7 @@ function WorkspaceScreenContent({ const sessionState = useSessionStore.getState().sessions[normalizedServerId]; const currentCursor = sessionState?.agentTimelineCursor.get(agentId); await getHostRuntimeStore().fetchAgentTimeline(normalizedServerId, agentId, { - direction: "tail", - projection: "projected", + ...planTimelineTailFetch(), ...(currentCursor ? { cursor: { epoch: currentCursor.epoch, seq: currentCursor.endSeq } } : {}), @@ -2915,6 +2905,8 @@ function WorkspaceScreenContent({ paneId?: string | null; focusPaneBeforeOpen?: boolean; host?: PaneHost; + /** Overrides the guarded tab close, for a host that closes the tab its own way. */ + onCloseCurrentTab?: () => void; }) => buildWorkspacePaneContentModel({ tab: input.tab, @@ -2964,9 +2956,11 @@ function WorkspaceScreenContent({ }); } : undefined, - onCloseCurrentTab: () => { - void handleCloseTabById(input.tab.tabId); - }, + onCloseCurrentTab: + input.onCloseCurrentTab ?? + (() => { + void handleCloseTabById(input.tab.tabId); + }), onRetargetCurrentTab: (target) => { if (!persistenceKey) { return; @@ -3041,16 +3035,36 @@ function WorkspaceScreenContent({ [buildPaneContentModel], ); const buildSheetPaneContentModel = useCallback( - function buildSheetPaneContentModel(tab: WorkspaceTabDescriptor) { + function buildSheetPaneContentModel(tab: WorkspaceTabDescriptor, closeCurrentTab: () => void) { return buildPaneContentModel({ tab, paneId: null, focusPaneBeforeOpen: false, host: "sheet", + onCloseCurrentTab: closeCurrentTab, }); }, [buildPaneContentModel], ); + const sheetPaneHost = useMemo( + () => + persistenceKey + ? { + workspaceKey: persistenceKey, + serverId: normalizedServerId, + workspaceId: normalizedWorkspaceId, + isWorkspaceFocused: isRouteFocused, + buildContent: buildSheetPaneContentModel, + } + : null, + [ + buildSheetPaneContentModel, + isRouteFocused, + normalizedServerId, + normalizedWorkspaceId, + persistenceKey, + ], + ); const handleFocusPane = useStableEvent(function handleFocusPane(paneId: string) { if (!persistenceKey || paneFocusSuppressedRef.current) { return; @@ -3539,14 +3553,7 @@ function WorkspaceScreenContent({ )} - + ) : ( @@ -3682,6 +3689,7 @@ function WorkspaceScreenContent({ view: "files", }); }); + const openMarkdownOutsideDirectory = useOpenOutsideWorkspaceFolder(normalizedServerId); const markdownPathOpener = useMemo( () => createInlinePathOpener({ @@ -3689,8 +3697,15 @@ function WorkspaceScreenContent({ client, openFile: openMarkdownFile, openDirectory: openMarkdownDirectory, + openOutsideDirectory: openMarkdownOutsideDirectory, }), - [workspaceDirectory, client, openMarkdownFile, openMarkdownDirectory], + [ + workspaceDirectory, + client, + openMarkdownFile, + openMarkdownDirectory, + openMarkdownOutsideDirectory, + ], ); useEffect(() => { if (!isRouteFocused) markdownPathOpener.cancel(); @@ -3758,7 +3773,11 @@ function WorkspaceScreenContent({ return gatedWorkspaceScreen; } return ( - + { - const content = editing(cache(files(children))); - return ( - - - - {serverId ? ( - {content} - ) : ( - content - )} - - - - ); - }, - [editing, cache, files, active, serverId, navigation, route], - ); -} diff --git a/packages/app/src/screens/workspace/workspace-tab-presentation.tsx b/packages/app/src/screens/workspace/workspace-tab-presentation.tsx index fb73376b8b..03f0254099 100644 --- a/packages/app/src/screens/workspace/workspace-tab-presentation.tsx +++ b/packages/app/src/screens/workspace/workspace-tab-presentation.tsx @@ -6,7 +6,6 @@ import { Check } from "lucide-react-native"; import { StyleSheet, withUnistyles } from "react-native-unistyles"; import { useTranslation } from "react-i18next"; import invariant from "tiny-invariant"; -import { ensurePanelsRegistered } from "@/panels/register-panels"; import { getPanelRegistration, type PanelIconProps } from "@/panels/panel-registry"; import type { WorkspaceTabDescriptor } from "@/screens/workspace/workspace-tabs-types"; import type { SidebarStateBucket } from "@/utils/sidebar-agent-state"; @@ -43,7 +42,6 @@ export function WorkspaceTabPresentationResolver({ workspaceId, children, }: WorkspaceTabPresentationResolverProps): ReactElement { - ensurePanelsRegistered(); const registration = getPanelRegistration(tab.kind); invariant(registration, `No panel registration for kind: ${tab.kind}`); diff --git a/packages/app/src/stores/workspace-layout-store.test.ts b/packages/app/src/stores/workspace-layout-store.test.ts index 431d550823..8b478b7d27 100644 --- a/packages/app/src/stores/workspace-layout-store.test.ts +++ b/packages/app/src/stores/workspace-layout-store.test.ts @@ -41,6 +41,7 @@ import { normalizeLayout, removePaneFromTree, removeTabFromTree, + selectSheetTab, stripEphemeralTabsFromLayout, type SplitNode, type SplitPane, @@ -173,7 +174,6 @@ it("feeds restored layout to timeline sync as a release signal, not a subscripti fetchLatestTail: async () => ({ hasNewer: false, endCursor: null }), onCatchUpEnded: () => undefined, reportError: () => undefined, - schedule: () => () => undefined, }); // The edge session-context.tsx owns. Pointing it at subscription instead would resume every // agent behind a restored tab on the daemon. @@ -4496,6 +4496,12 @@ describe("compact workspace sheet", () => { return store.getState().sheetsByWorkspace[workspaceKey]?.at(-1); } + function requireTopSheet(store: ReturnType) { + const sheet = topSheet(store); + if (!sheet) throw new Error("Expected a sheet"); + return sheet; + } + function sheetTargets(store: ReturnType) { return (store.getState().sheetsByWorkspace[workspaceKey] ?? []).map( (sheet) => sheet.tab.target, @@ -4647,7 +4653,7 @@ describe("compact workspace sheet", () => { .getState() .openTab({ workspaceKey, target: { kind: "file", path: "src/other.ts" }, intent: "reveal" }); - store.getState().openSheetAsTab(workspaceKey, nextTabId ?? ""); + store.getState().openTabInFront(workspaceKey, requireTopSheet(store)); expect(sheetTargets(store)).toEqual([]); expect(tabKinds(store)).toEqual(["terminal", "file"]); @@ -4683,7 +4689,7 @@ describe("compact workspace sheet", () => { if (!sheetTabId) throw new Error("Expected a sheet tab"); store.getState().setTabState(workspaceKey, sheetTabId, { scrollTop: 120 }); - const tabId = store.getState().openSheetAsTab(workspaceKey, sheetTabId); + const tabId = store.getState().openTabInFront(workspaceKey, requireTopSheet(store)); expect(tabId).toBe(sheetTabId); expect(topSheet(store)).toBeUndefined(); @@ -4787,6 +4793,40 @@ describe("compact workspace sheet", () => { expect(tabKinds(store)).toEqual(["terminal", "agent", "agent"]); }); + it("describes the sheet a reveal would show without opening it, and opens it as a tab", () => { + seedAgents([ + { id: "root", parentAgentId: null, workspaceId: "sheet-ws" }, + { id: "child", parentAgentId: "root", workspaceId: "sheet-ws" }, + ]); + const store = createCompactStore(); + const rootTabId = store + .getState() + .openTab({ workspaceKey, target: { kind: "agent", agentId: "root" }, intent: "reveal" }); + + const sheet = selectSheetTab(store.getState(), { + workspaceKey, + target: { kind: "agent", agentId: "child" }, + parentTabId: rootTabId ?? undefined, + }); + expect(sheet?.parentTabId).toBe(rootTabId); + expect( + selectSheetTab(store.getState(), { + workspaceKey, + target: { kind: "agent", agentId: "root" }, + }), + ).toBeNull(); + expect(topSheet(store)).toBeUndefined(); + if (!sheet) throw new Error("Expected a sheet tab"); + + const tabId = store.getState().openTabInFront(workspaceKey, sheet); + + expect(tabId).toBe(sheet.tab.tabId); + expect(topSheet(store)).toBeUndefined(); + const layout = store.getState().layoutByWorkspace[workspaceKey]; + expect(findPaneById(layout.root, "main")?.focusedTabId).toBe(tabId); + expect(layout.parentTabIdByTabId?.[tabId ?? ""]).toBe(rootTabId); + }); + it("gives a sheet target opened from inside the sheet the sheet's own parent", () => { seedAgents([ { id: "root", parentAgentId: null, workspaceId: "sheet-ws" }, @@ -4811,7 +4851,7 @@ describe("compact workspace sheet", () => { }); expect(topSheet(store)?.parentTabId).toBe(rootTabId); - store.getState().openSheetAsTab(workspaceKey, fileSheetTabId ?? ""); + store.getState().openTabInFront(workspaceKey, requireTopSheet(store)); const layout = store.getState().layoutByWorkspace[workspaceKey]; expect(layout.parentTabIdByTabId?.[fileSheetTabId ?? ""]).toBe(rootTabId); }); diff --git a/packages/app/src/stores/workspace-layout-store.ts b/packages/app/src/stores/workspace-layout-store.ts index 1c0b7a5037..43387bc743 100644 --- a/packages/app/src/stores/workspace-layout-store.ts +++ b/packages/app/src/stores/workspace-layout-store.ts @@ -156,13 +156,12 @@ interface WorkspaceLayoutStore { * `compactSheet` opens in a sheet; the returned tab id is the sheet tab's id. */ openTab: (input: OpenWorkspaceTabInput) => string | null; - /** Whether `openTab` with this input would show the target in a sheet. */ - opensInSheet: ( - input: Pick, - ) => boolean; setLayoutMode: (mode: WorkspaceLayoutMode) => void; - /** Moves a sheet's tab, keeping its tab id, into the focused pane. */ - openSheetAsTab: (workspaceKey: string, tabId: string) => string | null; + /** + * Moves a sheet's tab, keeping its tab id, into the focused pane and dismisses the sheets that + * would cover it. The sheet need not be one of the workspace's sheet tabs. + */ + openTabInFront: (workspaceKey: string, sheet: SheetTab) => string | null; /** Placement resolves lazily so an already acknowledged workspace never creates a side pane. */ autoOpenPullRequestTab: ( workspaceKey: string, @@ -521,6 +520,29 @@ export function selectExplorerSidebarPaneId( return resolveExplorerSidebarPaneId(layout, state.explorerSidebarPaneIdByWorkspace[workspaceKey]); } +/** + * The sheet tab a reveal of this target would show, or null when it opens as a tab. A caller + * that hosts the sheet itself (a list showing it in place) renders this without opening it. + */ +export function selectSheetTab( + state: Pick, + input: Pick, +): SheetTab | null { + const workspaceKey = trimNonEmpty(input.workspaceKey); + const target = normalizeWorkspaceTabTarget(input.target); + if (!workspaceKey || !target) return null; + const policy = resolveSheetPolicy(state, workspaceKey, target, "reveal"); + if (!policy) return null; + return placeTargetInSheet({ + kept: undefined, + target, + intent: "reveal", + policy, + parentTabId: resolveOpenParentTabId(state, workspaceKey, input.parentTabId), + state: undefined, + }); +} + /** A workspace's panes give up keyboard focus while focus is parked or the sheet covers them. */ export function selectPaneFocusSuspended( state: Pick, @@ -822,10 +844,8 @@ function placeTargetInSheet(input: { function promoteSheetToTab( state: WorkspaceLayoutStore, workspaceKey: string, - tabId: string, + sheet: SheetTab, ): { tabId: string; patch: Partial } | null { - const sheet = findSheet(state, workspaceKey, tabId); - if (!sheet) return null; const { tab } = sheet; const placement = getOpenTabPlacement(state, workspaceKey, tab.target, FOCUSED_PANE_PLACEMENT); const input = { @@ -910,9 +930,9 @@ function dismissSheets( function openSheetTabInFront( state: WorkspaceLayoutStore, workspaceKey: string, - tabId: string, + sheet: SheetTab, ): { tabId: string; patch: Partial } | null { - const promoted = promoteSheetToTab(state, workspaceKey, tabId); + const promoted = promoteSheetToTab(state, workspaceKey, sheet); if (!promoted) return null; const next = { ...state, ...promoted.patch }; return { @@ -1208,15 +1228,6 @@ export function createWorkspaceLayoutStore( })); return result.tabId; }, - opensInSheet: (input) => { - const normalizedWorkspaceKey = trimNonEmpty(input.workspaceKey); - const normalizedTarget = normalizeWorkspaceTabTarget(input.target); - if (!normalizedWorkspaceKey || !normalizedTarget) return false; - return ( - resolveSheetPlacement(get(), normalizedWorkspaceKey, normalizedTarget, input.intent) !== - null - ); - }, setLayoutMode: (mode) => { set((state) => { if (state.layoutMode === mode) return state; @@ -1225,7 +1236,7 @@ export function createWorkspaceLayoutStore( const next: WorkspaceLayoutStore = { ...state, layoutMode: mode }; for (const [workspaceKey, sheets] of Object.entries(state.sheetsByWorkspace)) { for (const sheet of sheets) { - const promoted = promoteSheetToTab(next, workspaceKey, sheet.tab.tabId); + const promoted = promoteSheetToTab(next, workspaceKey, sheet); Object.assign( next, promoted?.patch ?? withoutSheet(next, workspaceKey, sheet.tab.tabId), @@ -1235,11 +1246,10 @@ export function createWorkspaceLayoutStore( return next; }); }, - openSheetAsTab: (workspaceKey, tabId) => { + openTabInFront: (workspaceKey, sheet) => { const normalizedWorkspaceKey = trimNonEmpty(workspaceKey); - const normalizedTabId = trimNonEmpty(tabId); - if (!normalizedWorkspaceKey || !normalizedTabId) return null; - const promoted = openSheetTabInFront(get(), normalizedWorkspaceKey, normalizedTabId); + if (!normalizedWorkspaceKey) return null; + const promoted = openSheetTabInFront(get(), normalizedWorkspaceKey, sheet); if (!promoted) return null; set(promoted.patch); return promoted.tabId; @@ -1569,7 +1579,10 @@ export function createWorkspaceLayoutStore( return normalizedTabId; } // A target sheets do not host becomes the tab it would have opened as. - const promoted = openSheetTabInFront(next, normalizedWorkspaceKey, normalizedTabId); + const retargeted = findSheet(next, normalizedWorkspaceKey, normalizedTabId); + const promoted = retargeted + ? openSheetTabInFront(next, normalizedWorkspaceKey, retargeted) + : null; set(promoted?.patch ?? withoutSheet(next, normalizedWorkspaceKey, normalizedTabId)); return promoted?.tabId ?? null; } diff --git a/packages/app/src/styles/unistyles.ts b/packages/app/src/styles/unistyles.ts index 407faafdf6..96510c59f2 100644 --- a/packages/app/src/styles/unistyles.ts +++ b/packages/app/src/styles/unistyles.ts @@ -6,8 +6,7 @@ StyleSheet.configure({ breakpoints: { xs: 0, sm: 576, - medium: 600, - md: 720, + md: 600, lg: 992, xl: 1200, }, @@ -22,7 +21,6 @@ type AppThemes = typeof REGISTERED_THEMES; interface AppBreakpoints { xs: number; sm: number; - medium: number; md: number; lg: number; xl: number; diff --git a/packages/app/src/subagents/index.ts b/packages/app/src/subagents/index.ts index 6c539931e1..0b72ccfcf5 100644 --- a/packages/app/src/subagents/index.ts +++ b/packages/app/src/subagents/index.ts @@ -9,4 +9,4 @@ export { type ArchiveFinishedStatus, type UseArchiveFinishedSubagentsInput, } from "./use-archive-finished"; -export { useSubagentOpensInSheet } from "./opens-in-sheet"; +export { useSubagentSheetTab } from "./sheet-tab"; diff --git a/packages/app/src/subagents/opens-in-sheet.ts b/packages/app/src/subagents/opens-in-sheet.ts deleted file mode 100644 index 26432ea039..0000000000 --- a/packages/app/src/subagents/opens-in-sheet.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { useWorkspaceLayoutStore } from "@/stores/workspace-layout-store"; -import type { WorkspaceTabTarget } from "@/workspace-tabs/model"; -import type { SubagentRow } from "./select"; - -/** The workspace target a subagent row opens. */ -export function subagentRowTarget(row: SubagentRow): WorkspaceTabTarget { - return row.kind === "provider" - ? { kind: "provider_subagent", parentAgentId: row.parentAgentId, subagentId: row.id } - : { kind: "agent", agentId: row.id }; -} - -/** Answers, per subagent row, whether opening it in this workspace shows a sheet rather than a tab. */ -export function useSubagentOpensInSheet( - workspaceKey: string | null, -): (row: SubagentRow) => boolean { - // The rows render the answer, so this subscribes to what the answer reads: the layout mode and - // the workspace's tabs. A subagent already open as a tab reveals that tab instead of a sheet, - // and a row rendered while that tab existed must re-render once it closes, or choosing the row - // would still close the list it sits in. - useWorkspaceLayoutStore((state) => state.layoutMode); - useWorkspaceLayoutStore((state) => - workspaceKey ? state.layoutByWorkspace[workspaceKey] : undefined, - ); - return (row) => - workspaceKey !== null && - useWorkspaceLayoutStore - .getState() - .opensInSheet({ workspaceKey, target: subagentRowTarget(row), intent: "reveal" }); -} diff --git a/packages/app/src/subagents/parent/callout.tsx b/packages/app/src/subagents/parent/callout.tsx index f76e1267e3..7665c0d12a 100644 --- a/packages/app/src/subagents/parent/callout.tsx +++ b/packages/app/src/subagents/parent/callout.tsx @@ -3,8 +3,8 @@ import { Text, View } from "react-native"; import { useTranslation } from "react-i18next"; import { CornerUpLeft } from "lucide-react-native"; import { StyleSheet, withUnistyles } from "react-native-unistyles"; +import { StatusIcon } from "@/components/status-icon"; import { Button } from "@/components/ui/button"; -import { ComposerTrackMark } from "@/composer/tracks"; import { FOOTER_HEIGHT } from "@/constants/layout"; import type { Theme } from "@/styles/theme"; import { useParentAgent, type ParentAgent } from "./use-parent-agent"; @@ -22,6 +22,7 @@ function ParentIcon({ } const ThemedParentIcon = withUnistyles(ParentIcon); +const ICON_SIZE = 16; const foregroundColorMapping = (theme: Theme) => ({ color: theme.colors.foreground }); /** Stands in the composer's place on a subagent shown without one: who the parent is, and the way back. */ @@ -38,18 +39,12 @@ export function ParentAgentCallout({ return ( - - - - - {t("subagents.parent.parent")} - - - {parent.label ?? t("subagents.parent.parentAgent")} - - - - + + + + + {parent.label ?? t("subagents.parent.parentAgent")} + + + ); if (view.kind === "unavailable") { return ; } diff --git a/packages/app/src/usage/window-bar.tsx b/packages/app/src/usage/window-bar.tsx index 99c1eb9f21..b837872e01 100644 --- a/packages/app/src/usage/window-bar.tsx +++ b/packages/app/src/usage/window-bar.tsx @@ -1,29 +1,24 @@ import { Pin } from "lucide-react-native"; import { useMemo } from "react"; import { useTranslation } from "react-i18next"; -import { Pressable, Text, View, type StyleProp, type ViewStyle } from "react-native"; +import { Pressable, Text, View } from "react-native"; import { StyleSheet, withUnistyles } from "react-native-unistyles"; import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"; import { formatDisplayPct, formatProviderUsageLabel, formatResetLabel, + formatResetTime, formatRunsOutLabel, } from "./format"; import { UsageMeter } from "./meter"; import { displayPercent, usageWindowRowLabel } from "./model"; +import { UsageResetLine } from "./reset-line"; import type { UsageDisplayAs } from "./preferences"; import { windowTone } from "./tone"; import type { UsageTone, UsageWindow } from "./types"; import { useRelativeTimeTick } from "./use-relative-time-tick"; -// Pinned rows carry the pinned surface; hovering an unpinned row previews it at half strength, -// so a hover never reads as the selection. Pinned rows do not react to hover. -function highlightStyle(pinned: boolean, hovered: boolean) { - if (pinned) return styles.highlightPinned; - return hovered ? styles.highlightHovered : styles.highlightNone; -} - export function UsageWindowBar({ window, displayAs, @@ -54,9 +49,12 @@ export function UsageWindowBar({ window.runsOutAt != null && window.shortfallPct != null && (!retained || Date.parse(window.runsOutAt) > now); - const trailing = isAtRisk + const countdown = isAtRisk ? formatRunsOutLabel(window.runsOutAt, now, t) : formatResetLabel(window.resetsAt, retained, now, t); + // The exact time belongs to the reset; beside a runs-out warning it would read as the moment + // the quota runs out. + const exactTime = isAtRisk ? null : formatResetTime(window.resetsAt, now, t); const value = shownPct != null ? formatDisplayPct(shownPct, displayAs, i18n.resolvedLanguage, t) : "—"; @@ -64,60 +62,57 @@ export function UsageWindowBar({ const content = { label: formatProviderUsageLabel(window.id, window.label, t), value, - trailing, + countdown, + exactTime, isAtRisk, percent: shownPct ?? 0, tone, pinned, }; - // Same padding as the pinnable row, so bars line up in both modes. if (!pinnable) { return ( - + ); } - // The whole row pins the window to the sidebar Usage item. Pinned or not, it keeps the same - // padding so toggling only changes the background. + // The whole row pins the window to the sidebar Usage item; the pin glyph is the only sign of it. return ( - {({ hovered }: { hovered?: boolean }) => ( - - )} + ); } function WindowRowContent({ - highlight, label, value, - trailing, + countdown, + exactTime, isAtRisk, percent, tone, pinnable, pinned, }: { - highlight: StyleProp; label: string; value: string; - trailing: string | null | undefined; + countdown: string | null; + exactTime: string | null; isAtRisk: boolean; percent: number; tone: UsageTone; @@ -126,24 +121,17 @@ function WindowRowContent({ }) { return ( <> - - - - - - {label} - - - {value} - {trailing ? ( - {` · ${trailing}`} - ) : null} - - - - + + + {label} + + + {value} + {pinnable ? : null} + + ); } @@ -153,9 +141,9 @@ const ThemedPin = withUnistyles(Pin); function UsagePinGlyph({ pinned }: { pinned: boolean }) { const { t } = useTranslation(); const iconMapping = useMemo( - () => (theme: { colors: { foregroundMuted: string } }) => ({ - color: theme.colors.foregroundMuted, - fill: pinned ? theme.colors.foregroundMuted : "none", + () => (theme: { colors: { foreground: string; foregroundMuted: string } }) => ({ + color: pinned ? theme.colors.foreground : theme.colors.foregroundMuted, + fill: pinned ? theme.colors.foreground : "none", }), [pinned], ); @@ -179,59 +167,23 @@ function UsagePinGlyph({ pinned }: { pinned: boolean }) { } const styles = StyleSheet.create((theme) => ({ - contentRow: { flexDirection: "row", alignItems: "center", gap: theme.spacing[2] }, - windowContent: { flex: 1, gap: 3 }, + row: { gap: 3, paddingVertical: theme.spacing[1.5] }, pin: { width: 12, alignItems: "center" }, tooltipText: { color: theme.colors.popoverForeground, fontSize: theme.fontSize.sm }, - row: { - gap: 3, - // The highlight bleeds into the card padding so the label and bar stay on the card's rail. - marginHorizontal: -theme.spacing[2], - paddingHorizontal: theme.spacing[2], - paddingVertical: theme.spacing[1.5], - // Its own stacking context, so the highlight layer paints above the card and below the text. - zIndex: 0, - }, - highlightNone: { - display: "none", - }, - highlightPinned: { - ...StyleSheet.absoluteFill, - zIndex: -1, - borderRadius: theme.borderRadius.md, - backgroundColor: theme.colors.surface2, - }, - // The pinned surface at half strength: a separate layer, so the text keeps full opacity. - highlightHovered: { - ...StyleSheet.absoluteFill, - zIndex: -1, - borderRadius: theme.borderRadius.md, - backgroundColor: theme.colors.surface2, - opacity: theme.opacity[50], - }, labelRow: { flexDirection: "row", - justifyContent: "space-between", alignItems: "center", gap: theme.spacing[2], }, label: { flex: 1, - color: theme.colors.foregroundMuted, - fontSize: theme.fontSize.sm, - }, - value: { - flexShrink: 1, color: theme.colors.foreground, fontSize: theme.fontSize.sm, fontWeight: theme.fontWeight.medium, }, - reset: { - color: theme.colors.foregroundMuted, - fontWeight: theme.fontWeight.normal, - }, - atRisk: { - color: theme.colors.statusDanger, - fontWeight: theme.fontWeight.normal, + value: { + flexShrink: 0, + color: theme.colors.foreground, + fontSize: theme.fontSize.sm, }, })); diff --git a/packages/app/src/utils/terminal-renderer-readiness.test.ts b/packages/app/src/utils/terminal-renderer-readiness.test.ts index 45866f8df6..d7e5f71833 100644 --- a/packages/app/src/utils/terminal-renderer-readiness.test.ts +++ b/packages/app/src/utils/terminal-renderer-readiness.test.ts @@ -3,7 +3,6 @@ import { describe, expect, it } from "vitest"; import { applyTerminalRendererReadyChange, resolveTerminalStreamTarget, - shouldReplayTerminalSnapshotForRenderer, shouldShowTerminalLoadingOverlay, } from "./terminal-renderer-readiness"; @@ -74,27 +73,6 @@ describe("terminal-renderer-readiness", () => { expect(current).toBeNull(); }); - it("replays snapshots only for ready events from the current renderer", () => { - expect( - shouldReplayTerminalSnapshotForRenderer({ - change: { streamKey: "scope:terminal-1", isReady: true }, - terminalStreamKey: "scope:terminal-1", - }), - ).toBe(true); - expect( - shouldReplayTerminalSnapshotForRenderer({ - change: { streamKey: "scope:terminal-1", isReady: false }, - terminalStreamKey: "scope:terminal-1", - }), - ).toBe(false); - expect( - shouldReplayTerminalSnapshotForRenderer({ - change: { streamKey: "scope:terminal-1", isReady: true }, - terminalStreamKey: "scope:terminal-2", - }), - ).toBe(false); - }); - it("does not attach the stream before the matching renderer is ready", () => { expect( resolveTerminalStreamTarget({ diff --git a/packages/app/src/utils/terminal-renderer-readiness.ts b/packages/app/src/utils/terminal-renderer-readiness.ts index 7d4f855aba..197a8811f9 100644 --- a/packages/app/src/utils/terminal-renderer-readiness.ts +++ b/packages/app/src/utils/terminal-renderer-readiness.ts @@ -14,13 +14,6 @@ export function applyTerminalRendererReadyChange( return currentReadyStreamKey === change.streamKey ? null : currentReadyStreamKey; } -export function shouldReplayTerminalSnapshotForRenderer(input: { - change: TerminalRendererReadyChange; - terminalStreamKey: string; -}): boolean { - return input.change.isReady && input.change.streamKey === input.terminalStreamKey; -} - export function resolveTerminalStreamTarget(input: { terminalId: string; terminalStreamKey: string; diff --git a/packages/app/src/utils/test-daemon-connection.test.ts b/packages/app/src/utils/test-daemon-connection.test.ts index 4dc82dda29..29382b5c89 100644 --- a/packages/app/src/utils/test-daemon-connection.test.ts +++ b/packages/app/src/utils/test-daemon-connection.test.ts @@ -76,6 +76,25 @@ describe("test-daemon-connection connectToDaemon", () => { probe = new FakeDaemonProbe(); }); + it.each([ + { id: "direct:lan:6767", type: "directTcp" as const, endpoint: "lan:6767" }, + { + id: "relay:test", + type: "relay" as const, + relayEndpoint: "relay.paseo.sh:443", + daemonPublicKeyB64: "pubkey", + }, + ])("adoptable $type probe clients use the app WebSocket factory", async (connection) => { + const { connectToDaemon } = await import("./test-daemon-connection"); + const { createAppWebSocketFactory } = await import("@/runtime/websocket-factory"); + const result = await connectToDaemon(connection, { serverId: "srv_probe_test" }, probe.deps); + try { + expect(result.client.config.webSocketFactory).toBe(createAppWebSocketFactory()); + } finally { + await result.client.close(); + } + }); + it("reuses the app clientId for direct connections", async () => { const { connectToDaemon } = await import("./test-daemon-connection"); const first = await connectToDaemon( @@ -129,6 +148,23 @@ describe("test-daemon-connection connectToDaemon", () => { expect(probe.createdConfigs()[0]?.transportFactory).toBeUndefined(); }); + it("keeps the bundle cache factory on a probe client that the host runtime can adopt", async () => { + const { connectToDaemon } = await import("./test-daemon-connection"); + const createPluginClientBundleStore = () => ({ + async load() { + return []; + }, + async replace() {}, + }); + const { client } = await connectToDaemon( + { id: "direct:lan:6767", type: "directTcp", endpoint: "lan:6767" }, + { createPluginClientBundleStore }, + probe.deps, + ); + expect(client.config.createPluginClientBundleStore).toBe(createPluginClientBundleStore); + await client.close(); + }); + it("encodes the local socket target into the client config", async () => { const { connectToDaemon } = await import("./test-daemon-connection"); const result = await connectToDaemon( diff --git a/packages/app/src/utils/test-daemon-connection.ts b/packages/app/src/utils/test-daemon-connection.ts index 18ffa62dc4..1d1605af62 100644 --- a/packages/app/src/utils/test-daemon-connection.ts +++ b/packages/app/src/utils/test-daemon-connection.ts @@ -6,6 +6,7 @@ import { } from "@getpaseo/client/internal/daemon-client"; import type { DaemonClientConfig } from "@getpaseo/client/internal/daemon-client"; import type { HostConnection } from "@/types/host-connection"; +import { createAppWebSocketFactory } from "@/runtime/websocket-factory"; import { getOrCreateClientId } from "./client-id"; import { resolveAppVersion } from "./app-version"; import { @@ -132,12 +133,13 @@ function resolveConnectionCredentials( export async function buildClientConfig( connection: HostConnection, serverId?: string, - options?: { + options: { capabilities?: DaemonClientConfig["capabilities"]; trace?: DaemonClientConfig["trace"]; + createPluginClientBundleStore?: DaemonClientConfig["createPluginClientBundleStore"]; password?: string; localCredential?: DaemonClientConfig["localCredential"]; - }, + } = {}, deps: Pick< DaemonConnectionDependencies, | "getClientId" @@ -155,10 +157,12 @@ export async function buildClientConfig( clientType: "mobile" as const, appVersion: deps.resolveAppVersion() ?? undefined, suppressSendErrors: true, + webSocketFactory: createAppWebSocketFactory(), reconnect: { enabled: false }, ...resolveConnectionCredentials(connection, options), - ...(options?.capabilities ? { capabilities: options.capabilities } : {}), - ...(options?.trace ? { trace: options.trace } : {}), + ...(options.capabilities ? { capabilities: options.capabilities } : {}), + ...(options.trace ? { trace: options.trace } : {}), + createPluginClientBundleStore: options.createPluginClientBundleStore, ...((connection.type === "directSocket" || connection.type === "directPipe") && desktopTransportFactory ? { transportFactory: desktopTransportFactory } @@ -288,6 +292,7 @@ interface ProbeOptions { localCredential?: DaemonClientConfig["localCredential"]; capabilities?: DaemonClientConfig["capabilities"]; trace?: DaemonClientConfig["trace"]; + createPluginClientBundleStore?: DaemonClientConfig["createPluginClientBundleStore"]; } function resolveTimeout(connection: HostConnection, options?: ProbeOptions): number { diff --git a/packages/app/src/utils/time.ts b/packages/app/src/utils/time.ts index 948ee8eeb3..1c063d1a27 100644 --- a/packages/app/src/utils/time.ts +++ b/packages/app/src/utils/time.ts @@ -125,6 +125,11 @@ function getTimeFormatter(): Intl.DateTimeFormat { return cachedTimeFormatter; } +/** A clock time in the device's 12h/24h preference: "3:00 PM" or "15:00". */ +export function formatTimeOfDay(date: Date): string { + return getTimeFormatter().format(date); +} + /** * Format a chat-message timestamp for hover-revealed UI. * - Same day: "10:11 PM" or "22:11" depending on user preference @@ -132,7 +137,7 @@ function getTimeFormatter(): Intl.DateTimeFormat { * - Older, including today's weekday last week: "14 May 2026, 10:11 PM" */ export function formatMessageTimestamp(date: Date, now: Date = new Date()): string { - const time = getTimeFormatter().format(date); + const time = formatTimeOfDay(date); const daysAgo = localCalendarDaysBetween(date, now); if (daysAgo === 0) { diff --git a/packages/app/src/utils/tool-call-detail-state.ts b/packages/app/src/utils/tool-call-detail-state.ts index e2d983d8cb..b28848af8e 100644 --- a/packages/app/src/utils/tool-call-detail-state.ts +++ b/packages/app/src/utils/tool-call-detail-state.ts @@ -40,12 +40,6 @@ function hasMeaningfulFetchDetail(detail: Extract, -): boolean { - return Boolean(detail.subAgentType || detail.description || detail.log); -} - function hasMeaningfulPlainTextDetail( detail: Extract, ): boolean { @@ -75,9 +69,9 @@ export function hasMeaningfulToolCallDetail(detail: ToolCallDetail | undefined): case "fetch": return hasMeaningfulFetchDetail(detail); case "worktree_setup": - return false; + // A sub-agent card is a launch marker; the child's activity lives in the sub-agent panel. case "sub_agent": - return hasMeaningfulSubAgentDetail(detail); + return false; case "plain_text": return hasMeaningfulPlainTextDetail(detail); case "plan": @@ -92,7 +86,7 @@ export function isPendingToolCallDetail(params: { status: "executing" | "running" | "completed" | "failed" | "canceled"; error: unknown; }): boolean { - if (params.detail?.type === "worktree_setup") return false; + if (params.detail?.type === "worktree_setup" || params.detail?.type === "sub_agent") return false; const isRunning = params.status === "running" || params.status === "executing"; return isRunning && params.error == null && !hasMeaningfulToolCallDetail(params.detail); } diff --git a/packages/app/src/workspace-tabs/launcher/index.tsx b/packages/app/src/workspace-tabs/launcher/index.tsx index 2029808f31..c55208fc95 100644 --- a/packages/app/src/workspace-tabs/launcher/index.tsx +++ b/packages/app/src/workspace-tabs/launcher/index.tsx @@ -25,7 +25,6 @@ import { type PanelIconProps, type PanelPresentation, } from "@/panels/panel-registry"; -import { ensurePanelsRegistered } from "@/panels/register-panels"; import { getTerminalProfileIcon, resolveTerminalProfiles, @@ -109,7 +108,6 @@ export function useWorkspaceTabLaunchCatalog(input: { const { config } = useDaemonConfig(serverId); const plugins = useInstalledPlugins(); const isCompact = useIsCompactFormFactor(); - ensurePanelsRegistered(); const launchSelection = useCallback( (selection: NewTabSelection) => (destination: WorkspaceTabLaunchDestination) => { diff --git a/packages/app/src/workspace-tabs/open-beside.ts b/packages/app/src/workspace-tabs/open-beside.ts index abf6eba2ec..845c2c7f78 100644 --- a/packages/app/src/workspace-tabs/open-beside.ts +++ b/packages/app/src/workspace-tabs/open-beside.ts @@ -6,6 +6,7 @@ import { DEFAULT_PANE_ID, findPaneById, findPaneContainingTab, + selectSheetTab, useWorkspaceLayoutStore, type WorkspaceTabPlacement, } from "@/stores/workspace-layout-store"; @@ -144,7 +145,7 @@ export function openPreferredWorkspacePreview( // The sheet is already a single replaceable slot, so it needs no preview tab. if ( existing || - store.opensInSheet({ workspaceKey: input.workspaceKey, target: input.target, intent: "reveal" }) + selectSheetTab(store, { workspaceKey: input.workspaceKey, target: input.target }) !== null ) { return openPreferredWorkspaceTarget(input); } diff --git a/packages/app/src/workspace/open-in-file-manager/outside-folder.ts b/packages/app/src/workspace/open-in-file-manager/outside-folder.ts new file mode 100644 index 0000000000..e7d41d72d9 --- /dev/null +++ b/packages/app/src/workspace/open-in-file-manager/outside-folder.ts @@ -0,0 +1,36 @@ +import { useCallback } from "react"; +import { useTranslation } from "react-i18next"; +import { useToast } from "@/contexts/toast-context"; +import { useIsLocalDaemon } from "@/hooks/use-is-local-daemon"; +import { openDesktopTarget, useDesktopOpenTargets } from "@/workspace/desktop-open-targets"; + +/** + * Opens a folder outside the workspace in the system file manager. The Files + * panel only lists the workspace, so hosts without a local file manager get a + * toast instead. + */ +export function useOpenOutsideWorkspaceFolder(serverId: string): (folderPath: string) => void { + const { t } = useTranslation(); + const toast = useToast(); + const isLocalExecution = useIsLocalDaemon(serverId); + const { targets } = useDesktopOpenTargets({ isLocalExecution }); + const fileManagerTarget = targets.find((target) => target.kind === "file-manager"); + + return useCallback( + (folderPath: string) => { + const showOutsideWorkspace = () => + toast.show(t("common.errors.folderOutsideWorkspace", { path: folderPath })); + if (!fileManagerTarget) { + showOutsideWorkspace(); + return; + } + void openDesktopTarget({ editorId: fileManagerTarget.id, workspacePath: folderPath }).catch( + (error: unknown) => { + console.warn("[open-outside-workspace-folder] open failed", error); + showOutsideWorkspace(); + }, + ); + }, + [fileManagerTarget, t, toast], + ); +} diff --git a/packages/app/test-stubs/gorhom-bottom-sheet.ts b/packages/app/test-stubs/gorhom-bottom-sheet.ts index ee27421efd..7fc1d4bc4f 100644 --- a/packages/app/test-stubs/gorhom-bottom-sheet.ts +++ b/packages/app/test-stubs/gorhom-bottom-sheet.ts @@ -22,6 +22,10 @@ export function useBottomSheetModal(): never { export function useBottomSheet(): never { throw new Error("useBottomSheet is unavailable in tests"); } +// A drag area only hands its gesture to a sheet; with no sheet drawn there is nothing to drag. +export function useBottomSheetGestureHandlers(): never { + throw new Error("useBottomSheetGestureHandlers is unavailable in tests"); +} export const BottomSheetModalInternalProvider = PassThrough; export const INITIAL_CONTAINER_LAYOUT = { height: 0, diff --git a/packages/app/test-stubs/react-native-safe-area-context.ts b/packages/app/test-stubs/react-native-safe-area-context.ts index ae793cd921..40c064f943 100644 --- a/packages/app/test-stubs/react-native-safe-area-context.ts +++ b/packages/app/test-stubs/react-native-safe-area-context.ts @@ -1,8 +1,18 @@ -// The package ships untranspiled Flow, which the unit project cannot parse. Insets are a device -// fact no test asserts on, so they are zero. +import { createContext, useContext } from "react"; + +// The package ships untranspiled Flow, which the unit project cannot parse. Like the real package, +// the hook reads the insets context; outside a provider the insets are zero. const ZERO_INSETS = { top: 0, right: 0, bottom: 0, left: 0 } as const; -export const useSafeAreaInsets = () => ZERO_INSETS; +export interface EdgeInsets { + top: number; + right: number; + bottom: number; + left: number; +} + +export const SafeAreaInsetsContext = createContext(ZERO_INSETS); +export const useSafeAreaInsets = () => useContext(SafeAreaInsetsContext) ?? ZERO_INSETS; export const useSafeAreaFrame = () => ({ x: 0, y: 0, width: 0, height: 0 }); export const SafeAreaProvider = ({ children }: { children?: unknown }) => children; export const SafeAreaView = ({ children }: { children?: unknown }) => children; diff --git a/packages/app/vitest.config.ts b/packages/app/vitest.config.ts index 3254fc5e0c..ba4c0fc979 100644 --- a/packages/app/vitest.config.ts +++ b/packages/app/vitest.config.ts @@ -24,7 +24,9 @@ export default defineConfig({ transform(source, id) { // The ESM package contains a CommonJS WASM factory. Metro handles the // interop; Vite needs an ESM export instead of the CommonJS trailer. - if (!id.endsWith("/lib/module/web/wasm/md4c.js")) return; + // Vite can request the file with a version query (`md4c.js?v=`), so match the + // path without it. + if (!id.split("?")[0].endsWith("/lib/module/web/wasm/md4c.js")) return; const trailer = source.lastIndexOf("\nif (typeof exports === 'object'"); if (trailer < 0) throw new Error("Markdown WASM CommonJS trailer was not found"); return { @@ -80,6 +82,7 @@ export default defineConfig({ environment: "node", include: [ "src/**/*.{test,spec}.{ts,tsx}", + "modules/**/*.{test,spec}.{ts,tsx}", "native-release-version.test.ts", "app.config.test.ts", "vitest-environment.test.ts", @@ -96,7 +99,10 @@ export default defineConfig({ include: ["src/**/*.browser.{test,spec}.{ts,tsx}"], browser: { enabled: true, - provider: playwright(), + provider: playwright({ + // Exercise real WebGL glyph rendering on GPU-less CI runners. + launchOptions: { args: ["--enable-unsafe-swiftshader"] }, + }), headless: true, connectTimeout: 180_000, instances: [{ browser: "chromium" }], diff --git a/packages/cli/package.json b/packages/cli/package.json index be8188fff3..6c7fa3155d 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/cli", - "version": "0.13.2", + "version": "0.15.0-beta.1", "description": "Paseo CLI - control your AI coding agents from the command line", "bin": { "paseo": "bin/paseo" @@ -28,9 +28,9 @@ }, "dependencies": { "@clack/prompts": "^1.0.0", - "@getpaseo/client": "0.13.2", - "@getpaseo/protocol": "0.13.2", - "@getpaseo/server": "0.13.2", + "@getpaseo/client": "0.15.0-beta.1", + "@getpaseo/protocol": "0.15.0-beta.1", + "@getpaseo/server": "0.15.0-beta.1", "chalk": "^5.3.0", "commander": "^12.0.0", "mime-types": "^2.1.35", diff --git a/packages/cli/src/commands/daemon/restart.ts b/packages/cli/src/commands/daemon/restart.ts index ef88e39a23..97e2fbf604 100644 --- a/packages/cli/src/commands/daemon/restart.ts +++ b/packages/cli/src/commands/daemon/restart.ts @@ -3,8 +3,11 @@ import { readDaemonInstance, isSameDaemonInstance, DaemonInstanceError, + retryUnconfirmedTerminalCleanup, + TerminalCleanupNotConfirmedError, } from "@getpaseo/server/daemon-control"; import { setTimeout as delay } from "node:timers/promises"; +import type { DaemonGetStatusResponse } from "@getpaseo/protocol/messages"; import { connectToDaemon } from "../../utils/client.js"; import { withOutput, type CommandOptions } from "../../output/index.js"; import { addJsonAndDaemonHostOptions } from "../../utils/command-options.js"; @@ -20,13 +23,30 @@ export function daemonRestartCommand(): Command { ), ) .option("--timeout ", "Replacement readiness deadline (default: 600)") + .option("--kill-terminals", "Close every terminal instead of keeping them across the restart") .action(withOutput(runRestartCommand)); } +type DaemonStatus = DaemonGetStatusResponse["payload"]; + export async function runRestartCommand(options: CommandOptions, _command: Command) { const target = options.daemonTarget; const deadline = Date.now() + parseTimeoutMs(options.timeout); const remaining = () => Math.max(1, deadline - Date.now()); + const killTerminals = options.killTerminals === true; + // The supervisor reaps before the respawn and the replacement retries what that left; + // anything still named by a closing record survived both. A local caller retries once more + // itself; a remote one has only what the replacement reports. + const confirmTerminalsClosed = async (status: DaemonStatus) => { + if (!killTerminals) return; + if (target.kind === "instance") { + await retryUnconfirmedTerminalCleanup(target.home); + return; + } + // Absent on daemons without terminalsSurviveRestart, which have no terminal cleanup. + const unconfirmed = status.terminalCleanupUnconfirmed ?? []; + if (unconfirmed.length > 0) throw new TerminalCleanupNotConfirmedError(unconfirmed); + }; const instance = target.kind === "instance" ? await readDaemonInstance(target.home) : null; async function checkSupervisor() { if (target.kind !== "instance") return; @@ -54,7 +74,10 @@ export async function runRestartCommand(options: CommandOptions, _command: Comma workerPid = (await client.getDaemonStatus({ timeout: remaining() })).pid; await checkSupervisor(); try { - await client.restartServer("cli_restart", undefined, { timeout: remaining() }); + await client.restartServer("cli_restart", undefined, { + timeout: remaining(), + killTerminals, + }); acknowledged = true; } catch (error) { if (!isReconnectFailure(error)) throw error; @@ -77,6 +100,7 @@ export async function runRestartCommand(options: CommandOptions, _command: Comma const status = await replacement.getDaemonStatus({ timeout: remaining() }); if (status.pid !== workerPid) { await checkSupervisor(); + await confirmTerminalsClosed(status); return { type: "single" as const, data: { diff --git a/packages/cli/src/commands/daemon/status.ts b/packages/cli/src/commands/daemon/status.ts index 14c20534e6..cd499ea6cb 100644 --- a/packages/cli/src/commands/daemon/status.ts +++ b/packages/cli/src/commands/daemon/status.ts @@ -103,6 +103,7 @@ async function probeDaemonStatus( daemonNode: status.nodePath, providers: status.providers, relay: status.relay, + ...(status.terminalsUnavailable ? { terminals: status.terminalsUnavailable } : {}), }; } } finally { diff --git a/packages/cli/src/commands/daemon/stop.test.ts b/packages/cli/src/commands/daemon/stop.test.ts new file mode 100644 index 0000000000..7ee5f930f9 --- /dev/null +++ b/packages/cli/src/commands/daemon/stop.test.ts @@ -0,0 +1,110 @@ +import { spawn, type ChildProcess } from "node:child_process"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { hostname, tmpdir } from "node:os"; +import path from "node:path"; +import { Command } from "commander"; +import { afterEach, describe, expect, test } from "vitest"; +import { createStopCommandRunner, type StopCommandDeps } from "./stop.js"; + +// The daemon the gate is checked against: a connection whose server_info may or may not +// advertise terminalsSurviveRestart, and that records any shutdown it is asked for. +function createFakeDaemon(features: { terminalsSurviveRestart?: boolean } = {}) { + const shutdownRequests: Array<{ keepTerminals?: boolean }> = []; + const deps: StopCommandDeps = { + connectToDaemon: async () => ({ + getLastServerInfoMessage: () => ({ + status: "server_info", + serverId: "fake-daemon", + version: "0.11.0", + features, + }), + shutdownServer: async (options) => { + shutdownRequests.push({ keepTerminals: options?.keepTerminals }); + return { status: "shutdown_requested", clientId: "fake-client", requestId: "fake-request" }; + }, + close: async () => undefined, + }), + }; + return { deps, shutdownRequests }; +} + +const cleanups: Array<() => void> = []; + +afterEach(() => { + for (const cleanup of cleanups.splice(0)) cleanup(); +}); + +function stop(options: Record, deps: StopCommandDeps) { + return createStopCommandRunner(deps)(options as never, new Command("stop")); +} + +// A home whose lock names a live stand-in supervisor, so the local stop path runs for real. +function homeWithRunningSupervisor(): { home: string; supervisor: ChildProcess } { + const home = mkdtempSync(path.join(tmpdir(), "paseo-stop-keep-")); + const supervisor = spawn(process.execPath, ["-e", "setInterval(() => {}, 1e9)"], { + stdio: "ignore", + }); + writeFileSync( + path.join(home, "paseo.pid"), + JSON.stringify({ + pid: supervisor.pid, + startedAt: new Date().toISOString(), + hostname: hostname(), + uid: process.getuid?.() ?? 0, + listen: "127.0.0.1:1", + }), + ); + cleanups.push(() => { + supervisor.kill("SIGKILL"); + rmSync(home, { recursive: true, force: true }); + }); + return { home, supervisor }; +} + +describe("daemon stop --keep-terminals", () => { + test("refuses an endpoint daemon that does not advertise terminalsSurviveRestart", async () => { + const daemon = createFakeDaemon(); + await expect( + stop( + { daemonTarget: { kind: "endpoint", host: "127.0.0.1:7777" }, keepTerminals: true }, + daemon.deps, + ), + ).rejects.toMatchObject({ code: "TERMINALS_KEEP_UNSUPPORTED" }); + expect(daemon.shutdownRequests).toEqual([]); + }); + + test.skipIf(process.platform === "win32")( + "refuses a local daemon without the capability and never signals its supervisor", + async () => { + const daemon = createFakeDaemon(); + const { home, supervisor } = homeWithRunningSupervisor(); + await expect( + stop({ daemonTarget: { kind: "instance", home }, keepTerminals: true }, daemon.deps), + ).rejects.toMatchObject({ code: "TERMINALS_KEEP_UNSUPPORTED" }); + expect(daemon.shutdownRequests).toEqual([]); + expect(supervisor.exitCode).toBeNull(); + expect(supervisor.signalCode).toBeNull(); + }, + ); + + test("asks a capable daemon to keep its terminals", async () => { + const daemon = createFakeDaemon({ terminalsSurviveRestart: true }); + await stop( + { daemonTarget: { kind: "endpoint", host: "127.0.0.1:7777" }, keepTerminals: true }, + daemon.deps, + ); + expect(daemon.shutdownRequests).toEqual([{ keepTerminals: true }]); + }); + + test("rejects --force with --keep-terminals before contacting the daemon", async () => { + const daemon = createFakeDaemon({ terminalsSurviveRestart: true }); + const { home } = homeWithRunningSupervisor(); + await expect( + stop( + { daemonTarget: { kind: "instance", home }, keepTerminals: true, force: true }, + daemon.deps, + ), + ).rejects.toMatchObject({ code: "INVALID_OPTIONS" }); + expect(daemon.shutdownRequests).toEqual([]); + }); +}); diff --git a/packages/cli/src/commands/daemon/stop.ts b/packages/cli/src/commands/daemon/stop.ts index f2bf8b1255..141d50965e 100644 --- a/packages/cli/src/commands/daemon/stop.ts +++ b/packages/cli/src/commands/daemon/stop.ts @@ -1,6 +1,10 @@ import { Command } from "commander"; +import { + requireTerminalKeepCapability, + type DaemonClient, +} from "@getpaseo/client/internal/daemon-client"; import { stopDaemonInstance, type DaemonInstance } from "@getpaseo/server/daemon-control"; -import { connectToDaemon } from "../../utils/client.js"; +import { connectToDaemon, type ConnectOptions } from "../../utils/client.js"; import { withOutput, type CommandOptions } from "../../output/index.js"; import { addJsonAndDaemonHostOptions } from "../../utils/command-options.js"; import { describeDaemonTarget } from "../../utils/daemon-target.js"; @@ -10,19 +14,43 @@ export function daemonStopCommand(): Command { return addJsonAndDaemonHostOptions(new Command("stop").description("Stop the selected daemon")) .option("--timeout ", "Graceful exit deadline (default: 15)") .option("--force", "Permit forced local process cleanup") + .option( + "--keep-terminals", + "Leave terminals running; the next daemon started for this home takes them back", + ) .option("--kill-timeout ", "Forced exit deadline (default: 3)") .action(withOutput(runStopCommand)); } -export async function runStopCommand(options: CommandOptions, _command: Command) { +// The daemon connection stop needs; stop.test.ts passes an in-memory adapter. +export type StopDaemonConnection = Pick< + DaemonClient, + "getLastServerInfoMessage" | "shutdownServer" | "close" +>; + +export interface StopCommandDeps { + connectToDaemon(options: ConnectOptions): Promise; +} + +export const runStopCommand = createStopCommandRunner({ connectToDaemon }); + +export function createStopCommandRunner(deps: StopCommandDeps) { + return (options: CommandOptions, _command: Command) => runStop(options, deps); +} + +async function runStop(options: CommandOptions, deps: StopCommandDeps) { const target = options.daemonTarget; const timeoutMs = parseTimeoutMs(options.timeout, 15_000); const deadline = Date.now() + timeoutMs; const remaining = () => Math.max(1, deadline - Date.now()); + const keepTerminals = options.keepTerminals === true; const requestShutdown = async (instance?: DaemonInstance) => { - const client = await connectToDaemon({ target, timeout: remaining(), instance }); + const client = await deps.connectToDaemon({ target, timeout: remaining(), instance }); try { - await client.shutdownServer({ timeout: remaining() }); + // Checked on the connection that carries the shutdown: a daemon without the capability + // would close the terminals it was asked to keep. + if (keepTerminals) requireTerminalKeepCapability(client, describeDaemonTarget(target)); + await client.shutdownServer({ timeout: remaining(), keepTerminals }); } finally { await client.close(); } @@ -32,6 +60,11 @@ export async function runStopCommand(options: CommandOptions, _command: Command) code: "INVALID_OPTIONS", message: "--force requires a local --home; an endpoint gives no remote process authority.", }; + if (options.force && keepTerminals) + throw { + code: "INVALID_OPTIONS", + message: "--force kills terminals; it cannot be combined with --keep-terminals.", + }; const result: { action: string; home?: string; @@ -44,6 +77,7 @@ export async function runStopCommand(options: CommandOptions, _command: Command) ? { ...(await stopDaemonInstance(target.home, { force: options.force === true, + keepTerminals, timeoutMs, killTimeoutMs: parseTimeoutMs(options.killTimeout, 3_000), requestShutdown, diff --git a/packages/cli/tests/42-test-daemon-ephemeral-port.test.ts b/packages/cli/tests/42-test-daemon-ephemeral-port.test.ts new file mode 100644 index 0000000000..f559c275bc --- /dev/null +++ b/packages/cli/tests/42-test-daemon-ephemeral-port.test.ts @@ -0,0 +1,16 @@ +#!/usr/bin/env npx tsx + +import assert from "node:assert/strict"; +import { startTestDaemon, runPaseoCli } from "./helpers/test-daemon.ts"; + +// Port zero leaves allocation to the listening daemon, with no reserve/release gap. +const daemon = await startTestDaemon({ port: 0 }); +try { + assert(daemon.port > 0, "the helper returns the port the daemon actually bound"); + assert.equal(daemon.wsUrl, `ws://127.0.0.1:${daemon.port}`); + const result = await runPaseoCli(daemon, ["agent", "ls", "--host", daemon.wsUrl, "--json"]); + assert.equal(result.exitCode, 0, result.stderr); + assert.deepEqual(JSON.parse(result.stdout), []); +} finally { + await daemon.stop(); +} diff --git a/packages/cli/tests/45-daemon-terminals-survive.test.ts b/packages/cli/tests/45-daemon-terminals-survive.test.ts new file mode 100644 index 0000000000..7804ea6917 --- /dev/null +++ b/packages/cli/tests/45-daemon-terminals-survive.test.ts @@ -0,0 +1,324 @@ +#!/usr/bin/env npx tsx + +/** + * Terminals survive `paseo daemon restart` and `stop --keep-terminals`; `restart + * --kill-terminals`, `stop` and `stop --force` close them. Runs the built CLI and daemon in a + * throwaway home; every process it starts is stopped in `finally`. + */ + +import assert from "node:assert/strict"; +import { spawn } from "node:child_process"; +import { existsSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { mkdtemp, mkdir, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { readDaemonInstance } from "@getpaseo/server/daemon-control"; +import { runLocalPaseo } from "./helpers/local-cli.ts"; +import { getAvailablePort } from "./helpers/network.ts"; + +if (process.platform === "win32") { + console.log("Skipping terminal survival CLI test on Windows (POSIX shell terminals)."); + process.exit(0); +} + +console.log("=== Daemon terminals survive restart ===\n"); + +const paseoHome = await mkdtemp(join(tmpdir(), "paseo-terminals-survive-")); +const workDir = join(paseoHome, "work"); +await mkdir(workDir, { recursive: true }); +const port = await getAvailablePort(); +const env = { + PASEO_HOME: paseoHome, + PASEO_LOCAL_SPEECH_AUTO_DOWNLOAD: "0", + PASEO_DICTATION_ENABLED: "0", + PASEO_VOICE_MODE_ENABLED: "0", + // The daemon inherits this; terminals then run a plain POSIX shell with no startup files. + SHELL: "/bin/sh", +}; + +function isAlive(pid: number): boolean { + try { + process.kill(pid, 0); + return true; + } catch { + return false; + } +} + +async function waitFor( + probe: () => Promise | T | null | false, + message: string, + timeoutMs = 30_000, +): Promise { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + const value = await probe(); + if (value) return value; + await new Promise((resolve) => setTimeout(resolve, 100)); + } + throw new Error(message); +} + +async function paseo(args: string[], expectSuccess = true) { + const result = await runLocalPaseo(args, env); + if (expectSuccess) { + assert.equal( + result.exitCode, + 0, + `paseo ${args.join(" ")} failed:\nstdout:\n${result.stdout}\nstderr:\n${result.stderr}`, + ); + } + return result; +} + +async function json(args: string[]): Promise { + return JSON.parse((await paseo([...args, "--json"])).stdout) as T; +} + +async function capture(terminalId: string): Promise { + const { lines } = await json<{ lines: string[] }>(["terminal", "capture", terminalId]); + return lines.join("\n"); +} + +async function waitForScreen(terminalId: string, text: string): Promise { + await waitFor( + async () => (await capture(terminalId)).includes(text), + `terminal ${terminalId} never showed ${text}:\n${await capture(terminalId)}`, + ); +} + +async function terminalIds(): Promise { + return (await json>(["terminal", "ls", "--all"])).map((t) => t.id); +} + +// Worker records and the cleanup records a kill that could not finish leaves beside them. +function workerRecordCount(): number { + const dir = join(paseoHome, "terminal-worker"); + return existsSync(dir) + ? readdirSync(dir).filter((name) => /^(\d+|closing-.+)\.json$/.test(name)).length + : 0; +} + +// A shell terminal that reports its pid and prints a marker. +async function openTerminal(name: string): Promise<{ id: string; pid: number }> { + const terminal = await json<{ id: string }>([ + "terminal", + "create", + "--cwd", + workDir, + "--name", + name, + ]); + const pidFile = join(workDir, `${name}.pid`); + await paseo([ + "terminal", + "send-keys", + terminal.id, + "-l", + `echo $$ > '${pidFile}'; echo MARKER-${name}`, + ]); + await paseo(["terminal", "send-keys", terminal.id, "Enter"]); + const pid = await waitFor( + () => + existsSync(pidFile) && readFileSync(pidFile, "utf8").trim() + ? Number(readFileSync(pidFile, "utf8")) + : null, + `terminal ${name} never wrote its pid`, + ); + await waitForScreen(terminal.id, `MARKER-${name}`); + return { id: terminal.id, pid }; +} + +async function expectKept(terminal: { id: string; pid: number }, name: string, trigger: string) { + assert((await terminalIds()).includes(terminal.id), `${trigger}: terminal is still listed`); + assert(isAlive(terminal.pid), `${trigger}: terminal program is still alive`); + assert((await capture(terminal.id)).includes(`MARKER-${name}`), `${trigger}: marker is kept`); + await paseo(["terminal", "send-keys", terminal.id, "-l", `echo after-${trigger}`]); + await paseo(["terminal", "send-keys", terminal.id, "Enter"]); + await waitForScreen(terminal.id, `\nafter-${trigger}`); +} + +async function expectClosed(pid: number, trigger: string) { + await waitFor(() => !isAlive(pid), `${trigger}: terminal program ${pid} is still alive`, 15_000); +} + +// A zombie: a real process with a birth time that SIGKILL cannot remove while its parent (an +// exec'd `sleep` that never waits) lives. Cleanup can only report it as still alive. +async function startZombie(): Promise<{ zombiePid: number; parentPid: number }> { + const parent = spawn("/bin/sh", ["-c", "sleep 0 & echo $!; exec sleep 600"], { + stdio: ["ignore", "pipe", "ignore"], + }); + const zombiePid = await new Promise((resolve) => { + parent.stdout!.once("data", (chunk: Buffer) => resolve(Number(chunk.toString().trim()))); + }); + parent.unref(); + await waitFor( + async () => (await psField(zombiePid, "stat")).startsWith("Z"), + `process ${zombiePid} never became a zombie`, + ); + return { zombiePid, parentPid: parent.pid! }; +} + +async function psField(pid: number, field: "stat" | "lstart"): Promise { + const child = spawn("ps", ["-o", `${field}=`, "-p", String(pid)], { + env: { ...process.env, LC_ALL: "C" }, + stdio: ["ignore", "pipe", "ignore"], + }); + let out = ""; + child.stdout.on("data", (chunk: Buffer) => (out += chunk.toString())); + await new Promise((resolve) => child.once("close", resolve)); + return out.trim(); +} + +async function goneProcessPid(): Promise { + const child = spawn(process.execPath, ["-e", ""], { stdio: "ignore" }); + await new Promise((resolve) => child.once("exit", resolve)); + return child.pid!; +} + +// A record as a dead terminal worker leaves it, naming one terminal program that is a zombie. +async function plantRecordNaming(programPid: number): Promise { + const workerPid = await goneProcessPid(); + const record = { + recordId: "planted-record", + pid: workerPid, + bootId: null, + createdAt: new Date().toISOString(), + identity: { startedAt: "Thu Jan 1 00:00:00 1970", commandLine: "planted-worker" }, + protocolVersion: 1, + paseoVersion: "0.0.0-test", + socketPath: join(paseoHome, "planted-worker.sock"), + secret: "planted-secret", + terminals: [ + { id: "planted-terminal", pid: programPid, startedAt: await psField(programPid, "lstart") }, + ], + }; + writeFileSync( + join(paseoHome, "terminal-worker", `${workerPid}.json`), + `${JSON.stringify(record, null, 2)}\n`, + { mode: 0o600 }, + ); +} + +const trackedPids: number[] = []; + +try { + for (const [field, value] of [ + ["daemon.listen", `127.0.0.1:${port}`], + ["daemon.relay.enabled", "false"], + ["features.dictation.enabled", "false"], + ["features.voiceMode.enabled", "false"], + ] as const) { + await paseo(["daemon", "config", "set", field, value]); + } + await paseo(["daemon", "start"]); + + console.log("Test 1: daemon restart keeps the terminal"); + const kept = await openTerminal("kept"); + trackedPids.push(kept.pid); + await paseo(["daemon", "restart", "--home", paseoHome]); + await expectKept(kept, "kept", "restart"); + console.log("✓ same id, same program, marker and input after restart\n"); + + console.log("Test 2: stop --keep-terminals, then start, gives the terminal back"); + const forceAndKeep = await paseo( + ["daemon", "stop", "--home", paseoHome, "--force", "--keep-terminals"], + false, + ); + assert.notEqual(forceAndKeep.exitCode, 0, "--force with --keep-terminals is refused"); + await paseo(["daemon", "stop", "--home", paseoHome, "--keep-terminals"]); + assert.equal(await readDaemonInstance(paseoHome), null, "the supervisor stopped"); + assert(isAlive(kept.pid), "the program outlives the stopped daemon"); + await paseo(["daemon", "start"]); + await expectKept(kept, "kept", "keep-stop"); + console.log("✓ adopted with the same id and still usable\n"); + + console.log("Test 3: a plain stop with no daemon running closes kept terminals"); + await paseo(["daemon", "stop", "--home", paseoHome, "--keep-terminals"]); + assert(isAlive(kept.pid), "kept again"); + await paseo(["daemon", "stop", "--home", paseoHome]); + await expectClosed(kept.pid, "stop without a supervisor"); + assert.equal(workerRecordCount(), 0, "no worker record is left"); + console.log("✓ closed\n"); + + console.log("Test 4: restart --kill-terminals closes the terminal"); + await paseo(["daemon", "start"]); + const killedByRestart = await openTerminal("restart-kill"); + trackedPids.push(killedByRestart.pid); + await paseo(["daemon", "restart", "--home", paseoHome, "--kill-terminals"]); + await expectClosed(killedByRestart.pid, "restart --kill-terminals"); + assert.deepEqual(await terminalIds(), [], "no terminal is listed after the kill restart"); + console.log("✓ closed\n"); + + console.log("Test 5: daemon stop closes the terminal and its worker"); + const killedByStop = await openTerminal("stop-kill"); + trackedPids.push(killedByStop.pid); + await paseo(["daemon", "stop", "--home", paseoHome]); + await expectClosed(killedByStop.pid, "stop"); + assert.equal(workerRecordCount(), 0, "no worker record is left"); + console.log("✓ closed\n"); + + console.log("Test 6: daemon stop --force closes the terminal"); + await paseo(["daemon", "start"]); + const killedByForce = await openTerminal("force-kill"); + trackedPids.push(killedByForce.pid); + await paseo(["daemon", "stop", "--home", paseoHome, "--force"]); + await expectClosed(killedByForce.pid, "stop --force"); + assert.equal(workerRecordCount(), 0, "no worker record is left"); + console.log("✓ closed\n"); + + const endpoint = `127.0.0.1:${port}`; + console.log("Test 7: restart --host --kill-terminals closes the terminal"); + await paseo(["daemon", "start"]); + const killedByEndpointRestart = await openTerminal("endpoint-restart-kill"); + trackedPids.push(killedByEndpointRestart.pid); + await paseo(["daemon", "restart", "--host", endpoint, "--kill-terminals"]); + await expectClosed(killedByEndpointRestart.pid, "restart --host --kill-terminals"); + assert.deepEqual(await terminalIds(), [], "no terminal is listed after the kill restart"); + console.log("✓ closed and confirmed by the replacement\n"); + + console.log("Test 8: restart --host --kill-terminals reports a process cleanup could not end"); + const zombie = await startZombie(); + trackedPids.push(zombie.parentPid); + await plantRecordNaming(zombie.zombiePid); + const unconfirmed = await paseo( + ["daemon", "restart", "--host", endpoint, "--kill-terminals"], + false, + ); + assert.notEqual(unconfirmed.exitCode, 0, "the kill restart fails"); + const output = unconfirmed.stdout + unconfirmed.stderr; + assert(output.includes("Terminal cleanup was not confirmed"), `names the failure:\n${output}`); + assert(output.includes(`pid ${zombie.zombiePid}`), `names the surviving pid:\n${output}`); + process.kill(zombie.parentPid, "SIGKILL"); + await expectClosed(zombie.zombiePid, "zombie reaped once its parent exits"); + await paseo(["daemon", "stop", "--home", paseoHome]); + assert.equal(workerRecordCount(), 0, "the next stop retries the cleanup and retires the record"); + console.log("✓ reported, then retried by stop\n"); + + console.log("Test 9: restart --host --kill-terminals reports a worker record it cannot read"); + await paseo(["daemon", "start"]); + // A kill cleanup cannot check what an unreadable record names, and leaves nothing else + // behind, so the replacement daemon must still report it. + const unreadablePath = join(paseoHome, "terminal-worker", `${await goneProcessPid()}.json`); + writeFileSync(unreadablePath, "{ not json", { mode: 0o600 }); + const unreadable = await paseo( + ["daemon", "restart", "--host", endpoint, "--kill-terminals"], + false, + ); + assert.notEqual(unreadable.exitCode, 0, "the kill restart fails"); + const unreadableOutput = unreadable.stdout + unreadable.stderr; + assert(unreadableOutput.includes(unreadablePath), `names the record:\n${unreadableOutput}`); + assert(existsSync(unreadablePath), "the unreadable record is kept"); + rmSync(unreadablePath); + await paseo(["daemon", "stop", "--home", paseoHome]); + assert.equal(workerRecordCount(), 0, "no worker record is left"); + console.log("✓ reported with the record's path\n"); +} finally { + await runLocalPaseo(["daemon", "stop", "--home", paseoHome, "--force"], env); + for (const pid of trackedPids) { + if (isAlive(pid)) process.kill(pid, "SIGKILL"); + } + await rm(paseoHome, { recursive: true, force: true }); +} + +console.log("=== Daemon terminals survive restart passed ==="); diff --git a/packages/cli/tests/46-daemon-terminal-worker-upgrade.test.ts b/packages/cli/tests/46-daemon-terminal-worker-upgrade.test.ts new file mode 100644 index 0000000000..9090456406 --- /dev/null +++ b/packages/cli/tests/46-daemon-terminal-worker-upgrade.test.ts @@ -0,0 +1,561 @@ +#!/usr/bin/env npx tsx + +/** + * A terminal worker survives an upgrade of the installation that started it. Two disposable + * installations A and B (built dist, real copies of @getpaseo/server, @getpaseo/cli and + * node-pty, every other dependency a symlink into this repo) each get their own CLI shim, so + * each daemon's PASEO_CLI is a distinct path: + * + * 1. A daemon from A runs its worker from a copy in $PASEO_HOME/terminal-worker/. After + * `stop --keep-terminals` and moving A's node-pty, worker bundle and shell integration away, + * a daemon from B adopts the same worker and opens a new, working terminal in it with B's + * environment and CLI, while the first terminal keeps A's. + * 2. Worker protocol versions (PASEO_TERMINAL_WORKER_PROTOCOL_OVERRIDE): protocols 0–4 + * are obsolete unreleased wires, so their programs/workers/copies are closed and a current + * worker serves new terminals. A truly newer protocol is left running, reported as + * terminal_worker_incompatible, and closed by `daemon stop`. + * + * Every process it starts is stopped in `finally`. + */ + +import assert from "node:assert/strict"; +import { execFile } from "node:child_process"; +import { + chmodSync, + cpSync, + existsSync, + mkdirSync, + readdirSync, + readFileSync, + renameSync, + symlinkSync, + writeFileSync, +} from "node:fs"; +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { createServer } from "node:net"; + +if (process.platform === "win32") { + console.log("Skipping terminal worker upgrade CLI test on Windows (POSIX shell terminals)."); + process.exit(0); +} + +console.log("=== Terminal worker survives an upgrade ===\n"); + +const repoRoot = join(import.meta.dirname, "..", "..", ".."); +const root = await mkdtemp(join(tmpdir(), "paseo-worker-upgrade-")); +const paseoHome = join(root, "home"); +const cliHome = join(root, "os-home"); +const workDir = join(root, "work"); +for (const dir of [paseoHome, cliHome, workDir]) mkdirSync(dir, { recursive: true }); +const currentProtocolVersion = 5; +const zsh = ["/bin/zsh", "/usr/bin/zsh"].find((candidate) => existsSync(candidate)) ?? null; + +interface Installation { + name: string; + dir: string; + version: string; + shim: string; + serverDir: string; +} + +// --------------------------------------------------------------------------------------------- +// Installation fixtures +// --------------------------------------------------------------------------------------------- + +function linkEntries(source: string, target: string, taken: Set): void { + if (!existsSync(source)) return; + for (const name of readdirSync(source)) { + if (name.startsWith(".")) continue; + if (name.startsWith("@")) { + mkdirSync(join(target, name), { recursive: true }); + for (const scoped of readdirSync(join(source, name))) { + const key = `${name}/${scoped}`; + if (taken.has(key)) continue; + taken.add(key); + symlinkSync(join(source, name, scoped), join(target, name, scoped)); + } + continue; + } + if (taken.has(name)) continue; + taken.add(name); + symlinkSync(join(source, name), join(target, name)); + } +} + +function createInstallation(name: string, version: string): Installation { + const dir = join(root, `install-${name}`); + const modules = join(dir, "node_modules"); + mkdirSync(join(modules, "@getpaseo"), { recursive: true }); + + // Real copies: the server (its version marks the installation), the CLI (so it resolves this + // installation's server), and node-pty (so moving it away breaks only this installation). + const serverDir = join(modules, "@getpaseo", "server"); + const serverPackage = JSON.parse( + readFileSync(join(repoRoot, "packages/server/package.json"), "utf8"), + ) as Record; + mkdirSync(join(serverDir, "dist"), { recursive: true }); + writeFileSync( + join(serverDir, "package.json"), + `${JSON.stringify({ ...serverPackage, version }, null, 2)}\n`, + ); + for (const part of ["server", "src", "scripts"]) { + cpSync(join(repoRoot, "packages/server/dist", part), join(serverDir, "dist", part), { + recursive: true, + }); + } + const cliDir = join(modules, "@getpaseo", "cli"); + mkdirSync(cliDir, { recursive: true }); + cpSync(join(repoRoot, "packages/cli/package.json"), join(cliDir, "package.json")); + cpSync(join(repoRoot, "packages/cli/dist"), join(cliDir, "dist"), { recursive: true }); + cpSync(join(repoRoot, "packages/server/node_modules/node-pty"), join(modules, "node-pty"), { + recursive: true, + }); + + const taken = new Set(["@getpaseo/server", "@getpaseo/cli", "node-pty"]); + for (const source of [ + "packages/server/node_modules", + "packages/cli/node_modules", + "node_modules", + ]) { + linkEntries(join(repoRoot, source), modules, taken); + } + + const shim = join(dir, "bin", "paseo"); + mkdirSync(join(dir, "bin")); + writeFileSync( + shim, + `#!/bin/sh\nexec "${process.execPath}" "${join(cliDir, "dist", "index.js")}" "$@"\n`, + ); + chmodSync(shim, 0o755); + return { name, dir, version, shim, serverDir }; +} + +// The runtime files an upgrade replaces: node-pty, the worker bundle, the shell integration. +function moveRuntimeAway(installation: Installation): () => void { + const away = join(installation.dir, "moved-away"); + const moves = [ + join(installation.dir, "node_modules", "node-pty"), + join(installation.serverDir, "dist", "server", "terminal-worker"), + join(installation.serverDir, "dist", "server", "terminal", "shell-integration"), + ].map((from, index) => ({ from, to: join(away, String(index)) })); + mkdirSync(away, { recursive: true }); + for (const move of moves) renameSync(move.from, move.to); + return () => { + for (const move of moves) renameSync(move.to, move.from); + }; +} + +// --------------------------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------------------------- + +function isAlive(pid: number): boolean { + try { + process.kill(pid, 0); + return true; + } catch { + return false; + } +} + +async function waitFor( + probe: () => Promise | T | null | false, + message: () => string | Promise, + timeoutMs = 30_000, +): Promise { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + const value = await probe(); + if (value) return value; + await new Promise((resolve) => setTimeout(resolve, 100)); + } + throw new Error(await message()); +} + +interface RunResult { + exitCode: number; + stdout: string; + stderr: string; +} + +function run( + installation: Installation, + args: string[], + extraEnv: Record = {}, +): Promise { + const env = { + ...Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith("PASEO_"))), + HOME: cliHome, + USERPROFILE: cliHome, + PASEO_HOME: paseoHome, + PASEO_LOCAL_SPEECH_AUTO_DOWNLOAD: "0", + PASEO_DICTATION_ENABLED: "0", + PASEO_VOICE_MODE_ENABLED: "0", + // Each daemon hands its terminals its own installation's CLI. + PASEO_CLI: installation.shim, + PASEO_TEST_INSTALL: installation.name, + SHELL: "/bin/sh", + ...extraEnv, + }; + return new Promise((resolve) => { + execFile(installation.shim, args, { env, timeout: 120_000 }, (error, stdout, stderr) => { + let exitCode = 0; + if (error) exitCode = typeof error.code === "number" ? error.code : 1; + resolve({ exitCode, stdout, stderr }); + }); + }); +} + +async function paseo( + installation: Installation, + args: string[], + extraEnv: Record = {}, +): Promise { + const result = await run(installation, args, extraEnv); + assert.equal( + result.exitCode, + 0, + `paseo ${args.join(" ")} (${installation.name}) failed:\nstdout:\n${result.stdout}\nstderr:\n${result.stderr}`, + ); + return result; +} + +async function json(installation: Installation, args: string[]): Promise { + return JSON.parse((await paseo(installation, [...args, "--json"])).stdout) as T; +} + +async function capture(installation: Installation, terminalId: string): Promise { + const { lines } = await json<{ lines: string[] }>(installation, [ + "terminal", + "capture", + terminalId, + ]); + return lines.join("\n"); +} + +async function type(installation: Installation, terminalId: string, line: string) { + await paseo(installation, ["terminal", "send-keys", terminalId, "-l", line]); + await paseo(installation, ["terminal", "send-keys", terminalId, "Enter"]); +} + +async function waitForScreen(installation: Installation, terminalId: string, text: string) { + await waitFor( + async () => (await capture(installation, terminalId)).includes(text), + async () => + `terminal ${terminalId} never showed ${text}:\n${await capture(installation, terminalId)}`, + ); +} + +// Opens a terminal, records its shell's pid, and prints a marker. +async function openTerminal( + installation: Installation, + name: string, +): Promise<{ id: string; pid: number }> { + const terminal = await json<{ id: string }>(installation, [ + "terminal", + "create", + "--cwd", + workDir, + "--name", + name, + ]); + const pidFile = join(workDir, `${name}.pid`); + await type(installation, terminal.id, `echo $$ > '${pidFile}'; echo MARKER-${name}`); + const pid = await waitFor( + () => + existsSync(pidFile) && readFileSync(pidFile, "utf8").trim() + ? Number(readFileSync(pidFile, "utf8")) + : null, + () => `terminal ${name} never wrote its pid`, + ); + await waitForScreen(installation, terminal.id, `MARKER-${name}`); + trackedPids.push(pid); + return { id: terminal.id, pid }; +} + +// The value of `$variable` in the terminal's shell, written to a file (a long path would wrap +// on screen). +async function echoVariable( + installation: Installation, + terminalId: string, + label: string, + variable: string, +): Promise { + const valueFile = join(workDir, `${label}.value`); + await type( + installation, + terminalId, + `printf '%s' "$${variable}" > '${valueFile}.tmp' && mv '${valueFile}.tmp' '${valueFile}'`, + ); + await waitFor( + () => existsSync(valueFile), + async () => + `terminal ${terminalId} never wrote ${label}:\n${await capture(installation, terminalId)}`, + ); + return readFileSync(valueFile, "utf8"); +} + +interface WorkerRecordFile { + pid: number; + protocolVersion: unknown; + runtime?: string | null; + terminals: Array<{ id: string; pid: number }>; +} + +function workerRecords(): WorkerRecordFile[] { + const dir = join(paseoHome, "terminal-worker"); + if (!existsSync(dir)) return []; + return readdirSync(dir) + .filter((name) => /^\d+\.json$/.test(name)) + .map((name) => JSON.parse(readFileSync(join(dir, name), "utf8")) as WorkerRecordFile); +} + +function runtimeCopies(): string[] { + const dir = join(paseoHome, "terminal-worker"); + if (!existsSync(dir)) return []; + return readdirSync(dir).filter((name) => + existsSync(join(dir, name, "paseo-terminal-worker-runtime.json")), + ); +} + +function commandLineOf(pid: number): Promise { + return new Promise((resolve) => { + execFile("ps", ["-ww", "-o", "command=", "-p", String(pid)], (_error, stdout) => + resolve(stdout.trim()), + ); + }); +} + +async function terminalIds(installation: Installation): Promise { + return (await json>(installation, ["terminal", "ls", "--all"])).map( + (terminal) => terminal.id, + ); +} + +async function startDaemon(installation: Installation, extraEnv: Record = {}) { + const result = await paseo(installation, ["daemon", "start", "--json"], extraEnv); + lastListen = (JSON.parse(result.stdout) as { listen: string }).listen; + assert.match(lastListen, /^127\.0\.0\.1:[1-9]\d*$/, "start publishes the actual bound port"); + if (competingListener.listening) { + const competitor = competingListener.address(); + assert(competitor && typeof competitor !== "string"); + assert.notEqual( + Number(lastListen.split(":").at(-1)), + competitor.port, + "each daemon binds its own endpoint while the released port belongs to a peer", + ); + } +} + +async function stopDaemon(installation: Installation, keepTerminals = false) { + await paseo(installation, [ + "daemon", + "stop", + "--home", + paseoHome, + ...(keepTerminals ? ["--keep-terminals"] : []), + ]); +} + +// A terminal in a worker reporting `protocolVersion`, left running by `stop --keep-terminals`. +async function leaveWorkerWithProtocol( + installation: Installation, + protocolVersion: number, + name: string, +): Promise<{ terminal: { id: string; pid: number }; workerPid: number; runtime: string }> { + await startDaemon(installation, { + PASEO_TERMINAL_WORKER_PROTOCOL_OVERRIDE: String(protocolVersion), + }); + const terminal = await openTerminal(installation, name); + const [worker] = workerRecords(); + assert(worker, "the daemon started a worker"); + assert.equal(worker.protocolVersion, protocolVersion, "the worker reports the override"); + await stopDaemon(installation, true); + return { terminal, workerPid: worker.pid, runtime: worker.runtime! }; +} + +const trackedPids: number[] = []; +const a = createInstallation("A", "0.98.0"); +const b = createInstallation("B", "0.99.0"); +let restoreA: (() => void) | null = null; +let passed = false; +let lastListen = ""; +const competingListener = createServer(); + +try { + for (const [field, value] of [ + // Let the listening daemon reserve its port atomically. Clients discover the + // actual endpoint from this home's PID record after every start. + ["daemon.listen", "127.0.0.1:0"], + ["daemon.relay.enabled", "false"], + ["features.dictation.enabled", "false"], + ["features.voiceMode.enabled", "false"], + ] as const) { + await paseo(a, ["daemon", "config", "set", field, value]); + } + + console.log("Test 1: a daemon from A runs its worker from a copy in the home"); + await startDaemon(a); + const t1 = await openTerminal(a, "t1"); + const [firstWorker] = workerRecords(); + assert(firstWorker, "one worker runs"); + assert.equal(firstWorker.protocolVersion, currentProtocolVersion, "the current wire is adopted"); + assert.match(firstWorker.runtime ?? "", /^0\.98\.0-[0-9a-f]{12}$/); + const copyA = join(paseoHome, "terminal-worker", firstWorker.runtime!); + assert( + (await commandLineOf(firstWorker.pid)).includes(join(copyA, "terminal-worker.mjs")), + "the worker runs the copy's bundle", + ); + assert.equal(await echoVariable(a, t1.id, "CLI1", "PASEO_CLI"), a.shim, "T1 has A's CLI"); + console.log("✓ worker runs from", copyA, "\n"); + + console.log("Test 2: B adopts the worker after A's runtime files are gone"); + await stopDaemon(a, true); + restoreA = moveRuntimeAway(a); + await startDaemon(b, zsh ? { SHELL: zsh } : {}); + assert.deepEqual( + workerRecords().map((record) => record.pid), + [firstWorker.pid], + "B adopted the same worker instead of starting one", + ); + assert((await terminalIds(b)).includes(t1.id), "T1 is listed by B"); + const t2 = await openTerminal(b, "t2"); + assert.equal(await echoVariable(b, t2.id, "INSTALL2", "PASEO_TEST_INSTALL"), "B"); + assert.equal(await echoVariable(b, t2.id, "CLI2", "PASEO_CLI"), b.shim, "T2 has B's CLI"); + if (zsh) { + // Creating a zsh terminal reads Paseo's integration from the worker's copy (A's is gone); + // a missing file would have failed the create. + const zshVersion = await echoVariable(b, t2.id, "ZSH", "ZSH_VERSION"); + assert(zshVersion.length > 0, "T2 runs zsh with Paseo's shell integration"); + } else { + console.log(" (zsh is not installed: the shell-integration check is skipped)"); + } + assert.equal(await echoVariable(b, t1.id, "CLI1AGAIN", "PASEO_CLI"), a.shim, "T1 keeps A's CLI"); + console.log("✓ same worker, T2 uses B's environment, T1 still works\n"); + + console.log("Test 3: daemon stop closes both terminals and deletes the copy"); + await stopDaemon(b); + await waitFor( + () => !isAlive(t1.pid) && !isAlive(t2.pid) && !isAlive(firstWorker.pid), + () => "terminals or worker outlived daemon stop", + ); + assert.deepEqual(workerRecords(), [], "no worker record is left"); + assert.deepEqual(runtimeCopies(), [], "no copy is left"); + restoreA(); + restoreA = null; + console.log("✓ closed and cleaned up\n"); + + // A released endpoint belongs to nobody. Reproduce another process taking it + // between starts; worker adoption is keyed by the home, not by a stable TCP port. + const releasedPort = Number(lastListen.split(":").at(-1)); + await new Promise((resolve, reject) => { + competingListener.once("error", reject); + competingListener.listen(releasedPort, "127.0.0.1", resolve); + }); + console.log(`Competing listener owns released port ${releasedPort}`); + + // There is no supported previous wire at protocol 5. Future previous-version classification + // is covered by terminal-worker-protocol.test.ts; do not simulate an unreleased drain adapter. + for (const protocolVersion of [0, 1, 2, 3, 4]) { + console.log(`Test 4: obsolete protocol ${protocolVersion} is closed before serving terminals`); + const obsolete = await leaveWorkerWithProtocol( + a, + protocolVersion, + `obsolete-${protocolVersion}`, + ); + await startDaemon(b); + await waitFor( + () => !isAlive(obsolete.workerPid) && !isAlive(obsolete.terminal.pid), + () => "the obsolete worker or its terminal survived", + ); + assert(!(await terminalIds(b)).includes(obsolete.terminal.id), "its terminal is gone"); + const [current] = workerRecords(); + assert.equal(workerRecords().length, 1, "one current worker runs"); + assert(current); + assert.equal(current.protocolVersion, currentProtocolVersion); + assert.match(current.runtime ?? "", /^0\.99\.0-/); + await waitFor( + () => !runtimeCopies().includes(obsolete.runtime), + () => `the obsolete worker's copy ${obsolete.runtime} was not deleted`, + ); + assert.deepEqual(runtimeCopies(), [current.runtime], "the current copy stays"); + const replacement = await openTerminal(b, `replacement-${protocolVersion}`); + assert.deepEqual( + workerRecords() + .find((record) => record.pid === current.pid)! + .terminals.map((terminal) => terminal.id), + [replacement.id], + "new terminals open in the current worker", + ); + await type(b, replacement.id, `echo after-protocol-cut-${protocolVersion}`); + await waitForScreen(b, replacement.id, `\nafter-protocol-cut-${protocolVersion}`); + await stopDaemon(b); + await waitFor( + () => !isAlive(replacement.pid) && !isAlive(current.pid), + () => "the replacement worker or program outlived daemon stop", + ); + assert.deepEqual(workerRecords(), [], "no worker record is left"); + assert.deepEqual(runtimeCopies(), [], "no copy is left"); + console.log("✓ obsolete closed, current usable, copies cleaned up\n"); + } + + console.log("Test 5: a worker from a newer Paseo is left running and reported"); + const newer = await leaveWorkerWithProtocol(a, currentProtocolVersion + 1, "newer"); + await startDaemon(b); + const listed = await run(b, ["terminal", "ls", "--all", "--json"]); + assert.notEqual(listed.exitCode, 0, "terminal ls fails"); + assert.match(listed.stdout + listed.stderr, /held by a newer Paseo \(v0\.98\.0/); + const created = await run(b, ["terminal", "create", "--cwd", workDir, "--json"]); + assert.notEqual(created.exitCode, 0, "terminal create fails"); + assert.match(created.stdout + created.stderr, /held by a newer Paseo/); + const status = await paseo(b, ["daemon", "status", "--home", paseoHome]); + assert.match(status.stdout, /terminals: Terminals are held by a newer Paseo/); + assert(isAlive(newer.terminal.pid), "its program keeps running"); + assert.deepEqual( + workerRecords().map((record) => record.pid), + [newer.workerPid], + "no second worker starts", + ); + await stopDaemon(b); + await waitFor( + () => !isAlive(newer.workerPid) && !isAlive(newer.terminal.pid), + () => "daemon stop left the newer worker or its terminal running", + ); + assert.deepEqual(workerRecords(), [], "no worker record is left"); + assert.deepEqual(runtimeCopies(), [], "no copy is left"); + console.log("✓ reported, untouched, closed by stop\n"); + passed = true; +} finally { + if (!passed) { + for (const log of ["daemon.log", "terminal-worker.log"]) { + const logPath = join(paseoHome, log); + if (existsSync(logPath)) { + console.error(`--- ${log} (last 60 lines) ---`); + console.error(readFileSync(logPath, "utf8").split("\n").slice(-60).join("\n")); + } + } + } + if (competingListener.listening) { + await new Promise((resolve, reject) => + competingListener.close((error) => { + if (error) { + reject(error); + return; + } + resolve(); + }), + ); + } + restoreA?.(); + for (const installation of [b, a]) { + await run(installation, ["daemon", "stop", "--home", paseoHome, "--force"]); + } + for (const pid of trackedPids) { + if (isAlive(pid)) process.kill(pid, "SIGKILL"); + } + await rm(root, { recursive: true, force: true }); +} + +console.log("=== Terminal worker survives an upgrade passed ==="); diff --git a/packages/cli/tests/helpers/test-daemon.ts b/packages/cli/tests/helpers/test-daemon.ts index 5b5513d1a7..cfc9a87fb1 100644 --- a/packages/cli/tests/helpers/test-daemon.ts +++ b/packages/cli/tests/helpers/test-daemon.ts @@ -18,7 +18,7 @@ import { tmpdir } from "os"; import { join } from "path"; import { fileURLToPath } from "url"; import { ChildProcess, spawn } from "child_process"; -import { getAvailablePort } from "./network.ts"; +import { readDaemonInstance } from "@getpaseo/server/daemon-control"; export interface TestDaemonContext { /** Available local port for test daemon (never 6767) */ @@ -195,17 +195,20 @@ async function probeDaemonReady( } async function waitForDaemonReady( - port: number, paseoHome: string, timeout = 30000, env?: NodeJS.ProcessEnv, -): Promise { +): Promise { const deadline = Date.now() + timeout; - async function poll(): Promise { - if (await probeDaemonReady(port, paseoHome, env)) return; + async function poll(): Promise { + const instance = await readDaemonInstance(paseoHome); + if (instance?.listen) { + const port = Number(new URL(`http://${instance.listen}`).port); + if (await probeDaemonReady(port, paseoHome, env)) return port; + } if (Date.now() >= deadline) { - throw new Error(`Daemon failed to become ready on port ${port} within ${timeout}ms`); + throw new Error(`Daemon failed to publish a ready endpoint within ${timeout}ms`); } await sleep(100); return poll(); @@ -231,15 +234,14 @@ export async function startTestDaemon(options?: { timeout?: number; env?: NodeJS.ProcessEnv; }): Promise { - const port = options?.port ?? (await getAvailablePort()); + // Let the listening process allocate its port, without a reserve/release race. + const requestedPort = options?.port ?? 0; const { paseoHome, workDir } = options?.paseoHome && options?.workDir ? { paseoHome: options.paseoHome, workDir: options.workDir } : await createTempDirs(); const timeout = options?.timeout ?? 30000; - const wsUrl = `ws://${TEST_DAEMON_HOST}:${port}`; - // Find the CLI entry point - use the source file directly with tsx const cliDir = join(import.meta.dirname, "..", ".."); const cliSrcPath = join(cliDir, "src", "index.ts"); @@ -252,7 +254,7 @@ export async function startTestDaemon(options?: { ), ...TEST_DAEMON_ENV_DEFAULTS, PASEO_HOME: paseoHome, - PASEO_LISTEN: `${TEST_DAEMON_HOST}:${port}`, + PASEO_LISTEN: `${TEST_DAEMON_HOST}:${requestedPort}`, // Force no TTY to prevent QR code output CI: "true", ...options?.env, @@ -312,20 +314,18 @@ export async function startTestDaemon(options?: { } }); - const ctx: TestDaemonContext = { - port, - wsUrl, - paseoHome, - workDir, - process: daemonProcess, - isReady: false, - stop: cleanup, - }; - // Wait for daemon to be ready try { - await waitForDaemonReady(port, paseoHome, timeout, options?.env); - ctx.isReady = true; + const port = await waitForDaemonReady(paseoHome, timeout, options?.env); + return { + port, + wsUrl: `ws://${TEST_DAEMON_HOST}:${port}`, + paseoHome, + workDir, + process: daemonProcess, + isReady: true, + stop: cleanup, + }; } catch (err) { // Daemon failed to start - clean up and rethrow await cleanup(); @@ -335,8 +335,6 @@ export async function startTestDaemon(options?: { { cause: err }, ); } - - return ctx; } /** diff --git a/packages/client/package.json b/packages/client/package.json index df80ba532c..19c0490021 100644 --- a/packages/client/package.json +++ b/packages/client/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/client", - "version": "0.13.2", + "version": "0.15.0-beta.1", "description": "Paseo client SDK package", "files": [ "dist", @@ -47,8 +47,8 @@ "test": "vitest run" }, "dependencies": { - "@getpaseo/protocol": "0.13.2", - "@getpaseo/relay": "0.13.2", + "@getpaseo/protocol": "0.15.0-beta.1", + "@getpaseo/relay": "0.15.0-beta.1", "ws": "^8.20.0", "zod": "^4.4.3" }, diff --git a/packages/client/src/connection/index.ts b/packages/client/src/connection/index.ts index eda2fec26b..62753bca5c 100644 --- a/packages/client/src/connection/index.ts +++ b/packages/client/src/connection/index.ts @@ -125,6 +125,8 @@ export class ConnectionSubscriptions extends OwnedSubscriptions { // Protocol support belongs to the installed client. Only browser hosting needs // a resource supplied by the caller. Keep this exhaustive as the protocol evolves. export const DEFAULT_CLIENT_CAPABILITIES = { + [CLIENT_CAPS.terminalChunkedReplay]: true, + [CLIENT_CAPS.binaryChunkingV1]: true, [CLIENT_CAPS.helloRejection]: true, [CLIENT_CAPS.ownedSubscriptions]: true, [CLIENT_CAPS.allProviders]: true, diff --git a/packages/client/src/daemon-client-relay-e2ee-transport.ts b/packages/client/src/daemon-client-relay-e2ee-transport.ts index 258c0aa9b5..0faecdcb5e 100644 --- a/packages/client/src/daemon-client-relay-e2ee-transport.ts +++ b/packages/client/src/daemon-client-relay-e2ee-transport.ts @@ -1,3 +1,4 @@ +import { maxSecuredPlaintextByteLength } from "@getpaseo/relay"; import { MAX_RELAY_WEBSOCKET_MESSAGE_BYTES } from "@getpaseo/protocol/websocket-message-limit"; import { openClientSecureChannel, @@ -155,18 +156,15 @@ export function createEncryptedTransport( const relayTransport: RelayTransport = { send: (data) => { if (typeof data === "string") { - base.send(data); - return; + return base.send(data); } if (ArrayBuffer.isView(data)) { - base.send(normalizeTransportPayload(data)); - return; + return base.send(normalizeTransportPayload(data)); } if (data instanceof ArrayBuffer) { - base.send(data); - return; + return base.send(data); } - base.send(String(data)); + return base.send(String(data)); }, // The channel decides the close code. Report it now: a socket close event // arrives asynchronously, and the consumer must not act on an earlier @@ -226,6 +224,8 @@ export function createEncryptedTransport( }); return { + supportsDrain: base.supportsDrain, + maxFrameBytes: maxSecuredPlaintextByteLength(MAX_RELAY_WEBSOCKET_MESSAGE_BYTES), send: (data) => { if (!channel) { throw new Error("Encrypted channel not ready"); @@ -239,8 +239,9 @@ export function createEncryptedTransport( // Encryption and its transport handoff are synchronous up to send's first await. // Reject capacity failures here so a routed sender loses only its own channel. assertOutboundCapacity(wireBytes); - void channel.send(payload).catch((error) => { + return channel.send(payload).catch((error) => { emitError(error); + throw error; }); }, close: (code?: number, reason?: string) => { diff --git a/packages/client/src/daemon-client-transport-types.ts b/packages/client/src/daemon-client-transport-types.ts index ddcb57246b..64f84cf8c1 100644 --- a/packages/client/src/daemon-client-transport-types.ts +++ b/packages/client/src/daemon-client-transport-types.ts @@ -1,5 +1,8 @@ export interface DaemonTransport { - send: (data: string | Uint8Array | ArrayBuffer) => void; + /** False when the underlying socket cannot report write drain. */ + supportsDrain?: boolean; + maxFrameBytes?: number; + send: (data: string | Uint8Array | ArrayBuffer) => void | Promise; close: (code?: number, reason?: string) => void; onMessage: (handler: (data: unknown, isBinary: boolean) => void) => () => void; onOpen: (handler: () => void) => () => void; @@ -13,12 +16,16 @@ export type DaemonTransportFactory = (options: { protocols?: string[]; }) => DaemonTransport; -export type WebSocketFactory = ( - url: string, - options?: { headers?: Record; protocols?: string[] }, -) => WebSocketLike; +export interface WebSocketFactory { + ( + url: string, + options?: { headers?: Record; protocols?: string[] }, + ): WebSocketLike; + supportsDrain?: boolean; +} export interface WebSocketLike { + bufferedAmount?: number; readyState: number; send: (data: string | Uint8Array | ArrayBuffer) => void; close: (code?: number, reason?: string) => void; diff --git a/packages/client/src/daemon-client-transport.test.ts b/packages/client/src/daemon-client-transport.test.ts index 963a8b541c..c95c534129 100644 --- a/packages/client/src/daemon-client-transport.test.ts +++ b/packages/client/src/daemon-client-transport.test.ts @@ -175,3 +175,18 @@ describe("daemon-client transport helpers", () => { expect(decodeMessageData(bytes)).toBe("hello"); }); }); + +test("native drain capability survives WebSocket and encryption wrappers", async () => { + const { nativeWebSocketFactory } = await import("./daemon-client-websocket-transport.js"); + expect(nativeWebSocketFactory.supportsDrain).toBe(false); + const factory = Object.assign(() => ({ readyState: 1, send() {}, close() {} }), { + supportsDrain: false, + }); + const base = createWebSocketTransportFactory(factory)({ url: "ws://test" }); + expect(base.supportsDrain).toBe(false); + const encrypted = createEncryptedTransport(base, { + daemonPublicKeyB64: "unused-key", + logger: { warn() {} }, + }); + expect(encrypted.supportsDrain).toBe(false); +}); diff --git a/packages/client/src/daemon-client-websocket-transport.ts b/packages/client/src/daemon-client-websocket-transport.ts index f5734b4b51..c7ec87555d 100644 --- a/packages/client/src/daemon-client-websocket-transport.ts +++ b/packages/client/src/daemon-client-websocket-transport.ts @@ -39,6 +39,9 @@ export function nativeWebSocketFactory( return new (getGlobalWebSocket())(url, options?.protocols, { headers: options?.headers }); } +// React Native leaves bufferedAmount at zero, including while native output is queued. +nativeWebSocketFactory.supportsDrain = false; + export function createWebSocketTransportFactory(factory: WebSocketFactory): DaemonTransportFactory { return ({ url, headers, protocols }) => { const ws = factory(url, { headers, protocols }); @@ -50,11 +53,28 @@ export function createWebSocketTransportFactory(factory: WebSocketFactory): Daem } } return { + supportsDrain: factory.supportsDrain !== false, send: (data) => { if (typeof ws.readyState === "number" && ws.readyState !== 1) { throw new Error(`WebSocket not open (readyState=${ws.readyState})`); } ws.send(data); + if ((ws.bufferedAmount ?? 0) > 1024 * 1024) { + return new Promise((resolve, reject) => { + const drain = () => { + if (ws.readyState !== 1) { + reject(new Error("WebSocket closed while draining")); + return; + } + if ((ws.bufferedAmount ?? 0) <= 1024 * 1024) { + resolve(); + return; + } + setTimeout(drain, 10); + }; + drain(); + }); + } }, close: (code?: number, reason?: string) => { // Node's `ws` may emit an `error` when a connecting socket is closed before the diff --git a/packages/client/src/daemon-client.test.ts b/packages/client/src/daemon-client.test.ts index f663aeb8be..4fa7d5723c 100644 --- a/packages/client/src/daemon-client.test.ts +++ b/packages/client/src/daemon-client.test.ts @@ -1,5 +1,5 @@ import { readFileSync } from "node:fs"; -import { afterEach, expect, expectTypeOf, test, vi } from "vitest"; +import { afterEach, describe, expect, expectTypeOf, test, vi } from "vitest"; import { z } from "zod"; import { DaemonClient, @@ -9,8 +9,11 @@ import { type CreateAgentRequestOptions, type DaemonTransport, type Logger, + type PluginClientBundle, + type PluginClientBundleStore, } from "./daemon-client"; import { CLIENT_CAPS } from "@getpaseo/protocol/client-capabilities"; +import { ChunkedTransport } from "@getpaseo/protocol/chunked-transport"; import { BROWSER_AUTOMATION_COMMAND_NAMES } from "@getpaseo/protocol/browser-automation/rpc-schemas"; import { decodeFileTransferFrame, @@ -1092,6 +1095,7 @@ test("advertises client capabilities in hello", async () => { provider_snapshot_references: true, explicit_event_subscriptions: true, owned_subscriptions: true, + binary_chunking_v1: true, compact_provider_snapshots: true, custom_mode_icons: true, project_updates: true, @@ -1099,6 +1103,7 @@ test("advertises client capabilities in hello", async () => { projected_subagent_timeline: true, reasoning_merge_enum: true, terminal_reflowable_snapshot: true, + terminal_chunked_replay: true, timeline_notifications: true, plugin_timeline_items: true, workspace_setup_blocked: true, @@ -1640,6 +1645,77 @@ test("preserves legacy fetchAgent id overload", async () => { await expect(responsePromise).rejects.toThrow("legacy fetch sentinel"); }); +test.each([undefined, false, true])( + "loads history with whole-turn support advertised as %s", + async (wholeTurnTimeline) => { + const transport = createMockTransport(); + const client = new DaemonClient({ + url: "ws://test", + clientId: "history-compatibility", + reconnect: { enabled: false }, + transportFactory: () => transport.transport, + }); + clients.push(client); + const connected = client.connect(); + transport.triggerOpen({ + features: wholeTurnTimeline === undefined ? {} : { wholeTurnTimeline }, + }); + await connected; + + const requests = [ + { direction: "tail" as const }, + { direction: "before" as const, cursor: { epoch: "epoch-1", seq: 50 } }, + { direction: "after" as const, cursor: { epoch: "epoch-1", seq: 50 } }, + { direction: "before" as const, cursor: { epoch: "epoch-1", seq: 80 }, mergeWindow: true }, + ]; + for (const [index, request] of requests.entries()) { + const requestId = `history-${index}`; + const result = client.fetchAgentTimeline("agent-1", { + ...request, + requestId, + wholeTurns: true, + limit: 40, + projection: "projected", + }); + // Attach immediately so the old rejection is captured by the regression. + const completed = expect(result).resolves.toMatchObject({ requestId, entries: [] }); + expect(parseSentFrame(transport.sent.at(-1))).toEqual({ + type: "fetch_agent_timeline_request", + agentId: "agent-1", + requestId, + ...request, + limit: 40, + projection: "projected", + ...(wholeTurnTimeline === true ? { wholeTurns: true } : {}), + }); + transport.triggerMessage( + wrapSessionMessage({ + type: "fetch_agent_timeline_response", + payload: { + requestId, + agentId: "agent-1", + agent: null, + direction: request.direction, + projection: "projected", + epoch: "epoch-1", + reset: false, + staleCursor: false, + gap: false, + window: { minSeq: 0, maxSeq: 0, nextSeq: 1 }, + startCursor: null, + endCursor: null, + hasOlder: false, + hasNewer: false, + entries: [], + error: null, + }, + }), + ); + await completed; + } + }, +); + test("honors explicit fetchAgentTimeline timeout below the session RPC default", async () => { useHeartbeatClock(); const logger = createMockLogger(); @@ -2028,6 +2104,188 @@ test("gets a structured plugin log snapshot", async () => { ]); }); +describe("plugin catalog", () => { + async function connectedClient(createStore?: (serverId: string) => PluginClientBundleStore) { + const mock = createMockTransport(); + const client = new DaemonClient({ + url: "ws://test", + clientId: "clsk_unit_test", + logger: createMockLogger(), + createPluginClientBundleStore: createStore, + reconnect: { enabled: false }, + transportFactory: () => mock.transport, + }); + clients.push(client); + const connectPromise = client.connect(); + mock.triggerOpen({ features: { plugins: true } }); + await connectPromise; + return { client, mock }; + } + + async function fetchCatalog( + harness: Awaited>, + respond: (request: Record) => Array>, + ) { + const before = harness.mock.sent.length; + const response = harness.client.getPluginCatalog(); + await vi.waitFor(() => expect(harness.mock.sent.length).toBeGreaterThan(before)); + const request = parseSentFrame(harness.mock.sent.at(-1)); + harness.mock.triggerMessage( + wrapSessionMessage({ + type: "plugin.catalog.get.response", + payload: { requestId: request.requestId, plugins: respond(request) }, + }), + ); + return { request, plugins: await response }; + } + + test("reuses retained client bundles the daemon leaves out", async () => { + const harness = await connectedClient(); + const first = await fetchCatalog(harness, () => [ + { id: "kept", clientBundle: "kept bundle", clientBundleHash: "hash-kept" }, + { id: "changed", clientBundle: "old bundle", clientBundleHash: "hash-old" }, + ]); + expect(first.request).not.toHaveProperty("cachedClientBundles"); + + const second = await fetchCatalog(harness, () => [ + { id: "kept", clientBundleHash: "hash-kept" }, + { id: "changed", clientBundle: "new bundle", clientBundleHash: "hash-new" }, + ]); + + expect(second.request.cachedClientBundles).toEqual([ + { id: "kept", clientBundleHash: "hash-kept" }, + { id: "changed", clientBundleHash: "hash-old" }, + ]); + expect(second.plugins).toEqual([ + { id: "kept", clientBundle: "kept bundle", clientBundleHash: "hash-kept" }, + { id: "changed", clientBundle: "new bundle", clientBundleHash: "hash-new" }, + ]); + const third = await fetchCatalog(harness, () => []); + expect(third.request.cachedClientBundles).toEqual([ + { id: "kept", clientBundleHash: "hash-kept" }, + { id: "changed", clientBundleHash: "hash-new" }, + ]); + const fourth = await fetchCatalog(harness, () => []); + expect(fourth.request).not.toHaveProperty("cachedClientBundles"); + }); + + test("keeps fetching every bundle from a daemon that sends no bundle hashes", async () => { + const harness = await connectedClient(); + const legacyCatalog = () => [{ id: "legacy", clientBundle: "legacy bundle" }]; + await fetchCatalog(harness, legacyCatalog); + + const second = await fetchCatalog(harness, legacyCatalog); + + expect(second.request).not.toHaveProperty("cachedClientBundles"); + expect(second.plugins).toEqual([{ id: "legacy", clientBundle: "legacy bundle" }]); + }); + + test("a fresh client advertises persisted bundles on its first fetch and expands omitted code", async () => { + let persisted: PluginClientBundle[] = []; + let loads = 0; + const store: PluginClientBundleStore = { + async load() { + loads++; + return persisted; + }, + async replace(bundles) { + persisted = bundles; + }, + }; + const createdFor: string[] = []; + const createStore = (serverId: string) => { + createdFor.push(serverId); + return store; + }; + const bundle = { id: "kept", clientBundleHash: "hash-kept", clientBundle: "stored code" }; + const warm = await connectedClient(createStore); + await fetchCatalog(warm, () => [bundle]); + const cold = await connectedClient(createStore); + const first = await fetchCatalog(cold, () => [{ id: "kept", clientBundleHash: "hash-kept" }]); + expect(first.request.cachedClientBundles).toEqual([ + { id: "kept", clientBundleHash: "hash-kept" }, + ]); + expect(first.plugins).toEqual([bundle]); + expect(loads).toBe(2); + await fetchCatalog(cold, () => []); + expect(loads).toBe(2); + expect(createdFor).toEqual([ + warm.client.getLastServerInfoMessage()!.serverId, + cold.client.getLastServerInfoMessage()!.serverId, + ]); + expect(persisted).toEqual([]); + }); + + test.each(["missing", "unreadable"])( + "a %s persistent cache requests full bundles", + async (state) => { + const store: PluginClientBundleStore = { + async load() { + if (state === "unreadable") throw new Error("Storage unavailable"); + return []; + }, + async replace() {}, + }; + const bundle = { id: "full", clientBundleHash: "hash-full", clientBundle: "full code" }; + const result = await fetchCatalog(await connectedClient(() => store), () => [bundle]); + expect(result.request).not.toHaveProperty("cachedClientBundles"); + expect(result.plugins).toEqual([bundle]); + }, + ); + + test("failed cache writes never fail plugin loading", async () => { + const store: PluginClientBundleStore = { + async load() { + return []; + }, + async replace() { + throw new Error("Disk full"); + }, + }; + const bundle = { id: "full", clientBundleHash: "hash-full", clientBundle: "full code" }; + expect( + (await fetchCatalog(await connectedClient(() => store), () => [bundle])).plugins, + ).toEqual([bundle]); + }); + + test.each([false, true])( + "usable catalogs do not wait for storage; latest write survives a failed first write: %s", + async (failFirstWrite) => { + const writes: PluginClientBundle[][] = []; + let finishWrite = () => {}; + const blockedWrite = new Promise((resolve) => { + finishWrite = resolve; + }); + const store: PluginClientBundleStore = { + async load() { + return []; + }, + async replace(bundles) { + writes.push(bundles); + if (writes.length === 1) { + await blockedWrite; + if (failFirstWrite) throw new Error("Disk full"); + } + }, + }; + const harness = await connectedClient(() => store); + const first = { id: "plugin", clientBundle: "old", clientBundleHash: "hash-old" }; + const changed = { id: "plugin", clientBundle: "new", clientBundleHash: "hash-new" }; + try { + expect((await fetchCatalog(harness, () => [first])).plugins).toEqual([first]); + await vi.waitFor(() => expect(writes).toEqual([[first]])); + expect((await fetchCatalog(harness, () => [changed])).plugins).toEqual([changed]); + expect((await fetchCatalog(harness, () => [])).plugins).toEqual([]); + expect(writes).toEqual([[first]]); + finishWrite(); + await vi.waitFor(() => expect(writes).toEqual([[first], []])); + } finally { + finishWrite(); + } + }, + ); +}); + test("keeps a plugin reload pending past the session RPC deadline", async () => { useHeartbeatClock(); try { @@ -6132,66 +6390,80 @@ test("emits output events for the active terminal stream", async () => { unsubscribe(); }); -test("emits snapshot events for the subscribed terminal stream", async () => { - const logger = createMockLogger(); - const mock = createMockTransport(); +test.each([5, 500, 10000])( + "preserves explicit %s history demand on an old ANSI host and normalizes restore", + async (history) => { + const logger = createMockLogger(); + const mock = createMockTransport(); - const client = new DaemonClient({ - url: "ws://test", - clientId: "clsk_unit_test", - logger, - reconnect: { enabled: false }, - transportFactory: () => mock.transport, - }); - clients.push(client); + const client = new DaemonClient({ + url: "ws://test", + clientId: "clsk_unit_test", + logger, + reconnect: { enabled: false }, + transportFactory: () => mock.transport, + }); + clients.push(client); - const connectPromise = client.connect(); - mock.triggerOpen(); - await connectPromise; + const connectPromise = client.connect(); + mock.triggerOpen(); + await connectPromise; - const snapshots: unknown[] = []; - client.onTerminalStreamEvent((event) => { - if (event.type !== "snapshot") { - return; - } - snapshots.push(event.state); - }); + const events: unknown[] = []; + const replayEvents: unknown[] = []; + client.onTerminalStreamEvent((event) => { + if (event.type === "replay") replayEvents.push(event.replay); + events.push(event); + }); - const subscribePromise = client.subscribeTerminal("term-1", { requestId: "sub-2" }); - await vi.waitFor(() => - expect(parseSentFrame(mock.sent.at(-1)).type).toBe("subscribe_terminal_request"), - ); - mock.triggerMessage( - wrapSessionMessage({ - type: "subscribe_terminal_response", - payload: { - subscriptionId: "server-" + String(parseSentFrame(mock.sent.at(-1)).requestId), - terminalId: "term-1", + const subscribePromise = client.subscribeTerminal("term-1", { + requestId: "sub-2", + restore: { mode: "visible-snapshot", scrollbackLines: history }, + }); + await vi.waitFor(() => + expect(parseSentFrame(mock.sent.at(-1)).type).toBe("subscribe_terminal_request"), + ); + expect(parseSentFrame(mock.sent.at(-1)).restore).toEqual({ + mode: "visible-snapshot", + scrollbackLines: history, + }); + mock.triggerMessage( + wrapSessionMessage({ + type: "subscribe_terminal_response", + payload: { + subscriptionId: "server-" + String(parseSentFrame(mock.sent.at(-1)).requestId), + terminalId: "term-1", + slot: 12, + error: null, + requestId: "sub-2", + }, + }), + ); + await subscribePromise; + + const state = { + rows: 1, + cols: 5, + grid: [[{ char: "h" }, { char: "e" }, { char: "l" }, { char: "l" }, { char: "o" }]], + scrollback: [], + cursor: { row: 0, col: 5 }, + }; + mock.triggerMessage( + encodeTerminalStreamFrame({ + opcode: TerminalStreamOpcode.Snapshot, slot: 12, - error: null, - requestId: "sub-2", - }, - }), - ); - await subscribePromise; + payload: encodeTerminalSnapshotPayload(state), + }), + ); - const state = { - rows: 1, - cols: 5, - grid: [[{ char: "h" }, { char: "e" }, { char: "l" }, { char: "l" }, { char: "o" }]], - scrollback: [], - cursor: { row: 0, col: 5 }, - }; - mock.triggerMessage( - encodeTerminalStreamFrame({ - opcode: TerminalStreamOpcode.Snapshot, - slot: 12, - payload: encodeTerminalSnapshotPayload(state), - }), - ); - - expect(snapshots).toEqual([state]); -}); + expect(events).toEqual([]); + const data = new TextEncoder().encode("\x1b[31mold ANSI host界🙂"); + mock.triggerMessage( + encodeTerminalStreamFrame({ opcode: TerminalStreamOpcode.Restore, slot: 12, payload: data }), + ); + expect(replayEvents).toEqual([{ type: "begin" }, { type: "data", data }, { type: "end" }]); + }, +); test("sends explicit terminal input and resize commands", async () => { const logger = createMockLogger(); @@ -6562,91 +6834,101 @@ test("drops legacy agent_stream tool_call payloads and logs validation warning", expect(logger.warn).toHaveBeenCalled(); }); -test("parses canonical fetch_agent_timeline_response payloads without crashing", async () => { - const logger = createMockLogger(); - const mock = createMockTransport(); +test.each([false, true])( + "parses canonical timeline responses with chunking=%s", + async (chunked) => { + const logger = createMockLogger(); + const mock = createMockTransport(); - const client = new DaemonClient({ - url: "ws://test", - clientId: "clsk_unit_test", - logger, - reconnect: { enabled: false }, - transportFactory: () => mock.transport, - }); - clients.push(client); + const client = new DaemonClient({ + url: "ws://test", + clientId: "clsk_unit_test", + logger, + reconnect: { enabled: false }, + transportFactory: () => mock.transport, + }); + clients.push(client); - const connectPromise = client.connect(); - mock.triggerOpen(); - await connectPromise; + const connectPromise = client.connect(); + mock.triggerOpen({ features: { ownedSubscriptions: true, binaryChunkingV1: chunked } }); + await connectPromise; - const received: unknown[] = []; - const unsubscribe = client.on("fetch_agent_timeline_response", (msg) => { - received.push(msg); - }); + const received: unknown[] = []; + const unsubscribe = client.on("fetch_agent_timeline_response", (msg) => { + received.push(msg); + }); - mock.triggerMessage( - wrapSessionMessage({ - type: "fetch_agent_timeline_response", + const command = chunked ? "x".repeat(50 * 1024 * 1024) : "pwd"; + const sender = new ChunkedTransport({ + frameBytes: 24 * 1024 * 1024, + send: (frame) => mock.triggerMessage(frame), + deliver: () => {}, + }); + sender.enabled = chunked; + await sender.send( + wrapSessionMessage({ + type: "fetch_agent_timeline_response", + payload: { + requestId: "req-1", + agentId: "agent_cli", + agent: null, + direction: "tail", + projection: "projected", + epoch: "epoch-1", + reset: false, + staleCursor: false, + gap: false, + window: { minSeq: 1, maxSeq: 1, nextSeq: 2 }, + startCursor: { epoch: "epoch-1", seq: 1 }, + endCursor: { epoch: "epoch-1", seq: 1 }, + hasOlder: false, + hasNewer: false, + entries: [ + { + timestamp: "2026-02-08T20:20:00.000Z", + provider: "codex", + seqStart: 1, + seqEnd: 1, + sourceSeqRanges: [{ startSeq: 1, endSeq: 1 }], + collapsed: [], + item: { + type: "tool_call", + callId: "call_cli_snapshot", + name: "shell", + status: "running", + detail: { + type: "shell", + command, + }, + error: null, + }, + }, + ], + error: null, + }, + }), + ); + + unsubscribe(); + + expect(received).toHaveLength(1); + expect(received[0]).toMatchObject({ payload: { - requestId: "req-1", - agentId: "agent_cli", - agent: null, - direction: "tail", - projection: "projected", - epoch: "epoch-1", - reset: false, - staleCursor: false, - gap: false, - window: { minSeq: 1, maxSeq: 1, nextSeq: 2 }, - startCursor: { epoch: "epoch-1", seq: 1 }, - endCursor: { epoch: "epoch-1", seq: 1 }, - hasOlder: false, - hasNewer: false, entries: [ { - timestamp: "2026-02-08T20:20:00.000Z", - provider: "codex", - seqStart: 1, - seqEnd: 1, - sourceSeqRanges: [{ startSeq: 1, endSeq: 1 }], - collapsed: [], item: { type: "tool_call", - callId: "call_cli_snapshot", - name: "shell", status: "running", - detail: { - type: "shell", - command: "pwd", - }, error: null, + detail: { type: "shell", command }, }, }, ], - error: null, }, - }), - ); - - unsubscribe(); - - expect(received).toHaveLength(1); - expect(received[0]).toMatchObject({ - payload: { - entries: [ - { - item: { - type: "tool_call", - status: "running", - error: null, - detail: { type: "shell" }, - }, - }, - ], - }, - }); - expect(logger.warn).not.toHaveBeenCalled(); -}); + }); + expect(logger.warn).not.toHaveBeenCalled(); + }, +); test("rejects and logs a correlated response that violates the protocol schema", async () => { const mock = createMockTransport(); @@ -8216,3 +8498,429 @@ test("closes before admission when a protected-capable daemon is reached in lega expect(daemonReceived).toHaveLength(1); expect(JSON.parse(daemonReceived[0] as string)).toMatchObject({ type: "hello" }); }); + +test.each([ + { chunked: false, transportChunked: false }, + { chunked: true, transportChunked: false }, + { chunked: false, transportChunked: true }, + { chunked: true, transportChunked: true }, +])( + "default terminal observation requests ANSI replay (replay=$chunked, transport=$transportChunked)", + async ({ chunked, transportChunked }) => { + const transport = createMockTransport(); + const client = new DaemonClient({ + url: "ws://test", + clientId: "clsk_unit_test", + logger: createMockLogger(), + reconnect: { enabled: false }, + transportFactory: () => transport.transport, + }); + clients.push(client); + const connecting = client.connect(); + transport.triggerOpen({ + preserveSent: true, + features: { + ownedSubscriptions: true, + "terminal-restore-modes": true, + binaryChunkingV1: transportChunked, + }, + }); + await connecting; + const hello = JSON.parse(transport.sent[0] as string); + expect(hello.capabilities[CLIENT_CAPS.terminalChunkedReplay]).toBe(true); + expect(hello.capabilities[CLIENT_CAPS.binaryChunkingV1]).toBe(true); + const wire: Uint8Array[] = []; + const sender = new ChunkedTransport({ + frameBytes: 17, + send: (frame) => { + if (typeof frame === "string") throw new Error("Expected binary terminal frame"); + wire.push(frame); + transport.triggerMessage(frame); + }, + deliver: () => {}, + }); + sender.enabled = transportChunked; + const events: import("./terminal-stream-router").TerminalStreamEvent[] = []; + const observation = client.observeTerminal("default-terminal", (event) => events.push(event)); + await vi.waitFor(() => + expect(parseSentFrame(transport.sent.at(-1)).type).toBe("subscribe_terminal_request"), + ); + const request = parseSentFrame(transport.sent.at(-1)); + expect(request.restore).toEqual({ mode: "full-snapshot" }); + transport.triggerMessage( + wrapSessionMessage({ + type: "subscribe_terminal_response", + payload: { + terminalId: "default-terminal", + requestId: request.requestId, + subscriptionId: "default-subscription", + slot: 2, + error: null, + }, + }), + ); + await observation.ready; + const data = new TextEncoder().encode("\x1b[31mretained 界🙂\x1b[0m"); + const metadata = { rows: 24, cols: 80, retainedHistoryLines: 1000 }; + if (chunked) { + await sender.send( + encodeTerminalStreamFrame({ + opcode: TerminalStreamOpcode.ReplayBegin, + slot: 2, + payload: JSON.stringify(metadata), + }), + ); + await sender.send( + encodeTerminalStreamFrame({ + opcode: TerminalStreamOpcode.ReplayData, + slot: 2, + payload: data, + }), + ); + await sender.send( + encodeTerminalStreamFrame({ opcode: TerminalStreamOpcode.ReplayEnd, slot: 2 }), + ); + } else { + // An ANSI-era host selects its existing Restore path for this explicit request. + await sender.send( + encodeTerminalStreamFrame({ opcode: TerminalStreamOpcode.Restore, slot: 2, payload: data }), + ); + } + if (transportChunked) { + expect(wire.length).toBeGreaterThan(chunked ? 3 : 1); + expect(wire.some((frame) => frame[0] === 0x31)).toBe(true); + expect(wire.every((frame) => frame.length <= 17)).toBe(true); + } else { + expect(wire.map((frame) => frame[0])).toEqual(chunked ? [6, 7, 8] : [5]); + } + expect(events).toEqual([ + { + terminalId: "default-terminal", + subscriptionId: "default-subscription", + type: "replay", + replay: chunked ? { type: "begin", ...metadata } : { type: "begin" }, + }, + { + terminalId: "default-terminal", + subscriptionId: "default-subscription", + type: "replay", + replay: { type: "data", data }, + }, + { + terminalId: "default-terminal", + subscriptionId: "default-subscription", + type: "replay", + replay: { type: "end" }, + }, + ]); + const live = new TextEncoder().encode("live after replay 界🙂"); + await sender.send( + encodeTerminalStreamFrame({ opcode: TerminalStreamOpcode.Output, slot: 2, payload: live }), + ); + expect(events.at(-1)).toEqual({ + terminalId: "default-terminal", + subscriptionId: "default-subscription", + type: "output", + data: live, + }); + }, +); + +test("uses the frame budget selected by an asynchronously opened transport", async () => { + const mock = createMockTransport(); + mock.transport.maxFrameBytes = 1024; + const client = new DaemonClient({ + url: "ws://test", + clientId: "dynamic-budget", + transportFactory: () => mock.transport, + reconnect: { enabled: false }, + }); + clients.push(client); + const connecting = client.connect(); + mock.transport.maxFrameBytes = 16; + mock.triggerOpen({ features: { binaryChunkingV1: true } }); + await connecting; + client.sendHostFrame("route", new Uint8Array(100)); + await vi.waitFor(() => expect(mock.sent.length).toBeGreaterThan(1)); + expect(mock.sent.every((frame) => typeof frame !== "string" && frame.byteLength <= 16)).toBe( + true, + ); +}); + +test.each([false, true])("routed sends wait for origin drain (binary=%s)", async (binary) => { + const mock = createMockTransport(); + let drain!: () => void; + let blocked = false; + const send = mock.transport.send; + mock.transport.send = (frame) => { + send(frame); + if (blocked) + return new Promise((resolve) => { + drain = resolve; + }); + }; + const client = new DaemonClient({ + url: "ws://test", + clientId: "routed-drain", + transportFactory: () => mock.transport, + reconnect: { enabled: false }, + }); + clients.push(client); + const connecting = client.connect(); + mock.triggerOpen({ features: { binaryChunkingV1: true } }); + await connecting; + blocked = true; + let finished = false; + const write = Promise.resolve( + client.sendHostFrame("route", binary ? new Uint8Array([1]) : "hello"), + ).then(() => { + finished = true; + return undefined; + }); + await Promise.resolve(); + expect(finished).toBe(false); + drain(); + await write; + expect(finished).toBe(true); +}); + +test("a queued admission failure rejects its RPC without closing the client", async () => { + const mock = createMockTransport(); + const send = mock.transport.send; + let block = false; + let drain!: () => void; + mock.transport.send = (frame) => { + if (!block) return send(frame); + if (typeof frame !== "string") + return new Promise((resolve) => { + drain = resolve; + }); + throw new Error("capacity"); + }; + const client = new DaemonClient({ + url: "ws://test", + clientId: "queued-admission", + transportFactory: () => mock.transport, + reconnect: { enabled: false }, + }); + clients.push(client); + const connecting = client.connect(); + mock.triggerOpen(); + await connecting; + block = true; + const first = client.sendHostFrame("route", new Uint8Array([1])); + const ping = client.ping({ timeoutMs: 1000 }); + void ping.catch(() => {}); + drain(); + await first; + await expect(ping).rejects.toThrow("capacity"); + expect(client.isConnected).toBe(true); +}); + +test("RPC deadlines remain active while a preceding frame waits for drain", async () => { + const mock = createMockTransport(); + const send = mock.transport.send; + let blocked = false; + let drain!: () => void; + mock.transport.send = (frame) => { + if (!blocked) return send(frame); + if (typeof frame !== "string") + return new Promise((resolve) => { + drain = resolve; + }); + }; + const client = new DaemonClient({ + url: "ws://test", + clientId: "drain-deadline", + transportFactory: () => mock.transport, + reconnect: { enabled: false }, + }); + clients.push(client); + const connecting = client.connect(); + mock.triggerOpen(); + await connecting; + blocked = true; + const first = client.sendHostFrame("route", new Uint8Array([1])); + try { + await expect(client.ping({ timeoutMs: 20 })).rejects.toThrow("Timeout waiting for message"); + expect(client.isConnected).toBe(true); + } finally { + drain(); + await first; + } +}); + +test.each([false, true])( + "event listener errors do not close the transport (chunked=%s)", + async (chunked) => { + const mock = createMockTransport(); + const closed = vi.fn(); + mock.transport.close = closed; + const client = new DaemonClient({ + url: "ws://test", + clientId: "listener-error", + transportFactory: () => mock.transport, + reconnect: { enabled: false }, + }); + clients.push(client); + const connecting = client.connect(); + mock.triggerOpen({ features: { binaryChunkingV1: chunked } }); + await connecting; + const unsubscribe = client.subscribe(() => { + throw new Error("listener failed"); + }); + const text = wrapSessionMessage({ + type: "agent_deleted", + payload: { agentId: "agent-test", requestId: "listener-test" }, + }); + const payload = new TextEncoder().encode(text); + const frame = chunked ? new Uint8Array([0x31, 1, 0, 3, ...payload]) : text; + expect(() => mock.triggerMessage(frame)).toThrow("listener failed"); + expect(closed).not.toHaveBeenCalled(); + unsubscribe(); + const events: string[] = []; + client.subscribe((event) => { + events.push(event.type); + }); + mock.triggerMessage(frame); + expect(events).toEqual(["agent_deleted"]); + await client.sendHostFrame("route", "still connected"); + expect(client.isConnected).toBe(true); + }, +); + +test("malformed chunk metadata still closes the client transport", async () => { + const mock = createMockTransport(); + const closed = vi.fn(); + mock.transport.close = closed; + const client = new DaemonClient({ + url: "ws://test", + clientId: "malformed-chunk", + transportFactory: () => mock.transport, + reconnect: { enabled: false }, + }); + clients.push(client); + const connecting = client.connect(); + mock.triggerOpen({ features: { binaryChunkingV1: true } }); + await connecting; + mock.triggerMessage(new Uint8Array([0x31, 2, 0, 3, 65])); + expect(closed).toHaveBeenCalledWith(4003, "Invalid chunked transport"); +}); + +test.each([FileTransferOpcode.FileBegin, FileTransferOpcode.FileChunk, FileTransferOpcode.FileEnd])( + "upload stops at a queued pre-write rejection (opcode=%s)", + async (opcode) => { + const mock = createMockTransport(); + const send = mock.transport.send; + let drain!: () => void; + let blocked = false; + const attempts: number[] = []; + mock.transport.send = (frame) => { + if (typeof frame !== "string") { + const decoded = decodeFileTransferFrame(assertUint8Array(frame)); + if (decoded) { + attempts.push(decoded.opcode); + if (decoded.opcode === opcode) throw new Error("upload capacity"); + } else if (blocked) + return new Promise((resolve) => { + drain = resolve; + }); + } + return send(frame); + }; + const client = new DaemonClient({ + url: "ws://test", + clientId: "upload-admission", + transportFactory: () => mock.transport, + reconnect: { enabled: false }, + }); + clients.push(client); + const connecting = client.connect(); + mock.triggerOpen(); + await connecting; + blocked = true; + const first = client.sendHostFrame("route", new Uint8Array([1])); + const upload = client.uploadFile({ + fileName: "file.bin", + mimeType: "application/octet-stream", + bytes: new Uint8Array([1, 2]), + chunkSize: 1, + }); + let rejected: unknown; + void upload.catch((error) => { + rejected = error; + }); + await new Promise((resolve) => setTimeout(resolve, 0)); + drain(); + await first; + await vi.waitFor(() => expect(rejected).toMatchObject({ message: "upload capacity" }), { + timeout: 500, + }); + expect(attempts.at(-1)).toBe(opcode); + expect(client.isConnected).toBe(true); + }, +); + +test.each(["latency", "dictation start", "dictation finish"])( + "queued control send rejection reaches its caller (%s)", + async (operation) => { + const mock = createMockTransport(); + const send = mock.transport.send; + let blocked = false; + let drain!: () => void; + mock.transport.send = (frame) => { + if (!blocked) return send(frame); + if (typeof frame !== "string") + return new Promise((resolve) => { + drain = resolve; + }); + throw new Error("control capacity"); + }; + const client = new DaemonClient({ + url: "ws://test", + clientId: "control-admission", + transportFactory: () => mock.transport, + reconnect: { enabled: false }, + }); + clients.push(client); + const connecting = client.connect(); + mock.triggerOpen(); + await connecting; + blocked = true; + const first = client.sendHostFrame("route", new Uint8Array([1])); + let result: Promise; + if (operation === "latency") result = client.measureLatency({ timeoutMs: 1000 }); + else if (operation === "dictation start") + result = client.startDictationStream("dictation", "pcm"); + else result = client.finishDictationStream("dictation", 0); + const rejected = expect(result).rejects.toThrow("control capacity"); + drain(); + await first; + await rejected; + expect(client.isConnected).toBe(true); + }, +); + +test("routed channels inherit an origin without drain support", async () => { + const { createHostChannelTransport } = await import("./hosts/index.js"); + const mock = createMockTransport(); + mock.transport.supportsDrain = false; + const client = new DaemonClient({ + url: "ws://test", + clientId: "unpaced-route", + transportFactory: () => mock.transport, + reconnect: { enabled: false }, + }); + clients.push(client); + const connecting = client.connect(); + mock.triggerOpen(); + await connecting; + const route = createHostChannelTransport( + client, + "srv_destination", + "scope", + "route", + )({ url: "ws://route" }); + expect(route.supportsDrain).toBe(false); + route.close(); +}); diff --git a/packages/client/src/daemon-client.ts b/packages/client/src/daemon-client.ts index 59d928283f..3aa91f84c7 100644 --- a/packages/client/src/daemon-client.ts +++ b/packages/client/src/daemon-client.ts @@ -1,3 +1,7 @@ +import { + ChunkedTransport, + ChunkedTransportProtocolError, +} from "@getpaseo/protocol/chunked-transport"; import { HOST_ROUTE_OPCODE, encodeHostRouteFrame, @@ -396,6 +400,17 @@ export type DaemonEventHandler = (event: DaemonEvent) => void; export type BrowserAutomationExecuteRequestMessage = BrowserAutomationExecuteRequest; export type BrowserAutomationExecuteResponseMessage = BrowserAutomationExecuteResponse; +export interface PluginClientBundle { + id: string; + clientBundleHash: string; + clientBundle: string; +} + +/** Host-scoped storage. load must return only bundles whose contents have been verified. */ +export interface PluginClientBundleStore { + load(): Promise; + replace(bundles: PluginClientBundle[]): Promise; +} /** Endpoint security negotiated on a relay connection. See docs/relay-endpoint-security.md. */ export type RelaySecurityMode = "legacy" | "protected"; @@ -406,6 +421,8 @@ export interface DaemonClientConfig { sessionPermissions?: import("@getpaseo/protocol/messages").DaemonPermission[]; url: string; clientId: string; + /** Create one cache for the confirmed daemon identity, retained for this client lifetime. */ + createPluginClientBundleStore?: (serverId: string) => PluginClientBundleStore; clientType?: "mobile" | "browser" | "cli" | "mcp" | "hub"; appVersion?: string; runtimeGeneration?: number | null; @@ -686,6 +703,8 @@ export interface FetchAgentOptions { } type LegacyFetchAgentOptions = Omit; export interface FetchAgentTimelineOptions { + /** Prefer whole-turn pages when supported; older hosts retain item-based paging. */ + wholeTurns?: boolean; direction?: FetchAgentTimelineDirection; cursor?: FetchAgentTimelineCursor; limit?: number; @@ -766,6 +785,9 @@ type ShutdownRequestedStatusPayload = z.infer = CorrelatedResponsePayloads[TType]; +type PluginCatalogResponseEntry = + CorrelatedResponsePayload<"plugin.catalog.get.response">["plugins"][number]; +export type PluginCatalogEntry = Omit & { + clientBundle: string; +}; + export class DaemonConnectionError extends Error { readonly serverId?: string; readonly outcome?: "unknown"; @@ -1242,7 +1270,7 @@ function toReasonCode(reason: string | null | undefined): string | null { } interface PendingSend { - send: () => void; + send: () => void | Promise; resolve: () => void; reject: (error: Error) => void; timeoutHandle: ReturnType; @@ -1265,6 +1293,36 @@ export function supportsUsageReports(features: ServerInfoStatusPayload["features return features?.usageSources === true || features?.providerUsageList === true; } +export class TerminalKeepUnsupportedError extends Error { + readonly code = "TERMINALS_KEEP_UNSUPPORTED"; + // Own fields reach the CLI's JSON error output, which desktop reads. + readonly version: string | null; + + constructor(target: string, version: string | null) { + super( + `The daemon at ${target}${version ? ` (v${version})` : ""} closes terminals when it stops. Update it first, or run \`paseo daemon stop\` to stop it and close them.`, + ); + this.name = "TerminalKeepUnsupportedError"; + this.version = version; + } +} + +/** + * Gate for an explicit "keep terminals" stop. Older daemons drop `keepTerminals` and close the + * terminals anyway, so read the capability on the connection that will carry the shutdown and + * refuse before sending it. + */ +// COMPAT(terminalsSurviveRestart): added in v0.12.0, remove gate after 2027-04-21. +export function requireTerminalKeepCapability( + client: Pick, + target: string, +): void { + const serverInfo = client.getLastServerInfoMessage(); + if (serverInfo?.features?.terminalsSurviveRestart !== true) { + throw new TerminalKeepUnsupportedError(target, serverInfo?.version ?? null); + } +} + function buildFetchAgentsRequest( options: FetchAgentsOptions | undefined, requestId: string, @@ -1312,6 +1370,7 @@ export class DaemonClient { failed: (error) => this.logger.error({ err: error }, "Subscription failed"), }); private transport: DaemonTransport | null = null; + private chunkedTransport: ChunkedTransport | null = null; private helloAuth: HelloAuth; private transportCleanup: Array<() => void> = []; private rawMessageListeners: Set<(message: SessionOutboundMessage) => void> = new Set(); @@ -1341,6 +1400,15 @@ export class DaemonClient { private pendingBinaryFileReads = new Map(); private activeBinaryFileTransfers = new Map(); private completedBinaryFileReads = new Map(); + /** The last catalog's client bundles by plugin id, so later catalogs can leave them out. */ + private pluginClientBundles = new Map< + string, + { clientBundleHash: string; clientBundle: string } + >(); + private pluginClientBundleStore: PluginClientBundleStore | undefined; + private pluginClientBundlesLoaded: Promise | undefined; + private pluginClientBundlesWrite: PluginClientBundle[] | undefined; + private pluginClientBundlesWriting = false; private logger: Logger; private pendingSendQueue: PendingSend[] = []; /** @@ -1497,6 +1565,17 @@ export class DaemonClient { }); this.traceConnectionAttempt += 1; this.transport = transport; + this.chunkedTransport = new ChunkedTransport({ + get supportsDrain() { + return transport.supportsDrain; + }, + get frameBytes() { + return transport.maxFrameBytes ?? 32 * 1024 * 1024; + }, + send: (frame) => transport.send(frame), + onFailure: () => transport.close(4003, "Transport send failed"), + deliver: (frame) => this.handleTransportMessage(frame), + }); this.lastServerInfoMessage = null; this.authFailureReasonValue = null; @@ -1603,7 +1682,16 @@ export class DaemonClient { }); }), transport.onMessage((data) => { - if (this.transport === transport) this.handleTransportMessage(data); + if (this.transport !== transport) return; + const bytes = asUint8Array(data); + try { + if (typeof data === "string" || bytes) + this.chunkedTransport!.receive(typeof data === "string" ? data : bytes!); + else this.handleTransportMessage(data); + } catch (error) { + if (!(error instanceof ChunkedTransportProtocolError)) throw error; + transport.close(4003, "Invalid chunked transport"); + } }), ]; } catch (error) { @@ -1804,9 +1892,9 @@ export class DaemonClient { }) ).routeId; } - sendHostFrame(routeId: string, data: string | Uint8Array): void { + sendHostFrame(routeId: string, data: string | Uint8Array): Promise { if (typeof data === "string") { - this.sendSessionMessageStrict({ + return this.sendSessionMessageStrict({ type: "hosts.route.frame.request", routeId, data, @@ -1814,7 +1902,7 @@ export class DaemonClient { }); } else { if (!this.isConnected || !this.transport) throw this.unavailableError(); - this.sendTransportFrame(encodeHostRouteFrame(routeId, data)); + return this.sendTransportFrame(encodeHostRouteFrame(routeId, data)); } } private readonly hostFrameListeners = new Set<(frame: HostRouteFrame) => void>(); @@ -1872,6 +1960,11 @@ export class DaemonClient { // Message Subscription // ============================================================================ + /** Drain capability inherited by transports routed through this connection. */ + get supportsDrain(): boolean { + return this.transport?.supportsDrain !== false; + } + subscribe(handler: DaemonEventHandler): () => void { this.eventListeners.add(handler); return () => { @@ -1980,7 +2073,7 @@ export class DaemonClient { messageType: string, message: unknown, submitted?: () => void, - ): void { + ): Promise { const isOpen = this.config.trace?.isEnabled() === true && this.beginTraceSection("paseo.ws.message.outbound", { @@ -1989,25 +2082,30 @@ export class DaemonClient { ...describeRequestIdentity(message), }); try { - this.sendTransportFrame(JSON.stringify(message), submitted); + return this.sendTransportFrame(JSON.stringify(message), submitted); } finally { this.endTraceSection(isOpen); } } - private sendSessionPayload(payload: SessionInboundMessage): void { - this.sendJsonMessage("session", payload.type, { type: "session", message: payload }, () => { - if (!("requestId" in payload) || typeof payload.requestId !== "string") return; - for (const waiter of this.waiters) { - if (waiter.requestId === payload.requestId) waiter.submitted = true; - } - }); + private sendSessionPayload(payload: SessionInboundMessage): Promise { + return this.sendJsonMessage( + "session", + payload.type, + { type: "session", message: payload }, + () => { + if (!("requestId" in payload) || typeof payload.requestId !== "string") return; + for (const waiter of this.waiters) { + if (waiter.requestId === payload.requestId) waiter.submitted = true; + } + }, + ); } private sendTransportFrame( frame: string | Uint8Array | ArrayBuffer, submitted?: () => void, - ): void { + ): Promise { if (!this.transport) { throw this.unavailableError(); } @@ -2020,7 +2118,8 @@ export class DaemonClient { }); try { submitted?.(); - this.transport.send(frame); + const payload = typeof frame === "string" ? frame : asUint8Array(frame)!; + return this.chunkedTransport!.send(payload); } finally { this.endTraceSection(isOpen); } @@ -2049,10 +2148,10 @@ export class DaemonClient { } } - private sendBinaryFrame(frame: Uint8Array): void { + private sendBinaryFrame(frame: Uint8Array): Promise { if (!this.transport || this.connectionState.status !== "connected") { if (this.config.suppressSendErrors) { - return; + return Promise.resolve(); } throw new Error(`Transport not connected (status: ${this.connectionState.status})`); } @@ -2061,10 +2160,10 @@ export class DaemonClient { envelopeType: "binary", messageType: "binary", }); - this.sendTransportFrame(frame); + return this.sendTransportFrame(frame); } catch (error) { if (this.config.suppressSendErrors) { - return; + return Promise.resolve(); } throw error instanceof Error ? error : new Error(String(error)); } @@ -2079,7 +2178,7 @@ export class DaemonClient { private sendSessionMessageOrThrow(message: SessionInboundMessage): Promise { return this.sendWhenConnected(() => { const payload = SessionInboundMessageSchema.parse(message); - this.sendSessionPayload(payload); + return this.sendSessionPayload(payload); }); } @@ -2088,13 +2187,12 @@ export class DaemonClient { return this.sendWhenConnected(() => undefined); } - private sendWhenConnected(send: () => void): Promise { + private sendWhenConnected(send: () => void | Promise): Promise { const status = this.connectionState.status; // If connected, send immediately if (this.transport && status === "connected") { - send(); - return Promise.resolve(); + return Promise.resolve(send()); } // If connecting, queue the message to be sent once connected @@ -2133,8 +2231,7 @@ export class DaemonClient { clearTimeout(pending.timeoutHandle); try { if (this.transport && this.connectionState.status === "connected") { - pending.send(); - pending.resolve(); + void Promise.resolve(pending.send()).then(pending.resolve, pending.reject); } else { pending.reject(new DaemonConnectionError("Connection lost before message could be sent")); } @@ -2190,19 +2287,17 @@ export class DaemonClient { { ...params.options, requestId: params.requestId }, ); + // The response deadline still applies while the transport waits for drain. + void promise.catch(() => undefined); try { - await this.sendSessionMessageOrThrow(wire.message); + const sent = this.sendSessionMessageOrThrow(wire.message); + const result = await Promise.race([promise, sent.then(() => promise)]); + if (result.kind === "error") throw result.error; + return result.value; } catch (error) { const err = error instanceof Error ? error : new Error(String(error)); cancel(err); - void promise.catch(() => undefined); throw err; - } - - try { - const result = await promise; - if (result.kind === "error") throw result.error; - return result.value; } finally { await wire.finish(); } @@ -2292,13 +2387,13 @@ export class DaemonClient { }); } - private sendSessionMessageStrict(message: SessionInboundMessage): void { + private sendSessionMessageStrict(message: SessionInboundMessage): Promise { if (!this.transport || this.connectionState.status !== "connected") { throw this.unavailableError(); } const payload = SessionInboundMessageSchema.parse(message); try { - this.sendSessionPayload(payload); + return this.sendSessionPayload(payload); } catch (error) { throw error instanceof Error ? error : new Error(String(error)); } @@ -2496,15 +2591,16 @@ export class DaemonClient { }; this.pingProbe = probe; - try { - this.sendJsonMessage("ping", "ping", { type: "ping" }); - } catch (error) { - this.clearPingProbe(); + const rejectSend = (error: unknown) => { + if (this.pingProbe !== probe) return; const sendError = error instanceof Error ? error : new Error(String(error)); - if (probe.drivesLivenessFailure) { - this.recordLivenessFailure(sendError); - } - return Promise.reject(sendError); + this.rejectPingProbe(sendError); + if (probe.drivesLivenessFailure) this.recordLivenessFailure(sendError); + }; + try { + void this.sendJsonMessage("ping", "ping", { type: "ping" }).catch(rejectSend); + } catch (error) { + rejectSend(error); } return promise; @@ -3548,9 +3644,15 @@ export class DaemonClient { agentId: string, options: FetchAgentTimelineOptions = {}, ): Promise { + // COMPAT(wholeTurnTimeline): added after v0.13.2 (#8010); remove after 2027-04-27 once the daemon floor supports whole-turn pages. + // Reading history predates this capability and must keep working on older hosts. + const supportsWholeTurns = this.lastServerInfoMessage?.features?.wholeTurnTimeline === true; const resolvedRequestId = this.createRequestId(options.requestId); const message = SessionInboundMessageSchema.parse({ type: "fetch_agent_timeline_request", + ...(supportsWholeTurns && options.wholeTurns !== undefined + ? { wholeTurns: options.wholeTurns } + : {}), agentId, requestId: resolvedRequestId, ...(options.direction ? { direction: options.direction } : {}), @@ -4035,13 +4137,14 @@ export class DaemonClient { async restartServer( reason?: string, requestId?: string, - options?: { timeout?: number }, + options?: { timeout?: number; killTerminals?: boolean }, ): Promise { const resolvedRequestId = this.createRequestId(requestId); const message = SessionInboundMessageSchema.parse({ type: "restart_server_request", ...(reason && reason.trim().length > 0 ? { reason } : {}), requestId: resolvedRequestId, + ...(options?.killTerminals ? { killTerminals: true } : {}), }); return this.sendRequest({ requestId: resolvedRequestId, @@ -4069,6 +4172,7 @@ export class DaemonClient { const message = SessionInboundMessageSchema.parse({ type: "shutdown_server_request", requestId: resolvedRequestId, + ...(options?.keepTerminals ? { keepTerminals: true } : {}), }); return this.sendRequest({ requestId: resolvedRequestId, @@ -4151,7 +4255,7 @@ export class DaemonClient { } async sendVoiceAudioChunk(audio: string, format: string, isLast = false): Promise { - this.sendSessionMessage({ type: "voice_audio_chunk", audio, format, isLast }); + return this.sendSessionMessageStrict({ type: "voice_audio_chunk", audio, format, isLast }); } async startDictationStream(dictationId: string, format: string): Promise { @@ -4192,8 +4296,13 @@ export class DaemonClient { const cleanupError = new Error("Cancelled dictation start waiter"); try { - this.sendSessionMessageStrict({ type: "dictation_stream_start", dictationId, format }); - await Promise.race([ackPromise, errorPromise]); + const sent = this.sendSessionMessageStrict({ + type: "dictation_stream_start", + dictationId, + format, + }); + const response = Promise.race([ackPromise, errorPromise]); + await Promise.race([response, sent.then(() => response)]); } finally { ack.cancel(cleanupError); streamError.cancel(cleanupError); @@ -4328,12 +4437,17 @@ export class DaemonClient { const cleanupError = new Error("Cancelled dictation finish waiter"); try { - this.sendSessionMessageStrict({ type: "dictation_stream_finish", dictationId, finalSeq }); - const firstOutcome = await Promise.race([ + const sent = this.sendSessionMessageStrict({ + type: "dictation_stream_finish", + dictationId, + finalSeq, + }); + const response = Promise.race([ finalOutcomePromise, errorOutcomePromise, finishAcceptedOutcomePromise, ]); + const firstOutcome = await Promise.race([response, sent.then(() => response)]); if (firstOutcome.kind === "final") { return firstOutcome.payload; @@ -5249,8 +5363,10 @@ export class DaemonClient { return undefined; }, ); + const sendFrame = (frame: Uint8Array) => + Promise.race([this.sendBinaryFrame(frame), responsePromise]); try { - this.sendBinaryFrame( + await sendFrame( encodeFileTransferFrame({ opcode: FileTransferOpcode.FileBegin, requestId: resolvedRequestId, @@ -5264,6 +5380,7 @@ export class DaemonClient { }), ); + if (settled) return await responsePromise; const chunkSize = input.chunkSize ?? 128 * 1024; for (let offset = 0; offset < bytes.byteLength; offset += chunkSize) { // Native WebSocket.send encodes binary synchronously. Let rendering and @@ -5273,7 +5390,7 @@ export class DaemonClient { if (this.transport !== uploadTransport || this.connectionState.status !== "connected") { throw new DaemonConnectionError("Connection changed during file upload"); } - this.sendBinaryFrame( + await sendFrame( encodeFileTransferFrame({ opcode: FileTransferOpcode.FileChunk, requestId: resolvedRequestId, @@ -5282,7 +5399,7 @@ export class DaemonClient { ); } - this.sendBinaryFrame( + await sendFrame( encodeFileTransferFrame({ opcode: FileTransferOpcode.FileEnd, requestId: resolvedRequestId, @@ -5785,14 +5902,82 @@ export class DaemonClient { }); } - async getPluginCatalog() { + async getPluginCatalog(): Promise { + if (this.config.createPluginClientBundleStore && !this.pluginClientBundleStore) { + const serverInfo = this.getLastServerInfoMessage(); + if (!serverInfo) throw new Error("Plugin catalog requires a connected host"); + this.pluginClientBundleStore = this.config.createPluginClientBundleStore(serverInfo.serverId); + } + const store = this.pluginClientBundleStore; + if (store) { + this.pluginClientBundlesLoaded ??= store.load().then( + (bundles) => { + for (const { id, ...bundle } of bundles) this.pluginClientBundles.set(id, bundle); + return undefined; + }, + (error) => this.logger.warn({ err: error }, "Failed to load plugin client bundles"), + ); + await this.pluginClientBundlesLoaded; + } const requestId = this.createRequestId(); + const cached = this.pluginClientBundles; + const cachedClientBundles = [...cached].map(([id, { clientBundleHash }]) => ({ + id, + clientBundleHash, + })); const payload = await this.sendCorrelatedSessionRequest({ requestId, - message: { type: "plugin.catalog.get.request", requestId }, + message: { + type: "plugin.catalog.get.request", + requestId, + ...(cachedClientBundles.length > 0 ? { cachedClientBundles } : {}), + }, responseType: "plugin.catalog.get.response", }); - return payload.plugins; + const retained = new Map(); + const plugins = payload.plugins.map(({ clientBundle: sent, ...plugin }): PluginCatalogEntry => { + const previous = cached.get(plugin.id); + const clientBundle = + sent ?? + (previous?.clientBundleHash === plugin.clientBundleHash + ? previous?.clientBundle + : undefined); + if (clientBundle === undefined) { + throw new Error(`Plugin catalog left out the client bundle for ${plugin.id}`); + } + // COMPAT(pluginCatalogBundleHash): introduced by PR #6732 (unreleased); remove after + // 2027-04-27 once the daemon floor includes bundle hashes. Older bundles are not retained. + if (plugin.clientBundleHash !== undefined) { + retained.set(plugin.id, { clientBundleHash: plugin.clientBundleHash, clientBundle }); + } + return Object.assign(plugin, { clientBundle }); + }); + this.pluginClientBundles = retained; + if (store) { + this.pluginClientBundlesWrite = [...retained].map(([id, bundle]) => + Object.assign({ id }, bundle), + ); + void this.persistPluginClientBundles(store); + } + return plugins; + } + + private async persistPluginClientBundles(store: PluginClientBundleStore): Promise { + if (this.pluginClientBundlesWriting) return; + this.pluginClientBundlesWriting = true; + try { + while (this.pluginClientBundlesWrite) { + const bundles = this.pluginClientBundlesWrite; + this.pluginClientBundlesWrite = undefined; + try { + await store.replace(bundles); + } catch (error) { + this.logger.warn({ err: error }, "Failed to persist plugin client bundles"); + } + } + } finally { + this.pluginClientBundlesWriting = false; + } } async listPlugins(): Promise { @@ -6275,7 +6460,8 @@ export class DaemonClient { } /** - * Snapshot/restore and output arrive in receive. Subscribe to the returned handle + * Defaults to a full ANSI replay. Replay begin/data/end and live output arrive in receive. + * Subscribe to the returned handle * for terminal_stream_exit: payload.error means observation failure, not PTY exit. * Either outcome detaches this slot and releases the handle automatically. */ @@ -6294,7 +6480,7 @@ export class DaemonClient { { type: "subscribe_terminal_request", terminalId, - ...(options?.restore ? { restore: options.restore } : {}), + restore: options?.restore ?? { mode: "full-snapshot" }, }, options, ); @@ -6624,6 +6810,8 @@ export class DaemonClient { } private disposeTransport(code = 1001, reason = "Reconnecting"): void { + this.chunkedTransport?.close(); + this.chunkedTransport = null; this.owned.disconnected(); this.providerSnapshotUpdates.clear(); this.stopLivenessHeartbeat(); @@ -7093,15 +7281,6 @@ export class DaemonClient { probe.resolve(perfNow() - probe.startedAt); } - private clearPingProbe(): void { - const probe = this.pingProbe; - if (!probe) { - return; - } - this.pingProbe = null; - clearTimeout(probe.timeoutHandle); - } - private rejectPingProbe(error: Error): void { const probe = this.pingProbe; if (!probe) { @@ -7150,6 +7329,10 @@ export class DaemonClient { if (consumerMessage.type === "status") { const serverInfo = parseServerInfoStatusPayload(consumerMessage.payload); if (serverInfo) { + if (this.chunkedTransport) + this.chunkedTransport.enabled = + serverInfo.features?.binaryChunkingV1 === true && + this.config.capabilities?.[CLIENT_CAPS.binaryChunkingV1] !== false; this.lastServerInfoMessage = serverInfo; this.destinationServerId = serverInfo.serverId; this.connectionFailure = undefined; diff --git a/packages/client/src/hosts/index.ts b/packages/client/src/hosts/index.ts index 1baa9ebe43..aa5c910158 100644 --- a/packages/client/src/hosts/index.ts +++ b/packages/client/src/hosts/index.ts @@ -1,3 +1,4 @@ +import { MAX_HOST_CHANNEL_FRAME_BYTES } from "@getpaseo/protocol/binary-frames/index"; import { safeRandomId } from "../daemon-client-transport-utils.js"; import { DaemonClient } from "../daemon-client.js"; import type { DaemonTransportFactory } from "../daemon-client-transport-types.js"; @@ -84,13 +85,17 @@ export function createHostChannelTransport( }) .catch(close); return { + get supportsDrain() { + return origin.supportsDrain; + }, + maxFrameBytes: MAX_HOST_CHANNEL_FRAME_BYTES, send(data) { if (closed || !routeId) throw Object.assign(new Error(`Host ${serverId} is offline`), { code: "host_offline", serverId, }); - origin.sendHostFrame( + return origin.sendHostFrame( routeId, typeof data === "string" || data instanceof Uint8Array ? data : new Uint8Array(data), ); diff --git a/packages/client/src/index.ts b/packages/client/src/index.ts index 1437068f95..3655b0023a 100644 --- a/packages/client/src/index.ts +++ b/packages/client/src/index.ts @@ -1,3 +1,4 @@ +export type { TerminalReplayEvent, TerminalStreamEvent } from "./terminal-stream-router.js"; import type { AgentAddress } from "@getpaseo/protocol/addresses"; import { parentAddressLabels } from "@getpaseo/protocol/agent-labels"; export type { AgentAddress } from "@getpaseo/protocol/addresses"; diff --git a/packages/client/src/node/connector.test.ts b/packages/client/src/node/connector.test.ts index 6e916d4bec..882a2f5706 100644 --- a/packages/client/src/node/connector.test.ts +++ b/packages/client/src/node/connector.test.ts @@ -44,12 +44,14 @@ test("a slow consumer cannot exceed the shared byte budget and close releases re socket.pause(); await ready; const frame = new Uint8Array(1024 * 1024); - for (let index = 0; index < 4; index++) transport.send(frame); + const writes = Array.from({ length: 4 }, () => transport.send(frame)); + const drained = Promise.allSettled(writes); expect(budget.bufferedBytes).toBe(4 * 1024 * 1024); expect(() => transport.send(frame)).toThrow("Connected host buffer limit reached"); expect(budget.bufferedBytes).toBeLessThanOrEqual(budget.limit); transport.close(); await expect.poll(() => budget.bufferedBytes).toBe(0); + await drained; }); test("direct connector preserves 25 MiB binary frames in both directions", async () => { const server = await endpoint(); @@ -65,12 +67,13 @@ test("direct connector preserves 25 MiB binary frames in both directions", async await ready; const bytes = new Uint8Array(25 * 1024 * 1024).fill(173); const echoed = once(socket, "message"); - transport.send(bytes); + const sending = transport.send(bytes); const [sent, binary] = await echoed; expect(binary).toBe(true); expect(Buffer.from(sent as Uint8Array).equals(bytes)).toBe(true); socket.send(bytes); expect(Buffer.from(await received).equals(bytes)).toBe(true); + await sending; }); import { @@ -124,24 +127,29 @@ test("encrypted connector rejects overload synchronously and preserves the physi }); await new Promise((resolve) => transport.onOpen(resolve)); await ready; + expect(transport.maxFrameBytes).toBeLessThan(32 * 1024 * 1024); peer.pause(); const frame = new Uint8Array(1024 * 1024).fill(173); let rejected: unknown; + const writes: (void | Promise)[] = []; for (let index = 0; index < 8; index++) { try { - transport.send(frame); + writes.push(transport.send(frame)); } catch (error) { rejected = error; break; } } + const drained = Promise.allSettled(writes); expect(rejected).toMatchObject({ code: "resource_limit" }); expect(budget.bufferedBytes).toBeLessThanOrEqual(budget.limit); await new Promise((resolve) => setImmediate(resolve)); expect(errors).toEqual([]); expect(closed).toBe(false); - transport.send("sibling control"); + const sibling = transport.send("sibling control"); peer.resume(); + await drained; + await sibling; await expect.poll(() => received.includes("sibling control")).toBe(true); expect(received.filter((data) => data instanceof ArrayBuffer).length).toBeGreaterThan(0); expect( diff --git a/packages/client/src/node/index.ts b/packages/client/src/node/index.ts index 7132d09f10..464d16332d 100644 --- a/packages/client/src/node/index.ts +++ b/packages/client/src/node/index.ts @@ -2,6 +2,7 @@ export { createHostChannelTransport } from "../hosts/index.js"; import { HostTransportBudget } from "./buffering.js"; export { HostTransportBudget } from "./buffering.js"; import { homedir } from "node:os"; +import type { Agent } from "node:http"; import { WebSocket } from "ws"; import { parseHostTarget, type HostTarget } from "@getpaseo/protocol/host-target"; import { createSshTunnel, type SshTunnel } from "./ssh-tunnel.js"; @@ -19,10 +20,15 @@ export { parseHostTarget }; export type { SshTunnel } from "./ssh-tunnel.js"; export { createSshTunnel, resolveSshFailureDetail } from "./ssh-tunnel.js"; +export interface HostTransportOptions { + webSocketAgent?: (url: string) => Agent | undefined; +} + /** A factory owns one attempt, including a fresh SSH process and its teardown. */ export function createHostTransportFactory( connection: string, budget = new HostTransportBudget(), + options: HostTransportOptions = {}, ): DaemonTransportFactory { const target = parseHostTarget(connection); // Rises to "protected" once the daemon negotiates it, so a later attempt @@ -68,12 +74,13 @@ export function createHostTransportFactory( return; } const socketPath = socketTarget.socketPath?.replace(/^~(?=\/)/, homedir()); - let factory = createWebSocketTransportFactory((url, options) => { + let factory = createWebSocketTransportFactory((url, socketOptions) => { const socket = new WebSocket( socketPath && url.startsWith("ws+unix:") ? `ws+unix://${socketPath}:/ws` : url, - options?.protocols, + socketOptions?.protocols, { - headers: options?.headers, + headers: socketOptions?.headers, + agent: socketPath ? undefined : options.webSocketAgent?.(url), ...(socketPath ? { socketPath } : {}), maxPayload: 100 * 1024 * 1024, }, @@ -165,9 +172,15 @@ export function createHostTransportFactory( close(); }); return { + get supportsDrain() { + return transport?.supportsDrain; + }, + get maxFrameBytes() { + return transport?.maxFrameBytes; + }, send(data) { if (closed || !transport) throw new Error("Host transport is unavailable"); - transport.send(data); + return transport.send(data); }, close, onOpen(handler) { @@ -191,14 +204,16 @@ export function createHostTransportFactory( } export function createHostClient( connection: string, - config: Omit, + config: Omit & HostTransportOptions, budget?: HostTransportBudget, ): DaemonClient { const target = parseHostTarget(connection); + const { webSocketAgent, transportFactory, ...clientConfig } = config; return new DaemonClient({ - ...config, + ...clientConfig, url: "ws://host-connector/ws", ...(target.password ? { password: target.password } : {}), - transportFactory: createHostTransportFactory(connection, budget), + transportFactory: + transportFactory ?? createHostTransportFactory(connection, budget, { webSocketAgent }), }); } diff --git a/packages/client/src/terminal-stream-router.test.ts b/packages/client/src/terminal-stream-router.test.ts index 7b9e598410..b8ed727117 100644 --- a/packages/client/src/terminal-stream-router.test.ts +++ b/packages/client/src/terminal-stream-router.test.ts @@ -4,7 +4,7 @@ import { describe, expect, test } from "vitest"; import { TerminalStreamRouter, type TerminalStreamEvent } from "./terminal-stream-router.js"; describe("terminal-stream-router", () => { - test("routes restore frames as restore events", () => { + test("normalizes old ANSI restore into the replay lifecycle", () => { const router = new TerminalStreamRouter(); const events: TerminalStreamEvent[] = []; const payload = new TextEncoder().encode("restored screen"); @@ -16,14 +16,14 @@ describe("terminal-stream-router", () => { payload, }); - expect(events).toEqual([ - { + expect(events).toEqual( + ["begin", "data", "end"].map((type) => ({ terminalId: "term-1", subscriptionId: "subscription-1", - type: "restore", - data: payload, - }, - ]); + type: "replay", + replay: type === "data" ? { type, data: payload } : { type }, + })), + ); }); }); @@ -61,3 +61,45 @@ test("legacy listeners share a terminal slot without releasing each other", () = router.handleFrame(frame); expect(received).toEqual(["first", "second", "second"]); }); + +test("streams chunks without joining and ignores released slots during replay", () => { + const router = new TerminalStreamRouter(); + const events: TerminalStreamEvent[] = []; + const release = router.attach("old", "terminal", 4, (event) => events.push(event)); + const payload = new TextEncoder().encode( + JSON.stringify({ rows: 24, cols: 80, retainedHistoryLines: 1000 }), + ); + router.handleFrame({ opcode: TerminalStreamOpcode.ReplayBegin, slot: 4, payload }); + const data = new TextEncoder().encode("\x1b[31m界🙂"); + router.handleFrame({ + opcode: TerminalStreamOpcode.ReplayData, + slot: 4, + payload: data.subarray(0, 7), + }); + release(); + router.attach("new", "terminal", 5, (event) => events.push(event)); + router.handleFrame({ + opcode: TerminalStreamOpcode.ReplayData, + slot: 4, + payload: data.subarray(7), + }); + router.handleFrame({ + opcode: TerminalStreamOpcode.ReplayEnd, + slot: 4, + payload: new Uint8Array(), + }); + expect(events).toHaveLength(2); + expect(events[1]).toMatchObject({ + subscriptionId: "old", + type: "replay", + replay: { type: "data", data: data.subarray(0, 7) }, + }); + router.handleFrame({ opcode: TerminalStreamOpcode.ReplayBegin, slot: 5, payload }); + router.handleFrame({ opcode: TerminalStreamOpcode.ReplayData, slot: 5, payload: data }); + router.handleFrame({ + opcode: TerminalStreamOpcode.ReplayEnd, + slot: 5, + payload: new Uint8Array(), + }); + expect(events.slice(2).map((event) => event.subscriptionId)).toEqual(["new", "new", "new"]); +}); diff --git a/packages/client/src/terminal-stream-router.ts b/packages/client/src/terminal-stream-router.ts index a2c9575450..bca9fb3ea1 100644 --- a/packages/client/src/terminal-stream-router.ts +++ b/packages/client/src/terminal-stream-router.ts @@ -1,14 +1,17 @@ import { - decodeTerminalSnapshotPayload, TerminalStreamOpcode, + TerminalReplayMetadataSchema, type TerminalStreamFrame, } from "@getpaseo/protocol/binary-frames/index"; -import type { TerminalState } from "@getpaseo/protocol/messages"; + +export type TerminalReplayEvent = + | { type: "begin"; rows?: number; cols?: number; retainedHistoryLines?: number } + | { type: "data"; data: Uint8Array } + | { type: "end" }; export type TerminalStreamEvent = { terminalId: string; subscriptionId: string } & ( | { type: "output"; data: Uint8Array } - | { type: "snapshot"; state: TerminalState } - | { type: "restore"; data: Uint8Array } + | { type: "replay"; replay: TerminalReplayEvent } ); export class TerminalStreamRouter { @@ -61,20 +64,42 @@ export class TerminalStreamRouter { let event: TerminalStreamEvent; if (frame.opcode === TerminalStreamOpcode.Output) event = { ...identity, type: "output", data: frame.payload }; - else if (frame.opcode === TerminalStreamOpcode.Restore) - event = { ...identity, type: "restore", data: frame.payload }; - else if (frame.opcode === TerminalStreamOpcode.Snapshot) { - const state = decodeTerminalSnapshotPayload(frame.payload); - if (!state) return; - event = { ...identity, type: "snapshot", state }; - } else return; - registration.receive(event); - for (const listener of this.listeners) { + else if (frame.opcode === TerminalStreamOpcode.Restore) { + // COMPAT(terminalSingleRestore): added after v0.14.0; remove when ANSI host floor supports chunked replay after 2027-04-30. + for (const replay of [ + { type: "begin" }, + { type: "data", data: frame.payload }, + { type: "end" }, + ] as TerminalReplayEvent[]) + this.deliver(registration.receive, { ...identity, type: "replay", replay }); + continue; + } else if (frame.opcode === TerminalStreamOpcode.ReplayBegin) { + let raw: unknown; try { - listener(event); + raw = JSON.parse(new TextDecoder().decode(frame.payload)); } catch { - /* Passive diagnostics cannot interrupt delivery. */ + return; } + const parsed = TerminalReplayMetadataSchema.safeParse(raw); + if (!parsed.success) return; + const metadata = parsed.data; + event = { ...identity, type: "replay", replay: { type: "begin", ...metadata } }; + } else if (frame.opcode === TerminalStreamOpcode.ReplayData) + event = { ...identity, type: "replay", replay: { type: "data", data: frame.payload } }; + else if (frame.opcode === TerminalStreamOpcode.ReplayEnd) + event = { ...identity, type: "replay", replay: { type: "end" } }; + else return; + this.deliver(registration.receive, event); + } + } + + private deliver(receive: (event: TerminalStreamEvent) => void, event: TerminalStreamEvent): void { + receive(event); + for (const listener of this.listeners) { + try { + listener(event); + } catch { + /* Passive diagnostics cannot interrupt delivery. */ } } } diff --git a/packages/desktop/e2e/appearance-theme.electron.mjs b/packages/desktop/e2e/appearance-theme.electron.mjs new file mode 100644 index 0000000000..426c50f355 --- /dev/null +++ b/packages/desktop/e2e/appearance-theme.electron.mjs @@ -0,0 +1,158 @@ +import fs from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { execFile } from "node:child_process"; +import { promisify } from "node:util"; +import electronPath from "electron"; +import { build } from "esbuild"; + +export async function runAdaptiveThemeRegression(artifactDir) { + const { outputFiles } = await build({ + stdin: { + resolveDir: fileURLToPath(new URL("../../app", import.meta.url)), + contents: ` + import { createElement } from "react"; + import { createRoot } from "react-dom/client"; + import { StyleSheet, UnistylesRuntime, withUnistyles } from "react-native-unistyles"; + StyleSheet.configure({ + themes: { + dark: { foreground: "#fafafa", background: "#181b1a" }, + light: { foreground: "#1a1a1e", background: "#ffffff" }, + }, + settings: { adaptiveThemes: true }, + }); + const Message = withUnistyles(({ color }) => + createElement("p", { style: { color } }, "Theme-reactive message")); + createRoot(document.getElementById("root")).render(createElement(Message, { + style: { margin: 0 }, + uniProps: theme => ({ color: theme.foreground }), + })); + window.readThemeForTest = () => UnistylesRuntime.themeName; + `, + }, + bundle: true, + write: false, + format: "iife", + platform: "browser", + alias: { "react-native": "react-native-web" }, + define: { __DEV__: "false" }, + resolveExtensions: [".web.js", ".js", ".json"], + }); + const directory = await fs.mkdtemp(path.join(os.tmpdir(), "paseo-adaptive-theme-")); + try { + await fs.writeFile(path.join(directory, "renderer.js"), outputFiles[0].text); + await fs.writeFile(path.join(directory, "main.cjs"), `(${electronRegression.toString()})()`); + // A separate process avoids Playwright's focus emulation, which keeps hidden pages visible. + const env = { ...process.env }; + delete env.ELECTRON_RUN_AS_NODE; + const args = [ + ...(process.platform === "linux" ? ["--no-sandbox"] : []), + path.join(directory, "main.cjs"), + artifactDir, + ]; + const command = process.platform === "linux" ? "xvfb-run" : electronPath; + const commandArgs = + process.platform === "linux" + ? ["-a", "--server-args=-screen 0 1280x800x24", electronPath, ...args] + : args; + await promisify(execFile)(command, commandArgs, { + env, + timeout: 30_000, + }); + return JSON.parse(await fs.readFile(path.join(artifactDir, "adaptive-theme.json"), "utf8")); + } finally { + await fs.rm(directory, { recursive: true, force: true }); + } +} + +async function electronRegression() { + const { app, BrowserWindow, nativeTheme } = require("electron"); + const assert = require("node:assert/strict"); + const files = require("node:fs"); + const paths = require("node:path"); + const { setTimeout: delay } = require("node:timers/promises"); + app.setPath("userData", paths.join(__dirname, "profile")); + app.on("window-all-closed", () => {}); + // Electron keeps Linux's --no-sandbox in argv; the artifact directory is always last. + const artifactDir = process.argv.at(-1); + let window; + const observations = []; + const colors = { + dark: { foreground: "rgb(250, 250, 250)", background: "rgb(24, 27, 26)" }, + light: { foreground: "rgb(26, 26, 30)", background: "rgb(255, 255, 255)" }, + }; + async function read(expression) { + return window.webContents.executeJavaScript(expression); + } + async function expectValue(expression, expected) { + let actual; + for (let attempt = 0; attempt < 50; attempt++) { + actual = await read(expression); + if (actual === expected) return; + await delay(50); + } + assert.equal(actual, expected, expression); + } + try { + await app.whenReady(); + if (process.platform === "darwin") { + app.setActivationPolicy("accessory"); + app.dock.hide(); + } + for (const [from, to] of [ + ["dark", "light"], + ["light", "dark"], + ]) { + nativeTheme.themeSource = from; + window = new BrowserWindow({ width: 600, height: 200, show: false, skipTaskbar: true }); + await window.loadURL( + "data:text/html," + + encodeURIComponent(` + +
`), + ); + await read(files.readFileSync(paths.join(__dirname, "renderer.js"), "utf8")); + window.showInactive(); + const foreground = + "document.querySelector('p') && getComputedStyle(document.querySelector('p')).color"; + const background = "getComputedStyle(document.body).backgroundColor"; + await expectValue(foreground, colors[from].foreground); + await expectValue(background, colors[from].background); + window.hide(); + await expectValue("document.visibilityState", "hidden"); + nativeTheme.themeSource = to; + await expectValue(`matchMedia('(prefers-color-scheme: ${to})').matches`, true); + // Reading the public runtime while hidden must not consume the pending theme notification. + assert.equal(await read("window.readThemeForTest()"), to); + window.showInactive(); + await expectValue("document.visibilityState", "visible"); + await expectValue(background, colors[to].background); + try { + await expectValue(foreground, colors[to].foreground); + } finally { + files.writeFileSync( + paths.join(artifactDir, `theme-${from}-to-${to}.png`), + (await window.webContents.capturePage()).toPNG(), + ); + } + observations.push({ + from, + to, + foreground: await read(foreground), + background: await read(background), + }); + window.destroy(); + window = undefined; + } + files.writeFileSync( + paths.join(artifactDir, "adaptive-theme.json"), + JSON.stringify(observations, null, 2), + ); + app.exit(0); + } catch (error) { + console.error(error); + window?.destroy(); + app.exit(1); + } +} diff --git a/packages/desktop/e2e/browser-tabs.e2e.mjs b/packages/desktop/e2e/browser-tabs.e2e.mjs index 78d2fa978e..28afbab94f 100644 --- a/packages/desktop/e2e/browser-tabs.e2e.mjs +++ b/packages/desktop/e2e/browser-tabs.e2e.mjs @@ -14,6 +14,7 @@ import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/ import { chromium } from "playwright"; import { hideDeveloperToasts } from "../../app/e2e/support/developer-ui.mjs"; import { runAppearanceFontSizeRegression } from "./appearance-font-size.electron.mjs"; +import { runAdaptiveThemeRegression } from "./appearance-theme.electron.mjs"; import { runSettingsScrollRegression } from "./settings-scroll.electron.mjs"; import { runSettingsMemoryRegression } from "./settings-memory.electron.mjs"; @@ -1241,6 +1242,7 @@ async function main() { return; } + const adaptiveTheme = await runAdaptiveThemeRegression(artifactDir); await runAppearanceFontSizeRegression(page); const callerAgentId = await createCallerAgent(daemonPort); @@ -1265,7 +1267,12 @@ async function main() { artifactDir, }); const pluginLinks = await checkPluginLinks(); - writeJson(path.join(artifactDir, "result.json"), { ...report, settingsMemory, pluginLinks }); + writeJson(path.join(artifactDir, "result.json"), { + ...report, + settingsMemory, + pluginLinks, + adaptiveTheme, + }); console.log( `Browser desktop browser E2E passed: WebContents ${report.originalWebContentsId} remained ${report.finalWebContentsId}; viewport, inactive capture, focus continuity, list, snapshot, click, local-page selectors passed.`, ); diff --git a/packages/desktop/package.json b/packages/desktop/package.json index 4735fb5192..23198969dc 100644 --- a/packages/desktop/package.json +++ b/packages/desktop/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/desktop", - "version": "0.13.2", + "version": "0.15.0-beta.1", "private": true, "description": "Paseo desktop app (Electron wrapper)", "homepage": "https://paseo.sh", @@ -41,7 +41,7 @@ "@types/node": "24.6.0", "@types/ws": "^8.5.14", "electron": "44.2.0", - "electron-builder": "26.8.1", + "electron-builder": "26.18.0", "typescript": "5.9.3", "unzip-crx-3": "^0.2.0", "vitest": "^4.1.6", diff --git a/packages/desktop/src/daemon/cli/external.ts b/packages/desktop/src/daemon/cli/external.ts index 6c9deeccb1..4a55adff1c 100644 --- a/packages/desktop/src/daemon/cli/external.ts +++ b/packages/desktop/src/daemon/cli/external.ts @@ -4,6 +4,31 @@ import type { NodeEntrypointInvocation } from "../node-entrypoint-launcher.js"; import { createNodeEntrypointInvocation } from "../runtime-paths.js"; import { resolveExternalCliEntrypoint } from "./entrypoints.js"; +/** A CLI command that exited non-zero, with the `--json` error it printed when there was one. */ +export class ExternalCliCommandError extends Error { + readonly code: string | null; + readonly error: Record | null; + + constructor(message: string, error: Record | null) { + super(message); + this.name = "ExternalCliCommandError"; + this.error = error; + this.code = typeof error?.code === "string" ? error.code : null; + } +} + +// `--json` commands print `{ "error": { code, message, ... } }` on stderr when they fail. +function parseJsonCliError(stderr: string): Record | null { + try { + const parsed = JSON.parse(stderr) as { error?: unknown }; + return typeof parsed.error === "object" && parsed.error !== null + ? (parsed.error as Record) + : null; + } catch { + return null; + } +} + function createExternalCliInvocation(args: string[]): NodeEntrypointInvocation { return createNodeEntrypointInvocation({ entrypoint: resolveExternalCliEntrypoint(), @@ -85,7 +110,10 @@ export async function runExternalCliJsonCommand(args: string[]): Promise ({ paseoHome: "", @@ -73,7 +79,8 @@ vi.mock("./runtime-paths.js", () => ({ })), })); -vi.mock("./cli/external.js", () => ({ +vi.mock("./cli/external.js", async (importOriginal) => ({ + ...(await importOriginal>()), runExternalCliJsonCommand: mocks.runExternalCliJsonCommand, runExternalCliTextCommand: mocks.runExternalCliTextCommand, })); @@ -176,3 +183,107 @@ describe("daemon-manager commands", () => { expect(await handler({ listen: "localhost:6799" })).toBeNull(); }); }); + +describe("desktop stops and terminals", () => { + const reasons: DesktopDaemonStopReason[] = [ + "manual_ipc", + "settings", + "host_remove", + "quit", + "app_update", + "version_mismatch", + "restart", + ]; + + it("keeps terminals only for an app update or version-mismatch restart, never on Windows", () => { + for (const platform of ["darwin", "linux"] as const) { + expect(reasons.filter((reason) => keepsTerminalsOnStop(reason, platform))).toEqual([ + "app_update", + "version_mismatch", + ]); + } + expect(reasons.filter((reason) => keepsTerminalsOnStop(reason, "win32"))).toEqual([]); + }); + + function stopHarness(runCliJson: (args: string[]) => Promise) { + const stops: Array<{ keepTerminals: boolean | undefined }> = []; + const logged: string[] = []; + const instance = { + pid: 4242, + startedAt: "2026-10-21T00:00:00.000Z", + hostname: "host", + uid: 501, + listen: "127.0.0.1:6799", + }; + const stopInstance = (async ( + _home: string, + options: { + keepTerminals?: boolean; + requestShutdown?: (ready: { listen: string }) => Promise; + }, + ) => { + stops.push({ keepTerminals: options.keepTerminals }); + await options.requestShutdown?.({ listen: instance.listen }); + return { action: "stopped", pid: instance.pid, forced: false, usedLifecycleRpc: true }; + }) as unknown as NonNullable[0]["stopInstance"]>; + return { + stops, + logged, + input: { + home: "/tmp/paseo-home", + instance, + stopInstance, + runCliJson, + log: (message: string) => logged.push(message), + } as Omit[0], "reason" | "keepTerminals">, + }; + } + + it("asks the daemon to keep its terminals on an app update", async () => { + const calls: string[][] = []; + const harness = stopHarness(async (args) => { + calls.push(args); + return { action: "shutdown_requested" }; + }); + + await stopCapturedDaemon({ ...harness.input, reason: "app_update", keepTerminals: true }); + + expect(harness.stops).toEqual([{ keepTerminals: true }]); + expect(calls).toEqual([ + ["daemon", "stop", "--host", "127.0.0.1:6799", "--keep-terminals", "--json"], + ]); + }); + + it("stops a daemon without the capability with its terminals closed, and says so", async () => { + const calls: string[][] = []; + const harness = stopHarness(async (args) => { + calls.push(args); + if (args.includes("--keep-terminals")) { + throw new ExternalCliCommandError("refused", { + code: "TERMINALS_KEEP_UNSUPPORTED", + version: "0.11.0", + }); + } + return { action: "shutdown_requested" }; + }); + + await stopCapturedDaemon({ ...harness.input, reason: "app_update", keepTerminals: true }); + + expect(harness.stops).toEqual([{ keepTerminals: true }, { keepTerminals: false }]); + expect(calls[1]).toEqual(["daemon", "stop", "--host", "127.0.0.1:6799", "--json"]); + expect(harness.logged).toContain( + "daemon v0.11.0 cannot keep terminals; stopping it and closing them", + ); + }); + + it("does not retry a keep stop that failed for another reason", async () => { + const harness = stopHarness(async () => { + throw new ExternalCliCommandError("unreachable", { code: "DAEMON_UNREACHABLE" }); + }); + + await expect( + stopCapturedDaemon({ ...harness.input, reason: "app_update", keepTerminals: true }), + ).rejects.toThrow("unreachable"); + expect(harness.stops).toEqual([{ keepTerminals: true }]); + }); +}); diff --git a/packages/desktop/src/daemon/daemon-manager.ts b/packages/desktop/src/daemon/daemon-manager.ts index 5f3f5394c6..769b5513f5 100644 --- a/packages/desktop/src/daemon/daemon-manager.ts +++ b/packages/desktop/src/daemon/daemon-manager.ts @@ -37,7 +37,11 @@ import { closeLocalTransportSession, } from "./local-transport.js"; import { createNodeEntrypointInvocation, resolveDaemonRunnerEntrypoint } from "./runtime-paths.js"; -import { runExternalCliJsonCommand, runExternalCliTextCommand } from "./cli/external.js"; +import { + ExternalCliCommandError, + runExternalCliJsonCommand, + runExternalCliTextCommand, +} from "./cli/external.js"; import { createDesktopSettingsCommandHandlers, type DesktopCommandHandler, @@ -348,18 +352,84 @@ export async function stopDesktopDaemon( "Daemon changed since confirmation; inspect its current home and PID before stopping it.", ); if (!instance || (!owned && !explicit)) return resolveDesktopDaemonStatus(); - logDesktopDaemonLifecycle("stopping captured supervisor", { reason, pid: instance.pid, owned }); - await stopDaemonInstance(home, { - instance, - timeoutMs: 15_000, - requestShutdown: async (ready) => { - await runExternalCliJsonCommand(["daemon", "stop", "--host", ready.listen, "--json"]); - }, + const keepTerminals = keepsTerminalsOnStop(reason, process.platform); + logDesktopDaemonLifecycle("stopping captured supervisor", { + reason, + pid: instance.pid, + owned, + keepTerminals, }); + await stopCapturedDaemon({ home, instance, reason, keepTerminals }); if (owned) ownedLaunch = null; return resolveDesktopDaemonStatus(); } +export interface StopCapturedDaemonInput { + home: string; + instance: DaemonInstance; + reason: DesktopDaemonStopReason; + keepTerminals: boolean; + stopInstance?: typeof stopDaemonInstance; + runCliJson?: typeof runExternalCliJsonCommand; + log?: typeof logDesktopDaemonLifecycle; +} + +/** Stops the supervisor desktop captured, keeping its terminals when asked and supported. */ +export async function stopCapturedDaemon(input: StopCapturedDaemonInput): Promise { + const stopInstance = input.stopInstance ?? stopDaemonInstance; + const runCliJson = input.runCliJson ?? runExternalCliJsonCommand; + const logLifecycle = input.log ?? logDesktopDaemonLifecycle; + const stop = (keep: boolean) => + stopInstance(input.home, { + instance: input.instance, + timeoutMs: 15_000, + keepTerminals: keep, + requestShutdown: async (ready) => { + await runCliJson([ + "daemon", + "stop", + "--host", + ready.listen, + ...(keep ? ["--keep-terminals"] : []), + "--json", + ]); + }, + }); + try { + await stop(input.keepTerminals); + } catch (error) { + // The CLI refuses a keep stop before sending anything when the daemon predates the feature; + // that daemon closes terminals on every stop, as every upgrade did before. + if ( + !input.keepTerminals || + !(error instanceof ExternalCliCommandError) || + error.code !== "TERMINALS_KEEP_UNSUPPORTED" + ) { + throw error; + } + const version = typeof error.error?.version === "string" ? error.error.version : "unknown"; + logLifecycle(`daemon v${version} cannot keep terminals; stopping it and closing them`, { + reason: input.reason, + pid: input.instance.pid, + }); + await stop(false); + } +} + +/** + * Whether a desktop stop keeps the daemon's terminals running for the daemon that replaces it. + * Only when one comes straight back (an app update, a version-mismatch restart), and never on + * Windows: a surviving terminal worker runs Paseo.exe and would lock the install folder the + * update replaces. Quit, Settings, host removal and manual stops close terminals. + */ +export function keepsTerminalsOnStop( + reason: DesktopDaemonStopReason, + platform: NodeJS.Platform, +): boolean { + if (platform === "win32") return false; + return reason === "app_update" || reason === "version_mismatch"; +} + async function restartDaemon(): Promise { await runExternalCliJsonCommand(["daemon", "restart", "--home", getPaseoHome(), "--json"]); return resolveDesktopDaemonStatus(); diff --git a/packages/desktop/src/features/editor-targets/registry.test.ts b/packages/desktop/src/features/editor-targets/registry.test.ts index 4d8c4d80c7..0a6ae12328 100644 --- a/packages/desktop/src/features/editor-targets/registry.test.ts +++ b/packages/desktop/src/features/editor-targets/registry.test.ts @@ -86,6 +86,10 @@ class FakeEditorTargets implements EditorTargetRuntime { return this.paths.has(targetPath); } + expandHomePath(targetPath: string): string { + return targetPath.startsWith("~/") ? `/home/me/${targetPath.slice(2)}` : targetPath; + } + isAbsolutePath(targetPath: string): boolean { return targetPath.startsWith("/") || /^[A-Z]:\//u.test(targetPath); } @@ -513,6 +517,19 @@ describe("editor target registry", () => { expect(runtime.revealedPaths).toEqual(["C:/repo/src/app.ts"]); }); + it("opens a home-relative folder in the file manager", async () => { + const runtime = new FakeEditorTargets(); + runtime.addPath("/home/me/Downloads/contracts"); + + await openEditorTarget( + { editorId: "file-manager", workspacePath: "~/Downloads/contracts" }, + runtime, + [fileManagerTarget], + ); + + expect(runtime.openedPaths).toEqual(["/home/me/Downloads/contracts"]); + }); + it("keeps the platform file-manager ids used by stored preferences", async () => { const macTargets = await listAvailableEditorTargets(new FakeEditorTargets("darwin"), [ finderTarget, diff --git a/packages/desktop/src/features/editor-targets/registry.ts b/packages/desktop/src/features/editor-targets/registry.ts index 1e589f7a64..99a8e8d461 100644 --- a/packages/desktop/src/features/editor-targets/registry.ts +++ b/packages/desktop/src/features/editor-targets/registry.ts @@ -97,10 +97,16 @@ export function getEditorTarget( } export async function openEditorTarget( - input: EditorTargetLaunchInput & { editorId: string }, + request: EditorTargetLaunchInput & { editorId: string }, runtime: EditorTargetRuntime, targets: readonly EditorTarget[] = EDITOR_TARGETS, ): Promise { + // Assistant replies name folders like `~/Downloads/x`; expand them before the absolute-path guard. + const input = { + ...request, + workspacePath: runtime.expandHomePath(request.workspacePath), + filePath: request.filePath === undefined ? undefined : runtime.expandHomePath(request.filePath), + }; if (!runtime.isAbsolutePath(input.workspacePath)) { throw new Error("Editor target workspace path must be an absolute local path"); } diff --git a/packages/desktop/src/features/editor-targets/runtime.ts b/packages/desktop/src/features/editor-targets/runtime.ts index 9562b27977..36bfac0e65 100644 --- a/packages/desktop/src/features/editor-targets/runtime.ts +++ b/packages/desktop/src/features/editor-targets/runtime.ts @@ -61,6 +61,14 @@ function isAbsolutePath(value: string, platform: NodeJS.Platform): boolean { return platform === "win32" ? win32.isAbsolute(value) : posix.isAbsolute(value); } +function expandHomePath(value: string, homeDirectory: string): string { + if (value === "~") return homeDirectory; + if (value.startsWith("~/") || value.startsWith("~\\")) { + return path.join(homeDirectory, value.slice(2)); + } + return value; +} + function resolveExecutable( commands: readonly string[], input: { @@ -166,6 +174,7 @@ export function createEditorTargetRuntime( pathExists, isAbsolutePath: (targetPath) => isAbsolutePath(targetPath, platform), listDirectory, + expandHomePath: (targetPath) => expandHomePath(targetPath, homeDirectory), resolveCommand: (commands) => resolveExecutable(commands, { env, pathExists, platform }), async spawnDetached({ command, args }) { const commandScript = isWindowsCommandScript(command, platform); diff --git a/packages/desktop/src/features/editor-targets/target.ts b/packages/desktop/src/features/editor-targets/target.ts index f7111662c5..b6a9f93668 100644 --- a/packages/desktop/src/features/editor-targets/target.ts +++ b/packages/desktop/src/features/editor-targets/target.ts @@ -30,6 +30,8 @@ export interface EditorTargetRuntime { pathExists(path: string): boolean; isAbsolutePath(path: string): boolean; listDirectory(path: string): EditorTargetDirectoryEntry[]; + /** Resolves a leading `~` to the user's home directory. */ + expandHomePath(path: string): string; resolveCommand(commands: readonly string[]): string | null; spawnDetached(input: { command: string; args: readonly string[] }): Promise; openPath(path: string): Promise; diff --git a/packages/expo-two-way-audio/package.json b/packages/expo-two-way-audio/package.json index 1a38528c25..ff08d35c76 100644 --- a/packages/expo-two-way-audio/package.json +++ b/packages/expo-two-way-audio/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/expo-two-way-audio", - "version": "0.13.2", + "version": "0.15.0-beta.1", "description": "Native module for two way audio streaming", "keywords": [ "ExpoTwoWayAudio", @@ -33,7 +33,6 @@ "devDependencies": { "@types/jest": "^29.5.14", "@types/react": "^18.0.25", - "expo-module-scripts": "^5.0.8", "expo-modules-core": "^2.0.4" }, "peerDependencies": { diff --git a/packages/expo-two-way-audio/tsconfig.json b/packages/expo-two-way-audio/tsconfig.json index 102525ffa9..24e443895c 100644 --- a/packages/expo-two-way-audio/tsconfig.json +++ b/packages/expo-two-way-audio/tsconfig.json @@ -6,7 +6,7 @@ "module": "esnext", "moduleResolution": "bundler", "typeRoots": [ - "./node_modules/expo-module-scripts/ts-declarations", + "../../node_modules/expo-module-scripts/ts-declarations", "./node_modules/@types", "../../node_modules/@types" ] diff --git a/packages/highlight/package.json b/packages/highlight/package.json index d7708e5925..dfc43982bf 100644 --- a/packages/highlight/package.json +++ b/packages/highlight/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/highlight", - "version": "0.13.2", + "version": "0.15.0-beta.1", "files": [ "dist", "!dist/**/*.map", diff --git a/packages/plugin/package.json b/packages/plugin/package.json index 18421b41e1..8ed758eb5f 100644 --- a/packages/plugin/package.json +++ b/packages/plugin/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/plugin", - "version": "0.13.2", + "version": "0.15.0-beta.1", "description": "Paseo plugin SDK package", "files": [ "dist", @@ -52,6 +52,11 @@ "types": "./dist/client/index.d.ts", "source": "./src/client/index.ts", "default": "./dist/client/index.js" + }, + "./internal/lifecycle": { + "types": "./dist/server/lifecycle.d.ts", + "source": "./src/server/lifecycle.ts", + "default": "./dist/server/lifecycle.js" } }, "publishConfig": { @@ -72,8 +77,8 @@ "use-sync-external-store": "^1.6.0" }, "devDependencies": { - "@getpaseo/client": "0.13.2", - "@getpaseo/protocol": "0.13.2", + "@getpaseo/client": "0.15.0-beta.1", + "@getpaseo/protocol": "0.15.0-beta.1", "@types/node": "^20.9.0", "@types/react": "~19.2.0", "react": "19.2.3", @@ -83,8 +88,8 @@ "zod": "^4.4.3" }, "peerDependencies": { - "@getpaseo/client": "0.13.2", - "@getpaseo/protocol": "0.13.2", + "@getpaseo/client": "0.15.0-beta.1", + "@getpaseo/protocol": "0.15.0-beta.1", "react": ">=19.1.0 <20", "react-native": ">=0.81.5", "zod": "^4.4.3" diff --git a/packages/plugin/src/boundaries.test.ts b/packages/plugin/src/boundaries.test.ts index 017b69bda5..b0834956d6 100644 --- a/packages/plugin/src/boundaries.test.ts +++ b/packages/plugin/src/boundaries.test.ts @@ -13,6 +13,7 @@ const entries = { "./server/provider": "server", "./server/usage": "server", "./server/acp": "server", + "./internal/lifecycle": "server", "./client": "client", "./client/host": "client", "./client/ui": "client", @@ -134,12 +135,8 @@ describe("plugin SDK import boundaries", () => { it.each(Object.entries(entries))( "%s respects its %s boundary, including type dependencies", (specifier, runtime) => { - const name = - specifier === "." - ? "index" - : specifier.slice(2) + - (specifier === "./client" || specifier === "./server" ? "/index" : ""); - expect(boundaryViolations(path.join(sourceDirectory, `${name}.ts`), runtime)).toEqual([]); + const file = path.resolve(sourceDirectory, "..", manifest.exports[specifier].source); + expect(boundaryViolations(file, runtime)).toEqual([]); }, ); }); @@ -170,6 +167,7 @@ describe("plugin example import boundaries", () => { const entry = specifier.replace("@getpaseo/plugin", ".") as keyof typeof entries; if ( entry === "./client/host" || + entry.startsWith("./internal/") || !(entry in entries) || (entries[entry] !== "shared" && entries[entry] !== runtime) ) @@ -233,12 +231,16 @@ describe("plugin agent tools SDK boundary", () => { }, }); export default function contribute(server: PluginServerContext) { - server.before("agent.session_open", ({ request }) => { + server.addHook("agent.open.before", async ({ request }) => { const title: string | null = request.title; // @ts-expect-error labels are read-only request.labels.x = "changed"; if (request.labels.x !== "y") return; - return { ...request, tools: [...request.tools, tool] }; + // @ts-expect-error MCP servers use the same typed transport config as saved servers + request.mcpServers.invalid = { type: "http", url: 42 }; + return { ...request, tools: [...request.tools, tool], mcpServers: { + ...request.mcpServers, company: { type: "http", url: "https://tools.example.com/mcp" }, + } }; }); return () => {}; } @@ -247,6 +249,62 @@ describe("plugin agent tools SDK boundary", () => { }); }); +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"; + export default function contribute(server: PluginServerContext) { + server.addHook("worktree.create.before", async ({ request }) => { + if (request.kind === "checkout-branch") { + // @ts-expect-error Branch checkout has no branch-off base. + request.baseRef; + } else { + const base: string = request.baseRef; + } + const branch: string = request.branch; + // @ts-expect-error Repository identity is read-only. + request.repoRoot = "/other"; + // @ts-expect-error Source checkout identity is read-only. + request.sourceCheckout = "/other"; + if (request.kind === "checkout-change-request") { + const number: number = request.changeRequestNumber; + } + return { ...request, branch: "feature", baseRef: "main", slug: "feature", path: "/work/feature" }; + }); + server.addHook("worktree.create.before", async () => {}); + server.addHook("worktree.create.after", async ({ worktree }) => { + const path: string = worktree.path; + const branch: string = worktree.branch; + const source: string = worktree.sourceCheckout; + // @ts-expect-error Worktree facts have no workspace identity. + worktree.workspaceId; + }); + server.addHook("workspace.create.before", async ({ request }) => ({ ...request, title: "Changed" })); + server.addHook("workspace.create.before", async () => {}); + server.addHook("agent.open.before", async () => {}); + server.addHook("agent.turn.after", async ({ agent, outcome, timeline }, { paseo, signal }) => { + const kind: "completed" | "failed" | "canceled" = outcome.kind; + // @ts-expect-error Notification payloads have no creation request. + outcome.request; + }); + // @ts-expect-error Async handlers are required even for notifications. + server.addHook("agent.turn.before", () => {}); + // @ts-expect-error Legacy names are only accepted by deprecated registration methods. + server.addHook("agent.session_open", async () => {}); + // @ts-expect-error Unknown names fail typechecking. + server.addHook("nonsense", async () => {}); + // @ts-expect-error A prepare handler must return the whole request or undefined. + server.addHook("agent.create.before", async () => ({ invalid: true })); + server.before("agent.session_open", ({ request }) => request); + server.on("agent.turn_ended", () => {}); + return () => {}; + } + `), + ).toEqual([]); + }); +}); + describe("agent session reload SDK boundary", () => { it("exposes reload separately from snapshot refresh", () => { expect( diff --git a/packages/plugin/src/server/acp-internal/connection.ts b/packages/plugin/src/server/acp-internal/connection.ts index b2fbee8e2c..86e22b2afe 100644 --- a/packages/plugin/src/server/acp-internal/connection.ts +++ b/packages/plugin/src/server/acp-internal/connection.ts @@ -997,7 +997,9 @@ class AcpRuntime { ): string { if (messageId) { this.fallbackChunkIds.delete(kind); - return messageId; + // Native IDs identify a message within its chunk kind. Timeline IDs must + // also distinguish reasoning from replies and from generated fallback IDs. + return JSON.stringify([kind, messageId]); } let id = this.fallbackChunkIds.get(kind); if (!id) { diff --git a/packages/plugin/src/server/acp.test.ts b/packages/plugin/src/server/acp.test.ts index f4b429578f..1d99c73a75 100644 --- a/packages/plugin/src/server/acp.test.ts +++ b/packages/plugin/src/server/acp.test.ts @@ -1307,7 +1307,15 @@ describe("runAcpProvider streamed chunks without messageId (#4699)", () => { const items = events.flatMap((event) => event.type === "timeline.item" && (event.item.type === "assistant_message" || event.item.type === "reasoning") - ? [{ id: event.item.id, text: event.item.text }] + ? [ + { + id: event.item.id, + text: event.item.text, + ...(event.item.type === "assistant_message" && event.item.messageId + ? { messageId: event.item.messageId } + : {}), + }, + ] : [], ); expect(items).toEqual([ @@ -1315,7 +1323,11 @@ describe("runAcpProvider streamed chunks without messageId (#4699)", () => { { id: "agent_message_chunk:1", text: "- **Current temperature**: 25°C" }, { id: "agent_message_chunk:2", text: "next turn" }, { id: "agent_thought_chunk:3", text: "think A" }, - { id: "m-explicit", text: "say" }, + { + id: JSON.stringify(["agent_message_chunk", "m-explicit"]), + messageId: "m-explicit", + text: "say", + }, { id: "agent_thought_chunk:4", text: "think B" }, ]); await connection.close(); @@ -1402,6 +1414,21 @@ async function streamChunkTurns( } describe("ACP streamed message boundaries", () => { + it("keeps reasoning separate from a reply sharing its native message ID", async () => { + expect( + await streamChunkTurns([ + textChunk("private ", "agent_thought_chunk", "shared-id"), + textChunk("reasoning", "agent_thought_chunk", "shared-id"), + textChunk("public ", "agent_message_chunk", "shared-id"), + textChunk("reply", "agent_message_chunk", "shared-id"), + ]), + ).toEqual([ + { type: "reasoning", text: "private reasoning" }, + { type: "assistant_message", text: "public reply" }, + { type: "assistant_message", text: "Next turn" }, + ]); + }); + it.each([ { name: "tool call", @@ -1584,8 +1611,12 @@ describe("ACP session history replay", () => { ); try { expect(timelineProjection(events)).toEqual([ - { type: "user_message", id: "user-1", text: "What is the " }, - { type: "user_message", id: "user-1", text: "What is the temperature?" }, + { type: "user_message", id: '["user_message_chunk","user-1"]', text: "What is the " }, + { + type: "user_message", + id: '["user_message_chunk","user-1"]', + text: "What is the temperature?", + }, { type: "reasoning", id: "agent_thought_chunk:1", text: "Checking the sensor" }, { type: "tool_call", id: "tool-1", status: "running" }, { type: "tool_call", id: "tool-1", status: "completed" }, @@ -1599,6 +1630,48 @@ describe("ACP session history replay", () => { } }); + it("keeps replayed user, reasoning and reply chunks separate when their native IDs match", async () => { + const { connection, events } = await openReplaySession( + [ + userChunk("What is the ", "shared-id"), + userChunk("temperature?", "shared-id"), + textChunk("Checking ", "agent_thought_chunk", "shared-id"), + textChunk("the sensor", "agent_thought_chunk", "shared-id"), + textChunk("It is ", "agent_message_chunk", "shared-id"), + textChunk("25°C", "agent_message_chunk", "shared-id"), + ], + "replay", + ); + try { + const items = new Map( + events.flatMap((event) => + event.type === "timeline.item" ? [[event.item.id, event.item] as const] : [], + ), + ); + expect([...items.values()]).toEqual([ + { + type: "user_message", + id: '["user_message_chunk","shared-id"]', + messageId: "shared-id", + text: "What is the temperature?", + }, + { + type: "reasoning", + id: '["agent_thought_chunk","shared-id"]', + text: "Checking the sensor", + }, + { + type: "assistant_message", + id: '["agent_message_chunk","shared-id"]', + messageId: "shared-id", + text: "It is 25°C", + }, + ]); + } finally { + await connection.close(); + } + }); + it("continues anonymous user chunks into one message and starts a new one after an agent reply", async () => { const { connection, events } = await openReplaySession( [ diff --git a/packages/plugin/src/server/index.ts b/packages/plugin/src/server/index.ts index 264effafdf..bb6bf4ede8 100644 --- a/packages/plugin/src/server/index.ts +++ b/packages/plugin/src/server/index.ts @@ -13,8 +13,15 @@ export type { PluginSettingsState, } from "./contracts.js"; export type { + PluginHooks, + PluginHookEvents, + PluginHookRequests, + PluginHookPayload, + PluginHookResult, PluginHookContext, PluginHookWorkspace, + PluginHookWorktree, + PluginWorktreeCreateRequest, PluginHookAgent, PluginSessionOpenRequest, PluginTurnOutcome, diff --git a/packages/plugin/src/server/lifecycle.ts b/packages/plugin/src/server/lifecycle.ts index f3f2643a04..20df9c2dcb 100644 --- a/packages/plugin/src/server/lifecycle.ts +++ b/packages/plugin/src/server/lifecycle.ts @@ -21,6 +21,46 @@ export interface PluginHookWorkspace { archivedAt: string | null; } +export interface PluginHookWorktree { + path: string; + branch: string; + sourceCheckout: string; +} + +/** Resolved creation options before Git fetches refs or chooses a unique branch name. */ +export type PluginWorktreeCreateRequest = { + readonly repoRoot: string; + readonly sourceCheckout: string; + branch: string; + slug: string; + path: string; +} & ( + | { kind: "branch-off"; baseRef: string } + | { kind: "checkout-branch" } + | { + kind: "checkout-change-request"; + baseRef: string; + forge: string; + changeRequestNumber: number; + headRef: string; + headRepositoryOwner?: string; + headRepository?: string; + checkoutRefs?: { remoteName?: string; remoteRef: string }[]; + pushRemoteUrl?: string; + trackOriginHead?: boolean; + } + | { + kind: "checkout-github-pr"; + baseRef: string; + githubPrNumber: number; + headRef: string; + headRepositoryOwner?: string; + checkoutRefs?: { remoteName?: string; remoteRef: string }[]; + pushRemoteUrl?: string; + trackOriginHead?: boolean; + } +); + export interface PluginHookAgent { id: string; workspaceId: string | null; @@ -41,6 +81,7 @@ export interface PluginSessionOpenRequest { readonly labels: Readonly>; tools: AgentToolDefinition[]; env: Record; + mcpServers: NonNullable; } export type PluginTurnOutcome = @@ -48,9 +89,9 @@ export type PluginTurnOutcome = | { kind: "failed"; error: { message: string; code?: string } } | { kind: "canceled"; reason: string }; -export interface PluginLifecycleEvents { - "agent.turn_started": { agent: PluginHookAgent; turnId: string | null }; - "agent.turn_ended": { +export interface PluginHookEvents { + "agent.turn.before": { agent: PluginHookAgent; turnId: string | null }; + "agent.turn.after": { agent: PluginHookAgent; turnId: string | null; outcome: PluginTurnOutcome; @@ -60,26 +101,58 @@ export interface PluginLifecycleEvents { */ timeline: readonly AgentTimelineItem[]; }; - "agent.permission_requested": { agent: PluginHookAgent; request: AgentPermissionRequest }; - "agent.permission_resolved": { + "agent.permission.before": { agent: PluginHookAgent; request: AgentPermissionRequest }; + "agent.permission.after": { agent: PluginHookAgent; requestId: string; resolution: AgentPermissionResponse; }; - "agent.archived": { agent: PluginHookAgent; archivedAt: string }; - "agent.created": { agent: PluginHookAgent }; - "agent.closed": { agent: PluginHookAgent }; - "workspace.created": { workspace: PluginHookWorkspace }; - "workspace.archived": { workspace: PluginHookWorkspace }; + "agent.archive.after": { agent: PluginHookAgent; archivedAt: string }; + "agent.create.after": { agent: PluginHookAgent }; + "agent.close.after": { agent: PluginHookAgent }; + "workspace.create.after": { workspace: PluginHookWorkspace }; + "workspace.archive.after": { workspace: PluginHookWorkspace }; } -export interface PluginBeforeRequests { - "agent.create": { config: AgentSessionConfig; env?: Record }; - "agent.session_open": PluginSessionOpenRequest; - "workspace.create": Omit; +export interface PluginHookRequests { + "worktree.create.before": PluginWorktreeCreateRequest; + "agent.create.before": { config: AgentSessionConfig; env?: Record }; + "agent.open.before": PluginSessionOpenRequest; + "workspace.create.before": Omit; } +export type PluginHooks = { + [Name in keyof PluginHookRequests]: { + request: PluginHookRequests[Name]; + result: PluginHookRequests[Name]; + }; +} & { [Name in keyof PluginHookEvents]: { payload: PluginHookEvents[Name] } } & { + "worktree.create.after": { payload: { worktree: PluginHookWorktree } }; +}; + +export type PluginHookPayload = { + [Key in keyof PluginHooks]: PluginHooks[Key] extends { request: infer Request } + ? { request: Request } + : PluginHooks[Key] extends { payload: infer Payload } + ? Payload + : never; +}[Name]; +export type PluginHookResult = { + [Key in keyof PluginHooks]: PluginHooks[Key] extends { result: infer Result } + ? Result | void + : void; +}[Name]; + +type HookHandlers = { + [Name in keyof PluginHooks]: ( + payload: PluginHookPayload, + context: PluginHookContext, + ) => Promise>; +}; + export interface PluginLifecycleRegistration { + addHook(name: Name, handler: HookHandlers[Name]): () => void; + /** @deprecated Use addHook with the renamed hook. Removed after 2027-04-30. */ on( name: Name, handler: ( @@ -87,6 +160,7 @@ export interface PluginLifecycleRegistration { context: PluginHookContext, ) => void | Promise, ): () => void; + /** @deprecated Use addHook with the renamed hook. Removed after 2027-04-30. */ before( name: Name, handler: ( @@ -95,3 +169,69 @@ export interface PluginLifecycleRegistration { ) => PluginBeforeRequests[Name] | void | Promise, ): () => void; } + +/** @internal Lifecycle policy shared by the daemon and plugin process. */ +export const pluginHookRegistry = { + "workspace.create.before": { waits: true }, + "workspace.create.after": { waits: false }, + "workspace.archive.after": { waits: false }, + "worktree.create.before": { waits: true }, + "worktree.create.after": { waits: true }, + "agent.create.before": { waits: true }, + "agent.create.after": { waits: false }, + "agent.open.before": { waits: true }, + "agent.close.after": { waits: false }, + "agent.archive.after": { waits: false }, + "agent.turn.before": { waits: false }, + "agent.turn.after": { waits: false }, + "agent.permission.before": { waits: false }, + "agent.permission.after": { waits: false }, +} as const satisfies Record; + +// COMPAT(pluginHookNames): added in v0.14, remove after 2027-04-30 +const legacyEvents = { + "workspace.created": "workspace.create.after", + "workspace.archived": "workspace.archive.after", + "agent.created": "agent.create.after", + "agent.closed": "agent.close.after", + "agent.archived": "agent.archive.after", + "agent.turn_started": "agent.turn.before", + "agent.turn_ended": "agent.turn.after", + "agent.permission_requested": "agent.permission.before", + "agent.permission_resolved": "agent.permission.after", +} as const; +const legacyRequests = { + "workspace.create": "workspace.create.before", + "agent.create": "agent.create.before", + "agent.session_open": "agent.open.before", +} as const; +export type PluginLifecycleEvents = { + [Name in keyof typeof legacyEvents]: PluginHookEvents[(typeof legacyEvents)[Name]]; +}; +export type PluginBeforeRequests = { + [Name in keyof typeof legacyRequests]: PluginHookRequests[(typeof legacyRequests)[Name]]; +}; + +/** @internal SDK adapter for the daemon's hook registry. */ +export function createLifecycleRegistration( + register: ( + name: keyof PluginHooks, + handler: (input: never, context: PluginHookContext) => unknown, + ) => () => void, +): PluginLifecycleRegistration { + const names = new Set(Object.keys(pluginHookRegistry)); + return { + addHook(name, handler) { + if (!names.has(name)) throw new Error(`Unknown lifecycle hook: ${name}`); + return register(name, handler); + }, + on(name, handler) { + if (!Object.hasOwn(legacyEvents, name)) throw new Error(`Unknown lifecycle event: ${name}`); + return register(legacyEvents[name], handler); + }, + before(name, handler) { + if (!Object.hasOwn(legacyRequests, name)) throw new Error(`Unknown before hook: ${name}`); + return register(legacyRequests[name], handler); + }, + }; +} diff --git a/packages/protocol/package.json b/packages/protocol/package.json index e463e681e7..70d783f701 100644 --- a/packages/protocol/package.json +++ b/packages/protocol/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/protocol", - "version": "0.13.2", + "version": "0.15.0-beta.1", "description": "Paseo shared protocol schemas and wire types", "files": [ "dist", diff --git a/packages/protocol/src/agent-types.ts b/packages/protocol/src/agent-types.ts index c7fffe8ce9..ca04655430 100644 --- a/packages/protocol/src/agent-types.ts +++ b/packages/protocol/src/agent-types.ts @@ -288,7 +288,7 @@ export type ToolCallDetail = subAgentType?: string; description?: string; childSessionId?: string; - log: string; + log?: string; actions?: Array<{ index: number; toolName: string; diff --git a/packages/protocol/src/binary-frames/demux.test.ts b/packages/protocol/src/binary-frames/demux.test.ts index c56e417528..a350cfaf03 100644 --- a/packages/protocol/src/binary-frames/demux.test.ts +++ b/packages/protocol/src/binary-frames/demux.test.ts @@ -89,3 +89,18 @@ describe("host route binary framing", () => { ).toThrow("Invalid host route ID"); }); }); + +it.each([ + TerminalStreamOpcode.ReplayBegin, + TerminalStreamOpcode.ReplayData, + TerminalStreamOpcode.ReplayEnd, +])("decodes replay opcode %s directly and inside a host route", (opcode) => { + const payload = new TextEncoder().encode("界 replay"); + const bytes = encodeTerminalStreamFrame({ opcode, slot: 12, payload }); + const expected = { kind: "terminal", frame: { opcode, slot: 12, payload } }; + expect(decodeBinaryFrame(bytes)).toEqual(expected); + const routed = decodeBinaryFrame(encodeHostRouteFrame("host", bytes)); + expect(routed?.kind).toBe("host_route"); + if (routed?.kind !== "host_route") throw new Error("Missing host route"); + expect(decodeBinaryFrame(routed.frame.payload)).toEqual(expected); +}); diff --git a/packages/protocol/src/binary-frames/demux.ts b/packages/protocol/src/binary-frames/demux.ts index a8503b898f..c207026362 100644 --- a/packages/protocol/src/binary-frames/demux.ts +++ b/packages/protocol/src/binary-frames/demux.ts @@ -25,6 +25,9 @@ export function decodeBinaryFrame(bytes: Uint8Array): BinaryFrame | null { case TerminalStreamOpcode.Input: case TerminalStreamOpcode.Resize: case TerminalStreamOpcode.Snapshot: + case TerminalStreamOpcode.ReplayBegin: + case TerminalStreamOpcode.ReplayData: + case TerminalStreamOpcode.ReplayEnd: case TerminalStreamOpcode.Restore: { const frame = decodeTerminalStreamFrame(bytes); return frame ? { kind: "terminal", frame } : null; diff --git a/packages/protocol/src/binary-frames/host-route.ts b/packages/protocol/src/binary-frames/host-route.ts index f45cd714f9..643dcb4e98 100644 --- a/packages/protocol/src/binary-frames/host-route.ts +++ b/packages/protocol/src/binary-frames/host-route.ts @@ -3,6 +3,11 @@ import { MAX_WEBSOCKET_MESSAGE_BYTES } from "../websocket-message-limit.js"; export const HOST_ROUTE_OPCODE = 0x30; export const MAX_HOST_ROUTE_ID_BYTES = 256; export const MAX_HOST_ROUTE_HEADER_BYTES = 3 + MAX_HOST_ROUTE_ID_BYTES; +// A logical host channel crosses the 32 MiB route admission boundary. Text can +// expand sixfold when enclosed in JSON; binary adds the bounded route header. +export const MAX_HOST_CHANNEL_FRAME_BYTES = Math.floor( + (32 * 1024 * 1024 - MAX_HOST_ROUTE_HEADER_BYTES) / 6, +); export const MAX_ROUTED_PAYLOAD_BYTES = MAX_WEBSOCKET_MESSAGE_BYTES - MAX_HOST_ROUTE_HEADER_BYTES; export interface HostRouteFrame { routeId: string; diff --git a/packages/protocol/src/binary-frames/terminal.ts b/packages/protocol/src/binary-frames/terminal.ts index 3936502c89..b74ea7a8de 100644 --- a/packages/protocol/src/binary-frames/terminal.ts +++ b/packages/protocol/src/binary-frames/terminal.ts @@ -1,6 +1,12 @@ import { z } from "zod"; import { TerminalStateSchema } from "../messages.js"; +export const TerminalReplayMetadataSchema = z.object({ + rows: z.number().int().positive(), + cols: z.number().int().positive(), + retainedHistoryLines: z.number().int().nonnegative(), +}); + export const TerminalStreamResizeSchema = z.object({ rows: z.number().int().positive(), cols: z.number().int().positive(), @@ -13,6 +19,9 @@ export const TerminalStreamOpcode = { Resize: 0x03, Snapshot: 0x04, Restore: 0x05, + ReplayBegin: 0x06, + ReplayData: 0x07, + ReplayEnd: 0x08, } as const; export type TerminalStreamOpcode = (typeof TerminalStreamOpcode)[keyof typeof TerminalStreamOpcode]; @@ -58,6 +67,9 @@ function isTerminalStreamOpcode(value: number): value is TerminalStreamOpcode { value === TerminalStreamOpcode.Input || value === TerminalStreamOpcode.Resize || value === TerminalStreamOpcode.Snapshot || + value === TerminalStreamOpcode.ReplayBegin || + value === TerminalStreamOpcode.ReplayData || + value === TerminalStreamOpcode.ReplayEnd || value === TerminalStreamOpcode.Restore ); } diff --git a/packages/protocol/src/chunked-transport.test.ts b/packages/protocol/src/chunked-transport.test.ts new file mode 100644 index 0000000000..3979b48885 --- /dev/null +++ b/packages/protocol/src/chunked-transport.test.ts @@ -0,0 +1,392 @@ +import { describe, expect, it } from "vitest"; +import { ChunkedTransport } from "./chunked-transport.js"; + +describe("chunked transport", () => { + it("delivers a large UTF-8 logical message once, preserving order", async () => { + const delivered: (string | Uint8Array)[] = []; + const receiver = new ChunkedTransport({ + frameBytes: 17, + send: () => {}, + deliver: (v) => delivered.push(v), + }); + receiver.enabled = true; + const frames: (string | Uint8Array)[] = []; + const sender = new ChunkedTransport({ + frameBytes: 17, + send: (v) => { + frames.push(v); + receiver.receive(v); + }, + deliver: () => {}, + }); + sender.enabled = true; + const text = "🌍".repeat(100); + await sender.send(text); + expect(delivered).toEqual([text]); + expect(frames.length).toBeGreaterThan(1); + expect(frames.every((v) => v instanceof Uint8Array && v.byteLength <= 17)).toBe(true); + }); +}); + +it("preserves binary kind and leaves legacy frames unchanged", async () => { + const delivered: (string | Uint8Array)[] = []; + const receiver = new ChunkedTransport({ + frameBytes: 8, + send: () => {}, + deliver: (v) => delivered.push(v), + }); + const frames: (string | Uint8Array)[] = []; + const sender = new ChunkedTransport({ + frameBytes: 8, + send: (v) => { + frames.push(v); + receiver.receive(v); + }, + deliver: () => {}, + }); + const data = new Uint8Array(40).fill(5); + await sender.send(data); + expect(frames).toEqual([data]); + frames.length = 0; + sender.enabled = receiver.enabled = true; + await sender.send(data); + expect(frames).toHaveLength(10); + expect(delivered).toEqual([data, data]); +}); + +it("rejects malformed sequences and drops incomplete transfers on close", () => { + const delivered: unknown[] = []; + const receiver = new ChunkedTransport({ + frameBytes: 8, + send: () => {}, + deliver: (v) => delivered.push(v), + }); + receiver.enabled = true; + receiver.receive(new Uint8Array([0x31, 1, 0, 1, 65])); + expect(() => receiver.receive("interrupted")).toThrow("Interrupted"); + receiver.receive(new Uint8Array([0x31, 1, 0, 2, 66])); + expect(delivered).toEqual([]); +}); + +it("waits for drain before the next chunk and preserves logical ordering", async () => { + const frames: (string | Uint8Array)[] = []; + let drain!: () => void; + const sender = new ChunkedTransport({ + frameBytes: 8, + send: (v) => { + frames.push(v); + if (frames.length === 1) + return new Promise((resolve) => { + drain = resolve; + }); + }, + deliver: () => {}, + }); + sender.enabled = true; + const first = sender.send("abcdefghij"); + const next = new Uint8Array([1, 2, 3, 4]); + const second = sender.send(next); + await Promise.resolve(); + expect(frames).toHaveLength(1); + expect(sender.queuedByteLength).toBe(4); + drain(); + await Promise.all([first, second]); + expect(frames).toHaveLength(4); + expect(frames[3]).toEqual(next); + expect(sender.queuedByteLength).toBe(0); +}); + +it.each([ + [0x31, 2, 0, 3, 65], + [0x31, 1, 2, 3, 65], + [0x31, 1, 0, 4, 65], + [0x31, 1, 0, 2, 65], + [0x31, 1, 0, 1], +])("rejects malformed chunk metadata %j", (...bytes) => { + const receiver = new ChunkedTransport({ + frameBytes: 8, + send: () => {}, + deliver: () => { + throw new Error("Unexpected delivery"); + }, + }); + receiver.enabled = true; + expect(() => receiver.receive(new Uint8Array(bytes))).toThrow(); +}); + +it("reconnect discards partial state and requires negotiation again", () => { + const delivered: unknown[] = []; + const create = () => + new ChunkedTransport({ frameBytes: 8, send: () => {}, deliver: (v) => delivered.push(v) }); + const old = create(); + old.enabled = true; + old.receive(new Uint8Array([0x31, 1, 0, 1, 65])); + old.close(); + old.receive(new Uint8Array([0x31, 1, 0, 2, 66])); + const fresh = create(); + expect(fresh.enabled).toBe(false); + fresh.enabled = true; + fresh.receive(new Uint8Array([0x31, 1, 0, 3, 67])); + expect(delivered).toEqual(["C"]); +}); + +it("bounds logical messages waiting behind a blocked writer", async () => { + let drain!: () => void; + const transport = new ChunkedTransport({ + frameBytes: 32 * 1024 * 1024, + send: () => + new Promise((resolve) => { + drain = resolve; + }), + deliver: () => {}, + }); + const first = transport.send(new Uint8Array(100 * 1024 * 1024)); + const overflow = transport.send("one more byte"); + try { + await expect(overflow).rejects.toThrow("queue"); + } finally { + drain(); + await first; + } +}); + +it("requests drain for chunks while ordinary frames keep the immediate write path", async () => { + const waits: boolean[] = []; + const transport = new ChunkedTransport({ + frameBytes: 8, + send: (_frame, wait) => { + waits.push(wait); + }, + deliver: () => {}, + }); + transport.enabled = true; + await transport.send("small"); + await transport.send("abcdefghij"); + expect(waits).toEqual([false, true, true, true]); +}); + +it("charges queued ASCII messages by their UTF-8 bytes", async () => { + let drain!: () => void; + let blocked = true; + const transport = new ChunkedTransport({ + frameBytes: 32 * 1024 * 1024, + send: () => { + if (blocked) { + blocked = false; + return new Promise((resolve) => { + drain = resolve; + }); + } + }, + deliver: () => {}, + }); + transport.enabled = true; + const first = transport.send(new Uint8Array([1])); + const text = "x".repeat(10 * 1024 * 1024); + const queued = Array.from({ length: 4 }, () => transport.send(text)); + const settled = Promise.allSettled(queued); + expect(transport.queuedByteLength).toBe(40 * 1024 * 1024); + drain(); + await first; + expect((await settled).map((result) => result.status)).toEqual([ + "fulfilled", + "fulfilled", + "fulfilled", + "fulfilled", + ]); +}); + +it("notifies the socket owner when an awaited send overflows the queue", async () => { + let drain!: () => void; + const failures: unknown[] = []; + const transport = new ChunkedTransport({ + frameBytes: 32 * 1024 * 1024, + send: () => + new Promise((resolve) => { + drain = resolve; + }), + deliver: () => {}, + onFailure: (error) => { + failures.push(error); + }, + }); + const first = transport.send(new Uint8Array(100 * 1024 * 1024)); + const overflow = transport.send("extra"); + await expect(overflow).rejects.toThrow("queue"); + drain(); + await first; + expect(failures).toHaveLength(1); +}); + +it("bounds retained reassembly memory for many one-byte chunks", async () => { + const { spawnSync } = await import("node:child_process"); + // Exercise the built package as a Node consumer; CI builds it before protocol tests. + const entry = new URL("../dist/chunked-transport.js", import.meta.url).href; + const result = spawnSync( + process.execPath, + [ + "--expose-gc", + "--input-type=module", + "-e", + ` + import { ChunkedTransport } from ${JSON.stringify(entry)}; + let delivered = 0; + const receiver = new ChunkedTransport({ frameBytes: 8, send() {}, deliver(frame) { delivered = frame.byteLength; } }); + receiver.enabled = true; + global.gc(); + const before = process.memoryUsage().heapUsed; + receiver.receive(new Uint8Array([0x31, 1, 1, 1, 65])); + for (let index = 0; index < 300000; index++) receiver.receive(new Uint8Array([0x31, 1, 1, 0, 65])); + global.gc(); + const growth = process.memoryUsage().heapUsed - before; + receiver.receive(new Uint8Array([0x31, 1, 1, 2, 66])); + console.log(JSON.stringify({ growth, delivered })); + `, + ], + { encoding: "utf8", timeout: 15000 }, + ); + expect(result.status, result.stderr).toBe(0); + const observed = JSON.parse(result.stdout); + expect(observed.delivered).toBe(300002); + expect(observed.growth).toBeLessThan(8 * 1024 * 1024); +}, 20000); + +it.each(["ASCII", "中", "🌍", "\ud800", "\udc00", "\ud800x"])( + "accounts for queued UTF-8 text %j exactly", + async (text) => { + let drain!: () => void; + let blocked = true; + const transport = new ChunkedTransport({ + frameBytes: 1024, + send: () => { + if (blocked) { + blocked = false; + return new Promise((resolve) => { + drain = resolve; + }); + } + }, + deliver: () => {}, + }); + const first = transport.send(new Uint8Array([1])); + const second = transport.send(text); + expect(transport.queuedByteLength).toBe(new TextEncoder().encode(text).byteLength); + drain(); + await Promise.all([first, second]); + }, +); + +it("notifies the owner once when an accepted writer fails", async () => { + const failures: unknown[] = []; + const error = new Error("write failed"); + const transport = new ChunkedTransport({ + frameBytes: 1024, + deliver: () => {}, + onFailure: (failure) => { + failures.push(failure); + }, + send: () => Promise.reject(error), + }); + await expect(transport.send("hello", { waitForDrain: true })).rejects.toThrow("write failed"); + expect(failures).toEqual([error]); + expect(() => transport.send("again")).toThrow("Transport closed"); + expect(failures).toEqual([error]); +}); + +it.each([false, true])( + "a pre-write rejection preserves the sender (chunked=%s)", + async (chunked) => { + const failures: unknown[] = []; + let reject = true; + const transport = new ChunkedTransport({ + frameBytes: 8, + deliver: () => {}, + onFailure: (error) => { + failures.push(error); + }, + send: () => { + if (reject) throw new Error("capacity"); + }, + }); + transport.enabled = chunked; + expect(() => transport.send("abcdefghij")).toThrow("capacity"); + expect(failures).toEqual([]); + reject = false; + await transport.send("sibling"); + }, +); + +it("a queued pre-write rejection does not poison the next logical send", async () => { + let drain!: () => void; + const failures: unknown[] = []; + const delivered: string[] = []; + const transport = new ChunkedTransport({ + frameBytes: 1024, + deliver: () => {}, + onFailure: (error) => { + failures.push(error); + }, + send: (frame) => { + if (frame === "blocked") + return new Promise((resolve) => { + drain = resolve; + }); + if (frame === "reject") throw new Error("capacity"); + delivered.push(frame as string); + }, + }); + const first = transport.send("blocked"); + const rejected = transport.send("reject"); + const sibling = transport.send("sibling"); + const results = Promise.allSettled([first, rejected, sibling]); + drain(); + expect((await results).map((result) => result.status)).toEqual([ + "fulfilled", + "rejected", + "fulfilled", + ]); + expect(delivered).toEqual(["sibling"]); + expect(failures).toEqual([]); +}); + +it.each([false, true])("delivery errors leave framing usable (chunked=%s)", async (chunked) => { + let fail = true; + const delivered: (string | Uint8Array)[] = []; + const transport = new ChunkedTransport({ + frameBytes: 64, + send: () => {}, + deliver: (frame) => { + if (fail) throw new Error("listener failed"); + delivered.push(frame); + }, + }); + transport.enabled = chunked; + const frame = chunked ? new Uint8Array([0x31, 1, 0, 3, 65]) : "A"; + expect(() => transport.receive(frame)).toThrow("listener failed"); + fail = false; + transport.receive(frame); + expect(delivered).toEqual(["A"]); + await transport.send("still connected"); +}); + +it("unpaced transports retain ordinary outbound admission and accept inbound chunks", async () => { + const frames: unknown[] = []; + const delivered: unknown[] = []; + const transport = new ChunkedTransport({ + frameBytes: 8, + supportsDrain: false, + send: (frame) => { + frames.push(frame); + if (typeof frame === "string" && frame.length > 8) throw new Error("single frame limit"); + }, + deliver: (frame) => { + delivered.push(frame); + }, + }); + transport.enabled = true; + expect(() => transport.send("too large for one frame")).toThrow("single frame limit"); + expect(frames).toEqual(["too large for one frame"]); + transport.receive(new Uint8Array([0x31, 1, 0, 3, 65])); + expect(delivered).toEqual(["A"]); + await transport.send("small"); +}); diff --git a/packages/protocol/src/chunked-transport.ts b/packages/protocol/src/chunked-transport.ts new file mode 100644 index 0000000000..a32d68424f --- /dev/null +++ b/packages/protocol/src/chunked-transport.ts @@ -0,0 +1,214 @@ +import { MAX_WEBSOCKET_MESSAGE_BYTES } from "./websocket-message-limit.js"; + +type Frame = string | Uint8Array; + +/** A malformed wire frame, distinct from a consumer delivery failure. */ +export class ChunkedTransportProtocolError extends Error {} +// Reserved outside the application binary opcode space. Version, kind, flags follow. +const OPCODE = 0x31; +const HEADER = 4; + +/** Connection-scoped ordered framing, below serialization and routing, above encryption. */ +export class ChunkedTransport { + enabled = false; + private assembly: Uint8Array | undefined; + private size = 0; + private kind = 0; + private closed = false; + private pending: Promise | undefined; + private queuedBytes = 0; + private activeBytes = 0; + + constructor( + private readonly io: { + frameBytes: number; + supportsDrain?: boolean; + send: (frame: Frame, waitForDrain: boolean) => void | Promise; + deliver: (frame: Frame) => void; + onFailure?: (error: unknown) => void; + }, + ) { + if (io.frameBytes <= HEADER) throw new Error("Invalid transport frame budget"); + } + + /** Bytes waiting behind the active write; physical buffering owns the active frame. */ + get queuedByteLength(): number { + return this.queuedBytes - this.activeBytes; + } + get isWriting(): boolean { + return this.pending !== undefined; + } + + send(frame: Frame, options: { waitForDrain?: boolean; byteLength?: number } = {}): Promise { + const byteLength = options.byteLength ?? frameByteLength(frame); + if (byteLength > MAX_WEBSOCKET_MESSAGE_BYTES) throw new Error("Logical message too large"); + const chunk = + this.enabled && this.io.supportsDrain !== false && byteLength > this.io.frameBytes; + if (this.closed) throw new Error("Transport closed"); + const write = () => { + if (this.closed) throw new Error("Transport closed"); + this.activeBytes = byteLength; + // A synchronous rejection did not admit a frame. Only accepted writes can + // fail the connection; queued admission failures still belong to their sender. + const result = chunk + ? this.sendChunks( + typeof frame === "string" ? new TextEncoder().encode(frame) : frame, + typeof frame === "string", + ) + : this.io.send(frame, options.waitForDrain === true); + if (!result) return; + return result.catch((error) => { + this.fail(error); + throw error; + }); + }; + if (this.queuedBytes + byteLength > MAX_WEBSOCKET_MESSAGE_BYTES) { + const error = new Error("Logical output queue exceeded its byte limit"); + this.fail(error); + const rejected = Promise.reject(error); + void rejected.catch(() => {}); + return rejected; + } + this.queuedBytes += byteLength; + let result: void | Promise; + try { + result = this.pending ? this.pending.then(write) : write(); + } catch (error) { + this.queuedBytes -= byteLength; + this.activeBytes = 0; + throw error; + } + if (!result) { + this.queuedBytes -= byteLength; + this.activeBytes = 0; + return Promise.resolve(); + } + const completion = Promise.resolve(result).finally(() => { + this.queuedBytes -= byteLength; + this.activeBytes = 0; + }); + const tail = completion.then( + () => undefined, + () => undefined, + ); + this.pending = tail; + void tail.then(() => { + if (this.pending === tail) this.pending = undefined; + return undefined; + }); + return completion; + } + + private sendChunks(bytes: Uint8Array, text: boolean): Promise { + const capacity = this.io.frameBytes - HEADER; + const writeChunk = (offset: number) => { + if (this.closed) throw new Error("Transport closed"); + const end = Math.min(bytes.byteLength, offset + capacity); + const wire = new Uint8Array(HEADER + end - offset); + wire.set([ + OPCODE, + 1, + text ? 0 : 1, + (offset === 0 ? 1 : 0) | (end === bytes.byteLength ? 2 : 0), + ]); + wire.set(bytes.subarray(offset, end), HEADER); + return this.io.send(wire, true); + }; + const first = writeChunk(0); + return (async () => { + await first; + for (let offset = capacity; offset < bytes.byteLength; offset += capacity) + await writeChunk(offset); + })(); + } + + receive(frame: Frame): void { + if (this.closed) return; + let message: Frame | undefined; + try { + message = this.assemble(frame); + } catch (error) { + this.close(); + throw new ChunkedTransportProtocolError( + error instanceof Error ? error.message : String(error), + { cause: error }, + ); + } + if (message !== undefined) this.io.deliver(message); + } + + private assemble(frame: Frame): Frame | undefined { + if (typeof frame === "string" || frame[0] !== OPCODE) { + if (this.assembly) throw new Error("Interrupted chunked message"); + return frame; + } + if ( + !this.enabled || + frame.length <= HEADER || + frame[1] !== 1 || + frame[2]! > 1 || + (frame[3]! & ~3) !== 0 + ) + throw new Error("Invalid chunk header"); + const start = (frame[3]! & 1) !== 0; + const end = (frame[3]! & 2) !== 0; + if (start === !!this.assembly) throw new Error("Invalid chunk sequence"); + if (start) { + this.assembly = new Uint8Array(0); + this.kind = frame[2]!; + this.size = 0; + } + if (frame[2] !== this.kind) throw new Error("Chunk kind changed"); + this.size += frame.length - HEADER; + if (this.size > MAX_WEBSOCKET_MESSAGE_BYTES) throw new Error("Logical message too large"); + const payload = frame.subarray(HEADER); + if (this.assembly!.byteLength < this.size) { + const capacity = Math.min( + MAX_WEBSOCKET_MESSAGE_BYTES, + Math.max(this.size, this.assembly!.byteLength * 2, 16384), + ); + const grown = new Uint8Array(capacity); + grown.set(this.assembly!.subarray(0, this.size - payload.byteLength)); + this.assembly = grown; + } + this.assembly!.set(payload, this.size - payload.byteLength); + if (!end) return; + const data = this.assembly!.subarray(0, this.size); + this.assembly = undefined; + this.size = 0; + return this.kind === 0 ? new TextDecoder("utf-8", { fatal: true }).decode(data) : data.slice(); + } + + private fail(error: unknown): void { + if (this.closed) return; + this.close(); + this.io.onFailure?.(error); + } + + close(): void { + this.closed = true; + this.enabled = false; + this.assembly = undefined; + this.size = 0; + } +} + +function frameByteLength(frame: Frame): number { + if (typeof frame !== "string") return frame.byteLength; + let bytes = 0; + for (let index = 0; index < frame.length; index++) { + const code = frame.charCodeAt(index); + if (code <= 0x7f) bytes++; + else if (code <= 0x7ff) bytes += 2; + else if ( + code >= 0xd800 && + code <= 0xdbff && + frame.charCodeAt(index + 1) >= 0xdc00 && + frame.charCodeAt(index + 1) <= 0xdfff + ) { + bytes += 4; + index++; + } else bytes += 3; + } + return bytes; +} diff --git a/packages/protocol/src/client-capabilities.ts b/packages/protocol/src/client-capabilities.ts index a35852cc06..3ae02671e7 100644 --- a/packages/protocol/src/client-capabilities.ts +++ b/packages/protocol/src/client-capabilities.ts @@ -1,4 +1,6 @@ export const CLIENT_CAPS = { + terminalChunkedReplay: "terminal_chunked_replay", + binaryChunkingV1: "binary_chunking_v1", helloRejection: "hello_rejection", // COMPAT(ownedSubscriptions): added in v0.8.0, remove legacy ownership after 2027-03-09. ownedSubscriptions: "owned_subscriptions", diff --git a/packages/protocol/src/messages.plugins.test.ts b/packages/protocol/src/messages.plugins.test.ts index f266b65988..47e91493fe 100644 --- a/packages/protocol/src/messages.plugins.test.ts +++ b/packages/protocol/src/messages.plugins.test.ts @@ -23,6 +23,29 @@ describe("plugin protocol compatibility", () => { expect(SessionOutboundMessageSchema.parse(message)).toEqual(message); }, ); + it.each([ + { type: "plugin.catalog.get.request", requestId: "catalog" }, + { + type: "plugin.catalog.get.request", + requestId: "catalog", + cachedClientBundles: [{ id: "example", clientBundleHash: "a".repeat(64) }], + }, + ])("parses plugin catalog requests %j", (request) => { + expect(SessionInboundMessageSchema.parse(request)).toEqual(request); + }); + it("parses plugin catalogs that leave out a client bundle the client already holds", () => { + const message = { + type: "plugin.catalog.get.response", + payload: { + requestId: "catalog", + plugins: [ + { id: "cached", clientBundleHash: "a".repeat(64) }, + { id: "changed", clientBundle: "bundle", clientBundleHash: "b".repeat(64) }, + ], + }, + }; + expect(SessionOutboundMessageSchema.parse(message)).toEqual(message); + }); it("preserves manifest metadata in plugin list responses", () => { const message = { type: "plugin.list.response", diff --git a/packages/protocol/src/messages.ts b/packages/protocol/src/messages.ts index 3034598f1e..18654bf337 100644 --- a/packages/protocol/src/messages.ts +++ b/packages/protocol/src/messages.ts @@ -229,6 +229,8 @@ export const MutableDaemonConfigSchema = z .optional(), app: z.object({ baseUrl: z.string() }).optional(), catalogRefreshTimeoutMs: z.number().int().positive().optional(), + // COMPAT(usageSetting): added in v0.14, remove after 2027-05-01. + usage: z.object({ enabled: z.boolean() }).optional(), browserTools: MutableBrowserToolsConfigSchema.default({ enabled: false }), providers: z.record(z.string(), MutableDaemonProviderConfigSchema).default({}), metadataGeneration: MutableMetadataGenerationConfigSchema.default({ providers: [] }), @@ -237,6 +239,9 @@ export const MutableDaemonConfigSchema = z // COMPAT(idleRuntimeCleanupSetting): added in v0.13.0, keep optional while old daemons are supported. // Persisted host-wide value, applied live by the daemon. idleRuntimeCleanup: z.boolean().optional(), + // COMPAT(restartRecovery): added in v0.14.0, keep optional for older hosts. + resumeOnStartup: z.boolean().optional(), + resumePrompt: z.string().optional(), appendSystemPrompt: z.string().default(""), terminalProfiles: z.array(TerminalProfileSchema).optional(), agentProfiles: z.array(AgentProfileSchema).optional(), @@ -253,6 +258,7 @@ export const MutableDaemonConfigPatchSchema = z .object({ relay: MutableRelayConfigSchema.partial().optional(), mcp: z.object({ injectIntoAgents: z.boolean().optional() }).passthrough().optional(), + usage: z.object({ enabled: z.boolean() }).optional(), browserTools: MutableBrowserToolsConfigSchema.partial().optional(), providers: z .record(z.string(), MutableDaemonProviderConfigSchema.partial().passthrough()) @@ -262,6 +268,8 @@ export const MutableDaemonConfigPatchSchema = z autoArchiveAfterMerge: z.boolean().optional(), enableTerminalAgentHooks: z.boolean().optional(), idleRuntimeCleanup: z.boolean().optional(), + resumeOnStartup: z.boolean().optional(), + resumePrompt: z.string().optional(), appendSystemPrompt: z.string().optional(), terminalProfiles: z.array(TerminalProfileSchema).optional(), agentProfiles: z.array(AgentProfileSchema).optional(), @@ -633,7 +641,9 @@ const ToolCallDetailPayloadSchema: z.ZodType = z.discri subAgentType: z.string().optional(), description: z.string().optional(), childSessionId: z.string().optional(), - log: z.string(), + // COMPAT(subagent-log): added in v0.14.1, remove after 2027-04-30. A sub-agent card is a + // launch marker; apps before v0.14.1 required `log`, so daemons still send it empty. + log: z.string().optional(), // Compat cruft for clients <= 0.1.65-beta.3 that required this field. Producers still // emit `[]`; nothing reads it. Drop the field (and the `[]` emissions) once those // clients are no longer in the field. @@ -1470,6 +1480,10 @@ export const DiagnosticsRequestSchema = z.object({ export const PluginCatalogGetRequestSchema = z.object({ type: z.literal("plugin.catalog.get.request"), requestId: z.string(), + /** Client bundles the client already holds; the daemon leaves out each one whose hash matches. */ + cachedClientBundles: z + .array(z.object({ id: PluginIdSchema, clientBundleHash: z.string() })) + .optional(), }); export const PluginListRequestSchema = z.object({ @@ -1892,11 +1906,17 @@ export const RestartServerRequestMessageSchema = z.object({ type: z.literal("restart_server_request"), reason: z.string().optional(), requestId: z.string(), + // Restart keeps terminals unless this is true. Daemons that predate + // `features.terminalsSurviveRestart` ignore it and close terminals anyway. + killTerminals: z.boolean().optional(), }); export const ShutdownServerRequestMessageSchema = z.object({ type: z.literal("shutdown_server_request"), requestId: z.string(), + // Shutdown closes terminals unless this is true. Gate on + // `features.terminalsSurviveRestart`: older daemons drop the field. + keepTerminals: z.boolean().optional(), }); export const DaemonUpdateRequestMessageSchema = z.object({ @@ -1910,6 +1930,8 @@ export const AgentTimelineCursorSchema = z.object({ }); export const FetchAgentTimelineRequestMessageSchema = z.object({ + // Keep available turns whole for tail/before pages; after catch-up stays incremental. + wholeTurns: z.boolean().optional(), type: z.literal("fetch_agent_timeline_request"), agentId: z.string(), requestId: z.string(), @@ -3656,6 +3678,8 @@ export const ServerInfoStatusPayloadSchema = z providersSnapshot: z.boolean().optional(), connectedHosts: z.boolean().optional(), hostMultiplexing: z.boolean().optional(), + // COMPAT(usageSetting): added in v0.14, remove after 2027-05-01. + usageSetting: z.boolean().optional(), usageSources: z.boolean().optional(), // COMPAT(providersSnapshotCwd): added in v0.3.2, remove gate after 2027-02-10. providersSnapshotCwd: z.boolean().optional(), @@ -3719,12 +3743,16 @@ export const ServerInfoStatusPayloadSchema = z skillManagement: z.boolean().optional(), // COMPAT(idleRuntimeCleanupSetting): added in v0.13.0, remove gate after 2027-04-26. idleRuntimeCleanupSetting: z.boolean().optional(), + // COMPAT(restartRecovery): added in v0.14.0, remove gate after 2027-04-28. + resumeOnStartupSetting: z.boolean().optional(), // COMPAT(terminalRestoreModes): added in v0.1.81, remove gate after 2026-11-23. "terminal-restore-modes": z.boolean().optional(), // COMPAT(terminalInputModeReplay): added in v0.2.6, remove gate after 2027-02-02. "terminal-input-mode-replay": z.boolean().optional(), // COMPAT(terminalSizeOwnership): added in v0.2.6, remove gate after 2027-02-02. "terminal-size-ownership": z.boolean().optional(), + // COMPAT(terminalGraphemeWidths): added in v0.15.0, remove gate after 2027-05-01. + "terminal-grapheme-widths": z.boolean().optional(), // COMPAT(rewind): added in v0.1.X, drop the gate when floor >= v0.1.X. rewind: z.boolean().optional(), // COMPAT(agentTimelinePromptIndex): added in v0.2.X, drop the gate when floor >= v0.2.X. @@ -3757,6 +3785,8 @@ export const ServerInfoStatusPayloadSchema = z daemonDiagnostics: z.boolean().optional(), // COMPAT(daemonSelfUpdate): added in v0.1.93, remove gate after 2026-12-13. daemonSelfUpdate: z.boolean().optional(), + // COMPAT(terminalsSurviveRestart): added in v0.12.0, remove gate after 2027-04-21. + terminalsSurviveRestart: z.boolean().optional(), // COMPAT(agentForkContext): added in v0.1.102, remove gate after 2026-12-28. agentForkContext: z.boolean().optional(), // COMPAT(agentForkContextCursor): added in v0.1.108, remove gate after 2027-01-14. @@ -3765,6 +3795,7 @@ export const ServerInfoStatusPayloadSchema = z providerSubagents: z.boolean().optional(), // COMPAT(projectedSubagentTimeline): added after v0.8.0, remove gates after 2027-03-14; retain wire field. projectedSubagentTimeline: z.boolean().optional(), + wholeTurnTimeline: z.boolean().optional(), // COMPAT(providerSubagentNesting): added in v0.7, remove gate after 2027-03-04. providerSubagentNesting: z.boolean().optional(), // COMPAT(workspacePinning): added in v0.1.107, remove gate after 2027-01-12. @@ -3805,6 +3836,7 @@ export const ServerInfoStatusPayloadSchema = z selectiveAgentTimeline: z.boolean().optional(), explicitEventSubscriptions: z.boolean().optional(), ownedSubscriptions: z.boolean().optional(), + binaryChunkingV1: z.boolean().optional(), workspaceSetupObservation: z.boolean().optional(), workspaceSortTimes: z.boolean().optional(), // COMPAT(canonicalSubmittedPrompts): added in v0.2.6, remove gate after 2027-01-30. @@ -5118,6 +5150,22 @@ export const DaemonGetStatusResponseSchema = z.object({ error: z.string().nullable().optional(), }), ), + // Processes a terminal cleanup on this host (a kill restart or stop) could not confirm + // gone; empty when every cleanup finished. Daemons without terminalsSurviveRestart have + // no such cleanup and omit it. + terminalCleanupUnconfirmed: z + .array( + z.object({ + pid: z.number(), + role: z.string(), + reason: z.string(), + detail: z.string(), + }), + ) + .optional(), + // Set when this host's terminals are held by a terminal worker from a newer Paseo, which + // this daemon leaves running but cannot drive: why, and what the user can do. + terminalsUnavailable: z.string().optional(), }) .passthrough(), }); @@ -6754,7 +6802,10 @@ export const PluginCatalogGetResponseSchema = z.object({ plugins: z.array( z.object({ id: PluginIdSchema, - clientBundle: z.string(), + /** Left out only when the request listed this plugin with the same `clientBundleHash`. */ + clientBundle: z.string().optional(), + /** SHA-256 of `clientBundle`, hex encoded. */ + clientBundleHash: z.string().optional(), requirements: PluginRequirementsSchema.optional(), }), ), diff --git a/packages/protocol/src/messages.wire-compat.test.ts b/packages/protocol/src/messages.wire-compat.test.ts index d6b2bc02ff..abc89b06aa 100644 --- a/packages/protocol/src/messages.wire-compat.test.ts +++ b/packages/protocol/src/messages.wire-compat.test.ts @@ -200,8 +200,8 @@ describe("wire schema compatibility", () => { }); }); - test("sub_agent tool-call payload still parses against the v0.1.65-beta.3 schema", () => { - const parsed = LegacySubAgentToolCallSchema.parse({ + test("a sub-agent launch marker still parses against the v0.1.65-beta.3 schema", () => { + const card = { type: "tool_call", callId: "call-sub-agent-1", name: "Task", @@ -212,12 +212,26 @@ describe("wire schema compatibility", () => { subAgentType: "Explore", description: "Inspect repository structure", childSessionId: "child-session-1", - log: "[Read] README.md", + log: "", actions: [], }, - }); + } as const; - expect(parsed.detail.actions).toEqual([]); + const parsed = LegacySubAgentToolCallSchema.parse(JSON.parse(JSON.stringify(card))); + expect(parsed.detail).toMatchObject({ log: "", actions: [] }); + const { log: _log, ...withoutLog } = card.detail; + expect(LegacySubAgentToolCallSchema.safeParse({ ...card, detail: withoutLog }).success).toBe( + false, + ); + expect(AgentTimelineItemPayloadSchema.parse({ ...card, detail: withoutLog })).toMatchObject({ + detail: { type: "sub_agent", description: "Inspect repository structure" }, + }); + expect( + AgentTimelineItemPayloadSchema.parse({ + ...card, + detail: { ...card.detail, log: "[Read] README.md" }, + }), + ).toMatchObject({ detail: { log: "[Read] README.md" } }); }); test("old clients parse agent snapshots with rewind capabilities", () => { diff --git a/packages/protocol/src/paseo-tool-presentation/catalog.ts b/packages/protocol/src/paseo-tool-presentation/catalog.ts index 0c35b128b7..4844b7ceb7 100644 --- a/packages/protocol/src/paseo-tool-presentation/catalog.ts +++ b/packages/protocol/src/paseo-tool-presentation/catalog.ts @@ -19,6 +19,7 @@ export interface PaseoToolDetailSpec { export interface PaseoToolEntry { label: string; + completedLabel: string; context?: PaseoToolContext; detail?: PaseoToolDetailSpec; } @@ -123,14 +124,24 @@ function baseName(value: unknown): string | undefined { return value.split(/[\\/]/).findLast((segment) => segment.length > 0); } -function browser(label: string, context?: PaseoToolContext): PaseoToolEntry { - return { label, ...(context ? { context } : {}), detail: { inputOrder: BROWSER_FIELDS } }; +function browser( + label: string, + completedLabel: string, + context?: PaseoToolContext, +): PaseoToolEntry { + return { + label, + completedLabel, + ...(context ? { context } : {}), + detail: { inputOrder: BROWSER_FIELDS }, + }; } export const PASEO_TOOL_CATALOG = { // Agents create_agent: { label: "Create agent", + completedLabel: "Created agent", context: field("title", "initialPrompt"), detail: { promptField: "initialPrompt", @@ -140,6 +151,7 @@ export const PASEO_TOOL_CATALOG = { }, send_agent_prompt: { label: "Send message", + completedLabel: "Sent message", context: field("prompt"), detail: { promptField: "prompt", @@ -149,42 +161,55 @@ export const PASEO_TOOL_CATALOG = { }, get_agent_status: { label: "Check agent", + completedLabel: "Checked agent", context: targetAgent(), detail: { inputOrder: ["agentId"] }, }, get_agent_activity: { label: "Read agent activity", + completedLabel: "Read agent activity", context: targetAgent(), detail: { inputOrder: ["agentId", "limit"] }, }, list_agents: { label: "List agents", + completedLabel: "Listed agents", detail: { inputOrder: ["cwd", "statuses", "sinceHours", "limit", "includeArchived"] }, }, update_agent: { label: "Update agent", + completedLabel: "Updated agent", context: fieldOrTargetAgent("name"), detail: { inputOrder: AGENT_FIELDS }, }, set_agent_mode: { label: "Set agent mode", + completedLabel: "Set agent mode", context: field("modeId"), detail: { inputOrder: ["agentId", "modeId"] }, }, cancel_agent: { label: "Cancel agent", + completedLabel: "Canceled agent", context: targetAgent(), detail: { inputOrder: ["agentId"] }, }, archive_agent: { label: "Archive agent", + completedLabel: "Archived agent", context: targetAgent(), detail: { inputOrder: ["agentId"] }, }, - kill_agent: { label: "Kill agent", context: targetAgent(), detail: { inputOrder: ["agentId"] } }, - list_pending_permissions: { label: "List permissions" }, + kill_agent: { + label: "Kill agent", + completedLabel: "Killed agent", + context: targetAgent(), + detail: { inputOrder: ["agentId"] }, + }, + list_pending_permissions: { label: "List permissions", completedLabel: "Listed permissions" }, respond_to_permission: { label: "Respond to permission", + completedLabel: "Responded to permission", context: targetAgent(), detail: { inputOrder: ["agentId", "requestId", "response"] }, }, @@ -192,32 +217,41 @@ export const PASEO_TOOL_CATALOG = { // Workspaces and scripts create_workspace: { label: "Create workspace", + completedLabel: "Created workspace", context: workspaceContext(), detail: { inputOrder: WORKSPACE_FIELDS, outputFields: ["workspaceId", "projectId"] }, }, - list_hosts: { label: "List hosts" }, - list_workspaces: { label: "List workspaces" }, + list_hosts: { label: "List hosts", completedLabel: "Listed hosts" }, + list_workspaces: { label: "List workspaces", completedLabel: "Listed workspaces" }, rename_workspace: { label: "Rename workspace", + completedLabel: "Renamed workspace", context: field("title"), detail: { inputOrder: ["title", "workspaceId"] }, }, archive_workspace: { label: "Archive workspace", + completedLabel: "Archived workspace", context: field("workspaceId"), detail: { inputOrder: ["workspaceId"], outputFields: ["workspaceId", "archivedAgentIds", "removedDirectory"], }, }, - list_workspace_scripts: { label: "List scripts", detail: { inputOrder: ["workspaceId"] } }, + list_workspace_scripts: { + label: "List scripts", + completedLabel: "Listed scripts", + detail: { inputOrder: ["workspaceId"] }, + }, start_workspace_script: { label: "Start script", + completedLabel: "Started script", context: field("scriptName"), detail: { inputOrder: ["workspaceId", "scriptName"] }, }, stop_workspace_script: { label: "Stop script", + completedLabel: "Stopped script", context: field("scriptName"), detail: { inputOrder: ["workspaceId", "scriptName"] }, }, @@ -225,22 +259,30 @@ export const PASEO_TOOL_CATALOG = { // Terminals create_terminal: { label: "Create terminal", + completedLabel: "Created terminal", context: field("name", "command"), detail: { inputOrder: ["cwd", "workspaceId", "name", "command"] }, }, - list_terminals: { label: "List terminals", detail: { inputOrder: ["cwd", "all"] } }, + list_terminals: { + label: "List terminals", + completedLabel: "Listed terminals", + detail: { inputOrder: ["cwd", "all"] }, + }, capture_terminal: { label: "Read terminal", + completedLabel: "Read terminal", context: field("terminalId"), detail: { inputOrder: ["terminalId", "lines"] }, }, send_terminal_keys: { label: "Send keys", + completedLabel: "Sent keys", context: field("keys"), detail: { inputOrder: ["terminalId", "keys", "literal"] }, }, kill_terminal: { label: "Kill terminal", + completedLabel: "Killed terminal", context: field("terminalId"), detail: { inputOrder: ["terminalId"] }, }, @@ -248,6 +290,7 @@ export const PASEO_TOOL_CATALOG = { // Schedules and heartbeats create_schedule: { label: "Create schedule", + completedLabel: "Created schedule", context: field("name", "cron"), detail: { promptField: "prompt", @@ -257,6 +300,7 @@ export const PASEO_TOOL_CATALOG = { }, create_heartbeat: { label: "Create heartbeat", + completedLabel: "Created heartbeat", context: field("name", "cron"), detail: { promptField: "prompt", @@ -266,79 +310,93 @@ export const PASEO_TOOL_CATALOG = { }, update_schedule: { label: "Update schedule", + completedLabel: "Updated schedule", context: field("name", "id"), detail: { promptField: "prompt", inputOrder: AUTOMATION_FIELDS }, }, - list_schedules: { label: "List schedules" }, + list_schedules: { label: "List schedules", completedLabel: "Listed schedules" }, inspect_schedule: { label: "Inspect schedule", + completedLabel: "Inspected schedule", context: field("id"), detail: { inputOrder: ["id"] }, }, schedule_logs: { label: "Read schedule logs", + completedLabel: "Read schedule logs", context: field("id"), detail: { inputOrder: ["id"] }, }, run_schedule_once: { label: "Run schedule", + completedLabel: "Ran schedule", + context: field("id"), + detail: { inputOrder: ["id"] }, + }, + pause_schedule: { + label: "Pause schedule", + completedLabel: "Paused schedule", context: field("id"), detail: { inputOrder: ["id"] }, }, - pause_schedule: { label: "Pause schedule", context: field("id"), detail: { inputOrder: ["id"] } }, resume_schedule: { label: "Resume schedule", + completedLabel: "Resumed schedule", context: field("id"), detail: { inputOrder: ["id"] }, }, delete_schedule: { label: "Delete schedule", + completedLabel: "Deleted schedule", context: field("id"), detail: { inputOrder: ["id"] }, }, delete_heartbeat: { label: "Delete heartbeat", + completedLabel: "Deleted heartbeat", context: field("id"), detail: { inputOrder: ["id"] }, }, // Providers - list_providers: { label: "List providers" }, + list_providers: { label: "List providers", completedLabel: "Listed providers" }, list_models: { label: "List models", + completedLabel: "Listed models", context: field("provider"), detail: { inputOrder: ["provider"] }, }, - list_profiles: { label: "List profiles" }, + list_profiles: { label: "List profiles", completedLabel: "Listed profiles" }, inspect_provider: { label: "Inspect provider", + completedLabel: "Inspected provider", context: field("provider"), detail: { inputOrder: ["provider", "cwd", "settings"] }, }, // Browser - browser_list_tabs: browser("List browser tabs"), - browser_new_tab: browser("Open browser tab", field("url")), - browser_close_tab: browser("Close browser tab", field("browserId")), - browser_navigate: browser("Navigate", field("url")), - browser_back: browser("Go back"), - browser_forward: browser("Go forward"), - browser_reload: browser("Reload page"), - browser_snapshot: browser("Snapshot page"), - browser_screenshot: browser("Take screenshot"), - browser_click: browser("Click element", field("ref")), - browser_hover: browser("Hover element", field("ref")), - browser_drag: browser("Drag element", field("sourceRef")), - browser_fill: browser("Fill field", field("ref")), - browser_select: browser("Select option", field("value", "ref")), - browser_type: browser("Type text", field("text")), - browser_keypress: browser("Press key", field("key")), - browser_upload: browser("Upload files", field("filePaths")), - browser_wait: browser("Wait for page", field("text", "url")), - browser_scroll: browser("Scroll page"), - browser_resize: browser("Resize browser", viewportContext()), - browser_logs: browser("Read browser logs"), - browser_evaluate: browser("Run JavaScript", field("function")), + browser_list_tabs: browser("List browser tabs", "Listed browser tabs"), + browser_new_tab: browser("Open browser tab", "Opened browser tab", field("url")), + browser_close_tab: browser("Close browser tab", "Closed browser tab", field("browserId")), + browser_navigate: browser("Navigate", "Navigated", field("url")), + browser_back: browser("Go back", "Went back"), + browser_forward: browser("Go forward", "Went forward"), + browser_reload: browser("Reload page", "Reloaded page"), + browser_snapshot: browser("Snapshot page", "Snapshotted page"), + browser_screenshot: browser("Take screenshot", "Took screenshot"), + browser_click: browser("Click element", "Clicked element", field("ref")), + browser_hover: browser("Hover element", "Hovered element", field("ref")), + browser_drag: browser("Drag element", "Dragged element", field("sourceRef")), + browser_fill: browser("Fill field", "Filled field", field("ref")), + browser_select: browser("Select option", "Selected option", field("value", "ref")), + browser_type: browser("Type text", "Typed text", field("text")), + browser_keypress: browser("Press key", "Pressed key", field("key")), + browser_upload: browser("Upload files", "Uploaded files", field("filePaths")), + browser_wait: browser("Wait for page", "Waited for page", field("text", "url")), + browser_scroll: browser("Scroll page", "Scrolled page"), + browser_resize: browser("Resize browser", "Resized browser", viewportContext()), + browser_logs: browser("Read browser logs", "Read browser logs"), + browser_evaluate: browser("Run JavaScript", "Ran JavaScript", field("function")), } satisfies Record; export type PaseoToolName = keyof typeof PASEO_TOOL_CATALOG; diff --git a/packages/protocol/src/paseo-tool-presentation/index.ts b/packages/protocol/src/paseo-tool-presentation/index.ts index c04606a231..e5395a9e62 100644 --- a/packages/protocol/src/paseo-tool-presentation/index.ts +++ b/packages/protocol/src/paseo-tool-presentation/index.ts @@ -28,6 +28,8 @@ export const PASEO_TOOL_NAMES = Object.keys(PASEO_TOOL_CATALOG) as readonly Pase /** Returns null for tools outside the Paseo namespace. */ export function buildPaseoToolDisplay(input: PaseoToolDisplayInput): PaseoToolDisplay | null { + // Canonical details own internal lifecycle rows such as worktree setup. + if (input.detail.type !== "unknown") return null; const leafName = paseoLeafName(input.toolName); if (!leafName) return null; const entry = getPaseoToolEntry(leafName); @@ -39,6 +41,13 @@ export function buildPaseoToolDisplay(input: PaseoToolDisplayInput): PaseoToolDi return { displayName: entry.label, ...(summary ? { summary } : {}) }; } +/** A semantic action label for summaries, sharing the tool presentation catalog. */ +export function getPaseoToolActionLabel(toolName: string): string | null { + const leafName = paseoLeafName(toolName); + if (!leafName) return null; + return getPaseoToolEntry(leafName)?.completedLabel ?? humanizeLeafName(leafName); +} + /** The agent a Paseo call acts on, so callers can resolve its title. */ export function getPaseoToolTargetAgentId( toolName: string, @@ -49,7 +58,11 @@ export function getPaseoToolTargetAgentId( } function paseoLeafName(toolName: string): string | null { - return isPaseoToolName(toolName) ? getPaseoToolLeafName(toolName) : null; + if (isPaseoToolName(toolName)) return getPaseoToolLeafName(toolName); + const normalized = toolName.trim().toLowerCase(); + return normalized.startsWith("paseo_") && !normalized.startsWith("paseo__") + ? normalized.slice("paseo_".length) + : null; } function readToolInput(detail: ToolCallDetail): Readonly> { diff --git a/packages/protocol/src/terminal-snapshot.test.ts b/packages/protocol/src/terminal-snapshot.test.ts deleted file mode 100644 index 96d82a9205..0000000000 --- a/packages/protocol/src/terminal-snapshot.test.ts +++ /dev/null @@ -1,79 +0,0 @@ -import { describe, it, expect } from "vitest"; -import { renderTerminalSnapshotToAnsi } from "./terminal-snapshot"; -import type { TerminalState } from "./messages"; - -function cells(text: string): TerminalState["grid"][number] { - return [...text].map((char) => ({ char })); -} - -describe("renderTerminalSnapshotToAnsi", () => { - it("renders soft-wrapped rows as one contiguous logical line when wrap flags are present", () => { - // The server soft-wrapped one logical line "ABCDEFGHIJKLMNOP" at 10 cols into - // two grid rows. gridWrapped[0] = true marks row 0 as continuing into row 1. - const state: TerminalState = { - rows: 2, - cols: 10, - scrollback: [], - scrollbackWrapped: [], - grid: [cells("ABCDEFGHIJ"), cells("KLMNOP")], - gridWrapped: [true, false], - cursor: { row: 1, col: 6 }, - }; - - const ansi = renderTerminalSnapshotToAnsi(state); - - // The rows must arrive unbroken so xterm re-wraps them itself (and can later - // reflow them) — no hard newline injected between "...IJ" and "KL...". - expect(ansi).toContain("ABCDEFGHIJKLMNOP"); - // Auto-wrap must stay enabled; disabling it (ESC[?7l) is what makes xterm mark - // the rows non-wrapped and refuse to reflow them on resize. - expect(ansi).not.toContain("[?7l"); - }); - - it("falls back to verbatim per-row replay when wrap flags are absent (old daemon)", () => { - // No gridWrapped/scrollbackWrapped: the client cannot tell soft-wraps from hard - // newlines, so it must keep today's exact behaviour rather than guess. - const state: TerminalState = { - rows: 2, - cols: 10, - scrollback: [], - grid: [cells("ABCDEFGHIJ"), cells("KLMNOP")], - cursor: { row: 1, col: 6 }, - }; - - const ansi = renderTerminalSnapshotToAnsi(state); - - expect(ansi).toContain("[?7l"); - expect(ansi).toContain("ABCDEFGHIJ\r\nKLMNOP"); - }); -}); - -describe("renderTerminalSnapshotToAnsi wide chars", () => { - it("skips wide-char continuation cells so the glyph keeps its two columns", () => { - // The daemon captures "통" as the glyph followed by an empty continuation - // cell. Emitting anything for that cell pushes the rest of the row right. - const state: TerminalState = { - rows: 1, - cols: 10, - scrollback: [], - grid: [[{ char: "통" }, { char: "" }, { char: "합" }, { char: "" }, { char: "!" }]], - cursor: { row: 0, col: 5 }, - }; - - expect(renderTerminalSnapshotToAnsi(state)).toContain("통합!"); - }); - - it("replays snapshots from an old daemon verbatim, including its continuation spaces", () => { - // Old daemons already collapsed the continuation to " ". The serializer - // cannot tell that apart from a real space, so it must not guess. - const state: TerminalState = { - rows: 1, - cols: 10, - scrollback: [], - grid: [cells("통 합 !")], - cursor: { row: 0, col: 6 }, - }; - - expect(renderTerminalSnapshotToAnsi(state)).toContain("통 합 !"); - }); -}); diff --git a/packages/protocol/src/terminal-snapshot.ts b/packages/protocol/src/terminal-snapshot.ts deleted file mode 100644 index 1860067573..0000000000 --- a/packages/protocol/src/terminal-snapshot.ts +++ /dev/null @@ -1,224 +0,0 @@ -import type { TerminalCell, TerminalState } from "./messages.js"; - -interface TerminalStyle { - fg: number | undefined; - bg: number | undefined; - fgMode: number | undefined; - bgMode: number | undefined; - bold: boolean; - italic: boolean; - underline: boolean; - dim: boolean; - inverse: boolean; - strikethrough: boolean; -} - -const DEFAULT_STYLE: TerminalStyle = { - fg: undefined, - bg: undefined, - fgMode: undefined, - bgMode: undefined, - bold: false, - italic: false, - underline: false, - dim: false, - inverse: false, - strikethrough: false, -}; - -export function renderTerminalSnapshotToAnsi(state: TerminalState): string { - const rows = [...state.scrollback, ...state.grid]; - const wrapFlags = [...(state.scrollbackWrapped ?? []), ...(state.gridWrapped ?? [])]; - // Soft-wrapped lines can only be re-wrapped on resize when we know which rows - // were continuations. With that per-row flag we replay each logical line as one - // unbroken run (autowrap on) so xterm marks the continuations wrapped and reflows - // them. Without it (old daemon) we keep the verbatim per-row replay: autowrap off - // plus a hard newline per row. - const hasWrapInfo = wrapFlags.length === rows.length; - const lines: string[] = hasWrapInfo ? [] : ["\u001b[?7l"]; - - for (let rowIndex = 0; rowIndex < rows.length; rowIndex += 1) { - const row = rows[rowIndex] ?? []; - const continuesToNextRow = hasWrapInfo && wrapFlags[rowIndex] === true; - // A continuation row must fill the full width so the next row first cell - // triggers xterm auto-wrap, which is what marks the row wrapped/reflowable. - lines.push(renderTerminalRow(row, continuesToNextRow ? state.cols : undefined)); - if (rowIndex < rows.length - 1 && !continuesToNextRow) { - lines.push("\r\n"); - } - } - - lines.push("\u001b[0m"); - const cursorPresentationAnsi = renderCursorPresentationToAnsi(state.cursor); - if (cursorPresentationAnsi) { - lines.push(cursorPresentationAnsi); - } - lines.push(`\u001b[${state.cursor.row + 1};${state.cursor.col + 1}H`); - lines.push(state.cursor.hidden ? "\u001b[?25l" : "\u001b[?25h"); - if (!hasWrapInfo) { - lines.push("\u001b[?7h"); - } - return lines.join(""); -} - -function renderCursorPresentationToAnsi(cursor: TerminalState["cursor"]): string | null { - if (!cursor.style) { - return null; - } - - const cursorStyleCode = (() => { - if (cursor.style === "block") { - return cursor.blink === false ? 2 : 1; - } - if (cursor.style === "underline") { - return cursor.blink === false ? 4 : 3; - } - return cursor.blink === false ? 6 : 5; - })(); - - return `\u001b[${cursorStyleCode} q`; -} - -function renderTerminalRow(row: TerminalCell[], padToCols?: number): string { - const output: string[] = []; - const contentLength = getTerminalRowLength(row); - const length = padToCols !== undefined ? Math.max(contentLength, padToCols) : contentLength; - let previousStyle = DEFAULT_STYLE; - - for (let index = 0; index < length; index += 1) { - const cell = row[index] ?? { char: " " }; - // An empty char marks a wide-char continuation cell. The glyph in the - // previous cell already advances the cursor two columns, so emitting - // anything here would shift the rest of the row one column right. - if (cell.char === "") { - continue; - } - const nextStyle = getTerminalStyle(cell); - if (!terminalStylesEqual(previousStyle, nextStyle)) { - output.push(styleToAnsi(nextStyle)); - previousStyle = nextStyle; - } - output.push(cell.char || " "); - } - - if (!terminalStylesEqual(previousStyle, DEFAULT_STYLE)) { - output.push("\u001b[0m"); - } - - return output.join(""); -} - -function getTerminalRowLength(row: TerminalCell[]): number { - for (let index = row.length - 1; index >= 0; index -= 1) { - const cell = row[index]; - if (!cell) { - continue; - } - if (cell.char !== " ") { - return index + 1; - } - if ( - cell.fg !== undefined || - cell.bg !== undefined || - cell.fgMode !== undefined || - cell.bgMode !== undefined || - cell.bold || - cell.italic || - cell.underline || - cell.dim || - cell.inverse || - cell.strikethrough - ) { - return index + 1; - } - } - return 0; -} - -function getTerminalStyle(cell: TerminalCell): TerminalStyle { - return { - fg: cell.fg, - bg: cell.bg, - fgMode: cell.fgMode, - bgMode: cell.bgMode, - bold: Boolean(cell.bold), - italic: Boolean(cell.italic), - underline: Boolean(cell.underline), - dim: Boolean(cell.dim), - inverse: Boolean(cell.inverse), - strikethrough: Boolean(cell.strikethrough), - }; -} - -function terminalStylesEqual(left: TerminalStyle, right: TerminalStyle): boolean { - return ( - left.fg === right.fg && - left.bg === right.bg && - left.fgMode === right.fgMode && - left.bgMode === right.bgMode && - left.bold === right.bold && - left.italic === right.italic && - left.underline === right.underline && - left.dim === right.dim && - left.inverse === right.inverse && - left.strikethrough === right.strikethrough - ); -} - -function styleToAnsi(style: TerminalStyle): string { - const codes = ["0"]; - - if (style.bold) { - codes.push("1"); - } - if (style.dim) { - codes.push("2"); - } - if (style.italic) { - codes.push("3"); - } - if (style.underline) { - codes.push("4"); - } - if (style.inverse) { - codes.push("7"); - } - if (style.strikethrough) { - codes.push("9"); - } - - if (style.fg !== undefined && style.fgMode !== undefined) { - codes.push(...colorToSgr(style.fgMode, style.fg, false)); - } - - if (style.bg !== undefined && style.bgMode !== undefined) { - codes.push(...colorToSgr(style.bgMode, style.bg, true)); - } - - return `\u001b[${codes.join(";")}m`; -} - -function colorToSgr(mode: number, value: number, background: boolean): string[] { - if (mode === 1) { - if (value >= 8) { - return [String((background ? 100 : 90) + (value - 8))]; - } - return [String((background ? 40 : 30) + value)]; - } - - if (mode === 2) { - return [background ? "48" : "38", "5", String(value)]; - } - - if (mode === 3) { - return [ - background ? "48" : "38", - "2", - String((value >> 16) & 0xff), - String((value >> 8) & 0xff), - String(value & 0xff), - ]; - } - - return []; -} diff --git a/packages/protocol/src/timeline-turn.ts b/packages/protocol/src/timeline-turn.ts new file mode 100644 index 0000000000..f509787317 --- /dev/null +++ b/packages/protocol/src/timeline-turn.ts @@ -0,0 +1,24 @@ +/** Canonical run identity wins over trigger-shaped rows steered into that run. */ +export function continuesTimelineTurn( + previousTurnId: string | undefined, + nextTurnId: string | undefined, + nextIsTrigger: boolean, +): boolean { + if (previousTurnId !== undefined && nextTurnId !== undefined) { + return previousTurnId === nextTurnId; + } + // Missing IDs cannot recover historical batching or steering. Each visible + // trigger deterministically starts a turn in both paging and presentation. + return !nextIsTrigger; +} + +export function isTimelineTurnTrigger(item: { + type: string; + name?: string; + agentMessage?: unknown; +}): boolean { + return ( + item.type === "user_message" || + (item.type === "tool_call" && (item.agentMessage !== undefined || item.name === "heartbeat")) + ); +} diff --git a/packages/relay/package.json b/packages/relay/package.json index b2e0c5187f..86bde64a75 100644 --- a/packages/relay/package.json +++ b/packages/relay/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/relay", - "version": "0.13.2", + "version": "0.15.0-beta.1", "description": "Paseo relay for bridging daemon and client connections", "files": [ "dist", diff --git a/packages/server/package.json b/packages/server/package.json index f39d284343..191aee2945 100644 --- a/packages/server/package.json +++ b/packages/server/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/server", - "version": "0.13.2", + "version": "0.15.0-beta.1", "description": "Paseo backend server", "files": [ "dist/server", @@ -73,7 +73,7 @@ "clean": "node ../../scripts/clean-package-dist.mjs", "build": "npm run build:lib && npm run build:scripts", "build:clean": "npm run clean && npm run build", - "build:lib": "tsc -p tsconfig.server.json --incremental false && node scripts/build-opencode-bridge-plugin.mjs && node -e \"const fs=require('node:fs'); fs.mkdirSync('dist/server/server/speech/providers/local/sherpa/assets',{recursive:true}); fs.copyFileSync('src/server/speech/providers/local/sherpa/assets/silero_vad.onnx','dist/server/server/speech/providers/local/sherpa/assets/silero_vad.onnx'); fs.cpSync('src/terminal/shell-integration','dist/server/terminal/shell-integration',{recursive:true}); fs.cpSync('src/terminal/shell-integration','dist/src/terminal/shell-integration',{recursive:true}); fs.copyFileSync('src/terminal/terminal-ts-loader.mjs','dist/server/terminal/terminal-ts-loader.mjs'); fs.rmSync('dist/server/skills',{recursive:true,force:true}); fs.cpSync('../../skills','dist/server/skills',{recursive:true}); fs.rmSync('dist/server/builtin-plugins',{recursive:true,force:true}); fs.cpSync('../../plugins','dist/server/builtin-plugins',{recursive:true,filter:(source)=>!source.split(require('node:path').sep).some((segment)=>segment==='node_modules'||segment==='test')&&!/\\.(test|spec)\\.[cm]?[jt]sx?$/.test(source)&&!source.endsWith('.tsbuildinfo')});\"", + "build:lib": "tsc -p tsconfig.server.json --incremental false && node scripts/build-opencode-bridge-plugin.mjs && node scripts/build-terminal-worker.mjs && node -e \"const fs=require('node:fs'); fs.mkdirSync('dist/server/server/speech/providers/local/sherpa/assets',{recursive:true}); fs.copyFileSync('src/server/speech/providers/local/sherpa/assets/silero_vad.onnx','dist/server/server/speech/providers/local/sherpa/assets/silero_vad.onnx'); fs.cpSync('src/terminal/shell-integration','dist/server/terminal/shell-integration',{recursive:true}); fs.cpSync('src/terminal/shell-integration','dist/src/terminal/shell-integration',{recursive:true}); fs.copyFileSync('src/terminal/terminal-ts-loader.mjs','dist/server/terminal/terminal-ts-loader.mjs'); fs.rmSync('dist/server/skills',{recursive:true,force:true}); fs.cpSync('../../skills','dist/server/skills',{recursive:true}); fs.rmSync('dist/server/builtin-plugins',{recursive:true,force:true}); fs.cpSync('../../plugins','dist/server/builtin-plugins',{recursive:true,filter:(source)=>!source.split(require('node:path').sep).some((segment)=>segment==='node_modules'||segment==='test')&&!/\\.(test|spec)\\.[cm]?[jt]sx?$/.test(source)&&!source.endsWith('.tsbuildinfo')});\"", "build:scripts": "tsc -p tsconfig.scripts.json --incremental false && node -e \"const fs=require('node:fs'); fs.mkdirSync('dist/scripts',{recursive:true}); fs.copyFileSync('scripts/mcp-stdio-socket-bridge-cli.mjs','dist/scripts/mcp-stdio-socket-bridge-cli.mjs');\"", "prepack": "npm run build:clean && npm --prefix ../.. run build:daemon-web-ui", "start": "node dist/scripts/supervisor-entrypoint.js", @@ -89,7 +89,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 --maxWorkers=1 src/server/git-filename-diffs.e2e.test.ts src/server/daemon-e2e/checkout-diff-content.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/terminal-workspace-sdk.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/connected-hosts/hosts.e2e.test.ts && vitest run --maxWorkers=1 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 -t \"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 --maxWorkers=1 src/server/git-filename-diffs.e2e.test.ts src/server/daemon-e2e/checkout-diff-content.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/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/connected-hosts/hosts.e2e.test.ts src/server/owned-subscriptions.e2e.test.ts && vitest run --maxWorkers=1 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 -t \"merges into|creates a worktree and auto-archives both|versioned runtime|oversized attachments|connected hosts|password-protected daemon refuses|replays selected OMP history\"", "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", @@ -107,16 +107,18 @@ "@agentclientprotocol/sdk": "^0.17.1", "@anthropic-ai/claude-agent-sdk": "0.3.246", "@anthropic-ai/sdk": "^0.104.2", - "@getpaseo/client": "0.13.2", - "@getpaseo/highlight": "0.13.2", - "@getpaseo/plugin": "0.13.2", - "@getpaseo/protocol": "0.13.2", - "@getpaseo/relay": "0.13.2", + "@getpaseo/client": "0.15.0-beta.1", + "@getpaseo/highlight": "0.15.0-beta.1", + "@getpaseo/plugin": "0.15.0-beta.1", + "@getpaseo/protocol": "0.15.0-beta.1", + "@getpaseo/relay": "0.15.0-beta.1", "@isaacs/ttlcache": "^2.1.4", "@modelcontextprotocol/sdk": "1.29.0", "@opencode-ai/sdk": "1.14.46", "@opencode/client": "2.0.10", - "@xterm/headless": "^6.0.0", + "@xterm/addon-serialize": "0.14.0", + "@xterm/addon-unicode-graphemes": "0.5.0-beta.330", + "@xterm/headless": "6.1.0-beta.334", "ai": "5.0.78", "ajv": "^8.20.0", "bcryptjs": "^3.0.3", @@ -124,6 +126,7 @@ "esbuild": "^0.25.12", "express": "^4.18.2", "fast-deep-equal": "^3.1.3", + "https-proxy-agent": "^7.0.6", "lru-cache": "^11.5.1", "markdown-it": "^10.0.0", "mnemonic-id": "^3.2.7", @@ -141,6 +144,7 @@ "strip-ansi": "^7.1.2", "tree-kill": "^1.2.2", "typescript": "^5.9.3", + "undici": "^7.24.8", "uuid": "^9.0.1", "which": "^5.0.0", "ws": "^8.14.2", diff --git a/packages/server/scripts/build-opencode-bridge-plugin.mjs b/packages/server/scripts/build-opencode-bridge-plugin.mjs index 69f1e774f0..33cd3402ce 100644 --- a/packages/server/scripts/build-opencode-bridge-plugin.mjs +++ b/packages/server/scripts/build-opencode-bridge-plugin.mjs @@ -1,4 +1,4 @@ -import { mkdir } from "node:fs/promises"; +import { copyFile, mkdir } from "node:fs/promises"; import path from "node:path"; import { fileURLToPath } from "node:url"; @@ -27,4 +27,10 @@ for (const directory of ["", "v2/"]) { target: "es2022", outfile: outputPath, }); + if (directory === "v2/") { + await copyFile( + new URL("../src/server/agent/providers/opencode/v2/state.mjs", import.meta.url), + path.join(path.dirname(outputPath), "state.mjs"), + ); + } } diff --git a/packages/server/scripts/build-terminal-worker.mjs b/packages/server/scripts/build-terminal-worker.mjs new file mode 100644 index 0000000000..3a5b290fc3 --- /dev/null +++ b/packages/server/scripts/build-terminal-worker.mjs @@ -0,0 +1,55 @@ +// Bundles the terminal worker into one file with its shell integration beside it. The daemon +// copies this directory (plus node-pty) into $PASEO_HOME/terminal-worker/ and launches the worker +// from the copy, so a worker that outlives an upgrade never loads files from the installation +// that replaced the one it came from. See docs/terminal-worker.md. +// +// Usage: node scripts/build-terminal-worker.mjs [--outdir ] +// Default output: dist/server/terminal-worker/ + +import { cp, mkdir, rm } from "node:fs/promises"; +import path from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; + +import { build } from "esbuild"; + +const packageRoot = fileURLToPath(new URL("..", import.meta.url)); + +export const TERMINAL_WORKER_BUNDLE_NAME = "terminal-worker.mjs"; + +export async function buildTerminalWorkerBundle({ outDir }) { + await rm(outDir, { recursive: true, force: true }); + await mkdir(outDir, { recursive: true }); + await build({ + entryPoints: [path.join(packageRoot, "src/terminal/terminal-worker-process.ts")], + bundle: true, + format: "esm", + platform: "node", + target: "node20", + // Loaded from the copy's own node_modules/ at run time. + external: ["node-pty"], + // Bundled CommonJS dependencies call require() for Node built-ins. + banner: { + js: 'import { createRequire as __terminalWorkerCreateRequire } from "node:module"; const require = __terminalWorkerCreateRequire(import.meta.url);', + }, + outfile: path.join(outDir, TERMINAL_WORKER_BUNDLE_NAME), + logLevel: "warning", + }); + // terminal.ts resolves the zsh integration relative to its own module, which is the bundle. + await cp( + path.join(packageRoot, "src/terminal/shell-integration"), + path.join(outDir, "shell-integration"), + { recursive: true }, + ); +} + +function readOutDir(argv) { + const index = argv.indexOf("--outdir"); + if (index === -1) return path.join(packageRoot, "dist/server/terminal-worker"); + const value = argv[index + 1]; + if (!value) throw new Error("--outdir requires a directory"); + return path.resolve(value); +} + +if (import.meta.url === pathToFileURL(process.argv[1] ?? "").href) { + await buildTerminalWorkerBundle({ outDir: readOutDir(process.argv.slice(2)) }); +} diff --git a/packages/server/scripts/reproduce-codex-history-string-limit.mts b/packages/server/scripts/reproduce-codex-history-string-limit.mts new file mode 100644 index 0000000000..b0f49e4faf --- /dev/null +++ b/packages/server/scripts/reproduce-codex-history-string-limit.mts @@ -0,0 +1,108 @@ +// Opt-in diagnostic for #3905. Run from the repository root: +// node --import tsx packages/server/scripts/reproduce-codex-history-string-limit.mts 520 [legacy|paginated] +// Requires Codex 0.148+ on PATH and approximately 2 GiB of available memory. +// `paginated` migrates the synthetic rollout with `codex migrate-rollouts` first. +import { execFileSync, spawn } from "node:child_process"; +import { randomUUID } from "node:crypto"; +import { mkdtemp, mkdir, open, rm } from "node:fs/promises"; +import path from "node:path"; +import pino from "pino"; +import { CodexAppServerAgentSession } from "../src/server/agent/providers/codex-app-server-agent.js"; + +const megabytes = Number(process.argv[2] ?? "520"); +if (!Number.isSafeInteger(megabytes) || megabytes < 1 || megabytes > 600) { + throw new Error("Expected an integer size between 1 and 600 MiB"); +} +const historyMode = process.argv[3] ?? "legacy"; +if (historyMode !== "legacy" && historyMode !== "paginated") { + throw new Error("Expected history mode legacy or paginated"); +} +const root = await mkdtemp(path.join(process.cwd(), ".codex-history-repro-")); +const home = path.join(root, "codex-home"); +const now = new Date(); +const timestamp = now.toISOString(); +const threadId = randomUUID(); +const turnId = randomUUID(); +const sessions = path.join(home, "sessions", ...timestamp.slice(0, 10).split("-")); +await mkdir(sessions, { recursive: true }); +const rollout = await open( + path.join(sessions, `rollout-${timestamp.slice(0, 19).replaceAll(":", "-")}-${threadId}.jsonl`), + "w", +); +async function write(type: string, payload: unknown) { + await rollout.write(`${JSON.stringify({ timestamp, type, payload })}\n`); +} +await write("session_meta", { + id: threadId, + timestamp, + cwd: root, + originator: "codex_cli_rs", + cli_version: "0.159.0", + source: "cli", + model_provider: "openai", + history_mode: "legacy", +}); +await write("event_msg", { type: "task_started", turn_id: turnId, model_context_window: 200000 }); +await write("event_msg", { + type: "user_message", + message: "Synthetic oversized history", + images: [], + local_images: [], + text_elements: [], +}); +for (let index = 0; index < megabytes; index++) { + await write("event_msg", { + type: "agent_message", + message: "x".repeat(1024 * 1024), + phase: "commentary", + }); +} +await write("event_msg", { type: "task_complete", turn_id: turnId, last_agent_message: "done" }); +await rollout.close(); +if (historyMode === "paginated") { + execFileSync("codex", ["migrate-rollouts", "--apply", "--thread", threadId], { + env: { ...process.env, CODEX_HOME: home }, + stdio: "ignore", + }); +} +console.log( + `Opening synthetic ${megabytes} MiB ${historyMode} history through the real Codex app-server`, +); +const session = new CodexAppServerAgentSession( + { provider: "codex", cwd: root }, + { sessionId: threadId }, + pino({ level: "silent" }), + async () => + spawn( + "codex", + ["app-server", "--disable", "plugins", "--disable", "apps", "--disable", "remote_plugin"], + { + stdio: ["pipe", "pipe", "pipe"], + env: { ...process.env, CODEX_HOME: home }, + }, + ), + { codexHome: home }, + false, + false, + false, + undefined, + "history", +); +try { + await session.connect(); + let count = 0; + for await (const event of session.streamHistory()) { + if (event.type !== "timeline") continue; + count++; + if (event.item.type === "notification") console.log(event.item.message); + } + console.log(`History loaded: ${count} timeline rows`); +} catch (error) { + // A recoverable session error is acceptable for the crash-isolation assertion. + console.log( + `History rejected without crashing: ${error instanceof Error ? error.message : String(error)}`, + ); +} finally { + await session.close(); + await rm(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }); +} diff --git a/packages/server/scripts/supervisor-entrypoint.ts b/packages/server/scripts/supervisor-entrypoint.ts index ee3746accf..7d0e7f50aa 100644 --- a/packages/server/scripts/supervisor-entrypoint.ts +++ b/packages/server/scripts/supervisor-entrypoint.ts @@ -12,6 +12,7 @@ import { resolvePaseoHome } from "../src/server/paseo-home.js"; import { daemonLogPath } from "../src/server/daemon-instance.js"; import { PRIVATE_FILE_MODE } from "../src/server/private-files.js"; import { loadPersistedConfig } from "../src/server/persisted-config.js"; +import { reapTerminalWorkers } from "../src/terminal/terminal-worker-reaper.js"; import { runSupervisor } from "./supervisor.js"; import { resolveSupervisorLogFile } from "./supervisor-log-config.js"; @@ -175,6 +176,10 @@ async function main(): Promise { onWorkerExit: () => updatePidLock(paseoHome, { listen: null, serverId: null }, { ownerPid: process.pid }), onSupervisorExit: releaseLock, + cleanupTerminals: async (log) => { + const result = await reapTerminalWorkers({ paseoHome, log }); + log("Terminal worker cleanup result", { ...result }); + }, }); requestSupervisorShutdown = supervisor.requestShutdown; } diff --git a/packages/server/scripts/supervisor.terminal-cleanup.test.ts b/packages/server/scripts/supervisor.terminal-cleanup.test.ts new file mode 100644 index 0000000000..224a0788d3 --- /dev/null +++ b/packages/server/scripts/supervisor.terminal-cleanup.test.ts @@ -0,0 +1,180 @@ +import { spawn } from "node:child_process"; +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { describe, expect, test } from "vitest"; + +// A real supervisor with scripted workers. Each worker generation logs what it sees to an +// events file; `cleanupTerminals` logs "cleanup". The order of events is the contract: a kill +// intent cleans up before the next worker starts, a keep intent or a crash never cleans up. + +async function runSupervisorWith(workerScript: string, timeoutMs = 8_000) { + const home = await mkdtemp(path.join(tmpdir(), "paseo-terminal-cleanup-")); + const workerPath = path.join(home, "worker.mjs"); + const runnerPath = path.join(home, "runner.mjs"); + const eventsPath = path.join(home, "events.jsonl"); + const supervisor = new URL("./supervisor.ts", import.meta.url).href; + await writeFile( + workerPath, + ` + import { appendFileSync, existsSync, readFileSync, writeFileSync } from "node:fs"; + const counter = ${JSON.stringify(path.join(home, "generation"))}; + const generation = existsSync(counter) ? Number(readFileSync(counter, "utf8")) + 1 : 1; + writeFileSync(counter, String(generation)); + const record = (event) => + appendFileSync(${JSON.stringify(eventsPath)}, JSON.stringify(event) + "\\n"); + record({ started: generation }); + ${workerScript} + `, + ); + await writeFile( + runnerPath, + ` + import { appendFileSync } from "node:fs"; + import { runSupervisor } from ${JSON.stringify(supervisor)}; + runSupervisor({ + name: "TerminalCleanupTest", startupMessage: "starting", restartOnCrash: true, + resolveWorkerEntry: () => ${JSON.stringify(workerPath)}, workerArgs: [], workerExecArgv: [], + cleanupTerminals: async () => { + appendFileSync(${JSON.stringify(eventsPath)}, JSON.stringify("cleanup") + "\\n"); + }, + }); + `, + ); + const env = Object.fromEntries( + Object.entries(process.env).filter(([key]) => !key.startsWith("PASEO_")), + ); + const child = spawn(process.execPath, ["--import", "tsx", runnerPath], { + cwd: fileURLToPath(new URL("../../../", import.meta.url)), + env: { ...env, HOME: home, PASEO_HOME: home }, + stdio: ["ignore", "pipe", "pipe"], + }); + let output = ""; + child.stdout.on("data", (chunk) => (output += chunk)); + child.stderr.on("data", (chunk) => (output += chunk)); + try { + const code = await new Promise((resolve, reject) => { + const timer = setTimeout(() => { + child.kill("SIGKILL"); + reject(new Error(output)); + }, timeoutMs); + child.once("error", reject); + child.once("close", (exitCode) => { + clearTimeout(timer); + resolve(exitCode); + }); + }); + const events = (await readFile(eventsPath, "utf8").catch(() => "")) + .trim() + .split("\n") + .filter(Boolean) + .map((line) => JSON.parse(line) as unknown); + return { code, output, events }; + } finally { + await rm(home, { recursive: true, force: true }); + } +} + +// Generation 1 asks for `firstIntent`; generation 2 (if any) stops with `secondIntent`. +function scriptedWorker(firstIntent: string, secondIntent = "") { + return ` + process.on("message", (message) => { + if (message.type !== "paseo:graceful-shutdown") return; + record({ graceful: generation, keepTerminals: message.keepTerminals }); + process.exit(0); + }); + process.send({ type: "paseo:ready", listen: "endpoint-" + generation, serverId: "srv" }); + if (generation === 1) { ${firstIntent} } + else { ${secondIntent} } + `; +} + +const stopKeeping = `process.send({ type: "paseo:shutdown", reason: "test", keepTerminals: true });`; + +describe("supervisor terminal cleanup", () => { + test("a keep restart passes keepTerminals and never cleans up", async () => { + const result = await runSupervisorWith( + scriptedWorker( + `process.send({ type: "paseo:restart", reason: "test", keepTerminals: true });`, + stopKeeping, + ), + ); + expect(result.code, result.output).toBe(0); + expect(result.events).toEqual([ + { started: 1 }, + { graceful: 1, keepTerminals: true }, + { started: 2 }, + { graceful: 2, keepTerminals: true }, + ]); + }); + + test("a kill restart cleans up after the worker exits and before the respawn", async () => { + const result = await runSupervisorWith( + scriptedWorker( + `process.send({ type: "paseo:restart", reason: "test", keepTerminals: false });`, + stopKeeping, + ), + ); + expect(result.code, result.output).toBe(0); + expect(result.events).toEqual([ + { started: 1 }, + { graceful: 1, keepTerminals: false }, + "cleanup", + { started: 2 }, + { graceful: 2, keepTerminals: true }, + ]); + }); + + test("a kill restart whose worker hangs cleans up after the forced kill, before the respawn", async () => { + const result = await runSupervisorWith( + ` + process.on("message", (message) => { + if (message.type !== "paseo:graceful-shutdown") return; + record({ graceful: generation, keepTerminals: message.keepTerminals }); + if (generation === 2) process.exit(0); + }); + process.send({ type: "paseo:ready", listen: "endpoint-" + generation, serverId: "srv" }); + if (generation === 1) { + process.send({ type: "paseo:restart", reason: "test", keepTerminals: false }); + setInterval(() => {}, 1000); + } else { + ${stopKeeping} + } + `, + 20_000, + ); + expect(result.code, result.output).toBe(0); + expect(result.events).toEqual([ + { started: 1 }, + { graceful: 1, keepTerminals: false }, + "cleanup", + { started: 2 }, + { graceful: 2, keepTerminals: true }, + ]); + }, 30_000); + + test("a crash restart keeps terminals", async () => { + const result = await runSupervisorWith(scriptedWorker(`process.exit(1);`, stopKeeping)); + expect(result.code, result.output).toBe(0); + expect(result.events).toEqual([ + { started: 1 }, + { started: 2 }, + { graceful: 2, keepTerminals: true }, + ]); + }); + + test("a kill stop cleans up when the supervisor exits", async () => { + const result = await runSupervisorWith( + scriptedWorker( + `process.send({ type: "paseo:shutdown", reason: "test", keepTerminals: false });`, + ), + ); + expect(result.code, result.output).toBe(0); + expect(result.events).toEqual([ + { started: 1 }, + { graceful: 1, keepTerminals: false }, + "cleanup", + ]); + }); +}); diff --git a/packages/server/scripts/supervisor.ts b/packages/server/scripts/supervisor.ts index ec56822619..fac28946d5 100644 --- a/packages/server/scripts/supervisor.ts +++ b/packages/server/scripts/supervisor.ts @@ -21,6 +21,7 @@ type WorkerLifecycleMessage = | { type: "paseo:shutdown"; reason?: string; + keepTerminals: boolean; } | { type: "paseo:ready"; @@ -30,6 +31,7 @@ type WorkerLifecycleMessage = | { type: "paseo:restart"; reason?: string; + keepTerminals: boolean; }; interface SupervisorHeartbeatMessage { @@ -39,8 +41,11 @@ interface SupervisorHeartbeatMessage { interface SupervisorGracefulShutdownMessage { type: "paseo:graceful-shutdown"; reason: string; + keepTerminals: boolean; } +export type SupervisorLifecycleLog = (message: string, fields?: Record) => void; + interface SupervisorOptions { name: string; startupMessage: string; @@ -57,11 +62,15 @@ interface SupervisorOptions { onWorkerExit?: () => Promise | void; restartOnCrash?: boolean; onSupervisorExit?: () => Promise | void; + // Closes every terminal the worker left. Runs after a kill-intent restart or stop once the + // worker has exited (also after a forced kill), before a respawn, and on any supervisor + // exit except a keep-terminals stop. A crash restart keeps terminals and skips it. + cleanupTerminals?: (log: SupervisorLifecycleLog) => Promise; logFile?: SupervisorLogFileOptions; } export interface SupervisorController { - requestShutdown(reason: string): void; + requestShutdown(reason: string, options?: { keepTerminals?: boolean }): void; } function describeExit(code: number | null, signal: NodeJS.Signals | null): string { @@ -74,10 +83,11 @@ function parseLifecycleMessage(msg: unknown): WorkerLifecycleMessage | null { } const type = (msg as { type?: unknown }).type; if (type === "paseo:shutdown") { - const reason = (msg as { reason?: unknown }).reason; + const { reason, keepTerminals } = msg as { reason?: unknown; keepTerminals?: unknown }; return { type: "paseo:shutdown", ...(typeof reason === "string" && reason.trim().length > 0 ? { reason } : {}), + keepTerminals: keepTerminals === true, }; } if (type === "paseo:ready") { @@ -91,10 +101,11 @@ function parseLifecycleMessage(msg: unknown): WorkerLifecycleMessage | null { return { type: "paseo:ready", listen, serverId }; } if (type === "paseo:restart") { - const reason = (msg as { reason?: unknown }).reason; + const { reason, keepTerminals } = msg as { reason?: unknown; keepTerminals?: unknown }; return { type: "paseo:restart", ...(typeof reason === "string" && reason.trim().length > 0 ? { reason } : {}), + keepTerminals: keepTerminals === true, }; } return null; @@ -185,6 +196,9 @@ export function runSupervisor(options: SupervisorOptions): SupervisorController let child: ChildProcess | null = null; let restarting = false; let shuttingDown = false; + // The resolved terminal decision of the pending restart or stop. It survives the force-kill + // path, so a hung kill restart still closes terminals before the respawn. + let pendingKeepTerminals = false; let exiting = false; let lifecycleFailed = false; let publication = Promise.resolve(); @@ -217,12 +231,31 @@ export function runSupervisor(options: SupervisorOptions): SupervisorController const closeLogStream = (): Promise => durableLog.close(); - const exitSupervisor = (code: number): void => { + const runTerminalCleanup = async (when: string): Promise => { + if (!options.cleanupTerminals) { + return; + } + writeLifecycleLog("Closing terminals", { when }); + try { + await options.cleanupTerminals(writeLifecycleLog); + writeLifecycleLog("Terminal cleanup finished", { when }); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + log(`Terminal cleanup not confirmed (${when}): ${message}`); + } + }; + + const exitSupervisor = (code: number, exitOptions: { keepTerminals?: boolean } = {}): void => { if (exiting) { return; } exiting = true; - Promise.resolve(options.onSupervisorExit?.()) + const cleanup = + exitOptions.keepTerminals === true + ? Promise.resolve() + : runTerminalCleanup("supervisor_exit"); + cleanup + .then(() => options.onSupervisorExit?.()) .catch((error) => { const message = error instanceof Error ? error.message : String(error); log(`Supervisor exit cleanup failed: ${message}`); @@ -357,14 +390,20 @@ export function runSupervisor(options: SupervisorOptions): SupervisorController if (lifecycleMessage.type === "paseo:shutdown") { const reason = lifecycleMessage.reason ?? "worker_requested_shutdown"; - writeLifecycleLog("Worker requested shutdown", { reason }); - requestShutdown(reason); + writeLifecycleLog("Worker requested shutdown", { + reason, + keepTerminals: lifecycleMessage.keepTerminals, + }); + requestShutdown(reason, { keepTerminals: lifecycleMessage.keepTerminals }); return; } const reason = lifecycleMessage.reason ?? "worker_requested_restart"; - writeLifecycleLog("Worker requested restart", { reason }); - requestRestart(reason); + writeLifecycleLog("Worker requested restart", { + reason, + keepTerminals: lifecycleMessage.keepTerminals, + }); + requestRestart(reason, lifecycleMessage.keepTerminals); }); child.on("error", (error) => { @@ -395,7 +434,7 @@ export function runSupervisor(options: SupervisorOptions): SupervisorController if (shuttingDown) { log(`Worker exited (${exitDescriptor}). Supervisor shutting down.`); - exitSupervisor(0); + exitSupervisor(0, { keepTerminals: pendingKeepTerminals }); return; } @@ -404,13 +443,25 @@ export function runSupervisor(options: SupervisorOptions): SupervisorController ((code !== 0 && code !== null) || (signal !== null && signal !== "SIGTERM")); if (restarting || crashed) { + const closeTerminals = restarting && !pendingKeepTerminals; restarting = false; + pendingKeepTerminals = false; log( - crashed + crashed && !closeTerminals ? `Worker crashed (${exitDescriptor}). Restarting worker...` : `Worker exited (${exitDescriptor}). Restarting worker...`, ); - spawnWorker(); + if (!closeTerminals) { + spawnWorker(); + return; + } + // The replacement daemon must never adopt terminals the user asked to close. + void runTerminalCleanup("before_respawn").then(() => { + if (!shuttingDown) { + spawnWorker(); + } + return; + }); return; } @@ -429,9 +480,11 @@ export function runSupervisor(options: SupervisorOptions): SupervisorController const message: SupervisorGracefulShutdownMessage = { type: "paseo:graceful-shutdown", reason, + keepTerminals: pendingKeepTerminals, }; writeLifecycleLog("Supervisor requesting graceful worker shutdown", { reason, + keepTerminals: pendingKeepTerminals, supervisorPid: process.pid, workerPid: currentChild.pid ?? null, }); @@ -455,28 +508,33 @@ export function runSupervisor(options: SupervisorOptions): SupervisorController }); }; - const requestRestart = (reason: string) => { + const requestRestart = (reason: string, keepTerminals: boolean) => { if (!child || restarting || shuttingDown) { return; } restarting = true; - writeLifecycleLog("Restart requested", { reason }); + pendingKeepTerminals = keepTerminals; + writeLifecycleLog("Restart requested", { reason, keepTerminals }); log(`${reason}. Stopping worker for restart...`); requestWorkerShutdown(reason); scheduleForceKill(reason); }; - const requestShutdown = (reason: string) => { + const requestShutdown = (reason: string, shutdownOptions: { keepTerminals?: boolean } = {}) => { if (shuttingDown) { return; } shuttingDown = true; restarting = false; - writeLifecycleLog("Supervisor shutdown requested", { reason }); + pendingKeepTerminals = shutdownOptions.keepTerminals === true; + writeLifecycleLog("Supervisor shutdown requested", { + reason, + keepTerminals: pendingKeepTerminals, + }); log(`${reason}. Stopping worker...`); if (!child) { void publication.then(() => { - exitSupervisor(lifecycleFailed ? 1 : 0); + exitSupervisor(lifecycleFailed ? 1 : 0, { keepTerminals: pendingKeepTerminals }); return; }); return; diff --git a/packages/server/src/executable-resolution/executable-resolution.ts b/packages/server/src/executable-resolution/executable-resolution.ts index 97bb8af3a3..064dcec64e 100644 --- a/packages/server/src/executable-resolution/executable-resolution.ts +++ b/packages/server/src/executable-resolution/executable-resolution.ts @@ -1,17 +1,10 @@ -import { createRequire } from "node:module"; import { existsSync } from "node:fs"; import { delimiter, resolve } from "node:path"; import type { ProcessEnvRecord } from "../server/paseo-env.js"; import { execCommand } from "../utils/spawn.js"; +import which from "which"; import { windowsExecutableResolution } from "./windows.js"; -type Which = ( - command: string, - options: { all: true; path?: string; pathExt?: string }, -) => Promise; - -const require = createRequire(import.meta.url); -const which = require("which") as Which; const PROBE_TIMEOUT_MS = 2000; function hasPathSeparator(value: string): boolean { diff --git a/packages/server/src/executable-resolution/which.d.ts b/packages/server/src/executable-resolution/which.d.ts new file mode 100644 index 0000000000..e7fd869f25 --- /dev/null +++ b/packages/server/src/executable-resolution/which.d.ts @@ -0,0 +1,10 @@ +// `which` ships no types. Imported statically (not through createRequire) so the terminal +// worker bundle includes it: the worker runs from a copy that has only node-pty beside it. +// Listed in the tsconfig includes, since nothing imports a declaration file. +declare module "which" { + function which( + command: string, + options: { all: true; path?: string; pathExt?: string }, + ): Promise; + export default which; +} diff --git a/packages/server/src/server/agent/activity-curator.test.ts b/packages/server/src/server/agent/activity-curator.test.ts index c98bbae54d..4e9ce49528 100644 --- a/packages/server/src/server/agent/activity-curator.test.ts +++ b/packages/server/src/server/agent/activity-curator.test.ts @@ -247,7 +247,7 @@ second line'`, ]); }); - it("keeps nested sub-agent logs beside the sub-agent that produced them", () => { + it("lists each sub-agent as its launch marker", () => { const timeline: AgentTimelineItem[] = [ { type: "assistant_message", text: "Before first child." }, toolCallItem({ @@ -257,7 +257,7 @@ second line'`, type: "sub_agent", subAgentType: "Child one", description: "First investigation", - log: "[Assistant] First child result.", + log: "", }, }), { type: "assistant_message", text: "Between children." }, @@ -268,7 +268,7 @@ second line'`, type: "sub_agent", subAgentType: "Child two", description: "Second investigation", - log: "[Assistant] Second child result.", + log: "", }, }), { type: "assistant_message", text: "After second child." }, @@ -279,10 +279,8 @@ second line'`, expect(result.split("\n")).toEqual([ "[Assistant] Before first child.", "[Child one] First investigation", - "[Assistant] First child result.", "[Assistant] Between children.", "[Child two] Second investigation", - "[Assistant] Second child result.", "[Assistant] After second child.", ]); }); diff --git a/packages/server/src/server/agent/activity-curator.ts b/packages/server/src/server/agent/activity-curator.ts index 488867c657..2a7cbff5e6 100644 --- a/packages/server/src/server/agent/activity-curator.ts +++ b/packages/server/src/server/agent/activity-curator.ts @@ -164,9 +164,6 @@ function curateProjectedActivityEntries( break; } entries.push(formatToolCallEntry(item, options)); - if (item.detail.type === "sub_agent" && item.detail.log.trim()) { - entries.push(activityEntry(item.detail.log.trim())); - } break; } case "todo": diff --git a/packages/server/src/server/agent/agent-loading.ts b/packages/server/src/server/agent/agent-loading.ts index 761f1008bd..ba444a394d 100644 --- a/packages/server/src/server/agent/agent-loading.ts +++ b/packages/server/src/server/agent/agent-loading.ts @@ -135,6 +135,7 @@ export async function ensureAgentLoaded( labels: record.labels, workspaceId: record.workspaceId, owner: record.owner, + env: record.launchEnv, }); deps.logger.info({ agentId, provider: record.provider }, "Agent created from stored config"); } diff --git a/packages/server/src/server/agent/agent-manager-stream-coalescing.test.ts b/packages/server/src/server/agent/agent-manager-stream-coalescing.test.ts index 9dc194fa11..c423264869 100644 --- a/packages/server/src/server/agent/agent-manager-stream-coalescing.test.ts +++ b/packages/server/src/server/agent/agent-manager-stream-coalescing.test.ts @@ -6,6 +6,7 @@ import { afterEach, describe, expect, test, vi } from "vitest"; import { createTestLogger } from "../../test-utils/test-logger.js"; import { AgentManager, type AgentManagerEvent } from "./agent-manager.js"; import { AGENT_STREAM_COALESCE_DEFAULT_WINDOW_MS } from "./agent-stream-coalescer.js"; +import { limitAgentTimelineItemContent } from "./agent-timeline-content.js"; import type { AgentTimelineRow } from "./agent-timeline-store-types.js"; import { projectTimelineRows } from "./timeline-projection.js"; import type { @@ -31,7 +32,6 @@ import type { const COALESCE_WINDOW_MS = AGENT_STREAM_COALESCE_DEFAULT_WINDOW_MS; const BEFORE_COALESCE_WINDOW_MS = Math.max(COALESCE_WINDOW_MS - 1, 0); -const TOOL_CALL_CONTENT_MAX_LENGTH = 64 * 1024; const TEST_CAPABILITIES: AgentCapabilityFlags = { supportsStreaming: false, @@ -400,10 +400,7 @@ describe("target coalesced behavior", () => { try { const { agentId, session } = await createManagedSession(harness); const output = `${"a".repeat(512 * 1024)}${"z".repeat(512 * 1024)}`; - const expectedItem = toolCall({ - status: "completed", - output: "a".repeat(TOOL_CALL_CONTENT_MAX_LENGTH), - }); + const expectedItem = limitAgentTimelineItemContent(toolCall({ status: "completed", output })); session.pushEvent(timelineEvent(toolCall({ status: "completed", output }))); await waitForSessionEventQueue(); @@ -425,10 +422,7 @@ describe("target coalesced behavior", () => { try { const { agentId } = await createManagedSession(harness); const output = `${"a".repeat(512 * 1024)}${"z".repeat(512 * 1024)}`; - const expectedItem = toolCall({ - status: "completed", - output: "a".repeat(TOOL_CALL_CONTENT_MAX_LENGTH), - }); + const expectedItem = limitAgentTimelineItemContent(toolCall({ status: "completed", output })); await harness.manager.appendTimelineItem(agentId, toolCall({ status: "completed", output })); @@ -449,10 +443,7 @@ describe("target coalesced behavior", () => { try { const { agentId, session } = await createManagedSession(harness); const output = `${"a".repeat(512 * 1024)}${"z".repeat(512 * 1024)}`; - const expectedItem = toolCall({ - status: "completed", - output: "a".repeat(TOOL_CALL_CONTENT_MAX_LENGTH), - }); + const expectedItem = limitAgentTimelineItemContent(toolCall({ status: "completed", output })); session.setHistory([timelineEvent(toolCall({ status: "completed", output }))]); await harness.manager.hydrateTimelineFromProvider(agentId, { force: true }); @@ -470,10 +461,7 @@ describe("target coalesced behavior", () => { try { const { agentId } = await createManagedSession(harness); const output = `${"a".repeat(512 * 1024)}${"z".repeat(512 * 1024)}`; - const expectedItem = toolCall({ - status: "completed", - output: "a".repeat(TOOL_CALL_CONTENT_MAX_LENGTH), - }); + const expectedItem = limitAgentTimelineItemContent(toolCall({ status: "completed", output })); await harness.manager.emitLiveTimelineItem( agentId, @@ -495,10 +483,9 @@ describe("target coalesced behavior", () => { try { const { agentId, session } = await createManagedSession(harness); const content = `${"a".repeat(512 * 1024)}${"z".repeat(512 * 1024)}`; - const expectedItem = toolCall({ - status: "failed", - error: { content: "a".repeat(TOOL_CALL_CONTENT_MAX_LENGTH) }, - }); + const expectedItem = limitAgentTimelineItemContent( + toolCall({ status: "failed", error: { content } }), + ); session.pushEvent(timelineEvent(toolCall({ status: "failed", error: { content } }))); await waitForSessionEventQueue(); diff --git a/packages/server/src/server/agent/agent-manager.test.ts b/packages/server/src/server/agent/agent-manager.test.ts index ae8989c003..ccf29b17b0 100644 --- a/packages/server/src/server/agent/agent-manager.test.ts +++ b/packages/server/src/server/agent/agent-manager.test.ts @@ -21,6 +21,7 @@ import { } from "./agent-manager.js"; import { AgentStorage } from "./agent-storage.js"; import { InMemoryAgentTimelineStore } from "./agent-timeline-store.js"; +import { limitAgentTimelineItemContent } from "./agent-timeline-content.js"; import { toAgentPayload } from "./agent-projections.js"; import { projectTimelineRows } from "./timeline-projection.js"; import { getOpenAgentTabLabel, PARENT_AGENT_ID_LABEL } from "@getpaseo/protocol/agent-labels"; @@ -880,6 +881,66 @@ test("retries provider history hydration after a stream failure", async () => { } }); +test("notification batches share the run they start or join", async () => { + const session = new SteeringTestSession({ provider: "codex", cwd: process.cwd() }); + const workdir = mkdtempSync(join(tmpdir(), "agent-notification-turns-")); + const manager = new AgentManager({ + clients: { + codex: new (class extends TestAgentClient { + override async createSession(): Promise { + return session; + } + })(), + }, + logger, + }); + const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, { + workspaceId: undefined, + }); + const batch = (prefix: string) => + ["one", "two"] + .map((id) => + formatAgentMessage({ + id: `${prefix}-${id}`, + source: { kind: "agent-notification", agentId: "worker", event: "finished" }, + text: "Worker finished", + }), + ) + .join("\n\n"); + const consume = async (prompt: string, clientMessageId: string) => { + for await (const _event of manager.streamAgent(agent.id, prompt, { clientMessageId })) { + } + }; + try { + const first = consume("human", "human"); + await manager.waitForAgentRunStart(agent.id); + await expect( + manager.steerAgentRun(agent.id, batch("joined"), { clientMessageId: "joined-one" }), + ).resolves.toEqual({ status: "accepted" }); + session.pushEvent({ type: "turn_completed", provider: "codex", turnId: "active-turn-1" }); + await first; + const second = consume(batch("idle"), "idle-one"); + await manager.waitForAgentRunStart(agent.id); + session.pushEvent({ type: "turn_completed", provider: "codex", turnId: "active-turn-2" }); + await second; + expect( + manager.fetchTimeline(agent.id, { limit: 0 }).rows.map((row) => ({ + turnId: row.turnId, + id: row.item.type === "tool_call" ? row.item.callId : row.item.type, + })), + ).toEqual([ + { turnId: "active-turn-1", id: "user_message" }, + { turnId: "active-turn-1", id: "paseo-agent-message:joined-one" }, + { turnId: "active-turn-1", id: "paseo-agent-message:joined-two" }, + { turnId: "active-turn-2", id: "paseo-agent-message:idle-one" }, + { turnId: "active-turn-2", id: "paseo-agent-message:idle-two" }, + ]); + } finally { + await manager.closeAgent(agent.id); + rmSync(workdir, { recursive: true, force: true }); + } +}); + test("unavailable steer interrupts once and starts one replacement turn", async () => { const session = new SteeringTestSession({ provider: "codex", cwd: process.cwd() }); session.steerResult = "unavailable"; @@ -896,6 +957,131 @@ test("unavailable steer interrupts once and starts one replacement turn", async } }); +test("steers a send that arrives while the previous turn is still starting", async () => { + const startHeld = deferred(); + class SlowStartSteeringSession extends SteeringTestSession { + override async startTurn(prompt: AgentPromptInput): Promise<{ turnId: string }> { + await startHeld.promise; + return await super.startTurn(prompt); + } + } + const session = new SlowStartSteeringSession({ + provider: "codex", + cwd: process.cwd(), + }); + const workdir = mkdtempSync(join(tmpdir(), "agent-manager-steer-starting-")); + const manager = new AgentManager({ + clients: { + codex: new (class extends TestAgentClient { + override async createSession(): Promise { + return session; + } + })(), + }, + logger, + }); + let agentId: string | null = null; + try { + const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, { + workspaceId: undefined, + }); + agentId = agent.id; + const steerOptions = (clientMessageId: string) => ({ + replaceRunning: true, + activeTurnBehavior: "steer" as const, + runOptions: { clientMessageId }, + }); + await startAgentRun(manager, agent.id, "FIRST", logger, steerOptions("first-client")); + const second = startAgentRun( + manager, + agent.id, + "SECOND", + logger, + steerOptions("second-client"), + ); + + startHeld.resolve(); + await expect(second).resolves.toEqual({ disposition: "steered" }); + + expect(session.startPrompts).toEqual(["FIRST"]); + expect(session.interruptCount).toBe(0); + expect( + manager + .fetchTimeline(agent.id, { limit: 0 }) + .rows.filter((row) => row.item.type === "user_message") + .map((row) => ({ + text: row.item.type === "user_message" ? row.item.text : null, + turnId: row.turnId, + })), + ).toEqual([ + { text: "FIRST", turnId: "active-turn-1" }, + { text: "SECOND", turnId: "active-turn-1" }, + ]); + } finally { + startHeld.resolve(); + if (agentId) await manager.closeAgent(agentId).catch(() => undefined); + rmSync(workdir, { recursive: true, force: true }); + } +}); + +test("starts its own turn when the previous turn fails to start under a steer send", async () => { + const startHeld = deferred(); + class FailingFirstStartSession extends SteeringTestSession { + override async startTurn(prompt: AgentPromptInput): Promise<{ turnId: string }> { + if (prompt === "FIRST") { + this.startPrompts.push(prompt); + await startHeld.promise; + throw new Error("first start failed"); + } + return await super.startTurn(prompt); + } + } + const session = new FailingFirstStartSession({ + provider: "codex", + cwd: process.cwd(), + }); + const workdir = mkdtempSync(join(tmpdir(), "agent-manager-steer-failed-start-")); + const manager = new AgentManager({ + clients: { + codex: new (class extends TestAgentClient { + override async createSession(): Promise { + return session; + } + })(), + }, + logger, + }); + let agentId: string | null = null; + try { + const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, { + workspaceId: undefined, + }); + agentId = agent.id; + const steerOptions = (clientMessageId: string) => ({ + replaceRunning: true, + activeTurnBehavior: "steer" as const, + runOptions: { clientMessageId }, + }); + await startAgentRun(manager, agent.id, "FIRST", logger, steerOptions("first-client")); + const second = startAgentRun( + manager, + agent.id, + "SECOND", + logger, + steerOptions("second-client"), + ); + + startHeld.resolve(); + await expect(second).resolves.toEqual({ disposition: "turn_started" }); + await vi.waitFor(() => expect(session.startPrompts).toEqual(["FIRST", "SECOND"])); + expect(session.interruptCount).toBe(0); + } finally { + startHeld.resolve(); + if (agentId) await manager.closeAgent(agentId).catch(() => undefined); + rmSync(workdir, { recursive: true, force: true }); + } +}); + test("orders an accepted steer before output emitted while acknowledgement is pending", async () => { const entered = deferred(); const release = deferred(); @@ -1034,6 +1220,74 @@ test("orders buffered pre-steer output before an immediately accepted steer", as } }); +test("a steer the provider names without echoing it can be rewound to", async () => { + // Claude takes a steered message into the running turn without echoing it back as a user + // message, so the id it minted for the message reaches the manager only through the admission. + class SilentSteeringSession extends SteeringTestSession { + override readonly capabilities = { + ...TEST_CAPABILITIES, + supportsRewindFiles: true, + }; + rewindMessageIds: string[] = []; + + override async steerActiveTurn( + _prompt: AgentPromptInput, + options: import("./agent-sdk-types.js").SteerActiveTurnOptions, + ): Promise { + if (options.expectedTurnId !== `active-turn-${this.startCount}`) { + return { status: "unavailable" }; + } + return { status: "accepted", providerMessageId: `provider-${options.clientMessageId}` }; + } + + override async revertFiles({ messageId }: { messageId: string }): Promise { + this.rewindMessageIds.push(messageId); + } + } + const session = new SilentSteeringSession({ provider: "codex", cwd: process.cwd() }); + const workdir = mkdtempSync(join(tmpdir(), "agent-manager-steer-rewind-")); + const manager = new AgentManager({ + clients: { + codex: new (class extends TestAgentClient { + override async createSession(): Promise { + return session; + } + })(), + }, + logger, + }); + let agentId: string | null = null; + try { + const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, { + workspaceId: undefined, + }); + agentId = agent.id; + const run = manager.streamAgent(agent.id, "initial"); + void (async () => { + for await (const _event of run) { + } + })(); + await manager.waitForAgentRunStart(agent.id); + + await expect( + manager.steerAgentRun(agent.id, "steered", { clientMessageId: "steer-client" }), + ).resolves.toMatchObject({ status: "accepted" }); + const row = manager + .fetchTimeline(agent.id, { limit: 0 }) + .rows.find((candidate) => candidate.item.type === "user_message"); + expect(row).toMatchObject({ + providerMessageId: "provider-steer-client", + item: { text: "steered", clientMessageId: "steer-client" }, + }); + + await manager.rewind(agent.id, "steer-client", "files"); + expect(session.rewindMessageIds).toEqual(["provider-steer-client"]); + } finally { + if (agentId) await manager.closeAgent(agentId).catch(() => undefined); + rmSync(workdir, { recursive: true, force: true }); + } +}); + test("orders a concurrent replacement after a pending accepted steer", async () => { const entered = deferred(); const release = deferred(); @@ -2869,6 +3123,92 @@ test("createAgent passes daemon launch env through the provider launch context", }); }); +test.each([ + { provider: "codex", hasHandle: true }, + { provider: "opencode", hasHandle: true }, + { provider: "codex", hasHandle: false }, + { provider: "opencode", hasHandle: false }, +])( + "$provider preserves explicit launch env across reloads and storage-backed resumes (handle: $hasHandle)", + async ({ provider, hasHandle }) => { + const workdir = mkdtempSync(join(tmpdir(), "agent-manager-launch-env-")); + const storagePath = join(workdir, "agents"); + class LaunchEnvClient extends TestAgentClient { + lastLaunchContext: AgentLaunchContext | undefined; + + override async createSession( + config: AgentSessionConfig, + context?: AgentLaunchContext, + ): Promise { + this.lastLaunchContext = context; + const session = await super.createSession(config); + session.describePersistence = () => ({ provider, sessionId: session.id }); + return session; + } + + override async resumeSession( + handle: AgentPersistenceHandle, + config?: Partial, + context?: AgentLaunchContext, + ): Promise { + this.lastLaunchContext = context; + const session = await super.resumeSession(handle, config, context); + session.describePersistence = () => ({ provider, sessionId: handle.sessionId }); + return session; + } + } + + const client = new LaunchEnvClient(provider); + let storage = new AgentStorage(storagePath, logger); + let manager = new AgentManager({ clients: { [provider]: client }, registry: storage, logger }); + const env = { XDG_DATA_HOME: join(workdir, "agent-data"), CUSTOM_EMPTY: "" }; + const expectedEnv = { ...env }; + const agent = await manager.createAgent({ provider, cwd: workdir }, undefined, { + workspaceId: undefined, + env, + }); + onTestFinished(async () => { + await manager.closeAgent(agent.id); + await manager.flush(); + rmSync(workdir, { recursive: true, force: true }); + }); + env.XDG_DATA_HOME = "caller-mutated"; + + await manager.closeAgent(agent.id); + await manager.flush(); + + if (!hasHandle) { + const record = await storage.get(agent.id); + if (!record) throw new Error("Created agent was not persisted"); + await storage.upsert({ ...record, persistence: null }); + } + + // Fresh storage and manager instances must read the environment from disk. + for (let restart = 0; restart < 2; restart += 1) { + storage = new AgentStorage(storagePath, logger); + manager = new AgentManager({ clients: { [provider]: client }, registry: storage, logger }); + const resumed = await ensureAgentLoaded(agent.id, { + agentManager: manager, + agentStorage: storage, + logger, + }); + expect(client.lastLaunchContext).toEqual({ + agentId: agent.id, + env: { ...expectedEnv, PASEO_AGENT_ID: agent.id, PASEO_AGENT_CWD: workdir }, + }); + await manager.reloadAgentSession(agent.id); + expect(client.lastLaunchContext).toEqual({ + agentId: agent.id, + env: { ...expectedEnv, PASEO_AGENT_ID: agent.id, PASEO_AGENT_CWD: workdir }, + }); + expect(toAgentPayload(resumed)).not.toHaveProperty("launchEnv"); + expect(toAgentPayload(resumed).persistence?.metadata).not.toHaveProperty("launchEnv"); + await manager.closeAgent(agent.id); + await manager.flush(); + } + }, +); + test("createAgent passes persistSession to provider create options", async () => { const workdir = mkdtempSync(join(tmpdir(), "agent-manager-test-")); const storagePath = join(workdir, "agents"); @@ -4321,7 +4661,7 @@ test("importProviderSession imports the selected session without listing and pub expect(manager.getTimeline(imported.id)).toEqual([ { type: "user_message", text: "Trace provider imports" }, { type: "assistant_message", text: "Done" }, - { + limitAgentTimelineItemContent({ type: "tool_call", callId: "large-shell-result", name: "shell", @@ -4330,10 +4670,10 @@ test("importProviderSession imports the selected session without listing and pub detail: { type: "shell", command: "print output", - output: "x".repeat(64 * 1024), + output: "x".repeat(1024 * 1024), exitCode: 0, }, - }, + }), ]); expect(manager.listProviderSubagents(imported.id)).toEqual([ expect.objectContaining({ id: "thread-child", title: "Imported child", status: "completed" }), @@ -7747,7 +8087,7 @@ test("workspace ownership does not turn an ordinary agent into a disposable help expect(manager.listAgents().map((agent) => agent.id)).toEqual([agentId]); expect(await storage.get(agentId)).not.toBeNull(); // Workspace ownership preserves ordinary agent lifecycle hooks. - expect(beforeHookCalls).toContain("agent.create"); + expect(beforeHookCalls).toContain("agent.create.before"); }); test("global subscribers receive internal agent events only when they opt in", async () => { @@ -7788,6 +8128,60 @@ test("global subscribers receive internal agent events only when they opt in", a unsubscribeOptedIn(); }); +test("agent removal notifications respect scoped subscriptions and internal visibility", () => { + const manager = new AgentManager({ clients: {}, logger }); + const removedId = "00000000-0000-4000-8000-000000000901"; + const internalId = "00000000-0000-4000-8000-000000000902"; + const otherId = "00000000-0000-4000-8000-000000000903"; + const publicEvents: AgentManagerEvent[] = []; + const allEvents: AgentManagerEvent[] = []; + const scopedEvents: AgentManagerEvent[] = []; + const internalEvents: AgentManagerEvent[] = []; + const unrelatedEvents: AgentManagerEvent[] = []; + const releases = [ + manager.subscribe((event) => publicEvents.push(event), { replayState: false }), + manager.subscribe((event) => allEvents.push(event), { + replayState: false, + includeInternal: true, + }), + manager.subscribe((event) => scopedEvents.push(event), { + replayState: false, + agentId: removedId, + }), + manager.subscribe((event) => internalEvents.push(event), { + replayState: false, + agentId: internalId, + }), + manager.subscribe((event) => unrelatedEvents.push(event), { + replayState: false, + agentId: otherId, + }), + ]; + try { + manager.notifyAgentRemoved({ id: removedId, workspaceId: "workspace" }); + manager.notifyAgentRemoved({ id: internalId, workspaceId: "workspace", internal: true }); + const publicRemoval = { + type: "agent_removed", + agentId: removedId, + workspaceId: "workspace", + internal: false, + }; + const internalRemoval = { + type: "agent_removed", + agentId: internalId, + workspaceId: "workspace", + internal: true, + }; + expect(publicEvents).toEqual([publicRemoval]); + expect(allEvents).toEqual([publicRemoval, internalRemoval]); + expect(scopedEvents).toEqual([publicRemoval]); + expect(internalEvents).toEqual([internalRemoval]); + expect(unrelatedEvents).toEqual([]); + } finally { + for (const release of releases) release(); + } +}); + test("getAgent returns internal agents by ID", async () => { const internalAgentId = "00000000-0000-4000-8000-000000000107"; const workdir = mkdtempSync(join(tmpdir(), "agent-manager-test-")); @@ -11341,7 +11735,7 @@ test("listImportableSessions searches every provider result before global rankin ]); }); -test("user_message events wrapping a paseo-system envelope are not added to the timeline", async () => { +test("system-injected prompts appear as trigger tools in the live timeline", async () => { const workdir = mkdtempSync(join(tmpdir(), "agent-manager-envelope-live-")); const storagePath = join(workdir, "agents"); const storage = new AgentStorage(storagePath, logger); @@ -11370,13 +11764,16 @@ test("user_message events wrapping a paseo-system envelope are not added to the await manager.runAgent(snapshot.id, { text: "do something" }); const timeline = manager.getTimeline(snapshot.id); + expect(timeline).toContainEqual( + expect.objectContaining({ type: "tool_call", name: "heartbeat", status: "completed" }), + ); const userMessages = timeline.filter((item) => item.type === "user_message"); expect(userMessages).toHaveLength(1); expect(userMessages[0].text).toBe("plain user message"); }); -test("user_message events wrapping a paseo-system envelope are not restored during history replay", async () => { +test("system-injected prompts appear as trigger tools during history replay", async () => { const workdir = mkdtempSync(join(tmpdir(), "agent-manager-envelope-history-")); const storagePath = join(workdir, "agents"); const storage = new AgentStorage(storagePath, logger); @@ -11411,6 +11808,9 @@ test("user_message events wrapping a paseo-system envelope are not restored duri await manager.hydrateTimelineFromProvider(snapshot.id, { force: true }); const timeline = manager.getTimeline(snapshot.id); + expect(timeline).toContainEqual( + expect.objectContaining({ type: "tool_call", name: "heartbeat", status: "completed" }), + ); const userMessages = timeline.filter((item) => item.type === "user_message"); expect(userMessages).toHaveLength(1); @@ -11626,10 +12026,7 @@ test("commits startup notices once on create and after restored history", async exitCode: 0, }, }; - const limitedToolOutput: AgentTimelineItem = { - ...toolOutput, - detail: { type: "shell", command: "print output", output: "x".repeat(64 * 1024), exitCode: 0 }, - }; + const limitedToolOutput = limitAgentTimelineItemContent(toolOutput); class NotifyingSession extends TestAgentSession { readonly initialTimeline = [{ item: notice, timestamp: "2026-09-22T00:00:00.000Z" }]; override async *streamHistory(): AsyncGenerator { @@ -12006,15 +12403,15 @@ test.each([ const session = client.sessions[0]!; session.pushEvent({ type: "turn_started", provider: "codex", turnId: "hook-turn" }); await expect - .poll(() => events.filter(({ name }) => name === "agent.turn_started").length) + .poll(() => events.filter(({ name }) => name === "agent.turn.before").length) .toBe(1); expect(timelineStore.itemReads).toBe(readsBeforeDispatch); session.pushEvent(terminalEvent); await expect - .poll(() => events.filter(({ name }) => name === "agent.turn_ended")) + .poll(() => events.filter(({ name }) => name === "agent.turn.after")) .toEqual([ { - name: "agent.turn_ended", + name: "agent.turn.after", event: { agent: { id: agent.id, diff --git a/packages/server/src/server/agent/agent-manager.ts b/packages/server/src/server/agent/agent-manager.ts index 1342576f7f..94250e5cdd 100644 --- a/packages/server/src/server/agent/agent-manager.ts +++ b/packages/server/src/server/agent/agent-manager.ts @@ -85,7 +85,11 @@ import { import { invokeRewindCapability, type RewindMode } from "./rewind/rewind.js"; import { parseAgentMessage, projectAgentMessages } from "./agent-messages/index.js"; import { isStaleProviderSessionError } from "./stale-provider-session-error.js"; -import { stripInternalPaseoMcpServer, withRuntimePaseoMcpServer } from "./runtime-mcp-config.js"; +import { + PASEO_MCP_SERVER_NAME, + stripInternalPaseoMcpServer, + withRuntimePaseoMcpServer, +} from "./runtime-mcp-config.js"; import { resolveCreateAgentTitles } from "./create-agent-title.js"; import type { PaseoToolCatalogFactory } from "./tools/types.js"; import { isPaseoToolPolicyEnabled } from "./paseo-tool-policy.js"; @@ -232,6 +236,7 @@ export type { export type AgentManagerEvent = | { type: "agent_state"; agent: ManagedAgent } + | { type: "agent_removed"; agentId: string; workspaceId?: string; internal: boolean } | { type: "provider_subagent"; event: ProviderSubagentStoreEvent } | { type: "timeline_replacement"; agentId: string; epoch: string } | { @@ -417,6 +422,8 @@ interface ManagedAgentBase { owner?: AgentOwner; capabilities: AgentCapabilityFlags; config: AgentSessionConfig; + /** Explicit launch overrides, before per-opening hooks and daemon-owned variables. */ + launchEnv?: Record; runtimeInfo?: AgentRuntimeInfo; createdAt: Date; updatedAt: Date; @@ -559,18 +566,20 @@ interface AgentMetadataPatch { const SYSTEM_ERROR_PREFIX = "[System Error]"; -function attachPersistenceCwd( +function normalizePersistenceForConfig( handle: AgentPersistenceHandle | null, - cwd: string, + config: AgentSessionConfig, ): AgentPersistenceHandle | null { if (!handle) { return null; } + const { mcpServers: _launchMcpServers, ...metadata } = handle.metadata ?? {}; return { ...handle, metadata: { - ...handle.metadata, - cwd, + ...metadata, + cwd: config.cwd, + ...(config.mcpServers ? { mcpServers: config.mcpServers } : {}), }, }; } @@ -1352,7 +1361,7 @@ export class AgentManager { this.assertAcceptingAgentRegistrations(); const resolvedAgentId = validateAgentId(agentId ?? this.idFactory(), "createAgent"); if (this.pluginLifecycle && !config.internal) { - const request = await this.pluginLifecycle.before("agent.create", { + const request = await this.pluginLifecycle.before("agent.create.before", { config, env: options.env, }); @@ -1387,16 +1396,17 @@ export class AgentManager { const providerLaunchConfig = this.resolveProviderLaunchConfig(launchConfig, launchContext); const createOptions = this.buildCreateSessionOptions(options); const session = await client.createSession(providerLaunchConfig, launchContext, createOptions); - await this.requireExternalMcpSupport(session, storedConfig); + await this.requireExternalMcpSupport(session, providerLaunchConfig, launchContext); const agent = await this.registerSession(session, storedConfig, resolvedAgentId, { labels: options.labels, initialTitle: options.initialTitle, workspaceId: options.workspaceId, owner: options.owner, + launchEnv: options.env ? { ...options.env } : undefined, historyPrimed: true, }); if (!agent.internal) { - this.pluginLifecycle?.emit("agent.created", { + this.pluginLifecycle?.emit("agent.create.after", { agent: describeHookAgent({ ...agent, title: agent.config.title }), }); } @@ -1481,10 +1491,11 @@ export class AgentManager { : resumeOptions; const purpose = currentResumeOptions?.purpose ?? "interactive"; + const launchEnv = record?.launchEnv; const { storedConfig, launchConfig, paseoToolPolicy } = await this.prepareSessionConfig( mergedConfig, resolvedAgentId, - { purpose }, + { purpose, env: launchEnv }, ); const client = this.requireClient(handle.provider); const available = await client.isAvailable(); @@ -1499,7 +1510,7 @@ export class AgentManager { client, storedConfig.cwd, paseoToolPolicy, - undefined, + launchEnv, { reason: "resume", purpose, @@ -1515,9 +1526,10 @@ export class AgentManager { launchContext, currentResumeOptions, ); - await this.requireExternalMcpSupport(session, storedConfig); + await this.requireExternalMcpSupport(session, providerLaunchConfig, launchContext); return this.registerSession(session, storedConfig, resolvedAgentId, { ...options, + launchEnv, persistence: handle, restoring: true, }); @@ -1578,6 +1590,7 @@ export class AgentManager { }, { config: providerLaunchConfig, storedConfig, launchContext }, ); + await this.requireExternalMcpSupport(imported.session, providerLaunchConfig, launchContext); let handedToRegistration = false; try { const importedConfig = await this.normalizeConfig( @@ -1654,6 +1667,7 @@ export class AgentManager { const { storedConfig, launchConfig, paseoToolPolicy } = await this.prepareSessionConfig( refreshConfig, agentId, + { env: existing.launchEnv }, ); const hadPreviousPaseoToolPolicy = this.paseoToolPolicies.has(agentId); const previousPaseoToolPolicy = this.paseoToolPolicies.get(agentId); @@ -1662,7 +1676,7 @@ export class AgentManager { client, storedConfig.cwd, paseoToolPolicy, - undefined, + existing.launchEnv, { reason: "refresh", purpose: "interactive", @@ -1673,10 +1687,10 @@ export class AgentManager { ); const providerLaunchConfig = this.resolveProviderLaunchConfig(launchConfig, launchContext); if ( - Object.keys(storedConfig.mcpServers ?? {}).length > 0 && + Object.keys(stripInternalPaseoMcpServer(providerLaunchConfig).mcpServers ?? {}).length > 0 && existing.session.capabilities.supportsMcpServers !== true ) { - throw new Error(`Provider '${provider}' does not support MCP servers`); + throw this.unsupportedMcpError(providerLaunchConfig, launchContext); } let session: AgentSession | undefined; @@ -1695,7 +1709,7 @@ export class AgentManager { session = handle ? await client.resumeSession(handle, providerLaunchConfig, launchContext) : await client.createSession(providerLaunchConfig, launchContext); - await this.requireExternalMcpSupport(session, storedConfig); + await this.requireExternalMcpSupport(session, providerLaunchConfig, launchContext); this.assertAcceptingAgentRegistrations(); if (rehydrateFromDisk) { @@ -1713,6 +1727,7 @@ export class AgentManager { labels: existing.labels, workspaceId: existing.workspaceId, owner: existing.owner, + launchEnv: existing.launchEnv, createdAt: existing.createdAt, updatedAt: existing.updatedAt, lastUserMessageAt: existing.lastUserMessageAt, @@ -2107,7 +2122,7 @@ export class AgentManager { const archivedRecord = buildArchivedAgentRecord(record, options); await this.requireRegistry().upsert(archivedRecord); if (!record.archivedAt && !record.internal) { - this.pluginLifecycle?.emit("agent.archived", { + this.pluginLifecycle?.emit("agent.archive.after", { agent: describeHookAgent(archivedRecord), archivedAt: archivedRecord.archivedAt, }); @@ -2720,7 +2735,7 @@ export class AgentManager { throw error; } if (isStaleProviderSessionError(error)) { - pendingRun.start = { status: "failed", error: error.message }; + this.runs.settleForegroundStart(pendingRun, { status: "failed", error: error.message }); agent.pendingReplacement = false; if (!agent.activeForegroundTurnId) agent.lifecycle = "idle"; this.runs.settleForegroundRun(agentId, pendingRun.token); @@ -2728,20 +2743,24 @@ export class AgentManager { } agent.pendingReplacement = false; const errorMsg = error instanceof Error ? error.message : "Failed to start turn"; - pendingRun.start = { status: "failed", error: errorMsg }; - // A terminal rejection belongs after the submitted prompt even though no provider turn exists. - if (options?.clientMessageId) { - this.recordSubmittedPrompt(agent, prompt, options.clientMessageId, "rejected", { - messageId: options.clientMessageId, + this.runs.settleForegroundStart(pendingRun, { status: "failed", error: errorMsg }); + try { + // A terminal rejection belongs after the submitted prompt even though no provider turn exists. + if (options?.clientMessageId) { + this.recordSubmittedPrompt(agent, prompt, options.clientMessageId, "rejected", { + messageId: options.clientMessageId, + }); + } + await this.handleStreamEvent(agent, { + type: "turn_failed", + provider: agent.provider, + error: errorMsg, }); + this.finalizeForegroundTurn(agent); + } finally { + // A steer waiting on this start is released only once the run is cleared. + this.runs.settleForegroundRun(agentId, pendingRun.token); } - await this.handleStreamEvent(agent, { - type: "turn_failed", - provider: agent.provider, - error: errorMsg, - }); - this.finalizeForegroundTurn(agent); - this.runs.settleForegroundRun(agentId, pendingRun.token); throw error; } } @@ -2818,7 +2837,7 @@ export class AgentManager { agent.pendingReplacement = false; } const turnStartedAt = new Date(); - pendingRun.start = { status: "started", turnId }; + this.runs.settleForegroundStart(pendingRun, { status: "started", turnId }); agent.activeForegroundTurnId = turnId; this.openActiveTurn(agent, turnId, turnStartedAt); agent.lifecycle = "running"; @@ -2921,7 +2940,10 @@ export class AgentManager { ? { provider: mutableAgent.provider, sessionId: mutableAgent.runtimeInfo.sessionId } : null); if (persistenceHandle) { - mutableAgent.persistence = attachPersistenceCwd(persistenceHandle, mutableAgent.cwd); + mutableAgent.persistence = normalizePersistenceForConfig( + persistenceHandle, + mutableAgent.config, + ); } this.logger.trace( { @@ -3007,7 +3029,13 @@ export class AgentManager { expectedTurnId, }); if (admission.status === "accepted") { - await this.recordAcceptedSteer(agent, prompt, options?.clientMessageId, expectedTurnId); + await this.recordAcceptedSteer( + agent, + prompt, + options?.clientMessageId, + expectedTurnId, + admission.providerMessageId, + ); } return admission; }); @@ -3024,6 +3052,9 @@ export class AgentManager { prompt: AgentPromptInput, options?: AgentSteerOptions, ): Promise { + // A turn that is still starting has no id to steer yet. Replacing it would drop its + // prompt, so wait until it is accepted (or fails) and steer the turn it became. + await this.runs.waitForForegroundStart(agentId); const agent = this.requireSessionAgent(agentId); const expectedTurnId = agent.activeForegroundTurnId ?? agent.activeTurnId; if (!expectedTurnId) { @@ -3037,7 +3068,13 @@ export class AgentManager { expectedTurnId, }); if (admission.status === "accepted") { - await this.recordAcceptedSteer(agent, prompt, options?.clientMessageId, expectedTurnId); + await this.recordAcceptedSteer( + agent, + prompt, + options?.clientMessageId, + expectedTurnId, + admission.providerMessageId, + ); } return admission; }) @@ -3142,6 +3179,7 @@ export class AgentManager { prompt: AgentPromptInput, clientMessageId: string | undefined, expectedTurnId: string, + providerMessageId: string | undefined, ): Promise { if (!clientMessageId) { return; @@ -3149,6 +3187,7 @@ export class AgentManager { this.recordSubmittedPrompt(agent, prompt, clientMessageId, "accepted", { messageId: clientMessageId, turnId: expectedTurnId, + ...(providerMessageId ? { providerMessageId } : {}), }); this.emitState(agent); } @@ -3480,6 +3519,10 @@ export class AgentManager { "agent.rewind.complete", ); } catch (error) { + // Native rewind can commit a fork before history refresh fails. Recovery + // must resume that latest handle rather than the abandoned conversation. + this.refreshSessionPersistence(agent); + await this.persistSnapshot(agent); this.logger.warn( { err: error, agentId, provider: agent.provider, messageId, mode }, "agent.rewind.failed", @@ -3495,6 +3538,15 @@ export class AgentManager { await this.deleteCommittedTimeline(agentId); } + notifyAgentRemoved(agent: Pick): void { + this.dispatch({ + type: "agent_removed", + agentId: agent.id, + workspaceId: agent.workspaceId, + internal: agent.internal === true, + }); + } + async deleteCommittedTimeline(agentId: string): Promise { await this.durableTimelineStore?.deleteAgent(agentId); } @@ -3753,6 +3805,7 @@ export class AgentManager { publishWhenReady?: boolean; workspaceId?: string; owner?: AgentOwner; + launchEnv?: Record; }, ): Promise { let registered = false; @@ -3865,16 +3918,23 @@ export class AgentManager { private async requireExternalMcpSupport( session: AgentSession, - storedConfig: AgentSessionConfig, + launchConfig: AgentSessionConfig, + launchContext: AgentLaunchContext, ): Promise { if ( - Object.keys(storedConfig.mcpServers ?? {}).length === 0 || + Object.keys(stripInternalPaseoMcpServer(launchConfig).mcpServers ?? {}).length === 0 || session.capabilities.supportsMcpServers === true ) { return; } await this.closeUnregisteredSession(session); - throw new Error(`Provider '${storedConfig.provider}' does not support MCP servers`); + throw this.unsupportedMcpError(launchConfig, launchContext); + } + + private unsupportedMcpError(config: AgentSessionConfig, context: AgentLaunchContext): Error { + const owners = [...new Set(Object.values(context.mcpServerOwners ?? {}))]; + const source = owners.length ? ` (plugin ${owners.join(", ")})` : ""; + return new Error(`Provider '${config.provider}' does not support MCP servers${source}`); } private async initializeAgentTimelineForRegister(params: { @@ -3931,6 +3991,7 @@ export class AgentManager { persistence?: AgentPersistenceHandle; workspaceId?: string; owner?: AgentOwner; + launchEnv?: Record; } | undefined; }): ActiveManagedAgent { @@ -3941,6 +4002,7 @@ export class AgentManager { cwd: config.cwd, workspaceId: options?.workspaceId, owner: options?.owner, + launchEnv: options?.launchEnv, session, capabilities: session.capabilities, config, @@ -3960,9 +4022,9 @@ export class AgentManager { foregroundTurnWaiters: new Set(), finalizedForegroundTurnIds: new Set(), unsubscribeSession: null, - persistence: attachPersistenceCwd( + persistence: normalizePersistenceForConfig( options?.persistence ?? session.describePersistence(), - config.cwd, + config, ), historyPrimed: options?.historyPrimed ?? durableTimelineHasRows, lastUserMessageAt: options?.lastUserMessageAt ?? null, @@ -4034,7 +4096,7 @@ export class AgentManager { private emitClosedAgent(agent: ManagedAgentClosed, options?: { persist?: boolean }): void { this.emitState(agent, options); if (!agent.internal) { - this.pluginLifecycle?.emit("agent.closed", { + this.pluginLifecycle?.emit("agent.close.after", { agent: describeHookAgent({ ...agent, title: agent.config.title }), }); } @@ -4266,9 +4328,9 @@ export class AgentManager { newInfo.modeId !== agent.runtimeInfo?.modeId; agent.runtimeInfo = newInfo; if (!agent.persistence && newInfo.sessionId) { - agent.persistence = attachPersistenceCwd( + agent.persistence = normalizePersistenceForConfig( { provider: agent.provider, sessionId: newInfo.sessionId }, - agent.cwd, + agent.config, ); } // Emit state if runtimeInfo changed so clients get the updated model @@ -4626,9 +4688,9 @@ export class AgentManager { case "model_changed": agent.runtimeInfo = event.runtimeInfo; if (!agent.persistence && event.runtimeInfo.sessionId) { - agent.persistence = attachPersistenceCwd( + agent.persistence = normalizePersistenceForConfig( { provider: agent.provider, sessionId: event.runtimeInfo.sessionId }, - agent.cwd, + agent.config, ); } this.applyObservedMode(agent, event.runtimeInfo.modeId ?? agent.currentModeId); @@ -4702,7 +4764,7 @@ export class AgentManager { private refreshSessionPersistence(agent: ActiveManagedAgent): void { const handle = agent.session.describePersistence(); if (handle) { - agent.persistence = attachPersistenceCwd(handle, agent.cwd); + agent.persistence = normalizePersistenceForConfig(handle, agent.config); } } @@ -5342,7 +5404,7 @@ export class AgentManager { for (const subscriber of this.subscribers) { if ( subscriber.agentId && - event.type === "agent_stream" && + (event.type === "agent_stream" || event.type === "agent_removed") && subscriber.agentId !== event.agentId ) { continue; @@ -5378,6 +5440,7 @@ export class AgentManager { private eventBelongsToInternalAgent(event: AgentManagerEvent): boolean { if (event.type === "agent_state") return event.agent.internal === true; + if (event.type === "agent_removed") return event.internal; if (event.type === "agent_stream") return this.agents.get(event.agentId)?.internal === true; if (event.type !== "provider_subagent") return false; const parentAgentId = @@ -5519,6 +5582,8 @@ export class AgentManager { // A plugin changing during this open must still make the resulting session stale. const generation = this.sessionOpenGeneration; this.detachPluginTools(agentId); + let mcpServers: AgentSessionConfig["mcpServers"]; + let mcpServerOwners: Record | undefined; if (this.pluginLifecycle) { const request = { agentId, @@ -5531,14 +5596,20 @@ export class AgentManager { title: opening?.title ?? null, labels: opening?.labels ?? {}, tools: [], + mcpServers: {}, }; - const transformed = await this.pluginLifecycle.before("agent.session_open", request); + const transformed = await this.pluginLifecycle.before("agent.open.before", request); env = transformed.env; - if (request.purpose === "interactive") + if (request.purpose === "interactive") { this.attachedPluginTools.set(agentId, transformed.tools as AttachedAgentTool[]); + mcpServers = transformed.mcpServers; + mcpServerOwners = transformed.mcpServerOwners; + } } const context: AgentLaunchContext = { agentId, + mcpServers, + mcpServerOwners, env: { ...env, PASEO_AGENT_ID: agentId, @@ -5572,7 +5643,26 @@ export class AgentManager { launchConfig: AgentSessionConfig, launchContext: AgentLaunchContext, ): AgentSessionConfig { - return launchContext.paseoTools ? stripInternalPaseoMcpServer(launchConfig) : launchConfig; + const savedServerNames = new Set( + Object.keys(stripInternalPaseoMcpServer(launchConfig).mcpServers ?? {}), + ); + for (const name of Object.keys(launchContext.mcpServers ?? {})) { + const owner = launchContext.mcpServerOwners?.[name]; + if (name === PASEO_MCP_SERVER_NAME || savedServerNames.has(name)) { + const existingOwner = savedServerNames.has(name) + ? "agent saved configuration" + : "Paseo internal MCP server"; + throw new Error(`MCP server '${name}' from plugin ${owner} collides with ${existingOwner}`); + } + } + const merged = + Object.keys(launchContext.mcpServers ?? {}).length > 0 + ? { + ...launchConfig, + mcpServers: { ...launchConfig.mcpServers, ...launchContext.mcpServers }, + } + : launchConfig; + return launchContext.paseoTools ? stripInternalPaseoMcpServer(merged) : merged; } private async requireAvailableClient(options: { provider: AgentProvider }): Promise { diff --git a/packages/server/src/server/agent/agent-messages/envelope.ts b/packages/server/src/server/agent/agent-messages/envelope.ts index 2144d6ae02..a0aa880fce 100644 --- a/packages/server/src/server/agent/agent-messages/envelope.ts +++ b/packages/server/src/server/agent/agent-messages/envelope.ts @@ -1,5 +1,5 @@ import { renderPromptAttachmentAsText } from "../prompt-attachments.js"; -import { randomUUID } from "node:crypto"; +import { createHash, randomUUID } from "node:crypto"; import { z } from "zod"; import type { AgentPromptContentBlock, @@ -175,9 +175,18 @@ function projectAgentMessage(item: AgentTimelineItem): AgentTimelineItem | null if (item.type !== "user_message") return item; const message = parseAgentMessage(item.text); if (!message) { - // COMPAT(legacySystemEnvelope): added in v0.11.1; remove after 2027-04-08 once - // legacy notification history is retired. Schedules still use this envelope. - return isSystemInjectedEnvelope(item.text) ? null : item; + // Schedule bodies include their run ID, keeping identity stable across acceptance + // and provider replay even when the provider assigns its own message ID. + if (!isSystemInjectedEnvelope(item.text)) return item; + const text = item.text.slice("\n".length, -"\n".length); + return { + type: "tool_call", + callId: `paseo-system:${createHash("sha256").update(item.text).digest("hex")}`, + name: "heartbeat", + status: "completed", + error: null, + detail: { type: "plain_text", text, icon: "sparkles" }, + }; } const { source } = message; if (!source) { diff --git a/packages/server/src/server/agent/agent-projections.ts b/packages/server/src/server/agent/agent-projections.ts index 7d154e9c14..b388143d8e 100644 --- a/packages/server/src/server/agent/agent-projections.ts +++ b/packages/server/src/server/agent/agent-projections.ts @@ -95,6 +95,7 @@ export function toStoredAgentRecord( lastStatus: agent.lifecycle, lastModeId: agent.currentModeId ?? config?.modeId ?? null, config: config ?? null, + launchEnv: agent.launchEnv ? { ...agent.launchEnv } : undefined, runtimeInfo, features: normalizeFeatures(agent.features), persistence, diff --git a/packages/server/src/server/agent/agent-prompt.test.ts b/packages/server/src/server/agent/agent-prompt.test.ts index 00e70756de..2c150bd2e1 100644 --- a/packages/server/src/server/agent/agent-prompt.test.ts +++ b/packages/server/src/server/agent/agent-prompt.test.ts @@ -357,3 +357,21 @@ test("a human pasting an agent envelope stays a human message through provider r clientMessageId: "human-submission", }); }); + +test("schedule prompts remain visible as completed tool calls on replay", () => { + const text = formatSystemNotificationPrompt("Heartbeat: check progress"); + expect(projectAgentMessages({ type: "user_message", messageId: "fire-1", text })).toEqual([ + expect.objectContaining({ + type: "tool_call", + status: "completed", + detail: { type: "plain_text", text: "Heartbeat: check progress", icon: "sparkles" }, + }), + ]); +}); + +test("schedule trigger identity survives the provider assigning a message ID", () => { + const text = formatSystemNotificationPrompt("Schedule fired (id=heartbeat, run=run-1)."); + expect(projectAgentMessages({ type: "user_message", text })).toEqual( + projectAgentMessages({ type: "user_message", text, messageId: "provider-message" }), + ); +}); diff --git a/packages/server/src/server/agent/agent-run-state.test.ts b/packages/server/src/server/agent/agent-run-state.test.ts new file mode 100644 index 0000000000..29e09a5f94 --- /dev/null +++ b/packages/server/src/server/agent/agent-run-state.test.ts @@ -0,0 +1,51 @@ +import { describe, expect, test } from "vitest"; + +import { AgentRunState } from "./agent-run-state.js"; + +function track(promise: Promise): { readonly resolved: boolean } { + const state = { resolved: false }; + void (async () => { + await promise; + state.resolved = true; + })(); + return state; +} + +async function flushMicrotasks(): Promise { + await new Promise((resolve) => setImmediate(resolve)); +} + +describe("waitForForegroundStart", () => { + test("resolves once the starting turn has an id", async () => { + const runs = new AgentRunState(); + const run = runs.createPendingRun("agent"); + const wait = track(runs.waitForForegroundStart("agent")); + + await flushMicrotasks(); + expect(wait.resolved).toBe(false); + + runs.settleForegroundStart(run, { status: "started", turnId: "turn-1" }); + await flushMicrotasks(); + expect(wait.resolved).toBe(true); + }); + + test("waits for a failed start's run to be cleared", async () => { + const runs = new AgentRunState(); + const run = runs.createPendingRun("agent"); + const wait = track(runs.waitForForegroundStart("agent")); + + runs.settleForegroundStart(run, { status: "failed", error: "start failed" }); + await flushMicrotasks(); + expect(wait.resolved).toBe(false); + expect(runs.hasPendingRun("agent")).toBe(true); + + runs.settleForegroundRun("agent", run.token); + await flushMicrotasks(); + expect(wait.resolved).toBe(true); + }); + + test("resolves at once when no turn is starting", async () => { + const runs = new AgentRunState(); + await expect(runs.waitForForegroundStart("agent")).resolves.toBeUndefined(); + }); +}); diff --git a/packages/server/src/server/agent/agent-run-state.ts b/packages/server/src/server/agent/agent-run-state.ts index ad1eb0af34..0ea85f6d81 100644 --- a/packages/server/src/server/agent/agent-run-state.ts +++ b/packages/server/src/server/agent/agent-run-state.ts @@ -10,14 +10,18 @@ export interface ForegroundTurnWaiter { resolveSettled: () => void; } +type ForegroundRunStart = + | { status: "pending" } + | { status: "started"; turnId: string } + | { status: "failed"; error: string }; + export interface PendingForegroundRun { token: string; kind: "foreground"; stagedEvents: AgentStreamEvent[]; - start: - | { status: "pending" } - | { status: "started"; turnId: string } - | { status: "failed"; error: string }; + start: ForegroundRunStart; + turnStartedPromise: Promise; + resolveTurnStarted: () => void; settled: boolean; settledPromise: Promise; resolveSettled: () => void; @@ -54,6 +58,28 @@ export class AgentRunState { return run?.kind === "foreground" ? run : null; } + settleForegroundStart( + run: PendingForegroundRun, + start: Exclude, + ): void { + run.start = start; + if (start.status === "started") { + run.resolveTurnStarted(); + } + } + + /** + * Resolves once the agent's foreground run has a turn id or has ended. A failed start + * resolves only once its run is cleared, so callers never see a failed run still tracked. + */ + async waitForForegroundStart(agentId: string): Promise { + const run = this.getPendingRun(agentId); + if (run?.start.status !== "pending") { + return; + } + await Promise.race([run.turnStartedPromise, run.settledPromise]); + } + hasPendingRun(agentId: string): boolean { return this.getPendingRun(agentId) !== null; } @@ -277,10 +303,16 @@ export class ForegroundTurnStream { } function createPendingForegroundRun(): PendingForegroundRun { + let resolveTurnStarted!: () => void; + const turnStartedPromise = new Promise((resolvePromise) => { + resolveTurnStarted = resolvePromise; + }); return { ...createTrackedRunState(), kind: "foreground", start: { status: "pending" }, + turnStartedPromise, + resolveTurnStarted, stagedEvents: [], }; } diff --git a/packages/server/src/server/agent/agent-sdk-types.ts b/packages/server/src/server/agent/agent-sdk-types.ts index 6818e65445..903bbe5c99 100644 --- a/packages/server/src/server/agent/agent-sdk-types.ts +++ b/packages/server/src/server/agent/agent-sdk-types.ts @@ -208,7 +208,11 @@ export interface AgentSteerOptions extends AgentRunOptions { clearPendingPermissions?: boolean; } -export type SteerResult = { status: "accepted" } | { status: "unavailable" }; +// providerMessageId names the steered message in the provider's own history, when the provider +// mints one. Rewinding to the message needs it. +export type SteerResult = + | { status: "accepted"; providerMessageId?: string } + | { status: "unavailable" }; export interface SteerActiveTurnOptions extends AgentSteerOptions { expectedTurnId: string; @@ -313,7 +317,10 @@ export type ToolCallDetail = subAgentType?: string; description?: string; childSessionId?: string; - log: string; + // COMPAT(subagent-log): added in v0.14.1, remove after 2027-04-30. Apps before v0.14.1 + // require `log`; every producer sends it empty and carries the same tag. Optional here because + // protocol timeline items, where `log` is optional, flow into this type. + log?: string; actions?: Array<{ index: number; toolName: string; @@ -616,6 +623,9 @@ export interface AgentSessionConfig { } export interface AgentLaunchContext { + /** Launch-only plugin MCP servers and their owners; never persisted. */ + mcpServers?: Record; + mcpServerOwners?: Record; agentId?: string; env?: Record; /** @@ -687,6 +697,7 @@ export interface AgentSession { requestId: string, response: AgentPermissionResponse, ): Promise; + /** Null until a new provider process could resume this session; see docs/providers.md. */ describePersistence(): AgentPersistenceHandle | null; /** * Resolve once every foreground turn that predates this call can no longer run or become active. diff --git a/packages/server/src/server/agent/agent-storage.ts b/packages/server/src/server/agent/agent-storage.ts index be94a31d49..a097bd7f82 100644 --- a/packages/server/src/server/agent/agent-storage.ts +++ b/packages/server/src/server/agent/agent-storage.ts @@ -54,8 +54,10 @@ const STORED_AGENT_SCHEMA = z.object({ title: z.string().nullable().optional(), labels: z.record(z.string(), z.string()).default({}), lastStatus: AgentStatusSchema.default("closed"), + resumeOnStartup: z.boolean().optional(), lastModeId: z.string().nullable().optional(), config: SERIALIZABLE_CONFIG_SCHEMA, + launchEnv: z.record(z.string(), z.string()).optional(), runtimeInfo: z .object({ provider: z.string(), @@ -259,6 +261,8 @@ export class AgentStorage { if (existing && existing.archivedAt !== undefined) { record.archivedAt = existing.archivedAt; } + record.resumeOnStartup = + existing?.resumeOnStartup && agent.lifecycle !== "idle" && agent.lifecycle !== "error"; return record; }); } diff --git a/packages/server/src/server/agent/agent-timeline-content.test.ts b/packages/server/src/server/agent/agent-timeline-content.test.ts index 1ccb78c67a..1461d0aeef 100644 --- a/packages/server/src/server/agent/agent-timeline-content.test.ts +++ b/packages/server/src/server/agent/agent-timeline-content.test.ts @@ -1,12 +1,30 @@ +import { AgentTimelineItemPayloadSchema } from "@getpaseo/protocol/messages"; import { describe, expect, test } from "vitest"; +import type { AgentTimelineItem } from "./agent-sdk-types.js"; import { limitAgentTimelineItemContent } from "./agent-timeline-content.js"; +function serializedBytes(item: AgentTimelineItem): number { + return Buffer.byteLength(JSON.stringify(item), "utf8"); +} + describe("agent timeline content", () => { + test("returns an item within budget unchanged", () => { + const item: AgentTimelineItem = { + type: "tool_call", + callId: "small", + name: "Bash", + status: "completed", + error: null, + detail: { type: "shell", command: "ls", output: "x".repeat(60 * 1024) }, + }; + expect(limitAgentTimelineItemContent(item)).toBe(item); + }); + test.each([false, true])( - "preserves the exact UTF-16 prefix for oversized shell output (failed=%s)", + "cuts oversized shell output and keeps short fields whole (failed=%s)", (failed) => { - const text = "x".repeat(64 * 1024 - 1) + "🙂"; + const text = "x".repeat(1024 * 1024) + "🙂"; const item = limitAgentTimelineItemContent({ type: "tool_call", callId: "large-shell", @@ -15,45 +33,116 @@ describe("agent timeline content", () => { detail: { type: "shell", command: "echo large", output: text }, error: failed ? { content: text } : null, }); - expect(item).toEqual({ - type: "tool_call", + expect(item).toMatchObject({ callId: "large-shell", name: "Bash", - status: failed ? "failed" : "completed", - detail: { type: "shell", command: "echo large", output: text.slice(0, 64 * 1024) }, - error: failed ? { content: text.slice(0, 64 * 1024) } : null, + detail: { type: "shell", command: "echo large" }, }); + if (item.type !== "tool_call" || item.detail.type !== "shell") throw new Error("shape"); + expect(item.detail.output).toMatch(/^x+…\[truncated \d{3}\.\d KB\]$/); + expect(serializedBytes(item)).toBeLessThanOrEqual(64 * 1024); }, ); - test("marks truncated plain-text tool content within the content budget", () => { - const oversizedInput = "x".repeat(64 * 1024 + 1); - + test("replaces an oversized data URL in an unknown tool result with a marker", () => { + const url = `data:image/jpeg;base64,${"A".repeat(14 * 1024 * 1024)}`; const item = limitAgentTimelineItemContent({ type: "tool_call", - callId: "terminal-session-4242", - name: "terminal", + callId: "screenshot", + name: "node_repl.js", status: "completed", error: null, detail: { - type: "plain_text", - text: oversizedInput, - icon: "square_terminal", + type: "unknown", + input: { index: 1 }, + output: { content: [{ type: "image", url }], note: "captured" }, }, }); - - expect(limitAgentTimelineItemContent(item)).toEqual(item); expect(item).toEqual({ type: "tool_call", - callId: "terminal-session-4242", - name: "terminal", + callId: "screenshot", + name: "node_repl.js", status: "completed", error: null, detail: { - type: "plain_text", - text: "x".repeat(64 * 1024 - "\n\n[Content truncated]".length) + "\n\n[Content truncated]", - icon: "square_terminal", + type: "unknown", + input: { index: 1 }, + output: { content: [{ type: "image", url: "…[truncated 14.0 MB]" }], note: "captured" }, }, }); }); + + test("gives non-tool items a 256 KiB budget", () => { + const text = "a".repeat(10 * 1024 * 1024); + const item = limitAgentTimelineItemContent({ type: "assistant_message", text }); + if (item.type !== "assistant_message") throw new Error("shape"); + expect(item.text).toMatch(/^a+…\[truncated 9\.\d MB\]$/); + expect(item.text.length).toBeGreaterThan(200 * 1024); + expect(serializedBytes(item)).toBeLessThanOrEqual(256 * 1024); + }); + + test("bounds an item whose structure alone exceeds the budget", () => { + const item = limitAgentTimelineItemContent({ + type: "tool_call", + callId: "many", + name: "query", + status: "completed", + error: null, + detail: { type: "unknown", input: null, output: Array.from({ length: 1_000_000 }, () => 1) }, + }); + if (item.type !== "tool_call" || item.detail.type !== "unknown") throw new Error("shape"); + const output = item.detail.output as unknown[]; + expect(output.length).toBeLessThan(1_000_000); + expect(output.every((value) => value === 1)).toBe(true); + expect(serializedBytes(item)).toBeLessThanOrEqual(64 * 1024); + }); + + test("keeps short strings whole and limits idempotently when an item has many strings", () => { + const callId = "3f2b8c1e-9a4d-4e6f-8b2a-1c3d5e7f9a0b"; + const item = limitAgentTimelineItemContent({ + type: "tool_call", + callId, + name: "mcp__search__files", + status: "completed", + error: null, + detail: { + type: "unknown", + input: { query: "useWorkspaceSomethingVeryDescriptive" }, + output: Array.from( + { length: 10_000 }, + (_, index) => `${String(index).padStart(5, "0")}${"p".repeat(28)}`, + ), + }, + }); + if (item.type !== "tool_call" || item.detail.type !== "unknown") throw new Error("shape"); + expect(item.callId).toBe(callId); + expect(item.detail.input).toEqual({ query: "useWorkspaceSomethingVeryDescriptive" }); + const output = item.detail.output as string[]; + expect(output.length).toBeLessThan(10_000); + expect(output.every((path) => path.length === 33)).toBe(true); + expect(serializedBytes(item)).toBeLessThanOrEqual(64 * 1024); + expect(limitAgentTimelineItemContent(item)).toBe(item); + }); + + test("keeps a long typed array valid against the wire schema", () => { + const item = limitAgentTimelineItemContent({ + type: "todo", + items: Array.from({ length: 20_000 }, (_, index) => ({ + text: `Task ${index}`, + completed: false, + })), + }); + if (item.type !== "todo") throw new Error("shape"); + expect(item.items.length).toBeLessThan(20_000); + expect(AgentTimelineItemPayloadSchema.safeParse(item).success).toBe(true); + expect(serializedBytes(item)).toBeLessThanOrEqual(256 * 1024); + }); + + test("is stable on an already-limited item", () => { + const item = limitAgentTimelineItemContent({ + type: "reasoning", + text: "r".repeat(1024 * 1024), + }); + expect(limitAgentTimelineItemContent(item)).toBe(item); + }); }); diff --git a/packages/server/src/server/agent/agent-timeline-content.ts b/packages/server/src/server/agent/agent-timeline-content.ts index 003239b283..5117073e14 100644 --- a/packages/server/src/server/agent/agent-timeline-content.ts +++ b/packages/server/src/server/agent/agent-timeline-content.ts @@ -1,9 +1,19 @@ import type { AgentTimelineItem } from "./agent-sdk-types.js"; import type { JsonValue } from "@getpaseo/protocol/agent-types"; -const TOOL_CALL_CONTENT_MAX_LENGTH = 64 * 1024; export const PLUGIN_TIMELINE_DATA_MAX_BYTES = 64 * 1024; +// One timeline fetch sends its entries in one WebSocket message, so every item must stay small. +// Budgets count UTF-16 units plus a fixed cost per node; neither is exact JSON bytes. They bound +// long strings and long arrays, not wide objects (every entry is kept) or multi-byte text. +const TOOL_CALL_BUDGET = 64 * 1024; +const ITEM_BUDGET = 256 * 1024; +const NODE_COST = 8; +const MARKER_COST = 32; +// Ids, names, paths and queries stay whole, so an item keeps its identity across passes. +const SHORT_STRING = 1024; +const MAX_DEPTH = 64; + export function assertPluginTimelineDataSize(data: JsonValue): void { const serializedBytes = Buffer.byteLength(JSON.stringify(data), "utf8"); if (serializedBytes > PLUGIN_TIMELINE_DATA_MAX_BYTES) { @@ -17,66 +27,119 @@ function retainTextPrefix(text: string, length: number): string { return Buffer.from(text.slice(0, length), "utf16le").toString("utf16le"); } -function limitFailedShellError(item: AgentTimelineItem): AgentTimelineItem { - if ( - item.type !== "tool_call" || - item.detail.type !== "shell" || - item.status !== "failed" || - typeof item.error !== "object" || - item.error === null || - !("content" in item.error) || - typeof item.error.content !== "string" || - item.error.content.length <= TOOL_CALL_CONTENT_MAX_LENGTH - ) { - return item; - } - return { - ...item, - error: { - ...item.error, - content: retainTextPrefix(item.error.content, TOOL_CALL_CONTENT_MAX_LENGTH), - }, - }; +function formatSize(units: number): string { + if (units < 1024) return `${units} B`; + if (units < 1024 * 1024) return `${(units / 1024).toFixed(1)} KB`; + return `${(units / (1024 * 1024)).toFixed(1)} MB`; } -function limitPlainText(item: AgentTimelineItem): AgentTimelineItem { - if ( - item.type !== "tool_call" || - item.detail.type !== "plain_text" || - typeof item.detail.text !== "string" || - item.detail.text.length <= TOOL_CALL_CONTENT_MAX_LENGTH - ) { - return item; - } - const notice = "\n\n[Content truncated]"; - return { - ...item, - detail: { - ...item.detail, - text: - retainTextPrefix(item.detail.text, TOOL_CALL_CONTENT_MAX_LENGTH - notice.length) + notice, - }, - }; +function truncatedMarker(units: number): string { + return `…[truncated ${formatSize(units)}]`; } +interface ItemSize { + nodeCost: number; + stringLengths: number[]; + tooDeep: boolean; +} + +function measure(value: unknown, depth: number, size: ItemSize): void { + size.nodeCost += NODE_COST; + if (depth > MAX_DEPTH) { + size.tooDeep = true; + } else if (typeof value === "string") { + size.stringLengths.push(value.length); + } else if (Array.isArray(value)) { + for (const element of value) measure(element, depth + 1, size); + } else if (typeof value === "object" && value !== null) { + for (const [key, child] of Object.entries(value)) { + size.nodeCost += key.length; + measure(child, depth + 1, size); + } + } +} + +/** The largest per-string length that keeps all strings, once cut, within `available`. */ +function findStringCap(lengths: readonly number[], available: number): number { + let low = 0; + let high = 0; + for (const length of lengths) high = Math.max(high, length); + while (low < high) { + const cap = Math.ceil((low + high) / 2); + let total = 0; + for (const length of lengths) total += Math.min(length, cap); + if (total <= available) low = cap; + else high = cap - 1; + } + return low; +} + +interface CutState { + stringCap: number; + remaining: number; +} + +function cutString(text: string, cap: number): string { + if (text.length <= cap) return text; + // A partial data URL is useless to every reader, so drop it whole. + if (text.startsWith("data:")) return truncatedMarker(text.length); + return retainTextPrefix(text, cap) + truncatedMarker(text.length - cap); +} + +function cut(value: unknown, depth: number, state: CutState): unknown { + state.remaining -= NODE_COST; + if (depth > MAX_DEPTH) return "…[truncated]"; + if (typeof value === "string") { + const text = cutString(value, state.stringCap); + state.remaining -= text.length; + return text; + } + if (Array.isArray(value)) { + let changed = false; + const output: unknown[] = []; + for (const element of value) { + const remainingBefore = state.remaining; + const next = cut(element, depth + 1, state); + if (state.remaining < 0) { + // Drop this and later elements. A marker element would break typed arrays. + state.remaining = remainingBefore; + changed = true; + break; + } + changed ||= next !== element; + output.push(next); + } + return changed ? output : value; + } + if (typeof value === "object" && value !== null) { + let changed = false; + const output: Record = {}; + for (const [key, child] of Object.entries(value)) { + state.remaining -= key.length; + const next = cut(child, depth + 1, state); + changed ||= next !== child; + output[key] = next; + } + return changed ? output : value; + } + return value; +} + +/** Returns the item itself when it fits its budget; otherwise a copy with its largest strings cut. */ export function limitAgentTimelineItemContent(item: AgentTimelineItem): AgentTimelineItem { - item = limitFailedShellError(item); - item = limitPlainText(item); - if ( - item.type !== "tool_call" || - item.detail.type !== "shell" || - typeof item.detail.output !== "string" - ) { - return item; - } - if (item.detail.output.length <= TOOL_CALL_CONTENT_MAX_LENGTH) { - return item; - } - return { - ...item, - detail: { - ...item.detail, - output: retainTextPrefix(item.detail.output, TOOL_CALL_CONTENT_MAX_LENGTH), - }, - }; + const budget = item.type === "tool_call" ? TOOL_CALL_BUDGET : ITEM_BUDGET; + const size: ItemSize = { nodeCost: 0, stringLengths: [], tooDeep: false }; + measure(item, 0, size); + let stringTotal = 0; + for (const length of size.stringLengths) stringTotal += length; + if (!size.tooDeep && size.nodeCost + stringTotal <= budget) return item; + + // Strings get what structure leaves, but at least half the budget, less a margin for JSON + // escaping. Arrays drop the elements that do not fit, which bounds items whose short strings + // or structure alone are too big. + const markerCost = + MARKER_COST * size.stringLengths.filter((length) => length > SHORT_STRING).length; + const available = (budget * 15) / 16 - Math.min(size.nodeCost, budget / 2) - markerCost; + const stringCap = Math.max(SHORT_STRING, findStringCap(size.stringLengths, available)); + return cut(item, 0, { stringCap, remaining: budget }) as AgentTimelineItem; } diff --git a/packages/server/src/server/agent/agent-timeline-store-types.ts b/packages/server/src/server/agent/agent-timeline-store-types.ts index 639b24a904..9ca1ab37b9 100644 --- a/packages/server/src/server/agent/agent-timeline-store-types.ts +++ b/packages/server/src/server/agent/agent-timeline-store-types.ts @@ -17,6 +17,7 @@ export interface AgentTimelineCursor { export type AgentTimelineFetchDirection = "tail" | "before" | "after"; export interface AgentTimelineFetchOptions { + wholeTurns?: boolean; direction?: AgentTimelineFetchDirection; cursor?: AgentTimelineCursor; /** diff --git a/packages/server/src/server/agent/agent-timeline-store.test.ts b/packages/server/src/server/agent/agent-timeline-store.test.ts index eb46916fe3..9ec4df4d55 100644 --- a/packages/server/src/server/agent/agent-timeline-store.test.ts +++ b/packages/server/src/server/agent/agent-timeline-store.test.ts @@ -1,9 +1,45 @@ +import { execFile } from "node:child_process"; +import { promisify } from "node:util"; +import { fileURLToPath } from "node:url"; import { describe, expect, it } from "vitest"; import { selectReferenceProjectedTimelinePage } from "./test-utils/timeline-page-reference.js"; import type { AgentTimelineItem } from "./agent-sdk-types.js"; import { InMemoryAgentTimelineStore } from "./agent-timeline-store.js"; describe("InMemoryAgentTimelineStore", () => { + it("resets stale forward cursors to complete available turns", () => { + const store = new InMemoryAgentTimelineStore(); + store.initialize("agent", { epoch: "current" }); + for (let index = 0; index < 60; index++) + store.append( + "agent", + { + type: "tool_call", + callId: `call-${index}`, + name: "shell", + status: "completed", + error: null, + detail: { type: "unknown", input: null, output: null }, + }, + { turnId: "run" }, + ); + const page = store.fetch("agent", { + direction: "after", + cursor: { epoch: "old", seq: 10 }, + limit: 40, + wholeTurns: true, + }); + expect(page.rows).toHaveLength(60); + expect(page).toMatchObject({ + reset: true, + staleCursor: true, + startSeq: 1, + endSeq: 60, + hasOlder: false, + hasNewer: false, + }); + }); + it("clamps an overshooting before cursor into the bounded tail window", () => { const store = new InMemoryAgentTimelineStore(); store.initialize("agent-1", { @@ -145,6 +181,20 @@ describe("projected timeline retention", () => { }, ]); }); + + it("serves a merged assistant message within the item budget", () => { + const store = new InMemoryAgentTimelineStore(); + store.initialize("agent", { epoch: "e" }); + const chunk = "a".repeat(200 * 1024); + for (let index = 0; index < 10; index++) { + store.append("agent", { type: "assistant_message", messageId: "m", text: chunk }); + } + const [row] = store.fetch("agent", { limit: 1 }).rows; + expect(row).toMatchObject({ seqStart: 1, seqEnd: 10 }); + expect(row.item).toMatchObject({ type: "assistant_message", messageId: "m" }); + expect(Buffer.byteLength(JSON.stringify(row.item))).toBeLessThanOrEqual(256 * 1024); + expect(store.getLastAssistantMessage("agent")).toHaveLength(10 * chunk.length); + }); }); describe("projected sequence ownership", () => { @@ -217,32 +267,59 @@ it("includes transitive tool updates in a contiguous projected tail", () => { expect(tail).toMatchObject({ startSeq: 1, endSeq: 6, hasOlder: false }); }); -it("serves tail 200 from 100,000 retained rows without stalling the loop", async () => { - const store = new InMemoryAgentTimelineStore(); - store.initialize("large"); - for (let index = 0; index < 100_000; index++) { - store.append("large", { type: "user_message", text: String(index) }); - } - // Generation and its GC are outside the measured request window. - await new Promise((resolve) => setImmediate(resolve)); - const started = performance.now(); - const probe = new Promise((resolve) => - setImmediate(() => resolve(performance.now() - started)), +async function measureTimelineTail(wholeTurns: boolean) { + const fixture = fileURLToPath( + new URL("./test-utils/timeline-responsiveness.ts", import.meta.url), ); - let page = store.fetch("large", { limit: 200 }); - for (let repeat = 1; repeat < 8; repeat++) page = store.fetch("large", { limit: 200 }); - const duration = performance.now() - started; - const loopGap = await probe; - console.info({ duration, loopGap }); - expect(page.rows).toHaveLength(200); - expect(page.startSeq).toBe(99_801); - expect(page.endSeq).toBe(100_000); - // CI runners can pause for scheduling/GC; the local per-request 2 ms gate - // is measured separately. Eight requests amplify the old full-history work. - expect(duration).toBeLessThan(50); - expect(loopGap).toBeLessThan(50); + const { stdout, stderr } = await promisify(execFile)( + process.execPath, + ["--expose-gc", "--import", "tsx", fixture, String(wholeTurns)], + { timeout: 15_000 }, + ); + process.stderr.write(stderr); + return JSON.parse(stdout) as { + result: ReturnType; + blockingMs: number; + }; +} + +it("excludes unrelated test-runner CPU from the timeline fetch budget", async () => { + let unrelatedWork: ReturnType; + const burnCpu = () => { + const threadCpuUsage: (previous?: NodeJS.CpuUsage) => NodeJS.CpuUsage = Reflect.get( + process, + "threadCpuUsage", + ); + const start = threadCpuUsage(); + let elapsed: NodeJS.CpuUsage; + do { + elapsed = threadCpuUsage(start); + } while (elapsed.user + elapsed.system < 80_000); + unrelatedWork = setImmediate(burnCpu); + }; + unrelatedWork = setImmediate(burnCpu); + try { + const { result: tail, blockingMs } = await measureTimelineTail(false); + expect(tail.rows).toHaveLength(200); + expect(tail.startSeq).toBe(99_801); + expect(tail.endSeq).toBe(100_000); + expect(blockingMs).toBeLessThan(50); + } finally { + clearImmediate(unrelatedWork); + } }); +it.each([false, true])( + "serves tail 200 from 100,000 retained rows without stalling the loop (wholeTurns=%s)", + async (wholeTurns) => { + const { result: tail, blockingMs } = await measureTimelineTail(wholeTurns); + expect(tail.rows).toHaveLength(200); + expect(tail.startSeq).toBe(99_801); + expect(tail.endSeq).toBe(100_000); + expect(blockingMs).toBeLessThan(50); + }, +); + it("matches the previous reprojecting selector on seeded randomized timelines", () => { let seed = 0x76aabbcc; const random = (bound: number) => { diff --git a/packages/server/src/server/agent/agent-timeline-store.ts b/packages/server/src/server/agent/agent-timeline-store.ts index b9727e33e9..4c3b9c5c3a 100644 --- a/packages/server/src/server/agent/agent-timeline-store.ts +++ b/packages/server/src/server/agent/agent-timeline-store.ts @@ -1,5 +1,6 @@ import { randomUUID } from "node:crypto"; import { TimelineProjection, type ProjectedTimelineRow } from "./timeline-projection.js"; +import { limitAgentTimelineItemContent } from "./agent-timeline-content.js"; import type { AgentTimelineItem } from "./agent-sdk-types.js"; import type { AgentTimelineFetchOptions, @@ -107,6 +108,7 @@ export class InMemoryAgentTimelineStore { direction: reset ? "tail" : direction, cursorSeq: cursor?.seq, limit: options?.limit ?? DEFAULT_TIMELINE_FETCH_LIMIT, + wholeTurns: options?.wholeTurns, }); return { epoch: state.epoch, @@ -119,7 +121,12 @@ export class InMemoryAgentTimelineStore { hasNewer: page.hasNewer, startSeq: page.startSeq, endSeq: page.endSeq, - rows: page.entries.map((entry) => Object.assign({ seq: entry.seqEnd }, entry)), + // Stored rows are already within budget; this bounds assistant and reasoning merges. + rows: page.entries.map((entry) => + Object.assign({ seq: entry.seqEnd }, entry, { + item: limitAgentTimelineItemContent(entry.item), + }), + ), }; } diff --git a/packages/server/src/server/agent/finish-subscriptions/internal/observation.ts b/packages/server/src/server/agent/finish-subscriptions/internal/observation.ts index 887a4ba075..7abe483cf4 100644 --- a/packages/server/src/server/agent/finish-subscriptions/internal/observation.ts +++ b/packages/server/src/server/agent/finish-subscriptions/internal/observation.ts @@ -13,6 +13,8 @@ import type { FinishObservation } from "../index.js"; export function createFinishObservation(input: { agentManager: AgentManager; agentStorage: AgentStorage; + /** A child chosen for restart recovery reports its state only after its resume was sent. */ + waitForResume(agentId: string, signal: AbortSignal): Promise; messages(): AgentMessageDelivery; hosts(): ToolHosts; serverId: string; @@ -24,6 +26,7 @@ export function createFinishObservation(input: { hosts: input.hosts, local: { async wait(agentId, signal) { + await input.waitForResume(agentId, signal); await input.messages().waitForDispatch(agentId, signal); signal.throwIfAborted(); const live = agentManager.getAgent(agentId); @@ -52,6 +55,7 @@ export function createFinishObservation(input: { }; }, async observe(agentId, handler, signal, onError) { + await input.waitForResume(agentId, signal); const stored = await agentStorage.get(agentId); let updates = Promise.resolve(); const publish = (snapshot: AgentSnapshotPayload | null, event?: AgentStreamEvent) => { diff --git a/packages/server/src/server/agent/mcp-server.test.ts b/packages/server/src/server/agent/mcp-server.test.ts index f2c7da8574..ecf2d912a5 100644 --- a/packages/server/src/server/agent/mcp-server.test.ts +++ b/packages/server/src/server/agent/mcp-server.test.ts @@ -76,7 +76,7 @@ import type { GeneratedWorkspaceName } from "../worktree-branch-name-generator.j import type { ForgeService } from "../../services/forge-service.js"; import { areEquivalentPaths } from "../../utils/path.js"; import { createTerminalManager, type TerminalManager } from "../../terminal/terminal-manager.js"; -import { createWorkerTerminalManager } from "../../terminal/worker-terminal-manager.js"; +import { startWorkerTerminalManager } from "../../terminal/worker-terminal-manager.js"; import { PARENT_AGENT_ID_LABEL } from "@getpaseo/protocol/agent-labels"; import { PASEO_TOOL_NAMES } from "@getpaseo/protocol/paseo-tool-presentation/index"; import { MutableDaemonConfigSchema, type AgentProfile } from "@getpaseo/protocol/messages"; @@ -881,6 +881,7 @@ async function createAgentMcpServer( logger: options.logger, ...createFinishObservation({ ...options, + waitForResume: async () => {}, messages: () => messages, serverId: options.serverId ?? "self", hosts: () => { @@ -1384,13 +1385,24 @@ describe("terminal MCP tools", () => { ); it.each([ - ["in-process", createTerminalManager], - ["worker", createWorkerTerminalManager], + ["in-process", async () => ({ manager: createTerminalManager(), home: null })], + [ + "worker", + async () => { + const home = await mkdtemp(join(tmpdir(), "mcp-terminal-keys-home-")); + const manager = await startWorkerTerminalManager({ + paseoHome: home, + paseoVersion: "0.0.0-test", + logger, + }); + return { manager, home }; + }, + ], ] as const)( "delivers MCP key tokens through %s after terminal input modes change", async (_name, createManager) => { const { agentManager, agentStorage } = createTestDeps(); - const terminalManager = createManager(); + const { manager: terminalManager, home } = await createManager(); const terminal = await terminalManager.createTerminal({ cwd: process.cwd(), workspaceId: "ws-terminal-keys", @@ -1420,15 +1432,15 @@ describe("terminal MCP tools", () => { logger, }); + // Every step is a round trip through a real PTY. A loaded Windows runner (ConPTY) has + // taken over 3 s to reach READY, so each step gets the same window rather than 1 s. + const roundTrip = { timeout: 5000 }; let output = ""; const unsubscribe = terminal.subscribe((message) => { if (message.type === "output") { output += message.data; } }); - // Every key travels through the PTY and back; on loaded Windows runners one round - // trip can take seconds, so each wait gets the same budget as the first. - const roundTrip = { timeout: 5000 }; try { await vi.waitFor(async () => { const capture = await terminalManager.captureTerminal(terminal.id); @@ -1465,6 +1477,7 @@ describe("terminal MCP tools", () => { await server.close(); await terminalManager.killTerminalAndWait(terminal.id); terminalManager.killAll(); + if (home) await rm(home, { recursive: true, force: true }); } }, ); @@ -1480,7 +1493,6 @@ describe("terminal MCP tools", () => { id: "term-1", name: "daemon", cwd: process.cwd(), - getState: vi.fn().mockReturnValue({ scrollback: [], grid: [[]] }), }), captureTerminal, }); diff --git a/packages/server/src/server/agent/plugin-provider.test.ts b/packages/server/src/server/agent/plugin-provider.test.ts index 72bc0f475b..a9cf3b0ed5 100644 --- a/packages/server/src/server/agent/plugin-provider.test.ts +++ b/packages/server/src/server/agent/plugin-provider.test.ts @@ -4,6 +4,8 @@ import { join } from "node:path"; import { AgentStorage } from "./agent-storage.js"; import { createIdleRuntimeCleanup } from "./idle-runtime-cleanup/index.js"; import { relative } from "node:path"; +import { execFileSync } from "node:child_process"; +import { fileURLToPath } from "node:url"; import type { ProviderConnection, ProviderLaunch, @@ -25,6 +27,21 @@ import { StaleProviderSessionError, } from "./stale-provider-session-error.js"; +test("long concurrent plugin and child streams retain text-sized history and release it on archive", () => { + const fixture = fileURLToPath(new URL("./test-utils/plugin-stream-memory.ts", import.meta.url)); + const output = execFileSync( + process.execPath, + ["--expose-gc", "--max-old-space-size=512", "--import", "tsx", fixture], + { + encoding: "utf8", + timeout: 20_000, + }, + ); + const memory = JSON.parse(output) as { retained: number; closed: number }; + expect(memory.retained).toBeLessThan(24 * 1024 * 1024); + expect(memory.closed).toBeLessThan(6 * 1024 * 1024); +}); + const CAPABILITIES = [ "prompt.message", "session.configure", @@ -36,6 +53,7 @@ const CAPABILITIES = [ interface ProviderHarnessOptions { capabilities?: ProviderConnection["capabilities"]; completeTurn?: boolean; + closeAcknowledgementOnly?: boolean; openChildren?: (rootSessionId: string, emit: (event: ProviderEvent) => void) => void; handleInput?: (input: ProviderInput, emit: (event: ProviderEvent) => void) => Promise; } @@ -191,6 +209,7 @@ function createProviderHarness(options: ProviderHarnessOptions = {}) { } if (input.type === "session.close") { emit({ type: "session.closed", sessionId: input.sessionId }); + if (options.closeAcknowledgementOnly) return; } if ("requestId" in input) { emit({ type: "request.completed", requestId: input.requestId }); @@ -229,6 +248,572 @@ function eventsOfType(events: AgentStreamEvent[], type: AgentStreamEvent["type"] return events.filter((event) => event.type === type); } +function createRewindProviderHarness( + options: { + reuseAnswerId?: boolean; + forkOnRevert?: boolean; + handleInput?: ProviderHarnessOptions["handleInput"]; + } = {}, +) { + const nativeMessages: string[] = []; + let originalMessages: string[] | null = null; + const harness = createProviderHarness({ + closeAcknowledgementOnly: true, + capabilities: [ + ...CAPABILITIES, + "session.revert.conversation", + "session.revert.files", + "session.revert.both", + ], + async handleInput(input, emit) { + if (await options.handleInput?.(input, emit)) return true; + if (input.type === "session.open" && input.history === "replay") { + emit({ + type: "session.opened", + requestId: input.requestId, + sessionId: input.sessionId, + capabilities: [ + ...CAPABILITIES, + "session.revert.conversation", + "session.revert.files", + "session.revert.both", + ], + restoration: "core", + persistence: input.persistence ?? { version: 1, data: { token: "root" } }, + cwd: input.config.cwd, + }); + const messages = + options.forkOnRevert && + (input.persistence?.data as { token?: string })?.token === "root" && + originalMessages + ? originalMessages + : nativeMessages; + for (const [index, text] of messages.entries()) { + emit({ + type: "timeline.item", + sessionId: input.sessionId, + item: { type: "user_message", id: `user-${text}`, text, revertToken: text }, + }); + emit({ + type: "timeline.item", + sessionId: input.sessionId, + item: { + type: "assistant_message", + id: options.reuseAnswerId ? `answer-${index + 1}` : `answer-${text}`, + text: `Reply ${text}`, + }, + }); + } + emit({ type: "session.ready", requestId: input.requestId, sessionId: input.sessionId }); + return true; + } + if (input.type === "session.prompt") { + if (input.prompt.input.type !== "message") throw new Error("Expected a message"); + const text = input.prompt.input.content + .flatMap((part) => (part.type === "text" ? [part.text] : [])) + .join(""); + nativeMessages.push(text); + const turnId = `turn-${text}`; + emit({ + type: "session.prompt_result", + sessionId: input.sessionId, + clientMessageId: input.prompt.clientMessageId, + result: { type: "turn", turnId }, + }); + emit({ type: "session.turn", sessionId: input.sessionId, turnId, state: "started" }); + emit({ + type: "timeline.item", + sessionId: input.sessionId, + item: { + type: "user_message", + id: `user-${text}`, + text, + clientMessageId: input.prompt.clientMessageId, + revertToken: text, + }, + }); + emit({ + type: "timeline.item", + sessionId: input.sessionId, + item: { + type: "assistant_message", + id: options.reuseAnswerId ? `answer-${nativeMessages.length}` : `answer-${text}`, + text: `Reply ${text}`, + }, + }); + emit({ type: "session.turn", sessionId: input.sessionId, turnId, state: "completed" }); + return true; + } + if (input.type === "session.revert") { + if (options.forkOnRevert && input.scope !== "files") { + originalMessages = [...nativeMessages]; + emit({ + type: "session.persistence", + sessionId: input.sessionId, + persistence: { version: 1, data: { token: "fork" } }, + }); + } + if (input.scope !== "files") + nativeMessages.splice(nativeMessages.indexOf(String(input.token))); + emit({ type: "request.completed", requestId: input.requestId }); + return true; + } + return false; + }, + }); + return { ...harness, nativeMessages }; +} + +async function withRewindAgent( + run: (context: { + manager: AgentManager; + agentId: string; + nativeMessages: string[]; + messages: () => string[]; + }) => Promise, + options: Parameters[0] = {}, +) { + const harness = createRewindProviderHarness(options); + const logger = createTestLogger(); + const registry = new PluginAgentClientRegistry(logger); + registry.replace([harness.registration]); + const manager = new AgentManager({ + logger, + clients: registry.clients(), + providerDefinitions: registry.definitions(), + }); + const agent = await manager.createAgent( + { provider: harness.registration.id, cwd: tmpdir() }, + undefined, + { workspaceId: undefined }, + ); + const messages = () => + manager + .getTimeline(agent.id) + .flatMap((item) => + item.type === "user_message" || item.type === "assistant_message" ? [item.text] : [], + ); + try { + await manager.runAgent(agent.id, "A", { clientMessageId: "client-A" }); + await manager.runAgent(agent.id, "B", { clientMessageId: "client-B" }); + await manager.runAgent(agent.id, "C", { clientMessageId: "client-C" }); + expect(messages()).toEqual(["A", "Reply A", "B", "Reply B", "C", "Reply C"]); + await run({ manager, agentId: agent.id, nativeMessages: harness.nativeMessages, messages }); + } finally { + await manager.closeAgent(agent.id); + await registry.shutdown(); + } +} + +test("conversation rewind discards withdrawn plugin turns before and after a replacement prompt", async () => { + await withRewindAgent(async ({ manager, agentId, nativeMessages, messages }) => { + await manager.rewind(agentId, "user-B", "conversation"); + const afterRewind = messages(); + expect(nativeMessages).toEqual(["A"]); + await manager.runAgent(agentId, "D", { clientMessageId: "client-D" }); + const afterReplacement = messages(); + expect(nativeMessages).toEqual(["A", "D"]); + expect({ afterRewind, afterReplacement }).toEqual({ + afterRewind: ["A", "Reply A"], + afterReplacement: ["A", "Reply A", "D", "Reply D"], + }); + }); +}); + +test("file-only plugin rewind preserves the conversation before and after a replacement prompt", async () => { + await withRewindAgent(async ({ manager, agentId, nativeMessages, messages }) => { + await manager.rewind(agentId, "user-B", "files"); + expect(nativeMessages).toEqual(["A", "B", "C"]); + expect(messages()).toEqual(["A", "Reply A", "B", "Reply B", "C", "Reply C"]); + await manager.runAgent(agentId, "D", { clientMessageId: "client-D" }); + expect(messages()).toEqual(["A", "Reply A", "B", "Reply B", "C", "Reply C", "D", "Reply D"]); + }); +}); + +test("plugin rewind restores translation state when a replacement reuses a discarded item id", async () => { + const harness = createRewindProviderHarness({ reuseAnswerId: true }); + const registry = new PluginAgentClientRegistry(createTestLogger()); + registry.replace([harness.registration]); + const client = registry.clients()[harness.registration.id]!; + const session = await client.createSession({ provider: harness.registration.id, cwd: tmpdir() }); + const live: AgentStreamEvent[] = []; + try { + await session.run("A"); + await session.run("B"); + session.subscribe((event) => live.push(event)); + await session.revertConversation!({ messageId: "user-B" }); + live.length = 0; + await session.run("B revised"); + const assistant = live.flatMap((event) => + event.type === "timeline" && event.item.type === "assistant_message" ? [event.item.text] : [], + ); + expect(harness.nativeMessages).toEqual(["A", "B revised"]); + expect(assistant).toEqual(["Reply B revised"]); + } finally { + await session.close(); + await registry.shutdown(); + } +}); + +async function withPluginRewindSession( + options: Parameters[0], + run: ( + session: Awaited>, + harness: ReturnType, + ) => Promise, +) { + const harness = createRewindProviderHarness(options); + const registry = new PluginAgentClientRegistry(createTestLogger()); + registry.replace([harness.registration]); + const client = registry.clients()[harness.registration.id]!; + const session = await client.createSession({ provider: harness.registration.id, cwd: tmpdir() }); + try { + await session.run("A"); + await session.run("B"); + await session.run("C"); + await run(session, harness); + } finally { + await session.close(); + await registry.shutdown(); + } +} + +async function pluginMessages(session: Awaited>) { + const events = await Array.fromAsync(session.streamHistory()); + return events.flatMap((event) => + event.type === "timeline" && + (event.item.type === "user_message" || event.item.type === "assistant_message") + ? [event.item.text] + : [], + ); +} + +test("combined plugin rewind replays the retained native branch", async () => { + await withPluginRewindSession({}, async (session) => { + await session.revertBoth!({ messageId: "user-B" }); + expect(await pluginMessages(session)).toEqual(["A", "Reply A"]); + await session.revertConversation!({ messageId: "user-A" }); + expect(await pluginMessages(session)).toEqual([]); + }); +}); + +test("plugin rewind resumes the latest persistence rather than the original handle", async () => { + await withPluginRewindSession( + { + handleInput: async (input, emit) => { + if (input.type === "session.revert") + emit({ + type: "session.persistence", + sessionId: input.sessionId, + persistence: { version: 1, data: { token: "fork" } }, + }); + return false; + }, + }, + async (session, harness) => { + await session.revertConversation!({ messageId: "user-B" }); + expect(harness.inputs.findLast((input) => input.type === "session.open")).toMatchObject({ + persistence: { version: 1, data: { token: "fork" } }, + history: "replay", + }); + expect(await pluginMessages(session)).toEqual(["A", "Reply A"]); + }, + ); +}); + +test("failed native plugin rewind preserves history and does not reopen", async () => { + await withPluginRewindSession( + { + handleInput: async (input, emit) => { + if (input.type !== "session.revert") return false; + emit({ + type: "request.failed", + requestId: input.requestId, + error: { message: "native rewind failed" }, + }); + return true; + }, + }, + async (session, harness) => { + await expect(session.revertConversation!({ messageId: "user-B" })).rejects.toThrow( + "native rewind failed", + ); + expect(await pluginMessages(session)).toEqual([ + "A", + "Reply A", + "B", + "Reply B", + "C", + "Reply C", + ]); + expect(harness.inputs.filter((input) => input.type === "session.open")).toHaveLength(1); + }, + ); +}); + +test("failed plugin rewind replay blocks prompts until retry without repeating native rewind", async () => { + let failReplay = true; + await withPluginRewindSession( + { + handleInput: async (input, emit) => { + if (input.type !== "session.open" || input.history !== "replay" || !failReplay) + return false; + failReplay = false; + emit({ + type: "request.failed", + requestId: input.requestId, + error: { message: "replay failed" }, + }); + return true; + }, + }, + async (session, harness) => { + await expect(session.revertConversation!({ messageId: "user-B" })).rejects.toThrow( + "replay failed", + ); + await expect(session.run("D")).rejects.toThrow("Retry the rewind or reload"); + await session.revertConversation!({ messageId: "user-B" }); + await session.run("D"); + expect(await pluginMessages(session)).toEqual(["A", "Reply A", "D", "Reply D"]); + expect(harness.inputs.filter((input) => input.type === "session.revert")).toHaveLength(1); + }, + ); +}); + +test("retrying a failed plugin rewind replay replaces the manager timeline before prompting", async () => { + let failReplay = true; + await withRewindAgent( + async ({ manager, agentId, messages }) => { + await expect(manager.rewind(agentId, "user-B", "conversation")).rejects.toThrow( + "replay failed", + ); + await expect(manager.runAgent(agentId, "D")).rejects.toThrow("Retry the rewind or reload"); + await manager.rewind(agentId, "user-B", "conversation"); + expect(messages()).toEqual(["A", "Reply A"]); + await manager.runAgent(agentId, "D"); + expect(messages()).toEqual(["A", "Reply A", "D", "Reply D"]); + }, + { + handleInput: async (input, emit) => { + if (input.type !== "session.open" || input.history !== "replay" || !failReplay) + return false; + failReplay = false; + emit({ + type: "request.failed", + requestId: input.requestId, + error: { message: "replay failed" }, + }); + return true; + }, + }, + ); +}); + +test("reload after failed plugin rewind replay resumes the committed fork", async () => { + let failReplay = true; + await withRewindAgent( + async ({ manager, agentId, messages }) => { + await expect(manager.rewind(agentId, "user-B", "conversation")).rejects.toThrow( + "replay failed", + ); + await manager.reloadAgentSession(agentId, undefined, { rehydrateFromDisk: true }); + await manager.hydrateTimelineFromProvider(agentId, { force: true }); + expect(messages()).toEqual(["A", "Reply A"]); + }, + { + forkOnRevert: true, + handleInput: async (input, emit) => { + if (input.type === "session.close") { + emit({ type: "request.completed", requestId: input.requestId }); + return true; + } + if (input.type !== "session.open" || input.history !== "replay" || !failReplay) + return false; + failReplay = false; + emit({ + type: "request.failed", + requestId: input.requestId, + error: { message: "replay failed" }, + }); + return true; + }, + }, + ); +}); + +test("closing during plugin rewind replay closes each native binding once", async () => { + let opened!: () => void; + let release!: () => void; + const replayStarted = new Promise((resolve) => { + opened = resolve; + }); + const replayAllowed = new Promise((resolve) => { + release = resolve; + }); + await withPluginRewindSession( + { + handleInput: async (input) => { + if (input.type === "session.open" && input.history === "replay") { + opened(); + await replayAllowed; + } + return false; + }, + }, + async (session, harness) => { + const rewind = session.revertConversation!({ messageId: "user-B" }); + await replayStarted; + const closing = session.close(); + release(); + await Promise.all([rewind, closing]); + const closes = harness.inputs.flatMap((input) => + input.type === "session.close" ? [input.sessionId] : [], + ); + expect(closes).toHaveLength(2); + expect(new Set(closes).size).toBe(2); + }, + ); +}); + +test("plugin rewind retries a failed close before reopening the native writer", async () => { + let failClose = true; + await withPluginRewindSession( + { + handleInput: async (input, emit) => { + if (input.type !== "session.close" || !failClose) return false; + failClose = false; + emit({ + type: "request.failed", + requestId: input.requestId, + error: { message: "close failed" }, + }); + return true; + }, + }, + async (session, harness) => { + await expect(session.revertConversation!({ messageId: "user-B" })).rejects.toThrow( + "close failed", + ); + expect(harness.inputs.filter((input) => input.type === "session.open")).toHaveLength(1); + expect(await pluginMessages(session)).toEqual(["A", "Reply A"]); + expect(harness.inputs.filter((input) => input.type === "session.revert")).toHaveLength(1); + }, + ); +}); + +test("plugin rewind retries permission settlement before retiring its session", async () => { + let failPermission = true; + await withPluginRewindSession( + { + handleInput: async (input) => { + if (input.type !== "session.permission" || !failPermission) return false; + failPermission = false; + throw new Error("permission delivery failed"); + }, + }, + async (session, harness) => { + const opened = harness.inputs.find((input) => input.type === "session.open")!; + if (opened.type !== "session.open") throw new Error("Missing root"); + harness.emit({ + type: "session.permission", + sessionId: opened.sessionId, + request: { id: "pending", name: "tool", kind: "tool" }, + }); + await expect(session.revertConversation!({ messageId: "user-B" })).rejects.toThrow( + "permission delivery failed", + ); + expect(session.getPendingPermissions()).toHaveLength(1); + expect(harness.inputs.filter((input) => input.type === "session.close")).toHaveLength(0); + expect(await pluginMessages(session)).toEqual(["A", "Reply A"]); + expect(session.getPendingPermissions()).toEqual([]); + expect(harness.inputs.filter((input) => input.type === "session.permission")).toHaveLength(2); + }, + ); +}); + +test("plugin rewind replaces child listeners and settles old pending permissions", async () => { + await withPluginRewindSession({}, async (session, harness) => { + const root = harness.inputs.find((input) => input.type === "session.open")!; + if (root.type !== "session.open") throw new Error("Missing root"); + harness.emit({ + type: "session.permission", + sessionId: root.sessionId, + request: { id: "old-permission", name: "tool", kind: "tool", title: "Run tool" }, + }); + expect(session.getPendingPermissions()).toHaveLength(1); + await session.revertConversation!({ messageId: "user-B" }); + expect(session.getPendingPermissions()).toEqual([]); + expect(harness.inputs).toContainEqual( + expect.objectContaining({ + type: "session.permission", + permissionId: "old-permission", + response: { behavior: "deny", message: "Session replaced after rewind" }, + }), + ); + harness.emit({ + type: "timeline.item", + sessionId: "child-1", + item: { type: "assistant_message", id: "child-message", text: "Discarded child update" }, + }); + const history = await Array.fromAsync(session.streamHistory()); + expect(history.filter((event) => event.type === "provider_subagent")).toEqual([]); + const reopened = harness.inputs.findLast((input) => input.type === "session.open")!; + if (reopened.type !== "session.open") throw new Error("Missing reopened root"); + harness.emit({ + type: "session.opened", + sessionId: "child-1", + parentSessionId: reopened.sessionId, + capabilities: [], + restoration: "parent", + cwd: tmpdir(), + }); + harness.emit({ + type: "timeline.item", + sessionId: "child-1", + item: { type: "assistant_message", id: "child-message", text: "New child reply" }, + }); + const next = await Array.fromAsync(session.streamHistory()); + expect(next).toContainEqual( + expect.objectContaining({ + type: "provider_subagent", + event: expect.objectContaining({ + type: "timeline", + item: expect.objectContaining({ text: "New child reply" }), + }), + }), + ); + }); +}); + +test("nonpersisted plugin sessions reject conversation rewind before native mutation", async () => { + await withPluginRewindSession( + { + handleInput: async (input, emit) => { + if (input.type !== "session.open") return false; + emit({ + type: "session.opened", + requestId: input.requestId, + sessionId: input.sessionId, + capabilities: [...CAPABILITIES, "session.revert.conversation", "session.revert.files"], + restoration: "core", + cwd: input.config.cwd, + }); + emit({ type: "session.ready", requestId: input.requestId, sessionId: input.sessionId }); + return true; + }, + }, + async (session, harness) => { + expect(session.capabilities.supportsRewindConversation).toBe(false); + await expect(session.revertConversation!({ messageId: "user-B" })).rejects.toThrow( + "requires session persistence", + ); + expect(harness.inputs.filter((input) => input.type === "session.revert")).toEqual([]); + await session.revertFiles!({ messageId: "user-B" }); + expect(harness.nativeMessages).toEqual(["A", "B", "C"]); + }, + ); +}); + function openNestedChildren(rootSessionId: string, emit: (event: ProviderEvent) => void) { for (const [sessionId, parentSessionId] of [ ["a", rootSessionId], @@ -292,6 +877,99 @@ function expectNestedChildren(events: AgentStreamEvent[]) { } describe("PluginAgentClientRegistry", () => { + test("history keeps the tool's first position when completion follows later text", async () => { + const harness = createProviderHarness(); + const registry = new PluginAgentClientRegistry(createTestLogger()); + registry.replace([harness.registration]); + const client = registry.clients()[harness.registration.id]!; + const session = await client.createSession({ provider: client.provider, cwd: "/tmp" }); + const opened = harness.inputs.find((input) => input.type === "session.open"); + if (opened?.type !== "session.open") throw new Error("missing session open"); + const tool = { + type: "tool_call" as const, + id: "tool-position", + callId: "call-position", + name: "read", + detail: { type: "unknown" as const, input: null, output: null }, + error: null, + }; + try { + harness.emit({ + type: "timeline.item", + sessionId: opened.sessionId, + item: { ...tool, status: "running" }, + }); + harness.emit({ + type: "timeline.item", + sessionId: opened.sessionId, + item: { type: "assistant_message", id: "later-text", text: "Working" }, + }); + harness.emit({ + type: "timeline.item", + sessionId: opened.sessionId, + item: { ...tool, status: "completed" }, + }); + const items = []; + for await (const event of session.streamHistory()) + if (event.type === "timeline") items.push(event.item); + expect(items).toEqual([ + { + type: "tool_call", + callId: "call-position", + name: "read", + detail: tool.detail, + error: null, + status: "completed", + }, + { type: "assistant_message", messageId: "later-text", text: "Working" }, + ]); + } finally { + await session.close(); + await registry.shutdown(); + } + }); + + test("detached text deltas preserve split surrogates and history replays one complete message", async () => { + const harness = createProviderHarness(); + const registry = new PluginAgentClientRegistry(createTestLogger()); + registry.replace([harness.registration]); + const client = registry.clients()[harness.registration.id]!; + const session = await client.createSession({ provider: client.provider, cwd: "/tmp" }); + const opened = harness.inputs.find((input) => input.type === "session.open"); + if (opened?.type !== "session.open") throw new Error("missing session open"); + const events: AgentStreamEvent[] = []; + session.subscribe((event) => events.push(event)); + const prefix = "long prefix ".repeat(10); + const first = prefix + "a\uD83D"; + const complete = first + "\uDE00b"; + try { + for (const text of [first, complete, complete]) { + harness.emit({ + type: "timeline.item", + sessionId: opened.sessionId, + item: { type: "assistant_message", id: "split-message", text }, + }); + } + const deltas = events.flatMap((event) => + event.type === "timeline" && event.item.type === "assistant_message" + ? [event.item.text] + : [], + ); + expect(deltas).toEqual([first, "\uDE00b"]); + expect(deltas.join("")).toBe(prefix + "a😀b"); + const history: AgentStreamEvent[] = []; + for await (const event of session.streamHistory()) history.push(event); + expect( + history.flatMap((event) => + event.type === "timeline" && event.item.type === "assistant_message" ? [event.item] : [], + ), + ).toEqual([{ type: "assistant_message", messageId: "split-message", text: complete }]); + } finally { + await session.close(); + await registry.shutdown(); + } + }); + test("stores only agent options while the plugin receives merged defaults", async () => { const logger = createTestLogger(); const harness = createProviderHarness(); @@ -486,6 +1164,137 @@ describe("PluginAgentClientRegistry", () => { } }); + test.each(["completed", "canceled", "failed"] as const)( + "reports a reused plugin child as running until its next turn is %s", + async (outcome) => { + const logger = createTestLogger(); + const harness = createProviderHarness(); + const plugins = new PluginAgentClientRegistry(logger); + plugins.replace([harness.registration]); + const registry = buildProviderRegistry(logger, { pluginProviders: plugins.definitions() }); + const manager = new AgentManager({ + logger, + clients: { "plugin-direct": registry["plugin-direct"].createClient(logger) }, + providerDefinitions: { "plugin-direct": registry["plugin-direct"] }, + }); + try { + const agent = await manager.createAgent( + { provider: "plugin-direct", cwd: tmpdir() }, + undefined, + { workspaceId: undefined }, + ); + const open = harness.inputs.find((input) => input.type === "session.open")!; + harness.emit({ + type: "session.opened", + sessionId: "reusable-child", + parentSessionId: open.sessionId, + capabilities: [], + restoration: "parent", + title: "Plugin child", + cwd: tmpdir(), + }); + harness.emit({ + type: "session.turn", + sessionId: "reusable-child", + turnId: "first-turn", + state: "started", + }); + harness.emit({ + type: "session.turn", + sessionId: "reusable-child", + turnId: "first-turn", + state: "completed", + }); + await nextTurn(); + const [child] = manager.listProviderSubagents(agent.id); + expect(child).toMatchObject({ + id: "reusable-child", + title: "Plugin child", + status: "completed", + }); + + harness.emit({ + type: "session.turn", + sessionId: "reusable-child", + turnId: "second-turn", + state: "started", + }); + await nextTurn(); + expect(manager.listProviderSubagents(agent.id)).toMatchObject([ + { id: child.id, title: child.title, status: "running" }, + ]); + + harness.emit({ + type: "session.turn", + sessionId: "reusable-child", + turnId: "second-turn", + state: outcome, + }); + await nextTurn(); + expect(manager.listProviderSubagents(agent.id)).toMatchObject([ + { id: child.id, title: child.title, status: outcome }, + ]); + } finally { + await Promise.all(manager.listAgents().map((agent) => manager.closeAgent(agent.id))); + await plugins.shutdown(); + } + }, + ); + + test.each(["started", "completed", "canceled", "failed"] as const)( + "replays a reused plugin child's latest turn state: %s", + async (state) => { + const harness = createProviderHarness({ + openChildren(rootSessionId, emit) { + emit({ + type: "session.opened", + sessionId: "reusable-child", + parentSessionId: rootSessionId, + capabilities: [], + restoration: "parent", + cwd: "/workspace", + }); + for (const [turnId, turnState] of [ + ["first-turn", "started"], + ["first-turn", "completed"], + ["second-turn", "started"], + ] as const) { + emit({ type: "session.turn", sessionId: "reusable-child", turnId, state: turnState }); + } + if (state !== "started") { + emit({ + type: "session.turn", + sessionId: "reusable-child", + turnId: "second-turn", + state, + }); + } + }, + }); + const registry = new PluginAgentClientRegistry(createTestLogger()); + registry.replace([harness.registration]); + try { + const session = await registry.clients()[harness.registration.id]!.createSession({ + provider: harness.registration.id, + cwd: "/workspace", + }); + const statuses = []; + for await (const event of session.streamHistory()) { + if ( + event.type === "provider_subagent" && + event.event.type === "upsert" && + event.event.id === "reusable-child" + ) { + statuses.push(event.event.status); + } + } + expect(statuses.at(-1)).toBe(state === "started" ? "running" : state); + } finally { + await registry.shutdown(); + } + }, + ); + test("gates persistence operations on negotiated provider capabilities", async () => { const harness = createProviderHarness({ capabilities: ["session.persistence"] }); const registry = new PluginAgentClientRegistry(createTestLogger()); @@ -1321,3 +2130,28 @@ test("plugin without a runtime safety capability uses baseline collection withou await rm(home, { recursive: true, force: true }); } }); + +test("plugin provider import launches with runtime MCP servers and returns only saved configuration", async () => { + const harness = createProviderHarness(); + const registry = new PluginAgentClientRegistry(createTestLogger()); + registry.replace([harness.registration]); + const client = registry.clients()[harness.registration.id]!; + const storedConfig = { provider: harness.registration.id, cwd: "/project" }; + const company = { type: "http", url: "https://tools.example.com/mcp" } as const; + try { + const imported = await client.importSession!( + { providerHandleId: 'plugin:{"version":1,"data":{"token":"root"}}', cwd: "/project" }, + { config: { ...storedConfig, mcpServers: { company } }, storedConfig }, + ); + expect(harness.inputs).toContainEqual( + expect.objectContaining({ + type: "session.open", + config: expect.objectContaining({ mcpServers: { company } }), + }), + ); + expect(imported.config).toEqual(storedConfig); + await imported.session.close(); + } finally { + await registry.shutdown(); + } +}); diff --git a/packages/server/src/server/agent/plugin-provider.ts b/packages/server/src/server/agent/plugin-provider.ts index 68e9778e43..2d20056930 100644 --- a/packages/server/src/server/agent/plugin-provider.ts +++ b/packages/server/src/server/agent/plugin-provider.ts @@ -1,4 +1,5 @@ import { randomUUID } from "node:crypto"; +import { PluginSessionHistory } from "./plugin-session-history.js"; import { resolve as resolvePath } from "node:path"; import type { Logger } from "pino"; import type { JsonValue } from "@getpaseo/protocol/agent-types"; @@ -592,6 +593,7 @@ class ProviderRuntime { class ProviderRuntimeSession { readonly history: ProviderEvent[] = []; + private historyClaimed = false; private readonly listeners = new Set<(event: ProviderEvent) => void>(); private capabilities: readonly string[] = []; private openRequest: { requestId: string; deferred: Deferred } | null = null; @@ -601,6 +603,7 @@ class ProviderRuntimeSession { >(); private readonly activeTurnIds = new Set(); private terminal = false; + private closePromise: Promise | null = null; config: ProviderConfigState = { models: [], modes: [], thinkingOptions: [], settings: [] }; commands: Array<{ name: string; description: string; argumentHint?: string }> = []; persistence: ProviderPersistence | null = null; @@ -622,6 +625,10 @@ class ProviderRuntimeSession { } onEvent(listener: (event: ProviderEvent) => void): () => void { + // This buffer bridges session.open and adapter attachment. Once replayed, + // the adapter owns history; retaining live cumulative snapshots is quadratic. + this.historyClaimed = true; + this.history.length = 0; this.listeners.add(listener); return () => this.listeners.delete(listener); } @@ -713,10 +720,19 @@ class ProviderRuntimeSession { } async close(): Promise { + this.history.length = 0; if (this.restoration === "parent") { this.runtime.removeSession(this.id, this.providerSessionId); return; } + this.closePromise ??= this.closeNativeSession().catch((error) => { + this.closePromise = null; + throw error; + }); + await this.closePromise; + } + + private async closeNativeSession(): Promise { try { await this.runtime.complete({ type: "session.close", @@ -725,9 +741,9 @@ class ProviderRuntimeSession { }); } catch (error) { if (!this.runtime.isClosed) throw error; - } finally { - this.runtime.removeSession(this.id, this.providerSessionId); } + // A failed close still needs its routing for a subsequent session.closed ack. + this.runtime.removeSession(this.id, this.providerSessionId); } beginOpen(requestId: string): Promise { @@ -826,7 +842,7 @@ class ProviderRuntimeSession { if (event.type === "session.persistence" && this.restoration === "core") { this.persistence = event.persistence; } - this.history.push(event); + if (!this.historyClaimed) this.history.push(event); for (const listener of this.listeners) listener(event); } } @@ -1052,7 +1068,7 @@ class PluginAgentClient implements AgentClient { if (!persistence) throw new Error(`Plugin provider '${this.provider}' did not persist import`); return { session, - config: { ...context.config, provider: this.provider, cwd: input.cwd }, + config: { ...context.storedConfig, provider: this.provider, cwd: input.cwd }, persistence, timeline: session.timelineHistory(), providerSubagentEvents: session.subagentHistory(), @@ -1085,11 +1101,40 @@ class PluginAgentClient implements AgentClient { persistence: input.persistence, history: input.history, }); - const session = new PluginAgentSession(this.provider, bridge, () => { - this.rootsBySession.delete(bridge.id); - }); - this.rootsBySession.set(bridge.id, session); - this.attachPendingChildren(); + const forget = () => { + for (const [id, owner] of this.rootsBySession) { + if (owner === session) this.rootsBySession.delete(id); + } + }; + const bind = (next: ProviderRuntimeSession) => { + this.rootsBySession.set(next.id, session); + this.attachPendingChildren(); + }; + const config = mapSessionConfig(input.config, input.launchContext, input.persist); + const session = new PluginAgentSession( + this.provider, + bridge, + forget, + async (persistence, state) => { + forget(); + return await this.runtime.openSession({ + sessionId: randomUUID(), + config: { + ...config, + model: state.model, + mode: state.mode, + thinkingOption: state.thinkingOption, + settings: Object.fromEntries( + state.settings.map((setting) => [setting.id, setting.value]), + ), + }, + persistence, + history: "replay", + }); + }, + bind, + ); + bind(bridge); return session; } @@ -1128,25 +1173,54 @@ class PluginAgentClient implements AgentClient { } } +interface TimelineTextSnapshot { + type: "assistant_message" | "reasoning" | "user_message"; + text: string; +} + +function isTextSnapshotItem( + item: ProviderTimelineItem, +): item is Extract { + return ( + item.type === "assistant_message" || item.type === "reasoning" || item.type === "user_message" + ); +} + class PluginAgentSession implements AgentSession { readonly initialTimeline: ImportedProviderSession["timeline"]; private readonly listeners = new Set<(event: AgentStreamEvent) => void>(); - private readonly history: AgentStreamEvent[] = []; + private readonly history = new PluginSessionHistory(); private readonly pendingPermissions = new Map(); private readonly permissionResponses = new Map(); private readonly revertTokens = new Map(); - private readonly timelineSnapshots = new Map(); + private readonly timelineSnapshots = new Map(); private readonly subagentIdsBySession = new Map(); - private readonly childUnsubscribes = new Map void>(); - private readonly childSnapshots = new Map>(); + private readonly children = new Map< + string, + { session: ProviderRuntimeSession; unsubscribe: () => void } + >(); + private readonly childSnapshots = new Map>(); private unsubscribe: (() => void) | null = null; private currentTurnId: string | null = null; private closed = false; + private replay: { + persistence: ProviderPersistence; + config: ProviderConfigState; + messageId: string; + scope: "conversation" | "both"; + closed: boolean; + } | null = null; + private replaying: Promise | null = null; constructor( readonly provider: string, - private readonly bridge: ProviderRuntimeSession, + private bridge: ProviderRuntimeSession, private readonly onClose: () => void, + private readonly reopen: ( + persistence: ProviderPersistence, + state: ProviderConfigState, + ) => Promise, + private readonly onBind: (bridge: ProviderRuntimeSession) => void, ) { this.subagentIdsBySession.set(bridge.id, null); for (const event of bridge.history) this.accept(event, false); @@ -1163,7 +1237,13 @@ class PluginAgentSession implements AgentSession { } get capabilities(): AgentCapabilityFlags { - return agentCapabilities(this.bridge.negotiatedCapabilities); + const capabilities = agentCapabilities(this.bridge.negotiatedCapabilities); + const resumable = this.canReplayHistory; + return { + ...capabilities, + supportsRewindConversation: capabilities.supportsRewindConversation && resumable, + supportsRewindBoth: capabilities.supportsRewindBoth && resumable, + }; } get features(): AgentFeature[] { @@ -1191,6 +1271,7 @@ class PluginAgentSession implements AgentSession { prompt: AgentPromptInput, options: AgentRunOptions = {}, ): Promise<{ turnId: string }> { + this.assertReplayComplete(); const clientMessageId = options.clientMessageId ?? randomUUID(); const result = await this.bridge.prompt({ clientMessageId, @@ -1213,6 +1294,7 @@ class PluginAgentSession implements AgentSession { prompt: AgentPromptInput, options: SteerActiveTurnOptions, ): Promise { + this.assertReplayComplete(); if (!this.bridge.negotiatedCapabilities.includes("prompt.steer")) { return { status: "unavailable" }; } @@ -1236,7 +1318,8 @@ class PluginAgentSession implements AgentSession { } async *streamHistory(): AsyncGenerator { - for (const event of this.history) yield event; + await this.ensureReplay(); + for (const event of this.history.read(this.provider)) yield event; } get canStopRuntime(): (() => Promise) | undefined { @@ -1263,6 +1346,7 @@ class PluginAgentSession implements AgentSession { } async setMode(modeId: string): Promise { + this.assertReplayComplete(); await this.bridge.configure({ mode: modeId }); } @@ -1299,11 +1383,10 @@ class PluginAgentSession implements AgentSession { async close(): Promise { if (this.closed) return; this.closed = true; - this.unsubscribe?.(); - this.unsubscribe = null; - for (const unsubscribe of this.childUnsubscribes.values()) unsubscribe(); - this.childUnsubscribes.clear(); - this.subagentIdsBySession.clear(); + this.listeners.clear(); + await this.replaying?.catch(() => undefined); + await this.clearBinding(); + this.replay = null; this.listeners.clear(); this.onClose(); await this.bridge.close(); @@ -1318,14 +1401,17 @@ class PluginAgentSession implements AgentSession { } async setModel(modelId: string | null): Promise { + this.assertReplayComplete(); await this.bridge.configure({ model: modelId }); } async setThinkingOption(thinkingOptionId: string | null): Promise { + this.assertReplayComplete(); await this.bridge.configure({ thinkingOption: thinkingOptionId }); } async setFeature(featureId: string, value: unknown): Promise { + this.assertReplayComplete(); await this.bridge.configure({ settings: { [featureId]: toJsonValue(value, `setting '${featureId}'`) }, }); @@ -1344,16 +1430,20 @@ class PluginAgentSession implements AgentSession { } timelineHistory(): ImportedProviderSession["timeline"] { - return this.history.flatMap((event) => - event.type === "timeline" ? [{ item: event.item, timestamp: event.timestamp }] : [], - ); + return this.history + .read(this.provider) + .flatMap((event) => + event.type === "timeline" ? [{ item: event.item, timestamp: event.timestamp }] : [], + ); } subagentHistory(): NonNullable { - return this.history.filter( - (event): event is Extract => - event.type === "provider_subagent", - ); + return this.history + .read(this.provider) + .filter( + (event): event is Extract => + event.type === "provider_subagent", + ); } attachChild( @@ -1382,13 +1472,13 @@ class PluginAgentSession implements AgentSession { cwd: opened.cwd, }, }); - const snapshots = new Map(); + const snapshots = new Map(); this.childSnapshots.set(childId, snapshots); for (const event of child.history) this.acceptChildEvent(childId, event, snapshots); - this.childUnsubscribes.set( - child.id, - child.onEvent((event) => this.acceptChildEvent(childId, event, snapshots)), - ); + this.children.set(child.id, { + session: child, + unsubscribe: child.onEvent((event) => this.acceptChildEvent(childId, event, snapshots)), + }); } private accept(event: ProviderEvent, live: boolean): void { @@ -1568,7 +1658,7 @@ class PluginAgentSession implements AgentSession { private acceptChildEvent( childId: string, event: ProviderEvent, - snapshots: Map, + snapshots: Map, ): void { if (event.type === "timeline.item") { const item = mapTimelineItem(event.item, snapshots); @@ -1581,11 +1671,15 @@ class PluginAgentSession implements AgentSession { } return; } - if (event.type === "session.turn" && event.state !== "started") { + if (event.type === "session.turn") { this.publish({ type: "provider_subagent", provider: this.provider, - event: { type: "upsert", id: childId, status: event.state }, + event: { + type: "upsert", + id: childId, + status: event.state === "started" ? "running" : event.state, + }, }); return; } @@ -1602,7 +1696,84 @@ class PluginAgentSession implements AgentSession { } } + private async clearBinding(): Promise { + this.unsubscribe?.(); + this.unsubscribe = null; + for (const child of this.children.values()) { + child.unsubscribe(); + await child.session.close(); + } + this.children.clear(); + this.subagentIdsBySession.clear(); + this.history.clear(); + this.timelineSnapshots.clear(); + this.childSnapshots.clear(); + this.revertTokens.clear(); + this.pendingPermissions.clear(); + this.permissionResponses.clear(); + this.currentTurnId = null; + } + + private assertReplayComplete(): void { + if (this.replay) { + throw new Error( + "Plugin rewind history refresh is incomplete. Retry the rewind or reload the agent before continuing.", + ); + } + } + + // A native rewind has already committed. Until replay succeeds, neither history + // nor a new prompt may use the retired binding. Keep its latest handle for retry. + private async ensureReplay(): Promise { + if (!this.replay) return; + if (this.closed) throw new StaleProviderSessionError(this.id); + if (!this.replaying) { + this.replaying = this.replayBinding().finally(() => { + this.replaying = null; + }); + } + await this.replaying; + } + + private async replayBinding(): Promise { + const replay = this.replay!; + if (!replay.closed) { + for (const request of this.pendingPermissions.values()) { + await this.respondToPermission(request.id, { + behavior: "deny", + message: "Session replaced after rewind", + }); + this.pendingPermissions.delete(request.id); + this.permissionResponses.delete(request.id); + } + await this.clearBinding(); + await this.bridge.close(); + replay.closed = true; + } + const bridge = await this.reopen(replay.persistence, replay.config); + this.bridge = bridge; + this.subagentIdsBySession.set(bridge.id, null); + for (const event of bridge.history) this.accept(event, false); + this.unsubscribe = bridge.onEvent((event) => this.accept(event, true)); + this.onBind(bridge); + this.replay = null; + } + + private get canReplayHistory(): boolean { + return ( + this.bridge.restoration === "core" && + this.bridge.persistence !== null && + this.bridge.negotiatedCapabilities.includes("session.persistence") + ); + } + private async revert(messageId: string, scope: "conversation" | "files" | "both") { + const pending = this.replay; + await this.ensureReplay(); + if (pending?.messageId === messageId && pending.scope === scope) return; + if (scope !== "files" && !this.canReplayHistory) { + throw new Error("Plugin conversation rewind requires session persistence for history replay"); + } const token = this.revertTokens.get(messageId); if (token === undefined) throw new Error(`No provider revert token for message ${messageId}`); await this.bridge.revert({ @@ -1612,6 +1783,12 @@ class PluginAgentSession implements AgentSession { token, scope, }); + if (scope !== "files") { + const persistence = this.bridge.persistence; + if (!persistence) throw new Error("Plugin rewind removed session persistence"); + this.replay = { persistence, config: this.bridge.config, messageId, scope, closed: false }; + await this.ensureReplay(); + } } private publish(event: AgentStreamEvent): void { @@ -1717,24 +1894,24 @@ function mapPromptContent(prompt: AgentPromptInput): ProviderContent[] { function mapTimelineItem( item: ProviderTimelineItem, - snapshots: Map, + snapshots: Map, revertTokens?: Map, ): AgentTimelineItem | null { const previous = snapshots.get(item.id); - snapshots.set(item.id, item); - const { id, revertToken, ...withoutIdentity } = item; - if (revertToken !== undefined && revertTokens) { - revertTokens.set(id, revertToken); - if (item.type === "user_message" || item.type === "assistant_message") { - revertTokens.set(item.messageId ?? id, revertToken); - } + if (isTextSnapshotItem(item)) { + snapshots.set(item.id, { type: item.type, text: item.text }); } + const { id, revertToken: _revertToken, ...withoutIdentity } = item; + rememberRevertToken(item, revertTokens); if (item.type === "assistant_message" || item.type === "reasoning") { const previousText = previous?.type === item.type ? previous.text : ""; - const text = item.text.startsWith(previousText) + const suffix = item.text.startsWith(previousText) ? item.text.slice(previousText.length) : item.text; + // Match OpenCode's detachedSuffix: a sliced delta otherwise keeps its entire + // cumulative IPC snapshot alive in the projected timeline. Preserve split surrogates. + const text = Buffer.from(suffix, "utf16le").toString("utf16le"); if (text.length === 0) return null; return item.type === "assistant_message" ? { type: "assistant_message", text, messageId: item.messageId ?? id } @@ -1762,6 +1939,17 @@ function mapTimelineItem( return withoutIdentity as AgentTimelineItem; } +function rememberRevertToken( + item: ProviderTimelineItem, + tokens?: Map, +): void { + if (item.revertToken === undefined || !tokens) return; + tokens.set(item.id, item.revertToken); + if (item.type === "user_message" || item.type === "assistant_message") { + tokens.set(item.messageId ?? item.id, item.revertToken); + } +} + function persistenceHandle( provider: string, persistence: ProviderPersistence, diff --git a/packages/server/src/server/agent/plugin-session-history.ts b/packages/server/src/server/agent/plugin-session-history.ts new file mode 100644 index 0000000000..f5efd446d7 --- /dev/null +++ b/packages/server/src/server/agent/plugin-session-history.ts @@ -0,0 +1,66 @@ +import { TimelineProjection } from "./timeline-projection.js"; +import type { AgentStreamEvent } from "./agent-sdk-types.js"; + +// Replay canonical items, rather than retaining every streamed delta or tool state. +// Sequence numbers here only preserve adapter replay order, not wire cursors. +export class PluginSessionHistory { + private readonly timelines = new Map< + string, + { projection: TimelineProjection; seq: number; positions: Map } + >(); + private readonly events: Array<{ seq: number; event: AgentStreamEvent }> = []; + private seq = 0; + + push(event: AgentStreamEvent): void { + const seq = ++this.seq; + const child = + event.type === "provider_subagent" && event.event.type === "timeline" ? event.event : null; + if (event.type !== "timeline" && !child) { + this.events.push({ seq, event }); + return; + } + const key = child?.id ?? ""; + let projection = this.timelines.get(key); + if (!projection) { + projection = { projection: new TimelineProjection(), seq: 0, positions: new Map() }; + this.timelines.set(key, projection); + } + const timeline = event.type === "timeline" ? event : child!; + const row = projection.projection.append({ + seq: ++projection.seq, + item: timeline.item, + timestamp: timeline.timestamp ?? "", + ...(event.type === "timeline" && event.turnId ? { turnId: event.turnId } : {}), + }); + if (!projection.positions.has(row.seqStart)) projection.positions.set(row.seqStart, seq); + } + + read(provider: string): AgentStreamEvent[] { + const events = [...this.events]; + for (const [id, projection] of this.timelines) { + for (const row of projection.projection.getRows()) { + const timestamp = row.timestamp ? { timestamp: row.timestamp } : {}; + const event: AgentStreamEvent = id + ? { + type: "provider_subagent", + provider, + event: { type: "timeline", id, item: row.item, ...timestamp }, + } + : { + type: "timeline", + provider, + item: row.item, + ...timestamp, + ...(row.turnId ? { turnId: row.turnId } : {}), + }; + events.push({ seq: projection.positions.get(row.seqStart)!, event }); + } + } + return events.sort((a, b) => a.seq - b.seq).map(({ event }) => event); + } + + clear(): void { + this.timelines.clear(); + this.events.length = 0; + } +} diff --git a/packages/server/src/server/agent/provider-runtime.ts b/packages/server/src/server/agent/provider-runtime.ts index 398d35746d..c266614273 100644 --- a/packages/server/src/server/agent/provider-runtime.ts +++ b/packages/server/src/server/agent/provider-runtime.ts @@ -22,7 +22,12 @@ interface CreateAgentProviderRuntimeOptions { export async function createAgentProviderRuntime( options: CreateAgentProviderRuntimeOptions, ): Promise { - const bridge = new OpenCodeBridge({ paseoHome: options.paseoHome, logger: options.logger }); + const configuredPort = + options.snapshotManager.runtimeSettings?.opencode?.env?.PASEO_OPENCODE_BRIDGE_PORT; + const port = configuredPort === undefined ? undefined : Number(configuredPort); + if (port !== undefined && (!Number.isInteger(port) || port < 1 || port > 65535)) + throw new Error("PASEO_OPENCODE_BRIDGE_PORT must be an integer between 1 and 65535"); + const bridge = new OpenCodeBridge({ paseoHome: options.paseoHome, logger: options.logger, port }); try { await bridge.start(); const snapshotManager = new ProviderSnapshotManager({ diff --git a/packages/server/src/server/agent/provider-subagents/store.test.ts b/packages/server/src/server/agent/provider-subagents/store.test.ts index dc71c0f5c6..5c2ca55174 100644 --- a/packages/server/src/server/agent/provider-subagents/store.test.ts +++ b/packages/server/src/server/agent/provider-subagents/store.test.ts @@ -80,7 +80,7 @@ describe("ProviderSubagentStore", () => { const [row] = subagents.fetchTimeline("parent-a", "child-1").rows; expect(row?.item).toMatchObject({ type: "tool_call", - detail: { type: "shell", output: "x".repeat(64 * 1024) }, + detail: { type: "shell", output: expect.stringMatching(/^x+…\[truncated \d+\.\d KB\]$/) }, }); }); diff --git a/packages/server/src/server/agent/providers/acp-agent.test.ts b/packages/server/src/server/agent/providers/acp-agent.test.ts index e902493dcb..7e50b32cf5 100644 --- a/packages/server/src/server/agent/providers/acp-agent.test.ts +++ b/packages/server/src/server/agent/providers/acp-agent.test.ts @@ -1,6 +1,6 @@ import { type ChildProcess, type ChildProcessWithoutNullStreams } from "node:child_process"; import { EventEmitter } from "node:events"; -import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import { createRequire } from "node:module"; import { tmpdir } from "node:os"; import path from "node:path"; @@ -2634,6 +2634,72 @@ describe("ACPAgentSession slash commands", () => { }, ]); }); + + test("lists late command batches through the public ACP client", async () => { + const artifacts = path.resolve(".artifacts"); + await mkdir(artifacts, { recursive: true }); + const directory = await mkdtemp(path.join(artifacts, "acp-command-inventory-")); + const script = path.join(directory, "agent.mjs"); + await writeFile( + script, + ` +import { createInterface } from "node:readline"; +const send = (message) => process.stdout.write(JSON.stringify(message) + "\\n"); +const help = { name: "help", description: "Show available commands" }; +const skill = { name: "xlsx", description: "Work with spreadsheets", input: { hint: "[instructions]" } }; +const publish = (commands) => send({ + jsonrpc: "2.0", method: "session/update", params: { + sessionId: "inventory-session", update: { + sessionUpdate: "available_commands_update", availableCommands: commands, + }, + }, +}); +createInterface({ input: process.stdin }).on("line", (line) => { + const request = JSON.parse(line); + if (request.method === "initialize") { + send({ jsonrpc: "2.0", id: request.id, result: { protocolVersion: 1, agentCapabilities: {} } }); + } else if (request.method === "session/new") { + // The first batch is already cached when createSession returns. + publish([help]); + send({ jsonrpc: "2.0", id: request.id, result: { sessionId: "inventory-session" } }); + setTimeout(() => publish([help]), 100); + setTimeout(() => publish([help, skill]), 350); + } else if (request.id !== undefined) { + send({ jsonrpc: "2.0", id: request.id, error: { code: -32601, message: "Method not found" } }); + } +}); +`, + ); + const client = new GenericACPAgentClient({ + logger: createTestLogger(), + command: [process.execPath, script], + }); + try { + const session = await client.createSession({ provider: "acp", cwd: directory }); + try { + const commands = await session.listCommands!(); + expect(commands).toEqual([ + { + name: "help", + description: "Show available commands", + argumentHint: "", + kind: "command", + }, + { + name: "xlsx", + description: "Work with spreadsheets", + argumentHint: "[instructions]", + kind: "command", + }, + ]); + expect(await session.listCommands!()).toEqual(commands); + } finally { + await session.close(); + } + } finally { + await rm(directory, { recursive: true, force: true }); + } + }); }); describe("ACPAgentSession", () => { diff --git a/packages/server/src/server/agent/providers/acp-agent.ts b/packages/server/src/server/agent/providers/acp-agent.ts index e26b6e4ade..339c491e46 100644 --- a/packages/server/src/server/agent/providers/acp-agent.ts +++ b/packages/server/src/server/agent/providers/acp-agent.ts @@ -120,6 +120,7 @@ import { } from "../provider-launch-config.js"; import { renderPromptAttachmentAsText } from "../prompt-attachments.js"; import { appendOrReplaceGrowingAssistantMessage, runProviderTurn } from "./provider-runner.js"; +import { resolveResumeProcessCwd } from "./resume-process-cwd.js"; import { buildStringCommandShellInvocation, createStringCommandShellEnvOverlay, @@ -142,29 +143,29 @@ function assertChildWithPipes( } } -// Node reports a failed spawn (missing binary or missing cwd) as a child -// `error` event; without a listener it becomes an uncaught exception. -function rejectOnSpawnError(child: ChildProcess, stderrChunks: string[]): Promise { +// Watch process failures as well as spawn errors: the SDK leaves initialize +// pending when the child exits without replying. `close` waits for stderr to +// drain, so the failure includes the launcher's diagnostic. +function rejectOnProcessFailure(child: ChildProcess, stderrChunks: string[]): Promise { return new Promise((_, reject) => { child.once("error", (error) => { const stderr = stderrChunks.join("").trim(); reject(new Error(stderr ? `${String(error)}\n${stderr}` : String(error))); }); + child.once("close", (code, signal) => { + const stderr = stderrChunks.join("").trim(); + const status = signal ? `signal ${signal}` : `exit code ${code ?? "unknown"}`; + reject( + new Error( + `ACP agent process exited before initialization completed (${status})${ + stderr ? `\n${stderr}` : "" + }`, + ), + ); + }); }); } -async function isDirectory(target: string): Promise { - try { - return (await fs.stat(target)).isDirectory(); - } catch (error) { - const code = (error as NodeJS.ErrnoException).code; - if (code === "ENOENT" || code === "ENOTDIR") { - return false; - } - throw error; - } -} - function isRecord(value: unknown): value is Record { return value != null && typeof value === "object" && !Array.isArray(value); } @@ -325,6 +326,14 @@ const ACP_CLOSE_REQUEST_TIMEOUT_MS = 2_000; const ACP_IMPORT_HISTORY_LOAD_TIMEOUT_MS = 30_000; const ACP_IMPORT_HISTORY_BUDGET_MS = 60_000; +/** + * An ACP agent publishes its slash-command inventory incrementally. Wait this + * long without another batch before treating the inventory as complete. MiniMax + * publishes its skills about 350ms after its built-in commands. + */ +const COMMAND_INVENTORY_QUIET_MS = 600; +const COMMAND_INVENTORY_POLL_MS = 25; + function summarizeMalformedACPStdoutError(error: unknown): { type: string; message: string } { return { type: error instanceof Error ? error.name : typeof error, @@ -542,7 +551,7 @@ interface ACPProcessTransport { connection: ClientSideConnection; stderrChunks: string[]; spawnReady: Promise; - spawnError: Promise; + processError: Promise; } interface ACPImportPromptPreviews { @@ -1380,6 +1389,7 @@ export class ACPAgentClient implements AgentClient { client?: ACPClient; }, ): Promise { + const configuredOptions = ACPProviderOptionsSchema.parse(options?.providerOptions ?? {}); const transport = await this.spawnTransport(launchEnv, options?.client); const probe: UninitializedACPProcess = { child: transport.child, @@ -1391,7 +1401,7 @@ export class ACPAgentClient implements AgentClient { const initialize = await this.initializeTransport( transport, options?.initializeTimeoutMs, - options?.providerOptions, + configuredOptions.clientCapabilities, ); const initializedProbe: SpawnedACPProcess = { ...probe, @@ -1425,7 +1435,7 @@ export class ACPAgentClient implements AgentClient { stderrChunks.push(chunk.toString()); }); - const spawnErrorPromise = rejectOnSpawnError(child, stderrChunks); + const processErrorPromise = rejectOnProcessFailure(child, stderrChunks); const spawnReadyPromise = new Promise((resolve) => { child.once("spawn", () => { resolve(); @@ -1444,16 +1454,15 @@ export class ACPAgentClient implements AgentClient { connection, stderrChunks, spawnReady: spawnReadyPromise, - spawnError: spawnErrorPromise, + processError: processErrorPromise, }; } protected async initializeTransport( transport: ACPProcessTransport, initializeTimeoutMs?: number, - providerOptions?: Record, + clientCapabilities?: ACPClientCapabilities, ): Promise { - const configuredOptions = ACPProviderOptionsSchema.parse(providerOptions ?? {}); let timeout: ReturnType | null = null; const initializeTimeoutPromise = initializeTimeoutMs ? new Promise((_, reject) => { @@ -1470,11 +1479,11 @@ export class ACPAgentClient implements AgentClient { protocolVersion: PROTOCOL_VERSION, clientCapabilities: buildACPClientCapabilities( this.clientCapabilityMeta, - configuredOptions.clientCapabilities ?? this.clientCapabilities, + clientCapabilities ?? this.clientCapabilities, ), clientInfo: { name: "Paseo", version: "dev" }, }), - transport.spawnError, + transport.processError, ...(initializeTimeoutPromise ? [initializeTimeoutPromise] : []), ]), ); @@ -1555,7 +1564,7 @@ export class ACPAgentClient implements AgentClient { try { transport = await this.spawnTransport(PROBE_ENV); await withTimeout( - Promise.race([transport.spawnReady, transport.spawnError]), + Promise.race([transport.spawnReady, transport.processError]), phaseTimeoutMs, `ACP spawn timed out after ${phaseTimeoutMs}ms`, ); @@ -1753,7 +1762,8 @@ export class ACPAgentSession implements AgentSession, ACPClient { private lastActivityAt: string | null = null; private configOptions: SessionConfigOption[] = []; private cachedCommands: AgentSlashCommand[] = []; - private commandsReadyDeferred: { promise: Promise; resolve: () => void } | null = null; + /** When the last command batch arrived; null while nothing has been published. */ + private commandsUpdatedAt: number | null = null; private commandsReadySettled = false; private waitForInitialCommands: boolean; private initialCommandsWaitTimeoutMs: number; @@ -2051,58 +2061,39 @@ export class ACPAgentSession implements AgentSession, ACPClient { ]; } - private ensureCommandsReadyDeferred(): void { - if (this.commandsReadyDeferred || this.commandsReadySettled || this.cachedCommands.length > 0) { - return; - } - - let resolve!: () => void; - const promise = new Promise((r) => { - resolve = r; - }); - this.commandsReadyDeferred = { promise, resolve }; - } - private settleCommandsReady(): void { - if (this.commandsReadySettled) { - return; - } this.commandsReadySettled = true; - this.commandsReadyDeferred?.resolve(); - this.commandsReadyDeferred = null; } - private async waitForCommandsReady(): Promise { - const deferred = this.commandsReadyDeferred; - if (!deferred) { - return; - } - - let timer: ReturnType | null = null; - try { - await Promise.race([ - deferred.promise, - new Promise((resolve) => { - timer = setTimeout(resolve, this.initialCommandsWaitTimeoutMs); - }), - ]); - } finally { - if (timer) { - clearTimeout(timer); - } + /** + * Providers publish their command inventory incrementally. MiniMax sends its + * built-in commands twice, then a third batch about 350ms later that merges in + * every discovered skill. Returning after the first batch loses the skills. + * + * Wait for the inventory to go quiet rather than for the first batch. The + * quiet window must exceed the gap between a provider's own batches; 600ms + * covers MiniMax with margin. `initialCommandsWaitTimeoutMs` still bounds the + * whole wait for providers that publish once or never publish at all. + */ + private async waitForCommandsToSettle(): Promise { + const deadline = Date.now() + this.initialCommandsWaitTimeoutMs; + while (!this.commandsReadySettled && !this.closed) { + const remaining = deadline - Date.now(); + if (remaining <= 0) return; + const quietFor = this.commandsUpdatedAt === null ? 0 : Date.now() - this.commandsUpdatedAt; + if (quietFor >= COMMAND_INVENTORY_QUIET_MS) return; + await new Promise((resolve) => + setTimeout(resolve, Math.min(remaining, COMMAND_INVENTORY_POLL_MS)), + ); } } async listCommands(): Promise { - if (this.cachedCommands.length > 0) { - return this.cachedCommands; - } - if (!this.waitForInitialCommands || this.closed) { + if (this.commandsReadySettled || this.closed || !this.waitForInitialCommands) { return this.cachedCommands; } - this.ensureCommandsReadyDeferred(); - await this.waitForCommandsReady(); + await this.waitForCommandsToSettle(); this.settleCommandsReady(); return this.cachedCommands; } @@ -2733,14 +2724,12 @@ export class ACPAgentSession implements AgentSession, ACPClient { } } - // Cache an asynchronously-delivered slash-command batch and unblock any - // listCommands() call that is waiting on the initial batch. Used when a - // provider supplies an extensionCommandsParser whose result arrives after - // session/new (e.g. via a vendor extension notification). The ready gate is - // always settled — even for an empty batch — so a provider that legitimately - // reports no commands does not leave listCommands() blocked for the full - // initial-commands timeout. An optional sessionId scopes the batch to this - // session; notifications addressed to a different session are ignored. + // Cache an asynchronously-delivered slash-command batch from a provider that + // supplies an extensionCommandsParser (e.g. a vendor extension notification). + // An empty batch is the provider saying it has no commands, so it settles the + // waiter immediately instead of letting it wait out the quiet window. An + // optional sessionId scopes the batch to this session; notifications + // addressed to a different session are ignored. private applyResolvedCommands( commands: AgentSlashCommand[], options?: { sessionId?: string }, @@ -2754,7 +2743,13 @@ export class ACPAgentSession implements AgentSession, ACPClient { } if (commands.length > 0) { + this.commandsUpdatedAt = Date.now(); this.cachedCommands = commands; + // A non-empty batch may be followed by more. Let the quiet window decide + // when the inventory is complete rather than settling here; an empty + // batch is the provider saying it has nothing, which must still unblock + // the waiter immediately. + return; } this.settleCommandsReady(); } @@ -2877,11 +2872,8 @@ export class ACPAgentSession implements AgentSession, ACPClient { // Loading an archived agent's history runs nothing in its working directory, which // may have been removed with its worktree. session/load still names the original // directory; only the process starts from the home directory. - private async resolveProcessCwd(): Promise { - if (this.resumePurpose !== "history" || (await isDirectory(this.config.cwd))) { - return this.config.cwd; - } - return homedir(); + private resolveProcessCwd(): Promise { + return resolveResumeProcessCwd(this.config.cwd, this.resumePurpose); } private async spawnProcess(): Promise { @@ -2910,7 +2902,7 @@ export class ACPAgentSession implements AgentSession, ACPClient { child.stderr.on("data", (chunk: Buffer | string) => { stderrChunks.push(chunk.toString()); }); - const spawnError = rejectOnSpawnError(child, stderrChunks); + const processError = rejectOnProcessFailure(child, stderrChunks); child.once("exit", (code, signal) => { if (this.closed || this.historyRuntimeReleased) { return; @@ -2947,7 +2939,7 @@ export class ACPAgentSession implements AgentSession, ACPClient { ), clientInfo: { name: "Paseo", version: "dev" }, }), - spawnError, + processError, ]), ); @@ -3138,13 +3130,19 @@ export class ACPAgentSession implements AgentSession, ACPClient { this.handleUsageUpdate(update); return pendingUserEvents; case "available_commands_update": + this.commandsUpdatedAt = Date.now(); this.cachedCommands = update.availableCommands.map((command) => ({ name: command.name, description: command.description, argumentHint: command.input?.hint ?? "", kind: "command", })); - this.settleCommandsReady(); + // An empty batch means the agent has no commands and would otherwise + // wait out the whole quiet window. A non-empty batch may be one of + // several, so completion belongs to the quiet window. + if (update.availableCommands.length === 0) { + this.settleCommandsReady(); + } return pendingUserEvents; default: return pendingUserEvents; diff --git a/packages/server/src/server/agent/providers/acp-startup-exit.test.ts b/packages/server/src/server/agent/providers/acp-startup-exit.test.ts new file mode 100644 index 0000000000..39ae6f743e --- /dev/null +++ b/packages/server/src/server/agent/providers/acp-startup-exit.test.ts @@ -0,0 +1,112 @@ +import { execFile } from "node:child_process"; +import { promisify } from "node:util"; +import { describe, expect, test } from "vitest"; + +import { GenericACPAgentClient } from "./generic-acp-agent.js"; +import { createTestLogger } from "../../../test-utils/test-logger.js"; + +// Exercise the public catalog API with a real child, including stdout EOF and +// stderr draining. No provider installation or external service is involved. +const failingCommand: [string, ...string[]] = [ + process.execPath, + "-e", + "process.stdin.once('data', () => { process.stderr.write('launcher failed: fixture startup error\\n'); process.exitCode = 1; process.stdin.destroy(); });", +]; + +describe("ACP catalog startup failures", () => { + test("reports a process that exits during initialize with its stderr", async () => { + const client = new GenericACPAgentClient({ + logger: createTestLogger(), + command: failingCommand, + }); + await expect( + client.fetchCatalog({ scope: "workspace", cwd: process.cwd(), force: true }), + ).rejects.toThrow(/launcher failed: fixture startup error/); + }, 5_000); + + test("session startup reports the same process exit with its stderr", async () => { + const client = new GenericACPAgentClient({ + logger: createTestLogger(), + command: failingCommand, + }); + await expect(client.createSession({ provider: "acp", cwd: process.cwd() })).rejects.toThrow( + /launcher failed: fixture startup error/, + ); + }, 5_000); + + test("provider diagnostics report the startup exit instead of an initialize timeout", async () => { + const client = new GenericACPAgentClient({ + logger: createTestLogger(), + command: failingCommand, + diagnosticPhaseTimeoutMs: 2_000, + }); + const { diagnostic } = await client.getDiagnostic(); + expect(diagnostic).toContain( + "ACP agent process exited before initialization completed (exit code 1)", + ); + expect(diagnostic).toContain("launcher failed: fixture startup error"); + expect(diagnostic).not.toContain("initialize timed out"); + }); + + test("invalid provider options reject without crashing the host process", async () => { + const clientModule = new URL("./generic-acp-agent.ts", import.meta.url).href; + const loggerModule = new URL("../../../test-utils/test-logger.ts", import.meta.url).href; + const script = ` + import { GenericACPAgentClient } from ${JSON.stringify(clientModule)}; + import { createTestLogger } from ${JSON.stringify(loggerModule)}; + const client = new GenericACPAgentClient({ + logger: createTestLogger(), + command: [process.execPath, '-e', 'setInterval(() => {}, 1000)'], + }); + try { + await client.fetchCatalog({ + scope: 'workspace', cwd: process.cwd(), force: true, + providerOptions: { clientCapabilities: { fs: 'invalid' } }, + }); + throw new Error('Expected invalid options to reject'); + } catch (error) { + if (error.name !== 'ZodError') throw error; + } + // Let child cleanup and Node's unhandled-rejection check complete. + await new Promise(resolve => setTimeout(resolve, 100)); + console.log('host stayed alive'); + `; + const result = await promisify(execFile)( + process.execPath, + ["--import", "tsx", "--input-type=module", "-e", script], + { timeout: 10_000 }, + ); + expect(result.stdout).toContain("host stayed alive"); + expect(result.stderr).toBe(""); + }); + + test("a successful catalog probe still returns its models and closes cleanly", async () => { + const client = new GenericACPAgentClient({ + logger: createTestLogger(), + command: [ + process.execPath, + "-e", + ` + require('node:readline').createInterface({ input: process.stdin }).on('line', (line) => { + const request = JSON.parse(line); + const result = request.method === 'initialize' + ? { protocolVersion: 1, agentCapabilities: {} } + : { sessionId: 'fixture', models: { + currentModelId: 'fixture-model', + availableModels: [{ modelId: 'fixture-model', name: 'Fixture model' }] + } }; + process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id: request.id, result }) + '\\n'); + }); + `, + ], + }); + const catalog = await client.fetchCatalog({ + scope: "workspace", + cwd: process.cwd(), + force: true, + }); + expect(catalog.models).toEqual([ + expect.objectContaining({ id: "fixture-model", label: "Fixture model" }), + ]); + }); +}); diff --git a/packages/server/src/server/agent/providers/claude/agent.background-subagent.test.ts b/packages/server/src/server/agent/providers/claude/agent.background-subagent.test.ts index 8530e76844..8aa15581ae 100644 --- a/packages/server/src/server/agent/providers/claude/agent.background-subagent.test.ts +++ b/packages/server/src/server/agent/providers/claude/agent.background-subagent.test.ts @@ -466,13 +466,13 @@ describe("background Claude subagents", () => { type: "sub_agent", subAgentType: "general-purpose", description: "Count files here", - log: "[Bash] ls -1", + log: "", }, }); }); test.each(["before", "after"])( - "keeps one logged Task card when child tools start %s the parent finishes", + "keeps one Task card when child tools start %s the parent finishes", async (timing) => { // A child can stream across the main session's turn boundary. Claude opens the next // main-session turn with system/init; bare child frames do not open a turn. @@ -605,7 +605,7 @@ describe("background Claude subagents", () => { type: "sub_agent", subAgentType: "general-purpose", description: "Count files here", - log: "[Bash] ls -1", + log: "", }, }); }, diff --git a/packages/server/src/server/agent/providers/claude/agent.env.test.ts b/packages/server/src/server/agent/providers/claude/agent.env.test.ts index 0806a0dbc6..6d268e932c 100644 --- a/packages/server/src/server/agent/providers/claude/agent.env.test.ts +++ b/packages/server/src/server/agent/providers/claude/agent.env.test.ts @@ -30,16 +30,20 @@ function createQueryMock(events: unknown[]): Query { } describe("Claude SDK env", () => { - test.each(["node", "bun", process.execPath])( - "identifies the spawned %s process as Paseo after clearing parent session env", - async (command) => { + test.each( + ["node", "bun", process.execPath].flatMap((command) => + [undefined, "Paseo", "custom-client"].map((entrypoint) => ({ command, entrypoint })), + ), + )( + "preserves explicit launch identity $entrypoint in $command while clearing inherited session env", + async ({ command, entrypoint }) => { let output = ""; let exited = Promise.resolve([]); const query = claudeQuery( { prompt: "", options: {} }, { runtimeSettings: { env: { CLAUDE_CODE_ENTRYPOINT: "sdk-ts" } }, - launchEnv: { CLAUDE_CODE_ENTRYPOINT: "sdk-cli" }, + launchEnv: entrypoint === undefined ? {} : { CLAUDE_CODE_ENTRYPOINT: entrypoint }, queryFactory: ({ options }) => { if (!options.spawnClaudeCodeProcess) { throw new Error("Missing Claude process launcher"); @@ -65,7 +69,10 @@ describe("Claude SDK env", () => { try { expect(await exited).toEqual([0, null]); - expect(JSON.parse(output)).toEqual({ entrypoint: "Paseo", parentSession: null }); + expect(JSON.parse(output)).toEqual({ + ...(entrypoint === undefined ? {} : { entrypoint }), + parentSession: null, + }); } finally { query.close(); } diff --git a/packages/server/src/server/agent/providers/claude/agent.history-load.test.ts b/packages/server/src/server/agent/providers/claude/agent.history-load.test.ts index 921b4018be..e2ea6850bb 100644 --- a/packages/server/src/server/agent/providers/claude/agent.history-load.test.ts +++ b/packages/server/src/server/agent/providers/claude/agent.history-load.test.ts @@ -1,3 +1,4 @@ +import { measureMainThreadWork } from "../../../../test-utils/main-thread-work.js"; import fs, { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { open } from "node:fs/promises"; import { performance } from "node:perf_hooks"; @@ -117,13 +118,6 @@ describe("ClaudeAgentSession persisted history load", () => { await file.close(); } const daemon = await createTestPaseoDaemon(); - let lastTick = performance.now(); - let longestGap = 0; - const probe = setInterval(() => { - const now = performance.now(); - longestGap = Math.max(longestGap, now - lastTick); - lastTick = now; - }, 2); let loading = true; let answeredDuringLoad = false; const health = fetch(`http://127.0.0.1:${daemon.port}/api/health`).then(async (response) => { @@ -134,33 +128,39 @@ describe("ClaudeAgentSession persisted history load", () => { }); let session: AgentSession | undefined; try { - session = await resume(replyFactory("live after large resume")); - let index = 0; - for await (const event of session.streamHistory()) { - expect(event).toEqual({ - type: "timeline", - provider: "claude", - timestamp: undefined, - item: { type: "assistant_message", text: `${index}:${text}` }, - }); - index++; - } - loading = false; - await health; - await new Promise((resolve) => setTimeout(resolve, 5)); + const { + result: { resumed: loadedSession, historyCount }, + blockingMs, + } = await measureMainThreadWork("Claude history main-thread work", async () => { + const resumed = await resume(replyFactory("live after large resume")); + session = resumed; + let index = 0; + for await (const event of resumed.streamHistory()) { + expect(event).toEqual({ + type: "timeline", + provider: "claude", + timestamp: undefined, + item: { type: "assistant_message", text: `${index}:${text}` }, + }); + index++; + } + loading = false; + await health; + return { resumed, historyCount: index }; + }); console.info( JSON.stringify({ bytes, count, - longestGap, + blockingMs, answeredDuringLoad, elapsedMs: performance.now() - startedAt, }), ); - expect(index).toBe(count); - expect(longestGap).toBeLessThan(50); + expect(historyCount).toBe(count); + expect(blockingMs).toBeLessThan(50); expect(answeredDuringLoad).toBe(true); - const live = await collectSessionTurnEvents(session, "follow up"); + const live = await collectSessionTurnEvents(loadedSession, "follow up"); expect( live .filter((event) => event.type === "timeline" && event.item.type === "assistant_message") @@ -169,7 +169,6 @@ describe("ClaudeAgentSession persisted history load", () => { { type: "assistant_message", messageId: "live-reply", text: "live after large resume" }, ]); } finally { - clearInterval(probe); await session?.close(); await daemon.close(); } @@ -615,6 +614,43 @@ describe("ClaudeAgentSession persisted history load", () => { ); }); + test("replays a message steered into a running turn as the user's message", async () => { + const queued = (commandMode: string, prompt: unknown, sourceUuid?: string) => ({ + type: "attachment", + uuid: `attachment-${commandMode}`, + parentUuid: "a1", + attachment: { + type: "queued_command", + commandMode, + prompt, + ...(sourceUuid ? { source_uuid: sourceUuid } : {}), + }, + }); + const entries = [ + { type: "user", uuid: "u1", parentUuid: null, message: { content: "first" } }, + { type: "assistant", uuid: "a1", parentUuid: "u1", message: { content: "working" } }, + queued("prompt", [{ type: "text", text: "steered while working" }], "steered-1"), + queued("task-notification", "t1"), + { type: "assistant", uuid: "a2", parentUuid: "a1", message: { content: "answer" } }, + ]; + mkdirSync(path.dirname(transcriptPath()), { recursive: true }); + writeFileSync(transcriptPath(), entries.map((entry) => JSON.stringify(entry)).join("\n")); + + const session = await resume(); + try { + const users = []; + for await (const event of session.streamHistory()) { + if (event.type === "timeline" && event.item.type === "user_message") users.push(event.item); + } + expect(users).toEqual([ + { type: "user_message", text: "first", messageId: "u1" }, + { type: "user_message", text: "steered while working", messageId: "steered-1" }, + ]); + } finally { + await session.close(); + } + }); + test("loads readable history when the temporary directory is unavailable", async () => { const file = transcriptPath(); const entry = { type: "assistant", message: { content: [{ type: "text", text: "saved" }] } }; diff --git a/packages/server/src/server/agent/providers/claude/agent.image-rendering.test.ts b/packages/server/src/server/agent/providers/claude/agent.image-rendering.test.ts index 5a06fea7fd..a772e544d1 100644 --- a/packages/server/src/server/agent/providers/claude/agent.image-rendering.test.ts +++ b/packages/server/src/server/agent/providers/claude/agent.image-rendering.test.ts @@ -13,8 +13,8 @@ const MATERIALIZED_PNG_PATH_PATTERN = /paseo-attachments(?:-[^\\/]+)?[\\/](?:[^\\/]+[\\/])?[0-9a-f]{64}\.png$/; interface ClaudeImageTestSession { - translateMessageToEvents(message: SDKMessage): AgentStreamEvent[]; - convertHistoryEntry(entry: unknown): AgentTimelineItem[]; + translateMessageToEvents(message: SDKMessage): Promise; + convertHistoryEntry(entry: unknown): Promise; } async function createSession(): Promise { @@ -157,7 +157,7 @@ describe("Claude tool_result image rendering", () => { test("emits the image as assistant markdown and keeps base64 out of the live tool output", async () => { const session = await createSession(); - const events = session.translateMessageToEvents(imageToolResultUserMessage()); + const events = await session.translateMessageToEvents(imageToolResultUserMessage()); const timelineItems = events .filter((event) => event.type === "timeline") @@ -181,7 +181,7 @@ describe("Claude tool_result image rendering", () => { test("replays the image as assistant markdown through history conversion", async () => { const session = await createSession(); - const items = session.convertHistoryEntry(imageToolResultHistoryEntry()); + const items = await session.convertHistoryEntry(imageToolResultHistoryEntry()); const [imageMessage, ...extraImages] = imageMessages(items); expect(extraImages).toEqual([]); @@ -202,7 +202,7 @@ describe("Claude tool_result image rendering", () => { test("keeps base64 out of an errored tool_result that carries an image", async () => { const session = await createSession(); - const events = session.translateMessageToEvents(erroredImageToolResultUserMessage()); + const events = await session.translateMessageToEvents(erroredImageToolResultUserMessage()); const timelineItems = events .filter((event) => event.type === "timeline") @@ -226,7 +226,7 @@ describe("Claude tool_result image rendering", () => { test("emits one image message per image block in a multi-image tool_result", async () => { const session = await createSession(); - const events = session.translateMessageToEvents(multiImageToolResultUserMessage()); + const events = await session.translateMessageToEvents(multiImageToolResultUserMessage()); const timelineItems = events .filter((event) => event.type === "timeline") diff --git a/packages/server/src/server/agent/providers/claude/agent.import-titles.test.ts b/packages/server/src/server/agent/providers/claude/agent.import-titles.test.ts index e20b8d6faf..a826645d4c 100644 --- a/packages/server/src/server/agent/providers/claude/agent.import-titles.test.ts +++ b/packages/server/src/server/agent/providers/claude/agent.import-titles.test.ts @@ -1,3 +1,4 @@ +import { constants as bufferConstants } from "node:buffer"; import * as fs from "node:fs/promises"; import * as os from "node:os"; import * as path from "node:path"; @@ -236,4 +237,64 @@ describe("importing a renamed Claude session", () => { await expect(importSession(sessionId)).rejects.toThrow(); }); + + test("reads the rename from a transcript too large to hold as one string", async () => { + const sessionId = "oversized-transcript"; + const projectDir = claudeProjectDirSync(SESSION_CWD, { configDir }); + await fs.mkdir(projectDir, { recursive: true }); + const transcript = path.join(projectDir, `${sessionId}.jsonl`); + // A hole stands in for the long session this used to fail on: the file only + // has to be longer than a string can be, and the rename sits at its end. + await fs.writeFile(transcript, ""); + await fs.truncate(transcript, bufferConstants.MAX_STRING_LENGTH + 1); + await fs.appendFile( + transcript, + `\n${[ + userRecord({ sessionId, content: "Trace the slow query" }), + { type: "custom-title", customTitle: "Slow query hunt", sessionId }, + ] + .map((record) => JSON.stringify(record)) + .join("\n")}\n`, + ); + + const imported = await importSession(sessionId); + + expect(imported.config.title).toBe("Slow query hunt"); + }); + + test("reads the rename from behind more records than one read covers", async () => { + const sessionId = "late-records-rename"; + await writeSession({ + sessionId, + records: [ + userRecord({ sessionId, content: "Review this project" }), + { type: "custom-title", customTitle: "Scrollback review", sessionId }, + // One record longer than a single read, then enough records to leave the + // rename several reads back from the end of the file. + userRecord({ sessionId, content: "x".repeat(128 * 1024) }), + ...Array.from({ length: 64 }, (_, index) => + userRecord({ sessionId, content: `${"y".repeat(4 * 1024)} ${index}` }), + ), + ], + }); + + const imported = await importSession(sessionId); + + expect(imported.config.title).toBe("Scrollback review"); + }); + + test("imports a large record after the last rename without repeatedly copying it", async () => { + const sessionId = "large-record-after-rename"; + await writeSession({ + sessionId, + records: [ + { type: "custom-title", customTitle: "Large attachment review", sessionId }, + userRecord({ sessionId, content: "x".repeat(96 * 1024 * 1024) }), + ], + }); + + const imported = await importSession(sessionId); + + expect(imported.config.title).toBe("Large attachment review"); + }); }); diff --git a/packages/server/src/server/agent/providers/claude/agent.interrupt-restart-regression.test.ts b/packages/server/src/server/agent/providers/claude/agent.interrupt-restart-regression.test.ts index 02a09ba44b..fa0266c355 100644 --- a/packages/server/src/server/agent/providers/claude/agent.interrupt-restart-regression.test.ts +++ b/packages/server/src/server/agent/providers/claude/agent.interrupt-restart-regression.test.ts @@ -349,8 +349,11 @@ async function startSteeredTurn(sessionId: string): Promise<{ expectedTurnId: start.value.turnId, clientMessageId: "steer-client", }); - expect(steered).toEqual({ status: "accepted" }); await waitFor(() => query?.prompts.length === 2); + expect(steered).toEqual({ + status: "accepted", + providerMessageId: query?.prompts[1]?.uuid, + }); return { session, query: () => query, turn }; } @@ -972,7 +975,10 @@ test("steers an autonomous turn through its existing query without restarting it const steeredTimeline = await autonomousEvents.next(); const completion = await autonomousEvents.next(); - expect(steer).toEqual({ status: "accepted" }); + expect(steer).toEqual({ + status: "accepted", + providerMessageId: queryRef?.prompts[1]?.uuid, + }); expect(queryFactory).toHaveBeenCalledTimes(1); expect(queryRef?.interrupt).not.toHaveBeenCalled(); expect(queryRef?.prompts.map((prompt) => prompt.text)).toEqual(["seed prompt", "steer prompt"]); diff --git a/packages/server/src/server/agent/providers/claude/agent.rewind-anchors.test.ts b/packages/server/src/server/agent/providers/claude/agent.rewind-anchors.test.ts index 1b1932e9cd..ed9b324ff4 100644 --- a/packages/server/src/server/agent/providers/claude/agent.rewind-anchors.test.ts +++ b/packages/server/src/server/agent/providers/claude/agent.rewind-anchors.test.ts @@ -1,7 +1,11 @@ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; import { describe, expect, test, vi } from "vitest"; import { createTestLogger } from "../../../../test-utils/test-logger.js"; import { ClaudeAgentClient } from "./agent.js"; +import { claudeProjectDir } from "./project-dir.js"; import { FakeClaudeSdk } from "./test-rewind-claude-sdk.js"; import { streamSession } from "../test-utils/session-stream-adapter.js"; import type { AgentSession } from "../../agent-sdk-types.js"; @@ -267,3 +271,49 @@ describe("Claude rewind after a turn whose last assistant message came from a su expect(rewindSdk.recordedForks).toEqual([{ upToMessageId: "assistant-1" }]); }); }); + +describe("Claude rewind to a message steered into a running turn", () => { + test("forks at the entry Claude read the message after", async () => { + const configDir = mkdtempSync(path.join(tmpdir(), "claude-rewind-steer-")); + const previousConfigDir = process.env.CLAUDE_CONFIG_DIR; + process.env.CLAUDE_CONFIG_DIR = configDir; + const conversation = createConversation([{ assistantMessageId: "assistant-1" }]); + const rewindSdk = new FakeClaudeSdk(); + const session = await createSession(conversation, rewindSdk); + + try { + await runTurns(session, 1); + // A steered message opens no turn: Claude Code records it as a queued_command attachment + // under the uuid Paseo minted for it, hung off the entry it was read after. + const projectDir = await claudeProjectDir(process.cwd(), { configDir }); + mkdirSync(projectDir, { recursive: true }); + const entries = [ + { type: "user", uuid: conversation.userMessageIds[0], parentUuid: null }, + { type: "assistant", uuid: "assistant-1", parentUuid: conversation.userMessageIds[0] }, + { type: "user", uuid: "tool-result-1", parentUuid: "assistant-1" }, + { + type: "attachment", + uuid: "queued-command-1", + parentUuid: "tool-result-1", + attachment: { type: "queued_command", source_uuid: "steered-message-1" }, + }, + ]; + writeFileSync( + path.join(projectDir, `${SESSION_ID}.jsonl`), + entries.map((entry) => `${JSON.stringify(entry)}\n`).join(""), + ); + + await session.revertConversation?.({ messageId: "steered-message-1" }); + } finally { + await session.close(); + if (previousConfigDir === undefined) { + delete process.env.CLAUDE_CONFIG_DIR; + } else { + process.env.CLAUDE_CONFIG_DIR = previousConfigDir; + } + rmSync(configDir, { recursive: true, force: true }); + } + + expect(rewindSdk.recordedForks).toEqual([{ upToMessageId: "tool-result-1" }]); + }); +}); diff --git a/packages/server/src/server/agent/providers/claude/agent.sub-agent-replay.test.ts b/packages/server/src/server/agent/providers/claude/agent.sub-agent-replay.test.ts index 666e701649..91007aa7ce 100644 --- a/packages/server/src/server/agent/providers/claude/agent.sub-agent-replay.test.ts +++ b/packages/server/src/server/agent/providers/claude/agent.sub-agent-replay.test.ts @@ -8,6 +8,7 @@ import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; import { createTestLogger } from "../../../../test-utils/test-logger.js"; import type { AgentStreamEvent } from "../../agent-sdk-types.js"; +import { streamSession } from "../test-utils/session-stream-adapter.js"; import { ClaudeAgentClient } from "./agent.js"; import { claudeProjectDirSync } from "./project-dir.js"; @@ -77,6 +78,29 @@ function sidechainEntry(options: { agentId?: string; stopReason?: string | null }); } +function buildQueryMock(events: unknown[]) { + let index = 0; + return { + next: vi.fn(async () => { + if (index >= events.length) return { done: true, value: undefined }; + const value = events[index]; + index += 1; + return { done: false, value }; + }), + interrupt: vi.fn(async () => undefined), + return: vi.fn(async () => undefined), + close: vi.fn(() => undefined), + setPermissionMode: vi.fn(async () => undefined), + setModel: vi.fn(async () => undefined), + supportedModels: vi.fn(async () => []), + supportedCommands: vi.fn(async () => []), + rewindFiles: vi.fn(async () => ({ canRewind: true })), + [Symbol.asyncIterator]() { + return this; + }, + }; +} + describe("ClaudeAgentSession persisted subagent replay", () => { const logger = createTestLogger(); const queryFactory = vi.fn(() => { @@ -422,6 +446,237 @@ describe("ClaudeAgentSession persisted subagent replay", () => { }); }); + describe("a background subagent", () => { + // Shapes recorded from Claude Code 2.1.x: the launch returns at once with an async result, + // and a child stopped by an interrupt ends on the interrupt placeholder, not an end_turn. + function backgroundLaunch(): string[] { + return [ + parentEntry([ + { + type: "tool_use", + id: TOOL_USE_ID, + name: "Agent", + input: { + subagent_type: "general-purpose", + description: "probe sleeper", + run_in_background: true, + }, + }, + ]), + JSON.stringify({ + type: "user", + sessionId: "replay-session", + timestamp: "2026-07-26T06:27:48.000Z", + message: { + role: "user", + content: [ + { + type: "tool_result", + tool_use_id: TOOL_USE_ID, + content: [ + { + type: "text", + text: `Async agent launched successfully.\nagentId: ${AGENT_ID}`, + }, + ], + }, + ], + }, + toolUseResult: { isAsync: true, status: "async_launched", agentId: AGENT_ID }, + }), + ]; + } + + function readStatus(event: { status?: string }): string | undefined { + return event.status; + } + + function interruptedChild(): string[] { + return [ + JSON.stringify({ + type: "assistant", + isSidechain: true, + agentId: AGENT_ID, + timestamp: "2026-07-26T06:27:50.000Z", + message: { + role: "assistant", + content: [{ type: "tool_use", id: "toolu_child_bash", name: "Bash", input: {} }], + stop_reason: "tool_use", + }, + }), + JSON.stringify({ + type: "user", + isSidechain: true, + agentId: AGENT_ID, + timestamp: "2026-07-26T06:28:05.000Z", + message: { + role: "user", + content: [ + { + type: "tool_result", + tool_use_id: "toolu_child_bash", + content: "The user doesn't want to proceed with this tool use.", + is_error: true, + }, + ], + }, + }), + JSON.stringify({ + type: "user", + isSidechain: true, + agentId: AGENT_ID, + timestamp: "2026-07-26T06:28:05.001Z", + message: { + role: "user", + content: [{ type: "text", text: "[Request interrupted by user for tool use]" }], + }, + }), + ]; + } + + test.each([ + ["the meta sidecar", JSON.stringify({ toolUseId: TOOL_USE_ID })], + ["the legacy scrape", null], + ])("is canceled when an interrupt stopped it, linked through %s", async (_link, meta) => { + writeSession({ parentLines: backgroundLaunch(), meta, sidechainLines: interruptedChild() }); + + expect(upserts(await replayDescriptors()).at(-1)).toMatchObject({ + id: TOOL_USE_ID, + status: "canceled", + }); + }); + + test("stays running when the child was given a new prompt after the interrupt", async () => { + writeSession({ + parentLines: backgroundLaunch(), + meta: JSON.stringify({ toolUseId: TOOL_USE_ID }), + sidechainLines: [ + ...interruptedChild(), + JSON.stringify({ + type: "user", + isSidechain: true, + agentId: AGENT_ID, + timestamp: "2026-07-26T06:29:00.000Z", + message: { role: "user", content: [{ type: "text", text: "Carry on with the task." }] }, + }), + ], + }); + + const statuses = upserts(await replayDescriptors()).map(readStatus); + expect(statuses).not.toContain("canceled"); + expect(statuses).toContain("running"); + }); + + test.each(["interrupted", "running"])( + "ignores an API request copy of a %s child's launch result", + async (state) => { + const launch = backgroundLaunch(); + const result = JSON.parse(launch[1]!); + writeSession({ + parentLines: [ + ...launch, + JSON.stringify({ + type: "api-request-blob", + sessionId: "replay-session", + hash: "request-copy", + message: result.message, + }), + ], + meta: JSON.stringify({ toolUseId: TOOL_USE_ID }), + sidechainLines: + state === "interrupted" + ? interruptedChild() + : [sidechainEntry({ stopReason: "tool_use" })], + }); + expect(upserts(await replayDescriptors()).at(-1)).toMatchObject({ + id: TOOL_USE_ID, + status: state === "interrupted" ? "canceled" : "running", + }); + }, + ); + + test("stays running while the child has not finished", async () => { + writeSession({ + parentLines: backgroundLaunch(), + meta: JSON.stringify({ toolUseId: TOOL_USE_ID }), + sidechainLines: [sidechainEntry({ stopReason: "tool_use" })], + }); + + const statuses = upserts(await replayDescriptors()).map(readStatus); + expect(statuses).not.toContain("completed"); + expect(statuses).toContain("running"); + }); + + function taskNotification(status: string, form = "user"): string { + const text = `\n${AGENT_ID}\n${TOOL_USE_ID}\n${status}\nBackground task ended\n`; + const records = { + user: { message: { role: "user", content: [{ type: "text", text }] } }, + system: { + subtype: "task_notification", + task_id: AGENT_ID, + tool_use_id: TOOL_USE_ID, + status, + }, + "queue-operation": { operation: "enqueue", content: text }, + }; + return JSON.stringify({ + type: form, + timestamp: "2026-07-26T06:29:00.000Z", + ...records[form as keyof typeof records], + }); + } + + for (const form of ["user", "system", "queue-operation"]) { + test.each([ + ["completed", "completed"], + ["failed", "failed"], + ["killed", "canceled"], + ["stopped", "canceled"], + ])( + `restores a %s task notification from ${form} when the child stop_reason is null`, + async (status, expected) => { + writeSession({ + parentLines: [...backgroundLaunch(), taskNotification(status, form)], + meta: JSON.stringify({ toolUseId: TOOL_USE_ID }), + sidechainLines: [sidechainEntry({ stopReason: null })], + }); + expect(upserts(await replayDescriptors()).at(-1)).toMatchObject({ + id: TOOL_USE_ID, + status: expected, + }); + }, + ); + } + + test("prefers a stopped notification over the child's end_turn", async () => { + writeSession({ + parentLines: [...backgroundLaunch(), taskNotification("stopped")], + meta: JSON.stringify({ toolUseId: TOOL_USE_ID }), + sidechainLines: [sidechainEntry({ stopReason: "end_turn" })], + }); + expect(upserts(await replayDescriptors()).at(-1)).toMatchObject({ status: "canceled" }); + }); + + test("does not invent an outcome for an unknown notification status", async () => { + writeSession({ + parentLines: [...backgroundLaunch(), taskNotification("unknown")], + meta: JSON.stringify({ toolUseId: TOOL_USE_ID }), + sidechainLines: [sidechainEntry({ stopReason: null })], + }); + expect(upserts(await replayDescriptors()).at(-1)).toMatchObject({ status: "running" }); + }); + + test("completes from the child's own end_turn", async () => { + writeSession({ + parentLines: backgroundLaunch(), + meta: JSON.stringify({ toolUseId: TOOL_USE_ID }), + sidechainLines: [sidechainEntry({ stopReason: "end_turn" })], + }); + + expect(upserts(await replayDescriptors()).at(-1)).toMatchObject({ status: "completed" }); + }); + }); + test("does not replay a skill-spawned subagent the parent never named", async () => { // The reported bug. A /code-review subagent has no Task tool_use, so its sidecar carries only // agentType and its id appears nowhere in the parent — it used to replay as running forever, @@ -506,7 +761,7 @@ describe("ClaudeAgentSession persisted subagent replay", () => { ); }, 120_000); - test("limits retained child shell output to the timeline's existing content limit", async () => { + test("limits retained child shell output to the timeline item budget", async () => { const output = "x".repeat(128 * 1024); writeSession({ parentLines: [taskToolUse(), taskToolResult()], @@ -551,7 +806,10 @@ describe("ClaudeAgentSession persisted subagent replay", () => { type: "timeline", id: TOOL_USE_ID, item: expect.objectContaining({ - detail: expect.objectContaining({ type: "shell", output: output.slice(0, 64 * 1024) }), + detail: expect.objectContaining({ + type: "shell", + output: expect.stringMatching(/^x+…\[truncated \d+\.\d KB\]$/), + }), }), }), ]); @@ -1028,4 +1286,106 @@ describe("ClaudeAgentSession persisted subagent replay", () => { ); expect(items).toEqual([{ type: "assistant_message", text: report }]); }); + + test("keeps a subagent resumed after the session reopens on the row its transcript restored", async () => { + // Verified on the wire (Claude Code 2.1.309): SendMessage resumes a finished subagent under its + // original task_id but a new tool_use_id, and the child's frames still name the original Task + // call as their parent. A reopened session only knows that child from its transcript. + writeSession({ + parentLines: [taskToolUse(), taskToolResult()], + meta: JSON.stringify({ agentType: "general-purpose", toolUseId: TOOL_USE_ID }), + sidechainLines: [ + JSON.stringify({ + type: "assistant", + isSidechain: true, + agentId: AGENT_ID, + sessionId: "replay-session", + timestamp: "2026-07-26T06:27:50.000Z", + effort: "high", + message: { + role: "assistant", + model: "claude-sonnet-5", + content: [{ type: "text", text: "summary of the docs" }], + stop_reason: "end_turn", + }, + }), + ], + }); + const liveQuery = vi.fn(() => + buildQueryMock([ + { + type: "system", + subtype: "init", + session_id: "replay-session", + permissionMode: "default", + }, + { + type: "system", + subtype: "task_started", + task_id: AGENT_ID, + tool_use_id: "toolu_send_message", + description: "Summarize the docs", + subagent_type: "general-purpose", + task_type: "local_agent", + is_backgrounded: true, + prompt: "Summarize them again", + }, + { + type: "assistant", + parent_tool_use_id: TOOL_USE_ID, + session_id: "replay-session", + message: { + id: "msg_resumed_child", + role: "assistant", + model: "claude-opus-5", + content: [{ type: "text", text: "summary again" }], + }, + }, + { + type: "system", + subtype: "task_updated", + task_id: AGENT_ID, + patch: { status: "completed" }, + }, + { + type: "result", + subtype: "success", + usage: { input_tokens: 1, cache_read_input_tokens: 0, output_tokens: 1 }, + total_cost_usd: 0, + }, + ]), + ); + const session = await new ClaudeAgentClient({ + logger, + queryFactory: liveQuery, + resolveVersion: async () => "2.1.309", + resolveBinary: async () => "/test/claude/bin", + }).resumeSession({ provider: "claude", sessionId: "replay-session" }, { cwd }); + const events: AgentStreamEvent[] = []; + for await (const event of streamSession(session, "Ask it to summarize again")) { + events.push(event); + if (event.type === "turn_completed" || event.type === "turn_failed") break; + } + await session.close(); + + const live = events.flatMap((event) => + event.type === "provider_subagent" ? [event.event] : [], + ); + expect(new Set(live.map((event) => event.id))).toEqual(new Set([TOOL_USE_ID])); + expect(live).toContainEqual( + expect.objectContaining({ + type: "upsert", + id: TOOL_USE_ID, + subtitle: "general-purpose · Opus 5 · High", + }), + ); + expect(live).toContainEqual( + expect.objectContaining({ + type: "timeline", + id: TOOL_USE_ID, + item: expect.objectContaining({ type: "assistant_message", text: "summary again" }), + }), + ); + expect(live.at(-1)).toMatchObject({ type: "upsert", id: TOOL_USE_ID, status: "completed" }); + }); }); diff --git a/packages/server/src/server/agent/providers/claude/agent.sub-agent-sidechain.test.ts b/packages/server/src/server/agent/providers/claude/agent.sub-agent-sidechain.test.ts index 84293afa6a..f219baa1b1 100644 --- a/packages/server/src/server/agent/providers/claude/agent.sub-agent-sidechain.test.ts +++ b/packages/server/src/server/agent/providers/claude/agent.sub-agent-sidechain.test.ts @@ -273,7 +273,7 @@ describe("ClaudeAgentSession sub-agent sidechain updates", () => { queryFactory.mockReset(); }); - test("accumulates lightweight sub_agent detail and preserves callId lifecycle collapse", async () => { + test("labels the Task card from its input and preserves callId lifecycle collapse", async () => { const session = await new ClaudeAgentClient({ logger, queryFactory, @@ -307,9 +307,7 @@ describe("ClaudeAgentSession sub-agent sidechain updates", () => { expect(latest.detail.subAgentType).toBe("Explore"); expect(latest.detail.description).toBe("Inspect repository structure"); - expect(latest.detail.log).toContain("[Read] README.md"); - expect(latest.detail.log).toContain("[Edit] src/index.ts"); - expect(latest.detail.log).not.toContain("VERY_LARGE_OLD_STRING"); + expect(latest.detail.log).toBe(""); const rows: AgentTimelineRow[] = timelineToolCalls.map((item, index) => ({ seq: index + 1, @@ -396,10 +394,7 @@ describe("ClaudeAgentSession sub-agent sidechain updates", () => { .map((event) => event.item) .at(-1); - expect(latestSubAgentUpdate?.detail).toMatchObject({ - type: "sub_agent", - log: expect.stringContaining("[Read] README.md"), - }); + expect(latestSubAgentUpdate?.detail).toMatchObject({ type: "sub_agent", log: "" }); }); test("routes a resumed SendMessage sidechain to the original child without a second Task card", async () => { @@ -553,7 +548,7 @@ describe("ClaudeAgentSession sub-agent sidechain updates", () => { ).toMatchObject({ type: "upsert", id: "task-tail-1", status: "failed" }); }); - test("tails sub-agent actions instead of dropping latest entries at cap", async () => { + test("keeps the Task card the same size while the child runs", async () => { queryFactory.mockImplementation(() => buildQueryMock(buildTailScenarioEvents(205))); const session = await new ClaudeAgentClient({ @@ -568,24 +563,27 @@ describe("ClaudeAgentSession sub-agent sidechain updates", () => { const events = await collectUntilTerminal(streamSession(session, "delegate work")); await session.close(); - const timelineToolCalls = events - .filter( - (event): event is Extract => - event.type === "timeline" && event.item.type === "tool_call", + const runningCards = events + .flatMap((event) => + event.type === "timeline" && + event.item.type === "tool_call" && + event.item.callId === "task-tail-1" && + event.item.status === "running" && + event.item.detail.type === "sub_agent" + ? [event.item] + : [], ) - .map((event) => event.item) - .filter((item) => item.callId === "task-tail-1"); - const subAgentUpdates = timelineToolCalls.filter((item) => item.detail.type === "sub_agent"); - const latest = subAgentUpdates[subAgentUpdates.length - 1]; - expect(latest).toBeDefined(); - if (!latest || latest.detail.type !== "sub_agent") { - throw new Error("expected sub_agent detail"); - } + .map((item) => JSON.stringify(item)); + expect(runningCards).toHaveLength(1); - expect(latest.detail.log).not.toContain("[Read] file-1.md"); - expect(latest.detail.log).not.toContain("[Read] file-5.md"); - expect(latest.detail.log).toContain("[Read] file-6.md"); - expect(latest.detail.log).toContain("[Read] file-205.md"); + const childToolCalls = events.filter( + (event) => + event.type === "provider_subagent" && + event.event.type === "timeline" && + event.event.id === "task-tail-1" && + event.event.item.type === "tool_call", + ); + expect(childToolCalls).toHaveLength(205); }); test("keeps a long main-thread tool call out of the subagents track", async () => { diff --git a/packages/server/src/server/agent/providers/claude/agent.test.ts b/packages/server/src/server/agent/providers/claude/agent.test.ts index 2b2c725269..758fad2e8f 100644 --- a/packages/server/src/server/agent/providers/claude/agent.test.ts +++ b/packages/server/src/server/agent/providers/claude/agent.test.ts @@ -32,7 +32,7 @@ import type { AgentAttachment } from "@getpaseo/protocol/messages"; import { buildAgentPrompt, renderPromptAttachmentAsText } from "../../prompt-attachments.js"; interface TestClaudeSession { - translateMessageToEvents(message: SDKMessage): AgentStreamEvent[]; + translateMessageToEvents(message: SDKMessage): Promise; close(): Promise; } @@ -53,7 +53,7 @@ afterEach(() => { }); describe("convertClaudeHistoryEntry", () => { - test("maps user tool results to timeline items", () => { + test("maps user tool results to timeline items", async () => { const toolUseId = "toolu_test"; const entry = { type: "user", @@ -79,14 +79,14 @@ describe("convertClaudeHistoryEntry", () => { ]; const mapBlocks = vi.fn().mockReturnValue(stubTimeline); - const result = convertClaudeHistoryEntry(entry, mapBlocks); + const result = await convertClaudeHistoryEntry(entry, mapBlocks); expect(result).toEqual(stubTimeline); expect(mapBlocks).toHaveBeenCalledTimes(1); expect(Array.isArray(mapBlocks.mock.calls[0][0])).toBe(true); }); - test("replays persisted Claude tool results as completed tool calls", () => { + test("replays persisted Claude tool results as completed tool calls", async () => { const entry = { type: "user", message: { @@ -124,12 +124,12 @@ describe("convertClaudeHistoryEntry", () => { const mapPersistedToolResultBlocks = (): AgentTimelineItem[] => completedToolCall; - expect(convertClaudeHistoryEntry(entry, mapPersistedToolResultBlocks)).toEqual( + expect(await convertClaudeHistoryEntry(entry, mapPersistedToolResultBlocks)).toEqual( completedToolCall, ); }); - test("returns user messages when no tool blocks exist", () => { + test("returns user messages when no tool blocks exist", async () => { const entry = { type: "user", message: { @@ -138,7 +138,7 @@ describe("convertClaudeHistoryEntry", () => { }, }; - expect(convertClaudeHistoryEntry(entry, () => [])).toEqual([ + expect(await convertClaudeHistoryEntry(entry, () => [])).toEqual([ { type: "user_message", text: "Run npm test", @@ -146,7 +146,7 @@ describe("convertClaudeHistoryEntry", () => { ]); }); - test("converts compact boundary metadata variants", () => { + test("converts compact boundary metadata variants", async () => { const fixtures = [ { entry: { @@ -175,7 +175,7 @@ describe("convertClaudeHistoryEntry", () => { ] as const; for (const fixture of fixtures) { - expect(convertClaudeHistoryEntry(fixture.entry, () => [])).toEqual([ + expect(await convertClaudeHistoryEntry(fixture.entry, () => [])).toEqual([ { type: "compaction", status: "completed", @@ -186,7 +186,7 @@ describe("convertClaudeHistoryEntry", () => { } }); - test("skips synthetic user entries", () => { + test("skips synthetic user entries", async () => { const entry = { type: "user", isSynthetic: true, @@ -197,13 +197,13 @@ describe("convertClaudeHistoryEntry", () => { }; const mapBlocks = vi.fn().mockReturnValue([]); - const result = convertClaudeHistoryEntry(entry, mapBlocks); + const result = await convertClaudeHistoryEntry(entry, mapBlocks); expect(result).toEqual([]); expect(mapBlocks).not.toHaveBeenCalled(); }); - test("skips meta user entries from Claude skill loading", () => { + test("skips meta user entries from Claude skill loading", async () => { const entry = { type: "user", isMeta: true, @@ -219,13 +219,13 @@ describe("convertClaudeHistoryEntry", () => { }; const mapBlocks = vi.fn().mockReturnValue([]); - const result = convertClaudeHistoryEntry(entry, mapBlocks); + const result = await convertClaudeHistoryEntry(entry, mapBlocks); expect(result).toEqual([]); expect(mapBlocks).not.toHaveBeenCalled(); }); - test("skips interrupt placeholder transcript noise", () => { + test("skips interrupt placeholder transcript noise", async () => { const interruptEntry = { type: "user", message: { @@ -246,11 +246,11 @@ describe("convertClaudeHistoryEntry", () => { .fn() .mockReturnValue([{ type: "assistant_message", text: "No response requested." }]); - expect(convertClaudeHistoryEntry(interruptEntry, mapBlocks)).toEqual([]); - expect(convertClaudeHistoryEntry(assistantNoiseEntry, mapBlocks)).toEqual([]); + expect(await convertClaudeHistoryEntry(interruptEntry, mapBlocks)).toEqual([]); + expect(await convertClaudeHistoryEntry(assistantNoiseEntry, mapBlocks)).toEqual([]); }); - test("skips messages (model switch, /context, etc.)", () => { + test("skips messages (model switch, /context, etc.)", async () => { // Real entries from Claude Code JSONL history files const modelSwitch = { type: "user", @@ -305,24 +305,24 @@ describe("convertClaudeHistoryEntry", () => { const mapBlocks = vi.fn().mockReturnValue([]); - expect(convertClaudeHistoryEntry(modelSwitch, mapBlocks)).toEqual([]); - expect(convertClaudeHistoryEntry(modelSwitchWithAnsi, mapBlocks)).toEqual([]); - expect(convertClaudeHistoryEntry(contextDump, mapBlocks)).toEqual([]); - expect(convertClaudeHistoryEntry(planMode, mapBlocks)).toEqual([]); - expect(convertClaudeHistoryEntry(goodbye, mapBlocks)).toEqual([]); - expect(convertClaudeHistoryEntry(empty, mapBlocks)).toEqual([]); + expect(await convertClaudeHistoryEntry(modelSwitch, mapBlocks)).toEqual([]); + expect(await convertClaudeHistoryEntry(modelSwitchWithAnsi, mapBlocks)).toEqual([]); + expect(await convertClaudeHistoryEntry(contextDump, mapBlocks)).toEqual([]); + expect(await convertClaudeHistoryEntry(planMode, mapBlocks)).toEqual([]); + expect(await convertClaudeHistoryEntry(goodbye, mapBlocks)).toEqual([]); + expect(await convertClaudeHistoryEntry(empty, mapBlocks)).toEqual([]); // Real user messages must NOT be filtered const realMessage = { type: "user", message: { role: "user", content: "fix the bug in auth.ts" }, }; - expect(convertClaudeHistoryEntry(realMessage, mapBlocks)).toEqual([ + expect(await convertClaudeHistoryEntry(realMessage, mapBlocks)).toEqual([ { type: "user_message", text: "fix the bug in auth.ts" }, ]); }); - test("maps task notifications to synthetic tool calls", () => { + test("maps task notifications to synthetic tool calls", async () => { const entry = { type: "system", subtype: "task_notification", @@ -333,7 +333,7 @@ describe("convertClaudeHistoryEntry", () => { output_file: "/tmp/bg-fail-1.txt", }; - expect(convertClaudeHistoryEntry(entry, () => [])).toEqual([ + expect(await convertClaudeHistoryEntry(entry, () => [])).toEqual([ { type: "tool_call", callId: "task_notification_task-note-system-1", @@ -357,7 +357,7 @@ describe("convertClaudeHistoryEntry", () => { ]); }); - test("maps queue-operation task notifications to synthetic tool calls", () => { + test("maps queue-operation task notifications to synthetic tool calls", async () => { const entry = { type: "queue-operation", operation: "enqueue", @@ -372,7 +372,7 @@ describe("convertClaudeHistoryEntry", () => { ].join("\n"), }; - expect(convertClaudeHistoryEntry(entry, () => [])).toEqual([ + expect(await convertClaudeHistoryEntry(entry, () => [])).toEqual([ { type: "tool_call", callId: "task_notification_task-note-queue-1", @@ -396,7 +396,7 @@ describe("convertClaudeHistoryEntry", () => { ]); }); - test("passes assistant content blocks through to the mapper", () => { + test("passes assistant content blocks through to the mapper", async () => { const entry = { type: "assistant", message: { @@ -414,7 +414,7 @@ describe("convertClaudeHistoryEntry", () => { ]; const mapBlocks = vi.fn().mockReturnValue(mappedTimeline); - expect(convertClaudeHistoryEntry(entry, mapBlocks)).toEqual(mappedTimeline); + expect(await convertClaudeHistoryEntry(entry, mapBlocks)).toEqual(mappedTimeline); expect(mapBlocks).toHaveBeenCalledWith(entry.message.content); }); }); @@ -887,6 +887,68 @@ describe("ClaudeAgentSession features", () => { await session.close(); }); + test("keeps an extraArgs settings file when Paseo sets Claude flag settings", async () => { + const settingsDir = await fs.mkdtemp(path.join(os.tmpdir(), "paseo-claude-settings-")); + const settingsPath = path.join(settingsDir, "settings.json"); + await fs.writeFile( + settingsPath, + JSON.stringify({ env: { ENABLE_TOOL_SEARCH: "false" }, permissions: { deny: ["Monitor"] } }), + ); + const { queryFactory } = createQueryMock(); + const client = new ClaudeAgentClient({ + logger, + queryFactory, + resolveBinary: async () => "/test/claude/bin", + }); + const session = await client.createSession({ + provider: "claude", + cwd: process.cwd(), + model: "claude-opus-5-5", + providerOptions: { + extraArgs: { chrome: null, settings: settingsPath }, + }, + }); + + await session.startTurn("hello"); + + const options = queryFactory.mock.calls[0]?.[0].options; + expect(options?.extraArgs).toEqual({ chrome: null }); + expect(options?.settings).toEqual({ + env: { ENABLE_TOOL_SEARCH: "false" }, + permissions: { deny: ["Monitor"] }, + fastMode: false, + }); + await session.close(); + await fs.rm(settingsDir, { recursive: true, force: true }); + }); + + test("keeps inline extraArgs settings JSON for internal agents", async () => { + const { queryFactory } = createQueryMock(); + const client = new ClaudeAgentClient({ + logger, + queryFactory, + resolveBinary: async () => "/test/claude/bin", + }); + const session = await client.createSession({ + provider: "claude", + cwd: process.cwd(), + internal: true, + providerOptions: { + extraArgs: { settings: '{"env":{"ENABLE_TOOL_SEARCH":"false"}}' }, + }, + }); + + await session.startTurn("hello"); + + const options = queryFactory.mock.calls[0]?.[0].options; + expect(options?.extraArgs).toEqual({}); + expect(options?.settings).toEqual({ + env: { ENABLE_TOOL_SEARCH: "false" }, + disableAllHooks: true, + }); + await session.close(); + }); + test("lists fast mode only for supported Opus models", async () => { const client = new ClaudeAgentClient({ logger, resolveBinary: async () => "/test/claude/bin" }); @@ -1162,16 +1224,17 @@ describe("ClaudeAgentSession features", () => { const iterator = input[Symbol.asyncIterator](); await expect(iterator.next()).resolves.toMatchObject({ value: { type: "user" } }); - await expect( - session.steerActiveTurn?.("same turn follow-up", { - expectedTurnId: turnId, - clientMessageId: "steer-client-id", - }), - ).resolves.toEqual({ status: "accepted" }); + const admission = await session.steerActiveTurn?.("same turn follow-up", { + expectedTurnId: turnId, + clientMessageId: "steer-client-id", + }); + expect(admission).toEqual({ status: "accepted", providerMessageId: expect.any(String) }); + if (admission?.status !== "accepted") throw new Error("Expected steer admission"); await expect(iterator.next()).resolves.toMatchObject({ value: { type: "user", priority: "next", + uuid: admission.providerMessageId, message: { content: [{ type: "text", text: "same turn follow-up" }] }, }, }); @@ -1208,7 +1271,7 @@ describe("ClaudeAgentSession features", () => { input: Record, options: Record, ): Promise; - translateMessageToEvents(message: SDKMessage): AgentStreamEvent[]; + translateMessageToEvents(message: SDKMessage): Promise; }; try { @@ -1229,7 +1292,7 @@ describe("ClaudeAgentSession features", () => { expectedTurnId: turnId, clearPendingPermissions: true, }), - ).resolves.toEqual({ status: "accepted" }); + ).resolves.toEqual({ status: "accepted", providerMessageId: expect.any(String) }); await expect(firstPermission).resolves.toMatchObject({ behavior: "deny", interrupt: undefined, @@ -1248,7 +1311,7 @@ describe("ClaudeAgentSession features", () => { ), ).resolves.toMatchObject({ behavior: "deny", interrupt: undefined }); - internal.translateMessageToEvents({ + await internal.translateMessageToEvents({ type: "command_lifecycle", command_uuid: steerUuid, state: "started", @@ -1288,7 +1351,7 @@ describe("ClaudeAgentSession features", () => { const permission = internal.handlePermissionRequest("Write", {}, { toolUseID: "tool-1" }); await expect( session.steerActiveTurn?.("system notification", { expectedTurnId: turnId }), - ).resolves.toEqual({ status: "accepted" }); + ).resolves.toEqual({ status: "accepted", providerMessageId: expect.any(String) }); expect(session.getPendingPermissions()).toHaveLength(1); const requestId = session.getPendingPermissions()[0]!.id; await session.respondToPermission(requestId, { behavior: "deny", message: "test cleanup" }); @@ -2395,7 +2458,7 @@ describe("ClaudeAgentSession context window usage", () => { test("emits canonical task snapshots from Claude TaskCreate results", async () => { const session = await createSessionForTest(); try { - session.translateMessageToEvents({ + await session.translateMessageToEvents({ type: "assistant", message: { content: [ @@ -2409,7 +2472,7 @@ describe("ClaudeAgentSession context window usage", () => { }, } as unknown as SDKMessage); - const events = session.translateMessageToEvents({ + const events = await session.translateMessageToEvents({ type: "user", message: { content: [{ type: "tool_result", tool_use_id: "task-create-1", content: "created" }], @@ -3611,9 +3674,9 @@ describe("ClaudeAgentSession context window usage", () => { ]); try { - const compactEvents = (session as unknown as TestClaudeSession).translateMessageToEvents( - createCompactBoundary(), - ); + const compactEvents = await ( + session as unknown as TestClaudeSession + ).translateMessageToEvents(createCompactBoundary()); expect(compactEvents).toContainEqual( expect.objectContaining({ type: "usage_updated", @@ -3799,7 +3862,7 @@ describe("ClaudeAgentSession context window usage", () => { test("result.result is surfaced as an assistant message when no model output was produced", async () => { const session = await createSessionForTest(); - const events = session.translateMessageToEvents({ + const events = await session.translateMessageToEvents({ type: "result", subtype: "success", result: "Unknown command: /foo-doesnt-exist", @@ -3834,7 +3897,7 @@ describe("ClaudeAgentSession context window usage", () => { test("result.result is not duplicated when the model produced output during the turn", async () => { const session = await createSessionForTest(); - const events = session.translateMessageToEvents({ + const events = await session.translateMessageToEvents({ type: "result", subtype: "success", result: "Here is the answer.", diff --git a/packages/server/src/server/agent/providers/claude/agent.ts b/packages/server/src/server/agent/providers/claude/agent.ts index 55fb128578..0d180b5801 100644 --- a/packages/server/src/server/agent/providers/claude/agent.ts +++ b/packages/server/src/server/agent/providers/claude/agent.ts @@ -33,7 +33,9 @@ import { mapTaskNotificationSystemRecordToToolCall, mapTaskNotificationUserContentToToolCall, readTaskNotificationToolUseIdFromHistoryRecord, + readTaskNotificationFromHistoryRecord, } from "./task-notification-tool-call.js"; +import { isClaudeInterruptPlaceholderText } from "./interrupt-placeholder.js"; import { getClaudeContextWindowMaxTokens, getClaudeModelsWithSettings, @@ -46,6 +48,7 @@ import { parseClaudeCodeVersion, resolveClaudeDisabledThinkingForModel, } from "./model-manifest.js"; +import { expandTilde } from "../../../../utils/path.js"; import { parsePartialJsonObject } from "./partial-json.js"; import { withClaudeReplayHistory, type ClaudeReplayHistory } from "./transcript-history.js"; import { ClaudeSidechainTracker } from "./sidechain-tracker.js"; @@ -56,6 +59,8 @@ import { type ClaudeHookObservationInput, } from "./subagents/live-source.js"; import { observeReplaySubagents, type ClaudeReplayParentFacts } from "./subagents/replay-source.js"; +import { mapTaskStatus } from "./subagents/task-status.js"; +import type { ProviderSubagentStatus } from "../../provider-subagents/store.js"; import { foldSubagentObservations, type SubagentObservation } from "./subagents/observation.js"; import { observeReplayWorkflows } from "./subagents/workflow-replay-source.js"; import { limitAgentTimelineItemContent } from "../../agent-timeline-content.js"; @@ -77,6 +82,7 @@ import { renderPromptAttachmentAsText } from "../../prompt-attachments.js"; import { discoverClaudeModels } from "./model-discovery.js"; import { claudeQuery, type ClaudeOptions, type ClaudeQueryFactory } from "./query.js"; import { + findSteeredMessageParent, realClaudeRewindSdk, revertClaudeConversation, revertClaudeFiles, @@ -425,7 +431,6 @@ const CLAUDE_ROOT_ONLY_COMMANDS = new Set([ "usage", ]); const INTERRUPT_TOOL_USE_PLACEHOLDER = "[Request interrupted by user for tool use]"; -const INTERRUPT_PLACEHOLDER_PATTERN = /^\[Request interrupted by user(?:[^\]]*)\]$/; const NO_RESPONSE_REQUESTED_PLACEHOLDER = "No response requested."; const STEER_SUPERSEDED_PERMISSION_MESSAGE = "The user answered with a message instead of approving. Their message follows."; @@ -645,6 +650,40 @@ function readClaudeFastModeSetting(settings: ClaudeOptions["settings"]): boolean return typeof settings.fastMode === "boolean" ? settings.fastMode : null; } +type ClaudeSettingsObject = NonNullable>; + +// Mirrors `claude --settings`: the value is inline JSON or a path to a JSON file, +// resolved against the session cwd like the Claude process would. +async function readClaudeCliSettings(value: string, cwd: string): Promise { + const trimmed = value.trim(); + const isInlineJson = trimmed.startsWith("{"); + const source = isInlineJson ? "--settings JSON" : path.resolve(cwd, expandTilde(trimmed)); + let raw = trimmed; + if (!isInlineJson) { + try { + raw = await fsPromises.readFile(source, "utf8"); + } catch (error) { + throw new Error( + `Failed to read Claude settings file ${source}: ${error instanceof Error ? error.message : String(error)}`, + { cause: error }, + ); + } + } + let parsed: unknown; + try { + parsed = JSON.parse(raw); + } catch (error) { + throw new Error( + `Claude ${source} is not valid JSON: ${error instanceof Error ? error.message : String(error)}`, + { cause: error }, + ); + } + if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) { + throw new Error(`Claude ${source} must contain a JSON object`); + } + return parsed as ClaudeSettingsObject; +} + function mergeClaudeSettings( settings: ClaudeOptions["settings"], updates: NonNullable>, @@ -789,11 +828,6 @@ function normalizeClaudeTranscriptText(value: unknown): string | null { return normalized.length > 0 ? normalized : null; } -function isClaudeInterruptPlaceholderText(value: unknown): boolean { - const normalized = normalizeClaudeTranscriptText(value); - return normalized !== null && INTERRUPT_PLACEHOLDER_PATTERN.test(normalized); -} - function isClaudeNoResponsePlaceholderText(value: unknown): boolean { return normalizeClaudeTranscriptText(value) === NO_RESPONSE_REQUESTED_PLACEHOLDER; } @@ -2553,7 +2587,11 @@ class ClaudeAgentSession implements AgentSession { this.input.push(sdkMessage); setTimeout(() => { if (this.activeForegroundTurnId === turnId) { - this.emitSubmittedUserMessage(sdkMessage, turnId, options?.clientMessageId); + void this.emitSubmittedUserMessage(sdkMessage, turnId, options?.clientMessageId).catch( + (error: unknown) => { + this.logger.warn({ err: error }, "Failed to emit submitted Claude message"); + }, + ); } }, 0); } catch (error) { @@ -2597,7 +2635,7 @@ class ClaudeAgentSession implements AgentSession { return { status: "unavailable" }; } this.enqueueSteer(input, message, options.clearPendingPermissions === true); - return { status: "accepted" }; + return { status: "accepted", ...(message.uuid ? { providerMessageId: message.uuid } : {}) }; } private enqueueSteer( @@ -3064,7 +3102,7 @@ class ClaudeAgentSession implements AgentSession { async revertConversation(input: { messageId: string }): Promise { await this.ensureHistoryReady(); - const target = this.resolveConversationRewindTarget(input.messageId); + const target = await this.resolveConversationRewindTarget(input.messageId); if (target.kind === "fresh-session") { this.startFreshConversationSession(); return; @@ -3399,12 +3437,24 @@ class ClaudeAgentSession implements AgentSession { return messageId; } - private resolveConversationRewindTarget(messageId: string): ClaudeConversationRewindTarget { + private async resolveConversationRewindTarget( + messageId: string, + ): Promise { const targetUserMessageId = this.resolveClaudeMessageId(messageId); const index = this.rewindTurnAnchors.findIndex( (anchor) => anchor.userMessageId === targetUserMessageId, ); if (index < 0) { + // A message steered into a running turn opens no turn of its own. + const transcriptPath = this.claudeSessionId + ? await this.resolveHistoryPath(this.claudeSessionId) + : null; + const steerParent = transcriptPath + ? await findSteeredMessageParent(transcriptPath, targetUserMessageId) + : null; + if (steerParent) { + return { kind: "fork", messageId: steerParent }; + } throw new Error(`Claude rewind target ${messageId} is not in the tracked conversation`); } @@ -3615,7 +3665,7 @@ class ClaudeAgentSession implements AgentSession { this.config.providerOptions, this.config.toolPolicy, ); - const settingsOptions = this.buildSettingsOptions(providerOptions, { ultracode }); + const settingsOptions = await this.buildSettingsOptions(providerOptions, { ultracode }); const sdkEnv = this.harnessEnvironment; assertClaudeModeCanRun(permissionMode, sdkEnv); @@ -3700,10 +3750,10 @@ class ClaudeAgentSession implements AgentSession { return base; } - private buildSettingsOptions( + private async buildSettingsOptions( providerOptions: ClaudeProviderOptions, input: { ultracode: boolean }, - ): Pick | Record { + ): Promise | Record> { const fastMode = this.resolveFastModeSetting(); // Internal agents do daemon work such as naming a branch, so the user's and // project's hooks must not run for them. @@ -3711,12 +3761,21 @@ class ClaudeAgentSession implements AgentSession { if (fastMode === null && !input.ultracode && !disableAllHooks) { return {}; } + const updates = { + ...(fastMode === null ? {} : { fastMode }), + ...(input.ultracode ? { ultracode: true } : {}), + ...(disableAllHooks ? { disableAllHooks: true } : {}), + }; + // The SDK replaces extraArgs.settings with Options.settings, so a user's + // `--settings` would be dropped whenever Paseo sets flag settings. Fold it in. + const { settings: extraArgsSettings, ...extraArgs } = providerOptions.extraArgs ?? {}; + if (typeof extraArgsSettings !== "string") { + return { settings: mergeClaudeSettings(providerOptions.settings, updates) }; + } + const cliSettings = await readClaudeCliSettings(extraArgsSettings, this.config.cwd); return { - settings: mergeClaudeSettings(providerOptions.settings, { - ...(fastMode === null ? {} : { fastMode }), - ...(input.ultracode ? { ultracode: true } : {}), - ...(disableAllHooks ? { disableAllHooks: true } : {}), - }), + extraArgs, + settings: { ...cliSettings, ...providerOptions.settings, ...updates }, }; } @@ -4141,7 +4200,7 @@ class ClaudeAgentSession implements AgentSession { consecutiveInterruptAbortRecoveries = 0; if (await this.handleMissingResumedConversation(message, activeQuery)) return true; if (!this.ownsQuery(activeQuery)) return true; - this.routeSdkMessageFromPump(message); + await this.routeSdkMessageFromPump(message); return false; } finally { this.processingSdkMessages--; @@ -4265,7 +4324,7 @@ class ClaudeAgentSession implements AgentSession { return !this.closed && this.query === query; } - private routeSdkMessageFromPump(message: SDKMessage): void { + private async routeSdkMessageFromPump(message: SDKMessage): Promise { if (this.consumeSessionStateChange(message)) { return; } @@ -4299,7 +4358,7 @@ class ClaudeAgentSession implements AgentSession { "provider.claude.parsed_event", ); - const events = this.buildPumpedMessageEvents(message, identifiers.messageId, turnId); + const events = await this.buildPumpedMessageEvents(message, identifiers.messageId, turnId); if (events.length === 0) { return; @@ -4334,15 +4393,22 @@ class ClaudeAgentSession implements AgentSession { this.dispatchEvents(events); } - private buildPumpedMessageEvents( + private async buildPumpedMessageEvents( message: SDKMessage, messageIdHint: string | null, turnId: string | null, - ): AgentStreamEvent[] { - const messageEvents = this.translateMessageToEvents(message, { + ): Promise { + const query = this.query; + const messageEvents = await this.translateMessageToEvents(message, { suppressAssistantText: true, suppressReasoning: true, }); + if ( + this.closed || + this.query !== query || + (this.activeForegroundTurnId ?? this.autonomousTurn?.id ?? null) !== turnId + ) + return []; const assistantTimelineEvents = readClaudeParentToolUseId(message) ? [] : this.timelineAssembler @@ -4502,13 +4568,13 @@ class ClaudeAgentSession implements AgentSession { return withdrewAll; } - private translateMessageToEvents( + private async translateMessageToEvents( message: SDKMessage, options?: { suppressAssistantText?: boolean; suppressReasoning?: boolean; }, - ): AgentStreamEvent[] { + ): Promise { const parentToolUseId = readClaudeParentToolUseId(message); if (parentToolUseId) { return this.translateSidechainFrameToEvents(message, parentToolUseId); @@ -4556,11 +4622,11 @@ class ClaudeAgentSession implements AgentSession { this.appendSystemMessageEvents(message, events); break; case "user": - this.appendUserMessageEvents(message, events); + await this.appendUserMessageEvents(message, events); this.appendSidechainResultEvents(message, events); break; case "assistant": { - const timelineItems = this.mapBlocksToTimeline(message.message.content, { + const timelineItems = await this.mapBlocksToTimeline(message.message.content, { suppressAssistantText: options?.suppressAssistantText ?? false, suppressReasoning: options?.suppressReasoning ?? false, }); @@ -4571,7 +4637,7 @@ class ClaudeAgentSession implements AgentSession { break; } case "stream_event": - this.appendStreamEventEvents(message, events, options); + await this.appendStreamEventEvents(message, events, options); break; case "result": this.appendResultEvents(message, events); @@ -4636,7 +4702,7 @@ class ClaudeAgentSession implements AgentSession { /** * The Task card in the parent transcript, built from the declaration. * - * The sidechain tracker also emits this card, enriched with the child's action log, and the two + * The sidechain tracker also emits this card when it first sees the child, and the two * collapse on the shared tool-call id. Emitting it at declaration matters because a * backgrounded subagent produces no sidechain frames at all — verified on the wire — so the * tracker never runs for one and its card would otherwise stay an unlabeled "Task". @@ -4673,13 +4739,14 @@ class ClaudeAgentSession implements AgentSession { } } - private emitSubmittedUserMessage( + private async emitSubmittedUserMessage( message: Extract, turnId: string, clientMessageId?: string, - ): void { + ): Promise { const events: AgentStreamEvent[] = []; - this.appendUserMessageEvents(message, events); + await this.appendUserMessageEvents(message, events); + if (this.activeForegroundTurnId !== turnId) return; if (events.length === 0) { return; } @@ -4809,10 +4876,10 @@ class ClaudeAgentSession implements AgentSession { } } - private appendUserMessageEvents( + private async appendUserMessageEvents( message: Extract, events: AgentStreamEvent[], - ): void { + ): Promise { if (isSyntheticUserEntry(message)) { return; } @@ -4851,7 +4918,7 @@ class ClaudeAgentSession implements AgentSession { return; } if (Array.isArray(content)) { - this.appendUserContentArrayEvents(content, messageId, events); + await this.appendUserContentArrayEvents(content, messageId, events); } } @@ -4877,12 +4944,12 @@ class ClaudeAgentSession implements AgentSession { events.push({ type: "timeline", item, provider: "claude" }); } - private appendUserContentArrayEvents( + private async appendUserContentArrayEvents( content: ReadonlyArray, messageId: string | undefined, events: AgentStreamEvent[], - ): void { - const timelineItems = this.mapBlocksToTimeline(content, { + ): Promise { + const timelineItems = await this.mapBlocksToTimeline(content, { textMessageType: "user_message", }); for (const item of timelineItems) { @@ -4898,16 +4965,16 @@ class ClaudeAgentSession implements AgentSession { } } - private appendStreamEventEvents( + private async appendStreamEventEvents( message: Extract, events: AgentStreamEvent[], options: { suppressAssistantText?: boolean; suppressReasoning?: boolean } | undefined, - ): void { + ): Promise { const usageUpdatedEvent = this.contextUsage.buildStreamUsageEvent(message.event); if (usageUpdatedEvent) { events.push(usageUpdatedEvent); } - const timelineItems = this.mapPartialEvent(message.event, { + const timelineItems = await this.mapPartialEvent(message.event, { suppressAssistantText: options?.suppressAssistantText ?? false, suppressReasoning: options?.suppressReasoning ?? false, }); @@ -5402,7 +5469,7 @@ class ClaudeAgentSession implements AgentSession { ): Promise { const timeline: PersistedTimelineEntry[] = []; for await (const entry of entries) { - this.ingestPersistedHistoryEntry(entry, timeline, replay); + await this.ingestPersistedHistoryEntry(entry, timeline, replay); } if (timeline.length > 0) { @@ -5439,6 +5506,7 @@ class ClaudeAgentSession implements AgentSession { convertEntry: (entry) => this.convertHistoryEntry(entry), })), ]; + this.taskProtocolSource.restore(subagentReplay.restored); const restoredProviderSubagentIds = new Set( observations .filter((observation) => observation.kind === "declared") @@ -5462,11 +5530,11 @@ class ClaudeAgentSession implements AgentSession { return replay; } - private ingestPersistedHistoryEntry( + private async ingestPersistedHistoryEntry( entry: ClaudeHistoryEntry, timeline: PersistedTimelineEntry[], replay: ClaudeReplayOwnership, - ): void { + ): Promise { if (entry.isSidechain) { return; } @@ -5480,7 +5548,7 @@ class ClaudeAgentSession implements AgentSession { ? replay.toolOwners.get(notificationToolUseId) : undefined; if (notificationOwner) { - for (const item of this.convertHistoryEntry(entry)) { + for (const item of await this.convertHistoryEntry(entry)) { this.persistedProviderSubagentEvents.push({ type: "provider_subagent", provider: "claude", @@ -5497,7 +5565,7 @@ class ClaudeAgentSession implements AgentSession { const taskSnapshot = this.taskState.observe(entry); const items = [ ...(taskSnapshot ? [taskSnapshot] : []), - ...this.convertHistoryEntry(entry).map((item) => + ...(await this.convertHistoryEntry(entry)).map((item) => labelReplayedSubagentCard(item, replay.subagentToolCalls), ), ]; @@ -5534,10 +5602,10 @@ class ClaudeAgentSession implements AgentSession { }); } - private convertHistoryEntry(entry: ClaudeHistoryEntry): AgentTimelineItem[] { - return convertClaudeHistoryEntry(entry, (content) => this.mapBlocksToTimeline(content)).map( - limitAgentTimelineItemContent, - ); + private async convertHistoryEntry(entry: ClaudeHistoryEntry): Promise { + return ( + await convertClaudeHistoryEntry(entry, (content) => this.mapBlocksToTimeline(content)) + ).map(limitAgentTimelineItemContent); } // Maps Claude content blocks into AgentTimelineItems. @@ -5552,14 +5620,14 @@ class ClaudeAgentSession implements AgentSession { // // NOTE: convertClaudeHistoryEntry uses extractUserMessageText directly instead of this function // for user entries. Both paths must produce equivalent user_message items. - private mapBlocksToTimeline( + private async mapBlocksToTimeline( content: string | ReadonlyArray, options?: { textMessageType?: "assistant_message" | "user_message"; suppressAssistantText?: boolean; suppressReasoning?: boolean; }, - ): AgentTimelineItem[] { + ): Promise { const textMessageType = options?.textMessageType ?? "assistant_message"; const suppressText = textMessageType === "assistant_message" && (options?.suppressAssistantText ?? false); @@ -5586,7 +5654,7 @@ class ClaudeAgentSession implements AgentSession { if (!isClaudeContentChunk(block) || this.mapSubagentHandbackBlock(block, items)) { continue; } - this.mapBlockToTimeline(block, { + await this.mapBlockToTimeline(block, { items, userTextParts, textMessageType, @@ -5631,7 +5699,7 @@ class ClaudeAgentSession implements AgentSession { } } - private mapBlockToTimeline( + private async mapBlockToTimeline( block: ClaudeContentChunk, context: { items: AgentTimelineItem[]; @@ -5640,7 +5708,7 @@ class ClaudeAgentSession implements AgentSession { suppressText: boolean; suppressReasoning: boolean; }, - ): void { + ): Promise { switch (block.type) { case "text": case "text_delta": @@ -5664,7 +5732,7 @@ class ClaudeAgentSession implements AgentSession { case "code_execution_tool_result": case "bash_code_execution_tool_result": case "text_editor_code_execution_tool_result": - this.handleToolResult(block, context.items); + await this.handleToolResult(block, context.items); break; default: break; @@ -5710,7 +5778,10 @@ class ClaudeAgentSession implements AgentSession { ); } - private handleToolResult(block: ClaudeContentChunk, items: AgentTimelineItem[]): void { + private async handleToolResult( + block: ClaudeContentChunk, + items: AgentTimelineItem[], + ): Promise { const entry = typeof block.tool_use_id === "string" ? this.toolUseCache.get(block.tool_use_id) : undefined; const blockToolName = typeof block.tool_name === "string" ? block.tool_name : undefined; @@ -5743,7 +5814,7 @@ class ClaudeAgentSession implements AgentSession { this.rememberSettledSubagentToolCall(settledToolCall, entry); for (const image of images) { - const imageItem = renderProviderImageOutputAsAssistantMarkdown(image, { + const imageItem = await renderProviderImageOutputAsAssistantMarkdown(image, { materialize: materializeProviderImage, }); if (imageItem) { @@ -5967,13 +6038,13 @@ class ClaudeAgentSession implements AgentSession { return false; } - private mapPartialEvent( + private async mapPartialEvent( event: SDKPartialAssistantMessage["event"], options?: { suppressAssistantText?: boolean; suppressReasoning?: boolean; }, - ): AgentTimelineItem[] { + ): Promise { if (this.updatePartialEventToolState(event)) { return []; } @@ -5981,14 +6052,14 @@ class ClaudeAgentSession implements AgentSession { switch (event.type) { case "content_block_start": return isClaudeContentChunk(event.content_block) - ? this.mapBlocksToTimeline([event.content_block], { + ? await this.mapBlocksToTimeline([event.content_block], { suppressAssistantText: options?.suppressAssistantText, suppressReasoning: options?.suppressReasoning, }) : []; case "content_block_delta": return isClaudeContentChunk(event.delta) - ? this.mapBlocksToTimeline([event.delta], { + ? await this.mapBlocksToTimeline([event.delta], { suppressAssistantText: options?.suppressAssistantText, suppressReasoning: options?.suppressReasoning, }) @@ -6270,6 +6341,7 @@ function buildClaudeSubagentCardDetail( type: "sub_agent", ...(facts.title ? { subAgentType: facts.title } : {}), ...(facts.description ? { description: facts.description } : {}), + // COMPAT(subagent-log): remove after 2027-04-30. log: "", actions: [], }; @@ -6298,33 +6370,34 @@ async function readClaudeReplayParentFacts( entries: Iterable | AsyncIterable, ): Promise { const toolCalls = new Map(); - const linksByAgentId = new Map(); - const outcomes = new Map(); + const linksByAgentId = new Map(); + const outcomes: Map = new Map(); for await (const entry of entries) { + const notification = readTaskNotificationFromHistoryRecord(entry); + const status = mapTaskStatus(notification?.status ?? undefined); + if (notification?.toolUseId && status) { + outcomes.set(notification.toolUseId, { status }); + } const content = toObjectRecord(entry.message)?.content; if (!Array.isArray(content)) continue; for (const value of content) { const block = toObjectRecord(value); + const declaration = readClaudeReplayTaskDeclaration(entry.type, block); + if (declaration) toolCalls.set(declaration.id, declaration.identity); if ( - block?.type === "tool_use" && - (block.name === "Task" || block.name === "Agent") && - typeof block.id === "string" - ) { - const input = toObjectRecord(block.input); - const title = readNonEmptyString(input?.name) ?? readNonEmptyString(input?.subagent_type); - const description = readNonEmptyString(input?.description); - toolCalls.set(block.id, { - ...(title ? { title } : {}), - ...(description ? { description } : {}), + entry.type !== "user" || + block?.type !== "tool_result" || + typeof block.tool_use_id !== "string" + ) + continue; + if (toObjectRecord(entry.toolUseResult)?.status !== "async_launched") + outcomes.set(block.tool_use_id, { + status: block.is_error === true ? "failed" : "completed", }); - } - if (block?.type !== "tool_result" || typeof block.tool_use_id !== "string") continue; - outcomes.set(block.tool_use_id, { failed: block.is_error === true }); const agentId = readLegacyClaudeSubagentId(block.content); if (agentId) linksByAgentId.set(agentId, { toolCallId: block.tool_use_id, - failed: block.is_error === true, }); } } @@ -6335,6 +6408,29 @@ async function readClaudeReplayParentFacts( }; } +function readClaudeReplayTaskDeclaration( + entryType: unknown, + block: Record | undefined, +): { + id: string; + identity: { title?: string; description?: string }; +} | null { + if ( + entryType !== "assistant" || + block?.type !== "tool_use" || + (block.name !== "Task" && block.name !== "Agent") || + typeof block.id !== "string" + ) + return null; + const input = toObjectRecord(block.input); + const title = readNonEmptyString(input?.name) ?? readNonEmptyString(input?.subagent_type); + const description = readNonEmptyString(input?.description); + return { + id: block.id, + identity: { ...(title ? { title } : {}), ...(description ? { description } : {}) }, + }; +} + function readLegacyClaudeSubagentId(content: unknown): string | undefined { return /agentId:\s*([\w-]+)/.exec(JSON.stringify(content))?.[1]; } @@ -6351,12 +6447,14 @@ interface ClaudeHistoryEntry { [key: string]: unknown; } -function mapAssistantHistoryBlocksWithMessageId( +async function mapAssistantHistoryBlocksWithMessageId( entry: ClaudeHistoryEntry, content: string | ClaudeContentChunk[], - mapBlocks: (content: string | ClaudeContentChunk[]) => AgentTimelineItem[], -): AgentTimelineItem[] { - const items = mapBlocks(content); + mapBlocks: ( + content: string | ClaudeContentChunk[], + ) => AgentTimelineItem[] | Promise, +): Promise { + const items = await mapBlocks(content); const assistantMessageId = typeof entry.uuid === "string" && entry.uuid.length > 0 ? entry.uuid : null; if (!assistantMessageId) { @@ -6398,6 +6496,10 @@ function convertClaudeHistoryEntryPreamble( if (entry.type === "user" && isSyntheticHistoryUserEntry(entry)) { return { shortCircuit: [] }; } + const steeredPrompt = readSteeredPromptHistoryItem(entry); + if (steeredPrompt) { + return { shortCircuit: [steeredPrompt] }; + } // Only user and assistant records are conversation turns. Claude Code 2.1.x also journals each // API request as `api-request-blob` records whose message replays the system context. if (entry.type !== "user" && entry.type !== "assistant") { @@ -6424,10 +6526,27 @@ function isProviderImageMessage(item: AgentTimelineItem): boolean { return item.type === "assistant_message" && isProviderImageMarkdown(item.text); } -export function convertClaudeHistoryEntry( +/** + * A message steered into a running turn. Claude Code gives it no user entry: it records a + * queued_command attachment in prompt mode, under the uuid Paseo minted for the message, which is + * also what a rewind to it resolves. The other modes carry task notifications, not user messages. + */ +function readSteeredPromptHistoryItem(entry: ClaudeHistoryEntry): AgentTimelineItem | null { + if (entry.type !== "attachment") return null; + const attachment = toObjectRecord(entry.attachment); + if (attachment?.type !== "queued_command" || attachment.commandMode !== "prompt") return null; + const text = extractUserMessageText(attachment.prompt); + if (!text) return null; + const messageId = readTrimmedString(attachment.source_uuid); + return { type: "user_message", text, ...(messageId ? { messageId } : {}) }; +} + +export async function convertClaudeHistoryEntry( entry: ClaudeHistoryEntry, - mapBlocks: (content: string | ClaudeContentChunk[]) => AgentTimelineItem[], -): AgentTimelineItem[] { + mapBlocks: ( + content: string | ClaudeContentChunk[], + ) => AgentTimelineItem[] | Promise, +): Promise { const preamble = convertClaudeHistoryEntryPreamble(entry); if ("shortCircuit" in preamble) { return preamble.shortCircuit; @@ -6466,7 +6585,7 @@ export function convertClaudeHistoryEntry( } if (hasToolBlock && normalizedBlocks) { - const mapped = mapBlocks(normalizedBlocks); + const mapped = await mapBlocks(normalizedBlocks); if (entry.type === "user") { // tool_result handling (handleToolResult) emits image markdown as an assistant_message // alongside the tool_call. User-entry text blocks also map to assistant_message in this path @@ -6480,7 +6599,7 @@ export function convertClaudeHistoryEntry( } if (entry.type === "assistant" && contentValue) { - return mapAssistantHistoryBlocksWithMessageId(entry, contentValue, mapBlocks); + return await mapAssistantHistoryBlocksWithMessageId(entry, contentValue, mapBlocks); } return timeline; @@ -6785,40 +6904,79 @@ function normalizeClaudeSessionTitle(title: string | null): string | null { } const CLAUDE_CUSTOM_TITLE_TYPE = "custom-title"; +const CLAUDE_CUSTOM_TITLE_NEEDLE = Buffer.from(`"${CLAUDE_CUSTOM_TITLE_TYPE}"`); +const CLAUDE_TITLE_SCAN_CHUNK_BYTES = 64 * 1024; + +function readClaudeCustomTitleFromRecord(record: Buffer): string | null { + // The needle also matches a prompt that quotes it, so a record still has to + // parse as a `custom-title` entry carrying a usable name. Records without the + // needle are never decoded, so a long one costs a byte search and nothing more. + if (!record.includes(CLAUDE_CUSTOM_TITLE_NEEDLE)) { + return null; + } + let parsed: unknown; + try { + parsed = JSON.parse(record.toString("utf8").trim()); + } catch { + return null; + } + const entry = toObjectRecord(parsed); + if (!entry || entry.isSidechain || entry.type !== CLAUDE_CUSTOM_TITLE_TYPE) { + return null; + } + return normalizeClaudeSessionTitle( + typeof entry.customTitle === "string" ? entry.customTitle : null, + ); +} /** * The `custom-title` record is re-emitted every time the session is saved, so - * the current name is the last usable one in the file. Searching backwards finds it without - * walking the transcript, which matters because sessions reach tens of - * megabytes. + * the current name is the last usable one in the file. Reading backwards a chunk + * at a time finds it without walking the transcript, which matters because + * sessions reach tens of megabytes, and never holds the file as one string, so a + * transcript past V8's maximum string length still imports. */ -function readLastClaudeCustomTitle(content: string): string | null { - const needle = `"${CLAUDE_CUSTOM_TITLE_TYPE}"`; - let at = content.lastIndexOf(needle); - while (at >= 0) { - const lineStart = content.lastIndexOf("\n", at) + 1; - const lineEnd = content.indexOf("\n", at); - const line = lineEnd === -1 ? content.slice(lineStart) : content.slice(lineStart, lineEnd); - let parsed: unknown; - try { - parsed = JSON.parse(line.trim()); - } catch { - parsed = undefined; - } - const entry = toObjectRecord(parsed); - if (entry && !entry.isSidechain && entry.type === CLAUDE_CUSTOM_TITLE_TYPE) { - const title = normalizeClaudeSessionTitle( - typeof entry.customTitle === "string" ? entry.customTitle : null, +async function readLastClaudeCustomTitle(filePath: string): Promise { + const handle = await fsPromises.open(filePath, "r"); + try { + const stats = await handle.stat(); + if (!stats.isFile()) { + // Opening a directory succeeds on Windows even though reading it does not, + // so reject the way reading the transcript as a file would. + throw Object.assign( + new Error(`EISDIR: illegal operation on a directory, read '${filePath}'`), + { code: "EISDIR", path: filePath }, ); - if (title) { - return title; - } } - // The needle also matches a prompt that quotes it, and a record can carry no - // usable name, so keep looking backwards for one that does. - at = at <= 0 ? -1 : content.lastIndexOf(needle, at - 1); + let end = stats.size; + // Retain unfinished record pieces in reverse file order. Assemble each + // complete record once, so a large tool/image record costs linear work. + let pieces: Buffer[] = []; + while (end > 0) { + const length = Math.min(CLAUDE_TITLE_SCAN_CHUNK_BYTES, end); + const chunk = Buffer.alloc(length); + await handle.read(chunk, 0, length, end - length); + let recordEnd = chunk.length; + for ( + let at = chunk.lastIndexOf(10); + at >= 0; + at = at === 0 ? -1 : chunk.lastIndexOf(10, at - 1) + ) { + pieces.push(chunk.subarray(at + 1, recordEnd)); + const record = Buffer.concat(pieces.toReversed()); + const title = readClaudeCustomTitleFromRecord(record); + if (title) return title; + pieces = []; + recordEnd = at; + } + if (recordEnd > 0) pieces.push(chunk.subarray(0, recordEnd)); + end -= length; + } + // The first record in the file has no newline in front of it. + return readClaudeCustomTitleFromRecord(Buffer.concat(pieces.toReversed())); + } finally { + await handle.close(); } - return null; } function isErrnoException(error: unknown): error is NodeJS.ErrnoException { @@ -6830,9 +6988,8 @@ async function readClaudeRenamedSessionTitle(input: { sessionId: string; configDir: string; }): Promise { - let content: string; try { - content = await fsPromises.readFile(await claudeTranscriptPath(input), "utf8"); + return await readLastClaudeCustomTitle(await claudeTranscriptPath(input)); } catch (error) { // A session with no transcript on disk has no rename to carry over. Every // other read failure is a real fault and stays explicit. @@ -6841,7 +6998,6 @@ async function readClaudeRenamedSessionTitle(input: { } throw error; } - return readLastClaudeCustomTitle(content); } function normalizeImportablePromptPreview(text: string): string | null { diff --git a/packages/server/src/server/agent/providers/claude/interrupt-placeholder.ts b/packages/server/src/server/agent/providers/claude/interrupt-placeholder.ts new file mode 100644 index 0000000000..f74c899234 --- /dev/null +++ b/packages/server/src/server/agent/providers/claude/interrupt-placeholder.ts @@ -0,0 +1,6 @@ +const INTERRUPT_PLACEHOLDER_PATTERN = /^\[Request interrupted by user(?:[^\]]*)\]$/; + +/** The text Claude Code records in place of a turn that an interrupt stopped. */ +export function isClaudeInterruptPlaceholderText(value: unknown): boolean { + return typeof value === "string" && INTERRUPT_PLACEHOLDER_PATTERN.test(value.trim()); +} diff --git a/packages/server/src/server/agent/providers/claude/query.ts b/packages/server/src/server/agent/providers/claude/query.ts index c8fe4ba036..0f9525d5b1 100644 --- a/packages/server/src/server/agent/providers/claude/query.ts +++ b/packages/server/src/server/agent/providers/claude/query.ts @@ -73,8 +73,9 @@ function applyRuntimeSettingsToClaudeOptions( runtimeSettings, overlays: [launchEnv], }); - // Set our identity after sanitization clears the parent session's entrypoint. - providerEnvSpec.envOverlay.CLAUDE_CODE_ENTRYPOINT = "Paseo"; + // Session-open hooks may explicitly supply a client identity. Keep inherited + // SDK/parent identities cleared while honoring this launch-only contribution. + providerEnvSpec.envOverlay.CLAUDE_CODE_ENTRYPOINT = launchEnv?.CLAUDE_CODE_ENTRYPOINT; const providerEnv = createExternalProcessEnv(spawnOptions.env, providerEnvSpec.envOverlay); const selfNodeCommand = isDefaultRuntime ? buildSelfNodeCommand(resolved.args, providerEnv) diff --git a/packages/server/src/server/agent/providers/claude/rewind.test.ts b/packages/server/src/server/agent/providers/claude/rewind.test.ts index 2d6d3853c2..226f41d39c 100644 --- a/packages/server/src/server/agent/providers/claude/rewind.test.ts +++ b/packages/server/src/server/agent/providers/claude/rewind.test.ts @@ -1,11 +1,20 @@ import { randomUUID } from "node:crypto"; -import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { + mkdirSync, + mkdtempSync, + readFileSync, + readdirSync, + readlinkSync, + rmSync, + writeFileSync, +} from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; import { afterEach, describe, expect, test } from "vitest"; import type { Query } from "@anthropic-ai/claude-agent-sdk"; import { + findSteeredMessageParent, revertClaudeConversation, revertClaudeConversationAndFiles, revertClaudeFiles, @@ -217,4 +226,96 @@ describe("Claude rewind against the Claude SDK", () => { "first reply", ]); }); + + test("forks just before a message steered into a running turn", async () => { + tempRoot = mkdtempSync(path.join(tmpdir(), "claude-rewind-steer-")); + delete process.env.CLAUDE_CONFIG_DIR; + const projectDir = path.join(tempRoot, "projects", "-repo"); + mkdirSync(projectDir, { recursive: true }); + const sessionId = randomUUID(); + const firstUser = randomUUID(); + const toolUse = randomUUID(); + const toolResult = randomUUID(); + const steeredMessage = randomUUID(); + const queuedCommand = randomUUID(); + const transcriptPath = path.join(projectDir, `${sessionId}.jsonl`); + writeTranscript(transcriptPath, sessionId, [ + { type: "user", uuid: firstUser, parentUuid: null, text: "first" }, + { type: "assistant", uuid: toolUse, parentUuid: firstUser, text: "running a tool" }, + { type: "user", uuid: toolResult, parentUuid: toolUse, text: "tool output" }, + // What Claude Code writes when it reads a steered message between two tool calls. + JSON.stringify({ + type: "attachment", + uuid: queuedCommand, + parentUuid: toolResult, + sessionId, + attachment: { + type: "queued_command", + prompt: [{ type: "text", text: "steered" }], + source_uuid: steeredMessage, + }, + }), + { type: "assistant", uuid: randomUUID(), parentUuid: queuedCommand, text: "reply to steer" }, + ]); + + const parent = await findSteeredMessageParent(transcriptPath, steeredMessage); + expect(parent).toBe(toolResult); + expect(await findSteeredMessageParent(transcriptPath, randomUUID())).toBeNull(); + + let currentSessionId = sessionId; + await revertClaudeConversation({ + sdk: realClaudeRewindSdk, + sessionId, + transcriptPath, + messageId: parent!, + setSessionId: (nextSessionId) => { + currentSessionId = nextSessionId; + }, + }); + expect(readMessageTexts(path.join(projectDir, `${currentSessionId}.jsonl`))).toEqual([ + "first", + "running a tool", + "tool output", + ]); + }); }); + +test.runIf(process.platform === "linux")( + "releases the transcript descriptor after an early steer match", + async () => { + const artifacts = path.resolve(".artifacts"); + mkdirSync(artifacts, { recursive: true }); + const root = mkdtempSync(path.join(artifacts, "claude-rewind-descriptor-")); + const transcriptPath = path.join(root, "session.jsonl"); + const matchingEntry = { + type: "attachment", + parentUuid: "before-steer", + attachment: { type: "queued_command", source_uuid: "steered-message" }, + }; + const unreadEntry = JSON.stringify({ type: "assistant", message: "x".repeat(1024) }); + writeFileSync( + transcriptPath, + JSON.stringify(matchingEntry) + "\n" + (unreadEntry + "\n").repeat(1200), + ); + const openDescriptors = () => + readdirSync("/proc/self/fd").filter((descriptor) => { + try { + return readlinkSync(path.join("/proc/self/fd", descriptor)) === transcriptPath; + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return false; + throw error; + } + }).length; + try { + expect(openDescriptors()).toBe(0); + for (let attempt = 0; attempt < 5; attempt++) { + await expect(findSteeredMessageParent(transcriptPath, "steered-message")).resolves.toBe( + "before-steer", + ); + } + await expect.poll(openDescriptors, { timeout: 1000 }).toBe(0); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }, +); diff --git a/packages/server/src/server/agent/providers/claude/rewind.ts b/packages/server/src/server/agent/providers/claude/rewind.ts index 91183687e0..75607c184b 100644 --- a/packages/server/src/server/agent/providers/claude/rewind.ts +++ b/packages/server/src/server/agent/providers/claude/rewind.ts @@ -1,5 +1,7 @@ +import { createReadStream } from "node:fs"; import { appendFile, readFile } from "node:fs/promises"; import path from "node:path"; +import { createInterface } from "node:readline"; import { forkSession as claudeForkSession, type Query, @@ -70,6 +72,54 @@ function isSessionStoreEntry(value: unknown): value is SessionStoreEntry { ); } +/** + * The entry a message steered into a running turn follows. Claude Code gives such a message no + * entry of its own: it records a queued_command attachment, under the uuid Paseo minted for the + * message, hung off the entry it was read after. Forking at that entry drops the message and + * everything after it. Null when the transcript holds no such attachment. + */ +export async function findSteeredMessageParent( + transcriptPath: string, + messageId: string, +): Promise { + const input = createReadStream(transcriptPath, { encoding: "utf8" }); + const lines = createInterface({ + input, + crlfDelay: Infinity, + }); + try { + for await (const line of lines) { + if (!line.includes(messageId) || !line.includes('"queued_command"')) continue; + let entry: unknown; + try { + entry = JSON.parse(line); + } catch { + continue; + } + const record = entry as { + type?: unknown; + parentUuid?: unknown; + attachment?: { type?: unknown; source_uuid?: unknown }; + }; + if ( + record.type === "attachment" && + record.attachment?.type === "queued_command" && + record.attachment.source_uuid === messageId && + typeof record.parentUuid === "string" + ) { + return record.parentUuid; + } + } + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return null; + throw error; + } finally { + lines.close(); + input.destroy(); + } + return null; +} + export async function revertClaudeConversation(input: { sdk: ClaudeRewindSdk; sessionId: string | null; diff --git a/packages/server/src/server/agent/providers/claude/settings-argv.test.ts b/packages/server/src/server/agent/providers/claude/settings-argv.test.ts new file mode 100644 index 0000000000..36d1b9d794 --- /dev/null +++ b/packages/server/src/server/agent/providers/claude/settings-argv.test.ts @@ -0,0 +1,46 @@ +import * as fs from "node:fs/promises"; +import * as os from "node:os"; +import * as path from "node:path"; +import pino from "pino"; +import { expect, test } from "vitest"; +import { ClaudeAgentClient } from "./agent.js"; + +test("the real SDK passes the user's settings file contents alongside Paseo flags", async () => { + const cwd = await fs.mkdtemp(path.join(os.tmpdir(), "paseo-claude-settings-argv-")); + const capturePath = path.join(cwd, "argv.json"); + const binaryPath = path.join(cwd, "capture.mjs"); + const settingsPath = path.join(cwd, "settings.json"); + const userSettings = { + env: { ENABLE_TOOL_SEARCH: "false" }, + permissions: { deny: ["Monitor"] }, + }; + try { + // A CLI fixture records the real SDK's arguments without making a model request. + await fs.writeFile( + binaryPath, + `import fs from "node:fs"; fs.writeFileSync(${JSON.stringify(capturePath)}, JSON.stringify(process.argv.slice(2)));`, + ); + await fs.writeFile(settingsPath, JSON.stringify(userSettings)); + const client = new ClaudeAgentClient({ + logger: pino({ level: "silent" }), + resolveBinary: async () => binaryPath, + }); + const session = await client.createSession({ + provider: "claude", + cwd, + model: "claude-opus-5-5", + providerOptions: { extraArgs: { settings: settingsPath } }, + }); + try { + await session.startTurn("hello"); + } finally { + await session.close(); + } + const argv: string[] = JSON.parse(await fs.readFile(capturePath, "utf8")); + const settingsIndex = argv.indexOf("--settings"); + expect(settingsIndex).toBeGreaterThanOrEqual(0); + expect(JSON.parse(argv[settingsIndex + 1]!)).toEqual({ ...userSettings, fastMode: false }); + } finally { + await fs.rm(cwd, { recursive: true, force: true }); + } +}); diff --git a/packages/server/src/server/agent/providers/claude/sidechain-tracker.test.ts b/packages/server/src/server/agent/providers/claude/sidechain-tracker.test.ts index a17c1cd58c..427f279bea 100644 --- a/packages/server/src/server/agent/providers/claude/sidechain-tracker.test.ts +++ b/packages/server/src/server/agent/providers/claude/sidechain-tracker.test.ts @@ -4,7 +4,7 @@ import type { SDKMessage } from "@anthropic-ai/claude-agent-sdk"; import { ClaudeSidechainTracker } from "./sidechain-tracker.js"; describe("ClaudeSidechainTracker", () => { - it("retains a background child's actions across the parent finishing", () => { + it("keeps a background child's card across the parent finishing", () => { const tracker = new ClaudeSidechainTracker({ getToolInput: () => ({ subagent_type: "general-purpose", description: "List files" }), isDescriptorOwnedElsewhere: () => true, @@ -15,27 +15,67 @@ describe("ClaudeSidechainTracker", () => { parent_tool_use_id: "task-1", message: { content: [{ type: "tool_use", id, name: "Bash", input: { command } }] }, }) as unknown as SDKMessage; - tracker.handleMessage(action("ls", "ls -1"), "task-1"); + const parentCards = (events: ReturnType) => + events.filter((event) => event.type === "timeline"); + const childCallIds = (events: ReturnType) => + events.flatMap((event) => + event.type === "provider_subagent" && + event.event.type === "timeline" && + event.event.item.type === "tool_call" + ? [event.event.item.callId] + : [], + ); + + expect(parentCards(tracker.handleMessage(action("ls", "ls -1"), "task-1"))).toHaveLength(1); expect(tracker.finishAll("completed")).toEqual([]); - const events = tracker.handleMessage(action("pwd", "pwd"), "task-1"); - expect(events).toContainEqual( - expect.objectContaining({ - type: "timeline", - item: expect.objectContaining({ - detail: expect.objectContaining({ log: "[Bash] ls -1\n[Bash] pwd" }), - }), - }), - ); + const afterFinish = tracker.handleMessage(action("pwd", "pwd"), "task-1"); + expect(parentCards(afterFinish)).toEqual([]); + expect(childCallIds(afterFinish)).toEqual(["pwd"]); + tracker.delete("task-1"); const next = tracker.handleMessage(action("next", "ls"), "task-1"); - expect(next).toContainEqual( - expect.objectContaining({ - type: "timeline", - item: expect.objectContaining({ - detail: expect.objectContaining({ log: "[Bash] ls" }), - }), - }), - ); + expect(parentCards(next)).toHaveLength(1); + expect(childCallIds(next)).toEqual(["next"]); + }); + + it("shows a streamed child tool call's input once the assistant message brings it", () => { + const tracker = new ClaudeSidechainTracker({ getToolInput: () => null }); + const frames = [ + { + type: "stream_event", + parent_tool_use_id: "task-1", + event: { + type: "content_block_start", + index: 0, + content_block: { type: "tool_use", id: "bash-1", name: "Bash", input: {} }, + }, + }, + { + type: "assistant", + parent_tool_use_id: "task-1", + message: { + content: [ + { type: "tool_use", id: "bash-1", name: "Bash", input: { command: "echo child" } }, + ], + }, + }, + ] as unknown as SDKMessage[]; + + const childCards = frames + .flatMap((frame) => tracker.handleMessage(frame, "task-1")) + .flatMap((event) => + event.type === "provider_subagent" && + event.event.type === "timeline" && + event.event.item.type === "tool_call" + ? [event.event.item] + : [], + ); + + expect(childCards.at(-1)).toMatchObject({ + callId: "bash-1", + status: "running", + detail: { type: "shell", command: "echo child" }, + }); }); it("uses Claude's native agent name for the provider subagent title", () => { diff --git a/packages/server/src/server/agent/providers/claude/sidechain-tracker.ts b/packages/server/src/server/agent/providers/claude/sidechain-tracker.ts index 083b82cea6..5ca79641f9 100644 --- a/packages/server/src/server/agent/providers/claude/sidechain-tracker.ts +++ b/packages/server/src/server/agent/providers/claude/sidechain-tracker.ts @@ -5,7 +5,6 @@ import { mapClaudeFailedToolCall, mapClaudeRunningToolCall, } from "./tool-call-mapper.js"; -import { buildToolCallDisplayModel } from "@getpaseo/protocol/tool-call-display"; import { isClaudeSubagentHandbackToolName, readClaudeSubagentHandback, @@ -20,21 +19,17 @@ interface ClaudeContentChunk { type ClaudeToolCallItem = Extract; -interface SubAgentActionEntry { - index: number; +interface SubAgentChildCall { toolName: string; input: unknown; - summary?: string; } interface SubAgentActivityState { name?: string; subAgentType?: string; description?: string; - actions: SubAgentActionEntry[]; - actionKeys: string[]; - nextActionIndex: number; - actionIndexByKey: Map; + /** The child's tool calls awaiting results, which carry no input of their own. */ + runningCalls: Map; completedActionKeys: Set; } @@ -44,7 +39,6 @@ interface SubAgentActionCandidate { input: unknown; } -const MAX_SUB_AGENT_LOG_ENTRIES = 200; const MAX_SUB_AGENT_SUMMARY_CHARS = 160; function readTrimmedString(value: unknown): string | undefined { @@ -79,8 +73,7 @@ export class ClaudeSidechainTracker { needsSyntheticParentToolCard?: (toolUseId: string) => boolean; /** * The parent's tool call once Claude has answered it. A background child streams its frames - * after that answer, so its card keeps the settled status and output and gains the child's - * action log. + * after that answer, so its card keeps the settled status and output. */ getSettledParentToolCall?: (toolUseId: string) => ClaudeToolCallItem | undefined; }) { @@ -91,28 +84,27 @@ export class ClaudeSidechainTracker { } handleMessage(message: SDKMessage, parentToolUseId: string): AgentStreamEvent[] { + const existingState = this.activeSidechains.get(parentToolUseId); const state = - this.activeSidechains.get(parentToolUseId) ?? + existingState ?? ({ - actions: [], - actionKeys: [], - nextActionIndex: 1, - actionIndexByKey: new Map(), + runningCalls: new Map(), completedActionKeys: new Set(), } satisfies SubAgentActivityState); this.activeSidechains.set(parentToolUseId, state); - const contextUpdated = this.updateSubAgentContextFromTaskInput(state, parentToolUseId); + // The parent card is a launch marker: it changes only when the child is first seen or the + // task input names it differently, never with the child's activity. + const cardUpdated = + this.updateSubAgentContextFromTaskInput(state, parentToolUseId) || !existingState; const actionCandidates = this.extractSubAgentActionCandidates(message); const childTimelineItems = [ ...this.extractSubAgentTimelineItems(message, state), ...this.extractSubAgentToolResults(message, state), ]; - let actionUpdated = false; for (const action of actionCandidates) { if (state.completedActionKeys.has(action.key)) continue; - if (this.appendSubAgentAction(state, action)) { - actionUpdated = true; + if (this.trackChildCall(state, action)) { const toolCall = mapClaudeRunningToolCall({ name: action.toolName, callId: action.key, @@ -125,7 +117,7 @@ export class ClaudeSidechainTracker { } } - if (!contextUpdated && !actionUpdated && childTimelineItems.length === 0) { + if (!cardUpdated && childTimelineItems.length === 0) { return []; } @@ -145,11 +137,8 @@ export class ClaudeSidechainTracker { type: "sub_agent", ...(state.subAgentType ? { subAgentType: state.subAgentType } : {}), ...(state.description ? { description: state.description } : {}), - log: state.actions - .map((action) => - action.summary ? `[${action.toolName}] ${action.summary}` : `[${action.toolName}]`, - ) - .join("\n"), + // COMPAT(subagent-log): remove after 2027-04-30. + log: "", actions: [], }; @@ -170,18 +159,19 @@ export class ClaudeSidechainTracker { }, ]; - const parentCard: AgentStreamEvent[] = this.needsSyntheticParentToolCard(parentToolUseId) - ? [ - { - type: "timeline", - item: { - ...toolCall, - detail, + const parentCard: AgentStreamEvent[] = + cardUpdated && this.needsSyntheticParentToolCard(parentToolUseId) + ? [ + { + type: "timeline", + item: { + ...toolCall, + detail, + }, + provider: "claude", }, - provider: "claude", - }, - ] - : []; + ] + : []; return [ ...descriptorEvents, @@ -303,8 +293,7 @@ export class ClaudeSidechainTracker { if (!isClaudeContentChunk(block) || !block.type.endsWith("tool_result")) continue; const callId = readTrimmedString(block.tool_use_id); if (!callId || state.completedActionKeys.has(callId)) continue; - const actionIndex = state.actionIndexByKey.get(callId); - const action = actionIndex === undefined ? undefined : state.actions[actionIndex]; + const action = state.runningCalls.get(callId); const toolName = action?.toolName ?? readTrimmedString(block.tool_name); if (!toolName) continue; const params = { @@ -317,6 +306,7 @@ export class ClaudeSidechainTracker { ? mapClaudeFailedToolCall({ ...params, error: block }) : mapClaudeCompletedToolCall(params); if (toolCall) { + state.runningCalls.delete(callId); state.completedActionKeys.add(callId); items.push(toolCall); } @@ -412,13 +402,12 @@ export class ClaudeSidechainTracker { const key = readTrimmedString(block.id) ?? `stream:${block.name}:${typeof event.index === "number" ? event.index : 0}`; - return [ - { - key, - toolName: block.name, - input: block.input ?? null, - }, - ]; + // A streamed call starts with `{}` until its input arrives, so an empty input is not final. + const input = + block.input && typeof block.input === "object" && Object.keys(block.input).length > 0 + ? block.input + : null; + return [{ key, toolName: block.name, input }]; } private extractSubAgentActionCandidates(message: SDKMessage): SubAgentActionCandidate[] { @@ -448,84 +437,20 @@ export class ClaudeSidechainTracker { return []; } - private appendSubAgentAction( + /** Returns whether the call is new or has gained its input, so its running card changes. */ + private trackChildCall( state: SubAgentActivityState, candidate: SubAgentActionCandidate, ): boolean { - const normalizedToolName = readTrimmedString(candidate.toolName); - if (!normalizedToolName) { + const toolName = readTrimmedString(candidate.toolName); + if (!toolName) { return false; } - - const summary = this.deriveSubAgentActionSummary(normalizedToolName, candidate.input); - const existingIndex = state.actionIndexByKey.get(candidate.key); - - if (existingIndex !== undefined) { - const existing = state.actions[existingIndex]; - if (!existing) { - return false; - } - const nextSummary = existing.summary ?? summary; - if (existing.toolName === normalizedToolName && existing.summary === nextSummary) { - return false; - } - state.actions[existingIndex] = { - ...existing, - toolName: normalizedToolName, - input: existing.input ?? candidate.input, - ...(nextSummary ? { summary: nextSummary } : {}), - }; - return true; + const existing = state.runningCalls.get(candidate.key); + if (existing && (existing.input !== null || candidate.input === null)) { + return false; } - - state.actions.push({ - index: state.nextActionIndex, - toolName: normalizedToolName, - input: candidate.input, - ...(summary ? { summary } : {}), - }); - state.nextActionIndex += 1; - state.actionKeys.push(candidate.key); - this.trimSubAgentTail(state); - this.rebuildSubAgentActionIndex(state); + state.runningCalls.set(candidate.key, { toolName, input: candidate.input }); return true; } - - private trimSubAgentTail(state: SubAgentActivityState): void { - while (state.actions.length > MAX_SUB_AGENT_LOG_ENTRIES) { - state.actions.shift(); - const removedKey = state.actionKeys.shift(); - if (removedKey) state.completedActionKeys.delete(removedKey); - } - } - - private rebuildSubAgentActionIndex(state: SubAgentActivityState): void { - state.actionIndexByKey.clear(); - for (let index = 0; index < state.actionKeys.length; index += 1) { - const key = state.actionKeys[index]; - if (key) { - state.actionIndexByKey.set(key, index); - } - } - } - - private deriveSubAgentActionSummary(toolName: string, input: unknown): string | undefined { - const runningToolCall = mapClaudeRunningToolCall({ - name: toolName, - callId: `sub-agent-summary-${toolName}`, - input, - output: null, - }); - if (!runningToolCall) { - return undefined; - } - const display = buildToolCallDisplayModel({ - name: runningToolCall.name, - status: runningToolCall.status, - error: runningToolCall.error, - detail: runningToolCall.detail, - metadata: runningToolCall.metadata, - }); - return this.normalizeSubAgentText(display.summary); - } } diff --git a/packages/server/src/server/agent/providers/claude/subagents/live-source.test.ts b/packages/server/src/server/agent/providers/claude/subagents/live-source.test.ts index b0bfc3d755..b12ab8eb6a 100644 --- a/packages/server/src/server/agent/providers/claude/subagents/live-source.test.ts +++ b/packages/server/src/server/agent/providers/claude/subagents/live-source.test.ts @@ -156,6 +156,42 @@ describe("ClaudeTaskProtocolSource", () => { ]); }); + it("resumes a child a reopened session restored on its original row", () => { + const source = new ClaudeTaskProtocolSource(); + source.restore([ + { + taskId: "a1730a6215e1f5cf6", + id: "toolu_original", + presentation: { title: "general-purpose", model: "claude-sonnet-5", effort: "high" }, + }, + ]); + + // Restored is not running: a canceled turn and an unannounced frame leave it alone. + expect(source.cancelRunningForegroundTasks()).toEqual([]); + expect(source.resolveSubagentId("toolu_original")).toBeUndefined(); + + expect( + source.observe(taskStarted({ tool_use_id: "toolu_resumed", prompt: "Resumed prompt" })), + ).toEqual([ + { kind: "status", id: "toolu_original", status: "running" }, + { + kind: "timeline", + id: "toolu_original", + item: { type: "user_message", text: "Resumed prompt" }, + }, + ]); + expect(source.resolveSubagentId("toolu_original")).toBe("toolu_original"); + expect(source.resolveSubagentId("toolu_resumed")).toBe("toolu_original"); + expect( + source.observeSidechainFrame( + { type: "assistant", message: { model: "claude-opus-5" } } as unknown as SDKMessage, + "toolu_original", + ), + ).toEqual([ + { kind: "subtitle", id: "toolu_original", subtitle: "general-purpose · Opus 5 · High" }, + ]); + }); + it("declares a distinct task separately", () => { const source = new ClaudeTaskProtocolSource(); source.observe(taskStarted({ task_id: "first", tool_use_id: "toolu_first" })); diff --git a/packages/server/src/server/agent/providers/claude/subagents/live-source.ts b/packages/server/src/server/agent/providers/claude/subagents/live-source.ts index 2149fae139..b7b3201897 100644 --- a/packages/server/src/server/agent/providers/claude/subagents/live-source.ts +++ b/packages/server/src/server/agent/providers/claude/subagents/live-source.ts @@ -1,7 +1,8 @@ +import type { ProviderSubagentStatus } from "../../../provider-subagents/store.js"; +import { mapTaskStatus } from "./task-status.js"; import type { SDKMessage } from "@anthropic-ai/claude-agent-sdk"; import type { AgentMetadata } from "../../../agent-sdk-types.js"; -import type { ProviderSubagentStatus } from "../../../provider-subagents/store.js"; import { resolveObservedClaudeModelId } from "../models.js"; import type { SubagentObservation } from "./observation.js"; import { @@ -121,25 +122,13 @@ function readString(value: unknown): string | undefined { } /** - * The descriptor has no paused or pending state, and neither is terminal, so both read as - * running. `killed` is a cancellation, not a failure — the child was stopped, it did not error. + * A subagent a reopened session rebuilt from its transcript. Its `taskId` (the transcript's + * agentId) is the task id Claude announces again when SendMessage resumes the child. */ -function mapTaskStatus(status: string | undefined): ProviderSubagentStatus | undefined { - switch (status) { - case "pending": - case "running": - case "paused": - return "running"; - case "completed": - return "completed"; - case "failed": - return "failed"; - case "killed": - case "stopped": - return "canceled"; - default: - return undefined; - } +export interface ClaudeRestoredSubagent { + taskId: string; + id: string; + presentation: ClaudeSubagentPresentationFacts; } export interface ClaudeTaskProtocolSourceInput { @@ -183,6 +172,14 @@ export class ClaudeTaskProtocolSource { private readonly backgroundedIds = new Set(); /** Last status emitted per subagent, so a redundant announcement is not re-broadcast. */ private readonly lastStatusById = new Map(); + /** + * Children a reopened session restored from its transcript, by task id. Claude resumes one under + * its old task id with a new tool id, while its frames keep the original Task call as parent. + * Without this the resume reads as a new task: a second row, and every frame dropped as + * undeclared. Held apart from the declared table so a restored child is left alone until + * Claude announces it again. + */ + private readonly restoredByTaskId = new Map(); /** Claude facts stay inside the provider boundary; clients receive one compact subtitle. */ private readonly presentationById = new Map(); private readonly lastSubtitleById = new Map(); @@ -267,6 +264,14 @@ export class ClaudeTaskProtocolSource { } } + /** Remember the children a reopened session restored, for Claude to resume by task id. */ + restore(subagents: Iterable): void { + for (const subagent of subagents) { + if (this.subagentIdByTaskId.has(subagent.taskId)) continue; + this.restoredByTaskId.set(subagent.taskId, subagent); + } + } + /** * Forget the session. * @@ -280,6 +285,7 @@ export class ClaudeTaskProtocolSource { this.ownerSubagentIdByToolUseId.clear(); this.ownerSubagentIdByTaskId.clear(); this.declaredIds.clear(); + this.restoredByTaskId.clear(); this.workflowTaskIds.clear(); this.lastWorkflowResultByTaskId.clear(); this.idsWithExistingParentToolCard.clear(); @@ -336,7 +342,8 @@ export class ClaudeTaskProtocolSource { if (!id || message.skip_transcript === true || !isProviderSubagentTask(message)) return []; this.sawTaskStarted = true; - const existingId = this.subagentIdByTaskId.get(message.task_id); + const existingId = + this.subagentIdByTaskId.get(message.task_id) ?? this.adoptRestored(message.task_id); this.recordBackgrounded(existingId ?? id, message.is_backgrounded); if (existingId) { return this.observeExistingTaskStart(message, id, existingId); @@ -345,6 +352,20 @@ export class ClaudeTaskProtocolSource { return this.observeNewTaskStart(message, id, parentSubagentId); } + /** Declare a restored child under the id its transcript gave it, with what it already showed. */ + private adoptRestored(taskId: string): string | undefined { + const restored = this.restoredByTaskId.get(taskId); + if (!restored) return undefined; + this.restoredByTaskId.delete(taskId); + this.subagentIdByTaskId.set(taskId, restored.id); + this.canonicalIdByToolUseId.set(restored.id, restored.id); + this.declaredIds.add(restored.id); + this.presentationById.set(restored.id, restored.presentation); + const subtitle = buildClaudeSubagentSubtitle(restored.presentation); + if (subtitle) this.lastSubtitleById.set(restored.id, subtitle); + return restored.id; + } + private observeExistingTaskStart( message: TaskStartedMessage, toolUseId: string, diff --git a/packages/server/src/server/agent/providers/claude/subagents/replay-source.test.ts b/packages/server/src/server/agent/providers/claude/subagents/replay-source.test.ts index 413f39d427..fc48e9db3a 100644 --- a/packages/server/src/server/agent/providers/claude/subagents/replay-source.test.ts +++ b/packages/server/src/server/agent/providers/claude/subagents/replay-source.test.ts @@ -1,3 +1,9 @@ +import { readFile } from "node:fs/promises"; +import { fileURLToPath } from "node:url"; +import { + materializeProviderImage, + renderProviderImageOutputAsAssistantMarkdown, +} from "../../provider-image-output.js"; import type { SDKMessage } from "@anthropic-ai/claude-agent-sdk"; import { describe, expect, it } from "vitest"; @@ -30,7 +36,7 @@ function parentWithTaskCall(failed = false): ClaudeReplayParentFacts { ], ]), linksByAgentId: new Map(), - outcomesByToolCallId: new Map([[TOOL_USE_ID, { failed }]]), + outcomesByToolCallId: new Map([[TOOL_USE_ID, { status: failed ? "failed" : "completed" }]]), }; } @@ -79,6 +85,50 @@ describe("parseClaudeSubagentMeta", () => { }); describe("observeReplaySubagents", () => { + it("restores a resumed child on its original row after consuming async history", async () => { + async function* entries(): AsyncGenerator { + yield { type: "assistant", message: { model: "claude-opus-5" } }; + yield { + type: "assistant", + effort: "high", + message: { model: "claude-sonnet-5", usage: { input_tokens: 10, output_tokens: 2 } }, + }; + } + const replay = await observeReplaySubagents({ + subagents: [{ agentId: AGENT_ID, meta: { toolUseId: TOOL_USE_ID }, entries: entries() }], + parent: parentWithTaskCall(), + convertEntry: async () => [], + }); + expect(replay.restored).toEqual([ + { + taskId: AGENT_ID, + id: TOOL_USE_ID, + presentation: { + title: "general-purpose", + model: "claude-sonnet-5", + effort: "high", + usage: { totalTokens: 12 }, + }, + }, + ]); + const live = new ClaudeTaskProtocolSource(); + live.restore(replay.restored); + expect( + live.observe({ + type: "system", + subtype: "task_started", + task_id: AGENT_ID, + tool_use_id: "resumed-tool", + description: "Resume the captured task", + task_type: "local_agent", + is_backgrounded: true, + uuid: "00000000-0000-0000-0000-000000000000", + session_id: "reopened-session", + }), + ).toEqual([{ kind: "status", id: TOOL_USE_ID, status: "running" }]); + expect(live.resolveSubagentId("resumed-tool")).toBe(TOOL_USE_ID); + }); + it("links a subagent to its Task call through meta.toolUseId", async () => { const observations = ( await observeReplaySubagents({ @@ -111,7 +161,7 @@ describe("observeReplaySubagents", () => { [nestedToolUseId, { title: "Explore", description: "Nested audit" }], ]), linksByAgentId: new Map(), - outcomesByToolCallId: new Map([[nestedToolUseId, { failed: false }]]), + outcomesByToolCallId: new Map([[nestedToolUseId, { status: "completed" }]]), }, }, { @@ -167,8 +217,8 @@ describe("observeReplaySubagents", () => { it("falls back to the scraped link when there is no meta file", async () => { const parent: ClaudeReplayParentFacts = { toolCalls: new Map([[TOOL_USE_ID, { title: "Explore" }]]), - linksByAgentId: new Map([[AGENT_ID, { toolCallId: TOOL_USE_ID, failed: false }]]), - outcomesByToolCallId: new Map(), + linksByAgentId: new Map([[AGENT_ID, { toolCallId: TOOL_USE_ID }]]), + outcomesByToolCallId: new Map([[TOOL_USE_ID, { status: "completed" }]]), }; const [declared, ...rest] = ( @@ -257,8 +307,8 @@ describe("observeReplaySubagents", () => { subagents: [{ agentId: AGENT_ID, meta: null, entries: [] }], parent: { toolCalls: new Map([[TOOL_USE_ID, { title: "Explore" }]]), - linksByAgentId: new Map([[AGENT_ID, { toolCallId: TOOL_USE_ID, failed: true }]]), - outcomesByToolCallId: new Map(), + linksByAgentId: new Map([[AGENT_ID, { toolCallId: TOOL_USE_ID }]]), + outcomesByToolCallId: new Map([[TOOL_USE_ID, { status: "failed" }]]), }, convertEntry: () => [], }) @@ -660,3 +710,34 @@ describe("live and replay agree", () => { }); }); }); + +it("awaits image materialization before publishing replay observations", async () => { + const bytes = Buffer.from("async replay image fixture"); + const convertEntry = async () => { + const item = await renderProviderImageOutputAsAssistantMarkdown( + { data: bytes.toString("base64"), mimeType: "image/png" }, + { materialize: materializeProviderImage }, + ); + return item ? [item] : []; + }; + const { observations } = await observeReplaySubagents({ + parent: parentWithTaskCall(), + subagents: [ + { + agentId: AGENT_ID, + meta: { toolUseId: TOOL_USE_ID }, + entries: [{ type: "assistant", message: { content: [] } }], + }, + ], + convertEntry, + }); + const image = observations.find( + (observation) => + observation.kind === "timeline" && observation.item.type === "assistant_message", + ); + if (!image || image.kind !== "timeline" || image.item.type !== "assistant_message") + throw new Error("Expected replay image"); + const source = image.item.text.match(/!\[Image\]\(([^)]+)\)/)?.[1]; + expect(source).toBeTruthy(); + expect(await readFile(fileURLToPath(source!))).toEqual(bytes); +}); diff --git a/packages/server/src/server/agent/providers/claude/subagents/replay-source.ts b/packages/server/src/server/agent/providers/claude/subagents/replay-source.ts index 567a98dfe5..51e5ff9c09 100644 --- a/packages/server/src/server/agent/providers/claude/subagents/replay-source.ts +++ b/packages/server/src/server/agent/providers/claude/subagents/replay-source.ts @@ -3,7 +3,9 @@ import { z } from "zod"; import type { AgentTimelineItem } from "../../../agent-sdk-types.js"; import { normalizeProviderReplayTimestamp } from "../../../provider-history-timestamps.js"; import type { ProviderSubagentStatus } from "../../../provider-subagents/store.js"; +import { isClaudeInterruptPlaceholderText } from "../interrupt-placeholder.js"; import { resolveObservedClaudeModelId } from "../models.js"; +import type { ClaudeRestoredSubagent } from "./live-source.js"; import type { SubagentObservation } from "./observation.js"; import { buildClaudeSubagentSubtitle, type ClaudeSubagentUsage } from "./presentation.js"; @@ -139,9 +141,12 @@ export interface ClaudeReplayParentFacts { /** Task `tool_use` id -> identity declared in the parent's tool input. */ toolCalls: ReadonlyMap; /** agentId -> tool call, recovered by scraping tool-result text. Legacy fallback only. */ - linksByAgentId: ReadonlyMap; - /** Task `tool_use` id -> outcome. Usable once meta.json supplies the link directly. */ - outcomesByToolCallId: ReadonlyMap; + linksByAgentId: ReadonlyMap; + /** + * Task `tool_use` id -> outcome, whichever way the child was linked. A background launch has + * none: its immediate result only says the child started. + */ + outcomesByToolCallId: ReadonlyMap; } interface ParentLink { @@ -177,27 +182,14 @@ function resolveParentLink( parent: ClaudeReplayParentFacts, ): ParentLink | null { const metaToolUseId = subagent.meta?.toolUseId?.trim(); - if (metaToolUseId && parent.toolCalls.has(metaToolUseId)) { - const outcome = parent.outcomesByToolCallId.get(metaToolUseId); - let status: ProviderSubagentStatus | null = null; - if (outcome) status = outcome.failed ? "failed" : "completed"; - return { - id: metaToolUseId, - toolCallId: metaToolUseId, - status, - }; - } + const toolCallId = + metaToolUseId && parent.toolCalls.has(metaToolUseId) + ? metaToolUseId + : parent.linksByAgentId.get(subagent.agentId)?.toolCallId; + if (!toolCallId || !parent.toolCalls.has(toolCallId)) return null; - const scraped = parent.linksByAgentId.get(subagent.agentId); - if (scraped && parent.toolCalls.has(scraped.toolCallId)) { - return { - id: scraped.toolCallId, - toolCallId: scraped.toolCallId, - status: scraped.failed ? "failed" : "completed", - }; - } - - return null; + const status = parent.outcomesByToolCallId.get(toolCallId)?.status ?? null; + return { id: toolCallId, toolCallId, status }; } /** @@ -253,8 +245,9 @@ function observeSubtitle( async function observeSubagent( subagent: ClaudeReplaySubagentInput, parent: ClaudeReplayParentFacts, - convertEntry: (entry: ClaudeReplayEntry) => AgentTimelineItem[], + convertEntry: (entry: ClaudeReplayEntry) => AgentTimelineItem[] | Promise, toolOwners: Map, + restored: ClaudeRestoredSubagent[], parentSubagentId?: string, ): Promise { const link = resolveParentLink(subagent, parent); @@ -276,24 +269,23 @@ async function observeSubagent( lastTimestamp = timestamp; Object.assign(runtime, readRuntime(entry)); usage = readUsage(entry) ?? usage; - if (entry.type === "assistant") { - childTerminalStatus = entry.message?.stop_reason === "end_turn" ? "completed" : null; - } + childTerminalStatus = readChildTerminalStatus(entry, childTerminalStatus); recordReplayToolOwners(toolOwners, entry, link.id); - for (const item of convertEntry(entry)) { + for (const item of await convertEntry(entry)) { timeline.push({ kind: "timeline", id: link.id, item, ...(timestamp ? { timestamp } : {}) }); } } const observations = [ declareSubagent(subagent, link, toolCall, parentSubagentId, firstTimestamp), ]; - const subtitle = observeSubtitle( - link, - toolCall?.title ?? subagent.meta?.agentType, - runtime, - usage, - lastTimestamp, - ); + const title = toolCall?.title ?? subagent.meta?.agentType; + // The agentId is the task_id Claude resumes this child under, so live can find it again. + restored.push({ + taskId: subagent.agentId, + id: link.id, + presentation: { ...(title ? { title } : {}), ...runtime, ...(usage ? { usage } : {}) }, + }); + const subtitle = observeSubtitle(link, title, runtime, usage, lastTimestamp); if (subtitle) observations.push(subtitle); for (const observation of timeline) observations.push(observation); const terminalStatus = link.status ?? childTerminalStatus; @@ -308,6 +300,30 @@ async function observeSubagent( return observations; } +/** Advance the child's fallback outcome without retaining transcript entries. */ +function readChildTerminalStatus( + entry: ClaudeReplayEntry, + previous: ProviderSubagentStatus | null, +): ProviderSubagentStatus | null { + if (entry.type === "assistant") { + return entry.message?.stop_reason === "end_turn" ? "completed" : null; + } + if (entry.type !== "user") return previous; + const texts = readUserTexts(entry); + if (texts.length === 0) return previous; + return texts.some(isClaudeInterruptPlaceholderText) ? "canceled" : null; +} + +/** Tool results carry no user text and do not change the child's terminal status. */ +function readUserTexts(entry: ClaudeReplayEntry): string[] { + const content = entry.message?.content; + if (typeof content === "string") return [content]; + if (!Array.isArray(content)) return []; + return content.flatMap((block: { type?: unknown; text?: unknown } | null) => + block?.type === "text" && typeof block.text === "string" ? [block.text] : [], + ); +} + function recordReplayToolOwners( owners: Map, entry: ClaudeReplayEntry, @@ -323,10 +339,15 @@ function recordReplayToolOwners( export async function observeReplaySubagents(input: { subagents: readonly ClaudeReplaySubagentInput[]; parent: ClaudeReplayParentFacts; - convertEntry: (entry: ClaudeReplayEntry) => AgentTimelineItem[]; -}): Promise<{ observations: SubagentObservation[]; toolOwners: ReadonlyMap }> { + convertEntry: (entry: ClaudeReplayEntry) => AgentTimelineItem[] | Promise; +}): Promise<{ + observations: SubagentObservation[]; + toolOwners: ReadonlyMap; + restored: readonly ClaudeRestoredSubagent[]; +}> { const observations: SubagentObservation[] = []; const toolOwners = new Map(); + const restored: ClaudeRestoredSubagent[] = []; const unresolved = [...input.subagents].sort( (left, right) => (left.meta?.spawnDepth ?? 1) - (right.meta?.spawnDepth ?? 1), ); @@ -351,6 +372,7 @@ export async function observeReplaySubagents(input: { parent, input.convertEntry, toolOwners, + restored, ownerId, )) { observations.push(observation); @@ -360,7 +382,7 @@ export async function observeReplaySubagents(input: { madeProgress = true; } } - return { observations, toolOwners }; + return { observations, toolOwners, restored }; } function resolveReplayOwner( diff --git a/packages/server/src/server/agent/providers/claude/subagents/task-status.ts b/packages/server/src/server/agent/providers/claude/subagents/task-status.ts new file mode 100644 index 0000000000..a488ce12d7 --- /dev/null +++ b/packages/server/src/server/agent/providers/claude/subagents/task-status.ts @@ -0,0 +1,23 @@ +import type { ProviderSubagentStatus } from "../../../provider-subagents/store.js"; + +/** + * The descriptor has no paused or pending state, and neither is terminal, so both read as + * running. `killed` is a cancellation, not a failure — the child was stopped, it did not error. + */ +export function mapTaskStatus(status: string | undefined): ProviderSubagentStatus | undefined { + switch (status) { + case "pending": + case "running": + case "paused": + return "running"; + case "completed": + return "completed"; + case "failed": + return "failed"; + case "killed": + case "stopped": + return "canceled"; + default: + return undefined; + } +} diff --git a/packages/server/src/server/agent/providers/claude/subagents/workflow-replay-source.test.ts b/packages/server/src/server/agent/providers/claude/subagents/workflow-replay-source.test.ts index af03a515b7..edb673c664 100644 --- a/packages/server/src/server/agent/providers/claude/subagents/workflow-replay-source.test.ts +++ b/packages/server/src/server/agent/providers/claude/subagents/workflow-replay-source.test.ts @@ -1,3 +1,9 @@ +import { readFile } from "node:fs/promises"; +import { fileURLToPath } from "node:url"; +import { + materializeProviderImage, + renderProviderImageOutputAsAssistantMarkdown, +} from "../../provider-image-output.js"; import { describe, expect, it } from "vitest"; import { ProviderSubagentStore } from "../../../provider-subagents/store.js"; @@ -195,3 +201,29 @@ describe("Claude workflow replay", () => { }, ); }); + +it("awaits image materialization before publishing replay observations", async () => { + const bytes = Buffer.from("async replay image fixture"); + const convertEntry = async () => { + const item = await renderProviderImageOutputAsAssistantMarkdown( + { data: bytes.toString("base64"), mimeType: "image/png" }, + { materialize: materializeProviderImage }, + ); + return item ? [item] : []; + }; + const observations = await observeReplayWorkflows({ + workflows: [{ runId: RUN_ID, status: "completed" }], + parentEntries: parentEntries(), + entriesByRunId: new Map([[RUN_ID, [{ type: "assistant", message: { content: [] } }]]]), + convertEntry, + }); + const image = observations.find( + (observation) => + observation.kind === "timeline" && observation.item.type === "assistant_message", + ); + if (!image || image.kind !== "timeline" || image.item.type !== "assistant_message") + throw new Error("Expected replay image"); + const source = image.item.text.match(/!\[Image\]\(([^)]+)\)/)?.[1]; + expect(source).toBeTruthy(); + expect(await readFile(fileURLToPath(source!))).toEqual(bytes); +}); diff --git a/packages/server/src/server/agent/providers/claude/subagents/workflow-replay-source.ts b/packages/server/src/server/agent/providers/claude/subagents/workflow-replay-source.ts index 7496ce7c8d..17a278d00f 100644 --- a/packages/server/src/server/agent/providers/claude/subagents/workflow-replay-source.ts +++ b/packages/server/src/server/agent/providers/claude/subagents/workflow-replay-source.ts @@ -53,7 +53,7 @@ export async function observeReplayWorkflows(input: { string, Iterable | AsyncIterable >; - convertEntry?: (entry: ClaudeReplayEntry) => AgentTimelineItem[]; + convertEntry?: (entry: ClaudeReplayEntry) => AgentTimelineItem[] | Promise; }): Promise { const toolCallIdByRunId = await readWorkflowLinks(input.parentEntries); const observations: SubagentObservation[] = []; @@ -122,7 +122,7 @@ async function observeWorkflowTimeline(input: { id: string; result: unknown; entries: Iterable | AsyncIterable; - convertEntry?: (entry: ClaudeReplayEntry) => AgentTimelineItem[]; + convertEntry?: (entry: ClaudeReplayEntry) => AgentTimelineItem[] | Promise; finishedAt?: string; }): Promise { const observations: SubagentObservation[] = []; @@ -130,7 +130,7 @@ async function observeWorkflowTimeline(input: { for await (const entry of input.entries) { const timestamp = normalizeProviderReplayTimestamp(entry.timestamp); - const items = input.convertEntry?.(entry) ?? []; + const items = (await input.convertEntry?.(entry)) ?? []; for (const item of items) { if (item.type === "assistant_message") replayedAssistantText.add(item.text.trim()); observations.push({ diff --git a/packages/server/src/server/agent/providers/claude/task-notification-tool-call.ts b/packages/server/src/server/agent/providers/claude/task-notification-tool-call.ts index c8e38bf918..76ad89d8ef 100644 --- a/packages/server/src/server/agent/providers/claude/task-notification-tool-call.ts +++ b/packages/server/src/server/agent/providers/claude/task-notification-tool-call.ts @@ -407,19 +407,21 @@ export function mapTaskNotificationSystemRecordToToolCall( } export function readTaskNotificationToolUseIdFromHistoryRecord(record: unknown): string | null { + return readTaskNotificationFromHistoryRecord(record)?.toolUseId ?? null; +} + +export function readTaskNotificationFromHistoryRecord( + record: unknown, +): TaskNotificationEnvelope | null { const parsedRecord = TaskNotificationHistoryRecordSchema.safeParse(record); - if (!parsedRecord.success) { - return null; - } + if (!parsedRecord.success) return null; if (parsedRecord.data.type === "user" && parsedRecord.data.message) { - return ( - parseTaskNotificationFromUserContent({ - content: parsedRecord.data.message.content, - messageId: parsedRecord.data.uuid ?? parsedRecord.data.message_id, - })?.toolUseId ?? null - ); + return parseTaskNotificationFromUserContent({ + content: parsedRecord.data.message.content, + messageId: parsedRecord.data.uuid ?? parsedRecord.data.message_id, + }); } - return parseTaskNotificationFromSystemRecord(record)?.toolUseId ?? null; + return parseTaskNotificationFromSystemRecord(record); } export function coerceTaskNotificationHistoryRecordToSystemMessage( diff --git a/packages/server/src/server/agent/providers/codex-app-server-agent.local.e2e.test.ts b/packages/server/src/server/agent/providers/codex-app-server-agent.local.e2e.test.ts index 0469d9fbe1..dc7f920993 100644 --- a/packages/server/src/server/agent/providers/codex-app-server-agent.local.e2e.test.ts +++ b/packages/server/src/server/agent/providers/codex-app-server-agent.local.e2e.test.ts @@ -264,6 +264,98 @@ describe("Codex app-server provider (local e2e)", () => { 30_000, ); + test.runIf(isCodexInstalled())( + "reopens a promptless agent repeatedly before its first model request", + async () => { + const cwd = mkdtempSync(path.join(os.tmpdir(), "codex-promptless-cwd-")); + const logger = createTestLogger(); + const storage = new AgentStorage(path.join(cwd, "agents"), logger); + const manager = new AgentManager({ + clients: { codex: new CodexAppServerAgentClient(logger) }, + registry: storage, + logger, + }); + let agentId: string | undefined; + try { + const created = await manager.createAgent( + { provider: "codex", cwd, modeId: "auto", model: "mock-model" }, + undefined, + { workspaceId: undefined }, + ); + agentId = created.id; + // A real app-server rejects an unsaved thread on resume. No model request is + // needed to prove that reopening the agent remains safe before its first turn. + for (let i = 0; i < 2; i++) { + const reopened = await manager.reloadAgentSession(agentId); + expect(reopened.lifecycle).toBe("idle"); + expect(reopened.persistence).toBeNull(); + } + await storage.flush(); + expect((await storage.get(agentId))?.persistence).toBeNull(); + } finally { + if (agentId && manager.getAgent(agentId)) await manager.closeAgent(agentId); + await storage.flush(); + rmSync(cwd, { recursive: true, force: true }); + } + }, + 30_000, + ); + + test.runIf(isCodexInstalled())( + "reopens an agent that was never prompted without resuming its unsaved thread", + async () => { + const cwd = mkdtempSync(path.join(os.tmpdir(), "codex-unprompted-cwd-")); + const codexHome = mkdtempSync(path.join(os.tmpdir(), "codex-unprompted-home-")); + const mockServer = await startMockResponsesServer([ + assistantMessageSse("first"), + assistantMessageSse("second"), + ]); + const logger = createTestLogger(); + const storage = new AgentStorage(path.join(cwd, "agents"), logger); + const manager = new AgentManager({ + clients: { codex: new CodexAppServerAgentClient(logger) }, + registry: storage, + logger, + }); + let agentId: string | undefined; + try { + writeMockCodexConfig(codexHome, mockServer.url); + vi.stubEnv("CODEX_HOME", codexHome); + const created = await manager.createAgent( + { provider: "codex", cwd, modeId: "auto", model: "mock-model" }, + undefined, + { workspaceId: undefined }, + ); + agentId = created.id; + // Codex writes a thread's rollout at its first turn, so there is nothing to resume yet. + expect(manager.getAgent(agentId)?.persistence).toBeNull(); + await storage.flush(); + expect((await storage.get(agentId))?.persistence).toBeNull(); + + await manager.reloadAgentSession(agentId); + await manager.runAgent(agentId, "first prompt after reopening"); + const threadId = manager.getAgent(agentId)?.persistence?.sessionId; + expect(threadId).toEqual(expect.any(String)); + await storage.flush(); + expect((await storage.get(agentId))?.persistence?.sessionId).toBe(threadId); + + const reloaded = await manager.reloadAgentSession(agentId); + expect(reloaded.persistence?.sessionId).toBe(threadId); + await manager.runAgent(agentId, "continue the saved thread"); + expect(manager.getAgent(agentId)?.lifecycle).toBe("idle"); + expect(mockServer.requestBodies.at(-1)).toContain("first prompt after reopening"); + } finally { + if (agentId && manager.getAgent(agentId)) await manager.closeAgent(agentId); + await storage.flush(); + vi.unstubAllEnvs(); + await mockServer.close(); + rmSync(cwd, { recursive: true, force: true }); + rmSync(codexHome, { recursive: true, force: true }); + } + }, + 30_000, + ); + test.runIf(isCodexInstalled())( "surfaces request_user_input from the app-server as question permissions and timeline tool calls", async () => { diff --git a/packages/server/src/server/agent/providers/codex-app-server-agent.real.e2e.test.ts b/packages/server/src/server/agent/providers/codex-app-server-agent.real.e2e.test.ts index 5a6592862c..f564b7bf94 100644 --- a/packages/server/src/server/agent/providers/codex-app-server-agent.real.e2e.test.ts +++ b/packages/server/src/server/agent/providers/codex-app-server-agent.real.e2e.test.ts @@ -77,12 +77,19 @@ CHILD_SENTINEL in your own response. const completedChildIndex = events.findIndex( (event) => - event.type === "timeline" && - event.item.type === "tool_call" && - event.item.status === "completed" && - event.item.detail.type === "sub_agent" && - event.item.detail.log.includes("CHILD_SENTINEL"), + event.type === "provider_subagent" && + event.event.type === "upsert" && + event.event.status === "completed", ); + const childAssistantText = events + .flatMap((event) => + event.type === "provider_subagent" && + event.event.type === "timeline" && + event.event.item.type === "assistant_message" + ? [event.event.item.text] + : [], + ) + .join(""); const rootMessageIndexes = events.flatMap((event, index) => event.type === "timeline" && event.item.type === "assistant_message" ? [index] : [], ); @@ -105,6 +112,7 @@ CHILD_SENTINEL in your own response. .map((item) => item.text) .join(""); expect(topLevelAssistantText).not.toContain("CHILD_SENTINEL"); + expect(childAssistantText).toContain("CHILD_SENTINEL"); expect(completedChildIndex).toBeGreaterThanOrEqual(0); expect(rootMessageIndexes[0]).toBeGreaterThan(completedChildIndex); expect(terminalIndexes).toHaveLength(1); diff --git a/packages/server/src/server/agent/providers/codex-app-server-agent.test.ts b/packages/server/src/server/agent/providers/codex-app-server-agent.test.ts index 8c61635d6f..9986357cf4 100644 --- a/packages/server/src/server/agent/providers/codex-app-server-agent.test.ts +++ b/packages/server/src/server/agent/providers/codex-app-server-agent.test.ts @@ -16,6 +16,7 @@ import type { AgentSessionConfig, AgentSlashCommand, AgentStreamEvent, + AgentTimelineItem, } from "../agent-sdk-types.js"; import { buildCodexAppServerEnv, @@ -87,7 +88,9 @@ describe("Codex executable discovery", () => { import { CodexAppServerClient } from "./codex/app-server-transport.js"; import { createFakeCodexAppServer, + fakeCodexThreadHistory, type FakeCodexAppServer, + waitForNextEvent, waitForNextPermission, waitForNextTimelineItem, waitForProviderSubagent, @@ -113,8 +116,7 @@ interface CodexSessionTestAccess { }; ensureThreadLoaded(): Promise; handleToolApprovalRequest(params: unknown): Promise; - handleNotification(method: string, params: unknown): void; - loadPersistedHistory(client: CodexClientLike | null): Promise; + handleNotification(method: string, params: unknown): Promise; refreshResolvedCollaborationMode(): void; serviceTier: "fast" | null; planModeEnabled: boolean; @@ -212,6 +214,7 @@ async function startPublicSteeringSession( const started = await session.startTurn("first"); await appServer.waitForTurnStart(); appServer.startsTurn({ threadId: "thread-1", turnId: "native-A" }); + await new Promise((resolve) => setImmediate(resolve)); await new Promise((resolve) => setTimeout(resolve, 0)); return { session, paseoTurnId: started.turnId }; } @@ -225,6 +228,64 @@ function deferred() { } describe("Codex active-turn steering admission", () => { + test("steers an accepted turn whose native id arrives after startTurn returns", async () => { + const appServer = createFakeCodexAppServer({ + "turn/steer": () => ({ turn: { id: "native-A" } }), + }); + const session = new CodexAppServerAgentSession( + createConfig({ cwd: "/workspace/project" }), + null, + createTestLogger(), + async () => appServer.child, + ); + try { + const { turnId } = await session.startTurn("FIRST"); + const steer = session.steerActiveTurn("SECOND", { expectedTurnId: turnId }); + appServer.startsTurn({ threadId: "thread-1", turnId: "native-A" }); + + await expect(steer).resolves.toEqual({ status: "accepted" }); + expect( + appServer.requests().filter((request) => request.method === "turn/start"), + ).toHaveLength(1); + expect(appServer.requests().filter((request) => request.method === "turn/interrupt")).toEqual( + [], + ); + expect(appServer.requests().find((request) => request.method === "turn/steer")).toMatchObject( + { + params: { + threadId: "thread-1", + expectedTurnId: "native-A", + input: [{ type: "text", text: "SECOND" }], + }, + }, + ); + appServer.assertNoErrors(); + } finally { + await session.close(); + } + }); + + test("releases a waiting steer when the accepted turn ends before identification", async () => { + const appServer = createFakeCodexAppServer(); + const session = new CodexAppServerAgentSession( + createConfig({ cwd: "/workspace/project" }), + null, + createTestLogger(), + async () => appServer.child, + ); + try { + const { turnId } = await session.startTurn("FIRST"); + const steer = session.steerActiveTurn("SECOND", { expectedTurnId: turnId }); + appServer.completeTurn(); + + await expect(steer).resolves.toEqual({ status: "unavailable" }); + expect(appServer.requests().filter((request) => request.method === "turn/steer")).toEqual([]); + appServer.assertNoErrors(); + } finally { + await session.close(); + } + }); + test("a steer without the clearing contract leaves permissions open", async () => { const appServer = createFakeCodexAppServer({ "turn/steer": () => ({ turn: { id: "native-A" } }), @@ -354,9 +415,11 @@ describe("Codex active-turn steering admission", () => { }); await resolverEntered.promise; appServer.completeTurn({ threadId: "thread-1" }); + await new Promise((resolve) => setImmediate(resolve)); await new Promise((resolve) => setTimeout(resolve, 0)); const startedB = await session.startTurn("second"); appServer.startsTurn({ threadId: "thread-1", turnId: "native-B" }); + await new Promise((resolve) => setImmediate(resolve)); await new Promise((resolve) => setTimeout(resolve, 0)); commandResolution.resolve(null); @@ -478,6 +541,7 @@ async function startCompactionTurnTest(): Promise<{ await session.startTurn("exercise compaction lifecycle"); appServer.startsTurn({ threadId: "thread-1", turnId: "codex-turn-1" }); + await new Promise((resolve) => setImmediate(resolve)); return { appServer, session, events, terminalEvent }; } @@ -499,6 +563,81 @@ function archivedThreadErrorMessage(threadId: string): string { ); } +function codexUserItem(id: string, text: string) { + return { type: "userMessage", id, content: [{ type: "text", text }] }; +} + +function codexAgentItem(text: string) { + return { type: "agentMessage", id: `agent-${text}`, text }; +} + +// An AgentManager over a real Codex provider whose every spawn gets a fresh fake +// app-server serving `threads` from thread/read. +function createReopenableCodexAgent(threads: Record) { + const appServers: FakeCodexAppServer[] = []; + const provider = new CodexAppServerAgentClient(createTestLogger()); + const internals = castInternals<{ + goalsEnabledPromise: Promise | null; + autoReviewEnabledPromise: Promise | null; + spawnAppServer: () => Promise; + }>(provider); + internals.goalsEnabledPromise = Promise.resolve(false); + internals.autoReviewEnabledPromise = Promise.resolve(false); + internals.spawnAppServer = async () => { + const appServer = createFakeCodexAppServer({ + "thread/read": (params) => { + const { threadId } = params as { threadId: string }; + return { thread: { id: threadId, turns: threads[threadId] ?? [] } }; + }, + }); + appServers.push(appServer); + return appServer.child; + }; + // The fake app-server stands in for the Codex CLI, which test machines may not have. + const client: AgentClient = { + provider: "codex", + capabilities: provider.capabilities, + isAvailable: async () => true, + fetchCatalog: async () => ({ models: [], modes: [] }), + createSession: async () => { + throw new Error("Unexpected create"); + }, + resumeSession: (...args) => provider.resumeSession(...args), + }; + const manager = new AgentManager({ clients: { codex: client }, logger: createTestLogger() }); + const agentId = "00000000-0000-4000-8000-000000000001"; + const handle = { provider: "codex", sessionId: "saved-thread" }; + const config = createConfig({ cwd: process.cwd() }); + + async function open(): Promise { + await manager.resumeAgentFromPersistence(handle, config, agentId); + await manager.hydrateTimelineFromProvider(agentId); + } + + return { + manager, + agentId, + latestAppServer: () => appServers[appServers.length - 1], + threadMethods: (index: number) => + appServers[index] + .requests() + .map((request) => request.method) + .filter((method) => typeof method === "string" && method.startsWith("thread/")), + // Cold-loads the agent, closes its runtime, and reopens it while Paseo keeps its timeline. + async loadCloseAndReopen(): Promise { + await open(); + const projected = manager.getTimeline(agentId); + await manager.closeAgent(agentId); + await open(); + return projected; + }, + async close(): Promise { + await manager.closeAgent(agentId); + for (const appServer of appServers) appServer.assertNoErrors(); + }, + }; +} + function asInternals(session: CodexTestSession): CodexSessionTestAccess { return castInternals(session); } @@ -1149,6 +1288,9 @@ describe("Codex app-server provider", () => { ); await firstSession.startTurn("first turn"); await expect(beforeRestart.waitForTurnStart()).resolves.toMatchObject({ effort: "medium" }); + const saved = waitForNextEvent(firstSession, "thread_started"); + beforeRestart.startsTurn({ threadId: "thread-1" }); + await saved; const handle = firstSession.describePersistence()!; await firstSession.close(); @@ -1181,6 +1323,9 @@ describe("Codex app-server provider", () => { try { await session.startTurn("persist the configured session"); await appServer.waitForTurnStart(); + const saved = waitForNextEvent(session, "thread_started"); + appServer.startsTurn({ threadId: "thread-1" }); + await saved; const handle = session.describePersistence()!; expect(handle.metadata).not.toHaveProperty("providerOptions"); appServer.assertNoErrors(); @@ -1189,6 +1334,55 @@ describe("Codex app-server provider", () => { } }); + test("reports a new thread only after Codex announces its first turn", async () => { + const appServer = createFakeCodexAppServer(); + const session = await createProviderWithFakeAppServer(appServer).createSession(createConfig()); + try { + // Codex has started the thread but writes its rollout at the first turn, so another + // app-server could not resume it yet. + await expect(session.getRuntimeInfo()).resolves.toMatchObject({ sessionId: null }); + expect(session.describePersistence()).toBeNull(); + expect( + appServer.requests().filter((request) => request.method === "thread/start"), + ).toHaveLength(1); + + await session.startTurn("first prompt"); + await appServer.waitForTurnStart(); + expect(session.describePersistence()).toBeNull(); + + const saved = waitForNextEvent(session, "thread_started"); + appServer.startsTurn({ threadId: "thread-1" }); + await expect(saved).resolves.toMatchObject({ + type: "thread_started", + provider: "codex", + sessionId: "thread-1", + }); + expect(session.describePersistence()).toMatchObject({ + sessionId: "thread-1", + nativeHandle: "thread-1", + }); + await expect(session.getRuntimeInfo()).resolves.toMatchObject({ sessionId: "thread-1" }); + appServer.assertNoErrors(); + } finally { + await session.close(); + } + }); + + test("reports a resumed thread before its next turn", async () => { + const appServer = createFakeCodexAppServer(); + const session = await createProviderWithFakeAppServer(appServer).resumeSession( + { provider: "codex", sessionId: "saved-thread" }, + createConfig(), + ); + try { + expect(session.describePersistence()).toMatchObject({ sessionId: "saved-thread" }); + await expect(session.getRuntimeInfo()).resolves.toMatchObject({ sessionId: "saved-thread" }); + appServer.assertNoErrors(); + } finally { + await session.close(); + } + }); + test("preapproves only granted tools on the injected Codex MCP server", async () => { const session = createSession({ modeId: undefined, @@ -1460,7 +1654,9 @@ describe("Codex app-server provider", () => { command: "gh pr merge 2030 --squash", cwd: "/workspace/project", }); + await new Promise((resolve) => setImmediate(resolve)); appServer.says({ threadId: "thread-1", text: "Merged." }); + await new Promise((resolve) => setImmediate(resolve)); await expect(nextTimelineItem).resolves.toEqual({ type: "timeline", @@ -1504,6 +1700,7 @@ describe("Codex app-server provider", () => { command: "gh pr merge 2030 --squash", cwd: "/workspace/project", }); + await new Promise((resolve) => setImmediate(resolve)); await expect(nextTimelineItem).resolves.toEqual({ type: "timeline", @@ -1548,6 +1745,7 @@ describe("Codex app-server provider", () => { processId: "4242", text: "gh pr merge 2030 --squash\n", }); + await new Promise((resolve) => setImmediate(resolve)); await expect(nextTimelineItem).resolves.toEqual({ type: "timeline", @@ -1576,6 +1774,7 @@ describe("Codex app-server provider", () => { command: "sleep 30", output: "Process running with session id 4242", }); + await new Promise((resolve) => setImmediate(resolve)); await expect(relabeledTerminal).resolves.toEqual({ type: "timeline", @@ -1623,6 +1822,7 @@ describe("Codex app-server provider", () => { processId: "73", command, }); + await new Promise((resolve) => setImmediate(resolve)); const terminalWrite = waitForTimelineToolCall(session, "terminal-session-73-1"); appServer.typesIntoTerminal({ @@ -1632,6 +1832,7 @@ describe("Codex app-server provider", () => { processId: "73", text: "print(1)\n", }); + await new Promise((resolve) => setImmediate(resolve)); await expect(terminalWrite).resolves.toMatchObject({ item: { @@ -1668,7 +1869,9 @@ describe("Codex app-server provider", () => { processId: "4242", text: "git status\n", }); + await new Promise((resolve) => setImmediate(resolve)); + await firstTimelineItem; const secondTimelineItem = waitForNextTimelineItem(session); appServer.typesIntoTerminal({ threadId: "thread-1", @@ -1677,6 +1880,7 @@ describe("Codex app-server provider", () => { processId: "4242", text: "git push\n", }); + await new Promise((resolve) => setImmediate(resolve)); const [first, second] = await Promise.all([firstTimelineItem, secondTimelineItem]); expect(first.item).toMatchObject({ @@ -1844,7 +2048,7 @@ describe("Codex app-server provider", () => { purpose: "history", }); - expect(threadRequests).toEqual(["thread/read"]); + expect(threadRequests).toEqual(["thread/read", "thread/read"]); await session.close(); appServer.assertNoErrors(); }); @@ -1883,12 +2087,148 @@ describe("Codex app-server provider", () => { "thread/resume", "thread/unarchive", "thread/resume", - "thread/read", ]); await session.close(); appServer.assertNoErrors(); }); + test("resumes a Codex thread without asking for its turns", async () => { + const appServer = createFakeCodexAppServer(); + const provider = createProviderWithFakeAppServer(appServer); + + const session = await provider.resumeSession({ sessionId: "saved-thread" }); + + expect( + appServer + .requests() + .filter((request) => request.method === "thread/resume") + .map((request) => request.params), + ).toEqual([expect.objectContaining({ threadId: "saved-thread", excludeTurns: true })]); + await session.close(); + appServer.assertNoErrors(); + }); + + test("reopening an agent whose timeline Paseo still holds does not read Codex history", async () => { + const codex = createReopenableCodexAgent({ + "saved-thread": [ + { id: "turn-1", items: [codexUserItem("user-1", "Hello"), codexAgentItem("Hi there.")] }, + ], + }); + try { + const projected = await codex.loadCloseAndReopen(); + + expect(projected).toEqual([ + expect.objectContaining({ type: "user_message", messageId: "user-1", text: "Hello" }), + expect.objectContaining({ type: "assistant_message", text: "Hi there." }), + ]); + expect(codex.threadMethods(0)).toEqual([ + "thread/loaded/list", + "thread/resume", + "thread/read", + "thread/read", + ]); + expect(codex.threadMethods(1)).toEqual(["thread/loaded/list", "thread/resume"]); + expect(codex.manager.getTimeline(codex.agentId)).toEqual(projected); + } finally { + await codex.close(); + } + }); + + test("rewinds an agent reopened without reading its Codex history", async () => { + const firstTurn = { + id: "turn-1", + items: [codexUserItem("user-1", "First"), codexAgentItem("First answer.")], + }; + const codex = createReopenableCodexAgent({ + "saved-thread": [ + firstTurn, + { id: "turn-2", items: [codexUserItem("user-2", "Second"), codexAgentItem("Second.")] }, + ], + "forked-thread": [firstTurn], + }); + try { + await codex.loadCloseAndReopen(); + + await codex.manager.rewind(codex.agentId, "user-2", "conversation"); + + expect(codex.latestAppServer().recordedRollbacks).toEqual([ + { threadId: "forked-thread", numTurns: 1 }, + ]); + expect(codex.manager.getTimeline(codex.agentId)).toEqual([ + expect.objectContaining({ type: "user_message", messageId: "user-1", text: "First" }), + expect.objectContaining({ type: "assistant_message", text: "First answer." }), + ]); + } finally { + await codex.close(); + } + }); + + test("keeps a reopened agent's interaction with an earlier sub-agent on its original card", async () => { + const codex = createReopenableCodexAgent({ + "saved-thread": [ + { + id: "turn-1", + items: [ + codexUserItem("user-1", "Delegate"), + { + type: "subAgentActivity", + id: "spawn-child", + kind: "started", + agentThreadId: "child-thread", + agentPath: "/root/child", + }, + ], + }, + ], + "child-thread": [{ id: "child-turn-1", items: [codexAgentItem("Child started.")] }], + }); + try { + await codex.loadCloseAndReopen(); + const appServer = codex.latestAppServer(); + + const run = codex.manager.runAgent(codex.agentId, "Ask the child again"); + await appServer.waitForTurnStart(); + appServer.startsTurn({ threadId: "saved-thread", turnId: "turn-2" }); + appServer.beginsSubAgentActivity({ + callId: "interact-child", + threadId: "child-thread", + parentThreadId: "saved-thread", + kind: "interacted", + agentPath: "/root/child", + }); + appServer.says({ threadId: "child-thread", itemId: "child-reply", text: "Child replied." }); + appServer.completesSubAgentActivity({ + callId: "interact-child", + threadId: "child-thread", + parentThreadId: "saved-thread", + kind: "interacted", + agentPath: "/root/child", + }); + appServer.completeTurn({ threadId: "saved-thread" }); + await run; + + const toolCalls = codex.manager + .getTimeline(codex.agentId) + .filter((item) => item.type === "tool_call"); + expect(new Set(toolCalls.map((item) => item.callId))).toEqual(new Set(["spawn-child"])); + expect(toolCalls.at(-1)).toMatchObject({ callId: "spawn-child", status: "completed" }); + expect(codex.manager.getProviderSubagent(codex.agentId, "child-thread")).toMatchObject({ + toolCallId: "spawn-child", + status: "completed", + }); + expect( + codex.manager + .fetchProviderSubagentTimeline(codex.agentId, "child-thread") + .rows.map((row) => row.item), + ).toEqual([ + expect.objectContaining({ type: "assistant_message", text: "Child started." }), + expect.objectContaining({ type: "assistant_message", text: "Child replied." }), + ]); + } finally { + await codex.close(); + } + }); + test("closes Codex app-server when an interactive resume fails", async () => { const appServer = createFakeCodexAppServer({ "thread/resume": () => Promise.reject(new Error("thread resume failed")), @@ -2075,9 +2415,13 @@ describe("Codex app-server provider", () => { await session.startTurn("remember first"); emitCodexUserMessage(appServer, { id: "codex-first", text: "remember first" }); appServer.completeTurn(); + await new Promise((resolve) => setImmediate(resolve)); + await new Promise((resolve) => setImmediate(resolve)); await session.startTurn("remember second"); emitCodexUserMessage(appServer, { id: "codex-second", text: "remember second" }); appServer.completeTurn(); + await new Promise((resolve) => setImmediate(resolve)); + await new Promise((resolve) => setImmediate(resolve)); await session.revertConversation({ messageId: "codex-first" }); @@ -2116,6 +2460,8 @@ describe("Codex app-server provider", () => { turnId: "turn-first", }); appServer.completeTurn(); + await new Promise((resolve) => setImmediate(resolve)); + await new Promise((resolve) => setImmediate(resolve)); await session.startTurn("remember second"); emitCodexUserMessage(appServer, { id: "codex-second", @@ -2123,6 +2469,8 @@ describe("Codex app-server provider", () => { turnId: "turn-second", }); appServer.completeTurn(); + await new Promise((resolve) => setImmediate(resolve)); + await new Promise((resolve) => setImmediate(resolve)); await session.revertConversation({ messageId: "codex-second" }); @@ -2137,7 +2485,7 @@ describe("Codex app-server provider", () => { cwd: "/workspace/project", model: "gpt-5.4", serviceTier: null, - excludeTurns: false, + excludeTurns: true, persistExtendedHistory: true, }, ]); @@ -2151,8 +2499,9 @@ describe("Codex app-server provider", () => { test("rewinds a paginated conversation through the public session capability", async () => { const appServer = createFakeCodexAppServer({ - "thread/read": () => ({ - thread: { id: "thread-1", historyMode: "paginated", turns: [] }, + ...fakeCodexThreadHistory({ + "thread-1": { historyMode: "paginated", turns: [] }, + "forked-thread": { historyMode: "paginated", turns: [] }, }), "thread/rollback": () => { throw new Error("paginated threads do not support thread/rollback"); @@ -2172,6 +2521,8 @@ describe("Codex app-server provider", () => { turnId: "turn-first", }); appServer.completeTurn(); + await new Promise((resolve) => setImmediate(resolve)); + await new Promise((resolve) => setImmediate(resolve)); await session.startTurn("remember second"); emitCodexUserMessage(appServer, { id: "codex-second", @@ -2179,6 +2530,8 @@ describe("Codex app-server provider", () => { turnId: "turn-second", }); appServer.completeTurn(); + await new Promise((resolve) => setImmediate(resolve)); + await new Promise((resolve) => setImmediate(resolve)); await session.revertConversation({ messageId: "codex-first" }); @@ -2193,7 +2546,7 @@ describe("Codex app-server provider", () => { cwd: "/workspace/project", model: "gpt-5.4", serviceTier: null, - excludeTurns: false, + excludeTurns: true, persistExtendedHistory: true, }, ]); @@ -2210,11 +2563,10 @@ describe("Codex app-server provider", () => { async (historyMode) => { const appServer = createFakeCodexAppServer( historyMode === "paginated" - ? { - "thread/read": () => ({ - thread: { id: "thread-1", historyMode: "paginated", turns: [] }, - }), - } + ? fakeCodexThreadHistory({ + "thread-1": { historyMode: "paginated", turns: [] }, + "forked-thread": { historyMode: "paginated", turns: [] }, + }) : undefined, ); const customCodexConfig = { @@ -2249,6 +2601,8 @@ describe("Codex app-server provider", () => { turnId: "turn-first", }); appServer.completeTurn(); + await new Promise((resolve) => setImmediate(resolve)); + await new Promise((resolve) => setImmediate(resolve)); await session.startTurn("remember second"); emitCodexUserMessage(appServer, { id: "codex-second", @@ -2256,6 +2610,8 @@ describe("Codex app-server provider", () => { turnId: "turn-second", }); appServer.completeTurn(); + await new Promise((resolve) => setImmediate(resolve)); + await new Promise((resolve) => setImmediate(resolve)); await session.revertConversation({ messageId: "codex-first" }); @@ -2290,7 +2646,7 @@ describe("Codex app-server provider", () => { const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); await session.startTurn("remember this", { clientMessageId: "client-message" }); - asInternals(session).handleNotification("turn/started", { + await asInternals(session).handleNotification("turn/started", { threadId: "thread-1", turn: { id: "turn-1" }, }); @@ -2304,8 +2660,15 @@ describe("Codex app-server provider", () => { clientMessageId: "client-message", }, }); - expect(events.slice(0, 2).map((event) => event.type)).toEqual(["turn_started", "timeline"]); + // The first turn of a new thread also reports the thread, now that Codex has saved it. + expect(events.slice(0, 3).map((event) => event.type)).toEqual([ + "thread_started", + "turn_started", + "timeline", + ]); appServer.completeTurn(); + await new Promise((resolve) => setImmediate(resolve)); + await new Promise((resolve) => setImmediate(resolve)); await session.close(); }); @@ -2321,9 +2684,9 @@ describe("Codex app-server provider", () => { OPENAI_BASE_URL: "https://custom-relay.example.com", }); expect(capturedThreadStartConfig(capturedRequests)).toEqual({ - model_provider: "codex-iisb", + model_provider: "paseo:codex-iisb", model_providers: { - "codex-iisb": { + "paseo:codex-iisb": { name: "Custom Codex", base_url: "https://custom-relay.example.com/v1", env_key: "OPENAI_API_KEY", @@ -2341,15 +2704,30 @@ describe("Codex app-server provider", () => { ); expect(capturedThreadStartConfig(capturedRequests)).toEqual({ - model_provider: "codex-custom", + model_provider: "paseo:codex-custom", model_providers: { - "codex-custom": expect.objectContaining({ + "paseo:codex-custom": expect.objectContaining({ base_url: "https://custom-relay.example.com/v1", }), }, }); }); + test("namespaces provider ids that collide with Codex built-ins", async () => { + // `ollama` is a reserved Codex provider id: without namespacing, Codex rejects + // the generated config outright and the agent never starts. + const capturedRequests = await runCustomCodexProviderTurn("ollama", "https://ollama.com"); + + expect(capturedThreadStartConfig(capturedRequests)).toEqual({ + model_provider: "paseo:ollama", + model_providers: { + "paseo:ollama": expect.objectContaining({ + base_url: "https://ollama.com/v1", + }), + }, + }); + }); + test("resumeSession does not replace a persisted Codex thread when app-server resume fails", async () => { const threadRequests: string[] = []; const appServer = createFakeCodexAppServer({ @@ -3181,12 +3559,12 @@ describe("Codex app-server provider", () => { ]); }); - test("converts Codex collab agent notifications through the normal timeline path", () => { + test("converts Codex collab agent notifications through the normal timeline path", async () => { const session = createSession(); const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); - asInternals(session).handleNotification("item/started", { + await asInternals(session).handleNotification("item/started", { threadId: "test-thread", item: { type: "collabAgentToolCall", @@ -3222,12 +3600,12 @@ describe("Codex app-server provider", () => { ]); }); - test("folds child-thread Codex activity into the parent sub-agent tool call", () => { + test("keeps child-thread Codex activity out of the parent sub-agent card", async () => { const session = createSession(); const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { threadId: "test-thread", item: { type: "collabAgentToolCall", @@ -3241,12 +3619,12 @@ describe("Codex app-server provider", () => { }, }, }); - asInternals(session).handleNotification("item/agentMessage/delta", { + await asInternals(session).handleNotification("item/agentMessage/delta", { threadId: "child-thread-1", itemId: "child-message-1", delta: "Found", }); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { threadId: "child-thread-1", item: { type: "agentMessage", @@ -3254,13 +3632,12 @@ describe("Codex app-server provider", () => { text: "Found the path.", }, }); - asInternals(session).handleNotification("turn/completed", { + await asInternals(session).handleNotification("turn/completed", { threadId: "child-thread-1", turn: { status: "completed" }, }); const timelineEvents = events.filter((event) => event.type === "timeline"); - expect(timelineEvents).toHaveLength(4); expect(timelineEvents.every((event) => event.item.type === "tool_call")).toBe(true); const finalItem = timelineEvents.at(-1)?.item; expect(finalItem).toMatchObject({ @@ -3272,7 +3649,7 @@ describe("Codex app-server provider", () => { type: "sub_agent", subAgentType: "Sub-agent", description: "Report findings.", - log: "[Assistant] Found the path.", + log: "", actions: [], }, }); @@ -3332,12 +3709,15 @@ describe("Codex app-server provider", () => { threadId: "settled-child-thread", agentPath: "/root/settled-child", }); + await new Promise((resolve) => setImmediate(resolve)); appServer.completeTurn({ threadId: "settled-child-thread" }); + await new Promise((resolve) => setImmediate(resolve)); appServer.says({ threadId: "settled-child-thread", itemId: "late-child-message", text: "Late trailing output.", }); + await new Promise((resolve) => setImmediate(resolve)); const providerUpserts = events.flatMap((event) => event.type === "provider_subagent" && event.event.type === "upsert" ? [event.event] : [], @@ -3346,13 +3726,9 @@ describe("Codex app-server provider", () => { id: "settled-child-thread", status: "completed", }); - expect(events.at(-1)).toMatchObject({ + expect(events.findLast((event) => event.type === "timeline")).toMatchObject({ type: "timeline", - item: { - callId: "call-settled-child", - status: "completed", - detail: { type: "sub_agent", log: "[Assistant] Late trailing output." }, - }, + item: { callId: "call-settled-child", status: "completed" }, }); appServer.completesSubAgentActivity({ @@ -3361,6 +3737,7 @@ describe("Codex app-server provider", () => { agentPath: "/root/settled-child", kind: "interacted", }); + await new Promise((resolve) => setImmediate(resolve)); expect( events.findLast( (event) => event.type === "provider_subagent" && event.event.type === "upsert", @@ -3371,6 +3748,7 @@ describe("Codex app-server provider", () => { threadId: "settled-child-thread", turnId: "next-child-turn", }); + await new Promise((resolve) => setImmediate(resolve)); expect( events.findLast( (event) => event.type === "provider_subagent" && event.event.type === "upsert", @@ -3378,7 +3756,9 @@ describe("Codex app-server provider", () => { ).toMatchObject({ event: { id: "settled-child-thread", status: "running" } }); appServer.completeTurn({ threadId: "settled-child-thread" }); + await new Promise((resolve) => setImmediate(resolve)); appServer.completeTurn(); + await new Promise((resolve) => setImmediate(resolve)); await resultPromise; appServer.assertNoErrors(); } finally { @@ -3386,12 +3766,12 @@ describe("Codex app-server provider", () => { } }); - test("updates a registered child with its later native activity name", () => { + test("updates a registered child with its later native activity name", async () => { const session = createSession(); const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { threadId: "test-thread", item: { type: "collabAgentToolCall", @@ -3405,7 +3785,7 @@ describe("Codex app-server provider", () => { }, }, }); - asInternals(session).handleNotification("item/started", { + await asInternals(session).handleNotification("item/started", { threadId: "test-thread", item: { type: "subAgentActivity", @@ -3440,11 +3820,11 @@ describe("Codex app-server provider", () => { }); }); - test("renders child MCP image results in the provider subagent timeline", () => { + test("renders child MCP image results in the provider subagent timeline", async () => { const session = createSession(); const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { threadId: "test-thread", item: { type: "subAgentActivity", @@ -3455,7 +3835,7 @@ describe("Codex app-server provider", () => { }, }); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { threadId: "image-child-thread", item: { id: "child-mcp-image", @@ -3488,11 +3868,11 @@ describe("Codex app-server provider", () => { rmSync(source, { force: true }); }); - test("renders a child user message once across lifecycle notifications", () => { + test("renders a child user message once across lifecycle notifications", async () => { const session = createSession(); const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { threadId: "test-thread", item: { type: "subAgentActivity", @@ -3508,11 +3888,11 @@ describe("Codex app-server provider", () => { content: [{ type: "text", text: "Inspect this path." }], }; - asInternals(session).handleNotification("item/started", { + await asInternals(session).handleNotification("item/started", { threadId: "user-child-thread", item: childUserMessage, }); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { threadId: "user-child-thread", item: childUserMessage, }); @@ -3546,19 +3926,24 @@ describe("Codex app-server provider", () => { threadId: "child-thread-1", agentPath: "/root/child", }); + await new Promise((resolve) => setImmediate(resolve)); appServer.says({ threadId: "child-thread-1", itemId: "child-message-1", text: "Child findings.", }); + await new Promise((resolve) => setImmediate(resolve)); appServer.completeTurn({ threadId: "child-thread-1" }); + await new Promise((resolve) => setImmediate(resolve)); appServer.says({ threadId: "thread-1", itemId: "parent-message-1", text: "Parent report.", chunks: ["Parent ", "report."], }); + await new Promise((resolve) => setImmediate(resolve)); appServer.completeTurn(); + await new Promise((resolve) => setImmediate(resolve)); const result = await resultPromise; expect(result.finalText).toBe("Parent report."); @@ -3592,13 +3977,16 @@ describe("Codex app-server provider", () => { itemId: "first-parent-message", text: "First report.", }); + await new Promise((resolve) => setImmediate(resolve)); appServer.says({ threadId: "thread-1", itemId: "second-parent-message", text: "Second report.", chunks: ["", "Second report."], }); + await new Promise((resolve) => setImmediate(resolve)); appServer.completeTurn(); + await new Promise((resolve) => setImmediate(resolve)); const result = await resultPromise; expect(result.finalText).toBe("Second report."); @@ -3623,8 +4011,11 @@ describe("Codex app-server provider", () => { await appServer.waitForTurnStart(); appServer.says({ threadId: "thread-1", text: "First report." }); + await new Promise((resolve) => setImmediate(resolve)); appServer.says({ threadId: "thread-1", text: "Second report." }); + await new Promise((resolve) => setImmediate(resolve)); appServer.completeTurn(); + await new Promise((resolve) => setImmediate(resolve)); const result = await resultPromise; expect(result.finalText).toBe("Second report."); @@ -3642,29 +4033,37 @@ describe("Codex app-server provider", () => { createTestLogger(), async () => appServer.child, ); + const events: AgentStreamEvent[] = []; + session.subscribe((event) => events.push(event)); try { const resultPromise = session.run("Delegate the investigation, then report the result."); await appServer.waitForTurnStart(); appServer.startsTurn({ threadId: "child-thread-early" }); + await new Promise((resolve) => setImmediate(resolve)); appServer.says({ threadId: "child-thread-early", itemId: "child-message-early", text: "Early child findings.", }); + await new Promise((resolve) => setImmediate(resolve)); appServer.completeTurn({ threadId: "child-thread-early" }); + await new Promise((resolve) => setImmediate(resolve)); appServer.startsSubAgent({ callId: "spawn-child-early", threadId: "child-thread-early", agentPath: "/root/early-child", }); + await new Promise((resolve) => setImmediate(resolve)); appServer.says({ threadId: "thread-1", itemId: "parent-message-after-early-child", text: "Parent report after replay.", }); + await new Promise((resolve) => setImmediate(resolve)); appServer.completeTurn(); + await new Promise((resolve) => setImmediate(resolve)); const result = await resultPromise; expect(result.finalText).toBe("Parent report after replay."); @@ -3679,11 +4078,18 @@ describe("Codex app-server provider", () => { type: "tool_call", callId: "spawn-child-early", status: "completed", - detail: { - type: "sub_agent", - log: "[Assistant] Early child findings.", - }, + detail: { type: "sub_agent", log: "" }, }); + expect(events).toContainEqual( + expect.objectContaining({ + type: "provider_subagent", + event: expect.objectContaining({ + type: "timeline", + id: "child-thread-early", + item: expect.objectContaining({ type: "assistant_message" }), + }), + }), + ); appServer.assertNoErrors(); } finally { await session.close(); @@ -3708,36 +4114,43 @@ describe("Codex app-server provider", () => { threadId: "child-thread-stable", agentPath: "/root/stable-child", }); + await new Promise((resolve) => setImmediate(resolve)); appServer.beginsSubAgentActivity({ callId: "message-child-stable", threadId: "child-thread-stable", agentPath: "/root/stable-child", kind: "interacted", }); + await new Promise((resolve) => setImmediate(resolve)); appServer.completesSubAgentActivity({ callId: "message-child-stable", threadId: "child-thread-stable", agentPath: "/root/stable-child", kind: "interacted", }); + await new Promise((resolve) => setImmediate(resolve)); appServer.says({ threadId: "child-thread-stable", itemId: "stable-child-message", text: "Still on the same card.", }); + await new Promise((resolve) => setImmediate(resolve)); appServer.beginsSubAgentActivity({ callId: "interrupt-child-stable", threadId: "child-thread-stable", agentPath: "/root/stable-child", kind: "interrupted", }); + await new Promise((resolve) => setImmediate(resolve)); appServer.completesSubAgentActivity({ callId: "interrupt-child-stable", threadId: "child-thread-stable", agentPath: "/root/stable-child", kind: "interrupted", }); + await new Promise((resolve) => setImmediate(resolve)); appServer.completeTurn(); + await new Promise((resolve) => setImmediate(resolve)); const result = await resultPromise; const toolCalls = result.timeline.filter((item) => item.type === "tool_call"); @@ -3747,10 +4160,7 @@ describe("Codex app-server provider", () => { expect(toolCalls.at(-1)).toMatchObject({ callId: "spawn-child-stable", status: "canceled", - detail: { - type: "sub_agent", - log: "[Assistant] Still on the same card.", - }, + detail: { type: "sub_agent", log: "" }, }); appServer.assertNoErrors(); } finally { @@ -3772,6 +4182,7 @@ describe("Codex app-server provider", () => { await appServer.waitForTurnStart(); appServer.completeTurn({ threadId: "child-thread-fast" }); + await new Promise((resolve) => setImmediate(resolve)); const activity = { callId: "spawn-child-fast", threadId: "child-thread-fast", @@ -3779,8 +4190,11 @@ describe("Codex app-server provider", () => { kind: "started" as const, }; appServer.beginsSubAgentActivity(activity); + await new Promise((resolve) => setImmediate(resolve)); appServer.completesSubAgentActivity(activity); + await new Promise((resolve) => setImmediate(resolve)); appServer.completeTurn(); + await new Promise((resolve) => setImmediate(resolve)); const result = await resultPromise; const toolCalls = result.timeline.filter((item) => item.type === "tool_call"); @@ -3809,24 +4223,27 @@ describe("Codex app-server provider", () => { await appServer.waitForTurnStart(); appServer.completeTurn({ threadId: "child-late-compaction" }); + await new Promise((resolve) => setImmediate(resolve)); appServer.completesCompaction({ threadId: "child-late-compaction", itemId: "late-child-compaction", }); + await new Promise((resolve) => setImmediate(resolve)); appServer.startsSubAgent({ callId: "spawn-child-late-compaction", threadId: "child-late-compaction", agentPath: "/root/late-compaction", }); + await new Promise((resolve) => setImmediate(resolve)); appServer.completeTurn(); + await new Promise((resolve) => setImmediate(resolve)); const result = await resultPromise; const toolCalls = result.timeline.filter((item) => item.type === "tool_call"); - expect(toolCalls.map((item) => item.status)).toEqual(["running", "completed", "completed"]); + expect(toolCalls.map((item) => item.status)).toEqual(["running", "completed"]); expect(toolCalls.at(-1)).toMatchObject({ callId: "spawn-child-late-compaction", status: "completed", - detail: { type: "sub_agent", log: "[Compacted]" }, }); appServer.assertNoErrors(); } finally { @@ -3834,7 +4251,7 @@ describe("Codex app-server provider", () => { } }); - test("projects legacy child tools into one stable sub-agent log", async () => { + test("routes legacy child tools to the child timeline", async () => { const appServer = createFakeCodexAppServer(); const session = new CodexAppServerAgentSession( createConfig({ cwd: "/workspace/project" }), @@ -3842,6 +4259,8 @@ describe("Codex app-server provider", () => { createTestLogger(), async () => appServer.child, ); + const events: AgentStreamEvent[] = []; + session.subscribe((event) => events.push(event)); try { const resultPromise = session.run("Delegate the implementation."); @@ -3852,6 +4271,7 @@ describe("Codex app-server provider", () => { threadId: "legacy-tool-child", agentPath: "/root/legacy-tool-child", }); + await new Promise((resolve) => setImmediate(resolve)); const command = { threadId: "legacy-tool-child", callId: "legacy-child-command", @@ -3859,15 +4279,20 @@ describe("Codex app-server provider", () => { output: "child output", }; appServer.runsLegacyCommand(command); + await new Promise((resolve) => setImmediate(resolve)); appServer.completesCommand(command); + await new Promise((resolve) => setImmediate(resolve)); appServer.appliesLegacyPatch({ threadId: "legacy-tool-child", callId: "legacy-child-patch", path: "/workspace/project/src/child.ts", diff: "@@\n-old\n+new\n", }); + await new Promise((resolve) => setImmediate(resolve)); appServer.completeTurn({ threadId: "legacy-tool-child" }); + await new Promise((resolve) => setImmediate(resolve)); appServer.completeTurn(); + await new Promise((resolve) => setImmediate(resolve)); const result = await resultPromise; const toolCalls = result.timeline.filter((item) => item.type === "tool_call"); @@ -3878,24 +4303,31 @@ describe("Codex app-server provider", () => { expect(finalToolCall).toMatchObject({ callId: "spawn-legacy-tool-child", status: "completed", - detail: { type: "sub_agent" }, + detail: { type: "sub_agent", log: "" }, }); - if (finalToolCall?.detail.type === "sub_agent") { - expect(finalToolCall.detail.log.match(/\[Shell\]/g)).toHaveLength(1); - expect(finalToolCall.detail.log).toContain("[Edit]"); - } + const childToolCalls = events.flatMap((event) => + event.type === "provider_subagent" && + event.event.type === "timeline" && + event.event.id === "legacy-tool-child" && + event.event.item.type === "tool_call" + ? [event.event.item] + : [], + ); + expect(new Set(childToolCalls.map((item) => item.detail.type))).toEqual( + new Set(["shell", "edit"]), + ); appServer.assertNoErrors(); } finally { await session.close(); } }); - test("keeps nested MultiAgentV2 output inside the root sub-agent card", () => { + test("keeps nested MultiAgentV2 output out of the root sub-agent card", async () => { const session = createSession(); const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { threadId: "test-thread", item: { type: "subAgentActivity", @@ -3905,7 +4337,7 @@ describe("Codex app-server provider", () => { agentPath: "/root/child", }, }); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { threadId: "child-thread-root", item: { type: "subAgentActivity", @@ -3915,12 +4347,12 @@ describe("Codex app-server provider", () => { agentPath: "/root/child/grandchild", }, }); - asInternals(session).handleNotification("item/agentMessage/delta", { + await asInternals(session).handleNotification("item/agentMessage/delta", { threadId: "grandchild-thread", itemId: "grandchild-message", delta: "Grandchild findings.", }); - asInternals(session).handleNotification("turn/completed", { + await asInternals(session).handleNotification("turn/completed", { threadId: "grandchild-thread", turn: { status: "completed" }, }); @@ -3950,10 +4382,24 @@ describe("Codex app-server provider", () => { expect(beforeParentCompletes.at(-1)).toMatchObject({ callId: "spawn-child-root", status: "running", - detail: { type: "sub_agent", log: expect.stringContaining("Grandchild findings.") }, + detail: { type: "sub_agent", log: "" }, }); + expect(events).toContainEqual( + expect.objectContaining({ + type: "provider_subagent", + event: { + type: "timeline", + id: "grandchild-thread", + item: { + type: "assistant_message", + messageId: "grandchild-message", + text: "Grandchild findings.", + }, + }, + }), + ); - asInternals(session).handleNotification("turn/completed", { + await asInternals(session).handleNotification("turn/completed", { threadId: "child-thread-root", turn: { status: "completed" }, }); @@ -3963,12 +4409,12 @@ describe("Codex app-server provider", () => { }); }); - test("keeps a nested child under its spawning parent after a root interaction", () => { + test("keeps a nested child under its spawning parent after a root interaction", async () => { const session = createSession(); const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { threadId: "test-thread", item: { type: "subAgentActivity", @@ -3978,7 +4424,7 @@ describe("Codex app-server provider", () => { agentPath: "/root/child", }, }); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { threadId: "child-thread-root", item: { type: "subAgentActivity", @@ -3988,7 +4434,7 @@ describe("Codex app-server provider", () => { agentPath: "/root/child/grandchild", }, }); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { threadId: "test-thread", item: { type: "collabAgentToolCall", @@ -4001,7 +4447,7 @@ describe("Codex app-server provider", () => { }, }, }); - asInternals(session).handleNotification("item/agentMessage/delta", { + await asInternals(session).handleNotification("item/agentMessage/delta", { threadId: "grandchild-thread", itemId: "grandchild-after-wait", delta: "Still nested.", @@ -4018,37 +4464,44 @@ describe("Codex app-server provider", () => { "child-thread-root", "child-thread-root", ]); - expect(events.at(-1)).toMatchObject({ - type: "timeline", - item: { - callId: "spawn-child-root", - detail: { type: "sub_agent", log: expect.stringContaining("Still nested.") }, - }, - }); + expect(events).toContainEqual( + expect.objectContaining({ + type: "provider_subagent", + event: { + type: "timeline", + id: "grandchild-thread", + item: { + type: "assistant_message", + messageId: "grandchild-after-wait", + text: "Still nested.", + }, + }, + }), + ); }); - test("never treats an unmapped foreign terminal as the root terminal", () => { + test("never treats an unmapped foreign terminal as the root terminal", async () => { const session = createSession(); const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); - asInternals(session).handleNotification("turn/completed", { + await asInternals(session).handleNotification("turn/completed", { threadId: "unmapped-child-thread", turn: { status: "completed" }, }); expect(events).toEqual([]); - asInternals(session).handleNotification("turn/completed", { + await asInternals(session).handleNotification("turn/completed", { threadId: "test-thread", turn: { status: "completed" }, }); expect(events.filter((event) => event.type === "turn_completed")).toHaveLength(1); - asInternals(session).handleNotification("turn/started", { + await asInternals(session).handleNotification("turn/started", { threadId: "test-thread", turn: { id: "next-root-turn" }, }); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { threadId: "test-thread", item: { type: "subAgentActivity", @@ -4064,12 +4517,12 @@ describe("Codex app-server provider", () => { }); }); - test("routes msg-scoped legacy Codex events to their child thread", () => { + test("routes msg-scoped legacy Codex events to their child thread", async () => { const session = createSession(); const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { threadId: "test-thread", item: { type: "subAgentActivity", @@ -4079,7 +4532,7 @@ describe("Codex app-server provider", () => { agentPath: "/root/legacy-envelope-child", }, }); - asInternals(session).handleNotification("codex/event/exec_command_begin", { + await asInternals(session).handleNotification("codex/event/exec_command_begin", { msg: { type: "exec_command_begin", threadId: "legacy-envelope-child", @@ -4087,7 +4540,7 @@ describe("Codex app-server provider", () => { command: "pwd", }, }); - asInternals(session).handleNotification("codex/event/task_complete", { + await asInternals(session).handleNotification("codex/event/task_complete", { msg: { type: "task_complete", thread_id: "legacy-envelope-child", @@ -4125,7 +4578,7 @@ describe("Codex app-server provider", () => { }, }); - asInternals(session).handleNotification("codex/event/task_complete", { + await asInternals(session).handleNotification("codex/event/task_complete", { msg: { type: "task_complete" }, }); expect(events.filter((event) => event.type === "turn_completed")).toHaveLength(1); @@ -4147,11 +4600,13 @@ describe("Codex app-server provider", () => { const spawn = waitForTimelineToolCall(session, "spawn-legacy-only-child"); appServer.startsTurn({ threadId: "thread-1", turnId: "turn-with-legacy-only-child" }); + await new Promise((resolve) => setImmediate(resolve)); appServer.startsLegacyOnlySubAgent({ callId: "spawn-legacy-only-child", threadId: "legacy-only-child-thread", agentPath: "/root/legacy-only-child", }); + await new Promise((resolve) => setImmediate(resolve)); await expect(child).resolves.toMatchObject({ type: "provider_subagent", @@ -4179,6 +4634,7 @@ describe("Codex app-server provider", () => { }); appServer.completeTurn(); + await new Promise((resolve) => setImmediate(resolve)); await resultPromise; appServer.assertNoErrors(); } finally { @@ -4203,10 +4659,12 @@ describe("Codex app-server provider", () => { const resultPromise = session.run("Wait for the child."); await appServer.waitForTurnStart(); appServer.startsTurn({ threadId: "thread-1", turnId: "turn-waiting-for-child" }); + await new Promise((resolve) => setImmediate(resolve)); await expect(session.interrupt()).rejects.toThrow("A foreground turn is already active"); appServer.completeTurn(); + await new Promise((resolve) => setImmediate(resolve)); await resultPromise; appServer.assertNoErrors(); } finally { @@ -4231,10 +4689,12 @@ describe("Codex app-server provider", () => { const resultPromise = session.run("Wait for the child."); await appServer.waitForTurnStart(); appServer.startsTurn({ threadId: "thread-1", turnId: "turn-already-idle" }); + await new Promise((resolve) => setImmediate(resolve)); await expect(session.interrupt()).resolves.toBeUndefined(); appServer.completeTurn(); + await new Promise((resolve) => setImmediate(resolve)); await resultPromise; appServer.assertNoErrors(); } finally { @@ -4263,10 +4723,12 @@ describe("Codex app-server provider", () => { const interruptPromise = session.interrupt(); appServer.startsTurn({ threadId: "thread-1", turnId: "turn-identified-late" }); + await new Promise((resolve) => setImmediate(resolve)); await interruptPromise; expect(interruptedTurns).toEqual([{ threadId: "thread-1", turnId: "turn-identified-late" }]); appServer.completeTurn(); + await new Promise((resolve) => setImmediate(resolve)); await resultPromise; appServer.assertNoErrors(); } finally { @@ -4294,6 +4756,7 @@ describe("Codex app-server provider", () => { await appServer.waitForTurnStart(); const interruptPromise = session.interrupt(); appServer.completeTurn(); + await new Promise((resolve) => setImmediate(resolve)); await expect(interruptPromise).resolves.toBeUndefined(); await resultPromise; @@ -4353,7 +4816,9 @@ describe("Codex app-server provider", () => { const nativeStart = await appServer.waitForTurnStart().catch(() => null); if (nativeStart) { appServer.startsTurn({ threadId: "thread-1", turnId: "cleanup-turn" }); + await new Promise((resolve) => setImmediate(resolve)); appServer.completeTurn(); + await new Promise((resolve) => setImmediate(resolve)); } await resultPromise.catch(() => undefined); await session.close(); @@ -4371,7 +4836,7 @@ describe("Codex app-server provider", () => { }, }; - asInternals(session).handleNotification("turn/started", { + await asInternals(session).handleNotification("turn/started", { threadId: "test-thread", turn: { id: "autonomous-turn" }, }); @@ -4387,13 +4852,13 @@ describe("Codex app-server provider", () => { }); }); - test("never replaces the root identity with an early child thread start", () => { + test("never replaces the root identity with an early child thread start", async () => { const session = createSession(); - asInternals(session).handleNotification("thread/started", { + await asInternals(session).handleNotification("thread/started", { thread: { id: "child-thread-started-early" }, }); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { threadId: "test-thread", item: { type: "subAgentActivity", @@ -4407,12 +4872,12 @@ describe("Codex app-server provider", () => { expect(session.currentThreadId).toBe("test-thread"); }); - test("does not leak aggregate child telemetry into the root timeline", () => { + test("does not leak aggregate child telemetry into the root timeline", async () => { const session = createSession(); const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { threadId: "test-thread", item: { type: "subAgentActivity", @@ -4424,7 +4889,7 @@ describe("Codex app-server provider", () => { }); const eventCountAfterSpawn = events.length; - asInternals(session).handleNotification("turn/plan/updated", { + await asInternals(session).handleNotification("turn/plan/updated", { threadId: "child-thread-telemetry", plan: [{ step: "Child-only plan", status: "inProgress" }], }); @@ -4432,12 +4897,12 @@ describe("Codex app-server provider", () => { expect(events).toHaveLength(eventCountAfterSpawn); }); - test("keeps child context compaction inside the child card", () => { + test("keeps child context compaction on the child timeline", async () => { const session = createSession(); const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { threadId: "test-thread", item: { type: "subAgentActivity", @@ -4447,11 +4912,11 @@ describe("Codex app-server provider", () => { agentPath: "/root/compacting-child", }, }); - asInternals(session).handleNotification("item/started", { + await asInternals(session).handleNotification("item/started", { threadId: "child-thread-compaction", item: { type: "contextCompaction", id: "child-compaction" }, }); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { threadId: "child-thread-compaction", item: { type: "contextCompaction", id: "child-compaction" }, }); @@ -4465,18 +4930,78 @@ describe("Codex app-server provider", () => { (item) => item.type === "tool_call" && item.callId === "spawn-child-compaction", ), ).toBe(true); - expect(timelineItems.at(-1)).toMatchObject({ - type: "tool_call", - detail: { type: "sub_agent", log: "[Compacted]" }, - }); + expect( + events.flatMap((event) => + event.type === "provider_subagent" && event.event.type === "timeline" ? [event.event] : [], + ), + ).toEqual([ + { + type: "timeline", + id: "child-thread-compaction", + item: { type: "compaction", status: "loading" }, + }, + { + type: "timeline", + id: "child-thread-compaction", + item: { type: "compaction", status: "completed" }, + }, + ]); }); - test("keeps the parent sub-agent running when a child command fails during the child turn", () => { + test("settles a child compaction once when the item completion is missing or duplicated", async () => { const session = createSession(); const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); - asInternals(session).handleNotification("item/completed", { + for (const child of ["compacted-child", "turn-ended-child"]) { + await asInternals(session).handleNotification("item/completed", { + threadId: "test-thread", + item: { + type: "subAgentActivity", + id: `spawn-${child}`, + kind: "started", + agentThreadId: child, + agentPath: `/root/${child}`, + }, + }); + await asInternals(session).handleNotification("item/started", { + threadId: child, + item: { type: "contextCompaction", id: `${child}-compaction` }, + }); + } + await asInternals(session).handleNotification("thread/compacted", { + threadId: "compacted-child", + }); + await asInternals(session).handleNotification("item/completed", { + threadId: "compacted-child", + item: { type: "contextCompaction", id: "compacted-child-compaction" }, + }); + await asInternals(session).handleNotification("turn/completed", { + threadId: "turn-ended-child", + turn: { status: "completed" }, + }); + + const compactions = events.flatMap((event) => + event.type === "provider_subagent" && event.event.type === "timeline" + ? [ + `${event.event.id} ${event.event.item.type === "compaction" ? event.event.item.status : ""}`, + ] + : [], + ); + expect(compactions).toEqual([ + "compacted-child loading", + "turn-ended-child loading", + "compacted-child completed", + "turn-ended-child completed", + ]); + }); + + test("keeps the parent sub-agent running when a child command fails during the child turn", async () => { + const session = createSession(); + const events: AgentStreamEvent[] = []; + session.subscribe((event) => events.push(event)); + + await asInternals(session).handleNotification("item/completed", { threadId: "test-thread", item: { type: "collabAgentToolCall", @@ -4490,7 +5015,7 @@ describe("Codex app-server provider", () => { }, }, }); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { threadId: "child-thread-1", item: { type: "commandExecution", @@ -4503,7 +5028,7 @@ describe("Codex app-server provider", () => { }, }); - expect(events.at(-1)?.item).toMatchObject({ + expect(events.findLast((event) => event.type === "timeline")?.item).toMatchObject({ type: "tool_call", callId: "call-sub-agent-child-command-failure", name: "Sub-agent", @@ -4517,12 +5042,12 @@ describe("Codex app-server provider", () => { }); }); - test("does not synthesize a parent sub-agent failure from child error state alone", () => { + test("does not synthesize a parent sub-agent failure from child error state alone", async () => { const session = createSession(); const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { threadId: "test-thread", item: { type: "collabAgentToolCall", @@ -4584,14 +5109,13 @@ describe("Codex app-server provider", () => { }), }; - await asInternals(session).loadPersistedHistory(session.client); - const history: AgentStreamEvent[] = []; for await (const event of session.streamHistory()) { history.push(event); } expect(requests.map((request) => [request.method, request.params])).toEqual([ + ["thread/read", { threadId: "test-thread", includeTurns: false }], ["thread/read", { threadId: "test-thread", includeTurns: true }], ]); expect(history).toEqual([ @@ -4638,7 +5162,7 @@ describe("Codex app-server provider", () => { })), }; - await asInternals(session).loadPersistedHistory(session.client); + await Array.fromAsync(session.streamHistory()); expect(asInternals(session).codexUserMessageTurns().resolve("message-history")).toEqual({ index: 0, @@ -4707,8 +5231,6 @@ describe("Codex app-server provider", () => { }), }; - await asInternals(session).loadPersistedHistory(session.client); - const history: AgentStreamEvent[] = []; for await (const event of session.streamHistory()) { history.push(event); @@ -4773,11 +5295,11 @@ describe("Codex app-server provider", () => { const liveEvents: AgentStreamEvent[] = []; session.subscribe((event) => liveEvents.push(event)); - asInternals(session).handleNotification("turn/started", { + await asInternals(session).handleNotification("turn/started", { threadId: "v2-child-thread", turn: { id: "v2-child-turn-after-resume" }, }); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { threadId: "test-thread", item: { type: "subAgentActivity", @@ -4787,7 +5309,7 @@ describe("Codex app-server provider", () => { agentPath: "/root/v2-child", }, }); - asInternals(session).handleNotification("item/agentMessage/delta", { + await asInternals(session).handleNotification("item/agentMessage/delta", { threadId: "v2-child-thread", itemId: "v2-child-message-after-resume", delta: "More findings after resume.", @@ -4801,25 +5323,25 @@ describe("Codex app-server provider", () => { ); expect(liveToolCalls.at(-1)).toMatchObject({ status: "running", - detail: { type: "sub_agent", log: "[Assistant] More findings after resume." }, + detail: { type: "sub_agent", log: "" }, }); liveEvents.length = 0; - asInternals(session).handleNotification("turn/started", { + await asInternals(session).handleNotification("turn/started", { threadId: "legacy-child-thread", turn: { id: "legacy-child-turn-after-resume" }, }); - asInternals(session).handleNotification("item/agentMessage/delta", { + await asInternals(session).handleNotification("item/agentMessage/delta", { threadId: "legacy-child-thread", itemId: "legacy-child-message-after-resume", delta: "Legacy findings after resume.", }); - expect(liveEvents.at(-1)).toMatchObject({ + expect(liveEvents.findLast((event) => event.type === "timeline")).toMatchObject({ type: "timeline", item: { callId: "legacy-spawn-history", status: "running", - detail: { type: "sub_agent", log: "[Assistant] Legacy findings after resume." }, + detail: { type: "sub_agent", log: "" }, }, }); }); @@ -4869,8 +5391,6 @@ describe("Codex app-server provider", () => { }), }; - await asInternals(session).loadPersistedHistory(session.client); - const history: AgentStreamEvent[] = []; for await (const event of session.streamHistory()) { history.push(event); @@ -4934,8 +5454,6 @@ describe("Codex app-server provider", () => { }), }; - await asInternals(session).loadPersistedHistory(session.client); - const history: AgentStreamEvent[] = []; for await (const event of session.streamHistory()) { history.push(event); @@ -5058,6 +5576,7 @@ describe("Codex app-server provider", () => { threadId: "child-thread", agentPath: "/root/child", }); + await new Promise((resolve) => setImmediate(resolve)); await child; appServer.beginsSubAgentActivity({ callId: "parent-interacted", @@ -5066,7 +5585,9 @@ describe("Codex app-server provider", () => { kind: "interacted", agentPath: "/root", }); + await new Promise((resolve) => setImmediate(resolve)); appServer.completeTurn(); + await new Promise((resolve) => setImmediate(resolve)); await resultPromise; expect(providerSubagentIds).toEqual(new Set(["child-thread"])); @@ -5108,8 +5629,6 @@ describe("Codex app-server provider", () => { }), }; - await asInternals(session).loadPersistedHistory(session.client); - const history: AgentStreamEvent[] = []; for await (const event of session.streamHistory()) { history.push(event); @@ -5169,8 +5688,6 @@ describe("Codex app-server provider", () => { }), }; - await asInternals(session).loadPersistedHistory(session.client); - const history: AgentStreamEvent[] = []; for await (const event of session.streamHistory()) { history.push(event); @@ -5198,7 +5715,7 @@ describe("Codex app-server provider", () => { ]); }); - test("captures live Codex user message ids from item events", () => { + test("captures live Codex user message ids from item events", async () => { const session = createSession(); const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); @@ -5209,11 +5726,11 @@ describe("Codex app-server provider", () => { content: [{ type: "text", text: "Use the native Codex id." }], }; - asInternals(session).handleNotification("item/started", { + await asInternals(session).handleNotification("item/started", { threadId: "test-thread", item: userMessageItem, }); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { threadId: "test-thread", item: userMessageItem, }); @@ -5232,19 +5749,19 @@ describe("Codex app-server provider", () => { ]); }); - test("emits Codex context compaction markers from live thread items", () => { + test("emits Codex context compaction markers from live thread items", async () => { const session = createSession(); const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); - asInternals(session).handleNotification("item/started", { + await asInternals(session).handleNotification("item/started", { threadId: "test-thread", item: { type: "contextCompaction", id: "compact-live", }, }); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { threadId: "test-thread", item: { type: "contextCompaction", @@ -5282,7 +5799,9 @@ describe("Codex app-server provider", () => { threadId: "thread-1", itemId: "compact-without-completion", }); + await new Promise((resolve) => setImmediate(resolve)); appServer.completeTurn(); + await new Promise((resolve) => setImmediate(resolve)); await terminalEvent; expect( @@ -5304,11 +5823,14 @@ describe("Codex app-server provider", () => { threadId: "thread-1", itemId: "compact-completed-normally", }); + await new Promise((resolve) => setImmediate(resolve)); appServer.completesCompaction({ threadId: "thread-1", itemId: "compact-completed-normally", }); + await new Promise((resolve) => setImmediate(resolve)); appServer.completeTurn(); + await new Promise((resolve) => setImmediate(resolve)); await terminalEvent; expect( @@ -5327,8 +5849,11 @@ describe("Codex app-server provider", () => { try { appServer.startsCompaction({ threadId: "thread-1", itemId: "current-compaction" }); + await new Promise((resolve) => setImmediate(resolve)); appServer.completesCompaction({ threadId: "thread-1", itemId: "older-compaction" }); + await new Promise((resolve) => setImmediate(resolve)); appServer.completeTurn(); + await new Promise((resolve) => setImmediate(resolve)); await terminalEvent; expect( @@ -5350,10 +5875,12 @@ describe("Codex app-server provider", () => { try { appServer.startsCompaction({ threadId: "thread-1", itemId: `compact-${status}` }); + await new Promise((resolve) => setImmediate(resolve)); appServer.completeTurn({ status, error: status === "failed" ? { message: "Compaction failed" } : null, }); + await new Promise((resolve) => setImmediate(resolve)); await terminalEvent; expect( @@ -5367,17 +5894,17 @@ describe("Codex app-server provider", () => { } }); - test("emits and dedupes Codex thread/compacted notifications", () => { + test("emits and dedupes Codex thread/compacted notifications", async () => { const session = createSession(); session.activeForegroundTurnId = null; const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); - asInternals(session).handleNotification("thread/compacted", { + await asInternals(session).handleNotification("thread/compacted", { threadId: "test-thread", turnId: "legacy-compact-turn", }); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { threadId: "test-thread", item: { type: "contextCompaction", @@ -5398,17 +5925,17 @@ describe("Codex app-server provider", () => { ]); }); - test("emits consecutive Codex thread/compacted notifications", () => { + test("emits consecutive Codex thread/compacted notifications", async () => { const session = createSession(); session.activeForegroundTurnId = null; const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); - asInternals(session).handleNotification("thread/compacted", { + await asInternals(session).handleNotification("thread/compacted", { threadId: "test-thread", turnId: "legacy-compact-turn-1", }); - asInternals(session).handleNotification("thread/compacted", { + await asInternals(session).handleNotification("thread/compacted", { threadId: "test-thread", turnId: "legacy-compact-turn-2", }); @@ -5462,7 +5989,10 @@ describe("Codex app-server provider", () => { expect(session.currentThreadId).toBe("archived-thread-id"); expect(requests).toEqual([ { method: "thread/loaded/list", params: {} }, - { method: "thread/resume", params: { threadId: "archived-thread-id" } }, + { + method: "thread/resume", + params: { threadId: "archived-thread-id", excludeTurns: true }, + }, ]); }); @@ -5534,14 +6064,14 @@ describe("Codex app-server provider", () => { const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); await handler?.run({ emit: (event) => events.push(event) }); - asInternals(session).handleNotification("item/started", { + await asInternals(session).handleNotification("item/started", { threadId: "test-thread", item: { type: "contextCompaction", id: "manual-compact", }, }); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { threadId: "test-thread", item: { type: "contextCompaction", @@ -5656,23 +6186,23 @@ describe("Codex app-server provider", () => { }); }); - test("emits a synthetic plan approval permission after a successful Codex plan turn", () => { + test("emits a synthetic plan approval permission after a successful Codex plan turn", async () => { const session = createSession({ featureValues: { plan_mode: true, fast_mode: true }, }); const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); - asInternals(session).handleNotification("turn/started", { + await asInternals(session).handleNotification("turn/started", { turn: { id: "turn-plan-1" }, }); - asInternals(session).handleNotification("turn/plan/updated", { + await asInternals(session).handleNotification("turn/plan/updated", { plan: [ { step: "Inspect the existing auth flow", status: "completed" }, { step: "Implement the button behavior", status: "pending" }, ], }); - asInternals(session).handleNotification("turn/completed", { + await asInternals(session).handleNotification("turn/completed", { turn: { status: "completed", error: null }, }); @@ -5726,24 +6256,24 @@ describe("Codex app-server provider", () => { }); }); - test("does not complete Codex plan timeline cards while plan approval is pending", () => { + test("does not complete Codex plan timeline cards while plan approval is pending", async () => { const session = createSession({ featureValues: { plan_mode: true, fast_mode: true }, }); const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); - asInternals(session).handleNotification("turn/started", { + await asInternals(session).handleNotification("turn/started", { turn: { id: "turn-plan-thread-item" }, }); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { item: { id: "plan-item-1", type: "plan", text: "- Inspect README\n- Add a short note", }, }); - asInternals(session).handleNotification("turn/completed", { + await asInternals(session).handleNotification("turn/completed", { turn: { status: "completed", error: null }, }); @@ -5772,28 +6302,28 @@ describe("Codex app-server provider", () => { }); }); - test("replaces a pending synthetic plan approval when a later plan completes", () => { + test("replaces a pending synthetic plan approval when a later plan completes", async () => { const session = createSession({ featureValues: { plan_mode: true }, }); - asInternals(session).handleNotification("turn/started", { + await asInternals(session).handleNotification("turn/started", { turn: { id: "turn-plan-first" }, }); - asInternals(session).handleNotification("turn/plan/updated", { + await asInternals(session).handleNotification("turn/plan/updated", { plan: [{ step: "Implement the first plan", status: "pending" }], }); - asInternals(session).handleNotification("turn/completed", { + await asInternals(session).handleNotification("turn/completed", { turn: { status: "completed", error: null }, }); - asInternals(session).handleNotification("turn/started", { + await asInternals(session).handleNotification("turn/started", { turn: { id: "turn-plan-second" }, }); - asInternals(session).handleNotification("turn/plan/updated", { + await asInternals(session).handleNotification("turn/plan/updated", { plan: [{ step: "Implement the revised plan", status: "pending" }], }); - asInternals(session).handleNotification("turn/completed", { + await asInternals(session).handleNotification("turn/completed", { turn: { status: "completed", error: null }, }); @@ -5812,13 +6342,13 @@ describe("Codex app-server provider", () => { const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); - asInternals(session).handleNotification("turn/started", { + await asInternals(session).handleNotification("turn/started", { turn: { id: "turn-plan-pending" }, }); - asInternals(session).handleNotification("turn/plan/updated", { + await asInternals(session).handleNotification("turn/plan/updated", { plan: [{ step: "Implement the original plan", status: "pending" }], }); - asInternals(session).handleNotification("turn/completed", { + await asInternals(session).handleNotification("turn/completed", { turn: { status: "completed", error: null }, }); const pendingPlan = session.getPendingPermissions()[0]; @@ -5852,13 +6382,13 @@ describe("Codex app-server provider", () => { featureValues: { plan_mode: true }, }); - asInternals(session).handleNotification("turn/started", { + await asInternals(session).handleNotification("turn/started", { turn: { id: "turn-plan-pending" }, }); - asInternals(session).handleNotification("turn/plan/updated", { + await asInternals(session).handleNotification("turn/plan/updated", { plan: [{ step: "Implement the original plan", status: "pending" }], }); - asInternals(session).handleNotification("turn/completed", { + await asInternals(session).handleNotification("turn/completed", { turn: { status: "completed", error: null }, }); const pendingPlan = session.getPendingPermissions()[0]; @@ -5906,13 +6436,13 @@ describe("Codex app-server provider", () => { featureValues: { plan_mode: true }, }); - asInternals(session).handleNotification("turn/started", { + await asInternals(session).handleNotification("turn/started", { turn: { id: "turn-plan-pending" }, }); - asInternals(session).handleNotification("turn/plan/updated", { + await asInternals(session).handleNotification("turn/plan/updated", { plan: [{ step: "Implement the original plan", status: "pending" }], }); - asInternals(session).handleNotification("turn/completed", { + await asInternals(session).handleNotification("turn/completed", { turn: { status: "completed", error: null }, }); @@ -5937,10 +6467,10 @@ describe("Codex app-server provider", () => { const startTurn = session.startTurn("Revise the plan"); await promptRequested; - asInternals(session).handleNotification("turn/plan/updated", { + await asInternals(session).handleNotification("turn/plan/updated", { plan: [{ step: "Implement the newer plan", status: "pending" }], }); - asInternals(session).handleNotification("turn/completed", { + await asInternals(session).handleNotification("turn/completed", { turn: { status: "completed", error: null }, }); acceptPrompt?.(); @@ -5956,13 +6486,13 @@ describe("Codex app-server provider", () => { featureValues: { plan_mode: true }, }); - asInternals(session).handleNotification("turn/started", { + await asInternals(session).handleNotification("turn/started", { turn: { id: "turn-plan-pending" }, }); - asInternals(session).handleNotification("turn/plan/updated", { + await asInternals(session).handleNotification("turn/plan/updated", { plan: [{ step: "Implement the original plan", status: "pending" }], }); - asInternals(session).handleNotification("turn/completed", { + await asInternals(session).handleNotification("turn/completed", { turn: { status: "completed", error: null }, }); const pendingPlan = session.getPendingPermissions()[0]; @@ -5982,12 +6512,12 @@ describe("Codex app-server provider", () => { expect(session.getPendingPermissions()).toEqual([]); }); - test("emits imageView paths with spaces as valid assistant markdown images", () => { + test("emits imageView paths with spaces as valid assistant markdown images", async () => { const session = createSession(); const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { item: { id: "image-view-1", type: "imageView", @@ -6013,12 +6543,12 @@ describe("Codex app-server provider", () => { ["saved_path", { saved_path: "/tmp/generated-snake.png" }, "file:///tmp/generated-snake.png"], ])( "emits imageGeneration thread items with %s as assistant markdown images", - (_fieldName, imageFields, expectedPath) => { + async (_fieldName, imageFields, expectedPath) => { const session = createSession(); const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { item: { id: `image-generation-${_fieldName}`, type: "imageGeneration", @@ -6041,12 +6571,12 @@ describe("Codex app-server provider", () => { }, ); - test("materializes imageGeneration base64 results before rendering markdown", () => { + test("materializes imageGeneration base64 results before rendering markdown", async () => { const session = createSession(); const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { item: { id: "image-generation-base64", type: "imageGeneration", @@ -6194,21 +6724,22 @@ describe("Codex app-server provider", () => { } }); - test("ignores incomplete imageGeneration thread items without failing the turn", () => { + test("ignores incomplete imageGeneration thread items without failing the turn", async () => { const session = createSession(); const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); - expect(() => - asInternals(session).handleNotification("item/completed", { - item: { - id: "image-generation-incomplete", - type: "imageGeneration", - status: "in_progress", - }, - }), + expect( + async () => + await asInternals(session).handleNotification("item/completed", { + item: { + id: "image-generation-incomplete", + type: "imageGeneration", + status: "in_progress", + }, + }), ).not.toThrow(); - asInternals(session).handleNotification("turn/completed", { + await asInternals(session).handleNotification("turn/completed", { turn: { status: "completed", error: null }, }); @@ -6231,12 +6762,12 @@ describe("Codex app-server provider", () => { ["no failure details", null, { message: "Image generation failed" }], ])( "emits failed imageGeneration items with %s as failed tool calls", - (_label, failure, expectedError) => { + async (_label, failure, expectedError) => { const session = createSession(); const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { item: { id: "image-generation-failed", type: "imageGeneration", @@ -6296,8 +6827,6 @@ describe("Codex app-server provider", () => { })), }; - await asInternals(session).loadPersistedHistory(session.client); - const history: AgentStreamEvent[] = []; for await (const event of session.streamHistory()) { history.push(event); @@ -6323,12 +6852,12 @@ describe("Codex app-server provider", () => { ]); }); - test("emits usage_updated on token usage updates and keeps usage on turn completion", () => { + test("emits usage_updated on token usage updates and keeps usage on turn completion", async () => { const session = createSession(); const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); - asInternals(session).handleNotification("thread/tokenUsage/updated", { + await asInternals(session).handleNotification("thread/tokenUsage/updated", { tokenUsage: { model_context_window: 200000, last: { @@ -6339,7 +6868,7 @@ describe("Codex app-server provider", () => { }, }, }); - asInternals(session).handleNotification("turn/completed", { + await asInternals(session).handleNotification("turn/completed", { turn: { status: "completed", error: null }, }); @@ -6369,20 +6898,20 @@ describe("Codex app-server provider", () => { }); }); - test("streams Codex assistant message deltas and does not replay completed text", () => { + test("streams Codex assistant message deltas and does not replay completed text", async () => { const session = createSession(); const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); - asInternals(session).handleNotification("item/agentMessage/delta", { + await asInternals(session).handleNotification("item/agentMessage/delta", { itemId: "assistant-item-1", delta: "Hel", }); - asInternals(session).handleNotification("item/agentMessage/delta", { + await asInternals(session).handleNotification("item/agentMessage/delta", { itemId: "assistant-item-1", delta: "lo", }); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { item: { id: "assistant-item-1", type: "agentMessage", @@ -6406,20 +6935,20 @@ describe("Codex app-server provider", () => { ]); }); - test("emits only the missing assistant suffix when completed text extends streamed deltas", () => { + test("emits only the missing assistant suffix when completed text extends streamed deltas", async () => { const session = createSession(); const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); - asInternals(session).handleNotification("item/agentMessage/delta", { + await asInternals(session).handleNotification("item/agentMessage/delta", { itemId: "assistant-item-2", delta: "Hel", }); - asInternals(session).handleNotification("item/agentMessage/delta", { + await asInternals(session).handleNotification("item/agentMessage/delta", { itemId: "assistant-item-2", delta: "lo", }); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { item: { id: "assistant-item-2", type: "agentMessage", @@ -6449,24 +6978,24 @@ describe("Codex app-server provider", () => { ]); }); - test("emits a markdown divider when a new Codex assistant item starts after the previous one completed", () => { + test("emits a markdown divider when a new Codex assistant item starts after the previous one completed", async () => { const session = createSession(); const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); - asInternals(session).handleNotification("item/agentMessage/delta", { + await asInternals(session).handleNotification("item/agentMessage/delta", { itemId: "assistant-item-3", delta: "I’m in the waiting phase now. The next read is intentionally delayed so we get meaningful CI state instead of churn.", }); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { item: { id: "assistant-item-3", type: "agentMessage", text: "I’m in the waiting phase now. The next read is intentionally delayed so we get meaningful CI state instead of churn.", }, }); - asInternals(session).handleNotification("item/agentMessage/delta", { + await asInternals(session).handleNotification("item/agentMessage/delta", { itemId: "assistant-item-4", delta: "CI is still cooking. I’m staying on the current run rather than jumping around, because the first red job will tell us exactly whether anything else needs work.", @@ -6496,20 +7025,20 @@ describe("Codex app-server provider", () => { ]); }); - test("streams Codex reasoning deltas and does not replay completed reasoning", () => { + test("streams Codex reasoning deltas and does not replay completed reasoning", async () => { const session = createSession(); const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); - asInternals(session).handleNotification("item/reasoning/summaryTextDelta", { + await asInternals(session).handleNotification("item/reasoning/summaryTextDelta", { itemId: "reasoning-item-1", delta: "Think", }); - asInternals(session).handleNotification("item/reasoning/summaryTextDelta", { + await asInternals(session).handleNotification("item/reasoning/summaryTextDelta", { itemId: "reasoning-item-1", delta: "ing", }); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { item: { id: "reasoning-item-1", type: "reasoning", @@ -6533,20 +7062,20 @@ describe("Codex app-server provider", () => { ]); }); - test("emits only the missing reasoning suffix when completed reasoning extends streamed deltas", () => { + test("emits only the missing reasoning suffix when completed reasoning extends streamed deltas", async () => { const session = createSession(); const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); - asInternals(session).handleNotification("item/reasoning/summaryTextDelta", { + await asInternals(session).handleNotification("item/reasoning/summaryTextDelta", { itemId: "reasoning-item-2", delta: "Think", }); - asInternals(session).handleNotification("item/reasoning/summaryTextDelta", { + await asInternals(session).handleNotification("item/reasoning/summaryTextDelta", { itemId: "reasoning-item-2", delta: "ing", }); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { item: { id: "reasoning-item-2", type: "reasoning", @@ -6583,13 +7112,13 @@ describe("Codex app-server provider", () => { const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); - asInternals(session).handleNotification("turn/started", { + await asInternals(session).handleNotification("turn/started", { turn: { id: "turn-plan-2" }, }); - asInternals(session).handleNotification("turn/plan/updated", { + await asInternals(session).handleNotification("turn/plan/updated", { plan: [{ step: "Implement the new flow", status: "pending" }], }); - asInternals(session).handleNotification("turn/completed", { + await asInternals(session).handleNotification("turn/completed", { turn: { status: "completed", error: null }, }); @@ -6637,13 +7166,13 @@ describe("Codex app-server provider", () => { const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); - asInternals(session).handleNotification("turn/started", { + await asInternals(session).handleNotification("turn/started", { turn: { id: "turn-plan-3" }, }); - asInternals(session).handleNotification("turn/plan/updated", { + await asInternals(session).handleNotification("turn/plan/updated", { plan: [{ step: "Implement the safe flow", status: "pending" }], }); - asInternals(session).handleNotification("turn/completed", { + await asInternals(session).handleNotification("turn/completed", { turn: { status: "completed", error: null }, }); @@ -6705,13 +7234,13 @@ describe("Codex app-server provider", () => { const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); - asInternals(session).handleNotification("turn/started", { + await asInternals(session).handleNotification("turn/started", { turn: { id: "turn-plan-4" }, }); - asInternals(session).handleNotification("turn/plan/updated", { + await asInternals(session).handleNotification("turn/plan/updated", { plan: [{ step: "Implement the fast flow", status: "pending" }], }); - asInternals(session).handleNotification("turn/completed", { + await asInternals(session).handleNotification("turn/completed", { turn: { status: "completed", error: null }, }); @@ -6895,9 +7424,21 @@ describe("Codex importable sessions", () => { const threadsByModelProvider = [ { id: "stock-thread", cwd: "/workspace/project-a", modelProvider: "openai", updatedAt: 2 }, { id: "custom-thread", cwd: "/workspace/project-a", modelProvider: "my-codex", updatedAt: 1 }, + { + id: "new-custom-thread", + cwd: "/workspace/project-a", + modelProvider: "paseo:my-codex", + updatedAt: 3, + }, + { + id: "other-custom-thread", + cwd: "/workspace/project-a", + modelProvider: "paseo-my-codex", + updatedAt: 4, + }, ]; - test("a custom Codex provider lists the threads it created", async () => { + test("a custom Codex provider lists its old and namespaced threads without other providers", async () => { const appServer = createFakeCodexAppServer({ "thread/list": providerFilteringThreadListHandler(threadsByModelProvider), }); @@ -6910,10 +7451,40 @@ describe("Codex importable sessions", () => { const sessions = await provider.listImportableSessions({ cwd: "/workspace/project-a" }); - expect(sessions.map((session) => session.providerHandleId)).toEqual(["custom-thread"]); + expect(sessions.map((session) => session.providerHandleId)).toEqual([ + "custom-thread", + "new-custom-thread", + ]); appServer.assertNoErrors(); }); + test.each(["openai", "ollama", "lmstudio", "amazon-bedrock", "amazon-bedrock-runtime", "gcp"])( + "a custom provider named %s excludes native built-in sessions", + async (providerId) => { + const appServer = createFakeCodexAppServer({ + "thread/list": providerFilteringThreadListHandler([ + { id: "native-thread", cwd: "/workspace/project-a", modelProvider: providerId }, + { + id: "custom-thread", + cwd: "/workspace/project-a", + modelProvider: `paseo:${providerId}`, + }, + ]), + }); + const provider = createProviderWithFakeAppServer(appServer, { + runtimeSettings: { + env: { OPENAI_BASE_URL: "https://llm.example.test/v1", OPENAI_API_KEY: "test-key" }, + }, + customProvider: { id: providerId, label: "Custom Codex", extends: "codex" }, + }); + + const sessions = await provider.listImportableSessions({ cwd: "/workspace/project-a" }); + + expect(sessions.map((session) => session.providerHandleId)).toEqual(["custom-thread"]); + appServer.assertNoErrors(); + }, + ); + test("stock Codex keeps listing only its own threads", async () => { const appServer = createFakeCodexAppServer({ "thread/list": providerFilteringThreadListHandler(threadsByModelProvider), @@ -7182,6 +7753,7 @@ test("Codex runtime safety queries live terminals and retains unsupported app se await appServer.waitForTurnStart(); expect(await session.canStopRuntime()).toBe(false); appServer.completeTurn({ threadId: "thread-1" }); + await new Promise((resolve) => setImmediate(resolve)); await expect.poll(() => session.canStopRuntime()).toBe(true); response = { data: [{ processId: "shell-1" }], nextCursor: null }; expect(await session.canStopRuntime()).toBe(false); @@ -7199,3 +7771,60 @@ test("Codex runtime safety queries live terminals and retains unsupported app se await session.close(); } }); + +test("publishes a materialized image before dispatching the following turn completion", async () => { + const appServer = createFakeCodexAppServer(); + const session = new CodexAppServerAgentSession( + createConfig(), + null, + createTestLogger(), + async () => appServer.child, + ); + const events: AgentStreamEvent[] = []; + session.subscribe((event) => events.push(event)); + try { + await session.startTurn("generate an image"); + const data = Buffer.alloc(1024 * 1024, 47).toString("base64"); + const imageFrame = + JSON.stringify({ + method: "item/completed", + params: { + item: { + id: "ordered-image", + type: "imageGeneration", + status: "completed", + result: { data, mimeType: "image/png" }, + }, + }, + }) + "\n"; + const completed = new Promise((resolve) => + session.subscribe((event) => { + if (event.type === "turn_completed") resolve(); + }), + ); + appServer.child.stdout.write(imageFrame); + appServer.child.stdout.write( + JSON.stringify({ + method: "turn/completed", + params: { turn: { status: "completed", error: null } }, + }) + "\n", + ); + await completed; + await new Promise((resolve) => setTimeout(resolve, 5)); + const imageIndex = events.findIndex( + (event) => + event.type === "timeline" && + event.item.type === "assistant_message" && + event.item.text.includes("![Image]"), + ); + const completedIndex = events.findIndex((event) => event.type === "turn_completed"); + expect(imageIndex).toBeGreaterThanOrEqual(0); + expect(imageIndex).toBeLessThan(completedIndex); + const imageEvent = events[imageIndex]; + if (imageEvent.type !== "timeline" || imageEvent.item.type !== "assistant_message") + throw new Error("Expected image"); + expect(existsSync(markdownImageSource(imageEvent.item.text))).toBe(true); + } finally { + await session.close(); + } +}); diff --git a/packages/server/src/server/agent/providers/codex-app-server-agent.ts b/packages/server/src/server/agent/providers/codex-app-server-agent.ts index f438c98ec4..2aecd18e21 100644 --- a/packages/server/src/server/agent/providers/codex-app-server-agent.ts +++ b/packages/server/src/server/agent/providers/codex-app-server-agent.ts @@ -49,10 +49,10 @@ import { Dirent } from "node:fs"; import fs from "node:fs/promises"; import os from "node:os"; import path from "node:path"; +import { isDeepStrictEqual } from "node:util"; import { z } from "zod"; import { renderPromptAttachmentAsText } from "../prompt-attachments.js"; import { composeSystemPromptParts } from "../system-prompt.js"; -import { curateAgentActivity } from "../activity-curator.js"; import { CodexAsyncQuestions, codexAsyncQuestionToTimeline } from "./codex/async-questions.js"; import { mapCodexToolCallEnvelope, @@ -92,12 +92,18 @@ import { type CodexAppServerTraceContext, } from "./codex/app-server-transport.js"; import { type CodexUserMessageTurnIndex, revertCodexConversation } from "./codex/rewind.js"; +import { + type CodexHistoryRow, + CodexThreadHistoryTooLargeError, + readCodexThreadHistory, +} from "./codex/thread-history.js"; import { materializeProviderImage, renderProviderImageOutputAsAssistantMarkdown, type ProviderImageOutput, } from "./provider-image-output.js"; import { normalizeProviderReplayTimestamp } from "../provider-history-timestamps.js"; +import { limitAgentTimelineItemContent } from "../agent-timeline-content.js"; import { formatProviderDiagnostic, formatProviderDiagnosticError, @@ -145,6 +151,16 @@ function isCodexAlreadyUnarchivedError(error: unknown, threadId: string): boolea const TURN_START_TIMEOUT_MS = 90 * 1000; const INTERRUPT_TIMEOUT_MS = 2_000; const CODEX_PROVIDER = "codex" as const; +// These native provider identities belong to Codex, not to an older custom +// Paseo provider. Never include them in a custom provider's legacy import scan. +const CODEX_BUILTIN_MODEL_PROVIDER_IDS = new Set([ + "openai", + "ollama", + "lmstudio", + "amazon-bedrock", + "amazon-bedrock-runtime", + "gcp", +]); // Codex treats most app-server client names as the model-request originator. // This reserved Codex name is non-originating, so requests keep Codex's default // CLI identity instead of showing up as Paseo in provider usage logs. @@ -496,6 +512,11 @@ interface PersistedTimelineEntry { providerTurnId?: string; } +interface CodexThreadHistory { + timeline: PersistedTimelineEntry[]; + providerSubagentEvents: AgentStreamEvent[]; +} + interface PersistedSubAgentRoute { childThreadId: string; toolCall: ToolCallTimelineItem; @@ -1799,22 +1820,13 @@ function readCodexHistoryTimestamp(item: unknown): string | null { ); } -function readCodexTurnHistoryTimestamp( - turn: unknown, +/** Falls back to the row's start time for a user message and its end time otherwise. */ +function readCodexHistoryRowTimestamp( + row: CodexHistoryRow, timelineItem: AgentTimelineItem, ): string | null { - const record = toObjectRecord(turn); - if (!record) { - return null; - } - - const startedAt = - normalizeProviderReplayTimestamp(record.startedAt) ?? - normalizeProviderReplayTimestamp(record.started_at); - const completedAt = - normalizeProviderReplayTimestamp(record.completedAt) ?? - normalizeProviderReplayTimestamp(record.completed_at); - + const startedAt = normalizeProviderReplayTimestamp(row.startedAt); + const completedAt = normalizeProviderReplayTimestamp(row.completedAt); if (timelineItem.type === "user_message") { return startedAt ?? completedAt; } @@ -1939,12 +1951,12 @@ function codexImageOutputFromResult(result: unknown): ProviderImageOutput | null }; } -function mapCodexThreadImageItem( +async function mapCodexThreadImageItem( normalizedType: string, normalizedItem: Record, -): AgentTimelineItem | null { +): Promise { if (normalizedType === "imageView") { - return renderProviderImageOutputAsAssistantMarkdown({ + return await renderProviderImageOutputAsAssistantMarkdown({ path: firstStringField(normalizedItem, ["path"]), }); } @@ -1960,7 +1972,7 @@ function mapCodexThreadImageItem( const savedPath = firstStringField(normalizedItem, ["savedPath", "saved_path"]); const result = codexImageOutputFromResult(normalizedItem.result); - return renderProviderImageOutputAsAssistantMarkdown( + return await renderProviderImageOutputAsAssistantMarkdown( { path: savedPath ?? result?.path ?? null, url: result?.url ?? null, @@ -1982,10 +1994,10 @@ function mapCodexAgentMessage(item: Record): AgentTimelineItem }; } -export function threadItemToTimeline( +export async function threadItemToTimeline( item: unknown, options?: { includeUserMessage?: boolean; cwd?: string | null }, -): AgentTimelineItem | null { +): Promise { const itemRecord = toObjectRecord(item); if (!itemRecord) return null; const includeUserMessage = options?.includeUserMessage ?? true; @@ -1999,7 +2011,7 @@ export function threadItemToTimeline( : itemRecord; if (normalizedType === "imageView" || normalizedType === "imageGeneration") { - return mapCodexThreadImageItem(normalizedType, normalizedItem); + return await mapCodexThreadImageItem(normalizedType, normalizedItem); } if (normalizedType && CODEX_TOOL_THREAD_ITEM_TYPES.has(normalizedType)) { return mapCodexToolCallFromThreadItem(normalizedItem, { cwd }); @@ -2024,7 +2036,7 @@ export function threadItemToTimeline( } } -function mcpToolResultImagesToTimeline(item: unknown): AgentTimelineItem[] { +async function mcpToolResultImagesToTimeline(item: unknown): Promise { const itemRecord = toObjectRecord(item); if (!itemRecord) { return []; @@ -2037,104 +2049,40 @@ function mcpToolResultImagesToTimeline(item: unknown): AgentTimelineItem[] { } const { images } = splitCodexMcpToolResultImages(itemRecord.result); - return images - .map((image) => - renderProviderImageOutputAsAssistantMarkdown(image, { - materialize: materializeProviderImage, - }), - ) - .filter((timelineItem): timelineItem is AgentTimelineItem => timelineItem !== null); + const items: AgentTimelineItem[] = []; + for (const image of images) { + const imageItem = await renderProviderImageOutputAsAssistantMarkdown(image, { + materialize: materializeProviderImage, + }); + if (imageItem) items.push(imageItem); + } + return items; } -function threadItemToTimelineEntries( +async function threadItemToTimelineEntries( item: unknown, options?: { includeUserMessage?: boolean; cwd?: string | null }, -): AgentTimelineItem[] { - const timelineItem = threadItemToTimeline(item, options); +): Promise { + const timelineItem = await threadItemToTimeline(item, options); if (!timelineItem) { return []; } - return [timelineItem, ...mcpToolResultImagesToTimeline(item)]; -} - -const CodexThreadReadResponseSchema = z - .object({ - thread: z - .object({ - turns: z - .array( - z - .object({ - items: z.array(z.unknown()).default([]), - }) - .passthrough(), - ) - .default([]), - }) - .passthrough() - .default({ turns: [] }), - }) - .passthrough(); - -type CodexThreadReadResponse = z.infer; -type CodexThreadReadRequest = (threadId: string) => Promise; - -async function requestCodexThreadHistory( - requestThread: CodexThreadReadRequest, - threadId: string, -): Promise { - const response = await requestThread(threadId); - return CodexThreadReadResponseSchema.parse(response); + return [timelineItem, ...(await mcpToolResultImagesToTimeline(item))]; } async function loadCodexThreadHistoryTimeline(params: { + client: CodexAppServerClientLike; threadId: string; cwd: string | null; - requestThread: CodexThreadReadRequest; }): Promise { - const response = await requestCodexThreadHistory(params.requestThread, params.threadId); const timeline: PersistedTimelineEntry[] = []; const subAgentTimelineIndexByThreadId = new Map(); - for (const turn of response.thread.turns) { - for (const item of turn.items) { - const historicalSubAgentActivity = readCodexSubAgentActivity(item); - if (historicalSubAgentActivity) { - const existingIndex = subAgentTimelineIndexByThreadId.get( - historicalSubAgentActivity.agentThreadId, - ); - if (existingIndex !== undefined) { - const activityTimelineItem = threadItemToTimeline(item, { cwd: params.cwd }); - updateHistoricalSubAgentActivity( - timeline, - existingIndex, - historicalSubAgentActivity.kind, - activityTimelineItem?.type === "tool_call" && - activityTimelineItem.detail.type === "sub_agent" - ? activityTimelineItem.detail.subAgentType - : undefined, - ); - continue; - } - } - for (const timelineItem of threadItemToTimelineEntries(item, { cwd: params.cwd })) { - const timestamp = - readCodexHistoryTimestamp(item) ?? readCodexTurnHistoryTimestamp(turn, timelineItem); - const settledTimelineItem = - historicalSubAgentActivity && timelineItem.type === "tool_call" - ? settleHistoricalSubAgentActivity(timelineItem, historicalSubAgentActivity.kind) - : timelineItem; - timeline.push({ - item: settledTimelineItem, - timestamp: timestamp ?? undefined, - ...(timelineItem.type === "user_message" && typeof turn.id === "string" - ? { providerTurnId: turn.id } - : {}), - }); - for (const childThreadId of readCodexHistoricalSubAgentThreadIds(item)) { - subAgentTimelineIndexByThreadId.set(childThreadId, timeline.length - 1); - } - } - } + try { + await projectCodexThreadHistory(params, { timeline, subAgentTimelineIndexByThreadId }); + } catch (error) { + if (!(error instanceof CodexThreadHistoryTooLargeError)) throw error; + // The session stays usable; the row says why the history stops here. + timeline.push({ item: { type: "notification", level: "warning", message: error.message } }); } const subAgentRoutes = Array.from(subAgentTimelineIndexByThreadId.entries()).flatMap( ([childThreadId, timelineIndex]): PersistedSubAgentRoute[] => { @@ -2147,11 +2095,55 @@ async function loadCodexThreadHistoryTimeline(params: { return { timeline, subAgentRoutes }; } -function readCodexThread(client: CodexAppServerClientLike, threadId: string): Promise { - return client.request("thread/read", { - threadId, - includeTurns: true, - }); +async function projectCodexThreadHistory( + params: { client: CodexAppServerClientLike; threadId: string; cwd: string | null }, + projection: { + timeline: PersistedTimelineEntry[]; + subAgentTimelineIndexByThreadId: Map; + }, +): Promise { + const { timeline, subAgentTimelineIndexByThreadId } = projection; + for await (const row of readCodexThreadHistory(params.client, params.threadId)) { + const { item } = row; + const historicalSubAgentActivity = readCodexSubAgentActivity(item); + if (historicalSubAgentActivity) { + const existingIndex = subAgentTimelineIndexByThreadId.get( + historicalSubAgentActivity.agentThreadId, + ); + if (existingIndex !== undefined) { + const activityTimelineItem = await threadItemToTimeline(item, { cwd: params.cwd }); + updateHistoricalSubAgentActivity( + timeline, + existingIndex, + historicalSubAgentActivity.kind, + activityTimelineItem?.type === "tool_call" && + activityTimelineItem.detail.type === "sub_agent" + ? activityTimelineItem.detail.subAgentType + : undefined, + ); + continue; + } + } + for (const timelineItem of await threadItemToTimelineEntries(item, { cwd: params.cwd })) { + const timestamp = + readCodexHistoryTimestamp(item) ?? readCodexHistoryRowTimestamp(row, timelineItem); + const settledTimelineItem = + historicalSubAgentActivity && timelineItem.type === "tool_call" + ? settleHistoricalSubAgentActivity(timelineItem, historicalSubAgentActivity.kind) + : timelineItem; + timeline.push({ + // Cap each item as it is projected so a large history is never held uncapped. + item: limitAgentTimelineItemContent(settledTimelineItem), + timestamp: timestamp ?? undefined, + ...(timelineItem.type === "user_message" && row.turnId !== undefined + ? { providerTurnId: row.turnId } + : {}), + }); + for (const childThreadId of readCodexHistoricalSubAgentThreadIds(item)) { + subAgentTimelineIndexByThreadId.set(childThreadId, timeline.length - 1); + } + } + } } export async function forkCodexThread( @@ -3290,10 +3282,12 @@ export async function codexAppServerTurnInputFromPrompt( } if (block.type === "image") { try { - const filePath = materializeProviderImage({ - data: block.data, - mimeType: block.mimeType, - }).path; + const filePath = ( + await materializeProviderImage({ + data: block.data, + mimeType: block.mimeType, + }) + ).path; output.push({ type: "localImage", path: filePath }); } catch (error) { const message = error instanceof Error ? error.message : String(error); @@ -3384,10 +3378,14 @@ function buildCodexCustomProviderConfig( providerConfig.env_key = "OPENAI_API_KEY"; providerConfig.requires_openai_auth = false; } + // Namespace Paseo ids so they cannot override Codex's built-ins. A colon is + // forbidden in Paseo ids, keeping these keys distinct from every legacy id + // when both generations are listed together. + const providerKey = `paseo:${customProvider.id}`; return { - model_provider: customProvider.id, + model_provider: providerKey, model_providers: { - [customProvider.id]: providerConfig, + [providerKey]: providerConfig, }, }; } @@ -3400,8 +3398,6 @@ interface CodexSubAgentCallState { activityItemIds: Set; pendingCommandOutputDeltas: Map; pendingFileChangeOutputDeltas: Map; - childItemOrder: string[]; - childItems: Map; childThreadIds: Set; } @@ -3439,6 +3435,9 @@ export class CodexAppServerAgentSession implements AgentSession { > | null = null; private resolvedSandboxPolicy: Record | null = null; private currentThreadId: string | null = null; + // Codex writes a new thread's rollout at its first turn. Until then the thread exists only + // in this app-server, so no other app-server can resume it and it is not reported. + private savedThreadId: string | null = null; private currentTurnId: string | null = null; private pendingForegroundTurnIdentification: { foregroundTurnId: string; @@ -3461,10 +3460,12 @@ export class CodexAppServerAgentSession implements AgentSession { private serviceTier: string | null = null; private speedModels: CodexModel[] = []; private planModeEnabled = false; - private historyPending = false; - private persistedHistory: PersistedTimelineEntry[] = []; - private loadingPersistedHistory = false; - private persistedProviderSubagentEvents: AgentStreamEvent[] = []; + // History read by rewind or an archived resume, held until streamHistory consumes it. + private stagedHistory: CodexThreadHistory | null = null; + // Collects provider subagent events emitted while a thread history read rebuilds routes. + private historySubagentEvents: AgentStreamEvent[] | null = null; + // A resumed thread's earlier turns and sub-agents are known only after reading its history. + private historyIndexed = true; private pendingPermissions = new Map(); private mcpElicitationPermissionIds = new Map(); private pendingPermissionHandlers = new Map(); @@ -3501,6 +3502,9 @@ export class CodexAppServerAgentSession implements AgentSession { private compactionTriggerByItemId = new Map(); private pendingRootCompactionItemIds = new Set(); private pendingAnonymousRootCompactions = 0; + // Child threads with a compaction shown as loading. Some Codex builds settle it only through + // `thread/compacted` or the end of the child's turn. + private pendingChildCompactionThreadIds = new Set(); // Codex can report one completed compaction through both channels: // `thread/compacted` and a completed `contextCompaction` item. private unpairedCompactionNotificationCompletions = 0; @@ -3571,7 +3575,8 @@ export class CodexAppServerAgentSession implements AgentSession { if (this.resumeHandle?.sessionId) { this.currentThreadId = this.resumeHandle.sessionId; - this.historyPending = true; + this.savedThreadId = this.resumeHandle.sessionId; + this.historyIndexed = false; // Resuming can start a goal before the caller receives the session. if (this.initialResumePurpose === "interactive") this.startupEvents = []; } @@ -3619,7 +3624,7 @@ export class CodexAppServerAgentSession implements AgentSession { private async establishConnection(): Promise { if (this.initialResumePurpose === "history") { - await this.readArchivedHistory(); + this.stagedHistory = await this.readArchivedHistory(); this.connectionState = "history-ready"; return; } @@ -3652,7 +3657,6 @@ export class CodexAppServerAgentSession implements AgentSession { if (this.currentThreadId) { await this.ensureThreadLoaded(); - await this.loadPersistedHistory(this.client); await this.applyDefaultModelAndThinking(); } @@ -3967,39 +3971,40 @@ export class CodexAppServerAgentSession implements AgentSession { ); } - private async readArchivedHistory(): Promise { + private async readArchivedHistory(): Promise { const child = await this.spawnAppServer(); const client = new CodexAppServerClient(child, this.logger, () => this.traceContext()); try { await client.request("initialize", buildCodexAppServerInitializeParams()); client.notify("initialized", {}); - await this.loadPersistedHistory(client); + return await this.readThreadHistory(client); } finally { await client.dispose(); } } - private async loadPersistedHistory(client: CodexAppServerClientLike | null): Promise { - if (!client || !this.currentThreadId) return; - const threadId = this.currentThreadId; - - const history = await loadCodexThreadHistoryTimeline({ - threadId, + // Reads the thread and its sub-agent threads, rebuilding the turn index and + // sub-agent routes. The caller owns the returned history; nothing retains it. + private async readThreadHistory( + client: CodexAppServerClientLike | null, + ): Promise { + if (!client || !this.currentThreadId) { + return { timeline: [], providerSubagentEvents: [] }; + } + const { timeline, subAgentRoutes } = await loadCodexThreadHistoryTimeline({ + client, + threadId: this.currentThreadId, cwd: this.config.cwd ?? null, - requestThread: (threadIdToRead) => { - return readCodexThread(client, threadIdToRead); - }, }); - const { timeline, subAgentRoutes } = history; this.subAgentCallsByCallId.clear(); this.subAgentCallIdByChildThreadId.clear(); this.pendingSubAgentNotificationsByThreadId.clear(); - this.persistedProviderSubagentEvents = []; - this.loadingPersistedHistory = true; + const providerSubagentEvents: AgentStreamEvent[] = []; + this.historySubagentEvents = providerSubagentEvents; try { await this.loadPersistedSubAgentHistories(client, subAgentRoutes); } finally { - this.loadingPersistedHistory = false; + this.historySubagentEvents = null; } this.resetCodexUserMessageTurns(); for (const entry of timeline) { @@ -4010,8 +4015,15 @@ export class CodexAppServerAgentSession implements AgentSession { this.rememberCodexUserMessageTurn(entry.item.messageId, entry.providerTurnId); } } - this.persistedHistory = timeline; - this.historyPending = timeline.length > 0; + this.historyIndexed = true; + return { timeline, providerSubagentEvents }; + } + + // Turns and rewind route by the thread's earlier turns and sub-agents. A resumed + // session whose projection Paseo already holds reads them here and drops the rest. + private async ensureHistoryIndexed(): Promise { + if (this.historyIndexed) return; + await this.readThreadHistory(this.client); } private async loadPersistedSubAgentHistories( @@ -4038,9 +4050,9 @@ export class CodexAppServerAgentSession implements AgentSession { }); try { const childHistory = await loadCodexThreadHistoryTimeline({ + client, threadId: next.route.childThreadId, cwd: this.config.cwd ?? null, - requestThread: (childThreadId) => readCodexThread(client, childThreadId), }); for (const entry of childHistory.timeline) { this.emitProviderSubagentTimeline(next.route.childThreadId, entry.item, entry.timestamp); @@ -4063,7 +4075,13 @@ export class CodexAppServerAgentSession implements AgentSession { private async ensureThreadLoaded(): Promise { if (!this.client || !this.currentThreadId) return; - const params: Record = { threadId: this.currentThreadId }; + // Paseo reads history only when it replays it; the resume response needs no turns. + const params: Record = { threadId: this.currentThreadId, excludeTurns: true }; + if (this.deps.customCodexConfig) { + // Resume otherwise prefers the provider stored on the thread, including + // the unnamespaced key emitted by earlier Paseo versions. + params.modelProvider = this.deps.customCodexConfig.model_provider; + } const developerInstructions = composeSystemPromptParts( this.config.systemPrompt, this.config.daemonAppendSystemPrompt, @@ -4370,6 +4388,7 @@ export class CodexAppServerAgentSession implements AgentSession { this.dismissPendingPlanApprovals("Dismissed by a new prompt"); try { + await this.pendingNotifications; await this.connect(); if (!this.client) { throw new Error("Codex client not initialized"); @@ -4382,6 +4401,7 @@ export class CodexAppServerAgentSession implements AgentSession { if (this.currentThreadId) { await this.ensureThreadLoaded(); + await this.ensureHistoryIndexed(); } else { await this.ensureThread(); } @@ -4436,9 +4456,18 @@ export class CodexAppServerAgentSession implements AgentSession { ): Promise { const client = this.client; const threadId = this.currentThreadId; - const nativeTurnId = this.currentTurnId; + let nativeTurnId = this.currentTurnId; const foregroundTurnId = this.activeForegroundTurnId; - if (!client || !threadId || !nativeTurnId || foregroundTurnId !== options.expectedTurnId) { + if (!client || !threadId || foregroundTurnId !== options.expectedTurnId) { + return { status: "unavailable" }; + } + const pendingIdentification = this.pendingForegroundTurnIdentification; + // The start acknowledgement precedes the notification that identifies the native + // turn. Keep this steer attached to the accepted foreground turn while it arrives. + if (!nativeTurnId && pendingIdentification?.foregroundTurnId === foregroundTurnId) { + nativeTurnId = await pendingIdentification.promise; + } + if (!nativeTurnId) { return { status: "unavailable" }; } if (await this.resolveSlashCommandInvocation(prompt)) return { status: "unavailable" }; @@ -4555,21 +4584,12 @@ export class CodexAppServerAgentSession implements AgentSession { } async *streamHistory(): AsyncGenerator { - if ( - (!this.historyPending || this.persistedHistory.length === 0) && - this.persistedProviderSubagentEvents.length === 0 - ) { - return; - } - const history = this.persistedHistory; - const providerSubagents = this.persistedProviderSubagentEvents; - this.persistedHistory = []; - this.persistedProviderSubagentEvents = []; - this.historyPending = false; - for (const event of providerSubagents) { + const history = this.stagedHistory ?? (await this.readThreadHistory(this.client)); + this.stagedHistory = null; + for (const event of history.providerSubagentEvents) { yield event; } - for (const entry of history) { + for (const entry of history.timeline) { yield { type: "timeline", provider: CODEX_PROVIDER, @@ -4589,7 +4609,7 @@ export class CodexAppServerAgentSession implements AgentSession { } const info: AgentRuntimeInfo = { provider: CODEX_PROVIDER, - sessionId: this.currentThreadId, + sessionId: this.savedCurrentThreadId(), model: this.config.model ?? null, thinkingOptionId: normalizeCodexThinkingOptionId(this.config.thinkingOptionId) ?? null, modeId: this.currentMode ?? null, @@ -4920,17 +4940,18 @@ export class CodexAppServerAgentSession implements AgentSession { nativeHandle: string; metadata: Record; } | null { - if (!this.currentThreadId) return null; + const threadId = this.savedCurrentThreadId(); + if (!threadId) return null; const thinkingOptionId = normalizeCodexThinkingOptionId(this.config.thinkingOptionId) ?? null; return { provider: CODEX_PROVIDER, - sessionId: this.currentThreadId, - nativeHandle: this.currentThreadId, + sessionId: threadId, + nativeHandle: threadId, metadata: { provider: CODEX_PROVIDER, cwd: this.config.cwd, title: this.config.title ?? null, - threadId: this.currentThreadId, + threadId, modeId: this.config.modeId, model: this.config.model ?? null, thinkingOptionId, @@ -4942,6 +4963,12 @@ export class CodexAppServerAgentSession implements AgentSession { }; } + private savedCurrentThreadId(): string | null { + return this.currentThreadId !== null && this.currentThreadId === this.savedThreadId + ? this.currentThreadId + : null; + } + async revertConversation(input: { messageId: string }): Promise { await this.connect(); if (!this.client) { @@ -4952,6 +4979,7 @@ export class CodexAppServerAgentSession implements AgentSession { } else { await this.ensureThread(); } + await this.ensureHistoryIndexed(); await revertCodexConversation({ client: this.client, @@ -4965,11 +4993,11 @@ export class CodexAppServerAgentSession implements AgentSession { threadRollbackAvailable: this.threadRollbackAvailable, setThreadId: async (threadId) => { this.currentThreadId = threadId; + // Codex writes a forked thread's rollout when it forks it, even before any turn. + this.savedThreadId = threadId; this.cachedRuntimeInfo = null; - this.persistedHistory = []; - this.historyPending = false; - await this.loadPersistedHistory(this.client); - this.reconcileAsyncQuestionsAfterRewind(); + this.stagedHistory = await this.readThreadHistory(this.client); + this.reconcileAsyncQuestionsAfterRewind(this.stagedHistory.timeline); }, }); } @@ -5207,6 +5235,8 @@ export class CodexAppServerAgentSession implements AgentSession { await this.connect(); if (this.currentThreadId) { await this.ensureThreadLoaded(); + // A goal runs turns of its own. + await this.ensureHistoryIndexed(); } else { await this.ensureThread(); } @@ -5400,8 +5430,8 @@ export class CodexAppServerAgentSession implements AgentSession { } private emitEvent(event: AgentStreamEvent): void { - if (this.loadingPersistedHistory && event.type === "provider_subagent") { - this.persistedProviderSubagentEvents.push(event); + if (this.historySubagentEvents && event.type === "provider_subagent") { + this.historySubagentEvents.push(event); return; } this.notifySubscribers(event); @@ -5437,7 +5467,21 @@ export class CodexAppServerAgentSession implements AgentSession { return `codex-turn-${this.nextTurnOrdinal++}`; } - private handleNotification(method: string, params: unknown): void { + private pendingNotifications: Promise = Promise.resolve(); + + private handleNotification(method: string, params: unknown): Promise { + // An image must exist before its event, and completion must follow that event. + // Transport callbacks cannot await: the session owns their ordered drain. + const next = this.pendingNotifications.then(() => { + return this.closed ? undefined : this.processNotification(method, params); + }); + this.pendingNotifications = next.catch((error: unknown) => { + this.handleUnexpectedTermination(error instanceof Error ? error : new Error(String(error))); + }); + return this.pendingNotifications; + } + + private async processNotification(method: string, params: unknown): Promise { const notificationParams = toObjectRecord(params); if (method === "serverRequest/resolved" && typeof notificationParams?.requestId === "number") { const requestId = this.mcpElicitationPermissionIds.get(notificationParams.requestId); @@ -5467,13 +5511,16 @@ export class CodexAppServerAgentSession implements AgentSession { return; } if (route.kind === "sub_agent") { - this.dispatchSubAgentNotification(parsed, route.callId); + await this.dispatchSubAgentNotification(parsed, route.callId); return; } - this.dispatchParsedNotification(parsed); + await this.dispatchParsedNotification(parsed); } - private dispatchSubAgentNotification(parsed: ParsedCodexNotification, callId: string): void { + private async dispatchSubAgentNotification( + parsed: ParsedCodexNotification, + callId: string, + ): Promise { switch (parsed.kind) { case "thread_started": this.emitSubAgentActivityUpdate(callId, "running", { reopen: true }); @@ -5484,7 +5531,7 @@ export class CodexAppServerAgentSession implements AgentSession { case "reasoning_delta": case "item_started": case "item_completed": - this.dispatchParsedNotification(parsed); + await this.dispatchParsedNotification(parsed); return; case "exec_command_output_delta": case "file_change_output_delta": @@ -5502,6 +5549,9 @@ export class CodexAppServerAgentSession implements AgentSession { case "patch_apply_completed": this.handlePatchApplyCompletedNotification(parsed, callId); return; + case "context_compacted": + this.settleChildCompaction(parsed.threadId); + return; default: // Aggregate child telemetry is redundant and must not leak into the // root timeline. Concrete legacy tools are projected above for Codex @@ -5510,7 +5560,7 @@ export class CodexAppServerAgentSession implements AgentSession { } } - private dispatchParsedNotification(parsed: ParsedCodexNotification): void { + private async dispatchParsedNotification(parsed: ParsedCodexNotification): Promise { if (isCodexDeltaNotification(parsed)) { this.handleCodexDeltaNotification(parsed); return; @@ -5555,10 +5605,10 @@ export class CodexAppServerAgentSession implements AgentSession { this.handlePatchApplyCompletedNotification(parsed); return; case "item_completed": - this.handleItemCompletedNotification(parsed); + await this.handleItemCompletedNotification(parsed); return; case "item_started": - this.handleItemStartedNotification(parsed); + await this.handleItemStartedNotification(parsed); return; case "invalid_payload": this.warnInvalidNotificationPayload(parsed.method, parsed.params); @@ -5600,7 +5650,7 @@ export class CodexAppServerAgentSession implements AgentSession { pending.push(parsed); } - private replayPendingSubAgentNotifications(threadIds: readonly string[]): void { + private async replayPendingSubAgentNotifications(threadIds: readonly string[]): Promise { for (const threadId of threadIds) { const pending = this.pendingSubAgentNotificationsByThreadId.get(threadId); if (!pending) { @@ -5612,7 +5662,7 @@ export class CodexAppServerAgentSession implements AgentSession { continue; } for (const parsed of pending) { - this.dispatchSubAgentNotification(parsed, callId); + await this.dispatchSubAgentNotification(parsed, callId); } } } @@ -5678,20 +5728,10 @@ export class CodexAppServerAgentSession implements AgentSession { activityItemIds: new Set(), pendingCommandOutputDeltas: new Map(), pendingFileChangeOutputDeltas: new Map(), - childItemOrder: [], - childItems: new Map(), childThreadIds: new Set(), } satisfies CodexSubAgentCallState); - state.toolCall = { - ...timelineItem, - detail: { - ...timelineItem.detail, - log: - timelineItem.detail.log || - (state.toolCall.detail.type === "sub_agent" ? state.toolCall.detail.log : ""), - }, - }; + state.toolCall = timelineItem; state.parentCallId ??= parentCallId; state.parentSubagentId ??= parentSubagentId; const activity = readCodexSubAgentActivity(rawItem); @@ -5744,25 +5784,17 @@ export class CodexAppServerAgentSession implements AgentSession { const activityToolCall = mapCodexToolCallFromThreadItem(rawItem, { cwd: this.config.cwd ?? null, }); - if ( - activityToolCall?.detail.type === "sub_agent" && - state.toolCall.detail.type === "sub_agent" - ) { - state.toolCall = { - ...state.toolCall, - detail: { - ...state.toolCall.detail, - subAgentType: activityToolCall.detail.subAgentType, - }, - }; - } + const subAgentType = + activityToolCall?.detail.type === "sub_agent" + ? activityToolCall.detail.subAgentType + : undefined; let nextStatus: ToolCallTimelineItem["status"] | undefined = "running"; if (activity.kind === "interrupted") { nextStatus = "canceled"; } else if (isTerminalSubAgentStatus(state.toolCall.status)) { nextStatus = undefined; } - this.emitSubAgentActivityUpdate(callId, nextStatus); + this.emitSubAgentActivityUpdate(callId, nextStatus, { subAgentType }); return true; } @@ -5803,7 +5835,13 @@ export class CodexAppServerAgentSession implements AgentSession { ): boolean { if ( childSubAgentCallId && - this.handleSubAgentContextCompactionItem(childSubAgentCallId, parsed.item, "completed") + parsed.threadId && + this.handleSubAgentContextCompactionItem( + childSubAgentCallId, + parsed.threadId, + parsed.item, + "completed", + ) ) { return true; } @@ -5813,17 +5851,6 @@ export class CodexAppServerAgentSession implements AgentSession { ); } - private upsertSubAgentChildItem(callId: string, itemId: string, item: AgentTimelineItem): void { - const state = this.subAgentCallsByCallId.get(callId); - if (!state) { - return; - } - if (!state.childItems.has(itemId)) { - state.childItemOrder.push(itemId); - } - state.childItems.set(itemId, item); - } - private emitCodexToolTimelineItem( timelineItem: ToolCallTimelineItem, subAgentCallId: string | null, @@ -5833,7 +5860,6 @@ export class CodexAppServerAgentSession implements AgentSession { this.emitEvent({ type: "timeline", provider: CODEX_PROVIDER, item: timelineItem }); return; } - this.upsertSubAgentChildItem(subAgentCallId, timelineItem.callId, timelineItem); const state = this.subAgentCallsByCallId.get(subAgentCallId); if (state) { const targetThreadIds = childThreadId ? [childThreadId] : state.childThreadIds; @@ -5847,26 +5873,15 @@ export class CodexAppServerAgentSession implements AgentSession { ); } - private getSubAgentChildTimeline(state: CodexSubAgentCallState): AgentTimelineItem[] { - return state.childItemOrder - .map((itemId) => state.childItems.get(itemId)) - .filter((item): item is AgentTimelineItem => Boolean(item)); - } - private emitSubAgentActivityUpdate( callId: string, status?: ToolCallTimelineItem["status"], - options?: { reopen?: boolean }, + options?: { reopen?: boolean; subAgentType?: string }, ): void { const state = this.subAgentCallsByCallId.get(callId); if (!state || state.toolCall.detail.type !== "sub_agent") { return; } - const childTimeline = this.getSubAgentChildTimeline(state); - const log = - childTimeline.length > 0 - ? curateAgentActivity(childTimeline, { labelAssistantMessages: true }) - : ""; let resolvedStatus = status ?? state.toolCall.status; if ( status === "running" && @@ -5875,16 +5890,12 @@ export class CodexAppServerAgentSession implements AgentSession { ) { resolvedStatus = state.toolCall.status; } - for (const childThreadId of state.childThreadIds) { - this.emitProviderSubagentUpsert(childThreadId, state, resolvedStatus); - } - const baseToolCall = { - ...state.toolCall, - detail: { - ...state.toolCall.detail, - log, - }, - }; + const baseToolCall = options?.subAgentType + ? { + ...state.toolCall, + detail: { ...state.toolCall.detail, subAgentType: options.subAgentType }, + } + : state.toolCall; const nextToolCall: ToolCallTimelineItem = resolvedStatus === "failed" ? { @@ -5897,10 +5908,14 @@ export class CodexAppServerAgentSession implements AgentSession { status: resolvedStatus, error: null, }; + // The card is a launch marker: the child's activity streams to its own timeline, so the card + // is re-sent only when its status or label changes. + const cardChanged = !isDeepStrictEqual(nextToolCall, state.toolCall); state.toolCall = nextToolCall; - if (state.parentCallId && state.parentCallId !== callId) { - this.upsertSubAgentChildItem(state.parentCallId, state.callId, nextToolCall); - this.emitSubAgentActivityUpdate(state.parentCallId); + for (const childThreadId of state.childThreadIds) { + this.emitProviderSubagentUpsert(childThreadId, state, resolvedStatus); + } + if (!cardChanged || (state.parentCallId && state.parentCallId !== callId)) { return; } this.emitEvent({ type: "timeline", provider: CODEX_PROVIDER, item: nextToolCall }); @@ -6008,7 +6023,6 @@ export class CodexAppServerAgentSession implements AgentSession { ): void { this.applyBufferedDeltaTextToTimelineItem(timelineItem, itemId); if (itemId) { - this.upsertSubAgentChildItem(callId, itemId, timelineItem); this.pendingAgentMessages.delete(itemId); this.pendingReasoning.delete(itemId); this.pendingCommandOutputDeltas.delete(itemId); @@ -6019,19 +6033,29 @@ export class CodexAppServerAgentSession implements AgentSession { private handleSubAgentContextCompactionItem( callId: string, + childThreadId: string, item: { id?: string; type?: string; [key: string]: unknown }, status: "loading" | "completed", ): boolean { if (!this.isContextCompactionItem(item)) { return false; } - if (item.id) { - this.upsertSubAgentChildItem(callId, item.id, { type: "compaction", status }); + if (status === "loading") { + this.pendingChildCompactionThreadIds.add(childThreadId); + this.emitProviderSubagentTimeline(childThreadId, { type: "compaction", status }); + } else { + this.settleChildCompaction(childThreadId); } this.emitSubAgentActivityUpdate(callId); return true; } + private settleChildCompaction(childThreadId: string): void { + if (this.pendingChildCompactionThreadIds.delete(childThreadId)) { + this.emitProviderSubagentTimeline(childThreadId, { type: "compaction", status: "completed" }); + } + } + private shouldSkipCompletedThreadItem( timelineItem: AgentTimelineItem, normalizedItemType: string | undefined, @@ -6062,11 +6086,6 @@ export class CodexAppServerAgentSession implements AgentSession { text: parsed.delta, }); } - this.upsertSubAgentChildItem(subAgentCallId, parsed.itemId, { - type: "assistant_message", - messageId: parsed.itemId, - text, - }); this.emitSubAgentActivityUpdate(subAgentCallId, "running"); return; } @@ -6100,10 +6119,6 @@ export class CodexAppServerAgentSession implements AgentSession { text: parsed.delta, }); } - this.upsertSubAgentChildItem(subAgentCallId, parsed.itemId, { - type: "reasoning", - text: prev.join(""), - }); this.emitSubAgentActivityUpdate(subAgentCallId, "running"); return; } @@ -6153,6 +6168,7 @@ export class CodexAppServerAgentSession implements AgentSession { this.emitSubAgentActivityUpdate(subAgentCallId, "running", { reopen: true }); return; } + this.markCurrentThreadSaved(parsed.threadId); this.currentTurnId = parsed.turnId; const pendingIdentification = this.pendingForegroundTurnIdentification; if ( @@ -6166,11 +6182,23 @@ export class CodexAppServerAgentSession implements AgentSession { this.emitEvent({ type: "turn_started", provider: CODEX_PROVIDER }); } + // Codex has written the rollout by the time it announces a thread's turn, including a + // goal's or a compaction's. From here on the thread can be reported and resumed. + private markCurrentThreadSaved(threadId: string | null): void { + const current = this.currentThreadId; + if (!current || (threadId !== null && threadId !== current)) return; + if (this.savedThreadId === current) return; + this.savedThreadId = current; + this.cachedRuntimeInfo = null; + this.emitEvent({ type: "thread_started", provider: CODEX_PROVIDER, sessionId: current }); + } + private handleTurnCompletedNotification( parsed: Extract, ): void { const subAgentCallId = this.getSubAgentCallIdForThread(parsed.threadId); if (subAgentCallId) { + if (parsed.threadId) this.settleChildCompaction(parsed.threadId); let status: ToolCallTimelineItem["status"] = "completed"; if (parsed.status === "failed") { status = "failed"; @@ -6562,9 +6590,9 @@ export class CodexAppServerAgentSession implements AgentSession { } } - private reconcileAsyncQuestionsAfterRewind(): void { + private reconcileAsyncQuestionsAfterRewind(timeline: readonly PersistedTimelineEntry[]): void { const retainedIds = new Set( - this.persistedHistory.flatMap(({ item }) => + timeline.flatMap(({ item }) => item.type === "tool_call" && item.name === "request_user_input_async" ? [item.callId] : [], ), ); @@ -6578,9 +6606,13 @@ export class CodexAppServerAgentSession implements AgentSession { } } - private handleItemCompletedNotification( + private ownsNotificationTurn(turnId: string | null): boolean { + return !this.closed && this.activeForegroundTurnId === turnId; + } + + private async handleItemCompletedNotification( parsed: Extract, - ): void { + ): Promise { // Codex emits mirrored lifecycle notifications via both `codex/event/item_*` // and canonical `item/*`. Render ordinary items only from the canonical // channel, but accept a legacy-only child announcement so it can establish @@ -6590,20 +6622,23 @@ export class CodexAppServerAgentSession implements AgentSession { } this.receiveAsyncQuestion(parsed.threadId, parsed.item); if (this.isUserMessageItem(parsed.item)) { - this.handleUserMessageItem(parsed); + await this.handleUserMessageItem(parsed); return; } const childSubAgentCallId = this.getSubAgentCallIdForThread(parsed.threadId); if (this.handleCompletedSpecialItem(parsed, childSubAgentCallId)) { return; } - const timelineItem = threadItemToTimeline(parsed.item, { + const foregroundTurnId = this.activeForegroundTurnId; + const timelineItem = await threadItemToTimeline(parsed.item, { includeUserMessage: false, cwd: this.config.cwd ?? null, }); if (!timelineItem) { return; } + const imageItems = await mcpToolResultImagesToTimeline(parsed.item); + if (!this.ownsNotificationTurn(foregroundTurnId)) return; const registeredChildThreadIds = timelineItem.type === "tool_call" ? this.registerSubAgentToolCall({ @@ -6613,12 +6648,11 @@ export class CodexAppServerAgentSession implements AgentSession { parentSubagentId: resolveCodexParentSubagentId(childSubAgentCallId, parsed.threadId), }) : []; - const imageItems = mcpToolResultImagesToTimeline(parsed.item); if (childSubAgentCallId) { this.emitCompletedProviderSubagentItem(parsed, timelineItem); this.handleSubAgentChildItemCompleted(childSubAgentCallId, parsed.item.id, timelineItem); this.emitProviderSubagentTimelineItems(parsed.threadId, imageItems); - this.replayPendingSubAgentNotifications(registeredChildThreadIds); + await this.replayPendingSubAgentNotifications(registeredChildThreadIds); return; } const normalizedItemType = normalizeCodexThreadItemType( @@ -6626,7 +6660,7 @@ export class CodexAppServerAgentSession implements AgentSession { ); const itemId = parsed.item.id; if (this.shouldSkipCompletedThreadItem(timelineItem, normalizedItemType, itemId)) { - this.replayPendingSubAgentNotifications(registeredChildThreadIds); + await this.replayPendingSubAgentNotifications(registeredChildThreadIds); return; } if (this.consumeStreamedTextCompletion(timelineItem, itemId)) { @@ -6637,7 +6671,7 @@ export class CodexAppServerAgentSession implements AgentSession { this.emittedItemCompletedIds.add(itemId); this.emittedItemStartedIds.delete(itemId); } - this.replayPendingSubAgentNotifications(registeredChildThreadIds); + await this.replayPendingSubAgentNotifications(registeredChildThreadIds); return; } this.applyBufferedDeltaTextToTimelineItem(timelineItem, itemId); @@ -6666,7 +6700,7 @@ export class CodexAppServerAgentSession implements AgentSession { this.pendingCommandOutputDeltas.delete(itemId); this.pendingFileChangeOutputDeltas.delete(itemId); } - this.replayPendingSubAgentNotifications(registeredChildThreadIds); + await this.replayPendingSubAgentNotifications(registeredChildThreadIds); } private consumeStreamedTextCompletion( @@ -6738,20 +6772,26 @@ export class CodexAppServerAgentSession implements AgentSession { } } - private handleItemStartedNotification( + private async handleItemStartedNotification( parsed: Extract, - ): void { + ): Promise { if (shouldIgnoreMirroredLifecycleItem(parsed.source, parsed.item)) { return; } if (this.isUserMessageItem(parsed.item)) { - this.handleUserMessageItem(parsed); + await this.handleUserMessageItem(parsed); return; } const childSubAgentCallId = this.getSubAgentCallIdForThread(parsed.threadId); if ( childSubAgentCallId && - this.handleSubAgentContextCompactionItem(childSubAgentCallId, parsed.item, "loading") + parsed.threadId && + this.handleSubAgentContextCompactionItem( + childSubAgentCallId, + parsed.threadId, + parsed.item, + "loading", + ) ) { return; } @@ -6767,7 +6807,7 @@ export class CodexAppServerAgentSession implements AgentSession { if (this.handleRegisteredSubAgentActivity(parsed.item)) { return; } - const timelineItem = threadItemToTimeline(parsed.item, { + const timelineItem = await threadItemToTimeline(parsed.item, { includeUserMessage: false, cwd: this.config.cwd ?? null, }); @@ -6782,11 +6822,8 @@ export class CodexAppServerAgentSession implements AgentSession { }); if (childSubAgentCallId) { this.emitStartedProviderSubagentItem(parsed.threadId, timelineItem); - if (parsed.item.id) { - this.upsertSubAgentChildItem(childSubAgentCallId, parsed.item.id, timelineItem); - } this.emitSubAgentActivityUpdate(childSubAgentCallId, "running"); - this.replayPendingSubAgentNotifications(registeredChildThreadIds); + await this.replayPendingSubAgentNotifications(registeredChildThreadIds); return; } const normalizedItemType = normalizeCodexThreadItemType( @@ -6810,14 +6847,14 @@ export class CodexAppServerAgentSession implements AgentSession { this.pendingCommandOutputDeltas.delete(itemId); this.pendingFileChangeOutputDeltas.delete(itemId); } - this.replayPendingSubAgentNotifications(registeredChildThreadIds); + await this.replayPendingSubAgentNotifications(registeredChildThreadIds); } - private handleUserMessageItem( + private async handleUserMessageItem( parsed: Extract, - ): void { + ): Promise { const itemId = parsed.item.id; - const timelineItem = threadItemToTimeline(parsed.item, { + const timelineItem = await threadItemToTimeline(parsed.item, { includeUserMessage: true, cwd: this.config.cwd ?? null, }); @@ -6838,9 +6875,6 @@ export class CodexAppServerAgentSession implements AgentSession { if (parsed.threadId) { this.emitProviderSubagentTimeline(parsed.threadId, timelineItem); } - if (itemId) { - this.upsertSubAgentChildItem(childSubAgentCallId, itemId, timelineItem); - } this.emitSubAgentActivityUpdate(childSubAgentCallId, "running"); return; } @@ -7383,12 +7417,19 @@ export class CodexAppServerAgentClient implements AgentClient { const listLimit = options?.cwd ? Math.max(scanLimit, 50) : scanLimit; // Codex records each thread under the model provider that ran it and, // unless told otherwise, lists only the provider its own config selects. - // A custom provider runs under its own id, so ask for exactly that one. + // Include legacy custom ids, but keep Codex built-in sessions separate. const customProviderConfig = this.customProviderConfig(); + let modelProviders: string[] | undefined; + if (customProviderConfig && this.deps.customProvider) { + modelProviders = [customProviderConfig.model_provider]; + if (!CODEX_BUILTIN_MODEL_PROVIDER_IDS.has(this.deps.customProvider.id)) { + modelProviders.push(this.deps.customProvider.id); + } + } const allThreads = await readCodexThreadWindow(client, this.logger, { limit: listLimit, cwd: options?.cwd, - ...(customProviderConfig ? { modelProviders: [customProviderConfig.model_provider] } : {}), + ...(modelProviders ? { modelProviders } : {}), }); const threads = filterCodexThreadsByCwd(allThreads, options?.cwd); return threads.slice(0, limit).map((thread) => { diff --git a/packages/server/src/server/agent/providers/codex-custom-provider-import.local.e2e.test.ts b/packages/server/src/server/agent/providers/codex-custom-provider-import.local.e2e.test.ts index ebd8de5ab5..f546dc69e7 100644 --- a/packages/server/src/server/agent/providers/codex-custom-provider-import.local.e2e.test.ts +++ b/packages/server/src/server/agent/providers/codex-custom-provider-import.local.e2e.test.ts @@ -7,7 +7,8 @@ import path from "node:path"; import { afterEach, describe, expect, test } from "vitest"; import { createTestLogger } from "../../../test-utils/test-logger.js"; -import { CodexAppServerAgentClient } from "./codex-app-server-agent.js"; +import { spawnProcess } from "../../../utils/spawn.js"; +import { CodexAppServerAgentClient, CodexAppServerAgentSession } from "./codex-app-server-agent.js"; // Runs the real `codex` binary against a local Responses endpoint standing in // for a custom provider's OPENAI_BASE_URL, so no login is needed. @@ -88,52 +89,106 @@ describe("Codex custom provider import list", () => { for (const cleanup of cleanups.splice(0).toReversed()) await cleanup(); }); - test("lists a custom provider's session under that provider and imports it there", async () => { - const codexHome = mkdtempSync(path.join(os.tmpdir(), "codex-custom-import-home-")); - const cwd = mkdtempSync(path.join(os.tmpdir(), "codex-custom-import-cwd-")); - cleanups.push(() => rmSync(codexHome, { recursive: true, force: true })); - cleanups.push(() => rmSync(cwd, { recursive: true, force: true })); - const { baseUrl, server, requestCount } = await startResponsesEndpoint(); - cleanups.push(() => closeServer(server)); + test.each([ + { providerId: "my-codex", seedLegacy: false, seedBuiltin: false }, + { providerId: "ollama", seedLegacy: false, seedBuiltin: false }, + { providerId: "my-codex", seedLegacy: true, seedBuiltin: false }, + { providerId: "ollama", seedLegacy: false, seedBuiltin: true }, + ])( + "lists and imports sessions for $providerId (legacy: $seedLegacy, native: $seedBuiltin)", + async ({ providerId, seedLegacy, seedBuiltin }) => { + const codexHome = mkdtempSync(path.join(os.tmpdir(), "codex-custom-import-home-")); + const cwd = mkdtempSync(path.join(os.tmpdir(), "codex-custom-import-cwd-")); + cleanups.push(() => rmSync(codexHome, { recursive: true, force: true })); + cleanups.push(() => rmSync(cwd, { recursive: true, force: true })); + const { baseUrl, server, requestCount } = await startResponsesEndpoint(); + cleanups.push(() => closeServer(server)); - const logger = createTestLogger(); - const customCodex = new CodexAppServerAgentClient( - logger, - { env: { CODEX_HOME: codexHome, OPENAI_BASE_URL: baseUrl, OPENAI_API_KEY: "test-key" } }, - { customProvider: { id: "my-codex", label: "My Codex", extends: "codex" } }, - ); - const stockCodex = new CodexAppServerAgentClient(logger, { env: { CODEX_HOME: codexHome } }); + const logger = createTestLogger(); + if (seedLegacy || seedBuiltin) { + // Seed an old custom session or a native built-in session with real Codex. + const environment = { + ...process.env, + CODEX_HOME: codexHome, + CODEX_OSS_BASE_URL: baseUrl, + OPENAI_API_KEY: "test-key", + }; + const legacy = new CodexAppServerAgentSession( + { provider: "codex", cwd, model: "mock-model" }, + null, + logger, + async () => + spawnProcess("codex", ["app-server"], { cwd, env: environment, stdio: "pipe" }), + { + environment, + customCodexConfig: { + model_provider: providerId, + model_providers: seedBuiltin + ? {} + : { + [providerId]: { + name: "My Codex", + base_url: baseUrl, + wire_api: "responses", + env_key: "OPENAI_API_KEY", + requires_openai_auth: false, + }, + }, + }, + }, + ); + try { + await legacy.run("hello from the legacy provider"); + } finally { + await legacy.close(); + } + } + const customCodex = new CodexAppServerAgentClient( + logger, + { env: { CODEX_HOME: codexHome, OPENAI_BASE_URL: baseUrl, OPENAI_API_KEY: "test-key" } }, + { customProvider: { id: providerId, label: "My Codex", extends: "codex" } }, + ); + const stockCodex = new CodexAppServerAgentClient(logger, { env: { CODEX_HOME: codexHome } }); - const session = await customCodex.createSession({ - provider: "codex", - cwd, - model: "mock-model", - }); - try { - await session.run("hello from the custom provider"); - } finally { - await session.close(); - } + const session = await customCodex.createSession({ + provider: "codex", + cwd, + model: "mock-model", + }); + try { + await session.run("hello from the custom provider"); + } finally { + await session.close(); + } - const customSessions = await customCodex.listImportableSessions({ cwd }); - const stockSessions = await stockCodex.listImportableSessions({ cwd }); + const customSessions = await customCodex.listImportableSessions({ cwd }); + const stockSessions = await stockCodex.listImportableSessions({ cwd }); - expect(customSessions.map((entry) => entry.firstPromptPreview)).toEqual([ - "hello from the custom provider", - ]); - expect(stockSessions).toEqual([]); + expect(customSessions.map((entry) => entry.firstPromptPreview).sort()).toEqual( + seedLegacy + ? ["hello from the custom provider", "hello from the legacy provider"] + : ["hello from the custom provider"], + ); + expect(stockSessions).toEqual([]); - const config = { provider: "codex", cwd, model: "mock-model" }; - const imported = await customCodex.importSession( - { providerHandleId: customSessions[0].providerHandleId, cwd }, - { config, storedConfig: config }, - ); - const requestsBeforeImportedTurn = requestCount(); - try { - await imported.session.run("hello again after import"); - } finally { - await imported.session.close(); - } - expect(requestCount()).toBeGreaterThan(requestsBeforeImportedTurn); - }, 120_000); + const config = { provider: "codex", cwd, model: "mock-model" }; + const sessionToImport = seedLegacy + ? customSessions.find( + (entry) => entry.firstPromptPreview === "hello from the legacy provider", + )! + : customSessions[0]; + const imported = await customCodex.importSession( + { providerHandleId: sessionToImport.providerHandleId, cwd }, + { config, storedConfig: config }, + ); + const requestsBeforeImportedTurn = requestCount(); + try { + await imported.session.run("hello again after import"); + } finally { + await imported.session.close(); + } + expect(requestCount()).toBeGreaterThan(requestsBeforeImportedTurn); + }, + 120_000, + ); }); diff --git a/packages/server/src/server/agent/providers/codex-history-string-limit.real.e2e.test.ts b/packages/server/src/server/agent/providers/codex-history-string-limit.real.e2e.test.ts new file mode 100644 index 0000000000..fba51b9e1d --- /dev/null +++ b/packages/server/src/server/agent/providers/codex-history-string-limit.real.e2e.test.ts @@ -0,0 +1,53 @@ +import { execFile } from "node:child_process"; +import { mkdtemp, rm } from "node:fs/promises"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { expect, test } from "vitest"; + +// Regression for #3905. Real Codex, synthetic on-disk history, no model turns. +// Opt in because the oversized cases need approximately 2 GiB of memory and over +// 1 GiB of temporary storage. +const enabled = process.env.PASEO_CODEX_HISTORY_STRING_LIMIT_REPRO === "1"; +const script = fileURLToPath( + new URL("../../../../scripts/reproduce-codex-history-string-limit.mts", import.meta.url), +); + +test.runIf(enabled).each([ + { megabytes: 2, historyMode: "legacy", expected: "History loaded: 3 timeline rows" }, + { megabytes: 520, historyMode: "legacy", expected: "codex migrate-rollouts --apply --thread" }, + { megabytes: 520, historyMode: "paginated", expected: "History loaded: 521 timeline rows" }, +])( + "opening $megabytes MiB of $historyMode Codex history does not crash its hosting process", + async ({ megabytes, historyMode, expected }) => { + const root = await mkdtemp(path.join(process.cwd(), ".codex-history-test-")); + try { + const result = await new Promise<{ code: number; stdout: string; stderr: string }>( + (resolve) => { + const child = execFile( + process.execPath, + ["--import", "tsx", script, String(megabytes), historyMode], + { + cwd: root, + detached: true, + timeout: 120_000, + maxBuffer: 1024 * 1024, + }, + (error, stdout, stderr) => { + try { + if (child.pid) process.kill(-child.pid, "SIGKILL"); + } catch (killError) { + if ((killError as NodeJS.ErrnoException).code !== "ESRCH") throw killError; + } + resolve({ code: error ? Number(error.code ?? 1) : 0, stdout, stderr }); + }, + ); + }, + ); + expect(result.code, result.stderr).toBe(0); + expect(result.stdout).toContain(expected); + } finally { + await rm(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }); + } + }, + 180_000, +); diff --git a/packages/server/src/server/agent/providers/codex/app-server-transport.test.ts b/packages/server/src/server/agent/providers/codex/app-server-transport.test.ts index 3018461ba9..84b82b431b 100644 --- a/packages/server/src/server/agent/providers/codex/app-server-transport.test.ts +++ b/packages/server/src/server/agent/providers/codex/app-server-transport.test.ts @@ -185,14 +185,41 @@ describe("Codex app-server transport", () => { }); describe("Codex stdout byte admission", () => { - test("fails pending requests and the session before joining an oversized line", async () => { + test("an oversized response fails only its own request", async () => { + const child = createCodexAppServerChildProcess(); + const client = new CodexAppServerClient(child, createTestLogger()); + const terminations: Error[] = []; + client.setUnexpectedTerminationHandler((error) => terminations.push(error)); + const oversized = client.request("thread/items/list", {}).catch((error: Error) => error); + const other = client.request("model/list", {}); + const chunk = Buffer.alloc(64 * 1024, "x"); + child.stdout.write('{"id":1,"result":"'); + for (let index = 0; index < 2049; index++) child.stdout.write(chunk); + child.stdout.write('"}\n{"id":2,"result":{"data":[]}}\n'); + + expect(await oversized).toMatchObject({ + name: "CodexAppServerResponseTooLargeError", + method: "thread/items/list", + limitBytes: 128 * 1024 * 1024, + }); + await expect(other).resolves.toEqual({ data: [] }); + const next = client.request("model/list", {}); + child.stdout.write('{"id":3,"result":{"data":["next"]}}\n'); + await expect(next).resolves.toEqual({ data: ["next"] }); + expect(terminations).toEqual([]); + await client.dispose(); + child.stdout.end(); + child.stderr.end(); + }); + + test("an oversized notification fails pending requests and the session", async () => { const child = createCodexAppServerChildProcess(); const client = new CodexAppServerClient(child, createTestLogger()); const terminations: Error[] = []; client.setUnexpectedTerminationHandler((error) => terminations.push(error)); const request = client.request("thread/resume", {}, 1000).catch((error: Error) => error); const chunk = Buffer.alloc(64 * 1024, "x"); - child.stdout.write('{"id":1,"result":"'); + child.stdout.write('{"method":"item/completed","params":"'); for (let index = 0; index < 2048; index++) child.stdout.write(chunk); const error = await request; expect(error).toMatchObject({ diff --git a/packages/server/src/server/agent/providers/codex/app-server-transport.ts b/packages/server/src/server/agent/providers/codex/app-server-transport.ts index dfd4adfac4..5a218e2edb 100644 --- a/packages/server/src/server/agent/providers/codex/app-server-transport.ts +++ b/packages/server/src/server/agent/providers/codex/app-server-transport.ts @@ -33,11 +33,26 @@ interface JsonRpcNotification { } interface PendingRequest { + method: string; resolve: (value: unknown) => void; reject: (error: Error) => void; timer: NodeJS.Timeout; } +/** A response past the provider line cap. Only its request fails; the session stays up. */ +export class CodexAppServerResponseTooLargeError extends Error { + constructor( + readonly method: string, + readonly limitBytes: number, + ) { + super(`Codex app-server response to ${method} exceeds ${limitBytes} bytes`); + this.name = "CodexAppServerResponseTooLargeError"; + } +} + +// Codex serializes a response with `id` first, so its head names the request. +const OVERSIZED_RESPONSE_HEAD = /^\{"id":(\d+),"result":/; + export class CodexAppServerRpcError extends Error { constructor( message: string, @@ -258,7 +273,7 @@ export class CodexAppServerClient { this.pending.delete(id); reject(new Error(`Codex app-server request timed out for ${method}`)); }, timeoutMs); - this.pending.set(id, { resolve, reject, timer }); + this.pending.set(id, { method, resolve, reject, timer }); }); } @@ -304,8 +319,21 @@ export class CodexAppServerClient { } private handleStreamLimit(failure: ProviderStreamLimitError): void { - // A rejected response/notification cannot be replayed safely. Fail the session, + const responseId = OVERSIZED_RESPONSE_HEAD.exec(failure.lineHead)?.[1]; + const pending = responseId === undefined ? undefined : this.pending.get(Number(responseId)); + if (pending) { + clearTimeout(pending.timer); + this.pending.delete(Number(responseId)); + this.logger.warn( + { method: pending.method, limitBytes: failure.limitBytes }, + "Codex app-server response exceeded the line cap", + ); + pending.reject(new CodexAppServerResponseTooLargeError(pending.method, failure.limitBytes)); + return; + } + // A lost notification or server request cannot be replayed. Fail the session, // including live turns with no pending RPC, rather than dropping a stream unit. + this.stdoutLineReader.close(); this.handleUnexpectedTermination(failure); void this.dispose().catch((err) => { this.logger.warn({ err }, "Failed to terminate oversized Codex stdout producer"); diff --git a/packages/server/src/server/agent/providers/codex/rewind.test.ts b/packages/server/src/server/agent/providers/codex/rewind.test.ts index da7fe6a8f5..7a0b2dc0f9 100644 --- a/packages/server/src/server/agent/providers/codex/rewind.test.ts +++ b/packages/server/src/server/agent/providers/codex/rewind.test.ts @@ -108,7 +108,7 @@ describe("Codex Rewind", () => { cwd: "/workspace/project", model: "gpt-5.4-mini", serviceTier: null, - excludeTurns: false, + excludeTurns: true, persistExtendedHistory: true, }, ]); @@ -190,7 +190,7 @@ describe("Codex Rewind", () => { cwd: "/workspace/project", model: "gpt-5.4-mini", serviceTier: null, - excludeTurns: false, + excludeTurns: true, persistExtendedHistory: true, }, ]); diff --git a/packages/server/src/server/agent/providers/codex/rewind.ts b/packages/server/src/server/agent/providers/codex/rewind.ts index 021d57645c..a22931b92b 100644 --- a/packages/server/src/server/agent/providers/codex/rewind.ts +++ b/packages/server/src/server/agent/providers/codex/rewind.ts @@ -8,6 +8,7 @@ import { parseCodexThreadForkResponse, parseCodexThreadRollbackResponse, } from "./app-server-transport.js"; +import { readCodexThreadHistoryMode } from "./thread-history.js"; export interface CodexRewindClient { forkThread?(params: CodexThreadForkParams): Promise; @@ -20,26 +21,6 @@ export interface CodexUserMessageTurnIndex { count(): number; } -type CodexThreadHistoryMode = "legacy" | "paginated"; - -async function readCodexThreadHistoryMode( - client: CodexRewindClient, - threadId: string, -): Promise { - const response = await client.request("thread/read", { threadId, includeTurns: false }); - if (typeof response !== "object" || response === null || !("thread" in response)) { - throw new Error("Codex thread/read did not return thread metadata"); - } - const thread = response.thread; - if (typeof thread !== "object" || thread === null || !("historyMode" in thread)) { - return "legacy"; - } - if (thread.historyMode === "legacy" || thread.historyMode === "paginated") { - return thread.historyMode; - } - throw new Error(`Codex thread/read returned unknown history mode ${String(thread.historyMode)}`); -} - async function forkCodexThread( client: CodexRewindClient, params: CodexThreadForkParams, @@ -95,7 +76,8 @@ export async function revertCodexConversation(input: { model: input.model ?? null, serviceTier: input.serviceTier ?? null, ...(input.config ? { config: input.config } : {}), - excludeTurns: false, + // Paseo re-reads the rewound thread through paged history, not the fork reply. + excludeTurns: true, persistExtendedHistory: true, }; diff --git a/packages/server/src/server/agent/providers/codex/test-utils/fake-app-server.ts b/packages/server/src/server/agent/providers/codex/test-utils/fake-app-server.ts index 226eeb9738..99e6a73050 100644 --- a/packages/server/src/server/agent/providers/codex/test-utils/fake-app-server.ts +++ b/packages/server/src/server/agent/providers/codex/test-utils/fake-app-server.ts @@ -3,6 +3,10 @@ import { EventEmitter } from "node:events"; import { PassThrough } from "node:stream"; import type { AgentSession, AgentStreamEvent } from "../../../agent-sdk-types.js"; +import { CODEX_PROVIDER_LINE_BYTES } from "../app-server-transport.js"; + +/** A handler result that the fake writes as a response line past the provider line cap. */ +export const OVERSIZED_RESPONSE = Symbol("oversized Codex response"); type JsonObject = Record; type FakeCodexAppServerHandler = (params: unknown) => unknown; @@ -229,8 +233,18 @@ export function createFakeCodexAppServer( return; } - Promise.resolve(handler(message.params)) + let response: unknown; + try { + response = handler(message.params); + } catch (error) { + response = Promise.reject(error); + } + Promise.resolve(response) .then((result) => { + if (result === OVERSIZED_RESPONSE) { + writeOversizedResponse(message.id as number); + return undefined; + } const rpcError = toJsonObject(result).__jsonRpcError; if (rpcError) { child.stdout.write(`${JSON.stringify({ id: message.id, error: rpcError })}\n`); @@ -313,6 +327,16 @@ export function createFakeCodexAppServer( }); } + // Codex writes `id` first, then a result past the provider line cap. + function writeOversizedResponse(id: number): void { + child.stdout.write(`{"id":${id},"result":{"data":[{"item":{"text":"`); + const chunk = Buffer.alloc(1024 * 1024, "x"); + for (let written = 0; written <= CODEX_PROVIDER_LINE_BYTES; written += chunk.byteLength) { + child.stdout.write(chunk); + } + child.stdout.write('"}}]}}\n'); + } + function writeNotification(method: string, params: JsonObject): void { child.stdout.write(`${JSON.stringify({ method, params })}\n`); } @@ -696,3 +720,81 @@ export function waitForProviderSubagent( ): Promise { return waitForNextEvent(session, "provider_subagent", (event) => event.event.id === id); } + +export interface FakeCodexHistoryTurn { + id: string; + startedAt?: number; + completedAt?: number; + items: JsonObject[]; +} + +export interface FakeCodexHistoryThread { + /** Omitted on Codex builds older than 0.143, which only have legacy history. */ + historyMode?: "legacy" | "paginated"; + turns: FakeCodexHistoryTurn[]; +} + +export interface FakeCodexHistoryOptions { + /** Any response carrying one of these items is written past the line cap. */ + oversizedItemIds?: string[]; +} + +/** + * Codex's persisted thread history: `thread/read` for metadata and legacy full + * reads, `thread/items/list` for paginated threads. Paginated threads reject + * the full read as Codex 0.145 and 0.146 do. + */ +export function fakeCodexThreadHistory( + threads: Record, + options: FakeCodexHistoryOptions = {}, +): Record { + const oversizedItemIds = new Set(options.oversizedItemIds ?? []); + const isOversized = (items: JsonObject[]) => + items.some((item) => oversizedItemIds.has(String(item.id))); + + function readThread(params: unknown): { id: string; thread: FakeCodexHistoryThread } { + const id = String(toJsonObject(params).threadId); + const thread = threads[id]; + if (!thread) throw new Error(`thread not found: ${id}`); + return { id, thread }; + } + + return { + "thread/read": (params) => { + const { id, thread } = readThread(params); + if (!toJsonObject(params).includeTurns) { + return { + thread: { id, ...(thread.historyMode ? { historyMode: thread.historyMode } : {}) }, + }; + } + if (thread.historyMode === "paginated") { + throw new Error("paginated threads do not support thread/read(includeTurns=true)"); + } + if (isOversized(thread.turns.flatMap((turn) => turn.items))) return OVERSIZED_RESPONSE; + return { thread: { id, turns: thread.turns } }; + }, + "thread/items/list": (params) => { + const { thread } = readThread(params); + if (thread.historyMode !== "paginated") { + throw new Error("thread/items/list is not supported for legacy threads"); + } + const request = toJsonObject(params); + // Codex records each item's own times; the fake gives every item its turn's. + const rows = thread.turns.flatMap((turn) => + turn.items.map((item) => ({ + turnId: turn.id, + item, + startedAtMs: turn.startedAt === undefined ? null : turn.startedAt * 1000, + completedAtMs: turn.completedAt === undefined ? null : turn.completedAt * 1000, + })), + ); + const limit = Math.min(typeof request.limit === "number" ? request.limit : 25, 100); + const start = + typeof request.cursor === "string" ? Number(request.cursor.slice("cursor-".length)) : 0; + const end = Math.min(rows.length, start + limit); + const data = rows.slice(start, end); + if (isOversized(data.map((row) => row.item))) return OVERSIZED_RESPONSE; + return { data, nextCursor: end < rows.length ? `cursor-${end}` : null }; + }, + }; +} diff --git a/packages/server/src/server/agent/providers/codex/thread-history.test.ts b/packages/server/src/server/agent/providers/codex/thread-history.test.ts new file mode 100644 index 0000000000..8d3d8fce3d --- /dev/null +++ b/packages/server/src/server/agent/providers/codex/thread-history.test.ts @@ -0,0 +1,220 @@ +import type { ChildProcessWithoutNullStreams } from "node:child_process"; +import { describe, expect, test } from "vitest"; + +import { createTestLogger } from "../../../../test-utils/test-logger.js"; +import type { AgentSession, AgentStreamEvent } from "../../agent-sdk-types.js"; +import { CodexAppServerAgentClient } from "../codex-app-server-agent.js"; +import { + createFakeCodexAppServer, + type FakeCodexAppServer, + type FakeCodexHistoryOptions, + type FakeCodexHistoryThread, + fakeCodexThreadHistory, +} from "./test-utils/fake-app-server.js"; + +function userItem(id: string, text: string) { + return { type: "userMessage", id, content: [{ type: "text", text }] }; +} + +function agentItem(id: string, text: string) { + return { type: "agentMessage", id, text }; +} + +async function openCodexThread( + thread: FakeCodexHistoryThread, + options?: FakeCodexHistoryOptions, +): Promise<{ appServer: FakeCodexAppServer; session: AgentSession }> { + const appServer = createFakeCodexAppServer( + fakeCodexThreadHistory({ "saved-thread": thread }, options), + ); + const provider = new CodexAppServerAgentClient(createTestLogger()); + const internals = provider as unknown as { + goalsEnabledPromise: Promise | null; + autoReviewEnabledPromise: Promise | null; + spawnAppServer: () => Promise; + }; + internals.goalsEnabledPromise = Promise.resolve(false); + internals.autoReviewEnabledPromise = Promise.resolve(false); + internals.spawnAppServer = async () => appServer.child; + const session = await provider.resumeSession({ sessionId: "saved-thread" }); + return { appServer, session }; +} + +async function readHistory(session: AgentSession): Promise { + const events: AgentStreamEvent[] = []; + for await (const event of session.streamHistory()) events.push(event); + return events; +} + +function timelineItems(events: AgentStreamEvent[]) { + return events.flatMap((event) => (event.type === "timeline" ? [event.item] : [])); +} + +function historyRequests(appServer: FakeCodexAppServer) { + return appServer + .requests() + .filter( + (request) => + request.method === "thread/read" || + request.method === "thread/turns/list" || + request.method === "thread/items/list", + ) + .map((request) => ({ method: request.method, params: request.params })); +} + +describe("Codex thread history", () => { + test("loads a paginated thread through pages", async () => { + const answers = Array.from({ length: 150 }, (_, index) => + agentItem(`agent-${index}`, `Answer ${index}`), + ); + const { appServer, session } = await openCodexThread({ + historyMode: "paginated", + turns: [ + { + id: "turn-1", + startedAt: 1_778_832_941, + completedAt: 1_778_833_000, + items: [userItem("user-1", "First"), ...answers.slice(0, 120)], + }, + { + id: "turn-2", + startedAt: 1_778_833_094, + completedAt: 1_778_833_100, + items: [userItem("user-2", "Second"), ...answers.slice(120)], + }, + ], + }); + try { + const events = await readHistory(session); + + expect(timelineItems(events)).toEqual([ + { type: "user_message", text: "First", messageId: "user-1" }, + ...answers.slice(0, 120).map((answer) => ({ + type: "assistant_message", + text: answer.text, + messageId: answer.id, + })), + { type: "user_message", text: "Second", messageId: "user-2" }, + ...answers.slice(120).map((answer) => ({ + type: "assistant_message", + text: answer.text, + messageId: answer.id, + })), + ]); + const timestamps = events.flatMap((event) => + event.type === "timeline" ? [event.timestamp] : [], + ); + expect(timestamps[0]).toBe("2026-05-15T08:15:41.000Z"); + expect(timestamps[1]).toBe("2026-05-15T08:16:40.000Z"); + expect(timestamps[121]).toBe("2026-05-15T08:18:14.000Z"); + const requests = historyRequests(appServer); + expect(requests).not.toContainEqual( + expect.objectContaining({ params: expect.objectContaining({ includeTurns: true }) }), + ); + const itemPages = requests.filter((request) => request.method === "thread/items/list"); + expect(itemPages.length).toBeGreaterThan(1); + for (const page of itemPages) { + expect(page.params).toMatchObject({ threadId: "saved-thread", sortDirection: "asc" }); + expect((page.params as { limit: number }).limit).toBeLessThanOrEqual(100); + } + } finally { + await session.close(); + } + appServer.assertNoErrors(); + }); + + test("loads a paginated thread whose full read Codex 0.145 rejects", async () => { + const { appServer, session } = await openCodexThread({ + historyMode: "paginated", + turns: [{ id: "turn-1", items: [userItem("user-1", "Hello"), agentItem("agent-1", "Hi")] }], + }); + try { + expect(timelineItems(await readHistory(session))).toEqual([ + { type: "user_message", text: "Hello", messageId: "user-1" }, + { type: "assistant_message", text: "Hi", messageId: "agent-1" }, + ]); + } finally { + await session.close(); + } + appServer.assertNoErrors(); + }); + + test("a page too big to send shows a warning row and stops loading", async () => { + const answers = Array.from({ length: 120 }, (_, index) => + agentItem(`agent-${index}`, `Answer ${index}`), + ); + const { appServer, session } = await openCodexThread( + { + historyMode: "paginated", + turns: [ + { id: "turn-1", items: [userItem("user-1", "One"), ...answers] }, + { id: "turn-2", items: [userItem("user-2", "Two"), agentItem("huge", "never sent")] }, + ], + }, + { oversizedItemIds: ["huge"] }, + ); + const loaded = [ + { type: "user_message", text: "One", messageId: "user-1" }, + ...answers.slice(0, 99).map((answer) => ({ + type: "assistant_message", + text: answer.text, + messageId: answer.id, + })), + { + type: "notification", + level: "warning", + message: "The rest of this Codex thread's history is too large to load.", + }, + ]; + try { + expect(timelineItems(await readHistory(session))).toEqual(loaded); + // The oversized reply failed only its own request; the session still answers. + expect(timelineItems(await readHistory(session))).toEqual(loaded); + } finally { + await session.close(); + } + appServer.assertNoErrors(); + }); + + test("loads a legacy thread that fits in one read", async () => { + const { appServer, session } = await openCodexThread({ + historyMode: "legacy", + turns: [{ id: "turn-1", items: [userItem("user-1", "Hello"), agentItem("agent-1", "Hi")] }], + }); + try { + expect(timelineItems(await readHistory(session))).toEqual([ + { type: "user_message", text: "Hello", messageId: "user-1" }, + { type: "assistant_message", text: "Hi", messageId: "agent-1" }, + ]); + expect(historyRequests(appServer).map((request) => request.method)).not.toContain( + "thread/items/list", + ); + } finally { + await session.close(); + } + appServer.assertNoErrors(); + }); + + test("a legacy thread too big for one read shows the migration command", async () => { + const { appServer, session } = await openCodexThread( + { + historyMode: "legacy", + turns: [{ id: "turn-1", items: [userItem("user-1", "Hello"), agentItem("huge", "x")] }], + }, + { oversizedItemIds: ["huge"] }, + ); + const migrationRow = { + type: "notification", + level: "warning", + message: expect.stringContaining("codex migrate-rollouts --apply --thread saved-thread"), + }; + try { + expect(timelineItems(await readHistory(session))).toEqual([migrationRow]); + // The session stays up for the user to prompt until they archive it to migrate. + expect(timelineItems(await readHistory(session))).toEqual([migrationRow]); + } finally { + await session.close(); + } + appServer.assertNoErrors(); + }); +}); diff --git a/packages/server/src/server/agent/providers/codex/thread-history.ts b/packages/server/src/server/agent/providers/codex/thread-history.ts new file mode 100644 index 0000000000..bf7461deb6 --- /dev/null +++ b/packages/server/src/server/agent/providers/codex/thread-history.ts @@ -0,0 +1,168 @@ +import { z } from "zod"; + +import { CodexAppServerResponseTooLargeError } from "./app-server-transport.js"; + +// Codex clamps history pages to 100 rows. +const PAGE_SIZE = 100; + +export interface CodexThreadHistoryClient { + request(method: string, params?: unknown): Promise; +} + +export type CodexThreadHistoryMode = "legacy" | "paginated"; + +export interface CodexHistoryRow { + item: unknown; + turnId: string | undefined; + /** The item's times on a paginated thread; its turn's on a legacy thread. */ + startedAt: unknown; + completedAt: unknown; +} + +/** A history reply over the line cap; the rows before it were already read. */ +export class CodexThreadHistoryTooLargeError extends Error { + constructor(message: string) { + super(message); + this.name = "CodexThreadHistoryTooLargeError"; + } +} + +const CodexThreadMetadataSchema = z + .object({ + thread: z.object({ historyMode: z.enum(["legacy", "paginated"]).optional() }).passthrough(), + }) + .passthrough(); + +const CodexLegacyThreadReadSchema = z + .object({ + thread: z + .object({ + turns: z + .array( + z + .object({ + id: z.string().optional(), + startedAt: z.unknown().optional(), + completedAt: z.unknown().optional(), + items: z.array(z.unknown()).default([]), + }) + .passthrough(), + ) + .default([]), + }) + .passthrough() + .default({ turns: [] }), + }) + .passthrough(); + +const CodexItemsPageSchema = z + .object({ + data: z.array( + z + .object({ + turnId: z.string(), + item: z.unknown(), + startedAtMs: z.number().nullable().optional(), + completedAtMs: z.number().nullable().optional(), + }) + .passthrough(), + ), + nextCursor: z.string().nullable().optional(), + }) + .passthrough(); + +/** Codex builds before 0.143 report no history mode; their threads are legacy. */ +export async function readCodexThreadHistoryMode( + client: CodexThreadHistoryClient, + threadId: string, +): Promise { + const response = CodexThreadMetadataSchema.parse( + await client.request("thread/read", { threadId, includeTurns: false }), + ); + return response.thread.historyMode ?? "legacy"; +} + +/** + * Reads a thread's persisted items in order. Paginated threads are read in + * pages; a legacy thread arrives in one `thread/read` reply, as Codex offers + * no pages for it. + */ +export async function* readCodexThreadHistory( + client: CodexThreadHistoryClient, + threadId: string, +): AsyncGenerator { + if ((await readCodexThreadHistoryMode(client, threadId)) === "paginated") { + yield* readPaginatedHistory(client, threadId); + } else { + yield* readLegacyHistory(client, threadId); + } +} + +async function* readLegacyHistory( + client: CodexThreadHistoryClient, + threadId: string, +): AsyncGenerator { + const response = await requestHistory( + client, + "thread/read", + { threadId, includeTurns: true }, + `This Codex thread's history is too large to load in one read. ` + + `To move it to paginated history, archive this agent, ` + + `run \`codex migrate-rollouts --apply --thread ${threadId}\` (Codex 0.148 or newer), ` + + `then unarchive the agent.`, + ); + for (const turn of CodexLegacyThreadReadSchema.parse(response).thread.turns) { + for (const item of turn.items) { + yield { item, turnId: turn.id, startedAt: turn.startedAt, completedAt: turn.completedAt }; + } + } +} + +async function* readPaginatedHistory( + client: CodexThreadHistoryClient, + threadId: string, +): AsyncGenerator { + const seenCursors = new Set(); + let cursor: string | undefined; + for (;;) { + const page = CodexItemsPageSchema.parse( + await requestHistory( + client, + "thread/items/list", + { threadId, limit: PAGE_SIZE, sortDirection: "asc", cursor }, + "The rest of this Codex thread's history is too large to load.", + ), + ); + for (const row of page.data) { + yield { + item: row.item, + turnId: row.turnId, + startedAt: row.startedAtMs, + completedAt: row.completedAtMs, + }; + } + if (page.nextCursor == null) return; + // Codex's own client guards against a cursor that does not advance. + if (seenCursors.has(page.nextCursor)) { + throw new Error(`Codex repeated history cursor for thread ${threadId}`); + } + seenCursors.add(page.nextCursor); + cursor = page.nextCursor; + } +} + +async function requestHistory( + client: CodexThreadHistoryClient, + method: string, + params: unknown, + tooLargeMessage: string, +): Promise { + try { + return await client.request(method, params); + } catch (error) { + if (error instanceof CodexAppServerResponseTooLargeError) { + throw new CodexThreadHistoryTooLargeError(tooLargeMessage); + } + throw error; + } +} diff --git a/packages/server/src/server/agent/providers/codex/tool-call-mapper.ts b/packages/server/src/server/agent/providers/codex/tool-call-mapper.ts index 64629bc5d9..4e77dc9367 100644 --- a/packages/server/src/server/agent/providers/codex/tool-call-mapper.ts +++ b/packages/server/src/server/agent/providers/codex/tool-call-mapper.ts @@ -950,6 +950,7 @@ function mapCollabAgentToolCallItem( type: "sub_agent", subAgentType: "Sub-agent", ...(item.prompt ? { description: item.prompt } : {}), + // COMPAT(subagent-log): remove after 2027-04-30. log: "", actions: [], }; @@ -1006,6 +1007,7 @@ function mapSubAgentActivityItem( type: "sub_agent", subAgentType: nativeName, description, + // COMPAT(subagent-log): remove after 2027-04-30. log: "", actions: [], }, diff --git a/packages/server/src/server/agent/providers/jsonl-frame-decoder.test.ts b/packages/server/src/server/agent/providers/jsonl-frame-decoder.test.ts index c1c81bdae8..4844415324 100644 --- a/packages/server/src/server/agent/providers/jsonl-frame-decoder.test.ts +++ b/packages/server/src/server/agent/providers/jsonl-frame-decoder.test.ts @@ -1,5 +1,4 @@ -import { performance } from "node:perf_hooks"; -import { setTimeout as delay } from "node:timers/promises"; +import { measureMainThreadWork } from "../../../test-utils/main-thread-work.js"; import { describe, expect, it } from "vitest"; import { JsonlFrameDecoder, type JsonlFrameProblem } from "./jsonl-frame-decoder.js"; @@ -72,26 +71,15 @@ describe("provider line admission", () => { it("keeps the loop responsive while accumulating a fragmented provider response", async () => { const { decoder, frames, problems } = decoderHarness(); const part = "x".repeat(512); - let last = performance.now(); - let longestGap = 0; - const probe = setInterval(() => { - const now = performance.now(); - longestGap = Math.max(longestGap, now - last); - last = now; - }, 1); - try { - await delay(5); + const { blockingMs } = await measureMainThreadWork("fragmented JSONL main-thread work", () => { decoder.write('{"type":"notice","text":"'); - // 1 MiB is enough to expose the former rescan of every accumulated prefix. + // 1 MiB exposes the former rescan of every accumulated prefix. for (let index = 0; index < 2048; index++) decoder.write(part); decoder.write('"}\n'); - await delay(5); - expect(frames).toEqual([{ type: "notice", text: part.repeat(2048) }]); - expect(problems).toEqual([]); - expect(longestGap).toBeLessThan(50); - } finally { - clearInterval(probe); - } + }); + expect(frames).toEqual([{ type: "notice", text: part.repeat(2048) }]); + expect(problems).toEqual([]); + expect(blockingMs).toBeLessThan(50); }); it("rejects an unterminated over-cap UTF-8 line and stops accepting frames", () => { diff --git a/packages/server/src/server/agent/providers/jsonl-frame-decoder.ts b/packages/server/src/server/agent/providers/jsonl-frame-decoder.ts index 8b1b9767de..ff8fa83489 100644 --- a/packages/server/src/server/agent/providers/jsonl-frame-decoder.ts +++ b/packages/server/src/server/agent/providers/jsonl-frame-decoder.ts @@ -1,10 +1,17 @@ // Provider-process stdout only; these are not app/daemon wire limits. export const JSONL_PROVIDER_LINE_BYTES = 64 * 1024 * 1024; +// Enough of an oversized line to read which response it was, e.g. `{"id":12,"result":`. +const OVERSIZED_LINE_HEAD_BYTES = 64; + export class ProviderStreamLimitError extends Error { readonly code = "PROVIDER_STREAM_LINE_TOO_LARGE"; - constructor(readonly limitBytes: number) { + constructor( + readonly limitBytes: number, + /** The first bytes of the oversized line; the rest is discarded unread. */ + readonly lineHead = "", + ) { super( `Provider stdout line exceeds ${limitBytes} bytes. Start a new thread or reduce the provider response size.`, ); @@ -12,10 +19,26 @@ export class ProviderStreamLimitError extends Error { } } -/** Admits raw UTF-8 bytes before retaining, decoding or joining a complete line. */ +function readLineHead(parts: Buffer[]): string { + const head: Buffer[] = []; + let bytes = 0; + for (const part of parts) { + if (bytes >= OVERSIZED_LINE_HEAD_BYTES) break; + head.push(part.subarray(0, OVERSIZED_LINE_HEAD_BYTES - bytes)); + bytes += head[head.length - 1].byteLength; + } + return Buffer.concat(head).toString("utf8"); +} + +/** + * Admits raw UTF-8 bytes before retaining, decoding or joining a complete line. + * An oversized line is reported with its head and skipped up to its newline; + * the owner closes the reader if the stream cannot continue without it. + */ export class ProviderLineReader { private parts: Buffer[] = []; private bytes = 0; + private skippingOversizedLine = false; private stopped = false; constructor( @@ -31,11 +54,20 @@ export class ProviderLineReader { while (start < buffer.byteLength && !this.stopped) { const newline = buffer.indexOf(10, start); const end = newline === -1 ? buffer.byteLength : newline; + if (this.skippingOversizedLine) { + if (newline === -1) return; + this.skippingOversizedLine = false; + start = newline + 1; + continue; + } const length = end - start; if (length > this.limitBytes - this.bytes) { - this.close(); - this.onLimit(new ProviderStreamLimitError(this.limitBytes)); - return; + const head = readLineHead([...this.parts, buffer.subarray(start, end)]); + this.parts = []; + this.bytes = 0; + this.skippingOversizedLine = true; + this.onLimit(new ProviderStreamLimitError(this.limitBytes, head)); + continue; } if (length) this.parts.push(buffer.subarray(start, end)); this.bytes += length; @@ -150,7 +182,10 @@ export class JsonlFrameDecoder { (line) => { if (line.trim()) this.consumeLine(line); }, - (error) => this.drop("line-too-large", error), + (error) => { + this.lines.close(); + this.drop("line-too-large", error); + }, ); } diff --git a/packages/server/src/server/agent/providers/mock-load-test-agent.ts b/packages/server/src/server/agent/providers/mock-load-test-agent.ts index 7055030dc0..14322c6ccf 100644 --- a/packages/server/src/server/agent/providers/mock-load-test-agent.ts +++ b/packages/server/src/server/agent/providers/mock-load-test-agent.ts @@ -230,6 +230,7 @@ interface LargeAgentStreamPayloadRequest { } interface AgentStreamStressRequest { + tools: boolean; count: number; coalesced: boolean; } @@ -461,7 +462,7 @@ function parseLargeAgentStreamPayloadPrompt( function parseAgentStreamStressPrompt(prompt: AgentPromptInput): AgentStreamStressRequest | null { const text = promptToText(prompt); - const match = /emit\s+(\d+)\s+(coalesced\s+)?agent stream updates/i.exec(text); + const match = /emit\s+(\d+)\s+(coalesced\s+|tool\s+)?agent stream updates/i.exec(text); if (!match) { return null; } @@ -471,7 +472,8 @@ function parseAgentStreamStressPrompt(prompt: AgentPromptInput): AgentStreamStre } return { count: Math.min(count, 5_000), - coalesced: Boolean(match[2]), + coalesced: match[2]?.trim() === "coalesced", + tools: match[2]?.trim() === "tool", }; } @@ -1452,21 +1454,37 @@ export class MockLoadTestAgentSession implements AgentSession { this.emitTurnStarted(turn); for (let index = 0; index < stress.count; index += 1) { - this.emitTimeline( - turn.turnId, - stress.coalesced - ? { - type: "assistant_message", - text: `stress-update-${index}`, - messageId: turn.assistantMessageId, - } - : { - type: "todo", - items: [{ text: `stress-update-${index}`, completed: index % 2 === 0 }], - }, - ); + let item: AgentTimelineItem; + if (stress.tools) { + item = { + type: "tool_call", + callId: `${turn.turnId}:stress:${index}`, + name: "Bash", + status: "completed", + error: null, + detail: { type: "shell", command: `echo stress-${index}`, output: `stress-${index}` }, + }; + } else if (stress.coalesced) { + item = { + type: "assistant_message", + text: `stress-update-${index}`, + messageId: turn.assistantMessageId, + }; + } else { + item = { + type: "todo", + items: [{ text: `stress-update-${index}`, completed: index % 2 === 0 }], + }; + } + this.emitTimeline(turn.turnId, item); } + if (stress.tools) + this.emitTimeline(turn.turnId, { + type: "assistant_message", + text: `Completed ${stress.count} commands`, + messageId: turn.assistantMessageId, + }); this.activeTurn = null; const usage = { inputTokens: 1, diff --git a/packages/server/src/server/agent/providers/omp/agent.test.ts b/packages/server/src/server/agent/providers/omp/agent.test.ts index 7b56c9bdec..15392fc07c 100644 --- a/packages/server/src/server/agent/providers/omp/agent.test.ts +++ b/packages/server/src/server/agent/providers/omp/agent.test.ts @@ -1343,13 +1343,14 @@ describe("OMP agent client and session", () => { expect(omp.runtimeLaunches()).toHaveLength(1); }); - test("closes a replacement process if the session closes during relaunch", async () => { + test("rejects a pending recovery start and closes its processes when the session closes", async () => { const omp = new OmpHarness(); await omp.start(); omp.processExit("OMP RPC process exited with code 1 and signal null"); const turn = omp.startTurnDetached("continue"); + const rejected = expect(turn).rejects.toThrow("closed"); await omp.close(); - await turn; + await rejected; await waitForImmediate(); expect(omp.runtimeSessions().every((session) => session.closed)).toBe(true); }); @@ -1638,3 +1639,93 @@ test.each([ expect(await session.canStopRuntime!()).toBe(expected); }, ); + +test.each([false, true])( + "image prompt keeps OMP's vision capability contract (vision: %s)", + async (vision) => { + const runtime = new FakeOmp(); + runtime.queueSessionSetup((session) => { + session.state = { + ...session.state, + model: { + provider: "test", + id: "image-model", + input: vision ? ["text", "image"] : ["text"], + }, + }; + }); + const client = new OmpAgentClient({ logger: createTestLogger(), runtime }); + const session = await client.createSession({ provider: "omp", cwd: process.cwd() }); + onTestFinished(() => session.close()); + const bytes = Buffer.from("OMP attachment fixture"); + const first = session.startTurn([ + { type: "text", text: "Describe this image." }, + { type: "image", data: bytes.toString("base64"), mimeType: "image/png" }, + ]); + await expect(session.startTurn("overlapping prompt")).rejects.toThrow("already active"); + await first; + const [prompt] = runtime.latestSession().prompts; + expect(prompt.imageCount).toBe(vision ? 1 : 0); + if (vision) expect(prompt.message).toBe("Describe this image."); + else { + const imagePath = prompt.message.match(/\[Image available at: (.+)\]/)?.[1]; + expect(imagePath).toBeTruthy(); + const { readFile, rm } = await import("node:fs/promises"); + expect(await readFile(imagePath!)).toEqual(bytes); + await rm(imagePath!); + } + }, +); + +test("interrupting OMP during image conversion cancels the admitted turn and permits a follow-up", async () => { + const runtime = new FakeOmp(); + const client = new OmpAgentClient({ logger: createTestLogger(), runtime }); + const session = await client.createSession({ provider: "omp", cwd: process.cwd() }); + onTestFinished(() => session.close()); + const events: AgentStreamEvent[] = []; + session.subscribe((event) => events.push(event)); + let admitted = false; + const first = session + .startTurn([ + { + type: "image", + data: Buffer.alloc(16 * 1024 * 1024, 53).toString("base64"), + mimeType: "image/png", + }, + ]) + .then((result) => { + admitted = true; + return result; + }); + await waitForImmediate(); + expect(admitted).toBe(false); + expect(runtime.latestSession().prompts).toHaveLength(0); + await session.interrupt(); + const followup = await session.startTurn("follow-up after image interrupt"); + const original = await first; + expect(events).toContainEqual( + expect.objectContaining({ type: "turn_canceled", turnId: original.turnId }), + ); + expect(followup.turnId).not.toBe(original.turnId); + expect(runtime.latestSession().prompts).toEqual([ + { message: "follow-up after image interrupt", imageCount: 0 }, + ]); +}); + +test("closing OMP during image conversion rejects its pending start", async () => { + const runtime = new FakeOmp(); + const client = new OmpAgentClient({ logger: createTestLogger(), runtime }); + const session = await client.createSession({ provider: "omp", cwd: process.cwd() }); + const first = session.startTurn([ + { + type: "image", + data: Buffer.alloc(16 * 1024 * 1024, 54).toString("base64"), + mimeType: "image/png", + }, + ]); + const rejected = expect(first).rejects.toThrow("closed"); + await waitForImmediate(); + expect(runtime.latestSession().prompts).toHaveLength(0); + await session.close(); + await rejected; +}); diff --git a/packages/server/src/server/agent/providers/omp/agent.ts b/packages/server/src/server/agent/providers/omp/agent.ts index 434a49d89e..c8b44c0bd8 100644 --- a/packages/server/src/server/agent/providers/omp/agent.ts +++ b/packages/server/src/server/agent/providers/omp/agent.ts @@ -69,7 +69,7 @@ import { type OmpRuntimeOptions, } from "./provider-config.js"; export { formatOmpVersionSupport, resolveOmpDiagnosticPaths } from "./provider-config.js"; -import { OmpSubagentCardTracker, type OmpSubagentCardScheduler } from "./subagent-card-tracker.js"; +import { OmpSubagentCardTracker } from "./subagent-card-tracker.js"; import { ompSkillPromptUserText, shouldDisplayOmpCustomMessage } from "./custom-message.js"; import { getUserMessageText } from "./message-history.js"; import { mapOmpSystemNoticeToNotification } from "./system-notice.js"; @@ -130,7 +130,6 @@ export interface OmpAgentClientOptions { logger: Logger; runtimeSettings?: ProviderRuntimeSettings; runtime?: OmpRuntime; - subagentCardScheduler?: OmpSubagentCardScheduler; providerIdleScheduler?: OmpProviderIdleScheduler; noTurnScheduler?: OmpNoTurnScheduler; usagePollScheduler?: OmpUsagePollScheduler; @@ -205,7 +204,6 @@ interface OmpAgentSessionOptions { initialState: OmpSessionState; currentModeId?: string | null; logger: Logger; - subagentCardScheduler?: OmpSubagentCardScheduler; providerIdleScheduler?: OmpProviderIdleScheduler; noTurnScheduler?: OmpNoTurnScheduler; usagePollScheduler?: OmpUsagePollScheduler; @@ -317,9 +315,9 @@ function ompModelSupportsImageInput(model: OmpModel | null | undefined): boolean return model?.input?.includes("image") === true; } -function renderTextOnlyImageHint(image: { data: string; mimeType: string }): string { +async function renderTextOnlyImageHint(image: { data: string; mimeType: string }): Promise { try { - const materialized = materializeProviderImage({ + const materialized = await materializeProviderImage({ data: image.data, mimeType: image.mimeType, }); @@ -329,10 +327,10 @@ function renderTextOnlyImageHint(image: { data: string; mimeType: string }): str } } -function convertPromptInput( +async function convertPromptInput( prompt: AgentPromptInput, options: { model: OmpModel | null | undefined }, -): OmpPromptPayload { +): Promise { if (typeof prompt === "string") { return { text: prompt }; } @@ -355,7 +353,7 @@ function convertPromptInput( mimeType: block.mimeType, }); } else { - textParts.push(renderTextOnlyImageHint(block)); + textParts.push(await renderTextOnlyImageHint(block)); } continue; } @@ -773,9 +771,7 @@ export class OmpAgentSession implements AgentSession { this.logger.debug({ err: error }, "OMP context usage poll failed"); }, }); - this.subagentCardTracker = new OmpSubagentCardTracker({ - scheduler: options.subagentCardScheduler, - }); + this.subagentCardTracker = new OmpSubagentCardTracker(); this.lastKnownThinkingOptionId = normalizeOmpThinkingOption(options.config.thinkingOptionId) ?? this.state.thinkingLevel ?? @@ -868,11 +864,9 @@ export class OmpAgentSession implements AgentSession { throw new Error("An OMP turn is already active"); } - const payload = convertPromptInput(prompt, { model: this.state.model }); const turnId = randomUUID(); this.live = true; this.activeTurnId = turnId; - this.rememberClientMessage(options?.clientMessageId ?? null, payload.text); this.activeAssistantMessageId = null; this.activeTurnTerminalAssistantMessage = null; this.activeTurnStarted = false; @@ -880,6 +874,10 @@ export class OmpAgentSession implements AgentSession { this.activeTurnHasUserMessage = false; this.activePromptRequestId = null; this.clearNoTurnBuffers(); + const payload = await convertPromptInput(prompt, { model: this.state.model }); + if (this.closed) throw new Error("OMP session is closed"); + if (this.activeTurnId !== turnId) return { turnId }; + this.rememberClientMessage(options?.clientMessageId ?? null, payload.text); this.activeNoTurnPromptText = payload.text; this.usagePoller.startTurn(); if (announceTurn) { @@ -946,7 +944,9 @@ export class OmpAgentSession implements AgentSession { ): Promise { if (this.closed || this.activeTurnId !== options.expectedTurnId) return { status: "unavailable" }; - const payload = convertPromptInput(prompt, { model: this.state.model }); + const payload = await convertPromptInput(prompt, { model: this.state.model }); + if (this.closed || this.activeTurnId !== options.expectedTurnId) + return { status: "unavailable" }; if (this.parseSlashCommandInput(payload.text)) return { status: "unavailable" }; const submission = this.rememberClientMessage(options.clientMessageId ?? null, payload.text); try { @@ -2151,8 +2151,7 @@ export class OmpAgentSession implements AgentSession { return mapOmpToolDetail(toolCall, result, { toolCallId, bridgedTool: this.hostTools?.bridge?.tool(toolCall.toolName), - mapSubagentDetail: (detail) => - this.subagentCardTracker.detailFor(toolCallId, detail) ?? detail, + mapSubagentDetail: (detail) => this.subagentCardTracker.detailFor(toolCallId, detail), }); } @@ -2242,7 +2241,6 @@ export class OmpAgentClient implements AgentClient { private readonly logger: Logger; private readonly runtimeSettings?: ProviderRuntimeSettings; - private readonly subagentCardScheduler?: OmpSubagentCardScheduler; private readonly providerIdleScheduler?: OmpProviderIdleScheduler; private readonly noTurnScheduler?: OmpNoTurnScheduler; private readonly usagePollScheduler?: OmpUsagePollScheduler; @@ -2261,7 +2259,6 @@ export class OmpAgentClient implements AgentClient { ); this.logger = options.logger; this.runtimeSettings = runtimeSettings; - this.subagentCardScheduler = options.subagentCardScheduler; this.providerIdleScheduler = options.providerIdleScheduler; this.noTurnScheduler = options.noTurnScheduler; this.usagePollScheduler = options.usagePollScheduler; @@ -2345,7 +2342,6 @@ export class OmpAgentClient implements AgentClient { initialState, currentModeId: launchMode.modeId, logger: this.logger, - subagentCardScheduler: this.subagentCardScheduler, providerIdleScheduler: this.providerIdleScheduler, noTurnScheduler: this.noTurnScheduler, usagePollScheduler: this.usagePollScheduler, @@ -2417,7 +2413,6 @@ export class OmpAgentClient implements AgentClient { initialState, currentModeId: launchMode.modeId, logger: this.logger, - subagentCardScheduler: this.subagentCardScheduler, providerIdleScheduler: this.providerIdleScheduler, noTurnScheduler: this.noTurnScheduler, usagePollScheduler: this.usagePollScheduler, diff --git a/packages/server/src/server/agent/providers/omp/history-mapper.test.ts b/packages/server/src/server/agent/providers/omp/history-mapper.test.ts index 03c0ebe5ae..6d39c21c2d 100644 --- a/packages/server/src/server/agent/providers/omp/history-mapper.test.ts +++ b/packages/server/src/server/agent/providers/omp/history-mapper.test.ts @@ -637,7 +637,7 @@ describe("OMP history mapper", () => { subAgentType: "explore", description: "Inspect files", childSessionId: "/tmp/omp-task/Explore.jsonl", - log: "done\ntranscript: /tmp/omp-task/Explore.jsonl", + log: "", }, error: null, }, diff --git a/packages/server/src/server/agent/providers/omp/history.e2e.test.ts b/packages/server/src/server/agent/providers/omp/history.e2e.test.ts index 77521a9687..f0a00d5a0d 100644 --- a/packages/server/src/server/agent/providers/omp/history.e2e.test.ts +++ b/packages/server/src/server/agent/providers/omp/history.e2e.test.ts @@ -1,3 +1,4 @@ +import { measureMainThreadWork } from "../../../../test-utils/main-thread-work.js"; import { BUILTIN_PROVIDER_IDS } from "@getpaseo/protocol/provider-manifest"; import { mkdtemp, open, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; @@ -50,51 +51,45 @@ test("replays selected OMP history without blocking the event loop", async () => } finally { await file.close(); } - let last = performance.now(); - let longestGap = 0; - const probe = setInterval(() => { - const now = performance.now(); - longestGap = Math.max(longestGap, now - last); - last = now; - }, 5); - try { - const replayState = { finished: false }; - let repliesDuringReplay = 0; - const replay = readActiveOmpEntryChain(sessionFile, "row-0").finally(() => { - replayState.finished = true; - }); - // A real WebSocket RPC served by the isolated daemon on the same event loop. - const requests = (async () => { - while (!replayState.finished) { - await client.getDaemonStatus(); - if (!replayState.finished) repliesDuringReplay++; - await delay(10); - } - })(); - const [entries] = await Promise.all([replay, requests]); - await delay(10); - console.log( - JSON.stringify({ - bytes, - count, - longestGap, - repliesDuringReplay, - generationAndLoadMs: performance.now() - started, - }), - ); - expect(entries).toEqual([ - { - type: "message", - id: "row-0", - parentId: null, - message: { role: "user", content: text }, - }, - ]); - expect(longestGap).toBeLessThan(50); - expect(repliesDuringReplay).toBeGreaterThan(0); - } finally { - clearInterval(probe); - } + let repliesDuringReplay = 0; + const { result: replayedEntries, blockingMs } = await measureMainThreadWork( + "OMP history main-thread work", + async () => { + const replayState = { finished: false }; + const replay = readActiveOmpEntryChain(sessionFile, "row-0").finally(() => { + replayState.finished = true; + }); + // A real WebSocket RPC served by the isolated daemon on the same event loop. + const requests = (async () => { + while (!replayState.finished) { + await client.getDaemonStatus(); + if (!replayState.finished) repliesDuringReplay++; + await delay(10); + } + })(); + const [entries] = await Promise.all([replay, requests]); + return entries; + }, + ); + console.log( + JSON.stringify({ + bytes, + count, + blockingMs, + repliesDuringReplay, + generationAndLoadMs: performance.now() - started, + }), + ); + expect(replayedEntries).toEqual([ + { + type: "message", + id: "row-0", + parentId: null, + message: { role: "user", content: text }, + }, + ]); + expect(blockingMs).toBeLessThan(50); + expect(repliesDuringReplay).toBeGreaterThan(0); } finally { await client.close().finally(() => daemon.close()); } diff --git a/packages/server/src/server/agent/providers/omp/subagent-card-tracker.test.ts b/packages/server/src/server/agent/providers/omp/subagent-card-tracker.test.ts index 5164097661..6819292d33 100644 --- a/packages/server/src/server/agent/providers/omp/subagent-card-tracker.test.ts +++ b/packages/server/src/server/agent/providers/omp/subagent-card-tracker.test.ts @@ -1,6 +1,6 @@ import { describe, expect, test } from "vitest"; -import { OmpSubagentCardTracker, type OmpSubagentCardScheduler } from "./subagent-card-tracker.js"; +import { OmpSubagentCardTracker } from "./subagent-card-tracker.js"; import type { OmpSubagentLifecyclePayload, OmpSubagentProgressPayload } from "./rpc-types.js"; const PARENT_TOOL_CALL_ID = "task-1"; @@ -59,184 +59,84 @@ const PROGRESS: OmpSubagentProgressPayload[] = [ }, ]; -class ManualScheduler implements OmpSubagentCardScheduler { - private currentMs = 0; - private nextId = 1; - private readonly timers = new Map void }>(); - - now(): number { - return this.currentMs; - } - - setTimeout(callback: () => void, delayMs: number) { - const id = this.nextId; - this.nextId += 1; - this.timers.set(id, { dueMs: this.currentMs + delayMs, callback }); - return { token: id }; - } - - clearTimeout(timer: { token: unknown }): void { - if (typeof timer.token === "number") { - this.timers.delete(timer.token); - } - } - - advance(ms: number): void { - this.currentMs += ms; - const dueTimers = [...this.timers.entries()] - .filter(([, timer]) => timer.dueMs <= this.currentMs) - .sort((left, right) => left[1].dueMs - right[1].dueMs); - for (const [id, timer] of dueTimers) { - if (this.timers.delete(id)) { - timer.callback(); - } - } - } -} - describe("OmpSubagentCardTracker", () => { - test("folds lifecycle and progress into one throttled sub-agent detail", () => { - const scheduler = new ManualScheduler(); + test("keeps the card a launch marker while the child runs", () => { const emitted: string[] = []; - const tracker = new OmpSubagentCardTracker({ - scheduler, - emitToolCall: (toolCallId) => { - emitted.push(toolCallId); - return true; - }, - }); - tracker.handleLifecycle(LIFECYCLE); + const emit = (toolCallId: string) => { + emitted.push(toolCallId); + return true; + }; + const tracker = new OmpSubagentCardTracker(); + tracker.handleLifecycle(LIFECYCLE, emit); for (const payload of PROGRESS) { - tracker.handleProgress(payload); + tracker.handleProgress(payload, emit); } expect(emitted).toEqual([PARENT_TOOL_CALL_ID]); - const detailBeforeTrailing = tracker.detailFor(PARENT_TOOL_CALL_ID, { - type: "sub_agent", - subAgentType: "task", - description: "Task arg description wins", - log: "", - }); - expect(detailBeforeTrailing).toEqual({ - type: "sub_agent", - subAgentType: "task", - description: "Task arg description wins", - childSessionId: SESSION_FILE, - log: [ - "EchoSubagent started", - "[bash] echo subagent-hi", - "[yield]", - "EchoSubagent completed", - ].join("\n"), - }); - - scheduler.advance(500); - - expect(emitted).toEqual([PARENT_TOOL_CALL_ID, PARENT_TOOL_CALL_ID]); - }); - - test("aggregates batch progress streams into one index-prefixed log", () => { - const scheduler = new ManualScheduler(); - const emitted: string[] = []; - const tracker = new OmpSubagentCardTracker({ - scheduler, - emitToolCall: (toolCallId) => { - emitted.push(toolCallId); - return true; - }, - }); - - tracker.handleLifecycle({ - id: "Explore", - agent: "task", - description: "Inspect files", - status: "started", - sessionFile: "/tmp/one.jsonl", - parentToolCallId: "task.batch-1", - index: 0, - }); - scheduler.advance(600); - tracker.handleProgress({ - index: 5, - agent: "task", - task: "Run tests", - parentToolCallId: "task.batch-1", - progress: { - id: "Test", - status: "running", - description: "Run tests", - recentTools: [{ tool: "bash", args: "npm test", endMs: 10 }], - }, - sessionFile: "/tmp/two.jsonl", - }); - - expect(emitted).toEqual(["task.batch-1", "task.batch-1"]); expect( - tracker.detailFor("task.batch-1", { + tracker.detailFor(PARENT_TOOL_CALL_ID, { type: "sub_agent", - subAgentType: "batch", - actions: [], + subAgentType: "task", + description: "Task arg description wins", log: "", }), ).toEqual({ type: "sub_agent", - subAgentType: "batch", - description: "Inspect files", - childSessionId: "/tmp/one.jsonl", - log: "[1/6] Explore started\n[6/6] [bash] npm test", - actions: [], + subAgentType: "task", + description: "Task arg description wins", + childSessionId: SESSION_FILE, + log: "", }); }); - test("keeps dirty trailing state available for final detail and cancels it on cleanup", () => { - const scheduler = new ManualScheduler(); + test("re-emits the card when a later event names the child", () => { const emitted: string[] = []; - const tracker = new OmpSubagentCardTracker({ - scheduler, - emitToolCall: (toolCallId) => { - emitted.push(toolCallId); - return true; + const emit = (toolCallId: string) => { + emitted.push(toolCallId); + return true; + }; + const tracker = new OmpSubagentCardTracker(); + tracker.handleLifecycle({ ...LIFECYCLE, description: undefined, sessionFile: undefined }, emit); + tracker.handleProgress(PROGRESS[0], emit); + + expect(emitted).toEqual([PARENT_TOOL_CALL_ID, PARENT_TOOL_CALL_ID]); + expect(tracker.detailFor(PARENT_TOOL_CALL_ID, { type: "sub_agent", log: "" })).toEqual({ + type: "sub_agent", + childSessionId: SESSION_FILE, + log: "", + }); + + tracker.delete(PARENT_TOOL_CALL_ID); + expect(tracker.detailFor(PARENT_TOOL_CALL_ID, { type: "sub_agent", log: "" })).toEqual({ + type: "sub_agent", + log: "", + }); + }); + test("leaves the card alone when a later child of the same task starts", () => { + const emitted: string[] = []; + const emit = (toolCallId: string) => { + emitted.push(toolCallId); + return true; + }; + const tracker = new OmpSubagentCardTracker(); + tracker.handleLifecycle(LIFECYCLE, emit); + tracker.handleLifecycle( + { + ...LIFECYCLE, + id: "Second", + index: 1, + description: "Second child", + sessionFile: "/s.jsonl", }, + emit, + ); + + expect(emitted).toEqual([PARENT_TOOL_CALL_ID]); + expect(tracker.detailFor(PARENT_TOOL_CALL_ID, { type: "sub_agent", log: "" })).toEqual({ + type: "sub_agent", + description: "Run echo in subagent", + childSessionId: SESSION_FILE, + log: "", }); - - tracker.handleLifecycle({ - id: "Explore", - agent: "task", - description: "Inspect files", - status: "started", - parentToolCallId: "task-1", - index: 0, - }); - scheduler.advance(100); - tracker.handleProgress({ - index: 0, - agent: "task", - task: "Inspect files", - parentToolCallId: "task-1", - progress: { - id: "Explore", - status: "running", - recentOutput: ["found target file"], - }, - }); - - expect(emitted).toEqual(["task-1"]); - expect( - tracker.detailFor("task-1", { - type: "sub_agent", - log: "", - }).log, - ).toBe("Explore started\nfound target file"); - - tracker.delete("task-1"); - scheduler.advance(500); - - expect(emitted).toEqual(["task-1"]); - expect( - tracker.detailFor("task-1", { - type: "sub_agent", - log: "static", - }).log, - ).toBe("static"); }); }); diff --git a/packages/server/src/server/agent/providers/omp/subagent-card-tracker.ts b/packages/server/src/server/agent/providers/omp/subagent-card-tracker.ts index 7034c4c506..60ad291058 100644 --- a/packages/server/src/server/agent/providers/omp/subagent-card-tracker.ts +++ b/packages/server/src/server/agent/providers/omp/subagent-card-tracker.ts @@ -1,361 +1,106 @@ import type { ToolCallDetail } from "../../agent-sdk-types.js"; import type { OmpSubagentLifecyclePayload, OmpSubagentProgressPayload } from "./rpc-types.js"; -export interface OmpSubagentCardTimer { - readonly token: unknown; -} - -export interface OmpSubagentCardScheduler { - now(): number; - setTimeout(callback: () => void, delayMs: number): OmpSubagentCardTimer; - clearTimeout(timer: OmpSubagentCardTimer): void; -} - -export interface OmpSubagentCardTrackerOptions { - scheduler?: OmpSubagentCardScheduler; - emitToolCall?: (toolCallId: string) => boolean; -} - -interface OmpSubagentLogLine { - key: string; - text: string; -} - -interface OmpSubagentCardItem { +interface OmpSubagentCardChild { index: number; description?: string; - agent?: string; - status?: "pending" | "running" | "completed" | "failed" | "aborted"; childSessionId?: string; - lines: OmpSubagentLogLine[]; - lineKeys: Set; -} - -interface OmpSubagentCardState { - items: Map; - emitToolCall: (toolCallId: string) => boolean; - lastEmitMs: number | null; - trailingTimer: OmpSubagentCardTimer | null; - dirty: boolean; -} - -const MAX_LOG_LINES_PER_ITEM = 200; -const MAX_LOG_LINE_CHARS = 240; -const THROTTLE_INTERVAL_MS = 500; - -export function createOmpSubagentCardScheduler(): OmpSubagentCardScheduler { - return { - now: () => Date.now(), - setTimeout: (callback, delayMs) => ({ token: setTimeout(callback, delayMs) }), - clearTimeout: (timer) => { - clearTimeout(timer.token as ReturnType); - }, - }; } +/** + * Fills a task card's description and child session from OMP's sub-agent events. The card is a + * launch marker that names the task's first child; the children's activity belongs to their own + * timelines. + */ export class OmpSubagentCardTracker { - private readonly scheduler: OmpSubagentCardScheduler; - private readonly emitToolCall: (toolCallId: string) => boolean; - private readonly states = new Map(); - - constructor(options: OmpSubagentCardTrackerOptions) { - this.scheduler = options.scheduler ?? createOmpSubagentCardScheduler(); - this.emitToolCall = options.emitToolCall ?? (() => false); - } + private readonly firstChildren = new Map(); handleLifecycle( payload: OmpSubagentLifecyclePayload, - emitToolCall: (toolCallId: string) => boolean = this.emitToolCall, + emitToolCall: (toolCallId: string) => boolean, ): void { - const parentToolCallId = readTrimmedString(payload.parentToolCallId); - if (!parentToolCallId) { - return; - } - this.stateFor(parentToolCallId).emitToolCall = emitToolCall; - const item = this.upsertItem(parentToolCallId, { - index: payload.index, - agent: payload.agent, - description: payload.description, - status: payload.status === "started" ? "running" : payload.status, - childSessionId: payload.sessionFile, - }); - this.appendLine( - item, - `lifecycle:${payload.status}:${payload.id}`, - `${payload.id} ${payload.status}`, + this.update( + payload.parentToolCallId, + { + index: payload.index, + description: payload.description, + childSessionId: payload.sessionFile, + }, + emitToolCall, ); - this.requestEmit(parentToolCallId); } handleProgress( payload: OmpSubagentProgressPayload, - emitToolCall: (toolCallId: string) => boolean = this.emitToolCall, + emitToolCall: (toolCallId: string) => boolean, ): void { - const parentToolCallId = readTrimmedString(payload.parentToolCallId); - if (!parentToolCallId) { - return; - } - this.stateFor(parentToolCallId).emitToolCall = emitToolCall; - const item = this.upsertItem(parentToolCallId, { - index: payload.index, - agent: payload.agent, - description: payload.progress.description, - status: payload.progress.status, - childSessionId: payload.sessionFile, - }); - - const currentToolLine = summarizeTool(readRecord(payload.progress.currentTool)); - if (currentToolLine) { - this.appendLine(item, `current:${currentToolLine.key}`, currentToolLine.text); - } - - for (const tool of readRecordArray(payload.progress.recentTools)) { - const line = summarizeTool(tool); - if (line) { - this.appendLine(item, `tool:${line.key}`, line.text); - } - } - - for (const output of readOutputLines(payload.progress.recentOutput)) { - this.appendLine(item, `output:${output}`, output); - } - - if (payload.progress.status !== "running") { - this.appendLine( - item, - `status:${payload.progress.status}:${payload.progress.id}`, - `${payload.progress.id} ${payload.progress.status}`, - ); - } - - this.requestEmit(parentToolCallId); + this.update( + payload.parentToolCallId, + { + index: payload.index, + description: payload.progress.description, + childSessionId: payload.sessionFile, + }, + emitToolCall, + ); } detailFor(toolCallId: string, baseDetail: ToolCallDetail): ToolCallDetail { if (baseDetail.type !== "sub_agent") { return baseDetail; } - const state = this.states.get(toolCallId); - if (!state) { + const first = this.firstChildren.get(toolCallId); + if (!first) { return baseDetail; } - const items = [...state.items.values()].sort((left, right) => left.index - right.index); - const firstItem = items[0]; - if (!firstItem) { - return baseDetail; - } - - const detail: ToolCallDetail = { - type: "sub_agent", - ...(baseDetail.subAgentType ? { subAgentType: baseDetail.subAgentType } : {}), - ...((baseDetail.description ?? firstItem.description) - ? { description: baseDetail.description ?? firstItem.description } - : {}), - ...((firstItem.childSessionId ?? baseDetail.childSessionId) - ? { childSessionId: firstItem.childSessionId ?? baseDetail.childSessionId } - : {}), - log: buildLog(items, baseDetail.log), + const description = baseDetail.description ?? first.description; + const childSessionId = first.childSessionId ?? baseDetail.childSessionId; + return { + ...baseDetail, + ...(description ? { description } : {}), + ...(childSessionId ? { childSessionId } : {}), }; - return baseDetail.actions ? { ...detail, actions: baseDetail.actions } : detail; - } - - flush(toolCallId: string): void { - const state = this.states.get(toolCallId); - if (!state || !state.dirty) { - return; - } - this.emitNow(toolCallId, state); } delete(toolCallId: string): void { - const state = this.states.get(toolCallId); - if (state?.trailingTimer) { - this.scheduler.clearTimeout(state.trailingTimer); - } - this.states.delete(toolCallId); + this.firstChildren.delete(toolCallId); } clear(): void { - for (const toolCallId of this.states.keys()) { - this.delete(toolCallId); - } + this.firstChildren.clear(); } - private upsertItem( - parentToolCallId: string, - input: { - index: number; - agent?: string; - status?: "pending" | "running" | "completed" | "failed" | "aborted"; - description?: string; - childSessionId?: string; - }, - ): OmpSubagentCardItem { - const state = this.stateFor(parentToolCallId); - const existing = state.items.get(input.index); - if (existing) { - existing.agent = readTrimmedString(input.agent) ?? existing.agent; - existing.status = input.status ?? existing.status; - existing.description = readTrimmedString(input.description) ?? existing.description; - existing.childSessionId = readTrimmedString(input.childSessionId) ?? existing.childSessionId; - return existing; + private update( + parentToolCallId: string | undefined, + input: { index: number; description?: string; childSessionId?: string }, + emitToolCall: (toolCallId: string) => boolean, + ): void { + const toolCallId = readTrimmedString(parentToolCallId); + if (!toolCallId) { + return; } - - const item: OmpSubagentCardItem = { + const first = this.firstChildren.get(toolCallId); + if (first && input.index > first.index) { + return; + } + const existing = first?.index === input.index ? first : undefined; + const next: OmpSubagentCardChild = { index: input.index, - lines: [], - lineKeys: new Set(), - ...(readTrimmedString(input.agent) ? { agent: readTrimmedString(input.agent) } : {}), - ...(input.status ? { status: input.status } : {}), - ...(readTrimmedString(input.description) - ? { description: readTrimmedString(input.description) } - : {}), - ...(readTrimmedString(input.childSessionId) - ? { childSessionId: readTrimmedString(input.childSessionId) } - : {}), + description: readTrimmedString(input.description) ?? existing?.description, + childSessionId: readTrimmedString(input.childSessionId) ?? existing?.childSessionId, }; - state.items.set(input.index, item); - return item; - } - - private stateFor(parentToolCallId: string): OmpSubagentCardState { - const existing = this.states.get(parentToolCallId); - if (existing) { - return existing; - } - const state: OmpSubagentCardState = { - items: new Map(), - emitToolCall: this.emitToolCall, - lastEmitMs: null, - trailingTimer: null, - dirty: false, - }; - this.states.set(parentToolCallId, state); - return state; - } - - private appendLine(item: OmpSubagentCardItem, key: string, text: string): void { - const normalizedText = normalizeLine(text); - if (!normalizedText || item.lineKeys.has(key)) { + if ( + existing && + existing.description === next.description && + existing.childSessionId === next.childSessionId + ) { return; } - item.lines.push({ key, text: normalizedText }); - item.lineKeys.add(key); - while (item.lines.length > MAX_LOG_LINES_PER_ITEM) { - const removed = item.lines.shift(); - if (removed) { - item.lineKeys.delete(removed.key); - } - } + this.firstChildren.set(toolCallId, next); + emitToolCall(toolCallId); } - - private requestEmit(toolCallId: string): void { - const state = this.stateFor(toolCallId); - const now = this.scheduler.now(); - const elapsedMs = state.lastEmitMs === null ? THROTTLE_INTERVAL_MS : now - state.lastEmitMs; - if (elapsedMs >= THROTTLE_INTERVAL_MS) { - this.emitNow(toolCallId, state); - return; - } - - state.dirty = true; - if (state.trailingTimer) { - return; - } - state.trailingTimer = this.scheduler.setTimeout(() => { - state.trailingTimer = null; - if (state.dirty) { - this.emitNow(toolCallId, state); - } - }, THROTTLE_INTERVAL_MS - elapsedMs); - } - - private emitNow(toolCallId: string, state: OmpSubagentCardState): void { - if (state.trailingTimer) { - this.scheduler.clearTimeout(state.trailingTimer); - state.trailingTimer = null; - } - state.dirty = false; - state.lastEmitMs = this.scheduler.now(); - state.emitToolCall(toolCallId); - } -} - -function buildLog(items: OmpSubagentCardItem[], fallback: string): string { - const itemCount = Math.max(...items.map((item) => item.index)) + 1; - const lines = items.flatMap((item) => { - const prefix = itemCount > 1 ? `[${item.index + 1}/${itemCount}] ` : ""; - return item.lines.map((line) => `${prefix}${line.text}`); - }); - return lines.length > 0 ? lines.join("\n") : fallback; -} - -function summarizeTool(tool: Record | null): OmpSubagentLogLine | null { - if (!tool) { - return null; - } - const toolName = readTrimmedString(tool.tool) ?? readTrimmedString(tool.name); - if (!toolName) { - return null; - } - const args = readTrimmedString(tool.args) ?? summarizeUnknown(tool.input); - const endMs = typeof tool.endMs === "number" ? `:${tool.endMs}` : ""; - return { - key: `${toolName}:${args ?? ""}${endMs}`, - text: args ? `[${toolName}] ${args}` : `[${toolName}]`, - }; -} - -function readOutputLines(value: unknown): string[] { - if (!Array.isArray(value)) { - return []; - } - return value.flatMap((item) => { - const text = - readTrimmedString(item) ?? - (isRecord(item) - ? (readTrimmedString(item.text) ?? - readTrimmedString(item.output) ?? - readTrimmedString(item.content)) - : undefined); - return text ? [text] : []; - }); -} - -function readRecord(value: unknown): Record | null { - return isRecord(value) ? value : null; -} - -function readRecordArray(value: unknown): Record[] { - return Array.isArray(value) ? value.filter(isRecord) : []; -} - -function summarizeUnknown(value: unknown): string | undefined { - if (value === undefined || value === null) { - return undefined; - } - if (typeof value === "string") { - return readTrimmedString(value); - } - const json = JSON.stringify(value); - return typeof json === "string" ? normalizeLine(json) : undefined; -} - -function normalizeLine(value: string): string | undefined { - const normalized = value.trim().replace(/\s+/g, " "); - if (!normalized) { - return undefined; - } - if (normalized.length <= MAX_LOG_LINE_CHARS) { - return normalized; - } - return `${normalized.slice(0, MAX_LOG_LINE_CHARS)}...`; } function readTrimmedString(value: unknown): string | undefined { return typeof value === "string" && value.trim().length > 0 ? value.trim() : undefined; } - -function isRecord(value: unknown): value is Record { - return typeof value === "object" && value !== null && !Array.isArray(value); -} diff --git a/packages/server/src/server/agent/providers/omp/tool-call-mapper.test.ts b/packages/server/src/server/agent/providers/omp/tool-call-mapper.test.ts index ae4c0d0d77..cc13f9001f 100644 --- a/packages/server/src/server/agent/providers/omp/tool-call-mapper.test.ts +++ b/packages/server/src/server/agent/providers/omp/tool-call-mapper.test.ts @@ -85,7 +85,7 @@ describe("OMP tool call mapper", () => { expect(mapOmpToolDetail(parseToolArgs("todo", { op: "view" }), null)).toBeNull(); }); - test("uses task result text and transcript path as the best static replay detail", () => { + test("takes the child session from the task transcript path", () => { expect( mapOmpToolDetail( parseToolArgs("task", { @@ -106,7 +106,7 @@ describe("OMP tool call mapper", () => { subAgentType: "explore", description: "Inspect the target files", childSessionId: "/tmp/omp-task-static/Explore.jsonl", - log: "done\ntranscript: /tmp/omp-task-static/Explore.jsonl", + log: "", }); }); diff --git a/packages/server/src/server/agent/providers/omp/tool-call-mapper.ts b/packages/server/src/server/agent/providers/omp/tool-call-mapper.ts index 86b1ee53ef..500123758a 100644 --- a/packages/server/src/server/agent/providers/omp/tool-call-mapper.ts +++ b/packages/server/src/server/agent/providers/omp/tool-call-mapper.ts @@ -179,7 +179,6 @@ const OPAQUE_TEXT_TOOLS = new Set([ function mapOmpTaskDetail(args: unknown, result: OmpToolResult): ToolCallDetail { const argRecord = isRecord(args) ? args : {}; const firstTask = Array.isArray(argRecord.tasks) ? argRecord.tasks.find(isRecord) : undefined; - const resultText = extractTextFromToolResult(result); const childSessionId = readChildSessionId(result); return { type: "sub_agent", @@ -200,7 +199,8 @@ function mapOmpTaskDetail(args: unknown, result: OmpToolResult): ToolCallDetail argRecord.assignment, ), ...(childSessionId ? { childSessionId } : {}), - log: resultText?.trim() ?? "", + // COMPAT(subagent-log): remove after 2027-04-30. + log: "", }; } diff --git a/packages/server/src/server/agent/providers/opencode-agent.ts b/packages/server/src/server/agent/providers/opencode-agent.ts index 81288f3e4f..6fef290d91 100644 --- a/packages/server/src/server/agent/providers/opencode-agent.ts +++ b/packages/server/src/server/agent/providers/opencode-agent.ts @@ -4846,15 +4846,6 @@ class OpenCodeAgentSession implements AgentSession { ...item, status: "failed", error, - detail: - item.detail.type === "sub_agent" - ? { - ...item.detail, - log: [item.detail.log, error.message] - .filter((entry) => entry.trim().length > 0) - .join("\n"), - } - : item.detail, }, }, turnId, diff --git a/packages/server/src/server/agent/providers/opencode-bridge-adapter.test.ts b/packages/server/src/server/agent/providers/opencode-bridge-adapter.test.ts index 133ac3c992..6cb15ccb6d 100644 --- a/packages/server/src/server/agent/providers/opencode-bridge-adapter.test.ts +++ b/packages/server/src/server/agent/providers/opencode-bridge-adapter.test.ts @@ -80,8 +80,12 @@ describe("OpenCode bridge adapter", () => { await rm(paseoHome, { recursive: true, force: true }); }); const runtime = new TestOpenCodeHarness(); - runtime.enqueueClient(new TestOpenCodeClient()); - runtime.enqueueClient(new TestOpenCodeClient()); + const envClient = new TestOpenCodeClient(); + const mcpClient = new TestOpenCodeClient(); + envClient.sessionCreateResponse = { data: { id: "ses_env" } }; + mcpClient.sessionCreateResponse = { data: { id: "ses_mcp" } }; + runtime.enqueueClient(envClient); + runtime.enqueueClient(mcpClient); const client = new OpenCodeAgentClient(createTestLogger(), undefined, { serverManager: runtime, createClient: runtime.createClient, @@ -102,6 +106,12 @@ describe("OpenCode bridge adapter", () => { ); expect(runtime.acquisitions.map(({ kind }) => kind)).toEqual(["dedicated", "dedicated"]); + await expect(readBridgeContext(bridge, "ses_env")).resolves.toEqual({ + env: { PASEO_AGENT_ID: "one", CUSTOM_TOKEN: "secret" }, + }); + await expect(readBridgeContext(bridge, "ses_mcp")).resolves.toEqual({ + env: { PASEO_AGENT_ID: "two" }, + }); await customEnv.close(); await customMcp.close(); }); diff --git a/packages/server/src/server/agent/providers/opencode-bridge.local.e2e.test.ts b/packages/server/src/server/agent/providers/opencode-bridge.local.e2e.test.ts index 843ef21ebb..749374b29f 100644 --- a/packages/server/src/server/agent/providers/opencode-bridge.local.e2e.test.ts +++ b/packages/server/src/server/agent/providers/opencode-bridge.local.e2e.test.ts @@ -455,9 +455,25 @@ test.each([ let original: Awaited> | undefined; let resumed: Awaited> | undefined; try { + // Windows invokes the platform binary directly. Installing its wrapper also runs an + // unused postinstall binary probe, which has no timeout and can hold the fixture open. + const installPackage = + process.platform === "win32" + ? `${windowsPackage}-${process.arch}@${cliPackage.slice(cliPackage.lastIndexOf("@") + 1)}` + : cliPackage; + // npm abandons a stalled registry download only after its 5 minute default, past this + // test's budget, and the killed install keeps the fixture locked. Retry stalls sooner. await execCommand( "npm", - ["install", "--prefix", root, "--no-audit", "--no-fund", cliPackage], + [ + "install", + "--prefix", + root, + "--no-audit", + "--no-fund", + "--fetch-timeout=30000", + installPackage, + ], { cwd: root, timeout: 180_000, diff --git a/packages/server/src/server/agent/providers/opencode/bridge.test.ts b/packages/server/src/server/agent/providers/opencode/bridge.test.ts index 33f43c4f79..468baabe14 100644 --- a/packages/server/src/server/agent/providers/opencode/bridge.test.ts +++ b/packages/server/src/server/agent/providers/opencode/bridge.test.ts @@ -20,6 +20,7 @@ import { createPaseoAgentToolManifest, createPaseoToolCatalog } from "../../tool import { serializePaseoToolInputParameters } from "../../tools/paseo-tool-serialization.js"; import { OpenCodeBridge, + decorateOpenCodeV2Env, loadOpenCodeBridgePluginArtifact, materializeOpenCodeV2Plugin, } from "./bridge.js"; @@ -137,33 +138,28 @@ describe("OpenCodeBridge", () => { }; expect(ajv.compile(createDefinition.inputSchema)(createInput)).toBe(true); - const v2Config = z - .object({ plugins: z.array(z.object({ package: z.string() })) }) - .parse(JSON.parse((await bridge.decorateV2ServerEnv({})).OPENCODE_CONFIG_CONTENT)); - const v2Module: { - default: { setup(context: V2TestPluginContext): Promise<() => Promise> }; - } = await import( - pathToFileURL(path.join(fileURLToPath(v2Config.plugins[0]!.package), "server.js")).href - ); const tools = new Map(); - const dispose = await v2Module.default.setup({ - options: plugin, - tool: { - transform: async (transform) => { - transform({ - add: (tool) => { - tools.set(tool.name, tool); - }, - }); - return { dispose: async () => undefined }; + const dispose = await setupBoundV2Plugin( + bridge, + { + tool: { + transform: async (transform) => { + transform({ + add: (tool) => { + tools.set(tool.name, tool); + }, + }); + return { dispose: async () => undefined }; + }, + }, + session: { + context: async () => [], + get: async () => ({ parentID: "bound" }), + hook: async () => ({ dispose: async () => undefined }), }, }, - session: { - context: async () => [], - get: async () => ({ parentID: "bound" }), - hook: async () => ({ dispose: async () => undefined }), - }, - }); + ["bound"], + ); try { const created = await tools .get("paseo_create_agent")! @@ -402,45 +398,35 @@ describe("OpenCodeBridge", () => { const release = bridge.bindSession({ sessionId: "parent", env: {}, tools: catalog }); const releaseDisabled = bridge.bindSession({ sessionId: "disabled", env: {} }); try { - const env = await bridge.decorateV2ServerEnv({}); - const config = z - .object({ - plugins: z.array( - z.object({ - package: z.string(), - options: z.object({ baseUrl: z.string(), token: z.string() }), - }), - ), - }) - .parse(JSON.parse(env.OPENCODE_CONFIG_CONTENT)); - expect(await bridge.decorateV2ServerEnv(env)).toEqual(env); - const plugin = config.plugins[0]!; + const pluginUrl = await bridge.materializeV2Plugin(); + const env = decorateOpenCodeV2Env({}, pluginUrl); + expect(decorateOpenCodeV2Env(env, pluginUrl)).toEqual(env); const tools = new Map(); let filter!: (input: V2TestContext) => Promise; - const module: { - default: { setup(context: V2TestPluginContext): Promise<() => Promise> }; - } = await import(pathToFileURL(path.join(fileURLToPath(plugin.package), "server.js")).href); - const dispose = await module.default.setup({ - options: plugin.options, - tool: { - transform: async (transform) => { - transform({ - add: (tool) => { - tools.set(tool.name, tool); - }, - }); - return { dispose: async () => undefined }; + const dispose = await setupBoundV2Plugin( + bridge, + { + tool: { + transform: async (transform) => { + transform({ + add: (tool) => { + tools.set(tool.name, tool); + }, + }); + return { dispose: async () => undefined }; + }, + }, + session: { + context: async () => [], + get: async ({ sessionID }) => ({ parentID: sessionID === "child" ? "parent" : "" }), + hook: async (_name, callback) => { + filter = callback; + return { dispose: async () => undefined }; + }, }, }, - session: { - context: async () => [], - get: async () => ({ parentID: "parent" }), - hook: async (_name, callback) => { - filter = callback; - return { dispose: async () => undefined }; - }, - }, - }); + ["parent", "disabled"], + ); const allowed: V2TestContext = { sessionID: "child", tools: { paseo_echo_context: {}, native: {} }, @@ -453,6 +439,12 @@ describe("OpenCodeBridge", () => { }; await filter(disabled); expect(Object.keys(disabled.tools)).toEqual(["native"]); + const unrelated: V2TestContext = { + sessionID: "unrelated", + tools: { paseo_echo_context: {}, native: {} }, + }; + await filter(unrelated); + expect(Object.keys(unrelated.tools)).toEqual(["native"]); await expect( tools.get("paseo_echo_context")!.execute({ value: "child result" }, { sessionID: "child" }), ).resolves.toMatchObject({ content: [{ type: "text", text: "child result" }] }); @@ -486,35 +478,33 @@ describe("OpenCodeBridge", () => { await bridge.start(); const release = bridge.bindSession({ sessionId: "caller", env: {}, tools: catalog }); try { - const env = await bridge.decorateV2ServerEnv({}); - const { plugins } = JSON.parse(env.OPENCODE_CONFIG_CONTENT); - const plugin = plugins[0]; - const module = await import( - pathToFileURL(path.join(fileURLToPath(plugin.package), "server.js")).href - ); + const options = bridge.sharedV2Connection(); const tools = new Map(); - const dispose = await module.default.setup({ - options: plugin.options, - tool: { - transform: async (transform: (editor: { add(tool: V2TestTool): void }) => void) => { - transform({ add: (tool) => tools.set(tool.name, tool) }); - return { dispose: async () => undefined }; + const dispose = await setupBoundV2Plugin( + bridge, + { + tool: { + transform: async (transform: (editor: { add(tool: V2TestTool): void }) => void) => { + transform({ add: (tool) => tools.set(tool.name, tool) }); + return { dispose: async () => undefined }; + }, + }, + session: { + context: async () => [], + get: async () => ({ parentID: "" }), + hook: async () => ({ dispose: async () => undefined }), }, }, - session: { - context: async () => [], - get: async () => ({ parentID: "" }), - hook: async () => ({ dispose: async () => undefined }), - }, - } satisfies V2TestPluginContext); + ["caller"], + ); try { const input = { provider: "codex", title: "Invalid provider", initialPrompt: "Hello" }; const response = await fetch( - `${plugin.options.baseUrl}/_internal/opencode/sessions/caller/tools/create_agent`, + `${options.baseUrl}/_internal/opencode/sessions/caller/tools/create_agent`, { method: "POST", headers: { - Authorization: `Bearer ${plugin.options.token}`, + Authorization: `Bearer ${options.token}`, "Content-Type": "application/json", }, body: JSON.stringify(input), @@ -572,35 +562,24 @@ describe("OpenCodeBridge", () => { await bridge.start(); const release = bridge.bindSession({ sessionId: "session", env: {}, tools: catalog }); try { - const env = await bridge.decorateV2ServerEnv({}); - const plugin = z - .object({ - plugins: z.array( - z.object({ - package: z.string(), - options: z.object({ baseUrl: z.string(), token: z.string() }), - }), - ), - }) - .parse(JSON.parse(env.OPENCODE_CONFIG_CONTENT)).plugins[0]!; const pluginTools = new Map(); - const module: { - default: { setup(context: V2TestPluginContext): Promise<() => Promise> }; - } = await import(pathToFileURL(path.join(fileURLToPath(plugin.package), "server.js")).href); - const dispose = await module.default.setup({ - options: plugin.options, - tool: { - transform: async (transform) => { - transform({ add: (tool) => pluginTools.set(tool.name, tool) }); - return { dispose: async () => undefined }; + const dispose = await setupBoundV2Plugin( + bridge, + { + tool: { + transform: async (transform) => { + transform({ add: (tool) => pluginTools.set(tool.name, tool) }); + return { dispose: async () => undefined }; + }, + }, + session: { + context: async () => [], + get: async () => ({ parentID: undefined }), + hook: async () => ({ dispose: async () => undefined }), }, }, - session: { - context: async () => [], - get: async () => ({ parentID: undefined }), - hook: async () => ({ dispose: async () => undefined }), - }, - }); + ["session"], + ); const result = await pluginTools .get("paseo_browser_screenshot")! .execute({}, { sessionID: "session" }); @@ -642,7 +621,8 @@ describe("OpenCodeBridge", () => { const tools = new Map(); let hook!: (input: V2TestContext) => Promise; const dispose = await module.default.setup({ - options: { baseUrl: "", token: "" }, + options: { mode: "structured-only" }, + location: { directory: root }, tool: { transform: async (transform) => { transform({ @@ -657,7 +637,7 @@ describe("OpenCodeBridge", () => { context: async () => history, get: async () => ({ parentID: "parent" }), hook: async (_name, callback) => { - hook = callback; + hook ??= callback; return { dispose: async () => undefined }; }, }, @@ -701,9 +681,13 @@ describe("OpenCodeBridge", () => { name.startsWith("paseo-v2-"), ), ).toEqual([]); - const env = await bridge.decorateV2ServerEnv({ - OPENCODE_CONFIG_CONTENT: JSON.stringify({ plugins: ["user-plugin"] }), - }); + const pluginUrl = await bridge.materializeV2Plugin(); + const env = decorateOpenCodeV2Env( + { + OPENCODE_CONFIG_CONTENT: JSON.stringify({ plugins: ["user-plugin"] }), + }, + pluginUrl, + ); const config = z .object({ plugins: z.tuple([z.literal("user-plugin"), z.object({ package: z.string() })]) }) .parse(JSON.parse(env.OPENCODE_CONFIG_CONTENT)); @@ -711,6 +695,9 @@ describe("OpenCodeBridge", () => { expect((await stat(directory)).isDirectory()).toBe(true); const entry = await readFile(path.join(directory, "server.js"), "utf8"); expect(entry).toContain('id: "paseo"'); + expect(await readFile(path.join(directory, "state.mjs"), "utf8")).toBe( + await readFile(new URL("./v2/state.mjs", import.meta.url), "utf8"), + ); const manifest = JSON.parse(await readFile(path.join(directory, "package.json"), "utf8")); expect(manifest).toMatchObject({ type: "module", exports: { "./server": "./server.js" } }); } finally { @@ -856,7 +843,8 @@ interface V2TestContext { system?: Array<{ type: "text"; text: string }>; } interface V2TestPluginContext { - options: { baseUrl: string; token: string }; + options: Record; + location?: { directory: string }; tool: { transform( callback: (editor: { add(tool: V2TestTool): void }) => void, @@ -864,10 +852,33 @@ interface V2TestPluginContext { }; session: { context(input: { sessionID: string }): Promise; - get(input: { sessionID: string }): Promise<{ parentID: string }>; + get(input: { sessionID: string }): Promise<{ parentID: string | undefined }>; hook( name: string, callback: (input: V2TestContext) => Promise, ): Promise<{ dispose(): Promise }>; }; } + +async function setupBoundV2Plugin( + bridge: OpenCodeBridge, + context: Pick, + sessionIds: string[], +): Promise<() => Promise> { + const directory = fileURLToPath(await bridge.materializeV2Plugin()); + const module = await import(pathToFileURL(path.join(directory, "server.js")).href); + let bind!: (input: { sessionID: string; baseUrl: string; token: string }) => Promise; + const dispose: () => Promise = await module.default.setup({ + ...context, + options: {}, + location: { directory }, + rpc: { + register: async (_definition: unknown, handlers: { bind: typeof bind }) => { + bind = handlers.bind; + return { dispose: async () => undefined }; + }, + }, + }); + for (const sessionID of sessionIds) await bind({ sessionID, ...bridge.sharedV2Connection() }); + return dispose; +} diff --git a/packages/server/src/server/agent/providers/opencode/bridge.ts b/packages/server/src/server/agent/providers/opencode/bridge.ts index 7abe34475d..87ee07798b 100644 --- a/packages/server/src/server/agent/providers/opencode/bridge.ts +++ b/packages/server/src/server/agent/providers/opencode/bridge.ts @@ -30,6 +30,7 @@ class OpenCodeBridgeClientError extends Error { interface OpenCodeBridgeOptions { paseoHome: string; logger: Logger; + port?: number; } interface OpenCodeSessionBinding { @@ -54,6 +55,7 @@ interface OpenCodeConfig { export class OpenCodeBridge { private readonly paseoHome: string; private readonly logger: Logger; + private readonly port: number; private readonly token = randomBytes(32).toString("hex"); private readonly sessions = new Map(); private server: Server | null = null; @@ -65,6 +67,7 @@ export class OpenCodeBridge { constructor(options: OpenCodeBridgeOptions) { this.paseoHome = options.paseoHome; this.logger = options.logger.child({ module: "agent", component: "opencode-bridge" }); + this.port = options.port ?? 0; } async start(): Promise { @@ -75,7 +78,7 @@ export class OpenCodeBridge { }); await new Promise((resolve, reject) => { server.once("error", reject); - server.listen(0, "127.0.0.1", () => { + server.listen(this.port, "127.0.0.1", () => { server.off("error", reject); resolve(); }); @@ -94,6 +97,8 @@ export class OpenCodeBridge { } bindSession(input: BindOpenCodeSessionInput): () => void { + if (this.sessions.has(input.sessionId)) + throw new Error(`OpenCode session ${input.sessionId} is already bound to a Paseo agent`); const binding: OpenCodeSessionBinding = { env: { ...input.env }, ...(input.tools ? { tools: input.tools } : {}), @@ -127,12 +132,13 @@ export class OpenCodeBridge { }; } - async decorateV2ServerEnv(env: Record): Promise> { + async materializeV2Plugin(): Promise { this.v2PluginUrl ??= await this.materializePlugin(2); - return decorateOpenCodeV2Env(env, this.v2PluginUrl, { - baseUrl: this.requireBaseUrl(), - token: this.token, - }); + return this.v2PluginUrl; + } + + sharedV2Connection(baseUrl = this.requireBaseUrl()): OpenCodePluginOptions { + return { baseUrl, token: this.token }; } async close(): Promise { @@ -282,6 +288,8 @@ export async function materializeOpenCodeV2Plugin(paseoHome: string): Promise { }); describe("OpenCode v2 history reconciliation", () => { - it("keeps client message identity on live echoes but omits it from history", () => { + it("keeps client message identity on live echoes but omits it from history", async () => { const user: SessionMessageUser = { id: "native-message", type: "user", @@ -1568,13 +1569,13 @@ describe("OpenCode v2 history reconciliation", () => { time: { created: 1 }, metadata: { paseoClientMessageId: "client-message" }, }; - expect(new V2Timeline().messages([user])).toMatchObject([ + expect(await collectTimelineSnapshot(new V2Timeline(), [user])).toMatchObject([ { item: { clientMessageId: "client-message", messageId: "native-message" } }, ]); - expect(new V2Timeline(false).messages([user])).toMatchObject([ + expect(await collectTimelineSnapshot(new V2Timeline(false), [user])).toMatchObject([ { item: { type: "user_message", messageId: "native-message" } }, ]); - const [event] = new V2Timeline(false).messages([user]); + const [event] = await collectTimelineSnapshot(new V2Timeline(false), [user]); expect(event && "item" in event && event.item).not.toHaveProperty("clientMessageId"); }); function assistant(text: string): SessionMessageAssistant { @@ -1587,31 +1588,35 @@ describe("OpenCode v2 history reconciliation", () => { content: [{ type: "text", text }], }; } - it("emits only the missing suffix after reconnect, even if an intermediate snapshot lags", () => { + it("emits only the missing suffix after reconnect, even if an intermediate snapshot lags", async () => { const timeline = new V2Timeline(); - const text = (messages: ReturnType) => + const text = (messages: Awaited>) => messages.flatMap((event) => event.type === "timeline" && event.item.type === "assistant_message" ? [event.item.text] : [], ); - expect(text(timeline.messages([assistant("hello")]))).toEqual(["hello"]); - expect(timeline.messages([assistant("hel")])).toEqual([]); - expect(text(timeline.messages([assistant("hello world")]))).toEqual([" world"]); - expect(timeline.messages([assistant("hello world")])).toEqual([]); + expect(text(await collectTimelineSnapshot(timeline, [assistant("hello")]))).toEqual(["hello"]); + expect(await collectTimelineSnapshot(timeline, [assistant("hel")])).toEqual([]); + expect(text(await collectTimelineSnapshot(timeline, [assistant("hello world")]))).toEqual([ + " world", + ]); + expect(await collectTimelineSnapshot(timeline, [assistant("hello world")])).toEqual([]); }); - it("keeps reasoning separate from assistant output", () => { + it("keeps reasoning separate from assistant output", async () => { const timeline = new V2Timeline(); const message = assistant("answer"); message.content.unshift({ type: "reasoning", text: "thinking" }); expect( - timeline.messages([message]).map((event) => (event.type === "timeline" ? event.item : null)), + (await collectTimelineSnapshot(timeline, [message])).map((event) => + event.type === "timeline" ? event.item : null, + ), ).toEqual([ { type: "reasoning", text: "thinking" }, { type: "assistant_message", text: "answer", messageId: "message" }, ]); }); - it("emits tool state transitions once and keeps their call identity", () => { + it("emits tool state transitions once and keeps their call identity", async () => { const timeline = new V2Timeline(); const message = assistant(""); message.content = [ @@ -1623,7 +1628,7 @@ describe("OpenCode v2 history reconciliation", () => { state: { status: "running", input: { command: "pwd" }, metadata: {} }, }, ]; - expect(timeline.messages([message])).toMatchObject([ + expect(await collectTimelineSnapshot(timeline, [message])).toMatchObject([ { item: { type: "tool_call", callId: "call", status: "running" } }, ]); message.content = [ @@ -1639,9 +1644,9 @@ describe("OpenCode v2 history reconciliation", () => { }, }, ]; - expect(timeline.messages([message])).toMatchObject([ + expect(await collectTimelineSnapshot(timeline, [message])).toMatchObject([ { item: { type: "tool_call", callId: "call", status: "completed" } }, ]); - expect(timeline.messages([message])).toEqual([]); + expect(await collectTimelineSnapshot(timeline, [message])).toEqual([]); }); }); diff --git a/packages/server/src/server/agent/providers/opencode/runtime-client.test.ts b/packages/server/src/server/agent/providers/opencode/runtime-client.test.ts index b1ee5be697..07f312da0a 100644 --- a/packages/server/src/server/agent/providers/opencode/runtime-client.test.ts +++ b/packages/server/src/server/agent/providers/opencode/runtime-client.test.ts @@ -66,6 +66,7 @@ test("retries a rejected version probe after the configured binary changes", asy const script = join(root, "version.cjs"); const client = new OpenCodeRuntimeClient(createTestLogger(), { command: { mode: "replace", argv: [process.execPath, script] }, + env: { XDG_STATE_HOME: root }, }); try { await writeFile(script, 'console.log("opencode v2.0.3")'); @@ -95,6 +96,7 @@ test.each([ const script = join(root, "version.cjs"); const client = new OpenCodeRuntimeClient(createTestLogger(), { command: { mode: "replace", argv: [process.execPath, script] }, + env: { XDG_STATE_HOME: root }, }); try { await writeFile(script, initialSource); @@ -193,6 +195,7 @@ test.each([ logger, { command: { mode: "replace", argv: [process.execPath, script] }, + env: { XDG_STATE_HOME: root }, }, { serverManager: new TrackedServerManager({ logger }) }, ); @@ -209,3 +212,38 @@ test.each([ }, 10000, ); + +test("selects v2 without probing the binary when an external server is configured", async () => { + const { OpenCodeRuntimeClient } = await import("./runtime-client.js"); + const { createTestLogger } = await import("../../../../test-utils/test-logger.js"); + const client = new OpenCodeRuntimeClient(createTestLogger(), { + command: { mode: "replace", argv: [process.execPath, "-e", "process.exit(1)"] }, + env: { PASEO_OPENCODE_SERVER_URL: "http://127.0.0.1:4096" }, + }); + try { + const features = await client.listFeatures({ provider: "opencode", cwd: "/tmp/project" }); + expect(features.map((feature) => feature.label)).toEqual(["Auto-accept"]); + } finally { + await client.shutdown(); + } +}); + +test("keeps native Paseo tools available when an external server is configured", async () => { + const { OpenCodeRuntimeClient } = await import("./runtime-client.js"); + const { createTestLogger } = await import("../../../../test-utils/test-logger.js"); + const { OpenCodeBridge } = await import("./bridge.js"); + const bridge = new OpenCodeBridge({ paseoHome: "/tmp", logger: createTestLogger() }); + const external = new OpenCodeRuntimeClient( + createTestLogger(), + { env: { PASEO_OPENCODE_SERVER_URL: "http://127.0.0.1:4096" } }, + { bridge }, + ); + const local = new OpenCodeRuntimeClient(createTestLogger(), undefined, { bridge }); + try { + expect(external.capabilities.supportsNativePaseoTools).toBe(true); + expect(local.capabilities.supportsNativePaseoTools).toBe(true); + } finally { + await external.shutdown(); + await local.shutdown(); + } +}); diff --git a/packages/server/src/server/agent/providers/opencode/runtime-client.ts b/packages/server/src/server/agent/providers/opencode/runtime-client.ts index 2a34abe35d..e5fa17021a 100644 --- a/packages/server/src/server/agent/providers/opencode/runtime-client.ts +++ b/packages/server/src/server/agent/providers/opencode/runtime-client.ts @@ -19,7 +19,9 @@ import { import { execCommand } from "../../../../utils/spawn.js"; import { OpenCodeAgentClient } from "../opencode-agent.js"; import type { OpenCodeV2AgentClient } from "./v2/agent.js"; +import { resolveExternalOpenCodeServer } from "./v2/external-server.js"; import { withOpenCodeRuntimeNotice } from "./runtime-notice.js"; +import { selectOpenCodeService } from "./v2/service-selection.js"; // Keep the minimum aligned with the SDK and binary exercised by CI. const MINIMUM_V2: readonly [number, number] = [0, 10]; @@ -67,8 +69,25 @@ export class OpenCodeRuntimeClient implements AgentClient { this.resolveCreateConfig = this.legacy.resolveCreateConfig; this.isCreateConfigUnattended = this.legacy.isCreateConfigUnattended; } + private selectService() { + return selectOpenCodeService({ + explicit: resolveExternalOpenCodeServer({ ...globalThis.process.env, ...this.settings?.env }), + env: this.settings?.env, + }); + } private client(): Promise { this.selected ??= (async () => { + const selection = await this.selectService(); + if (selection.kind !== "owned") { + const { OpenCodeV2AgentClient } = await import("./v2/agent.js"); + return new OpenCodeV2AgentClient({ + logger: this.logger, + settings: this.settings, + managedProcesses: this.options.managedProcesses, + bridge: this.options.bridge, + selection, + }); + } let output: string; try { const launch = await resolveProviderLaunch({ @@ -97,6 +116,7 @@ export class OpenCodeRuntimeClient implements AgentClient { settings: this.settings, managedProcesses: this.options.managedProcesses, bridge: this.options.bridge, + selection, }); })().catch((error: unknown) => { // A failed probe must not poison refresh after the user updates the binary. @@ -106,9 +126,14 @@ export class OpenCodeRuntimeClient implements AgentClient { return this.selected; } async isAvailable() { + const selection = await this.selectService(); + if (selection.kind !== "owned") return true; return this.legacy.isAvailable(); } async getDiagnostic() { + const selection = await this.selectService(); + if (selection.kind !== "owned") + return { diagnostic: `OpenCode server: ${selection.server.url}` }; return this.legacy.getDiagnostic(); } async createSession( diff --git a/packages/server/src/server/agent/providers/opencode/test-utils/v2-harness.ts b/packages/server/src/server/agent/providers/opencode/test-utils/v2-harness.ts index 505955f64c..eb06928e63 100644 --- a/packages/server/src/server/agent/providers/opencode/test-utils/v2-harness.ts +++ b/packages/server/src/server/agent/providers/opencode/test-utils/v2-harness.ts @@ -172,6 +172,9 @@ export class V2Harness { event: { subscribe: (options) => this.events(options?.signal) }, }; readonly connection: V2Connection = { + bindSession: async () => {}, + unbindSession: async () => {}, + refreshLocation: async () => {}, client: this.api, release: async () => { this.releases += 1; diff --git a/packages/server/src/server/agent/providers/opencode/test-utils/v2-streamed-text-memory.ts b/packages/server/src/server/agent/providers/opencode/test-utils/v2-streamed-text-memory.ts index d9d254d9de..98cd79526a 100644 --- a/packages/server/src/server/agent/providers/opencode/test-utils/v2-streamed-text-memory.ts +++ b/packages/server/src/server/agent/providers/opencode/test-utils/v2-streamed-text-memory.ts @@ -1,3 +1,4 @@ +import { collectTimelineSnapshot } from "./v2-timeline.js"; import { TimelineProjection } from "../../../timeline-projection.js"; import { V2Timeline } from "../v2/timeline.js"; @@ -21,16 +22,18 @@ for (let index = 0; index < chunks; index++) { const event = mode === "delta" ? timeline.delta({ ...part, delta }) - : timeline.messages([ - { - id: "answer", - type: "assistant", - agent: "build", - model: { providerID: "test", id: "model" }, - time: { created: 2 }, - content: [{ type: "reasoning", text }], - }, - ])[0]; + : ( + await collectTimelineSnapshot(timeline, [ + { + id: "answer", + type: "assistant", + agent: "build", + model: { providerID: "test", id: "model" }, + time: { created: 2 }, + content: [{ type: "reasoning", text }], + }, + ]) + )[0]; if (event?.type !== "timeline") throw new Error("Expected a timeline event"); projection.append({ seq: index + 1, diff --git a/packages/server/src/server/agent/providers/opencode/test-utils/v2-timeline.ts b/packages/server/src/server/agent/providers/opencode/test-utils/v2-timeline.ts new file mode 100644 index 0000000000..e7aa552479 --- /dev/null +++ b/packages/server/src/server/agent/providers/opencode/test-utils/v2-timeline.ts @@ -0,0 +1,15 @@ +import type { SessionMessageInfo } from "@opencode/client"; +import type { AgentStreamEvent } from "../../../agent-sdk-types.js"; +import type { V2Timeline } from "../v2/timeline.js"; + +// Snapshot assertions without a live stream can collect the publisher's events. +export async function collectTimelineSnapshot( + timeline: V2Timeline, + messages: SessionMessageInfo[], +): Promise { + const events: AgentStreamEvent[] = []; + await timeline.messages(messages, (event) => { + events.push(event); + }); + return events; +} diff --git a/packages/server/src/server/agent/providers/opencode/tool-call-detail-parser.ts b/packages/server/src/server/agent/providers/opencode/tool-call-detail-parser.ts index 8214ebb1d0..b3eb432f86 100644 --- a/packages/server/src/server/agent/providers/opencode/tool-call-detail-parser.ts +++ b/packages/server/src/server/agent/providers/opencode/tool-call-detail-parser.ts @@ -153,21 +153,6 @@ const OpencodeGrepOutputSchema = z ]) .nullable(); -function formatLogEntry(value: unknown): string | undefined { - const outputText = readOutputText(value); - if (outputText) { - return outputText; - } - if (value === null || value === undefined) { - return undefined; - } - try { - return JSON.stringify(value, null, 2); - } catch { - return String(value); - } -} - function extractOpenCodeTaskSessionId(value: unknown): string | undefined { const text = readOutputText(value); if (text) { @@ -195,7 +180,6 @@ function extractOpenCodeTaskSessionId(value: unknown): string | undefined { function deriveOpencodeTaskDetail( input: unknown, output: unknown, - error: unknown, metadata: Record | undefined, ): ToolCallDetail | null { if (!isRecord(input)) { @@ -208,7 +192,6 @@ function deriveOpencodeTaskDetail( return null; } - const log = [formatLogEntry(output), formatLogEntry(error)].filter((entry) => entry).join("\n"); const childSessionId = normalizeSubAgentText(metadata?.sessionId) ?? extractOpenCodeTaskSessionId(output); return { @@ -216,7 +199,8 @@ function deriveOpencodeTaskDetail( ...(subAgentType ? { subAgentType } : {}), ...(description ? { description } : {}), ...(childSessionId ? { childSessionId } : {}), - log, + // COMPAT(subagent-log): remove after 2027-04-30. + log: "", actions: [], }; } @@ -373,11 +357,10 @@ export function deriveOpencodeToolDetail( toolName: string, input: unknown, output: unknown, - error: unknown = null, metadata?: Record, ): ToolCallDetail { if (toolName.trim().toLowerCase() === "task") { - const taskDetail = deriveOpencodeTaskDetail(input, output, error, metadata); + const taskDetail = deriveOpencodeTaskDetail(input, output, metadata); if (taskDetail) { return taskDetail; } diff --git a/packages/server/src/server/agent/providers/opencode/tool-call-mapper.test.ts b/packages/server/src/server/agent/providers/opencode/tool-call-mapper.test.ts index 1c9ba212e1..eb38a04ac6 100644 --- a/packages/server/src/server/agent/providers/opencode/tool-call-mapper.test.ts +++ b/packages/server/src/server/agent/providers/opencode/tool-call-mapper.test.ts @@ -460,7 +460,7 @@ describe("opencode tool-call mapper", () => { }); }); - it("maps completed task calls with final output log to sub_agent detail", () => { + it("maps completed task calls to sub_agent detail", () => { const item = expectMapped( mapOpencodeToolCall({ toolName: "task", @@ -480,7 +480,7 @@ describe("opencode tool-call mapper", () => { type: "sub_agent", subAgentType: "explore", description: "Explore agent-tools codebase", - log: "Found the CLI entrypoint and provider registry.", + log: "", actions: [], }); }); @@ -505,12 +505,12 @@ describe("opencode tool-call mapper", () => { subAgentType: "explore", description: "Explore current directory", childSessionId: "ses_2268db431ffe299vL1bbot8R7Z", - log: 'done', + log: "", actions: [], }); }); - it("maps aborted task calls with preserved error log to sub_agent detail", () => { + it("maps aborted task calls to sub_agent detail", () => { const item = expectMapped( mapOpencodeToolCall({ toolName: "task", @@ -531,7 +531,7 @@ describe("opencode tool-call mapper", () => { type: "sub_agent", subAgentType: "explore", description: "Explore agent-tools codebase", - log: "Tool execution aborted", + log: "", actions: [], }); }); diff --git a/packages/server/src/server/agent/providers/opencode/tool-call-mapper.ts b/packages/server/src/server/agent/providers/opencode/tool-call-mapper.ts index 8fbc861a84..261a4ec827 100644 --- a/packages/server/src/server/agent/providers/opencode/tool-call-mapper.ts +++ b/packages/server/src/server/agent/providers/opencode/tool-call-mapper.ts @@ -43,7 +43,7 @@ export function mapOpencodeToolCall(params: OpencodeToolCallParams): ToolCallTim const error = raw.error ?? null; const rawStatus = typeof raw.status === "string" ? raw.status : undefined; const status = normalizeToolCallStatus(rawStatus, error, output); - const detail = deriveOpencodeToolDetail(name, input, output, error, raw.metadata); + const detail = deriveOpencodeToolDetail(name, input, output, raw.metadata); if (status === "failed") { return { diff --git a/packages/server/src/server/agent/providers/opencode/v2/agent.test.ts b/packages/server/src/server/agent/providers/opencode/v2/agent.test.ts index 564e1f46c5..e8188730f5 100644 --- a/packages/server/src/server/agent/providers/opencode/v2/agent.test.ts +++ b/packages/server/src/server/agent/providers/opencode/v2/agent.test.ts @@ -17,6 +17,26 @@ function terminalEvents(events: AgentStreamEvent[]) { } describe("OpenCode v2 session lifecycle", () => { + test("refreshes the existing location before reading a forced catalog", async () => { + const harness = new V2Harness(); + const refreshed: string[] = []; + harness.connection.refreshLocation = async (directory) => { + refreshed.push(directory); + }; + harness.api.model.list = async () => ({ location: harness.info.location, data: [] }); + harness.api.provider.list = async () => ({ + location: harness.info.location, + data: [{ id: "test", name: "Test", activation: "enabled", package: "test" }], + }); + const client = new OpenCodeV2AgentClient({ + logger: createTestLogger(), + runtime: harness.runtime, + }); + await client.fetchCatalog({ scope: "workspace", cwd: "/tmp/project", force: true }); + await client.fetchCatalog({ scope: "workspace", cwd: "/tmp/project", force: false }); + expect(refreshed).toEqual(["/tmp/project"]); + await client.shutdown(); + }); test("completes from execution events without a long-lived HTTP wait", async () => { const harness = new V2Harness(); harness.prompt = async (input) => { diff --git a/packages/server/src/server/agent/providers/opencode/v2/agent.ts b/packages/server/src/server/agent/providers/opencode/v2/agent.ts index 2e50e759bd..119fa0ade7 100644 --- a/packages/server/src/server/agent/providers/opencode/v2/agent.ts +++ b/packages/server/src/server/agent/providers/opencode/v2/agent.ts @@ -8,7 +8,7 @@ import { } from "./configuration.js"; import { commands } from "./commands.js"; -import { waitForLocationReady, awaitPaseoPlugin } from "./readiness.js"; +import { waitForLocationReady } from "./readiness.js"; import type { SessionInfo } from "@opencode/client"; @@ -40,6 +40,7 @@ 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 type { OpenCodeServiceSelection } from "./service-selection.js"; import { modelRef, modesFromV2, modelsFromV2 } from "./mapping.js"; interface V2AgentOptions { @@ -48,6 +49,7 @@ interface V2AgentOptions { managedProcesses?: ManagedProcessRegistry; bridge?: OpenCodeBridge; runtime?: Pick; + selection?: OpenCodeServiceSelection; } export class OpenCodeV2AgentClient implements AgentClient { @@ -56,12 +58,12 @@ export class OpenCodeV2AgentClient implements AgentClient { private readonly runtime: Pick; private readonly connections = new Map(); constructor(private readonly options: V2AgentOptions) { - this.capabilities = { ...V2_CAPABILITIES, supportsNativePaseoTools: Boolean(options.bridge) }; + const bridge = options.bridge; + this.capabilities = { ...V2_CAPABILITIES, supportsNativePaseoTools: Boolean(bridge) }; this.runtime = options.runtime ?? new V2Runtime({ ...options, - decorateEnv: options.bridge ? (env) => options.bridge!.decorateV2ServerEnv(env) : undefined, }); } async isAvailable() { @@ -85,6 +87,10 @@ export class OpenCodeV2AgentClient implements AgentClient { await activity("plugin.list", () => waitForLocationReady({ client: connection.client, location, signal: request.signal }), ); + if (options.force) + await activity("paseo.bridge.refresh", () => + connection.refreshLocation(location.directory, request.signal), + ); const [models, agents, providers] = await Promise.all([ activity("model.list", () => connection.client.model.list({ location }, request)), activity("agent.list", () => connection.client.agent.list({ location }, request)), @@ -163,7 +169,8 @@ export class OpenCodeV2AgentClient implements AgentClient { requiresDedicatedV2Server(config, launch) ? { env: launch?.env, dedicated: true } : {}, ); let ownedConnection = connection; - const unbind = this.options.bridge?.bindSession({ + const bridge = this.options.bridge; + const unbind = bridge?.bindSession({ sessionId: info.id, env: launch?.env ?? {}, tools: launch?.paseoTools, @@ -172,7 +179,7 @@ export class OpenCodeV2AgentClient implements AgentClient { const bindChild = (childId: string) => { this.connections.set(childId, ownedConnection); if (bound.has(childId)) return; - const childUnbind = this.options.bridge?.bindSession({ + const childUnbind = bridge?.bindSession({ sessionId: childId, env: launch?.env ?? {}, tools: launch?.paseoTools, @@ -204,10 +211,6 @@ export class OpenCodeV2AgentClient implements AgentClient { moved, ); try { - if (this.options.bridge) { - const location = { directory: config.cwd }; - await awaitPaseoPlugin({ client: connection.client, location }); - } await session.initialize( launch?.env ? createProviderEnv({ runtimeSettings: this.options.settings, overlays: [launch.env] }) diff --git a/packages/server/src/server/agent/providers/opencode/v2/bridge-plugin.mjs b/packages/server/src/server/agent/providers/opencode/v2/bridge-plugin.mjs index 1664c0b59f..6971a5b323 100644 --- a/packages/server/src/server/agent/providers/opencode/v2/bridge-plugin.mjs +++ b/packages/server/src/server/agent/providers/opencode/v2/bridge-plugin.mjs @@ -1,100 +1,15 @@ -import { registerStructuredOutput, STRUCTURED_OUTPUT_TOOL } from "./structured-output-plugin.mjs"; +import { registerStructuredOutput } from "./structured-output-plugin.mjs"; +import { registerSharedBridge } from "./shared-bridge-plugin.mjs"; export default { id: "paseo", async setup(context) { const disposeStructuredOutput = await registerStructuredOutput(context); - const { baseUrl, token } = context.options; - if (!baseUrl || !token) return disposeStructuredOutput; - async function request(pathname, body, allowMissing = false) { - const response = await fetch(new URL(`/_internal/opencode${pathname}`, baseUrl), { - method: body === undefined ? "GET" : "POST", - headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" }, - ...(body === undefined ? {} : { body: JSON.stringify(body) }), - }); - if (allowMissing && response.status === 404) return null; - if (!response.ok) { - const payload = await response.json().catch(() => null); - const detail = formatErrorDetail(payload?.issues ?? payload?.details); - const message = - typeof payload?.error === "string" && payload.error - ? payload.error - : `Paseo tool bridge returned HTTP ${response.status}`; - const error = new Error(detail ? `${message}: ${detail}` : message); - error.status = response.status; - if (detail) error.details = detail; - throw error; - } - return response.json(); - } - async function scope(sessionID) { - const visited = new Set(); - while (sessionID && !visited.has(sessionID)) { - visited.add(sessionID); - const binding = await request( - `/sessions/${encodeURIComponent(sessionID)}/context?tools`, - undefined, - true, - ); - if (binding) return { ...binding, sessionID }; - const session = await context.session.get({ sessionID }); - sessionID = session.parentID; - } - throw new Error("OpenCode session is not bound to a Paseo agent"); - } - const manifest = await request("/tools"); - const registration = await context.tool.transform((editor) => { - for (const definition of manifest.tools) { - editor.add({ - name: `paseo_${definition.name}`, - description: definition.description, - input: definition.inputSchema, - options: { codemode: false }, - async execute(input, call) { - const binding = await scope(call.sessionID); - const result = await request( - `/sessions/${encodeURIComponent(binding.sessionID)}/tools/${encodeURIComponent(definition.name)}`, - input, - ); - return { - content: result.content.map(toOpenCodeContent), - metadata: { paseoTool: definition.name }, - }; - }, - }); - } - }); - const filtering = await context.session.hook("context", async (input) => { - const binding = await scope(input.sessionID); - const allowed = new Set(binding.tools.map((name) => `paseo_${name}`)); - for (const name of Object.keys(input.tools)) { - if (name !== STRUCTURED_OUTPUT_TOOL && name.startsWith("paseo_") && !allowed.has(name)) - delete input.tools[name]; - } - }); + if (context.options.mode === "structured-only") return disposeStructuredOutput; + const disposeBridge = await registerSharedBridge(context); return async () => { + await disposeBridge(); await disposeStructuredOutput(); - await filtering.dispose(); - await registration.dispose(); }; }, }; - -function formatErrorDetail(details) { - if (!Array.isArray(details)) return typeof details === "string" ? details : ""; - return details - .map((issue) => { - const path = - Array.isArray(issue?.path) && issue.path.length > 0 ? issue.path.join(".") : "input"; - return `${path}: ${issue?.message ?? "Invalid value"}`; - }) - .join("; "); -} - -// OpenCode tool content is text or a file; MCP images arrive as base64 data. -function toOpenCodeContent(part) { - if (part.type === "image") { - return { type: "file", uri: `data:${part.mimeType};base64,${part.data}`, mime: part.mimeType }; - } - return part; -} diff --git a/packages/server/src/server/agent/providers/opencode/v2/bridge-provisioning.test.ts b/packages/server/src/server/agent/providers/opencode/v2/bridge-provisioning.test.ts new file mode 100644 index 0000000000..52b483cca3 --- /dev/null +++ b/packages/server/src/server/agent/providers/opencode/v2/bridge-provisioning.test.ts @@ -0,0 +1,37 @@ +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { expect, test } from "vitest"; +import { hasManagedBridge, provisionLocalBridge } from "./bridge-provisioning.js"; + +test("installs a watched plugin without changing existing OpenCode configuration", async () => { + const root = await mkdtemp(path.join(tmpdir(), "paseo-opencode-provision-")); + const source = path.join(root, "source.js"); + const config = path.join(root, "opencode.json"); + await writeFile(source, "export default { id: 'paseo' };"); + await writeFile(path.join(root, "state.mjs"), "export const state = new Map();"); + await writeFile(config, '{"plugins":["existing"]}\n'); + try { + expect(await hasManagedBridge(root)).toBe(false); + await Promise.all([ + provisionLocalBridge({ configDirectory: root, artifact: source }), + provisionLocalBridge({ configDirectory: root, artifact: source }), + ]); + expect(await hasManagedBridge(root)).toBe(true); + const manifest = path.join(root, "plugins/paseo-managed-bridge/package.json"); + const formatted = `${JSON.stringify(JSON.parse(await readFile(manifest, "utf8")), null, 2)}\n`; + await writeFile(manifest, formatted); + expect(await hasManagedBridge(root)).toBe(true); + await provisionLocalBridge({ configDirectory: root, artifact: source }); + expect(await readFile(manifest, "utf8")).toBe(formatted); + expect(await readFile(config, "utf8")).toBe('{"plugins":["existing"]}\n'); + expect(await readFile(path.join(root, "plugins/paseo-managed-bridge/state.mjs"), "utf8")).toBe( + "export const state = new Map();", + ); + expect( + await readFile(path.join(root, "plugins/paseo-managed-bridge/server.js"), "utf8"), + ).toContain("id: 'paseo'"); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); diff --git a/packages/server/src/server/agent/providers/opencode/v2/bridge-provisioning.ts b/packages/server/src/server/agent/providers/opencode/v2/bridge-provisioning.ts new file mode 100644 index 0000000000..ce2626c38b --- /dev/null +++ b/packages/server/src/server/agent/providers/opencode/v2/bridge-provisioning.ts @@ -0,0 +1,89 @@ +import { mkdir, readFile } from "node:fs/promises"; +import { homedir } from "node:os"; +import path from "node:path"; +import { setTimeout as delay } from "node:timers/promises"; +import { writeFileAtomic } from "../../../../atomic-file.js"; + +const PACKAGE = JSON.stringify({ + name: "paseo-managed-bridge", + private: true, + type: "module", + exports: { "./server": "./server.js" }, +}); + +export function openCodeConfigDirectory(env: NodeJS.ProcessEnv): string { + return ( + env.OPENCODE_CONFIG_DIR ?? + path.join(env.XDG_CONFIG_HOME ?? path.join(homedir(), ".config"), "opencode") + ); +} + +export async function hasManagedBridge(configDirectory: string): Promise { + const directory = path.join(configDirectory, "plugins", "paseo-managed-bridge"); + const [manifest, artifact] = await Promise.all([ + readFile(path.join(directory, "package.json"), "utf8").catch(() => ""), + readFile(path.join(directory, "server.js")).catch(() => undefined), + ]); + return isManagedPackage(manifest) && Boolean(artifact?.length); +} + +export async function provisionLocalBridge(input: { + configDirectory: string; + artifact: string; +}): Promise { + const directory = path.join(input.configDirectory, "plugins", "paseo-managed-bridge"); + await mkdir(path.dirname(directory), { recursive: true }); + let created = false; + try { + await mkdir(directory); + created = true; + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; + } + const manifest = path.join(directory, "package.json"); + if (created) await writeFileAtomic(manifest, PACKAGE); + else if (!isManagedPackage(await readManagedManifest(manifest))) + throw new Error(`Cannot install OpenCode bridge: ${directory} is not managed by Paseo`); + const artifact = await readFile(input.artifact); + const state = await readFile(path.join(path.dirname(input.artifact), "state.mjs")); + const stateTarget = path.join(directory, "state.mjs"); + const existingState = await readFile(stateTarget).catch(() => undefined); + if (!existingState) await writeFileAtomic(stateTarget, state); + else if (!existingState.equals(state)) + throw new Error(`Cannot update OpenCode bridge state module at ${stateTarget}`); + const target = path.join(directory, "server.js"); + const existing = await readFile(target).catch(() => undefined); + if (!existing?.equals(artifact)) await writeFileAtomic(target, artifact); +} + +function isManagedPackage(content: string): boolean { + let value: unknown; + try { + value = JSON.parse(content); + } catch { + return false; + } + if (!value || typeof value !== "object" || Array.isArray(value)) return false; + const manifest = value as Record; + if (!manifest.exports || typeof manifest.exports !== "object" || Array.isArray(manifest.exports)) + return false; + const exports = manifest.exports as Record; + return ( + manifest.name === "paseo-managed-bridge" && + manifest.private === true && + manifest.type === "module" && + exports["./server"] === "./server.js" + ); +} + +async function readManagedManifest(file: string): Promise { + for (let attempt = 0; attempt < 20; attempt++) { + try { + return await readFile(file, "utf8"); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; + await delay(25); + } + } + return ""; +} diff --git a/packages/server/src/server/agent/providers/opencode/v2/children.ts b/packages/server/src/server/agent/providers/opencode/v2/children.ts index 8c2e0ec312..08af88dcb0 100644 --- a/packages/server/src/server/agent/providers/opencode/v2/children.ts +++ b/packages/server/src/server/agent/providers/opencode/v2/children.ts @@ -92,13 +92,13 @@ export class SessionChildren { this.childStates.set(info.id, signature); this.options.emit({ type: "provider_subagent", provider: "opencode", event: presentation }); } - for (const event of timeline.messages(await messages(this.options.client(), info.id))) { + await timeline.messages(await messages(this.options.client(), info.id), (event) => { if (event.type === "timeline") this.options.emit({ type: "provider_subagent", provider: "opencode", event: { type: "timeline", id: info.id, item: event.item, timestamp: event.timestamp }, }); - } + }); } } diff --git a/packages/server/src/server/agent/providers/opencode/v2/external-runtime.test.ts b/packages/server/src/server/agent/providers/opencode/v2/external-runtime.test.ts new file mode 100644 index 0000000000..f4f39f4aeb --- /dev/null +++ b/packages/server/src/server/agent/providers/opencode/v2/external-runtime.test.ts @@ -0,0 +1,180 @@ +import { createServer, type Server } from "node:http"; +import { createServer as createNetServer } from "node:net"; + +import { afterEach, describe, expect, test } from "vitest"; + +import { createTestLogger } from "../../../../../test-utils/test-logger.js"; +import { V2Runtime } from "./runtime.js"; +import { EXTERNAL_SERVER_PASSWORD_ENV, EXTERNAL_SERVER_URL_ENV } from "./external-server.js"; + +function listen(server: Server): Promise { + return new Promise((resolve, reject) => { + server.once("error", reject); + server.listen(0, "127.0.0.1", () => { + const address = server.address(); + if (!address || typeof address === "string") { + reject(new Error("Test server did not expose a TCP address")); + return; + } + resolve(address.port); + }); + }); +} + +function close(server: Server): Promise { + return new Promise((resolve, reject) => { + server.close((error) => { + if (error) { + reject(error); + return; + } + resolve(); + }); + server.closeAllConnections(); + }); +} + +function reserveClosedPort(): Promise { + return new Promise((resolve, reject) => { + const server = createNetServer(); + server.once("error", reject); + server.listen(0, "127.0.0.1", () => { + const address = server.address(); + if (!address || typeof address === "string") { + server.close(); + reject(new Error("Could not reserve a test port")); + return; + } + server.close((error) => { + if (error) { + reject(error); + return; + } + resolve(address.port); + }); + }); + }); +} + +describe("V2Runtime against an external server", () => { + let server: Server | undefined; + + afterEach(async () => { + if (server) await close(server); + server = undefined; + }); + + test("reuses the configured server and never spawns a local one", async () => { + const requests: Array<{ url: string | undefined; authorization: string | undefined }> = []; + server = createServer((request, response) => { + requests.push({ url: request.url, authorization: request.headers.authorization }); + if (request.url !== "/api/info") { + response.writeHead(404); + response.end(); + return; + } + response.writeHead(200, { "content-type": "application/json" }); + response.end(JSON.stringify({ version: "2.0.10", pid: 1, urls: [], paths: { tmp: "/tmp" } })); + }); + const port = await listen(server); + const runtime = new V2Runtime({ + logger: createTestLogger(), + externalServer: { url: `http://127.0.0.1:${port}`, password: "secret" }, + }); + + const first = await runtime.acquire(); + const second = await runtime.acquire(); + expect(first.client).toBe(second.client); + expect(requests).toEqual([ + { + url: "/api/info", + authorization: `Basic ${Buffer.from("opencode:secret").toString("base64")}`, + }, + ]); + + await first.release(); + await second.release(); + const refreshed = await runtime.acquire({ fresh: true }); + expect(refreshed.client).toBe(first.client); + await refreshed.release(); + await runtime.shutdown(); + expect(requests).toHaveLength(1); + }); + + test("selects the external server from provider environment", async () => { + const paths: Array = []; + server = createServer((request, response) => { + paths.push(request.url); + if (request.url !== "/api/info") { + response.writeHead(404); + response.end(); + return; + } + response.writeHead(200, { "content-type": "application/json" }); + response.end(JSON.stringify({ version: "2.0.10", pid: 1, urls: [], paths: { tmp: "/tmp" } })); + }); + const port = await listen(server); + const runtime = new V2Runtime({ + logger: createTestLogger(), + settings: { + env: { + [EXTERNAL_SERVER_URL_ENV]: `http://127.0.0.1:${port}`, + [EXTERNAL_SERVER_PASSWORD_ENV]: "", + }, + }, + }); + + const connection = await runtime.acquire(); + expect(paths).toEqual(["/api/info"]); + await connection.release(); + await runtime.shutdown(); + }); + + test("reports an unreachable configured server", async () => { + const port = await reserveClosedPort(); + const runtime = new V2Runtime({ + logger: createTestLogger(), + externalServer: { url: `http://127.0.0.1:${port}` }, + }); + + await expect(runtime.acquire()).rejects.toThrow( + `Cannot reach OpenCode v2 server at http://127.0.0.1:${port}`, + ); + await runtime.shutdown(); + }); + + test("rejects session configuration that requires process isolation", async () => { + const runtime = new V2Runtime({ + logger: createTestLogger(), + externalServer: { url: "http://127.0.0.1:1" }, + }); + await expect(runtime.acquire({ dedicated: true })).rejects.toThrow( + "require an isolated server", + ); + await runtime.shutdown(); + }); + + test("rejects provider process environment on an explicit server", async () => { + const runtime = new V2Runtime({ + logger: createTestLogger(), + externalServer: { url: "http://127.0.0.1:1" }, + settings: { env: { XDG_CONFIG_HOME: "/custom", PROVIDER_KEY: "secret" } }, + }); + await expect(runtime.acquire()).rejects.toThrow("XDG_CONFIG_HOME, PROVIDER_KEY"); + await runtime.shutdown(); + }); + + test("rejects an unsupported explicit server version", async () => { + server = createServer((_request, response) => { + response.writeHead(200, { "content-type": "application/json" }); + response.end(JSON.stringify({ version: "2.0.9", pid: 1, urls: [], paths: { tmp: "/tmp" } })); + }); + const port = await listen(server); + const runtime = new V2Runtime({ + logger: createTestLogger(), + externalServer: { url: `http://127.0.0.1:${port}` }, + }); + await expect(runtime.acquire()).rejects.toThrow("Unsupported OpenCode version 2.0.9"); + await runtime.shutdown(); + }); +}); diff --git a/packages/server/src/server/agent/providers/opencode/v2/external-server.test.ts b/packages/server/src/server/agent/providers/opencode/v2/external-server.test.ts new file mode 100644 index 0000000000..f9986215ad --- /dev/null +++ b/packages/server/src/server/agent/providers/opencode/v2/external-server.test.ts @@ -0,0 +1,60 @@ +import { describe, expect, test } from "vitest"; + +import { + EXTERNAL_SERVER_PASSWORD_ENV, + EXTERNAL_SERVER_URL_ENV, + resolveExternalOpenCodeServer, +} from "./external-server.js"; + +describe("resolveExternalOpenCodeServer", () => { + test("returns undefined when no URL is configured", () => { + expect(resolveExternalOpenCodeServer(undefined)).toBeUndefined(); + expect(resolveExternalOpenCodeServer({ [EXTERNAL_SERVER_URL_ENV]: " " })).toBeUndefined(); + }); + + test("reads the URL and password and removes a trailing slash", () => { + expect( + resolveExternalOpenCodeServer({ + [EXTERNAL_SERVER_URL_ENV]: " http://127.0.0.1:4096/ ", + [EXTERNAL_SERVER_PASSWORD_ENV]: "secret", + }), + ).toEqual({ url: "http://127.0.0.1:4096", password: "secret" }); + }); + + test("omits an empty password", () => { + expect( + resolveExternalOpenCodeServer({ + [EXTERNAL_SERVER_URL_ENV]: "https://opencode.example.com", + [EXTERNAL_SERVER_PASSWORD_ENV]: "", + }), + ).toEqual({ url: "https://opencode.example.com" }); + }); + + test("preserves spaces in the password", () => { + expect( + resolveExternalOpenCodeServer({ + [EXTERNAL_SERVER_URL_ENV]: "https://opencode.example.com", + [EXTERNAL_SERVER_PASSWORD_ENV]: " secret ", + }), + ).toEqual({ url: "https://opencode.example.com", password: " secret " }); + }); + + test("rejects relative and non-HTTP URLs", () => { + expect(() => + resolveExternalOpenCodeServer({ [EXTERNAL_SERVER_URL_ENV]: "127.0.0.1:4096" }), + ).toThrow(`${EXTERNAL_SERVER_URL_ENV} must be an absolute URL, received "127.0.0.1:4096"`); + expect(() => + resolveExternalOpenCodeServer({ [EXTERNAL_SERVER_URL_ENV]: "unix:/tmp/opencode.sock" }), + ).toThrow( + `${EXTERNAL_SERVER_URL_ENV} must use http or https, received "unix:/tmp/opencode.sock"`, + ); + }); + + test("rejects credentials embedded in URLs", () => { + expect(() => + resolveExternalOpenCodeServer({ + [EXTERNAL_SERVER_URL_ENV]: "https://user:password@opencode.example.com", + }), + ).toThrow("must not contain credentials"); + }); +}); diff --git a/packages/server/src/server/agent/providers/opencode/v2/external-server.ts b/packages/server/src/server/agent/providers/opencode/v2/external-server.ts new file mode 100644 index 0000000000..c00b158ce3 --- /dev/null +++ b/packages/server/src/server/agent/providers/opencode/v2/external-server.ts @@ -0,0 +1,38 @@ +export const EXTERNAL_SERVER_URL_ENV = "PASEO_OPENCODE_SERVER_URL"; +export const EXTERNAL_SERVER_PASSWORD_ENV = "PASEO_OPENCODE_SERVER_PASSWORD"; + +export interface ExternalOpenCodeServer { + url: string; + password?: string; +} + +/** + * Reads the optional connection to a user-managed OpenCode v2 server from + * provider environment. When absent, Paseo keeps spawning its own server. + */ +export function resolveExternalOpenCodeServer( + env: Record | undefined, +): ExternalOpenCodeServer | undefined { + const rawUrl = env?.[EXTERNAL_SERVER_URL_ENV]?.trim(); + if (!rawUrl) return undefined; + + let url: URL; + try { + url = new URL(rawUrl); + } catch { + throw new Error(`${EXTERNAL_SERVER_URL_ENV} must be an absolute URL, received "${rawUrl}"`); + } + if (url.protocol !== "http:" && url.protocol !== "https:") { + throw new Error(`${EXTERNAL_SERVER_URL_ENV} must use http or https, received "${rawUrl}"`); + } + if (url.username || url.password) + throw new Error( + `${EXTERNAL_SERVER_URL_ENV} must not contain credentials; use ${EXTERNAL_SERVER_PASSWORD_ENV}`, + ); + + const password = env?.[EXTERNAL_SERVER_PASSWORD_ENV]; + return { + url: url.toString().replace(/\/$/, ""), + ...(password ? { password } : {}), + }; +} diff --git a/packages/server/src/server/agent/providers/opencode/v2/owned-runtime.test.ts b/packages/server/src/server/agent/providers/opencode/v2/owned-runtime.test.ts new file mode 100644 index 0000000000..d60535889b --- /dev/null +++ b/packages/server/src/server/agent/providers/opencode/v2/owned-runtime.test.ts @@ -0,0 +1,77 @@ +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { expect, test } from "vitest"; +import { createTestLogger } from "../../../../../test-utils/test-logger.js"; +import { OpenCodeBridge } from "../bridge.js"; +import { provisionLocalBridge } from "./bridge-provisioning.js"; +import { V2Runtime } from "./runtime.js"; + +test("an owned helper uses an installed bridge once and survives catalog refresh", async () => { + const root = await mkdtemp(path.join(tmpdir(), "paseo-owned-opencode-")); + const config = path.join(root, "config", "opencode"); + const script = path.join(root, "server.cjs"); + const record = path.join(root, "env.json"); + const bridge = new OpenCodeBridge({ paseoHome: root, logger: createTestLogger() }); + await bridge.start(); + const artifact = fileURLToPath(await bridge.materializeV2Plugin()); + await provisionLocalBridge({ + configDirectory: config, + artifact: path.join(artifact, "server.js"), + }); + await writeFile( + script, + ` + const http = require('node:http'); + require('node:fs').writeFileSync(${JSON.stringify(record)}, process.env.OPENCODE_CONFIG_CONTENT); + 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)); + `, + ); + const runtime = new V2Runtime({ + logger: createTestLogger(), + bridge, + selection: { kind: "owned" }, + settings: { + command: { mode: "replace", argv: [process.execPath, script] }, + env: { XDG_CONFIG_HOME: path.join(root, "config"), OPENCODE_CONFIG_CONTENT: "{}" }, + }, + }); + try { + const first = await runtime.acquire(); + const pid = (await first.client.server.info()).pid; + expect(JSON.parse(await readFile(record, "utf8"))).toEqual({}); + await first.release(); + const refreshed = await runtime.acquire({ fresh: true }); + expect((await refreshed.client.server.info()).pid).toBe(pid); + await refreshed.release(); + } finally { + await runtime.shutdown(); + await bridge.close(); + await rm(root, { recursive: true, force: true }); + } +}, 15_000); + +test("reports a bridge port change that has not been applied", async () => { + const root = await mkdtemp(path.join(tmpdir(), "paseo-opencode-port-")); + const bridge = new OpenCodeBridge({ paseoHome: root, logger: createTestLogger() }); + await bridge.start(); + const actual = Number(new URL(bridge.sharedV2Connection().baseUrl).port); + const runtime = new V2Runtime({ + logger: createTestLogger(), + bridge, + selection: { kind: "explicit", server: { url: "http://127.0.0.1:1" } }, + settings: { env: { PASEO_OPENCODE_BRIDGE_PORT: actual === 1 ? "2" : "1" } }, + }); + try { + await expect(runtime.acquire()).rejects.toThrow("restart Paseo to apply the bridge port"); + } finally { + await runtime.shutdown(); + await bridge.close(); + await rm(root, { recursive: true, force: true }); + } +}); diff --git a/packages/server/src/server/agent/providers/opencode/v2/runtime.ts b/packages/server/src/server/agent/providers/opencode/v2/runtime.ts index cab5544582..0fe830fe45 100644 --- a/packages/server/src/server/agent/providers/opencode/v2/runtime.ts +++ b/packages/server/src/server/agent/providers/opencode/v2/runtime.ts @@ -16,11 +16,25 @@ import type { ManagedProcessRegistry } from "../../../../managed-processes/manag import { resolveOpenCodeHomeDir } from "../paths.js"; import { OpenCodeHttpError } from "../http-error.js"; import { raceProviderRefreshAbort } from "../../../provider-refresh-deadline.js"; +import { resolveExternalOpenCodeServer, type ExternalOpenCodeServer } from "./external-server.js"; +import { selectOpenCodeService, type OpenCodeServiceSelection } from "./service-selection.js"; +import { bridgeBindings, connectSharedService } from "./shared-service.js"; +import { + hasManagedBridge, + openCodeConfigDirectory, + provisionLocalBridge, +} from "./bridge-provisioning.js"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import type { OpenCodeBridge } from "../bridge.js"; export interface V2Connection { client: V2Api; release(): Promise; retain(): V2Connection; + bindSession(sessionId: string, cwd: string): Promise; + unbindSession(sessionId: string, cwd: string): Promise; + refreshLocation(cwd: string, signal?: AbortSignal): Promise; readonly exited: Promise; } interface Generation { @@ -28,12 +42,17 @@ interface Generation { users: number; stop(): Promise; exited: Promise; + bindSession(sessionId: string, cwd: string): Promise; + unbindSession(sessionId: string, cwd: string): Promise; + refreshLocation(cwd: string, signal?: AbortSignal): Promise; } export interface V2RuntimeOptions { logger: Logger; settings?: ProviderRuntimeSettings; managedProcesses?: ManagedProcessRegistry; - decorateEnv?: (env: Record) => Promise>; + externalServer?: ExternalOpenCodeServer; + selection?: OpenCodeServiceSelection; + bridge?: OpenCodeBridge; } export interface V2RuntimeAcquireOptions { @@ -49,17 +68,36 @@ export class V2Runtime { private generations = new Set(); private starts = new Set>(); private closed = false; + private readonly selection: Promise; - constructor(private readonly options: V2RuntimeOptions) {} + constructor(private readonly options: V2RuntimeOptions) { + this.selection = options.selection + ? Promise.resolve(options.selection) + : selectOpenCodeService({ + explicit: + options.externalServer ?? + resolveExternalOpenCodeServer({ + ...globalThis.process.env, + ...options.settings?.env, + }), + env: options.settings?.env, + }); + } async acquire(input: V2RuntimeAcquireOptions = {}): Promise { if (this.closed) throw new Error("OpenCode runtime is closed"); input.signal?.throwIfAborted(); + this.assertBridgePort(); + const selection = await raceProviderRefreshAbort(input.signal, this.selection); let pending: Promise; - if (input.env || input.dedicated) { + if (selection.kind !== "owned") { + this.assertSharedConfiguration(input, selection); + this.current ??= this.startTracked(); + pending = this.current; + } else if (input.env || input.dedicated) { pending = this.startTracked(input.env); } else { - if (input.fresh || !this.current) this.current = this.startTracked(); + if (!this.current) this.current = this.startTracked(); pending = this.current; } let generation: Generation; @@ -97,6 +135,39 @@ export class V2Runtime { return connection; } + private assertBridgePort(): void { + const port = this.options.settings?.env?.PASEO_OPENCODE_BRIDGE_PORT; + if (!port || !this.options.bridge) return; + const actual = new URL(this.options.bridge.sharedV2Connection().baseUrl).port; + if (Number(port) !== Number(actual)) + throw new Error("PASEO_OPENCODE_BRIDGE_PORT changed; restart Paseo to apply the bridge port"); + } + + private assertSharedConfiguration( + input: V2RuntimeAcquireOptions, + selection: OpenCodeServiceSelection, + ): void { + const connectionEnv = new Set([ + "PASEO_OPENCODE_SERVER_URL", + "PASEO_OPENCODE_SERVER_PASSWORD", + "PASEO_OPENCODE_BRIDGE_URL", + "PASEO_OPENCODE_BRIDGE_PORT", + ]); + if (selection.kind === "discovered") { + connectionEnv.add("XDG_CONFIG_HOME"); + connectionEnv.add("XDG_STATE_HOME"); + connectionEnv.add("OPENCODE_CONFIG_DIR"); + } + const processOverrides = Object.keys(this.options.settings?.env ?? {}).filter( + (key) => !connectionEnv.has(key), + ); + if (input.env || input.dedicated || processOverrides.length) { + throw new Error( + `Custom OpenCode MCP servers or process environment require an isolated server and cannot be used with a shared OpenCode service${processOverrides.length ? `: ${processOverrides.join(", ")}` : ""}.`, + ); + } + } + private lease(generation: Generation, pending: Promise): V2Connection { if (this.closed || !this.generations.has(generation)) throw new Error("OpenCode helper server is no longer running"); @@ -107,7 +178,7 @@ export class V2Runtime { released = true; generation.users -= 1; if (generation.users !== 0) return; - if (this.current === pending) this.current = null; + if (this.current === pending) return; this.generations.delete(generation); await generation.stop(); }; @@ -115,6 +186,9 @@ export class V2Runtime { client: generation.client, release, retain: () => this.lease(generation, pending), + bindSession: generation.bindSession, + unbindSession: generation.unbindSession, + refreshLocation: generation.refreshLocation, exited: generation.exited, }; } @@ -146,6 +220,16 @@ export class V2Runtime { } private async start(env: Record = {}): Promise { + const selection = await this.selection; + if (selection.kind !== "owned") { + const generation: Generation = { + ...(await connectSharedService(selection, this.options)), + users: 0, + }; + this.generations.add(generation); + return generation; + } + const { settings, managedProcesses, logger } = this.options; const launch = await resolveProviderLaunch({ commandConfig: settings?.command, @@ -160,9 +244,20 @@ export class V2Runtime { ...settings?.env, ...env, }; - const decorated = this.options.decorateEnv - ? await this.options.decorateEnv(configured) - : decorateOpenCodeV2Env(configured, await materializeOpenCodeV2Plugin(resolvePaseoHome())); + const bridge = this.options.bridge; + const plugin = bridge + ? await bridge.materializeV2Plugin() + : await materializeOpenCodeV2Plugin(resolvePaseoHome()); + const globalConfig = openCodeConfigDirectory({ ...globalThis.process.env, ...configured }); + const managed = await hasManagedBridge(globalConfig); + if (managed && bridge) + await provisionLocalBridge({ + configDirectory: globalConfig, + artifact: path.join(fileURLToPath(plugin), "server.js"), + }); + const decorated = managed + ? configured + : decorateOpenCodeV2Env(configured, plugin, bridge ? {} : { mode: "structured-only" }); const args = [...launch.args, "serve", "--hostname", "127.0.0.1", "--port", "0"]; const process = spawnProcess(launch.command, args, { cwd, @@ -253,7 +348,13 @@ export class V2Runtime { }, }); await client.server.info({ signal: AbortSignal.timeout(Math.max(1, deadline - Date.now())) }); - const generation: Generation = { client, users: 0, stop, exited }; + const generation: Generation = { + client, + users: 0, + stop, + exited, + ...bridgeBindings(client, bridge), + }; this.generations.add(generation); process.once("exit", () => { this.generations.delete(generation); diff --git a/packages/server/src/server/agent/providers/opencode/v2/service-selection.test.ts b/packages/server/src/server/agent/providers/opencode/v2/service-selection.test.ts new file mode 100644 index 0000000000..876582fb9c --- /dev/null +++ b/packages/server/src/server/agent/providers/opencode/v2/service-selection.test.ts @@ -0,0 +1,55 @@ +import { createServer } from "node:http"; +import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { tmpdir } from "node:os"; +import { expect, test } from "vitest"; +import { selectOpenCodeService } from "./service-selection.js"; + +test("selects the registered service with its credential and ignores stale registration", async () => { + const directory = await mkdtemp(path.join(tmpdir(), "paseo-service-")); + const file = path.join(directory, "service.json"); + let requests = 0; + const server = createServer((request, response) => { + requests++; + if ( + request.headers.authorization !== `Basic ${Buffer.from("opencode:secret").toString("base64")}` + ) { + response.writeHead(401).end(); + return; + } + response.writeHead(200, { "Content-Type": "application/json" }); + response.end(JSON.stringify({ version: "2.0.10", pid: process.pid })); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const address = server.address(); + if (!address || typeof address === "string") throw new Error("No test address"); + const url = `http://127.0.0.1:${address.port}`; + try { + await writeFile( + file, + JSON.stringify({ url, password: "secret", pid: process.pid, version: "2.0.10" }), + ); + expect(await selectOpenCodeService({ file })).toEqual({ + kind: "discovered", + server: { url, password: "secret" }, + }); + expect(requests).toBe(1); + expect( + await selectOpenCodeService({ file, explicit: { url: "http://explicit.test" } }), + ).toEqual({ kind: "explicit", server: { url: "http://explicit.test" } }); + expect(requests).toBe(1); + await writeFile(file, JSON.stringify({ url, password: "secret", pid: process.pid + 1 })); + expect(await selectOpenCodeService({ file })).toEqual({ kind: "owned" }); + } finally { + await new Promise((resolve, reject) => { + server.close((error) => { + if (error) { + reject(error); + return; + } + resolve(); + }); + }); + await rm(directory, { recursive: true, force: true }); + } +}); diff --git a/packages/server/src/server/agent/providers/opencode/v2/service-selection.ts b/packages/server/src/server/agent/providers/opencode/v2/service-selection.ts new file mode 100644 index 0000000000..eeb2cb0994 --- /dev/null +++ b/packages/server/src/server/agent/providers/opencode/v2/service-selection.ts @@ -0,0 +1,43 @@ +import { Service } from "@opencode/client/service"; +import { homedir, networkInterfaces } from "node:os"; +import path from "node:path"; +import type { ExternalOpenCodeServer } from "./external-server.js"; + +export type OpenCodeServiceSelection = + | { kind: "owned" } + | { kind: "explicit" | "discovered"; server: ExternalOpenCodeServer }; + +export async function selectOpenCodeService(input: { + explicit?: ExternalOpenCodeServer; + file?: string; + env?: Record; +}): Promise { + if (input.explicit) return { kind: "explicit", server: input.explicit }; + const state = + input.env?.XDG_STATE_HOME ?? + process.env.XDG_STATE_HOME ?? + path.join(homedir(), ".local", "state"); + const endpoint = await Service.discover({ + file: input.file ?? path.join(state, "opencode", "service.json"), + version: compatibleVersion, + }).catch(() => undefined); + if (!endpoint) return { kind: "owned" }; + if (!isLocalOpenCodeHost(new URL(endpoint.url).hostname)) return { kind: "owned" }; + return { + kind: "discovered", + server: { url: endpoint.url, ...(endpoint.auth ? { password: endpoint.auth.password } : {}) }, + }; +} + +export function isLocalOpenCodeHost(input: string): boolean { + const hostname = input.replace(/^\[|\]$/g, ""); + const localAddresses = Object.values(networkInterfaces()).flatMap((items) => + (items ?? []).map((item) => item.address), + ); + return ["localhost", "127.0.0.1", "::1", "0.0.0.0", "::", ...localAddresses].includes(hostname); +} + +export function compatibleVersion(version: string): boolean { + const match = /^2\.(\d+)\.(\d+)(?:[-+].*)?$/.exec(version); + return Boolean(match && (Number(match[1]) > 0 || Number(match[2]) >= 10)); +} diff --git a/packages/server/src/server/agent/providers/opencode/v2/session.ts b/packages/server/src/server/agent/providers/opencode/v2/session.ts index 9358a14040..a167ec0713 100644 --- a/packages/server/src/server/agent/providers/opencode/v2/session.ts +++ b/packages/server/src/server/agent/providers/opencode/v2/session.ts @@ -131,7 +131,7 @@ export class OpenCodeV2Session implements AgentSession { await this.configureConnection(); const location = { directory: this.config.cwd }; this.modes = modesFromV2((await this.client.agent.list({ location })).data); - this.timeline.messages(await messages(this.client, this.id)); + await this.timeline.messages(await messages(this.client, this.id), () => {}); await this.startStream(); await this.children.reconcile(this.id); } @@ -146,6 +146,7 @@ export class OpenCodeV2Session implements AgentSession { } private async configureConnection() { const location = { directory: this.config.cwd }; + await this.connection.bindSession(this.id, this.config.cwd); await waitForLocationReady({ client: this.client, location, signal: this.abort.signal }); if (this.requiresPaseoPlugin) await awaitPaseoPlugin({ client: this.client, location, signal: this.abort.signal }); @@ -207,6 +208,11 @@ export class OpenCodeV2Session implements AgentSession { if (!this.acquire) throw new Error("OpenCode helper server exited"); await this.stream; await this.sync.catch(() => undefined); + await this.connection + .unbindSession(this.id, this.config.cwd) + .catch((error: unknown) => + this.logger.warn({ error }, "Could not unbind the OpenCode Paseo bridge"), + ); const next = await this.acquire(); if (this.closed) { await next.release(); @@ -261,7 +267,11 @@ export class OpenCodeV2Session implements AgentSession { async *streamHistory() { await this.reconnectIfExited(); const history = new V2Timeline(false); - yield* history.messages(await messages(this.client, this.id)); + const events: AgentStreamEvent[] = []; + await history.messages(await messages(this.client, this.id), (event) => { + events.push(event); + }); + yield* events; } async getRuntimeInfo() { await this.reconnectIfExited(); @@ -382,6 +392,7 @@ export class OpenCodeV2Session implements AgentSession { } async startTurn(prompt: AgentPromptInput, options?: AgentRunOptions) { await this.reconnectIfExited(); + await this.connection.bindSession(this.id, this.config.cwd); return this.turns.startTurn(prompt, options); } steerActiveTurn(prompt: AgentPromptInput, options: SteerActiveTurnOptions): Promise { @@ -417,7 +428,7 @@ export class OpenCodeV2Session implements AgentSession { ]); this.info = info; this.history = history; - for (const event of this.timeline.messages(history)) this.emitTimeline(event); + await this.timeline.messages(history, (event) => this.emitTimeline(event)); await this.permissions.reconcile(this.id); } private async reconcile() { @@ -432,6 +443,7 @@ export class OpenCodeV2Session implements AgentSession { } } private async reconcileConnection() { + await this.connection.bindSession(this.id, this.config.cwd); // Session environments are process-local. Reapply this agent's snapshot before // reconciling a new connection, including event-stream reconnections. if (this.launchEnv) @@ -556,6 +568,11 @@ export class OpenCodeV2Session implements AgentSession { await this.stream; await this.reconnecting?.catch(() => undefined); await this.sync.catch(() => undefined); + await this.connection + .unbindSession(this.id, this.config.cwd) + .catch((error: unknown) => + this.logger.warn({ error }, "Could not unbind the OpenCode Paseo bridge"), + ); this.unbind?.(); try { if (!this.persist) await this.client.session.remove({ sessionID: this.id }); diff --git a/packages/server/src/server/agent/providers/opencode/v2/shared-bridge-plugin.mjs b/packages/server/src/server/agent/providers/opencode/v2/shared-bridge-plugin.mjs new file mode 100644 index 0000000000..4be98bfba9 --- /dev/null +++ b/packages/server/src/server/agent/providers/opencode/v2/shared-bridge-plugin.mjs @@ -0,0 +1,207 @@ +import { STRUCTURED_OUTPUT_TOOL } from "./structured-output-plugin.mjs"; + +// OpenCode owns this plugin for the lifetime of a location. Paseo supplies only +// live, per-session bindings over the authenticated OpenCode RPC channel. +export async function registerSharedBridge(context) { + const state = await import(new URL("./state.mjs", import.meta.url).href); + const { bindings, definitions } = state.stateFor(context.location); + const registrations = new Map(); + let updating = Promise.resolve(); + async function request(binding, pathname, body, allowMissing = false, signal) { + const requestSignal = body === undefined ? AbortSignal.timeout(5_000) : signal; + const response = await fetch(new URL(`/_internal/opencode${pathname}`, binding.baseUrl), { + method: body === undefined ? "GET" : "POST", + headers: { Authorization: `Bearer ${binding.token}`, "Content-Type": "application/json" }, + signal: requestSignal, + ...(body === undefined ? {} : { body: JSON.stringify(body) }), + }); + if (allowMissing && response.status === 404) return null; + const payload = await response.json().catch(() => null); + if (!response.ok) { + const detail = formatErrorDetail(payload?.issues ?? payload?.details); + const message = payload?.error ?? `Paseo tool bridge returned HTTP ${response.status}`; + const error = new Error(detail ? `${message}: ${detail}` : message); + error.status = response.status; + if (detail) error.details = detail; + throw error; + } + return payload; + } + async function find(sessionID) { + const seen = new Set(); + while (sessionID && !seen.has(sessionID)) { + seen.add(sessionID); + const binding = bindings.get(sessionID); + if (binding) return { ...binding, sessionID }; + sessionID = (await context.session.get({ sessionID })).parentID; + } + return null; + } + async function install(binding) { + const manifest = await request(binding, "/tools"); + for (const definition of manifest.tools) await installDefinition(definition); + } + async function installDefinition(definition) { + const signature = JSON.stringify(definition); + const known = definitions.get(definition.name); + if (known && JSON.stringify(known) !== signature) + throw new Error(`Conflicting Paseo tool definition: ${definition.name}`); + const old = registrations.get(definition.name); + if (old) { + if (old.signature !== signature) + throw new Error(`Conflicting Paseo tool definition: ${definition.name}`); + return; + } + const registration = await context.tool.transform((editor) => { + editor.add({ + name: `paseo_${definition.name}`, + description: definition.description, + input: definition.inputSchema, + options: { codemode: false }, + async execute(input, call) { + const scope = await find(call.sessionID); + if (!scope) throw new Error("OpenCode session is not bound to a Paseo agent"); + const result = await request( + scope, + `/sessions/${encodeURIComponent(scope.sessionID)}/tools/${encodeURIComponent(definition.name)}`, + input, + false, + call.signal, + ); + return { + content: result.content.map(toOpenCodeContent), + metadata: { paseoTool: definition.name }, + }; + }, + }); + }); + registrations.set(definition.name, { signature, registration }); + definitions.set(definition.name, definition); + } + async function clearUnusedDefinitions() { + if (bindings.size) return; + await Promise.all( + [...registrations.values()].map(({ registration }) => registration.dispose()), + ); + registrations.clear(); + definitions.clear(); + } + // Reinstall live tools before this plugin generation is made visible. + // Definitions are kept in memory, so unavailable owners cannot delay reload. + for (const definition of definitions.values()) await installDefinition(definition); + const object = { type: "object", additionalProperties: true }; + const rpc = await context.rpc.register( + { + id: "paseo.bridge", + methods: { + bind: { input: object, output: object }, + unbind: { input: object, output: object }, + refresh: { input: object, output: object }, + }, + events: {}, + }, + { + bind: async (input) => { + if ( + typeof input.sessionID !== "string" || + typeof input.baseUrl !== "string" || + typeof input.token !== "string" + ) + throw new Error("Invalid Paseo bridge binding"); + const next = updating + .catch(() => undefined) + .then(async () => { + const previous = bindings.get(input.sessionID); + if ( + previous && + (previous.baseUrl !== input.baseUrl || previous.token !== input.token) + ) { + let active; + try { + active = await request( + previous, + `/sessions/${encodeURIComponent(input.sessionID)}/context`, + undefined, + true, + ); + } catch (error) { + // Refusal or rejected credentials mean this endpoint no longer + // serves the previous binding. Other failures are inconclusive. + if ( + error?.status !== 401 && + error?.cause?.code !== "ECONNREFUSED" && + error?.code !== "ConnectionRefused" + ) + throw error; + } + if (active) + return { error: "OpenCode session is already bound to another Paseo bridge" }; + bindings.delete(input.sessionID); + await clearUnusedDefinitions(); + } + await install(input); + bindings.set(input.sessionID, { baseUrl: input.baseUrl, token: input.token }); + return {}; + }); + updating = next; + return await next; + }, + unbind: async (input) => { + const next = updating + .catch(() => undefined) + .then(async () => { + const binding = bindings.get(input.sessionID); + if (binding && binding.token === input.token && binding.baseUrl === input.baseUrl) + bindings.delete(input.sessionID); + await clearUnusedDefinitions(); + return {}; + }); + updating = next; + await next; + return {}; + }, + refresh: async () => { + await context.provider.reload(); + await context.model.reload(); + await context.agent.reload(); + await context.command.reload(); + await context.skill.reload(); + return {}; + }, + }, + ); + const filter = await context.session.hook("context", async (input) => { + const binding = await find(input.sessionID); + const scope = + binding && + (await request(binding, `/sessions/${encodeURIComponent(binding.sessionID)}/context?tools`)); + const allowed = new Set((scope?.tools ?? []).map((name) => `paseo_${name}`)); + for (const name of Object.keys(input.tools)) { + if (name.startsWith("paseo_") && name !== STRUCTURED_OUTPUT_TOOL && !allowed.has(name)) + delete input.tools[name]; + } + }); + return async () => { + await filter.dispose(); + await rpc.dispose(); + await Promise.all( + [...registrations.values()].map(({ registration }) => registration.dispose()), + ); + }; +} + +function toOpenCodeContent(part) { + if (part.type === "image") + return { type: "file", uri: `data:${part.mimeType};base64,${part.data}`, mime: part.mimeType }; + return part; +} + +function formatErrorDetail(details) { + if (!Array.isArray(details)) return typeof details === "string" ? details : ""; + return details + .map((issue) => { + const path = Array.isArray(issue?.path) && issue.path.length ? issue.path.join(".") : "input"; + return `${path}: ${issue?.message ?? "Invalid value"}`; + }) + .join("; "); +} diff --git a/packages/server/src/server/agent/providers/opencode/v2/shared-bridge.test.ts b/packages/server/src/server/agent/providers/opencode/v2/shared-bridge.test.ts new file mode 100644 index 0000000000..c560fa6558 --- /dev/null +++ b/packages/server/src/server/agent/providers/opencode/v2/shared-bridge.test.ts @@ -0,0 +1,168 @@ +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { expect, test } from "vitest"; +import { z } from "zod"; +import { createTestLogger } from "../../../../../test-utils/test-logger.js"; +import { OpenCodeBridge } from "../bridge.js"; + +interface Binding { + sessionID: string; + baseUrl: string; + token: string; +} +interface TestTool { + name: string; + execute(input: { value: string }, call: { sessionID: string }): Promise; +} +interface TestContext { + sessionID: string; + tools: Record; + system: unknown[]; +} + +test("a shared plugin binds Paseo sessions without involving unrelated sessions", async () => { + const home = await mkdtemp(path.join(tmpdir(), "paseo-shared-bridge-")); + const bridge = new OpenCodeBridge({ paseoHome: home, logger: createTestLogger() }); + const tool = { name: "echo", description: "echo", inputSchema: { value: z.string() } }; + const tools = new Map([[tool.name, tool]]); + bridge.setManifestCatalog({ tools }); + await bridge.start(); + const unbind = bridge.bindSession({ + sessionId: "paseo", + env: {}, + tools: { + tools, + getTool: (name) => tools.get(name), + executeTool: async (_name, input) => ({ + content: [{ type: "text", text: String((input as { value: string }).value) }], + }), + }, + }); + expect(() => bridge.bindSession({ sessionId: "paseo", env: {} })).toThrow("already bound"); + try { + const plugin = { + package: await bridge.materializeV2Plugin(), + options: bridge.sharedV2Connection(), + }; + const module = await import( + pathToFileURL(path.join(fileURLToPath(plugin.package), "server.js")).href + ); + const installed = new Map(); + const hooks: Array<(input: TestContext) => Promise> = []; + const refreshed: string[] = []; + let structured = false; + let rpc: Record Promise> = {}; + const context = { + options: {}, + location: { directory: home }, + provider: { + reload: async () => { + refreshed.push("provider"); + }, + }, + model: { + reload: async () => { + refreshed.push("model"); + }, + }, + agent: { + reload: async () => { + refreshed.push("agent"); + }, + }, + command: { + reload: async () => { + refreshed.push("command"); + }, + }, + skill: { + reload: async () => { + refreshed.push("skill"); + }, + }, + rpc: { + register: async (_definition: unknown, handlers: typeof rpc) => { + rpc = handlers; + return { dispose: async () => {} }; + }, + }, + tool: { + transform: async (fn: (editor: { add(item: TestTool): void }) => void) => { + fn({ add: (item) => installed.set(item.name, item) }); + return { dispose: async () => {} }; + }, + }, + session: { + context: async () => + structured ? [{ type: "user", metadata: { paseoOutputSchema: { type: "string" } } }] : [], + get: async () => ({ parentID: "" }), + hook: async (_name: string, fn: (input: TestContext) => Promise) => { + hooks.push(fn); + return { dispose: async () => {} }; + }, + }, + }; + let dispose = await module.default.setup(context); + await rpc.bind({ sessionID: "paseo", ...plugin.options }); + await rpc.refresh({ sessionID: "paseo", ...plugin.options }); + expect(refreshed).toEqual(["provider", "model", "agent", "command", "skill"]); + await expect( + rpc.bind({ sessionID: "paseo", ...plugin.options, token: "another-daemon" }), + ).resolves.toEqual({ error: "OpenCode session is already bound to another Paseo bridge" }); + const own = { sessionID: "paseo", tools: { paseo_echo: {}, native: {} }, system: [] }; + for (const hook of hooks) await hook(own); + expect(Object.keys(own.tools)).toEqual(["paseo_echo", "native"]); + expect( + await installed.get("paseo_echo")!.execute({ value: "ok" }, { sessionID: "paseo" }), + ).toMatchObject({ content: [{ type: "text", text: "ok" }] }); + await dispose(); + hooks.length = 0; + installed.clear(); + dispose = await module.default.setup(context); + const afterReload = { sessionID: "paseo", tools: { paseo_echo: {}, native: {} }, system: [] }; + for (const hook of hooks) await hook(afterReload); + expect(Object.keys(afterReload.tools)).toEqual(["paseo_echo", "native"]); + expect( + await installed.get("paseo_echo")!.execute({ value: "reloaded" }, { sessionID: "paseo" }), + ).toMatchObject({ content: [{ type: "text", text: "reloaded" }] }); + await bridge.close(); + await dispose(); + hooks.length = 0; + installed.clear(); + dispose = await module.default.setup(context); + const unrelated = { sessionID: "other", tools: { paseo_echo: {}, native: {} }, system: [] }; + for (const hook of hooks) await hook(unrelated); + expect(Object.keys(unrelated.tools)).toEqual(["native"]); + structured = true; + const structuredOnly = { + sessionID: "other", + tools: { paseo_structured_output: {} }, + system: [], + }; + for (const hook of hooks) await hook(structuredOnly); + expect(Object.keys(structuredOnly.tools)).toEqual(["paseo_structured_output"]); + const restarted = new OpenCodeBridge({ + paseoHome: home, + logger: createTestLogger(), + port: Number(new URL(plugin.options.baseUrl).port), + }); + restarted.setManifestCatalog({ tools }); + await restarted.start(); + const releaseRestarted = restarted.bindSession({ sessionId: "paseo", env: {} }); + try { + await expect( + rpc.bind({ sessionID: "paseo", ...restarted.sharedV2Connection() }), + ).resolves.toEqual({}); + } finally { + releaseRestarted(); + await restarted.close(); + } + await dispose(); + } finally { + unbind(); + await bridge.close(); + await rm(home, { recursive: true, force: true }); + } +}); diff --git a/packages/server/src/server/agent/providers/opencode/v2/shared-service.ts b/packages/server/src/server/agent/providers/opencode/v2/shared-service.ts new file mode 100644 index 0000000000..26fcbb7d26 --- /dev/null +++ b/packages/server/src/server/agent/providers/opencode/v2/shared-service.ts @@ -0,0 +1,192 @@ +import { OpenCode } from "@opencode/client"; +import { mkdir } from "node:fs/promises"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import type { Logger } from "pino"; +import type { ProviderRuntimeSettings } from "../../../provider-launch-config.js"; +import type { OpenCodeBridge } from "../bridge.js"; +import { OpenCodeHttpError } from "../http-error.js"; +import { resolveOpenCodeHomeDir } from "../paths.js"; +import { openCodeConfigDirectory, provisionLocalBridge } from "./bridge-provisioning.js"; +import { awaitPaseoPlugin } from "./readiness.js"; +import { + compatibleVersion, + isLocalOpenCodeHost, + type OpenCodeServiceSelection, +} from "./service-selection.js"; +import type { V2Api } from "./api.js"; + +interface SharedServiceOptions { + logger: Logger; + settings?: ProviderRuntimeSettings; + bridge?: OpenCodeBridge; +} + +export interface SharedService { + client: V2Api; + exited: Promise; + stop(): Promise; + bindSession(sessionId: string, cwd: string): Promise; + unbindSession(sessionId: string, cwd: string): Promise; + refreshLocation(cwd: string, signal?: AbortSignal): Promise; +} + +export async function connectSharedService( + selection: Extract, + options: SharedServiceOptions, +): Promise { + const server = selection.server; + const { logger } = options; + const lifetime = new AbortController(); + const closed = new Error(`OpenCode external server connection closed (${server.url})`); + let resolveExited!: (error: Error) => void; + const exited = new Promise((resolve) => { + resolveExited = resolve; + }); + const authorization = server.password + ? `Basic ${Buffer.from(`opencode:${server.password}`).toString("base64")}` + : undefined; + const client = OpenCode.make({ + baseUrl: server.url, + ...(authorization ? { headers: { Authorization: authorization } } : {}), + fetch: async (request, init) => { + const signal = init?.signal + ? AbortSignal.any([init.signal, lifetime.signal]) + : lifetime.signal; + const response = await fetch(request, { ...init, signal }); + const html = response.headers.get("content-type")?.includes("text/html") ?? false; + if (!response.ok || html) { + const requestUrl = request instanceof Request ? request.url : String(request); + throw new OpenCodeHttpError(new URL(requestUrl).pathname, response.status, html); + } + return response; + }, + }); + let info: Awaited>; + try { + info = await client.server.info({ + signal: AbortSignal.any([lifetime.signal, AbortSignal.timeout(30_000)]), + }); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + throw new Error(`Cannot reach OpenCode v2 server at ${server.url}: ${message}`, { + cause: error, + }); + } + if (!compatibleVersion(info.version)) + throw new Error( + `Unsupported OpenCode version ${info.version}; version 2.0.10 or newer is required`, + ); + const bridge = options.bridge; + const pluginDirectory = bridge ? fileURLToPath(await bridge.materializeV2Plugin()) : undefined; + if (selection.kind === "discovered" && pluginDirectory) { + const env = { ...globalThis.process.env, ...options.settings?.env }; + const configDirectory = openCodeConfigDirectory(env); + const home = resolveOpenCodeHomeDir(); + await mkdir(home, { recursive: true }); + const entries = await client.config.get({ location: { directory: home } }); + if ( + !entries.some( + (entry) => + entry.type === "directory" && path.resolve(entry.path) === path.resolve(configDirectory), + ) + ) + throw new Error( + `OpenCode service does not use the expected configuration directory ${configDirectory}; configure the bridge on that service explicitly`, + ); + await provisionLocalBridge({ + configDirectory, + artifact: path.join(pluginDirectory, "server.js"), + }); + } + const advertised = + options.settings?.env?.PASEO_OPENCODE_BRIDGE_URL ?? + globalThis.process.env.PASEO_OPENCODE_BRIDGE_URL; + validateBridgeAddress(selection, bridge, advertised); + const generation: SharedService = { + client, + stop: async () => { + if (lifetime.signal.aborted) return; + lifetime.abort(closed); + resolveExited(closed); + }, + exited, + ...bridgeBindings(client, bridge, advertised, pluginDirectory), + }; + logger.info({ url: server.url }, "Using existing OpenCode v2 server"); + return generation; +} + +function validateBridgeAddress( + selection: Extract, + bridge: OpenCodeBridge | undefined, + advertised: string | undefined, +): void { + if (advertised) { + let bridgeUrl: URL; + try { + bridgeUrl = new URL(advertised); + } catch { + throw new Error("PASEO_OPENCODE_BRIDGE_URL must be an absolute HTTP or HTTPS URL"); + } + if (bridgeUrl.protocol !== "http:" && bridgeUrl.protocol !== "https:") + throw new Error("PASEO_OPENCODE_BRIDGE_URL must be an absolute HTTP or HTTPS URL"); + } + const hostname = new URL(selection.server.url).hostname; + if (bridge && selection.kind === "explicit" && !advertised && !isLocalOpenCodeHost(hostname)) + throw new Error( + "Remote OpenCode requires PASEO_OPENCODE_BRIDGE_URL pointing to a reachable Paseo bridge tunnel and the Paseo plugin installed on the server", + ); +} + +export function bridgeBindings( + client: ReturnType, + bridge: OpenCodeBridge | undefined, + advertised?: string, + pluginDirectory?: string, +): Pick { + return { + bindSession: async (sessionId, cwd) => { + if (!bridge) return; + const location = { directory: cwd }; + let result: Awaited>; + try { + await awaitPaseoPlugin({ client, location }); + result = await client.rpc.call({ + location, + rpcID: "paseo.bridge", + method: "bind", + input: { sessionID: sessionId, ...bridge.sharedV2Connection(advertised) }, + }); + } catch (error) { + throw new Error( + `Cannot connect the Paseo tool bridge to OpenCode. Install the plugin from ${pluginDirectory ?? "Paseo's runtime directory"} and configure a reachable bridge URL: ${error instanceof Error ? error.message : String(error)}`, + { cause: error }, + ); + } + if (result.output && typeof result.output === "object" && "error" in result.output) + throw new Error(String(result.output.error)); + }, + unbindSession: async (sessionId, cwd) => { + if (bridge) + await client.rpc.call( + { + location: { directory: cwd }, + rpcID: "paseo.bridge", + method: "unbind", + input: { sessionID: sessionId, ...bridge.sharedV2Connection(advertised) }, + }, + { signal: AbortSignal.timeout(2_000) }, + ); + }, + refreshLocation: async (cwd, signal) => { + if (!bridge) return; + const location = { directory: cwd }; + await awaitPaseoPlugin({ client, location, signal }); + await client.rpc.call( + { location, rpcID: "paseo.bridge", method: "refresh", input: {} }, + { signal }, + ); + }, + }; +} diff --git a/packages/server/src/server/agent/providers/opencode/v2/state.mjs b/packages/server/src/server/agent/providers/opencode/v2/state.mjs new file mode 100644 index 0000000000..858be8f14a --- /dev/null +++ b/packages/server/src/server/agent/providers/opencode/v2/state.mjs @@ -0,0 +1,11 @@ +// OpenCode reloads the plugin entry point independently from this module. +// Keep live bindings and tool definitions in memory across those reloads. +const locations = new Map(); + +export function stateFor(location) { + const key = JSON.stringify([location.directory, location.workspaceID ?? null]); + if (!locations.has(key)) { + locations.set(key, { bindings: new Map(), definitions: new Map() }); + } + return locations.get(key); +} diff --git a/packages/server/src/server/agent/providers/opencode/v2/streaming.test.ts b/packages/server/src/server/agent/providers/opencode/v2/streaming.test.ts index aa74faa6cf..b8c118f037 100644 --- a/packages/server/src/server/agent/providers/opencode/v2/streaming.test.ts +++ b/packages/server/src/server/agent/providers/opencode/v2/streaming.test.ts @@ -1,3 +1,4 @@ +import { collectTimelineSnapshot } from "../test-utils/v2-timeline.js"; import { V2Timeline } from "./timeline.js"; import type { SessionMessageAssistant } from "@opencode/client"; import { describe, expect, test } from "vitest"; @@ -80,7 +81,7 @@ describe("OpenCode v2 token streaming", () => { } }); - test("deduplicates snapshots before and after deltas using per-type ordinals", () => { + test("deduplicates snapshots before and after deltas using per-type ordinals", async () => { const timeline = new V2Timeline(); const text = { assistantMessageID: "answer", type: "text", ordinal: 0 } as const; const reasoning = { ...text, type: "reasoning" } as const; @@ -99,24 +100,28 @@ describe("OpenCode v2 token streaming", () => { }, { type: "text", text: "Hello" }, ]); - expect(timeline.messages([snapshot])).toMatchObject([{ item: { text: "lo" } }]); + expect(await collectTimelineSnapshot(timeline, [snapshot])).toMatchObject([ + { item: { text: "lo" } }, + ]); expect(timeline.delta({ ...text, delta: "lo" })).toBeNull(); - expect(timeline.messages([snapshot])).toEqual([]); + expect(await collectTimelineSnapshot(timeline, [snapshot])).toEqual([]); expect(timeline.delta({ ...text, delta: "!" })).toMatchObject({ item: { text: "!" } }); - expect(timeline.messages([snapshot])).toEqual([]); + expect(await collectTimelineSnapshot(timeline, [snapshot])).toEqual([]); }); - test("recovers missed fragments from snapshots after reconnect", () => { + test("recovers missed fragments from snapshots after reconnect", async () => { const timeline = new V2Timeline(); const part = { assistantMessageID: "answer", type: "text", ordinal: 0 } as const; timeline.startPart(part); expect(timeline.delta({ ...part, delta: "Hel" })).toMatchObject({ item: { text: "Hel" } }); timeline.resetStreams(); expect(timeline.delta({ ...part, delta: "!" })).toBeNull(); - expect(timeline.messages([assistant([{ type: "text", text: "Hello!" }])])).toMatchObject([ - { item: { text: "lo!" } }, - ]); - expect(timeline.messages([assistant([{ type: "text", text: "Hello!" }])])).toEqual([]); + expect( + await collectTimelineSnapshot(timeline, [assistant([{ type: "text", text: "Hello!" }])]), + ).toMatchObject([{ item: { text: "lo!" } }]); + expect( + await collectTimelineSnapshot(timeline, [assistant([{ type: "text", text: "Hello!" }])]), + ).toEqual([]); }); test("withholds streamed prose during a structured-output turn", async () => { @@ -203,3 +208,62 @@ describe("OpenCode v2 token streaming", () => { } }); }); + +test.each(["text", "reasoning"] as const)( + "publishes snapshot %s before a live suffix during image materialization", + async (type) => { + const timeline = new V2Timeline(); + const part = { assistantMessageID: "answer", type, ordinal: 0 }; + timeline.startPart(part); + const emitted: AgentStreamEvent[] = []; + let settled = false; + const snapshot = timeline + .messages( + [ + assistant([ + { type, text: "Hello" }, + { + type: "tool", + id: "screenshot", + name: "paseo_browser_screenshot", + executed: false, + state: { + status: "completed", + input: {}, + content: [ + { type: "file", uri: "data:image/png;base64,aGVsbG8=", mime: "image/png" }, + ], + metadata: {}, + }, + time: { created: 2, ran: 2, completed: 2 }, + }, + ]), + ], + (event) => { + emitted.push(event); + }, + ) + .then(() => { + settled = true; + return undefined; + }); + await new Promise((resolve) => setImmediate(resolve)); + expect(settled).toBe(false); + const delta = timeline.delta({ ...part, delta: "Hello world" }); + if (delta) emitted.push(delta); + await snapshot; + const text = emitted.flatMap((event) => { + if (event.type !== "timeline") return []; + if ( + type === "text" && + event.item.type === "assistant_message" && + !event.item.text.includes("![Image]") + ) + return [event.item.text]; + if (type === "reasoning" && event.item.type === "reasoning") return [event.item.text]; + return []; + }); + expect(text).toEqual(["Hello", " world"]); + expect(text.join("")).toBe("Hello world"); + }, +); diff --git a/packages/server/src/server/agent/providers/opencode/v2/timeline.test.ts b/packages/server/src/server/agent/providers/opencode/v2/timeline.test.ts index d86b9a7dcb..6e9b886c09 100644 --- a/packages/server/src/server/agent/providers/opencode/v2/timeline.test.ts +++ b/packages/server/src/server/agent/providers/opencode/v2/timeline.test.ts @@ -1,3 +1,4 @@ +import { collectTimelineSnapshot } from "../test-utils/v2-timeline.js"; import type { SessionMessageAssistant } from "@opencode/client"; import { execFileSync } from "node:child_process"; import { fileURLToPath } from "node:url"; @@ -15,7 +16,7 @@ function assistant(content: SessionMessageAssistant["content"]): SessionMessageA }; } -test("a completed edit carries the replaced and replacement text", () => { +test("a completed edit carries the replaced and replacement text", async () => { // Captured from OpenCode 2.0.18, whose edit tool takes `path` instead of `filePath`. const edit = assistant([ { @@ -45,7 +46,7 @@ test("a completed edit carries the replaced and replacement text", () => { }, ]); - expect(new V2Timeline().messages([edit])).toMatchObject([ + expect(await collectTimelineSnapshot(new V2Timeline(), [edit])).toMatchObject([ { item: { type: "tool_call", @@ -57,7 +58,7 @@ test("a completed edit carries the replaced and replacement text", () => { ]); }); -test("a tool's image output is shown as an image, not as base64 in the tool output", () => { +test("a tool's image output is shown as an image, not as base64 in the tool output", async () => { const png = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFBQIAX8jx0gAAAABJRU5ErkJggg=="; const screenshot = assistant([ @@ -80,7 +81,7 @@ test("a tool's image output is shown as an image, not as base64 in the tool outp ]); const timeline = new V2Timeline(); - const events = timeline.messages([screenshot]); + const events = await collectTimelineSnapshot(timeline, [screenshot]); expect(JSON.stringify(events)).not.toContain(png); expect(events.map((event) => event.type === "timeline" && event.item)).toMatchObject([ @@ -95,7 +96,7 @@ test("a tool's image output is shown as an image, not as base64 in the tool outp text: expect.stringMatching(/^\n\n!\[Image\]\(file:\/\/.*paseo-attachments.*\.png\)\n\n$/), }, ]); - expect(timeline.messages([screenshot])).toEqual([]); + expect(await collectTimelineSnapshot(timeline, [screenshot])).toEqual([]); }); test("a surrogate pair split across deltas streams back intact", () => { diff --git a/packages/server/src/server/agent/providers/opencode/v2/timeline.ts b/packages/server/src/server/agent/providers/opencode/v2/timeline.ts index 0fdd6f9f40..5596443bbb 100644 --- a/packages/server/src/server/agent/providers/opencode/v2/timeline.ts +++ b/packages/server/src/server/agent/providers/opencode/v2/timeline.ts @@ -55,18 +55,32 @@ export class V2Timeline { return { type: "timeline", provider: "opencode", item, timestamp: new Date().toISOString() }; } - messages(messages: SessionMessageInfo[]): AgentStreamEvent[] { - const events: AgentStreamEvent[] = []; + private pendingMessages: Promise = Promise.resolve(); + + // Publish each cursor advance in the same synchronous step. Buffering snapshot + // events until image IO finishes lets live deltas overtake already committed text. + messages( + messages: SessionMessageInfo[], + publish: (event: AgentStreamEvent) => void, + ): Promise { + const result = this.pendingMessages.then(() => this.publishMessages(messages, publish)); + this.pendingMessages = result.catch(() => {}); + return result; + } + + private async publishMessages( + messages: SessionMessageInfo[], + publish: (event: AgentStreamEvent) => void, + ): Promise { const state: TimelineState = { structured: false, accepted: false }; for (const message of messages) { const timestamp = new Date(message.time.created).toISOString(); const push = (item: AgentTimelineItem) => - events.push({ type: "timeline", provider: "opencode", item, timestamp }); + publish({ type: "timeline", provider: "opencode", item, timestamp }); if (message.type === "user") this.userMessage(message, state, push); - else if (message.type === "assistant") this.assistantMessage(message, state, push); + else if (message.type === "assistant") await this.assistantMessage(message, state, push); else if (message.type === "compaction") this.compactionMessage(message, push); } - return events; } private userMessage( @@ -89,7 +103,7 @@ export class V2Timeline { }); } - private assistantMessage( + private async assistantMessage( message: Extract, state: TimelineState, push: (item: AgentTimelineItem) => void, @@ -99,16 +113,16 @@ export class V2Timeline { // paths address the same cursor entry. let textOrdinal = 0; let reasoningOrdinal = 0; - message.content.forEach((part, partIndex) => { + for (const [partIndex, part] of message.content.entries()) { if (part.type === "tool" && part.name === STRUCTURED_OUTPUT_TOOL) { this.structuredOutputPart(message.id, partIndex, part, state, push); } else if (part.type === "text" || part.type === "reasoning") { const ordinal = part.type === "text" ? textOrdinal++ : reasoningOrdinal++; this.textPart(message.id, part, ordinal, state, push); } else { - this.toolPart(message.id, partIndex, part, push); + await this.toolPart(message.id, partIndex, part, push); } - }); + } } private structuredOutputPart( @@ -156,7 +170,7 @@ export class V2Timeline { else push({ type: "reasoning", text: suffix }); } - private toolPart( + private async toolPart( messageID: string, partIndex: number, part: Extract< @@ -174,16 +188,16 @@ export class V2Timeline { if (item) push(item); // Images follow their tool call as markdown, as Claude and Codex emit them, // so base64 never reaches the tool output. - images.forEach((image, index) => { + for (const [index, image] of images.entries()) { const imageKey = `${key}:image:${index}`; - if (this.content.has(imageKey)) return; + if (this.content.has(imageKey)) continue; this.content.set(imageKey, ""); - const imageItem = renderProviderImageOutputAsAssistantMarkdown( + const imageItem = await renderProviderImageOutputAsAssistantMarkdown( { url: image.uri, mimeType: image.mime }, { materialize: materializeProviderImage }, ); if (imageItem) push(imageItem); - }); + } } private compactionMessage( diff --git a/packages/server/src/server/agent/providers/pi/agent.test.ts b/packages/server/src/server/agent/providers/pi/agent.test.ts index b9f31b61b2..7dc3fd184c 100644 --- a/packages/server/src/server/agent/providers/pi/agent.test.ts +++ b/packages/server/src/server/agent/providers/pi/agent.test.ts @@ -5,11 +5,13 @@ import { mkdirSync, mkdtempSync, openSync, + readFileSync, readSync, + realpathSync, rmSync, writeFileSync, } from "node:fs"; -import { tmpdir } from "node:os"; +import { homedir, tmpdir } from "node:os"; import path from "node:path"; import pino from "pino"; import { setImmediate as waitForImmediate } from "node:timers/promises"; @@ -23,6 +25,7 @@ import { PiRpcAgentSession, transformPiModels, } from "./agent.js"; +import { PiCliRuntime } from "./cli-runtime.js"; import { FakePi } from "./test-utils/fake-pi.js"; import { createPiExtensionHost } from "./extensions/index.js"; import { PiExtensionHost } from "./extensions/host.js"; @@ -2719,6 +2722,7 @@ describe("PiRpcAgentClient", () => { const root = mkdtempSync(path.join(tmpdir(), "paseo-pi-import-config-")); const cwd = path.join(root, "workspace"); const sessionsDir = path.join(root, "sessions"); + mkdirSync(cwd, { recursive: true }); mkdirSync(sessionsDir, { recursive: true }); const sessionFile = path.join(sessionsDir, "20260103_session.jsonl"); writeFileSync( @@ -3532,6 +3536,320 @@ describe("PiRpcAgentClient", () => { }); }); +describe("PiRpcAgentClient history resume", () => { + const BUILTIN_MCP_COMMAND = { + name: "mcp", + source: "extension", + sourceInfo: { path: "builtin:mcp" }, + } as const; + const PASEO_MCP_SERVERS = { + paseo: { type: "http", url: "http://127.0.0.1:6767/mcp/agents" }, + } as const; + + interface ArchivedPiSession { + handle: { + provider: string; + sessionId: string; + nativeHandle: string; + metadata: { cwd: string; model?: string }; + }; + sessionFile: string; + header: Record; + body: string; + originalBytes: Buffer; + } + + function createDeletedFolder(): string { + const folder = mkdtempSync(path.join(tmpdir(), "paseo-pi-deleted-cwd-")); + rmSync(folder, { recursive: true, force: true }); + return folder; + } + + function createFileWhereFolderWas(): string { + const folder = createDeletedFolder(); + writeFileSync(folder, "not a directory"); + onTestFinished(() => rmSync(folder, { force: true })); + return folder; + } + + function createExistingFolder(): string { + const folder = mkdtempSync(path.join(tmpdir(), "paseo-pi-existing-cwd-")); + onTestFinished(() => rmSync(folder, { recursive: true, force: true })); + return folder; + } + + function writeArchivedSession(cwd: string, metadata: { model?: string } = {}): ArchivedPiSession { + const dir = mkdtempSync(path.join(tmpdir(), "paseo-pi-archived-session-")); + onTestFinished(() => rmSync(dir, { recursive: true, force: true })); + const sessionFile = path.join(dir, "2026-01-01_pi-session-1.jsonl"); + const header = { + type: "session", + version: 3, + id: "pi-session-1", + timestamp: "2026-01-01T00:00:00.000Z", + cwd, + }; + const body = [ + JSON.stringify({ + type: "message", + id: "entry-1", + parentId: null, + message: { role: "user", content: "Où est le café ☕ ?" }, + }), + JSON.stringify({ + type: "message", + id: "entry-2", + parentId: "entry-1", + message: { role: "assistant", content: [{ type: "text", text: "Dans la cuisine." }] }, + }), + ] + .map((line) => `${line}\n`) + .join(""); + writeFileSync(sessionFile, `${JSON.stringify(header)}\n${body}`); + return { + handle: { + provider: "pi", + sessionId: "pi-session-1", + nativeHandle: sessionFile, + metadata: { cwd, ...metadata }, + }, + sessionFile, + header, + body, + originalBytes: readFileSync(sessionFile), + }; + } + + function readSessionCopy(sessionFile: string): { header: unknown; body: string } { + const content = readUtf8File(sessionFile); + const headerEnd = content.indexOf("\n"); + return { + header: JSON.parse(content.slice(0, headerEnd)), + body: content.slice(headerEnd + 1), + }; + } + + function resumeArchived( + client: PiRpcAgentClient, + archived: ArchivedPiSession, + purpose: "history" | "interactive", + overrides: Partial = {}, + ): Promise { + return client.resumeSession(archived.handle, overrides, undefined, { purpose }); + } + + function writeFakePiProcess(): { + command: [string, ...string[]]; + readLaunches: () => Array<{ cwd: string; session: string | null }>; + } { + const dir = mkdtempSync(path.join(tmpdir(), "paseo-pi-process-")); + onTestFinished(() => rmSync(dir, { recursive: true, force: true })); + const scriptPath = path.join(dir, "fake-pi.cjs"); + const launchesPath = path.join(dir, "launches.jsonl"); + writeFileSync( + scriptPath, + ` +const fs = require("node:fs"); +const readline = require("node:readline"); +const [launchesPath, ...piArgs] = process.argv.slice(2); +const sessionFlag = piArgs.indexOf("--session"); +const sessionFile = sessionFlag === -1 ? null : piArgs[sessionFlag + 1]; +fs.appendFileSync(launchesPath, JSON.stringify({ cwd: process.cwd(), session: sessionFile }) + "\\n"); +if (sessionFile) { + const header = JSON.parse(fs.readFileSync(sessionFile, "utf8").split("\\n", 1)[0]); + if (header.cwd && !fs.existsSync(header.cwd)) { + fs.writeSync( + 2, + "Stored session working directory does not exist: " + header.cwd + "\\nSession file: " + sessionFile + "\\nCurrent working directory: " + process.cwd() + "\\n", + ); + process.exit(1); + } +} +const models = [ + { provider: "openrouter", id: "a" }, + { provider: "openrouter", id: "b" }, +]; +const state = { + sessionId: "pi-session-1", + sessionFile, + model: models[0], + thinkingLevel: "medium", + isStreaming: false, + isCompacting: false, + messageCount: 0, + pendingMessageCount: 0, +}; +const commands = [${JSON.stringify(BUILTIN_MCP_COMMAND)}]; +function handle(request) { + switch (request.type) { + case "get_state": + return state; + case "get_commands": + return { commands }; + case "get_available_models": + return { models }; + case "set_model": + fs.appendFileSync( + sessionFile, + JSON.stringify({ type: "model_change", id: "model-1", provider: request.provider, modelId: request.modelId }) + "\\n", + ); + state.model = models.find((model) => model.id === request.modelId); + return state.model; + default: + return {}; + } +} +readline.createInterface({ input: process.stdin }).on("line", (line) => { + const request = JSON.parse(line); + process.stdout.write( + JSON.stringify({ id: request.id, type: "response", command: request.type, success: true, data: handle(request) }) + "\\n", + ); +}); +`, + ); + return { + command: [process.execPath, scriptPath, launchesPath], + readLaunches: () => + readUtf8File(launchesPath) + .trim() + .split("\n") + .map((line) => JSON.parse(line) as { cwd: string; session: string | null }), + }; + } + + test.each([ + ["is gone", createDeletedFolder], + ["is now a file", createFileWhereFolderWas], + ])( + "a history resume of an agent whose folder %s starts Pi from the home directory on a copy of its session", + async (_folderState, createFolder) => { + const archived = writeArchivedSession(createFolder()); + const pi = new FakePi(); + + const session = await resumeArchived(createClient(pi), archived, "history"); + onTestFinished(() => session.close()); + + expect(pi.recordedLaunches).toHaveLength(1); + const launch = pi.recordedLaunches[0]!; + expect(launch.cwd).toBe(homedir()); + expect(launch.session).not.toBe(archived.sessionFile); + expect(readSessionCopy(launch.session!)).toEqual({ + header: { ...archived.header, cwd: homedir() }, + body: archived.body, + }); + }, + ); + + test("a history resume of an agent whose folder is gone removes its session copy on close and leaves the original unchanged", async () => { + const archived = writeArchivedSession(createDeletedFolder()); + const pi = new FakePi(); + + const session = await resumeArchived(createClient(pi), archived, "history"); + const sessionCopy = pi.recordedLaunches[0]!.session!; + expect(existsSync(sessionCopy)).toBe(true); + await session.close(); + + expect(existsSync(path.dirname(sessionCopy))).toBe(false); + expect(readFileSync(archived.sessionFile)).toEqual(archived.originalBytes); + }); + + test("a history resume of an agent whose folder is gone persists the original session file while Pi reports the copy", async () => { + const storedCwd = createDeletedFolder(); + const archived = writeArchivedSession(storedCwd); + const pi = new FakePi(); + + const session = await resumeArchived(createClient(pi), archived, "history"); + onTestFinished(() => session.close()); + await session.getRuntimeInfo(); + + expect(pi.latestSession().state.sessionFile).toBe(pi.recordedLaunches[0]!.session); + expect(session.describePersistence()).toMatchObject({ + nativeHandle: archived.sessionFile, + metadata: { cwd: storedCwd }, + }); + }); + + test("a history resume of an agent whose folder is gone removes its session copy when Pi fails to start", async () => { + const archived = writeArchivedSession(createDeletedFolder()); + const pi = new FakePi(); + pi.queueSessionSetup((session) => { + session.getStateError = new Error("Pi RPC process exited with code 1 and signal null"); + }); + + await expect(resumeArchived(createClient(pi), archived, "history")).rejects.toThrow( + "Pi RPC process exited with code 1", + ); + + expect(pi.recordedLaunches).toHaveLength(1); + expect(pi.recordedLaunches[0]!.session).not.toBe(archived.sessionFile); + expect(existsSync(path.dirname(pi.recordedLaunches[0]!.session!))).toBe(false); + }); + + test("a history resume of an agent whose folder is gone checks MCP support from the home directory", async () => { + const archived = writeArchivedSession(createDeletedFolder()); + const pi = new FakePi(); + pi.queueCommands([BUILTIN_MCP_COMMAND]); + + const session = await resumeArchived(createClient(pi), archived, "history", { + mcpServers: PASEO_MCP_SERVERS, + }); + onTestFinished(() => session.close()); + + expect(pi.recordedLaunches.map((launch) => launch.cwd)).toEqual([homedir(), homedir()]); + expect(session.capabilities.supportsMcpServers).toBe(true); + }); + + test("an interactive resume of an agent whose folder is gone still fails in its stored folder", async () => { + const storedCwd = createDeletedFolder(); + const archived = writeArchivedSession(storedCwd); + const pi = new FakePi(); + + await expect(resumeArchived(createClient(pi), archived, "interactive")).rejects.toThrow( + `Stored session working directory does not exist: ${storedCwd}`, + ); + + expect(pi.recordedLaunches).toMatchObject([{ cwd: storedCwd, session: archived.sessionFile }]); + }); + + test("a history resume of an agent whose folder exists keeps the stored folder and session file", async () => { + const storedCwd = createExistingFolder(); + const archived = writeArchivedSession(storedCwd); + const pi = new FakePi(); + + const session = await resumeArchived(createClient(pi), archived, "history"); + onTestFinished(() => session.close()); + + expect(pi.recordedLaunches).toMatchObject([{ cwd: storedCwd, session: archived.sessionFile }]); + }); + + test("a history resume of an agent whose folder is gone opens its session in a real Pi process started from the home directory", async () => { + const archived = writeArchivedSession(createDeletedFolder(), { model: "openrouter/b" }); + const fakePiProcess = writeFakePiProcess(); + const logger = pino({ level: "silent" }); + const client = new PiRpcAgentClient({ + logger, + runtime: new PiCliRuntime({ logger, command: fakePiProcess.command }), + }); + + const session = await resumeArchived(client, archived, "history", { + mcpServers: PASEO_MCP_SERVERS, + }); + onTestFinished(() => session.close()); + + const launches = fakePiProcess.readLaunches(); + const home = realpathSync.native(homedir()); + expect(launches.map((launch) => realpathSync.native(launch.cwd))).toEqual([home, home]); + expect(session.capabilities.supportsMcpServers).toBe(true); + const sessionCopy = launches[1]!.session!; + expect(readUtf8File(sessionCopy)).toContain('"type":"model_change"'); + expect(session.describePersistence()?.nativeHandle).toBe(archived.sessionFile); + + await session.close(); + expect(existsSync(path.dirname(sessionCopy))).toBe(false); + expect(readFileSync(archived.sessionFile)).toEqual(archived.originalBytes); + }); +}); + describe("transformPiModels", () => { test("normalizes labels that include the upstream provider prefix", () => { expect( @@ -3583,3 +3901,174 @@ test("pi runtime safety protects queued replies and runtime-owned activity", asy native.getStateError = new Error("Unable to prove idle"); await expect(session.canStopRuntime!()).rejects.toThrow("Unable to prove idle"); }); + +test("reserves the Pi turn while an image prompt is materialized", async () => { + const { pi, session } = await createSession(); + onTestFinished(() => session.close()); + const first = session.startTurn([ + { type: "image", data: ONE_BY_ONE_PNG_BASE64, mimeType: "image/png" }, + ]); + await expect(session.startTurn("overlapping prompt")).rejects.toThrow("already active"); + await first; + expect(pi.latestSession().prompts).toHaveLength(1); +}); + +test("interrupting Pi during image conversion cancels the admitted turn and permits a follow-up", async () => { + const { pi, session } = await createSession(); + onTestFinished(() => session.close()); + const events: AgentStreamEvent[] = []; + session.subscribe((event) => events.push(event)); + let admitted = false; + const first = session + .startTurn([ + { + type: "image", + data: Buffer.alloc(16 * 1024 * 1024, 51).toString("base64"), + mimeType: "image/png", + }, + ]) + .then((result) => { + admitted = true; + return result; + }); + await waitForImmediate(); + expect(admitted).toBe(false); + expect(pi.latestSession().prompts).toHaveLength(0); + await session.interrupt(); + const followup = await session.startTurn("follow-up after image interrupt"); + const original = await first; + expect(events).toContainEqual( + expect.objectContaining({ type: "turn_canceled", turnId: original.turnId }), + ); + expect(followup.turnId).not.toBe(original.turnId); + expect(pi.latestSession().prompts).toEqual([ + { message: "follow-up after image interrupt", imageCount: 0 }, + ]); +}); + +test("closing Pi during image conversion rejects its pending start", async () => { + const { pi, session } = await createSession(); + const first = session.startTurn([ + { + type: "image", + data: Buffer.alloc(16 * 1024 * 1024, 52).toString("base64"), + mimeType: "image/png", + }, + ]); + const rejected = expect(first).rejects.toThrow("closed"); + await waitForImmediate(); + expect(pi.latestSession().prompts).toHaveLength(0); + await session.close(); + await rejected; +}); + +describe("Pi tool-result images", () => { + test.each([false, true])( + "tool-result images precede the reply and completion (isError=%s)", + async (isError) => { + const { pi, session, events } = await createSession(); + onTestFinished(() => session.close()); + const fakeSession = pi.latestSession(); + await session.startTurn("run"); + fakeSession.emit({ + type: "tool_execution_start", + toolCallId: "shot-1", + toolName: "screenshot", + args: {}, + }); + fakeSession.emit({ + type: "tool_execution_end", + toolCallId: "shot-1", + toolName: "screenshot", + result: { + content: [ + { type: "text", text: "captured" }, + { type: "image", data: Buffer.from("hello").toString("base64"), mimeType: "image/png" }, + ], + structuredContent: { + type: "image", + data: Buffer.from("hello").toString("base64"), + mimeType: "image/png", + note: "captured", + }, + }, + isError, + }); + fakeSession.emit({ + type: "message_update", + assistantMessageEvent: { type: "text_delta", delta: "Image read complete." }, + }); + fakeSession.finishTurn(); + await events.nextTurnCompletion(); + + const items = events.timelineItems(); + const toolIndex = items.findIndex( + (item) => + item.type === "tool_call" && + item.callId === "shot-1" && + item.status === (isError ? "failed" : "completed"), + ); + expect(toolIndex).toBeGreaterThanOrEqual(0); + // Base64 must never reach the tool output stringifier. + expect(JSON.stringify(items[toolIndex])).not.toContain( + Buffer.from("hello").toString("base64"), + ); + expect(items.slice(toolIndex + 1)).toEqual([ + expect.objectContaining({ + type: "assistant_message", + text: expect.stringContaining("![Image]("), + }), + expect.objectContaining({ type: "assistant_message", text: "Image read complete." }), + ]); + expect(events.timelineAndCompletionEvents().at(-1)).toEqual({ type: "turn_completed" }); + }, + ); +}); + +test("Pi image rendering preserves turn ownership across an interrupt and follow-up", async () => { + const { pi, session, events } = await createSession(); + onTestFinished(() => session.close()); + const emitted: AgentStreamEvent[] = []; + session.subscribe((event) => emitted.push(event)); + const native = pi.latestSession(); + const first = await session.startTurn("read image"); + native.emit({ + type: "tool_execution_end", + toolCallId: "large-image", + toolName: "screenshot", + result: { + content: [ + { + type: "image", + data: Buffer.alloc(8 * 1024 * 1024, 73).toString("base64"), + mimeType: "image/png", + }, + ], + }, + isError: false, + }); + native.finishTurn(); + await session.interrupt(); + const followup = await session.startTurn("follow-up after image"); + await waitForImmediate(); + await waitForImmediate(); + await expect + .poll(() => + events + .timelineItems() + .some((item) => item.type === "assistant_message" && item.text.includes("![Image](")), + ) + .toBe(true); + expect(events.turnCompletedEvents().some((event) => event.turnId === followup.turnId)).toBe( + false, + ); + const imageEvent = emitted.find( + (event) => + event.type === "timeline" && + event.item.type === "assistant_message" && + event.item.text.includes("![Image]("), + ); + expect(imageEvent).toMatchObject({ turnId: first.turnId }); + native.finishTurn(); + await events.nextTurnCompletion(); +}); diff --git a/packages/server/src/server/agent/providers/pi/agent.ts b/packages/server/src/server/agent/providers/pi/agent.ts index 881f8cbb29..8051c57fa9 100644 --- a/packages/server/src/server/agent/providers/pi/agent.ts +++ b/packages/server/src/server/agent/providers/pi/agent.ts @@ -2,7 +2,7 @@ import { mapCustomMessageToToolCall } from "../custom-message.js"; import { randomUUID } from "node:crypto"; import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { homedir, tmpdir } from "node:os"; -import { join, resolve as resolvePath } from "node:path"; +import { basename, join, resolve as resolvePath } from "node:path"; import type { Logger } from "pino"; import stripAnsi from "strip-ansi"; import { z } from "zod"; @@ -22,6 +22,7 @@ import { type AgentPersistenceHandle, type AgentPromptInput, type AgentProvider, + type AgentResumeSessionOptions, type AgentRunOptions, type AgentRunResult, type AgentRuntimeInfo, @@ -64,15 +65,24 @@ import { streamPiHistory, type PiCapturedUserMessageEntry, } from "./history-mapper.js"; -import { materializeProviderImage } from "../provider-image-output.js"; +import { + materializeProviderImage, + renderProviderImageOutputAsAssistantMarkdown, + type ProviderImageOutput, +} from "../provider-image-output.js"; import { PiCliRuntime } from "./cli-runtime.js"; import { createPiExtensionHost, piExtensionRuntimeBridge, type PiExtensionEventOutput, } from "./extensions/index.js"; +import { resolveResumeProcessCwd } from "../resume-process-cwd.js"; import { revertPiConversation } from "./rewind.js"; -import { listPiImportableSessions, readPiImportSessionConfig } from "./session-descriptor.js"; +import { + copyPiSessionFileWithCwd, + listPiImportableSessions, + readPiImportSessionConfig, +} from "./session-descriptor.js"; import type { PiRuntime, PiRuntimeSession, PiStartSessionInput } from "./runtime.js"; import type { PiAgentSessionEvent, @@ -89,6 +99,7 @@ import { mapToolDetail, parseToolArgs, parseToolResult, + splitPiToolResultImages, type PiToolResult, type PiTrackedToolCall, } from "./tool-call-mapper.js"; @@ -240,6 +251,7 @@ interface PiRpcAgentSessionOptions { initialState: PiSessionState; capabilities: AgentCapabilityFlags; currentModeId?: string | null; + persistedSessionFile?: string; cleanup?: () => void; extensionTimeoutMs?: number; logger: Logger; @@ -367,9 +379,9 @@ function piModelSupportsImageInput(model: PiModel | null | undefined): boolean { return model?.input?.includes("image") === true; } -function renderTextOnlyImageHint(image: { data: string; mimeType: string }): string { +async function renderTextOnlyImageHint(image: { data: string; mimeType: string }): Promise { try { - const materialized = materializeProviderImage({ + const materialized = await materializeProviderImage({ data: image.data, mimeType: image.mimeType, }); @@ -379,10 +391,10 @@ function renderTextOnlyImageHint(image: { data: string; mimeType: string }): str } } -function convertPromptInput( +async function convertPromptInput( prompt: AgentPromptInput, options: { model: PiModel | null | undefined }, -): PiPromptPayload { +): Promise { if (typeof prompt === "string") { return { text: prompt }; } @@ -405,7 +417,7 @@ function convertPromptInput( mimeType: block.mimeType, }); } else { - textParts.push(renderTextOnlyImageHint(block)); + textParts.push(await renderTextOnlyImageHint(block)); } continue; } @@ -487,13 +499,14 @@ function buildResumeConfig( function buildResumeStartInput(input: { resumeConfig: PiResumeConfig; + processCwd: string; sessionFile: string; launchContext: AgentLaunchContext | undefined; mcpConfigFile: PiTempFile | null; paseoExtension: PiTempFile | null; }): PiStartSessionInput { return { - cwd: input.resumeConfig.cwd, + cwd: input.processCwd, env: input.launchContext?.env, session: input.sessionFile, thinkingOptionId: normalizePiThinkingOption(input.resumeConfig.thinkingOptionId) ?? undefined, @@ -613,6 +626,19 @@ function createPiMcpConfigFile( }; } +async function createPiSessionCopy(sessionFile: string, cwd: string): Promise { + const dir = mkdtempSync(join(tmpdir(), "paseo-pi-session-")); + const cleanup = () => rmSync(dir, { recursive: true, force: true }); + const filePath = join(dir, basename(sessionFile)); + try { + await copyPiSessionFileWithCwd({ sourceFile: sessionFile, targetFile: filePath, cwd }); + } catch (error) { + cleanup(); + throw error; + } + return { path: filePath, cleanup }; +} + function createPiPaseoExtensionFile({ systemPrompt, mcpServers = {}, @@ -1201,6 +1227,7 @@ export class PiRpcAgentSession implements AgentSession { private closed = false; private readonly closeController = new AbortController(); private readonly pendingExtensionHydrations = new Set>(); + private pendingOutput: Promise | null = null; // Pi publishes the terminal before acknowledging abort. Autonomous runs have no // turn ID; retain their errors too until the cancellation request settles. private interruptingTurn: { turnId: string | undefined; error: string | null } | null = null; @@ -1226,6 +1253,7 @@ export class PiRpcAgentSession implements AgentSession { this.capabilities = options.capabilities; this.provider = PI_PROVIDER; this.currentModeId = options.currentModeId ?? null; + this.persistedSessionFile = options.persistedSessionFile; this.cleanup = options.cleanup; this.extensionTimeoutMs = options.extensionTimeoutMs ?? DEFAULT_PI_EXTENSION_RESULT_TIMEOUT_MS; this.logger = options.logger; @@ -1256,6 +1284,7 @@ export class PiRpcAgentSession implements AgentSession { private readonly runtimeSession: PiRuntimeSession; private readonly config: AgentSessionConfig; + private readonly persistedSessionFile?: string; private readonly cleanup?: () => void; private readonly extensionTimeoutMs: number; @@ -1280,7 +1309,6 @@ export class PiRpcAgentSession implements AgentSession { throw new Error("A Pi turn is already active"); } - const payload = convertPromptInput(prompt, { model: this.state.model }); const turnId = randomUUID(); this.activeTurnId = turnId; this.usagePoller.startTurn(); @@ -1292,6 +1320,9 @@ export class PiRpcAgentSession implements AgentSession { this.activePromptRequestId = null; this.pendingSteerSubmissions.length = 0; this.clearNoTurnBuffers(); + const payload = await convertPromptInput(prompt, { model: this.state.model }); + if (this.closed) throw new Error("Pi session is closed"); + if (this.activeTurnId !== turnId) return { turnId }; this.activeNoTurnPromptText = payload.text; const shouldProbeForNoTurnPrompt = this.parseSlashCommandInput(payload.text) !== null; @@ -1363,7 +1394,9 @@ export class PiRpcAgentSession implements AgentSession { if (this.closed || this.activeTurnId !== options.expectedTurnId) { return { status: "unavailable" }; } - const payload = convertPromptInput(prompt, { model: this.state.model }); + const payload = await convertPromptInput(prompt, { model: this.state.model }); + if (this.closed || this.activeTurnId !== options.expectedTurnId) + return { status: "unavailable" }; // Pi rejects steer RPCs that are extension commands, so slash inputs keep the // interrupt-and-replace fallback where they can run directly. if (this.parseSlashCommandInput(payload.text)) { @@ -1486,7 +1519,7 @@ export class PiRpcAgentSession implements AgentSession { return { provider: this.provider, sessionId: this.state.sessionId, - nativeHandle: this.state.sessionFile, + nativeHandle: this.persistedSessionFile ?? this.state.sessionFile, metadata: { cwd: this.config.cwd, ...(this.config.model ? { model: this.config.model } : {}), @@ -1598,6 +1631,7 @@ export class PiRpcAgentSession implements AgentSession { this.pendingExtensionUiRequests.size || this.pendingExtensionResults.size || this.pendingExtensionHydrations.size || + this.pendingOutput || this.pendingSteerSubmissions.length || this.pendingNoTurnOutputs.length || this.interruptingTurn @@ -1618,7 +1652,7 @@ export class PiRpcAgentSession implements AgentSession { try { await this.runtimeSession.close(); } finally { - await Promise.all(this.pendingExtensionHydrations); + await Promise.all([this.pendingOutput, ...this.pendingExtensionHydrations]); this.rejectAllExtensionResults(new Error("Pi session closed")); this.cleanup?.(); } @@ -1682,9 +1716,31 @@ export class PiRpcAgentSession implements AgentSession { } private emit(event: AgentStreamEvent): void { - for (const subscriber of this.subscribers) { - subscriber(event); + if (this.pendingOutput) { + this.emitAsync(() => Promise.resolve([event])); + return; } + this.publish(event); + } + + private publish(event: AgentStreamEvent): void { + for (const subscriber of this.subscribers) subscriber(event); + } + + // Keep timeline order while images are materialized, without delaying provider state changes. + private emitAsync(render: () => Promise): void { + const pending = (this.pendingOutput ?? Promise.resolve()) + .then(render) + .then((events) => { + if (!this.closed) for (const event of events) this.publish(event); + return undefined; + }) + .catch((error) => this.logger.error({ err: error }, "Pi output rendering failed")); + this.pendingOutput = pending; + void pending.then(() => { + if (this.pendingOutput === pending) this.pendingOutput = null; + return undefined; + }); } private emitExtensionOutput(output: PiExtensionEventOutput | undefined, turnId?: string): void { @@ -2311,8 +2367,11 @@ export class PiRpcAgentSession implements AgentSession { this.activeToolCalls.get(event.toolCallId) ?? parseToolArgs(event.toolName, null); this.activeToolCalls.delete(event.toolCallId); - const result = parseToolResult(event.result); - const error = event.isError ? event.result : null; + // Pull image blocks out of the result so base64 never reaches the tool output, then render + // each one as an assistant_message markdown image after the tool_call (mirroring the Claude + // provider, upstream #1717). + const { images, result } = splitPiToolResultImages(parseToolResult(event.result)); + const error = event.isError ? result : null; const status = event.isError ? "failed" : "completed"; this.extensionHost.onToolEnd({ callId: event.toolCallId, @@ -2322,6 +2381,30 @@ export class PiRpcAgentSession implements AgentSession { result, }); this.emitToolCallEvent(event.toolCallId, toolCall, status, result, error); + if (images.length === 0) return; + const turnId = this.currentTurnIdForEvent(); + this.emitAsync(() => this.renderToolResultImages(images, turnId)); + } + + private async renderToolResultImages( + images: ProviderImageOutput[], + turnId: string | undefined, + ): Promise { + const events: AgentStreamEvent[] = []; + for (const image of images) { + const imageItem = await renderProviderImageOutputAsAssistantMarkdown(image, { + materialize: materializeProviderImage, + }); + if (imageItem && !this.closed) { + events.push({ + type: "timeline", + provider: this.provider, + turnId, + item: imageItem, + }); + } + } + return events; } private emitCompactionTimeline(input: { @@ -2585,6 +2668,7 @@ export class PiRpcAgentClient implements AgentClient { handle: AgentPersistenceHandle, overrides?: Partial, launchContext?: AgentLaunchContext, + options?: AgentResumeSessionOptions, ): Promise { const sessionFile = handle.nativeHandle; if (!sessionFile) { @@ -2593,6 +2677,7 @@ export class PiRpcAgentClient implements AgentClient { const persistenceMetadata = parsePersistenceMetadata(handle.metadata); const resumeConfig = buildResumeConfig(persistenceMetadata, overrides, this.provider); + const processCwd = await resolveResumeProcessCwd(resumeConfig.cwd, options?.purpose); const providerOptions = PiProviderOptionsSchema.parse( resumeConfig.config.providerOptions ?? {}, @@ -2603,7 +2688,7 @@ export class PiRpcAgentClient implements AgentClient { ...launchContext?.env, }; const mcp = await this.prepareMcpInjection( - resumeConfig.cwd, + processCwd, resumeConfig.config.mcpServers, mcpEnv, runtime, @@ -2616,20 +2701,29 @@ export class PiRpcAgentClient implements AgentClient { ), mcpServers: mcp?.kind === "builtin" ? mcp.servers : undefined, }); + const tempFiles = mcpConfigFile ? [mcpConfigFile, paseoExtension] : [paseoExtension]; + const cleanupTempFiles = () => { + for (const tempFile of tempFiles) tempFile.cleanup(); + }; + let sessionCopy: PiTempFile | null = null; let runtimeSession: PiRuntimeSession; try { + if (processCwd !== resumeConfig.cwd) { + sessionCopy = await createPiSessionCopy(sessionFile, processCwd); + tempFiles.push(sessionCopy); + } runtimeSession = await runtime.startSession( buildResumeStartInput({ resumeConfig, - sessionFile, + processCwd, + sessionFile: sessionCopy?.path ?? sessionFile, launchContext, mcpConfigFile, paseoExtension, }), ); } catch (error) { - mcpConfigFile?.cleanup(); - paseoExtension?.cleanup(); + cleanupTempFiles(); throw error; } try { @@ -2642,15 +2736,15 @@ export class PiRpcAgentClient implements AgentClient { }, initialState, capabilities: capabilitiesForSession(mcp !== null), - cleanup: combineCleanup([mcpConfigFile?.cleanup, paseoExtension?.cleanup]), + persistedSessionFile: sessionCopy ? sessionFile : undefined, + cleanup: cleanupTempFiles, extensionTimeoutMs: providerOptions.extensionTimeoutMs, logger: this.logger, usagePollScheduler: this.usagePollScheduler, }); } catch (error) { await runtimeSession.close().catch(() => undefined); - mcpConfigFile?.cleanup(); - paseoExtension?.cleanup(); + cleanupTempFiles(); throw error; } } diff --git a/packages/server/src/server/agent/providers/pi/extensions/child-session.ts b/packages/server/src/server/agent/providers/pi/extensions/child-session.ts index 2013b831be..0c7c7df9aa 100644 --- a/packages/server/src/server/agent/providers/pi/extensions/child-session.ts +++ b/packages/server/src/server/agent/providers/pi/extensions/child-session.ts @@ -21,11 +21,11 @@ export function mapPiChildSession( return new PiChildSessionFollower(id, file, maxBytes).readNew(); } -function mapChildLine( +async function mapChildLine( mapper: PiHistoryMapper, id: string, line: string, -): ProviderSubagentInputEvent[] { +): Promise { let entry: { message?: PiAgentMessage; timestamp?: string }; try { entry = JSON.parse(line); @@ -33,7 +33,7 @@ function mapChildLine( return []; } if (!entry.message || typeof entry.message !== "object" || !("role" in entry.message)) return []; - return mapper.mapMessages([entry.message]).flatMap((mapped) => + return (await mapper.mapMessages([entry.message])).flatMap((mapped) => mapped.type === "timeline" ? [ { @@ -83,7 +83,10 @@ export class PiChildSessionFollower { const events: ProviderSubagentInputEvent[] = []; for (const line of data.subarray(0, lastNewline).toString("utf8").split("\n")) { if (this.items >= MAX_ITEMS) break; - const mapped = mapChildLine(this.mapper, this.id, line).slice(0, MAX_ITEMS - this.items); + const mapped = (await mapChildLine(this.mapper, this.id, line)).slice( + 0, + MAX_ITEMS - this.items, + ); this.items += mapped.length; events.push(...mapped); } diff --git a/packages/server/src/server/agent/providers/pi/extensions/edxeth-pi-subagents/fixtures/background-child-session.jsonl b/packages/server/src/server/agent/providers/pi/extensions/edxeth-pi-subagents/fixtures/background-child-session.jsonl new file mode 100644 index 0000000000..ed668e807f --- /dev/null +++ b/packages/server/src/server/agent/providers/pi/extensions/edxeth-pi-subagents/fixtures/background-child-session.jsonl @@ -0,0 +1,8 @@ +{"type": "session", "version": 3, "id": "e56a0006-f421-45be-9aef-e4019db1cf24", "timestamp": "2026-10-21T13:05:57.384Z", "cwd": "/tmp/paseo-edxeth-fixture/lean/workspace", "name": "[marker] Fixture marker verification", "parentSession": "/tmp/paseo-edxeth-fixture/lean/sessions/2026-10-21T13-05-53-085Z_01a15e91-73bd-7282-82c6-d3974711a941.jsonl"} +{"type": "custom", "customType": "pi-subagents_launch_metadata", "data": {"version": 1, "timestamp": "2026-10-21T13:05:57.385Z", "name": "fixture-marker", "title": "Fixture marker verification", "sessionTitle": "[marker] Fixture marker verification", "agent": "marker", "mode": "background", "sessionMode": "lineage-only", "autoExit": true, "parentClosePolicy": "terminate", "reportContextUsage": true, "async": true, "model": "openai-codex/gpt-5.6-sol", "thinking": "high", "modelRef": "openai-codex/gpt-5.6-sol:high", "definitionModel": "openai-codex/gpt-5.6-sol", "definitionThinking": "high", "allowModelOverride": true, "modelSource": "agent", "tools": "read", "denyTools": ["subagent", "subagent_resume", "subagent_kill"], "spawnableAgents": [], "spawnBudget": null, "extensions": [], "noContextFiles": false, "inheritAppendSystem": false, "noSession": false, "trustProject": false, "agentConfigDir": "/tmp/paseo-edxeth-fixture/lean/agent", "cwd": "/tmp/paseo-edxeth-fixture/lean/workspace", "boundarySystemPrompt": false}, "id": "57355eeb", "parentId": null, "timestamp": "2026-10-21T13:05:57.386Z"} +{"type": "session_info", "id": "847415e4", "parentId": "57355eeb", "timestamp": "2026-10-21T13:05:57.566Z", "name": "[marker] Fixture marker verification"} +{"type": "model_change", "id": "d4ad59be", "parentId": "847415e4", "timestamp": "2026-10-21T13:05:57.672Z", "provider": "openai-codex", "modelId": "gpt-5.6-sol"} +{"type": "thinking_level_change", "id": "7f6bf9d2", "parentId": "d4ad59be", "timestamp": "2026-10-21T13:05:57.672Z", "thinkingLevel": "high"} +{"type": "message", "id": "737b762e", "parentId": "6b436446", "timestamp": "2026-10-21T13:05:57.679Z", "message": {"role": "user", "content": [{"type": "text", "text": "\n\n\nReturn only the exact marker supplied by the user. Do not use tools.\n\nComplete your task autonomously.\n\nReturn only PASEO_EDXETH_LEAN_OK\n\nYour FINAL assistant message should summarize what you accomplished.\n\n"}], "timestamp": 1792587957678}} +{"type": "message", "id": "100b110d", "parentId": "737b762e", "timestamp": "2026-10-21T13:06:02.050Z", "message": {"role": "assistant", "content": [{"type": "text", "text": "PASEO_EDXETH_LEAN_OK"}], "api": "openai-codex-responses", "provider": "openai-codex", "model": "gpt-5.6-sol", "usage": {"input": 1713, "output": 13, "cacheRead": 0, "cacheWrite": 0, "reasoning": 0, "totalTokens": 1726, "cost": {"input": 0.006852, "output": 0.00026000000000000003, "cacheRead": 0, "cacheWrite": 0, "total": 0.007111999999999999}}, "stopReason": "stop", "timestamp": 1792587957684, "responseId": "resp_0bc8bfaee079148a016ad8b8b7edb08191924676ed8dcfd447", "rawStopReason": "completed"}} +{"type": "custom", "customType": "pi-subagent-completion", "data": {"reason": "normal"}, "id": "80bbd3bb", "parentId": "100b110d", "timestamp": "2026-10-21T13:06:02.054Z"} diff --git a/packages/server/src/server/agent/providers/pi/extensions/edxeth-pi-subagents/fixtures/background.json b/packages/server/src/server/agent/providers/pi/extensions/edxeth-pi-subagents/fixtures/background.json new file mode 100644 index 0000000000..fe4913f6b6 --- /dev/null +++ b/packages/server/src/server/agent/providers/pi/extensions/edxeth-pi-subagents/fixtures/background.json @@ -0,0 +1,263 @@ +{ + "provenance": { + "package": "Zeno2019/pi-subagents-lean", + "version": "2.9.2-lean.1", + "sourceCommit": "e10fe855808abcae193a205ea98f8ccd70d25620", + "piVersion": "0.87.1", + "captureDate": "2026-10-21" + }, + "events": [ + { + "type": "tool_execution_start", + "toolCallId": "call_f28b261de3c6440b953f0f56c3fec7d0|fc_0d35cf51b3ed48b9016ad8b8b4a63c81918a55903d0a4f12cb", + "toolName": "subagent", + "args": { + "agent": "marker", + "name": "fixture-marker", + "title": "Fixture marker verification", + "task": "Return only PASEO_EDXETH_LEAN_OK" + } + }, + { + "type": "tool_execution_end", + "toolCallId": "call_f28b261de3c6440b953f0f56c3fec7d0|fc_0d35cf51b3ed48b9016ad8b8b4a63c81918a55903d0a4f12cb", + "toolName": "subagent", + "result": { + "content": [ + { + "type": "text", + "text": "Sub-agent \"fixture-marker\" launched async with id 1bfdf3b3. Results will be delivered automatically as a steer message when it finishes. Use this exact id if you need to resume or stop this child.\n\nActivity: /home/pi-user/.pi/history/workspace/artifacts/2026-10-21T13-05-57-380Z_db802a71-7bb32177-573971ee-535c/subagents/1bfdf3b3/activity.jsonl\nRun evidence: /home/pi-user/.pi/history/workspace/artifacts/2026-10-21T13-05-57-380Z_db802a71-7bb32177-573971ee-535c/subagents/1bfdf3b3/result.json\nRead these on demand for progress or failure diagnosis; activity is evidence, not a completion verdict." + } + ], + "details": { + "evidence": { + "runId": "1bfdf3b3", + "cwd": "/tmp/paseo-edxeth-fixture/lean/workspace", + "activityFile": "/home/pi-user/.pi/history/workspace/artifacts/2026-10-21T13-05-57-380Z_db802a71-7bb32177-573971ee-535c/subagents/1bfdf3b3/activity.jsonl", + "resultFile": "/home/pi-user/.pi/history/workspace/artifacts/2026-10-21T13-05-57-380Z_db802a71-7bb32177-573971ee-535c/subagents/1bfdf3b3/result.json" + }, + "id": "1bfdf3b3", + "name": "fixture-marker", + "title": "Fixture marker verification", + "task": "Return only PASEO_EDXETH_LEAN_OK", + "agent": "marker", + "sessionFile": "/tmp/paseo-edxeth-fixture/background/child-session.jsonl", + "noSession": false, + "status": "started", + "mode": "background", + "deliveryState": "detached", + "parentClosePolicy": "terminate", + "async": true, + "autoExit": true + } + }, + "isError": false + }, + { + "type": "message_end", + "message": { + "role": "custom", + "customType": "subagent_result", + "content": "Sub-agent \"fixture-marker\" completed (7s).\n\nPASEO_EDXETH_LEAN_OK\n\nSession: /tmp/paseo-edxeth-fixture/background/child-session.jsonl\nResume: pi --session /tmp/paseo-edxeth-fixture/background/child-session.jsonl\n\nSub-agent context: 2K/372K tokens (0%) used at finish.\n\nActivity: /home/pi-user/.pi/history/workspace/artifacts/2026-10-21T13-05-57-380Z_db802a71-7bb32177-573971ee-535c/subagents/1bfdf3b3/activity.jsonl\nRun evidence: /home/pi-user/.pi/history/workspace/artifacts/2026-10-21T13-05-57-380Z_db802a71-7bb32177-573971ee-535c/subagents/1bfdf3b3/result.json\nRead these on demand for progress or failure diagnosis; activity is evidence, not a completion verdict.", + "display": true, + "details": { + "evidence": { + "runId": "1bfdf3b3", + "cwd": "/tmp/paseo-edxeth-fixture/lean/workspace", + "activityFile": "/home/pi-user/.pi/history/workspace/artifacts/2026-10-21T13-05-57-380Z_db802a71-7bb32177-573971ee-535c/subagents/1bfdf3b3/activity.jsonl", + "resultFile": "/home/pi-user/.pi/history/workspace/artifacts/2026-10-21T13-05-57-380Z_db802a71-7bb32177-573971ee-535c/subagents/1bfdf3b3/result.json", + "finalized": true + }, + "id": "1bfdf3b3", + "name": "fixture-marker", + "task": "Return only PASEO_EDXETH_LEAN_OK", + "agent": "marker", + "mode": "background", + "status": "completed", + "deliveryState": "detached", + "parentClosePolicy": "terminate", + "async": true, + "exitCode": 0, + "elapsed": 7, + "outputTokens": 13, + "contextTokens": 1775, + "contextWindow": 372000, + "sessionFile": "/tmp/paseo-edxeth-fixture/background/child-session.jsonl" + }, + "timestamp": 1792587964414 + } + } + ], + "messages": [ + { + "role": "assistant", + "content": [ + { + "type": "toolCall", + "id": "call_f28b261de3c6440b953f0f56c3fec7d0|fc_0d35cf51b3ed48b9016ad8b8b4a63c81918a55903d0a4f12cb", + "name": "subagent", + "arguments": { + "agent": "marker", + "name": "fixture-marker", + "title": "Fixture marker verification", + "task": "Return only PASEO_EDXETH_LEAN_OK" + } + } + ], + "api": "openai-codex-responses", + "provider": "openai-codex", + "model": "gpt-5.6-sol", + "usage": { + "input": 2020, + "output": 43, + "cacheRead": 0, + "cacheWrite": 0, + "reasoning": 0, + "totalTokens": 2063, + "cost": { + "input": 0.00808, + "output": 0.0008600000000000001, + "cacheRead": 0, + "cacheWrite": 0, + "total": 0.00894 + } + }, + "stopReason": "toolUse", + "timestamp": 1792587953256, + "responseId": "resp_0d35cf51b3ed48b9016ad8b8b3698481918f82962b6eaf2788", + "rawStopReason": "completed" + }, + { + "role": "toolResult", + "toolCallId": "call_f28b261de3c6440b953f0f56c3fec7d0|fc_0d35cf51b3ed48b9016ad8b8b4a63c81918a55903d0a4f12cb", + "toolName": "subagent", + "content": [ + { + "type": "text", + "text": "Sub-agent \"fixture-marker\" launched async with id 1bfdf3b3. Results will be delivered automatically as a steer message when it finishes. Use this exact id if you need to resume or stop this child.\n\nActivity: /home/pi-user/.pi/history/workspace/artifacts/2026-10-21T13-05-57-380Z_db802a71-7bb32177-573971ee-535c/subagents/1bfdf3b3/activity.jsonl\nRun evidence: /home/pi-user/.pi/history/workspace/artifacts/2026-10-21T13-05-57-380Z_db802a71-7bb32177-573971ee-535c/subagents/1bfdf3b3/result.json\nRead these on demand for progress or failure diagnosis; activity is evidence, not a completion verdict." + } + ], + "details": { + "evidence": { + "runId": "1bfdf3b3", + "cwd": "/tmp/paseo-edxeth-fixture/lean/workspace", + "activityFile": "/home/pi-user/.pi/history/workspace/artifacts/2026-10-21T13-05-57-380Z_db802a71-7bb32177-573971ee-535c/subagents/1bfdf3b3/activity.jsonl", + "resultFile": "/home/pi-user/.pi/history/workspace/artifacts/2026-10-21T13-05-57-380Z_db802a71-7bb32177-573971ee-535c/subagents/1bfdf3b3/result.json", + "finalized": true + }, + "id": "1bfdf3b3", + "name": "fixture-marker", + "title": "Fixture marker verification", + "task": "Return only PASEO_EDXETH_LEAN_OK", + "agent": "marker", + "sessionFile": "/tmp/paseo-edxeth-fixture/background/child-session.jsonl", + "noSession": false, + "status": "started", + "mode": "background", + "deliveryState": "detached", + "parentClosePolicy": "terminate", + "async": true, + "autoExit": true + }, + "isError": false, + "timestamp": 1792587957399 + }, + { + "role": "assistant", + "content": [ + { + "type": "thinking", + "thinking": "**Identifying need for await keyword**" + }, + { + "type": "text", + "text": "DONE" + } + ], + "api": "openai-codex-responses", + "provider": "openai-codex", + "model": "gpt-5.6-sol", + "usage": { + "input": 2258, + "output": 18, + "cacheRead": 0, + "cacheWrite": 0, + "reasoning": 11, + "totalTokens": 2276, + "cost": { + "input": 0.009032, + "output": 0.00036, + "cacheRead": 0, + "cacheWrite": 0, + "total": 0.009392 + } + }, + "stopReason": "stop", + "timestamp": 1792587957402, + "responseId": "resp_0d35cf51b3ed48b9016ad8b8b602108191a8e8f7fd77fbe5b5", + "rawStopReason": "completed" + }, + { + "role": "custom", + "customType": "subagent_result", + "content": "Sub-agent \"fixture-marker\" completed (7s).\n\nPASEO_EDXETH_LEAN_OK\n\nSession: /tmp/paseo-edxeth-fixture/background/child-session.jsonl\nResume: pi --session /tmp/paseo-edxeth-fixture/background/child-session.jsonl\n\nSub-agent context: 2K/372K tokens (0%) used at finish.\n\nActivity: /home/pi-user/.pi/history/workspace/artifacts/2026-10-21T13-05-57-380Z_db802a71-7bb32177-573971ee-535c/subagents/1bfdf3b3/activity.jsonl\nRun evidence: /home/pi-user/.pi/history/workspace/artifacts/2026-10-21T13-05-57-380Z_db802a71-7bb32177-573971ee-535c/subagents/1bfdf3b3/result.json\nRead these on demand for progress or failure diagnosis; activity is evidence, not a completion verdict.", + "display": true, + "details": { + "evidence": { + "runId": "1bfdf3b3", + "cwd": "/tmp/paseo-edxeth-fixture/lean/workspace", + "activityFile": "/home/pi-user/.pi/history/workspace/artifacts/2026-10-21T13-05-57-380Z_db802a71-7bb32177-573971ee-535c/subagents/1bfdf3b3/activity.jsonl", + "resultFile": "/home/pi-user/.pi/history/workspace/artifacts/2026-10-21T13-05-57-380Z_db802a71-7bb32177-573971ee-535c/subagents/1bfdf3b3/result.json", + "finalized": true + }, + "id": "1bfdf3b3", + "name": "fixture-marker", + "task": "Return only PASEO_EDXETH_LEAN_OK", + "agent": "marker", + "mode": "background", + "status": "completed", + "deliveryState": "detached", + "parentClosePolicy": "terminate", + "async": true, + "exitCode": 0, + "elapsed": 7, + "outputTokens": 13, + "contextTokens": 1775, + "contextWindow": 372000, + "sessionFile": "/tmp/paseo-edxeth-fixture/background/child-session.jsonl" + }, + "timestamp": 1792587964414 + }, + { + "role": "assistant", + "content": [ + { + "type": "text", + "text": "DONE" + } + ], + "api": "openai-codex-responses", + "provider": "openai-codex", + "model": "gpt-5.6-sol", + "usage": { + "input": 389, + "output": 5, + "cacheRead": 2176, + "cacheWrite": 0, + "reasoning": 0, + "totalTokens": 2570, + "cost": { + "input": 0.0015559999999999999, + "output": 0.0001, + "cacheRead": 0.0008704000000000001, + "cacheWrite": 0, + "total": 0.0025264 + } + }, + "stopReason": "stop", + "timestamp": 1792587964417, + "responseId": "resp_0d35cf51b3ed48b9016ad8b8bd0c548191bddd1fe3410a1c82", + "rawStopReason": "completed" + } + ] +} diff --git a/packages/server/src/server/agent/providers/pi/extensions/edxeth-pi-subagents/fixtures/foreground-child-session.jsonl b/packages/server/src/server/agent/providers/pi/extensions/edxeth-pi-subagents/fixtures/foreground-child-session.jsonl new file mode 100644 index 0000000000..a607a1032d --- /dev/null +++ b/packages/server/src/server/agent/providers/pi/extensions/edxeth-pi-subagents/fixtures/foreground-child-session.jsonl @@ -0,0 +1,8 @@ +{"type": "session", "version": 3, "id": "afbea6e0-7858-4ecf-8ef1-e26af9b7d6e0", "timestamp": "2026-10-21T13:05:17.628Z", "cwd": "/tmp/paseo-edxeth-fixture/upstream/workspace", "name": "[marker] Fixture marker verification", "parentSession": "/tmp/paseo-edxeth-fixture/upstream/sessions/2026-10-21T13-05-12-212Z_01a15e90-d414-7243-a701-4eb4b0bec880.jsonl"} +{"type": "custom", "customType": "pi-subagents_launch_metadata", "data": {"version": 1, "timestamp": "2026-10-21T13:05:17.628Z", "name": "fixture-marker", "title": "Fixture marker verification", "sessionTitle": "[marker] Fixture marker verification", "agent": "marker", "mode": "background", "sessionMode": "lineage-only", "autoExit": true, "parentClosePolicy": "terminate", "reportContextUsage": true, "async": false, "model": "openai-codex/gpt-5.6-sol", "thinking": "high", "modelRef": "openai-codex/gpt-5.6-sol:high", "definitionModel": "openai-codex/gpt-5.6-sol", "definitionThinking": "high", "allowModelOverride": true, "modelSource": "agent", "tools": "read", "denyTools": ["subagent", "subagent_resume", "subagent_kill"], "spawnableAgents": [], "spawnBudget": null, "extensions": [], "noContextFiles": false, "inheritAppendSystem": false, "noSession": false, "trustProject": false, "agentConfigDir": "/tmp/paseo-edxeth-fixture/upstream/agent", "cwd": "/tmp/paseo-edxeth-fixture/upstream/workspace", "boundarySystemPrompt": false}, "id": "3f7d3c3f", "parentId": null, "timestamp": "2026-10-21T13:05:17.629Z"} +{"type": "session_info", "id": "6e198450", "parentId": "3f7d3c3f", "timestamp": "2026-10-21T13:05:17.825Z", "name": "[marker] Fixture marker verification"} +{"type": "model_change", "id": "94bf4c0b", "parentId": "6e198450", "timestamp": "2026-10-21T13:05:17.962Z", "provider": "openai-codex", "modelId": "gpt-5.6-sol"} +{"type": "thinking_level_change", "id": "57cc6428", "parentId": "94bf4c0b", "timestamp": "2026-10-21T13:05:17.962Z", "thinkingLevel": "high"} +{"type": "message", "id": "a9e47f08", "parentId": "8c186624", "timestamp": "2026-10-21T13:05:17.970Z", "message": {"role": "user", "content": [{"type": "text", "text": "\n\n\nReturn only the exact marker supplied by the user. Do not use tools.\n\nComplete your task autonomously.\n\nReturn only PASEO_EDXETH_UPSTREAM_OK\n\nYour FINAL assistant message should summarize what you accomplished.\n\n"}], "timestamp": 1792587917968}} +{"type": "message", "id": "bc221a13", "parentId": "a9e47f08", "timestamp": "2026-10-21T13:05:23.476Z", "message": {"role": "assistant", "content": [{"type": "thinking", "thinking": "**Following user file marker exactly**"}, {"type": "text", "text": "PASEO_EDXETH_UPSTREAM_OK"}], "api": "openai-codex-responses", "provider": "openai-codex", "model": "gpt-5.6-sol", "usage": {"input": 1673, "output": 49, "cacheRead": 0, "cacheWrite": 0, "reasoning": 34, "totalTokens": 1722, "cost": {"input": 0.006692, "output": 0.0009800000000000002, "cacheRead": 0, "cacheWrite": 0, "total": 0.007672}}, "stopReason": "stop", "timestamp": 1792587917974, "responseId": "resp_09445c1733d532e7016ad8b8909c908191ba803c059497945e", "rawStopReason": "completed"}} +{"type": "custom", "customType": "pi-subagent-completion", "data": {"reason": "normal"}, "id": "832fc8c9", "parentId": "bc221a13", "timestamp": "2026-10-21T13:05:23.477Z"} diff --git a/packages/server/src/server/agent/providers/pi/extensions/edxeth-pi-subagents/fixtures/foreground.json b/packages/server/src/server/agent/providers/pi/extensions/edxeth-pi-subagents/fixtures/foreground.json new file mode 100644 index 0000000000..c8df8eb5c2 --- /dev/null +++ b/packages/server/src/server/agent/providers/pi/extensions/edxeth-pi-subagents/fixtures/foreground.json @@ -0,0 +1,156 @@ +{ + "provenance": { + "package": "edxeth/pi-subagents", + "version": "2.9.2", + "sourceCommit": "cf6dbf41c17986f3882e6804a68e8fb8282d25e6", + "piVersion": "0.87.1", + "captureDate": "2026-10-21" + }, + "events": [ + { + "type": "tool_execution_start", + "toolCallId": "call_0bc6fc2213cd49aa92950947bde5dd8a|fc_0a0ca4aa78cd296a016ad8b88d018481919eadbf09eb191a1a", + "toolName": "subagent", + "args": { + "agent": "marker", + "name": "fixture-marker", + "title": "Fixture marker verification", + "task": "Return only PASEO_EDXETH_UPSTREAM_OK" + } + }, + { + "type": "tool_execution_end", + "toolCallId": "call_0bc6fc2213cd49aa92950947bde5dd8a|fc_0a0ca4aa78cd296a016ad8b88d018481919eadbf09eb191a1a", + "toolName": "subagent", + "result": { + "content": [ + { + "type": "text", + "text": "Sub-agent \"fixture-marker\" completed (7s).\n\nPASEO_EDXETH_UPSTREAM_OK\n\nSession: /tmp/paseo-edxeth-fixture/foreground/child-session.jsonl\nResume: pi --session /tmp/paseo-edxeth-fixture/foreground/child-session.jsonl\n\nSub-agent context: 2K/372K tokens (0%) used at finish." + } + ], + "details": { + "id": "dd7f94e8", + "name": "fixture-marker", + "agent": "marker", + "status": "completed", + "mode": "background", + "parentClosePolicy": "terminate", + "deliveryState": "awaited", + "async": false, + "autoExit": true, + "exitCode": 0, + "elapsed": 7, + "outputTokens": 49, + "contextTokens": 1777, + "contextWindow": 372000, + "summary": "PASEO_EDXETH_UPSTREAM_OK", + "sessionFile": "/tmp/paseo-edxeth-fixture/foreground/child-session.jsonl" + } + }, + "isError": false + } + ], + "messages": [ + { + "role": "assistant", + "content": [ + { + "type": "toolCall", + "id": "call_0bc6fc2213cd49aa92950947bde5dd8a|fc_0a0ca4aa78cd296a016ad8b88d018481919eadbf09eb191a1a", + "name": "subagent", + "arguments": { + "agent": "marker", + "name": "fixture-marker", + "title": "Fixture marker verification", + "task": "Return only PASEO_EDXETH_UPSTREAM_OK" + } + } + ], + "api": "openai-codex-responses", + "provider": "openai-codex", + "model": "gpt-5.6-sol", + "usage": { + "input": 3256, + "output": 43, + "cacheRead": 0, + "cacheWrite": 0, + "reasoning": 0, + "totalTokens": 3299, + "cost": { + "input": 0.013023999999999999, + "output": 0.0008600000000000001, + "cacheRead": 0, + "cacheWrite": 0, + "total": 0.013883999999999999 + } + }, + "stopReason": "toolUse", + "timestamp": 1792587912428, + "responseId": "resp_0a0ca4aa78cd296a016ad8b88bd52881918cbb9b8326b3060a", + "rawStopReason": "completed" + }, + { + "role": "toolResult", + "toolCallId": "call_0bc6fc2213cd49aa92950947bde5dd8a|fc_0a0ca4aa78cd296a016ad8b88d018481919eadbf09eb191a1a", + "toolName": "subagent", + "content": [ + { + "type": "text", + "text": "Sub-agent \"fixture-marker\" completed (7s).\n\nPASEO_EDXETH_UPSTREAM_OK\n\nSession: /tmp/paseo-edxeth-fixture/foreground/child-session.jsonl\nResume: pi --session /tmp/paseo-edxeth-fixture/foreground/child-session.jsonl\n\nSub-agent context: 2K/372K tokens (0%) used at finish." + } + ], + "details": { + "id": "dd7f94e8", + "name": "fixture-marker", + "agent": "marker", + "status": "completed", + "mode": "background", + "parentClosePolicy": "terminate", + "deliveryState": "awaited", + "async": false, + "autoExit": true, + "exitCode": 0, + "elapsed": 7, + "outputTokens": 49, + "contextTokens": 1777, + "contextWindow": 372000, + "summary": "PASEO_EDXETH_UPSTREAM_OK", + "sessionFile": "/tmp/paseo-edxeth-fixture/foreground/child-session.jsonl" + }, + "isError": false, + "timestamp": 1792587924671 + }, + { + "role": "assistant", + "content": [ + { + "type": "text", + "text": "DONE" + } + ], + "api": "openai-codex-responses", + "provider": "openai-codex", + "model": "gpt-5.6-sol", + "usage": { + "input": 388, + "output": 5, + "cacheRead": 3072, + "cacheWrite": 0, + "reasoning": 0, + "totalTokens": 3465, + "cost": { + "input": 0.001552, + "output": 0.0001, + "cacheRead": 0.0012288000000000002, + "cacheWrite": 0, + "total": 0.0028808 + } + }, + "stopReason": "stop", + "timestamp": 1792587924675, + "responseId": "resp_0a0ca4aa78cd296a016ad8b896af2c81919c0ef586dd50f2f0", + "rawStopReason": "completed" + } + ] +} diff --git a/packages/server/src/server/agent/providers/pi/extensions/edxeth-pi-subagents/index.test.ts b/packages/server/src/server/agent/providers/pi/extensions/edxeth-pi-subagents/index.test.ts new file mode 100644 index 0000000000..86692ab32e --- /dev/null +++ b/packages/server/src/server/agent/providers/pi/extensions/edxeth-pi-subagents/index.test.ts @@ -0,0 +1,336 @@ +import { describe, expect, test } from "vitest"; +import { fileURLToPath } from "node:url"; +import { createPiExtensionHost } from "../index.js"; +import { readSubagentFixture, verifySubagentFixture } from "../subagent-fixture-test.js"; +import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { edxethPiSubagents } from "./index.js"; +import { streamPiHistory } from "../../history-mapper.js"; +import { ProviderSubagentStore } from "../../../../provider-subagents/store.js"; + +const args = { + agent: "scout", + name: "status-scout", + title: "Check child status", + task: "Return the completion marker", +}; + +describe("edxeth/pi-subagents adapter", () => { + test.each(["tool", "notification"])("ends a child that requested help via %s", (delivery) => { + const host = createPiExtensionHost(); + const call = { callId: "spawn-1", toolName: "subagent", args, status: "completed" as const }; + host.mapToolCall({ + ...call, + result: { details: { id: "run-1", name: args.name, status: "started" } }, + }); + const details = { id: "run-1", name: args.name, message: "Please clarify the task" }; + const result = + delivery === "tool" + ? host.mapToolCall({ ...call, result: { details: { ...details, status: "pinged" } } }) + : host.mapCustomMessage({ + role: "custom", + customType: "subagent_ping", + content: "Child requested help and exited", + details, + }); + expect(result?.subagents).toEqual([ + expect.objectContaining({ + type: "upsert", + id: "spawn-1", + status: "canceled", + subtitle: "Needs help", + }), + ]); + }); + + test("leaves unrelated tools and other subagent protocols to their adapters", () => { + const host = createPiExtensionHost(undefined, [edxethPiSubagents]); + const call = { callId: "other", toolName: "subagent", args, status: "completed" as const }; + for (const details of [null, {}, { mode: "single", results: [] }, { id: "run-1" }]) { + expect(host.mapToolCall({ ...call, result: { details } })).toBeUndefined(); + } + expect( + host.mapToolCall({ + ...call, + toolName: "unrelated", + result: { details: { id: "run-1", name: args.name, status: "completed" } }, + }), + ).toBeUndefined(); + for (const details of [{ id: "run-1" }, { id: "run-1", status: "unknown" }]) { + expect( + host.mapCustomMessage({ + role: "custom", + customType: "subagent_result", + content: "Unrecognized result", + details, + }), + ).toBeUndefined(); + } + }); + + test("waits for cancellation after a kill acknowledgement reports stopping", () => { + const host = createPiExtensionHost(); + host.mapToolCall({ + callId: "spawn-1", + toolName: "subagent", + args, + status: "completed", + result: { details: { id: "run-1", name: args.name, status: "started" } }, + }); + const stopping = host.mapToolCall({ + callId: "kill-1", + toolName: "subagent_kill", + args: { id: "run-1" }, + status: "completed", + result: { details: { id: "run-1", name: args.name, status: "stopping" } }, + }); + expect(stopping?.subagents ?? []).toEqual([]); + expect( + host.mapCustomMessage({ + role: "custom", + customType: "subagent_result", + content: "Cancelled", + details: { id: "run-1", status: "cancelled" }, + })?.subagents, + ).toEqual([{ type: "upsert", id: "spawn-1", status: "canceled" }]); + }); + + test("preserves a completion that arrives before its launch acknowledgement", () => { + const host = createPiExtensionHost(); + const early = host.mapCustomMessage({ + role: "custom", + customType: "subagent_result", + content: "Already done", + details: { id: "fast-run", status: "completed" }, + }); + expect(early?.subagents ?? []).toEqual([]); + const started = host.mapToolCall({ + callId: "fast-call", + toolName: "subagent", + args, + status: "completed", + result: { + details: { id: "fast-run", name: args.name, agent: args.agent, status: "started" }, + }, + }); + expect(started?.subagents).toEqual([ + { + type: "upsert", + id: "fast-call", + title: "scout", + description: args.task, + toolCallId: "fast-call", + status: "completed", + }, + ]); + }); + + test.each([ + { details: { status: "completed" }, expected: "completed" }, + { details: { status: "failed" }, expected: "failed" }, + { details: { status: "cancelled" }, expected: "canceled" }, + { details: { error: "Child watcher exited unexpectedly" }, expected: "failed" }, + ])("maps completion $details to $expected", ({ details, expected }) => { + const host = createPiExtensionHost(); + host.mapToolCall({ + callId: "spawn-1", + toolName: "subagent", + args, + status: "completed", + result: { details: { id: "run-1", name: args.name, status: "started" } }, + }); + expect( + host.mapCustomMessage({ + role: "custom", + customType: "subagent_result", + content: "Child result", + details: { id: "run-1", ...details }, + })?.subagents, + ).toEqual([{ type: "upsert", id: "spawn-1", status: expected }]); + }); + + test("a resume gets its own run and reads the retained child session", async () => { + const dir = await mkdtemp(join(tmpdir(), "paseo-edxeth-resume-")); + const file = join(dir, "child.jsonl"); + const host = createPiExtensionHost(); + try { + await writeFile( + file, + JSON.stringify({ + type: "message", + message: { role: "assistant", content: [{ type: "text", text: "RESUMED" }] }, + }) + "\n", + ); + const original = host.mapToolCall({ + callId: "spawn-1", + toolName: "subagent", + args, + status: "completed", + result: { + details: { id: "run-1", name: args.name, status: "completed", sessionFile: file }, + }, + }); + await original?.hydration; + const resumed = host.mapToolCall({ + callId: "resume-1", + toolName: "subagent_resume", + args: { sessionFile: file, task: "Continue" }, + status: "completed", + result: { + details: { id: "run-2", name: args.name, status: "started", sessionFile: file }, + }, + }); + expect(resumed?.childSessions).toEqual([{ id: "resume-1", file }]); + expect(await resumed?.hydration).toEqual([ + { + type: "provider_subagent", + provider: "pi", + event: { + type: "timeline", + id: "resume-1", + item: expect.objectContaining({ type: "assistant_message", text: "RESUMED" }), + }, + }, + ]); + expect( + host.mapCustomMessage({ + role: "custom", + customType: "subagent_result", + content: "Resumed run complete", + details: { id: "run-2", status: "completed", sessionFile: file }, + })?.subagents, + ).toEqual([{ type: "upsert", id: "resume-1", status: "completed" }]); + } finally { + host.close(); + await rm(dir, { recursive: true, force: true }); + } + }); + + test("settles each batched child by run id without creating a parent-call card", () => { + const host = createPiExtensionHost(); + const result = host.mapToolCall({ + callId: "batch-1", + toolName: "subagent", + args: { children: [args, { ...args, agent: "reviewer", name: "status-reviewer" }] }, + status: "completed", + result: { + details: { + status: "batch", + children: [ + { id: "run-1", ...args, mode: "background", status: "completed" }, + { id: "run-2", name: "status-reviewer", agent: "reviewer", status: "started" }, + ], + }, + }, + }); + expect(result?.subagents).toEqual([ + { + type: "upsert", + id: "batch-1:0", + title: "scout", + description: args.task, + toolCallId: "batch-1", + status: "completed", + }, + { + type: "upsert", + id: "batch-1:1", + title: "reviewer", + description: undefined, + toolCallId: "batch-1", + status: "running", + }, + ]); + expect( + host.mapCustomMessage({ + role: "custom", + customType: "subagent_result", + content: "Done", + details: { id: "run-2", status: "completed" }, + })?.subagents, + ).toEqual([{ type: "upsert", id: "batch-1:1", status: "completed" }]); + }); + + test.each([ + { mode: "foreground", statuses: ["running", "completed"] }, + { mode: "background", statuses: ["running", "running", "completed"] }, + ])("settles the captured $mode run live and on replay", async ({ mode, statuses }) => { + const fixture = readSubagentFixture(new URL(`./fixtures/${mode}.json`, import.meta.url), { + from: `/tmp/paseo-edxeth-fixture/${mode}/child-session.jsonl`, + to: fileURLToPath(new URL(`./fixtures/${mode}-child-session.jsonl`, import.meta.url)), + }); + const events = await verifySubagentFixture(fixture); + const updates = events.flatMap(({ event }) => (event.type === "upsert" ? [event] : [])); + expect(updates.map((event) => event.status)).toEqual(statuses); + expect(new Set(updates.map((event) => event.id)).size).toBe(1); + expect(events.some(({ event }) => event.type === "timeline")).toBe(true); + }); + + test.each(["foreground", "background"])( + "restores a completed %s child and its transcript to the consumer store", + async (mode) => { + const fixture = readSubagentFixture(new URL(`./fixtures/${mode}.json`, import.meta.url), { + from: `/tmp/paseo-edxeth-fixture/${mode}/child-session.jsonl`, + to: fileURLToPath(new URL(`./fixtures/${mode}-child-session.jsonl`, import.meta.url)), + }); + const store = new ProviderSubagentStore(); + for await (const event of streamPiHistory("pi", fixture.messages)) { + if (event.type === "provider_subagent") store.apply("parent", "pi", event.event); + } + const children = store.list("parent"); + expect(children).toEqual([expect.objectContaining({ status: "completed", title: "marker" })]); + const transcript = store.fetchTimeline("parent", children[0]!.id); + expect(transcript.rows).toContainEqual( + expect.objectContaining({ + item: expect.objectContaining({ + type: "assistant_message", + text: mode === "foreground" ? "PASEO_EDXETH_UPSTREAM_OK" : "PASEO_EDXETH_LEAN_OK", + }), + }), + ); + }, + ); + + test("settles a synchronous result on the card created when the tool started", () => { + const host = createPiExtensionHost(); + const call = { callId: "spawn-1", toolName: "subagent", args }; + const start = host.mapToolCall({ ...call, status: "running", result: null }); + expect(start?.subagents).toEqual([ + { + type: "upsert", + id: "spawn-1", + title: "scout", + description: args.task, + toolCallId: "spawn-1", + status: "running", + }, + ]); + const end = host.mapToolCall({ + ...call, + status: "completed", + result: { + content: [{ type: "text", text: "DONE" }], + details: { + id: "run-1", + name: args.name, + agent: args.agent, + mode: "background", + status: "completed", + deliveryState: "awaited", + exitCode: 0, + }, + }, + }); + expect(end?.subagents).toEqual([ + { + type: "upsert", + id: "spawn-1", + title: "scout", + description: args.task, + toolCallId: "spawn-1", + status: "completed", + }, + ]); + }); +}); diff --git a/packages/server/src/server/agent/providers/pi/extensions/edxeth-pi-subagents/index.ts b/packages/server/src/server/agent/providers/pi/extensions/edxeth-pi-subagents/index.ts new file mode 100644 index 0000000000..c58f0faf15 --- /dev/null +++ b/packages/server/src/server/agent/providers/pi/extensions/edxeth-pi-subagents/index.ts @@ -0,0 +1,119 @@ +import { z } from "zod"; +import type { PiChildSessionFile, PiExtension } from "../contract.js"; +import type { ProviderSubagentInputEvent } from "../../../../provider-subagents/store.js"; + +const Run = z + .object({ + id: z.string().trim().min(1), + name: z.string().trim().min(1), + agent: z.string().trim().min(1).optional(), + task: z.string().optional(), + status: z.enum(["started", "completed", "failed", "cancelled", "pinged"]), + sessionFile: z.string().trim().min(1).optional(), + }) + .passthrough(); +const Args = z.object({ task: z.string().optional() }).passthrough(); +const Batch = z.object({ status: z.enum(["started", "batch"]), children: z.array(Run).min(1) }); +const Completion = z + .object({ + id: z.string().trim().min(1), + status: z.enum(["completed", "failed", "cancelled", "pinged"]).optional(), + error: z.string().optional(), + sessionFile: z.string().trim().min(1).optional(), + }) + .passthrough(); +const Ping = Completion.extend({ message: z.string() }); + +function childStatus(status: z.infer["status"]) { + if (status === "started") return "running"; + // A ping ends the child process and needs a new resume run. It is not success. + if (status === "cancelled" || status === "pinged") return "canceled"; + return status; +} + +export const edxethPiSubagents: PiExtension = { + id: "edxeth/pi-subagents", + createSession: () => { + const callsByRun = new Map(); + const completions = new Map>(); + const readSessions = new Map(); + const childSession = (id: string, file: string | undefined): PiChildSessionFile[] => { + if (!file || readSessions.get(id) === file) return []; + readSessions.set(id, file); + return [{ id, file }]; + }; + const completeRun = (result: z.infer) => { + const status = result.status ?? (result.error === undefined ? undefined : "failed"); + if (!status) return undefined; + // A fast child can finish before the tool returns its run id. Keep the + // terminal outcome so a later "started" acknowledgement cannot regress it. + completions.set(result.id, { ...result, status }); + const id = callsByRun.get(result.id); + if (!id) return undefined; + const subagents: ProviderSubagentInputEvent[] = [ + { + type: "upsert", + id, + status: childStatus(status), + ...(status === "pinged" ? { subtitle: "Needs help" } : {}), + }, + ]; + return { subagents, childSessions: childSession(id, result.sessionFile) }; + }; + return { + mapToolCall(call) { + const isLaunch = call.toolName === "subagent" || call.toolName === "subagent_resume"; + if (!isLaunch || call.status === "running") return undefined; + const details = typeof call.result === "object" ? call.result?.details : null; + const single = Run.safeParse(details); + let runs: z.infer[]; + if (single.success) { + runs = [single.data]; + } else { + const batch = Batch.safeParse(details); + if (!batch.success) return undefined; + runs = batch.data.children; + } + const args = Args.safeParse(call.args); + const description = args.success ? args.data.task : undefined; + const subagents: ProviderSubagentInputEvent[] = []; + const childSessions: PiChildSessionFile[] = []; + for (const [index, run] of runs.entries()) { + const id = runs.length === 1 ? call.callId : `${call.callId}:${index}`; + const completion = completions.get(run.id); + const status = completion?.status ?? run.status; + callsByRun.set(run.id, id); + subagents.push({ + type: "upsert", + id, + title: run.agent ?? run.name, + description: run.task ?? description, + toolCallId: call.callId, + status: childStatus(status), + ...(status === "pinged" ? { subtitle: "Needs help" } : {}), + }); + childSessions.push(...childSession(id, completion?.sessionFile ?? run.sessionFile)); + } + return { + detail: { + type: "sub_agent", + description, + // COMPAT(subagent-log): remove after 2027-04-30. + log: "", + }, + subagents, + childSessions, + }; + }, + mapCustomMessage(message) { + if (message.customType === "subagent_ping") { + const ping = Ping.safeParse(message.details); + return ping.success ? completeRun({ ...ping.data, status: "pinged" }) : undefined; + } + if (message.customType !== "subagent_result") return undefined; + const parsed = Completion.safeParse(message.details); + return parsed.success ? completeRun(parsed.data) : undefined; + }, + }; + }, +}; diff --git a/packages/server/src/server/agent/providers/pi/extensions/gotgenes-pi-subagents/index.test.ts b/packages/server/src/server/agent/providers/pi/extensions/gotgenes-pi-subagents/index.test.ts index f89a9aefd3..7bb62a9d1f 100644 --- a/packages/server/src/server/agent/providers/pi/extensions/gotgenes-pi-subagents/index.test.ts +++ b/packages/server/src/server/agent/providers/pi/extensions/gotgenes-pi-subagents/index.test.ts @@ -130,6 +130,18 @@ describe("@gotgenes/pi-subagents adapter", () => { .filter((event) => event.event.type === "upsert") .map((event) => (event.event.type === "upsert" ? event.event.status : null)), ).toEqual(["running", "completed"]); + expect( + events.flatMap((event) => (event.event.type === "timeline" ? [event.event] : [])), + ).toEqual([ + { + type: "timeline", + id: "call_502323", + item: { + type: "assistant_message", + text: "Agent completed in 4.7s (1 tool uses, 9.0k token).\nAgent ID: 848583f5-6749-4a1\n\nThe workspace is empty.", + }, + }, + ]); }); test("correlates a background notification and result collection", async () => { const source = readSubagentFixture(new URL("./fixtures/background.json", import.meta.url)); diff --git a/packages/server/src/server/agent/providers/pi/extensions/gotgenes-pi-subagents/index.ts b/packages/server/src/server/agent/providers/pi/extensions/gotgenes-pi-subagents/index.ts index e1869705f8..9383911c3d 100644 --- a/packages/server/src/server/agent/providers/pi/extensions/gotgenes-pi-subagents/index.ts +++ b/packages/server/src/server/agent/providers/pi/extensions/gotgenes-pi-subagents/index.ts @@ -64,7 +64,8 @@ export const gotgenesPiSubagents: PiExtension = { type: "sub_agent" as const, subAgentType: title, description, - log: extractTextFromToolResult(call.result)?.trim() ?? "", + // COMPAT(subagent-log): remove after 2027-04-30. + log: "", }; if (call.status === "running") return { @@ -92,6 +93,10 @@ export const gotgenesPiSubagents: PiExtension = { outputFileFromToolResult(call.result) ?? pendingFilesByAgent.get(details.data.agentId); pendingFilesByAgent.delete(details.data.agentId); const childSessions = childSession(call.callId, file); + const childStatus = status(details.data.status); + // Without a session file, as on replay, the child's answer is the tool result. + const answer = + !file && childStatus !== "running" ? extractTextFromToolResult(call.result)?.trim() : ""; return { detail, subagents: [ @@ -101,8 +106,17 @@ export const gotgenesPiSubagents: PiExtension = { title, description, toolCallId: call.callId, - status: status(details.data.status), + status: childStatus, }, + ...(answer + ? [ + { + type: "timeline" as const, + id: call.callId, + item: { type: "assistant_message" as const, text: answer }, + }, + ] + : []), ], childSessions, }; @@ -118,7 +132,8 @@ export const gotgenesPiSubagents: PiExtension = { const detail = { type: "sub_agent" as const, description: details.success ? details.data.description : undefined, - log: extractTextFromToolResult(call.result)?.trim() ?? "", + // COMPAT(subagent-log): remove after 2027-04-30. + log: "", }; if (call.status === "running" || !details.success) return { detail }; const file = details.data.transcriptPath; diff --git a/packages/server/src/server/agent/providers/pi/extensions/index.test.ts b/packages/server/src/server/agent/providers/pi/extensions/index.test.ts index 9afacae977..d374c1a02d 100644 --- a/packages/server/src/server/agent/providers/pi/extensions/index.test.ts +++ b/packages/server/src/server/agent/providers/pi/extensions/index.test.ts @@ -83,7 +83,7 @@ describe("Pi extension host", () => { test("declines a throwing adapter and preserves generic history", async () => { const host = createPiExtensionHost(undefined, [throwingAdapter]); const mapper = new PiHistoryMapper("pi", [], {}, host); - const events = mapper.mapMessages([ + const events = await mapper.mapMessages([ { role: "assistant", content: [{ type: "toolCall", id: "call-1", name: "other", arguments: {} }], @@ -193,7 +193,7 @@ describe("Pi extension host", () => { await output?.hydration; expect(reads).toHaveLength(8); }); - test("claims a tool, declines an unrelated one, and maps history like live events", () => { + test("claims a tool, declines an unrelated one, and maps history like live events", async () => { const host = createPiExtensionHost(); const args = { agent: "scout", task: "Inspect files" }; const result = parseToolResult({ content: [{ type: "text", text: "Found two files" }] }); @@ -210,7 +210,7 @@ describe("Pi extension host", () => { type: "sub_agent", subAgentType: "scout", description: "Inspect files", - log: "Found two files", + log: "", }, }), ); @@ -225,7 +225,7 @@ describe("Pi extension host", () => { ).toBeUndefined(); const mapper = new PiHistoryMapper("pi"); - const events = mapper.mapMessages([ + const events = await mapper.mapMessages([ { role: "assistant", content: [{ type: "toolCall", id: "call-1", name: "subagent", arguments: args }], diff --git a/packages/server/src/server/agent/providers/pi/extensions/pi-subagents/index.test.ts b/packages/server/src/server/agent/providers/pi/extensions/pi-subagents/index.test.ts index 8e9db54047..740d66aadc 100644 --- a/packages/server/src/server/agent/providers/pi/extensions/pi-subagents/index.test.ts +++ b/packages/server/src/server/agent/providers/pi/extensions/pi-subagents/index.test.ts @@ -137,7 +137,7 @@ describe("pi-subagents adapter", () => { type: "sub_agent", subAgentType: "reviewer", description: "Review the Pi mapper change", - log: "The mapper change preserves provider status.", + log: "", }); }); diff --git a/packages/server/src/server/agent/providers/pi/extensions/pi-subagents/index.ts b/packages/server/src/server/agent/providers/pi/extensions/pi-subagents/index.ts index 64e814af3f..058171e8df 100644 --- a/packages/server/src/server/agent/providers/pi/extensions/pi-subagents/index.ts +++ b/packages/server/src/server/agent/providers/pi/extensions/pi-subagents/index.ts @@ -131,7 +131,8 @@ export const piSubagents: PiExtension = { type: "sub_agent" as const, subAgentType: args.data.agent, description: args.data.task, - log: extractTextFromToolResult(call.result)?.trim() ?? "", + // COMPAT(subagent-log): remove after 2027-04-30. + log: "", }; const base = { type: "upsert" as const, diff --git a/packages/server/src/server/agent/providers/pi/extensions/registry.ts b/packages/server/src/server/agent/providers/pi/extensions/registry.ts index c66fabad80..ca273b83bb 100644 --- a/packages/server/src/server/agent/providers/pi/extensions/registry.ts +++ b/packages/server/src/server/agent/providers/pi/extensions/registry.ts @@ -1,5 +1,6 @@ import { piAskUser } from "./pi-ask-user/index.js"; import { piSubagents } from "./pi-subagents/index.js"; +import { edxethPiSubagents } from "./edxeth-pi-subagents/index.js"; import { piMcpAdapter } from "./pi-mcp-adapter/index.js"; import { rpivTodo } from "./rpiv-todo/index.js"; import { piExampleTodo } from "./pi-example-todo/index.js"; @@ -10,6 +11,7 @@ import { rpivAskUserQuestion } from "./rpiv-ask-user-question/index.js"; export const piExtensions = [ piAskUser, // Dialog correlation + edxethPiSubagents, // Structured results before the generic subagent tool matcher piSubagents, // Delegation calls tintinwebPiSubagents, gotgenesPiSubagents, diff --git a/packages/server/src/server/agent/providers/pi/extensions/rpiv-ask-user-question/index.test.ts b/packages/server/src/server/agent/providers/pi/extensions/rpiv-ask-user-question/index.test.ts index 3ec9256a29..d3c9fb7a9e 100644 --- a/packages/server/src/server/agent/providers/pi/extensions/rpiv-ask-user-question/index.test.ts +++ b/packages/server/src/server/agent/providers/pi/extensions/rpiv-ask-user-question/index.test.ts @@ -79,7 +79,7 @@ test("cancellation declines each remaining real RPC dialog", () => { } }); -test("captured result renders in live and history tool rows, while foreign shapes decline", () => { +test("captured result renders in live and history tool rows, while foreign shapes decline", async () => { const call = { callId: end.toolCallId, toolName: end.toolName, @@ -93,7 +93,7 @@ test("captured result renders in live and history tool rows, while foreign shape label: "Questions", text: "Which snack?: Cookie\nWhich colors?: Red, Blue\nWhat project name?: Nebula", }); - const history = new PiHistoryMapper("pi").mapMessages([ + const history = await new PiHistoryMapper("pi").mapMessages([ { role: "assistant", content: [ diff --git a/packages/server/src/server/agent/providers/pi/extensions/subagent-fixture-test.ts b/packages/server/src/server/agent/providers/pi/extensions/subagent-fixture-test.ts index 8a9ca61d08..96ba771594 100644 --- a/packages/server/src/server/agent/providers/pi/extensions/subagent-fixture-test.ts +++ b/packages/server/src/server/agent/providers/pi/extensions/subagent-fixture-test.ts @@ -54,8 +54,6 @@ export async function verifySubagentFixture( try { await session.startTurn("Delegate work"); for (const event of fixture.events) pi.latestSession().emit(event); - const immediate = live.filter((event) => event.type === "provider_subagent"); - expect(immediate.some((event) => event.event.type === "timeline")).toBe(false); pi.latestSession().finishTurn(); const replay: AgentStreamEvent[] = []; for await (const event of streamPiHistory("pi", fixture.messages)) replay.push(event); diff --git a/packages/server/src/server/agent/providers/pi/extensions/task-fixture-test.ts b/packages/server/src/server/agent/providers/pi/extensions/task-fixture-test.ts index a3b2114cab..f702e0d7cf 100644 --- a/packages/server/src/server/agent/providers/pi/extensions/task-fixture-test.ts +++ b/packages/server/src/server/agent/providers/pi/extensions/task-fixture-test.ts @@ -89,7 +89,7 @@ export async function verifyTaskFixture(path: URL, expectedStatuses: string[]): for (const event of fixture.events) pi.latestSession().emit(event); pi.latestSession().finishTurn(); expect(todos(live)).toEqual(mapped); - const replay = new PiHistoryMapper("pi").mapMessages(fixture.messages); + const replay = await new PiHistoryMapper("pi").mapMessages(fixture.messages); expect(todos(replay)).toEqual(mapped); expect( replay.filter( diff --git a/packages/server/src/server/agent/providers/pi/extensions/tintinweb-pi-subagents/index.test.ts b/packages/server/src/server/agent/providers/pi/extensions/tintinweb-pi-subagents/index.test.ts index ad666bb4d3..60f3b12869 100644 --- a/packages/server/src/server/agent/providers/pi/extensions/tintinweb-pi-subagents/index.test.ts +++ b/packages/server/src/server/agent/providers/pi/extensions/tintinweb-pi-subagents/index.test.ts @@ -36,12 +36,17 @@ describe("@tintinweb/pi-subagents adapter", () => { }); expect(mapping?.subagents).toEqual([ expect.objectContaining({ id: "call-1", status: "completed" }), + { + type: "timeline", + id: "call-1", + item: { type: "assistant_message", text: "Wrapped up (turn limit)" }, + }, ]); expect(mapping?.detail).toEqual({ type: "sub_agent", subAgentType: "Explore", description: "Inspect", - log: "Wrapped up (turn limit)", + log: "", }); }); test("maps captured foreground lifecycle live and on replay", async () => { @@ -53,6 +58,18 @@ describe("@tintinweb/pi-subagents adapter", () => { .filter((event) => event.event.type === "upsert") .map((event) => (event.event.type === "upsert" ? event.event.status : null)), ).toEqual(["running", "completed"]); + expect( + events.flatMap((event) => (event.event.type === "timeline" ? [event.event] : [])), + ).toEqual([ + { + type: "timeline", + id: "call_458926", + item: { + type: "assistant_message", + text: "Agent completed in 6.6s (1 tool uses, 18.8k token).\n\nThe workspace directory `/tmp/paseo-pi-extension-phase3/workspace` is empty (no files or hidden dotfiles).", + }, + }, + ]); }); test("uses a structured notification to complete a background child", async () => { const source = readSubagentFixture(new URL("./fixtures/background.json", import.meta.url)); @@ -147,7 +164,7 @@ describe("@tintinweb/pi-subagents adapter", () => { expect(mapping?.detail).toEqual({ type: "sub_agent", description: undefined, - log: "Wrapped up (turn limit)", + log: "", }); }, ); diff --git a/packages/server/src/server/agent/providers/pi/extensions/tintinweb-pi-subagents/index.ts b/packages/server/src/server/agent/providers/pi/extensions/tintinweb-pi-subagents/index.ts index 56b5935172..6858dec8be 100644 --- a/packages/server/src/server/agent/providers/pi/extensions/tintinweb-pi-subagents/index.ts +++ b/packages/server/src/server/agent/providers/pi/extensions/tintinweb-pi-subagents/index.ts @@ -57,7 +57,8 @@ export const tintinwebPiSubagents: PiExtension = { type: "sub_agent" as const, subAgentType: title, description, - log: extractTextFromToolResult(call.result)?.trim() ?? "", + // COMPAT(subagent-log): remove after 2027-04-30. + log: "", }; if (call.status === "running") return { @@ -84,6 +85,10 @@ export const tintinwebPiSubagents: PiExtension = { const file = outputFileFromToolResult(call.result); const childSessions = file && !readSessions.has(file) ? [{ id: call.callId, file }] : []; if (file) readSessions.add(file); + const childStatus = status(details.data.status); + // A foreground child has no session file; its answer is the tool result. + const answer = + !file && childStatus !== "running" ? extractTextFromToolResult(call.result)?.trim() : ""; return { detail, subagents: [ @@ -93,8 +98,17 @@ export const tintinwebPiSubagents: PiExtension = { title, description, toolCallId: call.callId, - status: status(details.data.status), + status: childStatus, }, + ...(answer + ? [ + { + type: "timeline" as const, + id: call.callId, + item: { type: "assistant_message" as const, text: answer }, + }, + ] + : []), ], childSessions, }; @@ -110,7 +124,8 @@ export const tintinwebPiSubagents: PiExtension = { const detail = { type: "sub_agent" as const, description: details.success ? details.data.description : undefined, - log: extractTextFromToolResult(call.result)?.trim() ?? "", + // COMPAT(subagent-log): remove after 2027-04-30. + log: "", }; if (call.status === "running" || !details.success) return { detail }; return { diff --git a/packages/server/src/server/agent/providers/pi/history-mapper.test.ts b/packages/server/src/server/agent/providers/pi/history-mapper.test.ts index 24d18306b2..f4136956eb 100644 --- a/packages/server/src/server/agent/providers/pi/history-mapper.test.ts +++ b/packages/server/src/server/agent/providers/pi/history-mapper.test.ts @@ -221,3 +221,75 @@ describe("Pi history mapper", () => { ]); }); }); + +describe("Pi tool-result image replay", () => { + test("recreates an image from native tool-result history without its source file", async () => { + const events = await collectHistory([ + { + role: "assistant", + content: [ + { + type: "toolCall", + id: "image-read", + name: "read", + arguments: { path: "missing-preview.png" }, + }, + ], + }, + { + role: "toolResult", + toolCallId: "image-read", + toolName: "read", + content: [ + { type: "text", text: "Read image file [image/png]" }, + { type: "image", data: "aGVsbG8=", mimeType: "image/png" }, + ], + }, + ]); + expect(events.map((event) => event.item?.type)).toEqual([ + "tool_call", + "tool_call", + "assistant_message", + ]); + const image = events.find( + (event) => event.type === "timeline" && event.item.type === "assistant_message", + ); + expect(image).toMatchObject({ + type: "timeline", + item: { type: "assistant_message", text: expect.stringContaining("![Image](file://") }, + }); + if (image?.type !== "timeline" || image.item.type !== "assistant_message") + throw new Error("Missing image"); + const url = image.item.text.match(/\((file:[^)]+)\)/)![1]; + const { readFile, unlink } = await import("node:fs/promises"); + expect(await readFile(new URL(url))).toEqual(Buffer.from("hello")); + await unlink(new URL(url)); + const replay = await collectHistory([ + { + role: "toolResult", + toolCallId: "image-read", + toolName: "read", + content: [{ type: "image", data: "aGVsbG8=", mimeType: "image/png" }], + }, + ]); + expect(replay).toContainEqual(image); + expect(await readFile(new URL(url))).toEqual(Buffer.from("hello")); + }); +}); + +test("replayed Pi images keep their position before the following reply", async () => { + const events = await collectHistory([ + { + role: "toolResult", + toolCallId: "image-position", + toolName: "read", + content: [{ type: "image", data: "aGVsbG8=", mimeType: "image/png" }], + }, + { role: "assistant", content: [{ type: "text", text: "Image read complete." }] }, + ]); + expect( + events.map((event) => + event.item?.type === "assistant_message" ? event.item.text : event.item?.type, + ), + ).toEqual(["tool_call", expect.stringContaining("![Image]("), "Image read complete."]); +}); diff --git a/packages/server/src/server/agent/providers/pi/history-mapper.ts b/packages/server/src/server/agent/providers/pi/history-mapper.ts index 27a0250b00..89d9fcedce 100644 --- a/packages/server/src/server/agent/providers/pi/history-mapper.ts +++ b/packages/server/src/server/agent/providers/pi/history-mapper.ts @@ -1,5 +1,9 @@ import { mapCustomMessageToToolCall } from "../custom-message.js"; import type { AgentStreamEvent, AgentTimelineItem, ToolCallDetail } from "../../agent-sdk-types.js"; +import { + materializeProviderImage, + renderProviderImageOutputAsAssistantMarkdown, +} from "../provider-image-output.js"; import { createPiExtensionHost, type PiExtensionEventOutput, @@ -11,6 +15,7 @@ import { mapToolDetail, parseToolArgs, parseToolResult, + splitPiToolResultImages, type PiToolResult, type PiTrackedToolCall, } from "./tool-call-mapper.js"; @@ -71,7 +76,7 @@ export class PiHistoryMapper { private readonly extensionHost: PiExtensionHost = createPiExtensionHost(), ) {} - mapMessages(messages: readonly PiAgentMessage[]): AgentStreamEvent[] { + async mapMessages(messages: readonly PiAgentMessage[]): Promise { const events: AgentStreamEvent[] = []; for (const message of messages) { @@ -86,7 +91,7 @@ export class PiHistoryMapper { events.push(...this.mapAssistantMessage(message)); break; case "toolResult": { - events.push(...this.mapToolResultMessage(message)); + events.push(...(await this.mapToolResultMessage(message))); break; } case "bashExecution": @@ -207,24 +212,35 @@ export class PiHistoryMapper { return events; } - private mapToolResultMessage( + private async mapToolResultMessage( message: Extract, - ): AgentStreamEvent[] { + ): Promise { const tracked = this.pendingToolCalls.get(message.toolCallId) ?? parseToolArgs(message.toolName, null); this.pendingToolCalls.delete(message.toolCallId); const result = parseToolResult({ content: message.content, details: message.details }); + // Pull image blocks out of the result so base64 never reaches the tool output, then render + // each one as an assistant_message markdown image after the tool_call (mirroring the live + // path and the Claude provider, upstream #1717). + const { images, result: splitResult } = splitPiToolResultImages(result); const mapping = this.extensionHost.mapToolCall({ callId: message.toolCallId, toolName: tracked.toolName, args: tracked.args, status: message.isError ? "failed" : "completed", - result, + result: splitResult, }); - const detail = this.mapToolDetail(message.toolCallId, tracked, result, mapping?.detail); + const detail = this.mapToolDetail(message.toolCallId, tracked, splitResult, mapping?.detail); if (!detail) { return []; } + const imageEvents: AgentStreamEvent[] = []; + for (const image of images) { + const item = await renderProviderImageOutputAsAssistantMarkdown(image, { + materialize: materializeProviderImage, + }); + if (item) imageEvents.push({ type: "timeline", provider: this.provider, item }); + } return [ { type: "timeline", @@ -234,9 +250,10 @@ export class PiHistoryMapper { name: mapping?.name ?? tracked.toolName, isError: Boolean(message.isError), detail, - errorText: extractTextFromToolResult(result) ?? "Tool call failed", + errorText: extractTextFromToolResult(splitResult) ?? "Tool call failed", }), }, + ...imageEvents, ...this.extensionEvents(mapping), ]; } @@ -297,9 +314,10 @@ export async function* streamPiHistory( signal?: AbortSignal, ): AsyncGenerator { const mapper = new PiHistoryMapper(provider, userEntries, hooks, extensionHost); - for (const event of mapper.mapMessages(messages)) { + for (const message of messages) { if (signal?.aborted) return; - if (event) { + for (const event of await mapper.mapMessages([message])) { + if (signal?.aborted) return; yield event; } } diff --git a/packages/server/src/server/agent/providers/pi/session-descriptor.test.ts b/packages/server/src/server/agent/providers/pi/session-descriptor.test.ts index 280b558739..c6b0df5dbf 100644 --- a/packages/server/src/server/agent/providers/pi/session-descriptor.test.ts +++ b/packages/server/src/server/agent/providers/pi/session-descriptor.test.ts @@ -1,9 +1,13 @@ -import { mkdtemp, mkdir, utimes, writeFile } from "node:fs/promises"; +import { mkdtemp, mkdir, readFile, rm, utimes, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; -import { expect, test } from "vitest"; +import { expect, onTestFinished, test } from "vitest"; -import { listPiImportableSessions, readPiImportSessionConfig } from "./session-descriptor.js"; +import { + copyPiSessionFileWithCwd, + listPiImportableSessions, + readPiImportSessionConfig, +} from "./session-descriptor.js"; async function writeSession(root: string, lines: unknown[]): Promise { const sessionsDir = path.join(root, "sessions", "project"); @@ -216,3 +220,97 @@ test("Pi import config preserves thinking before a later model in large sessions thinkingOptionId: "low", }); }); + +test("a Pi session copy names the new cwd in its header and keeps every later byte", async () => { + const root = await mkdtemp(path.join(tmpdir(), "paseo-pi-session-copy-")); + onTestFinished(() => rm(root, { recursive: true, force: true })); + const header = { + type: "session", + version: 3, + id: "pi-session-1", + timestamp: "2026-01-01T00:00:00.000Z", + cwd: path.join(root, "removed-worktree"), + }; + const body = Buffer.from( + Array.from( + { length: 2_000 }, + (_, index) => + `${JSON.stringify({ type: "message", id: `entry-${index}`, message: { role: "user", content: `café ☕ ${index}` } })}\n`, + ).join(""), + ); + expect(body.length).toBeGreaterThan(64 * 1024); + const sourceFile = path.join(root, "source.jsonl"); + const targetFile = path.join(root, "copy.jsonl"); + await writeFile(sourceFile, Buffer.concat([Buffer.from(`${JSON.stringify(header)}\n`), body])); + + await copyPiSessionFileWithCwd({ sourceFile, targetFile, cwd: "/home/user" }); + + const copy = await readFile(targetFile); + const headerEnd = copy.indexOf(0x0a); + expect(JSON.parse(copy.subarray(0, headerEnd).toString("utf8"))).toEqual({ + ...header, + cwd: "/home/user", + }); + expect(copy.subarray(headerEnd + 1).equals(body)).toBe(true); +}); + +test("a Pi session copy refuses a file without a session header", async () => { + const root = await mkdtemp(path.join(tmpdir(), "paseo-pi-session-copy-")); + onTestFinished(() => rm(root, { recursive: true, force: true })); + const sourceFile = path.join(root, "source.jsonl"); + await writeFile(sourceFile, `${JSON.stringify({ type: "message", id: "entry-1" })}\n`); + + await expect( + copyPiSessionFileWithCwd({ sourceFile, targetFile: path.join(root, "copy.jsonl"), cwd: "/" }), + ).rejects.toThrow(`Pi session file has no session header: ${sourceFile}`); +}); + +const COPY_BODY = [ + { type: "message", id: "entry-1", message: { role: "user", content: "café ☕" } }, + { type: "message", id: "entry-2", message: { role: "assistant", content: "Dans la cuisine." } }, +] + .map((entry) => `${JSON.stringify(entry)}\n`) + .join(""); + +const COPY_HEADER = { + type: "session", + version: 3, + id: "pi-session-1", + timestamp: "2026-01-01T00:00:00.000Z", + cwd: "/removed-worktree", +}; + +async function copySessionContent(content: string): Promise { + const root = await mkdtemp(path.join(tmpdir(), "paseo-pi-session-copy-")); + onTestFinished(() => rm(root, { recursive: true, force: true })); + const sourceFile = path.join(root, "source.jsonl"); + const targetFile = path.join(root, "copy.jsonl"); + await writeFile(sourceFile, content); + await copyPiSessionFileWithCwd({ sourceFile, targetFile, cwd: "/home/user" }); + return readFile(targetFile); +} + +test.each([ + ["a header line longer than 64 KiB", "", { ...COPY_HEADER, padding: "x".repeat(70 * 1024) }], + ["a header with an empty cwd", "", { ...COPY_HEADER, cwd: "" }], + ["blank lines before the header", "\n\r\n", COPY_HEADER], +])("a Pi session copy accepts %s", async (_headerShape, prefix, header) => { + const copy = await copySessionContent(`${prefix}${JSON.stringify(header)}\n${COPY_BODY}`); + + const headerEnd = copy.indexOf(0x0a); + expect(JSON.parse(copy.subarray(0, headerEnd).toString("utf8"))).toEqual({ + ...header, + cwd: "/home/user", + }); + expect(copy.subarray(headerEnd + 1).equals(Buffer.from(COPY_BODY))).toBe(true); +}); + +test("a Pi session copy reports a missing session file", async () => { + const root = await mkdtemp(path.join(tmpdir(), "paseo-pi-session-copy-")); + onTestFinished(() => rm(root, { recursive: true, force: true })); + const sourceFile = path.join(root, "missing.jsonl"); + + await expect( + copyPiSessionFileWithCwd({ sourceFile, targetFile: path.join(root, "copy.jsonl"), cwd: "/" }), + ).rejects.toThrow(`Pi session file is missing: ${sourceFile}`); +}); diff --git a/packages/server/src/server/agent/providers/pi/session-descriptor.ts b/packages/server/src/server/agent/providers/pi/session-descriptor.ts index 01f55bc0ce..6c0cc300f2 100644 --- a/packages/server/src/server/agent/providers/pi/session-descriptor.ts +++ b/packages/server/src/server/agent/providers/pi/session-descriptor.ts @@ -1,7 +1,8 @@ -import type { Dirent } from "node:fs"; -import { open, readdir, readFile, stat } from "node:fs/promises"; +import { createReadStream, createWriteStream, type Dirent } from "node:fs"; +import { open, readdir, readFile, stat, writeFile } from "node:fs/promises"; import { homedir } from "node:os"; import path from "node:path"; +import { pipeline } from "node:stream/promises"; import type { ImportableProviderSession, @@ -18,6 +19,7 @@ const PI_SESSION_DIR_ENV = "PI_CODING_AGENT_SESSION_DIR"; const HEAD_BYTES = 64 * 1024; const TAIL_BYTES = 256 * 1024; const FULL_SCAN_LINE_LIMIT = 2_000; +const PI_SESSION_HEADER_SCAN_BYTES = 1024 * 1024; // Rank all discovered files cheaply, then parse only a bounded recent window. const IMPORT_CANDIDATE_OVERSCAN = 40; const IMPORT_CANDIDATE_MIN = 400; @@ -100,6 +102,59 @@ export async function listPiImportableSessions( ); } +export async function copyPiSessionFileWithCwd(input: { + sourceFile: string; + targetFile: string; + cwd: string; +}): Promise { + const found = findSessionHeaderLine( + await readSessionFileStart(input.sourceFile, PI_SESSION_HEADER_SCAN_BYTES), + ); + if (!found) { + throw new Error(`Pi session file has no session header: ${input.sourceFile}`); + } + await writeFile(input.targetFile, `${JSON.stringify({ ...found.header, cwd: input.cwd })}\n`, { + mode: 0o600, + }); + await pipeline( + createReadStream(input.sourceFile, { start: found.bodyStart }), + createWriteStream(input.targetFile, { flags: "a" }), + ); +} + +function findSessionHeaderLine( + scanned: Buffer, +): { header: Record; bodyStart: number } | null { + let lineStart = 0; + while (lineStart < scanned.length) { + const newline = scanned.indexOf(0x0a, lineStart); + const bodyStart = newline === -1 ? scanned.length : newline + 1; + const line = scanned.subarray(lineStart, bodyStart).toString("utf8").trim(); + if (line) { + const header = parseJsonRecord(line); + return header?.type === "session" ? { header, bodyStart } : null; + } + lineStart = bodyStart; + } + return null; +} + +async function readSessionFileStart(filePath: string, maxBytes: number): Promise { + const handle = await open(filePath, "r").catch((error: unknown) => { + if ((error as NodeJS.ErrnoException).code === "ENOENT") { + throw new Error(`Pi session file is missing: ${filePath}`); + } + throw error; + }); + try { + const buffer = Buffer.alloc(maxBytes); + const { bytesRead } = await handle.read(buffer, 0, maxBytes, 0); + return buffer.subarray(0, bytesRead); + } finally { + await handle.close().catch(() => undefined); + } +} + export async function readPiImportSessionConfig(filePath: string): Promise { const descriptor = await readPiSessionDescriptor(filePath); if (!descriptor) return {}; diff --git a/packages/server/src/server/agent/providers/pi/test-utils/fake-pi.ts b/packages/server/src/server/agent/providers/pi/test-utils/fake-pi.ts index 983b86c19d..90a80e4c66 100644 --- a/packages/server/src/server/agent/providers/pi/test-utils/fake-pi.ts +++ b/packages/server/src/server/agent/providers/pi/test-utils/fake-pi.ts @@ -1,3 +1,5 @@ +import { existsSync, readFileSync } from "node:fs"; + import type { PiRuntime, PiRuntimeLaunch, @@ -75,6 +77,12 @@ export class FakePi implements PiRuntime { const session = new FakePiSession(launch, this.removedModels); session.commands = this.queuedCommands.shift() ?? []; this.queuedSessionSetups.shift()?.(session); + const missingSessionCwd = launch.noSession ? null : readMissingSessionCwd(launch.session); + if (missingSessionCwd !== null) { + session.getStateError = new Error( + `Pi RPC process exited with code 1 and signal null\nStored session working directory does not exist: ${missingSessionCwd}\nSession file: ${launch.session}\nCurrent working directory: ${launch.cwd}`, + ); + } this.sessions.push(session); return session; } @@ -101,6 +109,27 @@ export class FakePi implements PiRuntime { } } +function readMissingSessionCwd(sessionFile: string | undefined): string | null { + if (!sessionFile || !existsSync(sessionFile)) { + return null; + } + const [headerLine = ""] = readFileSync(sessionFile, "utf8").split("\n", 1); + let header: unknown; + try { + header = JSON.parse(headerLine); + } catch { + return null; + } + if (typeof header !== "object" || header === null || !("cwd" in header)) { + return null; + } + const { type, cwd } = header as { type?: unknown; cwd?: unknown }; + if (type !== "session" || typeof cwd !== "string" || !cwd || existsSync(cwd)) { + return null; + } + return cwd; +} + export class FakePiSession implements PiRuntimeSession { readonly environment: Record; readonly prompts: Array<{ message: string; imageCount: number }> = []; diff --git a/packages/server/src/server/agent/providers/pi/tool-call-mapper.test.ts b/packages/server/src/server/agent/providers/pi/tool-call-mapper.test.ts index 63b557f994..0c065e27cd 100644 --- a/packages/server/src/server/agent/providers/pi/tool-call-mapper.test.ts +++ b/packages/server/src/server/agent/providers/pi/tool-call-mapper.test.ts @@ -1,6 +1,12 @@ import { describe, expect, test } from "vitest"; -import { mapToolDetail, parseToolArgs, parseToolResult } from "./tool-call-mapper.js"; +import { + extractTextFromToolResult, + mapToolDetail, + parseToolArgs, + parseToolResult, + splitPiToolResultImages, +} from "./tool-call-mapper.js"; describe("Pi tool call mapper", () => { test("maps bash args and result to shell detail", () => { @@ -56,3 +62,77 @@ describe("Pi tool call mapper", () => { }); }); }); + +describe("splitPiToolResultImages", () => { + test("extracts image blocks and replaces them with [image] placeholders", () => { + const parsed = parseToolResult({ + content: [ + { type: "text", text: "shot taken" }, + { type: "image", data: "aGVsbG8=", mimeType: "image/png" }, + ], + }); + const { images, result } = splitPiToolResultImages(parsed); + + expect(images).toEqual([{ data: "aGVsbG8=", mimeType: "image/png" }]); + expect(result).toEqual({ + content: [ + { type: "text", text: "shot taken" }, + { type: "text", text: "[image]" }, + ], + }); + }); + + test("replaces image-only results with a non-empty placeholder", () => { + const parsed = parseToolResult({ + content: [{ type: "image", data: "aGVsbG8=", mimeType: "image/jpeg" }], + }); + const { images, result } = splitPiToolResultImages(parsed); + + expect(images).toHaveLength(1); + expect(extractTextFromToolResult(result)).toBe("[image]"); + }); + + test("passes through string results and results without images", () => { + expect(splitPiToolResultImages("plain output")).toEqual({ + images: [], + result: "plain output", + }); + const textOnly = parseToolResult({ content: [{ type: "text", text: "no images" }] }); + expect(splitPiToolResultImages(textOnly)).toEqual({ images: [], result: textOnly }); + expect(splitPiToolResultImages(null)).toEqual({ images: [], result: null }); + }); + + test("keeps other fields on the result object", () => { + const parsed = parseToolResult({ + exitCode: 0, + content: [{ type: "image", data: "aGVsbG8=" }], + }); + const { result } = splitPiToolResultImages(parsed); + expect(result).toMatchObject({ exitCode: 0 }); + }); +}); + +test("tool-result images remove nested structured image data while preserving metadata", () => { + const data = Buffer.from("nested screenshot bytes").toString("base64"); + const result = parseToolResult({ + content: [{ type: "image", data, mimeType: "image/png" }], + structuredContent: { + content: [{ type: "image", data, mimeType: "image/png", width: 64 }], + captureId: "capture-1", + read: { type: "image", data, mimeType: "image/png", note: "Read image file" }, + extra: { data: "keep ordinary data" }, + }, + }); + const split = splitPiToolResultImages(result); + const detail = mapToolDetail(parseToolArgs("screenshot", {}), split.result); + expect(JSON.stringify(detail)).not.toContain(data); + expect(split.images).toEqual([{ data, mimeType: "image/png" }]); + expect(split.result).toMatchObject({ + structuredContent: { + content: [{ type: "image", data: "[image]", mimeType: "image/png", width: 64 }], + captureId: "capture-1", + read: { type: "image", data: "[image]", mimeType: "image/png", note: "Read image file" }, + extra: { data: "keep ordinary data" }, + }, + }); +}); diff --git a/packages/server/src/server/agent/providers/pi/tool-call-mapper.ts b/packages/server/src/server/agent/providers/pi/tool-call-mapper.ts index 8c18a8fdbf..8fbba690b8 100644 --- a/packages/server/src/server/agent/providers/pi/tool-call-mapper.ts +++ b/packages/server/src/server/agent/providers/pi/tool-call-mapper.ts @@ -1,6 +1,7 @@ import { z } from "zod"; import type { ToolCallDetail } from "../../agent-sdk-types.js"; +import type { ProviderImageOutput } from "../provider-image-output.js"; interface BashToolInput { command: string; @@ -52,6 +53,7 @@ interface PiToolResultObject { stdout?: string; text?: string; content?: PiToolResultContent[]; + structuredContent?: unknown; exitCode?: number; code?: number; details?: PiToolResultDetails; @@ -67,6 +69,12 @@ interface PiToolResultTextContent { text: string; } +const PiToolResultImageContentSchema = z.object({ + type: z.literal("image"), + data: z.string().min(1), + mimeType: z.string().optional(), +}); + interface PiToolResultUnknownContent { type: string; } @@ -236,6 +244,61 @@ export function parseToolResult(rawResult: unknown): PiToolResult { return null; } +// Pi returns images inside tool-result content as base64 blocks. Left in place they reach the +// tool-output stringifier, which dumps base64 into the tool output. We pull those blocks out to +// render them as image markdown and leave a "[image]" placeholder so image-only results still +// produce non-empty output (mirroring splitClaudeToolResultImages). +export function splitPiToolResultImages(result: PiToolResult): { + images: ProviderImageOutput[]; + result: PiToolResult; +} { + if (!result || typeof result === "string" || !result.content) { + return { images: [], result }; + } + const images: ProviderImageOutput[] = []; + let replaced = false; + const content = result.content.map((block) => { + const image = toPiImageOutput(block); + if (image) { + images.push(image); + replaced = true; + return { type: "text", text: "[image]" } satisfies PiToolResultTextContent; + } + return block; + }); + if (!replaced) { + return { images: [], result }; + } + return { + images, + result: { + ...result, + content, + ...(result.structuredContent === undefined + ? {} + : { structuredContent: withoutImageData(result.structuredContent) }), + }, + }; +} + +function withoutImageData(value: unknown): unknown { + if (Array.isArray(value)) return value.map(withoutImageData); + if (value === null || typeof value !== "object") return value; + const image = toPiImageOutput(value); + return Object.fromEntries( + Object.entries(value).map(([key, child]) => [ + key, + image && key === "data" ? "[image]" : withoutImageData(child), + ]), + ); +} + +function toPiImageOutput(block: unknown): ProviderImageOutput | null { + const parsed = PiToolResultImageContentSchema.safeParse(block); + if (!parsed.success) return null; + return { data: parsed.data.data, mimeType: parsed.data.mimeType ?? null }; +} + export function extractTextFromToolResult(result: PiToolResult): string | undefined { if (typeof result === "string") { return result; diff --git a/packages/server/src/server/agent/providers/provider-image-output.posix.test.ts b/packages/server/src/server/agent/providers/provider-image-output.posix.test.ts index 1f4da6e04a..5e71bad0bd 100644 --- a/packages/server/src/server/agent/providers/provider-image-output.posix.test.ts +++ b/packages/server/src/server/agent/providers/provider-image-output.posix.test.ts @@ -5,8 +5,8 @@ import { describe, expect, test } from "vitest"; import { materializeProviderImage } from "./provider-image-output.js"; describe.skipIf(process.platform === "win32")("materializeProviderImage", () => { - test("writes image attachments under a private temp directory", () => { - const materialized = materializeProviderImage({ + test("writes image attachments under a private temp directory", async () => { + const materialized = await materializeProviderImage({ data: "YWJjMTIz", mimeType: "image/png", }); diff --git a/packages/server/src/server/agent/providers/provider-image-output.test.ts b/packages/server/src/server/agent/providers/provider-image-output.test.ts index b4f4784a66..3388edb6d5 100644 --- a/packages/server/src/server/agent/providers/provider-image-output.test.ts +++ b/packages/server/src/server/agent/providers/provider-image-output.test.ts @@ -1,10 +1,11 @@ -import { existsSync, rmSync } from "node:fs"; +import { existsSync, rmSync, statSync, readFileSync } from "node:fs"; import path from "node:path"; import MarkdownIt from "markdown-it"; import { projectTimelineRows } from "../timeline-projection.js"; import { describe, expect, test } from "vitest"; import { + MAX_PROVIDER_IMAGE_BYTES, isProviderImageMarkdown, materializeProviderImage, renderProviderImageOutputAsAssistantMarkdown, @@ -12,8 +13,8 @@ import { const HASH = "a".repeat(64); -function renderImageMarkdown(imagePath: string): string { - const item = renderProviderImageOutputAsAssistantMarkdown({ path: imagePath }); +async function renderImageMarkdown(imagePath: string): Promise { + const item = await renderProviderImageOutputAsAssistantMarkdown({ path: imagePath }); if (!item || item.type !== "assistant_message") { throw new Error("Expected provider image output to render as assistant markdown."); } @@ -40,8 +41,8 @@ describe("isProviderImageMarkdown", () => { ).toBe(true); }); - test("emits Windows file paths as file URIs", () => { - const markdown = renderImageMarkdown( + test("emits Windows file paths as file URIs", async () => { + const markdown = await renderImageMarkdown( `C:\\Users\\me\\AppData\\Local\\Temp\\paseo-attachments\\${HASH}.png`, ); @@ -51,22 +52,24 @@ describe("isProviderImageMarkdown", () => { expect(isProviderImageMarkdown(markdown)).toBe(true); }); - test("emits POSIX file paths with spaces as valid file URI markdown", () => { - const markdown = renderImageMarkdown("/home/user/Projects/Project With Spaces/screenshot.png"); + test("emits POSIX file paths with spaces as valid file URI markdown", async () => { + const markdown = await renderImageMarkdown( + "/home/user/Projects/Project With Spaces/screenshot.png", + ); expect(markdown).toBe( "\n\n![Image](file:///home/user/Projects/Project%20With%20Spaces/screenshot.png)\n\n", ); }); - test("encodes URI-significant characters in POSIX file paths", () => { - const markdown = renderImageMarkdown("/tmp/screenshot#1?draft.png"); + test("encodes URI-significant characters in POSIX file paths", async () => { + const markdown = await renderImageMarkdown("/tmp/screenshot#1?draft.png"); expect(markdown).toBe("\n\n![Image](file:///tmp/screenshot%231%3Fdraft.png)\n\n"); }); - test("preserves double-leading slashes in POSIX file paths", () => { - const markdown = renderImageMarkdown("//tmp/screenshot#1.png"); + test("preserves double-leading slashes in POSIX file paths", async () => { + const markdown = await renderImageMarkdown("//tmp/screenshot#1.png"); expect(markdown).toBe("\n\n![Image](file:////tmp/screenshot%231.png)\n\n"); }); @@ -78,8 +81,8 @@ describe("isProviderImageMarkdown", () => { "\\\\?\\UNC\\server\\share\\shot?draft.png", "file://server/share/shot%3Fdraft.png", ], - ])("encodes %s image paths as file URIs", (_label, imagePath, expectedSource) => { - expect(renderImageMarkdown(imagePath)).toBe(`\n\n![Image](${expectedSource})\n\n`); + ])("encodes %s image paths as file URIs", async (_label, imagePath, expectedSource) => { + expect(await renderImageMarkdown(imagePath)).toBe(`\n\n![Image](${expectedSource})\n\n`); }); test("rejects user-authored markdown that is not a materialized attachment", () => { @@ -92,8 +95,8 @@ describe("isProviderImageMarkdown", () => { }); describe("materializeProviderImage", () => { - test("recreates the private temp directory if the cached directory is removed", () => { - const first = materializeProviderImage({ + test("recreates the private temp directory if the cached directory is removed", async () => { + const first = await materializeProviderImage({ data: "YWJjMTIz", mimeType: "image/png", }); @@ -102,7 +105,7 @@ describe("materializeProviderImage", () => { rmSync(firstDir, { recursive: true, force: true }); - const second = materializeProviderImage({ + const second = await materializeProviderImage({ data: "ZGVmNDU2", mimeType: "image/png", }); @@ -117,8 +120,8 @@ describe("materializeProviderImage", () => { }); describe("provider image paragraph boundaries", () => { - test.each(["", "\n"])("keeps image outputs separate from prose ending in %j", (ending) => { - const image = renderProviderImageOutputAsAssistantMarkdown({ + test.each(["", "\n"])("keeps image outputs separate from prose ending in %j", async (ending) => { + const image = await renderProviderImageOutputAsAssistantMarkdown({ url: "https://example.com/chart.png", }); if (!image) throw new Error("Expected image output"); @@ -152,10 +155,10 @@ describe("provider image paragraph boundaries", () => { }); }); -test("materialized image output retains paragraph boundaries and attachment recognition", () => { - const item = renderProviderImageOutputAsAssistantMarkdown( +test("materialized image output retains paragraph boundaries and attachment recognition", async () => { + const item = await renderProviderImageOutputAsAssistantMarkdown( { data: "YWJjMTIz", mimeType: "image/png" }, - { materialize: () => ({ path: `/tmp/paseo-attachments/${HASH}.png` }) }, + { materialize: async () => ({ path: `/tmp/paseo-attachments/${HASH}.png` }) }, ); expect(item).toEqual({ type: "assistant_message", @@ -164,3 +167,83 @@ test("materialized image output retains paragraph boundaries and attachment reco if (!item || item.type !== "assistant_message") throw new Error("Expected image output"); expect(isProviderImageMarkdown(item.text)).toBe(true); }); + +test("repeated content is reused without rewriting the attachment", async () => { + const image = { + data: Buffer.from("dedupe regression").toString("base64"), + mimeType: "image/png", + }; + const first = await materializeProviderImage(image); + const before = statSync(first.path, { bigint: true }); + await new Promise((resolve) => setTimeout(resolve, 20)); + const second = await materializeProviderImage(image); + expect(second.path).toBe(first.path); + expect(statSync(second.path, { bigint: true }).mtimeNs).toBe(before.mtimeNs); +}); + +test("64 MiB materialization leaves the event loop responsive and preserves bytes", async () => { + const bytes = Buffer.alloc(64 * 1024 * 1024, 37); + const data = bytes.toString("base64"); + // Main-thread CPU time between ticks bounds the decode and hash work done on the loop; + // wall-clock gaps on shared CI runners also count preemption and timer granularity. + // File writes stay on fs/promises, so they never block the loop. + const threadCpuMs = () => { + const { user, system } = process.threadCpuUsage(); + return (user + system) / 1000; + }; + let previous = threadCpuMs(); + let longest = 0; + const probe = setInterval(() => { + const now = threadCpuMs(); + longest = Math.max(longest, now - previous); + previous = now; + }, 1); + try { + const result = await materializeProviderImage({ data, mimeType: "image/png" }); + await new Promise((resolve) => setTimeout(resolve, 5)); + console.log(`64 MiB attachment longest blocking stretch: ${longest.toFixed(2)} ms CPU`); + expect(longest).toBeLessThan(50); + expect(readFileSync(result.path).equals(bytes)).toBe(true); + rmSync(result.path, { force: true }); + } finally { + clearInterval(probe); + } +}); + +test("preserves base64 decoding across whitespace and chunk boundaries", async () => { + const bytes = Buffer.alloc(512 * 1024, 123); + const base64 = bytes.toString("base64"); + const data = base64.match(/.{1,77}/g)!.join("\n"); + const result = await materializeProviderImage({ data, mimeType: "image/png" }); + expect(readFileSync(result.path).equals(bytes)).toBe(true); +}); + +test("rejects oversized materialization before work and leaves the queue usable", async () => { + const data = "A".repeat(Math.ceil(MAX_PROVIDER_IMAGE_BYTES / 3) * 4 + 260); + await expect(materializeProviderImage({ data, mimeType: "image/png" })).rejects.toThrow( + "exceeds", + ); + const omitted = await renderProviderImageOutputAsAssistantMarkdown( + { data, mimeType: "image/png" }, + { materialize: materializeProviderImage }, + ); + expect(omitted).toEqual({ + type: "assistant_message", + text: "Image output was omitted because it was not available as a file path or URL.", + }); + const image = await materializeProviderImage({ data: "YWJjMTIz", mimeType: "image/png" }); + expect(readFileSync(image.path).toString()).toBe("abc123"); +}); + +test("simultaneous requests for the same content share the published file", async () => { + const image = { + data: Buffer.from("concurrent dedupe fixture").toString("base64"), + mimeType: "image/png", + }; + const results = await Promise.all([ + materializeProviderImage(image), + materializeProviderImage(image), + ]); + expect(results[0]).toEqual(results[1]); + expect(readFileSync(results[0].path).toString()).toBe("concurrent dedupe fixture"); +}); diff --git a/packages/server/src/server/agent/providers/provider-image-output.ts b/packages/server/src/server/agent/providers/provider-image-output.ts index ba8843918b..0cd0787c1e 100644 --- a/packages/server/src/server/agent/providers/provider-image-output.ts +++ b/packages/server/src/server/agent/providers/provider-image-output.ts @@ -1,5 +1,6 @@ import { createHash } from "node:crypto"; -import * as fsSync from "node:fs"; +import * as fs from "node:fs/promises"; +import { setImmediate } from "node:timers/promises"; import os from "node:os"; import path from "node:path"; @@ -23,32 +24,26 @@ const PRIVATE_ATTACHMENT_DIR_MODE = 0o700; const MATERIALIZED_IMAGE_FILE_MODE = 0o600; let materializedImageAttachmentDir: string | null = null; +// Serialize materializations: one decoder and one file operation at a time, including +// concurrent history replay and live turns. A rejected operation must not poison the queue. +let pendingMaterialization: Promise = Promise.resolve(); -function canReuseMaterializedImageAttachmentDir(dir: string): boolean { - try { - const stats = fsSync.lstatSync(dir); - if (!stats.isDirectory()) { - return false; +async function getMaterializedImageAttachmentDir(): Promise { + if (materializedImageAttachmentDir) { + try { + const stats = await fs.lstat(materializedImageAttachmentDir); + if (stats.isDirectory()) { + await fs.chmod(materializedImageAttachmentDir, PRIVATE_ATTACHMENT_DIR_MODE); + return materializedImageAttachmentDir; + } + } catch { + /* Temp storage may have been removed between turns. */ } - fsSync.chmodSync(dir, PRIVATE_ATTACHMENT_DIR_MODE); - return true; - } catch { - return false; } -} - -function getMaterializedImageAttachmentDir(): string { - if ( - materializedImageAttachmentDir && - canReuseMaterializedImageAttachmentDir(materializedImageAttachmentDir) - ) { - return materializedImageAttachmentDir; - } - - materializedImageAttachmentDir = fsSync.mkdtempSync( + materializedImageAttachmentDir = await fs.mkdtemp( path.join(os.tmpdir(), PROVIDER_IMAGE_ATTACHMENT_DIR_PREFIX), ); - fsSync.chmodSync(materializedImageAttachmentDir, PRIVATE_ATTACHMENT_DIR_MODE); + await fs.chmod(materializedImageAttachmentDir, PRIVATE_ATTACHMENT_DIR_MODE); return materializedImageAttachmentDir; } @@ -71,32 +66,92 @@ function getImageExtension(mimeType: string): string { } } -function normalizeImageData(mimeType: string, data: string): { mimeType: string; data: string } { - if (data.startsWith("data:")) { - const match = data.match(/^data:([^;]+);base64,(.*)$/); - if (match) { - return { mimeType: match[1], data: match[2] }; - } - } - return { mimeType, data }; -} +// 128 MiB admits the measured 64 MiB fixture with headroom while bounding disk +// and decoding per image. This is materialization admission, not a wire schema limit. +export const MAX_PROVIDER_IMAGE_BYTES = 128 * 1024 * 1024; +const BASE64_CHUNK_CHARACTERS = 256 * 1024; // Multiple of four; decode units stay aligned. -// Filenames are a content hash of the bytes so re-materializing the same image -// within a process reuses the existing temp file instead of leaking a fresh one -// for repeated image blocks or history replay. export function materializeProviderImage(image: { data: string; mimeType: string | null; -}): MaterializedProviderImage { - const attachmentsDir = getMaterializedImageAttachmentDir(); - const normalized = normalizeImageData(image.mimeType ?? "image/png", image.data); - const bytes = Buffer.from(normalized.data, "base64"); - const extension = getImageExtension(normalized.mimeType); - const hash = createHash("sha256").update(bytes).digest("hex"); - const filePath = path.join(attachmentsDir, `${hash}.${extension}`); - fsSync.writeFileSync(filePath, bytes, { mode: MATERIALIZED_IMAGE_FILE_MODE }); - fsSync.chmodSync(filePath, MATERIALIZED_IMAGE_FILE_MODE); - return { path: filePath }; +}): Promise { + const result = pendingMaterialization.then(() => materializeImage(image)); + pendingMaterialization = result.catch(() => {}); + return result; +} + +async function materializeImage(image: { + data: string; + mimeType: string | null; +}): Promise { + const maxEncodedCharacters = Math.ceil(MAX_PROVIDER_IMAGE_BYTES / 3) * 4; + // Check length before inspecting/copying the payload, including a bounded data URI header. + if (image.data.length > maxEncodedCharacters + 256) { + throw new Error(`Image attachment exceeds ${MAX_PROVIDER_IMAGE_BYTES} bytes`); + } + let data = image.data; + let mimeType = image.mimeType ?? "image/png"; + if (data.startsWith("data:")) { + const separator = data.indexOf(";base64,"); + if (separator >= 0 && separator < 256) { + mimeType = data.slice(5, separator); + data = data.slice(separator + 8); + } + } + if (data.length > maxEncodedCharacters) { + throw new Error(`Image attachment exceeds ${MAX_PROVIDER_IMAGE_BYTES} bytes`); + } + const hash = createHash("sha256"); + for await (const bytes of decodeImage(data)) hash.update(bytes); + const dir = await getMaterializedImageAttachmentDir(); + const filePath = path.join(dir, `${hash.digest("hex")}.${getImageExtension(mimeType)}`); + try { + await fs.stat(filePath); + return { path: filePath }; + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; + } + + const staging = await fs.mkdtemp(path.join(dir, ".pending-")); + const stagingPath = path.join(staging, "image"); + try { + await fs.chmod(staging, PRIVATE_ATTACHMENT_DIR_MODE); + const file = await fs.open(stagingPath, "wx", MATERIALIZED_IMAGE_FILE_MODE); + try { + await file.chmod(MATERIALIZED_IMAGE_FILE_MODE); + // Decode again only for a new hash. This bounds retained memory to one chunk + // and performs no writes at all for repeated content, including history replay. + for await (const bytes of decodeImage(data)) await file.writeFile(bytes); + } finally { + await file.close(); + } + await fs.rename(stagingPath, filePath); + return { path: filePath }; + } finally { + await fs.rm(staging, { recursive: true, force: true }); + } +} + +async function* decodeImage(data: string): AsyncGenerator { + let carry = ""; + let decodedBytes = 0; + for (let offset = 0; offset < data.length; offset += BASE64_CHUNK_CHARACTERS) { + // Buffer.from ignores non-base64 characters. Carry incomplete quartets so + // line-wrapped payloads decode identically across chunk boundaries. + const chunk = + carry + + data.slice(offset, offset + BASE64_CHUNK_CHARACTERS).replace(/[^A-Za-z0-9+/_=-]/g, ""); + const finalChunk = offset + BASE64_CHUNK_CHARACTERS >= data.length || chunk.includes("="); + const end = finalChunk ? chunk.length : chunk.length - (chunk.length % 4); + const bytes = Buffer.from(chunk.slice(0, end), "base64"); + carry = chunk.slice(end); + decodedBytes += bytes.length; + if (decodedBytes > MAX_PROVIDER_IMAGE_BYTES) + throw new Error("Image attachment exceeds size limit"); + yield bytes; + await setImmediate(); + if (finalChunk) break; + } } // Recognizes markdown rendered for a materialized provider image: its source is a content-hashed @@ -112,7 +167,10 @@ export function isProviderImageMarkdown(text: string): boolean { } interface RenderProviderImageOutputOptions { - materialize?: (image: { data: string; mimeType: string | null }) => MaterializedProviderImage; + materialize?: (image: { + data: string; + mimeType: string | null; + }) => Promise; } function nonEmptyString(value: string | null | undefined): string | null { @@ -169,10 +227,10 @@ function escapeMarkdownImageSource(value: string): string { return markdownImageSource(value).replace(/\\/g, "\\\\").replace(/\)/g, "\\)"); } -export function renderProviderImageOutputAsAssistantMarkdown( +export async function renderProviderImageOutputAsAssistantMarkdown( image: ProviderImageOutput, options: RenderProviderImageOutputOptions = {}, -): AgentTimelineItem | null { +): Promise { const source = nonEmptyString(image.path) ?? nonEmptyString(image.url); if (source && !isDataImageSource(source)) { const altText = escapeMarkdownImageAlt(nonEmptyString(image.altText) ?? "Image"); @@ -191,7 +249,7 @@ export function renderProviderImageOutputAsAssistantMarkdown( let materialized: MaterializedProviderImage | null = null; try { materialized = options.materialize - ? options.materialize({ + ? await options.materialize({ data, mimeType: nonEmptyString(image.mimeType), }) diff --git a/packages/server/src/server/agent/providers/resume-process-cwd.ts b/packages/server/src/server/agent/providers/resume-process-cwd.ts new file mode 100644 index 0000000000..d32637a9a6 --- /dev/null +++ b/packages/server/src/server/agent/providers/resume-process-cwd.ts @@ -0,0 +1,26 @@ +import { stat } from "node:fs/promises"; +import { homedir } from "node:os"; + +import type { AgentResumePurpose } from "../agent-sdk-types.js"; + +export async function resolveResumeProcessCwd( + cwd: string, + purpose: AgentResumePurpose | undefined, +): Promise { + if (purpose !== "history" || (await isDirectory(cwd))) { + return cwd; + } + return homedir(); +} + +async function isDirectory(target: string): Promise { + try { + return (await stat(target)).isDirectory(); + } catch (error) { + const code = (error as NodeJS.ErrnoException).code; + if (code === "ENOENT" || code === "ENOTDIR") { + return false; + } + throw error; + } +} diff --git a/packages/server/src/server/agent/restart-recovery/index.test.ts b/packages/server/src/server/agent/restart-recovery/index.test.ts new file mode 100644 index 0000000000..0b1658b47d --- /dev/null +++ b/packages/server/src/server/agent/restart-recovery/index.test.ts @@ -0,0 +1,105 @@ +import { expect, test } from "vitest"; +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { AgentStorage, parseStoredAgentRecord } from "../agent-storage.js"; +import { createTestLogger } from "../../../test-utils/test-logger.js"; +import { createRestartRecovery } from "./index.js"; + +test("recovery saves intent before normalization, clears before dispatch, and resumes each agent independently", async () => { + const root = await mkdtemp(join(tmpdir(), "restart-recovery-")); + try { + const storage = new AgentStorage(root, createTestLogger()); + for (const [id, lastStatus] of [ + ["broken", "running"], + ["stuck", "running"], + ["working", "running"], + ["idle", "idle"], + ["initializing", "initializing"], + ] as const) { + await storage.upsert( + parseStoredAgentRecord({ + id, + lastStatus, + provider: "codex", + cwd: root, + createdAt: new Date().toISOString(), + updatedAt: new Date().toISOString(), + }), + ); + } + const dispatched: string[] = []; + const recovery = createRestartRecovery({ + storage, + settings: () => ({ enabled: true, prompt: "Continue verbatim.\n" }), + eligible: async () => true, + dispatch: async (id, prompt) => { + expect((await storage.get(id))?.resumeOnStartup).toBe(false); + if (id === "broken") throw new Error("unavailable"); + if (id === "stuck") return new Promise(() => {}); + dispatched.push(id + prompt); + }, + report: () => {}, + }); + await recovery.prepareStartup(); + expect((await storage.get("working"))?.resumeOnStartup).toBe(true); + expect((await storage.get("working"))?.lastStatus).toBe("closed"); + recovery.resumePending(); + const running = new AbortController().signal; + await recovery.waitForResume("broken", running); + await recovery.waitForResume("working", running); + await recovery.waitForResume("idle", running); + expect(dispatched).toEqual(["workingContinue verbatim.\n"]); + const stopped = new AbortController(); + stopped.abort(); + await expect(recovery.waitForResume("stuck", stopped.signal)).rejects.toBeDefined(); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("opt-out consumes pending recovery and excludes archived, private, owned and archived-workspace agents", async () => { + const root = await mkdtemp(join(tmpdir(), "restart-recovery-")); + try { + const storage = new AgentStorage(root, createTestLogger()); + for (const extra of [ + { id: "running" }, + { id: "archived", archivedAt: "today" }, + { id: "private", internal: true }, + { id: "owned", owner: { kind: "daemon", daemonId: "hub", executionId: "run" } }, + { id: "workspace", workspaceId: "archived" }, + ]) { + await storage.upsert( + parseStoredAgentRecord({ + lastStatus: "running", + provider: "codex", + cwd: root, + createdAt: new Date().toISOString(), + updatedAt: new Date().toISOString(), + ...extra, + }), + ); + } + let enabled = true; + const dispatched: string[] = []; + const recovery = createRestartRecovery({ + storage, + settings: () => ({ enabled, prompt: "Resume working." }), + eligible: async (record) => record.workspaceId !== "archived", + dispatch: async (id) => { + dispatched.push(id); + }, + report: () => {}, + }); + await recovery.captureRunningAgents(); + expect((await storage.get("running"))?.resumeOnStartup).toBe(true); + enabled = false; + await recovery.prepareStartup(); + enabled = true; + recovery.resumePending(); + expect(dispatched).toEqual([]); + expect((await storage.list()).every((record) => !record.resumeOnStartup)).toBe(true); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); diff --git a/packages/server/src/server/agent/restart-recovery/index.ts b/packages/server/src/server/agent/restart-recovery/index.ts new file mode 100644 index 0000000000..dc4e7d90c7 --- /dev/null +++ b/packages/server/src/server/agent/restart-recovery/index.ts @@ -0,0 +1,81 @@ +import type { AgentStorage, StoredAgentRecord } from "../agent-storage.js"; +interface Dependencies { + storage: AgentStorage; + settings(): { enabled: boolean; prompt: string }; + eligible(record: StoredAgentRecord): Promise; + dispatch(agentId: string, prompt: string): Promise; + report(agentId: string, error: unknown): void; +} +export function createRestartRecovery(deps: Dependencies) { + // Candidates are chosen at startup; each settles once its resume was sent or abandoned. + const resuming = new Map; resolve(): void }>(); + const eligible = async (record: StoredAgentRecord) => + !record.archivedAt && !record.internal && !record.owner && (await deps.eligible(record)); + async function resume(agentId: string) { + const record = await deps.storage.get(agentId); + if (!record?.resumeOnStartup) return; + await deps.storage.upsert({ ...record, resumeOnStartup: false }); + if (!deps.settings().enabled || !(await eligible(record))) return; + await deps.dispatch(agentId, deps.settings().prompt); + } + return { + /** Choose candidates before anything else reads or repairs persisted running status. */ + async prepareStartup() { + for (const record of await deps.storage.list()) { + const pending = + deps.settings().enabled && + (record.resumeOnStartup === true || record.lastStatus === "running") && + (await eligible(record)); + await deps.storage.upsert({ + ...record, + resumeOnStartup: pending, + lastStatus: + record.lastStatus === "running" || record.lastStatus === "initializing" + ? "closed" + : record.lastStatus, + }); + if (pending) { + let resolve!: () => void; + const promise = new Promise((settle) => { + resolve = settle; + }); + resuming.set(record.id, { promise, resolve }); + } + } + }, + async captureRunningAgents() { + await deps.storage.flush(); + for (const record of await deps.storage.list()) { + if (record.lastStatus === "running" && (await eligible(record))) + await deps.storage.upsert({ ...record, resumeOnStartup: deps.settings().enabled }); + } + }, + /** Resume every candidate in the background; a slow provider holds back only its agent. */ + resumePending() { + for (const [agentId, settled] of resuming) { + void resume(agentId) + .catch((error) => deps.report(agentId, error)) + .finally(() => { + resuming.delete(agentId); + settled.resolve(); + }); + } + }, + /** Wait until this agent's resume was sent or abandoned. Others return at once. */ + async waitForResume(agentId: string, signal: AbortSignal) { + const settled = resuming.get(agentId); + if (!settled) return; + let abort!: () => void; + const aborted = new Promise((_resolve, reject) => { + abort = () => reject(signal.reason); + if (signal.aborted) abort(); + else signal.addEventListener("abort", abort, { once: true }); + }); + try { + await Promise.race([settled.promise, aborted]); + } finally { + signal.removeEventListener("abort", abort); + } + }, + }; +} diff --git a/packages/server/src/server/agent/runtime-mcp-config.ts b/packages/server/src/server/agent/runtime-mcp-config.ts index af04e8021c..711638ce2f 100644 --- a/packages/server/src/server/agent/runtime-mcp-config.ts +++ b/packages/server/src/server/agent/runtime-mcp-config.ts @@ -1,6 +1,6 @@ import type { AgentSessionConfig, McpServerConfig } from "./agent-sdk-types.js"; -const PASEO_MCP_SERVER_NAME = "paseo"; +export const PASEO_MCP_SERVER_NAME = "paseo"; const PASEO_MCP_PATHNAME = "/mcp/agents"; export function stripInternalPaseoMcpServer(config: AgentSessionConfig): AgentSessionConfig { diff --git a/packages/server/src/server/agent/test-utils/plugin-stream-memory.ts b/packages/server/src/server/agent/test-utils/plugin-stream-memory.ts new file mode 100644 index 0000000000..948202bae2 --- /dev/null +++ b/packages/server/src/server/agent/test-utils/plugin-stream-memory.ts @@ -0,0 +1,176 @@ +import assert from "node:assert/strict"; +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { setTimeout as delay } from "node:timers/promises"; +import type { ProviderEvent, ProviderRegistration } from "@getpaseo/plugin/server/provider"; +import pino from "pino"; +import { PluginAgentClientRegistry } from "../plugin-provider.js"; +import { InMemoryAgentTimelineStore } from "../agent-timeline-store.js"; +import { AgentManager } from "../agent-manager.js"; +import { AgentStorage } from "../agent-storage.js"; +import { buildProviderRegistry } from "../provider-registry.js"; + +if (!global.gc) throw new Error("Run with --expose-gc"); +const logger = pino({ level: "silent" }); +const plugins = new PluginAgentClientRegistry(logger); +const root = await mkdtemp(join(tmpdir(), "plugin-stream-memory-")); +const emitters: Array<(event: ProviderEvent) => void> = []; +const ids: string[] = []; +const registrations: ProviderRegistration[] = Array.from({ length: 3 }, (_, index) => ({ + id: `memory-${index}`, + label: "Memory fixture", + async connect() { + let listener: (event: ProviderEvent) => void = () => {}; + const capabilities = ["prompt.message", "session.persistence"] as const; + return { + version: 1, + capabilities, + onEvent(callback) { + listener = callback; + // Plugin IPC delivers independent JSON strings, rather than shared ropes. + emitters[index] = (event) => listener(JSON.parse(JSON.stringify(event))); + return () => { + listener = () => {}; + }; + }, + async send(input) { + if (input.type === "session.open") { + ids[index] = input.sessionId; + listener({ + type: "session.opened", + requestId: input.requestId, + sessionId: input.sessionId, + cwd: "/tmp", + capabilities, + restoration: "core", + persistence: { version: 1, data: { index } }, + }); + listener({ + type: "session.ready", + requestId: input.requestId, + sessionId: input.sessionId, + }); + } else if (input.type === "catalog") { + listener({ + type: "catalog", + requestId: input.requestId, + catalog: { models: [], modes: [], thinkingOptions: [] }, + }); + } else if (input.type === "session.close") { + listener({ type: "session.closed", sessionId: input.sessionId }); + listener({ type: "request.completed", requestId: input.requestId }); + } + }, + async close() {}, + }; + }, +})); +plugins.replace(registrations); +const store = new InMemoryAgentTimelineStore(); +const manager = new AgentManager({ + clients: plugins.clients(), + providerDefinitions: buildProviderRegistry(logger, { pluginProviders: plugins.definitions() }), + registry: new AgentStorage(root, logger), + timelineStore: store, + logger, +}); +const agents = await Promise.all( + Object.keys(plugins.clients()).map((provider) => + manager.createAgent({ provider, cwd: root }, undefined, {}), + ), +); +const sessions = agents.map((agent) => agent.session!); +agents.forEach((_agent, index) => { + emitters[index]!({ + type: "session.opened", + sessionId: `child-${index}`, + parentSessionId: ids[index]!, + capabilities: [], + restoration: "parent", + cwd: root, + }); +}); +global.gc(); +const before = process.memoryUsage().heapUsed; +const steps = 4; +const chunks = 200; +const expected = new Map(); +for (let step = 0; step < steps; step++) { + for (let index = 0; index < sessions.length; index++) { + const text = `${index}:${step}:` + "推理".repeat(15000) + "a\uD83D\uDE00b"; + expected.set(`${index}:${step}`, text); + for (let chunk = 1; chunk <= chunks; chunk++) { + for (const sessionId of [ids[index]!, `child-${index}`]) { + emitters[index]!({ + type: "timeline.item", + sessionId, + item: { + type: "reasoning", + id: `reason-${step}`, + text: text.slice(0, Math.ceil((chunk * text.length) / chunks)), + }, + }); + } + } + emitters[index]!({ + type: "timeline.item", + sessionId: ids[index]!, + item: { + type: "tool_call", + id: `tool-${step}`, + callId: `tool-${step}`, + name: "read", + status: "completed", + error: null, + detail: { type: "unknown", input: null, output: "输出".repeat(16000) }, + }, + }); + emitters[index]!({ + type: "timeline.item", + sessionId: `child-${index}`, + item: { + type: "assistant_message", + id: `answer-${step}`, + text: "Child step complete.", + }, + }); + } + // Drain the manager's event queue; terminal tool states flush its real coalescer. + await delay(80); +} +global.gc(); +const retained = process.memoryUsage().heapUsed - before; +assert(retained < 24 * 1024 * 1024, `Retained heap exceeded 24 MiB: ${retained} bytes`); +for (let index = 0; index < sessions.length; index++) { + const items = store.getItems(agents[index]!.id); + assert.equal(items.length, steps * 2); + for (let step = 0; step < steps; step++) { + const item = items[step * 2]!; + assert.equal(item.type === "reasoning" && item.text, expected.get(`${index}:${step}`)); + } + const children = manager.listProviderSubagents(agents[index]!.id); + assert.equal(children.length, 1); + let rootItems = 0; + let childItems = 0; + for await (const event of sessions[index]!.streamHistory()) { + if (event.type === "timeline") rootItems++; + if (event.type === "provider_subagent" && event.event.type === "timeline") childItems++; + } + assert.equal(rootItems, steps * 2); + assert.equal(childItems, steps * 2); + await manager.archiveAgent(agents[index]!.id); + assert.equal(store.has(agents[index]!.id), false); + assert.equal( + manager.listAgents().some((agent) => agent.id === agents[index]!.id), + false, + ); +} +await plugins.shutdown(); +await manager.flushForShutdown(); +await rm(root, { recursive: true, force: true }); +global.gc(); +const closed = process.memoryUsage().heapUsed - before; +// Keep closed session references alive, as callers can retain them after archive. +assert.equal(sessions.length, 3); +process.stdout.write(JSON.stringify({ retained, closed })); diff --git a/packages/server/src/server/agent/test-utils/timeline-page-reference.ts b/packages/server/src/server/agent/test-utils/timeline-page-reference.ts index 8e9ab228a6..b3a51f22e5 100644 --- a/packages/server/src/server/agent/test-utils/timeline-page-reference.ts +++ b/packages/server/src/server/agent/test-utils/timeline-page-reference.ts @@ -234,7 +234,7 @@ export function selectReferenceProjectedTimelinePage(input: { // Existing selection fixtures exercise the retained owner through its public API. export function selectProjectedTimelinePage( - input: Parameters[0], + input: Parameters[0] & { wholeTurns?: boolean }, ) { const projection = new TimelineProjection(input.rows); const bounds = input.bounds ?? getTimelineBounds(input.rows) ?? { minSeq: 0, maxSeq: 0 }; diff --git a/packages/server/src/server/agent/test-utils/timeline-responsiveness.ts b/packages/server/src/server/agent/test-utils/timeline-responsiveness.ts new file mode 100644 index 0000000000..bfe5ee59c4 --- /dev/null +++ b/packages/server/src/server/agent/test-utils/timeline-responsiveness.ts @@ -0,0 +1,25 @@ +import { setImmediate as nextTurn } from "node:timers/promises"; +import { measureMainThreadWork } from "../../../test-utils/main-thread-work.js"; +import { InMemoryAgentTimelineStore } from "../agent-timeline-store.js"; + +// Measure a cold fetch on its own thread, without Vitest reporting or callbacks. +const wholeTurns = process.argv[2] === "true"; +const store = new InMemoryAgentTimelineStore(); +store.initialize("large"); +for (let index = 0; index < 100_000; index++) { + store.append("large", { type: "user_message", text: String(index) }); +} +// Finish fixture allocation and collect its temporary garbage before measuring. +globalThis.gc!(); +await nextTurn(); +const measured = await measureMainThreadWork( + `timeline tail main-thread work (wholeTurns=${wholeTurns})`, + () => { + let page = store.fetch("large", { limit: 200, wholeTurns }); + for (let repeat = 1; repeat < 8; repeat++) + page = store.fetch("large", { limit: 200, wholeTurns }); + return page; + }, +); + +process.stdout.write(JSON.stringify(measured)); diff --git a/packages/server/src/server/agent/timeline-projection.test.ts b/packages/server/src/server/agent/timeline-projection.test.ts index f2f832ffcf..d5e4c5b637 100644 --- a/packages/server/src/server/agent/timeline-projection.test.ts +++ b/packages/server/src/server/agent/timeline-projection.test.ts @@ -534,6 +534,154 @@ describe("selectProjectedTimelinePage", () => { }; } + test("whole-turn pages extend past the soft target and keep prompt jumps whole", () => { + const rows: AgentTimelineRow[] = Array.from({ length: 125 }, (_, index) => ({ + seq: index + 1, + timestamp: new Date(1000 + index).toISOString(), + turnId: ["short", "long", "latest"][Number(index >= 3) + Number(index >= 123)], + item: { + type: "tool_call", + callId: `tool-${index}`, + name: "shell", + status: "completed", + error: null, + detail: { type: "unknown", input: null, output: null }, + }, + })); + const tail = selectProjectedTimelinePage({ + rows, + direction: "tail", + limit: 40, + wholeTurns: true, + }); + expect(tail.entries.map((entry) => entry.seqStart)).toEqual( + rows.slice(3).map((row) => row.seq), + ); + expect(tail).toMatchObject({ startSeq: 4, endSeq: 125, hasOlder: true, hasNewer: false }); + const before = selectProjectedTimelinePage({ + rows, + direction: "before", + cursorSeq: 124, + limit: 40, + wholeTurns: true, + }); + expect(before.entries.map((entry) => entry.seqStart)).toEqual( + rows.slice(3, 123).map((row) => row.seq), + ); + expect(before.endSeq).toBe(123); + const older = selectProjectedTimelinePage({ + rows, + direction: "before", + cursorSeq: 4, + limit: 40, + wholeTurns: true, + }); + expect(older.entries.map((entry) => entry.seqStart)).toEqual([1, 2, 3]); + expect(older.hasOlder).toBe(false); + const jump = selectProjectedTimelinePage({ + rows, + direction: "before", + cursorSeq: 70, + limit: 40, + wholeTurns: true, + }); + expect(jump.entries.map((entry) => entry.seqStart)).toEqual( + rows.slice(3, 123).map((row) => row.seq), + ); + expect(jump).toMatchObject({ startSeq: 4, endSeq: 123, hasOlder: true, hasNewer: true }); + const nearPreviousPrompt = selectProjectedTimelinePage({ + rows, + direction: "before", + cursorSeq: 10, + limit: 40, + wholeTurns: true, + }); + expect(nearPreviousPrompt).toMatchObject({ startSeq: 1, endSeq: 123 }); + expect( + selectProjectedTimelinePage({ rows, direction: "tail", limit: 40 }).entries, + ).toHaveLength(40); + }); + + test("whole-turn pages share short runs and use the same deterministic legacy triggers", () => { + const rows: AgentTimelineRow[] = Array.from({ length: 24 }, (_, index) => ({ + seq: index + 1, + timestamp: new Date(1000 + index).toISOString(), + item: + index % 2 === 0 + ? { type: "user_message", text: `prompt-${index}` } + : { type: "assistant_message", text: `reply-${index}` }, + })); + const page = selectProjectedTimelinePage({ + rows, + direction: "tail", + limit: 7, + wholeTurns: true, + }); + expect(page.entries.map((entry) => entry.seqStart)).toEqual([17, 18, 19, 20, 21, 22, 23, 24]); + expect( + selectProjectedTimelinePage({ rows, direction: "tail", limit: 0, wholeTurns: true }).entries, + ).toHaveLength(24); + rows.push({ + ...toolRow(25, "completed"), + item: { ...toolRow(25, "completed").item, name: "heartbeat" } as AgentTimelineRow["item"], + }); + rows.push({ + seq: 26, + timestamp: new Date().toISOString(), + item: { type: "assistant_message", text: "awake" }, + }); + expect( + selectProjectedTimelinePage({ + rows, + direction: "tail", + limit: 1, + wholeTurns: true, + }).entries.map((entry) => entry.seqStart), + ).toEqual([25, 26]); + }); + + test("whole-turn tails close interleaved source coverage without changing forward catch-up", () => { + const rows: AgentTimelineRow[] = [ + { + seq: 1, + timestamp: new Date(1).toISOString(), + turnId: "first", + item: { type: "user_message", text: "go" }, + }, + { ...toolRow(2, "running"), turnId: "first" }, + { + seq: 3, + timestamp: new Date(3).toISOString(), + turnId: "second", + item: { type: "user_message", text: "next" }, + }, + { + seq: 4, + timestamp: new Date(4).toISOString(), + turnId: "second", + item: { type: "assistant_message", text: "done" }, + }, + { ...toolRow(5, "completed"), turnId: "first" }, + ]; + expect( + selectProjectedTimelinePage({ rows, direction: "tail", limit: 1, wholeTurns: true }), + ).toMatchObject({ + startSeq: 1, + endSeq: 5, + hasOlder: false, + hasNewer: false, + }); + expect( + selectProjectedTimelinePage({ + rows, + direction: "after", + cursorSeq: 2, + limit: 1, + wholeTurns: true, + }), + ).toEqual(selectProjectedTimelinePage({ rows, direction: "after", cursorSeq: 2, limit: 1 })); + }); + test("tail page returns full projected items instead of tool lifecycle deltas", () => { const rows: AgentTimelineRow[] = [ { seq: 1, timestamp: "2026-02-13T00:00:00.000Z", item: { type: "user_message", text: "go" } }, diff --git a/packages/server/src/server/agent/timeline-projection.ts b/packages/server/src/server/agent/timeline-projection.ts index 3a65f28531..bd5357e581 100644 --- a/packages/server/src/server/agent/timeline-projection.ts +++ b/packages/server/src/server/agent/timeline-projection.ts @@ -1,3 +1,4 @@ +import { continuesTimelineTurn, isTimelineTurnTrigger } from "@getpaseo/protocol/timeline-turn"; import type { AgentTimelineItem, ToolCallDetail } from "./agent-sdk-types.js"; import { timelineItemIdentity } from "@getpaseo/protocol/timeline-identity"; @@ -296,6 +297,7 @@ function mergeAssistantChunks(entries: readonly WorkingEntry[]): WorkingEntry[] export type ProjectedTimelineRow = AgentTimelineRow & TimelineProjectionEntry; interface ProjectedTimelinePageOptions { + wholeTurns?: boolean; bounds: { minSeq: number; maxSeq: number }; direction: TimelineLimitDirection; cursorSeq?: number; @@ -321,7 +323,7 @@ export class TimelineProjection { this.sourceRanges.sort((a, b) => a.startSeq - b.startSeq); } - append(row: AgentTimelineRow): void { + append(row: AgentTimelineRow): ProjectedTimelineRow { const rowIndex = this.appendProjected(row); const last = this.sourceRanges.at(-1); if (last && last.rowIndex === rowIndex && last.endSeq + 1 === row.seq) { @@ -329,6 +331,7 @@ export class TimelineProjection { } else { this.sourceRanges.push({ startSeq: row.seq, endSeq: row.seq, rowIndex }); } + return { ...this.rows[rowIndex] }; } private appendProjected(row: AgentTimelineRow): number { @@ -423,7 +426,8 @@ export class TimelineProjection { private selectTail(input: ProjectedTimelinePageOptions): ProjectedTimelinePageSelection { const limit = Math.max(0, Math.floor(input.limit ?? 0)); const requestedStart = limit === 0 ? 0 : Math.max(0, this.rows.length - limit); - const start = this.spans[this.spanIndex(requestedStart)].start; + const coveredStart = this.spans[this.spanIndex(requestedStart)].start; + const start = input.wholeTurns ? this.wholeTurnWindowStart(coveredStart) : coveredStart; return { entries: this.rows.slice(start), startSeq: this.rows[start].seqStart, @@ -433,6 +437,17 @@ export class TimelineProjection { }; } + private wholeTurnWindowStart(requestedStart: number): number { + let start = requestedStart; + for (;;) { + while (start > 0 && continuesProjectedTurn(this.rows[start - 1], this.rows[start])) start--; + // Source coverage can pull in an earlier tool and therefore its entire run. + const coveredStart = this.spans[this.spanIndex(start)].start; + if (coveredStart === start) return start; + start = coveredStart; + } + } + private selectAfter(input: ProjectedTimelinePageOptions): ProjectedTimelinePageSelection { const startSeq = Math.max( input.bounds.minSeq, @@ -480,13 +495,23 @@ export class TimelineProjection { else high = middle; } const limit = Math.max(0, Math.floor(input.limit ?? 0)); - const start = limit === 0 ? 0 : Math.max(0, low - limit); + const requestedStart = limit === 0 ? 0 : Math.max(0, low - limit); + const start = input.wholeTurns ? this.wholeTurnWindowStart(requestedStart) : requestedStart; + // Choose the window before extending the right edge, so a prompt jump + // cannot lose its target when the next turn is arbitrarily large. + if (input.wholeTurns) { + while (low < this.rows.length && continuesProjectedTurn(this.rows[low - 1], this.rows[low])) + low++; + } + let selectedEnd = endSeq; + if (input.wholeTurns) + selectedEnd = low === this.rows.length ? input.bounds.maxSeq : this.rows[low].seqStart - 1; return { entries: this.rows.slice(start, low), startSeq: this.rows[start]?.seqStart ?? null, - endSeq, + endSeq: selectedEnd, hasOlder: start > 0, - hasNewer: endSeq < input.bounds.maxSeq, + hasNewer: selectedEnd < input.bounds.maxSeq, }; } return { entries: [], startSeq: null, endSeq: null, hasOlder: false, hasNewer: true }; @@ -675,6 +700,13 @@ function selectProjectedEntriesAfter(input: { }; } +function continuesProjectedTurn( + previous: TimelineProjectionEntry, + next: TimelineProjectionEntry, +): boolean { + return continuesTimelineTurn(previous.turnId, next.turnId, isTimelineTurnTrigger(next.item)); +} + /** * Apply a projected-count limit to a flat AgentTimelineItem[] without seq metadata. * Used by callers that only have items in hand (e.g. MCP tools reading diff --git a/packages/server/src/server/bootstrap.smoke.test.ts b/packages/server/src/server/bootstrap.smoke.test.ts index f6304491ab..ac045741f1 100644 --- a/packages/server/src/server/bootstrap.smoke.test.ts +++ b/packages/server/src/server/bootstrap.smoke.test.ts @@ -670,11 +670,11 @@ describe("paseo daemon bootstrap", () => { test("rolls back standalone listener without starting plugins when main listen fails", async () => { const mainPort = await findFreePort(); - const standalonePort = await findFreePort(); const occupiedMain = http.createServer((_req, res) => { res.end("occupied-main"); }); await new Promise((resolve) => occupiedMain.listen(mainPort, "127.0.0.1", resolve)); + const standalonePort = await findFreePort(); const paseoHomeRoot = await mkdtemp(path.join(os.tmpdir(), "paseo-main-rollback-")); const paseoHome = path.join(paseoHomeRoot, ".paseo"); @@ -1069,7 +1069,7 @@ function probeWebSocketConnection( }); } -test("startup closes stale active records before serving status without resuming sessions", async () => { +test("disabled recovery closes stale active records without resuming sessions", async () => { const root = await mkdtemp(path.join(os.tmpdir(), "paseo-stale-status-")); const logger = pino({ level: "silent" }); const storagePath = path.join(root, ".paseo", "agents"); @@ -1121,6 +1121,7 @@ test("startup closes stale active records before serving status without resuming let sessionsCreated = 0; const handle = await createTestPaseoDaemon({ paseoHomeRoot: root, + resumeOnStartup: false, agentClients: createTestAgentClients({ beforeCreateSession: async () => { sessionsCreated++; @@ -1131,6 +1132,7 @@ test("startup closes stale active records before serving status without resuming try { const expected = records.map((record) => ({ ...record, + resumeOnStartup: false, lastStatus: record.lastStatus === "running" || record.lastStatus === "initializing" ? "closed" diff --git a/packages/server/src/server/bootstrap.ts b/packages/server/src/server/bootstrap.ts index 83ef2acb83..fa896ef898 100644 --- a/packages/server/src/server/bootstrap.ts +++ b/packages/server/src/server/bootstrap.ts @@ -1,3 +1,5 @@ +import { createRestartRecovery } from "./agent/restart-recovery/index.js"; +import { sendPromptToAgent } from "./agent/agent-prompt.js"; import { createIdleRuntimeCleanup } from "./agent/idle-runtime-cleanup/index.js"; import { createFinishSubscriptions, @@ -180,7 +182,7 @@ import { import { setupAutoArchiveOnMerge } from "./auto-archive-on-merge/index.js"; import { wrapSessionMessage, type SessionOutboundMessage } from "./messages.js"; import type { TerminalManager } from "../terminal/terminal-manager.js"; -import { createConfiguredTerminalManager } from "../terminal/terminal-manager-factory.js"; +import { startWorkerTerminalManager } from "../terminal/worker-terminal-manager.js"; import { applyTerminalAgentHookSetting } from "../terminal/agent-hooks/terminal-agent-hook-setting.js"; import { loadOrCreateDaemonKeyPair } from "./daemon-keypair.js"; import { createRelayRuntime, type RelayRuntime } from "./relay-runtime.js"; @@ -396,12 +398,14 @@ export type DaemonLifecycleIntent = clientId: string; requestId: string; reason: string; + keepTerminals: boolean; } | { type: "restart"; clientId: string; requestId: string; reason: string; + keepTerminals: boolean; }; export interface PaseoDaemonConfig { @@ -416,6 +420,7 @@ export interface PaseoDaemonConfig { trustedProxies?: true | string[]; mcpEnabled?: boolean; mcpInjectIntoAgents?: boolean; + usageEnabled?: boolean; browserToolsEnabled?: boolean; git?: { maxProcessesPerSecond: number; @@ -462,6 +467,8 @@ export interface PaseoDaemonConfig { downloadTokenTtlMs?: number; agentProviderSettings?: AgentProviderRuntimeSettingsMap; idleRuntimeCleanup?: boolean; + resumeOnStartup?: boolean; + resumePrompt?: string; providerCatalogRefreshTimeoutMs?: number; metadataGeneration?: { providers?: Array<{ @@ -493,7 +500,8 @@ export interface PaseoDaemon { scriptRuntimeStore: WorkspaceScriptRuntimeStore; browserToolsBroker: BrowserToolsBroker; start(): Promise; - stop(): Promise; + /** Stops the daemon. Terminals keep running for the next daemon only with keepTerminals. */ + stop(options?: { keepTerminals?: boolean }): Promise; getListenTarget(): ListenTarget | null; getServerId(): string; } @@ -583,6 +591,7 @@ function createInitialMutableDaemonConfig(config: ResolvedDaemonSettings): Mutab ...(config.providerCatalogRefreshTimeoutMs !== undefined ? { catalogRefreshTimeoutMs: config.providerCatalogRefreshTimeoutMs } : {}), + usage: { enabled: config.usageEnabled !== false }, browserTools: { enabled: config.browserToolsEnabled ?? false }, providers, metadataGeneration: { @@ -591,6 +600,8 @@ function createInitialMutableDaemonConfig(config: ResolvedDaemonSettings): Mutab autoArchiveAfterMerge: config.autoArchiveAfterMerge ?? false, enableTerminalAgentHooks: config.enableTerminalAgentHooks ?? false, idleRuntimeCleanup: config.idleRuntimeCleanup !== false, + resumeOnStartup: config.resumeOnStartup !== false, + resumePrompt: config.resumePrompt ?? "Resume working.", appendSystemPrompt: config.appendSystemPrompt ?? "", pluginsEnabled: config.pluginsEnabled ?? false, plugins: config.plugins ?? {}, @@ -709,7 +720,10 @@ export async function createPaseoDaemon( }); let boundListenTarget: ListenTarget | null = null; let workspaceRegistry: FileBackedWorkspaceRegistry | null = null; - const terminalManager = createConfiguredTerminalManager({ + const terminalManager = await startWorkerTerminalManager({ + paseoHome: config.paseoHome, + paseoVersion: daemonVersion, + logger, getTerminalActivityUrl: () => createTerminalActivityUrl(boundListenTarget), }); applyTerminalAgentHookSetting({ store: daemonConfigStore, logger }); @@ -957,7 +971,7 @@ export async function createPaseoDaemon( if (!hasActiveWorkspace) workspaceRuntimeStore.remove(cwd); } if (mutation.kind === "archive" && mutation.workspace) { - pluginRuntime.emit("workspace.archived", { + pluginRuntime.emit("workspace.archive.after", { workspace: describeHookWorkspace(mutation.workspace), }); } @@ -1030,7 +1044,19 @@ export async function createPaseoDaemon( agentStorage, ); await agentStorage.initialize(); - await closeStaleAgentRecords(agentStorage); + const restartRecovery = createRestartRecovery({ + storage: agentStorage, + settings: () => ({ + enabled: daemonConfigStore.get().resumeOnStartup !== false, + prompt: daemonConfigStore.get().resumePrompt ?? "Resume working.", + }), + eligible: async (record) => + !record.workspaceId || !(await workspaceRegistry?.get(record.workspaceId))?.archivedAt, + dispatch: (agentId, prompt) => + sendPromptToAgent({ agentId, prompt, agentManager, agentStorage, logger, unarchive: false }), + report: (agentId, err) => logger.error({ agentId, err }, "Agent restart recovery failed"), + }); + await restartRecovery.prepareStartup(); logger.info({ elapsed: elapsed() }, "Agent storage initialized"); await bootstrapWorkspaceRegistries({ serverId, @@ -1206,6 +1232,7 @@ export async function createPaseoDaemon( worktreesRoot: config.worktreesRoot, createPaseoWorktree: async (workflowInput, workflowOptions) => { return createRegisteredPaseoWorktree(workflowInput, { + lifecycle: pluginRuntime, github, ...(workflowOptions?.resolveDefaultBranch ? { @@ -1463,6 +1490,7 @@ export async function createPaseoDaemon( ...createFinishObservation({ agentManager, agentStorage, + waitForResume: restartRecovery.waitForResume, serverId, logger, messages: () => { @@ -1862,6 +1890,7 @@ export async function createPaseoDaemon( pluginRuntime.bindPaseoSessionHost(wsServer); await pluginRuntime.start(); providerSnapshotManager.settlePluginProviders(); + restartRecovery.resumePending(); await finishSubscriptions.start(); wsServer.beginAcceptingConnections(); const relaySecurityLogger = logger.child({ module: "relay-security" }); @@ -1935,7 +1964,9 @@ export async function createPaseoDaemon( } }; - const stop = async () => { + const stop = async (options?: { keepTerminals?: boolean }) => { + const keepTerminals = options?.keepTerminals === true; + let terminalShutdownError: unknown = null; localCredential = null; await deleteLocalCredential(config.paseoHome); // Stop tracking plugin provider registrations before anything tears plugins @@ -1954,6 +1985,7 @@ export async function createPaseoDaemon( await finishSubscriptions.close(); await wsServer?.agentMessages.close(); agentManager.prepareForShutdown(); + await restartRecovery.captureRunningAgents(); await closeAllAgents(logger, agentManager); await withTimeout({ promise: pluginRuntime.drainEvents(), @@ -1965,7 +1997,19 @@ export async function createPaseoDaemon( await agentStorage.flush().catch(() => undefined); await agentProviderRuntime.shutdown(); await pluginRuntime.stopAllPlugins(); - terminalManager.killAll(); + try { + if (keepTerminals) { + await terminalManager.detach(); + logger.info("Terminals left running for the next daemon"); + } else { + await terminalManager.closeTerminals(); + } + } catch (error) { + // Finish the rest of the shutdown, then report it: the supervisor and `daemon stop` + // retry the cleanup from the record the reaper kept. + terminalShutdownError = error; + logger.error({ err: error }, "Terminal shutdown failed"); + } await speechService.stop(); await scheduleService.stop().catch(() => undefined); await relayRuntime?.stop().catch(() => undefined); @@ -1988,6 +2032,9 @@ export async function createPaseoDaemon( if (listenTarget.type === "socket" && existsSync(listenTarget.path)) { unlinkSync(listenTarget.path); } + if (terminalShutdownError) { + throw terminalShutdownError; + } }; return { @@ -2005,16 +2052,6 @@ export async function createPaseoDaemon( }; } -async function closeStaleAgentRecords(agentStorage: AgentStorage): Promise { - // No provider runtimes are loaded at startup. Repair interrupted - // shutdowns before any status consumer sees the persisted active states. - for (const record of await agentStorage.list()) { - if (record.lastStatus === "running" || record.lastStatus === "initializing") { - await agentStorage.upsert({ ...record, lastStatus: "closed" }); - } - } -} - /** * Closing an agent asks its provider to close the session and waits for the * answer. A provider that never answers must not hold the daemon open, so a diff --git a/packages/server/src/server/config.test.ts b/packages/server/src/server/config.test.ts index 72d1c30f7d..53a77338b6 100644 --- a/packages/server/src/server/config.test.ts +++ b/packages/server/src/server/config.test.ts @@ -1,3 +1,4 @@ +import { measureMainThreadWork } from "../test-utils/main-thread-work.js"; import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; @@ -25,22 +26,18 @@ describe("server config", () => { const env = { PASEO_PASSWORD: "synthetic-audit-password" }; const persisted = loadPersistedConfig(paseoHome); const startup = resolveConfigFromPersisted(paseoHome, persisted, { env }); - const started = performance.now(); - const timer = new Promise((resolve) => - setTimeout(() => resolve(performance.now() - started), 0), + const { result: reloaded, blockingMs } = await measureMainThreadWork( + "config resolve main-thread work", + () => + resolveReloadableConfig( + { ...persisted, daemon: { ...persisted.daemon, browserTools: { enabled: true } } }, + { env }, + ), ); - const reloaded = resolveReloadableConfig( - { - ...persisted, - daemon: { ...persisted.daemon, browserTools: { enabled: true } }, - }, - { env }, - ); - const gap = await timer; expect(reloaded).not.toHaveProperty("auth"); expect(reloaded.browserToolsEnabled).toBe(true); expect(startup.auth?.password).toBeTypeOf("string"); - expect(gap).toBeLessThan(50); + expect(blockingMs).toBeLessThan(50); }); test("records when the daemon is managed by Paseo Desktop", async () => { diff --git a/packages/server/src/server/config.ts b/packages/server/src/server/config.ts index add78aa7f5..07c5c287b8 100644 --- a/packages/server/src/server/config.ts +++ b/packages/server/src/server/config.ts @@ -523,6 +523,10 @@ function resolveAppendSystemPrompt(persisted: ReturnType): boolean { + return persisted.daemon?.usage?.enabled !== false; +} + function resolveBrowserToolsEnabled(persisted: ReturnType): boolean { return persisted.daemon?.browserTools?.enabled ?? false; } @@ -548,6 +552,7 @@ function resolveStaticLoadConfigSettings( mcpEnabled: cli?.mcpEnabled ?? persisted.daemon?.mcp?.enabled ?? true, mcpInjectIntoAgents: cli?.mcpInjectIntoAgents ?? persisted.daemon?.mcp?.injectIntoAgents ?? false, + usageEnabled: resolveUsageEnabled(persisted), browserToolsEnabled: resolveBrowserToolsEnabled(persisted), autoArchiveAfterMerge: persisted.daemon?.autoArchiveAfterMerge ?? false, appendSystemPrompt: resolveAppendSystemPrompt(persisted), @@ -576,6 +581,7 @@ export type ResolvedDaemonSettings = Pick< | "trustedProxies" | "mcpEnabled" | "mcpInjectIntoAgents" + | "usageEnabled" | "browserToolsEnabled" | "git" | "autoArchiveAfterMerge" @@ -590,6 +596,8 @@ export type ResolvedDaemonSettings = Pick< | "relayRequireProtectedSecurity" | "appBaseUrl" | "idleRuntimeCleanup" + | "resumeOnStartup" + | "resumePrompt" | "providerCatalogRefreshTimeoutMs" | "metadataGeneration" | "providerOverrides" @@ -677,6 +685,7 @@ export function resolveReloadableConfig( relayEnabled: relay.enabled, relayRequireProtectedSecurity: relay.requireProtectedSecurity, idleRuntimeCleanup: persisted.agents?.idleRuntimeCleanup ?? true, + ...resolveRestartRecoveryConfig(persisted.agents), providerCatalogRefreshTimeoutMs: persisted.agents?.catalogRefreshTimeoutMs, metadataGeneration: persisted.agents?.metadataGeneration, providerOverrides: extractProviderOverrides( @@ -827,3 +836,10 @@ function resolveSpeechOverrideControlledPaths( if (env.PASEO_LOCAL_MODELS_DIR !== undefined) paths.push("providers.local.modelsDir"); return paths; } + +function resolveRestartRecoveryConfig(agents: PersistedConfig["agents"]) { + return { + resumeOnStartup: agents?.resumeOnStartup ?? true, + resumePrompt: agents?.resumePrompt ?? "Resume working.", + }; +} diff --git a/packages/server/src/server/connected-hosts/hosts.e2e.test.ts b/packages/server/src/server/connected-hosts/hosts.e2e.test.ts index b6765051f6..264589f82e 100644 --- a/packages/server/src/server/connected-hosts/hosts.e2e.test.ts +++ b/packages/server/src/server/connected-hosts/hosts.e2e.test.ts @@ -784,6 +784,211 @@ test("old capabilities fail before execution and authentication errors recover t expect((await online(paseo)).hosts[0]!.serverId).toBe(b.daemon.getServerId()); }); +async function updatableDestination() { + let features: { connectedHosts: boolean; hostMultiplexing: boolean } | undefined; + let holding = false; + const held: (() => void)[] = []; + let connections = 0; + const http = createServer(); + const ws = new WebSocketServer({ server: http }); + ws.on("connection", (socket) => { + connections++; + socket.on("message", (data) => { + const frame = JSON.parse(data.toString()); + if (frame.type === "ping") socket.send(JSON.stringify({ type: "pong" })); + if (frame.type !== "hello") return; + const reply = () => + socket.send( + JSON.stringify({ + type: "session", + message: { + type: "status", + payload: { + status: "server_info", + serverId: "srv_updated", + hostname: "updated", + version: "0.12.0", + ...(features ? { features } : {}), + }, + }, + }), + ); + if (holding) held.push(reply); + else reply(); + }); + }); + http.listen(0, "127.0.0.1"); + await once(http, "listening"); + cleanup.push(async () => { + for (const socket of ws.clients) socket.terminate(); + await new Promise((resolve) => ws.close(() => resolve())); + await new Promise((resolve) => http.close(() => resolve())); + }); + const address = http.address(); + if (!address || typeof address === "string") throw new Error("Missing destination port"); + return { + port: address.port, + connections: () => connections, + hold: () => { + holding = true; + }, + update: () => { + features = { connectedHosts: true, hostMultiplexing: true }; + holding = false; + for (const reply of held.splice(0)) reply(); + }, + }; +} +async function capabilityRetry(paseo: ReturnType): Promise { + let retryAt = ""; + await expect + .poll( + async () => { + const row = (await paseo.hosts.list()).hosts[0]; + retryAt = row?.nextRetryAt ?? ""; + return row; + }, + { timeout: 5000 }, + ) + .toMatchObject({ + status: "offline", + nextRetryAt: expect.any(String), + error: { code: "unsupported_capability" }, + }); + return Date.parse(retryAt); +} + +test("a destination updated past unsupported_capability keeps its guidance while retrying and comes online, while duplicate_host stays terminal", async () => { + const destination = await updatableDestination(); + const a = await daemon(); + const { paseo } = await api(a); + const host = await paseo.hosts.add({ connection: `127.0.0.1:${destination.port}` }); + await capabilityRetry(paseo); + destination.hold(); + await expect + .poll(async () => (await paseo.hosts.list()).hosts[0], { timeout: 5000 }) + .toMatchObject({ status: "connecting", error: { code: "unsupported_capability" } }); + await expect(paseo.hosts.client("srv_updated")).rejects.toMatchObject({ + code: "unsupported_capability", + }); + destination.update(); + expect((await online(paseo)).hosts[0]).toMatchObject({ + registrationId: host.registrationId, + serverId: "srv_updated", + nextRetryAt: null, + error: null, + }); + await paseo.hosts.add({ connection: `ws://127.0.0.1:${destination.port}/ws` }); + await expect + .poll(async () => (await paseo.hosts.list()).hosts[1], { timeout: 5000 }) + .toMatchObject({ status: "error", nextRetryAt: null, error: { code: "duplicate_host" } }); +}); + +test("disabling or removing a host cancels its pending capability retry", async () => { + const destination = await updatableDestination(); + const a = await daemon(); + const { paseo } = await api(a); + const host = await paseo.hosts.add({ connection: `127.0.0.1:${destination.port}` }); + let retryAt = await capabilityRetry(paseo); + let connections = destination.connections(); + await paseo.hosts.update(host.registrationId, { enabled: false }); + await new Promise((resolve) => setTimeout(resolve, retryAt - Date.now() + 500)); + expect(destination.connections()).toBe(connections); + await paseo.hosts.update(host.registrationId, { enabled: true }); + retryAt = await capabilityRetry(paseo); + connections = destination.connections(); + await paseo.hosts.remove(host.registrationId); + await new Promise((resolve) => setTimeout(resolve, retryAt - Date.now() + 500)); + expect(destination.connections()).toBe(connections); +}); + +import { + createDaemonChannel, + exportPublicKey, + generateKeyPair, + openDaemonSecureChannel, + type Transport, +} from "@getpaseo/relay/e2ee"; +test("a capability retry over a relay keeps the protected endpoint security it negotiated", async () => { + const keys = generateKeyPair(); + const legacyReceived: unknown[] = []; + let connections = 0; + let retryClosed = false; + const http = createServer(); + const ws = new WebSocketServer({ server: http }); + ws.on("connection", (socket) => { + connections++; + const wire: Transport = { + send: (data) => socket.send(data), + close: (code, reason) => socket.close(code, reason), + onmessage: null, + onclose: null, + onerror: null, + }; + socket.on("message", (data, isBinary) => { + const bytes = Buffer.from(data as Buffer); + wire.onmessage?.({ + data: isBinary + ? bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) + : bytes.toString(), + isBinary, + }); + }); + socket.on("close", (code, reason) => wire.onclose?.(code, reason.toString())); + if (connections > 1) { + socket.on("close", () => { + retryClosed = true; + }); + void createDaemonChannel(wire, keys, { + onmessage: (data) => legacyReceived.push(data), + }).catch(() => {}); + return; + } + const channel = openDaemonSecureChannel(wire, { + daemonKeyPair: keys, + events: { + onmessage: (data) => { + if (typeof data !== "string" || JSON.parse(data).type !== "hello") return; + void channel.then((secure) => + secure.send( + JSON.stringify({ + type: "session", + message: { + type: "status", + payload: { + status: "server_info", + serverId: "srv_relayed", + hostname: "relayed", + version: "0.12.0", + }, + }, + }), + ), + ); + }, + }, + }); + void channel.catch(() => {}); + }); + http.listen(0, "127.0.0.1"); + await once(http, "listening"); + cleanup.push(async () => { + for (const socket of ws.clients) socket.terminate(); + await new Promise((resolve) => ws.close(() => resolve())); + await new Promise((resolve) => http.close(() => resolve())); + }); + const address = http.address(); + if (!address || typeof address === "string") throw new Error("Missing relay port"); + const a = await daemon(); + const { paseo } = await api(a); + await paseo.hosts.add({ + connection: `relay://127.0.0.1:${address.port}/srv_relayed?key=${encodeURIComponent(exportPublicKey(keys.publicKey))}`, + }); + await capabilityRetry(paseo); + await expect.poll(() => retryClosed, { timeout: 15000 }).toBe(true); + expect(legacyReceived).toEqual([]); +}); + test("an unreachable saved target becomes online after its daemon starts without being added again", async () => { const reservation = createServer(); reservation.listen(0, "127.0.0.1"); @@ -2091,3 +2296,80 @@ test.each(["removed", "disabled"] as const)( ).toEqual([]); }, ); + +test( + "a 50 MiB timeline crosses a routed host without dropping content or the route", + { timeout: 30000 }, + async () => { + const b = await daemon(); + const a = await daemon(); + const destination = await api(b); + const origin = await api(a); + const workspace = await destination.paseo.workspaces.create({ + source: { kind: "directory", path: b.staticDir }, + }); + const agent = await workspace.agents.create({ + config: { provider: "claude/claude-test", modeId: "full-access" }, + title: "Large history", + }); + // Keep each row below the established item budget; exercise transport size across rows. + const text = "x".repeat(240 * 1024); + const rowCount = 220; + for (let index = 0; index < rowCount; index++) { + await b.daemon.agentManager.appendTimelineItem(agent.id, { type: "user_message", text }); + } + await origin.paseo.hosts.add({ connection: `127.0.0.1:${b.port}` }); + const serverId = (await online(origin.paseo)).hosts[0]!.serverId!; + const remote = await origin.paseo.hosts.client(serverId); + const response = await remote.agents.ref(agent.id).timeline.refetch({ limit: 0 }); + const messages = response.entries.flatMap((row) => + row.item.type === "user_message" ? [row.item.text] : [], + ); + expect(messages).toHaveLength(rowCount); + expect(messages.every((message) => message === text)).toBe(true); + expect( + messages.reduce((bytes, message) => bytes + Buffer.byteLength(message), 0), + ).toBeGreaterThan(50 * 1024 * 1024); + expect((await remote.workspaces.list()).entries).toHaveLength(1); + await remote.dispose(); + }, +); + +test("a pre-write host budget rejection leaves sibling routes connected", async () => { + const { HostTransportBudget } = await import("@getpaseo/client/node"); + const b = await daemon(); + const origin = createHostClient( + `127.0.0.1:${b.port}`, + { clientId: "budget-origin", reconnect: { enabled: false } }, + new HostTransportBudget(1024 * 1024), + ); + cleanup.push(() => origin.close()); + await origin.connect(); + const serverId = origin.getLastServerInfoMessage()!.serverId; + const routeIds = [ + await origin.openHostLink("budget-first"), + await origin.openHostLink("budget-sibling"), + ]; + const peers = routeIds.map( + (id, index) => + new DaemonClient({ + url: "ws://host-link/ws", + clientId: `budget-child-${index}`, + reconnect: { enabled: false }, + transportFactory: createHostChannelTransport(origin, serverId, `budget-${index}`, id), + }), + ); + for (const peer of peers) { + cleanup.push(() => peer.close()); + await peer.connect(); + } + await expect(async () => + origin.sendHostFrame(routeIds[0]!, new Uint8Array(2 * 1024 * 1024)), + ).rejects.toMatchObject({ code: "resource_limit" }); + await peers[1]!.ping({ timeoutMs: 2000 }); + expect([origin.isConnected, ...peers.map((peer) => peer.isConnected)]).toEqual([ + true, + true, + true, + ]); +}, 30000); diff --git a/packages/server/src/server/connected-hosts/index.ts b/packages/server/src/server/connected-hosts/index.ts index 1a8f7c2731..bfff76239c 100644 --- a/packages/server/src/server/connected-hosts/index.ts +++ b/packages/server/src/server/connected-hosts/index.ts @@ -7,10 +7,12 @@ import { z } from "zod"; import { createHostClient, createHostChannelTransport, + createHostTransportFactory, parseHostTarget, HostTransportBudget, } from "@getpaseo/client/node"; import type { DaemonClient } from "@getpaseo/client/internal/daemon-client"; +import type { DaemonTransportFactory } from "@getpaseo/client/internal/daemon-client-transport-types"; import { HostSummarySchema, HostAddSchema, @@ -21,6 +23,7 @@ import { type HostUpdate, } from "@getpaseo/protocol/hosts"; import type { DaemonPermission, WSHelloMessage } from "@getpaseo/protocol/messages"; +import { webSocketProxyAgent } from "../network/index.js"; export class HostError extends Error { constructor( @@ -234,22 +237,30 @@ export class ConnectedHosts { if (route.registrationId === id) route.close(code, "Host access was disabled, replaced or removed"); } - private start(row: Saved): void { + private start( + row: Saved, + resume?: { failures: number; transports: DaemonTransportFactory }, + ): void { if (!row.enabled || this.closed) return; + const transports = + resume?.transports ?? + createHostTransportFactory(row.connection, this.budget, { + webSocketAgent: webSocketProxyAgent, + }); let stopped = false; - const client = createHostClient( - row.connection, - { - clientId: `host-link-${this.self.serverId}-${row.registrationId}`, - connectTimeoutMs: 10000, - }, - this.budget, - ); + let attempts = resume?.failures ?? 0; + let retry: ReturnType | undefined; + const client = createHostClient(row.connection, { + clientId: `host-link-${this.self.serverId}-${row.registrationId}`, + connectTimeoutMs: 10000, + transportFactory: transports, + }); const live: Live = { client, accepted: false, stop: () => { stopped = true; + clearTimeout(retry); void client.close(); }, }; @@ -283,7 +294,7 @@ export class ConnectedHosts { if (info.features?.connectedHosts !== true || info.features?.hostMultiplexing !== true) throw new HostError( "unsupported_capability", - "Update the destination daemon to use connected hosts.", + "Update the destination daemon to use connected hosts; retrying automatically.", ); // Pin and persist under the same writer as management to prevent discovery races. await this.mutate(async () => { @@ -302,16 +313,22 @@ export class ConnectedHosts { if (stopped || client.getLastServerInfoMessage() !== info || !client.isConnected) return; Object.assign(row, next); live.accepted = true; + attempts = 0; this.changed(); }); } catch (error) { if (stopped) return; - row.status = "error"; row.error = connectionFailure(error, client.authFailureReason !== null) ?? { code: "host_offline", message: "Host connection failed", }; - row.nextRetryAt = null; + if (terminalFailures.has(row.error.code)) { + row.status = "error"; + row.nextRetryAt = null; + } else { + stopped = true; + retry = this.scheduleAcceptanceRetry(row, attempts, transports); + } this.changed(); await client.close(); } @@ -327,18 +344,17 @@ export class ConnectedHosts { if (route.registrationId === row.registrationId) route.close(); row.status = state.status === "connecting" ? "connecting" : "offline"; row.nextRetryAt = state.status === "disconnected" ? (state.nextRetryAt ?? null) : null; - row.error = - state.status === "disconnected" - ? (connectionFailure( - Object.assign(new Error("Check the SSH configuration and daemon credentials"), { - code: state.failureCode, - }), - client.authFailureReason !== null, - ) ?? { - code: "host_offline", - message: "Cannot reach host. Check the connection; retrying automatically.", - }) - : null; + if (state.status === "disconnected") + row.error = connectionFailure( + Object.assign(new Error("Check the SSH configuration and daemon credentials"), { + code: state.failureCode, + }), + client.authFailureReason !== null, + ) ?? { + code: "host_offline", + message: "Cannot reach host. Check the connection; retrying automatically.", + }; + else if (row.error?.code !== "unsupported_capability") row.error = null; if (row.error?.code === "authentication_failed") { row.status = "error"; row.nextRetryAt = null; @@ -349,6 +365,18 @@ export class ConnectedHosts { }); void client.connect().catch(() => {}); } + private scheduleAcceptanceRetry( + row: Saved, + failures: number, + transports: DaemonTransportFactory, + ): ReturnType { + const delay = acceptanceRetryDelayMs(failures); + row.status = "offline"; + row.nextRetryAt = new Date(Date.now() + delay).toISOString(); + const retry = setTimeout(() => this.start(row, { failures: failures + 1, transports }), delay); + retry.unref(); + return retry; + } async openRoute(input: { serverId: string; scopeId: string; @@ -508,10 +536,13 @@ export class ConnectedHosts { return; } if (!verified) throw new HostError("host_offline", "Host identity has not been verified"); - try { - transport.send(data); - } catch { + const rejectWrite = () => route.close("resource_limit", "Host buffer limit reached or transport unavailable"); + try { + const write = transport.send(data); + if (write) void write.catch(rejectWrite); + } catch { + rejectWrite(); } }, }; @@ -526,6 +557,20 @@ export class ConnectedHosts { } } +const ACCEPTANCE_RETRY_BASE_MS = 1500; +const ACCEPTANCE_RETRY_MAX_MS = 30_000; + +function acceptanceRetryDelayMs(failures: number): number { + return Math.min(ACCEPTANCE_RETRY_BASE_MS * 2 ** failures, ACCEPTANCE_RETRY_MAX_MS); +} + +const terminalFailures = new Set([ + "server_id_mismatch", + "self_host", + "duplicate_host", + "authentication_failed", +]); + function connectionFailure(error: unknown, authenticationFailed: boolean): HostSummary["error"] { if (error instanceof HostError) return { code: error.code, message: error.message }; if (error instanceof Error && "code" in error && error.code === "authentication_failed") diff --git a/packages/server/src/server/connected-hosts/link.ts b/packages/server/src/server/connected-hosts/link.ts index 85fe06ed4e..a18c89aeb0 100644 --- a/packages/server/src/server/connected-hosts/link.ts +++ b/packages/server/src/server/connected-hosts/link.ts @@ -1,7 +1,11 @@ import type { SessionDelivery } from "../session/owned-subscriptions/index.js"; import { EventEmitter } from "node:events"; import { createHash } from "node:crypto"; -import { encodeHostRouteFrame, type HostRouteFrame } from "@getpaseo/protocol/binary-frames/index"; +import { + MAX_HOST_CHANNEL_FRAME_BYTES, + encodeHostRouteFrame, + type HostRouteFrame, +} from "@getpaseo/protocol/binary-frames/index"; import type { DaemonPermission, SessionInboundMessage, @@ -10,6 +14,7 @@ import type { /** A logical socket has no network resources or authority of its own. */ export class VirtualHostSocket extends EventEmitter { + readonly maxFrameBytes = MAX_HOST_CHANNEL_FRAME_BYTES; readyState = 1; constructor( private readonly output: (data: string | Uint8Array) => Promise, diff --git a/packages/server/src/server/daemon-config-store.test.ts b/packages/server/src/server/daemon-config-store.test.ts index e3b6f48895..d9b2e94181 100644 --- a/packages/server/src/server/daemon-config-store.test.ts +++ b/packages/server/src/server/daemon-config-store.test.ts @@ -10,6 +10,10 @@ import { readSpeechSettings } from "./speech/speech-settings.js"; import type { PersistedConfig } from "./persisted-config.js"; import type { MutableDaemonConfig } from "@getpaseo/protocol/messages"; +function usageEnabled(persisted: PersistedConfig): boolean { + return persisted.daemon?.usage?.enabled !== false; +} + function reloadableConfig( persisted: PersistedConfig, options: { relayEnabledFallback?: boolean } = {}, @@ -23,6 +27,7 @@ function reloadableConfig( enabled: relay.enabled ?? options.relayEnabledFallback ?? true, }, mcp: { enabled: true, injectIntoAgents: false }, + usage: { enabled: usageEnabled(persisted) }, browserTools: { enabled: daemon.browserTools?.enabled ?? false }, providers: (agents.providers ?? {}) as MutableDaemonConfig["providers"], metadataGeneration: { providers: agents.metadataGeneration?.providers ?? [] }, @@ -940,6 +945,15 @@ describe("DaemonConfigStore", () => { await store.patch({ idleRuntimeCleanup: true }); expect(loadConfig(paseoHome, { env: {} }).idleRuntimeCleanup).toBe(true); + await store.patch({ resumeOnStartup: false, resumePrompt: "Keep going.\n" }); + expect(loadPersistedConfig(paseoHome).agents).toMatchObject({ + resumeOnStartup: false, + resumePrompt: "Keep going.\n", + }); + expect(loadConfig(paseoHome, { env: {} })).toMatchObject({ + resumeOnStartup: false, + resumePrompt: "Keep going.\n", + }); }); test("patch persists custom ACP provider overrides into config.json", async () => { @@ -1563,3 +1577,31 @@ describe("DaemonConfigStore speech settings", () => { expect(JSON.stringify(other.get())).not.toContain("secret"); }); }); + +test("usage policy persists across restart and live reload", async () => { + const paseoHome = mkdtempSync(path.join(tmpdir(), "usage-policy-")); + try { + const initial = reloadableConfig({}); + const store = new DaemonConfigStore(paseoHome, initial, undefined, { + reloadSource: { + resolve: (persisted) => ({ + mutable: reloadableConfig(persisted), + overrideControlledPaths: [], + }), + }, + }); + await store.patch({ usage: { enabled: false } }); + expect(loadConfig(paseoHome, { env: {} }).usageEnabled).toBe(false); + const persisted = loadPersistedConfig(paseoHome); + const restarted = new DaemonConfigStore(paseoHome, reloadableConfig(persisted)); + expect(restarted.get().usage).toEqual({ enabled: false }); + writeFileSync( + path.join(paseoHome, "config.json"), + JSON.stringify({ daemon: { usage: { enabled: true } } }), + ); + await store.reload(); + expect(store.get().usage).toEqual({ enabled: true }); + } finally { + rmSync(paseoHome, { recursive: true, force: true }); + } +}); diff --git a/packages/server/src/server/daemon-config-store.ts b/packages/server/src/server/daemon-config-store.ts index 57b9a6b916..e83874235f 100644 --- a/packages/server/src/server/daemon-config-store.ts +++ b/packages/server/src/server/daemon-config-store.ts @@ -22,6 +22,7 @@ type ProviderOverride = import("./agent/provider-launch-config.js").ProviderOver interface SupportedMutableConfigPatch { relay?: { enabled?: boolean; requireProtectedSecurity?: boolean }; mcp?: { injectIntoAgents?: boolean }; + usage?: { enabled: boolean }; browserTools?: { enabled?: boolean }; providers?: MutableDaemonConfig["providers"]; removeProviders?: string[]; @@ -29,6 +30,8 @@ interface SupportedMutableConfigPatch { autoArchiveAfterMerge?: boolean; enableTerminalAgentHooks?: boolean; idleRuntimeCleanup?: boolean; + resumeOnStartup?: boolean; + resumePrompt?: string; appendSystemPrompt?: string; terminalProfiles?: MutableDaemonConfig["terminalProfiles"]; agentProfiles?: MutableDaemonConfig["agentProfiles"]; @@ -180,6 +183,7 @@ const RELOADABLE_PATHS = [ "daemon.relay.requireProtectedSecurity", "daemon.mcp.enabled", "daemon.mcp.injectIntoAgents", + "daemon.usage.enabled", "daemon.browserTools.enabled", "daemon.hostnames", "daemon.cors.allowedOrigins", @@ -193,6 +197,8 @@ const RELOADABLE_PATHS = [ "daemon.agentProfiles", "app.baseUrl", "agents.idleRuntimeCleanup", + "agents.resumeOnStartup", + "agents.resumePrompt", "agents.providers", "agents.catalogRefreshTimeoutMs", "agents.metadataGeneration", @@ -205,6 +211,7 @@ const PERSISTED_TO_MUTABLE_PATH = new Map([ ["daemon.relay.requireProtectedSecurity", "relay.requireProtectedSecurity"], ["daemon.mcp.enabled", "mcp.enabled"], ["daemon.mcp.injectIntoAgents", "mcp.injectIntoAgents"], + ["daemon.usage.enabled", "usage.enabled"], ["daemon.browserTools.enabled", "browserTools.enabled"], ["daemon.hostnames", "hostnames"], ["daemon.cors.allowedOrigins", "cors.allowedOrigins"], @@ -218,6 +225,8 @@ const PERSISTED_TO_MUTABLE_PATH = new Map([ ["daemon.agentProfiles", "agentProfiles"], ["app.baseUrl", "app.baseUrl"], ["agents.idleRuntimeCleanup", "idleRuntimeCleanup"], + ["agents.resumeOnStartup", "resumeOnStartup"], + ["agents.resumePrompt", "resumePrompt"], ["agents.providers", "providers"], ["agents.catalogRefreshTimeoutMs", "catalogRefreshTimeoutMs"], ["agents.metadataGeneration", "metadataGeneration"], @@ -275,6 +284,7 @@ function pickRelayPatch( function pickSupportedPatchFields(patch: MutableDaemonConfigPatch): SupportedMutableConfigPatch { return { ...pickRelayPatch(patch.relay), + usage: patch.usage, ...(patch.mcp?.injectIntoAgents !== undefined ? { mcp: { injectIntoAgents: patch.mcp.injectIntoAgents } } : {}), @@ -292,6 +302,8 @@ function pickSupportedPatchFields(patch: MutableDaemonConfigPatch): SupportedMut ...(patch.enableTerminalAgentHooks !== undefined ? { enableTerminalAgentHooks: patch.enableTerminalAgentHooks } : {}), + ...(patch.resumeOnStartup !== undefined ? { resumeOnStartup: patch.resumeOnStartup } : {}), + ...(patch.resumePrompt !== undefined ? { resumePrompt: patch.resumePrompt } : {}), ...(patch.idleRuntimeCleanup !== undefined ? { idleRuntimeCleanup: patch.idleRuntimeCleanup } : {}), @@ -702,6 +714,7 @@ function mergeMutableAgentPatch( patch.providers === undefined && patch.metadataGeneration === undefined && patch.skills === undefined && + !hasRestartRecoveryPatch(patch) && patch.idleRuntimeCleanup === undefined && removeProviders.length === 0 ) { @@ -735,6 +748,7 @@ function mergeMutableAgentPatch( next["skills"] = { selection: patch.skills.selection }; } + Object.assign(next, restartRecoveryPatch(patch)); if (patch.idleRuntimeCleanup !== undefined) { next["idleRuntimeCleanup"] = patch.idleRuntimeCleanup; } @@ -757,6 +771,7 @@ function mergeMutableDaemonPatch( if (patch.mcp?.injectIntoAgents !== undefined) { next.mcp = { ...next.mcp, injectIntoAgents: patch.mcp.injectIntoAgents }; } + if (patch.usage) next.usage = patch.usage; if (patch.browserTools?.enabled !== undefined) { next.browserTools = { ...next.browserTools, enabled: patch.browserTools.enabled }; } @@ -771,3 +786,13 @@ function mergeMutableDaemonPatch( if (patch.agentProfiles !== undefined) next.agentProfiles = patch.agentProfiles; return Object.keys(next).length > 0 ? next : undefined; } + +function hasRestartRecoveryPatch(patch: SupportedMutableConfigPatch) { + return patch.resumeOnStartup !== undefined || patch.resumePrompt !== undefined; +} +function restartRecoveryPatch(patch: SupportedMutableConfigPatch) { + return { + ...(patch.resumeOnStartup !== undefined ? { resumeOnStartup: patch.resumeOnStartup } : {}), + ...(patch.resumePrompt !== undefined ? { resumePrompt: patch.resumePrompt } : {}), + }; +} diff --git a/packages/server/src/server/daemon-e2e/background-subagent-action-log.real.e2e.test.ts b/packages/server/src/server/daemon-e2e/background-subagent-action-log.real.e2e.test.ts index 7eba32f22a..557f8360de 100644 --- a/packages/server/src/server/daemon-e2e/background-subagent-action-log.real.e2e.test.ts +++ b/packages/server/src/server/daemon-e2e/background-subagent-action-log.real.e2e.test.ts @@ -1,6 +1,3 @@ -import { execFile } from "node:child_process"; -import { promisify } from "node:util"; -import { fileURLToPath } from "node:url"; import { mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; @@ -10,7 +7,7 @@ import { ClaudeAgentClient } from "../agent/providers/claude/agent.js"; import { createTestPaseoDaemon } from "../test-utils/paseo-daemon.js"; import { DaemonClient } from "../test-utils/daemon-client.js"; -test("background cards retain child actions after the parent finishes (#6253)", async () => { +test("background children keep their actions after the parent finishes (#6253)", async () => { const cwd = mkdtempSync(path.join(tmpdir(), "paseo-background-card-")); const logger = pino({ level: "silent" }); const daemon = await createTestPaseoDaemon({ @@ -62,22 +59,6 @@ test("background cards retain child actions after the parent finishes (#6253)", limit: 0, projection: "projected", }); - const { stdout } = await promisify(execFile)( - process.execPath, - [ - "--conditions=source", - "--import", - "tsx", - fileURLToPath(new URL("../../../../cli/src/index.ts", import.meta.url)), - "--host", - `127.0.0.1:${daemon.port}`, - "logs", - agent.id, - ], - { env: { ...process.env, PASEO_HOME: daemon.paseoHome }, timeout: 30_000 }, - ); - expect(stdout).toContain("[Bash] ls -1"); - expect(stdout).toContain("[Bash] pwd"); expect( atFinish.entries.filter( (row) => row.item.type === "tool_call" && row.item.detail?.type === "sub_agent", @@ -94,9 +75,6 @@ test("background cards retain child actions after the parent finishes (#6253)", ), ).toBe(true); } - for (const card of cards) { - expect(card.detail?.type === "sub_agent" ? card.detail.log : "").toContain("[Bash]"); - } } finally { await client.close(); await daemon.close(); diff --git a/packages/server/src/server/daemon-e2e/checkout-diff-content.e2e.test.ts b/packages/server/src/server/daemon-e2e/checkout-diff-content.e2e.test.ts index fe83c21305..56e7cdefb8 100644 --- a/packages/server/src/server/daemon-e2e/checkout-diff-content.e2e.test.ts +++ b/packages/server/src/server/daemon-e2e/checkout-diff-content.e2e.test.ts @@ -88,13 +88,9 @@ test.each(["uncommitted", "base", "commit"] as const)( 60_000, ); -test.each( - (["uncommitted", "base"] as const).flatMap((mode) => - (["single", "batch", "rename"] as const).map((shape) => ({ mode, shape })), - ), -)( - "$mode $shape diff includes hunks from a repository subdirectory", - async ({ mode, shape }) => { +test.each(["single", "batch", "rename"] as const)( + "%s diff includes hunks from a repository subdirectory before and after commit", + async (shape) => { const ctx = await createDaemonTestContext(); const cwd = mkdtempSync(join(tmpdir(), "checkout-diff-subdirectory-")); @@ -112,9 +108,7 @@ test.each( } git(cwd, "add", "."); git(cwd, "-c", "commit.gpgsign=false", "commit", "-m", "initial"); - if (mode === "base") { - git(cwd, "checkout", "-b", "feature"); - } + git(cwd, "checkout", "-b", "feature"); const filename = shape === "rename" ? "renamed.txt" : "normal.txt"; if (shape === "rename") { git(cwd, "mv", "sub/normal.txt", `sub/${filename}`); @@ -123,36 +117,38 @@ test.each( if (shape === "batch") { writeFileSync(join(cwd, "sibling.txt"), "new sibling\n"); } - if (mode === "base") { - git(cwd, "add", "."); - git(cwd, "-c", "commit.gpgsign=false", "commit", "-m", "edit"); + async function expectSubdirectoryDiff(mode: "uncommitted" | "base") { + const compare = { mode, baseRef: "main" }; + const rootDiff = await ctx.client.getCheckoutDiff(cwd, compare); + const subdirectoryDiff = await ctx.client.getCheckoutDiff(subdirectory, compare); + const subscription = ctx.client.observeCheckoutDiff(subdirectory, compare); + const liveDiff = await subscription.ready; + await subscription.release(); + + expect(rootDiff.error).toBeNull(); + expect(subdirectoryDiff.error).toBeNull(); + expect(liveDiff.error).toBeNull(); + expect(liveDiff.files).toEqual(rootDiff.files); + expect(rootDiff.files).toHaveLength(shape === "batch" ? 2 : 1); + const file = rootDiff.files.find((candidate) => candidate.path === `sub/${filename}`); + expect(file).toMatchObject({ + additions: 1, + deletions: 1, + ...(shape === "rename" ? { oldPath: "sub/normal.txt" } : {}), + }); + expect(file?.hunks.flatMap((hunk) => hunk.lines)).toEqual( + expect.arrayContaining([ + expect.objectContaining({ type: "remove", content: "before" }), + expect.objectContaining({ type: "add", content: "after" }), + ]), + ); + expect(subdirectoryDiff.files).toEqual(rootDiff.files); } - const compare = { mode, baseRef: "main" }; - const rootDiff = await ctx.client.getCheckoutDiff(cwd, compare); - const subdirectoryDiff = await ctx.client.getCheckoutDiff(subdirectory, compare); - const subscription = ctx.client.observeCheckoutDiff(subdirectory, compare); - const liveDiff = await subscription.ready; - await subscription.release(); - - expect(rootDiff.error).toBeNull(); - expect(subdirectoryDiff.error).toBeNull(); - expect(liveDiff.error).toBeNull(); - expect(liveDiff.files).toEqual(rootDiff.files); - expect(rootDiff.files).toHaveLength(shape === "batch" ? 2 : 1); - const file = rootDiff.files.find((candidate) => candidate.path === `sub/${filename}`); - expect(file).toMatchObject({ - additions: 1, - deletions: 1, - ...(shape === "rename" ? { oldPath: "sub/normal.txt" } : {}), - }); - expect(file?.hunks.flatMap((hunk) => hunk.lines)).toEqual( - expect.arrayContaining([ - expect.objectContaining({ type: "remove", content: "before" }), - expect.objectContaining({ type: "add", content: "after" }), - ]), - ); - expect(subdirectoryDiff.files).toEqual(rootDiff.files); + await expectSubdirectoryDiff("uncommitted"); + git(cwd, "add", "."); + git(cwd, "-c", "commit.gpgsign=false", "commit", "-m", "edit"); + await expectSubdirectoryDiff("base"); } finally { await ctx.cleanup(); rmSync(cwd, { recursive: true, force: true }); diff --git a/packages/server/src/server/daemon-e2e/codex-steer-starting.real.e2e.test.ts b/packages/server/src/server/daemon-e2e/codex-steer-starting.real.e2e.test.ts new file mode 100644 index 0000000000..60508205f2 --- /dev/null +++ b/packages/server/src/server/daemon-e2e/codex-steer-starting.real.e2e.test.ts @@ -0,0 +1,80 @@ +import { expect, test } from "vitest"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import pino from "pino"; + +import { CodexAppServerAgentClient } from "../agent/providers/codex-app-server-agent.js"; +import { DaemonClient } from "../test-utils/daemon-client.js"; +import { createMessageCollector } from "../test-utils/message-collector.js"; +import { createTestPaseoDaemon } from "../test-utils/paseo-daemon.js"; +import { canRunRealProvider } from "./real-provider-test-config.js"; + +test("keeps two concurrent startup steer messages in one real Codex turn", async (context) => { + if (!(await canRunRealProvider("codex"))) { + context.skip(); + return; + } + const cwd = mkdtempSync(path.join(tmpdir(), "codex-steer-starting-")); + const logger = pino({ level: "silent" }); + const daemon = await createTestPaseoDaemon({ + agentClients: { codex: new CodexAppServerAgentClient(logger) }, + logger, + }); + const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` }); + const collector = createMessageCollector(client); + const subscriptions: ReturnType[] = []; + try { + await client.connect(); + await client.fetchAgents({ subscribe: {} }); + for (let attempt = 0; attempt < 3; attempt += 1) { + const agent = await client.createAgent({ + cwd, + provider: "codex", + modeId: "full-access", + }); + const subscription = client.subscribeAgentTimeline(agent.id, () => {}); + subscriptions.push(subscription); + await subscription.ready; + await Promise.all([ + client.sendAgentMessage(agent.id, "Reply exactly: FIRST", { + messageId: `first-${attempt}`, + activeTurnBehavior: "steer", + }), + client.sendAgentMessage(agent.id, "Reply exactly: SECOND", { + messageId: `second-${attempt}`, + activeTurnBehavior: "steer", + }), + ]); + await client.waitForFinish(agent.id, 90_000); + const timeline = await client.fetchAgentTimeline(agent.id, { limit: 100 }); + const users = timeline.entries.filter((entry) => entry.item.type === "user_message"); + const events = collector.messages.flatMap((message) => + message.type === "agent_stream" && message.payload.agentId === agent.id + ? [message.payload.event] + : [], + ); + expect(users.map((entry) => entry.item.text).sort()).toEqual([ + "Reply exactly: FIRST", + "Reply exactly: SECOND", + ]); + expect(new Set(users.map((entry) => entry.turnId)).size).toBe(1); + expect(events.filter((event) => event.type === "turn_started")).toHaveLength(1); + expect( + events.filter((event) => event.type === "turn_canceled" || event.type === "turn_failed"), + ).toHaveLength(0); + expect( + timeline.entries.some( + (entry) => + entry.item.type === "assistant_message" && entry.item.text.includes("[System Error]"), + ), + ).toBe(false); + } + } finally { + await Promise.all(subscriptions.map((subscription) => subscription.release())); + collector.unsubscribe(); + await client.close(); + await daemon.close(); + rmSync(cwd, { recursive: true, force: true }); + } +}, 300_000); diff --git a/packages/server/src/server/daemon-e2e/creation-status.e2e.test.ts b/packages/server/src/server/daemon-e2e/creation-status.e2e.test.ts new file mode 100644 index 0000000000..c2293a2bc7 --- /dev/null +++ b/packages/server/src/server/daemon-e2e/creation-status.e2e.test.ts @@ -0,0 +1,64 @@ +import { expect, test } from "vitest"; +import { createDaemonTestContext } from "../test-utils/index.js"; +import { MockLoadTestAgentClient } from "../agent/providers/mock-load-test-agent.js"; +import type { AgentSnapshotPayload } from "../messages.js"; + +test("creation never regresses a running subscription to the pre-prompt idle snapshot", async () => { + const ctx = await createDaemonTestContext({ + agentClients: { mock: new MockLoadTestAgentClient() }, + mcpEnabled: false, + isDev: true, + }); + try { + const workspace = await ctx.client.createWorkspace({ + source: { kind: "directory", path: ctx.daemon.staticDir }, + }); + if (!workspace.workspace) throw new Error(workspace.error ?? "Missing workspace"); + const observations: { + list: string; + kind: string; + agent?: AgentSnapshotPayload; + agentId?: string; + }[] = []; + for (const [list, statuses] of [ + ["running", ["running", "initializing", "error"]], + ["done", ["idle", "closed"]], + ] as const) { + const result = await ctx.client.fetchAgents({ + filter: { statuses: [...statuses] }, + subscribe: {}, + }); + result.subscription.subscribe({ + snapshot() {}, + update(message) { + observations.push({ list, ...message.payload }); + }, + }); + } + const agent = await ctx.client.createAgent({ + workspaceId: workspace.workspace.id, + provider: "mock", + cwd: ctx.daemon.staticDir, + initialPrompt: "Work on this task", + }); + await expect + .poll(() => observations.filter((row) => row.agent?.id === agent.id).length) + .toBeGreaterThan(1); + // Fetching provides a round trip after creation so its queued update reaches the client. + expect((await ctx.client.fetchAgent({ agentId: agent.id }))?.agent.status).toBe("running"); + const relevant = observations.filter( + (row) => row.agent?.id === agent.id || row.agentId === agent.id, + ); + const firstRunning = relevant.findIndex((row) => row.agent?.status === "running"); + expect(firstRunning).toBeGreaterThanOrEqual(0); + expect( + relevant.slice(firstRunning).filter((row) => row.list === "done" && row.kind === "upsert"), + ).toEqual([]); + const timestamps = relevant.flatMap((row) => + row.agent ? [Date.parse(row.agent.updatedAt)] : [], + ); + expect(timestamps).toEqual([...timestamps].sort((a, b) => a - b)); + } finally { + await ctx.cleanup(); + } +}, 60_000); diff --git a/packages/server/src/server/daemon-e2e/daemon-restart-resume.e2e.test.ts b/packages/server/src/server/daemon-e2e/daemon-restart-resume.e2e.test.ts index efc99c9b59..1658356eed 100644 --- a/packages/server/src/server/daemon-e2e/daemon-restart-resume.e2e.test.ts +++ b/packages/server/src/server/daemon-e2e/daemon-restart-resume.e2e.test.ts @@ -76,10 +76,14 @@ import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; import { DaemonClient } from "../test-utils/daemon-client.js"; -async function restartFixture(root: string) { +async function restartFixture( + root: string, + settings: { resumeOnStartup?: boolean; resumePrompt?: string } = {}, + fixture: { holdResume?: boolean } = {}, +) { const child = fork( fileURLToPath(new URL("../test-utils/finish-subscription-daemon.ts", import.meta.url)), - [root], + [root, JSON.stringify(settings), JSON.stringify(fixture)], { execArgv: ["--conditions=source", "--import", "tsx"], stdio: ["ignore", "pipe", "pipe", "ipc"], @@ -183,7 +187,25 @@ test.each([false, true])( await expect.poll(() => readPrompts(root), { timeout: 15000 }).toHaveLength(1); const prompts = await readPrompts(root); expect(prompts[0]).toContain(`Agent ${childId}`); - expect(prompts[0]).toContain("was closed"); + expect(prompts[0]).not.toContain("was closed"); + const recoveredPrompts = (await readFile(path.join(root, "all-prompts.jsonl"), "utf8")) + .trim() + .split("\n") + .map((line) => JSON.parse(line)); + expect(recoveredPrompts.filter((entry) => entry.prompt === "Resume working.")).toHaveLength( + 1, + ); + const restored = recoveredPrompts.find((entry) => entry.prompt === "Resume working.").config; + const original = recoveredPrompts.find((entry) => + String(entry.prompt).includes("HOLD_CHILD"), + ).config; + expect(restored).toMatchObject({ + provider: original.provider, + model: original.model, + modeId: original.modeId, + cwd: original.cwd, + }); + await expect .poll( async () => @@ -196,7 +218,7 @@ test.each([false, true])( client = new DaemonClient({ url: `ws://127.0.0.1:${second.port}/ws`, appVersion: "0.13.0" }); await client.connect(); await client.fetchAgents({ subscribe: {} }); - expect((await client.fetchAgent(childId))?.agent.status).toBe("closed"); + expect((await client.fetchAgent(childId))?.agent.status).toBe("idle"); await client.close(); client = undefined; await stopFixture(second.child, false); @@ -220,3 +242,120 @@ test.each([false, true])( }, 60000, ); + +test.each([false, true])( + "host restart recovery settings (enabled=%s)", + async (enabled) => { + const root = await mkdtemp(path.join(tmpdir(), "resume-settings-process-")); + const processes: ChildProcess[] = []; + let client: DaemonClient | undefined; + const settings = { resumeOnStartup: enabled, resumePrompt: "Continue exactly.\n" }; + try { + const first = await restartFixture(root, settings); + processes.push(first.child); + client = new DaemonClient({ url: `ws://127.0.0.1:${first.port}/ws`, appVersion: "0.13.0" }); + await client.connect(); + const working = await client.createAgent({ + provider: "claude", + cwd: first.cwd, + modeId: "full-access", + }); + const idle = await client.createAgent({ + provider: "claude", + cwd: first.cwd, + modeId: "full-access", + }); + await client.sendMessage(working.id, "HOLD_CHILD"); + await expect + .poll( + async () => + ( + await new AgentStorage(path.join(first.paseoHome, "agents"), createTestLogger()).get( + working.id, + ) + )?.lastStatus, + ) + .toBe("running"); + const original = await new AgentStorage( + path.join(first.paseoHome, "agents"), + createTestLogger(), + ).get(working.id); + await client.close(); + client = undefined; + await stopFixture(first.child, false); + const second = await restartFixture(root, settings); + processes.push(second.child); + client = new DaemonClient({ url: `ws://127.0.0.1:${second.port}/ws`, appVersion: "0.13.0" }); + await client.connect(); + const storage = new AgentStorage(path.join(second.paseoHome, "agents"), createTestLogger()); + // Resume runs in the background; it is done once the saved intent is consumed. + await expect.poll(async () => (await storage.get(working.id))?.resumeOnStartup).toBe(false); + const resumePrompts = async () => + (await readFile(path.join(root, "all-prompts.jsonl"), "utf8")) + .trim() + .split("\n") + .map((line) => JSON.parse(line)) + .filter((entry) => entry.prompt === settings.resumePrompt); + await expect.poll(resumePrompts).toHaveLength(enabled ? 1 : 0); + expect((await client.fetchAgent(idle.id))?.agent.status).toBe("closed"); + const restored = await storage.get(working.id); + expect(restored?.persistence?.sessionId).toBe(original?.persistence?.sessionId); + } finally { + await client?.close(); + for (const child of processes.toReversed()) await stopFixture(child, true); + await rm(root, { recursive: true, force: true }); + } + }, + 60000, +); + +test("a provider that is slow to reopen does not hold daemon startup", async () => { + const root = await mkdtemp(path.join(tmpdir(), "resume-background-process-")); + const processes: ChildProcess[] = []; + let client: DaemonClient | undefined; + try { + const first = await restartFixture(root); + processes.push(first.child); + client = new DaemonClient({ url: `ws://127.0.0.1:${first.port}/ws`, appVersion: "0.13.0" }); + await client.connect(); + const working = await client.createAgent({ + provider: "claude", + cwd: first.cwd, + modeId: "full-access", + }); + await client.sendMessage(working.id, "HOLD_CHILD"); + await expect + .poll( + async () => + ( + await new AgentStorage(path.join(first.paseoHome, "agents"), createTestLogger()).get( + working.id, + ) + )?.lastStatus, + ) + .toBe("running"); + await client.close(); + client = undefined; + await stopFixture(first.child, false); + + const second = await restartFixture(root, {}, { holdResume: true }); + processes.push(second.child); + client = new DaemonClient({ url: `ws://127.0.0.1:${second.port}/ws`, appVersion: "0.13.0" }); + await client.connect(); + expect((await client.fetchAgent(working.id))?.agent.id).toBe(working.id); + second.child.send("release-resume"); + await expect + .poll(async () => + (await readFile(path.join(root, "all-prompts.jsonl"), "utf8")) + .trim() + .split("\n") + .map((line) => JSON.parse(line).prompt) + .filter((prompt) => prompt === "Resume working."), + ) + .toHaveLength(1); + } finally { + await client?.close(); + for (const child of processes.toReversed()) await stopFixture(child, true); + await rm(root, { recursive: true, force: true }); + } +}, 30000); diff --git a/packages/server/src/server/daemon-e2e/file-download.e2e.test.ts b/packages/server/src/server/daemon-e2e/file-download.e2e.test.ts index 862923dec6..54ec1964c1 100644 --- a/packages/server/src/server/daemon-e2e/file-download.e2e.test.ts +++ b/packages/server/src/server/daemon-e2e/file-download.e2e.test.ts @@ -102,53 +102,52 @@ describe("daemon E2E", () => { }, ); - test.each([ - { fileName: "download.txt", disposition: 'attachment; filename="download.txt"' }, - { - fileName: "café.txt", - disposition: "attachment; filename=\"caf?.txt\"; filename*=UTF-8''caf%C3%A9.txt", - }, - { - fileName: "中文报告 (最终版).txt", - disposition: - "attachment; filename=\"???? (???).txt\"; filename*=UTF-8''%E4%B8%AD%E6%96%87%E6%8A%A5%E5%91%8A%20%28%E6%9C%80%E7%BB%88%E7%89%88%29.txt", - }, - { - fileName: "報告書.md", - disposition: - "attachment; filename=\"???.md\"; filename*=UTF-8''%E5%A0%B1%E5%91%8A%E6%9B%B8.md", - }, - { - fileName: "보고서.txt", - disposition: - "attachment; filename=\"???.txt\"; filename*=UTF-8''%EB%B3%B4%EA%B3%A0%EC%84%9C.txt", - }, - { - fileName: "report-📄.txt", - disposition: - "attachment; filename=\"report-??.txt\"; filename*=UTF-8''report-%F0%9F%93%84.txt", - }, - ])( - "issues token over WS and downloads $fileName via HTTP", - async ({ fileName, disposition }) => { - const cwd = tmpCwd(); - try { + test("downloads ASCII and Unicode filenames through one workspace", async () => { + const cwd = tmpCwd(); + try { + const agent = await ctx.client.createAgent({ + provider: "codex", + model: CODEX_TEST_MODEL, + thinkingOptionId: CODEX_TEST_THINKING_OPTION_ID, + cwd, + title: "Download Token Test Agent", + }); + + expect(agent.id).toMatch( + /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/, + ); + + for (const { fileName, disposition } of [ + { fileName: "download.txt", disposition: 'attachment; filename="download.txt"' }, + { + fileName: "café.txt", + disposition: "attachment; filename=\"caf?.txt\"; filename*=UTF-8''caf%C3%A9.txt", + }, + { + fileName: "中文报告 (最终版).txt", + disposition: + "attachment; filename=\"???? (???).txt\"; filename*=UTF-8''%E4%B8%AD%E6%96%87%E6%8A%A5%E5%91%8A%20%28%E6%9C%80%E7%BB%88%E7%89%88%29.txt", + }, + { + fileName: "報告書.md", + disposition: + "attachment; filename=\"???.md\"; filename*=UTF-8''%E5%A0%B1%E5%91%8A%E6%9B%B8.md", + }, + { + fileName: "보고서.txt", + disposition: + "attachment; filename=\"???.txt\"; filename*=UTF-8''%EB%B3%B4%EA%B3%A0%EC%84%9C.txt", + }, + { + fileName: "report-📄.txt", + disposition: + "attachment; filename=\"report-??.txt\"; filename*=UTF-8''report-%F0%9F%93%84.txt", + }, + ]) { const filePath = path.join(cwd, fileName); - const fileContents = "download test payload"; + const fileContents = `download test payload: ${fileName}`; writeFileSync(filePath, fileContents, "utf-8"); - const agent = await ctx.client.createAgent({ - provider: "codex", - model: CODEX_TEST_MODEL, - thinkingOptionId: CODEX_TEST_THINKING_OPTION_ID, - cwd, - title: "Download Token Test Agent", - }); - - expect(agent.id).toMatch( - /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/, - ); - const tokenResponse = await ctx.client.requestDownloadToken(cwd, fileName); expect(tokenResponse.error).toBeNull(); @@ -167,12 +166,11 @@ describe("daemon E2E", () => { const body = await response.text(); expect(body).toBe(fileContents); - } finally { - rmSync(cwd, { recursive: true, force: true }); } - }, - 60000, - ); + } finally { + rmSync(cwd, { recursive: true, force: true }); + } + }, 60000); test("rejects invalid token", async () => { const response = await fetch( diff --git a/packages/server/src/server/daemon-e2e/opencode-initial-prompt-wait.real.e2e.test.ts b/packages/server/src/server/daemon-e2e/opencode-initial-prompt-wait.real.e2e.test.ts index e03c66bca0..db278d0249 100644 --- a/packages/server/src/server/daemon-e2e/opencode-initial-prompt-wait.real.e2e.test.ts +++ b/packages/server/src/server/daemon-e2e/opencode-initial-prompt-wait.real.e2e.test.ts @@ -46,7 +46,7 @@ describe("daemon E2E (real opencode) - initial prompt wait", () => { } }); - test("waitForFinish does not resolve before an initial prompt using opencode/big-pickle actually completes", async () => { + test("waitForFinish does not resolve before an OpenCode initial prompt completes", async () => { const cwd = tmpCwd(); const { client, daemon } = await createHarness(); diff --git a/packages/server/src/server/daemon-e2e/oversized-timeline.e2e.test.ts b/packages/server/src/server/daemon-e2e/oversized-timeline.e2e.test.ts new file mode 100644 index 0000000000..bc78db2eab --- /dev/null +++ b/packages/server/src/server/daemon-e2e/oversized-timeline.e2e.test.ts @@ -0,0 +1,46 @@ +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { expect, test } from "vitest"; +import { createDaemonTestContext } from "../test-utils/index.js"; + +// #2220: a timeline page is one WebSocket message, so a few huge entries used to close the socket. +test.each([40, 0])( + "fetching image-heavy history with limit %i keeps the direct connection usable", + async (limit) => { + const ctx = await createDaemonTestContext(); + const cwd = mkdtempSync(path.join(tmpdir(), "oversized-timeline-")); + try { + const agent = await ctx.client.createAgent({ provider: "codex", cwd }); + const imageUrl = `data:image/jpeg;base64,${"A".repeat(14 * 1024 * 1024)}`; + for (let index = 0; index < 5; index += 1) { + await ctx.daemon.daemon.agentManager.appendTimelineItem(agent.id, { + type: "tool_call", + callId: `screenshot-${index}`, + name: "node_repl.js", + status: "completed", + error: null, + detail: { + type: "unknown", + input: { index }, + output: { _meta: { "codex/toolSurface": { screenshot: { url: imageUrl } } } }, + }, + }); + } + + const page = await ctx.client.fetchAgentTimeline(agent.id, { direction: "tail", limit }); + const screenshots = page.entries.filter((entry) => entry.item.type === "tool_call"); + expect(screenshots).toHaveLength(5); + for (const entry of screenshots) { + expect(Buffer.byteLength(JSON.stringify(entry.item))).toBeLessThanOrEqual(64 * 1024); + } + + const next = await ctx.client.fetchAgentTimeline(agent.id, { direction: "tail", limit: 1 }); + expect(next.entries).toHaveLength(1); + } finally { + await ctx.cleanup(); + rmSync(cwd, { recursive: true, force: true }); + } + }, + 60_000, +); diff --git a/packages/server/src/server/daemon-e2e/real-provider-test-config.ts b/packages/server/src/server/daemon-e2e/real-provider-test-config.ts index e54b781e65..e15c618fbf 100644 --- a/packages/server/src/server/daemon-e2e/real-provider-test-config.ts +++ b/packages/server/src/server/daemon-e2e/real-provider-test-config.ts @@ -26,7 +26,7 @@ const PI_AUTH_CONFIG_PATH = join(homedir(), ".pi", "agent", "auth.json"); const CODEX_AUTH_CONFIG_PATH = join(homedir(), ".codex", "auth.json"); const CLAUDE_REAL_TEST_MODEL = "haiku"; const CODEX_REAL_TEST_MODEL = "~openai/gpt-latest"; -const OPENCODE_REAL_TEST_MODEL = "openrouter/google/gemini-2.5-flash-lite"; +const OPENCODE_REAL_TEST_MODEL = "openrouter/google/gemini-3.5-flash-lite"; const PI_OPENROUTER_REAL_TEST_MODEL = "openrouter/google/gemini-2.5-flash-lite"; const PI_CODEX_REAL_TEST_MODEL = "openai-codex/gpt-5.4"; const OMP_OPENROUTER_REAL_TEST_MODEL = "openrouter/google/gemini-2.5-flash-lite"; diff --git a/packages/server/src/server/daemon-e2e/relay-transport.e2e.test.ts b/packages/server/src/server/daemon-e2e/relay-transport.e2e.test.ts index 32d3a1f36c..f47accaa55 100644 --- a/packages/server/src/server/daemon-e2e/relay-transport.e2e.test.ts +++ b/packages/server/src/server/daemon-e2e/relay-transport.e2e.test.ts @@ -9,7 +9,7 @@ import { } from "@getpaseo/protocol/binary-frames/index"; import { getDaemonAuthFailureReason, - type DaemonClient as HostClient, + DaemonClient as HostClient, } from "@getpaseo/client/internal/daemon-client"; import type { SessionOutboundMessage } from "@getpaseo/protocol/messages"; import { describe, expect, test } from "vitest"; @@ -593,72 +593,112 @@ async function waitForCapturedLog( } }, 90000); - test("oversized attachments fail without disconnecting or resubmitting over the relay", async () => { - await startRelay({ useLocalRelay: true }); - const daemon = await createTestPaseoDaemon({ - relayEnabled: true, - relayEndpoint: `127.0.0.1:${relayPort}`, - relayUseTls: false, - relayPublicUseTls: false, - }); - let client: DaemonClient | null = null; - try { - const offerUrl = await getPairingOfferUrl({ - paseoHome: daemon.paseoHome, + test.each([true, false])( + "large messages cross the relay with unpaced upload admission preserved (supportsDrain=%s)", + async (supportsDrain) => { + await startRelay({ useLocalRelay: true }); + const daemon = await createTestPaseoDaemon({ relayEnabled: true, - relayEndpoint: daemon.config.relayEndpoint, + relayEndpoint: `127.0.0.1:${relayPort}`, + relayUseTls: false, + relayPublicUseTls: false, }); - const { serverId, daemonPublicKeyB64 } = decodeOfferFromFragmentUrl(offerUrl); - client = new DaemonClient({ - url: buildRelayWebSocketUrl({ - endpoint: `127.0.0.1:${relayPort}`, - useTls: false, - serverId, - role: "client", - }), - e2ee: { enabled: true, daemonPublicKeyB64 }, - reconnect: { baseDelayMs: 100, maxDelayMs: 100 }, - }); - await client.connect(); - const statuses: string[] = []; - client.subscribeConnectionStatus((state) => statuses.push(state.status)); - for (const imageMiB of [30, 61]) { - // Attachments are base64 in the JSON, then E2EE base64 expands the frame again. - const images = [ - { data: "A".repeat(4 * Math.ceil((imageMiB * 1024 * 1024) / 3)), mimeType: "image/png" }, - ]; + let client: HostClient | null = null; + try { + const offerUrl = await getPairingOfferUrl({ + paseoHome: daemon.paseoHome, + relayEnabled: true, + relayEndpoint: daemon.config.relayEndpoint, + }); + const { serverId, daemonPublicKeyB64 } = decodeOfferFromFragmentUrl(offerUrl); + client = new HostClient({ + clientId: "paced-relay-regression", + webSocketFactory: Object.assign((url: string) => new WebSocket(url), { supportsDrain }), + url: buildRelayWebSocketUrl({ + endpoint: `127.0.0.1:${relayPort}`, + useTls: false, + serverId, + role: "client", + }), + e2ee: { enabled: true, daemonPublicKeyB64 }, + reconnect: { baseDelayMs: 100, maxDelayMs: 100 }, + }); + await client.connect(); + const statuses: string[] = []; + client.subscribeConnectionStatus((state) => statuses.push(state.status)); + for (const imageMiB of [30, 61]) { + const images = [ + { + data: "A".repeat(4 * Math.ceil((imageMiB * 1024 * 1024) / 3)), + mimeType: "image/png", + }, + ]; + const creation = client.createWorkspace({ + source: { kind: "directory", path: daemon.staticDir }, + agent: { + provider: "claude", + cwd: daemon.staticDir, + initialPrompt: "Describe these screens.", + images, + }, + }); + if (supportsDrain) + await withTimeout(creation, 30000, "Chunked workspace creation did not settle"); + else await expect(creation).rejects.toThrow(/too large.*32\.0 MiB/); + } + expect((await client.fetchAgents()).entries).toHaveLength(supportsDrain ? 2 : 0); await expect( - withTimeout( - client.createWorkspace({ - source: { kind: "directory", path: daemon.staticDir }, - agent: { - provider: "claude", - cwd: daemon.staticDir, - initialPrompt: "Describe these screens.", - images, - }, - }), - 10000, - "Workspace creation did not settle", - ), - ).rejects.toThrow(/too large.*32\.0 MiB/); - expect((await client.fetchAgents()).entries).toEqual([]); - } - const agent = await client.createAgent({ provider: "claude", cwd: daemon.staticDir }); - await expect( - client.sendMessage(agent.id, "Describe these screens.", { + client.createWorkspace({ + source: { kind: "directory", path: daemon.staticDir }, + agent: { + provider: "claude", + cwd: daemon.staticDir, + initialPrompt: "Describe these screens.", + images: [{ data: "A".repeat(101 * 1024 * 1024), mimeType: "image/png" }], + }, + }), + ).rejects.toThrow(/too large.*100\.0 MiB/); + expect((await client.fetchAgents()).entries).toHaveLength(supportsDrain ? 2 : 0); + const agent = await client.createAgent({ provider: "claude", cwd: daemon.staticDir }); + const attachment = client.sendMessage(agent.id, "Describe these screens.", { images: [{ data: "A".repeat(40 * 1024 * 1024), mimeType: "image/png" }], - }), - ).rejects.toThrow(/too large.*32\.0 MiB/); - await client.sendMessage(agent.id, "A small follow-up still works."); - expect((await client.fetchAgents()).entries).toHaveLength(1); - expect(statuses).toEqual(["connected"]); - } finally { - await client?.close(); - await daemon.close(); - await stopRelay(); - } - }, 60000); + }); + if (supportsDrain) await attachment; + else await expect(attachment).rejects.toThrow(/too large.*32\.0 MiB/); + await expect( + client.sendMessage(agent.id, "Describe these screens.", { + images: [{ data: "A".repeat(101 * 1024 * 1024), mimeType: "image/png" }], + }), + ).rejects.toThrow(/too large.*100\.0 MiB/); + await client.sendMessage(agent.id, "A small follow-up still works."); + expect((await client.fetchAgents()).entries).toHaveLength(supportsDrain ? 3 : 1); + // Respect the per-item content budget while exceeding the relay frame limit. + const text = "x".repeat(240 * 1024); + for (let row = 0; row < 220; row++) + await daemon.daemon.agentManager.appendTimelineItem(agent.id, { + type: "user_message", + text, + }); + const timeline = await client.fetchAgentTimeline(agent.id, { + projection: "canonical", + limit: 0, + timeout: 30000, + }); + const delivered = timeline.entries.filter( + (row) => row.item.type === "user_message" && row.item.text === text, + ); + expect(delivered).toHaveLength(220); + expect(delivered.length * Buffer.byteLength(text)).toBeGreaterThan(50 * 1024 * 1024); + await client.ping(); + expect(statuses).toEqual(["connected"]); + } finally { + await client?.close(); + await daemon.close(); + await stopRelay(); + } + }, + 120000, + ); test("daemon connects to relay and client ping/pong works through relay", async () => { process.env.PASEO_PRIMARY_LAN_IP = "192.168.1.12"; diff --git a/packages/server/src/server/daemon-e2e/terminal-byte-headless-parity.e2e.test.ts b/packages/server/src/server/daemon-e2e/terminal-byte-headless-parity.e2e.test.ts index 2b789788ad..ed00f6cd9a 100644 --- a/packages/server/src/server/daemon-e2e/terminal-byte-headless-parity.e2e.test.ts +++ b/packages/server/src/server/daemon-e2e/terminal-byte-headless-parity.e2e.test.ts @@ -7,7 +7,6 @@ import { Terminal as HeadlessTerminal, type IBufferCell, type IBufferLine } from import { expect, test } from "vitest"; import type { TerminalCell, TerminalState } from "@getpaseo/protocol/messages"; -import { renderTerminalSnapshotToAnsi } from "@getpaseo/protocol/terminal-snapshot"; import type { TerminalStreamEvent } from "@getpaseo/client/internal/daemon-client"; import { DaemonClient } from "../test-utils/daemon-client.js"; import { createTestPaseoDaemon } from "../test-utils/paseo-daemon.js"; @@ -46,7 +45,7 @@ test("byte-stream headless terminal matches daemon state after high-output attac terminalId: terminal.id, headless: liveHeadless, }); - const initialSnapshot = waitForTerminalStreamEvent(client, terminal.id, "snapshot"); + const initialSnapshot = waitForReplayEnd(client, terminal.id); const liveSubscription = await subscribeTerminal(client, terminal.id); await initialSnapshot; @@ -60,13 +59,13 @@ test("byte-stream headless terminal matches daemon state after high-output attac text: BYTE_DONE_MARKER, rows: BYTE_TEST_SIZE.rows, }); - const daemonSnapshot = await readTerminalSnapshot({ + const daemonSnapshot = await readReplayViewport({ port: daemon.port, terminalId: terminal.id, }); await liveHeadless.flush(); - expect(liveHeadless.visibleLines()).toEqual(visibleTerminalLines(daemonSnapshot)); + expect(liveHeadless.visibleLines()).toEqual(daemonSnapshot.lines); expect(liveHeadless.cursor()).toEqual(daemonSnapshot.cursor); expect(liveHeadless.visibleLines()).toEqual(capturedViewport.lines); @@ -79,7 +78,7 @@ test("byte-stream headless terminal matches daemon state after high-output attac terminalId: terminal.id, headless: restoreHeadless, }); - const restoreFrame = waitForTerminalStreamEvent(client, terminal.id, "restore"); + const restoreFrame = waitForReplayEnd(client, terminal.id); await subscribeTerminal(client, terminal.id, { restore: { mode: "visible-snapshot", scrollbackLines: 200, size: BYTE_TEST_SIZE }, @@ -116,12 +115,10 @@ class ClientHeadlessTerminal { } applyEvent(event: TerminalStreamEvent): void { - if (event.type === "snapshot") { - this.enqueueText(renderTerminalSnapshotToAnsi(event.state), { resetDecoder: true }); - return; - } - if (event.type === "restore") { - this.enqueueText(this.decoder.decode(event.data, { stream: false }), { resetDecoder: true }); + if (event.type === "replay") { + if (event.replay.type === "begin") this.enqueueText("\x1bc", { resetDecoder: true }); + if (event.replay.type === "data") + this.enqueueText(this.decoder.decode(event.replay.data, { stream: true })); return; } this.enqueueText(this.decoder.decode(event.data, { stream: true })); @@ -187,35 +184,32 @@ async function subscribeTerminal( return response.subscription; } -async function readTerminalSnapshot(input: { - port: number; - terminalId: string; -}): Promise { - const client = new DaemonClient({ - url: `ws://127.0.0.1:${input.port}/ws`, - appVersion: "0.1.96", - clientType: "mobile", - }); +async function readReplayViewport(input: { port: number; terminalId: string }): Promise<{ + lines: string[]; + cursor: TerminalState["cursor"]; +}> { + const client = new DaemonClient({ url: `ws://127.0.0.1:${input.port}/ws`, clientType: "mobile" }); + const headless = new ClientHeadlessTerminal(BYTE_TEST_SIZE); + const stop = pipeTerminalStreamToHeadless({ client, terminalId: input.terminalId, headless }); try { await client.connect(); - const snapshot = waitForTerminalStreamEvent(client, input.terminalId, "snapshot"); + const completed = waitForReplayEnd(client, input.terminalId); await subscribeTerminal(client, input.terminalId); - const event = await snapshot; - return event.state; + await completed; + await headless.flush(); + return { lines: headless.visibleLines(), cursor: headless.cursor() }; } finally { + stop(); await client.close(); } } -function waitForTerminalStreamEvent( - client: DaemonClient, - terminalId: string, - type: TType, -): Promise> { - return client.waitForTerminalStreamEvent( - (event) => event.terminalId === terminalId && event.type === type, - 10_000, - ) as Promise>; +async function waitForReplayEnd(client: DaemonClient, terminalId: string): Promise { + await client.waitForTerminalStreamEvent( + (event) => + event.terminalId === terminalId && event.type === "replay" && event.replay.type === "end", + 10000, + ); } async function createPackageLockTerminalCwd(): Promise { @@ -287,24 +281,16 @@ async function waitForCondition( throw new Error(`Timed out after ${timeoutMs}ms waiting for terminal byte parity`); } -function visibleTerminalLines(state: TerminalState): string[] { - return state.grid.map(terminalRowText); -} - -function terminalRowText(row: TerminalState["grid"][number]): string { - return row - .map((cell) => cell.char) - .join("") - .trimEnd(); -} - function bufferLineText(line: IBufferLine | undefined, reusableCell: IBufferCell): string { const cells: TerminalCell[] = []; for (let col = 0; col < BYTE_TEST_SIZE.cols; col += 1) { const cell = line?.getCell(col, reusableCell); cells.push({ char: cell?.getChars() || " " }); } - return terminalRowText(cells); + return cells + .map((cell) => cell.char) + .join("") + .trimEnd(); } function packageLockStreamScript(): string { diff --git a/packages/server/src/server/daemon-e2e/terminal-worker-lifecycle.e2e.test.ts b/packages/server/src/server/daemon-e2e/terminal-worker-lifecycle.e2e.test.ts new file mode 100644 index 0000000000..d606b4d4d9 --- /dev/null +++ b/packages/server/src/server/daemon-e2e/terminal-worker-lifecycle.e2e.test.ts @@ -0,0 +1,688 @@ +import { afterEach, describe, expect, test } from "vitest"; +import { spawn, type ChildProcess } from "node:child_process"; +import { + chmodSync, + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { createServer } from "node:net"; +import { createRequire } from "node:module"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { setTimeout as delay } from "node:timers/promises"; +import { DaemonClient } from "../test-utils/daemon-client.js"; +import { resolveDaemonVersion } from "../daemon-version.js"; +import { readDaemonInstance, stopDaemonInstance } from "../daemon-instance.js"; +import { currentBootId } from "../pid-lock.js"; +import { connectTerminalWorker } from "../../terminal/terminal-worker-client.js"; +import { createTerminalWorkerProcessInspector } from "../../terminal/terminal-worker-processes.js"; +import { reapTerminalWorkers } from "../../terminal/terminal-worker-reaper.js"; +import { launchTerminalWorker } from "../../terminal/terminal-worker-launch.js"; +import { prepareTerminalWorkerRuntime } from "../../terminal/terminal-worker-runtime.js"; +import { createWorkerTerminalManager } from "../../terminal/worker-terminal-manager.js"; +import { + listTerminalWorkerRecords, + writeTerminalWorkerRecord, + type TerminalWorkerRecord, +} from "../../terminal/terminal-worker-record.js"; + +// Real supervisors started through scripts/supervisor-entrypoint.ts, driven by DaemonClient the +// way the app drives them. Every daemon, worker and program here lives in a throwaway home and +// is killed in afterEach; nothing touches another daemon. + +const SERVER_ROOT = path.resolve(import.meta.dirname, "../../.."); +const SUPERVISOR_ENTRY = path.join(SERVER_ROOT, "scripts/supervisor-entrypoint.ts"); +const READY_TIMEOUT_MS = 90_000; +const POSIX = process.platform !== "win32"; +const inspector = createTerminalWorkerProcessInspector(); + +interface Harness { + home: string; + workDir: string; + port: number; + supervisor: ChildProcess; + output: () => string; +} + +const harnesses: Harness[] = []; +const extraPids = new Set(); +const extraDirs: string[] = []; + +function isAlive(pid: number): boolean { + try { + process.kill(pid, 0); + return true; + } catch { + return false; + } +} + +async function waitFor( + probe: () => Promise | T | null | undefined | false, + message: string, + timeoutMs = READY_TIMEOUT_MS, +): Promise { + const deadline = Date.now() + timeoutMs; + let lastError: unknown = null; + while (Date.now() < deadline) { + try { + const value = await probe(); + if (value) return value; + } catch (error) { + lastError = error; + } + await delay(100); + } + throw new Error(`${message}${lastError ? ` (last error: ${String(lastError)})` : ""}`); +} + +async function getAvailablePort(): Promise { + const server = createServer(); + await new Promise((resolve) => server.listen(0, "127.0.0.1", () => resolve())); + const address = server.address(); + await new Promise((resolve) => server.close(() => resolve())); + if (!address || typeof address === "string") throw new Error("no port"); + return address.port; +} + +async function startSupervisor( + options: { home?: string; port?: number; pathPrefix?: string } = {}, +): Promise { + const home = options.home ?? mkdtempSync(path.join(tmpdir(), "tw-life-")); + const workDir = path.join(home, "work"); + mkdirSync(workDir, { recursive: true }); + const port = options.port ?? (await getAvailablePort()); + const env: NodeJS.ProcessEnv = { + ...Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith("PASEO_"))), + HOME: home, + USERPROFILE: home, + PASEO_HOME: home, + PASEO_LISTEN: `127.0.0.1:${port}`, + PASEO_RELAY_ENABLED: "false", + PASEO_NODE_INSPECT: "0", + PASEO_LOCAL_SPEECH_AUTO_DOWNLOAD: "0", + PASEO_DICTATION_ENABLED: "0", + PASEO_VOICE_MODE_ENABLED: "0", + CI: "true", + }; + if (options.pathPrefix) { + env.PATH = `${options.pathPrefix}${path.delimiter}${env.PATH ?? ""}`; + } + let output = ""; + const supervisor = spawn( + process.execPath, + ["--import", "tsx", SUPERVISOR_ENTRY, "--dev", "--no-relay"], + { cwd: SERVER_ROOT, env, stdio: ["ignore", "pipe", "pipe"] }, + ); + supervisor.stdout?.on("data", (chunk) => (output = (output + String(chunk)).slice(-20_000))); + supervisor.stderr?.on("data", (chunk) => (output = (output + String(chunk)).slice(-20_000))); + const harness: Harness = { home, workDir, port, supervisor, output: () => output }; + harnesses.push(harness); + await waitFor(async () => { + const instance = await readDaemonInstance(home); + return instance?.pid === supervisor.pid && instance.listen ? instance : null; + }, `supervisor did not become ready:\n${output}`); + return harness; +} + +async function connect(harness: Harness): Promise { + return waitFor(async () => { + const client = new DaemonClient({ + url: `ws://127.0.0.1:${harness.port}/ws`, + connectTimeoutMs: 5_000, + }); + try { + await client.connect(); + return client; + } catch (error) { + await client.close().catch(() => undefined); + throw error; + } + }, "cannot connect to the daemon"); +} + +// A plain `paseo daemon stop`: SIGTERM on POSIX, the shutdown RPC where there is no signal +// for it (Windows refuses a graceful stop without one). +async function stopDaemon(harness: Harness): Promise { + await stopDaemonInstance(harness.home, { + requestShutdown: async () => { + const client = await connect(harness); + try { + await client.shutdownServer(); + } finally { + await client.close(); + } + }, + }); +} + +async function daemonWorkerPid(client: DaemonClient): Promise { + return (await client.getDaemonStatus()).pid; +} + +async function waitForReplacement(harness: Harness, previousPid: number): Promise { + return waitFor(async () => { + const client = await connect(harness); + const pid = await daemonWorkerPid(client).catch(() => previousPid); + if (pid !== previousPid) return client; + await client.close(); + return null; + }, "the daemon worker was not replaced"); +} + +async function createWorkspace(client: DaemonClient, harness: Harness): Promise { + const result = await client.createWorkspace({ + source: { kind: "directory", path: harness.workDir }, + title: "lifecycle", + }); + if (!result.workspace) throw new Error(result.error ?? "workspace creation failed"); + return result.workspace.id; +} + +interface MarkedTerminal { + id: string; + programPid: number; +} + +// A terminal whose program writes its pid, prints a marker and echoes each input line. +async function createMarkedTerminal( + client: DaemonClient, + harness: Harness, + workspaceId: string, + marker: string, +): Promise { + const pidFile = path.join(harness.workDir, `${marker}.pid`); + const created = await client.createTerminal(harness.workDir, marker, undefined, { + workspaceId, + command: process.execPath, + args: [ + "-e", + `require("node:fs").writeFileSync(${JSON.stringify(pidFile)}, String(process.pid)); + console.log(${JSON.stringify(marker)}); + process.stdin.on("data", (data) => console.log("ECHO:" + data.toString().trim()));`, + ], + }); + if (!created.terminal) throw new Error(created.error ?? "terminal creation failed"); + const programPid = await waitFor( + () => (existsSync(pidFile) ? Number(readFileSync(pidFile, "utf8")) : null), + "terminal program did not start", + 10_000, + ); + await waitForScreen(client, created.terminal.id, marker); + return { id: created.terminal.id, programPid }; +} + +// A shell program that ignores SIGHUP. With `exec`, the shell becomes `sleep`: same pid and +// birth time, another command line. Without it, `sleep` runs as the shell's child. +async function createHupResistantTerminal( + client: DaemonClient, + harness: Harness, + workspaceId: string, + name: string, + mode: "exec" | "child", +): Promise<{ id: string; shellPid: number; sleepPid: number }> { + const shellPidFile = path.join(harness.workDir, `${name}.shell.pid`); + const sleepPidFile = path.join(harness.workDir, `${name}.sleep.pid`); + const script = + mode === "exec" + ? `trap '' HUP; echo $$ > '${shellPidFile}'; echo $$ > '${sleepPidFile}'; exec sleep 100000` + : `trap '' HUP; echo $$ > '${shellPidFile}'; sleep 100000 & echo $! > '${sleepPidFile}'; wait`; + const created = await client.createTerminal(harness.workDir, name, undefined, { + workspaceId, + command: "/bin/sh", + args: ["-c", script], + }); + if (!created.terminal) throw new Error(created.error ?? "terminal creation failed"); + const read = (file: string) => + existsSync(file) && readFileSync(file, "utf8").trim() + ? Number(readFileSync(file, "utf8").trim()) + : null; + const shellPid = await waitFor(() => read(shellPidFile), "shell did not start", 10_000); + const sleepPid = await waitFor(() => read(sleepPidFile), "sleep did not start", 10_000); + extraPids.add(shellPid); + extraPids.add(sleepPid); + // `exec` replaces the shell; wait until the process really is `sleep`. + await waitFor( + async () => { + const inspection = await inspector.inspect(sleepPid); + return inspection.status === "alive" && inspection.snapshot.commandLine?.startsWith("sleep"); + }, + "sleep did not start", + 10_000, + ); + return { id: created.terminal.id, shellPid, sleepPid }; +} + +async function screen(client: DaemonClient, terminalId: string): Promise { + return (await client.captureTerminal(terminalId, { stripAnsi: true })).lines.join("\n"); +} + +async function waitForScreen(client: DaemonClient, terminalId: string, text: string) { + await waitFor( + async () => (await screen(client, terminalId)).includes(text), + `terminal ${terminalId} never showed ${text}`, + 15_000, + ); +} + +async function expectKept( + client: DaemonClient, + terminal: MarkedTerminal, + marker: string, + trigger: string, +) { + const listed = await client.listTerminals(undefined, undefined, {}); + expect(listed.terminals.map((entry) => entry.id)).toContain(terminal.id); + expect(isAlive(terminal.programPid)).toBe(true); + expect(await screen(client, terminal.id)).toContain(marker); + client.sendTerminalInput(terminal.id, { type: "input", data: `after-${trigger}\r` }); + await waitForScreen(client, terminal.id, `ECHO:after-${trigger}`); +} + +async function waitUntilGone(pid: number, what: string) { + await waitFor(() => !isAlive(pid), `${what} (pid ${pid}) is still alive`, 15_000); +} + +async function liveRecords(home: string): Promise { + return (await listTerminalWorkerRecords(home)).flatMap((file) => + "record" in file ? [file.record] : [], + ); +} + +async function currentWorkerRecord(home: string): Promise { + const records = await liveRecords(home); + if (records.length !== 1) throw new Error(`expected one worker record, found ${records.length}`); + return records[0]!; +} + +async function expectAllClosed(home: string, pids: number[]) { + for (const pid of pids) { + await waitUntilGone(pid, "a process that should be closed"); + } + expect(await liveRecords(home)).toEqual([]); +} + +function spawnUnrelated(): ChildProcess { + const child = spawn(process.execPath, ["-e", "setInterval(() => {}, 1e9)"], { + detached: true, + stdio: "ignore", + }); + child.unref(); + extraPids.add(child.pid!); + return child; +} + +async function birthOf(pid: number): Promise { + const inspection = await inspector.inspect(pid); + if (inspection.status !== "alive" || !inspection.snapshot.startedAt) { + throw new Error(`no birth time for ${pid}`); + } + return inspection.snapshot.startedAt; +} + +afterEach(async () => { + for (const harness of harnesses.splice(0)) { + const pid = harness.supervisor.pid; + if (pid && isAlive(pid)) { + try { + process.kill(pid, "SIGCONT"); + } catch { + // gone + } + } + await stopDaemonInstance(harness.home, { force: true, timeoutMs: 15_000 }).catch( + () => undefined, + ); + if (pid && isAlive(pid)) process.kill(pid, "SIGKILL"); + for (const record of await liveRecords(harness.home)) { + if (isAlive(record.pid)) { + try { + process.kill(record.pid, "SIGCONT"); + } catch { + // gone + } + } + } + await reapTerminalWorkers({ paseoHome: harness.home, gracefulMs: 0 }).catch(() => undefined); + rmSync(harness.home, { recursive: true, force: true }); + } + for (const pid of extraPids) { + if (isAlive(pid)) { + try { + process.kill(pid, "SIGKILL"); + } catch { + // gone + } + } + } + extraPids.clear(); + for (const dir of extraDirs.splice(0)) rmSync(dir, { recursive: true, force: true }); +}); + +describe("terminals across daemon restarts", { timeout: 240_000 }, () => { + test("Settings restart keeps the terminal; Settings restart and close terminals kills it", async () => { + const harness = await startSupervisor(); + let client = await connect(harness); + const workspaceId = await createWorkspace(client, harness); + const terminal = await createMarkedTerminal(client, harness, workspaceId, "MARKER-SETTINGS"); + const workerPid = (await currentWorkerRecord(harness.home)).pid; + + // Exactly what the app sends from Settings: no killTerminals. + let daemonPid = await daemonWorkerPid(client); + await client.restartServer("settings_update"); + await client.close(); + client = await waitForReplacement(harness, daemonPid); + await expectKept(client, terminal, "MARKER-SETTINGS", "settings-restart"); + expect((await currentWorkerRecord(harness.home)).pid).toBe(workerPid); + + daemonPid = await daemonWorkerPid(client); + await client.restartServer("settings_update", undefined, { killTerminals: true }); + await client.close(); + client = await waitForReplacement(harness, daemonPid); + await waitUntilGone(terminal.programPid, "terminal program"); + await waitUntilGone(workerPid, "old terminal worker"); + expect((await client.listTerminals(undefined, undefined, {})).terminals).toEqual([]); + expect((await liveRecords(harness.home)).every((record) => record.pid !== workerPid)).toBe( + true, + ); + await client.close(); + }); + + test("a daemon crash keeps the terminal; the restarted daemon lists it", async () => { + const harness = await startSupervisor(); + let client = await connect(harness); + const workspaceId = await createWorkspace(client, harness); + const terminal = await createMarkedTerminal(client, harness, workspaceId, "MARKER-CRASH"); + const daemonPid = await daemonWorkerPid(client); + process.kill(daemonPid, "SIGKILL"); + await client.close(); + client = await waitForReplacement(harness, daemonPid); + await expectKept(client, terminal, "MARKER-CRASH", "crash"); + await client.close(); + }); + + test("daemon.update.request restarts the daemon and keeps the terminal", async () => { + // Fake npm only: `ls` reports this checkout as the global install at the daemon's + // version, `install -g` does nothing, and anything else fails so real npm never runs. + const fakeBin = mkdtempSync(path.join(tmpdir(), "tw-npm-")); + extraDirs.push(fakeBin); + const listing = JSON.stringify({ + path: path.join(fakeBin, "global"), + dependencies: { + "@getpaseo/cli": { + version: resolveDaemonVersion(import.meta.url), + path: SERVER_ROOT, + }, + }, + }); + const fakeNpm = path.join(fakeBin, "fake-npm.cjs"); + writeFileSync( + fakeNpm, + `const args = process.argv.slice(2); +const has = (...tokens) => tokens.every((token) => args.includes(token)); +if (has("-g", "ls", "@getpaseo/cli", "--json", "--depth=0", "--long")) { + process.stdout.write(${JSON.stringify(listing)} + "\\n"); +} else if (args[0] === "install" && has("-g", "@getpaseo/cli@latest")) { + // The installed version is already the running one: nothing to do. +} else { + process.stderr.write("unexpected npm call: " + args.join(" ") + "\\n"); + process.exit(1); +} +`, + ); + const npmScript = path.join(fakeBin, "npm"); + writeFileSync(npmScript, `#!/bin/sh\nexec "${process.execPath}" "${fakeNpm}" "$@"\n`); + chmodSync(npmScript, 0o755); + writeFileSync(path.join(fakeBin, "npm.cmd"), `@"${process.execPath}" "${fakeNpm}" %*\r\n`); + const harness = await startSupervisor({ pathPrefix: fakeBin }); + let client = await connect(harness); + const workspaceId = await createWorkspace(client, harness); + const terminal = await createMarkedTerminal(client, harness, workspaceId, "MARKER-UPDATE"); + const daemonPid = await daemonWorkerPid(client); + + const update = await client.updateDaemon(); + expect(update).toMatchObject({ success: true }); + await client.close(); + client = await waitForReplacement(harness, daemonPid); + await expectKept(client, terminal, "MARKER-UPDATE", "update"); + await client.close(); + }); + + test.skipIf(!POSIX)( + "POSIX: a kill restart whose shutdown hangs closes terminals before the respawn", + async () => { + const harness = await startSupervisor(); + let client = await connect(harness); + const workspaceId = await createWorkspace(client, harness); + const terminal = await createMarkedTerminal(client, harness, workspaceId, "MARKER-HUNG"); + const daemonPid = await daemonWorkerPid(client); + const supervisorPid = harness.supervisor.pid!; + const logPath = path.join(harness.home, "daemon.log"); + + // Barrier: the supervisor is paused, so the restart intent waits in its IPC channel. + // The daemon's own log line marks the intent dispatched; then the daemon is paused, so + // its graceful shutdown can never run and the supervisor's force path must. + process.kill(supervisorPid, "SIGSTOP"); + await client.restartServer("settings_update", undefined, { killTerminals: true }); + await waitFor( + () => readFileSync(logPath, "utf8").includes("Lifecycle intent dispatched"), + "the daemon never dispatched the restart intent", + 15_000, + ); + process.kill(daemonPid, "SIGSTOP"); + expect(isAlive(terminal.programPid)).toBe(true); + process.kill(supervisorPid, "SIGCONT"); + await client.close(); + + client = await waitForReplacement(harness, daemonPid); + const log = readFileSync(logPath, "utf8"); + const forced = log.indexOf("forcing process tree kill"); + const cleaned = log.indexOf('"msg":"Terminal cleanup finished","when":"before_respawn"'); + const respawned = log.indexOf('"msg":"Spawning worker"', forced); + expect(forced).toBeGreaterThan(-1); + expect(cleaned).toBeGreaterThan(forced); + expect(respawned).toBeGreaterThan(cleaned); + expect(isAlive(terminal.programPid)).toBe(false); + expect((await client.listTerminals(undefined, undefined, {})).terminals).toEqual([]); + await client.close(); + }, + ); +}); + +describe("terminals when the daemon stops", { timeout: 240_000 }, () => { + test.skipIf(!POSIX)( + "POSIX: stop closes a terminal whose program ignores HUP, child process included", + async () => { + const harness = await startSupervisor(); + const client = await connect(harness); + const workspaceId = await createWorkspace(client, harness); + const terminal = await createHupResistantTerminal( + client, + harness, + workspaceId, + "hup", + "child", + ); + const workerPid = (await currentWorkerRecord(harness.home)).pid; + await client.close(); + await stopDaemon(harness); + await expectAllClosed(harness.home, [terminal.shellPid, terminal.sleepPid, workerPid]); + }, + ); + + for (const force of [false, true]) { + test.skipIf(!POSIX)( + `POSIX: worker death reaps an exec'd HUP-resistant program and ${force ? "stop --force" : "stop"} closes its replacement`, + async () => { + const harness = await startSupervisor(); + const client = await connect(harness); + const workspaceId = await createWorkspace(client, harness); + const terminal = await createHupResistantTerminal( + client, + harness, + workspaceId, + "orphan", + "exec", + ); + const workerPid = (await currentWorkerRecord(harness.home)).pid; + const daemonPid = await daemonWorkerPid(client); + process.kill(workerPid, "SIGKILL"); + await waitUntilGone(workerPid, "terminal worker"); + await waitUntilGone(terminal.sleepPid, "orphaned terminal program"); + await waitFor( + async () => (await client.listTerminals(undefined, undefined, {})).terminals.length === 0, + "dead terminal was not removed", + ); + expect(await daemonWorkerPid(client)).toBe(daemonPid); + const replacement = await createMarkedTerminal(client, harness, workspaceId, "RECOVERED"); + await expectKept(client, replacement, "RECOVERED", "worker-death"); + await client.close(); + await stopDaemonInstance(harness.home, { force }); + await expectAllClosed(harness.home, [terminal.sleepPid, replacement.programPid]); + }, + ); + } + + test.skipIf(!POSIX)( + "POSIX: stop --force kills a stopped (SIGSTOP) worker and its terminal", + async () => { + const harness = await startSupervisor(); + const client = await connect(harness); + const workspaceId = await createWorkspace(client, harness); + const terminal = await createMarkedTerminal(client, harness, workspaceId, "MARKER-STOPPED"); + const workerPid = (await currentWorkerRecord(harness.home)).pid; + await client.close(); + process.kill(workerPid, "SIGSTOP"); + await stopDaemonInstance(harness.home, { force: true }); + await expectAllClosed(harness.home, [workerPid, terminal.programPid]); + }, + ); + + test("the worker socket rejects a wrong secret and leaves its terminals alone", async () => { + const harness = await startSupervisor(); + const client = await connect(harness); + const workspaceId = await createWorkspace(client, harness); + const terminal = await createMarkedTerminal(client, harness, workspaceId, "MARKER-AUTH"); + const record = await currentWorkerRecord(harness.home); + await expect( + connectTerminalWorker({ socketPath: record.socketPath, secret: "not-the-secret" }), + ).rejects.toThrow(); + await expectKept(client, terminal, "MARKER-AUTH", "auth"); + await client.close(); + }); + + test("stop and stop --force never signal processes a stale or earlier-boot record names", async () => { + const harness = await startSupervisor(); + const client = await connect(harness); + await client.close(); + const reused = spawnUnrelated(); + const earlierBoot = spawnUnrelated(); + const base = await currentWorkerRecord(harness.home); + // Same pid, another birth time: what a reused pid looks like, whatever its command line. + writeTerminalWorkerRecord(harness.home, { + ...base, + recordId: "stale-record", + pid: reused.pid!, + identity: { startedAt: "Thu Jan 1 00:00:00 1970", commandLine: "node -e setInterval" }, + terminals: [{ id: "t-stale", pid: reused.pid!, startedAt: "Thu Jan 1 00:00:00 1970" }], + }); + // The right birth time, but written before this boot. + writeTerminalWorkerRecord(harness.home, { + ...base, + recordId: "earlier-boot-record", + pid: earlierBoot.pid!, + bootId: currentBootId() ? "another-boot" : null, + createdAt: "2000-01-01T00:00:00.000Z", + identity: { + startedAt: await birthOf(earlierBoot.pid!), + commandLine: `node --paseo-terminal-worker earlier-boot-record`, + }, + terminals: [ + { id: "t-boot", pid: earlierBoot.pid!, startedAt: await birthOf(earlierBoot.pid!) }, + ], + }); + + await stopDaemon(harness); + expect(isAlive(reused.pid!)).toBe(true); + expect(isAlive(earlierBoot.pid!)).toBe(true); + expect(await liveRecords(harness.home)).toEqual([]); + + // A second round through --force, with the stale record put back. + writeTerminalWorkerRecord(harness.home, { + ...base, + recordId: "stale-record", + pid: reused.pid!, + identity: { startedAt: "Thu Jan 1 00:00:00 1970", commandLine: "node -e setInterval" }, + terminals: [{ id: "t-stale", pid: reused.pid!, startedAt: "Thu Jan 1 00:00:00 1970" }], + }); + await stopDaemonInstance(harness.home, { force: true }); + expect(isAlive(reused.pid!)).toBe(true); + expect(await liveRecords(harness.home)).toEqual([]); + }); +}); + +describe("a worker launched from its own copy", { timeout: 240_000 }, () => { + // What a built daemon does: bundle the worker, copy bundle + shell integration + node-pty into + // the home, launch from the copy. Here the copy's node-pty (ConPTY on Windows) opens a real + // terminal; nothing is loaded from this checkout once the worker runs. + test("opens a terminal and runs a command from the copied bundle and node-pty", async () => { + const home = mkdtempSync(path.join(tmpdir(), "tw-copy-home-")); + const bundleDirectory = mkdtempSync(path.join(tmpdir(), "tw-copy-bundle-")); + extraDirs.push(home, bundleDirectory); + const buildScript = path.join(SERVER_ROOT, "scripts/build-terminal-worker.mjs"); + const { buildTerminalWorkerBundle } = (await import(buildScript)) as { + buildTerminalWorkerBundle(input: { outDir: string }): Promise; + }; + await buildTerminalWorkerBundle({ outDir: bundleDirectory }); + const nodePtyDirectory = path.dirname( + createRequire(import.meta.url).resolve("node-pty/package.json"), + ); + const entry = prepareTerminalWorkerRuntime({ + paseoHome: home, + paseoVersion: "0.0.0-copy", + bundleDirectory, + nodePtyDirectory, + }); + + const launched = await launchTerminalWorker({ + paseoHome: home, + paseoVersion: "0.0.0-copy", + entry, + }); + extraPids.add(launched.record.pid); + expect(launched.record.runtime).toBe(entry.runtime); + const manager = createWorkerTerminalManager({ + worker: await connectTerminalWorker({ + socketPath: launched.record.socketPath, + secret: launched.record.secret, + }), + closeTerminals: async () => { + await reapTerminalWorkers({ paseoHome: home }); + }, + }); + try { + const session = await manager.createTerminal({ + workspaceId: "ws-copy", + cwd: home, + command: process.execPath, + args: ["-e", "console.log('COPY-' + 'OK'); setInterval(() => {}, 1000);"], + }); + await waitFor( + async () => + (await manager.captureTerminal(session.id, { stripAnsi: true })).lines + .join("\n") + .includes("COPY-OK"), + "the terminal in the copied worker never printed its marker", + 30_000, + ); + } finally { + await manager.closeTerminals(); + } + expect(isAlive(launched.record.pid)).toBe(false); + expect(existsSync(path.dirname(entry.scriptPath))).toBe(false); + }); +}); diff --git a/packages/server/src/server/daemon-e2e/terminal.e2e.test.ts b/packages/server/src/server/daemon-e2e/terminal.e2e.test.ts index 633bd3bc1c..36425ffeec 100644 --- a/packages/server/src/server/daemon-e2e/terminal.e2e.test.ts +++ b/packages/server/src/server/daemon-e2e/terminal.e2e.test.ts @@ -1,3 +1,4 @@ +import { Terminal as HeadlessTerminal } from "@xterm/headless"; import { afterEach, beforeEach, describe, expect, test } from "vitest"; import { mkdtempSync, rmSync } from "fs"; import { tmpdir } from "os"; @@ -10,7 +11,6 @@ import { type WSOutboundMessage, } from "@getpaseo/protocol/messages"; import { - decodeTerminalSnapshotPayload, decodeTerminalStreamFrame, encodeTerminalStreamFrame, TerminalStreamOpcode, @@ -80,6 +80,24 @@ async function waitForCondition( throw new Error(`Timed out after ${timeoutMs}ms waiting for condition`); } +function readHeadlessState(terminal: HeadlessTerminal): TerminalState { + const buffer = terminal.buffer.active; + const lines: TerminalState["grid"] = []; + for (let row = 0; row < buffer.length; row++) { + const cells: TerminalState["grid"][number] = []; + for (let col = 0; col < terminal.cols; col++) + cells.push({ char: buffer.getLine(row)?.getCell(col)?.getChars() ?? "" }); + lines.push(cells); + } + return { + rows: terminal.rows, + cols: terminal.cols, + grid: lines.slice(buffer.baseY), + scrollback: lines.slice(0, buffer.baseY), + cursor: { row: buffer.cursorY, col: buffer.cursorX }, + }; +} + async function waitForTerminalSnapshot( client: DaemonClient, terminalId: string, @@ -92,16 +110,34 @@ async function waitForTerminalSnapshot( reject(new Error(`Timeout waiting for terminal snapshot (${timeout}ms)`)); }, timeout); + let terminal: HeadlessTerminal | null = null; + let writes = Promise.resolve(); const unsubscribe = client.onTerminalStreamEvent((event) => { - if (event.terminalId !== terminalId || event.type !== "snapshot") { - return; + if (event.terminalId !== terminalId || event.type !== "replay") return; + const replay = event.replay; + if (replay.type === "begin") { + terminal?.dispose(); + terminal = new HeadlessTerminal({ + rows: replay.rows ?? 24, + cols: replay.cols ?? 80, + scrollback: 1000, + allowProposedApi: true, + }); + } else if (replay.type === "data") { + const active = terminal!; + writes = writes.then(() => new Promise((done) => active.write(replay.data, done))); + } else { + void writes.then(() => { + const active = terminal!; + const state = readHeadlessState(active); + if (!predicate(state)) return null; + clearTimeout(timeoutHandle); + unsubscribe(); + active.dispose(); + resolve(state); + return null; + }); } - if (!predicate(event.state)) { - return; - } - clearTimeout(timeoutHandle); - unsubscribe(); - resolve(event.state); }); }); } @@ -160,7 +196,7 @@ function toWsBuffer(raw: WebSocket.RawData): Buffer | null { return null; } -async function connectRawWebSocket(port: number): Promise { +async function connectRawWebSocket(port: number, chunkedReplay = false): Promise { const ws = new WebSocket(`ws://127.0.0.1:${port}/ws`); await new Promise((resolve, reject) => { ws.once("open", () => resolve()); @@ -180,6 +216,7 @@ async function connectRawWebSocket(port: number): Promise { clientId: `terminal-raw-${Date.now()}-${Math.random().toString(36).slice(2)}`, clientType: "cli", protocolVersion: 1, + capabilities: { terminal_chunked_replay: chunkedReplay }, }), ); @@ -386,17 +423,24 @@ async function collectRawBinaryFrames( }); } +async function decodeRestoreState( + frame: TerminalStreamFrame, + terminalId: string, +): Promise { + const size = ctx.daemon.daemon.terminalManager!.getTerminal(terminalId)!.getSize(); + const terminal = new HeadlessTerminal({ ...size, scrollback: 1000, allowProposedApi: true }); + try { + await new Promise((resolve) => terminal.write(frame.payload, resolve)); + return readHeadlessState(terminal); + } finally { + terminal.dispose(); + } +} + function getFrameText(frame: TerminalStreamFrame): string { if (frame.opcode === TerminalStreamOpcode.Output) { return new TextDecoder().decode(frame.payload); } - if (frame.opcode === TerminalStreamOpcode.Snapshot) { - const state = decodeTerminalSnapshotPayload(frame.payload); - if (!state) { - return ""; - } - return extractStateText(state); - } if (frame.opcode === TerminalStreamOpcode.Restore) { return new TextDecoder().decode(frame.payload); } @@ -446,7 +490,10 @@ function startTerminalOutputCapture(ws: WebSocket, slot: number): TerminalOutput if (!frame || frame.slot !== slot) { return; } - if (frame.opcode === TerminalStreamOpcode.Snapshot) { + if ( + frame.opcode === TerminalStreamOpcode.Restore || + frame.opcode === TerminalStreamOpcode.ReplayEnd + ) { snapshotCount += 1; return; } @@ -634,7 +681,7 @@ async function measureRepeatCadenceForTerminal(input: { const slot = await subscribeRawTerminal(ws, terminalId, `sub-repeat-cadence-${input.name}`); await waitForRawBinaryFrame( ws, - (frame) => frame.slot === slot && frame.opcode === TerminalStreamOpcode.Snapshot, + (frame) => frame.slot === slot && frame.opcode === TerminalStreamOpcode.Restore, 10000, ); await new Promise((resolve) => setTimeout(resolve, 1000)); @@ -817,13 +864,7 @@ test("live terminal restore skips the initial snapshot", async () => { expect(outputText).toContain("after-live"); expect(outputText).not.toContain("before-live"); - expect( - outputFrames.some( - (frame) => - frame.opcode === TerminalStreamOpcode.Snapshot || - frame.opcode === TerminalStreamOpcode.Restore, - ), - ).toBe(false); + expect(outputFrames.some((frame) => frame.opcode === TerminalStreamOpcode.Restore)).toBe(false); } finally { await closeWebSocket(ws); } @@ -901,15 +942,12 @@ test("propagates debounced terminal titles through list responses and snapshots" } expect(listedTitle).toBe("Build Output"); - const snapshotPromise = waitForTerminalSnapshot( - ctx.client, - terminalId, - (state) => state.title === "Build Output", + const attached = await ctx.client.subscribeTerminal(terminalId); + expect(attached.error).toBeNull(); + const afterAttach = await ctx.client.listTerminals(cwd); + expect(afterAttach.terminals.find((terminal) => terminal.id === terminalId)?.title).toBe( + "Build Output", ); - await ctx.client.subscribeTerminal(terminalId); - const snapshot = await snapshotPromise; - - expect(snapshot.title).toBe("Build Output"); rmSync(cwd, { recursive: true, force: true }); }, 30000); @@ -973,13 +1011,10 @@ test("subscribe response is sent before the initial snapshot frame", async () => return; } const frame = decodeTerminalStreamFrame(new Uint8Array(buffer)); - if (frame?.opcode !== TerminalStreamOpcode.Snapshot) { - return; - } - const state = decodeTerminalSnapshotPayload(frame.payload); - if (!state || !extractStateText(state).includes("hello-ordering")) { + if (frame?.opcode !== TerminalStreamOpcode.Restore) { return; } + if (!getFrameText(frame).includes("hello-ordering")) return; events.push("snapshot"); maybeResolve(); }; @@ -1113,7 +1148,7 @@ test("reconnected terminal streams replay active input modes after the snapshot" const firstSlot = await subscribeRawTerminal(firstWs, terminalId, "sub-input-mode-first"); await waitForRawBinaryFrame( firstWs, - (frame) => frame.slot === firstSlot && frame.opcode === TerminalStreamOpcode.Snapshot, + (frame) => frame.slot === firstSlot && frame.opcode === TerminalStreamOpcode.Restore, ); sendRawTerminalInput(firstWs, firstSlot, "e"); await waitForRawBinaryFrame( @@ -1140,7 +1175,7 @@ test("reconnected terminal streams replay active input modes after the snapshot" const secondSlot = await subscribeRawTerminal(secondWs, terminalId, "sub-input-mode-second"); await waitForRawBinaryFrame( secondWs, - (frame) => frame.slot === secondSlot && frame.opcode === TerminalStreamOpcode.Snapshot, + (frame) => frame.slot === secondSlot && frame.opcode === TerminalStreamOpcode.Restore, ); const replay = await waitForRawBinaryFrame( secondWs, @@ -1172,7 +1207,7 @@ test("reconnected terminal streams do not replay input modes before they are ena const slot = await subscribeRawTerminal(ws, terminalId, "sub-input-mode-inactive"); await waitForRawBinaryFrame( ws, - (frame) => frame.slot === slot && frame.opcode === TerminalStreamOpcode.Snapshot, + (frame) => frame.slot === slot && frame.opcode === TerminalStreamOpcode.Restore, ); await waitForNoRawBinaryFrame(ws, 300); } finally { @@ -1188,7 +1223,7 @@ test("fast output to a slow websocket client falls back to a snapshot", async () const ws = await connectRawWebSocket(ctx.daemon.port); await subscribeRawTerminal(ws, terminalId, "sub-raw"); - await waitForRawBinaryFrame(ws, (frame) => frame.opcode === TerminalStreamOpcode.Snapshot, 10000); + await waitForRawBinaryFrame(ws, (frame) => frame.opcode === TerminalStreamOpcode.Restore, 10000); const rawSocket = (ws as WebSocket & { _socket?: { pause: () => void; resume: () => void } }) ._socket; @@ -1203,12 +1238,12 @@ test("fast output to a slow websocket client falls back to a snapshot", async () await new Promise((resolve) => setTimeout(resolve, 750)); const catchUpFramePromise = waitForRawBinaryFrame( ws, - (frame) => frame.opcode === TerminalStreamOpcode.Snapshot, + (frame) => frame.opcode === TerminalStreamOpcode.Restore, 15000, ); rawSocket!.resume(); const catchUpFrame = await catchUpFramePromise; - expect(catchUpFrame.opcode).toBe(TerminalStreamOpcode.Snapshot); + expect(catchUpFrame.opcode).toBe(TerminalStreamOpcode.Restore); await closeWebSocket(ws); rmSync(cwd, { recursive: true, force: true }); @@ -1260,7 +1295,7 @@ test("resize updates server dimensions without sending a live snapshot", async ( await new Promise((resolve) => setTimeout(resolve, 300)); - const state = ctx.daemon.daemon.terminalManager?.getTerminal(terminalId)?.getState(); + const state = ctx.daemon.daemon.terminalManager?.getTerminal(terminalId)?.getSize(); expect(state?.rows).toBe(10); expect(state?.cols).toBe(40); @@ -1277,7 +1312,7 @@ test("the latest resize from any attached client owns the PTY size", async () => ); const readSize = () => { - const state = ctx.daemon.daemon.terminalManager?.getTerminal(terminalId)?.getState(); + const state = ctx.daemon.daemon.terminalManager?.getTerminal(terminalId)?.getSize(); return state ? { rows: state.rows, cols: state.cols } : null; }; const expectSize = async (size: { rows: number; cols: number }) => { @@ -1403,10 +1438,10 @@ test("websocket terminate then new connection gets snapshot with all prior outpu await subscribeRawTerminal(firstSocket, terminalId, "sub-drop-a"); const initialSnapshot = await waitForRawBinaryFrame( firstSocket, - (frame) => frame.opcode === TerminalStreamOpcode.Snapshot, + (frame) => frame.opcode === TerminalStreamOpcode.Restore, 10000, ); - expect(initialSnapshot.opcode).toBe(TerminalStreamOpcode.Snapshot); + expect(initialSnapshot.opcode).toBe(TerminalStreamOpcode.Restore); ctx.client.sendTerminalInput(terminalId, { type: "input", @@ -1442,9 +1477,9 @@ test("websocket terminate then new connection gets snapshot with all prior outpu try { await subscribeRawTerminal(secondSocket, terminalId, "sub-drop-b"); const reconnectFrame = await waitForRawBinaryFrame(secondSocket, () => true, 10000); - expect(reconnectFrame.opcode).toBe(TerminalStreamOpcode.Snapshot); + expect(reconnectFrame.opcode).toBe(TerminalStreamOpcode.Restore); - const state = decodeTerminalSnapshotPayload(reconnectFrame.payload); + const state = await decodeRestoreState(reconnectFrame, terminalId); expect(state).not.toBeNull(); expect(extractStateText(state!)).toContain("before-drop"); expect(extractStateText(state!)).toContain("while-dead"); @@ -1513,11 +1548,11 @@ test("snapshot fidelity through websocket decode preserves dimensions and visibl await subscribeRawTerminal(ws, terminalId, "sub-fidelity"); const snapshotFrame = await waitForRawBinaryFrame( ws, - (frame) => frame.opcode === TerminalStreamOpcode.Snapshot, + (frame) => frame.opcode === TerminalStreamOpcode.Restore, 10000, ); - const state = decodeTerminalSnapshotPayload(snapshotFrame.payload); + const state = await decodeRestoreState(snapshotFrame, terminalId); expect(state).not.toBeNull(); expect(state).toMatchObject({ rows: 24, @@ -1545,7 +1580,7 @@ test("terminal exit prevents resubscribe and sends no frames after exit", async await subscribeRawTerminal(ws, terminalId, "sub-exit"); await waitForRawBinaryFrame( ws, - (frame) => frame.opcode === TerminalStreamOpcode.Snapshot, + (frame) => frame.opcode === TerminalStreamOpcode.Restore, 10000, ); @@ -1561,8 +1596,7 @@ test("terminal exit prevents resubscribe and sends no frames after exit", async const exitMessage = await exitMessagePromise; expect(exitMessage.message.type).toBe("terminal_stream_exit"); - const subscribeResult = await ctx.client.subscribeTerminal(terminalId); - expect(subscribeResult.error).toBe("Terminal not found"); + await expect(ctx.client.subscribeTerminal(terminalId)).rejects.toThrow("Terminal not found"); await waitForNoRawBinaryFrame(ws, 750); } finally { await closeWebSocket(ws); @@ -1580,7 +1614,7 @@ test("empty input frame does not crash the server", async () => { const slot = await subscribeRawTerminal(ws, terminalId, "sub-empty-input"); await waitForRawBinaryFrame( ws, - (frame) => frame.opcode === TerminalStreamOpcode.Snapshot, + (frame) => frame.opcode === TerminalStreamOpcode.Restore, 10000, ); @@ -1619,7 +1653,7 @@ test("1MB output burst keeps frames decodable and terminal usable afterward", as await subscribeRawTerminal(ws, terminalId, "sub-large-output"); await waitForRawBinaryFrame( ws, - (frame) => frame.opcode === TerminalStreamOpcode.Snapshot, + (frame) => frame.opcode === TerminalStreamOpcode.Restore, 10000, ); @@ -1636,7 +1670,7 @@ test("1MB output burst keeps frames decodable and terminal usable afterward", as .reduce((sum, frame) => sum + frame.payload.byteLength, 0); return ( outputBytes >= 1024 * 1024 || - collectedFrames.some((frame) => frame.opcode === TerminalStreamOpcode.Snapshot) + collectedFrames.some((frame) => frame.opcode === TerminalStreamOpcode.Restore) ); }, 20000, @@ -1646,7 +1680,7 @@ test("1MB output burst keeps frames decodable and terminal usable afterward", as for (const frame of frames) { expect( frame.opcode === TerminalStreamOpcode.Output || - frame.opcode === TerminalStreamOpcode.Snapshot, + frame.opcode === TerminalStreamOpcode.Restore, ).toBe(true); } @@ -1836,3 +1870,194 @@ describe("list terminals across directories", () => { ]); }); }); + +test.each([3000, 12050])( + "chunked SDK replay retains requested history for %s printed lines", + async (count) => { + const cwd = tmpCwd(); + tempDirs.push(cwd); + const created = await createTerminalInWorkspace(ctx.client, { + cwd, + options: { + command: "/bin/sh", + args: [ + "-lc", + `i=1; while [ $i -le ${count} ]; do printf '\\033[31mreplay-%04d界🙂 payload-abcdefghijklmnopqrstuvwxyz0123456789\\033[0m\\n' $i; i=$((i+1)); done; sleep 30`, + ], + }, + }); + const id = created.terminal!.id; + await waitForCondition( + async () => + (await ctx.client.captureTerminal(id)).lines + .join("\n") + .includes(`replay-${String(count).padStart(4, "0")}`), + 10000, + ); + const events: import("@getpaseo/client").TerminalStreamEvent[] = []; + let end!: () => void; + const completed = new Promise((resolve) => { + end = resolve; + }); + const subscription = ctx.client.observeTerminal( + id, + (event) => { + events.push(event); + if (event.type === "replay" && event.replay.type === "end") end(); + }, + { restore: { mode: "visible-snapshot", scrollbackLines: 10000 } }, + ); + try { + await subscription.ready; + await completed; + const replay = events.flatMap((event) => (event.type === "replay" ? [event.replay] : [])); + expect(replay[0]).toMatchObject({ + type: "begin", + retainedHistoryLines: count === 12050 ? 10000 : expect.any(Number), + }); + expect(replay.at(-1)).toEqual({ type: "end" }); + const chunks = replay.flatMap((event) => (event.type === "data" ? [event.data] : [])); + expect(chunks.every((chunk) => chunk.length <= 65536)).toBe(true); + const text = Buffer.concat(chunks).toString("utf8"); + const begin = replay[0]; + if (begin?.type !== "begin" || begin.rows === undefined) + throw new Error("Missing replay dimensions"); + expect(text.match(/replay-\d{4,5}/g)).toHaveLength(Math.min(count, 10000 + begin.rows - 1)); + expect(text).toContain(`replay-${String(count).padStart(4, "0")}界🙂`); + if (count === 3000) expect(text).toContain("replay-0001界🙂"); + else { + expect(text).not.toContain("replay-0001"); + expect(chunks.length).toBeGreaterThan(1); + } + } finally { + await subscription.release(); + } + }, + 30000, +); + +test.each([false, true])( + "default SDK observation replays a terminal without waiting for output (quietScreen=%s)", + async (quietScreen) => { + const cwd = tmpCwd(); + tempDirs.push(cwd); + const created = await createTerminalInWorkspace(ctx.client, { + cwd, + options: { + command: process.execPath, + args: [ + "-e", + `${quietScreen ? 'process.stdout.write("QUIET-SCREEN\\r\\n");' : ""} process.stdin.on("data", data => process.stdout.write("LIVE:" + data)); setInterval(() => {}, 1000);`, + ], + }, + }); + const id = created.terminal!.id; + if (quietScreen) + await waitForCondition( + async () => (await ctx.client.captureTerminal(id)).lines.join("").includes("QUIET-SCREEN"), + 10000, + ); + const events: import("@getpaseo/client").TerminalStreamEvent[] = []; + const observation = ctx.client.observeTerminal(id, (event) => events.push(event)); + try { + await observation.ready; + await waitForCondition( + () => events.some((event) => event.type === "replay" && event.replay.type === "end"), + 10000, + ); + const replay = events.flatMap((event) => (event.type === "replay" ? [event.replay] : [])); + const begin = replay[0]; + if (begin?.type !== "begin" || !begin.rows || !begin.cols) + throw new Error("Missing replay begin geometry"); + expect(replay.at(-1)).toEqual({ type: "end" }); + const terminal = new HeadlessTerminal({ + rows: begin.rows, + cols: begin.cols, + allowProposedApi: true, + }); + try { + for (const event of replay) + if (event.type === "data") + await new Promise((resolve) => terminal.write(event.data, resolve)); + const text = extractStateText(readHeadlessState(terminal)); + expect(text).toBe(quietScreen ? "QUIET-SCREEN" : ""); + } finally { + terminal.dispose(); + } + ctx.client.sendTerminalInput(id, { type: "input", data: "next\r" }); + await waitForCondition( + () => + events.some( + (event) => + event.type === "output" && new TextDecoder().decode(event.data).includes("LIVE:next"), + ), + 10000, + ); + } finally { + await observation.release(); + } + }, + 30000, +); + +test.each([false, true])( + "a paused terminal consumer catches up through ANSI replay instead of retaining every output frame (chunked=%s)", + async (chunked) => { + const { existsSync } = await import("node:fs"); + const cwd = tmpCwd(); + tempDirs.push(cwd); + const marker = path.join(cwd, "output-complete"); + const created = await createTerminalInWorkspace(ctx.client, { + cwd, + options: { + command: process.execPath, + args: [ + "-e", + ` + const fs = require('node:fs'); + process.stdin.setRawMode?.(true); + process.stdin.resume(); + process.stdin.once('data', () => { + const chunk = Buffer.alloc(256 * 1024, 120); + let remaining = 128; + const write = () => { + if (remaining-- === 0) { fs.writeFileSync(${JSON.stringify(marker)}, 'done'); return; } + process.stdout.write(chunk, write); + }; + write(); + }); + `, + ], + }, + }); + const ws = await connectRawWebSocket(ctx.daemon.port, chunked); + try { + const slot = await subscribeRawTerminal(ws, created.terminal!.id, "slow-terminal"); + await waitForRawBinaryFrame( + ws, + (frame) => + frame.slot === slot && + frame.opcode === + (chunked ? TerminalStreamOpcode.ReplayEnd : TerminalStreamOpcode.Restore), + ); + const capture = startTerminalOutputCapture(ws, slot); + try { + ws.pause(); + sendRawTerminalInput(ws, slot, "go\n"); + await waitForCondition(() => existsSync(marker), 20000); + ws.resume(); + await waitForCondition(() => capture.snapshotCount > 0, 10000); + expect(ws.readyState).toBe(WebSocket.OPEN); + expect(capture.frames.reduce((total, frame) => total + frame.payloadBytes, 0)).toBeLessThan( + 32 * 1024 * 1024, + ); + } finally { + ws.resume(); + capture.stop(); + } + } finally { + await closeWebSocket(ws); + } + }, + 40000, +); diff --git a/packages/server/src/server/daemon-instance.ts b/packages/server/src/server/daemon-instance.ts index 02f4446795..b3b07e7ff0 100644 --- a/packages/server/src/server/daemon-instance.ts +++ b/packages/server/src/server/daemon-instance.ts @@ -11,6 +11,7 @@ import { } from "./pid-lock.js"; import { daemonLaunchEnvironment } from "./config-environment.js"; import { readPersistedConfig } from "./persisted-config.js"; +import { reapTerminalWorkers } from "../terminal/terminal-worker-reaper.js"; import treeKill from "tree-kill"; const killTree = (pid: number, signal: string): Promise => new Promise((resolve, reject) => @@ -29,6 +30,10 @@ export { resolvePaseoHome } from "./paseo-home.js"; export { ensurePrivateDirectory } from "./private-files.js"; export { daemonLaunchEnvironment } from "./config-environment.js"; export { readLocalCredentialForTarget } from "./local-credential.js"; +export { + TerminalCleanupNotConfirmedError, + retryUnconfirmedTerminalCleanup, +} from "../terminal/terminal-worker-reaper.js"; export { isSamePidLock as isSameDaemonInstance, type PidLockInfo as DaemonInstance, @@ -97,11 +102,23 @@ async function requestInstanceStop( instance: PidLockInfo, options: { force?: boolean; + keepTerminals?: boolean; requestShutdown?: (instance: PidLockInfo & { listen: string }) => Promise; }, ) { let forced = false; let usedLifecycleRpc = false; + if (options.keepTerminals) { + // SIGTERM means "stop and close terminals"; keeping them always goes over the RPC. + if (!instance.listen || !options.requestShutdown) { + throw new DaemonInstanceError( + "STOP_NO_GRACEFUL_CHANNEL", + `PID ${instance.pid} for ${home} has no listen address, so it cannot be asked to keep its terminals.`, + ); + } + await options.requestShutdown({ ...instance, listen: instance.listen }); + return { forced, usedLifecycleRpc: true }; + } if (process.platform === "win32") { if (instance.listen && options.requestShutdown) { try { @@ -142,6 +159,8 @@ export async function stopDaemonInstance( options: { instance?: PidLockInfo; force?: boolean; + // Leave the terminal worker running so the next daemon adopts it. Not valid with force. + keepTerminals?: boolean; timeoutMs?: number; killTimeoutMs?: number; requestShutdown?: (instance: PidLockInfo & { listen: string }) => Promise; @@ -153,6 +172,7 @@ export async function stopDaemonInstance( usedLifecycleRpc: boolean; }> { const { timeoutMs = 15_000, killTimeoutMs = 3_000 } = options; + assertStopOptions(options); const deadline = Date.now() + timeoutMs; const instance = await getPidLockInfo(home); if (options.instance && instance && !isSamePidLock(instance, options.instance)) { @@ -164,6 +184,9 @@ export async function stopDaemonInstance( if (!instance || !isPidLockOwnerRunning(instance)) { if (instance) await releasePidLock(home, { ownerPid: instance.pid, startedAt: instance.startedAt }); + // Terminals a `stop --keep-terminals` left behind belong to no daemon now; a plain stop + // closes them. + await closeLeftoverTerminals(home, { keepTerminals: options.keepTerminals, forced: false }); return { action: "not_running", pid: instance?.pid ?? null, @@ -200,9 +223,29 @@ export async function stopDaemonInstance( `Timed out waiting for supervisor PID ${instance.pid} in ${home} to exit${options.force ? "" : "; use --force to permit forced cleanup"}.`, ); await releasePidLock(home, { ownerPid: instance.pid, startedAt: instance.startedAt }); + // The supervisor already closed the terminals unless it was killed; this confirms it, and + // after --force (no graceful shutdown happened) does it at once. + await closeLeftoverTerminals(home, { keepTerminals: options.keepTerminals, forced }); return { action: "stopped", pid: instance.pid, forced, usedLifecycleRpc }; } +function assertStopOptions(options: { force?: boolean; keepTerminals?: boolean }): void { + if (options.force && options.keepTerminals) { + throw new DaemonInstanceError( + "INVALID_STOP_OPTIONS", + "--force kills terminals; it cannot be combined with --keep-terminals.", + ); + } +} + +async function closeLeftoverTerminals( + home: string, + options: { keepTerminals?: boolean; forced: boolean }, +): Promise { + if (options.keepTerminals) return; + await reapTerminalWorkers({ paseoHome: home, gracefulMs: options.forced ? 0 : undefined }); +} + export async function startDaemonInstance(input: { home: string; command: string; diff --git a/packages/server/src/server/daemon-worker.ts b/packages/server/src/server/daemon-worker.ts index bc5acbc404..8af60cd7bc 100644 --- a/packages/server/src/server/daemon-worker.ts +++ b/packages/server/src/server/daemon-worker.ts @@ -1,5 +1,6 @@ import { appendFileSync, mkdirSync } from "node:fs"; import path from "node:path"; +import { initializeEnvironmentProxy } from "./network/index.js"; import { createPaseoDaemon, formatListenTarget } from "./bootstrap.js"; import { loadConfig } from "./config.js"; import { resolvePaseoHome } from "./paseo-home.js"; @@ -13,6 +14,7 @@ type SupervisorLifecycleMessage = | { type: "paseo:shutdown"; reason: string; + keepTerminals: boolean; } | { type: "paseo:ready"; @@ -22,6 +24,7 @@ type SupervisorLifecycleMessage = | { type: "paseo:restart"; reason?: string; + keepTerminals: boolean; }; interface BootstrapResult { @@ -130,6 +133,11 @@ function applyCliFlagOverrides(config: ReturnType): void { async function main() { const { paseoHome, logger, config } = bootstrapFromEnvironment(); + for (const variable of initializeEnvironmentProxy()) { + writeWorkerLifecycleLog(paseoHome, "Ignoring invalid or unsupported HTTP proxy variable", { + variable, + }); + } let daemon: Awaited> | null = null; let shutdownPromise: Promise | null = null; let exitHookInstalled = false; @@ -151,12 +159,15 @@ async function main() { options?: { reason?: string; successExitCode?: number; + keepTerminals?: boolean; }, ) => { const reason = options?.reason ?? `worker_received_${signal}`; + // Signals mean "stop and close terminals"; only an explicit keep request keeps them. + const keepTerminals = options?.keepTerminals === true; if (!shutdownPromise) { logger.info( - { signal, reason, ...getProcessDiagnostics() }, + { signal, reason, keepTerminals, ...getProcessDiagnostics() }, `${signal} received, shutting down gracefully...`, ); @@ -175,7 +186,7 @@ async function main() { clearTimeout(forceExit); return 1; } - await daemon.stop(); + await daemon.stop({ keepTerminals }); clearTimeout(forceExit); logger.info("Server closed"); return options?.successExitCode ?? 0; @@ -209,36 +220,53 @@ async function main() { }; const handleLifecycleIntent = (intent: DaemonLifecycleIntent) => { + const fields = { + clientId: intent.clientId, + requestId: intent.requestId, + reason: intent.reason, + keepTerminals: intent.keepTerminals, + }; if (intent.type === "shutdown") { - logger.warn( - { clientId: intent.clientId, requestId: intent.requestId, reason: intent.reason }, - "Shutdown requested via websocket", - ); - if (sendSupervisorLifecycleMessage({ type: "paseo:shutdown", reason: intent.reason })) { + logger.warn(fields, "Shutdown requested via websocket"); + const sent = sendSupervisorLifecycleMessage({ + type: "paseo:shutdown", + reason: intent.reason, + keepTerminals: intent.keepTerminals, + }); + recordLifecycleIntentDispatched(intent.type, fields); + if (sent) { return; } - beginShutdown("shutdown lifecycle intent", { reason: intent.reason }); + beginShutdown("shutdown lifecycle intent", { + reason: intent.reason, + keepTerminals: intent.keepTerminals, + }); return; } - logger.warn( - { clientId: intent.clientId, requestId: intent.requestId, reason: intent.reason }, - "Restart requested via websocket", - ); - if ( - sendSupervisorLifecycleMessage({ - type: "paseo:restart", - ...(intent.reason ? { reason: intent.reason } : {}), - }) - ) { + logger.warn(fields, "Restart requested via websocket"); + const sent = sendSupervisorLifecycleMessage({ + type: "paseo:restart", + ...(intent.reason ? { reason: intent.reason } : {}), + keepTerminals: intent.keepTerminals, + }); + recordLifecycleIntentDispatched(intent.type, fields); + if (sent) { return; } beginShutdown("restart lifecycle intent", { reason: intent.reason, successExitCode: 0, + keepTerminals: intent.keepTerminals, }); }; + // Written straight to daemon.log: the pino stream goes through the supervisor's pipe, which + // a paused or busy supervisor does not drain. Tests synchronize on this line. + const recordLifecycleIntentDispatched = (type: string, fields: Record) => { + writeWorkerLifecycleLog(paseoHome, "Lifecycle intent dispatched", { type, ...fields }); + }; + const installSupervisorLivenessGuard = () => { if (typeof process.send !== "function") { return; @@ -278,9 +306,10 @@ async function main() { return; } if (type === "paseo:graceful-shutdown") { - const reason = (message as { reason?: unknown }).reason; + const { reason, keepTerminals } = message as { reason?: unknown; keepTerminals?: unknown }; beginShutdown("Supervisor shutdown request", { reason: typeof reason === "string" ? reason : "supervisor_requested_shutdown", + keepTerminals: keepTerminals === true, }); } }); diff --git a/packages/server/src/server/hub/execution-session.websocket.test.ts b/packages/server/src/server/hub/execution-session.websocket.test.ts index 88f376b3ba..266c55e196 100644 --- a/packages/server/src/server/hub/execution-session.websocket.test.ts +++ b/packages/server/src/server/hub/execution-session.websocket.test.ts @@ -248,7 +248,7 @@ test("ordinary Hub requests survive daemon restart and restore an archived works }), ).toMatchObject({ payload: { agentId, accepted: true } }); expect(hub.providerPromptTexts().filter((text) => text === "follow up")).toHaveLength(1); -}, 20_000); +}); test("Hub completes the standard hello before rejecting a second hello", async () => { const hub = await launchRelationship(); diff --git a/packages/server/src/server/hub/relationship-remote.ts b/packages/server/src/server/hub/relationship-remote.ts index 9c6f88a63d..6427b71fa6 100644 --- a/packages/server/src/server/hub/relationship-remote.ts +++ b/packages/server/src/server/hub/relationship-remote.ts @@ -1,5 +1,6 @@ import { WebSocket } from "ws"; import { z } from "zod"; +import { webSocketProxyAgent } from "../network/index.js"; import type { WebSocketLike } from "../websocket-server.js"; const SOCKET_PING_INTERVAL_MS = 10_000; @@ -166,6 +167,7 @@ export class DirectHubRelationshipRemote implements HubRelationshipRemote { openSocket(input: HubSocketCredentials, events: HubSocketEvents): HubSocketConnection { let sessionProtocol: "legacy" | "session-v1" = "legacy"; const socket = new WebSocket(input.webSocketUrl, { + agent: webSocketProxyAgent(input.webSocketUrl), handshakeTimeout: this.requestTimeoutMs, headers: { authorization: `Bearer ${input.credential}`, diff --git a/packages/server/src/server/managed-processes/managed-processes.test.ts b/packages/server/src/server/managed-processes/managed-processes.test.ts index e247db027f..b4be4d16bd 100644 --- a/packages/server/src/server/managed-processes/managed-processes.test.ts +++ b/packages/server/src/server/managed-processes/managed-processes.test.ts @@ -12,6 +12,7 @@ import { type ManagedProcessInspection, type ManagedProcessSnapshot, type ManagedProcessTable, + windowsPowerShellPath, } from "./managed-processes.js"; import { spawnProcess } from "../../utils/spawn.js"; import { @@ -333,7 +334,7 @@ describe("system managed process table", () => { }); expect(commandRunner.commands).toEqual([ { - command: "powershell.exe", + command: windowsPowerShellPath(), args: [ "-NoProfile", "-NonInteractive", @@ -345,6 +346,17 @@ describe("system managed process table", () => { }); }); +describe("windowsPowerShellPath", () => { + test("names Windows PowerShell under SystemRoot, whatever PATH holds", () => { + expect(windowsPowerShellPath({ SystemRoot: "D:\\Win", PATH: "" })).toBe( + "D:\\Win\\System32\\WindowsPowerShell\\v1.0\\powershell.exe", + ); + expect(windowsPowerShellPath({})).toBe( + "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe", + ); + }); +}); + class FakeProcessTable implements ManagedProcessTable { private readonly snapshots: Map; private readonly errorPids: Set; diff --git a/packages/server/src/server/managed-processes/managed-processes.ts b/packages/server/src/server/managed-processes/managed-processes.ts index 0031080c67..43c1b3c810 100644 --- a/packages/server/src/server/managed-processes/managed-processes.ts +++ b/packages/server/src/server/managed-processes/managed-processes.ts @@ -7,6 +7,20 @@ import { writeJsonFileAtomic } from "../atomic-file.js"; import { execCommand } from "../../utils/spawn.js"; import type { ProcessTerminator, TreeKillTarget } from "../../utils/tree-kill.js"; +/** + * Windows PowerShell by its install path. Process identity must not depend on the caller's + * PATH: a daemon or terminal worker can run with a PATH that does not reach System32. + */ +export function windowsPowerShellPath(env: NodeJS.ProcessEnv = process.env): string { + return path.win32.join( + env.SystemRoot ?? env.SYSTEMROOT ?? "C:\\Windows", + "System32", + "WindowsPowerShell", + "v1.0", + "powershell.exe", + ); +} + const MANAGED_PROCESS_GRACEFUL_SHUTDOWN_TIMEOUT_MS = 5_000; const MANAGED_PROCESS_FORCE_SHUTDOWN_TIMEOUT_MS = 1_000; const MANAGED_PROCESS_EXIT_POLL_INTERVAL_MS = 50; @@ -183,7 +197,7 @@ class SystemManagedProcessTable implements ManagedProcessTable { `$process = Get-CimInstance Win32_Process -Filter 'ProcessId = ${pid}';`, "if ($process) { $process | Select-Object ProcessId,CommandLine,CreationDate | ConvertTo-Json -Compress }", ].join(" "); - const { stdout } = await this.commandRunner.exec("powershell.exe", [ + const { stdout } = await this.commandRunner.exec(windowsPowerShellPath(), [ "-NoProfile", "-NonInteractive", "-Command", diff --git a/packages/server/src/server/network/index.ts b/packages/server/src/server/network/index.ts new file mode 100644 index 0000000000..46565d801a --- /dev/null +++ b/packages/server/src/server/network/index.ts @@ -0,0 +1,116 @@ +import type { Agent } from "node:http"; +import { EnvHttpProxyAgent, Pool, setGlobalDispatcher } from "undici"; +import { HttpsProxyAgent } from "https-proxy-agent"; + +interface ProxyEnvironment { + httpProxy: string; + httpsProxy: string; + noProxy: string; +} + +let environment = readEnvironment(process.env, process.platform).environment; + +function readEnvironment( + env: NodeJS.ProcessEnv, + platform: NodeJS.Platform, +): { + environment: ProxyEnvironment; + ignored: string[]; +} { + // process.env lookups are case-insensitive on Windows. Read each actual entry once. + const values = new Map( + Object.entries(env).map(([name, value]) => [ + platform === "win32" ? name.toLowerCase() : name, + value, + ]), + ); + const ignored: string[] = []; + function proxy(variable: string): string | undefined { + const value = values.get(variable); + if (value === undefined) return undefined; + if (!value.trim()) return undefined; + try { + const url = new URL(value.includes("://") ? value : `http://${value}`); + if (url.protocol !== "http:" && url.protocol !== "https:") + throw new Error("Unsupported proxy protocol"); + decodeURIComponent(url.username); + decodeURIComponent(url.password); + return url.href; + } catch { + ignored.push(variable); + return undefined; + } + } + const httpProxy = proxy("http_proxy") ?? proxy("HTTP_PROXY") ?? ""; + return { + environment: { + httpProxy, + httpsProxy: proxy("https_proxy") ?? proxy("HTTPS_PROXY") ?? httpProxy, + noProxy: values.get("no_proxy") ?? values.get("NO_PROXY") ?? "", + }, + ignored, + }; +} + +function bypassList(noProxy: string): string { + return noProxy.split(/[,\s]+/).includes("*") ? "*" : `${noProxy},localhost,127.0.0.1,[::1],::1`; +} + +function proxyClient(origin: URL, options: object) { + const pool = new Pool(origin, options); + if (!origin.username && !origin.password) return pool; + const credentials = `${decodeURIComponent(origin.username)}:${decodeURIComponent(origin.password)}`; + const authorization = `Basic ${Buffer.from(credentials).toString("base64")}`; + // This pool only sends CONNECT requests to this proxy, never requests to the origin. + // undici's URL auth requires both fields; HTTP Basic also permits either field to be empty. + return pool.compose( + (dispatch) => (request, handler) => + dispatch( + { + ...request, + headers: { ...request.headers, "proxy-authorization": authorization }, + }, + handler, + ), + ); +} + +/** Install once at startup; return ignored variable names for logging without exposing credentials. */ +export function initializeEnvironmentProxy( + env: NodeJS.ProcessEnv = process.env, + platform: NodeJS.Platform = process.platform, +): string[] { + const resolved = readEnvironment(env, platform); + environment = resolved.environment; + setGlobalDispatcher( + new EnvHttpProxyAgent({ + httpProxy: environment.httpProxy, + httpsProxy: environment.httpsProxy, + noProxy: bypassList(environment.noProxy), + clientFactory: proxyClient, + }), + ); + return resolved.ignored; +} + +/** ws uses Node HTTP agents rather than the fetch dispatcher. */ +export function webSocketProxyAgent(address: string): Agent | undefined { + const url = new URL(address); + const hostname = url.hostname.toLowerCase(); + const port = url.port || (url.protocol === "wss:" ? "443" : "80"); + const entries = bypassList(environment.noProxy) + .toLowerCase() + .split(/[,\s]+/); + if ( + entries.some((entry) => { + if (entry === "*") return true; + const match = entry.match(/^(.+):(\d+)$/); + if (match && Number(match[2]) !== Number(port)) return false; + const host = (match ? match[1]! : entry).replace(/^\*?\./, ""); + return host !== "" && (hostname === host || hostname.endsWith(`.${host}`)); + }) + ) + return undefined; + const proxy = url.protocol === "wss:" ? environment.httpsProxy : environment.httpProxy; + return proxy ? new HttpsProxyAgent(proxy) : undefined; +} diff --git a/packages/server/src/server/network/network.test.ts b/packages/server/src/server/network/network.test.ts new file mode 100644 index 0000000000..88e7d61aa6 --- /dev/null +++ b/packages/server/src/server/network/network.test.ts @@ -0,0 +1,341 @@ +import { fork } from "node:child_process"; +import { mkdtemp, readFile, rm } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { createServer, type Server } from "node:http"; +import { once } from "node:events"; +import { connect } from "node:net"; +import { afterEach, expect, test } from "vitest"; +import { WebSocket, WebSocketServer } from "ws"; +import { getGlobalDispatcher, setGlobalDispatcher } from "undici"; +import { initializeEnvironmentProxy, webSocketProxyAgent } from "./index.js"; +import { ConnectedHosts } from "../connected-hosts/index.js"; +const original = getGlobalDispatcher(); +const servers: Server[] = []; +afterEach(async () => { + const installed = getGlobalDispatcher(); + setGlobalDispatcher(original); + if (installed !== original) await installed.close(); + await Promise.all( + servers.splice(0).map( + (server) => + new Promise((resolve) => { + server.closeAllConnections(); + server.close(() => resolve()); + }), + ), + ); +}); +async function listen(server: Server) { + servers.push(server); + server.listen(0, "127.0.0.1"); + await once(server, "listening"); + const address = server.address(); + if (!address || typeof address === "string") throw new Error("Missing address"); + return `127.0.0.1:${address.port}`; +} +async function proxy() { + const tunnels: string[] = []; + const server = createServer(); + server.on("connect", (request, socket) => { + tunnels.push(request.url!); + socket.end("HTTP/1.1 502 Bad Gateway\r\nConnection: close\r\n\r\n"); + }); + return { url: `http://${await listen(server)}`, tunnels }; +} +test("loopback fetch and WebSockets bypass HTTP_PROXY with empty NO_PROXY", async () => { + const recorder = await proxy(); + initializeEnvironmentProxy({ HTTP_PROXY: recorder.url, NO_PROXY: "" }); + const server = createServer((_, response) => response.end("direct")); + const sockets = new WebSocketServer({ server }); + sockets.on("connection", (socket) => socket.send("direct")); + const address = await listen(server); + expect(await (await fetch(`http://${address}`)).text()).toBe("direct"); + const socket = new WebSocket(`ws://${address}`, { + agent: webSocketProxyAgent(`ws://${address}`), + }); + expect((await once(socket, "message"))[0].toString()).toBe("direct"); + socket.close(); + await once(socket, "close"); + await new Promise((resolve) => sockets.close(() => resolve())); + for (const host of ["localhost", "127.0.0.1", "[::1]"]) + expect(webSocketProxyAgent(`wss://${host}:1234`)).toBeUndefined(); + expect(recorder.tunnels).toEqual([]); +}); +test("fetch and WebSockets send non-loopback traffic through CONNECT", async () => { + const recorder = await proxy(); + initializeEnvironmentProxy({ http_proxy: recorder.url }); + await expect( + fetch("https://vendor.invalid/", { signal: AbortSignal.timeout(500) }), + ).rejects.toThrow(); + const socket = new WebSocket("wss://vendor.invalid", { + agent: webSocketProxyAgent("wss://vendor.invalid"), + }); + await once(socket, "error"); + expect( + recorder.tunnels.filter((host) => host === "vendor.invalid:443").length, + ).toBeGreaterThanOrEqual(2); +}); +test("NO_PROXY and absent variables keep matching WebSockets direct", async () => { + const recorder = await proxy(); + initializeEnvironmentProxy({ + HTTPS_PROXY: recorder.url, + NO_PROXY: "vendor.invalid,.example.invalid:443", + }); + expect(webSocketProxyAgent("wss://vendor.invalid")).toBeUndefined(); + await expect( + fetch("https://vendor.invalid/", { signal: AbortSignal.timeout(500) }), + ).rejects.toThrow(); + expect(webSocketProxyAgent("wss://sub.example.invalid")).toBeUndefined(); + expect(webSocketProxyAgent("wss://example.invalid:444")).toBeDefined(); + initializeEnvironmentProxy({ HTTP_PROXY: recorder.url, no_proxy: "*" }); + expect(webSocketProxyAgent("ws://vendor.invalid")).toBeUndefined(); + initializeEnvironmentProxy({}); + expect(webSocketProxyAgent("wss://vendor.invalid")).toBeUndefined(); + const address = await listen(createServer((_, response) => response.end("direct"))); + expect(await (await fetch(`http://${address}`)).text()).toBe("direct"); + expect(recorder.tunnels).toEqual([]); +}); + +test.each(["127.0.0.1", "localhost"])( + "scheme-less %s proxies work for fetch and WebSockets", + async (host) => { + const recorder = await proxy(); + const address = new URL(recorder.url); + initializeEnvironmentProxy({ https_proxy: `${host}:${address.port}` }); + await expect( + fetch("https://vendor.invalid", { signal: AbortSignal.timeout(500) }), + ).rejects.toThrow(); + const socket = new WebSocket("wss://vendor.invalid", { + agent: webSocketProxyAgent("wss://vendor.invalid"), + }); + await once(socket, "error"); + expect(recorder.tunnels).toContain("vendor.invalid:443"); + }, +); + +test.each([ + "http://[", + "http://user%zz:secret@proxy.corp", + "socks5://127.0.0.1:7890", + "ftp://proxy.corp:8080", +])("ignores invalid or unsupported proxy %s without stopping startup", async (value) => { + const recorder = await proxy(); + expect(initializeEnvironmentProxy({ HTTP_PROXY: recorder.url, https_proxy: value })).toEqual([ + "https_proxy", + ]); + expect(webSocketProxyAgent("wss://vendor.invalid")).toBeDefined(); + await expect( + fetch("https://vendor.invalid", { signal: AbortSignal.timeout(500) }), + ).rejects.toThrow(); + const socket = new WebSocket("wss://vendor.invalid", { + agent: webSocketProxyAgent("wss://vendor.invalid"), + }); + await once(socket, "error"); + expect(recorder.tunnels).toEqual(["vendor.invalid:443", "vendor.invalid:443"]); +}); + +test("daemon starts with an ignored proxy and writes one redacted warning to daemon.log", async () => { + const home = await mkdtemp(path.join(os.tmpdir(), "daemon-invalid-proxy-")); + const env = Object.fromEntries( + Object.entries(process.env).filter( + ([key]) => !["http_proxy", "https_proxy"].includes(key.toLowerCase()), + ), + ); + const worker = fork(fileURLToPath(new URL("../daemon-worker.ts", import.meta.url)), [], { + execArgv: ["--import", "tsx"], + silent: true, + env: { + ...env, + PASEO_HOME: home, + HOME: home, + USERPROFILE: home, + PASEO_LISTEN: "127.0.0.1:0", + PASEO_RELAY_ENABLED: "0", + https_proxy: "socks5://private:secret@127.0.0.1:7890", + }, + }); + worker.stdout?.resume(); + let stderr = ""; + worker.stderr?.on("data", (chunk) => { + stderr += String(chunk); + }); + try { + await new Promise((resolve, reject) => { + worker.on("message", (message) => { + if ( + typeof message === "object" && + message !== null && + "type" in message && + message.type === "paseo:ready" + ) + resolve(); + }); + worker.on("exit", (code) => reject(new Error(`Worker exited ${code}: ${stderr}`))); + }); + const log = await readFile(path.join(home, "daemon.log"), "utf8"); + const warnings = log + .split("\n") + .filter((line) => line.includes("Ignoring invalid or unsupported HTTP proxy variable")); + expect(warnings).toHaveLength(1); + expect(JSON.parse(warnings[0]!).variable).toBe("https_proxy"); + expect(warnings[0]).not.toContain("secret"); + } finally { + if (worker.exitCode === null && worker.signalCode === null) { + const exited = once(worker, "exit"); + worker.kill("SIGTERM"); + await exited; + } + await rm(home, { recursive: true, force: true }); + } +}, 60_000); + +test("accepts a scheme-less corporate proxy hostname", () => { + expect(initializeEnvironmentProxy({ https_proxy: "proxy.corp:8080" })).toEqual([]); + expect(webSocketProxyAgent("wss://vendor.invalid")).toBeDefined(); +}); + +test("an ignored lowercase variable falls back to the uppercase variable", async () => { + const recorder = await proxy(); + expect( + initializeEnvironmentProxy( + { + https_proxy: "socks5://proxy.invalid", + HTTPS_PROXY: recorder.url, + }, + "linux", + ), + ).toEqual(["https_proxy"]); + await expect( + fetch("https://vendor.invalid", { signal: AbortSignal.timeout(500) }), + ).rejects.toThrow(); + const socket = new WebSocket("wss://vendor.invalid", { + agent: webSocketProxyAgent("wss://vendor.invalid"), + }); + await once(socket, "error"); + expect(recorder.tunnels).toEqual(["vendor.invalid:443", "vendor.invalid:443"]); +}); + +test("case-insensitive environment access reports a variable only once", () => { + const env = new Proxy( + { https_proxy: "socks5://127.0.0.1:7890" }, + { + get(target, key) { + return Reflect.get(target, typeof key === "string" ? key.toLowerCase() : key); + }, + }, + ); + expect(initializeEnvironmentProxy(env)).toEqual(["https_proxy"]); +}); + +test("connected-host links send remote WebSockets through the environment proxy", async () => { + const recorder = await proxy(); + initializeEnvironmentProxy({ HTTPS_PROXY: recorder.url }); + const home = await mkdtemp(path.join(os.tmpdir(), "connected-host-proxy-")); + const hosts = new ConnectedHosts(home, { serverId: "self", label: "Self" }); + try { + await hosts.add( + { connection: "wss://remote.invalid/ws" }, + { sourceId: "test", manageSources: true }, + ); + await expect.poll(() => recorder.tunnels).toContain("remote.invalid:443"); + } finally { + await hosts.close(); + await rm(home, { recursive: true, force: true }); + } +}); + +test.each(["corp.internal,*", "vendor.invalid:0443"])( + "fetch and WebSockets share NO_PROXY=%s", + async (noProxy) => { + const recorder = await proxy(); + initializeEnvironmentProxy({ HTTPS_PROXY: recorder.url, NO_PROXY: noProxy }); + expect(webSocketProxyAgent("wss://vendor.invalid")).toBeUndefined(); + await expect( + fetch("https://vendor.invalid", { signal: AbortSignal.timeout(500) }), + ).rejects.toThrow(); + expect(recorder.tunnels).toEqual([]); + }, +); + +test("Windows mixed-case environment names route and bypass both transports", async () => { + const recorder = await proxy(); + // Windows preserves spelling but treats environment names without regard to case. + initializeEnvironmentProxy({ Https_Proxy: recorder.url, No_Proxy: "other.invalid" }, "win32"); + expect(webSocketProxyAgent("wss://other.invalid")).toBeUndefined(); + await expect( + fetch("https://other.invalid", { signal: AbortSignal.timeout(500) }), + ).rejects.toThrow(); + expect(webSocketProxyAgent("wss://vendor.invalid")).toBeDefined(); + await expect( + fetch("https://vendor.invalid", { signal: AbortSignal.timeout(500) }), + ).rejects.toThrow(); + const socket = new WebSocket("wss://vendor.invalid", { + agent: webSocketProxyAgent("wss://vendor.invalid"), + }); + await once(socket, "error"); + expect(recorder.tunnels).toEqual(["vendor.invalid:443", "vendor.invalid:443"]); +}); + +test("POSIX mixed-case names do not override standard proxy names", async () => { + const recorder = await proxy(); + initializeEnvironmentProxy( + { Https_Proxy: recorder.url, HTTPS_PROXY: recorder.url, No_Proxy: "*" }, + "linux", + ); + expect(webSocketProxyAgent("wss://vendor.invalid")).toBeDefined(); + await expect( + fetch("https://vendor.invalid", { signal: AbortSignal.timeout(500) }), + ).rejects.toThrow(); + expect(recorder.tunnels).toEqual(["vendor.invalid:443"]); +}); + +test("proxy credentials stay on CONNECT and do not reach the HTTP origin", async () => { + let originAuthorization: string | undefined; + const origin = createServer((request, response) => { + originAuthorization = request.headers["proxy-authorization"]; + response.end("through proxy"); + }); + const originAddress = new URL(`http://${await listen(origin)}`); + const authorizations: (string | undefined)[] = []; + const server = createServer(); + server.on("connect", (request, socket, head) => { + authorizations.push(request.headers["proxy-authorization"]); + const upstream = connect(Number(originAddress.port), "127.0.0.1", () => { + socket.write("HTTP/1.1 200 Connection Established\r\n\r\n"); + if (head.length) upstream.write(head); + socket.pipe(upstream).pipe(socket); + }); + socket.on("error", () => upstream.destroy()); + upstream.on("error", () => socket.destroy()); + socket.on("close", () => upstream.destroy()); + }); + initializeEnvironmentProxy({ HTTP_PROXY: `http://user:@${await listen(server)}` }); + const response = await fetch("http://vendor.invalid", { signal: AbortSignal.timeout(3000) }); + expect(await response.text()).toBe("through proxy"); + expect(authorizations).toEqual([`Basic ${Buffer.from("user:").toString("base64")}`]); + expect(originAuthorization).toBeUndefined(); +}); + +test.each(["user:@", ":secret@", "user:secret@"])( + "fetch and WebSockets authenticate proxy credentials %s", + async (credentials) => { + const authorizations: (string | undefined)[] = []; + const server = createServer(); + server.on("connect", (request, socket) => { + authorizations.push(request.headers["proxy-authorization"]); + socket.end("HTTP/1.1 502 Bad Gateway\r\nConnection: close\r\n\r\n"); + }); + initializeEnvironmentProxy({ HTTPS_PROXY: `http://${credentials}${await listen(server)}` }); + await expect( + fetch("https://vendor.invalid", { signal: AbortSignal.timeout(500) }), + ).rejects.toThrow(); + const socket = new WebSocket("wss://vendor.invalid", { + agent: webSocketProxyAgent("wss://vendor.invalid"), + }); + await once(socket, "error"); + const expected = `Basic ${Buffer.from(credentials.slice(0, -1)).toString("base64")}`; + expect(authorizations).toEqual([expected, expected]); + }, +); diff --git a/packages/server/src/server/owned-subscriptions.e2e.test.ts b/packages/server/src/server/owned-subscriptions.e2e.test.ts index 68437daf70..fc73e44db4 100644 --- a/packages/server/src/server/owned-subscriptions.e2e.test.ts +++ b/packages/server/src/server/owned-subscriptions.e2e.test.ts @@ -1,7 +1,8 @@ import { MockLoadTestAgentClient } from "./agent/providers/mock-load-test-agent.js"; import { createPaseoApi } from "@getpaseo/client"; +import type { AgentManager } from "./agent/agent-manager.js"; import { execFileSync } from "node:child_process"; -import { mkdir, writeFile } from "node:fs/promises"; +import { mkdir, readFile, writeFile } from "node:fs/promises"; import path from "node:path"; import { expect, test } from "vitest"; import type { z } from "zod"; @@ -71,15 +72,18 @@ class SubscriptionPeer { async request(message: z.input): Promise { this.socket.send(JSON.stringify({ type: "session", message })); await expect - .poll(() => - this.frames.some( - (frame) => - frame.type === "session" && - "payload" in frame.message && - "requestId" in frame.message.payload && - "requestId" in message && - frame.message.payload.requestId === message.requestId, - ), + .poll( + () => + this.frames.some( + (frame) => + frame.type === "session" && + "payload" in frame.message && + "requestId" in frame.message.payload && + "requestId" in message && + frame.message.payload.requestId === message.requestId, + ), + // Diagnostics invoke external tools with their own multi-second deadlines. + { timeout: 10_000 }, ) .toBe(true); } @@ -119,6 +123,16 @@ class SubscriptionPeer { } } +function removedAgentIds(peer: SubscriptionPeer): string[] { + return peer.frames.flatMap((frame) => + frame.type === "session" && + frame.message.type === "agent_update" && + frame.message.payload.kind === "remove" + ? [frame.message.payload.agentId] + : [], + ); +} + test("a pure list reply belongs only to its source socket in a shared logical session", async () => { const daemon = await createTestPaseoDaemon({ mcpEnabled: false }); const peers: SubscriptionPeer[] = []; @@ -225,6 +239,96 @@ test("combined filtered agent lists create independent server-owned observations } }); +test.each([ + { + state: "live", + prepare: async (_manager: AgentManager, _agentId: string) => {}, + }, + { + state: "stored-only", + prepare: (manager: AgentManager, agentId: string) => manager.closeAgent(agentId), + }, +])( + "$state agent deletion reaches directory observers across logical sessions without broadcasting its reply", + async ({ prepare }) => { + const daemon = await createTestPaseoDaemon({ mcpEnabled: false }); + const admin = new DaemonClient({ + url: `ws://127.0.0.1:${daemon.port}/ws`, + appVersion: "0.8.0", + }); + const peers: SubscriptionPeer[] = []; + try { + await admin.connect(); + const workspace = ( + await admin.createWorkspace({ source: { kind: "directory", path: daemon.staticDir } }) + ).workspace; + if (!workspace) throw new Error("Workspace creation failed"); + const removed = await admin.createAgent({ + provider: "codex", + cwd: daemon.staticDir, + workspaceId: workspace.id, + }); + const survivor = await admin.createAgent({ + provider: "codex", + cwd: daemon.staticDir, + workspaceId: workspace.id, + }); + const sentinel = path.join(daemon.staticDir, "keep-project-file.txt"); + await writeFile(sentinel, "keep this project file\n"); + await prepare(daemon.daemon.agentManager, removed.id); + const requester = await SubscriptionPeer.connect(daemon.port, "deletion-origin"); + const sibling = await SubscriptionPeer.connect(daemon.port, "deletion-origin"); + const observer = await SubscriptionPeer.connect(daemon.port, "deletion-observer"); + const legacy = await SubscriptionPeer.connect(daemon.port, "deletion-legacy", { + owned_subscriptions: false, + }); + peers.push(requester, sibling, observer, legacy); + for (const [index, peer] of peers.entries()) { + await peer.request({ + type: "fetch_agents_request", + requestId: `directory-${index}`, + subscribe: {}, + }); + const entries = peer.frames.flatMap((frame) => + frame.type === "session" && frame.message.type === "fetch_agents_response" + ? frame.message.payload.entries.map((entry) => entry.agent.id) + : [], + ); + expect(entries.sort()).toEqual([removed.id, survivor.id].sort()); + peer.frames.length = 0; + } + await requester.request({ + type: "delete_agent_request", + requestId: "delete-observed-agent", + agentId: removed.id, + }); + await expect + .poll(() => peers.map(removedAgentIds)) + .toEqual([[removed.id], [removed.id], [removed.id], [removed.id]]); + const replies = peers.map((peer) => + peer.frames.flatMap((frame) => + frame.type === "session" && frame.message.type === "agent_deleted" + ? [frame.message.payload] + : [], + ), + ); + expect(replies).toEqual([ + [{ agentId: removed.id, requestId: "delete-observed-agent" }], + [], + [], + [], + ]); + expect(await daemon.daemon.agentStorage.get(removed.id)).toBeNull(); + expect((await daemon.daemon.agentStorage.get(survivor.id))?.id).toBe(survivor.id); + expect(await readFile(sentinel, "utf8")).toBe("keep this project file\n"); + } finally { + for (const peer of peers) peer.close(); + await admin.close(); + await daemon.close(); + } + }, +); + test("workspace filters and identical queries coexist until their own release", async () => { const daemon = await createTestPaseoDaemon({ mcpEnabled: false }); const admin = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws`, appVersion: "0.8.0" }); @@ -679,7 +783,8 @@ test("same-workspace terminal directory observers do not share a teardown slot", peer.frames.length = 0; const result = await admin.createTerminal(daemon.staticDir, "Observed terminal", undefined, { workspaceId: workspace.id, - command: "/bin/cat", + command: process.execPath, + args: ["-e", "process.stdin.on('data', data => process.stdout.write(data))"], }); expect(result.error).toBe(null); await expect @@ -717,85 +822,100 @@ test("same-workspace terminal directory observers do not share a teardown slot", } }); -test("terminal output has separate server IDs and binary slots, including in a shared session", async () => { - const daemon = await createTestPaseoDaemon({ mcpEnabled: false }); - const admin = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws`, appVersion: "0.8.0" }); - const peers: SubscriptionPeer[] = []; - try { - await admin.connect(); - const workspace = ( - await admin.createWorkspace({ source: { kind: "directory", path: daemon.staticDir } }) - ).workspace!; - const result = await admin.createTerminal(daemon.staticDir, "Output ownership", undefined, { - workspaceId: workspace.id, - command: "/bin/cat", +test.each([false, true])( + "terminal output has separate server IDs and binary slots, including in a shared session (chunked=%s)", + async (chunked) => { + const daemon = await createTestPaseoDaemon({ mcpEnabled: false }); + const admin = new DaemonClient({ + url: `ws://127.0.0.1:${daemon.port}/ws`, + appVersion: "0.8.0", }); - expect(result.error).toBe(null); - const idle = await SubscriptionPeer.connect(daemon.port, "terminal-output-session"); - peers.push(idle); - const peer = await SubscriptionPeer.connect(daemon.port, "terminal-output-session"); - peers.push(peer); - for (const requestId of ["output-a", "output-b"]) { - await peer.request({ - type: "subscribe_terminal_request", - requestId, - terminalId: result.terminal!.id, + const peers: SubscriptionPeer[] = []; + try { + await admin.connect(); + const workspace = ( + await admin.createWorkspace({ source: { kind: "directory", path: daemon.staticDir } }) + ).workspace!; + const result = await admin.createTerminal(daemon.staticDir, "Output ownership", undefined, { + workspaceId: workspace.id, + command: process.execPath, + args: ["-e", "process.stdin.on('data', data => process.stdout.write(data))"], }); - } - const replies = peer.frames.flatMap((frame) => - frame.type === "session" && - frame.message.type === "subscribe_terminal_response" && - frame.message.payload.error === null - ? [frame.message.payload] - : [], - ); - expect(replies).toHaveLength(2); - const ids = replies.map( - (reply) => (reply as typeof reply & { subscriptionId: string }).subscriptionId, - ); - expect(ids.every((id) => typeof id === "string")).toBe(true); - expect(ids[0]).not.toBe(ids[1]); - expect(replies[0].slot).not.toBe(replies[1].slot); - await expect - .poll(() => - peer.binaryFrames - .map(decodeTerminalStreamFrame) - .filter((frame) => frame?.opcode === TerminalStreamOpcode.Snapshot) - .map((frame) => frame!.slot), - ) - .toEqual(expect.arrayContaining(replies.map((reply) => reply.slot))); - expect(idle.binaryFrames).toEqual([]); - await peer.request({ - type: "subscription.release.request", - requestId: "release-output-a", - subscriptionId: ids[0], - }); - peer.binaryFrames.length = 0; - admin.sendTerminalInput(result.terminal!.id, { type: "input", data: "remaining-observer\n" }); - await expect - .poll( - () => + expect(result.error).toBe(null); + const idle = await SubscriptionPeer.connect(daemon.port, "terminal-output-session", { + terminal_chunked_replay: chunked, + }); + peers.push(idle); + const peer = await SubscriptionPeer.connect(daemon.port, "terminal-output-session", { + terminal_chunked_replay: chunked, + }); + peers.push(peer); + for (const requestId of ["output-a", "output-b"]) { + await peer.request({ + type: "subscribe_terminal_request", + requestId, + terminalId: result.terminal!.id, + }); + } + const replies = peer.frames.flatMap((frame) => + frame.type === "session" && + frame.message.type === "subscribe_terminal_response" && + frame.message.payload.error === null + ? [frame.message.payload] + : [], + ); + expect(replies).toHaveLength(2); + const ids = replies.map( + (reply) => (reply as typeof reply & { subscriptionId: string }).subscriptionId, + ); + expect(ids.every((id) => typeof id === "string")).toBe(true); + expect(ids[0]).not.toBe(ids[1]); + expect(replies[0].slot).not.toBe(replies[1].slot); + await expect + .poll(() => peer.binaryFrames .map(decodeTerminalStreamFrame) - .filter((frame) => frame?.opcode === TerminalStreamOpcode.Output) - .map((frame) => Buffer.from(frame!.payload).toString()) - .join(""), - { timeout: 5000 }, - ) - .toContain("remaining-observer"); - expect( - peer.binaryFrames - .map(decodeTerminalStreamFrame) - .every((frame) => frame?.slot === replies[1].slot), - ).toBe(true); - expect(idle.binaryFrames).toEqual([]); - await admin.killTerminal(result.terminal!.id); - } finally { - for (const peer of peers) peer.close(); - await admin.close(); - await daemon.close(); - } -}); + .filter( + (frame) => + frame?.opcode === + (chunked ? TerminalStreamOpcode.ReplayEnd : TerminalStreamOpcode.Restore), + ) + .map((frame) => frame!.slot), + ) + .toEqual(expect.arrayContaining(replies.map((reply) => reply.slot))); + expect(idle.binaryFrames).toEqual([]); + await peer.request({ + type: "subscription.release.request", + requestId: "release-output-a", + subscriptionId: ids[0], + }); + peer.binaryFrames.length = 0; + admin.sendTerminalInput(result.terminal!.id, { type: "input", data: "remaining-observer\n" }); + await expect + .poll( + () => + peer.binaryFrames + .map(decodeTerminalStreamFrame) + .filter((frame) => frame?.opcode === TerminalStreamOpcode.Output) + .map((frame) => Buffer.from(frame!.payload).toString()) + .join(""), + { timeout: 5000 }, + ) + .toContain("remaining-observer"); + expect( + peer.binaryFrames + .map(decodeTerminalStreamFrame) + .every((frame) => frame?.slot === replies[1].slot), + ).toBe(true); + expect(idle.binaryFrames).toEqual([]); + await admin.killTerminal(result.terminal!.id); + } finally { + for (const peer of peers) peer.close(); + await admin.close(); + await daemon.close(); + } + }, +); test("a modern connection and pure reads retain no client observation producers", async () => { const daemon = await createTestPaseoDaemon({ mcpEnabled: false }); @@ -1423,7 +1543,7 @@ test("request outcomes for import and attention reach only their requesting sock }); const requester = await SubscriptionPeer.connect(daemon.port, "reply-shared"); const sibling = await SubscriptionPeer.connect(daemon.port, "reply-shared"); - const admin = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` }); + const admin = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws`, appVersion: "0.8.0" }); try { await admin.connect(); await requester.request({ @@ -1462,7 +1582,7 @@ test("request outcomes for import and attention reach only their requesting sock }), ); const agent = await admin.createAgent({ - provider: "codex", + provider: "mock", cwd: daemon.staticDir, title: "Attention", }); diff --git a/packages/server/src/server/paseo-worktree-service.ts b/packages/server/src/server/paseo-worktree-service.ts index 4080efd580..1205554d4a 100644 --- a/packages/server/src/server/paseo-worktree-service.ts +++ b/packages/server/src/server/paseo-worktree-service.ts @@ -1,3 +1,4 @@ +import type { PluginLifecycle } from "./plugins/lifecycle/index.js"; import { stat } from "node:fs/promises"; import { resolve } from "node:path"; @@ -59,6 +60,7 @@ export interface AttemptFirstAgentBranchAutoNameResult { } export interface CreatePaseoWorktreeDeps extends CreateWorktreeCoreDeps { + lifecycle?: Pick; workspaceGitService: WorkspaceGitService; workspaceProvisioning: Pick; } @@ -77,6 +79,15 @@ async function createPaseoWorktreeWithPriority( const workspaceCwdPlan = await planWorkspaceCwdForWorktree(input.cwd, deps.workspaceGitService); const createdWorktree = await createWorktreeCore(input, deps); try { + if (createdWorktree.created) { + await deps.lifecycle?.wait("worktree.create.after", { + worktree: { + path: createdWorktree.worktree.worktreePath, + branch: createdWorktree.worktree.branchName, + sourceCheckout: workspaceCwdPlan.sourceCheckout, + }, + }); + } await maybeMarkFirstAgentBranchAutoNameEligible({ createdWorktree }); const workspaceCwd = mapWorkspaceRelativeCwdToWorktree({ relativeWorkspaceCwd: workspaceCwdPlan.relativeWorkspaceCwd, @@ -155,7 +166,7 @@ async function isDirectory(targetPath: string): Promise { async function planWorkspaceCwdForWorktree( inputCwd: string, workspaceGitService: Pick, -): Promise<{ inputCwd: string; relativeWorkspaceCwd: string }> { +): Promise<{ inputCwd: string; relativeWorkspaceCwd: string; sourceCheckout: string }> { const normalizedInputCwd = resolve(inputCwd); const sourceCheckout = await workspaceGitService.getCheckout(normalizedInputCwd); const sourceWorktreePath = sourceCheckout.worktreeRoot ?? normalizedInputCwd; @@ -163,7 +174,7 @@ async function planWorkspaceCwdForWorktree( if (relativeWorkspaceCwd === null) { throw new Error(`Workspace cwd is outside its source worktree: ${normalizedInputCwd}`); } - return { inputCwd: normalizedInputCwd, relativeWorkspaceCwd }; + return { inputCwd: normalizedInputCwd, relativeWorkspaceCwd, sourceCheckout: sourceWorktreePath }; } export async function attemptFirstAgentBranchAutoName(options: { diff --git a/packages/server/src/server/persisted-config.ts b/packages/server/src/server/persisted-config.ts index 51bfb3d3a4..3138ec9132 100644 --- a/packages/server/src/server/persisted-config.ts +++ b/packages/server/src/server/persisted-config.ts @@ -259,6 +259,7 @@ export const PersistedConfigSchema = z }) .passthrough() .optional(), + usage: z.object({ enabled: z.boolean().optional() }).optional(), browserTools: z .object({ enabled: z.boolean().optional(), @@ -348,6 +349,8 @@ export const PersistedConfigSchema = z .object({ providers: z.preprocess(normalizeAgentProviders, ProviderOverridesSchema).optional(), idleRuntimeCleanup: z.boolean().optional(), + resumeOnStartup: z.boolean().optional(), + resumePrompt: z.string().optional(), catalogRefreshTimeoutMs: z.number().int().positive().max(2_147_483_647).optional(), metadataGeneration: AgentMetadataGenerationSchema.optional(), skills: z.object({ selection: AgentSkillSelectionSchema.optional() }).strict().optional(), diff --git a/packages/server/src/server/pid-lock.ts b/packages/server/src/server/pid-lock.ts index 314b44ea47..6f3e7135d9 100644 --- a/packages/server/src/server/pid-lock.ts +++ b/packages/server/src/server/pid-lock.ts @@ -30,13 +30,16 @@ function isErrnoException(err: unknown): err is NodeJS.ErrnoException { return err instanceof Error && "code" in err; } +// The field is assigned explicitly rather than declared as a constructor parameter property: +// the terminal worker loads this module under --experimental-strip-types, which cannot emit +// the assignment a parameter property implies. export class PidLockError extends Error { - constructor( - message: string, - public readonly existingLock?: PidLockInfo, - ) { + readonly existingLock?: PidLockInfo; + + constructor(message: string, existingLock?: PidLockInfo) { super(message); this.name = "PidLockError"; + this.existingLock = existingLock; } } @@ -69,7 +72,7 @@ let cachedBootId: string | null | undefined; // Linux names each boot. The wall-clock boot instant is not enough there: a VM paused while // its host sleeps keeps its uptime, so after it resumes the instant lands after locks its // running supervisor wrote. -function currentBootId(): string | null { +export function currentBootId(): string | null { if (cachedBootId === undefined) { try { cachedBootId = readFileSync("/proc/sys/kernel/random/boot_id", "utf-8").trim() || null; @@ -80,10 +83,17 @@ function currentBootId(): string | null { return cachedBootId; } -function writtenDuringThisBoot(lock: PidLockInfo): boolean { +/** + * Whether a record stamped with `startedAt` (and, on Linux, `bootId`) was written during the + * current boot. Daemon locks and terminal worker records share this rule. + */ +export function writtenDuringThisBoot(stamp: { + startedAt: string; + bootId?: string | null; +}): boolean { const thisBoot = currentBootId(); - if (lock.bootId && thisBoot) return lock.bootId === thisBoot; - return !precedesThisBoot(lock.startedAt); + if (stamp.bootId && thisBoot) return stamp.bootId === thisBoot; + return !precedesThisBoot(stamp.startedAt); } /** diff --git a/packages/server/src/server/plugins/agent-configuration.e2e.test.ts b/packages/server/src/server/plugins/agent-configuration.e2e.test.ts index 3228306297..a3e4e273a4 100644 --- a/packages/server/src/server/plugins/agent-configuration.e2e.test.ts +++ b/packages/server/src/server/plugins/agent-configuration.e2e.test.ts @@ -1,20 +1,32 @@ -import { mkdtemp, rm } from "node:fs/promises"; +import { mkdtemp, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { expect, test } from "vitest"; import { DaemonClient } from "../test-utils/daemon-client.js"; +import type { AgentClient, AgentSessionConfig } from "../agent/agent-sdk-types.js"; import { createTestAgentClient } from "../test-utils/fake-agent-client.js"; import { createTestPaseoDaemon } from "../test-utils/paseo-daemon.js"; -test("the configuration example adds MCP servers and overrides Codex options while preserving other configuration", async () => { +test("the configuration example saves Codex options and injects launch-only MCP servers while preserving other configuration", async () => { const directory = await mkdtemp(path.join(tmpdir(), "paseo-config-example-")); + const launches: AgentSessionConfig[] = []; const daemon = await createTestPaseoDaemon({ - daemonVersion: "0.8.0", - agentClients: { codex: createTestAgentClient("codex", { supportsMcpServers: true }) }, + daemonVersion: "0.14.0-beta.1", + agentClients: { + codex: createTestAgentClient("codex", { + supportsMcpServers: true, + beforeCreateSession: async (config) => { + launches.push(config); + }, + }), + }, mcpEnabled: false, }); - const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws`, appVersion: "0.8.0" }); + const client = new DaemonClient({ + url: `ws://127.0.0.1:${daemon.port}/ws`, + appVersion: "0.14.0-beta.1", + }); try { await client.connect(); await client.fetchAgents({ subscribe: {} }); @@ -44,9 +56,15 @@ test("the configuration example adds MCP servers and overrides Codex options whi }, mcpServers: { existing: { type: "http", url: "https://existing.example.com/mcp" }, - company: { type: "http", url: "https://tools.example.com/mcp" }, }, }); + expect(daemon.daemon.agentManager.getAgent(agent.id)!.config.mcpServers).toEqual({ + existing: { type: "http", url: "https://existing.example.com/mcp" }, + }); + expect(launches[0].mcpServers).toEqual({ + existing: { type: "http", url: "https://existing.example.com/mcp" }, + company: { type: "http", url: "https://tools.example.com/mcp" }, + }); await client.archiveAgent(agent.id); } finally { await client.close(); @@ -54,3 +72,71 @@ test("the configuration example adds MCP servers and overrides Codex options whi await rm(directory, { recursive: true, force: true }); } }, 60_000); + +test("session-open entrypoint contributions are optional and rederived for existing agents", async () => { + const directory = await mkdtemp(path.join(tmpdir(), "paseo-entrypoint-hook-")); + const launches: { provider: string; env?: Record }[] = []; + function recordingProvider(provider: "claude" | "codex"): AgentClient { + const inner = createTestAgentClient(provider); + return { + provider: inner.provider, + capabilities: inner.capabilities, + isAvailable: () => inner.isAvailable(), + fetchCatalog: (options) => inner.fetchCatalog(options), + createSession: async (...args: Parameters) => { + launches.push({ provider, env: args[1]?.env }); + return inner.createSession(...args); + }, + resumeSession: async (...args: Parameters) => { + launches.push({ provider, env: args[2]?.env }); + return inner.resumeSession(...args); + }, + }; + } + const daemon = await createTestPaseoDaemon({ + daemonVersion: "0.14.0-beta.2", + agentClients: { claude: recordingProvider("claude"), codex: recordingProvider("codex") }, + mcpEnabled: false, + }); + const client = new DaemonClient({ + url: `ws://127.0.0.1:${daemon.port}/ws`, + appVersion: "0.14.0-beta.2", + }); + try { + await writeFile( + path.join(directory, "paseo-plugin.json"), + JSON.stringify({ id: "entrypoint-test", requirements: { paseo: ">=0.14.0-beta.2" } }), + ); + await writeFile( + path.join(directory, "index.server.ts"), + ` +export default function contribute(server) { + return server.before("agent.session_open", ({ request }) => { + if (request.provider !== "claude") return; + return { ...request, env: { ...request.env, CLAUDE_CODE_ENTRYPOINT: "custom-client" } }; + }); +} +`, + ); + await client.connect(); + await client.fetchAgents({ subscribe: {} }); + const existing = await client.createAgent({ provider: "claude", cwd: directory }); + expect(launches.at(-1)?.env?.CLAUDE_CODE_ENTRYPOINT).toBeUndefined(); + await client.patchDaemonConfig({ pluginsEnabled: true }); + await client.installDirectoryPlugin(directory); + await daemon.daemon.agentManager.reloadAgentSession(existing.id); + expect(launches.at(-1)?.env?.CLAUDE_CODE_ENTRYPOINT).toBe("custom-client"); + await client.createAgent({ provider: "claude", cwd: directory }); + expect(launches.at(-1)?.env?.CLAUDE_CODE_ENTRYPOINT).toBe("custom-client"); + await client.createAgent({ provider: "codex", cwd: directory }); + expect(launches.at(-1)).toMatchObject({ provider: "codex" }); + expect(launches.at(-1)?.env?.CLAUDE_CODE_ENTRYPOINT).toBeUndefined(); + await client.disablePlugin("entrypoint-test"); + await daemon.daemon.agentManager.reloadAgentSession(existing.id); + expect(launches.at(-1)?.env?.CLAUDE_CODE_ENTRYPOINT).toBeUndefined(); + } finally { + await client.close(); + await daemon.close(); + await rm(directory, { recursive: true, force: true }); + } +}, 60_000); diff --git a/packages/server/src/server/plugins/agent-tools.e2e.test.ts b/packages/server/src/server/plugins/agent-tools.e2e.test.ts index 14629aa15e..b652c569fe 100644 --- a/packages/server/src/server/plugins/agent-tools.e2e.test.ts +++ b/packages/server/src/server/plugins/agent-tools.e2e.test.ts @@ -1,5 +1,5 @@ import { fileURLToPath } from "node:url"; -import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises"; +import { mkdtemp, mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import { expect, test } from "vitest"; @@ -11,6 +11,7 @@ import { type TestAgentClientOptions, } from "../test-utils/fake-agent-client.js"; import { createTestPaseoDaemon } from "../test-utils/paseo-daemon.js"; +import { importSessionFromPersistence } from "../agent/provider-session-import.js"; import { BuiltinPluginLoader } from "./builtin/index.js"; import { serializePaseoToolInputParameters } from "../agent/tools/paseo-tool-serialization.js"; import type { @@ -27,7 +28,7 @@ function recordingProvider(native: boolean, callbacks: TestAgentClientOptions = const events = { interrupts: 0 }; const inner = createTestAgentClient("codex", { ...callbacks, - supportsMcpServers: true, + supportsMcpServers: callbacks.supportsMcpServers ?? true, onStartTurn: (prompt, config) => { turns.push({ prompt, launchCount: launches.length }); callbacks.onStartTurn?.(prompt, config); @@ -52,6 +53,13 @@ function recordingProvider(native: boolean, callbacks: TestAgentClientOptions = launches.push({ config: config as AgentSessionConfig, context }); return inner.resumeSession(handle, config, context, options); }, + importSession: (input, context) => + importSessionFromPersistence({ + provider: "codex", + request: input, + context, + resumeSession: provider.resumeSession.bind(provider), + }), isAvailable: () => inner.isAvailable(), fetchCatalog: (options) => inner.fetchCatalog(options), }; @@ -72,7 +80,7 @@ const tool = defineAgentTool({ }, }); export default function contribute(server) { - server.before("agent.session_open", ({ request }) => { + server.addHook("agent.open.before", async ({ request }) => { if (request.labels.x !== "y") return; return { ...request, env: { ...request.env, OPEN_INFO: JSON.stringify({ title: request.title, labels: request.labels, reason: request.reason }) }, tools: [...request.tools, tool] }; }); @@ -89,14 +97,14 @@ async function setup( const directory = await mkdtemp(path.join(tmpdir(), "paseo-agent-tools-")); const recorder = recordingProvider(native, providerOptions); const daemon = await createTestPaseoDaemon({ - daemonVersion: "0.13.2", + daemonVersion: "0.14.0-beta.1", agentClients: { codex: recorder.provider }, mcpEnabled: true, providerOverrides: { codex: { paseoTools: policy } }, }); const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws`, - appVersion: "0.13.2", + appVersion: "0.14.0-beta.1", }); const mcps: Client[] = []; async function install(id: string, code: string) { @@ -104,7 +112,7 @@ async function setup( await mkdir(pluginDirectory); await writeFile( path.join(pluginDirectory, "paseo-plugin.json"), - JSON.stringify({ id, requirements: { paseo: ">=0.13.2" } }), + JSON.stringify({ id, requirements: { paseo: ">=0.14.0-beta.1" } }), ); await writeFile(path.join(pluginDirectory, "index.server.ts"), code); await client.installDirectoryPlugin(pluginDirectory); @@ -297,7 +305,7 @@ test("each plugin owns its tool array and callbacks can remove earlier attachmen const source = pluginSource.replace( " return () => {};", ` - server.before("agent.session_open", ({ request }) => { + server.addHook("agent.open.before", async ({ request }) => { if (request.labels.x === "y" && request.tools[0]?.name !== "plugin_echo") throw new Error("Lost plugin-local definitions"); return { ...request, tools: [] }; }); @@ -493,12 +501,12 @@ test("built-in plugins attach and execute tools while configured plugins are dis await mkdir(directory); await writeFile( path.join(directory, "paseo-plugin.json"), - JSON.stringify({ id: "builtin-tools", requirements: { paseo: ">=0.13.2" } }), + JSON.stringify({ id: "builtin-tools", requirements: { paseo: ">=0.14.0-beta.1" } }), ); await writeFile(path.join(directory, "index.server.ts"), pluginSource); const recorder = recordingProvider(true); const daemon = await createTestPaseoDaemon({ - daemonVersion: "0.13.2", + daemonVersion: "0.14.0-beta.1", agentClients: { codex: recorder.provider }, pluginsEnabled: false, builtinPlugins: new BuiltinPluginLoader(root, ["builtin-tools"]), @@ -750,3 +758,285 @@ test("the agent-tools example appends notes only for labeled agents", async () = await h.close(); } }, 60_000); + +const companyServer = { type: "http", url: "https://tools.example.com/mcp" } as const; +const mcpSource = ` +export default function contribute(server) { + server.addHook("agent.open.before", async ({ request }) => { + if (request.provider !== "codex") return; + return { ...request, mcpServers: { ...request.mcpServers, company: ${JSON.stringify(companyServer)} }, + env: { ...request.env, OPEN_REASON: request.reason } }; + }); + return () => {}; +} +`; + +test.each([ + { native: false, serverNames: ["paseo", "company"] }, + { native: true, serverNames: ["company"] }, +])( + "session-open MCP servers reach launch but never saved configuration (native=$native)", + async ({ native, serverNames }) => { + const h = await setup(native, mcpSource); + try { + const a = await h.create(); + expect(h.launches.at(-1)!.config.mcpServers?.company).toEqual(companyServer); + expect(a.config.mcpServers?.company).toBeUndefined(); + const snapshot = (await h.client.fetchAgent(a.id))!.agent; + expect(snapshot.id).toBe(a.id); + expect(JSON.stringify(snapshot)).not.toContain("tools.example.com"); + expect(h.launches.at(-1)!.context!.env!.OPEN_REASON).toBe("create"); + expect(Object.keys(h.launches.at(-1)!.config.mcpServers!)).toEqual(serverNames); + await h.daemon.daemon.agentManager.closeAgent(a.id); + const agentFiles = await readdir(path.join(h.daemon.paseoHome, "agents"), { + recursive: true, + }); + const recordFile = agentFiles.find((file) => file.endsWith(a.id + ".json"))!; + const record = await readFile(path.join(h.daemon.paseoHome, "agents", recordFile), "utf8"); + expect(record).not.toContain("tools.example.com"); + } finally { + await h.close(); + } + }, + 60_000, +); + +test("session-open MCP servers are rederived on resume, SDK reload, and provider import", async () => { + const source = reloadRpcSource + .replace(' if (request.labels.x !== "y") return;', "") + .replace( + "return { ...request, env:", + `return { ...request, mcpServers: { ...request.mcpServers, company: ${JSON.stringify(companyServer)} }, env:`, + ); + const h = await setup(true, source); + try { + const a = await h.create({ x: "y" }); + const manager = h.daemon.daemon.agentManager; + await manager.closeAgent(a.id); + await manager.resumeAgentFromPersistence(a.persistence!, a.config, a.id); + expect(h.launches.at(-1)!.config.mcpServers?.company).toEqual(companyServer); + expect(JSON.parse(h.launches.at(-1)!.context!.env!.OPEN_INFO).reason).toBe("resume"); + await h.client.invokePluginRpc("tools-test", "reload_agent", { id: a.id }); + expect(h.launches.at(-1)!.config.mcpServers?.company).toEqual(companyServer); + expect(JSON.parse(h.launches.at(-1)!.context!.env!.OPEN_INFO).reason).toBe("refresh"); + const imported = await manager.importProviderSession({ + provider: "codex", + providerHandleId: "imported-session", + cwd: h.directory, + workspaceId: "import-workspace", + labels: { x: "y" }, + }); + expect(h.launches.at(-1)!.config.mcpServers?.company).toEqual(companyServer); + expect(JSON.parse(h.launches.at(-1)!.context!.env!.OPEN_INFO).reason).toBe("import"); + expect(imported.config.mcpServers?.company).toBeUndefined(); + expect(JSON.stringify(imported.persistence)).not.toContain("tools.example.com"); + expect(manager.getAgent(a.id)!.config.mcpServers?.company).toBeUndefined(); + expect(JSON.stringify(manager.getAgent(a.id)!.persistence)).not.toContain("tools.example.com"); + } finally { + await h.close(); + } +}, 60_000); + +test("installing and disabling an MCP plugin reopens idle sessions before their next prompt", async () => { + const h = await setup(true, "export default function contribute() { return () => {}; }"); + try { + const a = await h.create(); + expect(h.launches.at(-1)!.config.mcpServers?.company).toBeUndefined(); + await h.install("company-mcp", mcpSource); + await sendAndFinish(h, a.id, "after install"); + expect(h.launches).toHaveLength(2); + expect(h.launches.at(-1)!.config.mcpServers?.company).toEqual(companyServer); + await h.client.disablePlugin("company-mcp"); + await sendAndFinish(h, a.id, "after disable"); + expect(h.launches).toHaveLength(3); + expect(h.launches.at(-1)!.config.mcpServers?.company).toBeUndefined(); + await sendAndFinish(h, a.id, "stable"); + expect(h.launches).toHaveLength(3); + expect(h.events.interrupts).toBe(0); + } finally { + await h.close(); + } +}, 60_000); + +test("installing and disabling an MCP plugin never interrupts a running turn", async () => { + let release!: () => void; + const blocked = new Promise((resolve) => { + release = resolve; + }); + const h = await setup( + true, + "export default function contribute() { return () => {}; }", + undefined, + { beforeTurnComplete: async () => blocked }, + ); + try { + const a = await h.create(); + await h.client.sendMessage(a.id, "busy", { activeTurnBehavior: "steer" }); + const manager = h.daemon.daemon.agentManager; + await expect.poll(() => manager.getAgent(a.id)!.activeTurnId).not.toBeNull(); + const turn = manager.getAgent(a.id)!.activeTurnId; + await h.install("company-mcp", mcpSource); + expect(h.launches).toHaveLength(1); + expect(manager.getAgent(a.id)!.activeTurnId).toBe(turn); + await h.client.disablePlugin("company-mcp"); + expect(h.launches).toHaveLength(1); + expect(manager.getAgent(a.id)!.activeTurnId).toBe(turn); + expect(h.events.interrupts).toBe(0); + release(); + await expect.poll(() => manager.hasInFlightRun(a.id)).toBe(false); + await sendAndFinish(h, a.id, "idle"); + expect(h.launches).toHaveLength(2); + expect(h.launches.at(-1)!.config.mcpServers?.company).toBeUndefined(); + } finally { + release(); + await h.close(); + } +}, 60_000); + +test.each([ + { + target: "saved configuration", + saved: true, + name: "company", + other: false, + error: /company.*plugin tools-test.*agent saved configuration/, + }, + { + target: "saved Paseo name", + saved: true, + name: "paseo", + other: false, + error: /paseo.*plugin tools-test.*agent saved configuration/, + }, + { + target: "Paseo internal server", + saved: false, + name: "paseo", + other: false, + error: /paseo.*plugin tools-test.*Paseo internal MCP server/, + }, + { + target: "another plugin with identical config", + saved: false, + name: "company", + other: true, + error: /Plugin tools-test.*company.*plugin other-mcp/, + }, +])( + "session-open MCP collisions with $target name both owners", + async ({ saved, name, other, error }) => { + const h = await setup(true, mcpSource.replace("company:", name + ":")); + try { + if (other) await h.install("other-mcp", mcpSource); + await expect( + h.daemon.daemon.agentManager.createAgent( + { + provider: "codex", + cwd: h.directory, + ...(saved + ? { mcpServers: { [name]: { type: "http", url: "https://saved.example.com" } } } + : {}), + }, + undefined, + {}, + ), + ).rejects.toThrow(error); + expect(h.launches).toHaveLength(0); + } finally { + await h.close(); + } + }, + 60_000, +); + +test("session-open MCP servers fail on unsupported providers and leave saved config untouched", async () => { + const h = await setup(false, mcpSource, undefined, { supportsMcpServers: false }); + try { + await h.client.disablePlugin("tools-test"); + const a = await h.create(); + await h.client.enablePlugin("tools-test"); + await expect(h.daemon.daemon.agentManager.reloadAgentSession(a.id)).rejects.toThrow( + /does not support MCP servers.*plugin tools-test/, + ); + expect(a.config.mcpServers?.company).toBeUndefined(); + await expect(h.create()).rejects.toThrow(/does not support MCP servers.*plugin tools-test/); + const imported = h.daemon.daemon.agentManager.importProviderSession({ + provider: "codex", + providerHandleId: "unsupported-import", + cwd: h.directory, + workspaceId: "import-workspace", + }); + await expect(imported).rejects.toThrow(/does not support MCP servers.*plugin tools-test/); + } finally { + await h.close(); + } +}, 60_000); + +test("history opens ignore session-open MCP servers", async () => { + const h = await setup(true, mcpSource); + try { + const a = await h.create(); + await h.client.archiveAgent(a.id); + await h.install("other-mcp", mcpSource); + await h.daemon.daemon.agentManager.resumeAgentFromPersistence(a.persistence!, a.config, a.id); + expect(h.launches.at(-1)!.config.mcpServers?.company).toBeUndefined(); + expect(h.launches.at(-1)!.context!.mcpServers).toBeUndefined(); + } finally { + await h.close(); + } +}, 60_000); + +test("session-open MCP maps are plugin-local and accumulate only across their own callbacks", async () => { + const h = await setup(true, mcpSource); + try { + await h.install( + "z-extend", + ` +export default function contribute(server) { + server.addHook("agent.open.before", async ({ request }) => { + if ("mcpServerOwners" in request) throw new Error("Daemon provenance leaked"); + if (Object.keys(request.mcpServers).length !== 0) throw new Error("Saw another plugin servers"); + return { ...request, mcpServers: { ...request.mcpServers, extra: { type: "stdio", command: "company-tools", args: ["--mcp"], env: { MODE: "agent" } } } }; + }); + server.addHook("agent.open.before", async ({ request }) => { + if (request.mcpServers.extra.command !== "company-tools") throw new Error("Lost own earlier server"); + return { ...request, mcpServers: { ...request.mcpServers, additional: { type: "http", url: "https://additional.example.com/mcp" } } }; + }); + server.addHook("agent.open.before", async () => undefined); + return () => {}; +}`, + ); + const a = await h.create(); + expect(h.launches.at(-1)!.config.mcpServers).toEqual({ + company: companyServer, + extra: { type: "stdio", command: "company-tools", args: ["--mcp"], env: { MODE: "agent" } }, + additional: { type: "http", url: "https://additional.example.com/mcp" }, + }); + const contributedServers = h.launches.at(-1)!.config.mcpServers; + await h.install( + "zz-remove", + `export default function contribute(server) { + server.addHook("agent.open.before", async ({ request }) => ({ ...request, mcpServers: {} })); + return () => {}; +}`, + ); + await sendAndFinish(h, a.id, "after removal"); + expect(h.launches.at(-1)!.config.mcpServers).toEqual(contributedServers); + expect(a.config.mcpServers).toBeUndefined(); + } finally { + await h.close(); + } +}, 60_000); + +test("session-open MCP configs are validated before a provider launches", async () => { + const h = await setup( + true, + mcpSource.replace(JSON.stringify(companyServer), '{ type: "http", url: 42 }'), + ); + try { + await expect(h.create()).rejects.toThrow(/Plugin tools-test.*agent.open.before/s); + expect(h.launches).toHaveLength(0); + } finally { + await h.close(); + } +}, 60_000); diff --git a/packages/server/src/server/plugins/builtin/index.test.ts b/packages/server/src/server/plugins/builtin/index.test.ts index 6160c8f855..5f4728ecfa 100644 --- a/packages/server/src/server/plugins/builtin/index.test.ts +++ b/packages/server/src/server/plugins/builtin/index.test.ts @@ -78,6 +78,45 @@ test("listed client bundle is published while plugins are disabled; unlisted dir } }, 60_000); +test("a repeated catalog fetch leaves out the client bundle the client already holds", async () => { + const root = await mkdtemp(path.join(os.tmpdir(), "paseo-builtin-catalog-cache-")); + roots.push(root); + const directory = await fixture(root, "large", true); + // About the size of a real plugin client bundle. + await writeFile( + path.join(directory, "index.client.tsx"), + `const payload = ${JSON.stringify("x".repeat(1_000_000))}; +export default function contribute() { void payload; return () => {}; }`, + ); + const daemon = await createTestPaseoDaemon({ + daemonVersion: "0.9.2", + pluginsEnabled: false, + builtinPlugins: new BuiltinPluginLoader(root, ["large"]), + }); + const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws`, appVersion: "0.9.2" }); + const responseBytes: number[] = []; + const unsubscribe = client.subscribeRawMessages((message) => { + if (message.type === "plugin.catalog.get.response") { + responseBytes.push(JSON.stringify(message).length); + } + }); + try { + await client.connect(); + const first = await client.getPluginCatalog(); + const second = await client.getPluginCatalog(); + + expect(second).toEqual(first); + expect(second[0]?.clientBundle).toContain("x".repeat(1_000_000)); + expect(responseBytes).toHaveLength(2); + expect(responseBytes[0]).toBeGreaterThan(1_000_000); + expect(responseBytes[1]).toBeLessThan(500); + } finally { + unsubscribe(); + await client.close(); + await daemon.close(); + } +}, 60_000); + test("directory, Git, and npm installs reject a built-in ID", async () => { const root = await mkdtemp(path.join(os.tmpdir(), "paseo-builtin-install-")); roots.push(root); diff --git a/packages/server/src/server/plugins/builtin/index.ts b/packages/server/src/server/plugins/builtin/index.ts index cf6ffe9eee..463ee8407d 100644 --- a/packages/server/src/server/plugins/builtin/index.ts +++ b/packages/server/src/server/plugins/builtin/index.ts @@ -14,6 +14,7 @@ export const builtinPlugins = [ "minimax-usage-source", "muse-provider", "opencode-go-usage-source", + "worktree-include", "zai-usage-source", ] as const; diff --git a/packages/server/src/server/plugins/compiler-build.ts b/packages/server/src/server/plugins/compiler-build.ts index 5abd0df6ef..51eb2d2549 100644 --- a/packages/server/src/server/plugins/compiler-build.ts +++ b/packages/server/src/server/plugins/compiler-build.ts @@ -257,6 +257,22 @@ function makeHermesInteropEager(code: string): string { return code.replaceAll("get: () => from[key]", "value: from[key]"); } +async function minifyClientBundle(code: string): Promise { + const { transform } = loadEsbuild(); + // Minify after the eager replace. Whitespace minify rewrites the getter this + // replace matches, and identifier minify can delete the helper entirely. + const result = await transform(code, { + minifyWhitespace: true, + minifySyntax: true, + minifyIdentifiers: false, + target: "es2020", + supported: { "async-await": false }, + charset: "ascii", + legalComments: "inline", + }); + return result.code; +} + function runtimeSpecifierError( specifier: string, target: PluginBuildTarget | "shared", @@ -368,7 +384,10 @@ async function compileTarget(entryPath: string, target: PluginBuildTarget): Prom checkSharedDependencies(result.metafile.inputs, pluginDirectory); const output = result.outputFiles[0]?.text; if (!output) throw new Error(`Plugin ${target} compilation produced no output`); - return wrapCommonJsBundle(makeHermesInteropEager(output)); + const eager = makeHermesInteropEager(output); + let prepared = eager; + if (target === "client") prepared = await minifyClientBundle(eager); + return wrapCommonJsBundle(prepared); } export async function compilePlugin(entryPaths: { diff --git a/packages/server/src/server/plugins/compiler.test.ts b/packages/server/src/server/plugins/compiler.test.ts index 67ca96e596..69510cdfb0 100644 --- a/packages/server/src/server/plugins/compiler.test.ts +++ b/packages/server/src/server/plugins/compiler.test.ts @@ -3,6 +3,7 @@ import { mkdir, mkdtemp, rm, symlink, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import { afterEach, describe, expect, it } from "vitest"; +import * as zod from "zod"; import { ZodError } from "zod"; import { compilePlugin, @@ -569,6 +570,101 @@ export default function contribute(client) { expect(clientBundle).toContain("__async"); }); + it("reduces client bytes while preserving registration and leaving server output readable", async () => { + const entries = await createSplitPlugin(); + const source = `import { z } from "zod"; +const commandSchema = z.object({ id: z.string(), title: z.string() }); +export default function contribute(client) { + const command = commandSchema.parse({ id: "open", title: "Open – plugin" }); + client.addCommandCenterItem({ + ...command, + icon: "Scan", + context: "global", + onSelect() { return Promise.resolve(command.title); }, + }); + return () => undefined; +}`; + await Promise.all([writeFile(entries.client, source), writeFile(entries.server, source)]); + const { clientBundle, serverBundle } = await compilePlugin(entries); + if (clientBundle === null || serverBundle === null) { + throw new Error("compilePlugin returned no bundle"); + } + + for (const bundle of [clientBundle, serverBundle]) { + const registered: { id: string; title: string; onSelect: () => Promise }[] = []; + const exports = new Function(`return ${bundle}`)()((specifier: string) => { + expect(specifier).toBe("zod"); + return zod; + }); + const cleanup = exports.default({ + addCommandCenterItem: (command: (typeof registered)[number]) => registered.push(command), + }); + expect(registered).toMatchObject([{ id: "open", title: "Open – plugin" }]); + await expect(registered[0]!.onSelect()).resolves.toBe("Open – plugin"); + expect(cleanup()).toBeUndefined(); + } + expect(Buffer.byteLength(clientBundle)).toBeLessThan(Buffer.byteLength(serverBundle) * 0.9); + expect(clientBundle.split("").every((char) => char.charCodeAt(0) <= 0x7f)).toBe(true); + expect(serverBundle).toContain('title: "Open'); + }); + + it("retains dependency license notices while minifying executable client code", async () => { + const entries = await createSplitPlugin(); + const dependency = path.join(entries.directory, "node_modules/licensed-dependency"); + const notice = "Copyright Example Authors. SPDX-License-Identifier: MIT"; + await mkdir(dependency, { recursive: true }); + await writeFile( + path.join(dependency, "package.json"), + JSON.stringify({ name: "licensed-dependency", main: "index.js" }), + ); + await writeFile( + path.join(dependency, "index.js"), + `/*! ${notice} */ +exports.title = function title(input) { + const trimmed = input.trim(); + return "Licensed " + trimmed; +};`, + ); + const source = `import { title } from "licensed-dependency"; +export default function contribute() { return title(" plugin "); }`; + await Promise.all([writeFile(entries.client, source), writeFile(entries.server, source)]); + const { clientBundle, serverBundle } = await compilePlugin(entries); + if (clientBundle === null || serverBundle === null) { + throw new Error("compilePlugin returned no bundle"); + } + + for (const bundle of [clientBundle, serverBundle]) { + expect(bundle).toContain(notice); + const exports = new Function(`return ${bundle}`)()(() => { + throw new Error("The dependency must be bundled"); + }); + expect(exports.default()).toBe("Licensed plugin"); + } + expect(Buffer.byteLength(clientBundle)).toBeLessThan(Buffer.byteLength(serverBundle) * 0.9); + }); + + it("keeps distinct host exports eager when minifying in the worker", async () => { + const entries = await createSplitPlugin(); + await writeFile( + entries.client, + `import * as host from "zod"; +export default function contribute() { return [host.first, host.second]; }`, + ); + const { clientBundle } = await compilePlugin({ client: entries.client, server: null }); + const host = { first: "first export", second: "second export" }; + const factory = new Function(`return ${clientBundle}`)() as ( + require: (specifier: string) => typeof host, + ) => { default: () => unknown }; + function requireHost(specifier: string): typeof host { + expect(specifier).toBe("zod"); + return host; + } + const exports = factory(requireHost); + host.first = "changed first export"; + host.second = "changed second export"; + expect(exports.default()).toEqual(["first export", "second export"]); + }); + it("rejects node imports from the client entry", async () => { const entries = await createSplitPlugin(); await writeFile( diff --git a/packages/server/src/server/plugins/index.posix.test.ts b/packages/server/src/server/plugins/index.posix.test.ts index 4ca5aeefd5..60216ff0fa 100644 --- a/packages/server/src/server/plugins/index.posix.test.ts +++ b/packages/server/src/server/plugins/index.posix.test.ts @@ -15,11 +15,12 @@ import { tmpdir } from "node:os"; import path from "node:path"; import { pathToFileURL } from "node:url"; import pino from "pino"; -import { afterEach, describe, expect, it } from "vitest"; +import { afterEach, beforeAll, describe, expect, it } from "vitest"; import { DaemonConfigStore } from "../daemon-config-store.js"; import { PluginService } from "./index.js"; import { BuiltinPluginLoader } from "./builtin/index.js"; import { ManagedPluginSources } from "./managed-source.js"; +import type { PluginProviderMetadata } from "./plugin-process-protocol.js"; import { startNpmRegistry, npmPluginPackages, @@ -179,6 +180,55 @@ function createPluginSelectivePausedRuntime(pausedPluginId: string) { return { runtime, started, releaseStart, starts }; } +function createGatedRuntime(providers: Record = {}) { + const gates = new Map>(); + const gate = (pluginId: string) => { + const existing = gates.get(pluginId); + if (existing) return existing; + const created = Promise.withResolvers(); + gates.set(pluginId, created); + return created; + }; + const begun: string[] = []; + const running = new Set(); + const runtime: TestPluginRuntime = { + ...emptyUsageRuntime, + catalog: () => [...running].map((id) => ({ id, clientBundle: "bundle" })), + invoke: async () => undefined, + getLogs: () => [], + clearLogs: () => undefined, + getProviderRegistrations: (pluginId) => + running.has(pluginId) ? (providers[pluginId] ?? []) : [], + startPlugin: async (pluginId) => { + begun.push(pluginId); + await gate(pluginId).promise; + running.add(pluginId); + }, + stopPluginById: async (pluginId) => running.delete(pluginId), + stopAll: async () => { + running.clear(); + }, + subscribe: () => () => undefined, + bindPaseoSessionHost: () => undefined, + }; + return { + runtime, + begun, + finish: (pluginId: string) => gate(pluginId).resolve(), + fail: (pluginId: string, error: Error) => gate(pluginId).reject(error), + }; +} + +function nextNotification(service: PluginService, pluginId: string): Promise { + return new Promise((resolve) => { + const unsubscribe = service.subscribe((notified) => { + if (notified !== pluginId) return; + unsubscribe(); + resolve(); + }); + }); +} + describe("PluginService", () => { it.each([ { shadow: false, runtime: "subprocess" }, @@ -372,15 +422,127 @@ describe("PluginService", () => { "startup-first": { source: "directory", path: first }, "startup-second": { source: "directory", path: second }, }); - const snapshots: string[][] = []; - service.subscribe(() => snapshots.push(catalogIds(service))); + const notifications: { pluginId: string; running: boolean }[] = []; + service.subscribe((pluginId) => + notifications.push({ pluginId, running: catalogIds(service).includes(pluginId) }), + ); await service.start(); - expect(snapshots).toEqual([["startup-first"], ["startup-first", "startup-second"]]); + expect(notifications).toEqual([ + { pluginId: "startup-first", running: true }, + { pluginId: "startup-second", running: true }, + ]); + expect(catalogIds(service)).toEqual(["startup-first", "startup-second"]); await service.stopAllPlugins(); }, 20_000); + it("starts configured plugins concurrently and publishes them in config order", async () => { + const home = await mkdtemp(path.join(tmpdir(), "paseo-plugin-home-")); + roots.push(home); + const gated = createGatedRuntime(); + const service = createService( + home, + { + alpha: { source: "directory", path: "/plugins/alpha" }, + beta: { source: "directory", path: "/plugins/beta" }, + gamma: { source: "directory", path: "/plugins/gamma" }, + }, + { runtime: gated.runtime }, + ); + const notified: string[] = []; + service.subscribe((pluginId) => notified.push(pluginId)); + let started = false; + const starting = (async () => { + await service.start(); + started = true; + })(); + + await expect.poll(() => gated.begun).toEqual(["alpha", "beta", "gamma"]); + + gated.finish("gamma"); + const alphaPublished = nextNotification(service, "alpha"); + gated.finish("alpha"); + await alphaPublished; + expect(notified).toEqual(["alpha"]); + expect(started).toBe(false); + + gated.finish("beta"); + await starting; + expect(notified).toEqual(["alpha", "beta", "gamma"]); + expect(catalogIds(service)).toEqual(["alpha", "beta", "gamma"]); + await service.stopAllPlugins(); + }); + + it("starts the other configured plugins when one fails while they are still starting", async () => { + const home = await mkdtemp(path.join(tmpdir(), "paseo-plugin-home-")); + roots.push(home); + const gated = createGatedRuntime(); + const service = createService( + home, + { + broken: { source: "directory", path: "/plugins/broken" }, + healthy: { source: "directory", path: "/plugins/healthy" }, + }, + { runtime: gated.runtime }, + ); + const notified: string[] = []; + service.subscribe((pluginId) => notified.push(pluginId)); + const starting = service.start(); + + await expect.poll(() => gated.begun).toEqual(["broken", "healthy"]); + const brokenPublished = nextNotification(service, "broken"); + gated.fail("broken", new Error("startup exploded")); + await brokenPublished; + gated.finish("healthy"); + await starting; + + expect(notified).toEqual(["broken", "healthy"]); + expect(catalogIds(service)).toEqual(["healthy"]); + expect(await service.listPlugins()).toMatchObject([ + { id: "broken", status: "failed", error: "startup exploded" }, + { id: "healthy", status: "running" }, + ]); + await service.stopAllPlugins(); + }); + + it("keeps a provider ID with the plugin listed first when both start at once", async () => { + const home = await mkdtemp(path.join(tmpdir(), "paseo-plugin-home-")); + roots.push(home); + const gated = createGatedRuntime({ + first: [{ id: "shared-agent", label: "First agent" }], + second: [{ id: "shared-agent", label: "Second agent" }], + }); + const service = createService( + home, + { + first: { source: "directory", path: "/plugins/first" }, + second: { source: "directory", path: "/plugins/second" }, + }, + { runtime: gated.runtime }, + ); + const starting = service.start(); + + await expect.poll(() => gated.begun).toEqual(["first", "second"]); + gated.finish("second"); + gated.finish("first"); + await starting; + + expect(service.getProviderRegistrations()).toMatchObject([ + { id: "shared-agent", label: "First agent" }, + ]); + expect(catalogIds(service)).toEqual(["first"]); + expect(await service.listPlugins()).toMatchObject([ + { id: "first", status: "running" }, + { + id: "second", + status: "failed", + error: 'Plugin second cannot register provider ID "shared-agent" twice', + }, + ]); + await service.stopAllPlugins(); + }); + it("uses an explicit config key, exposes reload failure, and retries from disk", async () => { const home = await mkdtemp(path.join(tmpdir(), "paseo-plugin-home-")); roots.push(home); @@ -730,7 +892,7 @@ export default function contribute(server: PluginServerContext) { await service.stopAllPlugins(); } }, - 30_000, + 60_000, ); it("keeps the running commit when a Git update build command fails", async () => { @@ -1071,27 +1233,65 @@ export default function contribute(plugin: unknown) { "second", `export default function contribute(plugin: unknown) { void plugin; return () => undefined; }`, ); + // Hold cleanup open so synchronous detach and queued recovery are tested + // independently of compiler/process startup speed on the runner. + let finishCleanup = () => undefined; + const cleanup = new Promise((resolve) => { + finishCleanup = resolve; + }); + const running = new Set(); + const runtime: TestPluginRuntime = { + ...emptyUsageRuntime, + catalog: () => [...running].map((id) => ({ id, clientBundle: "bundle" })), + invoke: async (pluginId) => { + if (!running.has(pluginId)) throw new Error(`Plugin is not available: ${pluginId}`); + return pluginId; + }, + getLogs: () => [], + clearLogs: () => undefined, + startPlugin: async (pluginId, _path, canPublish) => { + if (!canPublish()) throw new Error(`Plugin start cancelled: ${pluginId}`); + running.add(pluginId); + }, + stopPluginById: async (pluginId) => { + const existed = running.delete(pluginId); + await cleanup; + return existed; + }, + stopAll: async () => running.clear(), + subscribe: () => () => undefined, + bindPaseoSessionHost: () => undefined, + }; const store = createStore(home); const service = bindTestSessionHost( - new PluginService(pino({ level: "silent" }), store, "0.4.0"), + new PluginService(pino({ level: "silent" }), store, "0.4.0", { runtime }), ); - await service.start(); - await service.installDirectory({ path: first }); - await service.installDirectory({ path: second }); + try { + await service.start(); + await service.installDirectory({ path: first }); + await service.installDirectory({ path: second }); + expect(catalogIds(service)).toEqual(["first", "second"]); + await store.patch({ pluginsEnabled: false }); - await store.patch({ pluginsEnabled: false }); - - expect(service.catalog()).toEqual([]); - await expect(service.invokePluginRpc("second", "anything", {})).rejects.toThrow( - "Plugin is not available", - ); - await store.patch({ pluginsEnabled: true }); - await service.reloadPlugin("first"); - expect((await service.listPlugins()).map(({ id, status }) => ({ id, status }))).toEqual([ - { id: "first", status: "running" }, - { id: "second", status: "running" }, - ]); - await service.stopAllPlugins(); + expect(service.catalog()).toEqual([]); + await expect(service.invokePluginRpc("second", "anything", {})).rejects.toThrow( + "Plugin is not available", + ); + await store.patch({ pluginsEnabled: true }); + expect(service.catalog()).toEqual([]); + finishCleanup(); + // Observe recovery itself. Reloading here restarts a healthy plugin and + // would also conceal a failure to restart it after the global enable. + await expect + .poll(() => service.listPlugins(), { timeout: 10_000 }) + .toMatchObject([ + { id: "first", status: "running" }, + { id: "second", status: "running" }, + ]); + } finally { + finishCleanup(); + await service.stopAllPlugins(); + } }, 20_000); it("does not publish an in-flight start after a later global disable", async () => { @@ -1321,7 +1521,11 @@ export default function contribute(plugin: unknown) { }); describe("npm plugin installation", () => { - it("preserves dependencies and metadata, and reloads without npm", async () => { + let registry: Awaited>; + + // Give real npm fixture construction its own setup budget so it does not consume + // the installation journey on Windows. + beforeAll(async () => { const packages = npmPluginPackages(); const fixture = packages[1]; packages.push({ ...fixture, version: "2.0.0", tags: ["future"] }); @@ -1356,7 +1560,7 @@ describe("npm plugin installation", () => { for (const [name, overrides] of failures) { failedPackages.push({ ...fixture, name, files: { ...fixture.files, ...overrides } }); } - const registry = await startNpmRegistry([ + registry = await startNpmRegistry([ ...packages, { name: "paseo-prepared-plugin", @@ -1386,6 +1590,9 @@ export default function contribute() { }, ...failedPackages, ]); + }, 120_000); + + it("preserves dependencies and metadata, and reloads without npm", async () => { const home = await mkdtemp(path.join(tmpdir(), "paseo-npm-service-")); roots.push(home); const previousConfig = process.env.npm_config_userconfig; diff --git a/packages/server/src/server/plugins/index.ts b/packages/server/src/server/plugins/index.ts index 98e7ce5623..65faa39f75 100644 --- a/packages/server/src/server/plugins/index.ts +++ b/packages/server/src/server/plugins/index.ts @@ -45,6 +45,7 @@ interface PluginRuntimePort { emit?: PluginLifecycle["emit"]; drainEvents?: PluginRuntime["drainEvents"]; before?: PluginLifecycle["before"]; + wait?: PluginLifecycle["wait"]; catalog: PluginRuntime["catalog"]; invoke(pluginId: string, method: string, input: unknown): Promise; getLogs(pluginId: string): PluginLogEntry[]; @@ -168,6 +169,10 @@ export class PluginService { return this.runtime.callTool(pluginId, pluginInstanceId, agent, name, input, signal); }; + readonly wait: PluginLifecycle["wait"] = async (name, payload) => { + await this.runtime.wait?.(name, payload); + }; + async drainEvents(): Promise { await this.runtime.drainEvents?.(); } @@ -225,11 +230,18 @@ export class PluginService { } }); if (config.pluginsEnabled === true) { - for (const [pluginId, source] of Object.entries(config.plugins ?? {})) { - if (source.enabled === false) continue; - await this.startConfigured(pluginId); - this.notify(pluginId); - } + let earlierPublished: Promise = Promise.resolve(); + await Promise.all( + Object.entries(config.plugins ?? {}) + .filter(([, source]) => source.enabled !== false) + .map(async ([pluginId]) => { + const publishTurn = earlierPublished; + const starting = this.startConfigured(pluginId, publishTurn); + earlierPublished = Promise.all([publishTurn, starting]); + await starting; + this.notify(pluginId); + }), + ); } this.configStore.onFieldChange("pluginsEnabled", (value) => { this.handleGlobalSwitch(value === true); @@ -555,12 +567,12 @@ export class PluginService { }).catch((error) => this.logger.error({ err: error }, "Failed to enable plugins")); } - private async startConfigured(pluginId: string): Promise { + private async startConfigured(pluginId: string, publishTurn?: Promise): Promise { const source = this.configStore.get().plugins?.[pluginId]; if (!source || source.enabled === false || !this.canPublish(pluginId)) return; this.errors.delete(pluginId); try { - await this.startPlugin(pluginId, source.path); + await this.startPlugin(pluginId, source.path, publishTurn); } catch (error) { if (this.canPublish(pluginId)) this.recordFailure(pluginId, error); } @@ -589,8 +601,13 @@ export class PluginService { ); } - private async startPlugin(pluginId: string, sourcePath: string): Promise { + private async startPlugin( + pluginId: string, + sourcePath: string, + publishTurn?: Promise, + ): Promise { await this.runtime.startPlugin(pluginId, sourcePath, () => this.canPublish(pluginId)); + await publishTurn; try { await this.publishProviderRegistrations(pluginId, sourcePath); this.publishUsageSources(pluginId); diff --git a/packages/server/src/server/plugins/lifecycle-archive.e2e.test.ts b/packages/server/src/server/plugins/lifecycle-archive.e2e.test.ts index 6f3d8661e7..1b05b56b53 100644 --- a/packages/server/src/server/plugins/lifecycle-archive.e2e.test.ts +++ b/packages/server/src/server/plugins/lifecycle-archive.e2e.test.ts @@ -8,8 +8,11 @@ import { createTestPaseoDaemon } from "../test-utils/paseo-daemon.js"; test("closing and archiving agents publish their distinct lifecycle hooks once", async () => { const directory = await mkdtemp(path.join(tmpdir(), "paseo-archive-hooks-")); - const daemon = await createTestPaseoDaemon({ daemonVersion: "0.8.0" }); - const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws`, appVersion: "0.8.0" }); + const daemon = await createTestPaseoDaemon({ daemonVersion: "0.14.0-beta.1" }); + const client = new DaemonClient({ + url: `ws://127.0.0.1:${daemon.port}/ws`, + appVersion: "0.14.0-beta.1", + }); try { await client.connect(); await client.fetchAgents({ subscribe: {} }); @@ -39,7 +42,7 @@ test("closing and archiving agents publish their distinct lifecycle hooks once", .poll(async () => { const logs = await client.getPluginLogs("lifecycle-logger"); return logs - .filter((entry) => entry.message.startsWith('{"hook":"agent.closed"')) + .filter((entry) => entry.message.startsWith('{"hook":"agent.close.after"')) .map((entry) => JSON.parse(entry.message).data.agent.id); }) .toEqual([closed.id]); @@ -49,7 +52,7 @@ test("closing and archiving agents publish their distinct lifecycle hooks once", const logs = await client.getPluginLogs("lifecycle-logger"); return logs .filter((entry) => { - return entry.message.startsWith('{"hook":"agent.archived"'); + return entry.message.startsWith('{"hook":"agent.archive.after"'); }) .map((entry) => { return JSON.parse(entry.message).data.agent.id; @@ -61,7 +64,7 @@ test("closing and archiving agents publish their distinct lifecycle hooks once", .poll(async () => { const logs = await client.getPluginLogs("lifecycle-logger"); return logs - .filter((entry) => entry.message.startsWith('{"hook":"agent.closed"')) + .filter((entry) => entry.message.startsWith('{"hook":"agent.close.after"')) .map((entry) => JSON.parse(entry.message).data.agent.id) .sort(); }) @@ -75,20 +78,23 @@ test("closing and archiving agents publish their distinct lifecycle hooks once", test("daemon shutdown lets agent close hooks finish before stopping plugins", async () => { const directory = await mkdtemp(path.join(tmpdir(), "paseo-close-hook-shutdown-")); - const daemon = await createTestPaseoDaemon({ daemonVersion: "0.8.0" }); - const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws`, appVersion: "0.8.0" }); + const daemon = await createTestPaseoDaemon({ daemonVersion: "0.14.0-beta.1" }); + const client = new DaemonClient({ + url: `ws://127.0.0.1:${daemon.port}/ws`, + appVersion: "0.14.0-beta.1", + }); const completedFile = path.join(directory, "closed.txt"); try { await writeFile( path.join(directory, "paseo-plugin.json"), - JSON.stringify({ id: "close-hook-shutdown", requirements: { paseo: ">=0.8.0" } }), + JSON.stringify({ id: "close-hook-shutdown", requirements: { paseo: ">=0.14.0-beta.1" } }), ); await writeFile( path.join(directory, "index.server.ts"), `import { writeFile } from "node:fs/promises"; import { setTimeout } from "node:timers/promises"; export default function contribute(server) { - server.on("agent.closed", async (event, context) => { + server.addHook("agent.close.after", async (event, context) => { await setTimeout(200, undefined, { signal: context.signal }); await writeFile(${JSON.stringify(completedFile)}, event.agent.id); }); diff --git a/packages/server/src/server/plugins/lifecycle.e2e.test.ts b/packages/server/src/server/plugins/lifecycle.e2e.test.ts index 9c75f63746..bd1dfa8859 100644 --- a/packages/server/src/server/plugins/lifecycle.e2e.test.ts +++ b/packages/server/src/server/plugins/lifecycle.e2e.test.ts @@ -1,4 +1,5 @@ -import { cp, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { execFileSync } from "node:child_process"; +import { cp, mkdir, mkdtemp, readFile, realpath, rm, stat, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import { fileURLToPath } from "node:url"; @@ -6,6 +7,7 @@ import { expect, onTestFinished, test } from "vitest"; import { DaemonClient } from "../test-utils/daemon-client.js"; import { createTestPaseoDaemon } from "../test-utils/paseo-daemon.js"; import { resolveDaemonVersion } from "../daemon-version.js"; +import { BuiltinPluginLoader } from "./builtin/index.js"; test("a plugin transforms workspace creation once across receipt replays and observes its committed lifecycle", async () => { const directory = await mkdtemp(path.join(tmpdir(), "paseo-lifecycle-")); @@ -74,6 +76,76 @@ export default function contribute(server) { } }, 60_000); +test("addHook transforms workspace creation once across receipt replays and observes its committed lifecycle", async () => { + const directory = await mkdtemp(path.join(tmpdir(), "paseo-lifecycle-")); + const daemon = await createTestPaseoDaemon({ daemonVersion: "0.8.0" }); + const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws`, appVersion: "0.8.0" }); + try { + await writeFile( + path.join(directory, "paseo-plugin.json"), + JSON.stringify({ id: "lifecycle", requirements: { paseo: ">=0.8.0" } }), + ); + await writeFile( + path.join(directory, "index.server.ts"), + ` +export default function contribute(server) { + server.addHook("workspace.create.before", async ({ request }) => { + console.log(JSON.stringify({ hook: "workspace.before" })); + return { ...request, title: "Created through a hook" }; + }); + server.addHook("workspace.create.after", async (event) => { + console.log(JSON.stringify({ hook: "workspace.create.after", event })); + }); + server.addHook("workspace.archive.after", async (event) => { + console.log(JSON.stringify({ hook: "workspace.archive.after", event })); + }); + return () => {}; +} +`, + ); + await client.connect(); + await client.fetchAgents({ subscribe: {} }); + await client.patchDaemonConfig({ pluginsEnabled: true }); + await client.installDirectoryPlugin(directory); + const created = await client.createWorkspace({ + idempotencyKey: "plugin-workspace", + source: { kind: "directory", path: directory }, + }); + expect(created.workspace?.name).toBe("Created through a hook"); + const workspaceId = created.workspace!.id; + const replay = await client.createWorkspace({ + idempotencyKey: "plugin-workspace", + source: { kind: "directory", path: directory }, + }); + expect(replay.error).toBeNull(); + expect(replay.workspace?.id).toBe(workspaceId); + await client.archiveWorkspace(workspaceId); + await expect + .poll(async () => { + const logs = await client.getPluginLogs("lifecycle"); + return logs + .filter((entry) => { + return entry.message.startsWith('{"hook":'); + }) + .map((entry) => { + return JSON.parse(entry.message); + }); + }) + .toMatchObject([ + { hook: "workspace.before" }, + { + hook: "workspace.create.after", + event: { workspace: { id: workspaceId, cwd: directory } }, + }, + { hook: "workspace.archive.after", event: { workspace: { id: workspaceId } } }, + ]); + } finally { + await client.close(); + await daemon.close(); + await rm(directory, { recursive: true, force: true }); + } +}, 60_000); + test("plugins observe turns, answer permissions, and observe archive without blocking the agent", async () => { const directory = await mkdtemp(path.join(tmpdir(), "paseo-turn-hooks-")); const daemon = await createTestPaseoDaemon({ daemonVersion: "0.8.0" }); @@ -87,24 +159,24 @@ test("plugins observe turns, answer permissions, and observe archive without blo path.join(directory, "index.server.ts"), ` export default function contribute(server) { - server.on("agent.turn_started", (event) => { - console.log(JSON.stringify({ hook: "agent.turn_started", event })); + server.addHook("agent.turn.before", async (event) => { + console.log(JSON.stringify({ hook: "agent.turn.before", event })); }); - server.on("agent.turn_ended", (event) => { - console.log(JSON.stringify({ hook: "agent.turn_ended", event })); + server.addHook("agent.turn.after", async (event) => { + console.log(JSON.stringify({ hook: "agent.turn.after", event })); }); - server.on("agent.permission_requested", async (event, context) => { - console.log(JSON.stringify({ hook: "agent.permission_requested", event })); + server.addHook("agent.permission.before", async (event, context) => { + console.log(JSON.stringify({ hook: "agent.permission.before", event })); await context.paseo.agents.ref(event.agent.id).respondToPermission({ requestId: event.request.id, response: { behavior: "deny", message: "Declined by plugin" }, }); }); - server.on("agent.permission_resolved", (event) => { - console.log(JSON.stringify({ hook: "agent.permission_resolved", event })); + server.addHook("agent.permission.after", async (event) => { + console.log(JSON.stringify({ hook: "agent.permission.after", event })); }); - server.on("agent.archived", (event) => { - console.log(JSON.stringify({ hook: "agent.archived", event })); + server.addHook("agent.archive.after", async (event) => { + console.log(JSON.stringify({ hook: "agent.archive.after", event })); }); return () => {}; } @@ -139,16 +211,16 @@ export default function contribute(server) { { timeout: 10_000 }, ) .toMatchObject([ + { hook: "agent.permission.after", event: { resolution: { behavior: "deny" } } }, { - hook: "agent.permission_requested", + hook: "agent.permission.before", event: { request: { input: { command: "rm -f permission.txt" } } }, }, - { hook: "agent.permission_resolved", event: { resolution: { behavior: "deny" } } }, { - hook: "agent.turn_ended", + hook: "agent.turn.after", event: { outcome: { kind: "completed" }, timeline: [] }, }, - { hook: "agent.turn_started", event: { agent: { id: agent.id } } }, + { hook: "agent.turn.before", event: { agent: { id: agent.id } } }, ]); const page = await client.fetchAgentTimeline(agent.id, { direction: "tail", limit: 20 }); expect(page.entries.length).toBeGreaterThan(0); @@ -157,7 +229,7 @@ export default function contribute(server) { .poll(async () => { const logs = await client.getPluginLogs("turn-hooks"); return logs.filter((entry) => { - return entry.message.startsWith('{"hook":"agent.archived"'); + return entry.message.startsWith('{"hook":"agent.archive.after"'); }).length; }) .toBe(1); @@ -170,44 +242,41 @@ export default function contribute(server) { test("agent creation hooks change the provider and environment before the session opens", async () => { const directory = await mkdtemp(path.join(tmpdir(), "paseo-agent-hooks-")); - const daemon = await createTestPaseoDaemon({ daemonVersion: "0.8.0" }); - const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws`, appVersion: "0.8.0" }); - try { - await writeFile( - path.join(directory, "paseo-plugin.json"), - JSON.stringify({ id: "agent-hooks", requirements: { paseo: ">=0.8.0" } }), - ); - await writeFile( - path.join(directory, "index.server.ts"), - ` -export default function contribute(server) { - server.before("agent.create", ({ request }) => { - return { ...request, config: { ...request.config, provider: "codex" }, env: { ...request.env, HOOK_CREATE: "created" } }; + const pluginDirectory = await createProviderPlugin(directory, { + acknowledgeClose: true, + hooks: ` + server.addHook("agent.create.before", async ({ request }) => { + return { ...request, config: { ...request.config, provider: "${PROVIDER_ID}", model: "shutdown-model" }, env: { ...request.env, HOOK_CREATE: "created" } }; }); - server.before("agent.session_open", ({ request }) => { - console.log(JSON.stringify({ hook: "agent.session_open", request })); + server.addHook("agent.open.before", async ({ request }) => { + console.log(JSON.stringify({ hook: "agent.open.before", request })); return { ...request, env: { ...request.env, HOOK_OPEN: "opened" } }; }); - server.on("agent.created", (event) => { - console.log(JSON.stringify({ hook: "agent.created", event })); + server.addHook("agent.create.after", async (event) => { + console.log(JSON.stringify({ hook: "agent.create.after", event })); + });`, + reportOpen: true, }); - return () => {}; -} -`, - ); + const daemon = await createTestPaseoDaemon(); + const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` }); + try { await client.connect(); await client.fetchAgents({ subscribe: {} }); await client.patchDaemonConfig({ pluginsEnabled: true }); - await client.installDirectoryPlugin(directory); + await client.installDirectoryPlugin(pluginDirectory); const agent = await client.createAgent({ provider: "claude", cwd: directory, title: "Hook test", }); - expect(agent.provider).toBe("codex"); + expect(agent.provider).toBe(PROVIDER_ID); + expect(await daemon.daemon.agentStorage.get(agent.id)).toMatchObject({ + provider: PROVIDER_ID, + config: { model: "shutdown-model" }, + }); await expect .poll(async () => { - const logs = await client.getPluginLogs("agent-hooks"); + const logs = await client.getPluginLogs("shutdown-provider-plugin"); return logs .filter((entry) => { return entry.message.startsWith('{"hook":'); @@ -218,10 +287,17 @@ export default function contribute(server) { }) .toMatchObject([ { - hook: "agent.session_open", + hook: "agent.open.before", request: { agentId: agent.id, env: { HOOK_CREATE: "created" } }, }, - { hook: "agent.created", event: { agent: { id: agent.id, provider: "codex" } } }, + { + hook: "provider.open", + config: { env: { HOOK_CREATE: "created", HOOK_OPEN: "opened" } }, + }, + { + hook: "agent.create.after", + event: { agent: { id: agent.id, provider: PROVIDER_ID } }, + }, ]); await client.archiveAgent(agent.id); } finally { @@ -244,10 +320,10 @@ test("invalid output from an untyped plugin rejects creation before later callba path.join(directory, "index.server.ts"), ` export default function contribute(server) { - server.before("workspace.create", () => { + server.addHook("workspace.create.before", async () => { return { source: { kind: "worktree", branchName: 42 } }; }); - server.before("workspace.create", ({ request }) => { + server.addHook("workspace.create.before", async ({ request }) => { console.log("Unexpected later callback"); return request; }); @@ -260,7 +336,7 @@ export default function contribute(server) { await client.installDirectoryPlugin(directory); const result = await client.createWorkspace({ source: { kind: "directory", path: directory } }); expect(result.workspace).toBeNull(); - expect(result.error).toContain("Plugin invalid-hook before workspace.create failed"); + expect(result.error).toContain("Plugin invalid-hook workspace.create.before failed"); const logs = await client.getPluginLogs("invalid-hook"); expect( logs.some((entry) => { @@ -278,7 +354,9 @@ const PROVIDER_ID = "shutdown-provider"; async function createProviderPlugin( root: string, - options: { acknowledgeClose: boolean } = { acknowledgeClose: true }, + options: { acknowledgeClose: boolean; hooks?: string; reportOpen?: boolean } = { + acknowledgeClose: true, + }, ): Promise { const directory = path.join(root, "plugin"); await mkdir(directory, { recursive: true }); @@ -324,6 +402,7 @@ const provider: ProviderRegistration = { return; } if (input.type === "session.open") { + if (${JSON.stringify(options.reportOpen ?? false)}) console.log(JSON.stringify({ hook: "provider.open", config: input.config })); emit({ type: "session.opened", requestId: input.requestId, @@ -375,6 +454,7 @@ const provider: ProviderRegistration = { export default function contribute(server: { registerProvider(p: ProviderRegistration): void }) { server.registerProvider(provider); +${options.hooks ?? ""} return () => undefined; }`, ); @@ -383,7 +463,7 @@ export default function contribute(server: { registerProvider(p: ProviderRegistr test("a clean daemon shutdown leaves a completed plugin-provider agent without an error", async () => { const root = await mkdtemp(path.join(tmpdir(), "plugin-provider-shutdown-")); - onTestFinished(() => rm(root, { recursive: true, force: true })); + onTestFinished(() => rm(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 })); const pluginDirectory = await createProviderPlugin(root); const workspace = path.join(root, "workspace"); await mkdir(workspace, { recursive: true }); @@ -427,7 +507,7 @@ test("a clean daemon shutdown leaves a completed plugin-provider agent without a test("reloading a plugin leaves a completed plugin-provider agent without an error", async () => { const root = await mkdtemp(path.join(tmpdir(), "plugin-provider-reload-")); - onTestFinished(() => rm(root, { recursive: true, force: true })); + onTestFinished(() => rm(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 })); const pluginDirectory = await createProviderPlugin(root); const workspace = path.join(root, "workspace"); await mkdir(workspace, { recursive: true }); @@ -476,7 +556,7 @@ test("reloading a plugin leaves a completed plugin-provider agent without an err test("a provider that never acknowledges session.close does not hold the daemon open", async () => { const root = await mkdtemp(path.join(tmpdir(), "plugin-provider-stuck-close-")); - onTestFinished(() => rm(root, { recursive: true, force: true })); + onTestFinished(() => rm(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 })); const pluginDirectory = await createProviderPlugin(root, { acknowledgeClose: false }); const workspace = path.join(root, "workspace"); await mkdir(workspace, { recursive: true }); @@ -586,3 +666,644 @@ test("reloading a plugin does not send on a closed IPC channel", async () => { await rm(pluginDirectory, { recursive: true, force: true }); } }, 60_000); + +test("waiting hook failures reject the operation while notification failures are logged and later handlers run", async () => { + const directory = await mkdtemp(path.join(tmpdir(), "paseo-hook-failures-")); + const daemon = await createTestPaseoDaemon(); + const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` }); + try { + await writeFile( + path.join(directory, "paseo-plugin.json"), + JSON.stringify({ + id: "hook-failures", + requirements: { paseo: ">=0.14.0-beta.1" }, + }), + ); + await writeFile( + path.join(directory, "index.server.ts"), + ` +export default function contribute(server) { + server.addHook("workspace.create.before", async ({ request }) => { + if (request.title === "reject") throw new Error("waiting hook rejected"); + return request; + }); + server.addHook("workspace.create.after", async () => { + throw new Error("notification rejected"); + }); + server.addHook("workspace.create.after", async ({ workspace }) => { + console.log("Later notification for " + workspace.id); + }); + return () => {}; +}`, + ); + await client.connect(); + await client.patchDaemonConfig({ pluginsEnabled: true }); + await client.installDirectoryPlugin(directory); + const failed = await client.createWorkspace({ + title: "reject", + source: { kind: "directory", path: directory }, + }); + expect(failed.workspace).toBeNull(); + expect(failed.error).toContain( + "Plugin hook-failures workspace.create.before failed: waiting hook rejected", + ); + const created = await client.createWorkspace({ + source: { kind: "directory", path: directory }, + }); + expect(created.error).toBeNull(); + expect(created.workspace?.workspaceDirectory).toBe(directory); + await expect + .poll(async () => + (await client.getPluginLogs("hook-failures")).map(({ message }) => message).join("\n"), + ) + .toContain("Later notification for " + created.workspace!.id); + const messages = (await client.getPluginLogs("hook-failures")) + .map(({ message }) => message) + .join("\n"); + expect(messages).toContain("Lifecycle hook workspace.create.after failed"); + expect(messages).toContain("notification rejected"); + expect(messages).toContain("Later notification for " + created.workspace!.id); + } finally { + await client.close(); + await daemon.close(); + await rm(directory, { recursive: true, force: true }); + } +}, 60_000); + +test.each([false, true])( + "worktree creation waits for plugins before its first agent and rolls back failures (firstAgentContext: %s)", + async (withFirstAgentContext) => { + const root = await mkdtemp(path.join(tmpdir(), "paseo-worktree-hook-")); + const repository = path.join(root, "repository"); + execFileSync("git", ["init", "-b", "main", repository], { stdio: "pipe" }); + execFileSync( + "git", + [ + "-c", + "user.name=Test", + "-c", + "user.email=test@example.com", + "-c", + "commit.gpgsign=false", + "commit", + "--allow-empty", + "-m", + "initial", + ], + { cwd: repository, stdio: "pipe" }, + ); + execFileSync("git", ["checkout", "-b", "plugin-base"], { cwd: repository, stdio: "pipe" }); + await writeFile(path.join(repository, "from-plugin-base.txt"), "base"); + execFileSync("git", ["add", "."], { cwd: repository, stdio: "pipe" }); + execFileSync( + "git", + [ + "-c", + "user.name=Test", + "-c", + "user.email=test@example.com", + "-c", + "commit.gpgsign=false", + "commit", + "-m", + "plugin base", + ], + { cwd: repository, stdio: "pipe" }, + ); + execFileSync("git", ["checkout", "main"], { cwd: repository, stdio: "pipe" }); + const orderFile = path.join(root, "order.jsonl"); + const pluginDirectory = await createProviderPlugin(root, { + acknowledgeClose: true, + hooks: ` + server.addHook("worktree.create.before", async ({ request }) => { + const { appendFile } = await import("node:fs/promises"); + await appendFile(${JSON.stringify(orderFile)}, JSON.stringify({ hook: "worktree.create.before", request }) + "\\n"); + return { ...request, path: ${JSON.stringify(path.join(root, "elsewhere"))} + "/" + request.slug, + branch: request.branch === "accept-hook" ? "plugin-branch" : request.branch, + baseRef: request.branch === "accept-hook" ? "plugin-base" : request.baseRef }; + }); + server.addHook("worktree.create.after", async ({ worktree }) => { + const { appendFile, writeFile } = await import("node:fs/promises"); + await appendFile(${JSON.stringify(orderFile)}, JSON.stringify({ hook: "worktree.create.after", worktree }) + "\\n"); + if (worktree.branch === "reject-hook") throw new Error("worktree rejected"); + await writeFile(worktree.path + "/plugin-ready.txt", "ready"); + }); + server.addHook("workspace.create.after", async () => { + const { appendFile } = await import("node:fs/promises"); + await appendFile(${JSON.stringify(orderFile)}, JSON.stringify({ hook: "workspace.create.after" }) + "\\n"); + }); + server.addHook("agent.create.before", async ({ request }) => { + const { appendFile } = await import("node:fs/promises"); + await appendFile(${JSON.stringify(orderFile)}, JSON.stringify({ hook: "agent.create.before" }) + "\\n"); + return request; + }); + server.addHook("agent.open.before", async ({ request }) => { + const { readFile } = await import("node:fs/promises"); + const contents = await readFile(request.cwd + "/plugin-ready.txt", "utf8"); + if (contents !== "ready") throw new Error("missing plugin output"); + console.log(JSON.stringify({ hook: "first-agent-ready", agentId: request.agentId, cwd: request.cwd, contents })); + return request; + });`, + }); + let daemon = await createTestPaseoDaemon({ + paseoHomeRoot: path.join(root, "state"), + cleanup: false, + }); + let client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` }); + try { + await client.connect(); + await client.patchDaemonConfig({ pluginsEnabled: true }); + const installed = await client.installDirectoryPlugin(pluginDirectory); + expect(installed.status).toBe("running"); + const created = await client.createWorkspace({ + ...(withFirstAgentContext + ? { + firstAgentContext: { prompt: "Check the initialized worktree" }, + agent: { + provider: PROVIDER_ID, + cwd: repository, + initialPrompt: "Check the initialized worktree", + }, + } + : {}), + source: { + kind: "worktree", + cwd: repository, + branchName: "accept-hook", + worktreeSlug: "accept-hook", + }, + }); + expect(created.error).toBeNull(); + const cwd = created.workspace!.workspaceDirectory; + expect(created.workspace!.gitRuntime?.currentBranch).toBe("plugin-branch"); + const persisted = JSON.parse( + await readFile(path.join(daemon.paseoHome, "projects", "workspaces.json"), "utf8"), + ); + expect(persisted).toContainEqual( + expect.objectContaining({ + workspaceId: created.workspace!.id, + branch: "plugin-branch", + baseBranch: "refs/heads/plugin-base", + worktreeRoot: cwd, + }), + ); + expect(cwd).toBe(path.join(await realpath(root), "elsewhere", "accept-hook")); + expect(await readFile(path.join(cwd, "from-plugin-base.txt"), "utf8")).toBe("base"); + expect( + execFileSync("git", ["branch", "--show-current"], { cwd, encoding: "utf8" }).trim(), + ).toBe("plugin-branch"); + expect(await readFile(path.join(cwd, "plugin-ready.txt"), "utf8")).toBe("ready"); + const firstAgent = withFirstAgentContext + ? created.agent! + : await client.createAgent({ + provider: PROVIDER_ID, + cwd, + workspaceId: created.workspace!.id, + }); + expect(firstAgent).toMatchObject({ + cwd, + workspaceId: created.workspace!.id, + provider: PROVIDER_ID, + }); + await expect + .poll(async () => + (await client.getPluginLogs("shutdown-provider-plugin")) + .filter(({ message }) => message.startsWith('{"hook":"first-agent-ready"')) + .map(({ message }) => JSON.parse(message)), + ) + .toContainEqual({ + hook: "first-agent-ready", + agentId: firstAgent.id, + cwd, + contents: "ready", + }); + const records = (await readFile(orderFile, "utf8")) + .trim() + .split("\n") + .map((line) => JSON.parse(line)); + expect(records.map((record) => record.hook)).toEqual([ + "worktree.create.before", + "worktree.create.after", + "workspace.create.after", + "agent.create.before", + ]); + expect({ + ...records[1].worktree, + sourceCheckout: await realpath(records[1].worktree.sourceCheckout), + }).toEqual({ + path: cwd, + branch: "plugin-branch", + sourceCheckout: await realpath(repository), + }); + expect((await client.fetchWorkspaces()).entries.map((workspace) => workspace.id)).toContain( + created.workspace!.id, + ); + await client.archiveWorkspace(created.workspace!.id); + await expect(stat(cwd)).rejects.toMatchObject({ code: "ENOENT" }); + const hookRecordsBeforeRestore = await readFile(orderFile, "utf8"); + await client.close(); + await daemon.close(); + daemon = await createTestPaseoDaemon({ + paseoHomeRoot: path.join(root, "state"), + cleanup: false, + pluginsEnabled: true, + plugins: { + "shutdown-provider-plugin": { source: "directory", path: pluginDirectory, enabled: true }, + }, + }); + client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` }); + await client.connect(); + await client.restoreWorkspace(created.workspace!.id); + expect(await readFile(path.join(cwd, "from-plugin-base.txt"), "utf8")).toBe("base"); + expect(await readFile(orderFile, "utf8")).toBe(hookRecordsBeforeRestore); + const beforeFailure = await client.fetchWorkspaces(); + const worktreesBeforeFailure = execFileSync("git", ["worktree", "list", "--porcelain"], { + cwd: repository, + encoding: "utf8", + }); + const rejected = await client.createWorkspace({ + source: { + kind: "worktree", + cwd: repository, + branchName: "reject-hook", + worktreeSlug: "reject-hook", + }, + }); + expect(rejected.workspace).toBeNull(); + expect(rejected.error).toContain( + "Plugin shutdown-provider-plugin worktree.create.after failed: worktree rejected", + ); + const failedRecords = (await readFile(orderFile, "utf8")) + .trim() + .split("\n") + .map((line) => JSON.parse(line)); + const failedPath = failedRecords.at(-1).worktree.path; + await expect(stat(failedPath)).rejects.toMatchObject({ code: "ENOENT" }); + expect((await client.fetchWorkspaces()).entries.map(({ id }) => id).sort()).toEqual( + beforeFailure.entries.map(({ id }) => id).sort(), + ); + expect( + execFileSync("git", ["worktree", "list", "--porcelain"], { + cwd: repository, + encoding: "utf8", + }), + ).toBe(worktreesBeforeFailure); + } finally { + await client.close(); + await daemon.close(); + await rm(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }); + } + }, + 60_000, +); + +test("worktree before hook rejects unsafe destinations with plugin attribution before creating branches", async () => { + const root = await mkdtemp(path.join(tmpdir(), "paseo-worktree-before-invalid-")); + const repository = path.join(root, "repository"); + execFileSync("git", ["init", "-b", "main", repository], { stdio: "pipe" }); + execFileSync( + "git", + [ + "-c", + "user.name=Test", + "-c", + "user.email=test@example.com", + "-c", + "commit.gpgsign=false", + "commit", + "--allow-empty", + "-m", + "initial", + ], + { cwd: repository, stdio: "pipe" }, + ); + const occupied = path.join(root, "occupied"); + await mkdir(occupied); + const destinations = [ + occupied, + "relative/path", + repository, + path.join(repository, ".git", "worktree"), + root, + path.parse(root).root, + (await import("node:os")).homedir(), + ]; + const pluginDirectory = await createProviderPlugin(root, { + acknowledgeClose: true, + hooks: ` + server.addHook("worktree.create.before", async ({ request }) => { + if (request.branch === "throws") throw new Error("creation denied"); + if (request.branch === "readonly") return { ...request, repoRoot: "/different-repository" }; + return { ...request, path: ${JSON.stringify(destinations)}[Number(request.branch.slice(4))] }; + });`, + }); + const daemon = await createTestPaseoDaemon(); + const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` }); + try { + await client.connect(); + await client.patchDaemonConfig({ pluginsEnabled: true }); + await client.installDirectoryPlugin(pluginDirectory); + for (const branchName of [ + ...destinations.map((_, index) => `bad-${index}`), + "throws", + "readonly", + ]) { + const created = await client.createWorkspace({ + source: { kind: "worktree", cwd: repository, branchName, worktreeSlug: branchName }, + }); + expect(created.workspace).toBeNull(); + expect(created.error).toContain( + "Plugin shutdown-provider-plugin worktree.create.before failed:", + ); + expect( + execFileSync("git", ["branch", "--format=%(refname:short)"], { + cwd: repository, + encoding: "utf8", + }).trim(), + ).toBe("main"); + expect( + execFileSync("git", ["worktree", "list", "--porcelain"], { + cwd: repository, + encoding: "utf8", + }).match(/^worktree /gm), + ).toHaveLength(1); + } + expect((await client.fetchWorkspaces()).entries).toEqual([]); + } finally { + await client.close(); + await daemon.close(); + await rm(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }); + } +}, 60_000); + +test("the placement example creates a sibling worktree, opens its first agent there, lists and archives it", async () => { + const root = await mkdtemp(path.join(tmpdir(), "paseo-placement-example-")); + const repository = path.join(root, "repository"); + execFileSync("git", ["init", "-b", "main", repository], { stdio: "pipe" }); + execFileSync( + "git", + [ + "-c", + "user.name=Test", + "-c", + "user.email=test@example.com", + "-c", + "commit.gpgsign=false", + "commit", + "--allow-empty", + "-m", + "initial", + ], + { cwd: repository, stdio: "pipe" }, + ); + const providerDirectory = await createProviderPlugin(root, { + acknowledgeClose: true, + reportOpen: true, + }); + const daemon = await createTestPaseoDaemon(); + const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` }); + try { + await client.connect(); + await client.patchDaemonConfig({ pluginsEnabled: true }); + await client.installDirectoryPlugin(providerDirectory); + const installed = await client.installDirectoryPlugin( + fileURLToPath(new URL("../../../../../plugin-examples/worktree-placement", import.meta.url)), + ); + expect(installed.status).toBe("running"); + const created = await client.createWorkspace({ + source: { + kind: "worktree", + cwd: repository, + branchName: "feature/x", + worktreeSlug: "feature-x", + }, + }); + expect(created.error).toBeNull(); + const cwd = path.join(await realpath(root), "repository.feature-x"); + expect(created.workspace!.workspaceDirectory).toBe(cwd); + expect((await stat(cwd)).isDirectory()).toBe(true); + expect((await client.fetchWorkspaces()).entries.map((workspace) => workspace.id)).toContain( + created.workspace!.id, + ); + const worktrees = await client.getPaseoWorktreeList({ cwd: repository }); + expect(worktrees.error).toBeNull(); + expect(worktrees.worktrees).toContainEqual( + expect.objectContaining({ worktreePath: cwd, branchName: "feature/x" }), + ); + const collision = await client.createWorkspace({ + source: { + kind: "worktree", + cwd: repository, + branchName: "feature/x", + worktreeSlug: "another-slug", + }, + }); + expect(collision.workspace).toBeNull(); + expect(collision.error).toContain("Plugin worktree-placement worktree.create.before failed:"); + expect(collision.error).toContain("already exists"); + const agent = await client.createAgent({ + provider: PROVIDER_ID, + cwd, + workspaceId: created.workspace!.id, + }); + expect(agent.cwd).toBe(cwd); + const logs = await client.getPluginLogs("shutdown-provider-plugin"); + const opened = logs + .filter((entry) => entry.message.startsWith('{"hook":"provider.open"')) + .map((entry) => JSON.parse(entry.message)); + expect(opened.map((entry) => entry.config.cwd)).toContain(cwd); + await client.archiveWorkspace(created.workspace!.id); + await expect(stat(cwd)).rejects.toMatchObject({ code: "ENOENT" }); + } finally { + await client.close(); + await daemon.close(); + await rm(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }); + } +}, 60_000); + +test("worktree includes reach the first agent without copying tracked or unignored files", async () => { + const root = await mkdtemp(path.join(tmpdir(), "paseo-worktree-include-")); + const repository = path.join(root, "repository"); + execFileSync("git", ["init", "-b", "main", repository], { stdio: "pipe" }); + const git = (...args: string[]) => execFileSync("git", args, { cwd: repository, stdio: "pipe" }); + await mkdir(path.join(repository, "config")); + await writeFile(path.join(repository, ".gitignore"), ".env\nconfig/*.local.json\n"); + await writeFile( + path.join(repository, ".worktreeinclude"), + ".env\nconfig/*.local.json\nunignored.txt\n", + ); + await writeFile(path.join(repository, "config/tracked.local.json"), "git version"); + git("add", ".gitignore", ".worktreeinclude"); + git("add", "-f", "config/tracked.local.json"); + git( + "-c", + "user.name=Test", + "-c", + "user.email=test@example.com", + "-c", + "commit.gpgsign=false", + "commit", + "-m", + "initial", + ); + await writeFile(path.join(repository, ".env"), "SECRET=source"); + await writeFile(path.join(repository, "config/app.local.json"), "local config"); + await writeFile(path.join(repository, "config/tracked.local.json"), "uncommitted source version"); + await writeFile(path.join(repository, "unignored.txt"), "unignored source"); + const observed = path.join(root, "observed.json"); + const pluginDirectory = await createProviderPlugin(root, { + acknowledgeClose: true, + hooks: ` + server.addHook("agent.open.before", async ({ request }) => { + const { readFile, writeFile } = await import("node:fs/promises"); + const contents = await Promise.all([".env", "config/app.local.json", "config/tracked.local.json"].map(file => readFile(request.cwd + "/" + file, "utf8"))); + await writeFile(${JSON.stringify(observed)}, JSON.stringify(contents)); + });`, + }); + const daemon = await createTestPaseoDaemon({ builtinPlugins: new BuiltinPluginLoader() }); + const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` }); + try { + await client.connect(); + await client.patchDaemonConfig({ pluginsEnabled: true }); + expect((await client.installDirectoryPlugin(pluginDirectory)).status).toBe("running"); + const created = await client.createWorkspace({ + source: { kind: "worktree", cwd: repository, branchName: "include", worktreeSlug: "include" }, + }); + expect(created.error).toBeNull(); + await client.createAgent({ + provider: PROVIDER_ID, + cwd: created.workspace!.workspaceDirectory, + workspaceId: created.workspace!.id, + }); + expect(JSON.parse(await readFile(observed, "utf8"))).toEqual([ + "SECRET=source", + "local config", + "git version", + ]); + await expect( + stat(path.join(created.workspace!.workspaceDirectory, "unignored.txt")), + ).rejects.toMatchObject({ code: "ENOENT" }); + + const sourceWorktree = created.workspace!.workspaceDirectory; + await writeFile(path.join(sourceWorktree, ".env"), "SECRET=worktree"); + await writeFile(path.join(sourceWorktree, "config/app.local.json"), "worktree config"); + const nested = await client.createWorkspace({ + source: { + kind: "worktree", + cwd: sourceWorktree, + branchName: "nested", + worktreeSlug: "nested", + }, + }); + expect(nested.error).toBeNull(); + await client.createAgent({ + provider: PROVIDER_ID, + cwd: nested.workspace!.workspaceDirectory, + workspaceId: nested.workspace!.id, + }); + expect(JSON.parse(await readFile(observed, "utf8"))).toEqual([ + "SECRET=worktree", + "worktree config", + "git version", + ]); + + execFileSync("git", ["add", "-f", ".env"], { cwd: sourceWorktree, stdio: "pipe" }); + execFileSync( + "git", + [ + "-c", + "user.name=Test", + "-c", + "user.email=test@example.com", + "-c", + "commit.gpgsign=false", + "commit", + "-m", + "commit branch env", + ], + { cwd: sourceWorktree, stdio: "pipe" }, + ); + const existing = await client.createWorkspace({ + source: { + kind: "worktree", + cwd: repository, + baseBranch: "include", + branchName: "existing", + worktreeSlug: "existing", + }, + }); + expect(existing.error).toBeNull(); + await client.createAgent({ + provider: PROVIDER_ID, + cwd: existing.workspace!.workspaceDirectory, + workspaceId: existing.workspace!.id, + }); + expect(JSON.parse(await readFile(observed, "utf8"))).toEqual([ + "SECRET=worktree", + "local config", + "git version", + ]); + + await rm(path.join(repository, ".worktreeinclude")); + const noIncludes = await client.createWorkspace({ + source: { + kind: "worktree", + cwd: repository, + baseBranch: "main", + branchName: "no-includes", + worktreeSlug: "no-includes", + }, + }); + expect(noIncludes.error).toBeNull(); + await expect( + stat(path.join(noIncludes.workspace!.workspaceDirectory, ".env")), + ).rejects.toMatchObject({ code: "ENOENT" }); + await expect( + stat(path.join(noIncludes.workspace!.workspaceDirectory, "config/app.local.json")), + ).rejects.toMatchObject({ code: "ENOENT" }); + + await writeFile(path.join(repository, ".worktreeinclude"), ".env\nconfig/*.local.json\n"); + await rm(path.join(sourceWorktree, "config"), { recursive: true }); + await writeFile( + path.join(sourceWorktree, "config"), + "committed file blocks the config directory", + ); + execFileSync("git", ["add", "-A", "config"], { cwd: sourceWorktree, stdio: "pipe" }); + execFileSync( + "git", + [ + "-c", + "user.name=Test", + "-c", + "user.email=test@example.com", + "-c", + "commit.gpgsign=false", + "commit", + "-m", + "block config directory", + ], + { cwd: sourceWorktree, stdio: "pipe" }, + ); + const beforeFailure = await client.fetchWorkspaces(); + const worktreesBeforeFailure = git("worktree", "list", "--porcelain").toString(); + const failed = await client.createWorkspace({ + source: { + kind: "worktree", + cwd: repository, + baseBranch: "include", + branchName: "copy-failure", + worktreeSlug: "copy-failure", + }, + }); + expect(failed.workspace).toBeNull(); + expect(failed.error).toContain("Plugin worktree-include worktree.create.after failed:"); + expect((await client.fetchWorkspaces()).entries.map(({ id }) => id).sort()).toEqual( + beforeFailure.entries.map(({ id }) => id).sort(), + ); + expect(git("worktree", "list", "--porcelain").toString()).toBe(worktreesBeforeFailure); + } finally { + await client.close(); + await daemon.close(); + await rm(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }); + } +}, 60_000); diff --git a/packages/server/src/server/plugins/lifecycle.real.e2e.test.ts b/packages/server/src/server/plugins/lifecycle.real.e2e.test.ts index fc9cfbd84d..40de1215d8 100644 --- a/packages/server/src/server/plugins/lifecycle.real.e2e.test.ts +++ b/packages/server/src/server/plugins/lifecycle.real.e2e.test.ts @@ -6,7 +6,7 @@ import path from "node:path"; import { fileURLToPath } from "node:url"; import pino from "pino"; import { expect, test } from "vitest"; -import type { PluginBeforeRequests, PluginLifecycleEvents } from "@getpaseo/plugin/server"; +import type { PluginHookRequests, PluginHookEvents } from "@getpaseo/plugin/server"; import { ClaudeAgentClient } from "../agent/providers/claude/agent.js"; import { CodexAppServerAgentClient } from "../agent/providers/codex-app-server-agent.js"; import { DaemonClient } from "../test-utils/daemon-client.js"; @@ -14,14 +14,14 @@ import { createTestPaseoDaemon } from "../test-utils/paseo-daemon.js"; type RecordedHook = | { - [Name in keyof PluginLifecycleEvents]: { hook: Name; data: PluginLifecycleEvents[Name] }; - }[keyof PluginLifecycleEvents] + [Name in keyof PluginHookEvents]: { hook: Name; data: PluginHookEvents[Name] }; + }[keyof PluginHookEvents] | { - [Name in keyof PluginBeforeRequests]: { - hook: `before ${Name}`; - data: { request: PluginBeforeRequests[Name] }; + [Name in keyof PluginHookRequests]: { + hook: Name; + data: { request: PluginHookRequests[Name] }; }; - }[keyof PluginBeforeRequests]; + }[keyof PluginHookRequests]; const repoRoot = fileURLToPath(new URL("../../../../../", import.meta.url)); const evidenceDirectory = path.join(repoRoot, ".dev", "lifecycle-proof"); @@ -39,8 +39,8 @@ async function readHooks(client: DaemonClient): Promise { async function endedTurns(client: DaemonClient, agentId: string) { const events = await readHooks(client); - return events.filter((event): event is Extract => { - return event.hook === "agent.turn_ended" && event.data.agent.id === agentId; + return events.filter((event): event is Extract => { + return event.hook === "agent.turn.after" && event.data.agent.id === agentId; }); } @@ -63,7 +63,7 @@ async function waitForPermission(client: DaemonClient, agentId: string, command: const events = await readHooks(client); for (const event of events) { if ( - event.hook === "agent.permission_requested" && + event.hook === "agent.permission.before" && event.data.agent.id === agentId && event.data.request.input?.command === command ) { @@ -111,7 +111,7 @@ test.skipIf(process.platform !== "linux")( }); const logger = pino({ level: "info" }, destination); const daemon = await createTestPaseoDaemon({ - daemonVersion: "0.8.0", + daemonVersion: "0.14.0-beta.1", logger, agentClients: { claude: new ClaudeAgentClient({ logger }), @@ -121,7 +121,7 @@ test.skipIf(process.platform !== "linux")( }); const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws`, - appVersion: "0.8.0", + appVersion: "0.14.0-beta.1", }); const proof: Record = { port: daemon.port, @@ -169,7 +169,7 @@ test.skipIf(process.platform !== "linux")( const approvalId = await waitForPermission(client, agent.id, "git status"); expect(await readHooks(client)).toContainEqual( expect.objectContaining({ - hook: "agent.permission_resolved", + hook: "agent.permission.after", data: expect.objectContaining({ requestId: approvalId, resolution: expect.objectContaining({ behavior: "allow" }), @@ -186,7 +186,7 @@ test.skipIf(process.platform !== "linux")( const deniedId = await waitForPermission(client, agent.id, "rm -rf canary.txt"); expect(await readHooks(client)).toContainEqual( expect.objectContaining({ - hook: "agent.permission_resolved", + hook: "agent.permission.after", data: expect.objectContaining({ requestId: deniedId, resolution: expect.objectContaining({ behavior: "deny" }), @@ -224,7 +224,7 @@ test.skipIf(process.platform !== "linux")( .poll( async () => { return (await readHooks(client)).filter((event) => { - return event.hook === "agent.turn_started" && event.data.agent.id === agent.id; + return event.hook === "agent.turn.before" && event.data.agent.id === agent.id; }).length; }, { timeout: 30_000 }, @@ -278,23 +278,26 @@ test.skipIf(process.platform !== "linux")( ); return [...names].sort(); }) - .toEqual([ - "agent.archived", - "agent.closed", - "agent.created", - "agent.permission_requested", - "agent.permission_resolved", - "agent.turn_ended", - "agent.turn_started", - "before agent.create", - "before agent.session_open", - "before workspace.create", - "workspace.archived", - "workspace.created", - ]); + .toEqual( + [ + "agent.archive.after", + "agent.close.after", + "agent.create.after", + "agent.permission.before", + "agent.permission.after", + "agent.turn.after", + "agent.turn.before", + "agent.create.before", + "agent.open.before", + "worktree.create.after", + "workspace.create.before", + "workspace.archive.after", + "workspace.create.after", + ].sort(), + ); const openReasons = (await readHooks(client)) .filter((event) => { - return event.hook === "before agent.session_open"; + return event.hook === "agent.open.before"; }) .map((event) => { return event.data.request.reason; diff --git a/packages/server/src/server/plugins/lifecycle/handlers.test.ts b/packages/server/src/server/plugins/lifecycle/handlers.test.ts index bafd1f9b94..e17cca1ed5 100644 --- a/packages/server/src/server/plugins/lifecycle/handlers.test.ts +++ b/packages/server/src/server/plugins/lifecycle/handlers.test.ts @@ -1,7 +1,7 @@ import { expect, test } from "vitest"; import { createPaseoApi } from "@getpaseo/client"; import { DaemonClient } from "@getpaseo/client/internal/daemon-client"; -import { PluginHookHandlers } from "./index.js"; +import { validateBeforeResult, PluginHookHandlers } from "./index.js"; const paseo = createPaseoApi( new DaemonClient({ url: "ws://127.0.0.1:1/ws", clientId: "lifecycle-unit" }), @@ -9,18 +9,17 @@ const paseo = createPaseoApi( test("removing an old registration twice preserves a newer registration for the same hook", async () => { const hooks = new PluginHookHandlers(() => {}); - const remove = hooks.before("workspace.create", ({ request }) => { + const remove = hooks.addHook("workspace.create.before", async ({ request }) => { return { ...request, title: "old" }; }); remove(); - hooks.before("workspace.create", ({ request }) => { + hooks.addHook("workspace.create.before", async ({ request }) => { return { ...request, title: "new" }; }); remove(); const output = await hooks.invoke( "operation", - "before", - "workspace.create", + "workspace.create.before", { source: { kind: "directory", path: "/project" }, }, @@ -31,17 +30,17 @@ test("removing an old registration twice preserves a newer registration for the test("before hooks compose returned requests and preserve the original input", async () => { const hooks = new PluginHookHandlers(() => {}); - hooks.before("workspace.create", ({ request }) => { + hooks.addHook("workspace.create.before", async ({ request }) => { return { ...request, title: "first" }; }); - hooks.before("workspace.create", () => { + hooks.addHook("workspace.create.before", async () => { return; }); - hooks.before("workspace.create", ({ request }) => { + hooks.addHook("workspace.create.before", async ({ request }) => { return { ...request, title: request.title + ":second" }; }); const input = { source: { kind: "directory", path: "/project" } }; - expect(await hooks.invoke("operation", "before", "workspace.create", input, paseo)).toEqual({ + expect(await hooks.invoke("operation", "workspace.create.before", input, paseo)).toEqual({ source: { kind: "directory", path: "/project" }, title: "first:second", }); @@ -50,7 +49,7 @@ test("before hooks compose returned requests and preserve the original input", a test("teardown aborts an active callback and removes its registrations", async () => { const hooks = new PluginHookHandlers(() => {}); - hooks.before("workspace.create", async (_input, context) => { + hooks.addHook("workspace.create.before", async (_input, context) => { await new Promise((_resolve, reject) => { context.signal.addEventListener( "abort", @@ -63,8 +62,7 @@ test("teardown aborts an active callback and removes its registrations", async ( }); const invocation = hooks.invoke( "operation", - "before", - "workspace.create", + "workspace.create.before", { source: { kind: "directory", path: "/project" }, }, @@ -72,19 +70,18 @@ test("teardown aborts an active callback and removes its registrations", async ( ); hooks.close(); await expect(invocation).rejects.toThrow("Hook aborted"); - expect(hooks.catalog()).toEqual({ events: [], before: [] }); + expect(hooks.catalog()).toEqual([]); }); test("session-open hooks reject changes to session identity instead of silently ignoring them", async () => { const hooks = new PluginHookHandlers(() => {}); - hooks.before("agent.session_open", ({ request }) => { + hooks.addHook("agent.open.before", async ({ request }) => { return { ...request, provider: "another-provider" }; }); await expect( hooks.invoke( "operation", - "before", - "agent.session_open", + "agent.open.before", { agentId: "agent", workspaceId: "workspace", @@ -96,22 +93,22 @@ test("session-open hooks reject changes to session identity instead of silently title: null, labels: {}, tools: [], + mcpServers: {}, }, paseo, ), - ).rejects.toThrow("agent.session_open hooks can only change env"); + ).rejects.toThrow("agent.open.before hooks can only change env"); }); test.each([{ title: "Changed" }, { labels: { changed: "true" } }])( "session-open targeting metadata is read-only: %j", async (patch) => { const hooks = new PluginHookHandlers(() => {}); - hooks.before("agent.session_open", ({ request }) => ({ ...request, ...patch })); + hooks.addHook("agent.open.before", async ({ request }) => ({ ...request, ...patch })); await expect( hooks.invoke( "operation", - "before", - "agent.session_open", + "agent.open.before", { agentId: "agent", workspaceId: null, @@ -120,12 +117,139 @@ test.each([{ title: "Changed" }, { labels: { changed: "true" } }])( title: "Original", labels: {}, tools: [], + mcpServers: {}, env: {}, reason: "create", purpose: "interactive", }, paseo, ), - ).rejects.toThrow("agent.session_open hooks can only change env and tools"); + ).rejects.toThrow("agent.open.before hooks can only change env, tools, and mcpServers"); }, ); + +test("new request-changing registrations compose with legacy registrations in registration order", async () => { + const hooks = new PluginHookHandlers(() => {}); + hooks.before("workspace.create", ({ request }) => ({ ...request, title: "legacy" })); + hooks.addHook("workspace.create.before", async ({ request }) => ({ + ...request, + title: request.title + ":new", + })); + hooks.before("workspace.create", ({ request }) => ({ + ...request, + title: request.title + ":last", + })); + expect( + await hooks.invoke( + "operation", + "workspace.create.before", + { + source: { kind: "directory", path: "/project" }, + }, + paseo, + ), + ).toEqual({ source: { kind: "directory", path: "/project" }, title: "legacy:new:last" }); +}); + +test.each(["agent.session_open", "agent.create.prepare", "nonsense"])( + "addHook rejects unsupported name %s at registration", + (name) => { + const hooks = new PluginHookHandlers(() => {}); + // @ts-expect-error Runtime validation also protects untyped plugins. + expect(() => hooks.addHook(name, async () => {})).toThrow(name); + }, +); + +test.each([ + ["workspace.create", "workspace.create.before"], + ["workspace.created", "workspace.create.after"], + ["workspace.archived", "workspace.archive.after"], + ["agent.create", "agent.create.before"], + ["agent.created", "agent.create.after"], + ["agent.session_open", "agent.open.before"], + ["agent.closed", "agent.close.after"], + ["agent.archived", "agent.archive.after"], + ["agent.turn_started", "agent.turn.before"], + ["agent.turn_ended", "agent.turn.after"], + ["agent.permission_requested", "agent.permission.before"], + ["agent.permission_resolved", "agent.permission.after"], +] as const)("legacy %s registers only %s across the process boundary", (oldName, newName) => { + const hooks = new PluginHookHandlers(() => {}); + const handler = async () => {}; + const remove = + oldName === "workspace.create" || oldName === "agent.create" || oldName === "agent.session_open" + ? hooks.before(oldName, handler) + : hooks.on(oldName, handler); + hooks.addHook(newName, async () => {}); + expect(hooks.catalog()).toEqual([newName]); + remove(); + expect(hooks.catalog()).toEqual([newName]); + hooks.close(); + expect(hooks.catalog()).toEqual([]); +}); + +test("legacy notifications and addHook share payloads, registration order, and cleanup", async () => { + const hooks = new PluginHookHandlers(() => {}); + const received: unknown[] = []; + const remove = hooks.on("workspace.created", (event) => { + received.push(["old", event]); + }); + hooks.addHook("workspace.create.after", async (event) => { + received.push(["new", event]); + }); + const payload = { + workspace: { + id: "workspace", + projectId: "project", + cwd: "/project", + name: null, + archivedAt: null, + }, + }; + await hooks.invoke("first", "workspace.create.after", payload, paseo); + remove(); + remove(); + await hooks.invoke("second", "workspace.create.after", payload, paseo); + expect(received).toEqual([ + ["old", payload], + ["new", payload], + ["new", payload], + ]); +}); + +test("a waiting after hook propagates failures and stops later handlers", async () => { + const hooks = new PluginHookHandlers(() => {}); + const received: string[] = []; + hooks.addHook("worktree.create.after", async ({ worktree }) => { + received.push(worktree.path); + throw new Error("cannot initialize worktree"); + }); + hooks.addHook("worktree.create.after", async () => { + received.push("unexpected later handler"); + }); + await expect( + hooks.invoke( + "worktree", + "worktree.create.after", + { + worktree: { path: "/worktree", branch: "feature", sourceCheckout: "/source" }, + }, + paseo, + ), + ).rejects.toThrow("cannot initialize worktree"); + expect(received).toEqual(["/worktree"]); +}); + +test("checkout-branch hooks reject a branch-off baseRef", async () => { + const request = { + kind: "checkout-branch" as const, + repoRoot: "/repo", + sourceCheckout: "/repo", + branch: "feature", + slug: "feature", + path: "/work/feature", + }; + await expect( + validateBeforeResult("worktree.create.before", request, { ...request, baseRef: "main" }), + ).rejects.toThrow(/baseRef/); +}); diff --git a/packages/server/src/server/plugins/lifecycle/index.ts b/packages/server/src/server/plugins/lifecycle/index.ts index 2b379eb7f8..d4f58cc78c 100644 --- a/packages/server/src/server/plugins/lifecycle/index.ts +++ b/packages/server/src/server/plugins/lifecycle/index.ts @@ -1,3 +1,8 @@ +import { validateBranchSlug } from "@getpaseo/protocol/branch-slug"; +import { + createLifecycleRegistration, + pluginHookRegistry, +} from "@getpaseo/plugin/internal/lifecycle"; import { isDeepStrictEqual } from "node:util"; import { serializeAgentTool, @@ -11,38 +16,83 @@ import { z } from "zod"; import { CreateAgentRequestMessageSchema } from "@getpaseo/protocol/messages"; import type { PluginHookAgent, + PluginHookPayload, PluginHookContext, PluginLifecycleRegistration, } from "@getpaseo/plugin/server"; import { PARENT_AGENT_ID_LABEL } from "@getpaseo/protocol/agent-labels"; import type { - PluginBeforeRequests, + PluginHookRequests, PluginHookWorkspace, - PluginLifecycleEvents, + PluginHookEvents, } from "@getpaseo/plugin/server"; import { WorkspaceCreateRequestSchema } from "@getpaseo/protocol/messages"; import type { PersistedWorkspaceRecord } from "../../workspace-registry.js"; -export type PluginWireBeforeRequests = Omit & { - "agent.session_open": SessionOpenWireRequest; +export type PluginWireBeforeRequests = Omit & { + "agent.open.before": SessionOpenWireRequest; }; -export const lifecycleEventNames = [ - "agent.created", - "agent.closed", - "agent.turn_started", - "agent.turn_ended", - "agent.permission_requested", - "agent.permission_resolved", - "agent.archived", - "workspace.created", - "workspace.archived", -] as const; -export const beforeHookNames = ["agent.create", "agent.session_open", "workspace.create"] as const; +/** Daemon-only results; ownership never crosses the plugin process boundary. */ +export type PluginBeforeResults = PluginWireBeforeRequests & { + "agent.open.before": SessionOpenWireRequest & { mcpServerOwners?: Record }; +}; + +const worktreeRequestFields = { + repoRoot: z.string(), + sourceCheckout: z.string(), + branch: z.string().min(1), + slug: z.string().refine((value) => validateBranchSlug(value).valid, "Invalid worktree slug"), + path: z.string().min(1), +}; +const changeRequestFields = { + headRef: z.string().min(1), + headRepositoryOwner: z.string().optional(), + checkoutRefs: z + .array(z.object({ remoteName: z.string().optional(), remoteRef: z.string() })) + .optional(), + pushRemoteUrl: z.string().optional(), + trackOriginHead: z.boolean().optional(), +}; +const worktreeRequestSchema = z.discriminatedUnion("kind", [ + z + .object({ ...worktreeRequestFields, kind: z.literal("branch-off"), baseRef: z.string().min(1) }) + .strict(), + z + .object({ + ...worktreeRequestFields, + kind: z.literal("checkout-branch"), + }) + .strict(), + z + .object({ + ...worktreeRequestFields, + ...changeRequestFields, + kind: z.literal("checkout-change-request"), + baseRef: z.string().min(1), + forge: z.string(), + changeRequestNumber: z.number().int().positive(), + headRepository: z.string().optional(), + }) + .strict(), + z + .object({ + ...worktreeRequestFields, + ...changeRequestFields, + kind: z.literal("checkout-github-pr"), + baseRef: z.string().min(1), + githubPrNumber: z.number().int().positive(), + }) + .strict(), +]); const beforeSchemas = { - "agent.create": CreateAgentRequestMessageSchema.pick({ config: true, env: true }).strict(), - "agent.session_open": z + "worktree.create.before": worktreeRequestSchema, + "agent.create.before": CreateAgentRequestMessageSchema.pick({ + config: true, + env: true, + }).strict(), + "agent.open.before": z .object({ agentId: z.string(), workspaceId: z.string().nullable(), @@ -54,12 +104,16 @@ const beforeSchemas = { labels: z.record(z.string(), z.string()), tools: z.array(agentToolMetadataSchema), env: z.record(z.string(), z.string()), + mcpServers: CreateAgentRequestMessageSchema.shape.config.shape.mcpServers.unwrap(), }) .strict(), - "workspace.create": WorkspaceCreateRequestSchema.omit({ type: true, requestId: true }).strict(), + "workspace.create.before": WorkspaceCreateRequestSchema.omit({ + type: true, + requestId: true, + }).strict(), }; -const sessionOpenLocalResultSchema = beforeSchemas["agent.session_open"].extend({ +const sessionOpenLocalResultSchema = beforeSchemas["agent.open.before"].extend({ tools: z.array( z.custom( (tool) => @@ -73,14 +127,15 @@ const sessionOpenLocalResultSchema = beforeSchemas["agent.session_open"].extend( }); export interface PluginLifecycle { - emit( - name: Name, - event: PluginLifecycleEvents[Name], - ): void; + wait( + name: "worktree.create.after", + payload: PluginHookPayload<"worktree.create.after">, + ): Promise; + emit(name: Name, event: PluginHookEvents[Name]): void; before( name: Name, request: PluginWireBeforeRequests[Name], - ): Promise; + ): Promise; } export function validateBeforeRequest( @@ -124,32 +179,32 @@ export function publishAgentStream( event: AgentStreamEvent, ): void { if (event.type === "turn_started") { - lifecycle.emit("agent.turn_started", { agent, turnId: event.turnId ?? null }); + lifecycle.emit("agent.turn.before", { agent, turnId: event.turnId ?? null }); } else if (event.type === "turn_completed") { - lifecycle.emit("agent.turn_ended", { + lifecycle.emit("agent.turn.after", { agent, turnId: event.turnId ?? null, timeline: [], outcome: { kind: "completed" }, }); } else if (event.type === "turn_failed") { - lifecycle.emit("agent.turn_ended", { + lifecycle.emit("agent.turn.after", { agent, turnId: event.turnId ?? null, timeline: [], outcome: { kind: "failed", error: { message: event.error, code: event.code } }, }); } else if (event.type === "turn_canceled") { - lifecycle.emit("agent.turn_ended", { + lifecycle.emit("agent.turn.after", { agent, turnId: event.turnId ?? null, timeline: [], outcome: { kind: "canceled", reason: event.reason }, }); } else if (event.type === "permission_requested") { - lifecycle.emit("agent.permission_requested", { agent, request: event.request }); + lifecycle.emit("agent.permission.before", { agent, request: event.request }); } else if (event.type === "permission_resolved") { - lifecycle.emit("agent.permission_resolved", { + lifecycle.emit("agent.permission.after", { agent, requestId: event.requestId, resolution: event.resolution, @@ -157,15 +212,15 @@ export function publishAgentStream( } } -export function validateBeforeResult( +export async function validateBeforeResult( name: Name, input: PluginWireBeforeRequests[Name], output: unknown, -): PluginWireBeforeRequests[Name] { +): Promise { const result = validateBeforeRequest(name, output); - if (name === "agent.session_open") { - const previous = beforeSchemas["agent.session_open"].parse(input); - const next = beforeSchemas["agent.session_open"].parse(result); + if (name === "agent.open.before") { + const previous = beforeSchemas["agent.open.before"].parse(input); + const next = beforeSchemas["agent.open.before"].parse(result); if ( previous.agentId !== next.agentId || previous.workspaceId !== next.workspaceId || @@ -176,14 +231,21 @@ export function validateBeforeResult unknown; export class PluginHookHandlers implements PluginLifecycleRegistration { - private readonly events = new Map>(); - private readonly transforms = new Map>(); + private readonly handlers = new Map>(); private readonly active = new Map(); private readonly changed: () => void; @@ -203,29 +264,24 @@ export class PluginHookHandlers implements PluginLifecycleRegistration { constructor(changed: () => void, agentTools?: PluginAgentTools) { this.agentTools = agentTools; this.changed = changed; + const registration = createLifecycleRegistration((name, handler) => + this.register(name, handler as Handler), + ); + this.addHook = registration.addHook; + this.on = registration.on; + this.before = registration.before; } - readonly on: PluginLifecycleRegistration["on"] = (name, handler) => { - if (!lifecycleEventNames.includes(name)) { - throw new Error(`Unknown lifecycle event: ${name}`); - } - return this.register(this.events, name, handler as Handler); - }; + readonly addHook: PluginLifecycleRegistration["addHook"]; + readonly on: PluginLifecycleRegistration["on"]; + readonly before: PluginLifecycleRegistration["before"]; - readonly before: PluginLifecycleRegistration["before"] = (name, handler) => { - if (!beforeHookNames.includes(name)) { - throw new Error(`Unknown before hook: ${name}`); - } - return this.register(this.transforms, name, handler as Handler); - }; - - catalog(): { events: string[]; before: string[] } { - return { events: [...this.events.keys()], before: [...this.transforms.keys()] }; + catalog(): string[] { + return [...this.handlers.keys()]; } async invoke( id: string, - kind: "event" | "before", name: string, input: unknown, paseo: PluginHookContext["paseo"], @@ -233,34 +289,32 @@ export class PluginHookHandlers implements PluginLifecycleRegistration { const controller = new AbortController(); this.active.set(id, controller); try { - if (kind === "before") { - if ( - !beforeHookNames.includes( - name as keyof import("@getpaseo/plugin/server").PluginBeforeRequests, - ) - ) { - throw new Error(`Unknown before hook: ${name}`); - } - const hookName = name as keyof import("@getpaseo/plugin/server").PluginBeforeRequests; - if (hookName === "agent.session_open") { + if (Object.hasOwn(beforeSchemas, name)) { + const hookName = name as keyof PluginHookRequests; + if (hookName === "agent.open.before") { return await this.openSession(input, { paseo, signal: controller.signal }); } let request = validateBeforeRequest(hookName, input); - for (const handler of this.transforms.get(name) ?? []) { + for (const handler of this.handlers.get(name) ?? []) { controller.signal.throwIfAborted(); const result = await handler( { request: structuredClone(request) }, { paseo, signal: controller.signal }, ); - if (result !== undefined) request = validateBeforeResult(hookName, request, result); + if (result !== undefined) request = await validateBeforeResult(hookName, request, result); } return request; } - for (const handler of this.events.get(name) ?? []) { + for (const handler of this.handlers.get(name) ?? []) { controller.signal.throwIfAborted(); try { await handler(structuredClone(input), { paseo, signal: controller.signal }); } catch (error) { + if ( + Object.hasOwn(pluginHookRegistry, name) && + pluginHookRegistry[name as keyof typeof pluginHookRegistry].waits + ) + throw error; console.error(`Lifecycle hook ${name} failed`, error); } } @@ -274,10 +328,10 @@ export class PluginHookHandlers implements PluginLifecycleRegistration { input: unknown, context: PluginHookContext, ): Promise { - let request = validateBeforeRequest("agent.session_open", input); + let request = validateBeforeRequest("agent.open.before", input); this.agentTools?.detach(request.agentId); let tools: AgentToolDefinition[] = []; - for (const handler of this.transforms.get("agent.session_open") ?? []) { + for (const handler of this.handlers.get("agent.open.before") ?? []) { context.signal.throwIfAborted(); const result = await handler( { request: { ...structuredClone(request), tools: [...tools] } }, @@ -286,12 +340,17 @@ export class PluginHookHandlers implements PluginLifecycleRegistration { if (result === undefined) continue; const local = sessionOpenLocalResultSchema.parse(result); const metadata = local.tools.map(serializeAgentTool); - request = validateBeforeResult("agent.session_open", request, { ...local, tools: metadata }); + request = await validateBeforeResult("agent.open.before", request, { + ...local, + tools: metadata, + }); tools = local.tools; } context.signal.throwIfAborted(); - if (request.purpose === "history") request.tools = []; - else this.agentTools?.attach(request.agentId, tools); + if (request.purpose === "history") { + request.tools = []; + request.mcpServers = {}; + } else this.agentTools?.attach(request.agentId, tools); return request; } @@ -303,19 +362,14 @@ export class PluginHookHandlers implements PluginLifecycleRegistration { for (const controller of this.active.values()) { controller.abort(); } - this.events.clear(); - this.transforms.clear(); + this.handlers.clear(); } - private register( - registry: Map>, - name: string, - handler: Handler, - ): () => void { - let handlers = registry.get(name); + private register(name: string, handler: Handler): () => void { + let handlers = this.handlers.get(name); if (!handlers) { handlers = new Set(); - registry.set(name, handlers); + this.handlers.set(name, handlers); } handlers.add(handler); this.changed(); @@ -324,7 +378,7 @@ export class PluginHookHandlers implements PluginLifecycleRegistration { return; } if (handlers.size === 0) { - registry.delete(name); + this.handlers.delete(name); } this.changed(); }; diff --git a/packages/server/src/server/plugins/managed-source.posix.test.ts b/packages/server/src/server/plugins/managed-source.posix.test.ts index 466780b79a..7b694f1ef3 100644 --- a/packages/server/src/server/plugins/managed-source.posix.test.ts +++ b/packages/server/src/server/plugins/managed-source.posix.test.ts @@ -61,10 +61,24 @@ describe("managed Git plugin sources", () => { roots.push(home); const sources = new ManagedPluginSources(home); - const failure = sources.prepareInstall({ - source: "git:https://oauth2:super-secret@127.0.0.1:1/missing.git", + // Own the failure response instead of relying on a closed port and OS connect timing. + const server = createServer((_request, response) => { + response.writeHead(500, { "Content-Type": "text/plain" }); + response.end("clone rejected for oauth2:super-secret\n"); }); - await expect(failure).rejects.not.toThrow(/oauth2|super-secret/); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const address = server.address() as { port: number }; + try { + const failure = sources.prepareInstall({ + source: `git:http://oauth2:super-secret@127.0.0.1:${address.port}/missing.git`, + }); + await expect(failure).rejects.toThrow("500"); + await expect(failure).rejects.toThrow("clone rejected for [redacted]:[redacted]"); + await expect(failure).rejects.not.toThrow(/oauth2|super-secret/); + } finally { + server.closeAllConnections(); + await new Promise((resolve) => server.close(() => resolve())); + } }); it("normalizes explicit GitHub and Git identifiers to the same Git source", async () => { diff --git a/packages/server/src/server/plugins/plugin-paseo-api.e2e.test.ts b/packages/server/src/server/plugins/plugin-paseo-api.e2e.test.ts index cad97ce743..042388447b 100644 --- a/packages/server/src/server/plugins/plugin-paseo-api.e2e.test.ts +++ b/packages/server/src/server/plugins/plugin-paseo-api.e2e.test.ts @@ -1,6 +1,6 @@ +import { measureMainThreadWork } from "../../test-utils/main-thread-work.js"; import { execFile } from "node:child_process"; import { promisify } from "node:util"; -import { performance } from "node:perf_hooks"; import pino from "pino"; import { createPaseoDaemon } from "../bootstrap.js"; import { loadConfig } from "../config.js"; @@ -231,21 +231,12 @@ test("password-protected config reload preserves startup auth and session constr await client.fetchAgents({ subscribe: {} }); const configPath = path.join(home, "config.json"); await writeFile(configPath, JSON.stringify({ daemon: { browserTools: { enabled: true } } })); - let longestGap = 0; - let previous = performance.now(); - const probe = setInterval(() => { - const now = performance.now(); - longestGap = Math.max(longestGap, now - previous); - previous = now; - }, 1); - try { - const reloaded = await client.reloadDaemonConfig(); - longestGap = Math.max(longestGap, performance.now() - previous); - expect(reloaded.appliedPaths).toContain("daemon.browserTools.enabled"); - expect(longestGap).toBeLessThan(50); - } finally { - clearInterval(probe); - } + const { result: reloaded, blockingMs } = await measureMainThreadWork( + "daemon config reload main-thread work", + () => client.reloadDaemonConfig(), + ); + expect(reloaded.appliedPaths).toContain("daemon.browserTools.enabled"); + expect(blockingMs).toBeLessThan(50); expect((await client.getDaemonConfig()).config.browserTools.enabled).toBe(true); // A new physical session uses ready daemon state; corrupt config is reported only by an explicit read. await writeFile(configPath, "invalid JSON"); diff --git a/packages/server/src/server/plugins/plugin-process-protocol.ts b/packages/server/src/server/plugins/plugin-process-protocol.ts index c3fa5dda26..e582387d48 100644 --- a/packages/server/src/server/plugins/plugin-process-protocol.ts +++ b/packages/server/src/server/plugins/plugin-process-protocol.ts @@ -55,7 +55,7 @@ export type PluginProcessRequest = providerId: string; options: ProviderCatalogOptions; } - | { type: "hook"; requestId: string; kind: "event" | "before"; name: string; input: unknown } + | { type: "hook"; requestId: string; name: string; input: unknown } | { type: "hook.cancel"; requestId: string } | { type: "usage.fetch"; requestId: string; sourceId: string; input: unknown } | { type: "usage.discover"; requestId: string; sourceId: string; scope: UsageScope } @@ -79,13 +79,13 @@ export type PluginProcessRequest = export type PluginProcessMessage = | { type: "settings.changed"; settingsId: string } - | { type: "hooks.changed"; hooks: { events: string[]; before: string[] } } + | { type: "hooks.changed"; hooks: string[] } | { type: "ready"; methods: string[]; providers: PluginProviderMetadata[]; usageSources?: PluginUsageSourceMetadata[]; - hooks?: { events: string[]; before: string[] }; + hooks?: string[]; } | { type: "result"; requestId: string; output: unknown } | { type: "error"; requestId: string; error: string } @@ -109,7 +109,7 @@ export type PluginProcessMessage = | { type: "paseo_frame"; data: string | Uint8Array; isBinary: boolean } | { type: "paseo_close" }; -const hooksSchema = z.object({ events: z.array(z.string()), before: z.array(z.string()) }).strict(); +const hooksSchema = z.array(z.string()); const providerMetadataSchema = z .object({ @@ -211,7 +211,6 @@ export const PluginProcessRequestSchema: z.ZodType = z.dis .object({ type: z.literal("hook"), requestId: z.string(), - kind: z.enum(["event", "before"]), name: z.string(), input: z.unknown(), }) diff --git a/packages/server/src/server/plugins/plugin-process.ts b/packages/server/src/server/plugins/plugin-process.ts index e93ded990e..62514cd0b2 100644 --- a/packages/server/src/server/plugins/plugin-process.ts +++ b/packages/server/src/server/plugins/plugin-process.ts @@ -24,6 +24,7 @@ import { createPluginClientId } from "./plugin-session-identity.js"; import { PluginSettingsStore } from "./settings/index.js"; import { readPluginProviderIcon } from "./provider-icon.js"; +import { initializeEnvironmentProxy } from "../network/index.js"; function describeError(error: unknown): string { return error instanceof Error ? error.message : String(error); } @@ -288,6 +289,7 @@ export function createPluginWorker(options: { registerProvider, registerUsageSource, registerSettings, + addHook: hooks.addHook, on: hooks.on, before: hooks.before, }); @@ -563,7 +565,7 @@ export function createPluginWorker(options: { }); return; } - void hooks.invoke(message.requestId, message.kind, message.name, message.input, paseo).then( + void hooks.invoke(message.requestId, message.name, message.input, paseo).then( (output) => { return send({ type: "result", requestId: message.requestId, output }); }, @@ -605,6 +607,7 @@ if (process.argv[1] === fileURLToPath(import.meta.url)) { const parsed = PluginProcessRequestSchema.safeParse(raw); if (!worker && parsed.success && parsed.data.type === "initialize") { try { + initializeEnvironmentProxy(); worker = createPluginWorker({ channel, contribute: evaluateBundle(parsed.data.bundle) }); } catch (error) { channel.send({ type: "fatal", error: describeError(error) }); diff --git a/packages/server/src/server/plugins/requirements.posix.test.ts b/packages/server/src/server/plugins/requirements.posix.test.ts index 65462336a3..597d907e18 100644 --- a/packages/server/src/server/plugins/requirements.posix.test.ts +++ b/packages/server/src/server/plugins/requirements.posix.test.ts @@ -1,4 +1,5 @@ import { mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises"; +import { createHash } from "node:crypto"; import { tmpdir } from "node:os"; import path from "node:path"; import { pathToFileURL } from "node:url"; @@ -68,9 +69,18 @@ it("rejects incompatible installs without persisting them, then accepts the corr await expect(service.installDirectory({ path: root })).resolves.toMatchObject({ status: "running", }); - expect(service.catalog()).toEqual([ - { id: "example", requirements: { paseo: "^0.8.0" }, clientBundle: expect.any(String) }, + const catalog = service.catalog(); + expect(catalog).toEqual([ + { + id: "example", + requirements: { paseo: "^0.8.0" }, + clientBundle: expect.any(String), + clientBundleHash: expect.any(String), + }, ]); + expect(catalog[0]!.clientBundleHash).toBe( + createHash("sha256").update(catalog[0]!.clientBundle).digest("hex"), + ); }); it("marks pre-0.8 plugins failed on startup and recovers after migration and reload", async () => { diff --git a/packages/server/src/server/plugins/runtime.posix.test.ts b/packages/server/src/server/plugins/runtime.posix.test.ts index 30ada955a6..cfa3292567 100644 --- a/packages/server/src/server/plugins/runtime.posix.test.ts +++ b/packages/server/src/server/plugins/runtime.posix.test.ts @@ -1,5 +1,6 @@ import { mkdir, mkdtemp, readdir, readFile, rm, writeFile } from "node:fs/promises"; import { fork } from "node:child_process"; +import { createHash } from "node:crypto"; import { tmpdir } from "node:os"; import { PassThrough } from "node:stream"; import path from "node:path"; @@ -10,6 +11,7 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import type { AgentStreamEvent } from "../agent/agent-sdk-types.js"; import { PluginAgentClientRegistry } from "../agent/plugin-provider.js"; import { PluginRuntime } from "./runtime.js"; +import { resolveDaemonVersion } from "../daemon-version.js"; import type { PluginSessionSocket } from "./session-socket.js"; const temporaryDirectories: string[] = []; @@ -106,6 +108,12 @@ function createReloadChild( }; } +function sha256(text: string | undefined): string { + return createHash("sha256") + .update(text ?? "") + .digest("hex"); +} + function createTestRuntime( dependencies: NonNullable[2]> = {}, logger = pino({ level: "silent" }), @@ -651,7 +659,8 @@ lines.on("line", (line) => { type: "timeline.item", item: expect.objectContaining({ type: "assistant_message", - id: "assistant-1", + id: JSON.stringify(["agent_message_chunk", "assistant-1"]), + messageId: "assistant-1", text: "ACP says hi", }), }), @@ -1535,6 +1544,7 @@ export default function contribute(server: { registerProvider(provider: Provider expect(spawnChild).not.toHaveBeenCalled(); expect(runtime.catalog()[0]?.clientBundle).toContain("addTheme"); + expect(runtime.catalog()[0]?.clientBundleHash).toBe(sha256(runtime.catalog()[0]?.clientBundle)); await runtime.stopAll(); }); @@ -1697,6 +1707,7 @@ export function inspectHost(_input: z.input) { const plugin = runtime.catalog()[0]; expect(plugin?.clientBundle).toContain("Client-only surface"); expect(plugin?.clientBundle).not.toContain("node:os"); + expect(plugin?.clientBundleHash).toBe(sha256(plugin?.clientBundle)); await expect(runtime.invoke("split-runtime", "inspect", {})).resolves.toMatchObject({ platform: expect.any(String), }); @@ -2068,7 +2079,11 @@ const examples = (await readdir(examplesDirectory, { withFileTypes: true })) it.each(examples)("builds and loads the %s plugin example", async (example) => { const settingsDirectory = await mkdtemp(path.join(tmpdir(), "paseo-example-settings-")); temporaryDirectories.push(settingsDirectory); - const runtime = createTestRuntime({ settingsDirectory }, undefined, "0.13.2"); + const runtime = createTestRuntime( + { settingsDirectory }, + undefined, + resolveDaemonVersion(import.meta.url), + ); try { await runtime.startPlugin(example, path.join(examplesDirectory, example)); expect(runtime.catalog()).toMatchObject([{ id: example }]); diff --git a/packages/server/src/server/plugins/runtime.ts b/packages/server/src/server/plugins/runtime.ts index bc06d5d991..31f313cb7f 100644 --- a/packages/server/src/server/plugins/runtime.ts +++ b/packages/server/src/server/plugins/runtime.ts @@ -1,4 +1,6 @@ -import type { PluginWireBeforeRequests } from "./lifecycle/index.js"; +import { validateWorktreePath } from "../../utils/worktree-path.js"; +import type { PluginHookPayload } from "@getpaseo/plugin/server"; +import type { PluginWireBeforeRequests, PluginBeforeResults } from "./lifecycle/index.js"; import type { SessionOpenWireRequest, AttachedAgentTool } from "./agent-tools.js"; import type { UsageScope } from "@getpaseo/plugin/server/usage"; import { @@ -6,16 +8,12 @@ import { type ProviderStatus, type ProviderStatusRequest, } from "@getpaseo/plugin/server/provider"; -import type { - PluginLifecycleEvents, - PluginHookAgent, - AgentToolResult, -} from "@getpaseo/plugin/server"; +import type { PluginHookEvents, PluginHookAgent, AgentToolResult } from "@getpaseo/plugin/server"; import { validateBeforeRequest, validateBeforeResult } from "./lifecycle/index.js"; import { fork } from "node:child_process"; import path from "node:path"; import { fileURLToPath } from "node:url"; -import { randomUUID } from "node:crypto"; +import { createHash, randomUUID } from "node:crypto"; import type pino from "pino"; import { PROVIDER_CAPABILITIES, @@ -74,8 +72,10 @@ interface LoadedPlugin { instanceId: string; requirements: PluginRequirements | undefined; clientBundle: string; + /** Lets a client that already holds this bundle skip downloading it again. */ + clientBundleHash: string; methods: ReadonlySet; - hooks: { events: string[]; before: string[] }; + hooks: string[]; providers: readonly PluginProviderMetadata[]; usageSources: readonly PluginUsageSourceMetadata[]; child: PluginChild | null; @@ -246,6 +246,10 @@ function terminatePluginChild(child: PluginChild): void { if (!child.killed) child.kill(); } +function hashClientBundle(clientBundle: string): string { + return createHash("sha256").update(clientBundle).digest("hex"); +} + function describeError(error: unknown): string { return error instanceof Error ? error.message : String(error); } @@ -305,7 +309,7 @@ export class PluginRuntime { } private notifySessionOpenChange(loaded: LoadedPlugin): void { - if (!loaded.hooks.before.includes("agent.session_open")) return; + if (!loaded.hooks.includes("agent.open.before")) return; for (const listener of this.sessionOpenListeners) listener(); } @@ -369,9 +373,19 @@ export class PluginRuntime { return true; } - catalog(): Array<{ id: string; clientBundle: string; requirements?: PluginRequirements }> { + catalog(): Array<{ + id: string; + clientBundle: string; + clientBundleHash: string; + requirements?: PluginRequirements; + }> { return [...this.plugins.values()] - .map(({ id, clientBundle, requirements }) => ({ id, clientBundle, requirements })) + .map(({ id, clientBundle, clientBundleHash, requirements }) => ({ + id, + clientBundle, + clientBundleHash, + requirements, + })) .sort((left, right) => left.id.localeCompare(right.id)); } @@ -500,18 +514,14 @@ export class PluginRuntime { return this.request(loaded, { type: "invoke", requestId: randomUUID(), method, input }); } - emit( - name: Name, - event: PluginLifecycleEvents[Name], - ): void { + emit(name: Name, event: PluginHookEvents[Name]): void { for (const loaded of this.plugins.values()) { - if (!loaded.hooks.events.includes(name)) { + if (!loaded.hooks.includes(name)) { continue; } const request = this.request(loaded, { type: "hook", requestId: randomUUID(), - kind: "event", name, input: event, }) @@ -532,40 +542,76 @@ export class PluginRuntime { await Promise.all(this.pendingEvents); } + async wait( + name: "worktree.create.after", + payload: PluginHookPayload<"worktree.create.after">, + ): Promise { + const plugins = [...this.plugins.values()].sort((left, right) => + left.id.localeCompare(right.id), + ); + for (const loaded of plugins) { + if (!loaded.hooks.includes(name)) continue; + try { + await this.request(loaded, { type: "hook", requestId: randomUUID(), name, input: payload }); + } catch (error) { + throw new Error(`Plugin ${loaded.id} ${name} failed: ${describeError(error)}`, { + cause: error, + }); + } + } + } + async before( name: Name, input: PluginWireBeforeRequests[Name], - ): Promise { + ): Promise { let request = validateBeforeRequest(name, input); const plugins = [...this.plugins.values()].sort((left, right) => { return left.id.localeCompare(right.id); }); const attached: AttachedAgentTool[] = []; + const mcpServers: SessionOpenWireRequest["mcpServers"] = {}; + const mcpServerOwners: Record = {}; for (const loaded of plugins) { - if (!loaded.hooks.before.includes(name)) { + if (!loaded.hooks.includes(name)) { continue; } try { const output = await this.request(loaded, { type: "hook", requestId: randomUUID(), - kind: "before", name, - input: name === "agent.session_open" ? { ...request, tools: [] } : request, + input: name === "agent.open.before" ? { ...request, tools: [], mcpServers: {} } : request, }); - request = validateBeforeResult(name, request, output); - if (name === "agent.session_open") { - this.collectAgentTools(attached, loaded, (request as SessionOpenWireRequest).tools); + request = await validateBeforeResult(name, request, output); + if (name === "worktree.create.before") { + const worktree = request as PluginWireBeforeRequests["worktree.create.before"]; + worktree.path = await validateWorktreePath({ + candidate: worktree.path, + repoPath: worktree.repoRoot, + }); + } + if (name === "agent.open.before") { + const opened = request as SessionOpenWireRequest; + this.collectMcpServers(mcpServers, mcpServerOwners, loaded, opened.mcpServers); + this.collectAgentTools(attached, loaded, opened.tools); } } catch (error) { - if (name === "agent.session_open") + if (name === "agent.open.before") this.detachTools((request as SessionOpenWireRequest).agentId); - throw new Error(`Plugin ${loaded.id} before ${name} failed: ${describeError(error)}`, { + throw new Error(`Plugin ${loaded.id} ${name} failed: ${describeError(error)}`, { cause: error, }); } } - if (name === "agent.session_open") (request as SessionOpenWireRequest).tools = attached; + if (name === "agent.open.before") { + return { + ...request, + tools: attached, + mcpServers, + mcpServerOwners, + } as PluginBeforeResults[Name]; + } return request; } @@ -587,6 +633,23 @@ export class PluginRuntime { return output; } + private collectMcpServers( + servers: SessionOpenWireRequest["mcpServers"], + owners: Record, + loaded: LoadedPlugin, + contributions: SessionOpenWireRequest["mcpServers"], + ): void { + for (const [name, server] of Object.entries(contributions)) { + if (Object.hasOwn(servers, name)) { + throw new Error( + `MCP server ${name} from plugin ${loaded.id} collides with plugin ${owners[name]}`, + ); + } + servers[name] = server; + owners[name] = loaded.id; + } + } + private collectAgentTools( attached: AttachedAgentTool[], loaded: LoadedPlugin, @@ -710,13 +773,15 @@ export class PluginRuntime { if (!canPublish()) throw new Error(`Plugin start cancelled: ${pluginId}`); const serverBundle = bundles.serverBundle; if (!serverBundle) { + const clientBundle = bundles.clientBundle ?? ""; return { id: pluginId, instanceId: randomUUID(), - clientBundle: bundles.clientBundle ?? "", + clientBundle, + clientBundleHash: hashClientBundle(clientBundle), requirements: manifest.requirements, methods: new Set(), - hooks: { events: [], before: [] }, + hooks: [], providers: [], usageSources: [], child: null, @@ -843,9 +908,10 @@ export class PluginRuntime { id: pluginId, instanceId: randomUUID(), clientBundle, + clientBundleHash: hashClientBundle(clientBundle), requirements, methods: new Set(ready.methods), - hooks: ready.hooks ?? { events: [], before: [] }, + hooks: ready.hooks ?? [], providers: ready.providers ?? [], usageSources: ready.usageSources ?? [], child, @@ -925,11 +991,11 @@ export class PluginRuntime { private handleChildMessage(loaded: LoadedPlugin, message: PluginProcessMessage): void { if (message.type === "hooks.changed") { - const hadSessionOpen = loaded.hooks.before.includes("agent.session_open"); + const hadSessionOpen = loaded.hooks.includes("agent.open.before"); loaded.hooks = message.hooks; if ( this.plugins.get(loaded.id) === loaded && - hadSessionOpen !== loaded.hooks.before.includes("agent.session_open") + hadSessionOpen !== loaded.hooks.includes("agent.open.before") ) { for (const listener of this.sessionOpenListeners) listener(); } diff --git a/packages/server/src/server/plugins/test-fixtures/compile-responsiveness.e2e.ts b/packages/server/src/server/plugins/test-fixtures/compile-responsiveness.e2e.ts index 229e388b34..95aaec0d6a 100644 --- a/packages/server/src/server/plugins/test-fixtures/compile-responsiveness.e2e.ts +++ b/packages/server/src/server/plugins/test-fixtures/compile-responsiveness.e2e.ts @@ -1,9 +1,7 @@ +import { measureMainThreadWork } from "../../../test-utils/main-thread-work.js"; import assert from "node:assert/strict"; -import { createHook, executionAsyncResource } from "node:async_hooks"; import { open as openFile, writeFile } from "node:fs/promises"; -import { performance, PerformanceObserver } from "node:perf_hooks"; import path from "node:path"; -import { MessagePort } from "node:worker_threads"; import pino from "pino"; import { DaemonConfigStore } from "../../daemon-config-store.js"; import { PluginService } from "../index.js"; @@ -53,125 +51,9 @@ try { () => service.enablePlugin("responsive-build"), () => service.reloadPlugin("responsive-build"), ]) { - // Node 22.19+ exposes per-thread CPU accounting; the repository's older - // Node declarations do not include it yet. .tool-versions pins Node 22.20. - const threadCpuUsage: (previous?: NodeJS.CpuUsage) => NodeJS.CpuUsage = Reflect.get( - process, - "threadCpuUsage", - ); - const startedAt = performance.now(); - let previous = startedAt; - let cpu = threadCpuUsage(); - let longestWall = 0; - let longestBlocking = 0; - let longestWallCpu = 0; - let workerStarts = 0; - let portCallbacks = 0; - let longestWallEvents = { workerStarts: 0, portCallbacks: 0 }; - let longestBlockingWindow = { wallMs: 0, cpuMs: 0, resource: "" }; - let probe: ReturnType; - const callbacks = new Map(); - const recordBlocking = ( - blockingMs: number, - window: { wallMs: number; cpuMs: number; resource: string }, - ) => { - if (blockingMs > longestBlocking) { - longestBlocking = blockingMs; - longestBlockingWindow = window; - } - }; - let longestGc = 0; - const observeGc = (entries: readonly import("node:perf_hooks").PerformanceEntry[]) => { - for (const entry of entries) { - if (entry.startTime >= startedAt) longestGc = Math.max(longestGc, entry.duration); - } - }; - const gc = new PerformanceObserver((list) => observeGc(list.getEntries())); - gc.observe({ entryTypes: ["gc"] }); - // Measure work within callbacks, not CPU-counter increments attributed to - // the idle interval between them. Exclude this probe's own timer callback. - const activity = createHook({ - init(_id, type) { - if (type === "WORKER") workerStarts++; - }, - before(id) { - const resource = executionAsyncResource(); - if (resource instanceof MessagePort) portCallbacks++; - if (resource === probe) return; - callbacks.set(id, { - wall: performance.now(), - cpu: threadCpuUsage(), - resource: Object.prototype.toString.call(resource), - }); - }, - after(id) { - const start = callbacks.get(id); - if (!start) return; - callbacks.delete(id); - const wallMs = performance.now() - start.wall; - const { user, system } = threadCpuUsage(start.cpu); - const cpuMs = (user + system) / 1_000; - // A callback prevents the loop from serving IO for its entire span. - // Use the high-resolution clock, not Windows' coarse CPU increments. - recordBlocking(wallMs, { wallMs, cpuMs, resource: start.resource }); - }, - }).enable(); - const sample = () => { - const now = performance.now(); - const currentCpu = threadCpuUsage(); - const wallMs = now - previous; - const cpuMs = (currentCpu.user - cpu.user + currentCpu.system - cpu.system) / 1_000; - // Native worker construction and message deserialization can precede - // async_hooks.before. Include their interval when those events occurred. - if (workerStarts || portCallbacks) { - recordBlocking(Math.min(wallMs, cpuMs), { - wallMs, - cpuMs, - resource: "worker/port interval", - }); - } - if (wallMs > longestWall) { - longestWall = wallMs; - longestWallCpu = cpuMs; - longestWallEvents = { workerStarts, portCallbacks }; - } - workerStarts = 0; - portCallbacks = 0; - previous = now; - cpu = currentCpu; - }; - // Sleep between probes: a continuously runnable setImmediate loop consumes - // a core while the worker compiles. Raw gaps remain diagnostics; the - // assertion measures elapsed daemon-thread callback spans and GC pauses. - probe = setInterval(sample, 1); - try { - // The caller's current callback began before the hook was enabled. - // Include synchronous work before the action's first await explicitly. - const actionStartedAt = performance.now(); - const actionCpu = threadCpuUsage(); - const pending = action(); - const actionWallMs = performance.now() - actionStartedAt; - const actionCost = threadCpuUsage(actionCpu); - recordBlocking(actionWallMs, { - wallMs: actionWallMs, - cpuMs: (actionCost.user + actionCost.system) / 1_000, - resource: "action()", - }); - await pending; - await new Promise((resolve) => setImmediate(resolve)); - sample(); - observeGc(gc.takeRecords()); - } finally { - clearInterval(probe); - activity.disable(); - gc.disconnect(); - } - longestBlocking = Math.max(longestBlocking, longestGc); - process.stderr.write( - `plugin compile main-thread blocking: ${longestBlocking.toFixed(2)} ms ${JSON.stringify({ longestWall, longestWallCpu, ...longestWallEvents, longestBlockingWindow, longestGc })}\n`, - ); + const { blockingMs } = await measureMainThreadWork("plugin compile main-thread work", action); assert.ok(service.catalog()[0]?.clientBundle.includes("compiled fixture")); - results.push({ blockingMs: longestBlocking }); + results.push({ blockingMs }); } // Evaluate after both probes so parsing the returned code is not charged to compilation. const factory = globalThis.eval(service.catalog()[0]!.clientBundle) as ( diff --git a/packages/server/src/server/plugins/test-fixtures/usage-proxy-daemon.ts b/packages/server/src/server/plugins/test-fixtures/usage-proxy-daemon.ts new file mode 100644 index 0000000000..23364d3fda --- /dev/null +++ b/packages/server/src/server/plugins/test-fixtures/usage-proxy-daemon.ts @@ -0,0 +1,31 @@ +import path from "node:path"; +import { initializeEnvironmentProxy } from "../../network/index.js"; +import { DaemonClient } from "../../test-utils/daemon-client.js"; +import { createTestPaseoDaemon } from "../../test-utils/paseo-daemon.js"; +import { BuiltinPluginLoader, resolveBuiltinPluginsRoot } from "../builtin/index.js"; + +const mode = process.argv[2]; +if (mode !== "builtin" && mode !== "directory") throw new Error("Expected builtin or directory"); +const sources = ["claude-usage-source", "codex-usage-source"]; +// Built-ins run inside the daemon; directory plugins initialize their own subprocess network. +if (mode === "builtin") initializeEnvironmentProxy(); +const daemon = await createTestPaseoDaemon({ + pluginsEnabled: mode === "directory", + builtinPlugins: new BuiltinPluginLoader( + resolveBuiltinPluginsRoot(), + mode === "builtin" ? sources : [], + ), +}); +const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` }); +try { + await client.connect(); + if (mode === "directory") { + for (const source of sources) { + await client.installDirectoryPlugin(path.join(resolveBuiltinPluginsRoot(), source), source); + } + } + await client.listUsageReports(); +} finally { + await client.close(); + await daemon.close(); +} diff --git a/packages/server/src/server/plugins/usage-sources.e2e.test.ts b/packages/server/src/server/plugins/usage-sources.e2e.test.ts index 037da5e0c6..46dc134ff6 100644 --- a/packages/server/src/server/plugins/usage-sources.e2e.test.ts +++ b/packages/server/src/server/plugins/usage-sources.e2e.test.ts @@ -1,7 +1,11 @@ +import { execFile } from "node:child_process"; +import { promisify } from "node:util"; import { cp, mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; +import { createServer } from "node:http"; +import { once } from "node:events"; import { expect, test } from "vitest"; import { DaemonClient } from "../test-utils/daemon-client.js"; import { createTestPaseoDaemon } from "../test-utils/paseo-daemon.js"; @@ -335,3 +339,74 @@ export default function contribute(server) { await rm(root, { recursive: true, force: true }); } }, 60_000); + +test.each(["builtin", "directory"])( + "%s usage plugins reach the environment proxy", + async (mode) => { + const root = await mkdtemp(path.join(os.tmpdir(), "usage-proxy-")); + const tunnels: string[] = []; + const proxy = createServer(); + proxy.on("connect", (request, socket) => { + tunnels.push(request.url!); + socket.end("HTTP/1.1 502 Bad Gateway\r\nConnection: close\r\n\r\n"); + }); + proxy.listen(0, "127.0.0.1"); + await once(proxy, "listening"); + const address = proxy.address(); + if (!address || typeof address === "string") throw new Error("Missing proxy address"); + const guard = path.join(root, "network-guard.cjs"); + // Prevent vendor DNS/network access even when proxy support is broken. + await writeFile( + guard, + `const dns = require('node:dns'); +const lookup = dns.lookup; +dns.lookup = function(host, ...args) { + if (host === 'localhost' || host === '127.0.0.1' || host === '::1') return lookup.call(this, host, ...args); + args.at(-1)(Object.assign(new Error('External DNS forbidden in proxy test'), { code: 'ENOTFOUND' })); +};`, + ); + await mkdir(path.join(root, ".claude")); + await mkdir(path.join(root, ".codex")); + await writeFile( + path.join(root, ".claude", ".credentials.json"), + JSON.stringify({ claudeAiOauth: { accessToken: "fixture-claude" } }), + ); + await writeFile( + path.join(root, ".codex", "auth.json"), + JSON.stringify({ tokens: { access_token: "fixture-codex", account_id: "fixture-account" } }), + ); + try { + await promisify(execFile)( + process.execPath, + [ + "--import", + "tsx", + fileURLToPath(new URL("./test-fixtures/usage-proxy-daemon.ts", import.meta.url)), + mode, + ], + { + timeout: 45_000, + maxBuffer: 1024 * 1024, + env: { + ...process.env, + HOME: root, + USERPROFILE: root, + CODEX_HOME: path.join(root, ".codex"), + CLAUDE_CONFIG_DIR: path.join(root, ".claude"), + NODE_OPTIONS: `--require=${JSON.stringify(guard.replaceAll("\\", "/"))}`, + https_proxy: `http://127.0.0.1:${address.port}`, + no_proxy: "", + NO_PROXY: "", + }, + }, + ); + expect(tunnels).toContain("api.anthropic.com:443"); + expect(tunnels).toContain("chatgpt.com:443"); + } finally { + proxy.closeAllConnections(); + await new Promise((resolve) => proxy.close(() => resolve())); + await rm(root, { recursive: true, force: true }); + } + }, + 60_000, +); diff --git a/packages/server/src/server/relay-transport.ts b/packages/server/src/server/relay-transport.ts index 08fcd826d5..a0898df247 100644 --- a/packages/server/src/server/relay-transport.ts +++ b/packages/server/src/server/relay-transport.ts @@ -2,6 +2,7 @@ import { WebSocket } from "ws"; import type pino from "pino"; import { buildRelayWebSocketUrl } from "@getpaseo/protocol/daemon-endpoints"; +import { webSocketProxyAgent } from "./network/index.js"; import type { ExternalSocketMetadata } from "./websocket-server.js"; export interface RelayTransportOptions { @@ -56,7 +57,7 @@ const RELAY_WEBSOCKET_OPTIONS = { } as const; function createDefaultRelayWebSocket(url: string): RelayWebSocketLike { - return new WebSocket(url, RELAY_WEBSOCKET_OPTIONS); + return new WebSocket(url, { ...RELAY_WEBSOCKET_OPTIONS, agent: webSocketProxyAgent(url) }); } function isRecord(value: unknown): value is Record { diff --git a/packages/server/src/server/script-health-monitor.test.ts b/packages/server/src/server/script-health-monitor.test.ts index 96af0133ca..c5e4904a9d 100644 --- a/packages/server/src/server/script-health-monitor.test.ts +++ b/packages/server/src/server/script-health-monitor.test.ts @@ -68,13 +68,7 @@ function createStubTerminalManager( subscribe: () => () => {}, onExit: () => () => {}, onCommandFinished: () => () => {}, - getState: () => ({ - rows: 1, - cols: 1, - grid: [[{ char: "$" }]], - scrollback: [], - cursor: { row: 0, col: 0 }, - }), + hasOutput: () => true, kill: () => {}, onTitleChange: () => () => {}, getSize: () => ({ rows: 1, cols: 1 }), diff --git a/packages/server/src/server/service-proxy.test.ts b/packages/server/src/server/service-proxy.test.ts index 5764b19539..eb679d5629 100644 --- a/packages/server/src/server/service-proxy.test.ts +++ b/packages/server/src/server/service-proxy.test.ts @@ -1,7 +1,9 @@ +import { type EventEmitter, once } from "node:events"; import { readdirSync, readFileSync, statSync } from "node:fs"; import path from "node:path"; import http from "node:http"; import net from "node:net"; +import type { Duplex } from "node:stream"; import express from "express"; import { describe, expect, it } from "vitest"; import pino from "pino"; @@ -332,48 +334,39 @@ describe("service proxy subsystem shape", () => { }); }); -interface ForwardedFixture { +interface ProxiedServiceFixture { upstreamPort: number; daemonPort: number; + daemon: http.Server; hostname: string; close(): Promise; } /** - * Runs a real workspace service behind a real daemon listener. The upstream - * echoes the headers it received so tests can assert what actually crossed the - * proxy, not what a helper returned. + * Runs a real workspace service behind a real daemon listener that serves the + * service proxy for both HTTP and upgrades. */ -async function startForwardedHeadersFixture(upstreamHost = "127.0.0.1"): Promise { - const upstream = http.createServer((req, res) => { - let body = ""; - req.on("data", (chunk: Buffer) => { - body += chunk.toString(); +async function startProxiedService( + upstream: http.Server, + options: { upstreamHost?: string; logger?: pino.Logger } = {}, +): Promise { + const { upstreamHost = "127.0.0.1", logger: proxyLogger = logger } = options; + // Upgraded sockets keep the server alive; close() alone would hang. + const sockets = new Set(); + function trackConnections(server: http.Server) { + server.on("connection", (socket: net.Socket) => { + sockets.add(socket); + socket.once("close", () => sockets.delete(socket)); }); - req.on("end", () => { - res.writeHead(200, { "content-type": "application/json" }); - res.end(JSON.stringify({ ...req.headers, method: req.method, url: req.url, body })); - }); - }); - const upgradeSockets: net.Socket[] = []; - upstream.on("upgrade", (req, socket) => { - upgradeSockets.push(socket); - // The client resets this connection once it has the echo, so the reset - // reaches us as an 'error'. A raw upgrade socket has no default handler — - // without this the event goes unhandled and takes down the test process. - socket.on("error", () => socket.destroy()); - const payload = JSON.stringify(req.headers); - socket.write( - `HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nX-Echo-Length: ${payload.length}\r\n\r\n${payload}`, - ); - }); + } + trackConnections(upstream); await new Promise((resolve, reject) => { upstream.once("error", reject); upstream.listen(0, upstreamHost, resolve); }); const upstreamPort = (upstream.address() as net.AddressInfo).port; - const serviceProxy = createServiceProxySubsystem({ logger }); + const serviceProxy = createServiceProxySubsystem({ logger: proxyLogger }); const route = serviceProxy.registerWorkspaceService({ workspaceId: "workspace-a", projectSlug: "repo", @@ -390,24 +383,51 @@ async function startForwardedHeadersFixture(upstreamHost = "127.0.0.1"): Promise res.status(404).send("404 Not Found"); }); const daemon = http.createServer(app); + trackConnections(daemon); daemon.on("upgrade", serviceProxy.upgradeHandler({ passthroughUnknown: false })); await new Promise((resolve) => daemon.listen(daemonPort, "127.0.0.1", resolve)); return { upstreamPort, daemonPort, + daemon, hostname: route.hostname, async close() { - // Upgraded sockets keep the server alive; close() alone would hang. - for (const socket of upgradeSockets) socket.destroy(); - daemon.closeAllConnections(); + for (const socket of sockets) socket.destroy(); await new Promise((resolve) => daemon.close(() => resolve())); - upstream.closeAllConnections(); await new Promise((resolve) => upstream.close(() => resolve())); }, }; } +/** + * The upstream echoes the headers it received so tests can assert what + * actually crossed the proxy, not what a helper returned. + */ +function startForwardedHeadersFixture(upstreamHost = "127.0.0.1"): Promise { + const upstream = http.createServer((req, res) => { + let body = ""; + req.on("data", (chunk: Buffer) => { + body += chunk.toString(); + }); + req.on("end", () => { + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify({ ...req.headers, method: req.method, url: req.url, body })); + }); + }); + upstream.on("upgrade", (req, socket) => { + // The client resets this connection once it has the echo, so the reset + // reaches us as an 'error'. A raw upgrade socket has no default handler — + // without this the event goes unhandled and takes down the test process. + socket.on("error", () => socket.destroy()); + const payload = JSON.stringify(req.headers); + socket.write( + `HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nX-Echo-Length: ${payload.length}\r\n\r\n${payload}`, + ); + }); + return startProxiedService(upstream, { upstreamHost }); +} + function upgradeThroughProxy( port: number, host: string, @@ -651,3 +671,198 @@ describe("service proxy forwarded headers", () => { } }); }); + +function closed(emitter: EventEmitter): Promise { + return new Promise((resolve) => { + emitter.once("close", () => resolve()); + }); +} + +async function within(promise: Promise, ms: number, failure: string): Promise { + let timer: NodeJS.Timeout | undefined; + const timeout = new Promise((_resolve, reject) => { + timer = setTimeout(() => reject(new Error(`${failure} after ${ms}ms`)), ms); + }); + try { + return await Promise.race([promise, timeout]); + } finally { + clearTimeout(timer); + } +} + +function requestThroughProxy( + fixture: ProxiedServiceFixture, + requestPath: string, +): http.ClientRequest { + return http.get({ + hostname: "127.0.0.1", + port: fixture.daemonPort, + path: requestPath, + headers: { host: fixture.hostname }, + }); +} + +const STRAY_WARNING_GRACE_MS = 100; + +function createUpgradeUpstream(onUpgrade: (socket: Duplex) => void): http.Server { + const upstream = http.createServer(); + upstream.on("upgrade", (_req, socket) => { + socket.on("error", () => socket.destroy()); + socket.on("end", () => socket.end()); + socket.write( + "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\r\n", + ); + onUpgrade(socket); + }); + return upstream; +} + +function openUpgradeThroughProxy(fixture: ProxiedServiceFixture): Promise { + return new Promise((resolve, reject) => { + const socket = net.connect({ host: "127.0.0.1", port: fixture.daemonPort }, () => { + const lines = [ + "GET /ws HTTP/1.1", + `Host: ${fixture.hostname}`, + "Upgrade: websocket", + "Connection: Upgrade", + "", + "", + ]; + socket.write(lines.join("\r\n")); + }); + let raw = ""; + socket.on("data", (chunk: Buffer) => { + raw += chunk.toString(); + if (raw.includes("\r\n\r\n")) resolve(socket); + }); + socket.on("close", () => reject(new Error("upgrade closed before the 101 arrived"))); + socket.on("error", reject); + }); +} + +describe("service proxy connection teardown", () => { + it("closes the upstream connection when a client leaves an event stream", async () => { + const upstreamResponse = Promise.withResolvers(); + const upstream = http.createServer((_req, res) => { + res.writeHead(200, { "content-type": "text/event-stream" }); + res.write("data: open\n\n"); + upstreamResponse.resolve(res); + }); + const fixture = await startProxiedService(upstream); + try { + const request = requestThroughProxy(fixture, "/events"); + const [response] = (await once(request, "response")) as [http.IncomingMessage]; + await once(response, "data"); + const upstreamClosed = closed(await upstreamResponse.promise); + + request.destroy(); + + await within(upstreamClosed, 1000, "the service still holds the event stream"); + } finally { + await fixture.close(); + } + }, 5000); + + it("aborts the upstream request when a client leaves before the response starts", async () => { + const warnings: unknown[] = []; + const proxyLogger = pino( + { level: "warn" }, + { write: (line: string) => warnings.push(JSON.parse(line)) }, + ); + const upstreamResponse = Promise.withResolvers(); + const upstream = http.createServer((_req, res) => { + upstreamResponse.resolve(res); + }); + const fixture = await startProxiedService(upstream, { logger: proxyLogger }); + try { + const request = requestThroughProxy(fixture, "/slow"); + request.on("error", () => undefined); + const upstreamClosed = closed(await upstreamResponse.promise); + + request.destroy(); + + await within(upstreamClosed, 1000, "the service still holds the abandoned request"); + await new Promise((resolve) => setTimeout(resolve, STRAY_WARNING_GRACE_MS)); + expect(warnings).toEqual([]); + } finally { + await fixture.close(); + } + }, 5000); + + it("lets a complete response finish without resetting the service", async () => { + const upstreamResponse = Promise.withResolvers(); + const upstream = http.createServer((_req, res) => { + res.writeHead(200, { "content-type": "text/plain" }); + res.write("first;"); + upstreamResponse.resolve(res); + }); + const fixture = await startProxiedService(upstream); + try { + const response = httpGet(fixture.daemonPort, fixture.hostname, { path: "/" }); + const res = await upstreamResponse.promise; + const upstreamClosed = closed(res); + + res.end("second"); + + await expect(response).resolves.toEqual({ status: 200, body: "first;second" }); + await within(upstreamClosed, 1000, "the service response never closed"); + expect(res.writableFinished).toBe(true); + } finally { + await fixture.close(); + } + }, 5000); + + it("closes the upstream WebSocket when the daemon drops the client socket", async () => { + const upstreamSocket = Promise.withResolvers(); + const fixture = await startProxiedService( + createUpgradeUpstream((socket) => upstreamSocket.resolve(socket)), + ); + const daemonSide = Promise.withResolvers(); + fixture.daemon.on("upgrade", (_req, socket) => daemonSide.resolve(socket)); + try { + const client = await openUpgradeThroughProxy(fixture); + const upstreamClosed = closed(await upstreamSocket.promise); + + (await daemonSide.promise).destroy(); + + await within(upstreamClosed, 1000, "the service still holds the WebSocket"); + client.destroy(); + } finally { + await fixture.close(); + } + }, 5000); + + it("closes the upstream WebSocket when the client disconnects", async () => { + const upstreamSocket = Promise.withResolvers(); + const fixture = await startProxiedService( + createUpgradeUpstream((socket) => upstreamSocket.resolve(socket)), + ); + try { + const client = await openUpgradeThroughProxy(fixture); + const upstreamClosed = closed(await upstreamSocket.promise); + + client.destroy(); + + await within(upstreamClosed, 1000, "the service still holds the WebSocket"); + } finally { + await fixture.close(); + } + }, 5000); + + it("closes the client WebSocket when the service closes it", async () => { + const upstreamSocket = Promise.withResolvers(); + const fixture = await startProxiedService( + createUpgradeUpstream((socket) => upstreamSocket.resolve(socket)), + ); + try { + const client = await openUpgradeThroughProxy(fixture); + const clientClosed = closed(client); + + (await upstreamSocket.promise).destroy(); + + await within(clientClosed, 1000, "the client WebSocket is still open"); + } finally { + await fixture.close(); + } + }, 5000); +}); diff --git a/packages/server/src/server/service-proxy.ts b/packages/server/src/server/service-proxy.ts index ef93a27f9a..24bfd80c93 100644 --- a/packages/server/src/server/service-proxy.ts +++ b/packages/server/src/server/service-proxy.ts @@ -342,7 +342,14 @@ function proxyHttpRequest({ proxyRes.pipe(res, { end: true }); }, ); + let clientClosed = false; + res.on("close", () => { + if (res.writableFinished) return; + clientClosed = true; + proxyReq.destroy(); + }); proxyReq.on("error", (err) => { + if (clientClosed) return; logger.warn( { err, hostname: route.hostname, port: route.port }, "Service proxy: upstream unreachable", @@ -399,6 +406,9 @@ function proxyUpgradeRequest({ socket.on("error", () => { targetSocket.destroy(); }); + socket.on("close", () => { + targetSocket.destroy(); + }); } function sameRouteOwner(left: ServiceProxyRouteEntry, right: ServiceProxyRouteEntry): boolean { diff --git a/packages/server/src/server/session.test.ts b/packages/server/src/server/session.test.ts index 7321312826..d1408f9880 100644 --- a/packages/server/src/server/session.test.ts +++ b/packages/server/src/server/session.test.ts @@ -8,7 +8,15 @@ import { createTestCreationService, } from "./test-utils/session-stubs.js"; import { execSync } from "child_process"; -import { existsSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "fs"; +import { + existsSync, + mkdirSync, + mkdtempSync, + realpathSync, + rmSync, + symlinkSync, + writeFileSync, +} from "fs"; import { tmpdir } from "os"; import { join, resolve as resolvePath } from "path"; import pino from "pino"; @@ -28,6 +36,11 @@ import { type FileTransferFrame, } from "@getpaseo/protocol/binary-frames/index"; import { Session } from "./session.js"; +import { + terminalCleanupRecordPath, + terminalWorkerDirectory, + writeTerminalCleanupRecord, +} from "../terminal/terminal-worker-record.js"; import { OWNER_PERMISSIONS, type DaemonPermission } from "./authorization/index.js"; import { DownloadTokenStore } from "./file-download/token-store.js"; import { StructuredAgentFallbackError } from "./agent/agent-response-loop.js"; @@ -588,6 +601,78 @@ test("routes plugin requests and releases its owned catalog subscription on clea expect(releasePluginSubscription).toHaveBeenCalledOnce(); }); +test("leaves out the client bundles a catalog request already holds", async () => { + const messages: SessionOutboundMessage[] = []; + const pluginRuntime: NonNullable = { + before: async (_name, request) => request, + emit: () => {}, + listPlugins: async () => [], + getLogs: () => [], + installDirectory: async () => { + throw new Error("Unexpected install"); + }, + inspectDirectory: async () => ({ id: "unused" }), + reloadPlugin: async () => { + throw new Error("Unexpected reload"); + }, + enablePlugin: async () => { + throw new Error("Unexpected enable"); + }, + disablePlugin: async () => { + throw new Error("Unexpected disable"); + }, + removePlugin: async () => undefined, + subscribe: () => () => {}, + catalog: () => [ + { id: "cached", clientBundle: "cached bundle", clientBundleHash: "hash-cached" }, + { id: "changed", clientBundle: "new bundle", clientBundleHash: "hash-new" }, + { id: "added", clientBundle: "added bundle", clientBundleHash: "hash-added" }, + ], + invokePluginRpc: async () => null, + listUsageReports: async () => [], + listLegacyUsage: async () => ({ fetchedAt: "2026-01-01T00:00:00.000Z", providers: [] }), + }; + const session = createSessionForTest({ messages, pluginRuntime }); + + await session.handleMessage({ + type: "plugin.catalog.get.request", + requestId: "reconnect", + cachedClientBundles: [ + { id: "cached", clientBundleHash: "hash-cached" }, + { id: "changed", clientBundleHash: "hash-old" }, + { id: "removed", clientBundleHash: "hash-removed" }, + ], + }); + // Clients from before cachedClientBundles always receive every bundle. + await session.handleMessage({ type: "plugin.catalog.get.request", requestId: "legacy" }); + + expect(messages).toEqual([ + { + type: "plugin.catalog.get.response", + payload: { + requestId: "reconnect", + plugins: [ + { id: "cached", clientBundleHash: "hash-cached" }, + { id: "changed", clientBundle: "new bundle", clientBundleHash: "hash-new" }, + { id: "added", clientBundle: "added bundle", clientBundleHash: "hash-added" }, + ], + }, + }, + { + type: "plugin.catalog.get.response", + payload: { + requestId: "legacy", + plugins: [ + { id: "cached", clientBundle: "cached bundle", clientBundleHash: "hash-cached" }, + { id: "changed", clientBundle: "new bundle", clientBundleHash: "hash-new" }, + { id: "added", clientBundle: "added bundle", clientBundleHash: "hash-added" }, + ], + }, + }, + ]); + await session.cleanup(); +}); + describe("workspace label subscriptions", () => { type LabelSubscription = Awaited>; type LabelChange = Parameters[0]["onChange"]>[0]; @@ -1999,11 +2084,84 @@ describe("daemon status + pairing RPC", () => { { provider: "claude", available: true, error: null }, { provider: "codex", available: false, error: "boom" }, ], + terminalCleanupUnconfirmed: [], }, }, ]); }); + test("daemon.get_status.request reports what a terminal cleanup could not confirm gone", async () => { + const messages: unknown[] = []; + const paseoHome = makeHome(); + const unresolved = { + pid: 4242, + role: "terminal program" as const, + reason: "still alive" as const, + detail: "survived SIGKILL", + }; + await writeTerminalCleanupRecord(paseoHome, { + recordId: "closing-record", + pid: 4241, + bootId: null, + createdAt: new Date().toISOString(), + identity: { startedAt: "Thu Jan 1 00:00:00 1970", commandLine: "worker" }, + protocolVersion: 1, + paseoVersion: "0.0.0-test", + socketPath: join(paseoHome, "closing.sock"), + secret: "closing-secret", + terminals: [{ id: "t1", pid: 4242, startedAt: "Thu Jan 1 00:00:00 1970" }], + closing: { unresolved: [unresolved] }, + }); + const session = createSessionForTest({ + messages, + paseoHome, + serverId: "srv-test", + daemonVersion: "9.9.9", + daemonRuntimeConfig: { listen: "127.0.0.1:6767", getRelayConfig: () => null }, + agentManager: { listProviderAvailability: vi.fn().mockResolvedValue([]) }, + }); + + await session.handleMessage({ type: "daemon.get_status.request", requestId: "status-2" }); + + expect(messages).toEqual([ + expect.objectContaining({ + type: "daemon.get_status.response", + payload: expect.objectContaining({ terminalCleanupUnconfirmed: [unresolved] }), + }), + ]); + }); + + test("daemon.get_status.request fails when a terminal cleanup record cannot be read", async () => { + const messages: unknown[] = []; + const paseoHome = makeHome(); + mkdirSync(terminalWorkerDirectory(paseoHome), { recursive: true }); + const cleanupPath = terminalCleanupRecordPath(paseoHome, "closing-record"); + writeFileSync(cleanupPath, "{ not json"); + const session = createSessionForTest({ + messages, + paseoHome, + serverId: "srv-test", + daemonVersion: "9.9.9", + daemonRuntimeConfig: { listen: "127.0.0.1:6767", getRelayConfig: () => null }, + agentManager: { listProviderAvailability: vi.fn().mockResolvedValue([]) }, + }); + + await session.handleMessage({ type: "daemon.get_status.request", requestId: "status-3" }); + + expect(messages).toContainEqual( + expect.objectContaining({ + type: "rpc_error", + payload: expect.objectContaining({ + requestId: "status-3", + error: expect.stringContaining(cleanupPath), + }), + }), + ); + expect(messages).not.toContainEqual( + expect.objectContaining({ type: "daemon.get_status.response" }), + ); + }); + test("daemon.get_status.request falls back to a null/empty status when provider listing fails", async () => { const messages: unknown[] = []; const session = createSessionForTest({ @@ -2035,6 +2193,7 @@ describe("daemon status + pairing RPC", () => { listen: null, relay: null, providers: [], + terminalCleanupUnconfirmed: [], }, }, ]); diff --git a/packages/server/src/server/session.ts b/packages/server/src/server/session.ts index 9d25328079..00c8529482 100644 --- a/packages/server/src/server/session.ts +++ b/packages/server/src/server/session.ts @@ -485,6 +485,7 @@ export interface SessionOptions { workspaceAutoName: WorkspaceAutoName; daemonConfigStore: DaemonConfigStore; pluginRuntime?: { + wait: import("./plugins/lifecycle/index.js").PluginLifecycle["wait"]; before: import("./plugins/lifecycle/index.js").PluginLifecycle["before"]; emit: import("./plugins/lifecycle/index.js").PluginLifecycle["emit"]; listPlugins(): Promise; @@ -518,7 +519,7 @@ export interface SessionOptions { removePlugin(pluginId: string): Promise; subscribe(listener: (pluginId: string) => void): () => void; subscribeSettings?(listener: (pluginId: string, settingsId: string) => void): () => void; - catalog(): Array<{ id: string; clientBundle: string }>; + catalog(): Array<{ id: string; clientBundle: string; clientBundleHash?: string }>; invokePluginRpc(pluginId: string, method: string, input: unknown): Promise; listUsageReports(options?: { forceRefresh?: boolean; @@ -576,12 +577,14 @@ export type SessionLifecycleIntent = clientId: string; requestId: string; reason: string; + keepTerminals: boolean; } | { type: "restart"; clientId: string; requestId: string; reason: string; + keepTerminals: boolean; }; function parseClientCapabilities( @@ -1039,6 +1042,7 @@ export class Session { logger: this.sessionLogger, }); this.usageSession = new UsageSession({ + isEnabled: () => daemonConfigStore.get().usage?.enabled !== false, emit: (msg) => this.emit(msg), runtime: pluginRuntime, logger: this.sessionLogger, @@ -1104,6 +1108,7 @@ export class Session { "Terminal output": this.terminalController.getMetrics().streamSubscriptionCount, }), listProviderAvailability: () => this.agentManager.listProviderAvailability(), + getTerminalsUnavailable: () => terminalManager?.getUnavailableError?.()?.message ?? null, listAgents: () => this.agentManager.listAgents(), listProjects: () => this.projectRegistry.list(), listWorkspaces: () => this.workspaceRegistry.list(), @@ -1125,11 +1130,11 @@ export class Session { terminalManager, emit: (msg) => this.emit(msg), hasBinaryChannel: () => this.onBinaryMessage !== null, + supportsChunkedReplay: (source) => + this.supportsForSource(CLIENT_CAPS.terminalChunkedReplay, source), isPathWithinRoot: (rootPath, candidatePath) => this.isPathWithinRoot(rootPath, candidatePath), sessionLogger: this.sessionLogger, listTerminalWorkspaceRefs: () => this.listActiveWorkspaceRefs(), - clientSupportsWrapReflow: (source) => - this.supportsForSource(CLIENT_CAPS.terminalReflowableSnapshot, source), getClientBufferedAmount: (source) => this.getTransportBufferedAmount(source), }); this.agentDirectory = new AgentDirectory({ @@ -1988,6 +1993,24 @@ export class Session { return; } + if (event.type === "agent_removed") { + if (event.internal) return; + void this.agentUpdates + .removeAgent(event.agentId) + .then(() => { + if (event.workspaceId) + return this.emitWorkspaceUpdateForWorkspaceId(event.workspaceId); + return undefined; + }) + .catch((error) => { + this.sessionLogger.error( + { err: error, agentId: event.agentId }, + "Failed to emit agent removal", + ); + }); + return; + } + if (event.type === "agent_state") { this.sessionLogger.trace( { @@ -2584,12 +2607,17 @@ export class Session { }); } if (msg.type === "plugin.catalog.get.request") { + const cached = new Map( + msg.cachedClientBundles?.map((entry) => [entry.id, entry.clientBundleHash]), + ); + const plugins = (this.pluginRuntime?.catalog() ?? []).map(({ clientBundle, ...plugin }) => + plugin.clientBundleHash !== undefined && cached.get(plugin.id) === plugin.clientBundleHash + ? plugin + : Object.assign(plugin, { clientBundle }), + ); this.emit({ type: "plugin.catalog.get.response", - payload: { - requestId: msg.requestId, - plugins: this.pluginRuntime?.catalog() ?? [], - }, + payload: { requestId: msg.requestId, plugins }, }); return undefined; } @@ -2722,9 +2750,13 @@ export class Session { case "dictation_stream_cancel": return this.voiceSessions.handleMessage(msg); case "restart_server_request": - return this.handleRestartServerRequest(msg.requestId, msg.reason); + return this.handleRestartServerRequest(msg.requestId, msg.reason, { + keepTerminals: msg.killTerminals !== true, + }); case "shutdown_server_request": - return this.handleShutdownServerRequest(msg.requestId); + return this.handleShutdownServerRequest(msg.requestId, { + keepTerminals: msg.keepTerminals === true, + }); case "client_heartbeat": this.handleClientHeartbeat(msg); return undefined; @@ -3250,7 +3282,11 @@ export class Session { this.terminalController.handleBinaryFrame(binaryFrame.frame, source); } - private async handleRestartServerRequest(requestId: string, reason?: string): Promise { + private async handleRestartServerRequest( + requestId: string, + reason: string | undefined, + options: { keepTerminals: boolean }, + ): Promise { const lifecycleReason = normalizeClientRestartRpcReason(reason); const payload: { status: string } & Record = { status: "restart_requested", @@ -3261,7 +3297,10 @@ export class Session { } payload.requestId = requestId; - this.sessionLogger.warn({ reason: lifecycleReason }, "Restart requested via websocket"); + this.sessionLogger.warn( + { reason: lifecycleReason, keepTerminals: options.keepTerminals }, + "Restart requested via websocket", + ); this.emit({ type: "status", payload, @@ -3272,12 +3311,19 @@ export class Session { clientId: this.clientId, requestId, reason: lifecycleReason, + keepTerminals: options.keepTerminals, }); } - private async handleShutdownServerRequest(requestId: string): Promise { + private async handleShutdownServerRequest( + requestId: string, + options: { keepTerminals: boolean }, + ): Promise { const reason = CLIENT_SHUTDOWN_RPC_REASON; - this.sessionLogger.warn({ reason }, "Shutdown requested via websocket"); + this.sessionLogger.warn( + { reason, keepTerminals: options.keepTerminals }, + "Shutdown requested via websocket", + ); this.emit({ type: "status", payload: { @@ -3292,6 +3338,7 @@ export class Session { clientId: this.clientId, requestId, reason, + keepTerminals: options.keepTerminals, }); } @@ -3309,10 +3356,8 @@ export class Session { private async handleDeleteAgentRequest(agentId: string, requestId: string): Promise { this.sessionLogger.info({ agentId }, `Deleting agent ${agentId} from registry`); - const knownWorkspaceId = - this.agentManager.getAgent(agentId)?.workspaceId ?? - (await this.agentStorage.get(agentId))?.workspaceId ?? - null; + const knownAgent = + this.agentManager.getAgent(agentId) ?? (await this.agentStorage.get(agentId)); // File-backed storage still needs an early delete fence before closeAgent(). beginAgentDeleteIfSupported(this.agentStorage, agentId); @@ -3333,6 +3378,8 @@ export class Session { try { await this.agentStorage.remove(agentId); await this.agentManager.deleteAgentState(agentId); + // Directory removal is daemon-wide; agent_deleted below stays a source-scoped RPC reply. + if (knownAgent) this.agentManager.notifyAgentRemoved(knownAgent); } catch (error) { this.sessionLogger.error({ err: error, agentId }, `Failed to fully delete agent ${agentId}`); } @@ -3344,12 +3391,6 @@ export class Session { requestId, }, }); - - await this.agentUpdates.removeAgent(agentId); - - if (knownWorkspaceId) { - await this.emitWorkspaceUpdateForWorkspaceId(knownWorkspaceId); - } } private async handleArchiveAgentRequest(agentId: string, requestId: string): Promise { @@ -4471,7 +4512,10 @@ export class Session { }, ); createdAgentId = snapshot.id; - await this.agentUpdates.forwardLiveAgent(snapshot); + // `snapshot` predates the initial prompt; subscribers keep the last state they receive. + await this.agentUpdates.forwardLiveAgent( + this.agentManager.getAgent(snapshot.id) ?? liveSnapshot, + ); if (resolvedIntent.createdDirectoryWorkspace && trimmedPrompt) { this.workspaceAutoName.scheduleForDirectory( { @@ -5982,6 +6026,7 @@ export class Session { }, ): Promise { const result = await createPaseoWorktree(input, { + lifecycle: this.pluginRuntime, github: this.github, ...(options?.resolveDefaultBranch ? { resolveDefaultBranch: options.resolveDefaultBranch } @@ -6790,7 +6835,7 @@ export class Session { // and must not rerun hooks or compare their potentially changing output. if (this.pluginRuntime) { const { type, requestId, ...input } = request; - const transformed = await this.pluginRuntime.before("workspace.create", input); + const transformed = await this.pluginRuntime.before("workspace.create.before", input); creationRequest = { ...transformed, type, requestId }; } return creationRequest.source.kind === "directory" @@ -7805,6 +7850,7 @@ export class Session { direction, cursor, limit: msg.limit, + wholeTurns: msg.wholeTurns, }); const selectedTimeline = { timeline: fetchedControlTimeline, diff --git a/packages/server/src/server/session.workspaces.test.ts b/packages/server/src/server/session.workspaces.test.ts index 3755ff56d8..343c0a8843 100644 --- a/packages/server/src/server/session.workspaces.test.ts +++ b/packages/server/src/server/session.workspaces.test.ts @@ -1393,6 +1393,136 @@ test("create_agent_request does not title an existing workspace from the agent p } }); +test("create_agent_request does not publish the pre-prompt snapshot after the prompt starts", async () => { + vi.useFakeTimers(); + const workdir = mkdtempSync(path.join(tmpdir(), "paseo-create-agent-live-state-")); + const logger = createTestLogger(); + const agentStorage = new AgentStorage(path.join(workdir, "agents"), asSessionLogger(logger)); + // The test session's turn starts and then reports nothing, like a provider + // that stays quiet until its turn ends. + const agentManager = new AgentManager({ + clients: { codex: new CreateAgentTestClient() }, + registry: agentStorage, + logger: asSessionLogger(logger), + idFactory: () => "00000000-0000-4000-8000-000000000553", + }); + try { + const cwd = path.join(workdir, "repo"); + mkdirSync(cwd, { recursive: true }); + + const projectRegistry = new FileBackedProjectRegistry( + path.join(workdir, "projects.json"), + asSessionLogger(logger), + ); + const workspaceRegistry = new FileBackedWorkspaceRegistry( + path.join(workdir, "workspaces.json"), + asSessionLogger(logger), + ); + + await projectRegistry.upsert( + createPersistedProjectRecord({ + projectId: "proj-live-state", + rootPath: cwd, + kind: "git", + displayName: "repo", + createdAt: "2026-05-07T00:00:00.000Z", + updatedAt: "2026-05-07T00:00:00.000Z", + }), + ); + await workspaceRegistry.upsert( + createPersistedWorkspaceRecord({ + workspaceId: "ws-live-state", + projectId: "proj-live-state", + cwd, + kind: "local_checkout", + displayName: "repo", + title: null, + createdAt: "2026-05-07T00:00:00.000Z", + updatedAt: "2026-05-07T00:00:00.000Z", + }), + ); + + const agentUpdates: Extract["payload"][] = []; + const session = asTestSession( + new Session({ + workspaceRuntimeStore: createWorkspaceRuntimeStore(), + messageReceipts: createMessageReceiptsStub(), + agentMessages: createAgentMessageDeliveryStub(), + creationService: createTestCreationService(), + clientId: "test-client", + permissions: OWNER_PERMISSIONS, + appVersion: null, + onMessage: (message) => { + if (message.type === "agent_update") agentUpdates.push(message.payload); + }, + logger: asSessionLogger(logger), + downloadTokenStore: asDownloadTokenStore(), + pushNotifications: asPushNotifications(), + paseoHome: path.join(workdir, "paseo-home"), + agentManager, + agentStorage, + projectRegistry, + workspaceRegistry, + scheduleService: asScheduleService(), + checkoutDiffManager: asCheckoutDiffManager({ + subscribe: async () => ({ + initial: { cwd, files: [], error: null }, + unsubscribe: () => {}, + }), + scheduleRefreshForCwd: () => {}, + onWorkspaceStateMayHaveChanged: () => {}, + invalidateForge: () => {}, + getMetrics: () => ({ + checkoutDiffTargetCount: 0, + checkoutDiffSubscriptionCount: 0, + checkoutDiffWatcherCount: 0, + checkoutDiffFallbackRefreshTargetCount: 0, + }), + dispose: () => {}, + }), + workspaceGitService: createNoopWorkspaceGitService(), + daemonConfigStore: asDaemonConfigStore({ + get: () => ({ mcp: { injectIntoAgents: false }, providers: {} }), + onChange: () => () => {}, + }), + mcpBaseUrl: null, + stt: null, + tts: null, + generateWorkspaceName: async () => null, + providerSnapshotManager: createProviderSnapshotManagerStub().manager, + terminalManager: null, + }), + ); + await activateAgentUpdatesSubscription(session, "sub-live-state"); + + await session.handleMessage({ + type: "create_agent_request", + requestId: "req-create-live-state", + workspaceId: "ws-live-state", + config: { provider: "codex", cwd }, + initialPrompt: "Print the report", + attachments: [], + }); + await vi.runAllTimersAsync(); + + const [createdAgent] = agentManager.listAgents(); + expect(createdAgent?.lifecycle).toBe("running"); + const upserts = agentUpdates.flatMap((update) => + update.kind === "upsert" && update.agent.id === createdAgent?.id ? [update.agent] : [], + ); + expect(upserts.length).toBeGreaterThan(0); + // A client keeps the last update it hears, so the latest one must be the running agent. + expect(upserts.at(-1)).toMatchObject({ status: "running" }); + const updatedAt = upserts.map((agent) => Date.parse(agent.updatedAt)); + expect(updatedAt).toEqual([...updatedAt].sort((left, right) => left - right)); + } finally { + // Drain snapshot writes before removing their storage directory. + await agentManager.flush(); + vi.useRealTimers(); + rmSync(workdir, { recursive: true, force: true }); + } +}); + test("unsupported persisted agents are excluded from active lists but preserved in history payloads", async () => { const session = createSessionForWorkspaceTests({ appVersion: "0.1.45" }); const storedRecord = { @@ -5991,6 +6121,9 @@ test("archive_workspace_request archives a worktree-kind workspace and removes t projectId, cwd: worktree.worktreePath, kind: "worktree", + worktreeRoot: worktree.worktreePath, + mainRepoRoot: repoDir, + isPaseoOwnedWorktree: true, displayName: "worktree-kind-archive", createdAt: "2026-03-01T12:00:00.000Z", updatedAt: "2026-03-01T12:00:00.000Z", diff --git a/packages/server/src/server/session/daemon/daemon-self-update-session-controller.test.ts b/packages/server/src/server/session/daemon/daemon-self-update-session-controller.test.ts index 81c41f3421..e9bcf94b65 100644 --- a/packages/server/src/server/session/daemon/daemon-self-update-session-controller.test.ts +++ b/packages/server/src/server/session/daemon/daemon-self-update-session-controller.test.ts @@ -118,6 +118,7 @@ describe("DaemonSelfUpdateSessionController", () => { clientId: "client-1", requestId: "update-1", reason: "daemon_update", + keepTerminals: true, }, ]); }); diff --git a/packages/server/src/server/session/daemon/daemon-self-update-session-controller.ts b/packages/server/src/server/session/daemon/daemon-self-update-session-controller.ts index 461a97277b..bb75f008bd 100644 --- a/packages/server/src/server/session/daemon/daemon-self-update-session-controller.ts +++ b/packages/server/src/server/session/daemon/daemon-self-update-session-controller.ts @@ -19,6 +19,7 @@ interface DaemonSelfUpdateRestartIntent { clientId: string; requestId: string; reason: string; + keepTerminals: boolean; } export interface DaemonSelfUpdateSessionControllerOptions { @@ -88,6 +89,8 @@ export class DaemonSelfUpdateSessionController { clientId: this.clientId, requestId: msg.requestId, reason: "daemon_update", + // A self-update restart keeps terminals: the worker outlives the daemon. + keepTerminals: true, }); } catch (error) { if (error instanceof DaemonSelfUpdateInProgressError) { diff --git a/packages/server/src/server/session/daemon/daemon-session.test.ts b/packages/server/src/server/session/daemon/daemon-session.test.ts index e96256c4cf..cb6da8777b 100644 --- a/packages/server/src/server/session/daemon/daemon-session.test.ts +++ b/packages/server/src/server/session/daemon/daemon-session.test.ts @@ -212,6 +212,7 @@ describe("DaemonSession", () => { { provider: "claude", available: true, error: null }, { provider: "codex", available: false, error: "boom" }, ], + terminalCleanupUnconfirmed: [], }, }, ]); @@ -242,6 +243,7 @@ describe("DaemonSession", () => { listen: null, relay: null, providers: [], + terminalCleanupUnconfirmed: [], }, }, ]); diff --git a/packages/server/src/server/session/daemon/daemon-session.ts b/packages/server/src/server/session/daemon/daemon-session.ts index ccc9e66e6d..585fa45573 100644 --- a/packages/server/src/server/session/daemon/daemon-session.ts +++ b/packages/server/src/server/session/daemon/daemon-session.ts @@ -2,6 +2,7 @@ import type pino from "pino"; import type { ProviderAvailability } from "../../agent/agent-manager.js"; import type { SessionInboundMessage, SessionOutboundMessage } from "../../messages.js"; import { getPidLockInfo } from "../../pid-lock.js"; +import { readUnconfirmedTerminalCleanup } from "../../../terminal/terminal-worker-reaper.js"; import { generateLocalPairingOffer } from "../../pairing-offer.js"; import { collectDaemonDiagnostics, @@ -35,6 +36,7 @@ export interface DaemonSessionHost { clientId: string; requestId: string; reason: string; + keepTerminals: boolean; }): void; } @@ -49,6 +51,8 @@ export interface DaemonSessionOptions { listProjects: () => Promise; listWorkspaces: () => Promise; listProviderAvailability: () => Promise; + /** Why this host's terminals cannot be served (held by a newer Paseo's worker), if so. */ + getTerminalsUnavailable?: () => string | null; getWebSocketRuntimeMetrics?: () => DaemonWebSocketRuntimeDiagnosticSnapshot | null; getObservationMetrics?: () => Record; logger: pino.Logger; @@ -74,6 +78,7 @@ export class DaemonSession { private readonly listProjects: () => Promise; private readonly listWorkspaces: () => Promise; private readonly listProviderAvailability: () => Promise; + private readonly getTerminalsUnavailable: () => string | null; private readonly getWebSocketRuntimeMetrics: () => DaemonWebSocketRuntimeDiagnosticSnapshot | null; private readonly getObservationMetrics: DaemonSessionOptions["getObservationMetrics"]; private readonly logger: pino.Logger; @@ -92,6 +97,7 @@ export class DaemonSession { this.listProjects = options.listProjects; this.listWorkspaces = options.listWorkspaces; this.listProviderAvailability = options.listProviderAvailability; + this.getTerminalsUnavailable = options.getTerminalsUnavailable ?? (() => null); this.getWebSocketRuntimeMetrics = options.getWebSocketRuntimeMetrics ?? (() => null); this.getObservationMetrics = options.getObservationMetrics; this.logger = options.logger; @@ -173,6 +179,12 @@ export class DaemonSession { async handleGetStatusRequest( msg: Extract, ): Promise { + // Read outside the degraded-status fallback below: a status that cannot say whether + // terminal cleanup finished must fail the request, not report that nothing is left. + const terminalCleanupUnconfirmed = (await readUnconfirmedTerminalCleanup(this.paseoHome)).map( + ({ pid, role, reason, detail }) => ({ pid, role, reason, detail }), + ); + const terminalsUnavailable = this.getTerminalsUnavailable(); try { const pidInfo = await getPidLockInfo(this.paseoHome); const providers = (await this.listProviderAvailability()).map((p) => ({ @@ -192,6 +204,8 @@ export class DaemonSession { listen: this.daemonRuntimeConfig?.listen ?? null, relay: this.daemonRuntimeConfig?.getRelayConfig() ?? null, providers, + terminalCleanupUnconfirmed, + ...(terminalsUnavailable ? { terminalsUnavailable } : {}), }, }); } catch (error) { @@ -208,6 +222,8 @@ export class DaemonSession { listen: null, relay: null, providers: [], + terminalCleanupUnconfirmed, + ...(terminalsUnavailable ? { terminalsUnavailable } : {}), }, }); } diff --git a/packages/server/src/server/session/usage/usage-session.test.ts b/packages/server/src/server/session/usage/usage-session.test.ts index 2aa65992b8..3a397094a3 100644 --- a/packages/server/src/server/session/usage/usage-session.test.ts +++ b/packages/server/src/server/session/usage/usage-session.test.ts @@ -15,6 +15,7 @@ test("lists reports from usage sources", async () => { report: { status: "available" as const, windows: [] }, }; const usage = new UsageSession({ + isEnabled: () => true, emit: (message) => emitted.push(message), runtime: { async listUsageReports(options) { @@ -40,6 +41,7 @@ test("lists reports from usage sources", async () => { test("surfaces a legacy usage-list failure as an rpc_error envelope", async () => { const emitted: SessionOutboundMessage[] = []; const usage = new UsageSession({ + isEnabled: () => true, emit: (message) => emitted.push(message), runtime: { async listUsageReports() { @@ -61,6 +63,7 @@ test("surfaces a legacy usage-list failure as an rpc_error envelope", async () = test("request failures terminate with an error response and no updates", async () => { const emitted: SessionOutboundMessage[] = []; const usage = new UsageSession({ + isEnabled: () => true, emit: (message) => emitted.push(message), logger: pino({ level: "silent" }), }); @@ -72,3 +75,36 @@ test("request failures terminate with an error response and no updates", async ( }, ]); }); + +test("off rejects both protocols before runtime discovery and turning on restores reports", async () => { + let enabled = false; + let calls = 0; + const emitted: SessionOutboundMessage[] = []; + const usage = new UsageSession({ + isEnabled: () => enabled, + emit: (message) => emitted.push(message), + logger: pino({ level: "silent" }), + runtime: { + async listUsageReports() { + calls++; + return []; + }, + async listLegacyUsage() { + calls++; + return { fetchedAt: "now", providers: [] }; + }, + }, + }); + await usage.handleListReports({ type: "usage.list_reports.request", requestId: "off" }); + await usage.handleLegacyList({ type: "provider.usage.list.request", requestId: "old" }); + expect(calls).toBe(0); + expect(emitted[0]).toMatchObject({ payload: { error: "Usage is off on this host." } }); + expect(emitted[1]).toMatchObject({ + type: "rpc_error", + payload: { error: "Usage is off on this host." }, + }); + enabled = true; + await usage.handleListReports({ type: "usage.list_reports.request", requestId: "on" }); + expect(calls).toBe(1); + expect(emitted[2]).toMatchObject({ payload: { error: null } }); +}); diff --git a/packages/server/src/server/session/usage/usage-session.ts b/packages/server/src/server/session/usage/usage-session.ts index 500c03a088..cd1e2e8801 100644 --- a/packages/server/src/server/session/usage/usage-session.ts +++ b/packages/server/src/server/session/usage/usage-session.ts @@ -9,6 +9,7 @@ export interface UsageSessionOptions { listUsageReports(options: ListUsageReportsOptions): Promise; listLegacyUsage(): Promise<{ fetchedAt: string; providers: ProviderUsage[] }>; }; + isEnabled: () => boolean; logger: pino.Logger; } @@ -19,6 +20,7 @@ export class UsageSession { msg: Extract, ): Promise { try { + if (!this.options.isEnabled()) throw new Error("Usage is off on this host."); if (!this.options.runtime) throw new Error("Plugin runtime is unavailable"); await this.options.runtime.listUsageReports({ forceRefresh: msg.forceRefresh, @@ -49,6 +51,18 @@ export class UsageSession { async handleLegacyList( msg: Extract, ): Promise { + if (!this.options.isEnabled()) { + this.options.emit({ + type: "rpc_error", + payload: { + requestId: msg.requestId, + requestType: msg.type, + error: "Usage is off on this host.", + code: "provider_usage_list_failed", + }, + }); + return; + } try { if (!this.options.runtime) throw new Error("Plugin runtime is unavailable"); const usage = await this.options.runtime.listLegacyUsage(); diff --git a/packages/server/src/server/session/workspace-provisioning/workspace-provisioning-service.test.ts b/packages/server/src/server/session/workspace-provisioning/workspace-provisioning-service.test.ts index 0a3b8cb257..c93e535709 100644 --- a/packages/server/src/server/session/workspace-provisioning/workspace-provisioning-service.test.ts +++ b/packages/server/src/server/session/workspace-provisioning/workspace-provisioning-service.test.ts @@ -175,7 +175,7 @@ test("background workspace creation preserves hooks, inheritance and durable vis expect(child.background).toBe(true); expect(visible.background).toBe(false); expect(human.background).toBe(false); - expect(events).toEqual(Array(4).fill("workspace.created")); + expect(events).toEqual(Array(4).fill("workspace.create.after")); const reloaded = new FileBackedWorkspaceRegistry( path.join(tmpDir, "projects", "workspaces.json"), logger, diff --git a/packages/server/src/server/session/workspace-provisioning/workspace-provisioning-service.ts b/packages/server/src/server/session/workspace-provisioning/workspace-provisioning-service.ts index 3ac91a834a..08d7b93bf4 100644 --- a/packages/server/src/server/session/workspace-provisioning/workspace-provisioning-service.ts +++ b/packages/server/src/server/session/workspace-provisioning/workspace-provisioning-service.ts @@ -307,7 +307,9 @@ export function createWorkspaceProvisioningService(deps: { } function emitWorkspaceCreated(workspace: PersistedWorkspaceRecord): void { - deps.lifecycle?.emit("workspace.created", { workspace: describeHookWorkspace(workspace) }); + deps.lifecycle?.emit("workspace.create.after", { + workspace: describeHookWorkspace(workspace), + }); } async function resolveSourceProjectForWorktree(input: { diff --git a/packages/server/src/server/session/workspace-recovery/workspace-recovery-service.test.ts b/packages/server/src/server/session/workspace-recovery/workspace-recovery-service.test.ts index 22e903b5f1..5526166d05 100644 --- a/packages/server/src/server/session/workspace-recovery/workspace-recovery-service.test.ts +++ b/packages/server/src/server/session/workspace-recovery/workspace-recovery-service.test.ts @@ -4,6 +4,7 @@ import { mkdirSync, mkdtempSync, realpathSync, + readFileSync, rmSync, statSync, writeFileSync, @@ -476,3 +477,43 @@ test("restore rejects a branch checked out elsewhere without inventing another b }).trim(), ).toBe("* feature"); }); + +test("restores a user-created worktree at its recorded path outside Paseo's root", async () => { + const { tempDir, repoDir } = createGitRepository(); + const worktreeRoot = join(realpathSync(tempDir), "external-worktree"); + execFileSync("git", ["worktree", "add", "-b", "external-feature", worktreeRoot], { + cwd: repoDir, + stdio: "pipe", + }); + const workspace = createWorkspace({ + cwd: worktreeRoot, + worktreeRoot, + mainRepoRoot: repoDir, + branch: "external-feature", + baseBranch: "main", + isPaseoOwnedWorktree: false, + }); + execFileSync("git", ["worktree", "remove", worktreeRoot], { cwd: repoDir, stdio: "pipe" }); + const unarchived: string[] = []; + const service = createWorkspaceRecoveryService({ + paseoHome: join(tempDir, "paseo-home"), + getWorkspace: async () => workspace, + getProject: async () => createProject({ rootPath: repoDir }), + isDirectory: async (target) => existsSync(target) && statSync(target).isDirectory(), + unarchiveWorkspace: async (record) => { + unarchived.push(record.workspaceId); + }, + }); + await expect(service.restore(workspace.workspaceId)).resolves.toEqual({ + workspaceId: workspace.workspaceId, + action: "restore", + }); + expect(readFileSync(join(worktreeRoot, "README.md"), "utf8").trim()).toBe("initial"); + expect( + execFileSync("git", ["branch", "--show-current"], { + cwd: worktreeRoot, + encoding: "utf8", + }).trim(), + ).toBe("external-feature"); + expect(unarchived).toEqual([workspace.workspaceId]); +}); diff --git a/packages/server/src/server/session/workspace-recovery/workspace-recovery-service.ts b/packages/server/src/server/session/workspace-recovery/workspace-recovery-service.ts index 1a715dd349..a683a07744 100644 --- a/packages/server/src/server/session/workspace-recovery/workspace-recovery-service.ts +++ b/packages/server/src/server/session/workspace-recovery/workspace-recovery-service.ts @@ -166,6 +166,7 @@ export function createWorkspaceRecoveryService(deps: { } let previousWorktreePath = workspace.worktreeRoot; + let hasRecordedWorktreePath = Boolean(previousWorktreePath); if (!previousWorktreePath) { // COMPAT(worktreeRestoreMissingWorktreeRoot): records created before v0.1.110 // lack durable backing placement; remove filesystem discovery after 2027-01-17. @@ -176,6 +177,7 @@ export function createWorkspaceRecoveryService(deps: { previousWorktreePath = ownership.allowed ? (ownership.worktreePath ?? workspace.cwd) : workspace.cwd; + hasRecordedWorktreePath = ownership.allowed; } let recreatedWorktreePath: string; @@ -187,6 +189,7 @@ export function createWorkspaceRecoveryService(deps: { paseoHome: deps.paseoHome, worktreesRoot: deps.worktreesRoot, + ...(hasRecordedWorktreePath ? { worktreePath: previousWorktreePath } : {}), }); recreatedWorktreePath = result.worktreePath; } catch (error) { diff --git a/packages/server/src/server/terminal-activity-route.test.ts b/packages/server/src/server/terminal-activity-route.test.ts index afc97d77e8..e047c56ab9 100644 --- a/packages/server/src/server/terminal-activity-route.test.ts +++ b/packages/server/src/server/terminal-activity-route.test.ts @@ -95,7 +95,13 @@ it("accepts terminalId and token reports through the route into the tracker", as command: process.execPath, args: [ "-e", - `require("node:fs").writeFileSync(${JSON.stringify(envPath)}, JSON.stringify({ terminalId: process.env.PASEO_TERMINAL_ID, token: process.env.PASEO_ACTIVITY_TOKEN, url: process.env.PASEO_TERMINAL_ACTIVITY_URL })); setInterval(() => {}, 1000);`, + ` + const fs = require("node:fs"); + const envPath = ${JSON.stringify(envPath)}; + fs.writeFileSync(envPath + ".tmp", JSON.stringify({ terminalId: process.env.PASEO_TERMINAL_ID, token: process.env.PASEO_ACTIVITY_TOKEN, url: process.env.PASEO_TERMINAL_ACTIVITY_URL })); + fs.renameSync(envPath + ".tmp", envPath); + setInterval(() => {}, 1000); + `, ], }); await waitForCondition(() => existsSync(envPath), 10000); diff --git a/packages/server/src/server/test-fixtures/reconciliation-registries.ts b/packages/server/src/server/test-fixtures/reconciliation-registries.ts new file mode 100644 index 0000000000..2d020ec23f --- /dev/null +++ b/packages/server/src/server/test-fixtures/reconciliation-registries.ts @@ -0,0 +1,117 @@ +import type pino from "pino"; +import { createPersistedProjectRecord } from "../workspace-registry.js"; +import type { + PersistedProjectRecord, + PersistedWorkspaceRecord, + ProjectRegistry, + WorkspaceRegistry, +} from "../workspace-registry.js"; + +export function createTestRegistries() { + let archiveGate: { + started: ReturnType; + release: ReturnType; + } | null = null; + const holdNextArchive = () => { + archiveGate = { started: deferred(), release: deferred() }; + return archiveGate; + }; + const projects = new Map(); + const workspaces = new Map(); + + const projectRegistry: ProjectRegistry = { + initialize: async () => {}, + existsOnDisk: async () => true, + list: async () => Array.from(projects.values()), + get: async (id: string) => projects.get(id) ?? null, + getOrCreateActiveByRoot: async (input) => { + const existing = Array.from(projects.values()).find( + (project) => !project.archivedAt && project.rootPath === input.rootPath, + ); + if (existing) return existing; + const record = createPersistedProjectRecord({ + projectId: `prj_${projects.size}`, + rootPath: input.rootPath, + kind: input.kind, + displayName: input.displayName, + createdAt: input.timestamp, + updatedAt: input.timestamp, + }); + projects.set(record.projectId, record); + return record; + }, + update: async (id, updater) => { + const current = projects.get(id); + if (!current) return null; + const updated = updater(current); + projects.set(id, updated); + return updated; + }, + upsert: async (record: PersistedProjectRecord) => { + projects.set(record.projectId, record); + }, + archive: async (id: string, archivedAt: string) => { + const existing = projects.get(id); + if (existing) { + projects.set(id, { ...existing, archivedAt, updatedAt: archivedAt }); + } + }, + remove: async (id: string) => { + projects.delete(id); + }, + }; + + const workspaceRegistry: WorkspaceRegistry = { + initialize: async () => {}, + existsOnDisk: async () => true, + list: async () => Array.from(workspaces.values()), + get: async (id: string) => workspaces.get(id) ?? null, + update: async (id, updater) => { + const existing = workspaces.get(id); + if (!existing) return null; + const updated = updater(existing); + workspaces.set(id, updated); + return updated; + }, + upsert: async (record: PersistedWorkspaceRecord) => { + workspaces.set(record.workspaceId, record); + }, + archive: async (id: string, archivedAt: string) => { + const gate = archiveGate; + archiveGate = null; + if (gate) { + gate.started.resolve(); + await gate.release.promise; + } + const existing = workspaces.get(id); + if (!existing || existing.archivedAt) return false; + workspaces.set(id, { ...existing, archivedAt, updatedAt: archivedAt }); + return true; + }, + remove: async (id: string) => { + workspaces.delete(id); + }, + }; + + return { projects, workspaces, projectRegistry, workspaceRegistry, holdNextArchive }; +} + +export function createTestLogger() { + const logger = { + child: () => logger, + trace: () => undefined, + debug: () => undefined, + info: () => undefined, + warn: () => undefined, + error: () => undefined, + }; + return logger as unknown as pino.Logger; +} + +export function deferred(): { promise: Promise; resolve(): void } { + let resolve!: () => void; + const promise = new Promise((accept) => { + resolve = accept; + }); + return { promise, resolve }; +} diff --git a/packages/server/src/server/test-fixtures/reconciliation-responsiveness.ts b/packages/server/src/server/test-fixtures/reconciliation-responsiveness.ts new file mode 100644 index 0000000000..dd73ce38a8 --- /dev/null +++ b/packages/server/src/server/test-fixtures/reconciliation-responsiveness.ts @@ -0,0 +1,92 @@ +import assert from "node:assert/strict"; +import { createHook, executionAsyncResource } from "node:async_hooks"; +import { MessagePort } from "node:worker_threads"; +import path from "node:path"; +import { stat } from "node:fs/promises"; +import { setImmediate as nextTurn } from "node:timers/promises"; +import { measureMainThreadWork } from "../../test-utils/main-thread-work.js"; +import { createTestRegistries, createTestLogger } from "./reconciliation-registries.js"; +import { + createPersistedProjectRecord, + createPersistedWorkspaceRecord, +} from "../workspace-registry.js"; +import { WorkspaceReconciliationService } from "../workspace-reconciliation-service.js"; +import { deriveProjectKey } from "../project-key.js"; + +const rootPath = process.argv[2]; +if (!rootPath) throw new Error("Project root is required"); +const timestamp = "2025-01-01T00:00:00.000Z"; +const { projects, workspaces, projectRegistry, workspaceRegistry } = createTestRegistries(); +projects.set( + "p1", + createPersistedProjectRecord({ + projectId: "p1", + rootPath, + projectKey: deriveProjectKey({ + rootPath, + remoteUrl: null, + worktreeRoot: null, + mainRepoRoot: null, + }), + kind: "non_git", + displayName: "project", + createdAt: timestamp, + updatedAt: timestamp, + }), +); +for (let i = 0; i < 20000; i++) { + const workspaceId = `w${i}`; + workspaces.set( + workspaceId, + createPersistedWorkspaceRecord({ + workspaceId, + projectId: "p1", + cwd: path.join(rootPath, workspaceId), + kind: "directory", + displayName: workspaceId, + createdAt: timestamp, + updatedAt: timestamp, + }), + ); +} +const service = new WorkspaceReconciliationService({ + projectRegistry, + workspaceRegistry, + logger: createTestLogger(), +}); + +// Compile before launch and measure in plain Node, outside the test runner's +// thread and TypeScript loader. Keep the first real reconciliation cold. +// Initialize async filesystem support using the bundle, leaving every project +// and workspace path untouched until the first reconciliation. +await stat(process.argv[1]); +// Collect fixture allocations before the measured run; allocations made by +// reconciliation itself remain part of its budget. +assert.ok(global.gc, "Launch the probe with --expose-gc"); +global.gc(); +await nextTurn(); +let workerMessages = 0; +const activity = createHook({ + before() { + if (executionAsyncResource() instanceof MessagePort) workerMessages++; + }, +}).enable(); +try { + const measured = await measureMainThreadWork("workspace reconciliation main-thread work", () => + service.runOnce(), + ); + activity.disable(); + process.stdout.write( + JSON.stringify({ + blockingMs: measured.blockingMs, + filesystemRequests: measured.filesystemRequests, + yields: measured.yields, + workerMessages, + changesApplied: measured.result.changesApplied.length, + allArchived: [...workspaces.values()].every((workspace) => workspace.archivedAt !== null), + }), + ); +} finally { + activity.disable(); + service.dispose(); +} diff --git a/packages/server/src/server/test-utils/fake-agent-client.ts b/packages/server/src/server/test-utils/fake-agent-client.ts index 42ac0c7c79..4304a767e1 100644 --- a/packages/server/src/server/test-utils/fake-agent-client.ts +++ b/packages/server/src/server/test-utils/fake-agent-client.ts @@ -67,6 +67,7 @@ interface FakeAgentSessionOptions { export interface TestAgentClientOptions { beforeCreateSession?: (config: AgentSessionConfig) => Promise; + beforeResumeSession?: (handle: AgentPersistenceHandle) => Promise; closeSession?: () => Promise; onStartTurn?: (prompt: AgentPromptInput, config: AgentSessionConfig) => void; beforeTurnComplete?: (prompt: AgentPromptInput) => Promise; @@ -1254,6 +1255,7 @@ class FakeAgentClient implements AgentClient { overrides?: Partial, _launchContext?: AgentLaunchContext, ): Promise { + await this.options.beforeResumeSession?.(handle); const cfg: AgentSessionConfig = { provider: this.provider, cwd: overrides?.cwd ?? process.cwd(), diff --git a/packages/server/src/server/test-utils/finish-subscription-daemon.ts b/packages/server/src/server/test-utils/finish-subscription-daemon.ts index d35bc55ec8..eafe11e74a 100644 --- a/packages/server/src/server/test-utils/finish-subscription-daemon.ts +++ b/packages/server/src/server/test-utils/finish-subscription-daemon.ts @@ -9,18 +9,24 @@ const root = process.argv[2]; if (!root || !process.send) throw new Error("Expected isolated test home and IPC parent"); await mkdir(join(root, "static"), { recursive: true }); const held = Promise.withResolvers(); +const fixture = JSON.parse(process.argv[4] ?? "{}") as { holdResume?: boolean }; +const resumeReleased = Promise.withResolvers(); +if (!fixture.holdResume) resumeReleased.resolve(); const daemon = await createTestPaseoDaemon({ paseoHomeRoot: root, + ...JSON.parse(process.argv[3] ?? "{}"), staticDir: join(root, "static"), logger: pino({ level: "warn" }, pino.destination(join(root, "fixture.log"))), cleanup: false, mcpEnabled: true, agentClients: createTestAgentClients({ - onStartTurn: (prompt) => { + onStartTurn: (prompt, config) => { + void appendFile(join(root, "all-prompts.jsonl"), `${JSON.stringify({ prompt, config })}\n`); if (String(prompt).includes('kind="agent-notification"')) { void appendFile(join(root, "parent-prompts.jsonl"), `${JSON.stringify(prompt)}\n`); } }, + beforeResumeSession: () => resumeReleased.promise, beforeTurnComplete: (prompt) => String(prompt).includes("HOLD_CHILD") ? held.promise : Promise.resolve(), }), @@ -28,6 +34,7 @@ const daemon = await createTestPaseoDaemon({ process.send({ port: daemon.port, paseoHome: daemon.paseoHome, cwd: daemon.staticDir }); process.on("message", (message) => { if (message === "finish") held.resolve(); + if (message === "release-resume") resumeReleased.resolve(); if (message === "stop") { void daemon.close().then( () => process.exit(0), diff --git a/packages/server/src/server/test-utils/paseo-daemon.test.ts b/packages/server/src/server/test-utils/paseo-daemon.test.ts index 4ee417c221..3fbb0b5232 100644 --- a/packages/server/src/server/test-utils/paseo-daemon.test.ts +++ b/packages/server/src/server/test-utils/paseo-daemon.test.ts @@ -45,7 +45,15 @@ describe("createTestPaseoDaemon", () => { createTestPaseoDaemon({ listenPort: takenPort, cleanup: false, mcpEnabled: false }), ).rejects.toMatchObject({ code: "EADDRINUSE" }); - expect(await readdir(scratchTmp)).toEqual([]); + // A home under this scratch dir is too long for a unix socket path, so the terminal worker + // listens in the per-user `paseo-` directory of the temp root. Like tmux's, that + // owner-only directory is shared by every worker and outlives them; it must be empty. + const sharedSocketDir = `paseo-${process.getuid?.() ?? 0}`; + const leftovers = await readdir(scratchTmp); + expect(leftovers.filter((name) => name !== sharedSocketDir)).toEqual([]); + if (leftovers.includes(sharedSocketDir)) { + expect(await readdir(path.join(scratchTmp, sharedSocketDir))).toEqual([]); + } }, 60_000); }); diff --git a/packages/server/src/server/test-utils/paseo-daemon.ts b/packages/server/src/server/test-utils/paseo-daemon.ts index a1f8369b59..766fd49919 100644 --- a/packages/server/src/server/test-utils/paseo-daemon.ts +++ b/packages/server/src/server/test-utils/paseo-daemon.ts @@ -52,6 +52,8 @@ interface TestPaseoDaemonOptions { trustedProxies?: PaseoDaemonConfig["trustedProxies"]; agentProfiles?: AgentProfile[]; autoArchiveAfterMerge?: boolean; + resumeOnStartup?: boolean; + resumePrompt?: string; pluginsEnabled?: PaseoDaemonConfig["pluginsEnabled"]; builtinPlugins?: BuiltinPluginLoader; plugins?: PaseoDaemonConfig["plugins"]; @@ -226,6 +228,8 @@ async function prepareTestDaemonConfig( downloadTokenTtlMs: options.downloadTokenTtlMs, agentProfiles: options.agentProfiles, autoArchiveAfterMerge: options.autoArchiveAfterMerge, + resumeOnStartup: options.resumeOnStartup, + resumePrompt: options.resumePrompt, pluginsEnabled: options.pluginsEnabled, plugins: options.plugins, }; diff --git a/packages/server/src/server/utils/diff-highlighter.test.ts b/packages/server/src/server/utils/diff-highlighter.test.ts index 3ecb0372ad..794cd00856 100644 --- a/packages/server/src/server/utils/diff-highlighter.test.ts +++ b/packages/server/src/server/utils/diff-highlighter.test.ts @@ -3,7 +3,7 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { describe, expect, it } from "vitest"; import { setImmediate } from "node:timers/promises"; -import { performance } from "node:perf_hooks"; +import { measureMainThreadWork } from "../../test-utils/main-thread-work.js"; import { SessionDelivery } from "../session/owned-subscriptions/index.js"; import { highlightCode, highlightCodeWithBudget } from "@getpaseo/highlight"; import { @@ -840,26 +840,19 @@ describe("diff highlighting budget", () => { @@ -1 +1 @@ -const value = Math.max(42, 7); +const value = Math.max(43, 7);`)[0]; - let lastTick = performance.now(); - let longestGap = 0; - const timer = setInterval(() => { - const now = performance.now(); - longestGap = Math.max(longestGap, now - lastTick); - lastTick = now; - }, 1); try { - await setImmediate(); - const highlighted = await highlightDiffWithFileContent( - file, - cwd, - source === "supplied" ? { oldFileContent } : {}, + const { result: highlighted, blockingMs } = await measureMainThreadWork( + `diff highlight 5MiB ${source} main-thread work`, + () => + highlightDiffWithFileContent( + file, + cwd, + source === "supplied" ? { oldFileContent } : {}, + ), ); - await new Promise((resolve) => setTimeout(resolve, 5)); - console.info({ sourceBytes: Buffer.byteLength(oldFileContent), longestGap }); - expect(longestGap).toBeLessThan(50); + expect(blockingMs).toBeLessThan(50); expect(highlighted).toEqual(highlightDiffFromHunks(file)); } finally { - clearInterval(timer); rmSync(cwd, { recursive: true, force: true }); } }, @@ -952,23 +945,17 @@ it("highlights a one-line hunk from an over-budget JSON source without blocking @@ -2 +2 @@ - "value": 42, + "value": 43,`); - let last = performance.now(), - longestGap = 0; - const timer = setInterval(() => { - const now = performance.now(); - longestGap = Math.max(longestGap, now - last); - last = now; - }, 1); try { - const result = await highlightDiffWithFileContent(file, cwd, { oldFileContent }); - await new Promise((resolve) => setTimeout(resolve, 5)); - expect(longestGap).toBeLessThan(50); + const { result, blockingMs } = await measureMainThreadWork( + "diff highlight large JSON main-thread work", + () => highlightDiffWithFileContent(file, cwd, { oldFileContent }), + ); + expect(blockingMs).toBeLessThan(50); expect(result.hunks[0].lines.find((line) => line.type === "add")?.tokens).toContainEqual({ text: "43", style: "number", }); } finally { - clearInterval(timer); rmSync(cwd, { recursive: true, force: true }); } }); diff --git a/packages/server/src/server/watcher-liveness-canary.test.ts b/packages/server/src/server/watcher-liveness-canary.test.ts index 4da1481408..7e719da9f0 100644 --- a/packages/server/src/server/watcher-liveness-canary.test.ts +++ b/packages/server/src/server/watcher-liveness-canary.test.ts @@ -1,4 +1,5 @@ -import { mkdtemp, rm } from "node:fs/promises"; +import { watchFile, unwatchFile } from "node:fs"; +import { mkdtemp, readFile, rm, stat } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterEach, expect, test } from "vitest"; @@ -31,3 +32,39 @@ test("rejects when the watcher never reports the canary", async () => { await expect(canary.verify()).rejects.toThrow("did not report its liveness canary"); }); + +test("verifies a watcher that starts delivering after the initial canary write", async () => { + const watchRoot = await mkdtemp(join(tmpdir(), "paseo-watcher-canary-")); + cleanupPaths.push(watchRoot); + const canary = createWatcherLivenessCanary(watchRoot); + const verification = canary.verify(); + const verified = expect(verification).resolves.toBeUndefined(); + + // The initial write happens before the observer starts delivering changes. + await expect.poll(() => readFile(canary.path, "utf8")).toBe("paseo watcher liveness canary\n"); + watchFile(canary.path, { interval: 10 }, () => { + canary.filterEvents([{ path: canary.path, type: "update" }]); + }); + try { + await verified; + await expect(readFile(canary.path)).rejects.toMatchObject({ code: "ENOENT" }); + } finally { + unwatchFile(canary.path); + } +}); + +test("aborting verification stops pulses before removing the canary", async () => { + const watchRoot = await mkdtemp(join(tmpdir(), "paseo-watcher-canary-")); + cleanupPaths.push(watchRoot); + const canary = createWatcherLivenessCanary(watchRoot); + const controller = new AbortController(); + const verification = canary.verify(controller.signal); + const cancelled = expect(verification).rejects.toThrow("stop watching"); + await expect.poll(() => readFile(canary.path, "utf8")).toBe("paseo watcher liveness canary\n"); + const initialWrite = (await stat(canary.path)).mtimeMs; + await expect.poll(async () => (await stat(canary.path)).mtimeMs).toBeGreaterThan(initialWrite); + + controller.abort(new Error("stop watching")); + await cancelled; + await expect(readFile(canary.path)).rejects.toMatchObject({ code: "ENOENT" }); +}); diff --git a/packages/server/src/server/watcher-liveness-canary.ts b/packages/server/src/server/watcher-liveness-canary.ts index a366f0229a..2fc5c5dbdf 100644 --- a/packages/server/src/server/watcher-liveness-canary.ts +++ b/packages/server/src/server/watcher-liveness-canary.ts @@ -1,9 +1,11 @@ import { randomUUID } from "node:crypto"; import { rm, writeFile } from "node:fs/promises"; import { join } from "node:path"; +import { setInterval } from "node:timers/promises"; import type { FileChange } from "./file-observer/index.js"; export const WATCHER_LIVENESS_CANARY_TIMEOUT_MS = 10_000; +const CANARY_CONTENTS = "paseo watcher liveness canary\n"; export interface WatcherLivenessCanary { readonly path: string; @@ -32,7 +34,11 @@ export function createWatcherLivenessCanary( return filtered; }, async verify(signal) { - await writeFile(canaryPath, "paseo watcher liveness canary\n", { flag: "wx" }); + await writeFile(canaryPath, CANARY_CONTENTS, { flag: "wx" }); + // Native registration can return before macOS starts its FSEvents stream. + // Keep probing until an event round-trips instead of relying on the first write. + const pulses = new AbortController(); + const pulsing = pulseCanary(canaryPath, pulses.signal); let timeout: NodeJS.Timeout | null = null; let removeAbortListener = () => {}; try { @@ -55,12 +61,24 @@ export function createWatcherLivenessCanary( signal.addEventListener("abort", rejectForAbort, { once: true }); removeAbortListener = () => signal.removeEventListener("abort", rejectForAbort); }); - await Promise.race([reported, timeoutPromise, abortPromise]); + await Promise.race([reported, timeoutPromise, abortPromise, pulsing]); } finally { if (timeout) clearTimeout(timeout); removeAbortListener(); + pulses.abort(); + await Promise.allSettled([pulsing]); await rm(canaryPath, { force: true }); } }, }; } + +async function pulseCanary(path: string, signal: AbortSignal): Promise { + try { + for await (const _ of setInterval(100, undefined, { signal })) { + await writeFile(path, CANARY_CONTENTS); + } + } catch (error) { + if (!signal.aborted) throw error; + } +} diff --git a/packages/server/src/server/websocket-server.file-transfer.e2e.test.ts b/packages/server/src/server/websocket-server.file-transfer.e2e.test.ts index 5131456ee9..abce664ffd 100644 --- a/packages/server/src/server/websocket-server.file-transfer.e2e.test.ts +++ b/packages/server/src/server/websocket-server.file-transfer.e2e.test.ts @@ -90,7 +90,11 @@ test( TEST_TIMEOUT_MS, ); -async function connectSocket(port: number, clientId: string): Promise { +async function connectSocket( + port: number, + clientId: string, + capabilities?: Record, +): Promise { const socket = new WebSocket(`ws://127.0.0.1:${port}/ws`); await new Promise((resolve, reject) => { socket.once("open", resolve); @@ -98,7 +102,7 @@ async function connectSocket(port: number, clientId: string): Promise }); await sendAndWait( socket, - { type: "hello", clientId, clientType: "browser", protocolVersion: 1 }, + { type: "hello", clientId, clientType: "browser", protocolVersion: 1, capabilities }, (message) => message.type === "session" && message.message.type === "status" && @@ -166,3 +170,97 @@ function sendAndWait( socket.send(JSON.stringify(message)); return response; } + +test("an awaited timeline framing overflow closes the actual daemon socket", async () => { + const { createHostClient } = await import("@getpaseo/client/node"); + const { createPaseoApi } = await import("@getpaseo/client"); + const { default: pino } = await import("pino"); + const { Writable } = await import("node:stream"); + const messages: string[] = []; + const logger = pino( + { level: "warn" }, + new Writable({ + write(chunk, _encoding, done) { + messages.push(JSON.parse(chunk.toString()).msg); + done(); + }, + }), + ); + daemon = await createTestPaseoDaemon({ logger }); + const client = createHostClient(`127.0.0.1:${daemon.port}`, { + clientId: "framing-seed", + reconnect: { enabled: false }, + }); + await client.connect(); + const api = createPaseoApi(client); + try { + const workspace = await api.workspaces.create({ + source: { kind: "directory", path: daemon.staticDir }, + }); + const agents = []; + const text = "x".repeat(240 * 1024); + for (const [index, rows] of [350, 90].entries()) { + const agent = await workspace.agents.create({ + config: { provider: "claude/claude-test", modeId: "full-access" }, + title: `Framing overflow ${index}`, + }); + agents.push(agent.id); + for (let row = 0; row < rows; row++) + await daemon.daemon.agentManager.appendTimelineItem(agent.id, { + type: "user_message", + text, + }); + } + const source = await connectSocket(daemon.port, "framing-overflow", { + binary_chunking_v1: true, + }); + sockets.push(source); + const closed = new Promise((resolve) => source.once("close", () => resolve())); + const firstChunk = new Promise((resolve) => { + const listener = (data: RawData, binary: boolean) => { + if (!binary || (data as Buffer)[0] !== 0x31) return; + source.off("message", listener); + source.pause(); + resolve(); + }; + source.on("message", listener); + }); + const fetch = (agentId: string, requestId: string) => + source.send( + JSON.stringify({ + type: "session", + message: { + type: "fetch_agent_timeline_request", + requestId, + agentId, + direction: "tail", + projection: "canonical", + limit: 0, + }, + }), + ); + fetch(agents[0]!, "first"); + await firstChunk; + fetch(agents[1]!, "overflow"); + await expect + .poll(() => messages.includes("Closing physical WebSocket after outbound framing failure"), { + timeout: 15000, + }) + .toBe(true); + expect(messages).not.toContain("Closing physical WebSocket at outbound high-water mark"); + source.resume(); + await closed; + } finally { + await api.dispose(); + await client.close(); + } +}, 60000); + +test("malformed chunk metadata closes the daemon socket with a protocol error", async () => { + daemon = await createTestPaseoDaemon(); + const source = await connectSocket(daemon.port, "invalid-framing", { binary_chunking_v1: true }); + sockets.push(source); + const closed = new Promise((resolve) => source.once("close", (code) => resolve(code))); + source.send(new Uint8Array([0x31, 2, 0, 3, 65])); + expect(await closed).toBe(1002); +}); diff --git a/packages/server/src/server/websocket-server.relay-reconnect.test.ts b/packages/server/src/server/websocket-server.relay-reconnect.test.ts index 2d48a93c87..c99d5ac9cc 100644 --- a/packages/server/src/server/websocket-server.relay-reconnect.test.ts +++ b/packages/server/src/server/websocket-server.relay-reconnect.test.ts @@ -1157,6 +1157,7 @@ describe("relay external socket reconnect behavior", () => { expect(serverInfo.features?.workspaceMarkUnread).toBe(true); expect(serverInfo.features?.["terminal-input-mode-replay"]).toBe(true); expect(serverInfo.features?.["terminal-size-ownership"]).toBe(true); + expect(serverInfo.features?.["terminal-grapheme-widths"]).toBe(true); expect(serverInfo.features?.agentTurnIdentity).toBeUndefined(); expect(serverInfo.permissions).toEqual(DAEMON_PERMISSIONS); await server.close(); diff --git a/packages/server/src/server/websocket-server.ts b/packages/server/src/server/websocket-server.ts index 4473a4004d..7089812d21 100644 --- a/packages/server/src/server/websocket-server.ts +++ b/packages/server/src/server/websocket-server.ts @@ -1,3 +1,7 @@ +import { + ChunkedTransport, + ChunkedTransportProtocolError, +} from "@getpaseo/protocol/chunked-transport"; import { type WorkspaceRuntimeStore } from "./workspace-runtime-store/index.js"; import { createAgentMessageDelivery, @@ -124,8 +128,8 @@ import { MAX_PHYSICAL_SOCKET_BUFFERED_BYTES, outboundFrameByteLength, physicalSocketHasCapacity, - sendBoundedPhysicalFrame, sendBoundedPhysicalFrameAndWait, + sendBoundedPhysicalFrame, } from "./websocket/physical-socket.js"; const WS_CLOSE_DAEMON_AUTH_FAILED = 4401; @@ -440,6 +444,7 @@ function bufferFromWsData(data: Buffer | ArrayBuffer | Buffer[] | string): Buffe } export interface WebSocketLike { + maxFrameBytes?: number; readyState: number; bufferedAmount?: number; send: ( @@ -1273,6 +1278,67 @@ export class VoiceAssistantWebSocketServer { return { sockets: writableSockets, payload, bytes: outboundFrameByteLength(payload) }; } + private sendHelloResponse(ws: WebSocketLike, session: Session, hello: WSHelloMessage): void { + // The peer learns our support from this ordinary response before receiving chunks. + this.sendToClient(ws, this.createServerInfoMessage(session)); + this.chunkedSocket(ws).enabled = hello.capabilities?.[CLIENT_CAPS.binaryChunkingV1] === true; + } + + private readonly chunkedSockets = new WeakMap(); + + private chunkedSocket(ws: WebSocketLike): ChunkedTransport { + let transport = this.chunkedSockets.get(ws); + if (!transport) { + transport = new ChunkedTransport({ + frameBytes: ws.maxFrameBytes ?? 32 * 1024 * 1024, + onFailure: (err) => + this.closePhysicalSocket({ + ws, + logMessage: "Closing physical WebSocket after outbound framing failure", + logFields: { err }, + }), + send: (frame, waitForDrain) => { + const params = { + socket: ws, + frame, + onHighWater: () => this.closeAtOutboundHighWater(ws), + }; + if (waitForDrain) + return sendBoundedPhysicalFrameAndWait(params).then((sent) => { + if (!sent) throw new Error("Source is closed"); + return undefined; + }); + if (!sendBoundedPhysicalFrame(params)) throw new Error("Source is closed"); + }, + deliver: (frame) => + this.handleRawMessage(ws, typeof frame === "string" ? frame : Buffer.from(frame)), + }); + this.chunkedSockets.set(ws, transport); + } + return transport; + } + + private socketBufferedAmount(ws: WebSocketLike): number | null { + const queued = this.chunkedSockets.get(ws)?.queuedByteLength ?? 0; + if (typeof ws.bufferedAmount === "number") return ws.bufferedAmount + queued; + return queued > 0 ? queued : null; + } + + private sendSocketFrame( + ws: WebSocketLike, + frame: string | Uint8Array, + bytes: number, + waitForDrain = false, + ): Promise { + const transport = this.chunkedSocket(ws); + const admittedBytes = transport.isWriting + ? bytes + : Math.min(bytes, ws.maxFrameBytes ?? 32 * 1024 * 1024); + if (!this.ensureOutboundCapacity(ws, admittedBytes)) + return Promise.reject(new Error("Source is closed")); + return transport.send(frame, { waitForDrain, byteLength: bytes }); + } + private async sendMessageToClientAndWait( ws: WebSocketLike, message: WSOutboundMessage, @@ -1280,13 +1346,7 @@ export class VoiceAssistantWebSocketServer { const prepared = this.prepareJsonDelivery([ws], message, true); if (!prepared) throw new Error("Source message delivery unavailable"); try { - const sent = await sendBoundedPhysicalFrameAndWait({ - socket: ws, - frame: prepared.payload, - frameBytes: prepared.bytes, - onHighWater: () => this.closeAtOutboundHighWater(ws), - }); - if (!sent) throw new Error("Source is closed"); + await this.sendSocketFrame(ws, prepared.payload, prepared.bytes, true); this.runtimeMetrics.recordOutboundMessage(message, ws.bufferedAmount); } catch (err) { this.logger.warn({ err }, "ws_send_failed"); @@ -1313,14 +1373,7 @@ export class VoiceAssistantWebSocketServer { return; } try { - const sent = await sendBoundedPhysicalFrameAndWait({ - socket: ws, - frame, - onHighWater: () => this.closeAtOutboundHighWater(ws), - }); - if (!sent) { - throw new Error("Physical WebSocket is not open"); - } + await this.sendSocketFrame(ws, frame, frame.byteLength, true); this.runtimeMetrics.recordOutboundBinaryFrame(ws.bufferedAmount); } catch (err) { this.logger.warn({ err }, "ws_send_failed"); @@ -1335,13 +1388,9 @@ export class VoiceAssistantWebSocketServer { recordSent: () => void, ): void { try { - const sent = sendBoundedPhysicalFrame({ - socket: ws, - frame, - frameBytes, - onHighWater: () => this.closeAtOutboundHighWater(ws), + void this.sendSocketFrame(ws, frame, frameBytes).then(recordSent, (err) => { + this.logger.warn({ err }, "ws_send_failed"); }); - if (sent) recordSent(); } catch (err) { this.logger.warn({ err }, "ws_send_failed"); } @@ -1349,7 +1398,13 @@ export class VoiceAssistantWebSocketServer { private ensureOutboundCapacity(ws: WebSocketLike, frameBytes: number): boolean { if (ws.readyState !== 1) return false; - if (physicalSocketHasCapacity(ws, frameBytes)) return true; + if ( + physicalSocketHasCapacity( + { bufferedAmount: this.socketBufferedAmount(ws) ?? undefined }, + frameBytes, + ) + ) + return true; this.closeAtOutboundHighWater(ws); return false; @@ -1522,16 +1577,15 @@ export class VoiceAssistantWebSocketServer { if (!connection) { return null; } - if (source) return (source as WebSocketLike).bufferedAmount ?? null; + if (source) return this.socketBufferedAmount(source as WebSocketLike); // Relay-attached sockets are a WebSocketLike that doesn't expose // bufferedAmount. Return null when no socket gives a signal so the // terminal fallback can't mistake "no signal" for "client keeping up"; // a direct ws reports its real buffered bytes (0 when drained). let maxBuffered: number | null = null; for (const socket of connection.sockets) { - if (typeof socket.bufferedAmount === "number") { - maxBuffered = Math.max(maxBuffered ?? 0, socket.bufferedAmount); - } + const buffered = this.socketBufferedAmount(socket); + if (buffered !== null) maxBuffered = Math.max(maxBuffered ?? 0, buffered); } return maxBuffered; }, @@ -1568,8 +1622,9 @@ export class VoiceAssistantWebSocketServer { let total = 0; for (const socket of this.sessions.keys()) { if (socket instanceof VirtualHostSocket) continue; - if (typeof socket.bufferedAmount !== "number") return null; - total += socket.bufferedAmount; + const buffered = this.socketBufferedAmount(socket); + if (buffered === null) return null; + total += buffered; } return total; }, @@ -1770,7 +1825,7 @@ export class VoiceAssistantWebSocketServer { this.externalSessionsByKey.set(sessionKey, connection); } pending.identity.sessionId = connection.session.getSessionId(); - this.sendToClient(ws, this.createServerInfoMessage(connection.session)); + this.sendHelloResponse(ws, connection.session, message); connection.connectionLogger.info( { ...toConnectionLogFields(pending.identity), @@ -1906,7 +1961,7 @@ export class VoiceAssistantWebSocketServer { existing.sockets.add(ws); this.sessions.set(ws, existing); pending.identity.sessionId = existing.session.getSessionId(); - this.sendToClient(ws, this.createServerInfoMessage(existing.session)); + this.sendHelloResponse(ws, existing.session, message); pending.connectionLogger.info( { ...toConnectionLogFields(pending.identity), @@ -1949,8 +2004,10 @@ export class VoiceAssistantWebSocketServer { hostMultiplexing: true, // COMPAT(relayProtectedSecurity): added in v0.13.0, remove gate after 2027-04-21. relayProtectedSecurity: true, + usageSetting: true, usageSources: true, ownedSubscriptions: true, + binaryChunkingV1: true, agentRequestReceipts: true, workspaceRequestReceipts: true, creationLifecycle: true, @@ -2013,12 +2070,15 @@ export class VoiceAssistantWebSocketServer { skillManagement: true, // COMPAT(idleRuntimeCleanupSetting): added in v0.13.0, remove gate after 2027-04-26. idleRuntimeCleanupSetting: true, + resumeOnStartupSetting: true, // COMPAT(terminalRestoreModes): added in v0.1.81, remove gate after 2026-11-23. "terminal-restore-modes": true, // COMPAT(terminalInputModeReplay): added in v0.2.6, remove gate after 2027-02-02. "terminal-input-mode-replay": true, // COMPAT(terminalSizeOwnership): added in v0.2.6, remove gate after 2027-02-02. "terminal-size-ownership": true, + // COMPAT(terminalGraphemeWidths): added in v0.15.0, remove gate after 2027-05-01. + "terminal-grapheme-widths": true, workspaceTerminals: true, // COMPAT(rewind): added in v0.1.X, drop the gate when floor >= v0.1.X. rewind: true, @@ -2054,6 +2114,8 @@ export class VoiceAssistantWebSocketServer { daemonDiagnostics: true, // COMPAT(daemonSelfUpdate): added in v0.1.93, remove gate after 2026-12-13. daemonSelfUpdate: this.daemonRuntimeConfig?.desktopManaged !== true, + // COMPAT(terminalsSurviveRestart): added in v0.12.0, remove gate after 2027-04-21. + terminalsSurviveRestart: true, // COMPAT(agentForkContext): added in v0.1.102, remove gate after 2026-12-28. agentForkContext: true, // COMPAT(agentForkContextCursor): added in v0.1.108, remove gate after 2027-01-14. @@ -2062,6 +2124,7 @@ export class VoiceAssistantWebSocketServer { providerSubagents: true, // COMPAT(projectedSubagentTimeline): added after v0.8.0, remove gates after 2027-03-14; retain advertisement. projectedSubagentTimeline: true, + wholeTurnTimeline: true, // COMPAT(providerSubagentNesting): added in v0.7, remove gate after 2027-03-04. providerSubagentNesting: true, // COMPAT(workspacePinning): added in v0.1.107, remove gate after 2027-01-12. @@ -2160,10 +2223,16 @@ export class VoiceAssistantWebSocketServer { private bindSocketHandlers(ws: WebSocketLike): void { ws.on("message", (...args: unknown[]) => { const data = args[0] as Buffer | ArrayBuffer | Buffer[] | string; - this.handleRawMessage(ws, data); + try { + this.chunkedSocket(ws).receive(typeof data === "string" ? data : bufferFromWsData(data)); + } catch (error) { + if (!(error instanceof ChunkedTransportProtocolError)) throw error; + ws.close(1002, "Invalid chunked transport"); + } }); ws.on("close", async (...args: unknown[]) => { + this.chunkedSockets.get(ws)?.close(); const code = args[0]; const reason = args[1]; await this.detachSocket(ws, { @@ -2563,7 +2632,7 @@ export class VoiceAssistantWebSocketServer { identity: JSON.stringify([connection.principalId, connection.clientId]), permissions: () => connection.session.getPermissions(), routed: () => connection.session.isRouted(), - bufferedAmount: () => ws.bufferedAmount ?? null, + bufferedAmount: () => this.socketBufferedAmount(ws), delivery: connection.session.delivery, admit: (socket, permissions) => this.attachSocket(socket, undefined, undefined, false, { diff --git a/packages/server/src/server/websocket/encrypted-relay-socket.test.ts b/packages/server/src/server/websocket/encrypted-relay-socket.test.ts index f2a880f15f..3e17f0cbb4 100644 --- a/packages/server/src/server/websocket/encrypted-relay-socket.test.ts +++ b/packages/server/src/server/websocket/encrypted-relay-socket.test.ts @@ -140,3 +140,74 @@ test("encrypted sockets do not double-count bytes already buffered by the transp expect(socket.bufferedAmount).toBe(payload.byteLength + 40); }); + +test("50 MiB logical text and routed binary cross encrypted relay frames in both directions", async () => { + const { ChunkedTransport } = await import("@getpaseo/protocol/chunked-transport"); + const { openClientSecureChannel, openDaemonSecureChannel } = await import("@getpaseo/relay/e2ee"); + const { generateKeyPair, exportPublicKey, maxSecuredPlaintextByteLength } = + await import("@getpaseo/relay"); + const { encodeHostRouteFrame, decodeHostRouteFrame } = + await import("@getpaseo/protocol/binary-frames/index"); + type Transport = import("@getpaseo/relay/e2ee").Transport; + const limit = 32 * 1024 * 1024; + const wireSizes: number[] = []; + const endpoint = (): Transport => ({ + send: () => {}, + close: () => {}, + onmessage: null, + onclose: null, + onerror: null, + }); + const left = endpoint(); + const right = endpoint(); + const wire = (destination: Transport) => (data: string | ArrayBuffer) => { + const size = typeof data === "string" ? Buffer.byteLength(data) : data.byteLength; + expect(size).toBeLessThanOrEqual(limit); + wireSizes.push(size); + queueMicrotask(() => destination.onmessage?.({ data, isBinary: typeof data !== "string" })); + }; + left.send = wire(right); + right.send = wire(left); + const key = generateKeyPair(); + const delivered: (string | Uint8Array)[][] = [[], []]; + let receivers: InstanceType[] = []; + const incoming = (index: number) => (data: string | ArrayBuffer) => + receivers[index]!.receive(typeof data === "string" ? data : new Uint8Array(data)); + const daemonPromise = openDaemonSecureChannel(right, { + daemonKeyPair: key, + events: { onmessage: incoming(1) }, + }); + const client = await openClientSecureChannel(left, { + daemonPublicKeyB64: exportPublicKey(key.publicKey), + events: { onmessage: incoming(0) }, + }); + const daemon = await daemonPromise; + receivers = [client, daemon].map( + (channel, index) => + new ChunkedTransport({ + frameBytes: maxSecuredPlaintextByteLength(limit), + send: (frame) => channel.send(typeof frame === "string" ? frame : frame.slice().buffer), + deliver: (frame) => { + delivered[index]!.push(frame); + }, + }), + ); + for (const receiver of receivers) receiver.enabled = true; + const text = "x".repeat(50 * 1024 * 1024); + wireSizes.length = 0; + await receivers[1]!.send(text); + await new Promise((resolve) => setImmediate(resolve)); + expect(delivered[0]).toEqual([text]); + expect(wireSizes.length).toBeGreaterThan(1); + const routed = encodeHostRouteFrame("route", new Uint8Array(50 * 1024 * 1024).fill(7)); + await receivers[0]!.send(routed); + await new Promise((resolve) => setImmediate(resolve)); + expect(delivered[1]).toHaveLength(1); + const received = decodeHostRouteFrame(delivered[1]![0] as Uint8Array)!; + expect(received.routeId).toBe("route"); + expect( + Buffer.from(received.payload).equals(Buffer.from(new Uint8Array(50 * 1024 * 1024).fill(7))), + ).toBe(true); + client.close(); + daemon.close(); +}, 30_000); diff --git a/packages/server/src/server/websocket/encrypted-relay-socket.ts b/packages/server/src/server/websocket/encrypted-relay-socket.ts index f11162761c..794789718c 100644 --- a/packages/server/src/server/websocket/encrypted-relay-socket.ts +++ b/packages/server/src/server/websocket/encrypted-relay-socket.ts @@ -1,3 +1,5 @@ +import { maxSecuredPlaintextByteLength } from "@getpaseo/relay"; +import { MAX_RELAY_WEBSOCKET_MESSAGE_BYTES } from "@getpaseo/protocol/websocket-message-limit"; import { EventEmitter } from "node:events"; import { MAX_PHYSICAL_SOCKET_BUFFERED_BYTES } from "./physical-socket.js"; @@ -8,6 +10,7 @@ export interface EncryptedRelayChannel { } export interface EncryptedRelaySocket { + readonly maxFrameBytes: number; readonly readyState: number; readonly bufferedAmount: number; send: (data: string | Uint8Array | ArrayBuffer) => void | Promise; @@ -43,6 +46,7 @@ export function createEncryptedRelaySocket(params: { }); return { + maxFrameBytes: maxSecuredPlaintextByteLength(MAX_RELAY_WEBSOCKET_MESSAGE_BYTES), get readyState() { return readyState; }, diff --git a/packages/server/src/server/websocket/physical-socket.test.ts b/packages/server/src/server/websocket/physical-socket.test.ts index c81b1410d6..6dce3e151d 100644 --- a/packages/server/src/server/websocket/physical-socket.test.ts +++ b/packages/server/src/server/websocket/physical-socket.test.ts @@ -120,3 +120,96 @@ test("the awaitable physical send rejects callback errors", async () => { }), ).rejects.toThrow("send failed"); }); + +test("ordinary frames expose a paused real socket's backlog and terminate at the physical backstop", async () => { + const { once } = await import("node:events"); + const { WebSocket, WebSocketServer } = await import("ws"); + const { ChunkedTransport } = await import("@getpaseo/protocol/chunked-transport"); + const server = new WebSocketServer({ host: "127.0.0.1", port: 0 }); + await once(server, "listening"); + const connected = once(server, "connection"); + const address = server.address(); + if (typeof address === "string" || !address) throw new Error("Missing server address"); + const client = new WebSocket(`ws://127.0.0.1:${address.port}`); + await once(client, "open"); + const [socket] = (await connected) as [InstanceType]; + const tcp = (socket as unknown as { _socket: import("node:net").Socket })._socket; + let terminated = false; + const transport = new ChunkedTransport({ + frameBytes: 32 * 1024 * 1024, + deliver: () => {}, + send: (frame, wait) => { + const options = { + socket, + frame, + onHighWater: () => { + terminated = true; + socket.terminate(); + }, + }; + if (wait) return sendBoundedPhysicalFrameAndWait(options).then(() => undefined); + sendBoundedPhysicalFrame(options); + }, + }); + try { + client.pause(); + tcp.cork(); + const frame = new Uint8Array(256 * 1024); + for (let count = 0; count < 200; count++) await transport.send(frame); + expect(socket.bufferedAmount).toBeGreaterThan(4 * 1024 * 1024); + expect(transport.queuedByteLength).toBe(0); + for (let count = 0; count < 100; count++) { + if (terminated) break; + await transport.send(frame); + } + expect(terminated).toBe(true); + } finally { + transport.close(); + client.terminate(); + socket.terminate(); + await new Promise((resolve) => server.close(() => resolve())); + } +}); + +test("an awaited framing failure terminates its real socket immediately", async () => { + const { once } = await import("node:events"); + const { WebSocket, WebSocketServer } = await import("ws"); + const { ChunkedTransport } = await import("@getpaseo/protocol/chunked-transport"); + const server = new WebSocketServer({ host: "127.0.0.1", port: 0 }); + await once(server, "listening"); + const connected = once(server, "connection"); + const address = server.address(); + if (typeof address === "string" || !address) throw new Error("Missing server address"); + const client = new WebSocket(`ws://127.0.0.1:${address.port}`); + await once(client, "open"); + const [socket] = (await connected) as [InstanceType]; + const tcp = (socket as unknown as { _socket: import("node:net").Socket })._socket; + const transport = new ChunkedTransport({ + frameBytes: 32 * 1024 * 1024, + deliver: () => {}, + onFailure: () => socket.terminate(), + send: (frame) => + sendBoundedPhysicalFrameAndWait({ + socket, + frame, + onHighWater: () => socket.terminate(), + }).then(() => undefined), + }); + transport.enabled = true; + try { + client.pause(); + tcp.cork(); + const closed = once(socket, "close"); + const first = transport.send(new Uint8Array(100 * 1024 * 1024), { waitForDrain: true }); + const overflow = transport.send(new Uint8Array([1]), { waitForDrain: true }); + const settled = Promise.allSettled([first, overflow]); + await closed; + expect(socket.readyState).toBe(WebSocket.CLOSED); + expect((await settled).map((result) => result.status)).toEqual(["rejected", "rejected"]); + } finally { + transport.close(); + client.terminate(); + socket.terminate(); + await new Promise((resolve) => server.close(() => resolve())); + } +}); diff --git a/packages/server/src/server/workspace-archive-service.test.ts b/packages/server/src/server/workspace-archive-service.test.ts index a1a901c4d6..567c80054f 100644 --- a/packages/server/src/server/workspace-archive-service.test.ts +++ b/packages/server/src/server/workspace-archive-service.test.ts @@ -7,7 +7,9 @@ import { afterEach, describe, expect, test, vi } from "vitest"; import type { ForgeService } from "../services/forge-service.js"; import { createRealpathAwarePathMatcher } from "../utils/path.js"; -import { createWorktree, type WorktreeConfig } from "../utils/worktree.js"; +import { getPaseoWorktreeMetadataPath } from "../utils/worktree-metadata.js"; +import { archiveCommand } from "./worktree/commands.js"; +import { createWorktree, listPaseoWorktrees, type WorktreeConfig } from "../utils/worktree.js"; import type { ManagedAgent } from "./agent/agent-manager.js"; import type { AgentStorage, StoredAgentRecord } from "./agent/agent-storage.js"; import type { WorkspaceGitService } from "./workspace-git-service.js"; @@ -190,6 +192,54 @@ function assertArchiveResult( } describe("archiveByScope", () => { + test.each(["workspace", "worktree"] as const)( + "%s archive preserves a restored external worktree despite its marker", + async (kind) => { + const { tempDir, repoDir } = createGitRepo(); + const paseoHome = path.join(tempDir, ".paseo"); + const recordedPath = path.join(tempDir, "external"); + execFileSync("git", ["worktree", "add", "-b", "external", recordedPath], { + cwd: repoDir, + stdio: "pipe", + }); + execFileSync("git", ["worktree", "remove", recordedPath], { cwd: repoDir, stdio: "pipe" }); + const restored = await createWorktree({ + cwd: repoDir, + paseoHome, + worktreeSlug: "external", + worktreePath: recordedPath, + source: { kind: "restore", branchName: "external", baseRef: "main" }, + }); + expect(existsSync(await getPaseoWorktreeMetadataPath(restored.worktreePath))).toBe(true); + const workspaceId = "external-workspace"; + const result = await archiveByScope( + createArchiveDeps({ + paseoHome, + activeWorkspaces: [ + { + workspaceId, + cwd: restored.worktreePath, + kind: "worktree", + worktreeRoot: restored.worktreePath, + mainRepoRoot: repoDir, + isPaseoOwnedWorktree: false, + }, + ], + }), + { + scope: + kind === "workspace" + ? { kind, workspaceId } + : { kind, targetPath: restored.worktreePath }, + requestId: "archive-external", + }, + ); + expect(result.removedDirectory).toBe(false); + expect(existsSync(restored.worktreePath)).toBe(true); + expect(result.archivedWorkspaceIds).toEqual([workspaceId]); + }, + ); + test("workspace scope archives the record and removes the directory on last reference", async () => { const { tempDir, repoDir } = createGitRepo(); const paseoHome = path.join(tempDir, ".paseo"); @@ -220,6 +270,120 @@ describe("archiveByScope", () => { expect(existsSync(worktree.worktreePath)).toBe(false); }); + test("workspace scope archives the record but leaves a plugin-placed directory whose marker is gone", async () => { + const { tempDir, repoDir } = createGitRepo(); + const paseoHome = path.join(tempDir, ".paseo"); + const worktree = await createWorktree({ + cwd: repoDir, + worktreeSlug: "unproven-workspace", + source: { kind: "branch-off", baseBranch: "main", branchName: "unproven-workspace" }, + paseoHome, + worktreePath: path.join(tempDir, "placed-worktree"), + }); + // Remove the ownership marker: no proof remains for this path. + rmSync(await getPaseoWorktreeMetadataPath(worktree.worktreePath), { force: true }); + const workspaceId = "ws-unproven"; + + const logs: Array<{ targetPath: string; msg: string }> = []; + const dependencies = createArchiveDeps({ + paseoHome, + activeWorkspaces: [{ workspaceId, cwd: worktree.worktreePath, kind: "worktree" }], + }); + dependencies.sessionLogger = pino( + { level: "warn" }, + { + write(message) { + logs.push(JSON.parse(message)); + }, + }, + ); + const result = await archiveByScope(dependencies, { + scope: { kind: "workspace", workspaceId }, + requestId: "req-unproven-workspace", + }); + + assertArchiveResult(result, { archivedWorkspaceIds: [workspaceId], removedDirectory: false }); + expect(result.directoryLeftBehind?.path).toBe(worktree.worktreePath); + expect(result.directoryLeftBehind?.reason).toContain("no ownership proof"); + expect(existsSync(worktree.worktreePath)).toBe(true); + expect(logs).toContainEqual( + expect.objectContaining({ + targetPath: worktree.worktreePath, + msg: expect.stringContaining("no ownership proof"), + }), + ); + }); + + test("archives a plugin-placed worktree by its discovered directory name", async () => { + const { tempDir, repoDir } = createGitRepo(); + const paseoHome = path.join(tempDir, ".paseo"); + const worktreePath = path.join(tempDir, "sibling-feature"); + await createWorktree({ + cwd: repoDir, + paseoHome, + worktreePath, + worktreeSlug: "original-slug", + source: { kind: "branch-off", branchName: "feature", baseBranch: "main" }, + }); + const dependencies = createArchiveDeps({ paseoHome, activeWorkspaces: [] }); + const result = await archiveCommand( + { + ...dependencies, + workspaceGitService: { + ...dependencies.workspaceGitService, + listWorktrees: (cwd) => listPaseoWorktrees({ cwd, paseoHome }), + }, + }, + { + repoRoot: repoDir, + worktreeSlug: "sibling-feature", + scope: "worktree", + requestId: "slug-archive", + }, + ); + expect(result).toEqual({ ok: true, removedAgents: [] }); + expect(existsSync(worktreePath)).toBe(false); + }); + + test("workspace scope deletes a plugin-placed directory on registry proof even with the marker gone", async () => { + const { tempDir, repoDir } = createGitRepo(); + const paseoHome = path.join(tempDir, ".paseo"); + const worktree = await createWorktree({ + cwd: repoDir, + worktreeSlug: "registry-proven-workspace", + source: { + kind: "branch-off", + baseBranch: "main", + branchName: "registry-proven-workspace", + }, + paseoHome, + worktreePath: path.join(tempDir, "placed-worktree"), + }); + rmSync(await getPaseoWorktreeMetadataPath(worktree.worktreePath), { force: true }); + const workspaceId = "ws-registry-proven"; + + const result = await archiveByScope( + createArchiveDeps({ + paseoHome, + activeWorkspaces: [ + { + workspaceId, + cwd: worktree.worktreePath, + kind: "worktree", + isPaseoOwnedWorktree: true, + worktreeRoot: worktree.worktreePath, + mainRepoRoot: repoDir, + }, + ], + }), + { scope: { kind: "workspace", workspaceId }, requestId: "req-registry-proven-workspace" }, + ); + + assertArchiveResult(result, { archivedWorkspaceIds: [workspaceId], removedDirectory: true }); + expect(result.directoryLeftBehind).toBeUndefined(); + expect(existsSync(worktree.worktreePath)).toBe(false); + }); + test("workspace scope runs teardown while keeping a directory referenced by a sibling", async () => { const { tempDir, repoDir } = createGitRepo(); writeFileSync( diff --git a/packages/server/src/server/workspace-archive-service.ts b/packages/server/src/server/workspace-archive-service.ts index e9e58681a1..78f8c0b97d 100644 --- a/packages/server/src/server/workspace-archive-service.ts +++ b/packages/server/src/server/workspace-archive-service.ts @@ -69,6 +69,10 @@ export interface ArchiveResult { archivedAgentIds: string[]; archivedWorkspaceIds: string[]; removedDirectory: boolean; + // Set when the record archived but its worktree directory was left on + // disk because no ownership proof held for it. The directory is never + // deleted in that case; the path and reason surface here and in the log. + directoryLeftBehind?: { path: string; reason: string }; } export interface ArchiveByScopeRequest { @@ -92,6 +96,15 @@ export async function requireActiveWorkspaceForArchive( interface BackingDirectory { path: string; isPaseoOwnedWorktree: boolean; + // True when the directory backs a worktree workspace (or a worktree-scope + // archive), so a failed ownership proof means a Paseo worktree directory + // is being left behind rather than a user's local checkout being ignored. + expectsPaseoOwnership: boolean; + // True only when this backing came from a workspace registry record + // matched to this path (the record is itself an ownership proof, passed + // through to deletePaseoWorktree). Disk-derived backings stay false: + // they must prove ownership on disk. + registryProven: boolean; mainRepoRoot: string | null; paseoWorktreesRoot: string | null; } @@ -141,6 +154,7 @@ async function archiveByScopeWithPriority( } let removedDirectory = false; + let directoryLeftBehind: ArchiveResult["directoryLeftBehind"]; try { if (targetWorkspaceIds.length > 0) { @@ -168,18 +182,21 @@ async function archiveByScopeWithPriority( } if (target.backing !== null) { - removedDirectory = await maybeRemoveDirectory( + const removal = await maybeRemoveDirectory( dependencies, request, target, archivedWorkspaceIds, ); + removedDirectory = removal.removedDirectory; + directoryLeftBehind = removal.directoryLeftBehind; } return { archivedAgentIds: Array.from(archivedAgents), archivedWorkspaceIds, removedDirectory, + ...(directoryLeftBehind ? { directoryLeftBehind } : {}), }; } finally { if (targetWorkspaceIds.length > 0) { @@ -226,14 +243,16 @@ async function resolveArchiveTarget( }), ) ).filter((workspace): workspace is ActiveWorkspaceRef => workspace !== null); - const persistedMainRepoRoot = targetWorkspaces.find( - (workspace) => workspace.mainRepoRoot, - )?.mainRepoRoot; + const recordedId = await dependencies.findWorkspaceIdForCwd(backing.path); + const recorded = recordedId ? await dependencies.getWorkspace?.(recordedId) : null; + const record = + targetWorkspaces.find((workspace) => workspace.kind === "worktree") ?? + (recorded && matchesBackingDirectory(recorded.worktreeRoot ?? recorded.cwd) + ? recorded + : null) ?? + targetWorkspaces[0]; return { - backing: { - ...backing, - mainRepoRoot: persistedMainRepoRoot ?? backing.mainRepoRoot, - }, + backing: record ? await resolveWorkspaceBackingDirectory(record, dependencies) : backing, teardownTargets: targetWorkspaces.length > 0 ? targetWorkspaces.map((workspace) => ({ @@ -271,10 +290,22 @@ async function resolveWorkspaceBackingDirectory( workspace: ActiveWorkspaceRef, dependencies: Pick, ): Promise { + if (workspace.isPaseoOwnedWorktree === false) { + return { + path: resolve(workspace.worktreeRoot ?? workspace.cwd), + isPaseoOwnedWorktree: false, + expectsPaseoOwnership: false, + registryProven: false, + mainRepoRoot: workspace.mainRepoRoot ?? null, + paseoWorktreesRoot: null, + }; + } if (workspace.isPaseoOwnedWorktree && workspace.worktreeRoot && workspace.mainRepoRoot) { return { path: resolve(workspace.worktreeRoot), isPaseoOwnedWorktree: true, + expectsPaseoOwnership: true, + registryProven: true, mainRepoRoot: workspace.mainRepoRoot, paseoWorktreesRoot: null, }; @@ -283,6 +314,8 @@ async function resolveWorkspaceBackingDirectory( return { path: resolve(workspace.cwd), isPaseoOwnedWorktree: false, + expectsPaseoOwnership: false, + registryProven: false, mainRepoRoot: workspace.mainRepoRoot ?? null, paseoWorktreesRoot: null, }; @@ -309,6 +342,8 @@ async function resolveBackingDirectory( return { path: resolve(ownership.allowed && ownership.worktreePath ? ownership.worktreePath : cwd), isPaseoOwnedWorktree: ownership.allowed, + expectsPaseoOwnership: true, + registryProven: false, mainRepoRoot: ownership.repoRoot ?? null, paseoWorktreesRoot: ownership.worktreeRoot ?? null, }; @@ -352,10 +387,28 @@ async function maybeRemoveDirectory( request: Pick, target: ArchiveTarget, archivedWorkspaceIds: string[], -): Promise { +): Promise<{ + removedDirectory: boolean; + directoryLeftBehind?: { path: string; reason: string }; +}> { const backing = target.backing; if (!backing?.isPaseoOwnedWorktree) { - return false; + // Missing ownership proof for a worktree-backed directory: the record + // still archives, but the directory is left in place and surfaced. + // Never delete an unproven directory. + if (backing?.expectsPaseoOwnership) { + const reason = + "no ownership proof (not under the Paseo worktrees root, no paseo/worktree.json marker, no registry record)"; + dependencies.sessionLogger?.warn( + { targetPath: backing.path, requestId: request.requestId }, + `Worktree directory left in place during archive: ${reason}`, + ); + return { + removedDirectory: false, + directoryLeftBehind: { path: backing.path, reason }, + }; + } + return { removedDirectory: false }; } const archivedWorkspaceIdSet = new Set(archivedWorkspaceIds); @@ -382,7 +435,7 @@ async function maybeRemoveDirectory( { err: error, targetPath: backing.path, requestId: request.requestId }, "Worktree teardown failed during archive; workspace already archived", ); - return false; + return { removedDirectory: false }; } throw error; } @@ -396,7 +449,7 @@ async function maybeRemoveDirectory( dependencies, )) ) { - return false; + return { removedDirectory: false }; } try { @@ -407,16 +460,17 @@ async function maybeRemoveDirectory( worktreesRoot: backing.paseoWorktreesRoot ?? undefined, paseoHome: dependencies.paseoHome, worktreesBaseRoot: dependencies.paseoWorktreesBaseRoot, + registryProven: backing.registryProven, }); dependencies.workspaceGitService.invalidateWorktrees(); dependencies.github.invalidate({ cwd: backing.path }); - return true; + return { removedDirectory: true }; } catch (error) { dependencies.sessionLogger?.warn( { err: error, targetPath: backing.path, requestId: request.requestId }, "Worktree disk removal failed during archive; workspace already archived", ); - return false; + return { removedDirectory: false }; } } diff --git a/packages/server/src/server/workspace-git-fetch.test.ts b/packages/server/src/server/workspace-git-fetch.test.ts index 29a95b64d8..de9e69959e 100644 --- a/packages/server/src/server/workspace-git-fetch.test.ts +++ b/packages/server/src/server/workspace-git-fetch.test.ts @@ -1,4 +1,8 @@ import { describe, expect, test } from "vitest"; +import { createServer } from "node:http"; +import { mkdtemp, readFile, writeFile, rm, chmod } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; import { diffWorkspaceGitRefs, @@ -6,14 +10,21 @@ import { fetchWorkspaceGitRemote, parseWorkspaceGitRefs, } from "./workspace-git-fetch.js"; -import type { RunGitCommand } from "../utils/run-git-command.js"; +import { runGitCommand, type RunGitCommand } from "../utils/run-git-command.js"; describe("workspace Git remote refs", () => { test("runs the complete fetch through the supplied Git runner", async () => { const commands: string[][] = []; let refRead = 0; - const runGitCommand: RunGitCommand = async (args) => { + const run: RunGitCommand = async (args, options) => { commands.push(args); + if (args[0] === "fetch") { + expect(options.envOverlay).toEqual({ + GIT_TERMINAL_PROMPT: "0", + GIT_ASKPASS: "", + GCM_INTERACTIVE: "0", + }); + } const stdout = args[0] === "for-each-ref" ? `refs/remotes/origin/main\0${refRead++ === 0 ? "aaaaaaaa" : "bbbbbbbb"}` @@ -22,7 +33,7 @@ describe("workspace Git remote refs", () => { }; await expect( - fetchWorkspaceGitRemote("/repo", { onRefSnapshot() {} }, runGitCommand), + fetchWorkspaceGitRemote("/repo", { onRefSnapshot() {} }, run), ).resolves.toMatchObject({ changes: [ { @@ -109,3 +120,130 @@ describe("workspace Git remote refs", () => { ]); }); }); + +// Serve a real bare repository over Git's dumb HTTP transport, behind Basic authentication. +// Both the authentication challenge and successful fetch exercise Git itself. +async function withAuthenticatedRemote( + verify: (fixture: { + cwd: string; + run: RunGitCommand; + root: string; + origin: string; + expectedOid: string; + }) => Promise, +): Promise { + const root = await mkdtemp(join(tmpdir(), "paseo-fetch-auth-")); + const cwd = join(root, "checkout"); + const remote = join(root, "remote.git"); + const emptyConfig = join(root, "gitconfig"); + const askpass = join(root, "askpass.sh"); + const marker = join(root, "prompts"); + await writeFile(emptyConfig, ""); + await writeFile( + askpass, + `#!/bin/sh\nprintf 'prompt\\n' >> '${marker.replaceAll("'", "'\\''")}'\nexit 1\n`, + ); + await chmod(askpass, 0o755); + const askpassCommand = askpass; + const run: RunGitCommand = (args, options) => + runGitCommand(args, { + ...options, + env: { + ...options.env, + GIT_CONFIG_GLOBAL: emptyConfig, + GIT_CONFIG_NOSYSTEM: "1", + GIT_ASKPASS: askpassCommand, + SSH_ASKPASS: askpassCommand, + }, + }); + const server = createServer(async (request, response) => { + if ( + request.headers.authorization !== `Basic ${Buffer.from("fixture:secret").toString("base64")}` + ) { + response.writeHead(401, { "WWW-Authenticate": 'Basic realm="git-test"' }); + response.end(); + return; + } + const pathname = new URL(request.url!, "http://localhost").pathname; + try { + const contents = await readFile(join(root, pathname)); + response.writeHead(200, { "Content-Type": "application/octet-stream" }); + response.end(contents); + } catch { + response.writeHead(404); + response.end(); + } + }); + try { + await run(["init", "--initial-branch=main", cwd], { cwd: root }); + await run( + [ + "-c", + "user.name=Fixture", + "-c", + "user.email=fixture@example.invalid", + "commit", + "--allow-empty", + "-m", + "initial", + ], + { cwd }, + ); + await run(["clone", "--bare", cwd, remote], { cwd: root }); + await run(["update-server-info"], { cwd: remote }); + await run(["config", "credential.helper", ""], { cwd }); + await run(["config", "core.askPass", askpassCommand], { cwd }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const address = server.address(); + if (!address || typeof address === "string") throw new Error("Expected TCP server"); + const origin = `http://127.0.0.1:${address.port}/remote.git`; + await run(["remote", "add", "origin", origin], { cwd }); + const expectedOid = (await run(["rev-parse", "HEAD"], { cwd })).stdout.trim(); + await verify({ cwd, run, root, origin, expectedOid }); + } finally { + server.closeAllConnections(); + await new Promise((resolve) => server.close(() => resolve())); + await rm(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }); + } +} + +test.skipIf(process.platform === "win32")( + "background fetches never invoke askpass when credentials are missing", + async () => { + await withAuthenticatedRemote(async ({ cwd, run, root }) => { + for (let attempt = 0; attempt < 2; attempt++) { + const result = await fetchWorkspaceGitRemote(cwd, { onRefSnapshot() {} }, run); + expect(String(result.error)).toContain("terminal prompts disabled"); + } + await expect(readFile(join(root, "prompts"), "utf8")).rejects.toMatchObject({ + code: "ENOENT", + }); + }); + }, +); + +test.skipIf(process.platform === "win32")( + "background fetches still use stored credentials", + async () => { + await withAuthenticatedRemote(async ({ cwd, run, root, origin, expectedOid }) => { + const credentials = join(root, "credentials"); + await writeFile(credentials, origin.replace("http://", "http://fixture:secret@") + "\n"); + await run(["config", "credential.helper", `store --file="${credentials}"`], { cwd }); + + const result = await fetchWorkspaceGitRemote(cwd, { onRefSnapshot() {} }, run); + + expect(result.error).toBeNull(); + expect(result.changes).toContainEqual({ + kind: "added", + ref: "origin/main", + afterOid: expectedOid, + }); + expect((await run(["rev-parse", "refs/remotes/origin/main"], { cwd })).stdout.trim()).toBe( + expectedOid, + ); + await expect(readFile(join(root, "prompts"), "utf8")).rejects.toMatchObject({ + code: "ENOENT", + }); + }); + }, +); diff --git a/packages/server/src/server/workspace-git-fetch.ts b/packages/server/src/server/workspace-git-fetch.ts index 72f5d407da..5673600d23 100644 --- a/packages/server/src/server/workspace-git-fetch.ts +++ b/packages/server/src/server/workspace-git-fetch.ts @@ -33,7 +33,9 @@ export async function fetchWorkspaceGitRemote( try { await run(["fetch", "origin", "--prune"], { cwd, - envOverlay: { GIT_TERMINAL_PROMPT: "0" }, + // Terminal prompting and graphical credential prompting have separate controls. + // Keep cached credentials available, but never start a login from a passive fetch. + envOverlay: { GIT_TERMINAL_PROMPT: "0", GIT_ASKPASS: "", GCM_INTERACTIVE: "0" }, timeout: 120_000, }); } catch (caught) { diff --git a/packages/server/src/server/workspace-git-service.observation.integration.test.ts b/packages/server/src/server/workspace-git-service.observation.integration.test.ts index 55265416dc..371502748d 100644 --- a/packages/server/src/server/workspace-git-service.observation.integration.test.ts +++ b/packages/server/src/server/workspace-git-service.observation.integration.test.ts @@ -12,12 +12,7 @@ import { WorkspaceGitServiceImpl } from "./workspace-git-service.js"; import type { FileChange, FileObserver, SubscribeToFileChanges } from "./file-observer/index.js"; function createLogger(): pino.Logger { - const logger = { - child: () => logger, - debug: vi.fn(), - warn: vi.fn(), - }; - return logger as unknown as pino.Logger; + return pino({ level: "warn" }); } function createFacts(cwd: string): CheckoutSnapshotFacts { @@ -232,7 +227,14 @@ test("recursive observation updates tracked state and prunes ignored storms", as await vi.waitFor( () => { - expect(activeWatcherCount).toBe(2); + expect( + activeWatcherCount, + JSON.stringify({ + observer: observer.getDiagnostics(), + service: service.getMetrics(), + deliveredEvents, + }), + ).toBe(2); expect(workspaceRuntimeStore.get(repoDir)).not.toBeNull(); expect(service.getMetrics()).toMatchObject({ workspaceObservationSetupInFlightCount: 0, @@ -575,29 +577,48 @@ test("Git refresh, command tracing and 10,000 ignored alias events do no synchro await symlink(worktree, alias, process.platform === 'win32' ? 'junction' : 'dir'); const subscription = await service.requestWorkingTreeWatch(alias, () => { notifications++; }); const events = Array.from({ length: process.env.GIT_IO_TRACE ? 2 : 10000 }, (_, i) => ({ type: 'update', path: join(i % 2 ? alias : worktree, 'ignored', 'noise') })); - // A shared CI runner can deschedule the child during a wall-clock sample. - // Keep the 20ms gate, but take three independent batches and require one - // responsive callback/timer pair. All batches must remain filesystem-free. - const samples = []; - for (let trial = 0; trial < (process.env.GIT_IO_TRACE ? 1 : 3); trial++) { - await tick(); - let fsCalls = 0; - const hook = createHook({ init(_id, type) { if (type.startsWith('FSREQ')) fsCalls++; } }); - await marker('FILTER_START'); - hook.enable(); - const started = performance.now(); - const pulse = new Promise((resolve) => setTimeout(() => resolve(performance.now() - started), 0)); + let fsCalls = 0; + const hook = createHook({ init(_id, type) { if (type.startsWith('FSREQ')) fsCalls++; } }); + // Collect repository setup and event-fixture garbage before measuring + // the cold filter. Allocations made by the filter still count. + global.gc(); + await tick(); + await marker('FILTER_START'); + // Schedule the control only after marker IO settles, so it cannot run + // and allocate garbage before the cold filter starts. No await may + // separate this scheduling from the synchronous measurement. + const threadCpuUsage = Reflect.get(process, 'threadCpuUsage'); + let unrelatedWorkStarted = false; + const unrelatedWork = tick().then(() => { + unrelatedWorkStarted = true; + const started = threadCpuUsage(); + while (true) { + const cpu = threadCpuUsage(started); + if (cpu.user + cpu.system >= 80000) break; + } + }); + assert.equal(unrelatedWorkStarted, false, 'control work must not contaminate the cold filter'); + hook.enable(); + let blockingMs; + try { + // This callback is synchronous: measure its own span, without waiting + // for marker IO, loader messages or other event-loop callbacks. + const startedAt = performance.now(); + const startedCpu = threadCpuUsage(); callback(null, events); - const filterMs = performance.now() - started; + const cpu = threadCpuUsage(startedCpu); + // Cap coarse Windows CPU accounting by elapsed time; exclude descheduling. + blockingMs = Math.min(performance.now() - startedAt, (cpu.user + cpu.system) / 1000); + } finally { hook.disable(); - const loopGapMs = await pulse; await marker('FILTER_END'); - assert.equal(fsCalls, 0, "filesystem calls"); - assert.equal(notifications, 0, "ignored event notification"); - samples.push({ filterMs, loopGapMs, fsCalls }); } - console.log(JSON.stringify({ ...samples[0], samples })); - assert.ok(process.env.GIT_IO_TRACE || samples.some(({ filterMs, loopGapMs }) => filterMs < 20 && loopGapMs < 20), 'no responsive filter sample: ' + JSON.stringify(samples)); + await unrelatedWork; + assert.equal(unrelatedWorkStarted, true, 'control work must run outside the filter span'); + assert.equal(fsCalls, 0, "filesystem calls"); + assert.equal(notifications, 0, "ignored event notification"); + assert.ok(blockingMs < 20, 'blocking filter work: ' + blockingMs); + console.log(JSON.stringify({ blockingMs, fsCalls })); // Alias identity remains useful after deletion: no per-event realpath can recover this file. callback(null, [{ type: 'delete', path: join(worktree, 'tracked.txt') }]); assert.equal(notifications, 1); @@ -617,6 +638,7 @@ test("Git refresh, command tracing and 10,000 ignored alias events do no synchro const { stdout, stderr } = await promisify(execFile)( process.execPath, [ + "--expose-gc", "--import", "tsx", ...(tracing ? ["--trace-sync-io"] : []), @@ -637,7 +659,9 @@ test("Git refresh, command tracing and 10,000 ignored alias events do no synchro const output = stderr.split(`${phase}_START\n`)[1]?.split(`${phase}_END\n`)[0]; expect(output, `${phase}: synchronous filesystem IO`).toBe(""); } - expect(JSON.parse(stdout.trim().split("\n")[0])).toMatchObject({ fsCalls: 0 }); + const measurement = JSON.parse(stdout.trim().split("\n")[0]); + console.info("Git filter budget", { tracing, ...measurement }); + expect(measurement).toMatchObject({ fsCalls: 0 }); } }, 60_000); diff --git a/packages/server/src/server/workspace-git-service.test.ts b/packages/server/src/server/workspace-git-service.test.ts index 4b0b13b7a2..4e6acff9cd 100644 --- a/packages/server/src/server/workspace-git-service.test.ts +++ b/packages/server/src/server/workspace-git-service.test.ts @@ -796,15 +796,21 @@ describe("WorkspaceGitServiceImpl", () => { const service = createService({ getCheckoutStatus, subscribe, runGitCommand }); cwds.forEach((cwd) => service.registerWorkspace({ cwd }, vi.fn())); - await vi.waitFor(() => { - expect(service.getMetrics()).toMatchObject({ - workspaceRefreshAdmissionActiveCount: WORKSPACE_GIT_REFRESH_CONCURRENCY, - workspaceRefreshAdmissionPendingCount: 1, - workspaceObservationSetupAdmissionActiveCount: WORKSPACE_GIT_OBSERVATION_SETUP_CONCURRENCY, - workspaceObservationSetupAdmissionPendingCount: - cwds.length - WORKSPACE_GIT_OBSERVATION_SETUP_CONCURRENCY, - }); - }); + await vi.waitFor( + () => { + expect(service.getMetrics()).toMatchObject({ + workspaceRefreshAdmissionActiveCount: WORKSPACE_GIT_REFRESH_CONCURRENCY, + workspaceRefreshAdmissionPendingCount: 1, + workspaceObservationSetupAdmissionActiveCount: + WORKSPACE_GIT_OBSERVATION_SETUP_CONCURRENCY, + workspaceObservationSetupAdmissionPendingCount: + cwds.length - WORKSPACE_GIT_OBSERVATION_SETUP_CONCURRENCY, + }); + // Admission precedes asynchronous path setup; dispose only once watchers are pending. + expect(subscribe).toHaveBeenCalledTimes(WORKSPACE_GIT_OBSERVATION_SETUP_CONCURRENCY); + }, + { timeout: 10_000 }, + ); const queuedRefreshSettlement = service.getSnapshot(cwds.at(-1)!).then( () => ({ status: "fulfilled" as const, error: null }), (error: unknown) => ({ status: "rejected" as const, error }), @@ -1105,12 +1111,23 @@ describe("WorkspaceGitServiceImpl", () => { { cwd: join(REPO_CWD, "packages", "server") }, vi.fn(), ); - await vi.waitFor(() => { - expect(getCheckoutSnapshotFacts).toHaveBeenCalledTimes(2); - }); + await vi.waitFor( + () => { + expect(getCheckoutSnapshotFacts).toHaveBeenCalledTimes(2); + expect(service.getMetrics()).toMatchObject({ + repositoryWorkspaceLinkCount: 2, + workspaceObservationSetupInFlightCount: 0, + workspaceRefreshInFlightCount: 0, + fetchInFlightCount: 1, + }); + }, + { timeout: 10_000 }, + ); releaseFetch.resolve(); - await flushPromises(); + await vi.waitFor(() => { + expect(service.getMetrics().fetchInFlightCount).toBe(0); + }); await vi.advanceTimersByTimeAsync(1_000); await vi.waitFor(() => { expect(getCheckoutSnapshotFacts).toHaveBeenCalledTimes(4); @@ -1154,10 +1171,14 @@ describe("WorkspaceGitServiceImpl", () => { const subscription = service.registerWorkspace({ cwd: REPO_CWD }, listener); await vi.waitFor(() => { expect(getCheckoutSnapshotFacts).toHaveBeenCalledTimes(1); + expect(service.getMetrics().fetchInFlightCount).toBe(1); }); releaseFetch.resolve(); - await flushPromises(); + // The refresh debounce starts when the fetch result is applied, not when it is released. + await vi.waitFor(() => { + expect(service.getMetrics().fetchInFlightCount).toBe(0); + }); await vi.advanceTimersByTimeAsync(1_000); await vi.waitFor(() => { expect(getCheckoutRefDerivedState).toHaveBeenCalledTimes(1); diff --git a/packages/server/src/server/workspace-reconciliation-service.test.ts b/packages/server/src/server/workspace-reconciliation-service.test.ts index e1a8860e3b..b818804912 100644 --- a/packages/server/src/server/workspace-reconciliation-service.test.ts +++ b/packages/server/src/server/workspace-reconciliation-service.test.ts @@ -1,26 +1,45 @@ -import { execFileSync } from "node:child_process"; +import { execFile, execFileSync } from "node:child_process"; import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { promisify } from "node:util"; +import { build } from "esbuild"; +import { + createTestRegistries, + createTestLogger, + deferred, +} from "./test-fixtures/reconciliation-registries.js"; import type { ProjectCheckoutLitePayload } from "@getpaseo/protocol/messages"; import type pino from "pino"; -import { afterEach, describe, expect, test } from "vitest"; +import { afterAll, beforeAll, afterEach, describe, expect, test } from "vitest"; import { createPersistedProjectRecord, createPersistedWorkspaceRecord, } from "./workspace-registry.js"; -import type { - PersistedProjectRecord, - PersistedWorkspaceRecord, - ProjectRegistry, - WorkspaceRegistry, -} from "./workspace-registry.js"; import { type ReconciliationChange, WorkspaceReconciliationService, } from "./workspace-reconciliation-service.js"; import { deriveProjectKey } from "./project-key.js"; +let probeDirectory: string; +let probePath: string; +beforeAll(async () => { + probeDirectory = mkdtempSync(path.join(tmpdir(), "reconciliation-probe-")); + probePath = path.join(probeDirectory, "reconciliation.mjs"); + await build({ + entryPoints: [ + fileURLToPath(new URL("./test-fixtures/reconciliation-responsiveness.ts", import.meta.url)), + ], + outfile: probePath, + bundle: true, + platform: "node", + format: "esm", + }); +}); +afterAll(() => rmSync(probeDirectory, { recursive: true, force: true })); + function canonicalLocalProjectKey(rootPath: string): string { return deriveProjectKey({ rootPath, @@ -30,107 +49,6 @@ function canonicalLocalProjectKey(rootPath: string): string { }); } -function createTestRegistries() { - let archiveGate: { - started: ReturnType; - release: ReturnType; - } | null = null; - const holdNextArchive = () => { - archiveGate = { started: deferred(), release: deferred() }; - return archiveGate; - }; - const projects = new Map(); - const workspaces = new Map(); - - const projectRegistry: ProjectRegistry = { - initialize: async () => {}, - existsOnDisk: async () => true, - list: async () => Array.from(projects.values()), - get: async (id: string) => projects.get(id) ?? null, - getOrCreateActiveByRoot: async (input) => { - const existing = Array.from(projects.values()).find( - (project) => !project.archivedAt && project.rootPath === input.rootPath, - ); - if (existing) return existing; - const record = createPersistedProjectRecord({ - projectId: `prj_${projects.size}`, - rootPath: input.rootPath, - kind: input.kind, - displayName: input.displayName, - createdAt: input.timestamp, - updatedAt: input.timestamp, - }); - projects.set(record.projectId, record); - return record; - }, - update: async (id, updater) => { - const current = projects.get(id); - if (!current) return null; - const updated = updater(current); - projects.set(id, updated); - return updated; - }, - upsert: async (record: PersistedProjectRecord) => { - projects.set(record.projectId, record); - }, - archive: async (id: string, archivedAt: string) => { - const existing = projects.get(id); - if (existing) { - projects.set(id, { ...existing, archivedAt, updatedAt: archivedAt }); - } - }, - remove: async (id: string) => { - projects.delete(id); - }, - }; - - const workspaceRegistry: WorkspaceRegistry = { - initialize: async () => {}, - existsOnDisk: async () => true, - list: async () => Array.from(workspaces.values()), - get: async (id: string) => workspaces.get(id) ?? null, - update: async (id, updater) => { - const existing = workspaces.get(id); - if (!existing) return null; - const updated = updater(existing); - workspaces.set(id, updated); - return updated; - }, - upsert: async (record: PersistedWorkspaceRecord) => { - workspaces.set(record.workspaceId, record); - }, - archive: async (id: string, archivedAt: string) => { - const gate = archiveGate; - archiveGate = null; - if (gate) { - gate.started.resolve(); - await gate.release.promise; - } - const existing = workspaces.get(id); - if (!existing || existing.archivedAt) return false; - workspaces.set(id, { ...existing, archivedAt, updatedAt: archivedAt }); - return true; - }, - remove: async (id: string) => { - workspaces.delete(id); - }, - }; - - return { projects, workspaces, projectRegistry, workspaceRegistry, holdNextArchive }; -} - -function createTestLogger() { - const logger = { - child: () => logger, - trace: () => undefined, - debug: () => undefined, - info: () => undefined, - warn: () => undefined, - error: () => undefined, - }; - return logger as unknown as pino.Logger; -} - interface CapturedLogRecord { message: string; payload: unknown; @@ -209,14 +127,6 @@ function createCheckout( }; } -function deferred(): { promise: Promise; resolve(): void } { - let resolve!: () => void; - const promise = new Promise((accept) => { - resolve = accept; - }); - return { promise, resolve }; -} - class TestCheckouts { readonly reads: string[] = []; private readonly checkouts = new Map(); @@ -625,57 +535,54 @@ describe("WorkspaceReconciliationService", () => { test("keeps the event loop responsive while inspecting 20000 real workspace paths", async () => { const rootPath = realpathSync(mkdtempSync(path.join(tmpdir(), "reconcile-many-"))); tempDirs.push(rootPath); - const { projects, workspaces, projectRegistry, workspaceRegistry } = createTestRegistries(); - projects.set( - "p1", - createPersistedProjectRecord({ - projectId: "p1", - rootPath, - projectKey: canonicalLocalProjectKey(rootPath), - kind: "non_git", - displayName: "project", - createdAt: timestamp, - updatedAt: timestamp, - }), - ); - for (let i = 0; i < 20000; i++) { - const workspaceId = `w${i}`; - workspaces.set( - workspaceId, - createPersistedWorkspaceRecord({ - workspaceId, - projectId: "p1", - cwd: path.join(rootPath, workspaceId), - kind: "directory", - displayName: workspaceId, - createdAt: timestamp, - updatedAt: timestamp, - }), + // This CPU belongs to the runner, not to reconciliation. Keep it present + // throughout the read so a later loop turn cannot contaminate the budget. + let running = true; + const unrelatedWork = () => { + const threadCpuUsage: (previous?: NodeJS.CpuUsage) => NodeJS.CpuUsage = Reflect.get( + process, + "threadCpuUsage", ); - } - const service = new WorkspaceReconciliationService({ - projectRegistry, - workspaceRegistry, - logger: createTestLogger(), - }); - let last = performance.now(); - let longestGap = 0; - const probe = setInterval(() => { - const now = performance.now(); - longestGap = Math.max(longestGap, now - last); - last = now; - }, 1); - let result; + const start = threadCpuUsage(); + let elapsed: NodeJS.CpuUsage; + do { + elapsed = threadCpuUsage(start); + } while (elapsed.user + elapsed.system < 60_000); + if (running) unrelated = setImmediate(unrelatedWork); + }; + let unrelated = setImmediate(unrelatedWork); try { - result = await service.runOnce(); - await new Promise((resolve) => setTimeout(resolve, 1)); + const { stdout, stderr } = await promisify(execFile)( + process.execPath, + ["--expose-gc", probePath, rootPath], + { timeout: 25_000 }, + ); + process.stderr.write(stderr); + const { + changesApplied, + blockingMs, + filesystemRequests, + yields, + allArchived, + workerMessages, + } = JSON.parse(stdout) as { + changesApplied: number; + blockingMs: number; + filesystemRequests: number; + yields: number; + allArchived: boolean; + workerMessages: number; + }; + expect(blockingMs).toBeLessThan(20); + expect(filesystemRequests).toBe(20001); + expect(changesApplied).toBe(20000); + expect(allArchived).toBe(true); + expect(yields).toBeGreaterThan(0); + expect(workerMessages).toBe(0); } finally { - clearInterval(probe); - service.dispose(); + running = false; + clearImmediate(unrelated); } - expect(longestGap).toBeLessThan(20); - expect(result.changesApplied).toHaveLength(20000); - expect([...workspaces.values()].every((workspace) => workspace.archivedAt !== null)).toBe(true); }, 30000); test("preserves workspace archival that lands during boot reconciliation", async () => { diff --git a/packages/server/src/server/worktree-bootstrap.test.ts b/packages/server/src/server/worktree-bootstrap.test.ts index 96da6e648b..ed43e02388 100644 --- a/packages/server/src/server/worktree-bootstrap.test.ts +++ b/packages/server/src/server/worktree-bootstrap.test.ts @@ -209,13 +209,8 @@ describe("runWorktreeAutoTerminals", () => { getSize: () => ({ rows: 0, cols: 0 }), getTitle: () => undefined, getExitInfo: () => null, - getState: () => ({ - rows: 0, - cols: 0, - grid: [], - scrollback: [], - cursor: { row: 0, col: 0 }, - }), + hasOutput: () => false, + kill: () => {}, killAndWait: async () => {}, }; @@ -312,13 +307,8 @@ describe("runWorktreeAutoTerminals", () => { } }; }, - getState: () => ({ - rows: 1, - cols: 1, - grid: [[{ char: "$" }]], - scrollback: [], - cursor: { row: 0, col: 0 }, - }), + hasOutput: () => true, + kill: () => {}, onTitleChange: () => () => {}, onActivityChange: () => () => {}, diff --git a/packages/server/src/server/worktree-bootstrap.ts b/packages/server/src/server/worktree-bootstrap.ts index d656738bd4..1e1ba58f8e 100644 --- a/packages/server/src/server/worktree-bootstrap.ts +++ b/packages/server/src/server/worktree-bootstrap.ts @@ -269,9 +269,9 @@ export function buildWorktreeSetupDetail(input: { } async function waitForTerminalBootstrapReadiness( - terminal: Pick, + terminal: Pick, ): Promise { - if (terminalHasOutput(terminal.getState())) { + if (terminal.hasOutput()) { return; } @@ -304,7 +304,7 @@ async function waitForTerminalBootstrapReadiness( finish(); }); - if (terminalHasOutput(terminal.getState())) { + if (terminal.hasOutput()) { finish(); return; } @@ -313,17 +313,6 @@ async function waitForTerminalBootstrapReadiness( }); } -function terminalHasOutput(state: ReturnType): boolean { - for (const row of [...state.scrollback, ...state.grid]) { - for (const cell of row) { - if (cell.char.trim().length > 0) { - return true; - } - } - } - return false; -} - export async function runWorktreeAutoTerminals(options: { workspaceId: string; worktree: WorktreeConfig; diff --git a/packages/server/src/server/worktree-core.posix.test.ts b/packages/server/src/server/worktree-core.posix.test.ts index 4ec533d0c3..7a7a342732 100644 --- a/packages/server/src/server/worktree-core.posix.test.ts +++ b/packages/server/src/server/worktree-core.posix.test.ts @@ -24,6 +24,7 @@ import { getPaseoWorktreeMetadataPath, readPaseoWorktreeMetadata, } from "../utils/worktree-metadata.js"; +import { validateBeforeRequest, validateBeforeResult } from "./plugins/lifecycle/index.js"; import { UnknownBranchError } from "../utils/worktree.js"; import { createWorktreeCore as createCoreWorktree } from "./worktree-core.js"; import { isPlatform } from "../test-utils/platform.js"; @@ -419,6 +420,21 @@ describe.skipIf(isPlatform("win32"))("worktree-core POSIX-only", () => { expect(existsSync(result.worktree.worktreePath)).toBe(true); }); + test("keeps default placement suffixes when the default destination already exists", async () => { + const { tempDir, repoDir, paseoHome } = createGitRepo(); + cleanupPaths.push(tempDir); + const first = await createCoreWorktree( + { cwd: repoDir, paseoHome, branchName: "first", worktreeSlug: "same" }, + createCoreDeps(), + ); + const second = await createCoreWorktree( + { cwd: repoDir, paseoHome, branchName: "second", worktreeSlug: "same" }, + createCoreDeps(), + ); + expect(second.worktree.worktreePath).toBe(first.worktree.worktreePath + "-1"); + expect(existsSync(first.worktree.worktreePath)).toBe(true); + }); + test("creates branch-off worktrees from origin main without tracking origin main", async () => { const { tempDir, repoDir, paseoHome } = createGitRepoWithOriginMain(); cleanupPaths.push(tempDir); @@ -488,6 +504,42 @@ describe.skipIf(isPlatform("win32"))("worktree-core POSIX-only", () => { expect(result.worktree.branchName).toBe("feature/review-pr"); }); + test("round trips every resolved change-request field through an unchanged before-hook result", async () => { + const { tempDir, repoDir, paseoHome } = createGitHubPrRemoteRepo(); + cleanupPaths.push(tempDir); + const deps = createCoreDeps(); + const requests: unknown[] = []; + const result = await createCoreWorktree( + { cwd: repoDir, githubPrNumber: 123, refName: "feature/review-pr", paseoHome }, + { + ...deps, + lifecycle: { + before: async (name, request) => { + requests.push(request); + return validateBeforeResult(name, validateBeforeRequest(name, request), request); + }, + }, + }, + ); + expect(requests).toEqual([ + { + kind: "checkout-change-request", + forge: "github", + changeRequestNumber: 123, + headRef: "feature/review-pr", + baseRef: "main", + branch: "feature/review-pr", + checkoutRefs: [{ remoteName: "origin", remoteRef: "refs/pull/123/head" }], + trackOriginHead: true, + repoRoot: repoDir, + sourceCheckout: repoDir, + slug: "feature-review-pr", + path: result.worktree.worktreePath, + }, + ]); + expect(result.worktree.branchName).toBe("feature/review-pr"); + }); + test("uses the PR head ref as the default slug when no slug is supplied", async () => { const { tempDir, repoDir, paseoHome } = createGitHubPrRemoteRepo(); cleanupPaths.push(tempDir); diff --git a/packages/server/src/server/worktree-core.ts b/packages/server/src/server/worktree-core.ts index b0310d6e1f..cc6c9fdbd6 100644 --- a/packages/server/src/server/worktree-core.ts +++ b/packages/server/src/server/worktree-core.ts @@ -1,8 +1,11 @@ +import type { PluginWorktreeCreateRequest } from "@getpaseo/plugin/server"; +import type { PluginLifecycle } from "./plugins/lifecycle/index.js"; import { createNameId } from "mnemonic-id"; import type { ForgeService } from "../services/forge-service.js"; import { createWorktree, + resolveDefaultWorktreePath, slugify, validateBranchSlug, type CreatedWorktree, @@ -15,7 +18,7 @@ import { } from "./resolve-worktree-creation-intent.js"; import type { ChangeRequestCheckoutSource, FirstAgentContext } from "@getpaseo/protocol/messages"; import type { WorkspaceGitService } from "./workspace-git-service.js"; -import { runWithGitCommandPriority } from "../utils/run-git-command.js"; +import { runGitCommand, runWithGitCommandPriority } from "../utils/run-git-command.js"; export interface CreateWorktreeCoreInput { cwd: string; @@ -31,6 +34,7 @@ export interface CreateWorktreeCoreInput { } export interface CreateWorktreeCoreDeps { + lifecycle?: Pick; github: ForgeService; workspaceGitService?: Pick< WorkspaceGitService, @@ -90,7 +94,7 @@ async function createWorktreeCoreWithPriority( } const forge = await resolveForge(repoRoot, deps, intentInput); - const intent = await resolveWorktreeCreationIntent(intentInput, repoRoot, { + let intent = await resolveWorktreeCreationIntent(intentInput, repoRoot, { forge: forge.forge, forgeService: forge.service, resolveDefaultBranch: (root) => resolveDefaultBranch(root, deps), @@ -114,10 +118,33 @@ async function createWorktreeCoreWithPriority( } } + const defaultPath = await resolveDefaultWorktreePath({ + cwd: repoRoot, + paseoHome: input.paseoHome, + worktreesRoot: input.worktreesRoot, + worktreeSlug: normalizedSlug, + }); + const { stdout: sourceRoot } = await runGitCommand(["rev-parse", "--show-toplevel"], { + cwd: input.cwd, + }); + const sourceCheckout = sourceRoot.trim(); + const request = describeCreationRequest(intent, { + repoRoot, + sourceCheckout, + slug: normalizedSlug, + path: defaultPath, + }); + const transformed = deps.lifecycle + ? await deps.lifecycle.before("worktree.create.before", request) + : request; + normalizedSlug = validateWorktreeSlug(transformed.slug); + intent = creationIntentFromRequest(transformed, intent); + return { worktree: await createWorktree({ cwd: repoRoot, worktreeSlug: normalizedSlug, + worktreePath: transformed.path, source: intent, paseoHome: input.paseoHome, worktreesRoot: input.worktreesRoot, @@ -128,6 +155,61 @@ async function createWorktreeCoreWithPriority( }; } +function describeCreationRequest( + intent: WorktreeCreationIntent, + placement: Pick, +): PluginWorktreeCreateRequest { + if (intent.kind === "branch-off") + return { + ...placement, + kind: intent.kind, + branch: intent.branchName, + baseRef: intent.baseBranch, + }; + if (intent.kind === "checkout-branch") + return { ...placement, kind: intent.kind, branch: intent.branchName }; + const { localBranchName, baseRefName, ...facts } = intent; + return { + ...placement, + ...facts, + branch: localBranchName ?? intent.headRef, + baseRef: baseRefName, + }; +} + +function creationIntentFromRequest( + request: PluginWorktreeCreateRequest, + original: WorktreeCreationIntent, +): WorktreeCreationIntent { + if (request.kind === "branch-off") { + return { kind: request.kind, branchName: request.branch, baseBranch: request.baseRef }; + } + if (request.kind === "checkout-branch") { + return { + kind: request.kind, + branchName: request.branch, + }; + } + const { + repoRoot: _repoRoot, + sourceCheckout: _checkout, + slug: _slug, + path: _path, + branch, + baseRef, + ...facts + } = request; + const keepLocalBranchName = + branch !== request.headRef || + ((original.kind === "checkout-change-request" || original.kind === "checkout-github-pr") && + original.localBranchName !== undefined); + return { + ...facts, + ...(keepLocalBranchName ? { localBranchName: branch } : {}), + baseRefName: baseRef, + }; +} + async function resolveForge( repoRoot: string, deps: CreateWorktreeCoreDeps, diff --git a/packages/server/src/server/worktree-session.test.ts b/packages/server/src/server/worktree-session.test.ts index d462a2605a..7117aa2501 100644 --- a/packages/server/src/server/worktree-session.test.ts +++ b/packages/server/src/server/worktree-session.test.ts @@ -212,13 +212,7 @@ function createTerminalManagerStub(options?: { id: `terminal-${terminals.length + 1}`, name: input.name ?? "Terminal", cwd: input.cwd, - getState: () => ({ - rows: 1, - cols: 1, - scrollback: [[{ char: "$" }]], - grid: [], - cursor: { row: 0, col: 0 }, - }), + hasOutput: () => true, subscribe: () => () => {}, onExit: () => () => {}, onCommandFinished: () => () => {}, diff --git a/packages/server/src/server/worktree/commands.ts b/packages/server/src/server/worktree/commands.ts index 0aab346984..4382e46633 100644 --- a/packages/server/src/server/worktree/commands.ts +++ b/packages/server/src/server/worktree/commands.ts @@ -1,6 +1,6 @@ -import { join } from "node:path"; +import { basename } from "node:path"; -import { getPaseoWorktreesRoot, isPaseoOwnedWorktreeCwd } from "../../utils/worktree.js"; +import { isPaseoOwnedWorktreeCwd } from "../../utils/worktree.js"; import { archiveByScope, resolveWorkspaceIdAtPath, @@ -208,10 +208,18 @@ async function resolveWorktreeSlugPath( repoRoot: string, worktreeSlug: string, ): Promise { - const worktreesRoot = await getPaseoWorktreesRoot( - repoRoot, - dependencies.paseoHome, - dependencies.paseoWorktreesBaseRoot, - ); - return join(worktreesRoot, worktreeSlug); + // Worktrees can live anywhere (legacy root or wherever + // a plugin placed them), so a slug resolves against the + // discovered worktree list for the repo, never a guessed path. + const worktrees = await dependencies.workspaceGitService.listWorktrees(repoRoot); + const match = worktrees.find((entry) => basename(entry.path) === worktreeSlug); + if (!match) { + const found = worktrees.map((entry) => basename(entry.path)); + throw new Error( + found.length > 0 + ? `Paseo worktree not found for slug ${worktreeSlug}: found ${found.join(", ")}` + : `Paseo worktree not found for slug ${worktreeSlug}`, + ); + } + return match.path; } diff --git a/packages/server/src/terminal/headless-terminal.test.ts b/packages/server/src/terminal/headless-terminal.test.ts new file mode 100644 index 0000000000..d971f0d3f5 --- /dev/null +++ b/packages/server/src/terminal/headless-terminal.test.ts @@ -0,0 +1,60 @@ +import { spawnSync } from "node:child_process"; +import { fileURLToPath } from "node:url"; +import { describe, expect, it } from "vitest"; +import { createHeadlessTerminal } from "./headless-terminal.js"; + +const EMOJI_ROW = "A😀👍❤️👋🏽🇰🇷👨‍👩‍👧B"; +// A, six two-column emoji clusters, B. +const EMOJI_ROW_END_COL = 1 + 6 * 2 + 1; + +async function cursorColAfter(text: string): Promise { + const terminal = createHeadlessTerminal({ rows: 2, cols: 40 }); + try { + await new Promise((resolve) => terminal.write(text, resolve)); + return terminal.buffer.active.cursorX; + } finally { + terminal.dispose(); + } +} + +describe("createHeadlessTerminal", () => { + it("gives each emoji cluster one two-column cell", async () => { + expect(await cursorColAfter(EMOJI_ROW)).toBe(EMOJI_ROW_END_COL); + }); + + it("keeps ASCII and CJK widths", async () => { + expect(await cursorColAfter("ABC")).toBe(3); + expect(await cursorColAfter("中文")).toBe(4); + }); + + // The width table is decoded into a Node Buffer when the module loads. A + // Buffer carved out of Node's shared pool starts at a non-zero byteOffset, + // and an addon that reads the table header from offset 0 gets wrong widths + // or fails to load. Whether the pool offset is zero depends on earlier + // allocations, so the test forces a non-zero offset in a fresh process + // before the module loads. Zero bytes in front of the table make the + // misread header deterministic. + it("decodes widths correctly when Node's buffer pool offset is non-zero", () => { + const moduleUrl = new URL("./headless-terminal.ts", import.meta.url).href; + const script = ` + Buffer.poolSize = 8 * 1024 * 1024; + const occupied = Buffer.from(new Uint8Array(3 * 1024 * 1024)); + if (occupied.byteOffset !== 0 || occupied.buffer.byteLength !== Buffer.poolSize) { + throw new Error("expected a fresh shared pool"); + } + const { createHeadlessTerminal } = await import(${JSON.stringify(moduleUrl)}); + const terminal = createHeadlessTerminal({ rows: 2, cols: 40 }); + await new Promise((resolve) => terminal.write(${JSON.stringify(EMOJI_ROW)}, resolve)); + process.stdout.write(String(terminal.buffer.active.cursorX)); + terminal.dispose(); + `; + const result = spawnSync( + process.execPath, + ["--import", "tsx", "--input-type=module", "--eval", script], + { cwd: fileURLToPath(new URL(".", import.meta.url)), encoding: "utf8" }, + ); + + expect(result.status, result.stderr).toBe(0); + expect(result.stdout).toBe(String(EMOJI_ROW_END_COL)); + }); +}); diff --git a/packages/server/src/terminal/headless-terminal.ts b/packages/server/src/terminal/headless-terminal.ts new file mode 100644 index 0000000000..4e106c243b --- /dev/null +++ b/packages/server/src/terminal/headless-terminal.ts @@ -0,0 +1,22 @@ +import { UnicodeGraphemesAddon } from "@xterm/addon-unicode-graphemes"; +import xterm, { type Terminal } from "@xterm/headless"; + +export interface HeadlessTerminalOptions { + rows: number; + cols: number; + scrollback?: number; +} + +/** + * A headless xterm that measures text the way Paseo clients render it. + * + * Grapheme-cluster widths give every emoji cluster (VS16, skin-tone, flags, + * ZWJ sequences) one two-column cell, matching color-emoji fonts. Clients + * replay this buffer's ANSI with the same table, so cells and the cursor line + * up after reconnect. See docs/terminal-rendering.md. + */ +export function createHeadlessTerminal(options: HeadlessTerminalOptions): Terminal { + const terminal = new xterm.Terminal({ ...options, allowProposedApi: true }); + terminal.loadAddon(new UnicodeGraphemesAddon()); + return terminal; +} diff --git a/packages/server/src/terminal/paseo-cli-path.ts b/packages/server/src/terminal/paseo-cli-path.ts new file mode 100644 index 0000000000..18dff56f1b --- /dev/null +++ b/packages/server/src/terminal/paseo-cli-path.ts @@ -0,0 +1,83 @@ +import { existsSync } from "node:fs"; +import { createRequire } from "node:module"; +import { dirname, join, resolve as resolvePath } from "node:path"; + +// Where the Paseo CLI lives, for the PATH entry and PASEO_HOOK_CLI every terminal gets. Kept +// apart from terminal.ts so the daemon can resolve it without loading node-pty. + +const require = createRequire(import.meta.url); +const PASEO_CLI_BIN_ENTRY = "@getpaseo/cli/bin/paseo"; + +export function resolveExternalProcessPath(filePath: string): string { + return filePath.replace(/\.asar(?=[/\\]|$)/, ".asar.unpacked"); +} + +export function resolvePaseoCliBinDir(): string | null { + const cliExecutable = resolvePaseoCliExecutablePath(); + return cliExecutable ? dirname(cliExecutable) : null; +} + +export function resolvePaseoCliExecutablePath(): string | null { + const configuredCli = process.env.PASEO_CLI?.trim(); + if (configuredCli) { + return resolvePath(configuredCli); + } + + const cliEntrypoint = resolvePaseoCliBinEntrypoint(); + if (!cliEntrypoint) { + return null; + } + + const externalCliEntrypoint = resolveExternalProcessPath(cliEntrypoint); + const npmBinDir = findNpmBinDir(dirname(externalCliEntrypoint)); + if (npmBinDir) { + const shim = resolvePaseoCliShim(npmBinDir); + if (shim) { + return shim; + } + } + + return externalCliEntrypoint; +} + +function resolvePaseoCliBinEntrypoint(): string | null { + try { + return require.resolve(PASEO_CLI_BIN_ENTRY); + } catch { + return null; + } +} + +function findNpmBinDir(startPath: string): string | null { + let current = startPath; + while (true) { + const candidate = join(current, "node_modules", ".bin"); + if (hasPaseoCliShim(candidate)) { + return candidate; + } + + const parent = dirname(current); + if (parent === current) { + return null; + } + current = parent; + } +} + +function hasPaseoCliShim(binDir: string): boolean { + return resolvePaseoCliShim(binDir) !== null; +} + +function resolvePaseoCliShim(binDir: string): string | null { + for (const name of paseoCliShimNames()) { + const candidate = join(binDir, name); + if (existsSync(candidate)) { + return candidate; + } + } + return null; +} + +function paseoCliShimNames(): string[] { + return process.platform === "win32" ? ["paseo.cmd", "paseo.exe", "paseo"] : ["paseo"]; +} diff --git a/packages/server/src/terminal/terminal-capture.ts b/packages/server/src/terminal/terminal-capture.ts index e22d3b6f69..4f8a0f4625 100644 --- a/packages/server/src/terminal/terminal-capture.ts +++ b/packages/server/src/terminal/terminal-capture.ts @@ -1,6 +1,5 @@ import stripAnsi from "strip-ansi"; -import type { TerminalCell } from "@getpaseo/protocol/messages"; -import type { TerminalSession } from "./terminal.js"; +import type { IBuffer } from "@xterm/headless"; export interface CaptureTerminalLinesOptions { start?: number; @@ -13,14 +12,6 @@ export interface CaptureTerminalLinesResult { totalLines: number; } -function cellsToPlainText(cells: TerminalCell[], options: { stripAnsi: boolean }): string { - const text = cells - .map((cell) => cell.char) - .join("") - .trimEnd(); - return options.stripAnsi ? stripAnsi(text) : text; -} - function resolveCaptureLineIndex( lineNumber: number | undefined, totalLines: number, @@ -46,14 +37,10 @@ function resolveCaptureLineIndex( } export function captureTerminalLines( - terminal: TerminalSession, + buffer: IBuffer, options: CaptureTerminalLinesOptions = {}, ): CaptureTerminalLinesResult { - const state = terminal.getState(); - const allLines = [...state.scrollback, ...state.grid].map((cells) => - cellsToPlainText(cells, { stripAnsi: options.stripAnsi ?? true }), - ); - const totalLines = allLines.length; + const totalLines = buffer.length; const startIndex = resolveCaptureLineIndex(options.start, totalLines, "start"); const endIndex = resolveCaptureLineIndex(options.end, totalLines, "end"); @@ -64,8 +51,10 @@ export function captureTerminalLines( }; } - return { - lines: allLines.slice(startIndex, endIndex + 1), - totalLines, - }; + const lines: string[] = []; + for (let row = startIndex; row <= endIndex; row++) { + const text = buffer.getLine(row)!.translateToString(true).trimEnd(); + lines.push(options.stripAnsi === false ? text : stripAnsi(text)); + } + return { lines, totalLines }; } diff --git a/packages/server/src/terminal/terminal-manager-factory.ts b/packages/server/src/terminal/terminal-manager-factory.ts deleted file mode 100644 index 88dcc2d692..0000000000 --- a/packages/server/src/terminal/terminal-manager-factory.ts +++ /dev/null @@ -1,12 +0,0 @@ -import type { TerminalManager } from "./terminal-manager.js"; -import { createWorkerTerminalManager } from "./worker-terminal-manager.js"; - -export interface ConfiguredTerminalManagerOptions { - getTerminalActivityUrl?: () => string | null; -} - -export function createConfiguredTerminalManager( - options: ConfiguredTerminalManagerOptions = {}, -): TerminalManager { - return createWorkerTerminalManager(options); -} diff --git a/packages/server/src/terminal/terminal-manager.test.ts b/packages/server/src/terminal/terminal-manager.test.ts index 47905d1424..83ba035c37 100644 --- a/packages/server/src/terminal/terminal-manager.test.ts +++ b/packages/server/src/terminal/terminal-manager.test.ts @@ -457,7 +457,6 @@ it("setTerminalTitle returns false for unknown terminal ids without changing exi expect(manager.setTerminalTitle("unknown-id", "x")).toBe(false); expect(session.getTitle()).toBe("Existing title"); - expect(session.getState().title).toBe("Existing title"); expect(snapshots).toEqual([]); unsubscribe(); diff --git a/packages/server/src/terminal/terminal-manager.ts b/packages/server/src/terminal/terminal-manager.ts index df4ced389b..f8ba1851fa 100644 --- a/packages/server/src/terminal/terminal-manager.ts +++ b/packages/server/src/terminal/terminal-manager.ts @@ -1,11 +1,16 @@ +import { + replayTerminal, + type TerminalReplaySink, + type TerminalReplayMetadata, + type TerminalReplayOptions, +} from "./terminal-replay.js"; import { createTerminal, + type LocalTerminalSession, type TerminalActivityTransition, type TerminalSession, - type TerminalStateSnapshot, - type TerminalStateSnapshotOptions, } from "./terminal.js"; -import { captureTerminalLines, type CaptureTerminalLinesResult } from "./terminal-capture.js"; +import { type CaptureTerminalLinesResult } from "./terminal-capture.js"; import { randomBytes, randomUUID } from "node:crypto"; import { resolve, sep } from "node:path"; import { assertAbsolutePath, isSameOrDescendantPath } from "../server/path-utils.js"; @@ -50,6 +55,11 @@ export type TerminalWorkspaceContributionChangedListener = ( ) => void; export interface TerminalManager { + /** + * Set when this host's terminals cannot be served at all (a worker from a newer Paseo holds + * them). Callers that answer terminal requests report it instead of an empty list. + */ + getUnavailableError?(): Error | null; getTerminals(cwd: string, options?: { workspaceId?: string }): Promise; createTerminal(options: { id?: string; @@ -64,14 +74,17 @@ export interface TerminalManager { cols?: number; activityToken?: string; activityUrl?: string | null; + baseEnv?: Record; + paseoCliPath?: string | null; }): Promise; registerCwdEnv(options: { cwd: string; env: Record }): void; validateTerminalActivityToken(terminalId: string, token: string): "valid" | "unknown" | "invalid"; getTerminal(id: string): TerminalSession | undefined; - getTerminalState( + replayTerminal( id: string, - options?: TerminalStateSnapshotOptions, - ): Promise; + options: TerminalReplayOptions | undefined, + sink: TerminalReplaySink, + ): Promise; setTerminalTitle(id: string, title: string): boolean; setTerminalActivity(id: string, state: TerminalActivityState): Promise; clearTerminalAttention(id: string): Promise; @@ -97,15 +110,25 @@ export interface TerminalManagerOptions { getTerminalActivityUrl?: () => string | null; } +/** The in-process manager the terminal worker runs: it owns each PTY, so it knows its pid. */ +export interface LocalTerminalManager extends TerminalManager { + createTerminal( + options: Parameters[0], + ): Promise; + getTerminal(id: string): LocalTerminalSession | undefined; + getTerminalProcessId(id: string): number | null; + getTerminalActivityToken(id: string): string | null; +} + function createActivityToken(): string { return randomBytes(32).toString("base64url"); } export function createTerminalManager( managerOptions: TerminalManagerOptions = {}, -): TerminalManager { +): LocalTerminalManager { const terminalsByCwd = new Map(); - const terminalsById = new Map(); + const terminalsById = new Map(); const terminalExitUnsubscribeById = new Map void>(); const terminalTitleUnsubscribeById = new Map void>(); const terminalActivityUnsubscribeById = new Map void>(); @@ -186,7 +209,7 @@ export function createTerminalManager( return bestMatchRoot ? defaultEnvByRootCwd.get(bestMatchRoot) : undefined; } - function registerSession(session: TerminalSession): TerminalSession { + function registerSession(session: LocalTerminalSession): LocalTerminalSession { terminalsById.set(session.id, session); const unsubscribeExit = session.onExit(() => { removeSessionById(session.id, { kill: false }); @@ -321,7 +344,9 @@ export function createTerminalManager( cols?: number; activityToken?: string; activityUrl?: string | null; - }): Promise { + baseEnv?: Record; + paseoCliPath?: string | null; + }): Promise { assertAbsolutePath(options.cwd); const terminals = terminalsByCwd.get(options.cwd) ?? []; @@ -341,7 +366,7 @@ export function createTerminalManager( ...(terminalActivityUrl ? { PASEO_TERMINAL_ACTIVITY_URL: terminalActivityUrl } : {}), }; terminalActivityTokenById.set(terminalId, activityToken); - let session: TerminalSession; + let session: LocalTerminalSession; try { session = registerSession( await createTerminal({ @@ -355,6 +380,8 @@ export function createTerminalManager( ...(options.rows !== undefined ? { rows: options.rows } : {}), ...(options.cols !== undefined ? { cols: options.cols } : {}), ...(mergedEnv ? { env: mergedEnv } : {}), + ...(options.baseEnv ? { baseEnv: options.baseEnv } : {}), + ...(options.paseoCliPath === undefined ? {} : { paseoCliPath: options.paseoCliPath }), activityEnv, }), ); @@ -386,15 +413,21 @@ export function createTerminalManager( return expected === token ? "valid" : "invalid"; }, - getTerminal(id: string): TerminalSession | undefined { + getTerminal(id: string): LocalTerminalSession | undefined { return terminalsById.get(id); }, - async getTerminalState( - id: string, - options?: TerminalStateSnapshotOptions, - ): Promise { - return terminalsById.get(id)?.getStateSnapshot(options) ?? null; + getTerminalProcessId(id: string): number | null { + return terminalsById.get(id)?.pid ?? null; + }, + + getTerminalActivityToken(id: string): string | null { + return terminalActivityTokenById.get(id) ?? null; + }, + + async replayTerminal(id, options, sink) { + const session = terminalsById.get(id); + return session ? replayTerminal(session, options, sink) : null; }, setTerminalTitle(id: string, title: string): boolean { @@ -456,7 +489,7 @@ export function createTerminalManager( totalLines: 0, }; } - return captureTerminalLines(session, options); + return session.captureLines(options); }, listDirectories(): string[] { diff --git a/packages/server/src/terminal/terminal-replay.ts b/packages/server/src/terminal/terminal-replay.ts new file mode 100644 index 0000000000..73336a88f1 --- /dev/null +++ b/packages/server/src/terminal/terminal-replay.ts @@ -0,0 +1,135 @@ +import type { FramedSocket } from "./terminal-worker-frames.js"; +import type { + TerminalWorkerRequest, + TerminalWorkerToParentMessage, +} from "./terminal-worker-protocol.js"; +import type { LocalTerminalSession } from "./terminal.js"; + +export interface TerminalReplayOptions { + scrollbackLines?: number; +} + +export interface TerminalReplayMetadata { + rows: number; + cols: number; + retainedHistoryLines: number; + revision: number; + replayPreamble: string; +} +export type TerminalReplayEvent = + | { type: "begin"; metadata: TerminalReplayMetadata } + | { type: "data"; data: Uint8Array } + | { type: "end" }; +export type TerminalReplaySink = (event: TerminalReplayEvent) => void; +export const TERMINAL_REPLAY_CHUNK_BYTES = 64 * 1024; + +export function* createTerminalReplay( + session: LocalTerminalSession, + options: TerminalReplayOptions | undefined, +): Generator { + const { metadata, data } = session.serializeReplay(options); + yield { type: "begin", metadata }; + for (let offset = 0; offset < data.length; offset += TERMINAL_REPLAY_CHUNK_BYTES) { + yield { type: "data", data: data.subarray(offset, offset + TERMINAL_REPLAY_CHUNK_BYTES) }; + } + yield { type: "end" }; + return metadata; +} + +export async function replayTerminal( + session: LocalTerminalSession, + options: TerminalReplayOptions | undefined, + sink: TerminalReplaySink, +): Promise { + const replay = createTerminalReplay(session, options); + let next = replay.next(); + while (!next.done) { + sink(next.value); + next = replay.next(); + } + return next.value; +} + +interface TerminalReplayPorts { + getSession(id: string): LocalTerminalSession | undefined; + flushOutput(id: string): void; +} + +/** Worker-owned ANSI capture and paced delivery; live observations never wait for a replay. */ +export function createTerminalReplayController(ports: TerminalReplayPorts) { + let controller: FramedSocket | null = null; + + function sendToController(message: TerminalWorkerToParentMessage): void { + // A stalled physical controller is different from a stalled viewer: all its + // observations must reconnect to the surviving worker after this socket closes. + if (controller && controller.socket.writableLength > 4 * 1024 * 1024) { + controller.socket.destroy(); + return; + } + controller?.send(message); + } + + async function deliverReplay( + connection: FramedSocket, + message: Extract, + ): Promise { + ports.flushOutput(message.terminalId); + const session = ports.getSession(message.terminalId); + if (!session) { + await connection.sendAndWait({ + type: "response", + requestId: message.requestId, + ok: true, + result: null, + }); + return; + } + // Flush and capture share one synchronous turn. Each daemon viewer buffers + // its own live tail and discards revisions already included in this cut. + const replay = createTerminalReplay(session, message.options); + let next = replay.next(); + while (!next.done) { + if (controller !== connection) throw new Error("Terminal replay controller disconnected"); + await connection.sendAndWait({ + type: "terminalReplay", + requestId: message.requestId, + event: next.value, + }); + next = replay.next(); + } + await connection.sendAndWait({ + type: "response", + requestId: message.requestId, + ok: true, + result: next.value, + }); + } + + return { + setConnection(connection: FramedSocket | null): void { + if (controller === connection) return; + const previous = controller; + controller = connection; + previous?.socket.destroy(); + }, + send: sendToController, + async replay( + request: Extract, + ): Promise { + const connection = controller; + if (!connection) return; + try { + await deliverReplay(connection, request); + } catch (error) { + await connection + .sendAndWait({ + type: "response", + requestId: request.requestId, + ok: false, + error: error instanceof Error ? error.message : String(error), + }) + .catch(() => {}); + } + }, + }; +} diff --git a/packages/server/src/terminal/terminal-restore.test.ts b/packages/server/src/terminal/terminal-restore.test.ts index 7255cba1a5..ad008e1bd7 100644 --- a/packages/server/src/terminal/terminal-restore.test.ts +++ b/packages/server/src/terminal/terminal-restore.test.ts @@ -4,56 +4,45 @@ import { TerminalStreamOpcode, decodeTerminalStreamFrame, } from "@getpaseo/protocol/binary-frames/index"; -import type { TerminalCell, TerminalState } from "@getpaseo/protocol/messages"; import { + createTerminalRestoreDelivery, encodeTerminalRestoreFrame, resolveRestoreAfterOutputOverflow, resolveTerminalRestoreSnapshotOptions, - resolveTerminalSubscriptionSnapshotMode, } from "./terminal-restore.js"; -function terminalRow(text: string, cols = 80): TerminalCell[] { - return Array.from({ length: cols }, (_, index) => ({ - char: text[index] ?? " ", - })); -} - -function terminalState(text: string): TerminalState { - return { - rows: 1, - cols: 80, - grid: [terminalRow(text)], - scrollback: [], - cursor: { row: 0, col: text.length }, - }; -} - describe("terminal restore policy", () => { - test("uses ready snapshots only for restore-aware subscriptions", () => { - expect(resolveTerminalSubscriptionSnapshotMode(undefined)).toBe("state"); - expect(resolveTerminalSubscriptionSnapshotMode({ mode: "live" })).toBe("ready"); - }); - test("resolves bounded restore snapshot options", () => { - expect(resolveTerminalRestoreSnapshotOptions({ mode: "live" })).toBeNull(); - expect(resolveTerminalRestoreSnapshotOptions({ mode: "full-snapshot" })).toBeUndefined(); - expect(resolveTerminalRestoreSnapshotOptions({ mode: "visible-snapshot" })).toEqual({ + expect( + resolveTerminalRestoreSnapshotOptions({ restore: { mode: "live" }, chunked: false }), + ).toBeNull(); + expect( + resolveTerminalRestoreSnapshotOptions({ restore: { mode: "full-snapshot" }, chunked: false }), + ).toBeUndefined(); + expect( + resolveTerminalRestoreSnapshotOptions({ + restore: { mode: "visible-snapshot" }, + chunked: false, + }), + ).toEqual({ scrollbackLines: 200, }); expect( resolveTerminalRestoreSnapshotOptions({ - mode: "visible-snapshot", - scrollbackLines: 999, + restore: { mode: "visible-snapshot", scrollbackLines: 999 }, + chunked: false, }), ).toEqual({ scrollbackLines: 500 }); }); - test("promotes live restore to visible restore after output overflow", () => { + test("bounds pressure recovery for every restore mode", () => { expect(resolveRestoreAfterOutputOverflow({ mode: "live" })).toEqual({ mode: "visible-snapshot", + scrollbackLines: 500, }); expect(resolveRestoreAfterOutputOverflow({ mode: "full-snapshot" })).toEqual({ - mode: "full-snapshot", + mode: "visible-snapshot", + scrollbackLines: 500, }); }); @@ -61,10 +50,7 @@ describe("terminal restore policy", () => { const frame = decodeTerminalStreamFrame( encodeTerminalRestoreFrame({ slot: 4, - snapshot: { - state: terminalState("restored"), - revision: 1, - }, + data: new TextEncoder().encode("restored"), }), ); @@ -73,3 +59,40 @@ describe("terminal restore policy", () => { expect(new TextDecoder().decode(frame?.payload ?? new Uint8Array())).toContain("restored"); }); }); + +test("projects chunked replay begin onto the declared wire metadata", () => { + const frames: Uint8Array[] = []; + const deliver = createTerminalRestoreDelivery({ + slot: 7, + chunked: true, + send: (frame) => { + frames.push(frame); + }, + }); + deliver({ + type: "begin", + metadata: { + rows: 30, + cols: 120, + retainedHistoryLines: 842, + revision: 5123, + replayPreamble: "\x1b[?2004h", + }, + }); + const data = new TextEncoder().encode("\x1b[31m界 replay\x1b[0m"); + deliver({ type: "data", data }); + deliver({ type: "end" }); + const decoded = frames.map((frame) => decodeTerminalStreamFrame(frame)!); + expect(decoded.map((frame) => ({ slot: frame.slot, opcode: frame.opcode }))).toEqual([ + { slot: 7, opcode: TerminalStreamOpcode.ReplayBegin }, + { slot: 7, opcode: TerminalStreamOpcode.ReplayData }, + { slot: 7, opcode: TerminalStreamOpcode.ReplayEnd }, + ]); + expect(JSON.parse(new TextDecoder().decode(decoded[0]!.payload))).toEqual({ + rows: 30, + cols: 120, + retainedHistoryLines: 842, + }); + expect(decoded[1]!.payload).toEqual(data); + expect(decoded[2]!.payload.byteLength).toBe(0); +}); diff --git a/packages/server/src/terminal/terminal-restore.ts b/packages/server/src/terminal/terminal-restore.ts index ffc1bd9faa..c0ee7b1105 100644 --- a/packages/server/src/terminal/terminal-restore.ts +++ b/packages/server/src/terminal/terminal-restore.ts @@ -1,11 +1,11 @@ +import type { z } from "zod"; import type { SubscribeTerminalRequest } from "@getpaseo/protocol/messages"; import { TerminalStreamOpcode, - encodeTerminalSnapshotPayload, + type TerminalReplayMetadataSchema, encodeTerminalStreamFrame, } from "@getpaseo/protocol/binary-frames/index"; -import { renderTerminalSnapshotToAnsi } from "@getpaseo/protocol/terminal-snapshot"; -import type { TerminalStateSnapshot, TerminalStateSnapshotOptions } from "./terminal.js"; +import type { TerminalReplaySink, TerminalReplayOptions } from "./terminal-replay.js"; export const MAX_TERMINAL_OUTPUT_FRAME_BYTES = 256 * 1024; @@ -21,62 +21,84 @@ const MAX_VISIBLE_RESTORE_SCROLLBACK_LINES = 500; export type TerminalRestoreOptions = NonNullable; -export type TerminalSubscriptionSnapshotMode = "state" | "ready"; - -export function resolveTerminalSubscriptionSnapshotMode( - restore: TerminalRestoreOptions | undefined, -): TerminalSubscriptionSnapshotMode { - return restore ? "ready" : "state"; -} - export function resolveRestoreAfterOutputOverflow( restore: TerminalRestoreOptions | undefined, -): TerminalRestoreOptions | undefined { - if (restore?.mode === "live") { - return { mode: "visible-snapshot" }; - } - return restore; +): TerminalRestoreOptions { + return { + mode: "visible-snapshot", + scrollbackLines: Math.min( + restore?.scrollbackLines ?? MAX_VISIBLE_RESTORE_SCROLLBACK_LINES, + MAX_VISIBLE_RESTORE_SCROLLBACK_LINES, + ), + }; } -export function resolveTerminalRestoreSnapshotOptions( - restore: TerminalRestoreOptions, -): TerminalStateSnapshotOptions | null | undefined { +export function resolveTerminalRestoreSnapshotOptions({ + restore, + chunked, +}: { + restore: TerminalRestoreOptions; + chunked: boolean; +}): TerminalReplayOptions | null | undefined { if (restore.mode === "live") { return null; } - if (restore.mode === "visible-snapshot") { - return { - scrollbackLines: resolveVisibleRestoreScrollbackLines(restore.scrollbackLines), - }; + if (restore.mode === "full-snapshot") { + return chunked ? { scrollbackLines: restore.scrollbackLines } : undefined; } - return undefined; + const scrollbackLines = restore.scrollbackLines ?? DEFAULT_VISIBLE_RESTORE_SCROLLBACK_LINES; + return { + scrollbackLines: chunked + ? scrollbackLines + : Math.min(scrollbackLines, MAX_VISIBLE_RESTORE_SCROLLBACK_LINES), + }; } -export function encodeLegacyTerminalSnapshotFrame(input: { - slot: number; - snapshot: TerminalStateSnapshot; -}): Uint8Array { - return encodeTerminalStreamFrame({ - opcode: TerminalStreamOpcode.Snapshot, - slot: input.slot, - payload: encodeTerminalSnapshotPayload(input.snapshot.state), - }); -} - -export function encodeTerminalRestoreFrame(input: { - slot: number; - snapshot: TerminalStateSnapshot; -}): Uint8Array { +export function encodeTerminalRestoreFrame(input: { slot: number; data: Uint8Array }): Uint8Array { return encodeTerminalStreamFrame({ opcode: TerminalStreamOpcode.Restore, slot: input.slot, - payload: renderTerminalSnapshotToAnsi(input.snapshot.state), + payload: input.data, }); } -function resolveVisibleRestoreScrollbackLines(value: number | undefined): number { - if (typeof value !== "number") { - return DEFAULT_VISIBLE_RESTORE_SCROLLBACK_LINES; - } - return Math.min(Math.max(0, value), MAX_VISIBLE_RESTORE_SCROLLBACK_LINES); +/** The daemon's only old-app adapter. Capable delivery never assembles the replay. */ +export function createTerminalRestoreDelivery(input: { + slot: number; + chunked: boolean; + send(frame: Uint8Array): void; +}): TerminalReplaySink { + // COMPAT(terminalSingleRestore): added after v0.14.0; remove after 2027-04-30 when client floor supports chunked replay. + const legacyChunks: Uint8Array[] = []; + return (event) => { + if (!input.chunked) { + if (event.type === "data") legacyChunks.push(event.data); + if (event.type === "end") + input.send( + encodeTerminalRestoreFrame({ + slot: input.slot, + data: Buffer.concat(legacyChunks), + }), + ); + return; + } + const opcodes = { + begin: TerminalStreamOpcode.ReplayBegin, + data: TerminalStreamOpcode.ReplayData, + end: TerminalStreamOpcode.ReplayEnd, + }; + let payload: string | Uint8Array | undefined; + if (event.type === "begin") { + const begin = { + rows: event.metadata.rows, + cols: event.metadata.cols, + retainedHistoryLines: event.metadata.retainedHistoryLines, + } satisfies z.infer; + payload = JSON.stringify(begin); + } + if (event.type === "data") payload = event.data; + input.send( + encodeTerminalStreamFrame({ slot: input.slot, opcode: opcodes[event.type], payload }), + ); + }; } diff --git a/packages/server/src/terminal/terminal-serializer.ts b/packages/server/src/terminal/terminal-serializer.ts new file mode 100644 index 0000000000..5f79064948 --- /dev/null +++ b/packages/server/src/terminal/terminal-serializer.ts @@ -0,0 +1,42 @@ +import type { Terminal as TerminalType } from "@xterm/headless"; +import { SerializeAddon } from "@xterm/addon-serialize"; +import type { TerminalReplayOptions } from "./terminal-replay.js"; + +/** Serialize the owned model; the PTY is a transport, not an ANSI parser oracle. */ +export function createTerminalSerializer( + terminal: TerminalType, +): (options?: TerminalReplayOptions) => Uint8Array { + const addon = new SerializeAddon(); + terminal.loadAddon(addon); + return (options) => { + const data = addon.serialize({ scrollback: options?.scrollbackLines }); + const buffer = terminal.buffer.active; + // Addon 0.14 applies a horizontal offset after vertical movement has already + // clamped a pending-wrap column, losing a column. Restore a valid position + // absolutely; an x==cols cursor must keep its pending wrap for the next byte. + const position = + buffer.cursorX < terminal.cols ? `\x1b[${buffer.cursorY + 1};${buffer.cursorX + 1}H` : ""; + return Buffer.from(data + position + serializeCursorPresentation(terminal), "utf8"); + }; +} + +// Stable addon 0.14 serializes buffer/modes but omits DECSCUSR and cursor visibility. +// xterm 6 keeps the program-selected presentation in coreService, not public options. +function serializeCursorPresentation(terminal: TerminalType): string { + const core = ( + terminal as unknown as { + _core: { + coreService: { + isCursorHidden: boolean; + decPrivateModes: { cursorStyle?: "block" | "underline" | "bar"; cursorBlink?: boolean }; + }; + }; + } + )._core.coreService; + const visibility = `\x1b[?25${core.isCursorHidden ? "l" : "h"}`; + const cursorStyle = core.decPrivateModes.cursorStyle; + // Unset presentation belongs to each renderer's configured defaults. + if (cursorStyle === undefined) return visibility; + const style = { block: 2, underline: 4, bar: 6 }[cursorStyle]; + return `${visibility}\x1b[${style - (core.decPrivateModes.cursorBlink ? 1 : 0)} q`; +} diff --git a/packages/server/src/terminal/terminal-session-controller.test.ts b/packages/server/src/terminal/terminal-session-controller.test.ts index b438af8381..ccb152aa23 100644 --- a/packages/server/src/terminal/terminal-session-controller.test.ts +++ b/packages/server/src/terminal/terminal-session-controller.test.ts @@ -1,3 +1,6 @@ +import type { TerminalReplayOptions } from "./terminal-replay.js"; +import type { TerminalRestoreOptions } from "./terminal-restore.js"; +import type { TerminalReplayMetadata } from "./terminal-replay.js"; import { describe, expect, test, vi } from "vitest"; import pino from "pino"; @@ -7,8 +10,7 @@ import { decodeTerminalStreamFrame, type TerminalStreamFrame, } from "@getpaseo/protocol/binary-frames/index"; -import type { TerminalCell, TerminalState } from "@getpaseo/protocol/messages"; -import type { ServerMessage, TerminalSession, TerminalStateSnapshot } from "./terminal.js"; +import type { ServerMessage, TerminalSession } from "./terminal.js"; import { TerminalSessionController, type TerminalSessionControllerOptions, @@ -17,9 +19,35 @@ import { SessionDelivery } from "../server/session/owned-subscriptions/index.js" import type { TerminalManager, TerminalsChangedEvent } from "./terminal-manager.js"; import { isSameOrDescendantPath } from "../server/path-utils.js"; import { PluginSessionSocket } from "../server/plugins/session-socket.js"; +import { TerminalWorkerIncompatibleError } from "./terminal-worker-pool.js"; + +interface ReplayFixture { + data: Uint8Array; + metadata: TerminalReplayMetadata; +} +function terminalReplay(text: string, revision: number, replayPreamble = ""): ReplayFixture { + return { + data: Buffer.from(text), + metadata: { rows: 1, cols: 80, retainedHistoryLines: 0, revision, replayPreamble }, + }; +} +function replayFixture( + read: () => Promise, +): TerminalManager["replayTerminal"] { + return async (_id, _options, sink) => { + const replay = await read(); + if (!replay) return null; + await sink({ type: "begin", metadata: replay.metadata }); + await sink({ type: "data", data: replay.data }); + await sink({ type: "end" }); + return replay.metadata; + }; +} function createController( - options: TerminalSessionControllerOptions & { emitBinary(frame: Uint8Array): void }, + options: TerminalSessionControllerOptions & { + emitBinary(frame: Uint8Array): void | Promise; + }, ) { const source = {}; const ownership = new SessionDelivery( @@ -58,22 +86,6 @@ function deferred(): { return { promise, resolve, reject }; } -function terminalRow(text: string, cols = 80): TerminalCell[] { - return Array.from({ length: cols }, (_, index) => ({ - char: text[index] ?? " ", - })); -} - -function terminalState(text: string): TerminalState { - return { - rows: 1, - cols: 80, - grid: [terminalRow(text)], - scrollback: [], - cursor: { row: 0, col: text.length }, - }; -} - function createLogger(): pino.Logger { return { warn: vi.fn(), @@ -84,7 +96,7 @@ function createLogger(): pino.Logger { describe("terminal-session-controller restore", () => { test("delivers output produced while restore is in flight after the restore frame", async () => { let terminalListener: ((message: ServerMessage) => void) | null = null; - const snapshot = deferred(); + const snapshot = deferred(); const binaryFrames: TerminalStreamFrame[] = []; const outboundMessages: SessionOutboundMessage[] = []; const terminal: TerminalSession = { @@ -103,8 +115,7 @@ describe("terminal-session-controller restore", () => { onTitleChange: () => vi.fn(), onActivityChange: () => vi.fn(), getSize: () => ({ rows: 1, cols: 80 }), - getState: () => terminalState("restore-before"), - getStateSnapshot: () => ({ state: terminalState("restore-before"), revision: 1 }), + hasOutput: () => true, getReplayPreamble: () => "\x1b[?1h\x1b[?2004h", getTitle: () => undefined, getActivity: () => null, @@ -120,7 +131,7 @@ describe("terminal-session-controller restore", () => { registerCwdEnv: vi.fn(), validateTerminalActivityToken: vi.fn(() => "unknown"), getTerminal: vi.fn(() => terminal), - getTerminalState: vi.fn(() => snapshot.promise), + replayTerminal: replayFixture(() => snapshot.promise), setTerminalTitle: vi.fn(), setTerminalActivity: vi.fn(), killTerminal: vi.fn(), @@ -156,10 +167,10 @@ describe("terminal-session-controller restore", () => { }, }); await Promise.resolve(); - expect(terminalManager.getTerminalState).toHaveBeenCalledTimes(1); + expect(binaryFrames).toEqual([]); terminalListener?.({ type: "output", data: "restore-after\n", revision: 2 }); - snapshot.resolve({ state: terminalState("restore-before"), revision: 1 }); + snapshot.resolve(terminalReplay("restore-before", 1, "\x1b[?1h\x1b[?2004h")); await snapshot.promise; await new Promise((resolve) => setTimeout(resolve, 20)); @@ -201,8 +212,7 @@ function listSession(input: { onTitleChange: () => vi.fn(), onActivityChange: () => vi.fn(), getSize: () => ({ rows: 1, cols: 80 }), - getState: () => terminalState(""), - getStateSnapshot: () => ({ state: terminalState(""), revision: 0 }), + hasOutput: () => true, getReplayPreamble: () => "", getTitle: () => undefined, getActivity: () => null, @@ -235,7 +245,7 @@ describe("terminal-session-controller legacy terminal creation", () => { registerCwdEnv: vi.fn(), validateTerminalActivityToken: vi.fn(() => "unknown"), getTerminal: vi.fn(), - getTerminalState: vi.fn(), + replayTerminal: async () => null, setTerminalTitle: vi.fn(), setTerminalActivity: vi.fn(), clearTerminalAttention: vi.fn(), @@ -310,7 +320,7 @@ describe("terminal-session-controller legacy terminal creation", () => { registerCwdEnv: vi.fn(), validateTerminalActivityToken: vi.fn(() => "unknown"), getTerminal: vi.fn(), - getTerminalState: vi.fn(), + replayTerminal: async () => null, setTerminalTitle: vi.fn(), setTerminalActivity: vi.fn(), clearTerminalAttention: vi.fn(), @@ -347,6 +357,76 @@ describe("terminal-session-controller legacy terminal creation", () => { }); }); +describe("terminal-session-controller with terminals held by a newer Paseo", () => { + const incompatible = new TerminalWorkerIncompatibleError({ + paseoVersion: "9.9.9", + protocolVersion: 7, + }); + + function incompatibleManager(): TerminalManager { + return { + getUnavailableError: () => incompatible, + getTerminals: vi.fn(async () => Promise.reject(incompatible)), + createTerminal: vi.fn(async () => Promise.reject(incompatible)), + registerCwdEnv: vi.fn(), + validateTerminalActivityToken: vi.fn(() => "unknown"), + getTerminal: vi.fn(), + replayTerminal: async () => null, + setTerminalTitle: vi.fn(), + setTerminalActivity: vi.fn(), + clearTerminalAttention: vi.fn(), + killTerminal: vi.fn(), + killTerminalAndWait: vi.fn(), + captureTerminal: vi.fn(), + // The incompatible worker's terminals are not in this daemon's view. + listDirectories: vi.fn(() => []), + killAll: vi.fn(), + subscribeTerminalsChanged: vi.fn(() => vi.fn()), + subscribeTerminalActivity: vi.fn(() => vi.fn()), + subscribeTerminalWorkspaceContributionChanged: vi.fn(() => vi.fn()), + }; + } + + test.each([ + { type: "list_terminals_request" as const, requestId: "req-list" }, + { type: "list_terminals_request" as const, requestId: "req-list-cwd", cwd: "/work/repo" }, + { + type: "create_terminal_request" as const, + requestId: "req-create", + cwd: "/work/repo", + workspaceId: "ws-1", + }, + ])( + "answers $type ($requestId) with a terminal_worker_incompatible rpc_error", + async (request) => { + const outboundMessages: SessionOutboundMessage[] = []; + const controller = createController({ + terminalManager: incompatibleManager(), + emit: (message) => outboundMessages.push(message), + emitBinary: vi.fn(), + hasBinaryChannel: () => true, + isPathWithinRoot: isSameOrDescendantPath, + sessionLogger: createLogger(), + listTerminalWorkspaceRefs: async () => [{ workspaceId: "ws-1", cwd: "/work/repo" }], + }); + + await controller.dispatch(request); + + expect(outboundMessages).toEqual([ + { + type: "rpc_error", + payload: { + requestId: request.requestId, + requestType: request.type, + error: incompatible.message, + code: "terminal_worker_incompatible", + }, + }, + ]); + }, + ); +}); + async function flushMicrotasks(): Promise { await new Promise((resolve) => setTimeout(resolve, 0)); } @@ -357,99 +437,6 @@ async function waitForCoalescerFlush(): Promise { await new Promise((resolve) => setTimeout(resolve, 30)); } -describe("terminal-session-controller wrap-flag gating", () => { - function setup(clientSupportsWrapReflow?: () => boolean): { - controller: ReturnType; - getTerminalState: ReturnType; - } { - const terminal: TerminalSession = { - id: "term-1", - name: "Terminal", - cwd: "/tmp", - workspaceId: "ws-test", - send: vi.fn(), - subscribe: (listener) => { - queueMicrotask(() => listener({ type: "snapshotReady", revision: 1 })); - return vi.fn(); - }, - onExit: () => vi.fn(), - onCommandFinished: () => vi.fn(), - onTitleChange: () => vi.fn(), - onActivityChange: () => vi.fn(), - getSize: () => ({ rows: 1, cols: 80 }), - getState: () => terminalState("hello"), - getStateSnapshot: () => ({ state: terminalState("hello"), revision: 1 }), - getReplayPreamble: () => "", - getTitle: () => undefined, - getActivity: () => null, - setActivity: vi.fn(), - setTitle: vi.fn(), - getExitInfo: () => null, - kill: vi.fn(), - killAndWait: vi.fn(), - }; - const getTerminalState = vi.fn(() => - Promise.resolve({ state: terminalState("hello"), revision: 1 }), - ); - const terminalManager = { - getTerminals: vi.fn(), - createTerminal: vi.fn(), - registerCwdEnv: vi.fn(), - validateTerminalActivityToken: vi.fn(() => "unknown"), - getTerminal: vi.fn(() => terminal), - getTerminalState, - setTerminalTitle: vi.fn(), - setTerminalActivity: vi.fn(), - killTerminal: vi.fn(), - killTerminalAndWait: vi.fn(), - captureTerminal: vi.fn(), - listDirectories: vi.fn(() => []), - killAll: vi.fn(), - subscribeTerminalsChanged: vi.fn(() => vi.fn()), - subscribeTerminalActivity: vi.fn(() => vi.fn()), - subscribeTerminalWorkspaceContributionChanged: vi.fn(() => vi.fn()), - } as unknown as TerminalManager; - const controller = createController({ - terminalManager, - emit: vi.fn(), - emitBinary: vi.fn(), - hasBinaryChannel: () => true, - isPathWithinRoot: () => false, - sessionLogger: createLogger(), - ...(clientSupportsWrapReflow ? { clientSupportsWrapReflow } : {}), - }); - return { controller, getTerminalState }; - } - - async function subscribe(controller: ReturnType): Promise { - await controller.dispatch({ - type: "subscribe_terminal_request", - terminalId: "term-1", - requestId: "req-1", - restore: { mode: "visible-snapshot", scrollbackLines: 200 }, - }); - await flushMicrotasks(); - } - - test("requests wrap flags when the client supports reflowable snapshots", async () => { - const { controller, getTerminalState } = setup(() => true); - await subscribe(controller); - expect(getTerminalState).toHaveBeenCalledWith( - "term-1", - expect.objectContaining({ includeWrapFlags: true }), - ); - }); - - test("omits wrap flags when the client does not advertise support", async () => { - const { controller, getTerminalState } = setup(); - await subscribe(controller); - expect(getTerminalState).toHaveBeenCalledWith( - "term-1", - expect.objectContaining({ includeWrapFlags: false }), - ); - }); -}); - describe("terminal-session-controller subdirectory aggregation", () => { test("delivers a subdirectory change to a root subscriber as an aggregated, root-keyed snapshot", async () => { const rootCwd = "/work/repo"; @@ -470,7 +457,7 @@ describe("terminal-session-controller subdirectory aggregation", () => { registerCwdEnv: vi.fn(), validateTerminalActivityToken: vi.fn(() => "unknown"), getTerminal: vi.fn(), - getTerminalState: vi.fn(), + replayTerminal: async () => null, setTerminalTitle: vi.fn(), setTerminalActivity: vi.fn(), killTerminal: vi.fn(), @@ -538,7 +525,7 @@ describe("terminal-session-controller subdirectory aggregation", () => { registerCwdEnv: vi.fn(), validateTerminalActivityToken: vi.fn(() => "unknown"), getTerminal: vi.fn(), - getTerminalState: vi.fn(), + replayTerminal: async () => null, setTerminalTitle: vi.fn(), setTerminalActivity: vi.fn(), killTerminal: vi.fn(), @@ -630,7 +617,7 @@ describe("terminal-session-controller workspace-scoped subscriptions", () => { registerCwdEnv: vi.fn(), validateTerminalActivityToken: vi.fn(() => "unknown"), getTerminal: vi.fn(), - getTerminalState: vi.fn(), + replayTerminal: async () => null, setTerminalTitle: vi.fn(), setTerminalActivity: vi.fn(), killTerminal: vi.fn(), @@ -693,9 +680,17 @@ describe("terminal-session-controller workspace-scoped subscriptions", () => { }); describe("terminal-session-controller backpressure snapshot fallback", () => { - async function setup(getClientBufferedAmount: () => number | null): Promise<{ + async function setup( + getClientBufferedAmount: () => number | null, + chunked = false, + pace?: () => Promise, + restore?: TerminalRestoreOptions, + ): Promise<{ + messages: SessionOutboundMessage[]; pushOutput: (data: string) => void; frames: TerminalStreamFrame[]; + replayOptions: Array; + ready: () => void; }> { let terminalListener: ((message: ServerMessage) => void) | null = null; const terminal: TerminalSession = { @@ -706,19 +701,15 @@ describe("terminal-session-controller backpressure snapshot fallback", () => { send: vi.fn(), subscribe: (listener) => { terminalListener = listener; - // Legacy stream: a snapshot arrives on subscribe (one Snapshot frame), - // after which output streams through the coalescer as Output frames. - queueMicrotask(() => - listener({ type: "snapshot", state: terminalState("live"), revision: 1 }), - ); + // Readiness starts ANSI replay; later bytes use Output frames. + queueMicrotask(() => listener({ type: "snapshotReady", revision: 1 })); return vi.fn(); }, onExit: () => vi.fn(), onCommandFinished: () => vi.fn(), onTitleChange: () => vi.fn(), getSize: () => ({ rows: 1, cols: 80 }), - getState: () => terminalState("live"), - getStateSnapshot: () => ({ state: terminalState("live"), revision: 1 }), + hasOutput: () => true, getReplayPreamble: () => "", getTitle: () => undefined, setTitle: vi.fn(), @@ -726,14 +717,16 @@ describe("terminal-session-controller backpressure snapshot fallback", () => { kill: vi.fn(), killAndWait: vi.fn(), }; - const terminalManager = { + const replayOptions: Array = []; + const terminalManager: TerminalManager = { getTerminals: vi.fn(), createTerminal: vi.fn(), registerCwdEnv: vi.fn(), getTerminal: vi.fn(() => terminal), - getTerminalState: vi.fn(() => - Promise.resolve({ state: terminalState("live"), revision: 1 }), - ), + replayTerminal: (id, options, sink) => { + replayOptions.push(options); + return replayFixture(async () => terminalReplay("live", 1))(id, options, sink); + }, setTerminalTitle: vi.fn(), killTerminal: vi.fn(), killTerminalAndWait: vi.fn(), @@ -741,16 +734,26 @@ describe("terminal-session-controller backpressure snapshot fallback", () => { listDirectories: vi.fn(() => []), killAll: vi.fn(), subscribeTerminalsChanged: vi.fn(() => vi.fn()), - } as unknown as TerminalManager; + validateTerminalActivityToken: () => "unknown", + setTerminalActivity: async () => true, + clearTerminalAttention: async () => false, + subscribeTerminalActivity: () => () => {}, + subscribeTerminalWorkspaceContributionChanged: () => () => {}, + }; const frames: TerminalStreamFrame[] = []; + const messages: SessionOutboundMessage[] = []; const controller = createController({ terminalManager, - emit: vi.fn(), + emit: (message) => { + messages.push(message); + }, + supportsChunkedReplay: () => chunked, emitBinary: (bytes) => { const frame = decodeTerminalStreamFrame(bytes); if (frame) { frames.push(frame); + if (frame.opcode === TerminalStreamOpcode.ReplayBegin) return pace?.(); } }, hasBinaryChannel: () => true, @@ -763,6 +766,7 @@ describe("terminal-session-controller backpressure snapshot fallback", () => { type: "subscribe_terminal_request", terminalId: "term-1", requestId: "req-1", + restore, }); await waitForCoalescerFlush(); // Drop the initial subscribe snapshot frame so each test only sees frames @@ -770,11 +774,83 @@ describe("terminal-session-controller backpressure snapshot fallback", () => { frames.length = 0; return { + replayOptions, + ready: () => terminalListener?.({ type: "snapshotReady" }), pushOutput: (data) => terminalListener?.({ type: "output", data, revision: 2 }), frames, + messages, }; } + test.each([false, true])( + "preserves visible history defaults and explicit requests across delivery (chunked=%s)", + async (chunked) => { + const replayOpcodes = chunked + ? [ + TerminalStreamOpcode.ReplayBegin, + TerminalStreamOpcode.ReplayData, + TerminalStreamOpcode.ReplayEnd, + ] + : [TerminalStreamOpcode.Restore]; + for (const [restore, expected] of [ + [{ mode: "visible-snapshot" }, [{ scrollbackLines: 200 }]], + [{ mode: "visible-snapshot", scrollbackLines: 0 }, [{ scrollbackLines: 0 }]], + [{ mode: "visible-snapshot", scrollbackLines: 5 }, [{ scrollbackLines: 5 }]], + [{ mode: "visible-snapshot", scrollbackLines: 500 }, [{ scrollbackLines: 500 }]], + [ + { mode: "visible-snapshot", scrollbackLines: 10000 }, + [{ scrollbackLines: chunked ? 10000 : 500 }], + ], + [{ mode: "full-snapshot" }, [chunked ? { scrollbackLines: undefined } : undefined]], + [{ mode: "live" }, []], + ] as const) { + const fixture = await setup(() => 0, chunked, undefined, restore); + expect(fixture.replayOptions).toEqual(expected); + fixture.ready(); + await waitForCoalescerFlush(); + expect(fixture.replayOptions).toEqual([...expected, ...expected]); + expect(fixture.frames.map((frame) => frame.opcode)).toEqual( + restore.mode === "live" ? [] : replayOpcodes, + ); + fixture.pushOutput("after-restore"); + await waitForCoalescerFlush(); + expect(fixture.frames.at(-1)?.opcode).toBe(TerminalStreamOpcode.Output); + expect(new TextDecoder().decode(fixture.frames.at(-1)!.payload)).toBe("after-restore"); + } + }, + ); + + test.each([false, true])( + "bounds recovery without changing attach demand (chunked=%s)", + async (chunked) => { + for (const [restore, history] of [ + [{ mode: "visible-snapshot" }, 500], + [{ mode: "visible-snapshot", scrollbackLines: 10000 }, 500], + [{ mode: "full-snapshot" }, 500], + [{ mode: "visible-snapshot", scrollbackLines: 5 }, 5], + [{ mode: "visible-snapshot", scrollbackLines: 0 }, 0], + [{ mode: "full-snapshot", scrollbackLines: 0 }, 0], + [{ mode: "live", scrollbackLines: 0 }, 0], + [{ mode: "live" }, 500], + [undefined, 500], + ] as const) { + const fixture = await setup(() => 8 * 1024 * 1024, chunked, undefined, restore); + const initial = fixture.replayOptions.slice(); + fixture.pushOutput("pressure".repeat(40000)); + await waitForCoalescerFlush(); + expect(fixture.replayOptions.at(-1)).toEqual({ scrollbackLines: history }); + expect(fixture.replayOptions).toHaveLength(initial.length + 1); + fixture.ready(); // Worker adoption must use the original demand, even on the same stream. + await waitForCoalescerFlush(); + expect(fixture.replayOptions.slice(initial.length + 1)).toEqual(initial); + fixture.frames.length = 0; + fixture.pushOutput("after-catch-up"); + await waitForCoalescerFlush(); + expect(fixture.frames.map((frame) => frame.opcode)).toEqual([TerminalStreamOpcode.Output]); + } + }, + ); + test("streams all output without a snapshot when the client keeps up", async () => { const { pushOutput, frames } = await setup(() => 0); @@ -782,7 +858,7 @@ describe("terminal-session-controller backpressure snapshot fallback", () => { pushOutput(chunk); await waitForCoalescerFlush(); - expect(frames.some((frame) => frame.opcode === TerminalStreamOpcode.Snapshot)).toBe(false); + expect(frames.some((frame) => frame.opcode === TerminalStreamOpcode.Restore)).toBe(false); const outputFrames = frames.filter((frame) => frame.opcode === TerminalStreamOpcode.Output); expect(outputFrames.length).toBeGreaterThan(0); const receivedBytes = outputFrames.reduce( @@ -798,7 +874,7 @@ describe("terminal-session-controller backpressure snapshot fallback", () => { pushOutput("y".repeat(300 * 1024)); await waitForCoalescerFlush(); - expect(frames.some((frame) => frame.opcode === TerminalStreamOpcode.Snapshot)).toBe(true); + expect(frames.some((frame) => frame.opcode === TerminalStreamOpcode.Restore)).toBe(true); // After the snapshot the byte counter is reset, so a small follow-up chunk // streams as Output rather than tripping the fallback again. @@ -806,7 +882,7 @@ describe("terminal-session-controller backpressure snapshot fallback", () => { pushOutput("z".repeat(1024)); await waitForCoalescerFlush(); - expect(frames.some((frame) => frame.opcode === TerminalStreamOpcode.Snapshot)).toBe(false); + expect(frames.some((frame) => frame.opcode === TerminalStreamOpcode.Restore)).toBe(false); expect(frames.some((frame) => frame.opcode === TerminalStreamOpcode.Output)).toBe(true); }); @@ -822,7 +898,7 @@ describe("terminal-session-controller backpressure snapshot fallback", () => { pushOutput("p".repeat(300 * 1024)); await waitForCoalescerFlush(); - expect(frames.some((frame) => frame.opcode === TerminalStreamOpcode.Snapshot)).toBe(true); + expect(frames.some((frame) => frame.opcode === TerminalStreamOpcode.Restore)).toBe(true); }); test("falls back to a snapshot at the byte threshold when no backpressure signal exists", async () => { @@ -834,11 +910,41 @@ describe("terminal-session-controller backpressure snapshot fallback", () => { pushOutput("r".repeat(300 * 1024)); await waitForCoalescerFlush(); - expect(frames.some((frame) => frame.opcode === TerminalStreamOpcode.Snapshot)).toBe(true); + expect(frames.some((frame) => frame.opcode === TerminalStreamOpcode.Restore)).toBe(true); + }); + test("queues capable catch-up without waiting for the direct socket to drain", async () => { + let buffered = 0; + let release!: () => void; + const gate = new Promise((resolve) => { + release = resolve; + }); + const { pushOutput, frames, messages } = await setup( + () => buffered, + true, + () => (buffered ? gate : Promise.resolve()), + ); + buffered = 8 * 1024 * 1024; + pushOutput("y".repeat(300 * 1024)); + await waitForCoalescerFlush(); + expect(messages.filter((message) => message.type === "terminal_stream_exit")).toEqual([]); + expect(frames.map((frame) => frame.opcode)).toEqual([ + TerminalStreamOpcode.ReplayBegin, + TerminalStreamOpcode.ReplayData, + TerminalStreamOpcode.ReplayEnd, + ]); + buffered = 0; + release(); + await waitForCoalescerFlush(); + expect(frames.map((frame) => frame.opcode)).toContain(TerminalStreamOpcode.ReplayEnd); + frames.length = 0; + buffered = 8 * 1024 * 1024; // Small output must stay live after the replay resets its byte counter. + pushOutput("live-after-recovery"); + await waitForCoalescerFlush(); + expect(frames.map((frame) => frame.opcode)).toEqual([TerminalStreamOpcode.Output]); }); }); -function exitFixture(readSnapshot: () => Promise, backedUp = false) { +function exitFixture(readReplay: () => Promise, backedUp = false) { const outputs = new Set<(message: ServerMessage) => void>(); const exits = new Set[0]>(); const terminal: TerminalSession = { @@ -863,8 +969,7 @@ function exitFixture(readSnapshot: () => Promise, onTitleChange: () => () => {}, onActivityChange: () => () => {}, getSize: () => ({ rows: 1, cols: 80 }), - getState: () => terminalState("snapshot"), - getStateSnapshot: () => ({ state: terminalState("snapshot"), revision: 0 }), + hasOutput: () => true, getReplayPreamble: () => "", getTitle: () => undefined, getActivity: () => null, @@ -877,7 +982,7 @@ function exitFixture(readSnapshot: () => Promise, }; const manager: TerminalManager = { getTerminal: () => terminal, - getTerminalState: readSnapshot, + replayTerminal: replayFixture(readReplay), getTerminals: async () => [terminal], createTerminal: async () => terminal, registerCwdEnv() {}, @@ -955,7 +1060,7 @@ describe("terminal output before natural exit", () => { "flushes each observer's final bytes before exit (modern=%s)", async (modern) => { vi.useFakeTimers(); - const f = exitFixture(async () => ({ state: terminalState("snapshot"), revision: 0 })); + const f = exitFixture(async () => terminalReplay("snapshot", 0)); try { const source = {}; const owners = [ @@ -977,7 +1082,7 @@ describe("terminal output before natural exit", () => { row.message.payload.subscriptionId === owner.id)), ); expect(ordered.map((row) => row.binary?.opcode ?? row.message?.type)).toEqual([ - TerminalStreamOpcode.Snapshot, + TerminalStreamOpcode.Restore, TerminalStreamOpcode.Output, TerminalStreamOpcode.Output, "terminal_stream_exit", @@ -997,7 +1102,7 @@ describe("terminal output before natural exit", () => { test("waits for bootstrap snapshot and flushes buffered bytes without starting backpressure work", async () => { vi.useFakeTimers(); - const snapshot = deferred(); + const snapshot = deferred(); let reads = 0; const f = exitFixture(() => { reads++; @@ -1010,10 +1115,10 @@ describe("terminal output before natural exit", () => { f.exit(); await vi.advanceTimersByTimeAsync(0); expect(f.frames.map((row) => row.message?.type)).toEqual(["subscribe_terminal_response"]); - snapshot.resolve({ state: terminalState("snapshot"), revision: 0 }); + snapshot.resolve(terminalReplay("snapshot", 0)); await vi.advanceTimersByTimeAsync(0); expect(f.frames.slice(1).map((row) => row.binary?.opcode ?? row.message?.type)).toEqual([ - TerminalStreamOpcode.Snapshot, + TerminalStreamOpcode.Restore, TerminalStreamOpcode.Output, "terminal_stream_exit", ]); @@ -1033,11 +1138,10 @@ describe("terminal output before natural exit", () => { "finishes an in-flight backpressure snapshot (available=%s)", async (available) => { vi.useFakeTimers(); - const snapshot = deferred(); + const snapshot = deferred(); let reads = 0; const f = exitFixture( - async () => - ++reads === 1 ? { state: terminalState("initial"), revision: 0 } : snapshot.promise, + async () => (++reads === 1 ? terminalReplay("initial", 0) : snapshot.promise), true, ); try { @@ -1051,10 +1155,7 @@ describe("terminal output before natural exit", () => { await vi.advanceTimersByTimeAsync(0); expect(f.frames.some((row) => row.message?.type === "terminal_stream_exit")).toBe(false); if (available === "rejected") snapshot.reject(new Error("Snapshot failed during exit")); - else - snapshot.resolve( - available ? { state: terminalState("pressure-snapshot"), revision: 1 } : null, - ); + else snapshot.resolve(available ? terminalReplay("pressure-snapshot", 1) : null); await vi.advanceTimersByTimeAsync(0); const output = f.frames .filter((row) => row.binary?.opcode === TerminalStreamOpcode.Output) @@ -1074,7 +1175,7 @@ describe("terminal output before natural exit", () => { test("release during exit's pending snapshot suppresses late delivery", async () => { vi.useFakeTimers(); - const snapshot = deferred(); + const snapshot = deferred(); const f = exitFixture(() => snapshot.promise); const source = {}; try { @@ -1087,7 +1188,7 @@ describe("terminal output before natural exit", () => { subscriptionId: owner.id!, }; const release = f.delivery.request(source, request, () => f.delivery.release(owner.id!)); - snapshot.resolve({ state: terminalState("snapshot"), revision: 0 }); + snapshot.resolve(terminalReplay("snapshot", 0)); await release; await vi.advanceTimersByTimeAsync(0); expect(f.frames.map((row) => row.message?.type)).toEqual(["subscribe_terminal_response"]); @@ -1102,7 +1203,7 @@ describe("terminal output before natural exit", () => { test("explicit release discards only that observer's trailing output", async () => { vi.useFakeTimers(); - const f = exitFixture(async () => ({ state: terminalState("snapshot"), revision: 0 })); + const f = exitFixture(async () => terminalReplay("snapshot", 0)); const source = {}; try { const a = await f.subscribe(source, true, "a"); @@ -1150,8 +1251,8 @@ describe("terminal snapshot failure", () => { let reads = 0; const f = exitFixture(async () => { if (++reads === (phase === "backpressure" ? 2 : 1)) - throw new Error("Terminal worker request timed out: getTerminalState"); - return { state: terminalState("healthy"), revision: 0 }; + throw new Error("Terminal worker request timed out: replayTerminal"); + return terminalReplay("healthy", 0); }, phase === "backpressure"); try { const source = {}; @@ -1179,7 +1280,7 @@ describe("terminal snapshot failure", () => { payload: { terminalId: "exit-terminal", subscriptionId: failed.id, - error: "Terminal worker request timed out: getTerminalState", + error: "Terminal worker request timed out: replayTerminal", }, }, ]); @@ -1210,7 +1311,7 @@ describe("terminal snapshot failure", () => { ); test("release during pending rejection suppresses the failure and completes cleanup", async () => { - const snapshot = deferred(); + const snapshot = deferred(); const f = exitFixture(() => snapshot.promise); const source = {}; try { @@ -1222,7 +1323,7 @@ describe("terminal snapshot failure", () => { subscriptionId: owner.id!, }; const release = f.delivery.request(source, request, () => f.delivery.release(owner.id!)); - snapshot.reject(new Error("Terminal worker request timed out: getTerminalState")); + snapshot.reject(new Error("Terminal worker request timed out: replayTerminal")); await release; expect(f.frames.map((row) => row.message?.type)).toEqual(["subscribe_terminal_response"]); expect(f.delivery.registrationCount).toBe(0); @@ -1242,7 +1343,7 @@ test.each([false, true])( let reads = 0; const f = exitFixture(async () => { if (++reads === (backpressure ? 2 : 1)) throw new Error("Snapshot unavailable"); - return { state: terminalState("recovered"), revision: 0 }; + return terminalReplay("recovered", 0); }, backpressure); try { await f.subscribe({}, false, "legacy-recovery"); @@ -1256,7 +1357,7 @@ test.each([false, true])( for (const listener of f.outputs) listener({ type: "snapshotReady", revision: 2 }); await vi.advanceTimersByTimeAsync(5); expect(reads).toBe(backpressure ? 3 : 2); - expect(f.frames.some((row) => row.binary?.opcode === TerminalStreamOpcode.Snapshot)).toBe( + expect(f.frames.some((row) => row.binary?.opcode === TerminalStreamOpcode.Restore)).toBe( true, ); f.exit(); @@ -1276,3 +1377,51 @@ test.each([false, true])( } }, ); + +test("bounds a capturing viewer tail without ending a healthy viewer", async () => { + const pending = deferred(); + let reads = 0; + const f = exitFixture(() => + ++reads === 2 ? pending.promise : Promise.resolve(terminalReplay("retained", 0)), + ); + const desktop = {}, + phone = {}; + try { + await f.subscribe(desktop, true, "desktop"); + await waitForCoalescerFlush(); + await f.subscribe(phone, true, "phone"); + f.output("x".repeat(4 * 1024 * 1024 + 1), 1); + await waitForCoalescerFlush(); + expect( + f.frames.filter( + (row) => row.source === phone && row.message?.type === "terminal_stream_exit", + ), + ).toHaveLength(1); + expect( + f.frames.filter( + (row) => row.source === desktop && row.message?.type === "terminal_stream_exit", + ), + ).toHaveLength(0); + expect( + f.frames.some( + (row) => row.source === desktop && row.binary?.opcode === TerminalStreamOpcode.Output, + ), + ).toBe(true); + pending.resolve(terminalReplay("phone", 1)); + await waitForCoalescerFlush(); + f.output("AFTER-OVERFLOW", 2); + await waitForCoalescerFlush(); + expect( + f.frames.some( + (row) => + row.source === desktop && + row.binary?.opcode === TerminalStreamOpcode.Output && + Buffer.from(row.binary.payload).toString().includes("AFTER-OVERFLOW"), + ), + ).toBe(true); + expect(f.delivery.registrationCount).toBe(1); + } finally { + pending.resolve(null); + await f.delivery.close(); + } +}); diff --git a/packages/server/src/terminal/terminal-session-controller.ts b/packages/server/src/terminal/terminal-session-controller.ts index 4f46dbc88c..653524e54a 100644 --- a/packages/server/src/terminal/terminal-session-controller.ts +++ b/packages/server/src/terminal/terminal-session-controller.ts @@ -28,16 +28,16 @@ import { TerminalOutputCoalescer } from "./terminal-output-coalescer.js"; import { MAX_CLIENT_BUFFERED_BYTES, MAX_TERMINAL_OUTPUT_FRAME_BYTES, - encodeLegacyTerminalSnapshotFrame, - encodeTerminalRestoreFrame, + createTerminalRestoreDelivery, resolveRestoreAfterOutputOverflow, resolveTerminalRestoreSnapshotOptions, - resolveTerminalSubscriptionSnapshotMode, type TerminalRestoreOptions, } from "./terminal-restore.js"; +import type { TerminalReplayMetadata } from "./terminal-replay.js"; import type { TerminalSession } from "./terminal.js"; import type { TerminalManager, TerminalsChangedEvent } from "./terminal-manager.js"; import { applyTerminalSize } from "./terminal-size-ownership.js"; +import { TerminalWorkerIncompatibleError } from "./terminal-worker-pool.js"; import type { TerminalActivity } from "@getpaseo/protocol/terminal-activity"; import { terminalSubscriptionKey } from "@getpaseo/protocol/terminal-subscription-key"; @@ -67,31 +67,28 @@ interface ActiveTerminalStream { needsSnapshot: boolean; snapshotInFlight: boolean; retrySnapshotErrors: boolean; - readyRevision?: number; + // Readiness is independent of revision: reconnect adoption has no revision. + snapshotReady: boolean; restore?: TerminalRestoreOptions; bufferedOutputs: BufferedTerminalOutput[]; + bufferedOutputBytes: number; outputBytesSinceSnapshot: number; outputCoalescer: TerminalOutputCoalescer; } -interface SnapshotSendResult { - shouldContinue: boolean; - replayRevision?: number; -} +type SnapshotSendResult = + | { shouldContinue: false } + | { shouldContinue: true; replay: TerminalReplayMetadata | null }; export interface TerminalSessionControllerOptions { terminalManager: TerminalManager | null; emit: (msg: SessionOutboundMessage) => void; hasBinaryChannel: () => boolean; + supportsChunkedReplay?: (source: object) => boolean; isPathWithinRoot: (rootPath: string, candidatePath: string) => boolean; sessionLogger: pino.Logger; listTerminalWorkspaceRefs?: () => Promise; listTerminalWorkspaceRoots?: () => Promise; - // Whether the connected client can reflow restored snapshots. When true the - // daemon attaches per-row soft-wrap flags to snapshots; otherwise it omits them - // so old (strict-schema) clients still parse the snapshot. - clientSupportsWrapReflow?: (source: object) => boolean; - // Current max bytes queued on the client's transport(s) but not yet sent. // Drives the snapshot catch-up fallback: a keeping-up client reports ~0 and // keeps streaming; a backed-up client trips the snapshot path. Defaults to a // constant 0 (no backpressure signal) so callers without a transport always @@ -144,7 +141,6 @@ export class TerminalSessionController { private readonly sessionLogger: pino.Logger; private readonly listTerminalWorkspaceRefs: () => Promise; private readonly listTerminalWorkspaceRoots: () => Promise; - private readonly clientSupportsWrapReflow: (source: object) => boolean; private readonly getClientBufferedAmount: (source: object) => number | null; private readonly subscribedDirectories = new Map(); @@ -152,7 +148,7 @@ export class TerminalSessionController { private readonly activeStreams = new Map(); private nextSlot = 0; - constructor(options: TerminalSessionControllerOptions) { + constructor(private readonly options: TerminalSessionControllerOptions) { this.terminalManager = options.terminalManager; this.emit = options.emit; this.hasBinaryChannel = options.hasBinaryChannel; @@ -162,7 +158,6 @@ export class TerminalSessionController { this.listTerminalWorkspaceRoots = options.listTerminalWorkspaceRoots ?? (async () => (await this.listTerminalWorkspaceRefs()).map((workspace) => workspace.cwd)); - this.clientSupportsWrapReflow = options.clientSupportsWrapReflow ?? (() => false); this.getClientBufferedAmount = options.getClientBufferedAmount ?? (() => 0); } @@ -427,6 +422,8 @@ export class TerminalSessionController { } try { + const unavailable = this.terminalManager.getUnavailableError?.(); + if (unavailable) throw unavailable; let terminals: TerminalSession[]; if (msg.workspaceId !== undefined) { terminals = (await this.getAllTerminalSessions()).filter( @@ -449,6 +446,10 @@ export class TerminalSessionController { }); } catch (error) { this.sessionLogger.error({ err: error, cwd: msg.cwd }, "Failed to list terminals"); + if (error instanceof TerminalWorkerIncompatibleError) { + this.emitIncompatible(msg, error); + return; + } this.emit({ type: "list_terminals_response", payload: { @@ -460,6 +461,23 @@ export class TerminalSessionController { } } + // An empty list or a generic failure would read as "no terminals"; the client needs to know + // they exist and why it cannot reach them. + private emitIncompatible( + msg: { type: string; requestId: string }, + error: TerminalWorkerIncompatibleError, + ): void { + this.emit({ + type: "rpc_error", + payload: { + requestId: msg.requestId, + requestType: msg.type, + error: error.message, + code: error.code, + }, + }); + } + private async getAllTerminalSessions(): Promise { if (!this.terminalManager) { return []; @@ -597,6 +615,10 @@ export class TerminalSessionController { }); } catch (error) { this.sessionLogger.error({ err: error, cwd: msg.cwd }, "Failed to create terminal"); + if (error instanceof TerminalWorkerIncompatibleError) { + this.emitIncompatible(msg, error); + return; + } this.emit({ type: "create_terminal_response", payload: { @@ -876,9 +898,10 @@ export class TerminalSessionController { snapshotInFlight: false, retrySnapshotErrors: options.retrySnapshotErrors, exiting: false, - readyRevision: undefined, + snapshotReady: false, restore: options?.restore, bufferedOutputs: [], + bufferedOutputBytes: 0, outputBytesSinceSnapshot: 0, outputCoalescer: new TerminalOutputCoalescer({ timers: { setTimeout, clearTimeout }, @@ -906,7 +929,6 @@ export class TerminalSessionController { // The snapshot replaces this batch only after it succeeds. If the // terminal disappears during the read, completion still owns these bytes. activeStream.snapshotOutput = payload; - activeStream.restore = resolveRestoreAfterOutputOverflow(activeStream.restore); activeStream.needsSnapshot = true; void this.trySendSnapshot(activeStream); return; @@ -924,35 +946,45 @@ export class TerminalSessionController { this.activeStreams.set(slot, activeStream); - const unsubscribeOutput = terminal.subscribe( - (message) => { - if (this.activeStreams.get(slot) !== activeStream) { - return; - } - if (message.type === "snapshot" || message.type === "snapshotReady") { - activeStream.readyRevision = message.revision; - activeStream.outputCoalescer.flush(); - activeStream.needsSnapshot = true; - void this.trySendSnapshot(activeStream); - return; - } - if (message.type === "titleChange") { - return; - } - if (message.data.length === 0) { - return; - } - if (activeStream.needsSnapshot || activeStream.snapshotInFlight) { - activeStream.bufferedOutputs.push({ - data: message.data, - revision: message.revision, + const unsubscribeOutput = terminal.subscribe((message) => { + if (this.activeStreams.get(slot) !== activeStream) { + return; + } + if (message.type === "snapshotReady") { + activeStream.snapshotReady = true; + activeStream.outputCoalescer.flush(); + activeStream.needsSnapshot = true; + void this.trySendSnapshot(activeStream); + return; + } + if (message.type === "titleChange") { + return; + } + if (message.data.length === 0) { + return; + } + if (activeStream.needsSnapshot || activeStream.snapshotInFlight) { + activeStream.bufferedOutputBytes += Buffer.byteLength(message.data); + if (activeStream.bufferedOutputBytes > MAX_CLIENT_BUFFERED_BYTES) { + activeStream.owner.emit({ + type: "terminal_stream_exit", + payload: { + terminalId: activeStream.terminalId, + error: "Terminal replay live tail exceeded the buffer; attach again", + }, }); + this.detachRegistration(activeStream); + void activeStream.owner.release(); return; } - activeStream.outputCoalescer.handle(message.data); - }, - { initialSnapshot: resolveTerminalSubscriptionSnapshotMode(options?.restore) }, - ); + activeStream.bufferedOutputs.push({ + data: message.data, + revision: message.revision, + }); + return; + } + activeStream.outputCoalescer.handle(message.data); + }); const unsubscribeExit = terminal.onExit(() => this.detachStream(terminal.id, { emitExit: true }), ); @@ -989,22 +1021,27 @@ export class TerminalSessionController { this.detachStream(activeStream.terminalId, { emitExit: true }); return; } - if (activeStream.restore && activeStream.readyRevision === undefined) { + if (activeStream.restore && !activeStream.snapshotReady) { return; } activeStream.outputCoalescer.flush(); activeStream.snapshotInFlight = true; try { - const restore = activeStream.restore; + // A pressure catch-up replaces the skipped batch with a recent window. + // Keep the subscription demand intact for later adoption/full restores. + const restore = + activeStream.snapshotOutput !== undefined + ? resolveRestoreAfterOutputOverflow(activeStream.restore) + : activeStream.restore; const snapshotResult = restore ? await this.emitRestoreSnapshot(activeStream, terminalManager, restore) - : await this.emitLegacySnapshot(activeStream, terminalManager); + : await this.emitRestoreSnapshot(activeStream, terminalManager, { mode: "full-snapshot" }); if (!snapshotResult.shouldContinue) { return; } activeStream.snapshotOutput = undefined; - this.replayTerminalOutputAfterSnapshot(activeStream, terminal, snapshotResult.replayRevision); + this.replayTerminalOutputAfterSnapshot(activeStream, terminal, snapshotResult.replay); activeStream.needsSnapshot = false; activeStream.outputBytesSinceSnapshot = 0; } catch (error) { @@ -1042,47 +1079,31 @@ export class TerminalSessionController { } } - private async emitLegacySnapshot( - activeStream: ActiveTerminalStream, - terminalManager: TerminalManager, - ): Promise { - const snapshot = await terminalManager.getTerminalState(activeStream.terminalId, { - includeWrapFlags: this.clientSupportsWrapReflow(activeStream.owner.source), - }); - if (this.activeStreams.get(activeStream.slot) !== activeStream) { - return { shouldContinue: false }; - } - if (!snapshot) { - this.detachStream(activeStream.terminalId, { emitExit: true }); - return { shouldContinue: false }; - } - - activeStream.owner.emitBinary( - encodeLegacyTerminalSnapshotFrame({ - slot: activeStream.slot, - snapshot, - }), - ); - // The snapshot frame went out-of-band; keep the replay that follows on the - // coalescer's trailing path so it doesn't flush back-to-back with it. - activeStream.outputCoalescer.markFlushed(); - return { shouldContinue: true, replayRevision: snapshot.revision }; - } - private async emitRestoreSnapshot( activeStream: ActiveTerminalStream, terminalManager: TerminalManager, restore: TerminalRestoreOptions, ): Promise { - const snapshotOptions = resolveTerminalRestoreSnapshotOptions(restore); + const chunked = this.options.supportsChunkedReplay?.(activeStream.owner.source) === true; + const snapshotOptions = resolveTerminalRestoreSnapshotOptions({ restore, chunked }); if (snapshotOptions === null) { - return { shouldContinue: true }; + return { shouldContinue: true, replay: null }; } - const snapshot = await terminalManager.getTerminalState(activeStream.terminalId, { - ...snapshotOptions, - includeWrapFlags: this.clientSupportsWrapReflow(activeStream.owner.source), + const deliver = createTerminalRestoreDelivery({ + slot: activeStream.slot, + chunked, + // Network delivery belongs to the bounded application transport, not the worker request. + send: (frame) => activeStream.owner.emitBinary(frame), }); + const snapshot = await terminalManager.replayTerminal( + activeStream.terminalId, + snapshotOptions, + (event) => { + if (this.activeStreams.get(activeStream.slot) !== activeStream) return; + deliver(event); + }, + ); if (this.activeStreams.get(activeStream.slot) !== activeStream) { return { shouldContinue: false }; } @@ -1091,38 +1112,31 @@ export class TerminalSessionController { return { shouldContinue: false }; } - activeStream.owner.emitBinary( - encodeTerminalRestoreFrame({ - slot: activeStream.slot, - snapshot, - }), - ); // The restore frame went out-of-band; keep the replay that follows on the // coalescer's trailing path so it doesn't flush back-to-back with it. activeStream.outputCoalescer.markFlushed(); - return { shouldContinue: true, replayRevision: snapshot.revision }; + return { shouldContinue: true, replay: snapshot }; } private replayTerminalOutputAfterSnapshot( activeStream: ActiveTerminalStream, terminal: TerminalSession, - replayRevision: number | undefined, + replay: TerminalReplayMetadata | null, ): void { - const replayPreamble = terminal.getReplayPreamble(); + // A captured viewer must start from its cut, then apply the buffered mode changes. + // Live-only subscriptions have no capture and start from the current shared modes. + const replayPreamble = replay === null ? terminal.getReplayPreamble() : replay.replayPreamble; if (replayPreamble.length > 0) { activeStream.outputCoalescer.handle(replayPreamble); } + activeStream.bufferedOutputBytes = 0; const bufferedOutputs = activeStream.bufferedOutputs.splice( 0, activeStream.bufferedOutputs.length, ); for (const output of bufferedOutputs) { - if ( - replayRevision !== undefined && - output.revision !== undefined && - output.revision <= replayRevision - ) { + if (replay !== null && output.revision !== undefined && output.revision <= replay.revision) { continue; } activeStream.outputCoalescer.handle(output.data); diff --git a/packages/server/src/terminal/terminal-worker-client.test.ts b/packages/server/src/terminal/terminal-worker-client.test.ts new file mode 100644 index 0000000000..01a4dd91d3 --- /dev/null +++ b/packages/server/src/terminal/terminal-worker-client.test.ts @@ -0,0 +1,117 @@ +import { afterEach, describe, expect, it } from "vitest"; +import { existsSync, mkdtempSync, rmSync, statSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { isPlatform } from "../test-utils/platform.js"; +import { encodeFrame, FrameDecoder, TerminalWorkerFrameError } from "./terminal-worker-frames.js"; +import { connectTerminalWorker, TerminalWorkerConnectError } from "./terminal-worker-client.js"; +import { launchTerminalWorker } from "./terminal-worker-launch.js"; +import { terminalWorkerRecordPath } from "./terminal-worker-record.js"; + +const temporaryDirs: string[] = []; + +afterEach(() => { + for (const dir of temporaryDirs.splice(0)) { + rmSync(dir, { recursive: true, force: true }); + } +}); + +async function waitUntil(predicate: () => boolean, timeoutMs: number): Promise { + const deadline = Date.now() + timeoutMs; + while (!predicate()) { + if (Date.now() > deadline) throw new Error("condition not met in time"); + await new Promise((resolve) => setTimeout(resolve, 50)); + } +} + +describe("terminal worker frames", () => { + it("decodes frames split across chunks and several frames in one chunk", () => { + const first = encodeFrame({ type: "a", data: new Map([["k", 1]]) }); + const second = encodeFrame({ type: "b" }); + const joined = Buffer.concat([first, second]); + const decoder = new FrameDecoder(); + expect(decoder.push(joined.subarray(0, 3))).toEqual([]); + expect(decoder.push(joined.subarray(3, first.length + 2))).toEqual([ + { type: "a", data: new Map([["k", 1]]) }, + ]); + expect(decoder.push(joined.subarray(first.length + 2))).toEqual([{ type: "b" }]); + }); + + it("rejects a frame header announcing an oversized payload", () => { + const header = Buffer.alloc(4); + header.writeUInt32BE(0xffffffff, 0); + expect(() => new FrameDecoder().push(header)).toThrow(TerminalWorkerFrameError); + }); +}); + +describe("terminal worker authentication", () => { + it("closes a connection with the wrong secret and accepts the record's secret", async () => { + const paseoHome = mkdtempSync(path.join(tmpdir(), "tw-auth-")); + temporaryDirs.push(paseoHome); + const { record, recordPath } = await launchTerminalWorker({ + paseoHome, + paseoVersion: "0.0.0-test", + }); + expect(recordPath).toBe(terminalWorkerRecordPath(paseoHome, record.pid)); + if (!isPlatform("win32")) { + expect(statSync(recordPath).mode & 0o777).toBe(0o600); + expect(statSync(record.socketPath).mode & 0o777).toBe(0o600); + } + + await expect( + connectTerminalWorker({ socketPath: record.socketPath, secret: "wrong-secret" }), + ).rejects.toBeInstanceOf(TerminalWorkerConnectError); + + const connection = await connectTerminalWorker({ + socketPath: record.socketPath, + secret: record.secret, + }); + expect(connection.workerPid).toBe(record.pid); + // With no terminals, a worker whose controller leaves exits and removes its record. + connection.disconnect(); + await waitUntil(() => !existsSync(recordPath), 10_000); + }); +}); + +it("bounds a stalled framed writer to one chunk and resumes in order", async () => { + const { createServer, createConnection } = await import("node:net"); + const { attachFramedSocket } = await import("./terminal-worker-frames.js"); + const server = createServer(); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const address = server.address(); + if (!address || typeof address === "string") throw new Error("Missing test address"); + const accepted = new Promise((resolve) => + server.once("connection", resolve), + ); + const reader = createConnection(address.port, "127.0.0.1"); + reader.pause(); + const writer = await accepted; + const framed = attachFramedSocket(writer, () => {}); + let completed = 0; + let peakQueuedBytes = 0; + const received: number[] = []; + attachFramedSocket(reader, (value) => received.push((value as { index: number }).index)); + const sending = (async () => { + for (let index = 0; index < 512; index++) { + const pending = framed.sendAndWait({ index, data: Buffer.alloc(64 * 1024) }); + peakQueuedBytes = Math.max(peakQueuedBytes, writer.writableLength); + await pending; + completed++; + } + })(); + try { + await waitUntil(() => writer.writableLength > 0, 10000); + await new Promise((resolve) => setTimeout(resolve, 100)); + expect(completed).toBeLessThan(512); + expect(peakQueuedBytes).toBeLessThan(65 * 1024); + reader.resume(); + await sending; + await waitUntil(() => received.length === 512, 10000); + expect(received).toEqual(Array.from({ length: 512 }, (_, index) => index)); + expect(writer.destroyed).toBe(false); + } finally { + reader.destroy(); + writer.destroy(); + await new Promise((resolve) => server.close(() => resolve())); + } +}); diff --git a/packages/server/src/terminal/terminal-worker-client.ts b/packages/server/src/terminal/terminal-worker-client.ts new file mode 100644 index 0000000000..532f3075c6 --- /dev/null +++ b/packages/server/src/terminal/terminal-worker-client.ts @@ -0,0 +1,141 @@ +import { EventEmitter } from "node:events"; +import { createConnection } from "node:net"; +import { attachFramedSocket, type FramedSocket } from "./terminal-worker-frames.js"; +import { + TERMINAL_WORKER_PROTOCOL_VERSION, + type TerminalWorkerHello, + type TerminalWorkerHelloAck, + type TerminalWorkerRequest, + type TerminalWorkerToParentMessage, +} from "./terminal-worker-protocol.js"; + +const DEFAULT_CONNECT_TIMEOUT_MS = 5_000; + +/** The daemon's (or cleanup's) authenticated connection to one terminal worker. */ +export interface TerminalWorkerConnection { + readonly connected: boolean; + readonly workerPid: number; + send(message: TerminalWorkerRequest, callback: (error: Error | null) => void): boolean; + /** Closes the socket. The worker keeps running and keeps its terminals. */ + disconnect(): void; + on(event: "message", listener: (message: TerminalWorkerToParentMessage) => void): this; + on(event: "close", listener: () => void): this; +} + +export class TerminalWorkerConnectError extends Error { + constructor(message: string, options?: { cause?: unknown }) { + super(message, options); + this.name = "TerminalWorkerConnectError"; + } +} + +class SocketTerminalWorkerConnection extends EventEmitter implements TerminalWorkerConnection { + readonly workerPid: number; + private readonly framed: FramedSocket; + private closed = false; + + constructor(framed: FramedSocket, workerPid: number) { + super(); + this.framed = framed; + this.workerPid = workerPid; + framed.socket.once("close", () => { + this.closed = true; + this.emit("close"); + }); + } + + get connected(): boolean { + return !this.closed && !this.framed.socket.destroyed; + } + + send(message: TerminalWorkerRequest, callback: (error: Error | null) => void): boolean { + return this.framed.send(message, callback); + } + + disconnect(): void { + this.framed.close(); + } + + deliver(message: TerminalWorkerToParentMessage): void { + this.emit("message", message); + } +} + +function isHelloAck(message: unknown): message is TerminalWorkerHelloAck { + return ( + typeof message === "object" && + message !== null && + (message as { type?: unknown }).type === "helloAck" && + typeof (message as { pid?: unknown }).pid === "number" + ); +} + +/** + * Connects to a worker's socket and authenticates with the record's secret. The worker closes + * the socket on a wrong secret, so a rejected hello surfaces as a connect error. + */ +export function connectTerminalWorker(input: { + socketPath: string; + secret: string; + timeoutMs?: number; +}): Promise { + const timeoutMs = input.timeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS; + return new Promise((resolve, reject) => { + const socket = createConnection(input.socketPath); + let connection: SocketTerminalWorkerConnection | null = null; + let settled = false; + const fail = (error: Error) => { + if (settled) return; + settled = true; + clearTimeout(timer); + socket.destroy(); + reject(error); + }; + const timer = setTimeout(() => { + fail( + new TerminalWorkerConnectError( + `Terminal worker at ${input.socketPath} did not answer within ${timeoutMs}ms`, + ), + ); + }, timeoutMs); + const framed = attachFramedSocket(socket, (message) => { + if (connection) { + connection.deliver(message as TerminalWorkerToParentMessage); + return; + } + if (!isHelloAck(message)) { + fail(new TerminalWorkerConnectError("Terminal worker sent an unexpected first frame")); + return; + } + settled = true; + clearTimeout(timer); + connection = new SocketTerminalWorkerConnection(framed, message.pid); + resolve(connection); + }); + // `on`, not `once`: an error after authentication must not go unhandled. `close` + // follows every socket error and ends the connection. + socket.on("error", (error) => { + fail( + new TerminalWorkerConnectError( + `Cannot connect to terminal worker at ${input.socketPath}: ${error.message}`, + { cause: error }, + ), + ); + }); + socket.once("close", () => { + fail( + new TerminalWorkerConnectError( + `Terminal worker at ${input.socketPath} closed the connection during authentication`, + ), + ); + }); + socket.once("connect", () => { + const hello: TerminalWorkerHello = { + type: "hello", + secret: input.secret, + protocolVersion: TERMINAL_WORKER_PROTOCOL_VERSION, + }; + framed.send(hello); + }); + }); +} diff --git a/packages/server/src/terminal/terminal-worker-frames.ts b/packages/server/src/terminal/terminal-worker-frames.ts new file mode 100644 index 0000000000..897e91826f --- /dev/null +++ b/packages/server/src/terminal/terminal-worker-frames.ts @@ -0,0 +1,110 @@ +import type { Socket } from "node:net"; +import { deserialize, serialize } from "node:v8"; + +// Frames on the terminal worker socket: a 4-byte big-endian length, then a v8-serialized +// payload (the same structured-clone semantics the old fork IPC used with +// `serialization: "advanced"`). The frame format is part of the frozen envelope: every worker +// version must keep it. +const FRAME_HEADER_BYTES = 4; +const MAX_FRAME_BYTES = 256 * 1024 * 1024; + +export class TerminalWorkerFrameError extends Error { + constructor(message: string) { + super(message); + this.name = "TerminalWorkerFrameError"; + } +} + +export function encodeFrame(value: unknown): Buffer { + const payload = serialize(value); + if (payload.length > MAX_FRAME_BYTES) { + throw new TerminalWorkerFrameError( + `Terminal worker frame of ${payload.length} bytes is too large`, + ); + } + const header = Buffer.allocUnsafe(FRAME_HEADER_BYTES); + header.writeUInt32BE(payload.length, 0); + return Buffer.concat([header, payload]); +} + +export class FrameDecoder { + private buffered: Buffer = Buffer.alloc(0); + + push(chunk: Buffer): unknown[] { + this.buffered = this.buffered.length === 0 ? chunk : Buffer.concat([this.buffered, chunk]); + const messages: unknown[] = []; + while (this.buffered.length >= FRAME_HEADER_BYTES) { + const length = this.buffered.readUInt32BE(0); + if (length > MAX_FRAME_BYTES) { + throw new TerminalWorkerFrameError(`Terminal worker frame of ${length} bytes is too large`); + } + const end = FRAME_HEADER_BYTES + length; + if (this.buffered.length < end) break; + messages.push(deserialize(this.buffered.subarray(FRAME_HEADER_BYTES, end))); + this.buffered = this.buffered.subarray(end); + } + return messages; + } +} + +export interface FramedSocket { + readonly socket: Socket; + send(message: unknown, callback?: (error: Error | null) => void): boolean; + sendAndWait(message: unknown): Promise; + close(): void; +} + +/** + * Wraps a connected socket in length-prefixed frames. A malformed frame destroys the socket: + * the peer is either not a terminal worker endpoint or is corrupt, and both end the session. + */ +export function attachFramedSocket( + socket: Socket, + onMessage: (message: unknown) => void, +): FramedSocket { + const decoder = new FrameDecoder(); + socket.on("data", (chunk: Buffer) => { + let messages: unknown[]; + try { + messages = decoder.push(chunk); + } catch (error) { + socket.destroy(error instanceof Error ? error : new Error(String(error))); + return; + } + for (const message of messages) { + if (socket.destroyed) return; + onMessage(message); + } + }); + return { + socket, + send(message, callback) { + if (socket.destroyed || !socket.writable) { + callback?.(new Error("Terminal worker socket is closed")); + return false; + } + let frame: Buffer; + try { + frame = encodeFrame(message); + } catch (error) { + callback?.(error instanceof Error ? error : new Error(String(error))); + return false; + } + return socket.write(frame, (error) => callback?.(error ?? null)); + }, + sendAndWait(message) { + return new Promise((resolve, reject) => { + this.send(message, (error) => { + if (error) { + reject(error); + return; + } + resolve(); + }); + }); + }, + close() { + socket.end(() => socket.destroy()); + }, + }; +} diff --git a/packages/server/src/terminal/terminal-worker-launch.ts b/packages/server/src/terminal/terminal-worker-launch.ts new file mode 100644 index 0000000000..573abe3bd8 --- /dev/null +++ b/packages/server/src/terminal/terminal-worker-launch.ts @@ -0,0 +1,93 @@ +import { execFile } from "node:child_process"; +import { randomUUID } from "node:crypto"; +import { buildSelfNodeCommand } from "../server/paseo-env.js"; +import { ensurePrivateDirectory } from "../server/private-files.js"; +import { + readTerminalWorkerRecord, + terminalWorkerDirectory, + terminalWorkerRecordPath, + type TerminalWorkerRecord, +} from "./terminal-worker-record.js"; +import { resolveTerminalWorkerEntry, type TerminalWorkerEntry } from "./terminal-worker-runtime.js"; + +const LAUNCH_TIMEOUT_MS = 20_000; + +export class TerminalWorkerLaunchError extends Error { + constructor(message: string, options?: { cause?: unknown }) { + super(message, options); + this.name = "TerminalWorkerLaunchError"; + } +} + +/** + * Starts a terminal worker outside this process's tree: the launcher spawns the worker + * detached and exits once it listens, so the worker is re-parented and survives this daemon. + * Resolves with the record the worker wrote; a failed start leaves no worker behind. + */ +export async function launchTerminalWorker(input: { + paseoHome: string; + paseoVersion: string; + timeoutMs?: number; + /** Defaults to the copy of this installation's bundle (source in dev). */ + entry?: TerminalWorkerEntry; +}): Promise<{ record: TerminalWorkerRecord; recordPath: string }> { + const recordId = randomUUID(); + ensurePrivateDirectory(terminalWorkerDirectory(input.paseoHome)); + const entry = input.entry ?? resolveTerminalWorkerEntry(input); + const launch = buildSelfNodeCommand([ + ...entry.execArgv, + entry.scriptPath, + "--launch", + "--record-id", + recordId, + "--paseo-home", + input.paseoHome, + "--paseo-version", + input.paseoVersion, + ...(entry.runtime ? ["--runtime", entry.runtime] : []), + ]); + const stdout = await new Promise((resolve, reject) => { + execFile( + launch.command, + launch.args, + { + env: launch.env, + timeout: input.timeoutMs ?? LAUNCH_TIMEOUT_MS, + windowsHide: true, + encoding: "utf8", + }, + (error, out, err) => { + if (error) { + const detail = err.trim() || error.message; + reject( + new TerminalWorkerLaunchError(`Terminal worker failed to start: ${detail}`, { + cause: error, + }), + ); + return; + } + resolve(out); + }, + ); + }); + + let pid: number; + try { + const parsed = JSON.parse(stdout.trim()) as { pid?: unknown }; + if (typeof parsed.pid !== "number") throw new Error("missing pid"); + pid = parsed.pid; + } catch (error) { + throw new TerminalWorkerLaunchError( + `Terminal worker launcher printed an unexpected result: ${stdout.trim()}`, + { cause: error }, + ); + } + const recordPath = terminalWorkerRecordPath(input.paseoHome, pid); + const record = await readTerminalWorkerRecord(recordPath); + if (record.recordId !== recordId) { + throw new TerminalWorkerLaunchError( + `Terminal worker record ${recordPath} belongs to another launch`, + ); + } + return { record, recordPath }; +} diff --git a/packages/server/src/terminal/terminal-worker-ownership.test.ts b/packages/server/src/terminal/terminal-worker-ownership.test.ts new file mode 100644 index 0000000000..7abbb9aa62 --- /dev/null +++ b/packages/server/src/terminal/terminal-worker-ownership.test.ts @@ -0,0 +1,91 @@ +import { describe, expect, it } from "vitest"; +import type { ManagedProcessInspection } from "../server/managed-processes/managed-processes.js"; +import { + classifyTerminalProgramProcess, + classifyTerminalWorkerProcess, +} from "./terminal-worker-ownership.js"; + +const BIRTH = "Wed Oct 21 18:12:49 2026"; +const OTHER_BIRTH = "Wed Oct 21 18:13:02 2026"; + +function alive(startedAt: string | null, commandLine: string | null): ManagedProcessInspection { + return { status: "alive", snapshot: { pid: 4242, startedAt, commandLine } }; +} + +const workerRecord = { + recordId: "record-1", + identity: { + startedAt: BIRTH, + commandLine: "node terminal-worker-process.js --paseo-terminal-worker record-1", + }, +}; + +describe("terminal program ownership", () => { + it("owns a program that ran exec: same pid and birth time, new command line", () => { + expect( + classifyTerminalProgramProcess({ startedAt: BIRTH }, alive(BIRTH, "sleep 100000")), + ).toEqual({ status: "owned" }); + }); + + it("treats a reused pid with the same command line but another birth time as unrelated", () => { + expect( + classifyTerminalProgramProcess({ startedAt: BIRTH }, alive(OTHER_BIRTH, "/bin/zsh -l")), + ).toMatchObject({ status: "unrelated" }); + }); + + it("never owns a process without a birth time on either side, whatever its command", () => { + expect( + classifyTerminalProgramProcess({ startedAt: BIRTH }, alive(null, "/bin/zsh -l")), + ).toMatchObject({ status: "unknown" }); + expect( + classifyTerminalProgramProcess({ startedAt: null }, alive(BIRTH, "/bin/zsh -l")), + ).toMatchObject({ status: "unknown" }); + }); + + it("reports an inspection error as unknown, not gone", () => { + expect( + classifyTerminalProgramProcess( + { startedAt: BIRTH }, + { status: "error", error: new Error("ps failed") }, + ), + ).toMatchObject({ status: "unknown", reason: expect.stringContaining("ps failed") }); + }); + + it("reports a missing process as gone", () => { + expect(classifyTerminalProgramProcess({ startedAt: BIRTH }, { status: "not-found" })).toEqual({ + status: "gone", + }); + }); +}); + +describe("terminal worker ownership", () => { + it("owns the worker whose birth time matches and whose command line carries its record id", () => { + expect( + classifyTerminalWorkerProcess(workerRecord, alive(BIRTH, workerRecord.identity.commandLine)), + ).toEqual({ status: "owned" }); + }); + + it("treats another worker reusing the pid in the same second as unrelated", () => { + expect( + classifyTerminalWorkerProcess( + workerRecord, + alive(BIRTH, "node terminal-worker-process.js --paseo-terminal-worker record-2"), + ), + ).toMatchObject({ status: "unrelated" }); + }); + + it("treats a worker pid reused with another birth time as unrelated", () => { + expect( + classifyTerminalWorkerProcess( + workerRecord, + alive(OTHER_BIRTH, workerRecord.identity.commandLine), + ), + ).toMatchObject({ status: "unrelated" }); + }); + + it("does not own a worker whose command line cannot be read", () => { + expect(classifyTerminalWorkerProcess(workerRecord, alive(BIRTH, null))).toMatchObject({ + status: "unknown", + }); + }); +}); diff --git a/packages/server/src/terminal/terminal-worker-ownership.ts b/packages/server/src/terminal/terminal-worker-ownership.ts new file mode 100644 index 0000000000..9bd02b01cd --- /dev/null +++ b/packages/server/src/terminal/terminal-worker-ownership.ts @@ -0,0 +1,69 @@ +import type { ManagedProcessInspection } from "../server/managed-processes/managed-processes.js"; +import { TERMINAL_WORKER_MARKER_ARG, type TerminalWorkerRecord } from "./terminal-worker-record.js"; + +// Who a pid named in a terminal worker record belongs to, before anything signals it. +// +// This is deliberately not `processIdentityMatches` from managed-processes.ts: that matcher +// falls back to command text when a birth time is missing, and requires the original argv when +// it is present. A terminal program is often a shell that ran `exec`, which keeps its pid and +// birth time but changes its command line; and a reused pid can run the same command line. +// Here birth time alone identifies a terminal program, and nothing without one is ever owned. + +export type ProcessOwnership = + | { status: "gone" } + | { status: "unrelated"; reason: string } + | { status: "owned" } + | { status: "unknown"; reason: string }; + +export function classifyTerminalWorkerProcess( + record: Pick, + inspection: ManagedProcessInspection, +): ProcessOwnership { + const birth = classifyBirth(record.identity.startedAt, inspection); + if (birth.status !== "owned" || inspection.status !== "alive") return birth; + const commandLine = inspection.snapshot.commandLine; + if (!commandLine) { + return { status: "unknown", reason: "command line unavailable" }; + } + if (!hasWorkerMarker(commandLine, record.recordId)) { + return { status: "unrelated", reason: "command line lacks the worker marker" }; + } + return { status: "owned" }; +} + +export function classifyTerminalProgramProcess( + entry: { startedAt: string | null }, + inspection: ManagedProcessInspection, +): ProcessOwnership { + return classifyBirth(entry.startedAt, inspection); +} + +function classifyBirth( + recordedStartedAt: string | null, + inspection: ManagedProcessInspection, +): ProcessOwnership { + if (inspection.status === "not-found") return { status: "gone" }; + if (inspection.status === "error") { + const message = + inspection.error instanceof Error ? inspection.error.message : String(inspection.error); + return { status: "unknown", reason: `inspection failed: ${message}` }; + } + const startedAt = inspection.snapshot.startedAt; + if (!recordedStartedAt || !startedAt) { + return { status: "unknown", reason: "birth time unavailable" }; + } + if (startedAt !== recordedStartedAt) { + return { status: "unrelated", reason: "pid reused by a process with another birth time" }; + } + return { status: "owned" }; +} + +function hasWorkerMarker(commandLine: string, recordId: string): boolean { + const tokens = commandLine.split(/\s+/); + for (let index = 0; index < tokens.length - 1; index += 1) { + if (tokens[index] === TERMINAL_WORKER_MARKER_ARG && tokens[index + 1] === recordId) { + return true; + } + } + return false; +} diff --git a/packages/server/src/terminal/terminal-worker-pool.ts b/packages/server/src/terminal/terminal-worker-pool.ts new file mode 100644 index 0000000000..517d34aa33 --- /dev/null +++ b/packages/server/src/terminal/terminal-worker-pool.ts @@ -0,0 +1,288 @@ +import type { TerminalActivityState } from "@getpaseo/protocol/terminal-activity"; +import type { CaptureTerminalLinesResult } from "./terminal-capture.js"; +import type { + TerminalActivityListener, + TerminalsChangedListener, + TerminalWorkspaceContributionChangedListener, +} from "./terminal-manager.js"; +import type { TerminalSession } from "./terminal.js"; +import type { WorkerCreateTerminalOptions } from "./terminal-worker-protocol.js"; +import type { DaemonTerminalManager } from "./worker-terminal-manager.js"; + +// The daemon's terminal service over up to two terminal workers: the current one, which takes +// every new terminal, and one draining a previous worker protocol, which keeps serving the +// terminals it already runs and is let go once its last one exits. With no current worker (two +// were already running), the first terminal created after one exits starts one. A worker from a +// newer Paseo +// is not driven at all: the service then refuses terminal requests with +// TerminalWorkerIncompatibleError instead of serving a partial view. + +export class TerminalWorkerIncompatibleError extends Error { + readonly code = "terminal_worker_incompatible"; + readonly paseoVersion: string; + readonly protocolVersion: unknown; + + constructor(input: { paseoVersion: string; protocolVersion: unknown }) { + super( + `Terminals are held by a newer Paseo (v${input.paseoVersion}, worker protocol ${String(input.protocolVersion)}). Update Paseo to v${input.paseoVersion} or later to use them, or run \`paseo daemon stop\` to close them.`, + ); + this.name = "TerminalWorkerIncompatibleError"; + this.paseoVersion = input.paseoVersion; + this.protocolVersion = input.protocolVersion; + } +} + +export class NoTerminalWorkerAvailableError extends Error { + constructor(message: string) { + super(message); + this.name = "NoTerminalWorkerAvailableError"; + } +} + +export interface TerminalWorkerPoolMember { + manager: DaemonTerminalManager; + workerPid: number; + /** Resolves only after confirmed worker death and its scoped cleanup. */ + exited: Promise; + /** Waits for any reconnect; false once the member is retired or stopping. */ + ready(): Promise; + stopRecovery(): void; +} + +export interface TerminalWorkerPoolOptions { + current: TerminalWorkerPoolMember | null; + draining: TerminalWorkerPoolMember[]; + /** Set when a worker from a newer Paseo holds this home's terminals. */ + incompatible: TerminalWorkerIncompatibleError | null; + /** + * Starts a current worker when there is none. Throws NoTerminalWorkerAvailableError, saying + * why, while no worker may start. + */ + startCurrent?: () => Promise; + /** Closes every terminal of every worker in the home and verifies they ended. */ + closeAll: () => Promise; + /** A draining worker's last terminal exited and the pool let it go. */ + onDrained?: (member: TerminalWorkerPoolMember) => void; +} + +export function createTerminalWorkerPool( + options: TerminalWorkerPoolOptions, +): DaemonTerminalManager { + let current = options.current; + const draining = new Set(options.draining); + const terminalsChangedListeners = new Set(); + const terminalActivityListeners = new Set(); + const contributionListeners = new Set(); + let closePromise: Promise | null = null; + let detached = false; + // One start at a time, so concurrent creates never launch two workers. + let starting: Promise | null = null; + // Registrations belong to the service and are replayed whenever a current worker starts. + const cwdEnv = new Map>(); + + function members(): TerminalWorkerPoolMember[] { + return [...(current ? [current] : []), ...draining]; + } + + function assertAvailable(): void { + if (options.incompatible) throw options.incompatible; + } + + function ownerOf(terminalId: string): DaemonTerminalManager | null { + for (const member of members()) { + if (member.manager.getTerminal(terminalId)) return member.manager; + } + return null; + } + + function routed(terminalId: string): DaemonTerminalManager { + assertAvailable(); + const owner = ownerOf(terminalId) ?? current?.manager; + if (!owner) { + throw new NoTerminalWorkerAvailableError(`Terminal ${terminalId} is not running`); + } + return owner; + } + + function releaseIfDrained(member: TerminalWorkerPoolMember): void { + if (!draining.has(member) || member.manager.listDirectories().length > 0) return; + draining.delete(member); + // With no controller and no terminals the worker exits on its own. The request that closed + // the last terminal is still waiting for its answer. + void member.manager + .detach({ afterPendingRequests: true }) + .then(() => options.onDrained?.(member)); + } + + function forwardEvents(member: TerminalWorkerPoolMember): void { + void member.exited.then(() => { + if (current === member) current = null; + return draining.delete(member); + }); + member.manager.subscribeTerminalsChanged((event) => { + for (const listener of Array.from(terminalsChangedListeners)) listener(event); + releaseIfDrained(member); + }); + member.manager.subscribeTerminalActivity((event) => { + for (const listener of Array.from(terminalActivityListeners)) listener(event); + }); + member.manager.subscribeTerminalWorkspaceContributionChanged((event) => { + for (const listener of Array.from(contributionListeners)) listener(event); + }); + } + + for (const member of members()) forwardEvents(member); + for (const member of Array.from(draining)) releaseIfDrained(member); + + async function currentManager(): Promise { + if (closePromise || detached) + throw new NoTerminalWorkerAvailableError("No terminal worker can take new terminals"); + const candidate = current; + if (candidate && (await candidate.ready())) return candidate.manager; + const startCurrent = options.startCurrent; + if (!startCurrent || closePromise || detached) { + return Promise.reject( + new NoTerminalWorkerAvailableError("No terminal worker can take new terminals"), + ); + } + starting ??= startCurrent() + .then(async (member) => { + if (closePromise || detached) { + // The service closed or let go while the worker started: it takes no terminals. + member.stopRecovery(); + await member.manager.detach(); + throw new NoTerminalWorkerAvailableError("No terminal worker can take new terminals"); + } + forwardEvents(member); + for (const [cwd, env] of cwdEnv) member.manager.registerCwdEnv({ cwd, env }); + current = member; + return member; + }) + .finally(() => { + starting = null; + }); + return starting.then((member) => member.manager); + } + + function closeTerminals(): Promise { + closePromise ??= (async () => { + for (const member of members()) member.stopRecovery(); + await starting?.catch(() => {}); + await Promise.all(members().map((member) => member.manager.detach())); + draining.clear(); + await options.closeAll(); + })(); + return closePromise; + } + + return { + getUnavailableError(): Error | null { + return options.incompatible; + }, + + async getTerminals(cwd, filter) { + assertAvailable(); + const lists = await Promise.all( + members().map((member) => member.manager.getTerminals(cwd, filter)), + ); + return lists.flat(); + }, + + async createTerminal( + createOptions: WorkerCreateTerminalOptions & { workspaceId: string }, + ): Promise { + assertAvailable(); + const manager = await currentManager(); + return manager.createTerminal(createOptions); + }, + + registerCwdEnv(registration) { + cwdEnv.set(registration.cwd, registration.env); + if (current) current.manager.registerCwdEnv(registration); + }, + + validateTerminalActivityToken(terminalId, token) { + for (const member of members()) { + const result = member.manager.validateTerminalActivityToken(terminalId, token); + if (result !== "unknown") return result; + } + return "unknown"; + }, + + getTerminal(id) { + for (const member of members()) { + const session = member.manager.getTerminal(id); + if (session) return session; + } + return undefined; + }, + + async replayTerminal(id, replayOptions, sink) { + return routed(id).replayTerminal(id, replayOptions, sink); + }, + + setTerminalTitle(id, title) { + return ownerOf(id)?.setTerminalTitle(id, title) ?? false; + }, + + async setTerminalActivity(id, state: TerminalActivityState) { + return (await ownerOf(id)?.setTerminalActivity(id, state)) ?? false; + }, + + async clearTerminalAttention(id) { + return (await ownerOf(id)?.clearTerminalAttention(id)) ?? false; + }, + + killTerminal(id) { + ownerOf(id)?.killTerminal(id); + }, + + async killTerminalAndWait(id, waitOptions) { + await routed(id).killTerminalAndWait(id, waitOptions); + }, + + async captureTerminal(id, captureOptions): Promise { + return routed(id).captureTerminal(id, captureOptions); + }, + + listDirectories() { + return [...new Set(members().flatMap((member) => member.manager.listDirectories()))]; + }, + + killAll() { + void closeTerminals().catch(() => { + // The synchronous interface cannot report it; closeTerminals() callers see the error. + }); + }, + + closeTerminals, + + async detach() { + detached = true; + for (const member of members()) member.stopRecovery(); + await starting?.catch(() => {}); + await Promise.all(members().map((member) => member.manager.detach())); + }, + + async adoptTerminals() { + const counts = await Promise.all(members().map((member) => member.manager.adoptTerminals())); + for (const member of Array.from(draining)) releaseIfDrained(member); + return counts.reduce((sum, count) => sum + count, 0); + }, + + subscribeTerminalsChanged(listener) { + terminalsChangedListeners.add(listener); + return () => terminalsChangedListeners.delete(listener); + }, + + subscribeTerminalActivity(listener) { + terminalActivityListeners.add(listener); + return () => terminalActivityListeners.delete(listener); + }, + + subscribeTerminalWorkspaceContributionChanged(listener) { + contributionListeners.add(listener); + return () => contributionListeners.delete(listener); + }, + }; +} diff --git a/packages/server/src/terminal/terminal-worker-process.ts b/packages/server/src/terminal/terminal-worker-process.ts index a70d37c5b9..855c39da59 100644 --- a/packages/server/src/terminal/terminal-worker-process.ts +++ b/packages/server/src/terminal/terminal-worker-process.ts @@ -1,352 +1,765 @@ +import { createTerminalReplayController } from "./terminal-replay.js"; +import { spawn } from "node:child_process"; +import { randomBytes, timingSafeEqual } from "node:crypto"; +import { chmodSync, closeSync, existsSync, openSync, rmSync, writeSync } from "node:fs"; +import { createServer, type Server, type Socket } from "node:net"; +import { fileURLToPath } from "node:url"; +import { currentBootId } from "../server/pid-lock.js"; +import { PRIVATE_FILE_MODE } from "../server/private-files.js"; import { createTerminalManager } from "./terminal-manager.js"; -import { captureTerminalLines } from "./terminal-capture.js"; import { TerminalOutputCoalescer } from "./terminal-output-coalescer.js"; -import type { TerminalSession, TerminalStateSnapshotOptions } from "./terminal.js"; -import type { - TerminalWorkerRequest, - TerminalWorkerStateResult, - TerminalWorkerToParentMessage, - WorkerTerminalInfo, +import type { TerminalExitInfo, LocalTerminalSession } from "./terminal.js"; +import { attachFramedSocket, type FramedSocket } from "./terminal-worker-frames.js"; +import { createTerminalWorkerProcessInspector } from "./terminal-worker-processes.js"; +import { + TERMINAL_WORKER_MARKER_ARG, + terminalWorkerLogPath, + terminalWorkerRecordPath, + writeTerminalWorkerRecord, + type TerminalWorkerRecord, +} from "./terminal-worker-record.js"; +import { createTerminalWorkerRecordPublisher } from "./terminal-worker-record-publisher.js"; +import { resolveTerminalWorkerSocketPath } from "./terminal-worker-socket-path.js"; +import { + TERMINAL_WORKER_PROTOCOL_OVERRIDE_ENV, + TERMINAL_WORKER_PROTOCOL_VERSION, + type TerminalWorkerHello, + type TerminalWorkerHelloAck, + type TerminalWorkerListResult, + type TerminalWorkerRequest, + type TerminalWorkerToParentMessage, + type WorkerTerminalInfo, } from "./terminal-worker-protocol.js"; -type TerminalCreateRequest = Extract; +// The terminal worker owns every PTY. It runs detached from the daemon (re-parented by the +// launcher below) so a daemon restart, crash or forced kill of the daemon's process tree does +// not take the terminals down, and it talks to whichever daemon controls it over an +// owner-only socket authenticated by the secret in its record. +// +// `--launch` runs the launcher: it starts the real worker detached, waits for it to listen, +// prints `{ pid, socketPath }` and exits, which leaves the worker parented to init. -const manager = createTerminalManager(); -const unsubscribeByTerminalId = new Map void>>(); -const outputCoalescerByTerminalId = new Map(); -let ipcClosing = false; +const LAUNCH_ARG = "--launch"; +const READY_TIMEOUT_MS = 15_000; +const HELLO_TIMEOUT_MS = 5_000; +// A freshly launched worker waits this long for its first controller before giving up. +const FIRST_CONTROLLER_TIMEOUT_MS = 30_000; +// While nobody controls it, the worker checks that its record still exists. A deleted record +// (a removed $PASEO_HOME) means no daemon can ever find these terminals again. +const ORPHAN_CHECK_INTERVAL_MS = 10_000; +const READY_FD = 3; -interface InFlightTerminalCreateRequest { - requestId: string; - errorReported: boolean; +interface WorkerArgs { + recordId: string; + paseoHome: string; + paseoVersion: string; + // The copy under terminal-worker/ this worker runs from; absent when it runs from source. + runtime: string | null; } -let inFlightTerminalCreateRequest: InFlightTerminalCreateRequest | null = null; - -// The conpty failure signal is process-scoped, not request-scoped. Serializing -// creates keeps an async spawn failure attributable to exactly one request. -let createTerminalQueue: Promise = Promise.resolve(); - -// node-pty completes its Windows conpty spawn asynchronously on a separate -// conout worker thread. When that spawn fails (bad cwd, missing command, etc.) -// it throws an exception there that cannot be caught at the call site and would -// otherwise crash this worker process and sever every existing terminal. -process.on("uncaughtException", (error) => { - console.error("Terminal worker uncaught exception (kept alive):", error); - reportInFlightTerminalCreateFailure(error); -}); - -function sendToParent(message: TerminalWorkerToParentMessage): void { - if (ipcClosing || !process.connected || !process.send) { - return; - } - try { - process.send(message, (error) => { - if (error) { - ipcClosing = true; - } - }); - } catch { - ipcClosing = true; +function readArg(argv: string[], name: string): string { + const index = argv.indexOf(name); + const value = index === -1 ? undefined : argv[index + 1]; + if (!value) { + throw new Error(`Terminal worker requires ${name}`); } + return value; } -function buildTerminalStateResult( - session: TerminalSession | undefined, - options?: TerminalStateSnapshotOptions, -): TerminalWorkerStateResult { - if (!session) { - return null; - } - return { ...session.getStateSnapshot(options), replayPreamble: session.getReplayPreamble() }; -} - -function toTerminalInfo(session: TerminalSession): WorkerTerminalInfo { +function parseWorkerArgs(argv: string[], recordIdArg: string): WorkerArgs { return { - id: session.id, - name: session.name, - cwd: session.cwd, - workspaceId: session.workspaceId, - ...(session.getTitle() ? { title: session.getTitle() } : {}), - activity: session.getActivity(), + recordId: readArg(argv, recordIdArg), + paseoHome: readArg(argv, "--paseo-home"), + paseoVersion: readArg(argv, "--paseo-version"), + runtime: argv.includes("--runtime") ? readArg(argv, "--runtime") : null, }; } -function terminalWorkerErrorMessage(error: unknown): string { - return error instanceof Error ? error.message : "Terminal worker request failed"; -} - -function reportInFlightTerminalCreateFailure(error: unknown): void { - if (!inFlightTerminalCreateRequest || inFlightTerminalCreateRequest.errorReported) { - return; +// The protocol version this worker reports in its record and hello. Tests override it to stand +// up older and newer workers from one build. +function reportedProtocolVersion(): number { + const override = process.env[TERMINAL_WORKER_PROTOCOL_OVERRIDE_ENV]; + if (override === undefined || override === "") return TERMINAL_WORKER_PROTOCOL_VERSION; + const parsed = Number(override); + if (!Number.isSafeInteger(parsed)) { + throw new Error(`${TERMINAL_WORKER_PROTOCOL_OVERRIDE_ENV} is not an integer: ${override}`); } - inFlightTerminalCreateRequest.errorReported = true; - sendToParent({ - type: "response", - requestId: inFlightTerminalCreateRequest.requestId, - ok: false, - error: terminalWorkerErrorMessage(error), - }); + return parsed; } -function clearTerminalSubscriptions(terminalId: string): void { - const subscriptions = unsubscribeByTerminalId.get(terminalId); - if (subscriptions) { - for (const unsubscribe of subscriptions) { +function errorMessage(error: unknown): string { + return error instanceof Error ? error.message : String(error); +} + +// --------------------------------------------------------------------------------------------- +// Launcher +// --------------------------------------------------------------------------------------------- + +function runLauncher(argv: string[]): void { + const args = parseWorkerArgs(argv, "--record-id"); + const logFd = openSync(terminalWorkerLogPath(args.paseoHome), "a", PRIVATE_FILE_MODE); + const child = spawn( + process.execPath, + [ + ...process.execArgv, + fileURLToPath(import.meta.url), + TERMINAL_WORKER_MARKER_ARG, + args.recordId, + "--paseo-home", + args.paseoHome, + "--paseo-version", + args.paseoVersion, + ...(args.runtime ? ["--runtime", args.runtime] : []), + ], + { + detached: true, + stdio: ["ignore", "ignore", logFd, "pipe"], + env: process.env, + windowsHide: true, + }, + ); + closeSync(logFd); + + let settled = false; + let buffered = ""; + const finish = (code: number, output: string) => { + if (settled) return; + settled = true; + clearTimeout(timer); + if (code !== 0 && child.exitCode === null && child.pid) { + // A worker that never reported ready must not be left behind. try { - unsubscribe(); + process.kill(child.pid, "SIGKILL"); } catch { - // no-op + // Already gone. } } - } - unsubscribeByTerminalId.delete(terminalId); - const coalescer = outputCoalescerByTerminalId.get(terminalId); - if (coalescer) { - coalescer.dispose(); - outputCoalescerByTerminalId.delete(terminalId); - } + child.unref(); + (child.stdio[READY_FD] as NodeJS.ReadableStream & { destroy(): void }).destroy(); + // Exit from the write callback: a pipe write can still be pending when process.exit runs. + (code === 0 ? process.stdout : process.stderr).write(output, () => process.exit(code)); + }; + const timer = setTimeout(() => { + finish(1, `Terminal worker did not report ready within ${READY_TIMEOUT_MS}ms\n`); + }, READY_TIMEOUT_MS); + + const readyStream = child.stdio[READY_FD] as NodeJS.ReadableStream; + readyStream.setEncoding("utf8"); + readyStream.on("data", (chunk: string) => { + buffered += chunk; + const newline = buffered.indexOf("\n"); + if (newline === -1) return; + const line = buffered.slice(0, newline); + if (line.startsWith("ready ")) { + finish(0, `${JSON.stringify({ pid: child.pid, socketPath: line.slice("ready ".length) })}\n`); + return; + } + finish(1, `${line.startsWith("error ") ? line.slice("error ".length) : line}\n`); + }); + child.once("error", (error) => finish(1, `Cannot start terminal worker: ${error.message}\n`)); + child.once("exit", (code, signal) => { + finish(1, `Terminal worker exited before it was ready (${signal ?? `code ${code}`})\n`); + }); } -function watchTerminal(session: TerminalSession): void { - clearTerminalSubscriptions(session.id); +// --------------------------------------------------------------------------------------------- +// Worker +// --------------------------------------------------------------------------------------------- - // Coalesce pty output chunks into a single IPC message per ~5ms window so a - // burst of small chunks no longer costs one process.send each. The batch - // carries the LAST chunk's revision (the highest) so downstream snapshot - // replay dedup stays correct. - let pendingOutputRevision: number | undefined; - const outputCoalescer = new TerminalOutputCoalescer({ - timers: { setTimeout, clearTimeout }, - onFlush: ({ payload }) => { - const revision = pendingOutputRevision; - pendingOutputRevision = undefined; - sendToParent({ - type: "terminalMessage", - terminalId: session.id, - message: { type: "output", data: payload.toString("utf8"), revision }, - replayPreamble: session.getReplayPreamble(), - }); - }, +type TerminalCreateRequest = Extract; + +function runWorker(argv: string[]): void { + const args = parseWorkerArgs(argv, TERMINAL_WORKER_MARKER_ARG); + const protocolVersion = reportedProtocolVersion(); + const manager = createTerminalManager(); + const inspector = createTerminalWorkerProcessInspector(); + const sessionsById = new Map(); + const unsubscribeByTerminalId = new Map void>>(); + const outputCoalescerByTerminalId = new Map(); + // A terminal is published (terminalCreated) only once its program is recorded. An exit that + // arrives before then is held here and sent after the creation, so the controller never + // receives an exit for a terminal it does not know yet. + const exitsHeldDuringCreation = new Map(); + const secret = randomBytes(32).toString("base64url"); + let record: TerminalWorkerRecord | null = null; + let server: Server | null = null; + let controller: FramedSocket | null = null; + let everControlled = false; + let exiting = false; + + interface InFlightTerminalCreateRequest { + requestId: string; + errorReported: boolean; + } + + let inFlightTerminalCreateRequest: InFlightTerminalCreateRequest | null = null; + + // The conpty failure signal is process-scoped, not request-scoped. Serializing + // creates keeps an async spawn failure attributable to exactly one request. + let createTerminalQueue: Promise = Promise.resolve(); + + // node-pty completes its Windows conpty spawn asynchronously on a separate + // conout worker thread. When that spawn fails (bad cwd, missing command, etc.) + // it throws an exception there that cannot be caught at the call site and would + // otherwise crash this worker process and sever every existing terminal. + process.on("uncaughtException", (error) => { + console.error("Terminal worker uncaught exception (kept alive):", error); + reportInFlightTerminalCreateFailure(error); }); - outputCoalescerByTerminalId.set(session.id, outputCoalescer); - const unsubscribeMessage = session.subscribe( - (message) => { + const replayController = createTerminalReplayController({ + getSession: (id) => sessionsById.get(id), + flushOutput: (id) => outputCoalescerByTerminalId.get(id)?.flush(), + }); + function sendToController(message: TerminalWorkerToParentMessage): void { + replayController.send(message); + } + + const recordPublisher = createTerminalWorkerRecordPublisher((state) => { + writeTerminalWorkerRecord(args.paseoHome, state); + }); + + async function persistRecord(): Promise { + if (!record || exiting) return; + record = { + ...record, + terminals: record.terminals.filter((entry) => sessionsById.has(entry.id)), + }; + await recordPublisher.publish(record); + } + + function removeOwnFiles(): void { + rmSync(terminalWorkerRecordPath(args.paseoHome, process.pid), { force: true }); + if (record && process.platform !== "win32") { + rmSync(record.socketPath, { force: true }); + } + } + + function exitWorker(code: number): void { + if (exiting) return; + exiting = true; + recordPublisher.stop(); + removeOwnFiles(); + server?.close(); + process.exit(code); + } + + async function killEveryTerminalAndExit(): Promise { + const sessions = Array.from(sessionsById.values()); + await Promise.all( + sessions.map((session) => + session.killAndWait().catch((error: unknown) => { + console.error(`Terminal worker could not kill terminal ${session.id}:`, error); + }), + ), + ); + exitWorker(0); + } + + function exitIfIdle(): void { + if (!controller && everControlled && sessionsById.size === 0) { + exitWorker(0); + } + } + + function terminalMetadata(session: LocalTerminalSession) { + return { ...session.getSize(), hasOutput: session.hasOutput(), title: session.getTitle() }; + } + + function toTerminalInfo(session: LocalTerminalSession): WorkerTerminalInfo { + return { + id: session.id, + name: session.name, + cwd: session.cwd, + workspaceId: session.workspaceId, + ...(session.getTitle() ? { title: session.getTitle() } : {}), + activity: session.getActivity(), + }; + } + + function terminalWorkerErrorMessage(error: unknown): string { + return error instanceof Error ? error.message : "Terminal worker request failed"; + } + + function reportInFlightTerminalCreateFailure(error: unknown): void { + if (!inFlightTerminalCreateRequest || inFlightTerminalCreateRequest.errorReported) { + return; + } + inFlightTerminalCreateRequest.errorReported = true; + sendToController({ + type: "response", + requestId: inFlightTerminalCreateRequest.requestId, + ok: false, + error: terminalWorkerErrorMessage(error), + }); + } + + function clearTerminalSubscriptions(terminalId: string): void { + const subscriptions = unsubscribeByTerminalId.get(terminalId); + if (subscriptions) { + for (const unsubscribe of subscriptions) { + try { + unsubscribe(); + } catch { + // no-op + } + } + } + unsubscribeByTerminalId.delete(terminalId); + const coalescer = outputCoalescerByTerminalId.get(terminalId); + if (coalescer) { + coalescer.dispose(); + outputCoalescerByTerminalId.delete(terminalId); + } + } + + function watchTerminal(session: LocalTerminalSession): void { + clearTerminalSubscriptions(session.id); + + // Coalesce pty output chunks into a single frame per ~5ms window so a burst of small + // chunks no longer costs one socket write each. The batch carries the LAST chunk's + // revision (the highest) so downstream snapshot replay dedup stays correct. + let pendingOutputRevision: number | undefined; + const outputCoalescer = new TerminalOutputCoalescer({ + timers: { setTimeout, clearTimeout }, + onFlush: ({ payload }) => { + const revision = pendingOutputRevision; + pendingOutputRevision = undefined; + sendToController({ + type: "terminalMessage", + terminalId: session.id, + message: { type: "output", data: payload.toString("utf8"), revision }, + replayPreamble: session.getReplayPreamble(), + }); + }, + }); + outputCoalescerByTerminalId.set(session.id, outputCoalescer); + + const unsubscribeMessage = session.subscribe((message) => { if (message.type === "output") { pendingOutputRevision = message.revision; outputCoalescer.handle(message.data); return; } - // Non-output messages (snapshot/snapshotReady/titleChange) must not jump + // Non-output messages (snapshotReady/titleChange) must not jump // ahead of buffered output: flush the coalescer first, then forward. outputCoalescer.flush(); - sendToParent({ + sendToController({ type: "terminalMessage", terminalId: session.id, message, replayPreamble: session.getReplayPreamble(), }); - }, - // Creation already sends an authoritative state in terminalCreated. A second - // asynchronous state snapshot can arrive after the create response and - // overwrite a resize issued immediately by the caller. - { initialSnapshot: "ready" }, - ); - const unsubscribeExit = session.onExit((info) => { - outputCoalescer.flush(); - clearTerminalSubscriptions(session.id); - sendToParent({ - type: "terminalExit", - terminalId: session.id, - info, }); - }); - const unsubscribeTitle = session.onTitleChange((title) => { - outputCoalescer.flush(); - sendToParent({ - type: "terminalTitleChange", - terminalId: session.id, - title, - }); - }); - const unsubscribeCommandFinished = session.onCommandFinished((info) => { - outputCoalescer.flush(); - sendToParent({ - type: "terminalCommandFinished", - terminalId: session.id, - info, - }); - }); - const unsubscribeActivity = session.onActivityChange((transition) => { - sendToParent({ - type: "terminalActivityChange", - terminalId: session.id, - activity: transition.activity, - previous: transition.previous, - }); - }); - - unsubscribeByTerminalId.set(session.id, [ - unsubscribeMessage, - unsubscribeExit, - unsubscribeTitle, - unsubscribeCommandFinished, - unsubscribeActivity, - ]); -} - -function enqueueCreateTerminalRequest(message: TerminalCreateRequest): Promise { - const nextRequest = createTerminalQueue.then(() => handleCreateTerminalRequest(message)); - createTerminalQueue = nextRequest.catch(() => {}); - return nextRequest; -} - -async function handleCreateTerminalRequest(message: TerminalCreateRequest): Promise { - const request: InFlightTerminalCreateRequest = { - requestId: message.requestId, - errorReported: false, - }; - inFlightTerminalCreateRequest = request; - try { - const { workspaceId } = message.options; - if (!workspaceId) { - throw new Error("workspaceId is required"); - } - const session = await manager.createTerminal({ ...message.options, workspaceId }); - if (request.errorReported) { - session.kill(); - return; - } - watchTerminal(session); - const initialSnapshot = session.getStateSnapshot(); - sendToParent({ - type: "terminalCreated", - terminal: toTerminalInfo(session), - state: initialSnapshot.state, - }); - sendToParent({ - type: "response", - requestId: message.requestId, - ok: true, - result: { - terminal: toTerminalInfo(session), - state: initialSnapshot.state, - }, - }); - } catch (error) { - reportInFlightTerminalCreateFailure(error); - } finally { - if (inFlightTerminalCreateRequest === request) { - inFlightTerminalCreateRequest = null; - } - } -} - -async function handleRequest(message: TerminalWorkerRequest): Promise { - switch (message.type) { - case "createTerminal": { - await enqueueCreateTerminalRequest(message); - return; - } - - case "registerCwdEnv": { - manager.registerCwdEnv({ cwd: message.cwd, env: message.env }); - sendToParent({ type: "response", requestId: message.requestId, ok: true }); - return; - } - - case "setActivity": { - await manager.setTerminalActivity(message.terminalId, message.state); - sendToParent({ type: "response", requestId: message.requestId, ok: true }); - return; - } - - case "clearAttention": { - await manager.clearTerminalAttention(message.terminalId); - sendToParent({ type: "response", requestId: message.requestId, ok: true }); - return; - } - - case "killTerminal": { - manager.killTerminal(message.terminalId); - // Removal is owned by session.onExit -> terminalExit; the parent mirror - // clears contribution and emits terminalsChanged from that single path. - clearTerminalSubscriptions(message.terminalId); - sendToParent({ type: "response", requestId: message.requestId, ok: true }); - return; - } - - case "killTerminalAndWait": { - await manager.killTerminalAndWait(message.terminalId, message.options); - clearTerminalSubscriptions(message.terminalId); - sendToParent({ type: "response", requestId: message.requestId, ok: true }); - return; - } - - case "getTerminalState": { - // Flush buffered output before snapshotting: the headless state already includes it, - // so if the coalescer emitted it afterward (in a batch carrying a revision past the - // snapshot's) the controller's revision dedup wouldn't drop it and the client would - // see the bytes twice. Flushing first sends them with a revision <= the snapshot's. - outputCoalescerByTerminalId.get(message.terminalId)?.flush(); - sendToParent({ - type: "response", - requestId: message.requestId, - ok: true, - result: buildTerminalStateResult(manager.getTerminal(message.terminalId), message.options), + const unsubscribeExit = session.onExit((info) => { + outputCoalescer.flush(); + clearTerminalSubscriptions(session.id); + sessionsById.delete(session.id); + void persistRecord().catch((error) => { + if (!exiting) console.error("Cannot publish terminal exit:", error); }); - return; - } - - case "captureTerminal": { - const session = manager.getTerminal(message.terminalId); - const result = session - ? captureTerminalLines(session, { - start: message.start, - end: message.end, - stripAnsi: message.stripAnsi, - }) - : { lines: [], totalLines: 0 }; - sendToParent({ - type: "response", - requestId: message.requestId, - ok: true, - result, - }); - return; - } - - case "killAll": { - manager.killAll(); - for (const terminalId of Array.from(unsubscribeByTerminalId.keys())) { - clearTerminalSubscriptions(terminalId); + if (exitsHeldDuringCreation.has(session.id)) { + exitsHeldDuringCreation.set(session.id, info); + return; } - sendToParent({ type: "response", requestId: message.requestId, ok: true }); + sendToController({ + type: "terminalExit", + terminalId: session.id, + info, + }); + exitIfIdle(); + }); + const unsubscribeTitle = session.onTitleChange((title) => { + outputCoalescer.flush(); + sendToController({ + type: "terminalTitleChange", + terminalId: session.id, + title, + }); + }); + const unsubscribeCommandFinished = session.onCommandFinished((info) => { + outputCoalescer.flush(); + sendToController({ + type: "terminalCommandFinished", + terminalId: session.id, + info, + }); + }); + const unsubscribeActivity = session.onActivityChange((transition) => { + sendToController({ + type: "terminalActivityChange", + terminalId: session.id, + activity: transition.activity, + previous: transition.previous, + }); + }); + + unsubscribeByTerminalId.set(session.id, [ + unsubscribeMessage, + unsubscribeExit, + unsubscribeTitle, + unsubscribeCommandFinished, + unsubscribeActivity, + ]); + } + + // A terminal enters the record only with its program's birth time, so cleanup can always + // tell the program from a later process that reuses its pid. A program that already exited + // needs no entry; one whose birth time cannot be read is killed and the create fails. + async function recordTerminalProgram(session: LocalTerminalSession): Promise { + if (session.getExitInfo()) return; + // The manager drops a session as soon as its program exits, so only a live one has a pid. + const pid = manager.getTerminalProcessId(session.id); + if (pid === null) { + throw new Error(`Terminal ${session.id} has no program pid`); + } + const inspection = await inspector.inspect(pid); + if (inspection.status === "not-found" || session.getExitInfo()) { return; } + if (inspection.status === "error" || !inspection.snapshot.startedAt) { + const reason = + inspection.status === "error" ? errorMessage(inspection.error) : "no birth time reported"; + throw new Error(`Cannot identify terminal program ${pid}: ${reason}`); + } + if (!record) { + throw new Error("Terminal worker record is not written yet"); + } + record = { + ...record, + terminals: [ + ...record.terminals.filter((entry) => entry.id !== session.id), + { id: session.id, pid, startedAt: inspection.snapshot.startedAt }, + ], + }; + await persistRecord(); + } - case "send": { - const session = manager.getTerminal(message.terminalId); - session?.send(message.message); - sendToParent({ type: "response", requestId: message.requestId, ok: true }); - return; + function enqueueCreateTerminalRequest(message: TerminalCreateRequest): Promise { + const nextRequest = createTerminalQueue.then(() => handleCreateTerminalRequest(message)); + createTerminalQueue = nextRequest.catch(() => {}); + return nextRequest; + } + + async function handleCreateTerminalRequest(message: TerminalCreateRequest): Promise { + const request: InFlightTerminalCreateRequest = { + requestId: message.requestId, + errorReported: false, + }; + inFlightTerminalCreateRequest = request; + try { + const { workspaceId } = message.options; + if (!workspaceId) { + throw new Error("workspaceId is required"); + } + const session = await manager.createTerminal({ ...message.options, workspaceId }); + if (request.errorReported) { + session.kill(); + return; + } + sessionsById.set(session.id, session); + exitsHeldDuringCreation.set(session.id, null); + watchTerminal(session); + try { + await recordTerminalProgram(session); + } catch (error) { + exitsHeldDuringCreation.delete(session.id); + clearTerminalSubscriptions(session.id); + sessionsById.delete(session.id); + await session.killAndWait().catch(() => undefined); + throw error; + } + const state = terminalMetadata(session); + sendToController({ + type: "terminalCreated", + terminal: toTerminalInfo(session), + state, + }); + // Startup output/readiness may have arrived while recording the program, + // before the daemon knew this terminal. Publish its current modes after creation. + sendToController({ + type: "terminalMessage", + terminalId: session.id, + message: { type: "snapshotReady" }, + replayPreamble: session.getReplayPreamble(), + }); + sendToController({ + type: "response", + requestId: message.requestId, + ok: true, + result: { + terminal: toTerminalInfo(session), + state, + }, + }); + const heldExit = exitsHeldDuringCreation.get(session.id); + exitsHeldDuringCreation.delete(session.id); + if (heldExit) { + sendToController({ type: "terminalExit", terminalId: session.id, info: heldExit }); + exitIfIdle(); + } + } catch (error) { + reportInFlightTerminalCreateFailure(error); + } finally { + if (inFlightTerminalCreateRequest === request) { + inFlightTerminalCreateRequest = null; + } } } + + function listTerminals(): TerminalWorkerListResult { + return Array.from(sessionsById.values()).map((session) => { + // Buffered output is already in the headless state; flushing first keeps a later + // batch from carrying bytes the snapshot already shows. + outputCoalescerByTerminalId.get(session.id)?.flush(); + return { + terminal: toTerminalInfo(session), + state: terminalMetadata(session), + activityToken: manager.getTerminalActivityToken(session.id), + replayPreamble: session.getReplayPreamble(), + }; + }); + } + + async function handleRequest(message: TerminalWorkerRequest): Promise { + switch (message.type) { + case "createTerminal": { + await enqueueCreateTerminalRequest(message); + return; + } + + case "registerCwdEnv": { + manager.registerCwdEnv({ cwd: message.cwd, env: message.env }); + sendToController({ type: "response", requestId: message.requestId, ok: true }); + return; + } + + case "setActivity": { + await manager.setTerminalActivity(message.terminalId, message.state); + sendToController({ type: "response", requestId: message.requestId, ok: true }); + return; + } + + case "clearAttention": { + await manager.clearTerminalAttention(message.terminalId); + sendToController({ type: "response", requestId: message.requestId, ok: true }); + return; + } + + case "killTerminal": { + manager.killTerminal(message.terminalId); + // Removal is owned by session.onExit -> terminalExit; the parent mirror + // clears contribution and emits terminalsChanged from that single path. + sendToController({ type: "response", requestId: message.requestId, ok: true }); + return; + } + + case "killTerminalAndWait": { + await manager.killTerminalAndWait(message.terminalId, message.options); + sendToController({ type: "response", requestId: message.requestId, ok: true }); + return; + } + + case "replayTerminal": { + await replayController.replay(message); + return; + } + + case "captureTerminal": { + const session = manager.getTerminal(message.terminalId); + const result = session + ? session.captureLines({ + start: message.start, + end: message.end, + stripAnsi: message.stripAnsi, + }) + : { lines: [], totalLines: 0 }; + sendToController({ + type: "response", + requestId: message.requestId, + ok: true, + result, + }); + return; + } + + case "listTerminals": { + sendToController({ + type: "response", + requestId: message.requestId, + ok: true, + result: listTerminals(), + }); + return; + } + + case "shutdown": { + const sessions = Array.from(sessionsById.values()); + await Promise.all(sessions.map((session) => session.killAndWait().catch(() => undefined))); + // Exit once the response frame is flushed, so the requester sees the confirmation. + const requester = controller; + if (!requester) { + exitWorker(0); + return; + } + requester.send({ type: "response", requestId: message.requestId, ok: true }, () => + exitWorker(0), + ); + return; + } + + case "send": { + const session = manager.getTerminal(message.terminalId); + session?.send(message.message); + sendToController({ type: "response", requestId: message.requestId, ok: true }); + return; + } + } + } + + function isHello(message: unknown): message is TerminalWorkerHello { + return ( + typeof message === "object" && + message !== null && + (message as { type?: unknown }).type === "hello" && + typeof (message as { secret?: unknown }).secret === "string" + ); + } + + function secretMatches(candidate: string): boolean { + const expected = Buffer.from(secret, "utf8"); + const actual = Buffer.from(candidate, "utf8"); + return expected.length === actual.length && timingSafeEqual(expected, actual); + } + + function handleConnection(socket: Socket): void { + let authenticated = false; + socket.on("error", () => { + // `close` follows; a broken controller socket only means no controller. + }); + const helloTimer = setTimeout(() => socket.destroy(), HELLO_TIMEOUT_MS); + const framed = attachFramedSocket(socket, (message) => { + if (!authenticated) { + clearTimeout(helloTimer); + if (!isHello(message) || !secretMatches(message.secret)) { + socket.destroy(); + return; + } + authenticated = true; + // One controller at a time: a new authenticated connection replaces the old one. + controller = framed; + replayController.setConnection(framed); + everControlled = true; + const ack: TerminalWorkerHelloAck = { + type: "helloAck", + pid: process.pid, + protocolVersion, + }; + framed.send(ack); + return; + } + if (framed !== controller) { + return; + } + const request = message as TerminalWorkerRequest; + void handleRequest(request).catch((error: unknown) => { + sendToController({ + type: "response", + requestId: request.requestId, + ok: false, + error: terminalWorkerErrorMessage(error), + }); + }); + }); + socket.once("close", () => { + clearTimeout(helloTimer); + if (controller === framed) { + controller = null; + replayController.setConnection(null); + exitIfIdle(); + } + }); + } + + function reportReady(line: string): void { + try { + writeSync(READY_FD, `${line}\n`); + closeSync(READY_FD); + } catch { + // Started without a launcher pipe (tests that spawn the worker directly). + } + } + + async function start(): Promise { + const socketPath = resolveTerminalWorkerSocketPath({ + paseoHome: args.paseoHome, + workerPid: process.pid, + }); + if (process.platform !== "win32") { + rmSync(socketPath, { force: true }); + } + const listening = createServer(handleConnection); + await new Promise((resolve, reject) => { + listening.once("error", reject); + listening.listen(socketPath, () => { + listening.off("error", reject); + resolve(); + }); + }); + server = listening; + if (process.platform !== "win32") { + chmodSync(socketPath, PRIVATE_FILE_MODE); + } + + const self = await inspector.inspect(process.pid); + if ( + self.status !== "alive" || + !self.snapshot.startedAt || + !self.snapshot.commandLine?.includes(args.recordId) + ) { + const reason = self.status === "error" ? errorMessage(self.error) : "no usable snapshot"; + throw new Error(`Terminal worker cannot read its own process identity: ${reason}`); + } + record = { + recordId: args.recordId, + pid: process.pid, + bootId: currentBootId(), + createdAt: new Date().toISOString(), + identity: { startedAt: self.snapshot.startedAt, commandLine: self.snapshot.commandLine }, + protocolVersion, + paseoVersion: args.paseoVersion, + socketPath, + secret, + runtime: args.runtime, + terminals: [], + }; + writeTerminalWorkerRecord(args.paseoHome, record); + reportReady(`ready ${socketPath}`); + + setTimeout(() => { + if (!everControlled && sessionsById.size === 0) exitWorker(0); + }, FIRST_CONTROLLER_TIMEOUT_MS).unref(); + setInterval(() => { + if (!controller && !existsSync(terminalWorkerRecordPath(args.paseoHome, process.pid))) { + void killEveryTerminalAndExit(); + } + }, ORPHAN_CHECK_INTERVAL_MS); + } + + process.on("SIGTERM", () => { + void killEveryTerminalAndExit(); + }); + + start().catch((error: unknown) => { + const message = errorMessage(error).replace(/\n/g, " | "); + console.error(`Terminal worker failed to start: ${errorMessage(error)}`); + reportReady(`error ${message}`); + exitWorker(1); + }); } -process.on("message", (message: TerminalWorkerRequest) => { - void handleRequest(message).catch((error: unknown) => { - sendToParent({ - type: "response", - requestId: message.requestId, - ok: false, - error: terminalWorkerErrorMessage(error), - }); - }); -}); - -process.once("disconnect", () => { - ipcClosing = true; - manager.killAll(); -}); +if (process.argv.includes(LAUNCH_ARG)) { + runLauncher(process.argv.slice(2)); +} else { + runWorker(process.argv.slice(2)); +} diff --git a/packages/server/src/terminal/terminal-worker-processes.ts b/packages/server/src/terminal/terminal-worker-processes.ts new file mode 100644 index 0000000000..b0c2e6d0cb --- /dev/null +++ b/packages/server/src/terminal/terminal-worker-processes.ts @@ -0,0 +1,185 @@ +import { readFile } from "node:fs/promises"; +import { z } from "zod"; +import { execCommand } from "../utils/spawn.js"; +import { + createSystemManagedProcessTable, + type ManagedProcessCommandRunner, + type ManagedProcessInspection, + windowsPowerShellPath, +} from "../server/managed-processes/managed-processes.js"; + +// Process inspection for terminal worker ownership. Birth times are compared as the strings +// `ps -o lstart` and Win32_Process.CreationDate print, so every reader must print them the same +// way: `ps` follows LC_TIME, and the worker, the daemon, the supervisor and the CLI can run +// under different locales. Every `ps` here runs under LC_ALL=C. + +const PS_TIMEOUT_MS = 15_000; +const POSIX_LSTART_WIDTH = 24; + +export interface ProcessTableEntry { + pid: number; + ppid: number; + startedAt: string; + // POSIX session id where `ps` reports one (Linux). macOS `ps` has no session column. + sessionId: number | null; +} + +export interface TerminalWorkerProcessInspector { + /** True where the process table names each process's session (Linux). */ + readonly reportsSessions: boolean; + inspect(pid: number): Promise; + /** One snapshot of every process, for walking descendants. Throws when it cannot be read. */ + listProcesses(): Promise; + /** + * The environment a process was started with, as NAME=value entries; null when the process + * is gone. Throws when it cannot be read. Only called where `reportsSessions` is true. + */ + readEnvironment(pid: number): Promise; +} + +const WindowsProcessListSchema = z.array( + z.object({ + ProcessId: z.number().int(), + ParentProcessId: z.number().int().nullable().optional(), + CreationDate: z.string().nullable().optional(), + }), +); + +function createLocaleNeutralCommandRunner(): ManagedProcessCommandRunner { + return { + exec: (command, args) => + execCommand(command, args, { + envMode: "internal", + envOverlay: { LC_ALL: "C" }, + timeout: PS_TIMEOUT_MS, + maxBuffer: 64 * 1024 * 1024, + }).then(({ stdout, stderr }) => ({ stdout: String(stdout), stderr: String(stderr) })), + }; +} + +export function createTerminalWorkerProcessInspector( + options: { platform?: NodeJS.Platform; commandRunner?: ManagedProcessCommandRunner } = {}, +): TerminalWorkerProcessInspector { + const platform = options.platform ?? process.platform; + const commandRunner = options.commandRunner ?? createLocaleNeutralCommandRunner(); + const table = createSystemManagedProcessTable({ platform, commandRunner }); + return { + reportsSessions: platform === "linux", + inspect: (pid) => table.inspect(pid), + listProcesses: () => + platform === "win32" + ? listWindowsProcesses(commandRunner) + : listPosixProcesses(commandRunner, platform), + readEnvironment: (pid) => readLinuxEnvironment(platform, pid), + }; +} + +async function readLinuxEnvironment( + platform: NodeJS.Platform, + pid: number, +): Promise { + if (platform !== "linux") { + throw new Error(`reading a process environment is not supported on ${platform}`); + } + let raw: string; + try { + raw = await readFile(`/proc/${pid}/environ`, "utf8"); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return null; + throw error; + } + return raw.split("\0").filter((entry) => entry.length > 0); +} + +async function listPosixProcesses( + commandRunner: ManagedProcessCommandRunner, + platform: NodeJS.Platform, +): Promise { + const withSession = platform === "linux"; + const columns = withSession + ? ["-o", "pid=", "-o", "ppid=", "-o", "sid=", "-o", "lstart="] + : ["-o", "pid=", "-o", "ppid=", "-o", "lstart="]; + const { stdout } = await commandRunner.exec("ps", ["-A", "-ww", ...columns]); + const entries: ProcessTableEntry[] = []; + const leadingInts = withSession ? 3 : 2; + for (const line of stdout.split("\n")) { + const match = line.match( + withSession ? /^\s*(\d+)\s+(\d+)\s+(\d+)\s+(.+?)\s*$/ : /^\s*(\d+)\s+(\d+)\s+(.+?)\s*$/, + ); + if (!match) continue; + const startedAt = match[leadingInts + 1].slice(0, POSIX_LSTART_WIDTH).trim(); + entries.push({ + pid: Number(match[1]), + ppid: Number(match[2]), + sessionId: withSession ? Number(match[3]) : null, + startedAt, + }); + } + if (entries.length === 0) { + throw new Error("ps returned no processes"); + } + return entries; +} + +async function listWindowsProcesses( + commandRunner: ManagedProcessCommandRunner, +): Promise { + const command = + "@(Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,CreationDate) | ConvertTo-Json -Compress"; + const { stdout } = await commandRunner.exec(windowsPowerShellPath(), [ + "-NoProfile", + "-NonInteractive", + "-Command", + command, + ]); + const parsed: unknown = JSON.parse(stdout.trim()); + const rows = WindowsProcessListSchema.parse(Array.isArray(parsed) ? parsed : [parsed]); + return rows.flatMap((row) => + row.CreationDate + ? [ + { + pid: row.ProcessId, + ppid: row.ParentProcessId ?? 0, + startedAt: row.CreationDate, + sessionId: null, + }, + ] + : [], + ); +} + +/** + * Every process below `rootPid` in the snapshot, plus (where the platform reports sessions) + * every member of the session `rootPid` led and everything below those members. A PTY program + * is a session leader, and the kernel keeps its pid reserved as the session id while any member + * lives, so the session still names a HUP-ignoring job after the shell exits and the job is + * reparented. + */ +export function collectDescendants( + snapshot: ProcessTableEntry[], + rootPid: number, +): ProcessTableEntry[] { + const childrenByParent = new Map(); + for (const entry of snapshot) { + const siblings = childrenByParent.get(entry.ppid) ?? []; + siblings.push(entry); + childrenByParent.set(entry.ppid, siblings); + } + const found = new Map(); + const queue = [rootPid]; + for (const entry of snapshot) { + if (entry.sessionId === rootPid && entry.pid !== rootPid) { + found.set(entry.pid, entry); + queue.push(entry.pid); + } + } + while (queue.length > 0) { + const parent = queue.shift()!; + for (const child of childrenByParent.get(parent) ?? []) { + if (child.pid === rootPid || found.has(child.pid)) continue; + found.set(child.pid, child); + queue.push(child.pid); + } + } + return Array.from(found.values()); +} diff --git a/packages/server/src/terminal/terminal-worker-protocol.test.ts b/packages/server/src/terminal/terminal-worker-protocol.test.ts new file mode 100644 index 0000000000..6ea9a823db --- /dev/null +++ b/packages/server/src/terminal/terminal-worker-protocol.test.ts @@ -0,0 +1,25 @@ +import { describe, expect, it } from "vitest"; +import { classifyTerminalWorkerProtocol } from "./terminal-worker-protocol.js"; + +describe("classifyTerminalWorkerProtocol", () => { + it("rejects the unreleased cell protocol without a draining adapter", () => { + expect(classifyTerminalWorkerProtocol(1, 2)).toBe("obsolete"); + expect(classifyTerminalWorkerProtocol(2, 3)).toBe("obsolete"); + expect(classifyTerminalWorkerProtocol(3, 4)).toBe("obsolete"); + expect(classifyTerminalWorkerProtocol(4, 5)).toBe("obsolete"); + }); + it.each([ + [6, "current"], + [5, "previous"], + [4, "obsolete"], + [-1, "obsolete"], + [7, "newer"], + // A version this daemon cannot read comes from a Paseo it does not know. + ["6", "newer"], + [4.5, "newer"], + [Number.NaN, "newer"], + [undefined, "newer"], + ])("a worker reporting %s to a daemon at 6 is %s", (reported, fit) => { + expect(classifyTerminalWorkerProtocol(reported, 6)).toBe(fit); + }); +}); diff --git a/packages/server/src/terminal/terminal-worker-protocol.ts b/packages/server/src/terminal/terminal-worker-protocol.ts index 5e7d1a30c0..e781543697 100644 --- a/packages/server/src/terminal/terminal-worker-protocol.ts +++ b/packages/server/src/terminal/terminal-worker-protocol.ts @@ -1,11 +1,11 @@ -import type { - TerminalExitInfo, - ServerMessage, - ClientMessage, - TerminalStateSnapshot, - TerminalStateSnapshotOptions, -} from "./terminal.js"; -import type { TerminalState } from "@getpaseo/protocol/messages"; +import type { TerminalExitInfo, ServerMessage, ClientMessage } from "./terminal.js"; +import type { TerminalReplayEvent, TerminalReplayOptions } from "./terminal-replay.js"; +export interface WorkerTerminalState { + rows: number; + cols: number; + hasOutput: boolean; + title?: string; +} import type { TerminalActivity, TerminalActivityState } from "@getpaseo/protocol/terminal-activity"; import type { CaptureTerminalLinesResult } from "./terminal-capture.js"; @@ -31,6 +31,56 @@ export interface WorkerCreateTerminalOptions { cols?: number; activityToken?: string; activityUrl?: string | null; + // The worker outlives the daemon that started it, so the controlling daemon + // sends its own environment and Paseo CLI path with every create instead of + // letting the worker reuse whatever it inherited at launch. + baseEnv?: Record; + paseoCliPath?: string | null; +} + +// Bumped when a request, response or event changes shape. The frozen envelope never changes +// across versions: the frame format, `hello`/`helloAck`, the `listTerminals` info fields, and +// `shutdown`. A daemon drives a worker of its own version, drains one a version older (no new +// terminals; it exits after its last terminal), shuts down anything older, and leaves a newer +// worker running untouched. See docs/terminal-worker.md. +export const TERMINAL_WORKER_PROTOCOL_VERSION = 5; + +// Test-only: the protocol version a worker reports, so tests can stand up older and newer +// workers from one build. +export const TERMINAL_WORKER_PROTOCOL_OVERRIDE_ENV = "PASEO_TERMINAL_WORKER_PROTOCOL_OVERRIDE"; + +/** How a daemon at `current` treats a worker reporting `reported`. */ +export type TerminalWorkerProtocolFit = "current" | "previous" | "obsolete" | "newer"; + +export function classifyTerminalWorkerProtocol( + reported: unknown, + current: number = TERMINAL_WORKER_PROTOCOL_VERSION, +): TerminalWorkerProtocolFit { + // A version this daemon cannot read comes from a Paseo it does not know: treat it as newer. + if (typeof reported !== "number" || !Number.isSafeInteger(reported)) return "newer"; + if (reported === current) return "current"; + // Protocols 1 through 4 were unreleased; they have no draining adapter. + if (reported === current - 1 && reported >= 5) return "previous"; + return reported < current ? "obsolete" : "newer"; +} + +export interface TerminalWorkerHello { + type: "hello"; + secret: string; + protocolVersion: number; +} + +export interface TerminalWorkerHelloAck { + type: "helloAck"; + pid: number; + protocolVersion: number; +} + +export interface WorkerListedTerminal { + terminal: WorkerTerminalInfo; + state: WorkerTerminalState; + activityToken: string | null; + replayPreamble: string; } export interface WorkerKillAndWaitOptions { @@ -73,10 +123,10 @@ export type TerminalWorkerRequest = options?: WorkerKillAndWaitOptions; } | { - type: "getTerminalState"; + type: "replayTerminal"; requestId: string; terminalId: string; - options?: TerminalStateSnapshotOptions; + options?: TerminalReplayOptions; } | { type: "captureTerminal"; @@ -87,7 +137,12 @@ export type TerminalWorkerRequest = stripAnsi?: boolean; } | { - type: "killAll"; + type: "listTerminals"; + requestId: string; + } + | { + // Kill every terminal (waiting for each program to exit) and exit. + type: "shutdown"; requestId: string; } | { @@ -112,10 +167,11 @@ export type TerminalWorkerResponse = }; export type TerminalWorkerEvent = + | { type: "terminalReplay"; requestId: string; event: TerminalReplayEvent } | { type: "terminalCreated"; terminal: WorkerTerminalInfo; - state: TerminalState; + state: WorkerTerminalState; } | { type: "terminalMessage"; @@ -149,7 +205,6 @@ export type TerminalWorkerEvent = export type TerminalWorkerToParentMessage = TerminalWorkerResponse | TerminalWorkerEvent; +export type TerminalWorkerListResult = WorkerListedTerminal[]; + export type TerminalWorkerCaptureResult = CaptureTerminalLinesResult; -// The worker fills TerminalStateSnapshot.replayPreamble on getTerminalState so -// the parent can cache the input-mode preamble instead of re-deriving it. -export type TerminalWorkerStateResult = TerminalStateSnapshot | null; diff --git a/packages/server/src/terminal/terminal-worker-reaper.test.ts b/packages/server/src/terminal/terminal-worker-reaper.test.ts new file mode 100644 index 0000000000..a20d571b7f --- /dev/null +++ b/packages/server/src/terminal/terminal-worker-reaper.test.ts @@ -0,0 +1,645 @@ +import { afterEach, describe, expect, it } from "vitest"; +import { execFile, spawn, type ChildProcess } from "node:child_process"; +import { chmodSync, existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { Worker } from "node:worker_threads"; +import { isPlatform } from "../test-utils/platform.js"; +import { classifyTerminalProgramProcess } from "./terminal-worker-ownership.js"; +import { currentBootId } from "../server/pid-lock.js"; +import { + createTerminalWorkerProcessInspector, + type TerminalWorkerProcessInspector, +} from "./terminal-worker-processes.js"; +import { + readUnconfirmedTerminalCleanup, + reapTerminalWorkers, + retryUnconfirmedTerminalCleanup, + TerminalCleanupNotConfirmedError, +} from "./terminal-worker-reaper.js"; +import { + readTerminalWorkerRecord, + terminalCleanupRecordPath, + terminalWorkerDirectory, + writeTerminalWorkerRecord, + type TerminalWorkerRecord, +} from "./terminal-worker-record.js"; + +// Real throwaway processes stand in for workers and terminal programs, so every signal the +// reaper sends lands on a process this test started. Nothing here uses invented pids. + +const inspector = createTerminalWorkerProcessInspector(); +const children: ChildProcess[] = []; +const extraPids: number[] = []; +const temporaryDirs: string[] = []; + +function spawnIdle( + script = "setInterval(() => {}, 1e9)", + env: NodeJS.ProcessEnv = process.env, +): ChildProcess { + const child = spawn(process.execPath, ["-e", script], { + detached: true, + stdio: ["ignore", "pipe", "ignore"], + env, + }); + children.push(child); + return child; +} + +// A program with one child of its own in a separate process group, so only the descendant walk +// (not the program's group kill) can reach it. +async function spawnProgramWithChild(): Promise<{ program: ChildProcess; childPid: number }> { + const program = spawnIdle(` + const child = require("node:child_process").spawn(process.execPath, ["-e", "setInterval(() => {}, 1e9)"], { stdio: "ignore", detached: true }); + process.stdout.write(String(child.pid) + "\\n"); + setInterval(() => {}, 1e9); + `); + const childPid = await new Promise((resolve) => { + program.stdout!.once("data", (chunk: Buffer) => resolve(Number(chunk.toString().trim()))); + }); + extraPids.push(childPid); + return { program, childPid }; +} + +async function birthOf(pid: number): Promise { + const inspection = await inspector.inspect(pid); + if (inspection.status !== "alive" || !inspection.snapshot.startedAt) { + throw new Error(`cannot read birth time of ${pid}`); + } + return inspection.snapshot.startedAt; +} + +async function goneProcessPid(): Promise { + const child = spawn(process.execPath, ["-e", ""], { stdio: "ignore" }); + await new Promise((resolve) => child.once("exit", resolve)); + return child.pid!; +} + +function isAlive(pid: number): boolean { + try { + process.kill(pid, 0); + return true; + } catch { + return false; + } +} + +async function waitUntilGone(pid: number): Promise { + const deadline = Date.now() + 5_000; + while (isAlive(pid) && Date.now() < deadline) { + await new Promise((resolve) => setTimeout(resolve, 50)); + } +} + +// A member of the terminal "t1" carries its id, as every program a terminal starts does. +function terminalEnv(terminalId: string): NodeJS.ProcessEnv { + return { ...process.env, PASEO_TERMINAL_ID: terminalId }; +} + +// A process's start environment: /proc where the real inspector reads it (Linux), `ps -E` on +// macOS, whose real inspector has no session walk and so never reads one. +function readEnvironment(pid: number): Promise { + if (process.platform === "linux") return inspector.readEnvironment(pid); + return new Promise((resolve) => { + execFile("ps", ["-E", "-ww", "-o", "command=", "-p", String(pid)], (error, stdout) => { + resolve(error ? null : stdout.trim().split(/\s+/)); + }); + }); +} + +// The real process table as a Linux `ps` would print it for one session: `memberPid` belongs to +// the session `sessionId` led, and every other process to none this test knows. macOS `ps` has +// no session column, so this is the only way to run the Linux branch here; the member is a real +// process the test started. `reusedRoot` adds a process that took the session id's pid. +function withSessionMember(input: { + memberPid: number; + sessionId: number; + reusedRoot?: boolean; + environmentUnreadable?: boolean; +}): TerminalWorkerProcessInspector { + return { + reportsSessions: true, + inspect: (pid) => inspector.inspect(pid), + listProcesses: async () => { + // A fresh snapshot each call, so it is rewritten in place. + const snapshot = await inspector.listProcesses(); + for (const entry of snapshot) { + entry.sessionId = entry.pid === input.memberPid ? input.sessionId : null; + } + if (input.reusedRoot) { + snapshot.push({ + pid: input.sessionId, + ppid: 1, + startedAt: "Fri Jan 1 00:00:00 2100", + sessionId: input.sessionId, + }); + } + return snapshot; + }, + readEnvironment: (pid) => + input.environmentUnreadable + ? Promise.reject(new Error("permission denied")) + : readEnvironment(pid), + }; +} + +// A record this process cannot open until another thread restores it, the way a worker's +// rename over its record ends a Windows sharing violation. The thread waits for `release()`, then +// restores the record while this thread is still inside the (synchronous) record read. +async function unreadableUntilReleased( + recordPath: string, +): Promise<{ release: () => void; restored: Promise }> { + chmodSync(recordPath, 0); + const signal = new Int32Array(new SharedArrayBuffer(8)); + const thread = new Worker( + ` + const { parentPort, workerData } = require("node:worker_threads"); + const signal = new Int32Array(workerData.signal); + parentPort.postMessage("ready"); + Atomics.wait(signal, 0, 0); + Atomics.wait(signal, 1, 0, 30); + require("node:fs").chmodSync(workerData.recordPath, 0o600); + `, + { eval: true, workerData: { recordPath, signal: signal.buffer } }, + ); + await new Promise((resolve) => thread.once("message", resolve)); + const restored = new Promise((resolve, reject) => { + thread.once("exit", () => resolve()); + thread.once("error", reject); + }); + return { + release: () => { + Atomics.store(signal, 0, 1); + Atomics.notify(signal, 0); + }, + restored, + }; +} + +function makeHome(): string { + const home = mkdtempSync(path.join(tmpdir(), "tw-reaper-")); + temporaryDirs.push(home); + return home; +} + +function writeRecord( + home: string, + input: Partial & Pick, +): string { + const record: TerminalWorkerRecord = { + recordId: "record-under-test", + bootId: currentBootId(), + createdAt: new Date().toISOString(), + identity: { + startedAt: "Thu Jan 1 00:00:00 1970", + commandLine: "node terminal-worker --paseo-terminal-worker record-under-test", + }, + protocolVersion: 1, + paseoVersion: "0.0.0-test", + socketPath: path.join(home, "missing.sock"), + secret: "not-a-real-secret", + terminals: [], + ...input, + }; + return writeTerminalWorkerRecord(home, record); +} + +afterEach(async () => { + for (const child of children.splice(0)) { + if (child.pid && isAlive(child.pid)) { + try { + process.kill(-child.pid, "SIGKILL"); + } catch { + child.kill("SIGKILL"); + } + } + } + for (const pid of extraPids.splice(0)) { + if (isAlive(pid)) process.kill(pid, "SIGKILL"); + } + for (const dir of temporaryDirs.splice(0)) { + rmSync(dir, { recursive: true, force: true }); + } +}); + +describe.skipIf(isPlatform("win32"))("terminal worker reaper", () => { + it("ends the programs a dead worker left, and their children, then retires the record", async () => { + const home = makeHome(); + const { program, childPid } = await spawnProgramWithChild(); + const recordPath = writeRecord(home, { + pid: await goneProcessPid(), + terminals: [{ id: "t1", pid: program.pid!, startedAt: await birthOf(program.pid!) }], + }); + + const result = await reapTerminalWorkers({ paseoHome: home, inspector }); + + await waitUntilGone(program.pid!); + await waitUntilGone(childPid); + expect(isAlive(program.pid!)).toBe(false); + expect(isAlive(childPid)).toBe(false); + expect(result.signaled).toEqual(expect.arrayContaining([program.pid!, childPid])); + expect(existsSync(recordPath)).toBe(false); + }); + + it("never signals a live process that reuses the worker pid, but still ends its programs", async () => { + const home = makeHome(); + const reusedWorkerPid = spawnIdle().pid!; + const program = spawnIdle(); + writeRecord(home, { + pid: reusedWorkerPid, + terminals: [{ id: "t1", pid: program.pid!, startedAt: await birthOf(program.pid!) }], + }); + + const result = await reapTerminalWorkers({ paseoHome: home, inspector }); + + await waitUntilGone(program.pid!); + expect(isAlive(program.pid!)).toBe(false); + expect(isAlive(reusedWorkerPid)).toBe(true); + expect(result.signaled).not.toContain(reusedWorkerPid); + }); + + it("leaves a program alive when its pid now belongs to a process with another birth time", async () => { + const home = makeHome(); + const unrelated = spawnIdle(); + const original = { id: "t1", pid: unrelated.pid!, startedAt: "Thu Jan 1 00:00:00 1970" }; + const recordPath = writeRecord(home, { + pid: await goneProcessPid(), + terminals: [original], + }); + + await reapTerminalWorkers({ paseoHome: home, inspector, gracefulMs: 0 }); + + expect(isAlive(unrelated.pid!)).toBe(true); + expect(existsSync(recordPath)).toBe(false); + expect( + classifyTerminalProgramProcess(original, await inspector.inspect(original.pid)), + ).toMatchObject({ status: "unrelated" }); + }); + + it("retires a record from an earlier boot without signaling anything it names", async () => { + const home = makeHome(); + const program = spawnIdle(); + const recordPath = writeRecord(home, { + pid: spawnIdle().pid!, + bootId: null, + createdAt: "2000-01-01T00:00:00.000Z", + terminals: [{ id: "t1", pid: program.pid!, startedAt: await birthOf(program.pid!) }], + }); + + await reapTerminalWorkers({ paseoHome: home, inspector }); + + expect(isAlive(program.pid!)).toBe(true); + expect(existsSync(recordPath)).toBe(false); + }); + + it("keeps a record of what it could not inspect and reports cleanup unconfirmed", async () => { + const home = makeHome(); + const uninspectable = spawnIdle(); + const killable = spawnIdle(); + const failing: TerminalWorkerProcessInspector = { + reportsSessions: inspector.reportsSessions, + inspect: (pid) => + pid === uninspectable.pid + ? Promise.resolve({ status: "error", error: new Error("ps unavailable") }) + : inspector.inspect(pid), + listProcesses: () => inspector.listProcesses(), + readEnvironment: (pid) => inspector.readEnvironment(pid), + }; + const workerPid = await goneProcessPid(); + const recordPath = writeRecord(home, { + pid: workerPid, + terminals: [ + { id: "t1", pid: uninspectable.pid!, startedAt: await birthOf(uninspectable.pid!) }, + { id: "t2", pid: killable.pid!, startedAt: await birthOf(killable.pid!) }, + ], + }); + + let caught: unknown; + try { + await reapTerminalWorkers({ paseoHome: home, inspector: failing, confirmMs: 500 }); + } catch (error) { + caught = error; + } + + expect(caught).toBeInstanceOf(TerminalCleanupNotConfirmedError); + expect((caught as TerminalCleanupNotConfirmedError).unresolved).toEqual([ + expect.objectContaining({ pid: uninspectable.pid, reason: "inspection failed" }), + ]); + await waitUntilGone(killable.pid!); + expect(isAlive(killable.pid!)).toBe(false); + expect(isAlive(uninspectable.pid!)).toBe(true); + // The closing state goes to the cleanup record; the worker's own record is left as it was. + const kept = await readTerminalWorkerRecord( + terminalCleanupRecordPath(home, "record-under-test"), + ); + expect(kept.pid).toBe(workerPid); + expect(kept.closing?.unresolved.length).toBeGreaterThan(0); + expect(kept.terminals.map((entry) => entry.pid)).toEqual([uninspectable.pid]); + expect((await readTerminalWorkerRecord(recordPath)).closing).toBeUndefined(); + }); + + it("ends a session member its gone terminal program left behind, where sessions are reported", async () => { + const home = makeHome(); + const member = spawnIdle(undefined, terminalEnv("t1")); + const goneProgramPid = await goneProcessPid(); + const recordPath = writeRecord(home, { + pid: await goneProcessPid(), + terminals: [{ id: "t1", pid: goneProgramPid, startedAt: await birthOf(process.pid) }], + }); + + const result = await reapTerminalWorkers({ + paseoHome: home, + inspector: withSessionMember({ memberPid: member.pid!, sessionId: goneProgramPid }), + }); + + await waitUntilGone(member.pid!); + expect(isAlive(member.pid!)).toBe(false); + expect(result.signaled).toContain(member.pid); + expect(existsSync(recordPath)).toBe(false); + }); + + it("leaves alive a later session that reuses a gone terminal program's session id", async () => { + const home = makeHome(); + // Born after the recorded program, as any member of a later session is; only the missing + // terminal id tells it apart. + const member = spawnIdle(undefined, terminalEnv("another-terminal")); + const goneProgramPid = await goneProcessPid(); + const recordPath = writeRecord(home, { + pid: await goneProcessPid(), + terminals: [{ id: "t1", pid: goneProgramPid, startedAt: "Thu Jan 1 00:00:00 1970" }], + }); + + const result = await reapTerminalWorkers({ + paseoHome: home, + inspector: withSessionMember({ memberPid: member.pid!, sessionId: goneProgramPid }), + }); + + expect(isAlive(member.pid!)).toBe(true); + expect(result.signaled).toEqual([]); + expect(existsSync(recordPath)).toBe(false); + }); + + it("signals no session member it cannot identify, and keeps the cleanup unconfirmed", async () => { + const home = makeHome(); + const member = spawnIdle(undefined, terminalEnv("t1")); + const goneProgramPid = await goneProcessPid(); + writeRecord(home, { + pid: await goneProcessPid(), + terminals: [{ id: "t1", pid: goneProgramPid, startedAt: "Thu Jan 1 00:00:00 1970" }], + }); + + await expect( + reapTerminalWorkers({ + paseoHome: home, + inspector: withSessionMember({ + memberPid: member.pid!, + sessionId: goneProgramPid, + environmentUnreadable: true, + }), + }), + ).rejects.toBeInstanceOf(TerminalCleanupNotConfirmedError); + + expect(isAlive(member.pid!)).toBe(true); + expect(await readUnconfirmedTerminalCleanup(home)).toEqual([ + expect.objectContaining({ pid: goneProgramPid, reason: "inspection failed" }), + ]); + }); + + it("signals no session member whose environment carries no terminal id, and keeps the cleanup unconfirmed", async () => { + const home = makeHome(); + // A job started with a scrubbed environment (`env -i`) carries no terminal id at all: it + // may still be this terminal's, so it is neither signaled nor dismissed as unrelated. + const member = spawnIdle(undefined, {}); + const goneProgramPid = await goneProcessPid(); + writeRecord(home, { + pid: await goneProcessPid(), + terminals: [{ id: "t1", pid: goneProgramPid, startedAt: "Thu Jan 1 00:00:00 1970" }], + }); + const scrubbedMember = withSessionMember({ memberPid: member.pid!, sessionId: goneProgramPid }); + + for (let attempt = 0; attempt < 2; attempt += 1) { + await expect( + reapTerminalWorkers({ paseoHome: home, inspector: scrubbedMember }), + ).rejects.toBeInstanceOf(TerminalCleanupNotConfirmedError); + expect(isAlive(member.pid!)).toBe(true); + expect(await readUnconfirmedTerminalCleanup(home)).toEqual([ + expect.objectContaining({ + pid: goneProgramPid, + reason: "inspection failed", + detail: expect.stringContaining(`session member ${member.pid}`), + }), + ]); + } + expect(existsSync(terminalCleanupRecordPath(home, "record-under-test"))).toBe(true); + }); + + it("does not walk a gone terminal program's pid that another process took before the table was read", async () => { + const home = makeHome(); + const member = spawnIdle(undefined, terminalEnv("t1")); + const goneProgramPid = await goneProcessPid(); + writeRecord(home, { + pid: await goneProcessPid(), + terminals: [{ id: "t1", pid: goneProgramPid, startedAt: "Thu Jan 1 00:00:00 1970" }], + }); + + const result = await reapTerminalWorkers({ + paseoHome: home, + inspector: withSessionMember({ + memberPid: member.pid!, + sessionId: goneProgramPid, + reusedRoot: true, + }), + }); + + expect(isAlive(member.pid!)).toBe(true); + expect(result.signaled).toEqual([]); + }); + + // A kill cleanup that meets an unreadable worker record cannot check what it names and + // leaves nothing else behind, so status and retry must keep reporting it after a respawn. + it.each([ + ["cleanup", (home: string) => terminalCleanupRecordPath(home, "record-under-test")], + ["worker", (home: string) => path.join(terminalWorkerDirectory(home), "4242.json")], + ])("never reports an unreadable %s record as finished", async (_kind, recordPathIn) => { + const home = makeHome(); + mkdirSync(terminalWorkerDirectory(home), { recursive: true }); + const unreadablePath = recordPathIn(home); + writeFileSync(unreadablePath, "{ not json"); + + for (const attempt of [ + async () => await readUnconfirmedTerminalCleanup(home), + () => retryUnconfirmedTerminalCleanup(home), + () => reapTerminalWorkers({ paseoHome: home, inspector }), + ]) { + let caught: unknown; + try { + await attempt(); + } catch (error) { + caught = error; + } + expect(caught).toBeInstanceOf(TerminalCleanupNotConfirmedError); + expect((caught as TerminalCleanupNotConfirmedError).unreadableRecords).toEqual([ + expect.objectContaining({ path: unreadablePath }), + ]); + } + expect(existsSync(unreadablePath)).toBe(true); + }); + + it("signals nothing while the process table cannot be read, so a retry still ends the children", async () => { + const home = makeHome(); + const { program, childPid } = await spawnProgramWithChild(); + const recordPath = writeRecord(home, { + pid: await goneProcessPid(), + terminals: [{ id: "t1", pid: program.pid!, startedAt: await birthOf(program.pid!) }], + }); + const tableUnavailable: TerminalWorkerProcessInspector = { + reportsSessions: inspector.reportsSessions, + inspect: (pid) => inspector.inspect(pid), + listProcesses: () => Promise.reject(new Error("ps timed out")), + readEnvironment: (pid) => inspector.readEnvironment(pid), + }; + + await expect( + reapTerminalWorkers({ paseoHome: home, inspector: tableUnavailable }), + ).rejects.toBeInstanceOf(TerminalCleanupNotConfirmedError); + + expect(isAlive(program.pid!)).toBe(true); + expect(isAlive(childPid)).toBe(true); + const kept = await readTerminalWorkerRecord( + terminalCleanupRecordPath(home, "record-under-test"), + ); + expect(kept.closing?.unresolved.length).toBeGreaterThan(0); + expect(kept.terminals.map((entry) => entry.pid)).toEqual([program.pid]); + + const retry = await reapTerminalWorkers({ paseoHome: home, inspector, gracefulMs: 0 }); + + await waitUntilGone(program.pid!); + await waitUntilGone(childPid); + expect(isAlive(program.pid!)).toBe(false); + expect(isAlive(childPid)).toBe(false); + expect(retry.signaled).toEqual(expect.arrayContaining([program.pid!, childPid])); + expect(existsSync(recordPath)).toBe(false); + expect(existsSync(terminalCleanupRecordPath(home, "record-under-test"))).toBe(false); + }); + + it("escalates to SIGKILL a program that ignores SIGHUP and SIGTERM", async () => { + const home = makeHome(); + const stubborn = spawnIdle(` + process.on("SIGHUP", () => {}); + process.on("SIGTERM", () => {}); + setInterval(() => {}, 1e9); + `); + writeRecord(home, { + pid: await goneProcessPid(), + terminals: [{ id: "t1", pid: stubborn.pid!, startedAt: await birthOf(stubborn.pid!) }], + }); + + await reapTerminalWorkers({ paseoHome: home, inspector }); + + await waitUntilGone(stubborn.pid!); + expect(isAlive(stubborn.pid!)).toBe(false); + }); + + it.skipIf(process.getuid?.() === 0)( + "keeps the daemon event loop responsive while status retries an unreadable record", + async () => { + const home = makeHome(); + const recordPath = writeRecord(home, { pid: process.pid }); + chmodSync(recordPath, 0); + let serviced = false; + setImmediate(() => { + serviced = true; + }); + try { + await expect( + Promise.resolve().then(() => readUnconfirmedTerminalCleanup(home)), + ).rejects.toBeInstanceOf(TerminalCleanupNotConfirmedError); + expect(serviced).toBe(true); + } finally { + chmodSync(recordPath, 0o600); + } + }, + ); + + // chmod cannot make a file unreadable to root. + describe.skipIf(process.getuid?.() === 0)("a record that cannot be opened for a moment", () => { + it("still ends a live worker it names, then retires the record", async () => { + const home = makeHome(); + const worker = spawn( + process.execPath, + ["-e", "setInterval(() => {}, 1e9)", "--", "--paseo-terminal-worker", "record-under-test"], + { detached: true, stdio: "ignore" }, + ); + children.push(worker); + const recordPath = writeRecord(home, { + pid: worker.pid!, + identity: { + startedAt: await birthOf(worker.pid!), + commandLine: "node -e --paseo-terminal-worker record-under-test", + }, + }); + const record = await unreadableUntilReleased(recordPath); + + record.release(); + const result = await reapTerminalWorkers({ paseoHome: home, inspector, gracefulMs: 0 }); + await record.restored; + + await waitUntilGone(worker.pid!); + expect(isAlive(worker.pid!)).toBe(false); + expect(result.signaled).toContain(worker.pid!); + expect(existsSync(recordPath)).toBe(false); + }); + + it("confirms the cleanup of a worker that already exited, then retires the record", async () => { + const home = makeHome(); + const program = spawnIdle(); + const recordPath = writeRecord(home, { + pid: await goneProcessPid(), + terminals: [{ id: "t1", pid: program.pid!, startedAt: await birthOf(program.pid!) }], + }); + const record = await unreadableUntilReleased(recordPath); + + record.release(); + const result = await reapTerminalWorkers({ paseoHome: home, inspector, gracefulMs: 0 }); + await record.restored; + + await waitUntilGone(program.pid!); + expect(isAlive(program.pid!)).toBe(false); + expect(result.retired).toBe(1); + expect(existsSync(recordPath)).toBe(false); + }); + + it("still reports a record that stays unreadable, and signals nothing it names", async () => { + const home = makeHome(); + const worker = spawn( + process.execPath, + ["-e", "setInterval(() => {}, 1e9)", "--", "--paseo-terminal-worker", "record-under-test"], + { detached: true, stdio: "ignore" }, + ); + children.push(worker); + const recordPath = writeRecord(home, { + pid: worker.pid!, + identity: { + startedAt: await birthOf(worker.pid!), + commandLine: "node -e --paseo-terminal-worker record-under-test", + }, + }); + chmodSync(recordPath, 0); + + let caught: unknown; + try { + await reapTerminalWorkers({ paseoHome: home, inspector, gracefulMs: 0 }); + } catch (error) { + caught = error; + } + + expect(caught).toBeInstanceOf(TerminalCleanupNotConfirmedError); + expect((caught as TerminalCleanupNotConfirmedError).unreadableRecords).toEqual([ + expect.objectContaining({ path: recordPath, error: expect.stringContaining("EACCES") }), + ]); + expect(isAlive(worker.pid!)).toBe(true); + chmodSync(recordPath, 0o600); + expect(existsSync(recordPath)).toBe(true); + }); + }); +}); diff --git a/packages/server/src/terminal/terminal-worker-reaper.ts b/packages/server/src/terminal/terminal-worker-reaper.ts new file mode 100644 index 0000000000..2647d4b25e --- /dev/null +++ b/packages/server/src/terminal/terminal-worker-reaper.ts @@ -0,0 +1,642 @@ +import { randomUUID } from "node:crypto"; +import { setTimeout as delay } from "node:timers/promises"; +import treeKill from "tree-kill"; +import { writtenDuringThisBoot } from "../server/pid-lock.js"; +import { connectTerminalWorker } from "./terminal-worker-client.js"; +import { pruneTerminalWorkerRuntimes } from "./terminal-worker-runtime.js"; +import { + classifyTerminalProgramProcess, + classifyTerminalWorkerProcess, + type ProcessOwnership, +} from "./terminal-worker-ownership.js"; +import { + collectDescendants, + createTerminalWorkerProcessInspector, + type ProcessTableEntry, + type TerminalWorkerProcessInspector, +} from "./terminal-worker-processes.js"; +import { + listTerminalWorkerRecords, + retireTerminalWorkerRecord, + terminalCleanupRecordPath, + writeTerminalCleanupRecord, + type TerminalCleanupUnresolved, + type TerminalWorkerRecord, + type TerminalWorkerRecordFile, + type TerminalWorkerTerminalEntry, +} from "./terminal-worker-record.js"; + +// The one kill path for terminal workers outside a connected daemon, and the one the daemon +// uses for its own kill stop. Every kill intent (stop, quit, --force, a kill restart whose +// shutdown hung, a dead or stopped worker, a program that ignores HUP) ends here: +// +// 1. Classify the worker and every terminal program of each record on its own, by birth time. +// A record from an earlier boot names only processes the reboot ended: retire it unsignaled. +// Descendants of owned programs (and, on Linux, members of their sessions) join the +// candidates from one process-table snapshot taken before anything is signaled. Once a +// program is gone, its session id can belong to a later session, so a member of a gone +// program's session joins only when its environment carries that terminal's id. When the +// table cannot be read, nothing in the record is signaled: ending a program would reparent +// the children only the table can find, and a retry could never reach them again. +// 2. An owned worker gets an authenticated `shutdown`: it kills each terminal and waits for it. +// 3. After `gracefulMs`, SIGKILL whatever owned process is left, re-inspecting right before +// each signal. +// 4. Succeed only when every candidate is gone or proven unrelated. Otherwise keep a record of +// the unresolved entries, marked closing, in a cleanup record no worker rewrites, and throw +// TerminalCleanupNotConfirmedError. An unreadable record is never reported confirmed. + +const DEFAULT_GRACEFUL_MS = 5_000; +const DEFAULT_CONFIRM_MS = 3_000; +const POLL_INTERVAL_MS = 100; + +export interface UnresolvedTerminalProcess extends TerminalCleanupUnresolved { + recordPath: string; +} + +// What a cleanup could not confirm, as a caller reports it: read here, or from the daemon +// status of a host the caller cannot read itself. +export interface UnconfirmedTerminalProcess { + pid: number; + role: string; + reason: string; + detail: string; +} + +export interface UnreadableTerminalWorkerRecord { + path: string; + error: string; +} + +export class TerminalCleanupNotConfirmedError extends Error { + readonly code = "TERMINAL_CLEANUP_NOT_CONFIRMED"; + readonly unresolved: UnconfirmedTerminalProcess[]; + readonly unreadableRecords: UnreadableTerminalWorkerRecord[]; + + constructor( + unresolved: UnconfirmedTerminalProcess[], + unreadableRecords: UnreadableTerminalWorkerRecord[] = [], + ) { + super( + [ + "Terminal cleanup was not confirmed.", + ...(unresolved.length > 0 + ? [ + "These processes may still be running:", + ...unresolved.map( + (entry) => ` pid ${entry.pid} (${entry.role}): ${entry.reason} (${entry.detail})`, + ), + "Their record is kept; the next `paseo daemon stop` retries the cleanup.", + ] + : []), + ...(unreadableRecords.length > 0 + ? [ + "These records cannot be read, so the processes they name cannot be checked:", + ...unreadableRecords.map((entry) => ` ${entry.path}: ${entry.error}`), + "Repair or remove each once you have checked its processes are gone.", + ] + : []), + ].join("\n"), + ); + this.name = "TerminalCleanupNotConfirmedError"; + this.unresolved = unresolved; + this.unreadableRecords = unreadableRecords; + } +} + +/** + * Retries the cleanup an earlier kill could not confirm (records marked closing), leaving any + * live worker a daemon controls alone. Throws TerminalCleanupNotConfirmedError when processes + * still survive, or when a record cannot be read, so a kill restart can report them. + */ +export async function retryUnconfirmedTerminalCleanup(paseoHome: string): Promise { + const files = await listTerminalWorkerRecords(paseoHome); + const recordPaths = files.flatMap((file) => + ("record" in file && file.record.closing) || "error" in file ? [file.path] : [], + ); + if (recordPaths.length === 0) return; + await reapTerminalWorkers({ paseoHome, gracefulMs: 0, recordPaths }); +} + +/** + * What the last cleanup of this home could not confirm gone, as its closing records name it. + * Read without retrying, so a daemon can report it (daemon status) to clients that cannot read + * this home themselves. Throws TerminalCleanupNotConfirmedError when any record cannot be read, + * worker records included: a kill cleanup that met it could not check what it names, and a + * failed cleanup leaves nothing else behind, so the cleanup cannot be reported finished. + */ +export async function readUnconfirmedTerminalCleanup( + paseoHome: string, +): Promise { + const files = await listTerminalWorkerRecords(paseoHome); + const unresolved = files.flatMap((file) => + "record" in file && file.record.closing + ? file.record.closing.unresolved.map((entry) => ({ ...entry, recordPath: file.path })) + : [], + ); + const unreadable = files.flatMap((file) => + "error" in file ? [{ path: file.path, error: file.error.message }] : [], + ); + if (unreadable.length > 0) { + throw new TerminalCleanupNotConfirmedError(unresolved, unreadable); + } + return unresolved; +} + +export interface TerminalWorkerReapResult { + records: number; + retired: number; + signaled: number[]; +} + +export interface ReapTerminalWorkersOptions { + paseoHome: string; + /** Time the worker gets to close its terminals before SIGKILL. 0 skips the shutdown request. */ + gracefulMs?: number; + confirmMs?: number; + /** Limit cleanup to these record files. Defaults to every record in the home. */ + recordPaths?: string[]; + inspector?: TerminalWorkerProcessInspector; + log?: (message: string, fields?: Record) => void; +} + +interface Candidate { + pid: number; + startedAt: string; + role: UnresolvedTerminalProcess["role"]; + terminalId: string; + state: ProcessOwnership; + // Set when this program's children could not be looked up: its cleanup is never reported + // confirmed, even once the program itself is gone, and its entry stays for the retry. + descendantsUnconfirmed: string | null; +} + +interface CandidateDiscovery { + candidates: Candidate[]; + // The process table could not be read, so no process of the record may be signaled yet. + tableError: string | null; +} + +export async function reapTerminalWorkers( + options: ReapTerminalWorkersOptions, +): Promise { + const inspector = options.inspector ?? createTerminalWorkerProcessInspector(); + const gracefulMs = options.gracefulMs ?? DEFAULT_GRACEFUL_MS; + const confirmMs = options.confirmMs ?? DEFAULT_CONFIRM_MS; + const log = options.log ?? (() => {}); + const wanted = options.recordPaths ? new Set(options.recordPaths) : null; + const result: TerminalWorkerReapResult = { records: 0, retired: 0, signaled: [] }; + const unresolved: UnresolvedTerminalProcess[] = []; + const unreadable: UnreadableTerminalWorkerRecord[] = []; + + for (const file of await listTerminalWorkerRecords(options.paseoHome)) { + if (wanted && !wanted.has(file.path)) continue; + result.records += 1; + if ("error" in file) { + // Nothing in an unreadable record can identify a process, so nothing may be signaled, + // and nothing it names can be confirmed gone. + log("Skipping unreadable terminal worker record", { + recordPath: file.path, + error: file.error.message, + }); + unreadable.push({ path: file.path, error: file.error.message }); + continue; + } + const outcome = await reapRecord({ + paseoHome: options.paseoHome, + file, + inspector, + gracefulMs, + confirmMs, + log, + }); + result.signaled.push(...outcome.signaled); + if (outcome.unresolved.length === 0) { + result.retired += 1; + } else { + unresolved.push(...outcome.unresolved); + } + } + + // Copies of worker files no remaining record names belong to no worker now. + const pruned = await pruneTerminalWorkerRuntimes(options.paseoHome); + for (const failure of pruned.failed) { + log("Cannot remove a terminal worker copy; the next cleanup retries", failure); + } + + if (unresolved.length > 0 || unreadable.length > 0) { + throw new TerminalCleanupNotConfirmedError(unresolved, unreadable); + } + return result; +} + +type ReadableRecordFile = Extract; + +interface ReapRecordInput { + paseoHome: string; + file: ReadableRecordFile; + inspector: TerminalWorkerProcessInspector; + gracefulMs: number; + confirmMs: number; + log: NonNullable; +} + +async function reapRecord( + input: ReapRecordInput, +): Promise<{ signaled: number[]; unresolved: UnresolvedTerminalProcess[] }> { + const { file, inspector, log } = input; + const { record } = file; + const recordPath = file.path; + if (!writtenDuringThisBoot({ startedAt: record.createdAt, bootId: record.bootId })) { + await retireTerminalWorkerRecord(file); + log("Retired terminal worker record from an earlier boot", { recordPath }); + return { signaled: [], unresolved: [] }; + } + + const worker = classifyTerminalWorkerProcess(record, await inspector.inspect(record.pid)); + const discovery = await collectCandidates(record, inspector, log); + const tracked: TrackedProcesses = { + record, + inspector, + worker, + candidates: discovery.candidates, + }; + + if (discovery.tableError !== null) { + return await keepUnresolved(input, tracked, [], `not signaled: ${discovery.tableError}`); + } + + if (tracked.worker.status === "owned" && input.gracefulMs > 0) { + await requestWorkerShutdown(record, input.gracefulMs, log); + } + await waitUntilSettled( + tracked, + Date.now() + (tracked.worker.status === "owned" ? input.gracefulMs : 0), + ); + + let signaled: number[] = []; + if (!isSettled(tracked)) { + signaled = await forceKillOwned(tracked, recordPath, log); + await waitUntilSettled(tracked, Date.now() + input.confirmMs); + } + + return await keepUnresolved(input, tracked, signaled, null); +} + +// Retires the record when every process it names is settled; otherwise writes the cleanup +// record, marked closing, with only the unresolved entries. A live worker keeps rewriting its +// own record, so the closing state never goes there. `notSignaled` explains open processes that +// were deliberately left alone. +async function keepUnresolved( + input: Pick, + tracked: TrackedProcesses, + signaled: number[], + notSignaled: string | null, +): Promise<{ signaled: number[]; unresolved: UnresolvedTerminalProcess[] }> { + const { record } = tracked; + const { file, log } = input; + const recordPath = terminalCleanupRecordPath(input.paseoHome, record.recordId); + const { unresolved, remaining } = collectUnresolved(tracked, recordPath, notSignaled); + if (unresolved.length === 0) { + await retireTerminalWorkerRecord(file); + log("Terminal worker record cleaned up", { recordPath: file.path, signaled }); + return { signaled, unresolved }; + } + await writeTerminalCleanupRecord(input.paseoHome, { + ...record, + terminals: remaining, + closing: { + unresolved: unresolved.map(({ pid, role, reason, detail }) => ({ + pid, + role, + reason, + detail, + })), + }, + }); + log("Terminal worker cleanup not confirmed; record kept", { + recordPath, + unresolved: unresolved.map((entry) => ({ pid: entry.pid, reason: entry.reason })), + }); + return { signaled, unresolved }; +} + +interface TrackedProcesses { + record: TerminalWorkerRecord; + inspector: TerminalWorkerProcessInspector; + worker: ProcessOwnership; + candidates: Candidate[]; +} + +function isOpen(state: ProcessOwnership): boolean { + return state.status === "owned" || state.status === "unknown"; +} + +function isSettled(tracked: TrackedProcesses): boolean { + return !isOpen(tracked.worker) && tracked.candidates.every((c) => !isOpen(c.state)); +} + +async function refreshTracked(tracked: TrackedProcesses): Promise { + if (isOpen(tracked.worker)) { + tracked.worker = classifyTerminalWorkerProcess( + tracked.record, + await tracked.inspector.inspect(tracked.record.pid), + ); + } + for (const candidate of tracked.candidates) { + if (isOpen(candidate.state)) { + candidate.state = classifyTerminalProgramProcess( + candidate, + await tracked.inspector.inspect(candidate.pid), + ); + } + } +} + +async function waitUntilSettled(tracked: TrackedProcesses, deadline: number): Promise { + await refreshTracked(tracked); + while (!isSettled(tracked) && Date.now() < deadline) { + await delay(POLL_INTERVAL_MS); + await refreshTracked(tracked); + } +} + +// SIGKILL every process still owned, re-inspecting each right before its signal. +async function forceKillOwned( + tracked: TrackedProcesses, + recordPath: string, + log: NonNullable, +): Promise { + const { record, inspector } = tracked; + const signaled: number[] = []; + if (tracked.worker.status === "owned") { + tracked.worker = classifyTerminalWorkerProcess(record, await inspector.inspect(record.pid)); + if (tracked.worker.status === "owned") { + await forceKillWorker(record.pid); + signaled.push(record.pid); + log("Force-killed terminal worker", { pid: record.pid, recordPath }); + } + } + for (const candidate of tracked.candidates) { + if (candidate.state.status !== "owned") continue; + candidate.state = classifyTerminalProgramProcess( + candidate, + await inspector.inspect(candidate.pid), + ); + if (candidate.state.status !== "owned") continue; + forceKillProgram(candidate.pid); + signaled.push(candidate.pid); + log("Force-killed terminal program", { + pid: candidate.pid, + terminalId: candidate.terminalId, + recordPath, + }); + } + return signaled; +} + +function collectUnresolved( + tracked: TrackedProcesses, + recordPath: string, + notSignaled: string | null, +): { unresolved: UnresolvedTerminalProcess[]; remaining: TerminalWorkerTerminalEntry[] } { + const unresolved: UnresolvedTerminalProcess[] = []; + if (isOpen(tracked.worker)) { + unresolved.push( + describeUnresolved({ + pid: tracked.record.pid, + role: "worker", + state: tracked.worker, + recordPath, + notSignaled, + }), + ); + } + const remaining: TerminalWorkerTerminalEntry[] = []; + for (const candidate of tracked.candidates) { + const stillOpen = isOpen(candidate.state); + if (!stillOpen && candidate.descendantsUnconfirmed === null) continue; + unresolved.push( + stillOpen + ? describeUnresolved({ + pid: candidate.pid, + role: candidate.role, + state: candidate.state, + recordPath, + notSignaled, + }) + : { + pid: candidate.pid, + role: candidate.role, + reason: "inspection failed", + detail: candidate.descendantsUnconfirmed!, + recordPath, + }, + ); + remaining.push({ + id: candidate.terminalId, + pid: candidate.pid, + startedAt: candidate.startedAt, + }); + } + return { unresolved, remaining }; +} + +async function collectCandidates( + record: TerminalWorkerRecord, + inspector: TerminalWorkerProcessInspector, + log: NonNullable, +): Promise { + const candidates = new Map(); + for (const entry of record.terminals) { + candidates.set(entry.pid, { + pid: entry.pid, + startedAt: entry.startedAt, + role: "terminal program", + terminalId: entry.id, + state: classifyTerminalProgramProcess(entry, await inspector.inspect(entry.pid)), + descendantsUnconfirmed: null, + }); + } + // Owned programs are walked through the table. Where sessions are reported, so are programs + // already gone: the kernel keeps a session id reserved while a member lives, so a job the + // shell left behind is still found. A pid reused by another process (unrelated) leads someone + // else's session and is never walked. + const roots = Array.from(candidates.values()).filter( + (c) => c.state.status === "owned" || (c.state.status === "gone" && inspector.reportsSessions), + ); + if (roots.length === 0) return { candidates: Array.from(candidates.values()), tableError: null }; + + let snapshot: ProcessTableEntry[]; + try { + snapshot = await inspector.listProcesses(); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + log("Cannot list processes for terminal cleanup", { error: message }); + for (const root of roots) { + root.descendantsUnconfirmed = `its child processes could not be listed: ${message}`; + } + return { + candidates: Array.from(candidates.values()), + tableError: `process table unavailable: ${message}`, + }; + } + for (const root of roots) { + const inTable = snapshot.find((entry) => entry.pid === root.pid); + if (inTable && inTable.startedAt !== root.startedAt) { + // The program ended and its pid was reused before the snapshot: what is below that pid + // now belongs to someone else, and the old session ended with every member of it. + log("Not walking a terminal program pid reused before the process table was read", { + pid: root.pid, + terminalId: root.terminalId, + }); + continue; + } + if (!inTable && !inspector.reportsSessions) continue; + // Below a live program its parent links prove ownership. Once it is gone, its session id + // may have been reused by a later session, so each member must carry the terminal's id. + const rootGone = !inTable; + for (const descendant of collectDescendants(snapshot, root.pid)) { + if (candidates.has(descendant.pid)) continue; + if (rootGone) { + const proof = await proveTerminalMember(inspector, descendant.pid, root.terminalId); + if (proof.status === "gone") continue; + if (proof.status === "unknown") { + root.descendantsUnconfirmed = `session member ${descendant.pid} cannot be identified: ${proof.reason}`; + continue; + } + if (proof.status === "unrelated") { + log("Ignoring a session member that does not carry its terminal's id", { + pid: descendant.pid, + terminalId: root.terminalId, + }); + continue; + } + } + candidates.set(descendant.pid, { + pid: descendant.pid, + startedAt: descendant.startedAt, + role: "terminal program", + terminalId: root.terminalId, + state: { status: "owned" }, + descendantsUnconfirmed: null, + }); + } + } + return { candidates: Array.from(candidates.values()), tableError: null }; +} + +// A terminal's programs inherit PASEO_TERMINAL_ID (terminal-manager.ts) from its PTY program. +// A process in a later session that happens to reuse the session id does not carry it. +async function proveTerminalMember( + inspector: TerminalWorkerProcessInspector, + pid: number, + terminalId: string, +): Promise { + let environment: string[] | null; + try { + environment = await inspector.readEnvironment(pid); + } catch (error) { + return { + status: "unknown", + reason: `environment unreadable: ${error instanceof Error ? error.message : String(error)}`, + }; + } + if (environment === null) return { status: "gone" }; + if (environment.includes(`PASEO_TERMINAL_ID=${terminalId}`)) return { status: "owned" }; + // Another terminal's id proves the process belongs elsewhere. No id at all proves nothing: a + // job started with a scrubbed environment (`env -i`) can still be this terminal's. + return environment.some((entry) => entry.startsWith("PASEO_TERMINAL_ID=")) + ? { status: "unrelated", reason: "environment carries another terminal's id" } + : { status: "unknown", reason: "its environment carries no terminal id" }; +} + +async function requestWorkerShutdown( + record: TerminalWorkerRecord, + gracefulMs: number, + log: NonNullable, +): Promise { + const deadline = Date.now() + gracefulMs; + let connection; + try { + connection = await connectTerminalWorker({ + socketPath: record.socketPath, + secret: record.secret, + timeoutMs: Math.min(gracefulMs, 2_000), + }); + } catch (error) { + // A worker that cannot be reached is escalated by birth time below; a failed connection + // alone never authorizes a signal. + log("Terminal worker did not accept a shutdown request", { + pid: record.pid, + error: error instanceof Error ? error.message : String(error), + }); + return; + } + const responded = new Promise((resolve) => { + connection.on("message", (message) => { + if (message.type === "response") resolve(); + }); + }); + const closed = new Promise((resolve) => connection.on("close", () => resolve())); + const sendFailed = new Promise((resolve) => { + connection.send({ type: "shutdown", requestId: randomUUID() }, (error) => { + if (error) resolve(); + }); + }); + const timeout = new AbortController(); + await Promise.race([ + responded, + closed, + sendFailed, + delay(Math.max(0, deadline - Date.now()), undefined, { signal: timeout.signal }).catch( + () => undefined, + ), + ]); + timeout.abort(); + connection.disconnect(); +} + +function forceKillWorker(pid: number): Promise { + if (process.platform === "win32") { + return new Promise((resolve) => { + treeKill(pid, "SIGKILL", () => resolve()); + }); + } + signalIgnoringMissing(pid, "SIGKILL"); + return Promise.resolve(); +} + +function forceKillProgram(pid: number): void { + if (process.platform !== "win32") { + // A PTY program leads its own session and process group. The group cannot outlive its + // leader's pid while any member is alive, so it holds nothing but this program's job. + signalIgnoringMissing(-pid, "SIGKILL"); + } + signalIgnoringMissing(pid, "SIGKILL"); +} + +function signalIgnoringMissing(pid: number, signal: NodeJS.Signals): void { + try { + process.kill(pid, signal); + } catch (error) { + const code = (error as NodeJS.ErrnoException).code; + if (code !== "ESRCH" && code !== "EPERM") throw error; + } +} + +function describeUnresolved(input: { + pid: number; + role: UnresolvedTerminalProcess["role"]; + state: ProcessOwnership; + recordPath: string; + notSignaled: string | null; +}): UnresolvedTerminalProcess { + const { pid, role, state, recordPath, notSignaled } = input; + if (state.status === "unknown") { + return { pid, role, reason: "inspection failed", detail: state.reason, recordPath }; + } + if (notSignaled !== null) { + return { pid, role, reason: "inspection failed", detail: notSignaled, recordPath }; + } + return { pid, role, reason: "still alive", detail: "survived SIGKILL", recordPath }; +} diff --git a/packages/server/src/terminal/terminal-worker-record-publisher.test.ts b/packages/server/src/terminal/terminal-worker-record-publisher.test.ts new file mode 100644 index 0000000000..dba50b9efe --- /dev/null +++ b/packages/server/src/terminal/terminal-worker-record-publisher.test.ts @@ -0,0 +1,70 @@ +import { describe, expect, it } from "vitest"; +import { setTimeout as delay } from "node:timers/promises"; +import { createTerminalWorkerRecordPublisher } from "./terminal-worker-record-publisher.js"; +import type { TerminalWorkerRecord } from "./terminal-worker-record.js"; + +const record: TerminalWorkerRecord = { + recordId: "worker", + pid: 123, + bootId: null, + createdAt: "now", + identity: { startedAt: "now", commandLine: "worker" }, + protocolVersion: 1, + paseoVersion: "test", + socketPath: "socket", + secret: "secret", + terminals: [{ id: "terminal", pid: 124, startedAt: "now" }], +}; + +describe("live worker record publication", () => { + it.each(["EPERM", "EBUSY", "EACCES"])( + "publishes the latest state after %s contention clears", + async (code) => { + let locked = true; + const written: TerminalWorkerRecord[] = []; + const publisher = createTerminalWorkerRecordPublisher((state) => { + if (locked) throw Object.assign(new Error("reader holds record"), { code }); + written.push(state); + }); + try { + const creation = publisher.publish(record); + const exited = { ...record, terminals: [] }; + const exit = publisher.publish(exited); + expect(written).toEqual([]); + locked = false; + await Promise.all([creation, exit]); + expect(written).toEqual([exited]); + } finally { + publisher.stop(); + } + }, + ); + + it("does not recreate a retired record when a reader releases it", async () => { + let locked = true; + const written: TerminalWorkerRecord[] = []; + const publisher = createTerminalWorkerRecordPublisher((state) => { + if (locked) + throw Object.assign(new Error("reader holds record"), { + code: "EPERM", + }); + written.push(state); + }); + const pending = publisher.publish(record); + const rejected = expect(pending).rejects.toThrow("stopped"); + publisher.stop(); + locked = false; + await rejected; + await delay(50); + expect(written).toEqual([]); + await expect(publisher.publish(record)).rejects.toThrow("stopped"); + }); + + it("reports permanent storage failures without retrying", async () => { + const publisher = createTerminalWorkerRecordPublisher(() => { + throw Object.assign(new Error("disk full"), { code: "ENOSPC" }); + }); + await expect(publisher.publish(record)).rejects.toThrow("disk full"); + publisher.stop(); + }); +}); diff --git a/packages/server/src/terminal/terminal-worker-record-publisher.ts b/packages/server/src/terminal/terminal-worker-record-publisher.ts new file mode 100644 index 0000000000..415c785102 --- /dev/null +++ b/packages/server/src/terminal/terminal-worker-record-publisher.ts @@ -0,0 +1,62 @@ +import type { TerminalWorkerRecord } from "./terminal-worker-record.js"; + +const TRANSIENT_ERRORS = new Set(["EPERM", "EBUSY", "EACCES"]); + +/** Serializes live worker publication, retaining the latest state across reader contention. + * Creation awaits publication; exit notifications need not wait for a reader to close. + * Stop before retiring the record so a pending retry cannot recreate it. + */ +export function createTerminalWorkerRecordPublisher(write: (record: TerminalWorkerRecord) => void) { + let stopped = false; + let latest: TerminalWorkerRecord; + let timer: ReturnType | undefined; + let pending: + | { + promise: Promise; + resolve: () => void; + reject: (error: unknown) => void; + } + | undefined; + + function attempt(): void { + timer = undefined; + const publication = pending; + if (!publication) return; + try { + write(latest); + publication.resolve(); + pending = undefined; + } catch (error) { + if (TRANSIENT_ERRORS.has((error as NodeJS.ErrnoException).code ?? "")) { + timer = setTimeout(attempt, 25); + } else { + publication.reject(error); + pending = undefined; + } + } + } + + return { + publish(record: TerminalWorkerRecord): Promise { + if (stopped) return Promise.reject(new Error("Worker record publisher stopped")); + latest = record; + if (pending) return pending.promise; + let resolve!: () => void; + let reject!: (error: unknown) => void; + const promise = new Promise((yes, no) => { + resolve = yes; + reject = no; + }); + pending = { promise, resolve, reject }; + attempt(); + return promise; + }, + stop(): void { + stopped = true; + clearTimeout(timer); + timer = undefined; + pending?.reject(new Error("Worker record publisher stopped")); + pending = undefined; + }, + }; +} diff --git a/packages/server/src/terminal/terminal-worker-record.ts b/packages/server/src/terminal/terminal-worker-record.ts new file mode 100644 index 0000000000..3176d2ee8e --- /dev/null +++ b/packages/server/src/terminal/terminal-worker-record.ts @@ -0,0 +1,230 @@ +import { readdir, readFile, rm } from "node:fs/promises"; +import { setTimeout as delay } from "node:timers/promises"; +import path from "node:path"; +import { z } from "zod"; +import { writePrivateFileAtomicSync, writePrivateFileAtomic } from "../server/private-files.js"; + +// Owner-only metadata a detached terminal worker leaves in $PASEO_HOME so the next daemon can +// find, authenticate and adopt it, and so cleanup can identify every process it is allowed to +// signal. Process identity is the birth time `ps`/Win32_Process report, never the pid alone. + +const TerminalWorkerTerminalEntrySchema = z.object({ + id: z.string().min(1), + pid: z.number().int().positive(), + startedAt: z.string().min(1), +}); + +// One process a cleanup could not confirm gone, kept so a later caller (a retry, or a remote +// client reading daemon status) can name it. +const TerminalCleanupUnresolvedSchema = z.object({ + pid: z.number().int().positive(), + role: z.enum(["worker", "terminal program"]), + reason: z.enum(["still alive", "inspection failed"]), + detail: z.string(), +}); + +const TerminalWorkerRecordSchema = z.object({ + recordId: z.string().min(1), + pid: z.number().int().positive(), + bootId: z.string().nullable(), + createdAt: z.string().min(1), + identity: z.object({ + startedAt: z.string().min(1), + commandLine: z.string().min(1), + }), + // Read loosely: a version this daemon cannot interpret marks a worker from a newer Paseo + // (classifyTerminalWorkerProtocol), not an unreadable record. + protocolVersion: z.union([z.number(), z.string()]), + paseoVersion: z.string(), + socketPath: z.string().min(1), + secret: z.string().min(1), + // The copy of the worker's files it runs from (a directory name under terminal-worker/), or + // null when it runs from source. A copy named by any record is never deleted. + runtime: z.string().nullable().optional(), + terminals: z.array(TerminalWorkerTerminalEntrySchema), + // Set only in a cleanup record (below), with what a cleanup could not confirm gone. A record + // marked closing is never adopted: the next daemon or stop retries the cleanup instead. + closing: z.object({ unresolved: z.array(TerminalCleanupUnresolvedSchema).min(1) }).optional(), +}); + +export type TerminalWorkerTerminalEntry = z.infer; +export type TerminalCleanupUnresolved = z.infer; +export type TerminalWorkerRecord = z.infer; + +// A worker record (`.json`) belongs to the worker, which rewrites it from memory whenever +// a terminal starts or exits. A cleanup that cannot confirm every process gone therefore keeps +// its state in a cleanup record of its own (`closing-.json`) that no worker writes, so +// the kill intent and what it could not confirm survive any later worker rewrite. +type TerminalWorkerRecordKind = "worker" | "cleanup"; + +export type TerminalWorkerRecordFile = + | { + // The file holding this record's state: the cleanup record when there is one. + path: string; + record: TerminalWorkerRecord; + // The worker's own record file, when it still exists. + workerRecordPath: string | null; + } + | { path: string; error: Error }; + +// The worker's command line carries this marker followed by its record id, so a reused pid +// running some other process (even another worker) never matches the record. +export const TERMINAL_WORKER_MARKER_ARG = "--paseo-terminal-worker"; + +export function terminalWorkerDirectory(paseoHome: string): string { + return path.join(paseoHome, "terminal-worker"); +} + +export function terminalWorkerRecordPath(paseoHome: string, workerPid: number): string { + return path.join(terminalWorkerDirectory(paseoHome), `${workerPid}.json`); +} + +export function terminalCleanupRecordPath(paseoHome: string, recordId: string): string { + return path.join(terminalWorkerDirectory(paseoHome), `closing-${recordId}.json`); +} + +export function terminalWorkerLogPath(paseoHome: string): string { + return path.join(paseoHome, "terminal-worker.log"); +} + +export function writeTerminalWorkerRecord(paseoHome: string, record: TerminalWorkerRecord): string { + const recordPath = terminalWorkerRecordPath(paseoHome, record.pid); + writePrivateFileAtomicSync(recordPath, `${JSON.stringify(record, null, 2)}\n`); + return recordPath; +} + +/** Writes the state of a cleanup that could not confirm every process gone. */ +export async function writeTerminalCleanupRecord( + paseoHome: string, + record: TerminalWorkerRecord & { closing: NonNullable }, +): Promise { + if (!RECORD_ID_PATTERN.test(record.recordId)) { + throw new Error(`Terminal worker record id is not a file name: ${record.recordId}`); + } + const recordPath = terminalCleanupRecordPath(paseoHome, record.recordId); + await writePrivateFileAtomic(recordPath, `${JSON.stringify(record, null, 2)}\n`); + return recordPath; +} + +export async function readTerminalWorkerRecord(recordPath: string): Promise { + return TerminalWorkerRecordSchema.parse(JSON.parse(await readRecordFile(recordPath))); +} + +// A worker rewrites its record by renaming a new file over it. On Windows an open() that races +// that rename fails with EPERM (or EBUSY) for a moment, so such an error is retried for a short +// window before the record counts as unreadable. Reads and retries yield so daemon status and +// cleanup never block unrelated requests while another process holds the record open. +const TRANSIENT_READ_ERRORS = new Set(["EPERM", "EBUSY", "EACCES"]); +const TRANSIENT_READ_WINDOW_MS = 250; +const TRANSIENT_READ_PAUSE_MS = 10; + +async function readRecordFile(recordPath: string): Promise { + const deadline = Date.now() + TRANSIENT_READ_WINDOW_MS; + for (;;) { + try { + return await readFile(recordPath, "utf8"); + } catch (error) { + const code = (error as NodeJS.ErrnoException).code; + if (!code || !TRANSIENT_READ_ERRORS.has(code) || Date.now() >= deadline) throw error; + await delay(TRANSIENT_READ_PAUSE_MS); + } + } +} + +const RECORD_ID_PATTERN = /^[A-Za-z0-9-]+$/; +const WORKER_RECORD_NAME = /^\d+\.json$/; +const CLEANUP_RECORD_NAME = /^closing-[A-Za-z0-9-]+\.json$/; + +function recordKindOf(fileName: string): TerminalWorkerRecordKind | null { + if (WORKER_RECORD_NAME.test(fileName)) return "worker"; + if (CLEANUP_RECORD_NAME.test(fileName)) return "cleanup"; + return null; +} + +/** + * Every record in the home. A cleanup record is merged with the worker record of the same + * record id: its closing state wins, and terminals the worker recorded since join it, so the + * retry covers everything the worker still runs. + */ +export async function listTerminalWorkerRecords( + paseoHome: string, +): Promise { + const directory = terminalWorkerDirectory(paseoHome); + let names: string[]; + try { + names = await readdir(directory); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return []; + throw error; + } + const errors: TerminalWorkerRecordFile[] = []; + const workers: Array<{ path: string; record: TerminalWorkerRecord }> = []; + const cleanups: Array<{ path: string; record: TerminalWorkerRecord }> = []; + for (const name of names.sort()) { + const kind = recordKindOf(name); + if (!kind) continue; + const recordPath = path.join(directory, name); + try { + const record = await readTerminalWorkerRecord(recordPath); + (kind === "worker" ? workers : cleanups).push({ path: recordPath, record }); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") continue; + errors.push({ + path: recordPath, + error: error instanceof Error ? error : new Error(String(error)), + }); + } + } + const files: TerminalWorkerRecordFile[] = []; + const merged = new Set(); + for (const cleanup of cleanups) { + const worker = workers.find( + (entry) => + entry.record.recordId === cleanup.record.recordId && + entry.record.pid === cleanup.record.pid, + ); + if (worker) merged.add(worker.path); + const known = new Set(cleanup.record.terminals.map((entry) => `${entry.id}:${entry.pid}`)); + const added = (worker?.record.terminals ?? []).filter( + (entry) => !known.has(`${entry.id}:${entry.pid}`), + ); + files.push({ + path: cleanup.path, + record: { ...cleanup.record, terminals: [...cleanup.record.terminals, ...added] }, + workerRecordPath: worker?.path ?? null, + }); + } + for (const worker of workers) { + if (merged.has(worker.path)) continue; + files.push({ path: worker.path, record: worker.record, workerRecordPath: worker.path }); + } + return [...files, ...errors]; +} + +/** + * Deletes a record, the worker's own record file and the socket it names, unless a later worker + * that reused the pid wrote that file since. The pipe namespace on Windows needs no unlink. + */ +export async function retireTerminalWorkerRecord(file: { + path: string; + record: TerminalWorkerRecord; + workerRecordPath: string | null; +}): Promise { + if (file.path !== file.workerRecordPath) await rm(file.path, { force: true }); + if (file.workerRecordPath) { + if (await workerRecordNamesAnother(file.workerRecordPath, file.record.recordId)) return; + await rm(file.workerRecordPath, { force: true }); + } + if (process.platform !== "win32") { + await rm(file.record.socketPath, { force: true }); + } +} + +// True when the file now belongs to another worker, or cannot be read to tell. +async function workerRecordNamesAnother(recordPath: string, recordId: string): Promise { + try { + return (await readTerminalWorkerRecord(recordPath)).recordId !== recordId; + } catch (error) { + return (error as NodeJS.ErrnoException).code !== "ENOENT"; + } +} diff --git a/packages/server/src/terminal/terminal-worker-runtime.test.ts b/packages/server/src/terminal/terminal-worker-runtime.test.ts new file mode 100644 index 0000000000..feb4bf3309 --- /dev/null +++ b/packages/server/src/terminal/terminal-worker-runtime.test.ts @@ -0,0 +1,222 @@ +import { afterEach, describe, expect, it } from "vitest"; +import { + existsSync, + mkdirSync, + mkdtempSync, + readdirSync, + readFileSync, + rmSync, + statSync, + writeFileSync, +} from "node:fs"; +import { builtinModules } from "node:module"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { isPlatform } from "../test-utils/platform.js"; +import { + prepareTerminalWorkerRuntime, + pruneTerminalWorkerRuntimes, + TerminalWorkerRuntimeError, +} from "./terminal-worker-runtime.js"; +import { + terminalWorkerDirectory, + writeTerminalWorkerRecord, + type TerminalWorkerRecord, +} from "./terminal-worker-record.js"; + +const temporaryDirs: string[] = []; + +afterEach(() => { + for (const dir of temporaryDirs.splice(0)) rmSync(dir, { recursive: true, force: true }); +}); + +function makeDir(prefix: string): string { + const dir = mkdtempSync(path.join(tmpdir(), prefix)); + temporaryDirs.push(dir); + return dir; +} + +// A built bundle directory and a node-pty package shaped like the real ones. +function makeSources(bundleSource = "export {};\n"): { + bundleDirectory: string; + nodePtyDirectory: string; +} { + const bundleDirectory = makeDir("tw-bundle-"); + writeFileSync(path.join(bundleDirectory, "terminal-worker.mjs"), bundleSource); + mkdirSync(path.join(bundleDirectory, "shell-integration", "zsh"), { recursive: true }); + writeFileSync(path.join(bundleDirectory, "shell-integration", "zsh", ".zshenv"), "# zsh\n"); + const nodePtyDirectory = makeDir("tw-node-pty-"); + writeFileSync(path.join(nodePtyDirectory, "package.json"), '{"version":"1.2.3"}\n'); + mkdirSync(path.join(nodePtyDirectory, "lib")); + writeFileSync(path.join(nodePtyDirectory, "lib", "index.js"), "module.exports = {};\n"); + const native = path.join(nodePtyDirectory, "prebuilds", `${process.platform}-${process.arch}`); + mkdirSync(native, { recursive: true }); + writeFileSync(path.join(native, "pty.node"), "native"); + writeFileSync(path.join(native, "spawn-helper"), "#!/bin/sh\n", { mode: 0o755 }); + // Another platform's build is not copied. + mkdirSync(path.join(nodePtyDirectory, "prebuilds", "other-platform")); + return { bundleDirectory, nodePtyDirectory }; +} + +function recordNaming(runtime: string | null, pid = 4242): TerminalWorkerRecord { + return { + recordId: `record-${pid}`, + pid, + bootId: null, + createdAt: new Date().toISOString(), + identity: { startedAt: "Thu Jan 1 00:00:00 1970", commandLine: "worker" }, + protocolVersion: 1, + paseoVersion: "1.0.0", + socketPath: "/tmp/does-not-exist.sock", + secret: "secret", + runtime, + terminals: [], + }; +} + +describe("terminal worker runtime copy", () => { + it("copies the bundle, its shell integration and this platform's node-pty into the home", () => { + const home = makeDir("tw-runtime-home-"); + const entry = prepareTerminalWorkerRuntime({ + paseoHome: home, + paseoVersion: "1.0.0-beta.1", + ...makeSources(), + }); + + const directory = path.join(terminalWorkerDirectory(home), entry.runtime!); + expect(entry.runtime).toMatch(/^1\.0\.0-beta\.1-[0-9a-f]{12}$/); + expect(entry.scriptPath).toBe(path.join(directory, "terminal-worker.mjs")); + expect(entry.execArgv).toEqual([]); + expect(existsSync(path.join(directory, "shell-integration", "zsh", ".zshenv"))).toBe(true); + const nodePty = path.join(directory, "node_modules", "node-pty"); + expect(existsSync(path.join(nodePty, "lib", "index.js"))).toBe(true); + expect(readdirSync(path.join(nodePty, "prebuilds"))).toEqual([ + `${process.platform}-${process.arch}`, + ]); + if (!isPlatform("win32")) { + const helper = path.join(nodePty, "prebuilds", `${process.platform}-${process.arch}`); + expect(statSync(path.join(helper, "spawn-helper")).mode & 0o111).toBe(0o111); + } + }); + + it("reuses a finished copy of the same content and makes a new one for a different build", () => { + const home = makeDir("tw-runtime-home-"); + const sources = makeSources(); + const first = prepareTerminalWorkerRuntime({ + paseoHome: home, + paseoVersion: "1.0.0", + ...sources, + }); + const marker = path.join(terminalWorkerDirectory(home), first.runtime!, "terminal-worker.mjs"); + writeFileSync(marker, "// the running copy\n"); + + const again = prepareTerminalWorkerRuntime({ + paseoHome: home, + paseoVersion: "1.0.0", + ...sources, + }); + const rebuilt = prepareTerminalWorkerRuntime({ + paseoHome: home, + paseoVersion: "1.0.0", + ...makeSources("export const rebuilt = true;\n"), + }); + + expect(again.runtime).toBe(first.runtime); + expect(statSync(marker).size).toBe("// the running copy\n".length); + expect(rebuilt.runtime).not.toBe(first.runtime); + }); + + it("replaces a copy an earlier run left unfinished", () => { + const home = makeDir("tw-runtime-home-"); + const sources = makeSources(); + const first = prepareTerminalWorkerRuntime({ + paseoHome: home, + paseoVersion: "1.0.0", + ...sources, + }); + const directory = path.join(terminalWorkerDirectory(home), first.runtime!); + rmSync(directory, { recursive: true }); + mkdirSync(directory); + + prepareTerminalWorkerRuntime({ paseoHome: home, paseoVersion: "1.0.0", ...sources }); + + expect(existsSync(path.join(directory, "terminal-worker.mjs"))).toBe(true); + }); + + it("fails before copying anything when node-pty has no native build for this platform", () => { + const home = makeDir("tw-runtime-home-"); + const sources = makeSources(); + rmSync(path.join(sources.nodePtyDirectory, "prebuilds"), { recursive: true }); + + expect(() => + prepareTerminalWorkerRuntime({ paseoHome: home, paseoVersion: "1.0.0", ...sources }), + ).toThrow(TerminalWorkerRuntimeError); + expect(readdirSync(terminalWorkerDirectory(home))).toEqual([]); + }); + + it("removes only copies no worker record names", async () => { + const home = makeDir("tw-runtime-home-"); + const used = prepareTerminalWorkerRuntime({ + paseoHome: home, + paseoVersion: "1.0.0", + ...makeSources(), + }); + const unused = prepareTerminalWorkerRuntime({ + paseoHome: home, + paseoVersion: "0.9.0", + ...makeSources(), + }); + writeTerminalWorkerRecord(home, recordNaming(used.runtime)); + const socketDirectory = path.join(terminalWorkerDirectory(home), "sock"); + mkdirSync(socketDirectory); + + const result = await pruneTerminalWorkerRuntimes(home); + + expect(result.removed).toEqual([path.join(terminalWorkerDirectory(home), unused.runtime!)]); + expect(existsSync(path.dirname(used.scriptPath))).toBe(true); + expect(existsSync(socketDirectory)).toBe(true); + }); + + it("removes nothing while a record cannot be read", async () => { + const home = makeDir("tw-runtime-home-"); + const copy = prepareTerminalWorkerRuntime({ + paseoHome: home, + paseoVersion: "1.0.0", + ...makeSources(), + }); + writeFileSync(path.join(terminalWorkerDirectory(home), "4242.json"), "{ not json"); + + expect((await pruneTerminalWorkerRuntimes(home)).removed).toEqual([]); + expect(existsSync(copy.scriptPath)).toBe(true); + }); +}); + +describe("terminal worker bundle", () => { + // The copy holds the bundle and node-pty only. A package the bundle loads at run time + // (a require hidden from esbuild behind createRequire) would be missing from it. + it("loads nothing at run time but Node built-ins and node-pty", async () => { + const outDir = makeDir("tw-bundle-build-"); + const script = fileURLToPath( + new URL("../../scripts/build-terminal-worker.mjs", import.meta.url), + ); + const { buildTerminalWorkerBundle } = (await import(script)) as { + buildTerminalWorkerBundle(input: { outDir: string }): Promise; + }; + await buildTerminalWorkerBundle({ outDir }); + + const bundle = readFileSync(path.join(outDir, "terminal-worker.mjs"), "utf8"); + const loaded = new Set(); + for (const match of bundle.matchAll( + /(?:\brequire\w*(?:\.resolve)?\(|\bfrom\s+|\bimport\s*\()\s*"([^"]+)"/g, + )) { + loaded.add(match[1]!); + } + const builtins = new Set(builtinModules.flatMap((name) => [name, `node:${name}`])); + const packages = [...loaded].filter((specifier) => !builtins.has(specifier)); + expect(packages.map((specifier) => specifier.split("/")[0])).toEqual( + packages.map(() => "node-pty"), + ); + expect(existsSync(path.join(outDir, "shell-integration", "zsh"))).toBe(true); + }); +}); diff --git a/packages/server/src/terminal/terminal-worker-runtime.ts b/packages/server/src/terminal/terminal-worker-runtime.ts new file mode 100644 index 0000000000..7ee0696478 --- /dev/null +++ b/packages/server/src/terminal/terminal-worker-runtime.ts @@ -0,0 +1,249 @@ +import { createHash, randomUUID } from "node:crypto"; +import { + chmodSync, + existsSync, + mkdirSync, + readdirSync, + readFileSync, + renameSync, + rmSync, + statSync, + writeFileSync, +} from "node:fs"; +import { createRequire } from "node:module"; +import { access, readdir, rm } from "node:fs/promises"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { ensurePrivateDirectory } from "../server/private-files.js"; +import { listTerminalWorkerRecords, terminalWorkerDirectory } from "./terminal-worker-record.js"; + +// A terminal worker outlives the installation that started it. An npm or desktop update +// replaces that installation's files, so a worker launched from them would fail its next +// terminal create (node-pty's spawn-helper, the zsh integration). A built daemon therefore +// copies the worker bundle, its shell integration and node-pty into +// $PASEO_HOME/terminal-worker/-/ and launches the worker from there. +// The hash keeps two builds of one version (a local rebuild) from sharing a copy. A copy is +// removed once no worker record names it: after a worker drains, after a kill cleanup, and at +// daemon start. Dev runs (.ts source) launch from source and copy nothing. + +export const TERMINAL_WORKER_BUNDLE_NAME = "terminal-worker.mjs"; +// Written last into a finished copy; a directory without it is an interrupted copy. +const RUNTIME_MARKER = "paseo-terminal-worker-runtime.json"; +const TEMP_PREFIX = ".tmp-"; + +export class TerminalWorkerRuntimeError extends Error { + constructor(message: string, options?: { cause?: unknown }) { + super(message, options); + this.name = "TerminalWorkerRuntimeError"; + } +} + +/** What the launcher runs: the worker script, the node flags it needs, and the copy it is in. */ +export interface TerminalWorkerEntry { + scriptPath: string; + execArgv: string[]; + /** The copy's directory name under terminal-worker/, or null when run from source. */ + runtime: string | null; +} + +function sourceExecArgv(): string[] { + const loaderUrl = new URL("./terminal-ts-loader.mjs", import.meta.url).href; + const importSource = [ + 'import { register } from "node:module";', + 'import { pathToFileURL } from "node:url";', + `register(${JSON.stringify(loaderUrl)}, pathToFileURL("./"));`, + ].join(" "); + return [ + "--experimental-strip-types", + "--import", + `data:text/javascript,${encodeURIComponent(importSource)}`, + ]; +} + +/** + * The entry a daemon launches its worker from: the source file in dev, otherwise a copy of the + * built bundle in this home, prepared on demand. + */ +export function resolveTerminalWorkerEntry(input: { + paseoHome: string; + paseoVersion: string; +}): TerminalWorkerEntry { + if (import.meta.url.endsWith(".ts")) { + return { + scriptPath: fileURLToPath(new URL("./terminal-worker-process.ts", import.meta.url)), + execArgv: sourceExecArgv(), + runtime: null, + }; + } + const bundleDirectory = fileURLToPath(new URL("../terminal-worker/", import.meta.url)); + if (!existsSync(path.join(bundleDirectory, TERMINAL_WORKER_BUNDLE_NAME))) { + throw new TerminalWorkerRuntimeError( + `The terminal worker bundle is missing from ${bundleDirectory}; rebuild @getpaseo/server (npm run build).`, + ); + } + const require = createRequire(import.meta.url); + const nodePtyDirectory = path.dirname(require.resolve("node-pty/package.json")); + return prepareTerminalWorkerRuntime({ + paseoHome: input.paseoHome, + paseoVersion: input.paseoVersion, + bundleDirectory, + nodePtyDirectory, + }); +} + +function runtimeName(input: { + paseoVersion: string; + bundleDirectory: string; + nodePtyDirectory: string; +}): string { + const hash = createHash("sha256"); + hash.update(readFileSync(path.join(input.bundleDirectory, TERMINAL_WORKER_BUNDLE_NAME))); + hash.update(readFileSync(path.join(input.nodePtyDirectory, "package.json"))); + hash.update(`${process.platform}-${process.arch}`); + const version = input.paseoVersion.replace(/[^A-Za-z0-9._-]/g, "_"); + return `${version}-${hash.digest("hex").slice(0, 12)}`; +} + +// Plain fs calls on purpose: inside the desktop app the sources live in app.asar, which +// Electron's fs reads transparently but newer helpers like cpSync do not. +function copyTree(source: string, destination: string): void { + const stat = statSync(source); + if (stat.isDirectory()) { + mkdirSync(destination, { recursive: true }); + for (const name of readdirSync(source)) { + copyTree(path.join(source, name), path.join(destination, name)); + } + return; + } + writeFileSync(destination, readFileSync(source)); + // Keeps node-pty's spawn-helper executable. + chmodSync(destination, stat.mode & 0o777); +} + +function copyNodePty(source: string, destination: string): void { + mkdirSync(destination, { recursive: true }); + copyTree(path.join(source, "package.json"), path.join(destination, "package.json")); + copyTree(path.join(source, "lib"), path.join(destination, "lib")); + const native = [ + path.join("build", "Release"), + path.join("prebuilds", `${process.platform}-${process.arch}`), + ].filter((relative) => existsSync(path.join(source, relative))); + if (native.length === 0) { + throw new TerminalWorkerRuntimeError( + `node-pty at ${source} has no native build for ${process.platform}-${process.arch}`, + ); + } + for (const relative of native) { + copyTree(path.join(source, relative), path.join(destination, relative)); + } +} + +function isCompleteRuntime(directory: string): boolean { + return existsSync(path.join(directory, RUNTIME_MARKER)); +} + +/** + * Copies the worker bundle, its shell integration and node-pty into this home, unless a finished + * copy of the same content is already there. Returns the entry to launch from the copy. + */ +export function prepareTerminalWorkerRuntime(input: { + paseoHome: string; + paseoVersion: string; + bundleDirectory: string; + nodePtyDirectory: string; +}): TerminalWorkerEntry { + const root = terminalWorkerDirectory(input.paseoHome); + ensurePrivateDirectory(root); + const name = runtimeName(input); + const directory = path.join(root, name); + const entry = { + scriptPath: path.join(directory, TERMINAL_WORKER_BUNDLE_NAME), + execArgv: [], + runtime: name, + }; + if (isCompleteRuntime(directory)) return entry; + + // An interrupted copy left behind: no worker can be running from it. + rmSync(directory, { recursive: true, force: true }); + const temporary = path.join(root, `${TEMP_PREFIX}${name}-${randomUUID()}`); + try { + mkdirSync(temporary, { recursive: true }); + copyTree( + path.join(input.bundleDirectory, TERMINAL_WORKER_BUNDLE_NAME), + path.join(temporary, TERMINAL_WORKER_BUNDLE_NAME), + ); + copyTree( + path.join(input.bundleDirectory, "shell-integration"), + path.join(temporary, "shell-integration"), + ); + copyNodePty(input.nodePtyDirectory, path.join(temporary, "node_modules", "node-pty")); + writeFileSync( + path.join(temporary, RUNTIME_MARKER), + `${JSON.stringify({ paseoVersion: input.paseoVersion, copiedAt: new Date().toISOString() })}\n`, + ); + renameSync(temporary, directory); + } catch (error) { + rmSync(temporary, { recursive: true, force: true }); + if (isCompleteRuntime(directory)) return entry; + throw new TerminalWorkerRuntimeError( + `Cannot copy the terminal worker into ${directory}: ${error instanceof Error ? error.message : String(error)}`, + { cause: error }, + ); + } + return entry; +} + +export interface PruneTerminalWorkerRuntimesResult { + removed: string[]; + /** Copies that could not be deleted (a worker that just exited can still hold files on Windows). */ + failed: Array<{ directory: string; error: string }>; +} + +/** + * Deletes every copy no worker record names. With an unreadable record it deletes nothing: that + * record could name a copy a live worker runs from. + */ +export async function pruneTerminalWorkerRuntimes( + paseoHome: string, +): Promise { + const result: PruneTerminalWorkerRuntimesResult = { removed: [], failed: [] }; + const root = terminalWorkerDirectory(paseoHome); + const files = await listTerminalWorkerRecords(paseoHome); + const inUse = new Set(); + for (const file of files) { + if ("error" in file) return result; + if (file.record.runtime) inUse.add(file.record.runtime); + } + let names: string[]; + try { + names = await readdir(root); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return result; + throw error; + } + for (const name of names) { + if (inUse.has(name)) continue; + const directory = path.join(root, name); + if ( + !name.startsWith(TEMP_PREFIX) && + !(await access(path.join(directory, RUNTIME_MARKER)).then( + () => true, + (error: NodeJS.ErrnoException) => { + if (error.code === "ENOENT" || error.code === "ENOTDIR") return false; + throw error; + }, + )) + ) + continue; + try { + await rm(directory, { recursive: true, force: true }); + result.removed.push(directory); + } catch (error) { + result.failed.push({ + directory, + error: error instanceof Error ? error.message : String(error), + }); + } + } + return result; +} diff --git a/packages/server/src/terminal/terminal-worker-socket-path.test.ts b/packages/server/src/terminal/terminal-worker-socket-path.test.ts new file mode 100644 index 0000000000..409cf60c81 --- /dev/null +++ b/packages/server/src/terminal/terminal-worker-socket-path.test.ts @@ -0,0 +1,134 @@ +import { afterEach, describe, expect, it } from "vitest"; +import { chmodSync, mkdirSync, mkdtempSync, rmSync, symlinkSync } from "node:fs"; +import { createServer } from "node:net"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { isPlatform } from "../test-utils/platform.js"; +import { + resolveTerminalWorkerSocketPath, + TerminalWorkerSocketPathError, +} from "./terminal-worker-socket-path.js"; + +const temporaryDirs: string[] = []; + +function makeDir(prefix: string, root = tmpdir()): string { + const dir = mkdtempSync(path.join(root, prefix)); + temporaryDirs.push(dir); + return dir; +} + +// A home path long enough that its socket cannot fit sun_path, with multi-byte segments so the +// budget is measured in bytes, not characters. +function longHome(root: string): string { + const home = path.join(root, "worktree-ñandú-".repeat(5), "paseo-home"); + mkdirSync(home, { recursive: true }); + return home; +} + +afterEach(() => { + for (const dir of temporaryDirs.splice(0)) { + rmSync(dir, { recursive: true, force: true }); + } +}); + +describe.skipIf(isPlatform("win32"))("terminal worker socket path", () => { + it("uses the home's own socket directory when the path fits", () => { + // macOS $TMPDIR alone is ~50 bytes; a short root keeps the home's own path in budget. + const home = makeDir("tw-h-", "/tmp"); + const socketPath = resolveTerminalWorkerSocketPath({ + paseoHome: home, + workerPid: 4242, + platform: "darwin", + }); + expect(socketPath.startsWith(path.join(home, "terminal-worker", "sock"))).toBe(true); + }); + + it("falls to /tmp/paseo- when the home and TMPDIR are too long, within the byte budget", () => { + const root = makeDir("tw-sock-long-"); + const home = longHome(root); + const tmpDir = path.join(root, "tmp-ñandú-".repeat(6)); + mkdirSync(tmpDir, { recursive: true }); + const uid = process.getuid!(); + const socketPath = resolveTerminalWorkerSocketPath({ + paseoHome: home, + workerPid: 99999, + platform: "darwin", + tmpDir, + }); + expect(path.dirname(socketPath)).toBe(`/tmp/paseo-${uid}`); + expect(Buffer.byteLength(socketPath, "utf8")).toBeLessThanOrEqual(103); + }); + + it("rejects a shared-root directory that is a symlink, has another mode, or is not a directory", () => { + const root = makeDir("tw-sock-reject-"); + const home = longHome(root); + const uid = process.getuid!(); + const tmpDir = makeDir("tw-"); + const target = makeDir("tw-target-"); + chmodSync(target, 0o700); + symlinkSync(target, path.join(tmpDir, `paseo-${uid}`)); + // A budget check alone would accept the long-home fallback through the symlink; it must + // also be refused, and /tmp/paseo- takes over. + const socketPath = resolveTerminalWorkerSocketPath({ + paseoHome: home, + workerPid: 7, + platform: "darwin", + tmpDir, + }); + expect(path.dirname(socketPath)).toBe(`/tmp/paseo-${uid}`); + + const wideTmp = makeDir("tw-"); + mkdirSync(path.join(wideTmp, `paseo-${uid}`), { mode: 0o755 }); + chmodSync(path.join(wideTmp, `paseo-${uid}`), 0o755); + expect( + path.dirname( + resolveTerminalWorkerSocketPath({ + paseoHome: home, + workerPid: 7, + platform: "darwin", + tmpDir: wideTmp, + }), + ), + ).toBe(`/tmp/paseo-${uid}`); + }); + + it("names every rejected candidate with its byte length when none fits", () => { + const root = makeDir("tw-sock-none-"); + const home = longHome(root); + const tmpDir = path.join(root, "tmp-ñandú-".repeat(6)); + mkdirSync(tmpDir, { recursive: true }); + let caught: unknown; + try { + resolveTerminalWorkerSocketPath({ + paseoHome: home, + workerPid: 7, + platform: "darwin", + tmpDir, + // Another uid's /tmp/paseo- directory does not exist or is not ours; with a uid + // nobody owns, the /tmp candidate's directory is created by us but owned by our real + // uid, so it is rejected for its owner. + uid: 2_000_000_000, + }); + } catch (error) { + caught = error; + } + rmSync("/tmp/paseo-2000000000", { recursive: true, force: true }); + expect(caught).toBeInstanceOf(TerminalWorkerSocketPathError); + const rejected = (caught as TerminalWorkerSocketPathError).rejected; + expect(rejected).toHaveLength(3); + expect(rejected[0].reason).toMatch(/longer than 103 bytes/); + expect(rejected[0].byteLength).toBe(Buffer.byteLength(rejected[0].path, "utf8")); + expect(rejected[2].reason).toMatch(/owned by uid/); + }); + + it("accepts a real listen on the chosen path", async () => { + const home = makeDir("tw-l-", "/tmp"); + const socketPath = resolveTerminalWorkerSocketPath({ paseoHome: home, workerPid: 5 }); + const server = createServer(); + await new Promise((resolve, reject) => { + server.once("error", reject); + server.listen(socketPath, () => resolve()); + }); + await new Promise((resolve) => server.close(() => resolve())); + }); +}); diff --git a/packages/server/src/terminal/terminal-worker-socket-path.ts b/packages/server/src/terminal/terminal-worker-socket-path.ts new file mode 100644 index 0000000000..99fce0e64c --- /dev/null +++ b/packages/server/src/terminal/terminal-worker-socket-path.ts @@ -0,0 +1,133 @@ +import { createHash } from "node:crypto"; +import { lstatSync, mkdirSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { ensurePrivateDirectory } from "../server/private-files.js"; +import { terminalWorkerDirectory } from "./terminal-worker-record.js"; + +// `sun_path` holds 104 bytes on macOS and 108 on Linux, NUL included. Dev homes under +// worktrees and long $TMPDIR values exceed that, so the socket goes to the first owner-only +// directory whose full path fits, measured in UTF-8 bytes. +const SOCKET_PATH_BYTE_BUDGET: Partial> = { + darwin: 103, + linux: 107, +}; +const DEFAULT_SOCKET_PATH_BYTE_BUDGET = 103; +const OWNER_ONLY_MODE = 0o700; + +export interface TerminalWorkerSocketPathInput { + paseoHome: string; + workerPid: number; + platform?: NodeJS.Platform; + tmpDir?: string; + uid?: number; +} + +export interface RejectedSocketCandidate { + path: string; + byteLength: number; + reason: string; +} + +export class TerminalWorkerSocketPathError extends Error { + readonly rejected: RejectedSocketCandidate[]; + + constructor(rejected: RejectedSocketCandidate[], budget: number) { + super( + [ + `No terminal worker socket path fits ${budget} bytes in an owner-only directory:`, + ...rejected.map( + (candidate) => ` ${candidate.path} (${candidate.byteLength} bytes): ${candidate.reason}`, + ), + ].join("\n"), + ); + this.name = "TerminalWorkerSocketPathError"; + this.rejected = rejected; + } +} + +/** First 16 hex chars of sha256(home) plus the worker pid: unique per home and worker. */ +export function terminalWorkerSocketId(paseoHome: string, workerPid: number): string { + const digest = createHash("sha256").update(path.resolve(paseoHome)).digest("hex"); + return `${digest.slice(0, 16)}-${workerPid}`; +} + +/** + * Picks (and creates) the socket path a worker listens on. Windows uses a named pipe; POSIX + * tries $PASEO_HOME/terminal-worker/sock, then /paseo-, then /tmp/paseo-. + * A shared root is never chmodded: an existing directory there is used only when it is a real + * directory owned by this user with mode 0700. + */ +export function resolveTerminalWorkerSocketPath(input: TerminalWorkerSocketPathInput): string { + const platform = input.platform ?? process.platform; + const id = terminalWorkerSocketId(input.paseoHome, input.workerPid); + if (platform === "win32") { + return `\\\\.\\pipe\\paseo-tw-${id}`; + } + + const uid = input.uid ?? process.getuid?.() ?? 0; + const budget = SOCKET_PATH_BYTE_BUDGET[platform] ?? DEFAULT_SOCKET_PATH_BYTE_BUDGET; + const fileName = `tw-${id}.sock`; + const homeSocketDirectory = path.join(terminalWorkerDirectory(input.paseoHome), "sock"); + const candidates: Array<{ directory: string; prepare: () => string | null }> = [ + { + directory: homeSocketDirectory, + prepare: () => { + ensurePrivateDirectory(homeSocketDirectory); + return verifyOwnerOnlyDirectory(homeSocketDirectory, uid); + }, + }, + ...[input.tmpDir ?? tmpdir(), "/tmp"].map((root) => { + const directory = path.join(root, `paseo-${uid}`); + return { + directory, + prepare: () => prepareSharedRootDirectory(directory, uid), + }; + }), + ]; + + const rejected: RejectedSocketCandidate[] = []; + const seen = new Set(); + for (const candidate of candidates) { + const socketPath = path.join(candidate.directory, fileName); + if (seen.has(socketPath)) continue; + seen.add(socketPath); + const byteLength = Buffer.byteLength(socketPath, "utf8"); + if (byteLength > budget) { + rejected.push({ path: socketPath, byteLength, reason: `longer than ${budget} bytes` }); + continue; + } + let problem: string | null; + try { + problem = candidate.prepare(); + } catch (error) { + problem = error instanceof Error ? error.message : String(error); + } + if (problem) { + rejected.push({ path: socketPath, byteLength, reason: problem }); + continue; + } + return socketPath; + } + throw new TerminalWorkerSocketPathError(rejected, budget); +} + +function prepareSharedRootDirectory(directory: string, uid: number): string | null { + try { + mkdirSync(directory, { mode: OWNER_ONLY_MODE }); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; + } + return verifyOwnerOnlyDirectory(directory, uid); +} + +/** Returns why the directory cannot hold the socket, or null when it is owner-only. */ +function verifyOwnerOnlyDirectory(directory: string, uid: number): string | null { + const stats = lstatSync(directory); + if (stats.isSymbolicLink()) return "is a symlink"; + if (!stats.isDirectory()) return "is not a directory"; + if (stats.uid !== uid) return `is owned by uid ${stats.uid}, not ${uid}`; + const mode = stats.mode & 0o777; + if (mode !== OWNER_ONLY_MODE) return `has mode ${mode.toString(8)}, not 700`; + return null; +} diff --git a/packages/server/src/terminal/terminal.posix.test.ts b/packages/server/src/terminal/terminal.posix.test.ts index 4452fb6c1f..474507f771 100644 --- a/packages/server/src/terminal/terminal.posix.test.ts +++ b/packages/server/src/terminal/terminal.posix.test.ts @@ -1,3 +1,5 @@ +import { readTerminalState } from "./test-utils/terminal-state.js"; +import type { TerminalState } from "@getpaseo/protocol/messages"; // POSIX-only: node-pty + POSIX shell assertions /* eslint-disable max-nested-callbacks */ import { describe, it, expect, afterEach } from "vitest"; @@ -6,7 +8,7 @@ import { buildTerminalEnvironment, createTerminal, resolveZshShellIntegrationDir, - type TerminalSession, + type LocalTerminalSession as TerminalSession, } from "./terminal.js"; import { chmodSync, @@ -28,7 +30,7 @@ if (isPlatform("win32") && !process.env.ComSpec && !process.env.COMSPEC) { process.env.ComSpec = "C:\\Windows\\System32\\cmd.exe"; } -type TerminalRow = ReturnType["grid"][number]; +type TerminalRow = TerminalState["grid"][number]; function rowToText(row: TerminalRow): string { return row @@ -38,12 +40,12 @@ function rowToText(row: TerminalRow): string { } // Extract text from a single row -function getRowText(state: ReturnType, rowIndex: number): string { +function getRowText(state: TerminalState, rowIndex: number): string { return rowToText(state.grid[rowIndex]); } // Extract all visible lines as array (trimmed, empty lines included) -function getLines(state: ReturnType): string[] { +function getLines(state: TerminalState): string[] { return state.grid.map(rowToText); } @@ -55,7 +57,7 @@ async function waitForLines( ): Promise { const start = Date.now(); while (Date.now() - start < timeoutMs) { - const lines = getLines(session.getState()); + const lines = getLines(await readTerminalState(session)); let matches = true; for (let i = 0; i < expectedLines.length; i++) { if (lines[i] !== expectedLines[i]) { @@ -68,7 +70,7 @@ async function waitForLines( } await new Promise((resolve) => setTimeout(resolve, 50)); } - const actual = getLines(session.getState()).slice(0, expectedLines.length); + const actual = getLines(await readTerminalState(session)).slice(0, expectedLines.length); throw new Error( `Timeout waiting for expected lines.\nExpected:\n${JSON.stringify(expectedLines, null, 2)}\nActual:\n${JSON.stringify(actual, null, 2)}`, ); @@ -76,12 +78,12 @@ async function waitForLines( async function waitForState( session: TerminalSession, - predicate: (state: ReturnType) => boolean, + predicate: (state: TerminalState) => boolean, timeoutMs = 5000, -): Promise> { +): Promise { const start = Date.now(); while (Date.now() - start < timeoutMs) { - const state = session.getState(); + const state = await readTerminalState(session); if (predicate(state)) { return state; } @@ -232,19 +234,19 @@ function isOsc11OkLine(line: string): boolean { return line.startsWith("OSC11_OK:"); } -function hasDaOkLine(state: ReturnType): boolean { +function hasDaOkLine(state: TerminalState): boolean { return getLines(state).some(isDaOkLine); } -function hasDsrOkLine(state: ReturnType): boolean { +function hasDsrOkLine(state: TerminalState): boolean { return getLines(state).some(isDsrOkLine); } -function hasOsc11OkLine(state: ReturnType): boolean { +function hasOsc11OkLine(state: TerminalState): boolean { return getLines(state).some(isOsc11OkLine); } -function lastNonEmptyLineIsPrompt(state: ReturnType): boolean { +function lastNonEmptyLineIsPrompt(state: TerminalState): boolean { const last = getLines(state) .toReversed() @@ -322,7 +324,7 @@ describe.skipIf(isPlatform("win32"))("terminal POSIX-only", () => { // Line 2: "$" await waitForLines(session, ["$ echo hello", "hello", "$"]); - const state = session.getState(); + const state = await readTerminalState(session); expect(getRowText(state, 0)).toBe("$ echo hello"); expect(getRowText(state, 1)).toBe("hello"); expect(getRowText(state, 2)).toBe("$"); @@ -346,7 +348,7 @@ describe.skipIf(isPlatform("win32"))("terminal POSIX-only", () => { session.send({ type: "input", data: "echo second\r" }); await waitForLines(session, ["$ echo first", "first", "$ echo second", "second", "$"]); - const state = session.getState(); + const state = await readTerminalState(session); expect(getRowText(state, 0)).toBe("$ echo first"); expect(getRowText(state, 1)).toBe("first"); expect(getRowText(state, 2)).toBe("$ echo second"); @@ -370,7 +372,7 @@ describe.skipIf(isPlatform("win32"))("terminal POSIX-only", () => { await waitForLines(session, ["$ pwd", "/tmp", "$"]); - const state = session.getState(); + const state = await readTerminalState(session); expect(getRowText(state, 0)).toBe("$ pwd"); expect(getRowText(state, 1)).toBe("/tmp"); expect(getRowText(state, 2)).toBe("$"); @@ -431,7 +433,7 @@ describe.skipIf(isPlatform("win32"))("terminal POSIX-only", () => { expect(seenTitles).toContain("npm run dev"); expect(session.getTitle()).toBe("npm run dev"); - expect(session.getState().title).toBe("npm run dev"); + expect(session.getTitle()).toBe("npm run dev"); unsubscribeTitle(); }); @@ -457,7 +459,7 @@ describe.skipIf(isPlatform("win32"))("terminal POSIX-only", () => { expect(seenTitles).toContain("Build Log"); expect(session.getTitle()).toBe("Build Log"); - expect(session.getState().title).toBe("Build Log"); + expect(session.getTitle()).toBe("Build Log"); unsubscribeTitle(); }); @@ -478,7 +480,7 @@ describe.skipIf(isPlatform("win32"))("terminal POSIX-only", () => { await new Promise((resolve) => setTimeout(resolve, 150)); expect(session.getTitle()).toBe("typecheck"); - expect(session.getState().title).toBe("typecheck"); + expect(session.getTitle()).toBe("typecheck"); }); it("emits command completion from VS Code OSC 633 without visible output", async () => { @@ -507,7 +509,7 @@ describe.skipIf(isPlatform("win32"))("terminal POSIX-only", () => { await waitForState(session, () => commandCompletions.length === 1); expect(commandCompletions).toEqual([7]); - expect(getLines(session.getState()).join("\n")).not.toContain("633;D;7"); + expect(getLines(await readTerminalState(session)).join("\n")).not.toContain("633;D;7"); unsubscribeCommandFinished(); }); @@ -541,7 +543,7 @@ describe.skipIf(isPlatform("win32"))("terminal POSIX-only", () => { await waitForState(session, () => commandCompletions.length === 1); expect(commandCompletions).toEqual([3]); - expect(getLines(session.getState()).join("\n")).not.toContain("633;D;garbage"); + expect(getLines(await readTerminalState(session)).join("\n")).not.toContain("633;D;garbage"); unsubscribeCommandFinished(); }); @@ -696,7 +698,7 @@ describe.skipIf(isPlatform("win32"))("terminal POSIX-only", () => { await waitForState(session, () => commandCompletions.includes(1)); expect(commandCompletions).toEqual([1]); - expect(getLines(session.getState()).join("\n")).not.toContain("633;D;1"); + expect(getLines(await readTerminalState(session)).join("\n")).not.toContain("633;D;1"); unsubscribeCommandFinished(); }); @@ -720,7 +722,7 @@ describe.skipIf(isPlatform("win32"))("terminal POSIX-only", () => { await waitForLines(session, ["$ printf '\\033[31mRED\\033[0m'", "RED$"]); - const state = session.getState(); + const state = await readTerminalState(session); const outputRow = state.grid[1]; expect(outputRow[0].char).toBe("R"); @@ -750,7 +752,7 @@ describe.skipIf(isPlatform("win32"))("terminal POSIX-only", () => { await waitForLines(session, ["$ printf '\\033[38;5;208mORG\\033[0m'", "ORG$"]); - const state = session.getState(); + const state = await readTerminalState(session); const outputRow = state.grid[1]; // Check O cell @@ -776,7 +778,7 @@ describe.skipIf(isPlatform("win32"))("terminal POSIX-only", () => { await waitForLines(session, ["$ printf '\\033[38;2;255;128;64mRGB\\033[0m'", "RGB$"]); - const state = session.getState(); + const state = await readTerminalState(session); const outputRow = state.grid[1]; // Check R cell @@ -805,7 +807,7 @@ describe.skipIf(isPlatform("win32"))("terminal POSIX-only", () => { await waitForLines(session, ["$ printf '\\033[41mBG\\033[0m'", "BG$"]); - const state = session.getState(); + const state = await readTerminalState(session); const outputRow = state.grid[1]; expect(outputRow[0].char).toBe("B"); @@ -815,7 +817,7 @@ describe.skipIf(isPlatform("win32"))("terminal POSIX-only", () => { }); describe("subscribe", () => { - it("receives a snapshot on initial subscription", async () => { + it("receives readiness on initial subscription", async () => { const session = trackSession( await createTerminal({ workspaceId: "ws-test", @@ -831,7 +833,7 @@ describe.skipIf(isPlatform("win32"))("terminal POSIX-only", () => { await new Promise((resolve) => setTimeout(resolve, 100)); expect(messages.length).toBeGreaterThan(0); - expect(messages[0].type).toBe("snapshot"); + expect(messages[0].type).toBe("snapshotReady"); unsubscribe(); }); @@ -861,12 +863,14 @@ describe.skipIf(isPlatform("win32"))("terminal POSIX-only", () => { await waitForLines(session, ["$ echo test", "test", "$"]); expect(messages.some((message) => message.type === "output")).toBe(true); - expect(messages.some((message) => message.type === "snapshot")).toBe(false); + expect( + messages.every((message) => message.type === "output" || message.type === "titleChange"), + ).toBe(true); unsubscribe(); }); - it("does not emit snapshot messages for resize-only updates", async () => { + it("keeps resize updates in the live observation lifecycle", async () => { const session = trackSession( await createTerminal({ workspaceId: "ws-test", @@ -889,13 +893,15 @@ describe.skipIf(isPlatform("win32"))("terminal POSIX-only", () => { session.send({ type: "resize", rows: 30, cols: 100 }); await new Promise((resolve) => setTimeout(resolve, 200)); - expect(messages.some((message) => message.type === "snapshot")).toBe(false); + expect( + messages.every((message) => message.type === "output" || message.type === "titleChange"), + ).toBe(true); expect(session.getSize()).toEqual({ rows: 30, cols: 100 }); unsubscribe(); }); - it("emits output only after getState reflects the new data", async () => { + it("emits output only after text capture reflects the new data", async () => { const session = trackSession( await createTerminal({ workspaceId: "ws-test", @@ -912,7 +918,7 @@ describe.skipIf(isPlatform("win32"))("terminal POSIX-only", () => { return; } unsubscribe(); - const stateText = getLines(session.getState()).join("\n"); + const stateText = session.captureLines().lines.join("\n"); resolve(stateText.includes("state-after-output")); }); }); @@ -965,7 +971,7 @@ describe.skipIf(isPlatform("win32"))("terminal POSIX-only", () => { session.send({ type: "input", data: `${process.execPath} ${helperPath}\r` }); await waitForState(session, hasDaOkLine); - const ack = getLines(session.getState()).find(isDaOkLine) ?? ""; + const ack = getLines(await readTerminalState(session)).find(isDaOkLine) ?? ""; expect(ack).toMatch(/^DA_OK:\[\?[\d;]+c$/); }); @@ -1003,7 +1009,7 @@ describe.skipIf(isPlatform("win32"))("terminal POSIX-only", () => { session.send({ type: "input", data: `${process.execPath} ${helperPath} cursor\r` }); await waitForState(session, hasDsrOkLine); - const ack = getLines(session.getState()).find(isDsrOkLine) ?? ""; + const ack = getLines(await readTerminalState(session)).find(isDsrOkLine) ?? ""; expect(ack).toMatch(/^DSR_OK:\d+:\d+$/); }); @@ -1023,7 +1029,7 @@ describe.skipIf(isPlatform("win32"))("terminal POSIX-only", () => { session.send({ type: "input", data: `${process.execPath} ${helperPath} private-cursor\r` }); await waitForState(session, hasDsrOkLine); - const ack = getLines(session.getState()).find(isDsrOkLine) ?? ""; + const ack = getLines(await readTerminalState(session)).find(isDsrOkLine) ?? ""; expect(ack).toMatch(/^DSR_OK:\d+:\d+$/); }); @@ -1043,7 +1049,7 @@ describe.skipIf(isPlatform("win32"))("terminal POSIX-only", () => { session.send({ type: "input", data: `${process.execPath} ${helperPath} status\r` }); await waitForState(session, hasDsrOkLine); - const ack = getLines(session.getState()).find(isDsrOkLine) ?? ""; + const ack = getLines(await readTerminalState(session)).find(isDsrOkLine) ?? ""; expect(ack).toBe("DSR_OK:status"); }); @@ -1063,7 +1069,7 @@ describe.skipIf(isPlatform("win32"))("terminal POSIX-only", () => { session.send({ type: "input", data: `${process.execPath} ${helperPath}\r` }); await waitForState(session, hasOsc11OkLine); - const ack = getLines(session.getState()).find(isOsc11OkLine) ?? ""; + const ack = getLines(await readTerminalState(session)).find(isOsc11OkLine) ?? ""; expect(ack).toBe("OSC11_OK:ESC]11;rgb:0b0b/0b0b/0b0bESC\\"); }); }); @@ -1097,7 +1103,7 @@ describe.skipIf(isPlatform("win32"))("terminal POSIX-only", () => { unsubscribe(); }); - it("sends the current snapshot to a new subscriber instead of replaying raw output", async () => { + it("announces readiness for a fresh replay instead of replaying raw live output", async () => { const session = trackSession( await createTerminal({ workspaceId: "ws-test", @@ -1121,26 +1127,24 @@ describe.skipIf(isPlatform("win32"))("terminal POSIX-only", () => { "$", ]); - let snapshotText = ""; - const unsubscribe = session.subscribe((message) => { - if (message.type !== "snapshot") { - return; - } - snapshotText = [...message.state.scrollback, ...message.state.grid] - .map(rowToText) - .join("\n"); + let ready!: () => void; + const readiness = new Promise((resolve) => { + ready = resolve; }); - - await new Promise((resolve) => setTimeout(resolve, 100)); - - expect(snapshotText).toContain("before-detach"); - expect(snapshotText).toContain("after-detach"); + const unsubscribe = session.subscribe((message) => { + if (message.type === "snapshotReady") ready(); + }); + await readiness; + const state = await readTerminalState(session); + const text = [...state.scrollback, ...state.grid].map(rowToText).join("\n"); + expect(text).toContain("before-detach"); + expect(text).toContain("after-detach"); unsubscribe(); }); }); - describe("getState", () => { - it("returns current terminal state with grid", async () => { + describe("ANSI replay observation", () => { + it("reconstructs current terminal state from ANSI", async () => { const session = trackSession( await createTerminal({ workspaceId: "ws-test", @@ -1152,7 +1156,7 @@ describe.skipIf(isPlatform("win32"))("terminal POSIX-only", () => { }), ); - const state = session.getState(); + const state = await readTerminalState(session); expect(state.rows).toBe(24); expect(state.cols).toBe(80); @@ -1179,19 +1183,16 @@ describe.skipIf(isPlatform("win32"))("terminal POSIX-only", () => { await waitForLines(session, ["$"]); session.send({ type: "input", data: "printf '\\033[2 q\\033[?25l'\r" }); - const state = await waitForState( - session, - (current) => - current.cursor.style === "block" && - current.cursor.blink === false && - current.cursor.hidden === true, + const deadline = Date.now() + 5000; + while ( + !new TextDecoder().decode(session.serializeReplay().data).includes("\x1b[?25l\x1b[2 q") + ) { + if (Date.now() > deadline) throw new Error("cursor presentation did not reach replay"); + await new Promise((resolve) => setTimeout(resolve, 20)); + } + expect(new TextDecoder().decode(session.serializeReplay().data)).toContain( + "\x1b[?25l\x1b[2 q", ); - - expect(state.cursor).toMatchObject({ - style: "block", - blink: false, - hidden: true, - }); }); it("grid cells have char and color attributes", async () => { @@ -1206,7 +1207,7 @@ describe.skipIf(isPlatform("win32"))("terminal POSIX-only", () => { await waitForLines(session, ["$"]); - const state = session.getState(); + const state = await readTerminalState(session); // First cell should be "$" expect(state.grid[0][0].char).toBe("$"); expect(state.grid[0][0]).toHaveProperty("fg"); @@ -1238,7 +1239,7 @@ describe.skipIf(isPlatform("win32"))("terminal POSIX-only", () => { // The visible area will show something like: 17, 18, 19, 20, $ await waitForLines(session, ["17", "18", "19", "20", "$"]); - const state = session.getState(); + const state = await readTerminalState(session); // Scrollback should contain the earlier output expect(state.scrollback.length).toBeGreaterThan(0); @@ -1269,7 +1270,7 @@ describe.skipIf(isPlatform("win32"))("terminal POSIX-only", () => { session.kill(); // Should not throw when trying to get state after kill - const state = session.getState(); + const state = await readTerminalState(session); expect(state).toBeDefined(); }); diff --git a/packages/server/src/terminal/terminal.test.ts b/packages/server/src/terminal/terminal.test.ts index 751fb1b33a..3d1fcca545 100644 --- a/packages/server/src/terminal/terminal.test.ts +++ b/packages/server/src/terminal/terminal.test.ts @@ -1,3 +1,7 @@ +import { TerminalInputModeTracker } from "@getpaseo/protocol/terminal-input-mode"; +import { createTerminalSerializer } from "./terminal-serializer.js"; +import { readTerminalState } from "./test-utils/terminal-state.js"; +import type { TerminalState } from "@getpaseo/protocol/messages"; import { describe, it, expect, afterEach, vi } from "vitest"; import { isPlatform } from "../test-utils/platform.js"; import { @@ -10,7 +14,7 @@ import { humanizeProcessTitle, normalizeProcessTitle, resolveZshShellIntegrationDir, - type TerminalSession, + type LocalTerminalSession as TerminalSession, } from "./terminal.js"; import { chmodSync, @@ -26,7 +30,6 @@ import { import { spawnSync } from "node:child_process"; import * as pty from "node-pty"; import xterm from "@xterm/headless"; -import { renderTerminalSnapshotToAnsi } from "@getpaseo/protocol/terminal-snapshot"; import { delimiter, join } from "node:path"; import { tmpdir } from "node:os"; import { setImmediate as waitForImmediate, setTimeout as delay } from "node:timers/promises"; @@ -34,7 +37,7 @@ import { stripVTControlCharacters } from "node:util"; const hasZsh = existsSync("/bin/zsh"); -type TerminalRow = ReturnType["grid"][number]; +type TerminalRow = TerminalState["grid"][number]; function rowToText(row: TerminalRow): string { return row @@ -44,12 +47,12 @@ function rowToText(row: TerminalRow): string { } // Extract text from a single row -function getRowText(state: ReturnType, rowIndex: number): string { +function getRowText(state: TerminalState, rowIndex: number): string { return rowToText(state.grid[rowIndex]); } // Extract all visible lines as array (trimmed, empty lines included) -function getLines(state: ReturnType): string[] { +function getLines(state: TerminalState): string[] { return state.grid.map(rowToText); } @@ -65,7 +68,7 @@ async function waitForLines( ): Promise { const start = Date.now(); while (Date.now() - start < timeoutMs) { - const lines = getLines(session.getState()); + const lines = getLines(await readTerminalState(session)); let matches = true; for (let i = 0; i < expectedLines.length; i++) { if (lines[i] !== expectedLines[i]) { @@ -78,7 +81,7 @@ async function waitForLines( } await new Promise((resolve) => setTimeout(resolve, 50)); } - const actual = getLines(session.getState()).slice(0, expectedLines.length); + const actual = getLines(await readTerminalState(session)).slice(0, expectedLines.length); throw new Error( `Timeout waiting for expected lines.\nExpected:\n${JSON.stringify(expectedLines, null, 2)}\nActual:\n${JSON.stringify(actual, null, 2)}`, ); @@ -86,12 +89,12 @@ async function waitForLines( async function waitForState( session: TerminalSession, - predicate: (state: ReturnType) => boolean, + predicate: (state: TerminalState) => boolean, timeoutMs = 5000, -): Promise> { +): Promise { const start = Date.now(); while (Date.now() - start < timeoutMs) { - const state = session.getState(); + const state = await readTerminalState(session); if (predicate(state)) { return state; } @@ -407,7 +410,12 @@ describe("createTerminal", () => { cwd: realpathSync(tmpdir()), cols: 500, command: process.execPath, - args: ["-e", "process.stdout.write(JSON.stringify(process.argv.slice(1)))", nastyPrompt], + // Keep the PTY alive until the screen assertion; exit disposes its parser. + args: [ + "-e", + "process.stdout.write(JSON.stringify(process.argv.slice(1))); setInterval(() => {}, 100000)", + nastyPrompt, + ], }), ); @@ -473,7 +481,7 @@ describe("createTerminal", () => { }), ); - const state = session.getState(); + const state = await readTerminalState(session); expect(state.rows).toBe(24); expect(state.cols).toBe(80); }); @@ -493,12 +501,12 @@ describe("createTerminal", () => { }), ); - const state = session.getState(); + const state = await readTerminalState(session); expect(state.rows).toBe(40); expect(state.cols).toBe(120); }); - it("reports per-row soft-wrap flags only when wrap flags are requested", async () => { + it("preserves soft-wrap boundaries through public replay", async () => { const session = trackSession( await createTerminal({ workspaceId: "ws-test", @@ -513,21 +521,15 @@ describe("createTerminal", () => { const start = Date.now(); while (Date.now() - start < 5000) { - if (rowToText(session.getState().grid[2]).startsWith("A")) { + if (rowToText((await readTerminalState(session)).grid[2]).startsWith("A")) { break; } await new Promise((resolve) => setTimeout(resolve, 50)); } // Rows 0 and 1 continue onto the next row; row 2 is the end of the logical line. - const withFlags = session.getState({ includeWrapFlags: true }); + const withFlags = await readTerminalState(session); expect(withFlags.gridWrapped?.slice(0, 3)).toEqual([true, true, false]); - - // Back-compat gate: without the capability the daemon must not attach the new - // fields, so an old strict-schema client still parses the snapshot. - const withoutFlags = session.getState(); - expect(withoutFlags.gridWrapped).toBeUndefined(); - expect(withoutFlags.scrollbackWrapped).toBeUndefined(); }); it("restores CJK text without injected spaces when a snapshot round-trips through the client", async () => { @@ -555,9 +557,7 @@ describe("createTerminal", () => { // row back the way a selection copy would. const restored = new xterm.Terminal({ cols: 80, rows: 10, allowProposedApi: true }); try { - await new Promise((resolve) => - restored.write(renderTerminalSnapshotToAnsi(state), resolve), - ); + await new Promise((resolve) => restored.write(session.serializeReplay().data, resolve)); expect(restored.buffer.active.getLine(0)?.translateToString(true)).toBe(text); } finally { restored.dispose(); @@ -568,6 +568,71 @@ describe("createTerminal", () => { expect(state.grid[0][1].char).toBe(""); }); + it("reports the cursor column after an emoji cluster in DSR replies", async () => { + // Programs that measure the cursor (prompts, TUIs) must see the same + // column the client renders: an emoji occupies two cells. + const program = ` + process.stdin.setRawMode(true); + process.stdin.once("data", (reply) => { + process.stdout.write("\\r\\nREPLY " + JSON.stringify(reply.toString()).slice(2, -1)); + }); + process.stdout.write("A😀\\x1b[6n"); + setInterval(() => {}, 100000); + `; + const session = trackSession( + await createTerminal({ + workspaceId: "ws-test", + cwd: realpathSync(tmpdir()), + cols: 40, + rows: 5, + command: process.execPath, + args: ["-e", program], + }), + ); + + const state = await waitForState(session, (current) => + getRowText(current, 1).startsWith("REPLY"), + ); + + expect(getRowText(state, 1)).toBe("REPLY u001b[1;4R"); + }); + + it("replays emoji clusters at their columns with the cursor after them", async () => { + const text = "A😀B❤️C👋🏽D👨‍👩‍👧E"; + const session = trackSession( + await createTerminal({ + workspaceId: "ws-test", + cwd: realpathSync(tmpdir()), + cols: 40, + rows: 5, + command: process.execPath, + args: [ + "-e", + `process.stdout.write(${JSON.stringify(text)}); setInterval(() => {}, 100000);`, + ], + }), + ); + + const state = await waitForState(session, (current) => rowHasChar(current.grid[0], "E")); + + expect(state.grid[0].slice(0, 13).map((cell) => cell.char)).toEqual([ + "A", + "😀", + "", + "B", + "❤️", + "", + "C", + "👋🏽", + "", + "D", + "👨‍👩‍👧", + "", + "E", + ]); + expect(state.cursor).toEqual({ row: 0, col: 13 }); + }); + it("captures exit diagnostics from the terminal buffer", async () => { const session = trackSession( await createTerminal({ @@ -615,11 +680,8 @@ describe("createTerminal", () => { // Poll the parsed buffer until the final line lands, so the exit summary // (which reads the headless buffer) can't race the async xterm parse. - const finalLineParsed = (): boolean => { - const state = session.getState(); - const rowText = (row: { char: string }[]): string => row.map((cell) => cell.char).join(""); - return [...state.scrollback, ...state.grid].some((row) => rowText(row).includes("line-2999")); - }; + const finalLineParsed = (): boolean => + session.captureLines({ start: -12 }).lines.some((line) => line.includes("line-2999")); const deadline = Date.now() + 10000; while (!finalLineParsed()) { if (Date.now() > deadline) { @@ -678,7 +740,7 @@ describe("createTerminal", () => { ); await waitForLines(session, ["paseo-launch-ok"]); - expect(getLines(session.getState())[0]).toBe("paseo-launch-ok"); + expect(getLines(await readTerminalState(session))[0]).toBe("paseo-launch-ok"); }, ); @@ -721,7 +783,7 @@ describe("createTerminal", () => { ); await waitForLines(session, ["paseo-launch-ok"]); - expect(getLines(session.getState())[0]).toBe("paseo-launch-ok"); + expect(getLines(await readTerminalState(session))[0]).toBe("paseo-launch-ok"); }, ); @@ -743,7 +805,7 @@ describe("createTerminal", () => { ); await waitForLines(session, ["paseo-launch-ok"]); - expect(getLines(session.getState())[0]).toBe("paseo-launch-ok"); + expect(getLines(await readTerminalState(session))[0]).toBe("paseo-launch-ok"); }); it("leaves the command check to the terminal itself on Windows", async () => { @@ -807,7 +869,7 @@ describe.skipIf(isPlatform("win32"))("send input", () => { // Line 2: "$" await waitForLines(session, ["$ echo hello", "hello", "$"]); - const state = session.getState(); + const state = await readTerminalState(session); expect(getRowText(state, 0)).toBe("$ echo hello"); expect(getRowText(state, 1)).toBe("hello"); expect(getRowText(state, 2)).toBe("$"); @@ -829,7 +891,7 @@ describe.skipIf(isPlatform("win32"))("send input", () => { await waitForLines(session, ["$ pwd", "/tmp", "$"]); - const state = session.getState(); + const state = await readTerminalState(session); expect(getRowText(state, 0)).toBe("$ pwd"); expect(getRowText(state, 1)).toBe("/tmp"); expect(getRowText(state, 2)).toBe("$"); @@ -890,7 +952,6 @@ describe.skipIf(isPlatform("win32"))("terminal title", () => { expect(seenTitles).toContain("npm run dev"); expect(session.getTitle()).toBe("npm run dev"); - expect(session.getState().title).toBe("npm run dev"); unsubscribeTitle(); }); @@ -916,7 +977,6 @@ describe.skipIf(isPlatform("win32"))("terminal title", () => { expect(seenTitles).toContain("Build Log"); expect(session.getTitle()).toBe("Build Log"); - expect(session.getState().title).toBe("Build Log"); unsubscribeTitle(); }); @@ -937,7 +997,6 @@ describe.skipIf(isPlatform("win32"))("terminal title", () => { await new Promise((resolve) => setTimeout(resolve, 150)); expect(session.getTitle()).toBe("typecheck"); - expect(session.getState().title).toBe("typecheck"); }); it("emits command completion from VS Code OSC 633 without visible output", async () => { @@ -966,7 +1025,7 @@ describe.skipIf(isPlatform("win32"))("terminal title", () => { await waitForState(session, () => commandCompletions.length === 1); expect(commandCompletions).toEqual([7]); - expect(getLines(session.getState()).join("\n")).not.toContain("633;D;7"); + expect(getLines(await readTerminalState(session)).join("\n")).not.toContain("633;D;7"); unsubscribeCommandFinished(); }); @@ -1000,7 +1059,7 @@ describe.skipIf(isPlatform("win32"))("terminal title", () => { await waitForState(session, () => commandCompletions.length === 1); expect(commandCompletions).toEqual([3]); - expect(getLines(session.getState()).join("\n")).not.toContain("633;D;garbage"); + expect(getLines(await readTerminalState(session)).join("\n")).not.toContain("633;D;garbage"); unsubscribeCommandFinished(); }); @@ -1155,7 +1214,7 @@ describe.skipIf(isPlatform("win32"))("terminal title", () => { await waitForState(session, () => commandCompletions.includes(1)); expect(commandCompletions).toEqual([1]); - expect(getLines(session.getState()).join("\n")).not.toContain("633;D;1"); + expect(getLines(await readTerminalState(session)).join("\n")).not.toContain("633;D;1"); unsubscribeCommandFinished(); }); @@ -1189,7 +1248,6 @@ describe.skipIf(isPlatform("win32"))("terminal title", () => { expect(seenTitles).toEqual(["Build Log", "User terminal"]); expect(session.getTitle()).toBe("User terminal"); - expect(session.getState().title).toBe("User terminal"); unsubscribeTitle(); }); @@ -1219,7 +1277,6 @@ describe.skipIf(isPlatform("win32"))("terminal title", () => { expect(seenTitles).toEqual(["Build Log", "User terminal"]); expect(session.getTitle()).toBe("User terminal"); - expect(session.getState().title).toBe("User terminal"); unsubscribeTitle(); }); @@ -1248,7 +1305,6 @@ describe.skipIf(isPlatform("win32"))("terminal title", () => { expect(seenTitles).toEqual(["Build Log", "User terminal"]); expect(session.getTitle()).toBe("User terminal"); - expect(session.getState().title).toBe("User terminal"); unsubscribeTitle(); }); @@ -1272,7 +1328,7 @@ describe.skipIf(isPlatform("win32"))("colors", () => { await waitForLines(session, ["$ printf '\\033[31mRED\\033[0m'", "RED$"]); - const state = session.getState(); + const state = await readTerminalState(session); const outputRow = state.grid[1]; expect(outputRow[0].char).toBe("R"); @@ -1302,7 +1358,7 @@ describe.skipIf(isPlatform("win32"))("colors", () => { await waitForLines(session, ["$ printf '\\033[38;2;255;128;64mRGB\\033[0m'", "RGB$"]); - const state = session.getState(); + const state = await readTerminalState(session); const outputRow = state.grid[1]; // Check R cell @@ -1331,7 +1387,7 @@ describe.skipIf(isPlatform("win32"))("colors", () => { await waitForLines(session, ["$ printf '\\033[41mBG\\033[0m'", "BG$"]); - const state = session.getState(); + const state = await readTerminalState(session); const outputRow = state.grid[1]; expect(outputRow[0].char).toBe("B"); @@ -1355,7 +1411,7 @@ describe("resize", () => { await new Promise((resolve) => setTimeout(resolve, 100)); - const state = session.getState(); + const state = await readTerminalState(session); expect(state.rows).toBe(40); expect(state.cols).toBe(120); }); @@ -1373,7 +1429,7 @@ describe("resize", () => { session.send({ type: "resize", rows: 10, cols: 40 }); await new Promise((resolve) => setTimeout(resolve, 100)); - const state = session.getState(); + const state = await readTerminalState(session); expect(state.grid.length).toBe(10); expect(state.grid[0].length).toBe(40); }); @@ -1552,7 +1608,7 @@ it.runIf(isPlatform("linux", "darwin"))( env: { PATH: "bin" }, }); await waitForLines(session, ["paseo-launch-ok"]); - expect(getLines(session.getState())[0]).toBe("paseo-launch-ok"); + expect(getLines(await readTerminalState(session))[0]).toBe("paseo-launch-ok"); expect(session.cwd).toBe(realpathSync(projectDir)); expect(session.getExitInfo()).toBeNull(); } finally { @@ -1574,3 +1630,309 @@ it.runIf(isPlatform("linux", "darwin"))( ).rejects.toThrow(" node : command not found"); }, ); + +it.each([false, true])( + "serializes styled Unicode, cursor presentation and modes directly (alternate=%s)", + async (alternate) => { + // Exercise the serializer's input model directly. ConPTY renders program + // output: it consumes input modes and need not publish a hidden cursor move. + const terminal = new xterm.Terminal({ + rows: 4, + cols: 16, + scrollback: 10000, + allowProposedApi: true, + }); + const serialize = createTerminalSerializer(terminal); + const inputModes = new TerminalInputModeTracker(); + const content = + Array.from({ length: 8 }, (_, i) => "normal-" + i + "\r\n").join("") + + (alternate ? "\x1b[?1049h\x1b[H" : "") + + "\x1b[38;2;255;128;64;4m界é🙂\x1b[0m\r\nVIEW-READY\x1b[?1h\x1b[?2004h\x1b[>1u\x1b[?9001h\x1b[?7l\x1b[?1000h\x1b[5 q\x1b[?25l"; + const output = content + "\x1b[2;7H"; + await new Promise((resolve) => terminal.write(output, resolve)); + inputModes.feed(output); + const data = serialize(); + const ansi = new TextDecoder().decode(data); + expect(ansi).toContain("\x1b[?25l\x1b[5 q"); + expect(ansi).not.toContain("NaN"); + expect(terminal.buffer.normal.baseY).toBeGreaterThan(0); + const receiver = new xterm.Terminal({ + rows: 4, + cols: 16, + scrollback: 10000, + allowProposedApi: true, + }); + try { + await new Promise((resolve) => receiver.write(data, resolve)); + await new Promise((resolve) => receiver.write(inputModes.getPreamble(), resolve)); + expect(receiver.buffer.active.type).toBe(alternate ? "alternate" : "normal"); + const lines = Array.from({ length: receiver.buffer.active.length }, (_, i) => + receiver.buffer.active.getLine(i)!.translateToString(true), + ); + expect(lines.join("\n")).toContain("界é🙂"); + expect(lines.join("\n")).toContain("VIEW-READY"); + const coloredIndex = lines.findIndex((line) => line.includes("界")); + const colored = receiver.buffer.active.getLine(coloredIndex)!.getCell(0)!; + expect(colored.getChars()).toBe("界"); + expect(colored.getFgColor()).toBe(0xff8040); + expect(colored.isUnderline()).not.toBe(0); + expect(receiver.buffer.normal.getLine(0)!.translateToString(true)).toBe("normal-0"); + expect({ row: receiver.buffer.active.cursorY, col: receiver.buffer.active.cursorX }).toEqual({ + row: 1, + col: 6, + }); + expect(receiver.modes).toMatchObject({ + applicationCursorKeysMode: true, + bracketedPasteMode: true, + wraparoundMode: false, + mouseTrackingMode: "vt200", + }); + const modes = new TerminalInputModeTracker(); + modes.feed(ansi + inputModes.getPreamble()); + expect(modes.getState()).toMatchObject({ + kittyKeyboardFlags: 1, + win32InputMode: true, + applicationCursorKeys: true, + bracketedPaste: true, + }); + } finally { + receiver.dispose(); + terminal.dispose(); + } + }, +); + +it.each([ + { name: "unset", presentation: "", style: undefined, visible: true }, + { + name: "reset to client default", + presentation: "\x1b[5 q\x1b[0 q", + style: undefined, + visible: true, + }, + { name: "unset hidden", presentation: "\x1b[?25l", style: undefined, visible: false }, + ...[1, 2, 3, 4, 5, 6].map((style) => ({ + name: `explicit style ${style}`, + presentation: `\x1b[${style} q\x1b[?25l`, + style, + visible: false, + })), +])("replays cursor presentation without replacing client defaults ($name)", async (input) => { + const session = trackSession( + await createTerminal({ + cwd: realpathSync(tmpdir()), + workspaceId: "cursor-presentation", + command: process.execPath, + args: [ + "-e", + `process.stdout.write(${JSON.stringify(input.presentation + "CURSOR-READY\r\n")});setInterval(()=>{},1000)`, + ], + }), + ); + await waitForLines(session, ["CURSOR-READY"]); + const { data } = session.serializeReplay(); + const ansi = new TextDecoder().decode(data); + const receiver = new xterm.Terminal({ + cursorStyle: "bar", + cursorBlink: true, + allowProposedApi: true, + }); + const styles: number[] = []; + receiver.parser.registerCsiHandler({ intermediates: " ", final: "q" }, (params) => { + styles.push(Number(params[0])); + return false; + }); + try { + await new Promise((resolve) => receiver.write(data, resolve)); + expect(styles).toEqual(input.style === undefined ? [] : [input.style]); + expect(ansi).toContain(`\x1b[?25${input.visible ? "h" : "l"}`); + } finally { + receiver.dispose(); + } +}); + +it("captures input modes at the same committed cut as serialized bytes", async () => { + const session = trackSession( + await createTerminal({ + cwd: realpathSync(tmpdir()), + workspaceId: "mode-cut", + rows: 4, + cols: 80, + command: process.execPath, + args: [ + "-e", + 'process.stdin.on("data",()=>process.stdout.write("x".repeat(1024*1024)+"\x1b[?1hMODE-CUT"));setInterval(()=>{},1000)', + ], + }), + ); + const mismatches: string[] = []; + let completed!: () => void; + const output = new Promise((resolve) => { + completed = resolve; + }); + const unsubscribe = session.subscribe((message) => { + if (message.type !== "output") return; + if (session.getReplayPreamble().includes("\x1b[?1h")) { + const cut = session.serializeReplay({ scrollbackLines: 0 }); + if (!new TextDecoder().decode(cut.data).includes("\x1b[?1h")) + mismatches.push(cut.metadata.replayPreamble); + } + if (message.data.includes("MODE-CUT")) completed(); + }); + try { + session.send({ type: "input", data: "go\r" }); + await Promise.race([ + output, + delay(5000).then(() => { + throw new Error("mode cut did not complete"); + }), + ]); + expect(mismatches).toEqual([]); + } finally { + unsubscribe(); + } +}); + +it.each( + [false, true].flatMap((alternate) => [ + { + alternate, + pendingWrap: false, + position: "\x1b[3;16H", + cursor: { row: 2, col: 15 }, + after: { row: 2, col: 16 }, + }, + { + alternate, + pendingWrap: true, + position: "", + cursor: { row: 0, col: 16 }, + after: { row: 1, col: 1 }, + }, + ]), +)( + "replays a full-width row without losing cursor state ($alternate, pendingWrap=$pendingWrap)", + async (input) => { + const source = new xterm.Terminal({ + rows: 4, + cols: 16, + scrollback: 10000, + allowProposedApi: true, + }); + const serialize = createTerminalSerializer(source); + const receiver = new xterm.Terminal({ + rows: 4, + cols: 16, + scrollback: 10000, + allowProposedApi: true, + }); + try { + await new Promise((resolve) => + source.write( + (input.alternate ? "\x1b[?1049h" : "") + "x".repeat(16) + input.position, + resolve, + ), + ); + expect({ row: source.buffer.active.cursorY, col: source.buffer.active.cursorX }).toEqual( + input.cursor, + ); + await new Promise((resolve) => receiver.write(serialize(), resolve)); + expect({ row: receiver.buffer.active.cursorY, col: receiver.buffer.active.cursorX }).toEqual( + input.cursor, + ); + await new Promise((resolve) => receiver.write("Z", resolve)); + expect({ row: receiver.buffer.active.cursorY, col: receiver.buffer.active.cursorX }).toEqual( + input.after, + ); + } finally { + receiver.dispose(); + source.dispose(); + } + }, +); + +it.each([false, true])( + "replays the observed PTY projection including startup modes (alternate=%s)", + async (alternate) => { + const gate = mkdtempSync(join(tmpdir(), "terminal-projection-")); + temporaryDirs.push(gate); + const release = join(gate, "output"); + const content = + Array.from({ length: 8 }, (_, i) => `normal-${i}\r\n`).join("") + + (alternate ? "\x1b[?1049h\x1b[H" : "") + + "\x1b[38;2;255;128;64;4m界é🙂\x1b[0m\r\nVIEW-READY\x1b[?1h\x1b[?2004h\x1b[>1u\x1b[?9001h\x1b[?7l\x1b[?1000h\x1b[5 q\x1b[?25l\x1b[2;7H"; + const session = trackSession( + await createTerminal({ + cwd: realpathSync(tmpdir()), + workspaceId: "projection", + rows: 4, + cols: 16, + command: process.execPath, + args: [ + "-e", + `const fs=require("node:fs");let sent=false; + function emit(){if(!sent&&fs.existsSync(${JSON.stringify(release)})){sent=true;watcher.close();process.stdout.write(${JSON.stringify(content)});}} + const watcher=fs.watch(${JSON.stringify(gate)},emit);emit();setInterval(()=>{},1000);`, + ], + }), + ); + const bootstrap = session.serializeReplay(); + const output: string[] = []; + const unsubscribe = session.subscribe((message) => { + if (message.type === "output") output.push(message.data); + }); + const reference = new xterm.Terminal({ + rows: 4, + cols: 16, + scrollback: 10000, + allowProposedApi: true, + }); + const receiver = new xterm.Terminal({ + rows: 4, + cols: 16, + scrollback: 10000, + allowProposedApi: true, + }); + try { + await new Promise((resolve) => reference.write(bootstrap.data, resolve)); + await new Promise((resolve) => + reference.write(bootstrap.metadata.replayPreamble, resolve), + ); + writeFileSync(release, "release"); + const deadline = Date.now() + 5000; + while (!session.captureLines().lines.some((line) => line.includes("VIEW-READY"))) { + if (Date.now() > deadline) throw new Error("PTY did not render fixture output"); + await delay(20); + } + // Bootstrap and these committed output events cover precisely this source cut. + // Program bytes are not the oracle: ConPTY consumes modes and renders cells. + const replay = session.serializeReplay(); + const committed = output.join(""); + await new Promise((resolve) => reference.write(committed, resolve)); + await new Promise((resolve) => receiver.write(replay.data, resolve)); + await new Promise((resolve) => receiver.write(replay.metadata.replayPreamble, resolve)); + const text = (terminal: typeof receiver) => + Array.from({ length: terminal.buffer.active.length }, (_, i) => + terminal.buffer.active.getLine(i)!.translateToString(true).trimEnd(), + ); + expect(text(receiver)).toEqual(text(reference)); + expect(text(receiver).join("\n")).toContain("界é🙂"); + expect(text(receiver).join("\n")).toContain("VIEW-READY"); + expect(receiver.buffer.active.type).toBe(alternate ? "alternate" : "normal"); + expect({ row: receiver.buffer.active.cursorY, col: receiver.buffer.active.cursorX }).toEqual({ + row: reference.buffer.active.cursorY, + col: reference.buffer.active.cursorX, + }); + expect(receiver.modes).toEqual(reference.modes); + const expectedModes = new TerminalInputModeTracker(); + expectedModes.feed(bootstrap.metadata.replayPreamble + committed); + const actualModes = new TerminalInputModeTracker(); + actualModes.feed(new TextDecoder().decode(replay.data) + replay.metadata.replayPreamble); + expect(actualModes.getState()).toEqual(expectedModes.getState()); + } finally { + unsubscribe(); + receiver.dispose(); + reference.dispose(); + } + }, +); diff --git a/packages/server/src/terminal/terminal.ts b/packages/server/src/terminal/terminal.ts index 24f243b6ea..b09bc8bbf6 100644 --- a/packages/server/src/terminal/terminal.ts +++ b/packages/server/src/terminal/terminal.ts @@ -1,5 +1,5 @@ import * as pty from "node-pty"; -import xterm, { type Terminal as TerminalType } from "@xterm/headless"; +import type { Terminal as TerminalType } from "@xterm/headless"; import { randomUUID } from "crypto"; import { accessSync, @@ -15,19 +15,29 @@ import { basename, delimiter, dirname, extname, join, resolve as resolvePath } f import { createRequire } from "node:module"; import { fileURLToPath } from "node:url"; import { createExternalProcessEnv } from "../server/paseo-env.js"; +import { + resolveExternalProcessPath, + resolvePaseoCliBinDir, + resolvePaseoCliExecutablePath, +} from "./paseo-cli-path.js"; import { writePrivateFileAtomicSync } from "../server/private-files.js"; import { findExecutable, findExecutableWithoutProbing, } from "../executable-resolution/executable-resolution.js"; -import type { TerminalCell, TerminalState } from "@getpaseo/protocol/messages"; +import { createHeadlessTerminal } from "./headless-terminal.js"; +import { createTerminalSerializer } from "./terminal-serializer.js"; +import { + captureTerminalLines, + type CaptureTerminalLinesOptions, + type CaptureTerminalLinesResult, +} from "./terminal-capture.js"; +import type { TerminalReplayOptions, TerminalReplayMetadata } from "./terminal-replay.js"; import { TerminalInputModeTracker } from "@getpaseo/protocol/terminal-input-mode"; import { TerminalActivityTracker } from "./activity/terminal-activity-tracker.js"; import type { TerminalActivity, TerminalActivityState } from "@getpaseo/protocol/terminal-activity"; -const { Terminal } = xterm; const require = createRequire(import.meta.url); -const PASEO_CLI_BIN_ENTRY = "@getpaseo/cli/bin/paseo"; let nodePtySpawnHelperChecked = false; const TERMINAL_TITLE_DEBOUNCE_MS = 150; const TERMINAL_EXIT_OUTPUT_LINE_LIMIT = 12; @@ -62,26 +72,6 @@ export interface TerminalCommandFinishedInfo { exitCode: number | null; } -export interface TerminalStateSnapshot { - state: TerminalState; - revision: number; - // Input-mode replay preamble at snapshot time. Populated by the terminal - // worker so the daemon main loop doesn't have to re-derive it from output. - replayPreamble?: string; -} - -export interface TerminalStateSnapshotOptions { - scrollbackLines?: number; - // Include per-row soft-wrap flags (gridWrapped/scrollbackWrapped) so the client - // can reflow restored content on resize. Gated on a client capability, so old - // clients never receive the extra fields. - includeWrapFlags?: boolean; -} - -export interface TerminalSubscribeOptions { - initialSnapshot?: "state" | "ready"; -} - export type ClientMessage = | { type: "input"; data: string } | { type: "resize"; rows: number; cols: number } @@ -89,7 +79,6 @@ export type ClientMessage = export type ServerMessage = | { type: "output"; data: string; revision?: number } - | { type: "snapshot"; state: TerminalState; revision?: number } | { type: "snapshotReady"; revision?: number; replayPreamble?: string } | { type: "titleChange"; title?: string }; @@ -104,14 +93,13 @@ export interface TerminalSession { cwd: string; workspaceId: string; send(msg: ClientMessage): void; - subscribe(listener: (msg: ServerMessage) => void, options?: TerminalSubscribeOptions): () => void; + subscribe(listener: (msg: ServerMessage) => void): () => void; onExit(listener: (info: TerminalExitInfo) => void): () => void; onCommandFinished(listener: (info: TerminalCommandFinishedInfo) => void): () => void; onTitleChange(listener: (title?: string) => void): () => void; onActivityChange(listener: (transition: TerminalActivityTransition) => void): () => void; getSize(): { rows: number; cols: number }; - getState(): TerminalState; - getStateSnapshot(options?: TerminalStateSnapshotOptions): TerminalStateSnapshot; + hasOutput(): boolean; getReplayPreamble(): string; getTitle(): string | undefined; getActivity(): TerminalActivity | null; @@ -123,6 +111,16 @@ export interface TerminalSession { killAndWait(options?: { gracefulTimeoutMs?: number; forceTimeoutMs?: number }): Promise; } +/** A session that owns its PTY in this process, so it knows the program's pid. */ +export interface LocalTerminalSession extends TerminalSession { + readonly pid: number; + serializeReplay(options?: TerminalReplayOptions): { + metadata: TerminalReplayMetadata; + data: Uint8Array; + }; + captureLines(options?: CaptureTerminalLinesOptions): CaptureTerminalLinesResult; +} + function parseCommandFinishedOsc(data: string): TerminalCommandFinishedInfo | null { // OSC 633 is terminal control traffic, but a foreground command can still // print arbitrary control bytes. Keep this boundary to the exact VS Code @@ -153,6 +151,11 @@ export interface CreateTerminalOptions { title?: string; command?: string; args?: string[]; + // Environment the terminal starts from instead of this process's own. A detached terminal + // worker outlives the daemon that launched it, so each create carries the controlling + // daemon's environment and its resolved Paseo CLI path. + baseEnv?: Record; + paseoCliPath?: string | null; } function toTerminalActivity(snapshot: { @@ -181,6 +184,7 @@ function isTerminalActivityInterruptInput(data: string): boolean { interface BuildTerminalEnvironmentInput { shell: string; env: Record; + baseEnv?: Record; zshShellIntegrationDir?: string; paseoCliBinDir?: string | null; paseoHookCliPath?: string | null; @@ -410,84 +414,12 @@ export async function resolveTerminalSpawnCommand( return { command: resolved, args }; } +export { resolvePaseoCliBinDir, resolvePaseoCliExecutablePath }; + export function resolveZshShellIntegrationDir(): string { return fileURLToPath(new URL("./shell-integration/zsh", import.meta.url)); } -function resolveExternalProcessPath(filePath: string): string { - return filePath.replace(/\.asar(?=[/\\]|$)/, ".asar.unpacked"); -} - -export function resolvePaseoCliBinDir(): string | null { - const cliExecutable = resolvePaseoCliExecutablePath(); - return cliExecutable ? dirname(cliExecutable) : null; -} - -export function resolvePaseoCliExecutablePath(): string | null { - const configuredCli = process.env.PASEO_CLI?.trim(); - if (configuredCli) { - return resolvePath(configuredCli); - } - - const cliEntrypoint = resolvePaseoCliBinEntrypoint(); - if (!cliEntrypoint) { - return null; - } - - const externalCliEntrypoint = resolveExternalProcessPath(cliEntrypoint); - const npmBinDir = findNpmBinDir(dirname(externalCliEntrypoint)); - if (npmBinDir) { - const shim = resolvePaseoCliShim(npmBinDir); - if (shim) { - return shim; - } - } - - return externalCliEntrypoint; -} - -function resolvePaseoCliBinEntrypoint(): string | null { - try { - return require.resolve(PASEO_CLI_BIN_ENTRY); - } catch { - return null; - } -} - -function findNpmBinDir(startPath: string): string | null { - let current = startPath; - while (true) { - const candidate = join(current, "node_modules", ".bin"); - if (hasPaseoCliShim(candidate)) { - return candidate; - } - - const parent = dirname(current); - if (parent === current) { - return null; - } - current = parent; - } -} - -function hasPaseoCliShim(binDir: string): boolean { - return resolvePaseoCliShim(binDir) !== null; -} - -function resolvePaseoCliShim(binDir: string): string | null { - for (const name of paseoCliShimNames()) { - const candidate = join(binDir, name); - if (existsSync(candidate)) { - return candidate; - } - } - return null; -} - -function paseoCliShimNames(): string[] { - return process.platform === "win32" ? ["paseo.cmd", "paseo.exe", "paseo"] : ["paseo"]; -} - function resolveZshShellIntegrationRuntimeDir(): string { let username = "unknown"; try { @@ -517,10 +449,14 @@ function prepareZshShellIntegrationRuntimeDir(sourceDir = resolveZshShellIntegra export function buildTerminalEnvironment( input: BuildTerminalEnvironmentInput, ): Record { - const baseEnv: Record = createExternalProcessEnv(process.env, input.env, { - TERM: "xterm-256color", - TERM_PROGRAM: "kitty", - }); + const baseEnv: Record = createExternalProcessEnv( + input.baseEnv ?? process.env, + input.env, + { + TERM: "xterm-256color", + TERM_PROGRAM: "kitty", + }, + ); const envWithAgentHooks = prependPaseoCliToPath( baseEnv, input.paseoCliBinDir === undefined ? resolvePaseoCliBinDir() : input.paseoCliBinDir, @@ -556,6 +492,23 @@ function injectPaseoHookCli( }; } +// The environment and CLI path a terminal starts from: the caller's when it sends them (the +// daemon controlling a detached worker does), this process's otherwise. +function resolveTerminalEnvironmentSource( + input: Pick, +): Pick { + const source: Pick< + BuildTerminalEnvironmentInput, + "baseEnv" | "paseoCliBinDir" | "paseoHookCliPath" + > = {}; + if (input.baseEnv) source.baseEnv = input.baseEnv; + if (input.paseoCliPath !== undefined) { + source.paseoCliBinDir = input.paseoCliPath ? dirname(input.paseoCliPath) : null; + source.paseoHookCliPath = input.paseoCliPath; + } + return source; +} + function prependPaseoCliToPath( env: Record, cliBinDir: string | null, @@ -581,179 +534,6 @@ function prependPathEntry(currentPath: string, entry: string): string { return [entry, ...entries].join(delimiter); } -function extractCell(terminal: TerminalType, row: number, col: number): TerminalCell { - const buffer = terminal.buffer.active; - const line = buffer.getLine(row); - if (!line) { - return { char: " ", fg: undefined, bg: undefined }; - } - - const cell = line.getCell(col); - if (!cell) { - return { char: " ", fg: undefined, bg: undefined }; - } - - // Color modes from xterm.js: 0=DEFAULT, 1=16 colors (ANSI), 2=256 colors, 3=RGB - // getFgColorMode() returns packed value with mode in upper byte (e.g. 0x01000000 for mode 1) - const fgModeRaw = cell.getFgColorMode(); - const bgModeRaw = cell.getBgColorMode(); - const fgMode = fgModeRaw >> 24; - const bgMode = bgModeRaw >> 24; - - // Only return color if not default (mode 0) - const fg = fgMode !== 0 ? cell.getFgColor() : undefined; - const bg = bgMode !== 0 ? cell.getBgColor() : undefined; - - return { - // Wide chars (CJK) span two cells; xterm returns "" for the zero-width - // continuation. Collapsing it to " " injects a real space on restore. - char: cell.getWidth() === 0 ? "" : cell.getChars() || " ", - fg, - bg, - fgMode: fgMode !== 0 ? fgMode : undefined, - bgMode: bgMode !== 0 ? bgMode : undefined, - bold: cell.isBold() !== 0, - italic: cell.isItalic() !== 0, - underline: cell.isUnderline() !== 0, - dim: cell.isDim() !== 0, - inverse: cell.isInverse() !== 0, - strikethrough: cell.isStrikethrough() !== 0, - }; -} - -function extractGrid(terminal: TerminalType): TerminalCell[][] { - const grid: TerminalCell[][] = []; - const buffer = terminal.buffer.active; - // Visible viewport starts at baseY - const baseY = buffer.baseY; - - for (let row = 0; row < terminal.rows; row++) { - const rowCells: TerminalCell[] = []; - for (let col = 0; col < terminal.cols; col++) { - rowCells.push(extractCell(terminal, baseY + row, col)); - } - grid.push(rowCells); - } - - return grid; -} - -function extractScrollback( - terminal: TerminalType, - options?: { scrollbackLines?: number }, -): TerminalCell[][] { - const scrollback: TerminalCell[][] = []; - const buffer = terminal.buffer.active; - // baseY is the first row of the visible viewport (0-indexed) - // Lines 0 to baseY-1 are in scrollback, lines baseY onwards are visible - const scrollbackLines = buffer.baseY; - const startRow = - typeof options?.scrollbackLines === "number" - ? Math.max(0, scrollbackLines - options.scrollbackLines) - : 0; - - for (let row = startRow; row < scrollbackLines; row++) { - const rowCells: TerminalCell[] = []; - const line = buffer.getLine(row); - for (let col = 0; col < terminal.cols; col++) { - if (line) { - const cell = line.getCell(col); - if (cell) { - const fgModeRaw = cell.getFgColorMode(); - const bgModeRaw = cell.getBgColorMode(); - const fgMode = fgModeRaw >> 24; - const bgMode = bgModeRaw >> 24; - const fg = fgMode !== 0 ? cell.getFgColor() : undefined; - const bg = bgMode !== 0 ? cell.getBgColor() : undefined; - rowCells.push({ - // Wide chars (CJK) span two cells; xterm returns "" for the zero-width - // continuation. Collapsing it to " " injects a real space on restore. - char: cell.getWidth() === 0 ? "" : cell.getChars() || " ", - fg, - bg, - fgMode: fgMode !== 0 ? fgMode : undefined, - bgMode: bgMode !== 0 ? bgMode : undefined, - bold: cell.isBold() !== 0, - italic: cell.isItalic() !== 0, - underline: cell.isUnderline() !== 0, - dim: cell.isDim() !== 0, - inverse: cell.isInverse() !== 0, - strikethrough: cell.isStrikethrough() !== 0, - }); - } else { - rowCells.push({ char: " ", fg: undefined, bg: undefined }); - } - } else { - rowCells.push({ char: " ", fg: undefined, bg: undefined }); - } - } - scrollback.push(rowCells); - } - - return scrollback; -} - -// xterm marks a line `isWrapped` when it is a continuation of the PREVIOUS line. -// The snapshot carries the inverse, tmux-style flag — "this row continues onto the -// next row" — so the client can rejoin and reflow logical lines. So row y's flag is -// whether line y+1 is a wrapped continuation. -function lineContinuesToNext(terminal: TerminalType, absoluteRow: number): boolean { - return terminal.buffer.active.getLine(absoluteRow + 1)?.isWrapped === true; -} - -function extractGridWrapped(terminal: TerminalType): boolean[] { - const baseY = terminal.buffer.active.baseY; - const wrapped: boolean[] = []; - for (let row = 0; row < terminal.rows; row++) { - wrapped.push(lineContinuesToNext(terminal, baseY + row)); - } - return wrapped; -} - -function extractScrollbackWrapped( - terminal: TerminalType, - options?: { scrollbackLines?: number }, -): boolean[] { - const scrollbackLines = terminal.buffer.active.baseY; - const startRow = - typeof options?.scrollbackLines === "number" - ? Math.max(0, scrollbackLines - options.scrollbackLines) - : 0; - const wrapped: boolean[] = []; - for (let row = startRow; row < scrollbackLines; row++) { - wrapped.push(lineContinuesToNext(terminal, row)); - } - return wrapped; -} - -function extractCursorState(terminal: TerminalType): TerminalState["cursor"] { - const coreService = (terminal as unknown as { _core?: { coreService?: Record } }) - ._core?.coreService as - | { - decPrivateModes?: { cursorStyle?: unknown; cursorBlink?: unknown }; - isCursorHidden?: unknown; - } - | undefined; - const cursorStyle = coreService?.decPrivateModes?.cursorStyle; - const normalizedCursorStyle = - cursorStyle === "block" || cursorStyle === "underline" || cursorStyle === "bar" - ? cursorStyle - : undefined; - const cursorBlink = - typeof coreService?.decPrivateModes?.cursorBlink === "boolean" - ? coreService.decPrivateModes.cursorBlink - : undefined; - const hidden = Boolean(coreService?.isCursorHidden); - - return { - row: terminal.buffer.active.cursorY, - col: terminal.buffer.active.cursorX, - ...(hidden ? { hidden: true } : {}), - ...(normalizedCursorStyle ? { style: normalizedCursorStyle } : {}), - ...(typeof cursorBlink === "boolean" ? { blink: cursorBlink } : {}), - }; -} - function normalizeProcessToken(token: string): string { if (token.length === 0) { return token; @@ -967,7 +747,9 @@ export async function assertTerminalCommandCanStart( } } -export async function createTerminal(options: CreateTerminalOptions): Promise { +export async function createTerminal( + options: CreateTerminalOptions, +): Promise { const { cwd, workspaceId, @@ -980,8 +762,10 @@ export async function createTerminal(options: CreateTerminalOptions): Promise void>(); @@ -1012,13 +796,9 @@ export async function createTerminal(options: CreateTerminalOptions): Promise void>(); let titleChangeSubscription: { dispose(): void } | null = null; - // Create xterm.js headless terminal - const terminal = new Terminal({ - rows, - cols, - scrollback: 1000, - allowProposedApi: true, - }); + const terminal = createHeadlessTerminal({ rows, cols, scrollback: 10000 }); + + const serialize = createTerminalSerializer(terminal); ensureNodePtySpawnHelperExecutableForCurrentPlatform(); @@ -1033,6 +813,7 @@ export async function createTerminal(options: CreateTerminalOptions): Promise { if (killed) return; - const inputModeUpdate = inputModeTracker.feed(data); - for (const response of inputModeUpdate.responses) { - ptyProcess.write(response); - } recentOutputChunks.push(data); recentOutputLength += data.length; // Drop whole leading chunks while the rest still covers the char limit, so @@ -1326,32 +1107,15 @@ export async function createTerminal(options: CreateTerminalOptions): Promise void, - subscribeOptions?: TerminalSubscribeOptions, - ): () => void { + function subscribe(listener: (msg: ServerMessage) => void): () => void { let active = true; let snapshotDelivered = false; const queuedMessages: ServerMessage[] = []; - const initialSnapshot = subscribeOptions?.initialSnapshot ?? "state"; const subscriptionListener = (msg: ServerMessage): void => { if (!active) { return; @@ -1441,17 +1201,11 @@ export async function createTerminal(options: CreateTerminalOptions): Promise { if (!disposed && active && listeners.has(subscriptionListener)) { snapshotDelivered = true; - if (initialSnapshot === "ready") { - // Carry the input-mode preamble so the snapshot-less "ready" path - // (live restore) can replay it without a separate state fetch. - listener({ - type: "snapshotReady", - revision: stateRevision, - replayPreamble: getReplayPreamble(), - }); - } else { - listener({ type: "snapshot", ...getStateSnapshot() }); - } + listener({ + type: "snapshotReady", + revision: stateRevision, + replayPreamble: getReplayPreamble(), + }); for (const message of queuedMessages.splice(0)) { listener(message); } @@ -1624,6 +1378,7 @@ export async function createTerminal(options: CreateTerminalOptions): Promise captureTerminalLines(terminal.buffer.active, captureOptions), + hasOutput: () => { + const buffer = terminal.buffer.active; + for (let row = 0; row < buffer.length; row++) { + if (buffer.getLine(row)?.translateToString(true).trim()) return true; + } + return false; + }, getReplayPreamble, getTitle, getActivity, diff --git a/packages/server/src/terminal/test-utils/terminal-state.ts b/packages/server/src/terminal/test-utils/terminal-state.ts new file mode 100644 index 0000000000..fb5f5d610a --- /dev/null +++ b/packages/server/src/terminal/test-utils/terminal-state.ts @@ -0,0 +1,50 @@ +import type { TerminalState } from "@getpaseo/protocol/messages"; +import { createHeadlessTerminal } from "../headless-terminal.js"; +import type { LocalTerminalSession } from "../terminal.js"; + +/** Observe the public ANSI replay using a real receiver; no production cell extraction API. */ +export async function readTerminalState(session: LocalTerminalSession): Promise { + const { metadata, data } = session.serializeReplay(); + const terminal = createHeadlessTerminal({ + rows: metadata.rows, + cols: metadata.cols, + scrollback: 10000, + }); + try { + await new Promise((resolve) => terminal.write(data, resolve)); + const buffer = terminal.buffer.active; + const rows = Array.from({ length: buffer.length }, (_, row) => + Array.from({ length: terminal.cols }, (_cell, col) => { + const cell = buffer.getLine(row)!.getCell(col)!; + const fgMode = cell.getFgColorMode() >> 24; + const bgMode = cell.getBgColorMode() >> 24; + return { + char: cell.getWidth() === 0 ? "" : cell.getChars() || " ", + fg: fgMode ? cell.getFgColor() : undefined, + bg: bgMode ? cell.getBgColor() : undefined, + fgMode: fgMode || undefined, + bgMode: bgMode || undefined, + bold: !!cell.isBold(), + italic: !!cell.isItalic(), + underline: !!cell.isUnderline(), + dim: !!cell.isDim(), + inverse: !!cell.isInverse(), + strikethrough: !!cell.isStrikethrough(), + }; + }), + ); + const wrapped = rows.map((_, i) => buffer.getLine(i + 1)?.isWrapped === true); + return { + rows: terminal.rows, + cols: terminal.cols, + grid: rows.slice(buffer.baseY), + scrollback: rows.slice(0, buffer.baseY), + gridWrapped: wrapped.slice(buffer.baseY), + scrollbackWrapped: wrapped.slice(0, buffer.baseY), + cursor: { row: buffer.cursorY, col: buffer.cursorX }, + ...(session.getTitle() ? { title: session.getTitle() } : {}), + }; + } finally { + terminal.dispose(); + } +} diff --git a/packages/server/src/terminal/worker-terminal-manager.test.ts b/packages/server/src/terminal/worker-terminal-manager.test.ts index e11c9eca9f..b0ef983a8e 100644 --- a/packages/server/src/terminal/worker-terminal-manager.test.ts +++ b/packages/server/src/terminal/worker-terminal-manager.test.ts @@ -1,13 +1,41 @@ +import { TerminalInputModeTracker } from "@getpaseo/protocol/terminal-input-mode"; +import { encodeTerminalKeyInput } from "@getpaseo/protocol/terminal-key-input"; +import type { SubscribeTerminalRequest } from "@getpaseo/protocol/messages"; +import { TerminalSessionController } from "./terminal-session-controller.js"; +import { SessionDelivery } from "../server/session/owned-subscriptions/index.js"; +import { + decodeTerminalStreamFrame, + TerminalStreamOpcode, + type TerminalStreamFrame, +} from "@getpaseo/protocol/binary-frames/index"; +import type { SessionOutboundMessage } from "../server/messages.js"; +import { createConnection } from "node:net"; +import { attachFramedSocket } from "./terminal-worker-frames.js"; +import xterm from "@xterm/headless"; import { afterEach, expect, it } from "vitest"; import { isPlatform } from "../test-utils/platform.js"; import { EventEmitter } from "node:events"; -import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { + closeSync, + existsSync, + openSync, + mkdirSync, + mkdtempSync, + readdirSync, + readFileSync, + rmSync, + writeFileSync, +} from "node:fs"; import { delimiter, join } from "node:path"; import { tmpdir } from "node:os"; -import { createWorkerTerminalManager } from "./worker-terminal-manager.js"; +import pino from "pino"; +import { + createWorkerTerminalManager, + startWorkerTerminalManager, + type DaemonTerminalManager, +} from "./worker-terminal-manager.js"; import type { TerminalActivityTransitionEvent, - TerminalManager, TerminalWorkspaceContributionChangedEvent, } from "./terminal-manager.js"; import { @@ -19,8 +47,30 @@ import type { TerminalState } from "@getpaseo/protocol/messages"; import type { TerminalActivity } from "@getpaseo/protocol/terminal-activity"; import type { TerminalWorkerRequest, + WorkerTerminalState, TerminalWorkerToParentMessage, } from "./terminal-worker-protocol.js"; +import { classifyTerminalProgramProcess } from "./terminal-worker-ownership.js"; +import { createTerminalWorkerProcessInspector } from "./terminal-worker-processes.js"; +import { + readUnconfirmedTerminalCleanup, + reapTerminalWorkers, + TerminalCleanupNotConfirmedError, +} from "./terminal-worker-reaper.js"; +import { + listTerminalWorkerRecords, + readTerminalWorkerRecord, + terminalWorkerDirectory, + terminalWorkerRecordPath, + type TerminalWorkerRecord, +} from "./terminal-worker-record.js"; +import { TERMINAL_WORKER_PROTOCOL_OVERRIDE_ENV } from "./terminal-worker-protocol.js"; +import { + NoTerminalWorkerAvailableError, + TerminalWorkerIncompatibleError, +} from "./terminal-worker-pool.js"; +import { connectTerminalWorker } from "./terminal-worker-client.js"; +import { launchTerminalWorker } from "./terminal-worker-launch.js"; type TerminalRow = TerminalState["grid"][number]; @@ -46,8 +96,35 @@ async function waitForCondition( throw new Error(`Timed out after ${timeoutMs}ms waiting for condition`); } -function getVisibleText(session: TerminalSession): string { - return getVisibleTextFromState(session.getState()); +async function readReplay(manager: DaemonTerminalManager, id: string) { + const chunks: Uint8Array[] = []; + const metadata = await manager.replayTerminal(id, undefined, (event) => { + if (event.type === "data") chunks.push(event.data); + }); + if (!metadata) return null; + const terminal = new xterm.Terminal({ + rows: metadata.rows, + cols: metadata.cols, + scrollback: 1000, + allowProposedApi: true, + }); + await new Promise((resolve) => terminal.write(Buffer.concat(chunks), resolve)); + const buffer = terminal.buffer.active; + const rows = Array.from({ length: buffer.length }, (_, i) => { + const line = buffer.getLine(i)!; + return Array.from({ length: metadata.cols }, (_cell, col) => ({ + char: line.getCell(col)?.getChars() || " ", + })); + }); + const state: TerminalState = { + rows: metadata.rows, + cols: metadata.cols, + scrollback: rows.slice(0, buffer.baseY), + grid: rows.slice(buffer.baseY), + cursor: { row: buffer.cursorY, col: buffer.cursorX }, + }; + terminal.dispose(); + return { state, revision: metadata.revision }; } function rowToText(row: TerminalRow): string { @@ -76,20 +153,13 @@ function readRenderedTokenIndexesFromState(state: TerminalState): number[] { return indexes; } -function createTerminalState(): TerminalState { - const blankCell = { char: " " }; - return { - rows: 1, - cols: 1, - grid: [[blankCell]], - scrollback: [], - cursor: { row: 0, col: 0 }, - }; +function createTerminalState(): WorkerTerminalState { + return { rows: 1, cols: 1, hasOutput: false }; } class FakeTerminalWorker extends EventEmitter { connected = true; - killed = false; + readonly workerPid = 1; readonly sentMessages: TerminalWorkerRequest[] = []; send(message: TerminalWorkerRequest, callback: (error: Error | null) => void): boolean { @@ -100,14 +170,7 @@ class FakeTerminalWorker extends EventEmitter { disconnect(): void { this.connected = false; - this.emit("exit", 0, null); - } - - kill(): boolean { - this.killed = true; - this.connected = false; - this.emit("exit", 0, null); - return true; + this.emit("close"); } emitWorkerMessage(message: TerminalWorkerToParentMessage): void { @@ -115,8 +178,31 @@ class FakeTerminalWorker extends EventEmitter { } } -let manager: TerminalManager | null = null; +let manager: DaemonTerminalManager | null = null; const temporaryDirs: string[] = []; + +// A real detached worker in a throwaway home; afterEach closes its terminals and the worker. +async function startRealWorkerManager( + options: { + getTerminalActivityUrl?: () => string | null; + requestTimeoutMs?: number; + paseoHome?: string; + } = {}, +): Promise { + const { paseoHome = createTemporaryHome(), ...rest } = options; + return startWorkerTerminalManager({ + paseoHome, + paseoVersion: "0.0.0-test", + logger: pino({ level: "silent" }), + ...rest, + }); +} + +function createTemporaryHome(): string { + const paseoHome = mkdtempSync(join(tmpdir(), "worker-terminal-manager-home-")); + temporaryDirs.push(paseoHome); + return paseoHome; +} const terminalSessions: TerminalSession[] = []; function trackTerminal(session: TerminalSession): TerminalSession { @@ -150,7 +236,7 @@ afterEach(async () => { .catch(() => {}), ), ); - manager?.killAll(); + await manager?.closeTerminals(); manager = null; while (temporaryDirs.length > 0) { const dir = temporaryDirs.pop(); @@ -160,10 +246,187 @@ afterEach(async () => { } }); +it("retires a killed worker's sessions and shares one replacement across concurrent creates", async () => { + const paseoHome = createTemporaryHome(); + manager = await startRealWorkerManager({ paseoHome }); + manager.registerCwdEnv({ cwd: paseoHome, env: { QA_RECOVERY_ENV: "retained" } }); + const terminal = await manager.createTerminal({ + workspaceId: "ws-recovery", + cwd: paseoHome, + ...nodeTerminalCommand( + "process.stdin.on('data', chunk => process.stdout.write('echo:' + process.env.QA_RECOVERY_ENV + ':' + chunk)); setInterval(() => {}, 1000)", + ), + }); + const records = await listTerminalWorkerRecords(paseoHome); + const file = records.find((entry) => !("error" in entry)); + if (!file || "error" in file) throw new Error("Missing worker record"); + const changes: string[][] = []; + manager.subscribeTerminalsChanged((event) => + changes.push(event.terminals.map((item) => item.id)), + ); + const exits: unknown[] = []; + terminal.onExit((info) => exits.push(info)); + process.kill(file.record.pid, "SIGKILL"); + await waitForCondition(() => manager!.getTerminal(terminal.id) === undefined, 10000); + expect(changes).toContainEqual([]); + expect(exits).toHaveLength(1); + const sessions = await Promise.all( + Array.from({ length: 4 }, () => + manager!.createTerminal({ + workspaceId: "ws-recovery", + cwd: paseoHome, + ...nodeTerminalCommand( + "process.stdin.on('data', chunk => process.stdout.write('echo:' + process.env.QA_RECOVERY_ENV + ':' + chunk)); setInterval(() => {}, 1000)", + ), + }), + ), + ); + for (const session of sessions) { + const output: string[] = []; + session.subscribe((message) => { + if (message.type === "output") output.push(message.data); + }); + session.send({ type: "input", data: "recovered\r" }); + await waitForCondition(() => output.join("").includes("echo:retained:recovered"), 10000); + } + expect(await manager.getTerminals(paseoHome)).toHaveLength(4); + const remaining = (await listTerminalWorkerRecords(paseoHome)).filter( + (entry) => !("error" in entry), + ); + expect(remaining).toHaveLength(1); +}, 30000); + +it("reconnects a live worker without replacing terminal sessions or processes", async () => { + const paseoHome = createTemporaryHome(); + manager = await startRealWorkerManager({ paseoHome }); + const terminal = await manager.createTerminal({ + workspaceId: "ws-reconnect", + cwd: paseoHome, + ...nodeTerminalCommand( + "process.stdin.on('data', chunk => process.stdout.write('echo:' + chunk)); setInterval(() => {}, 1000)", + ), + }); + const [before] = await workerRecords(paseoHome); + const pids = await recordedTerminalPids(paseoHome); + let replayRequests = 0; + terminal.subscribe((message) => { + if (message.type === "snapshotReady") replayRequests += 1; + }); + // A second authenticated controller replaces the daemon's socket. The process stays alive. + const competitor = await connectTerminalWorker({ + socketPath: before!.socketPath, + secret: before!.secret, + }); + await waitForCondition(() => !competitor.connected, 10000); + await waitForCondition(async () => { + try { + return (await readReplay(manager!, terminal.id)) !== null; + } catch { + return false; + } + }, 10000); + await waitForCondition(() => replayRequests > 0, 1000); + expect(manager.getTerminal(terminal.id)).toBe(terminal); + expect(await recordedTerminalPids(paseoHome)).toEqual(pids); + expect((await workerRecords(paseoHome)).map((record) => record.pid)).toEqual([before!.pid]); + const output: string[] = []; + terminal.subscribe((message) => { + if (message.type === "output") output.push(message.data); + }); + terminal.send({ type: "input", data: "reconnected\r" }); + await waitForCondition(() => output.join("").includes("echo:reconnected"), 10000); +}, 30000); + +it.each(["detach", "closeTerminals"] as const)( + "does not replace a failed worker during %s", + async (operation) => { + const paseoHome = createTemporaryHome(); + manager = await startRealWorkerManager({ paseoHome }); + await manager.createTerminal({ + workspaceId: "ws-stop-recovery", + cwd: paseoHome, + ...nodeTerminalCommand("setInterval(() => {}, 1000)"), + }); + const [record] = await workerRecords(paseoHome); + process.kill(record!.pid, "SIGKILL"); + await manager[operation](); + await expect( + manager.createTerminal({ workspaceId: "ws-stop-recovery", cwd: paseoHome }), + ).rejects.toBeInstanceOf(NoTerminalWorkerAvailableError); + await manager.closeTerminals(); + expect(await workerRecords(paseoHome)).toEqual([]); + }, + 30000, +); + +it.each(["detach", "closeTerminals"] as const)( + "does not leak a replacement stopped during launch by %s", + async (operation) => { + const paseoHome = createTemporaryHome(); + manager = await startRealWorkerManager({ paseoHome }); + const terminal = await manager.createTerminal({ + workspaceId: "ws-launch-race", + cwd: paseoHome, + ...nodeTerminalCommand("setInterval(() => {}, 1000)"), + }); + const [record] = await workerRecords(paseoHome); + process.kill(record!.pid, "SIGKILL"); + await waitForCondition(() => !manager!.getTerminal(terminal.id), 10000); + const creating = manager.createTerminal({ workspaceId: "ws-launch-race", cwd: paseoHome }); + const rejected = expect(creating).rejects.toBeInstanceOf(NoTerminalWorkerAvailableError); + await manager[operation](); + await rejected; + await waitForCondition(async () => (await workerRecords(paseoHome)).length === 0, 10000); + expect(await manager.getTerminals(paseoHome)).toEqual([]); + }, + 30000, +); + +it.each(["current", "draining"] as const)( + "keeps the peer usable when the %s worker dies", + async (target) => { + const paseoHome = createTemporaryHome(); + const seeds = [ + await launchDetachedWorkerWithTerminal(paseoHome), + await launchDetachedWorkerWithTerminal(paseoHome), + ]; + // Exercise an existing seed adopted as current; launch age does not imply draining ownership. + const [firstAdopted] = await workerRecords(paseoHome); + const seed = seeds.find((candidate) => candidate.workerPid === firstAdopted!.pid)!; + manager = await startRealWorkerManager({ paseoHome }); + const added = await manager.createTerminal({ + workspaceId: "ws-peer", + cwd: seed.cwd, + ...nodeTerminalCommand("setInterval(() => {}, 1000)"), + }); + const records = await workerRecords(paseoHome); + const current = records.find((record) => + record.terminals.some((terminal) => terminal.id === added.id), + )!; + const draining = records.find((record) => record.pid !== current.pid)!; + const drainingId = draining.terminals[0]!.id; + const deadId = target === "current" ? added.id : drainingId; + const healthyId = target === "current" ? drainingId : added.id; + const healthy = manager.getTerminal(healthyId); + expect(healthy).toBeDefined(); + process.kill(target === "current" ? current.pid : draining.pid, "SIGKILL"); + await waitForCondition(() => !manager!.getTerminal(deadId), 10000); + expect(manager.getTerminal(healthyId)).toBe(healthy); + expect(await readReplay(manager, healthyId)).not.toBeNull(); + await manager.createTerminal({ + workspaceId: "ws-peer", + cwd: seed.cwd, + ...nodeTerminalCommand("setInterval(() => {}, 1000)"), + }); + expect((await workerRecords(paseoHome)).length).toBeLessThanOrEqual(2); + }, + 30000, +); + it("creates a terminal through the worker and streams output", async () => { const cwd = mkdtempSync(join(tmpdir(), "worker-terminal-manager-output-")); temporaryDirs.push(cwd); - manager = createWorkerTerminalManager(); + manager = await startRealWorkerManager(); const session = trackTerminal( await manager.createTerminal({ workspaceId: "ws-test", @@ -177,38 +440,33 @@ it("creates a terminal through the worker and streams output", async () => { }), ); const messages: string[] = []; - let snapshots = 0; + let readinessEvents = 0; const unsubscribe = session.subscribe((message) => { if (message.type === "output") { messages.push(message.data); } - if (message.type === "snapshot") { - snapshots += 1; + if (message.type === "snapshotReady") { + readinessEvents += 1; } }); await new Promise((resolve) => setTimeout(resolve, 100)); - const snapshotsBeforeOutput = snapshots; + expect(readinessEvents).toBe(1); session.send({ type: "input", data: "hello\r" }); - await waitForCondition( - () => - messages.join("").includes("worker-output:hello") || - getVisibleText(session).includes("worker-output:hello"), - 10000, - ); + await waitForCondition(() => messages.join("").includes("worker-output:hello"), 10000); await new Promise((resolve) => setTimeout(resolve, 100)); unsubscribe(); - expect(messages.join("") + getVisibleText(session)).toContain("worker-output:hello"); - expect(snapshots).toBe(snapshotsBeforeOutput); + expect(messages.join("")).toContain("worker-output:hello"); + expect(readinessEvents).toBe(1); }); it("delivers rapid small writes complete and in order through worker coalescing", async () => { const cwd = mkdtempSync(join(tmpdir(), "worker-terminal-manager-coalesce-")); temporaryDirs.push(cwd); const burstGatePath = join(cwd, "burst-ready"); - manager = createWorkerTerminalManager(); + manager = await startRealWorkerManager(); // The file gate starts the burst after this test subscribes without depending // on platform-specific PTY input echo/canonical-mode behavior. const session = trackTerminal( @@ -237,19 +495,19 @@ it("delivers rapid small writes complete and in order through worker coalescing" session.subscribe((message) => { if (message.type === "output") { events.push({ type: "output", data: message.data }); - } else if (message.type === "snapshot" || message.type === "snapshotReady") { + } else if (message.type === "snapshotReady") { events.push({ type: message.type }); } }); - // Let the snapshot subscription settle, then trigger the burst. + // Let readiness settle, then trigger the burst. await new Promise((resolve) => setTimeout(resolve, 100)); writeFileSync(burstGatePath, "go"); const expected = Array.from({ length: 500 }, (_, index) => index); let received: number[] = []; await waitForCondition(async () => { - const snapshot = await manager!.getTerminalState(session.id); + const snapshot = await readReplay(manager!, session.id); received = snapshot ? readRenderedTokenIndexesFromState(snapshot.state) : []; return expected.every((value, index) => received[index] === value); }, 10000); @@ -258,20 +516,19 @@ it("delivers rapid small writes complete and in order through worker coalescing" await waitForCondition(() => events.some((event) => event.type === "output"), 10000); - // No snapshot may land after output it should have preceded: every snapshot - // event must come before the first output event. + // Readiness precedes the ordered live stream. const firstOutputIndex = events.findIndex((event) => event.type === "output"); expect(firstOutputIndex).toBeGreaterThanOrEqual(0); - const snapshotAfterOutput = events + const readinessAfterOutput = events .slice(firstOutputIndex + 1) - .find((event) => event.type === "snapshot" || event.type === "snapshotReady"); - expect(snapshotAfterOutput).toBeUndefined(); + .find((event) => event.type === "snapshotReady"); + expect(readinessAfterOutput).toBeUndefined(); }); it("pulls fresh terminal state from the worker authority", async () => { const cwd = mkdtempSync(join(tmpdir(), "worker-terminal-manager-state-")); temporaryDirs.push(cwd); - manager = createWorkerTerminalManager(); + manager = await startRealWorkerManager(); const session = trackTerminal( await manager.createTerminal({ workspaceId: "ws-test", @@ -285,7 +542,7 @@ it("pulls fresh terminal state from the worker authority", async () => { let visibleText = ""; await waitForCondition(async () => { - const snapshot = await manager!.getTerminalState(session.id); + const snapshot = await readReplay(manager!, session.id); visibleText = snapshot ? getVisibleTextFromState(snapshot.state) : ""; return visibleText.includes("worker-state-ready"); }, 10000); @@ -298,11 +555,11 @@ it("pulls fresh terminal state from the worker authority", async () => { // preamble-caching contract is verified on Linux/macOS; the daemon's input-mode // handling runs identically on every platform once the escape is observed. it.skipIf(isPlatform("win32"))( - "caches the input-mode replay preamble from the worker after getTerminalState", + "caches input modes from worker output independently of replay capture", async () => { const cwd = mkdtempSync(join(tmpdir(), "worker-terminal-manager-preamble-")); temporaryDirs.push(cwd); - manager = createWorkerTerminalManager(); + manager = await startRealWorkerManager(); // \x1b[>1u pushes kitty keyboard flag 1, which the worker's input-mode // tracker records and reflects in its replay preamble (\x1b[=1;1u). const session = trackTerminal( @@ -316,11 +573,10 @@ it.skipIf(isPlatform("win32"))( }), ); - await waitForCondition(async () => { - const snapshot = await manager!.getTerminalState(session.id); - return snapshot !== null && session.getReplayPreamble() === "\x1b[=1;1u"; - }, 10000); - + await waitForCondition(() => session.getReplayPreamble() === "\x1b[=1;1u", 10000); + // Initial shared modes must be ready without a replay response repairing the cache. + expect(session.getReplayPreamble()).toBe("\x1b[=1;1u"); + expect(await readReplay(manager!, session.id)).not.toBeNull(); expect(session.getReplayPreamble()).toBe("\x1b[=1;1u"); }, ); @@ -328,7 +584,7 @@ it.skipIf(isPlatform("win32"))( it("refreshes cached terminal title after worker title changes", async () => { const cwd = mkdtempSync(join(tmpdir(), "worker-terminal-manager-title-")); temporaryDirs.push(cwd); - manager = createWorkerTerminalManager(); + manager = await startRealWorkerManager(); const session = trackTerminal( await manager.createTerminal({ workspaceId: "ws-test", @@ -342,28 +598,28 @@ it("refreshes cached terminal title after worker title changes", async () => { await waitForCondition(() => session.getTitle() === "Build Output", 10000); - expect(session.getState().title).toBe("Build Output"); + expect(session.getTitle()).toBe("Build Output"); }); it("refreshes cached terminal size after worker resize", async () => { const cwd = mkdtempSync(join(tmpdir(), "worker-terminal-manager-resize-")); temporaryDirs.push(cwd); - manager = createWorkerTerminalManager(); + manager = await startRealWorkerManager(); const session = trackTerminal(await manager.createTerminal({ cwd, workspaceId: "ws-test" })); session.send({ type: "resize", rows: 10, cols: 40 }); - const snapshot = await manager.getTerminalState(session.id); + const snapshot = await readReplay(manager, session.id); expect(snapshot?.state.rows).toBe(10); expect(snapshot?.state.cols).toBe(40); - expect(session.getState().rows).toBe(10); - expect(session.getState().cols).toBe(40); + expect(session.getSize().rows).toBe(10); + expect(session.getSize().cols).toBe(40); }); it("captures terminal output from the worker authority", async () => { const cwd = mkdtempSync(join(tmpdir(), "worker-terminal-manager-capture-")); temporaryDirs.push(cwd); - manager = createWorkerTerminalManager(); + manager = await startRealWorkerManager(); const session = trackTerminal(await manager.createTerminal({ cwd, workspaceId: "ws-test" })); session.send({ type: "input", data: "echo hello world\r" }); @@ -382,7 +638,7 @@ it("does not surface fire-and-forget send timeouts as unhandled rejections", asy const worker = new FakeTerminalWorker(); manager = createWorkerTerminalManager({ requestTimeoutMs: 5, - forkWorker: () => worker, + worker, }); worker.emitWorkerMessage({ @@ -416,7 +672,7 @@ it("does not surface fire-and-forget send timeouts as unhandled rejections", asy }); it("keeps registered cwd env inheritance behind the worker manager interface", async () => { - manager = createWorkerTerminalManager(); + manager = await startRealWorkerManager(); const cwd = mkdtempSync(join(tmpdir(), "worker-terminal-manager-env-")); temporaryDirs.push(cwd); const markerPath = join(cwd, "env.txt"); @@ -449,7 +705,7 @@ it("injects parent-minted terminal activity env through the worker", async () => temporaryDirs.push(cwd); const envPath = join(cwd, "activity-env.json"); const activityUrl = "http://127.0.0.1:12345/api/terminal-activity"; - manager = createWorkerTerminalManager({ + manager = await startRealWorkerManager({ getTerminalActivityUrl: () => activityUrl, }); @@ -496,8 +752,218 @@ it("injects parent-minted terminal activity env through the worker", async () => expect(env.path?.split(delimiter)[0]).toBe(paseoCliBinDir); }); +it("adopts a detached worker's terminals with their activity tokens and keeps them usable", async () => { + const paseoHome = createTemporaryHome(); + const cwd = mkdtempSync(join(tmpdir(), "worker-terminal-manager-adopt-")); + temporaryDirs.push(cwd); + const envPath = join(cwd, "adopt-env.json"); + const first = await startRealWorkerManager({ paseoHome }); + const created = await first.createTerminal({ + workspaceId: "ws-adopt", + cwd, + ...nodeTerminalCommand(` + require("node:fs").writeFileSync( + ${JSON.stringify(envPath)}, + JSON.stringify({ token: process.env.PASEO_ACTIVITY_TOKEN }), + ); + process.stdin.on("data", (chunk) => { + process.stdout.write("adopted-output:" + chunk.toString()); + }); + setInterval(() => {}, 1000); + `), + }); + await waitForCondition(() => existsSync(envPath), 10000); + const { token } = JSON.parse(readFileSync(envPath, "utf8")) as { token: string }; + + await first.detach(); + manager = await startRealWorkerManager({ paseoHome }); + + const adopted = manager.getTerminal(created.id); + expect(adopted?.workspaceId).toBe("ws-adopt"); + expect(await manager.getTerminals(cwd)).toHaveLength(1); + expect(manager.validateTerminalActivityToken(created.id, token)).toBe("valid"); + const messages: string[] = []; + adopted?.subscribe((message) => { + if (message.type === "output") messages.push(message.data); + }); + adopted?.send({ type: "input", data: "after-adopt\r" }); + await waitForCondition(() => messages.join("").includes("adopted-output:after-adopt"), 10000); +}); + +function isProcessAlive(pid: number): boolean { + try { + process.kill(pid, 0); + return true; + } catch { + return false; + } +} + +// The terminals the worker itself recorded, read from its own record file. +async function recordedTerminalPids(paseoHome: string): Promise> { + const pids = new Map(); + const directory = terminalWorkerDirectory(paseoHome); + for (const name of readdirSync(directory).filter((entry) => /^\d+\.json$/.test(entry))) { + for (const entry of (await readTerminalWorkerRecord(join(directory, name))).terminals) { + pids.set(entry.id, entry.pid); + } + } + return pids; +} + +it.each([false, true])( + "never adopts a live worker's terminals after a kill cleanup it could not finish, even once the worker rewrites its record (held reader: %s)", + async (holdReader) => { + const paseoHome = createTemporaryHome(); + const cwd = mkdtempSync(join(tmpdir(), "worker-terminal-manager-unfinished-kill-")); + temporaryDirs.push(cwd); + const first = await startRealWorkerManager({ paseoHome }); + manager = first; + const exitRequestPath = join(cwd, "exit-requested"); + const exitObservedPath = join(cwd, "exit-observed"); + const ending = await first.createTerminal({ + workspaceId: "ws-unfinished-kill", + cwd, + ...nodeTerminalCommand(` + const { existsSync, writeFileSync } = require("node:fs"); + setInterval(() => { + if (existsSync(${JSON.stringify(exitRequestPath)})) { + writeFileSync(${JSON.stringify(exitObservedPath)}, ""); + process.exit(0); + } + }, 25); + `), + }); + const remaining = await first.createTerminal({ + workspaceId: "ws-unfinished-kill", + cwd, + ...nodeTerminalCommand("setInterval(() => {}, 1000);"), + }); + const pids = await recordedTerminalPids(paseoHome); + const endingPid = pids.get(ending.id)!; + const remainingPid = pids.get(remaining.id)!; + const [record] = await workerRecords(paseoHome); + + // A kill cleanup whose process table read fails signals nothing and leaves the worker live. + const inspector = createTerminalWorkerProcessInspector(); + await expect( + reapTerminalWorkers({ + paseoHome, + inspector: { + ...inspector, + listProcesses: () => Promise.reject(new Error("ps timed out")), + }, + }), + ).rejects.toBeInstanceOf(TerminalCleanupNotConfirmedError); + expect((await readUnconfirmedTerminalCleanup(paseoHome)).length).toBeGreaterThan(0); + + // Keep an ordinary reader open until the worker delivers the terminal exit. + // Windows cannot replace the record while this handle is open. The exit must + // still reach the controller, and publication must recover after release. + const recordFd = holdReader + ? openSync(terminalWorkerRecordPath(paseoHome, record!.pid), "r") + : null; + try { + writeFileSync(exitRequestPath, ""); + await waitForCondition(() => first.getTerminal(ending.id) === undefined, 10000); + expect(existsSync(exitObservedPath)).toBe(true); + expect(isProcessAlive(endingPid)).toBe(false); + } finally { + if (recordFd !== null) closeSync(recordFd); + } + await waitForCondition( + async () => !(await recordedTerminalPids(paseoHome)).has(ending.id), + 10000, + ); + expect((await readUnconfirmedTerminalCleanup(paseoHome)).length).toBeGreaterThan(0); + + await first.detach(); + manager = await startRealWorkerManager({ paseoHome }); + + expect(manager.getTerminal(remaining.id)).toBeUndefined(); + expect(await manager.getTerminals(cwd)).toEqual([]); + expect(await readUnconfirmedTerminalCleanup(paseoHome)).toEqual([]); + const original = record!.terminals.find((entry) => entry.id === remaining.id)!; + // Startup can launch a new worker after cleanup and Windows can reuse the old PID. + // Require the original process to be gone, not the numeric PID to remain unused. + await expect + .poll( + async () => + !isProcessAlive(remainingPid) || + classifyTerminalProgramProcess(original, await inspector.inspect(remainingPid)).status === + "unrelated", + { timeout: 10000 }, + ) + .toBe(true); + }, +); + +// The worker's own `ps`, delayed: a program that exits while the worker reads its birth time +// lands its exit in the middle of creation. Only the worker launched while this PATH is set sees +// the shim; the PATH is restored as soon as it is up. +async function startWorkerWithSlowProcessTable( + delaySeconds: number, + options: { paseoHome?: string; requestTimeoutMs?: number } = {}, +): Promise { + const realPs = (process.env.PATH ?? "") + .split(delimiter) + .map((dir) => join(dir, "ps")) + .find((candidate) => existsSync(candidate)); + if (!realPs) throw new Error("ps not found on PATH"); + const shimDir = createTemporaryHome(); + writeFileSync(join(shimDir, "ps"), `#!/bin/sh\nsleep ${delaySeconds}\nexec ${realPs} "$@"\n`, { + mode: 0o755, + }); + const originalPath = process.env.PATH; + process.env.PATH = `${shimDir}${delimiter}${originalPath ?? ""}`; + try { + return await startRealWorkerManager(options); + } finally { + process.env.PATH = originalPath; + } +} + +async function expectCompletedShortCommand( + terminalManager: DaemonTerminalManager, + script: string, +): Promise { + const cwd = mkdtempSync(join(tmpdir(), "worker-terminal-manager-short-")); + temporaryDirs.push(cwd); + + const session = await terminalManager.createTerminal({ + workspaceId: "ws-test", + cwd, + command: "/bin/sh", + args: ["-c", script], + }); + + await waitForCondition(() => session.getExitInfo() !== null, 10000); + expect(session.getExitInfo()?.exitCode).toBe(0); + expect(terminalManager.getTerminal(session.id)).toBeUndefined(); + expect(await terminalManager.getTerminals(cwd)).toEqual([]); + expect(await readReplay(terminalManager, session.id)).toBeNull(); +} + +it.skipIf(isPlatform("win32"))( + "creates a short command that finishes before creation returns, with its exit", + async () => { + manager = await startRealWorkerManager(); + for (let attempt = 0; attempt < 3; attempt += 1) { + await expectCompletedShortCommand(manager, "echo short; exit 0"); + } + }, +); + +it.skipIf(isPlatform("win32"))( + "publishes the creation before an exit that arrives while the program is being recorded", + async () => { + manager = await startWorkerWithSlowProcessTable(0.3); + await expectCompletedShortCommand(manager, "sleep 0.1; echo short; exit 0"); + }, +); + it("starts the default shell through the worker and accepts quoted commands", async () => { - manager = createWorkerTerminalManager(); + manager = await startRealWorkerManager(); const cwd = mkdtempSync(join(tmpdir(), "worker-terminal-manager-shell-")); temporaryDirs.push(cwd); const markerPath = join(cwd, "shell quoted marker.txt"); @@ -518,7 +984,7 @@ it("lists subdirectory terminals when querying the workspace root", async () => const subdirCwd = join(rootCwd, "apps", "mobile"); mkdirSync(subdirCwd, { recursive: true }); temporaryDirs.push(rootCwd); - manager = createWorkerTerminalManager(); + manager = await startRealWorkerManager(); const created = trackTerminal( await manager.createTerminal({ workspaceId: "ws-test", @@ -536,7 +1002,7 @@ it("lists terminals locally without waiting on the worker", async () => { const worker = new FakeTerminalWorker(); manager = createWorkerTerminalManager({ requestTimeoutMs: 5, - forkWorker: () => worker, + worker, }); worker.emitWorkerMessage({ @@ -577,7 +1043,7 @@ it("includes only stamped terminals in workspace-scoped local reads", async () = const worker = new FakeTerminalWorker(); manager = createWorkerTerminalManager({ requestTimeoutMs: 5, - forkWorker: () => worker, + worker, }); worker.emitWorkerMessage({ @@ -629,7 +1095,7 @@ it("rejects non-absolute cwd in getTerminals", async () => { const worker = new FakeTerminalWorker(); manager = createWorkerTerminalManager({ requestTimeoutMs: 5, - forkWorker: () => worker, + worker, }); await expect(manager.getTerminals("relative/path")).rejects.toThrow("cwd must be absolute path"); @@ -639,7 +1105,7 @@ it("surfaces worker activity changes via getActivity, onActivityChange, and term const worker = new FakeTerminalWorker(); manager = createWorkerTerminalManager({ requestTimeoutMs: 50, - forkWorker: () => worker, + worker, }); worker.emitWorkerMessage({ @@ -702,7 +1168,7 @@ it("sets terminal activity through a worker request", async () => { const worker = new FakeTerminalWorker(); manager = createWorkerTerminalManager({ requestTimeoutMs: 50, - forkWorker: () => worker, + worker, }); worker.emitWorkerMessage({ type: "terminalCreated", @@ -735,7 +1201,7 @@ it("clears terminal attention through a worker request", async () => { const worker = new FakeTerminalWorker(); manager = createWorkerTerminalManager({ requestTimeoutMs: 50, - forkWorker: () => worker, + worker, }); worker.emitWorkerMessage({ type: "terminalCreated", @@ -766,7 +1232,7 @@ it("clears terminal attention through a worker request", async () => { it("clears finished attention on a real terminal", async () => { const cwd = mkdtempSync(join(tmpdir(), "worker-terminal-manager-attention-")); temporaryDirs.push(cwd); - manager = createWorkerTerminalManager(); + manager = await startRealWorkerManager(); const session = trackTerminal( await manager.createTerminal({ workspaceId: "ws-test", @@ -802,7 +1268,7 @@ it("clears finished attention on a real terminal", async () => { it("removes worker terminals after killAndWait", async () => { const cwd = mkdtempSync(join(tmpdir(), "worker-terminal-manager-kill-")); temporaryDirs.push(cwd); - manager = createWorkerTerminalManager(); + manager = await startRealWorkerManager(); const session = trackTerminal( await manager.createTerminal({ workspaceId: "ws-test", @@ -827,7 +1293,7 @@ it("produces one terminals-changed snapshot per title change", async () => { const worker = new FakeTerminalWorker(); manager = createWorkerTerminalManager({ requestTimeoutMs: 50, - forkWorker: () => worker, + worker, }); worker.emitWorkerMessage({ @@ -864,7 +1330,7 @@ it("produces one terminals-changed snapshot and one contribution event per activ const worker = new FakeTerminalWorker(); manager = createWorkerTerminalManager({ requestTimeoutMs: 50, - forkWorker: () => worker, + worker, }); worker.emitWorkerMessage({ @@ -914,7 +1380,7 @@ it("removes a killed worker terminal from terminalExit without duplicate snapsho const worker = new FakeTerminalWorker(); manager = createWorkerTerminalManager({ requestTimeoutMs: 50, - forkWorker: () => worker, + worker, }); const workingActivity = { state: "working" as const, changedAt: 1000 }; @@ -973,7 +1439,7 @@ it("does not resurrect a terminal that exited before its create response was han const worker = new FakeTerminalWorker(); manager = createWorkerTerminalManager({ requestTimeoutMs: 50, - forkWorker: () => worker, + worker, }); const snapshots: Array<{ cwd: string; terminalIds: string[] }> = []; @@ -1026,7 +1492,7 @@ it("replays the exit to a listener attached after a create that lost the race", const worker = new FakeTerminalWorker(); manager = createWorkerTerminalManager({ requestTimeoutMs: 50, - forkWorker: () => worker, + worker, }); const created = manager.createTerminal({ @@ -1074,7 +1540,7 @@ it("rejects createTerminal and registers nothing when the worker cannot start th const worker = new FakeTerminalWorker(); manager = createWorkerTerminalManager({ requestTimeoutMs: 50, - forkWorker: () => worker, + worker, }); const snapshots: Array<{ cwd: string; terminalIds: string[] }> = []; @@ -1104,3 +1570,1091 @@ it("rejects createTerminal and registers nothing when the worker cannot start th expect(await manager.getTerminals("/workspace")).toEqual([]); expect(snapshots).toEqual([]); }); + +// The live worker records in a home, by worker pid. +async function workerRecords(paseoHome: string): Promise { + return (await listTerminalWorkerRecords(paseoHome)).flatMap((file) => + "record" in file && !file.record.closing ? [file.record] : [], + ); +} + +// A worker launched while the override is set reports that protocol version; the variable is +// restored as soon as it is up, so later workers report the build's own. +async function startManagerWithWorkerProtocol( + paseoHome: string, + protocolVersion: number, +): Promise { + const previous = process.env[TERMINAL_WORKER_PROTOCOL_OVERRIDE_ENV]; + process.env[TERMINAL_WORKER_PROTOCOL_OVERRIDE_ENV] = String(protocolVersion); + try { + return await startRealWorkerManager({ paseoHome }); + } finally { + if (previous === undefined) delete process.env[TERMINAL_WORKER_PROTOCOL_OVERRIDE_ENV]; + else process.env[TERMINAL_WORKER_PROTOCOL_OVERRIDE_ENV] = previous; + } +} + +// A terminal running an idle program in a worker that reports `protocolVersion`, left running +// after its daemon lets go (stop --keep-terminals). +async function leaveWorkerWithTerminal( + paseoHome: string, + protocolVersion: number, +): Promise<{ terminalId: string; programPid: number; workerPid: number; cwd: string }> { + const cwd = mkdtempSync(join(tmpdir(), "worker-terminal-manager-protocol-")); + temporaryDirs.push(cwd); + const previous = await startManagerWithWorkerProtocol(paseoHome, protocolVersion); + const session = await previous.createTerminal({ + workspaceId: "ws-protocol", + cwd, + ...nodeTerminalCommand("setInterval(() => {}, 1000);"), + }); + const [record] = await workerRecords(paseoHome); + await previous.detach(); + return { + terminalId: session.id, + programPid: (await recordedTerminalPids(paseoHome)).get(session.id)!, + workerPid: record!.pid, + cwd, + }; +} + +it.each([1, 4])( + "hard cuts unreleased worker protocol %s, closing its terminals", + async (version) => { + const paseoHome = createTemporaryHome(); + const old = await leaveWorkerWithTerminal(paseoHome, version); + + manager = await startRealWorkerManager({ paseoHome }); + + await waitForCondition( + () => !isProcessAlive(old.workerPid) && !isProcessAlive(old.programPid), + 10000, + ); + expect(manager.getTerminal(old.terminalId)).toBeUndefined(); + const workers = await workerRecords(paseoHome); + expect(workers).toHaveLength(1); + expect(workers[0]!.protocolVersion).toBe(5); + }, +); + +it("leaves a worker from a newer Paseo running, reports it incompatible, and closes it on a kill stop", async () => { + const paseoHome = createTemporaryHome(); + const newer = await leaveWorkerWithTerminal(paseoHome, 6); + + manager = await startRealWorkerManager({ paseoHome }); + + const unavailable = manager.getUnavailableError?.(); + expect(unavailable).toBeInstanceOf(TerminalWorkerIncompatibleError); + expect(unavailable?.message).toContain("worker protocol 6"); + await expect(manager.getTerminals(newer.cwd)).rejects.toBeInstanceOf( + TerminalWorkerIncompatibleError, + ); + await expect( + manager.createTerminal({ workspaceId: "ws-protocol", cwd: newer.cwd }), + ).rejects.toBeInstanceOf(TerminalWorkerIncompatibleError); + expect(isProcessAlive(newer.programPid)).toBe(true); + expect((await workerRecords(paseoHome)).map((record) => record.pid)).toEqual([newer.workerPid]); + + await manager.closeTerminals(); + + expect(isProcessAlive(newer.workerPid)).toBe(false); + expect(isProcessAlive(newer.programPid)).toBe(false); + expect(await workerRecords(paseoHome)).toEqual([]); +}); + +// A worker launched on its own, as two daemons that each started one would leave it: running an +// idle program in a terminal, with no daemon attached. +async function launchDetachedWorkerWithTerminal( + paseoHome: string, + protocolVersion?: number, +): Promise<{ terminalId: string; workerPid: number; cwd: string }> { + const cwd = mkdtempSync(join(tmpdir(), "worker-terminal-manager-detached-")); + temporaryDirs.push(cwd); + const previous = process.env[TERMINAL_WORKER_PROTOCOL_OVERRIDE_ENV]; + if (protocolVersion !== undefined) { + process.env[TERMINAL_WORKER_PROTOCOL_OVERRIDE_ENV] = String(protocolVersion); + } + let launched: Awaited>; + try { + launched = await launchTerminalWorker({ paseoHome, paseoVersion: "0.0.0-test" }); + } finally { + if (previous === undefined) delete process.env[TERMINAL_WORKER_PROTOCOL_OVERRIDE_ENV]; + else process.env[TERMINAL_WORKER_PROTOCOL_OVERRIDE_ENV] = previous; + } + const worker = createWorkerTerminalManager({ + worker: await connectTerminalWorker({ + socketPath: launched.record.socketPath, + secret: launched.record.secret, + }), + }); + const session = await worker.createTerminal({ + workspaceId: "ws-detached", + cwd, + ...nodeTerminalCommand("setInterval(() => {}, 1000);"), + }); + await worker.detach(); + return { terminalId: session.id, workerPid: launched.record.pid, cwd }; +} + +// Worker pids alive in a home, from every record, closing ones included. +async function liveWorkerPids(paseoHome: string): Promise { + return (await listTerminalWorkerRecords(paseoHome)) + .flatMap((file) => ("record" in file ? [file.record.pid] : [])) + .filter(isProcessAlive) + .sort(); +} + +it.skipIf(isPlatform("win32"))( + "counts live workers whose cleanup could not be confirmed and never starts a third", + async () => { + const paseoHome = createTemporaryHome(); + const first = await launchDetachedWorkerWithTerminal(paseoHome); + const second = await launchDetachedWorkerWithTerminal(paseoHome); + // A kill cleanup that cannot read the process table signals nothing: both workers keep + // running with their records marked closing. + const inspector = createTerminalWorkerProcessInspector(); + await expect( + reapTerminalWorkers({ + paseoHome, + gracefulMs: 0, + inspector: { ...inspector, listProcesses: () => Promise.reject(new Error("ps timed out")) }, + }), + ).rejects.toBeInstanceOf(TerminalCleanupNotConfirmedError); + expect((await readUnconfirmedTerminalCleanup(paseoHome)).map((entry) => entry.role)).toContain( + "worker", + ); + + // The daemon's own retry fails the same way: only the full process table is unreadable. + const realPs = (process.env.PATH ?? "") + .split(delimiter) + .map((dir) => join(dir, "ps")) + .find((candidate) => existsSync(candidate)); + if (!realPs) throw new Error("ps not found on PATH"); + const shimDir = createTemporaryHome(); + writeFileSync( + join(shimDir, "ps"), + `#!/bin/sh\nif [ "$1" = "-A" ]; then echo "process table unavailable" >&2; exit 1; fi\nexec ${realPs} "$@"\n`, + { mode: 0o755 }, + ); + const originalPath = process.env.PATH; + process.env.PATH = `${shimDir}${delimiter}${originalPath ?? ""}`; + try { + manager = await startRealWorkerManager({ paseoHome }); + } finally { + process.env.PATH = originalPath; + } + + expect(await liveWorkerPids(paseoHome)).toEqual([first.workerPid, second.workerPid].sort()); + await expect( + manager.createTerminal({ workspaceId: "ws-detached", cwd: first.cwd }), + ).rejects.toThrow("2 terminal workers are already running"); + expect(await liveWorkerPids(paseoHome)).toEqual([first.workerPid, second.workerPid].sort()); + }, +); + +it("replays bounded ANSI chunks independently of live output and reconstructs the revision cut", async () => { + const cwd = createTemporaryHome(); + const finishBefore = join(cwd, "finish-before"); + manager = await startRealWorkerManager(); + const session = trackTerminal( + await manager.createTerminal({ + cwd, + workspaceId: "ws-replay", + rows: 8, + cols: 120, + ...nodeTerminalCommand(` + for (let i = 0; i < 800; i++) process.stdout.write("\\x1b[31m" + String(i).padStart(4, "0") + ":" + "x".repeat(100) + "\\x1b[0m\\r\\n"); + require("node:readline").createInterface({ input: process.stdin }).on("line", line => { + if (line !== "before") { process.stdout.write("LIVE-AFTER-REPLAY\\r\\n"); return; } + process.stdout.write("PRE-CUT"); + const finish = setInterval(() => { + if (!require("node:fs").existsSync(${JSON.stringify(finishBefore)})) return; + clearInterval(finish); + process.stdout.write("\\r\\n"); + }, 5); + }); + setInterval(() => {}, 1000); + `), + }), + ); + await waitForCondition( + async () => + (await manager!.captureTerminal(session.id)).lines.some((line) => line.startsWith("0799:")), + 10000, + ); + const events: string[] = []; + const replayEvents: string[] = []; + const liveOutputs: Array<{ data: string; revision?: number }> = []; + const chunks: Uint8Array[] = []; + let live = ""; + const unsubscribe = session.subscribe((event) => { + if (event.type === "output") { + events.push("live"); + liveOutputs.push(event); + live += event.data; + } + }); + session.send({ type: "input", data: "before\r" }); + await waitForCondition(() => live.includes("PRE-CUT"), 10000); + // A PTY may deliver the marker and its trailing newline separately. Finish + // that output before replay, so the two captures must describe the same cut. + writeFileSync(finishBefore, ""); + await waitForCondition(async () => { + const { lines } = await manager!.captureTerminal(session.id); + return lines.at(-2) === "PRE-CUT" && lines.at(-1) === ""; + }, 10000); + const expected = await manager.captureTerminal(session.id); + const metadata = await manager.replayTerminal(session.id, undefined, (event) => { + events.push(event.type); + replayEvents.push(event.type); + if (event.type === "begin") session.send({ type: "input", data: "go\r" }); + if (event.type === "data") chunks.push(event.data); + }); + await waitForCondition(() => live.includes("LIVE-AFTER-REPLAY"), 10000); + unsubscribe(); + // Existing live observers are independent of replay. Pre-cut output may also be + // flushed by capture before begin; only the replay events have begin/data/end order. + expect(events[0]).toBe("live"); + expect(replayEvents[0]).toBe("begin"); + expect(replayEvents.at(-1)).toBe("end"); + expect(replayEvents.slice(1, -1)).toEqual(chunks.map(() => "data")); + const beforeCut = liveOutputs.filter((output) => output.data.includes("PRE-CUT")); + const afterCut = liveOutputs.filter((output) => output.data.includes("LIVE-AFTER-REPLAY")); + expect(beforeCut).toHaveLength(1); + expect(afterCut).toHaveLength(1); + expect(beforeCut[0]!.revision).toBeDefined(); + expect(beforeCut[0]!.revision).toBeLessThanOrEqual(metadata!.revision); + expect(afterCut[0]!.revision).toBeGreaterThan(metadata!.revision); + expect(live.match(/LIVE-AFTER-REPLAY/g)).toHaveLength(1); + expect(chunks.length).toBeGreaterThan(1); + expect(chunks.every((chunk) => chunk.byteLength <= 64 * 1024)).toBe(true); + expect(metadata?.rows).toBe(8); + expect(metadata?.cols).toBe(120); + const terminal = new xterm.Terminal({ + rows: 8, + cols: 120, + scrollback: 1000, + allowProposedApi: true, + }); + try { + await new Promise((resolve) => terminal.write(Buffer.concat(chunks), resolve)); + const buffer = terminal.buffer.active; + expect( + Array.from({ length: buffer.length }, (_, i) => buffer.getLine(i)!.translateToString(true)), + ).toEqual(expected.lines); + expect(expected.lines.filter((line) => line.includes("PRE-CUT"))).toHaveLength(1); + expect(expected.lines.some((line) => line.includes("LIVE-AFTER-REPLAY"))).toBe(false); + expect(buffer.getLine(0)!.getCell(0)!.getFgColor()).toBe(1); + } finally { + terminal.dispose(); + } +}); + +it("completes a replay larger than the socket budget while a sibling stays usable", async () => { + const paseoHome = createTemporaryHome(); + const overflowProgress = join(paseoHome, "overflow-progress"); + manager = await startRealWorkerManager({ paseoHome }); + const terminal = trackTerminal( + await manager.createTerminal({ + cwd: paseoHome, + workspaceId: "ws-wide", + rows: 4, + cols: 1024, + ...nodeTerminalCommand(` + const row = Array.from({length: 1000}, (_, i) => "\\x1b[" + (31 + i % 2) + "mX").join(""); + for (let i = 0; i < 900; i++) process.stdout.write(row + "\\r\\n"); + // Seeing the marker must mean no trailing newline can still add history. + process.stdout.write("READY-WIDE"); + process.stdin.on("data", data => { if (data.toString().includes("small")) { process.stdout.write("SAME-TERMINAL-LIVE\\r\\n"); return; } process.stdout.write("q".repeat(8 * 1024 * 1024) + "\\r\\nRECOVERED-LIVE\\r\\n", () => require("node:fs").writeFileSync(${JSON.stringify(overflowProgress)}, "done")); }); + setInterval(() => {}, 1000); + `), + }), + ); + const siblingProgress = join(paseoHome, "sibling-progress"); + const sibling = trackTerminal( + await manager.createTerminal({ + cwd: paseoHome, + workspaceId: "ws-wide", + ...nodeTerminalCommand(` + let count = 0; + process.stdin.on("data", () => { + count++; + process.stdout.write((count > 1 ? "z".repeat(1024 * 1024) : "") + "SIBLING-ALIVE\\r\\n", () => require("node:fs").writeFileSync(${JSON.stringify(siblingProgress)}, String(count))); + }); + setInterval(() => {}, 1000); + `), + }), + ); + await waitForCondition( + async () => + (await manager!.captureTerminal(terminal.id)).lines.some((line) => + line.includes("READY-WIDE"), + ), + 20000, + ); + const seen: string[] = []; + const unsubscribe = sibling.subscribe((event) => { + if (event.type === "output") seen.push(event.data); + }); + let bytes = 0; + const metadata = await manager.replayTerminal(terminal.id, undefined, (event) => { + if (event.type === "data") bytes += event.data.byteLength; + if (event.type === "begin") { + sibling.send({ type: "input", data: "go\r" }); + } + }); + expect(bytes).toBeGreaterThan(4 * 1024 * 1024); + expect(metadata?.cols).toBe(1024); + await waitForCondition(() => seen.join("").includes("SIBLING-ALIVE"), 10000); + unsubscribe(); + expect(manager.getTerminal(sibling.id)).toBe(sibling); + const truncated = await manager.replayTerminal(terminal.id, { scrollbackLines: 200 }, () => {}); + expect(metadata!.retainedHistoryLines).toBeGreaterThan(200); + expect(truncated!.retainedHistoryLines).toBe(metadata!.retainedHistoryLines); + const concurrent = await Promise.all( + [0, 1].map(() => manager!.replayTerminal(terminal.id, { scrollbackLines: 200 }, () => {})), + ); + expect(concurrent.map((replay) => replay!.retainedHistoryLines)).toEqual([ + metadata!.retainedHistoryLines, + metadata!.retainedHistoryLines, + ]); + await manager.detach(); + const [record] = await workerRecords(paseoHome); + const socket = createConnection(record!.socketPath); + let began = false; + let ended = false; + let completed = false; + let resumedBytes = 0; + let cancelledReplayBegan = false; + let existingLiveOutput = ""; + const replayOrder: string[] = []; + const framed = attachFramedSocket(socket, (value) => { + const message = value as TerminalWorkerToParentMessage | { type: "helloAck" }; + if ( + message.type === "terminalMessage" && + message.terminalId === terminal.id && + message.message.type === "output" + ) { + existingLiveOutput += message.message.data; + replayOrder.push("live"); + } + if (message.type === "helloAck") { + framed.send({ type: "replayTerminal", terminalId: terminal.id, requestId: "stalled-replay" }); + } else if (message.type === "terminalReplay") { + if (message.requestId === "cancelled-replay") { + if (message.event.type === "begin") { + cancelledReplayBegan = true; + socket.pause(); + } + return; + } + if (message.event.type === "begin") { + began = true; + socket.pause(); + } + if (message.event.type === "data") resumedBytes += message.event.data.byteLength; + if (message.event.type === "end") { + ended = true; + replayOrder.push("end"); + } + } else if (message.type === "response" && message.requestId === "stalled-replay") + completed = message.ok; + }); + try { + framed.send({ type: "hello", secret: record!.secret, protocolVersion: 5 }); + await waitForCondition(() => began, 10000); + framed.send({ + type: "send", + terminalId: terminal.id, + requestId: "same-terminal-input", + message: { type: "input", data: "small\r" }, + }); + framed.send({ + type: "send", + terminalId: sibling.id, + requestId: "sibling-input", + message: { type: "input", data: "again\r" }, + }); + await waitForCondition( + () => existsSync(siblingProgress) && readFileSync(siblingProgress, "utf8") === "2", + 10000, + ); + await new Promise((resolve) => setTimeout(resolve, 150)); + expect(completed).toBe(false); + expect(socket.destroyed).toBe(false); + socket.resume(); + await waitForCondition(() => completed, 10000); + expect(ended).toBe(true); + expect(resumedBytes).toBe(bytes); + await waitForCondition(() => existingLiveOutput.includes("SAME-TERMINAL-LIVE"), 10000); + expect(existingLiveOutput.match(/SAME-TERMINAL-LIVE/g)).toHaveLength(1); + expect(replayOrder.indexOf("live")).toBeLessThan(replayOrder.indexOf("end")); + framed.send({ type: "replayTerminal", terminalId: terminal.id, requestId: "cancelled-replay" }); + await waitForCondition(() => cancelledReplayBegan, 10000); + // Replace a controller while its large replay is socket-paced. The original + // request must never leak frames or completion onto the replacement connection. + manager = await startRealWorkerManager({ paseoHome }); + socket.resume(); + await waitForCondition(() => socket.destroyed, 10000); + expect((await readReplay(manager, terminal.id))?.state.cols).toBe(1024); + } finally { + socket.destroy(); + } + expect( + (await manager!.captureTerminal(terminal.id)).lines.some((line) => line.includes("READY-WIDE")), + ).toBe(true); + const exitingReplay = await manager.replayTerminal( + terminal.id, + { scrollbackLines: 200 }, + (event) => { + if (event.type === "begin") manager!.killTerminal(terminal.id); + }, + ); + expect(exitingReplay!.cols).toBe(1024); + await waitForCondition(() => manager!.getTerminal(terminal.id) === undefined, 10000); + expect(manager.getTerminal(sibling.id)?.id).toBe(sibling.id); +}, 60000); + +function terminalViewers( + terminalManager: DaemonTerminalManager, + terminalId: string, + chunked = true, + getClientBufferedAmount?: (source: object) => number | null, +) { + const frames: Array<{ source: object; frame: TerminalStreamFrame }> = []; + const messages: Array<{ source: object; message: SessionOutboundMessage }> = []; + let blockedSource: object | null = null; + let started = false; + let finish!: (error?: Error) => void; + const block = new Promise((resolve, reject) => { + finish = (error) => (error ? reject(error) : resolve()); + }); + const delivery = new SessionDelivery( + (source, message) => { + messages.push({ source, message }); + }, + async (source, bytes) => { + const frame = decodeTerminalStreamFrame(bytes)!; + frames.push({ source, frame }); + if ( + source === blockedSource && + frame.opcode === (chunked ? TerminalStreamOpcode.ReplayBegin : TerminalStreamOpcode.Restore) + ) { + started = true; + await block; + } + }, + ); + const controller = new TerminalSessionController({ + terminalManager, + emit: (message) => { + delivery.reply(message); + }, + hasBinaryChannel: () => true, + supportsChunkedReplay: () => chunked, + getClientBufferedAmount, + isPathWithinRoot: () => true, + sessionLogger: pino({ level: "silent" }), + }); + return { + frames, + messages, + delivery, + controller, + block(source: object) { + blockedSource = source; + }, + started: () => started, + finish, + async attach( + source: object, + requestId: string, + restore: NonNullable = { + mode: "visible-snapshot", + scrollbackLines: 1000, + }, + ) { + delivery.attach(source, true); + const request = { + type: "subscribe_terminal_request" as const, + terminalId, + requestId, + restore, + }; + await delivery.request(source, request, () => controller.dispatch(request, delivery)); + }, + text(source: object) { + return frames + .filter((row) => row.source === source && row.frame.opcode === TerminalStreamOpcode.Output) + .map((row) => Buffer.from(row.frame.payload).toString("utf8")) + .join(""); + }, + ended(source: object) { + return messages.filter( + (row) => row.source === source && row.message.type === "terminal_stream_exit", + ); + }, + replayed(source: object) { + return frames.some( + (row) => row.source === source && row.frame.opcode === TerminalStreamOpcode.ReplayEnd, + ); + }, + }; +} + +it("isolates a failed app transport while another viewer of the same terminal stays live", async () => { + manager = await startRealWorkerManager(); + const session = trackTerminal( + await manager.createTerminal({ + cwd: createTemporaryHome(), + workspaceId: "two-viewers", + ...nodeTerminalCommand( + 'process.stdout.write("READY\\r\\n"); process.stdin.on("data", data => process.stdout.write("ECHO:" + data)); setInterval(() => {}, 1000);', + ), + }), + ); + await waitForCondition( + async () => + (await manager!.captureTerminal(session.id)).lines.some((line) => line.includes("READY")), + 10000, + ); + const viewers = terminalViewers(manager, session.id); + const desktop = {}, + phone = {}, + fresh = {}; + try { + await viewers.attach(desktop, "desktop"); + await waitForCondition(() => viewers.replayed(desktop), 10000); + await expect( + manager.replayTerminal(session.id, undefined, () => { + throw new Error("Consumer cancelled replay"); + }), + ).rejects.toThrow("Consumer cancelled replay"); + viewers.block(phone); + await viewers.attach(phone, "phone"); + await waitForCondition(viewers.started, 10000); + session.send({ type: "input", data: "BEFORE-FAILURE\r" }); + await waitForCondition(() => viewers.text(desktop).includes("ECHO:BEFORE-FAILURE"), 1500); + expect(viewers.ended(desktop)).toHaveLength(0); + expect(viewers.ended(phone)).toHaveLength(0); + viewers.finish(new Error("Phone socket closed")); + await viewers.delivery.detach(phone); + expect(viewers.ended(desktop)).toHaveLength(0); + session.send({ type: "input", data: "AFTER-FAILURE\r" }); + await waitForCondition(() => viewers.text(desktop).includes("ECHO:AFTER-FAILURE"), 10000); + expect(viewers.ended(desktop)).toHaveLength(0); + await viewers.attach(fresh, "fresh"); + await waitForCondition(() => viewers.replayed(fresh), 10000); + expect(manager.getTerminal(session.id)).toBe(session); + } finally { + viewers.finish(); + await viewers.delivery.close(); + } +}, 20000); + +it("keeps concurrent viewer replays and live output ordered behind slow app delivery", async () => { + manager = await startRealWorkerManager(); + const session = trackTerminal( + await manager.createTerminal({ + cwd: createTemporaryHome(), + workspaceId: "concurrent-delivery", + ...nodeTerminalCommand( + 'process.stdout.write("READY\\r\\n"); process.stdin.on("data", data => process.stdout.write("ECHO:" + data)); setInterval(() => {}, 1000);', + ), + }), + ); + await waitForCondition( + async () => (await manager!.captureTerminal(session.id)).lines.join("").includes("READY"), + 10000, + ); + const viewers = terminalViewers(manager, session.id); + const desktop = {}, + phone = {}, + concurrent = {}; + try { + await viewers.attach(desktop, "desktop"); + await waitForCondition(() => viewers.replayed(desktop), 10000); + viewers.block(phone); + await viewers.attach(phone, "phone"); + await waitForCondition(viewers.started, 10000); + await viewers.attach(concurrent, "concurrent"); + await waitForCondition(() => viewers.replayed(concurrent) && viewers.replayed(phone), 10000); + session.send({ type: "input", data: "DURING-DELIVERY\r" }); + await waitForCondition( + () => + viewers.text(phone).includes("ECHO:DURING-DELIVERY") && + viewers.text(desktop).includes("ECHO:DURING-DELIVERY"), + 3000, + ); + expect(viewers.text(phone).match(/ECHO:DURING-DELIVERY/g)).toHaveLength(1); + const order = viewers.frames + .filter((row) => row.source === phone) + .map((row) => row.frame.opcode); + expect(order.indexOf(TerminalStreamOpcode.Output)).toBeGreaterThan( + order.indexOf(TerminalStreamOpcode.ReplayEnd), + ); + expect(viewers.ended(phone)).toHaveLength(0); + expect(viewers.ended(desktop)).toHaveLength(0); + } finally { + viewers.finish(); + await viewers.delivery.close(); + } +}, 20000); + +it.each([true, false])( + "queues replay independently of app delivery past the worker deadline (chunked=%s)", + async (chunked) => { + const paseoHome = createTemporaryHome(); + // Slow program identification belongs to setup, not the replay request deadline. + // The POSIX shim deterministically exceeds 800 ms; Windows keeps its real OS path. + manager = isPlatform("win32") + ? await startRealWorkerManager({ paseoHome }) + : await startWorkerWithSlowProcessTable(1, { paseoHome }); + const created = await manager.createTerminal({ + cwd: paseoHome, + workspaceId: "slow-delivery", + ...nodeTerminalCommand( + 'process.stdout.write("READY\\r\\n"); process.stdin.on("data", data => process.stdout.write("ECHO:" + data)); setInterval(() => {}, 1000);', + ), + }); + await waitForCondition( + async () => (await manager!.captureTerminal(created.id)).lines.join("").includes("READY"), + 10000, + ); + await manager.detach(); + manager = await startRealWorkerManager({ paseoHome, requestTimeoutMs: 800 }); + const session = manager.getTerminal(created.id); + if (!session) throw new Error("Replay fixture did not adopt its prepared terminal"); + trackTerminal(session); + const viewers = terminalViewers(manager, session.id, chunked); + const phone = {}; + viewers.block(phone); + try { + await viewers.attach(phone, "slow-phone"); + await waitForCondition(viewers.started, 10000); + await new Promise((resolve) => setTimeout(resolve, 1100)); + expect(viewers.ended(phone)).toHaveLength(0); + expect((await manager.captureTerminal(session.id)).lines.join("")).toContain("READY"); + session.send({ type: "input", data: "AFTER-DEADLINE\r" }); + await waitForCondition(() => viewers.text(phone).includes("ECHO:AFTER-DEADLINE"), 3000); + } finally { + viewers.finish(); + await viewers.delivery.close(); + } + }, + 20000, +); + +it.each(["replacement", "socket-overflow"] as const)( + "recovers an attached restore viewer after worker %s", + async (loss) => { + const paseoHome = createTemporaryHome(); + const drained = join(paseoHome, "burst-drained"); + manager = await startRealWorkerManager({ paseoHome }); + const session = trackTerminal( + await manager.createTerminal({ + cwd: paseoHome, + workspaceId: "attached-reconnect", + ...nodeTerminalCommand( + `process.stdout.write("RETAINED\\r\\n"); process.stdin.on("data", data => { + if (data.toString().includes("BURST")) process.stdout.write("x".repeat(12 * 1024 * 1024) + "\\r\\nRETAINED-AFTER-LOSS\\r\\n", () => require("node:fs").writeFileSync(${JSON.stringify(drained)}, "done")); + else process.stdout.write("ECHO:" + data); + }); setInterval(() => {}, 1000);`, + ), + }), + ); + await waitForCondition( + async () => (await manager!.captureTerminal(session.id)).lines.join("").includes("RETAINED"), + 10000, + ); + const viewers = terminalViewers(manager, session.id); + const desktop = {}; + try { + await viewers.attach(desktop, "desktop"); + await waitForCondition(() => viewers.replayed(desktop), 10000); + viewers.frames.length = 0; + const [record] = await workerRecords(paseoHome); + if (loss === "replacement") { + const competitor = await connectTerminalWorker({ + socketPath: record!.socketPath, + secret: record!.secret, + }); + await waitForCondition(() => !competitor.connected, 10000); + } else { + session.send({ type: "input", data: "BURST\r" }); + // Stall only the daemon event loop. The detached worker and PTY keep running, + // filling the bounded worker socket and forcing its disconnect/re-adoption path. + const stall = new Int32Array(new SharedArrayBuffer(4)); + const deadline = Date.now() + 10000; + while (!existsSync(drained) && Date.now() < deadline) Atomics.wait(stall, 0, 0, 25); + expect(existsSync(drained)).toBe(true); + } + await waitForCondition(() => viewers.replayed(desktop), 10000); + const replay = viewers.frames + .filter((row) => row.frame.opcode === TerminalStreamOpcode.ReplayData) + .map((row) => Buffer.from(row.frame.payload).toString("utf8")) + .join(""); + expect(replay).toContain("RETAINED"); + if (loss === "socket-overflow") expect(replay).toContain("RETAINED-AFTER-LOSS"); + expect((await workerRecords(paseoHome)).map((worker) => worker.pid)).toEqual([record!.pid]); + session.send({ type: "input", data: "RECOVERED\r" }); + await waitForCondition(() => viewers.text(desktop).includes("ECHO:RECOVERED"), 3000); + expect(viewers.ended(desktop)).toHaveLength(0); + expect(manager.getTerminal(session.id)).toBe(session); + } finally { + await viewers.delivery.close(); + } + }, + 30000, +); + +it.each([true, false])( + "keeps live modes after a replay captured enabled=%s while restoring its own modes first", + async (enabled) => { + const on = "\x1b[?1h\x1b[?2004h"; + const off = "\x1b[?1l\x1b[?2004l"; + const captured = enabled ? on : ""; + const latest = enabled ? "" : on; + const live = (enabled ? off : on) + "MODE-LIVE"; + const worker = new FakeTerminalWorker(); + manager = createWorkerTerminalManager({ worker, requestTimeoutMs: 1000 }); + worker.emitWorkerMessage({ + type: "terminalCreated", + terminal: { + id: "mode-terminal", + name: "Terminal", + cwd: "/tmp", + workspaceId: "modes", + activity: null, + }, + state: createTerminalState(), + }); + worker.emitWorkerMessage({ + type: "terminalMessage", + terminalId: "mode-terminal", + replayPreamble: captured, + message: { type: "snapshotReady", revision: 1 }, + }); + const session = manager.getTerminal("mode-terminal")!; + const viewers = terminalViewers(manager, session.id); + const restoring = {}, + following = {}; + try { + await viewers.attach(restoring, "restoring"); + await waitForCondition( + () => worker.sentMessages.some((message) => message.type === "replayTerminal"), + 1000, + ); + const request = worker.sentMessages.find((message) => message.type === "replayTerminal")!; + const metadata = { + rows: 30, + cols: 120, + retainedHistoryLines: 10, + revision: 1, + replayPreamble: captured, + }; + worker.emitWorkerMessage({ + type: "terminalReplay", + requestId: request.requestId, + event: { type: "begin", metadata }, + }); + worker.emitWorkerMessage({ + type: "terminalReplay", + requestId: request.requestId, + event: { type: "data", data: Buffer.from("CAPTURE-A") }, + }); + worker.emitWorkerMessage({ + type: "terminalMessage", + terminalId: session.id, + replayPreamble: latest, + message: { type: "output", data: live, revision: 2 }, + }); + expect(session.getReplayPreamble()).toBe(latest); + worker.emitWorkerMessage({ + type: "terminalReplay", + requestId: request.requestId, + event: { type: "data", data: Buffer.from("CAPTURE-B") }, + }); + worker.emitWorkerMessage({ + type: "terminalReplay", + requestId: request.requestId, + event: { type: "end" }, + }); + worker.emitWorkerMessage({ + type: "response", + requestId: request.requestId, + ok: true, + result: metadata, + }); + await waitForCondition(() => viewers.text(restoring).includes("MODE-LIVE"), 1000); + expect(session.getReplayPreamble()).toBe(latest); + expect(viewers.text(restoring)).toBe(captured + live); + const sequence = viewers.frames + .filter((row) => row.source === restoring) + .map((row) => row.frame.opcode); + expect(sequence.indexOf(TerminalStreamOpcode.Output)).toBeGreaterThan( + sequence.indexOf(TerminalStreamOpcode.ReplayEnd), + ); + const modes = new TerminalInputModeTracker(); + modes.feed(session.getReplayPreamble()); + expect(encodeTerminalKeyInput({ key: "ArrowUp" }, { inputMode: modes.getState() })).toBe( + enabled ? "\x1b[A" : "\x1bOA", + ); + expect(modes.getState().bracketedPaste).toBe(!enabled); + await viewers.attach(following, "live-following", { mode: "live" }); + await waitForCondition(() => latest === "" || viewers.text(following).length > 0, 1000); + expect(viewers.text(following)).toBe(latest); + expect( + worker.sentMessages.filter((message) => message.type === "replayTerminal"), + ).toHaveLength(1); + } finally { + await viewers.delivery.close(); + } + }, +); + +it.each([3000, 12050])( + "retains ten thousand history rows and restores exact demands after %s printed rows", + async (count) => { + manager = await startRealWorkerManager(); + const gate = createTemporaryHome(); + const releaseNewline = join(gate, "newline"); + const session = trackTerminal( + await manager.createTerminal({ + cwd: createTemporaryHome(), + workspaceId: "ten-thousand", + rows: 4, + cols: 80, + ...nodeTerminalCommand( + `const fs=require("node:fs"); + const watcher=fs.watch(${JSON.stringify(gate)},()=>{ + if(fs.existsSync(${JSON.stringify(releaseNewline)})){ + watcher.close();process.stdout.write("\\r\\nROWS-COMPLETE"); + } + }); + for(let i=0;i<${count};i++) process.stdout.write("\\x1b[31mrow-"+String(i).padStart(5,"0")+" 界é🙂\\x1b[0m"+(i===${count}-1?"":"\\r\\n")); + setInterval(()=>{},1000)`, + ), + }), + ); + await waitForCondition( + async () => + (await manager!.captureTerminal(session.id, { start: -5 })).lines + .join("") + .includes("row-" + String(count - 1).padStart(5, "0")), + 15000, + ); + // A visible final label can precede its trailing CRLF. Hold that transition + // deliberately, then observe content on the following row before capture. + writeFileSync(releaseNewline, "release"); + await waitForCondition( + async () => + (await manager!.captureTerminal(session.id, { start: -1 })).lines[0] === "ROWS-COMPLETE", + 15000, + ); + for (const history of [0, 200, 1000, 10000]) { + const chunks: Uint8Array[] = []; + const metadata = await manager.replayTerminal( + session.id, + { scrollbackLines: history }, + (event) => { + if (event.type === "data") chunks.push(event.data); + }, + ); + expect(metadata).toMatchObject({ + rows: 4, + cols: 80, + retainedHistoryLines: Math.min(10000, count - 3), + }); + expect(chunks.every((chunk) => chunk.byteLength <= 64 * 1024)).toBe(true); + const restored = new xterm.Terminal({ + rows: 4, + cols: 80, + scrollback: 10000, + allowProposedApi: true, + }); + try { + await new Promise((resolve) => restored.write(Buffer.concat(chunks), resolve)); + const buffer = restored.buffer.active; + const labels = Array.from({ length: buffer.length }, (_, i) => + buffer.getLine(i)!.translateToString(true), + ).filter((line) => line.includes("row-")); + expect({ row: buffer.cursorY, col: buffer.cursorX }).toEqual({ row: 3, col: 13 }); + expect(buffer.getLine(buffer.length - 1)!.translateToString(true)).toBe("ROWS-COMPLETE"); + expect(labels).toHaveLength(Math.min(count, history + 3)); + expect(labels[0]).toContain("row-" + String(count - labels.length).padStart(5, "0")); + expect(labels.at(-1)).toContain("row-" + String(count - 1).padStart(5, "0") + " 界é🙂"); + } finally { + restored.dispose(); + } + } + }, + 30000, +); + +it.each([false, true])( + "shrinks real ten-thousand-row pressure recovery and preserves reattach (chunked=%s)", + async (chunked) => { + manager = await startRealWorkerManager(); + const session = trackTerminal( + await manager.createTerminal({ + cwd: createTemporaryHome(), + workspaceId: "pressure-history", + rows: 4, + cols: 120, + ...nodeTerminalCommand(` + process.stdin.setRawMode(true); + let row = 0; + function print(count) { + for(let i=0;i { + if(data.toString().includes("BURST")) { print(4000); process.stdout.write("BURST-DONE\\r\\n"); } + else process.stdout.write("ECHO:" + data.toString() + "\\r\\n"); + }); + setInterval(()=>{},1000); + `), + }), + ); + await waitForCondition( + async () => + (await manager!.captureTerminal(session.id, { start: -5 })).lines + .join("") + .includes("READY"), + 15000, + ); + const desktop = {}, + phone = {}, + fresh = {}; + let pressure = false; + const viewers = terminalViewers(manager, session.id, chunked, (source) => + source === phone && pressure ? 8 * 1024 * 1024 : 0, + ); + const restore = { mode: "full-snapshot" as const, scrollbackLines: 10000 }; + function payloads(source: object): Buffer[] { + const result: Buffer[] = []; + let chunks: Uint8Array[] = []; + for (const { source: owner, frame } of viewers.frames) { + if (owner !== source) continue; + if (frame.opcode === TerminalStreamOpcode.Restore) result.push(Buffer.from(frame.payload)); + if (frame.opcode === TerminalStreamOpcode.ReplayBegin) chunks = []; + if (frame.opcode === TerminalStreamOpcode.ReplayData) chunks.push(frame.payload); + if (frame.opcode === TerminalStreamOpcode.ReplayEnd) result.push(Buffer.concat(chunks)); + } + return result; + } + async function parse(payload: Uint8Array) { + const receiver = new xterm.Terminal({ + rows: 4, + cols: 120, + scrollback: 10000, + allowProposedApi: true, + }); + try { + await new Promise((resolve) => receiver.write(payload, resolve)); + const buffer = receiver.buffer.active; + return { + history: buffer.baseY, + text: Array.from({ length: buffer.length }, (_, i) => + buffer.getLine(i)!.translateToString(true), + ).join("\n"), + }; + } finally { + receiver.dispose(); + } + } + try { + await viewers.attach(desktop, "healthy", restore); + await viewers.attach(phone, "pressured", restore); + await waitForCondition( + () => payloads(phone).length === 1 && payloads(desktop).length === 1, + 15000, + ); + const initial = payloads(phone)[0]!; + expect((await parse(initial)).history).toBe(10000); + pressure = true; + session.send({ type: "input", data: "BURST" }); + await waitForCondition(() => payloads(phone).length >= 2, 15000); + pressure = false; + // The final burst marker may belong to the replay cut or to its live tail. + // Read the same replay/output exchange a renderer sees rather than assuming + // worker parsing and daemon request scheduling cut the burst at one point. + async function currentView(source: object) { + const frames = viewers.frames + .filter((row) => row.source === source) + .map((row) => row.frame); + const start = frames.findLastIndex( + (frame) => + frame.opcode === TerminalStreamOpcode.Restore || + frame.opcode === TerminalStreamOpcode.ReplayBegin, + ); + return parse( + Buffer.concat( + frames + .slice(start) + .filter( + (frame) => + frame.opcode === TerminalStreamOpcode.Restore || + frame.opcode === TerminalStreamOpcode.ReplayData || + frame.opcode === TerminalStreamOpcode.Output, + ) + .map((frame) => frame.payload), + ), + ); + } + await waitForCondition( + async () => + (await currentView(phone)).text.includes("BURST-DONE") && + (await currentView(desktop)).text.includes("BURST-DONE"), + 15000, + ); + const recovery = payloads(phone)[1]!; + const recovered = await parse(recovery); + expect(recovered.history).toBe(500); + expect(recovered.text).toContain("界é🙂"); + for (const source of [phone, desktop]) { + const indexes = [...(await currentView(source)).text.matchAll(/row-(\d+)/g)].map((match) => + Number(match[1]), + ); + expect(indexes.at(-1)).toBe(16049); + expect(indexes).toEqual(Array.from({ length: indexes.length }, (_, i) => indexes[0]! + i)); + } + expect(recovery.byteLength).toBeLessThan(initial.byteLength / 10); + expect(recovery.byteLength).toBeLessThan(256 * 1024); + expect(payloads(desktop)).toHaveLength(1); // The healthy peer keeps its full replay and live stream. + session.send({ type: "input", data: "AFTER-CATCH-UP" }); + await waitForCondition( + () => + viewers.text(phone).includes("ECHO:AFTER-CATCH-UP") && + viewers.text(desktop).includes("ECHO:AFTER-CATCH-UP"), + 10000, + ); + expect(viewers.text(phone).match(/ECHO:AFTER-CATCH-UP/g)).toHaveLength(1); + expect(viewers.text(desktop).match(/ECHO:AFTER-CATCH-UP/g)).toHaveLength(1); + await viewers.delivery.detach(phone); + await viewers.attach(fresh, "reattach", restore); + await waitForCondition(() => payloads(fresh).length === 1, 15000); + const reattached = await parse(payloads(fresh)[0]!); + expect(reattached.history).toBe(10000); + expect(reattached.text).toContain("row-16049"); + expect(reattached.text).toContain("ECHO:AFTER-CATCH-UP"); + expect(viewers.ended(desktop)).toHaveLength(0); + expect(viewers.ended(phone)).toHaveLength(0); + process.stdout.write( + JSON.stringify({ + chunked, + initialBytes: initial.byteLength, + recoveryBytes: recovery.byteLength, + reattachBytes: payloads(fresh)[0]!.byteLength, + retainedHistory: reattached.history, + recoveryHistory: recovered.history, + }) + "\n", + ); + } finally { + await viewers.delivery.close(); + } + }, + 45000, +); diff --git a/packages/server/src/terminal/worker-terminal-manager.ts b/packages/server/src/terminal/worker-terminal-manager.ts index 0a1adb2c44..9a82826cec 100644 --- a/packages/server/src/terminal/worker-terminal-manager.ts +++ b/packages/server/src/terminal/worker-terminal-manager.ts @@ -1,8 +1,12 @@ -import { fileURLToPath } from "node:url"; -import { fork } from "node:child_process"; +import type { TerminalReplaySink, TerminalReplayMetadata } from "./terminal-replay.js"; import { randomBytes, randomUUID } from "node:crypto"; +import { access } from "node:fs/promises"; +import { setTimeout as delay } from "node:timers/promises"; +import type { Logger } from "pino"; +import { createExternalProcessEnv } from "../server/paseo-env.js"; import { assertAbsolutePath, isSameOrDescendantPath } from "../server/path-utils.js"; -import type { TerminalState } from "@getpaseo/protocol/messages"; +import { writtenDuringThisBoot } from "../server/pid-lock.js"; +import type { WorkerTerminalState } from "./terminal-worker-protocol.js"; import type { TerminalActivity, TerminalActivityState } from "@getpaseo/protocol/terminal-activity"; import { deriveTerminalActivityStatusBucket } from "@getpaseo/protocol/terminal-activity"; import type { @@ -12,9 +16,29 @@ import type { TerminalCommandFinishedInfo, TerminalExitInfo, TerminalSession, - TerminalStateSnapshot, } from "./terminal.js"; +import { resolvePaseoCliExecutablePath } from "./paseo-cli-path.js"; import type { CaptureTerminalLinesResult } from "./terminal-capture.js"; +import { connectTerminalWorker, type TerminalWorkerConnection } from "./terminal-worker-client.js"; +import { launchTerminalWorker } from "./terminal-worker-launch.js"; +import { classifyTerminalWorkerProcess } from "./terminal-worker-ownership.js"; +import { + createTerminalWorkerProcessInspector, + type TerminalWorkerProcessInspector, +} from "./terminal-worker-processes.js"; +import { reapTerminalWorkers } from "./terminal-worker-reaper.js"; +import { + listTerminalWorkerRecords, + terminalWorkerRecordPath, + type TerminalWorkerRecord, +} from "./terminal-worker-record.js"; +import { + createTerminalWorkerPool, + NoTerminalWorkerAvailableError, + TerminalWorkerIncompatibleError, + type TerminalWorkerPoolMember, +} from "./terminal-worker-pool.js"; +import { pruneTerminalWorkerRuntimes } from "./terminal-worker-runtime.js"; import type { TerminalActivityListener, TerminalActivityTransitionEvent, @@ -25,12 +49,16 @@ import type { TerminalsChangedEvent, TerminalsChangedListener, } from "./terminal-manager.js"; +import { + classifyTerminalWorkerProtocol, + type TerminalWorkerProtocolFit, +} from "./terminal-worker-protocol.js"; import type { + TerminalWorkerListResult, TerminalWorkerRequest, TerminalWorkerResponse, TerminalWorkerToParentMessage, WorkerCreateTerminalOptions, - TerminalWorkerStateResult, WorkerTerminalInfo, } from "./terminal-worker-protocol.js"; @@ -64,7 +92,7 @@ interface PendingRequest { interface WorkerTerminalRecord { info: RequiredWorkerTerminalInfo; - state: TerminalState; + state: WorkerTerminalState; activity: TerminalActivity | null; // Cached input-mode preamble from the worker (the authoritative tracker lives // in the worker process). Updated with streamed output and snapshot responses. @@ -78,49 +106,45 @@ interface WorkerTerminalRecord { session: TerminalSession; } -interface TerminalWorkerProcess { - connected: boolean; - killed: boolean; - send(message: TerminalWorkerRequest, callback: (error: Error | null) => void): boolean; - disconnect(): void; - kill(): boolean; - on(event: "message", listener: (message: TerminalWorkerToParentMessage) => void): this; - on(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; +export interface TerminalCreateEnvironment { + baseEnv: Record; + paseoCliPath: string | null; } interface WorkerTerminalManagerOptions { + worker: TerminalWorkerConnection; + /** Reconnects a surviving worker; null means it is confirmed gone or the owner stopped. */ + reconnect?: () => Promise; requestTimeoutMs?: number; - forkWorker?: () => TerminalWorkerProcess; getTerminalActivityUrl?: () => string | null; + resolveCreateEnvironment?: () => TerminalCreateEnvironment; + // The kill path. The daemon passes the reaper, which verifies every program is gone; the + // default asks the connected worker to shut down. + closeTerminals?: () => Promise; +} + +/** The daemon's terminal manager: its terminals live in a worker that can outlive it. */ +export interface DaemonTerminalManager extends TerminalManager { + /** Registers every terminal the connected worker already runs. Resolves with their count. */ + adoptTerminals(): Promise; + /** Kills every terminal and verifies their programs ended. */ + closeTerminals(): Promise; + /** + * Lets go of the worker; its terminals keep running for the next daemon. With + * `afterPendingRequests`, requests already sent get their answers first. + */ + detach(options?: { afterPendingRequests?: boolean }): Promise; } function createActivityToken(): string { return randomBytes(32).toString("base64url"); } -function resolveWorkerUrl(): URL { - const currentUrl = import.meta.url; - if (currentUrl.endsWith(".ts")) { - return new URL("./terminal-worker-process.ts", currentUrl); - } - return new URL("./terminal-worker-process.js", currentUrl); -} - -function resolveWorkerExecArgv(): string[] { - if (!import.meta.url.endsWith(".ts")) { - return []; - } - const loaderUrl = new URL("./terminal-ts-loader.mjs", import.meta.url).href; - const importSource = [ - 'import { register } from "node:module";', - 'import { pathToFileURL } from "node:url";', - `register(${JSON.stringify(loaderUrl)}, pathToFileURL("./"));`, - ].join(" "); - return [ - "--experimental-strip-types", - "--import", - `data:text/javascript,${encodeURIComponent(importSource)}`, - ]; +function resolveDaemonTerminalCreateEnvironment(): TerminalCreateEnvironment { + return { + baseEnv: createExternalProcessEnv(process.env), + paseoCliPath: resolvePaseoCliExecutablePath(), + }; } function isResponse(message: TerminalWorkerToParentMessage): message is TerminalWorkerResponse { @@ -138,20 +162,18 @@ function cloneTerminalInfo(info: RequiredWorkerTerminalInfo): RequiredWorkerTerm }; } -function forkTerminalWorker(): TerminalWorkerProcess { - return fork(fileURLToPath(resolveWorkerUrl()), [], { - execArgv: resolveWorkerExecArgv(), - serialization: "advanced", - stdio: ["ignore", "ignore", "inherit", "ipc"], - }) as TerminalWorkerProcess; -} - export function createWorkerTerminalManager( - managerOptions: WorkerTerminalManagerOptions = {}, -): TerminalManager { - const worker = managerOptions.forkWorker ? managerOptions.forkWorker() : forkTerminalWorker(); + managerOptions: WorkerTerminalManagerOptions, +): DaemonTerminalManager { + let worker = managerOptions.worker; + let detached = false; + let reconnecting: Promise | null = null; const requestTimeoutMs = managerOptions.requestTimeoutMs ?? REQUEST_TIMEOUT_MS; + const resolveCreateEnvironment = + managerOptions.resolveCreateEnvironment ?? resolveDaemonTerminalCreateEnvironment; + const replaySinks = new Map(); const pendingRequests = new Map(); + const inFlight = new Set>(); const recordsById = new Map(); const terminalIdsByCwd = new Map>(); const terminalActivityTokenById = new Map(); @@ -162,8 +184,8 @@ export function createWorkerTerminalManager( const terminalActivityListeners = new Set(); const terminalWorkspaceContributionChangedListeners = new Set(); - let workerExited = false; - let workerShutdownTimer: ReturnType | null = null; + let workerDisconnected = false; + let closePromise: Promise | null = null; function emitTerminalsChanged(event: TerminalsChangedEvent): void { for (const listener of Array.from(terminalsChangedListeners)) { @@ -222,7 +244,7 @@ export function createWorkerTerminalManager( function registerRecord(input: { info: RequiredWorkerTerminalInfo; - state: TerminalState; + state: WorkerTerminalState; }): TerminalSession { const existing = recordsById.get(input.info.id); if (existing) { @@ -268,18 +290,11 @@ export function createWorkerTerminalManager( } sendBestEffortRequest({ type: "send", terminalId: record.info.id, message }); }, - subscribe( - listener: (msg: ServerMessage) => void, - options?: { initialSnapshot?: "state" | "ready" }, - ): () => void { + subscribe(listener: (msg: ServerMessage) => void): () => void { record.messageListeners.add(listener); - if (options?.initialSnapshot === "ready") { - queueMicrotask(() => { - if (record.messageListeners.has(listener)) { - listener({ type: "snapshotReady", revision: 0 }); - } - }); - } + queueMicrotask(() => { + if (record.messageListeners.has(listener)) listener({ type: "snapshotReady" }); + }); return () => { record.messageListeners.delete(listener); }; @@ -340,19 +355,8 @@ export function createWorkerTerminalManager( cols: record.state.cols, }; }, - getState(): TerminalState { - return record.state; - }, - getStateSnapshot(options?: { scrollbackLines?: number }): TerminalStateSnapshot { - const scrollbackLines = options?.scrollbackLines; - const scrollback = - typeof scrollbackLines === "number" - ? record.state.scrollback.slice(-scrollbackLines) - : record.state.scrollback; - return { - state: { ...record.state, scrollback }, - revision: 0, - }; + hasOutput(): boolean { + return record.state.hasOutput; }, getReplayPreamble(): string { return record.replayPreamble; @@ -420,9 +424,7 @@ export function createWorkerTerminalManager( if (!record) { return; } - if (message.message.type === "snapshot") { - record.state = message.message.state; - } + if (message.message.type === "output") record.state.hasOutput = true; record.replayPreamble = message.replayPreamble; for (const listener of Array.from(record.messageListeners)) { listener(message.message); @@ -587,46 +589,106 @@ export function createWorkerTerminalManager( } } - worker.on("message", (message: TerminalWorkerToParentMessage) => { - if (isResponse(message)) { - const pending = pendingRequests.get(message.requestId); - if (!pending) { + function attachWorker(): void { + const connection = worker; + connection.on("message", (message: TerminalWorkerToParentMessage) => { + if (message.type === "terminalReplay") { + // Consumption queues into the application's bounded transport synchronously. + // Never wait for app network delivery or accumulate a second replay queue here. + if (worker !== connection || !pendingRequests.has(message.requestId)) return; + try { + replaySinks.get(message.requestId)?.(message.event); + } catch (error) { + const pending = pendingRequests.get(message.requestId)!; + clearTimeout(pending.timeout); + pendingRequests.delete(message.requestId); + replaySinks.delete(message.requestId); + pending.reject(error instanceof Error ? error : new Error(String(error))); + } return; } - clearTimeout(pending.timeout); - pendingRequests.delete(message.requestId); - if (message.ok) { - pending.resolve(message.result); - } else { - pending.reject(new Error(message.error)); + if (isResponse(message)) { + const pending = pendingRequests.get(message.requestId); + if (!pending) { + return; + } + clearTimeout(pending.timeout); + pendingRequests.delete(message.requestId); + if (message.ok) { + pending.resolve(message.result); + } else { + pending.reject(new Error(message.error)); + } + return; } - return; - } - handleWorkerEvent(message); - }); + handleWorkerEvent(message); + }); - worker.on("exit", (code, signal) => { - workerExited = true; - if (workerShutdownTimer) { - clearTimeout(workerShutdownTimer); - workerShutdownTimer = null; - } - rejectPendingRequests(new Error(`Terminal worker exited (${signal ?? code ?? "unknown"})`)); - }); + connection.on("close", () => { + if (worker !== connection) return; + workerDisconnected = true; + rejectPendingRequests(new Error("Terminal worker connection closed")); + const reconnect = managerOptions.reconnect; + if (!detached && reconnect) { + reconnecting = (async () => { + const recovered = await reconnect(); + if (!recovered) { + for (const terminalId of Array.from(recordsById.keys())) { + handleTerminalExitEvent({ + type: "terminalExit", + terminalId, + info: { exitCode: null, signal: null, lastOutputLines: [] }, + }); + } + return; + } + if (detached) { + recovered.disconnect(); + return; + } + worker = recovered; + workerDisconnected = false; + attachWorker(); + await adoptTerminals(); + // Output emitted without a controller is retained in the worker's screen. Existing + // streams must fetch that screen before applying further live output. + for (const record of recordsById.values()) { + handleTerminalMessageEvent({ + type: "terminalMessage", + terminalId: record.info.id, + message: { type: "snapshotReady" }, + replayPreamble: record.replayPreamble, + }); + } + })().finally(() => { + reconnecting = null; + }); + void reconnecting.catch(() => {}); + } + }); + } + attachWorker(); - function sendRequest(input: TerminalWorkerRequestInput): Promise { - if (workerExited || !worker.connected) { + function sendRequest( + input: TerminalWorkerRequestInput, + sink?: TerminalReplaySink, + ): Promise { + if (reconnecting && workerDisconnected) + return reconnecting.then(() => sendRequest(input, sink)); + if (workerDisconnected || !worker.connected) { return Promise.reject(new Error("Terminal worker is not running")); } + const connection = worker; const requestId = randomUUID(); + if (sink) replaySinks.set(requestId, sink); const message = { ...input, requestId } as TerminalWorkerRequest; - return new Promise((resolve, reject) => { + const request = new Promise((resolve, reject) => { const timeout = setTimeout(() => { pendingRequests.delete(requestId); reject(new Error(`Terminal worker request timed out: ${input.type}`)); }, requestTimeoutMs); pendingRequests.set(requestId, { resolve, reject, timeout }); - worker.send(message, (error) => { + connection.send(message, (error) => { if (!error) { return; } @@ -635,6 +697,17 @@ export function createWorkerTerminalManager( reject(error); }); }); + // Tracks settlement only; the caller handles the rejection. + const settled = request.then( + () => undefined, + () => undefined, + ); + inFlight.add(settled); + void settled.finally(() => { + inFlight.delete(settled); + replaySinks.delete(requestId); + }); + return request; } function sendBestEffortRequest(input: TerminalWorkerRequestInput): void { @@ -645,6 +718,71 @@ export function createWorkerTerminalManager( }); } + function clearRecords(): void { + for (const terminalId of Array.from(recordsById.keys())) { + removeRecord(terminalId); + } + } + + function disconnectWorker(): Promise { + if (workerDisconnected || !worker.connected) { + return Promise.resolve(); + } + return new Promise((resolve) => { + worker.on("close", () => resolve()); + worker.disconnect(); + }); + } + + function closeTerminals(): Promise { + detached = true; + closePromise ??= (async () => { + await reconnecting; + if (managerOptions.closeTerminals) { + await disconnectWorker(); + clearRecords(); + await managerOptions.closeTerminals(); + return; + } + // Unverified: production passes the reaper, which confirms every program ended. + sendBestEffortRequest({ type: "shutdown" }); + await disconnectWorker(); + clearRecords(); + })(); + return closePromise; + } + + async function adoptTerminals(): Promise { + const listed = (await sendRequest({ type: "listTerminals" })) as TerminalWorkerListResult; + const cwds = new Set(); + const liveIds = new Set(listed.map((item) => item.terminal.id)); + for (const terminalId of Array.from(recordsById.keys())) { + if (!liveIds.has(terminalId)) + handleTerminalExitEvent({ + type: "terminalExit", + terminalId, + info: { exitCode: null, signal: null, lastOutputLines: [] }, + }); + } + for (const item of listed) { + const info = asRequiredWorkerTerminalInfo(item.terminal); + registerRecord({ info, state: item.state }); + const record = recordsById.get(info.id); + if (record) { + record.replayPreamble = item.replayPreamble; + } + // The agent hooks inside each shell keep the token they were started with. + if (item.activityToken) { + terminalActivityTokenById.set(info.id, item.activityToken); + } + cwds.add(info.cwd); + } + for (const cwd of cwds) { + emitTerminalsChanged({ cwd, terminals: listTerminalItemsForCwd(cwd) }); + } + return listed.length; + } + return { async getTerminals( cwd: string, @@ -688,6 +826,7 @@ export function createWorkerTerminalManager( const creation = { session: null as TerminalSession | null }; pendingCreationsById.set(terminalId, creation); try { + const environment = resolveCreateEnvironment(); await sendRequest({ type: "createTerminal", options: { @@ -695,6 +834,8 @@ export function createWorkerTerminalManager( id: terminalId, activityToken, activityUrl: terminalActivityUrl, + baseEnv: environment.baseEnv, + paseoCliPath: environment.paseoCliPath, }, }); if (!creation.session) { @@ -732,22 +873,12 @@ export function createWorkerTerminalManager( return recordsById.get(id)?.session; }, - async getTerminalState( - id: string, - options?: { scrollbackLines?: number }, - ): Promise { - const snapshot = (await sendRequest({ - type: "getTerminalState", - terminalId: id, - ...(options ? { options } : {}), - })) as TerminalWorkerStateResult; - if (snapshot && snapshot.replayPreamble !== undefined) { - const record = recordsById.get(id); - if (record) { - record.replayPreamble = snapshot.replayPreamble; - } - } - return snapshot; + async replayTerminal(id, options, sink): Promise { + const metadata = (await sendRequest( + { type: "replayTerminal", terminalId: id, options }, + sink, + )) as TerminalReplayMetadata | null; + return metadata; }, setTerminalTitle(id: string, title: string): boolean { @@ -812,25 +943,25 @@ export function createWorkerTerminalManager( }, killAll(): void { - void sendRequest({ type: "killAll" }) - .catch(() => { - // no-op - }) - .finally(() => { - if (worker.connected) { - worker.disconnect(); - } - if (!worker.killed && !workerShutdownTimer) { - workerShutdownTimer = setTimeout(() => { - worker.kill(); - }, 1000); - } - }); - for (const terminalId of Array.from(recordsById.keys())) { - removeRecord(terminalId); - } + void closeTerminals().catch(() => { + // The synchronous interface cannot report it; closeTerminals() callers see the error. + }); }, + closeTerminals, + + async detach(options?: { afterPendingRequests?: boolean }): Promise { + detached = true; + await reconnecting; + if (options?.afterPendingRequests) { + await Promise.allSettled(Array.from(inFlight)); + } + await disconnectWorker(); + clearRecords(); + }, + + adoptTerminals, + subscribeTerminalsChanged(listener: TerminalsChangedListener): () => void { terminalsChangedListeners.add(listener); return () => { @@ -856,6 +987,342 @@ export function createWorkerTerminalManager( }; } -export function terminateWorkerTerminalManager(manager: TerminalManager): void { - manager.killAll(); +export interface StartWorkerTerminalManagerOptions { + paseoHome: string; + paseoVersion: string; + logger: Logger; + getTerminalActivityUrl?: () => string | null; + requestTimeoutMs?: number; +} + +// The current worker plus one draining a previous protocol. Every live worker counts, +// incompatible, unreachable, unidentified and closing ones included: the daemon never starts a +// third. +const MAX_TERMINAL_WORKERS = 2; +const DRAINED_WORKER_EXIT_TIMEOUT_MS = 10_000; + +interface LiveWorkerRecord { + path: string; + record: TerminalWorkerRecord; + fit: TerminalWorkerProtocolFit; +} + +/** + * Connects the daemon to its terminal workers. A worker of this daemon's protocol is adopted + * (restart, crash, `stop --keep-terminals`); one a protocol older is adopted to drain; anything + * older is shut down, its terminals closed; one from a newer Paseo is left running and the + * terminal service reports it as incompatible. A worker is launched only when none is current, + * none is incompatible and fewer than two run; when two run, the first terminal created after one + * of them exits launches it. Records that cannot be adopted (a cleanup that + * never finished, a dead worker whose programs survived it) go through the reaper first, so a + * daemon never adopts terminals someone asked to close. + */ +export async function startWorkerTerminalManager( + options: StartWorkerTerminalManagerOptions, +): Promise { + const logger = options.logger.child({ module: "terminal-worker" }); + const inspector = createTerminalWorkerProcessInspector(); + const log = (message: string, fields?: Record) => logger.info(fields, message); + const live: LiveWorkerRecord[] = []; + const toReap: string[] = []; + for (const file of await listTerminalWorkerRecords(options.paseoHome)) { + if ("error" in file) { + logger.warn({ recordPath: file.path, err: file.error }, "Unreadable terminal worker record"); + continue; + } + const { record } = file; + if ( + record.closing || + !writtenDuringThisBoot({ startedAt: record.createdAt, bootId: record.bootId }) + ) { + toReap.push(file.path); + continue; + } + const worker = classifyTerminalWorkerProcess(record, await inspector.inspect(record.pid)); + if (worker.status === "owned") { + live.push({ + path: file.path, + record, + fit: classifyTerminalWorkerProtocol(record.protocolVersion), + }); + } else if (worker.status === "unknown") { + logger.warn( + { recordPath: file.path, pid: record.pid, reason: worker.reason }, + "Cannot identify terminal worker; leaving its record", + ); + } else { + // Its programs lost their PTY with the worker and cannot be adopted. + toReap.push(file.path); + } + } + + if (toReap.length > 0) { + await reapTerminalWorkers({ + paseoHome: options.paseoHome, + gracefulMs: 0, + recordPaths: toReap, + inspector, + log, + }).catch((error: unknown) => { + logger.warn({ err: error }, "Terminal cleanup of an unadoptable worker was not confirmed"); + }); + } + + const obsolete = live.filter((entry) => entry.fit === "obsolete"); + if (obsolete.length > 0) { + for (const entry of obsolete) { + logger.warn( + { + pid: entry.record.pid, + protocolVersion: entry.record.protocolVersion, + paseoVersion: entry.record.paseoVersion, + terminals: entry.record.terminals.length, + }, + "Closing a terminal worker two or more protocol versions old; its terminals close", + ); + } + await reapTerminalWorkers({ + paseoHome: options.paseoHome, + recordPaths: obsolete.map((entry) => entry.path), + inspector, + log, + }).catch((error: unknown) => { + logger.warn({ err: error }, "Closing an obsolete terminal worker was not confirmed"); + }); + } + + const closeAll = async () => { + const result = await reapTerminalWorkers({ paseoHome: options.paseoHome, inspector, log }); + logger.info(result, "Terminals closed"); + }; + const prune = async () => { + const result = await pruneTerminalWorkerRuntimes(options.paseoHome); + if (result.removed.length > 0) + log("Removed terminal worker copies", { removed: result.removed }); + for (const failure of result.failed) { + logger.warn(failure, "Cannot remove a terminal worker copy; the next start retries"); + } + }; + + const pruneAfterExit = async (workerPid: number) => { + if (await waitForWorkerRecordRemoval(options.paseoHome, workerPid)) { + await prune(); + return; + } + logger.warn({ pid: workerPid }, "Drained terminal worker has not exited yet"); + }; + + const newer = live.find((entry) => entry.fit === "newer"); + if (newer) { + const incompatible = new TerminalWorkerIncompatibleError({ + paseoVersion: newer.record.paseoVersion, + protocolVersion: newer.record.protocolVersion, + }); + logger.error({ pid: newer.record.pid }, incompatible.message); + await prune(); + return createTerminalWorkerPool({ + current: null, + draining: [], + incompatible, + closeAll, + }); + } + + const createMember = async ( + record: TerminalWorkerRecord, + connection: TerminalWorkerConnection, + ): Promise => { + let alive = true; + let resolveExit!: () => void; + const exited = new Promise((resolve) => { + resolveExit = resolve; + }); + let recovery: Promise | null = null; + const recoveryState = { stopped: false }; + const reconnect = () => { + recovery ??= (async () => { + while (!recoveryState.stopped) { + const ownership = classifyTerminalWorkerProcess( + record, + await inspector.inspect(record.pid), + ); + if (ownership.status === "gone" || ownership.status === "unrelated") { + await reapTerminalWorkers({ + paseoHome: options.paseoHome, + recordPaths: [terminalWorkerRecordPath(options.paseoHome, record.pid)], + inspector, + log, + gracefulMs: 0, + }).catch((error) => + logger.warn({ err: error }, "Dead terminal worker cleanup was not confirmed"), + ); + alive = false; + resolveExit(); + return null; + } + try { + return await connectTerminalWorker({ + socketPath: record.socketPath, + secret: record.secret, + timeoutMs: 500, + }); + } catch { + await delay(100); + } + } + return null; + })().finally(() => { + recovery = null; + }); + return recovery; + }; + const manager = createWorkerTerminalManager({ + worker: connection, + reconnect, + ...(options.requestTimeoutMs === undefined + ? {} + : { requestTimeoutMs: options.requestTimeoutMs }), + ...(options.getTerminalActivityUrl + ? { getTerminalActivityUrl: options.getTerminalActivityUrl } + : {}), + closeTerminals: closeAll, + }); + const count = await manager.adoptTerminals(); + if (count > 0) { + logger.info({ pid: record.pid, terminals: count }, "Adopted terminals from a running worker"); + } + return { + manager, + workerPid: record.pid, + exited, + ready: async () => { + await recovery; + return alive && !recoveryState.stopped; + }, + stopRecovery: () => { + recoveryState.stopped = true; + }, + }; + }; + + let current: TerminalWorkerPoolMember | null = null; + const draining: TerminalWorkerPoolMember[] = []; + const adoptable = [ + ...live.filter((entry) => entry.fit === "current"), + ...live.filter((entry) => entry.fit === "previous"), + ]; + for (const entry of adoptable) { + let connection: TerminalWorkerConnection; + try { + connection = await connectTerminalWorker({ + socketPath: entry.record.socketPath, + secret: entry.record.secret, + }); + } catch (error) { + logger.warn( + { pid: entry.record.pid, err: error }, + "Cannot reach terminal worker; leaving it running", + ); + continue; + } + const member = await createMember(entry.record, connection); + if (entry.fit === "current" && !current) { + logger.info({ pid: entry.record.pid }, "Adopting running terminal worker"); + current = member; + } else { + // A previous protocol, or a second worker of this one: it keeps its terminals and takes + // no new ones. + logger.info( + { pid: entry.record.pid, protocolVersion: entry.record.protocolVersion }, + "Draining terminal worker; it exits after its last terminal", + ); + draining.push(member); + } + } + + // Counted from the records rather than from what startup drove: a worker a cleanup could not + // confirm gone keeps running, and a draining one exits on its own. + const startCurrent = async (): Promise => { + const running = await countRunningTerminalWorkers(options.paseoHome, inspector); + if (running >= MAX_TERMINAL_WORKERS) { + throw new NoTerminalWorkerAvailableError( + `${running} terminal workers are already running in ${options.paseoHome}; new terminals can open once one of them exits`, + ); + } + const launched = await launchTerminalWorker({ + paseoHome: options.paseoHome, + paseoVersion: options.paseoVersion, + }); + const connection = await connectTerminalWorker({ + socketPath: launched.record.socketPath, + secret: launched.record.secret, + }); + logger.info( + { pid: launched.record.pid, runtime: launched.record.runtime ?? null }, + "Launched terminal worker", + ); + return createMember(launched.record, connection); + }; + + await prune(); + if (!current) { + try { + current = await startCurrent(); + } catch (error) { + if (!(error instanceof NoTerminalWorkerAvailableError)) throw error; + logger.warn(error.message); + } + } + + return createTerminalWorkerPool({ + current, + draining, + incompatible: null, + startCurrent, + closeAll, + onDrained: (member) => { + log("Released drained terminal worker", { pid: member.workerPid }); + void pruneAfterExit(member.workerPid); + }, + }); +} + +// Every worker that may still run in this home, one per record: a worker and its cleanup record +// are listed as one. Unreadable records and workers that cannot be identified count; a worker +// confirmed gone, or a pid reused by another process, does not. +async function countRunningTerminalWorkers( + paseoHome: string, + inspector: TerminalWorkerProcessInspector, +): Promise { + let running = 0; + for (const file of await listTerminalWorkerRecords(paseoHome)) { + if ("error" in file) { + running += 1; + continue; + } + const { record } = file; + if (!writtenDuringThisBoot({ startedAt: record.createdAt, bootId: record.bootId })) continue; + const worker = classifyTerminalWorkerProcess(record, await inspector.inspect(record.pid)); + if (worker.status === "owned" || worker.status === "unknown") running += 1; + } + return running; +} + +// A worker deletes its own record as it exits. +async function waitForWorkerRecordRemoval(paseoHome: string, workerPid: number): Promise { + const recordPath = terminalWorkerRecordPath(paseoHome, workerPid); + const deadline = Date.now() + DRAINED_WORKER_EXIT_TIMEOUT_MS; + while ( + await access(recordPath).then( + () => true, + (error: NodeJS.ErrnoException) => { + if (error.code === "ENOENT") return false; + throw error; + }, + ) + ) { + if (Date.now() >= deadline) return false; + await delay(100); + } + return true; } diff --git a/packages/server/src/test-utils/main-thread-work.ts b/packages/server/src/test-utils/main-thread-work.ts new file mode 100644 index 0000000000..66bb55e491 --- /dev/null +++ b/packages/server/src/test-utils/main-thread-work.ts @@ -0,0 +1,108 @@ +import { createHook, executionAsyncResource } from "node:async_hooks"; +import { performance, PerformanceObserver, type PerformanceEntry } from "node:perf_hooks"; +import { MessagePort } from "node:worker_threads"; + +/** Measure main-thread work without charging idle IO or runner descheduling. */ +export async function measureMainThreadWork(label: string, action: () => T | Promise) { + // Node 22.20 supplies this API; the repository's older declarations omit it. + const threadCpuUsage: (previous?: NodeJS.CpuUsage) => NodeJS.CpuUsage = Reflect.get( + process, + "threadCpuUsage", + ); + let blockingMs = 0; + let filesystemRequests = 0; + let yields = 0; + let longestCallbackMs = 0; + let longestCallbackCpuMs = 0; + let longestGapMs = 0; + let longestGcMs = 0; + let gcCount = 0; + let workerEvents = 0; + let draining = false; + const startedAt = performance.now(); + let previous = startedAt; + let previousCpu = threadCpuUsage(); + let probe: ReturnType; + let drain: ReturnType; + const callbacks = new Map(); + const record = (wallMs: number, cpu: NodeJS.CpuUsage) => { + const cpuMs = (cpu.user + cpu.system) / 1_000; + // Windows CPU accounting is coarse. Cap charged CPU by the real span so a + // counter increment cannot inflate a short callback. Zero-CPU waits drop out. + blockingMs = Math.max(blockingMs, Math.min(wallMs, cpuMs)); + if (wallMs > longestCallbackMs) { + longestCallbackMs = wallMs; + longestCallbackCpuMs = cpuMs; + } + }; + const observeGc = (entries: readonly PerformanceEntry[]) => { + for (const entry of entries) { + if (entry.startTime < startedAt) continue; + gcCount++; + longestGcMs = Math.max(longestGcMs, entry.duration); + } + }; + const gc = new PerformanceObserver((list) => observeGc(list.getEntries())); + gc.observe({ entryTypes: ["gc"] }); + const activity = createHook({ + init(_id, type) { + if (type.startsWith("FSREQ")) filesystemRequests++; + if (!draining && type === "Immediate") yields++; + if (type === "WORKER") workerEvents++; + }, + before(id) { + const resource = executionAsyncResource(); + if (resource === probe || resource === drain) return; + if (resource instanceof MessagePort) workerEvents++; + callbacks.set(id, { wall: performance.now(), cpu: threadCpuUsage() }); + }, + after(id) { + const start = callbacks.get(id); + if (!start) return; + callbacks.delete(id); + record(performance.now() - start.wall, threadCpuUsage(start.cpu)); + }, + }).enable(); + const sample = () => { + const now = performance.now(); + const cpu = threadCpuUsage(); + const wallMs = now - previous; + longestGapMs = Math.max(longestGapMs, wallMs); + // Worker construction/message cloning can precede async_hooks.before. + if (workerEvents) { + blockingMs = Math.max( + blockingMs, + Math.min(wallMs, (cpu.user - previousCpu.user + cpu.system - previousCpu.system) / 1_000), + ); + } + workerEvents = 0; + previous = now; + previousCpu = cpu; + }; + probe = setInterval(sample, 1); + let result: T; + try { + // The caller's current callback began before the hook was installed. + const wall = performance.now(); + const cpu = threadCpuUsage(); + const pending = action(); + record(performance.now() - wall, threadCpuUsage(cpu)); + result = await pending; + draining = true; + await new Promise((resolve) => { + drain = setImmediate(resolve); + }); + sample(); + observeGc(gc.takeRecords()); + } finally { + clearInterval(probe); + activity.disable(); + gc.disconnect(); + } + // GC CPU inside callbacks is charged above. Elapsed GC spans, like elapsed + // callback spans, include preemption and remain diagnostics rather than gates. + process.stderr.write( + `${label}: ${JSON.stringify({ blockingMs, filesystemRequests, yields, longestCallbackMs, longestCallbackCpuMs, longestGcMs, gcCount, longestGapMs })}\n`, + ); + return { result, blockingMs, filesystemRequests, yields }; +} diff --git a/packages/server/src/utils/checkout-git.ts b/packages/server/src/utils/checkout-git.ts index eed39f63e5..358bd6eb69 100644 --- a/packages/server/src/utils/checkout-git.ts +++ b/packages/server/src/utils/checkout-git.ts @@ -45,6 +45,8 @@ import { unquoteGitPath } from "./git-quoted-path.js"; import { isPaseoOwnedWorktreeCwd, resolvePaseoWorktreesBaseRoot } from "./worktree.js"; import { branchNameFromRef, + findPaseoWorktreeRootForCwd, + hasPaseoWorktreeMetadata, getPaseoWorktreeChangeRequestHintForBranch, type PaseoWorktreeMetadata, readPaseoWorktreeMetadata, @@ -1126,9 +1128,17 @@ async function getMainRepoRootFromCommonDir( }, ); const worktrees = parseWorktreeList(worktreeOut); + const paseoPaths = new Set( + ( + await Promise.all( + worktrees.map(async (wt) => ((await hasPaseoWorktreeMetadata(wt.path)) ? wt.path : null)), + ) + ).filter((p) => p !== null), + ); const nonBareNonPaseo = worktrees.filter( (wt) => !wt.isBare && + !paseoPaths.has(wt.path) && !isPaseoWorktreePath(wt.path, { paseoHome: context?.paseoHome, worktreesRoot: context?.worktreesRoot, @@ -1257,7 +1267,7 @@ async function getPaseoWorktreeForCwd( options: PaseoWorktreeLookupOptions = {}, ): Promise { // Fast-path reject: non-worktree paths do not need expensive ownership checks. - if (!/[\\/]worktrees[\\/]/.test(cwd)) { + if (!/[\\/]worktrees[\\/]/.test(cwd) && (await findPaseoWorktreeRootForCwd(cwd)) === null) { return { isPaseoOwnedWorktree: false }; } diff --git a/packages/server/src/utils/paseo-config-file.test.ts b/packages/server/src/utils/paseo-config-file.test.ts index 075ddd9720..6a7e43c757 100644 --- a/packages/server/src/utils/paseo-config-file.test.ts +++ b/packages/server/src/utils/paseo-config-file.test.ts @@ -3,10 +3,10 @@ import { execFile } from "node:child_process"; import { promisify } from "node:util"; import { fileURLToPath } from "node:url"; import { writeFile, truncate, rm } from "node:fs/promises"; -import { setImmediate as nextTurn } from "node:timers/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest"; +import { build } from "esbuild"; import { isPlatform } from "../test-utils/platform.js"; import { readPaseoConfig, @@ -21,6 +21,43 @@ import { writePaseoConfigForEdit, } from "./paseo-config-file.js"; +let probeDirectory: string; +let probePath: string; + +beforeAll(async () => { + probeDirectory = mkdtempSync(join(tmpdir(), "paseo-config-probe-")); + probePath = join(probeDirectory, "config-responsiveness.mjs"); + // Compile before starting the measured process. A runtime TypeScript loader + // owns MessagePorts that the responsiveness probe otherwise charges as work. + await build({ + entryPoints: [ + fileURLToPath(new URL("./test-fixtures/config-responsiveness.ts", import.meta.url)), + ], + outfile: probePath, + bundle: true, + platform: "node", + format: "esm", + }); +}); + +afterAll(() => { + rmSync(probeDirectory, { recursive: true, force: true }); +}); + +async function measureConfigRead(directory: string) { + const { stdout, stderr } = await promisify(execFile)(process.execPath, [probePath, directory], { + timeout: 15_000, + }); + process.stderr.write(stderr); + return JSON.parse(stdout) as { + result: Awaited>; + blockingMs: number; + filesystemRequests: number; + yields: number; + workerMessages: number; + }; +} + describe("paseo config file substrate", () => { let tempDir: string; @@ -67,7 +104,36 @@ describe("paseo config file substrate", () => { ); }); - it("keeps the longest loop stall below 20ms while admitting large configs", async () => { + it("excludes test-runner and loader activity from the config read budget", async () => { + await writeFile(join(tempDir, "paseo.json"), JSON.stringify({ worktree: { setup: "npm ci" } })); + const unrelatedWork = new Promise((resolve) => { + setImmediate(() => { + const threadCpuUsage: (previous?: NodeJS.CpuUsage) => NodeJS.CpuUsage = Reflect.get( + process, + "threadCpuUsage", + ); + const start = threadCpuUsage(); + let elapsed: NodeJS.CpuUsage; + do { + elapsed = threadCpuUsage(start); + } while (elapsed.user + elapsed.system < 60_000); + resolve(); + }); + }); + const { result, blockingMs, filesystemRequests, workerMessages } = + await measureConfigRead(tempDir); + await unrelatedWork; + expect(workerMessages).toBe(0); + expect(result).toEqual({ + ok: true, + config: { worktree: { setup: "npm ci" } }, + revision: await statPaseoConfigPath(tempDir), + }); + expect(filesystemRequests).toBeGreaterThan(0); + expect(blockingMs).toBeLessThan(20); + }); + + it("keeps main-thread work below 20ms while admitting large configs", async () => { const config = { scripts: Object.fromEntries( Array.from({ length: 7_000 }, (_, i) => [`script${i}`, { command: "echo hi" }]), @@ -75,48 +141,25 @@ describe("paseo config file substrate", () => { worktree: { setup: "npm ci" }, }; await writeFile(join(tempDir, "paseo.json"), JSON.stringify(config)); - let previous = performance.now(); - let longestGap = 0; - const probe = setInterval(() => { - const now = performance.now(); - longestGap = Math.max(longestGap, now - previous); - previous = now; - }, 1); - let result: Awaited>; - try { - result = await readPaseoConfigForEdit(tempDir); - await nextTurn(); - longestGap = Math.max(longestGap, performance.now() - previous); - } finally { - clearInterval(probe); - } + const { result, blockingMs, filesystemRequests, yields, workerMessages } = + await measureConfigRead(tempDir); expect(result).toEqual({ ok: true, config, revision: await statPaseoConfigPath(tempDir) }); - process.stdout.write(`project config 7,000 scripts max loop gap: ${longestGap.toFixed(2)}ms\n`); - expect(longestGap).toBeLessThan(20); + expect(blockingMs).toBeLessThan(20); + expect(filesystemRequests).toBeGreaterThan(0); + expect(yields).toBeGreaterThan(0); + expect(workerMessages).toBe(0); }); - it("rejects a 32MiB config with a loop stall below 20ms", async () => { + it("rejects a 32MiB config with main-thread work below 20ms", async () => { await writeFile( join(tempDir, "paseo.json"), JSON.stringify({ extra: "x".repeat(32 * 1024 * 1024) }), ); - let previous = performance.now(); - let longestGap = 0; - const probe = setInterval(() => { - const now = performance.now(); - longestGap = Math.max(longestGap, now - previous); - previous = now; - }, 1); - let result: Awaited>; - try { - result = await readPaseoConfigForEdit(tempDir); - await nextTurn(); - longestGap = Math.max(longestGap, performance.now() - previous); - } finally { - clearInterval(probe); - } - process.stdout.write(`project config 32MiB max loop gap: ${longestGap.toFixed(2)}ms\n`); - expect(longestGap).toBeLessThan(20); + const { result, blockingMs, filesystemRequests, workerMessages } = + await measureConfigRead(tempDir); + expect(blockingMs).toBeLessThan(20); + expect(filesystemRequests).toBeGreaterThan(0); + expect(workerMessages).toBe(0); expect(result).toEqual({ ok: false, error: { code: "invalid_project_config" } }); }); diff --git a/packages/server/src/utils/test-fixtures/config-responsiveness.ts b/packages/server/src/utils/test-fixtures/config-responsiveness.ts new file mode 100644 index 0000000000..787ad88674 --- /dev/null +++ b/packages/server/src/utils/test-fixtures/config-responsiveness.ts @@ -0,0 +1,30 @@ +import { createHook, executionAsyncResource } from "node:async_hooks"; +import { stat } from "node:fs/promises"; +import { MessagePort } from "node:worker_threads"; +import assert from "node:assert/strict"; +import { setImmediate as nextTurn } from "node:timers/promises"; +import { measureMainThreadWork } from "../../test-utils/main-thread-work.js"; +import { readPaseoConfigForEdit } from "../paseo-config-file.js"; + +// The parent bundles this fixture before launching plain Node, keeping test +// runner callbacks and runtime loader messages outside the measured thread. +// Read the real file once, without warming the config snapshot or schema. +const directory = process.argv[2]; +assert.ok(directory, "Config directory is required"); +// The daemon has already used asynchronous filesystem APIs before reading a +// project config. Start libuv's filesystem worker pool outside the measurement: +// its first submission synchronously creates workers in a fresh Node process. +// Stat the probe itself so the config, snapshot and schemas remain cold. +await stat(process.argv[1]); +await nextTurn(); +let workerMessages = 0; +const activity = createHook({ + before() { + if (executionAsyncResource() instanceof MessagePort) workerMessages++; + }, +}).enable(); +const measured = await measureMainThreadWork("project config main-thread work", () => + readPaseoConfigForEdit(directory), +); +activity.disable(); +process.stdout.write(JSON.stringify({ ...measured, workerMessages })); diff --git a/packages/server/src/utils/worktree-metadata.ts b/packages/server/src/utils/worktree-metadata.ts index 13c95567db..fcb0454672 100644 --- a/packages/server/src/utils/worktree-metadata.ts +++ b/packages/server/src/utils/worktree-metadata.ts @@ -2,7 +2,7 @@ import { mkdir, open, realpath, rename, stat, writeFile } from "node:fs/promises import { randomUUID } from "node:crypto"; import { constants } from "node:fs"; import pLimit from "p-limit"; -import { isAbsolute, join, resolve } from "path"; +import { dirname, isAbsolute, join, resolve } from "path"; import { z } from "zod"; const MAX_WORKTREE_METADATA_BYTES = 64 * 1024; @@ -329,6 +329,39 @@ export async function markPaseoWorktreeFirstAgentBranchAutoNameAttempted( }); } +export async function hasPaseoWorktreeMetadata(worktreeRoot: string): Promise { + try { + return (await readPaseoWorktreeMetadata(worktreeRoot)) !== null; + } catch { + return false; + } +} + +/** + * Filesystem-only search for a Paseo worktree root at or above cwd: the + * first directory containing a .git entry wins, and it only counts when + * its git admin dir holds the paseo/worktree.json marker. Lets callers + * cheaply rule out plain directories before running git ownership checks. + */ +export async function findPaseoWorktreeRootForCwd(cwd: string): Promise { + let current = resolve(cwd); + for (;;) { + if ( + await stat(join(current, ".git")).then( + () => true, + () => false, + ) + ) { + return (await hasPaseoWorktreeMetadata(current)) ? current : null; + } + const parent = dirname(current); + if (parent === current) { + return null; + } + current = parent; + } +} + export async function readPaseoWorktreeMetadata( worktreeRoot: string, ): Promise { diff --git a/packages/server/src/utils/worktree-path.ts b/packages/server/src/utils/worktree-path.ts new file mode 100644 index 0000000000..d36abea762 --- /dev/null +++ b/packages/server/src/utils/worktree-path.ts @@ -0,0 +1,88 @@ +import { realpath, lstat } from "node:fs/promises"; +import { homedir } from "node:os"; +import { basename, dirname, isAbsolute, join, parse, resolve, sep } from "node:path"; +import { getRelativePathInsideRoot } from "./path.js"; + +async function normalizeAbsolute(path: string): Promise { + try { + return await realpath(path); + } catch { + return resolve(path); + } +} + +// Resolve a path that does not exist yet (the normal case for a worktree +// destination): realpath the nearest existing ancestor, then append the +// missing tail. A plain resolve() would let a symlinked parent smuggle +// the destination past the denylist — e.g. /alias -> /.git. +async function normalizeCandidatePath(path: string): Promise { + let current = resolve(path); + const missing: string[] = []; + while (!(await pathExists(current))) { + missing.unshift(basename(current)); + const parent = dirname(current); + if (parent === current) { + break; + } + current = parent; + } + const resolvedAncestor = await normalizeAbsolute(current); + return missing.length > 0 ? join(resolvedAncestor, ...missing) : resolvedAncestor; +} + +async function pathExists(path: string): Promise { + try { + await lstat(path); + return true; + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return false; + throw error; + } +} + +/** + * Validate a worktree destination. Throws + * with the reason on any violation; returns the normalized absolute path. + */ +export async function validateWorktreePath(options: { + candidate: string; + repoPath: string; +}): Promise { + const { candidate, repoPath } = options; + if (!isAbsolute(candidate)) { + throw new Error( + `Worktree hook returned a relative path '${candidate}'; it must be an absolute path`, + ); + } + const normalized = await normalizeCandidatePath(candidate); + const normalizedRepoPath = await normalizeAbsolute(repoPath); + + if (normalized === parse(normalized).root) { + throw new Error("Worktree hook returned the filesystem root, which is not allowed"); + } + if (normalized === (await normalizeAbsolute(homedir()))) { + throw new Error("Worktree hook returned the user's home directory, which is not allowed"); + } + if (normalized === normalizedRepoPath) { + throw new Error("Worktree hook returned the repository root itself, which is not allowed"); + } + if ( + [normalized, resolve(candidate)].some((path) => + path + .split(sep) + .some((part) => (process.platform === "win32" ? part.toLowerCase() : part) === ".git"), + ) + ) { + throw new Error(`Worktree hook returned a path inside a .git directory: ${normalized}`); + } + const relativeToCandidate = getRelativePathInsideRoot(normalized, normalizedRepoPath); + if (relativeToCandidate !== null && relativeToCandidate !== "") { + throw new Error(`Worktree hook returned an ancestor of the repository: ${normalized}`); + } + if ((await pathExists(normalized)) || (await pathExists(candidate))) { + throw new Error( + `Worktree hook returned a path that already exists: ${normalized}. Paseo creates the returned path.`, + ); + } + return normalized; +} diff --git a/packages/server/src/utils/worktree.posix.test.ts b/packages/server/src/utils/worktree.posix.test.ts index aede7cf8e3..35d59cce3f 100644 --- a/packages/server/src/utils/worktree.posix.test.ts +++ b/packages/server/src/utils/worktree.posix.test.ts @@ -1,5 +1,6 @@ // POSIX-only: git worktree and teardown shell fixtures /* eslint-disable max-nested-callbacks */ +import { validateWorktreePath } from "./worktree-path.js"; import { describe, it, expect, beforeEach, afterEach } from "vitest"; import { createWorktree as createWorktreePrimitive, @@ -159,7 +160,7 @@ describe.skipIf(isPlatform("win32"))("worktree POSIX-only", () => { ).resolves.toMatchObject({ allowed: true, worktreeRoot: join(worktreesRoot, projectHash) }); await expect( isPaseoOwnedWorktreeCwd(result.worktreePath, { paseoHome }), - ).resolves.toMatchObject({ allowed: false }); + ).resolves.toMatchObject({ allowed: true, worktreePath: result.worktreePath }); const worktrees = await listPaseoWorktrees({ cwd: repoDir, paseoHome, worktreesRoot }); expect(worktrees.map((entry) => entry.path)).toContain(result.worktreePath); @@ -1380,6 +1381,200 @@ describe.skipIf(isPlatform("win32"))("worktree POSIX-only", () => { }); }); + describe("worktrees at explicit paths", () => { + let tempDir: string; + let repoDir: string; + let paseoHome: string; + + beforeEach(() => { + tempDir = realpathSync(mkdtempSync(join(tmpdir(), "worktree-explicit-test-"))); + repoDir = join(tempDir, "test-repo"); + paseoHome = join(tempDir, "paseo-home"); + + mkdirSync(repoDir, { recursive: true }); + execFileSync("git", ["init", "-b", "main"], { cwd: repoDir }); + execFileSync("git", ["config", "user.email", "test@test.com"], { cwd: repoDir }); + execFileSync("git", ["config", "user.name", "Test"], { cwd: repoDir }); + writeFileSync(join(repoDir, "file.txt"), "hello\n"); + execFileSync("git", ["add", "."], { cwd: repoDir }); + execFileSync("git", ["-c", "commit.gpgsign=false", "commit", "-m", "initial"], { + cwd: repoDir, + }); + }); + + afterEach(() => { + rmSync(tempDir, { recursive: true, force: true }); + }); + + it("places, owns, lists, and deletes a worktree outside the legacy root", async () => { + // Sibling layout: /wt- + + const result = await createWorktreePrimitive({ + cwd: repoDir, + worktreeSlug: "sibling-one", + source: { kind: "branch-off", baseBranch: "main", branchName: "feature/sibling" }, + paseoHome, + worktreePath: join(tempDir, "wt-sibling-one"), + }); + + expect(result.worktreePath).toBe(join(tempDir, "wt-sibling-one")); + expect(existsSync(join(result.worktreePath, "file.txt"))).toBe(true); + expect(existsSync(await getPaseoWorktreeMetadataPath(result.worktreePath))).toBe(true); + + const ownership = await isPaseoOwnedWorktreeCwd(result.worktreePath, { paseoHome }); + expect(ownership.allowed).toBe(true); + expect(ownership.worktreePath).toBe(result.worktreePath); + // A subdirectory of the worktree resolves to the worktree root. + mkdirSync(join(result.worktreePath, "sub"), { recursive: true }); + const nested = await isPaseoOwnedWorktreeCwd(join(result.worktreePath, "sub"), { + paseoHome, + }); + expect(nested.worktreePath).toBe(result.worktreePath); + + const listed = await listPaseoWorktrees({ cwd: repoDir, paseoHome }); + expect(listed.map((entry) => entry.path)).toContain(result.worktreePath); + + await deletePaseoWorktree({ cwd: repoDir, worktreePath: result.worktreePath, paseoHome }); + expect(existsSync(result.worktreePath)).toBe(false); + }); + + it("removes branches fetched by the source plan when git worktree add fails", async () => { + // A branch that exists only on the remote: resolving a + // checkout-branch plan fetches it into a local branch. A script + // failure must not leave that branch behind, or the next attempt + // would uniquify to a different branch name. + const remoteDir = join(tempDir, "remote.git"); + execFileSync("git", ["clone", "--bare", repoDir, remoteDir], { cwd: tempDir }); + execFileSync("git", ["remote", "add", "origin", remoteDir], { cwd: repoDir }); + execFileSync("git", ["push", "origin", "main"], { cwd: repoDir }); + execFileSync("git", ["branch", "feature/remote-check"], { cwd: repoDir }); + execFileSync("git", ["push", "origin", "feature/remote-check"], { cwd: repoDir }); + execFileSync("git", ["branch", "-D", "feature/remote-check"], { cwd: repoDir }); + execFileSync("git", ["fetch", "origin"], { cwd: repoDir }); + + mkdirSync(join(tempDir, "occupied")); + writeFileSync(join(tempDir, "occupied", "keep"), "keep"); + await expect( + createWorktreePrimitive({ + cwd: repoDir, + worktreeSlug: "remote-check", + source: { kind: "checkout-branch", branchName: "feature/remote-check" }, + paseoHome, + worktreePath: join(tempDir, "occupied"), + }), + ).rejects.toThrow(); + + const localBranches = execFileSync("git", ["branch", "--list", "feature/remote-check"], { + cwd: repoDir, + encoding: "utf8", + }); + expect(localBranches.trim()).toBe(""); + }); + + it("deletes only the registered destination nested beneath the legacy root", async () => { + const parent = join(paseoHome, "worktrees", "acme", "widgets"); + const worktreePath = join(parent, "topic"); + const siblingPath = join(parent, "sibling"); + await createWorktreePrimitive({ + cwd: repoDir, + paseoHome, + worktreeSlug: "topic", + worktreePath, + source: { kind: "branch-off", branchName: "topic", baseBranch: "main" }, + }); + await createWorktreePrimitive({ + cwd: repoDir, + paseoHome, + worktreeSlug: "sibling", + worktreePath: siblingPath, + source: { kind: "branch-off", branchName: "sibling", baseBranch: "main" }, + }); + mkdirSync(join(worktreePath, "nested")); + expect( + await isPaseoOwnedWorktreeCwd(join(worktreePath, "nested"), { paseoHome }), + ).toMatchObject({ allowed: true, worktreePath }); + await deletePaseoWorktree({ cwd: repoDir, paseoHome, worktreePath, registryProven: true }); + expect(existsSync(worktreePath)).toBe(false); + expect(readFileSync(join(siblingPath, "file.txt"), "utf8")).toBe("hello\n"); + }); + + it("rejects a destination under a symlink into .git", async () => { + const alias = join(tempDir, "git-alias"); + symlinkSync(join(repoDir, ".git"), alias, "dir"); + await expect( + validateWorktreePath({ candidate: join(alias, "new", "worktree"), repoPath: repoDir }), + ).rejects.toThrow("inside a .git directory"); + expect(existsSync(join(repoDir, ".git", "new"))).toBe(false); + }); + + it("uses an explicit worktreePath verbatim", async () => { + const explicitPath = join(tempDir, "explicit-wt"); + + const result = await createWorktreePrimitive({ + cwd: repoDir, + worktreeSlug: "explicit-one", + source: { kind: "branch-off", baseBranch: "main", branchName: "feature/explicit" }, + paseoHome, + worktreePath: explicitPath, + }); + + expect(result.worktreePath).toBe(explicitPath); + expect(existsSync(join(explicitPath, "file.txt"))).toBe(true); + }); + + it("restore recreates at the recorded path", async () => { + const created = await createWorktreePrimitive({ + cwd: repoDir, + worktreeSlug: "restorable", + source: { kind: "branch-off", baseBranch: "main", branchName: "feature/restorable" }, + paseoHome, + worktreePath: join(tempDir, "wt-sibling-one"), + }); + await deletePaseoWorktree({ cwd: repoDir, worktreePath: created.worktreePath, paseoHome }); + expect(existsSync(created.worktreePath)).toBe(false); + + const restored = await createWorktreePrimitive({ + cwd: repoDir, + worktreeSlug: "restorable", + source: { kind: "restore", branchName: "feature/restorable", baseRef: "main" }, + paseoHome, + worktreePath: created.worktreePath, + }); + + expect(restored.worktreePath).toBe(created.worktreePath); + expect(existsSync(join(restored.worktreePath, "file.txt"))).toBe(true); + }); + + it("does not treat a copied marker in a non-worktree directory as ownership", async () => { + const created = await createWorktreePrimitive({ + cwd: repoDir, + worktreeSlug: "marker-source", + source: { kind: "branch-off", baseBranch: "main", branchName: "feature/marker" }, + paseoHome, + worktreePath: join(tempDir, "wt-sibling-one"), + }); + const metadata = await readPaseoWorktreeMetadata(created.worktreePath); + expect(metadata).not.toBeNull(); + + // A plain directory with a .git file pointing at a copied admin dir + // that holds a paseo/worktree.json. Git does not list it as a + // worktree, so the copied marker must not prove ownership. + const fakeDir = join(tempDir, "fake-worktree"); + const fakeAdmin = join(tempDir, "fake-admin"); + mkdirSync(join(fakeAdmin, "paseo"), { recursive: true }); + mkdirSync(fakeDir, { recursive: true }); + writeFileSync(join(fakeAdmin, "paseo", "worktree.json"), JSON.stringify(metadata)); + writeFileSync(join(fakeDir, ".git"), `gitdir: ${fakeAdmin}\n`); + + const ownership = await isPaseoOwnedWorktreeCwd(fakeDir, { paseoHome }); + expect(ownership.allowed).toBe(false); + await expect( + deletePaseoWorktree({ cwd: repoDir, worktreePath: fakeDir, paseoHome }), + ).rejects.toThrow("Refusing to delete non-Paseo worktree"); + expect(existsSync(fakeDir)).toBe(true); + }); + }); + describe("paseo worktree manager", () => { let tempDir: string; let repoDir: string; diff --git a/packages/server/src/utils/worktree.test.ts b/packages/server/src/utils/worktree.test.ts index 605e2b8c20..f549b461f8 100644 --- a/packages/server/src/utils/worktree.test.ts +++ b/packages/server/src/utils/worktree.test.ts @@ -302,6 +302,22 @@ describe("paseo worktree manager", () => { expect(existsSync(created.worktreePath)).toBe(false); }); + it("deletes a worktree when Git reports its source through native and long path spellings", async () => { + const created = await createLegacyWorktreeForTest({ + branchName: "identity-delete", + cwd: repoDir, + baseBranch: "main", + worktreeSlug: "identity-delete", + paseoHome, + }); + await deletePaseoWorktree({ + cwd: realpathSync.native(repoDir), + worktreePath: created.worktreePath, + paseoHome, + }); + expect(existsSync(created.worktreePath)).toBe(false); + }); + it("is idempotent: deleting an already-absent worktree succeeds", async () => { const created = await createLegacyWorktreeForTest({ branchName: "idempotent-delete-branch", diff --git a/packages/server/src/utils/worktree.ts b/packages/server/src/utils/worktree.ts index 3ddc71b472..2fc8bc05db 100644 --- a/packages/server/src/utils/worktree.ts +++ b/packages/server/src/utils/worktree.ts @@ -24,6 +24,8 @@ export { import { type PaseoConfig } from "@getpaseo/protocol/paseo-config-schema"; import { createPaseoWorktreeChangeRequestHint, + hasPaseoWorktreeMetadata, + findPaseoWorktreeRootForCwd, normalizeBaseRefName, isQualifiedRef, type PaseoWorktreeChangeRequestHint, @@ -218,6 +220,7 @@ export interface CreateWorktreeOptions { source: WorktreeSource; paseoHome?: string; worktreesRoot?: string; + worktreePath?: string; } export class BranchAlreadyCheckedOutError extends Error { @@ -964,6 +967,24 @@ export async function isPaseoOwnedWorktreeCwd( } } + // Worktrees placed at plugin-chosen paths are + // proven by the marker createWorktree writes unconditionally: a + // paseo/worktree.json in the worktree's git admin dir, with the path + // still registered in the repo's `git worktree list`. The marker alone + // is not proof — it lives in a git admin dir a user can copy into a + // hand-made directory that git does not know about. + if (options?.knownGitCommonDir !== null) { + const metadataProof = await resolveMetadataOwnedWorktree(cwd, repoRoot); + if (metadataProof) { + return { + allowed: true, + ...(repoRoot !== undefined ? { repoRoot } : {}), + worktreeRoot: metadataProof.worktreeRoot, + worktreePath: metadataProof.worktreePath, + }; + } + } + const worktreesBaseRoot = resolvePaseoWorktreesBaseRoot(options); const relativePath = await getOwnershipRelativePath(worktreesBaseRoot, resolvedCwd); @@ -971,32 +992,51 @@ export async function isPaseoOwnedWorktreeCwd( // The / prefix is Paseo-private — nothing else writes there — so the // path shape alone is sufficient proof of ownership, even when git has already // forgotten about the worktree. - if (relativePath === null) { - return { - allowed: false, - ...(repoRoot !== undefined ? { repoRoot } : {}), - worktreePath: resolvedCwd, - }; + if (relativePath !== null) { + const parts = relativePath.split(sep).filter((part) => part.length > 0); + if (parts.length >= 2) { + const worktreesRoot = join(worktreesBaseRoot, parts[0]); + return { + allowed: true, + ...(repoRoot !== undefined ? { repoRoot } : {}), + worktreeRoot: worktreesRoot, + worktreePath: join(worktreesRoot, parts[1]), + }; + } } - const parts = relativePath.split(sep).filter((part) => part.length > 0); - if (parts.length < 2) { - return { - allowed: false, - ...(repoRoot !== undefined ? { repoRoot } : {}), - worktreePath: resolvedCwd, - }; - } - - const worktreesRoot = join(worktreesBaseRoot, parts[0]); return { - allowed: true, + allowed: false, ...(repoRoot !== undefined ? { repoRoot } : {}), - worktreeRoot: worktreesRoot, - worktreePath: join(worktreesRoot, parts[1]), + worktreePath: resolvedCwd, }; } +async function resolveMetadataOwnedWorktree( + cwd: string, + repoRoot: string | undefined, +): Promise<{ worktreePath: string; worktreeRoot: string } | null> { + try { + const root = await findPaseoWorktreeRootForCwd(cwd); + if (!root) return null; + const candidate = await normalizePathForOwnership(root); + if (repoRoot !== undefined && candidate === (await normalizePathForOwnership(repoRoot))) + return null; + const { stdout: listOutput } = await runGitCommand(["worktree", "list", "--porcelain"], { + cwd: candidate, + envOverlay: READ_ONLY_GIT_ENV, + }); + for (const entry of parseWorktreeList(listOutput)) { + if ((await normalizePathForOwnership(entry.path)) === candidate) { + return { worktreePath: candidate, worktreeRoot: dirname(candidate) }; + } + } + return null; + } catch { + return null; + } +} + type ParsedPaseoWorktreeInfo = Omit; function parseWorktreeList(output: string): ParsedPaseoWorktreeInfo[] { @@ -1063,12 +1103,17 @@ export async function listPaseoWorktrees({ envOverlay: READ_ONLY_GIT_ENV, }); + const mainCheckoutPath = await resolveRepoRootFromGitCommonDir(await getGitCommonDir(cwd)); const roots = await ownershipPathVariants(projectWorktreesRoot); const worktrees: PaseoWorktreeInfo[] = []; // Inspect foreign paths sequentially; a large worktree list must not consume the FS pool. for (const entry of parseWorktreeList(stdout)) { const path = await normalizePathForOwnership(entry.path); - if (!roots.some((root) => getRelativePathInsideRoot(root, path) !== null)) continue; + if ( + !roots.some((root) => getRelativePathInsideRoot(root, path) !== null) && + !(path !== mainCheckoutPath && (await hasPaseoWorktreeMetadata(path))) + ) + continue; worktrees.push({ ...entry, path, createdAt: await resolveWorktreeCreatedAtIso(path) }); } return worktrees; @@ -1082,6 +1127,30 @@ export interface DeletePaseoWorktreeOptions { worktreesRoot?: string; paseoHome?: string; worktreesBaseRoot?: string; + // The caller has a workspace registry record backing worktreePath (the + // record's cwd is this path). Registry membership is an ownership proof + // in its own right: it covers worktrees whose git admin dir is already + // gone, where the marker proof can no longer be verified. Only pass + // this when the record was matched against the path by the caller. + registryProven?: boolean; +} + +// Project scoping for delete: a proof for some other repo's worktree must +// not make this repo's delete remove it. Only refuses on a positive +// mismatch — when git has forgotten either side, the ownership proof the +// caller already established stands. +async function assertWorktreeBelongsToRepo(cwd: string, worktreePath: string): Promise { + let callerRepoRoot: string; + let targetRepoRoot: string; + try { + callerRepoRoot = await resolveRepoRootFromGitCommonDir(await getGitCommonDir(cwd)); + targetRepoRoot = await resolveRepoRootFromGitCommonDir(await getGitCommonDir(worktreePath)); + } catch { + return; + } + if ((await getOwnershipRelativePath(callerRepoRoot, targetRepoRoot)) !== "") { + throw new Error("Refusing to delete non-Paseo worktree"); + } } export async function deletePaseoWorktree({ @@ -1092,6 +1161,7 @@ export async function deletePaseoWorktree({ worktreesRoot, paseoHome, worktreesBaseRoot, + registryProven, }: DeletePaseoWorktreeOptions): Promise { if (!worktreePath && !worktreeSlug) { throw new Error("worktreePath or worktreeSlug is required"); @@ -1110,22 +1180,27 @@ export async function deletePaseoWorktree({ } const requestedPath = worktreePath ?? join(resolvedWorktreesRoot, worktreeSlug!); - const resolvedRequested = await normalizePathForOwnership(requestedPath); const ownership = await isPaseoOwnedWorktreeCwd(requestedPath, { paseoHome, worktreesRoot: worktreesBaseRoot, }); - const resolvedWorktree = - ownership.allowed && ownership.worktreePath ? ownership.worktreePath : resolvedRequested; - - const relativeWorktreePath = await getOwnershipRelativePath( - resolvedWorktreesRoot, - resolvedWorktree, - ); - if (relativeWorktreePath === null || relativeWorktreePath === "") { + // Deletion is gated on the ownership proof set (legacy shape, the + // paseo/worktree.json marker verified against `git worktree list`, or a + // caller-asserted registry record), not on living under the per-project + // hashed root: plugin-placed worktrees live anywhere. + let resolvedWorktree: string; + if (registryProven) { + resolvedWorktree = await normalizePathForOwnership(requestedPath); + } else if (ownership.allowed && ownership.worktreePath) { + resolvedWorktree = ownership.worktreePath; + } else { throw new Error("Refusing to delete non-Paseo worktree"); } + if (cwd) { + await assertWorktreeBelongsToRepo(cwd, resolvedWorktree); + } + if (await pathExists(resolvedWorktree)) { for (const teardownCwd of teardownCwds ?? [resolvedWorktree]) { await runWorktreeTeardownCommands({ @@ -1222,6 +1297,67 @@ async function removeDirectoryWithRetries(path: string): Promise { } } +async function listLocalBranchNames(cwd: string): Promise> { + const { stdout } = await runGitCommand( + ["for-each-ref", "--format=%(refname:short)", "refs/heads"], + { cwd }, + ); + return new Set( + stdout + .split("\n") + .map((name) => name.trim()) + .filter((name) => name.length > 0), + ); +} + +// The one local branch a source plan can create while resolving: a +// checkout-branch plan fetches refs/heads/, and a +// change-request/PR plan fetches refs/heads/ (which is +// the plan's branchName). branch-off creates no local branch. Only this +// ref may be rolled back when creation fails — never any other +// branch that appeared in the meantime; other creators own those. +function planCreatedLocalBranch( + source: WorktreeSource, + sourcePlan: WorktreeSourcePlan, +): string | null { + switch (source.kind) { + case "checkout-branch": + return source.branchName; + case "checkout-change-request": + case "checkout-github-pr": + return sourcePlan.branchName; + default: + return null; + } +} + +async function readLocalBranchTip(cwd: string, branchName: string): Promise { + try { + const { stdout } = await runGitCommand( + ["rev-parse", "--verify", `refs/heads/${branchName}^{commit}`], + { cwd }, + ); + const tip = stdout.trim(); + return tip.length > 0 ? tip : null; + } catch { + return null; + } +} + +/** Resolve the default placement once, before presenting it to creation hooks. */ +export async function resolveDefaultWorktreePath( + options: Pick, +): Promise { + const original = join( + await getPaseoWorktreesRoot(options.cwd, options.paseoHome, options.worktreesRoot), + options.worktreeSlug, + ); + let candidate = original; + let suffix = 1; + while (await pathExists(candidate)) candidate = `${original}-${suffix++}`; + return candidate; +} + /** * Create a git worktree with proper naming conventions */ @@ -1231,56 +1367,73 @@ export const createWorktree = async ({ worktreeSlug, paseoHome, worktreesRoot, + worktreePath: explicitWorktreePath, }: CreateWorktreeOptions): Promise => { + const branchesBefore = + source.kind === "checkout-branch" || + source.kind === "checkout-change-request" || + source.kind === "checkout-github-pr" + ? await listLocalBranchNames(cwd) + : new Set(); const sourcePlan = await resolveWorktreeSourcePlan({ cwd, source, desiredSlug: worktreeSlug }); - let worktreePath = join(await getPaseoWorktreesRoot(cwd, paseoHome, worktreesRoot), worktreeSlug); - await mkdir(dirname(worktreePath), { recursive: true }); + const fetchedBranch = planCreatedLocalBranch(source, sourcePlan); + const fetchedTip = + fetchedBranch && !branchesBefore.has(fetchedBranch) + ? await readLocalBranchTip(cwd, fetchedBranch) + : null; + try { + let worktreePath = + explicitWorktreePath ?? + (await resolveDefaultWorktreePath({ cwd, paseoHome, worktreesRoot, worktreeSlug })); + await mkdir(dirname(worktreePath), { recursive: true }); - // Also handle worktree path collision - let finalWorktreePath = worktreePath; - let pathSuffix = 1; - while (await pathExists(finalWorktreePath)) { - finalWorktreePath = `${worktreePath}-${pathSuffix}`; - pathSuffix++; - } - - // Primitive owner for `git worktree add`; callers route through createWorktreeCore. - await runGitCommand(["worktree", "add", finalWorktreePath, ...sourcePlan.addArguments], { - cwd, - timeout: 120_000, - }); - worktreePath = await normalizePathForOwnership(finalWorktreePath); - - if (sourcePlan.pushRemote) { - await configureWorktreePushRemote({ + // Primitive owner for `git worktree add`; callers route through createWorktreeCore. + await runGitCommand(["worktree", "add", worktreePath, ...sourcePlan.addArguments], { cwd, - branchName: sourcePlan.branchName, - remote: sourcePlan.pushRemote, + timeout: 120_000, }); - } - if (sourcePlan.trackingRemote) { - await configureWorktreeTrackingRemote({ - cwd, - branchName: sourcePlan.branchName, - remote: sourcePlan.trackingRemote, + worktreePath = await normalizePathForOwnership(worktreePath); + + if (sourcePlan.pushRemote) { + await configureWorktreePushRemote({ + cwd, + branchName: sourcePlan.branchName, + remote: sourcePlan.pushRemote, + }); + } + if (sourcePlan.trackingRemote) { + await configureWorktreeTrackingRemote({ + cwd, + branchName: sourcePlan.branchName, + remote: sourcePlan.trackingRemote, + }); + } + + await writePaseoWorktreeMetadata(worktreePath, { + baseRefName: sourcePlan.metadataBaseRefName, + ...(sourcePlan.metadataBaseRef ? { baseRef: sourcePlan.metadataBaseRef } : {}), + ...(sourcePlan.changeRequestLookupTarget + ? { changeRequestLookupTarget: sourcePlan.changeRequestLookupTarget } + : {}), }); + + await seedPaseoConfigFile({ sourceCwd: cwd, targetCwd: worktreePath }); + + return { + branchName: sourcePlan.branchName, + worktreePath, + comparisonBaseRef: sourcePlan.metadataBaseRef ?? sourcePlan.metadataBaseRefName, + }; + } catch (error) { + if ( + fetchedBranch && + fetchedTip && + (await readLocalBranchTip(cwd, fetchedBranch)) === fetchedTip + ) { + await runGitCommand(["branch", "-D", fetchedBranch], { cwd }).catch(() => {}); + } + throw error; } - - await writePaseoWorktreeMetadata(worktreePath, { - baseRefName: sourcePlan.metadataBaseRefName, - ...(sourcePlan.metadataBaseRef ? { baseRef: sourcePlan.metadataBaseRef } : {}), - ...(sourcePlan.changeRequestLookupTarget - ? { changeRequestLookupTarget: sourcePlan.changeRequestLookupTarget } - : {}), - }); - - await seedPaseoConfigFile({ sourceCwd: cwd, targetCwd: worktreePath }); - - return { - branchName: sourcePlan.branchName, - worktreePath, - comparisonBaseRef: sourcePlan.metadataBaseRef ?? sourcePlan.metadataBaseRefName, - }; }; interface ResolveWorktreeSourcePlanOptions { diff --git a/packages/server/tsconfig.scripts.json b/packages/server/tsconfig.scripts.json index cc8e24efd4..6a75825b00 100644 --- a/packages/server/tsconfig.scripts.json +++ b/packages/server/tsconfig.scripts.json @@ -19,6 +19,11 @@ "declaration": false, "sourceMap": true }, - "include": ["scripts/supervisor-entrypoint.ts", "scripts/dev-runner.ts", "scripts/supervisor.ts"], + "include": [ + "scripts/supervisor-entrypoint.ts", + "scripts/dev-runner.ts", + "scripts/supervisor.ts", + "src/executable-resolution/which.d.ts" + ], "exclude": ["node_modules", "dist"] } diff --git a/packages/server/tsconfig.server.json b/packages/server/tsconfig.server.json index 9c868b42df..1c7a5c3579 100644 --- a/packages/server/tsconfig.server.json +++ b/packages/server/tsconfig.server.json @@ -22,7 +22,12 @@ "declarationMap": true, "sourceMap": true }, - "include": ["src/server/**/*", "src/services/**/*", "src/terminal/**/*"], + "include": [ + "src/server/**/*", + "src/services/**/*", + "src/terminal/**/*", + "src/executable-resolution/which.d.ts" + ], "exclude": [ "node_modules", "dist", diff --git a/packages/website/package.json b/packages/website/package.json index 2166f1a22e..b45ec39396 100644 --- a/packages/website/package.json +++ b/packages/website/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/website", - "version": "0.13.2", + "version": "0.15.0-beta.1", "private": true, "type": "module", "scripts": { diff --git a/packages/website/public/schemas/paseo.config.v1.json b/packages/website/public/schemas/paseo.config.v1.json index c1c32ed20a..bae380d4c8 100644 --- a/packages/website/public/schemas/paseo.config.v1.json +++ b/packages/website/public/schemas/paseo.config.v1.json @@ -70,6 +70,14 @@ }, "additionalProperties": {} }, + "usage": { + "type": "object", + "properties": { + "enabled": { + "type": "boolean" + } + } + }, "browserTools": { "type": "object", "properties": { @@ -513,6 +521,12 @@ "idleRuntimeCleanup": { "type": "boolean" }, + "resumeOnStartup": { + "type": "boolean" + }, + "resumePrompt": { + "type": "string" + }, "catalogRefreshTimeoutMs": { "type": "integer", "exclusiveMinimum": 0, diff --git a/packages/website/src/docs.ts b/packages/website/src/docs.ts index 1325cd933f..896d86daf9 100644 --- a/packages/website/src/docs.ts +++ b/packages/website/src/docs.ts @@ -186,7 +186,13 @@ function insertDocByPath(nodes: DocsNavNode[], doc: Doc, stripTopDirectory = fal // A section's top-level directory and its category name the same thing, so // only directories below it become collapsible groups. - if (stripTopDirectory) directories.shift(); + if ( + stripTopDirectory && + directories[0] && + doc.frontmatter.category?.toLowerCase().endsWith(directories[0].toLowerCase()) + ) { + directories.shift(); + } let current = nodes; let parent: Extract | undefined; diff --git a/packages/website/src/plugin-docs-navigation.test.ts b/packages/website/src/plugin-docs-navigation.test.ts index 0aeed8ff88..a3e537620a 100644 --- a/packages/website/src/plugin-docs-navigation.test.ts +++ b/packages/website/src/plugin-docs-navigation.test.ts @@ -1,7 +1,26 @@ import { describe, expect, it } from "vitest"; -import { buildDocsNavTree, getDoc, getDocs, getLegacyDocsRedirect } from "./docs"; +import { buildDocsNavTree, getDoc, getDocs, getLegacyDocsRedirect, parseHeadings } from "./docs"; describe("plugin documentation", () => { + it.each(["en", "zh-CN"] as const)( + "nests local file copying under Git worktrees in %s", + (locale) => { + const workspaces = buildDocsNavTree(getDocs(locale)).find( + (node) => node.type === "category" && node.label === "Workspaces", + ); + expect(workspaces).toMatchObject({ + children: expect.arrayContaining([ + expect.objectContaining({ + type: "group", + href: "/docs/worktrees", + children: [expect.objectContaining({ href: "/docs/worktrees/worktreeinclude" })], + }), + ]), + }); + expect(getDoc("worktrees/worktreeinclude", locale)).toBeDefined(); + }, + ); + it("groups current guides by task without version navigation", () => { const plugins = buildDocsNavTree(getDocs("en")).find( (node) => node.type === "category" && node.label === "Plugins", @@ -14,11 +33,20 @@ describe("plugin documentation", () => { { type: "page", label: "Publishing", href: "/docs/plugins/publishing" }, { type: "page", label: "Provider plugins", href: "/docs/plugins/providers" }, { type: "page", label: "Migration", href: "/docs/plugins/migration" }, + { type: "page", label: "Hooks", href: "/docs/plugins/hooks" }, { type: "page", label: "Reference", href: "/docs/plugins/reference" }, ], }); }); + it.each(["en", "zh-CN"] as const)("resolves worktree placement hook links in %s", (locale) => { + const hooks = getDoc("plugins/hooks", locale)!; + expect(parseHeadings(hooks.content).map((heading) => heading.id)).toContain( + "worktreecreatebefore", + ); + expect(hooks.content).toContain("plugin-examples/worktree-placement"); + }); + it.each(["v0.7", "v0.8"])("redirects %s links to existing current pages", (version) => { for (const page of ["", "/index", "/reference", "/providers", "/migration"]) { const target = `/docs/plugins${page === "/index" ? "" : page}`; @@ -32,7 +60,7 @@ describe("plugin documentation", () => { }); it("serves canonical pages without redirect loops", () => { - for (const page of ["", "/publishing", "/reference", "/providers", "/migration"]) { + for (const page of ["", "/publishing", "/reference", "/providers", "/migration", "/hooks"]) { expect(getLegacyDocsRedirect(`/docs/plugins${page}`)).toBeUndefined(); expect(getLegacyDocsRedirect(`/docs/plugins${page}.md`)).toBeUndefined(); } diff --git a/packages/website/src/schedule-docs.test.ts b/packages/website/src/schedule-docs.test.ts index 015d85fe6c..76fca93287 100644 --- a/packages/website/src/schedule-docs.test.ts +++ b/packages/website/src/schedule-docs.test.ts @@ -4,7 +4,7 @@ import { expect, it } from "vitest"; const docsRoot = path.resolve(import.meta.dirname, "../../../public-docs"); -it.each(["schedules.md", "schedules-cli.md", "mcp.md", "worktrees.md"])( +it.each(["schedules.md", "schedules-cli.md", "mcp.md", "worktrees/index.md"])( "%s makes schedule run retention discoverable", async (file) => { const markdown = await readFile(path.join(docsRoot, file), "utf8"); diff --git a/patches/react-native-enriched-markdown+1.2.0-nightly-20261014-766fc0e67.patch b/patches/react-native-enriched-markdown+1.2.0-nightly-20261014-766fc0e67.patch index 7ec1ec33b5..1568bd6039 100644 --- a/patches/react-native-enriched-markdown+1.2.0-nightly-20261014-766fc0e67.patch +++ b/patches/react-native-enriched-markdown+1.2.0-nightly-20261014-766fc0e67.patch @@ -3770,3 +3770,117 @@ index eaa3279..05a02eb 100644 private: int forceHeightRecalculationCounter_{0}; std::shared_ptr measurementsManager_; +diff --git a/node_modules/react-native-enriched-markdown/ios/generated/ReactCodegen/EnrichedMarkdownTextSpec/Props.h b/node_modules/react-native-enriched-markdown/ios/generated/ReactCodegen/EnrichedMarkdownTextSpec/Props.h +--- a/node_modules/react-native-enriched-markdown/ios/generated/ReactCodegen/EnrichedMarkdownTextSpec/Props.h ++++ b/node_modules/react-native-enriched-markdown/ios/generated/ReactCodegen/EnrichedMarkdownTextSpec/Props.h +@@ -1639,6 +1639,7 @@ + struct EnrichedMarkdownMarkdownStyleCodeStruct { + std::string fontFamily{}; + Float fontSize{0.0}; ++ Float fontScale{0.0}; + SharedColor color{}; + SharedColor backgroundColor{}; + SharedColor borderColor{}; +@@ -1651,6 +1652,7 @@ + folly::dynamic result = folly::dynamic::object(); + result["fontFamily"] = fontFamily; + result["fontSize"] = fontSize; ++ result["fontScale"] = fontScale; + result["color"] = ::facebook::react::toDynamic(color); + result["backgroundColor"] = ::facebook::react::toDynamic(backgroundColor); + result["borderColor"] = ::facebook::react::toDynamic(borderColor); +@@ -1670,6 +1672,10 @@ + if (tmp_fontSize != map.end()) { + fromRawValue(context, tmp_fontSize->second, result.fontSize); + } ++ auto tmp_fontScale = map.find("fontScale"); ++ if (tmp_fontScale != map.end()) { ++ fromRawValue(context, tmp_fontScale->second, result.fontScale); ++ } + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { + fromRawValue(context, tmp_color->second, result.color); +@@ -6185,6 +6191,7 @@ + struct EnrichedMarkdownTextMarkdownStyleCodeStruct { + std::string fontFamily{}; + Float fontSize{0.0}; ++ Float fontScale{0.0}; + SharedColor color{}; + SharedColor backgroundColor{}; + SharedColor borderColor{}; +@@ -6197,6 +6204,7 @@ + folly::dynamic result = folly::dynamic::object(); + result["fontFamily"] = fontFamily; + result["fontSize"] = fontSize; ++ result["fontScale"] = fontScale; + result["color"] = ::facebook::react::toDynamic(color); + result["backgroundColor"] = ::facebook::react::toDynamic(backgroundColor); + result["borderColor"] = ::facebook::react::toDynamic(borderColor); +@@ -6216,6 +6224,10 @@ + if (tmp_fontSize != map.end()) { + fromRawValue(context, tmp_fontSize->second, result.fontSize); + } ++ auto tmp_fontScale = map.find("fontScale"); ++ if (tmp_fontScale != map.end()) { ++ fromRawValue(context, tmp_fontScale->second, result.fontScale); ++ } + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { + fromRawValue(context, tmp_color->second, result.color); +diff --git a/node_modules/react-native-enriched-markdown/android/generated/jni/react/renderer/components/EnrichedMarkdownTextSpec/Props.h b/node_modules/react-native-enriched-markdown/android/generated/jni/react/renderer/components/EnrichedMarkdownTextSpec/Props.h +--- a/node_modules/react-native-enriched-markdown/android/generated/jni/react/renderer/components/EnrichedMarkdownTextSpec/Props.h ++++ b/node_modules/react-native-enriched-markdown/android/generated/jni/react/renderer/components/EnrichedMarkdownTextSpec/Props.h +@@ -1639,6 +1639,7 @@ + struct EnrichedMarkdownMarkdownStyleCodeStruct { + std::string fontFamily{}; + Float fontSize{0.0}; ++ Float fontScale{0.0}; + SharedColor color{}; + SharedColor backgroundColor{}; + SharedColor borderColor{}; +@@ -1651,6 +1652,7 @@ + folly::dynamic result = folly::dynamic::object(); + result["fontFamily"] = fontFamily; + result["fontSize"] = fontSize; ++ result["fontScale"] = fontScale; + result["color"] = ::facebook::react::toDynamic(color); + result["backgroundColor"] = ::facebook::react::toDynamic(backgroundColor); + result["borderColor"] = ::facebook::react::toDynamic(borderColor); +@@ -1669,6 +1671,10 @@ + auto tmp_fontSize = map.find("fontSize"); + if (tmp_fontSize != map.end()) { + fromRawValue(context, tmp_fontSize->second, result.fontSize); ++ } ++ auto tmp_fontScale = map.find("fontScale"); ++ if (tmp_fontScale != map.end()) { ++ fromRawValue(context, tmp_fontScale->second, result.fontScale); + } + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { +@@ -6185,6 +6191,7 @@ + struct EnrichedMarkdownTextMarkdownStyleCodeStruct { + std::string fontFamily{}; + Float fontSize{0.0}; ++ Float fontScale{0.0}; + SharedColor color{}; + SharedColor backgroundColor{}; + SharedColor borderColor{}; +@@ -6197,6 +6204,7 @@ + folly::dynamic result = folly::dynamic::object(); + result["fontFamily"] = fontFamily; + result["fontSize"] = fontSize; ++ result["fontScale"] = fontScale; + result["color"] = ::facebook::react::toDynamic(color); + result["backgroundColor"] = ::facebook::react::toDynamic(backgroundColor); + result["borderColor"] = ::facebook::react::toDynamic(borderColor); +@@ -6215,6 +6223,10 @@ + auto tmp_fontSize = map.find("fontSize"); + if (tmp_fontSize != map.end()) { + fromRawValue(context, tmp_fontSize->second, result.fontSize); ++ } ++ auto tmp_fontScale = map.find("fontScale"); ++ if (tmp_fontScale != map.end()) { ++ fromRawValue(context, tmp_fontScale->second, result.fontScale); + } + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { diff --git a/patches/react-native-svg+15.15.4.patch b/patches/react-native-svg+15.15.4.patch index b6b4a85a90..90a30090d7 100644 --- a/patches/react-native-svg+15.15.4.patch +++ b/patches/react-native-svg+15.15.4.patch @@ -59,3 +59,130 @@ index 0c854d6..7dc2828 100644 } return props.transform as TransformsStyle['transform']; } +diff --git a/node_modules/react-native-svg/android/build.gradle b/node_modules/react-native-svg/android/build.gradle +--- a/node_modules/react-native-svg/android/build.gradle ++++ b/node_modules/react-native-svg/android/build.gradle +@@ -103,6 +103,7 @@ + } + + defaultConfig { ++ testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner' + minSdkVersion safeExtGet('minSdkVersion', 16) + //noinspection OldTargetApi + targetSdkVersion safeExtGet('targetSdkVersion', 28) +@@ -136,6 +137,8 @@ + } + + dependencies { ++ androidTestImplementation 'androidx.test:runner:1.6.2' ++ androidTestImplementation 'androidx.test.ext:junit:1.2.1' + implementation 'com.facebook.react:react-native:+' + implementation("com.facebook.fresco:fresco:${FRESCO_VERSION}") { + exclude group: 'com.facebook.soloader' +diff --git a/node_modules/react-native-svg/android/src/main/java/com/horcrux/svg/SvgView.java b/node_modules/react-native-svg/android/src/main/java/com/horcrux/svg/SvgView.java +--- a/node_modules/react-native-svg/android/src/main/java/com/horcrux/svg/SvgView.java ++++ b/node_modules/react-native-svg/android/src/main/java/com/horcrux/svg/SvgView.java +@@ -159,6 +159,8 @@ + @Override + protected void onSizeChanged(int w, int h, int oldw, int oldh) { + super.onSizeChanged(w, h, oldw, oldh); ++ // Percentage lengths and paths depend on the canvas size, not just SVG props. ++ clearChildCache(); + this.invalidate(); + } + +diff --git a/node_modules/react-native-svg/android/src/androidTest/java/com/horcrux/svg/SvgResizeTest.java b/node_modules/react-native-svg/android/src/androidTest/java/com/horcrux/svg/SvgResizeTest.java +new file mode 100644 +--- /dev/null ++++ b/node_modules/react-native-svg/android/src/androidTest/java/com/horcrux/svg/SvgResizeTest.java +@@ -0,0 +1,90 @@ ++package com.horcrux.svg; ++ ++import static org.junit.Assert.assertEquals; ++import static org.junit.Assert.assertTrue; ++ ++import android.graphics.Bitmap; ++import android.graphics.Canvas; ++import android.graphics.Color; ++import android.view.View; ++import androidx.test.ext.junit.runners.AndroidJUnit4; ++import androidx.test.platform.app.InstrumentationRegistry; ++import com.facebook.react.bridge.BridgeReactContext; ++import com.facebook.react.bridge.DynamicFromObject; ++import com.facebook.react.bridge.JavaOnlyArray; ++import com.facebook.react.bridge.JavaOnlyMap; ++import com.facebook.react.soloader.OpenSourceMergedSoMapping; ++import com.facebook.react.uimanager.DisplayMetricsHolder; ++import com.facebook.soloader.SoLoader; ++import org.junit.Test; ++import org.junit.runner.RunWith; ++ ++@RunWith(AndroidJUnit4.class) ++public class SvgResizeTest { ++ @Test ++ public void percentageFadeFollowsCanvasGrowthAndShrinkage() { ++ InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> { ++ android.content.Context app = InstrumentationRegistry.getInstrumentation().getTargetContext(); ++ DisplayMetricsHolder.initDisplayMetricsIfNotInitialized(app); ++ try { ++ SoLoader.init(app, OpenSourceMergedSoMapping.INSTANCE); ++ } catch (java.io.IOException exception) { ++ throw new RuntimeException(exception); ++ } ++ BridgeReactContext context = new DrawingContext(app); ++ SvgView svg = new SvgView(context); ++ LinearGradientView gradient = new LinearGradientView(context); ++ gradient.setName("fade"); ++ gradient.setX1(new DynamicFromObject("0%")); ++ gradient.setY1(new DynamicFromObject("0%")); ++ gradient.setX2(new DynamicFromObject("0%")); ++ gradient.setY2(new DynamicFromObject("100%")); ++ gradient.setGradientUnits(0); ++ gradient.setGradient(JavaOnlyArray.of(0.0, Color.RED, 1.0, Color.TRANSPARENT)); ++ svg.addView(gradient); ++ // Exercise recursive invalidation as well as the direct child case. ++ GroupView group = new GroupView(context); ++ RectView rectangle = new RectView(context); ++ rectangle.setX(new DynamicFromObject(0.0)); ++ rectangle.setY(new DynamicFromObject(0.0)); ++ rectangle.setWidth(new DynamicFromObject("100%")); ++ rectangle.setHeight(new DynamicFromObject("100%")); ++ rectangle.setFill(JavaOnlyMap.of("type", 1, "brushRef", "fade")); ++ group.addView(rectangle); ++ svg.addView(group); ++ ++ assertFade(svg, 80, 60); ++ assertFade(svg, 160, 120); ++ assertFade(svg, 60, 40); ++ assertFade(svg, 160, 120); ++ }); ++ } ++ ++ // Pixel rendering needs a React context but does not send layout events to JavaScript. ++ private static final class DrawingContext extends BridgeReactContext ++ implements com.facebook.react.uimanager.events.EventDispatcherProvider { ++ DrawingContext(android.content.Context context) { super(context); } ++ ++ @Override ++ public com.facebook.react.uimanager.events.EventDispatcher getEventDispatcher() { return null; } ++ } ++ ++ private static void assertFade(SvgView svg, int width, int height) { ++ svg.measure(View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY), ++ View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY)); ++ svg.layout(0, 0, width, height); ++ Bitmap image = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); ++ svg.draw(new Canvas(image)); ++ try { ++ int middle = Color.alpha(image.getPixel(width / 2, height / 2)); ++ int right = Color.alpha(image.getPixel(width - 2, height / 2)); ++ assertTrue("Gradient midpoint must follow canvas height at " + width + "x" + height ++ + "; alpha=" + middle, middle >= 120 && middle <= 135); ++ assertEquals("Fade must reach the right edge at " + width + "x" + height, middle, right); ++ assertTrue("Fade must end at the new bottom edge", ++ Color.alpha(image.getPixel(width / 2, height - 2)) < 20); ++ } finally { ++ image.recycle(); ++ } ++ } ++} diff --git a/patches/react-native-unistyles+3.2.4.patch b/patches/react-native-unistyles+3.2.4.patch index 7f40053f19..c3da63a8ac 100644 --- a/patches/react-native-unistyles+3.2.4.patch +++ b/patches/react-native-unistyles+3.2.4.patch @@ -486,3 +486,278 @@ diff --git a/node_modules/react-native-unistyles/lib/commonjs/core/withUnistyles ...(narrowedProps.style ? { style: styleSecrets.styles } : {}), +diff --git a/node_modules/react-native-unistyles/lib/commonjs/web/runtime.js b/node_modules/react-native-unistyles/lib/commonjs/web/runtime.js +index 305fa49..5957aa5 100644 +--- a/node_modules/react-native-unistyles/lib/commonjs/web/runtime.js ++++ b/node_modules/react-native-unistyles/lib/commonjs/web/runtime.js +@@ -35,10 +35,17 @@ class UnistylesRuntime { + return this.darkMedia; + } + get colorScheme() { ++ // Read the scheme through fresh lists, never through lightMedia/darkMedia. Chromium defers ++ // MediaQueryList change events while the document is hidden and drops the pending event ++ // of any list whose `matches` was read before the document became visible again, which ++ // would silence the adaptive-theme listeners registered on those two lists. ++ if ((0, _utils.isServer)()) { ++ return _types.ColorScheme.Unspecified; ++ } + switch (true) { +- case this.getLightMedia()?.matches: ++ case window.matchMedia('(prefers-color-scheme: light)').matches: + return _types.ColorScheme.Light; +- case this.getDarkMedia()?.matches: ++ case window.matchMedia('(prefers-color-scheme: dark)').matches: + return _types.ColorScheme.Dark; + default: + return _types.ColorScheme.Unspecified; +diff --git a/node_modules/react-native-unistyles/lib/module/web/runtime.js b/node_modules/react-native-unistyles/lib/module/web/runtime.js +index 7f13a06..c487bee 100644 +--- a/node_modules/react-native-unistyles/lib/module/web/runtime.js ++++ b/node_modules/react-native-unistyles/lib/module/web/runtime.js +@@ -31,10 +31,17 @@ export class UnistylesRuntime { + return this.darkMedia; + } + get colorScheme() { ++ // Read the scheme through fresh lists, never through lightMedia/darkMedia. Chromium defers ++ // MediaQueryList change events while the document is hidden and drops the pending event ++ // of any list whose `matches` was read before the document became visible again, which ++ // would silence the adaptive-theme listeners registered on those two lists. ++ if (isServer()) { ++ return ColorScheme.Unspecified; ++ } + switch (true) { +- case this.getLightMedia()?.matches: ++ case window.matchMedia('(prefers-color-scheme: light)').matches: + return ColorScheme.Light; +- case this.getDarkMedia()?.matches: ++ case window.matchMedia('(prefers-color-scheme: dark)').matches: + return ColorScheme.Dark; + default: + return ColorScheme.Unspecified; +diff --git a/node_modules/react-native-unistyles/src/web/runtime.ts b/node_modules/react-native-unistyles/src/web/runtime.ts +index a16dac0..6519858 100644 +--- a/node_modules/react-native-unistyles/src/web/runtime.ts ++++ b/node_modules/react-native-unistyles/src/web/runtime.ts +@@ -41,8 +41,16 @@ export class UnistylesRuntime { + get colorScheme() { ++ // Read the scheme through fresh lists, never through lightMedia/darkMedia. Chromium defers ++ // MediaQueryList change events while the document is hidden and drops the pending event ++ // of any list whose `matches` was read before the document became visible again, which ++ // would silence the adaptive-theme listeners registered on those two lists. ++ if (isServer()) { ++ return ColorScheme.Unspecified ++ } ++ + switch (true) { +- case this.getLightMedia()?.matches: ++ case window.matchMedia('(prefers-color-scheme: light)').matches: + return ColorScheme.Light +- case this.getDarkMedia()?.matches: ++ case window.matchMedia('(prefers-color-scheme: dark)').matches: + return ColorScheme.Dark + default: + return ColorScheme.Unspecified +diff --git a/node_modules/react-native-unistyles/android/src/main/java/com/unistyles/NativePlatform+android.kt b/node_modules/react-native-unistyles/android/src/main/java/com/unistyles/NativePlatform+android.kt +index 0f8d1f0..154a12a 100644 +--- a/node_modules/react-native-unistyles/android/src/main/java/com/unistyles/NativePlatform+android.kt ++++ b/node_modules/react-native-unistyles/android/src/main/java/com/unistyles/NativePlatform+android.kt +@@ -3,11 +3,16 @@ package com.unistyles + import android.os.Build + import android.content.Context + import android.content.res.Configuration ++import android.content.res.Resources ++import android.os.Handler ++import android.os.Looper + import android.util.DisplayMetrics + import android.view.View + import android.view.WindowManager + import androidx.annotation.Keep ++import androidx.core.content.OnConfigurationChangedProvider + import androidx.core.text.TextUtilsCompat ++import androidx.core.util.Consumer + import androidx.core.view.ViewCompat + import androidx.core.view.WindowCompat + import androidx.core.view.WindowInsetsCompat +@@ -22,6 +27,7 @@ import com.margelo.nitro.unistyles.Insets + import com.margelo.nitro.unistyles.Orientation + import com.margelo.nitro.unistyles.UnistyleDependency + import com.margelo.nitro.unistyles.UnistylesNativeMiniRuntime ++import java.lang.ref.WeakReference + import java.util.Locale + + @Keep +@@ -30,6 +36,14 @@ class NativePlatformAndroid(private val reactContext: ReactApplicationContext): + private val _insets = NativePlatformInsets(reactContext, this::getMiniRuntime) { this.onConfigChange() } + private var _miniRuntime: UnistylesNativeMiniRuntime = buildMiniRuntime() + private val _listener = NativePlatformListener(reactContext, this::getMiniRuntime) { this.diffMiniRuntime() } ++ private var _configurationProvider: WeakReference? = null ++ private val _activityConfigurationListener = Consumer { ++ Handler(Looper.getMainLooper()).post { this.onConfigChange() } ++ } ++ ++ // Application resources can lag behind configuration changes ++ private val configurationResources: Resources ++ get() = reactContext.currentActivity?.resources ?: reactContext.resources + + init { + checkEdgeToEdge() +@@ -37,12 +51,16 @@ class NativePlatformAndroid(private val reactContext: ReactApplicationContext): + } + + fun onDestroy() { ++ stopObservingActivityConfiguration() + _listener.onDestroy() + _insets.onDestroy() + reactContext.removeLifecycleEventListener(this) + } + + override fun onHostResume() { ++ observeActivityConfiguration() ++ // catch configuration changes missed while no Activity was attached ++ onConfigChange() + _insets.getInitialInsets(false) + _insets.startInsetsListener() + } +@@ -51,7 +69,26 @@ class NativePlatformAndroid(private val reactContext: ReactApplicationContext): + _insets.stopInsetsListener() + } + +- override fun onHostDestroy() {} ++ override fun onHostDestroy() { ++ stopObservingActivityConfiguration() ++ } ++ ++ private fun observeActivityConfiguration() { ++ val provider = reactContext.currentActivity as? OnConfigurationChangedProvider ++ ++ if (_configurationProvider?.get() === provider) { ++ return ++ } ++ ++ stopObservingActivityConfiguration() ++ provider?.addOnConfigurationChangedListener(_activityConfigurationListener) ++ _configurationProvider = provider?.let { WeakReference(it) } ++ } ++ ++ private fun stopObservingActivityConfiguration() { ++ _configurationProvider?.get()?.removeOnConfigurationChangedListener(_activityConfigurationListener) ++ _configurationProvider = null ++ } + + override val memorySize: Long + get() = 0 +@@ -61,7 +98,7 @@ class NativePlatformAndroid(private val reactContext: ReactApplicationContext): + } + + override fun getColorScheme(): ColorScheme { +- val uiMode = reactContext.resources.configuration.uiMode ++ val uiMode = configurationResources.configuration.uiMode + + val colorScheme = when (uiMode.and(Configuration.UI_MODE_NIGHT_MASK)) { + Configuration.UI_MODE_NIGHT_YES -> ColorScheme.DARK +@@ -73,15 +110,15 @@ class NativePlatformAndroid(private val reactContext: ReactApplicationContext): + } + + override fun getFontScale(): Double { +- return reactContext.resources.configuration.fontScale.toDouble() ++ return configurationResources.configuration.fontScale.toDouble() + } + + override fun getPixelRatio(): Double { +- return reactContext.resources.displayMetrics.density.toDouble() ++ return configurationResources.displayMetrics.density.toDouble() + } + + override fun getOrientation(): Orientation { +- val orientation = when (reactContext.resources.configuration.orientation) { ++ val orientation = when (configurationResources.configuration.orientation) { + Configuration.ORIENTATION_PORTRAIT -> Orientation.PORTRAIT + Configuration.ORIENTATION_LANDSCAPE -> Orientation.LANDSCAPE + else -> Orientation.PORTRAIT +@@ -122,7 +159,7 @@ class NativePlatformAndroid(private val reactContext: ReactApplicationContext): + return Dimensions(screenWidth, screenHeight) + } + else -> { +- val displayMetrics = reactContext.resources.displayMetrics ++ val displayMetrics = configurationResources.displayMetrics + + reactContext.currentActivity?.windowManager?.currentWindowMetrics?.bounds?.let { + val boundsWidth = (it.width() / displayMetrics.density).toDouble() +@@ -157,7 +194,7 @@ class NativePlatformAndroid(private val reactContext: ReactApplicationContext): + "com.facebook.react.modules.i18nmanager.I18nUtil", + Context.MODE_PRIVATE + ) +- val resourcesLocale = reactContext.resources.configuration.locales[0] ++ val resourcesLocale = configurationResources.configuration.locales[0] + val hasForcedRtl = sharedPrefs.getBoolean("RCTI18nUtil_forceRTL", false) + // user preferences + val isRtl = TextUtilsCompat.getLayoutDirectionFromLocale(Locale.getDefault()) == ViewCompat.LAYOUT_DIRECTION_RTL +diff --git a/node_modules/react-native-unistyles/android/src/main/java/com/unistyles/NativePlatform+insets.kt b/node_modules/react-native-unistyles/android/src/main/java/com/unistyles/NativePlatform+insets.kt +index a9c1804..f5a3c20 100644 +--- a/node_modules/react-native-unistyles/android/src/main/java/com/unistyles/NativePlatform+insets.kt ++++ b/node_modules/react-native-unistyles/android/src/main/java/com/unistyles/NativePlatform+insets.kt +@@ -38,7 +38,7 @@ class NativePlatformInsets( + } + + fun getInsets(): Insets { +- val density = reactContext.resources.displayMetrics.density ++ val density = (reactContext.currentActivity?.resources ?: reactContext.resources).displayMetrics.density + + return Insets( + this._insets.top / density, +diff --git a/node_modules/react-native-unistyles/cxx/shadowTree/ShadowTreeManager.cpp b/node_modules/react-native-unistyles/cxx/shadowTree/ShadowTreeManager.cpp +index 01026dc..3786ec4 100644 +--- a/node_modules/react-native-unistyles/cxx/shadowTree/ShadowTreeManager.cpp ++++ b/node_modules/react-native-unistyles/cxx/shadowTree/ShadowTreeManager.cpp +@@ -17,13 +17,16 @@ void shadow::ShadowTreeManager::updateShadowTree(jsi::Runtime& rt) { + } + + #if REACT_NATIVE_VERSION_MINOR >= 81 +- std::unordered_map tagToProps; ++ // Paseo backport of https://github.com/jpudysz/react-native-unistyles/pull/1357. ++ // UIManager::updateShadowTree commits a root cloned before the commit, so when a ++ // window-size commit (rotation, keyboard) lands in between, the retried Unistyles ++ // commit puts the previous layout constraints back and the app stays laid out for ++ // the old size. Commit here instead and clone from the root the commit hands us. ++ std::unordered_set affectedSurfaces; + + for (const auto& [family, props] : updates) { + auto safeProps = props.isObject() ? props : folly::dynamic::object(); + +- tagToProps.insert({family->getTag(), safeProps}); +- + auto* mutableFamily = const_cast(family); + + if (mutableFamily->nativeProps_DEPRECATED && mutableFamily->nativeProps_DEPRECATED->isObject()) { +@@ -31,9 +34,30 @@ void shadow::ShadowTreeManager::updateShadowTree(jsi::Runtime& rt) { + } else { + mutableFamily->nativeProps_DEPRECATED = std::make_unique(safeProps); + } ++ ++ affectedSurfaces.insert(family->getSurfaceId()); + } + +- UIManagerBinding::getBinding(rt)->getUIManager().updateShadowTree(std::move(tagToProps)); ++ const auto& shadowTreeRegistry = UIManagerBinding::getBinding(rt)->getUIManager().getShadowTreeRegistry(); ++ ++ shadowTreeRegistry.enumerate([&updates, &affectedSurfaces](const ShadowTree& shadowTree, bool&){ ++ if (!affectedSurfaces.contains(shadowTree.getSurfaceId())) { ++ return; ++ } ++ ++ auto transaction = [&updates](const RootShadowNode& oldRootShadowNode) -> RootShadowNode::Unshared { ++ auto affectedNodes = shadow::ShadowTreeManager::findAffectedNodes(oldRootShadowNode, updates); ++ ++ return std::static_pointer_cast(shadow::ShadowTreeManager::cloneShadowTree( ++ oldRootShadowNode, ++ updates, ++ affectedNodes ++ )); ++ }; ++ ++ // mountSynchronously: this is an update from C++, not React ++ shadowTree.commit(transaction, {false, true}); ++ }); + #else + const auto& shadowTreeRegistry = UIManagerBinding::getBinding(rt)->getUIManager().getShadowTreeRegistry(); + diff --git a/plugin-examples/agent-configuration/README.md b/plugin-examples/agent-configuration/README.md index 189afe6cfd..cb191bd3e1 100644 --- a/plugin-examples/agent-configuration/README.md +++ b/plugin-examples/agent-configuration/README.md @@ -1,14 +1,19 @@ # Agent configuration -Changes new Codex agents through `server.before("agent.create", ...)`: +Sets saved Codex options through `server.addHook("agent.create.before", async ...)`: - Sets `config.providerOptions.sandbox_mode` to `workspace-write`. - Sets `config.providerOptions.approval_policy` to `on-request`. -- Adds the `company` server to `config.mcpServers`. -- Preserves other configuration, provider options, MCP servers, and environment overrides. +- Preserves other configuration and provider options. + +Adds the `company` MCP server to Codex launches through +`server.addHook("agent.open.before", async ...)`. The server is never saved in the agent's configuration; +existing saved MCP servers are preserved. Existing agents receive the server through the +[session reopen behavior](../../public-docs/plugins/hooks.md#attach-tools-to-agents). Replace `https://tools.example.com/mcp` in `index.server.ts` with your MCP server URL before using -this example. The URL is a placeholder. The `company` entry replaces an existing server with that name. +this example. A `company` name collision with a saved server or another +plugin fails the session open and names both sources. Install on a daemon with plugins enabled: @@ -16,11 +21,13 @@ Install on a daemon with plugins enabled: paseo plugin install /absolute/path/to/plugin-examples/agent-configuration ``` -The callback receives the request after earlier plugins have transformed it. The nested spreads -preserve their settings; the explicit values replace only the named fields. Paseo validates and saves -the resulting configuration before starting the agent. Existing agents are unchanged. +Each session-open callback receives only this plugin's MCP servers. The nested spreads preserve +entries added by this plugin's earlier callbacks. The create callback receives configuration after +earlier plugins have transformed it; its explicit Codex options replace the named fields in the +saved configuration of new agents and remain after this plugin is disabled. -See the [lifecycle reference](../../public-docs/plugins/reference.md#lifecycle-hooks) for ordering -and callback shapes. [Lifecycle actions](../lifecycle-actions) demonstrates provider switching and -environment injection. Its provider-switch callback clears provider options when changing Codex to -Claude, so use these examples separately when trying the Codex-specific settings. +See [Inject MCP servers](../../public-docs/plugins/hooks.md#inject-mcp-servers) for choosing +between saved configuration and plugin-owned servers. [Lifecycle actions](../lifecycle-actions) +demonstrates provider switching and environment injection. Its provider-switch callback clears +provider options when changing Codex to Claude, so use these examples separately when trying the +Codex-specific settings. diff --git a/plugin-examples/agent-configuration/index.server.ts b/plugin-examples/agent-configuration/index.server.ts index 1f86e63a67..cfb236caa1 100644 --- a/plugin-examples/agent-configuration/index.server.ts +++ b/plugin-examples/agent-configuration/index.server.ts @@ -1,7 +1,7 @@ import type { PluginServerContext } from "@getpaseo/plugin/server"; export default function contribute(server: PluginServerContext) { - server.before("agent.create", ({ request }) => { + server.addHook("agent.create.before", async ({ request }) => { if (request.config.provider !== "codex") { return request; } @@ -15,12 +15,22 @@ export default function contribute(server: PluginServerContext) { sandbox_mode: "workspace-write", approval_policy: "on-request", }, - mcpServers: { - ...request.config.mcpServers, - company: { - type: "http", - url: "https://tools.example.com/mcp", - }, + }, + }; + }); + + server.addHook("agent.open.before", async ({ request }) => { + if (request.provider !== "codex") { + return; + } + + return { + ...request, + mcpServers: { + ...request.mcpServers, + company: { + type: "http", + url: "https://tools.example.com/mcp", }, }, }; diff --git a/plugin-examples/agent-configuration/paseo-plugin.json b/plugin-examples/agent-configuration/paseo-plugin.json index 1a049eda62..98e1460c12 100644 --- a/plugin-examples/agent-configuration/paseo-plugin.json +++ b/plugin-examples/agent-configuration/paseo-plugin.json @@ -1,6 +1,6 @@ { "id": "agent-configuration", "requirements": { - "paseo": ">=0.8.0" + "paseo": ">=0.14.0-beta.1" } } diff --git a/plugin-examples/agent-tools/README.md b/plugin-examples/agent-tools/README.md index e6ece3978e..e8674a9d66 100644 --- a/plugin-examples/agent-tools/README.md +++ b/plugin-examples/agent-tools/README.md @@ -29,5 +29,5 @@ From the repository root, `npm run typecheck` includes this example. Outside thi use `paseo plugin init` to create the package and TypeScript setup, then copy `index.server.ts` and the manifest into that project. -See [Attach tools to agents](../../public-docs/plugins/reference.md#attach-tools-to-agents) +See [Attach tools to agents](../../public-docs/plugins/hooks.md#attach-tools-to-agents) for targeting, execution, provider gates, collisions, and plugin reload behavior. diff --git a/plugin-examples/agent-tools/index.server.ts b/plugin-examples/agent-tools/index.server.ts index 600d743fbd..1bede92569 100644 --- a/plugin-examples/agent-tools/index.server.ts +++ b/plugin-examples/agent-tools/index.server.ts @@ -18,7 +18,7 @@ const appendWorkspaceNote = defineAgentTool({ }); export default function contribute(server: PluginServerContext) { - server.before("agent.session_open", ({ request }) => { + server.addHook("agent.open.before", async ({ request }) => { if (request.labels["notes/enabled"] !== "true") return; return { ...request, tools: [...request.tools, appendWorkspaceNote] }; }); diff --git a/plugin-examples/agent-tools/paseo-plugin.json b/plugin-examples/agent-tools/paseo-plugin.json index eaec7ffaf6..e67c53f072 100644 --- a/plugin-examples/agent-tools/paseo-plugin.json +++ b/plugin-examples/agent-tools/paseo-plugin.json @@ -1,4 +1,4 @@ { "id": "agent-tools", - "requirements": { "paseo": ">=0.13.2" } + "requirements": { "paseo": ">=0.14.0-beta.1" } } diff --git a/plugin-examples/lifecycle-actions/index.server.ts b/plugin-examples/lifecycle-actions/index.server.ts index c97f2a7254..7b1fb1e761 100644 --- a/plugin-examples/lifecycle-actions/index.server.ts +++ b/plugin-examples/lifecycle-actions/index.server.ts @@ -2,7 +2,7 @@ import type { PluginServerContext } from "@getpaseo/plugin/server"; import { latestOutputText, shellCommand } from "./server/inspect"; export default function contribute(server: PluginServerContext) { - server.before("workspace.create", ({ request }) => { + server.addHook("workspace.create.before", async ({ request }) => { if (request.title === "Isolated lifecycle example" && request.source.kind === "directory") { return { ...request, @@ -17,7 +17,7 @@ export default function contribute(server: PluginServerContext) { return request; }); - server.on("agent.turn_ended", async (event, context) => { + server.addHook("agent.turn.after", async (event, context) => { if (event.outcome.kind === "canceled") { return; } @@ -30,7 +30,7 @@ export default function contribute(server: PluginServerContext) { } }); - server.on("agent.permission_requested", async (event, context) => { + server.addHook("agent.permission.before", async (event, context) => { const command = shellCommand(event.request); if (command === null) { return; @@ -56,7 +56,7 @@ export default function contribute(server: PluginServerContext) { } }); - server.before("agent.create", ({ request }) => { + server.addHook("agent.create.before", async ({ request }) => { return { ...request, env: { @@ -66,7 +66,7 @@ export default function contribute(server: PluginServerContext) { }; }); - server.before("agent.create", ({ request }) => { + server.addHook("agent.create.before", async ({ request }) => { if (request.config.provider === "codex") { return { ...request, @@ -82,7 +82,7 @@ export default function contribute(server: PluginServerContext) { return request; }); - server.before("agent.session_open", ({ request }) => { + server.addHook("agent.open.before", async ({ request }) => { return { ...request, env: { diff --git a/plugin-examples/lifecycle-actions/paseo-plugin.json b/plugin-examples/lifecycle-actions/paseo-plugin.json index fe578fae6d..df289d0aa2 100644 --- a/plugin-examples/lifecycle-actions/paseo-plugin.json +++ b/plugin-examples/lifecycle-actions/paseo-plugin.json @@ -1,6 +1,6 @@ { "id": "lifecycle-actions", "requirements": { - "paseo": ">=0.8.0" + "paseo": ">=0.14.0-beta.1" } } diff --git a/plugin-examples/lifecycle-logger/README.md b/plugin-examples/lifecycle-logger/README.md index d6c00b8032..60259d34c7 100644 --- a/plugin-examples/lifecycle-logger/README.md +++ b/plugin-examples/lifecycle-logger/README.md @@ -1,6 +1,6 @@ # Lifecycle logger -Registers all eleven server lifecycle hooks and logs their data as JSON. It observes agent creation, +Registers agent, workspace, and worktree hooks and logs their data as JSON. It observes agent creation, session opening, turns, permissions, archive, and workspace creation/archive. Before hooks return the request unchanged. Environment values are redacted; prompts and timeline content are logged. diff --git a/plugin-examples/lifecycle-logger/index.server.ts b/plugin-examples/lifecycle-logger/index.server.ts index 0f5fd4ed95..e87be2c2f6 100644 --- a/plugin-examples/lifecycle-logger/index.server.ts +++ b/plugin-examples/lifecycle-logger/index.server.ts @@ -2,55 +2,59 @@ import type { PluginServerContext } from "@getpaseo/plugin/server"; import { logHook } from "./server/log"; export default function contribute(server: PluginServerContext) { - server.before("workspace.create", ({ request }) => { - logHook("before workspace.create", { request }); + server.addHook("workspace.create.before", async ({ request }) => { + logHook("workspace.create.before", { request }); return request; }); - server.on("workspace.created", (event) => { - logHook("workspace.created", event); + server.addHook("workspace.create.after", async (event) => { + logHook("workspace.create.after", event); }); - server.on("workspace.archived", (event) => { - logHook("workspace.archived", event); + server.addHook("workspace.archive.after", async (event) => { + logHook("workspace.archive.after", event); }); - server.before("agent.create", ({ request }) => { - logHook("before agent.create", { request }); + server.addHook("worktree.create.after", async (event) => { + logHook("worktree.create.after", event); + }); + + server.addHook("agent.create.before", async ({ request }) => { + logHook("agent.create.before", { request }); return request; }); - server.before("agent.session_open", ({ request }) => { - logHook("before agent.session_open", { request }); + server.addHook("agent.open.before", async ({ request }) => { + logHook("agent.open.before", { request }); return request; }); - server.on("agent.created", (event) => { - logHook("agent.created", event); + server.addHook("agent.create.after", async (event) => { + logHook("agent.create.after", event); }); - server.on("agent.closed", (event) => { - logHook("agent.closed", event); + server.addHook("agent.close.after", async (event) => { + logHook("agent.close.after", event); }); - server.on("agent.turn_started", (event) => { - logHook("agent.turn_started", event); + server.addHook("agent.turn.before", async (event) => { + logHook("agent.turn.before", event); }); - server.on("agent.turn_ended", (event) => { - logHook("agent.turn_ended", event); + server.addHook("agent.turn.after", async (event) => { + logHook("agent.turn.after", event); }); - server.on("agent.permission_requested", (event) => { - logHook("agent.permission_requested", event); + server.addHook("agent.permission.before", async (event) => { + logHook("agent.permission.before", event); }); - server.on("agent.permission_resolved", (event) => { - logHook("agent.permission_resolved", event); + server.addHook("agent.permission.after", async (event) => { + logHook("agent.permission.after", event); }); - server.on("agent.archived", (event) => { - logHook("agent.archived", event); + server.addHook("agent.archive.after", async (event) => { + logHook("agent.archive.after", event); }); return () => {}; diff --git a/plugin-examples/lifecycle-logger/paseo-plugin.json b/plugin-examples/lifecycle-logger/paseo-plugin.json index 8385fbf14c..2c964d4622 100644 --- a/plugin-examples/lifecycle-logger/paseo-plugin.json +++ b/plugin-examples/lifecycle-logger/paseo-plugin.json @@ -1,6 +1,6 @@ { "id": "lifecycle-logger", "requirements": { - "paseo": ">=0.8.0" + "paseo": ">=0.14.0-beta.1" } } diff --git a/plugin-examples/worktree-placement/README.md b/plugin-examples/worktree-placement/README.md new file mode 100644 index 0000000000..8d88d8c627 --- /dev/null +++ b/plugin-examples/worktree-placement/README.md @@ -0,0 +1,36 @@ +# Worktree placement + +Place worktrees next to their source checkout, using the repository directory name and branch. +For `/home/me/src/paseo` on branch `feature/x`, the new worktree is +`/home/me/src/paseo.feature-x`. Slashes in branch names become hyphens. + +Install on Paseo 0.14.0-beta.1 or newer with plugins enabled: + +```bash +paseo plugin install /absolute/path/to/plugin-examples/worktree-placement +``` + +The plugin is one file, `index.server.ts`: + +```ts +import { basename, dirname, join } from "node:path"; +import type { PluginServerContext } from "@getpaseo/plugin/server"; + +export default function contribute(server: PluginServerContext) { + return server.addHook("worktree.create.before", async ({ request }) => ({ + ...request, + path: join( + dirname(request.sourceCheckout), + `${basename(request.sourceCheckout)}.${request.branch.replaceAll("/", "-")}`, + ), + })); +} +``` + +Paseo validates the returned path and refuses an existing one. It creates, lists, restores, +and removes the worktree through the normal workspace workflow. Restoring uses the recorded +path without running the hook. Git can choose a unique branch name after this hook runs; +the path retains the branch name received by the hook. + +See [worktree.create.before](../../public-docs/plugins/hooks.md#worktreecreatebefore) +for the request fields and validation rules. diff --git a/plugin-examples/worktree-placement/index.server.ts b/plugin-examples/worktree-placement/index.server.ts new file mode 100644 index 0000000000..67509a000d --- /dev/null +++ b/plugin-examples/worktree-placement/index.server.ts @@ -0,0 +1,12 @@ +import { basename, dirname, join } from "node:path"; +import type { PluginServerContext } from "@getpaseo/plugin/server"; + +export default function contribute(server: PluginServerContext) { + return server.addHook("worktree.create.before", async ({ request }) => ({ + ...request, + path: join( + dirname(request.sourceCheckout), + `${basename(request.sourceCheckout)}.${request.branch.replaceAll("/", "-")}`, + ), + })); +} diff --git a/plugin-examples/worktree-placement/paseo-plugin.json b/plugin-examples/worktree-placement/paseo-plugin.json new file mode 100644 index 0000000000..ab7f7a20e6 --- /dev/null +++ b/plugin-examples/worktree-placement/paseo-plugin.json @@ -0,0 +1,4 @@ +{ + "id": "worktree-placement", + "requirements": { "paseo": ">=0.14.0-beta.1" } +} diff --git a/plugins/package.json b/plugins/package.json index 30d9929eef..e7d0a6019f 100644 --- a/plugins/package.json +++ b/plugins/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/builtin-plugins", - "version": "0.13.2", + "version": "0.15.0-beta.1", "private": true, "type": "module", "scripts": { diff --git a/plugins/worktree-include/LICENSE b/plugins/worktree-include/LICENSE new file mode 100644 index 0000000000..60cf520f1d --- /dev/null +++ b/plugins/worktree-include/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Carlos Precioso + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/plugins/worktree-include/index.server.ts b/plugins/worktree-include/index.server.ts new file mode 100644 index 0000000000..9055c1677d --- /dev/null +++ b/plugins/worktree-include/index.server.ts @@ -0,0 +1,8 @@ +import type { PluginServerContext } from "@getpaseo/plugin/server"; +import { copyWorktreeIncludes } from "./server/copy.js"; + +export default function contribute(server: PluginServerContext) { + return server.addHook("worktree.create.after", async ({ worktree }) => { + await copyWorktreeIncludes(worktree.path, worktree.sourceCheckout); + }); +} diff --git a/plugins/worktree-include/paseo-plugin.json b/plugins/worktree-include/paseo-plugin.json new file mode 100644 index 0000000000..711476b70f --- /dev/null +++ b/plugins/worktree-include/paseo-plugin.json @@ -0,0 +1 @@ +{ "id": "worktree-include", "requirements": { "paseo": ">=0.14.0-beta.1" } } diff --git a/plugins/worktree-include/server/copy.ts b/plugins/worktree-include/server/copy.ts new file mode 100644 index 0000000000..73a3ba63f3 --- /dev/null +++ b/plugins/worktree-include/server/copy.ts @@ -0,0 +1,71 @@ +// Derived from cprecioso/paseo-worktreeinclude (MIT); see ./LICENSE in the plugin root. +// Copyright (c) 2026 Carlos Precioso. +import { execFile } from "node:child_process"; +import { constants, existsSync } from "node:fs"; +import { copyFile, mkdir } from "node:fs/promises"; +import { dirname, join } from "node:path"; +import { promisify } from "node:util"; + +const exec = promisify(execFile); +const INCLUDE_FILE = ".worktreeinclude"; + +export type CopyResult = + | { kind: "no-include-file" } + | { kind: "copied"; copied: string[]; skipped: string[] }; + +async function git(cwd: string, args: string[], input?: string): Promise { + const child = exec("git", args, { cwd, maxBuffer: 64 * 1024 * 1024 }); + if (input !== undefined) { + child.child.stdin?.end(input); + } + const { stdout } = await child; + return stdout; +} + +async function gitAllowExit1(cwd: string, args: string[], input: string): Promise { + try { + return await git(cwd, args, input); + } catch (error) { + // `git check-ignore` exits 1 when nothing matched. + if ((error as { code?: number }).code === 1) return ""; + throw error; + } +} + +const splitNul = (s: string) => s.split("\0").filter(Boolean); + +// Copy files that match .worktreeinclude (gitignore syntax) +// AND are gitignored, so tracked files are never touched. +export async function copyWorktreeIncludes(worktree: string, source: string): Promise { + if (!existsSync(join(source, INCLUDE_FILE))) return { kind: "no-include-file" }; + + const matches = splitNul( + await git(source, [ + "ls-files", + "--others", + "--ignored", + `--exclude-from=${INCLUDE_FILE}`, + "-z", + ]), + ); + if (matches.length === 0) return { kind: "copied", copied: [], skipped: [] }; + + const ignored = splitNul( + await gitAllowExit1(source, ["check-ignore", "--stdin", "-z"], matches.join("\0") + "\0"), + ); + + const copied: string[] = []; + const skipped: string[] = []; + for (const file of ignored) { + const dest = join(worktree, file); + if (existsSync(dest)) { + skipped.push(file); + continue; + } + await mkdir(dirname(dest), { recursive: true }); + // Clone (APFS/btrfs copy-on-write) when supported, else fall back to a regular copy. + await copyFile(join(source, file), dest, constants.COPYFILE_FICLONE); + copied.push(file); + } + return { kind: "copied", copied, skipped }; +} diff --git a/public-docs/hub/configuration/hub-yml.md b/public-docs/hub/configuration/hub-yml.md index 91b71782d9..26578854a8 100644 --- a/public-docs/hub/configuration/hub-yml.md +++ b/public-docs/hub/configuration/hub-yml.md @@ -141,14 +141,15 @@ steps: Use one of these semantic event names for new GitHub workflows: -| `on` | Matches | -| ------------------------------------- | ------------------------------------------------------------------------- | -| `github.issue_created` | An `issues` delivery whose action is `opened`. | -| `github.pull_request_created` | A `pull_request` delivery whose action is `opened`. | -| `github.issue_comment_created` | An `issue_comment` delivery whose action is `created`, on an issue. | -| `github.pull_request_comment_created` | An `issue_comment` delivery whose action is `created`, on a pull request. | -| `github.issue_label_added` | An `issues` delivery whose action is `labeled`. | -| `github.pull_request_label_added` | A `pull_request` delivery whose action is `labeled`. | +| `on` | Matches | +| -------------------------------------- | ------------------------------------------------------------------------- | +| `github.issue_created` | An `issues` delivery whose action is `opened`. | +| `github.pull_request_created` | A `pull_request` delivery whose action is `opened`. | +| `github.pull_request_ready_for_review` | A draft pull request is marked ready for review. | +| `github.issue_comment_created` | An `issue_comment` delivery whose action is `created`, on an issue. | +| `github.pull_request_comment_created` | An `issue_comment` delivery whose action is `created`, on a pull request. | +| `github.issue_label_added` | An `issues` delivery whose action is `labeled`. | +| `github.pull_request_label_added` | A `pull_request` delivery whose action is `labeled`. | Existing configurations may continue to use `github.issues`, `github.issue_comment`, `github.pull_request_review`, `github.pull_request_review_comment`, and `github.push`. These legacy events retain their existing behavior. diff --git a/public-docs/hub/configuration/hub-yml.zh-CN.md b/public-docs/hub/configuration/hub-yml.zh-CN.md index 13f1ea5478..db8ddd38af 100644 --- a/public-docs/hub/configuration/hub-yml.zh-CN.md +++ b/public-docs/hub/configuration/hub-yml.zh-CN.md @@ -139,14 +139,15 @@ steps: 新的 GitHub workflow 请使用以下语义化事件名之一: -| `on` | 匹配 | -| ------------------------------------- | ----------------------------------------------------------------- | -| `github.issue_created` | action 为 `opened` 的 `issues` 投递。 | -| `github.pull_request_created` | action 为 `opened` 的 `pull_request` 投递。 | -| `github.issue_comment_created` | 在 issue 上、action 为 `created` 的 `issue_comment` 投递。 | -| `github.pull_request_comment_created` | 在 Pull Request 上、action 为 `created` 的 `issue_comment` 投递。 | -| `github.issue_label_added` | action 为 `labeled` 的 `issues` 投递。 | -| `github.pull_request_label_added` | action 为 `labeled` 的 `pull_request` 投递。 | +| `on` | 匹配 | +| -------------------------------------- | ----------------------------------------------------------------- | +| `github.issue_created` | action 为 `opened` 的 `issues` 投递。 | +| `github.pull_request_created` | action 为 `opened` 的 `pull_request` 投递。 | +| `github.pull_request_ready_for_review` | 草稿 PR 被标记为可审查。 | +| `github.issue_comment_created` | 在 issue 上、action 为 `created` 的 `issue_comment` 投递。 | +| `github.pull_request_comment_created` | 在 Pull Request 上、action 为 `created` 的 `issue_comment` 投递。 | +| `github.issue_label_added` | action 为 `labeled` 的 `issues` 投递。 | +| `github.pull_request_label_added` | action 为 `labeled` 的 `pull_request` 投递。 | 已有的配置可以继续使用 `github.issues`、`github.issue_comment`、`github.pull_request_review`、`github.pull_request_review_comment` 和 `github.push`。这些旧版事件保持原有的行为。 diff --git a/public-docs/hub/self-hosting/github-app.md b/public-docs/hub/self-hosting/github-app.md index 740ce9da5c..ad47a03f42 100644 --- a/public-docs/hub/self-hosting/github-app.md +++ b/public-docs/hub/self-hosting/github-app.md @@ -31,7 +31,7 @@ Keep GitHub's SSL verification enabled. ## Subscribe to GitHub events -Under **Subscribe to events**, select **Issue comment**, **Issues**, **Pull requests**, **Pull request review**, **Pull request review comment**, and **Push**. **Pull requests** is required for `github.pull_request_created` and `github.pull_request_label_added`. +Under **Subscribe to events**, select **Issue comment**, **Issues**, **Pull requests**, **Pull request review**, **Pull request review comment**, and **Push**. **Pull requests** is required for `github.pull_request_created`, `github.pull_request_ready_for_review`, and `github.pull_request_label_added`. ## Connect repositories diff --git a/public-docs/hub/self-hosting/github-app.zh-CN.md b/public-docs/hub/self-hosting/github-app.zh-CN.md index 75c0ac67a4..ef892fe815 100644 --- a/public-docs/hub/self-hosting/github-app.zh-CN.md +++ b/public-docs/hub/self-hosting/github-app.zh-CN.md @@ -29,7 +29,7 @@ GitHub 会使用以下 Hub URL: ## 订阅 GitHub 事件 {#subscribe-to-github-events} -在 **Subscribe to events** 下,选择 **Issue comment**、**Issues**、**Pull requests**、**Pull request review**、**Pull request review comment** 和 **Push**。`github.pull_request_created` 和 `github.pull_request_label_added` 需要 **Pull requests**。 +在 **Subscribe to events** 下,选择 **Issue comment**、**Issues**、**Pull requests**、**Pull request review**、**Pull request review comment** 和 **Push**。`github.pull_request_created`、`github.pull_request_ready_for_review` 和 `github.pull_request_label_added` 需要 **Pull requests**。 ## 连接仓库 {#connect-repositories} diff --git a/public-docs/hub/triggers/github.md b/public-docs/hub/triggers/github.md index 92be54bfe1..3585a2be3a 100644 --- a/public-docs/hub/triggers/github.md +++ b/public-docs/hub/triggers/github.md @@ -74,6 +74,10 @@ steps: `github.pull_request_created` fires only when someone opens a pull request. +To wait until a draft is finished, change `on` in the example above to `github.pull_request_ready_for_review`. It fires only when a draft is marked ready, with the user making that transition checked against `from_users`. Opening a pull request, later pushes, and converting it back to draft do not fire this event. + +Pull request webhook context includes `github.pull_request.draft` and `github.pull_request.head_sha` as delivered by GitHub. `github.pull_request` is `null` for other events, including conversation comments on a pull request. Fetch the live pull request with `gh pr view` before reviewing and again before posting. Finish without posting if it is now draft or its head differs from the reviewed SHA. Converting back to draft does not cancel a Hub run already in progress; the workflow owns these live checks. + ## Respond to new comments `.paseo/workflows/respond-to-issue-comment.yml`: @@ -177,14 +181,15 @@ steps: ## Choose the event -| `on` | Fires when | -| ------------------------------------- | ---------------------------------------------------- | -| `github.issue_created` | An issue is opened. | -| `github.pull_request_created` | A pull request is opened. | -| `github.issue_comment_created` | A comment is created on an issue. | -| `github.pull_request_comment_created` | A conversation comment is created on a pull request. | -| `github.issue_label_added` | A label is added to an issue. | -| `github.pull_request_label_added` | A label is added to a pull request. | +| `on` | Fires when | +| -------------------------------------- | ---------------------------------------------------- | +| `github.issue_created` | An issue is opened. | +| `github.pull_request_created` | A pull request is opened. | +| `github.pull_request_ready_for_review` | A draft pull request is marked ready for review. | +| `github.issue_comment_created` | A comment is created on an issue. | +| `github.pull_request_comment_created` | A conversation comment is created on a pull request. | +| `github.issue_label_added` | A label is added to an issue. | +| `github.pull_request_label_added` | A label is added to a pull request. | Choose `github.issue_comment_created` for a comment on an issue and `github.pull_request_comment_created` for a conversation comment on a pull request. GitHub delivers both as issue comments; Hub separates them for you. A comment on a changed line is a diff comment, covered by the legacy `github.pull_request_review_comment` event. diff --git a/public-docs/hub/triggers/github.zh-CN.md b/public-docs/hub/triggers/github.zh-CN.md index 3f599873f6..71c033129f 100644 --- a/public-docs/hub/triggers/github.zh-CN.md +++ b/public-docs/hub/triggers/github.zh-CN.md @@ -72,6 +72,10 @@ steps: `github.pull_request_created` 只在有人创建 PR 时触发。 +若要等草稿完成后再开始审查,将上例的 `on` 改为 `github.pull_request_ready_for_review`。只有将草稿 PR 标记为可审查时才会触发;创建 PR、后续 push 和转回草稿都不会触发。`from_users` 匹配执行此操作的用户。 + +PR webhook 的上下文通过 `github.pull_request.draft` 和 `github.pull_request.head_sha` 提供投递时的草稿状态和 head commit。其他事件(包括 PR 会话评论)的此字段为 `null`。审查前及发布结果前,通过 `gh pr view` 重新获取 PR;如果它已成为草稿或 head 与已审查的 SHA 不同,就结束运行而不发布结果。转回草稿不会取消已启动的 Hub 运行,workflow 应自行检查状态。 + ## 回复新评论 {#respond-to-new-comments} `.paseo/workflows/respond-to-issue-comment.yml`: @@ -175,14 +179,15 @@ steps: ## 选择事件 {#choose-the-event} -| `on` | 触发时机 | -| ------------------------------------- | ---------------------- | -| `github.issue_created` | 创建 issue。 | -| `github.pull_request_created` | 创建 PR。 | -| `github.issue_comment_created` | 在 issue 上创建评论。 | -| `github.pull_request_comment_created` | 在 PR 上创建对话评论。 | -| `github.issue_label_added` | 为 issue 添加标签。 | -| `github.pull_request_label_added` | 为 PR 添加标签。 | +| `on` | 触发时机 | +| -------------------------------------- | ------------------------ | +| `github.issue_created` | 创建 issue。 | +| `github.pull_request_created` | 创建 PR。 | +| `github.pull_request_ready_for_review` | 草稿 PR 被标记为可审查。 | +| `github.issue_comment_created` | 在 issue 上创建评论。 | +| `github.pull_request_comment_created` | 在 PR 上创建对话评论。 | +| `github.issue_label_added` | 为 issue 添加标签。 | +| `github.pull_request_label_added` | 为 PR 添加标签。 | issue 上的评论选择 `github.issue_comment_created`,PR 上的对话评论选择 `github.pull_request_comment_created`。GitHub 把两者都作为 issue 评论投递;Hub 会替你区分它们。针对某一行改动的评论属于 diff 评论,由旧的 `github.pull_request_review_comment` 事件处理。 diff --git a/public-docs/hub/triggers/index.md b/public-docs/hub/triggers/index.md index 164d1739eb..002ad5c20e 100644 --- a/public-docs/hub/triggers/index.md +++ b/public-docs/hub/triggers/index.md @@ -87,17 +87,18 @@ Hub includes an `executionId` in each prompt. When using a continuing agent, pas ## Events -| `on` | Fires when | -| ------------------------------------- | ---------------------------------------------------- | -| `github.issue_created` | An issue is opened. | -| `github.pull_request_created` | A pull request is opened. | -| `github.issue_comment_created` | A comment is created on an issue. | -| `github.pull_request_comment_created` | A conversation comment is created on a pull request. | -| `github.issue_label_added` | A label is added to an issue. | -| `github.pull_request_label_added` | A label is added to a pull request. | -| `slack.mention` | The bot is mentioned in a channel. | -| `discord.mention` | The bot is mentioned in a guild. | -| `manual.run` | A run started from the API. | +| `on` | Fires when | +| -------------------------------------- | ---------------------------------------------------- | +| `github.issue_created` | An issue is opened. | +| `github.pull_request_created` | A pull request is opened. | +| `github.pull_request_ready_for_review` | A draft pull request is marked ready for review. | +| `github.issue_comment_created` | A comment is created on an issue. | +| `github.pull_request_comment_created` | A conversation comment is created on a pull request. | +| `github.issue_label_added` | A label is added to an issue. | +| `github.pull_request_label_added` | A label is added to a pull request. | +| `slack.mention` | The bot is mentioned in a channel. | +| `discord.mention` | The bot is mentioned in a guild. | +| `manual.run` | A run started from the API. | New GitHub workflows should use a semantic event. The five legacy events remain compatible: `github.issues`, `github.issue_comment`, `github.pull_request_review`, `github.pull_request_review_comment`, and `github.push`. See [GitHub triggers](/docs/hub/triggers/github) for complete workflows and when to use each event. diff --git a/public-docs/hub/triggers/index.zh-CN.md b/public-docs/hub/triggers/index.zh-CN.md index 9835633efd..549614ca1a 100644 --- a/public-docs/hub/triggers/index.zh-CN.md +++ b/public-docs/hub/triggers/index.zh-CN.md @@ -85,17 +85,18 @@ Hub 在每段提示词中都包含一个 `executionId`。使用持续的 Agent ## 事件 {#events} -| `on` | 触发时机 | -| ------------------------------------- | ------------------------------- | -| `github.issue_created` | 有 issue 被创建。 | -| `github.pull_request_created` | 有 Pull Request 被创建。 | -| `github.issue_comment_created` | issue 上新增了评论。 | -| `github.pull_request_comment_created` | Pull Request 上新增了对话评论。 | -| `github.issue_label_added` | issue 被添加了标签。 | -| `github.pull_request_label_added` | Pull Request 被添加了标签。 | -| `slack.mention` | 机器人在频道中被提及。 | -| `discord.mention` | 机器人在服务器中被提及。 | -| `manual.run` | 通过 API 发起了一次运行。 | +| `on` | 触发时机 | +| -------------------------------------- | ------------------------------- | +| `github.issue_created` | 有 issue 被创建。 | +| `github.pull_request_created` | 有 Pull Request 被创建。 | +| `github.pull_request_ready_for_review` | 草稿 PR 被标记为可审查。 | +| `github.issue_comment_created` | issue 上新增了评论。 | +| `github.pull_request_comment_created` | Pull Request 上新增了对话评论。 | +| `github.issue_label_added` | issue 被添加了标签。 | +| `github.pull_request_label_added` | Pull Request 被添加了标签。 | +| `slack.mention` | 机器人在频道中被提及。 | +| `discord.mention` | 机器人在服务器中被提及。 | +| `manual.run` | 通过 API 发起了一次运行。 | 新的 GitHub workflow 应使用语义化事件。五个旧版事件仍然兼容:`github.issues`、`github.issue_comment`、`github.pull_request_review`、`github.pull_request_review_comment` 和 `github.push`。完整的 workflow 以及何时使用哪个事件,见 [GitHub 触发器](/docs/hub/triggers/github)。 diff --git a/public-docs/plugins/hooks.md b/public-docs/plugins/hooks.md new file mode 100644 index 0000000000..b535821e62 --- /dev/null +++ b/public-docs/plugins/hooks.md @@ -0,0 +1,659 @@ +--- +title: Plugin hooks +description: Register hooks to change requests or observe agent and workspace operations. +nav: Hooks +order: 48 +category: Plugins +--- + +# Plugin hooks + +Use `server.addHook(name, handler)` in `index.server.ts`. Hooks run while the plugin is enabled, even with no app connected. `addHook` is available from Paseo 0.14; set `requirements.paseo` to the release you build against. + +```ts +import type { PluginServerContext } from "@getpaseo/plugin/server"; + +export default function contribute(server: PluginServerContext) { + const remove = server.addHook("agent.open.before", async ({ request }) => ({ + ...request, + env: { ...request.env, REGION: "eu" }, + })); + return remove; +} +``` + +## Naming and timing + +Names follow `subject.operation.position`: the subject, the operation, then `before` or `after`. The name identifies a lifecycle position. Whether Paseo waits is a per-hook property shown in the table below. `workspace` covers every workspace; `worktree` covers only git worktrees. + +- Waiting hooks finish before Paseo continues. Throwing, returning invalid data, or exceeding 30 seconds fails the operation with `Plugin failed: …`. Request-changing hooks receive `{ request }` and may return a complete replacement request or `undefined`. +- Notifications receive the event object and return `Promise`. Paseo does not wait; errors are logged against the plugin and the operation continues. `agent.turn.before` and `agent.permission.before` are notifications fired when a turn starts or a permission becomes pending. + +All handlers must be async. Turn completion includes success, failure, and cancellation; inspect `outcome`. Permission completion includes every resolution; inspect `resolution`. + +Creating an agent happens once, and `agent.create.before` changes its saved configuration. Opening starts the provider process: the first run, resume after a daemon restart, reading history, importing an outside session, or reload. `agent.open.before` contributes launch-only environment, tools, and MCP servers each time. Creating opens the agent; opening an existing agent does not create it; closing ends the running instance. Opening a tab in the app is a separate action. + +`worktree.create.after` runs before the workspace is registered. It precedes `workspace.create.after`, and both precede the first agent's `agent.create.before` / `agent.open.before`. + +### Return early from a waiting hook + +Start detached work and return when the operation should continue immediately: + +```ts +server.addHook("worktree.create.after", async ({ worktree }) => { + void warmCaches(worktree.path); +}); +``` + +Paseo only sees the returned promise, so detached work gets no error reporting and no cancellation `signal`. + +## Hooks + +| Hook | Waits | Payload | Handler may change | +| ------------------------- | ----- | -------------------------------------- | ---------------------------------------------- | +| `workspace.create.before` | yes | `{ request }` | Entire create request | +| `workspace.create.after` | no | `{ workspace }` | | +| `workspace.archive.after` | no | `{ workspace }` | | +| `worktree.create.before` | yes | `{ request }` | Creation options and destination | +| `worktree.create.after` | yes | `{ worktree }` | Files in the worktree; throw to abort creation | +| `agent.create.before` | yes | `{ request: { config, env? } }` | Saved config except `cwd`; `env` | +| `agent.create.after` | no | `{ agent }` | | +| `agent.open.before` | yes | `{ request }` | Launch-only `env`, `tools`, `mcpServers` | +| `agent.close.after` | no | `{ agent }` | | +| `agent.archive.after` | no | `{ agent, archivedAt }` | | +| `agent.turn.before` | no | `{ agent, turnId }` | | +| `agent.turn.after` | no | `{ agent, turnId, outcome, timeline }` | | +| `agent.permission.before` | no | `{ agent, request }` | | +| `agent.permission.after` | no | `{ agent, requestId, resolution }` | | + +## Shared payloads + +```ts +interface PluginHookAgent { + id: string; + workspaceId: string | null; + parentAgentId: string | null; + provider: string; + cwd: string; + title: string | null; +} + +interface PluginHookWorkspace { + id: string; + projectId: string; + cwd: string; + name: string | null; + archivedAt: string | null; +} + +type PluginTurnOutcome = + | { kind: "completed" } + | { kind: "failed"; error: { message: string; code?: string } } + | { kind: "canceled"; reason: string }; +``` + +| Field | Shape / meaning | +| ------------ | -------------------------------------------------------------------------------------- | +| `turnId` | Provider-reported `string` or `null`; can repeat after a session reopens | +| `timeline` | Deprecated, always `[]`; fetch history with the SDK. | +| `request` | SDK `AgentPermissionRequest`; `kind` is `tool`, `plan`, `question`, `mode`, or `other` | +| `resolution` | SDK `AgentPermissionResponse` | +| `archivedAt` | Timestamp string | + +## workspace.create.before + +Receives `{ request }` with `source`, optional `title`, and `firstAgentContext`. You may replace the entire explicit create request; a throw, invalid result, or timeout fails creation. Existing workspaces and directory lookup/import are unaffected. + +### Choose workspace isolation + +```ts +server.addHook("workspace.create.before", async ({ request }) => { + if (request.source.kind !== "directory") { + return request; + } + + return { + ...request, + source: { + kind: "worktree", + cwd: request.source.path, + action: "branch-off", + }, + }; +}); +``` + +**Result:** an explicit directory creation request becomes a worktree request. Existing workspaces +and directory lookup/import operations are unaffected. + +## workspace.create.after + +Fires after the workspace record is created and its directory is available. Receives `{ workspace }`. + +```ts +server.addHook("workspace.create.after", async ({ workspace }) => { + console.log(workspace); +}); +``` + +## workspace.archive.after + +Fires after archive state is saved. Receives `{ workspace }`; worktree cleanup can still be pending. + +```ts +server.addHook("workspace.archive.after", async ({ workspace }) => { + console.log(workspace); +}); +``` + +## worktree.create.before {#worktreecreatebefore} + +Choose the location and creation options for a new worktree. Paseo awaits this hook before `git worktree add`, on creation from the app, CLI, MCP, and agent creation. Receives `{ request }`; return a complete replacement request or `undefined` to keep it. Throwing, invalid returned data, or a 30-second timeout aborts creation with the plugin and hook named in the error. + +```ts +import { basename, dirname, join } from "node:path"; + +server.addHook("worktree.create.before", async ({ request }) => ({ + ...request, + path: join( + dirname(request.sourceCheckout), + `${basename(request.sourceCheckout)}.${request.branch.replaceAll("/", "-")}`, + ), +})); +``` + +For source `/home/me/src/paseo` and branch `feature/x`, this creates `/home/me/src/paseo.feature-x`. See the complete [worktree-placement example](https://github.com/getpaseo/paseo/tree/main/plugin-examples/worktree-placement). + +| Request field | Meaning | +| ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | +| `kind` | `branch-off`, `checkout-branch`, `checkout-change-request`, or `checkout-github-pr` | +| `branch` | Requested local branch name | +| `baseRef` | Starting ref for branch-off; comparison base for change requests; absent for `checkout-branch`. To branch off a ref, return `kind: "branch-off"`. | +| `slug` | Normalized worktree name | +| `path` | Absolute destination; initially the default location with any existing-path suffix resolved | +| `repoRoot` | Read-only main repository root | +| `sourceCheckout` | Read-only source checkout root, including when creation starts from another worktree | +| `forge`, `changeRequestNumber`, `headRef` | Change-request checkout identity; GitHub legacy checkouts use `githubPrNumber` instead of `forge` and `changeRequestNumber` | +| `headRepositoryOwner`, `headRepository` | Optional source repository facts; `headRepository` is present only on change-request checkouts | +| `checkoutRefs` | Optional fetch sources: `{ remoteName?: string, remoteRef: string }[]` | +| `pushRemoteUrl`, `trackOriginHead` | Optional push destination and tracking policy | + +Once `path` is returned, `slug` only feeds branch-off naming; the CLI looks up worktrees by the basename of their path. + +Every field except `repoRoot` and `sourceCheckout` is transformable. Return all required facts for the chosen `kind`. Paseo resolves the Git source plan after this hook, so handlers can change the branch and base before fetching refs, while Git can still choose a unique final branch name afterward. + +Paseo resolves symlinked parents and validates the returned path. It must be absolute, must not exist, and must not be the filesystem root, your home directory, the repository root, inside a `.git` directory, or an ancestor of the repository. An existing destination fails creation; Paseo never adds a suffix to a plugin-chosen path. The plugin must leave directory creation to Paseo. + +Ordering: `worktree.create.before` → `git worktree add` → `worktree.create.after` → workspace registration. Restoring a missing worktree recreates it at its recorded path without running either worktree creation hook. + +## worktree.create.after + +Paseo waits for this hook after a new git worktree exists and before workspace registration, setup, terminals, or agents. Receives `{ worktree: { path, branch, sourceCheckout } }`: the absolute worktree path, branch name, and source checkout directory. There is no workspace id yet. Return nothing; write files directly into the worktree. Throwing or exceeding 30 seconds aborts creation and removes the new worktree. + +This covers branch-off, branch checkout, and PR checkout creation. Restoring a missing archived worktree uses a separate recovery path and does not fire this hook. + +```ts +import { copyFile } from "node:fs/promises"; + +server.addHook("worktree.create.after", async ({ worktree }) => { + await copyFile(`${worktree.sourceCheckout}/.env`, `${worktree.path}/.env`); +}); +``` + +## agent.create.before + +Receives `{ request: { config, env? } }`. Config changes are saved and remain after the plugin is disabled or removed; `env` applies to the initial launch and is not saved. You cannot change `config.cwd`. A throw, invalid result, or timeout fails creation. + +**`agent.create.before.config`** uses `AgentSessionConfig`: + +| Fields | Constraint | +| --------------------------------------------- | -------------------------------------------------------------------------- | +| `provider`, `model` | Separate fields; changing provider may require changing model/mode/options | +| `modeId`, `thinkingOptionId`, `featureValues` | Provider-specific selections | +| `title`, `systemPrompt` | Agent configuration | +| `providerOptions` | Opaque provider-specific options | +| `mcpServers`, `toolPolicy` | MCP configuration and exact-tool preapprovals | +| `cwd` | Cannot change | + +### Change saved configuration + +Add this callback inside `contribute(server)` to set the saved options for new Codex agents: + +```ts +server.addHook("agent.create.before", async ({ request }) => { + if (request.config.provider !== "codex") { + return request; + } + + return { + ...request, + config: { + ...request.config, + providerOptions: { + ...request.config.providerOptions, + sandbox_mode: "workspace-write", + approval_policy: "on-request", + }, + }, + }; +}); +``` + +| Input | Result | +| ------------------------------------------- | ----------------------- | +| `providerOptions.sandbox_mode: "read-only"` | `"workspace-write"` | +| `providerOptions.web_search: "disabled"` | Preserved by the spread | + +The selected provider validates `providerOptions`. Explicit Codex sandbox and approval options +override its mode presets. + +## agent.create.after + +Ordinary creation finishes. Receives `{ agent }`; import and resume do not fire it. + +```ts +server.addHook("agent.create.after", async ({ agent }) => { + console.log(agent); +}); +``` + +## agent.open.before + +Receives `{ request }`; only `env`, `tools`, and `mcpServers` may change, for this launch. All other fields are read-only. A throw, invalid result, or timeout fails the open. + +**`agent.open.before` request example:** + +```json +{ + "agentId": "agent-123", + "workspaceId": "workspace-456", + "provider": "codex", + "cwd": "/projects/shop", + "title": "Workspace notes", + "labels": { "notes/enabled": "true" }, + "tools": [], + "mcpServers": {}, + "reason": "resume", + "purpose": "interactive", + "env": { "COMPANY_ENV": "development" } +} +``` + +| Field | Values | +| ------------- | ----------------------------------------------------------------------------------------------------------------------- | +| `workspaceId` | String or `null` | +| `title` | Read-only string or `null`; creation title on create, stored title on resume. | +| `labels` | Read-only string map; creation labels on create, stored labels on resume. | +| `tools` | Editable `AgentToolDefinition[]`, local to this plugin. See [Attach tools to agents](#attach-tools-to-agents). | +| `mcpServers` | Editable launch-only server map, local to this plugin. See [Inject MCP servers](#inject-mcp-servers). | +| `reason` | `create`, `resume`, `refresh`, `import` | +| `purpose` | `interactive`, `history` | +| `env` | Launch override map; excludes the daemon's inherited environment. Replace the map to add, replace, or remove overrides. | + +### Inject environment variables on every session opening + +```ts +server.addHook("agent.open.before", async ({ request }) => { + return { + ...request, + env: { + ...request.env, + COMPANY_ENV: "development", + }, + }; +}); +``` + +Session-open overrides are re-derived on every open. `agent.create.before.env` applies only to the +initial launch and is not saved in the agent's configuration. + +### Inject MCP servers + +Use `agent.create.before.config.mcpServers` when the server should become part of the agent's saved +configuration. For a plugin-owned server, add this callback inside `contribute(server)`, replacing +the placeholder URL with your MCP endpoint: + +```ts +server.addHook("agent.open.before", async ({ request }) => { + if (request.provider !== "codex") return; + + return { + ...request, + mcpServers: { + ...request.mcpServers, + company: { type: "http", url: "https://tools.example.com/mcp" }, + }, + }; +}); +``` + +`request.mcpServers` uses the same server configurations as `AgentSessionConfig.mcpServers`. +The map starts empty for each plugin and accumulates across that plugin's own callbacks. It never +contains the agent's saved servers or another plugin's servers. Replace the map to add, replace, +or remove this plugin's entries; returning `undefined` preserves it. Paseo merges the plugins' +final maps in plugin-ID order. + +A name colliding with a saved server, Paseo's internal `paseo` server, or another plugin's server +fails the session open and names the server and both sources. A provider without MCP support fails +with `does not support MCP servers`, naming the plugin. Opens with `purpose: "history"` ignore +these servers. Install, disable, and reload changes reach existing agents through the +[session reopen behavior](#attach-tools-to-agents). + +### Attach tools to agents + +Define a tool in `index.server.ts` and attach it in `server.addHook("agent.open.before", async handler)`. +This example gives `append_workspace_note` only to agents with the label `notes/enabled: "true"`: + +```ts +import { writeFile } from "node:fs/promises"; +import path from "node:path"; +import { z } from "zod"; +import { defineAgentTool, type PluginServerContext } from "@getpaseo/plugin/server"; + +const appendWorkspaceNote = defineAgentTool({ + name: "append_workspace_note", + description: "Append a note to AGENT_NOTES.md in this agent's working directory.", + input: z.object({ note: z.string().min(1).describe("Note to append") }), + async execute({ note }, { agent, signal }) { + const notePath = path.join(agent.cwd, "AGENT_NOTES.md"); + await writeFile(notePath, `${note}\n`, { encoding: "utf8", flag: "a", signal }); + return { + text: `Saved note to ${notePath}`, + structuredContent: { path: notePath }, + }; + }, +}); + +export default function contribute(server: PluginServerContext) { + server.addHook("agent.open.before", async ({ request }) => { + if (request.labels["notes/enabled"] !== "true") return; + return { ...request, tools: [...request.tools, appendWorkspaceNote] }; + }); + return () => {}; +} +``` + +Set the label when creating an agent with the SDK: + +```ts +const agent = await paseo.agents.create({ + config: { provider: "codex/gpt-5.4" }, + cwd: "/projects/shop", + labels: { "notes/enabled": "true" }, +}); +``` + +Select agents using any of the session-open request fields: + +| Select by | Condition in the callback | +| ---------------- | -------------------------------------------- | +| Label | `request.labels["notes/enabled"] === "true"` | +| Provider | `request.provider === "codex"` | +| Workspace | `request.workspaceId === "workspace-456"` | +| Individual agent | `request.agentId === chosenAgentId` | + +`request.tools` starts empty for each plugin. Each callback sees the tools returned by earlier +callbacks in that plugin; replace the array to add or remove tools. Returning `undefined` preserves +the request. Tools are ignored for `purpose: "history"`. + +Import `defineAgentTool`, `AgentToolDefinition`, `AgentToolContext`, and `AgentToolResult` from +`@getpaseo/plugin/server`. The helper infers the validated input from your Zod schema: + +```ts +declare function defineAgentTool(tool: { + name: string; + title?: string; + description: string; + input: Input; + execute( + input: z.output, + context: AgentToolContext, + ): AgentToolResult | Promise; +}): AgentToolDefinition; + +interface AgentToolResult { + text?: string; + structuredContent?: unknown; + isError?: boolean; +} +``` + +| Execution context | Value | +| ----------------- | --------------------------------------------------------------------------------------------------- | +| `agent` | Calling agent as a `PluginHookAgent`, including `id`, `workspaceId`, `provider`, `cwd`, and `title` | +| `paseo` | SDK connected to this daemon | +| `signal` | Abort signal for this tool call; pass it to file operations or external requests | + +`execute` runs in the plugin process. Closures and the original Zod schema stay there; only tool +metadata and call inputs/results cross the process boundary. Paseo validates input before calling +`execute`. Invalid input returns schema issues to the agent. A thrown error becomes +`{ isError: true, text: message }` and the plugin keeps running. Canceling the call or closing its +transport aborts `signal` and discards the result. Tool calls have a 10 minute ceiling, separate +from the 30 second hook timeout. Closing or reopening an agent session drops its old definitions. + +Return model-visible text in `text`. `structuredContent` must be JSON-serializable; when `text` is +omitted, Paseo formats that value as text for the model. Set `isError: true` to report a tool error. + +Paseo delivers attached tools through its agent tool transport, using MCP or native registration +as the provider supports. The same definition and callback work with either. Attached tools obey +the [same gates as Paseo tools](/docs/mcp#limit-paseo-tools-by-provider). Only that agent sees them. + +Names must match `/^[a-z][a-z0-9_]*$/` and be at most 64 characters. A name colliding with a Paseo +tool or another plugin's tool on the same agent fails the session open and names both owners. +A duplicate name within one plugin also fails the session open. Agents the callback does not +target are unaffected. + +| Change | When the agent receives it | +| ------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Start, stop, or reload a plugin declaring `agent.open.before` | Open sessions become stale. Each reopens before its next idle prompt; a running turn continues without interruption. The next prompt after that reopen reuses the session. | +| Change which agents the callback targets | Run `paseo plugin reload agent-tools` after editing this example, then send the agent a prompt when it is idle. | +| Apply immediately | Call `await paseo.agents.ref(id).reload({ requestId: "reload-notes" })`. `requestId` is optional. This reopens the provider session, reruns hooks with `reason: "refresh"`, and interrupts a running turn. | +| Read the current snapshot | Call `await paseo.agents.ref(id).refresh()`. This reads state without reopening the session. | + +If an automatic reopen fails, the triggering prompt fails with that error. See the +[complete agent-tools example](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-tools). + +## agent.close.after + +A live agent runtime closes. Receives `{ agent }`. + +```ts +server.addHook("agent.close.after", async ({ agent }) => { + console.log(agent); +}); +``` + +## agent.archive.after + +Archive state is saved. Receives `{ agent, archivedAt }`; runtime cleanup can still be pending. + +```ts +server.addHook("agent.archive.after", async ({ agent, archivedAt }) => { + console.log(agent, archivedAt); +}); +``` + +## agent.turn.before + +A live turn starts. Receives `{ agent, turnId }`. History replay does not fire it. + +```ts +server.addHook("agent.turn.before", async ({ agent, turnId }) => { + console.log(agent, turnId); +}); +``` + +## agent.turn.after + +A live turn completes, fails, or is canceled. Receives `{ agent, turnId, outcome, timeline }`. `outcome.kind` is `completed`, `failed`, or `canceled`. `timeline` is deprecated and always empty; fetch history through the SDK as below. + +### Send a follow-up when a turn ends + +Copy [server/inspect.ts](https://github.com/getpaseo/paseo/blob/main/plugin-examples/lifecycle-actions/server/inspect.ts) +into your plugin. The helper imports types from `@getpaseo/protocol/agent-types`; add +`@getpaseo/protocol` at the version matching your daemon to your development dependencies +and install them before loading the plugin. `latestOutputText` joins text chunks after the latest user message. + +```ts +import type { PluginServerContext } from "@getpaseo/plugin/server"; +import { latestOutputText } from "./server/inspect"; + +export default function contribute(server: PluginServerContext) { + server.addHook("agent.turn.after", async (event, context) => { + if (event.outcome.kind === "canceled") { + return; + } + + const agent = context.paseo.agents.ref(event.agent.id); + const page = await agent.timeline.refetch({ direction: "tail", limit: 20 }); + const text = latestOutputText(page.entries.map(({ item }) => item)); + if (/out of credits/i.test(text)) { + await agent.send("Try again."); + } + }); + + return () => {}; +} +``` + +```text +Turn ends: "out of credits" + → plugin sends "Try again." + → a new turn starts +``` + +The handler fetches only the last 20 timeline items. Output before that page is not inspected. +Use `cursor` and `direction` to page further when your plugin needs more history. + +This sends a new message with the existing SDK. Persistent matches keep sending follow-ups; +add limits or delays in your plugin when needed. Attachments and tool effects are not replayed. + +## agent.permission.before + +A permission or question becomes pending. Receives `{ agent, request }`; `request` is an `AgentPermissionRequest`. Send the answer through the SDK. + +### Answer a permission request + +Using `shellCommand` from the same [helper file](https://github.com/getpaseo/paseo/blob/main/plugin-examples/lifecycle-actions/server/inspect.ts): + +```ts +import type { PluginServerContext } from "@getpaseo/plugin/server"; +import { shellCommand } from "./server/inspect"; + +export default function contribute(server: PluginServerContext) { + server.addHook("agent.permission.before", async (event, context) => { + const command = shellCommand(event.request); + if (command === null) { + return; + } + + const agent = context.paseo.agents.ref(event.agent.id); + if (/\brm\s+-rf\b/.test(command)) { + await agent.respondToPermission({ + requestId: event.request.id, + response: { behavior: "deny", message: "Recursive deletion is blocked." }, + }); + return; + } + + if (command.trim() === "git status") { + await agent.respondToPermission({ + requestId: event.request.id, + response: { behavior: "allow" }, + }); + } + }); + + return () => {}; +} +``` + +| Request | Result | +| ------------------------ | ------------------------- | +| `rm -rf build` | Declined | +| `git status` | Approved | +| Other command or request | Left pending for the user | +| Already-resolved request | SDK response fails | + +The regex is an example policy, not a shell parser. Permission requests can also be questions, +plans, and mode changes; requesting permission does not end the turn. + +## agent.permission.after + +A pending request is answered or cleared. Receives `{ agent, requestId, resolution }`; `resolution` is an `AgentPermissionResponse`. + +```ts +server.addHook("agent.permission.after", async ({ agent, requestId, resolution }) => { + console.log(agent, requestId, resolution); +}); +``` + +Agent hooks exclude the daemon's private disposable helpers. Public background workspaces and their ordinary agents use the same hooks. + +## Ordering and returned values + +```text +Creation request + → agent.create.before hooks (plugin-ID order; registration order within each plugin) + → resolve defaults and validate provider configuration + → derive launch configuration with Paseo runtime tools and daemon prompt + → agent.open.before hooks (same ordering; env and plugin-local tools and MCP servers) + → set PASEO_AGENT_ID and PASEO_AGENT_CWD + → open provider session and save agent configuration +``` + +| Callback returns | Next callback receives | +| ------------------------------------------------------- | --------------------------------------------------- | +| `{ ...request, env: { ...request.env, REGION: "eu" } }` | Prior request with `REGION` added/replaced | +| `{ ...request, env: { REGION: "eu" } }` | Prior request with the entire override map replaced | +| `undefined` | Unchanged request | +| Throws or returns invalid data | Operation fails; later callbacks do not run | + +There is no automatic deep merge. `env` accumulates across plugins; `tools` and `mcpServers` +accumulate only across callbacks within the same plugin. Returning a replacement map or array +replaces that scope's prior value. + +## Context and cleanup + +| Contract | Behavior | +| ---------------------------------- | ---------------------------------------------------------------------------------------------------------------- | +| `context.paseo` | Existing SDK connected to this daemon | +| `context.signal` | Aborted on invocation timeout or plugin stop; pass to external requests | +| Input data | Detached snapshot; change state through returned requests or SDK commands | +| Registration result | Idempotent remover, e.g. `const remove = server.addHook(...); remove();` | +| Reload, disable, removal, shutdown | Remaining registrations removed | +| Unknown hook name | Registration fails | +| Hook timeout | 30 seconds; aborts the signal. A waiting hook fails the pending operation; a notification handler logs an error. | +| Event-handler error | Logged against plugin; original operation continues | +| Event delivery | Live, best effort; no replay, persistence, or automatic retry | +| Event concurrency | Different events may overlap; callback completion order is not guaranteed | + +## Complete examples + +| Plugin | Includes | +| ------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------- | +| [lifecycle-logger](https://github.com/getpaseo/paseo/tree/main/plugin-examples/lifecycle-logger) | Agent, workspace, and worktree hooks; JSON logs with environment values redacted | +| [lifecycle-actions](https://github.com/getpaseo/paseo/tree/main/plugin-examples/lifecycle-actions) | Follow-ups, permissions, environment, provider switching, worktree selection | +| [agent-configuration](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-configuration) | MCP injection and Codex sandbox/approval options | +| [agent-tools](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-tools) | Label-targeted tools and file operations in the plugin process | + +Read logger output with `paseo plugin logs lifecycle-logger` or the host's `daemon.log`. + +## Renamed hooks + +The old registration methods are deprecated for removal after 2027-04-30. Existing plugins keep their behavior. Mixed old and new registrations within a plugin run in registration order. `addHook` accepts only the new names. + +| Old registration | New registration | +| -------------------------------------------------- | --------------------------------------------------------- | +| `server.before("workspace.create", handler)` | `server.addHook("workspace.create.before", asyncHandler)` | +| `server.on("workspace.created", handler)` | `server.addHook("workspace.create.after", asyncHandler)` | +| `server.on("workspace.archived", handler)` | `server.addHook("workspace.archive.after", asyncHandler)` | +| `server.before("agent.create", handler)` | `server.addHook("agent.create.before", asyncHandler)` | +| `server.on("agent.created", handler)` | `server.addHook("agent.create.after", asyncHandler)` | +| `server.before("agent.session_open", handler)` | `server.addHook("agent.open.before", asyncHandler)` | +| `server.on("agent.closed", handler)` | `server.addHook("agent.close.after", asyncHandler)` | +| `server.on("agent.archived", handler)` | `server.addHook("agent.archive.after", asyncHandler)` | +| `server.on("agent.turn_started", handler)` | `server.addHook("agent.turn.before", asyncHandler)` | +| `server.on("agent.turn_ended", handler)` | `server.addHook("agent.turn.after", asyncHandler)` | +| `server.on("agent.permission_requested", handler)` | `server.addHook("agent.permission.before", asyncHandler)` | +| `server.on("agent.permission_resolved", handler)` | `server.addHook("agent.permission.after", asyncHandler)` | diff --git a/public-docs/plugins/hooks.zh-CN.md b/public-docs/plugins/hooks.zh-CN.md new file mode 100644 index 0000000000..eecf370a29 --- /dev/null +++ b/public-docs/plugins/hooks.zh-CN.md @@ -0,0 +1,641 @@ +--- +title: 插件钩子 +description: 为 Agent 和工作区操作注册钩子,修改请求或接收通知。 +nav: 钩子 +--- + +# 插件钩子 {#plugin-hooks} + +在 `index.server.ts` 中使用 `server.addHook(name, handler)`。钩子在插件启用时运行,即使没有连接的应用。`addHook` 从 Paseo 0.14 起可用;将 `requirements.paseo` 设置为你开发插件时使用的版本。 + +```ts +import type { PluginServerContext } from "@getpaseo/plugin/server"; + +export default function contribute(server: PluginServerContext) { + const remove = server.addHook("agent.open.before", async ({ request }) => ({ + ...request, + env: { ...request.env, REGION: "eu" }, + })); + return remove; +} +``` + +## 命名与等待 {#naming-and-timing} + +名称遵循 `subject.operation.position`:主体、操作、`before` 或 `after`。名称标识生命周期中的位置;Paseo 是否等待由每个钩子决定,见下表。`workspace` 包括所有工作区,`worktree` 仅包括 git worktree。 + +- 等待型钩子结束后 Paseo 才继续。抛出错误、返回无效数据或超过 30 秒会让操作失败,错误包含 `Plugin failed: …`。修改请求的钩子收到 `{ request }`,可以返回完整的替换请求或 `undefined`。 +- 通知收到事件对象,返回 `Promise`。Paseo 不等待;错误会记录在插件名下,原操作继续。`agent.turn.before` 和 `agent.permission.before` 分别在轮次开始或权限进入待处理状态时发出通知。 + +所有处理函数都必须为异步函数。轮次完成包括成功、失败和取消,请查看 `outcome`。权限完成包括所有处理结果,请查看 `resolution`。 + +创建 Agent 会发生一次,`agent.create.before` 修改已保存的配置。打开 Agent 指启动 Provider 进程,包括首次运行、daemon 重启后恢复、读取历史、导入外部会话和重新加载。`agent.open.before` 为每次启动提供临时的环境变量、工具和 MCP 服务器。创建会打开 Agent;打开已有 Agent 不会创建它;关闭会结束运行中的实例。在应用中打开标签页不属于此操作。 + +`worktree.create.after` 在工作区注册前运行,随后是 `workspace.create.after`,两者都早于第一个 Agent 的 `agent.create.before` / `agent.open.before`。 + +### 从等待型钩子提前返回 {#return-early-from-a-waiting-hook} + +如果操作应立即继续,可以启动独立任务并返回: + +```ts +server.addHook("worktree.create.after", async ({ worktree }) => { + void warmCaches(worktree.path); +}); +``` + +Paseo 只观察返回的 Promise,因此独立任务没有错误报告,也没有取消 `signal`。 + +## 钩子一览 {#hooks} + +| 钩子 | 等待 | 载荷 | 可修改 | +| ------------------------- | ---- | -------------------------------------- | ----------------------------------------- | +| `workspace.create.before` | 是 | `{ request }` | 整个创建请求 | +| `workspace.create.after` | 否 | `{ workspace }` | | +| `workspace.archive.after` | 否 | `{ workspace }` | | +| `worktree.create.before` | 是 | `{ request }` | 创建选项和目标路径 | +| `worktree.create.after` | 是 | `{ worktree }` | worktree 中的文件;抛出错误中止创建 | +| `agent.create.before` | 是 | `{ request: { config, env? } }` | 除 `cwd` 外的已保存配置;`env` | +| `agent.create.after` | 否 | `{ agent }` | | +| `agent.open.before` | 是 | `{ request }` | 仅用于启动的 `env`、`tools`、`mcpServers` | +| `agent.close.after` | 否 | `{ agent }` | | +| `agent.archive.after` | 否 | `{ agent, archivedAt }` | | +| `agent.turn.before` | 否 | `{ agent, turnId }` | | +| `agent.turn.after` | 否 | `{ agent, turnId, outcome, timeline }` | | +| `agent.permission.before` | 否 | `{ agent, request }` | | +| `agent.permission.after` | 否 | `{ agent, requestId, resolution }` | | + +## 共享载荷 {#shared-payloads} + +```ts +interface PluginHookAgent { + id: string; + workspaceId: string | null; + parentAgentId: string | null; + provider: string; + cwd: string; + title: string | null; +} + +interface PluginHookWorkspace { + id: string; + projectId: string; + cwd: string; + name: string | null; + archivedAt: string | null; +} + +type PluginTurnOutcome = + | { kind: "completed" } + | { kind: "failed"; error: { message: string; code?: string } } + | { kind: "canceled"; reason: string }; +``` + +| 字段 | 结构 / 含义 | +| ------------ | ---------------------------------------------------------------------------------------- | +| `turnId` | Provider 报告的 `string` 或 `null`;会话重新打开后可能重复 | +| `timeline` | 已弃用,始终为 `[]`;通过 SDK 获取历史。 | +| `request` | SDK 的 `AgentPermissionRequest`;`kind` 为 `tool`、`plan`、`question`、`mode` 或 `other` | +| `resolution` | SDK 的 `AgentPermissionResponse` | +| `archivedAt` | 时间戳字符串 | + +## workspace.create.before {#workspacecreatebefore} + +收到 `{ request }`,其中包含 `source`、可选的 `title` 和 `firstAgentContext`。可替换整个显式创建请求;抛出错误、无效返回或超时会让创建失败。已有工作区和目录查找、导入不受影响。 + +### 选择工作区隔离方式 {#choose-workspace-isolation} + +```ts +server.addHook("workspace.create.before", async ({ request }) => { + if (request.source.kind !== "directory") { + return request; + } + + return { + ...request, + source: { + kind: "worktree", + cwd: request.source.path, + action: "branch-off", + }, + }; +}); +``` + +**结果**:显式的目录创建请求会变成 worktree 请求。已有的工作区以及目录查找/导入操作不受影响。 + +## workspace.create.after {#workspacecreateafter} + +工作区记录创建且目录可用后触发,收到 `{ workspace }`。 + +```ts +server.addHook("workspace.create.after", async ({ workspace }) => { + console.log(workspace); +}); +``` + +## workspace.archive.after {#workspacearchiveafter} + +归档状态保存后触发,收到 `{ workspace }`;worktree 清理可能尚未完成。 + +```ts +server.addHook("workspace.archive.after", async ({ workspace }) => { + console.log(workspace); +}); +``` + +## worktree.create.before {#worktreecreatebefore} + +为新 worktree 选择路径和创建选项。通过应用、CLI、MCP 或创建 Agent 新建 worktree 时,Paseo 在 `git worktree add` 之前等待此钩子。钩子收到 `{ request }`,返回完整的替换请求,或返回 `undefined` 保持原值。抛出错误、返回无效数据或超过 30 秒会终止创建,错误包含插件和钩子名称。 + +```ts +import { basename, dirname, join } from "node:path"; + +server.addHook("worktree.create.before", async ({ request }) => ({ + ...request, + path: join( + dirname(request.sourceCheckout), + `${basename(request.sourceCheckout)}.${request.branch.replaceAll("/", "-")}`, + ), +})); +``` + +源检出目录为 `/home/me/src/paseo`、分支为 `feature/x` 时,目标为 `/home/me/src/paseo.feature-x`。完整插件见 [worktree-placement 示例](https://github.com/getpaseo/paseo/tree/main/plugin-examples/worktree-placement)。 + +| 请求字段 | 含义 | +| ----------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | +| `kind` | `branch-off`、`checkout-branch`、`checkout-change-request` 或 `checkout-github-pr` | +| `branch` | 请求的本地分支名称 | +| `baseRef` | branch-off 的起始引用;变更请求的比较基准;`checkout-branch` 不含此字段。要从引用创建分支,返回 `kind: "branch-off"`。 | +| `slug` | 规范化的 worktree 名称 | +| `path` | 绝对目标路径,初始值为已处理现有路径后缀的默认位置 | +| `repoRoot` | 只读,主仓库根目录 | +| `sourceCheckout` | 只读,源检出根目录,也支持从另一个 worktree 发起创建 | +| `forge`、`changeRequestNumber`、`headRef` | 变更请求检出标识;旧版 GitHub 检出用 `githubPrNumber` 代替 `forge` 和 `changeRequestNumber` | +| `headRepositoryOwner`、`headRepository` | 可选的源仓库信息;`headRepository` 仅用于变更请求检出 | +| `checkoutRefs` | 可选的获取源:`{ remoteName?: string, remoteRef: string }[]` | +| `pushRemoteUrl`、`trackOriginHead` | 可选的推送目标和跟踪策略 | + +返回 `path` 后,`slug` 仅用于 branch-off 分支命名;CLI 使用路径的最后一级目录名查找 worktree。 + +除 `repoRoot` 和 `sourceCheckout` 外,所有字段都可以修改。返回所选 `kind` 的全部必填字段。Paseo 在钩子之后解析 Git 源计划,因此钩子可以在获取引用之前修改分支和基准,而 Git 之后仍可能选择唯一的最终分支名称。 + +Paseo 解析父目录中的符号链接并验证返回的路径。路径必须为绝对路径且不存在,不能是文件系统根目录、用户主目录、仓库根目录、`.git` 目录内的路径或仓库的祖先目录。目标已存在时创建失败,Paseo 不会为插件选择的路径添加后缀。插件应让 Paseo 创建目录。 + +顺序:`worktree.create.before` → `git worktree add` → `worktree.create.after` → 注册工作区。恢复缺失的 worktree 时使用记录的原路径,不运行这两个创建钩子。 + +## worktree.create.after {#worktreecreateafter} + +新的 git worktree 在磁盘上创建后,Paseo 会等待此钩子,然后才注册工作区、运行 setup、打开终端或启动 Agent。收到 `{ worktree: { path, branch, sourceCheckout } }`,分别是 worktree 绝对路径、分支名、来源 checkout 目录。此时还没有工作区 id。无需返回数据,直接写入 worktree 即可。抛出错误或超过 30 秒会中止创建并删除新 worktree。 + +此钩子覆盖新建分支、检出分支和检出 PR。恢复缺失的已归档 worktree 使用独立路径,不触发此钩子。 + +```ts +import { copyFile } from "node:fs/promises"; + +server.addHook("worktree.create.after", async ({ worktree }) => { + await copyFile(`${worktree.sourceCheckout}/.env`, `${worktree.path}/.env`); +}); +``` + +## agent.create.before {#agentcreatebefore} + +收到 `{ request: { config, env? } }`。配置修改会保存,即使插件以后被停用或移除;`env` 只用于首次启动,不会保存。不能修改 `config.cwd`。抛出错误、无效返回或超时会让创建失败。 + +**`agent.create.before.config`** 使用 `AgentSessionConfig`: + +| 字段 | 约束 | +| --------------------------------------------- | -------------------------------------------------------- | +| `provider`, `model` | 独立的字段;修改 Provider 可能需要同时修改模型/模式/选项 | +| `modeId`, `thinkingOptionId`, `featureValues` | 特定于 Provider 的选择 | +| `title`, `systemPrompt` | Agent 配置 | +| `providerOptions` | 不透明的、特定于 Provider 的选项 | +| `mcpServers`, `toolPolicy` | MCP 配置和精确的工具预批准 | +| `cwd` | 不能修改 | + +### 修改已保存的配置 {#change-saved-configuration} + +在 `contribute(server)` 中添加这个回调,为新的 Codex Agent 设置已保存的选项: + +```ts +server.addHook("agent.create.before", async ({ request }) => { + if (request.config.provider !== "codex") { + return request; + } + + return { + ...request, + config: { + ...request.config, + providerOptions: { + ...request.config.providerOptions, + sandbox_mode: "workspace-write", + approval_policy: "on-request", + }, + }, + }; +}); +``` + +| 输入 | 结果 | +| ------------------------------------------- | ------------------- | +| `providerOptions.sandbox_mode: "read-only"` | `"workspace-write"` | +| `providerOptions.web_search: "disabled"` | 由展开运算保留 | + +所选的 Provider 会校验 `providerOptions`。显式的 Codex 沙盒和批准选项会覆盖它的模式预设。 + +## agent.create.after {#agentcreateafter} + +常规创建完成后触发,收到 `{ agent }`;导入和恢复不会触发。 + +```ts +server.addHook("agent.create.after", async ({ agent }) => { + console.log(agent); +}); +``` + +## agent.open.before {#agentopenbefore} + +收到 `{ request }`,只能修改 `env`、`tools` 和 `mcpServers`,修改只用于此次启动。其他字段只读。抛出错误、无效返回或超时会让打开操作失败。 + +**`agent.open.before` 请求示例:** + +```json +{ + "agentId": "agent-123", + "workspaceId": "workspace-456", + "provider": "codex", + "cwd": "/projects/shop", + "title": "Workspace notes", + "labels": { "notes/enabled": "true" }, + "tools": [], + "mcpServers": {}, + "reason": "resume", + "purpose": "interactive", + "env": { "COMPANY_ENV": "development" } +} +``` + +| 字段 | 取值 | +| ------------- | -------------------------------------------------------------------------------------------------------- | +| `workspaceId` | 字符串或 `null` | +| `title` | 只读字符串或 `null`;创建时使用创建请求的标题,恢复时使用已保存的标题。 | +| `labels` | 只读的字符串映射;创建时使用创建请求的标签,恢复时使用已保存的标签。 | +| `tools` | 可编辑的 `AgentToolDefinition[]`,仅包含此插件的工具。参阅[为 Agent 附加工具](#attach-tools-to-agents)。 | +| `mcpServers` | 可编辑的服务器映射,仅用于启动且仅包含本插件的条目。参阅[注入 MCP 服务器](#inject-mcp-servers)。 | +| `reason` | `create`、`resume`、`refresh`、`import` | +| `purpose` | `interactive`、`history` | +| `env` | 启动覆盖映射;不包括 daemon 继承的环境变量。替换整个映射即可添加、替换或移除覆盖项。 | + +### 在每次打开会话时注入环境变量 {#inject-environment-variables-on-every-session-opening} + +```ts +server.addHook("agent.open.before", async ({ request }) => { + return { + ...request, + env: { + ...request.env, + COMPANY_ENV: "development", + }, + }; +}); +``` + +会话打开时的环境变量覆盖项会在每次打开时重新计算。`agent.create.before.env` 只作用于首次启动,不会写入 Agent 的已保存配置。 + +### 注入 MCP 服务器 {#inject-mcp-servers} + +需要将服务器保存为 Agent 配置的一部分时,使用 `agent.create.before.config.mcpServers`。 +插件拥有的服务器使用下面的回调,在 `contribute(server)` 中添加,并把占位 URL 替换为你的 MCP 端点: + +```ts +server.addHook("agent.open.before", async ({ request }) => { + if (request.provider !== "codex") return; + + return { + ...request, + mcpServers: { + ...request.mcpServers, + company: { type: "http", url: "https://tools.example.com/mcp" }, + }, + }; +}); +``` + +`request.mcpServers` 使用与 `AgentSessionConfig.mcpServers` 相同的服务器配置。 +每个插件的映射从空开始,只在该插件自己的回调之间累积,不包含 Agent 已保存的服务器或其他插件的服务器。 +替换映射即可添加、替换或移除本插件的条目;返回 `undefined` 会保持不变。 +Paseo 按插件 ID 顺序合并各插件的最终映射。 + +名称与已保存的服务器、Paseo 内部的 `paseo` 服务器或其他插件的服务器冲突时,会话打开失败,错误会指出服务器名称及双方来源。 +不支持 MCP 的 Provider 会报 `does not support MCP servers` 错误,并指出插件名称。 +`purpose: "history"` 的会话打开会忽略这些服务器。安装、停用和重新加载插件后,现有 Agent +通过[会话重新打开行为](#attach-tools-to-agents)获取变化。 + +### 为 Agent 附加工具 {#attach-tools-to-agents} + +在 `index.server.ts` 中定义工具,并在 `server.addHook("agent.open.before", async handler)` 中附加它。 +此示例只向带有 `notes/enabled: "true"` 标签的 Agent 提供 `append_workspace_note`: + +```ts +import { writeFile } from "node:fs/promises"; +import path from "node:path"; +import { z } from "zod"; +import { defineAgentTool, type PluginServerContext } from "@getpaseo/plugin/server"; + +const appendWorkspaceNote = defineAgentTool({ + name: "append_workspace_note", + description: "Append a note to AGENT_NOTES.md in this agent's working directory.", + input: z.object({ note: z.string().min(1).describe("Note to append") }), + async execute({ note }, { agent, signal }) { + const notePath = path.join(agent.cwd, "AGENT_NOTES.md"); + await writeFile(notePath, `${note}\n`, { encoding: "utf8", flag: "a", signal }); + return { + text: `Saved note to ${notePath}`, + structuredContent: { path: notePath }, + }; + }, +}); + +export default function contribute(server: PluginServerContext) { + server.addHook("agent.open.before", async ({ request }) => { + if (request.labels["notes/enabled"] !== "true") return; + return { ...request, tools: [...request.tools, appendWorkspaceNote] }; + }); + return () => {}; +} +``` + +通过 SDK 创建 Agent 时设置标签: + +```ts +const agent = await paseo.agents.create({ + config: { provider: "codex/gpt-5.4" }, + cwd: "/projects/shop", + labels: { "notes/enabled": "true" }, +}); +``` + +使用会话打开请求中的字段选择 Agent: + +| 选择依据 | 回调中的条件 | +| ---------- | -------------------------------------------- | +| 标签 | `request.labels["notes/enabled"] === "true"` | +| Provider | `request.provider === "codex"` | +| 工作区 | `request.workspaceId === "workspace-456"` | +| 单个 Agent | `request.agentId === chosenAgentId` | + +每个插件的 `request.tools` 都从空数组开始。同一插件中的后续回调会看到前面回调返回的工具; +替换数组即可添加或移除工具。返回 `undefined` 会保留请求。`purpose: "history"` 时会忽略工具。 + +从 `@getpaseo/plugin/server` 导入 `defineAgentTool`、`AgentToolDefinition`、`AgentToolContext` +和 `AgentToolResult`。辅助函数会根据 Zod schema 推断验证后的输入类型: + +```ts +declare function defineAgentTool(tool: { + name: string; + title?: string; + description: string; + input: Input; + execute( + input: z.output, + context: AgentToolContext, + ): AgentToolResult | Promise; +}): AgentToolDefinition; + +interface AgentToolResult { + text?: string; + structuredContent?: unknown; + isError?: boolean; +} +``` + +| 执行 context | 值 | +| ------------ | --------------------------------------------------------------------------------------------------- | +| `agent` | 发起调用的 Agent,以 `PluginHookAgent` 表示,包括 `id`、`workspaceId`、`provider`、`cwd` 和 `title` | +| `paseo` | 已连接到此 daemon 的 SDK | +| `signal` | 此次工具调用的中止信号;请把它传给文件操作或外部请求 | + +`execute` 在插件进程中运行。闭包和原始 Zod schema 保留在该进程中;只有工具元数据和调用的 +输入、结果会跨进程传递。Paseo 在调用 `execute` 前验证输入。无效输入会将 schema 问题返回给 +Agent。抛出的错误会转换为 `{ isError: true, text: message }`,插件继续运行。取消调用或关闭 +其传输连接会中止 `signal` 并丢弃结果。工具调用最长运行 10 分钟,与钩子的 30 秒超时分开。 +关闭或重新打开 Agent 会话会移除旧定义。 + +在 `text` 中返回模型可见的文本。`structuredContent` 必须可序列化为 JSON;省略 `text` 时, +Paseo 会将该值格式化为供模型读取的文本。设置 `isError: true` 可报告工具错误。 + +Paseo 通过 Agent 工具传输提供附加的工具,按 Provider 的支持情况使用 MCP 或原生注册。 +同一份定义和回调适用于这两种方式。附加的工具遵循[与 Paseo 工具相同的限制](/docs/mcp#limit-paseo-tools-by-provider)。 +只有该 Agent 能看到这些工具。 + +名称必须匹配 `/^[a-z][a-z0-9_]*$/`,且不超过 64 个字符。如果名称与同一 Agent 的 Paseo +工具或另一插件的工具冲突,会话打开会失败,并指出双方。一个插件内的重复名称也会导致 +会话打开失败。回调未选中的 Agent 不受影响。 + +| 变更 | Agent 何时收到变更 | +| ----------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| 启动、停止或重新加载声明了 `agent.open.before` 的插件 | 已打开的会话会标记为过期。每个会话在下一次空闲提示词前重新打开;正在运行的轮次会继续,不会被中断。重新打开后的下一条提示词复用该会话。 | +| 修改回调选择的 Agent | 编辑此示例后运行 `paseo plugin reload agent-tools`,然后在 Agent 空闲时发送提示词。 | +| 立即应用 | 调用 `await paseo.agents.ref(id).reload({ requestId: "reload-notes" })`。`requestId` 可选。这会重新打开 Provider 会话,以 `reason: "refresh"` 再次运行钩子,并中断正在运行的轮次。 | +| 读取当前快照 | 调用 `await paseo.agents.ref(id).refresh()`。这只读取状态,不会重新打开会话。 | + +如果自动重新打开失败,触发它的提示词会返回该错误。参阅 +[完整 agent-tools 示例](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-tools)。 + +## agent.close.after {#agentcloseafter} + +运行中的 Agent 实例关闭后触发,收到 `{ agent }`。 + +```ts +server.addHook("agent.close.after", async ({ agent }) => { + console.log(agent); +}); +``` + +## agent.archive.after {#agentarchiveafter} + +归档状态保存后触发,收到 `{ agent, archivedAt }`;运行时清理可能尚未完成。 + +```ts +server.addHook("agent.archive.after", async ({ agent, archivedAt }) => { + console.log(agent, archivedAt); +}); +``` + +## agent.turn.before {#agentturnbefore} + +实时轮次开始后触发,收到 `{ agent, turnId }`。历史重放不会触发。 + +```ts +server.addHook("agent.turn.before", async ({ agent, turnId }) => { + console.log(agent, turnId); +}); +``` + +## agent.turn.after {#agentturnafter} + +实时轮次完成、失败或取消后触发,收到 `{ agent, turnId, outcome, timeline }`。`outcome.kind` 为 `completed`、`failed` 或 `canceled`。`timeline` 已弃用且始终为空;请按下面的示例通过 SDK 获取历史。 + +### 在轮次结束时发送后续消息 {#send-a-follow-up-when-a-turn-ends} + +把 [server/inspect.ts](https://github.com/getpaseo/paseo/blob/main/plugin-examples/lifecycle-actions/server/inspect.ts) 复制到你的插件中。该辅助文件从 `@getpaseo/protocol/agent-types` 导入类型;请把与 daemon 版本相同的 `@getpaseo/protocol` 加入开发依赖,并在加载插件之前安装它们。`latestOutputText` 会拼接最近一条用户消息之后的文本片段。 + +```ts +import type { PluginServerContext } from "@getpaseo/plugin/server"; +import { latestOutputText } from "./server/inspect"; + +export default function contribute(server: PluginServerContext) { + server.addHook("agent.turn.after", async (event, context) => { + if (event.outcome.kind === "canceled") { + return; + } + + const agent = context.paseo.agents.ref(event.agent.id); + const page = await agent.timeline.refetch({ direction: "tail", limit: 20 }); + const text = latestOutputText(page.entries.map(({ item }) => item)); + if (/out of credits/i.test(text)) { + await agent.send("Try again."); + } + }); + + return () => {}; +} +``` + +```text +Turn ends: "out of credits" + → plugin sends "Try again." + → a new turn starts +``` + +该处理函数只获取最近 20 条时间线条目,不检查这一页之前的输出。插件需要更多历史时,请用 `cursor` 和 `direction` 继续翻页。 + +这会用现有的 SDK 发送一条新消息。持续匹配会不断发送后续消息;需要时请在插件中添加次数限制或延迟。附件和工具的效果不会被重放。 + +## agent.permission.before {#agentpermissionbefore} + +权限或问题进入待处理状态后触发,收到 `{ agent, request }`;`request` 为 `AgentPermissionRequest`。通过 SDK 回应。 + +### 回应权限请求 {#answer-a-permission-request} + +使用同一个[辅助文件](https://github.com/getpaseo/paseo/blob/main/plugin-examples/lifecycle-actions/server/inspect.ts)中的 `shellCommand`: + +```ts +import type { PluginServerContext } from "@getpaseo/plugin/server"; +import { shellCommand } from "./server/inspect"; + +export default function contribute(server: PluginServerContext) { + server.addHook("agent.permission.before", async (event, context) => { + const command = shellCommand(event.request); + if (command === null) { + return; + } + + const agent = context.paseo.agents.ref(event.agent.id); + if (/\brm\s+-rf\b/.test(command)) { + await agent.respondToPermission({ + requestId: event.request.id, + response: { behavior: "deny", message: "Recursive deletion is blocked." }, + }); + return; + } + + if (command.trim() === "git status") { + await agent.respondToPermission({ + requestId: event.request.id, + response: { behavior: "allow" }, + }); + } + }); + + return () => {}; +} +``` + +| 请求 | 结果 | +| ---------------- | -------------------- | +| `rm -rf build` | 拒绝 | +| `git status` | 批准 | +| 其他命令或请求 | 保持待处理,留给用户 | +| 已经处理过的请求 | SDK 响应失败 | + +这个正则表达式只是一个示例策略,而不是 shell 解析器。权限请求也可能是问题、计划和模式变更;请求权限不会结束当前轮次。 + +## agent.permission.after {#agentpermissionafter} + +待处理请求得到回应或清除后触发,收到 `{ agent, requestId, resolution }`;`resolution` 为 `AgentPermissionResponse`。 + +```ts +server.addHook("agent.permission.after", async ({ agent, requestId, resolution }) => { + console.log(agent, requestId, resolution); +}); +``` + +Agent 钩子不包括 daemon 的私有临时辅助 Agent。公开的后台工作区及其普通 Agent 使用相同钩子。 + +## 顺序与返回值 {#ordering-and-returned-values} + +```text +Creation request + → agent.create.before hooks (plugin-ID order; registration order within each plugin) + → resolve defaults and validate provider configuration + → derive launch configuration with Paseo runtime tools and daemon prompt + → agent.open.before hooks (same ordering; env and plugin-local tools and MCP servers) + → set PASEO_AGENT_ID and PASEO_AGENT_CWD + → open provider session and save agent configuration +``` + +| 回调返回 | 下一个回调收到 | +| ------------------------------------------------------- | --------------------------------- | +| `{ ...request, env: { ...request.env, REGION: "eu" } }` | 之前的请求,添加或替换了 `REGION` | +| `{ ...request, env: { REGION: "eu" } }` | 之前的请求,整个覆盖映射被替换 | +| `undefined` | 未改变的请求 | +| 抛出错误或返回无效数据 | 操作失败;后面的回调不会运行 | + +没有自动的深度合并。`env` 在插件之间累积;`tools` 和 `mcpServers` 只在同一插件的回调之间累积。 +返回替换的映射或数组会替换该范围内之前的值。 + +## context 与清理 {#context-and-cleanup} + +| 契约 | 行为 | +| -------------------------- | ---------------------------------------------------------------------------------- | +| `context.paseo` | 已连接到此 daemon 的现有 SDK | +| `context.signal` | 在调用超时或插件停止时中止;请把它传给外部请求 | +| 输入数据 | 分离的快照;通过返回的请求或 SDK 命令改变状态 | +| 注册结果 | 幂等的移除函数,例如 `const remove = server.addHook(...); remove();` | +| 重新加载、停用、移除、关闭 | 移除剩余的注册 | +| 未知的钩子名称 | 注册失败 | +| 钩子超时 | 30 秒;会中止 signal。等待型钩子会让待处理的操作失败;事件处理函数会记录一条错误。 | +| 事件处理函数出错 | 记录在插件名下;原操作继续进行 | +| 事件投递 | 实时、尽力而为;没有重放、持久化或自动重试 | +| 事件并发 | 不同的事件可能重叠;不保证回调完成的顺序 | + +## 完整示例 {#complete-examples} + +| 插件 | 包含 | +| ------------------------------------------------------------------------------------------------------ | --------------------------------------------------------- | +| [lifecycle-logger](https://github.com/getpaseo/paseo/tree/main/plugin-examples/lifecycle-logger) | Agent、工作区和 worktree 钩子;隐去环境变量值的 JSON 日志 | +| [lifecycle-actions](https://github.com/getpaseo/paseo/tree/main/plugin-examples/lifecycle-actions) | 后续消息、权限、环境变量、切换 Provider、选择 worktree | +| [agent-configuration](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-configuration) | MCP 注入以及 Codex 沙盒/批准选项 | +| [agent-tools](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-tools) | 按标签选择 Agent,并在插件进程中执行文件操作的工具 | + +用 `paseo plugin logs lifecycle-logger` 或主机的 `daemon.log` 读取 logger 的输出。 + +## 已重命名的钩子 {#renamed-hooks} + +旧注册方法已弃用,会在 2027-04-30 之后移除。现有插件继续按原来的方式运行。同一插件中混合使用新旧注册方法时,处理函数按注册顺序运行。`addHook` 只接受新名称。 + +| 旧注册方式 | 新注册方式 | +| -------------------------------------------------- | --------------------------------------------------------- | +| `server.before("workspace.create", handler)` | `server.addHook("workspace.create.before", asyncHandler)` | +| `server.on("workspace.created", handler)` | `server.addHook("workspace.create.after", asyncHandler)` | +| `server.on("workspace.archived", handler)` | `server.addHook("workspace.archive.after", asyncHandler)` | +| `server.before("agent.create", handler)` | `server.addHook("agent.create.before", asyncHandler)` | +| `server.on("agent.created", handler)` | `server.addHook("agent.create.after", asyncHandler)` | +| `server.before("agent.session_open", handler)` | `server.addHook("agent.open.before", asyncHandler)` | +| `server.on("agent.closed", handler)` | `server.addHook("agent.close.after", asyncHandler)` | +| `server.on("agent.archived", handler)` | `server.addHook("agent.archive.after", asyncHandler)` | +| `server.on("agent.turn_started", handler)` | `server.addHook("agent.turn.before", asyncHandler)` | +| `server.on("agent.turn_ended", handler)` | `server.addHook("agent.turn.after", asyncHandler)` | +| `server.on("agent.permission_requested", handler)` | `server.addHook("agent.permission.before", asyncHandler)` | +| `server.on("agent.permission_resolved", handler)` | `server.addHook("agent.permission.after", asyncHandler)` | diff --git a/public-docs/plugins/providers.md b/public-docs/plugins/providers.md index 6fbe766c61..9a87dfb155 100644 --- a/public-docs/plugins/providers.md +++ b/public-docs/plugins/providers.md @@ -287,6 +287,11 @@ Paseo refreshes an agent by closing its current provider session and opening it configuration and persistence. Re-read credentials, environment, global configuration, and MCP servers during `session.open`. There is no separate reload operation. +Conversation and combined rewind require a core-restored session with persistence. After a +successful rewind, Paseo closes the session and reopens its latest persistence value with +`history: "replay"`. Publish the retained native branch before `session.ready`, including its +children. File-only rewind keeps the current session and conversation history. + Use `restoration: "core"` when Paseo can reopen a session from persistence. A provider-owned child uses `restoration: "parent"`; emit it as another `session.opened` event with `parentSessionId` and recreate it while restoring the parent. diff --git a/public-docs/plugins/reference.md b/public-docs/plugins/reference.md index 69608a83a7..a5565b71c7 100644 --- a/public-docs/plugins/reference.md +++ b/public-docs/plugins/reference.md @@ -2,7 +2,7 @@ title: Plugin reference description: Local plugin files, client and server runtimes, platform limits, contributions, RPCs, lifecycle, hosts, and CLI commands. nav: Reference -order: 48 +order: 49 category: Plugins --- @@ -628,461 +628,11 @@ export default function contribute(client: PluginClientContext) { } ``` -Cleanup can be async. Release timers, watchers, sockets, and other resources created by the plugin. Paseo also removes registrations, unmounts surfaces, rejects pending RPCs, closes the plugin's daemon session, and stops its subprocess on reload, disable, removal, disconnect, or daemon shutdown. +Cleanup can be async. Release timers, watchers, sockets, and other resources created by the plugin. Reload, disable, and removal dispose the affected installation. Stopping a server plugin also closes its daemon session and stops its subprocess. Client installations follow [Hosts and lifecycle](#hosts-and-lifecycle), including retention during a temporary disconnect. ## Lifecycle hooks -In `index.server.ts`: - -```ts -import type { PluginServerContext } from "@getpaseo/plugin/server"; - -export default function contribute(server: PluginServerContext) { - server.on("agent.turn_ended", (event) => { - console.log(event.agent.id, event.outcome); - }); - - return () => {}; -} -``` - -| Register | Callback receives | Return | -| ------------------------------- | ---------------------------------- | ------------------------------------------------------------ | -| `server.on(name, callback)` | `(event, { paseo, signal })` | `void` or `Promise` | -| `server.before(name, callback)` | `({ request }, { paseo, signal })` | Modified request, or `undefined` to keep it; async supported | - -Hooks run on the daemon while the plugin is enabled, even with no app connected. - -### Change configuration and inject an MCP server - -Add this callback inside `contribute(server)`. Replace the placeholder URL with your MCP endpoint. - -```ts -server.before("agent.create", ({ request }) => { - if (request.config.provider !== "codex") { - return request; - } - - return { - ...request, - config: { - ...request.config, - providerOptions: { - ...request.config.providerOptions, - sandbox_mode: "workspace-write", - approval_policy: "on-request", - }, - mcpServers: { - ...request.config.mcpServers, - company: { - type: "http", - url: "https://tools.example.com/mcp", - }, - }, - }, - }; -}); -``` - -| Input | Result | -| ------------------------------------------- | ----------------------------- | -| `providerOptions.sandbox_mode: "read-only"` | `"workspace-write"` | -| `providerOptions.web_search: "disabled"` | Preserved by the spread | -| Existing `mcpServers.search` | Preserved by the spread | -| Existing `mcpServers.company` | Replaced with the entry above | - -The selected provider validates `providerOptions` and must support the configured MCP servers. -Explicit Codex sandbox and approval options override its mode presets. - -### Inject environment variables on every session opening - -```ts -server.before("agent.session_open", ({ request }) => { - return { - ...request, - env: { - ...request.env, - COMPANY_ENV: "development", - }, - }; -}); -``` - -This runs on create, resume, refresh, and import. To inject only on creation, set `env` in an -`agent.create` callback instead. - -### Attach tools to agents - -Define a tool in `index.server.ts` and attach it in `before("agent.session_open")`. -This example gives `append_workspace_note` only to agents with the label `notes/enabled: "true"`: - -```ts -import { writeFile } from "node:fs/promises"; -import path from "node:path"; -import { z } from "zod"; -import { defineAgentTool, type PluginServerContext } from "@getpaseo/plugin/server"; - -const appendWorkspaceNote = defineAgentTool({ - name: "append_workspace_note", - description: "Append a note to AGENT_NOTES.md in this agent's working directory.", - input: z.object({ note: z.string().min(1).describe("Note to append") }), - async execute({ note }, { agent, signal }) { - const notePath = path.join(agent.cwd, "AGENT_NOTES.md"); - await writeFile(notePath, `${note}\n`, { encoding: "utf8", flag: "a", signal }); - return { - text: `Saved note to ${notePath}`, - structuredContent: { path: notePath }, - }; - }, -}); - -export default function contribute(server: PluginServerContext) { - server.before("agent.session_open", ({ request }) => { - if (request.labels["notes/enabled"] !== "true") return; - return { ...request, tools: [...request.tools, appendWorkspaceNote] }; - }); - return () => {}; -} -``` - -Set the label when creating an agent with the SDK: - -```ts -const agent = await paseo.agents.create({ - config: { provider: "codex/gpt-5.4" }, - cwd: "/projects/shop", - labels: { "notes/enabled": "true" }, -}); -``` - -Select agents using any of the session-open request fields: - -| Select by | Condition in the callback | -| ---------------- | -------------------------------------------- | -| Label | `request.labels["notes/enabled"] === "true"` | -| Provider | `request.provider === "codex"` | -| Workspace | `request.workspaceId === "workspace-456"` | -| Individual agent | `request.agentId === chosenAgentId` | - -`request.tools` starts empty for each plugin. Each callback sees the tools returned by earlier -callbacks in that plugin; replace the array to add or remove tools. Returning `undefined` preserves -the request. Tools are ignored for `purpose: "history"`. - -Import `defineAgentTool`, `AgentToolDefinition`, `AgentToolContext`, and `AgentToolResult` from -`@getpaseo/plugin/server`. The helper infers the validated input from your Zod schema: - -```ts -declare function defineAgentTool(tool: { - name: string; - title?: string; - description: string; - input: Input; - execute( - input: z.output, - context: AgentToolContext, - ): AgentToolResult | Promise; -}): AgentToolDefinition; - -interface AgentToolResult { - text?: string; - structuredContent?: unknown; - isError?: boolean; -} -``` - -| Execution context | Value | -| ----------------- | --------------------------------------------------------------------------------------------------- | -| `agent` | Calling agent as a `PluginHookAgent`, including `id`, `workspaceId`, `provider`, `cwd`, and `title` | -| `paseo` | SDK connected to this daemon | -| `signal` | Abort signal for this tool call; pass it to file operations or external requests | - -`execute` runs in the plugin process. Closures and the original Zod schema stay there; only tool -metadata and call inputs/results cross the process boundary. Paseo validates input before calling -`execute`. Invalid input returns schema issues to the agent. A thrown error becomes -`{ isError: true, text: message }` and the plugin keeps running. Canceling the call or closing its -transport aborts `signal` and discards the result. Tool calls have a 10 minute ceiling, separate -from the 30 second hook timeout. Closing or reopening an agent session drops its old definitions. - -Return model-visible text in `text`. `structuredContent` must be JSON-serializable; when `text` is -omitted, Paseo formats that value as text for the model. Set `isError: true` to report a tool error. - -Paseo delivers attached tools through its agent tool transport, using MCP or native registration -as the provider supports. The same definition and callback work with either. Attached tools obey -the [same gates as Paseo tools](/docs/mcp#limit-paseo-tools-by-provider). Only that agent sees them. - -Names must match `/^[a-z][a-z0-9_]*$/` and be at most 64 characters. A name colliding with a Paseo -tool or another plugin's tool on the same agent fails the session open and names both owners. -A duplicate name within one plugin also fails the session open. Agents the callback does not -target are unaffected. - -| Change | When the agent receives it | -| -------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Start, stop, or reload a plugin declaring `agent.session_open` | Open sessions become stale. Each reopens before its next idle prompt; a running turn continues without interruption. The next prompt after that reopen reuses the session. | -| Change which agents the callback targets | Run `paseo plugin reload agent-tools` after editing this example, then send the agent a prompt when it is idle. | -| Apply immediately | Call `await paseo.agents.ref(id).reload({ requestId: "reload-notes" })`. `requestId` is optional. This reopens the provider session, reruns hooks with `reason: "refresh"`, and interrupts a running turn. | -| Read the current snapshot | Call `await paseo.agents.ref(id).refresh()`. This reads state without reopening the session. | - -If an automatic reopen fails, the triggering prompt fails with that error. See the -[complete agent-tools example](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-tools). - -### Choose workspace isolation - -```ts -server.before("workspace.create", ({ request }) => { - if (request.source.kind !== "directory") { - return request; - } - - return { - ...request, - source: { - kind: "worktree", - cwd: request.source.path, - action: "branch-off", - }, - }; -}); -``` - -**Result:** an explicit directory creation request becomes a worktree request. Existing workspaces -and directory lookup/import operations are unaffected. - -### Send a follow-up when a turn ends - -Copy [server/inspect.ts](https://github.com/getpaseo/paseo/blob/main/plugin-examples/lifecycle-actions/server/inspect.ts) -into your plugin. The helper imports types from `@getpaseo/protocol/agent-types`; add -`@getpaseo/protocol` at the same version as your plugin SDK to your development dependencies -and install them before loading the plugin. `latestOutputText` joins text chunks after the latest user message. - -```ts -import type { PluginServerContext } from "@getpaseo/plugin/server"; -import { latestOutputText } from "./server/inspect"; - -export default function contribute(server: PluginServerContext) { - server.on("agent.turn_ended", async (event, context) => { - if (event.outcome.kind === "canceled") { - return; - } - - const agent = context.paseo.agents.ref(event.agent.id); - const page = await agent.timeline.refetch({ direction: "tail", limit: 20 }); - const text = latestOutputText(page.entries.map(({ item }) => item)); - if (/out of credits/i.test(text)) { - await agent.send("Try again."); - } - }); - - return () => {}; -} -``` - -```text -Turn ends: "out of credits" - → plugin sends "Try again." - → a new turn starts -``` - -The handler fetches only the last 20 timeline items. Output before that page is not inspected. -Use `cursor` and `direction` to page further when your plugin needs more history. - -This sends a new message with the existing SDK. Persistent matches keep sending follow-ups; -add limits or delays in your plugin when needed. Attachments and tool effects are not replayed. - -### Answer a permission request - -Using `shellCommand` from the same [helper file](https://github.com/getpaseo/paseo/blob/main/plugin-examples/lifecycle-actions/server/inspect.ts): - -```ts -import type { PluginServerContext } from "@getpaseo/plugin/server"; -import { shellCommand } from "./server/inspect"; - -export default function contribute(server: PluginServerContext) { - server.on("agent.permission_requested", async (event, context) => { - const command = shellCommand(event.request); - if (command === null) { - return; - } - - const agent = context.paseo.agents.ref(event.agent.id); - if (/\brm\s+-rf\b/.test(command)) { - await agent.respondToPermission({ - requestId: event.request.id, - response: { behavior: "deny", message: "Recursive deletion is blocked." }, - }); - return; - } - - if (command.trim() === "git status") { - await agent.respondToPermission({ - requestId: event.request.id, - response: { behavior: "allow" }, - }); - } - }); - - return () => {}; -} -``` - -| Request | Result | -| ------------------------ | ------------------------- | -| `rm -rf build` | Declined | -| `git status` | Approved | -| Other command or request | Left pending for the user | -| Already-resolved request | SDK response fails | - -The regex is an example policy, not a shell parser. Permission requests can also be questions, -plans, and mode changes; requesting permission does not end the turn. - -### Events - -| Name | Event fields | Trigger | -| ---------------------------- | ------------------------------------------------------- | -------------------------------------------------- | -| `agent.created` | `agent` | Ordinary creation finishes; excludes import/resume | -| `agent.closed` | `agent` | A live agent runtime closes | -| `agent.turn_started` | `agent`, `turnId` | Live turn starts | -| `agent.turn_ended` | `agent`, `turnId`, `outcome`, deprecated `timeline: []` | Live turn completes, fails, or is canceled | -| `agent.permission_requested` | `agent`, `request` | Permission or question becomes pending | -| `agent.permission_resolved` | `agent`, `requestId`, `resolution` | Pending request is answered or cleared | -| `agent.archived` | `agent`, `archivedAt` | Archive state is saved | -| `workspace.created` | `workspace` | Record created; directory available | -| `workspace.archived` | `workspace` | Archive state is saved | - -Agent events exclude the daemon's private disposable helpers. Public background workspaces and -their ordinary agents run the same lifecycle hooks as other workspaces. Archive events can precede -runtime/worktree cleanup; observe lifecycle completion separately when cleanup matters. - -`agent.turn_ended.timeline` is deprecated and always empty. Fetch history on demand with -`context.paseo.agents.ref(event.agent.id).timeline.refetch({ direction: "tail", limit: 20 })`. -The hook payload size does not grow with conversation history. - -**Shared payload shapes** (`@getpaseo/plugin/server`): - -```ts -interface PluginHookAgent { - id: string; - workspaceId: string | null; - parentAgentId: string | null; - provider: string; - cwd: string; - title: string | null; -} - -interface PluginHookWorkspace { - id: string; - projectId: string; - cwd: string; - name: string | null; - archivedAt: string | null; -} - -type PluginTurnOutcome = - | { kind: "completed" } - | { kind: "failed"; error: { message: string; code?: string } } - | { kind: "canceled"; reason: string }; -``` - -| Field | Shape / meaning | -| ------------ | ----------------------------------------------------------------------------------------------------- | -| `turnId` | Provider-reported `string` or `null`; can repeat after a session reopens | -| `timeline` | `readonly AgentTimelineItem[]`; complete snapshot including earlier conversation; text may span items | -| `request` | SDK `AgentPermissionRequest`; `kind` is `tool`, `plan`, `question`, `mode`, or `other` | -| `resolution` | SDK `AgentPermissionResponse` | -| `archivedAt` | Timestamp string | - -### Before hooks - -| Name | Request fields | Editable | -| -------------------- | ---------------------------------------------------------------------------------------------------------------- | --------------------------------------- | -| `agent.create` | `config`, optional `env` | Public agent config except `cwd`; `env` | -| `agent.session_open` | `agentId`, `workspaceId`, `provider`, `cwd`, read-only `title` and `labels`, `reason`, `purpose`, `env`, `tools` | `env` and `tools` | -| `workspace.create` | `source`, optional `title`, `firstAgentContext` | Entire explicit creation request | - -**`agent.create.config`** uses `AgentSessionConfig`: - -| Fields | Constraint | -| --------------------------------------------- | -------------------------------------------------------------------------- | -| `provider`, `model` | Separate fields; changing provider may require changing model/mode/options | -| `modeId`, `thinkingOptionId`, `featureValues` | Provider-specific selections | -| `title`, `systemPrompt` | Agent configuration | -| `providerOptions` | Opaque provider-specific options | -| `mcpServers`, `toolPolicy` | MCP configuration and exact-tool preapprovals | -| `cwd` | Cannot change | - -**`agent.session_open` request example:** - -```json -{ - "agentId": "agent-123", - "workspaceId": "workspace-456", - "provider": "codex", - "cwd": "/projects/shop", - "title": "Workspace notes", - "labels": { "notes/enabled": "true" }, - "tools": [], - "reason": "resume", - "purpose": "interactive", - "env": { "COMPANY_ENV": "development" } -} -``` - -| Field | Values | -| ------------- | ----------------------------------------------------------------------------------------------------------------------- | -| `workspaceId` | String or `null` | -| `title` | Read-only string or `null`; creation title on create, stored title on resume. | -| `labels` | Read-only string map; creation labels on create, stored labels on resume. | -| `tools` | Editable `AgentToolDefinition[]`, local to this plugin. See [Attach tools to agents](#attach-tools-to-agents). | -| `reason` | `create`, `resume`, `refresh`, `import` | -| `purpose` | `interactive`, `history` | -| `env` | Launch override map; excludes the daemon's inherited environment. Replace the map to add, replace, or remove overrides. | - -### Ordering and returned values - -```text -Creation request - → agent.create hooks (plugin-ID order; registration order within each plugin) - → resolve defaults and validate provider configuration - → derive launch configuration with Paseo runtime tools and daemon prompt - → agent.session_open hooks (same ordering; env and plugin-local tools) - → set PASEO_AGENT_ID and PASEO_AGENT_CWD - → open provider session and save agent configuration -``` - -| Callback returns | Next callback receives | -| ------------------------------------------------------- | --------------------------------------------------- | -| `{ ...request, env: { ...request.env, REGION: "eu" } }` | Prior request with `REGION` added/replaced | -| `{ ...request, env: { REGION: "eu" } }` | Prior request with the entire override map replaced | -| `undefined` | Unchanged request | -| Throws or returns invalid data | Operation fails; later callbacks do not run | - -No automatic deep merge. Later callbacks can overwrite earlier values. Agent configuration is -saved; environment overrides are not persisted with it. - -### Context and cleanup - -| Contract | Behavior | -| ---------------------------------- | --------------------------------------------------------------------------------------------------------- | -| `context.paseo` | Existing SDK connected to this daemon | -| `context.signal` | Aborted on invocation timeout or plugin stop; pass to external requests | -| Input data | Detached snapshot; change state through returned requests or SDK commands | -| Registration result | Idempotent remover, e.g. `const remove = server.on(...); remove();` | -| Reload, disable, removal, shutdown | Remaining registrations removed | -| Unknown hook name | Registration fails | -| Hook timeout | 30 seconds; aborts the signal. A before hook fails the pending operation; an event handler logs an error. | -| Event-handler error | Logged against plugin; original operation continues | -| Event delivery | Live, best effort; no replay, persistence, or automatic retry | -| Event concurrency | Different events may overlap; callback completion order is not guaranteed | - -### Complete examples - -| Plugin | Includes | -| ------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------- | -| [lifecycle-logger](https://github.com/getpaseo/paseo/tree/main/plugin-examples/lifecycle-logger) | All eleven hooks; JSON logs with environment values redacted | -| [lifecycle-actions](https://github.com/getpaseo/paseo/tree/main/plugin-examples/lifecycle-actions) | Follow-ups, permissions, environment, provider switching, worktree selection | -| [agent-configuration](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-configuration) | MCP injection and Codex sandbox/approval options | -| [agent-tools](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-tools) | Label-targeted tools and file operations in the plugin process | - -Read logger output with `paseo plugin logs lifecycle-logger` or the host's `daemon.log`. +Register async handlers with `server.addHook(name, handler)`. See [Hooks](/docs/plugins/hooks) for names, payloads, ordering, errors, and complete examples. ## Screens and sidebar items @@ -2467,7 +2017,7 @@ Hiding preserves the registration, so showing it again restores its position. It an action already in progress. `remove()` is idempotent. Updates after removal do nothing. Paseo removes outstanding buttons when -the plugin installation or host connection is torn down. Return cleanup from the client entry for +the plugin installation is disposed (see [Hosts and lifecycle](#hosts-and-lifecycle)). Return cleanup from the client entry for your subscriptions, timers, and other resources. ## Use the Paseo SDK @@ -2795,9 +2345,11 @@ Plugins are installed per daemon. When the same contribution exists on several c Attachment sources remain scoped to each composer's host. -Workspace panels and Command Center items stay scoped to the active host and exact cached context. -Reload replaces their registrations. Disable, removal, host disconnect, and evaluation failure -remove Command Center items and clear the installation's query state. An already-restored panel tab +A dropped connection keeps client plugin registrations, mounted surfaces, local state, and query caches. Reconnecting through the existing `DaemonClient` object keeps unchanged installations and refreshes their settings. Consume SDK observation snapshots to refresh other daemon state; setup does not run again for an unchanged installation. Daemon calls still depend on connectivity. + +Switching connections (for example, from direct to relay) currently replaces the `DaemonClient` object and reinstalls client plugins. Reload, changed bundles or requirements, disable, plugin removal, and host removal also dispose affected installations and clear their query state. A replacement that fails evaluation leaves its contributions unavailable. + +Workspace panels and Command Center items stay scoped to the active host and exact cached context. An already-restored panel tab remains as unavailable until its matching contribution returns or the user closes it. Panel render failures stay inside the plugin error boundary. diff --git a/public-docs/plugins/reference.zh-CN.md b/public-docs/plugins/reference.zh-CN.md index 3c84f8cc0c..5375b98c68 100644 --- a/public-docs/plugins/reference.zh-CN.md +++ b/public-docs/plugins/reference.zh-CN.md @@ -504,444 +504,11 @@ export default function contribute(client: PluginClientContext) { } ``` -清理函数可以是异步的。请释放插件创建的计时器、监听器、套接字和其他资源。在重新加载、停用、移除、断开连接或 daemon 关闭时,Paseo 还会移除注册、卸载界面、reject 待处理的 RPC、关闭插件的 daemon 会话并停止它的子进程。 +清理函数可以是异步的。请释放插件创建的计时器、监听器、套接字和其他资源。重新加载、停用和移除会销毁受影响的插件安装。停止服务端插件还会关闭它的 daemon 会话并停止其子进程。客户端安装遵循[主机与生命周期](#hosts-and-lifecycle)中的规则,包括在暂时断开连接时保留安装。 ## 生命周期钩子 {#lifecycle-hooks} -在 `index.server.ts` 中: - -```ts -import type { PluginServerContext } from "@getpaseo/plugin/server"; - -export default function contribute(server: PluginServerContext) { - server.on("agent.turn_ended", (event) => { - console.log(event.agent.id, event.outcome); - }); - - return () => {}; -} -``` - -| 注册 | 回调接收 | 返回 | -| ------------------------------- | ---------------------------------- | --------------------------------------------------- | -| `server.on(name, callback)` | `(event, { paseo, signal })` | `void` 或 `Promise` | -| `server.before(name, callback)` | `({ request }, { paseo, signal })` | 修改后的请求,或返回 `undefined` 保持不变;支持异步 | - -只要插件处于启用状态,钩子就会在 daemon 上运行,即使没有应用连接。 - -### 修改配置并注入 MCP 服务器 {#change-configuration-and-inject-an-mcp-server} - -在 `contribute(server)` 中添加这个回调。把占位 URL 替换为你的 MCP 端点。 - -```ts -server.before("agent.create", ({ request }) => { - if (request.config.provider !== "codex") { - return request; - } - - return { - ...request, - config: { - ...request.config, - providerOptions: { - ...request.config.providerOptions, - sandbox_mode: "workspace-write", - approval_policy: "on-request", - }, - mcpServers: { - ...request.config.mcpServers, - company: { - type: "http", - url: "https://tools.example.com/mcp", - }, - }, - }, - }; -}); -``` - -| 输入 | 结果 | -| ------------------------------------------- | ------------------- | -| `providerOptions.sandbox_mode: "read-only"` | `"workspace-write"` | -| `providerOptions.web_search: "disabled"` | 由展开运算保留 | -| 已有的 `mcpServers.search` | 由展开运算保留 | -| 已有的 `mcpServers.company` | 被替换为上面的条目 | - -所选的 Provider 会校验 `providerOptions`,并且必须支持配置的 MCP 服务器。显式的 Codex 沙盒和批准选项会覆盖它的模式预设。 - -### 在每次打开会话时注入环境变量 {#inject-environment-variables-on-every-session-opening} - -```ts -server.before("agent.session_open", ({ request }) => { - return { - ...request, - env: { - ...request.env, - COMPANY_ENV: "development", - }, - }; -}); -``` - -它会在创建、恢复、刷新和导入时运行。如果只想在创建时注入,请改为在 `agent.create` 回调中设置 `env`。 - -### 为 Agent 附加工具 {#attach-tools-to-agents} - -在 `index.server.ts` 中定义工具,并在 `before("agent.session_open")` 中附加它。 -此示例只向带有 `notes/enabled: "true"` 标签的 Agent 提供 `append_workspace_note`: - -```ts -import { writeFile } from "node:fs/promises"; -import path from "node:path"; -import { z } from "zod"; -import { defineAgentTool, type PluginServerContext } from "@getpaseo/plugin/server"; - -const appendWorkspaceNote = defineAgentTool({ - name: "append_workspace_note", - description: "Append a note to AGENT_NOTES.md in this agent's working directory.", - input: z.object({ note: z.string().min(1).describe("Note to append") }), - async execute({ note }, { agent, signal }) { - const notePath = path.join(agent.cwd, "AGENT_NOTES.md"); - await writeFile(notePath, `${note}\n`, { encoding: "utf8", flag: "a", signal }); - return { - text: `Saved note to ${notePath}`, - structuredContent: { path: notePath }, - }; - }, -}); - -export default function contribute(server: PluginServerContext) { - server.before("agent.session_open", ({ request }) => { - if (request.labels["notes/enabled"] !== "true") return; - return { ...request, tools: [...request.tools, appendWorkspaceNote] }; - }); - return () => {}; -} -``` - -通过 SDK 创建 Agent 时设置标签: - -```ts -const agent = await paseo.agents.create({ - config: { provider: "codex/gpt-5.4" }, - cwd: "/projects/shop", - labels: { "notes/enabled": "true" }, -}); -``` - -使用会话打开请求中的字段选择 Agent: - -| 选择依据 | 回调中的条件 | -| ---------- | -------------------------------------------- | -| 标签 | `request.labels["notes/enabled"] === "true"` | -| Provider | `request.provider === "codex"` | -| 工作区 | `request.workspaceId === "workspace-456"` | -| 单个 Agent | `request.agentId === chosenAgentId` | - -每个插件的 `request.tools` 都从空数组开始。同一插件中的后续回调会看到前面回调返回的工具; -替换数组即可添加或移除工具。返回 `undefined` 会保留请求。`purpose: "history"` 时会忽略工具。 - -从 `@getpaseo/plugin/server` 导入 `defineAgentTool`、`AgentToolDefinition`、`AgentToolContext` -和 `AgentToolResult`。辅助函数会根据 Zod schema 推断验证后的输入类型: - -```ts -declare function defineAgentTool(tool: { - name: string; - title?: string; - description: string; - input: Input; - execute( - input: z.output, - context: AgentToolContext, - ): AgentToolResult | Promise; -}): AgentToolDefinition; - -interface AgentToolResult { - text?: string; - structuredContent?: unknown; - isError?: boolean; -} -``` - -| 执行 context | 值 | -| ------------ | --------------------------------------------------------------------------------------------------- | -| `agent` | 发起调用的 Agent,以 `PluginHookAgent` 表示,包括 `id`、`workspaceId`、`provider`、`cwd` 和 `title` | -| `paseo` | 已连接到此 daemon 的 SDK | -| `signal` | 此次工具调用的中止信号;请把它传给文件操作或外部请求 | - -`execute` 在插件进程中运行。闭包和原始 Zod schema 保留在该进程中;只有工具元数据和调用的 -输入、结果会跨进程传递。Paseo 在调用 `execute` 前验证输入。无效输入会将 schema 问题返回给 -Agent。抛出的错误会转换为 `{ isError: true, text: message }`,插件继续运行。取消调用或关闭 -其传输连接会中止 `signal` 并丢弃结果。工具调用最长运行 10 分钟,与钩子的 30 秒超时分开。 -关闭或重新打开 Agent 会话会移除旧定义。 - -在 `text` 中返回模型可见的文本。`structuredContent` 必须可序列化为 JSON;省略 `text` 时, -Paseo 会将该值格式化为供模型读取的文本。设置 `isError: true` 可报告工具错误。 - -Paseo 通过 Agent 工具传输提供附加的工具,按 Provider 的支持情况使用 MCP 或原生注册。 -同一份定义和回调适用于这两种方式。附加的工具遵循[与 Paseo 工具相同的限制](/docs/mcp#limit-paseo-tools-by-provider)。 -只有该 Agent 能看到这些工具。 - -名称必须匹配 `/^[a-z][a-z0-9_]*$/`,且不超过 64 个字符。如果名称与同一 Agent 的 Paseo -工具或另一插件的工具冲突,会话打开会失败,并指出双方。一个插件内的重复名称也会导致 -会话打开失败。回调未选中的 Agent 不受影响。 - -| 变更 | Agent 何时收到变更 | -| ------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| 启动、停止或重新加载声明了 `agent.session_open` 的插件 | 已打开的会话会标记为过期。每个会话在下一次空闲提示词前重新打开;正在运行的轮次会继续,不会被中断。重新打开后的下一条提示词复用该会话。 | -| 修改回调选择的 Agent | 编辑此示例后运行 `paseo plugin reload agent-tools`,然后在 Agent 空闲时发送提示词。 | -| 立即应用 | 调用 `await paseo.agents.ref(id).reload({ requestId: "reload-notes" })`。`requestId` 可选。这会重新打开 Provider 会话,以 `reason: "refresh"` 再次运行钩子,并中断正在运行的轮次。 | -| 读取当前快照 | 调用 `await paseo.agents.ref(id).refresh()`。这只读取状态,不会重新打开会话。 | - -如果自动重新打开失败,触发它的提示词会返回该错误。参阅 -[完整 agent-tools 示例](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-tools)。 - -### 选择工作区隔离方式 {#choose-workspace-isolation} - -```ts -server.before("workspace.create", ({ request }) => { - if (request.source.kind !== "directory") { - return request; - } - - return { - ...request, - source: { - kind: "worktree", - cwd: request.source.path, - action: "branch-off", - }, - }; -}); -``` - -**结果**:显式的目录创建请求会变成 worktree 请求。已有的工作区以及目录查找/导入操作不受影响。 - -### 在轮次结束时发送后续消息 {#send-a-follow-up-when-a-turn-ends} - -把 [server/inspect.ts](https://github.com/getpaseo/paseo/blob/main/plugin-examples/lifecycle-actions/server/inspect.ts) 复制到你的插件中。该辅助文件从 `@getpaseo/protocol/agent-types` 导入类型;请把与插件 SDK 版本相同的 `@getpaseo/protocol` 加入开发依赖,并在加载插件之前安装它们。`latestOutputText` 会拼接最近一条用户消息之后的文本片段。 - -```ts -import type { PluginServerContext } from "@getpaseo/plugin/server"; -import { latestOutputText } from "./server/inspect"; - -export default function contribute(server: PluginServerContext) { - server.on("agent.turn_ended", async (event, context) => { - if (event.outcome.kind === "canceled") { - return; - } - - const agent = context.paseo.agents.ref(event.agent.id); - const page = await agent.timeline.refetch({ direction: "tail", limit: 20 }); - const text = latestOutputText(page.entries.map(({ item }) => item)); - if (/out of credits/i.test(text)) { - await agent.send("Try again."); - } - }); - - return () => {}; -} -``` - -```text -Turn ends: "out of credits" - → plugin sends "Try again." - → a new turn starts -``` - -该处理函数只获取最近 20 条时间线条目,不检查这一页之前的输出。插件需要更多历史时,请用 `cursor` 和 `direction` 继续翻页。 - -这会用现有的 SDK 发送一条新消息。持续匹配会不断发送后续消息;需要时请在插件中添加次数限制或延迟。附件和工具的效果不会被重放。 - -### 回应权限请求 {#answer-a-permission-request} - -使用同一个[辅助文件](https://github.com/getpaseo/paseo/blob/main/plugin-examples/lifecycle-actions/server/inspect.ts)中的 `shellCommand`: - -```ts -import type { PluginServerContext } from "@getpaseo/plugin/server"; -import { shellCommand } from "./server/inspect"; - -export default function contribute(server: PluginServerContext) { - server.on("agent.permission_requested", async (event, context) => { - const command = shellCommand(event.request); - if (command === null) { - return; - } - - const agent = context.paseo.agents.ref(event.agent.id); - if (/\brm\s+-rf\b/.test(command)) { - await agent.respondToPermission({ - requestId: event.request.id, - response: { behavior: "deny", message: "Recursive deletion is blocked." }, - }); - return; - } - - if (command.trim() === "git status") { - await agent.respondToPermission({ - requestId: event.request.id, - response: { behavior: "allow" }, - }); - } - }); - - return () => {}; -} -``` - -| 请求 | 结果 | -| ---------------- | -------------------- | -| `rm -rf build` | 拒绝 | -| `git status` | 批准 | -| 其他命令或请求 | 保持待处理,留给用户 | -| 已经处理过的请求 | SDK 响应失败 | - -这个正则表达式只是一个示例策略,而不是 shell 解析器。权限请求也可能是问题、计划和模式变更;请求权限不会结束当前轮次。 - -### 事件 {#events} - -| 名称 | 事件字段 | 触发时机 | -| ---------------------------- | ----------------------------------------------------- | ----------------------------- | -| `agent.created` | `agent` | 普通创建完成;不包括导入/恢复 | -| `agent.closed` | `agent` | 一个运行中的 Agent 运行时关闭 | -| `agent.turn_started` | `agent`, `turnId` | 实时轮次开始 | -| `agent.turn_ended` | `agent`, `turnId`, `outcome`, 已弃用的 `timeline: []` | 实时轮次完成、失败或被取消 | -| `agent.permission_requested` | `agent`, `request` | 权限请求或问题进入待处理状态 | -| `agent.permission_resolved` | `agent`, `requestId`, `resolution` | 待处理的请求得到回应或被清除 | -| `agent.archived` | `agent`, `archivedAt` | 归档状态已保存 | -| `workspace.created` | `workspace` | 记录已创建;目录可用 | -| `workspace.archived` | `workspace` | 归档状态已保存 | - -Agent 事件不包括 daemon 私有的一次性辅助 Agent。公开的后台工作区及其普通 Agent 与其他工作区运行相同的生命周期钩子。归档事件可能早于运行时/worktree 清理;当清理很重要时,请单独观察生命周期何时完成。 - -`agent.turn_ended.timeline` 已弃用,并且始终为空。需要历史时,请用 `context.paseo.agents.ref(event.agent.id).timeline.refetch({ direction: "tail", limit: 20 })` 按需获取。钩子负载的大小不会随对话历史增长。 - -**共享的负载结构**(`@getpaseo/plugin/server`): - -```ts -interface PluginHookAgent { - id: string; - workspaceId: string | null; - parentAgentId: string | null; - provider: string; - cwd: string; - title: string | null; -} - -interface PluginHookWorkspace { - id: string; - projectId: string; - cwd: string; - name: string | null; - archivedAt: string | null; -} - -type PluginTurnOutcome = - | { kind: "completed" } - | { kind: "failed"; error: { message: string; code?: string } } - | { kind: "canceled"; reason: string }; -``` - -| 字段 | 结构 / 含义 | -| ------------ | ---------------------------------------------------------------------------------------- | -| `turnId` | Provider 报告的 `string` 或 `null`;会话重新打开后可能重复 | -| `timeline` | `readonly AgentTimelineItem[]`;包含之前对话的完整快照;文本可能跨越多个条目 | -| `request` | SDK 的 `AgentPermissionRequest`;`kind` 为 `tool`、`plan`、`question`、`mode` 或 `other` | -| `resolution` | SDK 的 `AgentPermissionResponse` | -| `archivedAt` | 时间戳字符串 | - -### before 钩子 {#before-hooks} - -| 名称 | 请求字段 | 可编辑 | -| -------------------- | ------------------------------------------------------------------------------------------------------------ | ----------------------------------- | -| `agent.create` | `config`,可选的 `env` | 除 `cwd` 外的公开 Agent 配置;`env` | -| `agent.session_open` | `agentId`, `workspaceId`, `provider`, `cwd`,只读的 `title` 和 `labels`,`reason`, `purpose`, `env`, `tools` | `env` 和 `tools` | -| `workspace.create` | `source`,可选的 `title`,`firstAgentContext` | 整个显式创建请求 | - -**`agent.create.config`** 使用 `AgentSessionConfig`: - -| 字段 | 约束 | -| --------------------------------------------- | -------------------------------------------------------- | -| `provider`, `model` | 独立的字段;修改 Provider 可能需要同时修改模型/模式/选项 | -| `modeId`, `thinkingOptionId`, `featureValues` | 特定于 Provider 的选择 | -| `title`, `systemPrompt` | Agent 配置 | -| `providerOptions` | 不透明的、特定于 Provider 的选项 | -| `mcpServers`, `toolPolicy` | MCP 配置和精确的工具预批准 | -| `cwd` | 不能修改 | - -**`agent.session_open` 请求示例:** - -```json -{ - "agentId": "agent-123", - "workspaceId": "workspace-456", - "provider": "codex", - "cwd": "/projects/shop", - "title": "Workspace notes", - "labels": { "notes/enabled": "true" }, - "tools": [], - "reason": "resume", - "purpose": "interactive", - "env": { "COMPANY_ENV": "development" } -} -``` - -| 字段 | 取值 | -| ------------- | -------------------------------------------------------------------------------------------------------- | -| `workspaceId` | 字符串或 `null` | -| `title` | 只读字符串或 `null`;创建时使用创建请求的标题,恢复时使用已保存的标题。 | -| `labels` | 只读的字符串映射;创建时使用创建请求的标签,恢复时使用已保存的标签。 | -| `tools` | 可编辑的 `AgentToolDefinition[]`,仅包含此插件的工具。参阅[为 Agent 附加工具](#attach-tools-to-agents)。 | -| `reason` | `create`、`resume`、`refresh`、`import` | -| `purpose` | `interactive`、`history` | -| `env` | 启动覆盖映射;不包括 daemon 继承的环境变量。替换整个映射即可添加、替换或移除覆盖项。 | - -### 顺序与返回值 {#ordering-and-returned-values} - -```text -Creation request - → agent.create hooks (plugin-ID order; registration order within each plugin) - → resolve defaults and validate provider configuration - → derive launch configuration with Paseo runtime tools and daemon prompt - → agent.session_open hooks (same ordering; env and plugin-local tools) - → set PASEO_AGENT_ID and PASEO_AGENT_CWD - → open provider session and save agent configuration -``` - -| 回调返回 | 下一个回调收到 | -| ------------------------------------------------------- | --------------------------------- | -| `{ ...request, env: { ...request.env, REGION: "eu" } }` | 之前的请求,添加或替换了 `REGION` | -| `{ ...request, env: { REGION: "eu" } }` | 之前的请求,整个覆盖映射被替换 | -| `undefined` | 未改变的请求 | -| 抛出错误或返回无效数据 | 操作失败;后面的回调不会运行 | - -没有自动的深度合并。后面的回调可以覆盖前面的值。Agent 配置会被保存;环境变量覆盖项不会随之持久化。 - -### context 与清理 {#context-and-cleanup} - -| 契约 | 行为 | -| -------------------------- | ----------------------------------------------------------------------------------- | -| `context.paseo` | 已连接到此 daemon 的现有 SDK | -| `context.signal` | 在调用超时或插件停止时中止;请把它传给外部请求 | -| 输入数据 | 分离的快照;通过返回的请求或 SDK 命令改变状态 | -| 注册结果 | 幂等的移除函数,例如 `const remove = server.on(...); remove();` | -| 重新加载、停用、移除、关闭 | 移除剩余的注册 | -| 未知的钩子名称 | 注册失败 | -| 钩子超时 | 30 秒;会中止 signal。before 钩子会让待处理的操作失败;事件处理函数会记录一条错误。 | -| 事件处理函数出错 | 记录在插件名下;原操作继续进行 | -| 事件投递 | 实时、尽力而为;没有重放、持久化或自动重试 | -| 事件并发 | 不同的事件可能重叠;不保证回调完成的顺序 | - -### 完整示例 {#complete-examples} - -| 插件 | 包含 | -| ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------ | -| [lifecycle-logger](https://github.com/getpaseo/paseo/tree/main/plugin-examples/lifecycle-logger) | 全部十一个钩子;隐去环境变量值的 JSON 日志 | -| [lifecycle-actions](https://github.com/getpaseo/paseo/tree/main/plugin-examples/lifecycle-actions) | 后续消息、权限、环境变量、切换 Provider、选择 worktree | -| [agent-configuration](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-configuration) | MCP 注入以及 Codex 沙盒/批准选项 | -| [agent-tools](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-tools) | 按标签选择 Agent,并在插件进程中执行文件操作的工具 | - -用 `paseo plugin logs lifecycle-logger` 或主机的 `daemon.log` 读取 logger 的输出。 +使用 `server.addHook(name, handler)` 注册异步处理函数。请参阅[钩子](/docs/plugins/hooks),了解命名、载荷、顺序、错误处理和完整示例。 ## 界面和侧边栏项 {#screens-and-sidebar-items} @@ -1187,7 +754,7 @@ export function IssueActions({ theme }: PluginSurfaceProps) { ```tsx import { Markdown } from "@getpaseo/plugin/client/ui"; -{"## 审查\n\n检查**通过**。"}; +{"## Review\n\nThe checks **passed**."}; ``` `children` 是唯一的属性,必须为字符串。更新它会立即渲染新内容;空字符串不渲染任何内容。 @@ -2151,7 +1718,7 @@ const behavior: PluginButtonBehavior = { 隐藏或禁用按钮会关闭它的浮层。更新它的 behavior 也会关闭浮层。隐藏会保留注册,因此再次显示时会恢复它 原来的位置。它不会取消已经在进行中的操作。 -`remove()` 是幂等的。移除之后的更新不起作用。当插件安装或主机连接被拆除时,Paseo 会移除尚存的按钮。 +`remove()` 是幂等的。移除之后的更新不起作用。当插件安装被销毁时,Paseo 会移除尚存的按钮(参见[主机与生命周期](#hosts-and-lifecycle))。 请从客户端入口返回清理函数,用来释放你的订阅、定时器和其他资源。 ## 使用 Paseo SDK {#use-the-paseo-sdk} @@ -2470,8 +2037,11 @@ Composer 菜单、搜索选择器、选中后的胶囊、草稿状态和提交 附件来源仍然限定在各个 Composer 所在的主机上。 -工作区面板和 Command Center 条目仍然限定在当前活动的主机和确切的缓存上下文中。重新加载会替换它们的 -注册。停用、移除、主机断开和求值失败会移除 Command Center 条目,并清除该安装的查询状态。已经恢复的面板 +连接中断时,客户端插件的注册、已挂载界面、本地状态和查询缓存会保留。通过原有的 `DaemonClient` 对象重新连接时,未变化的安装会保留,其设置会刷新。请使用 SDK 观察快照刷新其他 daemon 状态;未变化的安装不会再次运行初始化函数。调用 daemon 仍然依赖连接。 + +切换连接(例如从直连切换到中继)目前会替换 `DaemonClient` 对象并重新安装客户端插件。重新加载、插件包或版本要求变化、停用、移除插件和移除主机也会销毁受影响的安装,并清除其查询状态。如果替换安装求值失败,它的贡献将不可用。 + +工作区面板和 Command Center 条目仍然限定在当前活动的主机和确切的缓存上下文中。已经恢复的面板 标签页会保持“不可用”状态,直到与之匹配的贡献重新出现或用户关闭它。面板的渲染失败会被限制在插件的错误 边界内。 diff --git a/public-docs/worktrees.md b/public-docs/worktrees/index.md similarity index 88% rename from public-docs/worktrees.md rename to public-docs/worktrees/index.md index 5bb1db793f..faabb2d81f 100644 --- a/public-docs/worktrees.md +++ b/public-docs/worktrees/index.md @@ -35,6 +35,8 @@ With a custom root, Paseo keeps the same hashed layout under that directory: } ``` +Plugins can choose a location anywhere on disk with [`worktree.create.before`](/docs/plugins/hooks#worktreecreatebefore). The [worktree-placement example](https://github.com/getpaseo/paseo/tree/main/plugin-examples/worktree-placement) places worktrees next to the source checkout. Paseo validates the path, refuses an existing destination, and manages listing, archive, and deletion there. Recovery uses the recorded path without running creation hooks. + 1. Create a workspace with worktree isolation, Paseo creates the worktree and runs your setup hooks 2. Launch one or more agents in that workspace 3. Review the diff against the base branch @@ -80,6 +82,10 @@ paseo workspace create \ Add `--forge ` when Paseo cannot infer the forge from the source checkout. +## Copy local files with .worktreeinclude + +Use [`.worktreeinclude`](/docs/worktrees/worktreeinclude) to copy selected gitignored files, such as `.env`, from your source checkout before setup runs. + ## paseo.json Drop a `paseo.json` in your repo root. Paseo reads it from the committed version of the base branch you picked, so uncommitted changes in other branches don't apply. @@ -99,12 +105,14 @@ Drop a `paseo.json` in your repo root. Paseo reads it from the committed version ## Setup and teardown -`setup` runs once after the worktree is created. A fresh worktree has no installed dependencies and no ignored files (like `.env`), so use setup to install and copy what you need. `teardown` runs during archive, before the directory is removed. +Plugins can use [`worktree.create.after`](/docs/plugins/hooks#worktreecreateafter) to write files before setup, terminals, and the first agent. + +`setup` runs once after the worktree is created. Use setup to install dependencies and run project initialization. Use [`.worktreeinclude`](#copy-local-files-with-worktreeinclude) to copy ignored files such as `.env`. `teardown` runs during archive, before the directory is removed. ```json { "worktree": { - "setup": "npm ci\ncp \"$PASEO_SOURCE_CHECKOUT_PATH/.env\" .env\nnpm run db:migrate", + "setup": "npm ci\nnpm run db:migrate", "teardown": "npm run db:drop || true" } } diff --git a/public-docs/worktrees.zh-CN.md b/public-docs/worktrees/index.zh-CN.md similarity index 88% rename from public-docs/worktrees.zh-CN.md rename to public-docs/worktrees/index.zh-CN.md index 0bf3af55a4..cce65fc090 100644 --- a/public-docs/worktrees.zh-CN.md +++ b/public-docs/worktrees/index.zh-CN.md @@ -33,6 +33,8 @@ worktree 默认存放在 `$PASEO_HOME/worktrees/` 下,按源检出路径的哈 } ``` +插件可以通过 [`worktree.create.before`](/docs/plugins/hooks#worktreecreatebefore) 将 worktree 放到磁盘上的自选位置。[worktree-placement 示例](https://github.com/getpaseo/paseo/tree/main/plugin-examples/worktree-placement) 将其放在源检出目录旁边。Paseo 验证路径并拒绝已存在的目标,同时支持在该位置列出、归档和删除 worktree。恢复时使用记录的原路径,不运行创建钩子。 + 1. 创建一个使用 worktree 隔离的工作区,Paseo 会创建 worktree 并运行你的 setup 钩子 2. 在该工作区中启动一个或多个 Agent 3. 对照基础分支审查 diff @@ -78,6 +80,10 @@ paseo workspace create \ 当 Paseo 无法从源检出推断代码托管平台时,添加 `--forge `。 +## 使用 .worktreeinclude 复制本地文件 {#copy-local-files-with-worktreeinclude} + +使用 [`.worktreeinclude`](/docs/worktrees/worktreeinclude),在 setup 运行前将 `.env` 等选定的 Git 忽略文件从源检出复制到新 worktree。 + ## paseo.json {#paseojson} 在仓库根目录放一个 `paseo.json`。Paseo 从你所选基础分支的已提交版本中读取它,因此其他分支中未提交的改动不会生效。 @@ -97,12 +103,14 @@ paseo workspace create \ ## Setup 与 teardown {#setup-and-teardown} -`setup` 在 worktree 创建后运行一次。新的 worktree 没有安装依赖,也没有被忽略的文件(例如 `.env`),因此请用 setup 安装和复制你需要的内容。`teardown` 在归档期间、目录被删除之前运行。 +插件可以通过 [`worktree.create.after`](/docs/plugins/hooks#worktreecreateafter) 在 setup、终端和第一个 Agent 运行之前写入文件。 + +`setup` 在 worktree 创建后运行一次。使用 setup 安装依赖并初始化项目。使用 [`.worktreeinclude`](#copy-local-files-with-worktreeinclude) 复制 `.env` 等被忽略的文件。`teardown` 在归档期间、目录被删除之前运行。 ```json { "worktree": { - "setup": "npm ci\ncp \"$PASEO_SOURCE_CHECKOUT_PATH/.env\" .env\nnpm run db:migrate", + "setup": "npm ci\nnpm run db:migrate", "teardown": "npm run db:drop || true" } } diff --git a/public-docs/worktrees/worktreeinclude.md b/public-docs/worktrees/worktreeinclude.md new file mode 100644 index 0000000000..50c5f0370a --- /dev/null +++ b/public-docs/worktrees/worktreeinclude.md @@ -0,0 +1,61 @@ +--- +title: .worktreeinclude +description: Copy gitignored local files into new Paseo worktrees. +nav: .worktreeinclude +order: 12 +category: Workspaces +--- + +# .worktreeinclude + +Add `.worktreeinclude` at the root of your source checkout to copy local configuration into new [Git worktrees](/docs/worktrees). Paseo copies matching gitignored files before setup, terminals, and the first Agent start. + +## Copy your local configuration + +For a project whose `.gitignore` includes `.env` and `config/*.local.json`, create this `.worktreeinclude`: + +```gitignore +.env +config/*.local.json +``` + +When you create a worktree through Paseo, an existing `.env` and matching files such as `config/dev.local.json` are copied to the same relative paths in the new worktree. Their contents stay out of Git. + +Commit `.worktreeinclude` to share the patterns with your team. Each teammate supplies their own ignored files in the checkout they create worktrees from. + +## Pattern syntax + +Use gitignore syntax, with one pattern per line. Comments start with `#`. Prefix a pattern with `!` to exclude a match: + +```gitignore +# Local environment and configuration +.env +config/*.local.json +!config/production.local.json +``` + +A pattern only selects files that Git already ignores. Adding a path here does not ignore it, so also configure `.gitignore` when needed. Tracked files and untracked files that Git does not ignore are excluded. + +## When files are copied + +The built-in `worktree-include` plugin reads the file from the checkout you create the worktree from. That source can itself be another worktree. Keep the plugin enabled for copying to run. + +- Without `.worktreeinclude`, the plugin copies nothing. +- Matching files must exist in the source checkout. +- Existing destination files are skipped, preserving their contents. +- Copies happen during creation, with no ongoing synchronization between checkouts. +- A copy error aborts creation and removes the new worktree. Avoid including symlinked directories or nested repositories, which cannot be copied as files. + +## Run commands during setup + +Use `.worktreeinclude` for files that already exist locally. Use a [setup hook](/docs/worktrees#setup-and-teardown) to install dependencies, generate files, or fetch secrets: + +```json +{ + "worktree": { + "setup": "npm ci" + } +} +``` + +Put this configuration in `paseo.json` on the base branch used for the new worktree. Copied files are available when setup runs. diff --git a/public-docs/worktrees/worktreeinclude.zh-CN.md b/public-docs/worktrees/worktreeinclude.zh-CN.md new file mode 100644 index 0000000000..e80e386a01 --- /dev/null +++ b/public-docs/worktrees/worktreeinclude.zh-CN.md @@ -0,0 +1,61 @@ +--- +title: .worktreeinclude +description: 将 Git 忽略的本地文件复制到新的 Paseo worktree。 +nav: .worktreeinclude +order: 12 +category: Workspaces +--- + +# .worktreeinclude + +在源检出的根目录添加 `.worktreeinclude`,将本地配置复制到新的 [Git worktree](/docs/worktrees)。Paseo 会在 setup、终端和首个 Agent 启动之前复制匹配的 Git 忽略文件。 + +## 复制本地配置 {#copy-your-local-configuration} + +如果项目的 `.gitignore` 包含 `.env` 和 `config/*.local.json`,创建以下 `.worktreeinclude`: + +```gitignore +.env +config/*.local.json +``` + +通过 Paseo 创建 worktree 时,已有的 `.env` 和 `config/dev.local.json` 等匹配文件会被复制到新 worktree 中的相同相对路径。文件内容仍不会纳入 Git。 + +提交 `.worktreeinclude`,与团队共享这些模式。每位团队成员在用于创建 worktree 的检出中提供自己的忽略文件。 + +## 模式语法 {#pattern-syntax} + +使用 gitignore 语法,每行一个模式。注释以 `#` 开头。模式前加 `!` 可排除匹配项: + +```gitignore +# Local environment and configuration +.env +config/*.local.json +!config/production.local.json +``` + +模式只会选择 Git 已忽略的文件。在此添加路径不会使 Git 忽略该文件,需要时还应配置 `.gitignore`。已跟踪的文件和未被 Git 忽略的未跟踪文件都不会被复制。 + +## 文件复制时机 {#when-files-are-copied} + +内置的 `worktree-include` 插件从用于创建 worktree 的检出读取该文件。源检出也可以是另一个 worktree。保持该插件启用才能执行复制。 + +- 没有 `.worktreeinclude` 时,插件不会复制任何文件。 +- 匹配的文件必须存在于源检出中。 +- 目标中已存在的文件会被跳过,保留原有内容。 +- 复制发生在创建期间,之后不会在检出之间持续同步。 +- 复制错误会中止创建并删除新 worktree。避免包含符号链接目录或嵌套仓库,因为它们无法作为文件复制。 + +## 在 setup 期间运行命令 {#run-commands-during-setup} + +使用 `.worktreeinclude` 复制本地已有文件。使用 [setup 钩子](/docs/worktrees#setup-and-teardown) 安装依赖、生成文件或获取密钥: + +```json +{ + "worktree": { + "setup": "npm ci" + } +} +``` + +将此配置放入新 worktree 所用基准分支的 `paseo.json` 中。setup 运行时,复制的文件已可使用。 diff --git a/scripts/ci-workflow.test.mjs b/scripts/ci-workflow.test.mjs index c7e631c529..97720f46ec 100644 --- a/scripts/ci-workflow.test.mjs +++ b/scripts/ci-workflow.test.mjs @@ -1,5 +1,5 @@ import assert from "node:assert/strict"; -import { readFileSync, readdirSync, mkdtempSync, writeFileSync, rmSync } from "node:fs"; +import { readFileSync, readdirSync, mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs"; import { spawnSync } from "node:child_process"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -24,7 +24,10 @@ const gatedCiJobs = new Map([ "server-integration-windows", { name: "server-integration (windows-latest)", contract: "server" }, ], - ["server-tests-macos", { name: "server-tests (macos-14, file observation)", contract: "server" }], + [ + "server-tests-macos", + { name: "server-tests (macos-latest, file observation)", contract: "server" }, + ], ["desktop-tests-ubuntu", { name: "desktop-tests (ubuntu-latest)", contract: "desktop" }], ["desktop-tests-windows", { name: "desktop-tests (windows-latest)", contract: "desktop" }], ["app-tests", { name: "app-tests", contract: "app" }], @@ -157,6 +160,14 @@ test("focused contracts stay inside existing required checks", () => { assert.ok(!jobs.has("playwright-desktop")); }); +test("ordinary CI keeps app tests without prebuilding Android modules", () => { + const source = readFileSync(ciWorkflowPath, "utf8"); + const app = jobBlocks(source).get("app-tests").join("\n"); + assert.match(app, /npm run build:app-deps/); + assert.match(app, /npm run test --workspace=@getpaseo\/app/); + assert.doesNotMatch(source, /test:android|expo prebuild|gradlew|actions\/setup-java/); +}); + test("server builds exclude test utilities at every domain depth", () => { const tsconfig = JSON.parse(readFileSync(serverTsconfigPath, "utf8")); assert.ok(tsconfig.exclude.includes("src/server/**/test-utils/**")); @@ -641,3 +652,75 @@ process.exit(code); }); } }); + +// GitHub retires macOS 14 on 2026-11-02; brownouts already reject these jobs. +test("workflows avoid retired macOS 14 runners", () => { + for (const path of filesUnder(".github/workflows", (candidate) => /\.ya?ml$/.test(candidate))) { + assert.doesNotMatch( + readFileSync(new URL(path, repoRoot), "utf8"), + /macos-14(?:-large|-xlarge)?\b/, + path, + ); + } +}); + +test("macOS jobs use latest runners while preserving release architectures", () => { + for (const [workflow, jobId] of [ + [ciWorkflowPath, "server-tests-macos"], + [nixWorkflowPath, "build-desktop-darwin"], + ]) { + assert.match( + jobBlocks(readFileSync(workflow, "utf8")).get(jobId).join("\n"), + /^ runs-on: macos-latest$/m, + ); + } + const release = readFileSync(new URL(".github/workflows/desktop-release.yml", repoRoot), "utf8"); + assert.match(release, /runner: macos-latest\n\s+electron_arch: arm64/); + // GitHub has no standard macos-latest-intel alias; use the newest Intel image. + assert.match(release, /runner: macos-26-intel\n\s+electron_arch: x64/); +}); + +test("Nix desktop packaging resolves the workspace-local builder", () => { + const source = readFileSync(new URL("nix/desktop-package.nix", repoRoot), "utf8"); + const invocation = source.match(/^\s+([^\n]*electron-builder) \\\n/m)?.[1]; + assert.ok(invocation, "Nix invokes the desktop packaging tool"); + const directory = mkdtempSync(join(tmpdir(), "nix-builder-resolution-")); + try { + const desktop = join(directory, "packages/desktop"); + mkdirSync(join(desktop, "node_modules/.bin"), { recursive: true }); + mkdirSync(join(desktop, "node_modules/electron-builder")); + writeFileSync( + join(desktop, "node_modules/electron-builder/package.json"), + JSON.stringify({ + name: "electron-builder", + version: "1.0.0", + bin: { "electron-builder": "../.bin/electron-builder" }, + }), + ); + writeFileSync( + join(directory, "package.json"), + JSON.stringify({ private: true, workspaces: ["packages/desktop"] }), + ); + writeFileSync( + join(desktop, "package.json"), + JSON.stringify({ + name: "desktop-fixture", + private: true, + devDependencies: { "electron-builder": "1.0.0" }, + }), + ); + writeFileSync( + join(desktop, "node_modules/.bin/electron-builder"), + '#!/bin/sh\nprintf "workspace-builder\\n"\n', + { mode: 0o755 }, + ); + const result = spawnSync("sh", ["-c", `${invocation} --version`], { + cwd: desktop, + encoding: "utf8", + }); + assert.equal(result.status, 0, result.stderr); + assert.equal(result.stdout.trim(), "workspace-builder"); + } finally { + rmSync(directory, { recursive: true, force: true }); + } +}); diff --git a/scripts/oxlint/paseo-plugin.mjs b/scripts/oxlint/paseo-plugin.mjs index d6f8d0365e..af58021991 100644 --- a/scripts/oxlint/paseo-plugin.mjs +++ b/scripts/oxlint/paseo-plugin.mjs @@ -34,9 +34,130 @@ const noRawPressable = { }, }; +const SYNC_IO_MODULES = new Set(["fs", "node:fs", "child_process", "node:child_process"]); + +function propertyName(node) { + return node.type === "Identifier" ? node.name : node.value; +} + +function findDefinition(node, sourceCode) { + let scope = sourceCode.getScope(node); + while (scope && !scope.set.has(node.name)) scope = scope.upper; + return scope?.set.get(node.name)?.defs[0]; +} + +function isIoNamespaceImport(definition) { + if (definition?.node.type === "TSImportEqualsDeclaration") { + return SYNC_IO_MODULES.has(definition.node.moduleReference.expression?.value); + } + if (definition?.type !== "ImportBinding") return false; + return ( + (definition.node.type !== "ImportSpecifier" || + propertyName(definition.node.imported) === "default") && + SYNC_IO_MODULES.has(definition.parent.source.value) + ); +} + +// Follow only immutable namespace aliases. Resolve bindings rather than spelling so a parameter +// named `fs` is not mistaken for the imported namespace. +function isIoNamespace(node, sourceCode, seen = new Set()) { + if (!node || seen.has(node)) return false; + seen.add(node); + if (node.type === "AwaitExpression") return isIoNamespace(node.argument, sourceCode, seen); + if (node.type === "ImportExpression") return SYNC_IO_MODULES.has(node.source.value); + if (node.type === "CallExpression") { + return ( + node.callee.type === "Identifier" && + node.callee.name === "require" && + SYNC_IO_MODULES.has(node.arguments[0]?.value) + ); + } + if (node.type !== "Identifier") return false; + const definition = findDefinition(node, sourceCode); + if (isIoNamespaceImport(definition)) return true; + return ( + definition?.type === "Variable" && + definition.parent.kind === "const" && + definition.node.id.type === "Identifier" && + isIoNamespace(definition.node.init, sourceCode, seen) + ); +} + +const noSyncIo = { + meta: { + schema: [ + { + type: "object", + properties: { + allow: { + type: "object", + additionalProperties: { type: "array", items: { type: "string" } }, + }, + }, + additionalProperties: false, + }, + ], + }, + create(context) { + const filename = context.filename.replaceAll("\\", "/"); + const relativeFile = filename.split("/packages/server/src/")[1]; + const allowed = new Set(context.options[0]?.allow?.[relativeFile] ?? []); + const unused = new Set(allowed); + function check(node, name) { + if (typeof name !== "string" || !name.endsWith("Sync")) return; + if (allowed.has(name)) { + unused.delete(name); + return; + } + context.report({ + node, + message: `Synchronous Node IO (${name}) blocks the daemon event loop. Use an asynchronous capability at the owning module boundary.`, + }); + } + return { + "Program:exit"(node) { + for (const name of unused) { + context.report({ node, message: `Remove the unused sync IO exception for ${name}.` }); + } + }, + ImportDeclaration(node) { + if (node.importKind === "type" || !SYNC_IO_MODULES.has(node.source.value)) return; + for (const specifier of node.specifiers) { + if (specifier.type === "ImportSpecifier" && specifier.importKind !== "type") { + check(specifier, propertyName(specifier.imported)); + } + } + }, + ExportNamedDeclaration(node) { + if (node.exportKind === "type" || !SYNC_IO_MODULES.has(node.source?.value)) return; + for (const specifier of node.specifiers) { + if (specifier.exportKind !== "type") check(specifier, propertyName(specifier.local)); + } + }, + MemberExpression(node) { + if (node.computed && node.property.type !== "Literal") return; + const name = propertyName(node.property); + if (typeof name !== "string" || !name.endsWith("Sync")) return; + if (isIoNamespace(node.object, context.sourceCode)) { + check(node.property, name); + } + }, + VariableDeclarator(node) { + if (node.id.type !== "ObjectPattern" || !isIoNamespace(node.init, context.sourceCode)) { + return; + } + for (const property of node.id.properties) { + if (property.type === "Property") check(property, propertyName(property.key)); + } + }, + }; + }, +}; + export default { meta: { name: "paseo" }, rules: { "no-raw-pressable": noRawPressable, + "no-sync-io": noSyncIo, }, }; diff --git a/scripts/oxlint/paseo-plugin.test.mjs b/scripts/oxlint/paseo-plugin.test.mjs index c30a429026..4312f5e337 100644 --- a/scripts/oxlint/paseo-plugin.test.mjs +++ b/scripts/oxlint/paseo-plugin.test.mjs @@ -1,6 +1,6 @@ import assert from "node:assert/strict"; import { spawnSync } from "node:child_process"; -import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; import { test } from "node:test"; @@ -10,15 +10,21 @@ const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../ const oxlintBin = path.join(repoRoot, "node_modules/.bin/oxlint"); const pluginPath = path.join(repoRoot, "scripts/oxlint/paseo-plugin.mjs"); -function lint(source) { +function lint(source, rule = "paseo/no-raw-pressable", options, filename = "probe.tsx") { + const config = JSON.stringify({ + jsPlugins: [pluginPath], + rules: { [rule]: options ? ["error", options] : "error" }, + }); + return lintWithConfig(source, config, filename); +} + +function lintWithConfig(source, config, filename) { const dir = mkdtempSync(path.join(tmpdir(), "paseo-oxlint-")); try { - writeFileSync( - path.join(dir, ".oxlintrc.json"), - JSON.stringify({ jsPlugins: [pluginPath], rules: { "paseo/no-raw-pressable": "error" } }), - ); - writeFileSync(path.join(dir, "probe.tsx"), source); - const result = spawnSync(oxlintBin, ["-c", ".oxlintrc.json", "probe.tsx"], { + writeFileSync(path.join(dir, ".oxlintrc.json"), config); + mkdirSync(path.dirname(path.join(dir, filename)), { recursive: true }); + writeFileSync(path.join(dir, filename), source); + const result = spawnSync(oxlintBin, ["-c", ".oxlintrc.json", filename], { cwd: dir, encoding: "utf8", }); @@ -52,3 +58,95 @@ test("press primitives and pressable types are allowed", () => { ); assert.equal(result.failed, false, result.output); }); + +for (const source of [ + 'import { readFileSync as read } from "node:fs"; export { read };', + 'import { execSync } from "child_process"; export { execSync };', + 'import fs from "node:fs"; export const read = fs.readFileSync;', + 'import { default as fs } from "node:fs"; export const read = fs.readFileSync;', + 'import fs = require("node:fs"); export const read = fs.readFileSync;', + 'import * as fs from "fs"; export const read = fs["readFileSync"];', + 'import cp from "node:child_process"; export const run = cp.spawnSync;', + 'const { readFileSync: read } = require("node:fs"); export { read };', + 'const fs = require("fs"); export const read = fs.readFileSync;', + 'export const run = require("node:child_process").execFileSync;', + 'import fs from "node:fs"; const other = fs; export const read = other.statSync;', + 'export { readFileSync as read } from "node:fs";', + 'export const read = (await import("node:fs")).readFileSync;', +]) { + test(`sync IO is reported: ${source}`, () => { + const result = lint(source, "paseo/no-sync-io"); + assert.equal(result.failed, true, result.output); + assert.match(result.output, /Synchronous Node IO/); + }); +} + +test("async IO, types, unrelated methods and shadowed namespaces are allowed", () => { + const result = lint( + 'import fs from "node:fs"; import { readFile } from "node:fs/promises";\n' + + 'import type { readFileSync } from "node:fs";\n' + + "export const read = readFile; export const asyncRead = fs.promises.readFile;\n" + + "export function unrelated(fs: { readFileSync(): void }) { fs.readFileSync(); }\n" + + "export type Reader = typeof readFileSync;\n", + "paseo/no-sync-io", + ); + assert.equal(result.failed, false, result.output); +}); + +test("sync IO exceptions allow only named APIs in the named server module", () => { + const options = { allow: { "server/startup.ts": ["readFileSync"] } }; + const source = 'import { readFileSync } from "node:fs"; export { readFileSync };'; + const allowed = lint( + source, + "paseo/no-sync-io", + options, + "packages/server/src/server/startup.ts", + ); + assert.equal(allowed.failed, false, allowed.output); + const otherFile = lint( + source, + "paseo/no-sync-io", + options, + "packages/server/src/server/session.ts", + ); + assert.equal(otherFile.failed, true, otherFile.output); + assert.match(otherFile.output, /Synchronous Node IO/); + const otherApi = lint( + 'import fs from "node:fs"; export const read = fs.statSync;', + "paseo/no-sync-io", + options, + "packages/server/src/server/startup.ts", + ); + assert.equal(otherApi.failed, true, otherApi.output); + assert.match(otherApi.output, /Synchronous Node IO/); +}); + +test("repository config guards request paths while allowing startup APIs and test fixtures", () => { + const config = readFileSync(path.join(repoRoot, ".oxlintrc.json"), "utf8").replace( + '"./scripts/oxlint/paseo-plugin.mjs"', + JSON.stringify(pluginPath), + ); + const source = 'import { existsSync } from "node:fs"; export const probe = existsSync;'; + const request = lintWithConfig(source, config, "packages/server/src/server/probe.ts"); + assert.equal(request.failed, true, request.output); + assert.match(request.output, /Synchronous Node IO/); + for (const filename of [ + "packages/server/src/server/config.ts", + "packages/server/src/server/probe.test.ts", + "packages/app/src/probe.ts", + ]) { + const result = lintWithConfig(source, config, filename); + assert.equal(result.failed, false, result.output); + } +}); + +test("sync IO exceptions must be removed when a module stops using the API", () => { + const result = lint( + 'import { readFile } from "node:fs/promises"; export const read = readFile;', + "paseo/no-sync-io", + { allow: { "server/startup.ts": ["readFileSync"] } }, + "packages/server/src/server/startup.ts", + ); + assert.equal(result.failed, true, result.output); + assert.match(result.output, /Remove the unused sync IO exception for readFileSync/); +}); diff --git a/scripts/postinstall-patches.mjs b/scripts/postinstall-patches.mjs index 435f6331e0..3dbbeddcaf 100644 --- a/scripts/postinstall-patches.mjs +++ b/scripts/postinstall-patches.mjs @@ -24,7 +24,13 @@ const patchedPackages = [ }, // Registry cleanup: remove after react-native-unistyles ships // https://github.com/jpudysz/react-native-unistyles/pull/1203. + // Adaptive themes: keep until colorScheme reads no longer consume listener-owned media changes. // withUnistyles: also keep the uniProps filter until upstream consumes its control prop. + // Android configuration: backport 3.5.3; remove the two NativePlatform hunks at >= 3.5.3. + // https://github.com/jpudysz/react-native-unistyles/compare/v3.5.2...v3.5.3 + // Layout constraints: backport of https://github.com/jpudysz/react-native-unistyles/pull/1357 + // (commit from the root the commit hands us, so a concurrent window-size commit is kept). + // Remove the ShadowTreeManager hunk when the installed release includes that PR. { nodeModulesPath: "node_modules/react-native-unistyles", patchPrefix: "react-native-unistyles+", @@ -56,6 +62,8 @@ const patchedPackages = [ nodeModulesPath: "node_modules/@gorhom/bottom-sheet", patchPrefix: "@gorhom+bottom-sheet+", }, + // Android resize: retain until upstream clears descendant geometry when the SVG canvas resizes. + // The native pixel regression is included in the patch; preserve the separate transform hunks. { nodeModulesPath: "packages/app/node_modules/react-native-svg", patchPrefix: "react-native-svg+", diff --git a/scripts/postinstall-patches.test.mjs b/scripts/postinstall-patches.test.mjs index 9e4d4c0722..11cd2d157a 100644 --- a/scripts/postinstall-patches.test.mjs +++ b/scripts/postinstall-patches.test.mjs @@ -10,6 +10,43 @@ const bin = path.resolve("node_modules", ".bin"); const packageName = "react-native-draggable-flatlist"; const patchFile = `${packageName}+4.0.3.patch`; +for (const platform of ["ios", "android"]) { + test(`patched Markdown ships ${platform} props generated from its native specs`, () => { + const packageDir = path.resolve("packages/app/node_modules/react-native-enriched-markdown"); + const output = mkdtempSync(path.join(tmpdir(), `markdown-${platform}-codegen-`)); + try { + // includesGeneratedCode makes native builds use the shipped headers instead of + // regenerating them after patch-package changes the TypeScript specs. + const result = spawnSync( + process.execPath, + [ + path.resolve("node_modules/react-native/scripts/generate-codegen-artifacts.js"), + "-p", + packageDir, + "-t", + platform, + "-o", + output, + "-s", + "library", + ], + { encoding: "utf8" }, + ); + assert.equal(result.status, 0, result.stdout + result.stderr); + const header = + platform === "ios" + ? "ReactCodegen/EnrichedMarkdownTextSpec/Props.h" + : "jni/react/renderer/components/EnrichedMarkdownTextSpec/Props.h"; + assert.equal( + readFileSync(path.join(packageDir, platform, "generated", header), "utf8"), + readFileSync(path.join(output, header), "utf8"), + ); + } finally { + rmSync(output, { recursive: true, force: true }); + } + }); +} + function createCheckout() { const root = mkdtempSync(path.join(tmpdir(), "postinstall-patches-")); writeFileSync(path.join(root, "package.json"), JSON.stringify({ name: "checkout" })); diff --git a/scripts/test-support/npm-registry.mts b/scripts/test-support/npm-registry.mts index a0a39e27d9..5640487049 100644 --- a/scripts/test-support/npm-registry.mts +++ b/scripts/test-support/npm-registry.mts @@ -50,6 +50,7 @@ export async function startNpmRegistry(packages: FixturePackage[]) { `registry=${url}/\n//127.0.0.1:${address.port}/:_authToken=fixture-token\ncache=${root}/cache\n`, ); try { + const prepared = []; for (const [index, pkg] of packages.entries()) { const directory = path.join(root, String(index)); await mkdir(directory); @@ -65,11 +66,17 @@ export async function startNpmRegistry(packages: FixturePackage[]) { await mkdir(path.dirname(path.join(directory, file)), { recursive: true }); await writeFile(path.join(directory, file), content); } - const { stdout } = await execCommand("npm", ["pack", "--ignore-scripts", "--json"], { - cwd: directory, - }); - const packed: Array<{ filename: string }> = JSON.parse(stdout); - const artifact = await readFile(path.join(directory, packed[0].filename)); + prepared.push({ directory, manifest, pkg, index }); + } + // Pack all fixtures in one npm process instead of paying startup once per package. + const { stdout } = await execCommand( + "npm", + ["pack", "--ignore-scripts", "--json", ...prepared.map(({ directory }) => directory)], + { cwd: root }, + ); + const packed: Array<{ filename: string }> = JSON.parse(stdout); + for (const { manifest, pkg, index } of prepared) { + const artifact = await readFile(path.join(root, packed[index].filename)); const artifactPath = `/artifacts/${index}.tgz`; artifacts.set(artifactPath, artifact); const published = { diff --git a/skills/paseo-advisor/SKILL.md b/skills/paseo-advisor/SKILL.md index 94d4558e5a..23868d9a2d 100644 --- a/skills/paseo-advisor/SKILL.md +++ b/skills/paseo-advisor/SKILL.md @@ -9,7 +9,7 @@ argument-hint: "[--profile ] " Single agent. Reads the situation you're in. Gives a judgment. You decide what to do — the advisor doesn't drive the work. -**User's request:** $ARGUMENTS +Use the user's request and current conversation as input, including any arguments supplied with the skill invocation. Optional syntax: `[--profile ] `. ## Prerequisites @@ -40,13 +40,15 @@ This is analysis only. Do NOT edit, create, or delete any files. Do NOT write co ## Forwarded skills -If `$ARGUMENTS` contains another skill reference — `/unslop`, `/unslop-risk`, `$unslop`, etc. — the user is asking the advisor to run that skill against the current task. Examples: +If the user's request contains another skill reference, such as `/unslop`, `/skill:unslop`, or `$unslop`, the user is asking the advisor to run that skill against the current task. Examples: - `/paseo-advisor /unslop` → advisor runs `/unslop` on the current diff. - `/paseo-advisor /unslop-risk` → advisor does an unslop-risk review. - `/paseo-advisor $diagnose this build failure` → advisor invokes `/diagnose`. +- `/skill:paseo-advisor /skill:unslop` → advisor runs the `unslop` skill on the current diff in Pi. +- `$paseo-advisor $unslop` → advisor runs the `unslop` skill on the current diff in Codex. -Parse the forwarded skill name out of `$ARGUMENTS` (`/` or `$`). In the briefing, tell the advisor explicitly: +Parse the forwarded skill name from the user's request (`/`, `/skill:`, or `$`), excluding this skill's own invocation. In the briefing, tell the advisor explicitly: ``` Invoke the `` skill against this task. Load it via the Skill tool before doing anything else. diff --git a/skills/paseo-committee/SKILL.md b/skills/paseo-committee/SKILL.md index 2b16189556..e41ca8ba81 100644 --- a/skills/paseo-committee/SKILL.md +++ b/skills/paseo-committee/SKILL.md @@ -8,7 +8,7 @@ user-invocable: true Two agents from contrasting profiles, fresh context, planning a solution in parallel. -**User's additional context:** $ARGUMENTS +Use the user's request and current conversation as input, including any arguments supplied with the skill invocation. ## Prerequisites diff --git a/skills/paseo-handoff/SKILL.md b/skills/paseo-handoff/SKILL.md index b321365306..fac6793e5e 100644 --- a/skills/paseo-handoff/SKILL.md +++ b/skills/paseo-handoff/SKILL.md @@ -8,7 +8,7 @@ user-invocable: true Transfer the current task — context, decisions, failed attempts, constraints — to a fresh agent. The receiving agent starts with **zero context**, so the handoff prompt must be a self-contained briefing. -**User's arguments:** $ARGUMENTS +Use the user's request and current conversation as input, including any arguments supplied with the skill invocation. ## Prerequisites diff --git a/skills/paseo-help/SKILL.md b/skills/paseo-help/SKILL.md index 951c1207bc..52dcf57a44 100644 --- a/skills/paseo-help/SKILL.md +++ b/skills/paseo-help/SKILL.md @@ -7,7 +7,7 @@ description: Answer questions about the Paseo product and app, including setup, You are helping a user understand, configure, or troubleshoot Paseo itself. Answer their question directly, verify the answer against the current public documentation, and include the relevant documentation link. Do not send the user away to read the docs in place of helping them. -**User's question:** $ARGUMENTS +Use the user's question and current conversation as input, including any arguments supplied with the skill invocation. ## Use current documentation diff --git a/skills/paseo-plugin/SKILL.md b/skills/paseo-plugin/SKILL.md index 028d869085..b54938ad53 100644 --- a/skills/paseo-plugin/SKILL.md +++ b/skills/paseo-plugin/SKILL.md @@ -7,7 +7,7 @@ description: Build and manage trusted local Paseo plugins. Use when the user ask Build or manage the requested plugin directly. Use the current public docs to catch contract changes, but keep working from this skill if the network is unavailable. -**User's request:** $ARGUMENTS +Use the user's request and current conversation as input, including any arguments supplied with the skill invocation. ## Check current documentation @@ -27,28 +27,29 @@ public docs; this skill indexes the references and examples. Pick the contribution that matches the request. Each row names the registration, when it fits, and where the full contract lives. Most plugins combine several: a slash command that calls an RPC, which appends a timeline row, which a renderer draws. -| Contribution | Registration | Use it when | Reference | -| ------------------------- | ----------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -| Screen and sidebar item | `addScreen` + `addSidebarHeaderItem`/`addSidebarFooterItem` | A full screen of plugin UI, or sidebar header or footer rows that open a screen or popover | reference.md → Screens and sidebar items | -| Workspace panel | `addWorkspacePanel` | UI that lives as a tab beside agents, terminals, files, and diffs; `locations: ["explorer"]` for the Explorer | reference.md → Workspace panels | -| File panel | `addFilePanel` | View or edit a matching file inside the file tab through its file handle | reference.md → File panels; `plugin-examples/pdf-panel`, `plugin-examples/markdown-panel` | -| Command Center item | `addCommandCenterItem` | A global, workspace, or agent action reachable from ⌘K | reference.md → Command Center items | -| Client slash command | `addSlashCommand` | A `/command args` in the composer that runs plugin code instead of prompting the agent | reference.md → Slash commands | -| Composer pill | `addComposerPill` | A per-agent button in the composer track bar next to Tasks and Subagents | reference.md → Composer pills | -| Timeline transformer | `addTimelineTransformer` + `addTimelineRenderer` | Replace, explode, or hide a built-in timeline item, including while it streams | reference.md → Timeline items; `plugin-examples/timeline-items`, `plugin-examples/inline-thinking` | -| Timeline row | `paseo.agents.ref(id).timeline.append(...)` | Push a plugin-owned row into an agent timeline from a server handler and update it later | reference.md → Append a timeline row from the daemon | -| Attachment source | `client.addAttachmentSource` + `server.handle` | Let the user attach a searchable external resource, such as an issue, to a prompt | reference.md → Add a composer attachment source; `plugin-examples/linear` | -| Theme | `addTheme` | A light or dark palette under Settings → Appearance | reference.md → Contribute a theme; `plugin-examples/catppuccin` | -| Plugin RPC | `defineRpc` + `server.handle` + `useRpc` | Daemon-side work that is not a normal Paseo operation: vendor APIs, credentials, local files | reference.md → Add plugin-specific backend behavior | -| Lifecycle events | `server.on` | Observe agent/workspace lifecycle, inspect ended turns, and answer permission requests | [Lifecycle hooks](https://paseo.sh/docs/plugins/reference.md#lifecycle-hooks) | -| Creation and launch hooks | `server.before` | Change agent config, provider options, MCP servers, environment, or workspace isolation before the operation | [Before hooks](https://paseo.sh/docs/plugins/reference.md#before-hooks) | -| Paseo SDK | `usePaseo()` / handler `{ paseo }` | Normal Paseo operations: workspaces, agents, providers, config | reference.md → Use the Paseo SDK | +| Contribution | Registration | Use it when | Reference | +| ------------------------- | ----------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | +| Screen and sidebar item | `addScreen` + `addSidebarHeaderItem`/`addSidebarFooterItem` | A full screen of plugin UI, or sidebar header or footer rows that open a screen or popover | reference.md → Screens and sidebar items | +| Workspace panel | `addWorkspacePanel` | UI that lives as a tab beside agents, terminals, files, and diffs; `locations: ["explorer"]` for the Explorer | reference.md → Workspace panels | +| File panel | `addFilePanel` | View or edit a matching file inside the file tab through its file handle | reference.md → File panels; `plugin-examples/pdf-panel`, `plugin-examples/markdown-panel` | +| Command Center item | `addCommandCenterItem` | A global, workspace, or agent action reachable from ⌘K | reference.md → Command Center items | +| Client slash command | `addSlashCommand` | A `/command args` in the composer that runs plugin code instead of prompting the agent | reference.md → Slash commands | +| Composer pill | `addComposerPill` | A per-agent button in the composer track bar next to Tasks and Subagents | reference.md → Composer pills | +| Timeline transformer | `addTimelineTransformer` + `addTimelineRenderer` | Replace, explode, or hide a built-in timeline item, including while it streams | reference.md → Timeline items; `plugin-examples/timeline-items`, `plugin-examples/inline-thinking` | +| Timeline row | `paseo.agents.ref(id).timeline.append(...)` | Push a plugin-owned row into an agent timeline from a server handler and update it later | reference.md → Append a timeline row from the daemon | +| Attachment source | `client.addAttachmentSource` + `server.handle` | Let the user attach a searchable external resource, such as an issue, to a prompt | reference.md → Add a composer attachment source; `plugin-examples/linear` | +| Theme | `addTheme` | A light or dark palette under Settings → Appearance | reference.md → Contribute a theme; `plugin-examples/catppuccin` | +| Plugin RPC | `defineRpc` + `server.handle` + `useRpc` | Daemon-side work that is not a normal Paseo operation: vendor APIs, credentials, local files | reference.md → Add plugin-specific backend behavior | +| Lifecycle events | `server.on` | Observe agent/workspace lifecycle, inspect ended turns, and answer permission requests | [Lifecycle hooks](https://paseo.sh/docs/plugins/reference.md#lifecycle-hooks) | +| Creation and launch hooks | `server.before` | `agent.create` edits saved config; `agent.session_open` contributes launch-only `env`, `tools`, `mcpServers` on every open; `workspace.create` chooses isolation | [Before hooks](https://paseo.sh/docs/plugins/reference.md#before-hooks) | +| Paseo SDK | `usePaseo()` / handler `{ paseo }` | Normal Paseo operations: workspaces, agents, providers, config | reference.md → Use the Paseo SDK | -| Lifecycle task | Example | -| ------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ | -| Log all eleven hooks | [lifecycle-logger](https://github.com/getpaseo/paseo/tree/main/plugin-examples/lifecycle-logger) | -| Follow-ups, permissions, environment, provider switching, worktrees | [lifecycle-actions](https://github.com/getpaseo/paseo/tree/main/plugin-examples/lifecycle-actions) | -| Inject MCP servers and change Codex sandbox/approval options | [agent-configuration](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-configuration) | +| Lifecycle task | Example | +| ---------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ | +| Log all eleven hooks | [lifecycle-logger](https://github.com/getpaseo/paseo/tree/main/plugin-examples/lifecycle-logger) | +| Follow-ups, permissions, environment, provider switching, worktrees | [lifecycle-actions](https://github.com/getpaseo/paseo/tree/main/plugin-examples/lifecycle-actions) | +| Inject launch-only MCP servers and save Codex sandbox/approval options | [agent-configuration](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-configuration) | +| Attach a tool to selected agents | [agent-tools](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-tools) | ## Create the project @@ -377,6 +378,35 @@ Inputs and outputs are validated on both sides. Backend handlers receive the sam Use TanStack Query for async request state, caching, and mutations. +### Contribute tools and MCP servers at session open + +Use `before("agent.session_open")` for per-agent tools and plugin-owned MCP servers. Add this +callback inside `contribute(server)`: + +```ts +server.before("agent.session_open", ({ request }) => { + if (request.provider !== "codex") return; + return { + ...request, + mcpServers: { + ...request.mcpServers, + company: { type: "http", url: "https://tools.example.com/mcp" }, + }, + }; +}); +``` + +`tools` and `mcpServers` start empty for each plugin and accumulate across its own callbacks. +They are launch-only. Use `agent.create` to edit configuration that should be saved with the agent. +See [Attach tools to agents](https://paseo.sh/docs/plugins/reference.md#attach-tools-to-agents) +for `defineAgentTool` and targeting, and +[Inject MCP servers](https://paseo.sh/docs/plugins/reference.md#inject-mcp-servers) for server configuration and collisions. + +Starting, stopping, or reloading a plugin with a session-open hook marks open agent sessions stale. +Each reopens before its next idle prompt without interrupting a running turn. +`await paseo.agents.ref(id).reload()` applies changes immediately and interrupts a running turn; +`refresh()` only reads the current snapshot. + ### Debug daemon-side behavior Backend contributions can use normal Node logging. `console.log()` writes to the plugin's stdout;