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
efb65d7b82 Archive the active workspace from a collapsed sidebar (#10356)
* Archive the active workspace from the shortcut while its sidebar row is collapsed

The workspace.archive handler was registered by each sidebar row and only
enabled on the selected row, so a collapsed project or status group left no
handler and the shortcut did nothing. Move it to one always-mounted handler
keyed on the active route selection, as #2299 did for the pin shortcut.

Fixes #10246

* fix(app): keep archive shortcuts available during another archive

A worktree teardown keeps the previous archive request pending after
the user opens another workspace. Read the active target from the
workspace list so the first archive only hides its own workspace.

Co-authored-by: hiennd <74246327+neihyud@users.noreply.github.com>

* fix(app): share pending archives by workspace

Hold an archive attempt from its checkout check through the daemon
reply. The row button and shortcut now share that attempt for the
same workspace, and another workspace can still archive while it runs.

* fix(app): preserve archive after undo and theme changes

The archive guard protects a workspace through confirmation and
dispatch. The optimistic workspace state takes over when dispatch
hides the workspace, so Undo can restore it for another archive.

Keep the shortcut host outside the appearance boundary so its
pending redirect keeps reading the active workspace after a theme
change.

* test(app): verify theme changes during workspace archive

Use the platform modifier for the theme shortcut and wait for the sidebar to remount before opening the next workspace.

---------

Co-authored-by: hiennd <hiennd@aidia.vn>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: hiennd <74246327+neihyud@users.noreply.github.com>
2026-11-21 01:50:39 +00:00
27c126d352 Keep the Android browser keyboard closed when you swipe a terminal (#10225)
* fix(terminal): restore mobile scrolling and touch keyboard focus

* fix(app): keep a touch drag from refocusing the browser terminal

Builds on the contributor commit for the Android browser keyboard.
A touch drag now keeps the dismissed keyboard closed, and a tap
still opens it.

- Keep calling onFocus on every pointer-down, so a touch drag still
  marks the terminal as focused and claims its size as before. Only
  the input focus waits for a tap.
- Move the test tap into a helper.
- Leave the native fullscreen scrolling change, its tests, the
  inertial gesture check, and the QA video out of this branch. They
  belong to #7762.

Refs #9481

Co-authored-by: Tony <liutuo@outlook.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(app): keep an open keyboard open when you swipe the browser terminal

A touch drag blurred the terminal input to stop Android from reopening a
keyboard that Back had hidden. It also closed a keyboard that was open,
so scrolling while typing needed a new tap. Blur only when the visual
viewport shows no software keyboard.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Preserve the Android terminal keyboard state on swipe

---------

Co-authored-by: Tony <liutuo@outlook.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 17:54:24 +00:00
Mohamed Boudra 7e3826ad6c Forecast when provider quotas will run out (#10289)
* feat(usage): forecast quota remaining at reset

Show whether current usage will last until reset and how much quota is likely to remain. Anchor estimates to the last successful reading so the countdown does not move the projected runout between refreshes.

* fix(usage): keep quota forecasts tied to their readings

A cached provider observation must keep its own timestamp across refreshes. Hide forecasts after a failed request until a newer reading takes its place, and keep reset text within its column on narrow screens.

* fix(usage): hide stale forecasts after Refresh all fails

Store refresh failures with the cached readings they affect so card and list requests use the same forecast rule. Reports that arrive during a refresh retain their forecasts.

* test(usage): cover a timed-out Refresh all and retry

* test(usage): timestamp the expired-login refresh fixture

The expired-login result represents a new attempt. Give it a fresh timestamp so the UI can accept it without relaxing the guard against older reports.

* fix(usage): keep refresh errors visible alongside quota

Store request feedback with its refresh control. A newer report can restore the forecast while an overlapping failed request still needs to surface its error.
2026-11-20 22:51:32 +07:00
paseo-bot[bot] c853f98b90 fix(server): wait for restored checkout status on concurrent reads (#10304)
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-20 12:45:08 +00:00
Mohamed Boudra c3da87ee4c Support Gitea, Forgejo, and Codeberg change request watches (#10280)
* feat(server): add Gitea, Forgejo, and Codeberg support for change request watches

Implement the Gitea-family ChangeRequestSource using cwd-free tea login list and tea api --login -i requests, inspecting HTTP status codes directly on stdout/stderr rather than treating exit code 0 alone as success.

Reuse the shared per-host bounded poller for concurrency limits, 429 Retry-After pauses, and exponential backoff. Combine commit statuses and Actions tasks (including approval-held runs via need_approval and cross-repo waiting shadows) with mid-pagination headSha validation, and paginate comments, reviews, and inline review comments with bounded fan-out and quiet-poll caching.

* fix(server): address review findings on Gitea watch pagination, check sharing, and runs fetch

- Read /pulls/:index/reviews/:id/comments in a single request instead of a page loop because Gitea ignores page/limit on that endpoint and omits X-Total-Count/Link headers.
- Paginate /commits/:sha/status using the X-Total-Count response header instead of body total_count (which Gitea sets to the page length).
- Extract shared pure Gitea check schemas, shadow detection, rerun selection, and tea login matching into gitea-checks.ts imported by both gitea-service.ts and gitea-change-requests.ts.
- Remove the redundant /actions/runs fetch from the watch adapter because watch checks carry no action_required trait and approval-held tasks/pending shadows already map to pending.

* fix(server): preserve Gitea watch identity, checks, and backoff

* fix(server): route Gitea watches by base URL and retain complete updates

* fix(server): reconcile Gitea checks by job and refresh watch logins

* fix(server): validate Gitea and Forgejo Actions job responses

* fix(server): classify canceled native Actions statuses as neutral

* fix(server): drain failed Gitea polls before releasing host slots

* fix(server): let admitted Gitea polls finish with low quota

* fix(server): normalize Gitea watch URLs and refresh inline replies

* test(server): cover late Gitea rate limits across recovery windows
2026-11-20 18:41:41 +07:00
Mohamed Boudra 2298effb0b Support multi-forge change request watches and GitLab merge request watches (#10279)
* feat(server): add multi-forge routing and GitLab support for change request watches

Route change request watch URLs host-first through ForgeResolver (cloud host match plus cached async CLI auth probe) before delegating path canonicalization and polling to the matched forge adapter, while sharing adapter instances with workspace reads.

Persist the resolved forge id on saved watch records (defaulting legacy records to github) so daemon restarts recover active watches directly by forge without probing hosts during outages, and keep unknown-forge records intact rather than aborting boot.

Add the GitLab ChangeRequestSource using cwd-free glab api --hostname calls, bounded per-host polling and rate-limit/error backoff, head-pipeline job/bridge checks with mid-pagination headSha verification, discussions/comments, and observable GitLab approval transition updates without manufacturing a GitHub reviewDecision.

* fix(server): address review findings on GitLab watch rate limits, approvals, and legacy recovery

- Decide rate limits from HTTP status codes only on parsed glab responses so MR titles, comments, or IIDs mentioning 429 or rate limit never trip false host pauses.
- Remove the duplicate in-memory approval baseline and counter in favor of immutable GitLab approval system notes enriched with /approvals counts only on new notes, keeping seenActivity as the single persisted owner.
- Infer forge from URL shape when a persisted record omits forge so GitLab watches survive an older-daemon downgrade/upgrade cycle without probing.

* fix(server): handle GitLab locked merge state and custom-port glab host keys

- Pass the bare hostname to glab auth status and glab api --hostname (matching ForgeResolver.resolveHost and glab's api_host config) while preserving host:port in the canonical URL and description.
- Map GitLab's transient locked merge-in-progress state to open so watches keep polling until merged or closed.

* fix(server): preserve accurate GitLab watch updates and offline unsubscribe

* fix(server): validate GitLab watch project addresses and retain approval updates

* fix(server): honor GitLab watch profiles written by glab login

* fix(server): refresh authenticated GitLab watch profiles

* fix(server): keep GitLab poll access checks on merge requests

* fix(server): use GitLab MR access and enforce host pauses on every request

* fix(server): let admitted polls finish and retry denied GitLab reads

* fix(server): give quota-limited change request watches a turn

* fix(server): recover from shared forge quotas one poll at a time

* fix(server): rotate watches after failed quota recovery attempts
2026-11-20 18:05:10 +07:00
Mohamed Boudra a7fed94e51 Keep the Mac Explorer toggle in place (#10297)
Keep one titlebar toggle mounted while Explorer opens and closes. Reserve its footprint in the active rail so native pointer clicks and the header tab sequence work, and verify clearance from the Windows window controls.
2026-11-20 17:42:38 +07:00
252 changed files with 24773 additions and 5355 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",
@@ -0,0 +1,149 @@
import { test, expect, type Page } from "../support/fixtures";
import { gotoAppShell } from "../support/helpers/app";
import { seedWorkspace, type SeededWorkspace } from "../support/helpers/seed-client";
import { selectSidebarStatusGrouping } from "../support/helpers/sidebar";
import {
createGatedTeardown,
pressArchiveShortcut,
workspaceRow,
} from "../support/helpers/workspace-archive-undo";
// The archive shortcut used to be registered by the sidebar row itself, so it did nothing whenever
// the row was unmounted — a collapsed project section being the common case. It now lives in a
// single always-mounted handler keyed on the active route selection, like the pin shortcut.
// Returns the workspace route, so the test can assert archiving redirected off it.
async function openWorkspace(page: Page, workspaceId: string): Promise<string> {
const row = workspaceRow(page, workspaceId);
await expect(row).toBeVisible({ timeout: 30_000 });
await row.click();
await expect(page).toHaveURL((url) => url.pathname.endsWith(`/workspace/${workspaceId}`), {
timeout: 30_000,
});
return page.url();
}
async function collapseProjectSection(page: Page, project: SeededWorkspace): Promise<void> {
const header = page
.locator('[data-testid^="sidebar-project-row-"]')
.filter({ hasText: project.projectDisplayName });
await expect(header).toHaveCount(1, { timeout: 30_000 });
await header.click();
await expect(workspaceRow(page, project.workspaceId)).toHaveCount(0, { timeout: 10_000 });
}
async function collapseStatusGroupContaining(page: Page, workspaceId: string): Promise<void> {
const rows = page
.locator('[data-testid^="sidebar-status-group-rows-"]')
.filter({ has: workspaceRow(page, workspaceId) });
await expect(rows).toHaveCount(1, { timeout: 30_000 });
const rowsTestId = await rows.getAttribute("data-testid");
const bucket = rowsTestId?.replace("sidebar-status-group-rows-", "");
expect(bucket).toBeTruthy();
await page.getByTestId(`sidebar-status-group-${bucket}`).click();
await expect(workspaceRow(page, workspaceId)).toHaveCount(0, { timeout: 10_000 });
}
async function expectArchived(page: Page, workspace: SeededWorkspace, workspaceUrl: string) {
await expect(page).not.toHaveURL(workspaceUrl);
await expect
.poll(async () => {
const { entries } = await workspace.client.fetchWorkspaces();
return entries.some((entry) => entry.id === workspace.workspaceId);
})
.toBe(false);
}
test.describe("Archive workspace shortcut", () => {
test("archives the active workspace while its row is rendered", async ({ page }) => {
const workspace = await seedWorkspace({ repoPrefix: "archive-shortcut-expanded-" });
try {
await gotoAppShell(page);
const workspaceUrl = await openWorkspace(page, workspace.workspaceId);
await pressArchiveShortcut(page);
await expectArchived(page, workspace, workspaceUrl);
} finally {
await workspace.cleanup();
}
});
test("archives the active workspace while its project section is collapsed", async ({ page }) => {
const workspace = await seedWorkspace({ repoPrefix: "archive-shortcut-collapsed-" });
try {
await gotoAppShell(page);
const workspaceUrl = await openWorkspace(page, workspace.workspaceId);
await collapseProjectSection(page, workspace);
await pressArchiveShortcut(page);
await expectArchived(page, workspace, workspaceUrl);
} finally {
await workspace.cleanup();
}
});
test("archives the active workspace while its status group is collapsed", async ({ page }) => {
const workspace = await seedWorkspace({ repoPrefix: "archive-shortcut-status-" });
try {
await gotoAppShell(page);
const workspaceUrl = await openWorkspace(page, workspace.workspaceId);
await selectSidebarStatusGrouping(page);
await expect(page.getByTestId("sidebar-status-list-scroll")).toBeVisible({
timeout: 10_000,
});
await collapseStatusGroupContaining(page, workspace.workspaceId);
await pressArchiveShortcut(page);
await expectArchived(page, workspace, workspaceUrl);
} finally {
await workspace.cleanup();
}
});
test("archives a different workspace while the first worktree is still tearing down", async ({
page,
}) => {
const teardown = createGatedTeardown();
const project = await seedWorkspace({
repoPrefix: "archive-shortcut-teardown-",
repo: { paseoConfig: teardown.paseoConfig },
});
const next = await seedWorkspace({ repoPrefix: "archive-shortcut-next-" });
try {
const { workspace: worktree, error } = await project.client.createWorkspace({
source: {
kind: "worktree",
cwd: project.repoPath,
worktreeSlug: "archive-shortcut-teardown",
},
});
if (!worktree) throw new Error(error ?? "Could not seed the worktree");
await gotoAppShell(page);
await test.step("start the first archive and wait for its teardown", async () => {
await openWorkspace(page, worktree.id);
await pressArchiveShortcut(page);
await teardown.expectStarted();
});
await test.step("archive the second workspace before the first archive finishes", async () => {
const workspaceUrl = await openWorkspace(page, next.workspaceId);
await pressArchiveShortcut(page);
await expectArchived(page, next, workspaceUrl);
});
} finally {
teardown.release();
await project.cleanup();
await next.cleanup();
}
});
});
@@ -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 &&
@@ -503,6 +503,34 @@ test.describe("terminal history with a finger", () => {
await expectMouseWheelScrollsHistory(page);
});
test("finger scrolling leaves terminal input unfocused until a tap", async ({ page }) => {
await openPhoneTerminalHistory(page);
await blurTerminalInput(page);
await expectSingleFingerScroll(page, 24);
await expect(input(page)).not.toBeFocused();
await expectSingleFingerScroll(page, 1);
await expect(input(page)).not.toBeFocused();
await tapTerminalScreen(page);
await expect(input(page)).toBeFocused();
});
test("finger scrolling keeps a floating keyboard's input focused", async ({ page }) => {
await openPhoneTerminalHistory(page);
await tapTerminalScreen(page);
await expect(input(page)).toBeFocused();
// A floating keyboard leaves the visual viewport unchanged.
await expectSingleFingerScroll(page, 24);
await expect(input(page)).toBeFocused();
await expect(input(page)).toHaveAttribute("virtualkeyboardpolicy", "manual");
// Android Back also leaves the input focused. A tap restores automatic keyboard opening.
await tapTerminalScreen(page);
await expect(input(page)).not.toHaveAttribute("virtualkeyboardpolicy");
});
for (const mode of ["alternate", "mouse"] as const) {
test(`preserves finger navigation in ${mode} input mode`, async ({ page }) => {
await openPhoneInputCapture(page, mode);
@@ -531,6 +559,26 @@ async function openPhoneTerminalHistory(page: Page) {
});
await openPhoneTerminal(page);
await expect.poll(() => getTerminalBufferText(page)).toContain("HISTORY_150");
await expect
.poll(() => page.evaluate(() => window.__paseoTerminal!.buffer.active.baseY))
.toBeGreaterThan(0);
await page.evaluate(() => window.__paseoTerminal!.scrollToBottom());
await expect.poll(() => viewport(page)).toBeGreaterThan(0);
}
function terminalScreen(page: Page) {
return page.getByTestId("terminal-surface").filter({ visible: true }).locator(".xterm-screen");
}
async function tapTerminalScreen(page: Page) {
const box = await terminalScreen(page).boundingBox();
expect(box).not.toBeNull();
await page.touchscreen.tap(box!.x + box!.width / 2, box!.y + box!.height / 3);
}
async function blurTerminalInput(page: Page) {
await input(page).evaluate((element) => element.blur());
await expect(input(page)).not.toBeFocused();
}
async function openPhoneInputCapture(page: Page, mode: "alternate" | "mouse") {
@@ -570,6 +618,20 @@ async function openPhoneTerminal(page: Page) {
await page.getByTestId(`sidebar-workspace-row-${getServerId()}:${harness.workspaceId}`).click();
await expect(page.getByRole("textbox", { name: "Terminal input" })).toBeVisible();
await expect(page.getByTestId("terminal-surface").filter({ visible: true })).toBeVisible();
// The terminal stays mounted while the sidebar's closing backdrop still intercepts input.
await expect
.poll(() =>
page
.getByTestId("terminal-surface")
.filter({ visible: true })
.evaluate((root) => {
const box = root.querySelector(".xterm-screen")!.getBoundingClientRect();
return root.contains(
document.elementFromPoint(box.x + box.width / 2, box.y + box.height / 3),
);
}),
)
.toBe(true);
}
async function expectMouseWheelScrollsHistory(page: Page) {
+103 -1
View File
@@ -2,13 +2,14 @@ import { tmpdir } from "node:os";
import { randomUUID } from "node:crypto";
import path from "node:path";
import type { Page } from "@playwright/test";
import type { UsageReportEntry } from "@getpaseo/protocol/messages";
import type { UsageReport, UsageReportEntry } from "@getpaseo/protocol/messages";
import { expect, test } from "../support/fixtures";
import { gotoAppShell, openSettings } from "../support/helpers/app";
import { addConnectedHostAndReload } from "../support/helpers/hosts";
import { startIsolatedHostDaemon } from "../support/helpers/isolated-host-daemon";
import { openSettingsSection } from "../support/helpers/settings";
import { gate } from "../support/helpers/context-window";
import { installDaemonWebSocketGate } from "../support/helpers/daemon-websocket-gate";
import { getServerId } from "../support/helpers/server-id";
import { seedSidebarFooterPreferences } from "../support/helpers/sidebar-nav-settings";
import {
@@ -45,6 +46,7 @@ import {
refreshAllUsage,
togglePin,
usageItem,
usageModal,
} from "../support/helpers/usage-sidebar-item";
const emptyHome = path.join(tmpdir(), `paseo-usage-empty-${randomUUID()}`);
@@ -865,6 +867,106 @@ test("open usage clocks advance without refreshing or reopening", async ({ page
}
});
test("Refresh all keeps quota visible and restores the forecast after a timeout", async ({
page,
}) => {
const reading = new Date();
const login = await installLoginUsage(usageReading(reading, 40));
try {
const transport = await installDaemonWebSocketGate(page);
await openCompactUsageWithClock(page, reading);
await expectQuota(page, "40% used", /runs out in /);
await timeOutUsageRefresh(page, transport);
await expectQuota(page, "40% used", null);
await expectUsageRefreshError(page).toBeVisible();
await login.setReport(usageReading(reading, 10));
transport.releaseHeldClientRequest();
await refreshAllUsage(page);
await expectQuota(page, "10% used", "~50% left at reset");
await expectUsageRefreshError(page).toBeHidden();
} finally {
await login.cleanup();
}
});
test("a card refresh timeout is visible alongside a newer quota forecast", async ({ page }) => {
const reading = new Date();
const login = await installLoginUsage(usageReading(reading, 40));
try {
const transport = await installDaemonWebSocketGate(page);
await openCompactUsageWithClock(page, reading);
await expectQuota(page, "40% used", /runs out in /);
await delayCardRefreshResponse(page, transport);
await login.setReport(usageReading(reading, 10));
await refreshAllUsage(page);
await expectQuota(page, "10% used", "~50% left at reset");
await advanceUsageClock(page, 61_000);
await expectUsageRefreshError(page).toBeVisible();
await expectQuota(page, "10% used", "~50% left at reset");
} finally {
await login.cleanup();
}
});
function expectUsageRefreshError(page: Page) {
return expect(usageModal(page).getByText("Unable to refresh usage", { exact: true }));
}
async function delayCardRefreshResponse(
page: Page,
transport: Awaited<ReturnType<typeof installDaemonWebSocketGate>>,
) {
await expect(page.getByRole("button", { name: "Refresh all", exact: true })).toBeEnabled();
transport.holdNextServerMessage("usage.list_reports.response");
await refreshLoginUsage(page);
await transport.waitForHeldServerMessage("usage.list_reports.response");
}
function usageReading(observed: Date, usedPct: number): UsageReport {
return {
status: "available",
observedAt: observed.toISOString(),
windows: [
{
id: "session",
label: "Session",
usedPct,
durationSeconds: 18_000,
resetsAt: new Date(observed.getTime() + 4 * 3_600_000).toISOString(),
},
],
};
}
async function expectQuota(page: Page, amount: string, forecast: string | RegExp | null) {
const usage = usageModal(page);
await expect(usage.getByText(amount, { exact: true })).toBeVisible();
await expect(usage.getByText(/^resets in /)).toBeVisible();
if (forecast === null) {
await expect(usage.getByText(/^runs out in /)).toBeHidden();
return;
}
await expect(usage.getByText(forecast)).toBeVisible();
}
async function timeOutUsageRefresh(
page: Page,
transport: Awaited<ReturnType<typeof installDaemonWebSocketGate>>,
) {
const refresh = page.getByRole("button", { name: "Refresh all", exact: true });
await expect(refresh).toBeEnabled();
transport.holdNextClientRequest("usage.list_reports.request");
await refreshAllUsage(page);
await transport.waitForHeldClientRequest();
await expect(refresh).toBeDisabled();
await advanceUsageClock(page, 61_000);
await expect(refresh).toBeEnabled();
}
async function openCompactUsageWithClock(page: Page, now: Date) {
await page.setViewportSize({ width: 390, height: 844 });
await page.clock.install({ time: now });
@@ -318,6 +318,37 @@ test.describe("Workspace archive undo", () => {
}
});
test("archives a restored workspace while its undo is queued", async ({ page }) => {
const teardown = createGatedTeardown();
const repo = await createTempGitRepo("archive-undo-archive-", {
paseoConfig: teardown.paseoConfig,
});
try {
await openProjectViaDaemon(client, repo.path);
const worktree = await createWorktreeViaDaemon(client, {
cwd: repo.path,
slug: "archive-undo-archive",
});
worktreeDirectories.add(worktree.workspaceDirectory);
await gotoAppShell(page);
await archiveFromRowButton(page, worktree.workspaceId);
await teardown.expectStarted();
await undoButton(page).click();
await workspaceRow(page, worktree.workspaceId).click();
await expect(page).toHaveURL(new RegExp(`/workspace/${worktree.workspaceId}$`));
await pressArchiveShortcut(page);
await expectWorkspaceAbsentFromSidebar(page, worktree.workspaceId);
teardown.release();
await expectDirectoryPresence(worktree.workspaceDirectory, false);
} finally {
teardown.release();
await repo.cleanup();
}
});
test("Cmd/Ctrl+Z without an archive to undo leaves the sidebar alone", async ({ page }) => {
const worktree = await seedWorktree(page, "archive-undo-none");
@@ -20,6 +20,7 @@ import {
} from "../support/helpers/sidebar";
import { createTempGitRepo } from "../support/helpers/workspace";
import {
pressArchiveShortcut,
rowArchiveButton,
undoButton,
workspaceRow,
@@ -98,6 +99,18 @@ async function clickRowArchiveButton(page: Page, workspaceId: string): Promise<v
await rowArchiveButton(page, workspaceId).click();
}
async function cycleThemeAndWaitForSidebar(page: Page, workspaceId: string): Promise<void> {
const rowBeforeThemeChange = await workspaceRow(page, workspaceId).elementHandle();
if (!rowBeforeThemeChange)
throw new Error("The workspace row must be mounted before cycling the theme");
await page.keyboard.press("ControlOrMeta+Alt+t");
await expect
.poll(() => rowBeforeThemeChange.evaluate((element) => element.isConnected), {
message: "the sidebar remounts after the theme changes",
})
.toBe(false);
}
interface SessionEnvelope {
type?: unknown;
message?: {
@@ -211,18 +224,28 @@ async function relayDaemon(
* Holds the app's next checkout status request for `directory` once armed, so a test can act
* while the archive waits for the host's answer.
*/
async function holdCheckoutStatusRequest(page: Page, directory: string) {
async function holdCheckoutStatusRequest(
page: Page,
worktree: { workspaceDirectory: string; workspaceId: string },
) {
let armed = false;
let held: (() => void) | null = null;
let archiveRequests = 0;
await page.routeWebSocket(daemonWsRoutePattern(), (browser) => {
const server = browser.connectToServer();
browser.onMessage((message) => {
const request = typeof message === "string" ? parseSessionEnvelope(message)?.message : null;
if (
request?.type === "archive_workspace_request" &&
request.workspaceId === worktree.workspaceId
) {
archiveRequests += 1;
}
if (
armed &&
!held &&
request?.type === "checkout_status_request" &&
request.cwd === directory
request.cwd === worktree.workspaceDirectory
) {
held = () => server.send(message);
return;
@@ -236,6 +259,7 @@ async function holdCheckoutStatusRequest(page: Page, directory: string) {
armed = true;
},
waitForHeld: () => expect.poll(() => held !== null).toBe(true),
archiveRequests: () => archiveRequests,
release: () => {
if (!held) throw new Error("No checkout status request is held");
held();
@@ -388,7 +412,7 @@ test.describe("Workspace archive risk warning for worktree backing", () => {
): Promise<string> {
const serverId = getServerId();
const worktree = await createWorktree(slug);
const statusRequest = await holdCheckoutStatusRequest(page, worktree.workspaceDirectory);
const statusRequest = await holdCheckoutStatusRequest(page, worktree);
await openSidebarRow(page, worktree.workspaceId);
await workspaceRow(page, worktree.workspaceId).click();
await expectAppRoute(page, buildHostWorkspaceRoute(serverId, worktree.workspaceId));
@@ -432,6 +456,82 @@ test.describe("Workspace archive risk warning for worktree backing", () => {
await expectAppRoute(page, openedRoute);
});
async function openWorktreeWithCheckoutHeld(page: Page, slug: string) {
const worktree = await createWorktree(slug);
const statusRequest = await holdCheckoutStatusRequest(page, worktree);
// Opening the workspace can start a checkout read that the archive reuses.
statusRequest.arm();
await openSidebarRow(page, worktree.workspaceId);
await workspaceRow(page, worktree.workspaceId).click();
await expectAppRoute(page, buildHostWorkspaceRoute(getServerId(), worktree.workspaceId));
return { worktree, statusRequest };
}
test("the archive shortcut works in another workspace while a checkout check is pending", async ({
page,
}) => {
const { worktree, statusRequest } = await openWorktreeWithCheckoutHeld(
page,
"archive-risk-switch-shortcut",
);
await pressArchiveShortcut(page);
await statusRequest.waitForHeld();
try {
const otherWorkspaceId = worktree.project.workspaceId;
await workspaceRow(page, otherWorkspaceId).click();
await expectAppRoute(page, buildHostWorkspaceRoute(getServerId(), otherWorkspaceId));
await pressArchiveShortcut(page);
await expect.poll(() => hostListsWorkspace(otherWorkspaceId)).toBe(false);
} finally {
statusRequest.release();
}
await expect.poll(() => hostListsWorkspace(worktree.workspaceId)).toBe(false);
});
test("the row button and shortcut send one archive for the same worktree", async ({ page }) => {
const { worktree, statusRequest } = await openWorktreeWithCheckoutHeld(
page,
"archive-risk-repeat-shortcut",
);
await clickRowArchiveButton(page, worktree.workspaceId);
await statusRequest.waitForHeld();
try {
await pressArchiveShortcut(page);
} finally {
statusRequest.release();
}
await expect.poll(() => hostListsWorkspace(worktree.workspaceId)).toBe(false);
expect(statusRequest.archiveRequests()).toBe(1);
});
test("keeps the newly opened workspace after a theme change during an archive check", async ({
page,
}) => {
const { worktree, statusRequest } = await openWorktreeWithCheckoutHeld(
page,
"archive-risk-theme",
);
await pressArchiveShortcut(page);
await statusRequest.waitForHeld();
const otherWorkspaceId = worktree.project.workspaceId;
const otherRoute = buildHostWorkspaceRoute(getServerId(), otherWorkspaceId);
try {
await cycleThemeAndWaitForSidebar(page, otherWorkspaceId);
await workspaceRow(page, otherWorkspaceId).click();
await expectAppRoute(page, otherRoute);
} finally {
statusRequest.release();
}
await expect.poll(() => hostListsWorkspace(worktree.workspaceId)).toBe(false);
await expectAppRoute(page, otherRoute);
});
test("archiving the open worktree from its git actions leaves it for a new workspace", async ({
page,
}) => {
@@ -185,13 +185,15 @@ function onLogin(report: UsageReportEntry, login: string): UsageReportEntry {
}
export function expiredLogin(report: UsageReportEntry): UsageReportEntry {
const fetchedAt = Date.now();
return {
...report,
fetchedAt: new Date(fetchedAt).toISOString(),
report: {
status: "unavailable",
problem: {
kind: "expired",
expiresAt: new Date(Date.now() - 2 * 60 * 60_000).toISOString(),
expiresAt: new Date(fetchedAt - 2 * 60 * 60_000).toISOString(),
refreshedBy: "claude",
},
},
@@ -1,4 +1,4 @@
import { expect, type Page } from "@playwright/test";
import { expect, test, type Page } from "@playwright/test";
import { openChangesPanel } from "./branch-switcher";
export async function restoreArchivedWorkspace(page: Page): Promise<void> {
@@ -32,7 +32,11 @@ export async function expectCommittedFile(page: Page, filename: string): Promise
}
export async function expectCommittedFileAfterReload(page: Page, filename: string): Promise<void> {
await expectCommittedFile(page, filename);
await page.reload();
await expectCommittedFile(page, filename);
await test.step("See the committed file immediately after Restore", async () => {
await expectCommittedFile(page, filename);
});
await test.step("Reload and see the same committed file", async () => {
await page.reload();
await expectCommittedFile(page, filename);
});
}
+2 -1
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": {
@@ -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",
+1
View File
@@ -66,6 +66,7 @@
[role="slider"],
[role="menuitem"],
[tabindex],
[data-window-no-drag],
[contenteditable="true"] {
-webkit-app-region: no-drag !important;
}
@@ -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);
+2
View File
@@ -54,6 +54,7 @@ import { WindowSidebarMenuToggle } from "@/components/headers/sidebar-menu-toggl
import { DesktopWindowControls } from "@/components/desktop/window-controls";
import { SidebarModelProvider } from "@/components/sidebar/sidebar-model";
import { WorkspacePinShortcutHandler } from "@/components/workspace-pin-shortcut-handler";
import { WorkspaceArchiveShortcutHandler } from "@/components/workspace-archive-shortcut-handler";
import { WorkspaceRenameHost } from "@/components/workspace-rename-host";
import { WorkspaceArchiveUndoShortcutHost } from "@/workspace/archive-undo";
import { WorkspaceExplorerOpenGesture } from "@/mobile-panels/explorer-open-gesture";
@@ -537,6 +538,7 @@ function AppContainer({ children, chromeEnabled: chromeEnabledOverride }: AppCon
<View style={layoutStyles.surfaceFill}>
{workspaceChrome}
<AddHostFlowHost />
<WorkspaceArchiveShortcutHandler />
<AppearanceStyleBoundary>
{!isCompactLayout && appChromeLayout.sidebarToggleOwner === "window" ? (
<WindowChromeRegion corners="top-left">
@@ -24,6 +24,9 @@ import { isNative } from "@/constants/platform";
*/
export const WINDOW_CONTENT_DATASET = { "window-content": "" };
/** Reserves a clickable area for a control mounted outside the titlebar rail. */
export const WINDOW_NO_DRAG_DATASET = { "window-no-drag": "" };
export const titlebarDragSurfaceStyle: React.CSSProperties = {
cursor: "default",
// @ts-expect-error — WebkitAppRegion is not in CSSProperties
@@ -27,6 +27,7 @@ const NO_SHORTCUT: ShortcutKey[] = [];
interface CompactHeaderProps {
/** The leading island: the sidebar menu, or a back button. */
navigation: "menu" | "back";
inDesktopTitlebar?: boolean;
/** Back button action. Defaults to navigating back. */
onBack?: () => void;
title?: string;
@@ -49,6 +50,7 @@ interface CompactHeaderProps {
*/
export function CompactHeader({
navigation,
inDesktopTitlebar = false,
onBack,
title,
titleTestID,
@@ -58,22 +60,28 @@ export function CompactHeader({
}: CompactHeaderProps) {
const insets = useSafeAreaInsets();
const inTopBand = useTopBand() !== null;
const usesTitlebarHeight = inTopBand || inDesktopTitlebar;
const rootStyle = useMemo(
() => [
styles.root,
{
paddingTop: insets.top + (inTopBand ? 0 : HEADER_TOP_PADDING_MOBILE),
paddingTop: insets.top + (usesTitlebarHeight ? 0 : HEADER_TOP_PADDING_MOBILE),
marginLeft: insets.left,
marginRight: insets.right,
},
],
[inTopBand, insets.top, insets.left, insets.right],
[usesTitlebarHeight, insets.top, insets.left, insets.right],
);
return (
<IconButtonChromeProvider value="header-island">
<View style={rootStyle}>
<View style={inTopBand ? styles.topBandRow : styles.row}>
<View
style={[
usesTitlebarHeight ? styles.titlebarRow : styles.row,
inDesktopTitlebar && styles.desktopTitlebarDividerSpace,
]}
>
<View style={styles.island}>
{navigation === "menu" ? <SidebarMenuToggle /> : <BackButton onBack={onBack} />}
</View>
@@ -155,12 +163,16 @@ const styles = StyleSheet.create((theme) => ({
alignItems: "center",
gap: theme.spacing[2],
},
topBandRow: {
titlebarRow: {
height: HEADER_INNER_HEIGHT,
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[2],
},
desktopTitlebarDividerSpace: {
borderBottomWidth: theme.borderWidth[1],
borderBottomColor: "transparent",
},
titleGroup: {
flex: 1,
minWidth: 0,
@@ -128,7 +128,6 @@ import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip
import { Shortcut } from "@/components/ui/shortcut";
import type { ShortcutKey } from "@/utils/format-shortcut";
import { useShortcutKeys } from "@/hooks/use-shortcut-keys";
import { useKeyboardActionHandler } from "@/hooks/use-keyboard-action-handler";
import { useWorkspaceReadState } from "@/hooks/use-workspace-read-state";
import type { PrHint } from "@/git/use-pr-status-query";
import {
@@ -1298,17 +1297,6 @@ function WorkspaceRowWithMenu({
});
}, [markUnread, toast]);
useKeyboardActionHandler({
handlerId: `workspace-archive-${workspace.workspaceKey}`,
actions: ["workspace.archive"],
enabled: selected && !isArchiving,
priority: 0,
handle: () => {
handleArchive();
return true;
},
});
return (
<>
<WorkspaceRowInner
@@ -42,7 +42,6 @@ import { redirectIfArchivingActiveWorkspace } from "@/utils/sidebar-workspace-ar
import { useWorkspaceArchive } from "@/workspace/use-workspace-archive";
import type { ShortcutKey } from "@/utils/format-shortcut";
import { useShortcutKeys } from "@/hooks/use-shortcut-keys";
import { useKeyboardActionHandler } from "@/hooks/use-keyboard-action-handler";
import { useWorkspaceReadState } from "@/hooks/use-workspace-read-state";
import {
SidebarWorkspaceRowFrame,
@@ -702,17 +701,6 @@ function StatusWorkspaceRowWithMenu({
});
}, [markUnread, toast]);
useKeyboardActionHandler({
handlerId: `workspace-archive-${workspace.workspaceKey}`,
actions: ["workspace.archive"],
enabled: selected && !isArchiving,
priority: 0,
handle: () => {
handleArchive();
return true;
},
});
return (
<>
<StatusWorkspaceRowInner
@@ -13,6 +13,7 @@ import {
useRef,
type CSSProperties,
type MouseEvent as ReactMouseEvent,
type PointerEvent as ReactPointerEvent,
type Ref,
} from "react";
import type { DOMProps } from "expo/dom";
@@ -63,6 +64,12 @@ const HOST_DIV_STYLE: CSSProperties = {
paddingRight: 0,
};
interface TerminalTouchFocus {
pointerId: number;
x: number;
y: number;
}
function buildXtermThemeKey(theme: ITheme): string {
const values: Array<string> = [
theme.background,
@@ -553,10 +560,46 @@ export default function TerminalEmulator({
});
}, []);
const handleRootPointerDown = useCallback(() => {
onFocus?.();
runtimeRef.current?.focus();
}, [onFocus]);
const touchFocusRef = useRef<TerminalTouchFocus | null>(null);
const handleRootPointerDown = useCallback(
(event: ReactPointerEvent) => {
onFocus?.();
touchFocusRef.current = null;
if (event.pointerType !== "touch") {
runtimeRef.current?.focus();
return;
}
// Focusing before a touch becomes a tap opens the keyboard during a scroll.
if (event.isPrimary) {
touchFocusRef.current = {
pointerId: event.pointerId,
x: event.clientX,
y: event.clientY,
};
}
},
[onFocus],
);
const handleRootPointerMove = useCallback((event: ReactPointerEvent) => {
const touch = touchFocusRef.current;
if (touch?.pointerId !== event.pointerId) return;
if (Math.hypot(event.clientX - touch.x, event.clientY - touch.y) > 8) {
touchFocusRef.current = null;
runtimeRef.current?.suppressAutomaticKeyboard();
}
}, []);
const handleRootPointerUp = useCallback((event: ReactPointerEvent) => {
const touch = touchFocusRef.current;
touchFocusRef.current = null;
if (touch?.pointerId === event.pointerId) runtimeRef.current?.focus();
}, []);
const handleRootPointerCancel = useCallback(() => {
touchFocusRef.current = null;
}, []);
const handleRootContextMenu = useCallback(
(event: ReactMouseEvent) => {
@@ -588,6 +631,9 @@ export default function TerminalEmulator({
data-terminal-scrollbar-root="true"
style={rootDivStyle}
onPointerDown={handleRootPointerDown}
onPointerMove={handleRootPointerMove}
onPointerUp={handleRootPointerUp}
onPointerCancel={handleRootPointerCancel}
onContextMenu={handleRootContextMenu}
>
<div ref={hostRef} style={HOST_DIV_STYLE} />
@@ -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;
}
@@ -0,0 +1,8 @@
import { useGlobalWorkspaceArchiveAction } from "@/hooks/use-global-workspace-archive-action";
// Headless host for the archive shortcut, kept out of the root layout for the same reason as
// WorkspacePinShortcutHandler: the hook subscribes to the active workspace's fields.
export function WorkspaceArchiveShortcutHandler() {
useGlobalWorkspaceArchiveAction();
return null;
}
@@ -0,0 +1,77 @@
import { useCallback } from "react";
import { useKeyboardActionHandler } from "@/hooks/use-keyboard-action-handler";
import type { KeyboardActionId } from "@/keyboard/keyboard-action-dispatcher";
import { useActiveWorkspaceSelection } from "@/stores/navigation-active-workspace-store";
import { useWorkspaceFields } from "@/stores/session-store-hooks";
import { redirectIfArchivingActiveWorkspace } from "@/utils/sidebar-workspace-archive-redirect";
import { useWorkspaceArchive } from "@/workspace/use-workspace-archive";
import { isWorkspaceListed, type WorkspaceArchiveTarget } from "@/workspace/workspace-archive";
const WORKSPACE_ARCHIVE_ACTIONS: readonly KeyboardActionId[] = ["workspace.archive"];
// The archive shortcut used to live on the sidebar row, so it did nothing whenever the row was not
// rendered — a collapsed project or status group, a collapsed Pinned section, or focus mode. Like
// the pin shortcut (see use-global-workspace-pin-action.ts), it is one registration keyed on the
// active route selection.
export function useGlobalWorkspaceArchiveAction() {
const selection = useActiveWorkspaceSelection();
const serverId = selection?.serverId ?? null;
const routeWorkspaceId = selection?.workspaceId ?? null;
// `id` is the descriptor id, not the route id; see use-global-workspace-pin-action.ts.
const fields = useWorkspaceFields(serverId, routeWorkspaceId, (workspace) => ({
id: workspace.id,
workspaceKind: workspace.workspaceKind,
workspaceDirectory: workspace.workspaceDirectory,
name: workspace.name,
archivingAt: workspace.archivingAt,
diffStat: workspace.diffStat,
}));
// useWorkspaceArchive calls the latest render's callback, so `activeWorkspaceId` is whatever is
// routed when the archive starts, after any confirmation. It is the descriptor id, which is what
// the redirect compares against.
const activeWorkspaceId = fields?.id ?? null;
const redirectAfterArchive = useCallback(
(workspace: WorkspaceArchiveTarget) => {
redirectIfArchivingActiveWorkspace({
...workspace,
activeWorkspaceSelection:
serverId && activeWorkspaceId ? { serverId, workspaceId: activeWorkspaceId } : null,
});
},
[activeWorkspaceId, serverId],
);
const archiveController = useWorkspaceArchive({
serverId: serverId ?? "",
workspaceId: fields?.id ?? "",
workspaceKind: fields?.workspaceKind ?? "directory",
workspaceDirectory: fields?.workspaceDirectory ?? "",
name: fields?.name ?? "",
diffStat: fields?.diffStat,
onArchiveStarted: redirectAfterArchive,
});
const canArchive = fields !== null && fields.archivingAt === null;
const handle = useCallback(() => {
if (!canArchive || !serverId) {
return false;
}
// Archiving hides its target immediately. Read the store in case the shortcut
// runs again before React renders that update.
if (!isWorkspaceListed({ serverId, workspaceId: fields.id })) {
return false;
}
archiveController.archive();
return true;
}, [archiveController, canArchive, fields, serverId]);
useKeyboardActionHandler({
handlerId: "workspace-archive-global",
actions: WORKSPACE_ARCHIVE_ACTIONS,
enabled: canArchive,
priority: 0,
handle,
});
}
+3
View File
@@ -2323,6 +2323,9 @@ export const ar: TranslationResources = {
resetsIn: "تتم إعادة التعيين خلال {{duration}}",
resetsAtWeekday: "{{weekday}} {{time}}",
resetsAtDate: "{{date}}، {{time}}",
projectedLeftAtReset: "نحو {{percentage}} متبقية عند إعادة التعيين",
limitReached: "تم بلوغ الحد",
mayHaveRunOut: "ربما نفدت الحصة",
runsOutNow: "ينفد الآن",
runsOutIn: "ينفد خلال {{duration}}",
justNow: "الآن",
+3
View File
@@ -2333,6 +2333,9 @@ export const en = {
resetsIn: "resets in {{duration}}",
resetsAtWeekday: "{{weekday}} {{time}}",
resetsAtDate: "{{date}}, {{time}}",
projectedLeftAtReset: "~{{percentage}} left at reset",
limitReached: "Limit reached",
mayHaveRunOut: "May have run out",
runsOutNow: "runs out now",
runsOutIn: "runs out in {{duration}}",
justNow: "just now",
+3
View File
@@ -2354,6 +2354,9 @@ export const es: TranslationResources = {
resetsIn: "se restablece en {{duration}}",
resetsAtWeekday: "{{weekday}} {{time}}",
resetsAtDate: "{{date}}, {{time}}",
projectedLeftAtReset: "~{{percentage}} restante al restablecerse",
limitReached: "Límite alcanzado",
mayHaveRunOut: "Puede que ya se haya agotado",
runsOutNow: "se agota ahora",
runsOutIn: "se agota en {{duration}}",
justNow: "ahora mismo",
+3
View File
@@ -2355,6 +2355,9 @@ export const fr: TranslationResources = {
resetsIn: "se réinitialise dans {{duration}}",
resetsAtWeekday: "{{weekday}} {{time}}",
resetsAtDate: "{{date}}, {{time}}",
projectedLeftAtReset: "~{{percentage}} restant à la réinitialisation",
limitReached: "Limite atteinte",
mayHaveRunOut: "Le quota est peut-être épuisé",
runsOutNow: "s’épuise maintenant",
runsOutIn: "s’épuise dans {{duration}}",
justNow: "à l’instant",
+3
View File
@@ -2328,6 +2328,9 @@ export const ja: TranslationResources = {
resetsIn: "{{duration}}後にリセット",
resetsAtWeekday: "{{weekday}} {{time}}",
resetsAtDate: "{{date}} {{time}}",
projectedLeftAtReset: "リセット時に約{{percentage}}残る見込み",
limitReached: "上限に達しました",
mayHaveRunOut: "上限に達した可能性があります",
runsOutNow: "まもなく上限に到達",
runsOutIn: "{{duration}}後に上限に到達",
justNow: "たった今",
+3
View File
@@ -2316,6 +2316,9 @@ export const ko: TranslationResources = {
resetsIn: "{{duration}} 후 재설정",
resetsAtWeekday: "{{weekday}} {{time}}",
resetsAtDate: "{{date}} {{time}}",
projectedLeftAtReset: "초기화 시 약 {{percentage}} 남을 예정",
limitReached: "한도에 도달함",
mayHaveRunOut: "한도를 소진했을 수 있음",
runsOutNow: "지금 한도에 도달",
runsOutIn: "{{duration}} 후 한도에 도달",
justNow: "방금",
+3
View File
@@ -2339,6 +2339,9 @@ export const ptBR: TranslationResources = {
resetsIn: "redefine em {{duration}}",
resetsAtWeekday: "{{weekday}} {{time}}",
resetsAtDate: "{{date}}, {{time}}",
projectedLeftAtReset: "~{{percentage}} restará na renovação",
limitReached: "Limite atingido",
mayHaveRunOut: "A cota pode ter se esgotado",
runsOutNow: "esgota agora",
runsOutIn: "esgota em {{duration}}",
justNow: "agora mesmo",
+3
View File
@@ -2341,6 +2341,9 @@ export const ru: TranslationResources = {
resetsIn: "сброс через {{duration}}",
resetsAtWeekday: "{{weekday}} {{time}}",
resetsAtDate: "{{date}}, {{time}}",
projectedLeftAtReset: "К сбросу останется ~{{percentage}}",
limitReached: "Лимит исчерпан",
mayHaveRunOut: "Лимит мог уже исчерпаться",
runsOutNow: "закончится сейчас",
runsOutIn: "закончится через {{duration}}",
justNow: "только что",
+3
View File
@@ -2282,6 +2282,9 @@ export const zhCN: TranslationResources = {
resetsIn: "将在 {{duration}}后重置",
resetsAtWeekday: "{{weekday}} {{time}}",
resetsAtDate: "{{date}} {{time}}",
projectedLeftAtReset: "重置时约剩余 {{percentage}}",
limitReached: "已达到上限",
mayHaveRunOut: "额度可能已用完",
runsOutNow: "即将用尽",
runsOutIn: "将在 {{duration}}后用尽",
justNow: "刚刚",
@@ -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);
}
@@ -20,8 +20,6 @@ afterEach(async () => {
await act(async () => root.render(null));
usePanelStore.setState(initialPanel, true);
});
const noop = () => {};
const explorerState = { expanded: false };
const geometry: WindowLayout = {
bounds: { x: 0, y: 0, width: window.innerWidth, height: window.innerHeight },
verticalBarEdge: "trailing",
@@ -42,9 +40,8 @@ it("updates compact header actions on panel changes without rendering the worksp
title="Workspace"
subtitle="Project"
isSubtitleDistinct
onToggleExplorer={noop}
explorerToggleLabel="Explorer"
explorerToggleAccessibilityState={explorerState}
explorerAction={null}
inDesktopTitlebar={false}
tabSwitcher={null}
headerVariant="full"
>
@@ -1,11 +1,6 @@
import { Fragment, useMemo, type ReactNode } from "react";
import { useTranslation } from "react-i18next";
import { usePanelStore } from "@/stores/panel-store";
import { CompactHeader } from "@/components/headers/compact-header";
import {
EXPLORER_TOGGLE_KEYS,
WorkspaceExplorerToggle,
} from "@/screens/workspace/workspace-explorer-toggle";
import { WorkspaceHeaderProjectRow } from "@/screens/workspace/workspace-header-project-row";
import {
useWindowLayout,
@@ -23,10 +18,9 @@ interface CompactWorkspaceHeaderProps {
title: string;
subtitle: string;
isSubtitleDistinct: boolean;
onToggleExplorer: () => void;
explorerToggleLabel: string;
explorerToggleAccessibilityState: { expanded: boolean };
explorerAction: ReactNode;
tabSwitcher: ReactNode;
inDesktopTitlebar: boolean;
/** Workspace overflow menu. */
children: ReactNode;
headerVariant: "compact" | "full";
@@ -40,17 +34,15 @@ export function CompactWorkspaceHeader({
title,
subtitle,
isSubtitleDistinct,
onToggleExplorer,
explorerToggleLabel,
explorerToggleAccessibilityState,
explorerAction,
children,
tabSwitcher,
inDesktopTitlebar,
serverId,
headerVariant,
isRouteFocused,
isCompact,
}: CompactWorkspaceHeaderProps) {
const { t } = useTranslation();
const actionsInBar = resolveWorkspaceActionPlacement(useWindowLayout()) === "vertical-bar";
const projectRow = useMemo(
() => (
@@ -65,16 +57,7 @@ export function CompactWorkspaceHeader({
const symbols = {
"tab-count": tabSwitcher,
overflow: children,
explorer: (
<WorkspaceExplorerToggle
onPress={onToggleExplorer}
label={explorerToggleLabel}
tooltipLabel={t("workspace.tabs.explorerSidebar.toggle")}
tooltipKeys={EXPLORER_TOGGLE_KEYS}
accessibilityState={explorerToggleAccessibilityState}
mobile
/>
),
explorer: explorerAction,
};
const actions = resolveWorkspaceBarActions(headerVariant).map((symbol) => (
<Fragment key={symbol}>{symbols[symbol]}</Fragment>
@@ -85,6 +68,7 @@ export function CompactWorkspaceHeader({
{headerVariant === "compact" ? (
<CompactHeader
navigation="menu"
inDesktopTitlebar={inDesktopTitlebar}
title={title}
titleTestID="workspace-header-title"
subtitle={projectRow}
@@ -1,47 +1,37 @@
import { useMemo } from "react";
import { useTranslation } from "react-i18next";
import { PanelRight } from "lucide-react-native";
import { type StyleProp, type ViewStyle } from "react-native";
import { withUnistyles } from "react-native-unistyles";
import { HeaderToggleButton } from "@/components/headers/header-toggle-button";
import { View, type StyleProp, type ViewStyle } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { WINDOW_NO_DRAG_DATASET } from "@/components/desktop/titlebar-drag-region";
import { HeaderToggleButton, headerIconSlotStyle } from "@/components/headers/header-toggle-button";
import { SidebarCloseButton } from "@/components/headers/sidebar-close-button";
import {
extraMutedIconColorMapping,
iconButtonChromeGlyphSize,
mutedIconColorMapping,
} from "@/components/ui/icon-button-chrome";
import { WORKSPACE_SECONDARY_HEADER_HEIGHT } from "@/constants/layout";
import { useHasWindowChromeObstruction } from "@/utils/desktop-window";
import type { ShortcutKey } from "@/utils/format-shortcut";
const ThemedPanelRight = withUnistyles(PanelRight);
export const EXPLORER_TOGGLE_KEYS: ShortcutKey[] = ["mod", "E"];
const EXPLORER_TOGGLE_KEYS: ShortcutKey[] = ["mod", "E"];
interface WorkspaceExplorerToggleProps {
onPress: () => void;
label: string;
tooltipLabel: string;
tooltipKeys: ShortcutKey[];
accessibilityState: { expanded: boolean };
mobile: boolean;
style?: StyleProp<ViewStyle>;
}
export type WorkspaceExplorerToggleOwner = "mobile" | "header" | "window";
export function resolveWorkspaceExplorerToggleOwner({
isMobile,
hasMacTrafficLights,
}: {
isMobile: boolean;
hasMacTrafficLights: boolean;
}): WorkspaceExplorerToggleOwner {
if (isMobile) return "mobile";
return hasMacTrafficLights ? "window" : "header";
}
export function WorkspaceExplorerToggle({
function WorkspaceExplorerToggle({
onPress,
label,
tooltipLabel,
tooltipKeys,
accessibilityState,
mobile,
style,
@@ -51,7 +41,7 @@ export function WorkspaceExplorerToggle({
testID="workspace-explorer-toggle"
onPress={onPress}
tooltipLabel={tooltipLabel}
tooltipKeys={tooltipKeys}
tooltipKeys={EXPLORER_TOGGLE_KEYS}
tooltipSide="left"
style={style}
accessible
@@ -68,42 +58,97 @@ export function WorkspaceExplorerToggle({
);
}
interface DesktopWorkspaceExplorerToggleProps extends Omit<WorkspaceExplorerToggleProps, "mobile"> {
owner: WorkspaceExplorerToggleOwner;
export function useWorkspaceExplorerControls({
hasWorkspace,
compact,
focusMode,
expanded,
onToggle,
}: {
hasWorkspace: boolean;
compact: boolean;
focusMode: boolean;
expanded: boolean;
onToggle: () => void;
}) {
const { t } = useTranslation();
const hasLeadingWindowControls = useHasWindowChromeObstruction("top-left");
const inDesktopTitlebar = hasLeadingWindowControls && hasWorkspace && !compact && !focusMode;
return useMemo(() => {
const props = {
label: expanded
? t("workspace.tabs.explorerSidebar.close")
: t("workspace.tabs.explorerSidebar.open"),
tooltipLabel: t("workspace.tabs.explorerSidebar.toggle"),
onPress: onToggle,
accessibilityState: { expanded },
};
if (inDesktopTitlebar) {
// Keep the button in the header Tab order. The active rail carves its slot out of the drag region.
const headerSlot = expanded ? null : (
<View
pointerEvents="none"
style={[headerIconSlotStyle.slot, styles.headerAction]}
dataSet={WINDOW_NO_DRAG_DATASET}
/>
);
return {
inDesktopTitlebar,
headerAction: headerSlot,
compactAction: headerSlot,
dockAction: (
<View
pointerEvents="none"
style={[headerIconSlotStyle.slot, styles.dockAction]}
dataSet={WINDOW_NO_DRAG_DATASET}
/>
),
titlebarAction: (
<View pointerEvents="box-none" style={styles.titlebarSlot}>
<WorkspaceExplorerToggle {...props} mobile={false} />
</View>
),
};
}
return {
inDesktopTitlebar,
headerAction: compact ? null : (
<WorkspaceExplorerToggle {...props} mobile={false} style={styles.headerAction} />
),
compactAction: <WorkspaceExplorerToggle {...props} mobile />,
dockAction: compact ? (
<SidebarCloseButton
label={props.label}
onPress={onToggle}
testID="workspace-explorer-toggle"
accessibilityState={props.accessibilityState}
/>
) : null,
titlebarAction: null,
};
}, [compact, expanded, inDesktopTitlebar, onToggle, t]);
}
export function WorkspaceHeaderExplorerToggle({
owner,
accessibilityState,
style,
...toggleProps
}: DesktopWorkspaceExplorerToggleProps) {
if (owner === "mobile" || (owner === "window" && accessibilityState.expanded)) return null;
return (
<WorkspaceExplorerToggle
{...toggleProps}
accessibilityState={accessibilityState}
mobile={false}
style={style}
/>
);
}
export function WorkspaceExplorerSidebarToggle({
owner,
...toggleProps
}: DesktopWorkspaceExplorerToggleProps) {
if (owner === "header") return null;
if (owner === "mobile") {
// The compact Explorer is an overlay like the compact agent list, so it closes with the same X.
return (
<SidebarCloseButton
label={toggleProps.label}
onPress={toggleProps.onPress}
testID="workspace-explorer-toggle"
accessibilityState={toggleProps.accessibilityState}
/>
);
}
return <WorkspaceExplorerToggle {...toggleProps} mobile={false} />;
}
const styles = StyleSheet.create((theme) => ({
headerAction: {
marginRight: { xs: 0, md: -theme.spacing[2] },
},
dockAction: {
// The dock divider is absolutely positioned. Match the other headers' content center.
marginBottom: theme.borderWidth[1],
},
titlebarSlot: {
position: "absolute",
top: 0,
right: theme.spacing[1],
height: WORKSPACE_SECONDARY_HEADER_HEIGHT,
// Center with the bordered workspace header and Explorer tabs row.
borderBottomWidth: theme.borderWidth[1],
borderBottomColor: "transparent",
justifyContent: "center",
zIndex: 1,
},
}));
@@ -157,17 +157,8 @@ import {
} from "@/screens/workspace/workspace-desktop-tabs-row";
import { useDesktopBrowserNewTabRequests } from "@/desktop/browser/new-tab-requests";
import type { WorkspaceTabDescriptor } from "@/screens/workspace/workspace-tabs-types";
import {
resolveWorkspaceExplorerToggleOwner,
EXPLORER_TOGGLE_KEYS,
WorkspaceExplorerSidebarToggle,
WorkspaceHeaderExplorerToggle,
} from "@/screens/workspace/workspace-explorer-toggle";
import {
useHasWindowChromeObstruction,
WindowChromeRegion,
WindowChromeSafeArea,
} from "@/utils/desktop-window";
import { useWorkspaceExplorerControls } from "@/screens/workspace/workspace-explorer-toggle";
import { WindowChromeRegion, WindowChromeSafeArea } from "@/utils/desktop-window";
import {
resolveWorkspaceHeaderRenderState,
type WorkspaceHeaderCheckoutState,
@@ -1058,12 +1049,8 @@ function WorkspaceScreenContent({
const isMobile = useIsCompactFormFactor();
const canRenderDesktopPaneSplits = supportsDesktopPaneSplits();
const layoutMode = useWorkspaceLayoutStore((state) => state.layoutMode);
const hasMacTrafficLights = useHasWindowChromeObstruction("top-left");
const explorerToggleOwner = resolveWorkspaceExplorerToggleOwner({
isMobile,
hasMacTrafficLights,
});
const isFocusModeEnabled = usePanelStore((state) => state.desktop.focusModeEnabled);
const desktopFocusModeEnabled = isFocusModeEnabled && !isMobile;
const toggleFocusMode = usePanelStore((state) => state.toggleFocusMode);
const normalizedServerId = useMemo(() => trimNonEmpty(decodeSegment(serverId)) ?? "", [serverId]);
@@ -1308,11 +1295,6 @@ function WorkspaceScreenContent({
explorerOpen: isExplorerSidebarShowing,
});
const explorerSidebarToggleAccessibilityState = useMemo(
() => ({ expanded: isExplorerSidebarShowing }),
[isExplorerSidebarShowing],
);
useEffect(() => {
// Back dismisses the compact overlay only. On a wide native layout the
// explorer is a tab, `showMobileAgent` has no rendered consumer, and
@@ -1820,9 +1802,6 @@ function WorkspaceScreenContent({
}),
[t],
);
const explorerSidebarToggleLabel = isExplorerSidebarShowing
? t("workspace.tabs.explorerSidebar.close")
: t("workspace.tabs.explorerSidebar.open");
const activeTabKey = useMemo(() => activeTabId ?? "", [activeTabId]);
const handleCreateDraftTab = useCallback(
@@ -3228,6 +3207,13 @@ function WorkspaceScreenContent({
workspaceKey: persistenceKey,
});
const explorerControls = useWorkspaceExplorerControls({
hasWorkspace: !!workspaceDirectory,
compact: isMobile,
focusMode: desktopFocusModeEnabled,
expanded: isExplorerSidebarShowing,
onToggle: handleToggleExplorerSidebar,
});
const headerRight = useMemo(
() => (
<View style={styles.headerRight}>
@@ -3254,17 +3240,7 @@ function WorkspaceScreenContent({
{workspaceDirectory ? (
<>
<WorkspaceActions serverId={normalizedServerId} cwd={workspaceDirectory} />
{workspaceActionsInBar ? null : (
<WorkspaceHeaderExplorerToggle
owner={explorerToggleOwner}
onPress={handleToggleExplorerSidebar}
label={explorerSidebarToggleLabel}
tooltipLabel={t("workspace.tabs.explorerSidebar.toggle")}
tooltipKeys={EXPLORER_TOGGLE_KEYS}
style={styles.compactHeaderActionButton}
accessibilityState={explorerSidebarToggleAccessibilityState}
/>
)}
{workspaceActionsInBar ? null : explorerControls.headerAction}
</>
) : null}
</View>
@@ -3279,12 +3255,8 @@ function WorkspaceScreenContent({
scriptActions,
handleViewScriptTerminal,
handleOpenUrlInBrowserTab,
handleToggleExplorerSidebar,
explorerSidebarToggleLabel,
explorerSidebarToggleAccessibilityState,
explorerToggleOwner,
explorerControls.headerAction,
workspaceActionsInBar,
t,
],
);
@@ -3292,25 +3264,6 @@ function WorkspaceScreenContent({
() => shouldShowWorkspaceScreenHeader({ isFocusModeEnabled, isMobile }),
[isFocusModeEnabled, isMobile],
);
const renderExplorerSidebarHeaderAction = useCallback(
() => (
<WorkspaceExplorerSidebarToggle
owner={explorerToggleOwner}
onPress={handleToggleExplorerSidebar}
label={explorerSidebarToggleLabel}
tooltipLabel={t("workspace.tabs.explorerSidebar.toggle")}
tooltipKeys={EXPLORER_TOGGLE_KEYS}
accessibilityState={explorerSidebarToggleAccessibilityState}
/>
),
[
explorerSidebarToggleAccessibilityState,
explorerSidebarToggleLabel,
explorerToggleOwner,
handleToggleExplorerSidebar,
t,
],
);
const createTerminalDisabled = useMemo(
() => createTerminalMutation.isPending || pendingTerminalCreateInput !== null,
[createTerminalMutation.isPending, pendingTerminalCreateInput],
@@ -3333,10 +3286,6 @@ function WorkspaceScreenContent({
],
);
const focusedPaneIdOrUndefined = useMemo(() => focusedPaneId ?? undefined, [focusedPaneId]);
const desktopFocusModeEnabled = useMemo(
() => isFocusModeEnabled && !isMobile,
[isFocusModeEnabled, isMobile],
);
const workspaceFloatingPanelPortalHostName = useMemo(
() =>
`${WORKSPACE_FLOATING_PANEL_PORTAL_HOST_PREFIX}:${normalizedServerId}:${normalizedWorkspaceId}`,
@@ -3460,14 +3409,13 @@ function WorkspaceScreenContent({
isRouteFocused={isRouteFocused}
isCompact={isMobile}
tabSwitcher={tabSwitcher}
inDesktopTitlebar={explorerControls.inDesktopTitlebar}
explorerAction={explorerControls.compactAction}
isLoading={isWorkspaceHeaderLoading}
title={workspaceHeaderTitle}
subtitle={workspaceHeaderSubtitle}
isSubtitleDistinct={isWorkspaceHeaderSubtitleDistinct}
serverId={normalizedServerId}
onToggleExplorer={handleToggleExplorerSidebar}
explorerToggleLabel={explorerSidebarToggleLabel}
explorerToggleAccessibilityState={explorerSidebarToggleAccessibilityState}
>
<WorkspaceHeaderMenuMobile
pane={paneTabs?.actions.pane}
@@ -3493,20 +3441,19 @@ function WorkspaceScreenContent({
},
[
renderWorkspaceTabSwitcher,
explorerControls.inDesktopTitlebar,
explorerControls.compactAction,
isFocusModeEnabled,
toggleFocusMode,
canOpenImportSheet,
compactHeaderScripts,
createTerminalDisabled,
currentBranchName,
explorerSidebarToggleAccessibilityState,
explorerSidebarToggleLabel,
handleCopyBranchName,
handleCopyWorkspacePath,
handleCreateBrowserTab,
handleCreateTerminalWithProfile,
handleOpenSetupTab,
handleToggleExplorerSidebar,
isMobile,
isRouteFocused,
isWorkspaceHeaderLoading,
@@ -3734,7 +3681,7 @@ function WorkspaceScreenContent({
onExitFocusMode={toggleFocusMode}
onReorderTabsInPane={handleReorderTabsInPane}
buildPaneContentModel={buildDesktopPaneContentModel}
headerAction={renderExplorerSidebarHeaderAction()}
headerAction={explorerControls.dockAction}
/>
);
return (
@@ -3775,7 +3722,7 @@ function WorkspaceScreenContent({
toggleFocusMode,
handleReorderTabsInPane,
buildDesktopPaneContentModel,
renderExplorerSidebarHeaderAction,
explorerControls.dockAction,
desktopFocusModeEnabled,
]);
@@ -3849,6 +3796,7 @@ function WorkspaceScreenContent({
onReorderTabsInPane={handleReorderTabsInPane}
onSplitPane={handleSplitPane}
>
{explorerControls.titlebarAction}
{workspaceCenterColumn}
{sharedExplorer}
</WorkspaceTabDragScope>
@@ -3986,12 +3934,6 @@ const styles = StyleSheet.create((theme) => ({
md: theme.spacing[2],
},
},
compactHeaderActionButton: {
marginRight: {
xs: 0,
md: -theme.spacing[2],
},
},
compactHeaderMenuCluster: {
flexDirection: "row",
alignItems: "center",
@@ -1,10 +1,5 @@
import { buildDesktopFrameStyle } from "@/components/ui/combobox-frame-style";
import {
WorkspaceHeaderExplorerToggle,
WorkspaceExplorerSidebarToggle,
} from "./workspace-explorer-toggle";
import { describe, expect, it } from "vitest";
import { SidebarCloseButton } from "@/components/headers/sidebar-close-button";
import { resolveWorkspaceTabChipBackdrop } from "@/screens/workspace/workspace-tab-chip-backdrop";
import { darkPureBlackTheme, darkTheme, lightTheme } from "@/styles/theme";
import {
@@ -190,37 +185,6 @@ describe("retainWorkspaceTabMeasuredWidth", () => {
});
});
describe("Explorer toggle ownership", () => {
const toggleProps = {
onPress: () => {},
label: "Close Explorer sidebar",
tooltipLabel: "Toggle Explorer sidebar",
tooltipKeys: [],
accessibilityState: { expanded: true },
};
it("keeps only the header toggle when window controls do not obstruct it", () => {
expect(WorkspaceHeaderExplorerToggle({ ...toggleProps, owner: "header" })).not.toBeNull();
expect(WorkspaceExplorerSidebarToggle({ ...toggleProps, owner: "header" })).toBeNull();
});
it("keeps the dock toggle for window-owned and compact overlay chrome", () => {
for (const owner of ["window", "mobile"] as const) {
expect(WorkspaceHeaderExplorerToggle({ ...toggleProps, owner })).toBeNull();
expect(WorkspaceExplorerSidebarToggle({ ...toggleProps, owner })).not.toBeNull();
}
});
it("closes the compact overlay with the same X as the compact agent list", () => {
expect(WorkspaceExplorerSidebarToggle({ ...toggleProps, owner: "mobile" })?.type).toBe(
SidebarCloseButton,
);
expect(WorkspaceExplorerSidebarToggle({ ...toggleProps, owner: "window" })?.type).not.toBe(
SidebarCloseButton,
);
});
});
describe("resolveWorkspaceTabChipBackdrop", () => {
const themes = { light: lightTheme, dark: darkTheme, pureBlack: darkPureBlackTheme };
const rails = {
@@ -1053,12 +1053,19 @@ export class TerminalEmulatorRuntime {
if (!terminal) {
return;
}
terminal.textarea?.removeAttribute("virtualkeyboardpolicy");
if (input?.forceRefocus) {
terminal.blur();
}
terminal.focus();
}
suppressAutomaticKeyboard(): void {
// Android Chrome can reopen the keyboard during a drag after Back leaves the input
// focused. Manual policy prevents that without closing an already open keyboard.
this.terminal?.textarea?.setAttribute("virtualkeyboardpolicy", "manual");
}
blur(): void {
this.terminal?.blur();
}
@@ -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>
@@ -32,6 +32,7 @@ it("translates mounted usage rows when the language changes", async () => {
<>
<UsageWindowBar
window={window}
forecastAt={null}
displayAs="used"
pinnable={false}
pinned={false}
@@ -51,3 +52,68 @@ it("translates mounted usage rows when the language changes", async () => {
expect(container.textContent).toContain("セッション70% 使用済み");
expect(container.textContent).toContain("クレジット");
});
const narrowReadingMs = Date.now();
const narrowForecastAt = new Date(narrowReadingMs).toISOString();
const narrowWindow: UsageWindow = {
id: "weekly",
label: "Weekly",
usedPct: 0.2,
durationSeconds: 604_800,
resetsAt: new Date(narrowReadingMs + 165.5 * 3_600_000).toISOString(),
};
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(() =>
root.render(
<UsageWindowBar
window={narrowWindow}
forecastAt={narrowForecastAt}
displayAs="used"
pinnable={false}
pinned={false}
onTogglePin={ignorePin}
pinLabel=""
pinTestID=""
/>,
),
);
function textBounds(prefix: string) {
const element = Array.from(container.querySelectorAll("*")).find(
(node) => node.childElementCount === 0 && node.textContent.startsWith(prefix),
);
expect(element).toBeDefined();
const range = document.createRange();
range.selectNodeContents(element!);
return range.getBoundingClientRect();
}
const countdown = textBounds("se réinitialise");
const forecast = textBounds("~");
expect(forecast.left >= countdown.right || forecast.top >= countdown.bottom).toBe(true);
});
+6 -2
View File
@@ -70,7 +70,7 @@ export function UsageCard({
}) {
const { t } = useTranslation();
const isCompact = useIsCompactFormFactor();
const { refresh, refreshState } = useReportRefresh(serverId, entry.id, agentId);
const { refresh, refreshState } = useReportRefresh(serverId, entry, agentId);
// Where there is no hover the freshness is printed on the card; elsewhere the Refresh tooltip.
const showsFreshnessInline = isNative || isCompact || !refreshable;
const usage = entry.report;
@@ -176,7 +176,7 @@ function UsageCardBody({
refreshState: UsageRefresh;
}) {
const { t } = useTranslation();
const { windows, balances, details, retained, successfulAt, messages } = report;
const { windows, balances, details, retained, successfulAt, forecastAt, messages } = report;
const footer = entry.account.label ?? null;
return (
<>
@@ -194,6 +194,7 @@ function UsageCardBody({
entry={entry}
window={window}
retained={retained}
forecastAt={forecastAt}
display={display}
pinnable={pinnable}
/>
@@ -267,8 +268,10 @@ function CardWindowBar({
display,
pinnable,
retained,
forecastAt,
}: {
retained: boolean;
forecastAt: string | null;
entry: UsageReportEntry;
window: UsageWindow;
display: UsageDisplay;
@@ -285,6 +288,7 @@ function CardWindowBar({
<UsageWindowBar
window={window}
retained={retained}
forecastAt={forecastAt}
displayAs={display.displayAs}
pinnable={pinnable}
pinned={display.isPinned(pin)}
+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,
},
}));
+58 -8
View File
@@ -2,6 +2,7 @@ import { afterEach, describe, expect, it } from "vitest";
import { i18n } from "@/i18n/i18next";
import {
resolveUsageReport,
markUsageRefreshFailure,
displayPercent,
resolveAgentUsageView,
replaceReport,
@@ -82,7 +83,7 @@ describe("resolveUsageView", () => {
expect(resolveUsageView({ ...base, query: undefined })).toEqual({ kind: "loading" });
expect(
resolveUsageView({ ...base, query: { data: [], error: null, isFetching: true } }),
).toEqual({ kind: "ready", reports: [], isRefreshing: true });
).toEqual({ kind: "ready", reports: [], isRefreshing: true, refreshFailed: false });
expect(
resolveUsageView({
...base,
@@ -90,6 +91,19 @@ describe("resolveUsageView", () => {
}),
).toEqual({ kind: "error", message: "boom" });
});
it("shows a failed Refresh all alongside the reports still on screen", () => {
const reports = [entry({})];
expect(
resolveUsageView({
hostLabel: "Laptop",
isConnected: true,
supportsUsage: true,
query: ready(reports),
refreshState: "failed",
}),
).toEqual({ kind: "ready", reports, isRefreshing: false, refreshFailed: true });
});
});
afterEach(async () => {
@@ -203,15 +217,12 @@ describe("displayPercent", () => {
describe("resolveUsageRefresh", () => {
it("is pending while a refresh runs, even after an earlier failure", () => {
expect(resolveUsageRefresh({ isPending: true, error: new Error("boom") })).toBe("pending");
expect(resolveUsageRefresh({ isPending: true, isError: true })).toBe("pending");
});
it("is failed after a refresh errors", () => {
expect(resolveUsageRefresh({ isPending: false, error: new Error("boom") })).toBe("failed");
});
it("is idle before and after a successful refresh", () => {
expect(resolveUsageRefresh({ isPending: false, error: null })).toBe("idle");
it("reports the request outcome independently of the reading", () => {
expect(resolveUsageRefresh({ isPending: false, isError: true })).toBe("failed");
expect(resolveUsageRefresh({ isPending: false, isError: false })).toBe("idle");
});
});
@@ -352,6 +363,7 @@ it("resolves retained usage and successful time without inventing old-daemon his
details: [],
planLabel: null,
successfulAt: success.fetchedAt,
forecastAt: null,
retained: true,
messages: ["Rate limited"],
});
@@ -361,6 +373,7 @@ it("resolves retained usage and successful time without inventing old-daemon his
details: [],
planLabel: null,
successfulAt: null,
forecastAt: null,
retained: false,
messages: ["Rate limited"],
});
@@ -370,11 +383,48 @@ it("resolves retained usage and successful time without inventing old-daemon his
details: [],
planLabel: null,
successfulAt: success.fetchedAt,
forecastAt: success.fetchedAt,
retained: false,
messages: [],
});
});
it("uses the quota observation time for pace and keeps the reading after a failed request", () => {
const success = entry({ windows: [{ id: "weekly", label: "Weekly", usedPct: 42 }] });
if (success.report.status !== "available") throw new Error("fixture must be available");
const observedAt = success.fetchedAt;
const successfulAt = "2026-01-01T00:15:00.000Z";
const report = { ...success, successfulAt, report: { ...success.report, observedAt } };
expect(resolveUsageReport(report, i18n.t)).toMatchObject({
successfulAt,
forecastAt: observedAt,
});
expect(resolveUsageReport({ ...report, forecastStale: true }, i18n.t)).toMatchObject({
windows: success.report.windows,
successfulAt,
forecastAt: null,
});
});
it("keeps cached quota and hides its forecast when Refresh all fails before a new report arrives", () => {
const before = entry({ windows: [{ id: "weekly", label: "Weekly", usedPct: 42 }] });
const other = entry({ sourceId: "other" });
const refreshedAt = "2026-01-01T00:06:00.000Z";
const streamed = { ...other, fetchedAt: refreshedAt };
const attempted = [before, other];
const failed = markUsageRefreshFailure([before, streamed], attempted)!;
expect(resolveUsageReport(failed[0]!, i18n.t)).toMatchObject({
forecastAt: null,
windows: before.report.status === "available" ? before.report.windows : [],
});
expect(resolveUsageReport(failed[1]!, i18n.t).forecastAt).toBe(refreshedAt);
expect(resolveUsageReport(upsertReport(failed, before)[0]!, i18n.t).forecastAt).toBeNull();
const retried = settleReports(failed, [{ ...before, fetchedAt: refreshedAt }, streamed]);
expect(resolveUsageReport(retried[0]!, i18n.t).forecastAt).toBe(refreshedAt);
});
it("orders failed polls by attempt time even when successful data is older", () => {
const success = entry({});
if (success.report.status !== "available") throw new Error("fixture must be available");
+35 -7
View File
@@ -38,18 +38,31 @@ export function usageWindowRowLabel(input: {
return `${input.pinLabel}, ${summary}`;
}
/** A user-requested refresh of one report. The previous report stays on screen throughout. */
/** The outcome of a user-requested usage refresh. */
export type UsageRefresh = "idle" | "pending" | "failed";
export function resolveUsageRefresh(mutation: {
isPending: boolean;
error: unknown;
isError: boolean;
}): UsageRefresh {
if (mutation.isPending) return "pending";
if (mutation.error) return "failed";
if (mutation.isError) return "failed";
return "idle";
}
/** Keep quota readings after a failed refresh and attach the outcome to the readings it targeted. */
export function markUsageRefreshFailure(
current: UsageReportEntry[] | undefined,
attempted: readonly UsageReportEntry[],
): UsageReportEntry[] | undefined {
const attemptedAt = new Map(attempted.map((entry) => [entry.id, entry.fetchedAt]));
return current?.map((entry) =>
attemptedAt.get(entry.id) === entry.fetchedAt && !entry.forecastStale
? { ...entry, forecastStale: true }
: entry,
);
}
/**
* A host's report list with one report swapped for its refreshed copy, in place.
* `null` means the daemon no longer knows the ID, so the report leaves the list.
@@ -60,7 +73,9 @@ export function replaceReport(
refreshed: UsageReportEntry | null,
): UsageReportEntry[] {
if (!refreshed) return reports.filter((report) => report.id !== reportId);
return reports.map((report) => (report.id === reportId ? refreshed : report));
return reports.map((report) =>
report.id === reportId ? laterFetched(report, refreshed) : report,
);
}
/**
@@ -68,7 +83,9 @@ export function replaceReport(
* started, so a Refresh that lands while it streams is newer than what the request still delivers.
*/
function laterFetched(shown: UsageReportEntry, arriving: UsageReportEntry): UsageReportEntry {
return Date.parse(shown.fetchedAt) > Date.parse(arriving.fetchedAt) ? shown : arriving;
const shownAt = Date.parse(shown.fetchedAt);
const arrivingAt = Date.parse(arriving.fetchedAt);
return shownAt > arrivingAt || (shownAt === arrivingAt && shown.forecastStale) ? shown : arriving;
}
/**
@@ -117,10 +134,11 @@ export function resolveUsageView(
isConnected: boolean;
supportsUsage: boolean;
query: UsageQueryState | undefined;
refreshState?: UsageRefresh;
},
t: TFunction = i18n.t,
): UsageView {
const { hostLabel, isConnected, supportsUsage, query } = input;
const { hostLabel, isConnected, supportsUsage, query, refreshState } = input;
if (!isConnected)
return {
kind: "unavailable",
@@ -135,7 +153,12 @@ export function resolveUsageView(
if (input.enabled === false)
return { kind: "off", message: t("providerUsage.off", { host: hostLabel }) };
if (query?.data) {
return { kind: "ready", reports: query.data, isRefreshing: query.isFetching };
return {
kind: "ready",
reports: query.data,
isRefreshing: query.isFetching || refreshState === "pending",
refreshFailed: refreshState === "failed",
};
}
if (query?.error) {
return {
@@ -250,7 +273,12 @@ export function resolveUsageReport(entry: UsageReportEntry, t: TFunction) {
// COMPAT(usageLoginErrors): added in v0.11.0, remove after 2027-04-05 once daemon floor >= v0.11.0.
else messages.push(usageProblemText(entry.report, t));
}
const forecastAt =
snapshot && !snapshot.retained && !entry.forecastStale
? (snapshot.report.observedAt ?? snapshot.successfulAt)
: null;
return {
forecastAt,
windows: snapshot?.report.windows ?? [],
balances: snapshot?.report.balances ?? [],
details: snapshot?.report.details ?? [],
+45
View File
@@ -0,0 +1,45 @@
import { describe, expect, it } from "vitest";
import { usagePace } from "./pace";
import type { UsageWindow } from "./types";
const day = "2026-11-20T";
const reading = (time: string) => `${day}${time}:00.000Z`;
const window: UsageWindow = {
id: "five_hour",
label: "Session",
durationSeconds: 18_000,
usedPct: 65,
resetsAt: reading("15:00"),
};
describe("usage pace", () => {
it("projects the limit from the sample time and keeps it fixed between readings", () => {
const sampledAt = reading("12:00");
const estimate = { kind: "runsOut", at: `${day}13:04:36.923Z` };
expect(usagePace(window, sampledAt, Date.parse(sampledAt))).toEqual(estimate);
expect(usagePace(window, sampledAt, Date.parse(reading("12:30")))).toEqual(estimate);
});
it("updates after a later reading and works with a remaining percentage", () => {
const close = reading("13:30");
const safe = reading("14:00");
const forecast = usagePace(window, close, Date.parse(close));
expect(forecast.kind).toBe("remaining");
if (forecast.kind === "remaining") expect(forecast.remainingAtResetPct).toBeCloseTo(7.14);
expect(
usagePace({ ...window, usedPct: undefined, remainingPct: 35 }, safe, Date.parse(safe)),
).toEqual({ kind: "remaining", remainingAtResetPct: 18.75 });
});
it("only forecasts with timing and an active, usable reading", () => {
const sampledAt = reading("12:00");
const now = Date.parse(sampledAt);
expect(usagePace({ ...window, durationSeconds: undefined }, sampledAt, now)).toEqual({
kind: "unknown",
});
expect(usagePace(window, null, now)).toEqual({ kind: "unknown" });
expect(usagePace(window, reading("10:01"), now)).toEqual({ kind: "unknown" });
expect(usagePace(window, sampledAt, Date.parse(window.resetsAt!))).toEqual({ kind: "unknown" });
expect(usagePace({ ...window, usedPct: 100 }, sampledAt, now)).toEqual({ kind: "reached" });
});
});
+45
View File
@@ -0,0 +1,45 @@
import { usedPercent } from "./model";
import type { UsageWindow } from "./types";
type UsagePace =
| { kind: "unknown" }
| { kind: "reached" }
| { kind: "runsOut"; at: string }
| { kind: "remaining"; remainingAtResetPct: number };
/** Estimate from the window's average pace as of the reading. The clock only expires the estimate. */
export function usagePace(window: UsageWindow, observedAt: string | null, now: number): UsagePace {
if (observedAt === null) return { kind: "unknown" };
const reset = Date.parse(window.resetsAt ?? "");
if (reset <= now) return { kind: "unknown" };
const used = usedPercent(window);
if (used != null && used >= 100) return { kind: "reached" };
const supplied = window.runsOutAt;
const suppliedAt = Date.parse(supplied ?? "");
if (supplied && Number.isFinite(suppliedAt) && (!Number.isFinite(reset) || suppliedAt < reset)) {
return { kind: "runsOut", at: supplied };
}
const duration = (window.durationSeconds ?? 0) * 1_000;
const sampled = Date.parse(observedAt);
const elapsed = sampled - (reset - duration);
if (
used == null ||
!Number.isFinite(used) ||
used < 0 ||
!Number.isFinite(elapsed) ||
sampled >= reset ||
elapsed < Math.max(60_000, duration * 0.01)
) {
return { kind: "unknown" };
}
const projectedAtReset = (used / elapsed) * duration;
if (projectedAtReset > 100) {
const runsOut = sampled + ((100 - used) / used) * elapsed;
return { kind: "runsOut", at: new Date(runsOut).toISOString() };
}
return { kind: "remaining", remainingAtResetPct: 100 - projectedAtReset };
}
+42 -19
View File
@@ -20,6 +20,7 @@ import { useSessionStore, type SessionState } from "@/stores/session-store";
import { useUsageSetting } from "./setting";
import { usageCopy } from "./copy";
import {
markUsageRefreshFailure,
replaceReport,
resolveAgentUsageView,
resolveUsageRefresh,
@@ -97,17 +98,32 @@ async function streamReports(input: {
return settleReports(queryClient.getQueryData<UsageReportEntry[]>(queryKey), reports);
}
function listReports(
async function listReports(
queryClient: QueryClient,
serverId: string,
forceRefresh = false,
): Promise<UsageReportEntry[]> {
return streamReports({
queryClient,
queryKey: usageReportsQueryKey(serverId),
serverId,
forceRefresh,
});
const queryKey = usageReportsQueryKey(serverId);
const attempted = queryClient.getQueryData<UsageReportEntry[]>(queryKey) ?? [];
try {
return await streamReports({ queryClient, queryKey, serverId, forceRefresh });
} catch (error) {
recordUsageRefreshFailure(queryClient, queryKey, attempted);
throw error;
}
}
function recordUsageRefreshFailure(
queryClient: QueryClient,
queryKey: QueryKey,
attempted: readonly UsageReportEntry[],
): void {
const { dataUpdatedAt } = queryClient.getQueryState(queryKey) ?? {};
queryClient.setQueryData<UsageReportEntry[]>(
queryKey,
(current) => markUsageRefreshFailure(current, attempted),
{ updatedAt: dataUpdatedAt },
);
}
async function getReport(
@@ -158,9 +174,12 @@ export function useHostUsage(serverId: string): { view: UsageView; refresh: () =
dataShape: "value",
staleTimeMs: REPORTS_STALE_TIME_MS,
});
const refresh = useCallback(() => {
void refreshReports(queryClient, serverId).catch(() => undefined);
}, [queryClient, serverId]);
const mutation = useMutation({
mutationKey: [...usageReportsQueryKey(serverId), "refresh"],
mutationFn: (hostId: string) => refreshReports(queryClient, hostId),
});
const { mutate, variables } = mutation;
const refresh = useCallback(() => mutate(serverId), [mutate, serverId]);
const { t } = useTranslation();
const hostLabel = useHosts().find((host) => host.serverId === serverId)?.label ?? serverId;
const view = resolveUsageView(
@@ -170,6 +189,7 @@ export function useHostUsage(serverId: string): { view: UsageView; refresh: () =
isConnected,
supportsUsage: isSupported,
query: toQueryState(query),
refreshState: variables === serverId ? resolveUsageRefresh(mutation) : "idle",
},
t,
);
@@ -265,23 +285,26 @@ export function useUsageHosts(): UsageHost[] {
*/
export function useReportRefresh(
serverId: string,
reportId: string,
entry: UsageReportEntry,
agentId?: string,
): { refresh: () => void; refreshState: UsageRefresh } {
const queryClient = useQueryClient();
const usageScopeKey = useAgentUsageScopeKey(serverId, agentId);
const queryKey =
agentId === undefined
? usageReportsQueryKey(serverId)
: agentUsageQueryKey(serverId, agentId, usageScopeKey);
const mutation = useMutation({
mutationFn: () => getReport(serverId, reportId, true, agentId),
onSuccess: (report) => {
queryClient.setQueryData<UsageReportEntry[]>(
agentId === undefined
? usageReportsQueryKey(serverId)
: agentUsageQueryKey(serverId, agentId, usageScopeKey),
(reports) => (reports ? replaceReport(reports, reportId, report) : reports),
mutationKey: [...queryKey, "refresh", entry.id],
mutationFn: (attempted: UsageReportEntry) => getReport(serverId, attempted.id, true, agentId),
onSuccess: (report, attempted) => {
queryClient.setQueryData<UsageReportEntry[]>(queryKey, (reports) =>
reports ? replaceReport(reports, attempted.id, report) : reports,
);
},
onError: (_error, attempted) => recordUsageRefreshFailure(queryClient, queryKey, [attempted]),
});
const { mutate } = mutation;
const refresh = useCallback(() => mutate(), [mutate]);
const refresh = useCallback(() => mutate(entry), [mutate, entry]);
return { refresh, refreshState: resolveUsageRefresh(mutation) };
}
-48
View File
@@ -1,48 +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 gives way (truncates) and the countdown stays whole.
*/
export function UsageResetLine({
countdown,
exactTime,
atRisk = false,
testID,
}: {
countdown: string | null;
exactTime: string | null;
/** The countdown is a runs-out warning rather than a reset. */
atRisk?: boolean;
testID?: string;
}) {
if (!countdown) return null;
return (
<View style={styles.line} testID={testID}>
<Text style={atRisk ? styles.atRisk : styles.text}>{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: "center" },
text: {
flexShrink: 0,
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.sm,
fontWeight: theme.fontWeight.normal,
},
atRisk: {
flexShrink: 0,
color: theme.colors.statusDanger,
fontSize: theme.fontSize.sm,
fontWeight: theme.fontWeight.normal,
},
exactTime: { flexShrink: 1 },
}));
+9 -3
View File
@@ -1,6 +1,12 @@
import type { ProviderUsageTone, UsageReportEntry } from "@getpaseo/protocol/messages";
import type {
ProviderUsageTone,
UsageReportEntry as WireUsageReportEntry,
} from "@getpaseo/protocol/messages";
export type { UsageReportEntry };
export interface UsageReportEntry extends WireUsageReportEntry {
/** A refresh failed while this reading was cached. */
forecastStale?: true;
}
export type UsageReport = UsageReportEntry["report"];
export type UsageTone = ProviderUsageTone;
export type AvailableUsageReport = Extract<UsageReport, { status: "available" }>;
@@ -14,4 +20,4 @@ export type UsageView =
| { kind: "unavailable"; message: string }
| { kind: "loading" }
| { kind: "error"; message: string }
| { kind: "ready"; reports: UsageReportEntry[]; isRefreshing: boolean };
| { kind: "ready"; reports: UsageReportEntry[]; isRefreshing: boolean; refreshFailed: boolean };
+13 -5
View File
@@ -84,11 +84,18 @@ export function UsageBody({
);
}
if (view.reports.length === 0) {
return <UsageMessage text={t("providerUsage.empty")} />;
}
return <UsageList serverId={serverId} reports={view.reports} display={display} />;
return (
<View style={styles.reports}>
{view.refreshFailed ? (
<Alert size="sm" variant="error" title={t("providerUsage.refreshFailed")} />
) : null}
{view.reports.length === 0 ? (
<UsageMessage text={t("providerUsage.empty")} />
) : (
<UsageList serverId={serverId} reports={view.reports} display={display} />
)}
</View>
);
}
export function UsageMessage({ text }: { text: string }) {
@@ -100,6 +107,7 @@ export function UsageMessage({ text }: { text: string }) {
}
const styles = StyleSheet.create((theme) => ({
reports: { gap: theme.spacing[3] },
emptyCard: {
padding: theme.spacing[4],
alignItems: "center",
+48 -23
View File
@@ -1,3 +1,4 @@
import type { TFunction } from "i18next";
import { Pin } from "lucide-react-native";
import { useMemo } from "react";
import { useTranslation } from "react-i18next";
@@ -6,6 +7,7 @@ import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import {
formatDisplayPct,
formatPct,
formatProviderUsageLabel,
formatResetLabel,
formatResetTime,
@@ -13,9 +15,9 @@ import {
} from "./format";
import { UsageMeter } from "./meter";
import { displayPercent, usageWindowRowLabel } from "./model";
import { UsageResetLine } from "./reset-line";
import { usagePace } from "./pace";
import { UsageDatapointLine } from "./datapoint-line";
import type { UsageDisplayAs } from "./preferences";
import { windowTone } from "./tone";
import type { UsageTone, UsageWindow } from "./types";
import { useRelativeTimeTick } from "./use-relative-time-tick";
@@ -28,8 +30,10 @@ export function UsageWindowBar({
pinLabel,
pinTestID,
retained = false,
forecastAt,
}: {
retained?: boolean;
forecastAt: string | null;
window: UsageWindow;
displayAs: UsageDisplayAs;
/** Whether the row pins the window to the sidebar. When false the row is a plain bar. */
@@ -42,19 +46,11 @@ export function UsageWindowBar({
}) {
const { t, i18n } = useTranslation();
const shownPct = displayPercent(window, displayAs);
const tone = windowTone(window);
const now = useRelativeTimeTick({ enabled: window.runsOutAt != null || window.resetsAt != null });
const isAtRisk =
window.runsOutAt != null &&
window.shortfallPct != null &&
(!retained || Date.parse(window.runsOutAt) > now);
const countdown = isAtRisk
? formatRunsOutLabel(window.runsOutAt, now, t)
: formatResetLabel(window.resetsAt, retained, now, t);
// The exact time belongs to the reset; beside a runs-out warning it would read as the moment
// the quota runs out.
const exactTime = isAtRisk ? null : formatResetTime(window.resetsAt, now, t);
const pace = usagePace(window, forecastAt, now);
const forecast = formatPace(pace, now, t);
const countdown = formatResetLabel(window.resetsAt, retained, now, t);
const exactTime = formatResetTime(window.resetsAt, now, t);
const value =
shownPct != null ? formatDisplayPct(shownPct, displayAs, i18n.resolvedLanguage, t) : "—";
@@ -64,9 +60,8 @@ export function UsageWindowBar({
value,
countdown,
exactTime,
isAtRisk,
forecast,
percent: shownPct ?? 0,
tone,
pinned,
};
@@ -86,7 +81,7 @@ export function UsageWindowBar({
accessibilityLabel={usageWindowRowLabel({
pinLabel,
value,
trailing: [countdown, exactTime].filter(Boolean).join(" · "),
trailing: [countdown, exactTime, forecast?.label].filter(Boolean).join(" · "),
})}
accessibilityState={accessibilityState}
aria-checked={pinned}
@@ -103,9 +98,8 @@ function WindowRowContent({
value,
countdown,
exactTime,
isAtRisk,
forecast,
percent,
tone,
pinnable,
pinned,
}: {
@@ -113,9 +107,8 @@ function WindowRowContent({
value: string;
countdown: string | null;
exactTime: string | null;
isAtRisk: boolean;
forecast: PaceLabel | null;
percent: number;
tone: UsageTone;
pinnable: boolean;
pinned: boolean;
}) {
@@ -130,12 +123,44 @@ function WindowRowContent({
</Text>
{pinnable ? <UsagePinGlyph pinned={pinned} /> : null}
</View>
<UsageMeter percent={percent} tone={tone} />
<UsageResetLine countdown={countdown} exactTime={exactTime} atRisk={isAtRisk} />
<UsageMeter percent={percent} tone={forecast?.tone ?? "default"} />
<UsageDatapointLine datapoints={[countdown, exactTime, forecast?.label ?? null]} />
</>
);
}
interface PaceLabel {
label: string;
tone: UsageTone;
}
function formatPace(
pace: ReturnType<typeof usagePace>,
now: number,
t: TFunction,
): PaceLabel | null {
switch (pace.kind) {
case "reached":
return { label: t("providerUsage.timing.limitReached"), tone: "danger" };
case "runsOut": {
const label =
Date.parse(pace.at) <= now
? t("providerUsage.timing.mayHaveRunOut")
: formatRunsOutLabel(pace.at, now, t);
return label ? { label, tone: "danger" } : null;
}
case "remaining":
return {
label: t("providerUsage.timing.projectedLeftAtReset", {
percentage: formatPct(pace.remainingAtResetPct),
}),
tone: pace.remainingAtResetPct <= 10 ? "warning" : "default",
};
case "unknown":
return null;
}
}
const ThemedPin = withUnistyles(Pin);
function UsagePinGlyph({ pinned }: { pinned: boolean }) {
@@ -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[] {
@@ -14,6 +14,7 @@ import { buildWorkspaceTabPersistenceKey } from "@/workspace-tabs/model";
import { archiveWorkspaceWithUndo, supportsWorkspaceArchiveUndo } from "@/workspace/archive-undo";
import {
archiveWorkspaceOptimistically,
runWorkspaceArchiveAttempt,
type WorkspaceArchiveTarget,
} from "@/workspace/workspace-archive";
@@ -56,7 +57,6 @@ export function useWorkspaceArchive(input: ArchiveWorkspaceInput): WorkspaceArch
} = input;
const { t } = useTranslation();
const toast = useToast();
const confirmingRef = useRef(false);
// The archive starts after the host answers and you confirm. By then you may have opened another
// workspace, so the redirect reads the selection from the latest render.
const onArchiveStartedRef = useRef(onArchiveStarted);
@@ -119,26 +119,12 @@ export function useWorkspaceArchive(input: ArchiveWorkspaceInput): WorkspaceArch
}, [diffStat, name, serverId, t, toast, warningLabels, workspaceDirectory]);
const archive = useCallback(() => {
// A second press while the host answers or the warning is open would ask twice.
if (confirmingRef.current) {
return;
}
void (async () => {
if (workspaceKind === "worktree") {
confirmingRef.current = true;
let confirmed: boolean;
try {
confirmed = await confirmWorktreeArchive();
} finally {
confirmingRef.current = false;
}
if (!confirmed) {
return;
}
}
await archiveWorkspaceRecord();
})();
}, [archiveWorkspaceRecord, confirmWorktreeArchive, workspaceKind]);
void runWorkspaceArchiveAttempt({
workspace: { serverId, workspaceId },
confirm: workspaceKind === "worktree" ? confirmWorktreeArchive : undefined,
archive: archiveWorkspaceRecord,
});
}, [archiveWorkspaceRecord, confirmWorktreeArchive, serverId, workspaceId, workspaceKind]);
return {
archive,
@@ -17,6 +17,30 @@ export interface WorkspaceArchiveTarget {
workspaceId: string;
}
const pendingArchiveAttempts = new Set<string>();
/** Checks and starts one archive at a time for a workspace. */
export async function runWorkspaceArchiveAttempt(input: {
workspace: WorkspaceArchiveTarget;
confirm?: () => Promise<boolean>;
archive: () => Promise<void>;
}): Promise<void> {
const { serverId, workspaceId } = input.workspace;
const key = JSON.stringify([serverId, workspaceId]);
if (pendingArchiveAttempts.has(key)) return;
pendingArchiveAttempts.add(key);
try {
if (input.confirm && !(await input.confirm())) return;
if (!isWorkspaceListed(input.workspace)) return;
// Archive hides the row synchronously. Undo can restore it and start a new
// archive while the previous daemon request is still settling.
return input.archive();
} finally {
pendingArchiveAttempts.delete(key);
}
}
interface WorkspaceArchiveClient {
archiveWorkspace: (workspaceId: string) => Promise<{ error: string | null; canceled?: boolean }>;
}
+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,
});
}
@@ -0,0 +1,164 @@
import type { Locator, Page } from "@playwright/test";
import { expect, test } from "../../app/e2e/support/fixtures";
import { gotoWorkspace } from "../../app/e2e/support/helpers/launcher";
function explorerSidebar(page: Page) {
return page.getByTestId("workspace-explorer-sidebar").filter({ visible: true });
}
async function useDesktopWindowChrome(page: Page, mode: "native-mac" | "custom-windows") {
await page.addInitScript((windowChromeMode) => {
Object.assign(window, {
paseoDesktop: {
platform: windowChromeMode === "native-mac" ? "darwin" : "win32",
windowChromeMode,
invoke: async () => null,
events: { on: async () => () => undefined },
getPendingOpenProject: async () => null,
window: {
getCurrentWindow: () => ({
isFullscreen: async () => false,
onResized: async () => () => undefined,
}),
},
},
});
}, mode);
}
function explorerToggle(page: Page, expanded: boolean) {
return page.getByRole("button", {
name: expanded ? "Close Explorer sidebar" : "Open Explorer sidebar",
exact: true,
expanded,
});
}
async function recordExplorerToggle(button: Locator) {
const recording = await button.evaluateHandle((target) => {
const measure = () => {
const glyph = target.querySelector("svg")?.getBoundingClientRect();
return {
connected: target.isConnected,
x: glyph?.x,
y: glyph?.y,
width: glyph?.width,
height: glyph?.height,
};
};
const before = measure();
const frames: ReturnType<typeof measure>[] = [];
const done = new Promise<void>((resolve) => {
target.addEventListener(
"click",
() => {
const start = performance.now();
const sample = () => {
frames.push(measure());
if (performance.now() - start < 300) requestAnimationFrame(sample);
else resolve();
};
requestAnimationFrame(sample);
},
{ once: true },
);
});
return { before, frames, done };
});
try {
await button.click();
return await recording.evaluate(async ({ before, frames, done }) => {
await done;
return { before, frames };
});
} finally {
await recording.dispose();
}
}
async function expectExplorerToggleHasNativeClickArea(toggle: Locator) {
const regions = await toggle.evaluate((button) => {
const rect = button.getBoundingClientRect();
const x = rect.x + rect.width / 2;
const y = rect.y + rect.height / 2;
return [
...document.querySelectorAll('[style*="app-region"], [data-window-no-drag], [role="button"]'),
]
.filter((element) => {
const bounds = element.getBoundingClientRect();
return bounds.left <= x && x < bounds.right && bounds.top <= y && y < bounds.bottom;
})
.map((element) => getComputedStyle(element).getPropertyValue("-webkit-app-region"))
.filter((region) => region === "drag" || region === "no-drag");
});
expect(regions).toContain("drag");
expect(regions.at(-1)).toBe("no-drag");
}
async function expectExplorerToggleInHeaderTabOrder(page: Page, expanded: boolean) {
const toggle = explorerToggle(page, expanded);
await toggle.focus();
await page.keyboard.press("Tab");
await expect(page.getByRole("button", { name: "Workspace actions", exact: true })).toBeFocused();
await page.keyboard.press("Shift+Tab");
await expect(toggle).toBeFocused();
}
async function expectExplorerToggleToHoldPosition(page: Page, expanded: boolean) {
const toggle = explorerToggle(page, expanded);
await expect(toggle).toBeVisible();
await expectExplorerToggleHasNativeClickArea(toggle);
const { before, frames } = await recordExplorerToggle(toggle);
await expect(explorerToggle(page, !expanded)).toBeVisible();
expect(before.width).toBeGreaterThan(0);
expect(frames.find((frame) => JSON.stringify(frame) !== JSON.stringify(before))).toBeUndefined();
}
test("keeps the Mac Explorer toggle in place across open and close", async ({
page,
withWorkspace,
}) => {
await page.setViewportSize({ width: 1440, height: 900 });
await useDesktopWindowChrome(page, "native-mac");
const { workspaceId } = await withWorkspace();
await gotoWorkspace(page, workspaceId);
await expectExplorerToggleInHeaderTabOrder(page, false);
await expectExplorerToggleToHoldPosition(page, false);
await expectExplorerToggleInHeaderTabOrder(page, true);
await expectExplorerToggleToHoldPosition(page, true);
await page.setViewportSize({ width: 930, height: 900 });
await expectExplorerToggleToHoldPosition(page, false);
await expectExplorerToggleToHoldPosition(page, true);
});
async function expectClearOfWindowControls(page: Page, action: Locator) {
const minimize = page.getByRole("button", { name: "Minimize window", exact: true });
await expect(minimize).toBeVisible();
await expect(action).toBeVisible();
const controlBounds = await minimize.boundingBox();
const actionBounds = await action.boundingBox();
expect(actionBounds!.x + actionBounds!.width).toBeLessThanOrEqual(controlBounds!.x);
}
test("keeps the Explorer actions clear of Windows controls", async ({ page, withWorkspace }) => {
await page.setViewportSize({ width: 1440, height: 900 });
await useDesktopWindowChrome(page, "custom-windows");
const { workspaceId } = await withWorkspace();
await gotoWorkspace(page, workspaceId);
const open = explorerToggle(page, false);
await expectClearOfWindowControls(page, open);
await open.click();
const close = explorerToggle(page, true);
const newExplorerTab = explorerSidebar(page).getByRole("button", {
name: "New tab",
exact: true,
});
await expectClearOfWindowControls(page, close);
await expectClearOfWindowControls(page, newExplorerTab);
await close.click();
await expect(open).toBeVisible();
});
+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({
+7 -7
View File
@@ -96,12 +96,12 @@ test.each([
])(
"duration %s owns the window's identity and both names",
(durationSeconds, id, label, shortLabel) => {
expect(
windowFromReportedDuration({
durationSeconds: durationSeconds as number | null,
unknown: { id: "primary", label: "Primary limit", shortLabel: "" },
utilizationPct: 11,
}),
).toMatchObject({ id, label, shortLabel, usedPct: 11 });
const window = windowFromReportedDuration({
durationSeconds: durationSeconds as number | null,
unknown: { id: "primary", label: "Primary limit", shortLabel: "" },
utilizationPct: 11,
});
expect(window).toMatchObject({ id, label, shortLabel, usedPct: 11 });
expect(window.durationSeconds).toBe(durationSeconds ?? undefined);
},
);
+11 -5
View File
@@ -16,6 +16,8 @@ export interface UsageWindow {
usedPct?: number | null;
remainingPct?: number | null;
resetsAt?: string | null;
/** Full length of the quota window when known. */
durationSeconds?: number;
runsOutAt?: string | null;
shortfallPct?: number | null;
tone?: "default" | "ok" | "warning" | "danger";
@@ -48,6 +50,8 @@ export type UsageReport =
| {
status: "available";
planLabel?: string;
/** When the provider measured the quota, if the report returns a previous reading. */
observedAt?: string;
windows: UsageWindow[];
balances?: UsageBalance[];
details?: UsageDetail[];
@@ -96,6 +100,7 @@ export function windowFromUsedPct(input: {
shortLabel?: string;
summary?: boolean;
utilizationPct: number | null | undefined;
durationSeconds?: number;
resetsAt?: string | null;
tone?: UsageWindow["tone"];
}): UsageWindow {
@@ -107,6 +112,7 @@ export function windowFromUsedPct(input: {
remainingPct: usedPct === null ? null : Math.max(0, 100 - usedPct),
resetsAt: input.resetsAt ?? null,
};
if (input.durationSeconds !== undefined) window.durationSeconds = input.durationSeconds;
if (input.shortLabel !== undefined) window.shortLabel = input.shortLabel;
if (input.summary) window.summary = true;
if (input.tone) window.tone = input.tone;
@@ -129,11 +135,10 @@ export function windowFromReportedDuration(input: {
summary?: boolean;
tone?: UsageWindow["tone"];
}): UsageWindow {
const duration = input.durationSeconds;
const name =
duration !== null && Number.isFinite(duration) && duration > 0
? durationWindowName(duration)
: input.unknown;
const reported = input.durationSeconds;
const duration =
reported !== null && Number.isFinite(reported) && reported > 0 ? reported : undefined;
const name = duration === undefined ? input.unknown : durationWindowName(duration);
const scope = input.scope;
return windowFromUsedPct({
id: scope ? `${scope.id}:${name.id}` : name.id,
@@ -142,6 +147,7 @@ export function windowFromReportedDuration(input: {
? `${scope.label}${name.shortLabel ? ` ${name.shortLabel}` : ""}`
: name.shortLabel,
utilizationPct: input.utilizationPct,
durationSeconds: duration,
resetsAt: input.resetsAt,
summary: input.summary,
tone: input.tone,
+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": [
+2
View File
@@ -6992,6 +6992,7 @@ export const ProviderUsageWindowSchema = z.object({
usedPct: z.number().nullable().optional(),
remainingPct: z.number().nullable().optional(),
resetsAt: z.string().nullable().optional(),
durationSeconds: z.number().optional(),
runsOutAt: z.string().nullable().optional(),
shortfallPct: z.number().nullable().optional(),
tone: ProviderUsageToneSchema.optional(),
@@ -7054,6 +7055,7 @@ export const UsageProblemSchema = z.discriminatedUnion("kind", [
const AvailableUsageReportSchema = z.object({
status: z.literal("available"),
planLabel: z.string().optional(),
observedAt: z.string().optional(),
windows: z.array(ProviderUsageWindowSchema),
balances: z.array(ProviderUsageBalanceSchema).optional(),
details: z.array(ProviderUsageDetailSchema).optional(),
+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,

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