Compare commits

..
Author SHA1 Message Date
Mohamed Boudra 3914893aa1 Troubleshoot providers from their settings page, and tidy provider settings (#10487)
* feat(providers): add docs links, sign-in facts and a tidier provider page

A user whose Antigravity models looked stale had no way to find out why
without asking in chat. agy 1.5.14 picks its sign-in from the
environment: with SSH_CONNECTION, SSH_CLIENT or SSH_TTY set it reads a
token file, otherwise the OS keyring
(google-antigravity/antigravity-cli#1336). The daemon is often started
outside SSH while the user tests agy over SSH, so the two can be signed
in to different accounts and list different models.

- The Antigravity status reports whether agy runs in an SSH session, and
  the diagnostic report for plugin providers now includes the resolved
  command, path and version like built-in providers do.
- Providers carry an optional docsUrl (protocol field, plugin SDK
  registration, built-in definitions). The provider page links it from
  Troubleshooting, and the Antigravity page documents the sign-in
  mismatch.
- Provider and project settings get a breadcrumb title. Refresh moves to
  the Models header, the model list scrolls inside a fixed height with a
  full-width search, and section headers keep one spacing whether or not
  they hold an action.
- A switch no longer makes its row taller than the track, and every
  settings row is at least as tall as one with a switch, so a switch row
  and a text row line up.

* fix(providers): report Antigravity's sign-in when ACP does not start

A sign-in problem can be what stops agy's ACP server from starting, so
the diagnostic report now shows the SSH session rows in that case too.

The plugin provider diagnostic test no longer compares the daemon PATH
and shell rows, which differ per host (Windows reports ComSpec).

* fix(server): show the same provider version in the report and Installation

The plugin diagnostic read the version by calling the provider's
inspect itself with a 10s deadline, while the Installation row reads it
through the installation service with a 20s deadline and a cache. A
version check between 10 and 20 seconds showed in Installation and as
an error in the report.

The snapshot manager now hands getDiagnostic an inspectInstallation
that reads through the installation service, so both show one answer
and agy --version runs once for both.

* feat(app): give rows that open something the same height as other rows

Detail rows and collapsible row headers reserved a button's height so a
list where only some rows held a switch kept one height. Now that every
settings row is at least as tall as a switch row, that reserve only made
rows like Diagnostic report and Docs taller than their neighbours.

* test(app): compare rows that open something with text and switch rows

* feat(app): size the provider icon to the page title

* fix(app): scale the provider title icon with the interface size
2026-11-22 15:13:31 +07:00
Mohamed BoudraandClaude ede181d39a Refresh enabled provider catalogues in the background every 30 minutes (#10481)
* Refresh enabled provider catalogues in the background every 30 minutes

A long-running daemon cached discovered models until a manual Refresh or a
restart, so a server-side model rollout stayed invisible. The daemon now
refreshes each enabled provider about every 30 minutes, one provider per
staggered slot. A recent refresh pushes the next one back. Background
refreshes join discovery already in flight, publish only changed
catalogues, and keep a ready catalogue when a probe fails.

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

* Keep background refresh slots independent and its probes soft

Ticks no longer wait for a refresh to settle, so one slow provider cannot
delay the others. A provider with a background refresh still running is
skipped. The due check uses a fixed one-second timer slack instead of half
a slot, so a manual refresh always pushes the next probe a full interval.
Background probes pass force: false so OpenCode keeps its shared server.
A result that is not ready keeps a ready catalogue, which covers plugin
status probes that report a failed startup as unavailable.

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

* Keep a ready catalogue when a background refresh returns a partial one

Claude falls back to its curated list without discovery-gated models when
model discovery fails or times out. That result is ready, so a background
refresh published it and Mythos left the picker. Providers now mark such a
catalogue incomplete, and a background refresh keeps the ready catalogue it
would have replaced. A manual refresh still publishes it.

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

* Kill OpenCode servers whose startup is pending at shutdown

A probe still allocating its port when the daemon stopped spawned its
OpenCode server after shutdown returned, and the process outlived the
daemon. Background refresh makes that overlap likelier. Shutdown now waits
for pending startups and kills the generations they produce.

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

* Stop running probes before provider shutdown

A probe checking availability when the daemon stopped could still go on to
discovery and start an OpenCode server after provider cleanup returned.
The manager now aborts every running probe through its refresh signal when
it stops, and shutdown waits up to ten seconds for them to settle before it
shuts down provider clients.

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

* Refuse OpenCode spawns from operations begun before shutdown

A rotation accepted before shutdown waited for the old server to stop and
then started a replacement after cleanup returned. The server manager now
counts shutdowns; every operation that can start a server records the
epoch it began in, and the spawn step refuses once a shutdown has passed.
Operations begun after shutdown still start, since the manager is a
process-wide singleton.

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

* Keep manual refresh precedence over concurrent background refreshes

* Avoid eager provider snapshot downloads for unobserved directories

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-22 14:50:02 +07:00
Mohamed Boudra c28aa2570c docs(website): refresh sponsor page visitor and Discord member counts (#10498)
Homepage and docs visitors use the site-wide Plausible figure for the 30 complete days to 2026-11-21 (107,693), rounded down to 100,000. Discord members come from the live guild count (2,678). The README figure is unchanged because GitHub only exposes 14 days of traffic.
2026-11-22 14:29:02 +07:00
Mohamed Boudra 08ad7c7271 Let agents steer or interrupt another agent's running turn, and tell them how their message was delivered (#10483)
* feat(server): let agents queue, steer, or interrupt messages to other agents

An agent sender's `steer` used to mean "wait for the turn to end", unlike a
person's steer. Agents now get the same three choices a person has, plus a
named default: `queue` waits for the turn end, `steer` joins the running turn
(interrupting when the provider cannot steer), and `interrupt` replaces it.
A steer or interrupt carries the messages queued ahead of it, so delivery
order still equals admission order.

The receipt returns the applied behavior and guidance built from whether the
recipient is running and whether its provider can steer. A queued message's
guidance tells the sender to follow up with a short steer or interrupt
instead of resending, because a resent message is read twice.

Older clients send `steer` for every default agent send, so the daemon maps
their agent `steer` to `queue` when the client lacks the
`agent_active_turn_behaviors` capability. New clients talking to an older
daemon refuse `steer` rather than silently queueing it.

* fix(server): keep a steer's carried messages when the turn ends first

A steer that reached the provider after the turn ended made the manager
throw a plain error, and delivery failed the whole batch, including the
queued messages the steer carried. The manager now throws
AgentTurnChangedError, and delivery sends the batch again, into the next
turn or as a new one.

Also report the applied activeTurnBehavior in `paseo send --no-wait`
output, and expect the new hello capability in the client test.

* docs(skills): warn that an unread steer loses the messages it carried

* docs(skills): shorten the send_agent_prompt guidance

Keep what a sender acts on: leave activeTurnBehavior out, the three
values, read the guidance, follow up instead of resending, and the
steer loss case. Drop delivery facts the sender cannot act on.

* fix(server): stop the send_agent_prompt description promising an unread steer survives
2026-11-22 14:01:15 +07:00
Mohamed Boudra b2ecec8719 fix(opencode): stop adding a "This chat uses OpenCode v2" row to chats (#10490)
The notice flagged chats moved to the then-new v2 runtime. v2 has been
stable, so the row is noise. Previously saved openCodeRuntimeNotices
metadata is left in place and no longer read.
2026-11-22 13:44:56 +07:00
paseo-bot[bot] fa37fd20ca Make the recursive watcher inventory test deterministic (#10462)
* test(server): make recursive watcher inventory test deterministic

Deliver the file creation notification explicitly so the inventory check does not depend on the native watcher becoming ready. Hold scheduled scans until the test checks the inventory and require reconciliation to report the deletion.

* test(server): wait for the watcher callback without advancing audits

---------

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-22 06:07:40 +00:00
ff5a83bc5a Keep stale slash menu choices from archiving agents (#10484)
* fix(app): ignore slash menu picks made before the menu filters

On web the cursor reaches the autocomplete after paint. A Tab or Enter
pressed right after typing could pick from the unfiltered list, where
/exit is the default highlight, and archive the agent. Skip the pick when
the typed command no longer matches the query the menu was built for.

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

* fix(app): limit the stale slash menu guard to key presses

Clicks also pass the live input snapshot, so the guard could drop a
click on a visible option while the cursor update was still pending.
A click picks what the user sees. Check for a stale menu only when Tab
or Enter selects.

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

---------

Co-authored-by: 3ae3ae <ogyshjsm@naver.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Bae Seongmin <83870598+3ae3ae@users.noreply.github.com>
2026-11-22 05:50:48 +00:00
Mohamed Boudra 9cb0625cf5 Start an edited New workspace after a failed creation, and unify composer errors (#10482)
* fix(app): allow edited New workspace retries and unify composer errors

New workspace and the workspace setup dialog reused the mount's raw draft
or creation ID as the workspace.create idempotencyKey. When workspace
provisioning failed before readiness, the daemon kept that key's request
fingerprint on disk, so editing isolation, project, branch, prompt, or
model on the same screen failed with workspace_request_key_conflict.

Deriving the workspace idempotencyKey with draftCreationKey(id, request)
matches #9534 for agent drafts: unchanged retries (double-click,
reconnect, or resending as-is) keep one key, while edited retries start a
new workspace creation without requiring daemon or protocol changes.

Also move composer submission errors into one <Alert variant="error"
size="sm" /> slot owned by <Composer> (directly above the input, and in
ComposerFullscreenFooter when fullscreen) so New workspace, Workspace
draft tab, Workspace setup dialog, and active chat share the composer's
outer and inner rails without duplicate error toasts.

* fix(app): include launch target in creation key and toast background failures

Include launchTarget when deriving the New workspace creation key so
switching between blank Chat and a promptless terminal profile after a
pre-ready failure starts a fresh creation instead of replaying the failed
receipt.

Also show toast.error when workspace creation fails after the user has
left New workspace or closed WorkspaceSetupDialog, while keeping the
single composer alert with no duplicate toast when the form is still
visible.

* fix(app): avoid duplicate toast when handed-off agent startup fails

Once New workspace hands a ready workspace to its draft tab, the draft
tab awaits agentCreation.result and displays startup errors in its own
composer alert. Returning early after handoff prevents New workspace's
catch handler from firing a duplicate app-wide toast.
2026-11-22 12:28:10 +07:00
Mohamed Boudra 03adc4d4ba Keep working host connections from flapping on busy heartbeats and back off background probes (#10395)
* fix(app): stop busy-heartbeat adaptive switches and back off online probes

Hosts with multiple saved connections still replaced healthy relay links
during active use: every 120 seconds the runtime compared an idle alternate
probe against the single latest heartbeat RTT on the busy active socket
using a fixed 40 ms threshold, then tore down the live socket before
connecting the replacement (leaving the host in connecting for ~2 s).

Use the 60-second rolling minimum of active heartbeats as the baseline,
require at least max(40 ms, 35% of baseline RTT) improvement to switch,
exponentially back off inactive online probes from 2m to 30m while the
active connection keeps winning (resetting on candidate win, reconnect,
connection list changes, or foreground verify), and connect the replacement
before disposing the live client on adaptive switches.

Closes #9149

* fix(app): preserve active listener, recheck candidate, and refresh caches on make-before-break upgrade

Keep installed active-client status listeners bound to `this.activeClient`
rather than `switchRequestVersion` so a pending or failed speculative
upgrade never mutes disconnect events on the active socket. Recheck that
the target connection still exists and matches before and after disposing
the old client so removing or editing an endpoint during handshake aborts
the upgrade. Track the last online `connectionEpoch` in `HostRuntimeStore`
so make-before-break upgrades that stay `online` still trigger reconnect
cache invalidation and history sync generation bumps.
2026-11-22 11:27:27 +07:00
Mohamed Boudra 4b429c0030 Prevent zombie processes after plugin startup and reload (#10470)
* fix(server): prevent zombie children after plugin builds

Retiring a compiler thread closed its libuv loop while esbuild still owned a native child. Run the compiler in a subprocess so the daemon can reap it when the idle compiler disconnects.

* test(ci): check plugin compiler reaping on macOS
2026-11-22 11:11:59 +07:00
Mohamed Boudra 20f217b8cb fix(acp): finish Antigravity turns after recurring schedules (#10469)
Antigravity returns end_turn while a recurring schedule stays in progress. Exclude cron registration from the provider's deferred-turn blockers so waiting for a tool completion cannot strand the foreground turn.
2026-11-22 11:11:55 +07:00
Mohamed Boudra 984e2ea5e7 Lead the 0.17.1 changelog with Antigravity and keep instructions out of release notes (#10466)
* docs(changelog): lead 0.17.1 with Antigravity and cut instructions from the entry

The 0.17.1 entry ranked Antigravity seventh and carried setup steps, click
paths, migration notes, and edge-case qualifiers. Each highlight is now one
sentence that announces the change, and Antigravity leads. Two details that
left their highlight keep their own bullet: plugin worktree management moves
to Plugins and green quota bars move to Changed.

docs/release.md allowed highlights up to three sentences and exempted them
from the conciseness rules, which is how the instructions got in. The rules
now cover highlights too, permit a second sentence only for a breaking
requirement, and put the headline change first whatever its ordering group.

* docs(changelog): keep shortened 0.17.1 bullets within what shipped

Three bullets lost a clause that limited their claim: provider updates exist
only for CLIs with an update command, the scroll fix leaves out HTML previews
on iOS, and Git status reloads when files changed during the disconnect. Each
bullet now names what it covers instead of carrying an exception clause, and
the release guide says to shorten that way.

The Antigravity requirement links the setup page, which has the `acp`
argument a custom command needs.

* docs(changelog): scope the agent message and quota forecast highlights

An explicit interrupt from another agent still replaces the running turn, and
Usage shows a run-out time only for a quota on pace to run out before it
resets. Both highlights now say so in one sentence, and the release guide uses
the agent message highlight as its example of keeping that distinction.

Rewind in Command Center applies to the latest turn, so the bullet names it
again.

* docs(antigravity): explain the Hub model error after the CLI upgrade

The 0.17.1 highlight used to carry this recovery step. The highlight now links
the setup page, so the step lives there in both languages.
2026-11-22 10:14:31 +07:00
paseo-ai[bot] 133b078ac4 fix: update lockfile signatures and Nix hash [skip ci] 2026-11-21 22:46:04 +00:00
Mohamed Boudra 6ea095cb49 chore(release): reconcile v0.17.1 (#10457) 2026-11-22 05:36:59 +07:00
Mohamed Boudra f7e2ab4076 Keep the full history when reopening a long Antigravity agent after a restart (#10428)
* fix(acp): keep the whole history when an agent streams it after session/load

Reopening a long Antigravity agent after a daemon restart lost the end of its
timeline. When the client reads slowly, agy answers session/load part-way
through the history and keeps streaming the rest, with no end marker. The
replay window closed after a fixed five quiet periods (1 s), and every history
update processed after that was discarded as stale.

The window now closes only once a quiet period passes without a history
update. Command, configuration, mode and usage updates no longer count as
activity, so they cannot hold the session open. When the quiet period expires,
the loop reads pending input once before the silence is trusted, because a
stalled event loop reaches the timer with history still unread in the pipe.

The wait has no upper bound: any bound is another way to truncate, and the
agent goes silent once its history is sent.

* fix(acp): stop waiting for history replay when the connection closes

With the replay wait no longer capped, closing the provider connection while a
session was still replaying waited for the whole history, so a daemon stop
during a long reopen could run past its deadline. The connection marks itself
closed and then awaits in-flight opens, but the replay wait only checked the
runtime's own closing flag. The wait now also ends when the connection closes.

* fix(acp): only extend replay on history updates and fail open on mid-replay crash

* fix(server): bound shutdown flush so provider shutdown cancels in-flight reopens

* fix(acp): keep load replay open while a multi-read wire record is in flight
2026-11-22 04:01:42 +07:00
paseo-bot[bot] 2445adecdf fix(app): finish custom model saves when the daemon confirms them (#10432)
The daemon already schedules catalog discovery when provider configuration changes. Waiting on a second discovery kept the Add sheet open after the model was saved.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-21 18:33:44 +00:00
paseo-bot[bot] 0c02cfdfb1 fix(app): keep the composer focus hint from covering the placeholder (#6200)
* fix(app): keep the composer focus hint off the placeholder

The web composer draws its focus shortcut hint over the input's top-right
corner. When the placeholder and the hint did not fit on one line, as in
French at a phone width or with the longer desktop placeholder, the hint
was drawn on top of the end of the placeholder. The input now reserves
the hint's width as right padding while the hint shows, so the
placeholder wraps before it.

Closes #6191

* test(app): wait for the focus hint padding before checking overlap

* Keep focus hint padding in sync with composer layout

Reveal the shortcut after the input reserves space for its label. Remeasure draft height when padding changes the available text width.

---------

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-21 15:56:48 +00:00
paseo-ai[bot] 2098eb787c fix: update lockfile signatures and Nix hash [skip ci] 2026-11-21 13:55:05 +00:00
Mohamed Boudra 9c4106561a Refresh the Paseo Hub website (#10309)
* feat(website): refresh Paseo Hub page and add homepage Hub entry points

* chore(website): align Hub automation source copy and team visibility wording

* chore(website): simplify homepage Hub flow layout and remove highlight cards

* feat(website): unify page frame, rails, section rhythm, and hairline grids across home and /hub

* chore(website): remove forced eyebrow numbering and redundant section eyebrows

* feat(website): use Plus Jakarta Sans for display titles

* style(website): remove hairline rails from header and hero bands

* feat(website): derive landing page plugin count from published registry

* feat(website): replace Hub Discord demo with animated Slack mockup

* style(website): tighten display-scale Paseo Hub lockup gap

* website: interactive source showcase on /hub automations section

* website: prevent font-swap wrap jank and remove left bar on /hub source pills

* fix(website): align Hub examples and docs with service behavior

* fix(website): keep navigation and plugin carousels within the page frame

* fix(website): address Hub refresh review findings

* fix(website): preserve focus and labels in Hub showcase tabs

* fix(website): show the selected Hub preview immediately

* fix(website): keep Hub pricing tooltips inside their cards

* fix(website): wrap Hub source labels with larger text

* fix(website): scale Hub preview height with browser text

* fix(website): wrap long identifiers in Hub previews

* fix(website): wrap result chips in the Hub schedule preview

* fix(website): keep the Discord preview thread title readable

* fix(website): let Hub source descriptions wrap

* feat(website): link Hub previews to their trigger guides

Keep the self-hosting guides aligned with the Hub documentation already on main.

* fix(website): keep Hub previews readable at large font sizes

Let preview rows stack when the frame is too narrow for the avatar, padding, and text. Check the rendered text bounds at twice the default font size.
2026-11-21 20:47:56 +07:00
Mohamed Boudra c1c29fcb56 Deliver queued agent messages in order, so an interrupt never leaves a stale steer behind (#10404)
* fix(server): deliver an agent's messages in the order they were queued

An agent's interrupt was dispatched alone, ahead of the steers queued before
it. Those steers stayed queued and started a turn of their own after the
interrupt's turn ended, so a stale instruction ran after the newer message
that countermanded it.

The queue now keeps one ordered list per recipient and only ever dispatches
its front. An interrupt releases at admission and takes the older messages
along in the same replacing prompt. A person's prompt takes the queue along
the same way. Stop holds the queue for the recipient's next prompt instead
of releasing it into a new turn, and does not drop it: the queue also
carries finish notifications.

A quiet window now closes after ten seconds at most, so steady arrivals
cannot delay a waiting message without bound.

* fix(server): keep a prompt's place in line until the provider admits it

The queue removed a message when it handed the prompt to the agent
manager, before the provider had admitted it. In that gap the order was
no longer the queue's to decide:

- a person's prompt or a later interrupt sent while the provider was
  still starting a turn could pass a prompt that was admitted first;
- Stop during that start no longer saw the interrupt waiting to replace
  the turn, so the interrupt started a turn after the Stop;
- queued messages that rode a person's prompt were settled when the
  prompt was handed over, so a turn the provider rejected dropped them.

A message now stays in its recipient's list until the provider admits
the prompt that carries it, fails it, or the message is withdrawn. Every
prompt takes its place at admission, one operation acts on a recipient
at a time, and each operation covers only what was admitted before it
got in line. Stop holds every message still in the list and clears the
interrupt's urgency, so a held interrupt waits like a steer.

A prompt is a command only when it starts with a slash and a name with
no second slash, matching how providers read it. A prompt that begins
with a path now carries the queue like any other text. An interrupt the
provider runs as a command beside the turn takes no queued message
along, because it replaces nothing.

Test wiring that builds the MCP catalog or stubs the agent manager now
supplies the delivery module and the stop signal the server requires.

* fix(server): keep queue decisions made before a Stop or shutdown from going stale

Three races in the window where the provider is still starting or
stopping a turn:

- An interrupt admitted while a polling queue step was already in line
  got no step of its own. A person's steer sent next took the interrupt
  along and steered the turn the interrupt should have replaced. An
  interrupt now always reserves its place at admission.
- A dispatch in flight when Stop arrived checked the queue's phase to
  learn it was void. A message admitted before the provider answered
  moved the queue out of `held`, so the old dispatch became valid again:
  an interrupt from before the Stop started a turn alone, and a batch
  whose starting turn Stop canceled was rejected instead of kept. Each
  dispatch now records the Stops its recipient had seen when it was
  decided and is void once that count changes.
- Shutdown drained only what was queued when it began, so messages a
  rejected person's turn returned afterwards were left to the retry
  timer. The drain now runs after the operation in flight and reads the
  queue then.

* fix(server): void queue steps that were reserved before a Stop

A queue step that was already in line when Stop arrived checked for a
Stop only from the moment it ran. When an interrupt arrived while the
provider was still stopping, the queue left `held`, and the old step
started a turn with the held messages. The new interrupt then replaced
that turn in a second one.

A step now watches for a Stop from the moment it reserves its place and
does nothing once one has arrived. The held messages go with the next
prompt admitted after the Stop, in one turn.

The interleaving test gains a variant with a provider that is slow to
answer. It checks, for every five-step sequence, that no queue dispatch
after a Stop carries only messages from before it.

* fix(server): hold the queue again when the message that reopened it is withdrawn

After a Stop, a message admitted later reopens the queue and takes the
held messages along. When that message was withdrawn before its quiet
window closed, for example a change-request update whose watch was
cancelled, the window still fired and the held messages started a turn
on their own.

A Stop now marks the messages it finds. When a withdrawal leaves only
marked messages, the queue is held again and waits for the next prompt.

* docs(server): state that cancel_agent with no turn to stop holds nothing

Stop holds the queue only when it stops a running or starting turn.
On an idle recipient cancel_agent reports that it canceled no run, and
a queued steer keeps its quiet window. The lifecycle doc says so and a
daemon-level test pins it.

* docs(server): state when a queued message counts as delivered

A message leaves the queue when the agent manager acknowledges the start
of the turn that carries it. A turn that fails after that point is not
delivered again, and a start that is not acknowledged within 60 seconds
returns the messages a person's prompt carried.
2026-11-21 20:41:28 +07:00
Mohamed Boudra 1e30f9e046 Polish Usage quota bars, labels, and forecasts (#10397)
* fix(usage): clarify quota labels and show weekly forecasts sooner

* fix(usage): show the exhaustion time and keep exhausted bars red

* fix(usage): hide forecast text for quotas on track

* fix(usage): label quota times by local calendar date

* test(usage): keep the exhaustion clock test stable at midnight
2026-11-21 20:08:09 +07:00
paseo-bot[bot] 6946d0a429 fix(workspace): publish checkout status after restore (#10406)
A client that read checkout status while the worktree was absent can keep that response after Restore. Send the current status to subscribed clients before publishing the recovered workspace.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-21 12:39:02 +00:00
paseo-bot[bot] 344da5d088 Let every split divider drag after panes are added to a resized row (#5996)
* fix(app): let every split divider drag after panes are added to a resized row

Divider drags store sizes per group id, apart from the layout tree. A group
keeps its id when panes are added, so after resizing a row and splitting it
again the stored list had fewer entries than panes, and dividers past its end
could not move. Use the dragged sizes only while they have one entry per pane.

Closes #5893

* refactor(app): choose split group sizes at the call site

* test(app): take the page from the divider locator in the split resize spec

* test(app): name the split resize helper arguments

---------

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-21 11:56:09 +00:00
Mohamed Boudra 01aa8b3406 Verify releases on isolated release branches and harden shipping (#10396)
* chore(release): verify releases on isolated release branches and harden shipping

High-traffic merges on main cancel more than half of main CI runs, so waiting on main CI repeatedly stalls releases. Releases also ran duplicate post-tag CI, lacked a release-branch Desktop Packages trigger, hit unretried Apple notarytool polling errors and a finalize-rollout directory bug on macOS retries, and relied on a non-idempotent npm publish chain and conflict-prone reconcile cherry-picks.

This splits release execution into release:prep:* (reversible version commit without tagging, pushed once to release/** for isolated CI + Desktop Packages) and release:ship[:beta] (idempotent npm publishing with retry, propagation checks, automatic beta dist-tag sync on stable, and release/*-only tag push), adds conflict-free main reconciliation, and extends macOS xcrun retries to notarytool submit and wait.

* fix(release): address review findings on Docker retries, tag push, and reconciliation

Isolate manual Docker publish dispatches in their own non-cancelling concurrency group, verify HEAD matches origin/<release-branch> before release:ship publishes or tags (and remove one-shot combined scripts that bypassed release-branch checks), drop --refs from peeled annotated-tag lookups in push-current-release-tag.mjs, retry lockfile sync in reconcile-release.mjs when package-lock.json version lags package.json, and document cutting from pre-existing tags.

* fix(release): preserve TTY OTP prompts in npm publish and keep newer beta changelogs

Inherit TTY stdin/stdout for interactive npm publish and dist-tag add (plus --otp passthrough) while keeping stderr piped for retry classification, and keep newer beta or promoted stable changelog entries intact when an older beta tag is reconciled.
2026-11-21 18:32:08 +07:00
Mohamed Boudraandtabulius-ux d816b94c54 Show workspace archive progress across sessions (#10391)
Share the archive marker across connections so clients and plugins see when a workspace is being archived.

Closes #7698

Co-authored-by: tabulius-ux <252143044+tabulius-ux@users.noreply.github.com>
2026-11-21 17:08:42 +07:00
Mohamed Boudraandtabulius-ux 4c0bf97dbf Honor the working directory when resuming Codex (#10390)
Codex loads configuration and starts MCP servers while restoring the thread. Send the session directory during resume so those steps use the requested workspace.

Closes #7699

Co-authored-by: tabulius-ux <252143044+tabulius-ux@users.noreply.github.com>
2026-11-21 17:08:23 +07: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
388 changed files with 31366 additions and 7357 deletions
+15 -4
View File
@@ -2,7 +2,7 @@ name: CI
on:
push:
branches: [main]
branches: [main, "release/**"]
# Every base branch, so stacked PRs and PRs into any base get the same checks.
pull_request:
merge_group:
@@ -56,7 +56,7 @@ jobs:
filters: .github/ci-paths.yml
- name: Validate CI contracts
run: node --test scripts/ci-workflow.test.mjs scripts/daemon-launch-contract.test.mjs scripts/changelog-utils.test.mjs scripts/sync-fdroid-changelogs.test.mjs scripts/sync-release-notes-from-changelog.test.mjs scripts/upload-release-assets.test.mjs
run: node --test scripts/ci-workflow.test.mjs scripts/daemon-launch-contract.test.mjs scripts/changelog-utils.test.mjs scripts/release-version-utils.test.mjs scripts/publish-release-packages.test.mjs scripts/push-current-release-tag.test.mjs scripts/reconcile-release.test.mjs scripts/sync-fdroid-changelogs.test.mjs scripts/sync-release-notes-from-changelog.test.mjs scripts/upload-release-assets.test.mjs
quality:
name: quality
@@ -278,8 +278,8 @@ jobs:
# native-recursive.ts serves darwin and win32, but windows-latest above is the only
# runner that exercises it. macOS — the platform the reported watcher bug was on —
# otherwise has no server-test coverage. Scoped to the observer/watcher suites to
# bound runtime.
# otherwise has no server-test coverage. Keep this job scoped to regressions
# reported on macOS.
server-tests-macos:
name: server-tests (macos-latest, file observation)
needs: changes
@@ -307,6 +307,12 @@ jobs:
src/server/workspace-git-service.observation.integration.test.ts \
--bail=1
- name: Verify plugin compiler children are reaped
run: |
npm run test:unit --workspace=@getpaseo/server -- \
src/server/plugins/index.posix.test.ts \
-t "reaps compiler children" --bail=1
desktop-tests-ubuntu:
name: desktop-tests (ubuntu-latest)
needs: changes
@@ -579,6 +585,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
+3 -2
View File
@@ -2,7 +2,7 @@ name: Desktop Packages
on:
push:
branches: [main]
branches: [main, "release/**"]
# Packaging leaves ordinary PR CI, but a PR that changes what gets packaged
# or how it is smoked still proves the real artifacts before merge.
pull_request:
@@ -11,10 +11,11 @@ on:
- "plugins/**"
- "nix/**"
- ".github/workflows/desktop-packages.yml"
workflow_dispatch:
concurrency:
group: desktop-packages-${{ github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
cancel-in-progress: true
permissions:
contents: read
+6 -27
View File
@@ -170,33 +170,11 @@ jobs:
run: |
set -euo pipefail
export PASEO_REAL_XCRUN="$(command -v xcrun)"
stapler_bin="$(mktemp -d)"
trap 'rm -rf "$stapler_bin"' EXIT
cat > "$stapler_bin/xcrun" <<'STAPLER'
#!/bin/bash
if [[ "${1:-}" != stapler || "${2:-}" != staple ]]; then
exec "$PASEO_REAL_XCRUN" "$@"
fi
output="$(mktemp)"
trap 'rm -f "$output"' EXIT
for attempt in 1 2 3 4; do
if "$PASEO_REAL_XCRUN" "$@" >"$output" 2>&1; then
cat "$output"
exit 0
else
status=$?
fi
cat "$output"
if [[ "$status" != 68 || "$attempt" == 4 ]] ||
! grep -Fq 'NSURLErrorDomain Code=-1005' "$output"; then
exit "$status"
fi
echo "::warning::Apple staple connection lost; retrying the same signed app ($attempt/4)" >&2
sleep 30
done
STAPLER
chmod +x "$stapler_bin/xcrun"
export PATH="$stapler_bin:$PATH"
xcrun_bin="$(mktemp -d)"
trap 'rm -rf "$xcrun_bin"' EXIT
cp scripts/macos-xcrun-retry.sh "$xcrun_bin/xcrun"
chmod +x "$xcrun_bin/xcrun"
export PATH="$xcrun_bin:$PATH"
build_args=(-- --publish never --mac --${{ matrix.electron_arch }})
build_args+=("-c.publish.releaseType=$RELEASE_TYPE")
build_args+=("-c.publish.channel=$RELEASE_CHANNEL")
@@ -502,6 +480,7 @@ jobs:
shell: bash
run: |
set -euo pipefail
mkdir -p release-manifests
cd release-manifests
manifests_dir="$PWD/final"
mkdir -p "$manifests_dir"
+2 -2
View File
@@ -29,8 +29,8 @@ on:
- "true"
concurrency:
group: docker-${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: false
group: docker-${{ github.workflow }}-${{ github.event_name == 'workflow_dispatch' && inputs.publish == 'true' && format('publish-{0}', inputs.paseo_version || github.run_id) || github.ref }}
cancel-in-progress: ${{ !startsWith(github.ref, 'refs/tags/') && !(github.event_name == 'workflow_dispatch' && inputs.publish == 'true') }}
env:
REGISTRY: ghcr.io
+1
View File
@@ -3,6 +3,7 @@ name: Nix
on:
push:
branches: [main]
workflow_dispatch:
permissions:
contents: read
+53 -15
View File
@@ -1,56 +1,94 @@
# Changelog
## 0.17.0-beta.1 - 2026-11-19
## 0.17.1 - 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))
- **Antigravity approvals and history:** Choose a permission mode, answer tool approvals, and import or reopen sessions. Requires [Antigravity CLI 1.5.0 or later](https://paseo.sh/docs/supported-providers/antigravity). ([#10193](https://github.com/getpaseo/paseo/pull/10193))
- **Use existing worktrees:** Start a workspace in a worktree you already have, or create one from a branch or pull request. ([#10190](https://github.com/getpaseo/paseo/pull/10190))
- **Update providers in Paseo:** See each provider's status and installed version, and update supported CLIs from the app. ([#9568](https://github.com/getpaseo/paseo/pull/9568), [#9661](https://github.com/getpaseo/paseo/pull/9661))
- **Provider quota forecasts:** Usage shows when your current pace will use up a quota before it resets. ([#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 pull or merge request for new checks, reviews, and comments. ([#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))
- **Agent messages wait their turn:** By default, messages from other agents wait for the current turn to end. ([#9757](https://github.com/getpaseo/paseo/pull/9757), [#10404](https://github.com/getpaseo/paseo/pull/10404))
- **More goose models:** Select models from every provider configured in goose. ([#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 skills to `/` suggestions ([#10383](https://github.com/getpaseo/paseo/pull/10383))
- Added bundled orchestration skills to Antigravity ([#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 a separate Ultracode toggle for Claude ([#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 ([#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 content width to Default, Wide, and Full presets that also resize open chats and Markdown previews ([#10231](https://github.com/getpaseo/paseo/pull/10231))
- Changed Antigravity tool cards to show shell commands, output, and file diffs ([#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 healthy quota bars in Usage to green ([#10397](https://github.com/getpaseo/paseo/pull/10397))
- Changed worktree teardown to keep the worktree when the command times out ([#9852](https://github.com/getpaseo/paseo/pull/9852) by [@ragokan](https://github.com/ragokan))
- Changed workspace navigation on mobile to acknowledge taps sooner ([#9887](https://github.com/getpaseo/paseo/pull/9887))
- Changed workspace Git status to skip its reload after a short reconnect with no file changes ([#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))
- 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 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))
### Fixed
- Fixed an online host's workspaces going missing ([#10318](https://github.com/getpaseo/paseo/pull/10318))
- Fixed chat history timing out when many open chats refresh 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 agents failing to recover after stopping a foreground daemon with Ctrl+C ([#10381](https://github.com/getpaseo/paseo/pull/10381))
- Fixed long Antigravity chats losing the end of their history after a daemon restart ([#10428](https://github.com/getpaseo/paseo/pull/10428))
- Fixed Antigravity turns ending while a background command is still running ([#10310](https://github.com/getpaseo/paseo/pull/10310))
- Fixed the Add model sheet staying open after saving a custom model ([#10432](https://github.com/getpaseo/paseo/pull/10432))
- Fixed slash suggestions failing when a provider reports duplicate command names ([#10275](https://github.com/getpaseo/paseo/pull/10275))
- Fixed resumed Codex sessions using their previous working directory for configuration and MCP servers ([#10390](https://github.com/getpaseo/paseo/pull/10390) by [@tabulius-ux](https://github.com/tabulius-ux))
- 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 when several 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), [#10406](https://github.com/getpaseo/paseo/pull/10406))
- Fixed split-pane dividers stopping or lagging during drags ([#5996](https://github.com/getpaseo/paseo/pull/5996))
- 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 web composer's focus shortcut hint overlapping the placeholder ([#6200](https://github.com/getpaseo/paseo/pull/6200))
- 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 other sessions and plugins seeing a workspace as active while another session is archiving it ([#10391](https://github.com/getpaseo/paseo/pull/10391) by [@tabulius-ux](https://github.com/tabulius-ux))
- 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 ([#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 repeated finish notifications while an agent responds to background tasks ([#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 changing the Claude thinking level 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 Markdown previews and source views losing their scroll position when switching between them ([#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 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 plugin control of worktree creation, removal, and restoration ([#10278](https://github.com/getpaseo/paseo/pull/10278))
- Added a `focusHost` navigation option that selects the destination host in the sidebar ([#5574](https://github.com/getpaseo/paseo/pull/5574) by [@discwl](https://github.com/discwl))
## 0.16.2 - 2026-11-18
+52 -14
View File
@@ -1,56 +1,94 @@
# Changelog
## 0.17.0-beta.1 - 2026-11-19
## 0.17.1 - 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))
- **Antigravity 审批和历史记录**:选择权限模式、回复工具审批,以及导入或重新打开会话。需要 [Antigravity CLI 1.5.0 或更高版本](https://paseo.sh/zh-CN/docs/supported-providers/antigravity)。([#10193](https://github.com/getpaseo/paseo/pull/10193))
- **使用现有 worktree**:在已有的 worktree 中启动工作区,或从分支或 PR 创建 worktree。([#10190](https://github.com/getpaseo/paseo/pull/10190))
- **在 Paseo 中更新 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 监视 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))
- **Agent 消息排队等待**:默认情况下,其他 Agent 的消息会等当前轮次结束后再送达。([#9757](https://github.com/getpaseo/paseo/pull/9757), [#10404](https://github.com/getpaseo/paseo/pull/10404))
- **更多 goose 模型**:从 goose 中已配置的所有 Provider 选择模型。([#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))
- 为 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))
- 新增 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 会话新增列出已连接 daemon 项目的能力 ([#10392](https://github.com/getpaseo/paseo/pull/10392))
- 新增 `paseo ls --json` 输出的标签和工作区 ID ([#10076](https://github.com/getpaseo/paseo/pull/10076))
### 变更
- 将内容宽度改为默认、宽版和全宽预设,并同时调整已打开对话和 Markdown 预览的宽度 ([#10231](https://github.com/getpaseo/paseo/pull/10231))
- Antigravity 工具卡片现在显示 shell 命令、输出和文件 diff ([#10379](https://github.com/getpaseo/paseo/pull/10379))
- 从 GitHub 克隆时,优先显示匹配的私有仓库 ([#10264](https://github.com/getpaseo/paseo/pull/10264))
- “使用情况”页面中健康的配额进度条改为绿色 ([#10397](https://github.com/getpaseo/paseo/pull/10397))
- worktree 清理命令超时时保留 worktree ([#9852](https://github.com/getpaseo/paseo/pull/9852),贡献者:[@ragokan](https://github.com/ragokan))
- 手机端工作区导航更快响应点击 ([#9887](https://github.com/getpaseo/paseo/pull/9887))
- 短暂重连且文件未更改时,工作区 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))
- 工作区 Git 状态在短暂重连且检出的内容未更改时复用之前的快照 ([#10142](https://github.com/getpaseo/paseo/pull/10142),贡献者:[@VladimirGVP](https://github.com/VladimirGVP))
- 工作区导航会立即响应点击,并在手机端初始加载时减少屏幕外的对话行数 ([#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))
### 修复
- 修复在线主机的工作区不显示的问题 ([#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))
- 修复用 Ctrl+C 停止前台 daemon 后 Agent 恢复失败的问题 ([#10381](https://github.com/getpaseo/paseo/pull/10381))
- 修复 daemon 重启后较长的 Antigravity 对话丢失末尾历史记录的问题 ([#10428](https://github.com/getpaseo/paseo/pull/10428))
- 修复 Antigravity 后台命令仍在运行时轮次就已结束的问题 ([#10310](https://github.com/getpaseo/paseo/pull/10310))
- 修复保存自定义模型后“添加模型”弹窗一直保持打开的问题 ([#10432](https://github.com/getpaseo/paseo/pull/10432))
- 修复 Provider 返回重复命令名称时,斜杠建议列表出错的问题 ([#10275](https://github.com/getpaseo/paseo/pull/10275))
- 修复恢复的 Codex 会话的配置和 MCP 服务器仍沿用旧工作目录的问题 ([#10390](https://github.com/getpaseo/paseo/pull/10390),贡献者:[@tabulius-ux](https://github.com/tabulius-ux))
- 修复重新打开或回退父对话后,Codex 子 Agent 状态未更新的问题 ([#10171](https://github.com/getpaseo/paseo/pull/10171),贡献者:[@AnalyticETH](https://github.com/AnalyticETH))
- 修复切换 Claude 账号后,“使用情况”页面仍显示上一个账号配额的问题 ([#10236](https://github.com/getpaseo/paseo/pull/10236))
- 修复固定多个用量窗口时,侧边栏用量行隐藏周期标签的问题 ([#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), [#10406](https://github.com/getpaseo/paseo/pull/10406))
- 修复拖动分屏分隔条时卡住或跟手缓慢的问题 ([#5996](https://github.com/getpaseo/paseo/pull/5996))
- 修复 diff 中双击选词和三击选行的问题 ([#10252](https://github.com/getpaseo/paseo/pull/10252),贡献者:[@pedrovieira](https://github.com/pedrovieira))
- 修复启用聊天大纲时,Composer 与对话栏对不齐的问题 ([#10277](https://github.com/getpaseo/paseo/pull/10277))
- 修复网页版 Composer 的聚焦快捷键提示遮挡占位符文字的问题 ([#6200](https://github.com/getpaseo/paseo/pull/6200))
- 修复当前工作区所在的侧边栏分组折叠时,归档快捷键失效的问题 ([#10356](https://github.com/getpaseo/paseo/pull/10356),贡献者:[@hiennd-ctrl](https://github.com/hiennd-ctrl), [@neihyud](https://github.com/neihyud))
- 修复一个会话正在归档工作区时,其他会话和插件仍将其显示为活跃状态的问题 ([#10391](https://github.com/getpaseo/paseo/pull/10391),贡献者:[@tabulius-ux](https://github.com/tabulius-ux))
- 修复在 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))
- 修复 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))
- 修复在预览和源码之间切换时 Markdown 预览和源码视图丢失滚动位置的问题 ([#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))
### 插件
- 新增插件对 worktree 创建、移除和恢复的管理能力 ([#10278](https://github.com/getpaseo/paseo/pull/10278))
- 新增插件导航 `focusHost` 选项,用于在侧边栏选中目标主机 ([#5574](https://github.com/getpaseo/paseo/pull/5574),贡献者:[@discwl](https://github.com/discwl))
## 0.16.2 - 2026-11-18
+21 -5
View File
@@ -150,13 +150,29 @@ Users can also detach an existing subagent from the subagents track. Detach is d
`notifyOnFinish` defaults to `true` for agent-scoped creation and prompt follow-ups because most delegated work needs to report back to the creating agent. Set it to `false` for explicit reporting or no completion callback.
Agent-originated messages and automatic notifications share a recipient-daemon delivery module. A queued receipt acknowledges admission before provider dispatch. Idle recipients retain the two-second quiet window. While a recipient has a running or starting turn (including compaction), messages stay queued across quiet windows and are delivered together after that turn settles, including failure or cancellation. A ready batch is released when the daemon observes the recipient settle; the two-second timer also retries it. Agent callers using `steer`, including the default, wait for the turn to end; only explicit `interrupt` replaces a running turn. An explicit interrupt or a command the provider accepts out of band runs before earlier queued messages. Those messages stay queued and are delivered after the running or replacement turn ends. Human prompts dispatch directly with their existing behavior. Conflicting session-mode choices retain separate ordered dispatches.
Agent-originated messages and automatic notifications share a recipient-daemon delivery module. A queued receipt acknowledges admission before provider dispatch. The module keeps one ordered queue per recipient, and the recipient reads its prompts in the order the daemon admitted them. Nothing overtakes an older queued message. A prompt takes its place when the daemon admits it, even while the provider is still starting an earlier turn, and a message stays in the queue until the turn that carries it starts. The turn has started when the agent manager acknowledges the run start; a turn that fails after that point is not delivered again.
The pending message window is in memory. Clean shutdown flushes it before closing agents; an abrupt
crash can lose queued prompts. A durable send receipt remains pending until actual dispatch
An agent sender picks `queue`, `steer`, or `interrupt` with `activeTurnBehavior`. `steer` and `interrupt` mean what they mean for a person. A person's send has no `queue`. Each kind of prompt is released this way:
- **`queue`** (the agent default) waits. An idle recipient gets the queue after two quiet seconds; steady arrivals cannot hold that window open past ten seconds. While the recipient has a running or starting turn (including compaction), the queue waits and is delivered together when that turn ends on its own or fails. The daemon releases it when it observes the recipient settle; a two-second timer also retries. Finish notifications and change-request updates always queue.
- **`steer`** waits for neither the quiet window nor the turn. It is dispatched at admission as one prompt that enters the running turn: the messages queued before it, then the steer. A provider that cannot steer, or that refuses this steer, gets the prompt as a replacing turn instead, the same as a person's steer.
- **`interrupt`** is dispatched at admission the same way, as one prompt that replaces the running turn. An older queued message cannot start a turn after the newer `interrupt` that countermands it.
- **A person's prompt** (app, CLI, top-level MCP) is dispatched directly with its existing steer or interrupt behavior and takes the queue along the same way: the messages admitted before it first, then the person's text, in one provider prompt. Messages admitted after it follow it. The person's text keeps its own transcript row. When the turn does not start, the messages return to the queue in their place. That covers a start the provider rejects and a start that is not acknowledged within 60 seconds; a provider that starts the turn after those 60 seconds receives the messages twice.
- **Stop** (the stop button, Escape, `cancel_agent`, a Hub interrupt) starts nothing. Messages admitted before the Stop are held, not dropped, including an interrupt whose turn had not started yet. They go ahead of the recipient's next prompt, in that prompt's turn: a person's prompt, or an agent message or notification admitted after the Stop. A held steer or interrupt no longer enters the turn; it waits like a queued message. A queue step or dispatch decided before the Stop is void, and the queue is held again when the message that reopened it is withdrawn. A replacing prompt, a reload, and a rewind are not a Stop. Neither is `cancel_agent` on a recipient with no running or starting turn: it stops nothing, reports that it canceled no run, and a queued message keeps its quiet window.
The queued receipt carries the applied behavior and guidance text for the sender. The text comes from two facts known at admission: whether the recipient has a running turn, and whether its provider can steer (`AgentManager.canSteer`, which is true when the session offers `steerActiveTurn`). It does not wait for the outcome. Guidance for a message queued behind a running turn tells the sender to send a short `steer` or `interrupt` follow-up instead of resending, because the follow-up carries the queued message ahead of it and a resend would be read twice. The MCP tool, the WebSocket `send_agent_message_response`, the CLI, and the connected-host path all relay this one text.
Older CLIs and connected hosts send an explicit `steer` for every default agent send. The daemon reads an agent sender's `steer` as `queue` unless the client advertises the `agent_active_turn_behaviors` capability. A new client talking to a daemon without `server_info.features.agentActiveTurnBehaviors` sends no behavior for `queue` and refuses a `steer`.
A command the provider accepts out of band is the one exception to admission order: it runs alone without ending the turn. A queued command runs ahead of older messages, and a `steer` or `interrupt` that runs this way takes no queued message along. A person's command leaves the queue where it is. A prompt is a command when it starts with a slash and a name that has no second slash, so `/compact` is one and `/tmp/build.log is stale` is plain text.
One provider prompt has one session mode. A batch released by a steer, an interrupt, or a person's prompt uses the latest explicit choice in it, the person's own first. Queued messages with conflicting choices keep separate ordered dispatches.
The pending message window is in memory. Clean shutdown flushes it, held messages included, before
closing agents; an abrupt crash can lose queued prompts. A durable send receipt remains pending until actual dispatch
acknowledgment, so a lost window never becomes a completed receipt. Completion waits cover queued
admission within their original timeout and cancellation scope, and return permission checkpoints
while messages are waiting.
admission within their original timeout and cancellation scope, and return at permission
checkpoints and when a Stop holds the queue.
Finish notification intent has a separate daemon-owned lifetime. The finish-subscriptions module
persists caller, child, host, and ownership policy through an injectable store; its JSON adapter uses
+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.
+2 -2
View File
@@ -78,7 +78,7 @@ In the composer, the first glyph's ink starts on the text column's edge, and the
One gate, `resolveControlSizing`, picks touch or pointer sizing: touch when the layout is compact or touch is the primary input. An iPad with the sidebar docked is wide and touch-sized; a desktop is pointer-sized; a phone is both compact and touch. The primary input comes from `(pointer: coarse)` (`hasTouchPrimaryPointer` in `hooks/pointer-capabilities.ts`), not from whether a touch screen exists: WebKit keeps touch primary on an iPad with a trackpad attached, and Chromium reports a fine primary pointer for a laptop with a touch screen that its trackpad drives. The fact is read once at startup: attaching a pointer to a tablet does not shrink its controls, and a 2-in-1 launched with a pointer keeps pointer sizes after it switches to tablet mode until the app reloads. Stylesheets take sizes from `bySizing({ touch, pointer })`, which resolves to a breakpoint value, so a caller never sees which sizing it got. Rows, icon buttons and icon slots take theirs from `styles/density.ts`, which uses the same gate. An `{ xs, md }` literal for a hit target or glyph is wrong: on an iPad it yields the pointer size.
Buttons are pills (`borderRadius.full`) with medium-weight labels; an icon-only button is a circle. `<Switch>` follows the same two sizes: a 34×20 track by default and in `sm`, 44×26 where controls are touch-sized, and it reserves its size's control height so a row holding one lines up with a row holding a button. Buttons, text fields, dropdown triggers, and `<SegmentedControl>` (`packages/app/src/components/ui/segmented-control.tsx`) share the size contract — the same size name means the same height and label size on every control kind, so controls in one row line up. Segments run tighter than a button, because the gap between segments already reads as padding. The selected segment is a `surface3` fill with `foreground` text, not an inverted one — inverting it inside thin chrome puts a white slab in the toolbar. A settings row sizes the controls in its trailing slot itself, default in a card and `sm` when nested (`packages/app/src/components/ui/control-size.tsx`), so don't pass a size to a button, dropdown or field placed in a row. Code that computes with a control's height outside a stylesheet uses `controlHeightForLayout`. Never shrink a control's font or padding locally to fit a context — if the context needs a smaller control, the size tier is missing or the wrong one is in use.
Buttons are pills (`borderRadius.full`) with medium-weight labels; an icon-only button is a circle. `<Switch>` follows the same two sizes: a 34×20 track by default and in `sm`, 44×26 where controls are touch-sized, and it takes presses over its size's control height without adding that height to its row. Buttons, text fields, dropdown triggers, and `<SegmentedControl>` (`packages/app/src/components/ui/segmented-control.tsx`) share the size contract — the same size name means the same height and label size on every control kind, so controls in one row line up. Segments run tighter than a button, because the gap between segments already reads as padding. The selected segment is a `surface3` fill with `foreground` text, not an inverted one — inverting it inside thin chrome puts a white slab in the toolbar. A settings row sizes the controls in its trailing slot itself, default in a card and `sm` when nested (`packages/app/src/components/ui/control-size.tsx`), so don't pass a size to a button, dropdown or field placed in a row. Code that computes with a control's height outside a stylesheet uses `controlHeightForLayout`. Never shrink a control's font or padding locally to fit a context — if the context needs a smaller control, the size tier is missing or the wrong one is in use.
A `<Pressable>` wrapping a `<Text>` is a sixth variant. It is wrong. `<Button>` accepts `style`, `textStyle`, `leftIcon`, `disabled`, `size`, and `variant`.
@@ -134,7 +134,7 @@ A section or group explains itself through the `info` prop on `<SettingsSection>
Cards inside a section sit closer than sections. Rows inside a card touch — only the divider separates them. The rhythm is page → spacious; section → spacious; card → tight.
Rows have generous vertical padding: roughly 16px of content plus 16px of vertical padding for settings rows, 8–12px for sidebar list items where many rows must fit. A row that opens something (`<SettingsDetailRow>`, a collapsible row's header) is at least as tall as one holding a default control, so a list where only some of those rows carry a switch keeps one row height. Other rows take their content's height. Compressing rows below the established density to fit more on the screen is wrong. Too many rows means more cards or more sections, not smaller rows.
Rows have generous vertical padding: roughly 16px of content plus 16px of vertical padding for settings rows, 8–12px for sidebar list items where many rows must fit. Every row is at least as tall as one holding a switch, so text rows, switch rows and rows that open something (`<SettingsDetailRow>`, a collapsible row's header) line up. A row holding a button or a select is taller. Compressing rows below the established density to fit more on the screen is wrong. Too many rows means more cards or more sections, not smaller rows.
Rows revealed under a `<SettingsCollapsibleRow>` are nested rows, one step smaller than card rows: 8px of vertical padding, `fontSize.sm` text, `sm` controls, and one fixed height so rows with and without a trailing button line up. The collapsible row sets this for everything under it (`packages/app/src/components/settings/row-density.tsx`). Never pass a density to a row, and never pad or resize a nested row by hand. Settings rows that share a menu surface with menu rows, such as Usage's options, go inside `<MenuSettingsRows>`, which puts their labels on the menu rows' label rail (`menuRowContentInset`).
+1 -1
View File
@@ -57,7 +57,7 @@ Authoritative terminology. UI label wins. Don't invent synonyms; use what's here
- **Agent controls** — Provider, model, mode, thinking, and provider-feature controls for an agent or draft agent. Code: `AgentControls` / `DraftAgentControls` (`packages/app/src/composer/agent-controls/index.tsx`). Forbidden: "Agent status bar".
- **Composer footer** — Optional area rendered below the composer input but still inside the keyboard-shifted composer layout. Code: `Composer.footer` (`packages/app/src/composer/index.tsx`).
- **Composer track** — A contextual lane at the foot of a pane, by the composer input. Specific tracks use the `<thing> track` form: **Queue track**, **Subagents track**, **Tasks track**. The subagents and tasks tracks are pills floating over the transcript, each opening a panel with its rows; the queue track is a lane inside the composer itself. Code: queue track inside `Composer` (`packages/app/src/composer/index.tsx`), pill and panel frame in `packages/app/src/composer/tracks.tsx`, `SubagentsTrack` (`packages/app/src/subagents/track.tsx`), `AgentTaskList` (`packages/app/src/composer/task-list/index.tsx`).
- **Steer** — A follow-up admitted into an agent's already-running turn instead of interrupting it. Interrupting the turn discards steers the provider has not read yet; there is no take-back short of that, and no provider offers one. The stop button and Escape both interrupt. A steer the provider never read keeps its transcript row, matching Codex. Sending while the agent waits on a permission denies that request first, so the message reaches the same turn instead of stalling behind it. UI: "Send and steer". Code: `steerActiveTurn` (`packages/server/src/server/agent/agent-sdk-types.ts`). Don't confuse with **Queue track**, which holds messages client-side until the turn ends and never enters the running turn. Forbidden: "Delivery", "Queued prompt".
- **Steer** — A follow-up admitted into an agent's already-running turn instead of interrupting it. Interrupting the turn discards steers the provider has not read yet; there is no take-back short of that, and no provider offers one. The stop button and Escape both interrupt. A steer the provider never read keeps its transcript row, matching Codex. Sending while the agent waits on a permission denies that request first, so the message reaches the same turn instead of stalling behind it. UI: "Send and steer". Code: `steerActiveTurn` (`packages/server/src/server/agent/agent-sdk-types.ts`). Don't confuse with **Queue track**, which holds messages client-side until the turn ends and never enters the running turn. An agent sender's `activeTurnBehavior: "steer"` (CLI `--behavior steer`) means the same as a person's steer. Agent senders default to `queue` instead: the daemon holds the message until the running turn ends, as the queue track does for a person. Forbidden: "Delivery", "Queued prompt".
- **Subagent** — User-facing term for an agent session related to a parent agent session. Use **subagents** in UI copy and docs. Internal daemon/provider plumbing may say "child agent" or `child_session`, especially for provider-managed imports; do not surface "child agent" as a product term.
- **Attachment tray** — The selected-attachments row inside the composer input, above the text input. Code: `renderAttachmentTray` (`packages/app/src/composer/index.tsx`). Forbidden: "Attachment bar".
- **Fork** — Starting a NEW agent session seeded with a copy of another session's curated chat history. The history rides along as a `chat_history` composer attachment on a draft; the fork does **not** resume or branch the provider-side session, and the source session keeps running untouched. Two targets, one surface, one RPC (`agent.fork_context`, gated on the `agentForkContext` host feature). UI: the fork menu lives in the assistant turn footer and offers "Fork in a new tab" / "Fork in a new workspace". On a **completed** turn it sits beside the copy button and pins a boundary to that turn, so the fork stops where the turn ended. On the **in-flight** turn it sits beside the progress loader and elapsed timer, and omits the boundary entirely — `selectForkContextRows` projects the whole timeline when no boundary is given, so the fork captures everything **up to now**, including the response still streaming. That omission is what makes mid-run forking work; pinning a boundary there would silently drop the live response. Forbidden on provider-subagent (read-only) panes. Code: `useForkAgent` (`packages/app/src/hooks/use-fork-agent.ts`), `selectForkContextRows` (`packages/server/src/server/agent/activity-curator.ts`). Don't confuse with: git fork (unrelated; Paseo has no such concept), **Worktree** (filesystem isolation, not history copying).
+3 -2
View File
@@ -72,8 +72,9 @@ hashes, never prompts, environment values, or credentials.
Before messaging an archived workspace, call `workspace.recovery.inspect.request`, then
`workspace.recovery.restore.request` and await success. The native message handler unarchives the
agent and loads its persisted provider session. `activeTurnBehavior: "steer"` uses the provider's
native steering behavior, including Paseo's existing behavior when that provider cannot steer.
agent and loads its persisted provider session. A Hub message is a direct send (no `sourceAgentId`), so
`activeTurnBehavior: "steer"` uses the provider's native steering and interrupts the running turn
when that provider cannot steer. The daemon rejects `queue` on a direct send.
Execution completion and arrival-specific output authority remain Hub responsibilities.
The older `hub.execution.*` RPCs remain accepted for existing clients. Their execution ownership
+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.
+23 -2
View File
@@ -221,11 +221,32 @@ Plugin callbacks follow the same contract; see [plugin providers](plugins.md#con
`ProviderSnapshotManager` owns one refresh deadline per provider. The deadline starts before the
availability check and covers that check plus the complete catalog probe. Providers that make
multiple catalog requests must not apply this deadline separately to each request. The manager
aborts the shared refresh signal at the deadline. Providers name active catalog operations and
aborts the shared refresh signal at the deadline, and when it stops. Shutdown waits for running
probes to settle before it shuts down provider clients, so a probe cannot start provider work,
such as an OpenCode server, after its client has cleaned up. Providers name active catalog operations and
finish subprocess, server, or session cleanup before rejecting. Timeout errors list the operations
that were still active when the deadline expired.
Catalogue results stay cached by identity until explicit refresh or a change to that provider's configuration.
Catalogue results stay cached by identity until a refresh or a change to that provider's configuration.
Providers change their model lists on the server without a CLI update, so the daemon refreshes
each enabled provider about every 30 minutes (`ProviderRefreshSchedule`). One timer ticks
`30 min / enabled providers` apart, and each tick starts at most one refresh: the provider refreshed
longest ago, if that was a full interval ago. Ticks do not wait for refreshes, so a provider that
probes many workspace targets does not delay the others, and provider CLIs never start in a burst.
Any forced refresh, configuration change, or newly enabled provider counts as a refresh and pushes
that provider's next one back a full interval.
The background refresh takes the settings refresh path for one provider, with these differences:
- It joins discovery already in flight.
- It passes `force: false`, because providers treat `force` as a requested hard refresh. OpenCode
rotates its shared server on it.
- An unchanged catalogue keeps the published record and its `fetchedAt`, so idle clients receive
no update.
- A result that is not ready, or a catalogue the provider marks `incomplete`, keeps a ready
catalogue. Plugin status probes report a failed startup as unavailable, so that counts as
transient. Set `ProviderCatalog.incomplete` when discovery fails and you fall back to a partial
list, as Claude does when model discovery times out. A manual refresh still publishes all three.
Keys are resolved on each read so project configuration can select a different cached catalogue.
Selector opening may read a loading or stale query, but does not force provider probing.
+187 -111
View File
@@ -6,21 +6,26 @@ All workspaces share one version and release together.
A release has exactly two steps. The agent does the first, the user authorizes the second.
**Preparation** (reversible — agent does this):
**Preparation** (reversible — agent does this on the release branch):
- format, lint, typecheck all green
- resolve the [release base](#release-base-and-source), get the [release inventory](#release-inventory) approved when one applies, and confirm CI for the resulting release source is green
- resolve the [release base](#release-base-and-source) and get the [release inventory](#release-inventory) approved when one applies
- classify the diff from the previous stable to the release source as patch or minor, then show the
target version and rationale to the user
- draft the changelog, show it to the user, wait for review
- run the pre-release sanity check, surface findings to the user
- draft `CHANGELOG.md` and `CHANGELOG.zh-CN.md`, show the draft to the user, and wait for review
- run the pre-release sanity check (stable only) and surface findings to the user
- commit the approved changelog and any requested ACP update, run format, lint, and typecheck, then
run `npm run release:prep:<mode>` to create the `chore(release): cut <version>` commit without a tag
- push the `release/vX.Y.Z` or `release/vX.Y.Z-beta.N` branch and confirm its `CI` and
`Desktop Packages` runs pass (never wait on `main` CI)
**Go-ahead** (user says "go ahead"):
- commit the approved release inputs locally on the release branch
- run the release, which publishes npm and pushes the release branch and tag
- run `npm run release:ship` (stable) or `npm run release:ship:beta` (beta), which publishes npm
with retry and registry visibility checks, advances the `beta` dist-tag on stable when newer, and
pushes the tag on the already-verified commit
- create the release heartbeat immediately and babysit it to completion
- [reconcile `main`](#reconcile-main) with what shipped
- open the [reconcile `main`](#reconcile-main) PR right away so its CI runs in parallel with release
builds, then delete the remote release branch once the PR merges
Rules that apply to both steps:
@@ -87,29 +92,42 @@ An explicit user instruction can select another base.
1. Fetch `origin` with tags and resolve the base to one commit.
2. Create the release workspace through Paseo MCP on a new branch from the base, named
`release/vX.Y.Z` or `release/vX.Y.Z-beta.N` for the version being cut. Run the release from
this workspace: `release:push` pushes `HEAD` to the current branch.
`release/vX.Y.Z` or `release/vX.Y.Z-beta.N` for the version being cut. `release:push` refuses
`main` and any branch outside `release/*`.
3. Cherry-pick the approved commits in their `main` order with `git cherry-pick -x`, so each
commit records the `main` commit it came from. Include the prerequisites the inventory listed.
Resolve conflicts within the approved changes and report how. A resolution that needs new
behavior is a scope addition: surface it for selection.
4. Confirm CI for the release source. When the source is a commit whose CI already passed (the
captured `origin/main`, or the beta tag being promoted), use that run and watch pending CI to
completion. Otherwise push the release branch and run `gh workflow run ci.yml --ref <branch>`,
because CI push runs target only `main`.
5. Keep the changelog, any explicitly requested ACP catalog update, lockfile preparation, and the
version commit local until the go-ahead. The release command pushes the release branch and tag
as one batch, and the tag push starts the release workflows. Then run
`gh workflow run ci.yml --ref <branch>` so CI covers the complete release commit.
6. [Reconcile `main`](#reconcile-main).
4. Commit the approved `CHANGELOG.md`, `CHANGELOG.zh-CN.md`, and any explicitly requested ACP
catalog update on the release branch. Run `npm run format`, `npm run lint`, and
`npm run typecheck`, then run `npm run release:prep:<mode>`. This checks the packages, bumps all
workspace versions, generates stable F-Droid changelogs, updates `package-lock.json`, and creates
`chore(release): cut <version>` without a tag.
5. Push the release branch (`git push -u origin HEAD`). Pushing any `release/**` branch triggers
`CI` (all 21 jobs) and `Desktop Packages` (Linux user-namespace smoke) in their own concurrency
groups, isolated from `main` traffic. Never wait on `main` CI, because `main` cancels in-progress
runs on every merge. Wait for both runs on the release branch commit to pass before shipping.
Pushing a `release/**` branch without a `v*` tag triggers no publish workflows.
6. After go-ahead, run `npm run release:ship` (stable) or `npm run release:ship:beta` (beta). This
publishes to npm and pushes the `v*` tag on the already-verified commit. Because the release
branch is already pushed at `HEAD`, no second CI run starts and only the tag release workflows
run.
7. Start [Reconcile `main`](#reconcile-main) immediately so its PR checks overlap with desktop and
EAS builds.
When promoting or branching from a tag created before `release:prep:*`, `release:ship`, and the
`release/**` workflow triggers existed (for example `v0.17.0-beta.1`), either cherry-pick the
release-tooling commit onto the release branch (leaving product code unchanged) or follow the
older tag's scripts (`version:all:*`, manual `gh workflow run ci.yml --ref <branch>`,
`release:publish`, and `release:push`) until the next tag carries the new tooling.
A stable hotfix can take the version a patch beta line would promote to, such as `0.13.3`
shipping while `0.13.3-beta.2` soaks. Never republish or reuse a shipped version. Continue the line
as the next unused patch beta, `0.13.4-beta.1`, from the tested beta tag. No `version:all:*` mode
computes that from a prerelease, so follow the [manual steps](#manual-step-by-step) with
`npm version 0.13.4-beta.1 --include-workspace-root --message "chore(release): cut %s"` and
`npm run release:publish:beta`. Record the tested beta tag as its source so its soak still counts
for the unchanged content.
computes that from a prerelease, so run `npm run release:check`, bump with
`npm version 0.13.4-beta.1 --include-workspace-root --no-git-tag-version && git commit -m "chore(release): cut 0.13.4-beta.1"`,
push the release branch for `CI` and `Desktop Packages`, then ship with `npm run release:ship:beta`.
Record the tested beta tag as its source so its soak still counts for the unchanged content.
## Release inventory
@@ -137,19 +155,31 @@ For a promotion, every item defaults to defer.
## Reconcile main
After the release push, open a PR into `main` that brings in what shipped and keeps newer
development on `main`:
Right after the tag push (in parallel with desktop and EAS builds), open a PR into `main` from a
fresh branch off `origin/main` named `reconcile/vX.Y.Z` or `reconcile/vX.Y.Z-beta.N`:
- The shipped `CHANGELOG.md` and `CHANGELOG.zh-CN.md` entries, exactly as tagged. A beta or
promotion entry replaces the series entry on `main`. A stable hotfix on an older line goes
below any newer entries.
- The shipped version in every `package.json` and `package-lock.json`, unless `main` already
carries a newer version, plus the F-Droid changelog files a stable release generates.
- No claims about unshipped work: a shipped entry describes only the tagged content, and notes
`main` holds for changes that have not shipped stay out of it.
```bash
git fetch origin --tags
git checkout -b reconcile/vX.Y.Z origin/main
npm run release:reconcile -- --tag vX.Y.Z
```
Delete the release branch once the PR merges. The tag is the record of shipped source; Paseo
maintains no release track besides `main`.
`scripts/reconcile-release.mjs` updates the working tree without cherry-picking stale lockfile
hunks from the release base:
- Copies the tagged `CHANGELOG.md` and `CHANGELOG.zh-CN.md` entries verbatim. A beta or promotion
entry replaces the series beta entry on `main`. A stable hotfix on an older line is placed below
any newer entries.
- Copies the generated F-Droid changelog files from the tag for stable releases.
- Updates every `package.json` version and regenerates `package-lock.json` on top of current `main`
only when the shipped version is newer than `main`'s version.
- Leaves unshipped work on `main` untouched and makes no claims about unshipped work in the
changelog entry.
Commit, open the PR into `main`, and merge once its checks pass. After the reconcile PR merges and
the release completes, delete the remote release branch (`git push origin --delete release/vX.Y.Z`
or `release/vX.Y.Z-beta.N`). The tag is the record of shipped source; Paseo maintains no release
track besides `main`.
## ACP catalog updates
@@ -189,35 +219,42 @@ as described in **Fixing a failed release build**.
## Standard release (stable)
Before running any stable release command:
Before preparing a stable release on `release/vX.Y.Z`:
- Make sure the release source passed CI, the approved release inputs are committed locally on the release branch, and the working tree is clean.
- **Run `npm run format`, `npm run lint`, and `npm run typecheck` and commit any resulting changes BEFORE you start any `release:*` command.** `release:check` runs `npm install --workspaces --include-workspace-root` as part of `release:prepare`, which can mutate `package-lock.json` (e.g. churning `"dev": true` markers on optional deps). The next step, `version:all:*`, runs `npm version` which aborts when the working tree is dirty. If this happens mid-flight you have to commit the lockfile churn before retrying — and the pre-commit format hook will reject a lockfile-only commit because oxfmt internally skips `package-lock.json` while lefthook's glob still matches it. Avoid the whole mess by running format/lint/typecheck first, then `release:prepare` once on its own to absorb any lockfile churn into a normal commit, then start the release.
- Do not use a release command as a substitute for checking whether the current commit is actually ready.
- Commit the approved `CHANGELOG.md`, `CHANGELOG.zh-CN.md`, and any requested ACP update.
- Run `npm run format`, `npm run lint`, and `npm run typecheck`, commit any resulting changes, and
confirm the working tree is clean.
- Do not use a release command as a substitute for checking whether the current commit is ready.
```bash
# Run exactly one, matching the approved decision:
npm run release:patch
npm run release:minor
# 1. Preparation (reversible): run checks and commit the version bump without tagging.
npm run release:prep:patch
# or:
npm run release:prep:minor
# 2. Push the release branch and wait for CI + Desktop Packages on this commit.
git push -u origin HEAD
# 3. After go-ahead and green release-branch checks: publish npm and push the tag.
npm run release:ship
```
This bumps the version across all workspaces, runs checks, publishes to npm, and pushes the branch + tag. The tag push triggers `Desktop Release`, `Android APK Release`, `Docker`, and `Release Notes Sync` on GitHub Actions. The workflows create the GitHub Release as a draft while builds and release-note sync run. EAS picks up the same tag via the EAS GitHub app and starts the iOS + Android store builds in parallel (see "Mobile builds (EAS)" below) — there is no mobile-release workflow under `.github/workflows`.
`release:ship` runs `scripts/publish-release-packages.mjs` and `scripts/push-current-release-tag.mjs`:
After the stable release succeeds, check `npm view @getpaseo/cli dist-tags`. When the new stable
is newer than `beta`, move `beta` to it for every published package. This changes dist-tags only;
do not republish the packages:
- Publishes all seven `@getpaseo/*` packages in dependency order, skips versions already on npm,
retries transient 429/5xx/network errors, and waits until each version is visible on npm before
continuing.
- Checks `npm view @getpaseo/cli dist-tags` and moves npm's `beta` dist-tag to the new stable
version across all seven packages whenever the stable version is newer than `beta` (leaving
`beta` untouched during a stable hotfix on an older line).
- Refuses non-`release/*` branches, tags `HEAD` with `vX.Y.Z`, and pushes the tag. Because `HEAD`
is already on the release branch, no second CI run starts.
```bash
PASEO_VERSION=$(node -p "require('./package.json').version")
for package in highlight relay protocol client plugin server cli; do
npm dist-tag add "@getpaseo/$package@$PASEO_VERSION" beta
done
```
The tag push triggers `Desktop Release`, `Android APK Release`, `Docker`, and `Release Notes Sync` on GitHub Actions. The workflows create the GitHub Release as a draft while builds and release-note sync run. EAS picks up the same tag via the EAS GitHub app and starts the iOS + Android store builds in parallel (see "Mobile builds (EAS)" below) — there is no mobile-release workflow under `.github/workflows`.
Verify `latest` resolves to `PASEO_VERSION`, and `beta` resolves to `PASEO_VERSION` or the
active newer beta, before considering the stable release complete.
Verify `npm view @getpaseo/cli dist-tags` shows `latest` at the shipped version, and `beta` at the shipped version or an active newer beta, before considering the stable release complete.
The Docker workflow builds images from the checked-out source tree on pull requests and on `main` as non-publishing checks. Stable `vX.Y.Z` tag pushes publish `ghcr.io/getpaseo/paseo:X.Y.Z` and `ghcr.io/getpaseo/paseo:latest`; beta `vX.Y.Z-beta.N` tag pushes publish only `ghcr.io/getpaseo/paseo:X.Y.Z-beta.N` and never move `latest`.
The Docker workflow builds images from the checked-out source tree on `main` as non-publishing checks (cancelling superseded `main` runs). Stable `vX.Y.Z` tag pushes publish `ghcr.io/getpaseo/paseo:X.Y.Z` and `ghcr.io/getpaseo/paseo:latest`; beta `vX.Y.Z-beta.N` tag pushes publish only `ghcr.io/getpaseo/paseo:X.Y.Z-beta.N` and never move `latest`.
The production relay is the Elixir service in [getpaseo/paseo-relay](https://github.com/getpaseo/paseo-relay), with its own deployment process. Paseo releases and pushes to this repository do not deploy it. The Cloudflare relay code and workflow in this repository are legacy and are not used in production.
@@ -228,29 +265,43 @@ The production relay is the Elixir service in [getpaseo/paseo-relay](https://git
```bash
npm run typecheck # Verify the exact commit you intend to release
npm run release:check # Typecheck, build, dry-run pack
# Run exactly one approved version command:
# Run exactly one approved version command (commits without tagging):
npm run version:all:patch
npm run version:all:minor
npm run release:publish # Publish to npm
npm run release:push # Push HEAD + tag (triggers CI workflows)
# Then move npm's beta dist-tag to this stable version when it is newer than beta (see above).
git push -u origin HEAD # Trigger CI + Desktop Packages on release/vX.Y.Z
# Wait for CI and Desktop Packages on this branch to pass, then after go-ahead:
npm run release:publish # Publish to npm (idempotent, with propagation + beta dist-tag sync)
npm run release:push # Create tag vX.Y.Z on HEAD and push (triggers release workflows)
```
## Beta flow
```bash
npm run release:beta:patch # Start the next patch beta line
npm run release:beta:minor # Start the next minor beta line
# ... test desktop and APK prerelease assets from GitHub Releases ...
npm run release:beta:next # Optional: cut X.Y.Z-beta.2, beta.3, ...
npm run release:promote # Promote X.Y.Z-beta.N to stable X.Y.Z
# 1. Preparation (reversible) on release/vX.Y.Z-beta.N:
npm run release:prep:beta:patch # Start the next patch beta line
# or:
npm run release:prep:beta:minor # Start the next minor beta line
# or for follow-up betas:
npm run release:prep:beta:next # Cut X.Y.Z-beta.2, beta.3, ...
# 2. Push the release branch and wait for CI + Desktop Packages to pass:
git push -u origin HEAD
# 3. After go-ahead:
npm run release:ship:beta
# Later, after soak, promote on release/vX.Y.Z:
npm run release:prep:promote
git push -u origin HEAD
# Wait for CI + Desktop Packages to pass, then after go-ahead:
npm run release:ship
```
- Beta tags are published GitHub prereleases like `v0.1.41-beta.1`
- Betas publish npm packages with `--tag beta`, so `npm install @getpaseo/cli@beta` opts in while plain `npm install @getpaseo/cli` stays on `latest`
- The user-facing beta instructions, including the public TestFlight join link for the `Paseo Beta` group, live in `public-docs/updates.md` and its `zh-CN` pair. Update them when a beta path is added or removed.
- Betas publish desktop assets and APKs for testing. They also build iOS, upload it to TestFlight, add it to the `Paseo Beta` external group, and submit it for Beta App Review. They do not submit mobile builds to the production stores.
- `release:promote` creates a fresh stable tag like `v0.1.41`; the final release never reuses the beta tag
- `release:prep:promote` + `release:ship` creates a fresh stable tag like `v0.1.41`; the final release never reuses the beta tag
- Desktop assets now come from the Electron package at `packages/desktop`
- Require the Linux artifact CI checks with both restricted and usable user namespaces to pass before publication; see [packaged desktop smoke](testing.md#packaged-desktop-smoke). Keep the installed-package and AppImage checks together.
- Beta releases use Electron's `beta` update channel. Users on the stable channel only receive stable releases; users on the beta channel receive beta releases and the final stable release when it is published.
@@ -278,17 +329,17 @@ Drafts do not appear in GitHub's releases feed. Updater clients continue to see
### Default behavior
`npm run release:patch` or `npm run release:minor` → tag push → 36h ramp. No extra action needed.
`npm run release:prep:patch` or `npm run release:prep:minor` → push release branch → green checks → `npm run release:ship` → tag push → 36h ramp. No extra action needed.
The `rollout_hours` input on `desktop-release.yml` is **only read on `workflow_dispatch`** — tag-push runs always default to 36. To get any other rollout duration on a fresh release, use the post-publish flip below.
### Instant-admit release (rollout_hours=0)
`npm run release:patch` and `npm run release:minor` tag-push, and tag-push runs always stamp 36 hours. To admit everyone immediately (hotfix, doc-only change, a release you want out fast), cut the release normally, wait for it to publish, then flip the manifests:
Tag-push runs from `npm run release:ship` always stamp 36 hours. To admit everyone immediately (hotfix, doc-only change, a release you want out fast), ship the release normally, wait for it to publish, then flip the manifests:
```bash
# 1. Cut and publish (36h ramp from tag push).
npm run release:patch
# 1. Ship the verified release branch (36h ramp from tag push).
npm run release:ship
# 2. Wait for Desktop Release to publish the GitHub Release.
gh run watch <desktop-release-run-id> --exit-status
@@ -339,7 +390,7 @@ gh workflow run desktop-release.yml \
-f rollout_hours=6
```
This does **not** apply to fresh releases cut via `npm run release:patch` or `npm run release:minor` — those paths always tag-push and stamp 36. For a fresh release with a custom ramp, cut normally and then dispatch `desktop-rollout.yml` (same pattern as the instant-admit flow above, with your chosen `rollout_hours`).
This does **not** apply to fresh releases shipped via `npm run release:ship` — tag-push runs always stamp 36. For a fresh release with a custom ramp, ship normally and then dispatch `desktop-rollout.yml` (same pattern as the instant-admit flow above, with your chosen `rollout_hours`).
### Releasing during an active rollout
@@ -449,10 +500,11 @@ that resumes the release in the current conversation. Create it automatically
with `create_heartbeat`. The heartbeat owns the release until it either reaches
the completion checklist or finds a failure that needs new user authority.
Each heartbeat checks the release tag commit, all GitHub Actions runs for the
release branch and tag, npm dist-tags, the GitHub Release body and assets,
desktop updater manifests, the published Docker image, and the applicable EAS
workflow. Inspect the GitHub Release itself and confirm that the macOS, Linux,
Each heartbeat checks the release tag commit, `CI` and `Desktop Packages` for the release branch,
every tag-triggered GitHub Actions run (`Desktop Release`, `Android APK Release`, `Docker`,
`Release Notes Sync`), npm dist-tags, the GitHub Release body and assets, desktop updater
manifests, the published Docker image, the applicable EAS workflow, the reconcile PR, and remote
release branch cleanup. Inspect the GitHub Release itself and confirm that the macOS, Linux,
Windows, and Android APK assets are present along with the channel manifests
(`latest-mac.yml`, `latest-linux.yml`, and `latest.yml` for stable;
`beta-mac.yml`, `beta-linux.yml`, and `beta.yml` for beta).
@@ -461,8 +513,9 @@ For stable releases, also confirm every required mobile build, external
TestFlight distribution, Beta App Review submission, and store submission job
for the release commit. For betas, confirm
the beta EAS workflow completed its TestFlight distribution and Beta App Review
path. Delete the heartbeat only after every applicable checklist item passes,
then report the release as shipped.
path. Once the reconcile PR merges and every applicable checklist item passes,
delete the remote release branch (`git push origin --delete release/vX.Y.Z` or
`release/vX.Y.Z-beta.N`), delete the heartbeat, and report the release as shipped.
Pattern:
@@ -474,7 +527,7 @@ Pattern:
"timezone": "UTC",
"maxRuns": 120,
"expiresIn": "24h",
"prompt": "Resume the vX.Y.Z release babysit for commit <sha>. Check npm tags; every GitHub Actions run for the release branch and tag; the published GitHub Release body, expected desktop/APK assets, and channel manifests; the Docker image; and the matching EAS workflow. Completion requires every applicable checklist item. For stable, require build_ios, distribute_ios (Paseo Beta external distribution and Beta App Review submission), submit_ios_for_review, build_android, and submit_android to succeed. For beta, require the beta TestFlight distribution and Beta App Review path. If work is pending, wait for the next heartbeat. If a failure can be retried safely for the same version, follow the failed-release procedure; otherwise report the blocker. When every applicable completion-checklist item passes, delete THIS heartbeat, report shipped, and stop.",
"prompt": "Resume the vX.Y.Z release babysit for commit <sha>. Check npm tags; CI and Desktop Packages on release/vX.Y.Z; every tag-triggered GitHub Actions run; the published GitHub Release body, expected desktop/APK assets, and channel manifests; the Docker image; the matching EAS workflow; and the reconcile PR into main. Completion requires every applicable checklist item. For stable, require build_ios, distribute_ios (Paseo Beta external distribution and Beta App Review submission), submit_ios_for_review, build_android, and submit_android to succeed. For beta, require the beta TestFlight distribution and Beta App Review path. If work is pending, wait for the next heartbeat. If a failure can be retried safely for the same version, follow the failed-release procedure; otherwise report the blocker. When every applicable completion-checklist item passes and the reconcile PR is merged, delete origin/release/vX.Y.Z, delete THIS heartbeat, report shipped, and stop.",
}
```
@@ -576,12 +629,16 @@ intentionally unavailable to desktop updater clients.
## Notes
- `version:all:*` bumps root + syncs workspace versions and `@getpaseo/*` dependency versions
- The npm `version` lifecycle regenerates F-Droid changelog files from `CHANGELOG.md` for stable releases only (`npm run fdroid:changelogs`) and stages them, so the release tag carries them. Betas are a no-op. A stable run **aborts the release** if `CHANGELOG.md` has no entry for the version being cut — commit the changelog entry first. See [docs/android.md](android.md) for why these files are generated per ABI.
- `release:prepare` refreshes workspace `node_modules` links to prevent stale types
- `npm run dev:desktop` and `npm run build:desktop` target the Electron desktop package in `packages/desktop`
- If `release:publish` partially fails, re-run it — npm skips already-published versions
- If `release:publish:beta` partially fails, re-run it — npm skips already-published versions and keeps prereleases off `latest` because every publish uses `--tag beta`
- `version:all:*` bumps root, syncs workspace versions and `@getpaseo/*` dependency versions, and
commits `chore(release): cut <version>` without creating a tag. `release:push` creates and pushes
the tag atomically after release-branch CI passes.
- `release:push` refuses `main` and any branch outside `release/*`.
- The npm `version` lifecycle regenerates F-Droid changelog files from `CHANGELOG.md` for stable releases only (`npm run fdroid:changelogs`) and stages them, so the release commit and tag carry them. Betas are a no-op. A stable run **aborts the release** if `CHANGELOG.md` has no entry for the version being cut — commit the changelog entry first. See [docs/android.md](android.md) for why these files are generated per ABI.
- `release:prepare` refreshes workspace `node_modules` links to prevent stale types.
- `npm run dev:desktop` and `npm run build:desktop` target the Electron desktop package in `packages/desktop`.
- `release:publish` and `release:publish:beta` run `scripts/publish-release-packages.mjs`: if a run
fails partway through, re-running skips versions already published on npm, retries transient
registry errors, and waits for each version to become visible on npm before continuing.
- The website uses GitHub's latest published release API for download links, so published beta prereleases do not replace the stable download target.
## Changelog format
@@ -602,6 +659,7 @@ No prefix (`v`), no extra text. `Release Notes Sync` matches the `## X.Y.Z` (or
- `CHANGELOG.md` holds stable releases and at most one entry for the current beta series.
- The first beta of a version inserts a top entry like `## 0.1.60-beta.1 - YYYY-MM-DD`.
- Each subsequent beta rewrites that entry in place: the heading becomes the new beta number and date, and the body describes the full change from the previous stable release to this beta. Never add a second beta entry.
- The entry announces changes and leaves setup steps, click paths, migration notes, configuration keys, hedges and edge cases to product docs. The headline change is the first highlight. [Changelog conciseness](#changelog-conciseness) and [Changelog ordering](#changelog-ordering) hold the rules.
- The entry is a list of changes, not of PRs. When a later beta reverts, reworks, or follows up on something an earlier beta added, rewrite the bullet to the current behavior or delete it. A stable user never saw the earlier beta behavior, so fixes to it are not "Fixed" bullets.
- Anything that already shipped to stable through a patch release on an older line stays out of the beta entry.
- Stable promotion renames the entry to `## 0.1.60 - YYYY-MM-DD` after a final review.
@@ -657,14 +715,30 @@ claims a general improvement, rewrite it with the concrete change.
## Changelog conciseness
Every section bullet must be scannable at a glance. The changelog is not release documentation — it's a list. [Highlights](#changelog-highlights) get more room; every other bullet follows these limits.
An entry announces what changed. Product docs own setup, navigation, migration and edge cases, and the PR link leads to the rest. These rules apply to highlights and section bullets.
- **One sentence per bullet, max.** If a bullet contains two sentences, the second one is doing work that belongs in product docs, not the changelog. Cut it.
- **No instructions.** Cut setup steps, click paths, configuration keys, flags and migration notes. "Open a provider's settings from Settings, setup, or the model picker" is a click path. "Existing goose settings and sessions carry over to the bundled plugin" is a migration note.
- **One warning for a breaking requirement.** When the update stops something working until the user acts, state the requirement in one short sentence after the announcement, and link the product doc that has the steps: "Requires [Antigravity CLI 1.5.0 or later](https://paseo.sh/docs/supported-providers/antigravity)." Nothing else earns a second sentence.
- **No hedges or exception clauses.** Cut "when needed", "for eligible models", "on hosts where…", "except…", "with a hint shown when…" and "across common install shapes". Keep the condition that triggers a fixed failure, as in `Fixed <failure> when <condition>`.
- **The shorter bullet is still true.** When a change reaches only some providers, platforms or file types, name what it covers in the sentence's own words: "update supported CLIs" where one provider has no update command, "Markdown previews and source views" where HTML previews on iOS are left out, "by default" where an explicit interrupt still replaces the turn. Do not widen the claim to remove a clause.
- **State the outcome and stop.** Say what the user gets. Leave out queues, snapshots, caches, timeouts, LAN/WAN topology, TLS handshakes and IPC.
Each row is from the first draft of 0.17.1:
| Avoid | Write |
| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- |
| Open a provider's settings from Settings, setup, or the model picker to update supported CLIs and watch their output | Update supported CLIs from the app |
| Use Antigravity CLI 1.5.0 or later on the daemon host, and include `acp` if you override its command | Requires Antigravity CLI 1.5.0 or later |
| Reports and notifications from other agents arrive in order when the current turn ends instead of interrupting it. An interrupt or your own prompt carries earlier queued messages in the same turn, and Stop holds queued messages until the next prompt | By default, messages from other agents wait for the current turn to end |
| Changed worktree teardown to keep the worktree when the command exceeds one minute or the `worktree.teardownTimeoutMs` limit in `paseo.json` | Changed worktree teardown to keep the worktree when the command times out |
| Fixed file views losing their scroll position when switching Preview and Source, except HTML previews on iOS | Fixed Markdown previews and source views losing their scroll position when switching between them |
Section bullets also follow these limits:
- **One sentence per bullet, max.** A second sentence is documentation. Cut it.
- **No trailing periods.** Bullets are list items, not prose. Drop the period at the end of every bullet, including the period inside any bolded lead-in. `**Configurable terminal scrollback**` not `**Configurable terminal scrollback.**`.
- **One line per bullet.** If a bullet wraps to three lines in a narrow column, it's too long.
- **Split bullets that pack multiple distinct changes.** If a bullet uses "and", "plus", a comma list, or an em-dash to chain several independent improvements, break them into separate bullets — even when they share a theme or author. One bullet = one user-facing change.
- **Trim qualifying clauses.** Drop "with a hint shown when…", "matching the CLI's behaviour", "across common install shapes". If the detail doesn't change whether a user cares, cut it.
- **Stop after identifying the change.** Do not explain LAN/WAN topology, TLS handshakes, IPC, or other architecture in a changelog bullet. Put necessary background in product docs.
- **Attribution follows the split.** When you split a dense bullet, move each PR/author to the bullet it belongs to. Never duplicate the same PR across multiple bullets.
## Changelog highlights
@@ -677,7 +751,7 @@ reader who stops after the highlights should have missed nothing they would ask
```markdown
## 0.16.0 - 2026-11-20
- **Undo workspace archive:** Archiving a workspace in the app now shows a "Workspace archived" toast for six seconds. Undo, or Cmd/Ctrl+Z, restores the workspace with its tabs and agents. ([#8904](https://github.com/getpaseo/paseo/pull/8904))
- **Undo workspace archive:** Restore an archived workspace with Undo or Cmd/Ctrl+Z. ([#8904](https://github.com/getpaseo/paseo/pull/8904))
### Added
```
@@ -688,17 +762,19 @@ reader who stops after the highlights should have missed nothing they would ask
- **The lead-in is not a place or something Paseo already had.** A device, screen or area names
where the change landed. A feature name that was true of the last release hides the news: Paseo
already had keyboard shortcuts, so the lead-in says they now work on mobile.
- **The first sentence says the plain thing.** Write what a user would tell a friend: Paseo now
- **One short sentence says the plain thing.** Write what a user would tell a friend: Paseo now
shows the background tasks an agent is running. Leave out the conditions and mechanics that make
it true.
it true. A second sentence is only for a
[breaking requirement](#changelog-conciseness).
- **Describe the new behavior, not the old one.** Say what is faster or better now, and do not
dwell on how slow or broken it was before. A number is welcome as a short aside after the new
behavior is stated: seconds, a percentage, a multiple.
- **Do not list what a sentence already covers.** After "the same shortcuts as desktop", naming
five of them adds nothing. Keep a list only when it sets the scope, such as the providers a
feature works with.
- **The description runs one to three sentences.** Sentences end with periods, and the attribution
follows the last one. [Changelog wording](#changelog-wording) applies in full.
- **Sentences end with periods, and the attribution follows the last one.**
[Changelog wording](#changelog-wording) and [Changelog conciseness](#changelog-conciseness)
apply.
- **A highlight replaces the section bullets it covers.** A PR appears once in an entry, so its
attribution moves to the highlight.
- **A highlight is something a user would name.** Everything else stays a section bullet. A patch
@@ -707,13 +783,13 @@ reader who stops after the highlights should have missed nothing they would ask
of related fixes, becomes a highlight only when it passes the same test as a feature, and then
it is written as what works now: `**Fewer reconnects on return:**`.
| Avoid | Write |
| ------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------- |
| `**iPad and touch screens:**` | `**Touch-sized tablet controls:**` |
| `**Hardware keyboard shortcuts:**` | `**Keyboard shortcuts on mobile:**` |
| When an agent ends its turn while shells it started are still running, a pill lists them | Paseo now shows the background tasks an agent is running |
| A diff no longer waits 4 to 40 seconds behind worktree scans | Opening Changes shows the file tree right away, and diffs load about 6 times sooner on hosts with many worktrees |
| The same shortcuts as desktop: command center, file picker, new workspace, workspace jumps | The same shortcuts as desktop, including your custom bindings |
| Avoid | Write |
| ------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------- |
| `**iPad and touch screens:**` | `**Touch-sized tablet controls:**` |
| `**Hardware keyboard shortcuts:**` | `**Keyboard shortcuts on mobile:**` |
| When an agent ends its turn while shells it started are still running, a pill lists them | Paseo now shows the background tasks an agent is running |
| A diff no longer waits 4 to 40 seconds behind worktree scans | Opening Changes shows the file tree right away, and diffs load about 6 times sooner |
| The same shortcuts as desktop: command center, file picker, new workspace, workspace jumps | The same shortcuts as desktop, including your custom bindings |
Before showing a draft, read only the bold lead-ins top to bottom. Each one must answer "what is
new?" without its description, and each must outrank the one below it.
@@ -763,6 +839,9 @@ question.
for them: `Undo workspace archive`, `Fewer reconnects on return`. Fixes are routine, so one
that earned a highlight still follows everything new or improved.
- **The headline change goes first, whatever its group.** It is the change the release is announced
with. 0.17.1 leads with `Antigravity approvals and history`, which needs one provider. The groups
rank everything after it.
- **Reach decides before kind.** A new capability that needs a hardware keyboard is in group 3.
- **Rank the whole list in one pass.** The order you collected the pull requests in, the alphabet
and the order of the sections below are not rankings.
@@ -802,13 +881,12 @@ Every entry covers `previous stable release → release source`: first beta, lat
### Beta release
- [ ] The release base and changes match the [release base table](#release-base-and-source) and any approved [inventory](#release-inventory), and CI for the release source is green
- [ ] The release base and changes match the [release base table](#release-base-and-source) and any approved [inventory](#release-inventory)
- [ ] Every PR in the release range has been opened, and its full description and every linked issue have been read before drafting the changelog
- [ ] Fold this beta into the series' single `CHANGELOG.md` entry (heading `## X.Y.Z-beta.N - YYYY-MM-DD`, previous stable → release source), review it against the changelog policy, get approval, and commit it with its [`CHANGELOG.zh-CN.md` translation](#changelog-translations) before cutting the release
- [ ] Fold this beta into the series' single `CHANGELOG.md` entry (heading `## X.Y.Z-beta.N - YYYY-MM-DD`, previous stable → release source), review it against the changelog policy, get approval, and commit it with its [`CHANGELOG.zh-CN.md` translation](#changelog-translations) before running `release:prep:*`
- [ ] The diff from the previous stable to the resolved release source is classified as patch or minor, with the target version and rationale approved
- [ ] The changelog, ACP, lockfile, and version commits stayed local until the approved release command pushed the release branch and tag
- [ ] `npm run release:beta:patch`, `npm run release:beta:minor`, or `npm run release:beta:next` completes successfully
- [ ] Every GitHub Actions run for the complete release commit and tag is green
- [ ] `npm run release:prep:beta:patch`, `release:prep:beta:minor`, or `release:prep:beta:next` created the version commit on `release/vX.Y.Z-beta.N` without a tag, and the pushed branch passed `CI` and `Desktop Packages` before shipping (never relying on `main` CI)
- [ ] After go-ahead, `npm run release:ship:beta` published npm and pushed the `vX.Y.Z-beta.N` tag without triggering a second CI run
- [ ] npm shows the version under the `beta` dist-tag, not `latest`
- [ ] The GitHub prerelease was published only after the three beta manifests were uploaded, and it has the changelog body and every expected macOS, Linux, Windows, and Android APK asset
- [ ] GitHub `Desktop Release` workflow for the `v*-beta.N` tag is green
@@ -817,23 +895,21 @@ Every entry covers `previous stable release → release source`: first beta, lat
- [ ] GitHub `Docker` workflow is green and the versioned beta image is published without moving `latest`
- [ ] GitHub `Release Notes Sync` mirrored the beta entry into the prerelease body
- [ ] EAS `Release iOS Beta` completed its build, TestFlight distribution, external beta group, and Beta App Review path
- [ ] The [reconcile PR](#reconcile-main) brought the shipped changelog entries and version into `main`
- [ ] The [reconcile PR](#reconcile-main) brought the shipped changelog entries and version into `main`, and `origin/release/vX.Y.Z-beta.N` was deleted
- [ ] The release heartbeat was created after the tag push and deleted only after every item above passed
### Stable release (or promotion)
- [ ] Run the pre-release sanity check (see above) and address any findings
- [ ] The diff from the previous stable to the resolved release source is classified as patch or minor, with the target version and rationale approved
- [ ] The release base and changes match the [release base table](#release-base-and-source) and any approved [inventory](#release-inventory), and CI for the release source is green
- [ ] The release base and changes match the [release base table](#release-base-and-source) and any approved [inventory](#release-inventory)
- [ ] A promotion ships the tested beta's product content after its soak, unless the user explicitly overrode either default
- [ ] Every PR in the release range has been opened, and its full description and every linked issue have been read before drafting the changelog
- [ ] Ensure the approved release inputs are committed locally and the git worktree is clean before running any release command
- [ ] Ensure local `npm run typecheck` passes on that exact commit before running any release command
- [ ] Update `CHANGELOG.md` with user-facing release notes (features, fixes — not refactors). Promotion renames the series' `## X.Y.Z-beta.N` entry to `## X.Y.Z - YYYY-MM-DD` and re-checks it covers the full release. Commit the matching [`CHANGELOG.zh-CN.md` entry](#changelog-translations) with it
- [ ] Verify the changelog heading follows strict `## X.Y.Z - YYYY-MM-DD` format
- [ ] The changelog, ACP, lockfile, and version commits stayed local until the approved release command pushed the release branch and tag
- [ ] `npm run release:patch`, `npm run release:minor`, or `npm run release:promote` completes successfully
- [ ] Every GitHub Actions run for the complete release commit and tag is green
- [ ] Ensure local format, lint, and typecheck pass and the working tree is clean before running `release:prep:*`
- [ ] `npm run release:prep:patch`, `release:prep:minor`, or `release:prep:promote` created the version commit on `release/vX.Y.Z` without a tag, and the pushed branch passed `CI` and `Desktop Packages` before shipping (never relying on `main` CI)
- [ ] After go-ahead, `npm run release:ship` published npm, updated dist-tags, and pushed the `vX.Y.Z` tag without triggering a second CI run
- [ ] `latest` resolves to the new stable, and `beta` resolves to it too unless an active newer beta holds `beta`
- [ ] The GitHub Release was published only after the three stable manifests were uploaded, and it has the changelog body and every expected macOS, Linux, Windows, and Android APK asset
- [ ] GitHub `Desktop Release` workflow for the `v*` tag is green
@@ -848,5 +924,5 @@ Every entry covers `previous stable release → release source`: first beta, lat
- [ ] EAS iOS `submit_ios_for_review` succeeds, putting the build into App Store review
- [ ] EAS Android `build_android` completes for the same tag
- [ ] EAS Android `submit_android` succeeds, putting the build on its Play Store track
- [ ] The [reconcile PR](#reconcile-main) brought the shipped changelog entries and version into `main`
- [ ] The [reconcile PR](#reconcile-main) brought the shipped changelog entries, F-Droid changelogs, and version into `main`, and `origin/release/vX.Y.Z` was deleted
- [ ] The release heartbeat was created after the tag push and deleted only after every item above passed
@@ -0,0 +1,5 @@
- Antigravity approvals and history: Choose a permission mode, answer tool approvals, and import or reopen sessions. Requires Antigravity CLI 1.5.0 or later.
- Use existing worktrees: Start a workspace in a worktree you already have, or create one from a branch or pull request.
- Update providers in Paseo: See each provider's status and installed version, and update supported CLIs from the app.
Full notes: https://paseo.sh/changelog
@@ -0,0 +1,5 @@
- Antigravity approvals and history: Choose a permission mode, answer tool approvals, and import or reopen sessions. Requires Antigravity CLI 1.5.0 or later.
- Use existing worktrees: Start a workspace in a worktree you already have, or create one from a branch or pull request.
- Update providers in Paseo: See each provider's status and installed version, and update supported CLIs from the app.
Full notes: https://paseo.sh/changelog
@@ -0,0 +1,5 @@
- Antigravity approvals and history: Choose a permission mode, answer tool approvals, and import or reopen sessions. Requires Antigravity CLI 1.5.0 or later.
- Use existing worktrees: Start a workspace in a worktree you already have, or create one from a branch or pull request.
- Update providers in Paseo: See each provider's status and installed version, and update supported CLIs from the app.
Full notes: https://paseo.sh/changelog
@@ -0,0 +1,5 @@
- Antigravity approvals and history: Choose a permission mode, answer tool approvals, and import or reopen sessions. Requires Antigravity CLI 1.5.0 or later.
- Use existing worktrees: Start a workspace in a worktree you already have, or create one from a branch or pull request.
- Update providers in Paseo: See each provider's status and installed version, and update supported CLIs from the app.
Full notes: https://paseo.sh/changelog
+1 -1
View File
@@ -1 +1 @@
sha256-T3mbzIj0+IZBS4XA+4Ab6e6LtIi8PX4Rzs4wFEWeClk=
sha256-qZCOSeT264mXP2RcV+eD7lEkc3WAH1re6NjTtbQOHqY=
+39 -28
View File
@@ -1,12 +1,12 @@
{
"name": "paseo",
"version": "0.17.0-beta.1",
"version": "0.17.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "paseo",
"version": "0.17.0-beta.1",
"version": "0.17.1",
"hasInstallScript": true,
"license": "Apache-2.0",
"workspaces": [
@@ -6651,6 +6651,15 @@
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource-variable/plus-jakarta-sans": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource-variable/plus-jakarta-sans/-/plus-jakarta-sans-5.3.0.tgz",
"integrity": "sha512-/l/4r0yyWK9JzAlmA0LiYgGgmJe/Gswt4jTJEzr5QhJfwMbvJZDmYWyW0M4X7yCK69BajMVlV/Lx8g7WDc1+sw==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@getpaseo/app": {
"resolved": "packages/app",
"link": true
@@ -37468,7 +37477,7 @@
},
"packages/app": {
"name": "@getpaseo/app",
"version": "0.17.0-beta.1",
"version": "0.17.1",
"dependencies": {
"@codemirror/commands": "6.10.4",
"@codemirror/language": "6.12.4",
@@ -37508,6 +37517,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 +39647,13 @@
},
"packages/cli": {
"name": "@getpaseo/cli",
"version": "0.17.0-beta.1",
"version": "0.17.1",
"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.1",
"@getpaseo/protocol": "0.17.1",
"@getpaseo/server": "0.17.1",
"chalk": "^5.3.0",
"commander": "^12.0.0",
"mime-types": "^2.1.35",
@@ -39890,11 +39900,11 @@
},
"packages/client": {
"name": "@getpaseo/client",
"version": "0.17.0-beta.1",
"version": "0.17.1",
"license": "Apache-2.0",
"dependencies": {
"@getpaseo/protocol": "0.17.0-beta.1",
"@getpaseo/relay": "0.17.0-beta.1",
"@getpaseo/protocol": "0.17.1",
"@getpaseo/relay": "0.17.1",
"ws": "^8.20.0",
"zod": "^4.4.3"
},
@@ -39906,7 +39916,7 @@
},
"packages/desktop": {
"name": "@getpaseo/desktop",
"version": "0.17.0-beta.1",
"version": "0.17.1",
"license": "Apache-2.0",
"dependencies": {
"@getpaseo/cli": "*",
@@ -40149,7 +40159,7 @@
},
"packages/expo-two-way-audio": {
"name": "@getpaseo/expo-two-way-audio",
"version": "0.17.0-beta.1",
"version": "0.17.1",
"license": "MIT",
"devDependencies": {
"@types/jest": "^29.5.14",
@@ -40195,7 +40205,7 @@
},
"packages/highlight": {
"name": "@getpaseo/highlight",
"version": "0.17.0-beta.1",
"version": "0.17.1",
"license": "Apache-2.0",
"dependencies": {
"@codemirror/language": "6.12.4",
@@ -40225,7 +40235,7 @@
},
"packages/plugin": {
"name": "@getpaseo/plugin",
"version": "0.17.0-beta.1",
"version": "0.17.1",
"license": "Apache-2.0",
"dependencies": {
"@agentclientprotocol/sdk": "^1.4.0",
@@ -40233,8 +40243,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.1",
"@getpaseo/protocol": "0.17.1",
"@types/node": "^20.9.0",
"@types/react": "~19.2.0",
"react": "19.2.3",
@@ -40244,8 +40254,8 @@
"zod": "^4.4.3"
},
"peerDependencies": {
"@getpaseo/client": "0.17.0-beta.1",
"@getpaseo/protocol": "0.17.0-beta.1",
"@getpaseo/client": "0.17.1",
"@getpaseo/protocol": "0.17.1",
"react": ">=19.1.0 <20",
"react-native": ">=0.81.5",
"zod": "^4.4.3"
@@ -40267,7 +40277,7 @@
},
"packages/protocol": {
"name": "@getpaseo/protocol",
"version": "0.17.0-beta.1",
"version": "0.17.1",
"license": "Apache-2.0",
"dependencies": {
"semver": "^7.8.5",
@@ -40295,7 +40305,7 @@
},
"packages/relay": {
"name": "@getpaseo/relay",
"version": "0.17.0-beta.1",
"version": "0.17.1",
"license": "Apache-2.0",
"dependencies": {
"@noble/ciphers": "^2.4.0",
@@ -40517,17 +40527,17 @@
},
"packages/server": {
"name": "@getpaseo/server",
"version": "0.17.0-beta.1",
"version": "0.17.1",
"license": "Apache-2.0",
"dependencies": {
"@agentclientprotocol/sdk": "^0.17.1",
"@anthropic-ai/claude-agent-sdk": "0.3.326",
"@anthropic-ai/sdk": "^0.104.2",
"@getpaseo/client": "0.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.1",
"@getpaseo/highlight": "0.17.1",
"@getpaseo/plugin": "0.17.1",
"@getpaseo/protocol": "0.17.1",
"@getpaseo/relay": "0.17.1",
"@isaacs/ttlcache": "^2.1.4",
"@modelcontextprotocol/sdk": "1.29.0",
"@opencode-ai/sdk": "1.14.46",
@@ -41474,11 +41484,12 @@
},
"packages/website": {
"name": "@getpaseo/website",
"version": "0.17.0-beta.1",
"version": "0.17.1",
"dependencies": {
"@cloudflare/vite-plugin": "^1.29.1",
"@cloudflare/workers-types": "^4.20260317.1",
"@fontsource-variable/geist": "^5.3.0",
"@fontsource-variable/plus-jakarta-sans": "^5.3.0",
"@getpaseo/protocol": "*",
"@tanstack/react-router": "^1.170.16",
"@tanstack/react-start": "^1.168.26",
@@ -43084,7 +43095,7 @@
},
"plugins": {
"name": "@getpaseo/builtin-plugins",
"version": "0.17.0-beta.1",
"version": "0.17.1",
"dependencies": {
"@getpaseo/plugin": "*",
"zod": "^4.4.3"
+17 -14
View File
@@ -1,6 +1,6 @@
{
"name": "paseo",
"version": "0.17.0-beta.1",
"version": "0.17.1",
"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",
@@ -110,19 +110,22 @@
"version:all:beta:next": "node scripts/set-release-version.mjs --mode beta-next",
"version:all:promote": "node scripts/set-release-version.mjs --mode promote",
"release:check": "npm run release:prepare && npm run typecheck --workspace=@getpaseo/highlight && npm run typecheck --workspace=@getpaseo/relay && npm run typecheck --workspace=@getpaseo/protocol && npm run build:client:clean && npm run typecheck --workspace=@getpaseo/client && npm run typecheck --workspace=@getpaseo/plugin && npm run build:server:clean && npm run typecheck --workspace=@getpaseo/server && npm run typecheck --workspace=@getpaseo/cli && npm pack --dry-run --workspace=@getpaseo/highlight && npm pack --dry-run --workspace=@getpaseo/relay && npm pack --dry-run --workspace=@getpaseo/protocol && npm pack --dry-run --workspace=@getpaseo/client && npm pack --dry-run --workspace=@getpaseo/plugin && npm pack --dry-run --workspace=@getpaseo/server && npm pack --dry-run --workspace=@getpaseo/cli",
"release:publish:dry-run": "npm publish --dry-run --workspace=@getpaseo/highlight --access public && npm publish --dry-run --workspace=@getpaseo/relay --access public && npm publish --dry-run --workspace=@getpaseo/protocol --access public && npm publish --dry-run --workspace=@getpaseo/client --access public && npm publish --dry-run --workspace=@getpaseo/plugin --access public && npm publish --dry-run --workspace=@getpaseo/server --access public && npm publish --dry-run --workspace=@getpaseo/cli --access public",
"release:publish:beta:dry-run": "npm publish --dry-run --workspace=@getpaseo/highlight --access public --tag beta && npm publish --dry-run --workspace=@getpaseo/relay --access public --tag beta && npm publish --dry-run --workspace=@getpaseo/protocol --access public --tag beta && npm publish --dry-run --workspace=@getpaseo/client --access public --tag beta && npm publish --dry-run --workspace=@getpaseo/plugin --access public --tag beta && npm publish --dry-run --workspace=@getpaseo/server --access public --tag beta && npm publish --dry-run --workspace=@getpaseo/cli --access public --tag beta",
"release:publish": "npm publish --workspace=@getpaseo/highlight --access public && npm publish --workspace=@getpaseo/relay --access public && npm publish --workspace=@getpaseo/protocol --access public && npm publish --workspace=@getpaseo/client --access public && npm publish --workspace=@getpaseo/plugin --access public && npm publish --workspace=@getpaseo/server --access public && npm publish --workspace=@getpaseo/cli --access public",
"release:publish:beta": "npm publish --workspace=@getpaseo/highlight --access public --tag beta && npm publish --workspace=@getpaseo/relay --access public --tag beta && npm publish --workspace=@getpaseo/protocol --access public --tag beta && npm publish --workspace=@getpaseo/client --access public --tag beta && npm publish --workspace=@getpaseo/plugin --access public --tag beta && npm publish --workspace=@getpaseo/server --access public --tag beta && npm publish --workspace=@getpaseo/cli --access public --tag beta",
"release:prep:patch": "npm run release:check && npm run version:all:patch",
"release:prep:minor": "npm run release:check && npm run version:all:minor",
"release:prep:major": "npm run release:check && npm run version:all:major",
"release:prep:beta:patch": "npm run release:check && npm run version:all:beta:patch",
"release:prep:beta:minor": "npm run release:check && npm run version:all:beta:minor",
"release:prep:beta:major": "npm run release:check && npm run version:all:beta:major",
"release:prep:beta:next": "npm run release:check && npm run version:all:beta:next",
"release:prep:promote": "npm run release:check && npm run version:all:promote",
"release:publish:dry-run": "node scripts/publish-release-packages.mjs --dry-run",
"release:publish:beta:dry-run": "node scripts/publish-release-packages.mjs --beta --dry-run",
"release:publish": "node scripts/publish-release-packages.mjs",
"release:publish:beta": "node scripts/publish-release-packages.mjs --beta",
"release:push": "node scripts/push-current-release-tag.mjs",
"release:beta:patch": "npm run release:check && npm run version:all:beta:patch && npm run release:publish:beta && npm run release:push",
"release:beta:minor": "npm run release:check && npm run version:all:beta:minor && npm run release:publish:beta && npm run release:push",
"release:beta:major": "npm run release:check && npm run version:all:beta:major && npm run release:publish:beta && npm run release:push",
"release:beta:next": "npm run release:check && npm run version:all:beta:next && npm run release:publish:beta && npm run release:push",
"release:promote": "npm run release:check && npm run version:all:promote && npm run release:publish && npm run release:push",
"release:patch": "npm run release:check && npm run version:all:patch && npm run release:publish && npm run release:push",
"release:minor": "npm run release:check && npm run version:all:minor && npm run release:publish && npm run release:push",
"release:major": "npm run release:check && npm run version:all:major && npm run release:publish && npm run release:push"
"release:ship": "node scripts/push-current-release-tag.mjs --check && npm run release:publish && npm run release:push",
"release:ship:beta": "node scripts/push-current-release-tag.mjs --check && npm run release:publish:beta && npm run release:push",
"release:reconcile": "node scripts/reconcile-release.mjs"
},
"devDependencies": {
"@types/ws": "^8.5.14",
@@ -59,6 +59,35 @@ async function selectClientSlashCommand(page: Page, query: string, label: string
await input.press("Enter");
}
async function typeBeforeMenuFilters(
page: Page,
input: { text: string; key: "Tab" | "Enter" },
): Promise<void> {
await composerLocator(page).evaluate(async (element, { text, key }) => {
if (!(element instanceof HTMLTextAreaElement)) {
throw new Error("Composer input is not a textarea");
}
const setValue = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, "value")?.set;
if (!setValue) throw new Error("Textarea value setter is unavailable");
setValue.call(element, text);
element.setSelectionRange(text.length, text.length);
element.dispatchEvent(new Event("input", { bubbles: true }));
await Promise.resolve();
element.dispatchEvent(new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true }));
await new Promise((resolve) => requestAnimationFrame(() => setTimeout(resolve, 0)));
}, input);
}
async function showExitSuggestion(page: Page, query: string): Promise<void> {
await composerLocator(page).fill(query);
await expect(page.getByText("/exit", { exact: true }).first()).toBeVisible();
}
async function expectOpenAgentWithInput(page: Page, agentId: string, text: string): Promise<void> {
await expect(composerLocator(page)).toHaveValue(text);
await expectWorkspaceTabVisible(page, agentId);
}
async function expectAgentArchivedInSessions(page: Page, title: string): Promise<void> {
await openSessions(page);
await expectSessionRowArchived(page, title);
@@ -131,6 +160,16 @@ test.describe("Client slash commands", () => {
);
});
for (const key of ["Tab", "Enter"] as const) {
test(`${key} ignores an exit suggestion for an earlier query`, async ({ page }) => {
await withOpenReadyMockAgent(page, { title: "Stale slash command" }, async ({ agentId }) => {
await showExitSuggestion(page, "/e");
await typeBeforeMenuFilters(page, { text: "/co", key });
await expectOpenAgentWithInput(page, agentId, "/co");
});
});
}
test("slash clear replaces the active agent with a matching draft", async ({ page }) => {
await withOpenReadyMockAgent(
page,
@@ -0,0 +1,143 @@
import type { Locator } from "@playwright/test";
import { expect, test, type Page } from "../support/fixtures";
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
const APP_SETTINGS_KEY = "@paseo:app-settings";
async function useLanguage(page: Page, language: string): Promise<void> {
await page.addInitScript(
({ key, language: value }) => {
localStorage.setItem(key, JSON.stringify({ language: value }));
},
{ key: APP_SETTINGS_KEY, language },
);
}
/**
* Lays the placeholder out the way the textarea does, in a mirror element with
* the same box and font, and reports whether any of its lines reach the hint.
*/
async function placeholderOverlaps(input: Locator, hint: Locator): Promise<boolean> {
const hintBox = await hint.boundingBox();
if (!hintBox) throw new Error("Focus hint has no layout box");
return input.evaluate((element, box) => {
const textarea = element as HTMLTextAreaElement;
const style = getComputedStyle(textarea);
const rect = textarea.getBoundingClientRect();
const mirror = document.createElement("div");
for (const property of [
"boxSizing",
"paddingTop",
"paddingRight",
"paddingBottom",
"paddingLeft",
"borderTopWidth",
"borderRightWidth",
"borderBottomWidth",
"borderLeftWidth",
"fontFamily",
"fontSize",
"fontWeight",
"letterSpacing",
"lineHeight",
"textIndent",
"wordSpacing",
] as const) {
mirror.style[property] = style[property];
}
Object.assign(mirror.style, {
position: "fixed",
left: `${rect.left}px`,
top: `${rect.top}px`,
width: `${rect.width}px`,
borderStyle: "solid",
borderColor: "transparent",
whiteSpace: "pre-wrap",
overflowWrap: "break-word",
visibility: "hidden",
});
const text = document.createTextNode(textarea.placeholder);
mirror.appendChild(text);
document.body.appendChild(mirror);
const range = document.createRange();
range.selectNodeContents(text);
const lines = Array.from(range.getClientRects());
mirror.remove();
return lines.some(
(line) =>
line.right > box.x &&
line.left < box.x + box.width &&
line.bottom > box.y &&
line.top < box.y + box.height,
);
}, hintBox);
}
async function recordFirstVisibleHint(page: Page): Promise<void> {
await page.addInitScript(() => {
function sample() {
const root = document.querySelector('[data-testid="message-input-root"]');
const input = root?.querySelector("textarea");
const hint = Array.from(root?.querySelectorAll("div") ?? []).find(
(element) => !element.childElementCount && element.textContent?.endsWith("pour saisir"),
);
if (!input || !hint || Number(getComputedStyle(hint).opacity) === 0) {
requestAnimationFrame(sample);
return;
}
const inputRight = input.getBoundingClientRect().right;
const textRight = inputRight - parseFloat(getComputedStyle(input).paddingRight);
const hintLeft = hint.getBoundingClientRect().left;
Reflect.set(window, "__firstVisibleHintHasSpace", textRight <= hintLeft + 1);
}
requestAnimationFrame(sample);
});
}
async function expectFirstVisibleHintHasSpace(page: Page): Promise<void> {
await expect
.poll(() => page.evaluate(() => Reflect.get(window, "__firstVisibleHintHasSpace")))
.toBe(true);
}
const FRENCH_LAYOUTS = [
{ name: "phone width", width: 390, placeholder: "Message, @fichiers, /commandes" },
{
name: "desktop width",
width: 1024,
placeholder:
"Écrivez à l’agent, mentionnez des @fichiers ou utilisez les /commandes et /skills",
},
];
for (const layout of FRENCH_LAYOUTS) {
test.describe(`French composer at ${layout.name}`, () => {
test.use({ viewport: { width: layout.width, height: 844 } });
test("the focus hint does not cover the placeholder", async ({ page }) => {
const agent = await seedMockAgentWorkspace({
repoPrefix: "composer-focus-hint-",
title: "Composer focus hint",
});
try {
await useLanguage(page, "fr");
await recordFirstVisibleHint(page);
await openAgentRoute(page, agent);
const input = page.getByRole("textbox", { name: "Écrire à l’agent…" }).first();
await expect(input).toBeVisible();
await expect(input).toHaveAttribute("placeholder", layout.placeholder);
await input.blur();
const hint = page.getByText(/pour saisir$/).first();
await expect(hint).toBeVisible();
// The input takes the hint's width on the render after the hint lays out.
await expect.poll(() => placeholderOverlaps(input, hint)).toBe(false);
await expectFirstVisibleHintHasSpace(page);
} finally {
await agent.cleanup();
}
});
});
}
@@ -18,6 +18,7 @@ import {
expectComposerFullscreenControls,
sendComposerWithButton,
queueComposerWithButton,
fillComposerDraft,
configureComposerQueueSend,
activateRetainedComposerTab,
switchComposerTabWithKeyboard,
@@ -450,6 +451,32 @@ test("fullscreen Send keeps the configured queue behavior while an agent runs",
}
});
test("editing a queued draft restores its original height with the focus hint visible", async ({
page,
}) => {
await configureComposerQueueSend(page);
await resizeComposerViewport(page, "portrait");
const agent = await startRunningMockAgent(page, {
prefix: "composer-queued-draft-height-",
model: "one-minute-stream",
prompt: "Stay running while a draft is queued.",
});
try {
const draft = "Please review the latest changes.\nPlease review the latest changes.";
await fillComposerDraft(page, draft);
const originalHeight = await composerHeight(page);
await queueComposerWithButton(page);
await expect(composerLocator(page)).toHaveValue("");
await composerLocator(page).blur();
await expect(page.getByText(/ to focus$/)).toBeVisible();
await page.getByRole("button", { name: "Edit queued message", exact: true }).click();
await expect(composerLocator(page)).toHaveValue(draft);
await expectComposerHeight(page, originalHeight);
} finally {
await agent.cleanup();
}
});
test("image paste stays attached to the active editor across fullscreen entry and exit", async ({
page,
}) => {
@@ -1,4 +1,21 @@
import { execFileSync } from "node:child_process";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import type { createCreationScenario } from "../support/helpers/creation";
import { gotoAppShell } from "../support/helpers/app";
import { fillComposerDraft } from "../support/helpers/composer";
import {
connectNewWorkspaceDaemonClient,
openNewWorkspaceComposer,
selectWorkspaceIsolation,
} from "../support/helpers/new-workspace";
import {
seedTerminalProfiles,
selectLaunchOption,
submitTerminalLaunch,
} from "../support/helpers/new-workspace-launch";
import { waitForSidebarHydration } from "../support/helpers/workspace-ui";
import { expect } from "../support/fixtures";
import { test } from "../support/creation-fixtures";
@@ -116,12 +133,14 @@ for (const scenario of [
test(`retrying failed agent initialization preserves its workspace${scenario.suffix}`, async ({
creation,
startup,
page,
}) => {
await creation.openWorkspaceForm("local");
await creation.submitPrompt("Retry this workspace and agent together.", "Create");
await creation.expectAgentStillStarting();
await startup.fail();
await creation.expectStartupFailure();
await expect(page.getByTestId("app-toast")).toHaveCount(0);
await creation.expectOneCreatedWorkspace();
await scenario.prepare(creation);
await creation.submitPrompt("Retry this workspace and agent together.");
@@ -180,6 +199,105 @@ test("an edited agent draft starts after its first start failed", async ({
await expect(page.getByText(/request_key_conflict/)).toHaveCount(0);
});
test("editing a failed New workspace submission starts without a request key conflict", async ({
page,
}) => {
// An empty git repository naturally rejects worktree creation before workspace_ready.
const repoDir = mkdtempSync(path.join(tmpdir(), "paseo-empty-git-ws-"));
execFileSync("git", ["init"], { cwd: repoDir, stdio: "ignore" });
const client = await connectNewWorkspaceDaemonClient();
let projectId: string | null = null;
try {
const seeded = await client.createWorkspace({
source: { kind: "directory", path: repoDir },
});
if (!seeded.workspace) throw new Error(seeded.error ?? "Failed to seed empty git project");
projectId = seeded.workspace.projectId;
const listed = await client.listProjects();
const project = listed.projects.find((entry) => entry.projectId === projectId);
if (!project?.projectKey) throw new Error("Seeded project has no projectKey");
await gotoAppShell(page);
await waitForSidebarHydration(page);
await openNewWorkspaceComposer(page, {
projectKey: project.projectKey,
projectDisplayName: seeded.workspace.projectDisplayName,
});
await selectWorkspaceIsolation(page, "worktree");
await fillComposerDraft(page, "Start original worktree task.");
await page.getByRole("button", { name: "Create", exact: true }).click();
const composerError = page.getByTestId("composer-error").filter({ visible: true }).first();
await expect(composerError).toContainText("Unable to resolve repository default branch");
// The failure renders once in the composer alert, not duplicated in a top toast.
await expect(page.getByText("Unable to resolve repository default branch")).toHaveCount(1);
await selectWorkspaceIsolation(page, "local");
await fillComposerDraft(page, "hi");
await page.getByRole("button", { name: "Create", exact: true }).click();
await expect(page).toHaveURL(/\/workspace\//);
await expect(page.getByText(/request_key_conflict/)).toHaveCount(0);
await expect(
page.getByTestId("user-message").filter({ hasText: "hi", visible: true }),
).toBeVisible();
} finally {
if (projectId) await client.removeProject(projectId).catch(() => undefined);
await client.close();
rmSync(repoDir, { recursive: true, force: true });
}
});
test("switching only the launch target after a failed New workspace creation starts a new workspace", async ({
creation,
workspaceProvision,
page,
}) => {
const profiles = await seedTerminalProfiles([
{
id: "promptless-shell",
name: "Promptless Shell",
command: "sh",
args: ["-c", "echo ready; sleep 5"],
promptArg: "none",
},
]);
try {
await creation.openWorkspaceForm("local");
await workspaceProvision.fail();
await page.getByRole("button", { name: "Create", exact: true }).click();
await expect(
page.getByTestId("composer-error").filter({ visible: true }).first(),
).toContainText("Workspace provisioning failed for test");
await selectLaunchOption(page, "promptless-shell");
await submitTerminalLaunch(page);
await creation.expectOneCreatedWorkspace();
await expect(
page.locator('[data-testid^="workspace-tab-terminal_"]').filter({ visible: true }).first(),
).toBeVisible();
} finally {
await profiles.restore();
}
});
test("failing New workspace creation after switching workspaces shows an error toast", async ({
creation,
workspaceProvision,
page,
}) => {
await creation.openWorkspaceForm("local");
await workspaceProvision.hold();
await page.getByRole("button", { name: "Create", exact: true }).click();
await page.locator('[data-testid^="sidebar-workspace-row-"]').first().click();
await expect(page).toHaveURL(/\/workspace\//);
await workspaceProvision.fail();
await expect(page.getByTestId("app-toast")).toContainText(
"Workspace provisioning failed for test",
);
});
for (const entry of [
{
name: "agent draft",
@@ -1,3 +1,5 @@
import { mkdir, rm, writeFile } from "node:fs/promises";
import { dirname } from "node:path";
import { expect, test } from "../support/fixtures";
import { gotoAppShell, openSettings } from "../support/helpers/app";
import {
@@ -49,8 +51,10 @@ interface ProviderConfigClient {
}): Promise<unknown>;
}
test("adds and removes a custom model while the provider fails", async ({ page }) => {
test("adds and removes a custom model while the provider fails", async ({ page }, testInfo) => {
test.setTimeout(120_000);
const discoveryGate = testInfo.outputPath("hold-provider-discovery");
await mkdir(dirname(discoveryGate), { recursive: true });
const client = await connectDaemonClient<ProviderConfigClient>({
clientIdPrefix: "custom-model-failing-e2e",
});
@@ -60,7 +64,14 @@ test("adds and removes a custom model while the provider fails", async ({ page }
[FAILING_PROVIDER.id]: {
extends: "acp",
label: FAILING_PROVIDER.name,
command: ["node", "-e", "process.exit(1)"],
command: [
"node",
"-e",
'const { existsSync } = require("node:fs");' +
"const exitIfReleased = () => { if (!existsSync(process.argv[1])) process.exit(1); };" +
"exitIfReleased(); setInterval(exitIfReleased, 25);",
discoveryGate,
],
},
},
});
@@ -76,9 +87,15 @@ test("adds and removes a custom model while the provider fails", async ({ page }
await expect(page.getByRole("textbox", { name: "Search models" })).toHaveCount(0);
});
await addCustomModel(page, shortModelId);
await test.step("saving closes the Add sheet while provider discovery is still pending", async () => {
await writeFile(discoveryGate, "");
await addCustomModel(page, shortModelId);
});
await rm(discoveryGate);
await expect(page.getByTestId("provider-error")).toBeVisible({ timeout: 30_000 });
await removeListedCustomModel(page, shortModelId);
} finally {
await rm(discoveryGate, { force: true });
await client
.patchDaemonConfig({ removeProviders: [FAILING_PROVIDER.id] })
.catch(() => undefined);
@@ -118,7 +118,8 @@ async function exerciseProviderSettingsStack(page: Page) {
await page.getByRole("button", { name: "Refresh", exact: true }).click();
await expectProviderSettingsVisible(page);
await expect(page.getByText("Checked just now", { exact: true })).toBeVisible({
// The Models header puts the model count before it: "12 · Checked just now".
await expect(page.getByText(/Checked just now$/)).toBeVisible({
timeout: 30_000,
});
}
@@ -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 &&
@@ -0,0 +1,101 @@
import { expect, type Locator, type Page } from "@playwright/test";
import { test } from "../support/fixtures";
import { runWorkspaceActionFromCommandCenter } from "../support/helpers/command-center-workspace-actions";
import { clickNewChat, gotoWorkspace } from "../support/helpers/launcher";
import { seedWorkspace } from "../support/helpers/seed-client";
import { waitForWorkspaceTabsVisible } from "../support/helpers/workspace-tabs";
const DRAG_DISTANCE = -40;
function splitDividers(page: Page): Locator {
return page.getByTestId("workspace-split-resize-handle").filter({ visible: true });
}
async function dividerX(divider: Locator): Promise<number> {
const box = await divider.boundingBox();
if (!box) throw new Error("Divider has no bounding box");
return box.x;
}
async function dragDivider(divider: Locator, deltaX: number): Promise<void> {
const page = divider.page();
const box = await divider.boundingBox();
if (!box) throw new Error("Divider has no bounding box");
const x = box.x + box.width / 2;
const y = box.y + box.height / 2;
await page.mouse.move(x, y);
await page.mouse.down();
await page.mouse.move(x + deltaX / 2, y, { steps: 4 });
await page.mouse.move(x + deltaX, y, { steps: 4 });
await page.mouse.up();
}
async function expectDividerFollowsDrag({
page,
index,
}: {
page: Page;
index: number;
}): Promise<void> {
const divider = splitDividers(page).nth(index);
const before = await dividerX(divider);
await dragDivider(divider, DRAG_DISTANCE);
await expect
.poll(async () => (await dividerX(divider)) - before, {
message: `divider ${index + 1} should follow the drag`,
})
.toBeLessThan(DRAG_DISTANCE * 0.75);
}
async function splitRight({
page,
expectedDividers,
}: {
page: Page;
expectedDividers: number;
}): Promise<void> {
await runWorkspaceActionFromCommandCenter(page, "Split pane right");
await expect(splitDividers(page)).toHaveCount(expectedDividers);
}
test.describe("Split pane resize", () => {
test("every divider drags in a four-pane row", async ({ page }) => {
await page.setViewportSize({ width: 1600, height: 900 });
const workspace = await seedWorkspace({ repoPrefix: "split-resize-fresh-" });
try {
await gotoWorkspace(page, workspace.workspaceId);
await waitForWorkspaceTabsVisible(page);
await clickNewChat(page);
await splitRight({ page, expectedDividers: 1 });
await splitRight({ page, expectedDividers: 2 });
await splitRight({ page, expectedDividers: 3 });
for (const index of [0, 1, 2]) {
await expectDividerFollowsDrag({ page, index });
}
} finally {
await workspace.cleanup();
}
});
test("every divider drags after panes are added to a resized row", async ({ page }) => {
await page.setViewportSize({ width: 1600, height: 900 });
const workspace = await seedWorkspace({ repoPrefix: "split-resize-grown-" });
try {
await gotoWorkspace(page, workspace.workspaceId);
await waitForWorkspaceTabsVisible(page);
await clickNewChat(page);
await splitRight({ page, expectedDividers: 1 });
await expectDividerFollowsDrag({ page, index: 0 });
await splitRight({ page, expectedDividers: 2 });
await splitRight({ page, expectedDividers: 3 });
for (const index of [0, 1, 2]) {
await expectDividerFollowsDrag({ page, index });
}
} finally {
await workspace.cleanup();
}
});
});
+26 -11
View File
@@ -836,6 +836,8 @@ test("usage percentages state their meaning and follow the selected language", a
}
});
const exhaustionClock = /^runs out (?:[A-Z][a-z]{2} )?\d{1,2}:\d{2}(?: [AP]M)?$/;
test("open usage clocks advance without refreshing or reopening", async ({ page }) => {
test.setTimeout(120_000);
const now = new Date();
@@ -853,12 +855,16 @@ test("open usage clocks advance without refreshing or reopening", async ({ page
const card = page.getByTestId("usage-report-login-journey:account");
await expect(card.getByTestId("usage-freshness")).toHaveText("Updated just now");
await expect(card.getByText("resets in 30m", { exact: false }).first()).toBeVisible();
const forecast = card.getByText(exhaustionClock);
await expect(forecast).toBeVisible();
const forecastTime = (await forecast.innerText()).replace(/^[^0-9]+/, "");
// The shared minute clock is wall-aligned, and the daemon timestamps use real time.
// After two browser minutes the latest displayed tick is one or two minutes old.
await advanceUsageClock(page, 120_000);
await expect(card.getByTestId("usage-freshness")).toHaveText(/^Updated [12]m ago$/);
await expect(card.getByText(/resets in (28|29)m/).first()).toBeVisible();
await expect(card.getByText(/runs out in (28|29)m/)).toBeVisible();
// The weekday drops off at local midnight, but the forecast time stays fixed.
await expect(forecast).toHaveText(new RegExp(` ${forecastTime}$`));
await expect(card.getByTestId("provider-usage-balance-credits-reset")).toHaveText(
/^resets in (28|29)m\s·\s/,
);
@@ -867,7 +873,7 @@ 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 ({
test("Refresh all keeps quota visible after a timeout and shows only reset details when back on track", async ({
page,
}) => {
const reading = new Date();
@@ -875,7 +881,7 @@ test("Refresh all keeps quota visible and restores the forecast after a timeout"
try {
const transport = await installDaemonWebSocketGate(page);
await openCompactUsageWithClock(page, reading);
await expectQuota(page, "40% used", /runs out in /);
await expectQuota(page, "40% used", exhaustionClock);
await timeOutUsageRefresh(page, transport);
await expectQuota(page, "40% used", null);
@@ -884,7 +890,7 @@ test("Refresh all keeps quota visible and restores the forecast after a timeout"
await login.setReport(usageReading(reading, 10));
transport.releaseHeldClientRequest();
await refreshAllUsage(page);
await expectQuota(page, "10% used", "~50% left at reset");
await expectQuota(page, "10% used", null);
await expectUsageRefreshError(page).toBeHidden();
} finally {
await login.cleanup();
@@ -897,23 +903,29 @@ test("a card refresh timeout is visible alongside a newer quota forecast", async
try {
const transport = await installDaemonWebSocketGate(page);
await openCompactUsageWithClock(page, reading);
await expectQuota(page, "40% used", /runs out in /);
await expectQuota(page, "40% used", exhaustionClock);
await delayCardRefreshResponse(page, transport);
await login.setReport(usageReading(reading, 10));
await login.setReport(usageReading(reading, 45));
await refreshAllUsage(page);
await expectQuota(page, "10% used", "~50% left at reset");
await expectQuota(page, "45% used", exhaustionClock);
await advanceUsageClock(page, 61_000);
await expectUsageRefreshError(page).toBeVisible();
await expectQuota(page, "10% used", "~50% left at reset");
await expect(
usageModal(page)
.getByTestId("usage-report-login-journey:account")
.getByTestId("usage-refresh-error"),
).toHaveText("Unable to refresh usage");
await expectQuota(page, "45% used", exhaustionClock);
} finally {
await login.cleanup();
}
});
function expectUsageRefreshError(page: Page) {
return expect(usageModal(page).getByText("Unable to refresh usage", { exact: true }));
return expect(
usageModal(page).getByRole("alert").getByText("Unable to refresh usage", { exact: true }),
);
}
async function delayCardRefreshResponse(
@@ -947,7 +959,10 @@ async function expectQuota(page: Page, amount: string, forecast: string | RegExp
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();
await expect(usage.getByRole("checkbox", { name: /^Pin Claude Session/ })).toHaveAccessibleName(
/^Pin Claude Session, \d+% used · resets in [^·]+ · [^·]+$/,
);
await expect(usage.getByText(/^runs out /)).toBeHidden();
return;
}
await expect(usage.getByText(forecast)).toBeVisible();
@@ -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,
}) => {
@@ -15,6 +15,11 @@ import { delayBrowserAgentCreatedStatus } from "./helpers/new-workspace";
export const test = base.extend<{
startup: { release(): Promise<void>; fail(): Promise<void> };
workspaceProvision: {
hold(): Promise<void>;
fail(): Promise<void>;
release(): Promise<void>;
};
promptRejection: void;
composerMetadata: { set(patch: Record<string, string>): Promise<void> };
creation: Awaited<ReturnType<typeof createCreationScenario>>;
@@ -70,6 +75,57 @@ export default function contribute(server) {
await client.close();
}
},
workspaceProvision: async ({ page }, provide) => {
void page;
const client = await connectNewWorkspaceDaemonClient();
const plugin = await copyPluginExample("lifecycle-logger");
const gate = path.join(plugin.directory, "workspace-provision.txt");
const holdFile = path.join(plugin.directory, "workspace-provision-hold.txt");
const failFile = path.join(plugin.directory, "workspace-provision-fail.txt");
const previous = await client.getDaemonConfig();
try {
await writeFile(
path.join(plugin.directory, "index.server.ts"),
`
import { readFile, rm } from "node:fs/promises";
export default function contribute(server) {
return server.before("workspace.create", async ({ request }) => {
const gate = ${JSON.stringify(gate)};
let command = await readFile(gate, "utf8").catch(() => "release");
while (command === "hold") {
await new Promise(resolve => setTimeout(resolve, 20));
command = await readFile(gate, "utf8").catch(() => "release");
}
if (command === "fail") {
await rm(gate, { force: true });
throw new Error("Workspace provisioning failed for test");
}
return request;
});
}
`,
);
await client.patchDaemonConfig({ pluginsEnabled: true });
await client.installDirectoryPlugin(plugin.directory);
await provide({
hold: async () => {
await writeFile(holdFile, "hold");
await rename(holdFile, gate);
},
fail: async () => {
await writeFile(failFile, "fail");
await rename(failFile, gate);
},
release: () => rm(gate, { force: true }),
});
} finally {
await rm(gate, { force: true });
await client.removePlugin("lifecycle-logger");
await client.patchDaemonConfig({ pluginsEnabled: previous.config.pluginsEnabled });
await plugin.cleanup();
await client.close();
}
},
promptRejection: async ({ page }, provide) => {
void page;
const client = await connectNewWorkspaceDaemonClient();
@@ -19,8 +19,6 @@ export async function addCustomModel(page: Page, id: string): Promise<void> {
.getByRole("button", { name: "Add", exact: true })
.click();
await expect(page.getByRole("button", { name: `Remove ${id}`, exact: true })).toHaveCount(1);
// Config updates before provider refresh finishes and dismisses the add sheet.
// Resizing or interacting with the model list must wait for that save to finish.
await expect(page.getByTestId("add-custom-model-sheet")).toBeHidden();
}
+3 -1
View File
@@ -567,7 +567,9 @@ export async function expectProviderPageLoaded(page: Page, providerName: string)
await expect(page.getByTestId("provider-detail-title")).toHaveText(providerName, {
timeout: 30_000,
});
await expect(page.getByText("Provider status")).toBeVisible({ timeout: 30_000 });
await expect(page.getByRole("button", { name: "Diagnostic report" })).toBeVisible({
timeout: 30_000,
});
}
export async function expectProviderNotOnHost(page: Page): Promise<void> {
+2 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/app",
"version": "0.17.0-beta.1",
"version": "0.17.1",
"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",
+19
View File
@@ -29,6 +29,25 @@ export function agentCommandsQueryRoot(serverId: string) {
return [AGENT_COMMANDS_QUERY_ROOT, serverId] as const;
}
function queryCommandsCwd(query: { queryKey: readonly unknown[]; meta?: Record<string, unknown> }) {
const isDraft = query.queryKey[2] === "draft";
const cwd = query.meta?.agentCommandCwd ?? (isDraft ? query.queryKey[4] : undefined);
return typeof cwd === "string" ? normalizeAgentCommandsCwd(cwd) : undefined;
}
/** Marks every catalog for a directory stale. Only observed catalogs refetch; the rest refetch
* when next mounted. Used when a provider change is announced without its new snapshot. */
export function invalidateCommandsForDirectory(input: {
queryClient: QueryClient;
serverId: string;
cwd: string | null;
}): Promise<void> {
return input.queryClient.invalidateQueries({
queryKey: agentCommandsQueryRoot(input.serverId),
predicate: (query) => !input.cwd || queryCommandsCwd(query) === input.cwd,
});
}
/** Snapshot announcements contain provider metadata, not command catalogs. Ignore initial
* discovery and unrelated providers; explicit refresh still invalidates every catalog. */
export function invalidateCommandsForProviderChange(input: {
@@ -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">
@@ -1,13 +1,15 @@
import { AppearanceText as Text } from "@/appearance/text";
import { ChevronRight } from "lucide-react-native";
import { useMemo, type ReactNode } from "react";
import { Platform, ScrollView, View } from "react-native";
import { Platform, ScrollView, View, type PressableStateCallbackType } from "react-native";
import { KeyboardAwareScrollView } from "react-native-keyboard-controller";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { StyleSheet } from "react-native-unistyles";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { BackHeader } from "@/components/headers/back-header";
import { MenuHeader } from "@/components/headers/menu-header";
import { PressHighlight } from "@/components/ui/press-highlight";
import { useIsCompactFormFactor } from "@/constants/layout";
import { SPACING } from "@/styles/theme";
import { ICON_SIZE, SPACING, type Theme } from "@/styles/theme";
const PageScrollView = Platform.OS === "android" ? KeyboardAwareScrollView : ScrollView;
@@ -58,14 +60,7 @@ export function PageLayout({
testID={testID}
>
<View style={width === "wide" ? styles.contentWide : styles.content}>
{showTitle ? (
<View style={styles.titleRow} testID={titleTestID}>
<Text style={styles.title} testID="page-title">
{title}
</Text>
{actions}
</View>
) : null}
{showTitle ? <PageTitle title={title} actions={actions} testID={titleTestID} /> : null}
{children}
</View>
</PageScrollView>
@@ -73,6 +68,77 @@ export function PageLayout({
);
}
/** The page that holds this one. Its name is the first part of the title and goes back to it. */
export interface PageTitleParent {
label: string;
/** What the press does, such as "Back to providers". */
accessibilityLabel: string;
onPress: () => void;
testID?: string;
}
interface PageTitleProps {
parent?: PageTitleParent;
/** Drawn before the title, such as the icon of the thing the page is about. */
icon?: ReactNode;
title?: string;
/** A control that belongs to the title, drawn right after it. */
adornment?: ReactNode;
/** Controls for the whole page, drawn at the trailing edge. */
actions?: ReactNode;
testID?: string;
titleTestID?: string;
}
/**
* The heading of a desktop page. A page that opens from another page, such as one provider from
* Providers, names that page first: "Providers > Antigravity".
*/
export function PageTitle({
parent,
icon,
title,
adornment,
actions,
testID,
titleTestID = "page-title",
}: PageTitleProps) {
return (
<View style={styles.titleRow} testID={testID}>
<View style={styles.titleParts}>
{parent ? (
<PressHighlight
accessibilityRole="button"
accessibilityLabel={parent.accessibilityLabel}
onPress={parent.onPress}
testID={parent.testID}
>
{({ hovered }: PressableStateCallbackType & { hovered?: boolean }) => (
<Text style={[styles.title, styles.parent, hovered && styles.parentHovered]}>
{parent.label}
</Text>
)}
</PressHighlight>
) : null}
{parent && title !== undefined ? (
<ThemedChevronRight size={ICON_SIZE.lg} uniProps={separatorColor} />
) : null}
{icon}
{title !== undefined ? (
<Text style={[styles.title, styles.titleLeaf]} numberOfLines={1} testID={titleTestID}>
{title}
</Text>
) : null}
{adornment}
</View>
{actions}
</View>
);
}
const ThemedChevronRight = withUnistyles(ChevronRight);
const separatorColor = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
const styles = StyleSheet.create((theme) => ({
container: {
flex: 1,
@@ -102,11 +168,27 @@ const styles = StyleSheet.create((theme) => ({
gap: theme.spacing[4],
marginBottom: theme.spacing[6],
},
title: {
titleParts: {
// Line up with the section titles, which sit inset from their cards.
marginLeft: theme.spacing[1],
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[2],
flexShrink: 1,
minWidth: 0,
},
title: {
fontSize: theme.fontSize["4xl"],
fontWeight: theme.fontWeight.medium,
color: theme.colors.foreground,
},
titleLeaf: {
flexShrink: 1,
},
parent: {
color: theme.colors.foregroundMuted,
},
parentHovered: {
color: theme.colors.foreground,
},
}));
@@ -2,7 +2,9 @@ import { ArrowLeft } from "lucide-react-native";
import type { ReactNode } from "react";
import { Text, View } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { PageTitle, type PageTitleParent } from "@/components/page-layout";
import { Button } from "@/components/ui/button";
import { useIsCompactFormFactor } from "@/constants/layout";
/**
* "Back to …" above a settings detail page on wide layouts, where the page has no header of its
@@ -32,32 +34,43 @@ export function SettingsBackLink({
}
/**
* The top of a settings detail page: "Back to …" when the page has no header of its own, then the
* icon and name the page is about, with an optional action after the name.
* The top of a settings detail page: the icon and name of the thing the page is about, with an
* optional action after the name. On wide layouts it is the page's title and names the parent page
* first, which goes back to it. On compact layouts the back header already names the parent.
*/
export function SettingsDetailHeader({
back,
parent,
icon,
title,
trailing,
titleTestID,
}: {
back?: { label: string; onPress: () => void; testID?: string };
icon: ReactNode;
title: string;
parent: PageTitleParent;
icon?: ReactNode;
/** Absent while the page has nothing to name, such as a project that no longer exists. */
title?: string;
trailing?: ReactNode;
titleTestID?: string;
}) {
const isCompact = useIsCompactFormFactor();
if (!isCompact)
return (
<PageTitle
parent={parent}
icon={icon}
title={title}
adornment={trailing}
titleTestID={titleTestID}
/>
);
if (title === undefined) return null;
return (
<View style={styles.header}>
{back ? <SettingsBackLink {...back} /> : null}
<View style={styles.titleRow}>
{icon}
<Text style={styles.title} numberOfLines={1} testID={titleTestID}>
{title}
</Text>
{trailing}
</View>
<View style={styles.titleRow}>
{icon}
<Text style={styles.title} numberOfLines={1} testID={titleTestID}>
{title}
</Text>
{trailing}
</View>
);
}
@@ -67,15 +80,13 @@ const styles = StyleSheet.create((theme) => ({
alignSelf: "flex-start",
paddingHorizontal: 0,
},
header: {
gap: theme.spacing[2],
marginBottom: theme.spacing[4],
},
titleRow: {
marginTop: theme.spacing[2],
// Line up with the section titles, which sit inset from their cards.
marginLeft: theme.spacing[1],
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[3],
marginBottom: theme.spacing[4],
},
title: {
color: theme.colors.foreground,
@@ -0,0 +1,22 @@
import type { ReactNode } from "react";
import { View } from "react-native";
import { StyleSheet } from "react-native-unistyles";
/**
* The action at a heading's end. It adds no height, so a heading with a button is as tall as one
* without and both sit the same distance from their cards. The button stays centered on the title
* and its hit area grows past the heading.
*/
export function HeadingTrailing({ children }: { children: ReactNode }) {
if (children === null || children === undefined || children === false) return null;
return <View style={styles.trailing}>{children}</View>;
}
const styles = StyleSheet.create({
trailing: {
height: 0,
justifyContent: "center",
// A long trailing gives way to the title.
flexShrink: 1,
},
});
@@ -1,6 +1,7 @@
import { useMemo, type ReactNode } from "react";
import { Text, View, type StyleProp, type ViewStyle } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { HeadingTrailing } from "./heading-trailing";
import { SettingsInfoTip } from "./settings-info-tip";
interface SettingsGroupProps {
@@ -40,7 +41,7 @@ export function SettingsGroup({
/>
) : null}
</View>
{trailing}
<HeadingTrailing>{trailing}</HeadingTrailing>
</View>
{children}
</View>
@@ -3,6 +3,7 @@ import { useMemo, type ReactNode } from "react";
import { View, type StyleProp, type ViewStyle } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { ExternalLink, type ExternalLinkProps } from "@/components/ui/external-link";
import { HeadingTrailing } from "./heading-trailing";
import { SettingsInfoTip } from "./settings-info-tip";
import { settingsStyles } from "@/styles/settings";
@@ -67,7 +68,7 @@ export function SettingsSection({
<ExternalLink {...link} />
</View>
) : null}
{trailing}
<HeadingTrailing>{trailing}</HeadingTrailing>
</View>
<View style={styles.content}>{children}</View>
</View>
@@ -7,6 +7,7 @@ import {
SettingsCollapsibleRow,
SettingsDetailRow,
SettingsRow,
SettingsSwitch,
} from "@/components/settings";
let root: Root | null = null;
@@ -20,6 +21,7 @@ afterEach(() => {
});
function openNothing() {}
function toggleNothing() {}
function mountRows() {
container = document.createElement("div");
@@ -33,6 +35,13 @@ function mountRows() {
Download
</Button>
</SettingsRow>
<SettingsRow label="Text only" testID="text-row" />
<SettingsSwitch
label="Toggles"
value={false}
onValueChange={toggleNothing}
testID="switch-row"
/>
<SettingsDetailRow label="Opens a page" onPress={openNothing} testID="detail-row" />
<SettingsCollapsibleRow label="Group" defaultExpanded testID="group">
<SettingsRow label="Nested with a button" testID="nested-with-button">
@@ -74,11 +83,13 @@ describe("settings row density", () => {
expect(heightOf("group-toggle")).toBeGreaterThan(heightOf("nested-without-button"));
});
it("keeps a row that opens something as tall as a row holding a control", () => {
it("lines up text, switch, and opening rows below a row holding a button", () => {
mountRows();
expect(heightOf("detail-row")).toBe(heightOf("card-row"));
expect(heightOf("group-toggle")).toBe(heightOf("card-row"));
expect(heightOf("switch-row")).toBe(heightOf("text-row"));
expect(heightOf("detail-row")).toBe(heightOf("text-row"));
expect(heightOf("group-toggle")).toBe(heightOf("text-row"));
expect(heightOf("card-row")).toBeGreaterThan(heightOf("text-row"));
});
it("sizes nested text and controls one step below card rows", () => {
@@ -27,11 +27,6 @@ export function MenuSettingsRows({ children }: { children: ReactNode }) {
export interface SettingsRowLayout {
row: StyleProp<ViewStyle>;
/**
* A row as tall as one holding a control of `controlSize`, whether or not it holds one. In a menu
* it keeps the menu's row height.
*/
controlRow: StyleProp<ViewStyle>;
title: StyleProp<TextStyle>;
hint: StyleProp<TextStyle>;
/** The size of the controls in the row's trailing slot. */
@@ -43,7 +38,6 @@ function layoutFor(placement: RowPlacement): SettingsRowLayout {
case "nested":
return {
row: [settingsStyles.row, styles.nestedRow],
controlRow: [settingsStyles.row, styles.nestedRow],
title: [settingsStyles.rowTitle, styles.nestedText],
hint: [settingsStyles.rowHint, styles.nestedText],
controlSize: "sm",
@@ -51,7 +45,6 @@ function layoutFor(placement: RowPlacement): SettingsRowLayout {
case "menu":
return {
row: [settingsStyles.row, styles.menuRow],
controlRow: [settingsStyles.row, styles.menuRow],
title: settingsStyles.rowTitle,
hint: settingsStyles.rowHint,
controlSize: "md",
@@ -59,7 +52,6 @@ function layoutFor(placement: RowPlacement): SettingsRowLayout {
case "card":
return {
row: settingsStyles.row,
controlRow: [settingsStyles.row, styles.cardControlRow],
title: settingsStyles.rowTitle,
hint: settingsStyles.rowHint,
controlSize: "md",
@@ -74,9 +66,6 @@ export function useSettingsRowLayout(): SettingsRowLayout {
}
const styles = StyleSheet.create((theme) => ({
cardControlRow: {
minHeight: mapLayout(CONTROL_HEIGHTS.md, (height) => height + theme.spacing[4] * 2),
},
// Every nested row is as tall as one holding an `sm` control, so rows with and without a
// trailing button line up.
nestedRow: {
@@ -86,7 +86,7 @@ export function SettingsRowHeader({
const handlePointerEnter = useCallback(() => setPointerOver(true), []);
const handlePointerLeave = useCallback(() => setPointerOver(false), []);
const hovered = pointerOver && !disabled;
const rowStyle = useMemo(() => [layout.controlRow, hovered && styles.hovered], [hovered, layout]);
const rowStyle = useMemo(() => [layout.row, hovered && styles.hovered], [hovered, layout]);
const chevronStyle = useMemo(
() => [styles.chevron, expanded && styles.chevronExpanded],
[expanded],
@@ -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
@@ -462,8 +462,12 @@ function SplitNodeView({
groupId ? state.splitSizesByWorkspace[workspaceKey]?.[groupId] : undefined,
);
const groupChildren = node.kind === "group" ? node.group.children : EMPTY_SPLIT_NODES;
// Dragged sizes live per group id, apart from the layout tree, and a group keeps its id when
// panes are added or removed. They only apply while they still have one entry per child;
// otherwise the dividers past the end of the list could not move.
const layoutGroupSizes = node.kind === "group" ? node.group.sizes : EMPTY_SPLIT_SIZES;
const groupSizes =
storedGroupSizes ?? (node.kind === "group" ? node.group.sizes : EMPTY_SPLIT_SIZES);
storedGroupSizes?.length === groupChildren.length ? storedGroupSizes : layoutGroupSizes;
const visibleFlex = useMemo(
() => resolveVisibleGroupFlex(groupChildren, groupSizes, maximizedPaneId),
[groupChildren, groupSizes, maximizedPaneId],
@@ -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;
}
@@ -302,23 +302,23 @@ describe("control geometry", () => {
trackHeight: 20,
thumbSize: 16,
thumbTravel: 14,
reservedHeight: 32,
hitHeight: 32,
});
expect(switchGeometryForLayout("md", true)).toEqual({
trackWidth: 44,
trackHeight: 26,
thumbSize: 22,
thumbTravel: 18,
reservedHeight: 44,
hitHeight: 44,
});
// Tight chrome keeps the pointer-sized track on every layout and reserves its row's height.
// Tight chrome keeps the pointer-sized track on every layout and takes presses over its row's control height.
expect(switchGeometryForLayout("sm", true)).toMatchObject({
trackWidth: 34,
reservedHeight: 32,
hitHeight: 32,
});
expect(switchGeometryForLayout("sm", false)).toMatchObject({
trackWidth: 34,
reservedHeight: 28,
hitHeight: 28,
});
});
@@ -223,8 +223,11 @@ export interface SwitchGeometry {
thumbSize: number;
/** How far the thumb slides between off and on. */
thumbTravel: number;
/** The control height the switch reserves, so its row lines up with one holding a button. */
reservedHeight: number;
/**
* The height of the area that takes the press: the control height of the switch's size. The
* switch itself is only as tall as its track, so it never makes a row taller.
*/
hitHeight: number;
}
function switchSize(trackWidth: number, trackHeight: number, thumbSize: number) {
@@ -235,6 +238,15 @@ function switchSize(trackWidth: number, trackHeight: number, thumbSize: number)
const SWITCH_POINTER = switchSize(34, 20, 16);
const SWITCH_TOUCH = switchSize(44, 26, 22);
/**
* The height of a default switch. Exported so a row can be as tall as one holding a switch whether
* or not it holds one. A breakpoint value, so it only works inside a Unistyles stylesheet.
*/
export const SWITCH_HEIGHT = bySizing({
touch: SWITCH_TOUCH.trackHeight,
pointer: SWITCH_POINTER.trackHeight,
});
/**
* A switch follows the same two sizes as every other control. Its thumb travel feeds an
* animation, so the size is resolved to plain numbers here instead of a stylesheet breakpoint.
@@ -242,7 +254,7 @@ const SWITCH_TOUCH = switchSize(44, 26, 22);
export function switchGeometryForLayout(size: ControlSize, isCompact: boolean): SwitchGeometry {
const touchSized = controlSizingForLayout(isCompact) === "touch";
const track = size === "md" && touchSized ? SWITCH_TOUCH : SWITCH_POINTER;
return { ...track, reservedHeight: controlHeightForLayout(size, isCompact) };
return { ...track, hitHeight: controlHeightForLayout(size, isCompact) };
}
function fieldLineHeight(fontSize: number): number {
@@ -25,6 +25,8 @@ export interface SearchFieldProps {
/** Falls back to `placeholder`, which already names the field. */
accessibilityLabel?: string;
clearAccessibilityLabel: string;
/** Fill the container, for a search that heads one list. Defaults to the filter rail's width. */
fullWidth?: boolean;
testID?: string;
clearTestID?: string;
}
@@ -42,6 +44,7 @@ export function SearchField({
placeholder,
accessibilityLabel,
clearAccessibilityLabel,
fullWidth = false,
testID,
clearTestID,
}: SearchFieldProps): ReactElement {
@@ -55,7 +58,9 @@ export function SearchField({
}, [onChangeText]);
return (
<View style={[styles.field, isFocused && styles.fieldFocused]}>
<View
style={[styles.field, fullWidth && styles.fieldFullWidth, isFocused && styles.fieldFocused]}
>
<ThemedSearch size={14} uniProps={mutedColorMapping} />
<ThemedTextInput
testID={testID}
@@ -103,6 +108,9 @@ const styles = StyleSheet.create((theme) => ({
borderWidth: theme.borderWidth[1],
borderColor: theme.colors.border,
},
fieldFullWidth: {
maxWidth: "100%",
},
fieldFocused: {
borderColor: theme.colors.borderAccent,
backgroundColor: theme.colors.surface2,
+7 -2
View File
@@ -123,11 +123,16 @@ export function Switch({
const pressableStyle = useMemo(
() => [
styles.switchControl,
{ minHeight: geometry.reservedHeight },
// The press area is a full control tall and grows out of the track; the layout only sees
// the track.
{
minHeight: geometry.hitHeight,
marginVertical: (geometry.trackHeight - geometry.hitHeight) / 2,
},
disabled ? styles.disabled : null,
style,
],
[disabled, geometry.reservedHeight, style],
[disabled, geometry.hitHeight, geometry.trackHeight, style],
);
return (
@@ -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;
}
@@ -12,6 +12,7 @@ import { Composer } from "@/composer";
import { ProjectIconView } from "@/components/project-icon-view";
import { ICON_SIZE } from "@/styles/theme";
import { useToast } from "@/contexts/toast-context";
import { draftCreationKey } from "@/composer/draft/creation-key";
import { useAgentInputDraft } from "@/composer/draft/input-draft";
import { useProjectIcon } from "@/projects/icons";
import { useHostRuntimeClient, useHostRuntimeIsConnected } from "@/runtime/host-runtime";
@@ -96,13 +97,16 @@ async function callWorkspaceCreation({
worktreeSlug: string;
input: { cwd: string; agent?: CreateWorkspaceRequestOptions["agent"] };
}) {
return connectedClient.createWorkspace({
idempotencyKey: creationId,
const request: Omit<CreateWorkspaceRequestOptions, "idempotencyKey"> = {
agent: input.agent,
source:
creationMethod === "create_worktree"
? { kind: "worktree", cwd: input.cwd, worktreeSlug }
: { kind: "directory", path: input.cwd },
};
return connectedClient.createWorkspace({
...request,
idempotencyKey: draftCreationKey(creationId, request),
});
}
@@ -363,7 +367,9 @@ export function WorkspaceSetupDialog() {
} catch (error) {
const message = toErrorMessage(error);
setErrorMessage(message);
toast.error(message);
if (!getIsStillActive()) {
toast.error(message);
}
} finally {
if (getIsStillActive()) {
setPendingAction(null);
@@ -455,11 +461,10 @@ export function WorkspaceSetupDialog() {
commandDraft={composerState?.commandDraft}
agentControls={agentControlsWithDisabled}
inputWrapperStyle={styles.composerInputWrapper}
error={errorMessage}
/>
</KeyboardTranslateView>
</FileDropZone>
{errorMessage ? <Text style={styles.errorText}>{errorMessage}</Text> : null}
</AdaptiveModalSheet>
);
}
@@ -482,11 +487,6 @@ const styles = StyleSheet.create((theme) => ({
marginHorizontal: -theme.spacing[6],
marginVertical: -theme.spacing[2],
},
errorText: {
fontSize: theme.fontSize.base,
color: theme.colors.destructive,
lineHeight: 20,
},
composerSlot: {
paddingBottom: theme.spacing[4],
},
@@ -8,6 +8,21 @@ const request = {
clientMessageId: "draft-1:initial-message",
};
const workspaceRequest = {
source: {
kind: "worktree" as const,
cwd: "/repo",
projectId: "prj_1",
worktreeSlug: "clever-fox",
},
firstAgentContext: { prompt: "Start the original task.", attachments: [] },
agent: {
config: { provider: "codex", cwd: "/repo", model: "gpt-6" },
initialPrompt: "Start the original task.",
clientMessageId: "draft-1:initial-message",
},
};
describe("draftCreationKey", () => {
it("keeps the key for a retry of the same request, whatever its key order", () => {
const reordered = {
@@ -27,4 +42,52 @@ describe("draftCreationKey", () => {
expect(key).not.toBe(draftCreationKey("draft-1", request));
expect(key.startsWith("draft-1:")).toBe(true);
});
it.each([
{
name: "isolation",
edited: {
...workspaceRequest,
source: { kind: "directory" as const, path: "/repo", projectId: "prj_1" },
},
},
{
name: "project",
edited: {
...workspaceRequest,
source: { ...workspaceRequest.source, projectId: "prj_2", cwd: "/other" },
},
},
{
name: "prompt",
edited: {
...workspaceRequest,
firstAgentContext: { prompt: "hi", attachments: [] },
agent: { ...workspaceRequest.agent, initialPrompt: "hi" },
},
},
])(
"gives a New workspace request with edited $name a new key on the same draft",
({ edited }) => {
const key = draftCreationKey("draft-1", edited);
expect(key).not.toBe(draftCreationKey("draft-1", workspaceRequest));
expect(key.startsWith("draft-1:")).toBe(true);
},
);
it("gives a New workspace request with a changed launch target a new key even when the wire request matches", () => {
const emptyRequest = {
source: { kind: "directory" as const, path: "/repo", projectId: "prj_1" },
};
const chatKey = draftCreationKey("draft-1", {
request: emptyRequest,
launchTarget: { kind: "chat" },
});
const terminalKey = draftCreationKey("draft-1", {
request: emptyRequest,
launchTarget: { kind: "terminal", profileId: "shell" },
});
expect(terminalKey).not.toBe(chatKey);
expect(terminalKey.startsWith("draft-1:")).toBe(true);
});
});
@@ -1,7 +1,7 @@
import type { ComposerOptionControls } from "@/agent-controls/option-controls";
import { useCallback, useEffect, useMemo, useRef } from "react";
import type { JsonValue } from "@getpaseo/protocol/agent-types";
import { Keyboard, StyleSheet as RNStyleSheet, Text, View } from "react-native";
import { Keyboard, StyleSheet as RNStyleSheet, View } from "react-native";
import { useTranslation } from "react-i18next";
import { StyleSheet } from "react-native-unistyles";
import { CHAT_COLUMN_RAIL_DATASET } from "@/chat-rail";
@@ -536,16 +536,6 @@ export function WorkspaceDraftComposer({
);
return (
<View style={animatedStaticStyles.inputAreaWrapper} onLayout={onInputAreaLayout}>
{formErrorMessage ? (
<View
style={styles.formErrorRow}
dataSet={isComposerFullscreen ? undefined : CHAT_COLUMN_RAIL_DATASET}
>
<View style={styles.formError}>
<Text style={styles.errorText}>{formErrorMessage}</Text>
</View>
</View>
) : null}
{importPillPress && !isComposerFullscreen ? (
<View style={styles.importPillRow} dataSet={CHAT_COLUMN_RAIL_DATASET}>
<View style={styles.importPillContent}>
@@ -577,6 +567,7 @@ export function WorkspaceDraftComposer({
commandDraft={composerState.commandDraft}
agentControls={composerAgentControls}
isCompactLayout={isCompactComposerLayout}
error={formErrorMessage || null}
/>
</View>
);
@@ -592,11 +583,6 @@ const animatedStaticStyles = RNStyleSheet.create({
});
const styles = StyleSheet.create((theme) => ({
formErrorRow: {
width: "100%",
paddingHorizontal: theme.spacing[4],
alignItems: "center",
},
importPillRow: {
width: "100%",
paddingHorizontal: theme.spacing[4],
@@ -615,18 +601,4 @@ const styles = StyleSheet.create((theme) => ({
maxWidth: theme.contentMaxWidth,
flexDirection: "row",
},
formError: {
width: "100%",
maxWidth: theme.contentMaxWidth,
marginBottom: theme.spacing[2],
paddingHorizontal: theme.spacing[3],
paddingVertical: theme.spacing[2],
borderRadius: theme.borderRadius.md,
backgroundColor: theme.colors.surface2,
borderWidth: 1,
borderColor: theme.colors.destructive,
},
errorText: {
color: theme.colors.destructive,
},
}));
+8 -9
View File
@@ -8,6 +8,7 @@ import { createStore, type StoreApi } from "zustand/vanilla";
import { useStore } from "zustand";
import { getHostRuntimeStore } from "@/runtime/host-runtime";
import { LoadingSpinner } from "@/components/ui/loading-spinner";
import { Alert } from "@/components/ui/alert";
import {
View,
Pressable,
@@ -1016,6 +1017,8 @@ interface ComposerProps {
* `inputMode`.
*/
editingSession?: ComposerEditingSession;
/** Caller-owned submission error rendered in the composer's shared error slot. */
error?: string | null;
}
const EMPTY_ARRAY: readonly QueuedMessage[] = [];
@@ -1319,6 +1322,7 @@ function ComposerContentImpl({
isCompactLayout: isCompactLayoutOverride,
inputMode = "chat",
editingSession: providedEditingSession,
error: externalError,
readOnly = false,
submitLabel,
placeholder,
@@ -2544,14 +2548,13 @@ function ComposerContentImpl({
// Focusing the composer on a touch screen raises the on-screen keyboard over the conversation.
const messageInputAutoFocus = autoFocus && isDesktopWebBreakpoint && hasFinePointer;
const submitLoadingPressHandler = isAgentRunning ? handleCancelAgent : undefined;
const displayError = externalError || sendError;
const sendErrorNode = useMemo(
() =>
sendError ? (
<Text accessibilityRole="alert" style={styles.sendErrorText}>
{sendError}
</Text>
displayError ? (
<Alert variant="error" size="sm" description={displayError} testID="composer-error" />
) : null,
[sendError],
[displayError],
);
const githubEmptyText = githubSearchResultsQuery.isFetching
? t("composer.github.searching")
@@ -2837,10 +2840,6 @@ const styles = StyleSheet.create((theme: Theme) => ({
queueSendButton: {
backgroundColor: theme.colors.accent,
},
sendErrorText: {
color: theme.colors.palette.red[500],
fontSize: theme.fontSize.base,
},
})) as unknown as Record<string, object>;
const ThemedAttachmentSpinner = withUnistyles(LoadingSpinner);
@@ -117,10 +117,11 @@ export function useComposerHeight({
useEffect(() => {
const source = textareaRef.current;
if (!source || typeof ResizeObserver === "undefined") return;
let previousWidth = source.clientWidth;
const observer = new ResizeObserver(() => {
const nextWidth = source.clientWidth;
if (Math.abs(nextWidth - previousWidth) < 1) return;
let previousWidth: number | undefined;
const observer = new ResizeObserver(([entry]) => {
// Hint padding changes the width text wraps at even when clientWidth stays fixed.
const nextWidth = entry.contentRect.width;
if (nextWidth === previousWidth) return;
previousWidth = nextWidth;
measure(paramsRef.current.getText());
});
+39 -24
View File
@@ -677,24 +677,6 @@ function MessageInputOverlay({
return null;
}
function FocusHint({
visible,
focusInputKeys,
label,
}: {
visible: boolean;
focusInputKeys: ShortcutChord | null | undefined;
label: string;
}) {
const { isActiveComposer } = useComposerKeyboardScope();
if (!isActiveComposer || !visible || !focusInputKeys || !label.trim()) return null;
return (
<Text style={styles.focusHintText} pointerEvents="none">
{label}
</Text>
);
}
interface ComposerTextSurfaceProps {
readOnly: boolean;
value: string;
@@ -745,6 +727,32 @@ function ComposerTextSurface(props: ComposerTextSurfaceProps): React.ReactElemen
onRenderedLinesChange(event.nativeEvent.lines.length),
[onRenderedLinesChange],
);
const { isActiveComposer } = useComposerKeyboardScope();
const { focusHintLabel, focusHintVisible, focusInputKeys } = props;
const [focusHintLayout, setFocusHintLayout] = useState<{ label: string; width: number }>();
const handleFocusHintLayout = useCallback(
(event: LayoutChangeEvent) => {
setFocusHintLayout({ label: focusHintLabel, width: event.nativeEvent.layout.width });
},
[focusHintLabel],
);
const shouldShowFocusHint =
isActiveComposer &&
focusHintVisible &&
Boolean(focusInputKeys) &&
focusHintLabel.trim().length > 0;
const focusHintWidth =
shouldShowFocusHint && focusHintLayout?.label === focusHintLabel
? focusHintLayout.width
: undefined;
// Make room for the hint in the same render that reveals it.
const textInputStyle = useMemo(
() =>
focusHintWidth === undefined
? props.textInputStyle
: [props.textInputStyle, { paddingRight: focusHintWidth }],
[focusHintWidth, props.textInputStyle],
);
if (props.readOnly) {
return (
<View style={styles.textInputScrollWrapper}>
@@ -775,7 +783,7 @@ function ComposerTextSurface(props: ComposerTextSurfaceProps): React.ReactElemen
accessibilityLabel={props.accessibilityLabel}
onFocus={props.onFocus}
onBlur={props.onBlur}
style={props.textInputStyle}
style={textInputStyle}
multiline
scrollEnabled={props.scrollEnabled}
editable={props.editable}
@@ -785,11 +793,16 @@ function ComposerTextSurface(props: ComposerTextSurfaceProps): React.ReactElemen
onPasteError={props.onPasteError}
autoFocus={props.autoFocus}
/>
<FocusHint
visible={props.focusHintVisible}
focusInputKeys={props.focusInputKeys}
label={props.focusHintLabel}
/>
{shouldShowFocusHint ? (
<Text
key={focusHintLabel}
style={[styles.focusHintText, focusHintWidth === undefined && styles.unmeasuredFocusHint]}
pointerEvents="none"
onLayout={handleFocusHintLayout}
>
{focusHintLabel}
</Text>
) : null}
</View>
);
}
@@ -2460,10 +2473,12 @@ const styles = StyleSheet.create((theme: Theme) => ({
position: "absolute",
top: 0,
right: 0,
paddingLeft: theme.spacing[2],
fontSize: theme.fontSize.sm,
color: theme.colors.foregroundMuted,
opacity: 0.5,
},
unmeasuredFocusHint: { opacity: 0 },
textInput: {
// Preserve the controls when an ancestor constrains an overlong draft.
flexShrink: 1,
@@ -637,7 +637,7 @@ it("stores and expands identical content once across directory associations", as
});
it("coalesces missing bodies and keeps a newer pushed association when an older pull completes", async () => {
const { QueryClient } = await import("@tanstack/react-query");
const { QueryClient, QueryObserver } = await import("@tanstack/react-query");
const { applyProvidersSnapshotUpdate } = await import("./push-router");
const { fetchProvidersSnapshot, providersSnapshotQueryKey } =
await import("./providers-snapshot");
@@ -653,6 +653,16 @@ it("coalesces missing bodies and keeps a newer pushed association when an older
fetchedAt: { pi: fetchedAt },
requestId: hash,
});
// Announcements only download for directories a screen is showing.
const unsubscribers = ["/a", "/b", "/c"].map((cwd) => {
const queryKey = providersSnapshotQueryKey(serverId, cwd);
queryClient.setQueryData(queryKey, snapshot("seed"));
return new QueryObserver(queryClient, {
queryKey,
queryFn: async () => snapshot("seed"),
staleTime: Infinity,
}).subscribe(() => {});
});
let transfers = 0;
const client = {
async getProvidersSnapshot() {
@@ -776,6 +786,7 @@ it("coalesces missing bodies and keeps a newer pushed association when an older
entries: [{ models: [{ id: "shared" }] }],
});
} finally {
for (const unsubscribe of unsubscribers) unsubscribe();
queryClient.clear();
}
});
@@ -1,5 +1,5 @@
import { createRequire } from "node:module";
import { QueryClient, CancelledError } from "@tanstack/react-query";
import { QueryClient, CancelledError, QueryObserver } from "@tanstack/react-query";
import type { ProviderSnapshotEntry } from "@getpaseo/protocol/agent-types";
import type { GetProvidersSnapshotResponseMessage } from "@getpaseo/protocol/messages";
import { compactProviderSnapshot } from "@getpaseo/protocol/provider-snapshot-codec";
@@ -307,6 +307,14 @@ describe("provider snapshot publication identity", () => {
snapshotHash: "next-hash",
compactSnapshot: compactProviderSnapshot([{ ...entries[0]!, label: "Updated provider" }]),
};
// Announcements only publish into a directory a screen is showing.
const shownKey = providersSnapshotQueryKey(serverId, snapshot.cwd);
queryClient.setQueryData(shownKey, snapshot);
const unsubscribe = new QueryObserver(queryClient, {
queryKey: shownKey,
queryFn: async () => snapshot,
staleTime: Infinity,
}).subscribe(() => {});
try {
for (const body of [snapshot, changed, changed]) {
await applyProvidersSnapshotUpdate({
@@ -325,6 +333,7 @@ describe("provider snapshot publication identity", () => {
expect(published.entries[0]!.models).toBe(canonical.entries[0]!.models);
}
} finally {
unsubscribe();
queryClient.clear();
}
});
+168 -1
View File
@@ -8,8 +8,12 @@ import { checkoutDiffQueryKey } from "@/git/query-keys";
import { buildTerminalsQueryKey } from "@/screens/workspace/terminals/state";
import { daemonConfigQueryKey } from "@/data/daemon-config";
import { daemonPairingOfferQueryKey } from "@/data/daemon-pairing";
import { providersSnapshotQueryKey } from "@/data/providers-snapshot";
import { providersSnapshotQuery, providersSnapshotQueryKey } from "@/data/providers-snapshot";
import { replicaQueryOptions } from "@/data/query";
import { createProviderSnapshotCache } from "@/data/provider-snapshot-cache";
import { draftAgentCommandsQueryKey } from "@/agent-commands/cache";
import {
applyProvidersSnapshotUpdate,
checkoutDiffPushRoute,
invalidateServerDataQueriesAfterReconnect,
mountServerDataPushRouter,
@@ -594,6 +598,13 @@ describe("server data push router", () => {
const serverId = "server-1";
const pairingOfferKey = daemonPairingOfferQueryKey(serverId);
queryClient.setQueryData(pairingOfferKey, { relayEnabled: true, url: "https://pairing" });
const snapshotKey = providersSnapshotQueryKey(serverId);
queryClient.setQueryData(snapshotKey, { entries: [], generatedAt: "seed", requestId: "seed" });
const unsubscribeSnapshot = new QueryObserver(queryClient, {
queryKey: snapshotKey,
queryFn: async () => ({ entries: [], generatedAt: "seed", requestId: "seed" }),
staleTime: Infinity,
}).subscribe(() => undefined);
const unmount = mountServerDataPushRouter({ client: fake.client, queryClient, serverId });
fake.emit(providerUpdate("2026-01-01T00:00:00.000Z"));
@@ -622,6 +633,7 @@ describe("server data push router", () => {
generatedAt: "2026-01-01T00:00:00.000Z",
requestId: "providers_snapshot_update",
});
unsubscribeSnapshot();
});
it.each(["base", "all"] as const)("routes %s diff snapshots and updates", (mode) => {
@@ -982,3 +994,158 @@ describe("server data push router", () => {
expect(queryClient.getQueryState(otherProviderKey)?.isInvalidated).toBe(false);
});
});
describe("applyProvidersSnapshotUpdate by observation", () => {
const serverId = "observed-host";
const cwd = "/repo";
function createStorage() {
const values = new Map<string, string>();
return {
values,
async getItem(key: string) {
return values.get(key) ?? null;
},
async setItem(key: string, value: string) {
values.set(key, value);
},
async removeItem(key: string) {
values.delete(key);
},
async getAllKeys() {
return [...values.keys()];
},
async multiGet(keys: readonly string[]) {
return keys.map((key) => [key, values.get(key) ?? null] as const);
},
async multiRemove(keys: readonly string[]) {
for (const key of keys) values.delete(key);
},
};
}
function snapshotFor(label: string) {
return {
requestId: label,
cwd,
entries: [
{
provider: "codex",
status: "ready",
enabled: true,
label,
models: [{ provider: "codex", id: label, label, thinkingOptions: [] }],
},
],
generatedAt: "2026-01-01T00:00:00.000Z",
} as never;
}
function setup() {
const storage = createStorage();
const cache = createProviderSnapshotCache(storage);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
const calls: unknown[] = [];
let current = "v1";
const client = {
async getProvidersSnapshot(options?: unknown) {
calls.push(options);
return snapshotFor(current);
},
};
const observe = () =>
new QueryObserver(
queryClient,
replicaQueryOptions(
providersSnapshotQuery({ serverId, cwd, client: () => client, queryClient, cache }),
),
);
const announce = () =>
applyProvidersSnapshotUpdate({
serverId,
queryClient,
cache,
client,
message: {
type: "providers_snapshot_update",
payload: {
cwd,
entries: [],
snapshotHash: "hash-v2",
generatedAt: "2026-01-01T00:00:01Z",
},
} as never,
});
return {
queryClient,
calls,
storage,
observe,
announce,
setCurrent: (value: string) => {
current = value;
},
};
}
it("does nothing for a directory this client never opened", async () => {
const { queryClient, calls, storage, announce } = setup();
await announce();
expect(calls).toEqual([]);
expect(
queryClient.getQueryCache().find({ queryKey: providersSnapshotQueryKey(serverId, cwd) }),
).toBeUndefined();
expect(storage.values.size).toBe(0);
queryClient.clear();
});
it("marks an unobserved cached directory stale without downloading and refetches it on mount", async () => {
const { queryClient, calls, observe, announce, setCurrent } = setup();
const queryKey = providersSnapshotQueryKey(serverId, cwd);
const commandsKey = draftAgentCommandsQueryKey({
serverId,
draftConfig: { provider: "codex", cwd },
});
queryClient.setQueryData(queryKey, snapshotFor("v1"));
queryClient.setQueryData(commandsKey, [{ name: "review" }]);
setCurrent("v2");
await announce();
expect(calls).toEqual([]);
expect(queryClient.getQueryState(queryKey)?.isInvalidated).toBe(true);
expect(queryClient.getQueryState(commandsKey)?.isInvalidated).toBe(true);
const observer = observe();
const unsubscribe = observer.subscribe(() => {});
await queryClient.getQueryCache().find({ queryKey })?.promise;
expect(calls).toHaveLength(1);
expect(
(queryClient.getQueryData(queryKey) as { entries: Array<{ label: string }> }).entries[0]!
.label,
).toBe("v2");
unsubscribe();
queryClient.clear();
});
it("keeps the reference-aware fetch for an observed directory", async () => {
const { queryClient, calls, observe, announce } = setup();
const queryKey = providersSnapshotQueryKey(serverId, cwd);
const observer = observe();
const unsubscribe = observer.subscribe(() => {});
await queryClient.getQueryCache().find({ queryKey })?.promise;
expect(calls).toHaveLength(1);
await announce();
// The announced hash is not resident, so exactly one content transfer is fetched and
// published to the observed query.
expect(calls).toHaveLength(2);
expect(queryClient.getQueryState(queryKey)?.isInvalidated).toBe(false);
unsubscribe();
queryClient.clear();
});
});
+18 -1
View File
@@ -8,7 +8,10 @@ import type {
MutableDaemonConfig,
SessionOutboundMessage,
} from "@getpaseo/protocol/messages";
import { invalidateCommandsForProviderChange } from "@/agent-commands/cache";
import {
invalidateCommandsForDirectory,
invalidateCommandsForProviderChange,
} from "@/agent-commands/cache";
import { shareCheckoutDiff } from "@/git/diff-sharing";
import { orderCheckoutDiffFiles } from "@/git/diff-order";
import { daemonConfigQueryKey } from "@/data/daemon-config";
@@ -184,6 +187,20 @@ export async function applyProvidersSnapshotUpdate(input: {
const snapshot = { ...input.message.payload, requestId: "providers_snapshot_update" };
const cwd = normalizeProvidersSnapshotCwd(snapshot.cwd);
const queryKey = providersSnapshotQueryKey(input.serverId, cwd);
const cached = input.queryClient.getQueryCache().find({ queryKey, exact: true });
// Only a screen showing this directory is worth a download. A cached but unobserved
// directory refetches on its next mount; one this client never opened needs nothing.
if (!cached) return;
if (!cached.isActive()) {
await input.queryClient.cancelQueries({ queryKey, exact: true });
await input.queryClient.invalidateQueries({ queryKey, exact: true, refetchType: "none" });
await invalidateCommandsForDirectory({
queryClient: input.queryClient,
serverId: input.serverId,
cwd,
});
return;
}
const previous = input.queryClient.getQueryData<{ entries: ProviderSnapshotEntry[] }>(queryKey);
let announcement: typeof snapshot | undefined = snapshot;
void input.queryClient.cancelQueries({ queryKey, exact: true });
+50
View File
@@ -0,0 +1,50 @@
import { QueryClient, QueryObserver } from "@tanstack/react-query";
import { describe, expect, it } from "vitest";
import { replicaQueryOptions } from "./query";
function setup() {
const queryClient = new QueryClient();
const queryKey = ["replica", "value"] as const;
let fetches = 0;
const options = replicaQueryOptions({
queryKey,
pushEvent: "value_update",
queryFn: async () => {
fetches++;
return `fetch-${fetches}`;
},
});
return { queryClient, queryKey, options, fetchCount: () => fetches };
}
describe("replicaQueryOptions mount behavior", () => {
it("does not refetch on mount while the cached value is not invalidated", async () => {
const { queryClient, queryKey, options, fetchCount } = setup();
queryClient.setQueryData(queryKey, "cached");
const observer = new QueryObserver(queryClient, options);
const unsubscribe = observer.subscribe(() => {});
await Promise.resolve();
expect(fetchCount()).toBe(0);
expect(observer.getCurrentResult().data).toBe("cached");
unsubscribe();
queryClient.clear();
});
it("refetches on mount when the cached value was invalidated while unobserved", async () => {
const { queryClient, queryKey, options, fetchCount } = setup();
queryClient.setQueryData(queryKey, "cached");
await queryClient.invalidateQueries({ queryKey, refetchType: "none" });
expect(fetchCount()).toBe(0);
const observer = new QueryObserver(queryClient, options);
const unsubscribe = observer.subscribe(() => {});
await queryClient.getQueryCache().find({ queryKey })?.promise;
expect(fetchCount()).toBe(1);
expect(observer.getCurrentResult().data).toBe("fetch-1");
unsubscribe();
queryClient.clear();
});
});
+3 -1
View File
@@ -86,7 +86,9 @@ export function replicaQueryOptions<
},
},
queryFn: options.queryFn ?? skipToken,
refetchOnMount: false,
// Pushes keep a replica fresh; a mount only refetches what an invalidation marked stale
// while nothing observed it.
refetchOnMount: (query) => query.state.isInvalidated,
refetchOnReconnect: false,
refetchOnWindowFocus: false,
staleTime: Infinity,
@@ -110,6 +110,10 @@ function resolveAgentAutocompleteSnapshot(input: {
};
}
function isSameSlashCommand(a: SlashCommandRange | null, b: SlashCommandRange | null): boolean {
return a?.start === b?.start && a?.query === b?.query;
}
interface DirectorySuggestionEntry {
path: string;
kind: "file" | "directory";
@@ -746,9 +750,25 @@ export function useAgentAutocomplete(input: UseAgentAutocompleteInput): AgentAut
);
const selectOptionFromKeyPress = useCallback(
(option: AutocompleteOption, event?: AgentAutocompleteKeyPressEvent) =>
onSelectOption(option, event?.input),
[onSelectOption],
(option: AutocompleteOption, event?: AgentAutocompleteKeyPressEvent) => {
// The cursor reaches the menu after paint, so a key can land while the options still
// belong to an older query. Never pick from that list. A click picks what the user sees.
if (
mode === "command" &&
event &&
!isSameSlashCommand(
findActiveSlashCommand({
text: event.input.text,
cursorIndex: event.input.selection.start,
}),
activeSlashCommand,
)
) {
return;
}
onSelectOption(option, event?.input);
},
[activeSlashCommand, mode, onSelectOption],
);
const { selectedIndex, onKeyPress } = useAutocomplete({
@@ -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,
});
}
@@ -352,6 +352,19 @@ describe("applyProvidersSnapshotUpdate", () => {
queryClient = new QueryClient();
});
// Announcements only download for directories a screen is showing, so these tests mount one.
function showSnapshot(cwd?: string) {
const queryKey = providersSnapshotQueryKey(serverId, cwd);
if (queryClient.getQueryData(queryKey) === undefined) {
queryClient.setQueryData(queryKey, providersSnapshot([]));
}
return new QueryObserver(queryClient, {
queryKey,
queryFn: async () => providersSnapshot([]),
staleTime: Infinity,
}).subscribe(() => {});
}
function updateMessage(entries: ProviderSnapshotEntry[], cwd?: string): ProvidersSnapshotUpdate {
return {
type: "providers_snapshot_update",
@@ -364,6 +377,7 @@ describe("applyProvidersSnapshotUpdate", () => {
}
it("refreshes active commands only when their provider changes after discovery", async () => {
showSnapshot("/repo-a");
const key = sessionAgentCommandsQueryKey({ serverId, agentId: "agent-1" });
let requests = 0;
const observer = new QueryObserver(queryClient, {
@@ -447,6 +461,7 @@ describe("applyProvidersSnapshotUpdate", () => {
});
it("retries a failed command discovery when its provider first becomes ready", async () => {
showSnapshot("/repo-a");
const key = sessionAgentCommandsQueryKey({ serverId, agentId: "agent-1" });
let ready = false;
let requests = 0;
@@ -493,6 +508,7 @@ describe("applyProvidersSnapshotUpdate", () => {
providersSnapshotQueryKey(serverId, "/repo-a"),
providersSnapshot([codexEntry("ready", [readyCodexModel])]),
);
showSnapshot("/repo-a");
const send = (label: string) =>
applyProvidersSnapshotUpdate({
client: createClient(),
@@ -511,6 +527,7 @@ describe("applyProvidersSnapshotUpdate", () => {
});
it("routes updates to the home query cache when the message carries no cwd", async () => {
showSnapshot();
await applyProvidersSnapshotUpdate({
client: createClient(),
serverId,
@@ -527,6 +544,7 @@ describe("applyProvidersSnapshotUpdate", () => {
it("routes workspace updates to the matching scope without touching siblings", async () => {
queryClient.setQueryData(providersSnapshotQueryKey(serverId, "/repo-b"), providersSnapshot([]));
showSnapshot("/repo-a");
await applyProvidersSnapshotUpdate({
client: createClient(),
@@ -546,6 +564,7 @@ describe("applyProvidersSnapshotUpdate", () => {
});
it("persists compact push updates", async () => {
showSnapshot("/repo-a");
const entries = [codexEntry("ready", [readyCodexModel])];
const compactSnapshot = compactProviderSnapshot(entries);
const cache = createCache();
@@ -579,6 +598,7 @@ describe("applyProvidersSnapshotUpdate", () => {
providersSnapshotQueryKey(serverId, workspaceCwd),
providersSnapshot([codexEntry("loading")]),
);
showSnapshot(workspaceCwd);
await applyProvidersSnapshotUpdate({
client: createClient(),
@@ -606,6 +626,7 @@ describe("applyProvidersSnapshotUpdate", () => {
providersSnapshotQueryKey(serverId, "/repo-a"),
providersSnapshot([codexEntry("ready")]),
);
showSnapshot("/repo-a");
await applyProvidersSnapshotUpdate({
client: createClient(),
+3 -4
View File
@@ -2323,11 +2323,9 @@ export const ar: TranslationResources = {
resetsIn: "تتم إعادة التعيين خلال {{duration}}",
resetsAtWeekday: "{{weekday}} {{time}}",
resetsAtDate: "{{date}}، {{time}}",
projectedLeftAtReset: "نحو {{percentage}} متبقية عند إعادة التعيين",
limitReached: "تم بلوغ الحد",
mayHaveRunOut: "ربما نفدت الحصة",
runsOutNow: "ينفد الآن",
runsOutIn: "ينفد خلال {{duration}}",
runsOutAt: "ينفد عند {{time}}",
justNow: "الآن",
daysAgo: "قبل {{value}} يومًا",
daysAgo_zero: "قبل {{value}} يوم",
@@ -3115,6 +3113,7 @@ export const ar: TranslationResources = {
status: "حالة المزود",
checked: "تم الفحص {{time}}",
diagnosticReport: "تقرير التشخيص",
docs: "الوثائق",
dangerZone: "منطقة الخطر",
removeHint: "يحذف هذا المزود من config.json",
},
@@ -3160,7 +3159,7 @@ export const ar: TranslationResources = {
noSearchMatches: "لا توجد نماذج تطابق بحثك",
noneDetected: "لم يتم اكتشاف أي نماذج",
noCustom: "لا توجد نماذج مخصصة",
discovered: "اكتشف",
title: "النماذج",
custom: "نماذج مخصصة",
updated: "تم تحديث{{time}}",
},
+3 -4
View File
@@ -2333,11 +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}}",
runsOutAt: "runs out {{time}}",
justNow: "just now",
daysAgo: "{{value}}d ago",
hoursAgo: "{{value}}h ago",
@@ -3213,6 +3211,7 @@ export const en = {
status: "Provider status",
checked: "Checked {{time}}",
diagnosticReport: "Diagnostic report",
docs: "Docs",
dangerZone: "Danger zone",
removeHint: "Deletes this provider from config.json",
},
@@ -3258,7 +3257,7 @@ export const en = {
noSearchMatches: "No models match your search",
noneDetected: "No models detected",
noCustom: "No custom models",
discovered: "Discovered",
title: "Models",
custom: "Custom models",
updated: "Updated {{time}}",
},
+3 -4
View File
@@ -2354,11 +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}}",
runsOutAt: "agotamiento previsto {{time}}",
justNow: "ahora mismo",
daysAgo: "hace {{value}} d",
hoursAgo: "hace {{value}} h",
@@ -3143,6 +3141,7 @@ export const es: TranslationResources = {
status: "Estado del proveedor",
checked: "Comprobado {{time}}",
diagnosticReport: "Informe de diagnóstico",
docs: "Documentación",
dangerZone: "Zona de peligro",
removeHint: "Elimina este proveedor de config.json",
},
@@ -3188,7 +3187,7 @@ export const es: TranslationResources = {
noSearchMatches: "Ningún modelo coincide con tu búsqueda",
noneDetected: "No se detectaron modelos",
noCustom: "No hay modelos personalizados",
discovered: "descubierto",
title: "Modelos",
custom: "Modelos personalizados",
updated: "{{time}}actualizado",
},
+3 -4
View File
@@ -2355,11 +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}}",
runsOutAt: "épuisement prévu {{time}}",
justNow: "à l’instant",
daysAgo: "il y a {{value}} j",
hoursAgo: "il y a {{value}} h",
@@ -3149,6 +3147,7 @@ export const fr: TranslationResources = {
status: "État du fournisseur",
checked: "Vérifié {{time}}",
diagnosticReport: "Rapport de diagnostic",
docs: "Documentation",
dangerZone: "Zone de danger",
removeHint: "Supprime ce fournisseur de config.json",
},
@@ -3195,7 +3194,7 @@ export const fr: TranslationResources = {
noSearchMatches: "Aucun modèle ne correspond à votre recherche",
noneDetected: "Aucun modèle détecté",
noCustom: "Aucun modèle personnalisé",
discovered: "Détectés",
title: "Modèles",
custom: "Modèles personnalisés",
updated: "Mis à jour {{time}}",
},
+3 -4
View File
@@ -2328,11 +2328,9 @@ export const ja: TranslationResources = {
resetsIn: "{{duration}}後にリセット",
resetsAtWeekday: "{{weekday}} {{time}}",
resetsAtDate: "{{date}} {{time}}",
projectedLeftAtReset: "リセット時に約{{percentage}}残る見込み",
limitReached: "上限に達しました",
mayHaveRunOut: "上限に達した可能性があります",
runsOutNow: "まもなく上限に到達",
runsOutIn: "{{duration}}後に上限に到達",
runsOutAt: "{{time}}に上限に到達",
justNow: "たった今",
daysAgo: "{{value}}日前",
hoursAgo: "{{value}}時間前",
@@ -3111,6 +3109,7 @@ export const ja: TranslationResources = {
status: "プロバイダーの状態",
checked: "{{time}}に確認",
diagnosticReport: "診断レポート",
docs: "ドキュメント",
dangerZone: "危険な操作",
removeHint: "このプロバイダーを config.json から削除します",
},
@@ -3156,7 +3155,7 @@ export const ja: TranslationResources = {
noSearchMatches: "検索に一致するモデルがありません",
noneDetected: "モデルが検出されませんでした",
noCustom: "カスタムモデルはありません",
discovered: "検出済み",
title: "モデル",
custom: "カスタムモデル",
updated: "{{time}}に更新",
},
+3 -4
View File
@@ -2316,11 +2316,9 @@ export const ko: TranslationResources = {
resetsIn: "{{duration}} 후 재설정",
resetsAtWeekday: "{{weekday}} {{time}}",
resetsAtDate: "{{date}} {{time}}",
projectedLeftAtReset: "초기화 시 약 {{percentage}} 남을 예정",
limitReached: "한도에 도달함",
mayHaveRunOut: "한도를 소진했을 수 있음",
runsOutNow: "지금 한도에 도달",
runsOutIn: "{{duration}} 후 한도에 도달",
runsOutAt: "{{time}}에 한도에 도달",
justNow: "방금",
daysAgo: "{{value}}일 전",
hoursAgo: "{{value}}시간 전",
@@ -3096,6 +3094,7 @@ export const ko: TranslationResources = {
status: "프로바이더 상태",
checked: "{{time}} 확인됨",
diagnosticReport: "진단 보고서",
docs: "문서",
dangerZone: "위험 구역",
removeHint: "config.json에서 이 프로바이더를 삭제합니다",
},
@@ -3142,7 +3141,7 @@ export const ko: TranslationResources = {
noSearchMatches: "검색과 일치하는 모델이 없습니다",
noneDetected: "감지된 모델이 없습니다",
noCustom: "사용자 지정 모델 없음",
discovered: "발견됨",
title: "모델",
custom: "사용자 지정 모델",
updated: "{{time}} 업데이트됨",
},
+3 -4
View File
@@ -2339,11 +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}}",
runsOutAt: "esgotamento previsto para {{time}}",
justNow: "agora mesmo",
daysAgo: "há {{value}} d",
hoursAgo: "há {{value}} h",
@@ -3124,6 +3122,7 @@ export const ptBR: TranslationResources = {
status: "Status do provedor",
checked: "Verificado {{time}}",
diagnosticReport: "Relatório de diagnóstico",
docs: "Documentação",
dangerZone: "Zona de perigo",
removeHint: "Exclui este provedor do config.json",
},
@@ -3169,7 +3168,7 @@ export const ptBR: TranslationResources = {
noSearchMatches: "Nenhum modelo corresponde à sua busca",
noneDetected: "Nenhum modelo detectado",
noCustom: "Nenhum modelo personalizado",
discovered: "Descobertos",
title: "Modelos",
custom: "Modelos personalizados",
updated: "Atualizado {{time}}",
},
+3 -4
View File
@@ -2341,11 +2341,9 @@ export const ru: TranslationResources = {
resetsIn: "сброс через {{duration}}",
resetsAtWeekday: "{{weekday}} {{time}}",
resetsAtDate: "{{date}}, {{time}}",
projectedLeftAtReset: "К сбросу останется ~{{percentage}}",
limitReached: "Лимит исчерпан",
mayHaveRunOut: "Лимит мог уже исчерпаться",
runsOutNow: "закончится сейчас",
runsOutIn: "закончится через {{duration}}",
runsOutAt: "закончится {{time}}",
justNow: "только что",
daysAgo: "{{value}} дн. назад",
hoursAgo: "{{value}} ч назад",
@@ -3135,6 +3133,7 @@ export const ru: TranslationResources = {
status: "Состояние провайдера",
checked: "Проверено {{time}}",
diagnosticReport: "Диагностический отчёт",
docs: "Документация",
dangerZone: "Опасная зона",
removeHint: "Удаляет этого провайдера из config.json",
},
@@ -3181,7 +3180,7 @@ export const ru: TranslationResources = {
noSearchMatches: "Ни одна модель не соответствует вашему запросу",
noneDetected: "Модели не обнаружены",
noCustom: "Нет пользовательских моделей",
discovered: "Обнаруженные модели",
title: "Модели",
custom: "Пользовательские модели",
updated: "Обновлено {{time}}",
},
+3 -4
View File
@@ -2282,11 +2282,9 @@ export const zhCN: TranslationResources = {
resetsIn: "将在 {{duration}}后重置",
resetsAtWeekday: "{{weekday}} {{time}}",
resetsAtDate: "{{date}} {{time}}",
projectedLeftAtReset: "重置时约剩余 {{percentage}}",
limitReached: "已达到上限",
mayHaveRunOut: "额度可能已用完",
runsOutNow: "即将用尽",
runsOutIn: "将在 {{duration}}后用尽",
runsOutAt: "将在 {{time}} 用尽",
justNow: "刚刚",
daysAgo: "{{value}}天前",
hoursAgo: "{{value}}小时前",
@@ -3044,6 +3042,7 @@ export const zhCN: TranslationResources = {
status: "Provider 状态",
checked: "{{time}}检查",
diagnosticReport: "诊断报告",
docs: "文档",
dangerZone: "危险操作",
removeHint: "从 config.json 中删除此 Provider",
},
@@ -3089,7 +3088,7 @@ export const zhCN: TranslationResources = {
noSearchMatches: "没有匹配搜索的 Model",
noneDetected: "未检测到 Model",
noCustom: "没有自定义模型",
discovered: "已发现",
title: "Models",
custom: "自定义 Models",
updated: "已更新 {{time}}",
},
@@ -1,44 +1,53 @@
import { useMemo } from "react";
import { useTranslation } from "react-i18next";
import { View } from "react-native";
import { withUnistyles } from "react-native-unistyles";
import { SettingsDetailHeader } from "@/components/settings";
import { useIsCompactFormFactor } from "@/constants/layout";
import { ICON_SIZE, type Theme } from "@/styles/theme";
import { ProviderDetail, useProviderDetail } from "./provider-detail";
import { ProviderGlyph } from "./provider-glyph";
/**
* A provider's detail as a Settings page, shaped like a project's: the screen titles it
* "Providers", the page names the provider. On wide layouts the page has no back button of its
* own, so it draws "Back to providers".
* A provider's detail as a Settings page, shaped like a project's. On wide layouts the page is
* titled "Providers > name" and "Providers" goes back. On compact layouts the screen titles it
* "Providers" and the page names the provider.
*/
export function ProviderDetailPage({
serverId,
provider,
onBack,
showBack,
}: {
serverId: string;
provider: string;
onBack: () => void;
showBack: boolean;
}) {
const { t } = useTranslation();
const isCompact = useIsCompactFormFactor();
const detail = useProviderDetail({ serverId, provider, onRemoved: onBack });
const back = useMemo(
const parent = useMemo(
() => ({
label: t("settings.providers.detail.backToProviders"),
label: t("settings.hostSections.providers"),
accessibilityLabel: t("settings.providers.detail.backToProviders"),
onPress: onBack,
testID: "provider-detail-back",
}),
[onBack, t],
);
const icon = useMemo(
() => <ProviderGlyph serverId={serverId} provider={provider} />,
[provider, serverId],
() => (
<ThemedProviderGlyph
serverId={serverId}
provider={provider}
uniProps={isCompact ? rowTitleSize : pageTitleSize}
/>
),
[isCompact, provider, serverId],
);
return (
<View testID="provider-detail-page">
<SettingsDetailHeader
back={showBack ? back : undefined}
parent={parent}
icon={icon}
title={detail.label}
titleTestID="provider-detail-title"
@@ -47,3 +56,8 @@ export function ProviderDetailPage({
</View>
);
}
// The glyph is as large as the name beside it. The page title scales with the interface size.
const ThemedProviderGlyph = withUnistyles(ProviderGlyph);
const pageTitleSize = (theme: Theme) => ({ size: theme.fontSize["4xl"] });
const rowTitleSize = () => ({ size: ICON_SIZE.md });
@@ -14,9 +14,9 @@ import { Alert } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import { readAcpProviderInstallGuide } from "@/hooks/use-acp-provider-catalog";
import { useProvidersSnapshot } from "@/hooks/use-providers-snapshot";
import { useTimeAgo } from "@/hooks/use-time-ago";
import { useHostRuntimeIsConnected } from "@/runtime/host-runtime";
import { settingsStyles } from "@/styles/settings";
import { openExternalUrl } from "@/utils/open-external-url";
import {
readDetailPresence,
readDetailSections,
@@ -27,6 +27,7 @@ import { DiagnosticSheet } from "./diagnostic-sheet";
import { useProviderConfigActions, type ProviderEntry } from "./provider-config";
import { ProviderModels } from "./provider-models";
import { ProviderNotice } from "./provider-notice";
import { ProviderRefreshButton, useCheckedLabel, type ProviderRefresh } from "./provider-refresh";
export interface ProviderDetailState {
provider: string;
@@ -81,6 +82,9 @@ export function useProviderDetail({
/**
* Everything about one provider, top to bottom: what is wrong, whether it runs, its installation,
* its models, then the rare actions. The page and the sheet frame the same body.
*
* Refresh sits with the model list, which is what it is most often pressed for. A provider that
* lists no models of its own keeps it under Troubleshooting.
*/
export function ProviderDetail({
serverId,
@@ -106,6 +110,13 @@ export function ProviderDetail({
installGuide: readAcpProviderInstallGuide(provider),
});
const sections = readDetailSections(entry, shownInstallation);
const listsModels = sections.models === "all";
const providerRefresh: ProviderRefresh = {
checkedAt: entry.fetchedAt,
// The probe running again is a refresh too, whoever asked for it.
busy: isRefreshing || installation.refreshing || entry.status === "loading",
run: handleRefresh,
};
return (
<View testID="provider-detail">
@@ -120,15 +131,13 @@ export function ProviderDetail({
<ProviderModels
serverId={serverId}
entry={entry}
discovered={sections.models === "all"}
refresh={refresh}
refresh={listsModels ? providerRefresh : null}
/>
) : null}
<Troubleshooting
serverId={serverId}
entry={entry}
refreshing={isRefreshing || installation.refreshing}
onRefresh={handleRefresh}
refresh={listsModels ? null : providerRefresh}
/>
{/* Config no longer owns a provider whose removal has succeeded. */}
{detail.removing || detail.canRemove(entry) ? (
@@ -187,42 +196,39 @@ function EnabledCard({ serverId, entry }: { serverId: string; entry: ProviderEnt
function Troubleshooting({
serverId,
entry,
refreshing,
onRefresh,
refresh,
}: {
serverId: string;
entry: ProviderEntry;
refreshing: boolean;
onRefresh: () => void;
/** Null when the model list carries Refresh. */
refresh: ProviderRefresh | null;
}) {
const { t } = useTranslation();
const [diagnosticOpen, setDiagnosticOpen] = useState(false);
const openDiagnostic = useCallback(() => setDiagnosticOpen(true), []);
const closeDiagnostic = useCallback(() => setDiagnosticOpen(false), []);
const checked = useTimeAgo(entry.fetchedAt ? new Date(entry.fetchedAt) : null);
// The probe running again is a refresh too, whoever asked for it.
const busy = refreshing || entry.status === "loading";
const docsUrl = entry.docsUrl;
const openDocs = useCallback(() => {
if (docsUrl) void openExternalUrl(docsUrl);
}, [docsUrl]);
return (
<SettingsSection title={t("settings.providers.detail.troubleshooting")}>
<SettingsCard>
<SettingsRow
label={t("settings.providers.detail.status")}
hint={
entry.fetchedAt ? t("settings.providers.detail.checked", { time: checked }) : undefined
}
>
<Button variant="outline" onPress={onRefresh} loading={busy} testID="provider-refresh">
{busy
? t("settings.providers.diagnostic.refreshing")
: t("settings.providers.diagnostic.refresh")}
</Button>
</SettingsRow>
{refresh ? <ProviderStatusRow refresh={refresh} /> : null}
<SettingsDetailRow
label={t("settings.providers.detail.diagnosticReport")}
onPress={openDiagnostic}
testID="provider-diagnostic-report"
/>
{docsUrl ? (
<SettingsDetailRow
label={t("settings.providers.detail.docs")}
onPress={openDocs}
external
testID="provider-docs"
/>
) : null}
</SettingsCard>
<DiagnosticSheet
serverId={serverId}
@@ -234,6 +240,16 @@ function Troubleshooting({
);
}
function ProviderStatusRow({ refresh }: { refresh: ProviderRefresh }) {
const { t } = useTranslation();
const checked = useCheckedLabel(refresh);
return (
<SettingsRow label={t("settings.providers.detail.status")} hint={checked}>
<ProviderRefreshButton refresh={refresh} form="labelled" />
</SettingsRow>
);
}
function DangerZone({ removing, onRemove }: { removing: boolean; onRemove: () => void }) {
const { t } = useTranslation();
return (
@@ -2,10 +2,18 @@ import { StyleSheet } from "react-native-unistyles";
import { useProviderIcon } from "@/components/provider-icons";
import { ICON_SIZE } from "@/styles/theme";
/** A provider's icon at row size, drawn in the foreground colour. */
export function ProviderGlyph({ serverId, provider }: { serverId: string; provider: string }) {
/** A provider's icon in the foreground colour, at row size unless the caller names another. */
export function ProviderGlyph({
serverId,
provider,
size = ICON_SIZE.md,
}: {
serverId: string;
provider: string;
size?: number;
}) {
const Icon = useProviderIcon(provider, serverId);
return <Icon size={ICON_SIZE.md} color={styles.glyph.color} />;
return <Icon size={size} color={styles.glyph.color} />;
}
const styles = StyleSheet.create((theme) => ({
@@ -1,9 +1,9 @@
import { Plus, Trash2 } from "lucide-react-native";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { Text, View } from "react-native";
import { ScrollView, Text, View } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import type { AgentModelDefinition, AgentProvider } from "@getpaseo/protocol/agent-types";
import type { AgentModelDefinition } from "@getpaseo/protocol/agent-types";
import type { ProviderProfileModel } from "@getpaseo/protocol/provider-config";
import { compareMatchScores, scoreTextFields } from "@getpaseo/protocol/search/text-match";
import {
@@ -26,6 +26,7 @@ import {
type ProviderDiscoveredModelsCache,
} from "./discovered-models";
import type { ProviderEntry } from "./provider-config";
import { ProviderRefreshButton, useCheckedLabel, type ProviderRefresh } from "./provider-refresh";
const ThemedTrash = withUnistyles(Trash2);
const destructiveColorMapping = (theme: Theme) => ({ color: theme.colors.destructive });
@@ -51,17 +52,19 @@ function rankModels<T>(items: T[], query: string, fields: (item: T) => string[])
export function ProviderModels({
serverId,
entry,
discovered,
refresh,
}: {
serverId: string;
entry: ProviderEntry;
/** List the models the provider reports, with search. Only a running provider reports them. */
discovered: boolean;
refresh: (providers?: AgentProvider[]) => Promise<void>;
/**
* Lists the models the provider reports, with search and the way to ask for them again. Null for
* a provider that is not running, which reports none.
*/
refresh: ProviderRefresh | null;
}) {
const { t } = useTranslation();
const provider = entry.provider;
const discovered = refresh !== null;
const { config, patchConfig } = useDaemonConfig(serverId);
const [query, setQuery] = useState("");
const [addSheetOpen, setAddSheetOpen] = useState(false);
@@ -105,13 +108,11 @@ export function ProviderModels({
additionalModels: additionalModels.filter((model) => model.id !== modelId),
},
},
})
.then(() => refresh([provider]))
.finally(() => {
setDeletingModelId((current) => (current === modelId ? null : current));
});
}).finally(() => {
setDeletingModelId((current) => (current === modelId ? null : current));
});
},
[additionalModels, patchConfig, provider, refresh],
[additionalModels, patchConfig, provider],
);
const customTrailing = useMemo(
@@ -134,10 +135,8 @@ export function ProviderModels({
const discoveredTrailing = useMemo(
() =>
discoveredModels.length > 0 ? (
<Text style={settingsStyles.sectionHeaderTitle}>{discoveredModels.length}</Text>
) : null,
[discoveredModels.length],
refresh ? <DiscoveredTrailing count={discoveredModels.length} refresh={refresh} /> : null,
[discoveredModels.length, refresh],
);
let discoveredBody: React.ReactNode;
@@ -177,23 +176,29 @@ export function ProviderModels({
return (
<View testID="provider-models">
{discovered ? (
<>
<View style={styles.searchRail}>
<SettingsSection title={t("settings.providers.models.title")} trailing={discoveredTrailing}>
<View style={styles.searchRow}>
<SearchField
value={query}
onChangeText={setQuery}
placeholder={t("settings.providers.models.searchPlaceholder")}
clearAccessibilityLabel={t("sessions.actions.clearSearch")}
fullWidth
testID="provider-settings-search"
/>
</View>
<SettingsSection
title={t("settings.providers.models.discovered")}
trailing={discoveredTrailing}
>
<View style={settingsStyles.card}>{discoveredBody}</View>
</SettingsSection>
</>
<View style={settingsStyles.card}>
{/* A provider can report hundreds of models; the rest of the page stays in reach. */}
<ScrollView
style={styles.discoveredList}
// Android scrolls a ScrollView nested in the page or the sheet only with this flag.
nestedScrollEnabled
testID="provider-discovered-models"
>
{discoveredBody}
</ScrollView>
</View>
</SettingsSection>
) : null}
<SettingsSection title={t("settings.providers.models.custom")} trailing={customTrailing}>
<View style={settingsStyles.card}>{customBody}</View>
@@ -204,12 +209,27 @@ export function ProviderModels({
additionalModels={additionalModels}
visible={addSheetOpen}
onClose={handleCloseAddSheet}
refresh={refresh}
/>
</View>
);
}
/** How many models the provider reports, when it last reported them, and the way to ask again. */
function DiscoveredTrailing({ count, refresh }: { count: number; refresh: ProviderRefresh }) {
const checked = useCheckedLabel(refresh);
const facts = [count > 0 ? String(count) : null, checked].filter(Boolean).join(" · ");
return (
<View style={styles.headerTrailing}>
{facts ? (
<Text style={[settingsStyles.sectionHeaderTitle, styles.headerFacts]} numberOfLines={1}>
{facts}
</Text>
) : null}
<ProviderRefreshButton refresh={refresh} form="icon" />
</View>
);
}
function MutedRow({ children }: { children: string }) {
return (
<View style={styles.modelRow}>
@@ -286,14 +306,12 @@ function AddCustomModelSheet({
additionalModels,
visible,
onClose,
refresh,
}: {
serverId: string;
provider: string;
additionalModels: ProviderProfileModel[];
visible: boolean;
onClose: () => void;
refresh: (providers?: AgentProvider[]) => Promise<void>;
}) {
const { t } = useTranslation();
const { patchConfig } = useDaemonConfig(serverId);
@@ -322,13 +340,12 @@ function AddCustomModelSheet({
},
},
})
.then(() => refresh([provider]))
.then(() => onClose())
.catch((err: unknown) => {
setError(err instanceof Error ? err.message : t("settings.providers.models.failedToSave"));
})
.finally(() => setSaving(false));
}, [additionalModels, canAdd, onClose, patchConfig, provider, refresh, t, trimmed]);
}, [additionalModels, canAdd, onClose, patchConfig, provider, t, trimmed]);
const header = useMemo<SheetHeader>(
() => ({ title: t("settings.providers.models.addCustomTitle") }),
@@ -375,15 +392,23 @@ function AddCustomModelSheet({
const ADD_SNAP_POINTS = ["40%"];
const styles = StyleSheet.create((theme) => ({
searchRail: {
// The search field sizes itself along a row.
searchRow: {
flexDirection: "row",
marginBottom: theme.spacing[3],
},
// Nine rows and part of a tenth, so a longer list visibly continues.
discoveredList: {
maxHeight: 320,
},
headerTrailing: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[1],
},
// The facts give way before the button does.
headerFacts: {
flexShrink: 1,
},
modelRow: {
flexDirection: "row",
alignItems: "center",
@@ -0,0 +1,55 @@
import { RotateCw } from "lucide-react-native";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
import { useTimeAgo } from "@/hooks/use-time-ago";
/** Asking the provider again for its status, version and models. */
export interface ProviderRefresh {
/** When the provider last answered. Absent before its first answer. */
checkedAt: string | undefined;
/** A check is running, whoever asked for it. */
busy: boolean;
run: () => void;
}
/** "Checked 5m ago", kept current, or nothing before the provider's first answer. */
export function useCheckedLabel(refresh: ProviderRefresh): string | undefined {
const { t } = useTranslation();
const time = useTimeAgo(refresh.checkedAt ? new Date(refresh.checkedAt) : null);
return refresh.checkedAt ? t("settings.providers.detail.checked", { time }) : undefined;
}
export function ProviderRefreshButton({
refresh,
form,
}: {
refresh: ProviderRefresh;
/** `icon` in a section header, `labelled` in a row. */
form: "icon" | "labelled";
}) {
const { t } = useTranslation();
const label = refresh.busy
? t("settings.providers.diagnostic.refreshing")
: t("settings.providers.diagnostic.refresh");
if (form === "icon")
return (
<Button
variant="ghost"
leftIcon={RotateCw}
onPress={refresh.run}
loading={refresh.busy}
accessibilityLabel={label}
testID="provider-refresh"
/>
);
return (
<Button
variant="outline"
onPress={refresh.run}
loading={refresh.busy}
testID="provider-refresh"
>
{label}
</Button>
);
}
@@ -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 ===
+425 -1
View File
@@ -21,6 +21,7 @@ import { useSessionStore, type Agent } from "@/stores/session-store";
import { normalizeAgentSnapshot } from "@/utils/agent-snapshots";
import { isAgentArchiving, setAgentArchiving } from "@/hooks/use-archive-agent";
import { queryClient } from "@/data/query-client";
import { checkoutStatusQueryKey } from "@/git/query-keys";
import {
HostRuntimeController,
HostRuntimeStore,
@@ -1748,7 +1749,7 @@ describe("HostRuntimeController", () => {
});
latencies["relay:relay.paseo.sh:443"] = 30;
await vi.advanceTimersByTimeAsync(120_000);
await vi.advanceTimersByTimeAsync(240_000);
await controller.runProbeCycleNow();
expect(controller.getSnapshot().activeConnectionId).toBe("direct:lan:6767");
@@ -1807,6 +1808,429 @@ describe("HostRuntimeController", () => {
await controller.stop();
});
it("ignores busy active heartbeat spikes when comparing against an idle alternate probe", async () => {
// Replays the recorded 10:04-10:08 relay sequence (#9149): the active relay has a ~250-300 ms
// baseline over its recent heartbeats, spikes to 383/503/491 ms right before each alternate
// probe, and the idle alternate measures 236/322/291 ms.
useHostRuntimeClock();
const host = makeHost({
connections: [relayPrimary, relayAlternate],
preferredConnectionId: relayPrimary.id,
});
const clients: FakeDaemonClient[] = [];
let alternateProbes = 0;
const latencies: Record<string, number | Error> = {
[relayPrimary.id]: 260,
[relayAlternate.id]: 280,
};
const baseDeps = makeDeps(latencies, clients);
const controller = new HostRuntimeController({
host,
deps: {
...baseDeps,
connectToDaemon: async (input) => {
if (input.connection.id === relayAlternate.id) {
alternateProbes += 1;
}
return baseDeps.connectToDaemon(input);
},
},
});
await controller.start({ autoProbe: false });
expect(controller.getSnapshot().activeConnectionId).toBe(relayPrimary.id);
const activeClient = controller.getSnapshot().client as unknown as FakeDaemonClient;
const rounds = [
{ intervalMs: 120_000, baseline: 295, spike: 383, alternate: 236 },
{ intervalMs: 240_000, baseline: 251, spike: 503, alternate: 322 },
{ intervalMs: 480_000, baseline: 341, spike: 491, alternate: 291 },
];
for (const round of rounds) {
await vi.advanceTimersByTimeAsync(round.intervalMs - 10_000);
activeClient.heartbeatReportsRtt(round.baseline);
await controller.runProbeCycleNow();
await vi.advanceTimersByTimeAsync(10_000);
activeClient.heartbeatReportsRtt(round.spike);
latencies[relayAlternate.id] = round.alternate;
await controller.runProbeCycleNow();
}
expect(alternateProbes).toBe(4);
expect(controller.getSnapshot().activeConnectionId).toBe(relayPrimary.id);
expect(controller.getSnapshot().client).toBe(activeClient);
expect(activeClient.isDisposed()).toBe(false);
await controller.stop();
});
it("requires a proportional RTT improvement before switching away from a high-latency link", async () => {
useHostRuntimeClock();
const host = makeHost({
connections: [relayPrimary, relayAlternate],
preferredConnectionId: relayPrimary.id,
});
const clients: FakeDaemonClient[] = [];
const latencies: Record<string, number | Error> = {
[relayPrimary.id]: 300,
[relayAlternate.id]: 320,
};
const controller = new HostRuntimeController({
host,
deps: makeDeps(latencies, clients),
});
await controller.start({ autoProbe: false });
expect(controller.getSnapshot().activeConnectionId).toBe(relayPrimary.id);
const activeClient = controller.getSnapshot().client as unknown as FakeDaemonClient;
// 60 ms faster on a 300 ms link (20%) is noise, not enough to justify a switch.
activeClient.heartbeatReportsRtt(300);
latencies[relayAlternate.id] = 240;
for (let index = 0; index < 3; index += 1) {
await vi.advanceTimersByTimeAsync(30 * 60_000);
await controller.runProbeCycleNow();
}
expect(controller.getSnapshot().activeConnectionId).toBe(relayPrimary.id);
// 150 ms faster on a 300 ms link (50%) is a real win and switches after 3 consecutive probes.
latencies[relayAlternate.id] = 150;
for (let index = 0; index < 3; index += 1) {
await vi.advanceTimersByTimeAsync(index === 0 ? 30 * 60_000 : 120_000);
await controller.runProbeCycleNow();
}
expect(controller.getSnapshot().activeConnectionId).toBe(relayAlternate.id);
await controller.stop();
});
it("exponentially backs off inactive connection probes while the active connection keeps winning", async () => {
useHostRuntimeClock();
const host = makeHost({
connections: [relayPrimary, relayAlternate],
preferredConnectionId: relayPrimary.id,
});
const clients: FakeDaemonClient[] = [];
let alternateProbes = 0;
const baseDeps = makeDeps(
{
[relayPrimary.id]: 250,
[relayAlternate.id]: 260,
},
clients,
);
const controller = new HostRuntimeController({
host,
deps: {
...baseDeps,
connectToDaemon: async (input) => {
if (input.connection.id === relayAlternate.id) {
alternateProbes += 1;
}
return baseDeps.connectToDaemon(input);
},
},
});
await controller.start({ autoProbe: false });
const activeClient = controller.getSnapshot().client as unknown as FakeDaemonClient;
activeClient.heartbeatReportsRtt(250);
expect(alternateProbes).toBe(1);
// First inactive online probe runs at 2m -> active wins, next interval backs off to 4m.
await vi.advanceTimersByTimeAsync(120_000);
await controller.runProbeCycleNow();
expect(alternateProbes).toBe(2);
// At +2m (still < 4m), no inactive probe runs.
await vi.advanceTimersByTimeAsync(120_000);
await controller.runProbeCycleNow();
expect(alternateProbes).toBe(2);
// At +4m total, second inactive probe runs -> backs off to 8m.
await vi.advanceTimersByTimeAsync(120_000);
await controller.runProbeCycleNow();
expect(alternateProbes).toBe(3);
// At +6m (< 8m), still quiet; at +8m, third inactive probe runs -> backs off to 16m.
await vi.advanceTimersByTimeAsync(6 * 60_000);
await controller.runProbeCycleNow();
expect(alternateProbes).toBe(3);
await vi.advanceTimersByTimeAsync(2 * 60_000);
await controller.runProbeCycleNow();
expect(alternateProbes).toBe(4);
// Foreground verification resets backoff back to 2m without forcing an immediate probe.
await vi.advanceTimersByTimeAsync(3 * 60_000);
controller.ensureConnected({ verify: true });
await controller.runProbeCycleNow();
expect(alternateProbes).toBe(5);
await controller.stop();
});
it("keeps the active connection online while connecting the replacement during an adaptive switch", async () => {
useHostRuntimeClock();
const host = makeHost({
connections: [relayPrimary, relayAlternate],
preferredConnectionId: relayPrimary.id,
});
const clients: FakeDaemonClient[] = [];
const latencies: Record<string, number | Error> = {
[relayPrimary.id]: 300,
[relayAlternate.id]: 320,
};
let replacementConnectGate: ReturnType<typeof createDeferred<void>> | null = null;
let shouldFailReplacement = false;
const baseDeps = makeDeps(latencies, clients);
const controller = new HostRuntimeController({
host,
deps: {
...baseDeps,
createClient: (input) => {
const client = baseDeps.createClient(input) as unknown as FakeDaemonClient;
if (input.connection.id === relayAlternate.id) {
const origConnect = client.connect.bind(client);
client.connect = async () => {
if (replacementConnectGate) {
await replacementConnectGate.promise;
}
if (shouldFailReplacement) {
throw new Error("replacement handshake failed");
}
return origConnect();
};
}
return client as unknown as DaemonClient;
},
},
});
await controller.start({ autoProbe: false });
const initialClient = controller.getSnapshot().client as unknown as FakeDaemonClient;
initialClient.heartbeatReportsRtt(300);
latencies[relayAlternate.id] = 100;
const observedSnapshots: Array<{
status: string;
connectionId: string | null;
hasClient: boolean;
}> = [];
const unsubscribe = controller.subscribe(() => {
const snap = controller.getSnapshot();
observedSnapshots.push({
status: snap.connectionStatus,
connectionId: snap.activeConnectionId,
hasClient: snap.client !== null,
});
});
// Two wins first.
await vi.advanceTimersByTimeAsync(120_000);
await controller.runProbeCycleNow();
await vi.advanceTimersByTimeAsync(120_000);
await controller.runProbeCycleNow();
// Third win triggers a switch, but replacement connect fails: active client must stay online.
shouldFailReplacement = true;
await vi.advanceTimersByTimeAsync(120_000);
await controller.runProbeCycleNow();
expect(controller.getSnapshot().activeConnectionId).toBe(relayPrimary.id);
expect(controller.getSnapshot().connectionStatus).toBe("online");
expect(controller.getSnapshot().client).toBe(initialClient);
expect(initialClient.isDisposed()).toBe(false);
// Now let replacement succeed after a delay: host must stay online on initialClient while
// replacement connects, and never emit connecting or client=null.
shouldFailReplacement = false;
observedSnapshots.length = 0;
for (let index = 0; index < 2; index += 1) {
await vi.advanceTimersByTimeAsync(120_000);
await controller.runProbeCycleNow();
}
replacementConnectGate = createDeferred<void>();
await vi.advanceTimersByTimeAsync(120_000);
const switchingCycle = controller.runProbeCycleNow();
await vi.advanceTimersByTimeAsync(0);
expect(controller.getSnapshot().activeConnectionId).toBe(relayPrimary.id);
expect(controller.getSnapshot().connectionStatus).toBe("online");
expect(controller.getSnapshot().client).toBe(initialClient);
expect(initialClient.isDisposed()).toBe(false);
replacementConnectGate.resolve();
await switchingCycle;
expect(controller.getSnapshot().activeConnectionId).toBe(relayAlternate.id);
expect(controller.getSnapshot().connectionStatus).toBe("online");
expect(controller.getSnapshot().client).not.toBeNull();
expect(controller.getSnapshot().client).not.toBe(initialClient);
expect(initialClient.isDisposed()).toBe(true);
expect(observedSnapshots.some((snap) => snap.status !== "online" || !snap.hasClient)).toBe(
false,
);
unsubscribe();
await controller.stop();
});
it("keeps active client status updates working after a failed make-before-break upgrade", async () => {
useHostRuntimeClock();
const host = makeHost({
connections: [relayPrimary, relayAlternate],
preferredConnectionId: relayPrimary.id,
});
const clients: FakeDaemonClient[] = [];
const latencies: Record<string, number | Error> = {
[relayPrimary.id]: 300,
[relayAlternate.id]: 320,
};
const baseDeps = makeDeps(latencies, clients);
const controller = new HostRuntimeController({
host,
deps: {
...baseDeps,
createClient: (input) => {
const client = baseDeps.createClient(input) as unknown as FakeDaemonClient;
if (input.connection.id === relayAlternate.id) {
client.connect = async () => {
throw new Error("replacement handshake failed");
};
}
return client as unknown as DaemonClient;
},
},
});
await controller.start({ autoProbe: false });
const initialClient = controller.getSnapshot().client as unknown as FakeDaemonClient;
initialClient.heartbeatReportsRtt(300);
latencies[relayAlternate.id] = 100;
for (let index = 0; index < 3; index += 1) {
await vi.advanceTimersByTimeAsync(120_000);
await controller.runProbeCycleNow();
}
expect(controller.getSnapshot().activeConnectionId).toBe(relayPrimary.id);
expect(controller.getSnapshot().connectionStatus).toBe("online");
initialClient.setConnectionState({ status: "disconnected", reason: "transport closed" });
expect(controller.getSnapshot().connectionStatus).toBe("error");
expect(controller.getSnapshot().lastError).toBe("transport closed");
await controller.stop();
});
it("aborts a pending make-before-break upgrade when the candidate connection is removed", async () => {
useHostRuntimeClock();
const host = makeHost({
connections: [relayPrimary, relayAlternate],
preferredConnectionId: relayPrimary.id,
});
const clients: FakeDaemonClient[] = [];
const latencies: Record<string, number | Error> = {
[relayPrimary.id]: 300,
[relayAlternate.id]: 320,
};
const replacementGate = createDeferred<void>();
const replacementClients: FakeDaemonClient[] = [];
const baseDeps = makeDeps(latencies, clients);
const controller = new HostRuntimeController({
host,
deps: {
...baseDeps,
createClient: (input) => {
const client = baseDeps.createClient(input) as unknown as FakeDaemonClient;
if (input.connection.id === relayAlternate.id) {
replacementClients.push(client);
const origConnect = client.connect.bind(client);
client.connect = async () => {
await replacementGate.promise;
return origConnect();
};
}
return client as unknown as DaemonClient;
},
},
});
await controller.start({ autoProbe: false });
const initialClient = controller.getSnapshot().client as unknown as FakeDaemonClient;
initialClient.heartbeatReportsRtt(300);
latencies[relayAlternate.id] = 100;
for (let index = 0; index < 2; index += 1) {
await vi.advanceTimersByTimeAsync(120_000);
await controller.runProbeCycleNow();
}
await vi.advanceTimersByTimeAsync(120_000);
const switchingCycle = controller.runProbeCycleNow();
await vi.advanceTimersByTimeAsync(0);
expect(replacementClients).toHaveLength(1);
const updatePromise = controller.updateHost({
...host,
connections: [relayPrimary],
});
await vi.advanceTimersByTimeAsync(0);
replacementGate.resolve();
await Promise.all([switchingCycle, updatePromise]);
expect(controller.getSnapshot().activeConnectionId).toBe(relayPrimary.id);
expect(controller.getSnapshot().connectionStatus).toBe("online");
expect(controller.getSnapshot().client).toBe(initialClient);
expect(initialClient.isDisposed()).toBe(false);
expect(replacementClients[0]?.isDisposed()).toBe(true);
await controller.stop();
});
it("runs store cache recovery when a make-before-break adaptive switch advances the online epoch", async () => {
useHostRuntimeClock();
const host = makeHost({
serverId: "srv_upgrade_cache_recovery",
connections: [relayPrimary, relayAlternate],
preferredConnectionId: relayPrimary.id,
});
const clients: FakeDaemonClient[] = [];
const latencies: Record<string, number | Error> = {
[relayPrimary.id]: 300,
[relayAlternate.id]: 320,
};
const store = new HostRuntimeStore({
storage: createMemoryHostRuntimeStorage(),
deps: makeDeps(latencies, clients),
});
const queryKey = checkoutStatusQueryKey(host.serverId, "/repo");
try {
store.syncHosts([host]);
await vi.advanceTimersByTimeAsync(0);
expect(store.getSnapshot(host.serverId)?.connectionStatus).toBe("online");
const initialEpoch = store.getSnapshot(host.serverId)?.connectionEpoch ?? 0;
const activeClient = store.getSnapshot(host.serverId)?.client as unknown as FakeDaemonClient;
const initialHistoryGen =
useSessionStore.getState().sessions[host.serverId]?.historySyncGeneration ?? 0;
queryClient.setQueryData(queryKey, { branch: "main" });
expect(queryClient.getQueryState(queryKey)?.isInvalidated).toBe(false);
activeClient.heartbeatReportsRtt(300);
latencies[relayAlternate.id] = 100;
for (let index = 0; index < 3; index += 1) {
await vi.advanceTimersByTimeAsync(120_000);
await store.runProbeCycleNow(host.serverId);
}
expect(store.getSnapshot(host.serverId)?.activeConnectionId).toBe(relayAlternate.id);
expect(store.getSnapshot(host.serverId)?.connectionStatus).toBe("online");
expect(store.getSnapshot(host.serverId)?.connectionEpoch).toBeGreaterThan(initialEpoch);
expect(queryClient.getQueryState(queryKey)?.isInvalidated).toBe(true);
expect(
useSessionStore.getState().sessions[host.serverId]?.historySyncGeneration ?? 0,
).toBeGreaterThan(initialHistoryGen);
} finally {
queryClient.removeQueries({ queryKey });
store.syncHosts([]);
}
});
it("exposes one snapshot with active connection and status from same source", async () => {
const host = makeHost();
const clients: FakeDaemonClient[] = [];
+247 -68
View File
@@ -245,8 +245,11 @@ export interface HostRuntimeStartOptions {
const PROBE_TICK_MS = 2_000;
const PROBE_STEADY_MS = 10_000;
const PROBE_MAX_BACKOFF_MS = 30_000;
const PROBE_INACTIVE_WHILE_ONLINE_MS = 120_000;
const PROBE_INACTIVE_WHILE_ONLINE_INITIAL_MS = 120_000;
const PROBE_INACTIVE_WHILE_ONLINE_MAX_MS = 30 * 60_000;
const ACTIVE_RTT_WINDOW_MS = 60_000;
const ADAPTIVE_SWITCH_THRESHOLD_MS = 40;
const ADAPTIVE_SWITCH_MIN_IMPROVEMENT_RATIO = 0.35;
const ADAPTIVE_SWITCH_CONSECUTIVE_PROBES = 3;
const CONFIGURED_OVERRIDE_BOOTSTRAP_RETRY_MS = 1_000;
@@ -549,13 +552,14 @@ function probeIntervalForConnection(
firstSeenAt: number,
isActiveOnline: boolean,
hasActiveOnlineConnection: boolean,
inactiveOnlineIntervalMs: number,
now: number,
): number {
if (isActiveOnline) {
return PROBE_STEADY_MS;
}
if (hasActiveOnlineConnection) {
return PROBE_INACTIVE_WHILE_ONLINE_MS;
return inactiveOnlineIntervalMs;
}
const age = now - firstSeenAt;
if (age < 10_000) return 2_000;
@@ -728,6 +732,8 @@ export class HostRuntimeController {
private connectionLastProbedAt = new Map<string, number>();
private switchCandidateConnectionId: string | null = null;
private switchCandidateHitCount = 0;
private inactiveOnlineProbeBackoffStep = 0;
private activeRttSamples: Array<{ at: number; rttMs: number }> = [];
private clientIdPromise: Promise<string> | null = null;
private clientIdHash: string | null = null;
private switchRequestVersion = 0;
@@ -823,6 +829,9 @@ export class HostRuntimeController {
this.activeClient = null;
await prev.close().catch(() => undefined);
}
this.resetSwitchCandidate();
this.clearActiveRttSamples();
this.resetInactiveOnlineProbeBackoff();
this.applyConnectionEvent({ type: "stopped" });
this.updateSnapshot({
...toSnapshotConnectionPatch(this.connectionMachineState, this.connectionEpoch),
@@ -832,11 +841,15 @@ export class HostRuntimeController {
async updateHost(host: HostProfile): Promise<void> {
const passwordChanged = this.host.password !== host.password;
const connectionsChanged = !equal(this.host.connections, host.connections);
if (passwordChanged) {
this.probeRequestVersion += 1;
this.authRejectedConnectionIds.clear();
this.updateSnapshot({ authFailureReason: null });
}
if (passwordChanged || connectionsChanged) {
this.resetInactiveOnlineProbeBackoff();
}
const activeConnectionId = this.snapshot.activeConnectionId;
const previousActiveConnection = findConnectionById(this.host, activeConnectionId);
this.host = host;
@@ -862,6 +875,9 @@ export class HostRuntimeController {
}
ensureConnected(options?: { verify?: boolean }): void {
if (options?.verify) {
this.resetInactiveOnlineProbeBackoff();
}
this.activeClient?.ensureConnected(options);
}
@@ -962,6 +978,7 @@ export class HostRuntimeController {
const activeConnectionId = this.snapshot.activeConnectionId;
const hasActiveOnlineConnection = isOnline && activeConnectionId !== null;
const inactiveOnlineIntervalMs = this.inactiveOnlineProbeIntervalMs();
const connectionsToProbe = this.host.connections.filter((connection) => {
if (this.authRejectedConnectionIds.has(connection.id)) return false;
const lastProbed = this.connectionLastProbedAt.get(connection.id);
@@ -974,6 +991,7 @@ export class HostRuntimeController {
firstSeen,
isActiveOnline,
hasActiveOnlineConnection,
inactiveOnlineIntervalMs,
now,
);
return now - lastProbed >= interval;
@@ -1081,10 +1099,10 @@ export class HostRuntimeController {
// Adaptive switching counts fresh comparisons only. The probe map keeps the last known
// sample per connection for display and failover; a streak hit needs a candidate measured
// in this cycle and a heartbeat RTT from the socket that is active right now. Re-reading
// the cached map at every ten-second active tick turned one idle-probe sample into three
// "consecutive" wins, and a reconnected socket inherited its predecessor's RTT, so a
// working relay connection was replaced within seconds of coming online.
// in this cycle and a baseline RTT from the socket that is active right now. Using the
// rolling minimum of recent active heartbeats filters out single busy/stalled ticks so a
// loaded working socket does not lose to an idle probe, and a proportional threshold avoids
// flapping on normal jitter on high-RTT links.
const sampledCandidates = connectionsToProbe.filter(
(connection) => connection.id !== currentActiveConnectionId,
);
@@ -1102,22 +1120,29 @@ export class HostRuntimeController {
})
.sort((left, right) => left.latencyMs - right.latencyMs)[0] ?? null;
if (!fastest) {
// Every candidate sampled this cycle failed: that breaks the streak.
// Every candidate sampled this cycle failed: that breaks the streak and backs off.
this.resetSwitchCandidate();
this.advanceInactiveOnlineProbeBackoff();
return;
}
const activeRttMs = this.currentActiveSocketRttMs();
const activeRttMs = this.currentActiveSocketBaselineRttMs(performance.now());
if (activeRttMs === null) {
return;
}
const requiredImprovementMs = Math.max(
ADAPTIVE_SWITCH_THRESHOLD_MS,
activeRttMs * ADAPTIVE_SWITCH_MIN_IMPROVEMENT_RATIO,
);
const improvement = activeRttMs - fastest.latencyMs;
if (improvement < ADAPTIVE_SWITCH_THRESHOLD_MS) {
if (improvement < requiredImprovementMs) {
this.resetSwitchCandidate();
this.advanceInactiveOnlineProbeBackoff();
return;
}
this.resetInactiveOnlineProbeBackoff();
if (this.switchCandidateConnectionId === fastest.connectionId) {
this.switchCandidateHitCount += 1;
} else {
@@ -1130,6 +1155,7 @@ export class HostRuntimeController {
await this.switchToConnection({
connectionId: fastest.connectionId,
expectedProbeVersion: requestVersion,
keepActiveUntilConnected: true,
});
}
};
@@ -1194,6 +1220,7 @@ export class HostRuntimeController {
return;
}
if (rttMs !== null) {
this.recordActiveRttSample(rttMs, performance.now());
probeByConnectionId.set(connection.id, {
status: "available",
latencyMs: rttMs,
@@ -1245,6 +1272,45 @@ export class HostRuntimeController {
return client.getLastLivenessRttMs();
}
private recordActiveRttSample(rttMs: number, now: number): void {
this.activeRttSamples = this.activeRttSamples.filter(
(sample) => now - sample.at <= ACTIVE_RTT_WINDOW_MS,
);
this.activeRttSamples.push({ at: now, rttMs });
}
private clearActiveRttSamples(): void {
this.activeRttSamples = [];
}
private currentActiveSocketBaselineRttMs(now: number): number | null {
const currentRttMs = this.currentActiveSocketRttMs();
if (currentRttMs === null) return null;
this.recordActiveRttSample(currentRttMs, now);
let baseline = this.activeRttSamples[0]!.rttMs;
for (const sample of this.activeRttSamples) {
if (sample.rttMs < baseline) baseline = sample.rttMs;
}
return baseline;
}
private inactiveOnlineProbeIntervalMs(): number {
return Math.min(
PROBE_INACTIVE_WHILE_ONLINE_INITIAL_MS * 2 ** this.inactiveOnlineProbeBackoffStep,
PROBE_INACTIVE_WHILE_ONLINE_MAX_MS,
);
}
private advanceInactiveOnlineProbeBackoff(): void {
if (this.inactiveOnlineProbeIntervalMs() < PROBE_INACTIVE_WHILE_ONLINE_MAX_MS) {
this.inactiveOnlineProbeBackoffStep += 1;
}
}
private resetInactiveOnlineProbeBackoff(): void {
this.inactiveOnlineProbeBackoffStep = 0;
}
private resetSwitchCandidate(): void {
this.switchCandidateConnectionId = null;
this.switchCandidateHitCount = 0;
@@ -1434,6 +1500,7 @@ export class HostRuntimeController {
connectionId: string;
expectedProbeVersion?: number;
existingClient?: DaemonClient;
keepActiveUntilConnected?: boolean;
}): Promise<void> {
const { connectionId, expectedProbeVersion, existingClient } = input;
if (!this.canProceedForProbe(expectedProbeVersion)) {
@@ -1455,6 +1522,24 @@ export class HostRuntimeController {
return;
}
const makeBeforeBreak =
Boolean(input.keepActiveUntilConnected) &&
!existingClient &&
this.activeClient !== null &&
this.connectionMachineState.tag === "online";
const nextGeneration = this.snapshot.clientGeneration + 1;
if (makeBeforeBreak) {
await this.switchToConnectionMakeBeforeBreak({
connection,
clientId,
nextGeneration,
requestVersion,
expectedProbeVersion,
});
return;
}
await this.disposePreviousActiveClient();
if (!this.isSwitchStillValid(requestVersion, expectedProbeVersion)) {
@@ -1462,7 +1547,6 @@ export class HostRuntimeController {
return;
}
const nextGeneration = this.snapshot.clientGeneration + 1;
const client =
existingClient ??
this.deps.createClient({
@@ -1479,6 +1563,8 @@ export class HostRuntimeController {
}
this.activeClient = client;
this.clearActiveRttSamples();
this.resetInactiveOnlineProbeBackoff();
this.applyConnectionEvent({
type: "select_connection",
connectionId: connection.id,
@@ -1490,67 +1576,148 @@ export class HostRuntimeController {
client: null,
});
const failConnection = async (error: unknown) => {
if (!this.isCurrentSwitchRequest(requestVersion) || this.activeClient !== client) return;
const authFailure = getConnectionAuthFailureReason(error);
if (authFailure) this.authRejectedConnectionIds.add(connection.id);
this.unsubscribeClientStatus?.();
this.unsubscribeClientStatus = null;
this.unsubscribeClientHandlers?.();
this.unsubscribeClientHandlers = null;
client.setReconnectEnabled(false);
this.applyConnectionEvent({ type: "connect_failed", message: toErrorMessage(error) });
this.updateSnapshot({
...toSnapshotConnectionPatch(this.connectionMachineState, this.connectionEpoch),
client: null,
authFailureReason: authFailure,
});
if (authFailure) {
const probes = new Map(this.snapshot.probeByConnectionId);
probes.set(connection.id, { status: "unavailable", latencyMs: null });
this.updateSnapshot({ probeByConnectionId: probes });
for (const candidate of this.host.connections) {
if (!this.authRejectedConnectionIds.has(candidate.id)) {
this.connectionLastProbedAt.delete(candidate.id);
}
}
}
try {
await client.close();
} catch {
/* Preserve the compatibility/connection error. */
}
if (
authFailure &&
this.host.connections.some((candidate) => !this.authRejectedConnectionIds.has(candidate.id))
) {
void this.runProbeCycleNow();
}
};
try {
if (!existingClient) await client.connect();
if (!this.isCurrentSwitchRequest(requestVersion) || this.activeClient !== client) return;
this.unsubscribeClientHandlers =
this.deps.mountClientHandlers?.({ client, host: this.host, connection }) ?? null;
this.unsubscribeClientStatus = client.subscribeConnectionStatus((state) => {
if (!this.isCurrentSwitchRequest(requestVersion) || this.activeClient !== client) return;
if (client.authFailureReason) {
void failConnection(new DaemonAuthenticationError(client.authFailureReason));
return;
}
if (state.status === "connected") this.learnRelaySecurity(client, connection.id);
// Switch evidence belongs to the socket it was measured against.
if (state.status !== "connected") this.resetSwitchCandidate();
this.applyConnectionEvent({ type: "client_state", state, lastError: client.lastError });
this.updateSnapshot({
...toSnapshotConnectionPatch(this.connectionMachineState, this.connectionEpoch),
...this.buildAgentDirectoryStatusPatch(),
client,
authFailureReason: null,
});
});
this.attachActiveClient({ client, connection });
} catch (error) {
await failConnection(error);
await this.failActiveConnection({ client, connection, error });
}
}
private async switchToConnectionMakeBeforeBreak(input: {
connection: HostConnection;
clientId: string;
nextGeneration: number;
requestVersion: number;
expectedProbeVersion?: number;
}): Promise<void> {
const { connection, clientId, nextGeneration, requestVersion, expectedProbeVersion } = input;
const replacement = this.deps.createClient({
host: this.host,
connection,
clientId,
runtimeGeneration: nextGeneration,
});
replacement.setReconnectEnabled(false);
try {
await replacement.connect();
} catch (error) {
const authFailure = getConnectionAuthFailureReason(error);
if (authFailure) {
this.authRejectedConnectionIds.add(connection.id);
const probes = new Map(this.snapshot.probeByConnectionId);
probes.set(connection.id, { status: "unavailable", latencyMs: null });
this.updateSnapshot({ probeByConnectionId: probes });
}
await replacement.close().catch(() => undefined);
return;
}
const resolveValidTarget = (): HostConnection | null => {
if (!this.isSwitchStillValid(requestVersion, expectedProbeVersion)) return null;
const saved = findConnectionById(this.host, connection.id);
if (!saved || connectionNeedsNewClient(connection, saved, replacement)) return null;
return saved;
};
if (!resolveValidTarget()) {
await replacement.close().catch(() => undefined);
return;
}
replacement.setReconnectEnabled(true);
await this.disposePreviousActiveClient();
const target = resolveValidTarget();
if (!target) {
await replacement.close().catch(() => undefined);
return;
}
this.activeClient = replacement;
this.clearActiveRttSamples();
this.resetInactiveOnlineProbeBackoff();
this.applyConnectionEvent({
type: "select_connection",
connectionId: target.id,
connection: toActiveConnection(target),
});
this.snapshot = { ...this.snapshot, clientGeneration: nextGeneration };
this.attachActiveClient({ client: replacement, connection: target });
}
private attachActiveClient(input: { client: DaemonClient; connection: HostConnection }): void {
const { client, connection } = input;
this.unsubscribeClientHandlers =
this.deps.mountClientHandlers?.({ client, host: this.host, connection }) ?? null;
this.unsubscribeClientStatus = client.subscribeConnectionStatus((state) => {
if (this.activeClient !== client) return;
if (client.authFailureReason) {
void this.failActiveConnection({
client,
connection,
error: new DaemonAuthenticationError(client.authFailureReason),
});
return;
}
if (state.status === "connected") this.learnRelaySecurity(client, connection.id);
// Switch evidence belongs to the socket it was measured against.
if (state.status !== "connected") {
this.resetSwitchCandidate();
this.clearActiveRttSamples();
this.resetInactiveOnlineProbeBackoff();
}
this.applyConnectionEvent({ type: "client_state", state, lastError: client.lastError });
this.updateSnapshot({
...toSnapshotConnectionPatch(this.connectionMachineState, this.connectionEpoch),
...this.buildAgentDirectoryStatusPatch(),
client,
authFailureReason: null,
});
});
}
private async failActiveConnection(input: {
client: DaemonClient;
connection: HostConnection;
error: unknown;
}): Promise<void> {
const { client, connection, error } = input;
if (this.activeClient !== client) return;
const authFailure = getConnectionAuthFailureReason(error);
if (authFailure) this.authRejectedConnectionIds.add(connection.id);
this.unsubscribeClientStatus?.();
this.unsubscribeClientStatus = null;
this.unsubscribeClientHandlers?.();
this.unsubscribeClientHandlers = null;
client.setReconnectEnabled(false);
this.applyConnectionEvent({ type: "connect_failed", message: toErrorMessage(error) });
this.updateSnapshot({
...toSnapshotConnectionPatch(this.connectionMachineState, this.connectionEpoch),
client: null,
authFailureReason: authFailure,
});
if (authFailure) {
const probes = new Map(this.snapshot.probeByConnectionId);
probes.set(connection.id, { status: "unavailable", latencyMs: null });
this.updateSnapshot({ probeByConnectionId: probes });
for (const candidate of this.host.connections) {
if (!this.authRejectedConnectionIds.has(candidate.id)) {
this.connectionLastProbedAt.delete(candidate.id);
}
}
}
try {
await client.close();
} catch {
/* Preserve the compatibility/connection error. */
}
if (
authFailure &&
this.host.connections.some((candidate) => !this.authRejectedConnectionIds.has(candidate.id))
) {
void this.runProbeCycleNow();
}
}
@@ -1693,6 +1860,7 @@ export class HostRuntimeStore {
private hostRegistryStatus: HostRegistryStatus = "loading";
private deps: HostRuntimeControllerDeps;
private lastConnectionStatusByServer = new Map<string, HostRuntimeConnectionStatus>();
private lastOnlineEpochByServer = new Map<string, number>();
private connectionStatusStartedAtByServer = new Map<string, number>();
private queuedAgentDrainInFlight = new Set<string>();
private directorySyncByServer = new Map<string, DirectorySync>();
@@ -1950,6 +2118,7 @@ export class HostRuntimeStore {
rekeyMap(this.controllers, oldServerId, newServerId);
rekeyMap(this.lastConnectionStatusByServer, oldServerId, newServerId);
rekeyMap(this.lastOnlineEpochByServer, oldServerId, newServerId);
rekeyMap(this.connectionStatusStartedAtByServer, oldServerId, newServerId);
this.replicaCache.reconcileServerId(oldServerId, newServerId);
projectIconCache.reconcileServerId(oldServerId, newServerId);
@@ -2442,6 +2611,7 @@ export class HostRuntimeStore {
this.fleetDirectoryDemand.delete(serverId);
this.controllers.delete(serverId);
this.lastConnectionStatusByServer.delete(serverId);
this.lastOnlineEpochByServer.delete(serverId);
this.connectionStatusStartedAtByServer.delete(serverId);
this.directorySyncByServer.get(serverId)?.dispose();
this.directorySyncByServer.delete(serverId);
@@ -2492,6 +2662,9 @@ export class HostRuntimeStore {
);
const initialSnapshot = controller.getSnapshot();
this.lastConnectionStatusByServer.set(host.serverId, initialSnapshot.connectionStatus);
if (initialSnapshot.connectionStatus === "online") {
this.lastOnlineEpochByServer.set(host.serverId, initialSnapshot.connectionEpoch);
}
this.connectionStatusStartedAtByServer.set(host.serverId, Date.now());
controller.subscribe(() => {
const snapshot = controller.getSnapshot();
@@ -2591,6 +2764,7 @@ export class HostRuntimeStore {
const controller = this.controllers.get(serverId);
if (!controller) {
this.lastConnectionStatusByServer.delete(serverId);
this.lastOnlineEpochByServer.delete(serverId);
this.connectionStatusStartedAtByServer.delete(serverId);
return;
}
@@ -2605,6 +2779,7 @@ export class HostRuntimeStore {
},
});
const previousStatus = this.lastConnectionStatusByServer.get(serverId);
const previousOnlineEpoch = this.lastOnlineEpochByServer.get(serverId);
const statusChanged = previousStatus !== snapshot.connectionStatus;
const isUnavailable =
snapshot.connectionStatus !== "online" && snapshot.connectionStatus !== "idle";
@@ -2615,7 +2790,11 @@ export class HostRuntimeStore {
}
this.lastConnectionStatusByServer.set(serverId, snapshot.connectionStatus);
const didTransitionOnline =
snapshot.connectionStatus === "online" && previousStatus !== "online";
snapshot.connectionStatus === "online" &&
(previousStatus !== "online" || previousOnlineEpoch !== snapshot.connectionEpoch);
if (snapshot.connectionStatus === "online") {
this.lastOnlineEpochByServer.set(serverId, snapshot.connectionEpoch);
}
if (didTransitionOnline) {
useSessionStore.getState().bumpHistorySyncGeneration(serverId);
for (const child of this.controllers.values()) void child.reconnectVia(serverId);
@@ -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);
}
@@ -24,6 +24,7 @@ import { TitlebarDragRegion } from "@/components/desktop/titlebar-drag-region";
import { MenuHeader } from "@/components/headers/menu-header";
import { useIsCompactFormFactor } from "@/constants/layout";
import { useToast } from "@/contexts/toast-context";
import { draftCreationKey } from "@/composer/draft/creation-key";
import { useAgentInputDraft } from "@/composer/draft/input-draft";
import { useForgeSearchQuery } from "@/git/use-forge-search-query";
import { getForgePresentation } from "@/git/forge";
@@ -336,6 +337,7 @@ interface WorkspaceCreationResult {
async function createMultiplicityWorkspace(input: {
idempotencyKey: string;
launchTarget: LaunchTarget;
worktreeSlug: string;
client: NonNullable<ReturnType<typeof useHostRuntimeClient>>;
isolation: "local" | "worktree";
@@ -365,10 +367,8 @@ async function createMultiplicityWorkspace(input: {
prompt: input.prompt,
attachments: input.attachments,
});
const payload = await input.client.createWorkspace({
idempotencyKey: input.idempotencyKey,
const request: Omit<CreateWorkspaceRequestOptions, "idempotencyKey" | "onEvent"> = {
agent: input.agent,
onEvent: input.onEvent,
source: isWorktree
? {
kind: "worktree",
@@ -387,6 +387,14 @@ async function createMultiplicityWorkspace(input: {
},
...(firstAgentContext ? { firstAgentContext } : {}),
...(Object.keys(input.metadata).length > 0 ? { metadata: { ...input.metadata } } : {}),
};
const payload = await input.client.createWorkspace({
...request,
idempotencyKey: draftCreationKey(input.idempotencyKey, {
request,
launchTarget: input.launchTarget,
}),
onEvent: input.onEvent,
});
if (payload.error || !payload.workspace) {
throw new Error(payload.error ?? input.createFailedMessage);
@@ -508,7 +516,7 @@ async function createWorkspaceChatAgent(input: CreateChatAgentInput): Promise<Su
});
const images = await encodeImages(wirePayload.images);
let navigated = false;
let outcome: SubmitOutcome = "background";
const delivery: { outcome: SubmitOutcome } = { outcome: "background" };
const initialAgent: NonNullable<CreateWorkspaceRequestOptions["agent"]> = {
config: {
provider,
@@ -545,7 +553,7 @@ async function createWorkspaceChatAgent(input: CreateChatAgentInput): Promise<Su
provider,
composerState,
});
outcome = submitWorkspaceDraft({
delivery.outcome = submitWorkspaceDraft({
clearConsumedDraft,
draftKey: input.draftKey,
draftContextScopeKey: input.draftContextScopeKey,
@@ -571,9 +579,15 @@ async function createWorkspaceChatAgent(input: CreateChatAgentInput): Promise<Su
};
// A retry after a failed agent start belongs to the ready workspace's draft, not to this creation.
const agentCreation = { result: Promise.resolve().then(() => execute()) };
await agentCreation.result;
if (outcome === "background") clearConsumedDraft();
return outcome;
try {
await agentCreation.result;
} catch (error) {
// Once handed off to the workspace draft tab, that tab owns surfacing agent startup errors.
if (delivery.outcome === "navigated") return delivery.outcome;
throw error;
}
if (delivery.outcome === "background") clearConsumedDraft();
return delivery.outcome;
}
function buildComposerConfig(input: {
@@ -1349,6 +1363,7 @@ export function NewWorkspaceScreen({
: undefined;
const normalizedWorkspace = await createMultiplicityWorkspace({
idempotencyKey: creationIdentity.draftId,
launchTarget,
worktreeSlug: creationIdentity.worktreeSlug,
client: connectedClient,
isolation: createsWorktree ? "worktree" : "local",
@@ -1373,6 +1388,7 @@ export function NewWorkspaceScreen({
creationIdentity,
creationResult,
effectiveIsolation,
launchTarget,
mergeWorkspaces,
queryClient,
selectedItem,
@@ -1443,7 +1459,9 @@ export function NewWorkspaceScreen({
const message = toErrorMessage(error);
setPendingAction(null);
setErrorMessage(message);
toast.error(message);
if (!isStillOnCreateScreen()) {
toast.error(message);
}
}
},
[
@@ -1524,7 +1542,9 @@ export function NewWorkspaceScreen({
const message = toErrorMessage(error);
setPendingAction(null);
setErrorMessage(message);
toast.error(message);
if (!isStillOnCreateScreen()) {
toast.error(message);
}
}
}, [
ensureWorkspace,
@@ -1662,6 +1682,7 @@ export function NewWorkspaceScreen({
clearDraft={noopClearDraft}
autoFocus={terminalTakesPrompt}
autoFocusKey={launchFocusKey}
error={errorMessage}
/>
) : (
<Composer
@@ -1693,6 +1714,7 @@ export function NewWorkspaceScreen({
autoFocusKey={launchFocusKey}
commandDraft={composerState?.commandDraft}
agentControls={agentControlsWithDisabled}
error={errorMessage}
/>
);
return (
@@ -1705,7 +1727,6 @@ export function NewWorkspaceScreen({
onImportSession={importSession.open}
>
{composer}
{errorMessage ? <Text style={styles.errorText}>{errorMessage}</Text> : null}
</NewWorkspaceLayout>
{importSession.sheet}
</FileDropZone>
@@ -1867,11 +1888,6 @@ const styles = StyleSheet.create((theme) => ({
fontWeight: theme.fontWeight.normal,
color: theme.colors.foreground,
},
errorText: {
fontSize: theme.fontSize.base,
color: theme.colors.destructive,
lineHeight: 20,
},
}));
/**
@@ -29,7 +29,9 @@ import { EditingTextInput as TextInput } from "@/components/ui/text-input";
import { SettingsTextAreaCard } from "@/components/settings-textarea";
import { SettingsGroup } from "@/components/settings/headings/settings-group";
import { SettingsSection } from "@/components/settings/headings/settings-section";
import { SettingsBackLink, SettingsDetailHeader } from "@/components/settings";
import type { PageTitleParent } from "@/components/page-layout";
import { useIsCompactFormFactor } from "@/constants/layout";
import { SettingsDetailHeader } from "@/components/settings";
import { settingsStyles } from "@/styles/settings";
import { useProjects } from "@/hooks/use-projects";
import type { ProjectEditFormSnapshot } from "@/projects/edit-form";
@@ -95,14 +97,12 @@ export interface ProjectSettingsScreenProps {
serverId: string;
projectId: string;
onBackToProjects: () => void;
showBackToProjects: boolean;
}
export default function ProjectSettingsScreen({
serverId,
projectId,
onBackToProjects,
showBackToProjects,
}: ProjectSettingsScreenProps) {
const { projects } = useProjects();
const project = useMemo(
@@ -123,12 +123,7 @@ export default function ProjectSettingsScreen({
selectedHost.repoRoot.trim().length > 0;
if (!project || !selectedHost || !client || !canEdit) {
return (
<NoEditableTarget
onBackToProjects={onBackToProjects}
showBackToProjects={showBackToProjects}
/>
);
return <NoProject onBackToProjects={onBackToProjects} />;
}
return (
@@ -138,24 +133,29 @@ export default function ProjectSettingsScreen({
client={client}
isHostGone={isHostGone}
onBackToProjects={onBackToProjects}
showBackToProjects={showBackToProjects}
/>
);
}
function NoEditableTarget({
onBackToProjects,
showBackToProjects,
}: {
onBackToProjects: () => void;
showBackToProjects: boolean;
}) {
/** A project page with no project to name: the title is the way back to Projects. */
function NoProject({ onBackToProjects }: { onBackToProjects: () => void }) {
const parent = useProjectsParent(onBackToProjects);
return (
<>
<SettingsDetailHeader parent={parent} />
<NoEditableTarget onBackToProjects={onBackToProjects} />
</>
);
}
function NoEditableTarget({ onBackToProjects }: { onBackToProjects: () => void }) {
const { t } = useTranslation();
// The compact back header already goes back to Projects.
const isCompact = useIsCompactFormFactor();
return (
<View style={styles.noTargetContainer}>
{showBackToProjects ? <BackToProjectsButton onPress={onBackToProjects} /> : null}
<Text style={styles.noTargetText}>{t("settings.project.noEditableTarget")}</Text>
{showBackToProjects ? (
{isCompact ? null : (
<Button
testID="project-settings-back-button"
onPress={onBackToProjects}
@@ -163,19 +163,22 @@ function NoEditableTarget({
>
{t("settings.project.backToProjects")}
</Button>
) : null}
)}
</View>
);
}
function BackToProjectsButton({ onPress }: { onPress: () => void }) {
/** Projects as the first part of a project page's title, which goes back to the list. */
function useProjectsParent(onPress: () => void): PageTitleParent {
const { t } = useTranslation();
return (
<SettingsBackLink
label={t("settings.project.backToProjects")}
onPress={onPress}
testID="project-settings-back-link"
/>
return useMemo(
() => ({
label: t("settings.projects"),
accessibilityLabel: t("settings.project.backToProjects"),
onPress,
testID: "project-settings-back-link",
}),
[onPress, t],
);
}
@@ -185,7 +188,6 @@ interface ProjectSettingsBodyProps {
client: DaemonClient;
isHostGone: boolean;
onBackToProjects: () => void;
showBackToProjects: boolean;
}
function ProjectSettingsBody({
@@ -194,7 +196,6 @@ function ProjectSettingsBody({
client,
isHostGone,
onBackToProjects,
showBackToProjects,
}: ProjectSettingsBodyProps) {
const { t } = useTranslation();
const [isEditSheetOpen, setIsEditSheetOpen] = useState(false);
@@ -256,17 +257,7 @@ function ProjectSettingsBody({
const handleReload = useCallback(() => {
void readQuery.refetch();
}, [readQuery]);
const backLink = useMemo(
() =>
showBackToProjects
? {
label: t("settings.project.backToProjects"),
onPress: onBackToProjects,
testID: "project-settings-back-link",
}
: undefined,
[onBackToProjects, showBackToProjects, t],
);
const parent = useProjectsParent(onBackToProjects);
const titleIcon = useMemo(
() => (
<ProjectTitleIcon
@@ -294,9 +285,9 @@ function ProjectSettingsBody({
);
return (
<View role="main" style={styles.body}>
<View role="main">
<SettingsDetailHeader
back={backLink}
parent={parent}
icon={titleIcon}
title={selectedHost.projectName}
trailing={editButton}
@@ -327,7 +318,6 @@ function ProjectSettingsBody({
onReload: handleReload,
isHostGone,
onBackToProjects,
showBackToProjects,
})}
</View>
);
@@ -345,7 +335,6 @@ interface RenderContentInput {
onReload: () => void;
isHostGone: boolean;
onBackToProjects: () => void;
showBackToProjects: boolean;
}
function renderContent({
@@ -360,7 +349,6 @@ function renderContent({
onReload,
isHostGone,
onBackToProjects,
showBackToProjects,
}: RenderContentInput) {
if (readQuery.isLoading) {
return (
@@ -379,12 +367,7 @@ function renderContent({
}
if (isHostGone) {
return (
<NoEditableTarget
onBackToProjects={onBackToProjects}
showBackToProjects={showBackToProjects}
/>
);
return <NoEditableTarget onBackToProjects={onBackToProjects} />;
}
if (!loadedConfig) {
@@ -1118,10 +1101,6 @@ const styles = StyleSheet.create((theme) => ({
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.base,
},
body: {
padding: theme.spacing[4],
gap: theme.spacing[2],
},
editButton: {
padding: theme.spacing[1],
},
+2 -3
View File
@@ -1335,7 +1335,6 @@ export default function SettingsScreen({ view }: SettingsScreenProps) {
serverId={view.serverId}
projectId={view.projectId}
onBackToProjects={handleBackFromDetail}
showBackToProjects={!isCompactLayout}
/>
);
}
@@ -1345,7 +1344,6 @@ export default function SettingsScreen({ view }: SettingsScreenProps) {
serverId={view.serverId}
provider={view.providerId}
onBack={handleBackFromDetail}
showBack={!isCompactLayout}
/>
);
}
@@ -1450,7 +1448,8 @@ export default function SettingsScreen({ view }: SettingsScreenProps) {
<WindowChromeRegion corners="top-right">
<View style={desktopStyles.contentPane} testID="settings-detail-pane">
<PageLayout
title={detailTitle}
// A project or provider page draws its own title, which names the list it came from.
title={view.kind === "project" || view.kind === "provider" ? undefined : detailTitle}
actions={detailActions}
width={detailWidth}
titleTestID="settings-detail-header-title"
+3
View File
@@ -1,4 +1,5 @@
import { StyleSheet } from "react-native-unistyles";
import { mapLayout, SWITCH_HEIGHT } from "@/components/ui/control-geometry";
export const settingsStyles = StyleSheet.create((theme) => ({
section: {
@@ -34,6 +35,8 @@ export const settingsStyles = StyleSheet.create((theme) => ({
justifyContent: "space-between",
paddingVertical: theme.spacing[4],
paddingHorizontal: theme.spacing[4],
// As tall as a row holding a switch, so rows with and without one line up.
minHeight: mapLayout(SWITCH_HEIGHT, (height) => height + theme.spacing[4] * 2),
},
rowBorder: {
borderTopWidth: 1,
@@ -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>

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