Compare commits

...
Author SHA1 Message Date
Mohamed Boudra b2ba24ee73 fix(cli): close Hub run gaps for unchecked inputs, expired logins, and retries 2026-11-30 08:52:15 +01:00
Mohamed Boudra 41a157cbb4 docs(cli): note Hub run key scopes and prompt contents 2026-11-30 08:52:15 +01:00
Mohamed Boudra 3d087e5399 feat(cli): run Hub manual triggers with paseo hub run
Starting a manual.run trigger meant hand-writing a curl request with a
project slug, actor, delivery key and a space-separated input string.

`paseo hub run <trigger> [prompt]` sends that request with the stored
Hub login or an API key. It rejects inputs Hub would silently read as
prompt text, lists declared inputs when Hub rejects them, and asks for
missing ones in a terminal.
2026-11-30 08:52:15 +01:00
Daniel JB ClarkandClaude Sonnet 5.5 e31f379d54 perf(desktop): ship precompressed web assets in app-dist (#10635)
The desktop app's Resources/app-dist was copied raw from packages/app/dist,
so the daemon-served web UI first load transferred about 25 MB. The server
already prefers `<asset>.br` / `<asset>.gz` beside an asset (web-ui.ts), but
only the standalone `build:daemon-web-ui` ever created them.

build:desktop now precompresses packages/app/dist after `expo export` and
before electron-builder copies it to app-dist via extraResources (no files
glob excludes .br/.gz). The compression code moves to
scripts/precompress-assets.mjs, shared with build-daemon-web-ui.mjs, with the
same extension list and brotli max quality (about 38 s for the 25 MB bundle;
first load drops to about 4 MB with br, 5.6 MB with gzip).

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-30 14:51:00 +07:00
paseo-bot[bot]andMohamed Boudra f37991f8d4 Reopen ACP chats with a rejected saved thinking level (#10333)
* fix(acp): reopen chats with a rejected saved thinking level

A stale thinking override aborted resume after the provider loaded the session. Preserve the loaded session when the provider rejects a value that its current model no longer offers, so the user can open the chat and select a supported value.

* fix(acp): report the restored model’s thinking level

Restoring the saved model can change the active thinking level before Paseo replays a saved preference. Read the level from the model response so a stale preference falls back to the current model’s setting.

* fix(acp): apply the thinking level from every full settings response

Restoring the saved mode can change the thinking level just like restoring the model. Keep the active level synchronized when accepting the provider’s selectors so resume reports the current setting after either change.

* fix(acp): refresh the thinking level only while restoring a chat

Reading the level from every settings response also changed what the thinking
picker shows after a live model switch. This fix is about reopening a saved
chat, so the read now happens once, after the saved mode and model are
restored. Open chats behave as before; #10336 tracks their picker updates.

---------

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Mohamed Boudra <boudra.moha@gmail.com>
2026-11-30 14:40:52 +07:00
paseo-ai[bot] dbc3983314 fix: update lockfile signatures and Nix hash [skip ci] 2026-11-30 07:18:51 +00:00
paseo-bot[bot]andjsilhan b5f56a70f6 Finish Pi extension prompts when their work ends (#10572)
Closes #10548

Co-authored-by: jsilhan <jan.silhan@bighub.cz>
2026-11-30 14:09:32 +07:00
paseo-bot[bot]andLiebeLee 5ef84c6bc0 Keep workspace controls tappable after dismissing an opening file sheet (#11317)
Closes #11309

Co-authored-by: LiebeLee <27326628+LiebeLee@users.noreply.github.com>
2026-11-30 13:43:39 +07:00
paseo-bot[bot] 1e8bf499af test(terminal): restore AppImage zsh coverage (#11395)
The palette check reads the terminal overrides before building the child environment. Supply an empty override object so the AppImage fixture reaches its shell assertions.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-30 06:43:19 +00:00
paseo-bot[bot] 8849fd06c9 fix(desktop): avoid RPM conflicts with other Electron apps (#11354)
Electron RPMs can contain the same binary at different install paths. Turn off generated build-ID links so their RPMs can install alongside Paseo.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-30 13:39:34 +07:00
paseo-bot[bot]andmonarchmaisuriya 1cd2460a51 Restore finished Claude subagents after reopening (#10848)
Closes #8959

Co-authored-by: monarchmaisuriya <monarchmaisuriya7600@gmail.com>
2026-11-30 13:34:30 +07:00
yz 75abc739e6 Fix header taps scrolling panes to the top on iOS (#11262) 2026-11-30 13:33:06 +07:00
Bhaskaran S 728e09f0bb fix(app): archive closed subagents from 'Archive finished subagents' (#10865)
A child whose runtime was released (status closed) was listed in the
subagent track but treated as not finished, so the button skipped it
silently. Treat closed like idle/error, keeping the background-work and
parent/archived rechecks. Adds regression tests.
2026-11-30 13:29:52 +07:00
Mohamed Boudra cf68bd76d4 fix(server): deliver voice-only speak tool regardless of MCP injection policy (#11161)
* fix(server): deliver voice-only speak tool regardless of MCP injection policy

* fix(server): track HTTP MCP capability separately and validate voice speak before reload close
2026-11-30 13:22:56 +07:00
Mohamed Boudra 7f2ece0556 chore(release): reconcile v0.18.2 (#11393) 2026-11-30 13:15:10 +07:00
Mohamed Boudra f81d433afc fix(app): keep batched user messages on distinct timeline row keys (#11324)
* fix(app): keep batched user messages on distinct timeline row ids

When multiple queued or joined human prompts share a single provider turn, projectAgentMessages emits separate user_message rows with distinct clientMessageIds and the same provider messageId. appendUserMessage and buildCanonicalUserMessage bypassed createUserMessage's clientMessageId ?? messageId precedence by passing id: messageId, producing duplicate React keys in WebStreamViewport mountedHistoryRows.

Prefer clientMessageId over messageId when building canonical user rows, and normalize previously cached or retained rows whose id inherited a shared provider messageId during reconciliation and replica-cache hydration.

* refactor(app): keep legacy user row id heal at replica cache boundary

Pre-fix rows with id === messageId only persist in the replica cache, which already normalizes them on read. Move the helper into replica-cache with a COMPAT tag and remove the unreachable merge-path heal in produceUserMessage.
2026-11-30 13:14:41 +07:00
paseo-bot[bot] a931ac1cd7 test(cli): isolate worktree tests from the launch checkout (#11392)
An explicit daemon endpoint resolves relative paths from the daemon's working directory. Start the test daemon in the fixture repository so the checks exercise that path without reading the launch checkout.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-30 06:13:42 +00:00
paseo-bot[bot] cdfc788946 fix(cli): isolate the usage test from host reports (#11391)
The test daemon inherited settings that let built-in sources discover reports outside its temporary home. Give the usage fixture an explicit base environment so the list and removal assertions depend only on its plugin.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-30 06:13:10 +00:00
paseo-bot[bot]andShane Su 8be985cb27 Keep Muse token totals and context usage in the same session snapshot (#11389)
Co-authored-by: Shane Su <26364206+suniceman@users.noreply.github.com>
2026-11-30 05:42:58 +00:00
977049557a perf(app): open the mobile app faster after a cold launch (#11390)
A cold launch on Hermes keeps the JavaScript thread busy until the restored
workspace is on screen, so work removed there is launch time removed. A
sampled profile of a release build showed four costs that bought nothing:

- The provider snapshot cache rebuilt its size-and-age index on every
  launch by reading, parsing and validating every stored snapshot, about
  390 ms with a full 4 MB cache. The index is now stored and trusted for
  keys that still exist. Storage keys stay the authority: an indexed key
  that is gone is dropped, and a stored key the index does not list is
  read and measured.
- Zod compiled a parser for each object schema with `new Function`. Hermes
  has no JIT, so the compile was pure cost, about 145 ms. Native builds turn
  it off before any schema module loads; web and desktop keep it because V8
  optimises the compiled parsers.
- `localeCompare` builds a collator on every call, which dominated the
  project and workspace name sorts. They now share one collator.
- The replica cache measured each payload with a per-character loop, over
  about 1 MB of directory rows on every refresh.

Time from tap to the workspace on an Android emulator, release build,
median of six cold launches: 2.45 s to 1.76 s with a full provider cache,
2.30 s to 1.67 s with a small one.

Co-authored-by: Marcel Wysocki <4222082+maci0@users.noreply.github.com>
Co-authored-by: luke <1686898+luoph@users.noreply.github.com>
2026-11-30 12:37:40 +07:00
Mohamed Boudra 5d678b3848 perf(app): stop hidden workspaces re-rendering git actions on every switch (#11332)
Each retained workspace in the deck mounts git actions twice (header and
Changes surface). useGitActions subscribed to the whole workspaces map of the
host and resolved its workspace from the global active route. Any workspace
switch replaces that map, so every hidden workspace re-ran the hook and
rebuilt its actions. A hidden workspace also resolved the active workspace as
the one its archive action targets.

Callers now pass their own workspaceId, and the hook selects only that
descriptor, which the session store keeps by identity when other workspaces
change. The redirect after an archive reads the focused workspace when the
archive starts.
2026-11-30 12:23:58 +07:00
Mohamed Boudra 26550ff73f perf(app): skip the Markdown parse for replies that only link outside the workspace (#11327)
Opening a chat parsed every assistant reply that contained any Markdown link into a full
mdast tree, because a link into the workspace gets a hover title. A reply whose links all
point elsewhere produces no edit, so the parse and its garbage were wasted. Parse only when
the source contains the workspace root after a link, or a backslash escape that could spell
it. Character references already take the parse path through the `&` check.
2026-11-30 12:23:30 +07:00
116 changed files with 4668 additions and 385 deletions
+1 -1
View File
@@ -59,7 +59,7 @@ jobs:
filters: .github/ci-paths.yml
- name: Validate CI contracts
run: node --test scripts/ci-workflow.test.mjs scripts/daemon-launch-contract.test.mjs scripts/changelog-utils.test.mjs scripts/release-version-utils.test.mjs scripts/publish-release-packages.test.mjs scripts/push-current-release-tag.test.mjs scripts/reconcile-release.test.mjs scripts/sync-fdroid-changelogs.test.mjs scripts/sync-release-notes-from-changelog.test.mjs scripts/upload-release-assets.test.mjs
run: node --test scripts/ci-workflow.test.mjs scripts/daemon-launch-contract.test.mjs scripts/changelog-utils.test.mjs scripts/release-version-utils.test.mjs scripts/publish-release-packages.test.mjs scripts/push-current-release-tag.test.mjs scripts/reconcile-release.test.mjs scripts/sync-fdroid-changelogs.test.mjs scripts/sync-release-notes-from-changelog.test.mjs scripts/upload-release-assets.test.mjs scripts/precompress-assets.test.mjs
quality:
name: quality
+93
View File
@@ -1,5 +1,98 @@
# Changelog
## 0.18.2 - 2026-11-30
- **Redesigned model picker:** Pick models from a two-pane desktop view with cross-provider search, an in-place phone drawer with a thinking slider, and per-provider model lists in settings. ([#11186](https://github.com/getpaseo/paseo/pull/11186), [#11280](https://github.com/getpaseo/paseo/pull/11280), [#11295](https://github.com/getpaseo/paseo/pull/11295), [#11371](https://github.com/getpaseo/paseo/pull/11371), [#11313](https://github.com/getpaseo/paseo/pull/11313))
- **File actions and filter:** Filter the Files tree by name, and reveal, open in your default app, download, or copy paths from chat file links, file tabs, and sidebar trees. ([#11073](https://github.com/getpaseo/paseo/pull/11073), [#11299](https://github.com/getpaseo/paseo/pull/11299), [#11320](https://github.com/getpaseo/paseo/pull/11320) by [@YASICJUNWOO](https://github.com/YASICJUNWOO), [@apple-ouyang](https://github.com/apple-ouyang), [@iqshen](https://github.com/iqshen), [@Ctrl-Creeper](https://github.com/Ctrl-Creeper), [@softyoda](https://github.com/softyoda))
- **New butterfly app icons:** Desktop and mobile now share the updated butterfly icon, with proper macOS Dock sizing and system lighting. ([#11091](https://github.com/getpaseo/paseo/pull/11091))
- **Live usage updates:** Claude and Codex usage summaries now update as turns finish instead of waiting for the five-minute poll. ([#11170](https://github.com/getpaseo/paseo/pull/11170) by [@Zayooo00](https://github.com/Zayooo00))
- **Faster CLI startup:** Paseo CLI commands now start 7 to 22 times faster by loading only the requested command. ([#11155](https://github.com/getpaseo/paseo/pull/11155), [#11193](https://github.com/getpaseo/paseo/pull/11193), [#11363](https://github.com/getpaseo/paseo/pull/11363))
- **Native ACP question cards:** Plugin ACP providers such as Antigravity now pause on interactive form questions with Paseo's question card instead of printing numbered lists. ([#11135](https://github.com/getpaseo/paseo/pull/11135) by [@djbclark](https://github.com/djbclark), [@krazyjakee](https://github.com/krazyjakee))
- **OMP background jobs:** OMP agents now list running background tasks above the composer and let you stop them without interrupting the agent. ([#11270](https://github.com/getpaseo/paseo/pull/11270) by [@mcowger](https://github.com/mcowger))
- **Plugin HTTP tunnels:** Plugins can now expose local HTTP services at public HTTPS URLs through tunnel providers, with built-in `cloudflared` and Tailscale Funnel support. ([#11036](https://github.com/getpaseo/paseo/pull/11036))
### Added
- Added `--all` to `paseo schedule ls` to list schedules targeting existing agents, and noted hidden schedules in table output ([#11243](https://github.com/getpaseo/paseo/pull/11243) by [@suniceman](https://github.com/suniceman))
- Added `activeTurnBehavior: "queue"` support for non-agent senders so plugins and UI actions can queue prompts behind a running turn ([#11169](https://github.com/getpaseo/paseo/pull/11169))
### Improved
- Reduced app memory use by dropping duplicate in-memory copies of cached transcripts ([#11322](https://github.com/getpaseo/paseo/pull/11322))
- Held the native launch splash until the restored workspace is on screen so mobile cold starts no longer flash empty frames or spinners ([#11348](https://github.com/getpaseo/paseo/pull/11348))
- Added a neutral focus border to the message composer ([#11097](https://github.com/getpaseo/paseo/pull/11097), [#11272](https://github.com/getpaseo/paseo/pull/11272) by [@Zayooo00](https://github.com/Zayooo00))
- Changed protocol parsing to ignore unknown newer fields and skip unrecognized list items instead of dropping whole messages ([#11284](https://github.com/getpaseo/paseo/pull/11284))
- Improved workspace lookup speed on hosts with many workspaces by filtering before loading workspace configs ([#11266](https://github.com/getpaseo/paseo/pull/11266))
### Changed
- Changed unattended Hub agent runs and their subagents to automatically deny unexpected permission prompts instead of blocking until timeout ([#11179](https://github.com/getpaseo/paseo/pull/11179))
- Changed delegated agent turn-end notices with pending work to appear as compact tool rows instead of peer message bubbles ([#11175](https://github.com/getpaseo/paseo/pull/11175))
### Fixed
- Fixed iOS composer buttons ignoring taps while the software keyboard is open and the model picker opening behind the keyboard on unfolded wide screens ([#11276](https://github.com/getpaseo/paseo/pull/11276))
- Fixed tapping Fullscreen or Exit fullscreen in the mobile composer closing the keyboard and flashing misaligned frames ([#11326](https://github.com/getpaseo/paseo/pull/11326))
- Fixed phone photos and large Android image batches failing to send by uploading images as chunked files and downscaling HEIC photos ([#11137](https://github.com/getpaseo/paseo/pull/11137), [#9328](https://github.com/getpaseo/paseo/pull/9328), [#11281](https://github.com/getpaseo/paseo/pull/11281) by [@Brandon168](https://github.com/Brandon168))
- Fixed Android's system Bold text setting clipping trailing characters and labels across the app ([#11162](https://github.com/getpaseo/paseo/pull/11162) by [@JustinJoshi](https://github.com/JustinJoshi))
- Fixed the discovered Models list in Android provider settings failing to scroll ([#11350](https://github.com/getpaseo/paseo/pull/11350) by [@ilteoood](https://github.com/ilteoood))
- Fixed mobile sending push notifications for the active chat by counting native touches and typing as presence ([#8070](https://github.com/getpaseo/paseo/pull/8070) by [@truelecter](https://github.com/truelecter))
- Fixed SVG files opening as blank image previews on iOS and Android ([#9094](https://github.com/getpaseo/paseo/pull/9094))
- Fixed reconnects on hosts with many workspaces causing mobile freezes and 60-second request timeouts ([#11145](https://github.com/getpaseo/paseo/pull/11145) by [@TheUnlimited64](https://github.com/TheUnlimited64))
- Fixed desktop browser tabs controlled by an agent stealing keyboard focus from chat composers ([#11158](https://github.com/getpaseo/paseo/pull/11158) by [@puchkoff](https://github.com/puchkoff))
- Fixed the web and desktop image lightbox staying stuck on screen after switching to another session ([#11358](https://github.com/getpaseo/paseo/pull/11358) by [@matchy233](https://github.com/matchy233))
- Fixed long desktop and web chats crashing with React error #185 during scroll re-measurement ([#11138](https://github.com/getpaseo/paseo/pull/11138) by [@kogekiplay](https://github.com/kogekiplay))
- Fixed scrolling older history crashing desktop when a timeline plugin reuses output IDs across messages ([#8498](https://github.com/getpaseo/paseo/pull/8498) by [@kevinle128](https://github.com/kevinle128), [@ykurilov](https://github.com/ykurilov))
- Fixed opening Changes with wrapped long lines freezing the desktop app ([#11113](https://github.com/getpaseo/paseo/pull/11113))
- Fixed streaming code blocks growing and shrinking by a line while their closing fence arrives ([#7006](https://github.com/getpaseo/paseo/pull/7006) by [@luoph](https://github.com/luoph), [@RRD-dev](https://github.com/RRD-dev))
- Fixed sending a steering message while an agent streams splitting the reply in half ([#5267](https://github.com/getpaseo/paseo/pull/5267))
- Fixed the Schedules screen staying on a spinner when another saved host is offline or still connecting ([#11361](https://github.com/getpaseo/paseo/pull/11361) by [@agenore](https://github.com/agenore))
- Fixed starting a new session on another host submitting an unavailable remembered model instead of selecting an available one ([#9052](https://github.com/getpaseo/paseo/pull/9052) by [@mcowger](https://github.com/mcowger))
- Fixed the composer showing the wrong thinking level when an agent's level is absent from its model's option list ([#10937](https://github.com/getpaseo/paseo/pull/10937) by [@ortschun](https://github.com/ortschun))
- Fixed unexpanded Windows environment-variable paths like `%TEMP%\file.md` rendering as broken links in chat ([#11228](https://github.com/getpaseo/paseo/pull/11228) by [@suniceman](https://github.com/suniceman))
- Fixed Open in Antigravity on macOS launching the `agy` CLI instead of Antigravity IDE ([#10893](https://github.com/getpaseo/paseo/pull/10893) by [@wangfh5](https://github.com/wangfh5))
- Fixed opening a built-in plugin's settings page showing a "not installed or listed" error ([#11308](https://github.com/getpaseo/paseo/pull/11308))
- Fixed local host images inside plugin Markdown surfaces failing to render inline ([#11171](https://github.com/getpaseo/paseo/pull/11171))
- Fixed agent metadata disappearing from plugin views after an app reload ([#11265](https://github.com/getpaseo/paseo/pull/11265))
- Fixed Android terminal input doubling characters, dropping Backspace, breaking Korean/Pinyin/Gboard suggestions, and mishandling hardware Enter ([#11146](https://github.com/getpaseo/paseo/pull/11146), [#11318](https://github.com/getpaseo/paseo/pull/11318) by [@apple-ouyang](https://github.com/apple-ouyang), [@lennartschoch](https://github.com/lennartschoch), [@jasonmarkperez](https://github.com/jasonmarkperez))
- Fixed Light-mode terminals reporting dark colors to terminal apps and added live light/dark theme change notifications ([#11163](https://github.com/getpaseo/paseo/pull/11163), [#11312](https://github.com/getpaseo/paseo/pull/11312) by [@gstamp](https://github.com/gstamp))
- Fixed web and desktop terminals using the interface font instead of the configured Code font on the DOM renderer ([#11099](https://github.com/getpaseo/paseo/pull/11099) by [@sh0nuff](https://github.com/sh0nuff))
- Fixed Windows terminals exiting immediately on busy machines when ConPTY startup takes more than five seconds ([#11238](https://github.com/getpaseo/paseo/pull/11238))
- Fixed closing terminals or stopping the daemon on Windows leaving terminal programs running ([#11147](https://github.com/getpaseo/paseo/pull/11147))
- Fixed Cursor usage showing HTTP 401 or missing cards across macOS Keychain, encrypted desktop stores, and Windows ([#11148](https://github.com/getpaseo/paseo/pull/11148) by [@jasonhnd](https://github.com/jasonhnd), [@KronixDev](https://github.com/KronixDev), [@kiawin](https://github.com/kiawin), [@ChicorSun](https://github.com/ChicorSun), [@kbitz](https://github.com/kbitz))
- Fixed OpenCode v2 agents hiding plan usage windows in the chat meter and Codex usage reading stale OpenCode v1 logins ([#11153](https://github.com/getpaseo/paseo/pull/11153) by [@Wu-Jiayang](https://github.com/Wu-Jiayang))
- Fixed Usage missing custom Claude and Codex providers configured with separate credential directories ([#11149](https://github.com/getpaseo/paseo/pull/11149) by [@QichangZheng](https://github.com/QichangZheng))
- Fixed Claude and Codex wrapper commands or environment tokens showing a mismatched local account in Usage ([#11154](https://github.com/getpaseo/paseo/pull/11154))
- Fixed Claude progress updates hiding inside collapsed Thinking rows and multi-block messages repeating their final block ([#11160](https://github.com/getpaseo/paseo/pull/11160) by [@ThePharmer](https://github.com/ThePharmer))
- Fixed orphaned Claude CLI child processes leaking on concurrent resume or early cancel, and bounded headless metadata generation ([#11143](https://github.com/getpaseo/paseo/pull/11143) by [@desmond-rai](https://github.com/desmond-rai), [@nickmaglowsch](https://github.com/nickmaglowsch))
- Fixed idle Claude agents being marked as failed when their process exits cleanly with code 0 ([#11273](https://github.com/getpaseo/paseo/pull/11273) by [@lucamzanon](https://github.com/lucamzanon))
- Fixed Claude Advisor tool calls staying unsettled when rebuilding chat history ([#11202](https://github.com/getpaseo/paseo/pull/11202) by [@LucasValeQueiroz](https://github.com/LucasValeQueiroz), [@SirisZheng](https://github.com/SirisZheng))
- Fixed updated plugin system prompt instructions not reaching resumed Claude sessions ([#10917](https://github.com/getpaseo/paseo/pull/10917) by [@Tomblarom](https://github.com/Tomblarom))
- Fixed Codex alias `-c mcp_servers.*` overrides disappearing when Paseo injects MCP servers ([#11142](https://github.com/getpaseo/paseo/pull/11142))
- Fixed OpenCode v2 models having no Default thinking option to return to base model behavior ([#11184](https://github.com/getpaseo/paseo/pull/11184) by [@3ae3ae](https://github.com/3ae3ae))
- Fixed Pi and OMP live streaming splitting thinking and answer blocks out of order ([#11159](https://github.com/getpaseo/paseo/pull/11159))
- Fixed Pi chat history opening empty when transcripts contain unlinked title or model-change metadata ([#11379](https://github.com/getpaseo/paseo/pull/11379))
- Fixed sending a Pi extension slash command mid-turn aborting the active response ([#11341](https://github.com/getpaseo/paseo/pull/11341) by [@tridao](https://github.com/tridao))
- Fixed a rejected Pi history or rewind extension prompt crashing the daemon worker ([#11329](https://github.com/getpaseo/paseo/pull/11329) by [@thomasvan](https://github.com/thomasvan))
- Fixed completed Pi Tintinweb background subagents staying marked as Running ([#11168](https://github.com/getpaseo/paseo/pull/11168) by [@amcfague](https://github.com/amcfague))
- Fixed background OMP catalog refreshes triggering cancelled startup model requests ([#11129](https://github.com/getpaseo/paseo/pull/11129) by [@mcowger](https://github.com/mcowger))
- Fixed OMP turns timing out after ten minutes while actively streaming or waiting on a question card ([#11079](https://github.com/getpaseo/paseo/pull/11079) by [@LiebeLee](https://github.com/LiebeLee))
- Fixed Antigravity deferred turns ending early after an interim reply when the final background tool completes ([#10924](https://github.com/getpaseo/paseo/pull/10924) by [@Juns-g](https://github.com/Juns-g))
- Fixed stopping an unresponsive ACP agent leaving later prompts stuck behind an active foreground turn ([#11152](https://github.com/getpaseo/paseo/pull/11152))
- Fixed resumed Muse sessions dropping daemon and plugin system instructions ([#10915](https://github.com/getpaseo/paseo/pull/10915) by [@Tomblarom](https://github.com/Tomblarom))
- Fixed Unix-socket, named-pipe, non-loopback, and HTTP-proxy daemons dropping injected Paseo MCP tools and terminal activity reporting ([#11144](https://github.com/getpaseo/paseo/pull/11144))
- Fixed repeated daemon restarts duplicating provider image attachments in temporary directories ([#7895](https://github.com/getpaseo/paseo/pull/7895) by [@cleiter](https://github.com/cleiter))
- Fixed concurrent reloads of the same agent failing with "Unknown agent" ([#8369](https://github.com/getpaseo/paseo/pull/8369) by [@tieo](https://github.com/tieo))
- Fixed `paseo agent logs --tail` timing out on very large chat histories ([#10723](https://github.com/getpaseo/paseo/pull/10723) by [@minamorl](https://github.com/minamorl))
- Fixed `paseo agent logs` hanging instead of exiting after a daemon request timeout ([#11360](https://github.com/getpaseo/paseo/pull/11360))
- Fixed `paseo permit ls` missing pending permissions from background agents and agents past the first 200 ([#10655](https://github.com/getpaseo/paseo/pull/10655) by [@NightMachinery](https://github.com/NightMachinery))
- Fixed `paseo --host host:port` giving generic credential advice on HTTP 400 instead of suggesting `wss://` for TLS endpoints ([#11383](https://github.com/getpaseo/paseo/pull/11383))
### Plugins
- Added `update_workspace` and workspace `metadata` support to Paseo MCP and `PluginWorkspaceSnapshot` ([#11166](https://github.com/getpaseo/paseo/pull/11166))
- Fixed server plugin compilation failing when a dependency's type declarations import Node ambient types ([#8618](https://github.com/getpaseo/paseo/pull/8618) by [@nkwib](https://github.com/nkwib))
## 0.18.1 - 2026-11-27
- **Host metadata instructions:** Set host-wide instructions once to guide language, tone, and formatting for generated workspace titles, branch names, commit messages, and pull requests. ([#11064](https://github.com/getpaseo/paseo/pull/11064))
+93
View File
@@ -1,5 +1,98 @@
# Changelog
## 0.18.2 - 2026-11-30
- **重新设计的模型选择器**:桌面端采用支持跨 Provider 搜索的双栏视图,手机端合并为带思考强度滑块的单层抽屉,并支持在设置中按 Provider 筛选常用模型。([#11186](https://github.com/getpaseo/paseo/pull/11186), [#11280](https://github.com/getpaseo/paseo/pull/11280), [#11295](https://github.com/getpaseo/paseo/pull/11295), [#11371](https://github.com/getpaseo/paseo/pull/11371), [#11313](https://github.com/getpaseo/paseo/pull/11313))
- **文件操作与筛选**:支持按名称筛选文件树,并直接从对话文件链接、文件标签页和侧边栏文件树中定位文件、使用默认应用打开、下载或复制路径。([#11073](https://github.com/getpaseo/paseo/pull/11073), [#11299](https://github.com/getpaseo/paseo/pull/11299), [#11320](https://github.com/getpaseo/paseo/pull/11320),贡献者:[@YASICJUNWOO](https://github.com/YASICJUNWOO), [@apple-ouyang](https://github.com/apple-ouyang), [@iqshen](https://github.com/iqshen), [@Ctrl-Creeper](https://github.com/Ctrl-Creeper), [@softyoda](https://github.com/softyoda))
- **全新蝴蝶应用图标**:桌面端和移动端现已统一使用新版蝴蝶图标,并在 macOS 程序坞中具备正确的图标尺寸与系统光影。([#11091](https://github.com/getpaseo/paseo/pull/11091))
- **实时用量更新**:Claude 和 Codex 的用量摘要现在会在轮次结束时实时更新,不再需要等待五分钟轮询。([#11170](https://github.com/getpaseo/paseo/pull/11170),贡献者:[@Zayooo00](https://github.com/Zayooo00))
- **更快的 CLI 启动速度**:Paseo CLI 仅按需加载所执行的命令,启动速度提升 7 至 22 倍。([#11155](https://github.com/getpaseo/paseo/pull/11155), [#11193](https://github.com/getpaseo/paseo/pull/11193), [#11363](https://github.com/getpaseo/paseo/pull/11363))
- **原生 ACP 提问卡片**:Antigravity 等插件 ACP Provider 遇到交互式表单提问时,现在会暂停并显示 Paseo 原生提问卡片,而不再输出编号列表。([#11135](https://github.com/getpaseo/paseo/pull/11135),贡献者:[@djbclark](https://github.com/djbclark), [@krazyjakee](https://github.com/krazyjakee))
- **OMP 后台任务**:OMP Agent 现在会在 Composer 上方列出正在运行的后台任务,并支持直接停止而不中断 Agent。([#11270](https://github.com/getpaseo/paseo/pull/11270),贡献者:[@mcowger](https://github.com/mcowger))
- **插件 HTTP 隧道**:插件现在可以通过隧道 Provider 将本地 HTTP 服务暴露为公网 HTTPS 地址,内置支持 `cloudflared` 和 Tailscale Funnel。([#11036](https://github.com/getpaseo/paseo/pull/11036))
### 新增
- 为 `paseo schedule ls` 新增 `--all` 选项以列出指向现有 Agent 的定时任务,并在表格输出中提示已隐藏的定时任务 ([#11243](https://github.com/getpaseo/paseo/pull/11243),贡献者:[@suniceman](https://github.com/suniceman))
- 为非 Agent 发送方新增 `activeTurnBehavior: "queue"` 支持,使插件和界面操作可将提示词排队到当前运行轮次之后 ([#11169](https://github.com/getpaseo/paseo/pull/11169))
### 改进
- 移除了内存中重复保留的已缓存对话记录副本,降低了应用内存占用 ([#11322](https://github.com/getpaseo/paseo/pull/11322))
- 延长原生启动画面直到恢复的工作区渲染到屏幕上,避免移动端冷启动时闪烁空白帧或加载指示器 ([#11348](https://github.com/getpaseo/paseo/pull/11348))
- 为消息 Composer 新增中性色调的聚焦边框 ([#11097](https://github.com/getpaseo/paseo/pull/11097), [#11272](https://github.com/getpaseo/paseo/pull/11272),贡献者:[@Zayooo00](https://github.com/Zayooo00))
- 改进协议解析,忽略未知的新字段并跳过无法识别的列表项,不再丢弃整条消息 ([#11284](https://github.com/getpaseo/paseo/pull/11284))
- 在加载工作区配置前先进行过滤,提升包含大量工作区主机上的工作区查询速度 ([#11266](https://github.com/getpaseo/paseo/pull/11266))
### 变更
- 无人值守的 Hub Agent 及其子 Agent 遇到意外权限请求时,改为自动拒绝而不再阻塞直至超时 ([#11179](https://github.com/getpaseo/paseo/pull/11179))
- 仍有待处理任务的委托 Agent 轮次结束通知,改为显示为紧凑的工具调用行,而不再显示为对等消息气泡 ([#11175](https://github.com/getpaseo/paseo/pull/11175))
### 修复
- 修复 iOS 软键盘弹出时 Composer 按钮忽略点击,以及在展开的宽屏设备上模型选择器被键盘遮挡的问题 ([#11276](https://github.com/getpaseo/paseo/pull/11276))
- 修复在移动端 Composer 中点击全屏或退出全屏时收起键盘并闪烁错位帧的问题 ([#11326](https://github.com/getpaseo/paseo/pull/11326))
- 修复手机照片和大量 Android 图片批次发送失败的问题,改为以分块文件上传图片并将 HEIC 照片降采样为 JPEG ([#11137](https://github.com/getpaseo/paseo/pull/11137), [#9328](https://github.com/getpaseo/paseo/pull/9328), [#11281](https://github.com/getpaseo/paseo/pull/11281),贡献者:[@Brandon168](https://github.com/Brandon168))
- 修复 Android 系统开启粗体文字设置后应用内末尾字符和标签被截断的问题 ([#11162](https://github.com/getpaseo/paseo/pull/11162),贡献者:[@JustinJoshi](https://github.com/JustinJoshi))
- 修复 Android 的 Provider 设置中已发现的模型列表无法滚动的问题 ([#11350](https://github.com/getpaseo/paseo/pull/11350),贡献者:[@ilteoood](https://github.com/ilteoood))
- 修复移动端仍为当前正在查看的对话发送推送通知的问题,将原生触摸与输入计入在线活跃状态 ([#8070](https://github.com/getpaseo/paseo/pull/8070),贡献者:[@truelecter](https://github.com/truelecter))
- 修复 iOS 和 Android 上打开 SVG 文件预览显示空白的问题 ([#9094](https://github.com/getpaseo/paseo/pull/9094))
- 修复在包含大量工作区的主机上重连时导致移动端卡顿和 60 秒请求超时的问题 ([#11145](https://github.com/getpaseo/paseo/pull/11145),贡献者:[@TheUnlimited64](https://github.com/TheUnlimited64))
- 修复由 Agent 控制的桌面端浏览器标签页抢占对话 Composer 键盘焦点的问题 ([#11158](https://github.com/getpaseo/paseo/pull/11158),贡献者:[@puchkoff](https://github.com/puchkoff))
- 修复在网页端和桌面端切换到其他会话后图片灯箱仍卡在屏幕上的问题 ([#11358](https://github.com/getpaseo/paseo/pull/11358),贡献者:[@matchy233](https://github.com/matchy233))
- 修复桌面端和网页端长对话在滚动重新测量时触发 React 错误 #185 崩溃的问题 ([#11138](https://github.com/getpaseo/paseo/pull/11138),贡献者:[@kogekiplay](https://github.com/kogekiplay))
- 修复时间线插件跨消息复用输出 ID 时,滚动较早历史记录导致桌面端崩溃的问题 ([#8498](https://github.com/getpaseo/paseo/pull/8498),贡献者:[@kevinle128](https://github.com/kevinle128), [@ykurilov](https://github.com/ykurilov))
- 修复在变更视图中开启长行换行时桌面端卡死的问题 ([#11113](https://github.com/getpaseo/paseo/pull/11113))
- 修复流式输出代码块在闭合围栏尚未完整到达时高度增加一行又缩回的问题 ([#7006](https://github.com/getpaseo/paseo/pull/7006),贡献者:[@luoph](https://github.com/luoph), [@RRD-dev](https://github.com/RRD-dev))
- 修复在 Agent 流式回复过程中发送引导消息将回复截成两半的问题 ([#5267](https://github.com/getpaseo/paseo/pull/5267))
- 修复另一个已保存主机离线或仍在连接时,定时任务页面一直停留在加载状态的问题 ([#11361](https://github.com/getpaseo/paseo/pull/11361),贡献者:[@agenore](https://github.com/agenore))
- 修复在另一台主机上启动新会话时提交上次记住但该主机不可用的模型,而未自动选择可用模型的问题 ([#9052](https://github.com/getpaseo/paseo/pull/9052),贡献者:[@mcowger](https://github.com/mcowger))
- 修复 Agent 的思考强度不在其模型选项列表中时,Composer 显示错误思考强度的问题 ([#10937](https://github.com/getpaseo/paseo/pull/10937),贡献者:[@ortschun](https://github.com/ortschun))
- 修复对话中未展开的 Windows 环境变量路径(如 `%TEMP%\file.md`)被渲染为失效链接的问题 ([#11228](https://github.com/getpaseo/paseo/pull/11228),贡献者:[@suniceman](https://github.com/suniceman))
- 修复 macOS 上“在 Antigravity 中打开”启动 `agy` CLI 而不是 Antigravity IDE 的问题 ([#10893](https://github.com/getpaseo/paseo/pull/10893),贡献者:[@wangfh5](https://github.com/wangfh5))
- 修复打开内置插件设置页面时显示“未安装或未列出”错误的问题 ([#11308](https://github.com/getpaseo/paseo/pull/11308))
- 修复插件 Markdown 界面中的本地主机图片无法内联渲染的问题 ([#11171](https://github.com/getpaseo/paseo/pull/11171))
- 修复重新加载应用后插件视图中 Agent 元数据消失的问题 ([#11265](https://github.com/getpaseo/paseo/pull/11265))
- 修复 Android 终端输入重复字符、丢失退格键、破坏韩语/拼音/Gboard 候选词以及误处理实体回车键的问题 ([#11146](https://github.com/getpaseo/paseo/pull/11146), [#11318](https://github.com/getpaseo/paseo/pull/11318),贡献者:[@apple-ouyang](https://github.com/apple-ouyang), [@lennartschoch](https://github.com/lennartschoch), [@jasonmarkperez](https://github.com/jasonmarkperez))
- 修复浅色模式终端向终端程序报告深色配色的问题,并新增实时浅色/深色主题切换通知 ([#11163](https://github.com/getpaseo/paseo/pull/11163), [#11312](https://github.com/getpaseo/paseo/pull/11312),贡献者:[@gstamp](https://github.com/gstamp))
- 修复网页端和桌面端终端在 DOM 渲染器下使用界面字体而不是已配置代码字体的问题 ([#11099](https://github.com/getpaseo/paseo/pull/11099),贡献者:[@sh0nuff](https://github.com/sh0nuff))
- 修复在负载较高的 Windows 机器上 ConPTY 启动超过五秒时终端立即退出的问题 ([#11238](https://github.com/getpaseo/paseo/pull/11238))
- 修复在 Windows 上关闭终端或停止 daemon 时终端内程序仍在后台运行的问题 ([#11147](https://github.com/getpaseo/paseo/pull/11147))
- 修复 Cursor 使用情况在 macOS 钥匙串、加密桌面存储和 Windows 上返回 HTTP 401 或缺失卡片的问题 ([#11148](https://github.com/getpaseo/paseo/pull/11148),贡献者:[@jasonhnd](https://github.com/jasonhnd), [@KronixDev](https://github.com/KronixDev), [@kiawin](https://github.com/kiawin), [@ChicorSun](https://github.com/ChicorSun), [@kbitz](https://github.com/kbitz))
- 修复 OpenCode v2 Agent 在对话用量指示器中不显示套餐用量窗口,以及 Codex 使用情况读取过期 OpenCode v1 登录态的问题 ([#11153](https://github.com/getpaseo/paseo/pull/11153),贡献者:[@Wu-Jiayang](https://github.com/Wu-Jiayang))
- 修复使用情况遗漏配置了独立凭据目录的自定义 Claude 和 Codex Provider 的问题 ([#11149](https://github.com/getpaseo/paseo/pull/11149),贡献者:[@QichangZheng](https://github.com/QichangZheng))
- 修复使用包装命令或环境变量令牌的 Claude 和 Codex 在使用情况中显示不匹配的本地账号的问题 ([#11154](https://github.com/getpaseo/paseo/pull/11154))
- 修复 Claude 进度更新被隐藏在折叠的思考行内,以及多块消息重复显示最后一块的问题 ([#11160](https://github.com/getpaseo/paseo/pull/11160),贡献者:[@ThePharmer](https://github.com/ThePharmer))
- 修复并发恢复或提前取消时泄漏孤立 Claude CLI 子进程的问题,并限制无头元数据生成的并发 ([#11143](https://github.com/getpaseo/paseo/pull/11143),贡献者:[@desmond-rai](https://github.com/desmond-rai), [@nickmaglowsch](https://github.com/nickmaglowsch))
- 修复空闲 Claude Agent 进程以退出码 0 正常退出时被标记为失败的问题 ([#11273](https://github.com/getpaseo/paseo/pull/11273),贡献者:[@lucamzanon](https://github.com/lucamzanon))
- 修复重建对话历史时 Claude Advisor 工具调用一直停留在未完成状态的问题 ([#11202](https://github.com/getpaseo/paseo/pull/11202),贡献者:[@LucasValeQueiroz](https://github.com/LucasValeQueiroz), [@SirisZheng](https://github.com/SirisZheng))
- 修复更新后的插件系统提示词指令未能送达已恢复的 Claude 会话的问题 ([#10917](https://github.com/getpaseo/paseo/pull/10917),贡献者:[@Tomblarom](https://github.com/Tomblarom))
- 修复 Paseo 注入 MCP 服务器时 Codex 别名的 `-c mcp_servers.*` 覆盖配置丢失的问题 ([#11142](https://github.com/getpaseo/paseo/pull/11142))
- 修复 OpenCode v2 模型缺少 Default 思考选项、无法恢复模型默认行为的问题 ([#11184](https://github.com/getpaseo/paseo/pull/11184),贡献者:[@3ae3ae](https://github.com/3ae3ae))
- 修复 Pi 和 OMP 实时流式输出时思考块和回复块顺序错乱分割的问题 ([#11159](https://github.com/getpaseo/paseo/pull/11159))
- 修复包含未关联标题或模型变更元数据的 Pi 对话历史打开为空的问题 ([#11379](https://github.com/getpaseo/paseo/pull/11379))
- 修复在轮次进行中发送 Pi 扩展斜杠命令会中止当前回复的问题 ([#11341](https://github.com/getpaseo/paseo/pull/11341),贡献者:[@tridao](https://github.com/tridao))
- 修复被拒绝的 Pi 历史读取或回退扩展提示导致 daemon 工作进程崩溃的问题 ([#11329](https://github.com/getpaseo/paseo/pull/11329),贡献者:[@thomasvan](https://github.com/thomasvan))
- 修复已完成的 Pi Tintinweb 后台子 Agent 仍一直显示为运行中的问题 ([#11168](https://github.com/getpaseo/paseo/pull/11168),贡献者:[@amcfague](https://github.com/amcfague))
- 修复后台 OMP 目录刷新触发被取消的启动模型请求的问题 ([#11129](https://github.com/getpaseo/paseo/pull/11129),贡献者:[@mcowger](https://github.com/mcowger))
- 修复 OMP 轮次在持续流式输出或等待提问卡片超过十分钟后超时失败的问题 ([#11079](https://github.com/getpaseo/paseo/pull/11079),贡献者:[@LiebeLee](https://github.com/LiebeLee))
- 修复 Antigravity 延迟轮次在发出中间回复后,最后一个后台工具完成时提前结束轮次的问题 ([#10924](https://github.com/getpaseo/paseo/pull/10924),贡献者:[@Juns-g](https://github.com/Juns-g))
- 修复停止无响应的 ACP Agent 后,后续提示词一直卡在活跃前台轮次之后的问题 ([#11152](https://github.com/getpaseo/paseo/pull/11152))
- 修复恢复的 Muse 会话丢失 daemon 和插件系统指令的问题 ([#10915](https://github.com/getpaseo/paseo/pull/10915),贡献者:[@Tomblarom](https://github.com/Tomblarom))
- 修复监听 Unix 套接字、命名管道、非回环地址或处于 HTTP 代理后的 daemon 丢失内置 Paseo MCP 工具注入和终端活动上报的问题 ([#11144](https://github.com/getpaseo/paseo/pull/11144))
- 修复重复重启 daemon 在临时目录中不断复制 Provider 图片附件的问题 ([#7895](https://github.com/getpaseo/paseo/pull/7895),贡献者:[@cleiter](https://github.com/cleiter))
- 修复并发重载同一个 Agent 时返回“Unknown agent”错误的问题 ([#8369](https://github.com/getpaseo/paseo/pull/8369),贡献者:[@tieo](https://github.com/tieo))
- 修复 `paseo agent logs --tail` 在超长对话历史上超时的问题 ([#10723](https://github.com/getpaseo/paseo/pull/10723),贡献者:[@minamorl](https://github.com/minamorl))
- 修复 `paseo agent logs` 在 daemon 请求超时后挂起不退出的问题 ([#11360](https://github.com/getpaseo/paseo/pull/11360))
- 修复 `paseo permit ls` 遗漏后台 Agent 以及前 200 个之后 Agent 的待处理权限的问题 ([#10655](https://github.com/getpaseo/paseo/pull/10655),贡献者:[@NightMachinery](https://github.com/NightMachinery))
- 修复 `paseo --host host:port` 遇到 HTTP 400 时只提示检查凭据而未建议对 TLS 端点使用 `wss://` 的问题 ([#11383](https://github.com/getpaseo/paseo/pull/11383))
### 插件
- 为 Paseo MCP 和 `PluginWorkspaceSnapshot` 新增 `update_workspace` 和工作区 `metadata` 支持 ([#11166](https://github.com/getpaseo/paseo/pull/11166))
- 修复依赖的类型声明导入 Node 环境类型时服务端插件编译失败的问题 ([#8618](https://github.com/getpaseo/paseo/pull/8618),贡献者:[@nkwib](https://github.com/nkwib))
## 0.18.1 - 2026-11-27
- **主机元数据指令**:设置一次主机级指令,即可统一控制自动生成的工作区标题、分支名、提交信息和 PR 的语言、语气与格式。([#11064](https://github.com/getpaseo/paseo/pull/11064))
+2
View File
@@ -523,6 +523,8 @@ Measured bundle size for a standard Expo web export:
- gzip: 2.55 MiB
- brotli: 1.93 MiB
`npm run build:desktop` runs the same `scripts/precompress-assets.mjs` over `packages/app/dist` before electron-builder copies it to `app-dist`, so the desktop-served UI also gets `.br`/`.gz` siblings.
The desktop-managed daemon disables the bundled web UI by default (`PASEO_WEB_UI_ENABLED=false`) because the desktop app already ships the renderer as `app-dist`. Shipping the same assets again inside `@getpaseo/server` would duplicate the ~10.8 MiB install. Desktop packaging also excludes `node_modules/@getpaseo/server/dist/server/web-ui/**` from the packaged app.
## Built workspace packages
+11 -4
View File
@@ -447,10 +447,17 @@ wide layouts keep local geometry. That export is
what `patches/@gorhom+bottom-sheet+*.patch` adds.
A sheet whose owner may veto the close (unsaved work) passes `enableDismissOnClose={false}`. Every
close path then parks the sheet at index -1 with its content mounted; the owner hears
`onChange(-1)`, runs its guard, and either snaps back to 0 or drops its state, which unmounts the
sheet and takes it off the stack. Calling `dismiss()` on such a sheet bypasses the guard and
unmounts it, so its backdrop and Back press call `close()`.
close path then parks the sheet at index -1 with its content mounted; the owner runs its guard and
either snaps back to 0 or drops its state, which unmounts the sheet and takes it off the stack.
Calling `dismiss()` on such a sheet bypasses the guard and unmounts it, so its backdrop and Back
press call `close()`.
Run that guard from the wrapper's `onClosed`. Gorhom only calls `onChange` when a close ends at a
different index than the one it already recorded, and an interrupted mount animation leaves that
record at -1, so the close that follows is invisible: the sheet parks with its backdrop still over
the app, and every tap in the covered area is lost. `onClosed` watches the close animation settle at
the closed detent and reports it either way. Keeping `onChange` as well is harmless as long as the
guard is idempotent.
The wrapper must give Gorhom an object ref. Gorhom accepts a callback ref at the React boundary
but stores it in the modal queue and later reads `.current`; provider dismissal, replacement,
+1 -1
View File
@@ -4,7 +4,7 @@ Paseo Hub is an explicit opt-in connection from one Paseo daemon to one Hub. Run
not register it with a Hub. The relationship begins only when a user runs
`paseo hub connect [url]` from the daemon machine with an explicit API key or matching stored CLI login.
The human CLI login and daemon relationship are separate identities. `paseo hub login [url]` stores a durable organization-scoped CLI credential keyed by normalized Hub origin under `PASEO_HOME`. Interactive login optionally connects the local daemon, then points to the Hub UI for trigger configuration; it does not scaffold or deploy configuration. `paseo hub init` remains the explicit triggers-as-code scaffold: it writes one self-contained organization trigger under `.paseo/triggers/`, validates it through the trigger API, and optionally installs it. `paseo hub deploy` validates and installs every trigger in that directory; passing `--project` keeps deploying the legacy project bundle instead. `paseo hub export [directory]` writes the active organization's current triggers in the same layout, using the active login unless another Hub or API key is selected. Origin resolution uses explicit command input, `PASEO_HUB_URL`, active login, then `https://hub.paseo.sh`. Connect uses exact-origin authority to request a one-time enrollment token, then passes only that token to the daemon. The daemon generates and persists its own relationship credential.
The human CLI login and daemon relationship are separate identities. `paseo hub login [url]` stores a durable organization-scoped CLI credential keyed by normalized Hub origin under `PASEO_HOME`. Interactive login optionally connects the local daemon, then points to the Hub UI for trigger configuration; it does not scaffold or deploy configuration. `paseo hub init` remains the explicit triggers-as-code scaffold: it writes one self-contained organization trigger under `.paseo/triggers/`, validates it through the trigger API, and optionally installs it. `paseo hub deploy` validates and installs every trigger in that directory; passing `--project` keeps deploying the legacy project bundle instead. `paseo hub export [directory]` writes the active organization's current triggers in the same layout, using the active login unless another Hub or API key is selected. `paseo hub run` dispatches a `manual.run` trigger through `POST /api/v1/manual-runs`, which takes inputs and prompt as one string; the CLI rejects what Hub would silently read as prompt text (`packages/cli/src/commands/hub/run/`). Origin resolution uses explicit command input, `PASEO_HUB_URL`, active login, then `https://hub.paseo.sh`. Connect uses exact-origin authority to request a one-time enrollment token, then passes only that token to the daemon. The daemon generates and persists its own relationship credential.
## Connection and authority
@@ -0,0 +1,4 @@
- Redesigned model picker: Pick models from a two-pane desktop view with cross-provider search, an in-place phone drawer with a thinking slider, and per-provider model lists in settings.
- File actions and filter: Filter the Files tree by name, and reveal, open in your default app, download, or copy paths from chat file links, file tabs, and sidebar trees.
Full notes: https://paseo.sh/changelog
@@ -0,0 +1,4 @@
- Redesigned model picker: Pick models from a two-pane desktop view with cross-provider search, an in-place phone drawer with a thinking slider, and per-provider model lists in settings.
- File actions and filter: Filter the Files tree by name, and reveal, open in your default app, download, or copy paths from chat file links, file tabs, and sidebar trees.
Full notes: https://paseo.sh/changelog
@@ -0,0 +1,4 @@
- Redesigned model picker: Pick models from a two-pane desktop view with cross-provider search, an in-place phone drawer with a thinking slider, and per-provider model lists in settings.
- File actions and filter: Filter the Files tree by name, and reveal, open in your default app, download, or copy paths from chat file links, file tabs, and sidebar trees.
Full notes: https://paseo.sh/changelog
@@ -0,0 +1,4 @@
- Redesigned model picker: Pick models from a two-pane desktop view with cross-provider search, an in-place phone drawer with a thinking slider, and per-provider model lists in settings.
- File actions and filter: Filter the Files tree by name, and reveal, open in your default app, download, or copy paths from chat file links, file tabs, and sidebar trees.
Full notes: https://paseo.sh/changelog
+1 -1
View File
@@ -1 +1 @@
sha256-34bUBmRmjekbUSp93597GLTmSWKt23TCHaK3ViXG+iU=
sha256-vrmauZ6dprc1M88FePLIvVT6FhgnmS9HjHGzPcCypyk=
+29 -29
View File
@@ -1,12 +1,12 @@
{
"name": "paseo",
"version": "0.18.1",
"version": "0.18.2",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "paseo",
"version": "0.18.1",
"version": "0.18.2",
"hasInstallScript": true,
"license": "Apache-2.0",
"workspaces": [
@@ -37543,7 +37543,7 @@
},
"packages/app": {
"name": "@getpaseo/app",
"version": "0.18.1",
"version": "0.18.2",
"dependencies": {
"@codemirror/commands": "6.10.4",
"@codemirror/language": "6.12.4",
@@ -39696,13 +39696,13 @@
},
"packages/cli": {
"name": "@getpaseo/cli",
"version": "0.18.1",
"version": "0.18.2",
"license": "Apache-2.0",
"dependencies": {
"@clack/prompts": "^1.0.0",
"@getpaseo/client": "0.18.1",
"@getpaseo/protocol": "0.18.1",
"@getpaseo/server": "0.18.1",
"@getpaseo/client": "0.18.2",
"@getpaseo/protocol": "0.18.2",
"@getpaseo/server": "0.18.2",
"chalk": "^5.3.0",
"commander": "^12.0.0",
"mime-types": "^2.1.35",
@@ -39949,11 +39949,11 @@
},
"packages/client": {
"name": "@getpaseo/client",
"version": "0.18.1",
"version": "0.18.2",
"license": "Apache-2.0",
"dependencies": {
"@getpaseo/protocol": "0.18.1",
"@getpaseo/relay": "0.18.1",
"@getpaseo/protocol": "0.18.2",
"@getpaseo/relay": "0.18.2",
"ws": "^8.20.0",
"zod": "^4.4.3"
},
@@ -39965,7 +39965,7 @@
},
"packages/desktop": {
"name": "@getpaseo/desktop",
"version": "0.18.1",
"version": "0.18.2",
"license": "Apache-2.0",
"dependencies": {
"@getpaseo/cli": "*",
@@ -40208,7 +40208,7 @@
},
"packages/expo-two-way-audio": {
"name": "@getpaseo/expo-two-way-audio",
"version": "0.18.1",
"version": "0.18.2",
"license": "MIT",
"devDependencies": {
"@types/jest": "^29.5.14",
@@ -40254,7 +40254,7 @@
},
"packages/highlight": {
"name": "@getpaseo/highlight",
"version": "0.18.1",
"version": "0.18.2",
"license": "Apache-2.0",
"dependencies": {
"@codemirror/language": "6.12.4",
@@ -40284,7 +40284,7 @@
},
"packages/plugin": {
"name": "@getpaseo/plugin",
"version": "0.18.1",
"version": "0.18.2",
"license": "Apache-2.0",
"dependencies": {
"@agentclientprotocol/sdk": "^1.4.0",
@@ -40292,8 +40292,8 @@
"use-sync-external-store": "^1.6.0"
},
"devDependencies": {
"@getpaseo/client": "0.18.1",
"@getpaseo/protocol": "0.18.1",
"@getpaseo/client": "0.18.2",
"@getpaseo/protocol": "0.18.2",
"@types/node": "^20.9.0",
"@types/react": "~19.2.0",
"react": "19.2.3",
@@ -40303,8 +40303,8 @@
"zod": "^4.4.3"
},
"peerDependencies": {
"@getpaseo/client": "0.18.1",
"@getpaseo/protocol": "0.18.1",
"@getpaseo/client": "0.18.2",
"@getpaseo/protocol": "0.18.2",
"react": ">=19.1.0 <20",
"react-native": ">=0.81.5",
"zod": "^4.4.3"
@@ -40326,7 +40326,7 @@
},
"packages/protocol": {
"name": "@getpaseo/protocol",
"version": "0.18.1",
"version": "0.18.2",
"license": "Apache-2.0",
"dependencies": {
"semver": "^7.8.5",
@@ -40353,7 +40353,7 @@
}
},
"packages/react-native-enriched-markdown": {
"version": "0.18.1",
"version": "0.18.2",
"hasInstallScript": true,
"license": "MIT",
"peerDependencies": {
@@ -40369,7 +40369,7 @@
},
"packages/relay": {
"name": "@getpaseo/relay",
"version": "0.18.1",
"version": "0.18.2",
"license": "Apache-2.0",
"dependencies": {
"@noble/ciphers": "^2.4.0",
@@ -40591,17 +40591,17 @@
},
"packages/server": {
"name": "@getpaseo/server",
"version": "0.18.1",
"version": "0.18.2",
"license": "Apache-2.0",
"dependencies": {
"@agentclientprotocol/sdk": "^0.17.1",
"@anthropic-ai/claude-agent-sdk": "0.3.326",
"@anthropic-ai/sdk": "^0.104.2",
"@getpaseo/client": "0.18.1",
"@getpaseo/highlight": "0.18.1",
"@getpaseo/plugin": "0.18.1",
"@getpaseo/protocol": "0.18.1",
"@getpaseo/relay": "0.18.1",
"@getpaseo/client": "0.18.2",
"@getpaseo/highlight": "0.18.2",
"@getpaseo/plugin": "0.18.2",
"@getpaseo/protocol": "0.18.2",
"@getpaseo/relay": "0.18.2",
"@isaacs/ttlcache": "^2.1.4",
"@modelcontextprotocol/node": "2.1.2",
"@modelcontextprotocol/sdk": "1.29.0",
@@ -41552,7 +41552,7 @@
},
"packages/website": {
"name": "@getpaseo/website",
"version": "0.18.1",
"version": "0.18.2",
"dependencies": {
"@cloudflare/vite-plugin": "^1.29.1",
"@cloudflare/workers-types": "^4.20260317.1",
@@ -43178,7 +43178,7 @@
},
"plugins": {
"name": "@getpaseo/builtin-plugins",
"version": "0.18.1",
"version": "0.18.2",
"dependencies": {
"@getpaseo/plugin": "*",
"zod": "^4.4.3"
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "paseo",
"version": "0.18.1",
"version": "0.18.2",
"private": true,
"description": "Paseo: voice-controlled development environment for local AI coding agents",
"keywords": [
@@ -99,7 +99,7 @@
"web": "npm run web --workspace=@getpaseo/app",
"dev:desktop": "cross-env PASEO_LISTEN=127.0.0.1:6768 npm run dev --workspace=@getpaseo/desktop",
"dev:win:desktop": "npm run dev:win --workspace=@getpaseo/desktop",
"build:desktop": "npm run build:app-deps:clean && cd packages/app && cross-env PASEO_WEB_PLATFORM=electron npx expo export --platform web && cd ../.. && npm run build --workspace=@getpaseo/desktop --",
"build:desktop": "npm run build:app-deps:clean && cd packages/app && cross-env PASEO_WEB_PLATFORM=electron npx expo export --platform web && cd ../.. && node scripts/precompress-assets.mjs packages/app/dist && npm run build --workspace=@getpaseo/desktop --",
"db:query": "npm run db:query --workspace=@getpaseo/server --",
"cli": "./scripts/dev-home.sh npx tsx packages/cli/src/index.js",
"version": "npm run version:sync-internal && npm run fdroid:changelogs && npm run release:prepare && git add -A",
@@ -1,6 +1,6 @@
import { readFile, writeFile } from "node:fs/promises";
import path from "node:path";
import { expect, test } from "../support/fixtures";
import { expect, test, type Page } from "../support/fixtures";
import { expectComposerVisible } from "../support/helpers/composer";
import { installDaemonWebSocketGate } from "../support/helpers/daemon-websocket-gate";
import { installLocalDesktopHost } from "../support/helpers/local-desktop-host";
@@ -282,3 +282,63 @@ test("compact opens files and subagents in a sheet, leaving the tabs for agents"
await workspace.cleanup();
}
});
async function openFileAndDismissDuringAnimation(page: Page) {
const fileLink = page.getByText(FILE_LINK, { exact: true });
await expect(fileLink).toBeVisible({ timeout: 15_000 });
// Check and press in the same browser frame so automation cannot outlast the opening animation.
await fileLink.evaluate((link) => {
if (!(link instanceof HTMLElement)) throw new Error("Expected an HTML file link");
return new Promise<void>((resolve, reject) => {
const timeout = window.setTimeout(() => {
cancelAnimationFrame(frame);
reject(new Error("The file sheet did not pass through the opening position"));
}, 5_000);
const dismissDuringOpening = () => {
const header = document.querySelector('[data-testid="sheet-tab-header"]');
const top = header?.getBoundingClientRect().top ?? window.innerHeight;
const pressTarget = document.elementFromPoint(10, 10);
if (
top > window.innerHeight / 2 &&
top < window.innerHeight &&
pressTarget instanceof HTMLElement &&
pressTarget.getAttribute("aria-label") === "Bottom sheet backdrop"
) {
window.clearTimeout(timeout);
pressTarget.click();
resolve();
return;
}
frame = requestAnimationFrame(dismissDuringOpening);
};
let frame = requestAnimationFrame(dismissDuringOpening);
link.click();
});
});
}
test("a sheet dismissed while it is still opening closes its tab", async ({ page }) => {
await page.setViewportSize({ width: 390, height: 844 });
const workspace = await seedMockAgentWorkspace({
repoPrefix: "compact-sheet-opening-dismiss-",
title: "Sheet parent",
initialPrompt: promptMentioning(FILE_LINK),
});
try {
await writeFile(path.join(workspace.cwd, "linked.ts"), "one\ntwo\nthree\n", "utf8");
await openAgentRoute(page, { workspaceId: workspace.workspaceId, agentId: workspace.agentId });
await openFileAndDismissDuringAnimation(page);
await expectNoSheetOpen(page);
await expectOpenTabCount(page, 1);
await page
.getByRole("button", { name: /Switch tabs/ })
.filter({ visible: true })
.click();
await expect(page.getByText("Workspace tabs", { exact: true })).toBeVisible();
} finally {
await workspace.cleanup();
}
});
@@ -63,6 +63,8 @@ using namespace facebook::react;
- (instancetype)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame]) {
// The iOS status-bar tap region can overlap app header buttons (#11027).
self.scrollView.scrollsToTop = NO;
#if defined(__IPHONE_26_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_26_0
if (@available(iOS 26.0, *)) {
UIScrollView *scrollView = self.scrollView;
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/app",
"version": "0.18.1",
"version": "0.18.2",
"private": true,
"main": "index.ts",
"scripts": {
@@ -7,7 +7,7 @@ import { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { RetainedPanelActivity } from "@/components/retained-panel";
import { reduceStreamUpdate, type StreamItem } from "@/types/stream";
import { hydrateStreamState, reduceStreamUpdate, type StreamItem } from "@/types/stream";
import type { StreamRenderInput, StreamSegmentRenderers, StreamViewportHandle } from "./strategy";
import { createWebStreamStrategy } from "./strategy-web";
@@ -1660,4 +1660,86 @@ describe("createWebStreamStrategy", () => {
expect(container.querySelector('[data-testid="agent-chat-scroll"]')).toBe(scrollContainer);
expect(scrollTo).toHaveBeenCalledWith({ top: 2200, behavior: "auto" });
});
it("renders batched user messages sharing a provider messageId without duplicate React keys", () => {
const sharedProviderMessageId = "9ffc3d6e-f0ff-4005-8675-e76e9c5eb5a8";
const historyMounted = hydrateStreamState(
[
{
event: {
type: "timeline",
provider: "claude",
item: {
type: "user_message",
text: "first queued prompt",
messageId: sharedProviderMessageId,
clientMessageId: "client-queued-1",
},
},
timestamp: new Date("2026-11-29T13:00:00.000Z"),
timelineCursor: { epoch: "epoch-1", seq: 1 },
},
{
event: {
type: "timeline",
provider: "claude",
item: {
type: "user_message",
text: "second direct prompt",
messageId: sharedProviderMessageId,
clientMessageId: "client-direct-2",
},
},
timestamp: new Date("2026-11-29T13:00:01.000Z"),
timelineCursor: { epoch: "epoch-1", seq: 2 },
},
],
{ source: "canonical" },
);
const consoleError = vi.spyOn(console, "error").mockImplementation(() => {});
const renderers = createRenderers(() => {});
const strategy = createWebStreamStrategy({ isMobileBreakpoint: false });
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
const rendered = strategy.render({
agentId: "agent",
segments: { historyVirtualized: [], historyMounted, liveHead: [] },
boundary: {
hasVirtualizedHistory: false,
hasMountedHistory: true,
hasLiveHead: false,
},
renderers,
listEmptyComponent: null,
viewportRef: React.createRef<StreamViewportHandle>(),
routeBottomAnchorRequest: null,
isAuthoritativeHistoryReady: true,
onNearBottomChange: () => {},
onNearHistoryStart: async () => true,
isLoadingOlderHistory: false,
hasOlderHistory: false,
olderHistoryProgressKey: null,
scrollEnabled: true,
listStyle: null,
baseListContentContainerStyle: null,
forwardListContentContainerStyle: null,
contentMaxWidth: DEFAULT_CONTENT_MAX_WIDTH,
});
act(() => {
root?.render(rendered);
});
const isSameKeyMessage = (arg: unknown) => typeof arg === "string" && arg.includes("same key");
const duplicateKeyErrors = consoleError.mock.calls.filter((args) =>
args.some(isSameKeyMessage),
);
expect(duplicateKeyErrors).toEqual([]);
expect(
Array.from(container.querySelectorAll("[data-history-row-id]")).map((node) =>
node.getAttribute("data-history-row-id"),
),
).toEqual(["client-queued-1", "client-direct-2"]);
});
});
+3 -2
View File
@@ -4,6 +4,7 @@ import type {
CommandCenterRegistration,
CommandCenterRegistrationOwner,
} from "./contributions";
import { compareText } from "@/utils/collation";
export interface CommandCenterRegistry {
getSnapshot(): CommandCenterContributionSnapshot;
@@ -28,10 +29,10 @@ function compareContributions(
right: CommandCenterContribution,
): number {
if (left.groupRank !== right.groupRank) return left.groupRank - right.groupRank;
const groupDelta = left.group.localeCompare(right.group);
const groupDelta = compareText(left.group, right.group);
if (groupDelta !== 0) return groupDelta;
if (left.rank !== right.rank) return left.rank - right.rank;
return left.id.localeCompare(right.id);
return compareText(left.id, right.id);
}
function sameContributions(
@@ -205,6 +205,7 @@ export function useWorkspaceCommandCenterActions(): void {
const { overrides } = useKeyboardShortcutOverrides();
const { gitActions, isGit, archiveWorkspace } = useGitActions({
serverId: serverId ?? "",
workspaceId,
cwd: cwd ?? "",
icons: GIT_ACTION_ICONS,
});
@@ -688,6 +688,32 @@ it("keeps workspace-relative hover titles on explicit absolute file links", () =
);
});
it.each([
[
"an angle-bracket destination",
"[Open](</repo/src/file.ts>)",
'[Open](</repo/src/file.ts> "src/file.ts")',
],
["an escaped slash", "[Open](\\/repo/src/file.ts)", '[Open](\\/repo/src/file.ts "src/file.ts")'],
[
"an escaped separator",
"[Open](/repo\\/src/file.ts)",
'[Open](/repo\\/src/file.ts "src/file.ts")',
],
[
"a character reference",
"[Open](&#x2F;repo/src/file.ts)",
'[Open](&#x2F;repo/src/file.ts "src/file.ts")',
],
])("keeps the workspace hover title on a link written with %s", (_form, source, rendered) => {
expect(prepareMarkdownSource(source, "/repo").render()).toBe(rendered);
});
it("leaves links outside the workspace as written", () => {
const source = "[Docs](https://example.com/repo/x) and [Other](/repository/x) near /repo/x";
expect(prepareMarkdownSource(source, "/repo").render()).toBe(source);
});
it.each(['""', "''", "()"])("preserves an authored empty link title: %s", (title) => {
const source = `[Open](/repo/file.ts ${title})`;
expect(prepareMarkdownSource(source, "/repo").render()).toBe(source);
@@ -150,6 +150,13 @@ function workspaceHoverTitle(link: Link, markup: string, workspaceRoot?: string)
return link.url.slice(workspaceRoot.length + 1);
}
// Only a link into the workspace gets an edit, its hover title. A link's URL differs from its
// source text only by backslash escapes and character references, and `&` already takes the parse.
function mayLinkIntoWorkspace(source: string, workspaceRoot?: string): boolean {
if (!workspaceRoot || !source.includes("](")) return false;
return source.includes(`${workspaceRoot}/`) || source.includes("\\");
}
/** Preserve source spelling; adapt workspace images, spoiler delimiters, and entity text. */
export function prepareMarkdownSource(
source: string,
@@ -191,7 +198,7 @@ export function prepareMarkdownSource(
!/^[\t >]*[^\t >\r\n][^\r\n]*(?:\r\n|\r|\n)[^\r\n]+(?:\r\n|\r|\n)(?=[\t >:|-]*\|)[\t >|]*:?-[-\t :|]*$/m.test(
source,
) &&
!(workspaceRoot && source.includes("](")) &&
!mayLinkIntoWorkspace(source, workspaceRoot) &&
!(external && /\]|<[a-z]+:/i.test(source))
) {
return { images, ...metadata, render: () => source };
@@ -2,6 +2,7 @@ import {
BottomSheetModal as GorhomBottomSheetModal,
type BottomSheetModalProps,
type BottomSheetBackdropProps,
useBottomSheetInternal,
} from "@gorhom/bottom-sheet";
import React from "react";
import {
@@ -25,6 +26,7 @@ import {
type AttachSheetContentDrag,
type SheetContentDragGesture,
} from "@/components/ui/bottom-sheet-scope";
import { runOnJS, useAnimatedReaction, useSharedValue } from "react-native-reanimated";
import { SheetBackdrop } from "./sheet-backdrop";
type GorhomBottomSheetModalMethods = ElementRef<typeof GorhomBottomSheetModal>;
@@ -56,7 +58,7 @@ type IsolatedBottomSheetModalProps = Omit<
/**
* Whether closing (drag, backdrop, Back) also dismisses, which unmounts the content. Default
* true: the owner hears `onDismiss` and drops its state. Pass `false` for a sheet whose close the
* owner may veto: it parks at index -1 with its content mounted, the owner hears `onChange(-1)`,
* owner may veto: it parks at index -1 with its content mounted, the owner hears `onClosed`,
* and either snaps it back or unmounts it, which dismisses it from the stack.
*/
enableDismissOnClose?: boolean;
@@ -74,6 +76,15 @@ type IsolatedBottomSheetModalProps = Omit<
* inside the sheet and it throws on device only.
*/
contextBridge: ContextBridge | null;
/**
* Runs when a close animation settles at the closed detent, whoever started it.
*
* Gorhom reports that through `onChange(-1)`, but skips `onChange` when its index bookkeeping
* already reads -1. An interrupted mount animation leaves it there, so the next close ends where
* it began and the owner never hears about it. Watch this signal, not `onChange`, when a close
* the owner may veto still has to reach the owner.
*/
onClosed?: () => void;
};
export type IsolatedBottomSheetModalRef = GorhomBottomSheetModalMethods;
@@ -105,6 +116,7 @@ export const IsolatedBottomSheetModal = forwardRef<
contextBridge,
backdropOpacity,
enableDismissOnClose = true,
onClosed,
waitFor,
simultaneousHandlers,
...bottomSheetProps
@@ -151,6 +163,7 @@ export const IsolatedBottomSheetModal = forwardRef<
simultaneousHandlers={contentDragHandlers.simultaneousHandlers}
>
<BottomSheetScope attachContentDrag={attachContentDrag}>
{onClosed ? <SheetCloseSignal onClosed={onClosed} /> : null}
{contextBridge ? contextBridge(children) : children}
</BottomSheetScope>
</GorhomBottomSheetModal>
@@ -159,6 +172,43 @@ export const IsolatedBottomSheetModal = forwardRef<
return modal;
});
/**
* Reports a close animation that settles at the closed detent — the signal Gorhom only routes
* through `onChange(-1)`, which it drops when the sheet's current index already reads -1.
*
* `animatedAnimationState.nextIndex` is -1 for the whole close animation and undefined once it
* completes. The settled position then tells a real close from a spring back and an interruption.
*/
function SheetCloseSignal({ onClosed }: { onClosed: () => void }) {
const { animatedAnimationState, animatedDetentsState, animatedPosition } =
useBottomSheetInternal();
const closing = useSharedValue(false);
useAnimatedReaction(
() => {
const { nextIndex } = animatedAnimationState.get();
if (nextIndex === -1) return -1;
return nextIndex === undefined ? 0 : 1;
},
(phase, previousPhase) => {
if (phase === -1) {
closing.value = true;
return;
}
if (phase === 1) {
closing.value = false;
return;
}
if (previousPhase !== -1 || !closing.value) return;
closing.value = false;
const closedPosition = animatedDetentsState.get().closedDetentPosition;
if (closedPosition === undefined) return;
if (Math.abs(animatedPosition.value - closedPosition) < 1) runOnJS(onClosed)();
},
[animatedAnimationState, animatedDetentsState, animatedPosition, onClosed],
);
return null;
}
export function useIsolatedBottomSheetVisibility({
visible,
isEnabled,
@@ -6,9 +6,13 @@ import { createProviderSnapshotCache, type ProviderSnapshotCache } from "./provi
const SNAPSHOT_KEY_PREFIX = "@paseo/provider-snapshot/v2:";
const SNAPSHOT_INDEX_KEY = "@paseo/provider-snapshot-index/v2";
const STORED_INDEX_KEY = "@paseo/provider-snapshot-index/v3";
function createStorage(maxSnapshotBytes = Number.POSITIVE_INFINITY) {
const values = new Map<string, string>();
const stats = { getAllKeysCalls: 0 };
const stats = { getAllKeysCalls: 0, snapshotsRead: [] as string[] };
function recordRead(key: string) {
if (key.startsWith(SNAPSHOT_KEY_PREFIX)) stats.snapshotsRead.push(key);
}
type Operation = "setItem" | "removeItem" | "multiRemove";
let failure: { operation: Operation; timing: "before" | "after"; key?: string } | null = null;
@@ -31,6 +35,7 @@ function createStorage(maxSnapshotBytes = Number.POSITIVE_INFINITY) {
failure = { operation, timing, key };
},
async getItem(key: string) {
recordRead(key);
return values.get(key) ?? null;
},
async setItem(key: string, value: string) {
@@ -61,6 +66,7 @@ function createStorage(maxSnapshotBytes = Number.POSITIVE_INFINITY) {
return [...values.keys()];
},
async multiGet(keys: readonly string[]) {
keys.forEach(recordRead);
return keys.map((key) => [key, values.get(key) ?? null] as const);
},
async multiRemove(keys: readonly string[]) {
@@ -385,6 +391,62 @@ describe("provider snapshot cache", () => {
expect(storage.stats.getAllKeysCalls).toBe(1);
});
it("reads only the requested snapshot after a restart and still enforces the budget", async () => {
const storage = createStorage();
const cache = createProviderSnapshotCache(storage);
for (const [day, label] of ["one", "two", "three"].entries()) {
await writeSnapshot(cache, {
cwd: `/${label}`,
label,
generatedAt: `2026-08-0${day + 1}T00:00:00.000Z`,
});
}
const maxBytes = snapshotBytes(storage.values);
storage.stats.snapshotsRead.length = 0;
const restarted = createProviderSnapshotCache(storage, { maxBytes });
await expect(restarted.read("server-1", "/two")).resolves.toMatchObject({ hash: "two" });
expect(storage.stats.snapshotsRead).toEqual([
`${SNAPSHOT_KEY_PREFIX}["server-1","cwd","/two"]`,
`${SNAPSHOT_KEY_PREFIX}["server-1","hash","two"]`,
]);
await writeSnapshot(restarted, {
cwd: "/four",
label: "four",
generatedAt: "2026-08-04T00:00:00.000Z",
});
await expect(restarted.read("server-1", "/one")).resolves.toBeNull();
await expect(restarted.read("server-1", "/four")).resolves.not.toBeNull();
expect(snapshotBytes(storage.values)).toBeLessThanOrEqual(maxBytes);
expectConsistentSnapshots(storage.values);
});
it("counts snapshots that another cache instance stored after a restart", async () => {
const storage = createStorage();
const first = createProviderSnapshotCache(storage);
const second = createProviderSnapshotCache(storage);
await second.read("server-1", "/none");
await writeSnapshot(first, {
cwd: "/first",
label: "first",
generatedAt: "2026-08-01T00:00:00.000Z",
});
await writeSnapshot(second, {
cwd: "/second",
label: "second",
generatedAt: "2026-08-02T00:00:00.000Z",
});
const maxBytes = snapshotBytes(storage.values) - 1;
const restarted = createProviderSnapshotCache(storage, { maxBytes });
await expect(restarted.read("server-1", "/second")).resolves.toMatchObject({ hash: "second" });
await expect(restarted.read("server-1", "/first")).resolves.toBeNull();
expect(snapshotBytes(storage.values)).toBeLessThanOrEqual(maxBytes);
expectConsistentSnapshots(storage.values);
});
it("replaces an indexed snapshot without counting both versions", async () => {
const storage = createStorage();
const maxBytes = 1_000;
@@ -559,6 +621,13 @@ describe("provider snapshot cache", () => {
entries: [{ key: `${SNAPSHOT_KEY_PREFIX}phantom`, bytes: 999_999, writtenAt: "bad" }],
}),
);
storage.values.set(
STORED_INDEX_KEY,
JSON.stringify({
version: 3,
entries: [{ key: `${SNAPSHOT_KEY_PREFIX}phantom`, bytes: 999_999, writtenAt: "bad" }],
}),
);
const restarted = createProviderSnapshotCache(storage, { maxBytes });
await writeSnapshot(restarted, {
@@ -15,7 +15,8 @@ type SnapshotPayload = GetProvidersSnapshotResponseMessage["payload"];
const CACHE_VERSION = 2;
const CACHE_KEY_PREFIX = "@paseo/provider-snapshot/v2";
const CACHE_INDEX_KEY = "@paseo/provider-snapshot-index/v2";
const CACHE_INDEX_VERSION = 3;
const CACHE_INDEX_KEY = "@paseo/provider-snapshot-index/v3";
const DEFAULT_MAX_CACHE_BYTES = 4 * 1024 * 1024;
interface ProviderSnapshotStorage {
@@ -43,8 +44,22 @@ interface ProviderSnapshotIndexEntry {
key: string;
bytes: number;
writtenAt: string;
// A directory association names the body it depends on.
body?: string;
}
const ProviderSnapshotIndexSchema = z.object({
version: z.literal(CACHE_INDEX_VERSION),
entries: z.array(
z.object({
key: z.string(),
bytes: z.number(),
writtenAt: z.string(),
body: z.string().optional(),
}),
),
});
const StoredProviderSnapshotSchema: z.ZodType<StoredProviderSnapshot> = z.strictObject({
version: z.literal(CACHE_VERSION),
hash: z.string(),
@@ -109,14 +124,26 @@ function decodeCacheKey(key: string) {
return CacheKeySchema.parse(JSON.parse(key.slice(CACHE_KEY_PREFIX.length + 1)));
}
// Timestamps and keys are machine strings: code-unit order is the intended order, and it spares
// a collator call per comparison.
function oldestFirst(left: ProviderSnapshotIndexEntry, right: ProviderSnapshotIndexEntry): number {
const writtenAtOrder = left.writtenAt.localeCompare(right.writtenAt);
if (writtenAtOrder !== 0) return writtenAtOrder;
if (left.writtenAt !== right.writtenAt) return left.writtenAt < right.writtenAt ? -1 : 1;
// References must be evicted before equally recent bodies, regardless of key encoding.
const leftKind = decodeCacheKey(left.key)[1];
const rightKind = decodeCacheKey(right.key)[1];
if (leftKind !== rightKind) return leftKind === "cwd" ? -1 : 1;
return left.key.localeCompare(right.key);
const leftIsReference = left.body !== undefined;
if (leftIsReference !== (right.body !== undefined)) return leftIsReference ? -1 : 1;
if (left.key === right.key) return 0;
return left.key < right.key ? -1 : 1;
}
function parseStoredIndex(value: string | null): ProviderSnapshotIndexEntry[] {
if (value === null) return [];
try {
const result = ProviderSnapshotIndexSchema.safeParse(JSON.parse(value));
return result.success ? result.data.entries : [];
} catch (error) {
if (!(error instanceof SyntaxError)) throw error;
return [];
}
}
function parseStoredProviderSnapshot(key: string, value: string): StoredProviderSnapshot | null {
@@ -135,9 +162,23 @@ export function createProviderSnapshotCache(
): ProviderSnapshotCache {
const maxBytes = options.maxBytes ?? DEFAULT_MAX_CACHE_BYTES;
let index: ProviderSnapshotIndexEntry[] | null = null;
// The index value last read from or written to storage.
let storedIndex: string | null = null;
let operationQueue = Promise.resolve();
const bodies = new Map<string, CachedProviderSnapshot>();
// The stored index spares a restart from reading every snapshot to learn its size and age.
// Storage keys stay the authority on what exists: an indexed key that is gone is dropped, and
// a stored key the index does not list is read and measured here.
async function commitIndex(entries: ProviderSnapshotIndexEntry[]): Promise<void> {
const serialized = JSON.stringify({ version: CACHE_INDEX_VERSION, entries });
if (serialized !== storedIndex) {
await storage.setItem(CACHE_INDEX_KEY, serialized);
storedIndex = serialized;
}
index = entries;
}
async function reconcileCache(): Promise<void> {
const allKeys = await storage.getAllKeys();
// COMPAT(providerSnapshotCache): added in v0.7.2, remove legacy cleanup after 2027-03-06.
@@ -145,14 +186,17 @@ export function createProviderSnapshotCache(
(key) =>
key.startsWith("@paseo/provider-snapshot/v1:") ||
key === "@paseo/provider-snapshot-index/v1" ||
key === CACHE_INDEX_KEY,
key === "@paseo/provider-snapshot-index/v2",
);
if (legacyKeys.length) await storage.multiRemove(legacyKeys);
const keys = allKeys.filter((key) => key.startsWith(`${CACHE_KEY_PREFIX}:`));
const values = await storage.multiGet(keys);
storedIndex = allKeys.includes(CACHE_INDEX_KEY) ? await storage.getItem(CACHE_INDEX_KEY) : null;
const storedKeys = new Set(keys);
const entries = parseStoredIndex(storedIndex).filter((entry) => storedKeys.has(entry.key));
const indexedKeys = new Set(entries.map((entry) => entry.key));
const unindexedKeys = keys.filter((key) => !indexedKeys.has(key));
const values = unindexedKeys.length > 0 ? await storage.multiGet(unindexedKeys) : [];
const keysToRemove: string[] = [];
const entries: ProviderSnapshotIndexEntry[] = [];
const references: Array<{ key: string; body: string; writtenAt: string }> = [];
for (const [key, value] of values) {
if (value === null) continue;
try {
@@ -162,13 +206,12 @@ export function createProviderSnapshotCache(
continue;
}
const [serverId, kind] = decodeCacheKey(key);
entries.push({ key, bytes: storedBytes(key, value), writtenAt: stored.generatedAt });
if (kind === "cwd")
references.push({
key,
body: bodyKey(serverId, stored.hash),
writtenAt: stored.generatedAt,
});
entries.push({
key,
bytes: storedBytes(key, value),
writtenAt: stored.generatedAt,
...(kind === "cwd" ? { body: bodyKey(serverId, stored.hash) } : {}),
});
} catch (error) {
if (
!(error instanceof SyntaxError) &&
@@ -181,7 +224,8 @@ export function createProviderSnapshotCache(
}
// Reconstruct the dependency ordering before applying a possibly smaller budget.
for (const reference of references) {
for (const reference of entries) {
if (reference.body === undefined) continue;
const body = entries.find((entry) => entry.key === reference.body);
if (!body) keysToRemove.push(reference.key);
else if (body.writtenAt < reference.writtenAt) body.writtenAt = reference.writtenAt;
@@ -200,7 +244,7 @@ export function createProviderSnapshotCache(
for (const removedKey of keysToRemove) bodies.delete(removedKey);
await storage.multiRemove(keysToRemove);
}
index = retainedEntries;
await commitIndex(retainedEntries);
}
async function ensureCacheIndex(): Promise<ProviderSnapshotIndexEntry[]> {
@@ -235,7 +279,7 @@ export function createProviderSnapshotCache(
value,
};
}
const incoming = prepare(key, input);
const incoming = { ...prepare(key, input), body: requiredBody?.key };
// The index is committed last: membership proves a body was stored. Reusing it
// needs only its byte count, not another parse, expansion, or storage write.
const body = requiredBody
@@ -265,29 +309,27 @@ export function createProviderSnapshotCache(
const keysToRemove = [...replacedKeys].filter(
(replaced) => !admitted.some((entry) => entry.key === replaced),
);
for (const candidate of [...retainedEntries].sort(oldestFirst)) {
if (projectedBytes <= maxBytes) break;
projectedBytes -= candidate.bytes;
keysToRemove.push(candidate.key);
if (projectedBytes > maxBytes) {
for (const candidate of [...retainedEntries].sort(oldestFirst)) {
if (projectedBytes <= maxBytes) break;
projectedBytes -= candidate.bytes;
keysToRemove.push(candidate.key);
}
}
const removedKeys = new Set(keysToRemove);
if (keysToRemove.length > 0) {
for (const removedKey of keysToRemove) bodies.delete(removedKey);
await storage.multiRemove(keysToRemove);
}
// Body, then reference, then in-memory index. A failed write can leave a reusable
// Body, then reference, then index. A failed write can leave a reusable
// orphan body; reconciliation never retains a reference without its body.
for (const entry of admitted) {
if (entry.value !== undefined) await storage.setItem(entry.key, entry.value);
}
index = [
await commitIndex([
...retainedEntries.filter((entry) => !removedKeys.has(entry.key)),
...admitted.map(({ key: recordKey, bytes, writtenAt }) => ({
key: recordKey,
bytes,
writtenAt,
})),
];
...admitted.map(({ value: _value, ...entry }) => entry),
]);
}
async function readRecord(key: string): Promise<StoredProviderSnapshot | null> {
@@ -302,7 +344,7 @@ export function createProviderSnapshotCache(
if (!(error instanceof SyntaxError) && !(error instanceof RangeError)) throw error;
bodies.delete(key);
await storage.removeItem(key);
index = currentIndex.filter((entry) => entry.key !== key);
await commitIndex(currentIndex.filter((entry) => entry.key !== key));
return null;
}
}
@@ -65,7 +65,7 @@ const nativeRequire = createRequire(require.resolve("react-native/package.json")
const { AbortController: NativeAbortController }: { AbortController: typeof AbortController } =
nativeRequire("abort-controller/dist/abort-controller");
function createStorage(onWrite: () => void = () => {}) {
function createStorage(onWrite: (key: string) => void = () => {}) {
const values = new Map<string, string>();
return {
async getItem(key: string) {
@@ -73,7 +73,7 @@ function createStorage(onWrite: () => void = () => {}) {
},
async setItem(key: string, value: string) {
values.set(key, value);
onWrite();
onWrite(key);
},
async removeItem(key: string) {
values.delete(key);
@@ -164,7 +164,9 @@ describe.each([
async ({ abortOnWrite, hasBody, hasReference }) => {
const controller = new Controller();
let writes = 0;
const storage = createStorage(() => {
const storage = createStorage((key) => {
// The boundaries are the stored snapshots, not the cache's own index of them.
if (!key.startsWith("@paseo/provider-snapshot/")) return;
writes += 1;
if (writes === abortOnWrite) controller.abort();
});
@@ -0,0 +1,80 @@
import { afterEach, describe, expect, it } from "vitest";
import { useSessionStore, type WorkspaceDescriptor } from "@/stores/session-store";
import { selectGitActionsWorkspace } from "./actions-workspace";
const SERVER_ID = "git-actions-server";
function createWorkspace(id: string, workspaceDirectory: string): WorkspaceDescriptor {
return {
id,
projectId: "project-1",
projectDisplayName: "Project 1",
projectRootPath: workspaceDirectory,
workspaceDirectory,
projectKind: "git",
workspaceKind: "worktree",
name: id,
status: "done",
archivingAt: null,
statusEnteredAt: null,
diffStat: null,
scripts: [],
createdAt: null,
lastUserMessageAt: null,
};
}
function seed(workspaces: WorkspaceDescriptor[]): void {
const store = useSessionStore.getState();
store.initializeSession(SERVER_ID, null);
store.mergeWorkspaces(SERVER_ID, workspaces);
}
afterEach(() => {
useSessionStore.getState().clearSession(SERVER_ID);
});
describe("selectGitActionsWorkspace", () => {
it("resolves the workspace the git actions belong to, not another one in the same directory", () => {
seed([createWorkspace("ws-a", "/repo"), createWorkspace("ws-b", "/repo")]);
const workspace = selectGitActionsWorkspace(useSessionStore.getState(), {
serverId: SERVER_ID,
workspaceId: "ws-b",
workspaceDirectory: "/repo",
});
expect(workspace?.id).toBe("ws-b");
});
// Each retained workspace subscribes through this selector. Returning the same descriptor when
// another workspace on the host changes keeps hidden workspaces from re-rendering their git
// actions on every workspace switch.
it("keeps the descriptor reference when another workspace on the host changes", () => {
seed([createWorkspace("ws-a", "/repo-a"), createWorkspace("ws-b", "/repo-b")]);
const input = { serverId: SERVER_ID, workspaceId: "ws-a", workspaceDirectory: "/repo-a" };
const before = selectGitActionsWorkspace(useSessionStore.getState(), input);
useSessionStore
.getState()
.mergeWorkspaces(SERVER_ID, [{ ...createWorkspace("ws-b", "/repo-b"), status: "running" }]);
expect(useSessionStore.getState().sessions[SERVER_ID]?.workspaces.get("ws-b")?.status).toBe(
"running",
);
expect(before?.id).toBe("ws-a");
expect(selectGitActionsWorkspace(useSessionStore.getState(), input)).toBe(before);
});
it("falls back to the workspace in the checkout directory when the caller names no workspace", () => {
seed([createWorkspace("ws-a", "/repo-a"), createWorkspace("ws-b", "/repo-b")]);
const workspace = selectGitActionsWorkspace(useSessionStore.getState(), {
serverId: SERVER_ID,
workspaceId: null,
workspaceDirectory: "/repo-b",
});
expect(workspace?.id).toBe("ws-b");
});
});
+38
View File
@@ -0,0 +1,38 @@
import type { SessionsSnapshot } from "@/stores/session-store-hooks/selectors";
import type { WorkspaceDescriptor } from "@/stores/session-store";
import { resolveWorkspaceMapKeyByIdentity } from "@/utils/workspace-identity";
export interface GitActionsWorkspaceInput {
serverId: string;
/** The workspace that renders the git actions, or null when the caller has none. */
workspaceId: string | null | undefined;
/** The checkout directory, used to find the workspace when the caller names none. */
workspaceDirectory: string | null | undefined;
}
/**
* The workspace descriptor the git actions archive. Returns the stored descriptor itself, so a
* subscriber re-renders only when this workspace changes, not when another workspace on the host
* does.
*/
export function selectGitActionsWorkspace(
state: SessionsSnapshot,
input: GitActionsWorkspaceInput,
): WorkspaceDescriptor | null {
const workspaces = state.sessions[input.serverId]?.workspaces;
const workspaceKey = input.workspaceId
? resolveWorkspaceMapKeyByIdentity({ workspaces, workspaceId: input.workspaceId })
: null;
if (workspaceKey) {
return workspaces?.get(workspaceKey) ?? null;
}
if (!input.workspaceDirectory) {
return null;
}
for (const candidate of workspaces?.values() ?? []) {
if (candidate.workspaceDirectory === input.workspaceDirectory) {
return candidate;
}
}
return null;
}
+1
View File
@@ -1767,6 +1767,7 @@ export function ChangesSurface({
);
const { gitActions, branchLabel } = useGitActions({
serverId,
workspaceId,
cwd,
icons: GIT_ACTION_ICONS,
});
+20 -46
View File
@@ -28,14 +28,11 @@ import type { CheckoutPrMergeMethod } from "@getpaseo/protocol/messages";
import { openExternalUrl } from "@/utils/open-external-url";
import { useToast } from "@/contexts/toast-context";
import { useSessionStore, type WorkspaceDescriptor } from "@/stores/session-store";
import {
useActiveWorkspaceSelection,
type ActiveWorkspaceSelection,
} from "@/stores/navigation-active-workspace-store";
import { redirectIfArchivingActiveWorkspace } from "@/utils/sidebar-workspace-archive-redirect";
import { getFocusedWorkspaceSelection } from "@/navigation/workspace-route-navigation";
import { selectGitActionsWorkspace } from "@/git/actions-workspace";
import { type WorktreeArchiveWarningLabels } from "@/git/worktree-archive-warning";
import { useWorkspaceArchive } from "@/workspace/use-workspace-archive";
import { resolveWorkspaceMapKeyByIdentity } from "@/utils/workspace-identity";
import { readValidatedString } from "@/storage/validated-storage";
export type { GitActionId, GitAction, GitActions } from "@/git/policy";
@@ -200,6 +197,8 @@ function deriveGitActionsState(args: DeriveGitActionsStateArgs): DerivedGitActio
interface UseGitActionsInput {
serverId: string;
/** The workspace these actions belong to; a retained, hidden workspace passes its own. */
workspaceId: string | null | undefined;
cwd: string;
icons: {
commit: ReactElement;
@@ -222,38 +221,13 @@ interface UseGitActionsResult {
interface UseWorkspaceScreenArchiveControllerInput {
serverId: string;
activeWorkspaceSelection: ActiveWorkspaceSelection | null;
workspaceId: string | null | undefined;
workspaceDirectory: string | null | undefined;
branchLabel: string;
gitStatus: CheckoutStatusPayload | null;
t: (key: string, options?: Record<string, unknown>) => string;
}
function resolveArchiveWorkspaceDescriptor(input: {
workspaces: Map<string, WorkspaceDescriptor> | undefined;
activeWorkspaceSelection: ActiveWorkspaceSelection | null;
workspaceDirectory: string | null | undefined;
}): WorkspaceDescriptor | null {
const activeWorkspaceKey = input.activeWorkspaceSelection
? resolveWorkspaceMapKeyByIdentity({
workspaces: input.workspaces,
workspaceId: input.activeWorkspaceSelection.workspaceId,
})
: null;
if (activeWorkspaceKey) {
return input.workspaces?.get(activeWorkspaceKey) ?? null;
}
if (!input.workspaceDirectory) {
return null;
}
for (const candidate of input.workspaces?.values() ?? []) {
if (candidate.workspaceDirectory === input.workspaceDirectory) {
return candidate;
}
}
return null;
}
function resolveWorkspaceArchiveRisk(
workspace: WorkspaceDescriptor | null,
gitStatus: CheckoutStatusPayload | null,
@@ -284,23 +258,16 @@ function availableArchive(
function useWorkspaceScreenArchiveController({
serverId,
activeWorkspaceSelection,
workspaceId,
workspaceDirectory,
branchLabel,
gitStatus,
t,
}: UseWorkspaceScreenArchiveControllerInput) {
const sessionWorkspaces = useSessionStore((state) => state.sessions[serverId]?.workspaces);
const [isHidingWorkspace, setIsHidingWorkspace] = useState(false);
const workspaceDescriptor = useMemo(
() =>
resolveArchiveWorkspaceDescriptor({
workspaces: sessionWorkspaces,
activeWorkspaceSelection,
workspaceDirectory,
}),
[activeWorkspaceSelection, sessionWorkspaces, workspaceDirectory],
const workspaceDescriptor = useSessionStore((state) =>
selectGitActionsWorkspace(state, { serverId, workspaceId, workspaceDirectory }),
);
const [isHidingWorkspace, setIsHidingWorkspace] = useState(false);
const archiveRisk = resolveWorkspaceArchiveRisk(workspaceDescriptor, gitStatus);
const controller = useWorkspaceArchive({
@@ -313,7 +280,10 @@ function useWorkspaceScreenArchiveController({
warningLabels: getWorktreeArchiveWarningLabels(t),
onSetHiding: setIsHidingWorkspace,
onArchiveStarted: (archived) => {
redirectIfArchivingActiveWorkspace({ ...archived, activeWorkspaceSelection });
redirectIfArchivingActiveWorkspace({
...archived,
activeWorkspaceSelection: getFocusedWorkspaceSelection(),
});
},
});
@@ -324,10 +294,14 @@ function useWorkspaceScreenArchiveController({
};
}
export function useGitActions({ serverId, cwd, icons }: UseGitActionsInput): UseGitActionsResult {
export function useGitActions({
serverId,
workspaceId,
cwd,
icons,
}: UseGitActionsInput): UseGitActionsResult {
const { t } = useTranslation();
const toast = useToast();
const activeWorkspaceSelection = useActiveWorkspaceSelection();
const [postShipArchiveSuggested, setPostShipArchiveSuggested] = useState(false);
const [shipDefault, setShipDefault] = useState<"merge" | "pr">("pr");
@@ -646,7 +620,7 @@ export function useGitActions({ serverId, cwd, icons }: UseGitActionsInput): Use
const archiveController = useWorkspaceScreenArchiveController({
serverId,
activeWorkspaceSelection,
workspaceId,
workspaceDirectory: status?.cwd,
branchLabel,
gitStatus,
+3 -1
View File
@@ -4,12 +4,14 @@ import { useGitActions } from "@/git/use-actions";
interface WorkspaceActionsProps {
serverId: string;
workspaceId: string;
cwd: string;
}
export function WorkspaceActions({ serverId, cwd }: WorkspaceActionsProps) {
export function WorkspaceActions({ serverId, workspaceId, cwd }: WorkspaceActionsProps) {
const { gitActions } = useGitActions({
serverId,
workspaceId,
cwd,
icons: GIT_ACTION_ICONS,
});
@@ -5,7 +5,9 @@
import { polyfillCrypto } from "./crypto";
import { polyfillNavigator } from "./navigator";
import { polyfillScreenOrientation } from "./screen-orientation";
import { configureZodJit } from "./zod-jit";
configureZodJit();
polyfillCrypto();
polyfillNavigator();
// Polyfill screen.orientation for WebKitGTK desktop runtimes that lack the API.
@@ -0,0 +1,9 @@
import { z } from "zod";
// Zod compiles a parser for each object schema with `new Function` the first time it parses.
// Hermes has no JIT: it pays to compile that source at runtime and the result runs no faster than
// Zod's plain parser. A cold launch on Android spent about 145 ms less in Zod with this off.
// A schema reads the setting when it is constructed, so this runs before any schema module loads.
export function configureZodJit(): void {
z.config({ jitless: true });
}
@@ -0,0 +1,26 @@
import { readFileSync } from "node:fs";
import ts from "typescript";
import { expect, it } from "vitest";
import { z } from "zod";
import { configureZodJit } from "./zod-jit.native";
it("turns off Zod's compiled parsers on native before the app entry loads schema modules", () => {
const early = ts.createSourceFile(
"install-early.ts",
readFileSync(new URL("./install-early.ts", import.meta.url), "utf8"),
ts.ScriptTarget.Latest,
);
expect(
early.statements.some(
(statement) =>
ts.isExpressionStatement(statement) &&
ts.isCallExpression(statement.expression) &&
statement.expression.expression.getText(early) === "configureZodJit",
),
).toBe(true);
configureZodJit();
expect(z.config().jitless).toBe(true);
expect(z.object({ id: z.string() }).parse({ id: "a", extra: 1 })).toEqual({ id: "a" });
});
+2
View File
@@ -0,0 +1,2 @@
// Browsers and Electron keep Zod's compiled parsers: V8 optimises them. See zod-jit.native.ts.
export function configureZodJit(): void {}
@@ -4,6 +4,7 @@ import type {
WorkspaceStructureProject,
} from "@/projects/workspace-structure";
import { createProjectViewKey } from "@/projects/workspace-structure";
import { compareNames, compareText } from "@/utils/collation";
export type HostProjectListItem = WorkspaceStructureProject;
@@ -152,14 +153,9 @@ function compareHostProjectsForServer(
serverId: string,
): number {
return (
left.projectName.localeCompare(right.projectName, undefined, {
numeric: true,
sensitivity: "base",
}) ||
(getHostProjectId(left, serverId) ?? "").localeCompare(
getHostProjectId(right, serverId) ?? "",
) ||
left.viewKey.localeCompare(right.viewKey)
compareNames(left.projectName, right.projectName) ||
compareText(getHostProjectId(left, serverId) ?? "", getHostProjectId(right, serverId) ?? "") ||
compareText(left.viewKey, right.viewKey)
);
}
@@ -1,5 +1,6 @@
import type { ProjectDescriptor, WorkspaceDescriptor } from "@/stores/session-store";
import { projectDisplayNameFromProjectId } from "@/utils/project-display-name";
import { compareNames, compareText } from "@/utils/collation";
export interface WorkspaceStructureHostPlacement {
serverId: string;
@@ -114,10 +115,8 @@ export function buildWorkspaceStructureProjects(input: {
}))
.sort(
(left, right) =>
left.projectName.localeCompare(right.projectName, undefined, {
numeric: true,
sensitivity: "base",
}) || left.viewKey.localeCompare(right.viewKey),
compareNames(left.projectName, right.projectName) ||
compareText(left.viewKey, right.viewKey),
);
}
@@ -207,10 +206,8 @@ function getOrCreate<K, V>(map: Map<K, V>, key: K, create: () => V): V {
function compareWorkspaceStructureItems(left: WorkspaceSortItem, right: WorkspaceSortItem): number {
return (
left.workspaceName.localeCompare(right.workspaceName, undefined, {
numeric: true,
sensitivity: "base",
}) || left.workspaceKey.localeCompare(right.workspaceKey)
compareNames(left.workspaceName, right.workspaceName) ||
compareText(left.workspaceKey, right.workspaceKey)
);
}
@@ -233,6 +233,18 @@ function timeline(text = "Cached") {
};
}
async function cacheMultiByteTimelineAfterOtherHost(
storage: MemoryStorage,
maxBytes?: number,
): Promise<void> {
const cache = new ReplicaCache(storage, { ...noLegacyCleanup, maxBytes });
cache.setHosts([SERVER_ID, "other-host"]);
cache.commitTimeline("other-host", "agent-1", timeline("other host"));
await cache.flush();
cache.commitTimeline(SERVER_ID, "agent-1", timeline(`plain café 日本語 ${"🙂".repeat(50)}`));
await cache.flush();
}
it("keeps the unsettled turn with the cached messages", async () => {
const storage = new MemoryStorage();
const writer = createCache(storage);
@@ -977,6 +989,26 @@ describe("ReplicaCache", () => {
expect(storage.rows.has(`${SERVER_ID}:project:project-1`)).toBe(true);
});
it.each([
{ slack: 0, retained: [SERVER_ID, "other-host"] },
{ slack: -1, retained: [SERVER_ID] },
])(
"evicts on the exact stored size of text of every UTF-8 width (budget slack $slack)",
async ({ slack, retained }) => {
const unbounded = new MemoryStorage();
await cacheMultiByteTimelineAfterOtherHost(unbounded);
let storedBytes = 0;
for (const row of unbounded.rows.values()) storedBytes += Buffer.byteLength(row.payload);
const storage = new MemoryStorage();
await cacheMultiByteTimelineAfterOtherHost(storage, storedBytes + slack);
const cachedHosts = new Set<string>();
for (const row of storage.rows.values()) cachedHosts.add(row.serverId);
expect([...cachedHosts].sort()).toEqual(retained);
},
);
it("removes a targeted corrupt row from eviction bookkeeping", async () => {
const otherServerId = "other-host";
const storage = new MemoryStorage();
@@ -1392,6 +1424,52 @@ it("retains semantic agent messages across disk-cache reconstruction", async ()
expect(await createCache(storage).readTimeline(SERVER_ID, "agent-1")).toEqual(value);
});
it("heals cached user_message rows whose stored id collided on a shared provider messageId", async () => {
const storage = new MemoryStorage();
const writer = createCache(storage);
const sharedProviderMessageId = "9ffc3d6e-f0ff-4005-8675-e76e9c5eb5a8";
const value = timeline();
value.items = [
{
kind: "user_message",
id: sharedProviderMessageId,
messageId: sharedProviderMessageId,
clientMessageId: "client-queued-1",
text: "first queued prompt",
timestamp: new Date(1),
timelineCursor: { epoch: "epoch-1", seq: 1 },
},
{
kind: "user_message",
id: sharedProviderMessageId,
messageId: sharedProviderMessageId,
clientMessageId: "client-direct-2",
text: "second direct prompt",
timestamp: new Date(2),
timelineCursor: { epoch: "epoch-1", seq: 2 },
},
];
writer.commitTimeline(SERVER_ID, "agent-1", value);
await writer.flush();
const restored = await createCache(storage).readTimeline(SERVER_ID, "agent-1");
expect(restored?.items.map((item) => item.id)).toEqual(["client-queued-1", "client-direct-2"]);
expect(restored?.items).toMatchObject([
{
kind: "user_message",
id: "client-queued-1",
clientMessageId: "client-queued-1",
messageId: sharedProviderMessageId,
},
{
kind: "user_message",
id: "client-direct-2",
clientMessageId: "client-direct-2",
messageId: sharedProviderMessageId,
},
]);
});
it("retains workspace metadata across replica-cache reload and invalidates pre-metadata rows", async () => {
const storage = new MemoryStorage();
const writer = createCache(storage);
@@ -564,6 +564,14 @@ function deserializeTimelineItem(item: StoredTimelineItem): StreamItem {
return deserializeBuiltinTimelineItem(item);
}
// COMPAT(userMessageRowId): added in v0.18.2, remove after 2027-06-01.
// Earlier builds stored batched user rows under the shared provider messageId instead of clientMessageId.
function storedUserMessageRowId(
item: Extract<StoredTimelineItem, { kind: "user_message" }>,
): string {
return item.clientMessageId && item.id === item.messageId ? item.clientMessageId : item.id;
}
function deserializeBuiltinTimelineItem(
item: Exclude<StoredTimelineItem, { kind: "plugin" }>,
): StreamItem {
@@ -577,6 +585,7 @@ function deserializeBuiltinTimelineItem(
case "user_message":
return {
...base,
id: storedUserMessageRowId(item),
kind: item.kind,
...(item.clientMessageId ? { clientMessageId: item.clientMessageId } : {}),
...(item.messageId ? { messageId: item.messageId } : {}),
@@ -1,15 +1,29 @@
const NON_ASCII_RUNS = /[\u0080-\uffff]+/g;
// The size the row stores report for a payload. Counting avoids the JS Buffer polyfill, which
// materialises the whole byte array just to measure it.
export function replicaPayloadBytes(payload: string): number {
let bytes = 0;
for (let index = 0; index < payload.length; index += 1) {
const code = payload.charCodeAt(index);
if (code < 0x80) bytes += 1;
else if (code < 0x800) bytes += 2;
else if (code >= 0xd800 && code <= 0xdbff) {
bytes += 4;
index += 1;
} else bytes += 3;
// Payloads are JSON that is almost entirely ASCII, one byte per character. The regex engine
// finds the rest far faster than a character loop walks a megabyte of directory rows on Hermes.
let bytes = payload.length;
for (const run of payload.match(NON_ASCII_RUNS) ?? []) {
for (let index = 0; index < run.length; index += 1) {
const code = run.charCodeAt(index);
if (code < 0x800) bytes += 1;
else if (isHighSurrogate(code) && isLowSurrogate(run.charCodeAt(index + 1))) {
// Two code units become four bytes.
bytes += 2;
index += 1;
} else bytes += 2;
}
}
return bytes;
}
function isHighSurrogate(code: number): boolean {
return code >= 0xd800 && code <= 0xdbff;
}
function isLowSurrogate(code: number): boolean {
return code >= 0xdc00 && code <= 0xdfff;
}
@@ -95,20 +95,36 @@ function SheetTabSheet({ sheet, isTop, onClose }: SheetTabSheetProps) {
};
}, []);
// Every close path (drag, backdrop, Close, Back) slides the sheet down first; `onChange(-1)` then
// runs the one guarded close. The sheet keeps its content through the close, so a declined
// Every close path (drag, backdrop, Close, Back) slides the sheet down first; the owner then runs
// the one guarded close. The sheet keeps its content through the close, so a declined
// unsaved-changes prompt only has to bring it back up.
const close = useCallback(() => sheetRef.current?.close(), []);
//
// Both signals feed that one attempt. `onChange(-1)` covers the ordinary case; `onClosed` covers
// a close whose end index Gorhom's bookkeeping already held, which it therefore never reports as
// a change (an interrupted mount animation leaves it at -1).
const closeRequested = useRef(false);
const requestClose = useCallback(() => {
if (unmounted.current || closeRequested.current) return;
closeRequested.current = true;
void onClose(tab.tabId).then((stillOpen) => {
if (stillOpen) {
closeRequested.current = false;
sheetRef.current?.snapToIndex(0);
}
return stillOpen;
});
}, [onClose, tab.tabId]);
const handleChange = useCallback(
(index: number) => {
if (index !== -1 || unmounted.current) return;
void onClose(tab.tabId).then((stillOpen) => {
if (stillOpen) sheetRef.current?.snapToIndex(0);
return stillOpen;
});
if (index !== -1) {
closeRequested.current = false;
return;
}
requestClose();
},
[onClose, tab.tabId],
[requestClose],
);
const close = useCallback(() => sheetRef.current?.close(), []);
// Hidden workspaces stay mounted in the deck and under Settings; only the visible one owns Back.
const ownsBackPress = isTop && isWorkspaceFocused && isScreenFocused;
useEffect(() => {
@@ -133,6 +149,7 @@ function SheetTabSheet({ sheet, isTop, onClose }: SheetTabSheetProps) {
handleComponent={SheetHandle}
backdropOpacity={0.45}
onChange={handleChange}
onClosed={requestClose}
accessible={false}
>
<SheetPane sheet={sheet} onClose={close} isTop={isTop} />
@@ -3298,7 +3298,11 @@ function WorkspaceScreenContent({
) : null}
{workspaceDirectory ? (
<>
<WorkspaceActions serverId={normalizedServerId} cwd={workspaceDirectory} />
<WorkspaceActions
serverId={normalizedServerId}
workspaceId={normalizedWorkspaceId}
cwd={workspaceDirectory}
/>
{workspaceActionsInBar ? null : explorerControls.headerAction}
</>
) : null}
@@ -432,6 +432,75 @@ describe("createArchiveFinishedSubagents", () => {
});
});
describe("closed managed subagents", () => {
it("counts a closed child as finished", () => {
const archive = createArchiveFinishedSubagents([paseo("closed-child", "closed")], {
parentAgentId: "parent",
getManagedSubagent: () => undefined,
archiveManagedSubagent: async () => undefined,
dismissProviderSubagents: () => undefined,
});
expect(archive.getState().eligibleCount).toBe(1);
});
it("archives a closed child instead of skipping it", async () => {
const current = new Map([
["closed-child", managed("closed-child", "closed")],
["idle-child", managed("idle-child")],
]);
const archived: string[] = [];
const archive = createArchiveFinishedSubagents(
[paseo("closed-child", "closed"), paseo("idle-child")],
{
parentAgentId: "parent",
getManagedSubagent: ({ agentId }) => current.get(agentId),
archiveManagedSubagent: async ({ agentId }) => {
archived.push(agentId);
},
dismissProviderSubagents: () => undefined,
},
);
await expect(archive.archiveFinished()).resolves.toEqual({
archivedPaseoIds: ["closed-child", "idle-child"],
dismissedProviderIds: [],
skippedPaseoIds: [],
failures: [],
});
expect(archived).toEqual(["closed-child", "idle-child"]);
});
it("still skips a closed child that was resumed and is running by archive time", async () => {
const current = new Map([["closed-child", managed("closed-child", "running")]]);
const archive = createArchiveFinishedSubagents([paseo("closed-child", "closed")], {
parentAgentId: "parent",
getManagedSubagent: ({ agentId }) => current.get(agentId),
archiveManagedSubagent: async () => undefined,
dismissProviderSubagents: () => undefined,
});
await expect(archive.archiveFinished()).resolves.toEqual({
archivedPaseoIds: [],
dismissedProviderIds: [],
skippedPaseoIds: ["closed-child"],
failures: [],
});
});
it("still skips a closed child that has live background work", async () => {
const active = { ...paseo("closed-child", "closed"), backgroundWork: { count: 1 } };
const archive = createArchiveFinishedSubagents([active], {
parentAgentId: "parent",
getManagedSubagent: () => undefined,
archiveManagedSubagent: async () => undefined,
dismissProviderSubagents: () => undefined,
});
expect(archive.getState().eligibleCount).toBe(0);
});
});
it("excludes live background work and rechecks it before each archive", async () => {
const first = deferred<void>();
const active = { ...paseo("active"), backgroundWork: { count: 1 } };
@@ -38,11 +38,15 @@ export interface ArchiveFinishedSubagents {
archiveFinished(): Promise<ArchiveFinishedOutcome>;
}
// A closed agent has no live runtime (finished, or released by idle cleanup), so it is
// finished for archiving purposes just like idle and error.
function isArchivableManagedStatus(status: ManagedSubagentSnapshot["status"]): boolean {
return status === "idle" || status === "error" || status === "closed";
}
export function isFinishedSubagent(row: SubagentRow): boolean {
if (row.kind === "paseo")
return (
(row.status === "idle" || row.status === "error") && (row.backgroundWork?.count ?? 0) === 0
);
return isArchivableManagedStatus(row.status) && (row.backgroundWork?.count ?? 0) === 0;
return row.status === "completed" || row.status === "failed" || row.status === "canceled";
}
@@ -55,7 +59,7 @@ function canArchiveManagedSubagent(
!agent.archivedAt &&
agent.parentAgentId === parentAgentId &&
(agent.backgroundWork?.count ?? 0) === 0 &&
(agent.status === "idle" || agent.status === "error"),
isArchivableManagedStatus(agent.status),
);
}
@@ -2495,7 +2495,63 @@ describe("processTimelineResponse", () => {
.map((item) => ({ id: item.id, messageId: item.messageId })),
).toEqual([
{ id: "local-prompt", messageId: undefined },
{ id: "remote-prompt", messageId: "remote-prompt" },
{ id: "remote-client-prompt", messageId: "remote-prompt" },
]);
});
it("assigns unique row ids when batched user messages share a provider messageId", () => {
const sharedProviderMessageId = "9ffc3d6e-f0ff-4005-8675-e76e9c5eb5a8";
const result = processTimelineResponse({
...baseTimelineInput,
isInitializing: true,
hasActiveInitDeferred: true,
initRequestDirection: "tail",
payload: {
...baseTimelineInput.payload,
direction: "tail",
epoch: "epoch-1",
startCursor: { seq: 1 },
endCursor: { seq: 2 },
entries: [
{
...makeTimelineEntry(1, "first queued prompt", "user_message"),
item: {
type: "user_message",
text: "first queued prompt",
messageId: sharedProviderMessageId,
clientMessageId: "client-queued-1",
},
},
{
...makeTimelineEntry(2, "second direct prompt", "user_message"),
item: {
type: "user_message",
text: "second direct prompt",
messageId: sharedProviderMessageId,
clientMessageId: "client-direct-2",
},
},
],
},
});
expect(
result.tail.map((item) =>
item.kind === "user_message"
? { id: item.id, clientMessageId: item.clientMessageId, messageId: item.messageId }
: null,
),
).toEqual([
{
id: "client-queued-1",
clientMessageId: "client-queued-1",
messageId: sharedProviderMessageId,
},
{
id: "client-direct-2",
clientMessageId: "client-direct-2",
messageId: sharedProviderMessageId,
},
]);
});
+98
View File
@@ -329,6 +329,104 @@ describe("user message identity", () => {
},
]);
});
it("assigns distinct row ids to batched user messages that share a provider messageId", () => {
const sharedProviderMessageId = "9ffc3d6e-f0ff-4005-8675-e76e9c5eb5a8";
const firstTimestamp = new Date("2026-11-29T13:00:00.000Z");
const secondTimestamp = new Date("2026-11-29T13:00:01.000Z");
const hydrated = hydrateStreamState(
[
{
event: {
type: "timeline",
provider: "claude",
item: {
type: "user_message",
text: "first queued prompt",
messageId: sharedProviderMessageId,
clientMessageId: "client-queued-1",
},
},
timestamp: firstTimestamp,
timelineCursor: { epoch: "epoch-1", seq: 1 },
},
{
event: {
type: "timeline",
provider: "claude",
item: {
type: "user_message",
text: "second direct prompt",
messageId: sharedProviderMessageId,
clientMessageId: "client-direct-2",
},
},
timestamp: secondTimestamp,
timelineCursor: { epoch: "epoch-1", seq: 2 },
},
],
{ source: "canonical" },
);
expect(hydrated).toHaveLength(2);
expect(hydrated.map((item) => item.id)).toEqual(["client-queued-1", "client-direct-2"]);
expect(hydrated).toMatchObject([
{
kind: "user_message",
id: "client-queued-1",
clientMessageId: "client-queued-1",
messageId: sharedProviderMessageId,
text: "first queued prompt",
},
{
kind: "user_message",
id: "client-direct-2",
clientMessageId: "client-direct-2",
messageId: sharedProviderMessageId,
text: "second direct prompt",
},
]);
const afterFirstLive = applyStreamEvent({
tail: [],
head: [],
event: {
type: "timeline",
provider: "claude",
item: {
type: "user_message",
text: "first queued prompt",
messageId: sharedProviderMessageId,
clientMessageId: "client-queued-1",
},
},
timestamp: firstTimestamp,
timelineCursor: { epoch: "epoch-1", seq: 1 },
});
const afterSecondLive = applyStreamEvent({
tail: afterFirstLive.tail,
head: afterFirstLive.head,
event: {
type: "timeline",
provider: "claude",
item: {
type: "user_message",
text: "second direct prompt",
messageId: sharedProviderMessageId,
clientMessageId: "client-direct-2",
},
},
timestamp: secondTimestamp,
timelineCursor: { epoch: "epoch-1", seq: 2 },
});
expect(afterSecondLive.tail).toHaveLength(2);
expect(afterSecondLive.tail.map((item) => item.id)).toEqual([
"client-queued-1",
"client-direct-2",
]);
});
});
function assistantTimeline(
+4 -2
View File
@@ -969,7 +969,7 @@ function appendUserMessage(
const chunkSeed = chunk.trim() || chunk || images?.[0]?.id || "image";
const nextItem = createUserMessage({
id: messageId ?? createUniqueTimelineId(state, "user", chunkSeed, timestamp),
id: clientMessageId || messageId || createUniqueTimelineId(state, "user", chunkSeed, timestamp),
clientMessageId,
messageId,
timelineCursor,
@@ -1967,7 +1967,9 @@ function buildCanonicalUserMessage(params: {
const fallbackKey = normalized.chunk.trim() || images?.[0]?.id || "image";
const canonical = createUserMessage({
id:
item.messageId ?? createUniqueTimelineId([...tail, ...head], "user", fallbackKey, timestamp),
item.clientMessageId ||
item.messageId ||
createUniqueTimelineId([...tail, ...head], "user", fallbackKey, timestamp),
messageId: item.messageId,
clientMessageId: item.clientMessageId,
turnId,
+14
View File
@@ -0,0 +1,14 @@
// `String.prototype.localeCompare` builds a collator on every call. On Hermes that construction
// dominates a sort over a few hundred names, so comparisons that run in bulk share one collator.
const textCollator = new Intl.Collator();
const nameCollator = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" });
/** The order of `left.localeCompare(right)`. */
export function compareText(left: string, right: string): number {
return textCollator.compare(left, right);
}
/** Display-name order: ignores case and accents, and sorts embedded numbers by value. */
export function compareNames(left: string, right: string): number {
return nameCollator.compare(left, right);
}
+4 -4
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/cli",
"version": "0.18.1",
"version": "0.18.2",
"description": "Paseo CLI - control your AI coding agents from the command line",
"license": "Apache-2.0",
"bin": {
@@ -29,9 +29,9 @@
},
"dependencies": {
"@clack/prompts": "^1.0.0",
"@getpaseo/client": "0.18.1",
"@getpaseo/protocol": "0.18.1",
"@getpaseo/server": "0.18.1",
"@getpaseo/client": "0.18.2",
"@getpaseo/protocol": "0.18.2",
"@getpaseo/server": "0.18.2",
"chalk": "^5.3.0",
"commander": "^12.0.0",
"mime-types": "^2.1.35",
@@ -30,6 +30,7 @@ describe("Hub commands", () => {
"projects",
"export",
"deploy",
"run",
"logout",
]);
assert.match(connect?.helpInformation() ?? "", /--api-key <secret>/u);
+15
View File
@@ -1,10 +1,25 @@
/** What Hub itself answered, when a request reached it and failed. */
export interface HubProblem {
status: number;
code?: string;
}
export class HubCommandError extends Error {
// Private so `--json` error output, which spreads the error, does not gain a field.
readonly #hubProblem: HubProblem | undefined;
constructor(
readonly code: string,
message: string,
readonly details?: string,
hubProblem?: HubProblem,
) {
super(message);
this.name = "HubCommandError";
this.#hubProblem = hubProblem;
}
get hubProblem(): HubProblem | undefined {
return this.#hubProblem;
}
}
@@ -6,6 +6,7 @@ import {
configurationResourcesSchema,
enrollmentTokenSchema,
installResponseSchema,
manualRunResponseSchema,
projectsResponseSchema,
triggersResponseSchema,
triggerInstallationResponseSchema,
@@ -15,6 +16,7 @@ import {
type CliAuthorizationPoll,
type HubInstallResult,
type HubConfigurationResources,
type HubManualRun,
type HubProject,
type HubTrigger,
type HubTriggerInstallationResult,
@@ -28,6 +30,7 @@ export type {
CliAuthorizationPoll,
HubInstallResult,
HubConfigurationResources,
HubManualRun,
HubProject,
HubTrigger,
HubTriggerInstallationResult,
@@ -42,6 +45,15 @@ interface HubConfigurationInput {
files: readonly HubBundleFile[];
}
export interface HubManualRunRequest {
projectSlug: string;
trigger: string;
actor: string;
deliveryKey: string;
/** Hub reads inputs only from a string: leading `name=value` tokens, then the prompt. */
input: string;
}
export class HubHttpClient {
startCliAuthorization(origin: string): Promise<CliAuthorization> {
return requestHub({
@@ -100,11 +112,28 @@ export class HubHttpClient {
apiKey,
successStatus: 200,
schema: triggersResponseSchema,
failureMessage: "Hub trigger export failed",
failureMessage: "Hub trigger listing failed",
});
return response.triggers;
}
dispatchManualRun(
origin: string,
apiKey: string,
request: HubManualRunRequest,
): Promise<HubManualRun> {
return requestHub({
origin,
path: "/api/v1/manual-runs",
method: "POST",
apiKey,
body: request,
successStatus: 200,
schema: manualRunResponseSchema,
failureMessage: "Hub manual run failed",
});
}
validateTrigger(
origin: string,
apiKey: string,
@@ -62,6 +62,16 @@ export const triggerInstallationResponseSchema = z
})
.strict();
// Not strict: by the time this arrives the run exists. Rejecting a field a newer Hub adds
// would report a failure and invite a second run.
export const manualRunResponseSchema = z.object({
deliveryKey: z.string(),
providerEventReceiptId: z.string().min(1),
triggerRunId: z.string().min(1),
configuredTriggerName: z.string(),
workflowStatus: z.string().min(1),
});
export const configurationResourcesSchema = z
.object({
daemons: z.array(z.object({ id: z.string().uuid(), slug: z.string().min(1) }).strict()),
@@ -107,5 +117,6 @@ export type HubTrigger = z.infer<typeof triggerSchema>;
export type HubTriggerValidationResult = z.infer<typeof triggerValidationResponseSchema>;
export type HubTriggerInstallationResult = z.infer<typeof triggerInstallationResponseSchema>;
export type HubConfigurationResources = z.infer<typeof configurationResourcesSchema>;
export type HubManualRun = z.infer<typeof manualRunResponseSchema>;
export type HubInstallResult = z.infer<typeof installResponseSchema>;
export type HubValidationResult = z.infer<typeof validationResponseSchema>;
@@ -11,6 +11,7 @@ const problemSchema = z.object({
type: z.string().optional(),
title: z.string().optional(),
status: z.number().int().optional(),
code: z.string().optional(),
detail: z.string().optional(),
instance: z.string().optional(),
errors: z
@@ -29,6 +30,8 @@ export async function hubRequestFailure(
return new HubCommandError(
"HUB_REQUEST_FAILED",
`${failureMessage} with HTTP ${response.status}.`,
undefined,
{ status: response.status },
);
}
let body: unknown;
@@ -38,6 +41,8 @@ export async function hubRequestFailure(
return new HubCommandError(
"HUB_INVALID_RESPONSE",
`Hub returned malformed problem details for HTTP ${response.status}.`,
undefined,
{ status: response.status },
);
}
const parsed = problemSchema.safeParse(body);
@@ -48,6 +53,8 @@ export async function hubRequestFailure(
return new HubCommandError(
"HUB_INVALID_RESPONSE",
`Hub returned nonconforming problem details for HTTP ${response.status}.`,
undefined,
{ status: response.status },
);
}
const title = parsed.data.title ?? `${failureMessage} with HTTP ${response.status}`;
@@ -63,6 +70,7 @@ export async function hubRequestFailure(
code,
redactSecret(message, apiKey),
details === undefined ? undefined : redactSecret(details, apiKey),
{ status: response.status, code: parsed.data.code },
);
}
+10
View File
@@ -21,6 +21,7 @@ import { hubStatusResult } from "./status-output.js";
import { addHubResolutionHelp } from "./help.js";
import { addHubInitCommand, continueHubGuidedSetup } from "./init.js";
import { addHubPermissionsCommand } from "./permissions.js";
import { addHubRunCommand, terminalRunPrompts } from "./run/index.js";
interface HubCommandEnvironment {
env: Readonly<Record<string, string | undefined>>;
@@ -109,6 +110,15 @@ export function createHubCommand(overrides: Partial<HubCommandEnvironment> = {})
reporter: environment.reporter,
cwd: environment.cwd,
});
addHubRunCommand(hub, {
env: environment.env,
credentials: environment.credentials,
hub: environment.hub,
reporter: environment.reporter,
cwd: environment.cwd,
isInteractive: environment.isInteractive,
prompts: terminalRunPrompts,
});
addHubLogoutCommand(hub, {
credentials: environment.credentials,
daemon: environment.daemon,
@@ -0,0 +1,750 @@
import { strict as assert } from "node:assert";
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { createServer } from "node:http";
import type { AddressInfo } from "node:net";
import { tmpdir } from "node:os";
import path from "node:path";
import { afterEach, describe, it } from "vitest";
import { render } from "../../../output/render.js";
import type { HubCredentialStore, StoredHubCredential } from "../credentials.js";
import { HubCommandError } from "../error.js";
import { HubHttpClient } from "../hub-client/index.js";
import { runHubRun, type HubRunOptions, type HubRunPrompts } from "./index.js";
const servers: Array<ReturnType<typeof createServer>> = [];
const directories: string[] = [];
afterEach(async () => {
await Promise.all(
servers.splice(0).map(
(server) =>
new Promise<void>((resolve) => {
server.closeAllConnections();
server.close(() => resolve());
}),
),
);
await Promise.all(directories.splice(0).map((directory) => rm(directory, { recursive: true })));
});
const deployTrigger = trigger(
"deploy",
`name: deploy
on:
manual.run: {}
inputs:
environment:
type: string
required: true
choices: [staging, production]
replicas:
type: number
default: 1
dry_run:
type: boolean
run:
prompt: Deploy.
`,
);
describe("Hub manual run", () => {
it("starts a trigger by name with the stored login and nothing else to type", async () => {
const hub = await startHub();
const cli = harness({ login: { origin: hub.origin, credential: "stored-secret" } });
const result = await cli.run("deploy", undefined);
assert.equal(hub.requests.length, 1);
const [request] = hub.requests;
assert.equal(request?.route, "POST /api/v1/manual-runs");
assert.equal(request?.authorization, "Bearer stored-secret");
const { deliveryKey, ...body } = (request?.body ?? {}) as Record<string, unknown>;
assert.match(String(deliveryKey), /^[0-9a-f-]{36}$/u);
assert.deepEqual(body, {
projectSlug: "default",
trigger: "deploy",
actor: "paseo-cli",
input: "",
});
assert.deepEqual(result.data, { ...dispatched(String(deliveryKey)), origin: hub.origin });
assert.deepEqual(cli.progress, [`Running deploy on ${hub.origin}`]);
});
it("renders a calm table, the run ID alone, and Hub's fields as JSON and YAML", async () => {
const hub = await startHub();
const cli = harness({ login: { origin: hub.origin, credential: "stored-secret" } });
const result = await cli.run("deploy", undefined, { deliveryKey: "build-42" });
const table = render(result, { format: "table", noColor: true });
assert.match(table, /^TRIGGER\s+RUN ID\s+STATUS\s+HUB/u);
assert.match(table, new RegExp(`deploy\\s+${runId}\\s+running\\s+${hub.origin}`, "u"));
assert.equal(render(result, { quiet: true }), runId);
assert.deepEqual(JSON.parse(render(result, { format: "json" })), {
...dispatched("build-42"),
origin: hub.origin,
});
assert.match(render(result, { format: "yaml" }), new RegExp(`triggerRunId: ${runId}`, "u"));
});
it("sends inputs as Hub's leading name=value tokens, followed by the prompt", async () => {
const hub = await startHub({ triggers: [deployTrigger] });
const cli = harness({ login: { origin: hub.origin, credential: "stored-secret" } });
await cli.run("deploy", "ship the hotfix", {
input: ["environment=staging", "replicas=3"],
actor: "alice",
deliveryKey: "build-42",
});
assert.deepEqual(hub.dispatches(), [
{
projectSlug: "default",
trigger: "deploy",
actor: "alice",
deliveryKey: "build-42",
input: "environment=staging replicas=3 ship the hotfix",
},
]);
});
it("reads the prompt from a file and takes explicit Hub authority and project", async () => {
const hub = await startHub();
const cli = harness({
env: { PASEO_HUB_URL: hub.origin, PASEO_HUB_API_KEY: "env-secret" },
login: { origin: "https://other.test", credential: "stored-secret" },
});
const directory = await mkdtemp(path.join(tmpdir(), "paseo-hub-run-"));
directories.push(directory);
await writeFile(path.join(directory, "prompt.md"), "# Fix\n\nthe sync\n");
cli.cwd = directory;
await cli.run("deploy", undefined, {
promptFile: "prompt.md",
project: "payments",
apiKey: "flag-secret",
});
assert.equal(hub.requests[0]?.authorization, "Bearer flag-secret");
assert.deepEqual(
hub.dispatches().map(({ projectSlug, input }) => ({ projectSlug, input })),
[{ projectSlug: "payments", input: "# Fix\n\nthe sync" }],
);
});
it("refuses two prompt sources and an unreadable prompt file before contacting Hub", async () => {
const hub = await startHub();
const cli = harness({ login: { origin: hub.origin, credential: "stored-secret" } });
await rejectsWith(
cli.run("deploy", "text", { promptFile: "prompt.md" }),
"HUB_RUN_PROMPT_CONFLICT",
/prompt argument or --prompt-file/u,
);
await rejectsWith(
cli.run("deploy", undefined, { promptFile: "/nonexistent/prompt.md" }),
"HUB_RUN_PROMPT_UNREADABLE",
/\/nonexistent\/prompt\.md/u,
);
assert.deepEqual(hub.requests, []);
});
it.each([
["environment", /name=value/u],
["Environment=staging", /lowercase/u],
["environment=eu west", /cannot contain spaces/u],
])("refuses --input %j before contacting Hub", async (input, message) => {
const hub = await startHub();
const cli = harness({ login: { origin: hub.origin, credential: "stored-secret" } });
await rejectsWith(cli.run("deploy", undefined, { input: [input] }), "HUB_RUN_INPUT", message);
assert.deepEqual(hub.requests, []);
});
it("refuses an undeclared input, which Hub would silently read as prompt text", async () => {
const hub = await startHub({ triggers: [deployTrigger] });
const cli = harness({ login: { origin: hub.origin, credential: "stored-secret" } });
const error = await rejectsWith(
cli.run("deploy", undefined, { input: ["enviroment=production"] }),
"HUB_RUN_INPUT",
/Trigger "deploy" has no input "enviroment"/u,
);
assert.equal(
error.details,
[
'Inputs of "deploy":',
" -i environment=<staging|production> required",
" -i replicas=<number> default 1",
" -i dry_run=<true|false>",
].join("\n"),
);
assert.deepEqual(hub.dispatches(), []);
});
it("reads declared inputs from a preserved legacy multistep trigger", async () => {
const legacy = {
...trigger(
"release",
`name: release
legacy_multistep:
trigger:
name: release
on: manual.run
inputs:
channel:
type: string
required: false
`,
),
format: "legacy_multistep" as const,
};
const hub = await startHub({ triggers: [legacy] });
const cli = harness({ login: { origin: hub.origin, credential: "stored-secret" } });
await rejectsWith(
cli.run("release", undefined, { input: ["chanel=beta"] }),
"HUB_RUN_INPUT",
/no input "chanel"/u,
);
await cli.run("release", undefined, { input: ["channel=beta"] });
assert.deepEqual(
hub.dispatches().map(({ input }) => input),
["channel=beta"],
);
});
it("still runs with a dispatch-only API key and says the input names were not checked", async () => {
const hub = await startHub({
list: problem(403, "insufficient_scope", "Insufficient scope"),
});
const cli = harness({ env: { PASEO_HUB_URL: hub.origin, PASEO_HUB_API_KEY: "ci-secret" } });
await cli.run("deploy", undefined, { input: ["environment=staging"], json: true });
assert.deepEqual(
hub.dispatches().map(({ input }) => input),
["environment=staging"],
);
assert.deepEqual(cli.progress, [
"Input names were not checked: this credential cannot list triggers (configuration:validate).",
]);
});
it("does not run when the input names could not be checked because Hub failed", async () => {
const hub = await startHub({
list: problem(503, "infrastructure_unavailable", "Service unavailable"),
});
const cli = harness({ login: { origin: hub.origin, credential: "stored-secret" } });
await assert.rejects(cli.run("deploy", undefined, { input: ["environment=staging"] }));
assert.deepEqual(hub.dispatches(), []);
});
it.each([
["nope", 'No manual trigger "nope" on', "Manual triggers: deploy"],
["paused", 'Trigger "paused" is disabled on', "Enable it in Hub, then run it again."],
[
"on-push",
'Trigger "on-push" has no manual.run event',
"Add `manual.run: {}` under `on` and deploy it.",
],
])("explains why %s cannot run", async (name, message, details) => {
const hub = await startHub({
triggers: [
deployTrigger,
{ ...trigger("paused", "name: paused\non:\n manual.run: {}\n"), enabled: false },
trigger("on-push", "name: on-push\non:\n github.push: {}\n"),
],
run: problem(404, "trigger_not_found", "Trigger not found"),
});
const cli = harness({ login: { origin: hub.origin, credential: "stored-secret" } });
const error = await rejectsWith(
cli.run(name, undefined),
"HUB_TRIGGER_NOT_FOUND",
new RegExp(message, "u"),
);
assert.equal(error.details, details);
});
it("treats Hub's missing default project as an unknown trigger", async () => {
const hub = await startHub({
triggers: [deployTrigger],
run: problem(404, "project_not_found", "Project not found"),
});
const cli = harness({ login: { origin: hub.origin, credential: "stored-secret" } });
await rejectsWith(
cli.run("nope", undefined),
"HUB_TRIGGER_NOT_FOUND",
/No manual trigger "nope"/u,
);
await rejectsWith(
cli.run("nope", undefined, { project: "payments" }),
"HUB_NOT_FOUND",
/Project not found/u,
);
});
it("prints Hub's input validation verbatim, with the declared inputs", async () => {
const hub = await startHub({
triggers: [deployTrigger],
run: problem(400, "invalid_input", "Invalid trigger input", [
{ path: ["input"], message: "required input environment is missing" },
]),
});
const cli = harness({ login: { origin: hub.origin, credential: "stored-secret" } });
const error = await rejectsWith(
cli.run("deploy", undefined),
"HUB_INVALID_INPUT",
/^Invalid trigger input: required input environment is missing$/u,
);
assert.match(error.details ?? "", /^Inputs of "deploy":\n {2}-i environment=/u);
});
it.each([
[
problem(403, "actor_forbidden", "Actor forbidden"),
"HUB_REQUEST_FAILED",
/--actor <name>.*filters\.from_users/u,
],
[
problem(401, "unauthorized", "Authentication required"),
"HUB_REQUEST_FAILED",
/paseo hub login http/u,
],
[
problem(409, "dispatch_conflict", "Run not dispatched"),
"HUB_REQUEST_FAILED",
/--delivery-key build-42/u,
],
[
problem(503, "infrastructure_unavailable", "Service unavailable"),
"HUB_REQUEST_FAILED",
/--delivery-key build-42/u,
],
[
{ status: 200, body: { unexpected: true } },
"HUB_INVALID_RESPONSE",
/--delivery-key build-42/u,
],
])("says what to do after Hub answers %#", async (response, code, details) => {
const hub = await startHub({ run: response });
const cli = harness({ login: { origin: hub.origin, credential: "stored-secret" } });
await assert.rejects(cli.run("deploy", undefined, { deliveryKey: "build-42" }), (error) => {
assert.ok(error instanceof HubCommandError);
assert.equal(error.code, code);
assert.match(error.details ?? "", details);
assert.equal(`${error.message}${error.details ?? ""}`.includes("stored-secret"), false);
return true;
});
});
it("offers a safe retry when Hub cannot be reached", async () => {
const cli = harness({
env: { PASEO_HUB_URL: "http://127.0.0.1:1", PASEO_HUB_API_KEY: "secret" },
});
const error = await rejectsWith(
cli.run("deploy", undefined, { deliveryKey: "build-42" }),
"HUB_NETWORK_ERROR",
/Could not reach Paseo Hub at http:\/\/127\.0\.0\.1:1/u,
);
assert.match(error.details ?? "", /--delivery-key build-42/u);
});
it("accepts a response with fields this CLI does not know yet", async () => {
const hub = await startHub({
run: { status: 200, body: { ...dispatched("build-42"), activityUrl: "https://hub.test/a" } },
});
const cli = harness({ login: { origin: hub.origin, credential: "stored-secret" } });
const result = await cli.run("deploy", undefined, { deliveryKey: "build-42" });
assert.equal(result.data.triggerRunId, runId);
});
it("points at hub login when there is no credential", async () => {
const cli = harness({ env: { PASEO_HUB_URL: "https://hub.test" } });
await rejectsWith(
cli.run("deploy", undefined),
"HUB_API_KEY_REQUIRED",
/paseo hub login https:\/\/hub\.test/u,
);
});
it("fails immediately without a trigger name when it cannot ask", async () => {
const hub = await startHub({ triggers: [deployTrigger] });
const login = { origin: hub.origin, credential: "stored-secret" };
for (const cli of [
harness({ login }),
harness({ login, interactive: true, options: { json: true } }),
harness({ login, interactive: true, options: { quiet: true } }),
harness({ login, interactive: true, options: { format: "yaml" } }),
]) {
await rejectsWith(
cli.run(undefined, undefined),
"HUB_TRIGGER_REQUIRED",
/paseo hub run <trigger>/u,
);
}
assert.deepEqual(hub.requests, []);
});
it("in a terminal, offers the manual triggers and asks for missing required inputs", async () => {
const hub = await startHub({
triggers: [
deployTrigger,
trigger(
"audit",
"name: audit\non:\n manual.run: {}\ninputs:\n repo: {type: string, required: true}\n",
),
trigger("on-push", "name: on-push\non:\n github.push: {}\n"),
{ ...trigger("paused", "name: paused\non:\n manual.run: {}\n"), enabled: false },
],
});
const cli = harness({
login: { origin: hub.origin, credential: "stored-secret" },
interactive: true,
answers: ["deploy", "production"],
});
await cli.run(undefined, undefined);
assert.deepEqual(cli.asked, [
{ message: "Which trigger?", options: ["audit", "deploy"] },
{ message: "environment", options: ["staging", "production"] },
]);
assert.deepEqual(
hub.dispatches().map(({ trigger: name, input }) => ({ name, input })),
[{ name: "deploy", input: "environment=production" }],
);
});
it("asks for typed free text and rejects values Hub could not read", async () => {
const hub = await startHub({
triggers: [
trigger(
"scale",
"name: scale\non:\n manual.run: {}\ninputs:\n count: {type: number, required: true}\n",
),
],
});
const cli = harness({
login: { origin: hub.origin, credential: "stored-secret" },
interactive: true,
answers: ["4"],
});
await cli.run("scale", undefined);
assert.equal(cli.validators[0]?.("four"), "Enter a number");
assert.equal(cli.validators[0]?.(""), "Required");
assert.equal(cli.validators[0]?.("4 5"), "No spaces");
assert.equal(cli.validators[0]?.("4"), undefined);
assert.deepEqual(
hub.dispatches().map(({ input }) => input),
["count=4"],
);
});
it("does not ask again for an input already typed at the start of the prompt", async () => {
const hub = await startHub({ triggers: [deployTrigger] });
const cli = harness({
login: { origin: hub.origin, credential: "stored-secret" },
interactive: true,
});
await cli.run("deploy", "environment=staging ship it");
assert.deepEqual(cli.asked, []);
assert.deepEqual(
hub.dispatches().map(({ input }) => input),
["environment=staging ship it"],
);
});
it.each([
["a legacy project trigger", "legacy-deploy", [deployTrigger]],
[
"a trigger document it cannot read",
"odd",
[deployTrigger, trigger("odd", "name: odd\non: nonsense\n")],
],
])("says the input names were not checked for %s", async (_case, name, triggers) => {
const hub = await startHub({ triggers });
const cli = harness({ login: { origin: hub.origin, credential: "stored-secret" } });
await cli.run(name, undefined, { input: ["environment=staging"] });
assert.equal(
cli.progress.at(-1),
`Input names were not checked: no readable organization trigger "${name}".`,
);
});
it("is not blocked by another trigger's unreadable document, and reads YAML merge keys", async () => {
const hub = await startHub({
triggers: [
trigger("odd", "name: odd\non: nonsense\n"),
trigger(
"merged",
"name: merged\non:\n manual.run: {}\ninputs:\n a: &text {type: string}\n b: {<<: *text}\n",
),
],
});
const cli = harness({ login: { origin: hub.origin, credential: "stored-secret" } });
await cli.run("merged", undefined, { input: ["b=two"] });
assert.deepEqual(
hub.dispatches().map(({ input }) => input),
["b=two"],
);
assert.deepEqual(cli.progress, [`Running merged on ${hub.origin}`]);
});
it("adds nothing to the error output when an unchecked run fails", async () => {
const hub = await startHub({
list: problem(403, "insufficient_scope", "Insufficient scope"),
run: problem(503, "infrastructure_unavailable", "Service unavailable"),
});
const cli = harness({ env: { PASEO_HUB_URL: hub.origin, PASEO_HUB_API_KEY: "ci-secret" } });
await assert.rejects(cli.run("deploy", undefined, { input: ["a=b"], json: true }));
assert.deepEqual(cli.progress, []);
});
it("points at hub login when the credential expired before the triggers were listed", async () => {
const hub = await startHub({ list: problem(401, "unauthorized", "Authentication required") });
const cli = harness({ login: { origin: hub.origin, credential: "stored-secret" } });
await assert.rejects(cli.run("deploy", undefined, { input: ["a=b"] }), (error) => {
assert.ok(error instanceof HubCommandError);
assert.match(error.details ?? "", /paseo hub login http/u);
return true;
});
assert.deepEqual(hub.dispatches(), []);
});
it.each([
problem(403, "actor_forbidden", "Actor forbidden"),
problem(400, "invalid_input", "Invalid trigger input"),
])("asks for a new delivery key to correct a rejected request: %#", async (response) => {
const hub = await startHub({ run: response });
const cli = harness({ login: { origin: hub.origin, credential: "stored-secret" } });
const details = async (options: HubRunOptions) => {
let caught: unknown;
await cli.run("deploy", undefined, options).catch((error: unknown) => {
caught = error;
});
assert.ok(caught instanceof HubCommandError);
return caught.details ?? "";
};
assert.match(await details({ deliveryKey: "build-42" }), /new --delivery-key/u);
assert.doesNotMatch(await details({}), /--delivery-key/u);
});
it("does not send a picked choice that Hub would cut at the space", async () => {
const hub = await startHub({
triggers: [
trigger(
"region",
"name: region\non:\n manual.run: {}\ninputs:\n region: {type: string, required: true, choices: [us east]}\n",
),
],
});
const cli = harness({
login: { origin: hub.origin, credential: "stored-secret" },
interactive: true,
answers: ["us east"],
});
await rejectsWith(cli.run("region", undefined), "HUB_RUN_INPUT", /cannot contain spaces/u);
assert.deepEqual(hub.dispatches(), []);
});
it("starts nothing when the question is cancelled", async () => {
const hub = await startHub({ triggers: [deployTrigger] });
const cli = harness({
login: { origin: hub.origin, credential: "stored-secret" },
interactive: true,
answers: [null],
});
await rejectsWith(cli.run("deploy", undefined), "HUB_RUN_CANCELLED", /Nothing was started/u);
assert.deepEqual(hub.dispatches(), []);
});
});
const runId = "f83dc934-02a0-4849-8de7-699110be24ed";
function dispatched(deliveryKey: string) {
return {
deliveryKey,
providerEventReceiptId: "845e9d26-7977-45e1-bc69-d80a7b55a9cc",
triggerRunId: runId,
configuredTriggerName: "deploy",
workflowStatus: "running",
};
}
function trigger(name: string, yaml: string) {
return {
id: "a50e05af-4f20-4c8f-8dcc-58e5ea360663",
name,
enabled: true,
format: "single_run" as "single_run" | "legacy_multistep",
yaml,
};
}
interface FakeResponse {
status: number;
body: unknown;
}
function problem(
status: number,
code: string,
title: string,
issues?: Array<{ path: string[]; message: string }>,
): FakeResponse {
return {
status,
body: { title, status, code, detail: `${title}.`, ...(issues ? { issues } : {}) },
};
}
async function startHub(
input: {
triggers?: ReturnType<typeof trigger>[];
list?: FakeResponse;
run?: FakeResponse;
} = {},
) {
const requests: Array<{ route: string; authorization: string | undefined; body: unknown }> = [];
const server = createServer((request, response) => {
let body = "";
request.setEncoding("utf8");
request.on("data", (chunk: string) => {
body += chunk;
});
request.on("end", () => {
const route = `${request.method} ${request.url}`;
const parsed: unknown = body === "" ? undefined : JSON.parse(body);
requests.push({ route, authorization: request.headers.authorization, body: parsed });
const reply =
route === "GET /api/v1/triggers"
? (input.list ?? { status: 200, body: { triggers: input.triggers ?? [] } })
: (input.run ?? {
status: 200,
body: dispatched((parsed as { deliveryKey: string }).deliveryKey),
});
response.writeHead(reply.status, {
"content-type": reply.status >= 400 ? "application/problem+json" : "application/json",
});
response.end(JSON.stringify(reply.body));
});
});
servers.push(server);
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
const { port } = server.address() as AddressInfo;
return {
origin: `http://127.0.0.1:${port}`,
requests,
dispatches: () =>
requests
.filter(({ route }) => route === "POST /api/v1/manual-runs")
.map(({ body }) => body as Record<string, string>),
};
}
function harness(
input: {
env?: Record<string, string>;
login?: StoredHubCredential;
interactive?: boolean;
answers?: Array<string | null>;
options?: HubRunOptions;
} = {},
) {
const progress: string[] = [];
const asked: Array<{ message: string; options?: string[] }> = [];
const validators: Array<(value: string) => string | undefined> = [];
const answers = [...(input.answers ?? [])];
const prompts: HubRunPrompts = {
async select(question) {
asked.push({ message: question.message, options: question.options });
return answers.shift() ?? null;
},
async text(question) {
asked.push({ message: question.message });
validators.push(question.validate);
return answers.shift() ?? null;
},
};
const state = {
progress,
asked,
validators,
cwd: process.cwd(),
run(name: string | undefined, prompt: string | undefined, options: HubRunOptions = {}) {
return runHubRun(
name,
prompt,
{ ...input.options, ...options },
{
env: input.env ?? {},
credentials: memoryCredentials(input.login),
hub: new HubHttpClient(),
reporter: { progress: (message) => progress.push(message) },
cwd: () => state.cwd,
isInteractive: () => input.interactive ?? false,
prompts,
},
);
},
};
return state;
}
function memoryCredentials(login: StoredHubCredential | undefined): HubCredentialStore {
return {
active: () => login ?? null,
get: (origin) => (login?.origin === origin ? login : null),
save: () => assert.fail("a run never writes credentials"),
logoutActive: () => assert.fail("a run never writes credentials"),
};
}
async function rejectsWith(
operation: Promise<unknown>,
code: string,
message: RegExp,
): Promise<HubCommandError> {
let caught: unknown;
await operation.catch((error: unknown) => {
caught = error;
});
assert.ok(caught instanceof HubCommandError, `expected ${code}, got ${String(caught)}`);
assert.equal(caught.code, code);
assert.match(caught.message, message);
return caught;
}
+261
View File
@@ -0,0 +1,261 @@
import { randomUUID } from "node:crypto";
import { readFile } from "node:fs/promises";
import path from "node:path";
import type { Command } from "commander";
import {
isHumanOutput,
withOutput,
type CommandOptions,
type OutputSchema,
type SingleResult,
} from "../../../output/index.js";
import { addJsonOption, collectMultiple } from "../../../utils/command-options.js";
import { resolveHubCredential, resolveHubOrigin } from "../authority.js";
import type { HubCredentialStore } from "../credentials.js";
import { HubCommandError } from "../error.js";
import { addHubResolutionHelp } from "../help.js";
import type { HubHttpClient } from "../hub-client/index.js";
import { reportHubProgress, type HubReporter } from "../reporter.js";
import { availableTriggers, explainRunFailure, explainSignIn } from "./internal/failures.js";
import {
assertDeclared,
encodeInvocation,
missingInputs,
parseInputFlags,
type InputValue,
} from "./internal/inputs.js";
import { isRunnable, readManualTrigger, type ManualTrigger } from "./internal/manual-trigger.js";
import { askInputs, chooseTrigger, type HubRunPrompts } from "./internal/prompts.js";
export { terminalRunPrompts, type HubRunPrompts } from "./internal/prompts.js";
const DEFAULT_ACTOR = "paseo-cli";
interface HubRunResult {
origin: string;
triggerRunId: string;
configuredTriggerName: string;
workflowStatus: string;
deliveryKey: string;
providerEventReceiptId: string;
}
const schema: OutputSchema<HubRunResult> = {
idField: "triggerRunId",
columns: [
{ header: "TRIGGER", field: "configuredTriggerName" },
{ header: "RUN ID", field: "triggerRunId" },
{ header: "STATUS", field: "workflowStatus" },
{ header: "HUB", field: "origin" },
],
};
export type HubRunOptions = Pick<CommandOptions, "json" | "quiet" | "format"> & {
input?: string[];
promptFile?: string;
actor?: string;
deliveryKey?: string;
project?: string;
hub?: string;
apiKey?: string;
};
export interface HubRunDependencies {
env: Readonly<Record<string, string | undefined>>;
credentials: HubCredentialStore;
hub: Pick<HubHttpClient, "listTriggers" | "dispatchManualRun">;
reporter: HubReporter;
cwd(): string;
isInteractive(): boolean;
prompts: HubRunPrompts;
}
export async function runHubRun(
triggerArgument: string | undefined,
promptArgument: string | undefined,
options: HubRunOptions,
dependencies: HubRunDependencies,
): Promise<SingleResult<HubRunResult>> {
const flags = parseInputFlags(options.input ?? []);
const prompt = await readPrompt(promptArgument, options.promptFile, dependencies.cwd());
const canAsk = dependencies.isInteractive() && isHumanOutput(options);
if (triggerArgument === undefined && !canAsk) throw triggerRequired();
const resolution = {
options: { origin: options.hub, apiKey: options.apiKey },
env: dependencies.env,
credentials: dependencies.credentials,
};
const origin = resolveHubOrigin(resolution);
const credential = resolveHubCredential({ ...resolution, origin });
const triggers = organizationTriggers(dependencies.hub, origin, credential);
const name = triggerArgument ?? (await pickTrigger(triggers, origin, dependencies.prompts));
const { inputs, unchecked } =
flags.length > 0 || canAsk
? await completeInputs({ name, flags, prompt, canAsk, dependencies, triggers })
: { inputs: flags, unchecked: undefined };
reportHubProgress(dependencies.reporter, options, `Running ${name} on ${origin}`);
const deliveryKey = options.deliveryKey ?? randomUUID();
try {
const run = await dependencies.hub.dispatchManualRun(origin, credential, {
// Required by Hub, and ignored when the name belongs to an organization trigger.
projectSlug: options.project ?? "default",
trigger: name,
actor: options.actor ?? DEFAULT_ACTOR,
deliveryKey,
input: encodeInvocation(inputs, prompt),
});
// Said once Hub has accepted: a failed `--json` run keeps stderr as the error alone.
if (unchecked !== undefined) {
dependencies.reporter.progress(`Input names were not checked: ${unchecked}.`);
}
return { type: "single", data: { ...run, origin }, schema };
} catch (error) {
throw await explainRunFailure(error, {
trigger: name,
origin,
project: options.project,
deliveryKey,
keyFromCaller: options.deliveryKey !== undefined,
triggers,
});
}
}
export function addHubRunCommand(parent: Command, dependencies: HubRunDependencies): void {
addJsonOption(
addHubResolutionHelp(
parent
.command("run")
.description("Run a manual trigger")
.argument("[trigger]", "Trigger name. Omit in a terminal to pick one")
.argument("[prompt]", "Text the trigger receives as ${{ paseo.prompt }}")
.option(
"-i, --input <name=value>",
"Set a declared input (repeatable)",
collectMultiple,
[],
)
.option("--prompt-file <path>", "Read the prompt from a UTF-8 text file")
.option("--actor <name>", "Name checked against filters.from_users", DEFAULT_ACTOR)
.option("--delivery-key <key>", "Reuse on retry to avoid starting a second run")
.option("-p, --project <slug>", "Run a trigger from a legacy project bundle")
.option("--hub <origin>", "Paseo Hub origin")
.option("--api-key <secret>", "Organization API key")
// An unquoted prompt must fail instead of silently losing every word after the first.
.allowExcessArguments(false)
.addHelpText(
"after",
'\nExamples:\n paseo hub run triage\n paseo hub run deploy -i environment=staging "ship the hotfix"\n RUN_ID=$(paseo hub run triage --prompt-file report.md --quiet)\n',
),
),
).action(
withOutput(async (...args) => {
const trigger = args[0] as string | undefined;
const prompt = args[1] as string | undefined;
const options = args.at(-2) as HubRunOptions;
return runHubRun(trigger, prompt, options, dependencies);
}),
);
}
type OrganizationTriggers = () => Promise<readonly ManualTrigger[] | null>;
/** Listed at most once, and only when needed. `null`: the credential may only dispatch. */
function organizationTriggers(
hub: Pick<HubHttpClient, "listTriggers">,
origin: string,
credential: string,
): OrganizationTriggers {
let listed: Promise<readonly ManualTrigger[] | null> | undefined;
const list = async () => {
try {
const documents = await hub.listTriggers(origin, credential);
return documents.flatMap((document) => readManualTrigger(document) ?? []);
} catch (error) {
if (error instanceof HubCommandError && error.hubProblem?.status === 403) return null;
throw explainSignIn(error, origin);
}
};
return () => (listed ??= list());
}
async function pickTrigger(
triggers: OrganizationTriggers,
origin: string,
prompts: HubRunPrompts,
): Promise<string> {
const listed = await triggers();
if (listed === null) throw triggerRequired();
const names = listed
.filter(isRunnable)
.map(({ name }) => name)
.toSorted();
if (names.length === 0) {
throw new HubCommandError(
"HUB_TRIGGER_NOT_FOUND",
`Nothing to run on ${origin}.`,
availableTriggers(listed),
);
}
return chooseTrigger(prompts, names);
}
async function completeInputs(input: {
name: string;
flags: InputValue[];
prompt: string;
canAsk: boolean;
dependencies: HubRunDependencies;
triggers: OrganizationTriggers;
}): Promise<{ inputs: InputValue[]; unchecked?: string }> {
const { name, flags, prompt, canAsk, dependencies } = input;
const listed = await input.triggers();
const trigger = listed?.find((candidate) => candidate.name === name);
if (trigger === undefined) {
if (flags.length === 0) return { inputs: flags };
const unchecked =
listed === null
? "this credential cannot list triggers (configuration:validate)"
: `no readable organization trigger "${name}"`;
return { inputs: flags, unchecked };
}
// A trigger that cannot run gets Hub's answer, not questions about its inputs.
if (!isRunnable(trigger)) return { inputs: flags };
assertDeclared(trigger, flags);
if (!canAsk) return { inputs: flags };
const missing = missingInputs(trigger, flags, prompt);
return { inputs: [...flags, ...(await askInputs(dependencies.prompts, missing))] };
}
async function readPrompt(
argument: string | undefined,
file: string | undefined,
cwd: string,
): Promise<string> {
if (file === undefined) return argument?.trim() ?? "";
if (argument !== undefined) {
throw new HubCommandError(
"HUB_RUN_PROMPT_CONFLICT",
"Pass the prompt as a prompt argument or --prompt-file, not both.",
);
}
const filePath = path.resolve(cwd, file);
try {
return (await readFile(filePath, "utf8")).trim();
} catch {
throw new HubCommandError(
"HUB_RUN_PROMPT_UNREADABLE",
`Could not read the prompt file ${filePath}.`,
);
}
}
function triggerRequired(): HubCommandError {
return new HubCommandError(
"HUB_TRIGGER_REQUIRED",
"Name the trigger to run: paseo hub run <trigger>",
);
}
@@ -0,0 +1,133 @@
import { HubCommandError } from "../../error.js";
import { describeInputs } from "./inputs.js";
import { isRunnable, type ManualTrigger } from "./manual-trigger.js";
interface RunAttempt {
trigger: string;
origin: string;
project: string | undefined;
deliveryKey: string;
keyFromCaller: boolean;
/** The organization's triggers, or null when they cannot be listed. */
triggers(): Promise<readonly ManualTrigger[] | null>;
}
/** Turn a failed dispatch into what went wrong and what to do next. */
export async function explainRunFailure(error: unknown, attempt: RunAttempt): Promise<unknown> {
if (!(error instanceof HubCommandError)) return error;
const problem = error.hubProblem;
// Hub answers `project_not_found` for an unknown name when no `default` project exists.
if (
attempt.project === undefined &&
(problem?.code === "trigger_not_found" || problem?.code === "project_not_found")
) {
return explainMissingTrigger(error, attempt);
}
if (problem?.code === "invalid_input") {
return forCorrection(await explainInvalidInput(error, attempt), attempt);
}
if (problem?.code === "actor_forbidden") {
const advice = "Pass --actor <name> with a name listed in the trigger's filters.from_users.";
return forCorrection(advise(error, advice), attempt);
}
if (problem?.status === 401) return explainSignIn(error, attempt.origin);
// Hub may hold the request already: only the same delivery key makes a retry safe.
if (
problem === undefined ||
problem.status >= 500 ||
problem.code === "dispatch_conflict" ||
error.code === "HUB_INVALID_RESPONSE"
) {
return advise(
error,
`If Hub received the request, retry with --delivery-key ${attempt.deliveryKey} to avoid starting it twice.`,
);
}
return error;
}
export function explainSignIn(error: unknown, origin: string): unknown {
if (!(error instanceof HubCommandError) || error.hubProblem?.status !== 401) return error;
return advise(
error,
`Run \`paseo hub login ${origin}\`, or check --api-key and PASEO_HUB_API_KEY.`,
);
}
// Hub stores a request before rejecting it, and replays the stored one for the same key.
function forCorrection(error: HubCommandError, attempt: RunAttempt): HubCommandError {
if (!attempt.keyFromCaller) return error;
return advise(error, "Send the corrected request with a new --delivery-key.");
}
async function explainInvalidInput(
error: HubCommandError,
attempt: RunAttempt,
): Promise<HubCommandError> {
const trigger = (await listForHint(attempt))?.find(({ name }) => name === attempt.trigger);
const reasons = error.details?.replace(/^input: /gmu, "").replaceAll("\n", "; ");
return new HubCommandError(
"HUB_INVALID_INPUT",
reasons === undefined ? error.message : `${error.message}: ${reasons}`,
trigger === undefined ? undefined : describeInputs(trigger),
error.hubProblem,
);
}
async function explainMissingTrigger(
error: HubCommandError,
attempt: RunAttempt,
): Promise<HubCommandError> {
const triggers = await listForHint(attempt);
const found = triggers?.find(({ name }) => name === attempt.trigger);
const notFound = (message: string, details?: string) =>
new HubCommandError("HUB_TRIGGER_NOT_FOUND", message, details, error.hubProblem);
if (found === undefined) {
return notFound(
`No manual trigger "${attempt.trigger}" on ${attempt.origin}.`,
triggers === null ? undefined : availableTriggers(triggers),
);
}
if (!found.enabled) {
return notFound(
`Trigger "${found.name}" is disabled on ${attempt.origin}.`,
"Enable it in Hub, then run it again.",
);
}
if (!found.manual) {
return notFound(
`Trigger "${found.name}" has no manual.run event on ${attempt.origin}.`,
"Add `manual.run: {}` under `on` and deploy it.",
);
}
return error;
}
export function availableTriggers(triggers: readonly ManualTrigger[]): string {
const names = triggers
.filter(isRunnable)
.map(({ name }) => name)
.toSorted();
return names.length === 0
? "No manual triggers yet. Add `manual.run: {}` under `on` and deploy one."
: `Manual triggers: ${names.join(", ")}`;
}
// A hint is optional: failing to fetch it must not replace the error the person needs.
async function listForHint(attempt: RunAttempt): Promise<readonly ManualTrigger[] | null> {
try {
return await attempt.triggers();
} catch {
return null;
}
}
function advise(error: HubCommandError, advice: string): HubCommandError {
return new HubCommandError(
error.code,
error.message,
error.details === undefined ? advice : `${error.details}\n${advice}`,
error.hubProblem,
);
}
@@ -0,0 +1,103 @@
import { HubCommandError } from "../../error.js";
import type { DeclaredInput, ManualTrigger } from "./manual-trigger.js";
// Hub's manual dispatch takes one string: leading `name=value` tokens, then the prompt. A token
// it does not recognise ends the inputs and becomes prompt text, and the run starts with defaults.
// These checks stop an `-i` value Hub would misread without saying so; Hub validates the rest.
// Pairs at the start of the prompt are Hub's own syntax and pass through.
const INPUT_NAME = /^[a-z][a-z0-9_-]*$/u;
const LEADING_TOKEN = /^([a-z][a-z0-9_-]*)=[^\s]*(?:\s+|$)/u;
export interface InputValue {
name: string;
value: string;
}
export function parseInputFlags(flags: readonly string[]): InputValue[] {
return flags.map((flag) => {
const separator = flag.indexOf("=");
if (separator < 1) throw invalidInput(`--input expects name=value, got "${flag}".`);
const name = flag.slice(0, separator);
const value = flag.slice(separator + 1);
if (!INPUT_NAME.test(name)) {
throw invalidInput(
`Input names are lowercase letters, digits, "-" and "_", starting with a letter. Got "${name}".`,
);
}
return sendableInput(name, value);
});
}
export function sendableInput(name: string, value: string): InputValue {
if (/\s/u.test(value)) {
throw invalidInput(
`Input "${name}" cannot contain spaces. Hub separates inputs by spaces; put free text in the prompt.`,
);
}
return { name, value };
}
export function encodeInvocation(inputs: readonly InputValue[], prompt: string): string {
return [...inputs.map(({ name, value }) => `${name}=${value}`), prompt]
.filter((part) => part !== "")
.join(" ");
}
export function assertDeclared(trigger: ManualTrigger, inputs: readonly InputValue[]): void {
const unknown = inputs.find(
({ name }) => !trigger.inputs.some((declared) => declared.name === name),
);
if (unknown === undefined) return;
throw invalidInput(
`Trigger "${trigger.name}" has no input "${unknown.name}".`,
describeInputs(trigger),
);
}
/** Required inputs that neither a flag nor a token typed at the start of the prompt supplies. */
export function missingInputs(
trigger: ManualTrigger,
inputs: readonly InputValue[],
prompt: string,
): DeclaredInput[] {
const supplied = new Set(inputs.map(({ name }) => name));
let rest = prompt;
for (let token = LEADING_TOKEN.exec(rest); token !== null; token = LEADING_TOKEN.exec(rest)) {
if (!trigger.inputs.some(({ name }) => name === token?.[1])) break;
supplied.add(token[1]!);
rest = rest.slice(token[0].length);
}
return trigger.inputs.filter(
(input) => input.required === true && input.default === undefined && !supplied.has(input.name),
);
}
export function describeInputs(trigger: ManualTrigger): string {
if (trigger.inputs.length === 0) {
return `Trigger "${trigger.name}" declares no inputs. Put free text in the prompt.`;
}
const rows = trigger.inputs.map((input) => ({
flag: `-i ${input.name}=<${input.choices?.join("|") ?? VALUE_PLACEHOLDERS[input.type]}>`,
note: inputNote(input),
}));
const width = Math.max(...rows.map(({ flag }) => flag.length));
return [
`Inputs of "${trigger.name}":`,
...rows.map(({ flag, note }) => ` ${flag.padEnd(width)} ${note}`.trimEnd()),
].join("\n");
}
const VALUE_PLACEHOLDERS: Record<DeclaredInput["type"], string> = {
string: "text",
number: "number",
boolean: "true|false",
};
function inputNote(input: DeclaredInput): string {
if (input.default !== undefined) return `default ${String(input.default)}`;
return input.required === true ? "required" : "";
}
function invalidInput(message: string, details?: string): HubCommandError {
return new HubCommandError("HUB_RUN_INPUT", message, details);
}
@@ -0,0 +1,70 @@
import YAML from "yaml";
import { z } from "zod";
import type { HubTrigger } from "../../hub-client/index.js";
const inputsSchema = z
.record(
z.string(),
z.object({
type: z.enum(["string", "number", "boolean"]),
required: z.boolean().optional(),
default: z.union([z.string(), z.number(), z.boolean()]).optional(),
choices: z.array(z.union([z.string(), z.number(), z.boolean()])).optional(),
}),
)
.optional();
const singleRunSchema = z.object({
on: z.record(z.string(), z.unknown()),
inputs: inputsSchema,
});
// Hub keeps migrated workflows it cannot express as one run in this shape.
const legacyMultistepSchema = z.object({
legacy_multistep: z.object({
trigger: z.object({ on: z.string(), inputs: inputsSchema }),
}),
});
export type DeclaredInput = NonNullable<z.infer<typeof inputsSchema>>[string] & { name: string };
export interface ManualTrigger {
name: string;
enabled: boolean;
/** Whether the document declares `manual.run`. */
manual: boolean;
inputs: DeclaredInput[];
}
/** `null`: a document this CLI cannot read. Hub still decides whether it runs. */
export function readManualTrigger(trigger: HubTrigger): ManualTrigger | null {
try {
// Hub's parser follows `<<` merge keys.
const document: unknown = YAML.parse(trigger.yaml, { merge: true });
const { manual, inputs } = readDocument(trigger.format, document);
return {
name: trigger.name,
enabled: trigger.enabled,
manual,
inputs: Object.entries(inputs ?? {}).map(([name, input]) => Object.assign(input, { name })),
};
} catch {
return null;
}
}
export function isRunnable(trigger: ManualTrigger): boolean {
return trigger.enabled && trigger.manual;
}
function readDocument(
format: HubTrigger["format"],
document: unknown,
): { manual: boolean; inputs: z.infer<typeof inputsSchema> } {
if (format === "legacy_multistep") {
const { on, inputs } = legacyMultistepSchema.parse(document).legacy_multistep.trigger;
return { manual: on === "manual.run", inputs };
}
const { on, inputs } = singleRunSchema.parse(document);
return { manual: Object.hasOwn(on, "manual.run"), inputs };
}
@@ -0,0 +1,67 @@
import { isCancel, select, text } from "@clack/prompts";
import { HubCommandError } from "../../error.js";
import { sendableInput, type InputValue } from "./inputs.js";
import type { DeclaredInput } from "./manual-trigger.js";
/** Questions asked in a terminal. `null` means the person cancelled. */
export interface HubRunPrompts {
select(question: { message: string; options: string[] }): Promise<string | null>;
text(question: {
message: string;
validate(value: string): string | undefined;
}): Promise<string | null>;
}
export const terminalRunPrompts: HubRunPrompts = {
async select({ message, options }) {
const answer = await select<string>({
message,
options: options.map((value) => ({ value, label: value })),
});
return isCancel(answer) ? null : answer;
},
async text({ message, validate }) {
const answer = await text({ message, validate: (value) => validate(value ?? "") });
return isCancel(answer) ? null : answer;
},
};
export async function chooseTrigger(prompts: HubRunPrompts, names: string[]): Promise<string> {
return answered(await prompts.select({ message: "Which trigger?", options: names }));
}
export async function askInputs(
prompts: HubRunPrompts,
inputs: readonly DeclaredInput[],
): Promise<InputValue[]> {
const values: InputValue[] = [];
for (const input of inputs) {
const options =
input.choices?.map(String) ?? (input.type === "boolean" ? ["true", "false"] : undefined);
const answer =
options === undefined
? await prompts.text({
message: input.name,
validate: (value) => invalidAnswer(input, value),
})
: await prompts.select({ message: input.name, options });
values.push(sendableInput(input.name, answered(answer)));
}
return values;
}
function invalidAnswer(input: DeclaredInput, value: string): string | undefined {
if (value === "") return "Required";
if (/\s/u.test(value)) return "No spaces";
if (input.type === "number" && !/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?$/u.test(value)) {
return "Enter a number";
}
return undefined;
}
function answered(answer: string | null): string {
if (answer === null) {
throw new HubCommandError("HUB_RUN_CANCELLED", "Cancelled. Nothing was started.");
}
return answer;
}
+2 -2
View File
@@ -42,7 +42,7 @@ function normalizeFormat(raw: unknown): OutputOptions["format"] {
}
/** Extract output options from command options */
function extractOutputOptions(options: CommandOptions): OutputOptions {
function extractOutputOptions(options: Partial<CommandOptions>): OutputOptions {
const hasStructuredOutputSchema =
typeof options.outputSchema === "string" && options.outputSchema.trim().length > 0;
@@ -63,7 +63,7 @@ function extractOutputOptions(options: CommandOptions): OutputOptions {
};
}
export function isHumanOutput(options: CommandOptions): boolean {
export function isHumanOutput(options: Partial<CommandOptions>): boolean {
const { format, quiet } = extractOutputOptions(options);
return format === "table" && !quiet;
}
+14 -6
View File
@@ -24,7 +24,7 @@ import { $ } from "zx";
import { mkdtemp, rm, mkdir } from "fs/promises";
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { runPaseoCli, startTestDaemon } from "./helpers/test-daemon.ts";
import { runPaseoCli, startTestDaemon, type TestDaemonContext } from "./helpers/test-daemon.ts";
import { tmpdir } from "os";
import { join } from "path";
@@ -174,10 +174,11 @@ try {
// Exercise repository selection through the real CLI and daemon. An empty
// request used to fail before Git could inspect even a valid repository.
const daemon = await startTestDaemon();
const fixtureDir = await mkdtemp(join(tmpdir(), "paseo-worktree-test-"));
const repo = join(fixtureDir, "repository");
const git = promisify(execFile);
let daemon: TestDaemonContext | undefined;
try {
const repo = join(daemon.workDir, "repository");
await mkdir(repo);
await git("git", ["init", repo]);
await git("git", [
@@ -193,6 +194,9 @@ try {
"Initial commit",
]);
// With an explicit endpoint, relative paths resolve from the daemon cwd.
daemon = await startTestDaemon({ cwd: repo });
for (const args of [
["worktree", "ls", "--json"],
["worktree", "ls", "--cwd", repo, "--json"],
@@ -201,7 +205,7 @@ try {
]) {
const explicit = args.includes("--cwd");
const result = await runPaseoCli(daemon, args, {
cwd: explicit ? daemon.workDir : repo,
cwd: explicit ? fixtureDir : repo,
env: { FORCE_COLOR: undefined },
});
assert.strictEqual(result.exitCode, 0, result.stderr);
@@ -224,14 +228,18 @@ try {
],
]) {
const result = await runPaseoCli(daemon, args, {
cwd: args.includes("--cwd") ? daemon.workDir : repo,
cwd: args.includes("--cwd") ? fixtureDir : repo,
env: { FORCE_COLOR: undefined },
});
assert.notStrictEqual(result.exitCode, 0);
assert.strictEqual(JSON.parse(result.stderr).error.code, "WORKTREE_NOT_FOUND", result.stderr);
}
} finally {
await daemon.stop();
try {
await daemon?.stop();
} finally {
await rm(fixtureDir, { recursive: true, force: true });
}
}
console.log("=== All worktree tests passed ===");
+10 -1
View File
@@ -6,7 +6,16 @@ import { createE2ETestContext } from "./helpers/test-daemon.ts";
import { connectToDaemon } from "../src/utils/client.ts";
import { resolveCliVersion } from "../src/version.ts";
const context = await createE2ETestContext();
// Built-in usage sources discover accounts from the daemon's environment.
const context = await createE2ETestContext({
baseEnv: {
PATH: process.env.PATH,
SystemRoot: process.env.SystemRoot,
TEMP: process.env.TEMP,
TMP: process.env.TMP,
TMPDIR: process.env.TMPDIR,
},
});
try {
const directory = join(context.workDir, "usage-plugin");
await mkdir(directory);
+109
View File
@@ -0,0 +1,109 @@
#!/usr/bin/env npx tsx
import assert from "node:assert/strict";
import { createServer } from "node:http";
import type { AddressInfo } from "node:net";
import { runLocalPaseo } from "./helpers/local-cli.js";
const RUN_ID = "7f1c2a64-0b1e-4b55-9c52-6f0b7a1d2e90";
const dispatched: Record<string, unknown>[] = [];
const server = createServer((request, response) => {
let body = "";
request.setEncoding("utf8");
request.on("data", (chunk: string) => {
body += chunk;
});
request.on("end", () => {
const reply = (status: number, value: unknown) => {
response.writeHead(status, {
"content-type": status < 400 ? "application/json" : "application/problem+json",
});
response.end(JSON.stringify(value));
};
if (request.url === "/api/v1/triggers") {
reply(200, {
triggers: [
{
id: "0b0f4d3e-6a53-4a4b-8f0e-2f3c6a1b9d11",
name: "deploy",
enabled: true,
format: "single_run",
yaml: "name: deploy\non:\n manual.run: {}\ninputs:\n environment:\n type: string\n dry_run:\n type: boolean\nrun: {}\n",
},
],
});
return;
}
const dispatch = JSON.parse(body) as Record<string, unknown>;
dispatched.push(dispatch);
if (dispatch.trigger !== "deploy") {
reply(404, {
type: "about:blank",
title: "Trigger not found",
status: 404,
code: "trigger_not_found",
});
return;
}
reply(200, {
deliveryKey: dispatch.deliveryKey,
providerEventReceiptId: "receipt-1",
triggerRunId: RUN_ID,
configuredTriggerName: "deploy",
workflowStatus: "running",
});
});
});
try {
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
const origin = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
const connection = ["--hub", origin, "--api-key", "test-secret"];
const hubRun = (...args: string[]) => runLocalPaseo(["hub", "run", ...args, ...connection]);
const quiet = await hubRun(
"deploy",
"-i",
"environment=staging",
"--input",
"dry_run=false",
"ship the hotfix",
"--quiet",
);
assert.equal(quiet.exitCode, 0, quiet.stderr);
assert.equal(quiet.stdout, `${RUN_ID}\n`);
assert.equal(dispatched[0]?.input, "environment=staging dry_run=false ship the hotfix");
const yaml = await hubRun("deploy", "-o", "yaml");
assert.equal(yaml.exitCode, 0, yaml.stderr);
assert.match(yaml.stdout, new RegExp(`triggerRunId: ${RUN_ID}`, "u"));
const table = await hubRun("deploy", "--no-color");
assert.equal(table.exitCode, 0, table.stderr);
assert.match(table.stdout, /^TRIGGER\s+RUN ID\s+STATUS\s+HUB/u);
assert.equal(table.stderr, `Running deploy on ${origin}\n`);
const unknown = await hubRun("nope", "--json");
assert.equal(unknown.exitCode, 1);
assert.equal(unknown.stdout, "");
const { error } = JSON.parse(unknown.stderr) as { error: Record<string, unknown> };
assert.equal(error.code, "HUB_TRIGGER_NOT_FOUND");
assert.deepEqual(Object.keys(error).toSorted(), ["code", "details", "message", "name"]);
assert.doesNotMatch(unknown.stderr, /test-secret/u);
const before = dispatched.length;
// An unquoted prompt must not start a run with only its first word.
const unquoted = await hubRun("deploy", "ship", "the", "hotfix");
assert.equal(unquoted.exitCode, 1);
assert.match(unquoted.stderr, /too many arguments/u);
const unnamed = await hubRun();
assert.equal(unnamed.exitCode, 1);
assert.match(unnamed.stderr, /paseo hub run <trigger>/u);
assert.equal(dispatched.length, before);
console.log("✅ installed Paseo CLI runs Hub manual triggers");
} finally {
server.closeAllConnections();
await new Promise<void>((resolve) => server.close(() => resolve()));
}
+9 -2
View File
@@ -231,7 +231,10 @@ export async function startTestDaemon(options?: {
port?: number;
paseoHome?: string;
workDir?: string;
cwd?: string;
timeout?: number;
/** Environment to inherit before applying test defaults and explicit overrides. */
baseEnv?: NodeJS.ProcessEnv;
env?: NodeJS.ProcessEnv;
}): Promise<TestDaemonContext> {
// Let the listening process allocate its port, without a reserve/release race.
@@ -248,9 +251,12 @@ export async function startTestDaemon(options?: {
// Start daemon process using tsx to run TypeScript directly
const daemonProcess = spawn(process.execPath, [TSX_ENTRY, cliSrcPath, "daemon", "run"], {
cwd: options?.cwd,
env: {
...Object.fromEntries(
Object.entries(process.env).filter(([key]) => !key.startsWith("PASEO_")),
Object.entries(options?.baseEnv ?? process.env).filter(
([key]) => !key.startsWith("PASEO_"),
),
),
...TEST_DAEMON_ENV_DEFAULTS,
PASEO_HOME: paseoHome,
@@ -423,6 +429,7 @@ export async function runPaseoCli(
*/
export async function createE2ETestContext(options?: {
timeout?: number;
baseEnv?: NodeJS.ProcessEnv;
env?: NodeJS.ProcessEnv;
}): Promise<
TestDaemonContext & {
@@ -437,7 +444,7 @@ export async function createE2ETestContext(options?: {
}>;
}
> {
const ctx = await startTestDaemon({ timeout: options?.timeout, env: options?.env });
const ctx = await startTestDaemon(options);
const paseo = (
args: string[],
+3 -3
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/client",
"version": "0.18.1",
"version": "0.18.2",
"description": "Paseo client SDK package",
"license": "Apache-2.0",
"files": [
@@ -57,8 +57,8 @@
"measure:diff-materialization": "tsx scripts/measure-diff-materialization.ts"
},
"dependencies": {
"@getpaseo/protocol": "0.18.1",
"@getpaseo/relay": "0.18.1",
"@getpaseo/protocol": "0.18.2",
"@getpaseo/relay": "0.18.2",
"ws": "^8.20.0",
"zod": "^4.4.3"
},
@@ -18,6 +18,13 @@ async function main() {
return path.join(release, matches[0]);
};
try {
if (installedOnly) {
const rpmFiles = execFileSync("rpm", ["-qpl", findArtifact(".rpm")], { encoding: "utf8" });
if (/^\/usr\/lib\/\.build-id\//m.test(rpmFiles)) {
throw new Error("The Paseo RPM claims build-ID paths shared by other Electron packages");
}
}
process.env.PASEO_DESKTOP_SMOKE_ARTIFACT_DIR = path.join(artifactRoot, "installed");
const helper = fs.statSync("/opt/Paseo/chrome-sandbox");
if (helper.uid !== 0 || (helper.mode & 0o7777) !== 0o4755) {
+3
View File
@@ -80,6 +80,9 @@ deb:
afterInstall: scripts/linux-sandbox/after-install.tpl
rpm:
afterInstall: scripts/linux-sandbox/after-install.tpl
# Electron apps can bundle the same binaries under different install paths.
fpm:
- "--rpm-rpmbuild-define=_build_id_links none"
appImage:
# A nonempty argument list replaces builder's hardcoded --no-sandbox default.
executableArgs: ["--class=Paseo"]
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/desktop",
"version": "0.18.1",
"version": "0.18.2",
"private": true,
"description": "Paseo desktop app (Electron wrapper)",
"homepage": "https://paseo.sh",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/expo-two-way-audio",
"version": "0.18.1",
"version": "0.18.2",
"description": "Native module for two way audio streaming",
"keywords": [
"ExpoTwoWayAudio",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/highlight",
"version": "0.18.1",
"version": "0.18.2",
"license": "Apache-2.0",
"files": [
"dist",
+5 -5
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/plugin",
"version": "0.18.1",
"version": "0.18.2",
"description": "Paseo plugin SDK package",
"license": "Apache-2.0",
"files": [
@@ -83,8 +83,8 @@
"use-sync-external-store": "^1.6.0"
},
"devDependencies": {
"@getpaseo/client": "0.18.1",
"@getpaseo/protocol": "0.18.1",
"@getpaseo/client": "0.18.2",
"@getpaseo/protocol": "0.18.2",
"@types/node": "^20.9.0",
"@types/react": "~19.2.0",
"react": "19.2.3",
@@ -94,8 +94,8 @@
"zod": "^4.4.3"
},
"peerDependencies": {
"@getpaseo/client": "0.18.1",
"@getpaseo/protocol": "0.18.1",
"@getpaseo/client": "0.18.2",
"@getpaseo/protocol": "0.18.2",
"react": ">=19.1.0 <20",
"react-native": ">=0.81.5",
"zod": "^4.4.3"
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/protocol",
"version": "0.18.1",
"version": "0.18.2",
"description": "Paseo shared protocol schemas and wire types",
"license": "Apache-2.0",
"files": [
@@ -1,6 +1,6 @@
{
"name": "react-native-enriched-markdown",
"version": "0.18.1",
"version": "0.18.2",
"private": true,
"description": "Markdown-based Rich Text solution for React Native",
"main": "./lib/module/index",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/relay",
"version": "0.18.1",
"version": "0.18.2",
"description": "Paseo relay for bridging daemon and client connections",
"license": "Apache-2.0",
"files": [
+6 -6
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/server",
"version": "0.18.1",
"version": "0.18.2",
"description": "Paseo backend server",
"license": "Apache-2.0",
"files": [
@@ -114,11 +114,11 @@
"@agentclientprotocol/sdk": "^0.17.1",
"@anthropic-ai/claude-agent-sdk": "0.3.326",
"@anthropic-ai/sdk": "^0.104.2",
"@getpaseo/client": "0.18.1",
"@getpaseo/highlight": "0.18.1",
"@getpaseo/plugin": "0.18.1",
"@getpaseo/protocol": "0.18.1",
"@getpaseo/relay": "0.18.1",
"@getpaseo/client": "0.18.2",
"@getpaseo/highlight": "0.18.2",
"@getpaseo/plugin": "0.18.2",
"@getpaseo/protocol": "0.18.2",
"@getpaseo/relay": "0.18.2",
"@isaacs/ttlcache": "^2.1.4",
"@modelcontextprotocol/node": "2.1.2",
"@modelcontextprotocol/sdk": "1.29.0",
@@ -4641,6 +4641,303 @@ test("keeps the global Paseo-tools gate outside provider policy and MCP injectio
rmSync(workdir, { recursive: true, force: true });
});
test("voice-only delivery injects internal paseo MCP and native voiceOnly catalog even when Paseo tools are disabled", async () => {
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-test-"));
const storage = new AgentStorage(join(workdir, "agents"), logger);
const voiceActiveAgents = new Set<string>();
class VoiceMcpSession extends McpCapableTestAgentSession {
override readonly provider: AgentProvider;
constructor(config: AgentSessionConfig) {
super(config);
this.provider = config.provider;
}
override describePersistence(): AgentPersistenceHandle {
return {
provider: this.provider,
sessionId: this.id,
metadata: { cwd: workdir },
};
}
}
class VoiceMcpClient extends TestAgentClient {
override readonly capabilities = {
...TEST_CAPABILITIES,
supportsMcpServers: true,
};
readonly configs: AgentSessionConfig[] = [];
readonly launchContexts: Array<AgentLaunchContext | undefined> = [];
override async createSession(
config: AgentSessionConfig,
launchContext?: AgentLaunchContext,
): Promise<AgentSession> {
this.configs.push(config);
this.launchContexts.push(launchContext);
return new VoiceMcpSession(config);
}
override async resumeSession(
handle: AgentPersistenceHandle,
overrides?: Partial<AgentSessionConfig>,
launchContext?: AgentLaunchContext,
): Promise<AgentSession> {
const config = {
provider: handle.provider,
cwd: workdir,
...overrides,
} as AgentSessionConfig;
this.configs.push(config);
this.launchContexts.push(launchContext);
return new VoiceMcpSession(config);
}
}
class VoiceNativeClient extends VoiceMcpClient {
override readonly capabilities = {
...TEST_CAPABILITIES,
supportsMcpServers: true,
supportsNativePaseoTools: true,
};
}
const speakCatalog: PaseoToolCatalog = {
tools: new Map([
[
"speak",
{
name: "speak",
description: "Speak text",
handler: async () => ({ content: [], structuredContent: { ok: true } }),
},
],
]),
getTool: (name) => (name === "speak" ? speakCatalog.tools.get("speak") : undefined),
executeTool: async () => ({ content: [], structuredContent: { ok: true } }),
};
const mcpClient = new VoiceMcpClient("claude");
const nativeClient = new VoiceNativeClient("opencode");
const catalogCalls: Array<{
callerAgentId?: string;
paseoToolPolicy?: unknown;
voiceOnly?: boolean;
}> = [];
const manager = new AgentManager({
clients: { claude: mcpClient, opencode: nativeClient },
registry: storage,
logger,
mcpBaseUrl: "http://127.0.0.1:6767/mcp/agents",
mcpAuthToken: "voice-token",
paseoToolsEnabled: false,
hasActiveVoiceTools: (agentId) => voiceActiveAgents.has(agentId),
paseoToolCatalogFactory: (context) => {
catalogCalls.push(context);
return speakCatalog;
},
});
try {
const claudeAgent = await manager.createAgent(
{ provider: "claude", cwd: workdir },
"00000000-0000-4000-8000-000000000201",
{ workspaceId: undefined },
);
const opencodeAgent = await manager.createAgent(
{ provider: "opencode", cwd: workdir },
"00000000-0000-4000-8000-000000000202",
{ workspaceId: undefined },
);
// Non-voice sessions receive zero Paseo MCP servers and zero native Paseo tools.
expect(mcpClient.configs.at(-1)?.mcpServers).toBeUndefined();
expect(mcpClient.launchContexts.at(-1)?.voiceToolsEnabled).toBeUndefined();
expect(nativeClient.configs.at(-1)?.mcpServers).toBeUndefined();
expect(nativeClient.launchContexts.at(-1)?.paseoTools).toBeUndefined();
expect(catalogCalls).toEqual([]);
// Enabling voice mode on MCP provider injects loopback paseo MCP and marks voiceToolsEnabled.
voiceActiveAgents.add(claudeAgent.id);
await manager.reloadAgentSession(
claudeAgent.id,
{ systemPrompt: "voice prompt" },
{ requireVoiceSpeak: true },
);
expect(mcpClient.configs.at(-1)?.mcpServers?.paseo).toEqual({
type: "http",
url: `http://127.0.0.1:6767/mcp/agents?callerAgentId=${claudeAgent.id}`,
headers: { Authorization: "Bearer voice-token" },
});
expect(mcpClient.launchContexts.at(-1)?.voiceToolsEnabled).toBe(true);
// Enabling voice mode on native-tools provider builds a voiceOnly catalog with speak only.
voiceActiveAgents.add(opencodeAgent.id);
await manager.reloadAgentSession(
opencodeAgent.id,
{ systemPrompt: "voice prompt" },
{ requireVoiceSpeak: true },
);
expect(catalogCalls).toEqual([
{
callerAgentId: opencodeAgent.id,
paseoToolPolicy: { enabled: false },
voiceOnly: true,
},
]);
expect(nativeClient.launchContexts.at(-1)?.paseoTools).toBe(speakCatalog);
expect(nativeClient.configs.at(-1)?.mcpServers?.paseo).toBeUndefined();
// Disabling voice mode removes paseo MCP and voiceToolsEnabled again.
voiceActiveAgents.delete(claudeAgent.id);
await manager.reloadAgentSession(claudeAgent.id, { systemPrompt: "normal prompt" });
expect(mcpClient.configs.at(-1)?.mcpServers).toBeUndefined();
expect(mcpClient.launchContexts.at(-1)?.voiceToolsEnabled).toBeUndefined();
} finally {
rmSync(workdir, { recursive: true, force: true });
}
});
test("reloadAgentSession rejects voice mode when the session cannot mount speak and preserves the live session", async () => {
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-test-"));
const storage = new AgentStorage(join(workdir, "agents"), logger);
class PiNoMcpSession extends CloseRecordingTestAgentSession {
override readonly provider = "pi" as const;
override describePersistence(): AgentPersistenceHandle {
return {
provider: "pi",
sessionId: this.id,
metadata: { cwd: workdir },
};
}
}
const original = new PiNoMcpSession({ provider: "pi", cwd: workdir });
const reopened = new PiNoMcpSession({ provider: "pi", cwd: workdir });
let voiceActive = false;
class NoMcpPiClient extends TestAgentClient {
override readonly capabilities = {
...TEST_CAPABILITIES,
supportsMcpServers: false,
supportsNativePaseoTools: false,
};
override async createSession(): Promise<AgentSession> {
return original;
}
override async resumeSession(): Promise<AgentSession> {
return reopened;
}
}
class StdioOnlyAcpSession extends CloseRecordingTestAgentSession {
override readonly provider = "acp-stdio" as const;
override readonly capabilities = {
...TEST_CAPABILITIES,
supportsMcpServers: true,
supportsHttpMcpServers: false,
};
override describePersistence(): AgentPersistenceHandle {
return {
provider: "acp-stdio",
sessionId: this.id,
metadata: { cwd: workdir },
};
}
}
const acpOriginal = new StdioOnlyAcpSession({ provider: "acp-stdio", cwd: workdir });
const acpReopened = new StdioOnlyAcpSession({ provider: "acp-stdio", cwd: workdir });
class StdioOnlyAcpClient extends TestAgentClient {
override readonly capabilities = {
...TEST_CAPABILITIES,
supportsMcpServers: true,
};
override async createSession(): Promise<AgentSession> {
return acpOriginal;
}
override async resumeSession(): Promise<AgentSession> {
return acpReopened;
}
}
const manager = new AgentManager({
clients: {
pi: new NoMcpPiClient("pi"),
"acp-stdio": new StdioOnlyAcpClient("acp-stdio"),
},
registry: storage,
logger,
mcpBaseUrl: "http://127.0.0.1:6767/mcp/agents",
paseoToolsEnabled: false,
hasActiveVoiceTools: () => voiceActive,
});
try {
const created = await manager.createAgent(
{ provider: "pi", cwd: workdir, systemPrompt: "base prompt" },
"00000000-0000-4000-8000-000000000203",
{ workspaceId: undefined },
);
voiceActive = true;
await expect(
manager.reloadAgentSession(
created.id,
{ systemPrompt: "voice prompt" },
{ requireVoiceSpeak: true },
),
).rejects.toThrow(/speak/i);
expect(original.closed).toBe(false);
expect(reopened.closed).toBe(false);
expect(manager.getAgent(created.id)?.session).toBe(original);
expect(manager.getAgent(created.id)?.lifecycle).toBe("idle");
const stored = await storage.get(created.id);
expect(stored?.config?.systemPrompt).toBe("base prompt");
// ACP with mcpCapabilities.http=false still launches with stdio MCP servers,
// while rejecting voice mode cleanly without closing the live session.
voiceActive = false;
const acpAgent = await manager.createAgent(
{
provider: "acp-stdio",
cwd: workdir,
mcpServers: {
local: { type: "stdio", command: "node", args: ["mcp.js"] },
},
},
"00000000-0000-4000-8000-000000000204",
{ workspaceId: undefined },
);
expect(manager.getAgent(acpAgent.id)?.lifecycle).toBe("idle");
voiceActive = true;
await expect(
manager.reloadAgentSession(
acpAgent.id,
{ systemPrompt: "voice prompt" },
{ requireVoiceSpeak: true },
),
).rejects.toThrow(/speak/i);
expect(acpOriginal.closed).toBe(false);
expect(acpReopened.closed).toBe(false);
expect(manager.getAgent(acpAgent.id)?.session).toBe(acpOriginal);
expect(manager.getAgent(acpAgent.id)?.lifecycle).toBe("idle");
} finally {
rmSync(workdir, { recursive: true, force: true });
}
});
test("resumeAgentFromPersistence replaces stored internal paseo MCP with current runtime URL", async () => {
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-test-"));
const storagePath = join(workdir, "agents");
@@ -437,6 +437,7 @@ export interface AgentManagerOptions {
pluginSessions?: PluginSessionsRuntime;
paseoToolsEnabled?: boolean;
paseoToolCatalogFactory?: PaseoToolCatalogFactory;
hasActiveVoiceTools?: (agentId: string) => boolean;
resolvePaseoToolPolicy?: (provider: AgentProvider) => ProviderPaseoToolsPolicy | undefined;
appendSystemPrompt?: string;
agentStreamCoalesceWindowMs?: number;
@@ -1000,6 +1001,7 @@ export class AgentManager {
private readonly pluginSessions: PluginSessionsRuntime | undefined;
private paseoToolsEnabled = true;
private paseoToolCatalogFactory: PaseoToolCatalogFactory | null = null;
private hasActiveVoiceTools: (agentId: string) => boolean = () => false;
private readonly paseoToolPolicies = new Map<string, ProviderPaseoToolsPolicy | undefined>();
private readonly resolvePaseoToolPolicy: (
provider: AgentProvider,
@@ -1052,6 +1054,7 @@ export class AgentManager {
private configurePaseoTools(options: AgentManagerOptions): void {
this.paseoToolsEnabled = options.paseoToolsEnabled ?? true;
this.paseoToolCatalogFactory = options.paseoToolCatalogFactory ?? null;
this.hasActiveVoiceTools = options.hasActiveVoiceTools ?? (() => false);
}
registerClient(provider: AgentProvider, client: AgentClient): void {
@@ -1116,6 +1119,10 @@ export class AgentManager {
this.paseoToolsEnabled = enabled;
}
isPaseoToolsEnabled(): boolean {
return this.paseoToolsEnabled;
}
setPaseoToolCatalogFactory(factory: PaseoToolCatalogFactory | null): void {
this.paseoToolCatalogFactory = factory;
}
@@ -2098,7 +2105,7 @@ export class AgentManager {
reloadAgentSession(
agentId: string,
overrides?: Partial<AgentSessionConfig>,
options?: { rehydrateFromDisk?: boolean },
options?: { rehydrateFromDisk?: boolean; requireVoiceSpeak?: boolean },
): Promise<ManagedAgent> {
return this.trackAgentRegistrationOperation(
this.runLifecycleMutation(agentId, () =>
@@ -2110,7 +2117,7 @@ export class AgentManager {
private reloadAgentSessionInternal(
agentId: string,
overrides?: Partial<AgentSessionConfig>,
options?: { rehydrateFromDisk?: boolean },
options?: { rehydrateFromDisk?: boolean; requireVoiceSpeak?: boolean },
): Promise<ManagedAgent> {
return this.launchAgent(agentId, () => this.reopenAgentSession(agentId, overrides, options));
}
@@ -2132,7 +2139,7 @@ export class AgentManager {
private async reopenAgentSession(
agentId: string,
overrides?: Partial<AgentSessionConfig>,
options?: { rehydrateFromDisk?: boolean },
options?: { rehydrateFromDisk?: boolean; requireVoiceSpeak?: boolean },
): Promise<ManagedAgent> {
this.assertAcceptingAgentRegistrations();
let existing = this.requireSessionAgent(agentId);
@@ -2181,6 +2188,7 @@ export class AgentManager {
existing,
launchConfig,
launchContext,
options,
);
let session: AgentSession | undefined;
@@ -2202,6 +2210,7 @@ export class AgentManager {
? await client.resumeSession(handle, providerLaunchConfig, launchContext)
: await client.createSession(providerLaunchConfig, launchContext);
await this.requireExternalMcpSupport(session, providerLaunchConfig, launchContext);
this.assertVoiceSpeakSupportIfRequired(session, providerLaunchConfig, launchContext, options);
this.assertAcceptingAgentRegistrations();
if (rehydrateFromDisk) {
@@ -2264,6 +2273,7 @@ export class AgentManager {
existing: ActiveManagedAgent,
launchConfig: AgentSessionConfig,
launchContext: AgentLaunchContext,
options?: { requireVoiceSpeak?: boolean },
): AgentSessionConfig {
const providerLaunchConfig = this.resolveProviderLaunchConfig(launchConfig, launchContext);
const mcpServers = stripInternalPaseoMcpServer(providerLaunchConfig).mcpServers ?? {};
@@ -2273,6 +2283,12 @@ export class AgentManager {
) {
throw this.unsupportedMcpError(providerLaunchConfig, launchContext);
}
this.assertVoiceSpeakSupportIfRequired(
existing.session,
providerLaunchConfig,
launchContext,
options,
);
return providerLaunchConfig;
}
@@ -4939,6 +4955,29 @@ export class AgentManager {
return new Error(`Provider '${config.provider}' does not support MCP servers${source}`);
}
private assertVoiceSpeakSupportIfRequired(
session: AgentSession,
launchConfig: AgentSessionConfig,
launchContext: AgentLaunchContext,
options?: { requireVoiceSpeak?: boolean },
): void {
if (!options?.requireVoiceSpeak) {
return;
}
const hasNativeSpeak = launchContext.paseoTools?.tools.has("speak") === true;
const supportsHttpMcp =
session.capabilities.supportsMcpServers === true &&
session.capabilities.supportsHttpMcpServers !== false;
const hasMcpSpeak =
Boolean(launchConfig.mcpServers?.[PASEO_MCP_SERVER_NAME]) && supportsHttpMcp;
if (hasNativeSpeak || hasMcpSpeak) {
return;
}
throw new Error(
`Voice mode is unavailable for provider '${launchConfig.provider}': the session does not expose Paseo's 'speak' tool (requires native Paseo tool support or HTTP MCP server support).`,
);
}
private async initializeAgentTimelineForRegister(params: {
agentId: string;
now: Date;
@@ -6769,17 +6808,16 @@ export class AgentManager {
purpose: options.purpose,
resolveDefaultModel: options.resolveDefaultModel,
});
const voiceActive = this.hasActiveVoiceTools(agentId);
const paseoToolPolicy = this.paseoToolsEnabled
? this.resolvePaseoToolPolicy(storedConfig.provider)
: { enabled: false };
const generalEnabled = this.paseoToolsEnabled && isPaseoToolPolicyEnabled(paseoToolPolicy);
const launchConfig = this.applyDaemonAppendSystemPrompt(
withRuntimePaseoMcpServer({
config: storedConfig,
agentId,
mcpBaseUrl:
this.paseoToolsEnabled && isPaseoToolPolicyEnabled(paseoToolPolicy)
? this.mcpBaseUrl
: null,
mcpBaseUrl: generalEnabled || voiceActive ? this.mcpBaseUrl : null,
mcpAuthToken: this.mcpAuthToken,
}),
);
@@ -6856,10 +6894,23 @@ export class AgentManager {
...agentIdentityEnv({ agentId, cwd, opening }),
},
};
await this.attachLaunchPaseoTools(context, agentId, client, paseoToolPolicy);
return context;
}
private async attachLaunchPaseoTools(
context: AgentLaunchContext,
agentId: string,
client: AgentClient,
paseoToolPolicy: ProviderPaseoToolsPolicy | undefined,
): Promise<void> {
const voiceActive = this.hasActiveVoiceTools(agentId);
if (voiceActive) {
context.voiceToolsEnabled = true;
}
const generalEnabled = this.paseoToolsEnabled && isPaseoToolPolicyEnabled(paseoToolPolicy);
const useNativeTools =
this.paseoToolsEnabled &&
isPaseoToolPolicyEnabled(paseoToolPolicy) &&
client.capabilities.supportsNativePaseoTools;
(generalEnabled || voiceActive) && client.capabilities.supportsNativePaseoTools;
if (
this.paseoToolCatalogFactory &&
(useNativeTools || this.getPluginTools(agentId).length > 0)
@@ -6868,10 +6919,10 @@ export class AgentManager {
const catalog = await this.paseoToolCatalogFactory({
callerAgentId: agentId,
paseoToolPolicy,
...(useNativeTools && voiceActive && !generalEnabled ? { voiceOnly: true } : {}),
});
if (useNativeTools) context.paseoTools = catalog;
}
return context;
}
private resolveProviderLaunchConfig(
@@ -1,7 +1,9 @@
import { EventEmitter } from "node:events";
import http from "node:http";
import net from "node:net";
import os from "node:os";
import path from "node:path";
import { Readable } from "node:stream";
import { existsSync } from "node:fs";
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { describe, expect, test } from "vitest";
@@ -17,6 +19,8 @@ import pino from "pino";
import { withTimeout } from "../../utils/promise-timeout.js";
import { hashDaemonPassword } from "../auth.js";
import { createPaseoDaemon, type PaseoDaemonConfig } from "../bootstrap.js";
import type { SpeechService } from "../speech/speech-runtime.js";
import { DaemonClient } from "../test-utils/daemon-client.js";
import { createTestAgentClients } from "../test-utils/fake-agent-client.js";
import type {
AgentClient,
@@ -1188,3 +1192,278 @@ describe("agent MCP protocol negotiation", () => {
}
}, 30_000);
});
describe("voice-only speak MCP delivery", () => {
function createFakeVoiceSpeechService(spokenTexts: string[]): SpeechService {
const ready = {
enabled: true,
available: true,
retryable: false,
reasonCode: "ready" as const,
message: "Ready",
missingModelIds: [],
};
return {
resolveStt: () => ({
id: "local",
createSession: () => {
const session = new EventEmitter();
return Object.assign(session, {
requiredSampleRate: 16000,
async connect() {},
appendPcm16() {},
commit() {},
clear() {},
close() {},
});
},
}),
resolveSttLanguage: () => "en",
resolveTts: () => ({
async synthesizeSpeech(text: string) {
spokenTexts.push(text);
return { stream: Readable.from([Buffer.from("pcm")]), format: "pcm;rate=24000" };
},
}),
resolveTurnDetection: () => ({
id: "local",
createSession: () => {
const session = new EventEmitter();
return Object.assign(session, {
requiredSampleRate: 16000,
async connect() {},
appendPcm16() {},
flush() {},
reset() {},
close() {},
});
},
}),
resolveDictationStt: () => null,
resolveDictationSttLanguage: () => "en",
getReadiness: () => ({
voiceFeature: ready,
realtimeVoice: ready,
dictation: ready,
localModels: [],
}),
onReadinessChange: () => () => {},
reconfigure: () => {},
listLocalModels: async () => [],
downloadLocalModel: () => {},
deleteLocalModel: async () => {},
start: () => {},
stop: async () => {},
};
}
async function listMcpToolsAndCallSpeak(
mcpUrl: string,
authToken: string | null,
text?: string,
): Promise<{ toolNames: string[]; speakResult?: unknown }> {
const client = new StandardMcpClient({ name: "voice-mcp-e2e", version: "0.0.0" });
await client.connect(
new StandardMcpHttpTransport(new URL(mcpUrl), {
requestInit: authToken ? { headers: { Authorization: `Bearer ${authToken}` } } : undefined,
}),
);
try {
const tools = await client.listTools();
const toolNames = tools.tools.map((tool) => tool.name);
let speakResult: unknown;
if (text !== undefined) {
speakResult = await client.callTool({ name: "speak", arguments: { text } });
}
return { toolNames, speakResult };
} finally {
await client.close();
}
}
class VoiceRecordingAgentClient implements AgentClient {
readonly provider: AgentClient["provider"];
readonly capabilities: AgentClient["capabilities"];
constructor(
private readonly inner: AgentClient,
readonly launches: AgentSessionConfig[],
supportsMcpServers: boolean,
) {
this.provider = inner.provider;
this.capabilities = {
...inner.capabilities,
supportsMcpServers,
supportsNativePaseoTools: false,
};
}
private wrapSession(session: AgentSession): AgentSession {
return Object.assign(Object.create(Object.getPrototypeOf(session)), session, {
capabilities: this.capabilities,
}) as AgentSession;
}
async createSession(
...args: Parameters<AgentClient["createSession"]>
): ReturnType<AgentClient["createSession"]> {
this.launches.push(args[0]);
return this.wrapSession(await this.inner.createSession(...args));
}
async resumeSession(
...args: Parameters<AgentClient["resumeSession"]>
): ReturnType<AgentClient["resumeSession"]> {
this.launches.push({
provider: this.provider,
cwd: args[1]?.cwd ?? String(args[0].metadata?.cwd ?? ""),
...args[1],
});
return this.wrapSession(await this.inner.resumeSession(...args));
}
fetchCatalog(
...args: Parameters<AgentClient["fetchCatalog"]>
): ReturnType<AgentClient["fetchCatalog"]> {
return this.inner.fetchCatalog(...args);
}
isAvailable(): Promise<boolean> {
return this.inner.isAvailable();
}
}
test.each([
{
name: "default config (mcp.injectIntoAgents=false, mcp.enabled=true)",
mcpEnabled: true,
mcpInjectIntoAgents: false,
providerOverrides: undefined,
},
{
name: "mcp.enabled=false on loopback",
mcpEnabled: false,
mcpInjectIntoAgents: false,
providerOverrides: undefined,
},
{
name: "per-provider paseoTools.enabled=false",
mcpEnabled: true,
mcpInjectIntoAgents: true,
providerOverrides: { claude: { paseoTools: { enabled: false } } },
},
])(
"delivers only speak on voice enable under $name and rejects unsupported providers",
async ({ mcpEnabled, mcpInjectIntoAgents, providerOverrides }) => {
const paseoHome = await mkdtemp(path.join(os.tmpdir(), "paseo-voice-home-"));
const staticDir = await mkdtemp(path.join(os.tmpdir(), "paseo-voice-static-"));
const agentCwd = await mkdtemp(path.join(os.tmpdir(), "paseo-voice-cwd-"));
const port = await getAvailablePort();
const spokenTexts: string[] = [];
const claudeLaunches: AgentSessionConfig[] = [];
const codexLaunches: AgentSessionConfig[] = [];
const baseClients = createTestAgentClients();
const claudeBase = baseClients.claude!;
const codexBase = baseClients.codex!;
const daemon = await createPaseoDaemon(
{
listen: `127.0.0.1:${port}`,
paseoHome,
corsAllowedOrigins: [],
hostnames: true,
mcpEnabled,
mcpInjectIntoAgents,
providerOverrides,
staticDir,
mcpDebug: false,
agentClients: {
...baseClients,
claude: new VoiceRecordingAgentClient(claudeBase, claudeLaunches, true),
codex: new VoiceRecordingAgentClient(codexBase, codexLaunches, false),
},
agentStoragePath: path.join(paseoHome, "agents"),
},
pino({ level: "silent" }),
{ speechService: createFakeVoiceSpeechService(spokenTexts) },
);
await daemon.start();
const wsClient = new DaemonClient({ url: `ws://127.0.0.1:${port}/ws` });
wsClient.on("audio_output", (msg) => {
if (msg.type === "audio_output" && msg.payload.id) {
void wsClient.sendSessionMessage({ type: "audio_played", id: msg.payload.id });
}
});
try {
await wsClient.connect();
// Non-voice agent receives zero Paseo MCP servers.
const claudeAgent = await daemon.agentManager.createAgent(
{
provider: "claude",
cwd: agentCwd,
model: "claude-test-model",
modeId: "bypassPermissions",
},
undefined,
{ workspaceId: undefined },
);
expect(claudeLaunches.at(-1)?.mcpServers?.paseo).toBeUndefined();
// When mcp.enabled=false, non-voice /mcp/agents requests still get 404.
if (!mcpEnabled) {
const nonVoiceRes = await fetch(
`http://127.0.0.1:${port}/mcp/agents?callerAgentId=${claudeAgent.id}`,
{ method: "POST", headers: { "content-type": "application/json" }, body: "{}" },
);
expect(nonVoiceRes.status).toBe(404);
}
// Enabling voice mode injects loopback paseo MCP and exposes ONLY speak.
await wsClient.setVoiceMode(true, claudeAgent.id);
const injected = claudeLaunches.at(-1)?.mcpServers?.paseo;
expect(injected).toBeDefined();
expect(injected?.type).toBe("http");
if (!injected || injected.type !== "http") {
throw new Error("Expected HTTP paseo MCP server");
}
const { toolNames } = await listMcpToolsAndCallSpeak(
injected.url,
daemon.agentManager.getMcpAuthToken(),
"Hello from voice mode",
);
expect(toolNames).toEqual(["speak"]);
expect(spokenTexts).toEqual(["Hello from voice mode"]);
// Disabling voice mode drops paseo MCP on the restored non-voice session.
await wsClient.setVoiceMode(false, claudeAgent.id);
expect(claudeLaunches.at(-1)?.mcpServers?.paseo).toBeUndefined();
// Provider without MCP/native tools rejects set_voice_mode cleanly.
const unsupportedAgent = await daemon.agentManager.createAgent(
{ provider: "codex", cwd: agentCwd },
undefined,
{ workspaceId: undefined },
);
await expect(wsClient.setVoiceMode(true, unsupportedAgent.id)).rejects.toThrow(/speak/i);
if (!mcpEnabled) {
const rejectedRes = await fetch(
`http://127.0.0.1:${port}/mcp/agents?callerAgentId=${unsupportedAgent.id}`,
{ method: "POST", headers: { "content-type": "application/json" }, body: "{}" },
);
expect(rejectedRes.status).toBe(404);
}
} finally {
await wsClient.close();
await daemon.stop();
await rm(paseoHome, { recursive: true, force: true });
await rm(staticDir, { recursive: true, force: true });
await rm(agentCwd, { recursive: true, force: true });
}
},
30_000,
);
});
@@ -189,6 +189,8 @@ export interface AgentCapabilityFlags {
supportsSessionListing?: boolean;
supportsDynamicModes: boolean;
supportsMcpServers: boolean;
/** When false, HTTP MCP servers (such as Paseo's loopback endpoint) are not supported even if stdio MCP works. */
supportsHttpMcpServers?: boolean;
supportsNativePaseoTools?: boolean;
supportsReasoningStream: boolean;
supportsToolInvocations: boolean;
@@ -711,6 +713,8 @@ export interface AgentLaunchContext {
* AgentSessionConfig; providers may adapt it to their native tool surface.
*/
paseoTools?: PaseoToolCatalog;
/** True while Paseo voice mode is active for this session launch (never persisted). */
voiceToolsEnabled?: boolean;
}
export interface AgentCreateSessionOptions {
@@ -8,7 +8,11 @@ import { createTestLogger } from "../../test-utils/test-logger.js";
import { AgentManager } from "./agent-manager.js";
import { validateProviderOptions } from "./provider-options.js";
import { applyClaudeToolPolicy, ClaudeProviderOptionsSchema } from "./providers/claude/options.js";
import { applyCodexToolPolicy, CodexProviderOptionsSchema } from "./providers/codex/options.js";
import {
applyCodexMcpToolApproval,
applyCodexToolPolicy,
CodexProviderOptionsSchema,
} from "./providers/codex/options.js";
import {
buildOpenCodePermissionRules,
OpenCodeProviderOptionsSchema,
@@ -196,6 +200,52 @@ describe("exact MCP preapproval mappings", () => {
});
});
test("Codex speak approval sets tools.speak.approval_mode without restricting enabled_tools", () => {
expect(
applyCodexMcpToolApproval(
{
"mcp_servers.paseo": { url: "http://127.0.0.1/mcp/agents?callerAgentId=a1" },
"mcp_servers.other": { command: "node" },
},
"paseo",
"speak",
),
).toEqual({
"mcp_servers.paseo": {
url: "http://127.0.0.1/mcp/agents?callerAgentId=a1",
tools: { speak: { approval_mode: "approve" } },
},
"mcp_servers.other": { command: "node" },
});
expect(
applyCodexMcpToolApproval(
{
mcp_servers: {
paseo: { url: "http://127.0.0.1/mcp/agents?callerAgentId=a1" },
"my.dotted": { url: "http://127.0.0.1/other" },
},
},
"paseo",
"speak",
),
).toEqual({
mcp_servers: {
paseo: {
url: "http://127.0.0.1/mcp/agents?callerAgentId=a1",
tools: { speak: { approval_mode: "approve" } },
},
"my.dotted": { url: "http://127.0.0.1/other" },
},
});
expect(
applyCodexMcpToolApproval({ "mcp_servers.other": { command: "node" } }, "paseo", "speak"),
).toEqual({
"mcp_servers.other": { command: "node" },
});
});
test("Claude adds the exact MCP identity without replacing deny rules", () => {
expect(
applyClaudeToolPolicy(
@@ -3562,6 +3562,92 @@ describe("ACPAgentSession", () => {
expect(asInternals<ACPSessionInternals>(session).acpMcpServers()).toEqual([]);
});
test("gates HTTP MCP servers and supportsHttpMcpServers on agentCapabilities.mcpCapabilities.http without breaking stdio MCP", async () => {
const newSession = vi.fn().mockResolvedValue({
sessionId: "acp-http-cap-session",
modes: null,
models: null,
configOptions: [],
});
class CapabilityTestSession extends ACPAgentSession {
constructor(
private readonly httpCap: boolean | undefined,
config: AgentSessionConfig,
) {
super(config, {
provider: "test-acp",
logger: createTestLogger(),
defaultCommand: ["test-acp", "serve"],
defaultModes: [],
capabilities: {
supportsStreaming: true,
supportsSessionPersistence: true,
supportsDynamicModes: true,
supportsMcpServers: true,
supportsReasoningStream: true,
supportsToolInvocations: true,
},
});
}
protected override async spawnProcess(): Promise<SpawnedACPProcess> {
return {
child: createProbeChildStub(),
connection: {
newSession,
} as unknown as ClientSideConnection,
initialize: {
protocolVersion: PROTOCOL_VERSION,
agentCapabilities:
this.httpCap === undefined ? {} : { mcpCapabilities: { http: this.httpCap } },
},
};
}
}
const mcpServers: AgentSessionConfig["mcpServers"] = {
paseo: { type: "http", url: "http://127.0.0.1:6767/mcp/agents?callerAgentId=agent-1" },
local: { type: "stdio", command: "node", args: ["mcp.js"] },
};
const unsupported = new CapabilityTestSession(false, {
provider: "test-acp",
cwd: "/tmp/paseo-acp-test",
mcpServers,
});
await unsupported.initializeNewSession();
expect(unsupported.capabilities.supportsMcpServers).toBe(true);
expect(unsupported.capabilities.supportsHttpMcpServers).toBe(false);
expect(newSession).toHaveBeenLastCalledWith({
cwd: "/tmp/paseo-acp-test",
mcpServers: [{ name: "local", command: "node", args: ["mcp.js"], env: [] }],
});
const supported = new CapabilityTestSession(true, {
provider: "test-acp",
cwd: "/tmp/paseo-acp-test",
mcpServers,
});
await supported.initializeNewSession();
expect(supported.capabilities.supportsMcpServers).toBe(true);
expect(supported.capabilities.supportsHttpMcpServers).toBe(true);
expect(newSession).toHaveBeenLastCalledWith({
cwd: "/tmp/paseo-acp-test",
mcpServers: [
{
type: "http",
name: "paseo",
url: "http://127.0.0.1:6767/mcp/agents?callerAgentId=agent-1",
headers: [],
},
{ name: "local", command: "node", args: ["mcp.js"], env: [] },
],
});
});
test("summarizes JSON-RPC error details without stringifying objects", () => {
const summary = summarizeACPRequestError(
new RequestError(-32603, "Internal error", {
@@ -2014,7 +2014,7 @@ export class ACPAgentClient implements AgentClient {
export class ACPAgentSession implements AgentSession, ACPClient {
readonly provider: string;
readonly capabilities: AgentCapabilityFlags;
private readonly baseCapabilities: AgentCapabilityFlags;
private readonly logger: Logger;
private readonly runtimeSettings?: ProviderRuntimeSettings;
@@ -2111,7 +2111,7 @@ export class ACPAgentSession implements AgentSession, ACPClient {
this.interruptGraceMs = options.interruptGraceMs ?? ACP_INTERRUPT_GRACE_MS;
this.interruptKillGraceMs = options.interruptKillGraceMs ?? ACP_INTERRUPT_KILL_GRACE_MS;
this.terminateProcess = options.terminateProcess ?? terminateWithTreeKill;
this.capabilities = options.capabilities;
this.baseCapabilities = { ...options.capabilities };
this.logger = options.logger.child({ module: "agent", provider: options.provider });
this.runtimeSettings = options.runtimeSettings;
this.defaultCommand = options.defaultCommand;
@@ -2149,6 +2149,15 @@ export class ACPAgentSession implements AgentSession, ACPClient {
this.extensionCommandsParser = options.extensionCommandsParser;
}
get capabilities(): AgentCapabilityFlags {
return {
...this.baseCapabilities,
supportsHttpMcpServers:
this.baseCapabilities.supportsMcpServers &&
this.agentCapabilities?.mcpCapabilities?.http !== false,
};
}
get id(): string | null {
return this.sessionId;
}
@@ -3558,7 +3567,14 @@ export class ACPAgentSession implements AgentSession, ACPClient {
}
private acpMcpServers(): McpServer[] {
return this.capabilities.supportsMcpServers ? normalizeMcpServers(this.config.mcpServers) : [];
if (!this.baseCapabilities.supportsMcpServers) {
return [];
}
const servers = normalizeMcpServers(this.config.mcpServers);
if (this.agentCapabilities?.mcpCapabilities?.http === false) {
return servers.filter((server) => !("type" in server && server.type === "http"));
}
return servers;
}
private applySessionState(response: SessionStateResponse): void {
@@ -3619,9 +3635,7 @@ export class ACPAgentSession implements AgentSession, ACPClient {
);
}
}
if (this.config.thinkingOptionId && this.config.thinkingOptionId !== this.thinkingOptionId) {
await this.setThinkingOption(this.config.thinkingOptionId);
}
await this.applyConfiguredThinkingOption();
const configuredFeatureValues = this.config.providerOptions ?? {};
for (const featureOption of this.configFeatureOptions) {
if (!Object.prototype.hasOwnProperty.call(configuredFeatureValues, featureOption.id)) {
@@ -3644,6 +3658,41 @@ export class ACPAgentSession implements AgentSession, ACPClient {
this.openOptionsPatch = this.featureDifferences(configuredFeatureValues);
}
private async applyConfiguredThinkingOption(): Promise<void> {
if (this.initialHandle) {
// Restoring the saved mode or model can move the level, and those writes do not record it.
// Live switches keep their own behavior (#10336).
this.thinkingOptionId =
deriveCurrentConfigValue(this.configOptions, "thought_level") ?? this.thinkingOptionId;
}
const requested = this.config.thinkingOptionId;
if (!requested || requested === this.thinkingOptionId) {
return;
}
try {
await this.setThinkingOption(requested);
} catch (error) {
if (!this.initialHandle || this.thinkingOptionWriter || !isACPInvalidParams(error)) {
throw error;
}
const option = findSelectConfigOption({
configOptions: this.configOptions,
category: "thought_level",
});
if (!option || findSelectConfigChoice({ option, value: requested })) {
throw error;
}
this.logger.warn(
{ requested, current: this.thinkingOptionId, model: this.currentModel },
"Saved ACP thinking option is unavailable on resume; keeping the provider's current value",
);
}
}
/**
* A stored feature value is a preference carried over from whichever model the user
* last configured, so the session it lands on may have no such option. Paseo's own
@@ -449,7 +449,11 @@ describe("ClaudeAgentSession persisted subagent replay", () => {
describe("a background subagent", () => {
// Shapes recorded from Claude Code 2.1.x: the launch returns at once with an async result,
// and a child stopped by an interrupt ends on the interrupt placeholder, not an end_turn.
function backgroundLaunch({ toolUseId = TOOL_USE_ID, agentId = AGENT_ID } = {}): string[] {
function backgroundLaunch({
toolUseId = TOOL_USE_ID,
agentId = AGENT_ID,
name,
}: { toolUseId?: string; agentId?: string; name?: string } = {}): string[] {
return [
parentEntry([
{
@@ -458,6 +462,7 @@ describe("ClaudeAgentSession persisted subagent replay", () => {
name: "Agent",
input: {
subagent_type: "general-purpose",
...(name ? { name } : {}),
description: "probe sleeper",
run_in_background: true,
},
@@ -744,6 +749,94 @@ describe("ClaudeAgentSession persisted subagent replay", () => {
expect(upserts(await replayDescriptors()).at(-1)).toMatchObject({ status: "completed" });
});
test.each([
{ history: "with the launch result", hasLaunchResult: true, hasStop: false },
{ history: "after a recorded stop", hasLaunchResult: true, hasStop: true },
{ history: "with only the launch sidecar", hasLaunchResult: false, hasStop: false },
])("completes a SendMessage-resumed child $history", async ({ hasLaunchResult, hasStop }) => {
const launch = hasLaunchResult ? backgroundLaunch() : backgroundLaunch().slice(0, 1);
const prior = hasStop
? [
taskNotification({
status: "stopped",
form: "queue-operation",
includeToolUseId: false,
}),
]
: [];
const resumeToolId = "toolu_resume";
const completion = taskNotification({ status: "completed", form: "queue-operation" }).replace(
TOOL_USE_ID,
resumeToolId,
);
writeSession({
parentLines: [
...launch,
...prior,
parentEntry([
{
type: "tool_use",
id: resumeToolId,
name: "SendMessage",
input: { to: AGENT_ID, message: "Continue the task." },
},
]),
completion,
],
meta: hasLaunchResult ? null : JSON.stringify({ toolUseId: TOOL_USE_ID, finished: true }),
sidechainLines: [sidechainEntry({ stopReason: "tool_use" })],
});
expect(upserts(await replayDescriptors()).at(-1)).toMatchObject({
id: TOOL_USE_ID,
status: "completed",
});
});
test("completes a child resumed by name through SendMessage after a recorded stop", async () => {
const name = "probe-sleeper";
const resumeToolId = "toolu_resume";
writeSession({
parentLines: [
...backgroundLaunch({ name }),
taskNotification({ status: "stopped", form: "queue-operation", includeToolUseId: false }),
parentEntry([
{
type: "tool_use",
id: resumeToolId,
name: "SendMessage",
input: { to: name, message: "Continue the task." },
},
]),
JSON.stringify({
type: "user",
message: {
role: "user",
content: [
{
type: "tool_result",
tool_use_id: resumeToolId,
content: [{ type: "text", text: "Message delivered." }],
},
],
},
toolUseResult: { success: true, resumedAgentId: AGENT_ID },
}),
taskNotification({ status: "completed", form: "queue-operation" }).replace(
TOOL_USE_ID,
resumeToolId,
),
taskNotification({ status: "completed" }).replace(TOOL_USE_ID, resumeToolId),
],
meta: null,
sidechainLines: [sidechainEntry({ stopReason: "tool_use" })],
});
const descriptors = upserts(await replayDescriptors());
for (const descriptor of descriptors) expect(descriptor.id).toBe(TOOL_USE_ID);
expect(descriptors.at(-1)).toMatchObject({ id: TOOL_USE_ID, status: "completed" });
});
test("honors a later task-only stopped notification after a tool-linked completion", async () => {
writeSession({
parentLines: [
@@ -6193,7 +6193,15 @@ class ClaudeAgentSession implements AgentSession {
private async ingestPersistedSidechains(
history: ClaudeReplayHistory,
): Promise<ClaudeReplayOwnership> {
const parentFacts = await readClaudeReplayParentFacts(history.parentEntries);
const sidecarToolCallIdsByTaskId = new Map<string, string>();
for (const { agentId, meta } of history.subagents) {
const toolCallId = meta?.toolUseId?.trim();
if (toolCallId) sidecarToolCallIdsByTaskId.set(agentId, toolCallId);
}
const parentFacts = await readClaudeReplayParentFacts(
history.parentEntries,
sidecarToolCallIdsByTaskId,
);
// Replay produces the same observations the live task protocol produces, then folds them
// with the same function, so identity and status are derived once for both paths.
@@ -6201,7 +6209,10 @@ class ClaudeAgentSession implements AgentSession {
for (const subagent of history.subagents) {
subagents.push({
...subagent,
parentFacts: await readClaudeReplayParentFacts(subagent.entries),
parentFacts: await readClaudeReplayParentFacts(
subagent.entries,
sidecarToolCallIdsByTaskId,
),
});
}
const subagentReplay = await observeReplaySubagents({
@@ -7083,12 +7094,28 @@ function labelReplayedSubagentCard(
*/
async function readClaudeReplayParentFacts(
entries: Iterable<ClaudeHistoryEntry> | AsyncIterable<ClaudeHistoryEntry>,
sidecarToolCallIdsByTaskId: ReadonlyMap<string, string>,
): Promise<ClaudeReplayParentFacts> {
const toolCalls = new Map<string, { title?: string; description?: string }>();
const linksByAgentId = new Map<string, { toolCallId: string }>();
const resumeTargetsByToolCallId = new Map<string, string>();
const outcomes: Map<string, { status: ProviderSubagentStatus }> = new Map();
const resolveLaunchToolCallId = (taskId: string): string | undefined => {
const sidecarToolCallId = sidecarToolCallIdsByTaskId.get(taskId);
return sidecarToolCallId && toolCalls.has(sidecarToolCallId)
? sidecarToolCallId
: linksByAgentId.get(taskId)?.toolCallId;
};
for await (const entry of entries) {
for (const notificationOutcome of readClaudeReplayNotificationOutcomes(entry, linksByAgentId)) {
const notificationOutcomes = readClaudeReplayNotificationOutcomes(
entry,
linksByAgentId,
resumeTargetsByToolCallId,
resolveLaunchToolCallId,
);
for (const notificationOutcome of notificationOutcomes) {
outcomes.set(notificationOutcome.toolCallId, { status: notificationOutcome.status });
}
const content = toObjectRecord(entry.message)?.content;
@@ -7097,13 +7124,20 @@ async function readClaudeReplayParentFacts(
const block = toObjectRecord(value);
const declaration = readClaudeReplayTaskDeclaration(entry.type, block);
if (declaration) toolCalls.set(declaration.id, declaration.identity);
const resume = readClaudeReplayResume(entry.type, block);
if (resume) resumeTargetsByToolCallId.set(resume.id, resume.target);
if (
entry.type !== "user" ||
block?.type !== "tool_result" ||
typeof block.tool_use_id !== "string"
)
continue;
if (toObjectRecord(entry.toolUseResult)?.status !== "async_launched")
const result = toObjectRecord(entry.toolUseResult);
const resumedTaskId = readClaudeReplayResumedTaskId(block, result);
if (resumedTaskId && resumeTargetsByToolCallId.has(block.tool_use_id)) {
resumeTargetsByToolCallId.set(block.tool_use_id, resumedTaskId);
}
if (result?.status !== "async_launched")
outcomes.set(block.tool_use_id, {
status: block.is_error === true ? "failed" : "completed",
});
@@ -7125,6 +7159,8 @@ async function readClaudeReplayParentFacts(
function* readClaudeReplayNotificationOutcomes(
entry: ClaudeHistoryEntry,
linksByAgentId: ReadonlyMap<string, { toolCallId: string }>,
resumeTargetsByToolCallId: ReadonlyMap<string, string>,
resolveLaunchToolCallId: (taskId: string) => string | undefined,
): Generator<{ toolCallId: string; status: ProviderSubagentStatus }> {
const notification = readTaskNotificationOutcomeFromHistoryRecord(entry);
if (!notification) return;
@@ -7132,7 +7168,11 @@ function* readClaudeReplayNotificationOutcomes(
if (!status) return;
if (notification.toolUseId) {
yield { toolCallId: notification.toolUseId, status };
// A resumed child keeps its task ID, but Claude reports its outcome under the SendMessage call.
const taskId = resumeTargetsByToolCallId.get(notification.toolUseId);
const launchToolCallId =
taskId && taskId === notification.taskIds[0] ? resolveLaunchToolCallId(taskId) : undefined;
yield { toolCallId: launchToolCallId ?? notification.toolUseId, status };
return;
}
// Stopped tasks can omit tool-use-id; their launch results already link the native IDs.
@@ -7142,6 +7182,30 @@ function* readClaudeReplayNotificationOutcomes(
}
}
function readClaudeReplayResume(
entryType: unknown,
block: Record<string, unknown> | undefined,
): { id: string; target: string } | null {
if (
entryType !== "assistant" ||
block?.type !== "tool_use" ||
block.name !== "SendMessage" ||
typeof block.id !== "string"
) {
return null;
}
const target = readNonEmptyString(toObjectRecord(block.input)?.to);
return target ? { id: block.id, target } : null;
}
function readClaudeReplayResumedTaskId(
block: Record<string, unknown>,
result: Record<string, unknown> | undefined,
): string | null {
if (block.is_error === true || result?.success !== true) return null;
return readNonEmptyString(result.resumedAgentId);
}
function readClaudeReplayTaskDeclaration(
entryType: unknown,
block: Record<string, unknown> | undefined,
@@ -1878,6 +1878,38 @@ describe("Codex app-server provider", () => {
}
});
test("auto-approves paseo speak tool during active voice sessions without restricting enabled_tools", async () => {
const appServer = createFakeCodexAppServer();
const session = await createProviderWithFakeAppServer(appServer).createSession(
createConfig({
modeId: "auto",
mcpServers: {
paseo: { type: "http", url: "http://127.0.0.1:6767/mcp/agents?callerAgentId=agent-1" },
},
}),
{ voiceToolsEnabled: true },
);
try {
await session.startTurn("say hello");
const threadStart = appServer.requests().find((req) => req.method === "thread/start");
const startConfig = (threadStart?.params as { config?: Record<string, unknown> } | undefined)
?.config;
expect(startConfig).toEqual({
"mcp_servers.paseo": {
url: "http://127.0.0.1:6767/mcp/agents?callerAgentId=agent-1",
tools: { speak: { approval_mode: "approve" } },
},
});
expect(startConfig).not.toHaveProperty("mcp_servers");
expect(startConfig?.["mcp_servers.paseo"]).not.toHaveProperty("enabled_tools");
expect(startConfig?.["mcp_servers.paseo"]).not.toHaveProperty("default_tools_approval_mode");
appServer.completeTurn();
appServer.assertNoErrors();
} finally {
await session.close();
}
});
test("preapproves only granted tools on the injected Codex MCP server", async () => {
const session = createSession({
modeId: undefined,
@@ -144,10 +144,12 @@ import {
} from "../provider-notices.js";
import type { WorkspaceGitService } from "../../workspace-git-service.js";
import {
applyCodexMcpToolApproval,
applyCodexToolPolicy,
CodexProviderOptionsSchema,
type CodexProviderOptions,
} from "./codex/options.js";
import { PASEO_MCP_SERVER_NAME } from "../runtime-mcp-config.js";
function assertChildWithPipes(
child: ChildProcess,
@@ -353,6 +355,7 @@ interface CodexAppServerAgentDeps {
extends: string;
};
customCodexConfig?: CodexCustomProviderConfig | null;
voiceToolsEnabled?: boolean;
// The CODEX_HOME the session's app-server runs with; prompts and skills are read from it.
codexHome?: string;
_createCodexClient?: (
@@ -6166,7 +6169,10 @@ export class CodexAppServerAgentSession implements AgentSession {
}
}
}
const configured = applyCodexToolPolicy(innerConfig, this.config.toolPolicy);
let configured = applyCodexToolPolicy(innerConfig, this.config.toolPolicy);
if (this.deps.voiceToolsEnabled && this.config.mcpServers?.[PASEO_MCP_SERVER_NAME]) {
configured = applyCodexMcpToolApproval(configured, PASEO_MCP_SERVER_NAME, "speak");
}
return Object.keys(configured).length > 0 ? configured : null;
}
@@ -8423,7 +8429,11 @@ export class CodexAppServerAgentClient implements AgentClient {
null,
this.logger,
async () => spawn(),
{ ...this.sessionDeps(launchContext?.env), environment },
{
...this.sessionDeps(launchContext?.env),
environment,
...(launchContext?.voiceToolsEnabled ? { voiceToolsEnabled: true } : {}),
},
options?.persistSession === false,
goalsEnabled,
autoReviewEnabled,
@@ -8461,7 +8471,11 @@ export class CodexAppServerAgentClient implements AgentClient {
handle,
this.logger,
async () => spawn(),
{ ...this.sessionDeps(launchContext?.env), environment },
{
...this.sessionDeps(launchContext?.env),
environment,
...(launchContext?.voiceToolsEnabled ? { voiceToolsEnabled: true } : {}),
},
false,
goalsEnabled,
autoReviewEnabled,
@@ -133,6 +133,49 @@ export function applyCodexToolPolicy(
return next;
}
/**
* Auto-approves a single tool on an already-configured Codex MCP server without
* narrowing `enabled_tools` or changing `default_tools_approval_mode`, so other
* tools on the same server keep their existing visibility and approval policy.
*/
export function applyCodexMcpToolApproval(
config: Record<string, unknown>,
server: string,
tool: string,
): Record<string, unknown> {
const approveServerTool = (serverConfig: Record<string, unknown>): Record<string, unknown> => {
const existingTools = readRecord(serverConfig.tools);
let enabledTools: unknown[] | undefined;
if (Array.isArray(serverConfig.enabled_tools)) {
enabledTools = serverConfig.enabled_tools.includes(tool)
? serverConfig.enabled_tools
: [...serverConfig.enabled_tools, tool];
}
return {
...serverConfig,
...(enabledTools ? { enabled_tools: enabledTools } : {}),
tools: {
...existingTools,
[tool]: { approval_mode: "approve" },
},
};
};
if ("mcp_servers" in config) {
const mcpServers = readRecord(config.mcp_servers);
if (!(server in mcpServers)) return config;
mcpServers[server] = approveServerTool(readRecord(mcpServers[server]));
return { ...config, mcp_servers: mcpServers };
}
const key = `${MCP_SERVERS_PREFIX}${server}`;
if (!(key in config)) return config;
return {
...config,
[key]: approveServerTool(readRecord(config[key])),
};
}
function readRecord(value: unknown): Record<string, unknown> {
return value != null && typeof value === "object" && !Array.isArray(value) ? { ...value } : {};
}
@@ -1343,7 +1343,6 @@ export class PiRpcAgentSession implements AgentSession {
if (this.closed) throw new Error("Pi session is closed");
if (this.activeTurnId !== turnId) return { turnId };
this.activeNoTurnPromptText = payload.text;
const shouldProbeForNoTurnPrompt = this.parseSlashCommandInput(payload.text) !== null;
void (async () => {
try {
@@ -1369,7 +1368,11 @@ export class PiRpcAgentSession implements AgentSession {
await this.completeNoTurnPrompt(turnId);
return;
}
if (agentInvoked === undefined && shouldProbeForNoTurnPrompt) {
// Pi can acknowledge a prompt as handled even when the extension starts a run.
if (
agentInvoked === undefined &&
(ack.handledByExtension || this.parseSlashCommandInput(payload.text) !== null)
) {
await this.completePromptIfHandledWithoutTurn(turnId);
}
} catch (error) {
@@ -4,9 +4,11 @@ import path from "node:path";
import type { ChildProcessWithoutNullStreams } from "node:child_process";
import { EventEmitter } from "node:events";
import { PassThrough } from "node:stream";
import { setImmediate as waitForImmediate } from "node:timers/promises";
import pino from "pino";
import { describe, expect, test, vi } from "vitest";
import { describe, expect, onTestFinished, test, vi } from "vitest";
import { PiRpcAgentClient } from "./agent.js";
import { PiCliRuntime } from "./cli-runtime.js";
import type { PiRuntimeLaunch } from "./runtime.js";
@@ -495,6 +497,97 @@ describe("PiCliRuntime", () => {
expect(command.images).toBeUndefined();
});
test.each([
{ disposition: "started", agentInvoked: true },
{ disposition: "queued", agentInvoked: true },
])(
"maps a $disposition prompt disposition to agentInvoked $agentInvoked",
async ({ disposition, agentInvoked }) => {
const child = createPiChild();
replyToCommands(child, (command) => (command.type === "prompt" ? { disposition } : {}));
const session = await createRuntime(child).startSession({ cwd: "/workspace/project" });
await expect(session.prompt("summarize README.md")).resolves.toMatchObject({ agentInvoked });
},
);
test("preserves an explicit agentInvoked result in a prompt response", async () => {
const child = createPiChild();
replyToCommands(child, () => ({ disposition: "started", agentInvoked: false }));
const session = await createRuntime(child).startSession({ cwd: "/workspace/project" });
await expect(session.prompt("hello")).resolves.toEqual({
requestId: expect.any(String),
agentInvoked: false,
});
});
test("completes when an input extension handles a prompt without a model run", async () => {
const child = createPiChild();
replyToCommands(child, (command) => {
if (command.type === "prompt") {
const notification = {
type: "extension_ui_request",
id: "handled",
method: "notify",
message: "Handled by extension",
};
child.stdout.write(`${JSON.stringify(notification)}\n`);
return { disposition: "handled" };
}
return { sessionId: "pi-session-1", isStreaming: false };
});
const client = new PiRpcAgentClient({
logger: pino({ level: "silent" }),
runtime: createRuntime(child),
});
const session = await client.createSession({ provider: "pi", cwd: "/workspace/project" });
onTestFinished(() => session.close());
await expect(session.run("hello")).resolves.toMatchObject({
timeline: expect.arrayContaining([
expect.objectContaining({ type: "notification", message: "Handled by extension" }),
]),
});
});
test("waits for the reply when a handled slash command starts a model run", async () => {
const child = createPiChild();
let isStreaming = false;
replyToCommands(child, (command) => {
if (command.type === "prompt") {
isStreaming = true;
return { disposition: "handled" };
}
return { sessionId: "pi-session-1", isStreaming };
});
const client = new PiRpcAgentClient({
logger: pino({ level: "silent" }),
runtime: createRuntime(child),
});
const session = await client.createSession({ provider: "pi", cwd: "/workspace/project" });
onTestFinished(() => session.close());
const reply = session.run("/ask hello");
// Pi acknowledges the command while its model run is starting, before agent_start.
await waitForImmediate();
await waitForImmediate();
child.stdout.write(`${JSON.stringify({ type: "agent_start" })}\n`);
const message = { role: "assistant", content: [{ type: "text", text: "Hello" }] };
const update = {
type: "message_update",
message,
assistantMessageEvent: { type: "text_delta", delta: "Hello" },
};
child.stdout.write(`${JSON.stringify(update)}\n`);
child.stdout.write(
`${JSON.stringify({ type: "agent_end", messages: [message], willRetry: false })}\n`,
);
child.stdout.write(`${JSON.stringify({ type: "agent_settled" })}\n`);
await expect(reply).resolves.toMatchObject({ finalText: "Hello" });
});
test("sends the clear_queue RPC frame", async () => {
const child = createPiChild();
replyToCommands(child, () => ({}));
@@ -137,10 +137,16 @@ class PiCliRuntimeSession implements PiRuntimeSession {
});
const data = await promise;
if (typeof data === "object" && data !== null && !Array.isArray(data)) {
const { agentInvoked } = data as Record<string, unknown>;
const { agentInvoked, disposition } = data as Record<string, unknown>;
if (typeof agentInvoked === "boolean") {
return { requestId, agentInvoked };
}
if (disposition === "handled") {
return { requestId, handledByExtension: true };
}
if (disposition === "started" || disposition === "queued") {
return { requestId, agentInvoked: true };
}
}
return { requestId };
}
@@ -5,13 +5,10 @@ export interface PiImageContent {
data: string;
mimeType: string;
}
export interface PiPromptAck {
agentInvoked?: boolean;
}
export interface PiPromptAck {
requestId?: string;
agentInvoked?: boolean;
handledByExtension?: true;
}
export interface PiTextContent {
+41 -26
View File
@@ -102,7 +102,7 @@ import { formatAttachmentContentDisposition } from "./file-download/content-disp
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";
import { createSpeechService } from "./speech/speech-runtime.js";
import { createSpeechService, type SpeechService } from "./speech/speech-runtime.js";
import { createSpeechSettingsOwner } from "./speech/speech-settings.js";
import { AgentManager } from "./agent/agent-manager.js";
import { AgentStorage } from "./agent/agent-storage.js";
@@ -133,7 +133,7 @@ import {
type ResolvedDaemonSettings,
type CliConfigOverrides,
} from "./config.js";
import { resolvePaseoToolPolicy } from "./agent/paseo-tool-policy.js";
import { isPaseoToolPolicyEnabled, resolvePaseoToolPolicy } from "./agent/paseo-tool-policy.js";
import { BrowserToolsBroker } from "./browser-tools/broker.js";
import { DaemonConfigBrowserToolsPolicy } from "./browser-tools/policy.js";
import { WorkspaceGitServiceImpl } from "./workspace-git-service.js";
@@ -441,6 +441,7 @@ export interface PaseoDaemon {
export interface PaseoDaemonDependencies {
builtinPlugins?: BuiltinPluginLoader;
lazyTerminalWorker?: boolean;
speechService?: SpeechService;
getTailscaleNetwork?: () => TailscaleNetwork;
hubRelationshipRemote?: HubRelationshipRemote;
hubRelationshipClock?: HubRelationshipClock;
@@ -586,11 +587,13 @@ export async function createPaseoDaemon(
const elapsed = () => `${(performance.now() - bootstrapStart).toFixed(0)}ms`;
const daemonVersion = config.daemonVersion ?? resolveDaemonVersion(import.meta.url);
const initialMutableConfig = createInitialMutableDaemonConfig(config);
const speechService = createSpeechService({
logger,
openaiConfig: config.openai,
speechConfig: config.speech,
});
const speechService =
dependencies.speechService ??
createSpeechService({
logger,
openaiConfig: config.openai,
speechConfig: config.speech,
});
logger.info({ elapsed: elapsed() }, "Speech service created");
const daemonConfigStore = new DaemonConfigStore(config.paseoHome, initialMutableConfig, logger, {
relayEnabledMutable: config.relayEnabledMutable ?? true,
@@ -993,6 +996,8 @@ export async function createPaseoDaemon(
const git = daemonConfigStore.get().git;
if (git) configureGitProcessPolicy(git);
});
const hasActiveVoiceTools = (agentId: string): boolean =>
wsServer?.resolveVoiceCallerContext(agentId)?.enableVoiceTools === true;
const initialAgentManagerState = providerSnapshotManager.getAgentManagerProviderState();
const agentManager = new AgentManager({
pluginLifecycle: pluginRuntime,
@@ -1005,6 +1010,7 @@ export async function createPaseoDaemon(
workspaceGitService.onWorkspaceStateMayHaveChanged(cwd);
},
mcpAuthToken: agentMcpAuthToken,
hasActiveVoiceTools,
resolvePaseoToolPolicy: (provider) =>
resolvePaseoToolPolicy(provider, daemonConfigStore.get().providers),
logger,
@@ -1644,7 +1650,6 @@ export async function createPaseoDaemon(
setAgentProviderToolsEnabled(config.mcpEnabled !== false && config.mcpInjectIntoAgents !== false);
let mcpEnabled = config.mcpEnabled ?? true;
let agentMcpBaseUrl: string | null = null;
{
const agentMcpRoute = "/mcp/agents";
@@ -1653,14 +1658,20 @@ export async function createPaseoDaemon(
// 2025-era clients through its stateless legacy fallback. No per-session
// state is retained between requests, matching the previous
// `sessionIdGenerator: undefined` transport.
const createAgentMcpSession = async (callerAgentId?: string) => {
if (callerAgentId) await agentManager.refreshPluginTools(callerAgentId);
const createAgentMcpSession = async (
callerAgentId?: string,
options?: { voiceOnly?: boolean },
) => {
if (callerAgentId && !options?.voiceOnly) {
await agentManager.refreshPluginTools(callerAgentId);
}
const agentMcpServer = await createAgentMcpServer(
createAgentToolHostDependencies({
callerAgentId,
paseoToolPolicy: callerAgentId
? agentManager.getPaseoToolPolicy(callerAgentId)
: undefined,
voiceOnly: options?.voiceOnly,
}),
);
@@ -1677,7 +1688,17 @@ export async function createPaseoDaemon(
req: express.Request,
res: express.Response,
): Promise<void> => {
if (!mcpEnabled) {
const callerAgentIdRaw = req.query.callerAgentId;
let callerAgentId: string | undefined;
if (typeof callerAgentIdRaw === "string") {
callerAgentId = callerAgentIdRaw;
} else if (Array.isArray(callerAgentIdRaw) && typeof callerAgentIdRaw[0] === "string") {
callerAgentId = callerAgentIdRaw[0];
}
const voiceActive = Boolean(callerAgentId && hasActiveVoiceTools(callerAgentId));
const isActiveLoopbackVoiceRequest =
voiceActive && isLoopbackRemoteAddress(req.socket.remoteAddress);
if (!mcpEnabled && !isActiveLoopbackVoiceRequest) {
res.status(404).json({ error: "Agent MCP endpoint disabled" });
return;
}
@@ -1722,14 +1743,11 @@ export async function createPaseoDaemon(
});
return;
}
const callerAgentIdRaw = req.query.callerAgentId;
let callerAgentId: string | undefined;
if (typeof callerAgentIdRaw === "string") {
callerAgentId = callerAgentIdRaw;
} else if (Array.isArray(callerAgentIdRaw) && typeof callerAgentIdRaw[0] === "string") {
callerAgentId = callerAgentIdRaw[0];
}
const { handler } = await createAgentMcpSession(callerAgentId);
const policy = callerAgentId ? agentManager.getPaseoToolPolicy(callerAgentId) : undefined;
const generalPaseoToolsEnabled =
mcpEnabled && agentManager.isPaseoToolsEnabled() && isPaseoToolPolicyEnabled(policy);
const voiceOnly = voiceActive && !generalPaseoToolsEnabled;
const { handler } = await createAgentMcpSession(callerAgentId, { voiceOnly });
try {
// express.json() already consumed the stream, so hand the parsed body over.
await toNodeHandler(handler)(
@@ -1830,21 +1848,18 @@ export async function createPaseoDaemon(
);
}
const mcpBaseUrl = loopbackAgentEndpoint.getMcpBaseUrl();
agentMcpBaseUrl =
!mcpEnabled || config.mcpInjectIntoAgents === false ? null : mcpBaseUrl;
agentManager.setMcpBaseUrl(agentMcpBaseUrl);
agentManager.setMcpBaseUrl(mcpBaseUrl);
agentManager.setPaseoToolsEnabled(mcpEnabled && config.mcpInjectIntoAgents !== false);
daemonConfigStore.onFieldChange("mcp.enabled", (value) => {
mcpEnabled = value !== false;
const inject = daemonConfigStore.get().mcp.injectIntoAgents !== false;
agentManager.setMcpBaseUrl(mcpEnabled && inject ? mcpBaseUrl : null);
agentManager.setPaseoToolsEnabled(mcpEnabled && inject);
setAgentProviderToolsEnabled(mcpEnabled && inject);
});
daemonConfigStore.onFieldChange("mcp.injectIntoAgents", (value) => {
agentManager.setMcpBaseUrl(mcpEnabled && value ? mcpBaseUrl : null);
agentManager.setPaseoToolsEnabled(mcpEnabled && value !== false);
setAgentProviderToolsEnabled(mcpEnabled && value !== false);
const inject = value !== false;
agentManager.setPaseoToolsEnabled(mcpEnabled && inject);
setAgentProviderToolsEnabled(mcpEnabled && inject);
});
daemonConfigStore.onFieldChange("appendSystemPrompt", (value) => {
agentManager.setAppendSystemPrompt(typeof value === "string" ? value : "");
@@ -0,0 +1,104 @@
// ACP peer that accepts a thinking level on creation but rejects it after load.
const readline = require("node:readline");
const sessionId = "thinking-resume-session";
let model = "startup-model";
let effort = "low";
let mode = "agent";
let loaded = false;
const send = (message) =>
process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...message }) + "\n");
function select(id, category, currentValue, values) {
return {
id,
name: id,
category,
type: "select",
currentValue,
options: values.map((value) => ({ value, name: value })),
};
}
function configOptions() {
return [
select("mode", "mode", mode, ["agent", "plan"]),
select("model", "model", model, ["startup-model", "second-model"]),
select(
"effort",
"thought_level",
effort,
loaded && model === "second-model"
? ["minimal", "low", "medium", "high", "xhigh"]
: ["low", "high", "max"],
),
];
}
function assistantMessage(text) {
send({
method: "session/update",
params: {
sessionId,
update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text } },
},
});
}
readline.createInterface({ input: process.stdin }).on("line", (line) => {
const { id, method, params } = JSON.parse(line);
if (id === undefined) return;
let result;
switch (method) {
case "initialize":
result = {
protocolVersion: 1,
agentCapabilities: { loadSession: true, sessionCapabilities: { close: {} } },
};
break;
case "session/new":
result = { sessionId, configOptions: configOptions() };
break;
case "session/load":
loaded = true;
model = process.env.ACP_TEST_LOAD_MODEL;
effort = model === "second-model" && !process.env.ACP_TEST_SAVED_MODE ? "high" : "low";
assistantMessage("Response from the saved session");
result = { configOptions: configOptions() };
break;
case "session/set_config_option":
if (params.configId === "model") {
model = params.value;
if (loaded && model === "second-model") effort = "high";
} else if (params.configId === "mode") {
mode = params.value;
if (loaded && mode === process.env.ACP_TEST_SAVED_MODE) effort = "high";
} else if (loaded && params.value === "max") {
send({
id,
error: {
code: -32602,
message: "Invalid params",
data: "This model does not support that thinking level",
},
});
return;
} else {
effort = params.value;
}
result = { configOptions: configOptions() };
break;
case "session/prompt":
assistantMessage("Response from the saved session");
result = { stopReason: "end_turn" };
break;
case "session/close":
result = {};
break;
default:
send({ id, error: { code: -32601, message: "Method not found" } });
return;
}
send({ id, result });
});
@@ -576,3 +576,114 @@ test("bundled goose lists configured providers and switches models across provid
await rm(root, { recursive: true, force: true });
}
}, 60_000);
// Saves a chat with a thinking level the fixture rejects after load, then restarts the daemon.
async function withRestartedThinkingChat(
{ loadModel, savedMode }: { loadModel: string; savedMode?: string },
run: (client: DaemonClient, agentId: string) => Promise<void>,
): Promise<void> {
const root = await mkdtemp(path.join(os.tmpdir(), "paseo-acp-thinking-resume-"));
const options = {
paseoHomeRoot: root,
staticDir: path.join(root, "static"),
cleanup: false,
mcpEnabled: false,
pluginsEnabled: false,
providerOverrides: {
"thinking-fixture": {
extends: "acp" as const,
label: "Thinking fixture",
env: {
ACP_TEST_LOAD_MODEL: loadModel,
ACP_TEST_SAVED_MODE: savedMode ?? "",
},
command: [
process.execPath,
path.join(import.meta.dirname, "acp-thinking-resume-fixture.cjs"),
],
},
},
};
try {
const first = await createDaemonTestContext(options);
let agentId: string;
try {
const agent = await first.client.createAgent({
provider: "thinking-fixture",
cwd: root,
model: "second-model",
modeId: savedMode,
thinkingOptionId: "max",
});
agentId = agent.id;
expect(agent.thinkingOptionId).toBe("max");
await first.client.sendMessage(agentId, "Save this conversation");
expect((await first.client.waitForFinish(agentId, 10_000)).status).toBe("idle");
} finally {
await first.cleanup();
}
const restarted = await createDaemonTestContext(options);
try {
await run(restarted.client, agentId);
} finally {
await restarted.cleanup();
}
} finally {
await rm(root, { recursive: true, force: true });
}
}
test.each([
{ scenario: "the saved model loaded", loadModel: "second-model", savedMode: undefined },
{ scenario: "the saved model restored", loadModel: "startup-model", savedMode: undefined },
{ scenario: "the saved mode restored", loadModel: "second-model", savedMode: "plan" },
])(
"reopens an ACP chat with a rejected saved thinking level with $scenario",
async ({ loadModel, savedMode }) => {
await withRestartedThinkingChat({ loadModel, savedMode }, async (client, agentId) => {
const timeline = await client.fetchAgentTimeline(agentId, { limit: 40 });
expect(timeline.entries.map(({ item }) => item)).toContainEqual(
expect.objectContaining({
type: "assistant_message",
text: "Response from the saved session",
}),
);
expect((await client.fetchAgent(agentId))?.agent.runtimeInfo?.thinkingOptionId).toBe("high");
// Interactive writes still surface a provider rejection.
await expect(client.setAgentThinkingOption(agentId, "max")).rejects.toThrow("Invalid params");
await client.setAgentThinkingOption(agentId, "low");
expect((await client.fetchAgent(agentId))?.agent).toMatchObject({
thinkingOptionId: "low",
runtimeInfo: { thinkingOptionId: "low" },
});
});
},
60_000,
);
// The provider answers both live switches below with `high`. Publishing that value on an open
// chat belongs to #10336, so the picker keeps the level it had.
test("keeps the thinking level of a reopened ACP chat through live mode and model switches", async () => {
await withRestartedThinkingChat(
{ loadModel: "second-model", savedMode: "plan" },
async (client, agentId) => {
await client.setAgentThinkingOption(agentId, "low");
await client.setAgentMode(agentId, "agent");
await client.setAgentMode(agentId, "plan");
expect((await client.fetchAgent(agentId))?.agent).toMatchObject({
thinkingOptionId: "low",
runtimeInfo: { modeId: "plan", thinkingOptionId: "low" },
});
await client.setAgentModel(agentId, "startup-model");
await client.setAgentModel(agentId, "second-model");
expect((await client.fetchAgent(agentId))?.agent).toMatchObject({
thinkingOptionId: "low",
runtimeInfo: { model: "second-model", thinkingOptionId: "low" },
});
},
);
}, 60_000);
+2 -2
View File
@@ -1447,8 +1447,8 @@ export class Session {
agentStorage: this.agentStorage,
logger: this.sessionLogger,
}),
reloadAgentSession: (agentId, overrides) =>
this.agentManager.reloadAgentSession(agentId, overrides),
reloadAgentSession: (agentId, overrides, reloadOptions) =>
this.agentManager.reloadAgentSession(agentId, overrides, reloadOptions),
sendSpokenInput: async (agentId, text) => {
await this.handleSendAgentMessage(
agentId,
@@ -325,4 +325,94 @@ describe("VoiceSession streaming transcription", () => {
await voiceSession.cleanup();
});
test("rejects set_voice_mode and cleans up voice bridge when speak capability check fails", async () => {
const events: string[] = [];
const host = createFakeHost();
const reloadOptions: Array<unknown> = [];
host.reloadAgentSession = async (_agentId, _overrides, options) => {
reloadOptions.push(options);
throw new Error(
"Voice mode is unavailable for provider 'pi': the session does not expose Paseo's 'speak' tool",
);
};
const voiceSession = new VoiceSession({
host,
logger: pino({ level: "silent" }),
sessionId: "voice-capability-reject-test",
sttLanguage: "en",
tts: null,
stt: { id: "local", createSession: vi.fn(() => new FakeVoiceSttSession()) },
voice: {
turnDetection: {
id: "local",
createSession: vi.fn(() => new FakeVoiceTurnDetectionSession()),
},
},
voiceBridge: {
registerVoiceSpeakHandler: (id) => events.push(`register-speak:${id}`),
unregisterVoiceSpeakHandler: (id) => events.push(`unregister-speak:${id}`),
registerVoiceCallerContext: (id) => events.push(`register-ctx:${id}`),
unregisterVoiceCallerContext: (id) => events.push(`unregister-ctx:${id}`),
},
});
await voiceSession.handleSetVoiceMode(true, VOICE_AGENT_ID, "req-voice-1");
expect(reloadOptions).toEqual([{ requireVoiceSpeak: true }]);
expect(events).toEqual([
`register-speak:${VOICE_AGENT_ID}`,
`register-ctx:${VOICE_AGENT_ID}`,
`unregister-speak:${VOICE_AGENT_ID}`,
`unregister-ctx:${VOICE_AGENT_ID}`,
]);
expect(voiceSession.isActiveForAgent(VOICE_AGENT_ID)).toBe(false);
expect(host.emitted).toContainEqual({
type: "set_voice_mode_response",
payload: {
requestId: "req-voice-1",
enabled: false,
agentId: null,
accepted: false,
error:
"Voice mode is unavailable for provider 'pi': the session does not expose Paseo's 'speak' tool",
},
});
});
test("unregisters voice bridge before reloading when disabling voice mode", async () => {
const order: string[] = [];
const host = createFakeHost();
host.reloadAgentSession = async (agentId) => {
order.push(`reload:${agentId}`);
return { id: agentId } as unknown as ManagedAgent;
};
const voiceSession = new VoiceSession({
host,
logger: pino({ level: "silent" }),
sessionId: "voice-disable-order-test",
sttLanguage: "en",
tts: null,
stt: { id: "local", createSession: vi.fn(() => new FakeVoiceSttSession()) },
voice: {
turnDetection: {
id: "local",
createSession: vi.fn(() => new FakeVoiceTurnDetectionSession()),
},
},
voiceBridge: {
registerVoiceSpeakHandler: () => order.push("register-speak"),
unregisterVoiceSpeakHandler: () => order.push("unregister-speak"),
registerVoiceCallerContext: () => order.push("register-ctx"),
unregisterVoiceCallerContext: () => order.push("unregister-ctx"),
},
});
await voiceSession.handleSetVoiceMode(true, VOICE_AGENT_ID, "req-on");
order.length = 0;
await voiceSession.handleSetVoiceMode(false, VOICE_AGENT_ID, "req-off");
expect(order).toEqual(["unregister-speak", "unregister-ctx", `reload:${VOICE_AGENT_ID}`]);
});
});
@@ -125,6 +125,7 @@ export interface VoiceSessionHost {
reloadAgentSession(
agentId: string,
overrides: Partial<AgentSessionConfig>,
options?: { requireVoiceSpeak?: boolean },
): Promise<ManagedAgent>;
sendSpokenInput(agentId: string, text: string): Promise<void>;
interruptAgentIfRunning(agentId: string): Promise<void>;
@@ -513,7 +514,9 @@ export class VoiceSession {
{ agentId, elapsedMs: Date.now() - startedAt },
"enableVoiceModeForAgent.reloadAgentSession.start",
);
const refreshed = await this.host.reloadAgentSession(agentId, refreshOverrides);
const refreshed = await this.host.reloadAgentSession(agentId, refreshOverrides, {
requireVoiceSpeak: true,
});
this.sessionLogger.info(
{ agentId, refreshedAgentId: refreshed.id, elapsedMs: Date.now() - startedAt },
"enableVoiceModeForAgent.reloadAgentSession.done",
@@ -536,6 +539,9 @@ export class VoiceSession {
return;
}
this.unregisterVoiceSpeakHandler?.(agentId);
this.unregisterVoiceCallerContext?.(agentId);
if (restoreAgentConfig && this.voiceModeBaseConfig) {
const baseConfig = this.voiceModeBaseConfig;
try {
@@ -550,8 +556,6 @@ export class VoiceSession {
}
}
this.unregisterVoiceSpeakHandler?.(agentId);
this.unregisterVoiceCallerContext?.(agentId);
this.voiceModeBaseConfig = null;
this.voiceModeAgentId = null;
}
@@ -1215,6 +1215,7 @@ describe.skipIf(isPlatform("win32"))("terminal title", () => {
const env = buildTerminalEnvironment({
shell: "/bin/zsh",
env: {},
baseEnv: {
HOME: homeDir,
PATH: `${appDir}:${appDir}/usr/sbin:/usr/local/bin:/usr/bin:/bin`,
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/website",
"version": "0.18.1",
"version": "0.18.2",
"private": true,
"type": "module",
"scripts": {

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