mirror of
https://github.com/getpaseo/paseo.git
synced 2026-12-02 21:26:57 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ced52acef4 | ||
|
|
62da5b9463 | ||
|
|
6eb595f556 | ||
|
|
d8c29bbc85 | ||
|
|
7b8be44ac7 | ||
|
|
64ab894ff3 | ||
|
|
423178804f | ||
|
|
5f3396fec0 | ||
|
|
45dfc2b98b | ||
|
|
6cee7dc10d | ||
|
|
5b2aa7e0ca | ||
|
|
f576407576 | ||
|
|
b2b05b599e | ||
|
|
8fc8cb51b4 | ||
|
|
18dc910689 | ||
|
|
711188aadc | ||
|
|
d207bc5a57 | ||
|
|
f3213a2259 | ||
|
|
370afb86c6 | ||
|
|
6caf7f6653 |
+144
@@ -1,5 +1,149 @@
|
||||
# Changelog
|
||||
|
||||
## 0.19.0-beta.1 - 2026-12-02
|
||||
|
||||
- **Switch providers mid-chat:** Switch a chat to another provider and keep the conversation, with chat history now stored on the host. ([#11410](https://github.com/getpaseo/paseo/pull/11410))
|
||||
- **Queue survives restarts:** Queued messages now live on the host, so they survive app reloads, device switches and daemon restarts. ([#11424](https://github.com/getpaseo/paseo/pull/11424), [#11566](https://github.com/getpaseo/paseo/pull/11566), [#11740](https://github.com/getpaseo/paseo/pull/11740))
|
||||
- **One switch for agent tools:** Agent tools now sit behind one Enable tools setting with orchestration, schedules, PR watching and browser groups, and are on by default. ([#11189](https://github.com/getpaseo/paseo/pull/11189))
|
||||
- **Connected devices list:** Settings → Devices now shows which clients and hosts are connected and what each one can access. ([#11209](https://github.com/getpaseo/paseo/pull/11209))
|
||||
- **Plugin scorecards:** Plugin pages in the app and on paseo.sh show a scorecard, update history, related plugins and sponsor links. ([#11563](https://github.com/getpaseo/paseo/pull/11563), [#11674](https://github.com/getpaseo/paseo/pull/11674), [#11691](https://github.com/getpaseo/paseo/pull/11691))
|
||||
- **Share services through tunnels:** Share a running workspace service at a public URL from the Scripts menu, and dev servers keep their live-reload connections. Services now open at `localhost:<port>`, and `*.localhost` service URLs are removed. ([#11490](https://github.com/getpaseo/paseo/pull/11490))
|
||||
- **Lower CPU while agents run:** Running agents use far less CPU, GPU and battery, with lighter status rings, loaders and tool-call animations. ([#11456](https://github.com/getpaseo/paseo/pull/11456), [#11474](https://github.com/getpaseo/paseo/pull/11474), [#11564](https://github.com/getpaseo/paseo/pull/11564), [#11586](https://github.com/getpaseo/paseo/pull/11586), [#11591](https://github.com/getpaseo/paseo/pull/11591) by [@djbclark](https://github.com/djbclark), [@luoph](https://github.com/luoph), [@mariotaku](https://github.com/mariotaku))
|
||||
- **Steadier streaming replies:** Streaming replies show their final formatting as they arrive, and long replies no longer get slower to render as they grow. ([#11572](https://github.com/getpaseo/paseo/pull/11572), [#11582](https://github.com/getpaseo/paseo/pull/11582) by [@luoph](https://github.com/luoph))
|
||||
- **Faster mobile launch:** The mobile app shows your last workspace sooner after a cold launch, about 0.7 seconds on Android. ([#11390](https://github.com/getpaseo/paseo/pull/11390) by [@luoph](https://github.com/luoph), [@maci0](https://github.com/maci0))
|
||||
- **Desktop browser profiles:** Desktop browser tabs can use separate colored profiles, so you can stay signed in to two accounts on one site. ([#10357](https://github.com/getpaseo/paseo/pull/10357) by [@clkao](https://github.com/clkao))
|
||||
- **Swipe away the iOS keyboard:** Drag the chat down to hide the iOS keyboard, and chat controls now work on the first tap while it is open. ([#11625](https://github.com/getpaseo/paseo/pull/11625))
|
||||
|
||||
### Breaking
|
||||
|
||||
- Paseo CLI and daemon now require Node.js 22.16.0 or later ([#11410](https://github.com/getpaseo/paseo/pull/11410))
|
||||
|
||||
### Added
|
||||
|
||||
- Added Antigravity quota to Usage, refreshed only when you select Refresh ([#11585](https://github.com/getpaseo/paseo/pull/11585))
|
||||
- Added conversation-only rewind for OpenCode v2 agents ([#11675](https://github.com/getpaseo/paseo/pull/11675))
|
||||
- Added desktop browser tabs for workspaces on hosts connected through another host ([#11561](https://github.com/getpaseo/paseo/pull/11561))
|
||||
- Added `paseo hub run` to start Hub manual triggers from the terminal ([#11408](https://github.com/getpaseo/paseo/pull/11408))
|
||||
- Added Claude Enterprise monthly spend to the Usage card and sidebar summary ([#11514](https://github.com/getpaseo/paseo/pull/11514) by [@vivekkalyan](https://github.com/vivekkalyan))
|
||||
- Added Spend credits amounts for Codex individual spend limits ([#11702](https://github.com/getpaseo/paseo/pull/11702) by [@vivekkalyan](https://github.com/vivekkalyan))
|
||||
|
||||
### Improved
|
||||
|
||||
- Opened chats faster by skipping Markdown preparation for replies without workspace links ([#11327](https://github.com/getpaseo/paseo/pull/11327))
|
||||
- Reduced work on each workspace switch by updating Git actions only for the visible workspace ([#11332](https://github.com/getpaseo/paseo/pull/11332))
|
||||
- Stopped the sidebar re-rendering on agent updates that change only token usage ([#11565](https://github.com/getpaseo/paseo/pull/11565) by [@jl97mcad](https://github.com/jl97mcad))
|
||||
- Released hidden workspace composers after ten minutes during repeated workspace switches ([#11613](https://github.com/getpaseo/paseo/pull/11613) by [@js2me](https://github.com/js2me))
|
||||
- Kept typing responsive in long multiline drafts ([#11418](https://github.com/getpaseo/paseo/pull/11418))
|
||||
- Served the desktop app's web UI with Brotli and gzip compression instead of an uncompressed 25 MB bundle ([#10635](https://github.com/getpaseo/paseo/pull/10635) by [@djbclark](https://github.com/djbclark))
|
||||
- Changed chat loading to one steady spinner that reveals the chat and composer together, without an Updating messages flash ([#11575](https://github.com/getpaseo/paseo/pull/11575))
|
||||
- Kept the Restoring screen up until a restored workspace is ready ([#11486](https://github.com/getpaseo/paseo/pull/11486))
|
||||
- Showed a spinner on a worktree row while archive checks for uncommitted changes ([#11519](https://github.com/getpaseo/paseo/pull/11519), [#11574](https://github.com/getpaseo/paseo/pull/11574) by [@cxroop](https://github.com/cxroop))
|
||||
- Showed each host's icon with a status dot on host selectors ([#11568](https://github.com/getpaseo/paseo/pull/11568))
|
||||
- Sent the prompt with hardware-keyboard Return on iPhone, as on iPad ([#11537](https://github.com/getpaseo/paseo/pull/11537))
|
||||
- Replaced the Direct connection Advanced field with a Form and URI switch, so a pasted `tcp://` URI connects in one tap ([#11402](https://github.com/getpaseo/paseo/pull/11402) by [@thecardcheat](https://github.com/thecardcheat))
|
||||
|
||||
### Changed
|
||||
|
||||
- Changed archiving to keep a worktree that has uncommitted changes unless you confirm removal ([#11430](https://github.com/getpaseo/paseo/pull/11430))
|
||||
- Changed closing a New Agent tab with an unsent draft to ask before discarding it ([#11660](https://github.com/getpaseo/paseo/pull/11660))
|
||||
- Changed Cmd/Ctrl+click on a sidebar workspace to open it instead of entering select mode ([#11472](https://github.com/getpaseo/paseo/pull/11472))
|
||||
- Changed agents that already reported to their caller with `send_agent_prompt` to skip the extra finished notice ([#11583](https://github.com/getpaseo/paseo/pull/11583))
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fixed an attached image over 2000 px breaking every later turn in its chat ([#5119](https://github.com/getpaseo/paseo/pull/5119) by [@RUIIIOVO](https://github.com/RUIIIOVO))
|
||||
- Fixed voice mode agents never speaking back when Paseo tools were off ([#11161](https://github.com/getpaseo/paseo/pull/11161))
|
||||
- Fixed turning off voice mode without a daemon connection leaving the microphone on ([#11587](https://github.com/getpaseo/paseo/pull/11587) by [@luoph](https://github.com/luoph), [@RRD-dev](https://github.com/RRD-dev))
|
||||
- Fixed the app taking up to a minute to reconnect after returning from the background ([#10348](https://github.com/getpaseo/paseo/pull/10348) by [@dongsun1](https://github.com/dongsun1))
|
||||
- Fixed one failed WebSocket handshake doubling the reconnect delay ([#11428](https://github.com/getpaseo/paseo/pull/11428) by [@suniceman](https://github.com/suniceman))
|
||||
- Fixed chats staying on Reconnecting after the app switched to a faster connection ([#11029](https://github.com/getpaseo/paseo/pull/11029) by [@tmhaha](https://github.com/tmhaha))
|
||||
- Fixed Updating messages staying visible after reopening a cached chat ([#11464](https://github.com/getpaseo/paseo/pull/11464) by [@oyzh888](https://github.com/oyzh888))
|
||||
- Fixed terminal output stopping after a reconnect reused its subscription ([#10433](https://github.com/getpaseo/paseo/pull/10433) by [@chirag127](https://github.com/chirag127))
|
||||
- Fixed Files showing Host is not connected when the app launched before the host connected ([#11679](https://github.com/getpaseo/paseo/pull/11679))
|
||||
- Fixed Created and Last prompt sorting disappearing while a host is offline ([#11728](https://github.com/getpaseo/paseo/pull/11728))
|
||||
- Fixed iOS header taps scrolling the chat, Explorer or workspace list to the top ([#11262](https://github.com/getpaseo/paseo/pull/11262) by [@yzim](https://github.com/yzim))
|
||||
- Fixed a file sheet dismissed while opening leaving an invisible backdrop that blocked taps ([#11317](https://github.com/getpaseo/paseo/pull/11317) by [@LiebeLee](https://github.com/LiebeLee))
|
||||
- Fixed bottom sheets staying open when dismissed before their open animation started ([#11632](https://github.com/getpaseo/paseo/pull/11632))
|
||||
- Fixed Android attaching nothing when the app was recreated during image selection ([#7734](https://github.com/getpaseo/paseo/pull/7734))
|
||||
- Fixed pasting a file into the web composer inserting its path instead of attaching it ([#11718](https://github.com/getpaseo/paseo/pull/11718))
|
||||
- Fixed Content font size not applying to existing user messages in web chat ([#11469](https://github.com/getpaseo/paseo/pull/11469) by [@bearyjd](https://github.com/bearyjd))
|
||||
- Fixed `<br>` in a Markdown table cell splitting the table row ([#9587](https://github.com/getpaseo/paseo/pull/9587) by [@apple-ouyang](https://github.com/apple-ouyang))
|
||||
- Fixed hidden chat rows shifting the reading position on web ([#11538](https://github.com/getpaseo/paseo/pull/11538) by [@kogekiplay](https://github.com/kogekiplay))
|
||||
- Fixed a plugin slash command with an attachment being sent to the agent as a message ([#11483](https://github.com/getpaseo/paseo/pull/11483) by [@suniceman](https://github.com/suniceman))
|
||||
- Fixed Archive finished subagents skipping closed subagents ([#10865](https://github.com/getpaseo/paseo/pull/10865) by [@sbhas2k](https://github.com/sbhas2k))
|
||||
- Fixed Import Session missing the newest ACP sessions ([#10675](https://github.com/getpaseo/paseo/pull/10675))
|
||||
- Fixed Import Session hiding the provider error while Retry runs ([#11654](https://github.com/getpaseo/paseo/pull/11654))
|
||||
- Fixed setup dropping project suggestions from providers that answer after 60 seconds ([#11438](https://github.com/getpaseo/paseo/pull/11438) by [@suniceman](https://github.com/suniceman))
|
||||
- Fixed Open in file manager showing for workspaces on remote hosts ([#11463](https://github.com/getpaseo/paseo/pull/11463) by [@sleroq](https://github.com/sleroq))
|
||||
- Fixed Reveal in Finder for workspaces rooted at `/` ([#11206](https://github.com/getpaseo/paseo/pull/11206) by [@suniceman](https://github.com/suniceman))
|
||||
- Fixed large HTML files previewing as a blank pane on desktop ([#11504](https://github.com/getpaseo/paseo/pull/11504))
|
||||
- Fixed the Paseo RPM failing to install alongside other Electron RPMs ([#11354](https://github.com/getpaseo/paseo/pull/11354))
|
||||
- Fixed Restart and close terminals leaving terminal programs running on Windows ([#11398](https://github.com/getpaseo/paseo/pull/11398))
|
||||
- Fixed agent creation hanging behind provider checks for deleted worktrees ([#11646](https://github.com/getpaseo/paseo/pull/11646) by [@ralston](https://github.com/ralston))
|
||||
- Fixed finished Claude subagents showing as running or canceled after reopening a chat or restarting the daemon ([#10848](https://github.com/getpaseo/paseo/pull/10848), [#11594](https://github.com/getpaseo/paseo/pull/11594), [#11602](https://github.com/getpaseo/paseo/pull/11602) by [@monarchmaisuriya](https://github.com/monarchmaisuriya), [@desmond-rai](https://github.com/desmond-rai))
|
||||
- Fixed Claude agents started by Paseo missing Claude Code's chat titles ([#11057](https://github.com/getpaseo/paseo/pull/11057) by [@Zayooo00](https://github.com/Zayooo00))
|
||||
- Fixed turns Claude starts on its own staying hidden in reopened chats until Reload ([#11405](https://github.com/getpaseo/paseo/pull/11405))
|
||||
- Fixed Claude Code system notices being dropped from the chat ([#11419](https://github.com/getpaseo/paseo/pull/11419) by [@minamorl](https://github.com/minamorl))
|
||||
- Fixed Claude Code's Goal set reply missing from imported chats ([#11733](https://github.com/getpaseo/paseo/pull/11733))
|
||||
- Fixed listing commands in an archived Claude chat starting Claude Code ([#11521](https://github.com/getpaseo/paseo/pull/11521) by [@RawSalmon69](https://github.com/RawSalmon69))
|
||||
- Fixed Stop failing on unresponsive Pi and OMP agents ([#11618](https://github.com/getpaseo/paseo/pull/11618) by [@LouisDeconinck](https://github.com/LouisDeconinck))
|
||||
- Fixed Pi turns never finishing when an extension handles the prompt ([#10572](https://github.com/getpaseo/paseo/pull/10572) by [@jsilhan](https://github.com/jsilhan))
|
||||
- Fixed Pi prompts timing out during extension preflight and then running anyway ([#11525](https://github.com/getpaseo/paseo/pull/11525) by [@Stelath](https://github.com/Stelath))
|
||||
- Fixed Pi showing the prompt twice when an extension sends context before the reply ([#11533](https://github.com/getpaseo/paseo/pull/11533) by [@Stelath](https://github.com/Stelath))
|
||||
- Fixed Pi chats skipping project skills and settings in trusted workspaces ([#11527](https://github.com/getpaseo/paseo/pull/11527) by [@patrick-motard](https://github.com/patrick-motard))
|
||||
- Fixed new Pi agents failing with an old extension error after the conflict was fixed ([#11642](https://github.com/getpaseo/paseo/pull/11642))
|
||||
- Fixed the OMP Fast toggle missing before the first prompt ([#11553](https://github.com/getpaseo/paseo/pull/11553))
|
||||
- Fixed finished OMP form questions losing the question and chosen answer ([#11697](https://github.com/getpaseo/paseo/pull/11697), [#11706](https://github.com/getpaseo/paseo/pull/11706) by [@luoph](https://github.com/luoph), [@RRD-dev](https://github.com/RRD-dev))
|
||||
- Fixed Codex sends reporting failure after 60 seconds while Codex was still starting ([#11547](https://github.com/getpaseo/paseo/pull/11547) by [@nonononull](https://github.com/nonononull))
|
||||
- Fixed Codex features staying hidden behind a wrapper command such as `env codex` ([#11221](https://github.com/getpaseo/paseo/pull/11221) by [@suniceman](https://github.com/suniceman))
|
||||
- Fixed answers to Codex async questions being rejected ([#11225](https://github.com/getpaseo/paseo/pull/11225) by [@suniceman](https://github.com/suniceman))
|
||||
- Fixed reopening a Codex chat resetting its last-activity time ([#10760](https://github.com/getpaseo/paseo/pull/10760) by [@Juns-g](https://github.com/Juns-g))
|
||||
- Fixed Antigravity subagent tool calls splitting streamed replies mid-word ([#11535](https://github.com/getpaseo/paseo/pull/11535) by [@Suhail](https://github.com/Suhail))
|
||||
- Fixed Antigravity turns ending as completed after an internal executor error ([#10885](https://github.com/getpaseo/paseo/pull/10885) by [@vecyang1](https://github.com/vecyang1), [@luoph](https://github.com/luoph))
|
||||
- Fixed ACP chats failing to reopen when the provider rejects the saved thinking level ([#10333](https://github.com/getpaseo/paseo/pull/10333))
|
||||
- Fixed the ACP thinking picker keeping the old level after a mode change ([#11478](https://github.com/getpaseo/paseo/pull/11478) by [@suniceman](https://github.com/suniceman))
|
||||
- Fixed ACP setting errors leaving out the provider's explanation ([#11431](https://github.com/getpaseo/paseo/pull/11431) by [@suniceman](https://github.com/suniceman))
|
||||
- Fixed Muse usage losing token totals after a context update ([#11389](https://github.com/getpaseo/paseo/pull/11389) by [@suniceman](https://github.com/suniceman))
|
||||
- Fixed the Claude Usage card staying rate limited for hours ([#11597](https://github.com/getpaseo/paseo/pull/11597))
|
||||
- Fixed Claude Usage showing the old plan after a subscription change ([#11685](https://github.com/getpaseo/paseo/pull/11685) by [@matchy233](https://github.com/matchy233))
|
||||
- Fixed Codex Usage showing 0 credits for accounts without a credit balance ([#11515](https://github.com/getpaseo/paseo/pull/11515) by [@vivekkalyan](https://github.com/vivekkalyan))
|
||||
- Fixed Copilot Usage failing when the premium request quota is exceeded ([#11006](https://github.com/getpaseo/paseo/pull/11006) by [@nathanmcnulty](https://github.com/nathanmcnulty))
|
||||
- Fixed Copilot Usage reading the token of another host or account from GitHub CLI ([#11689](https://github.com/getpaseo/paseo/pull/11689))
|
||||
- Fixed Create PR from a fork opening the pull request on the fork instead of its parent ([#11436](https://github.com/getpaseo/paseo/pull/11436) by [@suniceman](https://github.com/suniceman))
|
||||
- Fixed a fork pull request disappearing from its worktree workspace after the first push ([#11441](https://github.com/getpaseo/paseo/pull/11441) by [@suniceman](https://github.com/suniceman))
|
||||
- Fixed Create PR returning the API URL instead of the pull request page ([#11439](https://github.com/getpaseo/paseo/pull/11439) by [@suniceman](https://github.com/suniceman))
|
||||
- Fixed GitHub check details failing to load annotations ([#11476](https://github.com/getpaseo/paseo/pull/11476) by [@suniceman](https://github.com/suniceman))
|
||||
- Fixed GitHub check details dropping annotations when a job log is unavailable ([#11509](https://github.com/getpaseo/paseo/pull/11509))
|
||||
- Fixed Gitea and Forgejo draft pull requests showing as open and conflicting ([#11545](https://github.com/getpaseo/paseo/pull/11545) by [@goodideal](https://github.com/goodideal))
|
||||
- Fixed workspaces with an IPv6 Git remote not detecting their Gitea or Forgejo forge ([#11692](https://github.com/getpaseo/paseo/pull/11692) by [@jamescordrey-ops](https://github.com/jamescordrey-ops))
|
||||
- Fixed workspace refreshes stalling when a `gh` or `glab` command ignores its timeout ([#11252](https://github.com/getpaseo/paseo/pull/11252), [#11411](https://github.com/getpaseo/paseo/pull/11411))
|
||||
- Fixed scheduled runs in a Paseo worktree creating a duplicate project ([#10378](https://github.com/getpaseo/paseo/pull/10378) by [@kotusenka](https://github.com/kotusenka))
|
||||
- Fixed archiving an agent failing with Unknown agent while another archive or close runs ([#10590](https://github.com/getpaseo/paseo/pull/10590) by [@apple-ouyang](https://github.com/apple-ouyang))
|
||||
- Fixed an agent's last reply being cut off when a notification arrived mid-reply ([#11578](https://github.com/getpaseo/paseo/pull/11578) by [@KiritoXDone](https://github.com/KiritoXDone))
|
||||
- Fixed a queued message running in the mode of a prompt sent after it ([#11722](https://github.com/getpaseo/paseo/pull/11722))
|
||||
- Fixed `paseo ls --json` dropping timestamps and background work ([#11423](https://github.com/getpaseo/paseo/pull/11423) by [@KiritoXDone](https://github.com/KiritoXDone))
|
||||
- Fixed `paseo inspect` and `paseo ls` hiding the model for Cursor Auto ([#11693](https://github.com/getpaseo/paseo/pull/11693))
|
||||
- Fixed `paseo workspace ls` reporting a wrong password as a stopped daemon ([#11676](https://github.com/getpaseo/paseo/pull/11676) by [@chirag127](https://github.com/chirag127))
|
||||
- Fixed `paseo daemon status` leaving out unconfirmed terminal cleanup ([#11658](https://github.com/getpaseo/paseo/pull/11658) by [@chirag127](https://github.com/chirag127))
|
||||
- Fixed CLI archive, detach and reload scanning all agent history for a full agent ID ([#11617](https://github.com/getpaseo/paseo/pull/11617) by [@maci0](https://github.com/maci0))
|
||||
|
||||
### Security
|
||||
|
||||
- Blocked client file access to the daemon's own state in the Paseo home directory, and warned when a saved host's daemon key changes ([#11452](https://github.com/getpaseo/paseo/pull/11452))
|
||||
- Restricted loopback origin matching to `localhost`, `127.0.0.1` and `::1` for daemon WebSocket and HTTP requests ([#11686](https://github.com/getpaseo/paseo/pull/11686))
|
||||
- Stopped images in pull request comments and reviews from loading files from the host ([#11699](https://github.com/getpaseo/paseo/pull/11699))
|
||||
- Stopped `.worktreeinclude` from copying local files into worktrees from fork pull requests ([#11709](https://github.com/getpaseo/paseo/pull/11709))
|
||||
- Rejected schedule IDs that point outside the schedules directory ([#11727](https://github.com/getpaseo/paseo/pull/11727))
|
||||
|
||||
### Plugins
|
||||
|
||||
- Added a workspace layout API so plugins can open, move and close panes and tabs ([#11328](https://github.com/getpaseo/paseo/pull/11328))
|
||||
- Added `requirements.app` to set a separate minimum app version from the daemon's ([#11494](https://github.com/getpaseo/paseo/pull/11494) by [@mcowger](https://github.com/mcowger))
|
||||
- Fixed a plugin error in a press handler or timer closing the iOS and Android app ([#11412](https://github.com/getpaseo/paseo/pull/11412))
|
||||
- Fixed plugin operations deleting plugin entries added to `config.json` by hand ([#11501](https://github.com/getpaseo/paseo/pull/11501) by [@matchy233](https://github.com/matchy233))
|
||||
- Fixed registry plugin installs failing with Missing npm artifact when npm leaves registry URLs out of lockfiles ([#11656](https://github.com/getpaseo/paseo/pull/11656) by [@Brandon168](https://github.com/Brandon168))
|
||||
- Fixed local plugin reloads taking 12 to 21 seconds when the daemon runs under a large directory ([#11653](https://github.com/getpaseo/paseo/pull/11653))
|
||||
|
||||
## 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))
|
||||
|
||||
@@ -1,5 +1,149 @@
|
||||
# Changelog
|
||||
|
||||
## 0.19.0-beta.1 - 2026-12-02
|
||||
|
||||
- **对话中切换 Provider**:可将对话切换到其他 Provider 并保留对话内容,对话记录现在存储在主机上。([#11410](https://github.com/getpaseo/paseo/pull/11410))
|
||||
- **排队消息重启不丢失**:排队消息现在保存在主机上,应用重新加载、切换设备或 daemon 重启后都不会丢失。([#11424](https://github.com/getpaseo/paseo/pull/11424), [#11566](https://github.com/getpaseo/paseo/pull/11566), [#11740](https://github.com/getpaseo/paseo/pull/11740))
|
||||
- **一键开关 Agent 工具**:Agent 工具现在由一个 **启用工具** 设置统一控制,包含编排、定时任务、PR 监控和浏览器分组,并默认开启。([#11189](https://github.com/getpaseo/paseo/pull/11189))
|
||||
- **已连接设备列表**:**设置 → 设备** 现在会显示哪些客户端和主机已连接,以及各自可以访问的内容。([#11209](https://github.com/getpaseo/paseo/pull/11209))
|
||||
- **插件评分卡**:应用和 paseo.sh 上的插件页面现在会显示评分卡、更新历史、相关插件和赞助链接。([#11563](https://github.com/getpaseo/paseo/pull/11563), [#11674](https://github.com/getpaseo/paseo/pull/11674), [#11691](https://github.com/getpaseo/paseo/pull/11691))
|
||||
- **通过隧道共享服务**:可从 Scripts 菜单将正在运行的工作区服务共享到公网地址,开发服务器也会保留实时重载连接。服务现在通过 `localhost:<port>` 打开,`*.localhost` 服务地址已移除。([#11490](https://github.com/getpaseo/paseo/pull/11490))
|
||||
- **Agent 运行时更省资源**:运行中的 Agent 占用的 CPU、GPU 和电量大幅减少,状态环、加载指示器和工具调用动画也更轻量。([#11456](https://github.com/getpaseo/paseo/pull/11456), [#11474](https://github.com/getpaseo/paseo/pull/11474), [#11564](https://github.com/getpaseo/paseo/pull/11564), [#11586](https://github.com/getpaseo/paseo/pull/11586), [#11591](https://github.com/getpaseo/paseo/pull/11591),贡献者:[@djbclark](https://github.com/djbclark), [@luoph](https://github.com/luoph), [@mariotaku](https://github.com/mariotaku))
|
||||
- **更稳定的流式回复**:流式回复在到达时即显示最终格式,长回复的渲染也不再随长度增长而变慢。([#11572](https://github.com/getpaseo/paseo/pull/11572), [#11582](https://github.com/getpaseo/paseo/pull/11582),贡献者:[@luoph](https://github.com/luoph))
|
||||
- **更快的移动端启动**:移动端冷启动后会更快显示上次的工作区,在 Android 上约快 0.7 秒。([#11390](https://github.com/getpaseo/paseo/pull/11390),贡献者:[@luoph](https://github.com/luoph), [@maci0](https://github.com/maci0))
|
||||
- **桌面端浏览器配置文件**:桌面端浏览器标签页可以使用不同颜色的独立配置文件,便于在同一网站上同时登录两个账号。([#10357](https://github.com/getpaseo/paseo/pull/10357),贡献者:[@clkao](https://github.com/clkao))
|
||||
- **下滑收起 iOS 键盘**:向下拖动对话即可收起 iOS 键盘,键盘打开时对话控件首次点击即可生效。([#11625](https://github.com/getpaseo/paseo/pull/11625))
|
||||
|
||||
### 破坏性变更
|
||||
|
||||
- Paseo CLI 和 daemon 现在需要 Node.js 22.16.0 或更高版本 ([#11410](https://github.com/getpaseo/paseo/pull/11410))
|
||||
|
||||
### 新增
|
||||
|
||||
- 在用量中新增 Antigravity 配额,仅在选择 **刷新** 时更新 ([#11585](https://github.com/getpaseo/paseo/pull/11585))
|
||||
- 为 OpenCode v2 Agent 新增仅回退对话的功能 ([#11675](https://github.com/getpaseo/paseo/pull/11675))
|
||||
- 为通过其他主机连接的主机上的工作区新增桌面端浏览器标签页 ([#11561](https://github.com/getpaseo/paseo/pull/11561))
|
||||
- 新增 `paseo hub run`,可从终端启动 Hub 手动触发器 ([#11408](https://github.com/getpaseo/paseo/pull/11408))
|
||||
- 在用量卡片和侧边栏摘要中新增 Claude Enterprise 月度支出 ([#11514](https://github.com/getpaseo/paseo/pull/11514),贡献者:[@vivekkalyan](https://github.com/vivekkalyan))
|
||||
- 为 Codex 个人支出限额新增 Spend credits 金额显示 ([#11702](https://github.com/getpaseo/paseo/pull/11702),贡献者:[@vivekkalyan](https://github.com/vivekkalyan))
|
||||
|
||||
### 改进
|
||||
|
||||
- 对不含工作区链接的回复跳过 Markdown 预处理,加快对话打开速度 ([#11327](https://github.com/getpaseo/paseo/pull/11327))
|
||||
- 仅为可见工作区更新 Git 操作,减少每次切换工作区的开销 ([#11332](https://github.com/getpaseo/paseo/pull/11332))
|
||||
- 仅改变 token 用量的 Agent 更新不再触发侧边栏重新渲染 ([#11565](https://github.com/getpaseo/paseo/pull/11565),贡献者:[@jl97mcad](https://github.com/jl97mcad))
|
||||
- 反复切换工作区时,隐藏的工作区 Composer 会在十分钟后释放 ([#11613](https://github.com/getpaseo/paseo/pull/11613),贡献者:[@js2me](https://github.com/js2me))
|
||||
- 在较长的多行草稿中保持输入流畅 ([#11418](https://github.com/getpaseo/paseo/pull/11418))
|
||||
- 桌面应用的网页界面改用 Brotli 和 gzip 压缩传输,不再发送未压缩的 25 MB 包 ([#10635](https://github.com/getpaseo/paseo/pull/10635),贡献者:[@djbclark](https://github.com/djbclark))
|
||||
- 对话加载改为显示一个稳定的加载指示器,并同时显示对话和 Composer,不再闪现 **正在更新消息** ([#11575](https://github.com/getpaseo/paseo/pull/11575))
|
||||
- 恢复工作区时保持 Restoring 界面,直到工作区就绪 ([#11486](https://github.com/getpaseo/paseo/pull/11486))
|
||||
- 归档检查未提交的更改时,在 worktree 行上显示加载指示器 ([#11519](https://github.com/getpaseo/paseo/pull/11519), [#11574](https://github.com/getpaseo/paseo/pull/11574),贡献者:[@cxroop](https://github.com/cxroop))
|
||||
- 在主机选择器上显示各主机的图标和状态圆点 ([#11568](https://github.com/getpaseo/paseo/pull/11568))
|
||||
- iPhone 上按硬件键盘的 Return 键即可发送提示词,与 iPad 一致 ([#11537](https://github.com/getpaseo/paseo/pull/11537))
|
||||
- 将 **直接连接** 的 Advanced 字段替换为 **表单** 与 URI 切换,粘贴 `tcp://` URI 后一次点击即可连接 ([#11402](https://github.com/getpaseo/paseo/pull/11402),贡献者:[@thecardcheat](https://github.com/thecardcheat))
|
||||
|
||||
### 变更
|
||||
|
||||
- 归档时如果 worktree 有未提交的更改,除非确认删除,否则保留该 worktree ([#11430](https://github.com/getpaseo/paseo/pull/11430))
|
||||
- 关闭带有未发送草稿的 **新建 Agent** 标签页时,会先询问是否丢弃草稿 ([#11660](https://github.com/getpaseo/paseo/pull/11660))
|
||||
- 在侧边栏中 Cmd/Ctrl+点击工作区改为打开该工作区,而不再进入选择模式 ([#11472](https://github.com/getpaseo/paseo/pull/11472))
|
||||
- 已通过 `send_agent_prompt` 向调用方汇报的 Agent 不再额外发送完成通知 ([#11583](https://github.com/getpaseo/paseo/pull/11583))
|
||||
|
||||
### 修复
|
||||
|
||||
- 修复附加超过 2000 px 的图片后,该对话之后的每一轮都失败的问题 ([#5119](https://github.com/getpaseo/paseo/pull/5119),贡献者:[@RUIIIOVO](https://github.com/RUIIIOVO))
|
||||
- 修复关闭 Paseo 工具时语音模式 Agent 始终不回话的问题 ([#11161](https://github.com/getpaseo/paseo/pull/11161))
|
||||
- 修复在没有 daemon 连接时关闭语音模式后麦克风仍保持开启的问题 ([#11587](https://github.com/getpaseo/paseo/pull/11587),贡献者:[@luoph](https://github.com/luoph), [@RRD-dev](https://github.com/RRD-dev))
|
||||
- 修复应用从后台返回后需要长达一分钟才能重新连接的问题 ([#10348](https://github.com/getpaseo/paseo/pull/10348),贡献者:[@dongsun1](https://github.com/dongsun1))
|
||||
- 修复一次 WebSocket 握手失败就使重连延迟翻倍的问题 ([#11428](https://github.com/getpaseo/paseo/pull/11428),贡献者:[@suniceman](https://github.com/suniceman))
|
||||
- 修复应用切换到更快的连接后,对话仍停留在 **正在重新连接** 的问题 ([#11029](https://github.com/getpaseo/paseo/pull/11029),贡献者:[@tmhaha](https://github.com/tmhaha))
|
||||
- 修复重新打开已缓存的对话后 **正在更新消息** 一直显示的问题 ([#11464](https://github.com/getpaseo/paseo/pull/11464),贡献者:[@oyzh888](https://github.com/oyzh888))
|
||||
- 修复重连复用订阅后终端输出停止的问题 ([#10433](https://github.com/getpaseo/paseo/pull/10433),贡献者:[@chirag127](https://github.com/chirag127))
|
||||
- 修复应用在主机连接前启动时 **文件** 显示 **Host 未连接** 的问题 ([#11679](https://github.com/getpaseo/paseo/pull/11679))
|
||||
- 修复主机离线时 **创建时间** 和 **最近提示词** 排序选项消失的问题 ([#11728](https://github.com/getpaseo/paseo/pull/11728))
|
||||
- 修复在 iOS 上点击标题栏会将对话、Explorer 或工作区列表滚动到顶部的问题 ([#11262](https://github.com/getpaseo/paseo/pull/11262),贡献者:[@yzim](https://github.com/yzim))
|
||||
- 修复文件面板在打开过程中被关闭后,留下阻挡点击的不可见遮罩的问题 ([#11317](https://github.com/getpaseo/paseo/pull/11317),贡献者:[@LiebeLee](https://github.com/LiebeLee))
|
||||
- 修复底部面板在打开动画开始前被关闭后仍保持打开的问题 ([#11632](https://github.com/getpaseo/paseo/pull/11632))
|
||||
- 修复 Android 在选择图片期间重建应用后未附加任何内容的问题 ([#7734](https://github.com/getpaseo/paseo/pull/7734))
|
||||
- 修复在网页版 Composer 中粘贴文件时插入文件路径而不是添加附件的问题 ([#11718](https://github.com/getpaseo/paseo/pull/11718))
|
||||
- 修复 **内容字体大小** 未应用到网页端对话中已有用户消息的问题 ([#11469](https://github.com/getpaseo/paseo/pull/11469),贡献者:[@bearyjd](https://github.com/bearyjd))
|
||||
- 修复 Markdown 表格单元格中的 `<br>` 拆分表格行的问题 ([#9587](https://github.com/getpaseo/paseo/pull/9587),贡献者:[@apple-ouyang](https://github.com/apple-ouyang))
|
||||
- 修复网页端隐藏的对话行导致阅读位置偏移的问题 ([#11538](https://github.com/getpaseo/paseo/pull/11538),贡献者:[@kogekiplay](https://github.com/kogekiplay))
|
||||
- 修复带附件的插件斜杠命令被当作消息发送给 Agent 的问题 ([#11483](https://github.com/getpaseo/paseo/pull/11483),贡献者:[@suniceman](https://github.com/suniceman))
|
||||
- 修复 **归档已完成的 subagent** 跳过已关闭子 Agent 的问题 ([#10865](https://github.com/getpaseo/paseo/pull/10865),贡献者:[@sbhas2k](https://github.com/sbhas2k))
|
||||
- 修复 **导入会话** 遗漏最新 ACP 会话的问题 ([#10675](https://github.com/getpaseo/paseo/pull/10675))
|
||||
- 修复 **导入会话** 在 **重试** 期间隐藏 Provider 错误的问题 ([#11654](https://github.com/getpaseo/paseo/pull/11654))
|
||||
- 修复设置时丢弃 60 秒后才响应的 Provider 所给出的项目建议的问题 ([#11438](https://github.com/getpaseo/paseo/pull/11438),贡献者:[@suniceman](https://github.com/suniceman))
|
||||
- 修复远程主机上的工作区显示 Open in file manager 的问题 ([#11463](https://github.com/getpaseo/paseo/pull/11463),贡献者:[@sleroq](https://github.com/sleroq))
|
||||
- 修复根目录为 `/` 的工作区无法使用 Reveal in Finder 的问题 ([#11206](https://github.com/getpaseo/paseo/pull/11206),贡献者:[@suniceman](https://github.com/suniceman))
|
||||
- 修复桌面端预览大型 HTML 文件时显示空白面板的问题 ([#11504](https://github.com/getpaseo/paseo/pull/11504))
|
||||
- 修复 Paseo RPM 无法与其他 Electron RPM 同时安装的问题 ([#11354](https://github.com/getpaseo/paseo/pull/11354))
|
||||
- 修复 Windows 上 Restart and close 终端后终端程序仍在运行的问题 ([#11398](https://github.com/getpaseo/paseo/pull/11398))
|
||||
- 修复已删除 worktree 的 Provider 检查导致 Agent 创建卡住的问题 ([#11646](https://github.com/getpaseo/paseo/pull/11646),贡献者:[@ralston](https://github.com/ralston))
|
||||
- 修复重新打开对话或重启 daemon 后,已完成的 Claude 子 Agent 显示为运行中或已取消的问题 ([#10848](https://github.com/getpaseo/paseo/pull/10848), [#11594](https://github.com/getpaseo/paseo/pull/11594), [#11602](https://github.com/getpaseo/paseo/pull/11602),贡献者:[@monarchmaisuriya](https://github.com/monarchmaisuriya), [@desmond-rai](https://github.com/desmond-rai))
|
||||
- 修复由 Paseo 启动的 Claude Agent 缺少 Claude Code 对话标题的问题 ([#11057](https://github.com/getpaseo/paseo/pull/11057),贡献者:[@Zayooo00](https://github.com/Zayooo00))
|
||||
- 修复 Claude 自行开始的轮次在重新打开的对话中被隐藏、直到 **重新加载** 才显示的问题 ([#11405](https://github.com/getpaseo/paseo/pull/11405))
|
||||
- 修复 Claude Code 系统通知从对话中丢失的问题 ([#11419](https://github.com/getpaseo/paseo/pull/11419),贡献者:[@minamorl](https://github.com/minamorl))
|
||||
- 修复导入的 Claude Code 对话中缺少 Goal set 回复的问题 ([#11733](https://github.com/getpaseo/paseo/pull/11733))
|
||||
- 修复在已归档的 Claude 对话中列出命令时启动 Claude Code 的问题 ([#11521](https://github.com/getpaseo/paseo/pull/11521),贡献者:[@RawSalmon69](https://github.com/RawSalmon69))
|
||||
- 修复 **停止** 对无响应的 Pi 和 OMP Agent 无效的问题 ([#11618](https://github.com/getpaseo/paseo/pull/11618),贡献者:[@LouisDeconinck](https://github.com/LouisDeconinck))
|
||||
- 修复扩展处理提示词时 Pi 轮次永远无法结束的问题 ([#10572](https://github.com/getpaseo/paseo/pull/10572),贡献者:[@jsilhan](https://github.com/jsilhan))
|
||||
- 修复 Pi 提示词在扩展预检期间超时后仍继续执行的问题 ([#11525](https://github.com/getpaseo/paseo/pull/11525),贡献者:[@Stelath](https://github.com/Stelath))
|
||||
- 修复扩展在回复前发送上下文时 Pi 重复显示提示词的问题 ([#11533](https://github.com/getpaseo/paseo/pull/11533),贡献者:[@Stelath](https://github.com/Stelath))
|
||||
- 修复在受信任的工作区中 Pi 对话跳过项目技能和设置的问题 ([#11527](https://github.com/getpaseo/paseo/pull/11527),贡献者:[@patrick-motard](https://github.com/patrick-motard))
|
||||
- 修复冲突解决后新建 Pi Agent 仍报旧扩展错误的问题 ([#11642](https://github.com/getpaseo/paseo/pull/11642))
|
||||
- 修复首次发送提示词前缺少 OMP **快速** 开关的问题 ([#11553](https://github.com/getpaseo/paseo/pull/11553))
|
||||
- 修复已完成的 OMP 表单提问不再显示提问内容和所选答案的问题 ([#11697](https://github.com/getpaseo/paseo/pull/11697), [#11706](https://github.com/getpaseo/paseo/pull/11706),贡献者:[@luoph](https://github.com/luoph), [@RRD-dev](https://github.com/RRD-dev))
|
||||
- 修复 Codex 仍在启动时发送消息于 60 秒后报告失败的问题 ([#11547](https://github.com/getpaseo/paseo/pull/11547),贡献者:[@nonononull](https://github.com/nonononull))
|
||||
- 修复通过 `env codex` 等包装命令启动时 Codex 功能被隐藏的问题 ([#11221](https://github.com/getpaseo/paseo/pull/11221),贡献者:[@suniceman](https://github.com/suniceman))
|
||||
- 修复 Codex 异步提问的回答被拒绝的问题 ([#11225](https://github.com/getpaseo/paseo/pull/11225),贡献者:[@suniceman](https://github.com/suniceman))
|
||||
- 修复重新打开 Codex 对话时重置其最近活动时间的问题 ([#10760](https://github.com/getpaseo/paseo/pull/10760),贡献者:[@Juns-g](https://github.com/Juns-g))
|
||||
- 修复 Antigravity 子 Agent 工具调用将流式回复从单词中间截断的问题 ([#11535](https://github.com/getpaseo/paseo/pull/11535),贡献者:[@Suhail](https://github.com/Suhail))
|
||||
- 修复 Antigravity 轮次在内部执行器出错后仍以完成状态结束的问题 ([#10885](https://github.com/getpaseo/paseo/pull/10885),贡献者:[@vecyang1](https://github.com/vecyang1), [@luoph](https://github.com/luoph))
|
||||
- 修复 Provider 拒绝已保存的思考强度时 ACP 对话无法重新打开的问题 ([#10333](https://github.com/getpaseo/paseo/pull/10333))
|
||||
- 修复切换模式后 ACP 思考强度选择器仍保留旧级别的问题 ([#11478](https://github.com/getpaseo/paseo/pull/11478),贡献者:[@suniceman](https://github.com/suniceman))
|
||||
- 修复 ACP 设置错误中缺少 Provider 说明的问题 ([#11431](https://github.com/getpaseo/paseo/pull/11431),贡献者:[@suniceman](https://github.com/suniceman))
|
||||
- 修复上下文更新后 Muse 用量丢失 token 总数的问题 ([#11389](https://github.com/getpaseo/paseo/pull/11389),贡献者:[@suniceman](https://github.com/suniceman))
|
||||
- 修复 Claude 用量卡片持续数小时显示受速率限制的问题 ([#11597](https://github.com/getpaseo/paseo/pull/11597))
|
||||
- 修复订阅变更后 Claude 用量仍显示旧套餐的问题 ([#11685](https://github.com/getpaseo/paseo/pull/11685),贡献者:[@matchy233](https://github.com/matchy233))
|
||||
- 修复没有额度余额的账号 Codex 用量显示 0 额度的问题 ([#11515](https://github.com/getpaseo/paseo/pull/11515),贡献者:[@vivekkalyan](https://github.com/vivekkalyan))
|
||||
- 修复超出高级请求配额时 Copilot 用量获取失败的问题 ([#11006](https://github.com/getpaseo/paseo/pull/11006),贡献者:[@nathanmcnulty](https://github.com/nathanmcnulty))
|
||||
- 修复 Copilot 用量从 GitHub CLI 读取其他 GitHub 主机或账号 token 的问题 ([#11689](https://github.com/getpaseo/paseo/pull/11689))
|
||||
- 修复从 fork 执行 **创建 PR** 时将 PR 创建在 fork 而非其上游仓库的问题 ([#11436](https://github.com/getpaseo/paseo/pull/11436),贡献者:[@suniceman](https://github.com/suniceman))
|
||||
- 修复 fork PR 在首次推送后从其 worktree 工作区中消失的问题 ([#11441](https://github.com/getpaseo/paseo/pull/11441),贡献者:[@suniceman](https://github.com/suniceman))
|
||||
- 修复 **创建 PR** 返回 API 地址而非 PR 页面的问题 ([#11439](https://github.com/getpaseo/paseo/pull/11439),贡献者:[@suniceman](https://github.com/suniceman))
|
||||
- 修复 GitHub 检查详情无法加载注释的问题 ([#11476](https://github.com/getpaseo/paseo/pull/11476),贡献者:[@suniceman](https://github.com/suniceman))
|
||||
- 修复作业日志不可用时 GitHub 检查详情丢失注释的问题 ([#11509](https://github.com/getpaseo/paseo/pull/11509))
|
||||
- 修复 Gitea 和 Forgejo 的草稿 PR 显示为已打开且存在冲突的问题 ([#11545](https://github.com/getpaseo/paseo/pull/11545),贡献者:[@goodideal](https://github.com/goodideal))
|
||||
- 修复 Git 远程地址为 IPv6 的工作区无法识别其 Gitea 或 Forgejo forge 的问题 ([#11692](https://github.com/getpaseo/paseo/pull/11692),贡献者:[@jamescordrey-ops](https://github.com/jamescordrey-ops))
|
||||
- 修复 `gh` 或 `glab` 命令忽略超时导致工作区刷新卡住的问题 ([#11252](https://github.com/getpaseo/paseo/pull/11252), [#11411](https://github.com/getpaseo/paseo/pull/11411))
|
||||
- 修复在 Paseo worktree 中运行定时任务时创建重复项目的问题 ([#10378](https://github.com/getpaseo/paseo/pull/10378),贡献者:[@kotusenka](https://github.com/kotusenka))
|
||||
- 修复在其他归档或关闭操作进行时归档 Agent 报 Unknown agent 错误的问题 ([#10590](https://github.com/getpaseo/paseo/pull/10590),贡献者:[@apple-ouyang](https://github.com/apple-ouyang))
|
||||
- 修复 Agent 回复过程中收到通知导致最后一条回复被截断的问题 ([#11578](https://github.com/getpaseo/paseo/pull/11578),贡献者:[@KiritoXDone](https://github.com/KiritoXDone))
|
||||
- 修复排队消息以之后发送的提示词的模式运行的问题 ([#11722](https://github.com/getpaseo/paseo/pull/11722))
|
||||
- 修复 `paseo ls --json` 丢失时间戳和后台任务的问题 ([#11423](https://github.com/getpaseo/paseo/pull/11423),贡献者:[@KiritoXDone](https://github.com/KiritoXDone))
|
||||
- 修复 `paseo inspect` 和 `paseo ls` 隐藏 Cursor Auto 模型的问题 ([#11693](https://github.com/getpaseo/paseo/pull/11693))
|
||||
- 修复 `paseo workspace ls` 将密码错误报告为 daemon 已停止的问题 ([#11676](https://github.com/getpaseo/paseo/pull/11676),贡献者:[@chirag127](https://github.com/chirag127))
|
||||
- 修复 `paseo daemon status` 遗漏未确认的终端清理的问题 ([#11658](https://github.com/getpaseo/paseo/pull/11658),贡献者:[@chirag127](https://github.com/chirag127))
|
||||
- 修复 CLI 归档、分离和重新加载时为匹配完整 Agent ID 而扫描全部 Agent 历史记录的问题 ([#11617](https://github.com/getpaseo/paseo/pull/11617),贡献者:[@maci0](https://github.com/maci0))
|
||||
|
||||
### 安全
|
||||
|
||||
- 阻止客户端访问 Paseo 主目录中 daemon 自身的状态文件,并在已保存主机的 daemon 密钥变化时发出警告 ([#11452](https://github.com/getpaseo/paseo/pull/11452))
|
||||
- 将 daemon WebSocket 和 HTTP 请求的回环来源匹配限制为 `localhost`、`127.0.0.1` 和 `::1` ([#11686](https://github.com/getpaseo/paseo/pull/11686))
|
||||
- 禁止 PR 评论和审查中的图片读取主机上的文件 ([#11699](https://github.com/getpaseo/paseo/pull/11699))
|
||||
- 禁止 `.worktreeinclude` 将本地文件复制到来自 fork PR 的 worktree 中 ([#11709](https://github.com/getpaseo/paseo/pull/11709))
|
||||
- 拒绝指向定时任务目录之外的定时任务 ID ([#11727](https://github.com/getpaseo/paseo/pull/11727))
|
||||
|
||||
### 插件
|
||||
|
||||
- 新增工作区布局 API,插件可以打开、移动和关闭面板与标签页 ([#11328](https://github.com/getpaseo/paseo/pull/11328))
|
||||
- 新增 `requirements.app`,可单独设置与 daemon 不同的最低应用版本 ([#11494](https://github.com/getpaseo/paseo/pull/11494),贡献者:[@mcowger](https://github.com/mcowger))
|
||||
- 修复插件在按下处理函数或定时器中出错导致 iOS 和 Android 应用关闭的问题 ([#11412](https://github.com/getpaseo/paseo/pull/11412))
|
||||
- 修复插件操作删除手动添加到 `config.json` 中插件条目的问题 ([#11501](https://github.com/getpaseo/paseo/pull/11501),贡献者:[@matchy233](https://github.com/matchy233))
|
||||
- 修复 npm 在锁文件中省略 registry 地址时,注册表插件安装报 Missing npm artifact 错误的问题 ([#11656](https://github.com/getpaseo/paseo/pull/11656),贡献者:[@Brandon168](https://github.com/Brandon168))
|
||||
- 修复 daemon 运行在大型目录下时,本地插件重新加载耗时 12 至 21 秒的问题 ([#11653](https://github.com/getpaseo/paseo/pull/11653))
|
||||
|
||||
## 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))
|
||||
|
||||
@@ -178,9 +178,9 @@ the switch. Promoting the switch cuts the running turn once the target is known
|
||||
already on the target takes the message and its settings as a plain prompt. A switch that fails keeps
|
||||
the message and holds the queue; the reason is in the daemon log.
|
||||
|
||||
The queue is saved in `$PASEO_HOME/agent-queues/` ([data model](data-model.md#directory-layout)),
|
||||
The queue is saved in `$PASEO_HOME/paseo.db` ([data model](data-model.md#agent-message-queues)),
|
||||
and a message is saved before its receipt is sent. Inline images are first saved as uploads, so the
|
||||
queue file holds references. An empty message is refused, and a recipient holds at most 100
|
||||
queue holds references. An empty message is refused, and a recipient holds at most 100
|
||||
messages.
|
||||
|
||||
A message is marked `dispatching` before the provider can receive it and removed when the provider
|
||||
|
||||
@@ -219,7 +219,14 @@ file after the daemon confirms persistence.
|
||||
|
||||
> **Window-state v1 limitation:** only the _first_ window of a session restores and persists saved geometry (size/position/maximized). Windows opened via ⌘⇧N / second-instance / "Open in new window" open at the default size, OS-cascaded, and do not persist — this avoids every window stacking on the same restored bounds and fighting over the single window-state store. Lifting this needs per-window state keys.
|
||||
>
|
||||
> **In-app browser profiles.** Each local browser tab runs in a persistent Electron partition and can switch profiles at any time; switching replaces the `<webview>` under the new partition and reloads the current URL in that profile's session. Partition names are the identity: `persist:paseo-browser` is **Default** and preserves cookies from before profiles; `persist:paseo-profile-<slug>` is a named profile. Display names and colors live in the main-owned catalog `<userData>/browser-profiles.json`, so editing a profile's name or color keeps sign-ins intact and updates open tabs live. Main admits only `persist:paseo-browser`, `persist:paseo-profile-<slug>`, and active host-proxy partitions (`persist:paseo-browser-host-<16hex>`) at `will-attach-webview`. The tab's chosen profile slug lives in its `workspace-browser-store` record. After every `did-attach`, the renderer registers its browser id, workspace id, partition, and current guest `WebContents` id, and main accepts it only when that guest belongs to the calling renderer and its session matches the partition. Registration is intentionally repeated because reparenting a retained `<webview>` can replace its guest without replacing the DOM element. Settings > Chat & panes manages profiles: clearing a profile clears its storage/cache and reloads its open tabs; removing a named profile closes its open tabs, removes it from the catalog, clears its session, and deletes its `Partitions/paseo-profile-<slug>` directory from disk. Default cannot be removed.
|
||||
> **In-app browser profiles.** A browser tab's Electron partition is the pair (route, profile). The route is local, or a host's browser proxy. The profile is **Default** or a named profile. Electron sets the proxy per session (`session.setProxy`), not per `<webview>`, so the route is part of the partition name. Partition names are the identity, and `packages/desktop/src/features/browser-partition.ts` owns them:
|
||||
>
|
||||
> | Route | Default | Named profile |
|
||||
> | ----- | ------------------------------------ | --------------------------------------------------- |
|
||||
> | Local | `persist:paseo-browser` | `persist:paseo-profile-<slug>` |
|
||||
> | Host | `persist:paseo-browser-host-<16hex>` | `persist:paseo-browser-host-<16hex>-profile-<slug>` |
|
||||
>
|
||||
> `persist:paseo-browser` keeps cookies from before profiles, and the host Default name predates profiles; do not rename either. A host runs one loopback SOCKS5 server and one tunnel. Every profile session on that host points `setProxy` at the same port, so a new profile never opens a second tunnel. Main binds a host profile's session when the renderer calls `ensureHostProxy` with its slug, and verifies it with `resolveProxy`. The status snapshot lists bound sessions in `profilePartitions`, and the tab mounts only after its profile appears there. A tab can switch profile and route at any time: the `<webview>` is replaced under the new partition and reloads the current URL. Display names and colors live in the main-owned catalog `<userData>/browser-profiles.json`, so editing a name or color keeps sign-ins intact and updates open tabs live. At `will-attach-webview`, main admits local partitions and only those host partitions whose session it bound. The tab's chosen profile slug lives in its `workspace-browser-store` record. After every `did-attach`, the renderer registers its browser id, workspace id, partition, and current guest `WebContents` id. Main accepts it only when that guest belongs to the calling renderer and its session matches the partition, and for a host partition, only when the session is bound to the proxy. Registration is repeated on purpose, because reparenting a retained `<webview>` can replace its guest without replacing the DOM element. Settings > Chat & panes manages profiles on every route: clearing a profile clears its storage and cache on the local route and on each host, then reloads its open tabs. Removing a named profile closes its open tabs, removes it from the catalog, clears its sessions, and deletes each of its `Partitions/` directories. Startup deletes the directories of profiles that are no longer in the catalog. Default cannot be removed.
|
||||
>
|
||||
> **In-app browser window opens.** Ordinary link opens, including Shift-clicked links, become Paseo workspace tabs and inherit the opener tab's browser profile. Script-created opens with popup features or a named window target and POST-backed opens remain secured Electron child windows in the opener’s browser profile, preserving `window.opener`, `postMessage`, named-window reuse, request bodies, and `window.close()` for OAuth, payment, and similar popup protocols. Unsupported URL schemes are denied before either path.
|
||||
>
|
||||
|
||||
+9
-5
@@ -34,7 +34,7 @@ Workspace archive runs lifecycle teardown from the exact `cwd` but removes only
|
||||
`worktreeRoot` after its last active reference disappears. Worktree recovery recreates that backing
|
||||
checkout from `mainRepoRoot`, then restores the relative path from `worktreeRoot` to `cwd`.
|
||||
|
||||
Paseo persists most stores as JSON files, and agent timelines in the [daemon database](#daemon-database). JSON data is validated at runtime with Zod schemas. Most JSON stores write atomically (write to temp file, then rename); a few still use plain `writeFile` — see each section. JSON stores have no schema-versioning/migration framework — schemas rely on optional fields with defaults for forward compatibility, with a small amount of inline normalization in `persisted-config.ts` for legacy provider/speech entries.
|
||||
Paseo persists most stores as JSON files, and agent timelines and agent message queues in the [daemon database](#daemon-database). JSON data is validated at runtime with Zod schemas. Most JSON stores write atomically (write to temp file, then rename); a few still use plain `writeFile` — see each section. JSON stores have no schema-versioning/migration framework — schemas rely on optional fields with defaults for forward compatibility, with a small amount of inline normalization in `persisted-config.ts` for legacy provider/speech entries.
|
||||
|
||||
All server-side stores live under `$PASEO_HOME` (defaults to `~/.paseo`).
|
||||
|
||||
@@ -60,9 +60,6 @@ $PASEO_HOME/
|
||||
│ └── {agentId}.json # One file per agent
|
||||
├── schedules/
|
||||
│ └── {scheduleId}.json # One file per schedule
|
||||
├── agent-queues/
|
||||
│ ├── {agentId}.json # Undelivered messages for one agent; removed when empty
|
||||
│ └── {agentId}.json.corrupt.{ms} # Unreadable queue file, set aside at startup
|
||||
├── projects/
|
||||
│ ├── projects.json # Project registry
|
||||
│ ├── workspaces.json # Workspace registry
|
||||
@@ -188,7 +185,7 @@ Terminal activity contributes to the workspace status bucket **per `workspaceId`
|
||||
## Daemon database
|
||||
|
||||
`$PASEO_HOME/paseo.db` is one SQLite file that the daemon opens at startup with `node:sqlite`
|
||||
(`packages/server/src/server/database/`). Agent timelines are its only store today. Each store is a
|
||||
(`packages/server/src/server/database/`). Agent timelines and agent message queues live here. Each store is a
|
||||
`SchemaModule`: its own table-name prefix and an append-only list of migrations.
|
||||
|
||||
- **Migrations.** Startup runs every module's pending migrations in one transaction, so a failed
|
||||
@@ -222,6 +219,13 @@ of a streamed assistant or reasoning message is stored as one chunk per source e
|
||||
row, so a chunk never rewrites the message. An earlier file store rewrote the whole transcript on
|
||||
every update. See [owned history](timeline-sync.md#owned-history).
|
||||
|
||||
### Agent message queues
|
||||
|
||||
`AgentMessageQueueStore` stores undelivered per-recipient messages in `agent_message_queue_items`
|
||||
and monotonic per-recipient sequence counters in `agent_message_queue_recipients`. Message text and
|
||||
structured payloads are stored as JSON strings so NUL bytes and lone surrogates round-trip through
|
||||
`node:sqlite`. See [agent-lifecycle.md](agent-lifecycle.md).
|
||||
|
||||
---
|
||||
|
||||
## 2. Daemon Configuration
|
||||
|
||||
+7
-3
@@ -257,9 +257,13 @@ Do not put any other code modules in the plugin root.
|
||||
|
||||
Shared files import contract helpers and types from `@getpaseo/plugin`. Server handler files import
|
||||
`PluginHandlerContext` from `@getpaseo/plugin/server`. Client files import Paseo UI from
|
||||
`@getpaseo/plugin/client/ui`. Its `Icon` draws a Lucide name from the client's installed
|
||||
icon set, or any `PluginIcon` through its `icon` prop; an unknown name or unsafe SVG renders nothing
|
||||
so it cannot break the plugin surface.
|
||||
`@getpaseo/plugin/client/ui`. The module provides host-rendered `Icon` and `ProviderIcon`
|
||||
components. `Icon` draws a Lucide name from the client's installed icon set, or any `PluginIcon`
|
||||
through its `icon` prop; an unknown name or unsafe SVG renders nothing so it cannot break the
|
||||
plugin surface. `ProviderIcon` resolves a built-in, catalog, or host-scoped plugin provider icon,
|
||||
defaulting to the installation's host when `hostId` is omitted; unknown providers render the
|
||||
standard provider fallback. `PluginCatalogSync` hydrates the host's provider snapshot before
|
||||
installing client contributions so `ProviderIcon` resolves plugin SVGs on initial render.
|
||||
Its controlled modal keeps presentation metadata on `<Modal title="…" icon={…}>` and body UI in
|
||||
`<Modal.Content>`. Body layout, sheet-aware scrolling, and clipboard actions follow the
|
||||
[host UI contract](../public-docs/plugins/reference.md#host-ui).
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
sha256-x6E6SY98/8pUNLomlPzSNedZ+ZKJPzsQeS9L455i+n0=
|
||||
sha256-oBd6CQ8+BhzMHhrpRIwzojuFPUwqXpgc3ZAPqKPs5QQ=
|
||||
|
||||
Generated
+29
-29
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "paseo",
|
||||
"version": "0.18.2",
|
||||
"version": "0.19.0-beta.1",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "paseo",
|
||||
"version": "0.18.2",
|
||||
"version": "0.19.0-beta.1",
|
||||
"hasInstallScript": true,
|
||||
"license": "Apache-2.0",
|
||||
"workspaces": [
|
||||
@@ -37552,7 +37552,7 @@
|
||||
},
|
||||
"packages/app": {
|
||||
"name": "@getpaseo/app",
|
||||
"version": "0.18.2",
|
||||
"version": "0.19.0-beta.1",
|
||||
"dependencies": {
|
||||
"@codemirror/commands": "6.10.4",
|
||||
"@codemirror/language": "6.12.4",
|
||||
@@ -39705,13 +39705,13 @@
|
||||
},
|
||||
"packages/cli": {
|
||||
"name": "@getpaseo/cli",
|
||||
"version": "0.18.2",
|
||||
"version": "0.19.0-beta.1",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@clack/prompts": "^1.0.0",
|
||||
"@getpaseo/client": "0.18.2",
|
||||
"@getpaseo/protocol": "0.18.2",
|
||||
"@getpaseo/server": "0.18.2",
|
||||
"@getpaseo/client": "0.19.0-beta.1",
|
||||
"@getpaseo/protocol": "0.19.0-beta.1",
|
||||
"@getpaseo/server": "0.19.0-beta.1",
|
||||
"chalk": "^5.3.0",
|
||||
"commander": "^12.0.0",
|
||||
"mime-types": "^2.1.35",
|
||||
@@ -39961,11 +39961,11 @@
|
||||
},
|
||||
"packages/client": {
|
||||
"name": "@getpaseo/client",
|
||||
"version": "0.18.2",
|
||||
"version": "0.19.0-beta.1",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@getpaseo/protocol": "0.18.2",
|
||||
"@getpaseo/relay": "0.18.2",
|
||||
"@getpaseo/protocol": "0.19.0-beta.1",
|
||||
"@getpaseo/relay": "0.19.0-beta.1",
|
||||
"ws": "^8.20.0",
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
@@ -39977,7 +39977,7 @@
|
||||
},
|
||||
"packages/desktop": {
|
||||
"name": "@getpaseo/desktop",
|
||||
"version": "0.18.2",
|
||||
"version": "0.19.0-beta.1",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@getpaseo/cli": "*",
|
||||
@@ -40221,7 +40221,7 @@
|
||||
},
|
||||
"packages/expo-two-way-audio": {
|
||||
"name": "@getpaseo/expo-two-way-audio",
|
||||
"version": "0.18.2",
|
||||
"version": "0.19.0-beta.1",
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"@types/jest": "^29.5.14",
|
||||
@@ -40267,7 +40267,7 @@
|
||||
},
|
||||
"packages/highlight": {
|
||||
"name": "@getpaseo/highlight",
|
||||
"version": "0.18.2",
|
||||
"version": "0.19.0-beta.1",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@codemirror/language": "6.12.4",
|
||||
@@ -40297,7 +40297,7 @@
|
||||
},
|
||||
"packages/plugin": {
|
||||
"name": "@getpaseo/plugin",
|
||||
"version": "0.18.2",
|
||||
"version": "0.19.0-beta.1",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@agentclientprotocol/sdk": "^1.4.0",
|
||||
@@ -40305,8 +40305,8 @@
|
||||
"use-sync-external-store": "^1.6.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@getpaseo/client": "0.18.2",
|
||||
"@getpaseo/protocol": "0.18.2",
|
||||
"@getpaseo/client": "0.19.0-beta.1",
|
||||
"@getpaseo/protocol": "0.19.0-beta.1",
|
||||
"@types/node": "^20.9.0",
|
||||
"@types/react": "~19.2.0",
|
||||
"react": "19.2.3",
|
||||
@@ -40316,8 +40316,8 @@
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@getpaseo/client": "0.18.2",
|
||||
"@getpaseo/protocol": "0.18.2",
|
||||
"@getpaseo/client": "0.19.0-beta.1",
|
||||
"@getpaseo/protocol": "0.19.0-beta.1",
|
||||
"react": ">=19.1.0 <20",
|
||||
"react-native": ">=0.81.5",
|
||||
"zod": "^4.4.3"
|
||||
@@ -40339,7 +40339,7 @@
|
||||
},
|
||||
"packages/protocol": {
|
||||
"name": "@getpaseo/protocol",
|
||||
"version": "0.18.2",
|
||||
"version": "0.19.0-beta.1",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"semver": "^7.8.5",
|
||||
@@ -40366,7 +40366,7 @@
|
||||
}
|
||||
},
|
||||
"packages/react-native-enriched-markdown": {
|
||||
"version": "0.18.2",
|
||||
"version": "0.19.0-beta.1",
|
||||
"hasInstallScript": true,
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
@@ -40382,7 +40382,7 @@
|
||||
},
|
||||
"packages/relay": {
|
||||
"name": "@getpaseo/relay",
|
||||
"version": "0.18.2",
|
||||
"version": "0.19.0-beta.1",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@noble/ciphers": "^2.4.0",
|
||||
@@ -40604,17 +40604,17 @@
|
||||
},
|
||||
"packages/server": {
|
||||
"name": "@getpaseo/server",
|
||||
"version": "0.18.2",
|
||||
"version": "0.19.0-beta.1",
|
||||
"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.2",
|
||||
"@getpaseo/highlight": "0.18.2",
|
||||
"@getpaseo/plugin": "0.18.2",
|
||||
"@getpaseo/protocol": "0.18.2",
|
||||
"@getpaseo/relay": "0.18.2",
|
||||
"@getpaseo/client": "0.19.0-beta.1",
|
||||
"@getpaseo/highlight": "0.19.0-beta.1",
|
||||
"@getpaseo/plugin": "0.19.0-beta.1",
|
||||
"@getpaseo/protocol": "0.19.0-beta.1",
|
||||
"@getpaseo/relay": "0.19.0-beta.1",
|
||||
"@isaacs/ttlcache": "^2.1.4",
|
||||
"@modelcontextprotocol/node": "2.1.2",
|
||||
"@modelcontextprotocol/sdk": "1.29.0",
|
||||
@@ -41579,7 +41579,7 @@
|
||||
},
|
||||
"packages/website": {
|
||||
"name": "@getpaseo/website",
|
||||
"version": "0.18.2",
|
||||
"version": "0.19.0-beta.1",
|
||||
"dependencies": {
|
||||
"@cloudflare/vite-plugin": "^1.29.1",
|
||||
"@cloudflare/workers-types": "^4.20260317.1",
|
||||
@@ -43205,7 +43205,7 @@
|
||||
},
|
||||
"plugins": {
|
||||
"name": "@getpaseo/builtin-plugins",
|
||||
"version": "0.18.2",
|
||||
"version": "0.19.0-beta.1",
|
||||
"dependencies": {
|
||||
"@getpaseo/plugin": "*",
|
||||
"zod": "^4.4.3"
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "paseo",
|
||||
"version": "0.18.2",
|
||||
"version": "0.19.0-beta.1",
|
||||
"private": true,
|
||||
"description": "Paseo: voice-controlled development environment for local AI coding agents",
|
||||
"keywords": [
|
||||
|
||||
@@ -21,6 +21,7 @@ import {
|
||||
expectAttachButtonDisabled,
|
||||
fillComposerDraft,
|
||||
dropFileOnComposer,
|
||||
pasteFilesIntoComposer,
|
||||
sendDraftToQueue,
|
||||
expectQueuedMessageButton,
|
||||
startRunningMockAgent,
|
||||
@@ -152,7 +153,7 @@ test.describe("Composer attachments", () => {
|
||||
// needed before this can be exercised end-to-end.
|
||||
});
|
||||
|
||||
test("attaches, previews, and removes an image before dropping a file", async ({
|
||||
test("attaches files from the menu, clipboard, and drag and drop", async ({
|
||||
page,
|
||||
withWorkspace,
|
||||
}) => {
|
||||
@@ -185,6 +186,19 @@ test.describe("Composer attachments", () => {
|
||||
await expectComposerFocused(page);
|
||||
});
|
||||
|
||||
await test.step("paste a Markdown file into the composer", async () => {
|
||||
const file = {
|
||||
name: "notes.md",
|
||||
mimeType: "text/markdown",
|
||||
buffer: Buffer.from("# Clipboard notes"),
|
||||
};
|
||||
const handled = await pasteFilesIntoComposer(page, [file]);
|
||||
await expect(page.getByText(file.name, { exact: true })).toBeVisible();
|
||||
await expect(page.getByRole("button", { name: file.name, exact: true })).toBeVisible();
|
||||
expect(handled).toBe(true);
|
||||
await expectComposerDraft(page, "");
|
||||
});
|
||||
|
||||
await test.step("dropping an image focuses the composer", async () => {
|
||||
await blurComposerInput(page);
|
||||
await expectComposerNotFocused(page);
|
||||
@@ -192,6 +206,15 @@ test.describe("Composer attachments", () => {
|
||||
await expectAttachmentPill(page, "composer-image-attachment-pill");
|
||||
await expectComposerFocused(page);
|
||||
});
|
||||
|
||||
await test.step("paste a file and an image together", async () => {
|
||||
await removeAttachmentPill(page, "composer-image-attachment-pill", "Remove image attachment");
|
||||
await expect(page.getByTestId("composer-image-attachment-pill")).toHaveCount(0);
|
||||
const file = { ...TEST_JSON, name: "clipboard.json" };
|
||||
await pasteFilesIntoComposer(page, [file, TEST_IMAGE]);
|
||||
await expect(page.getByRole("button", { name: file.name, exact: true })).toBeVisible();
|
||||
await expectAttachmentPill(page, "composer-image-attachment-pill");
|
||||
});
|
||||
});
|
||||
|
||||
test("dropped JSON file renders as a file attachment in New Workspace", async ({ page }) => {
|
||||
|
||||
@@ -9,7 +9,8 @@ import {
|
||||
expectRemovedPlugin,
|
||||
} from "../support/helpers/plugin-reconnect";
|
||||
import { verifyPluginTranslations } from "../support/helpers/plugin-translations";
|
||||
import { pluginRequirements } from "../support/helpers/plugin-fixture";
|
||||
import { copyPluginExample, pluginRequirements } from "../support/helpers/plugin-fixture";
|
||||
import { expectProviderIcon, readIconPaths } from "../support/helpers/plugin-provider-icons";
|
||||
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
@@ -26,7 +27,7 @@ const TINY_PNG = Buffer.from(
|
||||
);
|
||||
|
||||
const PLUGIN_SOURCE = `import { usePaseo } from "@getpaseo/plugin/client";
|
||||
import { Icon, Modal, useToast, Markdown } from "@getpaseo/plugin/client/ui";
|
||||
import { Icon, Modal, ProviderIcon, useToast, Markdown } from "@getpaseo/plugin/client/ui";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import React, { useState } from "react";
|
||||
import { Pressable, Text, View } from "react-native";
|
||||
@@ -53,7 +54,7 @@ function ModalBody({ onSaved }) {
|
||||
</View>;
|
||||
}
|
||||
|
||||
function Surface({ playAudio }) {
|
||||
function Surface({ host, theme, playAudio }) {
|
||||
const [audioStatus, setAudioStatus] = useState("Audio ready");
|
||||
async function play(base64) {
|
||||
setAudioStatus("Playing audio");
|
||||
@@ -62,6 +63,18 @@ function Surface({ playAudio }) {
|
||||
}
|
||||
const [open, setOpen] = useState(false);
|
||||
return <View>
|
||||
<View testID="plugin-provider-icon-builtin">
|
||||
<ProviderIcon provider="codex" size={18} color={theme.colors.foreground} />
|
||||
</View>
|
||||
<View testID="plugin-provider-icon-plugin">
|
||||
<ProviderIcon provider="direct-example" hostId={host.id} size={18} color={theme.colors.foreground} />
|
||||
</View>
|
||||
<View testID="plugin-provider-icon-fallback">
|
||||
<ProviderIcon provider="unknown-provider-e2e" size={18} color={theme.colors.foreground} />
|
||||
</View>
|
||||
<View testID="plugin-provider-icon-bot-ref">
|
||||
<Icon name="Bot" size={18} color={theme.colors.foreground} />
|
||||
</View>
|
||||
<Text>{audioStatus}</Text>
|
||||
<Markdown>{"\\n\\n"}</Markdown>
|
||||
<Pressable accessibilityRole="button" onPress={() => play(AUDIO_BASE64)}><Text>Play plugin audio</Text></Pressable>
|
||||
@@ -86,7 +99,7 @@ function Surface({ playAudio }) {
|
||||
}
|
||||
|
||||
export default function contribute(plugin) {
|
||||
plugin.addSurface("main", () => <Surface playAudio={plugin.playAudio} />);
|
||||
plugin.addSurface("main", (props) => <Surface {...props} playAudio={plugin.playAudio} />);
|
||||
plugin.addSidebarItem({
|
||||
id: "main",
|
||||
title: "Host UI",
|
||||
@@ -166,8 +179,9 @@ async function savePluginIssue(page: Page): Promise<void> {
|
||||
await expect(page.getByText("Plugin modal contexts ready", { exact: true })).not.toBeVisible();
|
||||
}
|
||||
|
||||
test("plugin modal adapts its presentation and preserves host contexts", async ({ page }) => {
|
||||
test("plugin host UI renders provider icons and preserves modal contexts", async ({ page }) => {
|
||||
const directory = await mkdtemp(path.join(tmpdir(), "paseo-plugin-host-ui-e2e-"));
|
||||
const providerPlugin = await copyPluginExample("provider-direct");
|
||||
const client = await connectNewWorkspaceDaemonClient({ ownProjects: false });
|
||||
const previousConfig = await client.getDaemonConfig();
|
||||
await writeFile(
|
||||
@@ -187,10 +201,29 @@ test("plugin modal adapts its presentation and preserves host contexts", async (
|
||||
|
||||
try {
|
||||
await client.patchDaemonConfig({ pluginsEnabled: true });
|
||||
await client.installDirectoryPlugin(providerPlugin.directory);
|
||||
await client.installDirectoryPlugin(directory);
|
||||
await useNonCompactLayout(page);
|
||||
await openHostUiPlugin(page);
|
||||
|
||||
await test.step("ProviderIcon renders built-in, daemon plugin SVG, and fallback icons", async () => {
|
||||
const providerIconPaths = await readIconPaths(page, providerPlugin.directory);
|
||||
await expectProviderIcon(page.getByTestId("plugin-provider-icon-plugin"), providerIconPaths);
|
||||
|
||||
const builtinSvg = page.getByTestId("plugin-provider-icon-builtin").locator("svg");
|
||||
const fallbackSvg = page.getByTestId("plugin-provider-icon-fallback").locator("svg");
|
||||
const botRefSvg = page.getByTestId("plugin-provider-icon-bot-ref").locator("svg");
|
||||
await expect(builtinSvg).toBeVisible();
|
||||
await expect(fallbackSvg).toBeVisible();
|
||||
await expect(botRefSvg).toBeVisible();
|
||||
|
||||
const fallbackMarkup = await fallbackSvg.innerHTML();
|
||||
const botRefMarkup = await botRefSvg.innerHTML();
|
||||
const builtinMarkup = await builtinSvg.innerHTML();
|
||||
expect(fallbackMarkup).toBe(botRefMarkup);
|
||||
expect(builtinMarkup).not.toBe(botRefMarkup);
|
||||
});
|
||||
|
||||
await test.step("plugin screen Markdown renders local absolute and file:// PNG images inline", async () => {
|
||||
await expectLoadedMarkdownImage(page, "Before");
|
||||
await expectLoadedMarkdownImage(page, "After");
|
||||
@@ -217,11 +250,13 @@ test("plugin modal adapts its presentation and preserves host contexts", async (
|
||||
});
|
||||
} finally {
|
||||
await client.removePlugin(PLUGIN_ID).catch(() => undefined);
|
||||
await client.removePlugin("provider-direct-example").catch(() => undefined);
|
||||
await client
|
||||
.patchDaemonConfig({ pluginsEnabled: previousConfig.config.pluginsEnabled ?? false })
|
||||
.catch(() => undefined);
|
||||
await client.close().catch(() => undefined);
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
await providerPlugin.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -2,6 +2,8 @@ import path from "node:path";
|
||||
import type { Page, TestInfo } from "@playwright/test";
|
||||
import { test, expect } from "../support/fixtures";
|
||||
import { gotoAppShell } from "../support/helpers/app";
|
||||
import { addConnectedHostsAndReload } from "../support/helpers/hosts";
|
||||
import { startIsolatedHostDaemon } from "../support/helpers/isolated-host-daemon";
|
||||
import {
|
||||
closeMobileAgentSidebar,
|
||||
expectMobileAgentSidebarHidden,
|
||||
@@ -141,6 +143,7 @@ async function withPaseoOwnedWorktree(
|
||||
async function readCachedRowIds(
|
||||
page: Page,
|
||||
rowKind: "workspace" | "checkpoint",
|
||||
hostServerId = getServerId(),
|
||||
): Promise<string[]> {
|
||||
return page.evaluate(
|
||||
async ({ serverId, kind }) => {
|
||||
@@ -169,7 +172,7 @@ async function readCachedRowIds(
|
||||
database.close();
|
||||
}
|
||||
},
|
||||
{ serverId: getServerId(), kind: rowKind },
|
||||
{ serverId: hostServerId, kind: rowKind },
|
||||
);
|
||||
}
|
||||
|
||||
@@ -317,7 +320,60 @@ async function expectRecoveredWorkspacesAfterReload(
|
||||
});
|
||||
}
|
||||
|
||||
async function expectTimeSortingAvailable(page: Page): Promise<void> {
|
||||
await page.getByLabel("Display preferences", { exact: true }).click();
|
||||
await page.getByRole("menuitem", { name: /^Sort/ }).click();
|
||||
await expect(page.getByRole("menuitem", { name: "Created", exact: true })).toBeVisible();
|
||||
await expect(page.getByRole("menuitem", { name: "Last prompt", exact: true })).toBeVisible();
|
||||
await page.getByRole("menuitem", { name: "Created", exact: true }).click();
|
||||
await page.getByLabel("Display preferences", { exact: true }).click();
|
||||
await expect(page.getByRole("menuitem", { name: /^Sort/ })).toContainText("Created");
|
||||
await page.keyboard.press("Escape");
|
||||
}
|
||||
|
||||
async function cacheSecondaryHostWorkspace(page: Page, serverId: string, workspaceId: string) {
|
||||
await expect(page.getByTestId(`sidebar-workspace-row-${serverId}:${workspaceId}`)).toBeVisible();
|
||||
await expect.poll(() => readCachedRowIds(page, "workspace", serverId)).toContain(workspaceId);
|
||||
}
|
||||
|
||||
test.describe("Sidebar workspace list", () => {
|
||||
test("keeps time sorting when a host's cached workspaces load offline", async ({ page }) => {
|
||||
test.setTimeout(120_000);
|
||||
const laptop = await startIsolatedHostDaemon("sidebar-sort-laptop");
|
||||
try {
|
||||
const other = await startIsolatedHostDaemon("sidebar-sort-other");
|
||||
try {
|
||||
const workspace = await seedWorkspace({
|
||||
repoPrefix: "sidebar-sort-laptop-",
|
||||
port: laptop.port,
|
||||
});
|
||||
try {
|
||||
await gotoAppShell(page);
|
||||
const hosts = [
|
||||
{ ...laptop, label: "Laptop" },
|
||||
{ ...other, label: "Other host" },
|
||||
];
|
||||
await test.step("cache the laptop workspace while its host is online", async () => {
|
||||
await addConnectedHostsAndReload(page, hosts);
|
||||
await cacheSecondaryHostWorkspace(page, laptop.serverId, workspace.workspaceId);
|
||||
await expectTimeSortingAvailable(page);
|
||||
});
|
||||
await test.step("reopen the sidebar with the laptop offline", async () => {
|
||||
await laptop.close();
|
||||
await addConnectedHostsAndReload(page, hosts);
|
||||
await cacheSecondaryHostWorkspace(page, laptop.serverId, workspace.workspaceId);
|
||||
await expectTimeSortingAvailable(page);
|
||||
});
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
}
|
||||
} finally {
|
||||
await other.close();
|
||||
}
|
||||
} finally {
|
||||
await laptop.close();
|
||||
}
|
||||
});
|
||||
test("recovers missing workspaces from a damaged legacy cache after reload", async ({
|
||||
page,
|
||||
}, testInfo) => {
|
||||
|
||||
@@ -178,24 +178,50 @@ export async function attachFileFromMenu(
|
||||
await (await chooserPromise).setFiles(file);
|
||||
}
|
||||
|
||||
export async function dropFileOnComposer(
|
||||
page: Page,
|
||||
file: { name: string; mimeType: string; buffer: Buffer },
|
||||
): Promise<void> {
|
||||
const dataTransfer = await page.evaluateHandle(
|
||||
({ name, mimeType, base64 }) => {
|
||||
const bytes = Uint8Array.from(atob(base64), (char) => char.charCodeAt(0));
|
||||
const droppedFile = new File([bytes], name, { type: mimeType });
|
||||
interface TransferFile {
|
||||
name: string;
|
||||
mimeType: string;
|
||||
buffer: Buffer;
|
||||
}
|
||||
|
||||
function createFileTransfer(page: Page, files: TransferFile[]) {
|
||||
return page.evaluateHandle(
|
||||
(entries) => {
|
||||
const transfer = new DataTransfer();
|
||||
transfer.items.add(droppedFile);
|
||||
for (const { name, mimeType, base64 } of entries) {
|
||||
const bytes = Uint8Array.from(atob(base64), (char) => char.charCodeAt(0));
|
||||
transfer.items.add(new File([bytes], name, { type: mimeType }));
|
||||
}
|
||||
return transfer;
|
||||
},
|
||||
{
|
||||
name: file.name,
|
||||
mimeType: file.mimeType,
|
||||
base64: file.buffer.toString("base64"),
|
||||
},
|
||||
files.map(({ name, mimeType, buffer }) => ({
|
||||
name,
|
||||
mimeType,
|
||||
base64: buffer.toString("base64"),
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
export async function pasteFilesIntoComposer(page: Page, files: TransferFile[]): Promise<boolean> {
|
||||
const clipboardData = await createFileTransfer(page, files);
|
||||
try {
|
||||
const input = composerInput(page);
|
||||
await input.focus();
|
||||
return await input.evaluate((element, transfer) => {
|
||||
const event = new ClipboardEvent("paste", {
|
||||
clipboardData: transfer,
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
});
|
||||
return !element.dispatchEvent(event);
|
||||
}, clipboardData);
|
||||
} finally {
|
||||
await clipboardData.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
export async function dropFileOnComposer(page: Page, file: TransferFile): Promise<void> {
|
||||
const dataTransfer = await createFileTransfer(page, [file]);
|
||||
|
||||
const composerRoot = page.getByTestId("message-input-root").filter({ visible: true }).first();
|
||||
await expect(composerRoot).toBeVisible({ timeout: 10_000 });
|
||||
|
||||
@@ -15,7 +15,7 @@ const MODEL_LABEL = "Select model (Example 1)";
|
||||
const WIDE = { width: 1400, height: 950 };
|
||||
const COMPACT = { width: 390, height: 844 };
|
||||
|
||||
async function readIconPaths(page: Page, pluginDirectory: string): Promise<string[]> {
|
||||
export async function readIconPaths(page: Page, pluginDirectory: string): Promise<string[]> {
|
||||
const svg = await readFile(path.join(pluginDirectory, "icon.svg"), "utf8");
|
||||
return page.evaluate(
|
||||
(source) =>
|
||||
@@ -33,7 +33,7 @@ function readIconDrawings(icons: SVGElement[]): string[][] {
|
||||
);
|
||||
}
|
||||
|
||||
async function expectProviderIcon(surface: Locator, paths: string[]): Promise<void> {
|
||||
export async function expectProviderIcon(surface: Locator, paths: string[]): Promise<void> {
|
||||
await expect(surface).toBeVisible();
|
||||
// Provider icons are decorative SVGs without accessible names. Compare the
|
||||
// plugin asset's drawing, allowing surface-specific size and theme colours.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/app",
|
||||
"version": "0.18.2",
|
||||
"version": "0.19.0-beta.1",
|
||||
"private": true,
|
||||
"main": "index.ts",
|
||||
"scripts": {
|
||||
|
||||
@@ -242,6 +242,28 @@ const longEditDetail = {
|
||||
newString: "new line\n".repeat(80),
|
||||
};
|
||||
|
||||
describe("tool detail empty state", () => {
|
||||
it("insets the empty-state text from the disclosure edge", () => {
|
||||
act(() =>
|
||||
root.render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<ToolCallDetailsContent maxHeight={200} />
|
||||
</QueryClientProvider>,
|
||||
),
|
||||
);
|
||||
const text = view().getByText("No additional details available");
|
||||
const style = getComputedStyle(text);
|
||||
expect(style.paddingTop).toBe("12px");
|
||||
expect(style.paddingRight).toBe("12px");
|
||||
expect(style.paddingBottom).toBe("12px");
|
||||
expect(style.paddingLeft).toBe("12px");
|
||||
const textBox = text.getBoundingClientRect();
|
||||
const containerBox = container.getBoundingClientRect();
|
||||
expect(textBox.left).toBeGreaterThanOrEqual(containerBox.left);
|
||||
expect(textBox.right).toBeLessThanOrEqual(containerBox.right);
|
||||
});
|
||||
});
|
||||
|
||||
describe("capped tool scrolling", () => {
|
||||
it.each([longShellDetail, longEditDetail])(
|
||||
"gives a capped $type detail one vertical scroll owner",
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { getFileExtension } from "@/attachments/file-types";
|
||||
import { getFileExtension, getMimeTypeFromPath } from "@/attachments/file-types";
|
||||
import { copyDesktopAttachmentFile } from "@/desktop/attachments/desktop-file-commands";
|
||||
import { readDesktopFileBase64 } from "@/desktop/attachments/desktop-preview-url";
|
||||
|
||||
@@ -8,6 +8,14 @@ export interface SelectedFile {
|
||||
readBytes(): Promise<Uint8Array>;
|
||||
}
|
||||
|
||||
export function selectedFileFromWebFile(file: File): SelectedFile {
|
||||
return {
|
||||
fileName: file.name,
|
||||
mimeType: file.type || getMimeTypeFromPath(file.name),
|
||||
readBytes: async () => new Uint8Array(await file.arrayBuffer()),
|
||||
};
|
||||
}
|
||||
|
||||
function base64ToUint8Array(base64: string): Uint8Array {
|
||||
const binaryString = atob(base64);
|
||||
const bytes = new Uint8Array(binaryString.length);
|
||||
|
||||
@@ -747,6 +747,7 @@ const styles = StyleSheet.create((theme) => {
|
||||
color: theme.colors.destructive,
|
||||
},
|
||||
emptyStateText: {
|
||||
padding: insets.padding,
|
||||
color: theme.colors.foregroundMuted,
|
||||
fontSize: theme.fontSize.base,
|
||||
fontStyle: "italic",
|
||||
|
||||
@@ -995,6 +995,65 @@ describe("attachments restored from a queued message", () => {
|
||||
expect(client.calls[0]?.options.attachments).toEqual([uploadedImage]);
|
||||
});
|
||||
|
||||
it("clears the optimistic timeline bubble when a direct send is queued behind a boundary", async () => {
|
||||
const client = createFakeSendClient();
|
||||
client.sendAgentMessage = async (agentId, text, options) => {
|
||||
client.calls.push({ agentId, text, options });
|
||||
return { deliveryStatus: "queued", messageId: options.messageId };
|
||||
};
|
||||
const stream = createFakeStream();
|
||||
|
||||
await dispatchComposerAgentMessage({
|
||||
client,
|
||||
agentId: "agent",
|
||||
text: "follow up",
|
||||
attachments: [],
|
||||
submission: stream,
|
||||
activeTurnBehavior: "interrupt",
|
||||
});
|
||||
|
||||
expect(stream.tail.get("agent") ?? []).toEqual([]);
|
||||
expect(stream.head.get("agent") ?? []).toEqual([]);
|
||||
});
|
||||
|
||||
it("clears the optimistic timeline bubble and settles staged switch via queued callback when a direct provider switch is queued", async () => {
|
||||
const client = createFakeSendClient();
|
||||
client.switchAgentProvider = async () => ({
|
||||
deliveryStatus: "queued",
|
||||
agent: undefined,
|
||||
});
|
||||
const stream = createFakeStream();
|
||||
let committed = 0;
|
||||
let queued = 0;
|
||||
|
||||
await dispatchComposerAgentMessage({
|
||||
client,
|
||||
agentId: "agent",
|
||||
text: "switch later",
|
||||
attachments: [],
|
||||
submission: stream,
|
||||
currentProvider: "claude",
|
||||
stagedProviderSwitch: {
|
||||
provider: "codex",
|
||||
model: null,
|
||||
thinkingOptionId: null,
|
||||
modeId: null,
|
||||
providerOptions: {},
|
||||
},
|
||||
onProviderSwitchCommitted: () => {
|
||||
committed += 1;
|
||||
},
|
||||
onProviderSwitchQueued: () => {
|
||||
queued += 1;
|
||||
},
|
||||
});
|
||||
|
||||
expect(committed).toBe(0);
|
||||
expect(queued).toBe(1);
|
||||
expect(stream.tail.get("agent") ?? []).toEqual([]);
|
||||
expect(stream.head.get("agent") ?? []).toEqual([]);
|
||||
});
|
||||
|
||||
it("counts a restored forge item as selected and toggles it off", () => {
|
||||
expect(isAttachmentSelectedForForgeItem([restoredIssue], issueItem)).toBe(true);
|
||||
expect(isAttachmentSelectedForForgeItem([restoredIssue], prItem)).toBe(false);
|
||||
|
||||
@@ -217,6 +217,7 @@ export interface DispatchComposerAgentMessageInput {
|
||||
currentModel?: string | null;
|
||||
stagedProviderSwitch?: StagedProviderSwitch | null;
|
||||
onProviderSwitchCommitted?: (agent: AgentSnapshotPayload | undefined) => void | Promise<void>;
|
||||
onProviderSwitchQueued?: () => void;
|
||||
}
|
||||
|
||||
function buildPendingProviderSwitch(
|
||||
@@ -242,6 +243,15 @@ function buildPendingProviderSwitch(
|
||||
});
|
||||
}
|
||||
|
||||
function isQueuedDeliveryResult(result: unknown): boolean {
|
||||
return (
|
||||
typeof result === "object" &&
|
||||
result !== null &&
|
||||
"deliveryStatus" in result &&
|
||||
result.deliveryStatus === "queued"
|
||||
);
|
||||
}
|
||||
|
||||
export async function dispatchComposerAgentMessage(
|
||||
input: DispatchComposerAgentMessageInput,
|
||||
): Promise<void> {
|
||||
@@ -281,16 +291,25 @@ export async function dispatchComposerAgentMessage(
|
||||
...(imagePayload.images ? { images: imagePayload.images } : {}),
|
||||
attachments: [...wirePayload.attachments, ...(imagePayload.attachments ?? [])],
|
||||
});
|
||||
if (isQueuedDeliveryResult(result)) {
|
||||
input.submission.reject(input.agentId, clientMessageId);
|
||||
input.onProviderSwitchQueued?.();
|
||||
return;
|
||||
}
|
||||
input.submission.accept(input.agentId, clientMessageId);
|
||||
await input.onProviderSwitchCommitted?.(result.agent);
|
||||
return;
|
||||
}
|
||||
await input.client.sendAgentMessage(input.agentId, input.text, {
|
||||
const result = await input.client.sendAgentMessage(input.agentId, input.text, {
|
||||
messageId: clientMessageId,
|
||||
...(input.activeTurnBehavior ? { activeTurnBehavior: input.activeTurnBehavior } : {}),
|
||||
...(imagePayload.images ? { images: imagePayload.images } : {}),
|
||||
attachments: [...wirePayload.attachments, ...(imagePayload.attachments ?? [])],
|
||||
});
|
||||
if (isQueuedDeliveryResult(result)) {
|
||||
input.submission.reject(input.agentId, clientMessageId);
|
||||
return;
|
||||
}
|
||||
input.submission.accept(input.agentId, clientMessageId);
|
||||
} catch (error) {
|
||||
input.submission.reject(input.agentId, clientMessageId);
|
||||
|
||||
@@ -3,7 +3,11 @@ import {
|
||||
isRasterImageFile,
|
||||
isRasterImagePath,
|
||||
} from "@/attachments/file-types";
|
||||
import { readDesktopFileBytes, type SelectedFile } from "@/attachments/selected-file";
|
||||
import {
|
||||
readDesktopFileBytes,
|
||||
selectedFileFromWebFile,
|
||||
type SelectedFile,
|
||||
} from "@/attachments/selected-file";
|
||||
import type { DroppedItem } from "@/components/file-drop/types";
|
||||
|
||||
interface DroppedAttachmentsRuntime {
|
||||
@@ -36,12 +40,7 @@ export function droppedItemsToSelectedFiles(
|
||||
if (isRasterImageFile(item.file)) {
|
||||
continue;
|
||||
}
|
||||
const file = item.file;
|
||||
files.push({
|
||||
fileName: file.name,
|
||||
mimeType: file.type || getMimeTypeFromPath(file.name),
|
||||
readBytes: async () => new Uint8Array(await file.arrayBuffer()),
|
||||
});
|
||||
files.push(selectedFileFromWebFile(item.file));
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
@@ -166,7 +166,7 @@ import type {
|
||||
WorkspaceFileComposerAttachment,
|
||||
WorkspaceComposerAttachment,
|
||||
} from "@/attachments/types";
|
||||
import type { SelectedFile } from "@/attachments/selected-file";
|
||||
import { selectedFileFromWebFile, type SelectedFile } from "@/attachments/selected-file";
|
||||
import { resolveComposerAttachmentSubmitFormat } from "@/composer/attachments/submit";
|
||||
import { ComposerInputProvider, type ComposerInput } from "@/composer/session";
|
||||
import type { ComposerFocusOptions } from "@/composer/model";
|
||||
@@ -1775,6 +1775,11 @@ function ComposerContentImpl({
|
||||
}
|
||||
}
|
||||
},
|
||||
onProviderSwitchQueued: () => {
|
||||
if (stagedProviderSwitch) {
|
||||
settleStagedProviderSwitch(serverId, targetAgentId, stagedProviderSwitch);
|
||||
}
|
||||
},
|
||||
activeTurnBehavior,
|
||||
activeTurnId:
|
||||
activeTurnBehavior === "steer"
|
||||
@@ -2041,6 +2046,13 @@ function ComposerContentImpl({
|
||||
[addFiles, client, t],
|
||||
);
|
||||
|
||||
const handlePasteFiles = useCallback(
|
||||
(files: File[]) => {
|
||||
void uploadSelectedFiles(files.map(selectedFileFromWebFile));
|
||||
},
|
||||
[uploadSelectedFiles],
|
||||
);
|
||||
|
||||
const handlePickFile = useCallback(async () => {
|
||||
if (!client) {
|
||||
toastErrorRef.current(t("composer.errors.daemonClientDisconnected"));
|
||||
@@ -2698,6 +2710,7 @@ function ComposerContentImpl({
|
||||
attachmentMenuItems={attachmentMenuItems}
|
||||
onAttachButtonRef={handleAttachButtonRef}
|
||||
onAddImages={addImages}
|
||||
onPasteFiles={handlePasteFiles}
|
||||
onPasteImages={handleNativePasteImages}
|
||||
client={client}
|
||||
isReadyForDictation={isDictationReady}
|
||||
|
||||
@@ -21,6 +21,7 @@ import {
|
||||
useRef,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useEffectEvent,
|
||||
useLayoutEffect,
|
||||
useImperativeHandle,
|
||||
useMemo,
|
||||
@@ -64,6 +65,7 @@ import {
|
||||
collectImageFilesFromClipboardData,
|
||||
filesToImageAttachments,
|
||||
} from "@/utils/image-attachments-from-files";
|
||||
import { isRasterImageFile } from "@/attachments/file-types";
|
||||
import type { ComposerAttachment } from "@/attachments/types";
|
||||
import type { ImageAttachment, MessagePayload, TextReplacement } from "@/composer/types";
|
||||
import { focusWithRetries } from "@/utils/web-focus";
|
||||
@@ -81,7 +83,7 @@ import { formatShortcut, type ShortcutKey } from "@/utils/format-shortcut";
|
||||
import { getShortcutOs } from "@/utils/shortcut-platform";
|
||||
import type { MessageInputKeyboardActionKind } from "@/keyboard/actions";
|
||||
import { isImeComposingKeyboardEvent } from "@/utils/keyboard-ime";
|
||||
import { isNative, isWeb } from "@/constants/platform";
|
||||
import { getIsElectron, isNative, isWeb } from "@/constants/platform";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { useComposerKeyboardScope } from "@/composer/keyboard-scope";
|
||||
import { RenderProfile } from "@/utils/render-profiler";
|
||||
@@ -173,6 +175,7 @@ export interface MessageInputProps {
|
||||
attachmentMenuItems: AttachmentMenuItem[];
|
||||
onAttachButtonRef?: (node: View | null) => void;
|
||||
onAddImages?: (images: ImageAttachment[]) => void;
|
||||
onPasteFiles?: (files: File[]) => void;
|
||||
onPasteImages?: (files: readonly NativePastedFile[]) => void;
|
||||
client: DaemonClient | null;
|
||||
/** Dictation start gate from host runtime (socket connected + directory ready). */
|
||||
@@ -520,22 +523,36 @@ function getTextInputNativeElement(current: ComposerTextInputHandle | null): HTM
|
||||
interface PasteEffectArgs {
|
||||
textarea: HTMLElement | null;
|
||||
isConnected: boolean;
|
||||
isSubmitLoading: boolean;
|
||||
disabled: boolean;
|
||||
isDictating: boolean;
|
||||
isRealtimeVoiceForCurrentAgent: boolean;
|
||||
onAddImages: ((images: ImageAttachment[]) => void) | undefined;
|
||||
onPasteFiles: ((files: File[]) => void) | undefined;
|
||||
}
|
||||
|
||||
function usePasteEffect(args: PasteEffectArgs): void {
|
||||
const {
|
||||
textarea,
|
||||
isConnected,
|
||||
isSubmitLoading,
|
||||
disabled,
|
||||
isDictating,
|
||||
isRealtimeVoiceForCurrentAgent,
|
||||
onAddImages,
|
||||
onPasteFiles,
|
||||
} = args;
|
||||
|
||||
const pasteFiles = useEffectEvent((clipboardData: DataTransfer | null) => {
|
||||
if (!isConnected || isSubmitLoading || !onPasteFiles || getIsElectron()) return false;
|
||||
|
||||
const files = Array.from(clipboardData?.files ?? []).filter((file) => !isRasterImageFile(file));
|
||||
if (files.length === 0) return false;
|
||||
|
||||
onPasteFiles(files);
|
||||
return true;
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!isWeb) return;
|
||||
|
||||
@@ -546,8 +563,13 @@ function usePasteEffect(args: PasteEffectArgs): void {
|
||||
if (disabled || isDictating || isRealtimeVoiceForCurrentAgent) return;
|
||||
|
||||
const imageFiles = collectImageFilesFromClipboardData(event.clipboardData);
|
||||
const didPasteFiles = pasteFiles(event.clipboardData);
|
||||
if (didPasteFiles) event.preventDefault();
|
||||
|
||||
if (imageFiles.length === 0) {
|
||||
if (pasteLinkedClipboardText(textarea, event.clipboardData)) event.preventDefault();
|
||||
if (!didPasteFiles && pasteLinkedClipboardText(textarea, event.clipboardData)) {
|
||||
event.preventDefault();
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (!isConnected || !onAddImages) return;
|
||||
@@ -1191,6 +1213,7 @@ interface ResolvedMessageInputProps {
|
||||
attachmentMenuItems: AttachmentMenuItem[];
|
||||
onAttachButtonRef: ((node: View | null) => void) | undefined;
|
||||
onAddImages: ((images: ImageAttachment[]) => void) | undefined;
|
||||
onPasteFiles: ((files: File[]) => void) | undefined;
|
||||
onPasteImages: ((files: readonly NativePastedFile[]) => void) | undefined;
|
||||
client: DaemonClient | null;
|
||||
isReadyForDictation: boolean | undefined;
|
||||
@@ -1239,6 +1262,7 @@ function resolveMessageInputProps(props: MessageInputProps): ResolvedMessageInpu
|
||||
attachmentMenuItems: props.attachmentMenuItems,
|
||||
onAttachButtonRef: props.onAttachButtonRef,
|
||||
onAddImages: props.onAddImages,
|
||||
onPasteFiles: props.onPasteFiles,
|
||||
onPasteImages: props.onPasteImages,
|
||||
client: props.client,
|
||||
isReadyForDictation: props.isReadyForDictation,
|
||||
@@ -1321,6 +1345,7 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
|
||||
attachmentMenuItems,
|
||||
onAttachButtonRef,
|
||||
onAddImages,
|
||||
onPasteFiles,
|
||||
onPasteImages,
|
||||
client,
|
||||
isReadyForDictation,
|
||||
@@ -1874,6 +1899,8 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
|
||||
isDictating,
|
||||
isRealtimeVoiceForCurrentAgent,
|
||||
onAddImages,
|
||||
onPasteFiles,
|
||||
isSubmitLoading,
|
||||
});
|
||||
|
||||
const handleSelectionChange = useCallback(
|
||||
|
||||
@@ -1,8 +1,4 @@
|
||||
import {
|
||||
DEFAULT_BROWSER_PROFILE_SLUG,
|
||||
getBrowserProfilePartition,
|
||||
useBrowserProfileCatalog,
|
||||
} from "../profiles";
|
||||
import { DEFAULT_BROWSER_PROFILE_SLUG, useBrowserProfileCatalog } from "../profiles";
|
||||
import { ProfileSelector } from "./profile-selector.electron";
|
||||
import {
|
||||
useCallback,
|
||||
@@ -831,16 +827,12 @@ export function BrowserPane({
|
||||
const updateBrowser = useBrowserStore((state) => state.updateBrowser);
|
||||
const setBrowserViewport = useBrowserStore((state) => state.setBrowserViewport);
|
||||
const setBrowserRoutingMode = useBrowserStore((state) => state.setBrowserRoutingMode);
|
||||
const proxyState = useHostBrowserProxy({ serverId, routingMode: browser?.routingMode });
|
||||
const isLocalProfileMode =
|
||||
proxyState.kind === "ready" && proxyState.effectiveRoutingMode === "local";
|
||||
let activePartition: string | null = null;
|
||||
if (proxyState.kind === "ready") {
|
||||
activePartition =
|
||||
proxyState.effectiveRoutingMode === "host"
|
||||
? proxyState.partition
|
||||
: getBrowserProfilePartition(profileSlug);
|
||||
}
|
||||
const proxyState = useHostBrowserProxy({
|
||||
serverId,
|
||||
routingMode: browser?.routingMode,
|
||||
profileSlug,
|
||||
});
|
||||
const activePartition = proxyState.kind === "ready" ? proxyState.partition : null;
|
||||
const browserViewport = browser?.viewport ?? RESPONSIVE_BROWSER_VIEWPORT;
|
||||
const browserViewportRef = useRef(browserViewport);
|
||||
browserViewportRef.current = browserViewport;
|
||||
@@ -1813,15 +1805,13 @@ export function BrowserPane({
|
||||
initialValue={draftUrl}
|
||||
/>
|
||||
</View>
|
||||
{isLocalProfileMode ? (
|
||||
<ProfileSelector
|
||||
selectedSlug={profileSlug}
|
||||
catalog={catalog.data ?? []}
|
||||
triggerStyle={profileTriggerStyle}
|
||||
onSelect={selectProfile}
|
||||
refresh={refreshProfiles}
|
||||
/>
|
||||
) : null}
|
||||
<ProfileSelector
|
||||
selectedSlug={profileSlug}
|
||||
catalog={catalog.data ?? []}
|
||||
triggerStyle={profileTriggerStyle}
|
||||
onSelect={selectProfile}
|
||||
refresh={refreshProfiles}
|
||||
/>
|
||||
<View style={styles.chromeRight}>
|
||||
<DeviceSizeMenu
|
||||
selectedId={selectedDeviceSizeId}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { getIsElectron } from "@/constants/platform";
|
||||
import { DEFAULT_BROWSER_PROFILE_SLUG } from "@/desktop/browser/profiles";
|
||||
import {
|
||||
getDesktopHost,
|
||||
type DesktopBrowserProxyStatusSnapshot,
|
||||
@@ -35,13 +36,18 @@ function notifyStatusListeners(serverId: string): void {
|
||||
}
|
||||
}
|
||||
|
||||
function hasSameProfilePartitions(a: Record<string, string>, b: Record<string, string>): boolean {
|
||||
const slugs = Object.keys(a);
|
||||
return slugs.length === Object.keys(b).length && slugs.every((slug) => a[slug] === b[slug]);
|
||||
}
|
||||
|
||||
function setCachedStatus(snapshot: DesktopBrowserProxyStatusSnapshot): void {
|
||||
const existing = statusByServerId.get(snapshot.serverId);
|
||||
if (
|
||||
existing &&
|
||||
existing.status === snapshot.status &&
|
||||
existing.error === snapshot.error &&
|
||||
existing.partition === snapshot.partition &&
|
||||
hasSameProfilePartitions(existing.profilePartitions, snapshot.profilePartitions) &&
|
||||
existing.socksPort === snapshot.socksPort
|
||||
) {
|
||||
return;
|
||||
@@ -53,9 +59,12 @@ function setCachedStatus(snapshot: DesktopBrowserProxyStatusSnapshot): void {
|
||||
function isStatusSnapshot(value: unknown): value is DesktopBrowserProxyStatusSnapshot {
|
||||
if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
|
||||
const record = value as Record<string, unknown>;
|
||||
const profilePartitions = record.profilePartitions;
|
||||
return (
|
||||
typeof record.serverId === "string" &&
|
||||
typeof record.partition === "string" &&
|
||||
typeof profilePartitions === "object" &&
|
||||
profilePartitions !== null &&
|
||||
Object.values(profilePartitions).every((partition) => typeof partition === "string") &&
|
||||
typeof record.status === "string"
|
||||
);
|
||||
}
|
||||
@@ -268,6 +277,7 @@ export function subscribeBrowserProxyStatus(serverId: string, listener: () => vo
|
||||
export async function ensureHostBrowserProxy(input: {
|
||||
serverId: string;
|
||||
target: SupportedTarget;
|
||||
profileSlug?: string;
|
||||
forceReconnect?: boolean;
|
||||
}): Promise<DesktopBrowserProxyStatusSnapshot | null> {
|
||||
installBrowserProxyRendererBridge();
|
||||
@@ -345,14 +355,15 @@ export async function prepareHostBrowserPartition(
|
||||
message: "Browser proxy bridge is unavailable in this desktop build.",
|
||||
};
|
||||
}
|
||||
if (status.status !== "ready") {
|
||||
const partition = status.profilePartitions[DEFAULT_BROWSER_PROFILE_SLUG];
|
||||
if (status.status !== "ready" || !partition) {
|
||||
return {
|
||||
ok: false,
|
||||
reason: "proxy_error",
|
||||
message: status.error ?? "Unable to connect browser proxy.",
|
||||
};
|
||||
}
|
||||
return { ok: true, partition: status.partition, isRemoteHost: true };
|
||||
return { ok: true, partition, isRemoteHost: true };
|
||||
} catch (error) {
|
||||
return {
|
||||
ok: false,
|
||||
|
||||
@@ -9,7 +9,7 @@ describe("resolveBrowserProxyPaneState", () => {
|
||||
resolveBrowserProxyPaneState({
|
||||
routing: { kind: "remote", support: "host_connecting" },
|
||||
effectiveRoutingMode: "host",
|
||||
localPartition: "persist:paseo-browser",
|
||||
profileSlug: "default",
|
||||
hostLabel: "devbox",
|
||||
proxyStatusSnapshot: null,
|
||||
ensureError: null,
|
||||
@@ -27,11 +27,11 @@ describe("resolveBrowserProxyPaneState", () => {
|
||||
resolveBrowserProxyPaneState({
|
||||
routing: { kind: "remote", support: "host_offline" },
|
||||
effectiveRoutingMode: "host",
|
||||
localPartition: "persist:paseo-browser",
|
||||
profileSlug: "default",
|
||||
hostLabel: "devbox",
|
||||
proxyStatusSnapshot: {
|
||||
serverId: "srv-remote",
|
||||
partition: "persist:paseo-browser-host-0123456789abcdef",
|
||||
profilePartitions: { default: "persist:paseo-browser-host-0123456789abcdef" },
|
||||
status: "connecting",
|
||||
error: null,
|
||||
socksPort: null,
|
||||
@@ -50,7 +50,7 @@ describe("resolveBrowserProxyPaneState", () => {
|
||||
it("keeps the prepared host partition mounted across transient host disconnects and reconnects", () => {
|
||||
const preparedSnapshot = {
|
||||
serverId: "srv-remote",
|
||||
partition: "persist:paseo-browser-host-0123456789abcdef",
|
||||
profilePartitions: { default: "persist:paseo-browser-host-0123456789abcdef" },
|
||||
status: "ready" as const,
|
||||
error: null,
|
||||
socksPort: 41234,
|
||||
@@ -60,7 +60,7 @@ describe("resolveBrowserProxyPaneState", () => {
|
||||
resolveBrowserProxyPaneState({
|
||||
routing: { kind: "remote", support: "host_offline" },
|
||||
effectiveRoutingMode: "host",
|
||||
localPartition: "persist:paseo-browser",
|
||||
profileSlug: "default",
|
||||
hostLabel: "devbox",
|
||||
proxyStatusSnapshot: preparedSnapshot,
|
||||
ensureError: null,
|
||||
@@ -68,7 +68,7 @@ describe("resolveBrowserProxyPaneState", () => {
|
||||
}),
|
||||
).toEqual({
|
||||
kind: "ready",
|
||||
partition: preparedSnapshot.partition,
|
||||
partition: preparedSnapshot.profilePartitions.default,
|
||||
isRemoteHost: true,
|
||||
effectiveRoutingMode: "host",
|
||||
hostLabel: "devbox",
|
||||
@@ -79,7 +79,7 @@ describe("resolveBrowserProxyPaneState", () => {
|
||||
resolveBrowserProxyPaneState({
|
||||
routing: { kind: "remote", support: "host_connecting" },
|
||||
effectiveRoutingMode: "host",
|
||||
localPartition: "persist:paseo-browser",
|
||||
profileSlug: "default",
|
||||
hostLabel: "devbox",
|
||||
proxyStatusSnapshot: preparedSnapshot,
|
||||
ensureError: null,
|
||||
@@ -87,7 +87,7 @@ describe("resolveBrowserProxyPaneState", () => {
|
||||
}),
|
||||
).toEqual({
|
||||
kind: "ready",
|
||||
partition: preparedSnapshot.partition,
|
||||
partition: preparedSnapshot.profilePartitions.default,
|
||||
isRemoteHost: true,
|
||||
effectiveRoutingMode: "host",
|
||||
hostLabel: "devbox",
|
||||
@@ -106,11 +106,11 @@ describe("resolveBrowserProxyPaneState", () => {
|
||||
resolveBrowserProxyPaneState({
|
||||
routing: supportedRouting,
|
||||
effectiveRoutingMode: "host",
|
||||
localPartition: "persist:paseo-browser",
|
||||
profileSlug: "default",
|
||||
hostLabel: "devbox",
|
||||
proxyStatusSnapshot: {
|
||||
serverId: "srv-remote",
|
||||
partition: "persist:paseo-browser-host-0123456789abcdef",
|
||||
profilePartitions: { default: "persist:paseo-browser-host-0123456789abcdef" },
|
||||
status: "error",
|
||||
error: "Host disconnected",
|
||||
socksPort: 41234,
|
||||
@@ -133,11 +133,11 @@ describe("resolveBrowserProxyPaneState", () => {
|
||||
resolveBrowserProxyPaneState({
|
||||
routing: supportedRouting,
|
||||
effectiveRoutingMode: "host",
|
||||
localPartition: "persist:paseo-browser",
|
||||
profileSlug: "default",
|
||||
hostLabel: "devbox",
|
||||
proxyStatusSnapshot: {
|
||||
serverId: "srv-remote",
|
||||
partition: "persist:paseo-browser-host-0123456789abcdef",
|
||||
profilePartitions: { default: "persist:paseo-browser-host-0123456789abcdef" },
|
||||
status: "ready",
|
||||
error: null,
|
||||
socksPort: 41234,
|
||||
@@ -159,11 +159,11 @@ describe("resolveBrowserProxyPaneState", () => {
|
||||
resolveBrowserProxyPaneState({
|
||||
routing: supportedRouting,
|
||||
effectiveRoutingMode: "host",
|
||||
localPartition: "persist:paseo-browser",
|
||||
profileSlug: "default",
|
||||
hostLabel: "devbox",
|
||||
proxyStatusSnapshot: {
|
||||
serverId: "srv-remote",
|
||||
partition: "persist:paseo-browser-host-0123456789abcdef",
|
||||
profilePartitions: { default: "persist:paseo-browser-host-0123456789abcdef" },
|
||||
status: "error",
|
||||
error: "Unable to create ticket",
|
||||
socksPort: null,
|
||||
@@ -185,7 +185,7 @@ describe("resolveBrowserProxyPaneState", () => {
|
||||
const routedTarget = { via: "unix:///tmp/paseo.sock", serverId: "srv-dev" };
|
||||
const input = {
|
||||
effectiveRoutingMode: "host" as const,
|
||||
localPartition: "persist:paseo-browser",
|
||||
profileSlug: "default",
|
||||
hostLabel: "dev",
|
||||
ensureError: null,
|
||||
onRetry: noop,
|
||||
@@ -212,7 +212,7 @@ describe("resolveBrowserProxyPaneState", () => {
|
||||
routing,
|
||||
proxyStatusSnapshot: {
|
||||
serverId: "srv-dev",
|
||||
partition: "persist:paseo-browser-host-dev",
|
||||
profilePartitions: { default: "persist:paseo-browser-host-dev" },
|
||||
status: "ready",
|
||||
error: null,
|
||||
socksPort: 41000,
|
||||
@@ -250,7 +250,7 @@ describe("resolveBrowserProxyPaneState", () => {
|
||||
routing: { kind: "remote", support: "host_connecting" },
|
||||
proxyStatusSnapshot: {
|
||||
serverId: "srv-dev",
|
||||
partition: "persist:paseo-browser-host-dev",
|
||||
profilePartitions: { default: "persist:paseo-browser-host-dev" },
|
||||
status: "ready",
|
||||
error: null,
|
||||
socksPort: 41000,
|
||||
@@ -259,4 +259,102 @@ describe("resolveBrowserProxyPaneState", () => {
|
||||
).toMatchObject({ kind: "ready", proxyStatus: "reconnecting" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("browser profiles", () => {
|
||||
const hostDefault = "persist:paseo-browser-host-0123456789abcdef";
|
||||
const hostWork = `${hostDefault}-profile-work`;
|
||||
const supportedRouting = {
|
||||
kind: "remote" as const,
|
||||
support: "supported" as const,
|
||||
target: "tcp://10.0.0.5:6767",
|
||||
};
|
||||
const base = {
|
||||
hostLabel: "devbox",
|
||||
ensureError: null,
|
||||
onRetry: noop,
|
||||
};
|
||||
|
||||
it("mounts the local partition of the tab's profile when routing locally", () => {
|
||||
expect(
|
||||
resolveBrowserProxyPaneState({
|
||||
...base,
|
||||
routing: supportedRouting,
|
||||
effectiveRoutingMode: "local",
|
||||
profileSlug: "work",
|
||||
proxyStatusSnapshot: null,
|
||||
}),
|
||||
).toMatchObject({ kind: "ready", partition: "persist:paseo-profile-work" });
|
||||
});
|
||||
|
||||
it("waits for the host to bind the profile's session instead of mounting another profile", () => {
|
||||
expect(
|
||||
resolveBrowserProxyPaneState({
|
||||
...base,
|
||||
routing: supportedRouting,
|
||||
effectiveRoutingMode: "host",
|
||||
profileSlug: "work",
|
||||
proxyStatusSnapshot: {
|
||||
serverId: "srv-remote",
|
||||
profilePartitions: { default: hostDefault },
|
||||
status: "ready",
|
||||
error: null,
|
||||
socksPort: 41234,
|
||||
},
|
||||
}),
|
||||
).toMatchObject({ kind: "connecting", effectiveRoutingMode: "host" });
|
||||
});
|
||||
|
||||
it("waits for a profile whose slug matches an Object property name", () => {
|
||||
expect(
|
||||
resolveBrowserProxyPaneState({
|
||||
...base,
|
||||
routing: supportedRouting,
|
||||
effectiveRoutingMode: "host",
|
||||
profileSlug: "constructor",
|
||||
proxyStatusSnapshot: {
|
||||
serverId: "srv-remote",
|
||||
profilePartitions: { default: hostDefault },
|
||||
status: "ready",
|
||||
error: null,
|
||||
socksPort: 41234,
|
||||
},
|
||||
}),
|
||||
).toMatchObject({ kind: "connecting", effectiveRoutingMode: "host" });
|
||||
});
|
||||
|
||||
it("mounts the host partition of the tab's profile once it is bound", () => {
|
||||
const snapshot = {
|
||||
serverId: "srv-remote",
|
||||
profilePartitions: { default: hostDefault, work: hostWork },
|
||||
status: "ready" as const,
|
||||
error: null,
|
||||
socksPort: 41234,
|
||||
};
|
||||
expect(
|
||||
resolveBrowserProxyPaneState({
|
||||
...base,
|
||||
routing: supportedRouting,
|
||||
effectiveRoutingMode: "host",
|
||||
profileSlug: "work",
|
||||
proxyStatusSnapshot: snapshot,
|
||||
}),
|
||||
).toEqual({
|
||||
kind: "ready",
|
||||
partition: hostWork,
|
||||
isRemoteHost: true,
|
||||
effectiveRoutingMode: "host",
|
||||
hostLabel: "devbox",
|
||||
proxyStatus: "ready",
|
||||
});
|
||||
expect(
|
||||
resolveBrowserProxyPaneState({
|
||||
...base,
|
||||
routing: { kind: "remote", support: "host_offline" },
|
||||
effectiveRoutingMode: "host",
|
||||
profileSlug: "work",
|
||||
proxyStatusSnapshot: snapshot,
|
||||
}),
|
||||
).toMatchObject({ kind: "ready", partition: hostWork, proxyStatus: "reconnecting" });
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useCallback, useEffect, useMemo, useState, useSyncExternalStore } from "react";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
|
||||
import { getIsElectron } from "@/constants/platform";
|
||||
import { getDesktopHost, type DesktopBrowserProxyStatus } from "@/desktop/host";
|
||||
import type { DesktopBrowserProxyStatus } from "@/desktop/host";
|
||||
import { getBrowserProfilePartition } from "@/desktop/browser/profiles";
|
||||
import { resolveBrowserRoutingMode, type BrowserRoutingMode } from "@/desktop/browser/store";
|
||||
import { useHosts } from "@/runtime/host-runtime";
|
||||
import { normalizeHostLabel } from "@/types/host-connection";
|
||||
@@ -51,29 +52,35 @@ export type BrowserProxyPaneState =
|
||||
retry: () => void;
|
||||
};
|
||||
|
||||
function hasPreparedHostPartition(
|
||||
/** The profile's host partition, once main has bound its session to the host's SOCKS5 port. */
|
||||
function readPreparedHostPartition(
|
||||
snapshot: ReturnType<typeof getCachedBrowserProxyStatus>,
|
||||
): snapshot is NonNullable<ReturnType<typeof getCachedBrowserProxyStatus>> & {
|
||||
partition: string;
|
||||
socksPort: number;
|
||||
} {
|
||||
return Boolean(snapshot?.partition && snapshot.socksPort !== null);
|
||||
profileSlug: string,
|
||||
): string | null {
|
||||
if (
|
||||
!snapshot ||
|
||||
snapshot.socksPort === null ||
|
||||
!Object.hasOwn(snapshot.profilePartitions, profileSlug)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
return snapshot.profilePartitions[profileSlug] ?? null;
|
||||
}
|
||||
|
||||
function resolveRemoteUnavailablePaneState(
|
||||
support: Exclude<Extract<HostBrowserRouting, { kind: "remote" }>["support"], "supported">,
|
||||
hostLabel: string,
|
||||
proxyStatusSnapshot: ReturnType<typeof getCachedBrowserProxyStatus>,
|
||||
preparedPartition: string | null,
|
||||
): BrowserProxyPaneState {
|
||||
// Once Electron main has verified and bound this host's fixed SOCKS5 partition,
|
||||
// keep the webview mounted across transient host disconnects/reconnects so SPA
|
||||
// state, forms, scroll, and DevTools survive. Requests still fail closed at the
|
||||
// local SOCKS5 listener while the tunnel is down.
|
||||
// Once Electron main has verified and bound this profile's session to the host's
|
||||
// fixed SOCKS5 port, keep the webview mounted across transient host
|
||||
// disconnects/reconnects so SPA state, forms, scroll, and DevTools survive.
|
||||
// Requests still fail closed at the local SOCKS5 listener while the tunnel is down.
|
||||
const isTransientDisconnect = support === "host_connecting" || support === "host_offline";
|
||||
if (isTransientDisconnect && hasPreparedHostPartition(proxyStatusSnapshot)) {
|
||||
if (isTransientDisconnect && preparedPartition) {
|
||||
return {
|
||||
kind: "ready",
|
||||
partition: proxyStatusSnapshot.partition,
|
||||
partition: preparedPartition,
|
||||
isRemoteHost: true,
|
||||
effectiveRoutingMode: "host",
|
||||
hostLabel,
|
||||
@@ -109,7 +116,7 @@ function resolvePreparedHostPaneStatus(
|
||||
export function resolveBrowserProxyPaneState(input: {
|
||||
routing: HostBrowserRouting;
|
||||
effectiveRoutingMode: BrowserRoutingMode;
|
||||
localPartition: string;
|
||||
profileSlug: string;
|
||||
hostLabel: string;
|
||||
proxyStatusSnapshot: ReturnType<typeof getCachedBrowserProxyStatus>;
|
||||
ensureError: string | null;
|
||||
@@ -118,7 +125,7 @@ export function resolveBrowserProxyPaneState(input: {
|
||||
const {
|
||||
routing,
|
||||
effectiveRoutingMode,
|
||||
localPartition,
|
||||
profileSlug,
|
||||
hostLabel,
|
||||
proxyStatusSnapshot,
|
||||
ensureError,
|
||||
@@ -128,7 +135,7 @@ export function resolveBrowserProxyPaneState(input: {
|
||||
if (routing.kind === "local" || effectiveRoutingMode === "local") {
|
||||
return {
|
||||
kind: "ready",
|
||||
partition: localPartition,
|
||||
partition: getBrowserProfilePartition(profileSlug),
|
||||
isRemoteHost: routing.kind === "remote",
|
||||
effectiveRoutingMode: "local",
|
||||
hostLabel,
|
||||
@@ -136,17 +143,18 @@ export function resolveBrowserProxyPaneState(input: {
|
||||
};
|
||||
}
|
||||
|
||||
const preparedPartition = readPreparedHostPartition(proxyStatusSnapshot, profileSlug);
|
||||
if (routing.support !== "supported") {
|
||||
return resolveRemoteUnavailablePaneState(routing.support, hostLabel, proxyStatusSnapshot);
|
||||
return resolveRemoteUnavailablePaneState(routing.support, hostLabel, preparedPartition);
|
||||
}
|
||||
|
||||
// Once the fixed-port SOCKS5 session partition is verified (socksPort !== null),
|
||||
// keep the webview mounted even if a background poll (e.g. HMR) left the cached
|
||||
// tunnel status in "error" or "reconnecting" while the host reconnects.
|
||||
if (hasPreparedHostPartition(proxyStatusSnapshot)) {
|
||||
// Once the profile's session is bound to the fixed-port SOCKS5 proxy, keep the
|
||||
// webview mounted even if a background poll (e.g. HMR) left the cached tunnel
|
||||
// status in "error" or "reconnecting" while the host reconnects.
|
||||
if (proxyStatusSnapshot && preparedPartition) {
|
||||
return {
|
||||
kind: "ready",
|
||||
partition: proxyStatusSnapshot.partition,
|
||||
partition: preparedPartition,
|
||||
isRemoteHost: true,
|
||||
effectiveRoutingMode: "host",
|
||||
hostLabel,
|
||||
@@ -179,8 +187,9 @@ export function resolveBrowserProxyPaneState(input: {
|
||||
export function useHostBrowserProxy(input: {
|
||||
serverId: string;
|
||||
routingMode?: BrowserRoutingMode;
|
||||
profileSlug: string;
|
||||
}): BrowserProxyPaneState {
|
||||
const { serverId, routingMode } = input;
|
||||
const { serverId, routingMode, profileSlug } = input;
|
||||
const hosts = useHosts();
|
||||
const host = useMemo(
|
||||
() => hosts.find((entry) => entry.serverId === serverId) ?? null,
|
||||
@@ -200,6 +209,9 @@ export function useHostBrowserProxy(input: {
|
||||
);
|
||||
|
||||
const [retryCounter, setRetryCounter] = useState(0);
|
||||
// A retry replaces the host tunnel once. Later runs (another profile on the same host)
|
||||
// reuse the tunnel that other tabs on this host share.
|
||||
const reconnectedRetryRef = useRef(0);
|
||||
const [ensureError, setEnsureError] = useState<string | null>(null);
|
||||
|
||||
const effectiveRoutingMode = resolveBrowserRoutingMode(
|
||||
@@ -225,10 +237,13 @@ export function useHostBrowserProxy(input: {
|
||||
installBrowserProxyRendererBridge();
|
||||
setEnsureError(null);
|
||||
|
||||
const forceReconnect = retryCounter > reconnectedRetryRef.current;
|
||||
reconnectedRetryRef.current = retryCounter;
|
||||
void ensureHostBrowserProxy({
|
||||
serverId,
|
||||
target: supportedTarget,
|
||||
forceReconnect: retryCounter > 0,
|
||||
profileSlug,
|
||||
forceReconnect,
|
||||
})
|
||||
.then((snapshot) => {
|
||||
if (cancelled) return undefined;
|
||||
@@ -249,13 +264,12 @@ export function useHostBrowserProxy(input: {
|
||||
};
|
||||
// targetKey serializes supportedTarget deterministically.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [effectiveRoutingMode, retryCounter, serverId, targetKey]);
|
||||
}, [effectiveRoutingMode, profileSlug, retryCounter, serverId, targetKey]);
|
||||
|
||||
const localPartition = getDesktopHost()?.browser?.profilePartition ?? "persist:paseo-browser";
|
||||
return resolveBrowserProxyPaneState({
|
||||
routing,
|
||||
effectiveRoutingMode,
|
||||
localPartition,
|
||||
profileSlug,
|
||||
hostLabel,
|
||||
proxyStatusSnapshot,
|
||||
ensureError,
|
||||
|
||||
@@ -177,7 +177,8 @@ export type DesktopBrowserProxyStatus = "idle" | "connecting" | "ready" | "recon
|
||||
|
||||
export interface DesktopBrowserProxyStatusSnapshot {
|
||||
serverId: string;
|
||||
partition: string;
|
||||
/** Profile slug -> partition, for every profile session bound to this host's proxy. */
|
||||
profilePartitions: Record<string, string>;
|
||||
status: DesktopBrowserProxyStatus;
|
||||
error: string | null;
|
||||
socksPort: number | null;
|
||||
@@ -218,6 +219,7 @@ export interface DesktopBrowserBridge {
|
||||
ensureHostProxy?: (input: {
|
||||
serverId: string;
|
||||
target: HostTransportSpec;
|
||||
profileSlug?: string;
|
||||
forceReconnect?: boolean;
|
||||
}) => Promise<DesktopBrowserProxyStatusSnapshot>;
|
||||
updateHostProxyTarget?: (input: { serverId: string; target: HostTransportSpec }) => Promise<void>;
|
||||
|
||||
@@ -4,7 +4,11 @@ import { File } from "expo-file-system";
|
||||
import { getDesktopHost, isElectronRuntime } from "@/desktop/host";
|
||||
import { isWeb } from "@/constants/platform";
|
||||
import { getMimeTypeFromPath } from "@/attachments/file-types";
|
||||
import { readDesktopFileBytes, type SelectedFile } from "@/attachments/selected-file";
|
||||
import {
|
||||
readDesktopFileBytes,
|
||||
selectedFileFromWebFile,
|
||||
type SelectedFile,
|
||||
} from "@/attachments/selected-file";
|
||||
|
||||
async function pickFilesWithDesktopDialog(): Promise<SelectedFile[] | null> {
|
||||
const dialog = getDesktopHost()?.dialog;
|
||||
@@ -52,15 +56,7 @@ function pickFilesWithWebInput(): Promise<SelectedFile[] | null> {
|
||||
return;
|
||||
}
|
||||
|
||||
const result: SelectedFile[] = [];
|
||||
for (const file of files) {
|
||||
result.push({
|
||||
fileName: file.name,
|
||||
mimeType: file.type || getMimeTypeFromPath(file.name),
|
||||
readBytes: async () => new Uint8Array(await file.arrayBuffer()),
|
||||
});
|
||||
}
|
||||
resolve(result);
|
||||
resolve(files.map(selectedFileFromWebFile));
|
||||
});
|
||||
|
||||
input.addEventListener("cancel", () => {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useHostFeatureMap } from "@/runtime/host-features";
|
||||
import { useHostFeatureAvailabilityMap } from "@/runtime/host-features";
|
||||
import { useCallback, useEffect, useMemo } from "react";
|
||||
import { useStoreWithEqualityFn } from "zustand/traditional";
|
||||
import { useCreateFlowStore } from "@/stores/create-flow-store";
|
||||
@@ -142,8 +142,9 @@ export function useSidebarWorkspacesList(options?: {
|
||||
|
||||
const workspaceSort = useSidebarViewStore((state) => state.workspaceSort);
|
||||
const groupMode = useSidebarViewStore((state) => state.groupMode);
|
||||
const sortSupport = useHostFeatureMap(directoryServerIds, "workspaceSortTimes");
|
||||
const workspaceSortSupported = [...sortSupport.values()].every(Boolean);
|
||||
const sortSupport = useHostFeatureAvailabilityMap(directoryServerIds, "workspaceSortTimes");
|
||||
// Cached workspaces are visible before their host sends server info.
|
||||
const workspaceSortSupported = ![...sortSupport.values()].includes(false);
|
||||
const sort =
|
||||
groupMode === "project" && (workspaceSort === "manual" || workspaceSortSupported)
|
||||
? workspaceSort
|
||||
|
||||
@@ -3,8 +3,13 @@ import appPackage from "../../package.json";
|
||||
import { afterEach, expect, it } from "vitest";
|
||||
import { QueryObserver } from "@tanstack/react-query";
|
||||
import { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
import type { SessionOutboundMessage } from "@getpaseo/protocol/messages";
|
||||
import type {
|
||||
GetProvidersSnapshotResponseMessage,
|
||||
SessionOutboundMessage,
|
||||
} from "@getpaseo/protocol/messages";
|
||||
import { compactProviderSnapshot } from "@getpaseo/protocol/provider-snapshot-codec";
|
||||
import { settingsRpc } from "@getpaseo/plugin";
|
||||
import { providerSnapshotIcons, replaceProviderSnapshotIcons } from "@/data/provider-icons";
|
||||
import { syncPluginCatalog } from "./catalog-sync-model";
|
||||
import { createPluginHosts } from "./hosts";
|
||||
import { openPluginNotification } from "./notification-open";
|
||||
@@ -569,3 +574,90 @@ it("keeps catalog loading before server_info arrives so cold-launch plugin taps
|
||||
expect(h.registry.getCatalogStatus("host")).toBe("ready");
|
||||
expect(openedRoutes).toEqual(["/h/host/plugin/ci-alerts/surface/alert?param.buildId=77"]);
|
||||
});
|
||||
|
||||
function providerSnapshotPayload(
|
||||
provider: string,
|
||||
iconSvg: string,
|
||||
snapshotHash: string,
|
||||
): GetProvidersSnapshotResponseMessage["payload"] {
|
||||
const entries = [
|
||||
{
|
||||
provider,
|
||||
label: provider,
|
||||
iconSvg,
|
||||
enabled: true,
|
||||
available: true,
|
||||
status: "ready" as const,
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
},
|
||||
];
|
||||
const compactSnapshot = compactProviderSnapshot(entries);
|
||||
return {
|
||||
requestId: "snapshot-req",
|
||||
snapshotHash,
|
||||
generatedAt: "2026-01-01T00:00:00.000Z",
|
||||
entries,
|
||||
compactSnapshot,
|
||||
};
|
||||
}
|
||||
|
||||
it("hydrates provider snapshot icons before installing plugins and refreshes them on catalog changes", async () => {
|
||||
replaceProviderSnapshotIcons("host", []);
|
||||
const events: string[] = [];
|
||||
const firstSvg = '<svg viewBox="0 0 24 24"><path d="M2 2h20v20H2z" /></svg>';
|
||||
const secondSvg = '<svg viewBox="0 0 24 24"><path d="M6 6h12v12H6z" /></svg>';
|
||||
let current = { svg: firstSvg, hash: "hash-1" };
|
||||
|
||||
class SnapshotCatalogClient extends CatalogClient {
|
||||
override async getProvidersSnapshot() {
|
||||
events.push(`snapshot:${current.hash}`);
|
||||
return providerSnapshotPayload("direct-example", current.svg, current.hash);
|
||||
}
|
||||
|
||||
override async getPluginCatalog() {
|
||||
events.push(
|
||||
`catalog:${providerSnapshotIcons.getState().get("host")?.get("direct-example") ?? "missing"}`,
|
||||
);
|
||||
return super.getPluginCatalog();
|
||||
}
|
||||
}
|
||||
|
||||
const h = harness();
|
||||
const client = new SnapshotCatalogClient();
|
||||
h.sync({ client, supportsProviderSnapshots: true });
|
||||
|
||||
await expect.poll(() => h.registry.getCatalogStatus("host")).toBe("ready");
|
||||
expect(events).toEqual(["snapshot:hash-1", `catalog:${firstSvg}`]);
|
||||
expect(providerSnapshotIcons.getState().get("host")?.get("direct-example")).toBe(firstSvg);
|
||||
|
||||
current = { svg: secondSvg, hash: "hash-2" };
|
||||
client.update({
|
||||
type: "status",
|
||||
payload: { status: "plugin_catalog_changed", pluginId: "direct-example" },
|
||||
});
|
||||
|
||||
await expect
|
||||
.poll(() => providerSnapshotIcons.getState().get("host")?.get("direct-example"))
|
||||
.toBe(secondSvg);
|
||||
expect(events).toEqual([
|
||||
"snapshot:hash-1",
|
||||
`catalog:${firstSvg}`,
|
||||
"snapshot:hash-2",
|
||||
`catalog:${secondSvg}`,
|
||||
]);
|
||||
});
|
||||
|
||||
it("still installs the plugin catalog when provider icon hydration fails", async () => {
|
||||
replaceProviderSnapshotIcons("host", []);
|
||||
class FailingSnapshotClient extends CatalogClient {
|
||||
override async getProvidersSnapshot(): Promise<GetProvidersSnapshotResponseMessage["payload"]> {
|
||||
throw new Error("Snapshot unavailable");
|
||||
}
|
||||
}
|
||||
|
||||
const h = harness();
|
||||
h.sync({ client: new FailingSnapshotClient(), supportsProviderSnapshots: true });
|
||||
|
||||
await expect.poll(() => h.registry.getCatalogStatus("host")).toBe("ready");
|
||||
expect(h.installed().id).toBe("reports");
|
||||
});
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { CancelledError } from "@tanstack/react-query";
|
||||
import type { AudioEngine } from "@/audio";
|
||||
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
import { fetchProvidersSnapshot } from "@/data/providers-snapshot";
|
||||
import type { PluginRegistry } from "./registry";
|
||||
import { pluginSettingsKey, pluginSettingsPrefix } from "./settings/query";
|
||||
|
||||
@@ -10,6 +12,7 @@ interface CatalogSyncInput {
|
||||
connected: boolean;
|
||||
/** `null` while `server_info` has not yet arrived for this host. */
|
||||
supported: boolean | null;
|
||||
supportsProviderSnapshots?: boolean;
|
||||
registry: Pick<
|
||||
PluginRegistry,
|
||||
"installCatalog" | "getSnapshot" | "removeHost" | "setCatalogStatus"
|
||||
@@ -23,6 +26,7 @@ export function syncPluginCatalog({
|
||||
audio,
|
||||
connected,
|
||||
supported,
|
||||
supportsProviderSnapshots = false,
|
||||
registry,
|
||||
onCatalogChanged,
|
||||
}: CatalogSyncInput): () => void {
|
||||
@@ -41,27 +45,42 @@ export function syncPluginCatalog({
|
||||
registry.setCatalogStatus(serverId, "loading");
|
||||
const installationOptions = { client, audio };
|
||||
let cancelled = false;
|
||||
const abortController = new AbortController();
|
||||
let refreshQueue = Promise.resolve();
|
||||
async function prepareProviderIcons() {
|
||||
if (!supportsProviderSnapshots) return;
|
||||
try {
|
||||
await fetchProvidersSnapshot({
|
||||
client,
|
||||
serverId,
|
||||
cwd: null,
|
||||
signal: abortController.signal,
|
||||
});
|
||||
} catch (error) {
|
||||
if (!cancelled && !(error instanceof CancelledError)) {
|
||||
console.warn(`[Plugins] Failed to load provider icons for ${serverId}`, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
function refresh(replacePluginId?: string) {
|
||||
refreshQueue = refreshQueue.then(() => {
|
||||
refreshQueue = refreshQueue.then(async () => {
|
||||
if (cancelled) return undefined;
|
||||
registry.setCatalogStatus(serverId, "loading");
|
||||
return client
|
||||
.getPluginCatalog()
|
||||
.then((catalog) => {
|
||||
if (!cancelled) {
|
||||
registry.installCatalog(serverId, catalog, { ...installationOptions, replacePluginId });
|
||||
registry.setCatalogStatus(serverId, "ready");
|
||||
}
|
||||
return undefined;
|
||||
})
|
||||
.catch((error) => {
|
||||
if (!cancelled) {
|
||||
registry.setCatalogStatus(serverId, "error");
|
||||
console.warn(`[Plugins] Failed to load catalog for ${serverId}`, error);
|
||||
}
|
||||
return undefined;
|
||||
});
|
||||
await prepareProviderIcons();
|
||||
if (cancelled) return undefined;
|
||||
try {
|
||||
const catalog = await client.getPluginCatalog();
|
||||
if (!cancelled) {
|
||||
registry.installCatalog(serverId, catalog, { ...installationOptions, replacePluginId });
|
||||
registry.setCatalogStatus(serverId, "ready");
|
||||
}
|
||||
} catch (error) {
|
||||
if (!cancelled) {
|
||||
registry.setCatalogStatus(serverId, "error");
|
||||
console.warn(`[Plugins] Failed to load catalog for ${serverId}`, error);
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
});
|
||||
return refreshQueue;
|
||||
}
|
||||
@@ -104,6 +123,7 @@ export function syncPluginCatalog({
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
abortController.abort();
|
||||
void observation
|
||||
.release()
|
||||
.catch((error) => console.warn("[Plugins] Failed to release catalog", error));
|
||||
|
||||
@@ -2,7 +2,7 @@ import { useVoiceAudioEngineOptional } from "@/contexts/voice-context";
|
||||
import { useEffect } from "react";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
import { useHostFeatureAvailability } from "@/runtime/host-features";
|
||||
import { useHostFeature, useHostFeatureAvailability } from "@/runtime/host-features";
|
||||
import { useHostRuntimeIsConnected } from "@/runtime/host-runtime";
|
||||
import { pluginListQueryKey } from "./plugin-list";
|
||||
import { pluginRegistry } from "./registry";
|
||||
@@ -18,6 +18,7 @@ export function PluginCatalogSync({
|
||||
const audio = useVoiceAudioEngineOptional();
|
||||
const connected = useHostRuntimeIsConnected(serverId);
|
||||
const supported = useHostFeatureAvailability(serverId, "plugins");
|
||||
const supportsProviderSnapshots = useHostFeature(serverId, "providersSnapshot");
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
useEffect(
|
||||
@@ -28,12 +29,13 @@ export function PluginCatalogSync({
|
||||
audio,
|
||||
connected,
|
||||
supported,
|
||||
supportsProviderSnapshots,
|
||||
registry: pluginRegistry,
|
||||
onCatalogChanged: () => {
|
||||
void queryClient.invalidateQueries({ queryKey: pluginListQueryKey(serverId) });
|
||||
},
|
||||
}),
|
||||
[audio, client, connected, queryClient, serverId, supported],
|
||||
[audio, client, connected, queryClient, serverId, supported, supportsProviderSnapshots],
|
||||
);
|
||||
|
||||
useEffect(() => () => pluginRegistry.removeHost(serverId), [serverId]);
|
||||
|
||||
@@ -798,10 +798,10 @@ describe("evaluatePluginClientBundle", () => {
|
||||
const plugin = evaluatePluginClientBundle(
|
||||
"example",
|
||||
`(function(require) {
|
||||
const { Icon, Modal, useToast, SettingsSection, SidebarRow, StreamedText } = require("@getpaseo/plugin/client/ui");
|
||||
const { Icon, ProviderIcon, Modal, useToast, SettingsSection, SidebarRow, StreamedText } = require("@getpaseo/plugin/client/ui");
|
||||
const module = { exports: {} };
|
||||
module.exports.default = function(plugin) {
|
||||
if (typeof Icon !== "function" || typeof Modal !== "function" || typeof Modal.Content !== "function" || typeof useToast !== "function" || typeof SettingsSection !== "function" || typeof SidebarRow !== "function" || typeof StreamedText !== "function") {
|
||||
if (typeof Icon !== "function" || typeof ProviderIcon !== "function" || typeof Modal !== "function" || typeof Modal.Content !== "function" || typeof useToast !== "function" || typeof SettingsSection !== "function" || typeof SidebarRow !== "function" || typeof StreamedText !== "function") {
|
||||
throw new Error("React Native plugin UI is incomplete");
|
||||
}
|
||||
plugin.addSurface("main", function Surface() { return null; });
|
||||
|
||||
@@ -1,14 +1,77 @@
|
||||
import { Settings } from "lucide-react-native";
|
||||
import React, { isValidElement, type ReactElement, type ReactNode } from "react";
|
||||
import { SvgXml } from "react-native-svg";
|
||||
import { describe, expect, it } from "vitest";
|
||||
// @vitest-environment jsdom
|
||||
import { createPaseoApi } from "@getpaseo/client";
|
||||
import { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
import type { PluginIconProps } from "@getpaseo/plugin";
|
||||
import { Icon, parsePluginIcon, parseSerializablePluginIcon, PluginIconView } from "./icons";
|
||||
import { PluginTranslationRuntime } from "@getpaseo/plugin/client/host";
|
||||
import { QueryClient } from "@tanstack/react-query";
|
||||
import { act, cleanup, renderHook } from "@testing-library/react";
|
||||
import { Bot, Settings } from "lucide-react-native";
|
||||
import React, { isValidElement, type ReactElement, type ReactNode } from "react";
|
||||
import Svg, { SvgXml } from "react-native-svg";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { replaceProviderSnapshotIcons } from "@/data/provider-icons";
|
||||
import { runPluginClientBundle, type PluginClientRuntime } from "./evaluate";
|
||||
import {
|
||||
Icon,
|
||||
parsePluginIcon,
|
||||
parseSerializablePluginIcon,
|
||||
PluginIconView,
|
||||
ProviderIcon,
|
||||
} from "./icons";
|
||||
import { PluginInstallationProvider } from "./installation-provider";
|
||||
import type { InstalledPlugin } from "./types";
|
||||
|
||||
const SVG = '<svg viewBox="0 0 24 24"><path fill="currentColor" d="M4 4h16v16H4z" /></svg>';
|
||||
const SVG_ICON = { svg: SVG };
|
||||
|
||||
const GLYPHS = new Set<unknown>([Settings, SvgXml]);
|
||||
const GLYPHS = new Set<unknown>([Settings, Bot, Svg, SvgXml]);
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
replaceProviderSnapshotIcons("host-a", []);
|
||||
replaceProviderSnapshotIcons("host-b", []);
|
||||
});
|
||||
|
||||
function makePlugin(serverId: string): InstalledPlugin {
|
||||
return {
|
||||
id: "icons-test",
|
||||
serverId,
|
||||
clientBundle: "",
|
||||
lifetime: new AbortController(),
|
||||
locale: "en",
|
||||
i18n: new PluginTranslationRuntime({ getLocale: () => "en", subscribe: () => () => {} }),
|
||||
paseo: createPaseoApi(
|
||||
new DaemonClient({
|
||||
url: "ws://127.0.0.1:1",
|
||||
clientId: "icons-test",
|
||||
reconnect: { enabled: false },
|
||||
}),
|
||||
),
|
||||
invoke: async () => undefined,
|
||||
subscribe: () => {
|
||||
throw new Error("Subscriptions are not used here");
|
||||
},
|
||||
queryClient: new QueryClient(),
|
||||
cleanup: () => undefined,
|
||||
settingsScreens: [],
|
||||
surfaces: [],
|
||||
sidebarViews: [],
|
||||
sidebarItems: { header: [], footer: [] },
|
||||
legacySidebarItems: [],
|
||||
workspaceRowBadgeItems: [],
|
||||
filePanels: [],
|
||||
composerItems: [],
|
||||
newWorkspaceItems: [],
|
||||
workspacePanels: [],
|
||||
commandCenterItems: [],
|
||||
clientSlashCommands: [],
|
||||
attachmentSources: [],
|
||||
themes: [],
|
||||
timelineTransformers: [],
|
||||
timelineRenderers: [],
|
||||
notificationOpenHandlers: [],
|
||||
};
|
||||
}
|
||||
|
||||
/** Expands function components down to what reaches the screen: a Lucide glyph, SvgXml, or DOM. */
|
||||
function draw(node: ReactNode): ReactElement | null {
|
||||
@@ -102,3 +165,100 @@ describe("Icon", () => {
|
||||
expect(Icon({ icon: { svg: '<svg onload="run()"></svg>' } })).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("ProviderIcon", () => {
|
||||
function hostWrapper(serverId: string) {
|
||||
const plugin = makePlugin(serverId);
|
||||
return function Wrapper({ children }: { children: ReactNode }) {
|
||||
return <PluginInstallationProvider plugin={plugin}>{children}</PluginInstallationProvider>;
|
||||
};
|
||||
}
|
||||
|
||||
it("renders built-in, catalog, host-scoped daemon plugin SVGs, reactive updates, and fallback icons", () => {
|
||||
const evaluated = runPluginClientBundle(
|
||||
{ serverId: "host-a", pluginId: "icons-test" },
|
||||
`(function(require) {
|
||||
const { ProviderIcon } = require("@getpaseo/plugin/client/ui");
|
||||
return {
|
||||
default: function(plugin) {
|
||||
plugin.addSurface("main", function() { return null; });
|
||||
plugin.__ProviderIcon = ProviderIcon;
|
||||
return function() {};
|
||||
},
|
||||
};
|
||||
})`,
|
||||
{} as PluginClientRuntime,
|
||||
);
|
||||
expect(evaluated.surfaces.map((s) => s.id)).toEqual(["main"]);
|
||||
|
||||
const hostASvg = '<svg viewBox="0 0 24 24"><path d="M4 4h16v16H4z" /></svg>';
|
||||
const hostBSvg = '<svg viewBox="0 0 24 24"><path d="M12 2L2 22h20z" /></svg>';
|
||||
replaceProviderSnapshotIcons("host-a", [{ provider: "direct-example", iconSvg: hostASvg }]);
|
||||
replaceProviderSnapshotIcons("host-b", [{ provider: "direct-example", iconSvg: hostBSvg }]);
|
||||
|
||||
const wrapper = hostWrapper("host-a");
|
||||
|
||||
// Built-in provider resolves without hostId
|
||||
const builtin = renderHook(
|
||||
() => ProviderIcon({ provider: "codex", size: 18, color: "#123456" }),
|
||||
{ wrapper },
|
||||
);
|
||||
expect(draw(builtin.result.current)).toMatchObject({
|
||||
type: Svg,
|
||||
props: { width: 18, height: 18, fill: "#123456" },
|
||||
});
|
||||
|
||||
// Catalog provider resolves with defaults
|
||||
const catalog = renderHook(() => ProviderIcon({ provider: "devin" }), { wrapper });
|
||||
expect(draw(catalog.result.current)).toMatchObject({
|
||||
type: SvgXml,
|
||||
props: { width: 24, height: 24, color: "currentColor" },
|
||||
});
|
||||
|
||||
// Daemon-registered plugin provider defaults to enclosing installation host and reacts to updates
|
||||
const implicitHost = renderHook(
|
||||
() => ProviderIcon({ provider: "direct-example", size: 20, color: "#abcdef" }),
|
||||
{ wrapper },
|
||||
);
|
||||
expect(draw(implicitHost.result.current)).toMatchObject({
|
||||
type: SvgXml,
|
||||
props: { xml: hostASvg, width: 20, height: 20, color: "#abcdef" },
|
||||
});
|
||||
|
||||
const updatedSvg = '<svg viewBox="0 0 24 24"><path d="M1 1h22v22H1z" /></svg>';
|
||||
act(() => {
|
||||
replaceProviderSnapshotIcons("host-a", [{ provider: "direct-example", iconSvg: updatedSvg }]);
|
||||
});
|
||||
expect(draw(implicitHost.result.current)).toMatchObject({
|
||||
type: SvgXml,
|
||||
props: { xml: updatedSvg, width: 20, height: 20, color: "#abcdef" },
|
||||
});
|
||||
|
||||
// Explicit hostId targets the named host without leaking across hosts
|
||||
const explicitHost = renderHook(
|
||||
() =>
|
||||
ProviderIcon({ provider: "direct-example", hostId: "host-b", size: 16, color: "#654321" }),
|
||||
{ wrapper },
|
||||
);
|
||||
expect(draw(explicitHost.result.current)).toMatchObject({
|
||||
type: SvgXml,
|
||||
props: { xml: hostBSvg, width: 16, height: 16, color: "#654321" },
|
||||
});
|
||||
|
||||
// Unknown provider falls back to Bot
|
||||
const fallback = renderHook(
|
||||
() =>
|
||||
ProviderIcon({
|
||||
provider: "unknown-provider",
|
||||
hostId: "host-a",
|
||||
size: 18,
|
||||
color: "#111111",
|
||||
}),
|
||||
{ wrapper },
|
||||
);
|
||||
expect(draw(fallback.result.current)).toMatchObject({
|
||||
type: Bot,
|
||||
props: { size: 18, color: "#111111" },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -8,8 +8,9 @@ import {
|
||||
type PluginSvgIcon,
|
||||
} from "@getpaseo/plugin";
|
||||
import type { PluginIcon } from "@getpaseo/plugin/client";
|
||||
import type { IconProps } from "@getpaseo/plugin/client/ui";
|
||||
import { SvgIcon } from "@/components/provider-icons";
|
||||
import type { IconProps, PluginProviderIconProps } from "@getpaseo/plugin/client/ui";
|
||||
import { SvgIcon, useProviderIcon } from "@/components/provider-icons";
|
||||
import { usePluginInstallationServerId } from "./installation-provider";
|
||||
|
||||
/** Host surfaces may thin a Lucide stroke; SVG and plugin components ignore it. */
|
||||
type HostIconProps = PluginIconProps & { strokeWidth?: number };
|
||||
@@ -153,3 +154,15 @@ export function Icon(props: IconProps): ReactElement | null {
|
||||
const color = props.color ?? "currentColor";
|
||||
return createElement(PluginIconView, { icon, size, color });
|
||||
}
|
||||
|
||||
/** The kit `ProviderIcon`. Resolves built-in, catalog, or host-scoped plugin provider icons. */
|
||||
export function ProviderIcon({
|
||||
provider,
|
||||
hostId,
|
||||
size = 24,
|
||||
color = "currentColor",
|
||||
}: PluginProviderIconProps): ReactElement {
|
||||
const installationServerId = usePluginInstallationServerId();
|
||||
const icon = useProviderIcon(provider, hostId ?? installationServerId);
|
||||
return createElement(icon, { size, color });
|
||||
}
|
||||
|
||||
@@ -20,7 +20,7 @@ export { FilePanelLoading as Loading } from "@/file-panels/loading";
|
||||
// COMPAT(pluginSettingsGroup): added in v0.13.0, remove after 2027-04-20
|
||||
export { SettingsGroup } from "@/components/settings";
|
||||
|
||||
export { Icon } from "../icons";
|
||||
export { Icon, ProviderIcon } from "../icons";
|
||||
export { Action, Combobox, Select, Toggle } from "./composer-controls";
|
||||
export { Modal } from "./modal";
|
||||
export { ScrollView, FlatList } from "./scroll-view";
|
||||
|
||||
@@ -151,6 +151,17 @@ describe("createWorkspaceAgentInBackground", () => {
|
||||
|
||||
expect(draftText()).toBe("a different idea");
|
||||
});
|
||||
it("keeps text typed while workspace creation was pending that has not been published yet", () => {
|
||||
const clearConsumedDraft = captureCleanup();
|
||||
useDraftStore.getState().stageDraftText({ draftKey: DRAFT_KEY, text: "Keep this newer draft" });
|
||||
|
||||
// Creation completes before the staged text is published after the next paint.
|
||||
clearConsumedDraft();
|
||||
useDraftStore.getState().flushDraftText(DRAFT_KEY);
|
||||
|
||||
expect(draftText()).toBe("Keep this newer draft");
|
||||
});
|
||||
|
||||
it("keeps a newer draft written while workspace creation was pending", async () => {
|
||||
useWorkspaceAttachmentsStore.getState().addWorkspaceAttachment({
|
||||
scopeKey: SCOPE_KEY,
|
||||
|
||||
@@ -40,6 +40,8 @@ export function captureWorkspaceDraftCleanup(input: WorkspaceDraftCleanupInput):
|
||||
const attachments = useWorkspaceAttachmentsStore.getState().attachmentsByScope[scopeKey];
|
||||
|
||||
return () => {
|
||||
// Text typed into a newer draft is published after the next paint; it is newer state too.
|
||||
useDraftStore.getState().flushDraftText(input.draftKey);
|
||||
// These stores update independently. A context-only edit does not bump the text version.
|
||||
// Any newer draft state owns the whole draft, including its unchanged context.
|
||||
if (
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/cli",
|
||||
"version": "0.18.2",
|
||||
"version": "0.19.0-beta.1",
|
||||
"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.2",
|
||||
"@getpaseo/protocol": "0.18.2",
|
||||
"@getpaseo/server": "0.18.2",
|
||||
"@getpaseo/client": "0.19.0-beta.1",
|
||||
"@getpaseo/protocol": "0.19.0-beta.1",
|
||||
"@getpaseo/server": "0.19.0-beta.1",
|
||||
"chalk": "^5.3.0",
|
||||
"commander": "^12.0.0",
|
||||
"mime-types": "^2.1.35",
|
||||
|
||||
@@ -81,6 +81,11 @@ describe("buildAgentLsFetchOptions", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves empty values and punctuation in repeated label filters", () => {
|
||||
const options = buildAgentLsFetchOptions({ label: ["tag=v=1,rc", "empty="] });
|
||||
expect(options.filter?.labels).toEqual({ tag: "v=1,rc", empty: "" });
|
||||
});
|
||||
|
||||
it("asks the daemon for internal agents only with --internal", () => {
|
||||
expect(buildAgentLsFetchOptions({ background: true, global: true })).toEqual({
|
||||
filter: { includeBackground: true },
|
||||
@@ -126,6 +131,17 @@ describe("buildAgentLsFetchOptions", () => {
|
||||
});
|
||||
|
||||
describe("runLsCommand", () => {
|
||||
it.each(["team", "=blue", " =blue"])(
|
||||
"rejects the whole listing when a label filter is malformed (%j)",
|
||||
async (label) => {
|
||||
await expect(
|
||||
listAgents({ daemonTarget, label: ["bot=worker", label] }, async () =>
|
||||
createPagingClient(),
|
||||
),
|
||||
).rejects.toMatchObject({ code: "INVALID_LABEL", message: `Invalid label format: ${label}` });
|
||||
},
|
||||
);
|
||||
|
||||
it("includes agent snapshot metadata in JSON listings", async () => {
|
||||
const result = await listAgents({ daemonTarget, global: true }, async () =>
|
||||
createPagingClient(),
|
||||
|
||||
@@ -141,16 +141,20 @@ export interface AgentLsOptions extends CommandOptions {
|
||||
}
|
||||
|
||||
function parseLabelFilters(labels: string[] | undefined): Record<string, string> {
|
||||
const labelFilters: Record<string, string> = {};
|
||||
for (const labelStr of labels ?? []) {
|
||||
const eqIndex = labelStr.indexOf("=");
|
||||
if (eqIndex !== -1) {
|
||||
const key = labelStr.slice(0, eqIndex);
|
||||
const value = labelStr.slice(eqIndex + 1);
|
||||
labelFilters[key] = value;
|
||||
}
|
||||
}
|
||||
return labelFilters;
|
||||
return Object.fromEntries(
|
||||
(labels ?? []).map((label) => {
|
||||
const separator = label.indexOf("=");
|
||||
const key = label.slice(0, separator);
|
||||
if (separator === -1 || !key.trim()) {
|
||||
throw {
|
||||
code: "INVALID_LABEL",
|
||||
message: `Invalid label format: ${label}`,
|
||||
details: "Labels must include a non-empty key in key=value format",
|
||||
} satisfies CommandError;
|
||||
}
|
||||
return [key, label.slice(separator + 1)];
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export function buildAgentLsFetchOptions(
|
||||
@@ -211,6 +215,7 @@ export async function listAgents(
|
||||
options: Parameters<typeof connectToDaemon>[0],
|
||||
) => Promise<AgentLsClient> = connectToDaemon,
|
||||
): Promise<AgentLsResult> {
|
||||
const fetchOptions = buildAgentLsFetchOptions(options);
|
||||
const client = await connect({ target: options.daemonTarget });
|
||||
|
||||
try {
|
||||
@@ -223,8 +228,6 @@ export async function listAgents(
|
||||
throw error;
|
||||
}
|
||||
|
||||
const labelFilters = parseLabelFilters(options.label);
|
||||
const fetchOptions = buildAgentLsFetchOptions(options);
|
||||
let agents = await fetchAllAgents(client, fetchOptions);
|
||||
|
||||
// By default, exclude archived agents. `-a` includes them.
|
||||
@@ -243,7 +246,8 @@ export async function listAgents(
|
||||
}
|
||||
|
||||
// Apply label filtering only when explicitly requested.
|
||||
if (Object.keys(labelFilters).length > 0) {
|
||||
const labelFilters = fetchOptions.filter?.labels;
|
||||
if (labelFilters) {
|
||||
agents = agents.filter((a) => {
|
||||
const agentLabels = a.labels;
|
||||
for (const [key, value] of Object.entries(labelFilters)) {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/client",
|
||||
"version": "0.18.2",
|
||||
"version": "0.19.0-beta.1",
|
||||
"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.2",
|
||||
"@getpaseo/relay": "0.18.2",
|
||||
"@getpaseo/protocol": "0.19.0-beta.1",
|
||||
"@getpaseo/relay": "0.19.0-beta.1",
|
||||
"ws": "^8.20.0",
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
|
||||
@@ -587,6 +587,236 @@ function describeProcess(pid) {
|
||||
return { pid, serverId: serverId ?? null, command };
|
||||
}
|
||||
|
||||
async function evaluateMainProcess(inspectorPort, expression) {
|
||||
const [target] = await (await fetch(`http://127.0.0.1:${inspectorPort}/json/list`)).json();
|
||||
const socket = new WebSocket(target.webSocketDebuggerUrl);
|
||||
try {
|
||||
return await new Promise((resolve, reject) => {
|
||||
socket.once("error", reject);
|
||||
socket.on("message", (data) => {
|
||||
const response = JSON.parse(String(data));
|
||||
if (response.id !== 1) return;
|
||||
if (response.error || response.result?.exceptionDetails) reject(new Error(String(data)));
|
||||
else resolve(response.result.result.value);
|
||||
});
|
||||
socket.once("open", () =>
|
||||
socket.send(
|
||||
JSON.stringify({
|
||||
id: 1,
|
||||
method: "Runtime.evaluate",
|
||||
params: {
|
||||
expression: `(async () => { const electron = process.mainModule.require('electron'); ${expression} })()`,
|
||||
returnByValue: true,
|
||||
awaitPromise: true,
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
} finally {
|
||||
socket.close();
|
||||
}
|
||||
}
|
||||
|
||||
/** Accepts the next native confirm dialog by clicking the button labeled `label`. */
|
||||
async function acceptNextDialog(inspect, label) {
|
||||
await inspect(`const { dialog } = electron; const show = dialog.showMessageBox;
|
||||
dialog.showMessageBox = async (owner, options) => {
|
||||
dialog.showMessageBox = show;
|
||||
return { response: options.buttons.indexOf(${JSON.stringify(label)}), checkboxChecked: false };
|
||||
}; return true;`);
|
||||
}
|
||||
|
||||
async function openBrowserProfileSettings(page) {
|
||||
await page.getByRole("button", { name: "Settings", exact: true }).click();
|
||||
await page
|
||||
.locator('[data-testid="settings-sidebar"]:visible')
|
||||
.getByRole("button", { name: "Chat & panes", exact: true })
|
||||
.click();
|
||||
await expect(page.getByTestId("settings-browser-profile-row-default")).toBeVisible();
|
||||
}
|
||||
|
||||
/**
|
||||
* On a host-proxied tab, creates and switches profiles, and proves each profile on the
|
||||
* host has its own storage while its requests still leave through the host daemon over
|
||||
* the host's one tunnel. Then clears and removes the profile from Settings.
|
||||
*/
|
||||
async function verifyHostProxiedProfiles({
|
||||
page,
|
||||
inspect,
|
||||
relayBridge,
|
||||
targetServer,
|
||||
targetUrl,
|
||||
hostPartition,
|
||||
routingPill,
|
||||
userData,
|
||||
}) {
|
||||
const picker = () => page.locator('[data-testid="browser-profile-picker"]:visible');
|
||||
const hostWorkPartition = `${hostPartition}-profile-work`;
|
||||
const guestAt = (partition) => readGuestState(page, { exactPartition: partition });
|
||||
const runInGuest = (partition, code) =>
|
||||
page.evaluate(
|
||||
async (input) => {
|
||||
const wv = [...document.querySelectorAll("webview")].find(
|
||||
(el) => el.getAttribute("partition") === input.partition,
|
||||
);
|
||||
return await wv.executeJavaScript(input.code);
|
||||
},
|
||||
{ partition, code },
|
||||
);
|
||||
const markGuest = (partition, marker) =>
|
||||
runInGuest(
|
||||
partition,
|
||||
`localStorage.setItem("partition_marker", ${JSON.stringify(marker)}); document.cookie = "profile=${marker}; Path=/; Max-Age=86400";`,
|
||||
);
|
||||
const cookieAt = (partition) => runInGuest(partition, "document.cookie");
|
||||
const choose = async (slug, name) => {
|
||||
await picker().click();
|
||||
await page.getByTestId(`browser-profile-option-${slug}`).click();
|
||||
await expect(picker()).toHaveAttribute("aria-label", `Browser profile: ${name}`);
|
||||
};
|
||||
const tunnelStats = () => {
|
||||
const stats = relayBridge.getStats("e2e-remote-host");
|
||||
return {
|
||||
clientConnections: stats.clientConnections,
|
||||
tunnelBytes: stats.connections[1]?.serverToClientBytes ?? 0,
|
||||
};
|
||||
};
|
||||
const loadedPage = {
|
||||
found: true,
|
||||
heading: "Proxied HTTP OK",
|
||||
wsResult: "WS_OK:ack:hello-tunnel",
|
||||
};
|
||||
const poll = (fn) => expect.poll(fn, { timeout: 30_000, intervals: [250, 500, 1000] });
|
||||
|
||||
// 1. The profile picker is on the host-proxied tab; create Work there.
|
||||
await expect(picker()).toHaveAttribute("aria-label", "Browser profile: Default");
|
||||
const before = tunnelStats();
|
||||
const wsCountBefore = targetServer.wsClientPorts.length;
|
||||
await picker().click();
|
||||
await page.getByTestId("browser-profile-create-trigger").click();
|
||||
await page.getByTestId("browser-create-profile-input").fill("Work");
|
||||
await page.getByTestId("browser-create-profile-submit").click();
|
||||
await expect(picker()).toHaveAttribute("aria-label", "Browser profile: Work");
|
||||
await poll(() => guestAt(hostWorkPartition)).toMatchObject({ ...loadedPage, marker: null });
|
||||
|
||||
// 2. Work still goes through the host: same SOCKS5 port, same tunnel, host daemon egress.
|
||||
const status = await page.evaluate(
|
||||
async () => await window.paseoDesktop.browser.getHostProxyStatus("e2e-remote-host"),
|
||||
);
|
||||
assert(
|
||||
status?.status === "ready" &&
|
||||
status.profilePartitions.default === hostPartition &&
|
||||
status.profilePartitions.work === hostWorkPartition &&
|
||||
typeof status.socksPort === "number",
|
||||
`Expected Default and Work bound to the host proxy, got ${JSON.stringify(status)}`,
|
||||
);
|
||||
const resolvedProxy = await inspect(
|
||||
`return await electron.session.fromPartition(${JSON.stringify(hostWorkPartition)}).resolveProxy("http://localhost:${targetServer.port}/");`,
|
||||
);
|
||||
assert(
|
||||
resolvedProxy.includes(`SOCKS5 127.0.0.1:${status.socksPort}`),
|
||||
`Expected Work to resolve to the host SOCKS5 port ${status.socksPort}, got ${resolvedProxy}`,
|
||||
);
|
||||
const after = tunnelStats();
|
||||
assert(
|
||||
after.clientConnections === before.clientConnections && after.tunnelBytes > before.tunnelBytes,
|
||||
`Expected Work to reuse the host tunnel, before=${JSON.stringify(before)} after=${JSON.stringify(after)}`,
|
||||
);
|
||||
const workWsPort = targetServer.wsClientPorts.slice(wsCountBefore).at(-1);
|
||||
assert(workWsPort, "Expected a guest WebSocket from the Work profile");
|
||||
const egressPid =
|
||||
process.platform === "linux"
|
||||
? processOwningConnection({ localPort: workWsPort, peerPort: targetServer.port })
|
||||
: null;
|
||||
const egressProcess = egressPid ? describeProcess(egressPid) : "skipped: needs Linux";
|
||||
assert(
|
||||
process.platform !== "linux" || egressProcess.serverId === "e2e-remote-host",
|
||||
`Expected the remote daemon to own Work's target connection, got ${JSON.stringify(egressProcess)}`,
|
||||
);
|
||||
|
||||
// 3. Default and Work keep separate storage and cookies on the same host.
|
||||
await markGuest(hostWorkPartition, "host-work");
|
||||
await choose("default", "Default");
|
||||
await poll(() => guestAt(hostPartition)).toMatchObject({
|
||||
...loadedPage,
|
||||
marker: "from-host-partition",
|
||||
});
|
||||
assert(
|
||||
!(await cookieAt(hostPartition)).includes("profile=host-work"),
|
||||
"Expected the host Default profile not to see Work's cookie",
|
||||
);
|
||||
await choose("work", "Work");
|
||||
await poll(() => guestAt(hostWorkPartition)).toMatchObject({
|
||||
...loadedPage,
|
||||
marker: "host-work",
|
||||
});
|
||||
|
||||
// 4. Work on the local route is a different partition from Work on the host route.
|
||||
await routingPill.click();
|
||||
await expect(routingPill).toHaveAttribute(
|
||||
"aria-label",
|
||||
"Switch browser routing from Local to Remote Proxy Host",
|
||||
{ timeout: 15_000 },
|
||||
);
|
||||
await poll(() => guestAt("persist:paseo-profile-work")).toMatchObject({
|
||||
...loadedPage,
|
||||
marker: null,
|
||||
});
|
||||
await routingPill.click();
|
||||
await expect(routingPill).toHaveAttribute(
|
||||
"aria-label",
|
||||
"Switch browser routing from Remote Proxy Host to Local",
|
||||
{ timeout: 15_000 },
|
||||
);
|
||||
await poll(() => guestAt(hostWorkPartition)).toMatchObject({
|
||||
...loadedPage,
|
||||
marker: "host-work",
|
||||
});
|
||||
|
||||
// 5. A second host tab on Default, to prove Clear and Remove leave Default alone.
|
||||
await openNewBrowserTabAndNavigate(page, targetUrl);
|
||||
await expect(picker()).toHaveAttribute("aria-label", "Browser profile: Default");
|
||||
await poll(() => guestAt(hostPartition)).toMatchObject({
|
||||
...loadedPage,
|
||||
marker: "from-host-partition",
|
||||
});
|
||||
|
||||
// 6. Clear Work in Settings clears it on the host route too; Default keeps its data.
|
||||
const hostWorkDir = path.join(userData, "Partitions", hostWorkPartition.slice("persist:".length));
|
||||
await poll(() => fs.existsSync(hostWorkDir)).toBe(true);
|
||||
await openBrowserProfileSettings(page);
|
||||
await acceptNextDialog(inspect, "Clear data");
|
||||
await page.getByTestId("settings-browser-profile-menu-work").click();
|
||||
await page.getByTestId("settings-browser-profile-clear-work").click();
|
||||
await expect(page.getByText("Browser data cleared", { exact: true })).toBeVisible();
|
||||
await poll(() => guestAt(hostWorkPartition)).toMatchObject({ ...loadedPage, marker: null });
|
||||
assert(
|
||||
!(await cookieAt(hostWorkPartition)).includes("profile=host-work"),
|
||||
"Expected Clear data to remove Work's cookie on the host route",
|
||||
);
|
||||
await poll(() => guestAt(hostPartition)).toMatchObject({ marker: "from-host-partition" });
|
||||
|
||||
// 7. Remove Work closes its host-proxied tab and deletes its host partition directory.
|
||||
await acceptNextDialog(inspect, "Remove");
|
||||
await page.getByTestId("settings-browser-profile-menu-work").click();
|
||||
await page.getByTestId("settings-browser-profile-remove-work").click();
|
||||
await expect(page.getByTestId("settings-browser-profile-row-work")).toHaveCount(0);
|
||||
await poll(() => fs.existsSync(hostWorkDir)).toBe(false);
|
||||
await page.getByTestId("settings-back-to-workspace").click();
|
||||
await poll(async () => (await guestAt(hostWorkPartition)).found).toBe(false);
|
||||
await poll(() => guestAt(hostPartition)).toMatchObject({ marker: "from-host-partition" });
|
||||
|
||||
return {
|
||||
hostWorkPartition,
|
||||
socksPort: status.socksPort,
|
||||
resolvedProxy,
|
||||
tunnelConnections: after.clientConnections,
|
||||
egressProcess,
|
||||
clearAndRemove: "passed",
|
||||
};
|
||||
}
|
||||
|
||||
async function waitForAppPage(browser, expoPort) {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
while (Date.now() < deadline) {
|
||||
@@ -679,8 +909,10 @@ async function openNewBrowserTabAndNavigate(page, url) {
|
||||
await expect(newTabBtn).toBeVisible({ timeout: 30_000 });
|
||||
await newTabBtn.click();
|
||||
|
||||
// An empty pane lists launchers as buttons; a pane with tabs opens a menu instead.
|
||||
const browserOption = page
|
||||
.getByRole("button", { name: /^Browser/i })
|
||||
.or(page.getByRole("menuitem", { name: /^Browser/i }))
|
||||
.and(page.locator(":visible"))
|
||||
.first();
|
||||
await expect(browserOption).toBeVisible({ timeout: 15_000 });
|
||||
@@ -750,7 +982,7 @@ async function verifyRoutedHostBrowsing({ page, targetServer, targetUrl }) {
|
||||
);
|
||||
assert(
|
||||
routedProxyStatus?.status === "ready" &&
|
||||
routedProxyStatus.partition === routedPartition &&
|
||||
routedProxyStatus.profilePartitions.default === routedPartition &&
|
||||
typeof routedProxyStatus.socksPort === "number",
|
||||
`Expected a ready routed host proxy, got ${JSON.stringify(routedProxyStatus)}`,
|
||||
);
|
||||
@@ -793,15 +1025,23 @@ async function main() {
|
||||
const userData = path.join(runtimeDir, "electron-user-data");
|
||||
const workspaceRoot = path.join(runtimeDir, "workspaces");
|
||||
|
||||
const [localDaemonPort, remoteDaemonPort, oldDaemonPort, routedDaemonPort, expoPort, cdpPort] =
|
||||
await Promise.all([
|
||||
reservePort(),
|
||||
reservePort(),
|
||||
reservePort(),
|
||||
reservePort(),
|
||||
reservePort(),
|
||||
reservePort(),
|
||||
]);
|
||||
const [
|
||||
localDaemonPort,
|
||||
remoteDaemonPort,
|
||||
oldDaemonPort,
|
||||
routedDaemonPort,
|
||||
expoPort,
|
||||
cdpPort,
|
||||
inspectorPort,
|
||||
] = await Promise.all([
|
||||
reservePort(),
|
||||
reservePort(),
|
||||
reservePort(),
|
||||
reservePort(),
|
||||
reservePort(),
|
||||
reservePort(),
|
||||
reservePort(),
|
||||
]);
|
||||
// The local daemon requires a password the renderer never sees, so the routed
|
||||
// tunnel can only authenticate to it with the desktop-managed local credential.
|
||||
const localDaemonPassword = "browser-proxy-e2e-local-password";
|
||||
@@ -811,6 +1051,7 @@ async function main() {
|
||||
const children = [];
|
||||
let legacyAdapter = null;
|
||||
let browser = null;
|
||||
let appPage = null;
|
||||
|
||||
try {
|
||||
seedPaseoHome({
|
||||
@@ -956,6 +1197,7 @@ async function main() {
|
||||
const desktopArgs = [
|
||||
process.execPath,
|
||||
devRunner,
|
||||
`--inspect=127.0.0.1:${inspectorPort}`,
|
||||
...(process.platform === "linux" ? ["--no-sandbox"] : []),
|
||||
];
|
||||
const desktopCommand = process.platform === "linux" ? "xvfb-run" : desktopArgs.shift();
|
||||
@@ -990,6 +1232,7 @@ async function main() {
|
||||
|
||||
browser = await chromium.connectOverCDP(`http://127.0.0.1:${cdpPort}`);
|
||||
const page = await waitForAppPage(browser, expoPort);
|
||||
appPage = page;
|
||||
await hideDeveloperToasts(page);
|
||||
await waitForDesktopStatus(page);
|
||||
|
||||
@@ -1169,7 +1412,22 @@ async function main() {
|
||||
});
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// 3. Old daemon without features.networkTunnel fails closed + Browse locally
|
||||
// 3. Browser profiles on the host-proxied tab
|
||||
// -------------------------------------------------------------------------
|
||||
const hostProfiles = await verifyHostProxiedProfiles({
|
||||
page,
|
||||
inspect: (expression) => evaluateMainProcess(inspectorPort, expression),
|
||||
relayBridge,
|
||||
targetServer,
|
||||
targetUrl,
|
||||
hostPartition: hostGuest.partition,
|
||||
routingPill,
|
||||
userData,
|
||||
});
|
||||
await page.screenshot({ path: path.join(artifactDir, "03-host-profiles.png") });
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// 4. Old daemon without features.networkTunnel fails closed + Browse locally
|
||||
// -------------------------------------------------------------------------
|
||||
const oldWsButton = page
|
||||
.getByRole("button", {
|
||||
@@ -1233,7 +1491,7 @@ async function main() {
|
||||
await page.screenshot({ path: path.join(artifactDir, "04-old-daemon-browse-locally.png") });
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// 4. Routed host: desktop -> local daemon -> routed daemon -> target
|
||||
// 5. Routed host: desktop -> local daemon -> routed daemon -> target
|
||||
// -------------------------------------------------------------------------
|
||||
const routedHost = await verifyRoutedHostBrowsing({
|
||||
page,
|
||||
@@ -1254,6 +1512,7 @@ async function main() {
|
||||
binaryFrames: secondaryTunnelConn.binaryFrames,
|
||||
},
|
||||
togglePartitionIsolation: "passed",
|
||||
hostProfiles,
|
||||
oldDaemonFailClosedAndBrowseLocally: "passed",
|
||||
routedHost,
|
||||
artifactDir,
|
||||
@@ -1262,6 +1521,11 @@ async function main() {
|
||||
2,
|
||||
),
|
||||
);
|
||||
} catch (error) {
|
||||
await appPage
|
||||
?.screenshot({ path: path.join(artifactDir, "failure.png") })
|
||||
.catch(() => undefined);
|
||||
throw error;
|
||||
} finally {
|
||||
await browser?.close().catch(() => undefined);
|
||||
legacyAdapter?.close();
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/desktop",
|
||||
"version": "0.18.2",
|
||||
"version": "0.19.0-beta.1",
|
||||
"private": true,
|
||||
"description": "Paseo desktop app (Electron wrapper)",
|
||||
"homepage": "https://paseo.sh",
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { getBrowserPartition, parseBrowserPartition } from "./browser-partition.js";
|
||||
|
||||
const LOCAL = { kind: "local" } as const;
|
||||
const host = (serverId: string) => ({ kind: "host", serverId }) as const;
|
||||
|
||||
describe("browser partition naming", () => {
|
||||
test("keeps the existing local and host default partition names", () => {
|
||||
expect(getBrowserPartition(LOCAL, "default")).toBe("persist:paseo-browser");
|
||||
expect(getBrowserPartition(LOCAL, "work")).toBe("persist:paseo-profile-work");
|
||||
expect(getBrowserPartition(host("srv_alpha_123"), "default")).toMatch(
|
||||
/^persist:paseo-browser-host-[0-9a-f]{16}$/,
|
||||
);
|
||||
});
|
||||
|
||||
test("composes a host route with a named profile into its own deterministic partition", () => {
|
||||
const hostDefault = getBrowserPartition(host("srv_alpha_123"), "default");
|
||||
const hostWork = getBrowserPartition(host("srv_alpha_123"), "work");
|
||||
|
||||
expect(hostWork).toBe(`${hostDefault}-profile-work`);
|
||||
expect(getBrowserPartition(host("srv_alpha_123"), "work")).toBe(hostWork);
|
||||
expect(getBrowserPartition(host("srv_beta_456"), "work")).not.toBe(hostWork);
|
||||
expect(getBrowserPartition(host("srv_alpha_123"), "customer")).not.toBe(hostWork);
|
||||
});
|
||||
|
||||
test("rejects invalid routes and profile slugs", () => {
|
||||
expect(() => getBrowserPartition(host(" "), "default")).toThrow();
|
||||
expect(() => getBrowserPartition(LOCAL, "Work")).toThrow();
|
||||
expect(() => getBrowserPartition(host("srv"), "a--b")).toThrow();
|
||||
});
|
||||
|
||||
test("parses every route and profile combination back", () => {
|
||||
const hostDefault = getBrowserPartition(host("srv"), "default");
|
||||
expect(parseBrowserPartition("persist:paseo-browser")).toEqual({
|
||||
route: "local",
|
||||
profileSlug: "default",
|
||||
});
|
||||
expect(parseBrowserPartition("persist:paseo-profile-work")).toEqual({
|
||||
route: "local",
|
||||
profileSlug: "work",
|
||||
});
|
||||
expect(parseBrowserPartition(hostDefault)).toEqual({ route: "host", profileSlug: "default" });
|
||||
expect(parseBrowserPartition(`${hostDefault}-profile-work`)).toEqual({
|
||||
route: "host",
|
||||
profileSlug: "work",
|
||||
});
|
||||
// A slug may itself look like a host suffix; the local prefix still owns it.
|
||||
expect(parseBrowserPartition("persist:paseo-profile-work-host-0123456789abcdef")).toEqual({
|
||||
route: "local",
|
||||
profileSlug: "work-host-0123456789abcdef",
|
||||
});
|
||||
});
|
||||
|
||||
test("rejects partitions outside the Paseo browser namespace", () => {
|
||||
for (const partition of [
|
||||
undefined,
|
||||
42,
|
||||
"persist:foreign",
|
||||
"paseo-browser",
|
||||
"persist:paseo-profile-default",
|
||||
"persist:paseo-profile-Work",
|
||||
"persist:paseo-browser-tab-a",
|
||||
"persist:paseo-browser-host-0123456789abcde",
|
||||
"persist:paseo-browser-host-0123456789ABCDEF",
|
||||
"persist:paseo-browser-host-0123456789abcdef0",
|
||||
"persist:paseo-browser-host-0123456789abcdef-profile-",
|
||||
"persist:paseo-browser-host-0123456789abcdef-profile-default",
|
||||
"persist:paseo-browser-host-0123456789abcdef-profile-Work",
|
||||
"persist:paseo-browser-11111111-1111-4111-8111-111111111111",
|
||||
]) {
|
||||
expect(parseBrowserPartition(partition)).toBeNull();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,81 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
/**
|
||||
* A browser tab's Electron session partition is the pair (route, profile).
|
||||
* Electron binds `session.setProxy` per partition, so the route lives in the name,
|
||||
* and the profile keeps cookies and storage apart on that route.
|
||||
*
|
||||
* local + default persist:paseo-browser
|
||||
* local + <slug> persist:paseo-profile-<slug>
|
||||
* host + default persist:paseo-browser-host-<16hex>
|
||||
* host + <slug> persist:paseo-browser-host-<16hex>-profile-<slug>
|
||||
*
|
||||
* The first three names predate this module and must not change: they hold the user's
|
||||
* existing cookies and storage on disk.
|
||||
*/
|
||||
export type BrowserRoute = { kind: "local" } | { kind: "host"; serverId: string };
|
||||
|
||||
export interface ParsedBrowserPartition {
|
||||
route: BrowserRoute["kind"];
|
||||
profileSlug: string;
|
||||
}
|
||||
|
||||
export const DEFAULT_BROWSER_PROFILE_SLUG = "default";
|
||||
export const PASEO_BROWSER_PROFILE_PARTITION = "persist:paseo-browser";
|
||||
|
||||
const PERSIST = "persist:";
|
||||
const LOCAL_PROFILE_PREFIX = "paseo-profile-";
|
||||
const HOST_PREFIX = "paseo-browser-host-";
|
||||
const HOST_PROFILE_INFIX = "-profile-";
|
||||
const NAMED_SLUG = /^(?=.{1,48}$)[a-z0-9]+(?:-[a-z0-9]+)*$/;
|
||||
const HOST_PARTITION = /^paseo-browser-host-([0-9a-f]{16})(?:-profile-(.+))?$/;
|
||||
|
||||
export function isNamedBrowserProfileSlug(slug: string): boolean {
|
||||
return NAMED_SLUG.test(slug) && slug !== DEFAULT_BROWSER_PROFILE_SLUG;
|
||||
}
|
||||
|
||||
function hostKey(serverId: string): string {
|
||||
const normalized = serverId.trim();
|
||||
if (!normalized) {
|
||||
throw new Error("Host serverId is required to derive a browser partition");
|
||||
}
|
||||
return createHash("sha256").update(normalized, "utf8").digest("hex").slice(0, 16);
|
||||
}
|
||||
|
||||
export function getBrowserPartition(route: BrowserRoute, profileSlug: string): string {
|
||||
const isDefault = profileSlug === DEFAULT_BROWSER_PROFILE_SLUG;
|
||||
if (!isDefault && !isNamedBrowserProfileSlug(profileSlug)) {
|
||||
throw new Error(`Invalid browser profile slug: ${profileSlug}`);
|
||||
}
|
||||
if (route.kind === "local") {
|
||||
return isDefault
|
||||
? PASEO_BROWSER_PROFILE_PARTITION
|
||||
: `${PERSIST}${LOCAL_PROFILE_PREFIX}${profileSlug}`;
|
||||
}
|
||||
const hostPartition = `${PERSIST}${HOST_PREFIX}${hostKey(route.serverId)}`;
|
||||
return isDefault ? hostPartition : `${hostPartition}${HOST_PROFILE_INFIX}${profileSlug}`;
|
||||
}
|
||||
|
||||
/** Returns the (route, profile) of a Paseo browser partition, or null for any other partition. */
|
||||
export function parseBrowserPartition(partition: unknown): ParsedBrowserPartition | null {
|
||||
if (typeof partition !== "string" || !partition.startsWith(PERSIST)) {
|
||||
return null;
|
||||
}
|
||||
if (partition === PASEO_BROWSER_PROFILE_PARTITION) {
|
||||
return { route: "local", profileSlug: DEFAULT_BROWSER_PROFILE_SLUG };
|
||||
}
|
||||
const name = partition.slice(PERSIST.length);
|
||||
if (name.startsWith(LOCAL_PROFILE_PREFIX)) {
|
||||
const slug = name.slice(LOCAL_PROFILE_PREFIX.length);
|
||||
return isNamedBrowserProfileSlug(slug) ? { route: "local", profileSlug: slug } : null;
|
||||
}
|
||||
const host = HOST_PARTITION.exec(name);
|
||||
if (!host) {
|
||||
return null;
|
||||
}
|
||||
const slug = host[2];
|
||||
if (slug === undefined) {
|
||||
return { route: "host", profileSlug: DEFAULT_BROWSER_PROFILE_SLUG };
|
||||
}
|
||||
return isNamedBrowserProfileSlug(slug) ? { route: "host", profileSlug: slug } : null;
|
||||
}
|
||||
@@ -2,11 +2,8 @@ import { randomUUID } from "node:crypto";
|
||||
import { readFile, rename, rm, writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
BROWSER_PROFILE_COLORS,
|
||||
isNamedBrowserProfileSlug,
|
||||
type BrowserProfileColor,
|
||||
} from "./browser-profile.js";
|
||||
import { isNamedBrowserProfileSlug } from "./browser-partition.js";
|
||||
import { BROWSER_PROFILE_COLORS, type BrowserProfileColor } from "./browser-profile.js";
|
||||
|
||||
const colorSchema = z.enum(BROWSER_PROFILE_COLORS);
|
||||
const nameSchema = z.string().trim().min(1).max(80);
|
||||
|
||||
@@ -2,24 +2,27 @@ import { mkdir, mkdtemp, rm, stat, writeFile } from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { getBrowserPartition, PASEO_BROWSER_PROFILE_PARTITION } from "./browser-partition.js";
|
||||
import {
|
||||
clearPaseoBrowserProfile,
|
||||
deleteBrowserProfilePartitionDirectory,
|
||||
getBrowserProfilePartition,
|
||||
deleteBrowserProfilePartitionDirectories,
|
||||
getLegacyPaseoBrowserProfileSession,
|
||||
getPaseoBrowserProfileSession,
|
||||
getPaseoBrowserProfileSessions,
|
||||
isNamedBrowserProfileSlug,
|
||||
isPaseoBrowserProfilePartition,
|
||||
listBrowserPartitionDirectories,
|
||||
listDiskHostBrowserProxyPartitions,
|
||||
listPaseoBrowserProfileGuests,
|
||||
PASEO_BROWSER_PROFILE_PARTITION,
|
||||
pruneOrphanedBrowserProfilePartitions,
|
||||
readHostBrowserProxyPartitions,
|
||||
readLegacyPaseoBrowserIds,
|
||||
} from "./browser-profile.js";
|
||||
import { getHostBrowserProxyPartition } from "./browser-proxy/partition.js";
|
||||
|
||||
function getHostBrowserProxyPartition(serverId: string, profileSlug = "default"): string {
|
||||
return getBrowserPartition({ kind: "host", serverId }, profileSlug);
|
||||
}
|
||||
|
||||
function directoryOf(partition: string): string {
|
||||
return partition.slice("persist:".length);
|
||||
}
|
||||
|
||||
function createFakeSession() {
|
||||
return {
|
||||
@@ -29,34 +32,37 @@ function createFakeSession() {
|
||||
};
|
||||
}
|
||||
|
||||
describe("browser profile partition naming", () => {
|
||||
it("maps default and named slugs to persistent partitions", () => {
|
||||
expect(getBrowserProfilePartition("default")).toBe(PASEO_BROWSER_PROFILE_PARTITION);
|
||||
expect(getBrowserProfilePartition("work")).toBe("persist:paseo-profile-work");
|
||||
expect(isNamedBrowserProfileSlug("work")).toBe(true);
|
||||
expect(isNamedBrowserProfileSlug("default")).toBe(false);
|
||||
expect(isNamedBrowserProfileSlug("Work")).toBe(false);
|
||||
expect(isNamedBrowserProfileSlug("a--b")).toBe(false);
|
||||
expect(isPaseoBrowserProfilePartition(PASEO_BROWSER_PROFILE_PARTITION)).toBe(true);
|
||||
expect(isPaseoBrowserProfilePartition("persist:paseo-profile-work")).toBe(true);
|
||||
expect(isPaseoBrowserProfilePartition("persist:paseo-profile-default")).toBe(false);
|
||||
expect(isPaseoBrowserProfilePartition("persist:other")).toBe(false);
|
||||
});
|
||||
|
||||
it("deletes a named profile partition directory and refuses default", async () => {
|
||||
describe("browser profile partition directories", () => {
|
||||
it("deletes a named profile's local and host-proxied directories and refuses default", async () => {
|
||||
const userData = await mkdtemp(path.join(os.tmpdir(), "paseo-partitions-"));
|
||||
try {
|
||||
const workDir = path.join(userData, "Partitions", "paseo-profile-work");
|
||||
const defaultDir = path.join(userData, "Partitions", "paseo-browser");
|
||||
await mkdir(workDir, { recursive: true });
|
||||
await mkdir(defaultDir, { recursive: true });
|
||||
const partitions = (name: string) => path.join(userData, "Partitions", name);
|
||||
const workDir = partitions("paseo-profile-work");
|
||||
const hostWorkDir = partitions(directoryOf(getHostBrowserProxyPartition("remote-a", "work")));
|
||||
const otherHostWorkDir = partitions(
|
||||
directoryOf(getHostBrowserProxyPartition("remote-b", "work")),
|
||||
);
|
||||
const kept = [
|
||||
partitions("paseo-browser"),
|
||||
partitions(directoryOf(getHostBrowserProxyPartition("remote-a"))),
|
||||
partitions(directoryOf(getHostBrowserProxyPartition("remote-a", "customer"))),
|
||||
partitions("paseo-profile-customer"),
|
||||
];
|
||||
for (const dir of [workDir, hostWorkDir, otherHostWorkDir, ...kept]) {
|
||||
await mkdir(dir, { recursive: true });
|
||||
}
|
||||
await writeFile(path.join(workDir, "Cookies"), "alice");
|
||||
await writeFile(path.join(hostWorkDir, "Cookies"), "alice-on-host");
|
||||
|
||||
await deleteBrowserProfilePartitionDirectory(userData, "work");
|
||||
await deleteBrowserProfilePartitionDirectories(userData, "work");
|
||||
|
||||
await expect(stat(workDir)).rejects.toThrow();
|
||||
expect((await stat(defaultDir)).isDirectory()).toBe(true);
|
||||
await expect(deleteBrowserProfilePartitionDirectory(userData, "default")).rejects.toThrow();
|
||||
for (const dir of [workDir, hostWorkDir, otherHostWorkDir]) {
|
||||
await expect(stat(dir)).rejects.toThrow();
|
||||
}
|
||||
for (const dir of kept) {
|
||||
expect((await stat(dir)).isDirectory()).toBe(true);
|
||||
}
|
||||
await expect(deleteBrowserProfilePartitionDirectories(userData, "default")).rejects.toThrow();
|
||||
} finally {
|
||||
await rm(userData, { recursive: true, force: true });
|
||||
}
|
||||
@@ -109,9 +115,9 @@ describe("listPaseoBrowserProfileGuests", () => {
|
||||
});
|
||||
|
||||
describe("getPaseoBrowserProfileSessions", () => {
|
||||
it("scopes single-profile clearing to only that profile session", () => {
|
||||
function createSessions() {
|
||||
const byPartition = new Map<string, ReturnType<typeof createFakeSession>>();
|
||||
const sessions = {
|
||||
return {
|
||||
fromPartition: vi.fn((partition: string) => {
|
||||
let existing = byPartition.get(partition);
|
||||
if (!existing) {
|
||||
@@ -121,46 +127,82 @@ describe("getPaseoBrowserProfileSessions", () => {
|
||||
return existing;
|
||||
}),
|
||||
};
|
||||
}
|
||||
const openedPartitions = (sessions: ReturnType<typeof createSessions>) =>
|
||||
sessions.fromPartition.mock.calls.map(([partition]) => partition);
|
||||
|
||||
const directories = [
|
||||
"paseo-profile-work",
|
||||
"paseo-profile-customer",
|
||||
"paseo-browser-11111111-1111-4111-8111-111111111111",
|
||||
];
|
||||
const hostDefault = getHostBrowserProxyPartition("remote-host-1");
|
||||
const hostWork = getHostBrowserProxyPartition("remote-host-1", "work");
|
||||
const otherHostWork = getHostBrowserProxyPartition("remote-host-2", "work");
|
||||
const hostCustomer = getHostBrowserProxyPartition("remote-host-1", "customer");
|
||||
const legacy = "paseo-browser-11111111-1111-4111-8111-111111111111";
|
||||
const directories = [
|
||||
"paseo-profile-work",
|
||||
"paseo-profile-customer",
|
||||
legacy,
|
||||
directoryOf(hostDefault),
|
||||
directoryOf(otherHostWork),
|
||||
directoryOf(hostCustomer),
|
||||
"unrelated",
|
||||
];
|
||||
|
||||
const workOnly = getPaseoBrowserProfileSessions(sessions, directories, { slug: "work" });
|
||||
expect(workOnly).toHaveLength(1);
|
||||
expect(sessions.fromPartition).toHaveBeenCalledWith("persist:paseo-profile-work");
|
||||
|
||||
sessions.fromPartition.mockClear();
|
||||
const hostPartition = getHostBrowserProxyPartition("remote-host-1");
|
||||
const defaultWithHost = getPaseoBrowserProfileSessions(sessions, directories, {
|
||||
slug: "default",
|
||||
hostPartitions: [hostPartition],
|
||||
it("clears a named profile across the local route and every host route", () => {
|
||||
const sessions = createSessions();
|
||||
const work = getPaseoBrowserProfileSessions(sessions, directories, {
|
||||
slug: "work",
|
||||
hostPartitions: [hostWork, hostDefault],
|
||||
});
|
||||
expect(defaultWithHost).toHaveLength(3);
|
||||
expect(sessions.fromPartition.mock.calls.map(([p]) => p)).toEqual([
|
||||
PASEO_BROWSER_PROFILE_PARTITION,
|
||||
"persist:paseo-browser-11111111-1111-4111-8111-111111111111",
|
||||
hostPartition,
|
||||
expect(work).toHaveLength(3);
|
||||
expect(openedPartitions(sessions)).toEqual([
|
||||
"persist:paseo-profile-work",
|
||||
otherHostWork,
|
||||
hostWork,
|
||||
]);
|
||||
});
|
||||
|
||||
sessions.fromPartition.mockClear();
|
||||
it("clears Default across the local route, legacy tabs, and every host route", () => {
|
||||
const sessions = createSessions();
|
||||
const defaults = getPaseoBrowserProfileSessions(sessions, directories, {
|
||||
slug: "default",
|
||||
hostPartitions: [hostWork, getHostBrowserProxyPartition("remote-host-3")],
|
||||
});
|
||||
expect(defaults).toHaveLength(4);
|
||||
expect(openedPartitions(sessions)).toEqual([
|
||||
PASEO_BROWSER_PROFILE_PARTITION,
|
||||
`persist:${legacy}`,
|
||||
hostDefault,
|
||||
getHostBrowserProxyPartition("remote-host-3"),
|
||||
]);
|
||||
});
|
||||
|
||||
it("clears every profile and route, including live sessions, without a slug", () => {
|
||||
const sessions = createSessions();
|
||||
const liveSession = createFakeSession();
|
||||
const all = getPaseoBrowserProfileSessions(sessions, directories, {
|
||||
hostPartitions: [hostPartition],
|
||||
hostPartitions: [hostWork],
|
||||
liveSessions: [liveSession],
|
||||
});
|
||||
expect(all).toContain(liveSession);
|
||||
expect(sessions.fromPartition.mock.calls.map(([p]) => p)).toEqual([
|
||||
expect(openedPartitions(sessions)).toEqual([
|
||||
PASEO_BROWSER_PROFILE_PARTITION,
|
||||
"persist:paseo-profile-work",
|
||||
"persist:paseo-profile-customer",
|
||||
"persist:paseo-browser-11111111-1111-4111-8111-111111111111",
|
||||
hostPartition,
|
||||
`persist:${legacy}`,
|
||||
hostDefault,
|
||||
otherHostWork,
|
||||
hostCustomer,
|
||||
hostWork,
|
||||
]);
|
||||
});
|
||||
|
||||
it("opens nothing for an invalid slug", () => {
|
||||
const sessions = createSessions();
|
||||
expect(getPaseoBrowserProfileSessions(sessions, directories, { slug: "Not Valid" })).toEqual(
|
||||
[],
|
||||
);
|
||||
expect(sessions.fromPartition).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("reads host proxy and legacy browser IDs safely", () => {
|
||||
expect(getPaseoBrowserProfileSession({ fromPartition: (p) => ({ p }) as never })).toEqual({
|
||||
p: PASEO_BROWSER_PROFILE_PARTITION,
|
||||
@@ -220,30 +262,30 @@ describe("clearPaseoBrowserProfile", () => {
|
||||
});
|
||||
|
||||
describe("partition directory discovery", () => {
|
||||
it("lists partition directories and host proxy partitions on disk", async () => {
|
||||
it("lists partition directories and prunes orphaned profiles on every route", async () => {
|
||||
const directory = await mkdtemp(path.join(os.tmpdir(), "paseo-partitions-list-"));
|
||||
try {
|
||||
expect(await listBrowserPartitionDirectories(directory)).toEqual([]);
|
||||
expect(listDiskHostBrowserProxyPartitions(directory)).toEqual([]);
|
||||
|
||||
const hostDir = getHostBrowserProxyPartition("remote-a").slice("persist:".length);
|
||||
for (const name of ["paseo-profile-work", hostDir, "unrelated"]) {
|
||||
const hostDefaultDir = directoryOf(getHostBrowserProxyPartition("remote-a"));
|
||||
const hostWorkDir = directoryOf(getHostBrowserProxyPartition("remote-a", "work"));
|
||||
const hostOrphanDir = directoryOf(getHostBrowserProxyPartition("remote-a", "orphaned"));
|
||||
for (const name of [
|
||||
"paseo-profile-work",
|
||||
"paseo-profile-orphaned",
|
||||
hostDefaultDir,
|
||||
hostWorkDir,
|
||||
hostOrphanDir,
|
||||
"unrelated",
|
||||
]) {
|
||||
await mkdir(path.join(directory, "Partitions", name), { recursive: true });
|
||||
}
|
||||
await writeFile(path.join(directory, "Partitions", "paseo-profile-file"), "");
|
||||
|
||||
expect((await listBrowserPartitionDirectories(directory)).sort()).toEqual(
|
||||
["paseo-profile-work", hostDir, "unrelated"].sort(),
|
||||
);
|
||||
expect(listDiskHostBrowserProxyPartitions(directory)).toEqual([`persist:${hostDir}`]);
|
||||
|
||||
await mkdir(path.join(directory, "Partitions", "paseo-profile-orphaned"), {
|
||||
recursive: true,
|
||||
});
|
||||
const pruned = await pruneOrphanedBrowserProfilePartitions(directory, new Set(["work"]));
|
||||
expect(pruned).toEqual(["orphaned"]);
|
||||
expect((await listBrowserPartitionDirectories(directory)).sort()).toEqual(
|
||||
["paseo-profile-work", hostDir, "unrelated"].sort(),
|
||||
["paseo-profile-work", hostDefaultDir, hostWorkDir, "unrelated"].sort(),
|
||||
);
|
||||
} finally {
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
|
||||
@@ -1,13 +1,12 @@
|
||||
import { readdir, rm } from "node:fs/promises";
|
||||
import { readdirSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import {
|
||||
getHostBrowserProxyPartition,
|
||||
isHostBrowserProxyPartition,
|
||||
} from "./browser-proxy/partition.js";
|
||||
|
||||
export const PASEO_BROWSER_PROFILE_PARTITION = "persist:paseo-browser";
|
||||
export const PASEO_BROWSER_NAMED_PROFILE_PREFIX = "paseo-profile-";
|
||||
DEFAULT_BROWSER_PROFILE_SLUG,
|
||||
getBrowserPartition,
|
||||
isNamedBrowserProfileSlug,
|
||||
PASEO_BROWSER_PROFILE_PARTITION,
|
||||
parseBrowserPartition,
|
||||
} from "./browser-partition.js";
|
||||
|
||||
export const BROWSER_PROFILE_COLORS = [
|
||||
"violet",
|
||||
@@ -24,42 +23,15 @@ export const BROWSER_PROFILE_COLORS = [
|
||||
|
||||
export type BrowserProfileColor = (typeof BROWSER_PROFILE_COLORS)[number];
|
||||
|
||||
const NAMED_SLUG = /^(?=.{1,48}$)[a-z0-9]+(?:-[a-z0-9]+)*$/;
|
||||
const LEGACY_PREFIX = "paseo-browser-";
|
||||
const LEGACY_BROWSER_ID_PATTERN =
|
||||
/^(?:[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|\d{13,}-[0-9a-f]+)$/i;
|
||||
const MAX_LEGACY_BROWSER_PROFILES = 1000;
|
||||
const MAX_HOST_BROWSER_PROFILES = 500;
|
||||
const DISK_HOST_PARTITION_DIR_PATTERN = /^paseo-browser-host-[0-9a-f]{16}$/;
|
||||
|
||||
export function isNamedBrowserProfileSlug(slug: string): boolean {
|
||||
return NAMED_SLUG.test(slug) && slug !== "default";
|
||||
}
|
||||
|
||||
export function getBrowserProfilePartition(slug: string): string {
|
||||
if (slug === "default") {
|
||||
return PASEO_BROWSER_PROFILE_PARTITION;
|
||||
}
|
||||
if (!isNamedBrowserProfileSlug(slug)) {
|
||||
throw new Error(`Invalid browser profile slug: ${slug}`);
|
||||
}
|
||||
return `persist:${PASEO_BROWSER_NAMED_PROFILE_PREFIX}${slug}`;
|
||||
}
|
||||
|
||||
export function isNamedProfileDirectory(name: string): boolean {
|
||||
return (
|
||||
name.startsWith(PASEO_BROWSER_NAMED_PROFILE_PREFIX) &&
|
||||
isNamedBrowserProfileSlug(name.slice(PASEO_BROWSER_NAMED_PROFILE_PREFIX.length))
|
||||
);
|
||||
}
|
||||
|
||||
export function isPaseoBrowserProfilePartition(partition: unknown): partition is string {
|
||||
return (
|
||||
partition === PASEO_BROWSER_PROFILE_PARTITION ||
|
||||
(typeof partition === "string" &&
|
||||
partition.startsWith("persist:") &&
|
||||
isNamedProfileDirectory(partition.slice("persist:".length)))
|
||||
);
|
||||
/** The profile a partition directory under `<userData>/Partitions` belongs to, on any route. */
|
||||
function readDirectoryProfileSlug(name: string): string | null {
|
||||
return parseBrowserPartition(`persist:${name}`)?.profileSlug ?? null;
|
||||
}
|
||||
|
||||
export async function listBrowserPartitionDirectories(userData: string): Promise<string[]> {
|
||||
@@ -72,19 +44,20 @@ export async function listBrowserPartitionDirectories(userData: string): Promise
|
||||
}
|
||||
}
|
||||
|
||||
export async function deleteBrowserProfilePartitionDirectory(
|
||||
/** Deletes a named profile's partition directories on the local route and every host route. */
|
||||
export async function deleteBrowserProfilePartitionDirectories(
|
||||
userData: string,
|
||||
slug: string,
|
||||
): Promise<void> {
|
||||
if (!isNamedBrowserProfileSlug(slug)) {
|
||||
throw new Error(`Cannot delete browser profile partition for slug: ${slug}`);
|
||||
throw new Error(`Cannot delete browser profile partitions for slug: ${slug}`);
|
||||
}
|
||||
const partitionDir = path.join(
|
||||
userData,
|
||||
"Partitions",
|
||||
`${PASEO_BROWSER_NAMED_PROFILE_PREFIX}${slug}`,
|
||||
const directories = await listBrowserPartitionDirectories(userData);
|
||||
await Promise.all(
|
||||
directories
|
||||
.filter((name) => readDirectoryProfileSlug(name) === slug)
|
||||
.map((name) => rm(path.join(userData, "Partitions", name), { recursive: true, force: true })),
|
||||
);
|
||||
await rm(partitionDir, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
export async function pruneOrphanedBrowserProfilePartitions(
|
||||
@@ -92,15 +65,17 @@ export async function pruneOrphanedBrowserProfilePartitions(
|
||||
activeSlugs: ReadonlySet<string>,
|
||||
): Promise<string[]> {
|
||||
const directories = await listBrowserPartitionDirectories(userData);
|
||||
const removed: string[] = [];
|
||||
const orphanedSlugs = new Set<string>();
|
||||
for (const name of directories) {
|
||||
if (!isNamedProfileDirectory(name)) continue;
|
||||
const slug = name.slice(PASEO_BROWSER_NAMED_PROFILE_PREFIX.length);
|
||||
if (activeSlugs.has(slug)) continue;
|
||||
await deleteBrowserProfilePartitionDirectory(userData, slug);
|
||||
removed.push(slug);
|
||||
const slug = readDirectoryProfileSlug(name);
|
||||
if (slug && isNamedBrowserProfileSlug(slug) && !activeSlugs.has(slug)) {
|
||||
orphanedSlugs.add(slug);
|
||||
}
|
||||
}
|
||||
return removed;
|
||||
for (const slug of orphanedSlugs) {
|
||||
await deleteBrowserProfilePartitionDirectories(userData, slug);
|
||||
}
|
||||
return [...orphanedSlugs];
|
||||
}
|
||||
|
||||
const PASEO_BROWSER_STORAGE_TYPES = [
|
||||
@@ -133,10 +108,10 @@ interface BrowserProfileWebContents extends BrowserProfileGuest {
|
||||
getType(): string;
|
||||
}
|
||||
|
||||
interface ListBrowserProfileGuestsInput {
|
||||
interface ListBrowserProfileGuestsInput<W extends BrowserProfileWebContents> {
|
||||
profileSession?: object;
|
||||
profileSessions?: Iterable<object>;
|
||||
webContents: BrowserProfileWebContents[];
|
||||
webContents: W[];
|
||||
}
|
||||
|
||||
interface ClearBrowserProfileInput {
|
||||
@@ -180,6 +155,7 @@ export function readLegacyPaseoBrowserIds(input: unknown): string[] {
|
||||
return [...browserIds];
|
||||
}
|
||||
|
||||
/** Default-profile host partitions for renderer-supplied host server ids. */
|
||||
export function readHostBrowserProxyPartitions(input: unknown): string[] {
|
||||
if (!Array.isArray(input)) {
|
||||
return [];
|
||||
@@ -190,7 +166,9 @@ export function readHostBrowserProxyPartitions(input: unknown): string[] {
|
||||
const trimmed = value.trim();
|
||||
if (!trimmed) continue;
|
||||
partitions.add(
|
||||
isHostBrowserProxyPartition(trimmed) ? trimmed : getHostBrowserProxyPartition(trimmed),
|
||||
parseBrowserPartition(trimmed)?.route === "host"
|
||||
? trimmed
|
||||
: getBrowserPartition({ kind: "host", serverId: trimmed }, DEFAULT_BROWSER_PROFILE_SLUG),
|
||||
);
|
||||
if (partitions.size >= MAX_HOST_BROWSER_PROFILES) {
|
||||
break;
|
||||
@@ -199,22 +177,12 @@ export function readHostBrowserProxyPartitions(input: unknown): string[] {
|
||||
return [...partitions];
|
||||
}
|
||||
|
||||
export function listDiskHostBrowserProxyPartitions(userDataDir: string): string[] {
|
||||
try {
|
||||
const partitionsDir = path.join(userDataDir, "Partitions");
|
||||
const entries = readdirSync(partitionsDir, { withFileTypes: true });
|
||||
const result: string[] = [];
|
||||
for (const entry of entries) {
|
||||
if (entry.isDirectory() && DISK_HOST_PARTITION_DIR_PATTERN.test(entry.name)) {
|
||||
result.push(`persist:${entry.name}`);
|
||||
}
|
||||
}
|
||||
return result.sort();
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sessions that hold a profile's data on every route. With a slug, only that profile
|
||||
* (Default also owns legacy per-tab partitions). Without a slug, every Paseo profile.
|
||||
* Host partitions come from disk directories and from `hostPartitions`, the ones
|
||||
* this process bound to a host proxy.
|
||||
*/
|
||||
export function getPaseoBrowserProfileSessions<S extends BrowserProfileSession>(
|
||||
sessions: { fromPartition(partition: string): S },
|
||||
directories: readonly string[],
|
||||
@@ -224,43 +192,42 @@ export function getPaseoBrowserProfileSessions<S extends BrowserProfileSession>(
|
||||
slug?: string;
|
||||
} = {},
|
||||
): S[] {
|
||||
if (options.slug && options.slug !== "default") {
|
||||
if (!isNamedBrowserProfileSlug(options.slug)) {
|
||||
return [];
|
||||
}
|
||||
return [sessions.fromPartition(getBrowserProfilePartition(options.slug))];
|
||||
}
|
||||
|
||||
const result = new Set<S>([sessions.fromPartition(PASEO_BROWSER_PROFILE_PARTITION)]);
|
||||
|
||||
if (options.slug === "default") {
|
||||
// Clearing Default also sweeps legacy per-tab partitions and remote host-proxy partitions.
|
||||
for (const name of directories) {
|
||||
if (isLegacyDirectory(name)) {
|
||||
result.add(sessions.fromPartition(`persist:${name}`));
|
||||
}
|
||||
}
|
||||
for (const partition of options.hostPartitions ?? []) {
|
||||
if (isHostBrowserProxyPartition(partition)) {
|
||||
result.add(sessions.fromPartition(partition));
|
||||
}
|
||||
}
|
||||
return [...result];
|
||||
const { slug } = options;
|
||||
if (
|
||||
slug !== undefined &&
|
||||
slug !== DEFAULT_BROWSER_PROFILE_SLUG &&
|
||||
!isNamedBrowserProfileSlug(slug)
|
||||
) {
|
||||
return [];
|
||||
}
|
||||
const includes = (profileSlug: string) => slug === undefined || profileSlug === slug;
|
||||
|
||||
const partitions = new Set<string>([
|
||||
getBrowserPartition({ kind: "local" }, slug ?? DEFAULT_BROWSER_PROFILE_SLUG),
|
||||
]);
|
||||
for (const name of directories) {
|
||||
if (isNamedProfileDirectory(name) || isLegacyDirectory(name)) {
|
||||
result.add(sessions.fromPartition(`persist:${name}`));
|
||||
const profileSlug = readDirectoryProfileSlug(name);
|
||||
if (
|
||||
profileSlug !== null
|
||||
? includes(profileSlug)
|
||||
: isLegacyDirectory(name) && includes(DEFAULT_BROWSER_PROFILE_SLUG)
|
||||
) {
|
||||
partitions.add(`persist:${name}`);
|
||||
}
|
||||
}
|
||||
for (const partition of options.hostPartitions ?? []) {
|
||||
if (isHostBrowserProxyPartition(partition)) {
|
||||
result.add(sessions.fromPartition(partition));
|
||||
const parsed = parseBrowserPartition(partition);
|
||||
if (parsed?.route === "host" && includes(parsed.profileSlug)) {
|
||||
partitions.add(partition);
|
||||
}
|
||||
}
|
||||
// A newly created profile's directory may not exist yet while its guest is live.
|
||||
for (const live of options.liveSessions ?? []) {
|
||||
result.add(live);
|
||||
|
||||
const result = new Set<S>([...partitions].map((partition) => sessions.fromPartition(partition)));
|
||||
if (slug === undefined) {
|
||||
// A newly created profile's directory may not exist yet while its guest is live.
|
||||
for (const live of options.liveSessions ?? []) {
|
||||
result.add(live);
|
||||
}
|
||||
}
|
||||
return [...result];
|
||||
}
|
||||
@@ -276,9 +243,9 @@ export function getLegacyPaseoBrowserProfileSession(
|
||||
: null;
|
||||
}
|
||||
|
||||
export function listPaseoBrowserProfileGuests(
|
||||
input: ListBrowserProfileGuestsInput,
|
||||
): BrowserProfileGuest[] {
|
||||
export function listPaseoBrowserProfileGuests<W extends BrowserProfileWebContents>(
|
||||
input: ListBrowserProfileGuestsInput<W>,
|
||||
): W[] {
|
||||
const allowedSessions = new Set<object>(input.profileSessions ?? []);
|
||||
if (input.profileSession) {
|
||||
allowedSessions.add(input.profileSession);
|
||||
|
||||
@@ -1,11 +1,6 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { BrowserWindow, ipcMain, session as electronSession, type WebContents } from "electron";
|
||||
import log from "electron-log/main";
|
||||
import {
|
||||
getHostBrowserProxyPartition,
|
||||
isHostBrowserProxyPartition,
|
||||
PASEO_BROWSER_HOST_PARTITION_PREFIX,
|
||||
} from "./partition.js";
|
||||
import {
|
||||
createBrowserProxyManager,
|
||||
type BrowserProxyManager,
|
||||
@@ -20,10 +15,7 @@ import {
|
||||
|
||||
export {
|
||||
createBrowserProxyManager,
|
||||
getHostBrowserProxyPartition,
|
||||
isHostBrowserProxyPartition,
|
||||
parseBrowserProxyTarget,
|
||||
PASEO_BROWSER_HOST_PARTITION_PREFIX,
|
||||
type BrowserProxyManager,
|
||||
type BrowserProxyStatus,
|
||||
type BrowserProxyStatusSnapshot,
|
||||
@@ -125,9 +117,13 @@ export function createElectronBrowserProxyController(deps: {
|
||||
if (!target) {
|
||||
throw new Error("Invalid browser proxy target");
|
||||
}
|
||||
if (rawInput.profileSlug !== undefined && typeof rawInput.profileSlug !== "string") {
|
||||
throw new Error("Invalid browser proxy profile");
|
||||
}
|
||||
return await manager.ensureHostProxy({
|
||||
serverId: rawInput.serverId,
|
||||
target,
|
||||
...(rawInput.profileSlug !== undefined ? { profileSlug: rawInput.profileSlug } : {}),
|
||||
forceReconnect: rawInput.forceReconnect === true,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,32 +0,0 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import {
|
||||
getHostBrowserProxyPartition,
|
||||
isHostBrowserProxyPartition,
|
||||
PASEO_BROWSER_HOST_PARTITION_PREFIX,
|
||||
} from "./partition.js";
|
||||
|
||||
describe("host browser proxy partition naming", () => {
|
||||
test("produces deterministic 16-hex-char persistent partitions per serverId", () => {
|
||||
const first = getHostBrowserProxyPartition("srv_alpha_123");
|
||||
const second = getHostBrowserProxyPartition("srv_alpha_123");
|
||||
const other = getHostBrowserProxyPartition("srv_beta_456");
|
||||
|
||||
expect(first).toBe(second);
|
||||
expect(first).not.toBe(other);
|
||||
expect(first.startsWith(PASEO_BROWSER_HOST_PARTITION_PREFIX)).toBe(true);
|
||||
expect(first).toMatch(/^persist:paseo-browser-host-[0-9a-f]{16}$/);
|
||||
expect(isHostBrowserProxyPartition(first)).toBe(true);
|
||||
expect(isHostBrowserProxyPartition(other)).toBe(true);
|
||||
});
|
||||
|
||||
test("validates only exact host proxy partition format", () => {
|
||||
expect(isHostBrowserProxyPartition("persist:paseo-browser-host-0123456789abcdef")).toBe(true);
|
||||
expect(isHostBrowserProxyPartition("persist:paseo-browser")).toBe(false);
|
||||
expect(isHostBrowserProxyPartition("persist:paseo-browser-host-0123456789abcde")).toBe(false);
|
||||
expect(isHostBrowserProxyPartition("persist:paseo-browser-host-0123456789abcdef0")).toBe(false);
|
||||
expect(isHostBrowserProxyPartition("persist:paseo-browser-host-0123456789ABCDEF")).toBe(false);
|
||||
expect(isHostBrowserProxyPartition("persist:paseo-browser-host-zzzzzzzzzzzzzzzz")).toBe(false);
|
||||
expect(isHostBrowserProxyPartition("persist:foreign")).toBe(false);
|
||||
expect(isHostBrowserProxyPartition(undefined)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,18 +0,0 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
export const PASEO_BROWSER_HOST_PARTITION_PREFIX = "persist:paseo-browser-host-";
|
||||
|
||||
const HOST_PARTITION_PATTERN = /^persist:paseo-browser-host-[0-9a-f]{16}$/;
|
||||
|
||||
export function getHostBrowserProxyPartition(serverId: string): string {
|
||||
const normalized = serverId.trim();
|
||||
if (!normalized) {
|
||||
throw new Error("Host serverId is required to derive a browser proxy partition");
|
||||
}
|
||||
const digest = createHash("sha256").update(normalized, "utf8").digest("hex").slice(0, 16);
|
||||
return `${PASEO_BROWSER_HOST_PARTITION_PREFIX}${digest}`;
|
||||
}
|
||||
|
||||
export function isHostBrowserProxyPartition(partition: string | undefined): partition is string {
|
||||
return typeof partition === "string" && HOST_PARTITION_PATTERN.test(partition);
|
||||
}
|
||||
@@ -6,7 +6,7 @@ import {
|
||||
type DecodedNetworkTunnelFrame,
|
||||
type NetworkTunnelFrame,
|
||||
} from "@getpaseo/protocol/network-tunnel";
|
||||
import { getHostBrowserProxyPartition } from "./partition.js";
|
||||
import { getBrowserPartition } from "../../browser-partition.js";
|
||||
import {
|
||||
createBrowserProxyManager,
|
||||
type BrowserProxyManager,
|
||||
@@ -204,10 +204,13 @@ describe("BrowserProxyManager", () => {
|
||||
|
||||
const target = "tcp://10.0.0.5:6767";
|
||||
const ready = await manager.ensureHostProxy({ serverId: "remote-1", target });
|
||||
const expectedPartition = getHostBrowserProxyPartition("remote-1");
|
||||
const expectedPartition = getBrowserPartition(
|
||||
{ kind: "host", serverId: "remote-1" },
|
||||
"default",
|
||||
);
|
||||
|
||||
expect(ready.status).toBe("ready");
|
||||
expect(ready.partition).toBe(expectedPartition);
|
||||
expect(ready.profilePartitions).toEqual({ default: expectedPartition });
|
||||
expect(ready.socksPort).toBeGreaterThan(0);
|
||||
expect(manager.isAllowedHostPartition(expectedPartition)).toBe(true);
|
||||
expect(manager.isProxiedSession(sessionsByPartition.get(expectedPartition)!)).toBe(true);
|
||||
@@ -304,7 +307,12 @@ describe("BrowserProxyManager", () => {
|
||||
expect(result.status).toBe("error");
|
||||
expect(result.socksPort).toBeNull();
|
||||
expect(result.error).toMatch(/resolveProxy|proxy/i);
|
||||
expect(manager.isAllowedHostPartition(result.partition)).toBe(false);
|
||||
expect(result.profilePartitions).toEqual({});
|
||||
expect(
|
||||
manager.isAllowedHostPartition(
|
||||
getBrowserPartition({ kind: "host", serverId: "remote-broken-proxy" }, "default"),
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
test("keeps socksPort null on initial tunnel failure, and preserves socksPort across later reconnect errors", async () => {
|
||||
@@ -335,7 +343,7 @@ describe("BrowserProxyManager", () => {
|
||||
const initialFail = await manager.ensureHostProxy({ serverId: "remote-flaky", target });
|
||||
expect(initialFail.status).toBe("error");
|
||||
expect(initialFail.socksPort).toBeNull();
|
||||
expect(manager.isAllowedHostPartition(initialFail.partition)).toBe(false);
|
||||
expect(initialFail.profilePartitions).toEqual({});
|
||||
|
||||
failTicket = false;
|
||||
const ready = await manager.ensureHostProxy({ serverId: "remote-flaky", target });
|
||||
@@ -362,4 +370,85 @@ describe("BrowserProxyManager", () => {
|
||||
expect(recovered.status).toBe("ready");
|
||||
expect(recovered.socksPort).toBe(ready.socksPort);
|
||||
});
|
||||
|
||||
test("binds every profile session on a host to the same SOCKS5 port and tunnel", async () => {
|
||||
const sessionsByPartition = new Map<string, ReturnType<typeof createFakeSession>>();
|
||||
const wires: Array<ReturnType<typeof createEchoTunnelWire>> = [];
|
||||
const statuses: BrowserProxyStatusSnapshot[] = [];
|
||||
const manager = createBrowserProxyManager({
|
||||
verifySocketOwner: async () => true,
|
||||
requestTicket: async () => "ticket",
|
||||
openTunnelWire: async () => {
|
||||
const created = createEchoTunnelWire();
|
||||
wires.push(created);
|
||||
return created.wire;
|
||||
},
|
||||
getSessionForPartition: (partition) => {
|
||||
let session = sessionsByPartition.get(partition);
|
||||
if (!session) {
|
||||
session = createFakeSession();
|
||||
sessionsByPartition.set(partition, session);
|
||||
}
|
||||
return session;
|
||||
},
|
||||
onStatusChange: (status) => statuses.push(status),
|
||||
});
|
||||
managers.push(manager);
|
||||
|
||||
const route = { kind: "host", serverId: "remote-profiles" } as const;
|
||||
const defaultPartition = getBrowserPartition(route, "default");
|
||||
const workPartition = getBrowserPartition(route, "work");
|
||||
const target = "tcp://10.0.0.20:6767";
|
||||
|
||||
const [first, second] = await Promise.all([
|
||||
manager.ensureHostProxy({ serverId: "remote-profiles", target }),
|
||||
manager.ensureHostProxy({ serverId: "remote-profiles", target, profileSlug: "work" }),
|
||||
]);
|
||||
|
||||
expect(first.socksPort).toBeGreaterThan(0);
|
||||
expect(second.socksPort).toBe(first.socksPort);
|
||||
expect(second.profilePartitions).toEqual({ default: defaultPartition, work: workPartition });
|
||||
expect(manager.getHostProxyStatus("remote-profiles")?.profilePartitions).toEqual({
|
||||
default: defaultPartition,
|
||||
work: workPartition,
|
||||
});
|
||||
expect(statuses.at(-1)?.profilePartitions).toEqual({
|
||||
default: defaultPartition,
|
||||
work: workPartition,
|
||||
});
|
||||
for (const partition of [defaultPartition, workPartition]) {
|
||||
const session = sessionsByPartition.get(partition)!;
|
||||
expect(session.lastProxyConfig?.proxyRules).toBe(`socks5://127.0.0.1:${first.socksPort}`);
|
||||
expect(manager.isAllowedHostPartition(partition)).toBe(true);
|
||||
expect(manager.isProxiedSession(session)).toBe(true);
|
||||
}
|
||||
expect(manager.listKnownPartitions().sort()).toEqual([defaultPartition, workPartition].sort());
|
||||
expect(wires).toHaveLength(1);
|
||||
|
||||
const reply = await socks5ConnectAndExchange(first.socksPort!, "localhost", 5173, "work");
|
||||
expect(reply).toBe("ECHO:work");
|
||||
expect(wires).toHaveLength(1);
|
||||
|
||||
await manager.releaseHostProxy("remote-profiles");
|
||||
expect(manager.isAllowedHostPartition(defaultPartition)).toBe(false);
|
||||
expect(manager.isAllowedHostPartition(workPartition)).toBe(false);
|
||||
});
|
||||
|
||||
test("refuses to bind an invalid profile slug", async () => {
|
||||
const manager = createBrowserProxyManager({
|
||||
verifySocketOwner: async () => true,
|
||||
requestTicket: async () => "ticket",
|
||||
openTunnelWire: async () => createEchoTunnelWire().wire,
|
||||
getSessionForPartition: () => createFakeSession(),
|
||||
});
|
||||
managers.push(manager);
|
||||
|
||||
await expect(
|
||||
manager.ensureHostProxy({
|
||||
serverId: "remote-invalid",
|
||||
target: "tcp://10.0.0.21:6767",
|
||||
profileSlug: "Not Valid",
|
||||
}),
|
||||
).rejects.toThrow(/profile/i);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
import net, { type AddressInfo, type Server, type Socket } from "node:net";
|
||||
import { getHostBrowserProxyPartition, isHostBrowserProxyPartition } from "./partition.js";
|
||||
import {
|
||||
DEFAULT_BROWSER_PROFILE_SLUG,
|
||||
getBrowserPartition,
|
||||
parseBrowserPartition,
|
||||
} from "../../browser-partition.js";
|
||||
import { createOsSocketOwnerVerifier, type SocketOwnerVerifier } from "./socket-owner.js";
|
||||
import {
|
||||
performSocks5Handshake,
|
||||
@@ -17,7 +21,8 @@ export type BrowserProxyStatus = "idle" | "connecting" | "ready" | "reconnecting
|
||||
|
||||
export interface BrowserProxyStatusSnapshot {
|
||||
serverId: string;
|
||||
partition: string;
|
||||
/** Profile slug -> partition, for every profile session bound and verified on this host. */
|
||||
profilePartitions: Record<string, string>;
|
||||
status: BrowserProxyStatus;
|
||||
error: string | null;
|
||||
socksPort: number | null;
|
||||
@@ -51,6 +56,8 @@ export interface BrowserProxyManagerDeps {
|
||||
export interface EnsureHostProxyInput {
|
||||
serverId: string;
|
||||
target: HostTransportSpec;
|
||||
/** The browser profile whose session to bind to the host proxy. Defaults to `default`. */
|
||||
profileSlug?: string;
|
||||
forceReconnect?: boolean;
|
||||
}
|
||||
|
||||
@@ -65,19 +72,23 @@ export interface BrowserProxyManager {
|
||||
disposeAll(): Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* One host route: one loopback SOCKS5 server and one tunnel. Every profile session
|
||||
* on the host points `setProxy` at the same SOCKS5 port.
|
||||
*/
|
||||
interface HostProxyEntry {
|
||||
readonly serverId: string;
|
||||
readonly partition: string;
|
||||
target: HostTransportSpec;
|
||||
status: BrowserProxyStatus;
|
||||
error: string | null;
|
||||
socksServer: Server | null;
|
||||
socksPort: number | null;
|
||||
session: BrowserProxySessionLike | null;
|
||||
sessionConfigured: boolean;
|
||||
/** Profile slug -> partition whose session is bound and verified. */
|
||||
boundPartitions: Map<string, string>;
|
||||
bindPromises: Map<string, Promise<void>>;
|
||||
mux: TunnelMuxClient | null;
|
||||
connectPromise: Promise<TunnelMuxClient> | null;
|
||||
ensurePromise: Promise<BrowserProxyStatusSnapshot> | null;
|
||||
routePromise: Promise<number> | null;
|
||||
activeSockets: Set<Socket>;
|
||||
disposed: boolean;
|
||||
}
|
||||
@@ -110,15 +121,19 @@ export function createBrowserProxyManager(deps: BrowserProxyManagerDeps): Browse
|
||||
function snapshotOf(entry: HostProxyEntry): BrowserProxyStatusSnapshot {
|
||||
return {
|
||||
serverId: entry.serverId,
|
||||
partition: entry.partition,
|
||||
profilePartitions: Object.fromEntries(entry.boundPartitions),
|
||||
status: entry.status,
|
||||
error: entry.error,
|
||||
// Only expose socksPort once Chromium's session proxy has been configured and
|
||||
// Only expose socksPort once a Chromium session proxy has been configured and
|
||||
// verified via resolveProxy so renderers never mount an unverified partition.
|
||||
socksPort: entry.sessionConfigured ? entry.socksPort : null,
|
||||
socksPort: hasBoundSession(entry) ? entry.socksPort : null,
|
||||
};
|
||||
}
|
||||
|
||||
function hasBoundSession(entry: HostProxyEntry): boolean {
|
||||
return entry.boundPartitions.size > 0;
|
||||
}
|
||||
|
||||
function setEntryStatus(
|
||||
entry: HostProxyEntry,
|
||||
status: BrowserProxyStatus,
|
||||
@@ -167,12 +182,44 @@ export function createBrowserProxyManager(deps: BrowserProxyManagerDeps): Browse
|
||||
return address.port;
|
||||
}
|
||||
|
||||
async function ensureSessionConfigured(entry: HostProxyEntry, socksPort: number): Promise<void> {
|
||||
if (entry.sessionConfigured && entry.session) {
|
||||
async function bindSession(
|
||||
entry: HostProxyEntry,
|
||||
profileSlug: string,
|
||||
partition: string,
|
||||
socksPort: number,
|
||||
): Promise<void> {
|
||||
if (entry.boundPartitions.has(profileSlug)) {
|
||||
return;
|
||||
}
|
||||
let bindTask = entry.bindPromises.get(profileSlug);
|
||||
if (!bindTask) {
|
||||
bindTask = (async () => {
|
||||
const session = await configureSession(partition, socksPort);
|
||||
if (entry.disposed) {
|
||||
throw new Error("Host browser proxy was disposed");
|
||||
}
|
||||
entry.boundPartitions.set(profileSlug, partition);
|
||||
allowedPartitions.add(partition);
|
||||
proxiedSessions.add(session);
|
||||
deps.onStatusChange?.(snapshotOf(entry));
|
||||
})();
|
||||
entry.bindPromises.set(profileSlug, bindTask);
|
||||
const settled = () => {
|
||||
if (entry.bindPromises.get(profileSlug) === bindTask) {
|
||||
entry.bindPromises.delete(profileSlug);
|
||||
}
|
||||
};
|
||||
bindTask.then(settled, settled);
|
||||
}
|
||||
await bindTask;
|
||||
}
|
||||
|
||||
const hostSession = deps.getSessionForPartition(entry.partition);
|
||||
async function configureSession(
|
||||
partition: string,
|
||||
socksPort: number,
|
||||
): Promise<BrowserProxySessionLike> {
|
||||
knownPartitions.add(partition);
|
||||
const hostSession = deps.getSessionForPartition(partition);
|
||||
await hostSession.setProxy({
|
||||
mode: "fixed_servers",
|
||||
proxyRules: `socks5://127.0.0.1:${socksPort}`,
|
||||
@@ -194,12 +241,26 @@ export function createBrowserProxyManager(deps: BrowserProxyManagerDeps): Browse
|
||||
`Session resolveProxy verification failed (localhost="${resolvedLocalhost}", 127.0.0.1="${resolvedLoopbackIp}")`,
|
||||
);
|
||||
}
|
||||
return hostSession;
|
||||
}
|
||||
|
||||
entry.session = hostSession;
|
||||
entry.sessionConfigured = true;
|
||||
allowedPartitions.add(entry.partition);
|
||||
knownPartitions.add(entry.partition);
|
||||
proxiedSessions.add(hostSession);
|
||||
/** The host route: its fixed SOCKS5 port and a connected tunnel, shared by every profile. */
|
||||
async function ensureRoute(entry: HostProxyEntry): Promise<number> {
|
||||
if (!entry.routePromise) {
|
||||
const routeTask = (async () => {
|
||||
const socksPort = await ensureSocksServer(entry);
|
||||
await ensureTunnelConnected(entry);
|
||||
return socksPort;
|
||||
})();
|
||||
entry.routePromise = routeTask;
|
||||
const settled = () => {
|
||||
if (entry.routePromise === routeTask) {
|
||||
entry.routePromise = null;
|
||||
}
|
||||
};
|
||||
routeTask.then(settled, settled);
|
||||
}
|
||||
return await entry.routePromise;
|
||||
}
|
||||
|
||||
async function ensureTunnelConnected(entry: HostProxyEntry): Promise<TunnelMuxClient> {
|
||||
@@ -214,7 +275,7 @@ export function createBrowserProxyManager(deps: BrowserProxyManagerDeps): Browse
|
||||
}
|
||||
|
||||
const nextStatus: BrowserProxyStatus =
|
||||
entry.sessionConfigured || entry.status === "ready" || entry.status === "reconnecting"
|
||||
hasBoundSession(entry) || entry.status === "ready" || entry.status === "reconnecting"
|
||||
? "reconnecting"
|
||||
: "connecting";
|
||||
setEntryStatus(entry, nextStatus, null);
|
||||
@@ -238,13 +299,13 @@ export function createBrowserProxyManager(deps: BrowserProxyManagerDeps): Browse
|
||||
mux.onClose(() => {
|
||||
if (entry.mux === mux) {
|
||||
entry.mux = null;
|
||||
if (!entry.disposed && entry.sessionConfigured) {
|
||||
if (!entry.disposed && hasBoundSession(entry)) {
|
||||
setEntryStatus(entry, "reconnecting", null);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (entry.sessionConfigured) {
|
||||
if (hasBoundSession(entry)) {
|
||||
setEntryStatus(entry, "ready", null);
|
||||
}
|
||||
return mux;
|
||||
@@ -358,21 +419,18 @@ export function createBrowserProxyManager(deps: BrowserProxyManagerDeps): Browse
|
||||
return existing;
|
||||
}
|
||||
|
||||
const partition = getHostBrowserProxyPartition(serverId);
|
||||
knownPartitions.add(partition);
|
||||
const entry: HostProxyEntry = {
|
||||
serverId,
|
||||
partition,
|
||||
target,
|
||||
status: "idle",
|
||||
error: null,
|
||||
socksServer: null,
|
||||
socksPort: null,
|
||||
session: null,
|
||||
sessionConfigured: false,
|
||||
boundPartitions: new Map(),
|
||||
bindPromises: new Map(),
|
||||
mux: null,
|
||||
connectPromise: null,
|
||||
ensurePromise: null,
|
||||
routePromise: null,
|
||||
activeSockets: new Set(),
|
||||
disposed: false,
|
||||
};
|
||||
@@ -385,6 +443,8 @@ export function createBrowserProxyManager(deps: BrowserProxyManagerDeps): Browse
|
||||
if (!serverId) {
|
||||
throw new Error("Host serverId is required");
|
||||
}
|
||||
const profileSlug = input.profileSlug ?? DEFAULT_BROWSER_PROFILE_SLUG;
|
||||
const partition = getBrowserPartition({ kind: "host", serverId }, profileSlug);
|
||||
|
||||
const entry = getOrCreateEntry(serverId, input.target);
|
||||
if (input.forceReconnect && entry.mux) {
|
||||
@@ -392,37 +452,19 @@ export function createBrowserProxyManager(deps: BrowserProxyManagerDeps): Browse
|
||||
entry.mux = null;
|
||||
}
|
||||
|
||||
if (entry.ensurePromise) {
|
||||
return await entry.ensurePromise;
|
||||
}
|
||||
|
||||
const ensureTask = (async (): Promise<BrowserProxyStatusSnapshot> => {
|
||||
try {
|
||||
if (entry.status !== "ready") {
|
||||
setEntryStatus(entry, entry.sessionConfigured ? "reconnecting" : "connecting", null);
|
||||
}
|
||||
const socksPort = await ensureSocksServer(entry);
|
||||
await ensureTunnelConnected(entry);
|
||||
await ensureSessionConfigured(entry, socksPort);
|
||||
setEntryStatus(entry, "ready", null);
|
||||
return snapshotOf(entry);
|
||||
} catch (error) {
|
||||
const message = formatError(error);
|
||||
if (!entry.disposed) {
|
||||
setEntryStatus(entry, "error", message);
|
||||
}
|
||||
return snapshotOf(entry);
|
||||
}
|
||||
})();
|
||||
|
||||
entry.ensurePromise = ensureTask;
|
||||
try {
|
||||
return await ensureTask;
|
||||
} finally {
|
||||
if (entry.ensurePromise === ensureTask) {
|
||||
entry.ensurePromise = null;
|
||||
if (entry.status !== "ready") {
|
||||
setEntryStatus(entry, hasBoundSession(entry) ? "reconnecting" : "connecting", null);
|
||||
}
|
||||
const socksPort = await ensureRoute(entry);
|
||||
await bindSession(entry, profileSlug, partition, socksPort);
|
||||
setEntryStatus(entry, "ready", null);
|
||||
} catch (error) {
|
||||
if (!entry.disposed) {
|
||||
setEntryStatus(entry, "error", formatError(error));
|
||||
}
|
||||
}
|
||||
return snapshotOf(entry);
|
||||
}
|
||||
|
||||
function updateHostProxyTarget(input: { serverId: string; target: HostTransportSpec }): void {
|
||||
@@ -432,7 +474,7 @@ export function createBrowserProxyManager(deps: BrowserProxyManagerDeps): Browse
|
||||
entry.target = input.target;
|
||||
entry.mux?.close();
|
||||
entry.mux = null;
|
||||
if (entry.sessionConfigured) {
|
||||
if (hasBoundSession(entry)) {
|
||||
setEntryStatus(entry, "reconnecting", null);
|
||||
}
|
||||
}
|
||||
@@ -444,7 +486,7 @@ export function createBrowserProxyManager(deps: BrowserProxyManagerDeps): Browse
|
||||
}
|
||||
|
||||
function isAllowedHostPartition(partition: string): boolean {
|
||||
return isHostBrowserProxyPartition(partition) && allowedPartitions.has(partition);
|
||||
return parseBrowserPartition(partition)?.route === "host" && allowedPartitions.has(partition);
|
||||
}
|
||||
|
||||
function isProxiedSession(session: object): boolean {
|
||||
@@ -459,7 +501,9 @@ export function createBrowserProxyManager(deps: BrowserProxyManagerDeps): Browse
|
||||
if (entry.disposed) return;
|
||||
entry.disposed = true;
|
||||
entriesByServerId.delete(entry.serverId);
|
||||
allowedPartitions.delete(entry.partition);
|
||||
for (const partition of entry.boundPartitions.values()) {
|
||||
allowedPartitions.delete(partition);
|
||||
}
|
||||
|
||||
entry.mux?.close();
|
||||
entry.mux = null;
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
export {
|
||||
getHostBrowserProxyPartition,
|
||||
isHostBrowserProxyPartition,
|
||||
PASEO_BROWSER_HOST_PARTITION_PREFIX,
|
||||
} from "./internal/partition.js";
|
||||
@@ -1,6 +1,5 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { PASEO_BROWSER_PROFILE_PARTITION } from "../browser-profile.js";
|
||||
import { getHostBrowserProxyPartition } from "../browser-proxy/partition.js";
|
||||
import { getBrowserPartition, PASEO_BROWSER_PROFILE_PARTITION } from "../browser-partition.js";
|
||||
import {
|
||||
getPaseoBrowserIdForWebContents,
|
||||
getPaseoBrowserWorkspaceId,
|
||||
@@ -11,6 +10,10 @@ import {
|
||||
unregisterPaseoBrowserFromHost,
|
||||
} from "./index.js";
|
||||
|
||||
function hostPartitionFor(serverId: string, profileSlug = "default"): string {
|
||||
return getBrowserPartition({ kind: "host", serverId }, profileSlug);
|
||||
}
|
||||
|
||||
class FakeRenderer {
|
||||
public constructor(public readonly id: number) {}
|
||||
|
||||
@@ -46,8 +49,8 @@ class FakeBrowserGuest {
|
||||
|
||||
describe("browser webview attachment", () => {
|
||||
test("accepts only allowed URLs on the shared profile or registered host proxy partitions", () => {
|
||||
const hostPartition = getHostBrowserProxyPartition("remote-host-a");
|
||||
const unregisteredHostPartition = getHostBrowserProxyPartition("remote-host-b");
|
||||
const hostPartition = hostPartitionFor("remote-host-a");
|
||||
const unregisteredHostPartition = hostPartitionFor("remote-host-b");
|
||||
const isAllowedHostPartition = (partition: string) => partition === hostPartition;
|
||||
|
||||
expect(
|
||||
@@ -88,7 +91,7 @@ describe("browser webview attachment", () => {
|
||||
});
|
||||
|
||||
test("registers a guest attached to an allowed host proxy session", () => {
|
||||
const hostPartition = getHostBrowserProxyPartition("remote-host-a");
|
||||
const hostPartition = hostPartitionFor("remote-host-a");
|
||||
const proxiedSession = {};
|
||||
const renderer = new FakeRenderer(9);
|
||||
const guest = new FakeBrowserGuest(901, renderer, proxiedSession);
|
||||
@@ -109,6 +112,53 @@ describe("browser webview attachment", () => {
|
||||
unregisterPaseoBrowser("browser-proxied");
|
||||
});
|
||||
|
||||
test("admits a host-proxied named profile only once its session is bound to the host proxy", () => {
|
||||
const boundWork = hostPartitionFor("remote-host-a", "work");
|
||||
const unboundWork = hostPartitionFor("remote-host-b", "work");
|
||||
const isAllowedHostPartition = (partition: string) => partition === boundWork;
|
||||
|
||||
expect(
|
||||
isPaseoBrowserWebviewAttach({
|
||||
src: "http://localhost:3000",
|
||||
partition: boundWork,
|
||||
isAllowedHostPartition,
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(
|
||||
isPaseoBrowserWebviewAttach({
|
||||
src: "http://localhost:3000",
|
||||
partition: unboundWork,
|
||||
isAllowedHostPartition,
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(
|
||||
isPaseoBrowserWebviewAttach({ src: "http://localhost:3000", partition: boundWork }),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
test("registers a guest on a host-proxied named profile only when its session is proxied", () => {
|
||||
const workPartition = hostPartitionFor("remote-host-a", "work");
|
||||
const proxiedSession = {};
|
||||
const renderer = new FakeRenderer(10);
|
||||
const guest = new FakeBrowserGuest(1001, renderer, proxiedSession);
|
||||
const register = (isAllowedHostSession: (session: object) => boolean) =>
|
||||
registerAttachedPaseoBrowser({
|
||||
browserId: "browser-proxied-work",
|
||||
workspaceId: "workspace-remote",
|
||||
webContentsId: guest.id,
|
||||
sender: renderer,
|
||||
partition: workPartition,
|
||||
sessionFromPartition: (partition) => (partition === workPartition ? proxiedSession : {}),
|
||||
isAllowedHostSession,
|
||||
findWebContents: () => guest,
|
||||
});
|
||||
|
||||
expect(register(() => false)).toBe(false);
|
||||
expect(register((session) => session === proxiedSession)).toBe(true);
|
||||
expect(getPaseoBrowserIdForWebContents(guest)).toBe("browser-proxied-work");
|
||||
unregisterPaseoBrowser("browser-proxied-work");
|
||||
});
|
||||
|
||||
test("admits only complete lowercase named profile partitions on allowed URLs", () => {
|
||||
const valid = "persist:paseo-profile-work";
|
||||
for (const partition of [valid, `persist:paseo-profile-${"a".repeat(48)}`]) {
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { webContents as allWebContents, type WebContents } from "electron";
|
||||
import { isPaseoBrowserProfilePartition } from "../browser-profile.js";
|
||||
import { isHostBrowserProxyPartition } from "../browser-proxy/partition.js";
|
||||
import { parseBrowserPartition } from "../browser-partition.js";
|
||||
import {
|
||||
BROWSER_NEW_TAB_REQUEST_EVENT,
|
||||
buildBrowserPopupWebPreferences,
|
||||
@@ -52,13 +51,12 @@ export function isPaseoBrowserWebviewAttach(input: {
|
||||
if (!isAllowedBrowserWebviewUrl(input.src)) {
|
||||
return false;
|
||||
}
|
||||
if (isPaseoBrowserProfilePartition(input.partition)) {
|
||||
return true;
|
||||
const parsed = parseBrowserPartition(input.partition);
|
||||
if (!parsed || !input.partition) {
|
||||
return false;
|
||||
}
|
||||
return (
|
||||
isHostBrowserProxyPartition(input.partition) &&
|
||||
(input.isAllowedHostPartition?.(input.partition) ?? false)
|
||||
);
|
||||
// A host-routed partition attaches only once main bound its session to the host proxy.
|
||||
return parsed.route === "local" || (input.isAllowedHostPartition?.(input.partition) ?? false);
|
||||
}
|
||||
|
||||
export function listRegisteredPaseoBrowserIds(): string[] {
|
||||
@@ -83,14 +81,11 @@ export function registerAttachedPaseoBrowser(input: RegisterAttachedBrowserInput
|
||||
if (!guest || guest.isDestroyed() || guest.hostWebContents !== input.sender) {
|
||||
return false;
|
||||
}
|
||||
const sessionMatchesProfile =
|
||||
isPaseoBrowserProfilePartition(input.partition) &&
|
||||
guest.session === input.sessionFromPartition(input.partition);
|
||||
const sessionMatchesHostProxy =
|
||||
isHostBrowserProxyPartition(input.partition) &&
|
||||
guest.session === input.sessionFromPartition(input.partition) &&
|
||||
(input.isAllowedHostSession?.(guest.session) ?? false);
|
||||
if (!sessionMatchesProfile && !sessionMatchesHostProxy) {
|
||||
const parsed = parseBrowserPartition(input.partition);
|
||||
if (!parsed || guest.session !== input.sessionFromPartition(input.partition)) {
|
||||
return false;
|
||||
}
|
||||
if (parsed.route === "host" && !(input.isAllowedHostSession?.(guest.session) ?? false)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
@@ -79,16 +79,13 @@ import {
|
||||
setWorkspaceActivePaseoBrowserId,
|
||||
unregisterPaseoBrowserHost,
|
||||
} from "./features/browser-webviews/index.js";
|
||||
import { isNamedBrowserProfileSlug, parseBrowserPartition } from "./features/browser-partition.js";
|
||||
import {
|
||||
clearPaseoBrowserProfile,
|
||||
deleteBrowserProfilePartitionDirectory,
|
||||
getBrowserProfilePartition,
|
||||
deleteBrowserProfilePartitionDirectories,
|
||||
getLegacyPaseoBrowserProfileSession,
|
||||
getPaseoBrowserProfileSessions,
|
||||
isNamedBrowserProfileSlug,
|
||||
isPaseoBrowserProfilePartition,
|
||||
listBrowserPartitionDirectories,
|
||||
listDiskHostBrowserProxyPartitions,
|
||||
listPaseoBrowserProfileGuests,
|
||||
pruneOrphanedBrowserProfilePartitions,
|
||||
readHostBrowserProxyPartitions,
|
||||
@@ -97,7 +94,6 @@ import {
|
||||
import {
|
||||
applyProxiedWebContentsPolicy,
|
||||
createElectronBrowserProxyController,
|
||||
isHostBrowserProxyPartition,
|
||||
} from "./features/browser-proxy/index.js";
|
||||
import { parseOpenProjectPathFromArgv } from "./open-project-routing.js";
|
||||
import {
|
||||
@@ -172,10 +168,7 @@ function readAttachedBrowserInput(input: unknown): AttachedBrowserInput | null {
|
||||
}
|
||||
const record = input as Record<string, unknown>;
|
||||
const partition = record.partition;
|
||||
if (
|
||||
typeof partition !== "string" ||
|
||||
(!isPaseoBrowserProfilePartition(partition) && !isHostBrowserProxyPartition(partition))
|
||||
) {
|
||||
if (typeof partition !== "string" || parseBrowserPartition(partition) === null) {
|
||||
return null;
|
||||
}
|
||||
if (typeof record.browserId !== "string" || record.browserId.trim().length === 0) {
|
||||
@@ -436,16 +429,17 @@ ipcMain.handle("paseo:browser:remove-profile", async (_event, input: unknown) =>
|
||||
if (!removed.ok) {
|
||||
return removed;
|
||||
}
|
||||
const partition = getBrowserProfilePartition(slug);
|
||||
const profileSession = session.fromPartition(partition);
|
||||
const openGuests = webContents
|
||||
.getAllWebContents()
|
||||
.filter(
|
||||
(contents) =>
|
||||
!contents.isDestroyed() &&
|
||||
(contents.getType() === "webview" || contents.getType() === "window") &&
|
||||
contents.session === profileSession,
|
||||
);
|
||||
const userData = app.getPath("userData");
|
||||
// The profile's sessions on the local route and on every host route.
|
||||
const profileSessions = getPaseoBrowserProfileSessions(
|
||||
session,
|
||||
await listBrowserPartitionDirectories(userData),
|
||||
{ slug, hostPartitions: browserProxy.manager.listKnownPartitions() },
|
||||
);
|
||||
const openGuests = listPaseoBrowserProfileGuests({
|
||||
profileSessions,
|
||||
webContents: webContents.getAllWebContents(),
|
||||
});
|
||||
for (const guest of openGuests) {
|
||||
getPaseoBrowserWebviewRegistry().unregisterWebContents(guest.id);
|
||||
try {
|
||||
@@ -460,11 +454,13 @@ ipcMain.handle("paseo:browser:remove-profile", async (_event, input: unknown) =>
|
||||
}
|
||||
try {
|
||||
await clearPaseoBrowserProfile({
|
||||
profileSessions: [profileSession],
|
||||
profileSessions,
|
||||
listGuests: () => [],
|
||||
logReloadError: () => {},
|
||||
});
|
||||
profileSession.flushStorageData();
|
||||
for (const profileSession of profileSessions) {
|
||||
profileSession.flushStorageData();
|
||||
}
|
||||
} catch (error) {
|
||||
log.warn("[browser-profile] failed to clear session before deleting partition", {
|
||||
slug,
|
||||
@@ -472,7 +468,7 @@ ipcMain.handle("paseo:browser:remove-profile", async (_event, input: unknown) =>
|
||||
});
|
||||
}
|
||||
try {
|
||||
await deleteBrowserProfilePartitionDirectory(app.getPath("userData"), slug);
|
||||
await deleteBrowserProfilePartitionDirectories(userData, slug);
|
||||
} catch (error) {
|
||||
log.warn("[browser-profile] failed to delete profile partition directory", {
|
||||
slug,
|
||||
@@ -619,10 +615,10 @@ ipcMain.handle("paseo:browser:clear-profile", async (_event, rawInput?: unknown)
|
||||
(browserId) => `paseo-browser-${browserId}`,
|
||||
);
|
||||
const allDirectories = [...new Set([...directories, ...legacyDirectories])];
|
||||
// Host partitions on disk arrive through `directories`.
|
||||
const hostPartitions = [
|
||||
...browserProxy.manager.listKnownPartitions(),
|
||||
...readHostBrowserProxyPartitions(options?.hostServerIds),
|
||||
...listDiskHostBrowserProxyPartitions(app.getPath("userData")),
|
||||
];
|
||||
const liveSessions = webContents
|
||||
.getAllWebContents()
|
||||
|
||||
@@ -3,7 +3,7 @@ import { dirname, join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import ts from "typescript";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { PASEO_BROWSER_PROFILE_PARTITION } from "./features/browser-profile.js";
|
||||
import { PASEO_BROWSER_PROFILE_PARTITION } from "./features/browser-partition.js";
|
||||
|
||||
// The preload runs inside Electron's sandbox and is tsc-compiled (not bundled), so at
|
||||
// runtime it may only load Electron's sandbox allowlist. Any other module (local or
|
||||
|
||||
@@ -150,6 +150,7 @@ contextBridge.exposeInMainWorld("paseoDesktop", {
|
||||
ensureHostProxy: (input: {
|
||||
serverId: string;
|
||||
target: HostTransportSpec;
|
||||
profileSlug?: string;
|
||||
forceReconnect?: boolean;
|
||||
}) =>
|
||||
ipcRenderer.invoke(
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/expo-two-way-audio",
|
||||
"version": "0.18.2",
|
||||
"version": "0.19.0-beta.1",
|
||||
"description": "Native module for two way audio streaming",
|
||||
"keywords": [
|
||||
"ExpoTwoWayAudio",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/highlight",
|
||||
"version": "0.18.2",
|
||||
"version": "0.19.0-beta.1",
|
||||
"license": "Apache-2.0",
|
||||
"files": [
|
||||
"dist",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/plugin",
|
||||
"version": "0.18.2",
|
||||
"version": "0.19.0-beta.1",
|
||||
"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.2",
|
||||
"@getpaseo/protocol": "0.18.2",
|
||||
"@getpaseo/client": "0.19.0-beta.1",
|
||||
"@getpaseo/protocol": "0.19.0-beta.1",
|
||||
"@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.2",
|
||||
"@getpaseo/protocol": "0.18.2",
|
||||
"@getpaseo/client": "0.19.0-beta.1",
|
||||
"@getpaseo/protocol": "0.19.0-beta.1",
|
||||
"react": ">=19.1.0 <20",
|
||||
"react-native": ">=0.81.5",
|
||||
"zod": "^4.4.3"
|
||||
|
||||
@@ -552,9 +552,28 @@ describe("lifecycle hook SDK types", () => {
|
||||
const path: string = worktree.path;
|
||||
const branch: string = worktree.branch;
|
||||
const source: string = worktree.sourceCheckout;
|
||||
const untrusted: boolean = worktree.untrusted;
|
||||
void path;
|
||||
void branch;
|
||||
void source;
|
||||
void untrusted;
|
||||
// @ts-expect-error Trust status is read-only.
|
||||
worktree.untrusted = false;
|
||||
// @ts-expect-error Worktree facts have no workspace identity.
|
||||
worktree.workspaceId;
|
||||
});
|
||||
server.addHook("workspace.create.after", async ({ workspace }) => {
|
||||
const untrusted: boolean = workspace.untrusted;
|
||||
void untrusted;
|
||||
// @ts-expect-error Trust status is read-only.
|
||||
workspace.untrusted = false;
|
||||
});
|
||||
server.addHook("workspace.archive.after", async ({ workspace }) => {
|
||||
const untrusted: boolean = workspace.untrusted;
|
||||
void untrusted;
|
||||
// @ts-expect-error Trust status is read-only.
|
||||
workspace.untrusted = false;
|
||||
});
|
||||
server.addHook("workspace.create.before", async ({ request }) => ({ ...request, title: "Changed" }));
|
||||
server.addHook("workspace.create.before", async () => {});
|
||||
server.addHook("agent.open.before", async () => {});
|
||||
@@ -990,3 +1009,50 @@ describe("tunnel provider SDK boundary", () => {
|
||||
).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("provider icon SDK boundary", () => {
|
||||
it("exposes ProviderIcon and PluginProviderIconProps from client UI and client types", () => {
|
||||
expect(
|
||||
typeErrors(`
|
||||
import type {
|
||||
PluginClientContext,
|
||||
PluginProviderIconProps,
|
||||
PluginSurfaceProps,
|
||||
} from "@getpaseo/plugin/client";
|
||||
import {
|
||||
Icon,
|
||||
ProviderIcon,
|
||||
type PluginProviderIconProps as UiProviderIconProps,
|
||||
} from "@getpaseo/plugin/client/ui";
|
||||
|
||||
function Surface({ host, theme }: PluginSurfaceProps) {
|
||||
const explicit: PluginProviderIconProps = {
|
||||
provider: "codex",
|
||||
hostId: host.id,
|
||||
size: 18,
|
||||
color: theme.colors.foreground,
|
||||
};
|
||||
const implicit: UiProviderIconProps = {
|
||||
provider: "claude",
|
||||
};
|
||||
return (
|
||||
<>
|
||||
<Icon name="Settings" size={18} color={theme.colors.foreground} />
|
||||
<ProviderIcon {...explicit} />
|
||||
<ProviderIcon {...implicit} />
|
||||
{/* @ts-expect-error provider is required */}
|
||||
<ProviderIcon hostId={host.id} />
|
||||
{/* @ts-expect-error hostId must be a string when passed */}
|
||||
<ProviderIcon provider="codex" hostId={123} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default function contribute(client: PluginClientContext) {
|
||||
client.addScreen({ id: "main", title: "Main", Component: Surface });
|
||||
return () => {};
|
||||
}
|
||||
`),
|
||||
).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -159,6 +159,14 @@ export type PluginIcon<Props extends PluginIconProps = PluginIconProps> =
|
||||
| PluginSerializableIcon
|
||||
| ComponentType<Props>;
|
||||
|
||||
export interface PluginProviderIconProps {
|
||||
provider: string;
|
||||
/** Target host ID. Defaults to the current plugin installation's host. */
|
||||
hostId?: string;
|
||||
size?: number;
|
||||
color?: string;
|
||||
}
|
||||
|
||||
export type PluginPanelLocation = "workspace" | "explorer";
|
||||
|
||||
export interface PluginOpenPanelOptions {
|
||||
|
||||
@@ -22,6 +22,7 @@ export type {
|
||||
PluginWorkspaceRowBadgeItemProps,
|
||||
PluginWorkspaceRowBadgeItemContribution,
|
||||
PluginIcon,
|
||||
PluginProviderIconProps,
|
||||
PluginPanelLocation,
|
||||
PluginOpenPanelOptions,
|
||||
PluginWorkspacePanelProps,
|
||||
|
||||
@@ -19,7 +19,7 @@ import type {
|
||||
TextProps,
|
||||
} from "react-native";
|
||||
import type { PluginIconProps } from "../icons.js";
|
||||
import type { PluginIcon } from "./contracts.js";
|
||||
import type { PluginIcon, PluginProviderIconProps } from "./contracts.js";
|
||||
|
||||
export interface ModalProps {
|
||||
title: string;
|
||||
@@ -60,6 +60,8 @@ export type IconProps = Partial<PluginIconProps> &
|
||||
({ name: string; icon?: never } | { icon: PluginIcon; name?: never });
|
||||
|
||||
export declare const Icon: ComponentType<IconProps>;
|
||||
/** Renders Paseo's icon for a built-in, catalog, or plugin-provided agent provider. */
|
||||
export declare const ProviderIcon: ComponentType<PluginProviderIconProps>;
|
||||
export declare const Modal: ModalComponent;
|
||||
export declare function useToast(): ToastApi;
|
||||
export interface StreamedTextProps extends Omit<TextProps, "children"> {
|
||||
@@ -70,6 +72,7 @@ export interface StreamedTextProps extends Omit<TextProps, "children"> {
|
||||
export declare const StreamedText: ComponentType<StreamedTextProps>;
|
||||
|
||||
export type { PluginIconProps } from "../icons.js";
|
||||
export type { PluginProviderIconProps } from "./contracts.js";
|
||||
|
||||
/** React Native scrolling with the host's sheet gestures when rendered inside a sheet. */
|
||||
export declare const ScrollView: ForwardRefExoticComponent<
|
||||
|
||||
@@ -19,6 +19,8 @@ export interface PluginHookWorkspace {
|
||||
cwd: string;
|
||||
name: string | null;
|
||||
archivedAt: string | null;
|
||||
/** True when the workspace comes from an untrusted source such as a fork change request. */
|
||||
readonly untrusted: boolean;
|
||||
/** Data plugins stored on the workspace. Paseo never reads a key. */
|
||||
metadata: Record<string, JsonValue>;
|
||||
}
|
||||
@@ -27,6 +29,8 @@ export interface PluginHookWorktree {
|
||||
path: string;
|
||||
branch: string;
|
||||
sourceCheckout: string;
|
||||
/** True when the worktree comes from an untrusted source such as a fork change request. */
|
||||
readonly untrusted: boolean;
|
||||
}
|
||||
|
||||
/** Resolved creation options before Git fetches refs or chooses a unique branch name. */
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/protocol",
|
||||
"version": "0.18.2",
|
||||
"version": "0.19.0-beta.1",
|
||||
"description": "Paseo shared protocol schemas and wire types",
|
||||
"license": "Apache-2.0",
|
||||
"files": [
|
||||
|
||||
@@ -84,7 +84,9 @@ export function parseGitRemoteLocation(remoteUrl: string): GitRemoteLocation | n
|
||||
return null;
|
||||
}
|
||||
const normalizedPath = normalizeRemotePath(path);
|
||||
if (!isValidRemoteHost(host) || !normalizedPath) return null;
|
||||
// URL already validates bracketed IPv6 literals. Keep the brackets for URL builders.
|
||||
const validHost = host.startsWith("[") || isValidRemoteHost(host);
|
||||
if (!validHost || !normalizedPath) return null;
|
||||
|
||||
const protocol = parsed.protocol.toLowerCase();
|
||||
const port =
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "react-native-enriched-markdown",
|
||||
"version": "0.18.2",
|
||||
"version": "0.19.0-beta.1",
|
||||
"private": true,
|
||||
"description": "Markdown-based Rich Text solution for React Native",
|
||||
"main": "./lib/module/index",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/relay",
|
||||
"version": "0.18.2",
|
||||
"version": "0.19.0-beta.1",
|
||||
"description": "Paseo relay for bridging daemon and client connections",
|
||||
"license": "Apache-2.0",
|
||||
"files": [
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/server",
|
||||
"version": "0.18.2",
|
||||
"version": "0.19.0-beta.1",
|
||||
"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.2",
|
||||
"@getpaseo/highlight": "0.18.2",
|
||||
"@getpaseo/plugin": "0.18.2",
|
||||
"@getpaseo/protocol": "0.18.2",
|
||||
"@getpaseo/relay": "0.18.2",
|
||||
"@getpaseo/client": "0.19.0-beta.1",
|
||||
"@getpaseo/highlight": "0.19.0-beta.1",
|
||||
"@getpaseo/plugin": "0.19.0-beta.1",
|
||||
"@getpaseo/protocol": "0.19.0-beta.1",
|
||||
"@getpaseo/relay": "0.19.0-beta.1",
|
||||
"@isaacs/ttlcache": "^2.1.4",
|
||||
"@modelcontextprotocol/node": "2.1.2",
|
||||
"@modelcontextprotocol/sdk": "1.29.0",
|
||||
|
||||
@@ -1208,28 +1208,39 @@ function createRecipient(
|
||||
async person(
|
||||
prompt: string,
|
||||
messageId: string,
|
||||
outcome: { fail?: Error; started?: Promise<void> } = {},
|
||||
outcome: { fail?: Error; started?: Promise<void>; sessionMode?: string } = {},
|
||||
) {
|
||||
const prompts: AgentPromptInput[] = [];
|
||||
const modes: Array<string | undefined> = [];
|
||||
const result = await delivery
|
||||
.sendDirect({ recipientId: "recipient", prompt, messageId }, async (joined) => {
|
||||
prompts.push(joined.prompt);
|
||||
if (outcome.fail) throw outcome.fail;
|
||||
const joinedIds =
|
||||
typeof joined.prompt === "string"
|
||||
? parseAgentMessages(joined.prompt)?.map((message) => message.id)
|
||||
: undefined;
|
||||
received.push(...(joinedIds ?? [messageId]));
|
||||
running = true;
|
||||
return {
|
||||
disposition: "turn_started" as const,
|
||||
started: outcome.started ?? Promise.resolve(),
|
||||
};
|
||||
})
|
||||
.sendDirect(
|
||||
{
|
||||
recipientId: "recipient",
|
||||
prompt,
|
||||
messageId,
|
||||
sessionMode: outcome.sessionMode,
|
||||
},
|
||||
async (joined) => {
|
||||
prompts.push(joined.prompt);
|
||||
modes.push(joined.sessionMode);
|
||||
if (outcome.fail) throw outcome.fail;
|
||||
const joinedIds =
|
||||
typeof joined.prompt === "string"
|
||||
? parseAgentMessages(joined.prompt)?.map((message) => message.id)
|
||||
: undefined;
|
||||
received.push(...(joinedIds ?? [messageId]));
|
||||
running = true;
|
||||
return {
|
||||
disposition: "turn_started" as const,
|
||||
started: outcome.started ?? Promise.resolve(),
|
||||
};
|
||||
},
|
||||
)
|
||||
.catch((error: unknown) => error);
|
||||
const [sentPrompt] = prompts;
|
||||
return {
|
||||
prompt: sentPrompt,
|
||||
sessionMode: modes[0],
|
||||
result,
|
||||
ids:
|
||||
typeof sentPrompt === "string"
|
||||
@@ -2425,3 +2436,824 @@ test("an agent's steer behind a queued switch does not cut the running turn to s
|
||||
expect(recipient.sent.map(({ ids }) => ids)).toEqual([["switch"]]);
|
||||
await recipient.delivery.close();
|
||||
});
|
||||
|
||||
test("a direct broader-mode send does not coalesce a queued plan-mode message and preserves FIFO mode order", async () => {
|
||||
const recipient = createRecipient();
|
||||
const planned = await recipient.delivery.enqueue({
|
||||
recipientId: "recipient",
|
||||
messageId: "plan-1",
|
||||
text: "Inspect files only",
|
||||
sessionMode: "plan",
|
||||
activeTurnBehavior: "queue",
|
||||
});
|
||||
await recipient.tick();
|
||||
|
||||
const direct = await recipient.person("Edit files now", "direct-1", {
|
||||
sessionMode: "bypassPermissions",
|
||||
});
|
||||
await expect(planned.dispatched).resolves.toBe("turn_started");
|
||||
await recipient.settle();
|
||||
|
||||
// Direct send did NOT coalesce plan-1 into a bypassPermissions prompt.
|
||||
expect(direct.prompt).toBeUndefined();
|
||||
expect(direct.result).toMatchObject({ disposition: "queued" });
|
||||
expect(recipient.sent).toEqual([
|
||||
{
|
||||
ids: ["plan-1"],
|
||||
behavior: "interrupt",
|
||||
idleOnly: false,
|
||||
mode: "plan",
|
||||
},
|
||||
]);
|
||||
|
||||
// Once the plan turn finishes, the direct send runs separately in bypassPermissions.
|
||||
await recipient.endTurn();
|
||||
expect(recipient.sent).toEqual([
|
||||
{
|
||||
ids: ["plan-1"],
|
||||
behavior: "interrupt",
|
||||
idleOnly: false,
|
||||
mode: "plan",
|
||||
},
|
||||
{
|
||||
ids: ["direct-1"],
|
||||
behavior: "steer",
|
||||
idleOnly: true,
|
||||
mode: "bypassPermissions",
|
||||
},
|
||||
]);
|
||||
expect(recipient.received).toEqual(["plan-1", "direct-1"]);
|
||||
expect(recipient.delivery.hasPending("recipient")).toBe(false);
|
||||
await recipient.delivery.close();
|
||||
});
|
||||
|
||||
test("a direct plan-mode send does not coalesce a queued broader-mode message and preserves FIFO mode order", async () => {
|
||||
const recipient = createRecipient();
|
||||
const broad = await recipient.delivery.enqueue({
|
||||
recipientId: "recipient",
|
||||
messageId: "broad-1",
|
||||
text: "Apply patch",
|
||||
sessionMode: "bypassPermissions",
|
||||
activeTurnBehavior: "queue",
|
||||
});
|
||||
await recipient.tick();
|
||||
|
||||
const direct = await recipient.person("Now review read-only", "direct-plan", {
|
||||
sessionMode: "plan",
|
||||
});
|
||||
await expect(broad.dispatched).resolves.toBe("turn_started");
|
||||
await recipient.settle();
|
||||
|
||||
expect(direct.prompt).toBeUndefined();
|
||||
expect(direct.result).toMatchObject({ disposition: "queued" });
|
||||
expect(recipient.sent).toEqual([
|
||||
{
|
||||
ids: ["broad-1"],
|
||||
behavior: "interrupt",
|
||||
idleOnly: false,
|
||||
mode: "bypassPermissions",
|
||||
},
|
||||
]);
|
||||
|
||||
await recipient.endTurn();
|
||||
expect(recipient.sent).toEqual([
|
||||
{
|
||||
ids: ["broad-1"],
|
||||
behavior: "interrupt",
|
||||
idleOnly: false,
|
||||
mode: "bypassPermissions",
|
||||
},
|
||||
{
|
||||
ids: ["direct-plan"],
|
||||
behavior: "steer",
|
||||
idleOnly: true,
|
||||
mode: "plan",
|
||||
},
|
||||
]);
|
||||
expect(recipient.received).toEqual(["broad-1", "direct-plan"]);
|
||||
await recipient.delivery.close();
|
||||
});
|
||||
|
||||
test.each([
|
||||
{
|
||||
name: "same explicit mode",
|
||||
queuedMode: "plan",
|
||||
directMode: "plan",
|
||||
expectedMode: "plan",
|
||||
},
|
||||
{
|
||||
name: "queued explicit mode with unset direct mode",
|
||||
queuedMode: "plan",
|
||||
directMode: undefined,
|
||||
expectedMode: "plan",
|
||||
},
|
||||
])(
|
||||
"a direct send still coalesces with a queued message when modes are compatible ($name)",
|
||||
async ({ queuedMode, directMode, expectedMode }) => {
|
||||
const recipient = createRecipient();
|
||||
const queued = await recipient.delivery.enqueue({
|
||||
recipientId: "recipient",
|
||||
messageId: "queued-1",
|
||||
text: "Queued note",
|
||||
sessionMode: queuedMode,
|
||||
activeTurnBehavior: "queue",
|
||||
});
|
||||
await recipient.tick();
|
||||
|
||||
const direct = await recipient.person("Direct follow-up", "direct-1", {
|
||||
sessionMode: directMode,
|
||||
});
|
||||
await expect(queued.dispatched).resolves.toBe("turn_started");
|
||||
expect(direct.result).toMatchObject({ disposition: "turn_started" });
|
||||
expect(direct.ids).toEqual(["queued-1", "direct-1"]);
|
||||
expect(direct.sessionMode).toBe(expectedMode);
|
||||
expect(recipient.sent).toEqual([]);
|
||||
expect(recipient.delivery.hasPending("recipient")).toBe(false);
|
||||
await recipient.delivery.close();
|
||||
},
|
||||
);
|
||||
|
||||
test("multiple queued messages across a mode boundary followed by a direct send never merge across modes", async () => {
|
||||
const recipient = createRecipient();
|
||||
const planned = await recipient.delivery.enqueue({
|
||||
recipientId: "recipient",
|
||||
messageId: "plan-1",
|
||||
text: "Plan first",
|
||||
sessionMode: "plan",
|
||||
activeTurnBehavior: "queue",
|
||||
});
|
||||
const broad = await recipient.delivery.enqueue({
|
||||
recipientId: "recipient",
|
||||
messageId: "broad-1",
|
||||
text: "Edit second",
|
||||
sessionMode: "bypassPermissions",
|
||||
activeTurnBehavior: "queue",
|
||||
});
|
||||
await recipient.tick();
|
||||
|
||||
const direct = await recipient.person("Edit third", "direct-broad", {
|
||||
sessionMode: "bypassPermissions",
|
||||
});
|
||||
await expect(planned.dispatched).resolves.toBe("turn_started");
|
||||
await recipient.settle();
|
||||
|
||||
expect(direct.prompt).toBeUndefined();
|
||||
expect(direct.result).toMatchObject({ disposition: "queued" });
|
||||
expect(recipient.sent).toEqual([
|
||||
{
|
||||
ids: ["plan-1"],
|
||||
behavior: "interrupt",
|
||||
idleOnly: false,
|
||||
mode: "plan",
|
||||
},
|
||||
]);
|
||||
|
||||
await recipient.endTurn();
|
||||
await expect(broad.dispatched).resolves.toBe("turn_started");
|
||||
expect(recipient.sent).toEqual([
|
||||
{
|
||||
ids: ["plan-1"],
|
||||
behavior: "interrupt",
|
||||
idleOnly: false,
|
||||
mode: "plan",
|
||||
},
|
||||
{
|
||||
ids: ["broad-1", "direct-broad"],
|
||||
behavior: "steer",
|
||||
idleOnly: true,
|
||||
mode: "bypassPermissions",
|
||||
},
|
||||
]);
|
||||
expect(recipient.received).toEqual(["plan-1", "broad-1", "direct-broad"]);
|
||||
await recipient.delivery.close();
|
||||
});
|
||||
|
||||
test("a direct send with unset mode still respects an existing mode boundary in the queue", async () => {
|
||||
const recipient = createRecipient();
|
||||
const planned = await recipient.delivery.enqueue({
|
||||
recipientId: "recipient",
|
||||
messageId: "plan-1",
|
||||
text: "Plan first",
|
||||
sessionMode: "plan",
|
||||
activeTurnBehavior: "queue",
|
||||
});
|
||||
await recipient.delivery.enqueue({
|
||||
recipientId: "recipient",
|
||||
messageId: "broad-1",
|
||||
text: "Edit second",
|
||||
sessionMode: "bypassPermissions",
|
||||
activeTurnBehavior: "queue",
|
||||
});
|
||||
await recipient.tick();
|
||||
|
||||
const direct = await recipient.person("Follow up", "direct-unset");
|
||||
await expect(planned.dispatched).resolves.toBe("turn_started");
|
||||
await recipient.settle();
|
||||
|
||||
expect(direct.prompt).toBeUndefined();
|
||||
expect(direct.result).toMatchObject({ disposition: "queued" });
|
||||
expect(recipient.sent.map(({ ids, mode }) => ({ ids, mode }))).toEqual([
|
||||
{ ids: ["plan-1"], mode: "plan" },
|
||||
]);
|
||||
|
||||
await recipient.endTurn();
|
||||
expect(recipient.sent.map(({ ids, mode }) => ({ ids, mode }))).toEqual([
|
||||
{ ids: ["plan-1"], mode: "plan" },
|
||||
{ ids: ["broad-1", "direct-unset"], mode: "bypassPermissions" },
|
||||
]);
|
||||
await recipient.delivery.close();
|
||||
});
|
||||
|
||||
test("a direct send behind a queued non-agent slash command keeps the command raw and alone", async () => {
|
||||
const recipient = createRecipient();
|
||||
const command = await recipient.delivery.enqueue({
|
||||
recipientId: "recipient",
|
||||
messageId: "cmd-1",
|
||||
text: "/review",
|
||||
activeTurnBehavior: "queue",
|
||||
});
|
||||
await recipient.tick();
|
||||
|
||||
const direct = await recipient.person("Summarize findings", "direct-1");
|
||||
await expect(command.dispatched).resolves.toBe("turn_started");
|
||||
await recipient.settle();
|
||||
|
||||
expect(direct.prompt).toBeUndefined();
|
||||
expect(direct.result).toMatchObject({ disposition: "queued" });
|
||||
expect(recipient.sent.map(({ ids }) => ids)).toEqual([["cmd-1"]]);
|
||||
|
||||
await recipient.endTurn();
|
||||
expect(recipient.sent.map(({ ids }) => ids)).toEqual([["cmd-1"], ["direct-1"]]);
|
||||
await recipient.delivery.close();
|
||||
});
|
||||
|
||||
test("an urgent interrupt with a conflicting mode does not coalesce a queued plan-mode message", async () => {
|
||||
const recipient = createRecipient();
|
||||
const planned = await recipient.delivery.enqueue({
|
||||
recipientId: "recipient",
|
||||
messageId: "plan-1",
|
||||
text: "Inspect only",
|
||||
sessionMode: "plan",
|
||||
activeTurnBehavior: "queue",
|
||||
});
|
||||
const urgent = await recipient.delivery.enqueue({
|
||||
recipientId: "recipient",
|
||||
messageId: "urgent-broad",
|
||||
source: { kind: "agent-message", agentId: "sender" },
|
||||
text: "Modify now",
|
||||
sessionMode: "bypassPermissions",
|
||||
activeTurnBehavior: "interrupt",
|
||||
});
|
||||
await expect(planned.dispatched).resolves.toBe("turn_started");
|
||||
await recipient.settle();
|
||||
|
||||
expect(recipient.sent).toEqual([
|
||||
{
|
||||
ids: ["plan-1"],
|
||||
behavior: "interrupt",
|
||||
idleOnly: false,
|
||||
mode: "plan",
|
||||
},
|
||||
]);
|
||||
|
||||
await recipient.endTurn();
|
||||
await expect(urgent.dispatched).resolves.toBe("turn_started");
|
||||
expect(recipient.sent).toEqual([
|
||||
{
|
||||
ids: ["plan-1"],
|
||||
behavior: "interrupt",
|
||||
idleOnly: false,
|
||||
mode: "plan",
|
||||
},
|
||||
{
|
||||
ids: ["urgent-broad"],
|
||||
behavior: "steer",
|
||||
idleOnly: true,
|
||||
mode: "bypassPermissions",
|
||||
},
|
||||
]);
|
||||
await recipient.delivery.close();
|
||||
});
|
||||
|
||||
test("a direct broader-mode send after Stop reopens a held plan-mode message without coalescing across modes", async () => {
|
||||
const recipient = createRecipient();
|
||||
const planned = await recipient.delivery.enqueue({
|
||||
recipientId: "recipient",
|
||||
messageId: "plan-held",
|
||||
text: "Plan before stop",
|
||||
sessionMode: "plan",
|
||||
activeTurnBehavior: "queue",
|
||||
});
|
||||
await recipient.stop();
|
||||
await recipient.tick();
|
||||
expect(recipient.sent).toEqual([]);
|
||||
|
||||
const direct = await recipient.person("Edit after stop", "direct-after-stop", {
|
||||
sessionMode: "bypassPermissions",
|
||||
});
|
||||
await expect(planned.dispatched).resolves.toBe("turn_started");
|
||||
await recipient.settle();
|
||||
|
||||
expect(direct.prompt).toBeUndefined();
|
||||
expect(direct.result).toMatchObject({ disposition: "queued" });
|
||||
expect(recipient.sent).toEqual([
|
||||
{
|
||||
ids: ["plan-held"],
|
||||
behavior: "interrupt",
|
||||
idleOnly: false,
|
||||
mode: "plan",
|
||||
},
|
||||
]);
|
||||
|
||||
await recipient.endTurn();
|
||||
expect(recipient.sent).toEqual([
|
||||
{
|
||||
ids: ["plan-held"],
|
||||
behavior: "interrupt",
|
||||
idleOnly: false,
|
||||
mode: "plan",
|
||||
},
|
||||
{
|
||||
ids: ["direct-after-stop"],
|
||||
behavior: "steer",
|
||||
idleOnly: true,
|
||||
mode: "bypassPermissions",
|
||||
},
|
||||
]);
|
||||
await recipient.delivery.close();
|
||||
});
|
||||
|
||||
function expectQueuedReceipt(result: {
|
||||
disposition: string;
|
||||
receipt?: { dispatched: Promise<unknown> };
|
||||
}) {
|
||||
expect(result.disposition).toBe("queued");
|
||||
if (result.disposition !== "queued" || !result.receipt) {
|
||||
throw new Error(`Expected queued disposition, received ${result.disposition}`);
|
||||
}
|
||||
return result.receipt;
|
||||
}
|
||||
|
||||
test("a direct broader-mode send does not coalesce a plan-mode dispatch returned to the queue after busy rejection", async () => {
|
||||
const clock = createClock();
|
||||
let busy = true;
|
||||
let releaseFirstAttempt!: () => void;
|
||||
const firstAttemptStarted = new Promise<void>((resolve) => {
|
||||
releaseFirstAttempt = resolve;
|
||||
});
|
||||
let finishFirstAttempt!: () => void;
|
||||
const firstAttemptGate = new Promise<void>((resolve) => {
|
||||
finishFirstAttempt = resolve;
|
||||
});
|
||||
let wake!: (recipientId: string) => void;
|
||||
let attempts = 0;
|
||||
const dispatched: Array<{ ids: readonly string[]; mode?: string }> = [];
|
||||
const directPrompts: AgentPromptInput[] = [];
|
||||
const delivery = createAgentMessageDelivery({
|
||||
store: createMemoryAgentMessageQueueStore(),
|
||||
schedule: clock.schedule,
|
||||
isRunning: () => busy,
|
||||
subscribe: (listener) => {
|
||||
wake = listener;
|
||||
return () => {};
|
||||
},
|
||||
dispatch: async (request) => {
|
||||
attempts++;
|
||||
if (attempts === 1) {
|
||||
releaseFirstAttempt();
|
||||
await firstAttemptGate;
|
||||
throw new AgentTurnBusyError("turn started concurrently");
|
||||
}
|
||||
if (!request.admit()) throw new Error("not admitted");
|
||||
dispatched.push({ ids: request.messageIds, mode: request.sessionMode });
|
||||
busy = true;
|
||||
return "turn_started";
|
||||
},
|
||||
onError: (error) => {
|
||||
throw error;
|
||||
},
|
||||
});
|
||||
|
||||
busy = false;
|
||||
const planned = await delivery.enqueue({
|
||||
recipientId: "recipient",
|
||||
messageId: "plan-1",
|
||||
text: "Plan first",
|
||||
sessionMode: "plan",
|
||||
activeTurnBehavior: "queue",
|
||||
});
|
||||
await firstAttemptStarted;
|
||||
|
||||
// plan-1 is currently marked dispatching/claimed in flight when the direct send arrives.
|
||||
const directPromise = delivery.sendDirect(
|
||||
{
|
||||
recipientId: "recipient",
|
||||
messageId: "direct-1",
|
||||
prompt: "Edit now",
|
||||
sessionMode: "bypassPermissions",
|
||||
},
|
||||
async (joined) => {
|
||||
directPrompts.push(joined.prompt);
|
||||
return { disposition: "turn_started", started: Promise.resolve() };
|
||||
},
|
||||
);
|
||||
// A later message admitted while direct-1 waits must stay behind direct-1.
|
||||
const later = await delivery.enqueue({
|
||||
recipientId: "recipient",
|
||||
messageId: "later-1",
|
||||
text: "Later message",
|
||||
sessionMode: "default",
|
||||
activeTurnBehavior: "queue",
|
||||
});
|
||||
|
||||
// First attempt fails with AgentTurnBusyError and hands plan-1 back to queued before direct runs.
|
||||
busy = true;
|
||||
finishFirstAttempt();
|
||||
const directResult = await directPromise;
|
||||
await expect(planned.dispatched).resolves.toBe("turn_started");
|
||||
|
||||
expect(directPrompts).toEqual([]);
|
||||
const queuedDirectReceipt = expectQueuedReceipt(directResult);
|
||||
expect(dispatched).toEqual([{ ids: ["plan-1"], mode: "plan" }]);
|
||||
|
||||
busy = false;
|
||||
wake("recipient");
|
||||
await expect(queuedDirectReceipt.dispatched).resolves.toBe("turn_started");
|
||||
expect(dispatched).toEqual([
|
||||
{ ids: ["plan-1"], mode: "plan" },
|
||||
{ ids: ["direct-1"], mode: "bypassPermissions" },
|
||||
]);
|
||||
|
||||
busy = false;
|
||||
wake("recipient");
|
||||
await expect(later.dispatched).resolves.toBe("turn_started");
|
||||
expect(dispatched).toEqual([
|
||||
{ ids: ["plan-1"], mode: "plan" },
|
||||
{ ids: ["direct-1"], mode: "bypassPermissions" },
|
||||
{ ids: ["later-1"], mode: "default" },
|
||||
]);
|
||||
await delivery.close();
|
||||
});
|
||||
|
||||
test("a direct send with a conflicting mode stays ahead of a queued provider switch on the current provider", async () => {
|
||||
const recipient = createRecipient();
|
||||
const planned = await recipient.delivery.enqueue({
|
||||
recipientId: "recipient",
|
||||
messageId: "plan-1",
|
||||
text: "Plan on current provider",
|
||||
sessionMode: "plan",
|
||||
activeTurnBehavior: "queue",
|
||||
});
|
||||
await recipient.queueSwitch("switch", "codex");
|
||||
recipient.send("queue", "after");
|
||||
await recipient.tick();
|
||||
|
||||
const direct = await recipient.person("Edit on current provider", "direct-1", {
|
||||
sessionMode: "bypassPermissions",
|
||||
});
|
||||
await expect(planned.dispatched).resolves.toBe("turn_started");
|
||||
await recipient.settle();
|
||||
|
||||
expect(direct.prompt).toBeUndefined();
|
||||
expect(direct.result).toMatchObject({ disposition: "queued" });
|
||||
expect(recipient.sent.map(({ ids, mode, switchTo }) => ({ ids, mode, switchTo }))).toEqual([
|
||||
{ ids: ["plan-1"], mode: "plan", switchTo: undefined },
|
||||
]);
|
||||
|
||||
await recipient.endTurn();
|
||||
await recipient.endTurn();
|
||||
await recipient.endTurn();
|
||||
expect(recipient.sent.map(({ ids, mode, switchTo }) => ({ ids, mode, switchTo }))).toEqual([
|
||||
{ ids: ["plan-1"], mode: "plan", switchTo: undefined },
|
||||
{ ids: ["direct-1"], mode: "bypassPermissions", switchTo: undefined },
|
||||
{ ids: ["switch"], mode: undefined, switchTo: "codex" },
|
||||
{ ids: ["after"], mode: undefined, switchTo: undefined },
|
||||
]);
|
||||
await recipient.delivery.close();
|
||||
});
|
||||
|
||||
test("retrying a direct send that is already queued returns its queued receipt without duplicating or interrupting", async () => {
|
||||
const recipient = createRecipient();
|
||||
const planned = await recipient.delivery.enqueue({
|
||||
recipientId: "recipient",
|
||||
messageId: "plan-1",
|
||||
text: "Plan first",
|
||||
sessionMode: "plan",
|
||||
activeTurnBehavior: "queue",
|
||||
});
|
||||
await recipient.tick();
|
||||
|
||||
let directCalls = 0;
|
||||
const first = await recipient.delivery.sendDirect(
|
||||
{
|
||||
recipientId: "recipient",
|
||||
messageId: "direct-retry",
|
||||
prompt: "Edit later",
|
||||
sessionMode: "bypassPermissions",
|
||||
fingerprint: "fp-1",
|
||||
},
|
||||
async () => {
|
||||
directCalls += 1;
|
||||
return { disposition: "turn_started", started: Promise.resolve() };
|
||||
},
|
||||
);
|
||||
await expect(planned.dispatched).resolves.toBe("turn_started");
|
||||
await recipient.settle();
|
||||
|
||||
// plan-1 is now running and direct-retry is waiting in the queue.
|
||||
const firstReceipt = expectQueuedReceipt(first);
|
||||
const retry = await recipient.delivery.sendDirect(
|
||||
{
|
||||
recipientId: "recipient",
|
||||
messageId: "direct-retry",
|
||||
prompt: "Edit later",
|
||||
sessionMode: "bypassPermissions",
|
||||
fingerprint: "fp-1",
|
||||
},
|
||||
async () => {
|
||||
directCalls += 1;
|
||||
return { disposition: "turn_started", started: Promise.resolve() };
|
||||
},
|
||||
);
|
||||
expect(expectQueuedReceipt(retry)).toBe(firstReceipt);
|
||||
expect(directCalls).toBe(0);
|
||||
expect(recipient.sent).toEqual([
|
||||
{ ids: ["plan-1"], behavior: "interrupt", idleOnly: false, mode: "plan" },
|
||||
]);
|
||||
|
||||
await expect(
|
||||
recipient.delivery.sendDirect(
|
||||
{
|
||||
recipientId: "recipient",
|
||||
messageId: "direct-retry",
|
||||
prompt: "Different body",
|
||||
sessionMode: "bypassPermissions",
|
||||
fingerprint: "fp-different",
|
||||
},
|
||||
async () => ({ disposition: "turn_started", started: Promise.resolve() }),
|
||||
),
|
||||
).rejects.toThrow("agent_request_key_conflict");
|
||||
|
||||
await recipient.endTurn();
|
||||
await expect(firstReceipt.dispatched).resolves.toBe("turn_started");
|
||||
expect(recipient.sent).toEqual([
|
||||
{ ids: ["plan-1"], behavior: "interrupt", idleOnly: false, mode: "plan" },
|
||||
{ ids: ["direct-retry"], behavior: "steer", idleOnly: true, mode: "bypassPermissions" },
|
||||
]);
|
||||
await recipient.delivery.close();
|
||||
});
|
||||
|
||||
test("lazy direct-send attachments resolve only when queued and preserve order ahead of concurrent arrivals", async () => {
|
||||
const store = createMemoryAgentMessageQueueStore();
|
||||
const recipient = createRecipient({ store });
|
||||
|
||||
// Direct send on an empty queue runs immediately without invoking resolveAttachments.
|
||||
let emptyResolverCalls = 0;
|
||||
await recipient.delivery.sendDirect(
|
||||
{
|
||||
recipientId: "recipient",
|
||||
messageId: "direct-empty",
|
||||
prompt: "Look",
|
||||
text: "Look",
|
||||
resolveAttachments: async () => {
|
||||
emptyResolverCalls += 1;
|
||||
return [];
|
||||
},
|
||||
},
|
||||
async () => ({ disposition: "turn_started", started: Promise.resolve() }),
|
||||
);
|
||||
expect(emptyResolverCalls).toBe(0);
|
||||
|
||||
const planned = await recipient.delivery.enqueue({
|
||||
recipientId: "recipient",
|
||||
messageId: "plan-1",
|
||||
text: "Plan first",
|
||||
sessionMode: "plan",
|
||||
activeTurnBehavior: "queue",
|
||||
});
|
||||
await recipient.tick();
|
||||
|
||||
let finishAttachments!: () => void;
|
||||
const attachmentGate = new Promise<void>((resolve) => {
|
||||
finishAttachments = resolve;
|
||||
});
|
||||
let queuedResolverCalls = 0;
|
||||
const directPromise = recipient.delivery.sendDirect(
|
||||
{
|
||||
recipientId: "recipient",
|
||||
messageId: "direct-img",
|
||||
prompt: [{ type: "image", data: "aGVsbG8=", mimeType: "image/png" }],
|
||||
text: "",
|
||||
sessionMode: "bypassPermissions",
|
||||
resolveAttachments: async () => {
|
||||
queuedResolverCalls += 1;
|
||||
await attachmentGate;
|
||||
return [
|
||||
{
|
||||
type: "github_issue",
|
||||
mimeType: "application/github-issue",
|
||||
number: 7,
|
||||
title: "Attached context",
|
||||
url: "https://example.com/7",
|
||||
},
|
||||
];
|
||||
},
|
||||
},
|
||||
async () => ({ disposition: "turn_started", started: Promise.resolve() }),
|
||||
);
|
||||
|
||||
// Another message arrives while resolveAttachments is still pending.
|
||||
const later = await recipient.delivery.enqueue({
|
||||
recipientId: "recipient",
|
||||
messageId: "later-1",
|
||||
text: "Later message",
|
||||
sessionMode: "default",
|
||||
activeTurnBehavior: "queue",
|
||||
});
|
||||
|
||||
finishAttachments();
|
||||
const directResult = await directPromise;
|
||||
const directReceipt = expectQueuedReceipt(directResult);
|
||||
await expect(planned.dispatched).resolves.toBe("turn_started");
|
||||
await recipient.settle();
|
||||
|
||||
expect(queuedResolverCalls).toBe(1);
|
||||
// Store order matches admission order: direct-img stays ahead of later-1 with its attachment.
|
||||
expect(await store.listByRecipient("recipient")).toMatchObject([
|
||||
{ id: "direct-img", attachments: [{ type: "github_issue", number: 7 }] },
|
||||
{ id: "later-1" },
|
||||
]);
|
||||
|
||||
await recipient.endTurn();
|
||||
await expect(directReceipt.dispatched).resolves.toBe("turn_started");
|
||||
await recipient.endTurn();
|
||||
await expect(later.dispatched).resolves.toBe("turn_started");
|
||||
expect(recipient.sent.map(({ ids, mode }) => ({ ids, mode }))).toEqual([
|
||||
{ ids: ["plan-1"], mode: "plan" },
|
||||
{ ids: ["direct-img"], mode: "bypassPermissions" },
|
||||
{ ids: ["later-1"], mode: "default" },
|
||||
]);
|
||||
await recipient.delivery.close();
|
||||
});
|
||||
|
||||
test("a direct provider switch does not coalesce a queued or Stop-held plan-mode message onto the target provider", async () => {
|
||||
const recipient = createRecipient();
|
||||
const planned = await recipient.delivery.enqueue({
|
||||
recipientId: "recipient",
|
||||
messageId: "claude-plan",
|
||||
text: "QUEUED_FOR_CLAUDE_ONLY",
|
||||
sessionMode: "plan",
|
||||
activeTurnBehavior: "queue",
|
||||
});
|
||||
await recipient.stop();
|
||||
await recipient.tick();
|
||||
|
||||
let directSwitchCalls = 0;
|
||||
const result = await recipient.delivery.sendDirect(
|
||||
{
|
||||
recipientId: "recipient",
|
||||
messageId: "switch-codex",
|
||||
prompt: "DIRECT_SWITCH_TO_CODEX",
|
||||
text: "DIRECT_SWITCH_TO_CODEX",
|
||||
sessionMode: "plan",
|
||||
providerSwitch: { provider: "codex", modeId: "plan" },
|
||||
},
|
||||
async () => {
|
||||
directSwitchCalls += 1;
|
||||
return { disposition: "turn_started", started: Promise.resolve() };
|
||||
},
|
||||
);
|
||||
const queuedSwitch = expectQueuedReceipt(result);
|
||||
await expect(planned.dispatched).resolves.toBe("turn_started");
|
||||
await recipient.settle();
|
||||
|
||||
expect(directSwitchCalls).toBe(0);
|
||||
expect(recipient.sent.map(({ ids, mode, switchTo }) => ({ ids, mode, switchTo }))).toEqual([
|
||||
{ ids: ["claude-plan"], mode: "plan", switchTo: undefined },
|
||||
]);
|
||||
|
||||
await recipient.endTurn();
|
||||
await expect(queuedSwitch.dispatched).resolves.toBe("turn_started");
|
||||
expect(recipient.sent.map(({ ids, mode, switchTo }) => ({ ids, mode, switchTo }))).toEqual([
|
||||
{ ids: ["claude-plan"], mode: "plan", switchTo: undefined },
|
||||
{ ids: ["switch-codex"], mode: "plan", switchTo: "codex" },
|
||||
]);
|
||||
await recipient.delivery.close();
|
||||
});
|
||||
|
||||
test("a direct provider switch does not steal an unheld collecting message onto the target provider", async () => {
|
||||
const recipient = createRecipient({ running: false });
|
||||
const queued = await recipient.delivery.enqueue({
|
||||
recipientId: "recipient",
|
||||
messageId: "claude-collecting",
|
||||
source: { kind: "agent-message", agentId: "worker" },
|
||||
text: "Collecting for current provider",
|
||||
activeTurnBehavior: "queue",
|
||||
});
|
||||
|
||||
let directSwitchCalls = 0;
|
||||
const result = await recipient.delivery.sendDirect(
|
||||
{
|
||||
recipientId: "recipient",
|
||||
messageId: "switch-codex",
|
||||
prompt: "Switch now",
|
||||
text: "Switch now",
|
||||
providerSwitch: { provider: "codex" },
|
||||
},
|
||||
async () => {
|
||||
directSwitchCalls += 1;
|
||||
return { disposition: "turn_started", started: Promise.resolve() };
|
||||
},
|
||||
);
|
||||
const queuedSwitch = expectQueuedReceipt(result);
|
||||
await expect(queued.dispatched).resolves.toBe("turn_started");
|
||||
await recipient.settle();
|
||||
|
||||
expect(directSwitchCalls).toBe(0);
|
||||
expect(recipient.sent.map(({ ids, switchTo }) => ({ ids, switchTo }))).toEqual([
|
||||
{ ids: ["claude-collecting"], switchTo: undefined },
|
||||
]);
|
||||
|
||||
await recipient.endTurn();
|
||||
await expect(queuedSwitch.dispatched).resolves.toBe("turn_started");
|
||||
expect(recipient.sent.map(({ ids, switchTo }) => ({ ids, switchTo }))).toEqual([
|
||||
{ ids: ["claude-collecting"], switchTo: undefined },
|
||||
{ ids: ["switch-codex"], switchTo: "codex" },
|
||||
]);
|
||||
await recipient.delivery.close();
|
||||
});
|
||||
|
||||
test("an explicit-mode direct or queued send does not retroactively promote an earlier implicit-mode queued message", async () => {
|
||||
const recipient = createRecipient();
|
||||
const implicit = await recipient.delivery.enqueue({
|
||||
recipientId: "recipient",
|
||||
messageId: "implicit-1",
|
||||
text: "Run in existing mode",
|
||||
activeTurnBehavior: "queue",
|
||||
});
|
||||
await recipient.tick();
|
||||
|
||||
const direct = await recipient.person("Switch to bypass", "direct-bypass", {
|
||||
sessionMode: "bypassPermissions",
|
||||
});
|
||||
await expect(implicit.dispatched).resolves.toBe("turn_started");
|
||||
await recipient.settle();
|
||||
|
||||
expect(direct.prompt).toBeUndefined();
|
||||
expect(direct.result).toMatchObject({ disposition: "queued" });
|
||||
expect(recipient.sent).toEqual([
|
||||
{
|
||||
ids: ["implicit-1"],
|
||||
behavior: "interrupt",
|
||||
idleOnly: false,
|
||||
mode: undefined,
|
||||
},
|
||||
]);
|
||||
|
||||
await recipient.endTurn();
|
||||
expect(recipient.sent).toEqual([
|
||||
{
|
||||
ids: ["implicit-1"],
|
||||
behavior: "interrupt",
|
||||
idleOnly: false,
|
||||
mode: undefined,
|
||||
},
|
||||
{
|
||||
ids: ["direct-bypass"],
|
||||
behavior: "steer",
|
||||
idleOnly: true,
|
||||
mode: "bypassPermissions",
|
||||
},
|
||||
]);
|
||||
|
||||
// Ordinary queue draining also refuses to promote an earlier implicit-mode message.
|
||||
const implicitQueued = await recipient.delivery.enqueue({
|
||||
recipientId: "recipient",
|
||||
messageId: "implicit-2",
|
||||
text: "Stay in current mode",
|
||||
activeTurnBehavior: "queue",
|
||||
});
|
||||
const explicitQueued = await recipient.delivery.enqueue({
|
||||
recipientId: "recipient",
|
||||
messageId: "explicit-2",
|
||||
text: "Now enter plan",
|
||||
sessionMode: "plan",
|
||||
activeTurnBehavior: "queue",
|
||||
});
|
||||
await recipient.endTurn();
|
||||
await expect(implicitQueued.dispatched).resolves.toBe("turn_started");
|
||||
expect(recipient.sent.at(-1)).toMatchObject({
|
||||
ids: ["implicit-2"],
|
||||
idleOnly: true,
|
||||
mode: undefined,
|
||||
});
|
||||
|
||||
await recipient.endTurn();
|
||||
await expect(explicitQueued.dispatched).resolves.toBe("turn_started");
|
||||
expect(recipient.sent.at(-1)).toMatchObject({
|
||||
ids: ["explicit-2"],
|
||||
idleOnly: true,
|
||||
mode: "plan",
|
||||
});
|
||||
await recipient.delivery.close();
|
||||
});
|
||||
|
||||
@@ -7,7 +7,11 @@ import {
|
||||
} from "../agent-prompt.js";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import type { UploadedImage } from "@getpaseo/protocol/agent-types";
|
||||
import type { AgentAttachment, QueuedProviderSwitch } from "@getpaseo/protocol/messages";
|
||||
import type {
|
||||
AgentAttachment,
|
||||
QueuedProviderSwitch,
|
||||
UploadedFileAttachment,
|
||||
} from "@getpaseo/protocol/messages";
|
||||
import type {
|
||||
AgentPromptContentBlock,
|
||||
AgentPromptInput,
|
||||
@@ -49,7 +53,7 @@ interface Message {
|
||||
beforeDispatch?: () => void;
|
||||
onDispatch?: (disposition: PromptDispatchDisposition) => void;
|
||||
}
|
||||
interface Receipt {
|
||||
export interface AgentMessageReceipt {
|
||||
status: "queued";
|
||||
messageId: string;
|
||||
activeTurnBehavior: AgentMessageBehavior;
|
||||
@@ -57,8 +61,11 @@ interface Receipt {
|
||||
guidance: string;
|
||||
dispatched: Promise<PromptDispatchDisposition>;
|
||||
}
|
||||
export type DirectSendResult<Result extends PromptDispatchResult> =
|
||||
| Result
|
||||
| { disposition: "queued"; receipt: AgentMessageReceipt };
|
||||
/** What a queued message is. Urgency and the hold change while it waits. */
|
||||
type QueuedContent = Omit<EnqueueStoreInput, "urgency" | "held">;
|
||||
type QueuedContent = Omit<EnqueueStoreInput, "urgency" | "held" | "insertBeforeId">;
|
||||
interface Admitted extends QueuedContent {
|
||||
/** claimed: a dispatch has it. It leaves the queue when the provider admits the prompt. */
|
||||
state: "queued" | "claimed" | "withdrawn" | "rejected";
|
||||
@@ -69,7 +76,9 @@ interface Admitted extends QueuedContent {
|
||||
outOfBandDeclined: boolean;
|
||||
/** Settles once the store holds it. Nothing dispatches it before that. */
|
||||
saved: Promise<void>;
|
||||
receipt: Receipt;
|
||||
/** True once the record exists in the store (for ordering concurrent lazy saves). */
|
||||
persisted: boolean;
|
||||
receipt: AgentMessageReceipt;
|
||||
resolve(disposition: PromptDispatchDisposition): void;
|
||||
reject(error: unknown): void;
|
||||
beforeDispatch?: () => void;
|
||||
@@ -126,11 +135,22 @@ interface DispatchRequest {
|
||||
interface DirectPrompt {
|
||||
recipientId: string;
|
||||
prompt: AgentPromptInput;
|
||||
/** Raw message text when the caller has it, used if queueing behind a boundary. */
|
||||
text?: string;
|
||||
/** Raw message attachments when the caller has them, used if queueing behind a boundary. */
|
||||
attachments?: readonly AgentAttachment[];
|
||||
/** Lazy attachment persistence invoked only when a direct prompt is queued behind a boundary. */
|
||||
resolveAttachments?: () => Promise<AgentAttachment[]>;
|
||||
uploadedImages?: readonly UploadedImage[];
|
||||
source?: AgentPromptSource;
|
||||
messageId?: string;
|
||||
sessionMode?: string;
|
||||
providerSwitch?: QueuedProviderSwitch;
|
||||
activeTurnBehavior?: QueuedMessageUrgency;
|
||||
clearPendingPermissions?: boolean;
|
||||
fingerprint?: string;
|
||||
unarchive?: boolean;
|
||||
onDispatch?: (disposition: PromptDispatchDisposition) => void;
|
||||
/** It continues the turn the queue is waiting on, so it takes nothing queued with it. */
|
||||
resumesTurn?: boolean;
|
||||
}
|
||||
@@ -188,16 +208,18 @@ export interface AgentMessageDelivery {
|
||||
* Admit a message and resolve once it is saved. A queued one waits for the running turn to
|
||||
* end; a steer or an interrupt releases at once, with everything queued before it.
|
||||
*/
|
||||
enqueue(message: Message): Promise<Receipt>;
|
||||
enqueue(message: Message): Promise<AgentMessageReceipt>;
|
||||
/**
|
||||
* Send a prompt that does not wait its turn. The messages admitted before it go ahead of it
|
||||
* in the same provider prompt, so none starts a turn of its own afterwards. Its place is
|
||||
* decided by this call, whenever the recipient gets to it. A command travels alone.
|
||||
* Send a prompt that does not wait its turn. Compatible messages admitted before it go ahead
|
||||
* of it in the same provider prompt, so none starts a turn of its own afterwards. When a
|
||||
* boundary (conflicting session mode, queued non-agent command, or provider switch) prevents
|
||||
* coalescing, the prompt is queued behind those messages and releases the first group at once.
|
||||
* A direct command or restart-resume travels alone.
|
||||
*/
|
||||
sendDirect<Result extends PromptDispatchResult>(
|
||||
direct: DirectPrompt,
|
||||
send: (joined: JoinedPrompt) => Promise<Result>,
|
||||
): Promise<Result>;
|
||||
): Promise<DirectSendResult<Result>>;
|
||||
/** The saved queue in delivery order. `held`: it waits for the recipient's next prompt. */
|
||||
list(recipientId: string): Promise<{ held: boolean; items: PersistedQueuedMessage[] }>;
|
||||
/** Settles with the delivery of a message still in the queue. Undefined once it has left. */
|
||||
@@ -288,36 +310,152 @@ function beforeSwitch(messages: Admitted[]): Admitted[] {
|
||||
return index < 0 ? messages : messages.slice(0, index);
|
||||
}
|
||||
|
||||
interface DispatchBoundary {
|
||||
readonly prompt: AgentPromptInput;
|
||||
readonly source: AgentPromptSource | null | undefined;
|
||||
readonly sessionMode?: string;
|
||||
readonly providerSwitch?: QueuedProviderSwitch;
|
||||
}
|
||||
|
||||
function travelsAlone(entry: DispatchBoundary): boolean {
|
||||
return Boolean(entry.providerSwitch) || (!entry.source && isCommand(entry.prompt));
|
||||
}
|
||||
|
||||
function hasConflictingSessionMode(input: {
|
||||
groupMode: string | undefined;
|
||||
nextMode: string | undefined;
|
||||
}): boolean {
|
||||
// An explicit sessionMode switches modes for this message and onward, so it cannot coalesce
|
||||
// onto an earlier group with either a different mode or an unset (implicit) mode.
|
||||
return input.nextMode !== undefined && input.groupMode !== input.nextMode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Provider switches, explicitly conflicting session modes and non-agent commands require
|
||||
* separate, ordered dispatches.
|
||||
*/
|
||||
function modeGroups(messages: Admitted[]): Admitted[][] {
|
||||
const groups: Admitted[][] = [];
|
||||
let group: Admitted[] = [];
|
||||
function dispatchGroups<Entry>(input: {
|
||||
entries: readonly Entry[];
|
||||
boundaryOf: (entry: Entry) => DispatchBoundary;
|
||||
}): Entry[][] {
|
||||
const groups: Entry[][] = [];
|
||||
let group: Entry[] = [];
|
||||
let mode: string | undefined;
|
||||
for (const message of messages) {
|
||||
if (message.providerSwitch || (!message.source && isCommand(message.text))) {
|
||||
for (const entry of input.entries) {
|
||||
const boundary = input.boundaryOf(entry);
|
||||
if (travelsAlone(boundary)) {
|
||||
if (group.length) {
|
||||
groups.push(group);
|
||||
group = [];
|
||||
mode = undefined;
|
||||
}
|
||||
groups.push([message]);
|
||||
groups.push([entry]);
|
||||
continue;
|
||||
}
|
||||
if (mode && message.sessionMode && mode !== message.sessionMode) {
|
||||
if (
|
||||
group.length > 0 &&
|
||||
hasConflictingSessionMode({ groupMode: mode, nextMode: boundary.sessionMode })
|
||||
) {
|
||||
groups.push(group);
|
||||
group = [];
|
||||
mode = undefined;
|
||||
}
|
||||
group.push(message);
|
||||
mode ??= message.sessionMode;
|
||||
group.push(entry);
|
||||
mode ??= boundary.sessionMode;
|
||||
}
|
||||
if (group.length) groups.push(group);
|
||||
return groups;
|
||||
}
|
||||
|
||||
function boundaryOfAdmitted(message: Admitted): DispatchBoundary {
|
||||
return {
|
||||
prompt: message.text,
|
||||
source: message.source,
|
||||
sessionMode: message.sessionMode,
|
||||
providerSwitch: message.providerSwitch,
|
||||
};
|
||||
}
|
||||
|
||||
function boundaryOfDirect(input: {
|
||||
direct: DirectPrompt;
|
||||
includeProviderSwitch: boolean;
|
||||
}): DispatchBoundary {
|
||||
return {
|
||||
prompt: input.direct.prompt,
|
||||
source: input.direct.source,
|
||||
sessionMode: input.direct.sessionMode,
|
||||
...(input.includeProviderSwitch ? { providerSwitch: input.direct.providerSwitch } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function modeGroups(messages: readonly Admitted[]): Admitted[][] {
|
||||
return dispatchGroups({ entries: messages, boundaryOf: boundaryOfAdmitted });
|
||||
}
|
||||
|
||||
function canCoalesceDirect(input: { ahead: readonly Admitted[]; direct: DirectPrompt }): boolean {
|
||||
// A direct provider switch only carries a Stop-held queue when every held message has no
|
||||
// explicit sessionMode and the switch itself requests no mode override. Any unheld message
|
||||
// or explicit mode belongs to the current provider and must not move across providers.
|
||||
const carriesHeldSwitch =
|
||||
Boolean(input.direct.providerSwitch) &&
|
||||
!input.direct.providerSwitch?.modeId &&
|
||||
input.direct.sessionMode === undefined &&
|
||||
input.ahead.length > 0 &&
|
||||
input.ahead.every((message) => message.held && message.sessionMode === undefined);
|
||||
const entries: DispatchBoundary[] = [
|
||||
...input.ahead.map(boundaryOfAdmitted),
|
||||
boundaryOfDirect({ direct: input.direct, includeProviderSwitch: !carriesHeldSwitch }),
|
||||
];
|
||||
return dispatchGroups({ entries, boundaryOf: (entry) => entry }).length <= 1;
|
||||
}
|
||||
|
||||
function toUploadedImageAttachments(
|
||||
uploadedImages: readonly UploadedImage[] | undefined,
|
||||
): Array<UploadedFileAttachment & { role: "image" }> {
|
||||
return (uploadedImages ?? []).map((image) => ({
|
||||
type: "uploaded_file",
|
||||
role: "image",
|
||||
id: image.id,
|
||||
fileName: image.fileName,
|
||||
mimeType: image.mimeType,
|
||||
size: image.size,
|
||||
path: image.path,
|
||||
}));
|
||||
}
|
||||
|
||||
function isPlainTextBlock(block: AgentPromptContentBlock): block is { type: "text"; text: string } {
|
||||
return block.type === "text" && !("contextKind" in block);
|
||||
}
|
||||
|
||||
function directQueueContent(direct: DirectPrompt): {
|
||||
text: string;
|
||||
attachments: AgentAttachment[];
|
||||
} {
|
||||
if (direct.text !== undefined || direct.attachments !== undefined) {
|
||||
return {
|
||||
text: direct.text ?? "",
|
||||
attachments: [...(direct.attachments ?? [])],
|
||||
};
|
||||
}
|
||||
const uploadedAttachments = toUploadedImageAttachments(direct.uploadedImages);
|
||||
if (typeof direct.prompt === "string") {
|
||||
return { text: direct.prompt, attachments: uploadedAttachments };
|
||||
}
|
||||
const textParts: string[] = [];
|
||||
const otherAttachments: AgentAttachment[] = [];
|
||||
for (const block of direct.prompt) {
|
||||
if (isPlainTextBlock(block)) {
|
||||
textParts.push(block.text);
|
||||
} else if (block.type !== "image") {
|
||||
otherAttachments.push(block);
|
||||
}
|
||||
}
|
||||
return {
|
||||
text: textParts.join("\n\n"),
|
||||
attachments: [...uploadedAttachments, ...otherAttachments],
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Owns the order in which prompts reach a recipient. Delivery order equals admission order:
|
||||
* only a prefix of the queue is ever dispatched, except a command a provider runs out of band.
|
||||
@@ -408,6 +546,7 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
batch: Ready[],
|
||||
idleOnly: boolean,
|
||||
stopped: () => boolean,
|
||||
activeTurnBehavior?: QueuedMessageUrgency,
|
||||
): DispatchRequest {
|
||||
const messages = messagesOf(batch);
|
||||
return {
|
||||
@@ -422,10 +561,10 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
prompt: formatBatch(batch),
|
||||
uploadedImages: uploadedImagesOf(batch),
|
||||
// A batch that waited for the turn to end is dispatched idle-only, so it never steers.
|
||||
activeTurnBehavior: messages.some((message) => message.urgency === "interrupt")
|
||||
? "interrupt"
|
||||
: "steer",
|
||||
// An interrupt may follow a message that asked for another mode; the latest choice wins.
|
||||
activeTurnBehavior:
|
||||
activeTurnBehavior ??
|
||||
(messages.some((message) => message.urgency === "interrupt") ? "interrupt" : "steer"),
|
||||
// Every message in a batch belongs to one compatible mode group.
|
||||
sessionMode: messages.findLast((message) => message.sessionMode)?.sessionMode,
|
||||
providerSwitch: messages[0]?.providerSwitch,
|
||||
clearPendingPermissions: messages.some((message) => message.clearPendingPermissions),
|
||||
@@ -580,6 +719,7 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
batch: Admitted[],
|
||||
idleOnly: boolean,
|
||||
stopped: () => boolean,
|
||||
activeTurnBehavior?: QueuedMessageUrgency,
|
||||
): Promise<void> {
|
||||
for (;;) {
|
||||
const prepared = await prepare(recipientId, batch);
|
||||
@@ -592,7 +732,7 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
await handBack(recipientId, messages);
|
||||
continue;
|
||||
}
|
||||
const request = requestFor(recipientId, dispatching, idleOnly, stopped);
|
||||
const request = requestFor(recipientId, dispatching, idleOnly, stopped, activeTurnBehavior);
|
||||
let disposition: PromptDispatchDisposition;
|
||||
try {
|
||||
for (const message of messages) message.beforeDispatch?.();
|
||||
@@ -667,8 +807,9 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
|
||||
/**
|
||||
* Dispatch what the latest steer or interrupt releases: it does not jump the queue, so
|
||||
* everything admitted before it goes first. A provider switch bounds the release, because it
|
||||
* cannot share a prompt. False when nothing may go into the running turn.
|
||||
* everything admitted before it goes first. The first compatible boundary group runs now
|
||||
* (respecting provider switches, conflicting session modes and non-agent commands), and
|
||||
* later groups follow as turns end. False when nothing may go into the running turn.
|
||||
*/
|
||||
async function release(
|
||||
recipientId: string,
|
||||
@@ -677,14 +818,26 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
): Promise<boolean> {
|
||||
const last = ahead.findLastIndex(isUrgent);
|
||||
if (last < 0) return false;
|
||||
const released = ahead.slice(0, last + 1);
|
||||
const released = ahead.slice(0, last + 1).filter(isQueued);
|
||||
const [first] = released;
|
||||
if (!first) return false;
|
||||
// Only releasing the switch itself replaces the running turn with it.
|
||||
if (first?.providerSwitch && !isUrgent(first)) return false;
|
||||
const now = first?.providerSwitch ? [first] : beforeSwitch(released);
|
||||
// The rest follows when the turn these start ends.
|
||||
for (const message of released.slice(now.length)) message.urgency = null;
|
||||
await deliver(recipientId, now, false, stopped);
|
||||
if (first.providerSwitch && !isUrgent(first)) return false;
|
||||
const now = first.providerSwitch ? [first] : (modeGroups(released)[0] ?? []);
|
||||
const behavior: QueuedMessageUrgency = released.some(
|
||||
(message) => message.urgency === "interrupt",
|
||||
)
|
||||
? "interrupt"
|
||||
: "steer";
|
||||
// The rest follows when the turn these start ends. Persist the downgrade before dispatching
|
||||
// so a daemon restart while the first group runs does not revive consumed urgency.
|
||||
const deferred = released.slice(now.length);
|
||||
if (deferred.length) {
|
||||
for (const message of deferred) message.urgency = null;
|
||||
const deferredIds = idsOf(deferred);
|
||||
await write(store.clearUrgency(recipientId, deferredIds), recipientId, deferredIds);
|
||||
}
|
||||
await deliver(recipientId, now, false, stopped, behavior);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -764,10 +917,14 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
};
|
||||
}
|
||||
|
||||
function admit(item: Admitted): void {
|
||||
function admit(item: Admitted, insertBeforeId?: string): void {
|
||||
const inbox = inboxes.get(item.recipientId) ?? emptyInbox();
|
||||
inboxes.set(item.recipientId, inbox);
|
||||
inbox.messages.push(item);
|
||||
const insertIndex = insertBeforeId
|
||||
? inbox.messages.findIndex((entry) => entry.id === insertBeforeId)
|
||||
: -1;
|
||||
if (insertIndex >= 0) inbox.messages.splice(insertIndex, 0, item);
|
||||
else inbox.messages.push(item);
|
||||
inbox.cancelTimer();
|
||||
if (item.urgency) {
|
||||
// A steer or an interrupt does not wait: it closes the window and takes the queue along. Its place
|
||||
@@ -795,7 +952,7 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
function createAdmitted(
|
||||
content: QueuedContent,
|
||||
state: Pick<Admitted, "urgency" | "held">,
|
||||
receipt: Pick<Receipt, "activeTurnBehavior" | "guidance">,
|
||||
receipt: Pick<AgentMessageReceipt, "activeTurnBehavior" | "guidance">,
|
||||
): Admitted {
|
||||
let resolve!: Admitted["resolve"];
|
||||
let reject!: Admitted["reject"];
|
||||
@@ -813,6 +970,7 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
state: "queued",
|
||||
outOfBandDeclined: false,
|
||||
saved: Promise.resolve(),
|
||||
persisted: false,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -820,7 +978,7 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
recipientId: string,
|
||||
activeTurnBehavior: AgentMessageBehavior,
|
||||
source: AgentPromptSource | null,
|
||||
): Pick<Receipt, "activeTurnBehavior" | "guidance"> {
|
||||
): Pick<AgentMessageReceipt, "activeTurnBehavior" | "guidance"> {
|
||||
return {
|
||||
activeTurnBehavior,
|
||||
guidance: describeAgentMessage({
|
||||
@@ -832,10 +990,29 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
};
|
||||
}
|
||||
|
||||
/** The store is called before this first yields, so saved order is admission order. */
|
||||
async function save(item: Admitted): Promise<void> {
|
||||
const { recipientId, id, urgency, held } = item;
|
||||
/** The store is called before this first yields (unless attachments are resolved lazily). */
|
||||
async function save(
|
||||
item: Admitted,
|
||||
insertBeforeId?: string,
|
||||
resolveAttachments?: () => Promise<AgentAttachment[]>,
|
||||
): Promise<void> {
|
||||
const { recipientId, id } = item;
|
||||
try {
|
||||
if (resolveAttachments) {
|
||||
item.attachments = [...(await resolveAttachments())];
|
||||
// A Stop, withdrawal, or archive during lazy attachment saving may have mutated or removed item.
|
||||
if (isWithdrawn(item) || item.state === "rejected") return;
|
||||
}
|
||||
if (!item.text.trim() && !item.attachments.length) {
|
||||
throw new Error("Agent message is empty");
|
||||
}
|
||||
const inboxMessages = inboxes.get(recipientId)?.messages;
|
||||
const itemIndex = inboxMessages ? inboxMessages.indexOf(item) : -1;
|
||||
const nextPersistedId =
|
||||
itemIndex >= 0
|
||||
? inboxMessages?.slice(itemIndex + 1).find((entry) => entry.persisted)?.id
|
||||
: undefined;
|
||||
const storeInsertBeforeId = nextPersistedId ?? insertBeforeId;
|
||||
const result = await store.enqueue({
|
||||
recipientId,
|
||||
id,
|
||||
@@ -848,12 +1025,14 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
unarchive: item.unarchive,
|
||||
clearPendingPermissions: item.clearPendingPermissions,
|
||||
fingerprint: item.fingerprint,
|
||||
urgency,
|
||||
held,
|
||||
urgency: item.urgency,
|
||||
held: item.held,
|
||||
...(storeInsertBeforeId ? { insertBeforeId: storeInsertBeforeId } : {}),
|
||||
});
|
||||
if (result.status === "conflict") throw new Error("agent_request_key_conflict");
|
||||
if (result.status === "full")
|
||||
throw new Error(`Agent ${recipientId} already has ${result.limit} queued messages`);
|
||||
item.persisted = true;
|
||||
// A dispatch the store never saw removed already reached the recipient.
|
||||
if (result.status === "duplicate" && result.record.state === "dispatching")
|
||||
claim(item, "turn_started");
|
||||
@@ -980,12 +1159,15 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
const saved = records.filter((record) => !admitted.has(record.id));
|
||||
if (!saved.length) return;
|
||||
const restored = saved.map(
|
||||
({ seq: _seq, state: _state, dispatchAttemptedAt: _at, ...record }) =>
|
||||
createAdmitted(
|
||||
({ seq: _seq, state: _state, dispatchAttemptedAt: _at, ...record }) => {
|
||||
const item = createAdmitted(
|
||||
record,
|
||||
{ urgency: record.urgency, held: record.held },
|
||||
receiptFor(recipientId, record.urgency ?? "queue", record.source),
|
||||
),
|
||||
);
|
||||
item.persisted = true;
|
||||
return item;
|
||||
},
|
||||
);
|
||||
const inbox = existing ?? emptyInbox();
|
||||
if (!existing && saved.every((record) => record.held)) inbox.phase = "held";
|
||||
@@ -1016,6 +1198,82 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
await Promise.all(writes);
|
||||
}
|
||||
|
||||
async function enqueueMessage(
|
||||
message: Message,
|
||||
options: {
|
||||
insertBeforeId?: string;
|
||||
resolveAttachments?: () => Promise<AgentAttachment[]>;
|
||||
} = {},
|
||||
): Promise<AgentMessageReceipt> {
|
||||
if (closed) throw new Error("Agent message delivery is closed");
|
||||
const { recipientId, fingerprint } = message;
|
||||
const { insertBeforeId, resolveAttachments } = options;
|
||||
const attachments = [...(message.attachments ?? [])];
|
||||
if (!message.text.trim() && !attachments.length && !resolveAttachments) {
|
||||
throw new Error("Agent message is empty");
|
||||
}
|
||||
const id = message.messageId ?? randomUUID();
|
||||
const queued = inboxes.get(recipientId)?.messages.find((entry) => entry.id === id);
|
||||
if (queued) {
|
||||
if (queued.fingerprint !== fingerprint) throw new Error("agent_request_key_conflict");
|
||||
await queued.saved;
|
||||
return queued.receipt;
|
||||
}
|
||||
const activeTurnBehavior = message.activeTurnBehavior ?? "queue";
|
||||
const source = message.source ?? null;
|
||||
const item = createAdmitted(
|
||||
{
|
||||
recipientId,
|
||||
id,
|
||||
enqueuedAt: new Date().toISOString(),
|
||||
text: message.text,
|
||||
attachments,
|
||||
source,
|
||||
sessionMode: message.sessionMode,
|
||||
providerSwitch: message.providerSwitch,
|
||||
unarchive: message.unarchive !== false,
|
||||
clearPendingPermissions: message.clearPendingPermissions === true,
|
||||
fingerprint,
|
||||
},
|
||||
{ urgency: activeTurnBehavior === "queue" ? null : activeTurnBehavior, held: false },
|
||||
receiptFor(recipientId, activeTurnBehavior, source),
|
||||
);
|
||||
item.beforeDispatch = message.beforeDispatch;
|
||||
item.onDispatch = message.onDispatch;
|
||||
// Admit into memory first so a lazy attachment resolver still preserves exact queue order.
|
||||
if (item.state === "queued") admit(item, insertBeforeId);
|
||||
item.saved = save(item, insertBeforeId, resolveAttachments);
|
||||
item.saved.catch(() => undefined);
|
||||
await item.saved;
|
||||
announceEnqueued(recipientId, id, source);
|
||||
return item.receipt;
|
||||
}
|
||||
|
||||
function enqueueDirect(input: {
|
||||
direct: DirectPrompt;
|
||||
insertBeforeId?: string;
|
||||
}): Promise<AgentMessageReceipt> {
|
||||
const { direct, insertBeforeId } = input;
|
||||
const { text, attachments } = directQueueContent(direct);
|
||||
return enqueueMessage(
|
||||
{
|
||||
recipientId: direct.recipientId,
|
||||
messageId: direct.messageId,
|
||||
source: direct.source,
|
||||
text,
|
||||
attachments,
|
||||
sessionMode: direct.sessionMode,
|
||||
providerSwitch: direct.providerSwitch,
|
||||
unarchive: direct.unarchive,
|
||||
clearPendingPermissions: direct.clearPendingPermissions,
|
||||
activeTurnBehavior: direct.activeTurnBehavior ?? "interrupt",
|
||||
fingerprint: direct.fingerprint,
|
||||
onDispatch: direct.onDispatch,
|
||||
},
|
||||
{ insertBeforeId, resolveAttachments: direct.resolveAttachments },
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
async start({ waitForResume } = {}) {
|
||||
const queues = new Map<string, PersistedQueuedMessage[]>();
|
||||
@@ -1043,52 +1301,27 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
);
|
||||
}
|
||||
},
|
||||
async enqueue(message) {
|
||||
if (closed) throw new Error("Agent message delivery is closed");
|
||||
const { recipientId, fingerprint } = message;
|
||||
const attachments = [...(message.attachments ?? [])];
|
||||
if (!message.text.trim() && !attachments.length) throw new Error("Agent message is empty");
|
||||
const id = message.messageId ?? randomUUID();
|
||||
const queued = inboxes.get(recipientId)?.messages.find((entry) => entry.id === id);
|
||||
if (queued) {
|
||||
if (queued.fingerprint !== fingerprint) throw new Error("agent_request_key_conflict");
|
||||
await queued.saved;
|
||||
return queued.receipt;
|
||||
}
|
||||
const activeTurnBehavior = message.activeTurnBehavior ?? "queue";
|
||||
const source = message.source ?? null;
|
||||
const item = createAdmitted(
|
||||
{
|
||||
recipientId,
|
||||
id,
|
||||
enqueuedAt: new Date().toISOString(),
|
||||
text: message.text,
|
||||
attachments,
|
||||
source,
|
||||
sessionMode: message.sessionMode,
|
||||
providerSwitch: message.providerSwitch,
|
||||
unarchive: message.unarchive !== false,
|
||||
clearPendingPermissions: message.clearPendingPermissions === true,
|
||||
fingerprint,
|
||||
},
|
||||
{ urgency: activeTurnBehavior === "queue" ? null : activeTurnBehavior, held: false },
|
||||
receiptFor(recipientId, activeTurnBehavior, source),
|
||||
);
|
||||
item.beforeDispatch = message.beforeDispatch;
|
||||
item.onDispatch = message.onDispatch;
|
||||
item.saved = save(item);
|
||||
item.saved.catch(() => undefined);
|
||||
// Its place is taken now, so a Stop or a prompt sent during the write finds it.
|
||||
if (item.state === "queued") admit(item);
|
||||
await item.saved;
|
||||
announceEnqueued(recipientId, id, source);
|
||||
return item.receipt;
|
||||
enqueue(message) {
|
||||
return enqueueMessage(message);
|
||||
},
|
||||
sendDirect<Result extends PromptDispatchResult>(
|
||||
async sendDirect<Result extends PromptDispatchResult>(
|
||||
direct: DirectPrompt,
|
||||
send: (joined: JoinedPrompt) => Promise<Result>,
|
||||
): Promise<Result> {
|
||||
): Promise<DirectSendResult<Result>> {
|
||||
const { recipientId } = direct;
|
||||
// A retried direct send whose earlier attempt was queued must return that queued entry
|
||||
// rather than coalescing with itself or interrupting the turn ahead of it.
|
||||
if (direct.messageId) {
|
||||
const existing = inboxes
|
||||
.get(recipientId)
|
||||
?.messages.find((entry) => entry.id === direct.messageId);
|
||||
if (existing) {
|
||||
if (existing.fingerprint !== direct.fingerprint)
|
||||
throw new Error("agent_request_key_conflict");
|
||||
await existing.saved;
|
||||
return { disposition: "queued", receipt: existing.receipt };
|
||||
}
|
||||
}
|
||||
// Its place in line is decided now: what is queued goes with it, what comes later follows.
|
||||
// A queued provider switch, and what follows it, waits for the turn this prompt starts.
|
||||
const takesQueue = !closed && !direct.resumesTurn && !isCommand(direct.prompt);
|
||||
@@ -1097,15 +1330,36 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
const ahead = beforeSwitch(queued);
|
||||
const behind = queued.slice(ahead.length);
|
||||
const stopped = inbox ? watchForStop(inbox) : () => false;
|
||||
return new Promise<Result>((resolve, reject) => {
|
||||
|
||||
// When queued messages ahead of this prompt cross a boundary (conflicting sessionMode or
|
||||
// queued non-agent command), insert this prompt immediately after `ahead` with urgency so
|
||||
// the earlier group runs first under its own mode and this prompt follows on its own turn
|
||||
// before any queued provider switch or later arrival.
|
||||
if (takesQueue && !canCoalesceDirect({ ahead: ahead.filter(isQueued), direct })) {
|
||||
const receipt = await enqueueDirect({ direct, insertBeforeId: behind[0]?.id });
|
||||
return { disposition: "queued", receipt };
|
||||
}
|
||||
|
||||
return new Promise<DirectSendResult<Result>>((resolve, reject) => {
|
||||
run(recipientId, async () => {
|
||||
let riders: Admitted[] = [];
|
||||
let result: Result;
|
||||
try {
|
||||
const dispatching = await markDispatching(
|
||||
recipientId,
|
||||
await prepare(recipientId, ahead),
|
||||
);
|
||||
const pending = closed ? [] : await prepare(recipientId, ahead);
|
||||
if (
|
||||
!closed &&
|
||||
takesQueue &&
|
||||
!canCoalesceDirect({ ahead: messagesOf(pending), direct })
|
||||
) {
|
||||
const aheadSet = new Set(ahead);
|
||||
const insertBeforeId = inboxes
|
||||
.get(recipientId)
|
||||
?.messages.find((entry) => !aheadSet.has(entry))?.id;
|
||||
const receipt = await enqueueDirect({ direct, insertBeforeId });
|
||||
resolve({ disposition: "queued", receipt });
|
||||
return;
|
||||
}
|
||||
const dispatching = await markDispatching(recipientId, pending);
|
||||
riders = messagesOf(dispatching);
|
||||
for (const message of riders) message.state = "claimed";
|
||||
for (const message of riders) message.beforeDispatch?.();
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
import { mkdtemp, rm } from "node:fs/promises";
|
||||
import { access, mkdtemp, rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { expect, onTestFinished, test } from "vitest";
|
||||
import { createTestLogger } from "../../../test-utils/test-logger.js";
|
||||
import { openDaemonDatabase, type DaemonDatabase } from "../../database/index.js";
|
||||
import { AgentTurnStartRejectedError } from "../agent-prompt.js";
|
||||
import type { AgentPromptInput, AgentTimelineItem } from "../agent-sdk-types.js";
|
||||
import {
|
||||
agentMessageQueueSchema,
|
||||
createAgentMessageDelivery,
|
||||
createJsonAgentMessageQueueStore,
|
||||
createSqliteAgentMessageQueueStore,
|
||||
MAX_AGENT_QUEUE_DEPTH,
|
||||
projectAgentMessages,
|
||||
type AgentMessageDelivery,
|
||||
@@ -21,6 +24,23 @@ async function createHome(): Promise<string> {
|
||||
return paseoHome;
|
||||
}
|
||||
|
||||
const openDatabases: DaemonDatabase[] = [];
|
||||
|
||||
function openQueueDatabase(paseoHome: string): DaemonDatabase {
|
||||
const database = openDaemonDatabase({
|
||||
path: join(paseoHome, "paseo.db"),
|
||||
modules: [agentMessageQueueSchema],
|
||||
logger: createTestLogger(),
|
||||
});
|
||||
openDatabases.push(database);
|
||||
onTestFinished(() => {
|
||||
database.close();
|
||||
const index = openDatabases.indexOf(database);
|
||||
if (index >= 0) openDatabases.splice(index, 1);
|
||||
});
|
||||
return database;
|
||||
}
|
||||
|
||||
interface DaemonOptions {
|
||||
running?: boolean;
|
||||
/** The provider takes the prompt and the daemon dies before hearing back. */
|
||||
@@ -58,9 +78,10 @@ function trackWrites(store: AgentMessageQueueStore) {
|
||||
return { store: tracked, settle };
|
||||
}
|
||||
|
||||
/** One daemon process over the queue files in `paseoHome`. Open another to restart it. */
|
||||
/** One daemon process over `paseo.db` in `paseoHome`. Open another to restart it. */
|
||||
function openDaemon(paseoHome: string, options: DaemonOptions = {}) {
|
||||
const { store, settle } = trackWrites(createJsonAgentMessageQueueStore(paseoHome));
|
||||
const database = openQueueDatabase(paseoHome);
|
||||
const { store, settle } = trackWrites(createSqliteAgentMessageQueueStore(database));
|
||||
const sent: Array<{ ids: readonly string[]; behavior: string; prompt: AgentPromptInput }> = [];
|
||||
const withdrawn: string[] = [];
|
||||
const errors: unknown[] = [];
|
||||
@@ -443,3 +464,36 @@ test("a message that cannot be read is dropped instead of blocking the ones behi
|
||||
expect(await daemon.saved("parent")).toEqual([]);
|
||||
await daemon.delivery.close();
|
||||
});
|
||||
|
||||
test("splitting an urgent release persists the urgency downgrade so a restart waits for the resumed turn", async () => {
|
||||
const home = await createHome();
|
||||
const first = openDaemon(home, { running: true });
|
||||
const planned = await queue(first.delivery, "plan-1", {
|
||||
sessionMode: "plan",
|
||||
activeTurnBehavior: "queue",
|
||||
});
|
||||
await queue(first.delivery, "direct-1", {
|
||||
sessionMode: "bypassPermissions",
|
||||
activeTurnBehavior: "interrupt",
|
||||
});
|
||||
await expect(planned.dispatched).resolves.toBe("turn_started");
|
||||
await first.settle();
|
||||
|
||||
expect(first.sent.map(({ ids }) => ids)).toEqual([["plan-1"]]);
|
||||
expect(await first.delivery.list("parent")).toMatchObject({
|
||||
held: false,
|
||||
items: [{ id: "direct-1", urgency: null, state: "queued" }],
|
||||
});
|
||||
await first.delivery.close();
|
||||
|
||||
// After restart while the first group's turn is running, direct-1 must NOT interrupt it.
|
||||
await expect(access(join(home, "agent-queues"))).rejects.toMatchObject({ code: "ENOENT" });
|
||||
const second = openDaemon(home, { running: true });
|
||||
await second.delivery.start();
|
||||
await second.settle();
|
||||
expect(second.sent).toEqual([]);
|
||||
|
||||
await second.endTurn();
|
||||
expect(second.sent.map(({ ids }) => ids)).toEqual([["direct-1"]]);
|
||||
await second.delivery.close();
|
||||
});
|
||||
|
||||
@@ -20,5 +20,8 @@ export {
|
||||
type QueuedMessageUrgency,
|
||||
type WithdrawStoreResult,
|
||||
} from "./store.js";
|
||||
export { createJsonAgentMessageQueueStore, type CorruptQueueFile } from "./internal/json-store.js";
|
||||
export { createMemoryAgentMessageQueueStore } from "./internal/memory-store.js";
|
||||
export {
|
||||
agentMessageQueueSchema,
|
||||
createSqliteAgentMessageQueueStore,
|
||||
} from "./internal/sqlite-store.js";
|
||||
|
||||
@@ -1,220 +0,0 @@
|
||||
import { readdir, readFile, rename, rm } from "node:fs/promises";
|
||||
import { basename, dirname, join, resolve } from "node:path";
|
||||
import { AgentAttachmentSchema, QueuedProviderSwitchSchema } from "@getpaseo/protocol/messages";
|
||||
import { z } from "zod";
|
||||
import { writeJsonFileAtomic } from "../../../atomic-file.js";
|
||||
import { agentPromptSourceSchema } from "../envelope.js";
|
||||
import type { AgentMessageQueueStore } from "../store.js";
|
||||
import {
|
||||
assertValidRecipientId,
|
||||
clearQueue,
|
||||
cloneQueuedMessage,
|
||||
createEmptyRecipientQueueState,
|
||||
createKeyedSerializer,
|
||||
enqueueIntoQueue,
|
||||
markDispatchingInQueue,
|
||||
markHeldInQueue,
|
||||
promoteInQueue,
|
||||
removeFromQueue,
|
||||
revertDispatchingInQueue,
|
||||
sortAllQueuedMessages,
|
||||
sortQueuedMessages,
|
||||
withdrawFromQueue,
|
||||
type RecipientQueueState,
|
||||
type TransitionOutcome,
|
||||
} from "./queue-state.js";
|
||||
|
||||
const PersistedQueuedMessageSchema = z.object({
|
||||
id: z.string().min(1),
|
||||
recipientId: z.string().min(1),
|
||||
seq: z.number().int().positive(),
|
||||
enqueuedAt: z.string().min(1),
|
||||
text: z.string(),
|
||||
attachments: z.array(AgentAttachmentSchema),
|
||||
source: agentPromptSourceSchema.nullable(),
|
||||
sessionMode: z.string().min(1).optional(),
|
||||
providerSwitch: QueuedProviderSwitchSchema.optional(),
|
||||
unarchive: z.boolean(),
|
||||
clearPendingPermissions: z.boolean(),
|
||||
urgency: z.enum(["steer", "interrupt"]).nullable(),
|
||||
held: z.boolean(),
|
||||
state: z.enum(["queued", "dispatching"]),
|
||||
dispatchAttemptedAt: z.string().min(1).optional(),
|
||||
fingerprint: z.string().optional(),
|
||||
});
|
||||
|
||||
const PersistedRecipientQueueFileSchema = z.object({
|
||||
version: z.literal(1),
|
||||
nextSeq: z.number().int().positive(),
|
||||
items: z.array(PersistedQueuedMessageSchema),
|
||||
});
|
||||
|
||||
/** The file is there and readable, but does not hold this recipient's queue. */
|
||||
class CorruptQueueFileError extends Error {
|
||||
constructor(
|
||||
readonly filePath: string,
|
||||
cause: unknown,
|
||||
) {
|
||||
super(cause instanceof Error ? cause.message : String(cause), { cause });
|
||||
this.name = "CorruptQueueFileError";
|
||||
}
|
||||
}
|
||||
|
||||
/** A queue file that could not be read, and where it was moved to. */
|
||||
export interface CorruptQueueFile {
|
||||
recipientId: string;
|
||||
movedTo: string;
|
||||
error: unknown;
|
||||
}
|
||||
|
||||
/** Creates a per-agent atomic JSON file `AgentMessageQueueStore` under `$PASEO_HOME/agent-queues/`. */
|
||||
export function createJsonAgentMessageQueueStore(
|
||||
paseoHome: string,
|
||||
options: { onCorruptFile?: (file: CorruptQueueFile) => void } = {},
|
||||
): AgentMessageQueueStore {
|
||||
const queuesDir = resolve(join(paseoHome, "agent-queues"));
|
||||
const cache = new Map<string, RecipientQueueState>();
|
||||
const serializer = createKeyedSerializer();
|
||||
|
||||
function recipientFilePath(recipientId: string): string {
|
||||
assertValidRecipientId(recipientId);
|
||||
const filePath = resolve(queuesDir, `${recipientId}.json`);
|
||||
if (dirname(filePath) !== queuesDir || basename(filePath) !== `${recipientId}.json`) {
|
||||
throw new Error(`Invalid agent queue recipient id: ${recipientId}`);
|
||||
}
|
||||
return filePath;
|
||||
}
|
||||
|
||||
async function loadRecipient(recipientId: string): Promise<RecipientQueueState> {
|
||||
const cached = cache.get(recipientId);
|
||||
if (cached) {
|
||||
return cached;
|
||||
}
|
||||
|
||||
const filePath = recipientFilePath(recipientId);
|
||||
let raw: string;
|
||||
try {
|
||||
raw = await readFile(filePath, "utf8");
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
|
||||
return createEmptyRecipientQueueState();
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
let parsed: z.infer<typeof PersistedRecipientQueueFileSchema>;
|
||||
try {
|
||||
parsed = PersistedRecipientQueueFileSchema.parse(JSON.parse(raw));
|
||||
for (const item of parsed.items) {
|
||||
if (item.recipientId !== recipientId) {
|
||||
throw new Error(
|
||||
`Mismatched recipientId in ${filePath}: expected ${recipientId}, found ${item.recipientId}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
throw new CorruptQueueFileError(filePath, error);
|
||||
}
|
||||
|
||||
const items = sortQueuedMessages(parsed.items.map(cloneQueuedMessage));
|
||||
const maxItemSeq = items.reduce((max, item) => Math.max(max, item.seq), 0);
|
||||
const state: RecipientQueueState = {
|
||||
nextSeq: Math.max(parsed.nextSeq, maxItemSeq + 1),
|
||||
items,
|
||||
};
|
||||
cache.set(recipientId, state);
|
||||
return state;
|
||||
}
|
||||
|
||||
/** Keeps the unreadable file for inspection and frees its name for new messages. */
|
||||
async function setAside(recipientId: string, error: CorruptQueueFileError): Promise<void> {
|
||||
const movedTo = `${error.filePath}.corrupt.${Date.now()}`;
|
||||
await rename(error.filePath, movedTo);
|
||||
options.onCorruptFile?.({ recipientId, movedTo, error: error.cause });
|
||||
}
|
||||
|
||||
async function persistRecipient(recipientId: string, state: RecipientQueueState): Promise<void> {
|
||||
const filePath = recipientFilePath(recipientId);
|
||||
if (state.items.length === 0) {
|
||||
await rm(filePath, { force: true });
|
||||
return;
|
||||
}
|
||||
await writeJsonFileAtomic(filePath, {
|
||||
version: 1,
|
||||
nextSeq: state.nextSeq,
|
||||
items: state.items,
|
||||
});
|
||||
}
|
||||
|
||||
async function mutate<Result>(
|
||||
recipientId: string,
|
||||
transition: (current: RecipientQueueState) => TransitionOutcome<Result>,
|
||||
): Promise<Result> {
|
||||
assertValidRecipientId(recipientId);
|
||||
return serializer.run(recipientId, async () => {
|
||||
const current = await loadRecipient(recipientId);
|
||||
const outcome = transition(current);
|
||||
if (outcome.changed) {
|
||||
await persistRecipient(recipientId, outcome.nextState);
|
||||
cache.set(recipientId, outcome.nextState);
|
||||
}
|
||||
return outcome.result;
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
async listAll() {
|
||||
await serializer.drainAll();
|
||||
let entries;
|
||||
try {
|
||||
entries = await readdir(queuesDir, { withFileTypes: true });
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
|
||||
return [];
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
const recipientIds = entries
|
||||
.filter(
|
||||
(entry) => entry.isFile() && entry.name.endsWith(".json") && !entry.name.startsWith("."),
|
||||
)
|
||||
.map((entry) => entry.name.slice(0, -".json".length));
|
||||
|
||||
const lists = await Promise.all(
|
||||
recipientIds.map((recipientId) =>
|
||||
serializer.run(recipientId, async () => {
|
||||
try {
|
||||
const state = await loadRecipient(recipientId);
|
||||
return state.items.map(cloneQueuedMessage);
|
||||
} catch (error) {
|
||||
// One bad file must not keep the daemon from starting.
|
||||
if (!(error instanceof CorruptQueueFileError)) throw error;
|
||||
await setAside(recipientId, error);
|
||||
return [];
|
||||
}
|
||||
}),
|
||||
),
|
||||
);
|
||||
return sortAllQueuedMessages(lists.flat());
|
||||
},
|
||||
async listByRecipient(recipientId) {
|
||||
assertValidRecipientId(recipientId);
|
||||
return serializer.run(recipientId, async () => {
|
||||
const state = await loadRecipient(recipientId);
|
||||
return state.items.map(cloneQueuedMessage);
|
||||
});
|
||||
},
|
||||
enqueue: (input) => mutate(input.recipientId, (current) => enqueueIntoQueue(current, input)),
|
||||
markDispatching: (recipientId, ids, attemptedAt) =>
|
||||
mutate(recipientId, (current) => markDispatchingInQueue(current, ids, attemptedAt)),
|
||||
revertDispatching: (recipientId, ids) =>
|
||||
mutate(recipientId, (current) => revertDispatchingInQueue(current, ids)),
|
||||
markHeld: (recipientId) => mutate(recipientId, (current) => markHeldInQueue(current)),
|
||||
promote: (recipientId, targetId, urgency) =>
|
||||
mutate(recipientId, (current) => promoteInQueue(current, targetId, urgency)),
|
||||
withdraw: (recipientId, id) => mutate(recipientId, (current) => withdrawFromQueue(current, id)),
|
||||
remove: (recipientId, ids) => mutate(recipientId, (current) => removeFromQueue(current, ids)),
|
||||
clearRecipient: (recipientId) => mutate(recipientId, (current) => clearQueue(current)),
|
||||
};
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import type { AgentMessageQueueStore, PersistedQueuedMessage } from "../store.js
|
||||
import {
|
||||
assertValidRecipientId,
|
||||
clearQueue,
|
||||
clearUrgencyInQueue,
|
||||
cloneQueuedMessage,
|
||||
createEmptyRecipientQueueState,
|
||||
createKeyedSerializer,
|
||||
@@ -61,6 +62,8 @@ export function createMemoryAgentMessageQueueStore(): AgentMessageQueueStore {
|
||||
revertDispatching: (recipientId, ids) =>
|
||||
mutate(recipientId, (current) => revertDispatchingInQueue(current, ids)),
|
||||
markHeld: (recipientId) => mutate(recipientId, (current) => markHeldInQueue(current)),
|
||||
clearUrgency: (recipientId, ids) =>
|
||||
mutate(recipientId, (current) => clearUrgencyInQueue(current, ids)),
|
||||
promote: (recipientId, targetId, urgency) =>
|
||||
mutate(recipientId, (current) => promoteInQueue(current, targetId, urgency)),
|
||||
withdraw: (recipientId, id) => mutate(recipientId, (current) => withdrawFromQueue(current, id)),
|
||||
|
||||
@@ -134,10 +134,19 @@ export function enqueueIntoQueue(
|
||||
};
|
||||
}
|
||||
|
||||
const insertIndex = input.insertBeforeId
|
||||
? current.items.findIndex((item) => item.id === input.insertBeforeId)
|
||||
: -1;
|
||||
const items = current.items.map(cloneQueuedMessage);
|
||||
let seq = current.nextSeq;
|
||||
if (insertIndex >= 0) {
|
||||
seq = items[insertIndex]!.seq;
|
||||
}
|
||||
|
||||
const record: PersistedQueuedMessage = {
|
||||
id: input.id,
|
||||
recipientId: input.recipientId,
|
||||
seq: current.nextSeq,
|
||||
seq,
|
||||
enqueuedAt: input.enqueuedAt,
|
||||
text: input.text,
|
||||
attachments: structuredClone(input.attachments),
|
||||
@@ -154,10 +163,26 @@ export function enqueueIntoQueue(
|
||||
...(input.fingerprint !== undefined ? { fingerprint: input.fingerprint } : {}),
|
||||
};
|
||||
|
||||
if (insertIndex >= 0) {
|
||||
items.splice(insertIndex, 0, record);
|
||||
for (let index = insertIndex + 1; index < items.length; index += 1) {
|
||||
items[index]!.seq = Math.max(items[index]!.seq, items[index - 1]!.seq + 1);
|
||||
}
|
||||
const maxSeq = items[items.length - 1]!.seq;
|
||||
return {
|
||||
nextState: {
|
||||
nextSeq: Math.max(current.nextSeq + 1, maxSeq + 1),
|
||||
items,
|
||||
},
|
||||
changed: true,
|
||||
result: { status: "inserted", record: cloneQueuedMessage(record) },
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
nextState: {
|
||||
nextSeq: current.nextSeq + 1,
|
||||
items: sortQueuedMessages([...current.items.map(cloneQueuedMessage), record]),
|
||||
items: sortQueuedMessages([...items, record]),
|
||||
},
|
||||
changed: true,
|
||||
result: { status: "inserted", record: cloneQueuedMessage(record) },
|
||||
@@ -234,6 +259,36 @@ export function revertDispatchingInQueue(
|
||||
};
|
||||
}
|
||||
|
||||
export function clearUrgencyInQueue(
|
||||
current: RecipientQueueState,
|
||||
ids: readonly string[],
|
||||
): TransitionOutcome<void> {
|
||||
if (ids.length === 0 || current.items.length === 0) {
|
||||
return { nextState: current, changed: false, result: undefined };
|
||||
}
|
||||
|
||||
const targetIds = new Set(ids);
|
||||
let changed = false;
|
||||
const nextItems = current.items.map((item) => {
|
||||
const copy = cloneQueuedMessage(item);
|
||||
if (targetIds.has(copy.id) && copy.urgency !== null) {
|
||||
copy.urgency = null;
|
||||
changed = true;
|
||||
}
|
||||
return copy;
|
||||
});
|
||||
|
||||
if (!changed) {
|
||||
return { nextState: current, changed: false, result: undefined };
|
||||
}
|
||||
|
||||
return {
|
||||
nextState: { nextSeq: current.nextSeq, items: nextItems },
|
||||
changed: true,
|
||||
result: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
export function markHeldInQueue(
|
||||
current: RecipientQueueState,
|
||||
): TransitionOutcome<PersistedQueuedMessage[]> {
|
||||
|
||||
@@ -0,0 +1,507 @@
|
||||
import type { AgentAttachment, QueuedProviderSwitch } from "@getpaseo/protocol/messages";
|
||||
import type { DaemonDatabase, SchemaModule, WriteSql } from "../../../database/index.js";
|
||||
import type { AgentPromptSource } from "../envelope.js";
|
||||
import {
|
||||
MAX_AGENT_QUEUE_DEPTH,
|
||||
type AgentMessageQueueStore,
|
||||
type EnqueueStoreInput,
|
||||
type EnqueueStoreResult,
|
||||
type PersistedQueuedMessage,
|
||||
type PromoteStoreResult,
|
||||
type QueuedMessageState,
|
||||
type QueuedMessageUrgency,
|
||||
type WithdrawStoreResult,
|
||||
} from "../store.js";
|
||||
import { assertValidRecipientId, cloneQueuedMessage, sortQueuedMessages } from "./queue-state.js";
|
||||
|
||||
/**
|
||||
* Tables of the agent message queue store.
|
||||
*
|
||||
* `agent_message_queue_recipients` holds the monotonic `next_seq` counter per recipient so
|
||||
* sequence numbers never regress across withdrawals, removals, clears, or daemon restarts.
|
||||
*
|
||||
* `agent_message_queue_items` holds undelivered messages. Caller-supplied strings (`id_json`,
|
||||
* `text_json`, `session_mode_json`, `fingerprint_json`) and structured payloads
|
||||
* (`attachments_json`, `source_json`, `provider_switch_json`) are stored as JSON strings because
|
||||
* `node:sqlite` truncates raw `TEXT` values at the first NUL byte and replaces lone surrogates
|
||||
* with U+FFFD during UTF-8 conversion.
|
||||
*/
|
||||
const SCHEMA_V1 = `
|
||||
CREATE TABLE agent_message_queue_recipients (
|
||||
recipient_id TEXT PRIMARY KEY,
|
||||
next_seq INTEGER NOT NULL CHECK (next_seq >= 1)
|
||||
);
|
||||
|
||||
CREATE TABLE agent_message_queue_items (
|
||||
recipient_id TEXT NOT NULL REFERENCES agent_message_queue_recipients (recipient_id) ON DELETE CASCADE,
|
||||
id_json TEXT NOT NULL,
|
||||
seq INTEGER NOT NULL CHECK (seq >= 1),
|
||||
enqueued_at TEXT NOT NULL,
|
||||
text_json TEXT NOT NULL,
|
||||
attachments_json TEXT NOT NULL,
|
||||
source_json TEXT,
|
||||
session_mode_json TEXT,
|
||||
provider_switch_json TEXT,
|
||||
unarchive INTEGER NOT NULL CHECK (unarchive IN (0, 1)),
|
||||
clear_pending_permissions INTEGER NOT NULL CHECK (clear_pending_permissions IN (0, 1)),
|
||||
urgency TEXT CHECK (urgency IS NULL OR urgency IN ('steer', 'interrupt')),
|
||||
held INTEGER NOT NULL CHECK (held IN (0, 1)),
|
||||
state TEXT NOT NULL CHECK (state IN ('queued', 'dispatching')),
|
||||
dispatch_attempted_at TEXT,
|
||||
fingerprint_json TEXT,
|
||||
PRIMARY KEY (recipient_id, id_json),
|
||||
UNIQUE (recipient_id, seq)
|
||||
);
|
||||
`;
|
||||
|
||||
/** The agent message queue store's schema in the daemon database. */
|
||||
export const agentMessageQueueSchema: SchemaModule = {
|
||||
name: "agent_message_queues",
|
||||
migrations: [{ up: (sql) => sql.exec(SCHEMA_V1) }],
|
||||
};
|
||||
|
||||
interface QueueItemRow {
|
||||
recipient_id: string;
|
||||
id_json: string;
|
||||
seq: number;
|
||||
enqueued_at: string;
|
||||
text_json: string;
|
||||
attachments_json: string;
|
||||
source_json: string | null;
|
||||
session_mode_json: string | null;
|
||||
provider_switch_json: string | null;
|
||||
unarchive: number;
|
||||
clear_pending_permissions: number;
|
||||
urgency: QueuedMessageUrgency | null;
|
||||
held: number;
|
||||
state: QueuedMessageState;
|
||||
dispatch_attempted_at: string | null;
|
||||
fingerprint_json: string | null;
|
||||
}
|
||||
|
||||
const ITEM_COLUMNS =
|
||||
"recipient_id, id_json, seq, enqueued_at, text_json, attachments_json, source_json, " +
|
||||
"session_mode_json, provider_switch_json, unarchive, clear_pending_permissions, urgency, held, " +
|
||||
"state, dispatch_attempted_at, fingerprint_json";
|
||||
|
||||
function encodeText(value: string): string {
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
|
||||
function decodeText(value: string): string {
|
||||
return JSON.parse(value) as string;
|
||||
}
|
||||
|
||||
function deserializeRow(row: QueueItemRow): PersistedQueuedMessage {
|
||||
const record: PersistedQueuedMessage = {
|
||||
id: decodeText(row.id_json),
|
||||
recipientId: row.recipient_id,
|
||||
seq: row.seq,
|
||||
enqueuedAt: row.enqueued_at,
|
||||
text: decodeText(row.text_json),
|
||||
attachments: JSON.parse(row.attachments_json) as AgentAttachment[],
|
||||
source: row.source_json === null ? null : (JSON.parse(row.source_json) as AgentPromptSource),
|
||||
unarchive: row.unarchive === 1,
|
||||
clearPendingPermissions: row.clear_pending_permissions === 1,
|
||||
urgency: row.urgency,
|
||||
held: row.held === 1,
|
||||
state: row.state,
|
||||
};
|
||||
if (row.session_mode_json !== null) {
|
||||
record.sessionMode = decodeText(row.session_mode_json);
|
||||
}
|
||||
if (row.provider_switch_json !== null) {
|
||||
record.providerSwitch = JSON.parse(row.provider_switch_json) as QueuedProviderSwitch;
|
||||
}
|
||||
if (row.dispatch_attempted_at !== null) {
|
||||
record.dispatchAttemptedAt = row.dispatch_attempted_at;
|
||||
}
|
||||
if (row.fingerprint_json !== null) {
|
||||
record.fingerprint = decodeText(row.fingerprint_json);
|
||||
}
|
||||
return record;
|
||||
}
|
||||
|
||||
function allocateSequence(input: {
|
||||
sql: WriteSql;
|
||||
recipientId: string;
|
||||
insertBeforeId: string | undefined;
|
||||
}): { seq: number; nextSeq: number } {
|
||||
const { sql, recipientId, insertBeforeId } = input;
|
||||
const recipientRow = sql.get<{ next_seq: number }>(
|
||||
"SELECT next_seq FROM agent_message_queue_recipients WHERE recipient_id = ?",
|
||||
recipientId,
|
||||
);
|
||||
const currentNextSeq = recipientRow?.next_seq ?? 1;
|
||||
const targetRow = insertBeforeId
|
||||
? sql.get<{ seq: number }>(
|
||||
"SELECT seq FROM agent_message_queue_items WHERE recipient_id = ? AND id_json = ?",
|
||||
recipientId,
|
||||
encodeText(insertBeforeId),
|
||||
)
|
||||
: undefined;
|
||||
|
||||
if (!targetRow) {
|
||||
return { seq: currentNextSeq, nextSeq: currentNextSeq + 1 };
|
||||
}
|
||||
|
||||
const tailRows = sql.all<{ id_json: string; seq: number }>(
|
||||
"SELECT id_json, seq FROM agent_message_queue_items " +
|
||||
"WHERE recipient_id = ? AND seq >= ? ORDER BY seq ASC",
|
||||
recipientId,
|
||||
targetRow.seq,
|
||||
);
|
||||
let previousSeq = targetRow.seq;
|
||||
const shifts: Array<{ idJson: string; nextSeq: number }> = [];
|
||||
for (const item of tailRows) {
|
||||
const shiftedSeq = Math.max(item.seq, previousSeq + 1);
|
||||
if (shiftedSeq !== item.seq) {
|
||||
shifts.push({ idJson: item.id_json, nextSeq: shiftedSeq });
|
||||
}
|
||||
previousSeq = shiftedSeq;
|
||||
}
|
||||
// Shift in descending seq order so UNIQUE (recipient_id, seq) holds at every step.
|
||||
for (let index = shifts.length - 1; index >= 0; index -= 1) {
|
||||
const shift = shifts[index]!;
|
||||
sql.run(
|
||||
"UPDATE agent_message_queue_items SET seq = ? WHERE recipient_id = ? AND id_json = ?",
|
||||
shift.nextSeq,
|
||||
recipientId,
|
||||
shift.idJson,
|
||||
);
|
||||
}
|
||||
return {
|
||||
seq: targetRow.seq,
|
||||
nextSeq: Math.max(currentNextSeq + 1, previousSeq + 1),
|
||||
};
|
||||
}
|
||||
|
||||
function buildInsertedRecord(input: {
|
||||
message: EnqueueStoreInput;
|
||||
seq: number;
|
||||
}): PersistedQueuedMessage {
|
||||
const { message, seq } = input;
|
||||
const record: PersistedQueuedMessage = {
|
||||
id: message.id,
|
||||
recipientId: message.recipientId,
|
||||
seq,
|
||||
enqueuedAt: message.enqueuedAt,
|
||||
text: message.text,
|
||||
attachments: structuredClone(message.attachments),
|
||||
source: message.source ? structuredClone(message.source) : null,
|
||||
unarchive: message.unarchive,
|
||||
clearPendingPermissions: message.clearPendingPermissions,
|
||||
urgency: message.urgency,
|
||||
held: message.held,
|
||||
state: "queued",
|
||||
};
|
||||
if (message.sessionMode !== undefined) {
|
||||
record.sessionMode = message.sessionMode;
|
||||
}
|
||||
if (message.providerSwitch !== undefined) {
|
||||
record.providerSwitch = structuredClone(message.providerSwitch);
|
||||
}
|
||||
if (message.fingerprint !== undefined) {
|
||||
record.fingerprint = message.fingerprint;
|
||||
}
|
||||
return record;
|
||||
}
|
||||
|
||||
function insertQueueRow(input: { sql: WriteSql; record: PersistedQueuedMessage }): void {
|
||||
const { sql, record } = input;
|
||||
sql.run(
|
||||
`INSERT INTO agent_message_queue_items (${ITEM_COLUMNS}) ` +
|
||||
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
|
||||
record.recipientId,
|
||||
encodeText(record.id),
|
||||
record.seq,
|
||||
record.enqueuedAt,
|
||||
encodeText(record.text),
|
||||
JSON.stringify(record.attachments),
|
||||
record.source === null ? null : JSON.stringify(record.source),
|
||||
record.sessionMode === undefined ? null : encodeText(record.sessionMode),
|
||||
record.providerSwitch === undefined ? null : JSON.stringify(record.providerSwitch),
|
||||
record.unarchive ? 1 : 0,
|
||||
record.clearPendingPermissions ? 1 : 0,
|
||||
record.urgency,
|
||||
record.held ? 1 : 0,
|
||||
record.state,
|
||||
null,
|
||||
record.fingerprint === undefined ? null : encodeText(record.fingerprint),
|
||||
);
|
||||
}
|
||||
|
||||
function enqueueInTransaction(input: {
|
||||
sql: WriteSql;
|
||||
message: EnqueueStoreInput;
|
||||
}): EnqueueStoreResult {
|
||||
const { sql, message } = input;
|
||||
const existingRow = sql.get<QueueItemRow>(
|
||||
`SELECT ${ITEM_COLUMNS} FROM agent_message_queue_items WHERE recipient_id = ? AND id_json = ?`,
|
||||
message.recipientId,
|
||||
encodeText(message.id),
|
||||
);
|
||||
if (existingRow) {
|
||||
const existing = deserializeRow(existingRow);
|
||||
if (existing.fingerprint !== message.fingerprint) {
|
||||
return { status: "conflict" };
|
||||
}
|
||||
return { status: "duplicate", record: existing };
|
||||
}
|
||||
|
||||
const countRow = sql.get<{ count: number }>(
|
||||
"SELECT COUNT(*) AS count FROM agent_message_queue_items WHERE recipient_id = ?",
|
||||
message.recipientId,
|
||||
);
|
||||
if ((countRow?.count ?? 0) >= MAX_AGENT_QUEUE_DEPTH) {
|
||||
return { status: "full", limit: MAX_AGENT_QUEUE_DEPTH };
|
||||
}
|
||||
|
||||
const { seq, nextSeq } = allocateSequence({
|
||||
sql,
|
||||
recipientId: message.recipientId,
|
||||
insertBeforeId: message.insertBeforeId,
|
||||
});
|
||||
|
||||
sql.run(
|
||||
"INSERT INTO agent_message_queue_recipients (recipient_id, next_seq) VALUES (?, ?) " +
|
||||
"ON CONFLICT (recipient_id) DO UPDATE SET next_seq = excluded.next_seq",
|
||||
message.recipientId,
|
||||
nextSeq,
|
||||
);
|
||||
|
||||
const record = buildInsertedRecord({ message, seq });
|
||||
insertQueueRow({ sql, record });
|
||||
return { status: "inserted", record };
|
||||
}
|
||||
|
||||
/**
|
||||
* Durable SQLite `AgentMessageQueueStore` backed by the daemon database.
|
||||
* Open the database with `agentMessageQueueSchema`.
|
||||
*/
|
||||
export function createSqliteAgentMessageQueueStore(
|
||||
database: DaemonDatabase,
|
||||
): AgentMessageQueueStore {
|
||||
return {
|
||||
async listAll(): Promise<PersistedQueuedMessage[]> {
|
||||
return database.read((sql) =>
|
||||
sql
|
||||
.all<QueueItemRow>(
|
||||
`SELECT ${ITEM_COLUMNS} FROM agent_message_queue_items ORDER BY recipient_id ASC, seq ASC`,
|
||||
)
|
||||
.map(deserializeRow),
|
||||
);
|
||||
},
|
||||
|
||||
async listByRecipient(recipientId: string): Promise<PersistedQueuedMessage[]> {
|
||||
assertValidRecipientId(recipientId);
|
||||
return database.read((sql) =>
|
||||
sql
|
||||
.all<QueueItemRow>(
|
||||
`SELECT ${ITEM_COLUMNS} FROM agent_message_queue_items WHERE recipient_id = ? ORDER BY seq ASC`,
|
||||
recipientId,
|
||||
)
|
||||
.map(deserializeRow),
|
||||
);
|
||||
},
|
||||
|
||||
async enqueue(input: EnqueueStoreInput): Promise<EnqueueStoreResult> {
|
||||
assertValidRecipientId(input.recipientId);
|
||||
if (!input.id) {
|
||||
throw new Error("Queued message id must be non-empty");
|
||||
}
|
||||
if (!input.enqueuedAt) {
|
||||
throw new Error("Queued message enqueuedAt must be non-empty");
|
||||
}
|
||||
return database.write((sql) => enqueueInTransaction({ sql, message: input }));
|
||||
},
|
||||
|
||||
async markDispatching(
|
||||
recipientId: string,
|
||||
ids: readonly string[],
|
||||
attemptedAt: string,
|
||||
): Promise<PersistedQueuedMessage[]> {
|
||||
assertValidRecipientId(recipientId);
|
||||
if (ids.length === 0) {
|
||||
return [];
|
||||
}
|
||||
return database.write((sql) => {
|
||||
const hasItems = sql.get<{ present: number }>(
|
||||
"SELECT 1 AS present FROM agent_message_queue_items WHERE recipient_id = ? LIMIT 1",
|
||||
recipientId,
|
||||
);
|
||||
if (!hasItems) {
|
||||
return [];
|
||||
}
|
||||
if (!attemptedAt) {
|
||||
throw new Error("attemptedAt must be non-empty");
|
||||
}
|
||||
const transitioned: PersistedQueuedMessage[] = [];
|
||||
for (const id of new Set(ids)) {
|
||||
const updated = sql.get<QueueItemRow>(
|
||||
"UPDATE agent_message_queue_items " +
|
||||
"SET state = 'dispatching', dispatch_attempted_at = ? " +
|
||||
"WHERE recipient_id = ? AND id_json = ? AND state = 'queued' " +
|
||||
`RETURNING ${ITEM_COLUMNS}`,
|
||||
attemptedAt,
|
||||
recipientId,
|
||||
encodeText(id),
|
||||
);
|
||||
if (updated) {
|
||||
transitioned.push(deserializeRow(updated));
|
||||
}
|
||||
}
|
||||
return sortQueuedMessages(transitioned);
|
||||
});
|
||||
},
|
||||
|
||||
async revertDispatching(recipientId: string, ids: readonly string[]): Promise<void> {
|
||||
assertValidRecipientId(recipientId);
|
||||
if (ids.length === 0) {
|
||||
return;
|
||||
}
|
||||
database.write((sql) => {
|
||||
for (const id of new Set(ids)) {
|
||||
sql.run(
|
||||
"UPDATE agent_message_queue_items " +
|
||||
"SET state = 'queued', dispatch_attempted_at = NULL " +
|
||||
"WHERE recipient_id = ? AND id_json = ? AND state = 'dispatching'",
|
||||
recipientId,
|
||||
encodeText(id),
|
||||
);
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
async markHeld(recipientId: string): Promise<PersistedQueuedMessage[]> {
|
||||
assertValidRecipientId(recipientId);
|
||||
return database.write((sql) => {
|
||||
sql.run(
|
||||
"UPDATE agent_message_queue_items " +
|
||||
"SET held = 1, urgency = NULL " +
|
||||
"WHERE recipient_id = ? AND (held = 0 OR urgency IS NOT NULL)",
|
||||
recipientId,
|
||||
);
|
||||
return sql
|
||||
.all<QueueItemRow>(
|
||||
`SELECT ${ITEM_COLUMNS} FROM agent_message_queue_items WHERE recipient_id = ? ORDER BY seq ASC`,
|
||||
recipientId,
|
||||
)
|
||||
.map(deserializeRow);
|
||||
});
|
||||
},
|
||||
|
||||
async clearUrgency(recipientId: string, ids: readonly string[]): Promise<void> {
|
||||
assertValidRecipientId(recipientId);
|
||||
if (ids.length === 0) {
|
||||
return;
|
||||
}
|
||||
database.write((sql) => {
|
||||
for (const id of new Set(ids)) {
|
||||
sql.run(
|
||||
"UPDATE agent_message_queue_items " +
|
||||
"SET urgency = NULL " +
|
||||
"WHERE recipient_id = ? AND id_json = ? AND urgency IS NOT NULL",
|
||||
recipientId,
|
||||
encodeText(id),
|
||||
);
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
async promote(
|
||||
recipientId: string,
|
||||
targetId: string,
|
||||
urgency: QueuedMessageUrgency,
|
||||
): Promise<PromoteStoreResult> {
|
||||
assertValidRecipientId(recipientId);
|
||||
return database.write((sql) => {
|
||||
const target = sql.get<{ seq: number; state: QueuedMessageState }>(
|
||||
"SELECT seq, state FROM agent_message_queue_items WHERE recipient_id = ? AND id_json = ?",
|
||||
recipientId,
|
||||
encodeText(targetId),
|
||||
);
|
||||
if (!target) {
|
||||
return { status: "not_found" };
|
||||
}
|
||||
if (target.state === "dispatching") {
|
||||
return { status: "already_dispatching" };
|
||||
}
|
||||
// Prefix 0..target advances in FIFO admission order; items already
|
||||
// dispatching stay in flight untouched while queued items are released.
|
||||
sql.run(
|
||||
"UPDATE agent_message_queue_items " +
|
||||
"SET held = 0, urgency = ? " +
|
||||
"WHERE recipient_id = ? AND seq <= ? AND state = 'queued'",
|
||||
urgency,
|
||||
recipientId,
|
||||
target.seq,
|
||||
);
|
||||
const items = sql
|
||||
.all<QueueItemRow>(
|
||||
`SELECT ${ITEM_COLUMNS} FROM agent_message_queue_items WHERE recipient_id = ? ORDER BY seq ASC`,
|
||||
recipientId,
|
||||
)
|
||||
.map(deserializeRow);
|
||||
const promoted = items
|
||||
.filter((item) => item.seq <= target.seq && item.state === "queued")
|
||||
.map(cloneQueuedMessage);
|
||||
return { status: "promoted", promoted, items };
|
||||
});
|
||||
},
|
||||
|
||||
async withdraw(recipientId: string, id: string): Promise<WithdrawStoreResult> {
|
||||
assertValidRecipientId(recipientId);
|
||||
return database.write((sql) => {
|
||||
const candidate = sql.get<QueueItemRow>(
|
||||
`SELECT ${ITEM_COLUMNS} FROM agent_message_queue_items WHERE recipient_id = ? AND id_json = ?`,
|
||||
recipientId,
|
||||
encodeText(id),
|
||||
);
|
||||
if (!candidate) {
|
||||
return { status: "not_found" };
|
||||
}
|
||||
if (candidate.state === "dispatching") {
|
||||
return { status: "already_dispatching" };
|
||||
}
|
||||
sql.run(
|
||||
"DELETE FROM agent_message_queue_items WHERE recipient_id = ? AND id_json = ?",
|
||||
recipientId,
|
||||
encodeText(id),
|
||||
);
|
||||
return { status: "withdrawn", item: deserializeRow(candidate) };
|
||||
});
|
||||
},
|
||||
|
||||
async remove(recipientId: string, ids: readonly string[]): Promise<void> {
|
||||
assertValidRecipientId(recipientId);
|
||||
if (ids.length === 0) {
|
||||
return;
|
||||
}
|
||||
database.write((sql) => {
|
||||
for (const id of new Set(ids)) {
|
||||
sql.run(
|
||||
"DELETE FROM agent_message_queue_items WHERE recipient_id = ? AND id_json = ?",
|
||||
recipientId,
|
||||
encodeText(id),
|
||||
);
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
async clearRecipient(recipientId: string): Promise<PersistedQueuedMessage[]> {
|
||||
assertValidRecipientId(recipientId);
|
||||
return database.write((sql) => {
|
||||
const rows = sql.all<QueueItemRow>(
|
||||
`SELECT ${ITEM_COLUMNS} FROM agent_message_queue_items WHERE recipient_id = ? ORDER BY seq ASC`,
|
||||
recipientId,
|
||||
);
|
||||
if (rows.length === 0) {
|
||||
return [];
|
||||
}
|
||||
sql.run("DELETE FROM agent_message_queue_items WHERE recipient_id = ?", recipientId);
|
||||
return rows.map(deserializeRow);
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,18 +1,30 @@
|
||||
import { access, mkdir, mkdtemp, readdir, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { access, mkdtemp, rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, describe, expect, test } from "vitest";
|
||||
import { createTestLogger } from "../../../../test-utils/test-logger.js";
|
||||
import {
|
||||
DatabaseClosedError,
|
||||
openDaemonDatabase,
|
||||
type DaemonDatabase,
|
||||
} from "../../../database/index.js";
|
||||
import { timelineSchema } from "../../timeline/index.js";
|
||||
import {
|
||||
MAX_AGENT_QUEUE_DEPTH,
|
||||
createJsonAgentMessageQueueStore,
|
||||
agentMessageQueueSchema,
|
||||
createMemoryAgentMessageQueueStore,
|
||||
createSqliteAgentMessageQueueStore,
|
||||
type AgentMessageQueueStore,
|
||||
type EnqueueStoreInput,
|
||||
} from "../index.js";
|
||||
|
||||
const openDatabases: DaemonDatabase[] = [];
|
||||
const temporaryHomes: string[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
for (const database of openDatabases.splice(0).toReversed()) {
|
||||
database.close();
|
||||
}
|
||||
await Promise.all(
|
||||
temporaryHomes.splice(0).map((home) => rm(home, { recursive: true, force: true })),
|
||||
);
|
||||
@@ -24,16 +36,14 @@ async function createTempHome(): Promise<string> {
|
||||
return home;
|
||||
}
|
||||
|
||||
async function fileExists(filePath: string): Promise<boolean> {
|
||||
try {
|
||||
await access(filePath);
|
||||
return true;
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
|
||||
return false;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
function openQueueDatabase(home: string): DaemonDatabase {
|
||||
const database = openDaemonDatabase({
|
||||
path: join(home, "paseo.db"),
|
||||
modules: [agentMessageQueueSchema],
|
||||
logger: createTestLogger(),
|
||||
});
|
||||
openDatabases.push(database);
|
||||
return database;
|
||||
}
|
||||
|
||||
function makeInput(overrides: Partial<EnqueueStoreInput> = {}): EnqueueStoreInput {
|
||||
@@ -51,6 +61,7 @@ function makeInput(overrides: Partial<EnqueueStoreInput> = {}): EnqueueStoreInpu
|
||||
urgency: overrides.urgency === undefined ? null : overrides.urgency,
|
||||
held: overrides.held ?? false,
|
||||
...(overrides.fingerprint !== undefined ? { fingerprint: overrides.fingerprint } : {}),
|
||||
...(overrides.insertBeforeId !== undefined ? { insertBeforeId: overrides.insertBeforeId } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -65,10 +76,11 @@ const adapters: AdapterFactory[] = [
|
||||
create: async () => ({ store: createMemoryAgentMessageQueueStore() }),
|
||||
},
|
||||
{
|
||||
name: "json",
|
||||
name: "sqlite",
|
||||
create: async () => {
|
||||
const home = await createTempHome();
|
||||
return { store: createJsonAgentMessageQueueStore(home), home };
|
||||
const database = openQueueDatabase(home);
|
||||
return { store: createSqliteAgentMessageQueueStore(database), home };
|
||||
},
|
||||
},
|
||||
];
|
||||
@@ -182,6 +194,130 @@ describe.each(adapters)("AgentMessageQueueStore contract ($name)", (adapter) =>
|
||||
]);
|
||||
});
|
||||
|
||||
test("round-trips NUL bytes, lone surrogates, CJK, and payloads over 64 KiB losslessly", async () => {
|
||||
const { store } = await adapter.create();
|
||||
const trickyId = "msg\0middle\ud800lone\udfff";
|
||||
const secondId = "before\0\ud800id";
|
||||
const trickyMode = "mode\0\ud800custom";
|
||||
const trickyFingerprint = "fp\0\ud800hash";
|
||||
const trickyText = `prefix\0middle\ud800lone\udfff日本語🚀${"x".repeat(70 * 1024)}`;
|
||||
const largeAttachmentText = `attach\0\ud800${"y".repeat(70 * 1024)}`;
|
||||
|
||||
const inserted = await store.enqueue(
|
||||
makeInput({
|
||||
id: trickyId,
|
||||
text: trickyText,
|
||||
sessionMode: trickyMode,
|
||||
fingerprint: trickyFingerprint,
|
||||
source: { kind: "agent-message", agentId: "sender-1", title: "Worker\0\ud800日本語" },
|
||||
attachments: [
|
||||
{
|
||||
type: "text",
|
||||
fileName: "big.txt",
|
||||
mimeType: "text/plain",
|
||||
size: largeAttachmentText.length,
|
||||
text: largeAttachmentText,
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
|
||||
expect(inserted.status).toBe("inserted");
|
||||
|
||||
// Idempotency, insertBeforeId, markDispatching, revertDispatching, promote, clearUrgency,
|
||||
// withdraw, and remove must all match the exact unmangled id.
|
||||
const dup = await store.enqueue(
|
||||
makeInput({ id: trickyId, text: "ignored", fingerprint: trickyFingerprint }),
|
||||
);
|
||||
expect(dup).toMatchObject({ status: "duplicate", record: { id: trickyId } });
|
||||
|
||||
const before = await store.enqueue(
|
||||
makeInput({ id: secondId, text: "ahead", insertBeforeId: trickyId, urgency: "steer" }),
|
||||
);
|
||||
expect(before).toMatchObject({ status: "inserted", record: { id: secondId, seq: 1 } });
|
||||
|
||||
await store.clearUrgency("agent-1", [secondId]);
|
||||
const promoted = await store.promote("agent-1", trickyId, "interrupt");
|
||||
expect(promoted.status).toBe("promoted");
|
||||
if (promoted.status === "promoted") {
|
||||
expect(promoted.promoted.map((item) => item.id)).toEqual([secondId, trickyId]);
|
||||
}
|
||||
|
||||
const marked = await store.markDispatching("agent-1", [trickyId], "2026-11-30T07:05:00.000Z");
|
||||
expect(marked.map((item) => item.id)).toEqual([trickyId]);
|
||||
await store.revertDispatching("agent-1", [trickyId]);
|
||||
|
||||
const listed = await store.listByRecipient("agent-1");
|
||||
expect(listed.map((item) => item.id)).toEqual([secondId, trickyId]);
|
||||
expect(listed[1]!.text).toBe(trickyText);
|
||||
expect(listed[1]!.sessionMode).toBe(trickyMode);
|
||||
expect(listed[1]!.fingerprint).toBe(trickyFingerprint);
|
||||
expect(listed[1]!.source).toEqual({
|
||||
kind: "agent-message",
|
||||
agentId: "sender-1",
|
||||
title: "Worker\0\ud800日本語",
|
||||
});
|
||||
expect(listed[1]!.attachments).toEqual([
|
||||
{
|
||||
type: "text",
|
||||
fileName: "big.txt",
|
||||
mimeType: "text/plain",
|
||||
size: largeAttachmentText.length,
|
||||
text: largeAttachmentText,
|
||||
},
|
||||
]);
|
||||
|
||||
expect(await store.withdraw("agent-1", secondId)).toMatchObject({
|
||||
status: "withdrawn",
|
||||
item: { id: secondId },
|
||||
});
|
||||
await store.remove("agent-1", [trickyId]);
|
||||
expect(await store.listByRecipient("agent-1")).toEqual([]);
|
||||
});
|
||||
|
||||
test("insertBeforeId preserves ordering, shifts contiguous tails, and keeps nextSeq monotonic", async () => {
|
||||
const { store } = await adapter.create();
|
||||
|
||||
await store.enqueue(makeInput({ id: "m1", text: "one" }));
|
||||
await store.enqueue(makeInput({ id: "m2", text: "two" }));
|
||||
await store.enqueue(makeInput({ id: "m3", text: "three" }));
|
||||
await store.enqueue(makeInput({ id: "m4", text: "four" }));
|
||||
|
||||
// Create a gap at seq 3 by withdrawing m3.
|
||||
expect(await store.withdraw("agent-1", "m3")).toMatchObject({ status: "withdrawn" });
|
||||
|
||||
// Insert before m1: m1 (1->2), m2 (2->3), gap at 3 absorbs shift so m4 stays at 4.
|
||||
const beforeFirst = await store.enqueue(
|
||||
makeInput({ id: "m0", text: "zero", insertBeforeId: "m1" }),
|
||||
);
|
||||
expect(beforeFirst).toMatchObject({ status: "inserted", record: { id: "m0", seq: 1 } });
|
||||
expect((await store.listByRecipient("agent-1")).map((item) => [item.id, item.seq])).toEqual([
|
||||
["m0", 1],
|
||||
["m1", 2],
|
||||
["m2", 3],
|
||||
["m4", 4],
|
||||
]);
|
||||
|
||||
// Insert before m4: shifts m4 (4->5) and advances nextSeq past both old nextSeq+1 and maxSeq+1.
|
||||
const beforeTail = await store.enqueue(
|
||||
makeInput({ id: "m3b", text: "three-b", insertBeforeId: "m4" }),
|
||||
);
|
||||
expect(beforeTail).toMatchObject({ status: "inserted", record: { id: "m3b", seq: 4 } });
|
||||
expect((await store.listByRecipient("agent-1")).map((item) => [item.id, item.seq])).toEqual([
|
||||
["m0", 1],
|
||||
["m1", 2],
|
||||
["m2", 3],
|
||||
["m3b", 4],
|
||||
["m4", 5],
|
||||
]);
|
||||
|
||||
// Missing insertBeforeId falls back to appending at nextSeq.
|
||||
const fallback = await store.enqueue(
|
||||
makeInput({ id: "m5", text: "five", insertBeforeId: "does-not-exist" }),
|
||||
);
|
||||
expect(fallback).toMatchObject({ status: "inserted", record: { id: "m5", seq: 7 } });
|
||||
});
|
||||
|
||||
test("clones inputs and returned records so external mutations cannot corrupt store state", async () => {
|
||||
const { store } = await adapter.create();
|
||||
const attachments: EnqueueStoreInput["attachments"] = [
|
||||
@@ -375,6 +511,31 @@ describe.each(adapters)("AgentMessageQueueStore contract ($name)", (adapter) =>
|
||||
expect("dispatchAttemptedAt" in items[2]!).toBe(false);
|
||||
});
|
||||
|
||||
test("clearUrgency clears urgency for matching ids without changing held or state", async () => {
|
||||
const { store } = await adapter.create();
|
||||
|
||||
await store.enqueue(makeInput({ id: "m1", urgency: "interrupt", held: false }));
|
||||
await store.enqueue(makeInput({ id: "m2", urgency: "steer", held: true }));
|
||||
await store.enqueue(makeInput({ id: "m3", urgency: null, held: false }));
|
||||
await store.markDispatching("agent-1", ["m1"], "2026-11-30T07:05:00.000Z");
|
||||
|
||||
await store.clearUrgency("agent-1", ["m1", "m3", "missing"]);
|
||||
await store.clearUrgency("agent-1", []);
|
||||
|
||||
expect(
|
||||
(await store.listByRecipient("agent-1")).map((item) => ({
|
||||
id: item.id,
|
||||
urgency: item.urgency,
|
||||
held: item.held,
|
||||
state: item.state,
|
||||
})),
|
||||
).toEqual([
|
||||
{ id: "m1", urgency: null, held: false, state: "dispatching" },
|
||||
{ id: "m2", urgency: "steer", held: true, state: "queued" },
|
||||
{ id: "m3", urgency: null, held: false, state: "queued" },
|
||||
]);
|
||||
});
|
||||
|
||||
test("markHeld marks all items held and clears urgency while preserving state", async () => {
|
||||
const { store } = await adapter.create();
|
||||
|
||||
@@ -523,7 +684,7 @@ describe.each(adapters)("AgentMessageQueueStore contract ($name)", (adapter) =>
|
||||
}
|
||||
});
|
||||
|
||||
test("rejects path traversal and invalid recipient ids on every recipient-scoped operation", async () => {
|
||||
test("rejects invalid recipient ids on every recipient-scoped operation", async () => {
|
||||
const { store } = await adapter.create();
|
||||
const invalidIds = ["", ".", "..", "../escape", "a/b", "a\\b", "a\0b", "agent.json"];
|
||||
|
||||
@@ -539,6 +700,9 @@ describe.each(adapters)("AgentMessageQueueStore contract ($name)", (adapter) =>
|
||||
/Invalid agent queue recipient/,
|
||||
);
|
||||
await expect(store.markHeld(badId)).rejects.toThrow(/Invalid agent queue recipient/);
|
||||
await expect(store.clearUrgency(badId, ["msg-1"])).rejects.toThrow(
|
||||
/Invalid agent queue recipient/,
|
||||
);
|
||||
await expect(store.promote(badId, "msg-1", "steer")).rejects.toThrow(
|
||||
/Invalid agent queue recipient/,
|
||||
);
|
||||
@@ -549,29 +713,51 @@ describe.each(adapters)("AgentMessageQueueStore contract ($name)", (adapter) =>
|
||||
});
|
||||
});
|
||||
|
||||
describe("createJsonAgentMessageQueueStore persistence & file hygiene", () => {
|
||||
test("persists items, states, and monotonic nextSeq across store restarts", async () => {
|
||||
describe("createSqliteAgentMessageQueueStore persistence & schema", () => {
|
||||
test("persists items, states, payloads, and monotonic nextSeq across database reopen", async () => {
|
||||
const home = await createTempHome();
|
||||
const store1 = createJsonAgentMessageQueueStore(home);
|
||||
const db1 = openQueueDatabase(home);
|
||||
const store1 = createSqliteAgentMessageQueueStore(db1);
|
||||
const largeText = `first\0\ud800${"z".repeat(70 * 1024)}`;
|
||||
|
||||
await store1.enqueue(
|
||||
makeInput({
|
||||
id: "m1",
|
||||
text: "first",
|
||||
text: largeText,
|
||||
source: { kind: "change-request-update", url: "https://github.com/getpaseo/paseo/pull/1" },
|
||||
sessionMode: "plan",
|
||||
fingerprint: "fp-1",
|
||||
}),
|
||||
);
|
||||
await store1.enqueue(makeInput({ id: "m2", text: "second", held: true }));
|
||||
await store1.enqueue(
|
||||
makeInput({
|
||||
id: "m2",
|
||||
text: "second",
|
||||
held: true,
|
||||
providerSwitch: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
modeId: "auto",
|
||||
thinkingOptionId: null,
|
||||
},
|
||||
}),
|
||||
);
|
||||
await store1.enqueue(makeInput({ id: "m3", text: "third" }));
|
||||
await store1.markDispatching("agent-1", ["m1"], "2026-11-30T07:10:00.000Z");
|
||||
await store1.withdraw("agent-1", "m3");
|
||||
db1.close();
|
||||
|
||||
const restarted = createJsonAgentMessageQueueStore(home);
|
||||
// Never creates the legacy agent-queues directory.
|
||||
await expect(access(join(home, "agent-queues"))).rejects.toMatchObject({ code: "ENOENT" });
|
||||
|
||||
const db2 = openQueueDatabase(home);
|
||||
const restarted = createSqliteAgentMessageQueueStore(db2);
|
||||
expect(await restarted.listAll()).toEqual([
|
||||
expect.objectContaining({
|
||||
id: "m1",
|
||||
seq: 1,
|
||||
text: largeText,
|
||||
sessionMode: "plan",
|
||||
state: "dispatching",
|
||||
dispatchAttemptedAt: "2026-11-30T07:10:00.000Z",
|
||||
fingerprint: "fp-1",
|
||||
@@ -581,142 +767,69 @@ describe("createJsonAgentMessageQueueStore persistence & file hygiene", () => {
|
||||
seq: 2,
|
||||
held: true,
|
||||
state: "queued",
|
||||
providerSwitch: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
modeId: "auto",
|
||||
thinkingOptionId: null,
|
||||
},
|
||||
}),
|
||||
]);
|
||||
|
||||
const afterRestartEnqueue = await restarted.enqueue(makeInput({ id: "m4", text: "fourth" }));
|
||||
expect(afterRestartEnqueue).toMatchObject({ status: "inserted", record: { id: "m4", seq: 4 } });
|
||||
|
||||
// Monotonic nextSeq also survives clearRecipient + reopen.
|
||||
await restarted.clearRecipient("agent-1");
|
||||
db2.close();
|
||||
|
||||
const db3 = openQueueDatabase(home);
|
||||
const afterClear = createSqliteAgentMessageQueueStore(db3);
|
||||
const fifth = await afterClear.enqueue(makeInput({ id: "m5", text: "fifth" }));
|
||||
expect(fifth).toMatchObject({ status: "inserted", record: { id: "m5", seq: 5 } });
|
||||
});
|
||||
|
||||
test("deletes empty recipient queue files and avoids creating files for empty operations", async () => {
|
||||
test("registers agent_message_queues schema alongside timelineSchema and leaves empty recipients untouched", async () => {
|
||||
const home = await createTempHome();
|
||||
const store = createJsonAgentMessageQueueStore(home);
|
||||
const queueFile = join(home, "agent-queues", "agent-1.json");
|
||||
const database = openDaemonDatabase({
|
||||
path: join(home, "paseo.db"),
|
||||
modules: [timelineSchema, agentMessageQueueSchema],
|
||||
logger: createTestLogger(),
|
||||
});
|
||||
openDatabases.push(database);
|
||||
|
||||
const version = database.read((sql) =>
|
||||
sql.get<{ version: number; min_reader_version: number }>(
|
||||
"SELECT version, min_reader_version FROM schema_versions WHERE module = ?",
|
||||
"agent_message_queues",
|
||||
),
|
||||
);
|
||||
expect(version).toEqual({ version: 1, min_reader_version: 1 });
|
||||
|
||||
const store = createSqliteAgentMessageQueueStore(database);
|
||||
expect(await store.listByRecipient("agent-1")).toEqual([]);
|
||||
expect(await store.markHeld("agent-1")).toEqual([]);
|
||||
expect(await store.withdraw("agent-1", "missing")).toEqual({ status: "not_found" });
|
||||
expect(await store.promote("agent-1", "missing", "steer")).toEqual({ status: "not_found" });
|
||||
await store.clearUrgency("agent-1", ["missing"]);
|
||||
await store.remove("agent-1", ["missing"]);
|
||||
expect(await store.clearRecipient("agent-1")).toEqual([]);
|
||||
expect(await fileExists(queueFile)).toBe(false);
|
||||
|
||||
await store.enqueue(makeInput({ id: "m1" }));
|
||||
expect(await fileExists(queueFile)).toBe(true);
|
||||
|
||||
await store.withdraw("agent-1", "m1");
|
||||
expect(await fileExists(queueFile)).toBe(false);
|
||||
|
||||
await store.enqueue(makeInput({ id: "m2" }));
|
||||
expect(await fileExists(queueFile)).toBe(true);
|
||||
await store.remove("agent-1", ["m2"]);
|
||||
expect(await fileExists(queueFile)).toBe(false);
|
||||
|
||||
await store.enqueue(makeInput({ id: "m3" }));
|
||||
expect(await fileExists(queueFile)).toBe(true);
|
||||
await store.clearRecipient("agent-1");
|
||||
expect(await fileExists(queueFile)).toBe(false);
|
||||
|
||||
// Re-enqueuing in the same store instance still preserves monotonic seq after file deletion.
|
||||
const next = await store.enqueue(makeInput({ id: "m4" }));
|
||||
expect(next).toMatchObject({ status: "inserted", record: { id: "m4", seq: 4 } });
|
||||
});
|
||||
|
||||
test("ignores hidden temp files in agent-queues directory during listAll", async () => {
|
||||
const home = await createTempHome();
|
||||
const queuesDir = join(home, "agent-queues");
|
||||
await mkdir(queuesDir, { recursive: true });
|
||||
await writeFile(join(queuesDir, ".agent-1.json.123.tmp"), "{not json", "utf8");
|
||||
|
||||
const store = createJsonAgentMessageQueueStore(home);
|
||||
await store.enqueue(makeInput({ id: "m1" }));
|
||||
|
||||
expect((await store.listAll()).map((item) => item.id)).toEqual(["m1"]);
|
||||
});
|
||||
|
||||
test("fails visibly on invalid persisted JSON, invalid schema, or recipientId mismatch", async () => {
|
||||
const home = await createTempHome();
|
||||
const queuesDir = join(home, "agent-queues");
|
||||
await mkdir(queuesDir, { recursive: true });
|
||||
|
||||
await writeFile(join(queuesDir, "bad-json.json"), "{broken", "utf8");
|
||||
await expect(
|
||||
createJsonAgentMessageQueueStore(home).listByRecipient("bad-json"),
|
||||
).rejects.toThrow();
|
||||
|
||||
await writeFile(
|
||||
join(queuesDir, "bad-schema.json"),
|
||||
JSON.stringify({ version: 1, nextSeq: 1, items: [{ id: 42 }] }),
|
||||
"utf8",
|
||||
const recipientCount = database.read((sql) =>
|
||||
sql.get<{ count: number }>("SELECT COUNT(*) AS count FROM agent_message_queue_recipients"),
|
||||
);
|
||||
await expect(
|
||||
createJsonAgentMessageQueueStore(home).listByRecipient("bad-schema"),
|
||||
).rejects.toThrow();
|
||||
expect(recipientCount?.count).toBe(0);
|
||||
});
|
||||
|
||||
await writeFile(
|
||||
join(queuesDir, "wrong-recipient.json"),
|
||||
JSON.stringify({
|
||||
version: 1,
|
||||
nextSeq: 2,
|
||||
items: [
|
||||
{
|
||||
id: "m1",
|
||||
recipientId: "other-agent",
|
||||
seq: 1,
|
||||
enqueuedAt: "2026-11-30T07:00:00.000Z",
|
||||
text: "hi",
|
||||
attachments: [],
|
||||
source: null,
|
||||
unarchive: true,
|
||||
clearPendingPermissions: false,
|
||||
urgency: null,
|
||||
held: false,
|
||||
state: "queued",
|
||||
},
|
||||
],
|
||||
}),
|
||||
"utf8",
|
||||
test("rejects operations with DatabaseClosedError after the database closes", async () => {
|
||||
const home = await createTempHome();
|
||||
const database = openQueueDatabase(home);
|
||||
const store = createSqliteAgentMessageQueueStore(database);
|
||||
database.close();
|
||||
|
||||
await expect(store.listAll()).rejects.toBeInstanceOf(DatabaseClosedError);
|
||||
await expect(store.enqueue(makeInput({ id: "m1" }))).rejects.toBeInstanceOf(
|
||||
DatabaseClosedError,
|
||||
);
|
||||
await expect(
|
||||
createJsonAgentMessageQueueStore(home).listByRecipient("wrong-recipient"),
|
||||
).rejects.toThrow(/Mismatched recipientId/);
|
||||
});
|
||||
|
||||
test("listAll sets one bad queue file aside and still loads every valid queue", async () => {
|
||||
const home = await createTempHome();
|
||||
const queuesDir = join(home, "agent-queues");
|
||||
const writer = createJsonAgentMessageQueueStore(home);
|
||||
await writer.enqueue(makeInput({ id: "m1", recipientId: "agent-1" }));
|
||||
await writer.enqueue(makeInput({ id: "m2", recipientId: "agent-2" }));
|
||||
await writeFile(join(queuesDir, "bad-agent.json"), "{broken", "utf8");
|
||||
const corrupted: Array<{ recipientId: string; movedTo: string }> = [];
|
||||
const store = createJsonAgentMessageQueueStore(home, {
|
||||
onCorruptFile: ({ recipientId, movedTo }) => corrupted.push({ recipientId, movedTo }),
|
||||
});
|
||||
|
||||
expect((await store.listAll()).map((item) => item.id)).toEqual(["m1", "m2"]);
|
||||
|
||||
const left = (await readdir(queuesDir)).filter((name) => name.startsWith("bad-agent"));
|
||||
expect(left).toHaveLength(1);
|
||||
const aside = left[0];
|
||||
expect(aside).toMatch(/^bad-agent\.json\.corrupt\.\d+$/);
|
||||
expect(await readFile(join(queuesDir, aside!), "utf8")).toBe("{broken");
|
||||
expect(corrupted).toEqual([{ recipientId: "bad-agent", movedTo: join(queuesDir, aside!) }]);
|
||||
// The recipient starts over with an empty queue.
|
||||
await store.enqueue(makeInput({ id: "m3", recipientId: "bad-agent" }));
|
||||
expect((await store.listByRecipient("bad-agent")).map((item) => item.id)).toEqual(["m3"]);
|
||||
});
|
||||
|
||||
test("write failure rejects enqueue and does not pollute in-memory cache", async () => {
|
||||
const home = await createTempHome();
|
||||
const store = createJsonAgentMessageQueueStore(home);
|
||||
expect(await store.listByRecipient("agent-1")).toEqual([]);
|
||||
|
||||
// Obstruct the target file path with a directory so rename fails.
|
||||
await mkdir(join(home, "agent-queues", "agent-1.json"), { recursive: true });
|
||||
|
||||
await expect(store.enqueue(makeInput({ id: "m1" }))).rejects.toThrow();
|
||||
await rm(join(home, "agent-queues", "agent-1.json"), { recursive: true, force: true });
|
||||
expect(await store.listByRecipient("agent-1")).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -30,7 +30,10 @@ export interface PersistedQueuedMessage {
|
||||
export type EnqueueStoreInput = Omit<
|
||||
PersistedQueuedMessage,
|
||||
"seq" | "state" | "dispatchAttemptedAt"
|
||||
>;
|
||||
> & {
|
||||
/** Insert immediately before this queued item when present, preserving its position. */
|
||||
insertBeforeId?: string;
|
||||
};
|
||||
|
||||
export type EnqueueStoreResult =
|
||||
| { status: "inserted"; record: PersistedQueuedMessage }
|
||||
@@ -70,6 +73,7 @@ export interface AgentMessageQueueStore {
|
||||
): Promise<PersistedQueuedMessage[]>;
|
||||
revertDispatching(recipientId: string, ids: readonly string[]): Promise<void>;
|
||||
markHeld(recipientId: string): Promise<PersistedQueuedMessage[]>;
|
||||
clearUrgency(recipientId: string, ids: readonly string[]): Promise<void>;
|
||||
promote(
|
||||
recipientId: string,
|
||||
targetId: string,
|
||||
|
||||
@@ -3,16 +3,17 @@ import {
|
||||
type AgentMessageDelivery,
|
||||
type AgentPromptSource,
|
||||
} from "./agent-messages/index.js";
|
||||
import type { DirectSendResult } from "./agent-messages/delivery.js";
|
||||
import type { Logger } from "pino";
|
||||
|
||||
import type { UploadedImage } from "@getpaseo/protocol/agent-types";
|
||||
import type { ActiveTurnBehavior, AgentAttachment } from "@getpaseo/protocol/messages";
|
||||
import type { AgentPromptInput, AgentRunOptions } from "./agent-sdk-types.js";
|
||||
import type { AgentManager, AgentPromptSubmissionOptions, ManagedAgent } from "./agent-manager.js";
|
||||
import { ForegroundPromptStart } from "./agent-run-state.js";
|
||||
import type { AgentStorage } from "./agent-storage.js";
|
||||
import { ensureAgentLoaded } from "./agent-loading.js";
|
||||
import { isStaleProviderSessionError } from "./stale-provider-session-error.js";
|
||||
import type { ActiveTurnBehavior } from "@getpaseo/protocol/messages";
|
||||
|
||||
export type AgentUnarchiveController = Pick<AgentManager, "notifyAgentState" | "unarchiveSnapshot">;
|
||||
|
||||
@@ -341,10 +342,20 @@ export interface SendPromptToAgentParams {
|
||||
/** A prompt that does not wait its turn. Messages queued for the agent go with it. */
|
||||
export interface SendDirectPromptParams extends SendPromptToAgentParams {
|
||||
agentMessages: Pick<AgentMessageDelivery, "sendDirect">;
|
||||
/** Raw message text when the caller has it, used if queueing behind a boundary. */
|
||||
text?: string;
|
||||
/** Raw message attachments when the caller has them, used if queueing behind a boundary. */
|
||||
attachments?: readonly AgentAttachment[];
|
||||
/** Lazy attachment persistence invoked only when a direct prompt is queued behind a boundary. */
|
||||
resolveAttachments?: () => Promise<AgentAttachment[]>;
|
||||
/** The sender's identity for retries of `messageId` when queued behind a boundary. */
|
||||
fingerprint?: string;
|
||||
/** Resumes a turn the daemon's restart cut off, so queued messages stay behind it. */
|
||||
resumesTurn?: boolean;
|
||||
}
|
||||
|
||||
export type SendDirectPromptResult = DirectSendResult<PromptDispatchResult>;
|
||||
|
||||
export interface StartCreatedAgentInitialPromptParams {
|
||||
agentStorage: AgentStorage;
|
||||
agentManager: AgentManager;
|
||||
@@ -449,17 +460,34 @@ async function resolvePromptSource(
|
||||
*/
|
||||
export async function sendPromptToAgent(
|
||||
params: SendDirectPromptParams,
|
||||
): Promise<PromptDispatchResult> {
|
||||
const { agentMessages, source, messageId, resumesTurn, ...send } = params;
|
||||
): Promise<SendDirectPromptResult> {
|
||||
const {
|
||||
agentMessages,
|
||||
source,
|
||||
messageId,
|
||||
text,
|
||||
attachments,
|
||||
resolveAttachments,
|
||||
fingerprint,
|
||||
resumesTurn,
|
||||
...send
|
||||
} = params;
|
||||
return agentMessages.sendDirect(
|
||||
{
|
||||
recipientId: params.agentId,
|
||||
prompt: params.prompt,
|
||||
text,
|
||||
attachments,
|
||||
resolveAttachments,
|
||||
uploadedImages: params.uploadedImages,
|
||||
source: await resolvePromptSource(source, params.agentManager, params.agentStorage),
|
||||
messageId,
|
||||
sessionMode: params.sessionMode,
|
||||
activeTurnBehavior: params.activeTurnBehavior === "steer" ? "steer" : "interrupt",
|
||||
clearPendingPermissions: params.clearPendingPermissions,
|
||||
fingerprint,
|
||||
unarchive: params.unarchive,
|
||||
onDispatch: params.onDispatch,
|
||||
resumesTurn,
|
||||
},
|
||||
(joined) =>
|
||||
|
||||
@@ -8,6 +8,9 @@ import pino from "pino";
|
||||
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
|
||||
|
||||
import { createTestPaseoDaemon } from "../../../test-utils/paseo-daemon.js";
|
||||
import { AgentManager } from "../../agent-manager.js";
|
||||
import { createStoredAgentTimeline } from "../../timeline/index.js";
|
||||
import { openTestTimelineDatabase } from "../../timeline/testing.js";
|
||||
import type { ClaudeRewindSdk } from "./rewind.js";
|
||||
import { ClaudeAgentClient } from "./agent.js";
|
||||
import { claudeProjectDirSync } from "./project-dir.js";
|
||||
@@ -17,8 +20,9 @@ import type { ClaudeQueryFactory } from "./query.js";
|
||||
import { collectSessionTurnEvents } from "../test-utils/session-stream-adapter.js";
|
||||
|
||||
/**
|
||||
* A resumed Claude agent whose transcript is missing or unreadable opens with an empty timeline.
|
||||
* The daemon log at its default level has to say which, and where it looked.
|
||||
* A resumed Claude agent whose transcript is missing (`ENOENT`) opens with an empty timeline.
|
||||
* An unreadable transcript (`EISDIR`, `EACCES`, I/O error) must reject so `AgentManager` does not
|
||||
* latch an empty timeline into `paseo.db`, while logging where it looked.
|
||||
*/
|
||||
|
||||
const SESSION_ID = "history-load-session";
|
||||
@@ -652,8 +656,13 @@ describe("ClaudeAgentSession persisted history load", () => {
|
||||
},
|
||||
);
|
||||
|
||||
test("logs the resolved transcript path when the transcript does not exist", async () => {
|
||||
await (await resume()).close();
|
||||
test("logs the resolved transcript path and returns empty history when the transcript does not exist", async () => {
|
||||
const session = await resume();
|
||||
try {
|
||||
expect(await Array.fromAsync(session.streamHistory())).toEqual([]);
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
|
||||
expect(records).toContainEqual(
|
||||
expect.objectContaining({
|
||||
@@ -665,11 +674,44 @@ describe("ClaudeAgentSession persisted history load", () => {
|
||||
);
|
||||
});
|
||||
|
||||
test("logs a warning with the error when the transcript cannot be read", async () => {
|
||||
test("skips a corrupt or truncated JSON line without failing transcript replay", async () => {
|
||||
mkdirSync(path.dirname(transcriptPath()), { recursive: true });
|
||||
writeFileSync(
|
||||
transcriptPath(),
|
||||
[
|
||||
JSON.stringify({ type: "user", uuid: "u1", message: { content: "before glitch" } }),
|
||||
'{"type":"assistant","message":{"content":"truncated',
|
||||
JSON.stringify({ type: "assistant", uuid: "a1", message: { content: "after glitch" } }),
|
||||
].join("\n"),
|
||||
);
|
||||
|
||||
const session = await resume();
|
||||
try {
|
||||
const history = await Array.fromAsync(session.streamHistory());
|
||||
expect(history).toEqual([
|
||||
{
|
||||
type: "timeline",
|
||||
provider: "claude",
|
||||
timestamp: undefined,
|
||||
item: { type: "user_message", text: "before glitch", messageId: "u1" },
|
||||
},
|
||||
{
|
||||
type: "timeline",
|
||||
provider: "claude",
|
||||
timestamp: undefined,
|
||||
item: { type: "assistant_message", text: "after glitch", messageId: "a1" },
|
||||
},
|
||||
]);
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("rejects and logs a warning when the transcript cannot be read", async () => {
|
||||
// A directory at the transcript path exists but cannot be read as a file.
|
||||
mkdirSync(transcriptPath(), { recursive: true });
|
||||
|
||||
await (await resume()).close();
|
||||
await expect(resume()).rejects.toThrow(/EISDIR/);
|
||||
|
||||
expect(records).toContainEqual(
|
||||
expect.objectContaining({
|
||||
@@ -682,6 +724,230 @@ describe("ClaudeAgentSession persisted history load", () => {
|
||||
);
|
||||
});
|
||||
|
||||
test("leaves agent unregistered with no paseo.db row on unreadable transcript, then imports full history on retry", async () => {
|
||||
const database = openTestTimelineDatabase();
|
||||
const timeline = createStoredAgentTimeline(database);
|
||||
const client = new ClaudeAgentClient({
|
||||
logger: pino({ level: "info" }, { write: (line: string) => records.push(JSON.parse(line)) }),
|
||||
queryFactory: () => {
|
||||
throw new Error("history load must not start a query");
|
||||
},
|
||||
resolveBinary: async () => process.execPath,
|
||||
resolveVersion: async () => "2.1.220",
|
||||
});
|
||||
const manager = new AgentManager({
|
||||
clients: { claude: client },
|
||||
logger: pino({ level: "silent" }),
|
||||
timeline,
|
||||
});
|
||||
|
||||
// Make the transcript path unreadable (directory -> EISDIR on all platforms).
|
||||
mkdirSync(transcriptPath(), { recursive: true });
|
||||
const agentId = "00000000-0000-4000-8000-000000000001";
|
||||
const handle = { provider: "claude" as const, sessionId: SESSION_ID };
|
||||
|
||||
try {
|
||||
await expect(manager.resumeAgentFromPersistence(handle, { cwd }, agentId)).rejects.toThrow(
|
||||
/EISDIR/,
|
||||
);
|
||||
|
||||
expect(manager.getAgent(agentId)).toBeNull();
|
||||
expect(await manager.hasStoredHistory(agentId)).toBe(false);
|
||||
expect(
|
||||
database.read((sql) =>
|
||||
sql.all("SELECT agent_id FROM timeline_scopes WHERE agent_id = ?", agentId),
|
||||
),
|
||||
).toEqual([]);
|
||||
|
||||
// Restore a readable transcript and retry: full history must now import cleanly.
|
||||
rmSync(transcriptPath(), { recursive: true, force: true });
|
||||
writeFileSync(
|
||||
transcriptPath(),
|
||||
[
|
||||
JSON.stringify({ type: "user", uuid: "u1", message: { content: "hello" } }),
|
||||
JSON.stringify({ type: "assistant", uuid: "a1", message: { content: "world" } }),
|
||||
].join("\n"),
|
||||
);
|
||||
|
||||
await manager.resumeAgentFromPersistence(handle, { cwd }, agentId);
|
||||
expect(await manager.hasStoredHistory(agentId)).toBe(true);
|
||||
const items = await manager.getTimeline(agentId);
|
||||
expect(items).toEqual([
|
||||
{ type: "user_message", text: "hello", messageId: "u1" },
|
||||
{ type: "assistant_message", text: "world", messageId: "a1" },
|
||||
]);
|
||||
} finally {
|
||||
await manager.closeAgent(agentId).catch(() => undefined);
|
||||
}
|
||||
});
|
||||
|
||||
// chmod does not remove read access on Windows, or for root.
|
||||
test.skipIf(process.platform === "win32" || process.getuid?.() === 0)(
|
||||
"propagates EACCES on unreadable transcript without latching empty history, then succeeds on retry",
|
||||
async () => {
|
||||
const database = openTestTimelineDatabase();
|
||||
const timeline = createStoredAgentTimeline(database);
|
||||
const client = new ClaudeAgentClient({
|
||||
logger: pino(
|
||||
{ level: "info" },
|
||||
{ write: (line: string) => records.push(JSON.parse(line)) },
|
||||
),
|
||||
queryFactory: () => {
|
||||
throw new Error("history load must not start a query");
|
||||
},
|
||||
resolveBinary: async () => process.execPath,
|
||||
resolveVersion: async () => "2.1.220",
|
||||
});
|
||||
const manager = new AgentManager({
|
||||
clients: { claude: client },
|
||||
logger: pino({ level: "silent" }),
|
||||
timeline,
|
||||
});
|
||||
|
||||
mkdirSync(path.dirname(transcriptPath()), { recursive: true });
|
||||
writeFileSync(
|
||||
transcriptPath(),
|
||||
[
|
||||
JSON.stringify({ type: "user", uuid: "u1", message: { content: "secret prompt" } }),
|
||||
JSON.stringify({ type: "assistant", uuid: "a1", message: { content: "secret reply" } }),
|
||||
].join("\n"),
|
||||
);
|
||||
chmodSync(transcriptPath(), 0o000);
|
||||
|
||||
const agentId = "00000000-0000-4000-8000-000000000002";
|
||||
const handle = { provider: "claude" as const, sessionId: SESSION_ID };
|
||||
|
||||
try {
|
||||
await expect(manager.resumeAgentFromPersistence(handle, { cwd }, agentId)).rejects.toThrow(
|
||||
/EACCES/,
|
||||
);
|
||||
|
||||
expect(manager.getAgent(agentId)).toBeNull();
|
||||
expect(await manager.hasStoredHistory(agentId)).toBe(false);
|
||||
|
||||
chmodSync(transcriptPath(), 0o600);
|
||||
|
||||
await manager.resumeAgentFromPersistence(handle, { cwd }, agentId);
|
||||
expect(await manager.hasStoredHistory(agentId)).toBe(true);
|
||||
const items = await manager.getTimeline(agentId);
|
||||
expect(items).toEqual([
|
||||
{ type: "user_message", text: "secret prompt", messageId: "u1" },
|
||||
{ type: "assistant_message", text: "secret reply", messageId: "a1" },
|
||||
]);
|
||||
} finally {
|
||||
chmodSync(transcriptPath(), 0o600);
|
||||
await manager.closeAgent(agentId).catch(() => undefined);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
test("rejects waiting readers and resets history readiness when rebind transcript load fails, then succeeds on retry", async () => {
|
||||
const entries = [
|
||||
{ type: "user", uuid: "u1", message: { content: "first" } },
|
||||
{ type: "assistant", uuid: "a1", message: { content: "first reply" } },
|
||||
{ type: "user", uuid: "u2", message: { content: "second" } },
|
||||
];
|
||||
mkdirSync(path.dirname(transcriptPath()), { recursive: true });
|
||||
writeFileSync(transcriptPath(), entries.map((entry) => JSON.stringify(entry)).join("\n"));
|
||||
|
||||
const forkId = "retryable-fork";
|
||||
const forkFile = path.join(path.dirname(transcriptPath()), `${forkId}.jsonl`);
|
||||
// Make the forked transcript unreadable on the initial rebind read.
|
||||
mkdirSync(forkFile, { recursive: true });
|
||||
|
||||
let releaseRetirement!: () => void;
|
||||
const retirementGate = new Promise<void>((resolve) => {
|
||||
releaseRetirement = resolve;
|
||||
});
|
||||
let retirementStarted!: () => void;
|
||||
const retiring = new Promise<void>((resolve) => {
|
||||
retirementStarted = resolve;
|
||||
});
|
||||
let pendingRead: ((value: unknown) => void) | undefined;
|
||||
let firstQuery = true;
|
||||
const queryFactory = ((input) => {
|
||||
if (!firstQuery) return replyFactory("live reply")(input);
|
||||
firstQuery = false;
|
||||
const messages = [
|
||||
{ type: "assistant", uuid: "before-rebind", message: { content: "before rebind" } },
|
||||
{ type: "result", subtype: "success", total_cost_usd: 0 },
|
||||
];
|
||||
return {
|
||||
async next() {
|
||||
const value = messages.shift();
|
||||
if (value) return { done: false, value };
|
||||
return new Promise((resolve) => {
|
||||
pendingRead = resolve;
|
||||
});
|
||||
},
|
||||
close() {
|
||||
pendingRead?.({ done: true, value: undefined });
|
||||
},
|
||||
async return() {
|
||||
retirementStarted();
|
||||
await retirementGate;
|
||||
return { done: true, value: undefined };
|
||||
},
|
||||
async supportedCommands() {
|
||||
return [];
|
||||
},
|
||||
[Symbol.asyncIterator]() {
|
||||
return this;
|
||||
},
|
||||
};
|
||||
}) as ClaudeQueryFactory;
|
||||
|
||||
const session = await resume(queryFactory, {
|
||||
async forkSession() {
|
||||
return { sessionId: forkId };
|
||||
},
|
||||
});
|
||||
try {
|
||||
await Array.fromAsync(session.streamHistory());
|
||||
await collectSessionTurnEvents(session, "before rewind");
|
||||
|
||||
const rewind = session.revertConversation!({ messageId: "u2" });
|
||||
await retiring;
|
||||
// Attach a reader while rebind is in flight; it must receive the EISDIR error, not [].
|
||||
const waitingRead = Array.fromAsync(session.streamHistory());
|
||||
releaseRetirement();
|
||||
await rewind;
|
||||
await expect(waitingRead).rejects.toThrow(/EISDIR/);
|
||||
|
||||
// A subsequent read while still unreadable also rejects (no empty latching).
|
||||
await expect(Array.fromAsync(session.streamHistory())).rejects.toThrow(/EISDIR/);
|
||||
|
||||
// Restoring the transcript lets a retry on the same session load full forked history.
|
||||
rmSync(forkFile, { recursive: true, force: true });
|
||||
writeFileSync(
|
||||
forkFile,
|
||||
entries
|
||||
.slice(0, 2)
|
||||
.map((entry) => JSON.stringify(entry))
|
||||
.join("\n"),
|
||||
);
|
||||
|
||||
const retried = await Array.fromAsync(session.streamHistory());
|
||||
expect(retried).toEqual([
|
||||
{
|
||||
type: "timeline",
|
||||
provider: "claude",
|
||||
timestamp: undefined,
|
||||
item: { type: "user_message", text: "first", messageId: "u1" },
|
||||
},
|
||||
{
|
||||
type: "timeline",
|
||||
provider: "claude",
|
||||
timestamp: undefined,
|
||||
item: { type: "assistant_message", text: "first reply", messageId: "a1" },
|
||||
},
|
||||
]);
|
||||
} finally {
|
||||
releaseRetirement();
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("replays a message steered into a running turn as the user's message", async () => {
|
||||
const queued = (commandMode: string, prompt: unknown, sourceUuid?: string) => ({
|
||||
type: "attachment",
|
||||
@@ -839,14 +1105,14 @@ describe("ClaudeAgentSession persisted history load", () => {
|
||||
|
||||
// chmod does not remove read access on Windows, or for root.
|
||||
test.skipIf(process.platform === "win32" || process.getuid?.() === 0)(
|
||||
"logs a warning with the error when Claude's project folders cannot be listed",
|
||||
"rejects and logs a warning with the error when Claude's project folders cannot be listed",
|
||||
async () => {
|
||||
// The transcript is not under cwd's folder, so the lookup lists the other project folders.
|
||||
mkdirSync(path.join(configDir, "projects"), { recursive: true });
|
||||
chmodSync(path.join(configDir, "projects"), 0o000);
|
||||
|
||||
try {
|
||||
await (await resume()).close();
|
||||
await expect(resume()).rejects.toThrow(/EACCES/);
|
||||
} finally {
|
||||
chmodSync(path.join(configDir, "projects"), 0o755);
|
||||
}
|
||||
|
||||
@@ -260,6 +260,9 @@ describe("importing a renamed Claude session", () => {
|
||||
const imported = await importSession(sessionId);
|
||||
|
||||
expect(imported.config.title).toBe("Slow query hunt");
|
||||
expect(imported.timeline.map((entry) => entry.item)).toContainEqual(
|
||||
expect.objectContaining({ type: "user_message", text: "Trace the slow query" }),
|
||||
);
|
||||
});
|
||||
|
||||
test("reads the rename from behind more records than one read covers", async () => {
|
||||
|
||||
@@ -108,6 +108,46 @@ describe("Claude session request journal replay", () => {
|
||||
},
|
||||
);
|
||||
|
||||
test("restores the goal acknowledgement before the reply that meets the goal", async () => {
|
||||
const condition = "Your latest reply is exactly the word DONE";
|
||||
const items = await replay([
|
||||
{
|
||||
type: "user",
|
||||
message: { role: "user", content: `/goal ${condition}` },
|
||||
},
|
||||
{
|
||||
type: "system",
|
||||
subtype: "local_command",
|
||||
uuid: "goal-confirmation",
|
||||
commandRun: { command: "goal", args: condition },
|
||||
content: `<local-command-stdout>Goal set: ${condition}</local-command-stdout>`,
|
||||
},
|
||||
{
|
||||
type: "assistant",
|
||||
uuid: "goal-reply",
|
||||
message: {
|
||||
role: "assistant",
|
||||
content: [{ type: "text", text: "DONE" }],
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "system",
|
||||
subtype: "local_command",
|
||||
commandRun: { command: "model" },
|
||||
content: "<local-command-stdout>Set model to opus</local-command-stdout>",
|
||||
},
|
||||
]);
|
||||
expect(items).toEqual([
|
||||
{ type: "user_message", text: `/goal ${condition}` },
|
||||
{
|
||||
type: "assistant_message",
|
||||
messageId: "goal-confirmation",
|
||||
text: `Goal set: ${condition}`,
|
||||
},
|
||||
{ type: "assistant_message", messageId: "goal-reply", text: "DONE" },
|
||||
]);
|
||||
});
|
||||
|
||||
test("preserves system compaction and background task notifications", async () => {
|
||||
const items = await replay([
|
||||
{
|
||||
|
||||
@@ -1887,8 +1887,13 @@ export class ClaudeAgentClient implements AgentClient {
|
||||
resolveMcpServersDelivery: (launch) => this.resolveMcpServersDelivery(launch),
|
||||
rewindSdk: this.rewindSdk,
|
||||
});
|
||||
await session.ensureHistoryReady();
|
||||
return session;
|
||||
try {
|
||||
await session.ensureHistoryReady();
|
||||
return session;
|
||||
} catch (error) {
|
||||
await session.close();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async getCatalogCacheKey(_options: FetchCatalogOptions): Promise<string> {
|
||||
@@ -2689,7 +2694,7 @@ class ClaudeAgentSession implements AgentSession {
|
||||
{ type: "provider_subagent" }
|
||||
>[] = [];
|
||||
private historyPending = false;
|
||||
// Readiness never rejects; history/rebind failures are logged at their owning boundary.
|
||||
// Clears back to null when a transcript read fails so a retry re-reads from disk.
|
||||
private historyReady: Promise<void> | null = null;
|
||||
private historySessionId: string | null = null;
|
||||
private replayingHistory = false;
|
||||
@@ -3501,7 +3506,7 @@ class ClaudeAgentSession implements AgentSession {
|
||||
"provider.claude.session_close.start",
|
||||
);
|
||||
this.closed = true;
|
||||
await this.ensureHistoryReady();
|
||||
await this.historyReady?.catch(() => {});
|
||||
this.rejectAllPendingPermissions(new Error("Claude session closed"));
|
||||
// AgentManager settles the run after runtime release. Preserve cleanup records
|
||||
// without reporting this closure as an explicit turn cancellation.
|
||||
@@ -3845,9 +3850,19 @@ class ClaudeAgentSession implements AgentSession {
|
||||
]);
|
||||
}
|
||||
})();
|
||||
this.historyReady = rebind.catch((error) => {
|
||||
const tracked = rebind.catch((error) => {
|
||||
this.logger.warn({ err: error, sessionId }, "Failed to rebind Claude session");
|
||||
if (this.historySessionId === sessionId) {
|
||||
if (this.historyReady === tracked) {
|
||||
this.historyReady = null;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
// Avoid an unhandled rejection if no reader is awaiting `historyReady`, while still
|
||||
// propagating the read error to any reader already waiting on the rebound history.
|
||||
tracked.catch(() => {});
|
||||
this.historyReady = tracked;
|
||||
return rebind;
|
||||
}
|
||||
|
||||
@@ -6143,9 +6158,18 @@ class ClaudeAgentSession implements AgentSession {
|
||||
|
||||
ensureHistoryReady(): Promise<void> {
|
||||
if (!this.historyReady) {
|
||||
this.historyReady = this.historySessionId
|
||||
? this.loadPersistedHistory(this.historySessionId)
|
||||
: Promise.resolve();
|
||||
if (!this.historySessionId) {
|
||||
this.historyReady = Promise.resolve();
|
||||
} else {
|
||||
const load = this.loadPersistedHistory(this.historySessionId);
|
||||
const pending = load.catch((error) => {
|
||||
if (this.historyReady === pending) {
|
||||
this.historyReady = null;
|
||||
}
|
||||
throw error;
|
||||
});
|
||||
this.historyReady = pending;
|
||||
}
|
||||
}
|
||||
return this.historyReady;
|
||||
}
|
||||
@@ -6164,36 +6188,70 @@ class ClaudeAgentSession implements AgentSession {
|
||||
return;
|
||||
}
|
||||
await withClaudeReplayHistory(historyPath, async (history) => {
|
||||
const replay = await this.ingestPersistedSidechains(history);
|
||||
await this.ingestPersistedHistory(history.parentEntries, replay);
|
||||
const providerSubagentEvents: Extract<AgentStreamEvent, { type: "provider_subagent" }>[] =
|
||||
[];
|
||||
const replay = await this.ingestPersistedSidechains(history, providerSubagentEvents);
|
||||
const timeline = await this.ingestPersistedHistory(
|
||||
history.parentEntries,
|
||||
replay,
|
||||
providerSubagentEvents,
|
||||
);
|
||||
if (providerSubagentEvents.length > 0) {
|
||||
this.persistedProviderSubagentEvents = [
|
||||
...this.persistedProviderSubagentEvents,
|
||||
...providerSubagentEvents,
|
||||
];
|
||||
this.historyPending = true;
|
||||
}
|
||||
if (timeline.length > 0) {
|
||||
this.persistedHistory = [...this.persistedHistory, ...timeline];
|
||||
this.historyPending = true;
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
this.resetPersistedHistoryReplayState();
|
||||
if (historyPath && isMissingTranscriptError({ error, historyPath })) {
|
||||
this.logger.info(
|
||||
{ sessionId, cwd: this.config.cwd, historyPath },
|
||||
"No Claude transcript to load history from",
|
||||
);
|
||||
return;
|
||||
}
|
||||
this.logger.warn(
|
||||
{ err: error, sessionId, historyPath },
|
||||
"Failed to load Claude history from transcript",
|
||||
);
|
||||
throw error;
|
||||
} finally {
|
||||
this.replayingHistory = false;
|
||||
}
|
||||
}
|
||||
|
||||
private resetPersistedHistoryReplayState(): void {
|
||||
this.persistedHistory = [];
|
||||
this.persistedProviderSubagentEvents = [];
|
||||
this.historyPending = false;
|
||||
this.userMessageIds = [];
|
||||
this.rewindTurnAnchors.length = 0;
|
||||
this.taskState.reset();
|
||||
this.taskProtocolSource.reset();
|
||||
}
|
||||
|
||||
private async ingestPersistedHistory(
|
||||
entries: Iterable<ClaudeHistoryEntry> | AsyncIterable<ClaudeHistoryEntry>,
|
||||
replay: ClaudeReplayOwnership,
|
||||
): Promise<void> {
|
||||
providerSubagentEvents: Extract<AgentStreamEvent, { type: "provider_subagent" }>[],
|
||||
): Promise<PersistedTimelineEntry[]> {
|
||||
const timeline: PersistedTimelineEntry[] = [];
|
||||
for await (const entry of entries) {
|
||||
await this.ingestPersistedHistoryEntry(entry, timeline, replay);
|
||||
}
|
||||
|
||||
if (timeline.length > 0) {
|
||||
this.persistedHistory = [...this.persistedHistory, ...timeline];
|
||||
this.historyPending = true;
|
||||
await this.ingestPersistedHistoryEntry(entry, timeline, replay, providerSubagentEvents);
|
||||
}
|
||||
return timeline;
|
||||
}
|
||||
|
||||
private async ingestPersistedSidechains(
|
||||
history: ClaudeReplayHistory,
|
||||
providerSubagentEvents: Extract<AgentStreamEvent, { type: "provider_subagent" }>[],
|
||||
): Promise<ClaudeReplayOwnership> {
|
||||
const sidecarToolCallIdsByTaskId = new Map<string, string>();
|
||||
for (const { agentId, meta } of history.subagents) {
|
||||
@@ -6245,13 +6303,12 @@ class ClaudeAgentSession implements AgentSession {
|
||||
if (observations.length === 0) return replay;
|
||||
|
||||
for (const event of foldSubagentObservations(observations)) {
|
||||
this.persistedProviderSubagentEvents.push({
|
||||
providerSubagentEvents.push({
|
||||
type: "provider_subagent",
|
||||
provider: "claude",
|
||||
event,
|
||||
});
|
||||
}
|
||||
this.historyPending = true;
|
||||
return replay;
|
||||
}
|
||||
|
||||
@@ -6259,6 +6316,7 @@ class ClaudeAgentSession implements AgentSession {
|
||||
entry: ClaudeHistoryEntry,
|
||||
timeline: PersistedTimelineEntry[],
|
||||
replay: ClaudeReplayOwnership,
|
||||
providerSubagentEvents: Extract<AgentStreamEvent, { type: "provider_subagent" }>[],
|
||||
): Promise<void> {
|
||||
if (entry.isSidechain) {
|
||||
return;
|
||||
@@ -6274,7 +6332,7 @@ class ClaudeAgentSession implements AgentSession {
|
||||
: undefined;
|
||||
if (notificationOwner) {
|
||||
for (const item of await this.convertHistoryEntry(entry)) {
|
||||
this.persistedProviderSubagentEvents.push({
|
||||
providerSubagentEvents.push({
|
||||
type: "provider_subagent",
|
||||
provider: "claude",
|
||||
event: {
|
||||
@@ -7322,6 +7380,30 @@ async function mapAssistantHistoryBlocksWithMessageId(
|
||||
return items;
|
||||
}
|
||||
|
||||
function readGoalAcknowledgement(entry: ClaudeHistoryEntry): AgentTimelineItem | null {
|
||||
if (
|
||||
entry.type !== "system" ||
|
||||
entry.subtype !== "local_command" ||
|
||||
typeof entry.content !== "string" ||
|
||||
!isObjectRecord(entry.commandRun) ||
|
||||
entry.commandRun.command !== "goal"
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const match = /^<local-command-stdout>(Goal set: [\s\S]+)<\/local-command-stdout>$/.exec(
|
||||
entry.content,
|
||||
);
|
||||
if (!match) return null;
|
||||
|
||||
const messageId = readTrimmedString(entry.uuid);
|
||||
return {
|
||||
type: "assistant_message",
|
||||
text: match[1].trim(),
|
||||
...(messageId ? { messageId } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function convertClaudeHistoryEntryPreamble(
|
||||
entry: ClaudeHistoryEntry,
|
||||
): { shortCircuit: AgentTimelineItem[] } | { proceed: { content: unknown } } {
|
||||
@@ -7354,6 +7436,10 @@ function convertClaudeHistoryEntryPreamble(
|
||||
if (steeredPrompt) {
|
||||
return { shortCircuit: [steeredPrompt] };
|
||||
}
|
||||
const goalAcknowledgement = readGoalAcknowledgement(entry);
|
||||
if (goalAcknowledgement) {
|
||||
return { shortCircuit: [goalAcknowledgement] };
|
||||
}
|
||||
// Only user and assistant records are conversation turns. Claude Code 2.1.x also journals each
|
||||
// API request as `api-request-blob` records whose message replays the system context.
|
||||
if (entry.type !== "user" && entry.type !== "assistant") {
|
||||
@@ -7952,3 +8038,8 @@ async function transcriptExists(file: string): Promise<boolean> {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function isMissingTranscriptError(input: { error: unknown; historyPath: string }): boolean {
|
||||
const err = input.error as NodeJS.ErrnoException | null;
|
||||
return err?.code === "ENOENT" && err.path === input.historyPath;
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { constants as bufferConstants } from "node:buffer";
|
||||
import { assignTaskNotificationReplayIds } from "./task-notification-tool-call.js";
|
||||
import fs, { type FileHandle } from "node:fs/promises";
|
||||
import { setImmediate } from "node:timers/promises";
|
||||
@@ -46,6 +47,7 @@ async function* locatedRecords(
|
||||
let offset = 0;
|
||||
let pieces: Buffer[] = [];
|
||||
let length = 0;
|
||||
let oversized = false;
|
||||
while (remaining > 0) {
|
||||
const buffer = Buffer.allocUnsafe(Math.min(READ_CHUNK_BYTES, remaining));
|
||||
const { bytesRead: count } = await fd.read(buffer, 0, buffer.length, null);
|
||||
@@ -59,37 +61,54 @@ async function* locatedRecords(
|
||||
await setImmediate();
|
||||
sliceStartedAt = performance.now();
|
||||
}
|
||||
pieces.push(buffer.subarray(start, end));
|
||||
length += end - start;
|
||||
const entry = parseRecord(Buffer.concat(pieces, length).toString("utf8"));
|
||||
const location = {
|
||||
file,
|
||||
offset,
|
||||
length,
|
||||
timestamp: normalizeProviderReplayTimestamp(entry?.timestamp),
|
||||
};
|
||||
if (!oversized && length <= bufferConstants.MAX_STRING_LENGTH) {
|
||||
pieces.push(buffer.subarray(start, end));
|
||||
const entry = parseRecordBuffer({ pieces, length });
|
||||
if (entry) {
|
||||
yield {
|
||||
entry,
|
||||
location: {
|
||||
file,
|
||||
offset,
|
||||
length,
|
||||
timestamp: normalizeProviderReplayTimestamp(entry.timestamp),
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
offset += length + 1;
|
||||
pieces = [];
|
||||
length = 0;
|
||||
if (entry) yield { entry, location };
|
||||
oversized = false;
|
||||
start = end + 1;
|
||||
}
|
||||
if (start < count) {
|
||||
pieces.push(buffer.subarray(start, count));
|
||||
length += count - start;
|
||||
// A single JSONL line longer than V8's max string length can never be parsed; drop its
|
||||
// buffered slices immediately while tracking byte length so subsequent line offsets stay exact.
|
||||
if (oversized || length > bufferConstants.MAX_STRING_LENGTH) {
|
||||
oversized = true;
|
||||
pieces = [];
|
||||
} else {
|
||||
pieces.push(buffer.subarray(start, count));
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!oversized && length > 0 && length <= bufferConstants.MAX_STRING_LENGTH) {
|
||||
const entry = parseRecordBuffer({ pieces, length });
|
||||
if (entry) {
|
||||
yield {
|
||||
entry,
|
||||
location: {
|
||||
file,
|
||||
offset,
|
||||
length,
|
||||
timestamp: normalizeProviderReplayTimestamp(entry.timestamp),
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
const entry = parseRecord(Buffer.concat(pieces, length).toString("utf8"));
|
||||
if (entry)
|
||||
yield {
|
||||
entry,
|
||||
location: {
|
||||
file,
|
||||
offset,
|
||||
length,
|
||||
timestamp: normalizeProviderReplayTimestamp(entry.timestamp),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Indexed sources parse only their own records using descriptors owned by this replay. */
|
||||
@@ -156,6 +175,21 @@ function isToolResult(entry: TranscriptEntry): boolean {
|
||||
);
|
||||
}
|
||||
|
||||
function parseRecordBuffer(input: {
|
||||
pieces: readonly Buffer[];
|
||||
length: number;
|
||||
}): TranscriptEntry | null {
|
||||
try {
|
||||
const line =
|
||||
input.pieces.length === 1
|
||||
? input.pieces[0]!.toString("utf8")
|
||||
: Buffer.concat(input.pieces, input.length).toString("utf8");
|
||||
return parseRecord(line);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function parseRecord(line: string): TranscriptEntry | null {
|
||||
try {
|
||||
const value: unknown = JSON.parse(line);
|
||||
|
||||
@@ -397,5 +397,146 @@ describe("OMP tool call mapper", () => {
|
||||
),
|
||||
).toEqual({ type: "plain_text", label: "Rollout scope", text: "Ask interrupted by message" });
|
||||
});
|
||||
|
||||
test("uses a lone checkbox option label as the question and Yes as its checked answer", () => {
|
||||
const checkboxHtml =
|
||||
'<form><label><input type="checkbox" name="agree" value="yes">I accept the terms</label></form>';
|
||||
expect(mapOmpToolDetail(parseToolArgs("ask", { html: checkboxHtml }), null)).toMatchObject({
|
||||
type: "plain_text",
|
||||
label: "I accept the terms",
|
||||
});
|
||||
expect(
|
||||
mapOmpToolDetail(
|
||||
parseToolArgs("ask", { html: checkboxHtml }),
|
||||
parseToolResult({
|
||||
content: [{ type: "text", text: 'User answers:\n{\n "agree": "yes"\n}' }],
|
||||
details: {
|
||||
answers: [
|
||||
{
|
||||
name: "agree",
|
||||
question: "I accept the terms",
|
||||
answer: "I accept the terms",
|
||||
},
|
||||
],
|
||||
},
|
||||
}),
|
||||
),
|
||||
).toEqual({
|
||||
type: "plain_text",
|
||||
label: "I accept the terms",
|
||||
text: "I accept the terms\nYes",
|
||||
});
|
||||
expect(
|
||||
mapOmpToolDetail(
|
||||
parseToolArgs("ask", { html: checkboxHtml }),
|
||||
parseToolResult({
|
||||
content: [{ type: "text", text: 'User answers:\n{\n "agree": "yes"\n}' }],
|
||||
}),
|
||||
),
|
||||
).toEqual({
|
||||
type: "plain_text",
|
||||
label: "I accept the terms",
|
||||
text: "I accept the terms\nYes",
|
||||
});
|
||||
});
|
||||
|
||||
test("maps multi-field details.answers and handles missing question, missing name, and empty answers", () => {
|
||||
const multiHtml = [
|
||||
"<form>",
|
||||
" <fieldset>",
|
||||
" <legend>Rollout scope</legend>",
|
||||
' <label><input type="radio" name="scope" value="one">Staging only</label>',
|
||||
" </fieldset>",
|
||||
' <label>Notes <textarea name="notes"></textarea></label>',
|
||||
"</form>",
|
||||
].join("\n");
|
||||
expect(
|
||||
mapOmpToolDetail(
|
||||
parseToolArgs("ask", { html: multiHtml }),
|
||||
parseToolResult({
|
||||
content: [{ type: "text", text: 'User answers:\n{"scope":"one","notes":""}' }],
|
||||
details: {
|
||||
answers: [
|
||||
{ name: "scope", answer: "Staging only" },
|
||||
{ question: "Extra question", answer: "Custom reply" },
|
||||
{ name: "notes", question: "Notes", answer: "" },
|
||||
],
|
||||
},
|
||||
}),
|
||||
),
|
||||
).toEqual({
|
||||
type: "plain_text",
|
||||
label: "Rollout scope",
|
||||
text: "Rollout scope\nStaging only\n\nExtra question\nCustom reply",
|
||||
});
|
||||
});
|
||||
|
||||
test("maps checkbox arrays, free-text fields, unmatched options, and skips empty values in User answers", () => {
|
||||
const multiHtml = [
|
||||
"<form>",
|
||||
" <p>Which tools?</p>",
|
||||
' <label><input type="checkbox" name="tools" value="d">Docker</label>',
|
||||
' <label><input type="checkbox" name="tools" value="k">Kubernetes</label>',
|
||||
' <label>Days <input type="number" name="days"></label>',
|
||||
' <label>Note <textarea name="note"></textarea></label>',
|
||||
' <label>Optional <input type="text" name="optional"></label>',
|
||||
"</form>",
|
||||
].join("\n");
|
||||
expect(
|
||||
mapOmpToolDetail(
|
||||
parseToolArgs("ask", { html: multiHtml }),
|
||||
parseToolResult({
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: 'User answers:\n{"tools":["d","custom-cli"],"days":7,"note":"keep logs","optional":""}',
|
||||
},
|
||||
],
|
||||
}),
|
||||
),
|
||||
).toEqual({
|
||||
type: "plain_text",
|
||||
label: "Which tools?",
|
||||
text: "Which tools?\nDocker, custom-cli\n\nDays\n7\n\nNote\nkeep logs",
|
||||
});
|
||||
});
|
||||
|
||||
test("falls back to raw text with the form question when User answers JSON is malformed", () => {
|
||||
expect(
|
||||
mapOmpToolDetail(
|
||||
parseToolArgs("ask", { html }),
|
||||
parseToolResult({
|
||||
content: [{ type: "text", text: "User answers:\n{not valid json" }],
|
||||
}),
|
||||
),
|
||||
).toEqual({
|
||||
type: "plain_text",
|
||||
label: "Rollout scope",
|
||||
text: "User answers:\n{not valid json",
|
||||
});
|
||||
});
|
||||
|
||||
test("preserves legacy multi-question details.results mapping", () => {
|
||||
expect(
|
||||
mapOmpToolDetail(
|
||||
parseToolArgs("ask", {
|
||||
questions: [{ question: "Which colors?" }, { question: "Which shape?" }],
|
||||
}),
|
||||
parseToolResult({
|
||||
content: [{ type: "text", text: "raw" }],
|
||||
details: {
|
||||
results: [
|
||||
{ question: "Which colors?", selectedOptions: ["Red", "Blue"] },
|
||||
{ question: "Which shape?", customInput: "Hexagon" },
|
||||
],
|
||||
},
|
||||
}),
|
||||
),
|
||||
).toEqual({
|
||||
type: "plain_text",
|
||||
label: "Which colors?",
|
||||
text: "Which colors?\nRed, Blue\n\nWhich shape?\nHexagon",
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -124,7 +124,8 @@ function mapOmpAskDetail(rawArgs: unknown, result: OmpToolResult): ToolCallDetai
|
||||
const details =
|
||||
result && typeof result !== "string" && isRecord(result.details) ? result.details : {};
|
||||
const form = readAskForm(args.html);
|
||||
const formLines = readFormAnswers(details, form, extractTextFromToolResult(result));
|
||||
const resultText = extractTextFromToolResult(result);
|
||||
const formLines = readFormAnswers({ details, form, resultText });
|
||||
const answers = Array.isArray(details.results) ? details.results : [details];
|
||||
const lines =
|
||||
formLines ??
|
||||
@@ -138,7 +139,8 @@ function mapOmpAskDetail(rawArgs: unknown, result: OmpToolResult): ToolCallDetai
|
||||
[...selected, firstString(answer.customInput)].filter(Boolean).join(", ") || "No selection";
|
||||
return question ? [`${question}\n${response}`] : [];
|
||||
});
|
||||
const text = lines.length ? lines.join("\n\n") : extractTextFromToolResult(result);
|
||||
const text = lines.length ? lines.join("\n\n") : resultText;
|
||||
const firstFormQuestion = form?.fields[0] ? formFieldQuestion(form.fields[0]) : undefined;
|
||||
return {
|
||||
type: "plain_text",
|
||||
label:
|
||||
@@ -146,7 +148,7 @@ function mapOmpAskDetail(rawArgs: unknown, result: OmpToolResult): ToolCallDetai
|
||||
details.question,
|
||||
formLines?.[0]?.split("\n", 1)[0],
|
||||
askedQuestion,
|
||||
form?.fields[0] && formFieldQuestion(form.fields[0]),
|
||||
firstFormQuestion?.split("\n", 1)[0],
|
||||
args.question,
|
||||
args.title,
|
||||
) ?? "Question",
|
||||
@@ -164,17 +166,24 @@ function readAskForm(html: unknown): OmpHtmlForm | undefined {
|
||||
}
|
||||
}
|
||||
|
||||
/** A field's question: the last paragraph of its prompt, which is its legend or label. */
|
||||
/** A field's question: the last paragraph of its prompt (legend/label), a lone option's label, or its name. */
|
||||
function formFieldQuestion(field: OmpFormField): string | undefined {
|
||||
const loneOptionLabel =
|
||||
field.kind === "choice" && field.options.length === 1 ? field.options[0]?.label : undefined;
|
||||
return firstString(
|
||||
field.prompt
|
||||
.split(/\n\s*\n/)
|
||||
.at(-1)
|
||||
?.trim(),
|
||||
loneOptionLabel,
|
||||
field.name,
|
||||
);
|
||||
}
|
||||
|
||||
function isLoneCheckbox(field: OmpFormField | undefined): boolean {
|
||||
return field?.kind === "choice" && field.control === "checkbox" && field.options.length === 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* The answers to an HTML-form ask, one `question\nanswer` block per field.
|
||||
* OMP 19 reports them in `details.answers` (`{ name, question, answer }`,
|
||||
@@ -182,17 +191,20 @@ function formFieldQuestion(field: OmpFormField): string | undefined {
|
||||
* (`User answers:\n{ "<name>": "<value>" }`) is read against the form so a
|
||||
* chosen value shows as its option's text.
|
||||
*/
|
||||
function readFormAnswers(
|
||||
details: Record<string, unknown>,
|
||||
form: OmpHtmlForm | undefined,
|
||||
resultText: string | undefined,
|
||||
): string[] | undefined {
|
||||
function readFormAnswers(input: {
|
||||
details: Record<string, unknown>;
|
||||
form: OmpHtmlForm | undefined;
|
||||
resultText: string | undefined;
|
||||
}): string[] | undefined {
|
||||
const { details, form, resultText } = input;
|
||||
if (Array.isArray(details.answers)) {
|
||||
const lines = details.answers.flatMap((entry) => {
|
||||
if (!isRecord(entry)) return [];
|
||||
const field = form?.fields.find((candidate) => candidate.name === entry.name);
|
||||
const question = firstString(entry.question, field && formFieldQuestion(field), entry.name);
|
||||
const answer = formatFormAnswer(entry.answer);
|
||||
const rawAnswer = formatFormAnswer(entry.answer);
|
||||
const answer =
|
||||
rawAnswer && isLoneCheckbox(field) && rawAnswer === question ? "Yes" : rawAnswer;
|
||||
return question && answer ? [`${question}\n${answer}`] : [];
|
||||
});
|
||||
if (lines.length) return lines;
|
||||
@@ -201,15 +213,18 @@ function readFormAnswers(
|
||||
const values = readUserAnswersText(resultText);
|
||||
if (!values) return undefined;
|
||||
const lines = form.fields.flatMap((field) => {
|
||||
if (!(field.name in values)) return [];
|
||||
if (!Object.hasOwn(values, field.name)) return [];
|
||||
const question = formFieldQuestion(field);
|
||||
const raw = values[field.name];
|
||||
const chosen = (Array.isArray(raw) ? raw : [raw]).map((value) => {
|
||||
const option =
|
||||
field.kind === "choice" ? field.options.find((entry) => entry.value === value) : undefined;
|
||||
return option?.label ?? formatFormAnswer(value);
|
||||
if (option && isLoneCheckbox(field) && option.label === question) {
|
||||
return "Yes";
|
||||
}
|
||||
return firstString(option?.label, formatFormAnswer(value));
|
||||
});
|
||||
const answer = chosen.filter(Boolean).join(", ");
|
||||
const question = formFieldQuestion(field);
|
||||
return question && answer ? [`${question}\n${answer}`] : [];
|
||||
});
|
||||
return lines.length ? lines : undefined;
|
||||
|
||||
@@ -4,6 +4,9 @@ import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import { createTestLogger } from "../../../test-utils/test-logger.js";
|
||||
import { AgentManager } from "../agent-manager.js";
|
||||
import { createStoredAgentTimeline } from "../timeline/index.js";
|
||||
import { openTestTimelineDatabase } from "../timeline/testing.js";
|
||||
import type { Event as OpenCodeEvent } from "@opencode-ai/sdk/v2/client";
|
||||
import type { OpencodeClient } from "@opencode-ai/sdk/v2/client";
|
||||
import type { OpenCodeEventSource } from "./opencode/event-consumer.js";
|
||||
@@ -2343,6 +2346,229 @@ describe("OpenCode adapter startTurn error handling", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
test("streamHistory throws when session.messages fails or returns no data", async () => {
|
||||
const errorClient = {
|
||||
session: {
|
||||
get: async () => ({ data: { revert: undefined }, error: undefined }),
|
||||
messages: async () => ({
|
||||
data: undefined,
|
||||
error: { name: "ServerError", message: "backend unavailable" },
|
||||
}),
|
||||
},
|
||||
} as never;
|
||||
|
||||
const errorSession = new __openCodeInternals.OpenCodeAgentSession(
|
||||
{ provider: "opencode", cwd: "/tmp/repo" },
|
||||
errorClient,
|
||||
"ses_msg_error",
|
||||
createTestLogger(),
|
||||
{},
|
||||
);
|
||||
await expect(Array.fromAsync(errorSession.streamHistory())).rejects.toThrow(
|
||||
/Failed to load OpenCode session messages for ses_msg_error.*backend unavailable/,
|
||||
);
|
||||
|
||||
const emptyClient = {
|
||||
session: {
|
||||
get: async () => ({ data: { revert: undefined }, error: undefined }),
|
||||
messages: async () => ({ data: undefined, error: undefined }),
|
||||
},
|
||||
} as never;
|
||||
|
||||
const emptySession = new __openCodeInternals.OpenCodeAgentSession(
|
||||
{ provider: "opencode", cwd: "/tmp/repo" },
|
||||
emptyClient,
|
||||
"ses_msg_empty",
|
||||
createTestLogger(),
|
||||
{},
|
||||
);
|
||||
await expect(Array.fromAsync(emptySession.streamHistory())).rejects.toThrow(
|
||||
/Failed to load OpenCode session messages for ses_msg_empty.*empty response/,
|
||||
);
|
||||
});
|
||||
|
||||
test("streamHistory throws when session.get fails on a reverted session, then filters reverted turns on retry", async () => {
|
||||
let failGet = true;
|
||||
let messagesCalls = 0;
|
||||
const fakeClient = {
|
||||
session: {
|
||||
get: async () =>
|
||||
failGet
|
||||
? {
|
||||
data: undefined,
|
||||
error: { name: "NotFoundError", message: "session missing" },
|
||||
}
|
||||
: {
|
||||
data: { revert: { messageID: "msg_reverted" } },
|
||||
error: undefined,
|
||||
},
|
||||
messages: async () => {
|
||||
messagesCalls += 1;
|
||||
return {
|
||||
data: [
|
||||
{
|
||||
info: { id: "msg_kept", sessionID: "ses_get_error", role: "user" },
|
||||
parts: [
|
||||
{
|
||||
id: "prt_kept",
|
||||
sessionID: "ses_get_error",
|
||||
messageID: "msg_kept",
|
||||
type: "text",
|
||||
text: "kept prompt",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
info: { id: "msg_reverted", sessionID: "ses_get_error", role: "user" },
|
||||
parts: [
|
||||
{
|
||||
id: "prt_reverted",
|
||||
sessionID: "ses_get_error",
|
||||
messageID: "msg_reverted",
|
||||
type: "text",
|
||||
text: "reverted prompt",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
error: undefined,
|
||||
};
|
||||
},
|
||||
},
|
||||
} as never;
|
||||
|
||||
const session = new __openCodeInternals.OpenCodeAgentSession(
|
||||
{ provider: "opencode", cwd: "/tmp/repo" },
|
||||
fakeClient,
|
||||
"ses_get_error",
|
||||
createTestLogger(),
|
||||
{},
|
||||
);
|
||||
|
||||
await expect(Array.fromAsync(session.streamHistory())).rejects.toThrow(
|
||||
/Failed to load OpenCode session ses_get_error.*session missing/,
|
||||
);
|
||||
expect(messagesCalls).toBe(0);
|
||||
|
||||
failGet = false;
|
||||
expect(await Array.fromAsync(session.streamHistory())).toEqual([
|
||||
{
|
||||
type: "timeline",
|
||||
provider: "opencode",
|
||||
item: { type: "user_message", text: "kept prompt", messageId: "msg_kept" },
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test("leaves agent unregistered with no paseo.db row when session.messages fails, then imports on retry", async () => {
|
||||
const cwd = mkdtempSync(path.join(os.tmpdir(), "opencode-history-retry-"));
|
||||
const database = openTestTimelineDatabase();
|
||||
const timeline = createStoredAgentTimeline(database);
|
||||
let failMessages = true;
|
||||
|
||||
const fakeSdkClient = {
|
||||
session: {
|
||||
get: async () => ({ data: { revert: undefined }, error: undefined }),
|
||||
messages: async () => {
|
||||
if (failMessages) {
|
||||
return {
|
||||
data: undefined,
|
||||
error: { name: "NetworkError", message: "temporary RPC outage" },
|
||||
};
|
||||
}
|
||||
return {
|
||||
data: [
|
||||
{
|
||||
info: { id: "msg_user", sessionID: "ses_retry", role: "user" },
|
||||
parts: [
|
||||
{
|
||||
id: "prt_user",
|
||||
sessionID: "ses_retry",
|
||||
messageID: "msg_user",
|
||||
type: "text",
|
||||
text: "hello opencode",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
info: { id: "msg_assistant", sessionID: "ses_retry", role: "assistant" },
|
||||
parts: [
|
||||
{
|
||||
id: "prt_assistant",
|
||||
sessionID: "ses_retry",
|
||||
messageID: "msg_assistant",
|
||||
type: "text",
|
||||
text: "recovered reply",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
error: undefined,
|
||||
};
|
||||
},
|
||||
abort: async () => ({ data: undefined, error: undefined }),
|
||||
},
|
||||
app: {
|
||||
agents: async () => ({ data: [], error: undefined }),
|
||||
},
|
||||
command: {
|
||||
list: async () => ({ data: [], error: undefined }),
|
||||
},
|
||||
} as never;
|
||||
|
||||
const fakeProviderClient = {
|
||||
provider: "opencode" as const,
|
||||
capabilities: {},
|
||||
isAvailable: async () => true,
|
||||
startSession: async () => {
|
||||
throw new Error("not used");
|
||||
},
|
||||
resumeSession: async (handle: { sessionId: string }, overrides?: { cwd?: string }) =>
|
||||
new __openCodeInternals.OpenCodeAgentSession(
|
||||
{ provider: "opencode", cwd: overrides?.cwd ?? cwd },
|
||||
fakeSdkClient,
|
||||
handle.sessionId,
|
||||
createTestLogger(),
|
||||
{},
|
||||
),
|
||||
};
|
||||
|
||||
const manager = new AgentManager({
|
||||
clients: { opencode: fakeProviderClient as never },
|
||||
logger: createTestLogger(),
|
||||
timeline,
|
||||
});
|
||||
|
||||
const agentId = "00000000-0000-4000-8000-000000000010";
|
||||
const handle = { provider: "opencode" as const, sessionId: "ses_retry" };
|
||||
|
||||
try {
|
||||
await expect(manager.resumeAgentFromPersistence(handle, { cwd }, agentId)).rejects.toThrow(
|
||||
/temporary RPC outage/,
|
||||
);
|
||||
|
||||
expect(manager.getAgent(agentId)).toBeNull();
|
||||
expect(await manager.hasStoredHistory(agentId)).toBe(false);
|
||||
expect(
|
||||
database.read((sql) =>
|
||||
sql.all("SELECT agent_id FROM timeline_scopes WHERE agent_id = ?", agentId),
|
||||
),
|
||||
).toEqual([]);
|
||||
|
||||
failMessages = false;
|
||||
await manager.resumeAgentFromPersistence(handle, { cwd }, agentId);
|
||||
|
||||
expect(await manager.hasStoredHistory(agentId)).toBe(true);
|
||||
expect(await manager.getTimeline(agentId)).toEqual([
|
||||
{ type: "user_message", text: "hello opencode", messageId: "msg_user" },
|
||||
{ type: "assistant_message", text: "recovered reply", messageId: "msg_assistant" },
|
||||
]);
|
||||
} finally {
|
||||
await manager.closeAgent(agentId).catch(() => undefined);
|
||||
rmSync(cwd, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("emits turn_failed when client.session.promptAsync throws synchronously", async () => {
|
||||
// Yield the server-connected event, then park forever. The adapter waits
|
||||
// for that first event before sending the prompt.
|
||||
|
||||
@@ -4946,19 +4946,27 @@ class OpenCodeAgentSession implements AgentSession {
|
||||
sessionID: this.sessionId,
|
||||
directory: this.config.cwd,
|
||||
});
|
||||
if (sessionResponse.error || !sessionResponse.data) {
|
||||
throw new Error(
|
||||
`Failed to load OpenCode session ${this.sessionId}: ${
|
||||
sessionResponse.error ? toDiagnosticErrorMessage(sessionResponse.error) : "empty response"
|
||||
}`,
|
||||
);
|
||||
}
|
||||
|
||||
const response = await this.client.session.messages({
|
||||
sessionID: this.sessionId,
|
||||
directory: this.config.cwd,
|
||||
});
|
||||
|
||||
if (response.error || !response.data) {
|
||||
return;
|
||||
throw new Error(
|
||||
`Failed to load OpenCode session messages for ${this.sessionId}: ${
|
||||
response.error ? toDiagnosticErrorMessage(response.error) : "empty response"
|
||||
}`,
|
||||
);
|
||||
}
|
||||
|
||||
const messages = filterOpenCodeRevertedMessages(
|
||||
response.data,
|
||||
sessionResponse.error ? null : sessionResponse.data?.revert,
|
||||
);
|
||||
const messages = filterOpenCodeRevertedMessages(response.data, sessionResponse.data.revert);
|
||||
for (const message of messages) {
|
||||
for (const event of buildOpenCodeReplayTimelineEvents(message)) {
|
||||
yield event;
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { lastAssistantMessageText } from "../../../assistant-message.js";
|
||||
import { projectTimelineRows } from "../../../timeline-projection.js";
|
||||
import { collectTimelineSnapshot } from "../test-utils/v2-timeline.js";
|
||||
import type { SessionMessageAssistant } from "@opencode/client";
|
||||
import { execFileSync } from "node:child_process";
|
||||
@@ -136,3 +138,37 @@ test.each(["delta", "snapshot"] as const)(
|
||||
expect(retainedBytesAfterStreaming(mode, chunks)).toBeLessThan(textBytes * 32);
|
||||
},
|
||||
);
|
||||
|
||||
test.each(["snapshot", "stream"] as const)(
|
||||
"empty reasoning between two text parts keeps their paragraphs distinct in %s",
|
||||
async (mode) => {
|
||||
const timeline = new V2Timeline();
|
||||
const message = assistant([
|
||||
{ type: "text", text: "I checked content search." },
|
||||
{ type: "reasoning", text: "" },
|
||||
{ type: "text", text: "The newly named tool works." },
|
||||
]);
|
||||
const liveEvents = [];
|
||||
if (mode === "stream") {
|
||||
const commentary = { assistantMessageID: message.id, type: "text" as const, ordinal: 0 };
|
||||
timeline.startPart(commentary);
|
||||
liveEvents.push(timeline.delta({ ...commentary, delta: "I checked content search." }));
|
||||
const final = { ...commentary, ordinal: 1 };
|
||||
timeline.startPart(final);
|
||||
liveEvents.push(timeline.delta({ ...final, delta: "The newly" }));
|
||||
}
|
||||
const replayEvents = await collectTimelineSnapshot(timeline, [message]);
|
||||
const rows = [...liveEvents, ...replayEvents].flatMap((event, index) =>
|
||||
event?.type === "timeline"
|
||||
? [{ item: event.item, timestamp: event.timestamp, seq: index + 1, turnId: "turn" }]
|
||||
: [],
|
||||
);
|
||||
const replies = projectTimelineRows({ rows, mode: "projected" }).flatMap(({ item }) =>
|
||||
item.type === "assistant_message" ? [item.text] : [],
|
||||
);
|
||||
|
||||
const expected = "I checked content search.\n\nThe newly named tool works.";
|
||||
expect.soft(replies).toEqual([expected]);
|
||||
expect.soft(lastAssistantMessageText(rows)).toBe(expected);
|
||||
},
|
||||
);
|
||||
|
||||
@@ -49,11 +49,13 @@ export class V2Timeline {
|
||||
if (!text.startsWith(emitted))
|
||||
throw new Error("OpenCode changed previously emitted message content");
|
||||
this.content.set(key, text);
|
||||
const suffix = detachedSuffix(text, emitted.length);
|
||||
const item: AgentTimelineItem =
|
||||
event.type === "text"
|
||||
? { type: "assistant_message", text: suffix, messageId: event.assistantMessageID }
|
||||
: { type: "reasoning", text: suffix };
|
||||
const item = this.textItem({
|
||||
messageID: event.assistantMessageID,
|
||||
type: event.type,
|
||||
ordinal: event.ordinal,
|
||||
text,
|
||||
previous: emitted,
|
||||
});
|
||||
return { type: "timeline", provider: "opencode", item, timestamp: new Date().toISOString() };
|
||||
}
|
||||
|
||||
@@ -199,10 +201,35 @@ export class V2Timeline {
|
||||
if (!part.text.startsWith(previous))
|
||||
throw new Error("OpenCode changed previously emitted message content");
|
||||
this.content.set(key, part.text);
|
||||
const suffix = detachedSuffix(part.text, previous.length);
|
||||
if (part.type === "text")
|
||||
push({ type: "assistant_message", text: suffix, messageId: messageID });
|
||||
else push({ type: "reasoning", text: suffix });
|
||||
push(this.textItem({ messageID, type: part.type, ordinal, text: part.text, previous }));
|
||||
}
|
||||
|
||||
private textItem({
|
||||
messageID,
|
||||
type,
|
||||
ordinal,
|
||||
text,
|
||||
previous,
|
||||
}: {
|
||||
messageID: string;
|
||||
type: "text" | "reasoning";
|
||||
ordinal: number;
|
||||
text: string;
|
||||
previous: string;
|
||||
}): AgentTimelineItem {
|
||||
const suffix = detachedSuffix(text, previous.length);
|
||||
if (type === "reasoning") return { type: "reasoning", text: suffix };
|
||||
|
||||
// Projection joins chunks with the same message ID. Separate OpenCode text parts
|
||||
// once, at the first emitted chunk, so live output and history replay agree.
|
||||
if (previous.length === 0) {
|
||||
for (let earlier = ordinal - 1; earlier >= 0; earlier--) {
|
||||
if (this.content.has(textPartKey(messageID, "text", earlier))) {
|
||||
return { type: "assistant_message", text: `\n\n${suffix}`, messageId: messageID };
|
||||
}
|
||||
}
|
||||
}
|
||||
return { type: "assistant_message", text: suffix, messageId: messageID };
|
||||
}
|
||||
|
||||
private async toolPart(
|
||||
|
||||
@@ -118,22 +118,24 @@ class CountingDatabase implements DaemonDatabase {
|
||||
describe("SQLite timeline backend against the memory backend", () => {
|
||||
it("stores the same history and serves the same pages on seeded randomized timelines", () => {
|
||||
const random = seededRandom(0x5eed_0001);
|
||||
const memory = new MemoryTimelineBackend();
|
||||
const sqlite = new SqliteTimelineBackend(openTestTimelineDatabase());
|
||||
const backends = [memory, sqlite] as const;
|
||||
for (let scenario = 0; scenario < 40; scenario++) {
|
||||
const memory = new MemoryTimelineBackend();
|
||||
const sqlite = new SqliteTimelineBackend(openTestTimelineDatabase());
|
||||
const backends = [memory, sqlite] as const;
|
||||
for (const backend of backends) backend.create(scope, { epoch: "e" });
|
||||
const scenarioScope: TimelineScope = { agentId: `agent-${scenario}` };
|
||||
const seededScope: TimelineScope = { agentId: `seeded-${scenario}` };
|
||||
for (const backend of backends) backend.create(scenarioScope, { epoch: "e" });
|
||||
let turn = 0;
|
||||
for (let step = 0; step < 120; step++) {
|
||||
const roll = random(20);
|
||||
const identity = String(random(6));
|
||||
const text = `${scenario}-${step}`;
|
||||
if (roll === 0) {
|
||||
const prompts = memory.promptRows(scope);
|
||||
const prompts = memory.promptRows(scenarioScope);
|
||||
if (prompts.length > 0) {
|
||||
const retireFromSeq = prompts[random(prompts.length)].seqStart;
|
||||
const results = backends.map((backend) =>
|
||||
backend.retire(scope, { retireFromSeq, selectChildren: () => [] }),
|
||||
backend.retire(scenarioScope, { retireFromSeq, selectChildren: () => [] }),
|
||||
);
|
||||
expect(results[1]).toEqual(results[0]);
|
||||
}
|
||||
@@ -143,7 +145,11 @@ describe("SQLite timeline backend against the memory backend", () => {
|
||||
const turnId = random(2) === 0 ? String(turn) : undefined;
|
||||
const metrics = [{ name: "tokens", value: step }] as never;
|
||||
const results = backends.map((backend) =>
|
||||
backend.stampTurnMetrics(scope, metrics, turnId === undefined ? {} : { turnId }),
|
||||
backend.stampTurnMetrics(
|
||||
scenarioScope,
|
||||
metrics,
|
||||
turnId === undefined ? {} : { turnId },
|
||||
),
|
||||
);
|
||||
expect(results[1]).toEqual(results[0]);
|
||||
continue;
|
||||
@@ -151,7 +157,7 @@ describe("SQLite timeline backend against the memory backend", () => {
|
||||
if (roll === 2) {
|
||||
const clientMessageId = `client-${random(step + 1)}`;
|
||||
const results = backends.map((backend) =>
|
||||
backend.attachProviderMessageId(scope, clientMessageId, `provider-${step}`),
|
||||
backend.attachProviderMessageId(scenarioScope, clientMessageId, `provider-${step}`),
|
||||
);
|
||||
expect(results[1]).toEqual(results[0]);
|
||||
continue;
|
||||
@@ -174,16 +180,16 @@ describe("SQLite timeline backend against the memory backend", () => {
|
||||
},
|
||||
];
|
||||
const next = entry(items[random(items.length)], { turnId: String(turn) });
|
||||
const retired = backends.map((backend) => backend.isRetired(scope, next));
|
||||
const retired = backends.map((backend) => backend.isRetired(scenarioScope, next));
|
||||
expect(retired[1]).toBe(retired[0]);
|
||||
const results = backends.map((backend) => backend.append(scope, [next]));
|
||||
const results = backends.map((backend) => backend.append(scenarioScope, [next]));
|
||||
expect(results[1]).toEqual(results[0]);
|
||||
}
|
||||
expectSameHistory(memory, sqlite);
|
||||
expectSameHistory(memory, sqlite, scenarioScope);
|
||||
// Seeding from projected rows, as an import does, keeps both in step too.
|
||||
const rows = memory.readRows(scope);
|
||||
for (const backend of backends) backend.create({ agentId: "seeded" }, { rows, epoch: "e" });
|
||||
expectSameHistory(memory, sqlite, { agentId: "seeded" });
|
||||
const rows = memory.readRows(scenarioScope);
|
||||
for (const backend of backends) backend.create(seededScope, { rows, epoch: "e" });
|
||||
expectSameHistory(memory, sqlite, seededScope);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,6 +3,7 @@ import { changeRequestStatusSchema } from "../../../services/change-request-sour
|
||||
import { registerPluginTools } from "./plugin-tools.js";
|
||||
import type { FinishSubscriptions, FinishRegistration } from "../finish-subscriptions/index.js";
|
||||
import type { AgentMessageDelivery } from "../agent-messages/index.js";
|
||||
import type { AgentMessageReceipt } from "../agent-messages/delivery.js";
|
||||
import {
|
||||
createHostResolver,
|
||||
HostOperationRejectedError,
|
||||
@@ -71,6 +72,7 @@ import { TerminalInputModeTracker } from "@getpaseo/protocol/terminal-input-mode
|
||||
import type { CreatePaseoWorktreeWorkflowFn } from "../../worktree-session.js";
|
||||
import { computeNextRunAt, validateScheduleCadence } from "../../schedule/cron.js";
|
||||
import {
|
||||
InvalidScheduleIdError,
|
||||
ScheduleNotFoundError,
|
||||
ScheduleStateConflictError,
|
||||
type ScheduleService,
|
||||
@@ -1136,7 +1138,7 @@ function createToolCatalog(
|
||||
try {
|
||||
schedule = await scheduleService.inspect(id);
|
||||
} catch (error) {
|
||||
if (error instanceof ScheduleNotFoundError) {
|
||||
if (error instanceof ScheduleNotFoundError || error instanceof InvalidScheduleIdError) {
|
||||
throw new PaseoToolInputError(error.message);
|
||||
}
|
||||
throw error;
|
||||
@@ -1153,7 +1155,7 @@ function createToolCatalog(
|
||||
try {
|
||||
return await action();
|
||||
} catch (error) {
|
||||
if (error instanceof ScheduleStateConflictError) {
|
||||
if (error instanceof ScheduleStateConflictError || error instanceof InvalidScheduleIdError) {
|
||||
throw new PaseoToolInputError(error.message);
|
||||
}
|
||||
throw error;
|
||||
@@ -2149,6 +2151,24 @@ function createToolCatalog(
|
||||
),
|
||||
);
|
||||
}
|
||||
function formatQueuedResponse(receipt: AgentMessageReceipt) {
|
||||
void receipt.dispatched.catch(() => {
|
||||
rejectNotification();
|
||||
});
|
||||
return {
|
||||
content: [],
|
||||
structuredContent: {
|
||||
success: true,
|
||||
deliveryStatus: receipt.status,
|
||||
messageId: receipt.messageId,
|
||||
activeTurnBehavior: receipt.activeTurnBehavior,
|
||||
status: agentManager.getAgent(agentId)?.lifecycle ?? "idle",
|
||||
guidance: notifying
|
||||
? `${receipt.guidance} ${PROMPTED_AGENT_NOTIFICATION_GUIDANCE}`
|
||||
: receipt.guidance,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
if (callerAgentId) {
|
||||
const receipt = await agentMessages()
|
||||
@@ -2169,22 +2189,7 @@ function createToolCatalog(
|
||||
rejectNotification();
|
||||
throw error;
|
||||
});
|
||||
void receipt.dispatched.catch(() => {
|
||||
rejectNotification();
|
||||
});
|
||||
return {
|
||||
content: [],
|
||||
structuredContent: {
|
||||
success: true,
|
||||
deliveryStatus: receipt.status,
|
||||
messageId: receipt.messageId,
|
||||
activeTurnBehavior: receipt.activeTurnBehavior,
|
||||
status: agentManager.getAgent(agentId)?.lifecycle ?? "idle",
|
||||
guidance: notifying
|
||||
? `${receipt.guidance} ${PROMPTED_AGENT_NOTIFICATION_GUIDANCE}`
|
||||
: receipt.guidance,
|
||||
},
|
||||
};
|
||||
return formatQueuedResponse(receipt);
|
||||
}
|
||||
|
||||
const dispatch = await sendPromptToAgent({
|
||||
@@ -2193,7 +2198,7 @@ function createToolCatalog(
|
||||
agentStorage,
|
||||
agentId,
|
||||
prompt,
|
||||
source: callerAgentId ? { kind: "agent-message", agentId: callerAgentId } : undefined,
|
||||
source: undefined,
|
||||
sessionMode,
|
||||
activeTurnBehavior,
|
||||
onDispatch: confirmDispatch,
|
||||
@@ -2207,6 +2212,9 @@ function createToolCatalog(
|
||||
});
|
||||
|
||||
// Return once the provider has accepted the turn, so the status reports it running.
|
||||
if (dispatch.disposition === "queued") {
|
||||
return formatQueuedResponse(dispatch.receipt);
|
||||
}
|
||||
const { disposition } = dispatch;
|
||||
if (dispatch.disposition === "turn_started") {
|
||||
await waitForAgentRunStartWithTimeout(agentManager, agentId, dispatch.started).catch(
|
||||
|
||||
@@ -9,7 +9,12 @@ import {
|
||||
createFinishObservation,
|
||||
createJsonFinishSubscriptionStore,
|
||||
} from "./agent/finish-subscriptions/index.js";
|
||||
import type { AgentMessageDelivery } from "./agent/agent-messages/index.js";
|
||||
import {
|
||||
agentMessageQueueSchema,
|
||||
createSqliteAgentMessageQueueStore,
|
||||
type AgentMessageDelivery,
|
||||
type AgentMessageQueueStore,
|
||||
} from "./agent/agent-messages/index.js";
|
||||
import type { AgentQueueBackend } from "./session/agent-queue-source.js";
|
||||
import { createWorkspaceRuntimeStore } from "./workspace-runtime-store/index.js";
|
||||
import type { PluginRegistries } from "@getpaseo/protocol/plugin-registry";
|
||||
@@ -618,10 +623,11 @@ export async function createPaseoDaemon(
|
||||
await mkdir(config.paseoHome, { recursive: true });
|
||||
const database = openDaemonDatabase({
|
||||
path: path.join(config.paseoHome, "paseo.db"),
|
||||
modules: [timelineSchema],
|
||||
modules: [timelineSchema, agentMessageQueueSchema],
|
||||
logger: rootLogger.child({ module: "database" }),
|
||||
});
|
||||
const timeline = createStoredAgentTimeline(database);
|
||||
const agentMessageQueueStore = createSqliteAgentMessageQueueStore(database);
|
||||
try {
|
||||
return await assemblePaseoDaemon({
|
||||
config,
|
||||
@@ -630,6 +636,7 @@ export async function createPaseoDaemon(
|
||||
hostMachineKindReady,
|
||||
database,
|
||||
timeline,
|
||||
agentMessageQueueStore,
|
||||
});
|
||||
} catch (error) {
|
||||
await timeline.close();
|
||||
@@ -646,6 +653,7 @@ interface PaseoDaemonAssembly {
|
||||
hostMachineKindReady: Promise<HostMachineKind | null>;
|
||||
database: DaemonDatabase;
|
||||
timeline: AgentTimeline;
|
||||
agentMessageQueueStore: AgentMessageQueueStore;
|
||||
}
|
||||
|
||||
async function assemblePaseoDaemon({
|
||||
@@ -655,6 +663,7 @@ async function assemblePaseoDaemon({
|
||||
hostMachineKindReady,
|
||||
database,
|
||||
timeline,
|
||||
agentMessageQueueStore,
|
||||
}: PaseoDaemonAssembly): Promise<PaseoDaemon> {
|
||||
const bootstrapStart = performance.now();
|
||||
const elapsed = () => `${(performance.now() - bootstrapStart).toFixed(0)}ms`;
|
||||
@@ -2056,6 +2065,7 @@ async function assemblePaseoDaemon({
|
||||
workspaceArchiveOperations,
|
||||
config.pushNotifications,
|
||||
tunnelManager,
|
||||
agentMessageQueueStore,
|
||||
);
|
||||
pluginRuntime.bindPaseoSessionHost(wsServer);
|
||||
await pluginRuntime.start();
|
||||
@@ -2141,6 +2151,7 @@ async function assemblePaseoDaemon({
|
||||
httpServer.closeAllConnections();
|
||||
await new Promise<void>((resolve) => httpServer.close(() => resolve()));
|
||||
}
|
||||
await wsServer?.agentMessages.close().catch(() => undefined);
|
||||
await timeline.close();
|
||||
database.close();
|
||||
throw error;
|
||||
|
||||
@@ -204,3 +204,154 @@ test("paseo.agents.ref().send with activeTurnBehavior queue works while running
|
||||
await close();
|
||||
}
|
||||
});
|
||||
|
||||
/** A Claude recipient running an initial turn, with named turn gates to inspect each mode transition. */
|
||||
async function createModeBoundaryRecipient(input: {
|
||||
initialModeId: string;
|
||||
title: string;
|
||||
initialPrompt: string;
|
||||
heldPrompts: readonly string[];
|
||||
}) {
|
||||
const artifacts = path.resolve(".artifacts");
|
||||
await mkdir(artifacts, { recursive: true });
|
||||
const root = await mkdtemp(path.join(artifacts, "agent-mode-boundary-"));
|
||||
const executedTurns: Array<{ prompt: string; modeId: string | undefined }> = [];
|
||||
const gates = new Map<string, { promise: Promise<void>; release: () => void }>();
|
||||
for (const prompt of [input.initialPrompt, ...input.heldPrompts]) {
|
||||
let release!: () => void;
|
||||
const promise = new Promise<void>((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
gates.set(prompt, { promise, release });
|
||||
}
|
||||
const daemon = await createTestPaseoDaemon({
|
||||
agentClients: createTestAgentClients({
|
||||
onStartTurn: (prompt, config) => {
|
||||
executedTurns.push({ prompt: String(prompt), modeId: config.modeId });
|
||||
},
|
||||
beforeTurnComplete: async (prompt) => {
|
||||
const text = String(prompt);
|
||||
for (const [needle, gate] of gates) {
|
||||
if (text.includes(needle)) {
|
||||
await gate.promise;
|
||||
return;
|
||||
}
|
||||
}
|
||||
},
|
||||
}),
|
||||
paseoHomeRoot: path.join(root, "daemon"),
|
||||
staticDir: path.join(root, "static"),
|
||||
cleanup: false,
|
||||
});
|
||||
const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` });
|
||||
const close = async () => {
|
||||
for (const gate of gates.values()) {
|
||||
gate.release();
|
||||
}
|
||||
await client.close();
|
||||
await daemon.close();
|
||||
await rm(root, { recursive: true, force: true });
|
||||
};
|
||||
try {
|
||||
await client.connect();
|
||||
await client.fetchAgents({ subscribe: {} });
|
||||
const agent = await client.createAgent({
|
||||
provider: "claude",
|
||||
cwd: root,
|
||||
modeId: input.initialModeId,
|
||||
title: input.title,
|
||||
});
|
||||
await client.sendMessage(agent.id, input.initialPrompt);
|
||||
await client.waitForAgentUpsert(agent.id, (snapshot) => snapshot.status === "running");
|
||||
const releaseTurn = (prompt: string) => {
|
||||
gates.get(prompt)?.release();
|
||||
};
|
||||
const waitForTurn = async (index: number) => {
|
||||
await expect.poll(() => executedTurns.length, { timeout: 10_000 }).toBe(index + 1);
|
||||
return executedTurns[index];
|
||||
};
|
||||
return { agent, client, releaseTurn, waitForTurn, close };
|
||||
} catch (error) {
|
||||
await close();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
test("a direct broader-mode send behind a queued plan-mode message runs as two separate turns in their respective modes", async () => {
|
||||
const { agent, client, releaseTurn, waitForTurn, close } = await createModeBoundaryRecipient({
|
||||
initialModeId: "default",
|
||||
title: "Mode Boundary Worker",
|
||||
initialPrompt: "Initial work",
|
||||
heldPrompts: ["Inspect files read-only"],
|
||||
});
|
||||
try {
|
||||
const queuedReceipt = await client.sendAgentMessage(agent.id, "Inspect files read-only", {
|
||||
activeTurnBehavior: "queue",
|
||||
sessionMode: "plan",
|
||||
});
|
||||
expect(queuedReceipt).toMatchObject({ deliveryStatus: "queued", activeTurnBehavior: "queue" });
|
||||
|
||||
const directReceipt = await client.sendAgentMessage(agent.id, "Edit production files", {
|
||||
activeTurnBehavior: "interrupt",
|
||||
sessionMode: "bypassPermissions",
|
||||
});
|
||||
expect(directReceipt).toMatchObject({
|
||||
deliveryStatus: "queued",
|
||||
activeTurnBehavior: "interrupt",
|
||||
});
|
||||
|
||||
releaseTurn("Initial work");
|
||||
expect(await waitForTurn(1)).toEqual({
|
||||
prompt: "Inspect files read-only",
|
||||
modeId: "plan",
|
||||
});
|
||||
|
||||
releaseTurn("Inspect files read-only");
|
||||
expect(await waitForTurn(2)).toEqual({
|
||||
prompt: "Edit production files",
|
||||
modeId: "bypassPermissions",
|
||||
});
|
||||
await client.waitForAgentUpsert(agent.id, (snapshot) => snapshot.status === "idle");
|
||||
} finally {
|
||||
await close();
|
||||
}
|
||||
});
|
||||
|
||||
test("a direct bypassPermissions send behind a queued implicit-mode message on a restricted-mode agent runs as two separate turns", async () => {
|
||||
const { agent, client, releaseTurn, waitForTurn, close } = await createModeBoundaryRecipient({
|
||||
initialModeId: "always-ask",
|
||||
title: "Implicit Mode Worker",
|
||||
initialPrompt: "Initial restricted turn",
|
||||
heldPrompts: ["Queued in existing mode"],
|
||||
});
|
||||
try {
|
||||
const queuedReceipt = await client.sendAgentMessage(agent.id, "Queued in existing mode", {
|
||||
activeTurnBehavior: "queue",
|
||||
});
|
||||
expect(queuedReceipt).toMatchObject({ deliveryStatus: "queued", activeTurnBehavior: "queue" });
|
||||
|
||||
const directReceipt = await client.sendAgentMessage(agent.id, "Apply edits in bypass mode", {
|
||||
activeTurnBehavior: "interrupt",
|
||||
sessionMode: "bypassPermissions",
|
||||
});
|
||||
expect(directReceipt).toMatchObject({
|
||||
deliveryStatus: "queued",
|
||||
activeTurnBehavior: "interrupt",
|
||||
});
|
||||
|
||||
releaseTurn("Initial restricted turn");
|
||||
expect(await waitForTurn(1)).toEqual({
|
||||
prompt: "Queued in existing mode",
|
||||
modeId: "always-ask",
|
||||
});
|
||||
|
||||
releaseTurn("Queued in existing mode");
|
||||
expect(await waitForTurn(2)).toEqual({
|
||||
prompt: "Apply edits in bypass mode",
|
||||
modeId: "bypassPermissions",
|
||||
});
|
||||
await client.waitForAgentUpsert(agent.id, (snapshot) => snapshot.status === "idle");
|
||||
} finally {
|
||||
await close();
|
||||
}
|
||||
});
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user