Compare commits

...
Author SHA1 Message Date
paseo-bot[bot]andOuyang Xingyuan 8cc28cd78f fix(app): keep increment and decrement lines in Edit diffs
A changed line inside a hunk can start with the same marker as a file header. Use the hunk ranges to preserve those lines in tool output.

Co-authored-by: Ouyang Xingyuan <galaxyroaming@qq.com>
2026-11-30 06:46:36 +00:00
Ouyang Xingyuan c45689d1ba fix(server): compact oversized edit diffs before timeline budget truncation 2026-11-30 06:44:47 +00: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
81 changed files with 2845 additions and 283 deletions
+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))
@@ -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
+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"
+1 -1
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": [
@@ -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 };
@@ -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;
}
@@ -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);
}
@@ -62,6 +62,20 @@ describe("tool-call-parsers", () => {
expect(parsed.find((entry) => entry.type === "add")?.content).toBe("+new");
});
it("keeps changed lines that start with two diff markers", () => {
const parsed = parseUnifiedDiff(
["--- a/counter.ts", "+++ b/counter.ts", "@@ -1 +1 @@", "---counter;", "+++counter;"].join(
"\n",
),
);
expect(parsed).toEqual([
{ type: "header", content: "@@ -1 +1 @@" },
{ type: "remove", content: "---counter;" },
{ type: "add", content: "+++counter;" },
]);
});
it("keeps file headers in multi-file diffs", () => {
const parsed = parseUnifiedDiff(
[
+20 -14
View File
@@ -162,47 +162,53 @@ export function parseUnifiedDiff(diffText?: string): DiffLine[] {
const fileHeaders = lines.filter((line) => line.startsWith("diff --git "));
const hasMultipleFiles = fileHeaders.length > 1;
const diff: DiffLine[] = [];
let oldLinesRemaining = 0;
let newLinesRemaining = 0;
for (const line of lines) {
if (!line.length) {
diff.push({ type: "context", content: line });
if (line.startsWith("diff --git ")) {
oldLinesRemaining = 0;
newLinesRemaining = 0;
if (hasMultipleFiles) diff.push({ type: "header", content: line });
continue;
}
const isFileHeader = hasMultipleFiles && line.startsWith("diff --git ");
if (line.startsWith("@@") || isFileHeader) {
if (line.startsWith("@@")) {
const range = /^@@ -\d+(?:,(\d+))? \+\d+(?:,(\d+))? @@/.exec(line);
oldLinesRemaining = Number(range?.[1] ?? 1);
newLinesRemaining = Number(range?.[2] ?? 1);
diff.push({ type: "header", content: line });
continue;
}
const inHunk = oldLinesRemaining > 0 || newLinesRemaining > 0;
if (line.startsWith("+")) {
if (!line.startsWith("+++")) {
if (inHunk || !line.startsWith("+++")) {
diff.push({ type: "add", content: line });
newLinesRemaining--;
}
continue;
}
if (line.startsWith("-")) {
if (!line.startsWith("---")) {
if (inHunk || !line.startsWith("---")) {
diff.push({ type: "remove", content: line });
oldLinesRemaining--;
}
continue;
}
if (
line.startsWith("diff --git") ||
line.startsWith("index ") ||
line.startsWith("---") ||
line.startsWith("+++")
) {
continue;
}
if (line.startsWith("index ")) continue;
if (line.startsWith("\\ No newline")) {
diff.push({ type: "header", content: line });
continue;
}
if (line.startsWith(" ")) {
oldLinesRemaining--;
newLinesRemaining--;
}
diff.push({ type: "context", content: line });
}
+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",
+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);
+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 {
@@ -145,4 +145,153 @@ describe("agent timeline content", () => {
});
expect(limitAgentTimelineItemContent(item)).toBe(item);
});
test("preserves a late-file edit in oversized full-file oldString/newString payloads", () => {
const lines = Array.from(
{ length: 800 },
(_, index) => `export const row_${index} = "${"x".repeat(70)}";`,
);
const oldString = `${lines.join("\n")}\n`;
const updated = [...lines];
updated[760] = 'export const row_760 = "UPDATED_AT_LINE_761";';
const newString = `${updated.join("\n")}\n`;
expect(oldString.length).toBeGreaterThan(64 * 1024);
const item = limitAgentTimelineItemContent({
type: "tool_call",
callId: "late-edit",
name: "edit",
status: "completed",
error: null,
detail: {
type: "edit",
filePath: "/repo/src/theoryContentEn.ts",
oldString,
newString,
},
});
if (item.type !== "tool_call" || item.detail.type !== "edit") throw new Error("shape");
expect(item.detail.oldString).toContain("row_757");
expect(item.detail.oldString).toContain("row_760");
expect(item.detail.oldString).toContain("row_763");
expect(item.detail.newString).toContain("UPDATED_AT_LINE_761");
expect(item.detail.oldString).not.toContain("row_0");
expect(item.detail.oldString).not.toContain("…[truncated");
expect(item.detail.newString).not.toContain("…[truncated");
expect(serializedBytes(item)).toBeLessThanOrEqual(64 * 1024);
expect(AgentTimelineItemPayloadSchema.safeParse(item).success).toBe(true);
expect(limitAgentTimelineItemContent(item)).toBe(item);
});
test("compacts far-apart edits in an oversized file into a multi-hunk unifiedDiff", () => {
const lines = Array.from(
{ length: 900 },
(_, index) => `const entry_${index} = "${"y".repeat(70)}";`,
);
const oldString = `${lines.join("\n")}\n`;
const updated = [...lines];
updated[5] = 'const entry_5 = "EARLY_CHANGE";';
updated[850] = 'const entry_850 = "LATE_CHANGE";';
const newString = `${updated.join("\n")}\n`;
const item = limitAgentTimelineItemContent({
type: "tool_call",
callId: "scattered-edit",
name: "edit",
status: "completed",
error: null,
detail: {
type: "edit",
filePath: "/repo/src/large.ts",
oldString,
newString,
},
});
if (item.type !== "tool_call" || item.detail.type !== "edit") throw new Error("shape");
expect(item.detail.oldString).toBeUndefined();
expect(item.detail.newString).toBeUndefined();
expect(item.detail.unifiedDiff).toContain("@@ -3,7 +3,7 @@");
expect(item.detail.unifiedDiff).toContain('+const entry_5 = "EARLY_CHANGE";');
expect(item.detail.unifiedDiff).toContain("@@ -848,7 +848,7 @@");
expect(item.detail.unifiedDiff).toContain('+const entry_850 = "LATE_CHANGE";');
expect(serializedBytes(item)).toBeLessThanOrEqual(64 * 1024);
expect(AgentTimelineItemPayloadSchema.safeParse(item).success).toBe(true);
expect(limitAgentTimelineItemContent(item)).toBe(item);
});
test("collapses an identical oversized edit payload to empty strings", () => {
const text = Array.from({ length: 800 }, (_, i) => `line ${i}: ${"z".repeat(80)}`).join("\n");
const item = limitAgentTimelineItemContent({
type: "tool_call",
callId: "noop-edit",
name: "edit",
status: "completed",
error: null,
detail: {
type: "edit",
filePath: "/repo/src/same.ts",
oldString: text,
newString: text,
},
});
if (item.type !== "tool_call" || item.detail.type !== "edit") throw new Error("shape");
expect(item.detail.oldString).toBe("");
expect(item.detail.newString).toBe("");
expect(serializedBytes(item)).toBeLessThanOrEqual(64 * 1024);
expect(limitAgentTimelineItemContent(item)).toBe(item);
});
test("bounds massive full-file rewrites past the Myers distance cap without blowing up", () => {
const oldString = Array.from({ length: 1000 }, (_, i) => `old ${i}: ${"a".repeat(80)}`).join(
"\n",
);
const newString = Array.from({ length: 1000 }, (_, i) => `new ${i}: ${"b".repeat(80)}`).join(
"\n",
);
const item = limitAgentTimelineItemContent({
type: "tool_call",
callId: "rewrite-edit",
name: "edit",
status: "completed",
error: null,
detail: {
type: "edit",
filePath: "/repo/src/rewrite.ts",
oldString,
newString,
},
});
if (item.type !== "tool_call" || item.detail.type !== "edit") throw new Error("shape");
expect(item.detail.oldString).toContain("old 0:");
expect(item.detail.newString).toContain("new 0:");
expect(serializedBytes(item)).toBeLessThanOrEqual(64 * 1024);
expect(AgentTimelineItemPayloadSchema.safeParse(item).success).toBe(true);
expect(limitAgentTimelineItemContent(item)).toBe(item);
});
test("keeps small edit snippets untouched when an oversized error exceeds the budget", () => {
const item = limitAgentTimelineItemContent({
type: "tool_call",
callId: "small-edit-big-error",
name: "edit",
status: "failed",
error: { message: "e".repeat(100 * 1024) },
detail: {
type: "edit",
filePath: "/repo/src/small.ts",
oldString: "a\nb\nc\nd\ne\nf\ng",
newString: "a\nb\nc\nd\ne\nf\nG",
},
});
if (item.type !== "tool_call" || item.detail.type !== "edit") throw new Error("shape");
expect(item.detail.oldString).toBe("a\nb\nc\nd\ne\nf\ng");
expect(item.detail.newString).toBe("a\nb\nc\nd\ne\nf\nG");
expect(serializedBytes(item)).toBeLessThanOrEqual(64 * 1024);
});
});
@@ -14,6 +14,8 @@ const MARKER_COST = 32;
// Ids, names, paths and queries stay whole, so an item keeps its identity across passes.
const SHORT_STRING = 1024;
const MAX_DEPTH = 64;
const EDIT_CONTEXT_LINES = 3;
const EDIT_MAX_DIFF_DISTANCE = 256;
// The app registers renderer kinds under the plugin ID rule, so stored kinds must use that format.
export function assertPluginTimelineKind(kind: string): void {
@@ -135,21 +137,278 @@ function cut(value: unknown, depth: number, state: CutState): unknown {
return value;
}
/** Returns the item itself when it fits its budget; otherwise a copy with its largest strings cut. */
export function limitAgentTimelineItemContent(item: AgentTimelineItem): AgentTimelineItem {
const budget = item.type === "tool_call" ? TOOL_CALL_BUDGET : ITEM_BUDGET;
type EditToolCallDetail = Extract<
Extract<AgentTimelineItem, { type: "tool_call" }>["detail"],
{ type: "edit" }
>;
interface EditDiffOp {
kind: "eq" | "del" | "add";
oldIdx: number;
newIdx: number;
}
interface EditDiffSpan {
oldLines: readonly string[];
newLines: readonly string[];
start: number;
oldEnd: number;
newEnd: number;
}
function splitEditLines(
oldText: string,
newText: string,
): {
oldLines: string[];
newLines: string[];
} {
let normalizedOld = oldText.replace(/\r\n/g, "\n");
let normalizedNew = newText.replace(/\r\n/g, "\n");
if (normalizedOld.endsWith("\n") && normalizedNew.endsWith("\n")) {
normalizedOld = normalizedOld.slice(0, -1);
normalizedNew = normalizedNew.slice(0, -1);
}
return {
oldLines: normalizedOld.split("\n"),
newLines: normalizedNew.split("\n"),
};
}
interface MyersTrace {
trace: Int32Array[];
distance: number;
offset: number;
}
function shouldMoveDown(v: Int32Array, offset: number, d: number, k: number): boolean {
return k === -d || (k !== d && v[offset + k - 1] < v[offset + k + 1]);
}
function computeMyersTrace(span: EditDiffSpan): MyersTrace | null {
const { oldLines, newLines, start, oldEnd, newEnd } = span;
const oldLen = oldEnd - start;
const newLen = newEnd - start;
const maxDistance = Math.min(EDIT_MAX_DIFF_DISTANCE, oldLen + newLen);
const offset = maxDistance;
const v = new Int32Array(2 * maxDistance + 1);
const trace: Int32Array[] = [];
for (let d = 0; d <= maxDistance; d += 1) {
trace.push(v.slice());
for (let k = -d; k <= d; k += 2) {
const moveDown = shouldMoveDown(v, offset, d, k);
let x = moveDown ? v[offset + k + 1] : v[offset + k - 1] + 1;
let y = x - k;
while (x < oldLen && y < newLen && oldLines[start + x] === newLines[start + y]) {
x += 1;
y += 1;
}
v[offset + k] = x;
if (x >= oldLen && y >= newLen) {
return { trace, distance: d, offset };
}
}
}
return null;
}
function diffLineSlice(span: EditDiffSpan): EditDiffOp[] | null {
const result = computeMyersTrace(span);
if (!result) return null;
const { start, oldEnd, newEnd } = span;
const { trace, distance, offset } = result;
const reversed: EditDiffOp[] = [];
let x = oldEnd - start;
let y = newEnd - start;
for (let d = distance; d > 0; d -= 1) {
const prev = trace[d];
const k = x - y;
const moveDown = shouldMoveDown(prev, offset, d, k);
const prevK = moveDown ? k + 1 : k - 1;
const prevX = prev[offset + prevK];
const prevY = prevX - prevK;
const midX = moveDown ? prevX : prevX + 1;
const midY = moveDown ? prevY + 1 : prevY;
while (x > midX && y > midY) {
x -= 1;
y -= 1;
reversed.push({ kind: "eq", oldIdx: start + x, newIdx: start + y });
}
reversed.push({
kind: moveDown ? "add" : "del",
oldIdx: start + prevX,
newIdx: start + prevY,
});
x = prevX;
y = prevY;
}
while (x > 0 && y > 0) {
x -= 1;
y -= 1;
reversed.push({ kind: "eq", oldIdx: start + x, newIdx: start + y });
}
reversed.reverse();
return reversed;
}
function buildCompactUnifiedDiff(span: EditDiffSpan): string | null {
const { oldLines, newLines, start, oldEnd, newEnd } = span;
const middleOps = diffLineSlice(span);
if (!middleOps) return null;
const ops: EditDiffOp[] = [];
const leadStart = Math.max(0, start - EDIT_CONTEXT_LINES);
for (let i = leadStart; i < start; i += 1) {
ops.push({ kind: "eq", oldIdx: i, newIdx: i });
}
for (const op of middleOps) ops.push(op);
const trailCount = Math.min(EDIT_CONTEXT_LINES, oldLines.length - oldEnd);
for (let i = 0; i < trailCount; i += 1) {
ops.push({ kind: "eq", oldIdx: oldEnd + i, newIdx: newEnd + i });
}
const output: string[] = [];
let idx = 0;
while (idx < ops.length) {
while (idx < ops.length && ops[idx].kind === "eq") idx += 1;
if (idx >= ops.length) break;
const hunkStart = Math.max(0, idx - EDIT_CONTEXT_LINES);
let lastEdit = idx;
idx += 1;
while (idx < ops.length) {
if (ops[idx].kind !== "eq") {
lastEdit = idx;
idx += 1;
continue;
}
if (idx - lastEdit > EDIT_CONTEXT_LINES * 2) break;
idx += 1;
}
const hunkEnd = Math.min(ops.length, lastEdit + EDIT_CONTEXT_LINES + 1);
const hunkOps = ops.slice(hunkStart, hunkEnd);
let oldCount = 0;
let newCount = 0;
for (const op of hunkOps) {
if (op.kind !== "add") oldCount += 1;
if (op.kind !== "del") newCount += 1;
}
const firstOp = hunkOps[0];
const oldStart = oldCount === 0 ? firstOp.oldIdx : firstOp.oldIdx + 1;
const newStart = newCount === 0 ? firstOp.newIdx : firstOp.newIdx + 1;
output.push(`@@ -${oldStart},${oldCount} +${newStart},${newCount} @@`);
for (const op of hunkOps) {
if (op.kind === "eq") output.push(` ${oldLines[op.oldIdx]}`);
else if (op.kind === "del") output.push(`-${oldLines[op.oldIdx]}`);
else output.push(`+${newLines[op.newIdx]}`);
}
idx = hunkEnd;
}
return output.join("\n");
}
/** Narrow full-file edit payloads before generic prefix cutting drops changes past the cap. */
function compactOversizedEditDetail(
detail: EditToolCallDetail,
maxTextBudget: number,
): EditToolCallDetail | null {
if (detail.unifiedDiff) return null;
const { oldString, newString } = detail;
if (!oldString || !newString) return null;
const { oldLines, newLines } = splitEditLines(oldString, newString);
let start = 0;
let oldEnd = oldLines.length;
let newEnd = newLines.length;
while (start < oldEnd && start < newEnd && oldLines[start] === newLines[start]) {
start += 1;
}
while (oldEnd > start && newEnd > start && oldLines[oldEnd - 1] === newLines[newEnd - 1]) {
oldEnd -= 1;
newEnd -= 1;
}
if (start === oldEnd && start === newEnd) {
return { ...detail, oldString: "", newString: "" };
}
const contextStart = Math.max(0, start - EDIT_CONTEXT_LINES);
const oldContextEnd = Math.min(oldLines.length, oldEnd + EDIT_CONTEXT_LINES);
const newContextEnd = Math.min(newLines.length, newEnd + EDIT_CONTEXT_LINES);
const trimmedOld = oldLines.slice(contextStart, oldContextEnd).join("\n");
const trimmedNew = newLines.slice(contextStart, newContextEnd).join("\n");
if (trimmedOld.length + trimmedNew.length <= maxTextBudget) {
if (trimmedOld.length >= oldString.length && trimmedNew.length >= newString.length) {
return null;
}
return { ...detail, oldString: trimmedOld, newString: trimmedNew };
}
const unifiedDiff = buildCompactUnifiedDiff({ oldLines, newLines, start, oldEnd, newEnd });
if (unifiedDiff && unifiedDiff.length < trimmedOld.length + trimmedNew.length) {
return {
type: "edit",
filePath: detail.filePath,
unifiedDiff,
};
}
if (trimmedOld.length < oldString.length || trimmedNew.length < newString.length) {
return { ...detail, oldString: trimmedOld, newString: trimmedNew };
}
return null;
}
function measureItem(item: AgentTimelineItem): { size: ItemSize; total: number } {
const size: ItemSize = { nodeCost: 0, stringLengths: [], tooDeep: false };
measure(item, 0, size);
let stringTotal = 0;
for (const length of size.stringLengths) stringTotal += length;
if (!size.tooDeep && size.nodeCost + stringTotal <= budget) return item;
return { size, total: size.nodeCost + stringTotal };
}
function computeStringCap(size: ItemSize, budget: number): number {
// Strings get what structure leaves, but at least half the budget, less a margin for JSON
// escaping. Arrays drop the elements that do not fit, which bounds items whose short strings
// or structure alone are too big.
const markerCost =
MARKER_COST * size.stringLengths.filter((length) => length > SHORT_STRING).length;
const available = (budget * 15) / 16 - Math.min(size.nodeCost, budget / 2) - markerCost;
const stringCap = Math.max(SHORT_STRING, findStringCap(size.stringLengths, available));
return cut(item, 0, { stringCap, remaining: budget }) as AgentTimelineItem;
return Math.max(SHORT_STRING, findStringCap(size.stringLengths, available));
}
/** Returns the item itself when it fits its budget; otherwise a copy with its largest strings cut. */
export function limitAgentTimelineItemContent(item: AgentTimelineItem): AgentTimelineItem {
const budget = item.type === "tool_call" ? TOOL_CALL_BUDGET : ITEM_BUDGET;
const initial = measureItem(item);
if (!initial.size.tooDeep && initial.total <= budget) return item;
let candidate = item;
let stringCap = computeStringCap(initial.size, budget);
if (item.type === "tool_call" && item.detail.type === "edit") {
const { oldString, newString } = item.detail;
if (
!item.detail.unifiedDiff &&
oldString &&
newString &&
(oldString.length > stringCap || newString.length > stringCap)
) {
const compacted = compactOversizedEditDetail(item.detail, Math.floor((budget * 3) / 4));
if (compacted) {
candidate = { ...item, detail: compacted };
const next = measureItem(candidate);
if (!next.size.tooDeep && next.total <= budget) return candidate;
stringCap = computeStringCap(next.size, budget);
}
}
}
return cut(candidate, 0, { stringCap, remaining: budget }) as AgentTimelineItem;
}
@@ -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 {
@@ -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 } : {};
}
+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 : "");
+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": {
+21 -19
View File
@@ -10,6 +10,7 @@ import type {
ProviderMcpServerConfig,
ProviderCatalog,
ProviderToolCallDetail,
ProviderUsage,
} from "@getpaseo/plugin/server/provider";
import type { z } from "zod";
import { MspConnection, commandId, type Notification } from "./connection.js";
@@ -45,6 +46,16 @@ import { Recovery } from "./recovery.js";
import { Questions } from "./questions.js";
import { Commands } from "./commands.js";
function tokenUsage(input: unknown): ProviderUsage {
const { cumulative, usage } = tokenUsageSchema.parse(input);
return {
inputTokens: cumulative.promptTokens,
outputTokens: cumulative.outputTokens,
cachedInputTokens: cumulative.cacheReadTokens ?? usage?.cachedTokens,
totalCostUsd: cumulative.cost?.partial === false ? cumulative.cost.usd : undefined,
};
}
interface SessionOptions {
serveArgs: string[];
id: string;
@@ -77,6 +88,7 @@ export class Session {
private opening = true;
private closing = false;
private systemPromptPending = true;
private lastUsage: ProviderUsage = {};
private interruptCompletion: {
turnId: string;
resolve(): void;
@@ -464,33 +476,23 @@ export class Session {
case "turn/completed":
this.completeTurn(notification.params);
break;
case "session/tokenUsage": {
const params = tokenUsageSchema.parse(notification.params);
this.options.emit({
type: "session.usage",
sessionId: this.options.id,
usage: {
inputTokens: params.cumulative.promptTokens,
outputTokens: params.cumulative.outputTokens,
cachedInputTokens: params.usage?.cachedTokens,
},
});
case "session/tokenUsage":
this.updateUsage(tokenUsage(notification.params));
break;
}
case "session/contextUsage": {
const params = contextUsageSchema.parse(notification.params);
this.options.emit({
type: "session.usage",
sessionId: this.options.id,
usage: {
contextWindowUsedTokens: params.usedTokens,
contextWindowMaxTokens: params.windowTokens,
},
this.updateUsage({
contextWindowUsedTokens: params.usedTokens,
contextWindowMaxTokens: params.windowTokens,
});
break;
}
}
}
private updateUsage(update: ProviderUsage): void {
this.lastUsage = { ...this.lastUsage, ...update };
this.options.emit({ type: "session.usage", sessionId: this.options.id, usage: this.lastUsage });
}
private startTurn(input: unknown): void {
const params = turnSchema.parse(input);
if (
+6 -1
View File
@@ -192,7 +192,12 @@ export const toolArgsSchema = z.object({
url: z.string().default(""),
});
export const tokenUsageSchema = z.object({
cumulative: z.object({ promptTokens: z.number(), outputTokens: z.number() }),
cumulative: z.object({
promptTokens: z.number(),
outputTokens: z.number(),
cacheReadTokens: z.number().optional(),
cost: z.object({ usd: z.number().nonnegative(), partial: z.boolean() }).optional(),
}),
usage: z.object({ cachedTokens: z.number().optional() }).optional(),
});
export const contextUsageSchema = z.object({
+16
View File
@@ -343,6 +343,22 @@ function applyWireVariants(message) {
}
}
function parityDelivery(message) {
if (message.method === "session/tokenUsage" && process.env.MUSE_TEST_PRICED_USAGE) {
const context = (usedTokens) => ({
jsonrpc: "2.0",
method: "session/contextUsage",
params: { sessionId: message.params.sessionId, usedTokens, windowTokens: 100000 },
});
message.params.cumulative.cacheReadTokens = 12000;
message.params.cumulative.cost = {
usd: 0.25,
partial: process.env.MUSE_TEST_PRICED_USAGE === "partial",
};
send(context(5000));
send(message);
send(context(7000));
return true;
}
if (process.env.MUSE_TEST_WORKFLOW && message.method === "turn/completed")
send({
jsonrpc: "2.0",
@@ -561,6 +561,35 @@ test("image turn sends a native image and the subsequent text turn succeeds", as
});
expect(turns[1].params.input).toEqual([{ type: "text", text: "hello" }]);
});
test.each(["complete", "partial"])(
"keeps context and token usage together with %s Muse pricing",
async (pricing) => {
const h = await harness("text-reasoning", { MUSE_TEST_PRICED_USAGE: pricing });
await h.open();
await h.prompt();
await h.wait((event) => event.type === "session.turn" && event.state === "completed");
const snapshots = h.events.flatMap((event) =>
event.type === "session.usage" ? [event.usage] : [],
);
const tokens = { inputTokens: 38169, outputTokens: 663, cachedInputTokens: 12000 };
expect(snapshots.slice(-3)).toEqual([
{ contextWindowUsedTokens: 5000, contextWindowMaxTokens: 100000 },
{
...tokens,
totalCostUsd: pricing === "complete" ? 0.25 : undefined,
contextWindowUsedTokens: 5000,
contextWindowMaxTokens: 100000,
},
{
...tokens,
totalCostUsd: pricing === "complete" ? 0.25 : undefined,
contextWindowUsedTokens: 7000,
contextWindowMaxTokens: 100000,
},
]);
},
);
for (const source of ["live", "history", "backfill"]) {
test(`reminder housekeeping emits no timeline items or child sessions from ${source}`, async () => {
const scenario = source === "history" ? "resume-without-cursor" : "text-reasoning";
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/builtin-plugins",
"version": "0.18.1",
"version": "0.18.2",
"private": true,
"type": "module",
"scripts": {