Compare commits

..
Author SHA1 Message Date
Mohamed Boudra 70300fcda0 chore(release): cut 0.17.0 2026-11-21 11:48:43 +01:00
Mohamed Boudra c89a4f18c1 docs(changelog): prepare 0.17.0 stable 2026-11-21 11:40:24 +01:00
Mohamed Boudra 1fe7bf1ccc feat(hub): let Hub sessions list daemon projects (#10392)
Allow trigger editors to discover working directories on the connected daemon through the existing project list RPC.
2026-11-21 16:41:17 +07:00
Mohamed Boudra b3ea018d77 fix(app): show the quota forecast as a plain datapoint on the usage line (#10385)
The forecast sat right-aligned and tone-coloured beside the reset line, so it
read as a second kind of information. It is now one more ' · '-separated
datapoint after the reset countdown and exact time; the meter keeps the tone.
2026-11-21 16:17:21 +07:00
Mohamed Boudra daa6b5cc24 Preserve agent recovery when stopping Paseo from a terminal (#10381)
* fix(server): preserve agent recovery on foreground shutdown

A terminal interrupt could reach provider runtimes before Paseo captured running agents. The development watcher also sent the interrupt down the daemon tree, including detached children. Keep provider shutdown under the supervisor's IPC lifecycle.

* fix(dev): keep protocol and client watchers running

Pass the watch flag through the final npm workspace command. Verify both watchers start before testing the dev runner shutdown.

* test(ci): exercise foreground shutdown with dependency watchers
2026-11-21 16:05:48 +07:00
paseo-ai[bot] 2bc10ff540 fix: update lockfile signatures and Nix hash [skip ci] 2026-11-21 09:01:59 +00:00
Mohamed Boudra 24a30b183a Polish Antigravity tool calls in the timeline (#10379)
* fix(providers): render Antigravity tools with timeline details

* fix(providers): preserve search queries and ambiguous MCP names

* fix(app): bound tool call diff previews
2026-11-21 15:54:07 +07:00
Mohamed Boudra 1bd9b4673d Update the Hub guides for self-contained triggers (#10375)
* docs(hub): update guides for self-contained triggers

* docs(hub): match Activity and integration controls to the dashboard

* docs(hub): clarify overview and legacy bundle deployment
2026-11-21 15:34:59 +07:00
Mohamed Boudra c9159df62a Suggest Antigravity skills inside prompts (#10383)
Preserve the provider command kind so Antigravity skills appear in inline autocomplete. Keep the built-in ACP commands available at the start of the prompt.
2026-11-21 15:09:28 +07:00
Mohamed Boudra d154df3165 Let plugins manage worktree creation, removal, and restoration (#10278)
* feat(plugins): let plugins manage worktree create, remove, and restore

Adds server.registerWorktreeManager({ create, remove?, restore? }) so external worktree tools such as Worktrunk can own Git worktree creation, removal, and restoration instead of overloading worktree.create.before.

Keeping worktree.create.before purely transformative preserves multi-plugin chaining, rollback, and the 30s hook budget, while giving manager operations a 120s budget matching git worktree commands. Paseo snapshots existing worktrees before create so managers cannot hijack pre-existing user worktrees, writes comparison-base and owning plugin metadata into paseo/worktree.json and the workspace record, saves refs/paseo/kept-commits before removal so restore stays safe, and falls back to built-in Git if a manager declines or is disabled.

* fix(plugins): harden worktree manager lifecycle, rollback, and schema

* fix(plugins): pass untrusted on create, clean up rejected worktrees, and sync docs

* refactor(plugins): unify worktree manager checkout flow and metadata rules

* fix(plugins): verify managed worktree ownership and restore targets

A failed callback does not establish ownership of worktrees created during its call. Require the manager to identify the checkout before Paseo attempts rollback, and verify the requested Git target before reopening a restored workspace.

* fix(plugins): preserve worktree setup on retry and refresh branch bases

A failed setup could leave a new branch behind and send the retry through the built-in checkout. Use the manager's reported branch creation status during rollback. Share base preparation so both checkout paths start from the updated remote-tracking ref.

* fix(plugins): preserve managed checkout targets and rollback

Keep branch creation ownership with the linked checkout so a failed after-hook can be retried with the same branch. Leave same-repository change requests with a local branch collision to the checkout path that fetches the change request head. Use the worktree timeout for compatibility commands.

* fix(worktrees): carry source trust and await managed creation

Preserve fork provenance for manager callbacks and the workspace record. Honor tracking branch creation in the manager example and let the CLI wait on the existing workspace creation lifecycle.

* fix(plugins): verify PR head commits, restore CLI worktree RPC, and fix Windows rollback paths

* fix(plugins): pre-resolve PR head, use NUL worktree snapshots, and wait on CLI worktree create

* fix(plugins): unify worktree list reader with Git 2.35 fallback and fetch PR head once

* fix(plugins): require exact worktree snapshot for managers and configure PR push remotes on adoption

* fix(server): coordinate workspace restores across daemon sessions

* fix(server): coordinate archive, undo, and restore across daemon checkout boundary

* fix: serialize open-project with checkout archive, sync sibling owners, lift client timeouts, bump plugin version

* fix: forbid nested secondary worktrees, preserve nested checkouts on archive, wait on openProject

* fix(server): refuse deleting a worktree containing a live nested Git worktree

* test(server): normalize Windows paths and teardown command in worktree-manager E2E

* fix(server): guard cross-repo nested checkouts on delete and share checkout trust across sibling workspaces

* fix(worktrees): scope nested checkout protection to managed worktrees

The removal scan treated dependency clones and recursive submodules as independent worktrees. Identify linked worktrees through Git metadata and use the scan only for manager-owned removals.

* test(worktrees): accept native line endings in archive fixtures

The nested submodule fixture checks that Git populated the checkout. The README line endings depend on the runner's Git configuration.

* docs(plugins): document the example manager Git requirement

* fix(worktrees): name the manager that returns an invalid path

The destination validator serves both creation hooks and managers. Keep its errors about the path so the caller can identify the plugin and operation.
2026-11-21 13:51:28 +07:00
paseo-bot[bot] 0a3fed0643 test(server): wait for file observation before atomic replacement (#10372)
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-21 06:45:56 +00:00
Mohamed Boudra fd2f885afd Restore a host's workspaces when its cached directory is evicted (#10318)
* fix(app): restore a host's workspaces after its cached directory is evicted

A host could keep a current directory checkpoint in the replica cache with
none of the rows it described. The daemon then answered "no changes" since
that cursor, and the sidebar had no projects to place cached workspaces
under, so every workspace for that host vanished and stayed missing across
restarts.

The cache already refused mutations for an evicted host, but it checked at
the moment a mutation was queued. Eviction happens later, inside the
serialized write, so anything queued before the eviction ran was still
written, checkpoint included. The check moves into materializePendingChanges
so it runs in the same serialized step that evicts, which also covers an
eviction that lands while an earlier persist is still indexing the store.

Checking at queue time was also losing good data: once a host was
invalidated, every mutation was dropped, including updates accepted between
a reconnect's baseline replacement and its write. Those are kept now,
because the baseline is in the same pending batch.

Version 1 checkpoints could have been written by that path, so they are no
longer trusted. A reader discards them and keeps the cached rows, so the
sidebar still paints from cache and each host re-syncs its directory once.
Later launches resume incrementally.

Both the race and the recovery live in the shared cache, so this covers iOS,
Android, web, and Electron. It does not address two tabs or windows sharing
one IndexedDB database, where another connection evicts the host.

* fix(app): hold workspace updates that arrive while the directory cache loads

A project update received while the cached directory was being read went
straight into the replica. It advanced the project cursor before any refresh
had established a baseline, and saved that cursor to the cache. On an install
damaged before the eviction fix, that write replaced the version 1 checkpoint
with a version 2 one before the reader could reject it. The refresh then asked
for project changes after the live update, the daemon had none, and projects
missing from the cache stayed missing across restarts.

Agents already open a transaction before the cache load, so their updates are
recorded and applied over the refreshed snapshot. Workspaces now do the same.
An update during the load also stops the cached cursors being adopted, so the
refresh fetches full snapshots, which is the recovery a damaged cache needs.

* fix(app): advance directory cursors from live updates only after a refresh

A live update moved the directory cursor whenever no refresh was in flight,
including when no refresh had ever completed on the current subscriptions.
If the first sync after discarding a version 1 checkpoint failed, the next
project update saved a cursor at its own sequence with only that project
stored. The retry asked for changes after it, the daemon had none, and the
other projects stayed missing across restarts. The previous commit closed
this window during the cache load only; a failed refresh reopened it.

A live event's sequence covers everything before it only when a refresh
completed on the subscriptions that delivered it, which is what
satisfiedDemandSource already records. Live events now update rows either
way but move the cursor only in that state, so a cursor never skips changes
the client did not receive. Once a refresh completes, live updates advance
the cursor as before.

The sidebar recovery e2e fixture unwrapped the checkpoint only when it was
version 1, so the version 2 writer made it abort before damaging the cache.
It now reads either envelope and stores the damage as version 1, the format
this branch stops trusting, so the test fails against the previous cache
module and passes here.

* fix(app): apply the eviction rule to malformed-row repairs

Repairing a malformed directory row reads the checkpoint, drops the affected
cursor, and writes the rest back. That write went straight to the row store
through queueOperation, outside the eviction check in the regular persist
path. If a write evicted the same host while the repair was reading, the
repair stored a checkpoint for a host with no directory rows, the state this
branch exists to prevent.

All three repair writes now go through one helper that runs in the serialized
writer and drops the checkpoint upsert when the host has been evicted since.
The deletes still apply.

* fix(app): record a host eviction only after its delete commits

Eviction marked the host as evicted before deleteHost ran. If storage aborted
that delete, the rows stayed stored but the mark remained. A malformed-row
repair running behind it trusted the mark: it skipped the checkpoint update
yet still deleted the row, leaving a workspace cursor with no workspace. The
next refresh then resumed past that workspace.

The mark is now set after the delete commits, so it always matches storage.
A failed eviction leaves no mark, and the repair updates the row and its
cursor together.
2026-11-21 13:31:29 +07:00
Mohamed Boudra 988cf4bec8 fix(acp): keep Antigravity turn open while non-daemon background tools run (#10310)
* fix(acp): keep Antigravity turn open while non-daemon background tools run

* fix(acp): address deferred turn steer, drain race, and echo scoping

* fix(acp): serialize deferred steers, gate on end_turn, and lock canceled tool updates

* fix(acp): unify deferred reply settlement and accept queued steers on send

* fix(acp): keep Stop unblocked during queued steers and gate reply settlement on post-tool updates

* fix(acp): ignore in-flight steer usage for settlement and deliver queued steers after RPC errors

* fix(acp): keep deferred background job running when a steer rejects and honor Stop cancellation

* fix(acp): settle deferred turn immediately on Stop even if a steer RPC is unanswered

* fix(acp): bound Stop drain for in-flight steers and tear down wedged runtimes

* fix(acp): terminate wedged child process on Stop timeout and reject prompts on closed sessions

* fix(acp): reject replacement prompt if session retires during interrupt and preserve streaming reply id

* fix(acp): always retire deferred ACP session cleanly on Stop and clear fallback id on steer start

* fix(server): reopen retired plugin sessions before applying configuration changes

* fix(acp): close deferred process before emitting cancel and synchronize mid-shutdown config changes

* fix(acp): do not reset deferred settle timer on excluded daemon tool updates

* fix(acp): release deferred turn when tool is reclassified as excluded

* fix(acp): gate deferred settlement reset on open qualifying tool membership

* fix(acp): decouple deferred reply tracking from open tool blockers

* fix(acp): track post-end_turn wire order and preserve settled reply across tool completion

* fix(acp): unify wire-order prompt response tracking and exclude daemon reclassification from crossedEndTurn

* fix(acp): preserve settled background reply across steers that start no new tools

* fix(acp): distinguish settled-with-open-tools reply state across steers

* fix(acp): share close and deferred interrupt retirement across overlapping calls

* fix(acp): make deferred retirement sole owner of prompt rejection and cancellation

* fix(acp): centralize session retirement in retireSession so rejected prompts never suppress session.closed

* fix(acp): bound session/cancel write in deferred retirement before teardown

* fix(acp,server): force-abort stalled connectors on Stop timeout and bound cancel wait in AgentManager

* fix(acp,server): enforce shutdown deadline on connector close and bound settings wait on queued Stop

* fix(acp): scope connector shutdown deadline to deferred retirement and finalize on late close
2026-11-21 13:27:45 +07:00
Mohamed Boudra a6a9d0b8c7 Keep agent timelines responsive after reconnect (#10368)
* fix(app): recover agent timelines after reconnect

Reconnecting resumed every hidden chat as soon as the visible chat settled, overwhelming the daemon when many tabs were open. Bound hidden catch-ups and give the visible chat priority. Refocusing a failed chat or foregrounding the app retries the timed-out fetch once per transition.

* fix(app): retain timeline retry paging policy

Carry the overflow policy with a failed request so retrying reconnect does not replay the entire backlog. Clear a failed attempt's parked follow-up so the scheduler can drain explicit retries without using the manual Retry indicator.

* fix(app): preserve history when a queued gap resumes

Choose the paging policy after a queued gap acquires its fetch slot. The tail that held the gap can establish coverage while it waits, so basing the policy on earlier coverage can unnecessarily replace history.
2026-11-21 13:26:44 +07:00
Mohamed Boudra b71b4d584a Keep live images responsive during history replay (#10371)
* perf(server): keep live image output responsive during history replay

A large attachment blocked all other provider images behind a daemon-wide queue. Share writes only for matching files and reduce the filesystem and decode turns needed to publish each image.

* fix(server): validate image storage and share the decode budget

Validate the cached directory before reusing an attachment and set file permissions without reading the process umask. A shared deadline bounds the work of concurrent decoders in each event-loop slice.

* perf(server): charge image decode slices for active work

Filesystem waits and unrelated event-loop work exhausted the wall-clock deadline before decoding started. Measure synchronous decode work against the shared budget so busy replay avoids extra yields.
2026-11-21 13:26:39 +07:00
Mohamed Boudra c9a7d523f8 Speed up Claude history reload under daemon load (#10369)
* fix(server): speed up Claude history resume under load

Each record read gave other daemon work another event-loop turn before history could finish rebuilding. Read transcript windows and resolve workflow links in one scan so resume preserves the full conversation with far fewer I/O waits.

* test(server): cover Claude replay across read windows

* fix(server): yield during dense Claude history replay

A read window of short records can keep transcript parsing and timeline ingest on the microtask queue for hundreds of milliseconds. Yield on elapsed time within each window so the daemon can service other requests.
2026-11-21 13:26:35 +07:00
Mohamed Boudra ca514b34a7 Keep Android composer buttons working on the first tap (#10308)
* fix(app): keep mobile composer buttons working on the first tap

After an unmatched native touch start (such as dismissing an Android Modal while a finger is down, double ACTION_DOWN in ReactRootView/ReactModalHostView, or a dropped synthetic ACTION_CANCEL), ReactFabric's ResponderEventPlugin left trackedTouchCount > 0 for the rest of the session because it only incremented/decremented by 1 instead of reconciling with nativeEvent.touches.length.

On Android, @mattermost/react-native-paste-input's PasteTextInput also set onSelectionChangeShouldSetResponder={emptyFunctionThatReturnsTrue} (which React Native core only sets on iOS). Whenever trackedTouchCount stayed > 0, every keystroke in the composer triggered topSelectionChange and let PasteTextInput claim the JS responder, swallowing the first tap on Send or any toolbar button.

Reconcile trackedTouchCount from nativeEvent.touches.length in ReactFabric (dev, prod, profiling) and ReactNativeResponder, remove the iOS-only onSelectionChangeShouldSetResponder prop from Android PasteTextInput, and drop the now-redundant createReactCancelEvent multi-pointer workaround from react-native-gesture-handler.

* fix(app): clear stale touchBank contacts when native touches reach zero

When a multi-touch gesture is cancelled by a single-pointer synthetic ACTION_CANCEL (or a prior touch end was dropped), ResponderTouchHistoryStore.recordTouchTrack only ended contacts listed in changedTouches, leaving other touchBank entries marked touchActive = true even though nativeEvent.touches.length was 0.

Mark all remaining active touchBank entries inactive whenever topTouchEnd or topTouchCancel reports 0 active native touches, so onResponderTerminate sees a clean touchHistory without needing RNGH's createReactCancelEvent workaround.
2026-11-21 13:20:02 +07:00
180 changed files with 16976 additions and 4806 deletions
+5
View File
@@ -579,6 +579,11 @@ jobs:
if: ${{ env.PASEO_CLI_TEST_SHARD == '3' }}
run: npm run test:unit --workspace=@getpaseo/cli
# The dependency watchers write build outputs, so run them after the parallel CLI tests.
- name: Run dev watch shutdown regression
if: ${{ env.PASEO_CLI_TEST_SHARD == '3' }}
run: node --import tsx packages/cli/tests/23-daemon-sigint-supervisor.test.ts --dev-watch
cli-tests-2:
name: cli-tests (shard 2/3)
needs: changes
+40 -10
View File
@@ -1,56 +1,86 @@
# Changelog
## 0.17.0-beta.1 - 2026-11-19
## 0.17.0 - 2026-11-21
- **Use existing worktrees:** Start a workspace in a worktree you already have, or create one from any branch or pull request. ([#10190](https://github.com/getpaseo/paseo/pull/10190))
- **Antigravity approvals and history:** Pick a permission mode, answer tool approvals, import CLI sessions and see your history when you reopen a chat. ([#10193](https://github.com/getpaseo/paseo/pull/10193))
- **Watch pull requests:** Agents can watch a GitHub PR and get notified when checks, reviews or comments change. ([#10148](https://github.com/getpaseo/paseo/pull/10148))
- **Use existing worktrees:** Start a workspace in a worktree you already have, or create one from a branch or pull request. Plugins can manage worktree creation, removal, and restoration. When you branch off a fork PR or MR, choose Run setup to approve workspace automation. ([#10190](https://github.com/getpaseo/paseo/pull/10190), [#10278](https://github.com/getpaseo/paseo/pull/10278))
- **Update providers in Paseo:** See each provider's status, installed version, and available updates in the provider list. Open a provider's settings from Settings, setup, or the model picker to update supported CLIs and watch their output. ([#9568](https://github.com/getpaseo/paseo/pull/9568), [#9661](https://github.com/getpaseo/paseo/pull/9661))
- **Provider quota forecasts:** Usage estimates when a quota will run out or how much will remain at reset, based on your current pace. The forecast appears inline with the reset time. ([#10289](https://github.com/getpaseo/paseo/pull/10289), [#10385](https://github.com/getpaseo/paseo/pull/10385))
- **Watch PRs and MRs:** Ask an agent to watch a GitHub, GitLab, Gitea, Forgejo, or Codeberg change request for updates to checks, reviews, or comments. Stop a watch from Background work. ([#10148](https://github.com/getpaseo/paseo/pull/10148), [#10279](https://github.com/getpaseo/paseo/pull/10279), [#10280](https://github.com/getpaseo/paseo/pull/10280))
- **Heartbeats in Background work:** See and stop an agent's heartbeats next to its background tasks. ([#10097](https://github.com/getpaseo/paseo/pull/10097), [#10216](https://github.com/getpaseo/paseo/pull/10216))
- **Agent messages wait their turn:** Reports and notifications from other agents arrive when the current turn ends instead of interrupting it. ([#9757](https://github.com/getpaseo/paseo/pull/9757))
- **Antigravity approvals and history:** Choose a permission mode, respond to tool approvals, and import or reopen sessions. Use Antigravity CLI 1.5.0 or later on the daemon host, and include `acp` if you override its command. In Hub, reselect the model and thinking level if a saved model ID includes an old effort suffix. ([#10193](https://github.com/getpaseo/paseo/pull/10193))
- **More goose models:** Select models from all providers configured in goose. Existing goose settings and sessions carry over to the bundled plugin. ([#9719](https://github.com/getpaseo/paseo/pull/9719) by [@i386](https://github.com/i386))
- **Plugin agent instructions:** Plugins can add their own instructions to agents. ([#9781](https://github.com/getpaseo/paseo/pull/9781))
### Added
- Added OpenRouter credit balances and API key spending to Usage and `paseo usage` ([#10269](https://github.com/getpaseo/paseo/pull/10269))
- Added Antigravity account quotas to Usage ([#10232](https://github.com/getpaseo/paseo/pull/10232) by [@luoph](https://github.com/luoph), [@RRD-dev](https://github.com/RRD-dev))
- Added Antigravity skill suggestions when you type `/` inside a prompt ([#10383](https://github.com/getpaseo/paseo/pull/10383))
- Added bundled orchestration skills to Antigravity on hosts where Paseo skills are installed ([#10273](https://github.com/getpaseo/paseo/pull/10273))
- Added shortcuts to open the model picker and cycle thinking levels with Cmd/Ctrl+/ and Cmd/Ctrl+Shift+/ ([#10147](https://github.com/getpaseo/paseo/pull/10147))
- Added agent settings to Command Center search before the first message ([#10182](https://github.com/getpaseo/paseo/pull/10182) by [@cleiter](https://github.com/cleiter))
- Added Rewind to Command Center for the latest turn ([#10144](https://github.com/getpaseo/paseo/pull/10144))
- Added a separate Ultracode toggle for eligible Claude models ([#10150](https://github.com/getpaseo/paseo/pull/10150) by [@fivetaku](https://github.com/fivetaku))
- Added Flex speed for Codex ([#9809](https://github.com/getpaseo/paseo/pull/9809) by [@qjqqyy](https://github.com/qjqqyy))
- Added syntax highlighting for shell scripts and Dockerfiles ([#10178](https://github.com/getpaseo/paseo/pull/10178))
- Added project listing on connected daemons for Hub sessions with `hub.execute` ([#10392](https://github.com/getpaseo/paseo/pull/10392))
- Added labels and workspace IDs to `paseo ls --json` ([#10076](https://github.com/getpaseo/paseo/pull/10076))
### Changed
- Changed `browser_new_tab` to ask agents to choose a Desktop when several are connected ([#10189](https://github.com/getpaseo/paseo/pull/10189))
- Changed workspace Git status to reuse its snapshot after a short reconnect when the checkout has not changed ([#10142](https://github.com/getpaseo/paseo/pull/10142) by [@VladimirGVP](https://github.com/VladimirGVP))
- Changed Appearance content width to Default (820 px), Wide (1,200 px), and Full presets that resize open chats, the composer, and Markdown previews together ([#10231](https://github.com/getpaseo/paseo/pull/10231))
- Changed Antigravity tool cards to show shell commands and output, file diffs, and Paseo tool details ([#10379](https://github.com/getpaseo/paseo/pull/10379))
- Changed Clone from GitHub to show matching private repositories first ([#10264](https://github.com/getpaseo/paseo/pull/10264))
- Changed worktree teardown to keep the worktree when the command exceeds one minute or the `worktree.teardownTimeoutMs` limit in `paseo.json` ([#9852](https://github.com/getpaseo/paseo/pull/9852) by [@ragokan](https://github.com/ragokan))
- Changed workspace navigation to acknowledge taps promptly and initially load fewer offscreen chat rows on mobile ([#9887](https://github.com/getpaseo/paseo/pull/9887))
- Changed worktree teardown to stop after one minute by default and keep the worktree; set `worktree.teardownTimeoutMs` in `paseo.json` for longer commands ([#9852](https://github.com/getpaseo/paseo/pull/9852) by [@ragokan](https://github.com/ragokan))
- Changed workspace Git status to reuse its snapshot after a short reconnect when the checkout has not changed ([#10142](https://github.com/getpaseo/paseo/pull/10142) by [@VladimirGVP](https://github.com/VladimirGVP))
- Changed `browser_new_tab` to ask agents to choose a Desktop when several are connected ([#10189](https://github.com/getpaseo/paseo/pull/10189))
### Fixed
- Fixed an online host's workspaces staying missing after the app evicts its cached directory ([#10318](https://github.com/getpaseo/paseo/pull/10318))
- Fixed chat history timing out when many open chats refresh at once after reconnecting ([#10368](https://github.com/getpaseo/paseo/pull/10368))
- Fixed slow reopening of long Claude chats while the daemon is busy ([#10369](https://github.com/getpaseo/paseo/pull/10369))
- Fixed images from a live reply waiting for images in another chat's history to load ([#10371](https://github.com/getpaseo/paseo/pull/10371))
- Fixed agent recovery failing and idle agents showing errors after stopping a foreground daemon with Ctrl+C on macOS or Linux ([#10381](https://github.com/getpaseo/paseo/pull/10381))
- Fixed Antigravity turns ending while a background command is still running ([#10310](https://github.com/getpaseo/paseo/pull/10310))
- Fixed slash suggestions failing when a provider reports duplicate command names ([#10275](https://github.com/getpaseo/paseo/pull/10275))
- Fixed stale Codex subagent statuses after reopening or rewinding the parent chat ([#10171](https://github.com/getpaseo/paseo/pull/10171) by [@AnalyticETH](https://github.com/AnalyticETH))
- Fixed Usage showing the previous Claude account's quota after switching accounts ([#10236](https://github.com/getpaseo/paseo/pull/10236))
- Fixed the sidebar usage row dropping period labels such as `5h` and `wk` when multiple usage windows are pinned ([#10274](https://github.com/getpaseo/paseo/pull/10274))
- Fixed Changes failing to recognize a checkout immediately after restoring its worktree ([#10224](https://github.com/getpaseo/paseo/pull/10224), [#10304](https://github.com/getpaseo/paseo/pull/10304))
- Fixed double-click word selection and triple-click line selection in diffs ([#10252](https://github.com/getpaseo/paseo/pull/10252) by [@pedrovieira](https://github.com/pedrovieira))
- Fixed the composer and chat column losing alignment when Chat outline is enabled ([#10277](https://github.com/getpaseo/paseo/pull/10277))
- Fixed the archive shortcut failing when the active workspace's sidebar group is collapsed ([#10356](https://github.com/getpaseo/paseo/pull/10356) by [@hiennd-ctrl](https://github.com/hiennd-ctrl), [@neihyud](https://github.com/neihyud))
- Fixed Android composer buttons requiring a second tap after typing or zooming a chat image ([#10057](https://github.com/getpaseo/paseo/pull/10057), [#10308](https://github.com/getpaseo/paseo/pull/10308))
- Fixed swiping a terminal in an Android browser opening the keyboard when it was closed ([#10225](https://github.com/getpaseo/paseo/pull/10225) by [@tonylt](https://github.com/tonylt))
- Fixed Collapse turns hiding a finished OMP or Pi reply when an idle provider notice appears ([#10135](https://github.com/getpaseo/paseo/pull/10135))
- Fixed repeated finish notifications while an agent responds to background tasks and its earlier finish is unread ([#10200](https://github.com/getpaseo/paseo/pull/10200))
- Fixed an empty chat losing the prompt and start of a reply after reconnecting mid-reply ([#9723](https://github.com/getpaseo/paseo/pull/9723) by [@ragokan](https://github.com/ragokan))
- Fixed changes between Claude thinking levels stopping its background work ([#10008](https://github.com/getpaseo/paseo/pull/10008) by [@gilad-rubin](https://github.com/gilad-rubin))
- Fixed OpenCode turns staying running after a shared OpenCode service stops ([#10187](https://github.com/getpaseo/paseo/pull/10187))
- Fixed OMP denying an approved tool call when session or grant choices were offered ([#10126](https://github.com/getpaseo/paseo/pull/10126) by [@dsingal0](https://github.com/dsingal0))
- Fixed a Codex message stopped before its turn starts showing an error instead of canceled ([#9931](https://github.com/getpaseo/paseo/pull/9931) by [@3ae3ae](https://github.com/3ae3ae))
- Fixed Changes failing to open when Git metadata watching reaches its limit ([#10188](https://github.com/getpaseo/paseo/pull/10188))
- Fixed copying selected reply text into plain-text targets with unwanted Markdown syntax ([#10079](https://github.com/getpaseo/paseo/pull/10079) by [@danberindei](https://github.com/danberindei))
- Fixed file views losing their scroll position when switching Preview and Source, except HTML previews on iOS ([#10195](https://github.com/getpaseo/paseo/pull/10195) by [@apple-ouyang](https://github.com/apple-ouyang))
- Fixed file tabs in split panes showing or focusing the wrong file ([#9888](https://github.com/getpaseo/paseo/pull/9888) by [@KosmoCHE](https://github.com/KosmoCHE))
- Fixed touch-screen submenus closing as soon as they open ([#10175](https://github.com/getpaseo/paseo/pull/10175) by [@christiantwu](https://github.com/christiantwu))
- Fixed dictation failing after another chat that used the microphone closes ([#10185](https://github.com/getpaseo/paseo/pull/10185) by [@Brandon168](https://github.com/Brandon168))
- Fixed composer taps being lost on Android after zooming a chat image ([#10057](https://github.com/getpaseo/paseo/pull/10057))
- Fixed clipped text on Samsung DeX ([#9995](https://github.com/getpaseo/paseo/pull/9995) by [@easyhunjune](https://github.com/easyhunjune))
- Fixed workspace images in chat failing to load after a slow host connection ([#10111](https://github.com/getpaseo/paseo/pull/10111) by [@ragokan](https://github.com/ragokan))
- Fixed desktop browser screenshots returning fully transparent images ([#9807](https://github.com/getpaseo/paseo/pull/9807) by [@monarchmaisuriya](https://github.com/monarchmaisuriya))
- Fixed Mermaid flowcharts with `@` in labels showing source instead of the diagram ([#10165](https://github.com/getpaseo/paseo/pull/10165) by [@monarchmaisuriya](https://github.com/monarchmaisuriya))
- Fixed hidden background workspaces triggering the dock badge and favicon ([#9983](https://github.com/getpaseo/paseo/pull/9983))
- Fixed desktop sidebar navigation crowding out workspaces ([#9903](https://github.com/getpaseo/paseo/pull/9903) by [@pentatonic-alex](https://github.com/pentatonic-alex))
- Fixed historical closed PR badges appearing on a repository's default branch ([#10053](https://github.com/getpaseo/paseo/pull/10053))
- Fixed plugin agents failing to reopen after their provider closes the session ([#10153](https://github.com/getpaseo/paseo/pull/10153))
- Fixed plugin screens and settings failing to use plugin state hooks ([#10049](https://github.com/getpaseo/paseo/pull/10049))
- Fixed a Codex message stopped before its turn starts showing an error instead of canceled ([#9931](https://github.com/getpaseo/paseo/pull/9931) by [@3ae3ae](https://github.com/3ae3ae))
- Fixed historical closed PR badges appearing on a repository's default branch ([#10053](https://github.com/getpaseo/paseo/pull/10053))
### Plugins
- Added a `focusHost` navigation option for plugins to select the destination host in the sidebar when opening a workspace or agent ([#5574](https://github.com/getpaseo/paseo/pull/5574) by [@discwl](https://github.com/discwl))
## 0.16.2 - 2026-11-18
+40 -10
View File
@@ -1,56 +1,86 @@
# Changelog
## 0.17.0-beta.1 - 2026-11-19
## 0.17.0 - 2026-11-21
- **使用现有 worktree**:在已有的 worktree 中启动工作区,或从任意分支或 PR 创建 worktree。([#10190](https://github.com/getpaseo/paseo/pull/10190))
- **Antigravity 审批和历史记录**:选择权限模式、回复工具审批、导入 CLI 会话,并在重新打开对话时查看历史记录。([#10193](https://github.com/getpaseo/paseo/pull/10193))
- **监视 PR**:Agent 可以监视 GitHub PR,在检查、审查或评论有变化时收到通知。([#10148](https://github.com/getpaseo/paseo/pull/10148))
- **使用现有 worktree**:在已有的 worktree 中启动工作区,或从分支或 PR 创建 worktree。插件可以管理 worktree 的创建、移除和恢复。从 fork 的 PR 或 MR 创建分支时,选择“运行设置”以批准工作区自动化。([#10190](https://github.com/getpaseo/paseo/pull/10190), [#10278](https://github.com/getpaseo/paseo/pull/10278))
- **在 Paseo 中更新 Provider**:在 Provider 列表中查看各 Provider 的状态、已安装版本和可用更新。从设置、初次配置或模型选择器打开 Provider 设置,即可更新受支持的 CLI 并查看输出。([#9568](https://github.com/getpaseo/paseo/pull/9568), [#9661](https://github.com/getpaseo/paseo/pull/9661))
- **Provider 配额预测**:“使用情况”页面根据当前使用速度估算配额何时用完,或重置时还会剩下多少。预测结果显示在重置时间同一行中。([#10289](https://github.com/getpaseo/paseo/pull/10289), [#10385](https://github.com/getpaseo/paseo/pull/10385))
- **监视 PR 和 MR**:让 Agent 监视 GitHub、GitLab、Gitea、Forgejo 或 Codeberg 上的 PR 或 MR,跟踪检查、审查或评论的变化。你可以在后台任务中停止监视。([#10148](https://github.com/getpaseo/paseo/pull/10148), [#10279](https://github.com/getpaseo/paseo/pull/10279), [#10280](https://github.com/getpaseo/paseo/pull/10280))
- **在后台任务中查看 heartbeat**:在 Agent 的后台任务旁查看和停止 heartbeat。([#10097](https://github.com/getpaseo/paseo/pull/10097), [#10216](https://github.com/getpaseo/paseo/pull/10216))
- **Agent 消息排队等待**:其他 Agent 的报告和通知会在当前轮次结束后到达,不会打断当前轮次。([#9757](https://github.com/getpaseo/paseo/pull/9757))
- **Antigravity 审批和历史记录**:选择权限模式、回复工具审批,以及导入或重新打开会话。请在 daemon 主机上使用 Antigravity CLI 1.5.0 或更新版本,如果覆盖了启动命令请包含 `acp`。如果 Hub 中保存的模型 ID 含有旧的推理强度后缀,请重新选择模型和思考级别。([#10193](https://github.com/getpaseo/paseo/pull/10193))
- **更多 goose 模型**:从 goose 中已配置的所有 Provider 选择模型。现有 goose 设置和会话会迁移到内置插件。([#9719](https://github.com/getpaseo/paseo/pull/9719),贡献者:[@i386](https://github.com/i386))
- **插件 Agent 指令**:插件可以向 Agent 添加自己的指令。([#9781](https://github.com/getpaseo/paseo/pull/9781))
### 新增
- 在“使用情况”页面和 `paseo usage` 中新增 OpenRouter 余额和 API 密钥支出 ([#10269](https://github.com/getpaseo/paseo/pull/10269))
- 在“使用情况”页面新增 Antigravity 账号配额 ([#10232](https://github.com/getpaseo/paseo/pull/10232),贡献者:[@luoph](https://github.com/luoph), [@RRD-dev](https://github.com/RRD-dev))
- 在提示词中输入 `/` 时,新增 Antigravity 技能建议 ([#10383](https://github.com/getpaseo/paseo/pull/10383))
- 在已安装 Paseo 技能的主机上,为 Antigravity 新增内置编排技能 ([#10273](https://github.com/getpaseo/paseo/pull/10273))
- 新增 Cmd/Ctrl+/ 和 Cmd/Ctrl+Shift+/ 快捷键,用于打开模型选择器和切换思考级别 ([#10147](https://github.com/getpaseo/paseo/pull/10147))
- 新增在发送第一条消息前通过命令中心搜索 Agent 设置 ([#10182](https://github.com/getpaseo/paseo/pull/10182),贡献者:[@cleiter](https://github.com/cleiter))
- 新增在命令中心回退最近轮次的操作 ([#10144](https://github.com/getpaseo/paseo/pull/10144))
- 新增符合条件的 Claude 模型的独立 Ultracode 开关 ([#10150](https://github.com/getpaseo/paseo/pull/10150),贡献者:[@fivetaku](https://github.com/fivetaku))
- 新增 Codex Flex 速度选项 ([#9809](https://github.com/getpaseo/paseo/pull/9809),贡献者:[@qjqqyy](https://github.com/qjqqyy))
- 新增 shell 脚本和 Dockerfile 的语法高亮 ([#10178](https://github.com/getpaseo/paseo/pull/10178))
- 为具有 `hub.execute` 权限的 Hub 会话新增列出已连接 daemon 活跃项目的能力 ([#10392](https://github.com/getpaseo/paseo/pull/10392))
- 新增 `paseo ls --json` 输出的标签和工作区 ID ([#10076](https://github.com/getpaseo/paseo/pull/10076))
### 变更
- 连接多个 Desktop 时,`browser_new_tab` 会让 Agent 选择打开标签页的 Desktop ([#10189](https://github.com/getpaseo/paseo/pull/10189))
- 工作区 Git 状态在短暂重连且检出的内容未更改时复用之前的快照 ([#10142](https://github.com/getpaseo/paseo/pull/10142),贡献者:[@VladimirGVP](https://github.com/VladimirGVP))
- 将“外观”中的内容宽度改为默认(820 px)、宽版(1,200 px)和全宽预设,同时调整已打开对话、Composer 和 Markdown 预览的宽度 ([#10231](https://github.com/getpaseo/paseo/pull/10231))
- Antigravity 工具卡片现在显示 shell 命令及输出、文件 diff 和 Paseo 工具详情 ([#10379](https://github.com/getpaseo/paseo/pull/10379))
- 从 GitHub 克隆时,优先显示匹配的私有仓库 ([#10264](https://github.com/getpaseo/paseo/pull/10264))
- worktree 清理命令在超过默认的一分钟或 `paseo.json` 中 `worktree.teardownTimeoutMs` 限制时保留 worktree ([#9852](https://github.com/getpaseo/paseo/pull/9852),贡献者:[@ragokan](https://github.com/ragokan))
- 工作区导航会立即响应点击,并在手机端初始加载时减少屏幕外的对话行数 ([#9887](https://github.com/getpaseo/paseo/pull/9887))
- worktree 清理命令默认在一分钟后停止并保留 worktree;如需更长时间,可在 `paseo.json` 中设置 `worktree.teardownTimeoutMs` ([#9852](https://github.com/getpaseo/paseo/pull/9852),贡献者:[@ragokan](https://github.com/ragokan))
- 工作区 Git 状态在短暂重连且检出的内容未更改时复用之前的快照 ([#10142](https://github.com/getpaseo/paseo/pull/10142),贡献者:[@VladimirGVP](https://github.com/VladimirGVP))
- 连接多个 Desktop 时,`browser_new_tab` 会让 Agent 选择打开标签页的 Desktop ([#10189](https://github.com/getpaseo/paseo/pull/10189))
### 修复
- 修复应用清除主机目录缓存后,在线主机的工作区一直不显示的问题 ([#10318](https://github.com/getpaseo/paseo/pull/10318))
- 修复重新连接后多个已打开的对话同时刷新时,历史记录加载超时的问题 ([#10368](https://github.com/getpaseo/paseo/pull/10368))
- 修复 daemon 繁忙时,重新打开较长的 Claude 对话速度慢的问题 ([#10369](https://github.com/getpaseo/paseo/pull/10369))
- 修复当前回复中的图片等待另一个对话的历史图片加载的问题 ([#10371](https://github.com/getpaseo/paseo/pull/10371))
- 修复在 macOS 或 Linux 上用 Ctrl+C 停止前台 daemon 后,Agent 恢复失败且空闲 Agent 显示错误的问题 ([#10381](https://github.com/getpaseo/paseo/pull/10381))
- 修复 Antigravity 后台命令仍在运行时轮次就已结束的问题 ([#10310](https://github.com/getpaseo/paseo/pull/10310))
- 修复 Provider 返回重复命令名称时,斜杠建议列表出错的问题 ([#10275](https://github.com/getpaseo/paseo/pull/10275))
- 修复重新打开或回退父对话后,Codex 子 Agent 状态未更新的问题 ([#10171](https://github.com/getpaseo/paseo/pull/10171),贡献者:[@AnalyticETH](https://github.com/AnalyticETH))
- 修复切换 Claude 账号后,“使用情况”页面仍显示上一个账号配额的问题 ([#10236](https://github.com/getpaseo/paseo/pull/10236))
- 修复固定多个用量窗口时,侧边栏用量行隐藏 `5h` 和 `wk` 等周期标签的问题 ([#10274](https://github.com/getpaseo/paseo/pull/10274))
- 修复恢复 worktree 后,“更改”无法立即识别检出目录的问题 ([#10224](https://github.com/getpaseo/paseo/pull/10224), [#10304](https://github.com/getpaseo/paseo/pull/10304))
- 修复 diff 中双击选词和三击选行的问题 ([#10252](https://github.com/getpaseo/paseo/pull/10252),贡献者:[@pedrovieira](https://github.com/pedrovieira))
- 修复启用聊天大纲时,Composer 与对话栏对不齐的问题 ([#10277](https://github.com/getpaseo/paseo/pull/10277))
- 修复当前工作区所在的侧边栏分组折叠时,归档快捷键失效的问题 ([#10356](https://github.com/getpaseo/paseo/pull/10356),贡献者:[@hiennd-ctrl](https://github.com/hiennd-ctrl), [@neihyud](https://github.com/neihyud))
- 修复在 Android 上输入文字或缩放对话图片后,首次点击 Composer 按钮无效的问题 ([#10057](https://github.com/getpaseo/paseo/pull/10057), [#10308](https://github.com/getpaseo/paseo/pull/10308))
- 修复在 Android 浏览器中滑动终端时弹出已关闭的键盘的问题 ([#10225](https://github.com/getpaseo/paseo/pull/10225),贡献者:[@tonylt](https://github.com/tonylt))
- 修复启用“折叠轮次”时,空闲的 Provider 通知导致已完成的 OMP 或 Pi 回复被隐藏的问题 ([#10135](https://github.com/getpaseo/paseo/pull/10135))
- 修复 Agent 响应后台任务时,在之前的完成状态未读的情况下重复发送完成通知的问题 ([#10200](https://github.com/getpaseo/paseo/pull/10200))
- 修复空对话在回复中途重连后丢失提示词和回复开头的问题 ([#9723](https://github.com/getpaseo/paseo/pull/9723),贡献者:[@ragokan](https://github.com/ragokan))
- 修复切换 Claude 思考级别时停止后台任务的问题 ([#10008](https://github.com/getpaseo/paseo/pull/10008),贡献者:[@gilad-rubin](https://github.com/gilad-rubin))
- 修复共享 OpenCode 服务停止后轮次一直显示为运行中的问题 ([#10187](https://github.com/getpaseo/paseo/pull/10187))
- 修复 OMP 提供会话或授权选项时拒绝已批准工具调用的问题 ([#10126](https://github.com/getpaseo/paseo/pull/10126),贡献者:[@dsingal0](https://github.com/dsingal0))
- 修复 Codex 消息在轮次开始前停止时显示错误而非已取消的问题 ([#9931](https://github.com/getpaseo/paseo/pull/9931),贡献者:[@3ae3ae](https://github.com/3ae3ae))
- 修复 Git 元数据监听达到上限时无法打开“更改”的问题 ([#10188](https://github.com/getpaseo/paseo/pull/10188))
- 修复将选中的回复复制到纯文本目标时出现多余 Markdown 语法的问题 ([#10079](https://github.com/getpaseo/paseo/pull/10079),贡献者:[@danberindei](https://github.com/danberindei))
- 修复在预览和源码之间切换时文件视图丢失滚动位置的问题,iOS 的 HTML 预览除外 ([#10195](https://github.com/getpaseo/paseo/pull/10195),贡献者:[@apple-ouyang](https://github.com/apple-ouyang))
- 修复拆分窗格中的文件标签页显示或聚焦错误文件的问题 ([#9888](https://github.com/getpaseo/paseo/pull/9888),贡献者:[@KosmoCHE](https://github.com/KosmoCHE))
- 修复触摸屏上的子菜单打开后立即关闭的问题 ([#10175](https://github.com/getpaseo/paseo/pull/10175),贡献者:[@christiantwu](https://github.com/christiantwu))
- 修复关闭另一个使用过麦克风的对话后无法听写的问题 ([#10185](https://github.com/getpaseo/paseo/pull/10185),贡献者:[@Brandon168](https://github.com/Brandon168))
- 修复 Android 缩放对话图片后 Composer 点击失效的问题 ([#10057](https://github.com/getpaseo/paseo/pull/10057))
- 修复 Samsung DeX 上的文字被裁剪的问题 ([#9995](https://github.com/getpaseo/paseo/pull/9995),贡献者:[@easyhunjune](https://github.com/easyhunjune))
- 修复主机连接缓慢后对话中的工作区图片无法加载的问题 ([#10111](https://github.com/getpaseo/paseo/pull/10111),贡献者:[@ragokan](https://github.com/ragokan))
- 修复桌面浏览器截图返回全透明图片的问题 ([#9807](https://github.com/getpaseo/paseo/pull/9807),贡献者:[@monarchmaisuriya](https://github.com/monarchmaisuriya))
- 修复 Mermaid 流程图标签含有 `@` 时显示源码而非图表的问题 ([#10165](https://github.com/getpaseo/paseo/pull/10165),贡献者:[@monarchmaisuriya](https://github.com/monarchmaisuriya))
- 修复隐藏的后台工作区触发程序坞徽标和网站图标状态的问题 ([#9983](https://github.com/getpaseo/paseo/pull/9983))
- 修复桌面侧边栏导航占满工作区列表空间的问题 ([#9903](https://github.com/getpaseo/paseo/pull/9903),贡献者:[@pentatonic-alex](https://github.com/pentatonic-alex))
- 修复仓库默认分支显示历史已关闭 PR 徽标的问题 ([#10053](https://github.com/getpaseo/paseo/pull/10053))
- 修复 Provider 关闭会话后插件 Agent 无法重新打开的问题 ([#10153](https://github.com/getpaseo/paseo/pull/10153))
- 修复插件页面和设置无法使用插件状态钩子的问题 ([#10049](https://github.com/getpaseo/paseo/pull/10049))
- 修复 Codex 消息在轮次开始前停止时显示错误而非已取消的问题 ([#9931](https://github.com/getpaseo/paseo/pull/9931),贡献者:[@3ae3ae](https://github.com/3ae3ae))
- 修复仓库默认分支显示历史已关闭 PR 徽标的问题 ([#10053](https://github.com/getpaseo/paseo/pull/10053))
### 插件
- 新增插件导航 `focusHost` 选项,打开工作区或 Agent 时在侧边栏选中目标主机 ([#5574](https://github.com/getpaseo/paseo/pull/5574),贡献者:[@discwl](https://github.com/discwl))
## 0.16.2 - 2026-11-18
+7 -2
View File
@@ -582,12 +582,17 @@ host, kinds, and ids. Opening a cached workspace uses exact workspace and projec
directory scan. One invalid row is deleted and returned as a miss without affecting other rows.
An invalid directory row and its affected checkpoint cursor are repaired in one transaction, so a
later launch cannot accept a checkpoint for a partial baseline. Directory changes and their
checkpoint are also applied in one transaction. Reads wait for accepted changes to reach storage,
checkpoint are also applied in one transaction. A stored checkpoint carries a version. When a writer
bug could have stored a checkpoint without its directory, bump the version: older checkpoints are
rejected on read, cached rows still paint, and each host re-syncs its directory once. Reads wait for
accepted changes to reach storage,
then retry only when a requested row changes during the read. Unrelated agent streams do not
invalidate the read. Directory baseline replacements and host removal or renaming still invalidate
the affected reads.
The cache is capped at 32 MiB and evicts whole hosts in least-recently-written order. Budget
The cache is capped at 32 MiB and evicts whole hosts in least-recently-written order. After an
eviction, only a baseline replacement stores that host's directory again. Mutations queued around
the eviction are dropped when they are written, so a checkpoint never outlives its rows. Budget
bookkeeping may scan opaque row sizes during a deferred write, never during host registry startup or
before a requested cache row can paint. The row store is not encrypted. A cached timeline can contain
source code, prompts, and tool output; encrypted-at-rest storage is a separate security decision.
+12
View File
@@ -471,6 +471,18 @@ Workspace records decide ownership, including explicit non-ownership after recov
ownership checks prefer the marker-verified worktree root over the legacy
path shape: a plugin can place a worktree several directories below the default worktrees root.
A plugin can also take over worktree creation, removal, and restoration with
`server.registerWorktreeManager({ create, remove?, restore? })`. It runs after
`worktree.create.before` and before `worktree.create.after`, with a 120-second timeout matching Git
worktree commands. Paseo snapshots existing worktree paths before calling `create` so a manager
cannot adopt a pre-existing directory as Paseo-owned, verifies Git worktree postconditions, records
`worktreeManagerPluginId` in `paseo/worktree.json` and on the workspace record,
and skips first-agent branch auto-rename. Removal saves `refs/paseo/kept-commits/<sha>` before
calling the owning plugin's `remove`, and `create`, `remove`, and `restore` carry `untrusted` for fork
change requests; `remove` and `restore` fall back to built-in Git when the plugin declines or is disabled. See the
[worktree managers reference](../public-docs/plugins/reference.md#worktree-managers) and
`plugin-examples/worktrunk`.
Emit from the operation owner, not a client subscription. Provider history replay must not trigger
live hooks. Notifications must not be awaited inside agent mutations: a handler can send a prompt
or answer a permission through its own daemon session. Awaiting it there deadlocks that command.
@@ -0,0 +1,3 @@
- Use existing worktrees: Start a workspace in a worktree you already have, or create one from a branch or pull request. Plugins can manage worktree creation, removal, and restoration. When you branch off a fork PR or MR, choose Run setup to approve workspace automation.
Full notes: https://paseo.sh/changelog
@@ -0,0 +1,3 @@
- Use existing worktrees: Start a workspace in a worktree you already have, or create one from a branch or pull request. Plugins can manage worktree creation, removal, and restoration. When you branch off a fork PR or MR, choose Run setup to approve workspace automation.
Full notes: https://paseo.sh/changelog
@@ -0,0 +1,3 @@
- Use existing worktrees: Start a workspace in a worktree you already have, or create one from a branch or pull request. Plugins can manage worktree creation, removal, and restoration. When you branch off a fork PR or MR, choose Run setup to approve workspace automation.
Full notes: https://paseo.sh/changelog
@@ -0,0 +1,3 @@
- Use existing worktrees: Start a workspace in a worktree you already have, or create one from a branch or pull request. Plugins can manage worktree creation, removal, and restoration. When you branch off a fork PR or MR, choose Run setup to approve workspace automation.
Full notes: https://paseo.sh/changelog
+1 -1
View File
@@ -1 +1 @@
sha256-T3mbzIj0+IZBS4XA+4Ab6e6LtIi8PX4Rzs4wFEWeClk=
sha256-gUBXG6rGxAAMUDgSXQw6GzkJ8U0xEoL9X/kZkLM4uxg=
+29 -28
View File
@@ -1,12 +1,12 @@
{
"name": "paseo",
"version": "0.17.0-beta.1",
"version": "0.17.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "paseo",
"version": "0.17.0-beta.1",
"version": "0.17.0",
"hasInstallScript": true,
"license": "Apache-2.0",
"workspaces": [
@@ -37468,7 +37468,7 @@
},
"packages/app": {
"name": "@getpaseo/app",
"version": "0.17.0-beta.1",
"version": "0.17.0",
"dependencies": {
"@codemirror/commands": "6.10.4",
"@codemirror/language": "6.12.4",
@@ -37508,6 +37508,7 @@
"@xterm/addon-webgl": "0.20.0-beta.329",
"@xterm/xterm": "6.1.0-beta.336",
"buffer": "^6.0.3",
"diff": "8.0.3",
"expo": "~57.0.30",
"expo-asset": "~57.0.20",
"expo-audio": "~57.0.5",
@@ -39637,13 +39638,13 @@
},
"packages/cli": {
"name": "@getpaseo/cli",
"version": "0.17.0-beta.1",
"version": "0.17.0",
"license": "Apache-2.0",
"dependencies": {
"@clack/prompts": "^1.0.0",
"@getpaseo/client": "0.17.0-beta.1",
"@getpaseo/protocol": "0.17.0-beta.1",
"@getpaseo/server": "0.17.0-beta.1",
"@getpaseo/client": "0.17.0",
"@getpaseo/protocol": "0.17.0",
"@getpaseo/server": "0.17.0",
"chalk": "^5.3.0",
"commander": "^12.0.0",
"mime-types": "^2.1.35",
@@ -39890,11 +39891,11 @@
},
"packages/client": {
"name": "@getpaseo/client",
"version": "0.17.0-beta.1",
"version": "0.17.0",
"license": "Apache-2.0",
"dependencies": {
"@getpaseo/protocol": "0.17.0-beta.1",
"@getpaseo/relay": "0.17.0-beta.1",
"@getpaseo/protocol": "0.17.0",
"@getpaseo/relay": "0.17.0",
"ws": "^8.20.0",
"zod": "^4.4.3"
},
@@ -39906,7 +39907,7 @@
},
"packages/desktop": {
"name": "@getpaseo/desktop",
"version": "0.17.0-beta.1",
"version": "0.17.0",
"license": "Apache-2.0",
"dependencies": {
"@getpaseo/cli": "*",
@@ -40149,7 +40150,7 @@
},
"packages/expo-two-way-audio": {
"name": "@getpaseo/expo-two-way-audio",
"version": "0.17.0-beta.1",
"version": "0.17.0",
"license": "MIT",
"devDependencies": {
"@types/jest": "^29.5.14",
@@ -40195,7 +40196,7 @@
},
"packages/highlight": {
"name": "@getpaseo/highlight",
"version": "0.17.0-beta.1",
"version": "0.17.0",
"license": "Apache-2.0",
"dependencies": {
"@codemirror/language": "6.12.4",
@@ -40225,7 +40226,7 @@
},
"packages/plugin": {
"name": "@getpaseo/plugin",
"version": "0.17.0-beta.1",
"version": "0.17.0",
"license": "Apache-2.0",
"dependencies": {
"@agentclientprotocol/sdk": "^1.4.0",
@@ -40233,8 +40234,8 @@
"use-sync-external-store": "^1.6.0"
},
"devDependencies": {
"@getpaseo/client": "0.17.0-beta.1",
"@getpaseo/protocol": "0.17.0-beta.1",
"@getpaseo/client": "0.17.0",
"@getpaseo/protocol": "0.17.0",
"@types/node": "^20.9.0",
"@types/react": "~19.2.0",
"react": "19.2.3",
@@ -40244,8 +40245,8 @@
"zod": "^4.4.3"
},
"peerDependencies": {
"@getpaseo/client": "0.17.0-beta.1",
"@getpaseo/protocol": "0.17.0-beta.1",
"@getpaseo/client": "0.17.0",
"@getpaseo/protocol": "0.17.0",
"react": ">=19.1.0 <20",
"react-native": ">=0.81.5",
"zod": "^4.4.3"
@@ -40267,7 +40268,7 @@
},
"packages/protocol": {
"name": "@getpaseo/protocol",
"version": "0.17.0-beta.1",
"version": "0.17.0",
"license": "Apache-2.0",
"dependencies": {
"semver": "^7.8.5",
@@ -40295,7 +40296,7 @@
},
"packages/relay": {
"name": "@getpaseo/relay",
"version": "0.17.0-beta.1",
"version": "0.17.0",
"license": "Apache-2.0",
"dependencies": {
"@noble/ciphers": "^2.4.0",
@@ -40517,17 +40518,17 @@
},
"packages/server": {
"name": "@getpaseo/server",
"version": "0.17.0-beta.1",
"version": "0.17.0",
"license": "Apache-2.0",
"dependencies": {
"@agentclientprotocol/sdk": "^0.17.1",
"@anthropic-ai/claude-agent-sdk": "0.3.326",
"@anthropic-ai/sdk": "^0.104.2",
"@getpaseo/client": "0.17.0-beta.1",
"@getpaseo/highlight": "0.17.0-beta.1",
"@getpaseo/plugin": "0.17.0-beta.1",
"@getpaseo/protocol": "0.17.0-beta.1",
"@getpaseo/relay": "0.17.0-beta.1",
"@getpaseo/client": "0.17.0",
"@getpaseo/highlight": "0.17.0",
"@getpaseo/plugin": "0.17.0",
"@getpaseo/protocol": "0.17.0",
"@getpaseo/relay": "0.17.0",
"@isaacs/ttlcache": "^2.1.4",
"@modelcontextprotocol/sdk": "1.29.0",
"@opencode-ai/sdk": "1.14.46",
@@ -41474,7 +41475,7 @@
},
"packages/website": {
"name": "@getpaseo/website",
"version": "0.17.0-beta.1",
"version": "0.17.0",
"dependencies": {
"@cloudflare/vite-plugin": "^1.29.1",
"@cloudflare/workers-types": "^4.20260317.1",
@@ -43084,7 +43085,7 @@
},
"plugins": {
"name": "@getpaseo/builtin-plugins",
"version": "0.17.0-beta.1",
"version": "0.17.0",
"dependencies": {
"@getpaseo/plugin": "*",
"zod": "^4.4.3"
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "paseo",
"version": "0.17.0-beta.1",
"version": "0.17.0",
"private": true,
"description": "Paseo: voice-controlled development environment for local AI coding agents",
"keywords": [
@@ -38,7 +38,7 @@
"dev": "npm run dev:server",
"dev:win": "powershell ./scripts/dev.ps1",
"dev:server": "cross-env PASEO_LISTEN=127.0.0.1:6768 ./scripts/dev-daemon.sh",
"dev:server:watch": "concurrently --kill-others --names protocol,client,server --prefix-colors yellow,blue,cyan \"npm run watch:protocol\" \"npm run watch:client\" \"npm run dev:server:raw\"",
"dev:server:watch": "npm run dev --workspace=@getpaseo/server -- --watch-dependencies",
"dev:server:raw": "npm run dev --workspace=@getpaseo/server",
"dev:app": "cross-env PASEO_LISTEN=127.0.0.1:6768 EXPO_PORT=8081 ./scripts/dev-app.sh",
"dev:android": "npm run dev:android --workspace=@getpaseo/app",
@@ -206,13 +206,14 @@ async function simulateDamagedLegacyDirectoryCache(
return;
}
const stored = JSON.parse(checkpoint.payload);
// Accept either writer so this fixture also reproduces on the unfixed client.
const cursors = stored.version === 1 ? stored.cursors : stored;
if (!cursors.workspaces?.generation) {
// Read the cursors from whichever version wrote them, then store them as version 1:
// the format whose writer could keep a checkpoint after evicting the rows it describes.
const cursors = typeof stored.version === "number" ? stored.cursors : stored;
if (!cursors?.workspaces?.generation) {
transaction.abort();
return;
}
store.put({ ...checkpoint, payload: JSON.stringify(cursors) });
store.put({ ...checkpoint, payload: JSON.stringify({ version: 1, cursors }) });
for (const row of rows) {
if (
row.serverId === serverId &&
+3 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/app",
"version": "0.17.0-beta.1",
"version": "0.17.0",
"private": true,
"main": "index.ts",
"scripts": {
@@ -40,7 +40,7 @@
"dev:ios": "npm --prefix ../.. run build:client && cross-env APP_VARIANT=development expo run:ios",
"build:apk": "npm --prefix ../.. run build:apk",
"build:apk:arm64": "npm --prefix ../.. run build:apk:arm64",
"test:android": "expo prebuild --platform android --no-install && cd android && ./gradlew :paseo-native-trace:testReleaseUnitTest :paseo-hardware-keyboard:testReleaseUnitTest :react-native-enriched-markdown:testReleaseUnitTest --tests '*InlineCodeFormattingTest' --tests '*ListBlockquoteMeasurementTest' --no-daemon --max-workers=2 -Dorg.gradle.parallel=false"
"test:android": "expo prebuild --platform android --no-install && cd android && ./gradlew :paseo-native-trace:testReleaseUnitTest :paseo-hardware-keyboard:testReleaseUnitTest :react-native-enriched-markdown:testReleaseUnitTest --tests '*InlineCodeFormattingTest' --no-daemon --max-workers=2 -Dorg.gradle.parallel=false"
},
"dependencies": {
"@codemirror/commands": "6.10.4",
@@ -81,6 +81,7 @@
"@xterm/addon-webgl": "0.20.0-beta.329",
"@xterm/xterm": "6.1.0-beta.336",
"buffer": "^6.0.3",
"diff": "8.0.3",
"expo": "~57.0.30",
"expo-asset": "~57.0.20",
"expo-audio": "~57.0.5",
@@ -266,7 +266,33 @@ function renderCopyOutput() {
return <button type="button">Copy output</button>;
}
const searchQuery = "IANA example domains";
const queryOnlySearch = { type: "search", query: searchQuery, toolName: "web_search" } as const;
function renderSearchDetails() {
return <ToolCallDetailsContent detail={queryOnlySearch} />;
}
function SearchBadge() {
const [expanded, setExpanded] = React.useState(false);
const toggle = React.useCallback(() => setExpanded((current) => !current), []);
return (
<ExpandableBadge
label="Search"
isExpanded={expanded}
onToggle={toggle}
renderDetails={renderSearchDetails}
/>
);
}
describe("tool detail interaction", () => {
it("shows the query when an expanded search has no results", async () => {
act(() => root.render(<SearchBadge />));
await page.getByRole("button", { name: "Search" }).click();
await expect.element(page.getByText(searchQuery, { exact: true })).toBeVisible();
});
it("keeps detail controls in the tab order", async () => {
function Badge() {
const [expanded, setExpanded] = React.useState(true);
@@ -352,6 +352,9 @@ function buildSearchSections(detail: SearchDetail, ds: DetailStyles): ReactNode[
</View>,
);
}
if (out.length === 0 && detail.query) {
return [<ScrollablePlainTextSection key="search-query" text={detail.query} ds={ds} />];
}
return out;
}
@@ -10,7 +10,10 @@ import type {
DaemonClient,
WorkspaceLabelListPayload,
} from "@getpaseo/client/internal/daemon-client";
import type { SessionOutboundMessage } from "@getpaseo/protocol/messages";
import type {
SessionOutboundMessage,
WorkspaceDescriptorPayload,
} from "@getpaseo/protocol/messages";
import {
normalizeProjectDescriptor,
normalizeWorkspaceDescriptor,
@@ -1667,6 +1670,187 @@ it("fills every cached workspace beneath live updates received during the SQLite
database.close();
});
/**
* A host whose cache was damaged before the eviction fix: workspaces survived, project rows did not,
* and a version 1 checkpoint still claims the project directory is current. The daemon holds
* projects A and B; renaming A is its update at `renameSeq`.
*/
async function createDamagedLegacyProjectDirectory(serverId: string, renameSeq: number) {
serverIds.add(serverId);
const { cache, database, storage, reopen, holdRead } = createSqliteCache();
cache.setHosts([serverId]);
const workspacePayload = (id: string, projectId: string): WorkspaceDescriptorPayload => ({
id,
projectId,
projectDisplayName: projectId,
projectRootPath: `/repo/${projectId}`,
workspaceDirectory: `/repo/${projectId}`,
projectKind: "git",
workspaceKind: "local_checkout",
name: id,
status: "done",
statusEnteredAt: null,
activityAt: null,
archivingAt: null,
diffStat: null,
scripts: [],
});
const project = (projectId: string, projectDisplayName: string) => ({
projectId,
projectDisplayName,
projectRootPath: `/repo/${projectId}`,
projectKind: "git" as const,
});
const workspaceEntries = [workspacePayload("wa", "A"), workspacePayload("wb", "B")];
cache.replaceDirectoryBaseline(serverId, {
agents: new Map(),
workspaces: new Map(
workspaceEntries.map((entry) => [entry.id, normalizeWorkspaceDescriptor(entry)]),
),
projects: new Map(),
});
await cache.flush();
await storage.apply({
deletes: [],
upserts: [
{
serverId,
kind: "checkpoint",
id: "singleton",
payload: JSON.stringify({
version: 1,
cursors: { projects: { generation: "g", afterSeq: renameSeq - 1 } },
}),
},
],
});
const reopened = reopen();
reopened.setHosts([serverId]);
const client = new FakeDirectoryClient();
let failNextProjectRequest = false;
client.listProjects = async (options?: unknown): Promise<ProjectListResult> => {
client.lastProjectOptions = options;
if (failNextProjectRequest) {
failNextProjectRequest = false;
throw new Error("Request timed out");
}
const resumesAfterRename =
(options as { sync?: { afterSeq?: number } } | undefined)?.sync?.afterSeq === renameSeq;
return resumesAfterRename
? {
requestId: "projects",
projects: [],
sync: { generation: "g", headSeq: renameSeq, mode: "changes", removals: [] },
}
: {
requestId: "projects",
projects: [project("A", "Renamed"), project("B", "B")],
sync: { generation: "g", headSeq: renameSeq, mode: "snapshot", removals: [] },
};
};
client.fetchWorkspaces = async (): Promise<WorkspaceFetchResult> => ({
requestId: "workspaces",
entries: workspaceEntries,
emptyProjects: [],
pageInfo: { hasMore: false, nextCursor: null, prevCursor: null },
sync: { generation: "g", headSeq: 2, mode: "snapshot", removals: [] },
});
const directory = new DirectorySync(
serverId,
{
onAgentStoppedRunning: () => {},
markAgentLoading: () => {},
markAgentReady: () => {},
markAgentError: () => {},
},
reopened,
);
const store = useSessionStore.getState();
store.initializeSession(serverId, client as unknown as DaemonClient, 1);
store.updateSessionServerInfo(serverId, {
serverId,
hostname: null,
version: "test",
features: { workspaceMultiplicity: true, directorySync: true, projectList: true },
});
directory.connectionChanged({
client: client as unknown as DaemonClient,
status: "online",
source: { clientGeneration: 1, connectionEpoch: 1 },
});
return {
client,
directory,
holdRead,
failNextProjectRequest: () => {
failNextProjectRequest = true;
},
renameProjectA: () =>
client.emit({
type: "project.update",
payload: {
kind: "upsert",
project: project("A", "Renamed"),
generation: "g",
seq: renameSeq,
},
}),
sessionProjectIds: () =>
[...useSessionStore.getState().sessions[serverId].projects.keys()].sort(),
persistedProjectIds: async () => {
await reopened.flush();
const restarted = reopen();
restarted.setHosts([serverId]);
return [...(await restarted.readDirectory(serverId)).projects.keys()].sort();
},
close: async () => {
directory.dispose();
await reopened.flush();
database.close();
},
};
}
it("re-syncs every project when a project update lands while an untrusted cache loads", async () => {
const damaged = await createDamagedLegacyProjectDirectory("untrusted-checkpoint-race", 6);
try {
let renamed = false;
damaged.holdRead(async () => {
if (renamed) return;
renamed = true;
damaged.renameProjectA();
});
damaged.directory.setDemand({}, true);
await damaged.directory.refreshDemand();
expect(renamed).toBe(true);
expect(damaged.client.lastProjectOptions).toEqual({ sync: {} });
expect(damaged.sessionProjectIds()).toEqual(["A", "B"]);
expect(await damaged.persistedProjectIds()).toEqual(["A", "B"]);
} finally {
await damaged.close();
}
});
it("re-syncs every project when a project update lands after the first sync fails", async () => {
const damaged = await createDamagedLegacyProjectDirectory("failed-first-sync", 3);
try {
damaged.failNextProjectRequest();
damaged.directory.setDemand({}, true);
await expect(damaged.directory.refreshDemand()).rejects.toThrow("Request timed out");
damaged.renameProjectA();
await damaged.directory.refreshDemand();
expect(damaged.client.lastProjectOptions).toEqual({ sync: {} });
expect(damaged.sessionProjectIds()).toEqual(["A", "B"]);
expect(await damaged.persistedProjectIds()).toEqual(["A", "B"]);
} finally {
await damaged.close();
}
});
function createWorkspaceLabelDirectory(serverId: string) {
const { client, directory } = createDirectory(serverId, { workspaceLabels: true });
const store = useSessionStore.getState();
@@ -288,7 +288,7 @@ export class DirectorySync {
this.revision += 1;
if (this.agentTransactions.record(source, delta)) return;
this.agents.applyDelta(delta);
this.noteLiveCursor("agents", delta);
if (this.extendsRefreshedBaseline(source)) this.noteLiveCursor("agents", delta);
this.persistCheckpoint();
}
@@ -300,7 +300,7 @@ export class DirectorySync {
this.workspaceRevision += 1;
if (this.workspaceTransactions.record(source, delta)) return;
this.applyWorkspaceDelta(delta);
if (delta.kind !== "script_status")
if (delta.kind !== "script_status" && this.extendsRefreshedBaseline(source))
this.noteLiveCursor(
"projectId" in delta || "project" in delta ? "projects" : "workspaces",
delta,
@@ -308,6 +308,20 @@ export class DirectorySync {
this.persistCheckpoint();
}
/**
* A live event's sequence covers everything before it only when a refresh completed on the
* subscriptions that delivered it. Before that (first sync still pending or failed) or after
* they lapse, the client may have missed earlier changes, so the event updates rows but leaves
* the cursor where the next refresh can still fetch what was missed.
*/
private extendsRefreshedBaseline(source: DirectorySourceToken): boolean {
const refreshed = this.satisfiedDemandSource;
return (
refreshed?.clientGeneration === source.clientGeneration &&
refreshed.connectionEpoch === source.connectionEpoch
);
}
private observeDirectoryEvents(): void {
if (this.eventSubscription) return;
const { client, source } = this.requireOnline();
@@ -566,24 +580,16 @@ export class DirectorySync {
input: { subscribe?: boolean } | undefined,
loadDirectoryCache: boolean,
): Promise<void> {
if (loadDirectoryCache) await this.loadCachedDirectory();
if (loadDirectoryCache) {
this.primeWorkspaceTransactionForCacheLoad();
await this.loadCachedDirectory();
}
const onlineConnection = this.getOnlineConnection();
if (!onlineConnection) return;
const { client, source } = onlineConnection;
const transaction = this.workspaceTransactions.begin(source, () => {
const baseline = this.workspaces.snapshot();
return {
workspaces: new Map(baseline.workspaces),
projects: new Map(baseline.projects),
// Cache hydration can advance the live replica while these requests await responses.
// Every page must use the cursors belonging to the maps captured here.
requestCursors: { ...this.cursors },
syncCursors: {},
syncModes: {},
touchedWorkspaceIds: new Set(),
touchedProjectIds: new Set(),
};
});
const transaction = this.workspaceTransactions.begin(source, () =>
this.createWorkspaceRefreshSnapshot(),
);
try {
await this.waitForSessionMetadata(client, source);
const serverInfo = useSessionStore.getState().sessions[this.serverId]?.serverInfo;
@@ -807,6 +813,31 @@ export class DirectorySync {
}));
}
// Updates that arrive before a refresh completes have no trusted baseline to advance from.
// Holding them keeps their cursor out of the cache until the refresh they are applied over.
private primeWorkspaceTransactionForCacheLoad(): void {
const connection = this.getOnlineConnection();
if (!connection) return;
this.workspaceTransactions.begin(connection.source, () =>
this.createWorkspaceRefreshSnapshot(),
);
}
private createWorkspaceRefreshSnapshot(): WorkspaceRefreshSnapshot {
const baseline = this.workspaces.snapshot();
return {
workspaces: new Map(baseline.workspaces),
projects: new Map(baseline.projects),
// Cache hydration can advance the live replica while these requests await responses.
// Every page must use the cursors belonging to the maps captured here.
requestCursors: { ...this.cursors },
syncCursors: {},
syncModes: {},
touchedWorkspaceIds: new Set(),
touchedProjectIds: new Set(),
};
}
private supportsDirectorySync(): boolean {
return (
useSessionStore.getState().sessions[this.serverId]?.serverInfo?.features?.directorySync ===
@@ -37,6 +37,9 @@ class MemoryStorage implements ReplicaRowStore {
onRead: (() => void) | null = null;
/** Throws once a read goes past this count, so a non-terminating read loop fails the test. */
readLimit: number | null = null;
/** Awaited before the store lists every row or deletes a host, so a test can interleave there. */
beforeReadAll: (() => Promise<void>) | null = null;
beforeDeleteHost: (() => Promise<void>) | null = null;
private key(row: Pick<ReplicaRow, "serverId" | "kind" | "id">): string {
return `${row.serverId}:${row.kind}:${row.id}`;
@@ -68,6 +71,7 @@ class MemoryStorage implements ReplicaRowStore {
}
async readAll(): Promise<ReplicaHostRows[]> {
await this.beforeReadAll?.();
const hosts = new Map<string, ReplicaRow[]>();
for (const row of this.rows.values()) {
const rows = hosts.get(row.serverId) ?? [];
@@ -91,6 +95,7 @@ class MemoryStorage implements ReplicaRowStore {
}
async deleteHost(serverId: string): Promise<void> {
await this.beforeDeleteHost?.();
for (const [key, row] of this.rows) if (row.serverId === serverId) this.rows.delete(key);
}
@@ -436,40 +441,49 @@ describe("ReplicaCache", () => {
await expectLegacyWorkspaceRefresh(cached);
});
it("rejects pre-baseline-fix checkpoints without discarding cached rows or timelines", async () => {
const storage = new MemoryStorage();
const writer = createCache(storage);
const baseline = directory();
writer.replaceDirectoryBaseline(SERVER_ID, baseline);
writer.commitTimeline(SERVER_ID, "agent-1", timeline());
await writer.flush();
await storage.apply({
deletes: [],
upserts: [
{
serverId: SERVER_ID,
kind: "checkpoint",
id: "singleton",
payload: JSON.stringify(baseline.checkpoint),
},
],
});
it.each([
["before the baseline fix", (checkpoint: DirectoryCheckpoint): unknown => checkpoint],
[
"before the eviction fix",
(checkpoint: DirectoryCheckpoint): unknown => ({ version: 1, cursors: checkpoint }),
],
])(
"rejects checkpoints written %s without discarding cached rows or timelines",
async (_era, legacyPayload) => {
const storage = new MemoryStorage();
const writer = createCache(storage);
const baseline = directory();
writer.replaceDirectoryBaseline(SERVER_ID, baseline);
writer.commitTimeline(SERVER_ID, "agent-1", timeline());
await writer.flush();
await storage.apply({
deletes: [],
upserts: [
{
serverId: SERVER_ID,
kind: "checkpoint",
id: "singleton",
payload: JSON.stringify(legacyPayload(baseline.checkpoint)),
},
],
});
const reader = createCache(storage);
const restored = await reader.readDirectory(SERVER_ID);
expect(restored.checkpoint).toBeUndefined();
expect([...restored.workspaces.keys()]).toEqual([...baseline.workspaces.keys()]);
expect([...restored.projects.keys()]).toEqual([...baseline.projects.keys()]);
expect([...restored.agents.keys()]).toEqual([...baseline.agents.keys()]);
expect(await reader.readTimeline(SERVER_ID, "agent-1")).toEqual(timeline());
expect(await storage.read(SERVER_ID, ["checkpoint"])).toEqual([]);
const reader = createCache(storage);
const restored = await reader.readDirectory(SERVER_ID);
expect(restored.checkpoint).toBeUndefined();
expect([...restored.workspaces.keys()]).toEqual([...baseline.workspaces.keys()]);
expect([...restored.projects.keys()]).toEqual([...baseline.projects.keys()]);
expect([...restored.agents.keys()]).toEqual([...baseline.agents.keys()]);
expect(await reader.readTimeline(SERVER_ID, "agent-1")).toEqual(timeline());
expect(await storage.read(SERVER_ID, ["checkpoint"])).toEqual([]);
reader.replaceDirectoryBaseline(SERVER_ID, baseline);
await reader.flush();
expect((await createCache(storage).readDirectory(SERVER_ID)).checkpoint).toEqual(
baseline.checkpoint,
);
});
reader.replaceDirectoryBaseline(SERVER_ID, baseline);
await reader.flush();
expect((await createCache(storage).readDirectory(SERVER_ID)).checkpoint).toEqual(
baseline.checkpoint,
);
},
);
it("does nothing until an owner explicitly commits data", async () => {
const storage = new MemoryStorage();
@@ -1102,6 +1116,113 @@ describe("ReplicaCache", () => {
).toEqual(["agent", "checkpoint", "project", "workspace"]);
});
it.each(["beforeReadAll", "beforeDeleteHost"] as const)(
"stores no checkpoint for a host evicted after its update was queued (%s)",
async (pausePoint) => {
const storage = new MemoryStorage();
const previousSession = new ReplicaCache(storage, noLegacyCleanup);
previousSession.setHosts([SERVER_ID, "other-host"]);
previousSession.replaceDirectoryBaseline(SERVER_ID, directory());
previousSession.replaceDirectoryBaseline("other-host", directory());
await previousSession.flush();
const cache = new ReplicaCache(storage, { ...noLegacyCleanup, maxBytes: 8_192 });
cache.setHosts([SERVER_ID, "other-host"]);
const paused = deferred();
const resume = deferred();
storage[pausePoint] = async () => {
storage[pausePoint] = null;
paused.resolve();
await resume.promise;
};
// Larger than the whole budget, so this persist evicts both hosts.
cache.commitTimeline(SERVER_ID, "agent-1", timeline("x".repeat(16_384)));
const eviction = cache.flush();
await paused.promise;
cache.commitDirectoryMutations(SERVER_ID, [], { agents: { generation: "g", afterSeq: 13 } });
resume.resolve();
await eviction;
await cache.flush();
const restored = await createCache(storage).readDirectory(SERVER_ID);
expect(restored.agents.size).toBe(0);
expect(restored.checkpoint).toBeUndefined();
},
);
it("stores no checkpoint for a host evicted while a malformed row is repaired", async () => {
const { storage } = await cacheWithoutBackgroundVisibility();
const reader = createCache(storage, 8_192);
storage.onRead = () => {
if (!storage.reads.at(-1)?.kinds.includes("checkpoint")) return;
storage.onRead = null;
// Larger than the whole budget, so this persist evicts the host before the repair writes.
reader.commitTimeline(SERVER_ID, "agent-1", timeline("x".repeat(16_384)));
void reader.flush();
};
expect(await reader.readWorkspace(SERVER_ID, "workspace-1")).toBeUndefined();
await reader.flush();
const restored = await createCache(storage).readDirectory(SERVER_ID);
expect(restored.projects.size).toBe(0);
expect(restored.checkpoint).toBeUndefined();
});
it("repairs a malformed row's cursor when the overlapping eviction fails", async () => {
const { storage } = await cacheWithoutBackgroundVisibility();
const reader = createCache(storage, 8_192);
storage.onRead = () => {
if (!storage.reads.at(-1)?.kinds.includes("checkpoint")) return;
storage.onRead = null;
storage.beforeDeleteHost = async () => {
storage.beforeDeleteHost = null;
throw new Error("Eviction aborted");
};
reader.commitTimeline(SERVER_ID, "agent-1", timeline("x".repeat(16_384)));
void reader.flush();
};
expect(await reader.readWorkspace(SERVER_ID, "workspace-1")).toBeUndefined();
// A newer timeline fits the budget, so no later eviction clears the checkpoint.
reader.commitTimeline(SERVER_ID, "agent-1", timeline());
await reader.flush();
const restored = await createCache(storage).readDirectory(SERVER_ID);
expect(restored.workspaces.size).toBe(0);
expect(restored.checkpoint).toEqual({
agents: { generation: "g", afterSeq: 12 },
projects: { generation: "g", afterSeq: 4 },
});
});
it("keeps an update queued behind the baseline that rebuilds an evicted host", async () => {
const storage = new MemoryStorage();
const cache = new ReplicaCache(storage, { ...noLegacyCleanup, maxBytes: 2_500 });
cache.setHosts([SERVER_ID, "other-host"]);
const baseline = directory();
cache.replaceDirectoryBaseline(SERVER_ID, baseline);
await cache.flush();
cache.replaceDirectoryBaseline("other-host", baseline);
await cache.flush();
expect((await cache.readDirectory(SERVER_ID)).agents.size).toBe(0);
const renamed = { ...agent(), title: "Renamed agent" };
cache.replaceDirectoryBaseline(SERVER_ID, baseline);
cache.commitDirectoryMutations(
SERVER_ID,
[{ kind: "agent", type: "upsert", id: renamed.id, value: renamed }],
{ agents: { generation: "g", afterSeq: 13 } },
);
await cache.flush();
cache.commitDirectoryMutations(SERVER_ID, [], { agents: { generation: "g", afterSeq: 14 } });
await cache.flush();
const restored = await createCache(storage).readDirectory(SERVER_ID);
expect(restored.checkpoint).toEqual({ agents: { generation: "g", afterSeq: 14 } });
expect(restored.agents.get(renamed.id)?.title).toBe("Renamed agent");
});
it("runs legacy cleanup once when storage is first used", async () => {
const storage = new MemoryStorage();
const cache = new ReplicaCache(storage, {
+34 -20
View File
@@ -397,15 +397,19 @@ const DirectoryCheckpointSchema = z.strictObject({
agents: DirectoryCursorSchema.optional(),
});
// Old checkpoints could describe a baseline that an overlapping refresh had discarded.
// Revalidate directory contents once without evicting cached rows or timelines.
// A checkpoint is trusted only when this version wrote it. Earlier writers could store one for a
// directory the cache no longer held: unversioned ones after an overlapping refresh, version 1
// after an eviction. Rejecting them revalidates directory contents once without evicting cached
// rows or timelines.
const DIRECTORY_CHECKPOINT_VERSION = 2;
const StoredDirectoryCheckpointSchema = z.strictObject({
version: z.literal(1),
version: z.literal(DIRECTORY_CHECKPOINT_VERSION),
cursors: DirectoryCheckpointSchema,
});
function serializeDirectoryCheckpoint(cursors: DirectoryCheckpoint) {
return { version: 1 as const, cursors };
return { version: DIRECTORY_CHECKPOINT_VERSION, cursors };
}
function deserializeDirectoryCheckpoint(payload: string): DirectoryCheckpoint {
@@ -968,6 +972,7 @@ export class ReplicaCache {
private pendingUpserts = new Map<string, StructuredReplicaUpsert>();
private pendingDeletes = new Map<string, ReplicaRowKey>();
private pendingBaselines = new Set<string>();
// Hosts whose stored directory was evicted. Only a baseline stores their directory again.
private readonly invalidatedHosts = new Set<string>();
private readonly maxBytes: number;
private totalBytes = 0;
@@ -1109,11 +1114,7 @@ export class ReplicaCache {
private async deleteInvalidRow(row: ReplicaRow): Promise<void> {
const invalidEntity = directoryEntityForRow(row);
if (!invalidEntity) {
const changes = { upserts: [], deletes: [row] } satisfies ReplicaRowChanges;
await this.queueOperation(async () => {
await this.rowStore.apply(changes);
this.applyStoredChanges(changes);
});
await this.applyRepair(row.serverId, { upserts: [], deletes: [row] });
return;
}
@@ -1144,10 +1145,7 @@ export class ReplicaCache {
]
: [],
};
await this.queueOperation(async () => {
await this.rowStore.apply(changes);
this.applyStoredChanges(changes);
});
await this.applyRepair(row.serverId, changes);
}
private async repairInvalidDirectoryRows(
@@ -1170,9 +1168,16 @@ export class ReplicaCache {
]
: [],
};
await this.queueOperation(async () => {
await this.rowStore.apply(changes);
this.applyStoredChanges(changes);
await this.applyRepair(serverId, changes);
}
// A repair is queued behind writes that can evict its host. If one did, the host has no
// directory left for the repaired checkpoint to describe, so only the deletes still apply.
private applyRepair(serverId: string, changes: ReplicaRowChanges): Promise<void> {
return this.queueOperation(async () => {
const applied = this.invalidatedHosts.has(serverId) ? { ...changes, upserts: [] } : changes;
await this.rowStore.apply(applied);
this.applyStoredChanges(applied);
});
}
@@ -1182,7 +1187,6 @@ export class ReplicaCache {
checkpoint?: DirectoryCheckpoint,
): void {
if (!this.activeServerIds.has(serverId)) return;
if (this.invalidatedHosts.has(serverId)) return;
for (const mutation of mutations) {
if (mutation.type === "delete") {
this.queueEntityDelete(serverId, mutation.kind, mutation.id);
@@ -1412,9 +1416,17 @@ export class ReplicaCache {
}
private materializePendingChanges(pending: PendingReplicaChanges): ReplicaRowChanges {
const deletes = new Map(pending.deletes.map((row) => [pendingRowKey(row), row]));
// Decided here, inside the serialized write, because eviction happens there too. A mutation
// queued before its host was evicted would otherwise store a checkpoint without its directory.
const isStorable = (row: ReplicaRowKey): boolean =>
row.kind === "timeline" ||
!this.invalidatedHosts.has(row.serverId) ||
pending.baselines.has(row.serverId);
const deletes = new Map(
pending.deletes.filter(isStorable).map((row) => [pendingRowKey(row), row]),
);
const upserts: ReplicaRow[] = [];
for (const upsert of pending.upserts) {
for (const upsert of pending.upserts.filter(isStorable)) {
const row = this.materializeUpsert(upsert);
if (row) upserts.push(row);
else deletes.set(pendingRowKey(upsert), upsert);
@@ -1563,8 +1575,10 @@ export class ReplicaCache {
projectedTotal -= bytes;
projectedBytes.delete(serverId);
evicted.add(serverId);
this.invalidatedHosts.add(serverId);
if (this.storedRows.has(serverId)) await this.rowStore.deleteHost(serverId);
// Only after the delete commits: a failed eviction leaves the rows stored, and writers that
// check this set must keep their checkpoint in step with those rows.
this.invalidatedHosts.add(serverId);
this.removeStoredHost(serverId);
}
@@ -92,13 +92,14 @@ test("visible catch-up settles before hidden open chats start fetching", async (
world.sync.dispose();
});
test("a failed visible catch-up releases hidden chats without bypassing its error", async () => {
test("a failed visible catch-up with a parked gap releases hidden chats without retrying", async () => {
const world = new TimelineWorld();
world.openedEarlier(["a-hidden"]);
world.sync.replaceVisibleAgentIds("pane", ["z-visible"]);
world.sync.setConnected(true);
(await world.nextMembership()).succeed();
const visible = await world.nextFetch("z-visible");
world.sync.recoverGap("z-visible", { epoch: "epoch-z-visible", endSeq: 1 });
world.expectNoPendingFetch();
visible.fail("temporarily unavailable");
const hidden = await world.nextFetch("a-hidden");
@@ -127,6 +128,63 @@ test("switching chats promotes the newly visible catch-up while another visible
world.sync.dispose();
});
test("reconnect drains hidden chats two at a time after the visible chat settles", async () => {
const world = new TimelineWorld();
const hidden = Array.from({ length: 15 }, (_, index) => `hidden-${10 + index}`);
world.openedEarlier(hidden);
world.show("pane", ["visible"]);
world.sync.setConnected(true);
(await world.nextMembership()).succeed();
const beforeDisconnect = await world.nextFetch("visible");
world.sync.setConnected(false);
beforeDisconnect.respond({ hasNewer: false });
world.sync.setConnected(true);
(await world.nextMembership()).succeed();
const visible = await world.nextFetch("visible");
world.expectNoPendingFetch();
visible.respond({ hasNewer: false });
const first = await world.nextFetch(hidden[0]);
let current = await world.nextFetch(hidden[1]);
world.expectNoPendingFetch();
first.fail("timeline request timed out");
for (const agentId of hidden.slice(2)) {
const next = await world.nextFetch(agentId);
world.expectNoPendingFetch();
current.respond({ hasNewer: false });
current = next;
}
current.respond({ hasNewer: false });
await vi.waitFor(() => {
expect(world.sync.getAgentTimelineStatus(hidden[0])).toBe("error");
for (const agentId of hidden.slice(1)) {
expect(world.sync.getAgentTimelineStatus(agentId)).toBe("ready");
}
});
world.expectNoPendingFetch();
world.sync.dispose();
});
test("focusing a queued chat starts it while both hidden catch-ups are running", async () => {
const world = new TimelineWorld();
world.openedEarlier(["hidden-a", "hidden-b", "next-visible"]);
world.show("pane", ["visible"]);
world.sync.setConnected(true);
(await world.nextMembership()).succeed();
(await world.nextFetch("visible")).respond({ hasNewer: false });
const first = await world.nextFetch("hidden-a");
const second = await world.nextFetch("hidden-b");
world.expectNoPendingFetch();
world.show("pane", ["next-visible"]);
expect(world.pendingFetchCount).toBe(1);
(await world.nextFetch("next-visible")).respond({ hasNewer: false });
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("next-visible")).toBe("ready"));
first.respond({ hasNewer: false });
second.respond({ hasNewer: false });
world.sync.dispose();
});
class TimelineWorld {
constructor(
private readonly observeMembership?: ViewedTimelineSyncPorts["observe"],
@@ -441,7 +499,7 @@ test("a gap absorbed by a running tail is recovered after the tail completes", a
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready"));
});
test("a gap parked behind a running tail resumes after the rows that tail applied", async () => {
test("a parked gap pages forward from the coverage established by the running tail", async () => {
const world = new TimelineWorld();
world.sync.setConnected(true);
world.sync.replaceVisibleAgentIds("workspace", ["agent-a"]);
@@ -460,7 +518,13 @@ test("a gap parked behind a running tail resumes after the rows that tail applie
projection: "projected",
wholeTurns: true,
});
recovery.respond({ hasNewer: false, seq: 7 });
recovery.respond({ hasNewer: true, seq: 47 });
const followUp = await world.nextFetch("agent-a");
expect(followUp.request).toMatchObject({
direction: "after",
cursor: { epoch: "epoch-agent-a", seq: 47 },
});
followUp.respond({ hasNewer: false, seq: 55 });
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready"));
world.sync.dispose();
});
@@ -941,14 +1005,51 @@ test("redeclaring unchanged visibility does not bypass catch-up error", async ()
await world.nextError();
world.sync.replaceVisibleAgentIds("workspace", ["agent-a"]);
world.sync.setActive(false);
world.sync.setActive(true);
world.expectNoPendingMembership();
world.expectNoPendingFetch();
expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("error");
});
test.each(["refocusing", "foregrounding"])(
"%s retries a timed-out visible timeline once",
async (trigger) => {
const world = new TimelineWorld();
world.show("pane", ["agent-a"]);
world.sync.setConnected(true);
(await world.nextMembership()).succeed();
(await world.nextFetch("agent-a")).fail("timeline request timed out");
await world.nextError();
expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("error");
const revisit = () => {
if (trigger === "refocusing") {
world.show("pane", []);
world.show("pane", ["agent-a"]);
} else {
world.sync.setActive(false);
world.sync.setActive(true);
}
};
revisit();
expect(world.pendingFetchCount).toBe(1);
expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("pending");
(await world.nextFetch("agent-a")).fail("timeline request timed out again");
await vi.waitFor(() => expect(world.errors).toHaveLength(2));
expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("error");
world.show("pane", ["agent-a"]);
world.sync.setActive(true);
world.expectNoPendingFetch();
revisit();
(await world.nextFetch("agent-a")).respond({ hasNewer: false });
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready"));
expect(world.sync.getAgentTimelineError("agent-a")).toBeNull();
world.expectNoPendingMembership();
world.sync.dispose();
},
);
test("a manual retry that fails returns to the error state", async () => {
const world = new TimelineWorld();
world.sync.setConnected(true);
@@ -968,6 +1069,37 @@ test("a manual retry that fails returns to the error state", async () => {
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("error"));
});
test("refocusing during a membership update retries a reconnect without replaying the backlog", async () => {
const world = freshnessWorld();
world.cursors.set("agent-a", { epoch: "epoch-agent-a", endSeq: 42 });
world.show("pane", ["agent-a"]);
world.sync.setConnected(true);
(await world.nextMembership()).succeed({ "agent-a": "current" });
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready"));
world.sync.setConnected(false);
world.sync.setConnected(true);
(await world.nextMembership()).succeed({ "agent-a": "behind" });
const failed = await world.nextFetch("agent-a");
expect(failed.request.direction).toBe("after");
failed.fail("timeline request timed out");
await world.nextError();
world.show("pane", ["agent-b"]);
const membership = await world.nextMembership();
world.show("pane", ["agent-a"]);
expect(world.pendingFetchCount).toBe(1);
const retry = await world.nextFetch("agent-a");
expect(retry.request).toEqual(failed.request);
membership.succeed();
retry.respond({ hasNewer: true, seq: 82 });
const tail = await world.nextFetch("agent-a");
expect(tail.request.direction).toBe("tail");
tail.respond({ hasNewer: false });
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready"));
world.sync.dispose();
});
test("gap recovery supersedes completed catch-up and pages through the current tail", async () => {
const world = new TimelineWorld();
world.sync.setConnected(true);
@@ -545,12 +545,27 @@ export function createViewedTimelineOwner(input: {
};
}
const MAX_HIDDEN_CATCH_UPS = 2;
type CatchUpStatus = "running" | "complete" | "error";
interface CatchUpRequest {
page: ProjectedTimelineForwardFetchPlan;
kind: "resume" | "gap";
}
interface CatchUpState {
generation: number;
status: CatchUpStatus;
request?: ProjectedTimelineForwardFetchPlan;
request?: CatchUpRequest;
}
function planCatchUpRequest(
request: CatchUpRequest | undefined,
applied: { epoch: string; endSeq: number } | undefined,
): CatchUpRequest {
if (!request) return { page: planTimelineResumeFetch(applied), kind: "resume" };
return { ...request, page: planTimelineCatchUpPastApplied(request.page, applied) };
}
function isSameCatchUpRequest(
@@ -573,11 +588,11 @@ function decideCatchUp(input: {
if (input.supersede) {
if (
input.current.status === "running" &&
isSameCatchUpRequest(input.current.request, input.request)
isSameCatchUpRequest(input.current.request?.page, input.request)
) {
return "keep";
}
if (input.current.status === "running" && input.current.request?.direction === "tail") {
if (input.current.status === "running" && input.current.request?.page.direction === "tail") {
return "keep-and-park";
}
return "replace";
@@ -597,9 +612,11 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
const sources = new Map<string, string[]>();
const catchUps = new Map<string, CatchUpState>();
const catchUpGenerations = new Map<string, number>();
// Authoritative fetch owed but not runnable yet: disconnected, unacknowledged, or parked.
// Fetches can outlive their catch-up generation when superseded or when a tab closes.
const inFlightCatchUps = new Set<{ agentId: string }>();
// Authoritative fetch owed but not runnable yet: disconnected, unacknowledged, or queued.
// Membership acknowledgement and catch-up completion drain parked requests.
const pendingCatchUps = new Map<string, ProjectedTimelineForwardFetchPlan>();
const pendingCatchUps = new Map<string, CatchUpRequest>();
const visibilityCatchUpPending = new Set<string>();
const visibilityCatchUpErrors = new Map<string, string>();
// A user-initiated retry owes a pending state until it settles.
@@ -723,16 +740,16 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
const fetchUntilCurrent = async (
agentId: string,
generation: number,
request: ProjectedTimelineForwardFetchPlan,
request: CatchUpRequest,
fallbackToLatestTailOnOverflow: boolean,
): Promise<void> => {
if (!ownsCatchUp(agentId, generation)) return;
try {
const page = await ports.fetchPage(agentId, request);
const page = await ports.fetchPage(agentId, request.page);
if (!ownsCatchUp(agentId, generation)) return;
if (page.hasNewer && page.endCursor) {
if (fallbackToLatestTailOnOverflow) {
if (request.page.direction === "after" && fallbackToLatestTailOnOverflow) {
await ports.fetchLatestTail(agentId);
if (!ownsCatchUp(agentId, generation)) return;
catchUps.set(agentId, { generation, status: "complete" });
@@ -742,10 +759,13 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
await fetchUntilCurrent(
agentId,
generation,
planTimelineCatchUpPastApplied(
planTimelineCatchUpAfter(page.endCursor),
ports.readCursor(agentId),
),
{
...request,
page: planTimelineCatchUpPastApplied(
planTimelineCatchUpAfter(page.endCursor),
ports.readCursor(agentId),
),
},
false,
);
return;
@@ -754,20 +774,15 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
throw new Error(`Timeline page for ${agentId} hasNewer without an end cursor`);
}
catchUps.set(agentId, { generation, status: "complete" });
const pendingCatchUp = pendingCatchUps.get(agentId);
if (pendingCatchUp) {
startCatchUp(agentId, { request: pendingCatchUp, supersede: true });
return;
}
setVisibilityCatchUpReady(agentId);
if (!pendingCatchUps.has(agentId)) setVisibilityCatchUpReady(agentId);
} catch (error) {
if (catchUps.get(agentId)?.generation === generation) {
// The parked follow-up belongs to the failed attempt. A retry owns the next request.
pendingCatchUps.delete(agentId);
catchUps.set(agentId, { generation, status: "error", request });
setVisibilityCatchUpError([agentId], error);
ports.reportError(error);
}
} finally {
startAcknowledgedCatchUps();
}
};
@@ -798,23 +813,29 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
);
};
const hiddenCatchUpSlotsAreFull = (agentId: string) => {
const visible = new Set(visibleAgentIds());
if (visible.has(agentId)) return false;
let hidden = 0;
for (const attempt of inFlightCatchUps) {
if (!visible.has(attempt.agentId)) hidden += 1;
}
return hidden >= MAX_HIDDEN_CATCH_UPS;
};
const startCatchUp = (
agentId: string,
options: {
request?: ProjectedTimelineForwardFetchPlan;
request?: CatchUpRequest;
supersede?: boolean;
} = {},
) => {
const { request, supersede = false } = options;
if (freshnessChecks.has(agentId)) {
if (request) pendingCatchUps.set(agentId, request);
return;
}
if (!canCatchUp(agentId)) {
if (request) pendingCatchUps.set(agentId, request);
return;
}
if (shouldWaitForVisibleCatchUp(agentId)) {
if (
freshnessChecks.has(agentId) ||
!canCatchUp(agentId) ||
shouldWaitForVisibleCatchUp(agentId)
) {
if (request) pendingCatchUps.set(agentId, request);
return;
}
@@ -824,11 +845,9 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
return;
}
const applied = ports.readCursor(agentId);
const nextRequest = request
? planTimelineCatchUpPastApplied(request, applied)
: planTimelineResumeFetch(applied);
const nextRequest = planCatchUpRequest(request, applied);
const current = catchUps.get(agentId);
const decision = decideCatchUp({ current, request: nextRequest, supersede });
const decision = decideCatchUp({ current, request: nextRequest.page, supersede });
if (decision === "keep-and-park") {
pendingCatchUps.set(agentId, nextRequest);
return;
@@ -836,18 +855,31 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
if (decision === "keep") {
return;
}
if (hiddenCatchUpSlotsAreFull(agentId)) {
if (request) pendingCatchUps.set(agentId, request);
return;
}
const generation = (catchUpGenerations.get(agentId) ?? 0) + 1;
catchUpGenerations.set(agentId, generation);
catchUps.set(agentId, { generation, status: "running", request: nextRequest });
pendingCatchUps.delete(agentId);
// A gap recovery pages forward to keep the coverage it extends. Without coverage there is
// nothing to keep, so an overflowing page falls back to the latest tail, as a resume does.
const attempt = { agentId };
inFlightCatchUps.add(attempt);
if (current?.status === "error" && !manualRetries.has(agentId)) {
visibilityCatchUpErrors.delete(agentId);
markCatchUpOwed(agentId);
notifyListeners();
}
// A queued gap uses the coverage available when its fetch starts.
void fetchUntilCurrent(
agentId,
generation,
nextRequest,
nextRequest.direction === "after" && (request === undefined || applied === undefined),
);
nextRequest.kind === "resume" || !applied,
).finally(() => {
inFlightCatchUps.delete(attempt);
startAcknowledgedCatchUps();
});
};
const startAcknowledgedCatchUps = () => {
@@ -859,9 +891,8 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
for (const agentId of ordered) {
const pendingCatchUp = pendingCatchUps.get(agentId);
const current = catchUps.get(agentId);
// Completion of a different chat must not bypass a failed chat's error or
// supersede an in-flight tail that owns its parked gap recovery.
if (current && !(current.status === "complete" && pendingCatchUp)) continue;
// A running tail owns its parked gap. A failed catch-up can only have a queued retry.
if (current?.status === "running" || (current && !pendingCatchUp)) continue;
startCatchUp(agentId, {
request: pendingCatchUp,
supersede: Boolean(pendingCatchUp),
@@ -869,6 +900,13 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
}
};
const retryFailedCatchUp = (agentId: string) => {
const catchUp = catchUps.get(agentId);
if (catchUp?.status === "error") {
startCatchUp(agentId, { request: catchUp.request, supersede: true });
}
};
const membershipIsSettled = (requested: string[]) =>
!membershipNeedsRetry &&
!freshnessCheckOwed &&
@@ -975,9 +1013,7 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
void reconcileMembership();
return;
}
if (catchUp?.status === "error") {
startCatchUp(agentId, { request: catchUp.request, supersede: true });
}
retryFailedCatchUp(agentId);
};
const commitDesiredMembership = (
@@ -1068,11 +1104,17 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
publishVisibleMembership();
},
replaceVisibleAgentIds(sourceId, agentIds) {
const previouslyVisible = new Set(visibleAgentIds());
const normalized = normalizeAgentIds(agentIds);
if (normalized.length === 0) sources.delete(sourceId);
else sources.set(sourceId, normalized);
rememberOpenedAgentIds(normalized);
publishVisibleMembership();
if (active) {
for (const agentId of normalized) {
if (!previouslyVisible.has(agentId)) retryFailedCatchUp(agentId);
}
}
startAcknowledgedCatchUps();
},
setActive(nextActive) {
@@ -1085,7 +1127,10 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
}
const canCheck = connected && ports.canCheckFreshness();
for (const agentId of visibleAgentIds()) {
if (visibilityCatchUpErrors.has(agentId)) continue;
if (visibilityCatchUpErrors.has(agentId)) {
retryFailedCatchUp(agentId);
continue;
}
markCatchUpOwed(agentId);
if (
canCheck &&
@@ -1132,7 +1177,10 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
recoverGap(agentId, cursor) {
if (!isDesired(agentId) || catchUps.get(agentId)?.status === "error") return;
startCatchUp(agentId, {
request: planTimelineCatchUpAfter({ epoch: cursor.epoch, seq: cursor.endSeq }),
request: {
page: planTimelineCatchUpAfter({ epoch: cursor.epoch, seq: cursor.endSeq }),
kind: "gap",
},
supersede: true,
});
},
+3 -4
View File
@@ -9,7 +9,7 @@ import {
formatResetTime,
} from "./format";
import { UsageMeter } from "./meter";
import { UsageResetLine } from "./reset-line";
import { UsageDatapointLine } from "./datapoint-line";
import type { UsageBalance } from "./types";
import { useRelativeTimeTick } from "./use-relative-time-tick";
@@ -77,9 +77,8 @@ export function UsageBalanceBar({
</Text>
</View>
{usedPct != null ? <UsageMeter percent={usedPct} tone={tone} /> : null}
<UsageResetLine
countdown={resetLabel}
exactTime={resetTime}
<UsageDatapointLine
datapoints={[resetLabel, resetTime]}
testID={`provider-usage-balance-${balance.id}-reset`}
/>
</View>
+26 -2
View File
@@ -63,7 +63,29 @@ const narrowWindow: UsageWindow = {
resetsAt: new Date(narrowReadingMs + 165.5 * 3_600_000).toISOString(),
};
it("keeps the French reset countdown and forecast apart in a narrow card", async () => {
it("shows the forecast as one more datapoint after the reset countdown, in the same line", async () => {
act(() =>
root.render(
<UsageWindowBar
window={narrowWindow}
forecastAt={narrowForecastAt}
displayAs="used"
pinnable={false}
pinned={false}
onTogglePin={ignorePin}
pinLabel=""
pinTestID=""
/>,
),
);
const line = Array.from(container.querySelectorAll("*")).find((node) =>
node.textContent.startsWith("resets in"),
);
expect(line?.textContent).toMatch(/^resets in .+\s· .+\s· ~\d+% left at reset$/);
});
it("wraps the forecast below the countdown in a narrow French card instead of overlapping it", async () => {
await i18n.changeLanguage("fr");
container.style.width = "272px";
act(() =>
@@ -91,5 +113,7 @@ it("keeps the French reset countdown and forecast apart in a narrow card", async
return range.getBoundingClientRect();
}
expect(textBounds("se réinitialise").right).toBeLessThan(textBounds("~").left);
const countdown = textBounds("se réinitialise");
const forecast = textBounds("~");
expect(forecast.left >= countdown.right || forecast.top >= countdown.bottom).toBe(true);
});
+38
View File
@@ -0,0 +1,38 @@
import { Fragment } from "react";
import { Text } from "react-native";
import { StyleSheet } from "react-native-unistyles";
/**
* The secondary datapoints under a usage meter, separated by " · ": reset countdown, exact reset
* time, quota forecast. They are one line of equal text that wraps at the separators when narrow.
*/
export function UsageDatapointLine({
datapoints,
testID,
}: {
datapoints: readonly (string | null)[];
testID?: string;
}) {
const shown = datapoints.filter((datapoint): datapoint is string => Boolean(datapoint));
if (shown.length === 0) return null;
return (
<Text style={styles.line} testID={testID}>
{shown.map((datapoint, index) => (
// Datapoints are distinct strings, so the text is a stable key.
<Fragment key={datapoint}>
{/* The no-break space keeps the dot on the line of the datapoint before it. */}
{index > 0 ? "\u00a0· " : null}
<Text>{datapoint}</Text>
</Fragment>
))}
</Text>
);
}
const styles = StyleSheet.create((theme) => ({
line: {
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.sm,
fontWeight: theme.fontWeight.normal,
},
}));
-40
View File
@@ -1,40 +0,0 @@
import { Text, View } from "react-native";
import { StyleSheet } from "react-native-unistyles";
/**
* The reset data of a window or balance: the countdown first, then the exact time. When the line
* is too narrow the exact time truncates and the countdown wraps within its column.
*/
export function UsageResetLine({
countdown,
exactTime,
testID,
}: {
countdown: string | null;
exactTime: string | null;
testID?: string;
}) {
if (!countdown) return null;
return (
<View style={styles.line} testID={testID}>
<Text style={[styles.text, styles.countdown]}>{countdown}</Text>
{exactTime ? (
<Text style={[styles.text, styles.exactTime]} numberOfLines={1} ellipsizeMode="tail">
{`\u00a0·\u00a0${exactTime}`}
</Text>
) : null}
</View>
);
}
const styles = StyleSheet.create((theme) => ({
line: { flexDirection: "row", alignItems: "baseline" },
text: {
flexShrink: 0,
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.sm,
fontWeight: theme.fontWeight.normal,
},
countdown: { maxWidth: "100%" },
exactTime: { flexShrink: 1, minWidth: 0 },
}));
+2 -26
View File
@@ -16,7 +16,7 @@ import {
import { UsageMeter } from "./meter";
import { displayPercent, usageWindowRowLabel } from "./model";
import { usagePace } from "./pace";
import { UsageResetLine } from "./reset-line";
import { UsageDatapointLine } from "./datapoint-line";
import type { UsageDisplayAs } from "./preferences";
import type { UsageTone, UsageWindow } from "./types";
import { useRelativeTimeTick } from "./use-relative-time-tick";
@@ -124,14 +124,7 @@ function WindowRowContent({
{pinnable ? <UsagePinGlyph pinned={pinned} /> : null}
</View>
<UsageMeter percent={percent} tone={forecast?.tone ?? "default"} />
{countdown || forecast ? (
<View style={styles.timingRow}>
<View style={styles.resetTiming}>
<UsageResetLine countdown={countdown} exactTime={exactTime} />
</View>
{forecast ? <Text style={styles.forecast(forecast.tone)}>{forecast.label}</Text> : null}
</View>
) : null}
<UsageDatapointLine datapoints={[countdown, exactTime, forecast?.label ?? null]} />
</>
);
}
@@ -199,23 +192,6 @@ function UsagePinGlyph({ pinned }: { pinned: boolean }) {
}
const styles = StyleSheet.create((theme) => ({
timingRow: {
flexDirection: "row",
alignItems: "flex-start",
gap: theme.spacing[2],
},
resetTiming: { flex: 1, minWidth: 0 },
forecast: (tone: UsageTone) => ({
color: {
danger: theme.colors.statusDanger,
warning: theme.colors.statusWarning,
default: theme.colors.foregroundMuted,
ok: theme.colors.statusSuccess,
}[tone],
fontSize: theme.fontSize.sm,
maxWidth: "50%",
textAlign: "right",
}),
row: { gap: 3, paddingVertical: theme.spacing[1.5] },
pin: { width: 12, alignItems: "center" },
tooltipText: { color: theme.colors.popoverForeground, fontSize: theme.fontSize.sm },
@@ -14,6 +14,47 @@ describe("tool-call-parsers", () => {
expect(diff.some((entry) => entry.type === "add")).toBe(true);
});
it("keeps an edit visible in a compact preview of a 6,000-line file", () => {
const context = "- a\n".repeat(3_000);
const before = context + context;
const after = `${context}- b\n${context.slice(4)}`;
const preview = buildLineDiff(before, after);
expect(preview).toHaveLength(10);
expect(preview.slice(4, 6).map((line) => line.type)).toEqual(["remove", "add"]);
expect(preview.filter((line) => line.type === "remove").map((line) => line.content)).toEqual([
"-- a",
]);
expect(preview.filter((line) => line.type === "add").map((line) => line.content)).toEqual([
"+- b",
]);
});
it("retains edits on both sides of a long unchanged range", () => {
const context = "- a\n".repeat(5_998);
const preview = buildLineDiff(`- b\n${context}- d\n`, `- c\n${context}- e\n`);
expect(preview.filter((line) => line.type === "remove").map((line) => line.content)).toEqual([
"-- b",
"-- d",
]);
expect(preview.filter((line) => line.type === "add").map((line) => line.content)).toEqual([
"+- c",
"+- e",
]);
expect(preview).toHaveLength(12);
});
it("shows a bounded replacement preview when an edit rewrites the file", () => {
const preview = buildLineDiff("- a\n".repeat(6_000), "- b\n".repeat(6_000));
expect(preview[0]).toEqual({ type: "remove", content: "-- a" });
expect(preview).toContainEqual({ type: "add", content: "+- b" });
expect(preview.at(-1)).toEqual({ type: "header", content: "…" });
expect(preview).toHaveLength(65);
});
it("parses unified diff", () => {
const parsed = parseUnifiedDiff("@@\n-old\n+new\n");
+83 -134
View File
@@ -1,3 +1,4 @@
import { diffArrays } from "diff";
import { z } from "zod";
import type { HighlightToken } from "@getpaseo/highlight";
@@ -52,156 +53,104 @@ function splitIntoWords(text: string): string[] {
return result;
}
function computeWordLevelDiff(
oldLine: string,
newLine: string,
): { oldSegments: DiffSegment[]; newSegments: DiffSegment[] } {
const oldWords = splitIntoWords(oldLine);
const newWords = splitIntoWords(newLine);
const MAX_EDIT_DISTANCE = 256;
const FULL_CONTEXT_LINE_LIMIT = 128;
const CONTEXT_LINES = 3;
const REPLACEMENT_PREVIEW_LINES = 32;
const OMITTED_LINES: DiffLine = { type: "header", content: "…" };
const m = oldWords.length;
const n = newWords.length;
function addWordHighlights(diff: DiffLine[]): void {
for (let index = 0; index + 1 < diff.length; index++) {
const before = diff[index];
const after = diff[index + 1];
if (before.type !== "remove" || after.type !== "add") continue;
if (before.content.length + after.content.length > 1024) continue;
// LCS to find common words
const dp: number[][] = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
const words = diffArrays(
splitIntoWords(before.content.slice(1)),
splitIntoWords(after.content.slice(1)),
{ maxEditLength: 64 },
);
if (!words) continue;
for (let i = m - 1; i >= 0; i -= 1) {
for (let j = n - 1; j >= 0; j -= 1) {
if (oldWords[i] === newWords[j]) {
dp[i][j] = dp[i + 1][j + 1] + 1;
} else {
dp[i][j] = Math.max(dp[i + 1][j], dp[i][j + 1]);
}
}
before.segments = words
.filter((part) => !part.added)
.map((part) => ({ text: part.value.join(""), changed: part.removed }));
after.segments = words
.filter((part) => !part.removed)
.map((part) => ({ text: part.value.join(""), changed: part.added }));
}
}
// Mark which words are in LCS (unchanged)
const oldInLCS = new Set<number>();
const newInLCS = new Set<number>();
function contextPreview(
lines: string[],
hasEditBefore: boolean,
hasEditAfter: boolean,
): DiffLine[] {
const leadingCount = hasEditBefore ? CONTEXT_LINES : 0;
const trailingCount = hasEditAfter ? CONTEXT_LINES : 0;
if (lines.length <= leadingCount + trailingCount) return contextLines(lines);
let i = 0;
let j = 0;
while (i < m && j < n) {
if (oldWords[i] === newWords[j]) {
oldInLCS.add(i);
newInLCS.add(j);
i += 1;
j += 1;
} else if (dp[i + 1][j] >= dp[i][j + 1]) {
i += 1;
} else {
j += 1;
}
return [
...contextLines(lines.slice(0, leadingCount)),
OMITTED_LINES,
...contextLines(lines.slice(lines.length - trailingCount)),
];
}
function contextLines(lines: string[]): DiffLine[] {
return lines.map((line) => ({ type: "context", content: ` ${line}` }));
}
function splitLineChange(before: string[], after: string[]) {
let start = 0;
let beforeEnd = before.length;
let afterEnd = after.length;
while (start < beforeEnd && start < afterEnd && before[start] === after[start]) start++;
while (beforeEnd > start && afterEnd > start && before[beforeEnd - 1] === after[afterEnd - 1]) {
beforeEnd--;
afterEnd--;
}
// Build segments: consecutive unchanged or changed words merged
const buildSegments = (words: string[], inLCS: Set<number>): DiffSegment[] => {
if (words.length === 0) return [];
const segments: DiffSegment[] = [];
let currentText = "";
let currentChanged: boolean | null = null;
for (let idx = 0; idx < words.length; idx++) {
const word = words[idx];
const changed = !inLCS.has(idx);
if (currentChanged === null) {
currentText = word;
currentChanged = changed;
} else if (changed === currentChanged) {
currentText += word;
} else {
segments.push({ text: currentText, changed: currentChanged });
currentText = word;
currentChanged = changed;
}
}
if (currentText) {
segments.push({ text: currentText, changed: currentChanged ?? false });
}
return segments;
};
const oldSegments = buildSegments(oldWords, oldInLCS);
const newSegments = buildSegments(newWords, newInLCS);
return {
oldSegments,
newSegments,
leading: before.slice(0, start),
before: before.slice(start, beforeEnd),
after: after.slice(start, afterEnd),
trailing: before.slice(beforeEnd),
};
}
function buildReplacementPreview(before: string[], after: string[]): DiffLine[] {
return [
...before
.slice(0, REPLACEMENT_PREVIEW_LINES)
.map((line): DiffLine => ({ type: "remove", content: `-${line}` })),
...after
.slice(0, REPLACEMENT_PREVIEW_LINES)
.map((line): DiffLine => ({ type: "add", content: `+${line}` })),
OMITTED_LINES,
];
}
export function buildLineDiff(originalText: string, updatedText: string): DiffLine[] {
const originalLines = splitIntoLines(originalText);
const updatedLines = splitIntoLines(updatedText);
// Anchor equal file edges so an edit to a repeated line stays at its original location.
const { leading, before, after, trailing } = splitLineChange(originalLines, updatedLines);
const compact = Math.max(originalLines.length, updatedLines.length) > FULL_CONTEXT_LINE_LIMIT;
if (compact && before.length === 0 && after.length === 0) return [];
const hasAnyContent = originalLines.length > 0 || updatedLines.length > 0;
if (!hasAnyContent) {
return [];
}
const leadingRows = compact ? contextPreview(leading, false, true) : contextLines(leading);
const changes = diffArrays(before, after, { maxEditLength: MAX_EDIT_DISTANCE });
if (!changes) return [...leadingRows, ...buildReplacementPreview(before, after)];
const m = originalLines.length;
const n = updatedLines.length;
const dp: number[][] = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
for (let i = m - 1; i >= 0; i -= 1) {
for (let j = n - 1; j >= 0; j -= 1) {
if (originalLines[i] === updatedLines[j]) {
dp[i][j] = dp[i + 1][j + 1] + 1;
} else {
dp[i][j] = Math.max(dp[i + 1][j], dp[i][j + 1]);
}
}
}
const diff: DiffLine[] = [];
let i = 0;
let j = 0;
while (i < m && j < n) {
if (originalLines[i] === updatedLines[j]) {
diff.push({ type: "context", content: ` ${originalLines[i]}` });
i += 1;
j += 1;
} else if (dp[i + 1][j] >= dp[i][j + 1]) {
diff.push({ type: "remove", content: `-${originalLines[i]}` });
i += 1;
} else {
diff.push({ type: "add", content: `+${updatedLines[j]}` });
j += 1;
}
}
while (i < m) {
diff.push({ type: "remove", content: `-${originalLines[i]}` });
i += 1;
}
while (j < n) {
diff.push({ type: "add", content: `+${updatedLines[j]}` });
j += 1;
}
// Post-process to add word-level segments for adjacent remove/add pairs
for (let idx = 0; idx < diff.length - 1; idx++) {
const curr = diff[idx];
const next = diff[idx + 1];
if (curr.type === "remove" && next.type === "add") {
// Strip the leading -/+ from content for comparison
const oldLineText = curr.content.slice(1);
const newLineText = next.content.slice(1);
const { oldSegments, newSegments } = computeWordLevelDiff(oldLineText, newLineText);
curr.segments = oldSegments;
next.segments = newSegments;
}
}
return diff;
const changedRows = changes.flatMap((part): DiffLine[] => {
if (part.removed) return part.value.map((line) => ({ type: "remove", content: `-${line}` }));
if (part.added) return part.value.map((line) => ({ type: "add", content: `+${line}` }));
return compact ? contextPreview(part.value, true, true) : contextLines(part.value);
});
addWordHighlights(changedRows);
const trailingRows = compact ? contextPreview(trailing, true, false) : contextLines(trailing);
return [...leadingRows, ...changedRows, ...trailingRows];
}
export function parseUnifiedDiff(diffText?: string): DiffLine[] {
+4 -4
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/cli",
"version": "0.17.0-beta.1",
"version": "0.17.0",
"description": "Paseo CLI - control your AI coding agents from the command line",
"license": "Apache-2.0",
"bin": {
@@ -29,9 +29,9 @@
},
"dependencies": {
"@clack/prompts": "^1.0.0",
"@getpaseo/client": "0.17.0-beta.1",
"@getpaseo/protocol": "0.17.0-beta.1",
"@getpaseo/server": "0.17.0-beta.1",
"@getpaseo/client": "0.17.0",
"@getpaseo/protocol": "0.17.0",
"@getpaseo/server": "0.17.0",
"chalk": "^5.3.0",
"commander": "^12.0.0",
"mime-types": "^2.1.35",
@@ -1,4 +1,5 @@
import { describe, expect, it } from "vitest";
import { runCreateCommandWithDeps } from "./create.js";
import { buildCreateWorktreeRequest, type WorktreeCreateOptions } from "./create-input.js";
const REPO = "/tmp/repo";
@@ -77,3 +78,52 @@ describe("buildCreateWorktreeRequest", () => {
});
});
});
it("uses the explicit worktree creation RPC and returns the created worktree details", async () => {
const result = await runCreateCommandWithDeps(
{
daemonTarget: { kind: "endpoint", host: "example.test:12345" },
mode: "branch-off",
newBranch: "topic",
base: "main",
cwd: REPO,
},
{
connectToDaemon: async () => ({
createPaseoWorktree: async (input) => {
expect(input).toEqual({
cwd: REPO,
worktreeSlug: "topic",
action: "branch-off",
refName: "main",
});
return {
workspace: {
id: "wks_topic",
projectId: "project",
projectDisplayName: "Repo",
projectRootPath: REPO,
workspaceDirectory: `${REPO}/topic`,
projectKind: "git",
workspaceKind: "worktree",
name: "topic",
status: "idle",
statusEnteredAt: null,
activityAt: null,
archivingAt: null,
scripts: [],
},
error: null,
requestId: "worktree-create",
};
},
close: async () => {},
}),
},
);
expect(result.data).toEqual({
name: "topic",
branchName: "topic",
worktreePath: `${REPO}/topic`,
});
});
+12 -1
View File
@@ -26,11 +26,22 @@ function cmdError(code: string, message: string, details?: string): CommandError
export async function runCreateCommand(
options: WorktreeCreateOptions,
_command: Command,
): Promise<SingleResult<WorktreeCreateResult>> {
return runCreateCommandWithDeps(options, { connectToDaemon });
}
export async function runCreateCommandWithDeps(
options: WorktreeCreateOptions,
deps: {
connectToDaemon(
options: Parameters<typeof connectToDaemon>[0],
): Promise<Pick<Awaited<ReturnType<typeof connectToDaemon>>, "createPaseoWorktree" | "close">>;
},
): Promise<SingleResult<WorktreeCreateResult>> {
const cwd = options.cwd ?? process.cwd();
const request = buildCreateWorktreeRequest(options, cwd);
const client = await connectToDaemon({ target: options.daemonTarget });
const client = await deps.connectToDaemon({ target: options.daemonTarget });
try {
const response = await client.createPaseoWorktree(request);
@@ -1,234 +1,241 @@
#!/usr/bin/env npx tsx
/**
* Regression: a single SIGINT sent to the supervised supervisor entrypoint must allow
* graceful daemon lifecycle shutdown to complete (no early forced exit path).
*/
import assert from "node:assert";
import { spawn, type ChildProcess } from "node:child_process";
import { mkdtemp, rm } from "node:fs/promises";
import assert from "node:assert/strict";
import { spawn } from "node:child_process";
import { once } from "node:events";
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { $ } from "zx";
import { setTimeout as delay } from "node:timers/promises";
import { WebSocket } from "ws";
import { DaemonClient, type WebSocketLike } from "@getpaseo/client/internal/daemon-client";
import { readDaemonInstance } from "@getpaseo/server/daemon-control";
import { runLocalPaseo } from "./helpers/local-cli.ts";
import { getAvailablePort } from "./helpers/network.ts";
$.verbose = false;
const pollIntervalMs = 100;
const testEnv = {
PASEO_LOCAL_SPEECH_AUTO_DOWNLOAD: process.env.PASEO_LOCAL_SPEECH_AUTO_DOWNLOAD ?? "0",
PASEO_DICTATION_ENABLED: process.env.PASEO_DICTATION_ENABLED ?? "0",
PASEO_VOICE_MODE_ENABLED: process.env.PASEO_VOICE_MODE_ENABLED ?? "0",
const paseoHome = await mkdtemp(join(tmpdir(), "paseo-sigint-supervisor-"));
const cwd = join(paseoHome, "workspace");
const eventsPath = join(paseoHome, "acp-events.jsonl");
const resumePrompt = "Continue the interrupted test.";
const watchDependencies = process.argv.includes("--dev-watch");
const env = {
PASEO_HOME: paseoHome,
PASEO_NODE_INSPECT: "0",
PASEO_RELAY_ENABLED: "false",
PASEO_LOCAL_SPEECH_AUTO_DOWNLOAD: "0",
PASEO_DICTATION_ENABLED: "0",
PASEO_VOICE_MODE_ENABLED: "0",
PASEO_LOG_FORMAT: "json",
};
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
type AcpEvent =
| { type: "session"; pid: number; sessionId: string }
| { type: "prompt"; sessionId: string; text: string }
| { type: "sigint"; pid: number };
function isProcessRunning(pid: number): boolean {
if (!Number.isInteger(pid) || pid <= 0) {
return false;
}
try {
process.kill(pid, 0);
return true;
} catch {
return false;
}
}
function signalProcessGroup(pid: number, signal: NodeJS.Signals): boolean {
if (!Number.isInteger(pid) || pid <= 0) {
return false;
}
if (process.platform === "win32") {
try {
process.kill(pid, signal);
return true;
} catch {
return false;
}
}
try {
process.kill(-pid, signal);
return true;
} catch {
return false;
}
}
interface DaemonStatus {
localDaemon: string | null;
pid: number | null;
}
async function readDaemonStatus(paseoHome: string): Promise<DaemonStatus> {
const result =
await $`PASEO_HOME=${paseoHome} PASEO_LOCAL_SPEECH_AUTO_DOWNLOAD=${testEnv.PASEO_LOCAL_SPEECH_AUTO_DOWNLOAD} PASEO_DICTATION_ENABLED=${testEnv.PASEO_DICTATION_ENABLED} PASEO_VOICE_MODE_ENABLED=${testEnv.PASEO_VOICE_MODE_ENABLED} npx paseo daemon status --home ${paseoHome} --json`.nothrow();
if (result.exitCode !== 0) {
return { localDaemon: null, pid: null };
}
try {
const parsed = JSON.parse(result.stdout) as { localDaemon?: unknown; pid?: unknown };
const localDaemon = typeof parsed.localDaemon === "string" ? parsed.localDaemon : null;
const pid =
typeof parsed.pid === "number" && Number.isInteger(parsed.pid) && parsed.pid > 0
? parsed.pid
: null;
return { localDaemon, pid };
} catch {
return { localDaemon: null, pid: null };
}
}
async function waitFor(
check: () => Promise<boolean> | boolean,
timeoutMs: number,
message: string,
): Promise<void> {
const deadline = Date.now() + timeoutMs;
async function poll(): Promise<void> {
if (await check()) return;
if (Date.now() >= deadline) throw new Error(message);
await sleep(pollIntervalMs);
return poll();
}
return poll();
}
interface ExitResult {
code: number | null;
signal: NodeJS.Signals | null;
}
function waitForProcessExit(processRef: ChildProcess, timeoutMs: number): Promise<ExitResult> {
return new Promise((resolve, reject) => {
const timeout = setTimeout(() => {
reject(new Error("timed out waiting for process exit"));
}, timeoutMs);
processRef.once("exit", (code, signal) => {
clearTimeout(timeout);
resolve({ code, signal });
});
async function readEvents(): Promise<AcpEvent[]> {
const contents = await readFile(eventsPath, "utf8").catch((error) => {
if (error.code === "ENOENT") return "";
throw error;
});
return contents
.split("\n")
.filter(Boolean)
.map((line) => JSON.parse(line) as AcpEvent);
}
console.log("=== Daemon SIGINT (supervisor regression) ===\n");
async function waitFor<T>(read: () => Promise<T | undefined>, message: string, timeoutMs = 15_000) {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
const value = await read();
if (value !== undefined) return value;
await delay(50);
}
throw new Error(message);
}
const port = await getAvailablePort();
const paseoHome = await mkdtemp(join(tmpdir(), "paseo-sigint-supervisor-"));
const cliRoot = join(import.meta.dirname, "..");
let supervisorProcess: ChildProcess | null = null;
let recentSupervisorLogs = "";
try {
console.log("Test 1: start supervisor-entrypoint in dev mode with isolated PASEO_HOME");
supervisorProcess = spawn(
process.execPath,
["--import", "tsx", "../server/scripts/supervisor-entrypoint.ts", "--dev"],
async function startSupervisor() {
const host = `127.0.0.1:${await getAvailablePort()}`;
const child = spawn(
watchDependencies ? "npm" : process.execPath,
watchDependencies
? ["run", "dev:server:watch"]
: ["--import", "tsx", "../server/scripts/supervisor-entrypoint.ts", "--dev"],
{
cwd: cliRoot,
cwd: join(import.meta.dirname, watchDependencies ? "../../.." : ".."),
env: {
...process.env,
...testEnv,
PASEO_HOME: paseoHome,
PASEO_LISTEN: `127.0.0.1:${port}`,
PASEO_RELAY_ENABLED: "false",
...Object.fromEntries(
Object.entries(process.env).filter(([key]) => !key.startsWith("PASEO_")),
),
HOME: paseoHome,
USERPROFILE: paseoHome,
...env,
PASEO_LISTEN: host,
CI: "true",
},
stdio: ["ignore", "pipe", "pipe"],
detached: process.platform !== "win32",
},
);
supervisorProcess.stdout?.on("data", (chunk) => {
recentSupervisorLogs = (recentSupervisorLogs + chunk.toString()).slice(-8000);
assert(child.pid, "supervisor should have a PID");
const exited = once(child, "close");
const client = new DaemonClient({
url: `ws://${host}/ws`,
clientId: "sigint-supervisor-test",
appVersion: "0.17.0-beta.1",
localCredential: async () =>
(await readFile(join(paseoHome, "local-credential"), "utf8")).trim(),
webSocketFactory: (url, options) => new WebSocket(url, options) as unknown as WebSocketLike,
reconnect: { enabled: false },
});
supervisorProcess.stderr?.on("data", (chunk) => {
recentSupervisorLogs = (recentSupervisorLogs + chunk.toString()).slice(-8000);
});
await waitFor(
async () => {
const status = await readDaemonStatus(paseoHome);
return (
status.localDaemon === "running" && status.pid !== null && isProcessRunning(status.pid)
);
},
120000,
"daemon did not become running in time",
);
console.log("✓ supervised daemon started\n");
console.log("Test 2: single SIGINT should shutdown gracefully without forced exit");
const exitPromise = waitForProcessExit(supervisorProcess, 30000);
const signaledGroup = signalProcessGroup(supervisorProcess.pid ?? -1, "SIGINT");
if (!signaledGroup) {
supervisorProcess.kill("SIGINT");
}
const exit = await exitPromise;
assert.strictEqual(
exit.signal,
null,
`supervisor should exit cleanly, got signal=${exit.signal}`,
);
assert.strictEqual(exit.code, 0, `supervisor should exit with status 0, got code=${exit.code}`);
await waitFor(
async () => {
const status = await readDaemonStatus(paseoHome);
return status.localDaemon === "stopped";
},
15000,
"daemon status did not transition to stopped after SIGINT",
);
assert(
!recentSupervisorLogs.includes("Forcing exit..."),
`worker entered forced-exit path during single SIGINT:\n${recentSupervisorLogs}`,
);
assert(
!recentSupervisorLogs.includes("Forcing shutdown - HTTP server didn't close in time"),
`worker hit shutdown timeout during single SIGINT:\n${recentSupervisorLogs}`,
);
console.log("✓ single SIGINT completed graceful shutdown without forced exit\n");
} finally {
if (supervisorProcess?.pid && isProcessRunning(supervisorProcess.pid)) {
const signaledGroup = signalProcessGroup(supervisorProcess.pid, "SIGTERM");
if (!signaledGroup) {
supervisorProcess.kill("SIGTERM");
let output = "";
const startedWatchers = new Set<string>();
function captureOutput(chunk: Buffer) {
output = (output + chunk.toString()).slice(-32000);
for (const watcher of ["protocol", "client"]) {
if (output.includes(`[${watcher}]`)) startedWatchers.add(watcher);
}
await waitFor(
() => !isProcessRunning(supervisorProcess!.pid ?? -1),
5000,
"supervisor cleanup timed out",
).catch(() => {
const killedGroup = signalProcessGroup(supervisorProcess!.pid ?? -1, "SIGKILL");
if (!killedGroup) {
supervisorProcess?.kill("SIGKILL");
}
});
}
child.stdout.on("data", captureOutput);
child.stderr.on("data", captureOutput);
try {
await Promise.race([
waitFor(
async () => {
const instance = await readDaemonInstance(paseoHome);
if (instance?.listen === host) return instance;
},
"supervisor did not publish its owned endpoint",
120_000,
),
exited.then((result) => {
throw new Error(`supervisor exited early: ${result}\n${output}`);
}),
]);
await client.connect();
if (watchDependencies) {
await waitFor(async () => {
if (startedWatchers.size === 2) return true;
}, "dev runner did not start both dependency watchers");
}
} catch (error) {
await client.close();
child.kill("SIGTERM");
throw error;
}
return { child, client, exited, output: () => output };
}
await $`PASEO_HOME=${paseoHome} PASEO_LOCAL_SPEECH_AUTO_DOWNLOAD=${testEnv.PASEO_LOCAL_SPEECH_AUTO_DOWNLOAD} PASEO_DICTATION_ENABLED=${testEnv.PASEO_DICTATION_ENABLED} PASEO_VOICE_MODE_ENABLED=${testEnv.PASEO_VOICE_MODE_ENABLED} npx paseo daemon stop --home ${paseoHome} --force`.nothrow();
function assertPidExited(pid: number) {
assert.throws(() => process.kill(pid, 0), { code: "ESRCH" }, `process ${pid} survived shutdown`);
}
async function interruptForeground(daemon: Awaited<ReturnType<typeof startSupervisor>>) {
const pid = daemon.child.pid!;
await daemon.client.close();
process.kill(process.platform === "win32" ? pid : -pid, "SIGINT");
const exit = await Promise.race([daemon.exited, delay(30_000, "timed out", { ref: false })]);
// npm re-raises SIGINT when its shell exits on the same foreground signal.
if (!watchDependencies || !Array.isArray(exit) || exit[1] !== "SIGINT") {
assert.deepEqual(exit, [0, null], daemon.output());
}
await waitFor(async () => {
if (!(await readDaemonInstance(paseoHome))) return true;
}, "supervisor did not release its PID lock");
const log = await readFile(join(paseoHome, "daemon.log"), "utf8");
assert(!log.includes("Forcing shutdown - HTTP server didn't close in time"), log.slice(-4000));
return log;
}
let daemon: Awaited<ReturnType<typeof startSupervisor>> | undefined;
try {
await mkdir(cwd);
const provider = join(import.meta.dirname, "helpers", "supervisor-acp.cjs");
await writeFile(
join(paseoHome, "config.json"),
JSON.stringify({
version: 1,
agents: {
resumeOnStartup: true,
resumePrompt,
providers: {
antigravity: { command: [process.execPath, provider, eventsPath] },
},
},
}),
);
daemon = await startSupervisor();
if (process.platform === "win32") {
await interruptForeground(daemon);
} else {
const idle = await daemon.client.createAgent({ provider: "antigravity", cwd });
const running = await daemon.client.createAgent({ provider: "antigravity", cwd });
const crashing = await daemon.client.createAgent({ provider: "antigravity", cwd });
const opened = (await readEvents()).filter((event) => event.type === "session");
const sessions = [idle, running, crashing].map((agent) => {
const handle = agent.persistence?.sessionId;
const session = opened.find((event) => handle?.includes(event.sessionId));
assert(session, `missing ACP process for agent ${agent.id}`);
return session;
});
// Exit just this provider while the host is up to prove failure reporting remains active.
process.kill(sessions[2].pid, "SIGTERM");
await waitFor(async () => {
const { agent } = (await daemon!.client.fetchAgent(crashing.id)) ?? {};
if (agent?.status === "error" && agent.attentionReason === "error") return agent;
}, "unexpected provider exit did not raise error attention");
const failure = await daemon.client.fetchAgentTimeline(crashing.id, { limit: 20 });
assert.match(JSON.stringify(failure.entries), /\[System Error\].*ACP process exited/);
console.log("Unexpected ACP exit raised error attention and added a timeline entry.");
await daemon.client.sendMessage(running.id, "Hold the turn open.");
await waitFor(async () => {
const { agent } = (await daemon!.client.fetchAgent(running.id)) ?? {};
if (agent?.status === "running") return agent;
}, "ACP turn did not start");
const workerPid = (await daemon.client.getDaemonStatus()).pid;
const log = await interruptForeground(daemon);
assert.deepEqual(
(await readEvents()).filter((event) => event.type === "sigint"),
[],
"the foreground interrupt reached an ACP process",
);
assert(!log.includes("worker_received_SIGINT"), "the foreground interrupt reached the worker");
assert.match(log, /supervisor_received_SIGINT/);
assertPidExited(workerPid);
for (const session of sessions) assertPidExited(session.pid);
console.log("Foreground SIGINT reached the supervisor. The worker and ACP processes exited.");
daemon = await startSupervisor();
const restoredIdle = (await daemon.client.fetchAgentTimeline(idle.id)).agent;
assert.equal(restoredIdle?.status, "idle");
assert.equal(restoredIdle?.requiresAttention, false);
await waitFor(async () => {
const { agent } = (await daemon!.client.fetchAgent(running.id)) ?? {};
if (agent?.status === "idle" && agent.attentionReason === "finished") return agent;
}, "interrupted agent did not finish the restart prompt");
assert.deepEqual(
(await readEvents()).filter((event) => event.type === "prompt"),
[
{ type: "prompt", sessionId: sessions[1].sessionId, text: "Hold the turn open." },
{ type: "prompt", sessionId: sessions[1].sessionId, text: resumePrompt },
],
);
console.log(
"Idle ACP reopened without error attention. The interrupted ACP turn resumed once.",
);
await interruptForeground(daemon);
}
} catch (error) {
console.error(daemon?.output());
throw error;
} finally {
await daemon?.client.close();
if (await readDaemonInstance(paseoHome)) {
await runLocalPaseo(["daemon", "stop", "--home", paseoHome, "--force"], env);
}
await rm(paseoHome, { recursive: true, force: true });
}
if (recentSupervisorLogs.trim().length === 0) {
console.log("(no supervisor logs captured)");
}
console.log("=== Supervisor SIGINT regression test passed ===");
@@ -0,0 +1,58 @@
const { randomUUID } = require("node:crypto");
const { appendFileSync } = require("node:fs");
const { createInterface } = require("node:readline");
const eventsPath = process.argv[2];
const record = (event) => appendFileSync(eventsPath, JSON.stringify(event) + "\n");
const modes = {
currentModeId: "default",
availableModes: [{ id: "default", name: "Default" }],
};
process.on("SIGINT", () => {
record({ type: "sigint", pid: process.pid });
process.exit(0);
});
createInterface({ input: process.stdin }).on("line", (line) => {
const message = JSON.parse(line);
if (message.id === undefined) return;
let result;
switch (message.method) {
case "initialize":
result = { protocolVersion: 1, agentCapabilities: { loadSession: true } };
break;
case "session/new": {
const sessionId = randomUUID();
record({ type: "session", pid: process.pid, sessionId });
result = { sessionId, modes };
break;
}
case "session/load":
result = { modes };
break;
case "session/close":
// Keep the provider alive long enough to detect a signal sent down the dev watcher tree.
setTimeout(() => reply(message.id, {}), 400);
return;
case "session/prompt": {
const { sessionId, prompt } = message.params;
const text = prompt
.filter((part) => part.type === "text")
.map((part) => part.text)
.join("");
record({ type: "prompt", sessionId, text });
if (text === "Hold the turn open.") return;
result = { stopReason: "end_turn" };
break;
}
default:
result = {};
}
reply(message.id, result);
});
function reply(id, result) {
process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id, result }) + "\n");
}
+3 -3
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/client",
"version": "0.17.0-beta.1",
"version": "0.17.0",
"description": "Paseo client SDK package",
"license": "Apache-2.0",
"files": [
@@ -49,8 +49,8 @@
"measure:diff-materialization": "tsx scripts/measure-diff-materialization.ts"
},
"dependencies": {
"@getpaseo/protocol": "0.17.0-beta.1",
"@getpaseo/relay": "0.17.0-beta.1",
"@getpaseo/protocol": "0.17.0",
"@getpaseo/relay": "0.17.0",
"ws": "^8.20.0",
"zod": "^4.4.3"
},
+100
View File
@@ -1623,6 +1623,106 @@ test("defaults session RPC waiters to sixty seconds", async () => {
await expect(responsePromise).rejects.toThrow("No response to fetch_agent_request after 60000ms");
});
test.each([
[
"archive_workspace_request",
(client: DaemonClient) => client.archiveWorkspace("workspace-1"),
(requestId: string) => ({
type: "archive_workspace_response" as const,
payload: {
requestId,
workspaceId: "workspace-1",
archivedAt: "2026-01-01T00:00:00.000Z",
error: null,
},
}),
],
[
"paseo_worktree_archive_request",
(client: DaemonClient) => client.archivePaseoWorktree({ worktreePath: "/repo/worktree" }),
(requestId: string) => ({
type: "paseo_worktree_archive_response" as const,
payload: { requestId, success: true, removedAgents: [], error: null },
}),
],
[
"workspace.recovery.restore.request",
(client: DaemonClient) => client.restoreWorkspace("workspace-1"),
(requestId: string) => ({
type: "workspace.recovery.restore.response" as const,
payload: { requestId, workspaceId: "workspace-1", accepted: true, error: null },
}),
],
[
"workspace.archive.undo.request",
(client: DaemonClient) => client.undoWorkspaceArchive("workspace-1"),
(requestId: string) => ({
type: "workspace.archive.undo.response" as const,
payload: { requestId, workspaceId: "workspace-1", accepted: true, error: null },
}),
],
[
"open_project_request",
(client: DaemonClient) => client.openProject("/repo/worktree"),
(requestId: string) => ({
type: "open_project_response" as const,
payload: { requestId, workspace: null, error: null },
}),
],
[
"create_paseo_worktree_request",
(client: DaemonClient) => client.createPaseoWorktree({ cwd: "/repo", worktreeSlug: "topic" }),
(requestId: string) => ({
type: "create_paseo_worktree_response" as const,
payload: { requestId, workspace: null, error: null, setupTerminalId: null },
}),
],
] as const)(
"waits on %s across queued and bounded daemon stages until response or disconnect",
async (_type, run, buildResponse) => {
useHeartbeatClock();
const transport = createMockTransport();
const client = new DaemonClient({
url: "ws://test",
clientId: "worktree-lifecycle-wait-test",
logger: createMockLogger(),
reconnect: { enabled: false },
transportFactory: () => transport.transport,
});
clients.push(client);
const connecting = client.connect();
transport.triggerOpen();
await connecting;
const pending = run(client);
const sentFrame = JSON.parse(assertStr(transport.sent.at(-1))) as {
message: { requestId: string };
};
let settled = false;
void pending.then(
() => {
settled = true;
return undefined;
},
() => {
settled = true;
return undefined;
},
);
await vi.advanceTimersByTimeAsync(200_000);
await Promise.resolve();
expect(settled).toBe(false);
transport.triggerMessage(wrapSessionMessage(buildResponse(sentFrame.message.requestId)));
await expect(pending).resolves.not.toThrow();
const disconnected = run(client);
transport.triggerClose({ code: 1006, reason: "gone" });
await expect(disconnected).rejects.toMatchObject({ code: "DAEMON_CONNECTION_LOST" });
},
);
test("honors explicit fetchAgent timeout below the session RPC default", async () => {
useHeartbeatClock();
const logger = createMockLogger();
+19 -3
View File
@@ -3188,6 +3188,9 @@ export class DaemonClient {
cwd,
},
responseType: "open_project_response",
// Opening a path whose checkout is currently archiving waits on the daemon checkout gate;
// wait for the terminal response or transport disconnect instead of timing out while queued.
timeout: 0,
});
}
@@ -3319,6 +3322,9 @@ export class DaemonClient {
workspaceId,
},
responseType: "archive_workspace_response",
// Archive may wait for a queued checkout operation and then run teardown/manager removal,
// each bounded on the daemon; wait for the terminal response or transport disconnect.
timeout: 0,
});
}
@@ -3841,7 +3847,9 @@ export class DaemonClient {
type: "workspace.recovery.restore.request",
workspaceId,
},
timeout: 150_000,
// Restore may wait behind an active archive/removal before running a bounded restore stage;
// wait for the terminal response or transport disconnect instead of timing out mid-workflow.
timeout: 0,
});
if (!payload.accepted) {
throw new Error(payload.error ?? "Workspace recovery was rejected by the host");
@@ -3857,8 +3865,9 @@ export class DaemonClient {
type: "workspace.archive.undo.request",
workspaceId,
},
// Undoing a finished worktree archive recreates the worktree, like recovery does.
timeout: 150_000,
// Undo may wait for an in-flight archive to settle and then recreate the worktree;
// wait for the terminal response or transport disconnect.
timeout: 0,
});
if (!payload.accepted) {
throw new Error(payload.error ?? "The host could not undo the workspace archive");
@@ -5439,6 +5448,9 @@ export class DaemonClient {
...(input.scope !== undefined ? { scope: input.scope } : {}),
},
responseType: "paseo_worktree_archive_response",
// Archive may wait for a queued checkout operation and then run teardown/manager removal,
// each bounded on the daemon; wait for the terminal response or transport disconnect.
timeout: 0,
});
}
@@ -5462,6 +5474,10 @@ export class DaemonClient {
...(input.githubPrNumber !== undefined ? { githubPrNumber: input.githubPrNumber } : {}),
},
responseType: "create_paseo_worktree_response",
// Every daemon stage (before hooks, shared 120s manager budget, Git, after hooks) enforces
// its own deadline, and transport heartbeats/close reject if the host drops, so wait for the
// terminal worktree response instead of aborting prematurely mid-workflow.
timeout: 0,
});
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/desktop",
"version": "0.17.0-beta.1",
"version": "0.17.0",
"private": true,
"description": "Paseo desktop app (Electron wrapper)",
"homepage": "https://paseo.sh",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/expo-two-way-audio",
"version": "0.17.0-beta.1",
"version": "0.17.0",
"description": "Native module for two way audio streaming",
"keywords": [
"ExpoTwoWayAudio",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/highlight",
"version": "0.17.0-beta.1",
"version": "0.17.0",
"license": "Apache-2.0",
"files": [
"dist",
+5 -5
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/plugin",
"version": "0.17.0-beta.1",
"version": "0.17.0",
"description": "Paseo plugin SDK package",
"license": "Apache-2.0",
"files": [
@@ -78,8 +78,8 @@
"use-sync-external-store": "^1.6.0"
},
"devDependencies": {
"@getpaseo/client": "0.17.0-beta.1",
"@getpaseo/protocol": "0.17.0-beta.1",
"@getpaseo/client": "0.17.0",
"@getpaseo/protocol": "0.17.0",
"@types/node": "^20.9.0",
"@types/react": "~19.2.0",
"react": "19.2.3",
@@ -89,8 +89,8 @@
"zod": "^4.4.3"
},
"peerDependencies": {
"@getpaseo/client": "0.17.0-beta.1",
"@getpaseo/protocol": "0.17.0-beta.1",
"@getpaseo/client": "0.17.0",
"@getpaseo/protocol": "0.17.0",
"react": ">=19.1.0 <20",
"react-native": ">=0.81.5",
"zod": "^4.4.3"
+72
View File
@@ -589,3 +589,75 @@ describe("sidebar data SDK boundary", () => {
).toEqual([]);
});
});
describe("worktree manager SDK boundary", () => {
it("types create, remove, and restore handlers with discriminated results and cleanup", () => {
expect(
typeErrors(`
import type {
PluginServerContext,
WorktreeManagerRegistration,
PluginWorktreeCreateInput,
PluginWorktreeCreateResult,
PluginWorktreeRemoveRequest,
PluginWorktreeRemoveResult,
PluginWorktreeRestoreRequest,
PluginWorktreeRestoreResult,
} from "@getpaseo/plugin/server";
export default function contribute(server: PluginServerContext) {
const manager: WorktreeManagerRegistration = {
async create(request: PluginWorktreeCreateInput, { paseo, signal }) {
const untrusted: boolean = request.untrusted;
const headSha: string | undefined = request.headSha;
void headSha;
// @ts-expect-error untrusted is read-only
request.untrusted = true;
// @ts-expect-error headSha is read-only
request.headSha = "deadbeef";
if (request.kind === "branch-off") {
const start: string = request.startPoint ?? request.baseRef;
// @ts-expect-error startPoint is read-only
request.startPoint = "other";
if (!start || untrusted) return;
}
if (signal.aborted) return;
void paseo;
const result: PluginWorktreeCreateResult = { type: "created", path: request.path };
return result;
},
async remove(request: PluginWorktreeRemoveRequest, { signal }) {
const reason: "archive" | "rollback" = request.reason;
const force: boolean = request.force;
const untrusted: boolean = request.untrusted;
// @ts-expect-error remove request fields are read-only
request.path = "/other";
if (!reason || !force || untrusted || signal.aborted) return;
const result: PluginWorktreeRemoveResult = { type: "removed" };
return result;
},
async restore(request: PluginWorktreeRestoreRequest) {
const untrusted: boolean = request.untrusted;
void untrusted;
if (request.target.type === "commit") return;
if (request.target.type === "from-base") {
const base: string = request.target.baseRef;
void base;
}
const result: PluginWorktreeRestoreResult = { type: "restored", path: request.path };
return result;
},
};
const dispose: () => void = server.registerWorktreeManager(manager);
server.registerWorktreeManager({
// @ts-expect-error create result requires discriminant
async create() {
return { path: "/tmp/wt" };
},
});
return dispose;
}
`),
).toEqual([]);
});
});
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+18 -1
View File
@@ -53,6 +53,18 @@ export interface AcpOptions {
initialCommandsTimeoutMs?: number;
/** Allow delayed session/load updates before publishing the session as ready. */
loadReplayQuietPeriodMs?: number;
/**
* Keep a turn open after `end_turn` while qualifying tool calls are still running,
* settling once those tools finish and the agent finishes its follow-up reply.
*/
deferTurnOnRunningTools?: {
/** Delay after `usage_update` closes a follow-up reply before settling. Defaults to 500ms. */
settleDelayMs?: number;
/** Quiet limit after qualifying tools finish if no reply settles via `usage_update`. Defaults to 120_000ms. */
quietLimitMs?: number;
/** Predicate deciding whether an open tool call keeps the turn open. Defaults to all running tools. */
keepsTurnOpen?: (toolCall: AcpToolCallSnapshot) => boolean;
};
/** An unattended mode that approves ACP allow-once requests in the specified native mode. */
autoAcceptMode?: {
mode: Omit<ProviderMode, "isUnattended">;
@@ -124,11 +136,16 @@ export interface AcpTransformer {
configure?(change: AcpConfigChange, context: AcpConfigureContext): Promise<"handled" | "pass">;
/** Rewrites every session config snapshot before Paseo sees it. */
config?(state: ProviderConfigState, context: AcpContext): ProviderConfigState;
/** Rewrites each advertised ACP slash command before Paseo sees it. */
command?(command: ProviderCommand, context: AcpContext): ProviderCommand;
notification?(
notification: { method: string; params: JsonValue },
context: AcpContext,
): AcpVendorUpdate | readonly AcpVendorUpdate[] | null;
toolCall?(toolCall: AcpToolCallSnapshot, context: AcpContext): AcpToolCallSnapshot;
toolCall?(
toolCall: AcpToolCallSnapshot,
context: AcpContext & { mcpServerNames?: readonly string[] },
): AcpToolCallSnapshot;
}
export function runAcpProvider(options: RunAcpProviderOptions): ProviderRegistration {
+2
View File
@@ -5,6 +5,7 @@ import type { PluginCleanup } from "../contracts.js";
import type { ProviderRegistration } from "./provider.js";
import type { UsageSourceRegistration } from "./usage.js";
import type { PluginLifecycleRegistration } from "./lifecycle.js";
import type { WorktreeManagerRegistration } from "./worktree.js";
export interface PluginHandlerContext {
paseo: PaseoApi;
@@ -64,6 +65,7 @@ export interface PluginServerContext extends PluginLifecycleRegistration {
): void;
registerProvider(provider: ProviderRegistration): void;
registerUsageSource(source: UsageSourceRegistration): void;
registerWorktreeManager(manager: WorktreeManagerRegistration): () => void;
}
export type PluginServerContribution = (server: PluginServerContext) => PluginCleanup;
+11
View File
@@ -35,3 +35,14 @@ export { spawnProcess, execCommand, terminateProcess } from "./process.js";
export { defineAgentTool } from "./agent-tools.js";
export type { AgentToolDefinition, AgentToolResult, AgentToolContext } from "./agent-tools.js";
export type {
PluginWorktreeContext,
PluginWorktreeCreateInput,
PluginWorktreeCreateResult,
PluginWorktreeRemoveRequest,
PluginWorktreeRemoveResult,
PluginWorktreeRestoreTarget,
PluginWorktreeRestoreRequest,
PluginWorktreeRestoreResult,
WorktreeManagerRegistration,
} from "./worktree.js";
+6 -1
View File
@@ -37,7 +37,12 @@ export type PluginWorktreeCreateRequest = {
slug: string;
path: string;
} & (
| { kind: "branch-off"; baseRef: string }
| {
kind: "branch-off";
baseRef: string;
/** Where the new branch starts when that is not `baseRef`, such as a fork's head. */
readonly startPoint?: string;
}
| { kind: "checkout-branch" }
| {
kind: "checkout-change-request";
+7 -1
View File
@@ -488,6 +488,7 @@ export interface ProviderCommand {
name: string;
description: string;
argumentHint?: string;
kind?: "command" | "skill";
}
export interface ProviderError {
@@ -1214,7 +1215,12 @@ const noticeSchema = z
})
.strip();
const commandSchema = z
.object({ name: idSchema, description: z.string(), argumentHint: z.string().optional() })
.object({
name: idSchema,
description: z.string(),
argumentHint: z.string().optional(),
kind: z.enum(["command", "skill"]).optional(),
})
.strip();
const usageSchema = z
.object({
+69
View File
@@ -0,0 +1,69 @@
import type { PluginHookContext, PluginWorktreeCreateRequest } from "./lifecycle.js";
/** Context passed to worktree manager callbacks. */
export type PluginWorktreeContext = PluginHookContext;
/** Resolved creation request handed to a worktree manager after `worktree.create.before`. */
export type PluginWorktreeCreateInput = PluginWorktreeCreateRequest & {
/** True when the worktree comes from an untrusted source such as a fork change request; skip repository-defined hooks. */
readonly untrusted: boolean;
/** Resolved remote head commit SHA for change-request checkouts when available. */
readonly headSha?: string;
};
/** Return `{ type: "created", path }` to claim creation, or `undefined` to decline. */
export interface PluginWorktreeCreateResult {
type: "created";
path: string;
}
export interface PluginWorktreeRemoveRequest {
readonly repoRoot: string | null;
readonly path: string;
readonly branch: string | null;
readonly reason: "archive" | "rollback";
readonly force: boolean;
/** True when the worktree came from an untrusted source such as a fork change request; skip repository-defined hooks. */
readonly untrusted: boolean;
}
/** Return `{ type: "removed" }` after removing the worktree, or `undefined` to fall back to Git. */
export interface PluginWorktreeRemoveResult {
type: "removed";
}
export type PluginWorktreeRestoreTarget =
| { readonly type: "branch"; readonly branch: string }
| { readonly type: "commit"; readonly commit: string }
| { readonly type: "from-base"; readonly branch: string; readonly baseRef: string };
export interface PluginWorktreeRestoreRequest {
readonly repoRoot: string;
/** Recorded path the worktree must be restored to. */
readonly path: string;
readonly target: PluginWorktreeRestoreTarget;
readonly baseRef: string | null;
/** True when the worktree came from an untrusted source such as a fork change request; skip repository-defined hooks. */
readonly untrusted: boolean;
}
/** Return `{ type: "restored", path }` after recreating the worktree, or `undefined` to fall back to Git. */
export interface PluginWorktreeRestoreResult {
type: "restored";
path: string;
}
export interface WorktreeManagerRegistration {
create(
request: PluginWorktreeCreateInput,
context: PluginWorktreeContext,
): Promise<PluginWorktreeCreateResult | void>;
remove?(
request: PluginWorktreeRemoveRequest,
context: PluginWorktreeContext,
): Promise<PluginWorktreeRemoveResult | void>;
restore?(
request: PluginWorktreeRestoreRequest,
context: PluginWorktreeContext,
): Promise<PluginWorktreeRestoreResult | void>;
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/protocol",
"version": "0.17.0-beta.1",
"version": "0.17.0",
"description": "Paseo shared protocol schemas and wire types",
"license": "Apache-2.0",
"files": [
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/relay",
"version": "0.17.0-beta.1",
"version": "0.17.0",
"description": "Paseo relay for bridging daemon and client connections",
"license": "Apache-2.0",
"files": [
+7 -7
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/server",
"version": "0.17.0-beta.1",
"version": "0.17.0",
"description": "Paseo backend server",
"license": "Apache-2.0",
"files": [
@@ -90,7 +90,7 @@
"speech:transcribe:local": "tsx scripts/transcribe-local-wav.ts",
"test": "npm run test:unit && npm run test:integration",
"test:unit": "vitest run --fileParallelism --exclude \"**/*.e2e.test.ts\"",
"test:integration": "vitest run --maxWorkers=1 src/server/git-filename-diffs.e2e.test.ts src/server/daemon-e2e/checkout-diff-content.e2e.test.ts src/server/daemon-e2e/create-agent-mode.e2e.test.ts src/server/daemon-e2e/filesystem.e2e.test.ts src/server/daemon-e2e/file-download.e2e.test.ts src/server/daemon-e2e/cli-logs-follow.e2e.test.ts src/server/creation/creation.e2e.test.ts src/server/daemon-e2e/creation-status.e2e.test.ts src/server/daemon-e2e/persisted-creation-caller.e2e.test.ts src/server/daemon-e2e/terminal-workspace-sdk.e2e.test.ts src/server/daemon-e2e/terminal-worker-lifecycle.e2e.test.ts src/server/workspace-create-worktree-source.e2e.test.ts src/server/daemon-e2e/models.e2e.test.ts src/server/daemon-e2e/live-preferences.e2e.test.ts src/server/daemon-e2e/oversized-message.e2e.test.ts src/server/agent/model-catalog.e2e.test.ts src/server/plugins/plugin-paseo-api.e2e.test.ts src/server/plugins/usage-sources.e2e.test.ts src/server/plugins/lifecycle.e2e.test.ts src/server/connected-hosts/hosts.e2e.test.ts src/server/owned-subscriptions.e2e.test.ts && vitest run --maxWorkers=1 src/server/agent/providers/omp/history.e2e.test.ts src/server/daemon-e2e/git-operations.e2e.test.ts src/server/session.create-agent-worktree-autoarchive.e2e.test.ts src/server/agent/providers/opencode-bridge.local.e2e.test.ts src/server/daemon-e2e/relay-transport.e2e.test.ts -t \"merges into|creates a worktree and auto-archives both|versioned runtime|oversized attachments|connected hosts|password-protected daemon refuses|replays selected OMP history\"",
"test:integration": "vitest run --maxWorkers=1 src/server/git-filename-diffs.e2e.test.ts src/server/daemon-e2e/checkout-diff-content.e2e.test.ts src/server/daemon-e2e/create-agent-mode.e2e.test.ts src/server/daemon-e2e/filesystem.e2e.test.ts src/server/daemon-e2e/file-download.e2e.test.ts src/server/daemon-e2e/cli-logs-follow.e2e.test.ts src/server/creation/creation.e2e.test.ts src/server/daemon-e2e/creation-status.e2e.test.ts src/server/daemon-e2e/persisted-creation-caller.e2e.test.ts src/server/daemon-e2e/terminal-workspace-sdk.e2e.test.ts src/server/daemon-e2e/terminal-worker-lifecycle.e2e.test.ts src/server/workspace-create-worktree-source.e2e.test.ts src/server/daemon-e2e/models.e2e.test.ts src/server/daemon-e2e/live-preferences.e2e.test.ts src/server/daemon-e2e/oversized-message.e2e.test.ts src/server/agent/model-catalog.e2e.test.ts src/server/plugins/plugin-paseo-api.e2e.test.ts src/server/plugins/usage-sources.e2e.test.ts src/server/plugins/lifecycle.e2e.test.ts src/server/plugins/worktree-manager.e2e.test.ts src/server/connected-hosts/hosts.e2e.test.ts src/server/owned-subscriptions.e2e.test.ts && vitest run --maxWorkers=1 src/server/agent/providers/omp/history.e2e.test.ts src/server/daemon-e2e/git-operations.e2e.test.ts src/server/session.create-agent-worktree-autoarchive.e2e.test.ts src/server/agent/providers/opencode-bridge.local.e2e.test.ts src/server/daemon-e2e/relay-transport.e2e.test.ts -t \"merges into|creates a worktree and auto-archives both|versioned runtime|oversized attachments|connected hosts|password-protected daemon refuses|replays selected OMP history\"",
"test:hub-cli-contract": "vitest run --maxWorkers=1 src/server/hub/hub-cli-contract.test.ts",
"test:integration:all": "npm run test:e2e",
"test:integration:real": "vitest run real.e2e.test.ts",
@@ -109,11 +109,11 @@
"@agentclientprotocol/sdk": "^0.17.1",
"@anthropic-ai/claude-agent-sdk": "0.3.326",
"@anthropic-ai/sdk": "^0.104.2",
"@getpaseo/client": "0.17.0-beta.1",
"@getpaseo/highlight": "0.17.0-beta.1",
"@getpaseo/plugin": "0.17.0-beta.1",
"@getpaseo/protocol": "0.17.0-beta.1",
"@getpaseo/relay": "0.17.0-beta.1",
"@getpaseo/client": "0.17.0",
"@getpaseo/highlight": "0.17.0",
"@getpaseo/plugin": "0.17.0",
"@getpaseo/protocol": "0.17.0",
"@getpaseo/relay": "0.17.0",
"@isaacs/ttlcache": "^2.1.4",
"@modelcontextprotocol/sdk": "1.29.0",
"@opencode-ai/sdk": "1.14.46",
+44 -3
View File
@@ -1,5 +1,6 @@
import { spawn } from "node:child_process";
import { fileURLToPath } from "url";
import { concurrently } from "concurrently";
import dotenv from "dotenv";
dotenv.config({
@@ -9,7 +10,27 @@ dotenv.config({
const daemonRunnerEntry = fileURLToPath(new URL("./supervisor-entrypoint.ts", import.meta.url));
const supervisorArgs = [...process.execArgv, daemonRunnerEntry, "--dev", ...process.argv.slice(2)];
const args = process.argv.slice(2);
// concurrently signals entire command trees, including detached descendants.
// Give it the dependency watchers. The daemon supervisor owns worker shutdown.
const watchers = args.includes("--watch-dependencies")
? concurrently(
[
{ command: "npm run watch:protocol", name: "protocol", prefixColor: "yellow" },
{ command: "npm run watch:client", name: "client", prefixColor: "blue" },
],
{
cwd: fileURLToPath(new URL("../../../", import.meta.url)),
killOthersOn: ["success", "failure"],
},
)
: null;
const supervisorArgs = [
...process.execArgv,
daemonRunnerEntry,
"--dev",
...args.filter((arg) => arg !== "--watch-dependencies"),
];
const supervisor = spawn(process.execPath, supervisorArgs, {
stdio: "inherit",
@@ -23,13 +44,32 @@ function exitCodeForSignal(signal: NodeJS.Signals): number {
return signal === "SIGINT" ? 130 : 1;
}
let stopping = false;
let lostWatchers = false;
function forwardSignal(signal: NodeJS.Signals): void {
if (supervisor.exitCode !== null || supervisor.signalCode !== null || supervisor.killed) {
return;
}
stopping = true;
supervisor.kill(signal);
}
const watchersStopped = watchers?.result.catch(() => undefined);
function handleWatchersStopped(): void {
if (stopping || supervisor.exitCode !== null || supervisor.signalCode !== null) return;
lostWatchers = true;
forwardSignal("SIGTERM");
}
void watchersStopped?.then(handleWatchersStopped);
async function finish(exitCode: number): Promise<void> {
stopping = true;
watchers?.commands.forEach((watcher) => watcher.kill());
await watchersStopped;
process.exit(lostWatchers ? 1 : exitCode);
}
// The supervisor handles SIGINT/SIGTERM itself and needs time to drain the
// worker gracefully. Keep this wrapper alive until the supervisor exits so npm
// does not release the shell while the daemon is still logging final shutdown.
@@ -37,9 +77,10 @@ process.on("SIGINT", () => forwardSignal("SIGINT"));
process.on("SIGTERM", () => forwardSignal("SIGTERM"));
supervisor.on("error", (error) => {
throw error;
process.stderr.write(`Failed to start daemon supervisor: ${error.message}\n`);
void finish(1);
});
supervisor.on("exit", (code, signal) => {
process.exit(code ?? (signal ? exitCodeForSignal(signal) : 1));
void finish(code ?? (signal ? exitCodeForSignal(signal) : 1));
});
+5
View File
@@ -316,14 +316,19 @@ export function runSupervisor(options: SupervisorOptions): SupervisorController
}
const spawnSpec = resolveWorkerSpawnSpec?.(workerEntry) ?? null;
// The supervisor receives terminal signals and orders shutdown over IPC.
// Providers must stay alive until the worker has captured restart recovery.
const detached = process.platform !== "win32";
writeLifecycleLog("Spawning worker", { workerEntry });
if (spawnSpec) {
child = spawn(spawnSpec.command, spawnSpec.args, {
detached,
stdio: ["inherit", "pipe", "pipe", "ipc"],
env: spawnSpec.env ?? workerEnv,
});
} else {
child = fork(workerEntry, workerArgs, {
detached,
stdio: ["inherit", "pipe", "pipe", "ipc"],
env: workerEnv,
execArgv: workerExecArgv,
+136 -94
View File
@@ -881,6 +881,7 @@ export class AgentManager {
>();
private readonly collectingRuntimes = new Set<string>();
private readonly lifecycleMutationTails = new Map<string, Promise<void>>();
private readonly pendingCancellations = new Map<string, Promise<unknown>>();
private readonly agentStreamCoalescer: AgentStreamCoalescer;
private mcpBaseUrl: string | null;
private readonly mcpAuthToken: string | null;
@@ -2463,80 +2464,83 @@ export class AgentManager {
// reload or close; providers do no sequencing of their own.
async setAgentMode(agentId: string, modeId: string): Promise<AgentProviderNotice | null> {
return this.runLifecycleMutation(agentId, async () => {
const agent = await this.ensureInteractiveSessionUnlocked(agentId);
const notice = (await agent.session.setMode(modeId)) ?? null;
await this.drainSessionEvents(agentId);
const currentMode = (await agent.session.getCurrentMode()) ?? modeId;
agent.config.modeId = currentMode ?? undefined;
agent.currentModeId = currentMode;
// Update runtimeInfo to reflect the new mode
if (agent.runtimeInfo) {
agent.runtimeInfo = { ...agent.runtimeInfo, modeId: currentMode };
}
this.touchUpdatedAt(agent);
this.emitState(agent);
return notice;
});
return this.runLifecycleMutation(agentId, () =>
this.withLiveInteractiveSessionUnlocked(agentId, async (agent) => {
const notice = (await agent.session.setMode(modeId)) ?? null;
await this.drainSessionEvents(agentId);
const currentMode = (await agent.session.getCurrentMode()) ?? modeId;
agent.config.modeId = currentMode ?? undefined;
agent.currentModeId = currentMode;
// Update runtimeInfo to reflect the new mode
if (agent.runtimeInfo) {
agent.runtimeInfo = { ...agent.runtimeInfo, modeId: currentMode };
}
this.touchUpdatedAt(agent);
this.emitState(agent);
return notice;
}),
);
}
async setAgentModel(agentId: string, modelId: string | null): Promise<void> {
return this.runLifecycleMutation(agentId, async () => {
const agent = await this.ensureInteractiveSessionUnlocked(agentId);
const normalizedModelId =
typeof modelId === "string" && modelId.trim().length > 0 ? modelId : null;
return this.runLifecycleMutation(agentId, () =>
this.withLiveInteractiveSessionUnlocked(agentId, async (agent) => {
const normalizedModelId =
typeof modelId === "string" && modelId.trim().length > 0 ? modelId : null;
const selection = await agent.session.setModel?.(normalizedModelId);
await this.drainSessionEvents(agentId);
const selection = await agent.session.setModel?.(normalizedModelId);
await this.drainSessionEvents(agentId);
// A reset clears the preference even when the provider retains its active model.
let effectiveModelId = normalizedModelId;
if (normalizedModelId !== null && selection) effectiveModelId = selection.model;
// A reset clears the preference even when the provider retains its active model.
let effectiveModelId = normalizedModelId;
if (normalizedModelId !== null && selection) effectiveModelId = selection.model;
agent.config.model = effectiveModelId ?? undefined;
if (agent.runtimeInfo) {
agent.runtimeInfo = { ...agent.runtimeInfo, model: effectiveModelId };
}
this.refreshSessionPersistence(agent);
this.touchUpdatedAt(agent);
this.emitState(agent);
});
agent.config.model = effectiveModelId ?? undefined;
if (agent.runtimeInfo) {
agent.runtimeInfo = { ...agent.runtimeInfo, model: effectiveModelId };
}
this.refreshSessionPersistence(agent);
this.touchUpdatedAt(agent);
this.emitState(agent);
}),
);
}
async setAgentThinkingOption(
agentId: string,
thinkingOptionId: string | null,
): Promise<AgentProviderNotice | null> {
return this.runLifecycleMutation(agentId, async () => {
const agent = await this.ensureInteractiveSessionUnlocked(agentId);
const normalizedThinkingOptionId =
typeof thinkingOptionId === "string" && thinkingOptionId.trim().length > 0
? thinkingOptionId
: null;
return this.runLifecycleMutation(agentId, () =>
this.withLiveInteractiveSessionUnlocked(agentId, async (agent) => {
const normalizedThinkingOptionId =
typeof thinkingOptionId === "string" && thinkingOptionId.trim().length > 0
? thinkingOptionId
: null;
let notice: AgentProviderNotice | null = null;
if (agent.session.setThinkingOption) {
notice = (await agent.session.setThinkingOption(normalizedThinkingOptionId)) ?? null;
}
await this.drainSessionEvents(agentId);
let notice: AgentProviderNotice | null = null;
if (agent.session.setThinkingOption) {
notice = (await agent.session.setThinkingOption(normalizedThinkingOptionId)) ?? null;
}
await this.drainSessionEvents(agentId);
let effectiveThinkingOptionId = normalizedThinkingOptionId;
const runtimeInfo = await agent.session.getRuntimeInfo();
if (runtimeInfo.thinkingOptionId !== undefined) {
effectiveThinkingOptionId = runtimeInfo.thinkingOptionId;
}
let effectiveThinkingOptionId = normalizedThinkingOptionId;
const runtimeInfo = await agent.session.getRuntimeInfo();
if (runtimeInfo.thinkingOptionId !== undefined) {
effectiveThinkingOptionId = runtimeInfo.thinkingOptionId;
}
agent.config.thinkingOptionId = effectiveThinkingOptionId ?? undefined;
if (agent.runtimeInfo) {
agent.runtimeInfo = {
...agent.runtimeInfo,
thinkingOptionId: effectiveThinkingOptionId,
};
}
this.touchUpdatedAt(agent);
this.emitState(agent);
return notice;
});
agent.config.thinkingOptionId = effectiveThinkingOptionId ?? undefined;
if (agent.runtimeInfo) {
agent.runtimeInfo = {
...agent.runtimeInfo,
thinkingOptionId: effectiveThinkingOptionId,
};
}
this.touchUpdatedAt(agent);
this.emitState(agent);
return notice;
}),
);
}
/**
@@ -2546,42 +2550,45 @@ export class AgentManager {
* one step once the provider accepts. Patches to one agent run one at a time, in arrival order.
*/
async setAgentOptions(agentId: string, requested: ProviderOptionsPatch): Promise<void> {
return this.runLifecycleMutation(agentId, async () => {
const agent = await this.ensureInteractiveSessionUnlocked(agentId);
const patch = this.convertLegacyOptions(agent.provider, requested);
let ended: ProviderOptionsPatch = {};
let sent: ProviderOptionsPatch = {};
if (Object.keys(patch).length > 0) {
// A provider that cannot apply options to a running agent must not store them either.
if (!agent.session.applyOptions) {
throw new ProviderOptionsValidationError(
agent.provider,
Object.keys(patch).map((key) => ({
path: [key],
message: "cannot change on a running session; it applies when the agent is opened",
})),
return this.runLifecycleMutation(agentId, () =>
this.withLiveInteractiveSessionUnlocked(agentId, async (agent) => {
const patch = this.convertLegacyOptions(agent.provider, requested);
let ended: ProviderOptionsPatch = {};
let sent: ProviderOptionsPatch = {};
if (Object.keys(patch).length > 0) {
// A provider that cannot apply options to a running agent must not store them either.
if (!agent.session.applyOptions) {
throw new ProviderOptionsValidationError(
agent.provider,
Object.keys(patch).map((key) => ({
path: [key],
message: "cannot change on a running session; it applies when the agent is opened",
})),
);
}
const set = Object.fromEntries(
Object.entries(patch).filter(([, value]) => value != null),
);
const resolved = this.effectiveOptionsFor(agent.provider, set);
sent = Object.fromEntries(Object.keys(patch).map((key) => [key, resolved[key] ?? null]));
const modelBefore = agent.runtimeInfo?.model;
ended = (await agent.session.applyOptions(sent)) ?? {};
// Changes the provider made on its own while applying are older than its final answer.
await this.drainSessionEvents(agentId);
await this.refreshRuntimeInfo(agent, { emit: false });
// An option can choose the model too, as an fx connection does. Reopening the agent on
// the earlier preference would send that model to the new connection.
const modelAfter = agent.runtimeInfo?.model;
if (agent.config.model && modelAfter && modelAfter !== modelBefore) {
agent.config.model = modelAfter;
}
}
const set = Object.fromEntries(Object.entries(patch).filter(([, value]) => value != null));
const resolved = this.effectiveOptionsFor(agent.provider, set);
sent = Object.fromEntries(Object.keys(patch).map((key) => [key, resolved[key] ?? null]));
const modelBefore = agent.runtimeInfo?.model;
ended = (await agent.session.applyOptions(sent)) ?? {};
// Changes the provider made on its own while applying are older than its final answer.
await this.drainSessionEvents(agentId);
await this.refreshRuntimeInfo(agent, { emit: false });
// An option can choose the model too, as an fx connection does. Reopening the agent on
// the earlier preference would send that model to the new connection.
const modelAfter = agent.runtimeInfo?.model;
if (agent.config.model && modelAfter && modelAfter !== modelBefore) {
agent.config.model = modelAfter;
}
}
this.storeOptionsPatch({ agent, patch: { ...patch, ...ended } });
this.updateEffectiveOptions({ agent, sent, reported: ended });
this.touchUpdatedAt(agent);
this.emitState(agent);
});
this.storeOptionsPatch({ agent, patch: { ...patch, ...ended } });
this.updateEffectiveOptions({ agent, sent, reported: ended });
this.touchUpdatedAt(agent);
this.emitState(agent);
}),
);
}
/** The config as the opened session left it: its own difference from the options it was given. */
@@ -3267,6 +3274,33 @@ export class AgentManager {
return this.requireSessionAgent(agentId);
}
/** Inside the agent's lane: transparently reopens a retired plugin session before applying config. */
private async withLiveInteractiveSessionUnlocked<T>(
agentId: string,
operation: (agent: ActiveManagedAgent) => Promise<T>,
): Promise<T> {
const pendingCancellation = this.pendingCancellations.get(agentId);
if (pendingCancellation) {
await this.waitWithTimeout({
operation: pendingCancellation.then(
() => undefined,
() => undefined,
),
timeoutMs: this.rescueTimeouts.interruptSessionMs,
});
}
const agent = await this.ensureInteractiveSessionUnlocked(agentId);
try {
return await operation(agent);
} catch (error) {
if (!isStaleProviderSessionError(error)) throw error;
await this.runs.getPendingRun(agentId)?.settledPromise.catch(() => undefined);
if (this.hasInFlightRun(agentId)) throw error;
await this.trackAgentRegistrationOperation(this.reloadAgentSessionInternal(agentId));
return await operation(this.requireSessionAgent(agentId));
}
}
private async *streamAfterHistoryLoad(
agentId: string,
prompt: AgentPromptInput,
@@ -3925,10 +3959,18 @@ export class AgentManager {
}
async cancelAgentRun(agentId: string): Promise<AgentRunCancellationResult> {
return this.runForegroundMutation(agentId, () => {
const cancellation = this.runForegroundMutation(agentId, () => {
this.requireSessionAgent(agentId).pendingReplacement = false;
return this.cancelAgentRunNow(agentId);
});
this.pendingCancellations.set(agentId, cancellation);
try {
return await cancellation;
} finally {
if (this.pendingCancellations.get(agentId) === cancellation) {
this.pendingCancellations.delete(agentId);
}
}
}
private async cancelAgentRunNow(agentId: string): Promise<AgentRunCancellationResult> {
@@ -4,7 +4,11 @@ import type pino from "pino";
import type { ForgeService } from "../../services/forge-service.js";
import { isPaseoOwnedWorktreeCwd } from "../../utils/worktree.js";
import { archiveByScope, type ActiveWorkspaceRef } from "../workspace-archive-service.js";
import {
archiveByScope,
type ActiveWorkspaceRef,
type ArchiveDependencies,
} from "../workspace-archive-service.js";
import type {
CreatePaseoWorktreeWorkflowFn,
CreatePaseoWorktreeWorkflowResult,
@@ -17,10 +21,15 @@ import type {
} from "../messages.js";
import type { AgentManager, AgentSubscriber, SubscribeOptions } from "./agent-manager.js";
import type { AgentStorage } from "./agent-storage.js";
import type { PluginWorktreeManagerRuntime } from "../plugins/runtime.js";
interface CreateAgentLifecycleDispatchDependencies {
paseoHome: string;
worktreesRoot?: string;
worktreeManagers?: Pick<PluginWorktreeManagerRuntime, "removeWorktree">;
workspaceArchiveOperations?: ArchiveDependencies["workspaceArchiveOperations"];
getWorkspace?: ArchiveDependencies["getWorkspace"];
isCheckoutUntrusted?: ArchiveDependencies["isCheckoutUntrusted"];
agentManager: AgentManager;
agentStorage: AgentStorage;
github: ForgeService;
@@ -184,11 +193,15 @@ export class CreateAgentLifecycleDispatch {
{
paseoHome: this.dependencies.paseoHome,
paseoWorktreesBaseRoot: this.dependencies.worktreesRoot,
worktreeManagers: this.dependencies.worktreeManagers,
workspaceArchiveOperations: this.dependencies.workspaceArchiveOperations,
github: this.dependencies.github,
workspaceGitService: this.dependencies.workspaceGitService,
agentManager: this.dependencies.agentManager,
agentStorage: this.dependencies.agentStorage,
findWorkspaceIdForCwd: this.dependencies.findWorkspaceIdForCwd,
getWorkspace: this.dependencies.getWorkspace,
isCheckoutUntrusted: this.dependencies.isCheckoutUntrusted,
listActiveWorkspaces: this.dependencies.listActiveWorkspaces,
archiveWorkspaceRecord: this.dependencies.archiveWorkspaceRecord,
emitWorkspaceUpdatesForWorkspaceIds: this.dependencies.emitWorkspaceUpdatesForWorkspaceIds,
@@ -6,6 +6,7 @@ import { createIdleRuntimeCleanup } from "./idle-runtime-cleanup/index.js";
import { relative } from "node:path";
import { execFileSync } from "node:child_process";
import { fileURLToPath } from "node:url";
import { runAcpProvider, type AcpStreamMessage } from "@getpaseo/plugin/server/acp";
import type {
ProviderConnection,
ProviderLaunch,
@@ -13,6 +14,7 @@ import type {
ProviderInput,
ProviderRegistration,
} from "@getpaseo/plugin/server/provider";
import { sendPreparedPromptToAgent } from "./agent-prompt.js";
import { setImmediate as nextTurn } from "node:timers/promises";
import { describe, expect, test } from "vitest";
import { createTestLogger } from "../../test-utils/test-logger.js";
@@ -256,6 +258,38 @@ function eventsOfType(events: AgentStreamEvent[], type: AgentStreamEvent["type"]
return events.filter((event) => event.type === type);
}
test("preserves skills in a plugin session's command list", async () => {
const harness = createProviderHarness();
const registry = new PluginAgentClientRegistry(createTestLogger());
registry.replace([harness.registration]);
const session = await registry.clients()[harness.registration.id]!.createSession({
provider: harness.registration.id,
cwd: tmpdir(),
});
try {
const open = harness.inputs.find((input) => input.type === "session.open")!;
harness.emit({
type: "session.commands",
sessionId: open.sessionId,
commands: [
{ name: "compact", description: "Compact the conversation" },
{ name: "diagnose", description: "Diagnose a bug", kind: "skill" },
],
});
await expect(session.listCommands!()).resolves.toEqual([
{
name: "compact",
description: "Compact the conversation",
argumentHint: "",
kind: "command",
},
{ name: "diagnose", description: "Diagnose a bug", argumentHint: "", kind: "skill" },
]);
} finally {
await session.close();
}
});
function createRewindProviderHarness(
options: {
reuseAnswerId?: boolean;
@@ -2814,3 +2848,592 @@ test("resumes a goose session saved by the generic ACP provider", async () => {
await plugins.shutdown();
}
});
test("preserves a deferred ACP background job on steer and cancels it on explicit Stop through AgentManager", async () => {
const logger = createTestLogger();
const home = await mkdtemp(join(tmpdir(), "paseo-acp-deferred-daemon-"));
const storage = new AgentStorage(join(home, "agents"), logger);
let cancelCount = 0;
let promptCount = 0;
let currentMode = "default";
let notifyAgent: ((message: AcpStreamMessage) => void) | null = null;
let holdNextPrompt: ((release: () => void) => void) | null = null;
const modeConfig = () => [
{
id: "mode",
name: "Mode",
category: "mode",
type: "select",
currentValue: currentMode,
options: [
{ value: "default", name: "Default" },
{ value: "plan", name: "Plan" },
],
},
];
const registration = runAcpProvider({
id: "deferred-acp-daemon",
label: "Deferred ACP Daemon",
acpOptions: {
deferTurnOnRunningTools: { settleDelayMs: 25, quietLimitMs: 1_000 },
},
connector() {
let controller!: ReadableStreamDefaultController<AcpStreamMessage>;
const readable = new ReadableStream<AcpStreamMessage>({
start(ctrl) {
controller = ctrl;
},
});
const send = (message: AcpStreamMessage) => controller.enqueue(message);
notifyAgent = send;
const writable = new WritableStream<AcpStreamMessage>({
write(message) {
if (!("method" in message)) return;
if (message.method === "session/cancel") {
cancelCount += 1;
return;
}
if (!("id" in message)) return;
if (message.method === "initialize") {
send({
jsonrpc: "2.0",
id: message.id,
result: { protocolVersion: 1, agentCapabilities: { loadSession: true } },
});
return;
}
if (message.method === "session/new") {
send({
jsonrpc: "2.0",
id: message.id,
result: { sessionId: "acp-s1", configOptions: modeConfig() },
});
return;
}
if (message.method === "session/load") {
send({ jsonrpc: "2.0", id: message.id, result: { configOptions: modeConfig() } });
return;
}
if (message.method === "session/set_config_option") {
const params = message.params as { value?: string } | undefined;
if (typeof params?.value === "string") currentMode = params.value;
send({ jsonrpc: "2.0", id: message.id, result: { configOptions: modeConfig() } });
return;
}
if (message.method === "session/prompt") {
promptCount += 1;
if (promptCount === 1) {
send({
jsonrpc: "2.0",
method: "session/update",
params: {
sessionId: "acp-s1",
update: {
sessionUpdate: "tool_call",
toolCallId: "bg-job-1",
name: "run_command",
title: "Background job",
status: "in_progress",
},
},
});
} else if (promptCount === 2) {
send({
jsonrpc: "2.0",
method: "session/update",
params: {
sessionId: "acp-s1",
update: {
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: "Steered reply" },
},
},
});
} else {
send({
jsonrpc: "2.0",
method: "session/update",
params: {
sessionId: "acp-s1",
update: {
sessionUpdate: "tool_call",
toolCallId: "bg-job-2",
name: "run_command",
title: "Cancelable job",
status: "in_progress",
},
},
});
}
if (holdNextPrompt) {
const hook = holdNextPrompt;
holdNextPrompt = null;
hook(() =>
send({ jsonrpc: "2.0", id: message.id, result: { stopReason: "cancelled" } }),
);
return;
}
send({ jsonrpc: "2.0", id: message.id, result: { stopReason: "end_turn" } });
return;
}
if (message.method === "session/close") {
send({ jsonrpc: "2.0", id: message.id, result: {} });
}
},
});
return { readable, writable };
},
});
const plugins = new PluginAgentClientRegistry(logger);
plugins.replace([registration]);
const manager = new AgentManager({ clients: plugins.clients(), registry: storage, logger });
try {
const agent = await manager.createAgent({ provider: registration.id, cwd: home }, undefined, {
workspaceId: undefined,
});
const first = await sendPreparedPromptToAgent({
agentManager: manager,
agentStorage: storage,
agentId: agent.id,
prompt: "start background job",
logger,
});
expect(first.disposition).toBe("turn_started");
if (first.disposition === "turn_started") await first.started;
await new Promise((resolve) => setTimeout(resolve, 40));
expect(manager.getAgent(agent.id)?.lifecycle).toBe("running");
// Follow-up steer through AgentManager preserves the background job without session/cancel.
const followUp = await sendPreparedPromptToAgent({
agentManager: manager,
agentStorage: storage,
agentId: agent.id,
prompt: "still working?",
activeTurnBehavior: "steer",
logger,
});
expect(followUp.disposition).toBe("steered");
expect(cancelCount).toBe(0);
await new Promise((resolve) => setTimeout(resolve, 40));
expect(manager.getAgent(agent.id)?.lifecycle).toBe("running");
// Completing the job + reply + usage_update settles the turn cleanly.
notifyAgent!({
jsonrpc: "2.0",
method: "session/update",
params: {
sessionId: "acp-s1",
update: { sessionUpdate: "tool_call_update", toolCallId: "bg-job-1", status: "completed" },
},
});
notifyAgent!({
jsonrpc: "2.0",
method: "session/update",
params: {
sessionId: "acp-s1",
update: {
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: "Background job finished." },
},
},
});
notifyAgent!({
jsonrpc: "2.0",
method: "session/update",
params: {
sessionId: "acp-s1",
update: { sessionUpdate: "usage_update", used: 120, size: 1000 },
},
});
await expect.poll(() => manager.getAgent(agent.id)?.lifecycle, { timeout: 3_000 }).toBe("idle");
expect(cancelCount).toBe(0);
// Start a second deferred job, send two steers while steer 1 waits on ACP, and press Stop.
let heldSteerResponse: (() => void) | null = null;
const second = await sendPreparedPromptToAgent({
agentManager: manager,
agentStorage: storage,
agentId: agent.id,
prompt: "start cancelable job",
logger,
});
if (second.disposition === "turn_started") await second.started;
await new Promise((resolve) => setTimeout(resolve, 40));
expect(manager.getAgent(agent.id)?.lifecycle).toBe("running");
// Hold the next steer prompt so Stop races with a queued second steer.
holdNextPrompt = (release) => {
heldSteerResponse = release;
};
const steerOne = await sendPreparedPromptToAgent({
agentManager: manager,
agentStorage: storage,
agentId: agent.id,
prompt: "held steer 1",
activeTurnBehavior: "steer",
logger,
});
expect(steerOne.disposition).toBe("steered");
const steerTwo = await sendPreparedPromptToAgent({
agentManager: manager,
agentStorage: storage,
agentId: agent.id,
prompt: "queued steer 2",
activeTurnBehavior: "steer",
logger,
});
expect(steerTwo.disposition).toBe("steered");
await expect.poll(() => heldSteerResponse).not.toBeNull();
const promptsBeforeStop = promptCount;
// Stop must send session/cancel immediately, retire the deferred session cleanly,
// and never dispatch the queued steer 2 to ACP.
await manager.cancelAgentRun(agent.id);
expect(cancelCount).toBe(1);
await expect.poll(() => manager.getAgent(agent.id)?.lifecycle, { timeout: 3_000 }).toBe("idle");
expect(promptCount).toBe(promptsBeforeStop);
// Changing mode immediately after stopping a deferred turn must transparently reopen the session.
await manager.setAgentMode(agent.id, "plan");
expect(manager.getAgent(agent.id)?.currentModeId).toBe("plan");
expect(currentMode).toBe("plan");
} finally {
await Promise.all(manager.listAgents().map((item) => manager.closeAgent(item.id)));
await plugins.shutdown();
await storage.flush();
await rm(home, { recursive: true, force: true });
}
});
test("reopens cleanly for mode changes and follow-up sends initiated while Stop is closing a slow ACP process", async () => {
const logger = createTestLogger();
const home = await mkdtemp(join(tmpdir(), "paseo-acp-slow-stop-"));
const storage = new AgentStorage(join(home, "agents"), logger);
const script = join(home, "slow-stop-agent.cjs");
const { writeFile } = await import("node:fs/promises");
await writeFile(
script,
`
const { createInterface } = require("node:readline");
const send = (msg) => process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...msg }) + "\\n");
let mode = "default";
const configOptions = () => [{
id: "mode", name: "Mode", category: "mode", type: "select", currentValue: mode,
options: [{ value: "default", name: "Default" }, { value: "plan", name: "Plan" }],
}];
process.on("SIGTERM", () => {
setTimeout(() => process.exit(0), 250);
});
createInterface({ input: process.stdin }).on("line", (line) => {
const msg = JSON.parse(line);
if (msg.method === "initialize") {
send({ id: msg.id, result: { protocolVersion: 1, agentCapabilities: { loadSession: true } } });
} else if (msg.method === "session/new") {
send({ id: msg.id, result: { sessionId: "slow-s1", configOptions: configOptions() } });
} else if (msg.method === "session/load") {
send({ id: msg.id, result: { configOptions: configOptions() } });
} else if (msg.method === "session/set_config_option") {
if (msg.params && typeof msg.params.value === "string") mode = msg.params.value;
send({ id: msg.id, result: { configOptions: configOptions() } });
} else if (msg.method === "session/prompt") {
const text = msg.params?.prompt?.[0]?.text ?? "";
if (text.includes("start bg")) {
send({ method: "session/update", params: { sessionId: "slow-s1", update: {
sessionUpdate: "tool_call", toolCallId: "slow-bg-1", name: "run_command",
title: "Slow bg job", status: "in_progress",
} } });
} else {
send({ method: "session/update", params: { sessionId: "slow-s1", update: {
sessionUpdate: "agent_message_chunk", content: { type: "text", text: "After stop reply" },
} } });
}
send({ id: msg.id, result: { stopReason: "end_turn" } });
} else if (msg.method === "session/close") {
send({ id: msg.id, result: {} });
}
});
`,
);
const registration = runAcpProvider({
id: "slow-stop-acp",
label: "Slow Stop ACP",
command: [process.execPath, script],
acpOptions: {
deferTurnOnRunningTools: { settleDelayMs: 25, quietLimitMs: 1_000 },
},
});
const plugins = new PluginAgentClientRegistry(logger);
plugins.replace([registration]);
const manager = new AgentManager({ clients: plugins.clients(), registry: storage, logger });
try {
const agent = await manager.createAgent({ provider: registration.id, cwd: home }, undefined, {
workspaceId: undefined,
});
const first = await sendPreparedPromptToAgent({
agentManager: manager,
agentStorage: storage,
agentId: agent.id,
prompt: "start bg",
logger,
});
if (first.disposition === "turn_started") await first.started;
await new Promise((resolve) => setTimeout(resolve, 40));
expect(manager.getAgent(agent.id)?.lifecycle).toBe("running");
// Start Stop (takes 250ms to terminate the child on SIGTERM) and trigger a mode change mid-shutdown.
const stopPromise = manager.cancelAgentRun(agent.id);
await new Promise((resolve) => setTimeout(resolve, 50));
const modePromise = manager.setAgentMode(agent.id, "plan");
await Promise.all([stopPromise, modePromise]);
expect(manager.getAgent(agent.id)?.currentModeId).toBe("plan");
expect(manager.getAgent(agent.id)?.lifecycle).toBe("idle");
// A follow-up prompt immediately after Stop + mode change succeeds cleanly.
const next = await sendPreparedPromptToAgent({
agentManager: manager,
agentStorage: storage,
agentId: agent.id,
prompt: "fresh prompt",
logger,
});
expect(next.disposition).toBe("turn_started");
if (next.disposition === "turn_started") await next.started;
await expect.poll(() => manager.getAgent(agent.id)?.lifecycle, { timeout: 3_000 }).toBe("idle");
} finally {
await Promise.all(manager.listAgents().map((item) => manager.closeAgent(item.id)));
await plugins.shutdown();
await storage.flush();
await rm(home, { recursive: true, force: true });
}
});
test("does not block mode changes after a plugin refuses Stop by ignoring session.interrupt", async () => {
const logger = createTestLogger();
let currentMode = "code";
const harness = createProviderHarness({
async handleInput(input, emit) {
if (input.type === "session.open") {
emit({
type: "session.opened",
requestId: input.requestId,
sessionId: input.sessionId,
capabilities: ["prompt.message", "session.interrupt", "session.configure"],
restoration: "core",
title: input.config.title,
cwd: input.config.cwd,
});
emit({
type: "session.config",
sessionId: input.sessionId,
config: {
mode: currentMode,
modes: [
{ id: "code", label: "Code" },
{ id: "plan", label: "Plan" },
],
models: [],
thinkingOptions: [],
},
});
emit({ type: "session.ready", requestId: input.requestId, sessionId: input.sessionId });
return true;
}
if (input.type === "session.prompt") {
emit({
type: "session.prompt_result",
sessionId: input.sessionId,
clientMessageId: input.prompt.clientMessageId,
result: { type: "turn", turnId: "hung-turn" },
});
emit({
type: "session.turn",
sessionId: input.sessionId,
turnId: "hung-turn",
state: "started",
});
return true;
}
if (input.type === "session.interrupt") {
// Intentionally never acknowledge session.interrupt.
return true;
}
if (input.type === "session.configure") {
if (input.changes.mode) currentMode = input.changes.mode;
emit({
type: "session.config",
sessionId: input.sessionId,
config: {
mode: currentMode,
modes: [
{ id: "code", label: "Code" },
{ id: "plan", label: "Plan" },
],
models: [],
thinkingOptions: [],
},
});
emit({ type: "request.completed", requestId: input.requestId });
return true;
}
return false;
},
});
const plugins = new PluginAgentClientRegistry(logger);
plugins.replace([harness.registration]);
const registry = buildProviderRegistry(logger, { pluginProviders: plugins.definitions() });
const manager = new AgentManager({
logger,
clients: { "plugin-direct": registry["plugin-direct"].createClient(logger) },
providerDefinitions: { "plugin-direct": registry["plugin-direct"] },
rescueTimeouts: { interruptSessionMs: 50 },
});
try {
const agent = await manager.createAgent(
{ provider: "plugin-direct", cwd: tmpdir() },
undefined,
{ workspaceId: undefined },
);
const stream = manager.streamAgent(agent.id, "start");
void stream.next();
await expect
.poll(() => manager.getAgent(agent.id)?.lifecycle, { timeout: 2_000 })
.toBe("running");
const cancelResult = await manager.cancelAgentRun(agent.id);
expect(cancelResult.status).toBe("refused");
// Settings change must not hang behind the unacknowledged session.interrupt.
await manager.setAgentMode(agent.id, "plan");
expect(manager.getAgent(agent.id)?.currentModeId).toBe("plan");
} finally {
await Promise.all(manager.listAgents().map((item) => manager.closeAgent(item.id)));
await plugins.shutdown();
}
});
test("bounds settings wait when Stop is queued behind an unanswered steer", async () => {
const logger = createTestLogger();
let currentMode = "code";
let releaseSteer: (() => void) | null = null;
const harness = createProviderHarness({
capabilities: ["prompt.message", "prompt.steer", "session.interrupt", "session.configure"],
async handleInput(input, emit) {
if (input.type === "session.open") {
emit({
type: "session.opened",
requestId: input.requestId,
sessionId: input.sessionId,
capabilities: [
"prompt.message",
"prompt.steer",
"session.interrupt",
"session.configure",
],
restoration: "core",
title: input.config.title,
cwd: input.config.cwd,
});
emit({
type: "session.config",
sessionId: input.sessionId,
config: {
mode: currentMode,
modes: [
{ id: "code", label: "Code" },
{ id: "plan", label: "Plan" },
],
models: [],
thinkingOptions: [],
},
});
emit({ type: "session.ready", requestId: input.requestId, sessionId: input.sessionId });
return true;
}
if (input.type === "session.prompt") {
if (input.prompt.delivery === "steer") {
releaseSteer = () =>
emit({
type: "session.prompt_result",
sessionId: input.sessionId,
clientMessageId: input.prompt.clientMessageId,
result: { type: "steer", turnId: "steer-turn" },
});
return true;
}
emit({
type: "session.prompt_result",
sessionId: input.sessionId,
clientMessageId: input.prompt.clientMessageId,
result: { type: "turn", turnId: "steer-turn" },
});
emit({
type: "session.turn",
sessionId: input.sessionId,
turnId: "steer-turn",
state: "started",
});
return true;
}
if (input.type === "session.interrupt") {
return true;
}
if (input.type === "session.configure") {
if (input.changes.mode) currentMode = input.changes.mode;
emit({
type: "session.config",
sessionId: input.sessionId,
config: {
mode: currentMode,
modes: [
{ id: "code", label: "Code" },
{ id: "plan", label: "Plan" },
],
models: [],
thinkingOptions: [],
},
});
emit({ type: "request.completed", requestId: input.requestId });
return true;
}
return false;
},
});
const plugins = new PluginAgentClientRegistry(logger);
plugins.replace([harness.registration]);
const registry = buildProviderRegistry(logger, { pluginProviders: plugins.definitions() });
const manager = new AgentManager({
logger,
clients: { "plugin-direct": registry["plugin-direct"].createClient(logger) },
providerDefinitions: { "plugin-direct": registry["plugin-direct"] },
rescueTimeouts: { interruptSessionMs: 50 },
});
try {
const agent = await manager.createAgent(
{ provider: "plugin-direct", cwd: tmpdir() },
undefined,
{ workspaceId: undefined },
);
const stream = manager.streamAgent(agent.id, "start");
void stream.next();
await expect
.poll(() => manager.getAgent(agent.id)?.lifecycle, { timeout: 2_000 })
.toBe("running");
// Start an unanswered steer, queue Stop behind it, then change mode.
const steerPromise = manager.steerAgentRun(agent.id, "unanswered steer").catch(() => undefined);
await new Promise((resolve) => setTimeout(resolve, 20));
const stopPromise = manager.cancelAgentRun(agent.id);
await new Promise((resolve) => setTimeout(resolve, 10));
// Mode change must complete within the bounded interrupt timeout even while Stop is queued.
await manager.setAgentMode(agent.id, "plan");
expect(manager.getAgent(agent.id)?.currentModeId).toBe("plan");
releaseSteer?.();
await Promise.all([steerPromise, stopPromise]);
} finally {
releaseSteer?.();
await Promise.all(manager.listAgents().map((item) => manager.closeAgent(item.id)));
await plugins.shutdown();
}
});
@@ -19,6 +19,7 @@ import {
type ProviderLaunch,
requireProviderCapabilities,
type ProviderCapability,
type ProviderCommand,
type ProviderConfigChanges,
type ProviderConfigState,
type ProviderConnection,
@@ -663,7 +664,7 @@ class ProviderRuntimeSession {
private closedByProvider = false;
private closePromise: Promise<void> | null = null;
config: ProviderConfigState = { models: [], modes: [], thinkingOptions: [] };
commands: Array<{ name: string; description: string; argumentHint?: string }> = [];
commands: ProviderCommand[] = [];
persistence: ProviderPersistence | null = null;
constructor(
@@ -739,6 +740,7 @@ class ProviderRuntimeSession {
}
async configure(changes: ProviderConfigChanges): Promise<void> {
if (this.terminal) throw new StaleProviderSessionError(this.id);
const input: Extract<ProviderInput, { type: "session.configure" }> = {
type: "session.configure",
requestId: randomUUID(),
@@ -1500,7 +1502,7 @@ class PluginAgentSession implements AgentSession {
return this.bridge.commands.map((command) => ({
...command,
argumentHint: command.argumentHint ?? "",
kind: "command",
kind: command.kind ?? "command",
}));
}
@@ -99,6 +99,74 @@ describe("ClaudeAgentSession persisted history load", () => {
rmSync(tempRoot, { recursive: true, force: true });
});
test("resumes many records within a chunk-sized event-loop turn budget", async () => {
const count = 3_072;
const text = "🙂".repeat(128);
const entries = Array.from({ length: count }, (_, index) =>
JSON.stringify({ type: "assistant", message: { content: `${index}:${text}` } }),
);
entries.splice(count / 2, 0, JSON.stringify({ type: "system", subtype: "compact_boundary" }));
mkdirSync(path.dirname(transcriptPath()), { recursive: true });
writeFileSync(transcriptPath(), entries.join("\n"));
let turns = 0;
let ticker: NodeJS.Immediate;
function tick() {
turns++;
const deadline = performance.now() + 2;
while (performance.now() < deadline) {}
ticker = setImmediate(tick);
}
ticker = setImmediate(tick);
const session = await resume().finally(() => clearImmediate(ticker));
try {
const messages = [];
for await (const event of session.streamHistory()) {
if (event.type === "timeline" && event.item.type === "assistant_message") {
messages.push(event.item.text);
}
}
expect(messages).toEqual(Array.from({ length: count }, (_, index) => `${index}:${text}`));
expect(turns).toBeLessThan(count);
} finally {
await session.close();
}
}, 30_000);
test("yields during replay of a dense window with an expensive consumer", async () => {
const file = transcriptPath();
const count = 500;
const record = JSON.stringify({ type: "assistant", message: { content: "saved reply" } });
mkdirSync(path.dirname(file), { recursive: true });
writeFileSync(file, (record + "\n").repeat(count));
await withClaudeReplayHistory(file, async (history) => {
let turns = 0;
let ticker: NodeJS.Immediate | undefined;
function tick() {
turns++;
ticker = setImmediate(tick);
}
let entries = 0;
try {
for await (const _entry of history.parentEntries) {
// Start counting after the read so only yields within the window count.
ticker ??= setImmediate(tick);
const deadline = performance.now() + 1;
while (performance.now() < deadline) {}
entries++;
}
} finally {
if (ticker) clearImmediate(ticker);
}
expect(entries).toBe(count);
expect(turns).toBeGreaterThanOrEqual(20);
});
});
test("serves unrelated health requests while resuming 32 MiB of ordered history", async () => {
const startedAt = performance.now();
mkdirSync(path.dirname(transcriptPath()), { recursive: true });
@@ -700,6 +768,75 @@ describe("ClaudeAgentSession persisted history load", () => {
},
);
test.each(["return", "throw"])(
"replays oversized records and closes every source after callback %s",
async (exit) => {
const parent = transcriptPath();
const directory = path.join(parent.slice(0, -".jsonl".length), "subagents");
const child = path.join(directory, "agent-child.jsonl");
const workflow = path.join(directory, "workflows", "wf_test", "agent-child.jsonl");
const notification = {
type: "system",
subtype: "task_notification",
task_id: "task-id",
status: "completed",
};
const result = {
type: "user",
message: {
content: [
{ type: "tool_result", tool_use_id: "tool-id", content: "é".repeat(600 * 1024) },
],
},
};
const parentRecords = [notification, result, notification];
const childRecords = parentRecords.map((entry) => ({
...entry,
isSidechain: true,
agentId: "child",
}));
mkdirSync(path.dirname(workflow), { recursive: true });
writeFileSync(parent, parentRecords.map((entry) => JSON.stringify(entry)).join("\n"));
writeFileSync(child, childRecords.map((entry) => JSON.stringify(entry)).join("\n"));
writeFileSync(workflow, childRecords.map((entry) => JSON.stringify(entry)).join("\n"));
const sources: AsyncIterable<unknown>[] = [];
const failure = new Error("consumer failed");
const replay = withClaudeReplayHistory(parent, async (history) => {
const parentEntries = await Array.fromAsync(history.parentEntries);
const firstId = expect.stringMatching(/^task_notification_.*_1$/);
const secondId = expect.stringMatching(/^task_notification_.*_2$/);
expect(parentEntries).toEqual([
{ ...notification, notificationId: firstId },
result,
{ ...notification, notificationId: secondId },
]);
const [first, , last] = parentEntries;
const childEntries = history.subagents[0]!.entries;
const workflowEntries = history.workflowEntriesByRunId.get("wf_test")!;
sources.push(history.parentEntries, childEntries, workflowEntries);
const expectedChildEntries = [
{ ...childRecords[0], notificationId: first!.notificationId },
childRecords[1],
{ ...childRecords[2], notificationId: last!.notificationId },
];
expect(await Array.fromAsync(childEntries)).toEqual(expectedChildEntries);
expect(await Array.fromAsync(workflowEntries)).toEqual(expectedChildEntries);
expect(await Array.fromAsync(history.parentEntries)).toEqual(parentEntries);
if (exit === "throw") throw failure;
});
if (exit === "throw") await expect(replay).rejects.toBe(failure);
else await replay;
// Reading again probes whether replay released each descriptor when the callback ended.
for (const source of sources) {
await expect(source[Symbol.asyncIterator]().next()).rejects.toMatchObject({
code: "EBADF",
});
}
},
);
// chmod does not remove read access on Windows, or for root.
test.skipIf(process.platform === "win32" || process.getuid?.() === 0)(
"logs a warning with the error when Claude's project folders cannot be listed",
@@ -878,11 +878,12 @@ describe("ClaudeAgentSession persisted subagent replay", () => {
const text = "é🙂".repeat(30_000);
const historyDir = claudeProjectDirSync(cwd, { configDir });
mkdirSync(historyDir, { recursive: true });
const first = parentEntry([{ type: "text", text }]);
// Put the first byte of é at the end of a 1 MiB read.
const padding = " ".repeat(1024 * 1024 - 1 - first.indexOf(text));
writeFileSync(
path.join(historyDir, "replay-session.jsonl"),
parentEntry([{ type: "text", text }]) +
"\r\nnot json\r\n" +
parentEntry([{ type: "text", text: "final row" }]),
padding + first + "\r\nnot json\r\n" + parentEntry([{ type: "text", text: "final row" }]),
);
const events = await replayEvents();
expect(events.filter((event) => event.type === "timeline").map((event) => event.item)).toEqual([
@@ -41,6 +41,34 @@ function parentEntries(
}
describe("Claude workflow replay", () => {
it("skips parent history when there are no workflow summaries", async () => {
const entries = {
[Symbol.iterator](): Iterator<ClaudeWorkflowParentEntry> {
throw new Error("parent history must not be read");
},
};
await expect(
observeReplayWorkflows({ workflows: [], parentEntries: entries }),
).resolves.toEqual([]);
});
it("links workflow results from a single traversal, including results before their calls", async () => {
const [call, result] = parentEntries();
const entries = (async function* () {
yield result!;
yield call!;
})();
const observations = await observeReplayWorkflows({
workflows: [{ runId: RUN_ID, status: "completed" }],
parentEntries: entries,
});
expect(observations).toEqual([
{ kind: "declared", id: TOOL_CALL_ID, toolCallId: TOOL_CALL_ID, title: "Workflow" },
{ kind: "subtitle", id: TOOL_CALL_ID, subtitle: "Workflow" },
{ kind: "status", id: TOOL_CALL_ID, status: "completed" },
]);
});
it("parses the persisted run summary observed from Claude Code 2.1.220", async () => {
expect(
parseClaudeWorkflowRun(
@@ -55,7 +55,9 @@ export async function observeReplayWorkflows(input: {
>;
convertEntry?: (entry: ClaudeReplayEntry) => AgentTimelineItem[] | Promise<AgentTimelineItem[]>;
}): Promise<SubagentObservation[]> {
const toolCallIdByRunId = await readWorkflowLinks(input.parentEntries);
if (input.workflows.length === 0) return [];
const runIds = new Set(input.workflows.map((workflow) => workflow.runId));
const toolCallIdByRunId = await readWorkflowLinks(input.parentEntries, runIds);
const observations: SubagentObservation[] = [];
for (const workflow of input.workflows) {
@@ -155,34 +157,33 @@ async function observeWorkflowTimeline(input: {
async function readWorkflowLinks(
entries: Iterable<ClaudeWorkflowParentEntry> | AsyncIterable<ClaudeWorkflowParentEntry>,
runIds: ReadonlySet<string>,
): Promise<Map<string, string>> {
const workflowToolCallIds = new Set<string>();
const toolCallIdByRunId = new Map<string, string>();
for await (const entry of entries) {
const content = entry.message?.content;
if (!Array.isArray(content)) continue;
for (const value of content) {
const block = toRecord(value);
if (block?.type !== "tool_use" || block.name !== "Workflow") continue;
const id = readString(block.id);
if (id) workflowToolCallIds.add(id);
}
}
const results: { runId: string; toolCallId: string }[] = [];
for await (const entry of entries) {
const content = entry.message?.content;
if (!Array.isArray(content)) continue;
for (const value of content) {
const block = toRecord(value);
if (block?.type === "tool_use" && block.name === "Workflow") {
const id = readString(block.id);
if (id) workflowToolCallIds.add(id);
}
if (block?.type !== "tool_result") continue;
const toolCallId = readString(block.tool_use_id);
if (!toolCallId || !workflowToolCallIds.has(toolCallId)) continue;
if (!toolCallId) continue;
const runId = readRunId(block.content);
if (runId) toolCallIdByRunId.set(runId, toolCallId);
if (runId && runIds.has(runId)) results.push({ runId, toolCallId });
}
}
// Resolve IDs in result order after all calls are known, even if a result precedes its call.
const toolCallIdByRunId = new Map<string, string>();
for (const { runId, toolCallId } of results) {
if (workflowToolCallIds.has(toolCallId)) toolCallIdByRunId.set(runId, toolCallId);
}
return toolCallIdByRunId;
}
@@ -13,6 +13,10 @@ import {
type ClaudeWorkflowRun,
} from "./subagents/workflow-replay-source.js";
const READ_CHUNK_BYTES = 1024 * 1024;
// Async iteration between reads uses microtasks, including work inside the consumer.
const REPLAY_SLICE_MS = 10;
interface TranscriptEntry extends ClaudeReplayEntry {
isSidechain?: unknown;
}
@@ -43,13 +47,18 @@ async function* locatedRecords(
let pieces: Buffer[] = [];
let length = 0;
while (remaining > 0) {
const buffer = Buffer.allocUnsafe(Math.min(64 * 1024, remaining));
const buffer = Buffer.allocUnsafe(Math.min(READ_CHUNK_BYTES, remaining));
const { bytesRead: count } = await fd.read(buffer, 0, buffer.length, null);
if (count === 0) break;
remaining -= count;
let sliceStartedAt = performance.now();
let start = 0;
let end: number;
while ((end = buffer.indexOf(10, start)) !== -1 && end < count) {
if (performance.now() - sliceStartedAt >= REPLAY_SLICE_MS) {
await setImmediate();
sliceStartedAt = performance.now();
}
pieces.push(buffer.subarray(start, end));
length += end - start;
const entry = parseRecord(Buffer.concat(pieces, length).toString("utf8"));
@@ -65,8 +74,6 @@ async function* locatedRecords(
if (entry) yield { entry, location };
start = end + 1;
}
// Bound parsing work as well as IO; microtasks alone do not service timers or sockets.
await setImmediate();
if (start < count) {
pieces.push(buffer.subarray(start, count));
length += count - start;
@@ -96,27 +103,52 @@ function indexedRecords(
},
};
async function* readEntries(): AsyncGenerator<TranscriptEntry> {
const chunk = Buffer.allocUnsafe(READ_CHUNK_BYTES);
let window: { file: string; offset: number; bytes: Buffer } | undefined;
let sliceStartedAt = performance.now();
for (const location of locations) {
const fd = descriptors.get(location.file)!;
const buffer = Buffer.allocUnsafe(location.length);
let read = 0;
while (read < buffer.length) {
const { bytesRead: count } = await fd.read(
buffer,
read,
buffer.length - read,
location.offset + read,
);
if (count === 0)
throw new Error(`Claude transcript was truncated during replay: ${location.file}`);
read += count;
if (
window?.file !== location.file ||
location.offset < window.offset ||
location.offset + location.length > window.offset + window.bytes.length
) {
const fd = descriptors.get(location.file)!;
const buffer = location.length > chunk.length ? Buffer.allocUnsafe(location.length) : chunk;
// Read ahead from the next indexed record. The index still owns selection and order,
// including sparse sidechains and workflow records sorted across files.
window = {
file: location.file,
offset: location.offset,
bytes: await readRecordWindow(fd, buffer, location),
};
sliceStartedAt = performance.now();
}
const entry = parseRecord(buffer.toString("utf8"));
if (performance.now() - sliceStartedAt >= REPLAY_SLICE_MS) {
await setImmediate();
sliceStartedAt = performance.now();
}
const start = location.offset - window.offset;
const entry = parseRecord(window.bytes.toString("utf8", start, start + location.length));
if (entry) yield entry;
}
}
}
async function readRecordWindow(
fd: FileHandle,
buffer: Buffer,
location: RecordLocation,
): Promise<Buffer> {
let read = 0;
while (read < location.length) {
const { bytesRead } = await fd.read(buffer, read, buffer.length - read, location.offset + read);
if (bytesRead === 0)
throw new Error(`Claude transcript was truncated during replay: ${location.file}`);
read += bytesRead;
}
return buffer.subarray(0, read);
}
function isToolResult(entry: TranscriptEntry): boolean {
return (
Array.isArray(entry.message?.content) &&
@@ -1,4 +1,13 @@
import { existsSync, rmSync, statSync } from "node:fs";
import {
existsSync,
mkdtempSync,
readFileSync,
rmSync,
statSync,
symlinkSync,
writeFileSync,
} from "node:fs";
import os from "node:os";
import path from "node:path";
import { describe, expect, test } from "vitest";
@@ -22,3 +31,30 @@ describe.skipIf(process.platform === "win32")("materializeProviderImage", () =>
}
});
});
test.skipIf(process.platform === "win32")(
"replaces a cached attachment directory turned into a symlink",
async () => {
const image = { data: "c3ltbGluayByZWdyZXNzaW9u", mimeType: "image/png" };
const first = await materializeProviderImage(image);
const dir = path.dirname(first.path);
const target = mkdtempSync(path.join(os.tmpdir(), "paseo-image-symlink-test-"));
let replacement: string | undefined;
try {
rmSync(dir, { recursive: true });
// Populate the target to exercise validation before accepting a cache hit.
writeFileSync(path.join(target, path.basename(first.path)), "symlink target");
symlinkSync(target, dir, "dir");
const second = await materializeProviderImage(image);
replacement = path.dirname(second.path);
expect(replacement).not.toBe(dir);
expect(path.basename(replacement)).toMatch(/^paseo-attachments-/);
expect(readFileSync(second.path, "utf8")).toBe("symlink regression");
} finally {
if (replacement && replacement !== dir) rmSync(replacement, { recursive: true });
rmSync(dir, { recursive: true, force: true });
rmSync(target, { recursive: true, force: true });
}
},
);
@@ -1,3 +1,4 @@
import { AsyncLocalStorage, createHook } from "node:async_hooks";
import { existsSync, rmSync, statSync, readFileSync } from "node:fs";
import path from "node:path";
import MarkdownIt from "markdown-it";
@@ -211,7 +212,7 @@ test("64 MiB materialization leaves the event loop responsive and preserves byte
});
test("preserves base64 decoding across whitespace and chunk boundaries", async () => {
const bytes = Buffer.alloc(512 * 1024, 123);
const bytes = Buffer.alloc(1024 * 1024, 123);
const base64 = bytes.toString("base64");
const data = base64.match(/.{1,77}/g)!.join("\n");
const result = await materializeProviderImage({ data, mimeType: "image/png" });
@@ -247,3 +248,114 @@ test("simultaneous requests for the same content share the published file", asyn
expect(results[0]).toEqual(results[1]);
expect(readFileSync(results[0].path).toString()).toBe("concurrent dedupe fixture");
});
test("a small image finishes before an earlier distinct 64 MiB image", async () => {
const largeData = Buffer.alloc(64 * 1024 * 1024, 42).toString("base64");
const smallData = Buffer.from("live image during large replay").toString("base64");
const completionOrder: string[] = [];
const large = materializeProviderImage({ data: largeData, mimeType: "image/png" }).then(
(image) => {
completionOrder.push("large");
return image;
},
);
const small = materializeProviderImage({ data: smallData, mimeType: "image/png" }).then(
(image) => {
completionOrder.push("small");
return image;
},
);
const images = await Promise.all([large, small]);
for (const image of images) rmSync(image.path, { force: true });
expect(completionOrder).toEqual(["small", "large"]);
});
test("publishing small distinct images stays within eight event-loop turns per image", async () => {
const count = 20;
const materializing = new AsyncLocalStorage<boolean>();
let turn = 0;
let lastActiveTurn = -1;
let activeTurns = 0;
const hook = createHook({
before() {
// A spinning immediate can tick many times while a filesystem worker is
// still running. Count only turns that advance the materializations.
if (materializing.getStore() && turn !== lastActiveTurn) {
lastActiveTurn = turn;
activeTurns++;
}
},
});
let probe = setImmediate(function tick() {
turn++;
probe = setImmediate(tick);
});
const images: string[] = [];
hook.enable();
try {
await materializing.run(true, async () => {
for (let index = 0; index < count; index++) {
const data = Buffer.from(`small attachment ${index}`).toString("base64");
const image = await materializeProviderImage({ data, mimeType: "image/png" });
images.push(image.path);
}
});
} finally {
hook.disable();
clearImmediate(probe);
for (const image of images) rmSync(image, { force: true });
}
expect(activeTurns).toBeLessThanOrEqual(8 * count);
});
test("six concurrent 8 MiB images share the main-thread CPU budget", async () => {
const inputs = Array.from({ length: 6 }, (_, index) => ({
data: Buffer.alloc(8 * 1024 * 1024, index + 1).toString("base64"),
mimeType: "image/png",
}));
const threadCpuMs = () => {
const { user, system } = process.threadCpuUsage();
return (user + system) / 1000;
};
let previous = threadCpuMs();
let longest = 0;
const probe = setInterval(() => {
const now = threadCpuMs();
longest = Math.max(longest, now - previous);
previous = now;
}, 1);
try {
const images = await Promise.all(inputs.map(materializeProviderImage));
await new Promise((resolve) => setTimeout(resolve, 5));
for (const image of images) rmSync(image.path, { force: true });
expect(longest).toBeLessThan(50);
} finally {
clearInterval(probe);
}
});
test("a busy event loop does not spend the image decode budget", async () => {
const count = 8;
let turns = 0;
let probe = setImmediate(function tick() {
turns++;
// Simulate unrelated work that exceeds a 10 ms decode slice.
const end = performance.now() + 20;
while (performance.now() < end) {
// Keep this event-loop turn busy.
}
probe = setImmediate(tick);
});
const paths: string[] = [];
try {
for (let index = 0; index < count; index++) {
const data = Buffer.from(`attachment on a busy loop ${index}`).toString("base64");
const image = await materializeProviderImage({ data, mimeType: "image/png" });
paths.push(image.path);
}
} finally {
clearImmediate(probe);
for (const image of paths) rmSync(image, { force: true });
}
expect(turns).toBeLessThanOrEqual(7 * count);
});
@@ -1,4 +1,4 @@
import { createHash } from "node:crypto";
import { createHash, randomUUID } from "node:crypto";
import * as fs from "node:fs/promises";
import { setImmediate } from "node:timers/promises";
import os from "node:os";
@@ -23,28 +23,26 @@ const PROVIDER_IMAGE_ATTACHMENT_DIR_PREFIX = `${PROVIDER_IMAGE_ATTACHMENT_DIR}-`
const PRIVATE_ATTACHMENT_DIR_MODE = 0o700;
const MATERIALIZED_IMAGE_FILE_MODE = 0o600;
let materializedImageAttachmentDir: string | null = null;
// Serialize materializations: one decoder and one file operation at a time, including
// concurrent history replay and live turns. A rejected operation must not poison the queue.
let pendingMaterialization: Promise<unknown> = Promise.resolve();
let attachmentDirectory: Promise<string> | undefined;
const pendingWrites = new Map<string, Promise<MaterializedProviderImage>>();
async function getMaterializedImageAttachmentDir(): Promise<string> {
if (materializedImageAttachmentDir) {
try {
const stats = await fs.lstat(materializedImageAttachmentDir);
if (stats.isDirectory()) {
await fs.chmod(materializedImageAttachmentDir, PRIVATE_ATTACHMENT_DIR_MODE);
return materializedImageAttachmentDir;
}
} catch {
/* Temp storage may have been removed between turns. */
}
}
materializedImageAttachmentDir = await fs.mkdtemp(
path.join(os.tmpdir(), PROVIDER_IMAGE_ATTACHMENT_DIR_PREFIX),
);
await fs.chmod(materializedImageAttachmentDir, PRIVATE_ATTACHMENT_DIR_MODE);
return materializedImageAttachmentDir;
function getMaterializedImageAttachmentDir(): Promise<string> {
attachmentDirectory ??= createAttachmentDirectory().catch((error) => {
attachmentDirectory = undefined;
throw error;
});
return attachmentDirectory;
}
async function createAttachmentDirectory(): Promise<string> {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), PROVIDER_IMAGE_ATTACHMENT_DIR_PREFIX));
await fs.chmod(dir, PRIVATE_ATTACHMENT_DIR_MODE);
return dir;
}
function isMissingPath(error: unknown): boolean {
const code = (error as NodeJS.ErrnoException).code;
return code === "ENOENT" || code === "ENOTDIR";
}
function getImageExtension(mimeType: string): string {
@@ -69,18 +67,18 @@ function getImageExtension(mimeType: string): string {
// 128 MiB admits the measured 64 MiB fixture with headroom while bounding disk
// and decoding per image. This is materialization admission, not a wire schema limit.
export const MAX_PROVIDER_IMAGE_BYTES = 128 * 1024 * 1024;
const BASE64_CHUNK_CHARACTERS = 256 * 1024; // Multiple of four; decode units stay aligned.
const BASE64_CHUNK_CHARACTERS = 1024 * 1024; // Multiple of four; decode units stay aligned.
const DECODE_SLICE_MS = 10;
let decodeBudgetMs = DECODE_SLICE_MS;
let pendingDecodeYield: Promise<void> | undefined;
export function materializeProviderImage(image: {
data: string;
mimeType: string | null;
}): Promise<MaterializedProviderImage> {
const result = pendingMaterialization.then(() => materializeImage(image));
pendingMaterialization = result.catch(() => {});
return result;
async function refillDecodeBudget(): Promise<void> {
await setImmediate();
decodeBudgetMs = DECODE_SLICE_MS;
pendingDecodeYield = undefined;
}
async function materializeImage(image: {
export async function materializeProviderImage(image: {
data: string;
mimeType: string | null;
}): Promise<MaterializedProviderImage> {
@@ -103,32 +101,74 @@ async function materializeImage(image: {
}
const hash = createHash("sha256");
for await (const bytes of decodeImage(data)) hash.update(bytes);
const dir = await getMaterializedImageAttachmentDir();
const filePath = path.join(dir, `${hash.digest("hex")}.${getImageExtension(mimeType)}`);
const filename = `${hash.digest("hex")}.${getImageExtension(mimeType)}`;
const directory = getMaterializedImageAttachmentDir();
const dir = await directory;
try {
await fs.stat(filePath);
return { path: filePath };
return await materializeInDirectory(dir, filename, data);
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
if (!isMissingPath(error)) throw error;
// Other requests may have already replaced the directory after the same deletion.
if (attachmentDirectory === directory) attachmentDirectory = undefined;
const replacement = await getMaterializedImageAttachmentDir();
return materializeInDirectory(replacement, filename, data);
}
}
const staging = await fs.mkdtemp(path.join(dir, ".pending-"));
const stagingPath = path.join(staging, "image");
function materializeInDirectory(
dir: string,
filename: string,
data: string,
): Promise<MaterializedProviderImage> {
const filePath = path.join(dir, filename);
const pending = pendingWrites.get(filePath);
if (pending) return pending;
const write = publishImage(dir, filePath, data).finally(() => {
pendingWrites.delete(filePath);
});
pendingWrites.set(filePath, write);
return write;
}
async function publishImage(
dir: string,
filePath: string,
data: string,
): Promise<MaterializedProviderImage> {
const [directory, existing] = await Promise.allSettled([fs.lstat(dir), fs.stat(filePath)]);
if (directory.status === "rejected") throw directory.reason;
const stats = directory.value;
const uid = process.platform === "win32" ? undefined : process.getuid?.();
if (
!stats.isDirectory() ||
(uid !== undefined && (stats.uid !== uid || (stats.mode & 0o077) !== 0))
) {
throw Object.assign(new Error("Private image attachment directory is unavailable"), {
code: "ENOENT",
});
}
if (existing.status === "fulfilled") return { path: filePath };
if (!isMissingPath(existing.reason)) throw existing.reason;
const stagingPath = path.join(dir, `.pending-${randomUUID()}`);
const file = await fs.open(stagingPath, "wx", MATERIALIZED_IMAGE_FILE_MODE);
try {
await fs.chmod(staging, PRIVATE_ATTACHMENT_DIR_MODE);
const file = await fs.open(stagingPath, "wx", MATERIALIZED_IMAGE_FILE_MODE);
try {
// Restore owner permissions if the umask masked them at open.
await file.chmod(MATERIALIZED_IMAGE_FILE_MODE);
// Decode again only for a new hash. This bounds retained memory to one chunk
// and performs no writes at all for repeated content, including history replay.
// Decode again only for new content, retaining one chunk at a time.
for await (const bytes of decodeImage(data)) await file.writeFile(bytes);
} finally {
await file.close();
}
await fs.rename(stagingPath, filePath);
return { path: filePath };
} finally {
await fs.rm(staging, { recursive: true, force: true });
} catch (error) {
await fs.unlink(stagingPath).catch((cleanupError) => {
if (!isMissingPath(cleanupError)) throw cleanupError;
});
throw error;
}
}
@@ -136,6 +176,13 @@ async function* decodeImage(data: string): AsyncGenerator<Buffer> {
let carry = "";
let decodedBytes = 0;
for (let offset = 0; offset < data.length; offset += BASE64_CHUNK_CHARACTERS) {
let pause = pendingDecodeYield;
while (pause) {
await pause;
pause = pendingDecodeYield;
}
// Charge synchronous work across decoders. File I/O and idle time leave the budget intact.
const startedAt = performance.now();
// Buffer.from ignores non-base64 characters. Carry incomplete quartets so
// line-wrapped payloads decode identically across chunk boundaries.
const chunk =
@@ -144,12 +191,13 @@ async function* decodeImage(data: string): AsyncGenerator<Buffer> {
const finalChunk = offset + BASE64_CHUNK_CHARACTERS >= data.length || chunk.includes("=");
const end = finalChunk ? chunk.length : chunk.length - (chunk.length % 4);
const bytes = Buffer.from(chunk.slice(0, end), "base64");
decodeBudgetMs -= performance.now() - startedAt;
if (decodeBudgetMs <= 0) pendingDecodeYield = refillDecodeBudget();
carry = chunk.slice(end);
decodedBytes += bytes.length;
if (decodedBytes > MAX_PROVIDER_IMAGE_BYTES)
throw new Error("Image attachment exceeds size limit");
yield bytes;
await setImmediate();
if (finalChunk) break;
}
}
@@ -139,6 +139,9 @@ export interface PaseoToolHostDependencies {
"getSnapshot" | "listWorktrees" | "resolveRepoRoot" | "invalidateWorktrees"
>;
findWorkspaceIdForCwd?: ArchiveDependencies["findWorkspaceIdForCwd"];
worktreeManagers?: ArchiveDependencies["worktreeManagers"];
workspaceArchiveOperations?: ArchiveDependencies["workspaceArchiveOperations"];
isCheckoutUntrusted?: ArchiveDependencies["isCheckoutUntrusted"];
listActiveWorkspaces?: ArchiveDependencies["listActiveWorkspaces"];
archiveWorkspaceRecord?: ArchiveDependencies["archiveWorkspaceRecord"];
emitWorkspaceUpdatesForWorkspaceIds?: ArchiveDependencies["emitWorkspaceUpdatesForWorkspaceIds"];
@@ -3415,11 +3418,17 @@ function archiveWorktreeDependencies(
return {
paseoHome: options.paseoHome,
paseoWorktreesBaseRoot: options.worktreesRoot,
worktreeManagers: options.worktreeManagers,
workspaceArchiveOperations: options.workspaceArchiveOperations,
isCheckoutUntrusted: options.isCheckoutUntrusted,
github: options.github,
workspaceGitService: options.workspaceGitService,
agentManager: context.agentManager,
agentStorage: context.agentStorage,
findWorkspaceIdForCwd: options.findWorkspaceIdForCwd,
...(options.workspaceRegistry
? { getWorkspace: (workspaceId: string) => options.workspaceRegistry!.get(workspaceId) }
: {}),
listActiveWorkspaces: options.listActiveWorkspaces,
archiveWorkspaceRecord: options.archiveWorkspaceRecord,
emitWorkspaceUpdatesForWorkspaceIds: options.emitWorkspaceUpdatesForWorkspaceIds,
@@ -160,7 +160,7 @@ const INBOUND_PERMISSION = {
"project.github.clone.request": "workspace.manage",
"project.icon.get.request": "workspace.read",
"project.icon.set.request": "workspace.manage",
"project.list.request": "workspace.read",
"project.list.request": ["workspace.read", "hub.execute"],
"project.suggestions.request": "workspace.read",
"project.remove.request": "workspace.manage",
"project.rename.request": "workspace.manage",
@@ -419,7 +419,7 @@ const OUTBOUND_PERMISSION = {
"project.github.clone.response": "workspace.manage",
"project.icon.get.response": "workspace.read",
"project.icon.set.response": "workspace.manage",
"project.list.response": "workspace.read",
"project.list.response": ["workspace.read", "hub.execute"],
"project.suggestions.response": "workspace.read",
"project.remove.response": "workspace.manage",
"project.rename.response": "workspace.manage",
@@ -6,6 +6,7 @@ import type { DaemonConfigStore } from "../daemon-config-store.js";
import {
archiveByScope,
type ActiveWorkspaceRef,
type ArchiveDependencies,
killTerminalsForWorkspace,
} from "../workspace-archive-service.js";
import type {
@@ -16,10 +17,15 @@ import type { ForgeService } from "../../services/forge-service.js";
import type { TerminalManager } from "../../terminal/terminal-manager.js";
import { isPaseoOwnedWorktreeCwd } from "../../utils/worktree.js";
import type { WorkspaceArchiveContext } from "../workspace-registry.js";
import type { PluginWorktreeManagerRuntime } from "../plugins/runtime.js";
export interface AutoArchiveArchiveOptions {
paseoHome: string;
paseoWorktreesBaseRoot?: string;
worktreeManagers?: Pick<PluginWorktreeManagerRuntime, "removeWorktree">;
workspaceArchiveOperations?: ArchiveDependencies["workspaceArchiveOperations"];
getWorkspace?: ArchiveDependencies["getWorkspace"];
isCheckoutUntrusted?: ArchiveDependencies["isCheckoutUntrusted"];
daemonConfigStore: DaemonConfigStore;
workspaceGitService: WorkspaceGitServiceImpl;
github: ForgeService;
@@ -99,11 +105,15 @@ export async function archiveIfSafe(input: {
{
paseoHome: options.paseoHome,
paseoWorktreesBaseRoot: options.paseoWorktreesBaseRoot,
worktreeManagers: options.worktreeManagers,
workspaceArchiveOperations: options.workspaceArchiveOperations,
github: options.github,
workspaceGitService: options.workspaceGitService,
agentManager: options.agentManager,
agentStorage: options.agentStorage,
findWorkspaceIdForCwd: options.findWorkspaceIdForCwd,
getWorkspace: options.getWorkspace,
isCheckoutUntrusted: options.isCheckoutUntrusted,
listActiveWorkspaces: options.listActiveWorkspaces,
archiveWorkspaceRecord: (workspaceIdToArchive, archivedAt) =>
options.archiveWorkspaceRecord(
+27 -1
View File
@@ -184,6 +184,7 @@ import {
killTerminalsForWorkspace,
type ActiveWorkspaceRef,
} from "./workspace-archive-service.js";
import { WorkspaceArchiveOperations } from "./workspace-archive-operations.js";
import { setupAutoArchiveOnMerge } from "./auto-archive-on-merge/index.js";
import { wrapSessionMessage, type SessionOutboundMessage } from "./messages.js";
import type { TerminalManager } from "../terminal/terminal-manager.js";
@@ -214,7 +215,10 @@ import { ScriptHealthMonitor } from "./script-health-monitor.js";
import { createScriptStatusEmitter } from "./script-status-projection.js";
import { WorkspaceScriptRuntimeStore } from "./workspace-script-runtime-store.js";
import { createWorkspaceScriptsService } from "./session/workspace-scripts/workspace-scripts-service.js";
import { assertWorkspaceAutomationAllowedForWorkspace } from "./workspace-automation-gate.js";
import {
assertWorkspaceAutomationAllowedForWorkspace,
isCheckoutUntrusted,
} from "./workspace-automation-gate.js";
import { spawnWorkspaceScript } from "./worktree-bootstrap.js";
import {
createManagedProcessRegistry,
@@ -743,6 +747,7 @@ export async function createPaseoDaemon(
});
const scriptRuntimeStore = new WorkspaceScriptRuntimeStore();
const workspaceSetupRuntime = new WorkspaceSetupRuntime();
const workspaceArchiveOperations = new WorkspaceArchiveOperations();
let configuredHostnames = config.hostnames ?? config.allowedHosts;
let appBaseUrl = config.appBaseUrl ?? "https://app.paseo.sh";
daemonConfigStore.onFieldChange("hostnames", (value) => {
@@ -1166,6 +1171,8 @@ export async function createPaseoDaemon(
worktreeRoot: workspace.worktreeRoot,
isPaseoOwnedWorktree: workspace.isPaseoOwnedWorktree,
mainRepoRoot: workspace.mainRepoRoot,
worktreeManagerPluginId: workspace.worktreeManagerPluginId,
untrustedSource: workspace.untrustedSource,
}));
};
const markWorkspaceArchivingExternal = (workspaceIds: Iterable<string>, archivingAt: string) => {
@@ -1224,6 +1231,8 @@ export async function createPaseoDaemon(
setupAutoArchiveOnMerge({
paseoHome: config.paseoHome,
paseoWorktreesBaseRoot: config.worktreesRoot,
worktreeManagers: pluginRuntime,
workspaceArchiveOperations,
daemonConfigStore,
workspaceGitService,
github,
@@ -1232,6 +1241,8 @@ export async function createPaseoDaemon(
terminalManager,
logger,
findWorkspaceIdForCwd: findWorkspaceIdForCwdExternal,
getWorkspace: (workspaceId) => workspaceRegistry.get(workspaceId),
isCheckoutUntrusted: (checkoutPath) => isCheckoutUntrusted(workspaceRegistry, checkoutPath),
listActiveWorkspaces: listActiveWorkspacesExternal,
getAutoArchivedChangeRequestUrl: async (workspaceId) =>
(await workspaceRegistry.get(workspaceId))?.autoArchivedChangeRequestUrl ?? null,
@@ -1252,6 +1263,7 @@ export async function createPaseoDaemon(
createPaseoWorktree: async (workflowInput, workflowOptions) => {
return createRegisteredPaseoWorktree(workflowInput, {
lifecycle: pluginRuntime,
worktreeManagers: pluginRuntime,
github,
...(workflowOptions?.resolveDefaultBranch
? {
@@ -1312,6 +1324,8 @@ export async function createPaseoDaemon(
{
paseoHome: config.paseoHome,
paseoWorktreesBaseRoot: config.worktreesRoot,
worktreeManagers: pluginRuntime,
workspaceArchiveOperations,
github,
workspaceGitService,
agentManager,
@@ -1329,6 +1343,7 @@ export async function createPaseoDaemon(
stopWorkspaceSetup: (workspaceIdToStop) => workspaceSetupRuntime.stop(workspaceIdToStop),
assertWorkspaceAutomationAllowed: (guardedWorkspaceId) =>
assertWorkspaceAutomationAllowedForWorkspace(workspaceRegistry, guardedWorkspaceId),
isCheckoutUntrusted: (checkoutPath) => isCheckoutUntrusted(workspaceRegistry, checkoutPath),
sessionLogger: logger,
},
{ scope: { kind: "workspace", workspaceId }, requestId },
@@ -1336,6 +1351,10 @@ export async function createPaseoDaemon(
const hubAgentLifecycle = new CreateAgentLifecycleDispatch({
paseoHome: config.paseoHome,
worktreesRoot: config.worktreesRoot,
worktreeManagers: pluginRuntime,
workspaceArchiveOperations,
getWorkspace: (workspaceId) => workspaceRegistry.get(workspaceId),
isCheckoutUntrusted: (checkoutPath) => isCheckoutUntrusted(workspaceRegistry, checkoutPath),
agentManager,
agentStorage,
github,
@@ -1434,6 +1453,8 @@ export async function createPaseoDaemon(
{
paseoHome: config.paseoHome,
paseoWorktreesBaseRoot: config.worktreesRoot,
worktreeManagers: pluginRuntime,
workspaceArchiveOperations,
github,
workspaceGitService,
agentManager,
@@ -1457,6 +1478,7 @@ export async function createPaseoDaemon(
stopWorkspaceSetup: (workspaceIdToStop) => workspaceSetupRuntime.stop(workspaceIdToStop),
assertWorkspaceAutomationAllowed: (guardedWorkspaceId) =>
assertWorkspaceAutomationAllowedForWorkspace(workspaceRegistry, guardedWorkspaceId),
isCheckoutUntrusted: (checkoutPath) => isCheckoutUntrusted(workspaceRegistry, checkoutPath),
sessionLogger: logger,
},
{
@@ -1583,6 +1605,9 @@ export async function createPaseoDaemon(
daemonConfigStore,
github,
workspaceGitService,
worktreeManagers: pluginRuntime,
workspaceArchiveOperations,
isCheckoutUntrusted: (checkoutPath) => isCheckoutUntrusted(workspaceRegistry, checkoutPath),
findWorkspaceIdForCwd: findWorkspaceIdForCwdExternal,
listActiveWorkspaces: listActiveWorkspacesExternal,
archiveWorkspaceRecord: (workspaceId, archivedAt) =>
@@ -1930,6 +1955,7 @@ export async function createPaseoDaemon(
pluginRuntime,
orchestrationSkills,
workspaceLabelService,
workspaceArchiveOperations,
);
pluginRuntime.bindPaseoSessionHost(wsServer);
await pluginRuntime.start();
@@ -2,6 +2,7 @@ import { mkdir, mkdtemp, rename, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { basename, dirname, join, sep } from "node:path";
import { afterEach, expect, test, vi } from "vitest";
import { createWatcherLivenessCanary } from "../watcher-liveness-canary.js";
import {
createFileObserver,
type FileChange,
@@ -167,12 +168,17 @@ test("survives atomic replacement and remains observable", async () => {
const root = await createRoot();
const target = join(root, "target.txt");
await writeFile(target, "before");
const canary = createWatcherLivenessCanary(root);
const events: FileChange[] = [];
const subscription = await subscribeToFileChanges(root, (error, batch) => {
expect(error).toBeNull();
events.push(...batch);
events.push(...canary.filterEvents(batch));
});
// macOS starts delivering native events asynchronously after subscription.
await canary.verify();
events.length = 0;
const replacement = join(root, "replacement.txt");
await writeFile(replacement, "after");
await rename(replacement, target);
@@ -62,6 +62,37 @@ test("Hub execute can steer ordinary agents while unrelated administration stays
expect(hub.serverInfoPermissions()).toEqual([["hub.execute"]]);
});
test("Hub execute can list daemon projects but cannot rename them", async () => {
const hub = await launchRelationship();
await hub.createSiblingWorkspace(hub.repoRoot());
expect(hub.serverInfoPermissions()).toEqual([["hub.execute"]]);
const listed = await hub.requestOrdinary({
type: "project.list.request",
requestId: "list-projects",
});
expect(listed).toMatchObject({
type: "project.list.response",
payload: {
requestId: "list-projects",
projects: [{ projectId: expect.any(String), projectRootPath: hub.repoRoot() }],
},
});
if (listed.type !== "project.list.response") throw new Error("Expected project list response");
expect(
await hub.requestOrdinary({
type: "project.rename.request",
requestId: "rename-project",
projectId: listed.payload.projects[0]?.projectId,
customName: "Hub rename",
}),
).toMatchObject({
type: "rpc_error",
payload: { requestId: "rename-project", code: "access_denied" },
});
});
test("Hub execute can title the workspace created with an agent", async () => {
const hub = await launchRelationship();
const created = await hub.requestOrdinary({
@@ -1,5 +1,6 @@
import type { JsonValue } from "@getpaseo/protocol/agent-types";
import type { PluginLifecycle } from "./plugins/lifecycle/index.js";
import type { PluginWorktreeManagerRuntime } from "./plugins/runtime.js";
import { stat } from "node:fs/promises";
import { resolve } from "node:path";
@@ -63,6 +64,10 @@ export interface AttemptFirstAgentBranchAutoNameResult {
export interface CreatePaseoWorktreeDeps extends CreateWorktreeCoreDeps {
lifecycle?: Pick<PluginLifecycle, "wait" | "before">;
worktreeManagers?: Pick<
PluginWorktreeManagerRuntime,
"hasWorktreeManager" | "createWorktree" | "removeWorktree"
>;
workspaceGitService: WorkspaceGitService;
workspaceProvisioning: Pick<WorkspaceProvisioningService, "createWorkspaceForWorktree">;
}
@@ -114,22 +119,13 @@ async function createPaseoWorktreeWithPriority(
worktreeRoot: createdWorktree.worktree.worktreePath,
branch: createdWorktree.worktree.branchName || null,
baseBranch: createdWorktree.worktree.comparisonBaseRef,
worktreeManagerPluginId: createdWorktree.worktree.worktreeManagerPluginId ?? null,
title: input.title?.trim() || resolveFirstAgentPromptTitle(input.firstAgentContext),
metadata: input.metadata,
expectsInitialAgent: Boolean(input.firstAgentContext),
background: input.background,
callerWorkspaceId: input.callerWorkspaceId,
...(createdWorktree.intent.kind === "checkout-change-request" &&
createdWorktree.intent.headRepository
? {
untrustedSource: {
kind: "change_request" as const,
forge: createdWorktree.intent.forge,
number: createdWorktree.intent.changeRequestNumber,
headRepository: createdWorktree.intent.headRepository,
},
}
: {}),
untrustedSource: createdWorktree.untrustedSource,
});
deps.github.invalidate({ cwd: createdWorktree.worktree.worktreePath });
@@ -152,6 +148,10 @@ async function createPaseoWorktreeWithPriority(
teardownCwds: [],
paseoHome: input.paseoHome,
worktreesBaseRoot: input.worktreesRoot,
worktreeManagers: deps.worktreeManagers,
worktreeManagerPluginId: createdWorktree.worktree.worktreeManagerPluginId ?? null,
removeReason: "rollback",
untrusted: Boolean(createdWorktree.untrustedSource),
},
error,
);
@@ -286,6 +286,10 @@ async function maybeMarkFirstAgentBranchAutoNameEligible(options: {
if (!createdWorktree.created || createdWorktree.intent.kind !== "branch-off") {
return;
}
// A worktree manager plugin owns branch and directory naming, so skip silent renames.
if (createdWorktree.worktree.worktreeManagerPluginId) {
return;
}
// A branch the caller named is their choice; only a placeholder slug is replaced.
if (input.branchName !== undefined) {
return;
+30 -1
View File
@@ -24,7 +24,7 @@ import { type ManagedPluginCandidate, ManagedPluginSources } from "./managed-sou
import { readPluginManifest } from "./manifest.js";
import { expandTilde } from "../../utils/path.js";
import { runPluginBuild } from "./preparation.js";
import { PluginRuntime } from "./runtime.js";
import { PluginRuntime, type PluginWorktreeManagerRuntime } from "./runtime.js";
import type { PluginRuntimeSubscription } from "./runtime-subscription.js";
import { BuiltinPluginLoader, type BuiltinPlugin } from "./builtin/index.js";
import type {
@@ -50,6 +50,10 @@ interface PluginRuntimePort {
drainEvents?: PluginRuntime["drainEvents"];
before?: PluginLifecycle["before"];
wait?: PluginLifecycle["wait"];
hasWorktreeManager?: PluginWorktreeManagerRuntime["hasWorktreeManager"];
createWorktree?: PluginWorktreeManagerRuntime["createWorktree"];
removeWorktree?: PluginWorktreeManagerRuntime["removeWorktree"];
restoreWorktree?: PluginWorktreeManagerRuntime["restoreWorktree"];
catalog: PluginRuntime["catalog"];
invoke(pluginId: string, method: string, input: unknown): Promise<unknown>;
startSubscription: PluginRuntime["startSubscription"];
@@ -192,6 +196,31 @@ export class PluginService {
return request;
};
readonly hasWorktreeManager: PluginWorktreeManagerRuntime["hasWorktreeManager"] = (options) => {
return this.runtime.hasWorktreeManager?.(options) ?? false;
};
readonly createWorktree: PluginWorktreeManagerRuntime["createWorktree"] = async (
request,
options,
) => {
return (await this.runtime.createWorktree?.(request, options)) ?? null;
};
readonly removeWorktree: PluginWorktreeManagerRuntime["removeWorktree"] = async (
request,
options,
) => {
return (await this.runtime.removeWorktree?.(request, options)) ?? null;
};
readonly restoreWorktree: PluginWorktreeManagerRuntime["restoreWorktree"] = async (
request,
options,
) => {
return (await this.runtime.restoreWorktree?.(request, options)) ?? null;
};
subscribeSettings(listener: (pluginId: string, settingsId: string) => void): () => void {
this.settingsListeners.add(listener);
return () => this.settingsListeners.delete(listener);
@@ -57,7 +57,12 @@ const changeRequestFields = {
};
const worktreeRequestSchema = z.discriminatedUnion("kind", [
z
.object({ ...worktreeRequestFields, kind: z.literal("branch-off"), baseRef: z.string().min(1) })
.object({
...worktreeRequestFields,
kind: z.literal("branch-off"),
baseRef: z.string().min(1),
startPoint: z.string().min(1).optional(),
})
.strict(),
z
.object({
@@ -239,6 +244,28 @@ function changesSessionOpenTarget(previous: SessionOpenRequest, next: SessionOpe
);
}
type WorktreeBeforeRequest = z.infer<(typeof beforeSchemas)["worktree.create.before"]>;
function validateWorktreeBeforeResult(
previous: WorktreeBeforeRequest,
next: WorktreeBeforeRequest,
): WorktreeBeforeRequest {
if (previous.repoRoot !== next.repoRoot || previous.sourceCheckout !== next.sourceCheckout) {
throw new Error("worktree.create.before hooks cannot change repoRoot or sourceCheckout");
}
if (previous.kind === "branch-off" && next.kind === "branch-off") {
if (next.startPoint !== undefined && next.startPoint !== previous.startPoint) {
throw new Error("worktree.create.before hooks cannot change startPoint");
}
if (next.startPoint === undefined && previous.startPoint !== undefined) {
return { ...next, startPoint: previous.startPoint };
}
} else if (next.kind === "branch-off" && next.startPoint !== undefined) {
throw new Error("worktree.create.before hooks cannot change startPoint");
}
return next;
}
export async function validateBeforeResult<Name extends keyof PluginWireBeforeRequests>(
name: Name,
input: PluginWireBeforeRequests[Name],
@@ -280,9 +307,7 @@ export async function validateBeforeResult<Name extends keyof PluginWireBeforeRe
if (name === "worktree.create.before") {
const previous = beforeSchemas["worktree.create.before"].parse(input);
const next = beforeSchemas["worktree.create.before"].parse(result);
if (previous.repoRoot !== next.repoRoot || previous.sourceCheckout !== next.sourceCheckout) {
throw new Error("worktree.create.before hooks cannot change repoRoot or sourceCheckout");
}
return validateWorktreeBeforeResult(previous, next) as PluginWireBeforeRequests[Name];
}
return result;
}
@@ -45,6 +45,11 @@ export interface PluginUsageSourceMetadata {
icon?: string;
}
export interface PluginWorktreeManagerCapabilities {
hasRemove: boolean;
hasRestore: boolean;
}
export type PluginProcessRequest =
| { type: "tool.call"; requestId: string; agent: PluginHookAgent; name: string; input: unknown }
| { type: "tool.cancel"; requestId: string }
@@ -84,6 +89,10 @@ export type PluginProcessRequest =
}
| { type: "hook"; requestId: string; name: string; input: unknown }
| { type: "hook.cancel"; requestId: string }
| { type: "worktree.create"; requestId: string; request: unknown }
| { type: "worktree.remove"; requestId: string; request: unknown }
| { type: "worktree.restore"; requestId: string; request: unknown }
| { type: "worktree.cancel"; requestId: string }
| { type: "usage.fetch"; requestId: string; sourceId: string; input: unknown }
| { type: "usage.discover"; requestId: string; sourceId: string; scope: UsageScope }
| { type: "invoke"; requestId: string; method: string; input: unknown }
@@ -115,6 +124,10 @@ export type PluginProcessRequest =
export type PluginProcessMessage =
| { type: "settings.changed"; settingsId: string }
| { type: "hooks.changed"; hooks: string[] }
| {
type: "worktree_manager.changed";
worktreeManager: PluginWorktreeManagerCapabilities | null;
}
| {
type: "ready";
methods: string[];
@@ -122,6 +135,7 @@ export type PluginProcessMessage =
providers: PluginProviderMetadata[];
usageSources?: PluginUsageSourceMetadata[];
hooks?: string[];
worktreeManager?: PluginWorktreeManagerCapabilities | null;
}
| { type: "result"; requestId: string; output: unknown }
| { type: "error"; requestId: string; error: string }
@@ -149,6 +163,12 @@ export type PluginProcessMessage =
| { type: "paseo_close" };
const hooksSchema = z.array(z.string());
const worktreeManagerCapabilitiesSchema = z
.object({
hasRemove: z.boolean(),
hasRestore: z.boolean(),
})
.strict();
const providerMetadataSchema = z
.object({
@@ -294,6 +314,14 @@ export const PluginProcessRequestSchema: z.ZodType<PluginProcessRequest> = z.dis
})
.strict(),
z.object({ type: z.literal("hook.cancel"), requestId: z.string() }).strict(),
z
.object({
type: z.enum(["worktree.create", "worktree.remove", "worktree.restore"]),
requestId: z.string().min(1),
request: z.unknown(),
})
.strict(),
z.object({ type: z.literal("worktree.cancel"), requestId: z.string().min(1) }).strict(),
z
.object({
type: z.literal("usage.fetch"),
@@ -356,6 +384,12 @@ export const PluginProcessMessageSchema: z.ZodType<PluginProcessMessage> = z.dis
[
z.object({ type: z.literal("settings.changed"), settingsId: z.string() }).strict(),
z.object({ type: z.literal("hooks.changed"), hooks: hooksSchema }).strict(),
z
.object({
type: z.literal("worktree_manager.changed"),
worktreeManager: worktreeManagerCapabilitiesSchema.nullable(),
})
.strict(),
z
.object({
type: z.literal("ready"),
@@ -364,6 +398,7 @@ export const PluginProcessMessageSchema: z.ZodType<PluginProcessMessage> = z.dis
providers: z.array(providerMetadataSchema),
usageSources: z.array(usageSourceMetadataSchema).optional(),
hooks: hooksSchema.optional(),
worktreeManager: worktreeManagerCapabilitiesSchema.nullable().optional(),
})
.strict(),
z
@@ -16,6 +16,10 @@ import type {
PluginHandlerContext,
PluginServerContext,
PluginServerContribution,
PluginWorktreeCreateInput,
PluginWorktreeRemoveRequest,
PluginWorktreeRestoreRequest,
WorktreeManagerRegistration,
} from "@getpaseo/plugin/server";
import { assertPluginWireValue } from "@getpaseo/protocol/binary-frames/index";
import {
@@ -115,6 +119,8 @@ export function createPluginWorker(options: {
const subscriptions = new PluginSubscriptionHandlers({ send, sendAndWait });
const providers = new Map<string, ProviderRegistration>();
const usageSources = new Map<string, UsageSourceRegistration>();
let worktreeManager: WorktreeManagerRegistration | null = null;
const worktreeRequests = new Map<string, AbortController>();
const providerConnections = new Map<
string,
{ connection: ProviderConnection; unsubscribe: () => void; closing?: Promise<void> }
@@ -228,6 +234,36 @@ export function createPluginWorker(options: {
usageSources.set(id, { ...source, id });
}
function worktreeManagerCapabilities() {
if (!worktreeManager) return null;
return {
hasRemove: worktreeManager.remove !== undefined,
hasRestore: worktreeManager.restore !== undefined,
};
}
function registerWorktreeManager(manager: WorktreeManagerRegistration): () => void {
if (!manager || typeof manager.create !== "function") {
throw new Error("Plugin worktree manager must implement create()");
}
if (manager.remove !== undefined && typeof manager.remove !== "function") {
throw new Error("Invalid remove callback for plugin worktree manager");
}
if (manager.restore !== undefined && typeof manager.restore !== "function") {
throw new Error("Invalid restore callback for plugin worktree manager");
}
if (worktreeManager !== null) {
throw new Error("Plugin already registered a worktree manager");
}
worktreeManager = manager;
send({ type: "worktree_manager.changed", worktreeManager: worktreeManagerCapabilities() });
return () => {
if (worktreeManager !== manager) return;
worktreeManager = null;
send({ type: "worktree_manager.changed", worktreeManager: null });
};
}
function providerMetadata(provider: ProviderRegistration) {
return {
id: provider.id,
@@ -433,6 +469,7 @@ export function createPluginWorker(options: {
handle,
registerProvider,
registerUsageSource,
registerWorktreeManager,
registerSettings,
addHook: hooks.addHook,
on: hooks.on,
@@ -459,6 +496,7 @@ export function createPluginWorker(options: {
methods: [...handlers.keys()].sort(),
subscriptions: subscriptions.catalog(),
hooks: hooks.catalog(),
worktreeManager: worktreeManagerCapabilities(),
providers: [...providers.values()]
.sort((left, right) => left.id.localeCompare(right.id))
.map(providerMetadata),
@@ -478,6 +516,8 @@ export function createPluginWorker(options: {
for (const pending of pendingProviderConnections.values()) pending.tombstoned = true;
for (const request of installationRequests.values())
request.abort(new Error("Plugin is stopping"));
for (const request of worktreeRequests.values()) request.abort(new Error("Plugin is stopping"));
worktreeManager = null;
const currentCleanup = cleanup;
cleanup = null;
try {
@@ -519,6 +559,9 @@ export function createPluginWorker(options: {
message.type === "provider.catalog_key" ||
message.type === "usage.fetch" ||
message.type === "usage.discover" ||
message.type === "worktree.create" ||
message.type === "worktree.remove" ||
message.type === "worktree.restore" ||
message.type === "subscribe"
) {
send({ type: "error", requestId: message.requestId, error: "Plugin is stopping" });
@@ -704,6 +747,10 @@ export function createPluginWorker(options: {
handleHookMessage(message);
return;
}
if (isWorktreeMessage(message)) {
handleWorktreeMessage(message);
return;
}
if (message.type === "invoke") invoke(message);
else handleSubscriptionMessage(message);
}
@@ -769,6 +816,88 @@ export function createPluginWorker(options: {
): message is Extract<PluginProcessRequest, { type: "hook" | "hook.cancel" }> {
return message.type === "hook" || message.type === "hook.cancel";
}
function isWorktreeMessage(
message: PluginProcessRequest,
): message is Extract<
PluginProcessRequest,
{ type: "worktree.create" | "worktree.remove" | "worktree.restore" | "worktree.cancel" }
> {
return (
message.type === "worktree.create" ||
message.type === "worktree.remove" ||
message.type === "worktree.restore" ||
message.type === "worktree.cancel"
);
}
function handleWorktreeMessage(
message: Extract<
PluginProcessRequest,
{ type: "worktree.create" | "worktree.remove" | "worktree.restore" | "worktree.cancel" }
>,
): void {
if (message.type === "worktree.cancel") {
worktreeRequests.get(message.requestId)?.abort(new Error("Worktree request canceled"));
return;
}
if (!paseo) {
send({
type: "error",
requestId: message.requestId,
error: "Plugin Paseo API is unavailable",
});
return;
}
const manager = worktreeManager;
if (!manager) {
send({
type: "error",
requestId: message.requestId,
error: "Plugin has no registered worktree manager",
});
return;
}
const controller = new AbortController();
worktreeRequests.set(message.requestId, controller);
const context = { paseo, signal: controller.signal };
void (async () => {
if (message.type === "worktree.create") {
return (
(await manager.create(
structuredClone(message.request) as PluginWorktreeCreateInput,
context,
)) ?? null
);
}
if (message.type === "worktree.remove") {
if (!manager.remove) {
throw new Error("Plugin worktree manager does not implement remove");
}
return (
(await manager.remove(
structuredClone(message.request) as PluginWorktreeRemoveRequest,
context,
)) ?? null
);
}
if (!manager.restore) {
throw new Error("Plugin worktree manager does not implement restore");
}
return (
(await manager.restore(
structuredClone(message.request) as PluginWorktreeRestoreRequest,
context,
)) ?? null
);
})()
.then(
(output) => send({ type: "result", requestId: message.requestId, output }),
(error) =>
send({ type: "error", requestId: message.requestId, error: describeError(error) }),
)
.finally(() => worktreeRequests.delete(message.requestId));
}
return { shutdown };
}
@@ -257,6 +257,59 @@ afterEach(async () => {
});
describe("PluginRuntime", () => {
it("reports a spent create budget without blaming a manager it did not call", async () => {
const first = await createPlugin(
"first-manager",
`import { existsSync, writeFileSync } from "node:fs";
import path from "node:path";
export default function contribute(server) {
return server.registerWorktreeManager({
async create({ path: directory }, { signal }) {
writeFileSync(path.join(directory, "started"), "");
while (!existsSync(path.join(directory, "decline"))) {
signal.throwIfAborted();
await new Promise((resolve) => setTimeout(resolve, 20));
}
},
});
}`,
);
const second = await createPlugin(
"second-manager",
`export default function contribute(server) {
return server.registerWorktreeManager({
async create() { throw new Error("Second manager was called"); },
});
}`,
);
const runtime = createTestRuntime();
try {
await runtime.startPlugin("first-manager", first);
await runtime.startPlugin("second-manager", second);
// Advance the deadline clock while real subprocess IPC and timers keep running.
vi.useFakeTimers({ toFake: ["Date"] });
const creation = runtime.createWorktree({
kind: "branch-off",
repoRoot: first,
sourceCheckout: first,
branch: "topic",
slug: "topic",
path: first,
baseRef: "main",
untrusted: false,
});
const failure = creation.catch((error: unknown) => error);
await expect.poll(() => readTextIfPresent(path.join(first, "started"))).toBe("");
vi.setSystemTime(Date.now() + 120_000);
await writeFile(path.join(first, "decline"), "");
expect(await failure).toMatchObject({ message: "Worktree creation manager budget expired" });
} finally {
vi.useRealTimers();
await runtime.stopAll();
}
});
it.each([
{ specifier: "@getpaseo/plugin", moduleDirectory: "shared" },
{ specifier: "@getpaseo/plugin", moduleDirectory: "server" },
+171 -3
View File
@@ -18,7 +18,15 @@ import {
type ProviderStatus,
type ProviderStatusRequest,
} from "@getpaseo/plugin/server/provider";
import type { PluginHookEvents, PluginHookAgent, AgentToolResult } from "@getpaseo/plugin/server";
import type {
PluginHookEvents,
PluginHookAgent,
AgentToolResult,
PluginWorktreeCreateInput,
PluginWorktreeRemoveRequest,
PluginWorktreeRestoreRequest,
} from "@getpaseo/plugin/server";
import { z } from "zod";
import { validateBeforeRequest, validateBeforeResult } from "./lifecycle/index.js";
import { fork } from "node:child_process";
import path from "node:path";
@@ -42,6 +50,7 @@ import type {
PluginProcessRequest,
PluginProviderMetadata,
PluginUsageSourceMetadata,
PluginWorktreeManagerCapabilities,
} from "./plugin-process-protocol.js";
import { PluginProcessMessageSchema } from "./plugin-process-protocol.js";
import {
@@ -53,7 +62,40 @@ import { InternalPluginChild } from "./internal-child.js";
import { evaluateBundle } from "./bundle-evaluator.js";
const REQUEST_TIMEOUT_MS = 30_000;
const WORKTREE_MANAGER_TIMEOUT_MS = 120_000;
const TOOL_CALL_TIMEOUT_MS = 10 * 60_000;
const worktreeCreateResultSchema = z
.object({ type: z.literal("created"), path: z.string().min(1) })
.strict()
.nullable();
const worktreeRemoveResultSchema = z
.object({ type: z.literal("removed") })
.strict()
.nullable();
const worktreeRestoreResultSchema = z
.object({ type: z.literal("restored"), path: z.string().min(1) })
.strict()
.nullable();
export interface PluginWorktreeManagerRuntime {
hasWorktreeManager(options?: {
operation?: "create" | "remove" | "restore";
preferredPluginId?: string;
}): boolean;
createWorktree(
request: PluginWorktreeCreateInput,
options?: { signal?: AbortSignal },
): Promise<{ pluginId: string; path: string } | null>;
removeWorktree(
request: PluginWorktreeRemoveRequest,
options?: { preferredPluginId?: string; signal?: AbortSignal },
): Promise<{ pluginId: string } | null>;
restoreWorktree(
request: PluginWorktreeRestoreRequest,
options?: { preferredPluginId?: string; signal?: AbortSignal },
): Promise<{ pluginId: string; path: string } | null>;
}
const MAX_LOG_ENTRIES = 500;
const MAX_LOG_BYTES = 256 * 1024;
const MAX_LOG_LINE_BYTES = 16 * 1024;
@@ -87,6 +129,8 @@ interface PluginRequestOptions {
signal?: AbortSignal;
/** Receives `provider.installation.report` messages for the request. */
report?: (report: ProviderUpdateReport) => void;
/** Overrides the default per-message timeout (e.g. shared budget across serial worktree managers). */
timeoutMs?: number;
}
interface LoadedPlugin {
@@ -100,6 +144,7 @@ interface LoadedPlugin {
subscriptionMethods: ReadonlySet<string>;
subscriptions: Map<string, BufferedPluginSubscription>;
hooks: string[];
worktreeManager: PluginWorktreeManagerCapabilities | null;
providers: readonly PluginProviderMetadata[];
usageSources: readonly PluginUsageSourceMetadata[];
child: PluginChild | null;
@@ -293,8 +338,17 @@ function isInstallationRequest(message: PluginProcessRequest): boolean {
);
}
function isWorktreeManagerRequest(message: PluginProcessRequest): boolean {
return (
message.type === "worktree.create" ||
message.type === "worktree.remove" ||
message.type === "worktree.restore"
);
}
function requestTimeoutMs(message: PluginProcessRequest): number | null {
if (message.type === "tool.call") return TOOL_CALL_TIMEOUT_MS;
if (isWorktreeManagerRequest(message)) return WORKTREE_MANAGER_TIMEOUT_MS;
// An updater runs as long as it needs; daemon shutdown aborts it.
if (message.type === "provider.installation.update") return null;
return REQUEST_TIMEOUT_MS;
@@ -752,6 +806,109 @@ export class PluginRuntime {
return request;
}
hasWorktreeManager(options?: {
operation?: "create" | "remove" | "restore";
preferredPluginId?: string;
}): boolean {
const operation = options?.operation ?? "create";
const supports = (manager: PluginWorktreeManagerCapabilities | null): boolean => {
if (!manager) return false;
if (operation === "remove") return manager.hasRemove;
if (operation === "restore") return manager.hasRestore;
return true;
};
if (options?.preferredPluginId) {
return supports(this.plugins.get(options.preferredPluginId)?.worktreeManager ?? null);
}
for (const loaded of this.plugins.values()) {
if (supports(loaded.worktreeManager)) return true;
}
return false;
}
async createWorktree(
request: PluginWorktreeCreateInput,
options?: { signal?: AbortSignal },
): Promise<{ pluginId: string; path: string } | null> {
const plugins = [...this.plugins.values()]
.filter((plugin) => plugin.worktreeManager !== null)
.sort((left, right) => left.id.localeCompare(right.id));
// All create callbacks share one timeout budget.
const deadline = Date.now() + WORKTREE_MANAGER_TIMEOUT_MS;
for (const loaded of plugins) {
const remainingMs = deadline - Date.now();
if (remainingMs <= 0) {
throw new Error("Worktree creation manager budget expired");
}
try {
const raw = await this.request(
loaded,
{ type: "worktree.create", requestId: randomUUID(), request },
{ signal: options?.signal, timeoutMs: remainingMs },
);
const parsed = worktreeCreateResultSchema.parse(raw ?? null);
if (parsed !== null) {
return { pluginId: loaded.id, path: parsed.path };
}
} catch (error) {
throw new Error(`Plugin ${loaded.id} worktree.create failed: ${describeError(error)}`, {
cause: error,
});
}
}
return null;
}
async removeWorktree(
request: PluginWorktreeRemoveRequest,
options?: { preferredPluginId?: string; signal?: AbortSignal },
): Promise<{ pluginId: string } | null> {
if (!options?.preferredPluginId) return null;
const loaded = this.plugins.get(options.preferredPluginId);
if (!loaded?.worktreeManager?.hasRemove) return null;
try {
const raw = await this.request(
loaded,
{ type: "worktree.remove", requestId: randomUUID(), request },
{ signal: options.signal },
);
const parsed = worktreeRemoveResultSchema.parse(raw ?? null);
if (parsed !== null) {
return { pluginId: loaded.id };
}
return null;
} catch (error) {
throw new Error(`Plugin ${loaded.id} worktree.remove failed: ${describeError(error)}`, {
cause: error,
});
}
}
async restoreWorktree(
request: PluginWorktreeRestoreRequest,
options?: { preferredPluginId?: string; signal?: AbortSignal },
): Promise<{ pluginId: string; path: string } | null> {
if (!options?.preferredPluginId) return null;
const loaded = this.plugins.get(options.preferredPluginId);
if (!loaded?.worktreeManager?.hasRestore) return null;
try {
const raw = await this.request(
loaded,
{ type: "worktree.restore", requestId: randomUUID(), request },
{ signal: options.signal },
);
const parsed = worktreeRestoreResultSchema.parse(raw ?? null);
if (parsed !== null) {
return { pluginId: loaded.id, path: parsed.path };
}
return null;
} catch (error) {
throw new Error(`Plugin ${loaded.id} worktree.restore failed: ${describeError(error)}`, {
cause: error,
});
}
}
async getProviderCatalogCacheKey(
pluginId: string,
providerId: string,
@@ -853,12 +1010,14 @@ export class PluginRuntime {
loaded.pending.delete(requestId);
if (message.type === "tool.call")
void send(child, { type: "tool.cancel", requestId }).catch(() => {});
if (isWorktreeManagerRequest(message))
void send(child, { type: "worktree.cancel", requestId }).catch(() => {});
if (isInstallationRequest(message))
void send(child, { type: "provider.installation.cancel", requestId }).catch(() => {});
signal?.removeEventListener("abort", cancel);
reject(signal?.reason ?? new Error("Tool call canceled"));
reject(signal?.reason ?? new Error("Plugin request canceled"));
};
const timeoutMs = requestTimeoutMs(message);
const timeoutMs = options.timeoutMs ?? requestTimeoutMs(message);
const timeout =
timeoutMs === null
? undefined
@@ -870,6 +1029,9 @@ export class PluginRuntime {
if (message.type === "hook") {
void send(child, { type: "hook.cancel", requestId }).catch(() => {});
}
if (isWorktreeManagerRequest(message)) {
void send(child, { type: "worktree.cancel", requestId }).catch(() => {});
}
// The handler may still start after the daemon gave up on it.
if (message.type === "subscribe") {
const { subscriptionId } = message;
@@ -935,6 +1097,7 @@ export class PluginRuntime {
subscriptionMethods: new Set(),
subscriptions: new Map(),
hooks: [],
worktreeManager: null,
providers: [],
usageSources: [],
child: null,
@@ -1067,6 +1230,7 @@ export class PluginRuntime {
subscriptionMethods: new Set(ready.subscriptions ?? []),
subscriptions: new Map(),
hooks: ready.hooks ?? [],
worktreeManager: ready.worktreeManager ?? null,
providers: ready.providers ?? [],
usageSources: ready.usageSources ?? [],
child,
@@ -1156,6 +1320,10 @@ export class PluginRuntime {
}
return;
}
if (message.type === "worktree_manager.changed") {
loaded.worktreeManager = message.worktreeManager;
return;
}
if (message.type === "settings.changed") {
this.dependencies.onSettingsChanged?.(loaded.id, message.settingsId);
return;
File diff suppressed because it is too large Load Diff
@@ -1,10 +1,25 @@
import type { ForgeService, PullRequestCheckoutTarget } from "../services/forge-service.js";
import type { WorktreeCheckoutRef, WorktreeSource } from "../utils/worktree.js";
import type { UntrustedWorkspaceSource } from "./workspace-automation-gate.js";
export type WorktreeCreationIntent = Exclude<
WorktreeSource,
{ kind: "restore" | "restore-from-base" | "restore-commit" }
>;
> & { untrustedSource?: UntrustedWorkspaceSource };
export function worktreeUntrustedSource(
intent: WorktreeCreationIntent,
): UntrustedWorkspaceSource | undefined {
if (intent.kind === "checkout-change-request" && intent.headRepository) {
return {
kind: "change_request",
forge: intent.forge,
number: intent.changeRequestNumber,
headRepository: intent.headRepository,
};
}
return intent.untrustedSource;
}
export interface ResolveWorktreeCreationIntentInput {
worktreeSlug?: string;
@@ -156,7 +171,11 @@ async function fetchChangeRequestHead(params: {
changeRequest: { number: number; forge?: string };
repoRoot: string;
deps: ResolveWorktreeCreationIntentDeps;
}): Promise<{ baseBranch: string; startPoint: string }> {
}): Promise<{
baseBranch: string;
startPoint: string;
untrustedSource?: UntrustedWorkspaceSource;
}> {
const { input, changeRequest, repoRoot, deps } = params;
assertCheckoutSourceMatchesResolvedForge(changeRequest, deps);
const checkout = await resolvePrCheckoutIntent({
@@ -165,6 +184,7 @@ async function fetchChangeRequestHead(params: {
repoRoot,
deps,
});
const untrustedSource = worktreeUntrustedSource(checkout);
const startPoint = `refs/paseo/change-requests/${changeRequest.number}`;
const remote = await deps.fetchRef({
repoRoot,
@@ -180,10 +200,10 @@ async function fetchChangeRequestHead(params: {
sources: [{ remoteName: remote, remoteRef: `refs/heads/${baseName}` }],
destination: baseBranch,
});
return { baseBranch, startPoint };
return { baseBranch, startPoint, untrustedSource };
} catch {
// Without the remote's copy, the base resolves as any base branch name does.
return { baseBranch: baseName, startPoint };
return { baseBranch: baseName, startPoint, untrustedSource };
}
}
@@ -529,6 +529,10 @@ test("routes plugin requests and releases its owned catalog subscription on clea
return request;
},
emit: () => {},
hasWorktreeManager: () => false,
createWorktree: async () => null,
removeWorktree: async () => null,
restoreWorktree: async () => null,
listPlugins: async () => [plugin],
getLogs: () => [
{
@@ -670,6 +674,10 @@ test("leaves out the client bundles a catalog request already holds", async () =
const pluginRuntime: NonNullable<SessionOptions["pluginRuntime"]> = {
before: async (_name, request) => request,
emit: () => {},
hasWorktreeManager: () => false,
createWorktree: async () => null,
removeWorktree: async () => null,
restoreWorktree: async () => null,
listPlugins: async () => [],
getLogs: () => [],
installDirectory: async () => {
+164 -46
View File
@@ -113,6 +113,7 @@ import {
assertWorkspaceAutomationAllowedForWorkspace,
clearWorkspaceAutomationBlock,
formatWorkspaceAutomationBlockedMessage,
isCheckoutUntrusted,
} from "./workspace-automation-gate.js";
import {
WorkspaceLabelError,
@@ -246,7 +247,12 @@ import {
matchesAgentUpdatesFilter,
type AgentUpdatesService,
} from "./session/agent-updates/agent-updates-service.js";
import { expandTilde } from "../utils/path.js";
import {
createRealpathAwarePathMatcher,
expandTilde,
isRealpathInsideRoot,
normalizePathForIdentity,
} from "../utils/path.js";
import {
searchDirectoryEntries,
WORKSPACE_SEARCH_HIDDEN_DIRECTORIES,
@@ -287,7 +293,11 @@ import {
handleWorkspaceSetupStatusRequest as handleWorkspaceSetupStatusRequestMessage,
handleWorkspaceSetupRunRequest as handleWorkspaceSetupRunRequestMessage,
} from "./worktree-session.js";
import { archiveByScope, type ActiveWorkspaceRef } from "./workspace-archive-service.js";
import {
archiveByScope,
resolveWorkspaceBackingPath,
type ActiveWorkspaceRef,
} from "./workspace-archive-service.js";
import {
WorkspaceArchiveOperations,
type WorkspaceArchiveUndoInput,
@@ -529,6 +539,10 @@ export interface SessionOptions {
wait: import("./plugins/lifecycle/index.js").PluginLifecycle["wait"];
before: import("./plugins/lifecycle/index.js").PluginLifecycle["before"];
emit: import("./plugins/lifecycle/index.js").PluginLifecycle["emit"];
hasWorktreeManager: import("./plugins/runtime.js").PluginWorktreeManagerRuntime["hasWorktreeManager"];
createWorktree: import("./plugins/runtime.js").PluginWorktreeManagerRuntime["createWorktree"];
removeWorktree: import("./plugins/runtime.js").PluginWorktreeManagerRuntime["removeWorktree"];
restoreWorktree: import("./plugins/runtime.js").PluginWorktreeManagerRuntime["restoreWorktree"];
listPlugins(): Promise<import("@getpaseo/protocol/messages").PluginListItem[]>;
getLogs(pluginId: string): import("@getpaseo/protocol/messages").PluginLogEntry[];
installDirectory(input: {
@@ -1034,12 +1048,34 @@ export class Session {
this.workspaceRecovery = createWorkspaceRecoveryService({
paseoHome: this.paseoHome,
worktreesRoot: this.worktreesRoot,
worktreeManagers: this.pluginRuntime,
getWorkspace: (workspaceId) => this.workspaceRegistry.get(workspaceId),
getProject: (projectId) => this.projectRegistry.get(projectId),
isDirectory: (path) => this.filesystem.isDirectory(path),
unarchiveWorkspace: async (workspace) => {
await this.workspaceProvisioning.ensureWorkspaceRecordUnarchived(workspace);
},
isCheckoutUntrusted: (checkoutPath) =>
isCheckoutUntrusted(this.workspaceRegistry, checkoutPath),
syncCheckoutWorktreeManager: async ({
worktreeRoot,
worktreeManagerPluginId,
excludeWorkspaceId,
}) => {
const matchesCheckout = createRealpathAwarePathMatcher(worktreeRoot);
const workspaces = await this.workspaceRegistry.listAll();
const timestamp = new Date().toISOString();
for (const candidate of workspaces) {
if (candidate.workspaceId === excludeWorkspaceId) continue;
if (!matchesCheckout(candidate.worktreeRoot ?? candidate.cwd)) continue;
if ((candidate.worktreeManagerPluginId ?? null) === worktreeManagerPluginId) continue;
const { worktreeManagerPluginId: _previous, ...withoutManager } = candidate;
const updated: PersistedWorkspaceRecord = worktreeManagerPluginId
? { ...withoutManager, worktreeManagerPluginId, updatedAt: timestamp }
: { ...withoutManager, updatedAt: timestamp };
await this.workspaceRegistry.upsert(updated);
}
},
});
this.diffSession = new DiffSession(checkoutDiffManager.streams, this.sessionLogger);
this.checkoutSession = new CheckoutSession({
@@ -1251,9 +1287,15 @@ export class Session {
),
logger: this.sessionLogger,
});
this.workspaceArchiveOperations = resolveWorkspaceArchiveOperations(workspaceArchiveOperations);
this.createAgentLifecycleDispatch = new CreateAgentLifecycleDispatch({
paseoHome: this.paseoHome,
worktreesRoot: this.worktreesRoot,
worktreeManagers: this.pluginRuntime,
workspaceArchiveOperations: this.workspaceArchiveOperations,
getWorkspace: (workspaceId) => this.workspaceRegistry.get(workspaceId),
isCheckoutUntrusted: (checkoutPath) =>
isCheckoutUntrusted(this.workspaceRegistry, checkoutPath),
agentManager: this.agentManager,
agentStorage: this.agentStorage,
github: this.github,
@@ -1292,7 +1334,6 @@ export class Session {
},
);
this.workspaceSetupRuntime = resolveWorkspaceSetupRuntime(workspaceSetupRuntime);
this.workspaceArchiveOperations = resolveWorkspaceArchiveOperations(workspaceArchiveOperations);
this.getDaemonTcpPort = getDaemonTcpPort ?? null;
this.getDaemonTcpHost = getDaemonTcpHost ?? null;
this.serviceProxyPublicBaseUrl = serviceProxyPublicBaseUrl ?? null;
@@ -5782,11 +5823,14 @@ export class Session {
{
paseoHome: this.paseoHome,
paseoWorktreesBaseRoot: this.worktreesRoot,
worktreeManagers: this.pluginRuntime,
workspaceArchiveOperations: this.workspaceArchiveOperations,
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, archivedAt) =>
this.archiveWorkspaceRecord(workspaceId, archivedAt),
@@ -5798,6 +5842,8 @@ export class Session {
clearWorkspaceArchiving: (workspaceIds) => this.clearWorkspaceArchiving(workspaceIds),
killTerminalsForWorkspace: (workspaceId) =>
this.terminalController.killTerminalsForWorkspace(workspaceId),
isCheckoutUntrusted: (checkoutPath) =>
isCheckoutUntrusted(this.workspaceRegistry, checkoutPath),
sessionLogger: this.sessionLogger,
},
msg,
@@ -6503,9 +6549,60 @@ export class Session {
};
}
private async withWorkspaceCheckout<T>(workspaceId: string, run: () => Promise<T>): Promise<T> {
const workspace = await this.workspaceRegistry.get(workspaceId);
if (!workspace) {
return run();
}
const checkoutPath = await resolveWorkspaceBackingPath(workspace, {
paseoHome: this.paseoHome,
paseoWorktreesBaseRoot: this.worktreesRoot,
});
return this.workspaceArchiveOperations.withCheckout(checkoutPath, run);
}
private async withCheckoutForDirectory<T>(cwd: string, run: () => Promise<T>): Promise<T> {
const normalizedCwd = resolve(cwd);
const matchesCwd = createRealpathAwarePathMatcher(normalizedCwd);
const workspaces = await this.workspaceRegistry.listAll();
let matchingWorkspace = workspaces.find((workspace) => matchesCwd(workspace.cwd));
if (!matchingWorkspace) {
let bestDepth = -1;
for (const workspace of workspaces) {
if (
workspace.worktreeRoot !== null &&
isRealpathInsideRoot(workspace.worktreeRoot, normalizedCwd)
) {
const depth = normalizePathForIdentity(workspace.worktreeRoot).length;
if (depth > bestDepth) {
bestDepth = depth;
matchingWorkspace = workspace;
}
}
}
}
let checkoutPath = normalizedCwd;
if (matchingWorkspace) {
checkoutPath = await resolveWorkspaceBackingPath(matchingWorkspace, {
paseoHome: this.paseoHome,
paseoWorktreesBaseRoot: this.worktreesRoot,
});
} else {
const checkout = await this.workspaceGitService.getCheckout(normalizedCwd);
if (checkout.isGit && checkout.worktreeRoot) {
checkoutPath = resolve(checkout.worktreeRoot);
}
}
return this.workspaceArchiveOperations.withCheckout(checkoutPath, run);
}
private async restoreWorkspaceAndEmit(workspaceId: string): Promise<void> {
await this.workspaceRecovery.restore(workspaceId);
await this.publishRecoveredWorkspace(workspaceId);
await this.workspaceArchiveOperations.restore(workspaceId, () =>
this.withWorkspaceCheckout(workspaceId, async () => {
await this.workspaceRecovery.restore(workspaceId);
await this.publishRecoveredWorkspace(workspaceId);
}),
);
}
private async publishRecoveredWorkspace(workspaceId: string): Promise<void> {
@@ -6552,6 +6649,7 @@ export class Session {
): Promise<CreatePaseoWorktreeResult> {
const result = await createPaseoWorktree(input, {
lifecycle: this.pluginRuntime,
worktreeManagers: this.pluginRuntime,
github: this.github,
...(options?.resolveDefaultBranch
? { resolveDefaultBranch: options.resolveDefaultBranch }
@@ -6582,6 +6680,8 @@ export class Session {
worktreeRoot: workspace.worktreeRoot,
isPaseoOwnedWorktree: workspace.isPaseoOwnedWorktree,
mainRepoRoot: workspace.mainRepoRoot,
worktreeManagerPluginId: workspace.worktreeManagerPluginId,
untrustedSource: workspace.untrustedSource,
}));
}
@@ -7436,24 +7536,29 @@ export class Session {
}
const cwd = expandTilde(request.source.path);
const directoryExists = await this.filesystem.isDirectory(cwd).catch(() => false);
if (!directoryExists) {
throw new SessionRequestError("directory_not_found", `Directory not found: ${cwd}`);
}
const explicitTitle = request.title?.trim() || null;
const promptTitle = resolveFirstAgentPromptTitle(request.firstAgentContext);
const workspace = await this.workspaceProvisioning.createWorkspaceForDirectory(
cwd,
explicitTitle ?? promptTitle,
request.source.projectId,
{
expectsInitialAgent: Boolean(request.firstAgentContext),
workspaceId,
metadata: request.metadata,
...(await this.workspaceBackgroundIntent(request.background, request.callerAgentId)),
},
const backgroundIntent = await this.workspaceBackgroundIntent(
request.background,
request.callerAgentId,
);
const workspace = await this.withCheckoutForDirectory(cwd, async () => {
const directoryExists = await this.filesystem.isDirectory(cwd).catch(() => false);
if (!directoryExists) {
throw new SessionRequestError("directory_not_found", `Directory not found: ${cwd}`);
}
return this.workspaceProvisioning.createWorkspaceForDirectory(
cwd,
explicitTitle ?? promptTitle,
request.source.projectId,
{
expectsInitialAgent: Boolean(request.firstAgentContext),
workspaceId,
metadata: request.metadata,
...backgroundIntent,
},
);
});
await this.syncWorkspaceGitObserverForWorkspace(workspace);
const descriptor = await this.describeWorkspaceRecord(workspace);
await this.emitCreatedWorkspaceUpdate(
@@ -7535,34 +7640,41 @@ export class Session {
): Promise<void> {
const requestedCwd = request.cwd;
const cwd = expandTilde(requestedCwd);
const directoryExists = await this.filesystem.isDirectory(cwd).catch(() => false);
if (!directoryExists) {
this.sessionLogger.info(
{ requestedCwd, resolvedCwd: cwd, reason: "directory_not_found" },
"Open project rejected",
);
this.emit({
type: "open_project_response",
payload: {
requestId: request.requestId,
workspace: null,
error: `Directory not found: ${cwd}`,
errorCode: "directory_not_found",
},
});
return;
}
try {
const projectsBefore = new Map<string, PersistedProjectRecord>();
for (const project of await this.projectRegistry.list()) {
projectsBefore.set(project.projectId, project);
const opened = await this.withCheckoutForDirectory(cwd, async () => {
const directoryExists = await this.filesystem.isDirectory(cwd).catch(() => false);
if (!directoryExists) {
return null;
}
const projectsBefore = new Map<string, PersistedProjectRecord>();
for (const project of await this.projectRegistry.list()) {
projectsBefore.set(project.projectId, project);
}
const workspacesBefore = new Map<string, PersistedWorkspaceRecord>();
for (const workspaceRecord of await this.workspaceRegistry.listActive()) {
workspacesBefore.set(workspaceRecord.workspaceId, workspaceRecord);
}
const workspace = await this.workspaceProvisioning.findOrCreateWorkspaceForDirectory(cwd);
return { workspace, projectsBefore, workspacesBefore };
});
if (!opened) {
this.sessionLogger.info(
{ requestedCwd, resolvedCwd: cwd, reason: "directory_not_found" },
"Open project rejected",
);
this.emit({
type: "open_project_response",
payload: {
requestId: request.requestId,
workspace: null,
error: `Directory not found: ${cwd}`,
errorCode: "directory_not_found",
},
});
return;
}
const workspacesBefore = new Map<string, PersistedWorkspaceRecord>();
for (const workspaceRecord of await this.workspaceRegistry.listActive()) {
workspacesBefore.set(workspaceRecord.workspaceId, workspaceRecord);
}
const workspace = await this.workspaceProvisioning.findOrCreateWorkspaceForDirectory(cwd);
const { workspace, projectsBefore, workspacesBefore } = opened;
const project = await this.projectRegistry.get(workspace.projectId);
await this.syncWorkspaceGitObserverForWorkspace(workspace);
const descriptor = await this.describeWorkspaceRecord(workspace);
@@ -8130,6 +8242,8 @@ export class Session {
{
paseoHome: this.paseoHome,
paseoWorktreesBaseRoot: this.worktreesRoot,
worktreeManagers: this.pluginRuntime,
workspaceArchiveOperations: this.workspaceArchiveOperations,
github: this.github,
workspaceGitService: this.workspaceGitService,
agentManager: this.agentManager,
@@ -8146,6 +8260,8 @@ export class Session {
clearWorkspaceArchiving: (workspaceIds) => this.clearWorkspaceArchiving(workspaceIds),
assertWorkspaceAutomationAllowed: (workspaceId) =>
assertWorkspaceAutomationAllowedForWorkspace(this.workspaceRegistry, workspaceId),
isCheckoutUntrusted: (checkoutPath) =>
isCheckoutUntrusted(this.workspaceRegistry, checkoutPath),
killTerminalsForWorkspace: (workspaceId) =>
this.terminalController.killTerminalsForWorkspace(workspaceId),
stopWorkspaceSetup: (workspaceId) => this.workspaceSetupRuntime.stop(workspaceId),
@@ -8208,7 +8324,9 @@ export class Session {
): Promise<void> {
try {
await this.workspaceArchiveOperations.undo(request.workspaceId, (input) =>
this.restoreArchivedWorkspaceAndAgents(request.workspaceId, input),
this.withWorkspaceCheckout(request.workspaceId, () =>
this.restoreArchivedWorkspaceAndAgents(request.workspaceId, input),
),
);
this.emit({
type: "workspace.archive.undo.response",
@@ -52,6 +52,7 @@ export interface CreateWorktreeWorkspaceInput {
worktreeRoot: string;
branch: string | null;
baseBranch: string | null;
worktreeManagerPluginId?: string | null;
title: string | null;
metadata?: Record<string, JsonValue>;
expectsInitialAgent?: boolean;
@@ -273,14 +274,23 @@ export function createWorkspaceProvisioningService(deps: {
checkout.isGit && checkout.isPaseoOwnedWorktree
? await readPaseoWorktreeMetadata(checkout.worktreeRoot ?? normalizedCwd)
: null;
const checkoutRoot = checkout.worktreeRoot ?? normalizedCwd;
const matchesCheckout = createRealpathAwarePathMatcher(checkoutRoot);
const inheritedUntrustedSource = (await workspaceRegistry.listAll()).find(
(candidate) =>
Boolean(candidate.untrustedSource) &&
matchesCheckout(candidate.worktreeRoot ?? candidate.cwd),
)?.untrustedSource;
const timestamp = new Date().toISOString();
const workspace = createPersistedWorkspaceRecord({
workspaceId: context?.workspaceId ?? generateWorkspaceId(),
projectId: project.projectId,
...initialWorkspacePlacement({ source: "checkout", cwd: normalizedCwd, checkout }),
baseBranch: baseMetadata?.baseRef ?? baseMetadata?.baseRefName ?? null,
worktreeManagerPluginId: baseMetadata?.worktreeManagerPluginId ?? null,
title: title?.trim() || null,
metadata: context?.metadata,
...(inheritedUntrustedSource ? { untrustedSource: inheritedUntrustedSource } : {}),
createdAt: timestamp,
updatedAt: timestamp,
...(await resolveCreationMetadata(context)),
@@ -320,6 +330,7 @@ export function createWorkspaceProvisioningService(deps: {
baseBranch: input.baseBranch,
mainRepoRoot: repoRoot,
}),
worktreeManagerPluginId: input.worktreeManagerPluginId ?? null,
title: input.title,
metadata: input.metadata,
createdAt: timestamp,
@@ -9,8 +9,11 @@ import {
isPaseoOwnedWorktreeCwd,
mapWorkspaceCwdToWorktree,
rollbackCreatedPaseoWorktree,
runPluginWorktreeManagerCheckout,
type WorktreeSource,
} from "../../../utils/worktree.js";
import type { PluginWorktreeManagerRuntime } from "../../plugins/runtime.js";
import type { PluginWorktreeRestoreTarget } from "@getpaseo/plugin/server";
import { WorktreeRequestError, toWorktreeRequestError } from "../../worktree-errors.js";
import {
resolveWorkspaceDisplayName,
@@ -64,10 +67,20 @@ type UnavailableRecoveryState = Extract<WorkspaceRecoveryState, { kind: "unavail
export function createWorkspaceRecoveryService(deps: {
paseoHome: string;
worktreesRoot?: string;
worktreeManagers?: Pick<
PluginWorktreeManagerRuntime,
"hasWorktreeManager" | "restoreWorktree" | "removeWorktree"
>;
getWorkspace: (workspaceId: string) => Promise<PersistedWorkspaceRecord | null>;
getProject: (projectId: string) => Promise<PersistedProjectRecord | null>;
isDirectory: (path: string) => Promise<boolean>;
unarchiveWorkspace: (workspace: PersistedWorkspaceRecord) => Promise<void>;
isCheckoutUntrusted?: (checkoutPath: string) => Promise<boolean>;
syncCheckoutWorktreeManager?: (input: {
worktreeRoot: string;
worktreeManagerPluginId: string | null;
excludeWorkspaceId: string;
}) => Promise<void>;
}): WorkspaceRecoveryService {
async function resolveRecovery(
workspaceId: string,
@@ -140,17 +153,32 @@ export function createWorkspaceRecoveryService(deps: {
throw new Error(resolved.message);
}
let workspaceToUnarchive = resolved.workspace;
let recreated: { worktreePath: string; pluginId: string | null } | null = null;
if (resolved.kind === "restore") {
await recreateArchivedWorktree(resolved.workspace, resolved.sourceRepoRoot);
recreated = await recreateArchivedWorktree(resolved.workspace, resolved.sourceRepoRoot);
if ((resolved.workspace.worktreeManagerPluginId ?? null) !== recreated.pluginId) {
const { worktreeManagerPluginId: _previous, ...withoutManager } = resolved.workspace;
workspaceToUnarchive = recreated.pluginId
? { ...withoutManager, worktreeManagerPluginId: recreated.pluginId }
: withoutManager;
}
}
await deps.unarchiveWorkspace(workspaceToUnarchive);
if (recreated) {
await deps.syncCheckoutWorktreeManager?.({
worktreeRoot: recreated.worktreePath,
worktreeManagerPluginId: recreated.pluginId,
excludeWorkspaceId: workspaceId,
});
}
await deps.unarchiveWorkspace(resolved.workspace);
return { workspaceId, action: resolved.kind };
}
async function recreateArchivedWorktree(
workspace: PersistedWorkspaceRecord,
sourceRepoRoot: string,
): Promise<void> {
): Promise<{ worktreePath: string; pluginId: string | null }> {
let source: WorktreeSource;
const checkout = parseWorkspaceHead(workspace);
if (checkout.kind === "branch") {
@@ -194,18 +222,22 @@ export function createWorkspaceRecoveryService(deps: {
hasRecordedWorktreePath = ownership.allowed;
}
const untrusted =
Boolean(workspace.untrustedSource) ||
Boolean(await deps.isCheckoutUntrusted?.(previousWorktreePath));
let recreatedWorktreePath: string;
let restoredByPluginId: string | null = null;
try {
const result = await createWorktree({
cwd: sourceRepoRoot,
worktreeSlug: basename(previousWorktreePath),
const restored = await recreateWorktreeCheckout({
workspace,
sourceRepoRoot,
source,
paseoHome: deps.paseoHome,
worktreesRoot: deps.worktreesRoot,
...(hasRecordedWorktreePath ? { worktreePath: previousWorktreePath } : {}),
previousWorktreePath,
hasRecordedWorktreePath,
untrusted,
});
recreatedWorktreePath = result.worktreePath;
recreatedWorktreePath = restored.worktreePath;
restoredByPluginId = restored.pluginId;
} catch (error) {
throw toWorktreeRequestError(error);
}
@@ -236,15 +268,98 @@ export function createWorkspaceRecoveryService(deps: {
teardownCwds: [],
paseoHome: deps.paseoHome,
worktreesBaseRoot: deps.worktreesRoot,
worktreeManagers: deps.worktreeManagers,
worktreeManagerPluginId: restoredByPluginId,
removeReason: "rollback",
untrusted,
},
error,
);
}
return { worktreePath: recreatedWorktreePath, pluginId: restoredByPluginId };
}
async function recreateWorktreeCheckout(options: {
workspace: PersistedWorkspaceRecord;
sourceRepoRoot: string;
source: Extract<WorktreeSource, { kind: "restore" | "restore-commit" | "restore-from-base" }>;
previousWorktreePath: string;
hasRecordedWorktreePath: boolean;
untrusted: boolean;
}): Promise<{ worktreePath: string; pluginId: string | null }> {
const {
workspace,
sourceRepoRoot,
source,
previousWorktreePath,
hasRecordedWorktreePath,
untrusted,
} = options;
const managerPluginId = workspace.worktreeManagerPluginId;
if (managerPluginId && hasRecordedWorktreePath && deps.worktreeManagers) {
const adopted = await runPluginWorktreeManagerCheckout({
cwd: sourceRepoRoot,
source,
operation: "restore",
preferredPluginId: managerPluginId,
untrusted,
paseoHome: deps.paseoHome,
worktreesBaseRoot: deps.worktreesRoot,
worktreeManagers: deps.worktreeManagers,
run: () =>
deps.worktreeManagers!.restoreWorktree(
{
repoRoot: sourceRepoRoot,
path: previousWorktreePath,
target: restoreTargetFromWorktreeSource(source),
baseRef: workspace.baseBranch,
untrusted,
},
{ preferredPluginId: managerPluginId },
),
verifyValidatedPath: (validatedPath, pluginId) => {
if (!createRealpathAwarePathMatcher(previousWorktreePath)(validatedPath)) {
throw new WorktreeRequestError({
code: "unknown",
message: `Plugin ${pluginId} restored worktree to ${validatedPath}, expected ${previousWorktreePath}`,
});
}
},
});
if (adopted) {
return {
worktreePath: adopted.worktreePath,
pluginId: adopted.worktreeManagerPluginId ?? managerPluginId,
};
}
}
const result = await createWorktree({
cwd: sourceRepoRoot,
worktreeSlug: basename(previousWorktreePath),
source,
paseoHome: deps.paseoHome,
worktreesRoot: deps.worktreesRoot,
...(hasRecordedWorktreePath ? { worktreePath: previousWorktreePath } : {}),
});
return { worktreePath: result.worktreePath, pluginId: null };
}
return { inspect, restore };
}
function restoreTargetFromWorktreeSource(
source: Extract<WorktreeSource, { kind: "restore" | "restore-commit" | "restore-from-base" }>,
): PluginWorktreeRestoreTarget {
if (source.kind === "restore") {
return { type: "branch", branch: source.branchName };
}
if (source.kind === "restore-commit") {
return { type: "commit", commit: source.commit };
}
return { type: "from-base", branch: source.branchName, baseRef: source.baseRef };
}
async function resolveRecoveryBase(repoRoot: string, recordedBase: string | null): Promise<string> {
if (recordedBase) {
try {
+11 -3
View File
@@ -70,6 +70,12 @@ import type { HubRelationshipManagement } from "./hub/relationship-controller.js
import { WorkspaceSetupObservation } from "./workspace-setup-observation.js";
import { WorkspaceSetupRuntime } from "./workspace-setup-runtime.js";
import { WorkspaceArchiveOperations } from "./workspace-archive-operations.js";
function resolveWorkspaceArchiveOperations(
operations: WorkspaceArchiveOperations | undefined,
): WorkspaceArchiveOperations {
return operations ?? new WorkspaceArchiveOperations();
}
import type { HubExecutionAgents } from "./hub/daemon-executions.js";
import type { AgentProvider } from "./agent/agent-sdk-types.js";
import { ProviderSnapshotManager } from "./agent/provider-snapshot-manager.js";
@@ -618,9 +624,9 @@ export class VoiceAssistantWebSocketServer {
private readonly voiceCallerContexts = new Map<string, VoiceCallerContext>();
private readonly workspaceSetupObservation = new WorkspaceSetupObservation();
private readonly workspaceSetupRuntime: WorkspaceSetupRuntime;
// One lane per workspace across every connection, so an undo from any client can cancel an
// archive another connection started.
private readonly workspaceArchiveOperations = new WorkspaceArchiveOperations();
// One lane per workspace and per checkout across the daemon, so archive, undo, and restore
// from any client or background caller coordinate through one boundary.
private readonly workspaceArchiveOperations: WorkspaceArchiveOperations;
private readonly providerSnapshotManager: ProviderSnapshotManager;
private onLifecycleIntent!: ((intent: SessionLifecycleIntent) => void) | null;
private onBranchChanged!:
@@ -711,9 +717,11 @@ export class VoiceAssistantWebSocketServer {
pluginRuntime?: SessionOptions["pluginRuntime"],
orchestrationSkills?: SessionOptions["orchestrationSkills"],
workspaceLabelService?: WorkspaceLabelService,
workspaceArchiveOperations?: WorkspaceArchiveOperations,
) {
this.logger = logger.child({ module: "websocket-server" });
this.workspaceSetupRuntime = workspaceSetupRuntime;
this.workspaceArchiveOperations = resolveWorkspaceArchiveOperations(workspaceArchiveOperations);
this.advertiseDaemonStatusRpc = wsConfig.daemonStatusRpc !== false;
this.advertiseRelayConfig = wsConfig.relayConfig !== false;
this.connectionLifecycle = wsConfig.startPaused === true ? "starting" : "accepting";
@@ -273,4 +273,146 @@ describe("WorkspaceArchiveOperations", () => {
kind: "archived",
});
});
test("concurrent restores join the in-flight restore and share its outcome", async () => {
const operations = new WorkspaceArchiveOperations();
let release!: () => void;
const gate = new Promise<void>((resolve) => {
release = resolve;
});
let calls = 0;
const first = operations.restore("ws", async () => {
calls += 1;
await gate;
throw new Error("restore setup failed");
});
const second = operations.restore("ws", async () => {
calls += 1;
});
release();
await expect(first).rejects.toThrow("restore setup failed");
await expect(second).rejects.toThrow("restore setup failed");
expect(calls).toBe(1);
await operations.restore("ws", async () => {
calls += 1;
});
expect(calls).toBe(2);
});
test("undo after a restore queued behind a running archive still aborts the archive and shares the undo outcome", async () => {
const operations = new WorkspaceArchiveOperations();
const archive = parkedArchive(["agent-a"]);
const order: string[] = [];
let restoreCalls = 0;
const archiveDone = operations.archive("ws", async (signal) => {
try {
return await archive.run(signal);
} finally {
order.push("archive stopped");
}
});
await archive.started;
const restoreDone = operations.restore("ws", async () => {
restoreCalls += 1;
order.push("restore");
});
expect(archive.aborted).toBe(false);
const undoDone = operations.undo("ws", async ({ archivedAt }) => {
order.push(`undo:${archivedAt}`);
});
expect(archive.aborted).toBe(true);
archive.release();
await expect(archiveDone).resolves.toEqual({ kind: "canceled", archivedAt: "stamp" });
await Promise.all([restoreDone, undoDone]);
expect(restoreCalls).toBe(0);
expect(order).toEqual(["archive stopped", "undo:stamp"]);
});
test("restore queued behind a running archive waits without aborting it when no undo arrives", async () => {
const operations = new WorkspaceArchiveOperations();
const archive = parkedArchive(["agent-a"]);
const order: string[] = [];
const archiveDone = operations.archive("ws", async (signal) => {
const result = await archive.run(signal);
order.push("archived");
return result;
});
await archive.started;
const restoreDone = operations.restore("ws", async () => {
order.push("restored");
});
expect(archive.aborted).toBe(false);
archive.release();
await expect(archiveDone).resolves.toMatchObject({ kind: "archived" });
await restoreDone;
expect(order).toEqual(["archived", "restored"]);
});
test("undo after restore has already started joins the running restore", async () => {
const operations = new WorkspaceArchiveOperations();
await operations.archive("ws", async () => archived(["agent-a"]));
const restoreGate = deferred();
let restoreCalls = 0;
let undoCalls = 0;
const restoreDone = operations.restore("ws", async () => {
restoreCalls += 1;
await restoreGate.promise;
});
// Flush microtask so restore has moved past any settled archive check.
await Promise.resolve();
const undoDone = operations.undo("ws", async () => {
undoCalls += 1;
});
restoreGate.resolve();
await Promise.all([restoreDone, undoDone]);
expect(restoreCalls).toBe(1);
expect(undoCalls).toBe(0);
});
test("withCheckout serializes operations on the same checkout path while allowing independent checkouts in parallel", async () => {
const operations = new WorkspaceArchiveOperations();
const firstGate = deferred();
const firstStarted = deferred();
const order: string[] = [];
const first = operations.withCheckout("/tmp/paseo-checkout-a", async () => {
order.push("a1-start");
firstStarted.resolve();
await firstGate.promise;
order.push("a1-end");
return "first";
});
await firstStarted.promise;
const second = operations.withCheckout("/tmp/paseo-checkout-a/", async () => {
order.push("a2");
return "second";
});
const other = operations.withCheckout("/tmp/paseo-checkout-b", async () => {
order.push("b");
return "other";
});
await expect(other).resolves.toBe("other");
expect(order).toEqual(["a1-start", "b"]);
firstGate.resolve();
await expect(first).resolves.toBe("first");
await expect(second).resolves.toBe("second");
expect(order).toEqual(["a1-start", "b", "a1-end", "a2"]);
});
});
@@ -1,3 +1,6 @@
import { resolve } from "node:path";
import { normalizePathForIdentity } from "../utils/path.js";
import { type ArchiveResult, WorkspaceArchiveCanceledError } from "./workspace-archive-service.js";
export type WorkspaceArchiveOutcome =
@@ -8,23 +11,42 @@ export interface WorkspaceArchiveUndoInput {
archivedAt?: string;
}
interface PendingArchive {
controller: AbortController;
done: Promise<WorkspaceArchiveOutcome>;
}
type LaneEntry =
| { kind: "archiving"; controller: AbortController; done: Promise<WorkspaceArchiveOutcome> }
| {
kind: "restoring";
pendingArchive: PendingArchive | null;
supersededBy: Promise<void> | null;
done: Promise<void>;
}
| { kind: "undoing"; done: Promise<void> };
/**
* One lane per workspace for archive and its undo, shared by every session on the daemon.
* Daemon-wide coordinator for workspace archive, undo, and restore operations.
*
* Per-workspace lanes:
* - An archive while one runs joins it.
* - An undo while an archive runs aborts it, waits for it to stop, then restores.
* - An archive while an undo runs waits for the undo, then archives.
* - An undo while an undo runs joins it.
* - An undo while an archive runs (including when a restore queued behind it) aborts the archive,
* waits for it to stop, then restores.
* - A restore while an archive runs waits for the archive without aborting it, then restores.
* - An archive while an undo or restore runs waits for it, then archives.
* - A duplicate undo or restore while recovery runs joins it.
*
* Each call claims the lane synchronously, so whichever request arrives last decides the
* workspace's final state no matter how the earlier work interleaves.
* Per-checkout gates:
* - Any archive or recovery mutating the same backing checkout directory (including CLI worktree
* archives covering multiple workspace records, background auto-archives, and sibling workspaces
* sharing one checkout) serializes through `withCheckout` so a restore cannot inspect or unarchive
* a checkout while an archive is still deleting it.
* - Lock order is strictly workspace lane -> checkout gate, preventing deadlocks.
*/
export class WorkspaceArchiveOperations {
private readonly lanes = new Map<string, LaneEntry>();
private readonly checkoutGates = new Map<string, Promise<void>>();
archive(
workspaceId: string,
@@ -57,16 +79,92 @@ export class WorkspaceArchiveOperations {
if (current?.kind === "undoing") {
return current.done;
}
current?.controller.abort();
if (current?.kind === "restoring" && current.pendingArchive === null) {
return current.done;
}
let pendingArchive: PendingArchive | null = null;
if (current?.kind === "archiving") {
pendingArchive = { controller: current.controller, done: current.done };
} else if (current?.kind === "restoring") {
pendingArchive = current.pendingArchive;
}
pendingArchive?.controller.abort();
const done = (async () => {
const outcome =
current?.kind === "archiving" ? await current.done.catch(() => undefined) : undefined;
const outcome = pendingArchive ? await pendingArchive.done.catch(() => undefined) : undefined;
await restore({ archivedAt: outcome?.kind === "canceled" ? outcome.archivedAt : undefined });
})();
if (current?.kind === "restoring") {
current.supersededBy = done;
}
this.claim(workspaceId, { kind: "undoing", done });
return done;
}
/**
* Run a workspace recovery restore on the per-workspace lane so concurrent restores
* across daemon sessions share one outcome and wait for checkout + validation to settle.
* When queued behind an in-flight archive, the archive stays cancelable by a subsequent undo.
*/
restore(workspaceId: string, run: () => Promise<void>): Promise<void> {
const current = this.lanes.get(workspaceId);
if (current?.kind === "undoing" || current?.kind === "restoring") {
return current.done;
}
const pendingArchive: PendingArchive | null =
current?.kind === "archiving" ? { controller: current.controller, done: current.done } : null;
const entry: Extract<LaneEntry, { kind: "restoring" }> = {
kind: "restoring",
pendingArchive,
supersededBy: null,
done: Promise.resolve(),
};
entry.done = (async () => {
if (pendingArchive) {
await settled(pendingArchive.done);
entry.pendingArchive = null;
if (entry.supersededBy) {
await entry.supersededBy;
return;
}
} else {
await settled(current?.done);
}
await run();
})();
this.claim(workspaceId, entry);
return entry.done;
}
/**
* Serialize mutations touching the same backing checkout directory across all daemon callers
* (UI archive, CLI worktree archive, background auto-archive, undo, and recovery restore).
*/
withCheckout<T>(checkoutPath: string, run: () => Promise<T>): Promise<T> {
const key = normalizePathForIdentity(resolve(checkoutPath));
const previous = this.checkoutGates.get(key);
let release!: () => void;
const current = new Promise<void>((resolveGate) => {
release = resolveGate;
});
const gate = previous ? previous.then(() => current) : current;
this.checkoutGates.set(key, gate);
const cleanup = () => {
if (this.checkoutGates.get(key) === gate) {
this.checkoutGates.delete(key);
}
};
void gate.then(cleanup, cleanup);
return (async () => {
await settled(previous);
try {
return await run();
} finally {
release();
}
})();
}
private claim(workspaceId: string, entry: LaneEntry): void {
this.lanes.set(workspaceId, entry);
const release = () => {
@@ -1290,3 +1290,59 @@ test("a canceled archive with no matching agents leaves earlier closed agents ar
});
expect(restored).toEqual([]);
});
test.each(["outer", "inner"])(
"archive keeps nested workspace when %s is managed",
async (managed) => {
const { repoDir } = createGitRepo();
const rootDir = path.dirname(repoDir);
const outerPath = path.join(rootDir, "worktrees", "team");
const innerPath = path.join(outerPath, "topic");
mkdirSync(path.dirname(outerPath), { recursive: true });
execFileSync("git", ["worktree", "add", "-b", "team", outerPath], {
cwd: repoDir,
stdio: "pipe",
});
execFileSync("git", ["worktree", "add", "-b", "topic", innerPath], {
cwd: repoDir,
stdio: "pipe",
});
const dirtyFile = path.join(innerPath, "uncommitted.txt");
writeFileSync(dirtyFile, "keep-inner");
const activeWorkspaces: ActiveWorkspaceRef[] = [
{
workspaceId: "ws-team",
cwd: outerPath,
kind: "worktree",
worktreeRoot: outerPath,
worktreeManagerPluginId: managed === "outer" ? "manager" : null,
isPaseoOwnedWorktree: true,
mainRepoRoot: repoDir,
},
{
workspaceId: "ws-topic",
cwd: innerPath,
kind: "worktree",
worktreeRoot: innerPath,
worktreeManagerPluginId: managed === "inner" ? "manager" : null,
isPaseoOwnedWorktree: true,
mainRepoRoot: repoDir,
},
];
const deps = createArchiveDeps({
paseoHome: rootDir,
activeWorkspaces,
});
const result = await archiveByScope(deps, {
scope: { kind: "workspace", workspaceId: "ws-team" },
requestId: "archive-outer",
});
expect(result.archivedWorkspaceIds).toEqual(["ws-team"]);
expect(result.removedDirectory).toBe(false);
expect(existsSync(outerPath)).toBe(true);
expect(readFileSync(dirtyFile, "utf8")).toBe("keep-inner");
},
);
@@ -19,19 +19,26 @@ import type {
WorkspaceArchiveContext,
WorkspaceRegistry,
} from "./workspace-registry.js";
import { createRealpathAwarePathMatcher } from "../utils/path.js";
import { createRealpathAwarePathMatcher, isRealpathInsideRoot } from "../utils/path.js";
import { runWithGitCommandPriority } from "../utils/run-git-command.js";
import { WorkspaceAutomationBlockedError } from "./workspace-automation-gate.js";
import type { PluginWorktreeManagerRuntime } from "./plugins/runtime.js";
import type { WorkspaceArchiveOperations } from "./workspace-archive-operations.js";
export type ActiveWorkspaceRef = Pick<
PersistedWorkspaceRecord,
"workspaceId" | "cwd" | "kind" | "worktreeRoot" | "isPaseoOwnedWorktree" | "mainRepoRoot"
>;
> & {
worktreeManagerPluginId?: string | null;
untrustedSource?: PersistedWorkspaceRecord["untrustedSource"];
};
export interface ArchiveDependencies {
paseoHome?: string;
// Base directory that may hold worktrees across repositories.
paseoWorktreesBaseRoot?: string;
worktreeManagers?: Pick<PluginWorktreeManagerRuntime, "removeWorktree">;
workspaceArchiveOperations?: Pick<WorkspaceArchiveOperations, "withCheckout">;
github: ForgeService;
workspaceGitService: Pick<WorkspaceGitService, "getSnapshot" | "invalidateWorktrees">;
agentManager: Pick<AgentManager, "listAgents" | "getAgent" | "archiveAgent" | "archiveSnapshot">;
@@ -53,6 +60,7 @@ export interface ArchiveDependencies {
killTerminalsForWorkspace: (workspaceId: string) => Promise<void>;
stopWorkspaceSetup?: (workspaceId: string) => Promise<void>;
assertWorkspaceAutomationAllowed?: (workspaceId: string) => Promise<void>;
isCheckoutUntrusted?: (checkoutPath: string) => Promise<boolean>;
sessionLogger?: Logger;
}
@@ -119,6 +127,8 @@ interface BackingDirectory {
registryProven: boolean;
mainRepoRoot: string | null;
paseoWorktreesRoot: string | null;
worktreeManagerPluginId: string | null;
untrusted: boolean;
}
interface ArchiveTarget {
@@ -142,6 +152,13 @@ export async function resolveWorkspaceIdAtPath(
return dependencies.findWorkspaceIdForCwd(targetPath);
}
export async function resolveWorkspaceBackingPath(
workspace: ActiveWorkspaceRef,
dependencies: Pick<ArchiveDependencies, "paseoHome" | "paseoWorktreesBaseRoot">,
): Promise<string> {
return (await resolveWorkspaceBackingDirectory(workspace, dependencies)).path;
}
// Resolves the in-scope record set, tears each down
// (agents + terminals + record), then removes the backing directory iff it is
// Paseo-owned AND no active workspace still references it.
@@ -164,69 +181,98 @@ async function archiveByScopeWithPriority(
};
checkpoint();
const target = await resolveArchiveTarget(dependencies, request.scope);
const targetWorkspaceIds = target.workspaceIds;
const runArchive = async (): Promise<ArchiveResult> => {
checkpoint();
const target = await resolveArchiveTarget(dependencies, request.scope);
const targetWorkspaceIds = target.workspaceIds;
await stopWorkspaceSetups(dependencies, target.setupWorkspaceIds, request.requestId);
checkpoint();
await stopWorkspaceSetups(dependencies, target.setupWorkspaceIds, request.requestId);
checkpoint();
if (targetWorkspaceIds.length > 0) {
dependencies.markWorkspaceArchiving(targetWorkspaceIds, new Date().toISOString());
}
let removedDirectory = false;
let directoryLeftBehind: ArchiveResult["directoryLeftBehind"];
try {
if (targetWorkspaceIds.length > 0) {
await dependencies.emitWorkspaceUpdatesForWorkspaceIds(targetWorkspaceIds);
dependencies.markWorkspaceArchiving(targetWorkspaceIds, new Date().toISOString());
}
checkpoint();
const { archivedAgents, archivedWorkspaceIds } = await archiveTargetRecords(
dependencies,
targetWorkspaceIds,
{ requestId: request.requestId, checkpoint, archivedAt },
);
checkpoint();
let removedDirectory = false;
let directoryLeftBehind: ArchiveResult["directoryLeftBehind"];
if (target.backing?.mainRepoRoot) {
try {
await dependencies.workspaceGitService.getSnapshot(target.backing.mainRepoRoot, {
force: true,
reason: "archive-worktree",
});
} catch (error) {
dependencies.sessionLogger?.warn(
{ err: error, cwd: target.backing.mainRepoRoot, requestId: request.requestId },
"Failed to force-refresh workspace git snapshot after archiving",
try {
if (targetWorkspaceIds.length > 0) {
await dependencies.emitWorkspaceUpdatesForWorkspaceIds(targetWorkspaceIds);
}
checkpoint();
const { archivedAgents, archivedWorkspaceIds } = await archiveTargetRecords(
dependencies,
targetWorkspaceIds,
{ requestId: request.requestId, checkpoint, archivedAt },
);
checkpoint();
if (target.backing?.mainRepoRoot) {
try {
await dependencies.workspaceGitService.getSnapshot(target.backing.mainRepoRoot, {
force: true,
reason: "archive-worktree",
});
} catch (error) {
dependencies.sessionLogger?.warn(
{ err: error, cwd: target.backing.mainRepoRoot, requestId: request.requestId },
"Failed to force-refresh workspace git snapshot after archiving",
);
}
}
if (target.backing !== null) {
const removal = await maybeRemoveDirectory(
dependencies,
{ requestId: request.requestId, checkpoint },
target,
archivedWorkspaceIds,
);
removedDirectory = removal.removedDirectory;
directoryLeftBehind = removal.directoryLeftBehind;
}
return {
archivedAgentIds: Array.from(archivedAgents),
archivedWorkspaceIds,
removedDirectory,
...(directoryLeftBehind ? { directoryLeftBehind } : {}),
};
} finally {
if (targetWorkspaceIds.length > 0) {
dependencies.clearWorkspaceArchiving(targetWorkspaceIds);
await dependencies.emitWorkspaceUpdatesForWorkspaceIds(targetWorkspaceIds);
}
}
};
if (target.backing !== null) {
const removal = await maybeRemoveDirectory(
dependencies,
{ requestId: request.requestId, checkpoint },
target,
archivedWorkspaceIds,
);
removedDirectory = removal.removedDirectory;
directoryLeftBehind = removal.directoryLeftBehind;
}
return {
archivedAgentIds: Array.from(archivedAgents),
archivedWorkspaceIds,
removedDirectory,
...(directoryLeftBehind ? { directoryLeftBehind } : {}),
};
} finally {
if (targetWorkspaceIds.length > 0) {
dependencies.clearWorkspaceArchiving(targetWorkspaceIds);
await dependencies.emitWorkspaceUpdatesForWorkspaceIds(targetWorkspaceIds);
}
const checkoutPath = dependencies.workspaceArchiveOperations
? await resolveArchiveCheckoutPath(dependencies, request.scope)
: null;
if (dependencies.workspaceArchiveOperations && checkoutPath) {
return dependencies.workspaceArchiveOperations.withCheckout(checkoutPath, runArchive);
}
return runArchive();
}
async function resolveArchiveCheckoutPath(
dependencies: ArchiveDependencies,
scope: ArchiveScope,
): Promise<string | null> {
if (scope.kind === "workspace") {
const record =
(await dependencies.getWorkspace?.(scope.workspaceId)) ??
(await dependencies.listActiveWorkspaces()).find(
(workspace) => workspace.workspaceId === scope.workspaceId,
);
if (!record) {
return null;
}
return resolveWorkspaceBackingPath(record, dependencies);
}
return (await resolveBackingDirectory(scope.targetPath, dependencies)).path;
}
async function resolveArchiveTarget(
@@ -313,6 +359,8 @@ async function resolveWorkspaceBackingDirectory(
workspace: ActiveWorkspaceRef,
dependencies: Pick<ArchiveDependencies, "paseoHome" | "paseoWorktreesBaseRoot">,
): Promise<BackingDirectory> {
const worktreeManagerPluginId = workspace.worktreeManagerPluginId ?? null;
const untrusted = Boolean(workspace.untrustedSource);
if (workspace.isPaseoOwnedWorktree === false) {
return {
path: resolve(workspace.worktreeRoot ?? workspace.cwd),
@@ -321,6 +369,8 @@ async function resolveWorkspaceBackingDirectory(
registryProven: false,
mainRepoRoot: workspace.mainRepoRoot ?? null,
paseoWorktreesRoot: null,
worktreeManagerPluginId,
untrusted,
};
}
if (workspace.isPaseoOwnedWorktree && workspace.worktreeRoot && workspace.mainRepoRoot) {
@@ -331,6 +381,8 @@ async function resolveWorkspaceBackingDirectory(
registryProven: true,
mainRepoRoot: workspace.mainRepoRoot,
paseoWorktreesRoot: null,
worktreeManagerPluginId,
untrusted,
};
}
if (workspace.kind !== "worktree") {
@@ -341,6 +393,8 @@ async function resolveWorkspaceBackingDirectory(
registryProven: false,
mainRepoRoot: workspace.mainRepoRoot ?? null,
paseoWorktreesRoot: null,
worktreeManagerPluginId,
untrusted,
};
}
@@ -350,7 +404,12 @@ async function resolveWorkspaceBackingDirectory(
workspace.worktreeRoot ?? workspace.cwd,
dependencies,
);
return { ...backing, mainRepoRoot: workspace.mainRepoRoot ?? backing.mainRepoRoot };
return {
...backing,
mainRepoRoot: workspace.mainRepoRoot ?? backing.mainRepoRoot,
worktreeManagerPluginId: worktreeManagerPluginId ?? backing.worktreeManagerPluginId,
untrusted: untrusted || backing.untrusted,
};
}
async function resolveBackingDirectory(
@@ -369,6 +428,8 @@ async function resolveBackingDirectory(
registryProven: false,
mainRepoRoot: ownership.repoRoot ?? null,
paseoWorktreesRoot: ownership.worktreeRoot ?? null,
worktreeManagerPluginId: null,
untrusted: false,
};
}
@@ -453,11 +514,16 @@ async function maybeRemoveDirectory(
teardownTarget.workspaceId === null || archivedWorkspaceIdSet.has(teardownTarget.workspaceId),
);
let untrustedBacking =
backing.untrusted || Boolean(await dependencies.isCheckoutUntrusted?.(backing.path));
try {
const allowedTeardownTargets = await filterAllowedTeardownTargets(
dependencies,
teardownTargets,
);
if (allowedTeardownTargets.length < teardownTargets.length) {
untrustedBacking = true;
}
for (const teardownTarget of uniqueTeardownTargets(allowedTeardownTargets)) {
request.checkpoint();
await runWorktreeTeardownCommands({
@@ -481,7 +547,7 @@ async function maybeRemoveDirectory(
if (
!(await isDirectoryUnreferenced(
remainingActive,
backing.path,
backing,
new Set(archivedWorkspaceIds),
dependencies,
))
@@ -501,6 +567,10 @@ async function maybeRemoveDirectory(
paseoHome: dependencies.paseoHome,
worktreesBaseRoot: dependencies.paseoWorktreesBaseRoot,
registryProven: backing.registryProven,
worktreeManagers: dependencies.worktreeManagers,
worktreeManagerPluginId: backing.worktreeManagerPluginId,
removeReason: "archive",
untrusted: untrustedBacking,
});
dependencies.workspaceGitService.invalidateWorktrees();
dependencies.github.invalidate({ cwd: backing.path });
@@ -618,21 +688,28 @@ export async function archiveWorkspaceContents(
return archivedAgents;
}
// True when, after archiving
// the in-scope records, no active workspace still points at targetDir. Derived
// from records each call — no stored counter.
// Active workspaces on the same checkout keep it alive. A manager can place
// a checkout anywhere, so also protect nested workspaces when either checkout
// is manager-owned.
async function isDirectoryUnreferenced(
activeWorkspaces: ActiveWorkspaceRef[],
targetDir: string,
targetDirectory: BackingDirectory,
archivedWorkspaceIds: ReadonlySet<string>,
dependencies: Pick<ArchiveDependencies, "paseoHome" | "paseoWorktreesBaseRoot">,
): Promise<boolean> {
const target = resolve(targetDir);
const target = targetDirectory.path;
const matchesTarget = createRealpathAwarePathMatcher(target);
for (const workspace of activeWorkspaces) {
if (archivedWorkspaceIds.has(workspace.workspaceId)) continue;
const backingDirectory = await resolveWorkspaceBackingDirectory(workspace, dependencies);
if (matchesTarget(backingDirectory.path)) return false;
if (
(targetDirectory.worktreeManagerPluginId || backingDirectory.worktreeManagerPluginId) &&
(isRealpathInsideRoot(target, backingDirectory.path) ||
isRealpathInsideRoot(target, workspace.cwd))
) {
return false;
}
}
return true;
}
@@ -1,3 +1,4 @@
import { createRealpathAwarePathMatcher } from "../utils/path.js";
import type { WorkspaceRegistry } from "./workspace-registry.js";
export interface UntrustedWorkspaceSource {
@@ -34,17 +35,44 @@ export async function assertWorkspaceAutomationAllowedForWorkspace(
assertWorkspaceAutomationAllowed(workspace.untrustedSource);
}
export async function isCheckoutUntrusted(
registry: Pick<WorkspaceRegistry, "listAll">,
checkoutPath: string,
): Promise<boolean> {
const matchesCheckout = createRealpathAwarePathMatcher(checkoutPath);
const workspaces = await registry.listAll();
return workspaces.some(
(workspace) =>
Boolean(workspace.untrustedSource) &&
matchesCheckout(workspace.worktreeRoot ?? workspace.cwd),
);
}
export async function clearWorkspaceAutomationBlock(
registry: Pick<WorkspaceRegistry, "update">,
registry: Pick<WorkspaceRegistry, "update" | "listAll">,
workspaceId: string,
): Promise<boolean> {
let cleared = false;
const timestamp = new Date().toISOString();
const workspace = await registry.update(workspaceId, (record) => {
if (!record.untrustedSource) return record;
cleared = true;
const { untrustedSource: _removed, ...trusted } = record;
return { ...trusted, updatedAt: new Date().toISOString() };
return { ...trusted, updatedAt: timestamp };
});
if (!workspace) throw new Error(`Workspace not found: ${workspaceId}`);
const checkoutPath = workspace.worktreeRoot ?? workspace.cwd;
const matchesCheckout = createRealpathAwarePathMatcher(checkoutPath);
const siblings = await registry.listAll();
for (const sibling of siblings) {
if (sibling.workspaceId === workspaceId || !sibling.untrustedSource) continue;
if (!matchesCheckout(sibling.worktreeRoot ?? sibling.cwd)) continue;
await registry.update(sibling.workspaceId, (record) => {
if (!record.untrustedSource) return record;
cleared = true;
const { untrustedSource: _removed, ...trusted } = record;
return { ...trusted, updatedAt: timestamp };
});
}
return cleared;
}
@@ -88,6 +88,7 @@ const PersistedWorkspaceRecordSchema = z.object({
.transform((value) => value ?? null),
isPaseoOwnedWorktree: z.boolean().default(false),
mainRepoRoot: z.string().nullable().default(null),
worktreeManagerPluginId: z.string().min(1).optional(),
createdAt: z.string(),
updatedAt: z.string(),
archivedAt: z.string().nullable(),
@@ -698,6 +699,7 @@ export function createPersistedWorkspaceRecord(input: {
baseBranch?: string | null;
isPaseoOwnedWorktree?: boolean;
mainRepoRoot?: string | null;
worktreeManagerPluginId?: string | null;
createdAt: string;
updatedAt: string;
archivedAt?: string | null;
@@ -708,7 +710,7 @@ export function createPersistedWorkspaceRecord(input: {
untrustedSource?: UntrustedWorkspaceSource;
background?: boolean;
}): PersistedWorkspaceRecord {
const { background, ...rest } = input;
const { background, worktreeManagerPluginId, ...rest } = input;
return PersistedWorkspaceRecordSchema.parse({
...rest,
background: background ?? false,
@@ -718,6 +720,7 @@ export function createPersistedWorkspaceRecord(input: {
baseBranch: input.baseBranch ?? null,
isPaseoOwnedWorktree: input.isPaseoOwnedWorktree ?? false,
mainRepoRoot: input.mainRepoRoot ?? null,
...(worktreeManagerPluginId ? { worktreeManagerPluginId } : {}),
archivedAt: input.archivedAt ?? null,
autoArchivedChangeRequestUrl: input.autoArchivedChangeRequestUrl ?? null,
pinnedAt: input.pinnedAt ?? null,
@@ -25,9 +25,15 @@ import {
readPaseoWorktreeMetadata,
} from "../utils/worktree-metadata.js";
import { validateBeforeRequest, validateBeforeResult } from "./plugins/lifecycle/index.js";
import { UnknownBranchError } from "../utils/worktree.js";
import {
isPaseoOwnedWorktreeCwd,
listGitWorktrees,
listPaseoWorktrees,
UnknownBranchError,
} from "../utils/worktree.js";
import { createWorktreeCore as createCoreWorktree } from "./worktree-core.js";
import { isPlatform } from "../test-utils/platform.js";
import { createWithWorktrunk } from "../../../../plugin-examples/worktrunk/server/wt.js";
function createGitHubServiceStub(): ForgeService {
return {
@@ -1035,6 +1041,87 @@ describe.skipIf(isPlatform("win32"))("worktree-core POSIX-only", () => {
expect(getBranchUpstream(result.worktree.worktreePath)).toBeNull();
});
test.each([true, false])(
"checks out the fetched PR head with local branch collision=%s",
async (collision) => {
const { tempDir, repoDir, remoteDir, paseoHome } = createSameRepoGitHubPrRemoteRepo();
cleanupPaths.push(tempDir);
const branch = "daemon-shutdown-diagnostics";
const cached = execFileSync("git", ["rev-parse", "main"], {
cwd: repoDir,
encoding: "utf8",
}).trim();
if (collision) execFileSync("git", ["branch", "-f", branch, cached], { cwd: repoDir });
const expected = execFileSync(
"git",
["--git-dir", remoteDir, "rev-parse", "refs/pull/1790/head"],
{ encoding: "utf8" },
).trim();
expect(cached).not.toBe(expected);
const wt = path.join(tempDir, "wt");
writeFileSync(
wt,
`#!/bin/sh
if [ "$3" = remove ]; then
exec git -C "$2" worktree remove --force "$2-pr-checkout"
fi
repo="$2"
shift 2
branch=""
base=""
while [ "$#" -gt 0 ]; do
case "$1" in
--create) branch="$2"; shift 2 ;;
--base) base="$2"; shift 2 ;;
*) shift ;;
esac
done
git -C "$repo" worktree add --quiet -b "$branch" "$repo-pr-checkout" "$base" || exit $?
printf '{"action":"created","path":"%s","branch":"%s","created_branch":true}\\n' "$repo-pr-checkout" "$branch"
printf 'setup' > "$repo-pr-checkout/.worktrunk-setup"
`,
{ mode: 0o755 },
);
const previous = process.env.WORKTRUNK_BIN;
process.env.WORKTRUNK_BIN = wt;
try {
const result = await createCoreWorktree(
{ cwd: repoDir, action: "checkout", refName: branch, githubPrNumber: 1790, paseoHome },
{
...createCoreDeps(),
worktreeManagers: {
hasWorktreeManager: () => true,
createWorktree: async (request) => {
const managed = await createWithWorktrunk(request, new AbortController().signal);
return managed ? { pluginId: "worktrunk", path: managed.path } : null;
},
removeWorktree: async () => null,
},
},
);
expect(
execFileSync("git", ["rev-parse", "HEAD"], {
cwd: result.worktree.worktreePath,
encoding: "utf8",
}).trim(),
).toBe(expected);
expect(
execFileSync("git", ["rev-parse", `refs/heads/${branch}`], {
cwd: repoDir,
encoding: "utf8",
}).trim(),
).toBe(collision ? cached : expected);
expect(existsSync(path.join(result.worktree.worktreePath, ".worktrunk-setup"))).toBe(
!collision,
);
} finally {
if (previous === undefined) delete process.env.WORKTRUNK_BIN;
else process.env.WORKTRUNK_BIN = previous;
}
},
);
test("pushes a deduplicated same-repo GitHub PR branch to the PR head", async () => {
const { tempDir, repoDir, remoteDir, paseoHome } = createSameRepoGitHubPrRemoteRepo();
cleanupPaths.push(tempDir);
@@ -1467,6 +1554,454 @@ describe.skipIf(isPlatform("win32"))("worktree-core POSIX-only", () => {
expect(getBranchUpstream(second.worktree.worktreePath)).toBe("paseo-pr-526/main");
});
test("rejects and rolls back a managed fork PR checkout whose HEAD is behind the current PR head", async () => {
const { tempDir, repoDir, headRemoteDir, paseoHome } = createForkGitHubPrRemoteRepo();
cleanupPaths.push(tempDir);
const staleBranch = "archived-fork-pr-526";
const staleWorktreePath = path.join(tempDir, "stale-fork-pr");
git(repoDir, "branch", staleBranch, "main");
const github = {
...createGitHubServiceStub(),
getPullRequestCheckoutTarget: async () => ({
number: 526,
baseRefName: "main",
headRefName: "main",
headOwnerLogin: "therainisme",
headRepositorySshUrl: headRemoteDir,
headRepositoryUrl: headRemoteDir,
isCrossRepository: true,
}),
};
await expect(
createCoreWorktree(
{
cwd: repoDir,
worktreeSlug: "fork-pr-stale",
action: "checkout",
githubPrNumber: 526,
refName: "main",
paseoHome,
},
{
...createCoreDeps({ github }),
worktreeManagers: {
hasWorktreeManager: () => true,
createWorktree: async () => {
git(repoDir, "worktree", "add", staleWorktreePath, staleBranch);
return { pluginId: "stale-manager", path: staleWorktreePath };
},
removeWorktree: async () => null,
},
},
),
).rejects.toThrow("expected change request head");
expect(existsSync(staleWorktreePath)).toBe(false);
});
test("fails before calling the manager when the remote PR ref cannot be fetched", async () => {
const { tempDir, repoDir, headRemoteDir, paseoHome } = createForkGitHubPrRemoteRepo();
cleanupPaths.push(tempDir);
let managerCalled = false;
git(repoDir, "remote", "set-url", "origin", path.join(tempDir, "missing-remote.git"));
const github = {
...createGitHubServiceStub(),
getPullRequestCheckoutTarget: async () => ({
number: 526,
baseRefName: "main",
headRefName: "main",
headOwnerLogin: "therainisme",
headRepositorySshUrl: headRemoteDir,
headRepositoryUrl: headRemoteDir,
isCrossRepository: true,
}),
};
await expect(
createCoreWorktree(
{
cwd: repoDir,
worktreeSlug: "fork-pr-offline",
action: "checkout",
githubPrNumber: 526,
refName: "main",
paseoHome,
},
{
...createCoreDeps({ github }),
worktreeManagers: {
hasWorktreeManager: () => true,
createWorktree: async () => {
managerCalled = true;
return null;
},
removeWorktree: async () => null,
},
},
),
).rejects.toThrow("Unable to fetch change request refs");
expect(managerCalled).toBe(false);
});
test("accepts a managed fork PR checkout matching the pre-fetched headSha even after multiple mid-setup pushes", async () => {
const { tempDir, repoDir, headRemoteDir, paseoHome } = createForkGitHubPrRemoteRepo();
cleanupPaths.push(tempDir);
const baseRemoteDir = path.join(tempDir, "base.git");
const initialPrHead = git(repoDir, "ls-remote", "origin", "refs/pull/526/head").split(
/\s+/,
)[0];
const managedPath = path.join(tempDir, "mid-push-fork-pr");
const github = {
...createGitHubServiceStub(),
getPullRequestCheckoutTarget: async () => ({
number: 526,
baseRefName: "main",
headRefName: "main",
headOwnerLogin: "therainisme",
headRepositorySshUrl: headRemoteDir,
headRepositoryUrl: headRemoteDir,
isCrossRepository: true,
}),
};
const pushCommit = (message: string) => {
const headCloneDir = path.join(tempDir, "therainisme-clone");
writeFileSync(path.join(headCloneDir, "README.md"), `${message}\n`);
git(headCloneDir, "add", "README.md");
git(headCloneDir, "-c", "commit.gpgsign=false", "commit", "-m", message);
const head = git(headCloneDir, "rev-parse", "HEAD");
git(headCloneDir, "push", "origin", "main");
execFileSync("git", [`--git-dir=${baseRemoteDir}`, "fetch", headRemoteDir, "main"], {
stdio: "pipe",
});
execFileSync(
"git",
[`--git-dir=${baseRemoteDir}`, "update-ref", "refs/pull/526/head", head],
{ stdio: "pipe" },
);
};
const result = await createCoreWorktree(
{
cwd: repoDir,
worktreeSlug: "fork-pr-mid-push",
action: "checkout",
githubPrNumber: 526,
refName: "main",
paseoHome,
},
{
...createCoreDeps({ github }),
worktreeManagers: {
hasWorktreeManager: () => true,
createWorktree: async (request) => {
expect(request.headSha).toBe(initialPrHead);
// Two pushes happen while the manager creates the worktree from request.headSha.
pushCommit("mid-setup push B");
git(repoDir, "worktree", "add", "-b", "pr-526-snap", managedPath, request.headSha!);
pushCommit("mid-setup push C");
return { pluginId: "mid-push-manager", path: managedPath };
},
removeWorktree: async () => null,
},
},
);
expect(git(result.worktree.worktreePath, "rev-parse", "HEAD")).toBe(initialPrHead);
});
test("configures fork push remote on a managed Worktrunk PR checkout so Push updates the fork branch", async () => {
const { tempDir, repoDir, headRemoteDir, paseoHome } = createForkGitHubPrRemoteRepo();
cleanupPaths.push(tempDir);
const baseRemoteDir = path.join(tempDir, "base.git");
const wt = path.join(tempDir, "fake-wt-fork-push");
writeFileSync(
wt,
`#!/bin/sh
repo="$2"
shift 2
branch=""
base=""
while [ "$#" -gt 0 ]; do
case "$1" in
--create) branch="$2"; shift 2 ;;
--base) base="$2"; shift 2 ;;
*) shift ;;
esac
done
git -C "$repo" worktree add --quiet -b "$branch" "$repo-fork-managed" "$base" || exit $?
printf '{"action":"created","path":"%s","branch":"%s","created_branch":true}\\n' "$repo-fork-managed" "$branch"
`,
{ mode: 0o755 },
);
const github = {
...createGitHubServiceStub(),
getPullRequestCheckoutTarget: async () => ({
number: 526,
baseRefName: "main",
headRefName: "main",
headOwnerLogin: "therainisme",
headRepositorySshUrl: headRemoteDir,
headRepositoryUrl: headRemoteDir,
isCrossRepository: true,
}),
};
const previous = process.env.WORKTRUNK_BIN;
process.env.WORKTRUNK_BIN = wt;
try {
const result = await createCoreWorktree(
{
cwd: repoDir,
worktreeSlug: "fork-pr-managed-push",
action: "checkout",
githubPrNumber: 526,
refName: "main",
paseoHome,
},
{
...createCoreDeps({ github }),
worktreeManagers: {
hasWorktreeManager: () => true,
createWorktree: async (request) => {
const managed = await createWithWorktrunk(request, new AbortController().signal);
return managed ? { pluginId: "worktrunk", path: managed.path } : null;
},
removeWorktree: async () => null,
},
},
);
expect(result.worktree.worktreeManagerPluginId).toBe("worktrunk");
expect(result.worktree.branchName).toBe("therainisme/main");
writeFileSync(path.join(result.worktree.worktreePath, "README.md"), "pushed from wt\n");
git(result.worktree.worktreePath, "add", "README.md");
git(
result.worktree.worktreePath,
"-c",
"commit.gpgsign=false",
"commit",
"-m",
"managed fork commit",
);
const pushedSha = git(result.worktree.worktreePath, "rev-parse", "HEAD");
await pushCurrentBranch(result.worktree.worktreePath);
expect(
execFileSync("git", [`--git-dir=${headRemoteDir}`, "rev-parse", "refs/heads/main"], {
encoding: "utf8",
}).trim(),
).toBe(pushedSha);
expect(
execFileSync(
"git",
[`--git-dir=${baseRemoteDir}`, "for-each-ref", "refs/heads/therainisme/main"],
{ encoding: "utf8" },
).trim(),
).toBe("");
} finally {
if (previous === undefined) delete process.env.WORKTRUNK_BIN;
else process.env.WORKTRUNK_BIN = previous;
}
});
test("falls back to built-in Git without calling managers when Git rejects worktree list -z", async () => {
const { tempDir, repoDir, paseoHome } = createGitRepo();
cleanupPaths.push(tempDir);
const trailingSpaceWorktree = path.join(tempDir, "detached space ");
git(repoDir, "worktree", "add", "--detach", trailingSpaceWorktree, "main");
writeFileSync(path.join(trailingSpaceWorktree, "keep.txt"), "do not delete\n");
const realGit = execFileSync("which", ["git"], { encoding: "utf8" }).trim();
const shimDir = path.join(tempDir, "legacy-git-bin");
mkdirSync(shimDir, { recursive: true });
writeFileSync(
path.join(shimDir, "git"),
`#!/bin/sh
for arg in "$@"; do
if [ "$arg" = "-z" ]; then
echo 'error: unknown switch -z' >&2
exit 129
fi
done
exec "${realGit}" "$@"
`,
{ mode: 0o755 },
);
let managerCalled = false;
const previousPath = process.env.PATH;
process.env.PATH = `${shimDir}:${previousPath ?? ""}`;
try {
const result = await createCoreWorktree(
{
cwd: repoDir,
worktreeSlug: "legacy-git-fallback",
action: "branch-off",
branchName: "legacy-git-fallback",
paseoHome,
},
{
...createCoreDeps(),
worktreeManagers: {
hasWorktreeManager: () => true,
createWorktree: async () => {
managerCalled = true;
return { pluginId: "bad-manager", path: trailingSpaceWorktree };
},
removeWorktree: async () => null,
},
},
);
expect(managerCalled).toBe(false);
expect(result.worktree.branchName).toBe("legacy-git-fallback");
expect(result.worktree.worktreeManagerPluginId).toBeUndefined();
expect(readFileSync(path.join(trailingSpaceWorktree, "keep.txt"), "utf8")).toBe(
"do not delete\n",
);
} finally {
if (previousPath === undefined) delete process.env.PATH;
else process.env.PATH = previousPath;
}
});
test("protects pre-existing and discovers newly managed worktrees whose paths contain a line break", async () => {
const { tempDir, repoDir, paseoHome } = createGitRepo();
cleanupPaths.push(tempDir);
const newlineWorktree = path.join(tempDir, "manual\nworktree");
git(repoDir, "worktree", "add", "-b", "newline-branch", newlineWorktree, "main");
writeFileSync(path.join(newlineWorktree, "keep.txt"), "uncommitted\n");
await expect(
createCoreWorktree(
{
cwd: repoDir,
worktreeSlug: "newline-hijack",
action: "branch-off",
branchName: "newline-hijack",
paseoHome,
},
{
...createCoreDeps(),
worktreeManagers: {
hasWorktreeManager: () => true,
createWorktree: async () => ({
pluginId: "bad-manager",
path: newlineWorktree,
}),
removeWorktree: async () => null,
},
},
),
).rejects.toThrow("already-existing worktree");
expect(readFileSync(path.join(newlineWorktree, "keep.txt"), "utf8")).toBe("uncommitted\n");
expect(await readPaseoWorktreeMetadata(newlineWorktree)).toBeNull();
// A newly created managed worktree inside a directory containing a line break must remain
// visible to discovery and marker-based ownership checks.
const managedNewlineDir = path.join(tempDir, "parent\nbreak", "managed-wt");
mkdirSync(path.dirname(managedNewlineDir), { recursive: true });
const created = await createCoreWorktree(
{
cwd: repoDir,
worktreeSlug: "newline-managed",
action: "branch-off",
branchName: "newline-managed",
paseoHome,
},
{
...createCoreDeps(),
worktreeManagers: {
hasWorktreeManager: () => true,
createWorktree: async (request) => {
git(repoDir, "worktree", "add", "-b", request.branch, managedNewlineDir, "main");
return { pluginId: "newline-manager", path: managedNewlineDir };
},
removeWorktree: async () => null,
},
},
);
const expectedPath = realpathSync(managedNewlineDir);
expect(created.worktree.worktreePath).toBe(expectedPath);
const allGitWorktrees = await listGitWorktrees({ cwd: repoDir });
expect(allGitWorktrees.map((entry) => entry.path)).toContain(expectedPath);
const paseoWorktrees = await listPaseoWorktrees({ cwd: repoDir, paseoHome });
expect(paseoWorktrees.map((entry) => entry.path)).toContain(expectedPath);
const ownership = await isPaseoOwnedWorktreeCwd(expectedPath, { paseoHome });
expect(ownership.allowed).toBe(true);
expect(ownership.worktreePath).toBe(expectedPath);
});
test("declines a Worktrunk fork PR checkout when the archived local branch already exists so Git checks out the latest PR head", async () => {
const { tempDir, repoDir, headRemoteDir, paseoHome } = createForkGitHubPrRemoteRepo();
cleanupPaths.push(tempDir);
const archivedBranch = "therainisme/main";
const archivedTip = git(repoDir, "rev-parse", "main");
git(repoDir, "branch", archivedBranch, archivedTip);
const latestPrHead = git(repoDir, "ls-remote", "origin", "refs/pull/526/head").split(
/\s+/,
)[0];
expect(latestPrHead).not.toBe(archivedTip);
const wt = path.join(tempDir, "fake-wt-fork-pr");
writeFileSync(
wt,
`#!/bin/sh
echo "wt should not be invoked when local branch already exists" >&2
exit 1
`,
{ mode: 0o755 },
);
const github = {
...createGitHubServiceStub(),
getPullRequestCheckoutTarget: async () => ({
number: 526,
baseRefName: "main",
headRefName: "main",
headOwnerLogin: "therainisme",
headRepositorySshUrl: headRemoteDir,
headRepositoryUrl: headRemoteDir,
isCrossRepository: true,
}),
};
const previous = process.env.WORKTRUNK_BIN;
process.env.WORKTRUNK_BIN = wt;
try {
const result = await createCoreWorktree(
{
cwd: repoDir,
worktreeSlug: "fork-pr-reopen",
action: "checkout",
githubPrNumber: 526,
refName: "main",
paseoHome,
},
{
...createCoreDeps({ github }),
worktreeManagers: {
hasWorktreeManager: () => true,
createWorktree: async (request) => {
expect(request.untrusted).toBe(true);
expect(request.headSha).toBe(latestPrHead);
const managed = await createWithWorktrunk(request, new AbortController().signal);
return managed ? { pluginId: "worktrunk", path: managed.path } : null;
},
removeWorktree: async () => null,
},
},
);
expect(git(result.worktree.worktreePath, "rev-parse", "HEAD")).toBe(latestPrHead);
expect(git(repoDir, "rev-parse", `refs/heads/${archivedBranch}`)).toBe(archivedTip);
} finally {
if (previous === undefined) delete process.env.WORKTRUNK_BIN;
else process.env.WORKTRUNK_BIN = previous;
}
});
test("throws a typed error for an unknown checkout branch", async () => {
const { tempDir, repoDir, paseoHome } = createGitRepo();
cleanupPaths.push(tempDir);
@@ -1648,9 +2183,26 @@ describe.skipIf(isPlatform("win32"))("worktree-core POSIX-only", () => {
branchName: "follow-up",
paseoHome,
},
createCoreDeps({ github }),
{
...createCoreDeps({ github }),
worktreeManagers: {
hasWorktreeManager: () => true,
async createWorktree(request) {
expect(request.untrusted).toBe(true);
return null;
},
async removeWorktree() {
return null;
},
},
},
);
expect(result.untrustedSource).toMatchObject({
kind: "change_request",
forge: "github",
number: 526,
});
const readme = readFileSync(path.join(result.worktree.worktreePath, "README.md"), "utf8");
// The fork's branch is not in this repository, so a pull request from the new branch goes
// into the fork pull request's base, compared as the remote has it now.
+73 -1
View File
@@ -1,12 +1,19 @@
import type { PluginWorktreeCreateRequest } from "@getpaseo/plugin/server";
import type {
PluginWorktreeCreateInput,
PluginWorktreeCreateRequest,
} from "@getpaseo/plugin/server";
import type { PluginLifecycle } from "./plugins/lifecycle/index.js";
import type { PluginWorktreeManagerRuntime } from "./plugins/runtime.js";
import { createNameId } from "mnemonic-id";
import type { ForgeService } from "../services/forge-service.js";
import {
createWorktree,
fetchFirstAvailableRef,
prepareWorktreeBranchOff,
type PreparedWorktreeBranchOff,
resolveDefaultWorktreePath,
runPluginWorktreeManagerCheckout,
slugify,
validateBranchSlug,
type CreatedWorktree,
@@ -16,11 +23,14 @@ import {
type ResolveWorktreeCreationIntentInput,
UnsupportedForgeCheckoutTargetError,
type WorktreeCreationIntent,
worktreeUntrustedSource,
} from "./resolve-worktree-creation-intent.js";
import type { ChangeRequestCheckoutSource, FirstAgentContext } from "@getpaseo/protocol/messages";
import type { WorkspaceGitService } from "./workspace-git-service.js";
import { runGitCommand, runWithGitCommandPriority } from "../utils/run-git-command.js";
import type { UntrustedWorkspaceSource } from "./workspace-automation-gate.js";
export interface CreateWorktreeCoreInput {
cwd: string;
worktreeSlug?: string;
@@ -36,6 +46,10 @@ export interface CreateWorktreeCoreInput {
export interface CreateWorktreeCoreDeps {
lifecycle?: Pick<PluginLifecycle, "before">;
worktreeManagers?: Pick<
PluginWorktreeManagerRuntime,
"hasWorktreeManager" | "createWorktree" | "removeWorktree"
>;
github: ForgeService;
workspaceGitService?: Pick<
WorkspaceGitService,
@@ -47,6 +61,7 @@ export interface CreateWorktreeCoreDeps {
export interface CreateWorktreeCoreResult {
worktree: CreatedWorktree;
intent: WorktreeCreationIntent;
untrustedSource?: UntrustedWorkspaceSource;
repoRoot: string;
created: boolean;
}
@@ -146,8 +161,28 @@ async function createWorktreeCoreWithPriority(
const transformed = deps.lifecycle
? await deps.lifecycle.before("worktree.create.before", request)
: request;
const originalUntrustedSource = worktreeUntrustedSource(intent);
normalizedSlug = validateWorktreeSlug(transformed.slug);
intent = creationIntentFromRequest(transformed, intent);
const untrustedSource = originalUntrustedSource ?? worktreeUntrustedSource(intent);
const { worktree: managedWorktree, preparedBranchOff } = await tryCreateWithWorktreeManager({
repoRoot,
transformed,
intent,
untrusted: Boolean(untrustedSource),
input,
deps,
});
if (managedWorktree) {
return {
worktree: managedWorktree,
intent,
untrustedSource,
repoRoot,
created: true,
};
}
return {
worktree: await createWorktree({
@@ -155,15 +190,51 @@ async function createWorktreeCoreWithPriority(
worktreeSlug: normalizedSlug,
worktreePath: transformed.path,
source: intent,
preparedBranchOff,
paseoHome: input.paseoHome,
worktreesRoot: input.worktreesRoot,
}),
intent,
untrustedSource,
repoRoot,
created: true,
};
}
async function tryCreateWithWorktreeManager(options: {
repoRoot: string;
transformed: PluginWorktreeCreateRequest;
intent: WorktreeCreationIntent;
untrusted: boolean;
input: Pick<CreateWorktreeCoreInput, "paseoHome" | "worktreesRoot">;
deps: Pick<CreateWorktreeCoreDeps, "worktreeManagers">;
}): Promise<{ worktree: CreatedWorktree | null; preparedBranchOff?: PreparedWorktreeBranchOff }> {
const { repoRoot, transformed, intent, untrusted, input, deps } = options;
let preparedBranchOff: PreparedWorktreeBranchOff | undefined;
const worktree = await runPluginWorktreeManagerCheckout({
cwd: repoRoot,
source: intent,
operation: "create",
untrusted,
paseoHome: input.paseoHome,
worktreesBaseRoot: input.worktreesRoot,
worktreeManagers: deps.worktreeManagers,
run: async ({ changeRequestHeadSha }) => {
let request: PluginWorktreeCreateInput = {
...transformed,
untrusted,
...(changeRequestHeadSha ? { headSha: changeRequestHeadSha } : {}),
};
if (request.kind === "branch-off" && intent.kind === "branch-off") {
preparedBranchOff = await prepareWorktreeBranchOff(repoRoot, intent);
request = { ...request, baseRef: preparedBranchOff.baseRef };
}
return deps.worktreeManagers!.createWorktree(request);
},
});
return { worktree, preparedBranchOff };
}
function describeCreationRequest(
intent: WorktreeCreationIntent,
placement: Pick<PluginWorktreeCreateRequest, "repoRoot" | "sourceCheckout" | "slug" | "path">,
@@ -174,6 +245,7 @@ function describeCreationRequest(
kind: intent.kind,
branch: intent.branchName,
baseRef: intent.baseBranch,
...(intent.startPoint ? { startPoint: intent.startPoint } : {}),
};
if (intent.kind === "checkout-branch")
return { ...placement, kind: intent.kind, branch: intent.branchName };
+21 -1
View File
@@ -78,7 +78,7 @@ export function isPathInsideRoot(root: string, candidate: string): boolean {
}
export function normalizePathForIdentity(value: string): string {
const canonicalPath = resolveRealpathVariants(value)[0] ?? value;
const canonicalPath = resolveNearestExistingAncestorRealpath(value);
return normalizePathForComparison(canonicalPath, looksLikeDefiniteWindowsPath(canonicalPath));
}
@@ -150,6 +150,26 @@ function resolveRealpathVariants(value: string): string[] {
return variants;
}
function resolveNearestExistingAncestorRealpath(value: string): string {
if (process.platform !== "win32" && looksLikeDefiniteWindowsPath(value)) {
return value;
}
const tail: string[] = [];
let current = value;
while (true) {
const resolved = resolveRealpathVariants(current)[0];
if (resolved) {
return tail.length === 0 ? resolved : nodePath.join(resolved, ...tail.toReversed());
}
const parent = nodePath.dirname(current);
if (parent === current) {
return value;
}
tail.push(nodePath.basename(current));
current = parent;
}
}
function shouldCompareAsWindows(left: string, right: string): boolean {
return looksLikeDefiniteWindowsPath(left) || looksLikeDefiniteWindowsPath(right);
}
@@ -22,6 +22,7 @@ const PaseoWorktreeMetadataV1Schema = z.object({
baseRefName: z.string().min(1),
baseRef: z.string().min(1).optional(),
changeRequestLookupTarget: ChangeRequestLookupTargetSchema.optional(),
worktreeManagerPluginId: z.string().min(1).optional(),
});
const PaseoWorktreeMetadataV2Schema = z.object({
@@ -29,6 +30,7 @@ const PaseoWorktreeMetadataV2Schema = z.object({
baseRefName: z.string().min(1),
baseRef: z.string().min(1).optional(),
changeRequestLookupTarget: ChangeRequestLookupTargetSchema.optional(),
worktreeManagerPluginId: z.string().min(1).optional(),
firstAgentBranchAutoName: z
.discriminatedUnion("status", [
z.object({
@@ -227,6 +229,7 @@ export async function writePaseoWorktreeMetadata(
baseRefName: string;
baseRef?: string;
changeRequestLookupTarget?: PaseoWorktreeChangeRequestHint;
worktreeManagerPluginId?: string;
},
): Promise<void> {
return mutateMetadata(worktreeRoot, async (root) => {
@@ -244,6 +247,9 @@ export async function writePaseoWorktreeMetadata(
...(options.changeRequestLookupTarget
? { changeRequestLookupTarget: options.changeRequestLookupTarget }
: {}),
...(options.worktreeManagerPluginId
? { worktreeManagerPluginId: options.worktreeManagerPluginId }
: {}),
};
await writePaseoWorktreeMetadataFile(root, metadata);
});
+11 -11
View File
@@ -47,24 +47,24 @@ async function pathExists(path: string): Promise<boolean> {
export async function validateWorktreePath(options: {
candidate: string;
repoPath: string;
/** The worktree manager already created the destination, so it is expected to exist. */
allowExistingPath?: boolean;
}): Promise<string> {
const { candidate, repoPath } = options;
const { candidate, repoPath, allowExistingPath = false } = options;
if (!isAbsolute(candidate)) {
throw new Error(
`Worktree hook returned a relative path '${candidate}'; it must be an absolute path`,
);
throw new Error(`The returned path is relative: ${candidate}. Use an absolute path.`);
}
const normalized = await normalizeCandidatePath(candidate);
const normalizedRepoPath = await normalizeAbsolute(repoPath);
if (normalized === parse(normalized).root) {
throw new Error("Worktree hook returned the filesystem root, which is not allowed");
throw new Error("The filesystem root cannot be a worktree destination");
}
if (normalized === (await normalizeAbsolute(homedir()))) {
throw new Error("Worktree hook returned the user's home directory, which is not allowed");
throw new Error("The user's home directory cannot be a worktree destination");
}
if (normalized === normalizedRepoPath) {
throw new Error("Worktree hook returned the repository root itself, which is not allowed");
throw new Error("The repository root cannot be a worktree destination");
}
if (
[normalized, resolve(candidate)].some((path) =>
@@ -73,15 +73,15 @@ export async function validateWorktreePath(options: {
.some((part) => (process.platform === "win32" ? part.toLowerCase() : part) === ".git"),
)
) {
throw new Error(`Worktree hook returned a path inside a .git directory: ${normalized}`);
throw new Error(`The returned path is inside a .git directory: ${normalized}`);
}
const relativeToCandidate = getRelativePathInsideRoot(normalized, normalizedRepoPath);
if (relativeToCandidate !== null && relativeToCandidate !== "") {
throw new Error(`Worktree hook returned an ancestor of the repository: ${normalized}`);
throw new Error(`The returned path is an ancestor of the repository: ${normalized}`);
}
if ((await pathExists(normalized)) || (await pathExists(candidate))) {
if (!allowExistingPath && ((await pathExists(normalized)) || (await pathExists(candidate)))) {
throw new Error(
`Worktree hook returned a path that already exists: ${normalized}. Paseo creates the returned path.`,
`The returned path already exists: ${normalized}. Paseo creates the returned path.`,
);
}
return normalized;
File diff suppressed because it is too large Load Diff
+57
View File
@@ -109,6 +109,63 @@ test("switches language on the same page, keeping the query and then every link"
await expect(page.locator("html")).toHaveAttribute("lang", "en");
});
async function openHubDoc(page: Page, prefix: string, slug: string, heading: string) {
await page.goto(`${prefix}/docs/hub/${slug}`);
await expect(page.getByRole("heading", { name: heading, level: 1 })).toBeVisible();
}
async function expectHubDocRedirect(
page: Page,
prefix: string,
legacySlug: string,
slug: string,
heading: string,
) {
await page.goto(`${prefix}/docs/hub/${legacySlug}`);
await expect(page).toHaveURL(`${prefix}/docs/hub/${slug}`);
await expect(page.getByRole("heading", { name: heading, level: 1 })).toBeVisible();
}
for (const { locale, prefix, linear, linearApp, webhooks, triggers, reference } of [
{
locale: "English",
prefix: "",
linear: "Linear triggers",
linearApp: "Linear for Hub",
webhooks: "Inbound webhooks",
triggers: "Triggers",
reference: "Trigger YAML reference",
},
{
locale: "Simplified Chinese",
prefix: "/zh-CN",
linear: "Linear 触发器",
linearApp: "为 Hub 配置 Linear",
webhooks: "入站 webhook",
triggers: "触发器",
reference: "触发器 YAML 参考",
},
]) {
test(`opens ${locale} Hub guides and redirects legacy bookmarks`, async ({ page }) => {
await test.step("opens direct links to the new guides", async () => {
await openHubDoc(page, prefix, "triggers/linear", linear);
await openHubDoc(page, prefix, "self-hosting/linear-app", linearApp);
await openHubDoc(page, prefix, "triggers/webhooks", webhooks);
});
await test.step("redirects legacy guides within the same language", async () => {
await expectHubDocRedirect(page, prefix, "workflows", "triggers", triggers);
await expectHubDocRedirect(
page,
prefix,
"configuration/hub-yml",
"configuration/reference",
reference,
);
});
});
}
test("shows the language as an abbreviation and lists every language by name", async ({ page }) => {
await page.goto("/docs/cli#running-agents");
const button = languageButton(page);

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