mirror of
https://github.com/getpaseo/paseo.git
synced 2026-10-19 07:42:52 +00:00
Compare commits
41
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
22488d4502 | ||
|
|
2a5264c188 | ||
|
|
8ddeb79c8d | ||
|
|
c90587e5b7 | ||
|
|
56f4fca9e4 | ||
|
|
28f7528588 | ||
|
|
f13bb2136c | ||
|
|
2323ee6844 | ||
|
|
1e00f452ea | ||
|
|
a162e1075f | ||
|
|
8f1091da64 | ||
|
|
4dd0e50e78 | ||
|
|
dc785bb29a | ||
|
|
93bfb34e21 | ||
|
|
2d85fe4e04 | ||
|
|
1463396ebc | ||
|
|
d4ea77b910 | ||
|
|
f715221de8 | ||
|
|
aedba5ec27 | ||
|
|
bdc58fb07c | ||
|
|
3f1a04304d | ||
|
|
50cf244e86 | ||
|
|
aaeefdc00b | ||
|
|
c5deaa0516 | ||
|
|
72c180aaf7 | ||
|
|
66b2567be3 | ||
|
|
cb2b569bbd | ||
|
|
2ecf3ba783 | ||
|
|
4515061f88 | ||
|
|
3c478e5967 | ||
|
|
05637a7f05 | ||
|
|
13d21f60f1 | ||
|
|
fc3b2c4eb7 | ||
|
|
a9fef4879a | ||
|
|
a292b402cf | ||
|
|
64c9f263e8 | ||
|
|
48059aeae3 | ||
|
|
7fd469ae19 | ||
|
|
56d5680742 | ||
|
|
06bde1e57a | ||
|
|
396a2bc0b2 |
+28
-5
@@ -1,12 +1,12 @@
|
||||
# Changelog
|
||||
|
||||
## 0.11.0-beta.5 - 2026-10-06
|
||||
## 0.11.0 - 2026-10-07
|
||||
|
||||
### Added
|
||||
|
||||
- Added Muse Code as a provider, with model, approval mode, and reasoning effort controls ([#5719](https://github.com/getpaseo/paseo/pull/5719), [#5775](https://github.com/getpaseo/paseo/pull/5775) by [@millerben95](https://github.com/millerben95))
|
||||
- Added Antigravity as a provider that drives the installed `agy` CLI, always in Full access ([#5714](https://github.com/getpaseo/paseo/pull/5714), [#5795](https://github.com/getpaseo/paseo/pull/5795))
|
||||
- Added a Usage screen, opened from the sidebar footer, showing each subscription account's quota windows with Refresh ([#5465](https://github.com/getpaseo/paseo/pull/5465), [#5685](https://github.com/getpaseo/paseo/pull/5685), [#5786](https://github.com/getpaseo/paseo/pull/5786), [#5805](https://github.com/getpaseo/paseo/pull/5805), [#5921](https://github.com/getpaseo/paseo/pull/5921))
|
||||
- Added Usage, opened from the sidebar footer as a dialog on desktop and a sheet on mobile, showing each subscription account's quota windows with Refresh ([#5465](https://github.com/getpaseo/paseo/pull/5465), [#5685](https://github.com/getpaseo/paseo/pull/5685), [#5786](https://github.com/getpaseo/paseo/pull/5786), [#5805](https://github.com/getpaseo/paseo/pull/5805), [#5921](https://github.com/getpaseo/paseo/pull/5921), [#6216](https://github.com/getpaseo/paseo/pull/6216))
|
||||
- Added an opt-in Usage summary to the sidebar footer that shows the windows you pin ([#5903](https://github.com/getpaseo/paseo/pull/5903), [#5975](https://github.com/getpaseo/paseo/pull/5975), [#6089](https://github.com/getpaseo/paseo/pull/6089))
|
||||
- Added Usage discovery of ChatGPT logins from Codex CLI, OpenCode, Pi, and OMP ([#5844](https://github.com/getpaseo/paseo/pull/5844))
|
||||
- Added Usage discovery of Claude logins from the Claude Code credential file, the macOS keychain, Pi, and OMP ([#5844](https://github.com/getpaseo/paseo/pull/5844))
|
||||
@@ -16,9 +16,12 @@
|
||||
- Added Fast mode and an Auto thinking level to OMP ([#5550](https://github.com/getpaseo/paseo/pull/5550) by [@n24q02m](https://github.com/n24q02m), [@abhi-wan-kenobi](https://github.com/abhi-wan-kenobi))
|
||||
- Added MCP servers to OMP schedules and Hub runs ([#5550](https://github.com/getpaseo/paseo/pull/5550) by [@omercnet](https://github.com/omercnet))
|
||||
- Added a Content width setting for the maximum width of chat and Markdown files on wide screens ([#5680](https://github.com/getpaseo/paseo/pull/5680))
|
||||
- Added syntax highlighting for Vue files ([#6205](https://github.com/getpaseo/paseo/pull/6205) by [@Davnn1](https://github.com/Davnn1))
|
||||
- Added `agents.providers.<id>.options` in `config.json` as default options for every provider, with per-agent overrides ([#5780](https://github.com/getpaseo/paseo/pull/5780))
|
||||
- Added the terminal key bar and Paste to terminal panes on iPad and Android tablets ([#5712](https://github.com/getpaseo/paseo/pull/5712) by [@lardissone](https://github.com/lardissone))
|
||||
- Added screens and sidebar header and footer items to the plugin SDK ([#5685](https://github.com/getpaseo/paseo/pull/5685))
|
||||
- Added a display name, icon, screenshots, and videos to the plugin manifest ([#6263](https://github.com/getpaseo/paseo/pull/6263))
|
||||
- Added an `OVERVIEW.md` template to `paseo plugin init` for plugin registry listings ([#6226](https://github.com/getpaseo/paseo/pull/6226))
|
||||
- Added usage sources to the plugin SDK ([#5465](https://github.com/getpaseo/paseo/pull/5465), [#5876](https://github.com/getpaseo/paseo/pull/5876))
|
||||
- Added `spawnProcess()`, `execCommand()`, and `terminateProcess()` to the plugin SDK for launching CLIs, including Windows `.cmd` and `.bat` scripts ([#6151](https://github.com/getpaseo/paseo/pull/6151))
|
||||
- Added `client.playAudio()` to the plugin SDK for playing audio on every client ([#5976](https://github.com/getpaseo/paseo/pull/5976))
|
||||
@@ -27,8 +30,9 @@
|
||||
|
||||
### Changed
|
||||
|
||||
- Changed `paseo plugin add owner/slug` to install the reviewed plugin from the plugin registry, so local directories need a path such as `./slug` and direct GitHub installs need `github:owner/repo` ([#6224](https://github.com/getpaseo/paseo/pull/6224))
|
||||
- Changed the context window details to show usage for the account the agent runs under, including custom `CLAUDE_CONFIG_DIR` and `CODEX_HOME` homes ([#5465](https://github.com/getpaseo/paseo/pull/5465))
|
||||
- Changed the context window details on desktop to a hover card with Refresh ([#5975](https://github.com/getpaseo/paseo/pull/5975))
|
||||
- Changed the context window details on desktop to a hover card with Refresh ([#5975](https://github.com/getpaseo/paseo/pull/5975), [#6185](https://github.com/getpaseo/paseo/pull/6185))
|
||||
- Changed the context window meter to show before an agent's first turn ([#6089](https://github.com/getpaseo/paseo/pull/6089))
|
||||
- Changed Codex Fast to a Speed menu listing the Normal, Fast, and Ultrafast speeds each model offers, shown as a lightning bolt on desktop that turns yellow while Fast or Ultrafast is selected ([#5708](https://github.com/getpaseo/paseo/pull/5708), [#6152](https://github.com/getpaseo/paseo/pull/6152) by [@Nurshot](https://github.com/Nurshot))
|
||||
- Changed Explorer tabs to work like workspace tabs, with a + menu, drag and drop, and Close for Files and Changes ([#5942](https://github.com/getpaseo/paseo/pull/5942))
|
||||
@@ -44,12 +48,18 @@
|
||||
### Fixed
|
||||
|
||||
- Fixed Claude agents never showing Thought rows on Claude Opus 4.7 and later ([#4355](https://github.com/getpaseo/paseo/pull/4355) by [@ThePharmer](https://github.com/ThePharmer))
|
||||
- Fixed a background Claude subagent's card showing as a bare "Task" that stayed running, or as "Agent" after a daemon restart ([#6067](https://github.com/getpaseo/paseo/pull/6067), [#6100](https://github.com/getpaseo/paseo/pull/6100))
|
||||
- Fixed a Claude agent showing as running while only its background helpers worked, and a send or Stop killing those helpers ([#6295](https://github.com/getpaseo/paseo/pull/6295) by [@IsakPersson](https://github.com/IsakPersson))
|
||||
- Fixed a Claude agent in Auto mode failing to switch modes when Claude Code uses Bedrock or Vertex ([#6272](https://github.com/getpaseo/paseo/pull/6272))
|
||||
- Fixed a Claude subagent's auto-mode report showing as a raw SubagentHandback tool card instead of markdown ([#6248](https://github.com/getpaseo/paseo/pull/6248))
|
||||
- Fixed background Claude subagent cards showing as a bare "Task" that stayed running, as "Agent" after a daemon restart, or unlabeled when two launch together ([#6067](https://github.com/getpaseo/paseo/pull/6067), [#6100](https://github.com/getpaseo/paseo/pull/6100), [#6268](https://github.com/getpaseo/paseo/pull/6268))
|
||||
- Fixed Claude Code terminals not showing as needing input when Claude is idle ([#6022](https://github.com/getpaseo/paseo/pull/6022))
|
||||
- Fixed Claude usage calling a rate-limited login again before its retry time ([#6089](https://github.com/getpaseo/paseo/pull/6089))
|
||||
- Fixed a Claude agent that entered plan mode on its own still showing and storing its previous mode ([#6074](https://github.com/getpaseo/paseo/pull/6074))
|
||||
- Fixed a resumed agent returning to its creation-time mode after its mode was changed in the session ([#5140](https://github.com/getpaseo/paseo/pull/5140) by [@ThePlenkov](https://github.com/ThePlenkov))
|
||||
- Fixed ACP plugin providers failing to launch a `.cmd` or `.bat` CLI on Windows ([#6151](https://github.com/getpaseo/paseo/pull/6151))
|
||||
- Fixed ACP agents running on their default model when the configured model is one the agent does not advertise ([#6273](https://github.com/getpaseo/paseo/pull/6273))
|
||||
- Fixed archiving an ACP agent leaving its provider running when the provider never answers close ([#6213](https://github.com/getpaseo/paseo/pull/6213) by [@apple-ouyang](https://github.com/apple-ouyang))
|
||||
- Fixed an archived ACP agent showing an empty chat after its worktree was removed ([#6228](https://github.com/getpaseo/paseo/pull/6228))
|
||||
- Fixed ACP agents rejecting every following message after a turn failed with a permission request open ([#6045](https://github.com/getpaseo/paseo/pull/6045))
|
||||
- Fixed the context window meter never appearing for ACP agents that report context usage ([#4848](https://github.com/getpaseo/paseo/pull/4848) by [@apple-ouyang](https://github.com/apple-ouyang))
|
||||
- Fixed schedule runs and workspace metadata recording `[object Object]` when an ACP agent rejects a session setting ([#5765](https://github.com/getpaseo/paseo/pull/5765))
|
||||
@@ -64,12 +74,14 @@
|
||||
- Fixed opening an archived OMP agent starting an `omp` process that stayed running ([#5550](https://github.com/getpaseo/paseo/pull/5550) by [@thomasvan](https://github.com/thomasvan))
|
||||
- Fixed an OMP turn staying running forever when the run contains a message Paseo does not show, such as an OMP rule reminder ([#6112](https://github.com/getpaseo/paseo/pull/6112))
|
||||
- Fixed a prompt OMP rejects, such as for a missing API key, ending as a completed turn with no error ([#6110](https://github.com/getpaseo/paseo/pull/6110), [#6115](https://github.com/getpaseo/paseo/pull/6115))
|
||||
- Fixed reopened OMP chats showing "Custom message" rows for compactions and other entries OMP writes on its own ([#6198](https://github.com/getpaseo/paseo/pull/6198), [#6215](https://github.com/getpaseo/paseo/pull/6215))
|
||||
- Fixed Pi and OMP sessions whose model was removed failing to import or reopen ([#6061](https://github.com/getpaseo/paseo/pull/6061))
|
||||
- Fixed Pi agents on Pi 0.99 starting without Paseo's MCP servers when `pi-mcp-adapter` is not installed ([#5762](https://github.com/getpaseo/paseo/pull/5762) by [@ArietidsZ](https://github.com/ArietidsZ))
|
||||
- Fixed a running Pi subagent showing an empty transcript until it finished ([#5755](https://github.com/getpaseo/paseo/pull/5755))
|
||||
- Fixed a grouped Tintinweb pi-subagents completion marking only its first agent completed and leaving the rest on working ([#5826](https://github.com/getpaseo/paseo/pull/5826))
|
||||
- Fixed OpenCode `ask` rules for `paseo_*` tools running the tool without a prompt ([#5801](https://github.com/getpaseo/paseo/pull/5801) by [@ymarcus93](https://github.com/ymarcus93))
|
||||
- Fixed the first OpenCode prompt waiting for the event stream timeout when the OpenCode server was slow to become ready ([#5873](https://github.com/getpaseo/paseo/pull/5873) by [@axsuul](https://github.com/axsuul))
|
||||
- Fixed OpenCode v2 agents staying running after a question is dismissed or a tool permission is denied ([#6177](https://github.com/getpaseo/paseo/pull/6177), [#6188](https://github.com/getpaseo/paseo/pull/6188))
|
||||
- Fixed the Nix packages failing to start the daemon and to open terminals ([#5523](https://github.com/getpaseo/paseo/pull/5523) by [@wongcallum](https://github.com/wongcallum))
|
||||
- Fixed OpenCode v2 agents failing to start on the Nix packages ([#5988](https://github.com/getpaseo/paseo/pull/5988))
|
||||
- Fixed each Paseo skill appearing twice in Codex's skill list ([#5827](https://github.com/getpaseo/paseo/pull/5827) by [@3ae3ae](https://github.com/3ae3ae))
|
||||
@@ -83,12 +95,18 @@
|
||||
- Fixed Codex terminal rows reading only "Terminal" without the command on current Codex ([#5774](https://github.com/getpaseo/paseo/pull/5774))
|
||||
- Fixed the composer showing the catalog default thinking level instead of the one the agent runs on ([#5804](https://github.com/getpaseo/paseo/pull/5804))
|
||||
- Fixed the composer showing another model's label when the agent's model is missing from the loaded catalog ([#5796](https://github.com/getpaseo/paseo/pull/5796))
|
||||
- Fixed the chat jumping back by several screens when scrolling up through older history on web and desktop ([#5945](https://github.com/getpaseo/paseo/pull/5945), [#5970](https://github.com/getpaseo/paseo/pull/5970))
|
||||
- Fixed the chat jumping back by several screens when scrolling up through older history on web and desktop ([#5945](https://github.com/getpaseo/paseo/pull/5945), [#5970](https://github.com/getpaseo/paseo/pull/5970), [#6172](https://github.com/getpaseo/paseo/pull/6172))
|
||||
- Fixed images in chat shifting the text below them when they finish loading ([#5970](https://github.com/getpaseo/paseo/pull/5970))
|
||||
- Fixed copying all the code in a chat code block sometimes including its ``` fence lines ([#6138](https://github.com/getpaseo/paseo/pull/6138))
|
||||
- Fixed copying across a code block nested in a numbered list item renumbering the next item ([#6158](https://github.com/getpaseo/paseo/pull/6158))
|
||||
- Fixed copying a chat selection across an image losing its alt text and source, or including the image when the selection started below it ([#6181](https://github.com/getpaseo/paseo/pull/6181), [#6195](https://github.com/getpaseo/paseo/pull/6195))
|
||||
- Fixed relative `path:line` file links in chat opening at the first line referenced for that file ([#5653](https://github.com/getpaseo/paseo/pull/5653) by [@3ae3ae](https://github.com/3ae3ae))
|
||||
- Fixed PR comments with linked pictures showing raw HTML tags and losing the image link ([#5968](https://github.com/getpaseo/paseo/pull/5968))
|
||||
- Fixed text typed by the browser tool appearing in your message box instead of the browser tab ([#6207](https://github.com/getpaseo/paseo/pull/6207))
|
||||
- Fixed Astro expressions losing their colors after a nested template string ([#6219](https://github.com/getpaseo/paseo/pull/6219))
|
||||
- Fixed downloading files whose names contain non-ASCII characters ([#6278](https://github.com/getpaseo/paseo/pull/6278), [#6281](https://github.com/getpaseo/paseo/pull/6281) by [@dillonzq](https://github.com/dillonzq), [@jasonhnd](https://github.com/jasonhnd))
|
||||
- Fixed the PR panel, sidebar workspace status, and "Worked for" line showing English in other app languages ([#6196](https://github.com/getpaseo/paseo/pull/6196), [#6208](https://github.com/getpaseo/paseo/pull/6208), [#6225](https://github.com/getpaseo/paseo/pull/6225) by [@dillonzq](https://github.com/dillonzq))
|
||||
- Fixed French translations that read as word-for-word machine translation ([#6004](https://github.com/getpaseo/paseo/pull/6004) by [@fxlelouarn](https://github.com/fxlelouarn))
|
||||
- Fixed the desktop window not dragging from the workspace header after scrolling a long chat ([#5233](https://github.com/getpaseo/paseo/pull/5233) by [@Zhou-Ruichen](https://github.com/Zhou-Ruichen))
|
||||
- Fixed opening an agent on a touch screen in the desktop layout raising the on-screen keyboard ([#5477](https://github.com/getpaseo/paseo/pull/5477) by [@dinhphieu](https://github.com/dinhphieu))
|
||||
- Fixed Option+arrow, Cmd+arrow, and Cmd+Backspace line editing in the macOS terminal ([#3339](https://github.com/getpaseo/paseo/pull/3339) by [@gpambrozio](https://github.com/gpambrozio))
|
||||
@@ -96,12 +114,16 @@
|
||||
- Fixed a new worktree workspace being archived when its `paseo.json` cannot be parsed ([#6036](https://github.com/getpaseo/paseo/pull/6036) by [@3ae3ae](https://github.com/3ae3ae))
|
||||
- Fixed workspace script status not updating in other connected clients ([#6007](https://github.com/getpaseo/paseo/pull/6007) by [@swbiggart](https://github.com/swbiggart))
|
||||
- Fixed agents and terminals inheriting the voice library path, which truncated Git Bash's PATH on Windows ([#5987](https://github.com/getpaseo/paseo/pull/5987) by [@hanh9898](https://github.com/hanh9898))
|
||||
- Fixed dictation failing until the model was deleted by hand when the daemon stopped while extracting a local speech model ([#6210](https://github.com/getpaseo/paseo/pull/6210) by [@3ae3ae](https://github.com/3ae3ae))
|
||||
- Fixed macOS hosts showing as `UNKNOWN` when the network supplies no hostname ([#5922](https://github.com/getpaseo/paseo/pull/5922))
|
||||
- Fixed `paseo daemon status` reporting a daemon in a Linux VM as stopped after the host wakes from sleep ([#6279](https://github.com/getpaseo/paseo/pull/6279))
|
||||
- Fixed relay reconnects being ignored after a relay connection stalled before its handshake ([#5648](https://github.com/getpaseo/paseo/pull/5648) by [@3ae3ae](https://github.com/3ae3ae))
|
||||
- Fixed `paseo daemon run` exiting with "Daemon failed to start" when the program that launched it stops reading its output ([#6117](https://github.com/getpaseo/paseo/pull/6117))
|
||||
- Fixed CLI commands crashing with `EPIPE`, and the Windows desktop app showing an error dialog, when their output stops being read ([#6097](https://github.com/getpaseo/paseo/pull/6097))
|
||||
- Fixed daemon self-update on a linked global install giving the wrong reason for refusing ([#6095](https://github.com/getpaseo/paseo/pull/6095))
|
||||
- Fixed daemon self-update failing for an npm install under a prefix other than npm's global prefix ([#5649](https://github.com/getpaseo/paseo/pull/5649) by [@3ae3ae](https://github.com/3ae3ae))
|
||||
- Fixed opening an archived agent whose worktree was removed showing "Workspace unavailable" when the workspace had no recorded branch ([#5694](https://github.com/getpaseo/paseo/pull/5694))
|
||||
- Fixed a failed send to an archived agent whose directory was removed taking it out of History ([#6255](https://github.com/getpaseo/paseo/pull/6255))
|
||||
- Fixed a host's version staying stale on the host page after its daemon restarts ([#5351](https://github.com/getpaseo/paseo/pull/5351) by [@bashrusakh](https://github.com/bashrusakh))
|
||||
- Fixed Remote SSH hosts failing to connect to a password-protected daemon, with a new Daemon password field ([#6081](https://github.com/getpaseo/paseo/pull/6081) by [@royenheart](https://github.com/royenheart))
|
||||
- Fixed removing a host during its first connection attempt not stopping the connection ([#5722](https://github.com/getpaseo/paseo/pull/5722))
|
||||
@@ -121,6 +143,7 @@
|
||||
- Fixed `paseo schedule update --no-max-runs` and `--no-expires-in` failing before reaching the daemon ([#5973](https://github.com/getpaseo/paseo/pull/5973) by [@Mar-garet](https://github.com/Mar-garet))
|
||||
- Fixed `daemon.log` saying nothing when a resumed Claude agent's transcript is missing or cannot be read ([#5818](https://github.com/getpaseo/paseo/pull/5818) by [@gabrielgiordan](https://github.com/gabrielgiordan))
|
||||
- Fixed reloading a plugin adding `[System Error] Provider connection closed` to finished chats on its provider ([#5579](https://github.com/getpaseo/paseo/pull/5579))
|
||||
- Fixed `paseo plugin add .` looking for the plugin in the daemon's directory instead of the CLI's ([#6239](https://github.com/getpaseo/paseo/pull/6239))
|
||||
- Fixed plugin settings screens on desktop having no way back to the Plugins page ([#5620](https://github.com/getpaseo/paseo/pull/5620))
|
||||
- Fixed plugin client code failing to import npm packages that declare only `main` or `module` ([#5838](https://github.com/getpaseo/paseo/pull/5838))
|
||||
- Fixed the SDK's `send()` and `run()` rejecting `activeTurnBehavior` in TypeScript ([#5605](https://github.com/getpaseo/paseo/pull/5605) by [@wjxdy](https://github.com/wjxdy))
|
||||
|
||||
@@ -39,21 +39,33 @@
|
||||
<img src="https://paseo.sh/mobile-mockup.png" alt="Paseo mobile app" width="100%">
|
||||
</p>
|
||||
|
||||
Run agents in parallel on your own machines. Ship from your phone or your desk.
|
||||
Paseo is a desktop, mobile, web, and CLI app for coding agents. Open the desktop app and work: agents, editor, terminals, diffs, pull requests, and a browser in one window. Run many agents at once, each in its own worktree, on one machine or several. The mobile app is the full app, native on iOS and Android.
|
||||
|
||||
- **Parallel agents:** Run many agents at once, each in its own worktree.
|
||||
- **Built-in orchestration:** Agents in Paseo can create worktrees, launch other agents, and talk to them, across providers.
|
||||
- **Full IDE:** Edit files, review diffs, open pull requests, and run terminals, in split panes you arrange how you want.
|
||||
- **Self-hosted:** Agents run on your machine with your full dev environment. Use your tools, your configs, and your skills.
|
||||
- **Multi-provider:** Claude Code, Codex, Copilot, OpenCode, Pi, Antigravity, and Muse Code through the same interface. Pick the right model for each job.
|
||||
- **Voice control:** Dictate tasks or talk through problems in voice mode. Hands-free when you need it.
|
||||
- **Cross-device:** iOS, Android, desktop, web, and CLI. Start work at your desk, check in from your phone, script it from the terminal.
|
||||
- **Privacy-first:** Paseo doesn't have any telemetry, tracking, or forced log-ins.
|
||||
|
||||
[Run parallel tasks in Paseo](https://paseo.sh/docs/parallel-development): start agents in separate worktrees, review their diffs, run each app, and check it in the built-in browser.
|
||||
|
||||
## Plugins
|
||||
|
||||
Add themes, workspace panels, commands, settings screens, and coding-agent providers with trusted
|
||||
TypeScript plugins. Install from npm, Git, or a local directory with `paseo plugin install <source>`.
|
||||
Plugins run on the daemon and show up in every client you connect, with the same UI on desktop, web,
|
||||
iOS, and Android. Write a plugin once and it is on your phone.
|
||||
|
||||
Start with the [plugin quickstart](https://paseo.sh/docs/plugins). Plugins run with access to your daemon
|
||||
machine and inside connected clients; install only code you trust.
|
||||
- **UI:** screens, sidebar items, workspace panels, Command Center items, slash commands, composer pills, attachment sources, timeline items, themes.
|
||||
- **Agent lifecycle:** change configuration, environment, and MCP servers, answer permissions, follow up when a turn ends.
|
||||
- **Providers:** add a coding agent as a provider.
|
||||
|
||||
Install from the registry with `paseo plugin add owner/slug`, or from Git or a local directory.
|
||||
|
||||
**[Browse plugins](https://paseo.sh/plugins)** · **[Plugin docs](https://paseo.sh/docs/plugins)**
|
||||
|
||||
Plugins run with access to your daemon machine and inside connected clients; install only code you trust.
|
||||
|
||||
## Getting Started
|
||||
|
||||
@@ -77,16 +89,16 @@ Download it from [paseo.sh/download](https://paseo.sh/download) or the [GitHub r
|
||||
|
||||
To connect from your phone, open **Settings → your host → Pair Device**.
|
||||
|
||||
### CLI / headless
|
||||
### Server
|
||||
|
||||
Install the CLI and start Paseo:
|
||||
For a server, a VM, or any machine without the desktop app. Install the CLI and start the daemon:
|
||||
|
||||
```bash
|
||||
npm install -g @getpaseo/cli
|
||||
paseo
|
||||
```
|
||||
|
||||
Paseo starts locally, then asks whether to enable the end-to-end encrypted relay for device pairing. If you decline, connect directly over TCP, Tailscale, or another VPN. This path is useful for servers and remote machines.
|
||||
Paseo starts, then asks whether to enable the end-to-end encrypted relay for device pairing. If you decline, connect directly over TCP, Tailscale, or another VPN. The desktop, mobile, and web apps connect to this daemon like any other host.
|
||||
|
||||
For full setup and configuration, see:
|
||||
|
||||
@@ -197,7 +209,7 @@ npm run typecheck
|
||||
|
||||
## Sponsors
|
||||
|
||||
Paseo is built by one person and funded by the people who use it. Support the work on [GitHub Sponsors](https://github.com/sponsors/boudra). Companies can [sponsor Paseo](https://paseo.sh/sponsor#spot) monthly and have their logo shown here and on the paseo.sh homepage.
|
||||
Paseo is an independent project used by tens of thousands of developers daily, built by one person and funded by the people who use it. Support the work on [GitHub Sponsors](https://github.com/sponsors/boudra). Companies can [sponsor Paseo](https://paseo.sh/sponsor#spot) monthly and have their logo shown here and on the paseo.sh homepage.
|
||||
|
||||
<!-- Sponsor logos go here, in the same order as packages/website/src/data/sponsors.ts -->
|
||||
|
||||
|
||||
@@ -197,10 +197,11 @@ Claude Code announces subagent lifecycle on the SDK stream (`task_started` / `ta
|
||||
|
||||
- **Not every announced task belongs in the track.** Task subagents announce as `local_agent` and workflows as `local_workflow`; a backgrounded shell announces as `local_bash` with the same `tool_use_id` shape, and ambient housekeeping sets `skip_transcript`. The Claude provider normalizes a workflow to a generic provider-subagent descriptor titled `Workflow`, using Claude's summary as its description and timeline opener. Shared storage, protocol, and UI do not distinguish it from another provider subagent.
|
||||
- **A task that was never declared gets no descriptor, by any route.** Filtered tasks still emit `task_notification`s carrying a `tool_use_id`, and still emit frames carrying `parent_tool_use_id`. Attributing either produces a descriptor with no identity and a defaulted `running` status — a nameless row that never finishes. Status, presentation updates, and sidechain frames all route through the declaration table.
|
||||
- **Task ids are session-scoped, not turn-scoped.** Cancelling a turn must not clear the routing table: a backgrounded child settles after the interrupt and needs its descriptor to still exist. Cancellation instead terminalizes the declared children that were running in the foreground, and a later `task_notification` is free to correct that guess. Backgrounded children are identified by `task_updated.patch.is_backgrounded`.
|
||||
- **Task ids are session-scoped, not turn-scoped.** Cancelling a turn must not clear the routing table: a backgrounded child settles after the interrupt and needs its descriptor to still exist. Cancellation instead terminalizes the declared children that were running in the foreground, and a later `task_notification` is free to correct that guess. Backgrounded children are identified by `is_backgrounded` on `task_started` (set at spawn; a resumed subagent is always background) or, when moved there later, on `task_updated.patch`.
|
||||
- **A resumed task can be announced again with a new `tool_use_id`.** The first Task tool id remains the canonical descriptor and later ids are routing aliases for the same session-scoped task. The resumed prompt is added to that child timeline.
|
||||
- **Effort is only reachable through hooks.** It appears nowhere on the message stream at any depth, and the level Paseo requests is not necessarily the level that runs — a model that does not support it is silently downgraded. A hook firing inside a subagent reports the active post-downgrade level next to its `agent_id`, which is the same id `task_started` calls `task_id`.
|
||||
- **Backgrounded subagents emit no frames carrying `parent_tool_use_id` at all.** Everything keyed off that field sees nothing for one; they are visible only because the task protocol announces them.
|
||||
- **Only `system/init` and `result` bracket a main-session turn.** Background subagents emit neither on the main stream, while their task frames, their own background jobs' `task_notification`, and `rate_limit_event` arrive with no `parent_tool_use_id`, the same shape as main-session work. `session_state_changed` stays `running` for as long as any background subagent lives (Claude Code 2.1.280), so it cannot open a turn; its `idle` can close one.
|
||||
- **Nested ownership comes from the launching sidechain, not `spawn_depth` alone.** A sidechain's Agent or Bash tool call records the direct owner of that `tool_use_id`; the following `task_started` inherits it. This routes a grandchild descriptor and child-owned background notifications without relying on labels or flattening them into the managed parent.
|
||||
- **On replay, `<session>/subagents/` holds every descendant beside the root.** Resolve the tree one proven generation at a time: the root transcript admits direct children, then each admitted sidechain transcript admits its children by `toolUseId`. `spawnDepth` orders candidates but does not establish ownership. Unresolved sidecars remain excluded as ambient or unrelated work.
|
||||
- **Replay `totalTokens` is a context-size reading, not cumulative spend.** Claude Code finalizes a subagent by summing the _last_ assistant message's usage block and shipping that as `usage.total_tokens`. Summing per-entry usage instead multiplies the cached prefix by the turn count and reports a number several times larger than the live path.
|
||||
|
||||
+17
-12
@@ -117,15 +117,19 @@ the bundled integration; an entry with `extends` shadows it with a custom provid
|
||||
|
||||
## Install from a registry
|
||||
|
||||
Registry installs are off by default. Set `pluginRegistryEnabled: true` in daemon config or
|
||||
`PASEO_PLUGIN_REGISTRY_ENABLED=1`, then restart the daemon. While they are off, bare
|
||||
`owner/repo` is GitHub shorthand and the daemon never contacts a registry.
|
||||
|
||||
With registry installs on, `paseo plugin install owner/slug` installs the registry's reviewed
|
||||
artifact, and GitHub shorthand requires `github:`. Registry installs
|
||||
`paseo plugin add owner/slug` installs the registry's reviewed artifact by default.
|
||||
Browse published plugins at [paseo.sh/plugins](https://paseo.sh/plugins).
|
||||
Use `git:owner/repository` or a full Git URL for a Git source. Registry installs
|
||||
keep the registry URL and ID, so update checks use its approved pin. Explicit version/ref
|
||||
selection is unavailable for registry installs; install an explicit source to select your own.
|
||||
|
||||
Registry overviews are untrusted author content, even before installation. Render them with
|
||||
`@getpaseo/protocol/plugin-overview`: no raw HTML, HTTPS-only links and images, no relative
|
||||
URLs, and isolated external links. The website adapter and corpus tests live in
|
||||
`packages/website/src/plugins/overview.tsx` and `overview.test.tsx`; the reusable corpus is
|
||||
`packages/protocol/tests/fixtures/plugin-overview.json`. A future app overview must share
|
||||
this policy. Installed-plugin descriptions in the app remain plain text.
|
||||
|
||||
Use `host/owner/slug` for a registry at `https://host`, or set
|
||||
`PASEO_PLUGIN_REGISTRY` to change the default base (including a path prefix).
|
||||
Private registry credentials live in daemon config under
|
||||
@@ -138,13 +142,13 @@ owns static hosting, record shapes, pins, and advisory install counts.
|
||||
|
||||
## Install a Git source
|
||||
|
||||
GitHub repositories use `owner/repository` or `github:owner/repository`. Other hosts use a Git
|
||||
URL. An existing directory still wins over source resolution.
|
||||
GitHub repositories use `git:owner/repository` or `github:owner/repository`. Other hosts use a Git
|
||||
URL.
|
||||
|
||||
```bash
|
||||
paseo plugin install owner/repository
|
||||
paseo plugin install git:owner/repository
|
||||
paseo plugin install https://gitlab.com/group/repository.git
|
||||
paseo plugin install owner/monorepo:plugins/review
|
||||
paseo plugin install git:owner/monorepo:plugins/review
|
||||
paseo plugin install github:owner/repository --ref main
|
||||
```
|
||||
|
||||
@@ -155,8 +159,9 @@ and ask for approval. `ls` reports the installed commit without contacting the r
|
||||
## Managed source ownership
|
||||
|
||||
The [public source reference](../public-docs/plugins/reference.md#plugin-sources) owns identifier
|
||||
syntax and npm prerequisites; the [publishing guide](../public-docs/plugins/publishing.md) owns distribution. Both clients send the source unchanged
|
||||
through `installPluginSource`; only the daemon resolves host paths and acquires sources.
|
||||
syntax and npm prerequisites; the [publishing guide](../public-docs/plugins/publishing.md) owns distribution. The CLI resolves directory sources before
|
||||
calling `installPluginSource`; see the public source reference for CLI and app path semantics.
|
||||
Only the daemon reads plugin files and acquires sources.
|
||||
|
||||
`ManagedPluginSources` owns acquisition and offline source description. Config stores the active
|
||||
directory; sources.json stores managed kind and the Git acquisition remote. The remote is needed
|
||||
|
||||
+1
-1
@@ -103,7 +103,7 @@ OpenCode owns user message IDs. Do not pass Paseo-generated IDs to OpenCode prom
|
||||
|
||||
Active-turn steering is an optional `AgentSession.steerActiveTurn` operation. The manager owns admission against its exact foreground turn, canonical user-message creation, echo reconciliation, and falls back to the normal interrupt-and-replace path only when the adapter reports `unavailable`. An adapter error leaves the steer's fate ambiguous and must surface without an interrupt or retry. Codex calls `turn/steer` with the native expected turn and Paseo client user-message ID. Claude pushes an admitted steer into the exact active SDK query input; isolated control commands remain unavailable. OpenCode calls `session/prompt_async` with an OpenCode-generated message ID; the server queues the prompt while busy and the next LLM call in the same Paseo turn includes it. Pi sends its native `steer` RPC, which queues the message for delivery after the in-flight assistant turn's tool calls. Slash-command inputs report `unavailable` because pi rejects extension commands on the steer path, and echo identity is correlated by message text because pi's steer RPC takes no message ID. A missing session reports `unavailable` and uses the normal interrupt fallback.
|
||||
|
||||
A steering adapter also owes its interrupt: stopping a turn must discard the steers the provider has not read yet, or one of them resumes the turn the user just stopped. Codex clears pending input when it aborts a turn; Claude does not, so its adapter cancels the SDK messages it queued before calling `query.interrupt()`. Pi requires `clear_queue` before `abort`; older binaries without that RPC retain their native queue behavior until the pi compatibility floor reaches 0.84.4.
|
||||
A steering adapter also owes its interrupt: stopping a turn must discard the steers the provider has not read yet, or one of them resumes the turn the user just stopped. Codex clears pending input when it aborts a turn; Claude does not, so its adapter cancels the SDK messages it queued before calling `query.interrupt()`. It calls `query.interrupt()` only while a main-session turn is in flight (between `system/init` and that turn's `result`): with the main session idle, an interrupt reaches only background subagents and no result follows it, so the adapter withdraws its unstarted messages and stops there. The adapter also declares `perTaskStopAffordance`, because without it the CLI kills every background subagent on interrupt. Pi requires `clear_queue` before `abort`; older binaries without that RPC retain their native queue behavior until the pi compatibility floor reaches 0.84.4.
|
||||
|
||||
`SteerActiveTurnOptions.clearPendingPermissions` makes permission release part of the provider contract. A provider that accepts such a steer queues it first, denies permissions blocking its delivery, and stops once the steer is read. Steers without the flag leave permissions open. A denied plan remains in the timeline because the pending card was the only other copy of its text.
|
||||
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
Added
|
||||
- Added Muse Code as a provider, with model, approval mode, and reasoning effort controls
|
||||
- Added Antigravity as a provider that drives the installed agy CLI, always in Full access
|
||||
- Added Usage, opened from the sidebar footer as a dialog on desktop and a sheet on mobile, showing each subscription account's quota windows with Refresh
|
||||
- Added an opt-in Usage summary to the sidebar footer that shows the windows you pin
|
||||
|
||||
Full notes: https://paseo.sh/changelog
|
||||
@@ -0,0 +1,7 @@
|
||||
Added
|
||||
- Added Muse Code as a provider, with model, approval mode, and reasoning effort controls
|
||||
- Added Antigravity as a provider that drives the installed agy CLI, always in Full access
|
||||
- Added Usage, opened from the sidebar footer as a dialog on desktop and a sheet on mobile, showing each subscription account's quota windows with Refresh
|
||||
- Added an opt-in Usage summary to the sidebar footer that shows the windows you pin
|
||||
|
||||
Full notes: https://paseo.sh/changelog
|
||||
@@ -0,0 +1,7 @@
|
||||
Added
|
||||
- Added Muse Code as a provider, with model, approval mode, and reasoning effort controls
|
||||
- Added Antigravity as a provider that drives the installed agy CLI, always in Full access
|
||||
- Added Usage, opened from the sidebar footer as a dialog on desktop and a sheet on mobile, showing each subscription account's quota windows with Refresh
|
||||
- Added an opt-in Usage summary to the sidebar footer that shows the windows you pin
|
||||
|
||||
Full notes: https://paseo.sh/changelog
|
||||
@@ -0,0 +1,7 @@
|
||||
Added
|
||||
- Added Muse Code as a provider, with model, approval mode, and reasoning effort controls
|
||||
- Added Antigravity as a provider that drives the installed agy CLI, always in Full access
|
||||
- Added Usage, opened from the sidebar footer as a dialog on desktop and a sheet on mobile, showing each subscription account's quota windows with Refresh
|
||||
- Added an opt-in Usage summary to the sidebar footer that shows the windows you pin
|
||||
|
||||
Full notes: https://paseo.sh/changelog
|
||||
+1
-1
@@ -1 +1 @@
|
||||
sha256-mQOyGIvwVt45hldUnYuZTKJg4mLPm7d8jXXNlSQnExE=
|
||||
sha256-zL3+gbScK8eMkjQUtKDX4UJTXt4BMeqMSyeWB017MA4=
|
||||
|
||||
Generated
+29
-28
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "paseo",
|
||||
"version": "0.11.0-beta.5",
|
||||
"version": "0.11.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "paseo",
|
||||
"version": "0.11.0-beta.5",
|
||||
"version": "0.11.0",
|
||||
"hasInstallScript": true,
|
||||
"license": "Apache-2.0",
|
||||
"workspaces": [
|
||||
@@ -36413,7 +36413,7 @@
|
||||
},
|
||||
"packages/app": {
|
||||
"name": "@getpaseo/app",
|
||||
"version": "0.11.0-beta.5",
|
||||
"version": "0.11.0",
|
||||
"dependencies": {
|
||||
"@codemirror/commands": "6.10.4",
|
||||
"@codemirror/language": "6.12.4",
|
||||
@@ -37496,12 +37496,12 @@
|
||||
},
|
||||
"packages/cli": {
|
||||
"name": "@getpaseo/cli",
|
||||
"version": "0.11.0-beta.5",
|
||||
"version": "0.11.0",
|
||||
"dependencies": {
|
||||
"@clack/prompts": "^1.0.0",
|
||||
"@getpaseo/client": "0.11.0-beta.5",
|
||||
"@getpaseo/protocol": "0.11.0-beta.5",
|
||||
"@getpaseo/server": "0.11.0-beta.5",
|
||||
"@getpaseo/client": "0.11.0",
|
||||
"@getpaseo/protocol": "0.11.0",
|
||||
"@getpaseo/server": "0.11.0",
|
||||
"chalk": "^5.3.0",
|
||||
"commander": "^12.0.0",
|
||||
"mime-types": "^2.1.35",
|
||||
@@ -37748,10 +37748,10 @@
|
||||
},
|
||||
"packages/client": {
|
||||
"name": "@getpaseo/client",
|
||||
"version": "0.11.0-beta.5",
|
||||
"version": "0.11.0",
|
||||
"dependencies": {
|
||||
"@getpaseo/protocol": "0.11.0-beta.5",
|
||||
"@getpaseo/relay": "0.11.0-beta.5",
|
||||
"@getpaseo/protocol": "0.11.0",
|
||||
"@getpaseo/relay": "0.11.0",
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -37762,7 +37762,7 @@
|
||||
},
|
||||
"packages/desktop": {
|
||||
"name": "@getpaseo/desktop",
|
||||
"version": "0.11.0-beta.5",
|
||||
"version": "0.11.0",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@getpaseo/cli": "*",
|
||||
@@ -38006,7 +38006,7 @@
|
||||
},
|
||||
"packages/expo-two-way-audio": {
|
||||
"name": "@getpaseo/expo-two-way-audio",
|
||||
"version": "0.11.0-beta.5",
|
||||
"version": "0.11.0",
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"@types/jest": "^29.5.14",
|
||||
@@ -38902,7 +38902,7 @@
|
||||
},
|
||||
"packages/highlight": {
|
||||
"name": "@getpaseo/highlight",
|
||||
"version": "0.11.0-beta.5",
|
||||
"version": "0.11.0",
|
||||
"dependencies": {
|
||||
"@codemirror/language": "6.12.4",
|
||||
"@codemirror/legacy-modes": "^6.5.3",
|
||||
@@ -38931,14 +38931,14 @@
|
||||
},
|
||||
"packages/plugin": {
|
||||
"name": "@getpaseo/plugin",
|
||||
"version": "0.11.0-beta.5",
|
||||
"version": "0.11.0",
|
||||
"dependencies": {
|
||||
"@agentclientprotocol/sdk": "^1.4.0",
|
||||
"use-sync-external-store": "^1.6.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@getpaseo/client": "0.11.0-beta.5",
|
||||
"@getpaseo/protocol": "0.11.0-beta.5",
|
||||
"@getpaseo/client": "0.11.0",
|
||||
"@getpaseo/protocol": "0.11.0",
|
||||
"@types/node": "^20.9.0",
|
||||
"@types/react": "~19.2.0",
|
||||
"react": "19.1.0",
|
||||
@@ -38948,8 +38948,8 @@
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@getpaseo/client": "0.11.0-beta.5",
|
||||
"@getpaseo/protocol": "0.11.0-beta.5",
|
||||
"@getpaseo/client": "0.11.0",
|
||||
"@getpaseo/protocol": "0.11.0",
|
||||
"react": "~19.1.0",
|
||||
"react-native": ">=0.81.5",
|
||||
"zod": "^4.4.3"
|
||||
@@ -38971,7 +38971,7 @@
|
||||
},
|
||||
"packages/protocol": {
|
||||
"name": "@getpaseo/protocol",
|
||||
"version": "0.11.0-beta.5",
|
||||
"version": "0.11.0",
|
||||
"dependencies": {
|
||||
"semver": "^7.8.5",
|
||||
"zod": "^4.4.3"
|
||||
@@ -38998,7 +38998,7 @@
|
||||
},
|
||||
"packages/relay": {
|
||||
"name": "@getpaseo/relay",
|
||||
"version": "0.11.0-beta.5",
|
||||
"version": "0.11.0",
|
||||
"dependencies": {
|
||||
"base64-js": "^1.5.1",
|
||||
"tweetnacl": "^1.0.3",
|
||||
@@ -39216,16 +39216,16 @@
|
||||
},
|
||||
"packages/server": {
|
||||
"name": "@getpaseo/server",
|
||||
"version": "0.11.0-beta.5",
|
||||
"version": "0.11.0",
|
||||
"dependencies": {
|
||||
"@agentclientprotocol/sdk": "^0.17.1",
|
||||
"@anthropic-ai/claude-agent-sdk": "0.3.246",
|
||||
"@anthropic-ai/sdk": "^0.104.2",
|
||||
"@getpaseo/client": "0.11.0-beta.5",
|
||||
"@getpaseo/highlight": "0.11.0-beta.5",
|
||||
"@getpaseo/plugin": "0.11.0-beta.5",
|
||||
"@getpaseo/protocol": "0.11.0-beta.5",
|
||||
"@getpaseo/relay": "0.11.0-beta.5",
|
||||
"@getpaseo/client": "0.11.0",
|
||||
"@getpaseo/highlight": "0.11.0",
|
||||
"@getpaseo/plugin": "0.11.0",
|
||||
"@getpaseo/protocol": "0.11.0",
|
||||
"@getpaseo/relay": "0.11.0",
|
||||
"@isaacs/ttlcache": "^2.1.4",
|
||||
"@modelcontextprotocol/sdk": "1.29.0",
|
||||
"@opencode-ai/sdk": "1.14.46",
|
||||
@@ -40146,7 +40146,7 @@
|
||||
},
|
||||
"packages/website": {
|
||||
"name": "@getpaseo/website",
|
||||
"version": "0.11.0-beta.5",
|
||||
"version": "0.11.0",
|
||||
"dependencies": {
|
||||
"@cloudflare/vite-plugin": "^1.29.1",
|
||||
"@cloudflare/workers-types": "^4.20260317.1",
|
||||
@@ -40174,6 +40174,7 @@
|
||||
"@types/react": "^19.1.6",
|
||||
"@types/react-dom": "^19.1.5",
|
||||
"@vitejs/plugin-react": "^4.5.1",
|
||||
"parse5": "^7.3.0",
|
||||
"typescript": "^5.9.3",
|
||||
"vite": "^7.3.3",
|
||||
"vite-tsconfig-paths": "^5.1.4",
|
||||
@@ -41753,7 +41754,7 @@
|
||||
},
|
||||
"plugins": {
|
||||
"name": "@getpaseo/builtin-plugins",
|
||||
"version": "0.11.0-beta.5",
|
||||
"version": "0.11.0",
|
||||
"dependencies": {
|
||||
"@getpaseo/plugin": "*",
|
||||
"zod": "^4.4.3"
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "paseo",
|
||||
"version": "0.11.0-beta.5",
|
||||
"version": "0.11.0",
|
||||
"private": true,
|
||||
"description": "Paseo: voice-controlled development environment for local AI coding agents",
|
||||
"keywords": [
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import overviewCorpus from "../../../protocol/tests/fixtures/plugin-overview.json";
|
||||
import { pluginRequirements } from "../support/helpers/plugin-fixture";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
@@ -557,7 +558,7 @@ async function retryGitInstallAndInspectRows(
|
||||
|
||||
await installPlugin(page, missingSource);
|
||||
await expect(page.getByTestId("plugin-management-feedback")).toContainText(
|
||||
"Plugin source is neither an existing directory nor a Git URL",
|
||||
`Plugin directory does not exist: ${missingSource}`,
|
||||
);
|
||||
await expect(page.getByLabel("Plugin source")).toHaveValue(missingSource);
|
||||
await capturePluginInstallForm(page, testInfo, "compact-error");
|
||||
@@ -655,3 +656,27 @@ async function reloadAndRemoveNpmPlugin(page: Page) {
|
||||
await expect(page.getByText("Removed npm-review", { exact: true })).toBeVisible();
|
||||
await expect(page.getByLabel("npm-review running")).toHaveCount(0);
|
||||
}
|
||||
|
||||
test("renders installed-plugin descriptions as plain text", async ({ page, pluginEnvironment }) => {
|
||||
const description = overviewCorpus.map(({ markdown }) => markdown).join("\n\n");
|
||||
await installPluginWithUntrustedDescription(pluginEnvironment, description);
|
||||
await gotoAppShell(page);
|
||||
await openPluginSettings(page);
|
||||
const text = page.getByText(description, { exact: true });
|
||||
await expect(text).toBeVisible();
|
||||
// This field must remain a text node, with no Markdown links, images, or HTML children.
|
||||
expect(await text.evaluate((element) => element.childElementCount)).toBe(0);
|
||||
});
|
||||
|
||||
async function installPluginWithUntrustedDescription(
|
||||
environment: PluginEnvironment,
|
||||
description: string,
|
||||
) {
|
||||
const directory = await createDirectoryPlugin(
|
||||
environment.directory,
|
||||
"plain-text-plugin",
|
||||
description,
|
||||
"Plain text plugin",
|
||||
);
|
||||
await environment.client.installPluginSource({ source: directory });
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { expect, type Page } from "@playwright/test";
|
||||
import { getStateLabel } from "@/git/pull-request-panel/data";
|
||||
import { en } from "@/i18n/resources/en";
|
||||
import { openPullRequestPanel } from "./workspace-tabs";
|
||||
|
||||
export async function openPrPane(page: Page): Promise<void> {
|
||||
@@ -14,7 +14,7 @@ export async function expectPrPaneState(
|
||||
page: Page,
|
||||
state: "open" | "merged" | "closed" | "draft",
|
||||
): Promise<void> {
|
||||
await expect(page.getByTestId("pr-pane-state")).toHaveText(getStateLabel(state), {
|
||||
await expect(page.getByTestId("pr-pane-state")).toHaveText(en.workspace.git.pr.states[state], {
|
||||
timeout: 15_000,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -244,13 +244,16 @@ const FOOTER_GEOMETRY_TOLERANCE = 0.01;
|
||||
* Settings together at the end.
|
||||
*/
|
||||
export async function expectFooterIconRow(page: Page): Promise<void> {
|
||||
const boxes = (
|
||||
await Promise.all(
|
||||
FOOTER_ICON_TEST_IDS.map((testID) =>
|
||||
page.locator(`[data-testid="${testID}"]:visible`).first().boundingBox(),
|
||||
),
|
||||
)
|
||||
).map((box) => box!);
|
||||
// Read one browser-frame snapshot: the compact drawer can translate between separate RPCs.
|
||||
const boxes = await page
|
||||
.locator(FOOTER_ICON_TEST_IDS.map((testID) => `[data-testid="${testID}"]:visible`).join(","))
|
||||
.evaluateAll((elements) =>
|
||||
elements.map((element) => {
|
||||
const { x, y, width, height } = element.getBoundingClientRect();
|
||||
return { testID: element.getAttribute("data-testid"), x, y, width, height };
|
||||
}),
|
||||
);
|
||||
expect(boxes.map((box) => box.testID)).toEqual(FOOTER_ICON_TEST_IDS);
|
||||
const [first] = boxes;
|
||||
for (const box of boxes) {
|
||||
expect(Math.abs(box.y + box.height / 2 - first!.y - first!.height / 2)).toBeLessThan(2);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/app",
|
||||
"version": "0.11.0-beta.5",
|
||||
"version": "0.11.0",
|
||||
"private": true,
|
||||
"main": "index.ts",
|
||||
"scripts": {
|
||||
|
||||
@@ -9,12 +9,13 @@ import {
|
||||
isPipelineActiveStatus,
|
||||
mapPipelineStatus,
|
||||
} from "@/git/forges/gitlab";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
import { IDENTITY_COLOR_NAMES, identityColor } from "@/styles/identity-colors";
|
||||
import {
|
||||
deriveAvatarColor,
|
||||
formatAge,
|
||||
getActivityVerb,
|
||||
getStateLabel,
|
||||
getActivityVerbKey,
|
||||
getStateLabelKey,
|
||||
mapPrPaneData,
|
||||
} from "./data";
|
||||
|
||||
@@ -779,37 +780,34 @@ describe("formatAge", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("getStateLabel", () => {
|
||||
const english = i18n.getFixedT("en");
|
||||
const french = i18n.getFixedT("fr");
|
||||
|
||||
describe("getStateLabelKey", () => {
|
||||
it.each([
|
||||
["open", "Open"],
|
||||
["draft", "Draft"],
|
||||
["merged", "Merged"],
|
||||
["closed", "Closed"],
|
||||
] as const)("maps %s → %s", (state, expected) => {
|
||||
expect(getStateLabel(state)).toBe(expected);
|
||||
["open", "Open", "Ouverte"],
|
||||
["draft", "Draft", "Brouillon"],
|
||||
["merged", "Merged", "Fusionnée"],
|
||||
["closed", "Closed", "Fermée"],
|
||||
] as const)("labels %s as %s, and %s in French", (state, englishLabel, frenchLabel) => {
|
||||
expect(english(getStateLabelKey(state))).toBe(englishLabel);
|
||||
expect(french(getStateLabelKey(state))).toBe(frenchLabel);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getActivityVerb", () => {
|
||||
it("returns Commented for comment kind", () => {
|
||||
expect(getActivityVerb({ kind: "comment" })).toBe("Commented");
|
||||
});
|
||||
|
||||
it("returns Approved for approved review", () => {
|
||||
expect(getActivityVerb({ kind: "review", reviewState: "approved" })).toBe("Approved");
|
||||
});
|
||||
|
||||
it("returns Requested changes for changes_requested review", () => {
|
||||
expect(getActivityVerb({ kind: "review", reviewState: "changes_requested" })).toBe(
|
||||
describe("getActivityVerbKey", () => {
|
||||
it.each([
|
||||
[{ kind: "comment" }, "Commented", "A commenté"],
|
||||
[{ kind: "review", reviewState: "approved" }, "Approved", "A approuvé"],
|
||||
[
|
||||
{ kind: "review", reviewState: "changes_requested" },
|
||||
"Requested changes",
|
||||
);
|
||||
});
|
||||
|
||||
it("returns Reviewed for a commented review with body (generic case)", () => {
|
||||
expect(getActivityVerb({ kind: "review", reviewState: "commented" })).toBe("Reviewed");
|
||||
});
|
||||
|
||||
it("returns Reviewed when reviewState is undefined", () => {
|
||||
expect(getActivityVerb({ kind: "review" })).toBe("Reviewed");
|
||||
"A demandé des modifications",
|
||||
],
|
||||
[{ kind: "review", reviewState: "commented" }, "Reviewed", "A relu"],
|
||||
[{ kind: "review" }, "Reviewed", "A relu"],
|
||||
] as const)("labels %o as %s, and %s in French", (item, englishVerb, frenchVerb) => {
|
||||
expect(english(getActivityVerbKey(item))).toBe(englishVerb);
|
||||
expect(french(getActivityVerbKey(item))).toBe(frenchVerb);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -318,16 +318,18 @@ function parsePullRequestNumber(url: string): number | null {
|
||||
}
|
||||
}
|
||||
|
||||
export function getStateLabel(state: PrState): string {
|
||||
if (state === "draft") return "Draft";
|
||||
if (state === "merged") return "Merged";
|
||||
if (state === "closed") return "Closed";
|
||||
return "Open";
|
||||
export function getStateLabelKey(state: PrState) {
|
||||
if (state === "draft") return "workspace.git.pr.states.draft";
|
||||
if (state === "merged") return "workspace.git.pr.states.merged";
|
||||
if (state === "closed") return "workspace.git.pr.states.closed";
|
||||
return "workspace.git.pr.states.open";
|
||||
}
|
||||
|
||||
export function getActivityVerb(item: Pick<PrPaneActivity, "kind" | "reviewState">): string {
|
||||
if (item.kind === "comment") return "Commented";
|
||||
if (item.reviewState === "approved") return "Approved";
|
||||
if (item.reviewState === "changes_requested") return "Requested changes";
|
||||
return "Reviewed";
|
||||
export function getActivityVerbKey(item: Pick<PrPaneActivity, "kind" | "reviewState">) {
|
||||
if (item.kind === "comment") return "workspace.git.pr.activity.commented";
|
||||
if (item.reviewState === "approved") return "workspace.git.pr.activity.approved";
|
||||
if (item.reviewState === "changes_requested") {
|
||||
return "workspace.git.pr.activity.requestedChanges";
|
||||
}
|
||||
return "workspace.git.pr.activity.reviewed";
|
||||
}
|
||||
|
||||
@@ -63,7 +63,7 @@ import {
|
||||
canAddPullRequestActivityToChat,
|
||||
} from "./context-attachment";
|
||||
import { ChecksSection, getCheckIdentity } from "./checks-section";
|
||||
import { getActivityVerb, getStateLabel } from "./data";
|
||||
import { getActivityVerbKey, getStateLabelKey } from "./data";
|
||||
import type { PrPaneActivity, PrPaneCheck, PrPaneData, PrState } from "./data";
|
||||
import type { ForgeSpecificStatusFacts } from "@/git/merge-capability";
|
||||
import { CheckPresentationIcon } from "@/git/check-presentation.view";
|
||||
@@ -538,7 +538,7 @@ export function PullRequestPane({
|
||||
<View style={styles.metaLine}>
|
||||
<StateIcon size={14} uniProps={statePresentation.iconColor} />
|
||||
<Text style={stateLabelStyle(data.state)} testID="pr-pane-state">
|
||||
{getStateLabel(data.state)}
|
||||
{t(getStateLabelKey(data.state))}
|
||||
</Text>
|
||||
{nativeHeaderMeta}
|
||||
{repoIdentity ? (
|
||||
@@ -760,7 +760,8 @@ function ActivityAvatar({ activity, size }: { activity: PrPaneActivity; size: nu
|
||||
}
|
||||
|
||||
function ActivityVerb({ activity }: { activity: PrPaneActivity }) {
|
||||
const verb = getActivityVerb(activity).toLowerCase();
|
||||
const { t } = useTranslation();
|
||||
const verb = t(getActivityVerbKey(activity)).toLowerCase();
|
||||
if (activity.kind === "review" && activity.reviewState === "approved") {
|
||||
return (
|
||||
<View style={styles.verbGroup}>
|
||||
@@ -1065,8 +1066,12 @@ function ThreadBlock({
|
||||
? formatPullRequestThreadPath(thread.location)
|
||||
: t("workspace.git.pr.thread.discussion")}
|
||||
</Text>
|
||||
{thread.isResolved ? <StatusBadge label="Resolved" variant="success" /> : null}
|
||||
{thread.location?.isOutdated ? <StatusBadge label="Outdated" /> : null}
|
||||
{thread.isResolved ? (
|
||||
<StatusBadge label={t("workspace.git.pr.thread.resolved")} variant="success" />
|
||||
) : null}
|
||||
{thread.location?.isOutdated ? (
|
||||
<StatusBadge label={t("workspace.git.pr.thread.outdated")} />
|
||||
) : null}
|
||||
<View style={styles.headerTrailing}>
|
||||
{collapsed ? (
|
||||
<View style={styles.threadCount}>
|
||||
|
||||
@@ -76,6 +76,7 @@ const untranslatedLocalFallbacks = [
|
||||
|
||||
const pullRequestPanelSources = [
|
||||
"git/pull-request-panel/pane.tsx",
|
||||
"git/pull-request-panel/data.ts",
|
||||
"git/pull-request-panel/checks-section.tsx",
|
||||
"components/sidebar/sidebar-status-list.tsx",
|
||||
] as const;
|
||||
@@ -87,6 +88,16 @@ const untranslatedPullRequestPanelLabels = [
|
||||
"Adding...",
|
||||
"Comment actions",
|
||||
"Thread actions",
|
||||
"Commented",
|
||||
"Approved",
|
||||
"Requested changes",
|
||||
"Reviewed",
|
||||
"Draft",
|
||||
"Merged",
|
||||
"Closed",
|
||||
"Open",
|
||||
"Resolved",
|
||||
"Outdated",
|
||||
] as const;
|
||||
|
||||
function findUntranslatedPullRequestPanelLabels(): string[] {
|
||||
@@ -244,6 +255,14 @@ describe("translation resources", () => {
|
||||
expect(pr.actions.addingToChat).not.toBe(englishPr.actions.addingToChat);
|
||||
expect(pr.accessibility.commentActions).not.toBe(englishPr.accessibility.commentActions);
|
||||
expect(pr.accessibility.threadActions).not.toBe(englishPr.accessibility.threadActions);
|
||||
for (const verb of Object.keys(englishPr.activity) as (keyof typeof englishPr.activity)[]) {
|
||||
expect(pr.activity[verb]).not.toBe(englishPr.activity[verb]);
|
||||
}
|
||||
for (const state of Object.keys(englishPr.states) as (keyof typeof englishPr.states)[]) {
|
||||
expect(pr.states[state]).not.toBe(englishPr.states[state]);
|
||||
}
|
||||
expect(pr.thread.resolved).not.toBe(englishPr.thread.resolved);
|
||||
expect(pr.thread.outdated).not.toBe(englishPr.thread.outdated);
|
||||
expect(resource.sidebar.statusGroupAccessibility).not.toBe(
|
||||
en.sidebar.statusGroupAccessibility,
|
||||
);
|
||||
|
||||
@@ -1070,6 +1070,8 @@ export const ar: TranslationResources = {
|
||||
},
|
||||
thread: {
|
||||
discussion: "سلسلة المناقشة",
|
||||
resolved: "تم الحل",
|
||||
outdated: "قديم",
|
||||
},
|
||||
errors: {
|
||||
statusLoadFailed: "غير قادر على تحميل حالة طلب السحب",
|
||||
|
||||
@@ -1078,6 +1078,8 @@ export const en = {
|
||||
},
|
||||
thread: {
|
||||
discussion: "Discussion thread",
|
||||
resolved: "Resolved",
|
||||
outdated: "Outdated",
|
||||
},
|
||||
errors: {
|
||||
statusLoadFailed: "Unable to load pull request status",
|
||||
@@ -2160,7 +2162,7 @@ export const en = {
|
||||
globalTitle: "Enable plugins",
|
||||
globalHint: "Global switch for every configured plugin",
|
||||
sourceLabel: "Plugin source",
|
||||
sourcePlaceholder: "Directory, Git URL, or npm package",
|
||||
sourcePlaceholder: "owner/slug, directory, Git URL, or npm package",
|
||||
docs: "Docs",
|
||||
install: "Install plugin",
|
||||
installing: "Installing…",
|
||||
|
||||
@@ -1093,16 +1093,18 @@ export const es: TranslationResources = {
|
||||
open: "Abierto",
|
||||
},
|
||||
activity: {
|
||||
commented: "Comentado",
|
||||
approved: "Aprobado",
|
||||
requestedChanges: "Cambios solicitados",
|
||||
reviewed: "Revisado",
|
||||
commented: "Comentó",
|
||||
approved: "Aprobó",
|
||||
requestedChanges: "Solicitó cambios",
|
||||
reviewed: "Revisó",
|
||||
},
|
||||
time: {
|
||||
justNow: "En este momento",
|
||||
},
|
||||
thread: {
|
||||
discussion: "Hilo de discusión",
|
||||
resolved: "Resuelto",
|
||||
outdated: "Desactualizado",
|
||||
},
|
||||
errors: {
|
||||
statusLoadFailed: "No se puede cargar el estado de la solicitud de extracción",
|
||||
|
||||
@@ -1094,6 +1094,8 @@ export const fr: TranslationResources = {
|
||||
},
|
||||
thread: {
|
||||
discussion: "Fil de discussion",
|
||||
resolved: "Résolu",
|
||||
outdated: "Obsolète",
|
||||
},
|
||||
errors: {
|
||||
statusLoadFailed: "Impossible de charger le statut de la pull request",
|
||||
|
||||
@@ -1083,6 +1083,8 @@ export const ja: TranslationResources = {
|
||||
},
|
||||
thread: {
|
||||
discussion: "ディスカッションスレッド",
|
||||
resolved: "解決済み",
|
||||
outdated: "古い",
|
||||
},
|
||||
errors: {
|
||||
statusLoadFailed: "プルリクエストのステータスを読み込めません",
|
||||
|
||||
@@ -1077,6 +1077,8 @@ export const ko: TranslationResources = {
|
||||
},
|
||||
thread: {
|
||||
discussion: "토론 스레드",
|
||||
resolved: "해결됨",
|
||||
outdated: "오래됨",
|
||||
},
|
||||
errors: {
|
||||
statusLoadFailed: "풀 리퀘스트 상태를 불러올 수 없습니다",
|
||||
|
||||
@@ -27,7 +27,7 @@ export const pluginSettings = {
|
||||
globalTitle: "تفعيل الإضافات",
|
||||
globalHint: "مفتاح عام لكل الإضافات المضبوطة",
|
||||
sourceLabel: "مصدر الإضافة",
|
||||
sourcePlaceholder: "مجلد أو رابط Git أو حزمة npm",
|
||||
sourcePlaceholder: "owner/slug, مجلد أو رابط Git أو حزمة npm",
|
||||
docs: "الوثائق",
|
||||
install: "تثبيت الإضافة",
|
||||
installing: "جارٍ التثبيت…",
|
||||
@@ -82,7 +82,7 @@ export const pluginSettings = {
|
||||
globalTitle: "Activar plugins",
|
||||
globalHint: "Interruptor global para todos los plugins configurados",
|
||||
sourceLabel: "Fuente del plugin",
|
||||
sourcePlaceholder: "Directorio, URL de Git o paquete npm",
|
||||
sourcePlaceholder: "owner/slug, Directorio, URL de Git o paquete npm",
|
||||
docs: "Documentación",
|
||||
install: "Instalar plugin",
|
||||
installing: "Instalando…",
|
||||
@@ -137,7 +137,7 @@ export const pluginSettings = {
|
||||
globalTitle: "Activer les plugins",
|
||||
globalHint: "Interrupteur global pour tous les plugins configurés",
|
||||
sourceLabel: "Source du plugin",
|
||||
sourcePlaceholder: "Dossier, URL Git ou paquet npm",
|
||||
sourcePlaceholder: "owner/slug, Dossier, URL Git ou paquet npm",
|
||||
docs: "Documentation",
|
||||
install: "Installer le plugin",
|
||||
installing: "Installation…",
|
||||
@@ -192,7 +192,7 @@ export const pluginSettings = {
|
||||
globalTitle: "プラグインを有効化",
|
||||
globalHint: "設定済みプラグインすべての共通スイッチ",
|
||||
sourceLabel: "プラグインソース",
|
||||
sourcePlaceholder: "ディレクトリ、Git URL、npm パッケージ",
|
||||
sourcePlaceholder: "owner/slug, ディレクトリ、Git URL、npm パッケージ",
|
||||
docs: "ドキュメント",
|
||||
install: "プラグインをインストール",
|
||||
installing: "インストール中…",
|
||||
@@ -246,7 +246,7 @@ export const pluginSettings = {
|
||||
globalTitle: "플러그인 활성화",
|
||||
globalHint: "설정된 모든 플러그인의 전역 스위치",
|
||||
sourceLabel: "플러그인 소스",
|
||||
sourcePlaceholder: "디렉터리, Git URL 또는 npm 패키지",
|
||||
sourcePlaceholder: "owner/slug, 디렉터리, Git URL 또는 npm 패키지",
|
||||
docs: "문서",
|
||||
install: "플러그인 설치",
|
||||
installing: "설치 중…",
|
||||
@@ -301,7 +301,7 @@ export const pluginSettings = {
|
||||
globalTitle: "Ativar plugins",
|
||||
globalHint: "Controle global para todos os plugins configurados",
|
||||
sourceLabel: "Fonte do plugin",
|
||||
sourcePlaceholder: "Diretório, URL Git ou pacote npm",
|
||||
sourcePlaceholder: "owner/slug, Diretório, URL Git ou pacote npm",
|
||||
docs: "Documentação",
|
||||
install: "Instalar plugin",
|
||||
installing: "Instalando…",
|
||||
@@ -356,7 +356,7 @@ export const pluginSettings = {
|
||||
globalTitle: "Включить плагины",
|
||||
globalHint: "Общий переключатель для всех настроенных плагинов",
|
||||
sourceLabel: "Источник плагина",
|
||||
sourcePlaceholder: "Каталог, URL Git или пакет npm",
|
||||
sourcePlaceholder: "owner/slug, Каталог, URL Git или пакет npm",
|
||||
docs: "Документация",
|
||||
install: "Установить плагин",
|
||||
installing: "Установка…",
|
||||
@@ -410,7 +410,7 @@ export const pluginSettings = {
|
||||
globalTitle: "启用插件",
|
||||
globalHint: "所有已配置插件的全局开关",
|
||||
sourceLabel: "插件来源",
|
||||
sourcePlaceholder: "目录、Git URL 或 npm 包",
|
||||
sourcePlaceholder: "owner/slug, 目录、Git URL 或 npm 包",
|
||||
docs: "文档",
|
||||
install: "安装插件",
|
||||
installing: "正在安装…",
|
||||
|
||||
@@ -1084,15 +1084,17 @@ export const ptBR: TranslationResources = {
|
||||
},
|
||||
activity: {
|
||||
commented: "Comentou",
|
||||
approved: "Aprovado",
|
||||
approved: "Aprovou",
|
||||
requestedChanges: "Solicitou alterações",
|
||||
reviewed: "Revisado",
|
||||
reviewed: "Revisou",
|
||||
},
|
||||
time: {
|
||||
justNow: "agora mesmo",
|
||||
},
|
||||
thread: {
|
||||
discussion: "Tópico de discussão",
|
||||
resolved: "Resolvido",
|
||||
outdated: "Desatualizado",
|
||||
},
|
||||
errors: {
|
||||
statusLoadFailed: "Não foi possível carregar o status da pull request",
|
||||
|
||||
@@ -1087,6 +1087,8 @@ export const ru: TranslationResources = {
|
||||
},
|
||||
thread: {
|
||||
discussion: "Ветка обсуждения",
|
||||
resolved: "Решено",
|
||||
outdated: "Устарело",
|
||||
},
|
||||
errors: {
|
||||
statusLoadFailed: "Не удалось загрузить статус PR",
|
||||
|
||||
@@ -1046,22 +1046,24 @@ export const zhCN: TranslationResources = {
|
||||
},
|
||||
},
|
||||
states: {
|
||||
draft: "Draft",
|
||||
merged: "已 merge",
|
||||
draft: "草稿",
|
||||
merged: "已合并",
|
||||
closed: "已关闭",
|
||||
open: "Open",
|
||||
open: "开放",
|
||||
},
|
||||
activity: {
|
||||
commented: "已评论",
|
||||
approved: "已批准",
|
||||
requestedChanges: "请求修改",
|
||||
reviewed: "已 review",
|
||||
reviewed: "已审查",
|
||||
},
|
||||
time: {
|
||||
justNow: "刚刚",
|
||||
},
|
||||
thread: {
|
||||
discussion: "讨论主题",
|
||||
resolved: "已解决",
|
||||
outdated: "已过时",
|
||||
},
|
||||
errors: {
|
||||
statusLoadFailed: "无法加载 Pull Request 状态",
|
||||
|
||||
@@ -3047,6 +3047,34 @@ describe("HostRuntimeStore", () => {
|
||||
useSessionStore.getState().clearSession(host.serverId);
|
||||
});
|
||||
|
||||
it("drains a queued message as a steer so a turn the agent just started is not interrupted", async () => {
|
||||
const host = makeHost({ serverId: "srv_steer_queue_drain" });
|
||||
const fakeClient = new FakeDaemonClient();
|
||||
const store = new HostRuntimeStore({
|
||||
deps: {
|
||||
createClient: () => fakeClient as unknown as DaemonClient,
|
||||
connectToDaemon: async () => ({
|
||||
client: fakeClient as unknown as DaemonClient,
|
||||
serverId: host.serverId,
|
||||
hostname: null,
|
||||
}),
|
||||
getClientId: async () => "cid_steer_queue_drain",
|
||||
},
|
||||
});
|
||||
const sessionStore = useSessionStore.getState();
|
||||
sessionStore.initializeSession(host.serverId, fakeClient as unknown as DaemonClient, 1);
|
||||
sessionStore.setQueuedMessages(
|
||||
host.serverId,
|
||||
new Map([["agent", [{ id: "queued", text: "next task", attachments: [] }]]]),
|
||||
);
|
||||
|
||||
store.drainQueuedAgentMessage(host.serverId, "agent");
|
||||
await fakeClient.waitForSentMessages(1);
|
||||
|
||||
expect(fakeClient.sentAgentMessages[0]?.[2]?.activeTurnBehavior).toBe("steer");
|
||||
sessionStore.clearSession(host.serverId);
|
||||
});
|
||||
|
||||
it("uses legacy GitHub attachments when draining a queue for an old daemon", async () => {
|
||||
const host = makeHost({ serverId: "srv_legacy_queue_attachment" });
|
||||
const fakeClient = new FakeDaemonClient();
|
||||
|
||||
@@ -2426,6 +2426,11 @@ export class HostRuntimeStore {
|
||||
}),
|
||||
encodeImages,
|
||||
submission: createMessageSubmissionWriter(serverId),
|
||||
// The queue drains when the agent goes idle, but the agent can start a turn of its own
|
||||
// in that same moment (a wake-up after background work). Steering folds the message
|
||||
// into that turn instead of interrupting it; with no turn running, the daemon starts
|
||||
// a normal one.
|
||||
activeTurnBehavior: "steer",
|
||||
});
|
||||
},
|
||||
})
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/cli",
|
||||
"version": "0.11.0-beta.5",
|
||||
"version": "0.11.0",
|
||||
"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.11.0-beta.5",
|
||||
"@getpaseo/protocol": "0.11.0-beta.5",
|
||||
"@getpaseo/server": "0.11.0-beta.5",
|
||||
"@getpaseo/client": "0.11.0",
|
||||
"@getpaseo/protocol": "0.11.0",
|
||||
"@getpaseo/server": "0.11.0",
|
||||
"chalk": "^5.3.0",
|
||||
"commander": "^12.0.0",
|
||||
"mime-types": "^2.1.35",
|
||||
|
||||
@@ -358,14 +358,21 @@ test.skipIf(process.platform === "win32").each([["start"], ["daemon", "run"]])(
|
||||
stdio: "ignore",
|
||||
});
|
||||
const exited = new Promise((resolve) => child!.once("exit", resolve));
|
||||
// The lock file exists before its contents identify the supervisor.
|
||||
let supervisorPid: number | undefined;
|
||||
await expect
|
||||
.poll(async () => existsSync(path.join(home, "paseo.pid")), { timeout: 10_000 })
|
||||
.toBe(true);
|
||||
const lock = JSON.parse(await readFile(path.join(home, "paseo.pid"), "utf8"));
|
||||
.poll(
|
||||
async () => {
|
||||
supervisorPid = (await readDaemonInstance(home))?.pid;
|
||||
return supervisorPid;
|
||||
},
|
||||
{ timeout: 10_000 },
|
||||
)
|
||||
.toBeTypeOf("number");
|
||||
await f.ok(["status", "--home", home]);
|
||||
child.kill("SIGINT");
|
||||
await exited;
|
||||
expect(() => process.kill(lock.pid, 0)).toThrow();
|
||||
expect(() => process.kill(supervisorPid!, 0)).toThrow();
|
||||
expect((await f.ok(["status", "--home", home])).localDaemon).toBe("stopped");
|
||||
} finally {
|
||||
child?.kill("SIGTERM");
|
||||
|
||||
@@ -255,12 +255,12 @@ describe("plugin management commands", () => {
|
||||
const stderr = vi.spyOn(process.stderr, "write").mockImplementation(() => true);
|
||||
const command = createPluginCommand();
|
||||
|
||||
await command.parseAsync(["install", "owner/monorepo", "--path", "plugins/review"], {
|
||||
await command.parseAsync(["install", "git:owner/monorepo", "--path", "plugins/review"], {
|
||||
from: "user",
|
||||
});
|
||||
|
||||
expect(installPluginSource).toHaveBeenCalledWith({
|
||||
source: "owner/monorepo:plugins/review",
|
||||
source: "git:owner/monorepo:plugins/review",
|
||||
});
|
||||
stderr.mockRestore();
|
||||
});
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
import path from "node:path";
|
||||
import { expandUserPath } from "../../classify.js";
|
||||
import { createInterface } from "node:readline/promises";
|
||||
import { reviewPluginUpdates, type UpdateOutcome } from "./update.js";
|
||||
import { Command } from "commander";
|
||||
import type { PluginListItem, PluginLogEntry } from "@getpaseo/protocol/messages";
|
||||
import {
|
||||
formatPluginSourceReference,
|
||||
parsePluginSourceReference,
|
||||
formatPluginIdentity,
|
||||
} from "@getpaseo/protocol/plugin-source-reference";
|
||||
import type { CommandOptions, ListResult, OutputSchema, SingleResult } from "../../output/index.js";
|
||||
@@ -125,7 +128,18 @@ export async function runPluginInstallCommand(
|
||||
process.stderr.write(
|
||||
"Trusting plugin code: server code and preparation commands run unsandboxed on the daemon host; client code runs inside Paseo. Dependencies and future updates are part of the codebase you trust.\n",
|
||||
);
|
||||
const sourceReference = formatPluginSourceReference(source, options.path);
|
||||
const reference = parsePluginSourceReference(source);
|
||||
let resolvedSource = source;
|
||||
if (reference.kind === "directory") {
|
||||
const directory = expandUserPath(reference.source);
|
||||
// An absolute path can target a daemon on a different operating system.
|
||||
const absoluteDirectory =
|
||||
path.posix.isAbsolute(directory) || path.win32.isAbsolute(directory)
|
||||
? directory
|
||||
: path.resolve(directory);
|
||||
resolvedSource = formatPluginSourceReference(absoluteDirectory, reference.pluginPath);
|
||||
}
|
||||
const sourceReference = formatPluginSourceReference(resolvedSource, options.path);
|
||||
const data = await withPluginSourceClient(options.daemonTarget, (client) =>
|
||||
client.installPluginSource({
|
||||
source: sourceReference,
|
||||
@@ -215,10 +229,12 @@ export function createPluginCommand(): Command {
|
||||
plugin
|
||||
.command("install")
|
||||
.alias("add")
|
||||
.description("Trust and install a plugin from a directory, Git repository, or npm package")
|
||||
.description(
|
||||
"Trust and install a plugin from a registry, directory, Git repository, or npm package",
|
||||
)
|
||||
.argument(
|
||||
"<source>",
|
||||
"Host directory, GitHub owner/repo, git: or npm: source, optionally followed by :plugin/path",
|
||||
"Registry owner/slug or host/owner/slug, host directory, explicit git:owner/repo or Git URL, or npm: source",
|
||||
)
|
||||
.option("--id <id>", "Runtime plugin ID (defaults to paseo-plugin.json id)")
|
||||
.option("--ref <ref>", "Git branch, tag, or commit")
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { exec, execFile } from "node:child_process";
|
||||
import { mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises";
|
||||
import { createRequire } from "node:module";
|
||||
import path from "node:path";
|
||||
@@ -9,6 +9,7 @@ import { scaffoldPluginDirectory } from "./scaffold.js";
|
||||
|
||||
const directories: string[] = [];
|
||||
const execFileAsync = promisify(execFile);
|
||||
const execAsync = promisify(exec);
|
||||
const tscPath = createRequire(import.meta.url).resolve("typescript/bin/tsc");
|
||||
|
||||
async function typecheckPlugin(directory: string): Promise<void> {
|
||||
@@ -28,6 +29,47 @@ afterEach(async () => {
|
||||
});
|
||||
|
||||
describe("plugin scaffold", () => {
|
||||
it("creates an author overview beside the manifest", async () => {
|
||||
const parent = await mkdtemp(path.join(tmpdir(), "paseo-plugin-scaffold-"));
|
||||
directories.push(parent);
|
||||
const directory = path.join(parent, "hello-plugin");
|
||||
await scaffoldPluginDirectory(directory);
|
||||
|
||||
const overview = await readFile(path.join(directory, "OVERVIEW.md"), "utf8");
|
||||
const comments = overview.match(/<!--[\s\S]*?-->/g) ?? [];
|
||||
expect(comments).toHaveLength(1);
|
||||
expect(overview.replace(/<!--[\s\S]*?-->/g, "").trim()).toBe("");
|
||||
expect(overview).toContain("required to list");
|
||||
expect(overview).toContain("README");
|
||||
expect(overview).toContain("choosing a plugin in Paseo");
|
||||
expect(overview).toContain("Length follows complexity");
|
||||
expect(overview).toContain("1. Describe what your plugin is and does");
|
||||
expect(overview).toContain("2. Explain how it works only when it is not obvious");
|
||||
expect(overview).toContain("3. Explain setup when needed");
|
||||
expect(overview).toContain("4. Explain capabilities and settings");
|
||||
expect(overview).toContain("permissions");
|
||||
expect(overview).toContain("known limits");
|
||||
expect(overview).not.toContain("This plugin entry was imported");
|
||||
const packageJson = JSON.parse(await readFile(path.join(directory, "package.json"), "utf8"));
|
||||
expect(packageJson.files).toContain("OVERVIEW.md");
|
||||
expect(await readdir(directory)).toContain("paseo-plugin.json");
|
||||
});
|
||||
|
||||
it("includes the author overview in the packed npm artifact", async () => {
|
||||
const parent = await mkdtemp(path.join(tmpdir(), "paseo-plugin-scaffold-"));
|
||||
directories.push(parent);
|
||||
const directory = path.join(parent, "packed-plugin");
|
||||
await scaffoldPluginDirectory(directory);
|
||||
|
||||
const { stdout } = await execAsync("npm pack --dry-run --ignore-scripts --json", {
|
||||
cwd: directory,
|
||||
});
|
||||
const [artifact] = JSON.parse(stdout) as { files: { path: string }[] }[];
|
||||
expect(artifact.files.map((file) => file.path)).toEqual(
|
||||
expect.arrayContaining(["OVERVIEW.md", "paseo-plugin.json"]),
|
||||
);
|
||||
});
|
||||
|
||||
it(
|
||||
"creates a standalone split-runtime project that typechecks",
|
||||
{ timeout: 15_000 },
|
||||
@@ -51,6 +93,8 @@ describe("plugin scaffold", () => {
|
||||
expect(JSON.parse(await readFile(path.join(directory, "paseo-plugin.json"), "utf8"))).toEqual(
|
||||
{
|
||||
id: "hello-plugin",
|
||||
$comment: expect.stringContaining('"icon": "assets/icon.png"'),
|
||||
media: [],
|
||||
requirements: { paseo: `>=${cliPackageJson.version}` },
|
||||
},
|
||||
);
|
||||
@@ -60,6 +104,7 @@ describe("plugin scaffold", () => {
|
||||
version: "0.0.0",
|
||||
files: [
|
||||
"paseo-plugin.json",
|
||||
"OVERVIEW.md",
|
||||
"index.client.ts",
|
||||
"index.client.tsx",
|
||||
"index.server.ts",
|
||||
|
||||
@@ -3,6 +3,34 @@ import path from "node:path";
|
||||
import { PluginIdSchema } from "@getpaseo/protocol/messages";
|
||||
import { resolveCliVersion } from "../../version.js";
|
||||
|
||||
const OVERVIEW = `<!--
|
||||
OVERVIEW.md is required to list your plugin in the registry. Keep it beside
|
||||
paseo-plugin.json in your repository at the pinned commit and in your npm package.
|
||||
Replace this comment with useful facts before publishing.
|
||||
|
||||
This overview is for people choosing a plugin in Paseo, on the plugin page under
|
||||
its install command. README assumes a GitHub audience and includes technical
|
||||
details, installation instructions, and badges. Long, AI-generated READMEs leave
|
||||
people reading past that material to understand what the plugin does.
|
||||
|
||||
Write these parts in order, including only what helps someone decide to install:
|
||||
|
||||
1. Describe what your plugin is and does in plain terms first.
|
||||
2. Explain how it works only when it is not obvious.
|
||||
3. Explain setup when needed: settings, accounts, tokens, providers, tools, or
|
||||
other plugins. Include applicable daemon version and operating system
|
||||
requirements. Setup guidance is allowed; installation instructions are not.
|
||||
4. Explain capabilities and settings worth understanding, what each option does,
|
||||
what the plugin reads or sends and where, permissions, and known limits.
|
||||
|
||||
Length follows complexity; a theme needs one paragraph. Choose headings only
|
||||
when they help. Use sentence case and plain factual language, with no em dashes.
|
||||
Omit installation commands, badges, changelog, contributing or license sections,
|
||||
marketing, and unsupported claims. Avoid implementation filler such as empty
|
||||
cleanup functions, theme-token field lists, or lists of absent features.
|
||||
-->
|
||||
`;
|
||||
|
||||
const TSCONFIG = {
|
||||
compilerOptions: {
|
||||
target: "ES2020",
|
||||
@@ -155,6 +183,7 @@ export async function scaffoldPluginDirectory(
|
||||
version: "0.0.0",
|
||||
files: [
|
||||
"paseo-plugin.json",
|
||||
"OVERVIEW.md",
|
||||
"index.client.ts",
|
||||
"index.client.tsx",
|
||||
"index.server.ts",
|
||||
@@ -177,8 +206,19 @@ export async function scaffoldPluginDirectory(
|
||||
const files = new Map<string, string>([
|
||||
[
|
||||
"paseo-plugin.json",
|
||||
`${JSON.stringify({ id, requirements: { paseo: `>=${version}` } }, null, 2)}\n`,
|
||||
`${JSON.stringify(
|
||||
{
|
||||
id,
|
||||
$comment:
|
||||
'Add "name": "My plugin" to set a display name. Add "icon": "assets/icon.png" for a PNG inside the package. Add image or video paths (relative to this manifest) or HTTPS URLs to media. Include local assets in package.json files.',
|
||||
media: [],
|
||||
requirements: { paseo: `>=${version}` },
|
||||
},
|
||||
null,
|
||||
2,
|
||||
)}\n`,
|
||||
],
|
||||
["OVERVIEW.md", OVERVIEW],
|
||||
["package.json", `${JSON.stringify(packageJson, null, 2)}\n`],
|
||||
["tsconfig.json", `${JSON.stringify(TSCONFIG, null, 2)}\n`],
|
||||
["index.client.tsx", CLIENT_ENTRY],
|
||||
|
||||
@@ -8,11 +8,13 @@ import {
|
||||
} from "../../../../scripts/test-support/npm-registry.mjs";
|
||||
import assert from "node:assert/strict";
|
||||
import { execFile } from "node:child_process";
|
||||
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { pathToFileURL } from "node:url";
|
||||
import { promisify } from "node:util";
|
||||
import { once } from "node:events";
|
||||
import { WebSocket, WebSocketServer } from "ws";
|
||||
import { connectToDaemon } from "../../src/utils/client.ts";
|
||||
import { createE2ETestContext } from "../helpers/test-daemon.ts";
|
||||
|
||||
@@ -45,6 +47,81 @@ async function main(): Promise<void> {
|
||||
);
|
||||
await writeFile(path.join(directory, "index.server.ts"), pluginSource);
|
||||
|
||||
// Observe real CLI requests while forwarding them to the isolated daemon.
|
||||
const proxy = new WebSocketServer({ host: "127.0.0.1", port: 0 });
|
||||
const sources: string[] = [];
|
||||
proxy.on("connection", (socket, request) => {
|
||||
const upstream = new WebSocket(`ws://127.0.0.1:${context.port}${request.url}`, {
|
||||
headers: { authorization: request.headers.authorization ?? "" },
|
||||
});
|
||||
const ready = once(upstream, "open");
|
||||
socket.on("message", async (data, isBinary) => {
|
||||
const message = JSON.parse(data.toString());
|
||||
if (
|
||||
message.type === "session" &&
|
||||
message.message.type === "plugin.source.install.request"
|
||||
) {
|
||||
sources.push(message.message.source);
|
||||
}
|
||||
await ready;
|
||||
upstream.send(data, { binary: isBinary });
|
||||
});
|
||||
upstream.on("message", (data, isBinary) => socket.send(data, { binary: isBinary }));
|
||||
socket.on("close", () => upstream.close());
|
||||
upstream.on("close", () => socket.close());
|
||||
});
|
||||
await once(proxy, "listening");
|
||||
const address = proxy.address();
|
||||
assert.ok(address && typeof address !== "string");
|
||||
const sibling = path.join(context.workDir, "x");
|
||||
const caller = path.join(context.workDir, "caller");
|
||||
await mkdir(caller);
|
||||
await mkdir(path.join(sibling, "sub"), { recursive: true });
|
||||
for (const target of [caller, path.join(sibling, "sub"), context.paseoHome]) {
|
||||
await writeFile(
|
||||
path.join(target, "paseo-plugin.json"),
|
||||
JSON.stringify({
|
||||
id: "relative-cli",
|
||||
requirements: { paseo: `>=${resolveCliVersion()}` },
|
||||
}),
|
||||
);
|
||||
await writeFile(path.join(target, "index.server.ts"), pluginSource);
|
||||
}
|
||||
assert.notEqual(caller, process.cwd()); // The daemon inherits the test runner's cwd.
|
||||
try {
|
||||
for (const [source, expectedSource, expectedDirectory, extraArgs] of [
|
||||
[".", caller, caller, []],
|
||||
["../x:sub", `${sibling}:sub`, path.join(sibling, "sub"), []],
|
||||
["../x", `${sibling}:sub`, path.join(sibling, "sub"), ["--path", "sub"]],
|
||||
["~", context.paseoHome, context.paseoHome, []],
|
||||
["~/.:.", `${context.paseoHome}:.`, context.paseoHome, []],
|
||||
] as const) {
|
||||
sources.length = 0;
|
||||
const result = await context.paseo(
|
||||
["plugin", "add", source, ...extraArgs, "--host", `127.0.0.1:${address.port}`, "--json"],
|
||||
{ cwd: caller },
|
||||
);
|
||||
assert.deepEqual(sources, [expectedSource]);
|
||||
assert.equal(result.exitCode, 0, result.stderr);
|
||||
assert.equal(JSON.parse(result.stdout).path, expectedDirectory);
|
||||
const removed = await context.paseo(["plugin", "remove", "relative-cli", "--json"]);
|
||||
assert.equal(removed.exitCode, 0, removed.stderr);
|
||||
}
|
||||
// An absolute path belongs to the daemon's platform, which can differ from the CLI's.
|
||||
const windowsSource = `C:\\${path.basename(context.workDir)}\\missing:sub`;
|
||||
sources.length = 0;
|
||||
const missing = await context.paseo(
|
||||
["plugin", "add", windowsSource, "--host", `127.0.0.1:${address.port}`, "--json"],
|
||||
{ cwd: caller },
|
||||
);
|
||||
assert.deepEqual(sources, [windowsSource]);
|
||||
assert.equal(missing.exitCode, 1);
|
||||
assert.match(missing.stderr, /Plugin directory does not exist/);
|
||||
} finally {
|
||||
for (const socket of proxy.clients) socket.close();
|
||||
await promisify(proxy.close.bind(proxy))();
|
||||
}
|
||||
|
||||
const install = await context.paseo(["plugin", "install", directory, "--json"]);
|
||||
assert.equal(install.exitCode, 0, install.stderr);
|
||||
assert.equal(JSON.parse(install.stdout).id, "cli-e2e");
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/client",
|
||||
"version": "0.11.0-beta.5",
|
||||
"version": "0.11.0",
|
||||
"description": "Paseo client SDK package",
|
||||
"files": [
|
||||
"dist",
|
||||
@@ -39,8 +39,8 @@
|
||||
"test": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
"@getpaseo/protocol": "0.11.0-beta.5",
|
||||
"@getpaseo/relay": "0.11.0-beta.5",
|
||||
"@getpaseo/protocol": "0.11.0",
|
||||
"@getpaseo/relay": "0.11.0",
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/desktop",
|
||||
"version": "0.11.0-beta.5",
|
||||
"version": "0.11.0",
|
||||
"private": true,
|
||||
"description": "Paseo desktop app (Electron wrapper)",
|
||||
"homepage": "https://paseo.sh",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/expo-two-way-audio",
|
||||
"version": "0.11.0-beta.5",
|
||||
"version": "0.11.0",
|
||||
"description": "Native module for two way audio streaming",
|
||||
"keywords": [
|
||||
"ExpoTwoWayAudio",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/highlight",
|
||||
"version": "0.11.0-beta.5",
|
||||
"version": "0.11.0",
|
||||
"files": [
|
||||
"dist",
|
||||
"!dist/**/*.map",
|
||||
|
||||
@@ -144,6 +144,19 @@ const title = "Hello";
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps an Astro expression open through nested template strings", () => {
|
||||
const code = "<p>{`a ${`}`} b`}</p>";
|
||||
|
||||
const tokens = highlightCode(code, "Nested.astro").flat();
|
||||
|
||||
expect(tokens).toEqual(
|
||||
expect.arrayContaining([
|
||||
{ text: "`}`", style: "string" },
|
||||
{ text: " b`", style: "string" },
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it("highlights Vue SFCs across script, template, and style", () => {
|
||||
const code = [
|
||||
'<script lang="ts">',
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
import { parser as cssParser } from "@lezer/css";
|
||||
import { parser as htmlParser } from "@lezer/html";
|
||||
import { parser as jsParser } from "@lezer/javascript";
|
||||
import { findClosingBrace } from "../js-scanner.js";
|
||||
|
||||
interface Range {
|
||||
from: number;
|
||||
@@ -23,88 +24,11 @@ interface Range {
|
||||
const jsxParser = jsParser.configure({ dialect: "ts jsx" });
|
||||
const typescriptParser = jsParser.configure({ dialect: "ts" });
|
||||
|
||||
function isSpace(code: number): boolean {
|
||||
return code === 32 || code === 9 || code === 10 || code === 13;
|
||||
}
|
||||
|
||||
function isRegexStart(text: string, position: number): boolean {
|
||||
let previous = position - 1;
|
||||
while (previous >= 0 && isSpace(text.charCodeAt(previous))) previous--;
|
||||
if (previous < 0) return true;
|
||||
|
||||
const character = text[previous];
|
||||
if (/[)\]}<"'`\d]/.test(character)) return false;
|
||||
const code = text.charCodeAt(previous);
|
||||
if (code === 62) return previous > 0 && text.charCodeAt(previous - 1) === 61;
|
||||
if (!/[A-Za-z_$]/.test(character)) return true;
|
||||
|
||||
let start = previous;
|
||||
while (start >= 0 && /[A-Za-z0-9_$]/.test(text[start])) start--;
|
||||
const keyword = text.slice(start + 1, previous + 1);
|
||||
return /^(return|typeof|instanceof|in|of|new|void|delete|yield|await|case|do|else|throw|extends|assert|with)$/.test(
|
||||
keyword,
|
||||
);
|
||||
}
|
||||
|
||||
function skipQuotedText(text: string, opening: number): number {
|
||||
const quote = text.charCodeAt(opening);
|
||||
for (let position = opening + 1; position < text.length; position++) {
|
||||
const code = text.charCodeAt(position);
|
||||
if (code === 92) position++;
|
||||
else if (code === quote) return position;
|
||||
}
|
||||
return text.length - 1;
|
||||
}
|
||||
|
||||
function skipLineComment(text: string, opening: number): number {
|
||||
const newline = text.indexOf("\n", opening + 2);
|
||||
return newline >= 0 ? newline : text.length - 1;
|
||||
}
|
||||
|
||||
function skipBlockComment(text: string, opening: number): number {
|
||||
const closing = text.indexOf("*/", opening + 2);
|
||||
return closing >= 0 ? closing + 1 : text.length - 1;
|
||||
}
|
||||
|
||||
function skipRegex(text: string, opening: number): number {
|
||||
let isInCharacterClass = false;
|
||||
for (let position = opening + 1; position < text.length; position++) {
|
||||
const code = text.charCodeAt(position);
|
||||
if (code === 10 || code === 13) return position;
|
||||
if (code === 92) position++;
|
||||
else if (isInCharacterClass && code === 93) isInCharacterClass = false;
|
||||
else if (!isInCharacterClass && code === 91) isInCharacterClass = true;
|
||||
else if (!isInCharacterClass && code === 47) return position;
|
||||
}
|
||||
return text.length - 1;
|
||||
}
|
||||
|
||||
function findClosingBrace(text: string, opening: number): number {
|
||||
let depth = 0;
|
||||
for (let position = opening; position < text.length; position++) {
|
||||
const code = text.charCodeAt(position);
|
||||
if (code === 47 && text.charCodeAt(position + 1) === 47) {
|
||||
position = skipLineComment(text, position);
|
||||
} else if (code === 47 && text.charCodeAt(position + 1) === 42) {
|
||||
position = skipBlockComment(text, position);
|
||||
} else if (code === 47 && isRegexStart(text, position)) {
|
||||
position = skipRegex(text, position);
|
||||
} else if (code === 34 || code === 39 || code === 96) {
|
||||
position = skipQuotedText(text, position);
|
||||
} else if (code === 123) {
|
||||
depth++;
|
||||
} else if (code === 125 && --depth === 0) {
|
||||
return position;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
function findExpressions(text: string): Range[] {
|
||||
const ranges: Range[] = [];
|
||||
for (let position = 0; position < text.length; position++) {
|
||||
if (text.charCodeAt(position) !== 123) continue;
|
||||
const closing = findClosingBrace(text, position);
|
||||
const closing = findClosingBrace(text, position + 1);
|
||||
if (closing < 0) break;
|
||||
ranges.push({ from: position, to: closing });
|
||||
position = closing;
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
// Scans JavaScript embedded in a template (Astro `{ }` expressions, Vue `{{ }}`
|
||||
// interpolations) for the brace that closes it, without parsing the code.
|
||||
|
||||
function isSpace(code: number): boolean {
|
||||
return code === 32 || code === 9 || code === 10 || code === 13;
|
||||
}
|
||||
|
||||
function isRegexStart(text: string, position: number): boolean {
|
||||
let previous = position - 1;
|
||||
while (previous >= 0 && isSpace(text.charCodeAt(previous))) previous--;
|
||||
if (previous < 0) return true;
|
||||
|
||||
const character = text[previous];
|
||||
if (/[)\]}<"'`\d]/.test(character)) return false;
|
||||
const code = text.charCodeAt(previous);
|
||||
if (code === 62) return previous > 0 && text.charCodeAt(previous - 1) === 61;
|
||||
if (!/[A-Za-z_$]/.test(character)) return true;
|
||||
|
||||
let start = previous;
|
||||
while (start >= 0 && /[A-Za-z0-9_$]/.test(text[start])) start--;
|
||||
const keyword = text.slice(start + 1, previous + 1);
|
||||
return /^(return|typeof|instanceof|in|of|new|void|delete|yield|await|case|do|else|throw|extends|assert|with)$/.test(
|
||||
keyword,
|
||||
);
|
||||
}
|
||||
|
||||
// Template strings nested deeper than this are treated as running to the end.
|
||||
const MAX_TEMPLATE_NESTING = 32;
|
||||
|
||||
function skipQuotedText(text: string, opening: number, nesting = 0): number {
|
||||
const quote = text.charCodeAt(opening);
|
||||
for (let position = opening + 1; position < text.length; position++) {
|
||||
const code = text.charCodeAt(position);
|
||||
if (code === 92) position++;
|
||||
else if (code === quote) return position;
|
||||
else if (quote === 96 && code === 36 && text.charCodeAt(position + 1) === 123) {
|
||||
position = skipTemplateSubstitution(text, position + 2, nesting);
|
||||
}
|
||||
}
|
||||
return text.length - 1;
|
||||
}
|
||||
|
||||
function skipTemplateSubstitution(text: string, start: number, nesting: number): number {
|
||||
if (nesting >= MAX_TEMPLATE_NESTING) return text.length - 1;
|
||||
const closing = findClosingBrace(text, start, () => true, nesting + 1);
|
||||
return closing >= 0 ? closing : text.length - 1;
|
||||
}
|
||||
|
||||
function skipLineComment(text: string, opening: number): number {
|
||||
const newline = text.indexOf("\n", opening + 2);
|
||||
return newline >= 0 ? newline : text.length - 1;
|
||||
}
|
||||
|
||||
function skipBlockComment(text: string, opening: number): number {
|
||||
const closing = text.indexOf("*/", opening + 2);
|
||||
return closing >= 0 ? closing + 1 : text.length - 1;
|
||||
}
|
||||
|
||||
function skipRegex(text: string, opening: number): number {
|
||||
let isInCharacterClass = false;
|
||||
for (let position = opening + 1; position < text.length; position++) {
|
||||
const code = text.charCodeAt(position);
|
||||
if (code === 10 || code === 13) return position;
|
||||
if (code === 92) position++;
|
||||
else if (isInCharacterClass && code === 93) isInCharacterClass = false;
|
||||
else if (!isInCharacterClass && code === 91) isInCharacterClass = true;
|
||||
else if (!isInCharacterClass && code === 47) return position;
|
||||
}
|
||||
return text.length - 1;
|
||||
}
|
||||
|
||||
// Finds the first `}` outside nested braces, strings, comments, and regexes
|
||||
// for which `isEnd` holds.
|
||||
export function findClosingBrace(
|
||||
text: string,
|
||||
start: number,
|
||||
isEnd: (position: number) => boolean = () => true,
|
||||
nesting = 0,
|
||||
): number {
|
||||
let depth = 0;
|
||||
for (let position = start; position < text.length; position++) {
|
||||
const code = text.charCodeAt(position);
|
||||
if (code === 47 && text.charCodeAt(position + 1) === 47) {
|
||||
position = skipLineComment(text, position);
|
||||
} else if (code === 47 && text.charCodeAt(position + 1) === 42) {
|
||||
position = skipBlockComment(text, position);
|
||||
} else if (code === 47 && isRegexStart(text, position)) {
|
||||
position = skipRegex(text, position);
|
||||
} else if (code === 34 || code === 39 || code === 96) {
|
||||
position = skipQuotedText(text, position, nesting);
|
||||
} else if (code === 123) {
|
||||
depth++;
|
||||
} else if (code === 125 && depth === 0) {
|
||||
if (isEnd(position)) return position;
|
||||
} else if (code === 125) {
|
||||
depth--;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
import { parser as cssParser } from "@lezer/css";
|
||||
import { parser as htmlParser } from "@lezer/html";
|
||||
import { parser as jsParser } from "@lezer/javascript";
|
||||
import { findClosingBrace } from "../js-scanner.js";
|
||||
|
||||
interface Range {
|
||||
from: number;
|
||||
@@ -17,104 +18,6 @@ interface Range {
|
||||
const typescriptParser = jsParser.configure({ dialect: "ts" });
|
||||
const expressionParser = jsParser.configure({ top: "SingleExpression" });
|
||||
|
||||
function isSpace(code: number): boolean {
|
||||
return code === 32 || code === 9 || code === 10 || code === 13;
|
||||
}
|
||||
|
||||
function isRegexStart(text: string, position: number): boolean {
|
||||
let previous = position - 1;
|
||||
while (previous >= 0 && isSpace(text.charCodeAt(previous))) previous--;
|
||||
if (previous < 0) return true;
|
||||
|
||||
const character = text[previous];
|
||||
if (/[)\]}<"'`\d]/.test(character)) return false;
|
||||
const code = text.charCodeAt(previous);
|
||||
if (code === 62) return previous > 0 && text.charCodeAt(previous - 1) === 61;
|
||||
if (!/[A-Za-z_$]/.test(character)) return true;
|
||||
|
||||
let start = previous;
|
||||
while (start >= 0 && /[A-Za-z0-9_$]/.test(text[start])) start--;
|
||||
const keyword = text.slice(start + 1, previous + 1);
|
||||
return /^(return|typeof|instanceof|in|of|new|void|delete|yield|await|case|do|else|throw|extends|assert|with)$/.test(
|
||||
keyword,
|
||||
);
|
||||
}
|
||||
|
||||
// Template strings nested deeper than this are treated as running to the end.
|
||||
const MAX_TEMPLATE_NESTING = 32;
|
||||
|
||||
function skipQuotedText(text: string, opening: number, nesting = 0): number {
|
||||
const quote = text.charCodeAt(opening);
|
||||
for (let position = opening + 1; position < text.length; position++) {
|
||||
const code = text.charCodeAt(position);
|
||||
if (code === 92) position++;
|
||||
else if (code === quote) return position;
|
||||
else if (quote === 96 && code === 36 && text.charCodeAt(position + 1) === 123) {
|
||||
position = skipTemplateSubstitution(text, position + 2, nesting);
|
||||
}
|
||||
}
|
||||
return text.length - 1;
|
||||
}
|
||||
|
||||
function skipTemplateSubstitution(text: string, start: number, nesting: number): number {
|
||||
if (nesting >= MAX_TEMPLATE_NESTING) return text.length - 1;
|
||||
const closing = findClosingBrace(text, start, () => true, nesting + 1);
|
||||
return closing >= 0 ? closing : text.length - 1;
|
||||
}
|
||||
|
||||
function skipLineComment(text: string, opening: number): number {
|
||||
const newline = text.indexOf("\n", opening + 2);
|
||||
return newline >= 0 ? newline : text.length - 1;
|
||||
}
|
||||
|
||||
function skipBlockComment(text: string, opening: number): number {
|
||||
const closing = text.indexOf("*/", opening + 2);
|
||||
return closing >= 0 ? closing + 1 : text.length - 1;
|
||||
}
|
||||
|
||||
function skipRegex(text: string, opening: number): number {
|
||||
let isInCharacterClass = false;
|
||||
for (let position = opening + 1; position < text.length; position++) {
|
||||
const code = text.charCodeAt(position);
|
||||
if (code === 10 || code === 13) return position;
|
||||
if (code === 92) position++;
|
||||
else if (isInCharacterClass && code === 93) isInCharacterClass = false;
|
||||
else if (!isInCharacterClass && code === 91) isInCharacterClass = true;
|
||||
else if (!isInCharacterClass && code === 47) return position;
|
||||
}
|
||||
return text.length - 1;
|
||||
}
|
||||
|
||||
// Finds the first `}` outside nested braces, strings, comments, and regexes
|
||||
// for which `isEnd` holds.
|
||||
function findClosingBrace(
|
||||
text: string,
|
||||
start: number,
|
||||
isEnd: (position: number) => boolean,
|
||||
nesting = 0,
|
||||
): number {
|
||||
let depth = 0;
|
||||
for (let position = start; position < text.length; position++) {
|
||||
const code = text.charCodeAt(position);
|
||||
if (code === 47 && text.charCodeAt(position + 1) === 47) {
|
||||
position = skipLineComment(text, position);
|
||||
} else if (code === 47 && text.charCodeAt(position + 1) === 42) {
|
||||
position = skipBlockComment(text, position);
|
||||
} else if (code === 47 && isRegexStart(text, position)) {
|
||||
position = skipRegex(text, position);
|
||||
} else if (code === 34 || code === 39 || code === 96) {
|
||||
position = skipQuotedText(text, position, nesting);
|
||||
} else if (code === 123) {
|
||||
depth++;
|
||||
} else if (code === 125 && depth === 0) {
|
||||
if (isEnd(position)) return position;
|
||||
} else if (code === 125) {
|
||||
depth--;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
function findInterpolationEnd(text: string, start: number): number {
|
||||
return findClosingBrace(text, start, (position) => text.charCodeAt(position + 1) === 125);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/plugin",
|
||||
"version": "0.11.0-beta.5",
|
||||
"version": "0.11.0",
|
||||
"description": "Paseo plugin SDK package",
|
||||
"files": [
|
||||
"dist",
|
||||
@@ -70,8 +70,8 @@
|
||||
"use-sync-external-store": "^1.6.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@getpaseo/client": "0.11.0-beta.5",
|
||||
"@getpaseo/protocol": "0.11.0-beta.5",
|
||||
"@getpaseo/client": "0.11.0",
|
||||
"@getpaseo/protocol": "0.11.0",
|
||||
"@types/node": "^20.9.0",
|
||||
"@types/react": "~19.2.0",
|
||||
"react": "19.1.0",
|
||||
@@ -81,8 +81,8 @@
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@getpaseo/client": "0.11.0-beta.5",
|
||||
"@getpaseo/protocol": "0.11.0-beta.5",
|
||||
"@getpaseo/client": "0.11.0",
|
||||
"@getpaseo/protocol": "0.11.0",
|
||||
"react": "~19.1.0",
|
||||
"react-native": ">=0.81.5",
|
||||
"zod": "^4.4.3"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/protocol",
|
||||
"version": "0.11.0-beta.5",
|
||||
"version": "0.11.0",
|
||||
"description": "Paseo shared protocol schemas and wire types",
|
||||
"files": [
|
||||
"dist",
|
||||
|
||||
@@ -23,6 +23,27 @@ describe("plugin protocol compatibility", () => {
|
||||
expect(SessionOutboundMessageSchema.parse(message)).toEqual(message);
|
||||
},
|
||||
);
|
||||
it("preserves manifest metadata in plugin list responses", () => {
|
||||
const message = {
|
||||
type: "plugin.list.response",
|
||||
payload: {
|
||||
requestId: "metadata",
|
||||
plugins: [
|
||||
{
|
||||
id: "review",
|
||||
name: "Review tools",
|
||||
icon: "assets/icon.png",
|
||||
media: ["screenshot.png", "https://example.com/demo.mp4"],
|
||||
path: "/plugins/review",
|
||||
enabled: false,
|
||||
status: "disabled",
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
expect(SessionOutboundMessageSchema.parse(message)).toEqual(message);
|
||||
});
|
||||
|
||||
it("parses plugin timeline append messages and advertises the capability", () => {
|
||||
expect(
|
||||
SessionInboundMessageSchema.parse({
|
||||
|
||||
@@ -6632,6 +6632,9 @@ export const PluginNpmInstallationSchema = z.object({
|
||||
|
||||
export const PluginListItemSchema = z.object({
|
||||
id: PluginIdSchema,
|
||||
name: z.string().optional(),
|
||||
icon: z.string().optional(),
|
||||
media: z.array(z.string()).optional(),
|
||||
description: z.string().optional(),
|
||||
path: z.string(),
|
||||
enabled: z.boolean(),
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { pluginOverviewUrl } from "./plugin-overview.js";
|
||||
|
||||
describe("plugin overview destinations", () => {
|
||||
it.each([
|
||||
undefined,
|
||||
"",
|
||||
"./docs",
|
||||
"../docs",
|
||||
"/login",
|
||||
"//example.com",
|
||||
"#section",
|
||||
"?login",
|
||||
"http://example.com",
|
||||
"mailto:hello@example.com",
|
||||
"ftp://example.com",
|
||||
"javascript:alert(1)",
|
||||
"data:image/png;base64,AAAA",
|
||||
"vbscript:msgbox(1)",
|
||||
"javascript:alert(1)",
|
||||
"javascript%3Aalert(1)",
|
||||
"javascript%253Aalert(1)",
|
||||
"java\tscript:alert(1)",
|
||||
" https://example.com",
|
||||
"https://example.com\n",
|
||||
"https:example.com",
|
||||
"https:///example.com",
|
||||
"https://paseo.sh@evil.example",
|
||||
"https://example.com\\@evil.example",
|
||||
"https://",
|
||||
])("leaves %s as text", (url) => {
|
||||
expect(pluginOverviewUrl(url)).toBeUndefined();
|
||||
});
|
||||
|
||||
it.each([
|
||||
"https://example.com/path?q=a&b=c#section",
|
||||
"HTTPS://example.com/path",
|
||||
"https://example.com/%3Cscript%3E",
|
||||
])("allows %s without decoding it again", (url) => {
|
||||
expect(pluginOverviewUrl(url)).toBe(url);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,49 @@
|
||||
/** Presentation contract for author-controlled registry content, independent of the UI runtime. */
|
||||
export const pluginOverviewPolicy = {
|
||||
rawHtml: false,
|
||||
elements: [
|
||||
"p",
|
||||
"br",
|
||||
"hr",
|
||||
"h1",
|
||||
"h2",
|
||||
"h3",
|
||||
"h4",
|
||||
"h5",
|
||||
"h6",
|
||||
"blockquote",
|
||||
"ul",
|
||||
"ol",
|
||||
"li",
|
||||
"strong",
|
||||
"em",
|
||||
"del",
|
||||
"pre",
|
||||
"code",
|
||||
"a",
|
||||
"img",
|
||||
"table",
|
||||
"thead",
|
||||
"tbody",
|
||||
"tr",
|
||||
"th",
|
||||
"td",
|
||||
],
|
||||
link: { rel: "noopener noreferrer nofollow", target: "_blank" },
|
||||
} as const;
|
||||
|
||||
/** Validate decoded Markdown destinations; never resolve against the reader's page or repository. */
|
||||
export function pluginOverviewUrl(value: string | undefined): string | undefined {
|
||||
// URL parsers discard controls and normalize backslashes; reject those ambiguous spellings.
|
||||
// eslint-disable-next-line no-control-regex
|
||||
if (!value || !/^https:\/\/[^/?#]/i.test(value) || /[\u0000-\u0020\u007f\\]/.test(value))
|
||||
return undefined;
|
||||
try {
|
||||
const url = new URL(value);
|
||||
if (url.protocol !== "https:" || !url.hostname || url.username || url.password)
|
||||
return undefined;
|
||||
return value;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { pluginMediaKind } from "./plugin-registry.js";
|
||||
|
||||
describe("plugin media kind", () => {
|
||||
it.each([
|
||||
["https://cdn.example.com/a/preview.png", "image"],
|
||||
["https://cdn.example.com/a/preview.JPG", "image"],
|
||||
["https://cdn.example.com/a/preview.jpeg", "image"],
|
||||
["https://cdn.example.com/a/preview.webp", "image"],
|
||||
["https://cdn.example.com/a/preview.gif", "image"],
|
||||
["https://cdn.example.com/a/demo.mp4", "video"],
|
||||
["https://cdn.example.com/a/demo.WebM", "video"],
|
||||
["https://cdn.example.com/a/demo.mp4?raw=true#t=2", "video"],
|
||||
["https://cdn.example.com/mp4/preview.png?format=mp4", "image"],
|
||||
] as const)("reads %s as %s from its path extension", (url, kind) => {
|
||||
expect(pluginMediaKind(url)).toBe(kind);
|
||||
});
|
||||
});
|
||||
@@ -39,13 +39,21 @@ export const PublishedPluginSchema = z.object({
|
||||
repository: z.object({ url: z.string().url(), commit: z.string().optional() }),
|
||||
artifact: PluginRegistryArtifactSchema,
|
||||
icon: z.string().url().optional(),
|
||||
screenshots: z.array(z.string().url()),
|
||||
/** Images and videos in display order; see `pluginMediaKind`. */
|
||||
media: z.array(z.string().url()),
|
||||
submittedAt: z.string(),
|
||||
reviewedAt: z.string(),
|
||||
updatedAt: z.string(),
|
||||
publishedAt: z.string(),
|
||||
installs: z.number().int().nonnegative().optional(),
|
||||
});
|
||||
const VIDEO_EXTENSIONS = new Set(["mp4", "webm"]);
|
||||
|
||||
/** Whether a registry media entry is a video or an image, from its path extension. */
|
||||
export function pluginMediaKind(url: string): "image" | "video" {
|
||||
const extension = new URL(url).pathname.split(".").pop()?.toLowerCase() ?? "";
|
||||
return VIDEO_EXTENSIONS.has(extension) ? "video" : "image";
|
||||
}
|
||||
export const PublishedPluginDetailSchema = PublishedPluginSchema.extend({ readme: z.string() });
|
||||
export const PluginRegistryIndexSchema = z.object({
|
||||
schemaVersion: z.literal(1),
|
||||
@@ -54,6 +62,8 @@ export const PluginRegistryIndexSchema = z.object({
|
||||
z.object({ slug: z.string(), label: z.string(), description: z.string().optional() }),
|
||||
),
|
||||
plugins: z.array(PublishedPluginSchema),
|
||||
/** Plugin IDs the maintainer features, in display order. An ID may name a plugin that is not listed. */
|
||||
featured: z.array(z.string()),
|
||||
generatedAt: z.string(),
|
||||
});
|
||||
export type PluginRegistryIdentity = z.infer<typeof PluginRegistryIdentitySchema>;
|
||||
|
||||
@@ -3,6 +3,35 @@ import { describe, expect, it } from "vitest";
|
||||
import { parsePluginSourceReference } from "./plugin-source-reference.js";
|
||||
|
||||
describe("plugin source references", () => {
|
||||
it.each([
|
||||
".",
|
||||
"..",
|
||||
"./owner/slug",
|
||||
"../owner/slug",
|
||||
"/owner/slug",
|
||||
"~/owner/slug",
|
||||
"~",
|
||||
"C:\\",
|
||||
"C:/",
|
||||
"D:\\plugins\\repository",
|
||||
"D:/plugins/repository",
|
||||
"\\\\server\\share",
|
||||
"\\\\server\\share\\plugins\\review",
|
||||
".\\plugins\\review",
|
||||
"..\\plugins\\review",
|
||||
])("recognizes the explicit directory %s by shape", (source) => {
|
||||
expect(parsePluginSourceReference(source)).toEqual({
|
||||
kind: "directory",
|
||||
source,
|
||||
pluginPath: undefined,
|
||||
});
|
||||
expect(parsePluginSourceReference(`${source}:plugins/review`)).toEqual({
|
||||
kind: "directory",
|
||||
source,
|
||||
pluginPath: "plugins/review",
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
["npm:review@1.2.0:nested", "npm:review@1.2.0", "nested"],
|
||||
["npm:review@^1.2.0", "npm:review@^1.2.0", undefined],
|
||||
@@ -16,6 +45,7 @@ describe("plugin source references", () => {
|
||||
["git:file:///repo:plugins/main", "git:file:///repo", "plugins/main"],
|
||||
["plugins.example.com:8443/owner/slug", "plugins.example.com:8443/owner/slug", undefined],
|
||||
["owner/repository", "owner/repository", undefined],
|
||||
["plugins/foo", "plugins/foo", undefined],
|
||||
["owner/repository:plugins/review", "owner/repository", "plugins/review"],
|
||||
[
|
||||
"https://example.test:8443/owner/repository.git",
|
||||
@@ -39,10 +69,8 @@ describe("plugin source references", () => {
|
||||
"file:///D:/plugins/repository",
|
||||
"plugins/review",
|
||||
],
|
||||
["D:\\plugins\\repository", "D:\\plugins\\repository", undefined],
|
||||
["D:\\plugins\\repository:plugins/review", "D:\\plugins\\repository", "plugins/review"],
|
||||
])("parses %s", (reference, source, pluginPath) => {
|
||||
expect(parsePluginSourceReference(reference)).toEqual({ source, pluginPath });
|
||||
expect(parsePluginSourceReference(reference)).toEqual({ kind: "managed", source, pluginPath });
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -1,19 +1,27 @@
|
||||
import { parsePluginRegistryReference } from "./plugin-registry.js";
|
||||
import type { PluginInstallation } from "./messages.js";
|
||||
export interface PluginSourceReference {
|
||||
kind: "directory" | "managed";
|
||||
source: string;
|
||||
pluginPath: string | undefined;
|
||||
}
|
||||
|
||||
export function parsePluginSourceReference(reference: string): PluginSourceReference {
|
||||
if (parsePluginRegistryReference(reference)) return { source: reference, pluginPath: undefined };
|
||||
const prefix = /^(npm:|github:|git:(?!\/\/))/.exec(reference)?.[0];
|
||||
const source = prefix ? reference.slice(prefix.length) : reference;
|
||||
const parsed = splitPluginPath(source, { scp: prefix !== "npm:" });
|
||||
return { ...parsed, source: `${prefix ?? ""}${parsed.source}` };
|
||||
if (!prefix && /^(\.\.?(?:[/\\]|$)|\/|~|[A-Za-z]:[/\\]|\\\\)/.test(parsed.source)) {
|
||||
return { kind: "directory", ...parsed };
|
||||
}
|
||||
if (parsePluginRegistryReference(reference))
|
||||
return { kind: "managed", source: reference, pluginPath: undefined };
|
||||
return { kind: "managed", ...parsed, source: `${prefix ?? ""}${parsed.source}` };
|
||||
}
|
||||
|
||||
function splitPluginPath(reference: string, options: { scp: boolean }): PluginSourceReference {
|
||||
function splitPluginPath(
|
||||
reference: string,
|
||||
options: { scp: boolean },
|
||||
): Pick<PluginSourceReference, "source" | "pluginPath"> {
|
||||
const separator = reference.lastIndexOf(":");
|
||||
if (separator === -1) return { source: reference, pluginPath: undefined };
|
||||
|
||||
|
||||
+1202
File diff suppressed because it is too large
Load Diff
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/relay",
|
||||
"version": "0.11.0-beta.5",
|
||||
"version": "0.11.0",
|
||||
"description": "Paseo relay for bridging daemon and client connections",
|
||||
"files": [
|
||||
"dist",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/server",
|
||||
"version": "0.11.0-beta.5",
|
||||
"version": "0.11.0",
|
||||
"description": "Paseo backend server",
|
||||
"files": [
|
||||
"dist/server",
|
||||
@@ -107,11 +107,11 @@
|
||||
"@agentclientprotocol/sdk": "^0.17.1",
|
||||
"@anthropic-ai/claude-agent-sdk": "0.3.246",
|
||||
"@anthropic-ai/sdk": "^0.104.2",
|
||||
"@getpaseo/client": "0.11.0-beta.5",
|
||||
"@getpaseo/highlight": "0.11.0-beta.5",
|
||||
"@getpaseo/plugin": "0.11.0-beta.5",
|
||||
"@getpaseo/protocol": "0.11.0-beta.5",
|
||||
"@getpaseo/relay": "0.11.0-beta.5",
|
||||
"@getpaseo/client": "0.11.0",
|
||||
"@getpaseo/highlight": "0.11.0",
|
||||
"@getpaseo/plugin": "0.11.0",
|
||||
"@getpaseo/protocol": "0.11.0",
|
||||
"@getpaseo/relay": "0.11.0",
|
||||
"@isaacs/ttlcache": "^2.1.4",
|
||||
"@modelcontextprotocol/sdk": "1.29.0",
|
||||
"@opencode-ai/sdk": "1.14.46",
|
||||
|
||||
@@ -309,18 +309,30 @@ export async function sendPromptToAgent(
|
||||
const unarchive = params.unarchive ?? true;
|
||||
|
||||
const record = await params.agentStorage.get(params.agentId);
|
||||
let archivedAtToRestore: string | null = null;
|
||||
if (record?.archivedAt) {
|
||||
if (!unarchive) {
|
||||
return { disposition: "turn_started" };
|
||||
}
|
||||
await unarchiveAgentState(params.agentStorage, params.agentManager, params.agentId);
|
||||
if (await unarchiveAgentState(params.agentStorage, params.agentManager, params.agentId)) {
|
||||
archivedAtToRestore = record.archivedAt;
|
||||
}
|
||||
}
|
||||
|
||||
await ensureAgentLoaded(params.agentId, {
|
||||
agentManager: params.agentManager,
|
||||
agentStorage: params.agentStorage,
|
||||
logger: params.logger,
|
||||
});
|
||||
try {
|
||||
await ensureAgentLoaded(params.agentId, {
|
||||
agentManager: params.agentManager,
|
||||
agentStorage: params.agentStorage,
|
||||
logger: params.logger,
|
||||
});
|
||||
} catch (error) {
|
||||
// A send that could not load the agent leaves it where it was: still archived.
|
||||
// Concurrent sends share this load, so none of them holds a live session.
|
||||
if (archivedAtToRestore) {
|
||||
await params.agentManager.archiveSnapshot(params.agentId, archivedAtToRestore);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
if (params.sessionMode) {
|
||||
await params.agentManager.setAgentMode(params.agentId, params.sessionMode);
|
||||
|
||||
@@ -628,6 +628,11 @@ export interface AgentCreateSessionOptions {
|
||||
* Defaults to true. Providers that cannot honor false should no-op.
|
||||
*/
|
||||
persistSession?: boolean;
|
||||
/**
|
||||
* Model ids added by provider configuration (`models` / `additionalModels`).
|
||||
* Providers that validate against runtime-advertised models must accept these.
|
||||
*/
|
||||
configuredModelIds?: readonly string[];
|
||||
}
|
||||
|
||||
/** What a resumed session is for: driving the agent, or reading what it already did. */
|
||||
@@ -637,6 +642,8 @@ export type AgentResumePurpose = "interactive" | "history";
|
||||
export interface AgentResumeSessionOptions {
|
||||
/** Defaults to interactive. History loading may be read-only for archived native sessions. */
|
||||
purpose?: AgentResumePurpose;
|
||||
/** See AgentCreateSessionOptions.configuredModelIds. */
|
||||
configuredModelIds?: readonly string[];
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -723,6 +723,57 @@ describe("AgentStreamCoalescer", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
test("keeps a known tool call detail when a later update in the window has none", () => {
|
||||
const { coalescer, flushes } = createHarness();
|
||||
primeLeadingEdge(coalescer, flushes);
|
||||
|
||||
coalescer.handle(
|
||||
"agent-1",
|
||||
timeline({
|
||||
type: "tool_call",
|
||||
callId: "agent-call",
|
||||
name: "Task",
|
||||
status: "running",
|
||||
error: null,
|
||||
detail: {
|
||||
type: "sub_agent",
|
||||
subAgentType: "general-purpose",
|
||||
description: "List files",
|
||||
log: "",
|
||||
actions: [],
|
||||
},
|
||||
}),
|
||||
);
|
||||
coalescer.handle(
|
||||
"agent-1",
|
||||
timeline({
|
||||
type: "tool_call",
|
||||
callId: "agent-call",
|
||||
name: "Agent",
|
||||
status: "completed",
|
||||
error: null,
|
||||
detail: { type: "unknown", input: { description: "List files" }, output: null },
|
||||
}),
|
||||
);
|
||||
|
||||
expect(flushes.map((flush) => flush.item)).toEqual([
|
||||
{
|
||||
type: "tool_call",
|
||||
callId: "agent-call",
|
||||
name: "Agent",
|
||||
status: "completed",
|
||||
error: null,
|
||||
detail: {
|
||||
type: "sub_agent",
|
||||
subAgentType: "general-purpose",
|
||||
description: "List files",
|
||||
log: "",
|
||||
actions: [],
|
||||
},
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test("preserves mixed text and tool call arrival order within a flush", async () => {
|
||||
const { coalescer, flushes } = createHarness();
|
||||
primeLeadingEdge(coalescer, flushes);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { AgentProvider, AgentStreamEvent, AgentTimelineItem } from "./agent-sdk-types.js";
|
||||
import { mergeToolCallItems } from "./timeline-projection.js";
|
||||
|
||||
export const AGENT_STREAM_COALESCE_DEFAULT_WINDOW_MS = 60;
|
||||
|
||||
@@ -183,9 +184,16 @@ export class AgentStreamCoalescer {
|
||||
}
|
||||
|
||||
const existingIndex = buffer.toolCallEntryIndexes.get(event.item.callId);
|
||||
const existing = existingIndex !== undefined ? buffer.entries[existingIndex] : undefined;
|
||||
// Merge rather than replace, so an update that carries less (an unknown detail after a
|
||||
// labeled one) cannot erase what the timeline would have kept had both been flushed.
|
||||
let item = event.item;
|
||||
if (existing?.kind === "tool_call") {
|
||||
item = mergeToolCallItems(existing.item, event.item);
|
||||
}
|
||||
const entry: PendingToolCallEntry = {
|
||||
kind: "tool_call",
|
||||
item: event.item,
|
||||
item,
|
||||
provider: event.provider,
|
||||
...(event.turnId !== undefined ? { turnId: event.turnId } : {}),
|
||||
};
|
||||
|
||||
@@ -492,6 +492,7 @@ function wrapClientProvider(
|
||||
const listFeatures = inner.listFeatures?.bind(inner);
|
||||
const archiveNativeSession = inner.archiveNativeSession?.bind(inner);
|
||||
const unarchiveNativeSession = inner.unarchiveNativeSession?.bind(inner);
|
||||
const configuredModelIds = [...profileModels, ...additionalModels].map((model) => model.id);
|
||||
|
||||
return {
|
||||
provider,
|
||||
@@ -509,7 +510,7 @@ function wrapClientProvider(
|
||||
providerOptions: mergeProviderOptions(providerOptions, config.providerOptions),
|
||||
},
|
||||
launchContext,
|
||||
options,
|
||||
{ ...options, configuredModelIds },
|
||||
),
|
||||
),
|
||||
resumeSession: async (handle, overrides, launchContext, options) =>
|
||||
@@ -526,7 +527,7 @@ function wrapClientProvider(
|
||||
providerOptions: mergeProviderOptions(providerOptions, overrides?.providerOptions),
|
||||
},
|
||||
launchContext,
|
||||
options,
|
||||
{ ...options, configuredModelIds },
|
||||
),
|
||||
),
|
||||
fetchCatalog: async (options, context) => {
|
||||
|
||||
@@ -5,7 +5,7 @@ import { createRequire } from "node:module";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { pathToFileURL } from "node:url";
|
||||
import { afterEach, describe, expect, test, vi } from "vitest";
|
||||
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
|
||||
import {
|
||||
AgentSideConnection,
|
||||
ClientSideConnection,
|
||||
@@ -54,8 +54,10 @@ import type { AgentStreamEvent } from "../agent-sdk-types.js";
|
||||
import type {
|
||||
AgentCapabilityFlags,
|
||||
AgentPersistenceHandle,
|
||||
AgentSession,
|
||||
ProviderRefreshContext,
|
||||
} from "../agent-sdk-types.js";
|
||||
import { buildProviderRegistry } from "../provider-registry.js";
|
||||
import { createTestLogger } from "../../../test-utils/test-logger.js";
|
||||
import { buildStringCommandShellInvocation } from "../../../utils/string-command-shell.js";
|
||||
import { asInternals } from "../../test-utils/class-mocks.js";
|
||||
@@ -4370,3 +4372,151 @@ describe("ACPAgentSession close() with an unresponsive provider", () => {
|
||||
expect(isProcessAlive(pid)).toBe(false);
|
||||
}, 15_000);
|
||||
});
|
||||
|
||||
// An ACP agent that advertises two models (or none, with ACP_ADVERTISE_MODELS=none) but,
|
||||
// like Cline, runs any model id it is given.
|
||||
const PERMISSIVE_MODEL_ACP_AGENT = `
|
||||
import { Readable, Writable } from "node:stream";
|
||||
const { AgentSideConnection, PROTOCOL_VERSION, ndJsonStream } = await import(process.env.ACP_SDK_URL);
|
||||
let currentModelId = "advertised-default";
|
||||
const modelState = () =>
|
||||
process.env.ACP_ADVERTISE_MODELS === "none"
|
||||
? undefined
|
||||
: {
|
||||
currentModelId,
|
||||
availableModels: [
|
||||
{ modelId: "advertised-default", name: "Advertised default" },
|
||||
{ modelId: "advertised-other", name: "Advertised other" },
|
||||
],
|
||||
};
|
||||
new AgentSideConnection(
|
||||
() => ({
|
||||
async initialize() {
|
||||
return { protocolVersion: PROTOCOL_VERSION, agentCapabilities: { loadSession: true } };
|
||||
},
|
||||
async newSession() {
|
||||
return { sessionId: "permissive-session", models: modelState() };
|
||||
},
|
||||
async loadSession() {
|
||||
return { models: modelState() };
|
||||
},
|
||||
async unstable_setSessionModel({ modelId }) {
|
||||
currentModelId = modelId;
|
||||
return {};
|
||||
},
|
||||
async authenticate() {},
|
||||
async cancel() {},
|
||||
async prompt() {
|
||||
return { stopReason: "end_turn" };
|
||||
},
|
||||
}),
|
||||
ndJsonStream(Writable.toWeb(process.stdout), Readable.toWeb(process.stdin)),
|
||||
);
|
||||
`;
|
||||
|
||||
describe("custom ACP provider with configured models", () => {
|
||||
let dir: string;
|
||||
let agentScript: string;
|
||||
let session: AgentSession | null = null;
|
||||
|
||||
beforeEach(async () => {
|
||||
dir = await mkdtemp(path.join(tmpdir(), "paseo-acp-configured-models-"));
|
||||
agentScript = path.join(dir, "agent.mjs");
|
||||
await writeFile(agentScript, PERMISSIVE_MODEL_ACP_AGENT);
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await session?.close();
|
||||
session = null;
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
function buildRegistry(
|
||||
override: {
|
||||
models?: Array<{ id: string; label: string }>;
|
||||
additionalModels?: Array<{ id: string; label: string }>;
|
||||
},
|
||||
agentEnv: Record<string, string> = {},
|
||||
) {
|
||||
return buildProviderRegistry(createTestLogger(), {
|
||||
providerOverrides: {
|
||||
permissive: {
|
||||
extends: "acp",
|
||||
label: "Permissive",
|
||||
command: [process.execPath, agentScript],
|
||||
env: {
|
||||
ACP_SDK_URL: pathToFileURL(
|
||||
createRequire(import.meta.url).resolve("@agentclientprotocol/sdk"),
|
||||
).href,
|
||||
...agentEnv,
|
||||
},
|
||||
...override,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async function createSessionOnModel(
|
||||
registry: ReturnType<typeof buildRegistry>,
|
||||
model: string,
|
||||
): Promise<AgentSession> {
|
||||
const client = registry.permissive.createClient(createTestLogger());
|
||||
session = await client.createSession({ provider: "permissive", cwd: dir, model });
|
||||
return session;
|
||||
}
|
||||
|
||||
test("runs on a model added through additionalModels that the agent does not advertise", async () => {
|
||||
const registry = buildRegistry({
|
||||
additionalModels: [{ id: "stealth/pixel-canary", label: "Pixel Canary" }],
|
||||
});
|
||||
|
||||
const created = await createSessionOnModel(registry, "stealth/pixel-canary");
|
||||
|
||||
expect((await created.getRuntimeInfo()).model).toBe("stealth/pixel-canary");
|
||||
});
|
||||
|
||||
test("runs on a model from a replacement models list that the agent does not advertise", async () => {
|
||||
const registry = buildRegistry({
|
||||
models: [{ id: "stealth/pixel-canary", label: "Pixel Canary" }],
|
||||
});
|
||||
|
||||
const created = await createSessionOnModel(registry, "stealth/pixel-canary");
|
||||
|
||||
expect((await created.getRuntimeInfo()).model).toBe("stealth/pixel-canary");
|
||||
});
|
||||
|
||||
test("runs on a model from additionalModels when the agent advertises no models", async () => {
|
||||
const registry = buildRegistry(
|
||||
{ additionalModels: [{ id: "stealth/pixel-canary", label: "Pixel Canary" }] },
|
||||
{ ACP_ADVERTISE_MODELS: "none" },
|
||||
);
|
||||
|
||||
const created = await createSessionOnModel(registry, "stealth/pixel-canary");
|
||||
|
||||
expect((await created.getRuntimeInfo()).model).toBe("stealth/pixel-canary");
|
||||
});
|
||||
|
||||
test("resumes on a model added through additionalModels that the agent does not advertise", async () => {
|
||||
const registry = buildRegistry({
|
||||
additionalModels: [{ id: "stealth/pixel-canary", label: "Pixel Canary" }],
|
||||
});
|
||||
const client = registry.permissive.createClient(createTestLogger());
|
||||
|
||||
session = await client.resumeSession(
|
||||
{ provider: "permissive", sessionId: "permissive-session", metadata: { cwd: dir } },
|
||||
{ model: "stealth/pixel-canary" },
|
||||
);
|
||||
|
||||
expect((await session.getRuntimeInfo()).model).toBe("stealth/pixel-canary");
|
||||
});
|
||||
|
||||
test("keeps the agent's model when the requested model is neither advertised nor configured", async () => {
|
||||
const registry = buildRegistry({
|
||||
additionalModels: [{ id: "stealth/pixel-canary", label: "Pixel Canary" }],
|
||||
});
|
||||
|
||||
const created = await createSessionOnModel(registry, "stale/removed-model");
|
||||
|
||||
expect((await created.getRuntimeInfo()).model).toBe("advertised-default");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -76,6 +76,9 @@ import {
|
||||
type AgentPersistenceHandle,
|
||||
type AgentPromptContentBlock,
|
||||
type AgentPromptInput,
|
||||
type AgentResumePurpose,
|
||||
type AgentCreateSessionOptions,
|
||||
type AgentResumeSessionOptions,
|
||||
type AgentRunOptions,
|
||||
type AgentRunResult,
|
||||
type AgentRuntimeInfo,
|
||||
@@ -148,6 +151,18 @@ function rejectOnSpawnError(child: ChildProcess, stderrChunks: string[]): Promis
|
||||
});
|
||||
}
|
||||
|
||||
async function isDirectory(target: string): Promise<boolean> {
|
||||
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<string, unknown> {
|
||||
return value != null && typeof value === "object" && !Array.isArray(value);
|
||||
}
|
||||
@@ -497,6 +512,8 @@ interface ACPAgentSessionOptions {
|
||||
capabilities: AgentCapabilityFlags;
|
||||
extensionCommandsParser?: ACPExtensionCommandsParser;
|
||||
handle?: AgentPersistenceHandle;
|
||||
resumePurpose?: AgentResumePurpose;
|
||||
configuredModelIds?: readonly string[];
|
||||
agentId?: string;
|
||||
launchEnv?: Record<string, string>;
|
||||
waitForInitialCommands?: boolean;
|
||||
@@ -964,6 +981,7 @@ export class ACPAgentClient implements AgentClient {
|
||||
async createSession(
|
||||
config: AgentSessionConfig,
|
||||
launchContext?: AgentLaunchContext,
|
||||
options?: AgentCreateSessionOptions,
|
||||
): Promise<AgentSession> {
|
||||
this.assertProvider(config);
|
||||
const providerOptions = ACPProviderOptionsSchema.parse(config.providerOptions ?? {});
|
||||
@@ -991,6 +1009,7 @@ export class ACPAgentClient implements AgentClient {
|
||||
supportsMcpServers:
|
||||
providerOptions.supportsMcpServers ?? this.capabilities.supportsMcpServers,
|
||||
},
|
||||
configuredModelIds: options?.configuredModelIds,
|
||||
agentId: launchContext?.agentId,
|
||||
launchEnv: launchContext?.env,
|
||||
extensionCommandsParser: this.extensionCommandsParser,
|
||||
@@ -1006,6 +1025,7 @@ export class ACPAgentClient implements AgentClient {
|
||||
handle: AgentPersistenceHandle,
|
||||
overrides?: Partial<AgentSessionConfig>,
|
||||
launchContext?: AgentLaunchContext,
|
||||
options?: AgentResumeSessionOptions,
|
||||
): Promise<AgentSession> {
|
||||
if (handle.provider !== this.provider) {
|
||||
throw new Error(`Cannot resume ${handle.provider} handle with ${this.provider} provider`);
|
||||
@@ -1047,6 +1067,8 @@ export class ACPAgentClient implements AgentClient {
|
||||
providerOptions.supportsMcpServers ?? this.capabilities.supportsMcpServers,
|
||||
},
|
||||
handle,
|
||||
resumePurpose: options?.purpose,
|
||||
configuredModelIds: options?.configuredModelIds,
|
||||
agentId: launchContext?.agentId,
|
||||
launchEnv: launchContext?.env,
|
||||
extensionCommandsParser: this.extensionCommandsParser,
|
||||
@@ -1675,6 +1697,7 @@ export class ACPAgentSession implements AgentSession, ACPClient {
|
||||
configOptions: SessionConfigOption[],
|
||||
) => SessionConfigOption[];
|
||||
private readonly configFeatureOptions: ACPConfigFeatureOption[];
|
||||
private readonly configuredModelIds: ReadonlySet<string>;
|
||||
private readonly clientCapabilities?: ACPClientCapabilities;
|
||||
private readonly clientCapabilityMeta?: ACPClientCapabilityMeta;
|
||||
private readonly modeIdTransformer?: (modeId: string) => string | null;
|
||||
@@ -1700,6 +1723,7 @@ export class ACPAgentSession implements AgentSession, ACPClient {
|
||||
private readonly terminalEntries = new Map<string, TerminalEntry>();
|
||||
private readonly persistedHistory: AgentTimelineItem[] = [];
|
||||
private readonly initialHandle?: AgentPersistenceHandle;
|
||||
private readonly resumePurpose: AgentResumePurpose;
|
||||
|
||||
private readonly config: AgentSessionConfig;
|
||||
private child: ChildProcessWithoutNullStreams | null = null;
|
||||
@@ -1742,6 +1766,7 @@ export class ACPAgentSession implements AgentSession, ACPClient {
|
||||
this.sessionResponseTransformer = options.sessionResponseTransformer;
|
||||
this.configOptionsTransformer = options.configOptionsTransformer;
|
||||
this.configFeatureOptions = options.configFeatureOptions ?? [];
|
||||
this.configuredModelIds = new Set(options.configuredModelIds);
|
||||
this.clientCapabilities = options.clientCapabilities;
|
||||
this.clientCapabilityMeta = options.clientCapabilityMeta;
|
||||
this.modeIdTransformer = options.modeIdTransformer;
|
||||
@@ -1753,6 +1778,7 @@ export class ACPAgentSession implements AgentSession, ACPClient {
|
||||
this.agentId = options.agentId;
|
||||
this.launchEnv = options.launchEnv;
|
||||
this.initialHandle = options.handle;
|
||||
this.resumePurpose = options.resumePurpose ?? "interactive";
|
||||
this.config = { ...config, provider: options.provider };
|
||||
this.currentMode = config.modeId ?? null;
|
||||
this.currentModel = config.model ?? null;
|
||||
@@ -2175,12 +2201,20 @@ export class ACPAgentSession implements AgentSession, ACPClient {
|
||||
return;
|
||||
}
|
||||
|
||||
await this.setModelWithSelection({ modelId, selection: this.resolveModelSelection(modelId) });
|
||||
}
|
||||
|
||||
private resolveModelSelection(modelId: string): ACPModelSelection {
|
||||
const selection = resolveACPModelSelection({
|
||||
modelId,
|
||||
availableModels: this.availableModels,
|
||||
configOptions: this.configOptions,
|
||||
});
|
||||
await this.setModelWithSelection({ modelId, selection });
|
||||
if (selection.availableModel || !this.configuredModelIds.has(modelId)) {
|
||||
return selection;
|
||||
}
|
||||
// A model the user added in provider config is applied even when the agent does not advertise it.
|
||||
return { ...selection, availableModel: { modelId, name: modelId } };
|
||||
}
|
||||
|
||||
private async setModelWithSelection({
|
||||
@@ -2194,21 +2228,20 @@ export class ACPAgentSession implements AgentSession, ACPClient {
|
||||
throw new Error("ACP session not initialized");
|
||||
}
|
||||
|
||||
if (selection.hasAvailableModels) {
|
||||
if (!selection.availableModel) {
|
||||
this.warnInvalidSelection(
|
||||
modelId,
|
||||
`is not a valid ${this.provider} model. Available options: ${this.availableModels
|
||||
?.map((model) => model.modelId)
|
||||
.join(", ")}`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof this.connection.unstable_setSessionModel !== "function") {
|
||||
throw new Error(this.modelSelectionUnavailableMessage());
|
||||
}
|
||||
if (selection.hasAvailableModels && !selection.availableModel) {
|
||||
this.warnInvalidSelection(
|
||||
modelId,
|
||||
`is not a valid ${this.provider} model. Available options: ${this.availableModels
|
||||
?.map((model) => model.modelId)
|
||||
.join(", ")}`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
selection.availableModel &&
|
||||
typeof this.connection.unstable_setSessionModel === "function"
|
||||
) {
|
||||
try {
|
||||
await this.connection.unstable_setSessionModel({
|
||||
sessionId: this.sessionId,
|
||||
@@ -2770,6 +2803,16 @@ export class ACPAgentSession implements AgentSession, ACPClient {
|
||||
return {};
|
||||
}
|
||||
|
||||
// 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<string> {
|
||||
if (this.resumePurpose !== "history" || (await isDirectory(this.config.cwd))) {
|
||||
return this.config.cwd;
|
||||
}
|
||||
return homedir();
|
||||
}
|
||||
|
||||
private async spawnProcess(): Promise<SpawnedACPProcess> {
|
||||
const prefix = await resolveProviderLaunch({
|
||||
commandConfig: this.runtimeSettings?.command,
|
||||
@@ -2783,7 +2826,7 @@ export class ACPAgentSession implements AgentSession, ACPClient {
|
||||
const command = prefix.command;
|
||||
const args = [...prefix.args, ...this.defaultCommand.slice(1)];
|
||||
const child = spawnProcess(command, args, {
|
||||
cwd: this.config.cwd,
|
||||
cwd: await this.resolveProcessCwd(),
|
||||
...createProviderEnvSpec({
|
||||
runtimeSettings: this.runtimeSettings,
|
||||
overlays: [this.launchEnv],
|
||||
@@ -2893,13 +2936,11 @@ export class ACPAgentSession implements AgentSession, ACPClient {
|
||||
const configuredModelId = this.config.model;
|
||||
let switchedModel = false;
|
||||
if (configuredModelId && configuredModelId !== this.currentModel) {
|
||||
const selection = resolveACPModelSelection({
|
||||
modelId: configuredModelId,
|
||||
availableModels: this.availableModels,
|
||||
configOptions: this.configOptions,
|
||||
});
|
||||
try {
|
||||
await this.setModelWithSelection({ modelId: configuredModelId, selection });
|
||||
await this.setModelWithSelection({
|
||||
modelId: configuredModelId,
|
||||
selection: this.resolveModelSelection(configuredModelId),
|
||||
});
|
||||
switchedModel = true;
|
||||
} catch (error) {
|
||||
if (!this.isModelSelectionUnavailableError(error)) {
|
||||
|
||||
@@ -31,6 +31,7 @@ function createQueryMock(events: unknown[]): Query {
|
||||
describe("Claude SDK env", () => {
|
||||
test("forwards launch-context env through Claude process env", async () => {
|
||||
let capturedEnv: Record<string, string | undefined> | undefined;
|
||||
let capturedPerTaskStopAffordance: boolean | undefined;
|
||||
const launchContext: AgentLaunchContext = {
|
||||
env: {
|
||||
PASEO_AGENT_ID: "00000000-0000-4000-8000-000000000201",
|
||||
@@ -39,6 +40,7 @@ describe("Claude SDK env", () => {
|
||||
};
|
||||
const queryFactory = vi.fn(({ options }: ClaudeQueryInput) => {
|
||||
capturedEnv = options.env;
|
||||
capturedPerTaskStopAffordance = options.perTaskStopAffordance;
|
||||
return createQueryMock([
|
||||
{
|
||||
type: "system",
|
||||
@@ -91,6 +93,10 @@ describe("Claude SDK env", () => {
|
||||
expect(capturedEnv?.MCP_TIMEOUT).toBe("claude-startup-timeout");
|
||||
expect(capturedEnv?.MCP_TOOL_TIMEOUT).toBe("claude-tool-timeout");
|
||||
expect(session.usageSession?.()?.env).toBe(capturedEnv);
|
||||
// Paseo reads session_state_changed to know when an autonomous turn is over.
|
||||
expect(capturedEnv?.CLAUDE_CODE_EMIT_SESSION_STATE_EVENTS).toBe("1");
|
||||
// Without it, Stop and replace kill every background subagent along with the turn.
|
||||
expect(capturedPerTaskStopAffordance).toBe(true);
|
||||
} finally {
|
||||
await session.close();
|
||||
expect(session.usageSession?.()).toBeNull();
|
||||
|
||||
+60
-20
@@ -91,6 +91,17 @@ function buildUsage() {
|
||||
};
|
||||
}
|
||||
|
||||
/** Claude opening a turn of its own. Every main-session turn starts with one. */
|
||||
function buildTurnInit(sessionId: string) {
|
||||
return {
|
||||
type: "system",
|
||||
subtype: "init",
|
||||
session_id: sessionId,
|
||||
permissionMode: "default",
|
||||
model: "opus",
|
||||
};
|
||||
}
|
||||
|
||||
function buildSuccessResult(sessionId: string) {
|
||||
return {
|
||||
type: "result",
|
||||
@@ -153,13 +164,7 @@ function createScriptedQuery(params: {
|
||||
},
|
||||
} satisfies ScriptedQuery;
|
||||
|
||||
scriptedQuery.emit({
|
||||
type: "system",
|
||||
subtype: "init",
|
||||
session_id: params.sessionId,
|
||||
permissionMode: "default",
|
||||
model: "opus",
|
||||
});
|
||||
scriptedQuery.emit(buildTurnInit(params.sessionId));
|
||||
|
||||
void (async () => {
|
||||
for await (const prompt of params.prompt) {
|
||||
@@ -252,6 +257,21 @@ async function waitFor(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Paseo interrupts Claude only while a main-session turn is in flight, which it learns from the
|
||||
* init. The pump asks for its next frame only after routing the last one, so a second next() call
|
||||
* proves the init was read.
|
||||
*/
|
||||
async function waitForInitRouted(
|
||||
query: () => { next: ReturnType<typeof vi.fn> } | null | undefined,
|
||||
) {
|
||||
await waitFor(() => (query()?.next.mock.calls.length ?? 0) >= 2);
|
||||
}
|
||||
|
||||
function buildCommandLifecycle(commandUuid: string | null | undefined, state: string) {
|
||||
return { type: "command_lifecycle", command_uuid: commandUuid, state };
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
queryFactory.mockReset();
|
||||
});
|
||||
@@ -282,6 +302,7 @@ test("interrupt only calls query.interrupt and leaves the query open", async ()
|
||||
const firstTurn = streamSession(session, "first prompt");
|
||||
await firstTurn.next();
|
||||
await waitFor(() => queries[0]?.prompts.length === 1);
|
||||
await waitForInitRouted(() => queries[0]);
|
||||
|
||||
await session.interrupt();
|
||||
await waitFor(() => queries[0]?.interrupt.mock.calls.length === 1);
|
||||
@@ -322,6 +343,7 @@ async function startSteeredTurn(sessionId: string): Promise<{
|
||||
throw new Error("Expected the original Claude turn to start");
|
||||
}
|
||||
await waitFor(() => query?.prompts.length === 1);
|
||||
await waitForInitRouted(() => query);
|
||||
|
||||
const steered = await session.steerActiveTurn!("queued steer", {
|
||||
expectedTurnId: start.value.turnId,
|
||||
@@ -371,11 +393,8 @@ test("interrupt still stops the turn when Claude has already dequeued the steer"
|
||||
test("a steer Claude has already read is no longer discardable on interrupt", async () => {
|
||||
const { session, query, turn } = await startSteeredTurn("queued-steer-completed-session");
|
||||
|
||||
query()?.emit({
|
||||
type: "command_lifecycle",
|
||||
command_uuid: query()?.prompts[1]?.uuid,
|
||||
state: "completed",
|
||||
});
|
||||
query()?.emit(buildCommandLifecycle(query()?.prompts[0]?.uuid, "started"));
|
||||
query()?.emit(buildCommandLifecycle(query()?.prompts[1]?.uuid, "completed"));
|
||||
// Frames are translated in order, so the marker landing proves the lifecycle frame was read.
|
||||
query()?.emit({ type: "assistant", message: { content: "STEER_READ" } });
|
||||
await consumeUntil(turn, (event) => collectAssistantText([event]).includes("STEER_READ"));
|
||||
@@ -388,6 +407,23 @@ test("a steer Claude has already read is no longer discardable on interrupt", as
|
||||
await session.close();
|
||||
});
|
||||
|
||||
test("a steer Claude cancelled is no longer withdrawn on interrupt", async () => {
|
||||
const { session, query, turn } = await startSteeredTurn("queued-steer-cancelled-session");
|
||||
|
||||
query()?.emit(buildCommandLifecycle(query()?.prompts[0]?.uuid, "started"));
|
||||
// "cancelled" is terminal: API errors, interrupts and "now" pre-emption all end a message.
|
||||
query()?.emit(buildCommandLifecycle(query()?.prompts[1]?.uuid, "cancelled"));
|
||||
query()?.emit({ type: "assistant", message: { content: "STEER_CANCELLED" } });
|
||||
await consumeUntil(turn, (event) => collectAssistantText([event]).includes("STEER_CANCELLED"));
|
||||
|
||||
await session.interrupt();
|
||||
await waitFor(() => query()?.interrupt.mock.calls.length === 1);
|
||||
|
||||
expect(query()?.cancelAsyncMessage).not.toHaveBeenCalled();
|
||||
await collectUntilTerminal(turn);
|
||||
await session.close();
|
||||
});
|
||||
|
||||
function buildStoppedTaskNotification(sessionId: string) {
|
||||
return {
|
||||
type: "system",
|
||||
@@ -473,6 +509,7 @@ async function startInterruptedToolTurn(sessionId: string): Promise<{
|
||||
const turn = streamSession(session, "run the slow tool");
|
||||
await turn.next();
|
||||
await waitFor(() => query?.prompts.length === 1);
|
||||
await waitForInitRouted(() => query);
|
||||
|
||||
await session.interrupt();
|
||||
await collectUntilTerminal(turn);
|
||||
@@ -523,6 +560,7 @@ test("Claude can still wake into an autonomous turn once the interrupted request
|
||||
|
||||
query()?.emit(buildStoppedTaskNotification(sessionId));
|
||||
query()?.emit(buildAbortedResult(sessionId));
|
||||
query()?.emit(buildTurnInit(sessionId));
|
||||
query()?.emit({
|
||||
type: "assistant",
|
||||
message: { content: "AUTONOMOUS_WAKE_RESPONSE" },
|
||||
@@ -579,6 +617,7 @@ test("reuses the existing query after interrupt before starting the next prompt"
|
||||
const firstTurn = streamSession(session, "first prompt");
|
||||
await firstTurn.next();
|
||||
await waitFor(() => queries[0]?.prompts.length === 1);
|
||||
await waitForInitRouted(() => queries[0]);
|
||||
|
||||
await session.interrupt();
|
||||
await collectUntilTerminal(firstTurn);
|
||||
@@ -652,6 +691,7 @@ test("recovers when the query pump sees a single interrupt abort before the next
|
||||
const output = createAsyncQueue<Record<string, unknown>>();
|
||||
const prompts: PromptRecord[] = [];
|
||||
let throwAbortOnNext = false;
|
||||
let queryRef: Pick<ScriptedQuery, "next"> | null = null;
|
||||
|
||||
queryFactory.mockImplementation(({ prompt }: { prompt: AsyncIterable<unknown> }) => {
|
||||
const scriptedQuery = {
|
||||
@@ -685,13 +725,8 @@ test("recovers when the query pump sees a single interrupt abort before the next
|
||||
},
|
||||
} satisfies ScriptedQuery;
|
||||
|
||||
scriptedQuery.emit({
|
||||
type: "system",
|
||||
subtype: "init",
|
||||
session_id: "interrupt-abort-recovery-session",
|
||||
permissionMode: "default",
|
||||
model: "opus",
|
||||
});
|
||||
queryRef = scriptedQuery;
|
||||
scriptedQuery.emit(buildTurnInit("interrupt-abort-recovery-session"));
|
||||
|
||||
void (async () => {
|
||||
for await (const promptMessage of prompt) {
|
||||
@@ -730,6 +765,7 @@ test("recovers when the query pump sees a single interrupt abort before the next
|
||||
|
||||
const firstTurn = streamSession(session, "first prompt");
|
||||
await firstTurn.next();
|
||||
await waitForInitRouted(() => queryRef);
|
||||
await session.interrupt();
|
||||
await collectUntilTerminal(firstTurn);
|
||||
|
||||
@@ -768,6 +804,7 @@ test("stale abort result after replacement start does not poison the new foregro
|
||||
const firstTurn = streamSession(session, "first prompt");
|
||||
const firstStarted = await firstTurn.next();
|
||||
await waitFor(() => queryRef?.prompts.length === 1);
|
||||
await waitForInitRouted(() => queryRef);
|
||||
|
||||
await session.interrupt();
|
||||
const firstTurnEvents = [firstStarted.value!, ...(await collectUntilTerminal(firstTurn))];
|
||||
@@ -812,7 +849,7 @@ test("stale abort result after replacement start does not poison the new foregro
|
||||
await session.close();
|
||||
});
|
||||
|
||||
test("creates an autonomous live turn when assistant output arrives without a foreground run", async () => {
|
||||
test("creates an autonomous live turn when Claude starts a turn without a foreground run", async () => {
|
||||
const logger = createTestLogger();
|
||||
let queryRef: ScriptedQuery | null = null;
|
||||
|
||||
@@ -848,6 +885,7 @@ test("creates an autonomous live turn when assistant output arrives without a fo
|
||||
await collectUntilTerminal(streamSession(session, "seed prompt"));
|
||||
|
||||
const subscribedEvents = subscribeToEvents(session);
|
||||
queryRef?.emit(buildTurnInit("autonomous-live-session"));
|
||||
queryRef?.emit({
|
||||
type: "assistant",
|
||||
message: { content: "AUTONOMOUS_WAKE_RESPONSE" },
|
||||
@@ -916,6 +954,7 @@ test("steers an autonomous turn through its existing query without restarting it
|
||||
|
||||
await collectUntilTerminal(streamSession(session, "seed prompt"));
|
||||
const autonomousEvents = subscribeToEvents(session);
|
||||
queryRef?.emit(buildTurnInit("autonomous-steer-session"));
|
||||
queryRef?.emit({
|
||||
type: "assistant",
|
||||
message: { content: "AUTONOMOUS_RESPONSE" },
|
||||
@@ -999,6 +1038,7 @@ test("auto-completes an open autonomous turn when a foreground prompt starts", a
|
||||
await collectUntilTerminal(streamSession(session, "seed prompt"));
|
||||
|
||||
const subscribedEvents = subscribeToEvents(session);
|
||||
queryRef?.emit(buildTurnInit("autonomous-handoff-session"));
|
||||
queryRef?.emit({
|
||||
type: "assistant",
|
||||
message: { content: "BACKGROUND_ONLY_RESPONSE" },
|
||||
|
||||
@@ -327,6 +327,57 @@ test("fails an auto mode turn when Claude Code uses Vertex", async () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("switches an auto mode session to another mode when Claude Code uses Bedrock", async () => {
|
||||
const previousBedrock = process.env.CLAUDE_CODE_USE_BEDROCK;
|
||||
process.env.CLAUDE_CODE_USE_BEDROCK = "1";
|
||||
const queryMock = createBaseQueryMock(vi.fn(async () => ({ done: true, value: undefined })));
|
||||
sdkQueryFactory.mockImplementation(() => queryMock);
|
||||
const client = new ClaudeAgentClient({
|
||||
logger: createTestLogger(),
|
||||
queryFactory: sdkQueryFactory,
|
||||
resolveBinary: async () => "/test/claude/bin",
|
||||
});
|
||||
const session = await client.createSession({
|
||||
provider: "claude",
|
||||
cwd: process.cwd(),
|
||||
modeId: "auto",
|
||||
});
|
||||
|
||||
try {
|
||||
await session.setMode("acceptEdits");
|
||||
|
||||
expect(await session.getCurrentMode()).toBe("acceptEdits");
|
||||
expect(sdkQueryFactory).toHaveBeenCalledTimes(1);
|
||||
expect(sdkQueryFactory.mock.calls[0]?.[0]?.options?.permissionMode).toBe("acceptEdits");
|
||||
} finally {
|
||||
restoreEnvValue("CLAUDE_CODE_USE_BEDROCK", previousBedrock);
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("does not keep a query started in a mode that Claude Code rejected", async () => {
|
||||
const launchedModes: Array<string | undefined> = [];
|
||||
sdkQueryFactory.mockImplementation(({ options }: { options: { permissionMode?: string } }) => {
|
||||
launchedModes.push(options.permissionMode);
|
||||
const queryMock = createBaseQueryMock(vi.fn(async () => ({ done: true, value: undefined })));
|
||||
if (launchedModes.length === 1) {
|
||||
queryMock.setPermissionMode.mockRejectedValue(new Error("bypass refused"));
|
||||
}
|
||||
return queryMock;
|
||||
});
|
||||
const session = await createSession();
|
||||
|
||||
try {
|
||||
await expect(session.setMode("bypassPermissions")).rejects.toThrow("bypass refused");
|
||||
await session.listCommands();
|
||||
|
||||
expect(await session.getCurrentMode()).toBe("default");
|
||||
expect(launchedModes).toEqual(["bypassPermissions", "default"]);
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("logs redacted query summary and never leaks sentinel secrets", async () => {
|
||||
const envSecret = "PASEO_ENV_SENTINEL_SECRET";
|
||||
const runtimeSecret = "PASEO_RUNTIME_SENTINEL_SECRET";
|
||||
@@ -435,6 +486,7 @@ test("interruptActiveTurn only interrupts the active query without info logs", a
|
||||
} | null;
|
||||
input: { end: () => void } | null;
|
||||
queryRestartNeeded: boolean;
|
||||
mainTurnInFlight: boolean;
|
||||
interruptActiveTurn: () => Promise<void>;
|
||||
} = asInternals(session);
|
||||
const interrupt = vi.fn(async () => undefined);
|
||||
@@ -447,6 +499,7 @@ test("interruptActiveTurn only interrupts the active query without info logs", a
|
||||
};
|
||||
internal.input = { end };
|
||||
internal.queryRestartNeeded = false;
|
||||
internal.mainTurnInFlight = true;
|
||||
|
||||
try {
|
||||
await internal.interruptActiveTurn();
|
||||
@@ -1037,11 +1090,11 @@ test("preserves bypass capability across query restarts triggered by thinking ch
|
||||
|
||||
expect(capturedOptions).toHaveLength(2);
|
||||
expect(capturedOptions[0]).toMatchObject({
|
||||
permissionMode: "default",
|
||||
permissionMode: "bypassPermissions",
|
||||
allowDangerouslySkipPermissions: true,
|
||||
});
|
||||
expect(capturedOptions[1]).toMatchObject({
|
||||
permissionMode: "acceptEdits",
|
||||
permissionMode: "bypassPermissions",
|
||||
allowDangerouslySkipPermissions: true,
|
||||
effort: "high",
|
||||
});
|
||||
@@ -1140,6 +1193,7 @@ test("reuses one autonomous run for unbound stream_event bursts with no foregrou
|
||||
const queryMock = createBaseQueryMock(vi.fn(async () => ({ done: true, value: undefined })));
|
||||
|
||||
internal.turnState = "idle";
|
||||
await internal.routeSdkMessageFromPump(claudeTurnInit(), queryMock);
|
||||
await internal.routeSdkMessageFromPump(
|
||||
{
|
||||
type: "stream_event",
|
||||
@@ -1182,6 +1236,468 @@ test("reuses one autonomous run for unbound stream_event bursts with no foregrou
|
||||
await session.close();
|
||||
});
|
||||
|
||||
interface SessionStateInternals {
|
||||
turnState: "idle" | "foreground" | "autonomous";
|
||||
routeSdkMessageFromPump: (
|
||||
message: Record<string, unknown>,
|
||||
activeQuery: QueryMock,
|
||||
) => Promise<void>;
|
||||
autonomousTurn: { id: string } | null;
|
||||
activeForegroundTurnId: string | null;
|
||||
}
|
||||
|
||||
function sessionState(state: "idle" | "running" | "requires_action") {
|
||||
return {
|
||||
type: "system",
|
||||
subtype: "session_state_changed",
|
||||
state,
|
||||
uuid: `state-${state}`,
|
||||
session_id: "sess-1",
|
||||
};
|
||||
}
|
||||
|
||||
/** Claude opening a turn of its own. Every main-session turn starts with one. */
|
||||
function claudeTurnInit() {
|
||||
return {
|
||||
type: "system",
|
||||
subtype: "init",
|
||||
session_id: "sess-1",
|
||||
permissionMode: "default",
|
||||
model: "opus",
|
||||
};
|
||||
}
|
||||
|
||||
function successResult() {
|
||||
return { type: "result", subtype: "success", usage: buildUsage(), total_cost_usd: 0 };
|
||||
}
|
||||
|
||||
function commandLifecycle(
|
||||
commandUuid: string,
|
||||
state: "queued" | "started" | "completed" | "cancelled",
|
||||
) {
|
||||
return { type: "command_lifecycle", command_uuid: commandUuid, state };
|
||||
}
|
||||
|
||||
function unboundTextDelta(text: string) {
|
||||
return {
|
||||
type: "stream_event",
|
||||
parent_tool_use_id: null,
|
||||
event: { type: "content_block_delta", delta: { type: "text_delta", text } },
|
||||
};
|
||||
}
|
||||
|
||||
// What a background subagent emits on the main stream with no parent tool use id, so by frame
|
||||
// shape alone each looks like main-session work. Verified on the wire: none arrives inside a turn
|
||||
// Claude opened, and no result follows any of them.
|
||||
const helperTaskStarted = {
|
||||
type: "system",
|
||||
subtype: "task_started",
|
||||
task_id: "helper-task",
|
||||
tool_use_id: "toolu_helper",
|
||||
task_type: "local_agent",
|
||||
subagent_type: "general-purpose",
|
||||
description: "Background helper",
|
||||
is_backgrounded: true,
|
||||
uuid: "uuid-task-started",
|
||||
session_id: "sess-1",
|
||||
};
|
||||
const helperTaskProgress = {
|
||||
type: "system",
|
||||
subtype: "task_progress",
|
||||
task_id: "helper-task",
|
||||
tool_use_id: "toolu_helper",
|
||||
description: "Background helper",
|
||||
usage: { total_tokens: 1200, tool_uses: 3, duration_ms: 900 },
|
||||
last_tool_name: "Bash",
|
||||
uuid: "uuid-task-progress",
|
||||
session_id: "sess-1",
|
||||
};
|
||||
// A subagent's own background Bash job completing.
|
||||
const subagentOwnedTaskNotification = {
|
||||
type: "system",
|
||||
subtype: "task_notification",
|
||||
task_id: "bg-job-of-subagent",
|
||||
tool_use_id: "toolu_subagent_bash",
|
||||
status: "completed",
|
||||
summary: "Background command completed",
|
||||
output_file: "/tmp/bg-job-of-subagent.output",
|
||||
uuid: "uuid-task-notification",
|
||||
session_id: "sess-1",
|
||||
};
|
||||
const helperCompleted = {
|
||||
type: "system",
|
||||
subtype: "task_notification",
|
||||
task_id: "helper-task",
|
||||
tool_use_id: "toolu_helper",
|
||||
status: "completed",
|
||||
summary: "Background helper finished",
|
||||
output_file: "/tmp/helper-task.output",
|
||||
uuid: "uuid-helper-completed",
|
||||
session_id: "sess-1",
|
||||
};
|
||||
const rateLimitEvent = {
|
||||
type: "rate_limit_event",
|
||||
rate_limit_info: { status: "allowed" },
|
||||
uuid: "uuid-rate-limit",
|
||||
session_id: "sess-1",
|
||||
};
|
||||
|
||||
function createPendingQueryMock(): QueryMock {
|
||||
return createBaseQueryMock(vi.fn(() => new Promise<never>(() => {})));
|
||||
}
|
||||
|
||||
test("a main-session frame opens no turn until Claude starts one", async () => {
|
||||
const session = await createSession();
|
||||
const internal: SessionStateInternals = asInternals(session);
|
||||
const queryMock = createPendingQueryMock();
|
||||
|
||||
// Main-session output only ever arrives inside a turn Claude opened with system/init, so a
|
||||
// stray unbound frame is not the start of one.
|
||||
await internal.routeSdkMessageFromPump(unboundTextDelta("stray"), queryMock);
|
||||
expect(internal.autonomousTurn).toBeNull();
|
||||
|
||||
// The wake-up case autonomous turns exist for: a completed background subagent makes the main
|
||||
// session start a turn of its own, with no prompt from the user.
|
||||
await internal.routeSdkMessageFromPump(claudeTurnInit(), queryMock);
|
||||
await internal.routeSdkMessageFromPump(unboundTextDelta("picking this up"), queryMock);
|
||||
expect(internal.autonomousTurn?.id).toBe("autonomous-turn-1");
|
||||
|
||||
await internal.routeSdkMessageFromPump(successResult(), queryMock);
|
||||
expect(internal.autonomousTurn).toBeNull();
|
||||
|
||||
await session.close();
|
||||
});
|
||||
|
||||
test("a background subagent's frames never open a turn while the main session is idle", async () => {
|
||||
sdkQueryFactory.mockImplementation(() => createPendingQueryMock());
|
||||
const session = await createSession();
|
||||
const internal: SessionStateInternals = asInternals(session);
|
||||
const queryMock = createPendingQueryMock();
|
||||
|
||||
// Claude Code 2.1.280 reports "running" for as long as any background subagent is alive.
|
||||
await internal.routeSdkMessageFromPump(sessionState("running"), queryMock);
|
||||
for (const frame of [
|
||||
helperTaskStarted,
|
||||
helperTaskProgress,
|
||||
subagentOwnedTaskNotification,
|
||||
rateLimitEvent,
|
||||
helperCompleted,
|
||||
]) {
|
||||
await internal.routeSdkMessageFromPump(frame, queryMock);
|
||||
expect(internal.autonomousTurn).toBeNull();
|
||||
expect(internal.turnState).toBe("idle");
|
||||
}
|
||||
|
||||
// The next user message starts its own foreground turn rather than landing on a phantom one.
|
||||
const { turnId } = await session.startTurn("PING");
|
||||
expect(internal.activeForegroundTurnId).toBe(turnId);
|
||||
expect(internal.autonomousTurn).toBeNull();
|
||||
expect(internal.turnState).toBe("foreground");
|
||||
|
||||
await session.close();
|
||||
});
|
||||
|
||||
test("Claude waking up after a helper finishes gets an autonomous turn that its result closes", async () => {
|
||||
const session = await createSession();
|
||||
const internal: SessionStateInternals = asInternals(session);
|
||||
const queryMock = createPendingQueryMock();
|
||||
const events: AgentStreamEvent[] = [];
|
||||
session.subscribe((event) => events.push(event));
|
||||
|
||||
// The helper's completion arrives outside any turn. Claude then starts one to react to it.
|
||||
await internal.routeSdkMessageFromPump(helperTaskStarted, queryMock);
|
||||
await internal.routeSdkMessageFromPump(helperCompleted, queryMock);
|
||||
expect(internal.autonomousTurn).toBeNull();
|
||||
|
||||
await internal.routeSdkMessageFromPump(claudeTurnInit(), queryMock);
|
||||
expect(internal.autonomousTurn?.id).toBe("autonomous-turn-1");
|
||||
expect(internal.turnState).toBe("autonomous");
|
||||
|
||||
await internal.routeSdkMessageFromPump(unboundTextDelta("the helper is done"), queryMock);
|
||||
await internal.routeSdkMessageFromPump(successResult(), queryMock);
|
||||
expect(internal.autonomousTurn).toBeNull();
|
||||
expect(internal.turnState).toBe("idle");
|
||||
expect(events.filter((event) => event.type === "turn_started")).toHaveLength(1);
|
||||
expect(events.filter((event) => event.type === "turn_completed")).toHaveLength(1);
|
||||
|
||||
await session.close();
|
||||
});
|
||||
|
||||
test("a steer folded into a turn keeps one turn, and a turn Claude starts after it gets its own", async () => {
|
||||
sdkQueryFactory.mockImplementation(() => createPendingQueryMock());
|
||||
const session = await createSession();
|
||||
const internal: SessionStateInternals = asInternals(session);
|
||||
const queryMock = createPendingQueryMock();
|
||||
const events: AgentStreamEvent[] = [];
|
||||
session.subscribe((event) => events.push(event));
|
||||
|
||||
const { turnId } = await session.startTurn("hello");
|
||||
await internal.routeSdkMessageFromPump(claudeTurnInit(), queryMock);
|
||||
// A message pushed mid-turn is folded in at the next tool boundary: Claude acknowledges it, but
|
||||
// starts no new turn.
|
||||
await internal.routeSdkMessageFromPump(commandLifecycle("folded-steer", "queued"), queryMock);
|
||||
await internal.routeSdkMessageFromPump(commandLifecycle("folded-steer", "started"), queryMock);
|
||||
expect(internal.activeForegroundTurnId).toBe(turnId);
|
||||
expect(internal.autonomousTurn).toBeNull();
|
||||
|
||||
await internal.routeSdkMessageFromPump(successResult(), queryMock);
|
||||
expect(internal.activeForegroundTurnId).toBeNull();
|
||||
expect(internal.turnState).toBe("idle");
|
||||
|
||||
// A message that arrived while Claude wrote its final answer runs as a turn of its own.
|
||||
await internal.routeSdkMessageFromPump(claudeTurnInit(), queryMock);
|
||||
expect(internal.autonomousTurn?.id).toBe("autonomous-turn-2");
|
||||
await internal.routeSdkMessageFromPump(successResult(), queryMock);
|
||||
expect(internal.autonomousTurn).toBeNull();
|
||||
expect(internal.turnState).toBe("idle");
|
||||
expect(events.filter((event) => event.type === "turn_started")).toHaveLength(2);
|
||||
expect(events.filter((event) => event.type === "turn_completed")).toHaveLength(2);
|
||||
|
||||
await session.close();
|
||||
});
|
||||
|
||||
test("session state never opens a turn", async () => {
|
||||
const session = await createSession();
|
||||
const internal: SessionStateInternals = asInternals(session);
|
||||
const queryMock = createPendingQueryMock();
|
||||
const events: AgentStreamEvent[] = [];
|
||||
session.subscribe((event) => events.push(event));
|
||||
|
||||
// "running" covers background subagents too, so it says nothing about the main session.
|
||||
for (const state of ["idle", "running", "requires_action", "idle"] as const) {
|
||||
await internal.routeSdkMessageFromPump(sessionState(state), queryMock);
|
||||
expect(internal.autonomousTurn).toBeNull();
|
||||
expect(internal.turnState).toBe("idle");
|
||||
}
|
||||
// State frames are bookkeeping, never timeline content.
|
||||
expect(events).toEqual([]);
|
||||
|
||||
await session.close();
|
||||
});
|
||||
|
||||
test("an idle session state closes an autonomous turn that no result closed", async () => {
|
||||
const session = await createSession();
|
||||
const internal: SessionStateInternals = asInternals(session);
|
||||
const queryMock = createPendingQueryMock();
|
||||
const events: AgentStreamEvent[] = [];
|
||||
session.subscribe((event) => events.push(event));
|
||||
|
||||
await internal.routeSdkMessageFromPump(claudeTurnInit(), queryMock);
|
||||
expect(internal.autonomousTurn?.id).toBe("autonomous-turn-1");
|
||||
|
||||
// Safety net: Claude says nothing at all is running any more.
|
||||
await internal.routeSdkMessageFromPump(sessionState("idle"), queryMock);
|
||||
expect(internal.autonomousTurn).toBeNull();
|
||||
expect(internal.turnState).toBe("idle");
|
||||
expect(events.filter((event) => event.type === "turn_completed")).toHaveLength(1);
|
||||
|
||||
await session.close();
|
||||
});
|
||||
|
||||
test("session state never opens or closes a foreground turn", async () => {
|
||||
sdkQueryFactory.mockImplementation(() => createPendingQueryMock());
|
||||
const session = await createSession();
|
||||
const internal: SessionStateInternals = asInternals(session);
|
||||
const queryMock = createPendingQueryMock();
|
||||
|
||||
await internal.routeSdkMessageFromPump(sessionState("idle"), queryMock);
|
||||
const { turnId } = await session.startTurn("hello");
|
||||
|
||||
// The send's own running, then an idle that trails the previous turn and lands late.
|
||||
await internal.routeSdkMessageFromPump(sessionState("running"), queryMock);
|
||||
await internal.routeSdkMessageFromPump(sessionState("idle"), queryMock);
|
||||
expect(internal.activeForegroundTurnId).toBe(turnId);
|
||||
expect(internal.autonomousTurn).toBeNull();
|
||||
expect(internal.turnState).toBe("foreground");
|
||||
|
||||
await internal.routeSdkMessageFromPump(
|
||||
{ type: "result", subtype: "success", usage: buildUsage(), total_cost_usd: 0 },
|
||||
queryMock,
|
||||
);
|
||||
expect(internal.activeForegroundTurnId).toBeNull();
|
||||
expect(internal.turnState).toBe("idle");
|
||||
|
||||
await session.close();
|
||||
});
|
||||
|
||||
interface InterruptInternals extends SessionStateInternals {
|
||||
pendingInterruptAbort: boolean;
|
||||
}
|
||||
|
||||
type InterruptibleQueryMock = QueryMock & { cancelAsyncMessage: ReturnType<typeof vi.fn> };
|
||||
|
||||
function createInterruptibleQueryMock(): InterruptibleQueryMock {
|
||||
return Object.assign(createPendingQueryMock(), {
|
||||
cancelAsyncMessage: vi.fn(async () => true),
|
||||
});
|
||||
}
|
||||
|
||||
/** The uuid Paseo stamped on the first message it pushed into the SDK input. */
|
||||
async function readFirstPromptUuid(): Promise<string | null> {
|
||||
const input = sdkQueryFactory.mock.calls[0]?.[0] as { prompt: AsyncIterable<unknown> };
|
||||
return await createPromptUuidReader(input.prompt)();
|
||||
}
|
||||
|
||||
function abortedResult() {
|
||||
return {
|
||||
type: "result",
|
||||
subtype: "error_during_execution",
|
||||
errors: [],
|
||||
usage: buildUsage(),
|
||||
total_cost_usd: 0,
|
||||
};
|
||||
}
|
||||
|
||||
test("an interrupt before Claude starts the message withdraws it instead of interrupting", async () => {
|
||||
const queryMock = createInterruptibleQueryMock();
|
||||
sdkQueryFactory.mockImplementation(() => queryMock);
|
||||
const session = await createSession();
|
||||
const internal: InterruptInternals = asInternals(session);
|
||||
const events: AgentStreamEvent[] = [];
|
||||
session.subscribe((event) => events.push(event));
|
||||
|
||||
await session.startTurn("hello");
|
||||
// Claude has not acknowledged the message yet: no init, no command_lifecycle "started".
|
||||
await session.interrupt();
|
||||
|
||||
await vi.waitFor(() => expect(queryMock.cancelAsyncMessage).toHaveBeenCalledTimes(1));
|
||||
expect(queryMock.cancelAsyncMessage).toHaveBeenCalledWith(await readFirstPromptUuid());
|
||||
expect(queryMock.interrupt).not.toHaveBeenCalled();
|
||||
// No result follows an interrupt that never happened, so no flag may wait for one.
|
||||
expect(internal.pendingInterruptAbort).toBe(false);
|
||||
expect(events.filter((event) => event.type === "turn_canceled")).toHaveLength(1);
|
||||
|
||||
await session.close();
|
||||
});
|
||||
|
||||
test("an interrupt after Claude took the message but before it started stops it", async () => {
|
||||
const queryMock = createInterruptibleQueryMock();
|
||||
// Claude has dequeued the message for its next turn, so withdrawing it is a no-op.
|
||||
queryMock.cancelAsyncMessage.mockImplementation(async () => false);
|
||||
sdkQueryFactory.mockImplementation(() => queryMock);
|
||||
const session = await createSession();
|
||||
const internal: InterruptInternals = asInternals(session);
|
||||
|
||||
await session.startTurn("hello");
|
||||
// No command_lifecycle "started" or init has reached Paseo yet.
|
||||
await session.interrupt();
|
||||
|
||||
await vi.waitFor(() => expect(queryMock.interrupt).toHaveBeenCalledTimes(1));
|
||||
expect(queryMock.cancelAsyncMessage).toHaveBeenCalledWith(await readFirstPromptUuid());
|
||||
expect(internal.pendingInterruptAbort).toBe(true);
|
||||
|
||||
await session.close();
|
||||
});
|
||||
|
||||
test("a prompt sent while a stopped prompt is being withdrawn is not withdrawn too", async () => {
|
||||
const queryMock = createInterruptibleQueryMock();
|
||||
let settleWithdrawal: (cancelled: boolean) => void = () => {};
|
||||
queryMock.cancelAsyncMessage.mockImplementationOnce(
|
||||
() => new Promise<boolean>((resolve) => (settleWithdrawal = resolve)),
|
||||
);
|
||||
sdkQueryFactory.mockImplementation(() => queryMock);
|
||||
const session = await createSession();
|
||||
|
||||
await session.startTurn("first");
|
||||
const firstUuid = await readFirstPromptUuid();
|
||||
await session.interrupt();
|
||||
await vi.waitFor(() => expect(queryMock.cancelAsyncMessage).toHaveBeenCalledTimes(1));
|
||||
|
||||
await session.startTurn("second");
|
||||
settleWithdrawal(false);
|
||||
|
||||
await vi.waitFor(() => expect(queryMock.interrupt).toHaveBeenCalledTimes(1));
|
||||
expect(queryMock.cancelAsyncMessage).toHaveBeenCalledTimes(1);
|
||||
expect(queryMock.cancelAsyncMessage).toHaveBeenCalledWith(firstUuid);
|
||||
|
||||
await session.close();
|
||||
});
|
||||
|
||||
test("an interrupt while only background subagents run never reaches Claude", async () => {
|
||||
const queryMock = createInterruptibleQueryMock();
|
||||
sdkQueryFactory.mockImplementation(() => queryMock);
|
||||
const session = await createSession();
|
||||
const internal: InterruptInternals = asInternals(session);
|
||||
|
||||
await session.startTurn("delegate to a helper");
|
||||
const promptUuid = await readFirstPromptUuid();
|
||||
await internal.routeSdkMessageFromPump(commandLifecycle(promptUuid ?? "", "started"), queryMock);
|
||||
await internal.routeSdkMessageFromPump(claudeTurnInit(), queryMock);
|
||||
await internal.routeSdkMessageFromPump(helperTaskStarted, queryMock);
|
||||
await internal.routeSdkMessageFromPump(successResult(), queryMock);
|
||||
// The main session is done; its helper keeps working.
|
||||
await internal.routeSdkMessageFromPump(sessionState("running"), queryMock);
|
||||
await internal.routeSdkMessageFromPump(helperTaskProgress, queryMock);
|
||||
|
||||
// Without perTaskStopAffordance, an interrupt here kills every running helper.
|
||||
await session.interrupt();
|
||||
|
||||
expect(queryMock.interrupt).not.toHaveBeenCalled();
|
||||
expect(queryMock.cancelAsyncMessage).not.toHaveBeenCalled();
|
||||
expect(internal.pendingInterruptAbort).toBe(false);
|
||||
|
||||
await session.close();
|
||||
});
|
||||
|
||||
test("an interrupt during a main turn interrupts Claude once and drops the aborted result", async () => {
|
||||
const queryMock = createInterruptibleQueryMock();
|
||||
sdkQueryFactory.mockImplementation(() => queryMock);
|
||||
const session = await createSession();
|
||||
const internal: InterruptInternals = asInternals(session);
|
||||
const events: AgentStreamEvent[] = [];
|
||||
session.subscribe((event) => events.push(event));
|
||||
|
||||
await session.startTurn("long task");
|
||||
const promptUuid = await readFirstPromptUuid();
|
||||
await internal.routeSdkMessageFromPump(commandLifecycle(promptUuid ?? "", "started"), queryMock);
|
||||
await internal.routeSdkMessageFromPump(claudeTurnInit(), queryMock);
|
||||
|
||||
await session.interrupt();
|
||||
await vi.waitFor(() => expect(queryMock.interrupt).toHaveBeenCalledTimes(1));
|
||||
// Claude already started the message, so there is nothing to withdraw.
|
||||
expect(queryMock.cancelAsyncMessage).not.toHaveBeenCalled();
|
||||
expect(internal.pendingInterruptAbort).toBe(true);
|
||||
|
||||
// A replacement starts before the aborted turn reports its result.
|
||||
const { turnId } = await session.startTurn("replacement");
|
||||
await internal.routeSdkMessageFromPump(abortedResult(), queryMock);
|
||||
expect(internal.activeForegroundTurnId).toBe(turnId);
|
||||
expect(internal.pendingInterruptAbort).toBe(false);
|
||||
expect(events.filter((event) => event.type === "turn_failed")).toHaveLength(0);
|
||||
|
||||
await internal.routeSdkMessageFromPump(claudeTurnInit(), queryMock);
|
||||
await internal.routeSdkMessageFromPump(successResult(), queryMock);
|
||||
expect(internal.activeForegroundTurnId).toBeNull();
|
||||
expect(queryMock.interrupt).toHaveBeenCalledTimes(1);
|
||||
|
||||
await session.close();
|
||||
});
|
||||
|
||||
test("a new turn clears an interrupt flag no result will consume", async () => {
|
||||
const session = await createSession();
|
||||
const internal: InterruptInternals = asInternals(session);
|
||||
const queryMock = createPendingQueryMock();
|
||||
const events: AgentStreamEvent[] = [];
|
||||
session.subscribe((event) => events.push(event));
|
||||
|
||||
// An interrupt that landed just after its turn had ended: Claude emits no result for it.
|
||||
internal.pendingInterruptAbort = true;
|
||||
|
||||
await internal.routeSdkMessageFromPump(claudeTurnInit(), queryMock);
|
||||
expect(internal.pendingInterruptAbort).toBe(false);
|
||||
expect(internal.autonomousTurn?.id).toBe("autonomous-turn-1");
|
||||
|
||||
// This turn's own failure is reported, not swallowed as the interrupted turn's leftover.
|
||||
await internal.routeSdkMessageFromPump(
|
||||
{ ...abortedResult(), errors: ["API Error: 500 upstream failure"] },
|
||||
queryMock,
|
||||
);
|
||||
expect(events.filter((event) => event.type === "turn_failed")).toHaveLength(1);
|
||||
expect(internal.autonomousTurn).toBeNull();
|
||||
|
||||
await session.close();
|
||||
});
|
||||
|
||||
test("tracks run lifecycle transitions for success, error, and interrupt", async () => {
|
||||
const session = await createSession();
|
||||
let streamCase: "success" | "error" | "interrupt" = "success";
|
||||
|
||||
@@ -712,4 +712,56 @@ describe("ClaudeAgentSession persisted subagent replay", () => {
|
||||
expect(timeline.length).toBeGreaterThan(0);
|
||||
expect(timeline[0]).toMatchObject({ id: TOOL_USE_ID });
|
||||
});
|
||||
|
||||
test("replays a SubagentHandback report as the subagent's final message", async () => {
|
||||
const handbackId = "toolu_handback";
|
||||
const report = "## Verdict\n\n- **Coherent**";
|
||||
writeSession({
|
||||
parentLines: [taskToolUse(), taskToolResult()],
|
||||
meta: JSON.stringify({ toolUseId: TOOL_USE_ID }),
|
||||
sidechainLines: [
|
||||
JSON.stringify({
|
||||
type: "assistant",
|
||||
isSidechain: true,
|
||||
agentId: AGENT_ID,
|
||||
message: {
|
||||
role: "assistant",
|
||||
content: [
|
||||
{
|
||||
type: "tool_use",
|
||||
id: handbackId,
|
||||
name: "SubagentHandback",
|
||||
input: { message: report },
|
||||
},
|
||||
],
|
||||
},
|
||||
}),
|
||||
JSON.stringify({
|
||||
type: "user",
|
||||
isSidechain: true,
|
||||
agentId: AGENT_ID,
|
||||
message: {
|
||||
role: "user",
|
||||
content: [
|
||||
{
|
||||
type: "tool_result",
|
||||
tool_use_id: handbackId,
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: '{"success":true,"message":"Report delivered to your caller."}',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
const items = (await replayDescriptors()).flatMap((event) =>
|
||||
event.event.type === "timeline" ? [event.event.item] : [],
|
||||
);
|
||||
expect(items).toEqual([{ type: "assistant_message", text: report }]);
|
||||
});
|
||||
});
|
||||
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import pino from "pino";
|
||||
import { expect, test } from "vitest";
|
||||
|
||||
import type { AgentStreamEvent, AgentTimelineItem } from "../../agent-sdk-types.js";
|
||||
import { collectSessionTurnEvents } from "../test-utils/session-stream-adapter.js";
|
||||
import { ClaudeAgentClient } from "./agent.js";
|
||||
|
||||
const ROOT_PROMPT = `Use Claude Code's native Agent tool exactly once, never Paseo tools, with this complete task:
|
||||
|
||||
Do not use any tools. Reply with exactly this markdown report and nothing else:
|
||||
## HANDBACK_HEADING
|
||||
- **HANDBACK_BOLD** item
|
||||
|
||||
Then reply exactly ROOT_DONE.`;
|
||||
|
||||
function subagentItems(events: AgentStreamEvent[]): AgentTimelineItem[] {
|
||||
return events.flatMap((event) =>
|
||||
event.type === "provider_subagent" && event.event.type === "timeline" ? [event.event.item] : [],
|
||||
);
|
||||
}
|
||||
|
||||
function expectHandbackAsReport(items: AgentTimelineItem[]): void {
|
||||
expect(items.filter((item) => item.type === "tool_call")).toEqual([]);
|
||||
expect(
|
||||
items.flatMap((item) => (item.type === "assistant_message" ? [item.text] : [])).join(""),
|
||||
).toContain("## HANDBACK_HEADING\n- **HANDBACK_BOLD** item");
|
||||
}
|
||||
|
||||
test("an auto-mode Claude subagent's handback report shows as its final message", async () => {
|
||||
const cwd = mkdtempSync(path.join(tmpdir(), "paseo-claude-subagent-handback-"));
|
||||
const client = new ClaudeAgentClient({ logger: pino({ level: "warn" }) });
|
||||
const session = await client.createSession({ provider: "claude", cwd, modeId: "auto" });
|
||||
try {
|
||||
const events = await collectSessionTurnEvents(session, ROOT_PROMPT);
|
||||
expectHandbackAsReport(subagentItems(events));
|
||||
|
||||
const persistence = session.describePersistence();
|
||||
expect(persistence).not.toBeNull();
|
||||
await session.close();
|
||||
const restored = await client.resumeSession(persistence!, { cwd });
|
||||
try {
|
||||
const replayed: AgentStreamEvent[] = [];
|
||||
for await (const event of restored.streamHistory()) replayed.push(event);
|
||||
expectHandbackAsReport(subagentItems(replayed));
|
||||
} finally {
|
||||
await restored.close();
|
||||
}
|
||||
} finally {
|
||||
await session.close();
|
||||
rmSync(cwd, { recursive: true, force: true });
|
||||
}
|
||||
}, 240_000);
|
||||
@@ -78,7 +78,7 @@ describe("subagent lifecycle across an interrupt", () => {
|
||||
queryFactory.mockReset();
|
||||
});
|
||||
|
||||
async function startInterruptibleTurn() {
|
||||
async function startInterruptibleTurn(taskStarted: Record<string, unknown> = {}) {
|
||||
const channel = buildOpenQueryMock();
|
||||
queryFactory.mockImplementation(() => channel.query);
|
||||
const session = await new ClaudeAgentClient({
|
||||
@@ -107,6 +107,7 @@ describe("subagent lifecycle across an interrupt", () => {
|
||||
task_type: "local_agent",
|
||||
subagent_type: "general-purpose",
|
||||
description: "Reply with banana",
|
||||
...taskStarted,
|
||||
});
|
||||
await vi.waitFor(() => expect(subagentEvents.length).toBeGreaterThan(0));
|
||||
|
||||
@@ -169,6 +170,31 @@ describe("subagent lifecycle across an interrupt", () => {
|
||||
await session.close();
|
||||
});
|
||||
|
||||
test("a child spawned in the background is not canceled with the turn that spawned it", async () => {
|
||||
// Claude announces a background spawn on task_started itself and sends no task_updated patch.
|
||||
const { channel, session, subagentEvents } = await startInterruptibleTurn({
|
||||
is_backgrounded: true,
|
||||
});
|
||||
|
||||
await session.interrupt();
|
||||
channel.push({
|
||||
type: "system",
|
||||
subtype: "task_notification",
|
||||
task_id: TASK_ID,
|
||||
tool_use_id: SUBAGENT_ID,
|
||||
status: "completed",
|
||||
});
|
||||
|
||||
await vi.waitFor(() =>
|
||||
expect(subagentEvents).toContainEqual(
|
||||
expect.objectContaining({ id: SUBAGENT_ID, status: "completed" }),
|
||||
),
|
||||
);
|
||||
expect(statuses(subagentEvents, SUBAGENT_ID)).toEqual(["running", "completed"]);
|
||||
|
||||
await session.close();
|
||||
});
|
||||
|
||||
test("a foreground child is canceled with the turn that spawned it", async () => {
|
||||
const { session, subagentEvents } = await startInterruptibleTurn();
|
||||
|
||||
|
||||
@@ -3160,10 +3160,15 @@ describe("ClaudeAgentSession context window usage", () => {
|
||||
});
|
||||
|
||||
test("a compaction abandoned in an autonomous turn does not suppress the next marker", async () => {
|
||||
// Trailing output after the foreground result opens an autonomous turn, which starts
|
||||
// compacting and is then ended by the next foreground turn, never reaching a boundary.
|
||||
// Claude starts a turn of its own after the foreground result, which starts compacting and is
|
||||
// then ended by the next foreground turn, never reaching a boundary.
|
||||
const session = await createSessionForTurns([
|
||||
[createSuccessResult(), createMessageStartEvent(), createCompactingStatus()],
|
||||
[
|
||||
createSuccessResult(),
|
||||
createInitMessage(),
|
||||
createMessageStartEvent(),
|
||||
createCompactingStatus(),
|
||||
],
|
||||
[createCompactingStatus(), createSuccessResult()],
|
||||
]);
|
||||
|
||||
|
||||
@@ -44,6 +44,7 @@ import {
|
||||
} from "./model-manifest.js";
|
||||
import { parsePartialJsonObject } from "./partial-json.js";
|
||||
import { ClaudeSidechainTracker } from "./sidechain-tracker.js";
|
||||
import { readClaudeSubagentHandback } from "./subagent-handback.js";
|
||||
import { ClaudeTaskState } from "./task-state.js";
|
||||
import {
|
||||
ClaudeTaskProtocolSource,
|
||||
@@ -451,6 +452,15 @@ function errorToMessageString(error: unknown): string {
|
||||
return "";
|
||||
}
|
||||
|
||||
/**
|
||||
* Claude opens every main-session turn with system/init and closes it with exactly one result:
|
||||
* a prompt, a wake-up after background work, a slash command, an API error. Background subagents
|
||||
* never emit either on the main stream.
|
||||
*/
|
||||
function isClaudeTurnInit(message: SDKMessage): boolean {
|
||||
return message.type === "system" && message.subtype === "init";
|
||||
}
|
||||
|
||||
function firstStringField(
|
||||
input: Record<string, unknown>,
|
||||
primaryKey: string,
|
||||
@@ -2069,11 +2079,12 @@ class ClaudeAgentSession implements AgentSession {
|
||||
private activeForegroundQuery: Query | null = null;
|
||||
private activeForegroundInput: AsyncMessageInput<SDKUserMessage> | null = null;
|
||||
/**
|
||||
* Steers pushed into the live SDK input that Claude may not have read yet. Interrupting the turn
|
||||
* has to discard them, or the SDK dequeues one and resumes the turn we just stopped. SDK user
|
||||
* UUIDs are provider-private; never let them escape the adapter boundary.
|
||||
* Messages pushed into the live SDK input (steers, and a foreground turn's own prompt) whose
|
||||
* command_lifecycle has not reached "started". Interrupting has to withdraw them, or the SDK
|
||||
* dequeues one and resumes the turn we just stopped. SDK user UUIDs are provider-private; never
|
||||
* let them escape the adapter boundary.
|
||||
*/
|
||||
private readonly queuedSteerUuids = new Set<string>();
|
||||
private readonly unstartedMessageUuids = new Set<string>();
|
||||
/** Human steers whose text has not reached Claude yet and therefore supersede blocking cards. */
|
||||
private readonly permissionClearingSteerUuids = new Set<string>();
|
||||
private claudeSessionId: string | null;
|
||||
@@ -2084,6 +2095,7 @@ class ClaudeAgentSession implements AgentSession {
|
||||
private toolUseCache = new Map<string, ToolUseCacheEntry>();
|
||||
private toolUseIndexToId = new Map<number, string>();
|
||||
private toolUseInputBuffers = new Map<string, string>();
|
||||
private subagentHandbackIds = new Set<string>();
|
||||
private pendingPermissions = new Map<string, PendingPermission>();
|
||||
private activeForegroundTurnId: string | null = null;
|
||||
private autonomousTurn: AutonomousTurnState | null = null;
|
||||
@@ -2124,6 +2136,12 @@ class ClaudeAgentSession implements AgentSession {
|
||||
private queryPumpPromise: Promise<void> | null = null;
|
||||
private queryRestartNeeded = false;
|
||||
private pendingInterruptAbort = false;
|
||||
/**
|
||||
* Whether Claude's main session is inside one of its own turns: set by system/init and by a
|
||||
* pushed message's command_lifecycle "started" (/compact works for seconds before its init),
|
||||
* cleared by the turn's result or an idle session state. See observeMainTurnBracket.
|
||||
*/
|
||||
private mainTurnInFlight = false;
|
||||
private foregroundHasVisibleActivity = false;
|
||||
private activeTurnHasAssistantText = false;
|
||||
private readonly contextUsage: ClaudeContextUsageState;
|
||||
@@ -2270,6 +2288,7 @@ class ClaudeAgentSession implements AgentSession {
|
||||
this.contextUsage.beginTurn();
|
||||
this.transitionTurnState("foreground", "foreground turn started");
|
||||
this.clearRecentStderr();
|
||||
if (sdkUserMessageId) this.unstartedMessageUuids.add(sdkUserMessageId);
|
||||
|
||||
let cancelIssued = false;
|
||||
const requestCancel = () => {
|
||||
@@ -2280,13 +2299,18 @@ class ClaudeAgentSession implements AgentSession {
|
||||
if (this.cancelCurrentTurn === requestCancel) {
|
||||
this.cancelCurrentTurn = null;
|
||||
}
|
||||
// Whether Claude has this message in hand. A late idle from the previous turn can clear
|
||||
// mainTurnInFlight after Claude started it, so the message's own lifecycle counts too.
|
||||
const claudeStartedTurn =
|
||||
this.mainTurnInFlight ||
|
||||
(sdkUserMessageId !== null && !this.unstartedMessageUuids.has(sdkUserMessageId));
|
||||
this.rejectAllPendingPermissions(new Error("Permission request canceled"));
|
||||
this.finishForegroundTurn({
|
||||
type: "turn_canceled",
|
||||
provider: "claude",
|
||||
reason: "Interrupted",
|
||||
});
|
||||
void this.interruptActiveTurn().catch((error) => {
|
||||
void this.interruptActiveTurn(claudeStartedTurn).catch((error) => {
|
||||
this.logger.warn({ err: error }, "Failed to interrupt during cancel");
|
||||
});
|
||||
};
|
||||
@@ -2296,6 +2320,11 @@ class ClaudeAgentSession implements AgentSession {
|
||||
|
||||
try {
|
||||
await this.ensureQuery();
|
||||
if (cancelIssued) {
|
||||
// Stopped while Claude was still starting up: withdrawn by never sending it.
|
||||
if (sdkUserMessageId) this.unstartedMessageUuids.delete(sdkUserMessageId);
|
||||
return { turnId };
|
||||
}
|
||||
if (!this.input) {
|
||||
throw new Error("Claude session input stream not initialized");
|
||||
}
|
||||
@@ -2309,6 +2338,7 @@ class ClaudeAgentSession implements AgentSession {
|
||||
}
|
||||
}, 0);
|
||||
} catch (error) {
|
||||
if (sdkUserMessageId) this.unstartedMessageUuids.delete(sdkUserMessageId);
|
||||
this.finishForegroundTurn(
|
||||
this.buildTurnFailedEvent(error instanceof Error ? error.message : "Claude stream failed"),
|
||||
);
|
||||
@@ -2357,7 +2387,7 @@ class ClaudeAgentSession implements AgentSession {
|
||||
clearPendingPermissions: boolean,
|
||||
): void {
|
||||
const uuid = message.uuid;
|
||||
if (uuid) this.queuedSteerUuids.add(uuid);
|
||||
if (uuid) this.unstartedMessageUuids.add(uuid);
|
||||
if (uuid && clearPendingPermissions) {
|
||||
this.permissionClearingSteerUuids.add(uuid);
|
||||
}
|
||||
@@ -2368,7 +2398,7 @@ class ClaudeAgentSession implements AgentSession {
|
||||
}
|
||||
} catch (error) {
|
||||
if (uuid) {
|
||||
this.queuedSteerUuids.delete(uuid);
|
||||
this.unstartedMessageUuids.delete(uuid);
|
||||
this.permissionClearingSteerUuids.delete(uuid);
|
||||
}
|
||||
throw error;
|
||||
@@ -2439,8 +2469,15 @@ class ClaudeAgentSession implements AgentSession {
|
||||
const normalized = isPermissionMode(modeId) ? modeId : "default";
|
||||
assertClaudeModeCanRun(normalized, this.harnessEnvironment);
|
||||
const previousMode = this.currentMode;
|
||||
const activeQuery = await this.ensureQuery();
|
||||
await activeQuery.setPermissionMode(normalized);
|
||||
const launchesQuery = !this.query || this.queryRestartNeeded;
|
||||
const activeQuery = await this.ensureQuery(normalized);
|
||||
try {
|
||||
await activeQuery.setPermissionMode(normalized);
|
||||
} catch (error) {
|
||||
// The query was launched in the rejected mode; relaunch in the current mode next time.
|
||||
if (launchesQuery) this.queryRestartNeeded = true;
|
||||
throw error;
|
||||
}
|
||||
if (normalized === "plan") {
|
||||
if (previousMode !== "plan") {
|
||||
this.planResumeMode = previousMode;
|
||||
@@ -3126,7 +3163,7 @@ class ClaudeAgentSession implements AgentSession {
|
||||
return { kind: "fresh-session" };
|
||||
}
|
||||
|
||||
private async ensureQuery(): Promise<Query> {
|
||||
private async ensureQuery(launchMode: PermissionMode = this.currentMode): Promise<Query> {
|
||||
if (this.query && !this.queryRestartNeeded) {
|
||||
return this.query;
|
||||
}
|
||||
@@ -3170,9 +3207,11 @@ class ClaudeAgentSession implements AgentSession {
|
||||
this.persistence = null;
|
||||
|
||||
const input = createAsyncMessageInput<SDKUserMessage>();
|
||||
const options = await this.buildOptions();
|
||||
const options = await this.buildOptions(launchMode);
|
||||
this.logger.debug({ options: summarizeClaudeOptionsForLog(options) }, "claude query");
|
||||
this.input = input;
|
||||
// A fresh Claude process has no turn of its own in flight.
|
||||
this.mainTurnInFlight = false;
|
||||
this.query = claudeQuery(
|
||||
{ prompt: input.iterable, options },
|
||||
{
|
||||
@@ -3292,11 +3331,16 @@ class ClaudeAgentSession implements AgentSession {
|
||||
return createProviderEnv({
|
||||
baseEnv: process.env,
|
||||
runtimeSettings: this.runtimeSettings,
|
||||
overlays: [this.launchEnv],
|
||||
overlays: [
|
||||
this.launchEnv,
|
||||
// Makes the CLI announce session_state_changed, whose "idle" is the safety net that closes
|
||||
// an autonomous turn (see consumeSessionStateChange).
|
||||
{ CLAUDE_CODE_EMIT_SESSION_STATE_EVENTS: "1" },
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
private async buildOptions(): Promise<ClaudeOptions> {
|
||||
private async buildOptions(permissionMode: PermissionMode): Promise<ClaudeOptions> {
|
||||
const { thinking, effort, ultracode } = this.resolveThinkingConfig();
|
||||
const appendedSystemPrompt = this.buildAppendedSystemPrompt();
|
||||
const providerOptions = applyClaudeToolPolicy(
|
||||
@@ -3305,7 +3349,7 @@ class ClaudeAgentSession implements AgentSession {
|
||||
);
|
||||
const settingsOptions = this.buildSettingsOptions(providerOptions, { ultracode });
|
||||
const sdkEnv = this.harnessEnvironment;
|
||||
assertClaudeModeCanRun(this.currentMode, sdkEnv);
|
||||
assertClaudeModeCanRun(permissionMode, sdkEnv);
|
||||
|
||||
const claudeBinary = await this.resolveBinary();
|
||||
this.logger.debug(
|
||||
@@ -3328,7 +3372,7 @@ class ClaudeAgentSession implements AgentSession {
|
||||
const base: ClaudeOptions = {
|
||||
cwd: this.config.cwd,
|
||||
includePartialMessages: true,
|
||||
permissionMode: this.currentMode,
|
||||
permissionMode,
|
||||
// Dynamic mode switching can recreate the underlying Claude query. Keep the
|
||||
// bypass launch capability available so later setPermissionMode("bypassPermissions")
|
||||
// calls do not fail after a model/thinking/rewind-driven restart.
|
||||
@@ -3359,6 +3403,10 @@ class ClaudeAgentSession implements AgentSession {
|
||||
...settingsOptions,
|
||||
// Provider subagent panes render the child's nested transcript.
|
||||
forwardSubagentText: true,
|
||||
// Stop and replace abort only the main turn, like Esc in Claude Code, and background
|
||||
// subagents keep running. Without this declaration an interrupt kills every one of them.
|
||||
// Claude stops a helper itself with its TaskStop tool.
|
||||
perTaskStopAffordance: true,
|
||||
hooks: this.buildSubagentEffortHooks(),
|
||||
...(this.persistSession === undefined ? {} : { persistSession: this.persistSession }),
|
||||
env: sdkEnv,
|
||||
@@ -3889,35 +3937,67 @@ class ClaudeAgentSession implements AgentSession {
|
||||
return false;
|
||||
}
|
||||
|
||||
private isAssistantishMessage(message: SDKMessage): boolean {
|
||||
return (
|
||||
message.type === "assistant" ||
|
||||
message.type === "stream_event" ||
|
||||
message.type === "tool_progress" ||
|
||||
(message.type === "system" && message.subtype === "task_notification")
|
||||
);
|
||||
/**
|
||||
* Claude's account of whether anything in the session is working, which is not the same as the
|
||||
* main session working: Claude Code 2.1.280 stays "running" for as long as any background
|
||||
* subagent is alive. So "running" never opens a turn.
|
||||
*
|
||||
* "idle" means nothing at all is running, so it closes an autonomous turn whatever opened it.
|
||||
* It never closes a foreground turn: an idle can trail the previous turn and land just after a
|
||||
* new send, and it must not end that send.
|
||||
*
|
||||
* Returns true when the frame was a state change, which is bookkeeping and never reaches the
|
||||
* timeline.
|
||||
*/
|
||||
private consumeSessionStateChange(message: SDKMessage): boolean {
|
||||
if (message.type !== "system" || message.subtype !== "session_state_changed") {
|
||||
return false;
|
||||
}
|
||||
if (message.state === "idle") {
|
||||
this.mainTurnInFlight = false;
|
||||
this.completeAutonomousTurn();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Tracks mainTurnInFlight from Claude's own turn brackets (isClaudeTurnInit). */
|
||||
private observeMainTurnBracket(message: SDKMessage): void {
|
||||
if (message.type === "result") {
|
||||
this.mainTurnInFlight = false;
|
||||
return;
|
||||
}
|
||||
if (isClaudeTurnInit(message)) {
|
||||
this.mainTurnInFlight = true;
|
||||
// A new turn has begun, so the interrupted one is over. An interrupt that landed after its
|
||||
// turn had already ended gets no result, and the leftover flag would swallow this turn's.
|
||||
this.pendingInterruptAbort = false;
|
||||
return;
|
||||
}
|
||||
if (readClaudeCommandLifecycle(message)?.state === "started") {
|
||||
this.mainTurnInFlight = true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Claude keeps talking about the request it was told to kill — the notification for the tool it
|
||||
* just stopped, trailing assistant output. That is not new work, so it must not open a turn: the
|
||||
* only message that would close that turn is the result shouldSuppressStaleResult drops, leaving
|
||||
* the agent stuck reporting "running" forever.
|
||||
* Only the main session's own turn start opens an autonomous turn. Everything a background
|
||||
* subagent emits (its task frames, its own background jobs' notifications, rate limit events)
|
||||
* arrives outside one, and no result would ever close a turn it opened.
|
||||
*/
|
||||
private shouldStartAutonomousTurn(message: SDKMessage): boolean {
|
||||
if (this.activeForegroundTurnId || this.pendingInterruptAbort) {
|
||||
return false;
|
||||
}
|
||||
return this.isAssistantishMessage(message);
|
||||
private opensAutonomousTurn(message: SDKMessage): boolean {
|
||||
return isClaudeTurnInit(message) && !this.activeForegroundTurnId;
|
||||
}
|
||||
|
||||
private async routeSdkMessageFromPump(message: SDKMessage): Promise<void> {
|
||||
if (this.consumeSessionStateChange(message)) {
|
||||
return;
|
||||
}
|
||||
this.observeMainTurnBracket(message);
|
||||
if (this.shouldSuppressStaleResult(message)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const isForeground = Boolean(this.activeForegroundTurnId);
|
||||
if (this.shouldStartAutonomousTurn(message)) {
|
||||
if (this.opensAutonomousTurn(message)) {
|
||||
this.startAutonomousTurn();
|
||||
}
|
||||
if (!isForeground && !this.autonomousTurn && message.type === "result") {
|
||||
@@ -4059,7 +4139,13 @@ class ClaudeAgentSession implements AgentSession {
|
||||
return true;
|
||||
}
|
||||
|
||||
private async interruptActiveTurn(): Promise<void> {
|
||||
/**
|
||||
* Interrupts Claude only when a turn of its main session is running. With nothing running there
|
||||
* is nothing to stop but our own queued messages, so those are withdrawn instead: an interrupt
|
||||
* would reach only background helpers (and kill them on a CLI that ignores
|
||||
* perTaskStopAffordance), and no result would follow to consume pendingInterruptAbort.
|
||||
*/
|
||||
private async interruptActiveTurn(claudeStartedTurn = this.mainTurnInFlight): Promise<void> {
|
||||
const queryToInterrupt = this.query;
|
||||
if (!queryToInterrupt || typeof queryToInterrupt.interrupt !== "function") {
|
||||
this.logger.trace(
|
||||
@@ -4073,8 +4159,16 @@ class ClaudeAgentSession implements AgentSession {
|
||||
);
|
||||
return;
|
||||
}
|
||||
this.pendingInterruptAbort = true;
|
||||
await this.discardQueuedSteers(queryToInterrupt);
|
||||
if (claudeStartedTurn) {
|
||||
this.pendingInterruptAbort = true;
|
||||
await this.withdrawUnstartedMessages(queryToInterrupt);
|
||||
} else {
|
||||
// Claude can dequeue a message for its next turn before announcing it started; withdrawing
|
||||
// it is then a no-op, and only an interrupt stops it. Withdraw once: a prompt sent while
|
||||
// this withdrawal was in flight belongs to the next turn.
|
||||
if (await this.withdrawUnstartedMessages(queryToInterrupt)) return;
|
||||
this.pendingInterruptAbort = true;
|
||||
}
|
||||
try {
|
||||
await this.awaitWithTimeout(
|
||||
queryToInterrupt.interrupt(),
|
||||
@@ -4086,14 +4180,15 @@ class ClaudeAgentSession implements AgentSession {
|
||||
}
|
||||
|
||||
/**
|
||||
* Interrupt means interrupt: a steer Claude never read dies with the turn instead of resuming it.
|
||||
* A steer already dequeued cannot be recalled, and does not need to be — the interrupt kills it.
|
||||
* Interrupt means interrupt: a message Claude never started dies with the turn instead of
|
||||
* resuming it. One already dequeued cannot be recalled, and does not need to be, since the
|
||||
* interrupt kills it. Returns whether Claude confirmed every message withdrawn.
|
||||
*/
|
||||
private async discardQueuedSteers(query: Query): Promise<void> {
|
||||
const uuids = [...this.queuedSteerUuids];
|
||||
this.queuedSteerUuids.clear();
|
||||
private async withdrawUnstartedMessages(query: Query): Promise<boolean> {
|
||||
const uuids = [...this.unstartedMessageUuids];
|
||||
this.unstartedMessageUuids.clear();
|
||||
this.permissionClearingSteerUuids.clear();
|
||||
if (uuids.length === 0) return;
|
||||
if (uuids.length === 0) return true;
|
||||
// The SDK runtime supports this, but its public Query type has not caught up. Keep the
|
||||
// compatibility escape hatch inside the Claude adapter.
|
||||
const cancelAsyncMessage = (
|
||||
@@ -4101,14 +4196,17 @@ class ClaudeAgentSession implements AgentSession {
|
||||
cancelAsyncMessage?: (uuid: string) => Promise<boolean>;
|
||||
}
|
||||
).cancelAsyncMessage;
|
||||
if (!cancelAsyncMessage) return;
|
||||
if (!cancelAsyncMessage) return false;
|
||||
let withdrewAll = true;
|
||||
for (const uuid of uuids) {
|
||||
try {
|
||||
await cancelAsyncMessage.call(query, uuid);
|
||||
if (!(await cancelAsyncMessage.call(query, uuid))) withdrewAll = false;
|
||||
} catch (error) {
|
||||
this.logger.warn({ err: error }, "Failed to discard a queued Claude steer");
|
||||
withdrewAll = false;
|
||||
this.logger.warn({ err: error }, "Failed to withdraw a queued Claude message");
|
||||
}
|
||||
}
|
||||
return withdrewAll;
|
||||
}
|
||||
|
||||
private translateMessageToEvents(
|
||||
@@ -4157,7 +4255,7 @@ class ClaudeAgentSession implements AgentSession {
|
||||
}
|
||||
}
|
||||
|
||||
this.forgetReadSteer(message);
|
||||
this.forgetStartedMessage(message);
|
||||
|
||||
switch (message.type) {
|
||||
case "system":
|
||||
@@ -4191,11 +4289,14 @@ class ClaudeAgentSession implements AgentSession {
|
||||
return events;
|
||||
}
|
||||
|
||||
/** Once Claude has read a steer there is nothing left to discard on interrupt. */
|
||||
private forgetReadSteer(message: unknown): void {
|
||||
/**
|
||||
* Once Claude has started a message, or cancelled it, there is nothing left to withdraw on
|
||||
* interrupt.
|
||||
*/
|
||||
private forgetStartedMessage(message: unknown): void {
|
||||
const lifecycle = readClaudeCommandLifecycle(message);
|
||||
if (!lifecycle || lifecycle.state === "queued") return;
|
||||
this.queuedSteerUuids.delete(lifecycle.commandUuid);
|
||||
this.unstartedMessageUuids.delete(lifecycle.commandUuid);
|
||||
this.permissionClearingSteerUuids.delete(lifecycle.commandUuid);
|
||||
}
|
||||
|
||||
@@ -5184,7 +5285,7 @@ class ClaudeAgentSession implements AgentSession {
|
||||
// User SDK entries can arrive as multiple text blocks, but Paseo treats them as one message.
|
||||
const userTextParts: string[] = [];
|
||||
for (const block of content) {
|
||||
if (!isClaudeContentChunk(block)) {
|
||||
if (!isClaudeContentChunk(block) || this.mapSubagentHandbackBlock(block, items)) {
|
||||
continue;
|
||||
}
|
||||
this.mapBlockToTimeline(block, {
|
||||
@@ -5272,6 +5373,24 @@ class ClaudeAgentSession implements AgentSession {
|
||||
}
|
||||
}
|
||||
|
||||
// A subagent's handback call is its final message, and the call's result is only an
|
||||
// acknowledgement, so neither becomes a tool call.
|
||||
private mapSubagentHandbackBlock(block: ClaudeContentChunk, items: AgentTimelineItem[]): boolean {
|
||||
if (typeof block.tool_use_id === "string" && this.subagentHandbackIds.has(block.tool_use_id)) {
|
||||
this.subagentHandbackIds.delete(block.tool_use_id);
|
||||
return true;
|
||||
}
|
||||
const handback = readClaudeSubagentHandback(block);
|
||||
if (!handback) {
|
||||
return false;
|
||||
}
|
||||
this.subagentHandbackIds.add(handback.callId);
|
||||
if (handback.report) {
|
||||
items.push({ type: "assistant_message", text: handback.report });
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private handleToolUseStart(block: ClaudeContentChunk, items: AgentTimelineItem[]): void {
|
||||
const entry = this.upsertToolUseEntry(block);
|
||||
if (!entry) {
|
||||
@@ -6492,7 +6611,8 @@ function extractClaudeUserText(messageRaw: unknown): string | null {
|
||||
|
||||
interface ClaudeCommandLifecycle {
|
||||
commandUuid: string;
|
||||
state: "queued" | "started" | "completed";
|
||||
/** "cancelled" is terminal too: API errors, interrupts and "now" pre-emption end a message. */
|
||||
state: "queued" | "started" | "completed" | "cancelled";
|
||||
}
|
||||
|
||||
/** Runtime-only Claude frames are validated here because the SDK's public union omits them. */
|
||||
@@ -6501,7 +6621,7 @@ function readClaudeCommandLifecycle(message: unknown): ClaudeCommandLifecycle |
|
||||
if (record?.type !== "command_lifecycle") return null;
|
||||
if (
|
||||
typeof record.command_uuid !== "string" ||
|
||||
!["queued", "started", "completed"].includes(String(record.state))
|
||||
!["queued", "started", "completed", "cancelled"].includes(String(record.state))
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -35,4 +35,64 @@ describe("ClaudeSidechainTracker", () => {
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("shows a SubagentHandback report as the subagent's final message", () => {
|
||||
const tracker = new ClaudeSidechainTracker({ getToolInput: () => null });
|
||||
const report = " indented code\n\n## Verdict\n\n- **Coherent**";
|
||||
const frames = [
|
||||
{
|
||||
type: "stream_event",
|
||||
parent_tool_use_id: "task-1",
|
||||
event: {
|
||||
type: "content_block_start",
|
||||
index: 0,
|
||||
content_block: {
|
||||
type: "tool_use",
|
||||
id: "handback-1",
|
||||
name: "SubagentHandback",
|
||||
input: {},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "assistant",
|
||||
parent_tool_use_id: "task-1",
|
||||
message: {
|
||||
id: "msg-1",
|
||||
content: [
|
||||
{
|
||||
type: "tool_use",
|
||||
id: "handback-1",
|
||||
name: "SubagentHandback",
|
||||
input: { message: report },
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "user",
|
||||
parent_tool_use_id: "task-1",
|
||||
message: {
|
||||
content: [
|
||||
{
|
||||
type: "tool_result",
|
||||
tool_use_id: "handback-1",
|
||||
tool_name: "SubagentHandback",
|
||||
content: [{ type: "text", text: '{"success":true}' }],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const childItems = frames
|
||||
.flatMap((frame) => tracker.handleMessage(frame as unknown as SDKMessage, "task-1"))
|
||||
.flatMap((event) =>
|
||||
event.type === "provider_subagent" && event.event.type === "timeline"
|
||||
? [event.event.item]
|
||||
: [],
|
||||
);
|
||||
|
||||
expect(childItems).toEqual([{ type: "assistant_message", text: report, messageId: "msg-1" }]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -6,6 +6,10 @@ import {
|
||||
mapClaudeRunningToolCall,
|
||||
} from "./tool-call-mapper.js";
|
||||
import { buildToolCallDisplayModel } from "@getpaseo/protocol/tool-call-display";
|
||||
import {
|
||||
isClaudeSubagentHandbackToolName,
|
||||
readClaudeSubagentHandback,
|
||||
} from "./subagent-handback.js";
|
||||
|
||||
import type { AgentMetadata, AgentStreamEvent, AgentTimelineItem } from "../../agent-sdk-types.js";
|
||||
|
||||
@@ -91,7 +95,7 @@ export class ClaudeSidechainTracker {
|
||||
const contextUpdated = this.updateSubAgentContextFromTaskInput(state, parentToolUseId);
|
||||
const actionCandidates = this.extractSubAgentActionCandidates(message);
|
||||
const childTimelineItems = [
|
||||
...this.extractSubAgentTimelineItems(message),
|
||||
...this.extractSubAgentTimelineItems(message, state),
|
||||
...this.extractSubAgentToolResults(message, state),
|
||||
];
|
||||
let actionUpdated = false;
|
||||
@@ -233,7 +237,10 @@ export class ClaudeSidechainTracker {
|
||||
this.activeSidechains.clear();
|
||||
}
|
||||
|
||||
private extractSubAgentTimelineItems(message: SDKMessage): AgentTimelineItem[] {
|
||||
private extractSubAgentTimelineItems(
|
||||
message: SDKMessage,
|
||||
state: SubAgentActivityState,
|
||||
): AgentTimelineItem[] {
|
||||
if (message.type !== "assistant" || !Array.isArray(message.message?.content)) {
|
||||
return [];
|
||||
}
|
||||
@@ -253,6 +260,18 @@ export class ClaudeSidechainTracker {
|
||||
} else if (block.type === "thinking") {
|
||||
const text = readTrimmedString(block.thinking);
|
||||
if (text) items.push({ type: "reasoning", text });
|
||||
} else {
|
||||
const handback = readClaudeSubagentHandback(block);
|
||||
if (!handback) continue;
|
||||
// The handback's result is only an acknowledgement, never a tool card.
|
||||
state.completedActionKeys.add(handback.callId);
|
||||
if (handback.report) {
|
||||
items.push({
|
||||
type: "assistant_message",
|
||||
text: handback.report,
|
||||
...(messageId ? { messageId } : {}),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
return items;
|
||||
@@ -391,6 +410,12 @@ export class ClaudeSidechainTracker {
|
||||
}
|
||||
|
||||
private extractSubAgentActionCandidates(message: SDKMessage): SubAgentActionCandidate[] {
|
||||
return this.extractToolActionCandidates(message).filter(
|
||||
(action) => !isClaudeSubagentHandbackToolName(action.toolName),
|
||||
);
|
||||
}
|
||||
|
||||
private extractToolActionCandidates(message: SDKMessage): SubAgentActionCandidate[] {
|
||||
if (message.type === "assistant") {
|
||||
return this.extractAssistantMessageActions(message);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
/**
|
||||
* Since Claude Code 2.1.271, a subagent in auto mode delivers its report to its caller through a
|
||||
* `SubagentHandback` tool call instead of its final text. The report is the subagent's final
|
||||
* message, so Paseo shows it as one and hides the call and its acknowledgement.
|
||||
*/
|
||||
const SUBAGENT_HANDBACK_TOOL_NAME = "SubagentHandback";
|
||||
|
||||
export interface ClaudeSubagentHandback {
|
||||
callId: string;
|
||||
/** Null while the call is still streaming its input. */
|
||||
report: string | null;
|
||||
}
|
||||
|
||||
export function isClaudeSubagentHandbackToolName(name: unknown): boolean {
|
||||
return name === SUBAGENT_HANDBACK_TOOL_NAME;
|
||||
}
|
||||
|
||||
export function readClaudeSubagentHandback(block: {
|
||||
type: string;
|
||||
[key: string]: unknown;
|
||||
}): ClaudeSubagentHandback | null {
|
||||
if (block.type !== "tool_use" || !isClaudeSubagentHandbackToolName(block.name)) return null;
|
||||
if (typeof block.id !== "string" || block.id.length === 0) return null;
|
||||
const input = block.input as { message?: unknown } | null | undefined;
|
||||
const report = typeof input?.message === "string" ? input.message : "";
|
||||
return { callId: block.id, report: report.trim().length > 0 ? report : null };
|
||||
}
|
||||
@@ -511,6 +511,33 @@ describe("ClaudeTaskProtocolSource", () => {
|
||||
expect(source.cancelRunningForegroundTasks()).toEqual([]);
|
||||
});
|
||||
|
||||
it("does not cancel a subagent announced as backgrounded at spawn", () => {
|
||||
// Claude sets is_backgrounded on task_started for a child spawned in the background, and
|
||||
// sends no task_updated patch for it.
|
||||
const source = new ClaudeTaskProtocolSource();
|
||||
source.observe(taskStarted({ is_backgrounded: true }));
|
||||
|
||||
expect(source.cancelRunningForegroundTasks()).toEqual([]);
|
||||
});
|
||||
|
||||
it("does not cancel a resumed subagent, which Claude always runs in the background", () => {
|
||||
const source = new ClaudeTaskProtocolSource();
|
||||
source.observe(taskStarted({ tool_use_id: "toolu_original", is_backgrounded: false }));
|
||||
source.observe(taskUpdated("completed"));
|
||||
source.observe(taskStarted({ tool_use_id: "toolu_resumed", is_backgrounded: true }));
|
||||
|
||||
expect(source.cancelRunningForegroundTasks()).toEqual([]);
|
||||
});
|
||||
|
||||
it("still cancels a subagent announced in the foreground", () => {
|
||||
const source = new ClaudeTaskProtocolSource();
|
||||
source.observe(taskStarted({ is_backgrounded: false }));
|
||||
|
||||
expect(source.cancelRunningForegroundTasks()).toEqual([
|
||||
{ kind: "status", id: "toolu_01DgLoPMW9", status: "canceled" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("still routes a backgrounded subagent that settles after the interrupt", () => {
|
||||
// The headline case: interrupt, continue, and the child that was told to outlive the turn
|
||||
// reports completion later. Wiping the routing table on cancel drops this on the floor and
|
||||
|
||||
@@ -16,7 +16,8 @@ import {
|
||||
*
|
||||
* Verified on the wire (Claude Code 2.1.220, Paseo's own query options):
|
||||
*
|
||||
* task_started task_id, tool_use_id, description, subagent_type, task_type
|
||||
* task_started task_id, tool_use_id, description, subagent_type, task_type,
|
||||
* is_backgrounded
|
||||
* task_updated task_id, patch.status, patch.is_backgrounded
|
||||
* task_notification task_id, tool_use_id, status
|
||||
*
|
||||
@@ -39,6 +40,11 @@ interface TaskStartedMessage {
|
||||
task_type?: string;
|
||||
prompt?: string;
|
||||
skip_transcript?: boolean;
|
||||
/**
|
||||
* Set at spawn: true for a task registered in the background. A resumed subagent is always
|
||||
* registered in the background.
|
||||
*/
|
||||
is_backgrounded?: boolean;
|
||||
}
|
||||
|
||||
/** Task-tool subagents. Backgrounded shell commands announce as `local_bash`. */
|
||||
@@ -71,8 +77,8 @@ interface TaskUpdatedMessage {
|
||||
task_id: string;
|
||||
/**
|
||||
* `is_backgrounded` is declared on `SDKTaskUpdatedMessage["patch"]`: it flips when a foreground
|
||||
* task is backgrounded, which is the only signal that separates a child that dies with its turn
|
||||
* from one that was explicitly told to outlive it.
|
||||
* task is moved to the background after `task_started`. Together with `task_started`'s own
|
||||
* flag it separates a child that dies with its turn from one told to outlive it.
|
||||
*/
|
||||
patch?: { status?: string; is_backgrounded?: boolean };
|
||||
}
|
||||
@@ -171,8 +177,8 @@ export class ClaudeTaskProtocolSource {
|
||||
/** Workflow invocations already own a real Workflow card in the parent timeline. */
|
||||
private readonly idsWithExistingParentToolCard = new Set<string>();
|
||||
/**
|
||||
* Declared subagents that were moved to the background. They outlive the turn that spawned
|
||||
* them, so a turn ending is not evidence that they stopped.
|
||||
* Declared subagents running in the background, whether spawned there or moved there later.
|
||||
* They outlive the turn that spawned them, so a turn ending is not evidence that they stopped.
|
||||
*/
|
||||
private readonly backgroundedIds = new Set<string>();
|
||||
/** Last status emitted per subagent, so a redundant announcement is not re-broadcast. */
|
||||
@@ -331,6 +337,7 @@ export class ClaudeTaskProtocolSource {
|
||||
|
||||
this.sawTaskStarted = true;
|
||||
const existingId = this.subagentIdByTaskId.get(message.task_id);
|
||||
this.recordBackgrounded(existingId ?? id, message.is_backgrounded);
|
||||
if (existingId) {
|
||||
return this.observeExistingTaskStart(message, id, existingId);
|
||||
}
|
||||
@@ -414,14 +421,15 @@ export class ClaudeTaskProtocolSource {
|
||||
|
||||
private observeTaskUpdated(message: TaskUpdatedMessage): SubagentObservation[] {
|
||||
const id = this.subagentIdByTaskId.get(message.task_id);
|
||||
const backgrounded = message.patch?.is_backgrounded;
|
||||
if (id && typeof backgrounded === "boolean") {
|
||||
if (backgrounded) this.backgroundedIds.add(id);
|
||||
else this.backgroundedIds.delete(id);
|
||||
}
|
||||
if (id) this.recordBackgrounded(id, message.patch?.is_backgrounded);
|
||||
return this.observeStatus(message.task_id, message.patch?.status);
|
||||
}
|
||||
|
||||
private recordBackgrounded(id: string, backgrounded: boolean | undefined): void {
|
||||
if (backgrounded === true) this.backgroundedIds.add(id);
|
||||
else if (backgrounded === false) this.backgroundedIds.delete(id);
|
||||
}
|
||||
|
||||
private observeTaskNotification(message: TaskNotificationMessage): SubagentObservation[] {
|
||||
const observations = this.observeWorkflowResult(message);
|
||||
observations.push(...this.observeUsage(message.task_id, message.usage));
|
||||
|
||||
+154
@@ -0,0 +1,154 @@
|
||||
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
import { createTestLogger } from "../../../test-utils/test-logger.js";
|
||||
import type { AgentStreamEvent } from "../agent-sdk-types.js";
|
||||
import { GenericACPAgentClient } from "./generic-acp-agent.js";
|
||||
|
||||
describe("GenericACPAgentClient archived history", () => {
|
||||
test("replays an archived session whose working directory was removed", async () => {
|
||||
await withFakeACPAgent(async ({ command, removedCwd, loadRequestsPath }) => {
|
||||
const client = new GenericACPAgentClient({ logger: createTestLogger(), command });
|
||||
|
||||
const session = await client.resumeSession(
|
||||
{ provider: "acp", sessionId: "archived-session", metadata: { cwd: removedCwd } },
|
||||
undefined,
|
||||
undefined,
|
||||
{ purpose: "history" },
|
||||
);
|
||||
try {
|
||||
expect(await collectTimelineText(session.streamHistory())).toEqual([
|
||||
"user_message:What is in the README?",
|
||||
"assistant_message:It describes the project.",
|
||||
]);
|
||||
const loadRequests = JSON.parse(await readFile(loadRequestsPath, "utf8"));
|
||||
expect(loadRequests).toEqual([{ sessionId: "archived-session", cwd: removedCwd }]);
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
test("replays an archived session whose working directory path is now a file", async () => {
|
||||
await withFakeACPAgent(async ({ command, removedCwd }) => {
|
||||
await writeFile(removedCwd, "not a directory", "utf8");
|
||||
const client = new GenericACPAgentClient({ logger: createTestLogger(), command });
|
||||
|
||||
const session = await client.resumeSession(
|
||||
{ provider: "acp", sessionId: "archived-session", metadata: { cwd: removedCwd } },
|
||||
undefined,
|
||||
undefined,
|
||||
{ purpose: "history" },
|
||||
);
|
||||
try {
|
||||
expect(await collectTimelineText(session.streamHistory())).toEqual([
|
||||
"user_message:What is in the README?",
|
||||
"assistant_message:It describes the project.",
|
||||
]);
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
test("still requires the working directory to resume a session that will run", async () => {
|
||||
await withFakeACPAgent(async ({ command, removedCwd }) => {
|
||||
const client = new GenericACPAgentClient({ logger: createTestLogger(), command });
|
||||
|
||||
await expect(
|
||||
client.resumeSession(
|
||||
{ provider: "acp", sessionId: "archived-session", metadata: { cwd: removedCwd } },
|
||||
undefined,
|
||||
undefined,
|
||||
{ purpose: "interactive" },
|
||||
),
|
||||
).rejects.toThrow("ENOENT");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
async function collectTimelineText(events: AsyncGenerator<AgentStreamEvent>): Promise<string[]> {
|
||||
const text: string[] = [];
|
||||
for await (const event of events) {
|
||||
if (event.type !== "timeline") {
|
||||
continue;
|
||||
}
|
||||
if (event.item.type === "user_message" || event.item.type === "assistant_message") {
|
||||
text.push(`${event.item.type}:${event.item.text}`);
|
||||
}
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
async function withFakeACPAgent(
|
||||
run: (input: {
|
||||
command: [string, ...string[]];
|
||||
removedCwd: string;
|
||||
loadRequestsPath: string;
|
||||
}) => Promise<void>,
|
||||
): Promise<void> {
|
||||
const testDir = await mkdtemp(path.join(tmpdir(), "paseo-acp-archived-history-"));
|
||||
try {
|
||||
const scriptPath = path.join(testDir, "fake-acp-agent.cjs");
|
||||
const loadRequestsPath = path.join(testDir, "load-requests.json");
|
||||
await writeFile(scriptPath, fakeACPAgentScript, "utf8");
|
||||
await run({
|
||||
command: [process.execPath, scriptPath, loadRequestsPath],
|
||||
removedCwd: path.join(testDir, "removed-worktree"),
|
||||
loadRequestsPath,
|
||||
});
|
||||
} finally {
|
||||
await rm(testDir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
const fakeACPAgentScript = `
|
||||
const fs = require("node:fs");
|
||||
const readline = require("node:readline");
|
||||
|
||||
const loadRequestsPath = process.argv[2];
|
||||
const loadRequests = [];
|
||||
const rl = readline.createInterface({ input: process.stdin });
|
||||
|
||||
function write(message) {
|
||||
process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...message }) + "\\n");
|
||||
}
|
||||
|
||||
function replay(sessionId, sessionUpdate, text) {
|
||||
write({
|
||||
method: "session/update",
|
||||
params: { sessionId, update: { sessionUpdate, content: { type: "text", text } } },
|
||||
});
|
||||
}
|
||||
|
||||
rl.on("line", (line) => {
|
||||
const message = JSON.parse(line);
|
||||
if (message.method === "initialize") {
|
||||
write({
|
||||
id: message.id,
|
||||
result: {
|
||||
protocolVersion: message.params?.protocolVersion ?? 1,
|
||||
agentCapabilities: { loadSession: true, sessionCapabilities: { close: {} } },
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (message.method === "session/load") {
|
||||
const { sessionId, cwd } = message.params;
|
||||
loadRequests.push({ sessionId, cwd });
|
||||
fs.writeFileSync(loadRequestsPath, JSON.stringify(loadRequests));
|
||||
replay(sessionId, "user_message_chunk", "What is in the README?");
|
||||
replay(sessionId, "agent_message_chunk", "It describes the project.");
|
||||
write({ id: message.id, result: {} });
|
||||
return;
|
||||
}
|
||||
|
||||
if (message.id !== undefined) {
|
||||
write({ id: message.id, result: {} });
|
||||
}
|
||||
});
|
||||
`;
|
||||
@@ -459,7 +459,9 @@ describe("OMP agent client and session", () => {
|
||||
|
||||
test("fails a turn when the provider idle gate passes its deadline", async () => {
|
||||
const scheduler = new ManualIdleScheduler();
|
||||
const omp = new OmpHarness({ providerIdleScheduler: scheduler, providerIdleDeadlineMs: 1 });
|
||||
// Long enough that the gate's first check, made right after the turn ends, cannot already
|
||||
// be past it on a slow runner.
|
||||
const omp = new OmpHarness({ providerIdleScheduler: scheduler, providerIdleDeadlineMs: 50 });
|
||||
await omp.start();
|
||||
const { completion } = await omp.startPromptUntilProviderIdle("first", "first done", {
|
||||
isStreaming: true,
|
||||
@@ -473,7 +475,7 @@ describe("OMP agent client and session", () => {
|
||||
args: { command: "sleep 30" },
|
||||
});
|
||||
expect(omp.runningToolCallIds()).toEqual(["tool-at-deadline"]);
|
||||
await new Promise((resolve) => setTimeout(resolve, 2));
|
||||
await new Promise((resolve) => setTimeout(resolve, 60));
|
||||
scheduler.retry();
|
||||
await expect(completion).rejects.toThrow(/provider idle/i);
|
||||
expect(omp.runningToolCallIds()).toEqual([]);
|
||||
|
||||
@@ -87,7 +87,8 @@ function mergeToolCallDetail(existing: ToolCallDetail, incoming: ToolCallDetail)
|
||||
return incoming;
|
||||
}
|
||||
|
||||
function mergeToolCallItems(
|
||||
/** Fold a later update for the same tool call into the one it follows. */
|
||||
export function mergeToolCallItems(
|
||||
existing: Extract<AgentTimelineItem, { type: "tool_call" }>,
|
||||
incoming: Extract<AgentTimelineItem, { type: "tool_call" }>,
|
||||
): Extract<AgentTimelineItem, { type: "tool_call" }> {
|
||||
|
||||
@@ -126,6 +126,7 @@ import { createPaseoWorktree as createRegisteredPaseoWorktree } from "./paseo-wo
|
||||
import { createWorkspaceProvisioningService } from "./session/workspace-provisioning/workspace-provisioning-service.js";
|
||||
import { createPaseoWorktreeWorkflow } from "./worktree-session.js";
|
||||
import { DownloadTokenStore } from "./file-download/token-store.js";
|
||||
import { formatAttachmentContentDisposition } from "./file-download/content-disposition.js";
|
||||
import type { OpenAiSpeechProviderConfig } from "./speech/providers/openai/config.js";
|
||||
import type { LocalSpeechProviderConfig } from "./speech/providers/local/config.js";
|
||||
import type { RequestedSpeechProviders } from "./speech/speech-types.js";
|
||||
@@ -414,7 +415,6 @@ export interface PaseoDaemonConfig {
|
||||
plugins?: Record<string, PluginSource>;
|
||||
pluginRegistries?: PluginRegistries;
|
||||
pluginRegistryUrl?: string;
|
||||
pluginRegistryEnabled?: boolean;
|
||||
staticDir: string;
|
||||
mcpDebug: boolean;
|
||||
isDev?: boolean;
|
||||
@@ -625,7 +625,6 @@ export async function createPaseoDaemon(
|
||||
usageSession: (id) => agentManager.usageSession(id),
|
||||
},
|
||||
managedSources: new ManagedPluginSources(config.paseoHome, {
|
||||
enabled: config.pluginRegistryEnabled ?? false,
|
||||
registries: config.pluginRegistries,
|
||||
defaultUrl: config.pluginRegistryUrl,
|
||||
}),
|
||||
@@ -838,9 +837,8 @@ export async function createPaseoDaemon(
|
||||
return;
|
||||
}
|
||||
|
||||
const safeFileName = entry.fileName.replace(/["\r\n]/g, "_");
|
||||
res.setHeader("Content-Type", entry.mimeType);
|
||||
res.setHeader("Content-Disposition", `attachment; filename="${safeFileName}"`);
|
||||
res.setHeader("Content-Disposition", formatAttachmentContentDisposition(entry.fileName));
|
||||
res.setHeader("Content-Length", fileStats.size.toString());
|
||||
|
||||
const stream = fileHandle.createReadStream();
|
||||
|
||||
@@ -30,7 +30,6 @@ export const DAEMON_SETTING_ENV_KEYS = [
|
||||
"PASEO_LOG_ROTATE_SIZE",
|
||||
"PASEO_PASSWORD",
|
||||
"PASEO_PLUGIN_REGISTRY",
|
||||
"PASEO_PLUGIN_REGISTRY_ENABLED",
|
||||
"PASEO_RELAY_ENABLED",
|
||||
"PASEO_RELAY_ENDPOINT",
|
||||
"PASEO_RELAY_PUBLIC_ENDPOINT",
|
||||
|
||||
@@ -211,15 +211,6 @@ test("loads private plugin registry settings through the configuration boundary"
|
||||
});
|
||||
expect(config.pluginRegistryUrl).toBe("https://plugins.example.test/internal");
|
||||
expect(config.pluginRegistries).toEqual(pluginRegistries);
|
||||
expect(config.pluginRegistryEnabled).toBe(false);
|
||||
await writeFile(
|
||||
path.join(home, "config.json"),
|
||||
JSON.stringify({ pluginRegistries, pluginRegistryEnabled: true }),
|
||||
);
|
||||
expect(loadConfig(home, { env: {} }).pluginRegistryEnabled).toBe(true);
|
||||
expect(
|
||||
loadConfig(home, { env: { PASEO_PLUGIN_REGISTRY_ENABLED: "false" } }).pluginRegistryEnabled,
|
||||
).toBe(false);
|
||||
} finally {
|
||||
await rm(home, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
@@ -628,10 +628,6 @@ export function resolveConfigFromPersisted(
|
||||
plugins: persisted.plugins,
|
||||
pluginRegistries: persisted.pluginRegistries,
|
||||
pluginRegistryUrl: env.PASEO_PLUGIN_REGISTRY,
|
||||
pluginRegistryEnabled:
|
||||
parseBooleanEnv(env.PASEO_PLUGIN_REGISTRY_ENABLED) ??
|
||||
persisted.pluginRegistryEnabled ??
|
||||
false,
|
||||
mcpDebug: env.MCP_DEBUG === "1",
|
||||
isDev: resolvePaseoNodeEnv(env) === "development",
|
||||
agentStoragePath: path.join(paseoHome, "agents"),
|
||||
|
||||
@@ -831,6 +831,29 @@ test("send_agent_message auto-unarchives archived agents", async () => {
|
||||
}
|
||||
}, 180000);
|
||||
|
||||
test("send_agent_message leaves an archived agent archived when its directory is gone", async () => {
|
||||
const cwd = tmpCwd();
|
||||
try {
|
||||
const created = await ctx.client.createAgent({
|
||||
config: {
|
||||
...getFullAccessConfig("codex"),
|
||||
cwd,
|
||||
},
|
||||
});
|
||||
const archived = await ctx.client.archiveAgent(created.id);
|
||||
rmSync(cwd, { recursive: true, force: true });
|
||||
|
||||
await expect(ctx.client.sendMessage(created.id, "hello")).rejects.toThrow(
|
||||
"Working directory does not exist",
|
||||
);
|
||||
|
||||
const afterSend = await ctx.client.fetchAgent({ agentId: created.id });
|
||||
expect(afterSend?.agent.archivedAt).toBe(archived.archivedAt);
|
||||
} finally {
|
||||
rmSync(cwd, { recursive: true, force: true });
|
||||
}
|
||||
}, 30000);
|
||||
|
||||
test("refresh_agent auto-unarchives archived agents", async () => {
|
||||
const cwd = tmpCwd();
|
||||
try {
|
||||
|
||||
@@ -24,42 +24,77 @@ describe("daemon E2E", () => {
|
||||
}, 60000);
|
||||
|
||||
describe("file download tokens", () => {
|
||||
test("issues token over WS and downloads via HTTP", async () => {
|
||||
const cwd = tmpCwd();
|
||||
const filePath = path.join(cwd, "download.txt");
|
||||
const fileContents = "download test payload";
|
||||
writeFileSync(filePath, fileContents, "utf-8");
|
||||
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 {
|
||||
const filePath = path.join(cwd, fileName);
|
||||
const fileContents = "download test payload";
|
||||
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",
|
||||
});
|
||||
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).toBeTruthy();
|
||||
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, "download.txt");
|
||||
const tokenResponse = await ctx.client.requestDownloadToken(cwd, fileName);
|
||||
|
||||
expect(tokenResponse.error).toBeNull();
|
||||
expect(tokenResponse.token).toBeTruthy();
|
||||
expect(tokenResponse.fileName).toBe("download.txt");
|
||||
expect(tokenResponse.error).toBeNull();
|
||||
expect(tokenResponse.token).toMatch(
|
||||
/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,
|
||||
);
|
||||
expect(tokenResponse.fileName).toBe(fileName);
|
||||
|
||||
const response = await fetch(
|
||||
`http://127.0.0.1:${ctx.daemon.port}/api/files/download?token=${tokenResponse.token}`,
|
||||
);
|
||||
const response = await fetch(
|
||||
`http://127.0.0.1:${ctx.daemon.port}/api/files/download?token=${tokenResponse.token}`,
|
||||
);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.headers.get("content-type")).toBe(tokenResponse.mimeType);
|
||||
const disposition = response.headers.get("content-disposition") ?? "";
|
||||
expect(disposition).toContain("download.txt");
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.headers.get("content-type")).toBe(tokenResponse.mimeType);
|
||||
expect(response.headers.get("content-disposition")).toBe(disposition);
|
||||
|
||||
const body = await response.text();
|
||||
expect(body).toBe(fileContents);
|
||||
|
||||
rmSync(cwd, { recursive: true, force: true });
|
||||
}, 60000);
|
||||
const body = await response.text();
|
||||
expect(body).toBe(fileContents);
|
||||
} finally {
|
||||
rmSync(cwd, { recursive: true, force: true });
|
||||
}
|
||||
},
|
||||
60000,
|
||||
);
|
||||
|
||||
test("rejects invalid token", async () => {
|
||||
const response = await fetch(
|
||||
|
||||
@@ -304,6 +304,166 @@ async function waitForRunningClaudeSleep(
|
||||
);
|
||||
}
|
||||
|
||||
// Explicit point-in-time polls of agent status, on top of (not instead of) the pushed
|
||||
// agent_update events the collector already records. A phantom "running" flip that starts and
|
||||
// ends between two polls would still be caught by the pushed-event scan the callers pair this
|
||||
// with; polling here additionally proves the daemon answers fetchAgent with "idle" throughout,
|
||||
// not just that it eventually pushes one.
|
||||
async function sampleAgentStatuses(
|
||||
client: DaemonClient,
|
||||
agentId: string,
|
||||
samples: number,
|
||||
intervalMs: number,
|
||||
): Promise<string[]> {
|
||||
const statuses: string[] = [];
|
||||
for (let i = 0; i < samples; i += 1) {
|
||||
const snapshot = await client.fetchAgent({ agentId });
|
||||
statuses.push(snapshot?.agent.status ?? "missing");
|
||||
if (i < samples - 1) {
|
||||
await sleep(intervalMs);
|
||||
}
|
||||
}
|
||||
return statuses;
|
||||
}
|
||||
|
||||
// NOTE: agent_stream events on the wire (AgentStreamEventPayloadSchema in
|
||||
// packages/protocol/src/messages.ts) do not include a "provider_subagent" variant. A backgrounded
|
||||
// subagent's descriptor updates are forwarded exclusively as separate "agent.provider_subagents.update"
|
||||
// messages (see forwardProviderSubagentUpdate in session.ts), and that push channel's delivery is
|
||||
// gated by capabilities this test's plain DaemonClient does not declare. list_provider_subagents is a
|
||||
// plain request/response RPC unaffected by that gating, so status history below polls it directly
|
||||
// instead of trying to reconstruct status transitions from the stream.
|
||||
type ProviderSubagentDescriptor = Awaited<
|
||||
ReturnType<DaemonClient["listProviderSubagents"]>
|
||||
>["subagents"][number];
|
||||
|
||||
interface ProviderSubagentPoll {
|
||||
subagent: ProviderSubagentDescriptor;
|
||||
// Every status observed while polling, in order, so a transient cancel cannot hide behind a
|
||||
// later "completed" read even though the store's status field is not expected to un-cancel.
|
||||
history: string[];
|
||||
}
|
||||
|
||||
// Polls agent.provider_subagents.list until the backgrounded helper is registered at all.
|
||||
// "Main's turn is running" (waitForAgentUpsert) fires on generic turn-start bookkeeping, which
|
||||
// can be true before Claude has actually issued the Agent tool call; canceling that early
|
||||
// cancels a turn with no helper launched yet, which is not what "Stop spares a helper" means to
|
||||
// test. This confirms the helper actually exists before the caller acts on it.
|
||||
async function waitForProviderSubagentToExist(
|
||||
client: DaemonClient,
|
||||
agentId: string,
|
||||
timeoutMs = 60_000,
|
||||
): Promise<ProviderSubagentDescriptor> {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
while (Date.now() < deadline) {
|
||||
const { subagents } = await client.listProviderSubagents(agentId);
|
||||
if (subagents[0]) {
|
||||
return subagents[0];
|
||||
}
|
||||
await sleep(300);
|
||||
}
|
||||
throw new Error(
|
||||
`Timed out waiting for a background helper to be registered for agent ${agentId}`,
|
||||
);
|
||||
}
|
||||
|
||||
// Claude starts the wake-up turn a moment after the helper's completion lands (0.1 to 5 s in
|
||||
// recorded traces), so poll for it instead of checking the instant the helper reads completed.
|
||||
// The daemon announces an autonomous turn to subscribers as a pushed "running" agent_update,
|
||||
// not as an agent_stream turn_started (that stream reaches the client that started a run).
|
||||
async function waitForWakeTurn(
|
||||
collector: ReturnType<typeof createMessageCollector>,
|
||||
agentId: string,
|
||||
fromIndex: number,
|
||||
timeoutMs = 30_000,
|
||||
): Promise<boolean> {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
while (Date.now() < deadline) {
|
||||
const window = collector.messages.slice(fromIndex);
|
||||
const woke =
|
||||
getAgentStatuses(window, agentId).includes("running") ||
|
||||
window.some(
|
||||
(message) =>
|
||||
message.type === "agent_stream" &&
|
||||
message.payload.agentId === agentId &&
|
||||
message.payload.event.type === "turn_started",
|
||||
);
|
||||
if (woke) return true;
|
||||
await sleep(500);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// The wake-up turn runs briefly after it opens, so the final state is read once it settles.
|
||||
async function waitForAgentStatus(
|
||||
client: DaemonClient,
|
||||
agentId: string,
|
||||
status: string,
|
||||
timeoutMs = 60_000,
|
||||
): Promise<string | undefined> {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
let last: string | undefined;
|
||||
while (Date.now() < deadline) {
|
||||
last = (await client.fetchAgent({ agentId }))?.agent.status;
|
||||
if (last === status) return last;
|
||||
await sleep(500);
|
||||
}
|
||||
return last;
|
||||
}
|
||||
|
||||
// Polls agent.provider_subagents.list until the single backgrounded helper leaves "running".
|
||||
// Scenarios in this file always launch exactly one background helper, so subagents[0] is it.
|
||||
async function waitForProviderSubagentTerminal(
|
||||
client: DaemonClient,
|
||||
agentId: string,
|
||||
timeoutMs = 90_000,
|
||||
): Promise<ProviderSubagentPoll> {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
const history: string[] = [];
|
||||
let lastSeen: ProviderSubagentDescriptor[] = [];
|
||||
while (Date.now() < deadline) {
|
||||
const { subagents } = await client.listProviderSubagents(agentId);
|
||||
lastSeen = subagents;
|
||||
const subagent = subagents[0];
|
||||
if (subagent) {
|
||||
history.push(subagent.status);
|
||||
if (subagent.status !== "running") {
|
||||
return { subagent, history };
|
||||
}
|
||||
}
|
||||
await sleep(1_000);
|
||||
}
|
||||
throw new Error(
|
||||
`Timed out waiting for the background helper to leave "running". history=${JSON.stringify(history)} lastSeen=${JSON.stringify(lastSeen)}`,
|
||||
);
|
||||
}
|
||||
|
||||
// Pulls the main agent's own assistant text via fetchAgentTimeline rather than the push
|
||||
// collector. Assistant text delivery is paced (docs/agent-stream-performance.md), so checking
|
||||
// the collector immediately after waitForFinish resolves can still miss the final text; the
|
||||
// timeline fetch is authoritative and matches what the pre-existing tests in this file do.
|
||||
async function fetchAssistantTexts(
|
||||
client: DaemonClient,
|
||||
agentId: string,
|
||||
limit = 100,
|
||||
): Promise<string[]> {
|
||||
const timeline = await client.fetchAgentTimeline(agentId, { limit });
|
||||
return timeline.entries
|
||||
.filter((entry) => entry.item.type === "assistant_message")
|
||||
.map((entry) => (entry.item as Extract<AgentTimelineItem, { type: "assistant_message" }>).text);
|
||||
}
|
||||
|
||||
async function fetchSubagentAssistantTexts(
|
||||
client: DaemonClient,
|
||||
agentId: string,
|
||||
subagentId: string,
|
||||
): Promise<string[]> {
|
||||
const timeline = await client.fetchProviderSubagentTimeline(agentId, subagentId, { limit: 50 });
|
||||
return timeline.rows
|
||||
.filter((row) => row.item.type === "assistant_message")
|
||||
.map((row) => (row.item as Extract<AgentTimelineItem, { type: "assistant_message" }>).text);
|
||||
}
|
||||
|
||||
describe("daemon E2E (real claude) - send message during tool call", () => {
|
||||
let canRun = false;
|
||||
interface SteeringResources {
|
||||
@@ -504,6 +664,141 @@ describe("daemon E2E (real claude) - send message during tool call", () => {
|
||||
}
|
||||
}, 210_000);
|
||||
|
||||
test("a background subagent keeps running after a message is sent while it works", async () => {
|
||||
// The scenario the rest of this file explicitly rules out: every other test here tells Claude
|
||||
// "Do not use a background task", so steering during a backgrounded subagent was never
|
||||
// covered. A subagent streams on the parent's channel, so a parent that mistakes the child's
|
||||
// frames for its own work reports "running" after it has already finished, and the message
|
||||
// sent into that window is refused, or delivered by cancelling the turn and taking the
|
||||
// subagent with it. Both outcomes are user-visible, and both are what this asserts against.
|
||||
const logger = pino({ level: "silent" });
|
||||
const resources: SteeringResources = {
|
||||
cwd: tmpCwd(),
|
||||
daemon: null,
|
||||
client: null,
|
||||
collector: null,
|
||||
};
|
||||
try {
|
||||
resources.daemon = await createTestPaseoDaemon({
|
||||
agentClients: { claude: new ClaudeAgentClient({ logger }) },
|
||||
logger,
|
||||
});
|
||||
resources.client = new DaemonClient({ url: `ws://127.0.0.1:${resources.daemon.port}/ws` });
|
||||
const { client, cwd } = resources;
|
||||
if (!client) throw new Error("Claude background-subagent test client was not created");
|
||||
await within("connect background-subagent test client", 15_000, client.connect());
|
||||
await within(
|
||||
"subscribe background-subagent test client",
|
||||
15_000,
|
||||
client.fetchAgents({ subscribe: {} }),
|
||||
);
|
||||
const agent = await within(
|
||||
"create background-subagent test agent",
|
||||
30_000,
|
||||
client.createAgent({
|
||||
cwd: cwd ?? process.cwd(),
|
||||
title: "claude-background-survives-send",
|
||||
...getRealProviderConfig("claude"),
|
||||
}),
|
||||
);
|
||||
resources.collector = createMessageCollector(client);
|
||||
await within(
|
||||
"launch one background subagent and end the turn",
|
||||
30_000,
|
||||
client.sendAgentMessage(
|
||||
agent.id,
|
||||
[
|
||||
"Use the Agent tool exactly once with run_in_background: true.",
|
||||
"subagent_type: general-purpose.",
|
||||
`description: "bg survivor".`,
|
||||
`prompt: "Use the Bash tool with run_in_background: true to run exactly: sleep 40.`,
|
||||
`Wait for its completion notification, then reply exactly: CHILD_DONE."`,
|
||||
"Immediately after launching it, reply with the single word LAUNCHED and end your turn.",
|
||||
"Do not wait for it. Do not call any other tools.",
|
||||
].join(" "),
|
||||
{ messageId: generateClientMessageId() },
|
||||
),
|
||||
);
|
||||
|
||||
// The main session has ended its turn. It must read as idle even though the subagent it
|
||||
// launched is still streaming on the shared channel.
|
||||
const afterLaunch = await within(
|
||||
"wait for the main session to go idle after launching the subagent",
|
||||
120_000,
|
||||
client.waitForFinish(agent.id, 110_000),
|
||||
);
|
||||
expect(
|
||||
afterLaunch.status,
|
||||
"a main session that finished its turn must not report busy because a subagent is running",
|
||||
).not.toBe("running");
|
||||
|
||||
// And a message sent in that window must be accepted rather than refused.
|
||||
const followUpId = generateClientMessageId();
|
||||
await within(
|
||||
"send a message to the idle main session while the subagent runs",
|
||||
30_000,
|
||||
client.sendAgentMessage(agent.id, "Are you there? Reply exactly: MAIN_ALIVE.", {
|
||||
messageId: followUpId,
|
||||
}),
|
||||
);
|
||||
await within(
|
||||
"wait for the main session to answer",
|
||||
120_000,
|
||||
client.waitForFinish(agent.id, 110_000),
|
||||
);
|
||||
|
||||
const timeline = await within(
|
||||
"fetch background-subagent timeline",
|
||||
15_000,
|
||||
client.fetchAgentTimeline(agent.id, { limit: 200 }),
|
||||
);
|
||||
const assistantText = timeline.entries
|
||||
.filter((entry) => entry.item.type === "assistant_message")
|
||||
.map(
|
||||
(entry) => (entry.item as Extract<AgentTimelineItem, { type: "assistant_message" }>).text,
|
||||
)
|
||||
.join("\\n");
|
||||
expect(
|
||||
assistantText,
|
||||
"the main session must be reachable while its background subagent still runs",
|
||||
).toContain("MAIN_ALIVE");
|
||||
|
||||
// The subagent must have survived the send rather than being cancelled with the turn. Its
|
||||
// status is read from agent.provider_subagents.list (see the note above
|
||||
// waitForProviderSubagentToExist): agent_stream carries no provider_subagent events.
|
||||
const { subagents } = await within(
|
||||
"list provider subagents after the send",
|
||||
15_000,
|
||||
client.listProviderSubagents(agent.id),
|
||||
);
|
||||
expect(subagents.length, "the background subagent must be tracked").toBeGreaterThan(0);
|
||||
expect(
|
||||
subagents.map((subagent) => subagent.status),
|
||||
"a backgrounded subagent must not be canceled by a message sent to the main session",
|
||||
).not.toContain("canceled");
|
||||
const { subagent, history } = await within(
|
||||
"wait for the background subagent to finish",
|
||||
90_000,
|
||||
waitForProviderSubagentTerminal(client, agent.id, 80_000),
|
||||
);
|
||||
expect(subagent.status, "the helper must complete, not be canceled or fail").toBe(
|
||||
"completed",
|
||||
);
|
||||
expect(history, "no status poll may read canceled").not.toContain("canceled");
|
||||
} finally {
|
||||
const cleanup = await Promise.allSettled([
|
||||
Promise.resolve(resources.collector?.unsubscribe()),
|
||||
resources.client?.close() ?? Promise.resolve(),
|
||||
resources.daemon?.close() ?? Promise.resolve(),
|
||||
]);
|
||||
if (resources.cwd) rmSync(resources.cwd, { recursive: true, force: true });
|
||||
const failures = cleanup.flatMap((result) =>
|
||||
result.status === "rejected" ? [result.reason] : [],
|
||||
);
|
||||
expect(failures, "Claude background-subagent E2E cleanup failures").toEqual([]);
|
||||
}
|
||||
}, 300_000);
|
||||
|
||||
test("Stop cancels a queued Claude steer before it can resume the interrupted turn", async () => {
|
||||
const logger = pino({ level: "silent" });
|
||||
const cwd = tmpCwd();
|
||||
@@ -678,4 +973,430 @@ describe("daemon E2E (real claude) - send message during tool call", () => {
|
||||
rmSync(cwd, { recursive: true, force: true });
|
||||
}
|
||||
}, 300_000);
|
||||
|
||||
test("a helper's own nested background job does not phantom-run the parent or kill the helper", async () => {
|
||||
// The exact reported bug: main backgrounds a helper, the helper itself starts its OWN
|
||||
// background job (a grandchild from main's perspective) and then keeps working in the
|
||||
// foreground. The grandchild's completion is bookkeeping that belongs to the helper, not to
|
||||
// main, and must not make main phantom-report "running" or get treated as busy.
|
||||
const logger = pino({ level: "silent" });
|
||||
const resources: SteeringResources = {
|
||||
cwd: tmpCwd(),
|
||||
daemon: null,
|
||||
client: null,
|
||||
collector: null,
|
||||
};
|
||||
try {
|
||||
resources.daemon = await createTestPaseoDaemon({
|
||||
agentClients: { claude: new ClaudeAgentClient({ logger }) },
|
||||
logger,
|
||||
});
|
||||
resources.client = new DaemonClient({ url: `ws://127.0.0.1:${resources.daemon.port}/ws` });
|
||||
const { client, cwd } = resources;
|
||||
if (!client) throw new Error("nested background-job test client was not created");
|
||||
await within("connect nested background-job test client", 15_000, client.connect());
|
||||
await within(
|
||||
"subscribe nested background-job test client",
|
||||
15_000,
|
||||
client.fetchAgents({ subscribe: {} }),
|
||||
);
|
||||
const agent = await within(
|
||||
"create nested background-job test agent",
|
||||
30_000,
|
||||
client.createAgent({
|
||||
cwd: cwd ?? process.cwd(),
|
||||
title: "claude-nested-background-job",
|
||||
...getRealProviderConfig("claude"),
|
||||
}),
|
||||
);
|
||||
resources.collector = createMessageCollector(client);
|
||||
|
||||
await within(
|
||||
"launch a helper with its own nested background job and end the turn",
|
||||
30_000,
|
||||
client.sendAgentMessage(
|
||||
agent.id,
|
||||
[
|
||||
"Use the Agent tool exactly once with run_in_background: true.",
|
||||
"subagent_type: general-purpose.",
|
||||
`description: "nested bg survivor".`,
|
||||
`prompt: "Use the Bash tool with run_in_background: true to run exactly:`,
|
||||
`python3 -c 'import time; time.sleep(5)'.`,
|
||||
`Immediately after starting it, without waiting for it, use the Bash tool again`,
|
||||
`in the foreground to run exactly: python3 -c 'import time; time.sleep(50)'.`,
|
||||
`After that foreground command finishes, reply exactly: CHILD_DONE."`,
|
||||
"Immediately after launching it, reply with the single word LAUNCHED and end your turn.",
|
||||
"Do not wait for it. Do not call any other tools.",
|
||||
].join(" "),
|
||||
{ messageId: generateClientMessageId() },
|
||||
),
|
||||
);
|
||||
|
||||
const afterLaunch = await within(
|
||||
"wait for the main session to go idle after launching the nested-background helper",
|
||||
120_000,
|
||||
client.waitForFinish(agent.id, 110_000),
|
||||
);
|
||||
expect(afterLaunch.status, "the main session must be idle once it replied LAUNCHED").toBe(
|
||||
"idle",
|
||||
);
|
||||
|
||||
// The helper's own nested background job (5s) finishes while the helper is still busy
|
||||
// in its unrelated foreground sleep (50s). Sample for 30s, well past the nested job's
|
||||
// completion even when the helper is slow to start it,
|
||||
// both by polling and by scanning every pushed agent_update in the window, so a brief
|
||||
// phantom flip cannot slip between polls.
|
||||
const sampleWindowStart = resources.collector.messages.length;
|
||||
const polledStatuses = await sampleAgentStatuses(client, agent.id, 11, 3_000);
|
||||
const pushedStatuses = getAgentStatuses(
|
||||
resources.collector.messages.slice(sampleWindowStart),
|
||||
agent.id,
|
||||
);
|
||||
const observedRunning = [...polledStatuses, ...pushedStatuses].filter(
|
||||
(status) => status === "running",
|
||||
);
|
||||
expect(
|
||||
observedRunning,
|
||||
`the parent must stay idle across the nested job's completion; polled=${JSON.stringify(polledStatuses)} pushed=${JSON.stringify(pushedStatuses)}`,
|
||||
).toEqual([]);
|
||||
|
||||
// A message sent in that window must still be answered normally.
|
||||
await within(
|
||||
"send PONG request while the nested job settles",
|
||||
30_000,
|
||||
client.sendMessage(agent.id, "Reply with exactly PONG.", {
|
||||
messageId: generateClientMessageId(),
|
||||
}),
|
||||
);
|
||||
await within("wait for the PONG reply", 60_000, client.waitForFinish(agent.id, 50_000));
|
||||
// Pulled via fetchAgentTimeline, not the push collector: assistant text delivery is paced
|
||||
// (docs/agent-stream-performance.md) and can trail waitForFinish's own completion signal,
|
||||
// so the collector can still be missing the final text the instant waitForFinish resolves.
|
||||
const pongTexts = await within(
|
||||
"fetch timeline for the PONG reply",
|
||||
15_000,
|
||||
fetchAssistantTexts(client, agent.id, 20),
|
||||
);
|
||||
expect(
|
||||
pongTexts.join("\n"),
|
||||
"the agent must answer PONG while the helper is still running",
|
||||
).toContain("PONG");
|
||||
|
||||
const messagesBeforeWake = resources.collector.messages.length;
|
||||
|
||||
// The helper itself must survive: never recorded canceled, and it eventually reports
|
||||
// CHILD_DONE from its own foreground sleep finishing.
|
||||
const { subagent, history } = await within(
|
||||
"wait for the nested-background helper to finish",
|
||||
90_000,
|
||||
waitForProviderSubagentTerminal(client, agent.id, 80_000),
|
||||
);
|
||||
expect(subagent.status, "the helper must complete, not be canceled or fail").toBe(
|
||||
"completed",
|
||||
);
|
||||
expect(
|
||||
history,
|
||||
`no provider subagent status poll may ever read canceled; history=${JSON.stringify(history)}`,
|
||||
).not.toContain("canceled");
|
||||
const subagentTexts = await fetchSubagentAssistantTexts(client, agent.id, subagent.id);
|
||||
expect(
|
||||
subagentTexts.join("\n"),
|
||||
"the helper's own transcript must contain its final CHILD_DONE reply",
|
||||
).toContain("CHILD_DONE");
|
||||
|
||||
// The helper's completion should wake the main session with a fresh turn (the
|
||||
// session-state-driven autonomous turn), separate from the PONG exchange above.
|
||||
const wokeMainAgent = await waitForWakeTurn(
|
||||
resources.collector,
|
||||
agent.id,
|
||||
messagesBeforeWake,
|
||||
);
|
||||
if (!wokeMainAgent) {
|
||||
const wakeWindowMessages = resources.collector.messages.slice(messagesBeforeWake);
|
||||
const wakeWindowEventTypes = wakeWindowMessages
|
||||
.filter(
|
||||
(message) => message.type === "agent_stream" && message.payload.agentId === agent.id,
|
||||
)
|
||||
.map((message) =>
|
||||
message.type === "agent_stream" ? message.payload.event.type : "unknown",
|
||||
);
|
||||
const timeline = await client
|
||||
.fetchAgentTimeline(agent.id, { limit: 100 })
|
||||
.catch(() => null);
|
||||
throw new Error(
|
||||
`the helper's completion must wake the main session with a new turn. ` +
|
||||
`wakeWindowEventTypes=${JSON.stringify(wakeWindowEventTypes)} ` +
|
||||
`recentTimeline=${JSON.stringify(timeline ? summarizeTimelineItems(timeline) : null)}`,
|
||||
);
|
||||
}
|
||||
|
||||
expect(await waitForAgentStatus(client, agent.id, "idle"), "the agent must end idle").toBe(
|
||||
"idle",
|
||||
);
|
||||
} finally {
|
||||
const cleanup = await Promise.allSettled([
|
||||
Promise.resolve(resources.collector?.unsubscribe()),
|
||||
resources.client?.close() ?? Promise.resolve(),
|
||||
resources.daemon?.close() ?? Promise.resolve(),
|
||||
]);
|
||||
if (resources.cwd) rmSync(resources.cwd, { recursive: true, force: true });
|
||||
const failures = cleanup.flatMap((result) =>
|
||||
result.status === "rejected" ? [result.reason] : [],
|
||||
);
|
||||
expect(failures, "nested background-job E2E cleanup failures").toEqual([]);
|
||||
}
|
||||
}, 300_000);
|
||||
|
||||
test("the app's default steer survives a backgrounded helper while the main session works", async () => {
|
||||
// appSettings.sendBehavior defaults to "steer" (packages/app/src/hooks/use-settings/storage.ts),
|
||||
// so this is what the app actually sends when a user replies while an agent looks busy.
|
||||
const logger = pino({ level: "silent" });
|
||||
const resources: SteeringResources = {
|
||||
cwd: tmpCwd(),
|
||||
daemon: null,
|
||||
client: null,
|
||||
collector: null,
|
||||
};
|
||||
try {
|
||||
resources.daemon = await createTestPaseoDaemon({
|
||||
agentClients: { claude: new ClaudeAgentClient({ logger }) },
|
||||
logger,
|
||||
});
|
||||
resources.client = new DaemonClient({ url: `ws://127.0.0.1:${resources.daemon.port}/ws` });
|
||||
const { client, cwd } = resources;
|
||||
if (!client) throw new Error("default-steer background-helper test client was not created");
|
||||
await within("connect default-steer test client", 15_000, client.connect());
|
||||
await within(
|
||||
"subscribe default-steer test client",
|
||||
15_000,
|
||||
client.fetchAgents({ subscribe: {} }),
|
||||
);
|
||||
const agent = await within(
|
||||
"create default-steer test agent",
|
||||
30_000,
|
||||
client.createAgent({
|
||||
cwd: cwd ?? process.cwd(),
|
||||
title: "claude-default-steer-background-helper",
|
||||
...getRealProviderConfig("claude"),
|
||||
}),
|
||||
);
|
||||
resources.collector = createMessageCollector(client);
|
||||
|
||||
await within(
|
||||
"launch the background helper and start the main session's own foreground sleep",
|
||||
30_000,
|
||||
client.sendAgentMessage(
|
||||
agent.id,
|
||||
[
|
||||
"Use the Agent tool exactly once with run_in_background: true.",
|
||||
"subagent_type: general-purpose.",
|
||||
`description: "bg survivor b".`,
|
||||
`prompt: "Use the Bash tool in the foreground to run exactly:`,
|
||||
`python3 -c 'import time; time.sleep(42)'. After it finishes, reply exactly: CHILD_DONE."`,
|
||||
"Do not wait for that background helper to finish before continuing.",
|
||||
"After launching it, use the Bash tool one more time yourself, WITHOUT run_in_background,",
|
||||
"to run exactly: python3 -c 'import time; time.sleep(16)'.",
|
||||
// Matching the proven pattern from the first test in this file: tell Claude to wait
|
||||
// for a later message rather than relying on the sleep call itself to block, since a
|
||||
// Bash call can resolve through Claude Code's own async task_notification path once a
|
||||
// background subagent is already active instead of blocking the turn.
|
||||
"Do not reply or finish your turn until a later user message arrives, no matter how",
|
||||
"quickly that Bash command finishes. When that later message arrives, address it and",
|
||||
"end your turn. Do not call any other tools.",
|
||||
].join(" "),
|
||||
{ messageId: generateClientMessageId() },
|
||||
),
|
||||
);
|
||||
|
||||
// Confirm the daemon considers main's own turn active before steering it. This does not
|
||||
// wait for a specific "sleep 16" shell call to show as running: Claude Code 2.1.280 can
|
||||
// report a slower Bash call through its own async task_notification tool instead of a
|
||||
// classic blocking call once a background subagent is already active, so pinning to a
|
||||
// literal running shell tool_call is not reliable here. Busy at the daemon level is what
|
||||
// "while main is busy with its own sleep" actually needs.
|
||||
await within(
|
||||
"confirm main's own turn is active before steering",
|
||||
30_000,
|
||||
client.waitForAgentUpsert(agent.id, (snapshot) => snapshot.status === "running", 25_000),
|
||||
);
|
||||
// The running status precedes the Agent tool call, so a steer sent on it alone can reach
|
||||
// Claude before the helper exists and prove nothing about a helper surviving it.
|
||||
await within(
|
||||
"confirm the background helper is registered before steering",
|
||||
60_000,
|
||||
waitForProviderSubagentToExist(client, agent.id, 55_000),
|
||||
);
|
||||
|
||||
await within(
|
||||
"send the app's default steer while main is busy with its own sleep",
|
||||
30_000,
|
||||
client.sendMessage(agent.id, "Reply with exactly PONG.", {
|
||||
messageId: generateClientMessageId(),
|
||||
activeTurnBehavior: "steer",
|
||||
}),
|
||||
);
|
||||
|
||||
const finish = await within(
|
||||
"wait for the main session to finish after the steer",
|
||||
120_000,
|
||||
client.waitForFinish(agent.id, 110_000),
|
||||
);
|
||||
expect(finish.status, "the main session must end idle after the steer").toBe("idle");
|
||||
// Pulled via fetchAgentTimeline, not the push collector: see fetchAssistantTexts.
|
||||
const postSteerTexts = await within(
|
||||
"fetch timeline for the post-steer PONG reply",
|
||||
15_000,
|
||||
fetchAssistantTexts(client, agent.id, 20),
|
||||
);
|
||||
expect(postSteerTexts.join("\n"), "PONG must be answered after the steer").toContain("PONG");
|
||||
|
||||
const { subagent, history } = await within(
|
||||
"wait for the background helper to finish",
|
||||
90_000,
|
||||
waitForProviderSubagentTerminal(client, agent.id, 80_000),
|
||||
);
|
||||
expect(subagent.status, "the helper must complete, not be canceled or fail").toBe(
|
||||
"completed",
|
||||
);
|
||||
expect(
|
||||
history,
|
||||
`no provider subagent status poll may ever read canceled; history=${JSON.stringify(history)}`,
|
||||
).not.toContain("canceled");
|
||||
const subagentTexts = await fetchSubagentAssistantTexts(client, agent.id, subagent.id);
|
||||
expect(
|
||||
subagentTexts.join("\n"),
|
||||
"the helper's own transcript must contain its final CHILD_DONE reply",
|
||||
).toContain("CHILD_DONE");
|
||||
} finally {
|
||||
const cleanup = await Promise.allSettled([
|
||||
Promise.resolve(resources.collector?.unsubscribe()),
|
||||
resources.client?.close() ?? Promise.resolve(),
|
||||
resources.daemon?.close() ?? Promise.resolve(),
|
||||
]);
|
||||
if (resources.cwd) rmSync(resources.cwd, { recursive: true, force: true });
|
||||
const failures = cleanup.flatMap((result) =>
|
||||
result.status === "rejected" ? [result.reason] : [],
|
||||
);
|
||||
expect(failures, "default-steer background-helper E2E cleanup failures").toEqual([]);
|
||||
}
|
||||
}, 300_000);
|
||||
|
||||
test("Stop cancels the main session's own turn but spares its background helper", async () => {
|
||||
const logger = pino({ level: "silent" });
|
||||
const resources: SteeringResources = {
|
||||
cwd: tmpCwd(),
|
||||
daemon: null,
|
||||
client: null,
|
||||
collector: null,
|
||||
};
|
||||
try {
|
||||
resources.daemon = await createTestPaseoDaemon({
|
||||
agentClients: { claude: new ClaudeAgentClient({ logger }) },
|
||||
logger,
|
||||
});
|
||||
resources.client = new DaemonClient({ url: `ws://127.0.0.1:${resources.daemon.port}/ws` });
|
||||
const { client, cwd } = resources;
|
||||
if (!client) throw new Error("Stop-spares-helper test client was not created");
|
||||
await within("connect Stop-spares-helper test client", 15_000, client.connect());
|
||||
await within(
|
||||
"subscribe Stop-spares-helper test client",
|
||||
15_000,
|
||||
client.fetchAgents({ subscribe: {} }),
|
||||
);
|
||||
const agent = await within(
|
||||
"create Stop-spares-helper test agent",
|
||||
30_000,
|
||||
client.createAgent({
|
||||
cwd: cwd ?? process.cwd(),
|
||||
title: "claude-stop-spares-helper",
|
||||
...getRealProviderConfig("claude"),
|
||||
}),
|
||||
);
|
||||
resources.collector = createMessageCollector(client);
|
||||
|
||||
await within(
|
||||
"launch the background helper and start the main session's own foreground sleep",
|
||||
30_000,
|
||||
client.sendAgentMessage(
|
||||
agent.id,
|
||||
[
|
||||
"Use the Agent tool exactly once with run_in_background: true.",
|
||||
"subagent_type: general-purpose.",
|
||||
`description: "bg survivor c".`,
|
||||
`prompt: "Use the Bash tool in the foreground to run exactly:`,
|
||||
`python3 -c 'import time; time.sleep(43)'. After it finishes, reply exactly: CHILD_DONE."`,
|
||||
"Do not wait for that background helper to finish before continuing.",
|
||||
"After launching it, use the Bash tool one more time yourself, WITHOUT run_in_background,",
|
||||
"to run exactly: python3 -c 'import time; time.sleep(23)'.",
|
||||
"Do not call any other tools.",
|
||||
].join(" "),
|
||||
{ messageId: generateClientMessageId() },
|
||||
),
|
||||
);
|
||||
|
||||
// Confirm the helper has actually been launched (registered) before Stop, not just that
|
||||
// main's turn shows "running": that status can flip true on generic turn-start bookkeeping
|
||||
// before Claude has issued the Agent tool call, and canceling that early cancels a turn
|
||||
// with no helper to spare yet.
|
||||
await within(
|
||||
"confirm the background helper is registered before Stop",
|
||||
60_000,
|
||||
waitForProviderSubagentToExist(client, agent.id, 55_000),
|
||||
);
|
||||
|
||||
const messagesBeforeStop = resources.collector.messages.length;
|
||||
await within("Stop the main session's own turn", 30_000, client.cancelAgent(agent.id));
|
||||
const afterStop = await within(
|
||||
"wait for the agent to go idle after Stop",
|
||||
60_000,
|
||||
client.waitForFinish(agent.id, 50_000),
|
||||
);
|
||||
expect(afterStop.status, "Stop must leave the agent idle").toBe("idle");
|
||||
|
||||
// The helper must survive Stop: it keeps running and later reports CHILD_DONE, which
|
||||
// wakes the main session with a fresh autonomous turn.
|
||||
const { subagent, history } = await within(
|
||||
"wait for the background helper to finish after Stop",
|
||||
90_000,
|
||||
waitForProviderSubagentTerminal(client, agent.id, 80_000),
|
||||
);
|
||||
expect(subagent.status, "Stop must not cancel or fail the background helper").toBe(
|
||||
"completed",
|
||||
);
|
||||
expect(
|
||||
history,
|
||||
`no provider subagent status poll may ever read canceled; history=${JSON.stringify(history)}`,
|
||||
).not.toContain("canceled");
|
||||
const subagentTexts = await fetchSubagentAssistantTexts(client, agent.id, subagent.id);
|
||||
expect(
|
||||
subagentTexts.join("\n"),
|
||||
"the helper's own transcript must contain its final CHILD_DONE reply",
|
||||
).toContain("CHILD_DONE");
|
||||
|
||||
const wokeMainAgent = await waitForWakeTurn(
|
||||
resources.collector,
|
||||
agent.id,
|
||||
messagesBeforeStop,
|
||||
);
|
||||
expect(
|
||||
wokeMainAgent,
|
||||
"the helper's completion after Stop must wake the main session with a new turn",
|
||||
).toBe(true);
|
||||
|
||||
expect(await waitForAgentStatus(client, agent.id, "idle"), "the agent must end idle").toBe(
|
||||
"idle",
|
||||
);
|
||||
} finally {
|
||||
const cleanup = await Promise.allSettled([
|
||||
Promise.resolve(resources.collector?.unsubscribe()),
|
||||
resources.client?.close() ?? Promise.resolve(),
|
||||
resources.daemon?.close() ?? Promise.resolve(),
|
||||
]);
|
||||
if (resources.cwd) rmSync(resources.cwd, { recursive: true, force: true });
|
||||
const failures = cleanup.flatMap((result) =>
|
||||
result.status === "rejected" ? [result.reason] : [],
|
||||
);
|
||||
expect(failures, "Stop-spares-helper E2E cleanup failures").toEqual([]);
|
||||
}
|
||||
}, 300_000);
|
||||
});
|
||||
|
||||
@@ -3,7 +3,7 @@ import { existsSync } from "node:fs";
|
||||
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir, uptime } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, beforeEach, describe, expect, test } from "vitest";
|
||||
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
|
||||
|
||||
import { readDaemonInstance, stopDaemonInstance } from "./daemon-instance.js";
|
||||
import { acquirePidLock, getPidLockInfo, isLocked, type PidLockInfo } from "./pid-lock.js";
|
||||
@@ -94,3 +94,42 @@ describe("daemon instance identity across a reboot", () => {
|
||||
await expect(readFile(join(paseoHome, "paseo.pid"), "utf-8")).rejects.toThrow(/ENOENT/);
|
||||
});
|
||||
});
|
||||
|
||||
// Linux keeps a boot's id while a VM is paused for a host sleep, though the VM's wall clock
|
||||
// runs ahead of its uptime once it resumes. A sleep longer than the time between boot and
|
||||
// the supervisor's start puts the wall-clock boot instant after the lock's startedAt.
|
||||
describe.runIf(process.platform === "linux")("daemon instance identity on Linux", () => {
|
||||
let paseoHome: string;
|
||||
|
||||
beforeEach(async () => {
|
||||
paseoHome = await mkdtemp(join(tmpdir(), "paseo-daemon-instance-linux-"));
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
vi.useRealTimers();
|
||||
await rm(paseoHome, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
test("a supervisor still holds the lock after its paused VM resumes", async () => {
|
||||
await acquirePidLock(paseoHome, null, { ownerPid: process.pid });
|
||||
|
||||
vi.useFakeTimers({ toFake: ["Date"] });
|
||||
vi.setSystemTime(Date.now() + uptime() * 1000 + 12 * 60 * 60_000);
|
||||
|
||||
expect(await readDaemonInstance(paseoHome)).toMatchObject({ pid: process.pid });
|
||||
expect(await isLocked(paseoHome)).toMatchObject({ locked: true });
|
||||
await expect(
|
||||
acquirePidLock(paseoHome, null, { ownerPid: process.pid + 10_000 }),
|
||||
).rejects.toThrow("Another Paseo daemon is already running");
|
||||
});
|
||||
|
||||
test("a lock written during another boot has no running owner", async () => {
|
||||
await writeLock(paseoHome, {
|
||||
...lockFor(process.pid, new Date()),
|
||||
bootId: "00000000-0000-0000-0000-000000000000",
|
||||
});
|
||||
|
||||
expect(await readDaemonInstance(paseoHome)).toBeNull();
|
||||
expect(await isLocked(paseoHome)).toMatchObject({ locked: false });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { formatAttachmentContentDisposition } from "./content-disposition.js";
|
||||
|
||||
describe("formatAttachmentContentDisposition", () => {
|
||||
test.each([
|
||||
{ fileName: "report.txt", disposition: 'attachment; filename="report.txt"' },
|
||||
{
|
||||
fileName: "café.txt",
|
||||
disposition: "attachment; filename=\"caf?.txt\"; filename*=UTF-8''caf%C3%A9.txt",
|
||||
},
|
||||
{
|
||||
fileName: "Résumé Ångström.pdf",
|
||||
disposition:
|
||||
"attachment; filename=\"R?sum? ?ngstr?m.pdf\"; filename*=UTF-8''R%C3%A9sum%C3%A9%20%C3%85ngstr%C3%B6m.pdf",
|
||||
},
|
||||
{
|
||||
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: "report-📄.txt",
|
||||
disposition:
|
||||
"attachment; filename=\"report-??.txt\"; filename*=UTF-8''report-%F0%9F%93%84.txt",
|
||||
},
|
||||
{
|
||||
fileName: 'say "hi" \\ bye.txt',
|
||||
disposition: 'attachment; filename="say \\"hi\\" \\\\ bye.txt"',
|
||||
},
|
||||
{
|
||||
fileName: "100%25 done.txt",
|
||||
disposition: "attachment; filename=\"100%25 done.txt\"; filename*=UTF-8''100%2525%20done.txt",
|
||||
},
|
||||
{
|
||||
fileName: "l'été (1)*.txt",
|
||||
disposition:
|
||||
"attachment; filename=\"l'?t? (1)*.txt\"; filename*=UTF-8''l%27%C3%A9t%C3%A9%20%281%29%2A.txt",
|
||||
},
|
||||
])("$fileName", ({ fileName, disposition }) => {
|
||||
expect(formatAttachmentContentDisposition(fileName)).toBe(disposition);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,32 @@
|
||||
const NON_PRINTABLE_ASCII = /[^\x20-\x7e]/g;
|
||||
const PERCENT_ESCAPE = /%[0-9A-Fa-f]{2}/;
|
||||
const QUOTED_STRING_SPECIALS = /[\\"]/g;
|
||||
const NON_ATTR_CHARS_LEFT_BY_URI_ENCODING = /['()*]/g;
|
||||
|
||||
/**
|
||||
* Content-Disposition for a file download (RFC 6266).
|
||||
*
|
||||
* Any name that is not plain ASCII also gets `filename*=UTF-8''…`, because
|
||||
* browsers do not read raw Latin-1 bytes in `filename` and fall back to a name
|
||||
* taken from the URL. A name with a percent escape gets it too, so browsers do
|
||||
* not decode the escape in `filename`.
|
||||
*/
|
||||
export function formatAttachmentContentDisposition(fileName: string): string {
|
||||
const asciiFileName = fileName.replace(NON_PRINTABLE_ASCII, "?");
|
||||
const disposition = `attachment; filename=${quote(asciiFileName)}`;
|
||||
if (asciiFileName === fileName && !PERCENT_ESCAPE.test(fileName)) {
|
||||
return disposition;
|
||||
}
|
||||
return `${disposition}; filename*=UTF-8''${encodeExtendedValue(fileName)}`;
|
||||
}
|
||||
|
||||
function quote(value: string): string {
|
||||
return `"${value.replace(QUOTED_STRING_SPECIALS, "\\$&")}"`;
|
||||
}
|
||||
|
||||
function encodeExtendedValue(value: string): string {
|
||||
return encodeURIComponent(value).replace(
|
||||
NON_ATTR_CHARS_LEFT_BY_URI_ENCODING,
|
||||
(char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`,
|
||||
);
|
||||
}
|
||||
@@ -308,7 +308,6 @@ export const PersistedConfigSchema = z
|
||||
|
||||
providers: ProvidersSchema.optional(),
|
||||
pluginRegistries: PluginRegistriesSchema.optional(),
|
||||
pluginRegistryEnabled: z.boolean().optional(),
|
||||
pluginsEnabled: z.boolean().optional(),
|
||||
plugins: z.record(PluginIdSchema, PluginSourceSchema).optional(),
|
||||
worktrees: WorktreesConfigSchema.optional(),
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { open, readFile, stat, unlink, utimes } from "node:fs/promises";
|
||||
import type { FileHandle } from "node:fs/promises";
|
||||
import { ensurePrivateDirectory } from "./private-files.js";
|
||||
@@ -15,6 +16,7 @@ export const pidLockInfoSchema = z.object({
|
||||
serverId: z.string().nullable().optional(),
|
||||
desktopManaged: z.boolean().optional(),
|
||||
heartbeat: z.literal(true).optional(),
|
||||
bootId: z.string().optional(),
|
||||
});
|
||||
|
||||
export interface PidLockInfo extends z.infer<typeof pidLockInfoSchema> {}
|
||||
@@ -62,16 +64,38 @@ function precedesThisBoot(startedAt: string): boolean {
|
||||
return stamped < Date.now() - uptime() * 1000 - BOOT_INSTANT_TOLERANCE_MS;
|
||||
}
|
||||
|
||||
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 {
|
||||
if (cachedBootId === undefined) {
|
||||
try {
|
||||
cachedBootId = readFileSync("/proc/sys/kernel/random/boot_id", "utf-8").trim() || null;
|
||||
} catch {
|
||||
cachedBootId = null;
|
||||
}
|
||||
}
|
||||
return cachedBootId;
|
||||
}
|
||||
|
||||
function writtenDuringThisBoot(lock: PidLockInfo): boolean {
|
||||
const thisBoot = currentBootId();
|
||||
if (lock.bootId && thisBoot) return lock.bootId === thisBoot;
|
||||
return !precedesThisBoot(lock.startedAt);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the process that wrote this lock is still running.
|
||||
*
|
||||
* A PID alone does not identify the supervisor: the operating system hands the number to
|
||||
* something else once the supervisor is gone, and a reboot reassigns it freely. A process
|
||||
* cannot predate the boot it runs under, so a lock stamped before this boot is abandoned
|
||||
* cannot predate the boot it runs under, so a lock written during another boot is abandoned
|
||||
* however alive its PID looks.
|
||||
*/
|
||||
export function isPidLockOwnerRunning(lock: PidLockInfo): boolean {
|
||||
if (precedesThisBoot(lock.startedAt)) return false;
|
||||
if (!writtenDuringThisBoot(lock)) return false;
|
||||
return isPidRunning(lock.pid);
|
||||
}
|
||||
|
||||
@@ -214,6 +238,7 @@ export async function acquirePidLock(
|
||||
}
|
||||
|
||||
// Create new lock with exclusive flag
|
||||
const bootId = currentBootId();
|
||||
const lockInfo: PidLockInfo = {
|
||||
pid: lockOwnerPid,
|
||||
startedAt: new Date().toISOString(),
|
||||
@@ -221,6 +246,7 @@ export async function acquirePidLock(
|
||||
uid: process.getuid?.() ?? 0,
|
||||
listen,
|
||||
heartbeat: true,
|
||||
...(bootId ? { bootId } : {}),
|
||||
...(process.env.PASEO_DESKTOP_MANAGED === "1" ? { desktopManaged: true } : {}),
|
||||
};
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
stat,
|
||||
writeFile,
|
||||
} from "node:fs/promises";
|
||||
import { createServer } from "node:http";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { pathToFileURL } from "node:url";
|
||||
@@ -418,7 +419,7 @@ describe("PluginService", () => {
|
||||
await service.stopAllPlugins();
|
||||
}, 20_000);
|
||||
|
||||
it("lists manifest descriptions for running and disabled plugins without hiding malformed entries", async () => {
|
||||
it("lists manifest metadata for running and disabled plugins without hiding malformed entries", async () => {
|
||||
const home = await mkdtemp(path.join(tmpdir(), "paseo-plugin-home-"));
|
||||
roots.push(home);
|
||||
const running = await createPlugin("running", "export default () => () => {};");
|
||||
@@ -426,7 +427,13 @@ describe("PluginService", () => {
|
||||
const malformed = await createPlugin("malformed", "export default () => () => {};");
|
||||
await writeFile(
|
||||
path.join(running, "paseo-plugin.json"),
|
||||
JSON.stringify({ id: "running", description: "Runs checks" }),
|
||||
JSON.stringify({
|
||||
id: "running",
|
||||
description: "Runs checks",
|
||||
name: "Checks",
|
||||
icon: "icon.png",
|
||||
media: ["screenshot.png", "https://example.com/demo.mp4"],
|
||||
}),
|
||||
);
|
||||
await writeFile(
|
||||
path.join(disabled, "paseo-plugin.json"),
|
||||
@@ -442,16 +449,123 @@ describe("PluginService", () => {
|
||||
await service.start();
|
||||
|
||||
expect(
|
||||
(await service.listPlugins()).map(({ id, description }) => ({ id, description })),
|
||||
(await service.listPlugins()).map(({ id, description, name, icon, media }) => ({
|
||||
id,
|
||||
description,
|
||||
name,
|
||||
icon,
|
||||
media,
|
||||
})),
|
||||
).toEqual([
|
||||
{ id: "disabled", description: "Waits until enabled" },
|
||||
{ id: "malformed", description: undefined },
|
||||
{ id: "running", description: "Runs checks" },
|
||||
{
|
||||
id: "running",
|
||||
description: "Runs checks",
|
||||
name: "Checks",
|
||||
icon: "icon.png",
|
||||
media: ["screenshot.png", "https://example.com/demo.mp4"],
|
||||
},
|
||||
]);
|
||||
await service.stopAllPlugins();
|
||||
});
|
||||
|
||||
it("prefers an existing directory and installs its selected plugin subdirectory", async () => {
|
||||
it("resolves a bare registry id even when a matching directory exists in the daemon cwd", async () => {
|
||||
const home = await mkdtemp(path.join(tmpdir(), "paseo-plugin-home-"));
|
||||
const owner = path.join(process.cwd(), `registry-shadow-${randomUUID()}`);
|
||||
await mkdir(owner);
|
||||
roots.push(home, owner);
|
||||
const source = `${path.basename(owner)}/example`;
|
||||
const repository = await createPlugin("registry-example", "export default () => () => {};\n");
|
||||
await mkdir(path.join(owner, "example"));
|
||||
await cp(repository, path.join(owner, "example"), { recursive: true });
|
||||
await runGitCommand(["init", "-b", "main"], { cwd: repository });
|
||||
await runGitCommand(["add", "-A"], { cwd: repository });
|
||||
await runGitCommand(
|
||||
[
|
||||
"-c",
|
||||
"user.name=Paseo Tests",
|
||||
"-c",
|
||||
"user.email=paseo@example.test",
|
||||
"commit",
|
||||
"-m",
|
||||
"fixture",
|
||||
],
|
||||
{ cwd: repository },
|
||||
);
|
||||
const { stdout } = await runGitCommand(["rev-parse", "HEAD"], { cwd: repository });
|
||||
const requests: Array<string | undefined> = [];
|
||||
const server = createServer((request, response) => {
|
||||
requests.push(request.url);
|
||||
response.setHeader("Content-Type", "application/json");
|
||||
response.end(
|
||||
JSON.stringify({
|
||||
id: source,
|
||||
name: "Example",
|
||||
description: "Test",
|
||||
categories: [],
|
||||
author: { github: path.basename(owner) },
|
||||
repository: { url: "https://github.com/fixture/example" },
|
||||
artifact: {
|
||||
kind: "git",
|
||||
remote: pathToFileURL(repository).href,
|
||||
commit: stdout.trim(),
|
||||
pluginPath: ".",
|
||||
},
|
||||
media: [],
|
||||
submittedAt: "2026-10-03",
|
||||
reviewedAt: "2026-10-03",
|
||||
updatedAt: "2026-10-03",
|
||||
publishedAt: "2026-10-03",
|
||||
readme: "# Test",
|
||||
}),
|
||||
);
|
||||
});
|
||||
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
|
||||
const address = server.address();
|
||||
if (!address || typeof address === "string") throw new Error("Missing registry address");
|
||||
const url = `http://127.0.0.1:${address.port}`;
|
||||
const store = createStore(home);
|
||||
store.patch({ pluginsEnabled: false });
|
||||
const service = bindTestSessionHost(
|
||||
new PluginService(pino({ level: "silent" }), store, "0.4.0", {
|
||||
managedSources: new ManagedPluginSources(home, { defaultUrl: url }),
|
||||
}),
|
||||
);
|
||||
try {
|
||||
await service.start();
|
||||
await expect(service.installSource({ source })).resolves.toMatchObject({
|
||||
id: "registry-example",
|
||||
status: "disabled",
|
||||
installation: {
|
||||
identity: { kind: "git", registry: { url, id: source } },
|
||||
currentRevision: stdout.trim(),
|
||||
},
|
||||
});
|
||||
expect(requests).toEqual([`/plugins/${source}.json`]);
|
||||
await expect(
|
||||
service.installSource({ source: `./${source}`, id: "local-example" }),
|
||||
).resolves.toMatchObject({
|
||||
installation: { identity: { kind: "directory", path: path.join(owner, "example") } },
|
||||
});
|
||||
expect(requests).toEqual([`/plugins/${source}.json`]);
|
||||
} finally {
|
||||
await service.stopAllPlugins();
|
||||
await new Promise<void>((resolve) => server.close(() => resolve()));
|
||||
}
|
||||
}, 30_000);
|
||||
|
||||
it("names a missing explicit directory instead of trying a managed source", async () => {
|
||||
const home = await mkdtemp(path.join(tmpdir(), "paseo-plugin-home-"));
|
||||
roots.push(home);
|
||||
const directory = path.join(home, "missing");
|
||||
const service = createService(home);
|
||||
await expect(service.installSource({ source: directory })).rejects.toThrow(
|
||||
`Plugin directory does not exist: ${directory}`,
|
||||
);
|
||||
});
|
||||
|
||||
it("installs an explicit directory and its selected plugin subdirectory", async () => {
|
||||
const home = await mkdtemp(path.join(tmpdir(), "paseo-plugin-home-"));
|
||||
roots.push(home);
|
||||
const repository = await mkdtemp(path.join(tmpdir(), "owner-repository-"));
|
||||
|
||||
@@ -21,6 +21,7 @@ import { BUILTIN_PROVIDER_IDS } from "@getpaseo/protocol/provider-manifest";
|
||||
import type { DaemonConfigStore } from "../daemon-config-store.js";
|
||||
import { type ManagedPluginCandidate, ManagedPluginSources } from "./managed-source.js";
|
||||
import { readPluginManifest } from "./manifest.js";
|
||||
import { expandTilde } from "../../utils/path.js";
|
||||
import { runPluginBuild } from "./preparation.js";
|
||||
import { PluginRuntime } from "./runtime.js";
|
||||
import { BuiltinPluginLoader, type BuiltinPlugin } from "./builtin/index.js";
|
||||
@@ -215,7 +216,12 @@ export class PluginService {
|
||||
}),
|
||||
};
|
||||
const manifest = await readPluginManifest(path.resolve(source.path)).catch(() => null);
|
||||
if (manifest?.description) item.description = manifest.description;
|
||||
if (manifest) {
|
||||
item.name = manifest.name;
|
||||
item.description = manifest.description;
|
||||
item.icon = manifest.icon;
|
||||
item.media = manifest.media;
|
||||
}
|
||||
item.installation = await this.managedSources
|
||||
?.describe(id, source.path)
|
||||
.catch(() => undefined);
|
||||
@@ -286,16 +292,11 @@ export class PluginService {
|
||||
if (input.id && this.builtinPluginIds.has(input.id)) {
|
||||
throw new Error(`Plugin ID "${input.id}" is reserved for a built-in plugin`);
|
||||
}
|
||||
const directDirectory = path.resolve(input.source);
|
||||
const explicit = /^(npm:|github:|git:(?!\/\/))/.test(input.source);
|
||||
const directInfo = await stat(directDirectory).catch(() => null);
|
||||
const reference = directInfo?.isDirectory()
|
||||
? { source: input.source, pluginPath: undefined }
|
||||
: parsePluginSourceReference(input.source);
|
||||
const directory = path.resolve(reference.source);
|
||||
let info = directInfo;
|
||||
if (!info?.isDirectory() && !explicit) info = await stat(directory).catch(() => null);
|
||||
if (info?.isDirectory()) {
|
||||
const reference = parsePluginSourceReference(input.source);
|
||||
if (reference.kind === "directory") {
|
||||
const directory = path.resolve(expandTilde(reference.source));
|
||||
const info = await stat(directory).catch(() => null);
|
||||
if (!info?.isDirectory()) throw new Error(`Plugin directory does not exist: ${directory}`);
|
||||
if (input.ref) throw new Error("Plugin --ref is only valid for Git sources");
|
||||
const pluginDirectory = resolveLocalPluginPath(directory, reference.pluginPath);
|
||||
return this.installDirectory({ path: pluginDirectory, id: input.id });
|
||||
|
||||
@@ -280,7 +280,60 @@ describe("managed Git plugin sources", () => {
|
||||
});
|
||||
|
||||
describe("registry plugin sources", () => {
|
||||
it("treats owner/repository as GitHub shorthand without contacting the registry while registry installs are off", async () => {
|
||||
it("explains how to choose a revision when --ref is used with a registry id", async () => {
|
||||
const home = await mkdtemp(path.join(tmpdir(), "paseo-registry-ref-home-"));
|
||||
roots.push(home);
|
||||
const sources = new ManagedPluginSources(home);
|
||||
await expect(
|
||||
sources.prepareInstall({ source: "fixture/example", ref: "main" }),
|
||||
).rejects.toThrow(
|
||||
"Registry installs pin the reviewed revision. Drop --ref, or install from an explicit github:owner/repository source to choose a revision.",
|
||||
);
|
||||
});
|
||||
|
||||
it("names the registry URL and recovery steps when the registry fetch fails", async () => {
|
||||
const home = await mkdtemp(path.join(tmpdir(), "paseo-registry-offline-home-"));
|
||||
roots.push(home);
|
||||
const server = createServer((request) => request.socket.destroy());
|
||||
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
|
||||
const address = server.address();
|
||||
if (!address || typeof address === "string") throw new Error("Missing registry address");
|
||||
const url = `http://127.0.0.1:${address.port}`;
|
||||
try {
|
||||
const sources = new ManagedPluginSources(home, { defaultUrl: url });
|
||||
await expect(sources.prepareInstall({ source: "fixture/example" })).rejects.toThrow(
|
||||
`Could not reach plugin registry ${url}/plugins/fixture/example.json. Plugin fixture/example was not installed. Retry or use an explicit npm: or github: source.`,
|
||||
);
|
||||
} finally {
|
||||
await new Promise<void>((resolve) => server.close(() => resolve()));
|
||||
}
|
||||
});
|
||||
|
||||
it("explains explicit local and GitHub sources when a registry ID is missing", async () => {
|
||||
const home = await mkdtemp(path.join(tmpdir(), "paseo-registry-missing-home-"));
|
||||
roots.push(home);
|
||||
const requests: Array<string | undefined> = [];
|
||||
const server = createServer((request, response) => {
|
||||
requests.push(request.url);
|
||||
response.writeHead(404).end();
|
||||
});
|
||||
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
|
||||
const address = server.address();
|
||||
if (!address || typeof address === "string") throw new Error("Missing registry address");
|
||||
try {
|
||||
const sources = new ManagedPluginSources(home, {
|
||||
defaultUrl: `http://127.0.0.1:${address.port}`,
|
||||
});
|
||||
await expect(sources.prepareInstall({ source: "fixture/missing" })).rejects.toThrow(
|
||||
"If you intended a local directory, use ./fixture/missing. If you intended a GitHub source, use git:fixture/missing, or a full Git URL for another Git host.",
|
||||
);
|
||||
expect(requests).toEqual(["/plugins/fixture/missing.json"]);
|
||||
} finally {
|
||||
await new Promise<void>((resolve) => server.close(() => resolve()));
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps explicit Git sources and persisted Git installs independent of the registry", async () => {
|
||||
const repository = await createRepository();
|
||||
const home = await mkdtemp(path.join(tmpdir(), "paseo-registry-off-home-"));
|
||||
roots.push(home);
|
||||
@@ -298,12 +351,34 @@ describe("registry plugin sources", () => {
|
||||
const sources = new ManagedPluginSources(home, {
|
||||
defaultUrl: `http://127.0.0.1:${address.port}`,
|
||||
});
|
||||
const candidate = await sources.prepareInstall({ source: "fixture/repository" });
|
||||
expect(candidate.record).toEqual({
|
||||
kind: "git",
|
||||
remote: "https://github.com/fixture/repository.git",
|
||||
});
|
||||
await sources.discard(candidate);
|
||||
for (const source of [
|
||||
"git:fixture/repository",
|
||||
"https://github.com/fixture/repository.git",
|
||||
]) {
|
||||
const candidate = await sources.place(
|
||||
"managed-example",
|
||||
await sources.prepareInstall({ source }),
|
||||
);
|
||||
expect(candidate.record).toEqual({
|
||||
kind: "git",
|
||||
remote: "https://github.com/fixture/repository.git",
|
||||
});
|
||||
sources.commit("managed-example", candidate.record);
|
||||
const restarted = new ManagedPluginSources(home, {
|
||||
defaultUrl: `http://127.0.0.1:${address.port}/changed`,
|
||||
});
|
||||
expect((await restarted.preview("managed-example", candidate.directory)).outcome).toBe(
|
||||
"current",
|
||||
);
|
||||
expect(
|
||||
(await restarted.describe("managed-example", candidate.directory)).identity,
|
||||
).toEqual({
|
||||
kind: "git",
|
||||
remote: "https://github.com/fixture/repository.git",
|
||||
pluginPath: ".",
|
||||
});
|
||||
await sources.discard(candidate);
|
||||
}
|
||||
});
|
||||
expect(requests).toEqual([]);
|
||||
} finally {
|
||||
@@ -332,12 +407,17 @@ describe("registry plugin sources", () => {
|
||||
intent: string | string[] | undefined;
|
||||
authorization: string | undefined;
|
||||
}> = [];
|
||||
let missing = false;
|
||||
const server = createServer((req, res) => {
|
||||
requests.push({
|
||||
path: req.url,
|
||||
intent: req.headers["x-paseo-install"],
|
||||
authorization: req.headers.authorization,
|
||||
});
|
||||
if (missing) {
|
||||
res.writeHead(404).end();
|
||||
return;
|
||||
}
|
||||
res.setHeader("Content-Type", "application/json");
|
||||
res.end(
|
||||
JSON.stringify({
|
||||
@@ -353,7 +433,7 @@ describe("registry plugin sources", () => {
|
||||
commit,
|
||||
pluginPath: "packages/example",
|
||||
},
|
||||
screenshots: [],
|
||||
media: [],
|
||||
submittedAt: "2026-10-03",
|
||||
reviewedAt: "2026-10-03",
|
||||
updatedAt: "2026-10-03",
|
||||
@@ -369,7 +449,6 @@ describe("registry plugin sources", () => {
|
||||
const url = `http://${host}/internal`;
|
||||
try {
|
||||
const sources = new ManagedPluginSources(home, {
|
||||
enabled: true,
|
||||
defaultUrl: url,
|
||||
registries: { [host]: { authorization: "Bearer test" } },
|
||||
});
|
||||
@@ -380,7 +459,11 @@ describe("registry plugin sources", () => {
|
||||
).toBe("managed-example");
|
||||
await sources.verifyCandidate("managed-example", candidate);
|
||||
sources.commit("managed-example", candidate.record);
|
||||
const preview = await sources.preview("managed-example", candidate.directory);
|
||||
const restarted = new ManagedPluginSources(home, {
|
||||
defaultUrl: "http://127.0.0.1:1/changed",
|
||||
registries: { [host]: { authorization: "Bearer test" } },
|
||||
});
|
||||
const preview = await restarted.preview("managed-example", candidate.directory);
|
||||
expect(preview.outcome).toBe("current");
|
||||
expect(preview.current?.identity).toEqual({
|
||||
kind: "git",
|
||||
@@ -388,6 +471,10 @@ describe("registry plugin sources", () => {
|
||||
pluginPath: "packages/example",
|
||||
registry: { url, id: "acme/example" },
|
||||
});
|
||||
missing = true;
|
||||
await expect(restarted.preview("managed-example", candidate.directory)).rejects.toThrow(
|
||||
"Check that the installed plugin is still published in this registry before updating",
|
||||
);
|
||||
expect(requests).toEqual([
|
||||
{ path: "/internal/plugins/acme/example.json", intent: "1", authorization: "Bearer test" },
|
||||
{
|
||||
@@ -395,6 +482,11 @@ describe("registry plugin sources", () => {
|
||||
intent: undefined,
|
||||
authorization: "Bearer test",
|
||||
},
|
||||
{
|
||||
path: "/internal/plugins/acme/example.json",
|
||||
intent: undefined,
|
||||
authorization: "Bearer test",
|
||||
},
|
||||
]);
|
||||
} finally {
|
||||
await new Promise<void>((resolve, reject) =>
|
||||
@@ -424,27 +516,17 @@ it("installs and updates only the npm artifacts pinned by the plugin registry",
|
||||
const server = createServer((request, response) => {
|
||||
intents.push(request.headers["x-paseo-install"]);
|
||||
response.end(
|
||||
// Install reads only the ID and artifact, so the document omits the directory's display fields.
|
||||
JSON.stringify({
|
||||
id: "acme/example",
|
||||
name: "Example",
|
||||
description: "Test",
|
||||
categories: [],
|
||||
author: { github: "acme" },
|
||||
repository: { url: "https://github.com/acme/example" },
|
||||
artifact: { kind: "npm", package: "paseo-fixture-plugin", ...pin },
|
||||
screenshots: [],
|
||||
submittedAt: "2026-10-03",
|
||||
reviewedAt: "2026-10-03",
|
||||
updatedAt: "2026-10-03",
|
||||
publishedAt: "2026-10-03",
|
||||
readme: "# Example",
|
||||
}),
|
||||
);
|
||||
});
|
||||
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
|
||||
const address = server.address();
|
||||
if (!address || typeof address === "string") throw new Error("Missing registry address");
|
||||
const options = { enabled: true, defaultUrl: `http://127.0.0.1:${address.port}` };
|
||||
const options = { defaultUrl: `http://127.0.0.1:${address.port}` };
|
||||
try {
|
||||
const sources = new ManagedPluginSources(home, options);
|
||||
const candidate = await sources.place(
|
||||
|
||||
@@ -147,11 +147,13 @@ export class ManagedPluginSources {
|
||||
input: InstallInput,
|
||||
target?: PluginUpdateTarget,
|
||||
): Promise<ManagedPluginCandidate> {
|
||||
const registry = this.registryOptions.enabled
|
||||
? parsePluginRegistryReference(input.source, this.registryOptions.defaultUrl)
|
||||
: null;
|
||||
const registry = parsePluginRegistryReference(input.source, this.registryOptions.defaultUrl);
|
||||
if (registry) {
|
||||
if (input.ref || input.pluginPath)
|
||||
if (input.ref)
|
||||
throw new Error(
|
||||
"Registry installs pin the reviewed revision. Drop --ref, or install from an explicit github:owner/repository source to choose a revision.",
|
||||
);
|
||||
if (input.pluginPath)
|
||||
throw new Error("Registry sources use their reviewed artifact path and revision");
|
||||
const resolved = await resolveRegistryPlugin(registry, this.registryOptions, true);
|
||||
const candidate = await this.prepareInstall(resolved.input, resolved.target);
|
||||
@@ -175,7 +177,7 @@ export class ManagedPluginSources {
|
||||
sourceRoot = path.join(versionRoot, "node_modules", artifact.packageName);
|
||||
record = { kind: "npm" };
|
||||
} else {
|
||||
const remote = normalizeGitSource(input.source, !this.registryOptions.enabled);
|
||||
const remote = normalizeGitSource(input.source);
|
||||
sourceRoot = path.join(versionRoot, "checkout");
|
||||
await clone(remote, sourceRoot);
|
||||
const commit = await resolveRequestedRef(sourceRoot, input.ref);
|
||||
@@ -227,7 +229,7 @@ export class ManagedPluginSources {
|
||||
const location = this.locate(pluginId, configuredPath);
|
||||
let target: PluginUpdateTarget;
|
||||
let outcome: PluginUpdatePreview["outcome"];
|
||||
if (this.registryOptions.enabled && current.identity.registry) {
|
||||
if (current.identity.registry) {
|
||||
if (selection) throw new Error("Registry updates use only the reviewed registry pin");
|
||||
const resolved = await resolveRegistryPlugin(
|
||||
current.identity.registry,
|
||||
@@ -304,7 +306,7 @@ export class ManagedPluginSources {
|
||||
await this.assertCurrent(proposal, configuredPath);
|
||||
const identity = this.locate(proposal.id, configuredPath).identity;
|
||||
const record = this.records[proposal.id];
|
||||
if (this.registryOptions.enabled && identity.kind !== "directory" && identity.registry) {
|
||||
if (identity.kind !== "directory" && identity.registry) {
|
||||
const resolved = await resolveRegistryPlugin(identity.registry, this.registryOptions, false);
|
||||
assertRegistryArtifactIdentity(identity, resolved.artifact);
|
||||
if (!isDeepStrictEqual(resolved.target, proposal.target))
|
||||
@@ -436,10 +438,9 @@ function reviewLinks(current: PluginInstallation, target: PluginUpdateTarget): s
|
||||
}
|
||||
return [];
|
||||
}
|
||||
/** Bare owner/repo is GitHub shorthand unless registry references own that syntax. */
|
||||
function normalizeGitSource(source: string, bareGitHubShorthand: boolean): string {
|
||||
const expandsShorthand =
|
||||
bareGitHubShorthand || source.startsWith("github:") || source.startsWith("git:");
|
||||
/** Only explicit Git prefixes expand GitHub shorthand. */
|
||||
function normalizeGitSource(source: string): string {
|
||||
const expandsShorthand = source.startsWith("github:") || source.startsWith("git:");
|
||||
if (source.startsWith("github:")) {
|
||||
const shorthand = source.slice(7);
|
||||
if (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(shorthand)) {
|
||||
|
||||
@@ -1,13 +1,19 @@
|
||||
import {
|
||||
PublishedPluginDetailSchema,
|
||||
PluginRegistryArtifactSchema,
|
||||
PluginRegistryIdSchema,
|
||||
type PluginRegistries,
|
||||
type PluginRegistryIdentity,
|
||||
} from "@getpaseo/protocol/plugin-registry";
|
||||
import type { PluginUpdateTarget } from "@getpaseo/protocol/messages";
|
||||
import { z } from "zod";
|
||||
|
||||
// Install reads only these fields; the rest of a published plugin is the directory's display data.
|
||||
const RegistryInstallDocumentSchema = z.object({
|
||||
id: PluginRegistryIdSchema,
|
||||
artifact: PluginRegistryArtifactSchema,
|
||||
});
|
||||
|
||||
export interface RegistryOptions {
|
||||
/** Off: bare owner/repo is GitHub shorthand and no registry is contacted. */
|
||||
enabled?: boolean;
|
||||
defaultUrl?: string;
|
||||
registries?: PluginRegistries;
|
||||
}
|
||||
@@ -29,14 +35,29 @@ export async function resolveRegistryPlugin(
|
||||
const headers: Record<string, string> = {};
|
||||
if (authorization) headers.Authorization = authorization;
|
||||
if (install) headers["X-Paseo-Install"] = "1";
|
||||
const response = await fetch(`${identity.url.replace(/\/+$/, "")}/plugins/${identity.id}.json`, {
|
||||
headers,
|
||||
redirect: "error",
|
||||
signal: AbortSignal.timeout(30000),
|
||||
});
|
||||
const url = `${identity.url.replace(/\/+$/, "")}/plugins/${identity.id}.json`;
|
||||
let response: Response;
|
||||
try {
|
||||
response = await fetch(url, {
|
||||
headers,
|
||||
redirect: "error",
|
||||
signal: AbortSignal.timeout(30000),
|
||||
});
|
||||
} catch (cause) {
|
||||
const guidance = install
|
||||
? `Plugin ${identity.id} was not installed. Retry or use an explicit npm: or github: source.`
|
||||
: `Could not check updates for ${identity.id}. Retry later.`;
|
||||
throw new Error(`Could not reach plugin registry ${url}. ${guidance}`, { cause });
|
||||
}
|
||||
if (response.status === 404) {
|
||||
const guidance = install
|
||||
? `If you intended a local directory, use ./${identity.id}. If you intended a GitHub source, use git:${identity.id}, or a full Git URL for another Git host.`
|
||||
: "Check that the installed plugin is still published in this registry before updating.";
|
||||
throw new Error(`Plugin ${identity.id} was not found in registry ${base.host}. ${guidance}`);
|
||||
}
|
||||
if (!response.ok)
|
||||
throw new Error(`Registry ${base.host} returned ${response.status} for ${identity.id}`);
|
||||
const plugin = PublishedPluginDetailSchema.parse(await response.json());
|
||||
const plugin = RegistryInstallDocumentSchema.parse(await response.json());
|
||||
if (plugin.id !== identity.id) throw new Error("Registry returned a different plugin ID");
|
||||
const artifact = plugin.artifact;
|
||||
const target: PluginUpdateTarget =
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user