Compare commits

..
Author SHA1 Message Date
Mohamed Boudra 8860f2eb14 fix(server): finish canceled creation and restore cleanup
Remove canceled durable agent records before evaluating receipt retry safety, and roll back a recreated checkout when restore expires. Verify cancellation at the registration boundary and drive journal deadlines with an injected clock.
2026-09-09 19:45:38 +02:00
Mohamed Boudra fb349d6bb7 fix(server): cancel and account for expired agent startup
Keep cancellation, serialized operations, and durable receipts in AgentRequests so Hub can release expired startup waiters without allowing a late launch or cleanup replay to overtake the next continuation.
2026-09-09 19:25:35 +02:00
73 changed files with 1524 additions and 2450 deletions
+61 -68
View File
@@ -1,98 +1,91 @@
# Changelog
## 0.8.0 - 2026-09-10
## 0.8.0-beta.1 - 2026-09-08
Paseo 0.8 adds plugin header buttons, custom providers, and richer chat components, alongside fixes for desktop updates and mobile keyboards.
This release considerably extends what plugins can do: complete providers, custom components in the chat, slash commands, settings screens, and agent lifecycle hooks.
**Before upgrading:** desktop now requires macOS 13 or newer. Plugins written for 0.7 need the [0.8 migration guide](https://paseo.sh/docs/plugins/v0.8/migration), including separate client/server entries and the revised composer pill API.
The plugin API has a breaking change. Plugins now use separate client and server entries and runtime-owned SDK entry points, so plugins written for 0.7 must follow the [migration guide](https://paseo.sh/docs/plugins/v0.8/migration) before they load on 0.8.
### Added
- Added answer forms for Codex questions asked while the agent continues working ([#4587](https://github.com/getpaseo/paseo/pull/4587))
- Added Mark as unread to finished workspaces in the sidebar menu ([#3603](https://github.com/getpaseo/paseo/pull/3603) by [@edihasaj](https://github.com/edihasaj))
- Added an in-app What's new sheet in the help menu, Settings → About, and desktop update callout ([#4576](https://github.com/getpaseo/paseo/pull/4576))
- Added Import session to the sidebar footer, History, and Command Center ([#4216](https://github.com/getpaseo/paseo/pull/4216))
- Added search, pagination, and workspace filtering to Import session ([#4216](https://github.com/getpaseo/paseo/pull/4216))
- Added sidebar item reordering and visibility controls in Appearance settings ([#4203](https://github.com/getpaseo/paseo/pull/4203))
- Added provider notifications from Pi extensions and OpenCode to the timeline ([#3411](https://github.com/getpaseo/paseo/pull/3411) by [@trim21](https://github.com/trim21))
- Added a fullscreen Mermaid viewer on web and desktop ([#4107](https://github.com/getpaseo/paseo/pull/4107) by [@gengjiawen](https://github.com/gengjiawen))
- Added Copy, Copy line, and Select all to the web diff context menu ([#4229](https://github.com/getpaseo/paseo/pull/4229))
- Added Gajae Code to the ACP provider catalog ([#3471](https://github.com/getpaseo/paseo/pull/3471) by [@Yeachan-Heo](https://github.com/Yeachan-Heo))
- Added per-provider controls for disabling all or selected Paseo tools ([#4277](https://github.com/getpaseo/paseo/pull/4277) by [@mcowger](https://github.com/mcowger))
- Added explicit approval before running setup, automatic terminals, or scripts in fork pull request workspaces ([#4215](https://github.com/getpaseo/paseo/pull/4215))
- Added Hub follow-ups to existing agents, including archived workspace recovery ([#4354](https://github.com/getpaseo/paseo/pull/4354))
- Added provider catalog discovery to Hub executions ([#4242](https://github.com/getpaseo/paseo/pull/4242))
It also fixes regressions across desktop updates, mobile, Import session, and agent lifecycle.
### Plugins
- Added custom providers with their own icons, settings, permissions, and timeline rendering ([#4314](https://github.com/getpaseo/paseo/pull/4314))
- Added provider session recovery after plugin reload ([#4629](https://github.com/getpaseo/paseo/pull/4629) by [@mcowger](https://github.com/mcowger))
- Added custom timeline components and persisted timeline rows ([e34aea2](https://github.com/getpaseo/paseo/commit/e34aea206e6ec7ac2d5fa9766db28fb221ae990c))
- Added client slash commands that run without a provider turn ([e34aea2](https://github.com/getpaseo/paseo/commit/e34aea206e6ec7ac2d5fa9766db28fb221ae990c))
- Added plugin settings screens under Settings → Plugins ([#4357](https://github.com/getpaseo/paseo/pull/4357))
- Added lifecycle hooks for agent creation, turns, permissions, and archive events ([#4435](https://github.com/getpaseo/paseo/pull/4435))
- Added transforms for new agents' provider, model, environment, MCP servers, and workspace isolation ([#4435](https://github.com/getpaseo/paseo/pull/4435))
- Added header buttons and composer pills with actions, menus, custom popovers, and live updates ([#4577](https://github.com/getpaseo/paseo/pull/4577))
- Added custom modal bodies with scrolling, keyboard-aware inputs, and clipboard actions ([#4392](https://github.com/getpaseo/paseo/pull/4392))
- Added terminal creation, input, capture, and management to the SDK ([#4358](https://github.com/getpaseo/paseo/pull/4358))
- Added live project subscriptions through `paseo.projects.subscribe()` ([#3983](https://github.com/getpaseo/paseo/pull/3983) by [@omercnet](https://github.com/omercnet))
- Added permission responses through `agent.respondToPermission()` ([#3985](https://github.com/getpaseo/paseo/pull/3985) by [@omercnet](https://github.com/omercnet))
- Added provider usage queries through `providers.listUsage()` ([#4062](https://github.com/getpaseo/paseo/pull/4062) by [@ivanbrykov](https://github.com/ivanbrykov))
- Added supported Paseo version requirements to plugin manifests ([#4430](https://github.com/getpaseo/paseo/pull/4430))
- Changed plugins to separate client and server entries with runtime-specific SDK imports ([#4347](https://github.com/getpaseo/paseo/pull/4347) by [@liujin0506](https://github.com/liujin0506), [@panrafal](https://github.com/panrafal))
- Changed composer pill registration to use `button`, `registration.update()`, and `registration.remove()` ([#4577](https://github.com/getpaseo/paseo/pull/4577))
- Changed `paseo plugin ls` to show runtime state, installed commit, and load errors without contacting a remote ([#4265](https://github.com/getpaseo/paseo/pull/4265))
- Fixed workspace plugin panels missing from the Explorer menu ([#4446](https://github.com/getpaseo/paseo/pull/4446))
- Added provider contributions: a plugin registers a complete provider, directly or through the bundled ACP shim, with its own icon, session settings, permissions, and timeline rendering ([#4314](https://github.com/getpaseo/paseo/pull/4314))
- Added live timeline items: a plugin renders custom components in the chat by transforming timeline items at render time ([e34aea2](https://github.com/getpaseo/paseo/commit/e34aea206e6ec7ac2d5fa9766db28fb221ae990c))
- Added durable timeline rows: a daemon handler appends its own persisted rows to an agent's timeline ([e34aea2](https://github.com/getpaseo/paseo/commit/e34aea206e6ec7ac2d5fa9766db28fb221ae990c))
- Added slash commands: a plugin registers commands in the composer that run on the client without a provider turn ([e34aea2](https://github.com/getpaseo/paseo/commit/e34aea206e6ec7ac2d5fa9766db28fb221ae990c))
- Added settings screens: a plugin contributes screens under Settings → Plugins from shared settings components, with host-scoped persistence, validation, and Command Center navigation ([#4357](https://github.com/getpaseo/paseo/pull/4357))
- Added lifecycle hooks: server callbacks observe agent creation, turns, permissions, and archive events, and can answer permissions or send follow-ups ([#4435](https://github.com/getpaseo/paseo/pull/4435))
- Added agent creation transforms: before hooks rewrite a new agent's provider, model, launch environment, MCP servers, and workspace isolation ([#4435](https://github.com/getpaseo/paseo/pull/4435))
- Added modal bodies: a plugin owns the whole sheet body with custom padding, ScrollView or FlatList scrolling, horizontal tabs, keyboard-aware inputs, and a clipboard copy action ([#4392](https://github.com/getpaseo/paseo/pull/4392), [#4431](https://github.com/getpaseo/paseo/pull/4431))
- Added terminals to the SDK: create, list, write, send keys, capture, and kill terminals by workspace ID ([#4358](https://github.com/getpaseo/paseo/pull/4358))
- Added `paseo.projects.subscribe()` for live project updates ([#3983](https://github.com/getpaseo/paseo/pull/3983) by [@omercnet](https://github.com/omercnet))
- Added `agent.respondToPermission()` to answer pending permissions from a plugin ([#3985](https://github.com/getpaseo/paseo/pull/3985) by [@omercnet](https://github.com/omercnet))
- Added version requirements: `requirements.paseo` in `paseo-plugin.json` declares the supported Paseo versions, incompatible installs, updates, and reloads are rejected before any code runs, and prerelease Paseo versions satisfy any range their stable core satisfies ([#4430](https://github.com/getpaseo/paseo/pull/4430), [#4452](https://github.com/getpaseo/paseo/pull/4452))
- Changed plugins to separate `index.client.ts` and `index.server.ts` entries with `client/`, `server/`, and `shared/` directories; plugins written for 0.7 must follow the [migration guide](https://paseo.sh/docs/plugins/v0.8/migration) ([#4206](https://github.com/getpaseo/paseo/pull/4206))
- Changed the plugin SDK into runtime-owned entry points: `@getpaseo/plugin` for shared code, `@getpaseo/plugin/client` for the app, and `@getpaseo/plugin/server` for the daemon, with crossed imports rejected at compile time ([#4347](https://github.com/getpaseo/paseo/pull/4347) by [@liujin0506](https://github.com/liujin0506), [@panrafal](https://github.com/panrafal))
- Changed legacy plugin load failures to say the plugin was built for an older Paseo and link to the migration guide ([#4265](https://github.com/getpaseo/paseo/pull/4265))
- Changed `paseo plugin ls` to report runtime state, source, installed commit, and load errors without contacting a remote ([#4265](https://github.com/getpaseo/paseo/pull/4265))
- Fixed workspace plugin panels missing from the Explorer tab-rail menu ([#4446](https://github.com/getpaseo/paseo/pull/4446))
- Added versioned plugin documentation for v0.7 and v0.8 with a migration guide ([#4245](https://github.com/getpaseo/paseo/pull/4245), [#4452](https://github.com/getpaseo/paseo/pull/4452))
### Added
- Added Import session to the sidebar footer, the History and sidebar empty states, and the Command Center ([#4216](https://github.com/getpaseo/paseo/pull/4216))
- Added search, Load more, and a This workspace / Show all scope to the Import session sheet ([#4216](https://github.com/getpaseo/paseo/pull/4216))
- Added customizable top-level sidebar items: reorder and hide New workspace, History, Search, Schedules, and plugin items from Appearance settings ([#4203](https://github.com/getpaseo/paseo/pull/4203))
- Added provider notifications from Pi extensions and OpenCode as timeline items with info, warning, and error levels ([#3411](https://github.com/getpaseo/paseo/pull/3411) by [@trim21](https://github.com/trim21))
- Added a fullscreen viewer for Mermaid diagrams on web and desktop ([#4107](https://github.com/getpaseo/paseo/pull/4107) by [@gengjiawen](https://github.com/gengjiawen))
- Added Copy, Copy line, and Select all to the web diff context menu, with Cmd/Ctrl+A and Escape ([#4229](https://github.com/getpaseo/paseo/pull/4229))
- Added Gajae Code to the ACP provider catalog ([#3471](https://github.com/getpaseo/paseo/pull/3471) by [@Yeachan-Heo](https://github.com/Yeachan-Heo))
- Added per-provider Paseo tool policy in daemon config to disable all or selected Paseo tools for a provider ([#4277](https://github.com/getpaseo/paseo/pull/4277) by [@mcowger](https://github.com/mcowger))
- Added explicit setup approval for fork pull request workspaces: setup, automatic terminals, and scripts wait for Run setup or `paseo workspace setup <id>` ([#4215](https://github.com/getpaseo/paseo/pull/4215))
- Added Hub follow-ups to existing agents, archived workspace recovery, and provider catalog discovery through the daemon API ([#4354](https://github.com/getpaseo/paseo/pull/4354), [#4242](https://github.com/getpaseo/paseo/pull/4242))
### Changed
- Changed the desktop app to require macOS 13 or newer; macOS 12 stops receiving desktop updates ([#4322](https://github.com/getpaseo/paseo/pull/4322))
- Changed `--host` to a global CLI option: `paseo --host <target> <command>` ([#4238](https://github.com/getpaseo/paseo/pull/4238))
- Changed the sidebar footer Home button to Import session ([#4216](https://github.com/getpaseo/paseo/pull/4216))
- Changed `paseo hub init` and default `paseo hub deploy` to use organization triggers in `.paseo/triggers/` ([#4517](https://github.com/getpaseo/paseo/pull/4517))
- Changed Codex Fast availability to the supported model list, including GPT-6 Astra ([#4640](https://github.com/getpaseo/paseo/pull/4640))
- Changed CLI installs to resolve patched React 19.1.x releases ([#4100](https://github.com/getpaseo/paseo/pull/4100) by [@liujin0506](https://github.com/liujin0506))
- Changed the sidebar footer Home button to Import session; the Home route and tile remain ([#4216](https://github.com/getpaseo/paseo/pull/4216))
### Improved
- Reconnected every host immediately when returning to the app ([#4160](https://github.com/getpaseo/paseo/pull/4160))
- Smoothed mobile keyboard transitions by moving the timeline and composer together ([#4275](https://github.com/getpaseo/paseo/pull/4275))
- Reduced stalls when opening large diffs ([#4574](https://github.com/getpaseo/paseo/pull/4574))
- Reloaded only providers whose configuration changed ([#4332](https://github.com/getpaseo/paseo/pull/4332))
- Removed unsolicited timeline and catalog traffic from idle SDK connections ([#4470](https://github.com/getpaseo/paseo/pull/4470))
- Added macOS updater diagnostics to App Diagnostics ([#4322](https://github.com/getpaseo/paseo/pull/4322))
- Reconnected every host immediately on app foreground instead of waiting for reconnect backoff ([#4160](https://github.com/getpaseo/paseo/pull/4160))
- Smoothed mobile keyboard transitions by moving the timeline and composer together instead of relaying out every frame ([#4275](https://github.com/getpaseo/paseo/pull/4275))
- Reloaded only the providers whose configuration changed instead of restarting every provider and resetting every catalog ([#4332](https://github.com/getpaseo/paseo/pull/4332))
- Shortened agent tab tooltips to one title line with the agent ID and last activity ([#4214](https://github.com/getpaseo/paseo/pull/4214))
- Added macOS updater and ShipIt state to App Diagnostics ([#4322](https://github.com/getpaseo/paseo/pull/4322))
### Fixed
- Fixed the mobile terminal keyboard closing and reopening when using toolbar keys or Enter ([#4469](https://github.com/getpaseo/paseo/pull/4469))
- Fixed macOS desktop updates closing the app without installing the new version ([#4322](https://github.com/getpaseo/paseo/pull/4322))
- Fixed the desktop updater reporting up to date before release manifests were available ([#4201](https://github.com/getpaseo/paseo/pull/4201))
- Fixed the desktop updater reporting up to date while a new release had no updater manifests yet ([#4201](https://github.com/getpaseo/paseo/pull/4201))
- Fixed `paseo restart` failing from the desktop-installed CLI on Linux `.deb`, RPM, and tarball installs ([#4207](https://github.com/getpaseo/paseo/pull/4207))
- Fixed the packaged macOS Dock icon rendering oversized ([#4389](https://github.com/getpaseo/paseo/pull/4389))
- Fixed the mobile terminal keyboard closing and reopening when using toolbar keys or Enter ([#4469](https://github.com/getpaseo/paseo/pull/4469))
- Fixed cached conversations and workspace lists failing to appear when live updates arrived during loading ([#4436](https://github.com/getpaseo/paseo/pull/4436))
- Fixed cached conversations and the workspace list not painting when live updates arrived during cache reads ([#4436](https://github.com/getpaseo/paseo/pull/4436))
- Fixed queued messages not sending after a turn completed while the app was in the background ([#4160](https://github.com/getpaseo/paseo/pull/4160))
- Fixed Codex reloads and follow-ups after workspace archive failing with an active-writer error ([#4353](https://github.com/getpaseo/paseo/pull/4353))
- Fixed repeated Claude compaction updates leaving extra Compacting rows spinning ([#4391](https://github.com/getpaseo/paseo/pull/4391) by [@tomgrin10](https://github.com/tomgrin10))
- Fixed the New workspace form losing the selected model after creating a workspace ([#4401](https://github.com/getpaseo/paseo/pull/4401))
- Fixed a crash with `Select a model` when the selected provider disappeared during workspace creation ([#4332](https://github.com/getpaseo/paseo/pull/4332))
- Fixed Codex model rows staying on Loading forever in the New workspace model picker ([#4283](https://github.com/getpaseo/paseo/pull/4283) by [@colonelpanic8](https://github.com/colonelpanic8))
- Fixed reloading a Codex agent failing with `already has an active writer` ([#4353](https://github.com/getpaseo/paseo/pull/4353))
- Fixed Pi agents stuck running after an extension-triggered turn ([#3849](https://github.com/getpaseo/paseo/pull/3849) by [@mjakl](https://github.com/mjakl))
- Fixed delayed workspace creation navigating away after you switched elsewhere ([#2986](https://github.com/getpaseo/paseo/pull/2986) by [@cleiter](https://github.com/cleiter))
- Fixed New workspace losing the selected model after creating a workspace ([#4401](https://github.com/getpaseo/paseo/pull/4401))
- Fixed a crash when the selected provider disappeared during workspace creation ([#4332](https://github.com/getpaseo/paseo/pull/4332))
- Fixed Codex model rows staying on Loading in the model picker ([#4283](https://github.com/getpaseo/paseo/pull/4283) by [@colonelpanic8](https://github.com/colonelpanic8))
- Fixed nested subagents appearing under the root agent instead of their actual parent ([#4321](https://github.com/getpaseo/paseo/pull/4321))
- Fixed repeated tool-call IDs across autonomous turns producing duplicate timeline rows ([140b0bb](https://github.com/getpaseo/paseo/commit/140b0bb716205cf0e00c0ff5b6b3c20af6c79413))
- Fixed Import session loading forever when one provider hung ([#4216](https://github.com/getpaseo/paseo/pull/4216))
- Fixed nested provider subagents shown as direct children of the root agent and their notifications appearing in the root timeline ([#4321](https://github.com/getpaseo/paseo/pull/4321))
- Fixed repeated provider tool-call IDs across autonomous turns producing duplicate timeline rows ([140b0bb](https://github.com/getpaseo/paseo/commit/140b0bb716205cf0e00c0ff5b6b3c20af6c79413))
- Fixed the Import session spinner never stopping when one provider hung; the provider now shows an inline error with Retry ([#4216](https://github.com/getpaseo/paseo/pull/4216))
- Fixed Import session ignoring Claude Code `/rename` titles ([#4216](https://github.com/getpaseo/paseo/pull/4216))
- Fixed importing a session creating a duplicate workspace for an already-open directory ([#4216](https://github.com/getpaseo/paseo/pull/4216))
- Fixed importing a session into a directory with an active workspace creating a duplicate workspace ([#4216](https://github.com/getpaseo/paseo/pull/4216))
- Fixed empty ACP sessions appearing in Import session ([#4335](https://github.com/getpaseo/paseo/pull/4335))
- Fixed restored terminal titles briefly showing Terminal before loading ([#4553](https://github.com/getpaseo/paseo/pull/4553))
- Fixed diff file headers lagging behind while scrolling on web and desktop ([#4240](https://github.com/getpaseo/paseo/pull/4240))
- Fixed Changes and its diff going out of sync when switching between Committed and Uncommitted ([#4199](https://github.com/getpaseo/paseo/pull/4199))
- Fixed Mermaid diagrams shrinking during streaming or becoming corrupted on reload ([#4210](https://github.com/getpaseo/paseo/pull/4210))
- Fixed diff file headers lagging behind the document while scrolling on web and desktop ([#4240](https://github.com/getpaseo/paseo/pull/4240))
- Fixed the Changes tree and its working diff going out of sync when switching between Committed and Uncommitted ([#4199](https://github.com/getpaseo/paseo/pull/4199))
- Fixed Mermaid diagrams shrinking on every streaming re-render and the inline diagram box collapsing ([#4107](https://github.com/getpaseo/paseo/pull/4107) by [@gengjiawen](https://github.com/gengjiawen))
- Fixed Mermaid source corrupted on reload when cached history overlapped the live message ([#4210](https://github.com/getpaseo/paseo/pull/4210))
- Fixed Settings navigation retaining closed views in memory on desktop ([#4228](https://github.com/getpaseo/paseo/pull/4228))
- Fixed the file watcher missing nested directory changes on Windows ([#4354](https://github.com/getpaseo/paseo/pull/4354))
- Fixed daemon Git commands allowing a repository's `core.fsmonitor` to execute its own command ([#4208](https://github.com/getpaseo/paseo/pull/4208))
- Fixed terminal activity reporting for OpenCode 2 sessions ([#4300](https://github.com/getpaseo/paseo/pull/4300) by [@mr-karan](https://github.com/mr-karan))
- Fixed the website offering downloads for the wrong platform before loading ([#4222](https://github.com/getpaseo/paseo/pull/4222))
- Fixed the file watcher missing nested directory changes on Windows ([#4354](https://github.com/getpaseo/paseo/pull/4354), [#4358](https://github.com/getpaseo/paseo/pull/4358))
- Fixed daemon Git commands honoring a repository's `core.fsmonitor`, which let a checkout run its own command ([#4208](https://github.com/getpaseo/paseo/pull/4208))
- Fixed terminal activity reporting for OpenCode 2 sessions started from a terminal ([#4300](https://github.com/getpaseo/paseo/pull/4300) by [@mr-karan](https://github.com/mr-karan))
- Changed the plugin SDK's React peer range to `~19.1.0` so CLI installs resolve a patched 19.1.x instead of the version dependency scanners flag ([#4100](https://github.com/getpaseo/paseo/pull/4100) by [@liujin0506](https://github.com/liujin0506))
- Fixed the paseo.sh homepage offering the Mac download to every visitor before hydration and desktop builds to phones ([#4222](https://github.com/getpaseo/paseo/pull/4222))
## 0.7.2 - 2026-09-02
+2 -7
View File
@@ -106,15 +106,10 @@ Repo dev commands use checkout-local state by default. In this checkout, `PASEO_
See [docs/development.md](docs/development.md) for full setup, build sync requirements, and debugging.
## Release branches
When the user says "this goes to next", create or
retarget the PR to `next` and preserve that destination through delivery. Follow
[release branch discipline](docs/release.md#release-branch-discipline) for creating
and updating `next`, integrating it after a release, and releasing a hotfix from a tag.
## Critical rules
- **Before changing the plugin SDK, compiler, host module maps, scaffold, or examples, read [SDK import boundaries](docs/plugins.md#sdk-import-boundaries).** Classify the export by runtime first and preserve the enforced boundaries.
- **NEVER restart the main Paseo daemon on port 6767 without permission** — it manages all running agents. If you're an agent, restarting it kills your own process.
- **NEVER assume a timeout means the service needs restarting** — timeouts can be transient.
- **NEVER add auth checks to tests** — agent providers handle their own auth.
+1 -31
View File
@@ -47,36 +47,6 @@ commit the prepared inputs locally and run the release command. Its branch and
tag push is the one remote release batch and starts CI for the complete release
commit.
## Release branch discipline
While you finalize a release on `main`, use a temporary `next` branch for work intended for the following
release. This applies to both beta and stable releases.
- Create each new `next` from freshly fetched `origin/main`. Reuse it while active.
- "This goes to next" means create the PR against `next` or retarget an existing
PR, and keep that destination through delivery.
- Keep `next` current by merging `origin/main` into it as release fixes land.
Avoid rebasing this shared branch because agents and open PRs depend on its history.
- After the release ships, bring `next` up to date and open a `next` → `main` PR.
Pass CI and merge without squashing away the individual PR commits needed for
the changelog. Retarget remaining PRs based on `next` to `main` and delete the integrated
`next`. Create it fresh when needed again.
**Setup still needed:** CI, Docker, and Nix PR checks currently target only `main`,
and GitHub permits only squash merges. Enable checks and required-check protection
for `next`, CI on its pushes, and merge commits for the integration PR. Handle PR
base changes (`edited` events) so retargeting runs checks against the new base;
GitHub's default PR events do not cover this. Deployment triggers stay unchanged.
### Hotfix from a release tag
If `main` contains changes you do not want to release, branch from the affected
release tag and cherry-pick only the required fixes. Run CI on that branch, then
use the normal release flow with it as the explicit source, choosing a new patch
or beta version. Ensure the fixes and changelog also reach `main` and any active
`next`, preserving newer development and version changes there. This is a
short-lived hotfix branch, not another maintained release track.
## ACP catalog updates
ACP catalog work enters a release through an explicit user request:
@@ -94,7 +64,7 @@ release push as the changelog and version commit.
There are two supported release paths:
1. **Direct stable release**: you are ready to ship the resolved release source to everyone immediately (default `origin/main`).
1. **Direct stable release**: you are ready to ship the current `main` commit to everyone immediately.
2. **Beta flow**: release candidates on the `beta` channel. Each beta carries its own changelog entry, publishes npm only on the explicit `beta` dist-tag, and stays behind the Stable/Beta switch on `/download`.
Paseo has one linear release track even though npm dist-tags are independent
@@ -1,8 +0,0 @@
Paseo 0.8 adds plugin header buttons, custom providers, and richer chat components, alongside fixes for desktop updates and mobile keyboards.
Before upgrading: desktop now requires macOS 13 or newer. Plugins written for 0.7 need the 0.8 migration guide, including separate client/server entries and the revised composer pill API.
Added
- Added answer forms for Codex questions asked while the agent continues working
Full notes: https://paseo.sh/changelog
@@ -1,8 +0,0 @@
Paseo 0.8 adds plugin header buttons, custom providers, and richer chat components, alongside fixes for desktop updates and mobile keyboards.
Before upgrading: desktop now requires macOS 13 or newer. Plugins written for 0.7 need the 0.8 migration guide, including separate client/server entries and the revised composer pill API.
Added
- Added answer forms for Codex questions asked while the agent continues working
Full notes: https://paseo.sh/changelog
@@ -1,8 +0,0 @@
Paseo 0.8 adds plugin header buttons, custom providers, and richer chat components, alongside fixes for desktop updates and mobile keyboards.
Before upgrading: desktop now requires macOS 13 or newer. Plugins written for 0.7 need the 0.8 migration guide, including separate client/server entries and the revised composer pill API.
Added
- Added answer forms for Codex questions asked while the agent continues working
Full notes: https://paseo.sh/changelog
@@ -1,8 +0,0 @@
Paseo 0.8 adds plugin header buttons, custom providers, and richer chat components, alongside fixes for desktop updates and mobile keyboards.
Before upgrading: desktop now requires macOS 13 or newer. Plugins written for 0.7 need the 0.8 migration guide, including separate client/server entries and the revised composer pill API.
Added
- Added answer forms for Codex questions asked while the agent continues working
Full notes: https://paseo.sh/changelog
+1 -1
View File
@@ -1 +1 @@
sha256-j8U5S71SJoC+5yh7IjkadrRZaHOYeMsi1z8B6K7j4R4=
sha256-8P7kk9B2A81e13IIyyfo8fIoNGlrutfV/WGKAFHscUc=
+27 -28
View File
@@ -1,12 +1,12 @@
{
"name": "paseo",
"version": "0.8.0",
"version": "0.8.0-beta.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "paseo",
"version": "0.8.0",
"version": "0.8.0-beta.1",
"hasInstallScript": true,
"license": "Apache-2.0",
"workspaces": [
@@ -36196,7 +36196,7 @@
},
"packages/app": {
"name": "@getpaseo/app",
"version": "0.8.0",
"version": "0.8.0-beta.1",
"dependencies": {
"@codemirror/commands": "6.10.4",
"@codemirror/language": "6.12.4",
@@ -37261,12 +37261,12 @@
},
"packages/cli": {
"name": "@getpaseo/cli",
"version": "0.8.0",
"version": "0.8.0-beta.1",
"dependencies": {
"@clack/prompts": "^1.0.0",
"@getpaseo/client": "0.8.0",
"@getpaseo/protocol": "0.8.0",
"@getpaseo/server": "0.8.0",
"@getpaseo/client": "0.8.0-beta.1",
"@getpaseo/protocol": "0.8.0-beta.1",
"@getpaseo/server": "0.8.0-beta.1",
"chalk": "^5.3.0",
"commander": "^12.0.0",
"mime-types": "^2.1.35",
@@ -37513,10 +37513,10 @@
},
"packages/client": {
"name": "@getpaseo/client",
"version": "0.8.0",
"version": "0.8.0-beta.1",
"dependencies": {
"@getpaseo/protocol": "0.8.0",
"@getpaseo/relay": "0.8.0",
"@getpaseo/protocol": "0.8.0-beta.1",
"@getpaseo/relay": "0.8.0-beta.1",
"zod": "^4.4.3"
},
"devDependencies": {
@@ -37527,7 +37527,7 @@
},
"packages/desktop": {
"name": "@getpaseo/desktop",
"version": "0.8.0",
"version": "0.8.0-beta.1",
"license": "Apache-2.0",
"dependencies": {
"@getpaseo/cli": "*",
@@ -37538,7 +37538,6 @@
"zod": "^4.4.3"
},
"devDependencies": {
"@electron/asar": "3.4.1",
"@types/node": "24.6.0",
"@types/ws": "^8.5.14",
"electron": "44.2.0",
@@ -37771,7 +37770,7 @@
},
"packages/expo-two-way-audio": {
"name": "@getpaseo/expo-two-way-audio",
"version": "0.8.0",
"version": "0.8.0-beta.1",
"license": "MIT",
"devDependencies": {
"@types/jest": "^29.5.14",
@@ -38667,7 +38666,7 @@
},
"packages/highlight": {
"name": "@getpaseo/highlight",
"version": "0.8.0",
"version": "0.8.0-beta.1",
"dependencies": {
"@codemirror/language": "6.12.4",
"@codemirror/legacy-modes": "^6.5.3",
@@ -38696,14 +38695,14 @@
},
"packages/plugin": {
"name": "@getpaseo/plugin",
"version": "0.8.0",
"version": "0.8.0-beta.1",
"dependencies": {
"@agentclientprotocol/sdk": "^1.4.0",
"use-sync-external-store": "^1.6.0"
},
"devDependencies": {
"@getpaseo/client": "0.8.0",
"@getpaseo/protocol": "0.8.0",
"@getpaseo/client": "0.8.0-beta.1",
"@getpaseo/protocol": "0.8.0-beta.1",
"@types/node": "^20.9.0",
"@types/react": "~19.2.0",
"react": "19.1.0",
@@ -38713,8 +38712,8 @@
"zod": "^4.4.3"
},
"peerDependencies": {
"@getpaseo/client": "0.8.0",
"@getpaseo/protocol": "0.8.0",
"@getpaseo/client": "0.8.0-beta.1",
"@getpaseo/protocol": "0.8.0-beta.1",
"react": "~19.1.0",
"react-native": ">=0.81.5",
"zod": "^4.4.3"
@@ -38736,7 +38735,7 @@
},
"packages/protocol": {
"name": "@getpaseo/protocol",
"version": "0.8.0",
"version": "0.8.0-beta.1",
"dependencies": {
"semver": "^7.8.5",
"zod": "^4.4.3"
@@ -38763,7 +38762,7 @@
},
"packages/relay": {
"name": "@getpaseo/relay",
"version": "0.8.0",
"version": "0.8.0-beta.1",
"dependencies": {
"base64-js": "^1.5.1",
"tweetnacl": "^1.0.3",
@@ -38981,16 +38980,16 @@
},
"packages/server": {
"name": "@getpaseo/server",
"version": "0.8.0",
"version": "0.8.0-beta.1",
"dependencies": {
"@agentclientprotocol/sdk": "^0.17.1",
"@anthropic-ai/claude-agent-sdk": "0.3.246",
"@anthropic-ai/sdk": "^0.104.2",
"@getpaseo/client": "0.8.0",
"@getpaseo/highlight": "0.8.0",
"@getpaseo/plugin": "0.8.0",
"@getpaseo/protocol": "0.8.0",
"@getpaseo/relay": "0.8.0",
"@getpaseo/client": "0.8.0-beta.1",
"@getpaseo/highlight": "0.8.0-beta.1",
"@getpaseo/plugin": "0.8.0-beta.1",
"@getpaseo/protocol": "0.8.0-beta.1",
"@getpaseo/relay": "0.8.0-beta.1",
"@isaacs/ttlcache": "^2.1.4",
"@modelcontextprotocol/sdk": "1.29.0",
"@opencode-ai/sdk": "1.14.46",
@@ -39868,7 +39867,7 @@
},
"packages/website": {
"name": "@getpaseo/website",
"version": "0.8.0",
"version": "0.8.0-beta.1",
"dependencies": {
"@cloudflare/vite-plugin": "^1.29.1",
"@cloudflare/workers-types": "^4.20260317.1",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "paseo",
"version": "0.8.0",
"version": "0.8.0-beta.1",
"private": true,
"description": "Paseo: voice-controlled development environment for local AI coding agents",
"keywords": [
@@ -1,22 +0,0 @@
import { test } from "../support/fixtures";
import { verifyDelayedWorkspaceCreation } from "../support/helpers/new-workspace-navigation";
test.describe("Delayed workspace creation", () => {
test.describe.configure({ timeout: 120_000 });
for (const launch of ["chat", "terminal", "empty"] as const) {
test(`${launch}: keeps the workspace chosen during creation`, async ({ page }) => {
await verifyDelayedWorkspaceCreation(page, launch, "leave");
});
test(`worktree ${launch}: keeps the workspace chosen during creation`, async ({ page }) => {
await verifyDelayedWorkspaceCreation(page, launch, "leave", "worktree");
});
test(`${launch}: opens the created workspace when the user stays`, async ({ page }) => {
await verifyDelayedWorkspaceCreation(page, launch, "stay");
});
}
test("preserves a newer draft opened while creation is pending", async ({ page }) => {
await verifyDelayedWorkspaceCreation(page, "chat", "new-draft");
});
});
@@ -1,197 +0,0 @@
import { expect, test, type Page } from "../fixtures";
import { readFile } from "node:fs/promises";
import { buildHostWorkspaceRoute } from "@/utils/host-routes";
import { gotoAppShell } from "./app";
import { scrollTimelineToOldestLoadedEdge } from "./timeline-pagination";
import {
archiveLocalWorkspaceFromDaemon,
archiveWorkspaceFromDaemon,
connectNewWorkspaceDaemonClient,
countWorkspaceAgents,
countWorkspaceTerminals,
delayBrowserWorkspaceCreatedResponse,
expectNewWorkspaceDraft,
fillNewWorkspaceDraft,
openNewWorkspaceComposer,
openProjectViaDaemon,
selectWorkspaceIsolation,
submitNewWorkspaceEmpty,
submitNewWorkspacePrompt,
waitForCreatedWorkspace,
} from "./new-workspace";
import { createTempGitRepo } from "./workspace";
import { expectAppRoute } from "./route-assertions";
import { getServerId } from "./server-id";
import {
expectTerminalOutputContains,
expectWorkspaceOpensWithTerminalTab,
fillTerminalPrompt,
seedTerminalProfiles,
selectLaunchOption,
submitTerminalLaunch,
type TerminalProfile,
} from "./new-workspace-launch";
import { switchWorkspaceViaSidebar, waitForSidebarHydration } from "./workspace-ui";
import { dropFileOnComposer, expectAttachmentPill } from "./composer";
const PROMPT = "Hello from the navigation guard";
const NEXT_PROMPT = "Keep this newer draft";
const CONTEXT = {
name: "context.json",
mimeType: "application/json",
buffer: Buffer.from('{"preserve":"attachment"}'),
};
const PROFILE: TerminalProfile = {
id: "e2e-nav-guard-echo",
name: "Nav Guard Echo",
command: "/bin/sh",
args: ["-c", 'echo captured: "$0"; sleep 120', "{{{prompt}}}"],
};
export async function verifyDelayedWorkspaceCreation(
page: Page,
launch: "chat" | "terminal" | "empty",
destination: "leave" | "stay" | "new-draft",
isolation: "local" | "worktree" = "local",
): Promise<void> {
const client = await connectNewWorkspaceDaemonClient();
const repo = await createTempGitRepo("workspace-focus-");
const profileSeed = await seedTerminalProfiles([PROFILE]);
const delay = await delayBrowserWorkspaceCreatedResponse(page);
const serverId = getServerId();
let localWorkspaceId: string | undefined;
let createdDirectory: string | undefined;
let newDraftRoute = "";
try {
const project = await openProjectViaDaemon(client, repo.path);
localWorkspaceId = project.workspaceId;
const knownIds = new Set((await client.fetchWorkspaces()).entries.map((entry) => entry.id));
await gotoAppShell(page);
await waitForSidebarHydration(page);
await switchWorkspaceViaSidebar({ page, serverId, workspaceId: project.workspaceId });
await test.step("Submit workspace creation with the requested content", async () => {
await openNewWorkspaceComposer(page, project);
await selectWorkspaceIsolation(page, isolation);
if (launch === "chat") {
await dropFileOnComposer(page, CONTEXT);
await expectAttachmentPill(page, "composer-file-attachment-pill");
await submitNewWorkspacePrompt(page, PROMPT);
} else if (launch === "terminal") {
await selectLaunchOption(page, PROFILE.id);
await fillTerminalPrompt(page, PROMPT);
await submitTerminalLaunch(page);
} else {
await submitNewWorkspaceEmpty(page);
}
await delay.waitForCreateRequest();
});
await test.step("Choose where to work while the creation response is held", async () => {
if (destination !== "stay") {
await switchWorkspaceViaSidebar({ page, serverId, workspaceId: project.workspaceId });
}
if (destination === "new-draft") {
await openNewWorkspaceComposer(page, project);
await fillNewWorkspaceDraft(page, NEXT_PROMPT);
const url = new URL(page.url());
newDraftRoute = url.pathname + url.search;
}
// Recording pacing only; the response is held deterministically above.
if (process.env.E2E_RECORD_VIDEO === "1") {
await page.mouse.move(1100, 80);
await page.waitForTimeout(1500);
}
delay.release();
});
const created = await waitForCreatedWorkspace(client, knownIds);
createdDirectory = created.workspaceDirectory;
expect(created.workspaceKind).toBe(isolation === "worktree" ? "worktree" : "local_checkout");
await test.step("Completion creates exactly the requested resource and preserves focus", async () => {
await expect
.poll(() => countWorkspaceAgents(client, created.id))
.toBe(launch === "chat" ? 1 : 0);
await expect
.poll(() => countWorkspaceTerminals(client, created.id))
.toBe(launch === "terminal" ? 1 : 0);
// A negative navigation assertion needs an observation window after completion.
await page.waitForTimeout(5000);
const expectedRoute =
destination === "new-draft"
? newDraftRoute
: buildHostWorkspaceRoute(
serverId,
destination === "stay" ? created.id : project.workspaceId,
);
await expectAppRoute(page, expectedRoute);
if (destination === "new-draft") await expectNewWorkspaceDraft(page, NEXT_PROMPT);
if (launch === "chat") {
expect(delay.agentRequests).toHaveLength(1);
const upload = delay.agentRequests[0]?.attachments?.find(
(item) => item.type === "uploaded_file",
);
if (!upload) throw new Error("The create request did not contain the submitted file");
expect(await readFile(upload.path)).toEqual(CONTEXT.buffer);
expect(delay.agentRequests[0]).toMatchObject({
workspaceId: created.id,
initialPrompt: PROMPT,
config: {
provider: "mock",
model: "ten-second-stream",
modeId: "load-test",
thinkingOptionId: "low",
cwd: created.workspaceDirectory,
},
attachments: [
expect.objectContaining({
fileName: CONTEXT.name,
mimeType: CONTEXT.mimeType,
size: CONTEXT.buffer.length,
}),
],
});
}
});
await test.step("Visit the new workspace and return without submitting a second draft", async () => {
await switchWorkspaceViaSidebar({ page, serverId, workspaceId: created.id });
if (launch === "chat") {
await scrollTimelineToOldestLoadedEdge(page);
await expect(page.getByText(PROMPT, { exact: true }).first()).toBeVisible();
} else if (launch === "terminal") {
await expectWorkspaceOpensWithTerminalTab(page);
await expectTerminalOutputContains(page, `captured: ${PROMPT}`);
}
await switchWorkspaceViaSidebar({ page, serverId, workspaceId: project.workspaceId });
await switchWorkspaceViaSidebar({ page, serverId, workspaceId: created.id });
await expect
.poll(() => countWorkspaceAgents(client, created.id))
.toBe(launch === "chat" ? 1 : 0);
await expect
.poll(() => countWorkspaceTerminals(client, created.id))
.toBe(launch === "terminal" ? 1 : 0);
if (launch === "chat") {
expect(delay.agentRequests).toHaveLength(1);
await openNewWorkspaceComposer(page, project);
await expectNewWorkspaceDraft(page, destination === "new-draft" ? NEXT_PROMPT : "");
}
if (process.env.E2E_RECORD_VIDEO === "1") {
await page.mouse.move(1100, 80);
await page.waitForTimeout(1500);
}
});
} catch (error) {
await page.screenshot({ path: test.info().outputPath("before-cleanup.png") });
console.error(error);
throw error;
} finally {
delay.release();
if (createdDirectory) await archiveWorkspaceFromDaemon(client, createdDirectory);
if (localWorkspaceId) await archiveLocalWorkspaceFromDaemon(client, localWorkspaceId);
await profileSeed.restore();
await client.close();
await repo.cleanup();
}
}
@@ -1,5 +1,4 @@
import { expect, type BrowserContext, type Page } from "@playwright/test";
import type { CreateAgentRequestMessage } from "@getpaseo/protocol/messages";
import type { DaemonClient as InternalDaemonClient } from "@getpaseo/client/internal/daemon-client";
import { decodeWorkspaceIdFromPathSegment } from "@/utils/host-routes";
import { connectDaemonClient } from "./daemon-client-loader";
@@ -17,7 +16,6 @@ type NewWorkspaceDaemonClient = Pick<
| "connect"
| "createPaseoWorktree"
| "createWorkspace"
| "fetchAgents"
| "fetchWorkspaces"
| "getPaseoWorktreeList"
| "getDaemonConfig"
@@ -26,7 +24,6 @@ type NewWorkspaceDaemonClient = Pick<
| "enablePlugin"
| "inspectWorkspaceRecovery"
| "listProjects"
| "listTerminals"
| "on"
| "patchDaemonConfig"
| "removeProject"
@@ -625,120 +622,3 @@ export async function delayBrowserAgentCreatedStatus(
waitForDelayedCreatedStatus: () => delayedCreatedStatusSeen,
};
}
export interface WorkspaceCreatedDelayControl {
agentRequests: readonly CreateAgentRequestMessage[];
release(): void;
waitForCreateRequest(): Promise<void>;
}
/**
* Holds `workspace.create.response` so a test can act as the user does while the daemon is still
* running `git worktree add` — most importantly, navigate somewhere else.
*/
export async function delayBrowserWorkspaceCreatedResponse(
page: Page,
): Promise<WorkspaceCreatedDelayControl> {
const daemonPortPattern = daemonWsRoutePattern();
const agentRequests: CreateAgentRequestMessage[] = [];
const createRequestIds = new Set<string>();
const delayedForwards: Array<() => void> = [];
let releaseRequested = false;
let resolveCreateRequest: (() => void) | null = null;
const createRequestSeen = new Promise<void>((resolve) => {
resolveCreateRequest = resolve;
});
await page.routeWebSocket(daemonPortPattern, (ws) => {
const server = ws.connectToServer();
ws.onMessage((message) => {
const sessionMessage = getSessionMessage(message);
if (sessionMessage?.type === "create_agent_request")
agentRequests.push(sessionMessage as CreateAgentRequestMessage);
if (sessionMessage?.type === "workspace.create.request") {
const requestId = getStringField(sessionMessage, "requestId");
if (requestId) {
createRequestIds.add(requestId);
resolveCreateRequest?.();
}
}
server.send(message);
});
server.onMessage((message) => {
const sessionMessage = getSessionMessage(message);
const payload =
sessionMessage?.type === "workspace.create.response" &&
typeof sessionMessage.payload === "object"
? (sessionMessage.payload as Record<string, unknown>)
: null;
const requestId = payload ? getStringField(payload, "requestId") : null;
if (requestId && createRequestIds.has(requestId) && !releaseRequested) {
delayedForwards.push(() => ws.send(message));
return;
}
ws.send(message);
});
});
return {
agentRequests,
release() {
releaseRequested = true;
for (const forward of delayedForwards.splice(0)) {
forward();
}
},
waitForCreateRequest: () => createRequestSeen,
};
}
type WorkspaceEntry = Awaited<
ReturnType<NewWorkspaceDaemonClient["fetchWorkspaces"]>
>["entries"][number];
/**
* Waits for a workspace the caller did not already know about, and returns it. Tests that create a
* workspace without navigating to it have no route to assert on, so the daemon's own list is the
* signal that creation finished.
*/
export async function waitForCreatedWorkspace(
client: NewWorkspaceDaemonClient,
knownWorkspaceIds: ReadonlySet<string>,
options?: { timeout?: number },
): Promise<WorkspaceEntry> {
let created: WorkspaceEntry | undefined;
await expect
.poll(
async () => {
const payload = await client.fetchWorkspaces();
created = payload.entries.find((entry) => !knownWorkspaceIds.has(entry.id));
return created !== undefined;
},
{ timeout: options?.timeout ?? 60_000 },
)
.toBe(true);
if (!created) {
throw new Error("Workspace list reported a new workspace but it could not be read back");
}
return created;
}
export async function countWorkspaceAgents(
client: NewWorkspaceDaemonClient,
workspaceId: string,
): Promise<number> {
const payload = await client.fetchAgents({ filter: { includeArchived: true } });
return payload.entries.filter((entry) => entry.agent.workspaceId === workspaceId).length;
}
export async function countWorkspaceTerminals(
client: NewWorkspaceDaemonClient,
workspaceId: string,
): Promise<number> {
const payload = await client.listTerminals(undefined, undefined, { workspaceId });
return payload.terminals.length;
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/app",
"version": "0.8.0",
"version": "0.8.0-beta.1",
"private": true,
"main": "index.ts",
"scripts": {
@@ -80,11 +80,8 @@ function QuestionOptionRow({
);
const optionLabelStyle = useMemo(
() => [
styles.optionLabel,
{ color: isSelected ? theme.colors.foreground : theme.colors.foregroundMuted },
],
[isSelected, theme.colors.foreground, theme.colors.foregroundMuted],
() => [styles.optionLabel, { color: theme.colors.foreground }],
[theme.colors.foreground],
);
const optionDescriptionStyle = useMemo(
() => [styles.optionDescription, { color: theme.colors.foregroundMuted }],
@@ -99,11 +96,11 @@ function QuestionOptionRow({
styles.selectionControl,
multiSelect ? styles.selectionControlCheckbox : styles.selectionControlRadio,
{
borderColor: isSelected ? theme.colors.accent : theme.colors.foregroundExtraMuted,
borderColor: isSelected ? theme.colors.accent : theme.colors.foregroundMuted,
backgroundColor: isSelected && multiSelect ? theme.colors.accent : "transparent",
},
],
[isSelected, multiSelect, theme.colors.accent, theme.colors.foregroundExtraMuted],
[isSelected, multiSelect, theme.colors.accent, theme.colors.foregroundMuted],
);
const radioDotStyle = useMemo(
() => [styles.selectionRadioDot, { backgroundColor: theme.colors.accent }],
@@ -631,7 +628,7 @@ const styles = StyleSheet.create((theme) => ({
questionText: {
flex: 1,
fontSize: theme.fontSize.base,
fontWeight: theme.fontWeight.normal,
fontWeight: theme.fontWeight.medium,
lineHeight: 22,
},
optionsWrap: {
@@ -656,7 +653,7 @@ const styles = StyleSheet.create((theme) => ({
},
questionNavText: {
fontSize: theme.fontSize.base,
fontWeight: theme.fontWeight.normal,
fontWeight: theme.fontWeight.medium,
},
optionItem: {
flexDirection: "row",
@@ -680,7 +677,7 @@ const styles = StyleSheet.create((theme) => ({
},
optionLabel: {
fontSize: theme.fontSize.base,
fontWeight: theme.fontWeight.normal,
fontWeight: theme.fontWeight.semibold,
lineHeight: 22,
},
optionDescription: {
@@ -1,35 +0,0 @@
import type { AgentSessionConfig } from "@getpaseo/protocol/agent-types";
import type { AgentSnapshotPayload, CreateAgentRequestMessage } from "@getpaseo/protocol/messages";
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
import { encodeImages } from "@/utils/encode-images";
import type { UserMessageImageAttachment } from "@/types/stream";
export interface WorkspaceDraftAgentRequest {
workspaceId: string;
config: AgentSessionConfig;
text: string;
clientMessageId: string;
images?: UserMessageImageAttachment[];
attachments?: CreateAgentRequestMessage["attachments"];
}
/**
* Shared by the workspace draft tab and by the new-workspace screen when it finishes creation
* after the user has already navigated away and no draft tab will ever mount.
*/
export async function requestWorkspaceDraftAgent(
client: DaemonClient,
request: WorkspaceDraftAgentRequest,
): Promise<AgentSnapshotPayload> {
const images = await encodeImages(request.images);
return await client.createAgent({
config: request.config,
workspaceId: request.workspaceId,
clientMessageId: request.clientMessageId,
...(request.text ? { initialPrompt: request.text } : {}),
...(images && images.length > 0 ? { images } : {}),
...(request.attachments && request.attachments.length > 0
? { attachments: request.attachments }
: {}),
});
}
@@ -24,7 +24,7 @@ import type { Agent } from "@/stores/session-store";
import { useWorkspaceFields } from "@/stores/session-store-hooks";
import { useWorkspaceDraftSubmissionStore } from "@/stores/workspace-draft-submission-store";
import { useAgentControlCommandCenterActions } from "@/command-center/agent-control-registration";
import { requestWorkspaceDraftAgent } from "@/composer/draft/create-agent-request";
import { encodeImages } from "@/utils/encode-images";
import type { WorkspaceFileOpenRequest } from "@/workspace/file-open";
import { shouldAutoFocusWorkspaceDraftComposer } from "@/screens/workspace/workspace-draft-pane-focus";
import {
@@ -194,14 +194,15 @@ async function submitDraftCreateRequest(input: {
featureValues: autoSubmitConfig?.featureValues ?? composerState.featureValues,
});
const imagesData = await encodeImages(images);
const attachmentsArray = Array.isArray(attachments) ? attachments : undefined;
const result = await requestWorkspaceDraftAgent(client, {
const result = await client.createAgent({
config,
workspaceId,
text,
...(text ? { initialPrompt: text } : {}),
clientMessageId: attempt.clientMessageId,
...(images ? { images } : {}),
...(attachmentsArray ? { attachments: attachmentsArray } : {}),
...(imagesData && imagesData.length > 0 ? { images: imagesData } : {}),
...(attachmentsArray && attachmentsArray.length > 0 ? { attachments: attachmentsArray } : {}),
});
return {
+12 -108
View File
@@ -85,15 +85,10 @@ import { useProjectIcons } from "@/projects/icons";
import { ICON_SIZE, type Theme } from "@/styles/theme";
import type { ComposerAttachment } from "@/attachments/types";
import { useDraftWorkspaceAttachmentScopeKey } from "@/attachments/workspace-attachments-store";
import { requestWorkspaceDraftAgent } from "@/composer/draft/create-agent-request";
import { buildWorkspaceDraftAgentConfig } from "@/screens/workspace/workspace-draft-agent-config";
import type { MessagePayload } from "@/composer/types";
import type { UserComposerAttachment } from "@/attachments/types";
import type { AgentAttachment, ForgeSearchItem } from "@getpaseo/protocol/messages";
import type {
CreatePaseoWorktreeInput,
DaemonClient,
} from "@getpaseo/client/internal/daemon-client";
import type { CreatePaseoWorktreeInput } from "@getpaseo/client/internal/daemon-client";
import type { AgentProvider } from "@getpaseo/protocol/agent-types";
import type { WorkspaceDraftTabSetup, WorkspaceTabTarget } from "@/workspace-tabs/model";
import { isEmptyWorkspaceSubmission, runCreateEmptyWorkspace } from "./new-workspace-empty";
@@ -128,11 +123,6 @@ import {
type ListTerminalsPayload,
upsertCreatedTerminalPayload,
} from "./workspace/terminals/state";
import {
captureWorkspaceDraftCleanup,
createWorkspaceAgentInBackground,
} from "./new-workspace/background-handoff";
import { useNewWorkspaceScreenPresence } from "./new-workspace/screen-presence";
const ThemedFolderPlus = withUnistyles(FolderPlus);
const foregroundMutedColorMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
@@ -757,19 +747,10 @@ function normalizeBranchDetails(
return names.map((name) => ({ name, committerDate: 0 }));
}
/**
* "background" means the user left the New workspace screen mid-creation, so nothing navigated
* and the screen — if still mounted under another route — has to drop its pending state itself.
*/
type SubmitOutcome = "navigated" | "background";
interface SubmitDraftInput {
clearConsumedDraft: () => void;
serverId: string;
draftKey: string;
clearDraft: (lifecycle: "sent" | "abandoned") => void;
draftId?: string;
draftContextScopeKey: string | null;
initialSetup?: WorkspaceDraftTabSetup;
workspaceId: string;
workspaceDirectory: string;
@@ -778,8 +759,6 @@ interface SubmitDraftInput {
provider: AgentProvider;
composerState: NewWorkspaceComposerState;
supportsForgeSearch: boolean;
resolveClient: () => DaemonClient;
isStillOnCreateScreen: () => boolean;
}
type NewWorkspaceComposerState = NonNullable<
@@ -881,13 +860,9 @@ interface CreateChatAgentInput {
withInitialAgent: boolean;
}) => Promise<ReturnType<typeof normalizeWorkspaceDescriptor>>;
serverId: string;
draftKey: string;
clearDraft: (lifecycle: "sent" | "abandoned") => void;
draftId?: string;
draftContextScopeKey: string | null;
supportsForgeSearch: boolean;
resolveClient: () => DaemonClient;
isStillOnCreateScreen: () => boolean;
labels: {
composerStateRequired: string;
selectModel: string;
@@ -943,9 +918,8 @@ function buildComposerInitialValues(input: {
return undefined;
}
async function runCreateChatAgent(input: CreateChatAgentInput): Promise<SubmitOutcome> {
async function runCreateChatAgent(input: CreateChatAgentInput): Promise<void> {
const { payload, composerState, ensureWorkspace, serverId, clearDraft } = input;
const clearConsumedDraft = captureWorkspaceDraftCleanup(input);
const { text, attachments, cwd } = payload;
if (!composerState) {
throw new Error(input.labels.composerStateRequired);
@@ -973,13 +947,10 @@ async function runCreateChatAgent(input: CreateChatAgentInput): Promise<SubmitOu
provider,
composerState,
});
return await submitWorkspaceDraft({
clearConsumedDraft,
submitWorkspaceDraft({
serverId,
clearDraft,
draftKey: input.draftKey,
draftId: input.draftId,
draftContextScopeKey: input.draftContextScopeKey,
initialSetup,
workspaceId: ensuredWorkspace.id,
workspaceDirectory: ensuredWorkspace.workspaceDirectory,
@@ -988,8 +959,6 @@ async function runCreateChatAgent(input: CreateChatAgentInput): Promise<SubmitOu
provider,
composerState,
supportsForgeSearch: input.supportsForgeSearch,
resolveClient: input.resolveClient,
isStillOnCreateScreen: input.isStillOnCreateScreen,
});
}
@@ -1052,7 +1021,7 @@ function resolveWorkspaceDraftSubmissionConfig(input: {
};
}
async function submitWorkspaceDraft(input: SubmitDraftInput): Promise<SubmitOutcome> {
function submitWorkspaceDraft(input: SubmitDraftInput): void {
const {
serverId,
clearDraft,
@@ -1080,33 +1049,6 @@ async function submitWorkspaceDraft(input: SubmitDraftInput): Promise<SubmitOutc
composerState,
initialSetup,
});
// Creation blocks on a slow daemon RPC. If the user moved on while it ran, the destination
// screen's draft tab will never mount to issue create_agent, so this path does it instead.
if (!input.isStillOnCreateScreen()) {
await createWorkspaceAgentInBackground({
clearConsumedDraft: input.clearConsumedDraft,
createAgent: () =>
requestWorkspaceDraftAgent(input.resolveClient(), {
workspaceId,
config: buildWorkspaceDraftAgentConfig({
provider: submission.provider,
cwd: submission.cwd,
...(submission.modeId ? { modeId: submission.modeId } : {}),
...(submission.model ? { model: submission.model } : {}),
...(submission.thinkingOptionId
? { thinkingOptionId: submission.thinkingOptionId }
: {}),
...(submission.featureValues ? { featureValues: submission.featureValues } : {}),
}),
text: text.trim(),
clientMessageId,
...(wirePayload.images.length > 0 ? { images: wirePayload.images } : {}),
...(wirePayload.attachments.length > 0 ? { attachments: wirePayload.attachments } : {}),
}),
});
return "background";
}
useCreateFlowStore.getState().setPending({
serverId,
draftId,
@@ -1140,7 +1082,6 @@ async function submitWorkspaceDraft(input: SubmitDraftInput): Promise<SubmitOutc
workspaceId,
target: submission.target,
});
return "navigated";
}
function useNewWorkspaceHostSelector(input: {
@@ -1650,7 +1591,6 @@ export function NewWorkspaceScreen({
const isolationPickerAnchorRef = useRef<View>(null);
const hostPickerAnchorRef = useRef<View | null>(null);
const isDraftHandoffActive = useIsNewWorkspaceDraftHandoffActive({ draftId, selectedServerId });
const isStillOnCreateScreen = useNewWorkspaceScreenPresence();
// Launch target: what the composer submits to (chat agent, or a terminal
// profile). Mirrors useWorkspaceIsolation's pattern below: the derived
@@ -1756,12 +1696,11 @@ export function NewWorkspaceScreen({
}, []);
const withConnectedClient = useCallback(() => {
const connectedClient = getHostRuntimeStore().getClient(selectedServerId);
if (!connectedClient?.isConnected) {
if (!client || !isConnected) {
throw new Error(t("newWorkspace.errors.hostDisconnected"));
}
return connectedClient;
}, [selectedServerId, t]);
return client;
}, [client, isConnected, t]);
const clientReady = isConnected && Boolean(client);
const hasSelectedSourceDirectory = selectedSourceDirectory !== null;
@@ -2104,49 +2043,31 @@ export function NewWorkspaceScreen({
await updateFormPreferences({ launchTarget });
if (isEmptyWorkspaceSubmission(payload)) {
setPendingAction("empty");
let outcome: SubmitOutcome = "background";
await runCreateEmptyWorkspace({
payload,
ensureWorkspace,
serverId: selectedServerId,
navigate: (targetServerId, workspaceId) => {
if (!isStillOnCreateScreen()) {
return;
}
outcome = "navigated";
navigateToWorkspace({ serverId: targetServerId, workspaceId });
},
navigate: (targetServerId, workspaceId) =>
navigateToWorkspace({ serverId: targetServerId, workspaceId }),
});
// Nothing navigated, so this screen may still be mounted under another route. Release
// the pending lock it would otherwise keep forever.
if (outcome === "background") {
setPendingAction(null);
}
return;
}
setPendingAction("chat");
const outcome = await runCreateChatAgent({
await runCreateChatAgent({
payload,
composerState,
forkDraftSetup,
ensureWorkspace,
serverId: selectedServerId,
clearDraft: chatDraft.clear,
draftKey,
draftId,
draftContextScopeKey,
supportsForgeSearch,
resolveClient: withConnectedClient,
isStillOnCreateScreen,
labels: {
composerStateRequired: t("newWorkspace.errors.composerStateRequired"),
selectModel: t("newWorkspace.errors.selectModel"),
},
});
if (outcome === "background") {
setPendingAction(null);
}
} catch (error) {
const message = toErrorMessage(error);
setPendingAction(null);
@@ -2156,20 +2077,16 @@ export function NewWorkspaceScreen({
},
[
composerState,
draftContextScopeKey,
draftId,
chatDraft.clear,
draftKey,
ensureWorkspace,
forkDraftSetup,
isStillOnCreateScreen,
launchTarget,
selectedServerId,
supportsForgeSearch,
t,
toast,
updateFormPreferences,
withConnectedClient,
],
);
@@ -2178,7 +2095,6 @@ export function NewWorkspaceScreen({
setErrorMessage(null);
await updateFormPreferences({ launchTarget });
setPendingAction("terminal");
let outcome: SubmitOutcome = "background";
await runCreateTerminalWorkspace({
cwd: selectedSourceDirectory ?? "",
prompt: terminalPromptText,
@@ -2212,20 +2128,9 @@ export function NewWorkspaceScreen({
withConnectedClient().sendTerminalInput(terminalId, { type: "input", data });
},
serverId: selectedServerId,
// The terminal is spawned and fed its command before this runs, so skipping the
// navigation costs nothing: it is standalone, and `reconcileTabs` auto-opens standalone
// terminals when the workspace is next visited.
navigate: (targetServerId, workspaceId, target) => {
if (!isStillOnCreateScreen()) {
return;
}
outcome = "navigated";
navigateToWorkspace({ serverId: targetServerId, workspaceId, target });
},
navigate: (targetServerId, workspaceId, target) =>
navigateToWorkspace({ serverId: targetServerId, workspaceId, target }),
});
if (outcome === "background") {
setPendingAction(null);
}
} catch (error) {
const message = toErrorMessage(error);
setPendingAction(null);
@@ -2234,7 +2139,6 @@ export function NewWorkspaceScreen({
}
}, [
ensureWorkspace,
isStillOnCreateScreen,
launchTarget,
queryClient,
selectedServerId,
@@ -1,176 +0,0 @@
import { beforeEach, describe, expect, it } from "vitest";
import { useCreateFlowStore } from "@/stores/create-flow-store";
import { useDraftStore } from "@/stores/draft-store";
import { useWorkspaceAttachmentsStore } from "@/attachments/workspace-attachments-store";
import { useWorkspaceDraftSubmissionStore } from "@/stores/workspace-draft-submission-store";
import {
captureWorkspaceDraftCleanup,
createWorkspaceAgentInBackground,
} from "./background-handoff";
const DRAFT_ID = "draft_1";
const DRAFT_KEY = "new-workspace";
const SCOPE_KEY = "draft:draft_1";
function saveDraft(text: string) {
useDraftStore
.getState()
.saveDraftInput({ draftKey: DRAFT_KEY, draft: { text, attachments: [] } });
}
function draftText(): string | undefined {
return useDraftStore.getState().drafts[DRAFT_KEY]?.input.text;
}
function captureCleanup() {
return captureWorkspaceDraftCleanup({
draftId: DRAFT_ID,
draftKey: DRAFT_KEY,
clearDraft: (lifecycle) =>
useDraftStore.getState().clearDraftInput({ draftKey: DRAFT_KEY, lifecycle }),
draftContextScopeKey: SCOPE_KEY,
});
}
function run(createAgent: () => Promise<unknown>, clearConsumedDraft = captureCleanup()) {
return createWorkspaceAgentInBackground({ createAgent, clearConsumedDraft });
}
beforeEach(() => {
useWorkspaceDraftSubmissionStore.setState({ pendingByDraftId: {}, setupByDraftId: {} });
useCreateFlowStore.setState({ pendingByDraftId: {} });
useWorkspaceAttachmentsStore.setState({ attachmentsByScope: { [SCOPE_KEY]: [] } });
saveDraft("do the thing");
});
describe("createWorkspaceAgentInBackground", () => {
it("preserves context added to a newer draft without editing its text", async () => {
await run(async () => {
useWorkspaceAttachmentsStore.getState().addWorkspaceAttachment({
scopeKey: SCOPE_KEY,
attachment: {
kind: "chat_history",
id: "fork-context",
attachment: {
type: "text",
mimeType: "text/plain",
contextKind: "chat_history",
title: "Chat history",
text: "Preserve this context",
},
source: { serverId: "local", agentId: "agent-1" },
},
});
useWorkspaceDraftSubmissionStore.getState().setDraftSetup({
draftId: DRAFT_ID,
setup: {
cwd: "/work/new-repo",
provider: "codex",
modeId: null,
model: null,
thinkingOptionId: null,
featureValues: {},
},
});
});
expect(useWorkspaceAttachmentsStore.getState().attachmentsByScope[SCOPE_KEY]).toHaveLength(1);
expect(useWorkspaceDraftSubmissionStore.getState().setupByDraftId[DRAFT_ID]?.setup.cwd).toBe(
"/work/new-repo",
);
});
it("creates one agent and clears the consumed draft setup, attachments and input", async () => {
let calls = 0;
useWorkspaceDraftSubmissionStore.getState().setDraftSetup({
draftId: DRAFT_ID,
setup: {
cwd: "/work/repo",
provider: "claude",
modeId: null,
model: null,
thinkingOptionId: null,
featureValues: {},
},
});
await run(async () => {
calls += 1;
});
expect(calls).toBe(1);
expect(useWorkspaceDraftSubmissionStore.getState().setupByDraftId).toEqual({});
expect(useWorkspaceAttachmentsStore.getState().attachmentsByScope[SCOPE_KEY]).toBeUndefined();
expect(draftText()).toBe("");
});
it("preserves context changed while workspace creation was pending", async () => {
const clearConsumedDraft = captureCleanup();
useWorkspaceAttachmentsStore.getState().addWorkspaceAttachment({
scopeKey: SCOPE_KEY,
attachment: {
kind: "chat_history",
id: "fork-context",
attachment: {
type: "text",
mimeType: "text/plain",
contextKind: "chat_history",
title: "Chat history",
text: "Preserve this context",
},
source: { serverId: "local", agentId: "agent-1" },
},
});
await run(async () => undefined, clearConsumedDraft);
expect(useWorkspaceAttachmentsStore.getState().attachmentsByScope[SCOPE_KEY]).toHaveLength(1);
expect(draftText()).toBe("do the thing");
});
it("leaves no pending submission behind, so no draft tab can create a second agent", async () => {
await run(async () => undefined);
expect(useWorkspaceDraftSubmissionStore.getState().pendingByDraftId).toEqual({});
expect(useCreateFlowStore.getState().pendingByDraftId).toEqual({});
});
it("rethrows a failed creation and keeps the prompt for retry", async () => {
const failure = new Error("daemon exploded");
await expect(
run(async () => {
throw failure;
}),
).rejects.toThrow(failure);
expect(draftText()).toBe("do the thing");
});
it("keeps a prompt typed into the shared draft while creation was in flight", async () => {
await run(async () => {
saveDraft("a different idea");
});
expect(draftText()).toBe("a different idea");
});
it("keeps a newer draft written while workspace creation was pending", async () => {
useWorkspaceAttachmentsStore.getState().addWorkspaceAttachment({
scopeKey: SCOPE_KEY,
attachment: {
kind: "chat_history",
id: "fork-context",
attachment: {
type: "text",
mimeType: "text/plain",
contextKind: "chat_history",
title: "Chat history",
text: "Preserve this context",
},
source: { serverId: "local", agentId: "agent-1" },
},
});
const clearConsumedDraft = captureCleanup();
saveDraft("a newer workspace idea");
await run(async () => undefined, clearConsumedDraft);
expect(draftText()).toBe("a newer workspace idea");
expect(useWorkspaceAttachmentsStore.getState().attachmentsByScope[SCOPE_KEY]).toHaveLength(1);
});
});
@@ -1,54 +0,0 @@
import { useWorkspaceAttachmentsStore } from "@/attachments/workspace-attachments-store";
import { useDraftStore } from "@/stores/draft-store";
import { useWorkspaceDraftSubmissionStore } from "@/stores/workspace-draft-submission-store";
interface WorkspaceDraftCleanupInput {
draftId?: string;
draftKey: string;
clearDraft: (lifecycle: "sent" | "abandoned") => void;
draftContextScopeKey: string | null;
}
/** Capture ownership before workspace creation starts, not when its response arrives. */
export function captureWorkspaceDraftCleanup(input: WorkspaceDraftCleanupInput): () => void {
const draftId = input.draftId?.trim() ?? "";
const scopeKey = input.draftContextScopeKey ?? "";
const draftVersion = useDraftStore.getState().drafts[input.draftKey]?.version;
const setup = useWorkspaceDraftSubmissionStore.getState().setupByDraftId[draftId];
const attachments = useWorkspaceAttachmentsStore.getState().attachmentsByScope[scopeKey];
return () => {
// 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 (
useDraftStore.getState().drafts[input.draftKey]?.version !== draftVersion ||
useWorkspaceDraftSubmissionStore.getState().setupByDraftId[draftId] !== setup ||
useWorkspaceAttachmentsStore.getState().attachmentsByScope[scopeKey] !== attachments
) {
return;
}
useWorkspaceDraftSubmissionStore.getState().clearDraftSetup({ draftId });
if (scopeKey) {
useWorkspaceAttachmentsStore.getState().clearWorkspaceAttachments({ scopeKey });
}
input.clearDraft("sent");
};
}
/**
* The workspace draft tab normally issues create_agent once it mounts on the destination screen.
* When the user leaves the New workspace screen before creation resolves, that tab never mounts,
* so this path issues the request itself. The agent tab opens on its own when the workspace is
* next visited — `reconcileTabs` auto-opens agents.
*
* The caller must not write a pending entry to the draft-submission or create-flow stores on this
* path: those drive the draft tab's auto-submit, and the daemon does not dedupe create_agent by
* clientMessageId, so a leftover entry would create a second agent when the workspace is opened.
*/
export async function createWorkspaceAgentInBackground(input: {
clearConsumedDraft: () => void;
createAgent: () => Promise<unknown>;
}): Promise<void> {
await input.createAgent();
input.clearConsumedDraft();
}
@@ -1,22 +0,0 @@
import { describe, expect, it } from "vitest";
import { isNewWorkspaceScreenActive } from "./screen-presence";
describe("isNewWorkspaceScreenActive", () => {
it("is active while the screen is mounted and the route is /new", () => {
expect(isNewWorkspaceScreenActive({ isMounted: true, pathname: "/new" })).toBe(true);
});
it("is inactive once the screen has been popped off the stack", () => {
expect(isNewWorkspaceScreenActive({ isMounted: false, pathname: "/new" })).toBe(false);
});
it("is inactive while another route sits on top of the screen", () => {
expect(isNewWorkspaceScreenActive({ isMounted: true, pathname: "/settings" })).toBe(false);
});
it("is inactive on a workspace route", () => {
expect(isNewWorkspaceScreenActive({ isMounted: true, pathname: "/host/workspace/wks_1" })).toBe(
false,
);
});
});
@@ -1,41 +0,0 @@
import { usePathname } from "expo-router";
import { useCallback, useEffect, useRef } from "react";
const NEW_WORKSPACE_PATHNAME = "/new";
export interface NewWorkspaceScreenPresence {
isMounted: boolean;
pathname: string;
}
/**
* Workspace creation blocks on a slow daemon RPC, so by the time it resolves the user may have
* moved on. Both signals are needed: popping to a workspace unmounts the screen while its last
* observed pathname stays "/new", and pushing a route on top of it keeps it mounted underneath.
*/
export function isNewWorkspaceScreenActive(input: NewWorkspaceScreenPresence): boolean {
return input.isMounted && input.pathname === NEW_WORKSPACE_PATHNAME;
}
export function useNewWorkspaceScreenPresence(): () => boolean {
const pathname = usePathname();
const pathnameRef = useRef(pathname);
pathnameRef.current = pathname;
const isMountedRef = useRef(true);
useEffect(() => {
isMountedRef.current = true;
return () => {
isMountedRef.current = false;
};
}, []);
return useCallback(
() =>
isNewWorkspaceScreenActive({
isMounted: isMountedRef.current,
pathname: pathnameRef.current,
}),
[],
);
}
+4 -4
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/cli",
"version": "0.8.0",
"version": "0.8.0-beta.1",
"description": "Paseo CLI - control your AI coding agents from the command line",
"bin": {
"paseo": "bin/paseo"
@@ -28,9 +28,9 @@
},
"dependencies": {
"@clack/prompts": "^1.0.0",
"@getpaseo/client": "0.8.0",
"@getpaseo/protocol": "0.8.0",
"@getpaseo/server": "0.8.0",
"@getpaseo/client": "0.8.0-beta.1",
"@getpaseo/protocol": "0.8.0-beta.1",
"@getpaseo/server": "0.8.0-beta.1",
"chalk": "^5.3.0",
"commander": "^12.0.0",
"mime-types": "^2.1.35",
+3 -3
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/client",
"version": "0.8.0",
"version": "0.8.0-beta.1",
"description": "Paseo client SDK package",
"files": [
"dist",
@@ -39,8 +39,8 @@
"test": "vitest run"
},
"dependencies": {
"@getpaseo/protocol": "0.8.0",
"@getpaseo/relay": "0.8.0",
"@getpaseo/protocol": "0.8.0-beta.1",
"@getpaseo/relay": "0.8.0-beta.1",
"zod": "^4.4.3"
},
"devDependencies": {
@@ -5,7 +5,6 @@ const os = require("node:os");
const path = require("node:path");
const { setTimeout: delay } = require("node:timers/promises");
const { chromium } = require("playwright");
const { extractFile } = require("@electron/asar");
const EXECUTABLE_NAME = "Paseo";
const SMOKE_TIMEOUT_MS = 60_000;
@@ -806,23 +805,9 @@ async function stopCliDaemon({ appPath, env }) {
});
}
function assertLinuxDesktopIdentity(appPath) {
if (process.platform === "linux") {
const metadata = JSON.parse(
extractFile(path.join(appPath, "resources", "app.asar"), "package.json").toString(),
);
if (metadata.desktopName !== `${EXECUTABLE_NAME}.desktop`) {
throw new Error(
`Packaged Linux desktop identity ${JSON.stringify(metadata.desktopName)} does not match ${EXECUTABLE_NAME}.desktop`,
);
}
}
}
async function smokePackagedDesktopApp({ appPath }) {
const executablePath = getExecutablePath(appPath);
assertExecutable(executablePath, "Packaged app executable");
assertLinuxDesktopIdentity(appPath);
ensureLinuxSandboxPermissions(appPath);
await smokeColdCliDaemonStart({ appPath });
+2 -4
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/desktop",
"version": "0.8.0",
"version": "0.8.0-beta.1",
"private": true,
"description": "Paseo desktop app (Electron wrapper)",
"homepage": "https://paseo.sh",
@@ -35,7 +35,6 @@
"zod": "^4.4.3"
},
"devDependencies": {
"@electron/asar": "3.4.1",
"@types/node": "24.6.0",
"@types/ws": "^8.5.14",
"electron": "44.2.0",
@@ -44,6 +43,5 @@
"unzip-crx-3": "^0.2.0",
"vitest": "^4.1.6",
"wait-on": "8.0.5"
},
"desktopName": "Paseo.desktop"
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/expo-two-way-audio",
"version": "0.8.0",
"version": "0.8.0-beta.1",
"description": "Native module for two way audio streaming",
"keywords": [
"ExpoTwoWayAudio",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/highlight",
"version": "0.8.0",
"version": "0.8.0-beta.1",
"files": [
"dist",
"!dist/**/*.map",
+5 -5
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/plugin",
"version": "0.8.0",
"version": "0.8.0-beta.1",
"description": "Paseo plugin SDK package",
"files": [
"dist",
@@ -65,8 +65,8 @@
"use-sync-external-store": "^1.6.0"
},
"devDependencies": {
"@getpaseo/client": "0.8.0",
"@getpaseo/protocol": "0.8.0",
"@getpaseo/client": "0.8.0-beta.1",
"@getpaseo/protocol": "0.8.0-beta.1",
"@types/node": "^20.9.0",
"@types/react": "~19.2.0",
"react": "19.1.0",
@@ -76,8 +76,8 @@
"zod": "^4.4.3"
},
"peerDependencies": {
"@getpaseo/client": "0.8.0",
"@getpaseo/protocol": "0.8.0",
"@getpaseo/client": "0.8.0-beta.1",
"@getpaseo/protocol": "0.8.0-beta.1",
"react": "~19.1.0",
"react-native": ">=0.81.5",
"zod": "^4.4.3"
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/protocol",
"version": "0.8.0",
"version": "0.8.0-beta.1",
"description": "Paseo shared protocol schemas and wire types",
"files": [
"dist",
+40
View File
@@ -1075,8 +1075,38 @@ export const WorkspaceRecoveryInspectRequestSchema = z.object({
requestId: z.string(),
});
const AgentRequestOperationSchema = z.object({
key: z.string().min(1).max(512),
deadlineAt: z.string().datetime().optional(),
});
export const AgentRequestsCancelRequestSchema = z.object({
type: z.literal("agent.requests.cancel.request"),
requestId: z.string(),
key: z.string().min(1).max(512),
creationKey: z.string().min(1).max(512),
});
export const AgentRequestsInspectRequestSchema = AgentRequestsCancelRequestSchema.extend({
type: z.literal("agent.requests.inspect.request"),
});
export const AgentRequestsCancelResponseSchema = z.object({
type: z.literal("agent.requests.cancel.response"),
payload: z.object({
requestId: z.string(),
agentId: z.string().nullable(),
outcome: z.enum(["settled", "pending", "unknown"]),
}),
});
export const AgentRequestsInspectResponseSchema = AgentRequestsCancelResponseSchema.extend({
type: z.literal("agent.requests.inspect.response"),
});
export const WorkspaceRecoveryRestoreRequestSchema = z.object({
type: z.literal("workspace.recovery.restore.request"),
operation: AgentRequestOperationSchema.optional(),
workspaceId: z.string(),
requestId: z.string(),
});
@@ -1394,6 +1424,7 @@ export const FetchAgentRequestMessageSchema = z.object({
export const SendAgentMessageRequestSchema = z.object({
type: z.literal("send_agent_message_request"),
operation: AgentRequestOperationSchema.optional(),
requestId: z.string(),
/** Accepts full ID, unique prefix, or exact full title (server resolves). */
agentId: z.string(),
@@ -1680,6 +1711,7 @@ export type CreateAgentWorktreeTarget = z.infer<typeof CreateAgentWorktreeTarget
export const CreateAgentRequestMessageSchema = z.object({
type: z.literal("create_agent_request"),
operation: AgentRequestOperationSchema.optional(),
// A creation key requires initialPrompt to be sent separately with a stable messageId.
idempotencyKey: z.string().min(1).max(512).optional(),
config: AgentSessionConfigSchema,
@@ -1773,6 +1805,7 @@ export const RefreshAgentRequestMessageSchema = z.object({
export const CancelAgentRequestMessageSchema = z.object({
type: z.literal("cancel_agent_request"),
operation: AgentRequestOperationSchema.optional(),
agentId: z.string(),
requestId: z.string().optional(),
});
@@ -2545,6 +2578,7 @@ export const ProjectGithubCloneRequestSchema = z.object({
export const ArchiveWorkspaceRequestSchema = z.object({
type: z.literal("archive_workspace_request"),
operation: AgentRequestOperationSchema.optional(),
workspaceId: z.string(),
requestId: z.string(),
});
@@ -2977,6 +3011,7 @@ export const HubExecutionAgentCreateRequestSchema = z.object({
type: z.literal("hub.execution.agent.create.request"),
requestId: z.string(),
executionId: z.string(),
deadlineAt: z.string().datetime().optional(),
provider: z.string(),
cwd: z.string(),
prompt: z.string(),
@@ -3096,6 +3131,8 @@ export const SessionInboundMessageSchema = z.discriminatedUnion("type", [
WorkspaceLabelDeleteInspectRequestSchema,
WorkspaceRecoveryInspectRequestSchema,
WorkspaceRecoveryRestoreRequestSchema,
AgentRequestsCancelRequestSchema,
AgentRequestsInspectRequestSchema,
SetVoiceModeMessageSchema,
SendAgentMessageRequestSchema,
WaitForFinishRequestSchema,
@@ -3433,6 +3470,7 @@ export const ServerInfoStatusPayloadSchema = z
.object({
// COMPAT(agentRequestReceipts): added in v0.8.0; remove gate after 2027-03-05.
agentRequestReceipts: z.boolean().optional(),
agentRequestCancellation: z.boolean().optional(),
// COMPAT(hubAgentRpc): added in v0.8.0; remove gate after 2027-03-05.
hubAgentRpc: z.boolean().optional(),
providersSnapshot: z.boolean().optional(),
@@ -6543,6 +6581,8 @@ export const SessionOutboundMessageSchema = z.discriminatedUnion("type", [
AgentAttentionRequiredMessageSchema,
AgentForkContextResponseMessageSchema,
CancelAgentResponseMessageSchema,
AgentRequestsCancelResponseSchema,
AgentRequestsInspectResponseSchema,
ClearAgentAttentionResponseMessageSchema,
WorkspaceCreateResponseSchema,
WorkspaceClearAttentionResponseSchema,
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/relay",
"version": "0.8.0",
"version": "0.8.0-beta.1",
"description": "Paseo relay for bridging daemon and client connections",
"files": [
"dist",
+6 -6
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/server",
"version": "0.8.0",
"version": "0.8.0-beta.1",
"description": "Paseo backend server",
"files": [
"dist/server",
@@ -71,11 +71,11 @@
"@agentclientprotocol/sdk": "^0.17.1",
"@anthropic-ai/claude-agent-sdk": "0.3.246",
"@anthropic-ai/sdk": "^0.104.2",
"@getpaseo/client": "0.8.0",
"@getpaseo/highlight": "0.8.0",
"@getpaseo/plugin": "0.8.0",
"@getpaseo/protocol": "0.8.0",
"@getpaseo/relay": "0.8.0",
"@getpaseo/client": "0.8.0-beta.1",
"@getpaseo/highlight": "0.8.0-beta.1",
"@getpaseo/plugin": "0.8.0-beta.1",
"@getpaseo/protocol": "0.8.0-beta.1",
"@getpaseo/relay": "0.8.0-beta.1",
"@isaacs/ttlcache": "^2.1.4",
"@modelcontextprotocol/sdk": "1.29.0",
"@opencode-ai/sdk": "1.14.46",
@@ -19,7 +19,6 @@ import { toAgentPayload } from "./agent-projections.js";
import { projectTimelineRows } from "./timeline-projection.js";
import { getOpenAgentTabLabel, PARENT_AGENT_ID_LABEL } from "@getpaseo/protocol/agent-labels";
import { formatSystemNotificationPrompt, startAgentRun } from "./agent-prompt.js";
import { StaleProviderSessionError } from "./stale-provider-session-error.js";
import { ensureAgentLoaded, ensureUnarchivedAgentLoaded } from "./agent-loading.js";
import type { StoredAgentRecord } from "./agent-storage.js";
import type {
@@ -69,12 +68,6 @@ function deferred<T>(): Deferred<T> {
return { promise, resolve, reject };
}
async function drainAsyncGenerator<T>(generator: AsyncGenerator<T>): Promise<void> {
for await (const _ of generator) {
// Drain provider events while AgentManager subscribers observe them.
}
}
function waitForAgentLifecycle(
manager: AgentManager,
agentId: string,
@@ -526,32 +519,6 @@ class TestAgentSession implements AgentSession {
async close(): Promise<void> {}
}
class ResumeTrackingTestAgentClient extends TestAgentClient {
private readonly retryStarted = deferred<void>();
override async resumeSession(
_handle: AgentPersistenceHandle,
config?: Partial<AgentSessionConfig>,
): Promise<AgentSession> {
this.resumeOverrides.push(config);
const signalRetryStarted = () => this.retryStarted.resolve();
return new (class extends TestAgentSession {
override async startTurn(): Promise<{ turnId: string }> {
signalRetryStarted();
return await super.startTurn();
}
})({
provider: this.provider,
cwd: config?.cwd ?? process.cwd(),
daemonAppendSystemPrompt: config?.daemonAppendSystemPrompt,
});
}
waitForRetryStart(): Promise<void> {
return this.retryStarted.promise;
}
}
class McpCapableTestAgentSession extends TestAgentSession {
override readonly capabilities = {
...TEST_CAPABILITIES,
@@ -1510,6 +1477,41 @@ function fakeCodexEmitting(args: FakeCodexEmitterArgs): AgentClient {
const logger = createTestLogger();
test("canceling provider startup settles creation and closes a late session without registering it", async () => {
const client = new HeldAgentCreationClient();
const manager = new AgentManager({ clients: { codex: client }, logger });
const controller = new AbortController();
let outcome = "pending";
const creation = manager
.createAgent({ provider: "codex", cwd: process.cwd() }, undefined, {
workspaceId: undefined,
signal: controller.signal,
})
.then(
() => {
outcome = "created";
return;
},
() => {
outcome = "canceled";
},
);
await client.waitForCreationToStart();
try {
controller.abort(new Error("startup expired"));
await creation;
expect(outcome).toBe("canceled");
client.finishCreating();
await expect.poll(() => client.createdSessionClosed).toBe(true);
expect(manager.listAgents()).toEqual([]);
} finally {
client.finishCreating();
await creation;
manager.prepareForShutdown();
await manager.flushForShutdown();
}
});
test("does not register a session that finishes starting after shutdown begins", async () => {
const client = new HeldAgentCreationClient();
const manager = new AgentManager({
@@ -3710,201 +3712,6 @@ test("updateProviderRegistry removes providers omitted from the next registry",
expect(removedClient.createSessionCalls).toBe(0);
});
test("retires loaded agents when their plugin provider is replaced", async () => {
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-plugin-provider-reload-"));
const storage = new AgentStorage(join(workdir, "agents"), logger);
const provider = "plugin-provider";
class OriginalPluginClient extends TestAgentClient {
session: CloseRecordingTestAgentSession | null = null;
constructor() {
super(provider);
}
override async createSession(config: AgentSessionConfig): Promise<AgentSession> {
const session = new CloseRecordingTestAgentSession(config);
session.describePersistence = () => ({
provider,
sessionId: "plugin-session",
});
this.session = session;
return session;
}
}
const original = new OriginalPluginClient();
const replacement = new TestAgentClient(provider);
const manager = new AgentManager({
clients: { [provider]: original },
providerDefinitions: { [provider]: { enabled: true } },
registry: storage,
logger,
});
const created = await manager.createAgent({ provider, cwd: workdir }, undefined, {
workspaceId: undefined,
});
try {
manager.updateProviderRegistry({
providerDefinitions: { [provider]: { enabled: true } },
clients: { [provider]: replacement },
retiredProviders: [provider],
});
await manager.waitForAgentClose(created.id);
expect(original.session?.closed).toBe(true);
expect(manager.getAgent(created.id)).toBeNull();
const resumed = await ensureAgentLoaded(created.id, {
agentManager: manager,
agentStorage: storage,
logger,
});
expect(resumed.id).toBe(created.id);
expect(replacement.resumeOverrides).toEqual([
expect.objectContaining({ cwd: workdir, provider }),
]);
} finally {
await manager.closeAgent(created.id).catch(() => undefined);
await manager.flush().catch(() => undefined);
await storage.flush().catch(() => undefined);
rmSync(workdir, { recursive: true, force: true });
}
});
test("a prompt after provider replacement reopens the stale session", async () => {
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-stale-prompt-"));
const storage = new AgentStorage(join(workdir, "agents"), logger);
const provider = "plugin-provider";
class StalePluginSession extends CloseRecordingTestAgentSession {
override async startTurn(): Promise<{ turnId: string }> {
throw new StaleProviderSessionError("stale-bridge");
}
}
class StalePluginClient extends TestAgentClient {
constructor() {
super(provider);
}
override async createSession(config: AgentSessionConfig): Promise<AgentSession> {
const session = new StalePluginSession(config);
session.describePersistence = () => ({
provider,
sessionId: "plugin-session",
});
return session;
}
}
const staleClient = new StalePluginClient();
const replacement = new ResumeTrackingTestAgentClient(provider);
const manager = new AgentManager({
clients: { [provider]: staleClient },
providerDefinitions: { [provider]: { enabled: true } },
registry: storage,
logger,
});
const created = await manager.createAgent({ provider, cwd: workdir }, undefined, {
workspaceId: undefined,
});
try {
manager.updateProviderRegistry({
providerDefinitions: { [provider]: { enabled: true } },
clients: { [provider]: replacement },
});
const dispatch = await startAgentRun(manager, created.id, "continue after reload", logger);
expect(dispatch.disposition).toBe("turn_started");
await replacement.waitForRetryStart();
const result = await manager.waitForAgentEvent(created.id);
expect(result.status).toBe("idle");
expect(replacement.resumeOverrides).toHaveLength(1);
} finally {
await manager.closeAgent(created.id).catch(() => undefined);
await manager.flush().catch(() => undefined);
await storage.flush().catch(() => undefined);
rmSync(workdir, { recursive: true, force: true });
}
});
test("a replacement prompt recovers when the retired session fails to start", async () => {
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-stale-replacement-"));
const storage = new AgentStorage(join(workdir, "agents"), logger);
const provider = "plugin-provider";
class StaleReplacementSession extends TestAgentSession {
private starts = 0;
override async startTurn(): Promise<{ turnId: string }> {
this.starts += 1;
if (this.starts > 1) throw new StaleProviderSessionError("stale-bridge");
return { turnId: "initial-turn" };
}
override async interrupt(): Promise<void> {
if (this.starts > 1) throw new StaleProviderSessionError("stale-bridge");
this.pushEvent({
type: "turn_canceled",
provider: this.provider,
turnId: "initial-turn",
});
}
}
class StaleReplacementClient extends TestAgentClient {
constructor() {
super(provider);
}
override async createSession(config: AgentSessionConfig): Promise<AgentSession> {
const session = new StaleReplacementSession(config);
session.describePersistence = () => ({ provider, sessionId: "plugin-session" });
return session;
}
}
const replacement = new ResumeTrackingTestAgentClient(provider);
const manager = new AgentManager({
clients: { [provider]: new StaleReplacementClient() },
providerDefinitions: { [provider]: { enabled: true } },
registry: storage,
logger,
rescueTimeouts: { interruptSessionMs: 20 },
});
const created = await manager.createAgent({ provider, cwd: workdir }, undefined, {
workspaceId: undefined,
});
try {
const initial = manager.streamAgent(created.id, "initial");
void drainAsyncGenerator(initial);
await manager.waitForAgentRunStart(created.id);
manager.updateProviderRegistry({
providerDefinitions: { [provider]: { enabled: true } },
clients: { [provider]: replacement },
});
const dispatch = await startAgentRun(manager, created.id, "replacement", logger, {
replaceRunning: true,
});
expect(dispatch.disposition).toBe("turn_started");
await replacement.waitForRetryStart();
const result = await manager.waitForAgentEvent(created.id);
expect(result.status).toBe("idle");
expect(replacement.resumeOverrides).toHaveLength(1);
} finally {
await manager.closeAgent(created.id).catch(() => undefined);
await manager.flush().catch(() => undefined);
await storage.flush().catch(() => undefined);
rmSync(workdir, { recursive: true, force: true });
}
});
test("createAgent passes explicit model strings through to the provider", async () => {
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-test-"));
const storagePath = join(workdir, "agents");
@@ -77,7 +77,6 @@ import {
} from "./agent-run-state.js";
import { invokeRewindCapability, type RewindMode } from "./rewind/rewind.js";
import { isSystemInjectedEnvelope } from "./agent-prompt.js";
import { isStaleProviderSessionError } from "./stale-provider-session-error.js";
import { stripInternalPaseoMcpServer, withRuntimePaseoMcpServer } from "./runtime-mcp-config.js";
import { resolveCreateAgentTitles } from "./create-agent-title.js";
import type { PaseoToolCatalogFactory } from "./tools/types.js";
@@ -279,6 +278,7 @@ type ProviderEnabledMap = Partial<Record<AgentProvider, ProviderEnabledFlag>>;
type ProviderClientMap = Partial<Record<AgentProvider, AgentClient>>;
export interface CreateAgentOptions {
signal?: AbortSignal;
labels?: Record<string, string>;
initialPrompt?: string;
env?: Record<string, string>;
@@ -776,7 +776,6 @@ export class AgentManager {
updateProviderRegistry(input: {
providerDefinitions: ProviderEnabledMap;
clients: ProviderClientMap;
retiredProviders?: readonly AgentProvider[];
}): void {
this.providerEnabled.clear();
this.providerDefinitions.clear();
@@ -793,18 +792,6 @@ export class AgentManager {
this.clients.set(provider, client);
}
}
for (const provider of input.retiredProviders ?? []) {
for (const agent of this.agents.values()) {
if (agent.provider !== provider) continue;
void this.closeAgent(agent.id).catch((error) => {
this.logger.warn(
{ err: error, agentId: agent.id, provider },
"Failed to close agent after provider retirement",
);
});
}
}
}
getRegisteredProviderIds(): AgentProvider[] {
@@ -1241,8 +1228,16 @@ export class AgentManager {
);
const providerLaunchConfig = this.resolveProviderLaunchConfig(launchConfig, launchContext);
const createOptions = this.buildCreateSessionOptions(options);
const session = await client.createSession(providerLaunchConfig, launchContext, createOptions);
options.signal?.throwIfAborted();
const session = await this.waitForCreatedSession(
client.createSession(providerLaunchConfig, launchContext, createOptions),
options.signal,
);
await this.requireExternalMcpSupport(session, storedConfig);
if (options.signal?.aborted) {
await this.closeUnregisteredSession(session);
options.signal.throwIfAborted();
}
const agent = await this.registerSession(session, storedConfig, resolvedAgentId, {
labels: options.labels,
initialTitle: options.initialTitle,
@@ -1258,6 +1253,38 @@ export class AgentManager {
return agent;
}
private async waitForCreatedSession(
operation: Promise<AgentSession>,
signal?: AbortSignal,
): Promise<AgentSession> {
if (!signal) return operation;
return new Promise<AgentSession>((accept, reject) => {
const abort = () => {
signal.removeEventListener("abort", abort);
reject(signal.reason);
};
signal.addEventListener("abort", abort, { once: true });
if (signal.aborted) abort();
void operation
.then(
async (session) => {
signal.removeEventListener("abort", abort);
if (signal.aborted) {
await this.closeUnregisteredSession(session);
} else accept(session);
return;
},
(error: unknown) => {
signal.removeEventListener("abort", abort);
reject(error);
},
)
.catch((error: unknown) =>
this.logger.error({ err: error }, "Failed to close canceled provider creation"),
);
});
}
private buildCreateSessionOptions(options?: {
persistSession?: boolean;
}): AgentCreateSessionOptions | undefined {
@@ -2374,13 +2401,6 @@ export class AgentManager {
if (pendingRun.settled) {
throw error;
}
if (isStaleProviderSessionError(error)) {
pendingRun.start = { status: "failed", error: error.message };
agent.pendingReplacement = false;
if (!agent.activeForegroundTurnId) agent.lifecycle = "idle";
this.runs.settleForegroundRun(agentId, pendingRun.token);
throw error;
}
agent.pendingReplacement = false;
const errorMsg = error instanceof Error ? error.message : "Failed to start turn";
pendingRun.start = { status: "failed", error: errorMsg };
@@ -2906,9 +2926,6 @@ export class AgentManager {
response: AgentPermissionResponse,
): Promise<AgentPermissionResult | void> {
const agent = this.requireAgent(agentId);
if (agent.inFlightPermissionResponses.has(requestId)) {
throw new Error("A response to this permission request is already being submitted");
}
agent.inFlightPermissionResponses.add(requestId);
try {
@@ -3103,11 +3120,8 @@ export class AgentManager {
epoch: this.timelineStore.getEpoch(agentId),
});
}
// Rewind stages provider events under the run lock; publish its final state directly.
this.refreshSessionPersistence(agent);
await this.refreshSessionState(agent, { emit: false });
await this.refreshRuntimeInfo(agent);
await this.persistSnapshot(agent);
this.emitState(agent, { persist: false });
this.logger.info(
{ agentId, provider: agent.provider, messageId, mode },
"agent.rewind.complete",
@@ -4258,18 +4272,14 @@ export class AgentManager {
private onStreamThreadStarted(agent: ActiveManagedAgent): void {
const previousSessionId = agent.persistence?.sessionId ?? null;
this.refreshSessionPersistence(agent);
if (agent.persistence?.sessionId !== previousSessionId) {
this.emitState(agent);
}
void this.refreshRuntimeInfo(agent);
}
private refreshSessionPersistence(agent: ActiveManagedAgent): void {
const handle = agent.session.describePersistence();
if (handle) {
agent.persistence = attachPersistenceCwd(handle, agent.cwd);
if (agent.persistence?.sessionId !== previousSessionId) {
this.emitState(agent);
}
}
void this.refreshRuntimeInfo(agent);
}
private async onStreamTimelineEvent(params: {
@@ -4474,7 +4484,6 @@ export class AgentManager {
): void {
const hadPendingPermissions = agent.pendingPermissions.size > 0;
agent.pendingPermissions.set(event.request.id, event.request);
this.refreshSessionPersistence(agent);
if (!hadPendingPermissions && !agent.internal) {
this.broadcastAgentAttention(agent, "permission");
}
@@ -4489,7 +4498,6 @@ export class AgentManager {
}): void {
const { agent, event, options, flags } = params;
agent.pendingPermissions.delete(event.requestId);
this.refreshSessionPersistence(agent);
if (!options?.fromHistory && agent.inFlightPermissionResponses.has(event.requestId)) {
agent.bufferedPermissionResolutions.set(event.requestId, event);
flags.shouldDispatchEvent = false;
@@ -8,7 +8,6 @@ import type {
import type { AgentManager, ManagedAgent } from "./agent-manager.js";
import type { AgentStorage } from "./agent-storage.js";
import { ensureAgentLoaded } from "./agent-loading.js";
import { isStaleProviderSessionError } from "./stale-provider-session-error.js";
import { getParentAgentIdFromLabels } from "@getpaseo/protocol/agent-labels";
import type { ActiveTurnBehavior } from "@getpaseo/protocol/messages";
@@ -22,9 +21,7 @@ export type AgentRunController = Pick<
| "replaceAgentRun"
| "steerOrReplaceActiveTurn"
| "streamAgent"
> & {
reloadAgentSession(agentId: string): Promise<unknown>;
};
>;
export interface StartAgentRunOptions {
replaceRunning?: boolean;
@@ -81,14 +78,6 @@ async function startOrReplaceRun(
return { iterator, replaced };
}
async function drainAgentRunIterator(
iterator: AsyncGenerator<import("./agent-sdk-types.js").AgentStreamEvent>,
): Promise<void> {
for await (const _ of iterator) {
// Events are broadcast via AgentManager subscribers.
}
}
export async function startAgentRun(
agentManager: AgentRunController,
agentId: string,
@@ -115,26 +104,6 @@ export async function startAgentRun(
if (agentManager.tryRunOutOfBand(agentId, prompt, options?.runOptions)) {
return { disposition: "out_of_band" };
}
try {
return await startAgentRunInner(agentManager, agentId, prompt, logger, options);
} catch (error) {
if (!isStaleProviderSessionError(error)) throw error;
logger.info({ agentId, err: error }, "Provider session went stale; reopening from persistence");
// The live session belongs to a retired plugin runtime. Reload swaps in a
// fresh session on the current runtime while preserving history and labels.
await agentManager.reloadAgentSession(agentId);
return await startAgentRunInner(agentManager, agentId, prompt, logger, options);
}
}
async function startAgentRunInner(
agentManager: AgentRunController,
agentId: string,
prompt: AgentPromptInput,
logger: Logger,
options?: StartAgentRunOptions,
): Promise<{ disposition: PromptDispatchDisposition }> {
const snapshot = agentManager.getAgent(agentId);
const steered = await steerOrReplaceActiveRun(agentManager, agentId, prompt, options);
if (steered?.disposition === "steered") {
return steered;
@@ -153,17 +122,8 @@ async function startAgentRunInner(
);
void (async () => {
try {
try {
await drainAgentRunIterator(iterator);
} catch (error) {
if (!isStaleProviderSessionError(error)) throw error;
logger.info(
{ agentId, err: error },
"Provider session went stale; reopening from persistence",
);
await agentManager.reloadAgentSession(agentId);
const retry = await startOrReplaceRun(agentManager, agentId, prompt, options);
await drainAgentRunIterator(retry.iterator);
for await (const _ of iterator) {
// Events are broadcast via AgentManager subscribers.
}
logger.trace(
{
@@ -222,6 +182,7 @@ export function isSystemInjectedEnvelope(text: string): boolean {
}
export interface SendPromptToAgentParams {
signal?: AbortSignal;
agentManager: AgentManager;
agentStorage: AgentStorage;
agentId: string;
@@ -244,6 +205,7 @@ export interface SendPromptToAgentParams {
}
export interface StartCreatedAgentInitialPromptParams {
signal?: AbortSignal;
agentManager: AgentManager;
agentId: string;
snapshot?: ManagedAgent;
@@ -269,6 +231,7 @@ const AGENT_RUN_START_TIMEOUT_MS = 60_000;
export async function waitForAgentRunStartWithTimeout(
agentManager: AgentManager,
agentId: string,
signal?: AbortSignal,
): Promise<void> {
const provider = agentManager.getAgent(agentId)?.provider ?? "provider";
const startAbort = new AbortController();
@@ -283,7 +246,9 @@ export async function waitForAgentRunStartWithTimeout(
);
try {
await agentManager.waitForAgentRunStart(agentId, { signal: startAbort.signal });
await agentManager.waitForAgentRunStart(agentId, {
signal: signal ? AbortSignal.any([signal, startAbort.signal]) : startAbort.signal,
});
} finally {
clearTimeout(startTimeout);
}
@@ -303,6 +268,7 @@ export async function waitForAgentRunStartWithTimeout(
export async function sendPromptToAgent(
params: SendPromptToAgentParams,
): Promise<{ disposition: PromptDispatchDisposition }> {
params.signal?.throwIfAborted();
const unarchive = params.unarchive ?? true;
const record = await params.agentStorage.get(params.agentId);
@@ -323,6 +289,7 @@ export async function sendPromptToAgent(
await params.agentManager.setAgentMode(params.agentId, params.sessionMode);
}
params.signal?.throwIfAborted();
const runOptions = params.messageId
? { ...params.runOptions, clientMessageId: params.messageId }
: params.runOptions;
@@ -347,6 +314,7 @@ export async function startCreatedAgentInitialPrompt(
return currentSnapshot;
}
params.signal?.throwIfAborted();
const dispatchResult = await startAgentRun(
params.agentManager,
params.agentId,
@@ -358,7 +326,7 @@ export async function startCreatedAgentInitialPrompt(
);
if (dispatchResult.disposition === "turn_started") {
await waitForAgentRunStartWithTimeout(params.agentManager, params.agentId);
await waitForAgentRunStartWithTimeout(params.agentManager, params.agentId, params.signal);
}
const refreshedSnapshot = params.agentManager.getAgent(params.agentId) ?? params.snapshot ?? null;
@@ -55,6 +55,7 @@ export type EnsureWorkspaceForCreate = (
export interface CreateAgentFromSessionInput {
kind: "session";
signal?: AbortSignal;
agentId?: string;
config: AgentSessionConfig;
workspaceId: string;
@@ -79,6 +80,7 @@ export interface CreateAgentFromSessionInput {
export interface CreateAgentFromMcpInput {
kind: "mcp";
signal?: AbortSignal;
provider: string;
title: string;
initialPrompt?: string;
@@ -180,10 +182,12 @@ export async function createAgentCommand(
? await resolveSessionCreateAgent(dependencies, input)
: await resolveMcpCreateAgent(dependencies, input);
const signal = input.signal;
signal?.throwIfAborted();
const snapshot = await dependencies.agentManager.createAgent(
resolved.config,
input.kind === "session" ? input.agentId : undefined,
resolved.createOptions,
{ ...resolved.createOptions, signal },
);
resolved.setupContinuation?.startAfterAgentCreate({
@@ -197,7 +201,7 @@ export async function createAgentCommand(
input.onCreated?.({ agentId: snapshot.id, createdWorktree: resolved.createdWorktree ?? null });
}
if (resolved.prompt !== undefined) {
const sendResult = await sendInitialPrompt(dependencies, resolved, snapshot);
const sendResult = await sendInitialPrompt(dependencies, resolved, snapshot, signal);
initialPromptStarted = sendResult.started;
liveSnapshot = sendResult.liveSnapshot;
initialPromptError = sendResult.error ?? null;
@@ -449,6 +453,7 @@ async function sendInitialPrompt(
dependencies: CreateAgentCommandDependencies,
resolved: ResolvedCreateAgent,
snapshot: ManagedAgent,
signal?: AbortSignal,
): Promise<{ started: boolean; liveSnapshot: ManagedAgent; error?: unknown }> {
try {
const prompt = resolved.prompt;
@@ -458,6 +463,7 @@ async function sendInitialPrompt(
const liveSnapshot = await startCreatedAgentInitialPrompt({
agentManager: dependencies.agentManager,
agentId: snapshot.id,
signal,
snapshot,
prompt,
runOptions: resolved.runOptions,
@@ -8,10 +8,6 @@ import { describe, expect, test } from "vitest";
import { createTestLogger } from "../../test-utils/test-logger.js";
import type { AgentStreamEvent } from "./agent-sdk-types.js";
import { PluginAgentClientRegistry } from "./plugin-provider.js";
import {
isStaleProviderSessionError,
StaleProviderSessionError,
} from "./stale-provider-session-error.js";
const CAPABILITIES = [
"prompt.message",
@@ -29,10 +25,6 @@ interface ProviderHarnessOptions {
function createProviderHarness(options: ProviderHarnessOptions = {}) {
let listener: ((event: ProviderEvent) => void) | null = null;
let closeCount = 0;
let resolveClosed!: () => void;
const closed = new Promise<void>((resolve) => {
resolveClosed = resolve;
});
const inputs: ProviderInput[] = [];
const emit = (event: ProviderEvent) => listener?.(event);
const capabilities = options.capabilities ?? CAPABILITIES;
@@ -188,7 +180,6 @@ function createProviderHarness(options: ProviderHarnessOptions = {}) {
},
async close() {
closeCount += 1;
resolveClosed();
},
};
@@ -200,12 +191,7 @@ function createProviderHarness(options: ProviderHarnessOptions = {}) {
},
};
return {
registration,
inputs,
closeCount: () => closeCount,
waitForClose: () => closed,
};
return { registration, inputs, closeCount: () => closeCount };
}
function eventsOfType(events: AgentStreamEvent[], type: AgentStreamEvent["type"]) {
@@ -272,84 +258,6 @@ describe("PluginAgentClientRegistry", () => {
expect(eventsOfType(events, "turn_failed")).toHaveLength(1);
});
test("closes a stale session after its plugin provider is replaced", async () => {
const old = createProviderHarness();
const next = createProviderHarness();
const registry = new PluginAgentClientRegistry(createTestLogger());
try {
registry.replace([old.registration]);
const stale = await registry.clients()[old.registration.id]!.createSession({
provider: old.registration.id,
cwd: "/workspace",
});
const persistence = stale.describePersistence();
expect(persistence).not.toBeNull();
registry.replace([next.registration]);
await old.waitForClose();
expect(old.closeCount()).toBe(1);
await expect(stale.close()).resolves.toBeUndefined();
const replacement = registry.clients()[next.registration.id];
expect(replacement).toBeDefined();
const resumed = await replacement!.resumeSession(persistence!, {
cwd: "/workspace",
});
await expect(
resumed.startTurn("after reload", { clientMessageId: "after-reload" }),
).resolves.toEqual({ turnId: "turn-1" });
expect(next.inputs).toContainEqual(
expect.objectContaining({
type: "session.open",
history: "replay",
persistence: {
version: 1,
data: { token: "root" },
},
}),
);
await resumed.close();
} finally {
await registry.shutdown();
}
});
test("prompting a stale session raises StaleProviderSessionError", async () => {
const old = createProviderHarness();
const registry = new PluginAgentClientRegistry(createTestLogger());
try {
registry.replace([old.registration]);
const stale = await registry.clients()[old.registration.id]!.createSession({
provider: old.registration.id,
cwd: "/workspace",
});
registry.replace([]);
await old.waitForClose();
expect(old.closeCount()).toBe(1);
const failure = await stale
.startTurn("after reload", { clientMessageId: "after-reload" })
.then(
() => null,
(error: unknown) => error,
);
expect(failure).toBeInstanceOf(StaleProviderSessionError);
expect(isStaleProviderSessionError(failure)).toBe(true);
expect(isStaleProviderSessionError(new Error("Provider connection is closed"))).toBe(false);
expect(isStaleProviderSessionError(new Error("boom"))).toBe(false);
} finally {
await registry.shutdown();
}
});
test("adapts callback providers into the existing AgentClient and AgentSession path", async () => {
const harness = createProviderHarness();
const registry = new PluginAgentClientRegistry(createTestLogger());
@@ -58,7 +58,6 @@ import {
} from "./create-agent-mode.js";
import type { ProviderDefinition } from "./provider-registry.js";
import { runProviderTurn } from "./providers/provider-runner.js";
import { StaleProviderSessionError } from "./stale-provider-session-error.js";
interface Deferred<Value> {
promise: Promise<Value>;
@@ -131,10 +130,6 @@ class ProviderRuntime {
return this.connection?.capabilities ?? [];
}
get isClosed(): boolean {
return this.closed;
}
async isAvailable(): Promise<boolean> {
await this.getConnection();
return true;
@@ -564,7 +559,6 @@ class ProviderRuntimeSession {
sessionId: this.providerSessionId,
prompt,
});
if (this.terminal) throw new StaleProviderSessionError(this.id);
const pending = deferred<Extract<ProviderEvent, { type: "session.prompt_result" }>>();
this.prompts.set(prompt.clientMessageId, pending);
try {
@@ -574,9 +568,6 @@ class ProviderRuntimeSession {
prompt,
});
return (await pending.promise).result;
} catch (error) {
if (this.terminal || this.runtime.isClosed) throw new StaleProviderSessionError(this.id);
throw error;
} finally {
this.prompts.delete(prompt.clientMessageId);
}
@@ -632,8 +623,6 @@ class ProviderRuntimeSession {
requestId: randomUUID(),
sessionId: this.providerSessionId,
});
} catch (error) {
if (!this.runtime.isClosed) throw error;
} finally {
this.runtime.removeSession(this.id, this.providerSessionId);
}
@@ -2281,7 +2281,6 @@ describe("ProviderSnapshotManager cwd routing", () => {
const withoutPlugin = manager.replacePluginProviders([]);
expect(manager.hasProvider(registration.id)).toBe(false);
expect(withoutPlugin.clients[registration.id]).toBeUndefined();
expect(withoutPlugin.retiredProviders).toEqual([registration.id]);
} finally {
await manager.shutdown();
manager.destroy();
@@ -191,7 +191,6 @@ export interface AgentManagerProviderState {
>
>;
clients: Partial<Record<AgentProvider, AgentClient>>;
retiredProviders?: readonly AgentProvider[];
}
interface ProviderLoadOptions {
@@ -403,9 +402,6 @@ export class ProviderSnapshotManager {
this.createAgentManagerState(this.generation.definitions, clients);
this.pluginProviders.replace(registrations);
const plugins = this.pluginProviders.definitions();
const retiredProviders = Object.keys(previousPlugins).filter(
(provider) => previousPlugins[provider] !== plugins[provider],
);
const definitions = { ...this.generation.definitions };
const changed = new Set<AgentProvider>();
for (const provider of new Set([...Object.keys(previousPlugins), ...Object.keys(plugins)])) {
@@ -419,7 +415,7 @@ export class ProviderSnapshotManager {
const generation = this.createGeneration(definitions, this.providerOverrides);
const state = this.createAgentManagerState(definitions, clients);
this.installGeneration(generation, clients, changed);
return { ...state, retiredProviders };
return state;
}
private ensureClient(
@@ -24,12 +24,6 @@ interface TestClaudeSession {
close(): Promise<void>;
}
function isLoadingCompactionEvent(event: AgentStreamEvent): boolean {
return (
event.type === "timeline" && event.item.type === "compaction" && event.item.status === "loading"
);
}
function isPermissionResolvedEvent(
event: AgentStreamEvent,
): event is Extract<AgentStreamEvent, { type: "permission_resolved" }> {
@@ -1987,15 +1981,6 @@ describe("ClaudeAgentSession context window usage", () => {
};
}
function createCompactingStatus(): Record<string, unknown> {
return {
type: "system",
subtype: "status",
status: "compacting",
session_id: "session-1",
};
}
test("emits turn_started before the submitted user message", async () => {
const session = await createSessionForTurns([[]]);
const events: AgentStreamEvent[] = [];
@@ -2872,110 +2857,6 @@ describe("ClaudeAgentSession context window usage", () => {
}
});
test("repeated compacting statuses open a single compaction marker", async () => {
const session = await createSessionForTurns([
[
createCompactingStatus(),
createCompactingStatus(),
createCompactingStatus(),
createCompactBoundary(),
createCompactingStatus(),
createCompactingStatus(),
createCompactBoundary(),
createSuccessResult(),
],
]);
try {
const events = await collectStreamEvents(session, "compact twice");
const compactions = events.flatMap((event) =>
event.type === "timeline" && event.item.type === "compaction" ? [event.item.status] : [],
);
expect(compactions).toEqual(["loading", "completed", "loading", "completed"]);
} finally {
await session.close();
}
});
test("a compaction abandoned mid-turn does not suppress the next compaction marker", async () => {
// The first turn starts compacting and then ends without ever reaching a
// compact_boundary, so the marker it opened is never resolved.
const session = await createSessionForTurns([
[createCompactingStatus(), createSuccessResult()],
[createCompactingStatus(), createSuccessResult()],
]);
try {
const abandonedTurn = await collectStreamEvents(session, "abandoned compaction");
expect(abandonedTurn.filter(isLoadingCompactionEvent)).toHaveLength(1);
const nextTurn = await collectStreamEvents(session, "next compaction");
expect(nextTurn.filter(isLoadingCompactionEvent)).toHaveLength(1);
} finally {
await session.close();
}
});
test("an interrupted compaction does not suppress the next compaction marker", async () => {
// The first turn starts compacting and is then interrupted, so it never reaches a
// compact_boundary and the marker it opened is never resolved.
const session = await createSessionForTurns([
[createCompactingStatus()],
[createCompactingStatus(), createSuccessResult()],
]);
try {
const interruptedTurn: AgentStreamEvent[] = [];
const streaming = (async () => {
for await (const event of streamSession(session, "interrupted compaction")) {
interruptedTurn.push(event);
}
})();
await vi.waitFor(() => {
expect(interruptedTurn.filter(isLoadingCompactionEvent)).toHaveLength(1);
});
await session.interrupt();
await streaming;
expect(interruptedTurn).toContainEqual(
expect.objectContaining({ type: "turn_canceled", provider: "claude" }),
);
const nextTurn = await collectStreamEvents(session, "next compaction");
expect(nextTurn.filter(isLoadingCompactionEvent)).toHaveLength(1);
} finally {
await session.close();
}
});
test("a compaction abandoned in an autonomous turn does not suppress the next marker", async () => {
// Trailing output after the foreground result opens an autonomous turn, which starts
// compacting and is then ended by the next foreground turn, never reaching a boundary.
const session = await createSessionForTurns([
[createSuccessResult(), createMessageStartEvent(), createCompactingStatus()],
[createCompactingStatus(), createSuccessResult()],
]);
try {
const observed: AgentStreamEvent[] = [];
const unsubscribe = session.subscribe((event) => {
observed.push(event);
});
await collectStreamEvents(session, "foreground turn");
await vi.waitFor(() => {
expect(observed.filter(isLoadingCompactionEvent)).toHaveLength(1);
});
unsubscribe();
const nextTurn = await collectStreamEvents(session, "next compaction");
expect(nextTurn.filter(isLoadingCompactionEvent)).toHaveLength(1);
} finally {
await session.close();
}
});
test("result.result is surfaced as an assistant message when no model output was produced", async () => {
const session = await createSessionForTest();
@@ -2095,7 +2095,6 @@ class ClaudeAgentSession implements AgentSession {
private lastOptionsModel: string | null = null;
private lastRuntimeModel: string | null = null;
private compacting = false;
private compactionMarkerOpen = false;
private queryPumpPromise: Promise<void> | null = null;
private queryRestartNeeded = false;
private pendingInterruptAbort = false;
@@ -3573,7 +3572,6 @@ class ClaudeAgentSession implements AgentSession {
this.activeForegroundInput = null;
this.cancelCurrentTurn = null;
this.activeTurnHasAssistantText = false;
this.compactionMarkerOpen = false;
this.syncTurnState("foreground turn terminal");
}
@@ -3585,7 +3583,6 @@ class ClaudeAgentSession implements AgentSession {
}
if (terminalSeen) {
this.compactionMarkerOpen = false;
if (this.activeForegroundTurnId) {
this.activeForegroundTurnId = null;
this.activeForegroundQuery = null;
@@ -3627,7 +3624,6 @@ class ClaudeAgentSession implements AgentSession {
this.activeForegroundQuery = null;
this.activeForegroundInput = null;
this.activeTurnHasAssistantText = false;
this.compactionMarkerOpen = false;
this.syncTurnState("autonomous turn completed");
}
@@ -4264,22 +4260,15 @@ class ClaudeAgentSession implements AgentSession {
const status = toObjectRecord(message)?.status;
if (status === "compacting") {
this.compacting = true;
// Claude Code repeats this status every 30 seconds until the compaction
// finishes. Each repeat used to open its own marker, and the app only ever
// resolves one of them, so the rest stayed on "Compacting..." forever.
if (!this.compactionMarkerOpen) {
this.compactionMarkerOpen = true;
events.push({
type: "timeline",
item: { type: "compaction", status: "loading" },
provider: "claude",
});
}
events.push({
type: "timeline",
item: { type: "compaction", status: "loading" },
provider: "claude",
});
}
return;
}
if (message.subtype === "compact_boundary") {
this.compactionMarkerOpen = false;
const compactMetadata = readCompactionMetadata(message);
events.push({
type: "timeline",
@@ -97,88 +97,6 @@ async function createConnectedSession(
}
describe("Codex app-server provider features", () => {
test.each([
"gpt-6-astra",
"gpt-5.6",
"gpt-5.6-sol",
"gpt-5.6-terra",
"gpt-5.6-luna",
"gpt-5.5",
"gpt-5.4",
])("exposes and sends Fast for %s", async (model) => {
const { session, appServer } = await createConnectedSession({ model });
try {
expect(session.features).toContainEqual(
expect.objectContaining({
id: "fast_mode",
value: false,
}),
);
await session.setFeature?.("fast_mode", true);
await session.startTurn("hello");
await expect(appServer.waitForTurnStart()).resolves.toMatchObject({
model,
serviceTier: "fast",
});
} finally {
await session.close();
}
});
test.each([
"gpt-5.3-codex-spark",
"gpt-5.3-codex",
"gpt-5.4-mini",
"gpt-5.4-nano",
"gpt-5.5-pro",
"gpt-5",
"gpt-4.1",
"o3",
"o4-mini",
"gpt-6-unknown",
])("does not expose or restore Fast for %s", async (model) => {
const { session, appServer } = await createConnectedSession({
model,
featureValues: { fast_mode: true },
});
try {
expect(session.features.map((feature) => feature.id)).toEqual(["plan_mode"]);
await expect(session.setFeature?.("fast_mode", true)).rejects.toThrow(
`Codex fast mode is not available for model '${model}'`,
);
await session.startTurn("hello");
await expect(appServer.waitForTurnStart()).resolves.not.toMatchObject({
serviceTier: expect.anything(),
});
} finally {
await session.close();
}
});
test("restores Fast on Astra and preserves it when switching supported models", async () => {
const { session, appServer } = await createConnectedSession({
model: "gpt-6-astra",
featureValues: { fast_mode: true },
});
try {
expect(session.features).toContainEqual(
expect.objectContaining({
id: "fast_mode",
value: true,
}),
);
await session.setModel("gpt-5.6-sol");
await session.setModel("gpt-6-astra");
await session.startTurn("hello");
await expect(appServer.waitForTurnStart()).resolves.toMatchObject({
model: "gpt-6-astra",
serviceTier: "fast",
});
} finally {
await session.close();
}
});
test("features returns fast and plan toggles when supported", async () => {
const { session } = await createConnectedSession();
@@ -187,7 +105,7 @@ describe("Codex app-server provider features", () => {
type: "toggle",
id: "fast_mode",
label: "Fast",
description: "Priority inference at increased usage",
description: "Priority inference at 2x usage",
tooltip: "Toggle fast mode",
icon: "zap",
value: false,
@@ -211,7 +129,7 @@ describe("Codex app-server provider features", () => {
type: "toggle",
id: "fast_mode",
label: "Fast",
description: "Priority inference at increased usage",
description: "Priority inference at 2x usage",
tooltip: "Toggle fast mode",
icon: "zap",
value: true,
@@ -332,7 +250,7 @@ describe("Codex app-server provider features", () => {
type: "toggle",
id: "fast_mode",
label: "Fast",
description: "Priority inference at increased usage",
description: "Priority inference at 2x usage",
tooltip: "Toggle fast mode",
icon: "zap",
value: true,
@@ -52,7 +52,6 @@ import { z } from "zod";
import { renderPromptAttachmentAsText } from "../prompt-attachments.js";
import { composeSystemPromptParts } from "../system-prompt.js";
import { curateAgentActivity } from "../activity-curator.js";
import { CodexAsyncQuestions, codexAsyncQuestionToTimeline } from "./codex/async-questions.js";
import {
mapCodexToolCallEnvelope,
mapCodexToolCallFromThreadItem,
@@ -1846,17 +1845,6 @@ function mapCodexThreadImageItem(
);
}
function mapCodexAgentMessage(item: Record<string, unknown>): AgentTimelineItem {
const question = codexAsyncQuestionToTimeline(item);
if (question) return question;
const messageId = nonEmptyString(item.id);
return {
type: "assistant_message",
text: typeof item.text === "string" ? item.text : "",
...(messageId ? { messageId } : {}),
};
}
export function threadItemToTimeline(
item: unknown,
options?: { includeUserMessage?: boolean; cwd?: string | null },
@@ -1883,8 +1871,14 @@ export function threadItemToTimeline(
switch (normalizedType) {
case "userMessage":
return mapCodexThreadUserMessageItem(normalizedItem, includeUserMessage);
case "agentMessage":
return mapCodexAgentMessage(normalizedItem);
case "agentMessage": {
const messageId = nonEmptyString(normalizedItem.id);
return {
type: "assistant_message",
text: typeof normalizedItem.text === "string" ? normalizedItem.text : "",
...(messageId ? { messageId } : {}),
};
}
case "plan":
return mapCodexThreadPlanItem(normalizedItem);
case "reasoning":
@@ -3299,7 +3293,6 @@ export class CodexAppServerAgentSession implements AgentSession {
private readonly logger: Logger;
private readonly config: AgentSessionConfig;
private readonly asyncQuestions: CodexAsyncQuestions;
private currentMode: string;
private hasWorkflowModeOverride: boolean;
private readonly providerOptions: CodexProviderOptions;
@@ -3412,7 +3405,6 @@ export class CodexAppServerAgentSession implements AgentSession {
this.currentMode = config.modeId ?? DEFAULT_CODEX_MODE_ID;
this.providerOptions = CodexProviderOptionsSchema.parse(config.providerOptions ?? {});
this.config = config;
this.asyncQuestions = new CodexAsyncQuestions(resumeHandle?.metadata?.asyncQuestions);
this.config.thinkingOptionId = normalizeCodexThinkingOptionId(this.config.thinkingOptionId);
if (this.config.featureValues?.fast_mode && codexModelSupportsFastMode(this.config.model)) {
this.serviceTier = "fast";
@@ -3807,9 +3799,6 @@ export class CodexAppServerAgentSession implements AgentSession {
}
this.resetCodexUserMessageTurns();
for (const entry of timeline) {
if (entry.item.type === "tool_call" && entry.item.name === "request_user_input_async") {
entry.item = this.asyncQuestions.timeline(entry.item.callId) ?? entry.item;
}
if (entry.item.type === "user_message") {
this.rememberCodexUserMessageTurn(entry.item.messageId, entry.providerTurnId);
}
@@ -4475,16 +4464,13 @@ export class CodexAppServerAgentSession implements AgentSession {
}
getPendingPermissions(): AgentPermissionRequest[] {
return [...this.pendingPermissions.values(), ...this.asyncQuestions.pending()];
return Array.from(this.pendingPermissions.values());
}
async respondToPermission(
requestId: string,
response: AgentPermissionResponse,
): Promise<AgentPermissionResult | void> {
if (this.asyncQuestions.hasPending(requestId)) {
return this.respondToAsyncQuestion(requestId, response);
}
const pending = this.pendingPermissionHandlers.get(requestId);
if (!pending) {
throw new Error(`No pending Codex app-server permission request with id '${requestId}'`);
@@ -4578,33 +4564,6 @@ export class CodexAppServerAgentSession implements AgentSession {
pending.resolve({ answers: {} });
}
private async respondToAsyncQuestion(
requestId: string,
response: AgentPermissionResponse,
): Promise<AgentPermissionResult | void> {
const prepared = this.asyncQuestions.prepareResponse(requestId, response);
let followUpPrompt = prepared.prompt;
const expectedTurnId = this.activeForegroundTurnId;
if (prepared.prompt && expectedTurnId) {
const result = await this.steerActiveTurn(prepared.prompt, {
expectedTurnId,
clientMessageId: randomUUID(),
});
if (result.status !== "accepted") {
throw new Error("The active Codex turn changed. Retry sending your answer.");
}
followUpPrompt = undefined;
}
this.emitEvent({ type: "timeline", provider: CODEX_PROVIDER, item: prepared.complete() });
this.emitEvent({
type: "permission_resolved",
provider: CODEX_PROVIDER,
requestId,
resolution: response,
});
return followUpPrompt ? { followUpPrompt } : undefined;
}
private handlePlanPermissionResponse(params: {
requestId: string;
response: AgentPermissionResponse;
@@ -4741,7 +4700,6 @@ export class CodexAppServerAgentSession implements AgentSession {
toolPolicy: this.config.toolPolicy,
systemPrompt: this.config.systemPrompt,
mcpServers: this.config.mcpServers,
asyncQuestions: this.asyncQuestions.serialize(),
},
};
}
@@ -4771,7 +4729,6 @@ export class CodexAppServerAgentSession implements AgentSession {
this.persistedHistory = [];
this.historyPending = false;
await this.loadPersistedHistory();
this.reconcileAsyncQuestionsAfterRewind();
},
});
}
@@ -5946,7 +5903,6 @@ export class CodexAppServerAgentSession implements AgentSession {
error: parsed.errorMessage ?? "Codex turn failed",
});
} else if (parsed.status === "interrupted") {
this.dismissInterruptedAsyncQuestions();
this.emitEvent({ type: "turn_canceled", provider: CODEX_PROVIDER, reason: "interrupted" });
} else {
if (this.planModeEnabled && this.latestPlanResult?.text) {
@@ -6299,43 +6255,6 @@ export class CodexAppServerAgentSession implements AgentSession {
}
}
private receiveAsyncQuestion(threadId: string | null, item: unknown): void {
if (threadId !== this.currentThreadId) return;
const request = this.asyncQuestions.receive(item);
if (request)
this.emitEvent({ type: "permission_requested", provider: CODEX_PROVIDER, request });
}
private dismissInterruptedAsyncQuestions(): void {
const resolution: AgentPermissionResponse = { behavior: "deny", message: "Interrupted" };
for (const request of this.asyncQuestions.pending()) {
const prepared = this.asyncQuestions.prepareResponse(request.id, resolution);
this.emitEvent({ type: "timeline", provider: CODEX_PROVIDER, item: prepared.complete() });
this.emitEvent({
type: "permission_resolved",
provider: CODEX_PROVIDER,
requestId: request.id,
resolution,
});
}
}
private reconcileAsyncQuestionsAfterRewind(): void {
const retainedIds = new Set(
this.persistedHistory.flatMap(({ item }) =>
item.type === "tool_call" && item.name === "request_user_input_async" ? [item.callId] : [],
),
);
for (const requestId of this.asyncQuestions.retain(retainedIds)) {
this.emitEvent({
type: "permission_resolved",
provider: CODEX_PROVIDER,
requestId,
resolution: { behavior: "deny", message: "Removed by rewind" },
});
}
}
private handleItemCompletedNotification(
parsed: Extract<ParsedCodexNotification, { kind: "item_completed" }>,
): void {
@@ -6346,7 +6265,6 @@ export class CodexAppServerAgentSession implements AgentSession {
if (shouldIgnoreMirroredLifecycleItem(parsed.source, parsed.item)) {
return;
}
this.receiveAsyncQuestion(parsed.threadId, parsed.item);
if (this.isUserMessageItem(parsed.item)) {
this.handleUserMessageItem(parsed);
return;
@@ -1,436 +0,0 @@
import { tmpdir } from "node:os";
import { expect, test } from "vitest";
import { CodexAppServerAgentSession } from "./codex-app-server-agent.js";
import {
createFakeCodexAppServer,
waitForNextEvent,
waitForTimelineToolCall,
} from "./codex/test-utils/fake-app-server.js";
import { createTestLogger } from "../../../test-utils/test-logger.js";
import type { AgentStreamEvent } from "../agent-sdk-types.js";
import { AgentManager } from "../agent-manager.js";
const questionItem = {
type: "agentMessage",
id: "async-question-1",
text: "Which color?\n- Blue\n- Green",
phase: "final_answer",
delivery: "async",
questions: [{ title: "Which color?", options: ["Blue", "Green"] }],
};
async function setup(metadata?: Record<string, unknown>, rejectSteer = false) {
const appServer = createFakeCodexAppServer({
"turn/interrupt": () => ({}),
"turn/steer": () => {
if (rejectSteer) return { __jsonRpcError: { code: -32000, message: "Delivery failed" } };
return { turnId: "native-turn" };
},
"thread/read": () => ({ thread: { id: "thread-1", turns: [] } }),
});
const session = new CodexAppServerAgentSession(
{ provider: "codex", cwd: tmpdir(), model: "gpt-5.4", modeId: "full-access" },
metadata ? { sessionId: "thread-1", metadata } : null,
createTestLogger(),
async () => appServer.child,
);
const events: AgentStreamEvent[] = [];
session.subscribe((event) => events.push(event));
await session.startTurn("Help me choose a color while you inspect the project.");
const started = waitForNextEvent(session, "turn_started");
appServer.startsTurn({ threadId: "thread-1", turnId: "native-turn" });
await started;
async function ask() {
const shown = waitForTimelineToolCall(session, questionItem.id);
appServer.child.stdout.write(
JSON.stringify({
method: "item/completed",
params: { threadId: "thread-1", turnId: "native-turn", item: questionItem },
}) + "\n",
);
await shown;
}
async function say(text: string) {
const shown = waitForNextEvent(
session,
"timeline",
(event) => event.item.type === "assistant_message" && event.item.text.includes(text),
);
appServer.says({ threadId: "thread-1", text });
await shown;
}
async function finish(status: "completed" | "interrupted" = "completed") {
const finished = waitForNextEvent(
session,
status === "completed" ? "turn_completed" : "turn_canceled",
);
appServer.completeTurn({ status });
await finished;
}
function allowAnswers() {
rejectSteer = false;
}
return { session, appServer, events, ask, say, finish, allowAnswers };
}
const answer = { behavior: "allow" as const, updatedInput: { answers: { "Question 1": "Green" } } };
async function setupRewind(fail = false) {
const records = [
{ item: { ...questionItem, id: "earlier-pending" } },
{ item: { ...questionItem, id: "earlier-answered" }, resolution: ["Blue"] },
{ item: { ...questionItem, id: "removed-pending" } },
{ item: { ...questionItem, id: "removed-answered" }, resolution: ["Green"] },
];
function userMessage(id: string) {
return { type: "userMessage", id, content: [{ type: "text", text: id }] };
}
const turns = [
{
id: "earlier-turn",
items: [userMessage("earlier"), ...records.slice(0, 2).map((r) => r.item)],
},
{
id: "removed-turn",
items: [userMessage("rewind-here"), ...records.slice(2).map((r) => r.item)],
},
];
const appServer = createFakeCodexAppServer({
"thread/read": (params) => {
const { threadId } = params as { threadId: string };
return {
thread: { id: threadId, turns: threadId === "thread-1" ? turns : turns.slice(0, 1) },
};
},
...(fail
? {
"thread/rollback": () => ({ __jsonRpcError: { code: -32000, message: "Rewind failed" } }),
}
: {}),
});
const session = new CodexAppServerAgentSession(
{ provider: "codex", cwd: tmpdir(), model: "gpt-5.4", modeId: "full-access" },
{ sessionId: "thread-1", metadata: { asyncQuestions: records } },
createTestLogger(),
async () => appServer.child,
);
const events: AgentStreamEvent[] = [];
session.subscribe((event) => events.push(event));
await session.connect();
return { session, events, records };
}
test("rewind removes only questions outside the remaining history, including after resume", async () => {
const { session, events, records } = await setupRewind();
let metadata: Record<string, unknown> | undefined;
try {
await session.revertConversation({ messageId: "rewind-here" });
expect(session.getPendingPermissions().map((p) => p.id)).toEqual([
"permission-earlier-pending",
]);
metadata = session.describePersistence()!.metadata;
expect(metadata.asyncQuestions).toEqual(
records.slice(0, 2).map((record) => ({
resolution: record.resolution,
item: {
type: "agentMessage",
id: record.item.id,
delivery: "async",
questions: questionItem.questions,
},
})),
);
expect(events.filter((e) => e.type === "permission_resolved")).toEqual([
expect.objectContaining({ requestId: "permission-removed-pending" }),
]);
const history = [];
for await (const event of session.streamHistory()) history.push(event);
expect(
history.some(
(e) =>
e.type === "timeline" &&
e.item.type === "tool_call" &&
e.item.callId === "removed-pending",
),
).toBe(false);
} finally {
await session.close();
}
const resumed = await setup(metadata);
try {
expect(resumed.session.getPendingPermissions().map((p) => p.id)).toEqual([
"permission-earlier-pending",
]);
} finally {
await resumed.session.close();
}
});
test("failed rewind preserves question state", async () => {
const { session, events } = await setupRewind(true);
try {
const before = session.describePersistence();
await expect(session.revertConversation({ messageId: "rewind-here" })).rejects.toThrow(
"Rewind failed",
);
expect(session.describePersistence()).toEqual(before);
expect(session.getPendingPermissions().map((p) => p.id)).toEqual([
"permission-earlier-pending",
"permission-removed-pending",
]);
expect(events.some((e) => e.type === "permission_resolved")).toBe(false);
} finally {
await session.close();
}
});
async function manage(session: CodexAppServerAgentSession) {
const manager = new AgentManager({
clients: {
codex: {
provider: "codex",
capabilities: session.capabilities,
createSession: async () => session,
resumeSession: async () => session,
isAvailable: async () => true,
fetchCatalog: async () => ({ models: [], modes: [] }),
},
},
logger: createTestLogger(),
});
const agent = await manager.createAgent(
{ provider: "codex", cwd: tmpdir(), model: "gpt-5.4" },
undefined,
{ workspaceId: undefined },
);
return { manager, agent };
}
test("manager publishes and saves the provider state after rewind", async () => {
const { session } = await setupRewind();
const { manager, agent } = await manage(session);
try {
await manager.rewind(agent.id, "rewind-here", "conversation");
const snapshot = manager.getAgent(agent.id)!;
expect(Array.from(snapshot.pendingPermissions.keys())).toEqual(["permission-earlier-pending"]);
expect(snapshot.persistence).toEqual(session.describePersistence());
expect(snapshot.persistence?.sessionId).toBe("forked-thread");
} finally {
await manager.closeAgent(agent.id);
}
});
test("manager snapshots capture pending and answered question state before the turn ends", async () => {
const { session, ask } = await setup();
const { manager, agent } = await manage(session);
try {
await ask();
const [permission] = session.getPendingPermissions();
expect(manager.getAgent(agent.id)?.persistence?.metadata?.asyncQuestions).toEqual([
{
item: {
type: "agentMessage",
id: questionItem.id,
delivery: "async",
questions: questionItem.questions,
},
},
]);
await manager.respondToPermission(agent.id, permission.id, answer);
expect(manager.getAgent(agent.id)?.persistence?.metadata?.asyncQuestions).toEqual([
{
item: {
type: "agentMessage",
id: questionItem.id,
delivery: "async",
questions: questionItem.questions,
},
resolution: ["Green"],
},
]);
} finally {
await manager.closeAgent(agent.id);
}
});
test("concurrent answers deliver only one response to the active Codex turn", async () => {
const { session, appServer, ask } = await setup();
const { manager, agent } = await manage(session);
try {
await ask();
const [permission] = session.getPendingPermissions();
const results = await Promise.allSettled([
manager.respondToPermission(agent.id, permission.id, answer),
manager.respondToPermission(agent.id, permission.id, answer),
]);
expect(results.map((result) => result.status)).toEqual(["fulfilled", "rejected"]);
expect(appServer.requests().filter((request) => request.method === "turn/steer")).toHaveLength(
1,
);
expect(session.getPendingPermissions()).toEqual([]);
} finally {
await manager.closeAgent(agent.id);
}
});
test("a failed submission releases the request so the user can retry", async () => {
const { session, ask, allowAnswers } = await setup(undefined, true);
const { manager, agent } = await manage(session);
try {
await ask();
const [permission] = session.getPendingPermissions();
await expect(manager.respondToPermission(agent.id, permission.id, answer)).rejects.toThrow(
"Delivery failed",
);
expect(session.getPendingPermissions().map((request) => request.id)).toEqual([permission.id]);
allowAnswers();
await manager.respondToPermission(agent.id, permission.id, answer);
expect(session.getPendingPermissions()).toEqual([]);
} finally {
await manager.closeAgent(agent.id);
}
});
test("shows an async question, keeps streaming, and delivers its answer without interrupting", async () => {
const { session, appServer, events, ask, say } = await setup();
try {
await ask();
const [permission] = session.getPendingPermissions();
expect(permission).toMatchObject({
kind: "question",
input: {
questions: [
{
header: "Question 1",
question: "Which color?",
isOther: true,
options: [{ label: "Blue" }, { label: "Green" }],
},
],
},
});
await say("I am still inspecting the project.");
expect(
events.some(
(event) =>
event.type === "timeline" &&
event.item.type === "assistant_message" &&
event.item.text.includes("still inspecting"),
),
).toBe(true);
await session.respondToPermission(permission.id, answer);
expect(session.getPendingPermissions()).toEqual([]);
expect(appServer.requests().filter((request) => request.method === "turn/steer")).toMatchObject(
[
{
params: {
expectedTurnId: "native-turn",
clientUserMessageId: expect.any(String),
input: [{ type: "text", text: expect.stringContaining("Which color?\nGreen") }],
},
},
],
);
expect(appServer.requests().filter((request) => request.method === "turn/interrupt")).toEqual(
[],
);
expect(
events.some(
(event) => event.type === "permission_resolved" && event.requestId === permission.id,
),
).toBe(true);
} finally {
await session.close();
}
});
test("keeps a failed answer pending for retry", async () => {
const { session, ask } = await setup(undefined, true);
try {
await ask();
const [permission] = session.getPendingPermissions();
expect(permission).toBeDefined();
await expect(session.respondToPermission(permission.id, answer)).rejects.toThrow();
expect(session.getPendingPermissions()).toHaveLength(1);
} finally {
await session.close();
}
});
test("Stop dismisses async questions before cancellation and keeps them dismissed after resume", async () => {
const first = await setup();
let metadata: Record<string, unknown> | undefined;
try {
await first.ask();
expect(first.session.getPendingPermissions()).toHaveLength(1);
first.session.subscribe((event) => {
if (event.type === "turn_canceled") {
metadata = first.session.describePersistence()!.metadata;
}
});
await first.session.interrupt();
await first.finish("interrupted");
expect(first.session.getPendingPermissions()).toEqual([]);
expect(metadata?.asyncQuestions).toEqual([
expect.objectContaining({ resolution: "dismissed" }),
]);
expect(first.events).toContainEqual(
expect.objectContaining({
type: "permission_resolved",
requestId: "permission-async-question-1",
resolution: { behavior: "deny", message: "Interrupted" },
}),
);
} finally {
await first.session.close();
}
const resumed = await setup(metadata);
try {
await resumed.ask();
expect(resumed.session.getPendingPermissions()).toEqual([]);
} finally {
await resumed.session.close();
}
});
test("late answers use the existing follow-up prompt and dismissal does not interrupt", async () => {
const { session, appServer, ask, finish } = await setup();
try {
await ask();
const [permission] = session.getPendingPermissions();
expect(permission).toBeDefined();
await finish();
expect(session.getPendingPermissions()).toHaveLength(1);
expect(await session.respondToPermission(permission.id, answer)).toEqual({
followUpPrompt: "Answers to your questions:\n\nWhich color?\nGreen",
});
expect(appServer.requests().some((request) => request.method === "turn/interrupt")).toBe(false);
} finally {
await session.close();
}
});
test("restores unanswered questions and does not reopen answered questions on duplicate events", async () => {
const first = await setup();
let metadata: Record<string, unknown> | undefined;
try {
await first.ask();
expect(first.session.getPendingPermissions()).toHaveLength(1);
metadata = first.session.describePersistence()!.metadata;
} finally {
await first.session.close();
}
const resumed = await setup(metadata);
try {
const [permission] = resumed.session.getPendingPermissions();
expect(permission).toBeDefined();
await resumed.session.respondToPermission(permission.id, { behavior: "deny" });
await resumed.ask();
expect(resumed.session.getPendingPermissions()).toEqual([]);
expect(
resumed.appServer.requests().some((request) => request.method === "turn/interrupt"),
).toBe(false);
} finally {
await resumed.session.close();
}
});
@@ -1,22 +1,12 @@
import type { AgentFeature, AgentFeatureToggle } from "../agent-sdk-types.js";
// Codex Fast is distinct from API Priority processing. Keep model support aligned with
// https://developers.openai.com/codex/speed and https://developers.openai.com/codex/models.
const CODEX_FAST_MODE_SUPPORTED_MODELS = new Set([
"gpt-6-astra",
"gpt-5.6",
"gpt-5.6-sol",
"gpt-5.6-terra",
"gpt-5.6-luna",
"gpt-5.5",
"gpt-5.4",
]);
const CODEX_FAST_MODE_SUPPORTED_MODEL_PREFIXES = ["gpt-5", "gpt-4.1", "o3", "o4-mini"] as const;
export const CODEX_FAST_MODE_FEATURE: Omit<AgentFeatureToggle, "value"> = {
type: "toggle",
id: "fast_mode",
label: "Fast",
description: "Priority inference at increased usage",
description: "Priority inference at 2x usage",
tooltip: "Toggle fast mode",
icon: "zap",
};
@@ -40,7 +30,9 @@ export function codexModelSupportsFastMode(modelId: string | null | undefined):
if (!normalizedModelId) {
return false;
}
return CODEX_FAST_MODE_SUPPORTED_MODELS.has(normalizedModelId);
return CODEX_FAST_MODE_SUPPORTED_MODEL_PREFIXES.some(
(prefix) => normalizedModelId === prefix || normalizedModelId.startsWith(prefix),
);
}
export function buildCodexFeatures(input: {
@@ -1,155 +0,0 @@
import { z } from "zod";
import type {
AgentPermissionRequest,
AgentPermissionResponse,
ToolCallTimelineItem,
} from "../../agent-sdk-types.js";
const QuestionSchema = z.object({
title: z.string().trim().min(1),
options: z.array(z.string().min(1)).nullish(),
});
const ItemSchema = z.object({
type: z.literal("agentMessage"),
id: z.string().min(1),
delivery: z.literal("async"),
questions: z.array(QuestionSchema).min(1),
});
const RecordSchema = z.object({
item: ItemSchema,
resolution: z.union([z.literal("dismissed"), z.array(z.string())]).optional(),
});
type QuestionRecord = z.infer<typeof RecordSchema>;
function requestId(itemId: string): string {
return `permission-${itemId}`;
}
function toPermission(record: QuestionRecord): AgentPermissionRequest {
return {
id: requestId(record.item.id),
provider: "codex",
name: "request_user_input_async",
kind: "question",
title: "Question",
input: {
questions: record.item.questions.map((question, index) => ({
id: String(index),
header: `Question ${index + 1}`,
question: question.title,
options: (question.options ?? []).map((label) => ({ label })),
isOther: true,
})),
},
};
}
function toTimeline(record: QuestionRecord): ToolCallTimelineItem {
const answers = Array.isArray(record.resolution) ? record.resolution : undefined;
return {
type: "tool_call",
callId: record.item.id,
name: "request_user_input_async",
status: "completed",
error: null,
detail: {
type: "plain_text",
icon: "brain",
text:
record.item.questions
.map((question, index) =>
[question.title, answers ? answers[index] : (question.options ?? []).join(", ")]
.filter(Boolean)
.join("\n"),
)
.join("\n\n") + (record.resolution === "dismissed" ? "\n\nDismissed" : ""),
},
};
}
export function codexAsyncQuestionToTimeline(item: unknown): ToolCallTimelineItem | null {
const parsed = ItemSchema.safeParse(item);
return parsed.success ? toTimeline({ item: parsed.data }) : null;
}
/** Codex emits these as completed messages; the outstanding answer belongs to the session. */
export class CodexAsyncQuestions {
private readonly records = new Map<string, QuestionRecord>();
constructor(saved: unknown) {
const parsed = z.array(RecordSchema).safeParse(saved);
if (parsed.success) {
for (const record of parsed.data) this.records.set(requestId(record.item.id), record);
}
}
receive(item: unknown): AgentPermissionRequest | null {
const parsed = ItemSchema.safeParse(item);
if (!parsed.success || this.records.has(requestId(parsed.data.id))) return null;
const record = { item: parsed.data };
this.records.set(requestId(parsed.data.id), record);
return toPermission(record);
}
pending(): AgentPermissionRequest[] {
return Array.from(this.records.values())
.filter((record) => record.resolution === undefined)
.map(toPermission);
}
hasPending(id: string): boolean {
const record = this.records.get(id);
return record !== undefined && record.resolution === undefined;
}
prepareResponse(
id: string,
response: AgentPermissionResponse,
): { prompt?: string; complete: () => ToolCallTimelineItem } {
const record = this.records.get(id);
if (!record || record.resolution !== undefined)
throw new Error("Question is no longer pending");
let resolution: QuestionRecord["resolution"] = "dismissed";
let prompt: string | undefined;
if (response.behavior === "allow") {
const answers = z.record(z.string(), z.string()).parse(response.updatedInput?.answers);
resolution = record.item.questions.map((_, index) => {
const answer = answers[`Question ${index + 1}`]?.trim();
if (!answer) throw new Error(`Answer Question ${index + 1} before submitting`);
return answer;
});
const values = resolution;
prompt =
"Answers to your questions:\n\n" +
record.item.questions
.map((question, index) => `${question.title}\n${values[index]}`)
.join("\n\n");
}
return {
prompt,
complete: () => {
record.resolution = resolution;
return toTimeline(record);
},
};
}
timeline(itemId: string): ToolCallTimelineItem | null {
const record = this.records.get(requestId(itemId));
return record ? toTimeline(record) : null;
}
retain(itemIds: ReadonlySet<string>): string[] {
const removedPendingIds: string[] = [];
for (const [id, record] of this.records) {
if (itemIds.has(record.item.id)) continue;
this.records.delete(id);
if (record.resolution === undefined) removedPendingIds.push(id);
}
return removedPendingIds;
}
serialize(): unknown {
return Array.from(this.records.values());
}
}
@@ -618,7 +618,7 @@ function toJsonObject(value: unknown): JsonObject {
type StreamEventType = AgentStreamEvent["type"];
type StreamEventOfType<TType extends StreamEventType> = Extract<AgentStreamEvent, { type: TType }>;
export function waitForNextEvent<TType extends StreamEventType>(
function waitForNextEvent<TType extends StreamEventType>(
session: AgentSession,
type: TType,
accepts?: (event: StreamEventOfType<TType>) => boolean,
@@ -2,7 +2,7 @@ import { mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { afterEach, expect, test } from "vitest";
import { AgentRequests } from "./index.js";
import { AgentRequests, AgentRequestError } from "./index.js";
const directories: string[] = [];
afterEach(async () => {
@@ -141,3 +141,210 @@ test("failed local message preparation does not leave an ambiguous receipt", asy
await requests.send(input);
expect(sends).toBe(1);
});
test("canceling startup rejects its waiter and fences later phases and retries", async () => {
const { requests, directory } = await fixture();
const context = { key: "arrival", deadlineAt: new Date(Date.now() + 60_000).toISOString() };
let entered!: () => void;
const started = new Promise<void>((resolve) => {
entered = resolve;
});
const pending = requests.run(context, async (signal) => {
if (!signal) throw new Error("missing operation signal");
entered();
await new Promise<void>((_, reject) =>
signal.addEventListener("abort", () => reject(signal.reason), { once: true }),
);
});
const failed = expect(pending).rejects.toThrow("agent_request_canceled");
await started;
await requests.cancel(context.key);
await failed;
let sent = false;
await expect(
new AgentRequests(directory).run(context, async () => {
sent = true;
}),
).rejects.toThrow("agent_request_canceled");
expect(sent).toBe(false);
expect(await requests.run({ ...context, key: "other-arrival" }, async () => "ok")).toBe("ok");
});
test("an expired startup deadline cannot launch even without a cancel frame", async () => {
const { requests } = await fixture();
let launched = false;
await expect(
requests.run({ key: "expired", deadlineAt: "2000-01-01T00:00:00.000Z" }, async () => {
launched = true;
}),
).rejects.toThrow("agent_request_canceled");
expect(launched).toBe(false);
});
test("a noncooperative operation leaves explicit pending cleanup without trapping cancel callers", async () => {
const { requests } = await fixture();
let entered!: () => void;
const started = new Promise<void>((resolve) => {
entered = resolve;
});
let release!: () => void;
const gate = new Promise<void>((resolve) => {
release = resolve;
});
const pending = requests.run(
{ key: "hung", deadlineAt: new Date(Date.now() + 60_000).toISOString() },
async () => {
entered();
await gate;
},
);
const failed = expect(pending).rejects.toThrow("agent_request_canceled");
await started;
expect(await requests.cancelOperation("hung", "conversation")).toEqual({
agentId: null,
outcome: "pending",
});
await failed;
release();
await expect
.poll(() => requests.cancelOperation("hung", "conversation"))
.toEqual({ agentId: null, outcome: "settled" });
});
test("a reconstructed journal reports interrupted startup as unknown and never launches a canceled phase", async () => {
const { requests, directory } = await fixture();
let entered!: () => void;
const started = new Promise<void>((resolve) => {
entered = resolve;
});
let release!: () => void;
const gate = new Promise<void>((resolve) => {
release = resolve;
});
const context = { key: "interrupted", deadlineAt: new Date(Date.now() + 60_000).toISOString() };
const pending = requests.run(context, async () => {
entered();
await gate;
});
await started;
const restarted = new AgentRequests(directory);
const replays = await Promise.allSettled([
restarted.run(context, async () => "must not launch"),
restarted.run(context, async () => "must not launch"),
]);
expect(replays).toEqual([
{ status: "rejected", reason: new AgentRequestError("agent_request_outcome_unknown") },
{ status: "rejected", reason: new AgentRequestError("agent_request_outcome_unknown") },
]);
expect(await restarted.cancelOperation(context.key, "conversation")).toEqual({
agentId: null,
outcome: "unknown",
});
await expect(restarted.run(context, async () => "must not run")).rejects.toThrow(
"agent_request_outcome_unknown",
);
release();
await pending;
});
test("a live deadline settles a hung waiter without a cancel frame and preserves late cleanup", async () => {
const { directory } = await fixture();
let expire!: () => void;
const now = Date.parse("2026-09-09T00:00:00Z");
const requests = new AgentRequests(directory, {
now: () => now,
schedule(callback, delayMs) {
expect(delayMs).toBe(120_000);
expire = callback;
return () => {};
},
});
let release!: () => void;
const gate = new Promise<void>((resolve) => {
release = resolve;
});
let enter!: () => void;
const entered = new Promise<void>((resolve) => {
enter = resolve;
});
const pending = requests.run(
{ key: "deadline", deadlineAt: new Date(now + 120_000).toISOString() },
async () => {
enter();
await gate;
},
);
const rejected = expect(pending).rejects.toThrow("agent_request_canceled");
await entered;
expire();
await rejected;
expect(await requests.inspectOperation("deadline", "conversation")).toMatchObject({
outcome: "pending",
});
await expect(requests.run({ key: "deadline" }, async () => "must not launch")).rejects.toThrow(
"agent_request_canceled",
);
release();
await requests.cancelAndSettle("deadline");
expect(await requests.inspectOperation("deadline", "conversation")).toMatchObject({
outcome: "settled",
});
expect(await requests.run({ key: "next" }, async () => "ready")).toBe("ready");
});
test("retransmitted phases serialize while other operation keys continue", async () => {
const { requests } = await fixture();
let release!: () => void;
const gate = new Promise<void>((resolve) => {
release = resolve;
});
let entered!: () => void;
const started = new Promise<void>((resolve) => {
entered = resolve;
});
const order: string[] = [];
const first = requests.run({ key: "arrival" }, async () => {
order.push("first");
entered();
await gate;
order.push("settled");
});
await started;
const second = requests.run({ key: "arrival" }, async () => {
order.push("second");
});
await requests.run({ key: "other" }, async () => {
order.push("other");
});
expect(order).toEqual(["first", "other"]);
release();
await Promise.all([first, second]);
expect(order).toEqual(["first", "other", "settled", "second"]);
});
test("successful control receipts survive restart and reject changed targets", async () => {
const { requests, directory } = await fixture();
let archives = 0;
const action = async () => {
archives++;
};
await requests.control({ key: "cleanup" }, { workspaceId: "one" }, action);
const restarted = new AgentRequests(directory);
await restarted.control({ key: "cleanup" }, { workspaceId: "one" }, action);
expect(archives).toBe(1);
await expect(
restarted.control({ key: "cleanup" }, { workspaceId: "two" }, action),
).rejects.toThrow("agent_request_key_conflict");
});
test("refused provider cancellation remains unknown after restart", async () => {
const { requests, directory } = await fixture();
await expect(
requests.run({ key: "refused" }, async () => {
throw new AgentRequestError("agent_request_outcome_unknown");
}),
).rejects.toThrow("agent_request_outcome_unknown");
expect(
await new AgentRequests(directory).inspectOperation("refused", "conversation"),
).toMatchObject({ outcome: "unknown" });
});
@@ -11,11 +11,253 @@ const ReceiptSchema = z.object({
});
type Receipt = z.infer<typeof ReceiptSchema>;
export class AgentRequestError extends Error {
constructor(
public readonly code:
| "agent_request_canceled"
| "agent_request_outcome_unknown"
| "agent_request_key_conflict",
) {
super(code);
this.name = "AgentRequestError";
}
}
interface RequestClock {
now(): number;
schedule(callback: () => void, delayMs: number): () => void;
}
const systemClock: RequestClock = {
now: () => Date.now(),
schedule(callback, delayMs) {
const timer = setTimeout(callback, delayMs);
return () => clearTimeout(timer);
},
};
/** One daemon-owned request journal, shared by all of its socket sessions. */
export class AgentRequests {
private readonly pending = new Map<string, Promise<string>>();
private readonly pending = new Map<string, Promise<unknown>>();
private readonly operations = new Map<
string,
{ controllers: Set<AbortController>; initialized: Promise<void>; unknown: boolean }
>();
private readonly operationWrites = new Map<string, Promise<void>>();
constructor(private readonly directory: string) {}
constructor(
private readonly directory: string,
private readonly clock: RequestClock = systemClock,
) {}
/** Runtime cancellation belongs to the same journal as idempotent create/send receipts. */
async run<T>(
context: { key: string; deadlineAt?: string } | undefined,
operation: (signal?: AbortSignal) => Promise<T>,
): Promise<T> {
if (!context) return operation();
let active = this.operations.get(context.key);
if (!active) {
const previousWrite = this.operationWrites.get(context.key);
active = {
controllers: new Set(),
unknown: false,
initialized: (async () => {
await previousWrite;
if (await this.wasInterrupted(context.key))
throw new AgentRequestError("agent_request_outcome_unknown");
})(),
};
this.operations.set(context.key, active);
}
const operationState = active;
const controller = new AbortController();
const controllers = active.controllers;
controllers.add(controller);
let clearTimer: (() => void) | undefined;
let abort: (() => void) | undefined;
let started = false;
let recorded = false;
try {
await active.initialized;
const remaining =
context.deadlineAt === undefined
? undefined
: Date.parse(context.deadlineAt) - this.clock.now();
if (
(remaining !== undefined && (!Number.isFinite(remaining) || remaining <= 0)) ||
(await this.wasCanceled(context.key))
) {
throw new AgentRequestError("agent_request_canceled");
}
controller.signal.throwIfAborted();
if (remaining !== undefined)
clearTimer = this.clock.schedule(
() => controller.abort(new AgentRequestError("agent_request_canceled")),
remaining,
);
await this.recordOperationState(context.key);
recorded = true;
controller.signal.throwIfAborted();
started = true;
const operationKey = digest(["operation", context.key]);
const previous = this.pending.get(operationKey) ?? Promise.resolve();
const tracked = previous
.catch(() => undefined)
.then(() => {
controller.signal.throwIfAborted();
return operation(controller.signal);
})
.catch((error: unknown) => {
if (error instanceof AgentRequestError && error.code === "agent_request_outcome_unknown")
operationState.unknown = true;
throw error;
})
.finally(async () => {
controllers.delete(controller);
if (controllers.size === 0) this.operations.delete(context.key);
await this.recordOperationState(context.key, operationState.unknown);
if (this.pending.get(operationKey) === tracked) this.pending.delete(operationKey);
});
this.pending.set(operationKey, tracked);
return await Promise.race([
tracked,
new Promise<never>((_, reject) => {
abort = () => reject(controller.signal.reason);
controller.signal.addEventListener("abort", abort, { once: true });
if (controller.signal.aborted) abort();
}),
]);
} finally {
clearTimer?.();
if (abort) controller.signal.removeEventListener("abort", abort);
if (controller.signal.aborted) await this.recordCancellation(context.key);
if (!started) {
controllers.delete(controller);
if (controllers.size === 0) this.operations.delete(context.key);
if (recorded) await this.recordOperationState(context.key);
}
}
}
async cancel(key: string): Promise<void> {
// Persist before acknowledging: a delayed request or a new socket must also be fenced.
await this.recordCancellation(key);
for (const controller of this.operations.get(key)?.controllers ?? []) {
controller.abort(new AgentRequestError("agent_request_canceled"));
}
}
async control(
context: { key: string; deadlineAt?: string } | undefined,
request: unknown,
operation: () => Promise<unknown>,
): Promise<void> {
await this.run(context, async () => {
if (!context) {
await operation();
return;
}
const file = path.join(this.directory, `control-${digest(context.key)}.json`);
const fingerprint = digest(request);
try {
const receipt = z
.object({ fingerprint: z.string() })
.parse(JSON.parse(await readFile(file, "utf8")));
if (receipt.fingerprint !== fingerprint)
throw new AgentRequestError("agent_request_key_conflict");
return;
} catch (error) {
if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) throw error;
}
await operation();
await writeJsonFileAtomic(file, { fingerprint });
});
}
async cancelAndSettle(key: string): Promise<void> {
await this.cancel(key);
await this.pending.get(digest(["operation", key]))?.catch(() => undefined);
await this.operationWrites.get(key);
if (await this.wasInterrupted(key))
throw new AgentRequestError("agent_request_outcome_unknown");
}
async cancelOperation(
key: string,
creationKey: string,
): Promise<{
agentId: string | null;
outcome: "settled" | "pending" | "unknown";
}> {
await this.cancel(key);
return this.inspectOperation(key, creationKey);
}
async inspectOperation(
key: string,
creationKey: string,
): Promise<{
agentId: string | null;
outcome: "settled" | "pending" | "unknown";
}> {
await this.operationWrites.get(key);
const active = this.operations.has(key);
const receipt = await readReceipt(
path.join(this.directory, `${digest(["create", creationKey])}.json`),
);
let outcome: "pending" | "unknown" | "settled" = "settled";
if (receipt?.state === "pending" || (await this.wasInterrupted(key))) outcome = "unknown";
if (active) outcome = "pending";
return { agentId: receipt?.agentId ?? null, outcome };
}
private recordOperationState(key: string, unknown = false): Promise<void> {
const previous = this.operationWrites.get(key) ?? Promise.resolve();
const write = previous
.catch(() => undefined)
.then(() =>
writeJsonFileAtomic(path.join(this.directory, `operation-${digest(key)}.json`), {
state: unknown || this.operations.has(key) ? "pending" : "settled",
}),
);
this.operationWrites.set(key, write);
void write
.finally(() => {
if (this.operationWrites.get(key) === write) this.operationWrites.delete(key);
})
.catch(() => undefined);
return write;
}
private async wasInterrupted(key: string): Promise<boolean> {
try {
const state = z
.object({ state: z.enum(["pending", "settled"]) })
.parse(
JSON.parse(
await readFile(path.join(this.directory, `operation-${digest(key)}.json`), "utf8"),
),
);
return state.state === "pending";
} catch (error) {
if (error instanceof Error && "code" in error && error.code === "ENOENT") return false;
throw error;
}
}
private recordCancellation(key: string): Promise<void> {
return writeJsonFileAtomic(path.join(this.directory, `canceled-${digest(key)}.json`), true);
}
private async wasCanceled(key: string): Promise<boolean> {
try {
await readFile(path.join(this.directory, `canceled-${digest(key)}.json`));
return true;
} catch (error) {
if (error instanceof Error && "code" in error && error.code === "ENOENT") return false;
throw error;
}
}
create(input: {
key: string;
@@ -89,10 +331,11 @@ export class AgentRequests {
const file = path.join(this.directory, `${key}.json`);
const existing = await readReceipt(file);
if (existing) {
if (existing.fingerprint !== fingerprint) throw new Error("agent_request_key_conflict");
if (existing.fingerprint !== fingerprint)
throw new AgentRequestError("agent_request_key_conflict");
if (existing.state === "completed") return existing.agentId;
if (!(await operation.recover(existing.agentId))) {
throw new Error("agent_request_outcome_unknown");
throw new AgentRequestError("agent_request_outcome_unknown");
}
await writeJsonFileAtomic(file, { ...existing, state: "completed" });
return existing.agentId;
@@ -1,11 +0,0 @@
/** Thrown when a prompt reaches a plugin session whose connection died with its plugin. */
export class StaleProviderSessionError extends Error {
constructor(sessionId: string) {
super(`Provider session ${sessionId} is stale after its plugin reloaded`);
this.name = "StaleProviderSessionError";
}
}
export function isStaleProviderSessionError(error: unknown): error is StaleProviderSessionError {
return error instanceof StaleProviderSessionError;
}
@@ -6,6 +6,8 @@ type OutboundOperation = SessionOutboundMessage["type"];
export type PermissionRequirement = DaemonPermission | readonly DaemonPermission[] | null;
const INBOUND_PERMISSION = {
"agent.requests.inspect.request": ["workspace.write", "hub.execute"],
"agent.requests.cancel.request": ["workspace.write", "hub.execute"],
abort_request: "workspace.write",
"agent.config.apply.request": ["workspace.write", "hub.execute"],
"agent.detach.request": "workspace.write",
@@ -206,6 +208,8 @@ const INBOUND_PERMISSION = {
} as const satisfies Record<InboundOperation, PermissionRequirement>;
const OUTBOUND_PERMISSION = {
"agent.requests.inspect.response": ["workspace.write", "hub.execute"],
"agent.requests.cancel.response": ["workspace.write", "hub.execute"],
activity_log: "workspace.read",
"agent.config.apply.response": ["workspace.write", "hub.execute"],
"agent.detach.response": "workspace.write",
+4
View File
@@ -1,3 +1,4 @@
import { AgentRequests } from "./agent/requests/index.js";
import { describeHookWorkspace } from "./plugins/lifecycle/index.js";
import express from "express";
import { createServer as createHTTPServer, type IncomingMessage, type ServerResponse } from "http";
@@ -856,6 +857,7 @@ export async function createPaseoDaemon(
serviceProxyListenTarget = parseListenString(config.serviceProxy.standaloneListen);
}
const agentRequests = new AgentRequests(path.join(config.paseoHome, "agent-requests"));
const agentStorage = new AgentStorage(config.agentStoragePath, logger);
const projectRegistry = new FileBackedProjectRegistry(
path.join(config.paseoHome, "projects", "projects.json"),
@@ -1257,6 +1259,7 @@ export async function createPaseoDaemon(
createExecutionAgents: (daemonId) =>
new DaemonExecutions({
daemonId,
agentRequests,
agentManager,
agentStorage,
createAgent,
@@ -1717,6 +1720,7 @@ export async function createPaseoDaemon(
pluginRuntime,
orchestrationSkills,
workspaceLabelService,
agentRequests,
);
pluginRuntime.bindPaseoSessionHost(wsServer);
await pluginRuntime.start();
@@ -326,3 +326,40 @@ test("failed create never archives a reused worktree", async () => {
});
expect(await hub.worktreeState(worktreeCwd!)).toEqual({ exists: true, listed: true });
});
test("control cancels a held legacy provider create and fences a delayed replay", async () => {
const hub = await launchRelationship();
hub.holdAgentCreation();
hub.beginOwnedCreate("held-create", "expired-create");
await hub.agentCreationAttempts(1);
const creation = hub.ownedCreateResult("held-create");
const control = hub.controlExecution("expired-create", "archive");
try {
expect(await control).toMatchObject({ success: true });
expect(await creation).toMatchObject({ payload: { success: false } });
} finally {
hub.finishAgentCreation();
}
hub.beginOwnedCreate("late-create", "expired-create");
expect(await hub.ownedCreateResult("late-create")).toMatchObject({ payload: { success: false } });
});
test("the legacy absolute deadline cancels provider creation without a control frame", async () => {
const hub = await launchRelationship();
hub.holdAgentCreation();
hub.beginOwnedCreate("deadline-create", "deadline-create", {
deadlineAt: new Date(Date.now() + 1_000).toISOString(),
});
try {
await hub.agentCreationAttempts(1);
expect(await hub.ownedCreateResult("deadline-create")).toMatchObject({
payload: { success: false },
});
} finally {
hub.finishAgentCreation();
}
hub.beginOwnedCreate("deadline-replay", "deadline-create");
expect(await hub.ownedCreateResult("deadline-replay")).toMatchObject({
payload: { success: false },
});
});
@@ -1,3 +1,4 @@
import type { AgentRequests } from "../agent/requests/index.js";
import type {
AgentSnapshotPayload,
AgentStreamEventPayload,
@@ -17,6 +18,7 @@ import { daemonExecutionKey, type DaemonAgentOwner } from "../agent/agent-owner.
export interface HubExecutionAgentCreateInput {
executionId: string;
deadlineAt?: string;
provider: string;
cwd: string;
prompt: string;
@@ -53,6 +55,7 @@ export type OwnedAgentEvent =
interface DaemonExecutionsOptions {
daemonId: string;
agentRequests: AgentRequests;
agentManager: AgentManager;
agentStorage: AgentStorage;
createAgent: BoundCreateAgentCommand;
@@ -122,6 +125,8 @@ export class DaemonExecutions implements HubExecutionAgents {
const pending = this.pendingControlActions.get(actionKey);
if (pending) return pending;
const canceled = this.options.agentRequests.cancelAndSettle(executionKey);
void canceled.catch(() => undefined);
const previous =
this.controlTails.get(executionKey) ??
this.pendingCreates.get(executionKey)?.then(() => undefined) ??
@@ -129,6 +134,7 @@ export class DaemonExecutions implements HubExecutionAgents {
const authorityGeneration = this.authorityGeneration;
const control = previous
.catch(() => undefined)
.then(() => canceled)
.then(() => this.controlOwnedExecution(owner, input, authorityGeneration));
this.pendingControlActions.set(actionKey, control);
this.controlTails.set(executionKey, control);
@@ -148,6 +154,9 @@ export class DaemonExecutions implements HubExecutionAgents {
this.authorityActive = false;
this.authorityGeneration++;
await Promise.allSettled([
...[...this.pendingCreates.keys()].map((key) =>
this.options.agentRequests.cancelAndSettle(key),
),
...this.pendingCreates.values(),
...this.pendingControlActions.values(),
]);
@@ -180,12 +189,25 @@ export class DaemonExecutions implements HubExecutionAgents {
requireHubMcpNamespace(input.mcpServers);
requireToolPolicyServers(input.toolPolicy, input.mcpServers);
return this.options.agentRequests.run(
{ key: daemonExecutionKey(owner), deadlineAt: input.deadlineAt },
(signal) => this.createNewOwnedAgent(owner, input, authorityGeneration, signal),
);
}
private async createNewOwnedAgent(
owner: DaemonAgentOwner,
input: HubExecutionAgentCreateInput,
authorityGeneration: number,
signal?: AbortSignal,
): Promise<OwnedAgentSnapshot> {
let createdWorktree: CreatePaseoWorktreeWorkflowResult | null = null;
let createdAgentId: string | null = null;
let result: Awaited<ReturnType<BoundCreateAgentCommand>>;
try {
result = await this.createAgentCommand({
kind: "mcp",
signal,
provider: input.model ? `${input.provider}/${input.model}` : input.provider,
title: input.prompt,
initialPrompt: input.prompt,
@@ -215,6 +237,7 @@ export class DaemonExecutions implements HubExecutionAgents {
createdAgentId = created.agentId;
},
});
signal?.throwIfAborted();
this.requireAuthority(authorityGeneration);
requireExecutionWorkspaceId(result.liveSnapshot);
} catch (error) {
@@ -149,6 +149,7 @@ export class HubExecutionController {
if (!isAbsolute(message.cwd)) throw new Error("Hub agent cwd must be absolute");
const result = await this.agents.create({
executionId: message.executionId,
deadlineAt: message.deadlineAt,
provider: message.provider,
cwd: message.cwd,
prompt: message.prompt,
@@ -251,7 +251,7 @@ test("Hub interrupts an owned running execution idempotently", async () => {
expect(hub.ownedAgentIsRunning(created.payload.agentId!)).toBe(false);
});
test("Hub control waits for an in-flight create of the same execution", async () => {
test("Hub control cancels an in-flight create of the same execution", async () => {
const hub = await launchRelationship();
hub.holdAgentCreation();
hub.beginOwnedCreate("pending-control-create", "execution-pending-control", {
@@ -264,10 +264,8 @@ test("Hub control waits for an in-flight create of the same execution", async ()
const created = await hub.ownedCreateResult("pending-control-create");
const archived = await hub.executionControlResult("pending-control-archive");
expect(created).toMatchObject({ payload: { success: true, agentId: expect.any(String) } });
expect(created).toMatchObject({ payload: { success: false, agentId: null } });
expect(archived).toMatchObject({ success: true, error: null, action: "archive" });
expect(created.payload.agent?.workspaceId).toEqual(expect.any(String));
expect(await hub.ownedAgentArchivedAt(created.payload.agentId!)).toEqual(expect.any(String));
});
test("Hub archives an execution workspace on a local checkout", async () => {
@@ -1,3 +1,4 @@
import { AgentRequests } from "../../agent/requests/index.js";
import { execFile } from "node:child_process";
import { execFileSync } from "node:child_process";
import { EventEmitter } from "node:events";
@@ -1558,6 +1559,7 @@ export class HubRelationshipHarness {
private executionsForReconstruction(manager: AgentManager, storage: AgentStorage) {
return new DaemonExecutions({
agentRequests: new AgentRequests(path.join(this.paseoHome, "agent-requests")),
daemonId: this.relationshipFile()!.relationship.daemonId,
agentManager: manager,
agentStorage: storage,
@@ -202,7 +202,6 @@ function buildRunOutput(params: {
type ScheduleAgentManager = Pick<
AgentRunController,
| "getAgent"
| "reloadAgentSession"
| "tryRunOutOfBand"
| "hasInFlightRun"
| "replaceAgentRun"
@@ -0,0 +1,255 @@
import { randomUUID } from "node:crypto";
import { expect, test } from "vitest";
import { WebSocket } from "ws";
import { z } from "zod";
import { createTestPaseoDaemon } from "./test-utils/paseo-daemon.js";
import { createTestAgentClient } from "./test-utils/fake-agent-client.js";
const Envelope = z.object({
type: z.literal("session"),
message: z.object({ type: z.string(), payload: z.record(z.string(), z.unknown()) }),
});
function exchange(
socket: WebSocket,
frame: unknown,
accepts: (type: string, payload: Record<string, unknown>) => boolean,
) {
return new Promise<Record<string, unknown>>((resolve, reject) => {
const timer = setTimeout(() => {
cleanup();
reject(new Error("Daemon response missing"));
}, 10_000);
const receive = (data: WebSocket.RawData) => {
const parsed = Envelope.safeParse(JSON.parse(data.toString()));
if (parsed.success && accepts(parsed.data.message.type, parsed.data.message.payload)) {
cleanup();
resolve(parsed.data.message.payload);
}
};
const cleanup = () => {
clearTimeout(timer);
socket.off("message", receive);
};
socket.on("message", receive);
socket.send(JSON.stringify(frame));
});
}
function request(socket: WebSocket, message: Record<string, unknown>) {
const requestId = randomUUID();
return exchange(
socket,
{ type: "session", message: { ...message, requestId } },
(_type, payload) => payload["requestId"] === requestId,
);
}
async function connect(port: number) {
const socket = new WebSocket(`ws://127.0.0.1:${port}/ws`);
await new Promise<void>((resolve, reject) => {
socket.once("open", resolve);
socket.once("error", reject);
});
const info = await exchange(
socket,
{ type: "hello", clientId: randomUUID(), clientType: "browser", protocolVersion: 1 },
(_type, payload) => payload["status"] === "server_info",
);
expect(info["features"]).toMatchObject({ agentRequestCancellation: true });
return socket;
}
test("socket cancellation settles a held create, disposes its late provider session, and fences a reconnect replay", async () => {
let started!: () => void;
const entered = new Promise<void>((resolve) => {
started = resolve;
});
let release!: () => void;
const gate = new Promise<void>((resolve) => {
release = resolve;
});
let creates = 0;
let closes = 0;
const provider = createTestAgentClient("codex", {
beforeCreateSession: async () => {
creates++;
started();
await gate;
},
closeSession: async () => {
closes++;
},
});
const host = await createTestPaseoDaemon({ agentClients: { codex: provider } });
let socket = await connect(host.port);
const key = randomUUID();
const creationKey = randomUUID();
const config = { provider: "codex", cwd: host.paseoHome };
const operation = { key, deadlineAt: new Date(Date.now() + 60_000).toISOString() };
try {
const unkeyed = await request(socket, {
type: "create_agent_request",
config,
operation,
initialPrompt: "must not launch",
});
expect(unkeyed).toMatchObject({ status: "agent_create_failed" });
expect(creates).toBe(0);
const creation = request(socket, {
type: "create_agent_request",
config,
idempotencyKey: creationKey,
operation,
});
await entered;
const canceled = await request(socket, {
type: "agent.requests.cancel.request",
key,
creationKey,
});
expect(["pending", "settled"]).toContain(canceled["outcome"]);
expect(await creation).not.toMatchObject({ status: "agent_created" });
release();
await expect.poll(() => closes).toBe(1);
await expect
.poll(() => request(socket, { type: "agent.requests.inspect.request", key, creationKey }))
.toMatchObject({ outcome: "settled", agentId: null });
expect(host.daemon.agentManager.listAgents()).toEqual([]);
socket.close();
socket = await connect(host.port);
const replay = await request(socket, {
type: "create_agent_request",
config,
idempotencyKey: creationKey,
operation,
});
expect(replay).not.toMatchObject({ status: "agent_created" });
expect(creates).toBe(1);
const next = await request(socket, {
type: "create_agent_request",
config,
idempotencyKey: creationKey,
operation: { ...operation, key: randomUUID() },
});
expect(next).toMatchObject({ status: "agent_created" });
const repeated = await request(socket, {
type: "create_agent_request",
config,
idempotencyKey: creationKey,
operation: { ...operation, key: randomUUID() },
});
expect(repeated["agentId"]).toBe(next["agentId"]);
expect(creates).toBe(2);
expect(host.daemon.agentManager.listAgents()).toHaveLength(1);
} finally {
release();
socket.close();
await host.close();
}
}, 30_000);
test("expiry during provider send settles the socket caller and retains cleanup ownership until cancellation finishes", async () => {
let entered!: () => void;
const started = new Promise<void>((resolve) => {
entered = resolve;
});
let release!: () => void;
const gate = new Promise<void>((resolve) => {
release = resolve;
});
let turns = 0;
const provider = createTestAgentClient("codex", {
beforeStartTurn: async () => {
entered();
await gate;
},
onStartTurn: () => {
turns++;
},
});
const host = await createTestPaseoDaemon({ agentClients: { codex: provider } });
const socket = await connect(host.port);
const creationKey = randomUUID();
const key = randomUUID();
try {
const created = await request(socket, {
type: "create_agent_request",
config: { provider: "codex", cwd: host.paseoHome },
idempotencyKey: creationKey,
});
const agentId = z.string().parse(created["agentId"]);
const messageId = randomUUID();
const operation = { key, deadlineAt: new Date(Date.now() + 60_000).toISOString() };
const sending = request(socket, {
type: "send_agent_message_request",
agentId,
messageId,
text: "hello",
operation,
});
await started;
await request(socket, { type: "agent.requests.cancel.request", key, creationKey });
expect(await sending).not.toMatchObject({ accepted: true });
// The provider has not acknowledged start. Cancellation cannot claim this work settled yet.
expect(
await request(socket, { type: "agent.requests.inspect.request", key, creationKey }),
).toMatchObject({ outcome: "pending", agentId });
release();
await expect
.poll(() => request(socket, { type: "agent.requests.inspect.request", key, creationKey }))
.toMatchObject({ outcome: "settled", agentId });
expect(host.daemon.agentManager.hasInFlightRun(agentId)).toBe(false);
await request(socket, {
type: "send_agent_message_request",
agentId,
messageId,
text: "hello",
operation,
});
expect(turns).toBe(1);
const next = await request(socket, {
type: "send_agent_message_request",
agentId,
messageId: randomUUID(),
text: "next",
operation: { ...operation, key: randomUUID() },
});
expect(next).toMatchObject({ accepted: true });
expect(turns).toBe(2);
} finally {
release();
socket.close();
await host.close();
}
}, 30_000);
test("a delayed duplicate archive acknowledgement cannot archive a restored continuation again", async () => {
const host = await createTestPaseoDaemon({
agentClients: { codex: createTestAgentClient("codex") },
});
const socket = await connect(host.port);
try {
const created = await request(socket, {
type: "create_agent_request",
config: { provider: "codex", cwd: host.paseoHome },
idempotencyKey: randomUUID(),
});
const workspaceId = z.object({ workspaceId: z.string() }).parse(created["agent"]).workspaceId;
const archive = {
type: "archive_workspace_request",
workspaceId,
operation: { key: randomUUID() },
};
expect(await request(socket, archive)).toMatchObject({ error: null });
expect(
await request(socket, { type: "workspace.recovery.restore.request", workspaceId }),
).toMatchObject({ error: null });
expect(await request(socket, archive)).toMatchObject({ error: null });
expect(
await request(socket, { type: "workspace.recovery.inspect.request", workspaceId }),
).toMatchObject({ state: { kind: "unavailable", reason: "workspace_not_archived" } });
} finally {
socket.close();
await host.close();
}
}, 30_000);
+141 -47
View File
@@ -1,5 +1,5 @@
import type { SessionEventSubscription } from "@getpaseo/protocol/messages";
import type { AgentRequests } from "./agent/requests/index.js";
import { AgentRequestError, type AgentRequests } from "./agent/requests/index.js";
import equal from "fast-deep-equal";
import { v4 as uuidv4 } from "uuid";
import { lstat, mkdir, mkdtemp, rename, rm, stat } from "node:fs/promises";
@@ -464,7 +464,10 @@ export interface SessionOptions {
worktreesRoot?: string;
agentManager: AgentManager;
agentStorage: AgentStorage;
agentRequests: Pick<AgentRequests, "create" | "send">;
agentRequests: Pick<
AgentRequests,
"create" | "send" | "run" | "control" | "cancelOperation" | "inspectOperation"
>;
projectRegistry: ProjectRegistry;
workspaceRegistry: WorkspaceRegistry;
directorySync?: DirectorySyncService;
@@ -754,7 +757,10 @@ export class Session {
private readonly daemonSession: DaemonSession;
private readonly hubExecutionController: HubExecutionController | null;
private readonly workspaceScripts: WorkspaceScriptsService;
private readonly agentRequests: Pick<AgentRequests, "create" | "send">;
private readonly agentRequests: Pick<
AgentRequests,
"create" | "send" | "run" | "control" | "cancelOperation" | "inspectOperation"
>;
private readonly createAgentLifecycleDispatch: CreateAgentLifecycleDispatch;
constructor(options: SessionOptions) {
@@ -2002,6 +2008,7 @@ export class Session {
this.dispatchAgentRelationshipMessage(msg) ??
this.dispatchAgentTimelineMessage(msg, source) ??
this.dispatchHubExecutionMessage(msg) ??
this.dispatchAgentRequestMessage(msg) ??
this.dispatchAgentLifecycleMessage(msg) ??
this.dispatchAgentConfigMessage(msg) ??
this.dispatchCheckoutMessage(msg) ??
@@ -2385,6 +2392,27 @@ export class Session {
return undefined;
}
private dispatchAgentRequestMessage(msg: SessionInboundMessage): Promise<void> | undefined {
switch (msg.type) {
case "agent.requests.inspect.request":
return this.agentRequests.inspectOperation(msg.key, msg.creationKey).then((result) => {
return this.emit({
type: "agent.requests.inspect.response",
payload: { requestId: msg.requestId, ...result },
});
});
case "agent.requests.cancel.request":
return this.agentRequests.cancelOperation(msg.key, msg.creationKey).then((result) => {
return this.emit({
type: "agent.requests.cancel.response",
payload: { requestId: msg.requestId, ...result },
});
});
default:
return undefined;
}
}
private dispatchAgentLifecycleMessage(msg: SessionInboundMessage): Promise<void> | undefined {
switch (msg.type) {
case "fetch_agents_request":
@@ -2408,11 +2436,15 @@ export class Session {
case "project.icon.set.request":
return this.handleProjectIconSetRequest(msg);
case "send_agent_message_request":
return this.handleSendAgentMessageRequest(msg);
return this.agentRequests.run(msg.operation, (signal) =>
this.handleSendAgentMessageRequest(msg, signal),
);
case "wait_for_finish_request":
return this.handleWaitForFinish(msg.agentId, msg.requestId, msg.timeoutMs);
case "create_agent_request":
return this.handleCreateAgentRequest(msg);
return this.agentRequests.run(msg.operation, (signal) =>
this.handleCreateAgentRequest(msg, signal),
);
case "resume_agent_request":
return this.handleResumeAgentRequest(msg);
case "import_agent_request":
@@ -2420,7 +2452,7 @@ export class Session {
case "refresh_agent_request":
return this.handleRefreshAgentRequest(msg);
case "cancel_agent_request":
return this.handleCancelAgentRequest(msg.agentId, msg.requestId);
return this.handleCancelAgentRequest(msg.agentId, msg.requestId, msg.operation);
case "agent_permission_response":
return this.handleAgentPermissionResponse(msg.agentId, msg.requestId, msg.response);
case "clear_agent_attention":
@@ -2660,7 +2692,9 @@ export class Session {
case "workspace.recovery.inspect.request":
return this.handleWorkspaceRecoveryInspectRequest(msg);
case "workspace.recovery.restore.request":
return this.handleWorkspaceRecoveryRestoreRequest(msg);
return this.agentRequests.run(msg.operation, (signal) =>
this.handleWorkspaceRecoveryRestoreRequest(msg, signal),
);
case "workspace.clear_attention.request":
return this.handleWorkspaceClearAttentionRequest(msg);
case "workspace.mark_unread.request":
@@ -3481,9 +3515,10 @@ export class Session {
private async handleWorkspaceRecoveryRestoreRequest(
request: Extract<SessionInboundMessage, { type: "workspace.recovery.restore.request" }>,
signal?: AbortSignal,
): Promise<void> {
try {
await this.restoreWorkspaceAndEmit(request.workspaceId);
await this.restoreWorkspaceAndEmit(request.workspaceId, signal);
this.emit({
type: "workspace.recovery.restore.response",
payload: {
@@ -3568,14 +3603,20 @@ export class Session {
/**
* Handle create agent request
*/
private async handleCreateAgentRequest(msg: CreateAgentRequestMessage): Promise<void> {
private async handleCreateAgentRequest(
msg: CreateAgentRequestMessage,
signal?: AbortSignal,
): Promise<void> {
try {
if (msg.operation && msg.idempotencyKey === undefined) {
throw new Error("Cancelable creation requires an idempotencyKey");
}
let agent: AgentSnapshotPayload;
if (msg.idempotencyKey !== undefined) {
if (msg.initialPrompt !== undefined) {
throw new Error("Idempotent creation requires sending the initial prompt separately");
}
const { requestId: _requestId, idempotencyKey, ...request } = msg;
const { requestId: _requestId, idempotencyKey, operation: _operation, ...request } = msg;
const id = await this.agentRequests.create({
key: idempotencyKey,
request,
@@ -3583,14 +3624,14 @@ export class Session {
this.agentManager.getAgent(agentId) != null ||
(await this.agentStorage.get(agentId)) !== null,
create: async (agentId) => {
await this.createSessionAgent(msg, agentId);
await this.createSessionAgent(msg, agentId, signal);
},
});
const record = await this.agentStorage.get(id);
if (!record) throw new Error("Previously created agent no longer exists");
agent = this.buildStoredAgentPayload(record);
} else {
agent = await this.createSessionAgent(msg);
agent = await this.createSessionAgent(msg, undefined, signal);
}
this.emit({
type: "status",
@@ -3625,9 +3666,23 @@ export class Session {
}
}
private async cleanupCanceledAgentCreate(
agentId: string | null,
signal?: AbortSignal,
): Promise<string | null> {
if (!signal?.aborted || !agentId) return agentId;
beginAgentDeleteIfSupported(this.agentStorage, agentId);
await this.agentManager.closeAgent(agentId);
await this.agentManager.flush();
await this.agentStorage.remove(agentId);
await this.agentManager.deleteAgentState(agentId);
return null;
}
private async createSessionAgent(
msg: CreateAgentRequestMessage,
agentId?: string,
signal?: AbortSignal,
): Promise<AgentSnapshotPayload> {
const {
config,
@@ -3676,6 +3731,7 @@ export class Session {
hasLegacyGitOptions: Boolean(git),
});
createdWorktreeForCleanup = createdWorktree;
signal?.throwIfAborted();
const resolvedIntent = await this.resolveSessionCreateAgentIntent({
request: msg,
createdWorktree,
@@ -3697,6 +3753,7 @@ export class Session {
},
{
kind: "session",
signal,
agentId,
config: resolvedIntent.config,
workspaceId: resolvedIntent.intent.workspaceId,
@@ -3716,6 +3773,7 @@ export class Session {
},
);
createdAgentId = snapshot.id;
signal?.throwIfAborted();
await this.agentUpdates.forwardLiveAgent(snapshot);
if (resolvedIntent.createdDirectoryWorkspace && trimmedPrompt) {
this.workspaceAutoName.scheduleForDirectory(
@@ -3738,6 +3796,7 @@ export class Session {
);
return this.buildAgentPayload(liveSnapshot);
} catch (error) {
createdAgentId = await this.cleanupCanceledAgentCreate(createdAgentId, signal);
await this.createAgentLifecycleDispatch.cleanupCreatedWorktreeAfterFailedAgentCreate({
createdWorktree: createdWorktreeForCleanup,
createdAgentId,
@@ -4031,13 +4090,19 @@ export class Session {
}
}
private async handleCancelAgentRequest(agentId: string, requestId?: string): Promise<void> {
private async handleCancelAgentRequest(
agentId: string,
requestId?: string,
operation?: { key: string; deadlineAt?: string },
): Promise<void> {
this.sessionLogger.info({ agentId }, `Cancel request received for agent ${agentId}`);
try {
await cancelAgentRunCommand(
{ agentManager: this.agentManager, logger: this.sessionLogger },
agentId,
await this.agentRequests.control(operation, { action: "interrupt", agentId }, () =>
cancelAgentRunCommand(
{ agentManager: this.agentManager, logger: this.sessionLogger },
agentId,
),
);
if (requestId) {
const agent = this.agentManager.getAgent(agentId);
@@ -5269,8 +5334,8 @@ export class Session {
};
}
private async restoreWorkspaceAndEmit(workspaceId: string): Promise<void> {
await this.workspaceRecovery.restore(workspaceId);
private async restoreWorkspaceAndEmit(workspaceId: string, signal?: AbortSignal): Promise<void> {
await this.workspaceRecovery.restore(workspaceId, signal);
const workspace = await this.workspaceRegistry.get(workspaceId);
if (!workspace) {
throw new Error(`Recovered workspace record not found: ${workspaceId}`);
@@ -6834,34 +6899,39 @@ export class Session {
throw new Error(`Workspace not found: ${request.workspaceId}`);
}
await archiveByScope(
{
paseoHome: this.paseoHome,
paseoWorktreesBaseRoot: this.worktreesRoot,
github: this.github,
workspaceGitService: this.workspaceGitService,
agentManager: this.agentManager,
agentStorage: this.agentStorage,
findWorkspaceIdForCwd: (cwd) => this.findWorkspaceIdForCwd(cwd),
getWorkspace: (workspaceId) => this.workspaceRegistry.get(workspaceId),
listActiveWorkspaces: () => this.listActiveWorkspaceRefs(),
archiveWorkspaceRecord: (workspaceId) => this.archiveWorkspaceRecord(workspaceId),
emitWorkspaceUpdatesForWorkspaceIds: (workspaceIds) =>
this.emitWorkspaceUpdatesForWorkspaceIds(workspaceIds),
markWorkspaceArchiving: (workspaceIds, archivingAt) =>
this.markWorkspaceArchiving(workspaceIds, archivingAt),
clearWorkspaceArchiving: (workspaceIds) => this.clearWorkspaceArchiving(workspaceIds),
assertWorkspaceAutomationAllowed: (workspaceId) =>
assertWorkspaceAutomationAllowedForWorkspace(this.workspaceRegistry, workspaceId),
killTerminalsForWorkspace: (workspaceId) =>
this.terminalController.killTerminalsForWorkspace(workspaceId),
stopWorkspaceSetup: (workspaceId) => this.workspaceSetupRuntime.stop(workspaceId),
sessionLogger: this.sessionLogger,
},
{
scope: { kind: "workspace", workspaceId: existing.workspaceId },
requestId: request.requestId,
},
await this.agentRequests.control(
request.operation,
{ action: "archive", workspaceId: request.workspaceId },
() =>
archiveByScope(
{
paseoHome: this.paseoHome,
paseoWorktreesBaseRoot: this.worktreesRoot,
github: this.github,
workspaceGitService: this.workspaceGitService,
agentManager: this.agentManager,
agentStorage: this.agentStorage,
findWorkspaceIdForCwd: (cwd) => this.findWorkspaceIdForCwd(cwd),
getWorkspace: (workspaceId) => this.workspaceRegistry.get(workspaceId),
listActiveWorkspaces: () => this.listActiveWorkspaceRefs(),
archiveWorkspaceRecord: (workspaceId) => this.archiveWorkspaceRecord(workspaceId),
emitWorkspaceUpdatesForWorkspaceIds: (workspaceIds) =>
this.emitWorkspaceUpdatesForWorkspaceIds(workspaceIds),
markWorkspaceArchiving: (workspaceIds, archivingAt) =>
this.markWorkspaceArchiving(workspaceIds, archivingAt),
clearWorkspaceArchiving: (workspaceIds) => this.clearWorkspaceArchiving(workspaceIds),
assertWorkspaceAutomationAllowed: (workspaceId) =>
assertWorkspaceAutomationAllowedForWorkspace(this.workspaceRegistry, workspaceId),
killTerminalsForWorkspace: (workspaceId) =>
this.terminalController.killTerminalsForWorkspace(workspaceId),
stopWorkspaceSetup: (workspaceId) => this.workspaceSetupRuntime.stop(workspaceId),
sessionLogger: this.sessionLogger,
},
{
scope: { kind: "workspace", workspaceId: existing.workspaceId },
requestId: request.requestId,
},
),
);
const archivedWorkspace = await this.workspaceRegistry.get(request.workspaceId);
@@ -7569,6 +7639,7 @@ export class Session {
private async handleSendAgentMessageRequest(
msg: Extract<SessionInboundMessage, { type: "send_agent_message_request" }>,
signal?: AbortSignal,
): Promise<void> {
const resolved = await this.resolveAgentIdentifier(msg.agentId);
if (!resolved.ok) {
@@ -7584,7 +7655,21 @@ export class Session {
return;
}
let cancellation: Promise<unknown> | undefined;
const abort = () => {
if (this.agentManager.getAgent(resolved.agentId)) {
cancellation ??= this.agentManager.cancelAgentRun(resolved.agentId).then((result) => {
if (result.status === "refused")
throw new AgentRequestError("agent_request_outcome_unknown");
return result;
});
void cancellation.catch(() => undefined);
}
};
signal?.addEventListener("abort", abort, { once: true });
if (signal?.aborted) abort();
try {
signal?.throwIfAborted();
const agentId = resolved.agentId;
const prompt = buildAgentPrompt(msg.text, msg.images, msg.attachments);
@@ -7598,9 +7683,11 @@ export class Session {
"agent.session.send_agent_message",
);
const send = async () => {
signal?.throwIfAborted();
const result = await sendPromptToAgent({
agentManager: this.agentManager,
agentStorage: this.agentStorage,
signal,
agentId,
prompt,
messageId: msg.messageId,
@@ -7608,8 +7695,12 @@ export class Session {
clearPendingPermissions: true,
logger: this.sessionLogger,
});
if (signal?.aborted) {
await this.agentManager.cancelAgentRun(agentId);
signal.throwIfAborted();
}
if (result.disposition === "turn_started") {
await waitForAgentRunStartWithTimeout(this.agentManager, agentId);
await waitForAgentRunStartWithTimeout(this.agentManager, agentId, signal);
}
};
if (msg.messageId) {
@@ -7650,6 +7741,9 @@ export class Session {
error: errorToFriendlyMessage(error),
},
});
} finally {
signal?.removeEventListener("abort", abort);
await cancellation;
}
}
@@ -1,3 +1,4 @@
import { AgentRequests } from "./agent/requests/index.js";
import { createAgentRequestsStub } from "./test-utils/session-stubs.js";
import { execFileSync } from "node:child_process";
import {
@@ -932,6 +933,126 @@ test("client heartbeat clears attention for the focused terminal", async () => {
});
});
test("expiry after agent registration removes its durable record before creation can retry", async () => {
const workdir = mkdtempSync(path.join(tmpdir(), "paseo-canceled-create-"));
const logger = createTestLogger();
const agentStorage = new AgentStorage(path.join(workdir, "agents"), logger);
const agentManager = new AgentManager({
clients: { codex: new CreateAgentTestClient() },
registry: agentStorage,
logger,
});
const projectRegistry = new FileBackedProjectRegistry(
path.join(workdir, "projects.json"),
logger,
);
const workspaceRegistry = new FileBackedWorkspaceRegistry(
path.join(workdir, "workspaces.json"),
logger,
);
let expire!: () => void;
const requests = new AgentRequests(path.join(workdir, "requests"), {
now: () => 0,
schedule(callback) {
expire = callback;
return () => {};
},
});
let registeredId: string | undefined;
const unsubscribe = agentManager.subscribe(
(event) => {
if (event.type === "agent_state" && registeredId === undefined) {
registeredId = event.agent.id;
expire();
}
},
{ replayState: false },
);
try {
const emitted: SessionOutboundMessage[] = [];
const session = asTestSession(
new Session({
agentRequests: requests,
clientId: "test-client",
serverId: "test-server",
permissions: OWNER_PERMISSIONS,
appVersion: null,
onMessage: (message) => emitted.push(message),
logger: asSessionLogger(logger),
downloadTokenStore: asDownloadTokenStore(),
pushNotifications: asPushNotifications(),
paseoHome: path.join(workdir, "paseo-home"),
agentManager,
agentStorage,
projectRegistry,
workspaceRegistry,
scheduleService: asScheduleService(),
checkoutDiffManager: asCheckoutDiffManager({
subscribe: async () => ({
initial: { cwd: workdir, files: [], error: null },
unsubscribe: () => {},
}),
scheduleRefreshForCwd: () => {},
onWorkspaceStateMayHaveChanged: () => {},
invalidateForge: () => {},
getMetrics: () => ({
checkoutDiffTargetCount: 0,
checkoutDiffSubscriptionCount: 0,
checkoutDiffWatcherCount: 0,
checkoutDiffFallbackRefreshTargetCount: 0,
}),
dispose: () => {},
}),
workspaceGitService: createNoopWorkspaceGitService(),
daemonConfigStore: asDaemonConfigStore({
get: () => ({ mcp: { injectIntoAgents: false }, providers: {} }),
onChange: () => () => {},
}),
mcpBaseUrl: null,
stt: null,
tts: null,
providerSnapshotManager: createProviderSnapshotManagerStub().manager,
terminalManager: null,
}),
);
await session.handleMessage({
type: "create_agent_request",
requestId: "canceled",
idempotencyKey: "conversation",
operation: { key: "arrival", deadlineAt: "2026-09-09T00:00:00Z" },
config: { provider: "codex", cwd: workdir },
});
await requests.cancelAndSettle("arrival");
expect(registeredId).toEqual(expect.any(String));
expect(agentManager.listAgents()).toEqual([]);
expect(await agentStorage.list()).toEqual([]);
expect(await requests.inspectOperation("arrival", "conversation")).toEqual({
outcome: "settled",
agentId: null,
});
unsubscribe();
await session.handleMessage({
type: "create_agent_request",
requestId: "retry",
idempotencyKey: "conversation",
operation: { key: "next", deadlineAt: "2026-09-09T00:00:00Z" },
config: { provider: "codex", cwd: workdir },
});
expect(agentManager.listAgents()).toHaveLength(1);
expect(
emitted.filter(
(message) => message.type === "status" && message.payload.status === "agent_created",
),
).toHaveLength(1);
} finally {
unsubscribe();
await Promise.all(agentManager.listAgents().map((agent) => agentManager.closeAgent(agent.id)));
await agentManager.flush();
rmSync(workdir, { recursive: true, force: true });
}
});
test("create_agent_request keeps requested child cwd when grouped under an existing parent workspace", async () => {
const workdir = mkdtempSync(path.join(tmpdir(), "paseo-create-agent-cwd-"));
try {
@@ -117,6 +117,108 @@ describe("workspace recovery", () => {
expect(unarchived).toEqual([workspace.workspaceId]);
});
test("a repeated restore of an already active workspace succeeds without another unarchive", async () => {
const workspace = createWorkspace({ archivedAt: null });
const { service, unarchived } = createHarness({ workspace, directories: [workspace.cwd] });
await expect(service.restore(workspace.workspaceId)).resolves.toEqual({
workspaceId: workspace.workspaceId,
action: "unarchive",
});
expect(unarchived).toEqual([]);
});
test("an active workspace with a missing directory cannot report a successful restore", async () => {
const workspace = createWorkspace({ archivedAt: null });
const { service, unarchived } = createHarness({ workspace });
await expect(service.restore(workspace.workspaceId)).rejects.toThrow();
expect(unarchived).toEqual([]);
});
test("expiry after filesystem recreation rolls back the new checkout", async () => {
const { tempDir, repoDir } = createGitRepository();
const branch = "feature/canceled-restore";
execFileSync("git", ["branch", branch], { cwd: repoDir, stdio: "pipe" });
const paseoHome = join(tempDir, "paseo-home");
const worktreesRoot = join(tempDir, "worktrees");
const created = await createWorktree({
cwd: repoDir,
worktreeSlug: "canceled-restore",
source: { kind: "checkout-branch", branchName: branch },
runSetup: false,
paseoHome,
worktreesRoot,
});
const worktreeRoot = realpathSync(created.worktreePath);
rmSync(worktreeRoot, { recursive: true, force: true });
const workspace = createWorkspace({
cwd: worktreeRoot,
branch,
worktreeRoot,
mainRepoRoot: repoDir,
});
const controller = new AbortController();
let unarchived = false;
const service = createWorkspaceRecoveryService({
paseoHome,
worktreesRoot,
getWorkspace: async () => workspace,
getProject: async () => createProject({ rootPath: repoDir }),
isDirectory: async (target) => {
const exists = existsSync(target) && statSync(target).isDirectory();
if (target === worktreeRoot && exists) controller.abort(new Error("expired"));
return exists;
},
unarchiveWorkspace: async () => {
unarchived = true;
},
});
await expect(service.restore(workspace.workspaceId, controller.signal)).rejects.toThrow(
"expired",
);
expect(unarchived).toBe(false);
expect(existsSync(worktreeRoot)).toBe(false);
expect(
execFileSync("git", ["worktree", "list", "--porcelain"], {
cwd: repoDir,
stdio: "pipe",
}).toString(),
).not.toContain(worktreeRoot);
});
test("expiry during restore preparation cannot unarchive the workspace", async () => {
const workspace = createWorkspace({ kind: "directory", branch: null });
let release!: () => void;
const gate = new Promise<void>((resolve) => {
release = resolve;
});
let entered!: () => void;
const started = new Promise<void>((resolve) => {
entered = resolve;
});
let unarchived = false;
const service = createWorkspaceRecoveryService({
paseoHome: "/paseo-home",
worktreesRoot: "/worktrees",
getWorkspace: async () => workspace,
getProject: async () => createProject(),
isDirectory: async () => {
entered();
await gate;
return true;
},
unarchiveWorkspace: async () => {
unarchived = true;
},
});
const controller = new AbortController();
const restoring = service.restore(workspace.workspaceId, controller.signal);
await started;
controller.abort(new Error("expired"));
release();
await expect(restoring).rejects.toThrow("expired");
expect(unarchived).toBe(false);
});
test("does not offer recovery for a missing non-worktree directory", async () => {
const workspace = createWorkspace({ kind: "directory", branch: null });
const { service } = createHarness({ workspace });
@@ -40,7 +40,10 @@ export type WorkspaceRecoveryState =
export interface WorkspaceRecoveryService {
inspect(workspaceId: string): Promise<WorkspaceRecoveryState>;
restore(workspaceId: string): Promise<{ workspaceId: string; action: WorkspaceRecoveryAction }>;
restore(
workspaceId: string,
signal?: AbortSignal,
): Promise<{ workspaceId: string; action: WorkspaceRecoveryAction }>;
}
type RecoveryPlan =
@@ -78,7 +81,7 @@ export function createWorkspaceRecoveryService(deps: {
message: "This workspace is no longer known to the host.",
};
}
if (!workspace.archivedAt) {
if (!workspace.archivedAt && (await deps.isDirectory(workspace.cwd))) {
return {
kind: "unavailable",
workspaceId,
@@ -87,6 +90,14 @@ export function createWorkspaceRecoveryService(deps: {
};
}
if (!workspace.archivedAt) {
return {
kind: "unavailable",
workspaceId,
reason: "workspace_directory_missing",
message: "The workspace directory no longer exists.",
};
}
const project = await deps.getProject(workspace.projectId);
if (!project) {
return {
@@ -140,15 +151,20 @@ export function createWorkspaceRecoveryService(deps: {
async function restore(
workspaceId: string,
signal?: AbortSignal,
): Promise<{ workspaceId: string; action: WorkspaceRecoveryAction }> {
signal?.throwIfAborted();
const resolved = await resolveRecovery(workspaceId);
signal?.throwIfAborted();
if (resolved.kind === "unavailable") {
if (resolved.reason === "workspace_not_archived") return { workspaceId, action: "unarchive" };
throw new Error(resolved.message);
}
if (resolved.kind === "restore") {
await recreateArchivedWorktree(resolved.workspace, resolved.sourceRepoRoot);
await recreateArchivedWorktree(resolved.workspace, resolved.sourceRepoRoot, signal);
}
signal?.throwIfAborted();
await deps.unarchiveWorkspace(resolved.workspace);
return { workspaceId, action: resolved.kind };
}
@@ -156,6 +172,7 @@ export function createWorkspaceRecoveryService(deps: {
async function recreateArchivedWorktree(
workspace: PersistedWorkspaceRecord,
sourceRepoRoot: string,
signal?: AbortSignal,
): Promise<void> {
const branch = workspace.branch;
if (!branch) {
@@ -200,6 +217,7 @@ export function createWorkspaceRecoveryService(deps: {
}
try {
signal?.throwIfAborted();
const recreatedWorkspacePath = mapWorkspaceCwdToWorktree({
sourceWorktreePath: previousWorktreePath,
workspaceCwd: workspace.cwd,
@@ -217,6 +235,7 @@ export function createWorkspaceRecoveryService(deps: {
message: `Selected project directory is missing from the restored worktree: ${recreatedWorkspacePath}`,
});
}
signal?.throwIfAborted();
} catch (error) {
return rollbackCreatedPaseoWorktree(
{
@@ -58,11 +58,14 @@ interface FakeAgentSessionOptions {
sessionId?: string;
memoryMarker?: string | null;
closeSession?: () => Promise<void>;
beforeStartTurn?: () => Promise<void>;
onStartTurn?: (prompt: AgentPromptInput) => void;
}
export interface TestAgentClientOptions {
beforeCreateSession?: () => Promise<void>;
closeSession?: () => Promise<void>;
beforeStartTurn?: () => Promise<void>;
onStartTurn?: (prompt: AgentPromptInput) => void;
supportsMcpServers?: boolean;
}
@@ -336,6 +339,7 @@ class FakeAgentSession implements AgentSession {
private activeForegroundTurnId: string | null = null;
private readonly closeSession: (() => Promise<void>) | undefined;
private readonly beforeStartTurn: (() => Promise<void>) | undefined;
private readonly onStartTurn: ((prompt: AgentPromptInput) => void) | undefined;
constructor(options: FakeAgentSessionOptions) {
@@ -349,6 +353,7 @@ class FakeAgentSession implements AgentSession {
this.memoryMarker = options.memoryMarker ?? null;
this.closeSession = options.closeSession;
this.onStartTurn = options.onStartTurn;
this.beforeStartTurn = options.beforeStartTurn;
this.historyPath = path.join(
tmpdir(),
"paseo-fake-provider-history",
@@ -433,6 +438,7 @@ class FakeAgentSession implements AgentSession {
}
async startTurn(prompt: AgentPromptInput): Promise<{ turnId: string }> {
await this.beforeStartTurn?.();
if (this.activeForegroundTurnId) {
throw new Error("A foreground turn is already active");
}
@@ -1202,12 +1208,14 @@ class FakeAgentClient implements AgentClient {
config: AgentSessionConfig,
_launchContext?: AgentLaunchContext,
): Promise<AgentSession> {
await this.options.beforeCreateSession?.();
return new FakeAgentSession({
providerName: this.provider,
config: { ...config },
supportsMcpServers: this.options.supportsMcpServers,
closeSession: this.options.closeSession,
onStartTurn: this.options.onStartTurn,
beforeStartTurn: this.options.beforeStartTurn,
});
}
@@ -1233,6 +1241,7 @@ class FakeAgentClient implements AgentClient {
memoryMarker: typeof marker === "string" ? marker : null,
closeSession: this.options.closeSession,
onStartTurn: this.options.onStartTurn,
beforeStartTurn: this.options.beforeStartTurn,
});
}
@@ -286,6 +286,12 @@ export function createAgentRequestsStub(): SessionOptions["agentRequests"] {
return agentId;
},
send: (input) => input.send(),
run: (_startup, operation) => operation(),
control: async (_context, _request, operation) => {
await operation();
},
cancelOperation: async () => ({ agentId: null, outcome: "settled" }),
inspectOperation: async () => ({ agentId: null, outcome: "settled" }),
};
}
@@ -650,6 +650,7 @@ export class VoiceAssistantWebSocketServer {
pluginRuntime?: SessionOptions["pluginRuntime"],
orchestrationSkills?: SessionOptions["orchestrationSkills"],
workspaceLabelService?: WorkspaceLabelService,
agentRequests?: AgentRequests,
) {
this.logger = logger.child({ module: "websocket-server" });
this.workspaceSetupRuntime = workspaceSetupRuntime;
@@ -668,7 +669,7 @@ export class VoiceAssistantWebSocketServer {
this.orchestrationSkills = orchestrationSkills;
this.agentManager = agentManager;
this.agentStorage = agentStorage;
this.agentRequests = new AgentRequests(join(paseoHome, "agent-requests"));
this.agentRequests = agentRequests ?? new AgentRequests(join(paseoHome, "agent-requests"));
this.projectRegistry = projectRegistry ?? createNoopProjectRegistry();
this.workspaceRegistry = workspaceRegistry ?? createNoopWorkspaceRegistry();
this.workspaceLabelService = workspaceLabelService ?? null;
@@ -1633,6 +1634,7 @@ export class VoiceAssistantWebSocketServer {
...(this.serverCapabilities ? { capabilities: this.serverCapabilities } : {}),
features: {
agentRequestReceipts: true,
agentRequestCancellation: true,
hubAgentRpc: true,
// COMPAT(directorySync): added in v0.3.x, remove gate after 2027-02-12.
directorySync: true,
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/website",
"version": "0.8.0",
"version": "0.8.0-beta.1",
"private": true,
"type": "module",
"scripts": {
+21 -16
View File
@@ -188,21 +188,26 @@ An environment or dynamic named-agent expression must have a finite set of possi
### Steps
| Field | Required | Notes |
| ----------------- | -------- | -------------------------------------------------------------------------------------------------------------------- |
| `id` | yes | Unique within the workflow. |
| `environment` | yes | Literal environment name or finite expression resolving to one. |
| `max_runtime` | yes | Step hard limit. |
| `idle_timeout` | yes | Idle limit no longer than `max_runtime`. |
| `startup_timeout` | no | Step startup waiting budget. See [startup timeout](/docs/hub/configuration#startup-timeout) for defaults and limits. |
| `agent` | yes | Named agent, finite expression selecting a named agent, or complete static inline agent. |
| `prompt` | yes | Ordered `text` and `include` blocks. |
| `if` | no | Expression deciding whether the step runs. |
| `env` | no | Environment variables from connection values. |
| `output.schema` | no | JSON Schema for structured step output. |
| `allow_outputs` | no | Provider output capabilities with optional `max` and `required`. |
| `auto_archive` | no | Archive the agent after the step ends. |
| `github` | no | Explicit GitHub authority for this step. |
| Field | Required | Notes |
| --------------- | -------- | ---------------------------------------------------------------------------------------- |
| `id` | yes | Unique within the workflow. |
| `environment` | yes | Literal environment name or finite expression resolving to one. |
| `max_runtime` | yes | Absolute step limit, including agent startup. |
| `idle_timeout` | yes | Idle limit no longer than `max_runtime`. |
| `agent` | yes | Named agent, finite expression selecting a named agent, or complete static inline agent. |
| `prompt` | yes | Ordered `text` and `include` blocks. |
| `if` | no | Expression deciding whether the step runs. |
| `env` | no | Environment variables from connection values. |
| `output.schema` | no | JSON Schema for structured step output. |
| `allow_outputs` | no | Provider output capabilities with optional `max` and `required`. |
| `auto_archive` | no | Archive the agent after the step ends. |
| `github` | no | Explicit GitHub authority for this step. |
`max_runtime` starts when Hub dispatches the step. Preparing a filesystem worktree, creating the provider agent, restoring a continuation workspace, and acknowledging the initial prompt all consume that budget. The deadline does not reset when startup finishes or activity arrives. The trigger's whole-run deadline can end the step sooner. Provider-specific startup failures can also end a step before its deadline.
`idle_timeout` starts alongside dispatch. An `initializing` or `running` agent status clears the idle deadline; an `idle` status starts it again. Meaningful agent activity refreshes an armed idle deadline. Connection heartbeats do not count as agent activity. Allow enough idle time for preparation before the daemon reports an active agent.
Continuation requires a daemon that supports cancelable agent requests. Update the daemon if Hub requests an update. When a deadline expires, Hub ends the step and reconciles daemon cleanup before another step can use the same conversation. If a daemon restart leaves the operation's outcome unknown, inspect the agent and workspace in Paseo before retrying with a new conversation key; Hub does not automatically repeat an ambiguous launch or prompt.
An inline agent is static and complete:
@@ -271,7 +276,7 @@ Keys use the existing expression syntax and must resolve to a non-empty string o
An existing session keeps its daemon, agent configuration, target, environment, and tool contracts. Changing those settings for the same key fails with an explanation; choose a different key or **New agent**. Prompts and output destinations belong to each arrival and may change. A worktree branch is chosen when the session is first created and reused on later arrivals.
A follow-up steers the active agent without extending its runtime deadline or credential expiry. With a `run.github` grant or connection token in `run.env`, follow-ups share the active agent’s credentials. Once all requests finish, Hub revokes leased tokens; the next arrival starts a new agent with fresh credentials. Agents without temporary credentials can be reused after completion.
Triggers that mint temporary environment credentials, including a `run.github` grant or a connection token in `run.env`, must choose **New agent** when the event has a conversation or uses a custom key. These credentials expire with the execution, and an existing agent's environment cannot be refreshed. Hub-managed reply tools remain available with continuation.
### Upgrading
-17
View File
@@ -64,23 +64,6 @@ A Discord starter uses `discord.mention`, your Discord user ID, and `discord.rep
Setup asks before replacing the selected trigger file. It preserves other triggers and any existing legacy bundle. Read [Hub security](/docs/hub/security) before widening `from_users` or the agent's authority.
## Startup timeout
Hub waits up to **two minutes** for agent startup, including worktree creation, provider startup, and initial prompt acceptance. For a slower machine, set `run.startup_timeout` in the trigger YAML:
```yaml
name: inspect
on:
manual.run: {}
run:
target: { daemon: devbox, cwd: /workspace/project }
agent: { provider: codex, mode: full-access }
startup_timeout: 5m
prompt: Inspect this repository and summarize its current state.
```
Use a positive duration in `ms`, `s`, `m`, or `h`, up to `24h`. Omitting the field uses `2m`. The existing `max_runtime` and `idle_timeout` limits still apply during startup and can expire sooner. This setting changes Hub's waiting budget; provider-specific timeouts remain in effect.
## Deploy from the CLI
Run from the repository root:
+2 -2
View File
@@ -37,7 +37,7 @@ steps:
${{ paseo.prompt }}
```
The agent can use `git` and `gh` within the declared repositories and permissions. See [agent continuation](/docs/hub/configuration/hub-yml#agent-continuation) for the token lifecycle when requests continue an agent.
The agent can use `git` and `gh` within the declared repositories and permissions. Hub mints the token when the step starts and revokes it when execution ends.
## Fields
@@ -73,4 +73,4 @@ env:
SOME_TOKEN: "${{ paseo.connections.some-connection.token }}"
```
Hub resolves the value when it prepares the agent's environment. See [Hub security](/docs/hub/security) for provider and host boundaries.
Hub resolves the value for the step and does not persist it. See [Hub security](/docs/hub/security) for provider and host boundaries.
+2 -2
View File
@@ -44,7 +44,7 @@ If the daemon is offline or needs a newer Paseo version, the agent selectors sho
Dashboard triggers default to **Same conversation**. Messages in the same Slack or Discord thread, events on the same GitHub issue or pull request, and events on the same Linear issue continue the existing agent in that project. An event without a conversation starts a new agent.
If the agent is busy, the new prompt steers its current work. Each arrival keeps its own output limits and completion status. If a reusable workspace is archived, Hub asks Paseo to restore it before sending the prompt.
If the agent is busy, the new prompt steers its current work. If its workspace is archived, Hub asks Paseo to restore it before sending the prompt. Each arrival still has its own deadline, output limits, and completion status.
Choose **Custom key** to group arrivals by an input, or **New agent** to keep them separate. A self-contained trigger document can express the same choice:
@@ -67,7 +67,7 @@ run:
prompt: Handle this request and call finish_execution when complete.
```
The [continuation reference](/docs/hub/configuration/hub-yml#agent-continuation) covers keys and agent reuse. The run detail shows whether each arrival created, continued, or restored an agent.
The [continuation reference](/docs/hub/configuration/hub-yml#agent-continuation) describes keys and compatibility. The run detail shows whether each arrival created, continued, or restored an agent.
Hub includes an `executionId` in each prompt. When using a continuing agent, pass that ID to `reply` and `finish_execution`. These tools act on that arrival's destination and contract; an old or unrelated execution ID is rejected.