Compare commits

..
Author SHA1 Message Date
Mohamed Boudra 67d512ca27 fix(app): hold running indicators in place while their panel is hidden
A ring, loader or shimmer in a panel that was not showing drew its resting
frame. On a phone the sidebar slides into view before its panel counts as
showing, so every ring sat at the resting position during the slide and
jumped to the running position when the slide settled.

A hidden indicator now stays bound to its clock and stops running it. The
clock and the loader's ticker hold the time they have run and count on from
it, so an indicator continues from where it stopped.
2026-12-01 13:25:22 +01:00
Mohamed Boudra bdad80d9bf fix(app): count the indicator clock with a timing the driver cannot end early
The native clock was a decay that never slows. React Native's driver ends
a decay when its value moves less than 0.1 between two frames, and two
frames that carry the same millisecond are enough. #11586 started the
decay again from the JS thread, but every end still showed as a pause and
a jump until the JS thread got to it.

The clock is now a linear timing, which the driver reads off the time
since it started and has no such check. It counts in ten-minute spans.
The end of a span is the one event that reaches the JS thread, which
starts the next span at the current time.
2026-12-01 13:25:22 +01:00
paseo-bot[bot]andDesmond Leong 1adabf70c8 fix(claude): settle stopped subagents after a daemon restart (#11594)
Claude can send a stop before it announces tasks in the new session. Match the terminal notice to the restored child so the open chat updates its original row.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Desmond Leong <desmond@returning.ai>
2026-12-01 12:12:45 +00:00
87427c2aa1 Release the microphone when voice mode stops without a daemon connection (#11587)
If the daemon is unreachable when voice mode stops, setVoiceMode(false)
rejects and stopVoice never stopped microphone capture or released the
screen wake lock. The runtime then reported voice as disabled while the
microphone stayed open.

Release capture and the wake lock in a finally block. The rejection still
propagates to the caller.

Closes #7558

Co-authored-by: luke <luopeihuan@gmail.com>
Co-authored-by: RoundRedDot <roundreddot@gmail.com>
2026-12-01 18:10:26 +07:00
Mohamed Boudra cfa4536358 Show Antigravity usage again, refreshed only when you ask (#11585)
* Show Antigravity usage again, refreshed only when you ask

Google's December 2026 terms allow running the unmodified agy harness,
including `agy -p`, through supported interfaces. Each `agy -p "/usage"`
still refreshes the quota on Google's backend, so Paseo must not run it
in the background.

Add `refresh: "manual"` to usage source registrations. The daemon never
fetches a manual source on lists, polls, or agent observations. A
targeted or host-wide forceRefresh fetches it once and caches the result
until the next forceRefresh. Before the first refresh, the report entry
has status `not_fetched`, and the card asks the user to refresh. A failed
manual refresh is not retried.

Restore the Antigravity usage source as a manual source. API key sign-in
reports a no-quota message instead of an error.

Update the Antigravity docs for the new terms and the plugin reference
for the new field.

Refs #10952

* Keep a manual usage result when agents join or leave the account

A manual result was keyed by the account's login set. Each Antigravity
agent adds a login, so a second agent or a closed agent reset the card to
"Not checked yet". Key a manual result by its report id instead.
2026-12-01 18:08:31 +07:00
Mohamed Boudra 7f75b0e166 Keep status rings turning when the native driver ends their clock (#11586)
Every status ring and tool-call shimmer on native rides one decay animation. React Native's driver ends a decay when its value moves less than 0.1 between two frames, and on Android two frames that carry the same millisecond are enough. The clock kept its handle, so every indicator froze until all of them left the screen and one came back.

The clock now listens for the driver ending the decay and starts it again at the current time.
2026-12-01 18:00:04 +07:00
Mohamed Boudra b0ca089d54 Skip redundant finished notification after a child agent reports via send_agent_prompt (#11583)
* fix(server): skip redundant finished notice after a child reports to its caller

When a watched child calls send_agent_prompt to report back to its caller, its final wrap-up response usually takes longer than the 2s message-delivery quiet window, so the caller wakes up on the report and then receives a second redundant 'Agent ... finished' notification once the child's turn ends.

Track per-watch report state on the daemon instead of relying on debounce timing or extra agent parameters: admitting an agent-message from a watched child to its caller marks active (non-pending) watches for that pair as reported, while subsequent non-reporting tool calls or a new turn_started clear the mark. Clean turn completions with the mark set end silently (or keep following silently if pending work remains); errors, permission requests, cancellations, and closes are never suppressed.

* docs(agent-lifecycle): note text-only output after explicit report keeps mark

* fix(server): ignore turn 1 turn_started after report and update cross-host batch e2e test

On remote children, turn 1's own turn_started frame can arrive over the observation stream after a fast send_agent_message already marked the watch as reported. Track turn completion so only a turn_started after a completed turn resets per-turn report state.

Update hosts.e2e.test.ts so turn 1 verifies suppression of the redundant finished notice after REMOTE_REPORT, and a follow-up unreported turn exercises automatic remote completion delivery.
2026-12-01 17:44:03 +07:00
Mohamed Boudra 91e7713721 refactor(client,desktop,app): share HostTransportSpec and protocol URIs for browser proxy (#11577)
Follows up on #11561 so adding a new transport (such as hub://) requires no parallel union or dial branch in the desktop browser proxy.

- Move HostTransportSpec, localListenOfHostTarget, and serializeSshTransportUri into @getpaseo/protocol so app, client, and desktop share one URI and local-listen contract.
- Move routed (via) dialing into @getpaseo/client/node createHostTransportFactory (lazy-loading the full client entry so @getpaseo/client/node/lean stays lean) and export DaemonTransport and HostTransportSpec publicly.
- Collapse BrowserProxyTarget / DesktopBrowserProxyTarget onto HostTransportSpec, remove per-transport branches from openTunnelWireConnection, and deduplicate browser routing input assembly between the hook and bridge.
- Rename linkCeiling to admittedCeiling in server handleTunnelHello to match both routed channels and Hub sockets.
2026-12-01 17:43:46 +07:00
SunicemanandShane Su e20ea2aaf2 fix(acp): preserve plain-text setting errors (#11431)
Co-authored-by: Shane Su <shane.su@maiscrm.com>
2026-12-01 10:42:48 +00:00
Mohamed Boudraandluoph 806214d285 Keep long Markdown replies cheap to stream on web and mobile (#11582)
Streaming one long reply made each reveal frame more expensive as the reply grew. The renderer now splits a streaming message into sealed head parts and a tail on every platform, and finds the boundary by parsing only the source after it.

Refs #7584

Co-authored-by: luoph <1686898+luoph@users.noreply.github.com>
2026-12-01 17:36:12 +07:00
KiritoXDone e5edb6efd5 fix(server): keep the full last reply across notifications (#11578) 2026-12-01 10:12:40 +00:00
Mohamed Boudra 0a0544fa4f fix(app): keep chat loading minimal and stop post-load Updating messages flash (#11575)
* fix(app): simplify chat loading state and eliminate post-load updating toast

Loading a workspace or chat previously shifted the spinner vertically as status text swapped in and out, jumped again when underfilled history handed off to the stream viewport overlay, and flashed an "Updating messages" toast right after content painted.

- Render LoadingState as a centered minimal spinner with accessibilityLabel only (no visible text).
- Hoist the agent-initial-fill overlay onto ChatAgentReadyContent so initial history fill shares the same full-pane geometry as agent-loading and reveals the chat and composer together.
- Emit a follow-up catch_up after a bootstrap tail replace only when live head rows actually extend past endCursor.seq, avoiding a redundant after fetch that kept visibility catch-up pending after the chat rendered.
- Keep the FRESHNESS_CHECK_QUIET_MS quiet window across initial subscribe and tail catch-up for opened cursorless chats (such as display-only caches with range: null).

* refactor(app): remove dead viewport initial-fill fallback and unused hostName prop

* fix(app): keep initial history fill overlay non-interactive

The previous viewport-level agent-initial-fill overlay used pointerEvents: none so pointer interactions were never blocked while underfilled history fetched older pages. Hoisting it onto ChatHistoryLoadingOverlay omitted pointerEvents: none, which intercepted scroll.hover() until the held page timed out.
2026-12-01 17:09:59 +07:00
Mohamed Boudra 914143e8b0 Show connected clients and hosts with scopes in Devices settings (#11209)
* feat(devices): show connected clients and hosts with scopes in host settings

Expose live daemon sessions and inbound/outbound peer daemon links in
Settings → Host → Devices, and move Ways to connect (Relay + Tailscale)
into a Pair a device header button sheet so the Devices view stays focused
on active connections.

Protocol changes stay backward compatible with older daemons and clients:
- Optional hello.clientInfo carries device name, platform, kind, and peer
  daemon identity without widening the existing clientType enum.
- daemon.clients.list.request/.response/.changed (gated on
  server_info.features.connectedClients and access.manage) streams live
  connected clients and inbound daemon links with their routed sessions.
- HostSummary gains optional version, permissions, and connectedAt fields
  populated from the remote daemon's server_info while online.

* fix(devices): trim unused client wire fields, stabilize pair modal, and add browser E2E

* fix(devices): reset pair modal step on dismiss and close sheet before host switch

* fix(page-layout): attach titleTestID to title parts instead of outer header with actions

* refactor(devices): flatten daemon session summary primitive and align with auth plan

* fix(devices): keep idle and reconnecting host-link sessions visible via hello.hostLink
2026-12-01 16:59:16 +07:00
paseo-bot[bot] 1969fb331c test(terminal): batch the burst rows in the pressure recovery fixture (#11576)
The fixture batched its 12,050 startup rows because ConPTY on Windows
pays for each TTY write, but it still wrote the 4,000-row burst one row
at a time. On a loaded Windows runner the burst took longer than the
15 s wait for BURST-DONE. Write the burst through the same batching.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-01 09:33:53 +00:00
Mohamed Boudra 16b4c0b25c Show archiving with a neutral trailing spinner instead of the Working ring (#11574)
* fix(app): show archiving with a neutral trailing spinner instead of the working ring

Archiving was wired through the sidebar row's leading isLoading prop, which renders the blue Working StatusRing (and labels hoisted/status-grouped badges as Working). After #11519 made the pre-archive checkout-status check observable, every worktree archive flashed or held the Working ring even when the workspace was idle or awaiting confirmation.

Keep leading status untouched while archiving, show a muted trailing LoadingSpinner after a 150ms delay so fast local checks do not flash, stop spinning as soon as a confirmation dialog opens (while keeping duplicate presses locked out), and dim row content without shifting row or title layout.

* refactor(app): rename row archive-indicator prop to showArchiveIndicator
2026-12-01 16:20:33 +07:00
Mohamed Boudra 82ef763fc2 fix(markdown): stabilize incomplete Markdown while streaming (#11572)
During streaming, incomplete Markdown delimiters briefly rendered as raw
text, wrapped long link URLs, or flipped block types (such as a paragraph
exploding into a Setext H2 on a trailing `-` before a bullet list item,
empty headings/task checkboxes/admonitions, or half-formed tables and code
fences) before snapping back on completion.

Add an incremental, zero-AST streaming stabilizer that runs only while
`streaming` is true before `prepareMarkdownSource`, `splitMermaidFences`,
and `EnrichedMarkdownText`:

- Auto-closes open inline code spans, emphasis/strong/strikethrough
  (in LIFO order and before trailing whitespace), and unfinished links
  via `PENDING_MARKDOWN_LINK` (rendered as a non-interactive link-styled
  span on web and inert on native until the destination closes).
- Withholds bare opening delimiters, incomplete images/link definitions,
  ATX heading prefixes, Setext underline false positives after paragraphs,
  empty list/task/quote/admonition prefixes, opening and partial closing
  code fences (including inside quotes and nested lists), unconfirmed
  table headers/separators/incomplete body rows, and partial HTML tags.
- Caches completed-line fence state per renderer so steady-state reveal
  frames stay bounded to the active trailing block, and avoids double
  stabilization and phantom tail gaps on native head/tail splits.
2026-12-01 16:11:02 +07:00
Mohamed Boudra b6220fd9c6 Show the host icon with a status dot on host selectors (#11568)
* feat(app): show host icon with status dot on host selectors

After adding configurable and auto-detected host icons in #10702, host
selector triggers and single-slot host menu rows still showed only a
bare status dot. Introduce a shared HostStatusIcon that pairs the
resolved host icon (in its identity color) with a corner status dot and
surface-matched knockout ring, and use it across host selector triggers
and compact host menus.

* refactor(app): expose resolved backdrop from FieldTrigger
2026-12-01 16:06:26 +07:00
paseo-ai[bot] c3e627e1cb fix: update lockfile signatures and Nix hash [skip ci] 2026-12-01 08:59:56 +00:00
Mohamed Boudra 78633752b1 Support proxying workspace browser tabs through routed hosts (#11561)
* feat(server): accept network tunnels on routed host channels

Routed host channels required `hello` as the first frame, so a browser
tunnel to a host reached through another daemon failed with
routed_unsupported. The origin daemon now forwards a first-frame
`tunnel_hello` untouched; it pinned the destination's identity when it
accepted the link, so it does not wait for server_info. The destination
redeems the ticket and also requires workspace.write on the physical
link's admitted ceiling, so a narrowed link cannot carry a tunnel even
with a valid ticket.

`server_info.features.routedNetworkTunnel` lets the app require both
daemons to support this before routing a browser tab through them.

* feat(desktop): open browser proxy tunnels to routed hosts

A routed host has no address of its own, so the desktop browser proxy
could not reach it and the pane showed "routed hosts unsupported". The
proxy now opens a client session to the origin daemon and runs the
network tunnel over a host channel to the routed host.

All tunnel targets (direct, SSH, relay, routed) now run the tunnel_hello
handshake over the client's DaemonTransport instead of a separate socket
stack, so the proxy reuses the same connectors the app uses. SSH tunnels
take an explicit spawn env so the desktop can strip AppImage variables.

The renderer resolves the origin host for routed hosts and only offers
the proxy when both daemons advertise routedNetworkTunnel; older daemons
get the update-required state. The gate is tagged
COMPAT(routedNetworkTunnel) for removal.

* test(desktop): verify routed host browser proxy in Electron E2E
2026-12-01 15:52:03 +07:00
Mohamed Boudra 22a4447431 feat(plugins): add plugin scorecard, updates, and sidebar across website and app (#11563)
* feat(plugins): add plugin scorecard, updates, and sidebar across website and app

Extend the plugin registry wire contract with optional Health, Review, Capabilities, Updates history, author profile, sponsor funding, compatibility, and custom action link fields so users can evaluate plugin maintenance and review findings before installing without false-safety defaults.

Separate neutral plugin capabilities from review caveats so legitimate access disclosures never lower safety signals, use progressive disclosure for technical inspection details, and omit review semaphore bars when a listing has no review payload.

* fix(plugins): gate scorecards on host capability and widen scorecard wire enums

Add server_info.features.pluginRegistryScorecards so older daemons show an update-host notice instead of a false baseline-review message, show a loading skeleton on Scorecard and Updates while detail fetches, widen health grade and review status wire schemas to strings so future registry values never hide listings on older daemons, and omit review dots on related cards when no review summary is present.
2026-12-01 15:50:45 +07:00
Mohamed Boudra 5b99e6699c feat(sync,app): add optimistic overlays to SyncStore for immediate queue UI (#11566)
Queueing, cancelling, and promoting messages waited for a daemon round trip and follow-up agent.queue.update before updating the queue track, leaving a noticeable gap during uploads or over slow links.

Layered uncommitted optimistic overlays onto SyncedStoreRegistry keyed by partition so every subscriber sees pending writes immediately without mutating authoritative views or SyncPersistence. Committed overlays settle without extra requests when authoritative state already matches, or reconcile across one causal cursor catch-up so neither flashes nor ghost rows occur. Also flush pending agent.queue updates ahead of queue RPC responses on the server and remove the ad-hoc WeakSet hide workaround in AgentQueueModel.
2026-12-01 15:45:00 +07:00
Mohamed Boudra 9626465912 Run Hub manual triggers from the CLI with paseo hub run (#11408)
* feat(cli): run Hub manual triggers with paseo hub run

Starting a manual.run trigger meant hand-writing a curl request with a
project slug, actor, delivery key and a space-separated input string.

`paseo hub run <trigger> [prompt]` sends that request with the stored
Hub login or an API key. It rejects inputs Hub would silently read as
prompt text, lists declared inputs when Hub rejects them, and asks for
missing ones in a terminal.

* docs(cli): note Hub run key scopes and prompt contents

* fix(cli): close Hub run gaps for unchecked inputs, expired logins, and retries
2026-12-01 15:34:43 +07:00
Mohamed Boudraandjl97mcad 40a8d9bdd2 perf(app): stop re-rendering the sidebar on agent updates that change nothing it shows (#11565)
Three causes made one agent update cost work across the whole sidebar:

- useSidebarWorkspacesList returned a new object on every render. The
  sidebar model lists it as a dependency of its context value, so any
  render of SidebarModelProvider re-rendered every sidebar surface, even
  when no workspace entry changed.
- With two or more running agents in one workspace, each usage update
  bumps updatedAt and makes another agent the workspace's latest. The
  activity index then gave the workspace a new entry time, so its row
  changed on every update and the timestamp kept showing "now". An
  updatedAt bump now keeps the time the workspace entered its status;
  an attention event still sets a new one.
- Every update rewrote the pending permissions map, even when the
  agent's permissions were unchanged.

Add an opt-in Playwright measurement (npm run test:e2e:agent-update-cost)
that drives mock agents on 400 seeded agents and records renderer CPU,
task time, React commits, and per-component renders per agent update.

Co-authored-by: jl97mcad <56251999+jl97mcad@users.noreply.github.com>
2026-12-01 15:26:01 +07:00
Mohamed BoudraandMariotaku 576a1430a0 perf(app): move the tool-call shimmer thirty times a second, on the ring's frames (#11564)
The shimmer on a running tool call's label moved on every display frame,
so a chat with a running tool call held the window at 60 frames a second
(120 on a 120 Hz display) for as long as the call ran.

The shimmer now steps thirty times a second on the same grid as the status
ring, so the two share frames:

- indicator-motion/steps.ts owns the grid: one step every 1000/30 ms.
- A shimmer pass is the whole number of steps closest to its smooth
  length, so the band and speed change by at most half a step.
- On web, a loop with its own phase starts at the current grid step.
- On native, the shimmer rides the shared indicator clock with its own
  phase instead of starting a clock of its own on a different frame.

Closes #5429, closes #7559, closes #3971

Co-authored-by: Mariotaku <830358+mariotaku@users.noreply.github.com>
2026-12-01 15:25:52 +07:00
CL KaoandMohamed Boudra 4e31842453 feat(desktop): add colored browser profiles with per-tab switching and Settings management (#10357)
* feat(desktop): add colored browser profiles with per-tab picker and Settings management

Co-authored-by: Mohamed Boudra <boudra.moha@gmail.com>

* Fix browser-profiles E2E menu placement waits and Settings nav selector

* Allow switching browser profiles anytime and polish toolbar and Settings UI

- Remove the first-load profile lock: drop NavigationPhase, retirePristineGuest, trackBrowserGuestCommits, the paseo:browser:retire-pristine IPC, and the read-only locked badge. Picking another profile on any tab replaces the webview under the new partition and reloads the current URL in that profile's session.
- Enable horizontal flip on MenuFlyout so submenus near the right edge open to the left instead of overlapping their parent menu.
- Align ProfileSelector's inline create page with WorkspaceLabelCreatePage (single-row swatches, MenuHint errors, no redundant header label) and simplify its tooltip to the profile name.
- Polish Settings > Chat & panes > Browser profiles: align custom rows' kebab triggers on the card's trailing rail with Edit, Clear data, and Remove inside the menu; use Field error styling and default FormTextInput sizing in the profile editor modal; tighten UI copy.

* Standardize tinted IdentityIconBadge primitive and adopt in browser profiles

* Resolve rebase duplications with main (#11490) and use getBrowserRecord

* Address review findings: clear host partitions with Default, retire removed slugs, wait for Metro port close, and align label chip tint

---------

Co-authored-by: Mohamed Boudra <boudra.moha@gmail.com>
2026-12-01 14:46:41 +07:00
Mohamed Boudra 0b5b9b5111 Warn when a host's daemon key changes, and keep clients out of daemon state (#11452)
* fix(app): warn and clear the saved password when a host's daemon key changes

A pairing link for a saved host ID with a different daemon key was treated
like any other route change. On the same relay it overwrote the saved key;
on another relay it added a second relay connection to the same host. Both
kept the host's saved password, so the app sent it to whichever daemon held
the new key.

A host now holds one daemon key. Approving a new key drops every relay
connection to the old key and clears the saved password. The confirmation
sheet tells the three cases apart: a new host, a new route to a saved host
(shown with the saved host's label), and a changed key, which shows a
"Host identity changed" warning with the saved and new fingerprints and a
destructive "Replace host identity" action.

* fix(server): refuse client file access to daemon state in $PASEO_HOME

The file service scoped each request to a cwd the client chose, so any
client, including a scoped one, could name $PASEO_HOME (or `/`) as its cwd
and read local-credential, daemon-keypair.json, config.json, and host links,
or edit them.

Every file RPC (read, stream, list, watch, write, create, rename, duplicate,
delete, download token) and directory suggestions now refuse paths that
resolve into $PASEO_HOME after `..` and symlinks resolve. Inside it, the
managed worktrees root, uploads/, paseo-attachments/, and
desktop-attachments/ stay readable: worktrees live there by default, and the
app reads pasted uploads and assistant images back through the same file
read path.

* fix(server): keep plans in $PASEO_HOME readable from chat links

Agents write plans to ~/.paseo/plans and users open them from chat links. The daemon-state allowlist missed that directory, so those previews were refused.

* docs(security): rewrite new SECURITY.md sections in plain English

* fix(server): let owners read non-secret daemon files while blanket-banning secrets

* fix(server): also block dot-prefixed atomic temp files for daemon secrets
2026-12-01 14:40:44 +07:00
paseo-bot[bot] bc626e838d fix(omp): show Fast in the draft composer (#11553)
OMP returned an empty list of draft controls even when the live session exposed Fast. Read the native setting from a temporary session so users can choose Fast before the first prompt.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-01 07:12:50 +00:00
Kogeki 24a2e8f07c fix(app): tighten plugin row height estimate and ignore hidden rows in web virtualizer (#11538) 2026-12-01 06:42:59 +00:00
809650f0de fix(gitea): detect WIP/draft PRs and avoid misreporting CONFLICTING (#11545)
* fix(gitea): detect WIP/draft PRs and avoid misreporting CONFLICTING

* Match Gitea draft fallback to forge defaults

---------

Co-authored-by: jerry <jerry@codevai.cc>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-01 06:13:10 +00:00
paseo-bot[bot]andnonononull 753947a118 fix: 协调 Codex 启动与消息发送的超时期限 (#11547)
Co-authored-by: nonononull <230730833+nonononull@users.noreply.github.com>
2026-12-01 05:42:49 +00:00
Mohamed Boudra 6fffbb8c18 feat: unify and persist agent message queues on the daemon (#11424)
* feat(server): add durable agent message queue store

Define the AgentMessageQueueStore interface along with atomic per-agent JSON and in-memory adapters and shared contract tests.

This is the persistence foundation for unifying human and agent message queues behind a SQLite-ready store boundary. Withdraw and promote return atomic discriminated outcomes inside the per-recipient lock so callers avoid racy pre-reads against active dispatches.

* feat(server): keep queued agent messages across daemon restarts

Queued messages lived in memory. A crash lost them, a restored finish
subscription then reported a child that never ran its task, and a clean
shutdown forced a flush into busy agents and swallowed the failures.

The daemon now saves a message before acknowledging it, leaves the queue
in place on shutdown, and checks the recipient's history after a crash
before sending an interrupted dispatch again.

Behavior changes:
- A provider that refuses to start a turn no longer drops the message. It
  stays queued and the queue is held, because retrying alone would be
  refused again and add the prompt to the history each time. The sender's
  finish notice waits until the message is delivered.
- Retrying a queued send with the same messageId is acknowledged at once
  instead of blocking until delivery.

Refs #8436

* feat(protocol,server,client): add agent message queue RPCs and client sync

Expose the daemon's durable per-agent message queue over the session protocol so clients can hydrate, observe live updates, withdraw, and promote queued messages without maintaining a local queue.

- Keep queue updates opt-in via session.events.set_subscription and legacyWantsEvent=false so older clients never receive unknown frames.
- Sequence per-agent queue broadcasts on the session so out-of-order storage reads cannot overwrite newer queue state, while still publishing empty lists when an archived or deleted agent's queue is cleared.
- Ignore AbortError on withdrawn queued dispatch promises so user or lifecycle withdrawals do not log spurious run errors.

Refs #8436, #9023

* feat(app): show the host's message queue above the composer

The app kept its own queue and sent it when it saw the agent stop. A
reload lost the queued messages, nothing was sent with the app closed,
and other clients and agent senders could not be seen. The host now owns
the queue; the app only lists it and asks the host to withdraw or send a
row.

Behavior changes:
- Stop leaves queued messages paused instead of sending them.
- Sending a message directly (steer or interrupt) delivers the queued
  messages ahead of it.
- Hosts without the agent message queue have no Queue action, and a
  "queue" send behavior interrupts.

Edit restores uploads as references to the files the host holds, so it
works after a reload or from another device without uploading again.

Refs #8436, #9023

* fix(app): keep the composer on screen with a long message queue

The queue list had no height limit and could not shrink, so enough rows
pushed the message input and Stop past the bottom of the window with no way
to scroll back. The rows now scroll in a capped frame that gives up height
before the input does. The frame is a View because the web build drops
Unistyles styles on the shared ScrollView.

Also keeps row icons from being squashed by a long sender name, puts row
text on the composer's text rail, and focuses the input after Edit.

* fix(server): set aside a corrupt agent queue file instead of failing startup

One unreadable file under agent-queues/ stopped the daemon from booting.
It is renamed so it can be inspected, a warning is logged, and every other
queue loads.

* feat(protocol,server,client): queue a provider switch behind a running turn

A switch staged mid-turn relied on the app holding the prompt until the
turn ended. The host owns the queue now, so the queued message carries the
target provider and settings and the host switches when its turn comes.

The queued switch divides the queue: nothing ahead of it moves to the new
provider and nothing behind it runs on the old one. A switch that fails
keeps the message and holds the queue.

The switch request's new fields are optional. The client refuses to send a
queued switch to a host without the message queue, which would otherwise
drop the field and switch at once.

Refs #8436, #9023

* test(server): cover a queued message the timeline already holds after a crash

* feat(app): queue a staged provider switch with its message

A prompt sent mid-turn with a staged switch goes to the host's queue with
the switch. Its row names the target provider, and Edit stages the switch
again.

Edits to the target's settings after queuing apply to the next message,
not to the queued one.

Refs #8436, #9023

* fix(app): steer instead of interrupting on a host without a message queue

A "queue" send behavior fell back to "interrupt" on an older host, which
killed the running turn the user meant to wait for.

* fix(app): cap composer input independently of dock queue track

ComposerViewportContent previously applied the 0.6x inline editing cap to the entire composer slot, including ComposerQueueTrack. On compact phones after keyboard open/close, restoring an attachment pill grew MessageInput enough to collapse the queued message list to ~10px.

Bound the outer dock slot to the full viewport capacity, move the 0.6x inline cap onto ComposerInputCap around the input box, and cap compact queue rows at 140dp so ~2 queued rows stay usable alongside a restored image pill.

* refactor(protocol,server,client,app): add cursor-synced resource primitive for agent queue

Replace the daemon-wide agent.queue.update event subscription and separate
list fetch with a shared cursor-synced resource primitive:

- protocol: defineSyncedResource({ prefix, scope, value }) generates list
  request/response/update schemas with optional subscribe and generation/seq
  sync cursors; remove agent.queue.update from SessionEventSubscriptionSchema.
- server: daemon-scoped SyncedResourceSource + handleSyncedResourceListRequest
  track per-scope monotonic seq, answer matching cursors with mode: unchanged
  without reading, and emit scoped updates only to active subscribers.
- client: SyncedResourceRegistry ref-counts one server subscription per
  (prefix, scopeKey), retains cursors in a bounded LRU cache on release, and
  resumes with afterSeq on reconnect or re-focus.
- app: synced-resource model and useSyncedResource hook gate subscriptions on
  panel visibility and host features; agent-queue composes on top for withdraw,
  promote, and per-row busy guards.

* fix(protocol,client): keep synced resource descriptors free of zod

Split the zero-Zod SyncedResourceDescriptor and AgentQueueResource descriptor
out of @getpaseo/protocol/messages so @getpaseo/client and thin CLI commands
do not pull messages.ts or zod into the static startup graph.

* refactor(protocol,server,client,app): replace synced-resource with storage-agnostic sync library

Replace the whole-snapshot synced-resource layer with a storage-agnostic
cursor-sync protocol and library across protocol, server, client, and app:

- protocol (src/sync/): zero-Zod descriptors (defineSyncStream,
  defineSyncCollection, AgentQueueCollection) and pure zod-aot schemas with
  nested args, { epoch, afterSeq } cursors, mode: snapshot | changes deltas,
  tail/after/before paging, and per-subscription prevSeq on updates.
- server (server/sync/): SyncBackend interface for in-memory or durable
  backends, handleSyncRequest (authorize, attach-before-read, live buffering,
  per-session projectResponse/projectLive, prevSeq stamping), shared
  VersionedCollection (reused by directory-sync), and bounded-LRU lazy-diff
  createMemoryCollectionBackend. Rewire agent.queue onto agent.queue.sync.*.
- client (src/sync/): SyncedStoreRegistry with single subscribe()->unsub API
  (no .release()), ref-counting, real delta merging, gap/epoch catch-up loops,
  backward loadOlder() paging, exponential backoff with reconnect recovery,
  and pluggable SyncPersistence.
- app (src/sync/): thin useSync / useSyncCollection hooks gated on
  useRetainedPanelActive() and host features; slim agent-queue to queue
  commands and busy guards.
- End-to-end proofs covering production agent.queue, a chat timeline over
  both memory and durable node:sqlite (restart epoch survival, paging, chunks,
  rewinds, gap recovery, cold-start persistence), and a filtered agent
  directory (normalized keys, tombstones, per-session filtering without false
  gaps, LRU eviction, backoff).

* fix(server): clear dirty flag before reading in memory collection backend

Clear partition.dirty before awaiting options.read() (restoring it on error)
and loop in read() while dirty so a mutation arriving during an unsubscribed
read cannot leave the cached partition stale.

Also add a real-browser Playwright test in composer-queue.spec.ts verifying
that switching away from a retained agent tab and returning catches up on
queue changes made while hidden.
2026-12-01 12:41:02 +07:00
Mohamed Boudra af36a85a8f Share workspace services through tunnel providers and remove the service proxy (#11490)
* feat(scripts): share workspace services through tunnel providers

Workspace services now show their real address, http://localhost:<port>,
and you can expose a running service at a public URL by picking a tunnel
provider from the Scripts menu. The *.localhost friendly-URL proxy is
removed.

The proxy shared the daemon's HTTP server, so service WebSocket upgrades
were handled twice and dev servers lost HMR (#638). Tunnel providers
(#11036) already give a public URL with one owner per exposure, so the
proxy no longer earns its upgrade routing, host classification, and
config surface.

daemon.serviceProxy and PASEO_SERVICE_PROXY_* are now ignored with a
startup warning instead of failing startup (COMPAT(serviceProxyRemoved)).
Script payloads keep the legacy proxy URL fields on the wire so older
clients still parse them. PASEO_URL and PASEO_SERVICE_<NAME>_URL now
point at http://localhost:<port>.

Closes #638

* fix(scripts): let the daemon open workspace service tunnels

The app opened service tunnels with the generic tunnel RPC and a fixed
127.0.0.1 target. Two things broke:

- v0.18 daemons already advertise tunnelProviders, so the app showed the
  tunnel picker there, but those daemons never report a script's tunnel or
  close it when the service stops. The tunnel ran with no way to see,
  copy, or stop it.
- A service that listens only on ::1 got a tunnel to 127.0.0.1, so the
  public URL failed while health showed the service as healthy.

The daemon now owns the workflow through workspace.script.tunnel.open and
workspace.script.tunnel.close, gated on a new workspaceScriptTunnels
feature. It probes which loopback address the service accepts, and it
builds the exposure ID and slug, so clients no longer construct them.

* test(server): drop removed service proxy constructor slots

Removing the serviceProxy and serviceProxyPublicBaseUrl parameters shifted the positional VoiceAssistantWebSocketServer arguments in four test harnesses, so providerSnapshotManager and the push sender landed in the wrong slots. The runtime store also goes back to storing entries as given, since port is optional and every reader checks its type.

* fix(scripts): show a service tunnel as an address of its service

The Scripts menu drew the tunnel as a full menu row with its own icon,
so it read as a second service. It now sits on the host rail under
localhost:<port>: "Tunnel ›" when there is none, one host row with
Open, Copy and Stop when ready, and one status row while connecting or
failed. The full URL, provider and errors move into tooltips.

The provider picker lists names only. An unavailable provider shows
"Unavailable", and its reason and fix sit behind an info tip.

Submenu flyouts now open on the left when the right side has no room,
so the picker no longer covers a menu at the right edge of the window.
The side is chosen once, when the flyout opens. useMenuSubTrigger gives
custom rows the same anchor, hover intent and navigation as
MenuSubTrigger.

The compact sheet stops repeating the tunnel URL under Copy.

* fix(scripts): show tunnel details to touch users

On touch, the tunnel host row tooltip now opens on press, and the compact
sheet notes a temporary tunnel URL next to the host.
2026-12-01 11:32:24 +07:00
c3c86b9d18 perf(app): turn the status ring thirty times a second, not once per display frame (#11474)
A window is composed and presented again every time something in it
moves. The ring on a running workspace turned with the display, so a
visible ring held the whole window at 60 or 120 frames a second for as
long as any agent ran, even while the chat on screen was idle. On macOS
that work lands in WindowServer; on Android in RenderThread.

The ring now takes 27 positions per 900 ms turn, which is 30 a second.
Each is a position the smooth turn passes through, 1.2 px apart on the
12 px ring. On web the keyframes use steps(27), and the compositor draws
a frame only when the step changes. On native the shared clock holds its
position at each step; a view whose transform did not change is not
invalidated, so nothing is drawn between steps.

The native clock starts on a frame and advances whole frames, so a step
that is a whole number of frames long would turn over exactly on a
frame, and rounding would pick the side. Each step turns over an eighth
of a step early, which is between two frames at 60, 90 and 120 Hz.

The tool-call shimmer still moves every frame, so a chat with a running
tool call in view draws at the display's rate as before.

Refs #5429, #7559, #3971

Co-authored-by: Wanno Drijfhout <git@wanno.eu>
Co-authored-by: luke <luopeihuan@gmail.com>
Co-authored-by: Daniel JB Clark <djbclark@gmail.com>
2026-12-01 11:00:05 +07:00
Mohamed Boudra 5140065373 fix(app): send with hardware-keyboard Return on iPhone (#11537)
The composer's Return key command was registered only for the iPad
idiom, so an iPhone with a keyboard attached inserted a newline instead.
A key command runs only for physical key presses, so the on-screen
keyboard's Return needs no gate.
2026-12-01 10:54:50 +07:00
Mohamed Boudra 0f3ed9118b fix(app): stop Cmd/Ctrl+click from entering sidebar select mode (#11472)
Holding Cmd to preview sidebar jump badges or rolling off shortcuts like Cmd+Tab or Cmd+B before clicking a workspace row accidentally entered sticky multi-select mode. Outside select mode, only Shift+click (without Cmd/Ctrl) and the row menu now enter select mode; once select mode is active, Cmd/Ctrl+click and plain clicks continue to toggle rows and Shift+click continues to adjust ranges.

Also make readPressModifiers trust explicit boolean modifier flags on non-touch pointer events instead of ORing with the held-key tracker, so a swallowed key-up cannot cause phantom modifier clicks on desktop while keeping the fallback for native and touch-synthesized presses.
2026-12-01 10:45:24 +07:00
paseo-bot[bot]andStelath 66b57ed3b3 fix(pi): keep the turn open when an extension sends context before Pi answers the prompt (#11533)
Pi answers the prompt RPC only after extension preflight. A custom message an
extension sends from before_agent_start therefore reaches Paseo before the
response and before agent_start. The adapter treated that message as an
extension command's output and completed the turn. The run then continued
without a turn, and Pi's echo of the prompt arrived without the client message
ID, so the chat showed the user's message twice.

A custom message no longer completes a turn whose prompt is unanswered. Once Pi
answers, the adapter asks Pi for its state, as it already does for slash
commands, and completes the turn only if no run is starting.

Co-authored-by: Stelath <25530613+Stelath@users.noreply.github.com>
2026-12-01 03:13:28 +00:00
b9bd2a2b05 fix(acp): report thinking changes returned by mode selection (#11478)
* fix(acp): report thinking changes returned by mode selection

* Verify ACP mode changes through the daemon

---------

Co-authored-by: Shane Su <shane.su@maiscrm.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-01 03:12:52 +00:00
748972b982 fix(antigravity): fail ACP turns ending with silent executor errors (#10885)
* fix(antigravity): fail ACP turns ending with silent executor errors

* fix(antigravity): narrow turnEnd and keep queued follow-ups after a failed one

AcpTransformer.turnEnd now returns a ProviderError and no longer exposes the
last wire chunk, so ACP chunk boundaries stay inside @getpaseo/plugin. The
Antigravity provider matches the error frame on the whole assistant message.

A tool call update now clears lastAssistantMessage. When a follow-up reply
fails while later follow-ups are queued, Paseo reports it as a notice and
sends the rest instead of dropping them.

Refs #10776

Co-authored-by: luke <luopeihuan@gmail.com>

---------

Co-authored-by: V <vecsat@foxmail.com>
Co-authored-by: Mohamed Boudra <boudra.moha@gmail.com>
Co-authored-by: luke <luopeihuan@gmail.com>
2026-12-01 10:00:23 +07:00
paseo-bot[bot]andPatrick Motard 1f6b2493f0 Load project resources in trusted Pi chats (#11527)
* fix(pi): trust project resources for user sessions

* fix(pi): respect workspace trust for project resources

* test(agent): cover trusted lazy resume

* fix(agent): fail explicitly on workspace-trust lookup errors

Swallowing lookup failures and defaulting to untrusted hid infrastructure
errors behind a degraded session instead of surfacing them, per the
server's fail-explicit error-handling convention.

* refactor(agent): name resume options type

* Keep Pi project approval on trusted session launches

Co-authored-by: Patrick Motard <motard19@gmail.com>

* Share Pi approval arguments across create and resume

* Approve project resources for custom Pi providers

---------

Co-authored-by: Patrick Motard <motard19@gmail.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-01 02:43:10 +00:00
paseo-bot[bot]andStelath 2575621974 fix(pi): wait for the prompt response while Pi runs extension preflight (#11525)
Pi answers the prompt RPC only after extension preflight. An extension can ask
the user a question or compact the session there, which can take minutes. The
adapter gave the request the control-plane deadline, failed the turn with
"Pi RPC request timed out phase=prompt", and Pi then ran the prompt anyway:
the reply arrived outside any turn and the user's message appeared twice.

The prompt request now waits for a response, process death or close, as the
compact request already does. Stop still interrupts a prompt that never
answers.

Co-authored-by: Stelath <25530613+Stelath@users.noreply.github.com>
2026-12-01 02:42:41 +00:00
paseo-bot[bot]andphanthawas.jir c51431fc98 fix(server): list commands without starting an archived agent's runtime (#11521)
A timeline read loads an archived agent as a history session. The list
commands handler checked archivedAt only for agents that were not loaded,
so it called listCommands on that session and started the provider
process. Read the stored record for loaded agents too.

Co-authored-by: phanthawas.jir <phanthawas.jir@dappmaker.co.th>
2026-12-01 02:12:51 +00:00
paseo-bot[bot]andWaterChen 7454db9b0d Show when a worktree archive is pending (#11519)
* fix(app): show a worktree archive as pending while the host checks it

Since #9625 an archive of a worktree first asks the host for its checkout
status, then warns or archives. The row only showed its pending state once
that answer arrived, so on a slow host the press looked like it did nothing
and people pressed again.

runWorkspaceArchiveAttempt already tracks the in-flight attempt per
workspace. Make it observable and have the sidebar rows and the git actions
treat it as archiving, so the pending ring and disabled state show from the
press until the archive starts or the warning is cancelled.

Closes #10366

* Update archive pending tests for the force option

Co-authored-by: WaterChen <chenxxyy299@gmail.com>

---------

Co-authored-by: WaterChen <chenxxyy299@gmail.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-01 01:13:12 +00:00
kotusenka c00398cd10 fix(server): keep scheduled worktree runs in their project (#10378) 2026-12-01 01:12:44 +00:00
paseo-bot[bot] 6e1dbe31af fix(server): build the OpenCode tool manifest only when it is requested (#11518)
Since #11189, one daemon config reload runs the tools, mcp.injectIntoAgents
and browserTools.enabled listeners, and each one rebuilt the full agent tool
manifest on the main thread. A reload that turns on browser tools blocked the
event loop for 30-78 ms on CI runners, and the password-protected config
reload gate (< 50 ms) in plugin-paseo-api.e2e failed on main and on PRs.

The manifest is only read when OpenCode asks the bridge for the unbound tool
list. The provider runtime now passes the bridge a catalog factory; the bridge
builds the catalog on the first request and reuses it until the factory is
replaced. A config change now only swaps a closure.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-01 00:36:44 +00:00
SunicemanandShane Su 0437922aff fix(app): preserve filesystem roots in Explorer paths (#11206)
Co-authored-by: Shane Su <26364206+suniceman@users.noreply.github.com>
2026-11-30 23:42:42 +00:00
paseo-bot[bot] eaa4589e07 fix(server): keep GitHub check details when a job log fails (#11509)
A job log is optional context. Keep the annotations and failed jobs available when GitHub CLI cannot return one of the logs.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-30 22:42:42 +00:00
paseo-bot[bot] 4c480c9afe Show when an HTML file is too large to preview on desktop (#11504)
* fix(app): explain when an HTML file is too large to preview

Electron leaves the preview blank when the encoded document URL exceeds its 2 MiB limit. Show the existing file size message before trying to load a URL that Electron will reject.

* fix(app): theme the oversized HTML preview message

---------

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-30 21:42:39 +00:00
paseo-bot[bot] 39709a4a97 test(website): wait for hydration before focusing the Pro seat help (#11508)
Hydration scrolls the window back to the top. When the Hub page hydrated
after the test had scrolled the Pro card into view and focused its help,
the tooltip stayed open but off screen, and toBeInViewport failed on
webkit in main CI run 46454713101.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-30 21:21:03 +00:00
SunicemanandShane Su 85b68cb062 Load GitHub check annotations and workflow jobs with GET (#11476)
Co-authored-by: Shane Su <26364206+suniceman@users.noreply.github.com>
2026-11-30 21:12:42 +00:00
Matchy d399c82f51 fix(server): keep plugin entries other writers put in config.json (#11501)
The daemon owns plugin source entries and `paseo reload` does not pick up
edits to `plugins`, so its in-memory copy goes stale when config.json is
edited while it runs. Every plugin operation (install, enable, disable,
update, remove) then wrote that whole stale map back to disk. A hand-added
entry was silently deleted by the next operation on any other plugin, and
an entry removed by hand was written back. Local directory plugins hit
this most, since they are the ones people add by editing config.json.

Persisting a plugins patch now applies only the entries that changed
relative to the in-memory copy onto the plugins read from disk. Reload
still ignores plugin edits; they now survive until the next restart loads
them, as docs/plugins.md describes.

Verified with new DaemonConfigStore tests covering a hand-added entry, a
hand-removed entry, and removing one plugin while another sits on disk;
all three failed before the change.
2026-11-30 19:42:40 +00:00
SunicemanandShane Su 9a520f0adc Keep attached plugin slash commands out of the agent conversation (#11483)
Co-authored-by: Shane Su <26364206+suniceman@users.noreply.github.com>
2026-11-30 17:12:44 +00:00
Mohamed Boudra 81357c6e7b fix(app): keep the Restoring screen up until a restored workspace is ready (#11486)
Two separate races let the restore gate drop early.

The daemon sends the workspace_update before the restore reply, but the
app batched workspace updates to the next animation frame. The reply
resolved first, the route never saw "restoring with the workspace
present", no post-restore handoff started, and the chat mounted while it
was still loading. Buffered workspace updates now flush when any reply
arrives, so a caller that reads the store after its reply sees the update.
Unsolicited updates keep their per-frame batching.

The handoff released after a fixed three frames, but the desktop tab row
shows tabs only after RN-web onLayout measures every label, which runs
through ResizeObserver and setTimeout and can land later. The gate then
dropped onto an empty tab strip. On-screen chrome behind the gate can now
hold the reveal; the tab row holds until its measured track matches its
labels. The 2.5s handoff timeout still bounds the hold.
2026-11-30 23:56:14 +07:00
Mohamed Boudra 95cc11ab7b Put agent tools behind one Enable tools setting with tool groups (#11189)
* feat(server,app): group agent tools under one Enable tools setting

Replace the separate "Enable Paseo tools" and "Browser tools" settings with
one `daemon.tools` configuration: an `enabled` switch plus per-group switches
for orchestration, schedules, PR watching, and browser. Every built-in tool
now declares its group, scope, and daemon permission in one registry, so
native providers and the loopback MCP endpoint filter the same catalog.

Tools are on by default for hosts that never set the legacy injection flag.
Hosts that set `daemon.mcp.injectIntoAgents: false` keep tools off. Legacy
`daemon.mcp.*` and `daemon.browserTools.enabled` are still read when
`daemon.tools` is absent; those shims are tagged COMPAT.

Voice mode now requires tools. When tools are off it refuses with reasonCode
"tools_disabled" and the voice settings page offers a one-click Enable tools
action. Dictation is unaffected.

* fix(app): keep the host's tool groups when setup is shown again

The Orchestration step started its tool groups from the defaults and wrote
all four on Continue, so a host with Browser on or Schedules off lost those
choices when the user opened setup again. The groups sit in a collapsed row,
so the user never saw the switches. Setup now shows the host's groups and
writes only the groups the user changed.

The compact-layout setup test assumed the host starts with tools off; it now
turns them off first, since tools are on by default.

* fix(server): keep wire schemas out of the configuration entry point

tools-config.ts imported the default tool groups from protocol/messages,
which pulled every wire schema into @getpaseo/server/configuration. The
group constants now live in the Zod-free protocol/tool-groups module, and
messages re-exports them.

The WebSocket server read the config store behind a guard that only
existed for incomplete test stubs. The store is a required dependency, so
the guard is gone and the stubs provide get().

* feat(app): show only the Enable tools switch in setup

Setup is for getting started, so the Orchestration step shows a plain
Enable tools switch next to skills and the CLI. Tool groups stay in
Settings > Tools & prompts. Setup writes only the main switch, so the
groups a host already saved are never touched.

* fix(server,app): let voice mode deliver speak when agent tools are off

Main now delivers a speak-only tool set to an agent in voice mode when
agent tools are off (#11161). This branch refused voice mode in that case
with reasonCode "tools_disabled", which blocked that path.

Voice mode no longer checks the Enable tools setting. The master switch
still removes every built-in and plugin tool, except speak for an active
voice session. The voice settings alert, its Enable tools button, the
"Required for voice mode" hint, and the tools_disabled server capability
are removed.

Also removes a duplicate DaemonClient import that the rebase onto main
left in agent-mcp.e2e.test.ts.
2026-11-30 23:42:56 +07:00
paseo-bot[bot] 93c883a398 test(server): restore the live Codex smoke prompt (#11473)
The smoke test stopped before sending its prompt because it read the retired features property. Check the Plan toggle in session controls to exercise the current provider interface.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-30 16:42:47 +00:00
SunicemanandShane Su d5880784e2 Return the browser URL after creating a GitHub pull request (#11439)
Co-authored-by: Shane Su <26364206+suniceman@users.noreply.github.com>
2026-11-30 16:12:45 +00:00
paseo-bot[bot]andClaude Opus 5.5 5d4a1b4ed7 test(server): give the Windows socket-overflow burst room to finish (#11470)
The socket-overflow restore test stalls the daemon until the PTY has
accepted an 8 MiB burst, with a 10 s limit. On Windows, ConPTY takes
2-6 s for that write on a normal run, and a loaded runner went past
10 s. Wait up to 30 s, and raise the test timeout to 60 s to match.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 15:49:13 +00:00
paseo-bot[bot]andbearyjd e350293d13 fix(app): apply content font size to existing chat messages (#11469)
Existing user text keeps its generated web font class after the theme changes. Subscribe the message text to appearance changes so the open chat can refresh it in place.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: bearyjd <28201062+bearyjd@users.noreply.github.com>
2026-11-30 15:13:02 +00:00
Konrad Karkosz 69563e111b fix(claude): keep the SDK version so Claude Code writes chat titles (#11057)
Paseo clears CLAUDE_AGENT_SDK_VERSION from the Claude process env along
with the parent-session vars. Without it, and with no explicit entrypoint,
Claude Code labels the process a bare `claude -p` run (`sdk-cli`) and never
writes the automatic chat title (`ai-title`) to the transcript. Keep the
version the SDK sets for its own child.
2026-11-30 14:42:41 +00:00
paseo-bot[bot]andOYZH888 8f696db2f2 Fix timeline sync when reopening a cached chat (#11464)
Co-authored-by: OYZH888 <16219422+oyzh888@users.noreply.github.com>
2026-11-30 14:12:43 +00:00
paseo-bot[bot] c9ec9863ba Keep worktrees with uncommitted changes when archiving (#11430)
* fix(archive): keep worktrees with uncommitted changes

Archive used forced Git removal after workspace teardown, even when a file appeared after a clean status check. Check the worktree after teardown and preserve it unless the caller explicitly requests forced removal.

* Remove clean worktrees with initialized submodules

---------

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-30 20:38:31 +07:00
paseo-bot[bot]andSleroq 24ceb52147 fix(app): hide file manager action for remote workspaces (#11463)
Co-authored-by: Sleroq <hireme@sleroq.link>
2026-11-30 13:13:08 +00:00
paseo-bot[bot] 4c4b384c7f test(app): verify how the sidebar list settles after archive (#11461)
The final row returns to its usual gap even when its travel is shorter than the toast. Let the toast expire on the normal browser clock and verify that the row moves through an intermediate position before it settles.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-30 13:12:42 +00:00
Mohamed Boudra 1a606451cd perf(app): keep running-turn indicators off the main thread (#11456)
* perf(app): keep running-turn indicators off the main thread

The six-dot loader, the status ring and the tool-call label shimmer run for
as long as an agent works. Each of them was driven per frame from the thread
that runs React: a requestAnimationFrame loop for the loader on web, a
text-clipped background animation that repainted the label every frame, and
Reanimated shared values that commit a shadow tree every frame on native.

Hand each animation to the platform's animation engine once instead:

- Web: Web Animations API loops over transform and opacity, carried by the
  compositor. No script, style or paint per frame. CSS @keyframes are not
  used because React's root animationiteration listener makes Chromium wake
  the main thread around every cycle of every CSS animation.
- Native: React Native's Animated native driver, with a never-slowing decay
  as a frame-exact clock. The loader's six steps come from a timer aligned
  to step boundaries, not a frame callback.
- One motion policy for all three: no motion under reduced motion, in a
  hidden retained panel, or in the background; the indicator draws its
  resting frame instead.

The look, cadence and phase-sharing of the indicators are unchanged.

Closes #4634

* fix(app): compose the native ring's turning style at render

The module-scope guard for Unistyles style reads flags any `*styles`
property read in a module initializer. Keep only the transform at module
scope and combine it with the rotator geometry in the component.
2026-11-30 19:56:33 +07:00
KiritoXDone 23934841f0 fix(cli): preserve snapshot metadata in agent listings (#11423) 2026-11-30 12:42:54 +00:00
SunicemanandShane Su d2d4105366 Count an errored WebSocket handshake once during reconnect (#11428)
Co-authored-by: Shane Su <26364206+suniceman@users.noreply.github.com>
2026-11-30 11:42:52 +00:00
SunicemanandShane Su 37cb22dac8 Allow slow provider discovery to finish in project suggestions (#11438)
Co-authored-by: Shane Su <26364206+suniceman@users.noreply.github.com>
2026-11-30 11:13:43 +00:00
taemin HAandCodex 397d1e14d6 fix(app): Keep chats synchronized after online connection replacement (#11029)
* fix(app): Keep chats synchronized after online connection replacement

Initialize each new timeline owner from its bound client's connection
state. An adaptive transport switch can replace the client while the host
stays online, so the connection-state effect does not otherwise rerun.

Cover the online replacement with a real browser/daemon regression and
include before/after QA evidence.

Co-Authored-By: Codex <noreply@openai.com>

* test(app): Harden online connection replacement coverage

Advance the browser clock while awaiting real heartbeat and probe cycles
to avoid minutes of wall-clock waits. Check continuous connectivity,
hidden-chat catch-up, and prompt dismissal of the reconnect indicator.

Keep exact subscription matching as the shared helper default. Record
RED and GREEN evidence from byte-identical final test sources.

Co-Authored-By: Codex <noreply@openai.com>

---------

Co-authored-by: Codex <noreply@openai.com>
2026-11-30 11:13:13 +00:00
Nathan McNulty d193e419e9 fix(copilot-usage): allow negative remaining quota on overage (#11006) 2026-11-30 11:12:42 +00:00
Galaxy RoamingandMohamed Boudra bd20e3fe98 fix(app): keep Markdown table <br> line breaks inside their cells (#9587)
* fix(app): keep Markdown table <br> line breaks inside their cells

* fix(app): scan HTML table wrappers in a single forward pass

* fix(app): preserve tag-only line prefixes before wrapped tables

* fix(app): pad <br> U+2028 separator on both sides for flanking emphasis

* build(app): rebuild the Markdown web parser with table cell line breaks

The engine moved into the repository, so the table cell change now lives
once in cpp/parser/MD4CParser.cpp and web gets it from a rebuilt WASM
instead of a second TypeScript pass over the parsed tree. Built with
emsdk 4.0.10; a build of the unchanged sources parses every Markdown file
in the repository the same as the previous artifact.

The parser now autolinks a bare URL after a table cell break, as it does
the first one. Sources without `<br` skip the extra table parse.

Co-authored-by: Ouyang Xingyuan <galaxyroaming@qq.com>

* fix(app): keep table cell line breaks when copying a table

A table cell can now hold a line break, but the copy paths wrote it as a
newline, which splits the Markdown row. Web selection copy and the native
serializers write it back as `<br>`. The native row accessibility label
joined the two lines into one word, so it now reads them apart.

---------

Co-authored-by: Mohamed Boudra <boudra.moha@gmail.com>
2026-11-30 17:16:48 +07:00
paseo-bot[bot]andminamorl 39eaba6181 fix(server): show Claude Code system notifications instead of dropping them (#11419)
Claude Code reports things the user needs to know through
`{"type":"system","subtype":"notification"}`, for example that a requested
Code Mode did not start. The Claude provider had no branch for that subtype,
so the text only reached a trace-level raw event.

Map it to the existing timeline `notification` item (warning for `high` and
`immediate` priority, info otherwise) and log it as `claude.notification`
at warn or info.

Fixes #11241

Co-authored-by: minamorl <minamorl@users.noreply.github.com>
2026-11-30 10:13:05 +00:00
paseo-bot[bot] 63ede58d7d fix(app): keep long multiline drafts responsive (#11418)
The composer laid out the entire draft in a hidden textarea on every edit. Once complete lines establish the height cap and fullscreen threshold, measure those lines and keep the full text in the editor.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-30 10:12:40 +00:00
paseo-bot[bot] 3986e8b808 fix(server): enforce the forge host auth probe deadline (#11411)
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-30 09:43:18 +00:00
paseo-bot[bot] 9fd8921697 fix(claude): show autonomous turns in reopened chats (#11405)
Command discovery can launch Claude before the user sends a message. Start reading each query when it launches so a turn Claude starts on its own reaches the live timeline.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-30 09:42:48 +00:00
paseo-bot[bot] 269fa33491 Close terminal programs on Windows when Restart and close terminals runs (#11398)
* fix(terminal): kill the program tree first on Windows in killAndWait

On Windows, node-pty's kill closes the pseudoconsole at once and kills
the console's processes only after a forked helper reports them.
Closing the pseudoconsole closes the output pipe, and node-pty reports
that as the program's exit. killAndWait therefore saw an exit inside
its graceful wait and skipped the force step added in #11147. The
terminal worker exits right after killAndWait during shutdown, so the
helper's kill never ran and the program kept running after "Restart
and close terminals".

On Windows, killAndWait now kills the program's process tree before it
closes the console. Windows has no graceful signal, and node-pty's own
kill was already TerminateProcess, so no graceful step is lost.

Refs #11134

* test(terminal): end the program before the caller of killAndWait exits

---------

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-30 09:27:42 +00:00
paseo-bot[bot] ebcea47942 Show the latest ACP sessions in Import Session (#10675)
* fix(acp): show the latest sessions in Import Session

ACP peers can return sessions in storage order. Applying the result limit before sorting discards newer sessions before the daemon receives them.

* fix(acp): keep import results when extra pages stall

Once the provider supplies enough sessions, bound the time spent looking for newer ones. Return the rows already collected and close the listing connection when the extra scan ends.

* test(website): check plugin search parameters by name

Native GET form submission and hydrated navigation serialize the same filters in different orders. Verify the term and ranking window in both flows.

* test(server): wait for the watcher before deleting a file

The native macOS watcher starts delivering events after subscription returns. Use the existing liveness canary before removing the file under test.

* fix(acp): start the optional scan budget with the listing

* test(acp): follow the connection that lists sessions

---------

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-30 09:12:49 +00:00
Mohamed Boudra fb9a1644f0 feat(plugins): let plugins read and arrange a workspace's layout (#11328)
Plugins can open, focus, move and close a workspace's panes and tabs, show or hide the Explorer, and read the layout, through a handle available in components, the client entry and commands. Requires Paseo 0.18.3 or later. `openPanel` is deprecated and behaves as before.

Tab closing moved out of the workspace screen into `@/workspace-tabs/close`, so plugin and UI closes share the same unsaved-work and destructive prompts.

Also fixes two problems a plugin's arrangement could reach: a chat in a phone's Explorer overlay never loaded, and a sheet from a hidden workspace was presented over the workspace on screen.

Includes two test-only repairs for CI failures outside this change: an ACP interrupt test with a too-short grace period, and a terminal lifecycle test whose failure message carried no daemon output.
2026-11-30 16:12:12 +07:00
paseo-ai[bot] 93278b217b fix: update lockfile signatures and Nix hash [skip ci] 2026-11-30 09:06:19 +00:00
Mohamed Boudra 5f453a2f74 Switch providers within the same chat on durable SQLite timelines (#11410)
* feat(timeline,agents): owned SQLite timelines and in-chat provider switching

* test: align rebased timeline, ACP reopen, and rewind tests with SQLite history
2026-11-30 15:56:36 +07:00
Mohamed Boudra 01aced8cd2 fix(app): keep uncaught plugin errors from crashing the native app (#11412)
React Native reports an error thrown out of a press handler, timer,
animation frame, or microtask to ErrorUtils as fatal, so one bad plugin
callback terminated a release app. The plugin error boundary only covers
render and effects.

Client bundles now evaluate with a paseo-plugin://<server>/<plugin>
source URL, and a wrapped global handler logs errors whose stack has a
plugin frame instead of forwarding them. Errors without a plugin frame
reach the previous handler unchanged.

Hermes prints an empty source for new Function code and records no
creation site, so the bundle receives a Function that appends a source
URL to code it compiles. Code compiled through eval, globalThis.Function,
or from already compiled code stays unattributed and fatal.

Refs #10978
2026-11-30 15:45:16 +07:00
paseo-bot[bot] 9d994aca9b fix(server): release workspace refreshes after forge CLI timeouts (#11252)
A forge command can ignore the default termination signal and keep its workspace refresh slot occupied. Use a forceful signal at the existing deadline so the refresh can finish.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-30 08:43:35 +00:00
paseo-bot[bot]and김동선 839d45103b Reconnect promptly when the app returns to a stalled handshake (#10348)
* fix(client): reconnect right away when the app returns to the foreground

While the app is hidden the OS blocks the network, so relay retries fail
and the backoff climbs to 24-30s. On returning, ensureConnected({ verify })
either waited for a connect attempt started while hidden to hit its 15s
timeout, or retried after that inflated backoff, leaving the mobile app on
"Reconnecting to host" for 40-60s.

Foregrounding now resets the backoff, and replaces a connect attempt that
has been pending for 3s or more instead of waiting out its timeout.

* fix(client): keep the base retry delay after a foreground reconnect

Use the immediate retry path when replacing a stalled connection attempt.
Arming a retry timer first would raise the backoff even though the
replacement cancels that timer before it fires.

Co-authored-by: 김동선 <88572124+dongsun1@users.noreply.github.com>

* fix(client): keep queued requests during foreground reconnect

A stalled handshake has not sent the queued requests. Replace its transport while the client remains connecting so the new handshake can send them with their existing deadlines.

* fix(client): serialize foreground credential lookup and handshake

Enter connecting before reading credentials so a foreground event shares the active connection attempt. Retire the previous transport before the read so no obsolete socket can disconnect the new one.

* fix(client): time out stalled credential lookups

Keep a single connection attempt from credential lookup through hello. Foreground recovery can replace that attempt, and only the current lookup can install a transport.

* fix(client): retire the connection deadline before retrying

A failed hello already schedules its retry. Clear the ended attempt at the retry transition so its deadline cannot change the error or raise the delay.

* Preserve the handshake timeout after credential lookup

---------

Co-authored-by: 김동선 <88572124+dongsun1@users.noreply.github.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-30 08:42:51 +00:00
Mohamed Boudraandthecardcheat 96fee23fbd Switch Direct connection between Form and URI modes (#11402)
* feat(app): switch Direct connection between Form and URI modes

The Advanced disclosure kept a second copy of the address. Connect read
the Host and Port fields while a tcp:// URI sat in the open Advanced
field, so a blank Host failed with "Host is required" and an edited URI
connected to the old address.

The step now holds one input whose type is the mode. Connect reads only
that input, so a hidden copy cannot exist. Switching modes converts the
input and never fails; an invalid port carries over as text so Connect
reports it. A tcp:// or relay:// address typed into Host moves to URI
mode, where its password and SSL settings count. A pairing link keeps
the Form segment disabled because it cannot be expressed as fields.

URI mode has no Password field, so a rejected password opens an inline
"Password for {host}" prompt, the same as Paste pairing link. URI mode
keeps the Form body's height and the actions sit in the sheet footer,
so Cancel and Connect stay put when the mode changes.

Closes #5495

Co-authored-by: thecardcheat <pitt.joshua.miller@gmail.com>

* fix(app): treat #offer= pairing links in Direct connection as a URI

paseo daemon pair prints an #offer= link next to the relay:// URI.
Pasted into Host it stayed in Form mode and probed the app's web host
as a daemon. All three pairing link formats now share one check.

* fix(app): show the whole Direct connection form on short phones

The compact sheet opened at the shared 65% stop. With Password always
visible and the mode switch above it, the form needs about 485dp of
sheet, so on phones about 690dp tall or shorter the footer covered the
Password field and its eye button. The sheet now opens at 80%.

---------

Co-authored-by: thecardcheat <pitt.joshua.miller@gmail.com>
2026-11-30 15:06:33 +07:00
Daniel JB ClarkandClaude Sonnet 5.5 e31f379d54 perf(desktop): ship precompressed web assets in app-dist (#10635)
The desktop app's Resources/app-dist was copied raw from packages/app/dist,
so the daemon-served web UI first load transferred about 25 MB. The server
already prefers `<asset>.br` / `<asset>.gz` beside an asset (web-ui.ts), but
only the standalone `build:daemon-web-ui` ever created them.

build:desktop now precompresses packages/app/dist after `expo export` and
before electron-builder copies it to app-dist via extraResources (no files
glob excludes .br/.gz). The compression code moves to
scripts/precompress-assets.mjs, shared with build-daemon-web-ui.mjs, with the
same extension list and brotli max quality (about 38 s for the 25 MB bundle;
first load drops to about 4 MB with br, 5.6 MB with gzip).

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-30 14:51:00 +07:00
paseo-bot[bot]andMohamed Boudra f37991f8d4 Reopen ACP chats with a rejected saved thinking level (#10333)
* fix(acp): reopen chats with a rejected saved thinking level

A stale thinking override aborted resume after the provider loaded the session. Preserve the loaded session when the provider rejects a value that its current model no longer offers, so the user can open the chat and select a supported value.

* fix(acp): report the restored model’s thinking level

Restoring the saved model can change the active thinking level before Paseo replays a saved preference. Read the level from the model response so a stale preference falls back to the current model’s setting.

* fix(acp): apply the thinking level from every full settings response

Restoring the saved mode can change the thinking level just like restoring the model. Keep the active level synchronized when accepting the provider’s selectors so resume reports the current setting after either change.

* fix(acp): refresh the thinking level only while restoring a chat

Reading the level from every settings response also changed what the thinking
picker shows after a live model switch. This fix is about reopening a saved
chat, so the read now happens once, after the saved mode and model are
restored. Open chats behave as before; #10336 tracks their picker updates.

---------

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Mohamed Boudra <boudra.moha@gmail.com>
2026-11-30 14:40:52 +07:00
paseo-ai[bot] dbc3983314 fix: update lockfile signatures and Nix hash [skip ci] 2026-11-30 07:18:51 +00:00
paseo-bot[bot]andjsilhan b5f56a70f6 Finish Pi extension prompts when their work ends (#10572)
Closes #10548

Co-authored-by: jsilhan <jan.silhan@bighub.cz>
2026-11-30 14:09:32 +07:00
paseo-bot[bot]andLiebeLee 5ef84c6bc0 Keep workspace controls tappable after dismissing an opening file sheet (#11317)
Closes #11309

Co-authored-by: LiebeLee <27326628+LiebeLee@users.noreply.github.com>
2026-11-30 13:43:39 +07:00
paseo-bot[bot] 1e8bf499af test(terminal): restore AppImage zsh coverage (#11395)
The palette check reads the terminal overrides before building the child environment. Supply an empty override object so the AppImage fixture reaches its shell assertions.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-30 06:43:19 +00:00
paseo-bot[bot] 8849fd06c9 fix(desktop): avoid RPM conflicts with other Electron apps (#11354)
Electron RPMs can contain the same binary at different install paths. Turn off generated build-ID links so their RPMs can install alongside Paseo.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-30 13:39:34 +07:00
paseo-bot[bot]andmonarchmaisuriya 1cd2460a51 Restore finished Claude subagents after reopening (#10848)
Closes #8959

Co-authored-by: monarchmaisuriya <monarchmaisuriya7600@gmail.com>
2026-11-30 13:34:30 +07:00
yz 75abc739e6 Fix header taps scrolling panes to the top on iOS (#11262) 2026-11-30 13:33:06 +07:00
Bhaskaran S 728e09f0bb fix(app): archive closed subagents from 'Archive finished subagents' (#10865)
A child whose runtime was released (status closed) was listed in the
subagent track but treated as not finished, so the button skipped it
silently. Treat closed like idle/error, keeping the background-work and
parent/archived rechecks. Adds regression tests.
2026-11-30 13:29:52 +07:00
Mohamed Boudra cf68bd76d4 fix(server): deliver voice-only speak tool regardless of MCP injection policy (#11161)
* fix(server): deliver voice-only speak tool regardless of MCP injection policy

* fix(server): track HTTP MCP capability separately and validate voice speak before reload close
2026-11-30 13:22:56 +07:00
Mohamed Boudra 7f2ece0556 chore(release): reconcile v0.18.2 (#11393) 2026-11-30 13:15:10 +07:00
Mohamed Boudra f81d433afc fix(app): keep batched user messages on distinct timeline row keys (#11324)
* fix(app): keep batched user messages on distinct timeline row ids

When multiple queued or joined human prompts share a single provider turn, projectAgentMessages emits separate user_message rows with distinct clientMessageIds and the same provider messageId. appendUserMessage and buildCanonicalUserMessage bypassed createUserMessage's clientMessageId ?? messageId precedence by passing id: messageId, producing duplicate React keys in WebStreamViewport mountedHistoryRows.

Prefer clientMessageId over messageId when building canonical user rows, and normalize previously cached or retained rows whose id inherited a shared provider messageId during reconciliation and replica-cache hydration.

* refactor(app): keep legacy user row id heal at replica cache boundary

Pre-fix rows with id === messageId only persist in the replica cache, which already normalizes them on read. Move the helper into replica-cache with a COMPAT tag and remove the unreachable merge-path heal in produceUserMessage.
2026-11-30 13:14:41 +07:00
paseo-bot[bot] a931ac1cd7 test(cli): isolate worktree tests from the launch checkout (#11392)
An explicit daemon endpoint resolves relative paths from the daemon's working directory. Start the test daemon in the fixture repository so the checks exercise that path without reading the launch checkout.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-30 06:13:42 +00:00
paseo-bot[bot] cdfc788946 fix(cli): isolate the usage test from host reports (#11391)
The test daemon inherited settings that let built-in sources discover reports outside its temporary home. Give the usage fixture an explicit base environment so the list and removal assertions depend only on its plugin.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-30 06:13:10 +00:00
paseo-bot[bot]andShane Su 8be985cb27 Keep Muse token totals and context usage in the same session snapshot (#11389)
Co-authored-by: Shane Su <26364206+suniceman@users.noreply.github.com>
2026-11-30 05:42:58 +00:00
977049557a perf(app): open the mobile app faster after a cold launch (#11390)
A cold launch on Hermes keeps the JavaScript thread busy until the restored
workspace is on screen, so work removed there is launch time removed. A
sampled profile of a release build showed four costs that bought nothing:

- The provider snapshot cache rebuilt its size-and-age index on every
  launch by reading, parsing and validating every stored snapshot, about
  390 ms with a full 4 MB cache. The index is now stored and trusted for
  keys that still exist. Storage keys stay the authority: an indexed key
  that is gone is dropped, and a stored key the index does not list is
  read and measured.
- Zod compiled a parser for each object schema with `new Function`. Hermes
  has no JIT, so the compile was pure cost, about 145 ms. Native builds turn
  it off before any schema module loads; web and desktop keep it because V8
  optimises the compiled parsers.
- `localeCompare` builds a collator on every call, which dominated the
  project and workspace name sorts. They now share one collator.
- The replica cache measured each payload with a per-character loop, over
  about 1 MB of directory rows on every refresh.

Time from tap to the workspace on an Android emulator, release build,
median of six cold launches: 2.45 s to 1.76 s with a full provider cache,
2.30 s to 1.67 s with a small one.

Co-authored-by: Marcel Wysocki <4222082+maci0@users.noreply.github.com>
Co-authored-by: luke <1686898+luoph@users.noreply.github.com>
2026-11-30 12:37:40 +07:00
Mohamed Boudra 5d678b3848 perf(app): stop hidden workspaces re-rendering git actions on every switch (#11332)
Each retained workspace in the deck mounts git actions twice (header and
Changes surface). useGitActions subscribed to the whole workspaces map of the
host and resolved its workspace from the global active route. Any workspace
switch replaces that map, so every hidden workspace re-ran the hook and
rebuilt its actions. A hidden workspace also resolved the active workspace as
the one its archive action targets.

Callers now pass their own workspaceId, and the hook selects only that
descriptor, which the session store keeps by identity when other workspaces
change. The redirect after an archive reads the focused workspace when the
archive starts.
2026-11-30 12:23:58 +07:00
Mohamed Boudra 26550ff73f perf(app): skip the Markdown parse for replies that only link outside the workspace (#11327)
Opening a chat parsed every assistant reply that contained any Markdown link into a full
mdast tree, because a link into the workspace gets a hover title. A reply whose links all
point elsewhere produces no edit, so the parse and its garbage were wasted. Parse only when
the source contains the workspace root after a link, or a backslash escape that could spell
it. Character references already take the parse path through the `&` check.
2026-11-30 12:23:30 +07:00
916 changed files with 83504 additions and 17268 deletions
+1 -1
View File
@@ -59,7 +59,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/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
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 scripts/precompress-assets.test.mjs
quality:
name: quality
+2 -1
View File
@@ -45,7 +45,6 @@ At the start of non-trivial work, list `docs/` and skim anything relevant to the
| [docs/custom-providers.md](docs/custom-providers.md) | Custom provider config: Z.AI, Alibaba/Qwen, ACP agents, profiles, custom binaries |
| [docs/plugins.md](docs/plugins.md) | Local plugin manifest, directory source config, RPCs, native surfaces, and attachment sources |
| [docs/website-i18n.md](docs/website-i18n.md) | Website languages: locale URLs, translated Markdown pairs, `{#id}` anchors, Chinese style |
| [docs/service-proxy.md](docs/service-proxy.md) | Service proxy: exposing workspace scripts at public URLs, DNS setup, reverse proxy config |
| [docs/relay-endpoint-security.md](docs/relay-endpoint-security.md) | Relay E2EE modes: Noise NK mapping, record framing, negotiation, the `requireProtectedSecurity` flag, close codes |
| [docs/development.md](docs/development.md) | Dev server, build sync gotchas, CLI reference, agent state, Playwright MCP |
| [docs/rpc-namespacing.md](docs/rpc-namespacing.md) | WebSocket RPC naming convention — dotted namespaces and `.request`/`.response` pairs |
@@ -55,8 +54,10 @@ At the start of non-trivial work, list `docs/` and skim anything relevant to the
| [docs/permissions.md](docs/permissions.md) | Semantic daemon permissions, principals, credentials, pairing invitations, and Hub authority |
| [docs/terminal-performance.md](docs/terminal-performance.md) | Terminal latency pipeline, coalescing/backpressure invariants, benchmark + perf spec usage |
| [docs/terminal-rendering.md](docs/terminal-rendering.md) | Native terminal view: xterm owns the grid, cluster placement, emoji widths, mixed-direction limits, render regression |
| [docs/timeline-sync.md](docs/timeline-sync.md) | Owned agent history, rewind retirements, live stream vs authoritative fetch, paged catch-up, client replica |
| [docs/agent-stream-performance.md](docs/agent-stream-performance.md) | Assistant text pipeline — coalescing window, paced reveal, why arrival lumps are smoothed at render |
| [docs/agent-stream-disclosure.md](docs/agent-stream-disclosure.md) | Expand/collapse in the chat timeline — hold contract, native anchor sequence, frame spacing, render-window cost |
| [docs/running-indicators.md](docs/running-indicators.md) | Loader, status ring, tool-call shimmer — motion policy, compositor loops on web, native-driver clock, why not CSS keyframes |
| [docs/markdown-renderer.md](docs/markdown-renderer.md) | Shared Markdown engine, the vendored library fork, native selection, links, images and library constraints |
| [docs/native-text-selection.md](docs/native-text-selection.md) | Native diagram grouping, selection boundaries and leading inline image limitations |
| [docs/file-observation.md](docs/file-observation.md) | Recursive watcher ownership, Linux constraints, teardown invariants, and Parcel comparison |
+19 -1
View File
@@ -44,6 +44,12 @@ The QR code or pairing link is the trust anchor. It contains the daemon's public
When a daemon password is configured, relay clients send it in the encrypted `hello` message, so the relay never sees it. The daemon rejects a relay client that sends a wrong password or none, so a leaked pairing link alone does not grant access to a password-protected daemon.
The app binds each saved host to one daemon key. If you open a pairing link for a saved host with a different key, the app shows a "Host identity changed" warning. The warning displays both the saved key fingerprint and the new one.
If you cancel, the app leaves your saved host unchanged. If you replace the host identity, the app removes all relay connections to the old key and clears the saved password. The app never sends a password saved for one daemon to another.
You will see this warning once after you reset Paseo on a host. If you did not reset that host, cancel the prompt. Someone could be trying to impersonate your host.
## Local daemon trust boundary
By default, the daemon binds to `127.0.0.1`. With no password configured, anything that can reach the daemon socket can control the daemon. Loopback is reachable by other users on the machine and by some forwarding tools.
@@ -52,7 +58,19 @@ The daemon supports an optional shared-secret password (set via `auth.password`
The daemon writes a new `$PASEO_HOME/local-credential` on every run with mode `0600` and removes it on shutdown. The CLI and desktop main process read it only for the daemon whose PID lock `listen` matches their connection target. A same-user process can read this credential, so the password protects against network clients and other OS users, not processes running as the daemon user. Protect `$PASEO_HOME` accordingly. Relay traffic remains end-to-end encrypted independently of password admission.
Connected clients are trusted operators of the daemon user. File previews follow that authority: a preview request may read any regular file the daemon process can read, while keeping path normalization and symlink checks in the daemon file service. Workspace-relative paths remain a UI convenience, not a security boundary.
Connected clients act with the permissions of the daemon user. Through the daemon file API, a client can access any regular file the daemon user can read outside `$PASEO_HOME`. Workspace paths are a UI convenience, so they do not restrict which files a client can open.
To protect daemon secrets, the file API refuses secret files inside `$PASEO_HOME` for every client, including owners. This blocks reads, writes, directory listings, watches, downloads, and path suggestions for `local-credential`, `daemon-keypair.json`, `hub-relationship.json`, `hub-credentials.json`, `hosts.json`, and `terminal-worker/`. The daemon resolves `..` and symlinks before checking the path, so it also refuses links from a workspace into those files.
Clients with owner permissions (`daemon.manage` and `access.manage`) can still access non-secret files inside `$PASEO_HOME`, such as `config.json` and `daemon.log`. For scoped clients without those permissions, the file API refuses all of `$PASEO_HOME` except five user-content folders:
- The managed worktrees folder (`worktrees/`, or `worktrees.root` when it is inside `$PASEO_HOME`)
- `uploads/`
- `paseo-attachments/`
- `desktop-attachments/`
- `plans/`
This restriction applies only to client file requests. Every other file the daemon user can read remains accessible. Coding agents and terminals run as the daemon user and can still read `$PASEO_HOME` directly.
When Paseo checks out a change request from a different repository, it does not run that workspace's `paseo.json` setup, automatic terminals, named scripts, or teardown until you explicitly run setup for that workspace. The decision lasts for the workspace and does not re-prompt after new commits. Same-repository changes, ordinary branches, local workspaces, agent launches, terminals, explicit shell commands, and metadata-generation instructions are outside this gate.
+102 -27
View File
@@ -39,8 +39,8 @@ An unarchived agent may be `closed` without being deleted or archived. Closing r
processes and subscriptions while retaining its Paseo identity, persistence handle, timeline,
workspace, labels, title, usage, attention, timestamps, and parent relationship. Opening or prompting
the agent runs through `ensureAgentLoaded()`, which resumes the durable provider session under the
same Paseo agent ID. Provider history is not appended again when the canonical timeline is already
primed.
same Paseo agent ID. Resume does not read provider history when the agent already has a timeline;
see [owned history](timeline-sync.md#owned-history).
Reload releases the old runtime before resuming its durable session: an idle provider process can
still own an exclusive writer. A close failure retains that runtime for cleanup and blocks the
@@ -152,7 +152,7 @@ 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. 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.
Agent-originated messages and automatic notifications share a recipient-daemon delivery module. The daemon saves a queued message, then acknowledges it with a receipt, 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.
Any sender picks `queue`, `steer`, or `interrupt` with `activeTurnBehavior`. Agent senders default to `queue`; non-agent senders (app, CLI, plugins, Hub, top-level MCP) default to `interrupt`. Each kind of prompt is released this way:
@@ -170,33 +170,64 @@ A command the provider accepts out of band is the one exception to admission ord
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 at permission
checkpoints and when a Stop holds the queue.
A provider switch can wait in the queue too (`agent.provider.switch.request` with
`activeTurnBehavior: "queue"`). The message carries the target provider and settings, shares a prompt
with nothing, and divides the queue: what is ahead of it goes to the current provider, and it and
what follows go to the target. A direct prompt therefore takes along only the queued rows ahead of
the switch. Promoting the switch cuts the running turn once the target is known to be usable. A chat
already on the target takes the message and its settings as a plain prompt. A switch that fails keeps
the message and holds the queue; the reason is in the daemon log.
The queue is saved in `$PASEO_HOME/agent-queues/` ([data model](data-model.md#directory-layout)),
and a message is saved before its receipt is sent. Inline images are first saved as uploads, so the
queue file holds references. An empty message is refused, and a recipient holds at most 100
messages.
A message is marked `dispatching` before the provider can receive it and removed when the provider
admits it. A dispatch that is not admitted returns the message to its place. A refused turn start
also holds the queue: retrying by itself would be refused again and would add the prompt to the
history each time. A message that cannot be sent is removed so that it does not block the ones
behind it.
Shutdown does not send the queue. It waits only for dispatches already in flight, and everything
else stays saved, held messages included. Closing an idle runtime keeps the queue. Archiving or
deleting the agent clears it.
Bootstrap restores queues before restart recovery resumes agents, and before finish subscriptions,
change-request watches, and ingress start. A held queue stays held. Other queues are sent, after the
resume prompt for an agent that restart recovery resumes. A crash can leave a message marked
`dispatching`, so the daemon looks for it in the recipient's history: a message found there is
removed, and one not found, or whose history cannot be read, is sent again.
A client that retries a queued message with the same `messageId` is acknowledged again at once. The
completed send receipt is written after dispatch, and a different request under that `messageId`
conflicts. Completion waits cover queued admission within their original timeout and cancellation
scope, and return at permission checkpoints and when the queue is held.
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
`$PASEO_HOME/finish-subscriptions.json`. Registration must commit before creation or queued-prompt
acknowledgment promises a notification. A pending replacement retains its predecessor until dispatch
accepts; rejected dispatch removes only the candidate. Recovery coalesces registrations for the same
caller, child, and host into one watch.
accepts; rejected dispatch removes only the candidate. The record keeps the prompt's `messageId`, so
withdrawing that message removes the subscription, also after a restart. Recovery coalesces
registrations for the same caller, child, and host into one watch.
Bootstrap restores these watches after repairing stale running records to `closed` and before opening
ingress. Reading a closed child's result does not load its provider. A finish notification reports that
the child has settled (see below); the parent decides whether its task is complete. A child chosen for restart
recovery is observed only after its resume was sent, so the parent never hears that it was closed
in between. Archived or deleted parents suppress delivery;
in between. A subscription whose prompt is still queued stays pending until that prompt is
dispatched, so a held follow-up reports nothing. Archived or deleted parents suppress delivery;
parent-owned creation watches also stop
reporting after detachment.
Intent remains stored until the parent's notification dispatch is acknowledged. Dispatch failure
retries the captured notification; it does not change the child's reported outcome. Remote host loss
follows the [connected-host observation policy](connected-hosts.md#delegating-agents). Shutdown stops observation before flushing message delivery, retaining
outstanding intent. A crash after successful dispatch but before removal commits can repeat the
notification. Clean shutdown can also flush an already queued callback while retaining its intent,
so that callback can repeat after restart. This is an at-least-once wakeup, without turn attribution or exactly-once delivery.
follows the [connected-host observation policy](connected-hosts.md#delegating-agents). Shutdown stops
observation and retains outstanding intent. A final or permission notice has an id derived from its
subscription, so observing the same outcome again while the notice is queued adds nothing. A crash
after successful dispatch but before removal commits can repeat the notification. This is an
at-least-once wakeup, without turn attribution or exactly-once delivery.
A turn end is not always a settled child. A child can end its turn with work that will start its next
turn by itself: a running turn, queued messages, a pending provider wake-up
@@ -205,17 +236,23 @@ wake-ups), or the child's own outstanding finish subscriptions as a caller. Hear
crons, change-request watches, and other daemon background items never count: they are external
triggers, not work the caller is waiting for.
Every turn end reports `finished` at once. When work is still pending, the notice names it and the
subscription follows the child: each later turn end reports `finished` again, and the child settling
with nothing pending sends a final `finished` and removes the subscription, even when the work
drains without another turn. Reporting at once keeps a long-lived task, such as a dev server, from
leaving the caller without the child's reply. Following is what lets the caller hear the reply a
background task wakes up later ([#6346](https://github.com/getpaseo/paseo/issues/6346)). A work change
that leaves work pending sends nothing. Errors, permission requests, and closes report as they
happen. `followingSince` is stored when following starts, so a restart keeps following instead of
waiting for another turn end. After 24 hours of following, the caller gets a final `finished` with
the child's last reply and the subscription ends. Remote children and providers without the probe
report their first turn end as a settled `finished`.
Every turn end reports `finished` at once, unless the child already sent an agent message to its
caller during that turn and started no further tool work afterwards. In that case the child's
message already delivered its reply, so the redundant `finished` notice is skipped: a settled watch
ends silently, and a watch with pending work keeps following silently until a later turn starts or
the work drains. Starting another non-reporting tool call or a new turn clears that mark (plain text output after the
message does not), and errors, permission requests, cancellations, and closes are never suppressed. When work is still
pending on an unreported turn end, the notice names it and the subscription follows the child: each
later turn end reports `finished` again, and the child settling with nothing pending sends a final
`finished` and removes the subscription, even when the work drains without another turn. Reporting
at once keeps a long-lived task, such as a dev server, from leaving the caller without the child's
reply. Following is what lets the caller hear the reply a background task wakes up later
([#6346](https://github.com/getpaseo/paseo/issues/6346)). A work change that leaves work pending
sends nothing. Errors, permission requests, and closes report as they happen. `followingSince` is
stored when following starts, so a restart keeps following instead of waiting for another turn end.
After 24 hours of following, the caller gets a final `finished` with the child's last reply and the
subscription ends. Remote children and providers without the probe report their first turn end as a
settled `finished`.
Permission requests are notification checkpoints, not the end of that subscription. The caller is notified again after a permission response when the child finishes, errors, or requests another permission.
The permission notification includes the normalized request plus the child and request IDs, so the caller can inspect it and respond without fetching agent status.
@@ -277,7 +314,8 @@ lifecycle is separate from public workspace visibility and is not a public creat
Archive is a **soft delete**: the agent record stays on disk with `archivedAt` set, the runtime is closed, and the agent disappears from active lists. Archive is **global** — it lives on the server and propagates to every connected client.
Archive sets `archivedAt`, invokes the provider's native archive hook, and cascades to managed
children.
children. The timeline and the provider children stay, so an archived chat reads them without its
provider; deleting the agent removes them.
`create_agent_request` can opt an agent into `autoArchive`. In that mode the daemon archives the agent after the first terminal turn event (`turn_completed`, `turn_failed`, or `turn_canceled`). When the agent owns an isolated workspace, auto-archive archives that workspace too; the managed worktree is removed when its final workspace reference is gone.
@@ -373,6 +411,8 @@ Workspace status is an aggregate activity signal computed **per `workspaceId`**.
Running provider-native subagents contribute `running` to the workspace owned by their parent agent. Their completed, failed, and canceled states stay in the parent's subagents track.
Only the parent's current runtime makes a provider child running. A child's stored status is the last report about it, and that report can come from provider history or from a runtime an earlier daemon ran, so a stored `running` child does not make the workspace running or keep the parent's runtime alive. It counts again once the live session reports it running. Closing a runtime cancels the children that runtime reported running; children it never reported keep their stored status.
A finished or failed workspace can be marked unread after it has been reviewed. The daemon restores
attention on its newest eligible workspace-root agent, `error` for an agent whose lifecycle is
`error` and `finished` otherwise, without sending a new notification. Opening a workspace restores
@@ -394,6 +434,41 @@ that leaves the lifecycle at `error`, and replaces unread `finished` attention;
agent would show the green dot or none. Subagents track marks are the exception: they follow the
child's lifecycle, because the track is where a failed child stays visible.
## The queue track
The queue track is the list above the composer of the messages the host holds for the open agent
(`packages/app/src/composer/queue/`). One list covers every sender, in the order the host sends
them: your queued prompts, agent messages, finish notifications, and change-request updates.
The host owns the [queue](#relationships). `packages/app/src/agent-queue/` reads it as the open
agent's `agent.queue` synced collection through `packages/app/src/sync/`, subscribed while the
agent's panel is visible. A hidden panel keeps its last rows and releases the subscription. When you
return or the host reconnects, the client sends its cursor and gets back only the rows added,
changed, or removed since. A queued message therefore survives a reload, is sent with
every client closed, and shows on every client that views the agent. Files upload to the host before
the message is queued, so any device can open a row's attachments.
Rows take these commands:
- **Send now** promotes the row with your send behavior setting: `steer`, otherwise `interrupt`.
- **Edit** is offered on your own messages only. It withdraws the row, then replaces the composer
draft with its text and attachments, and stages the row's provider switch again. If the host
already started sending the row, the draft stays as it is.
- **Cancel** withdraws the row.
A message you send directly (`steer` or `interrupt`) takes the queued rows with it, ahead of your
text.
A message sent mid-turn with a staged provider switch is queued whatever the send behavior, and its
row names the target.
A row the host is `dispatching` takes no command. A held queue shows a paused notice. The notice
does not name Stop, because a refused turn start holds the queue too.
A host without `server_info.features.agentMessageQueue` has no queue track. The composer offers no
Queue action there, and a `queue` send behavior sends as `steer`, so it does not cut the running
turn.
## The subagents track
The track is a pill at the foot of an agent's pane (`packages/app/src/subagents/track.tsx`): a count you can read at a glance, and a panel behind it — a popover on wide screens, a sheet on compact ones — holding the rows. It floats over the transcript rather than sitting in a band above the composer, so the timeline scrolls underneath it; `packages/app/src/panels/agent-tracks.tsx` owns that placement, and the pill frame is shared with the task list in `packages/app/src/composer/tracks.tsx`.
+12 -4
View File
@@ -29,7 +29,7 @@ So arrival sets a _target_ and the reveal rate is derived from the backlog inste
- **The coalescer is leading + trailing.** The first delta after an idle window flushes synchronously; only the rest of the burst waits for the trailing timer. Reverting to trailing-only adds a full window to the first character of every turn. Same shape and the same reason as `TerminalOutputCoalescer`.
- **The leading flush adds a canonical row, and that is fine.** A burst's first chunk lands as its own timeline row. `mergeAssistantChunks` / `mergeReasoningChunks` in `timeline-projection.ts` join contiguous same-turn rows, and clients read the projected timeline, so history is unaffected. Tests that assert on raw rows have to account for the extra row; tests that assert on what a client sees do not.
- **The store holds the full text; only the rendered slice is paced.** Copy, selection, the chat outline, and scroll geometry all read the same string the user can see. Pacing the store instead would leave the bottom anchor chasing a content height that is ahead of the reveal.
- **One source assistant message is one display row.** Presentation projects plugin output and caches unchanged history. The shared [Markdown renderer](markdown-renderer.md) owns rendering on every platform. Chat paces the visible source and applies a 32,000-character render cap on web; native keeps the complete message. The native renderer keeps closed blocks in a stable head and sends the paced suffix to a separate tail view during streaming; completion reunites them for selection. This stays inside the renderer, without promoting blocks into timeline history.
- **One source assistant message is one display row.** Presentation projects plugin output and caches unchanged history. The shared [Markdown renderer](markdown-renderer.md) owns rendering on every platform. Chat paces the visible source and applies a 32,000-character render cap on web; native keeps the complete message. While streaming, the renderer keeps closed blocks in head parts and sends the paced suffix to a separate tail; completion reunites them for selection. This stays inside the renderer, without promoting blocks into timeline history.
- **Message identity survives completion.** Assistant row ids are source message ids. Plugin rows can replace a source, so find, scroll-to-message and history reveal still use `getStreamItemMessageId`. Width-specific measurements describe whole rendered messages.
- **First sight of a text is revealed whole.** Only growth is paced. This is what makes history hydration, timeline replay, a virtualized row remounting on scroll, and an already-finished message all render complete on first paint without a special case for each.
- **Leaving `phase: "streaming"` snaps the reveal.** A completed turn must never be left holding characters. `layoutStream` sets the phase, so anything outside the live head with an active turn is already complete.
@@ -49,11 +49,19 @@ So arrival sets a _target_ and the reveal rate is derived from the backlog inste
while text arrives, and release obsolete window caches as the reader reveals more history;
window caches must stay bounded while their source timeline remains loaded.
## Native parsing cost
## Markdown parsing cost
The native library reparses and measures its entire `markdown` prop on each update. During streaming, the renderer splits source at an mdast block boundary and memoizes the head, so per-frame updates parse only the tail. Boundary discovery runs when a source line completes, rather than on every reveal frame. The unfinished line and final parsed block stay in the tail, preserving list continuation, setext headings, tables and open fences. Reference-dependent source and HTML retain a larger tail because later source can change their meaning. A single long block therefore still carries its full parsing cost.
Both engines reparse their entire `markdown` prop on each update: md4c in C++ on native, md4c in WASM plus a JSON tree on web. Source adaptation adds a full mdast parse for some text, such as any `&`, at about 1 µs per character. Rendering a growing reply whole on each reveal frame therefore makes the reply quadratic to stream.
Completion restores one native text view per Mermaid-delimited segment, so selection crosses prose paragraphs again. The head retains its trailing block margin while split. JS reveal remains the pacing source; native opacity animation stays disabled.
While streaming, `createStreamingMarkdownSplitter` in `components/markdown/streaming.ts` splits the message into head parts and a tail, on every platform. The tail is the last block and the unfinished line, so list continuation, setext headings, tables and open fences render as they will when complete. Rules that keep the cost per frame flat as the reply grows:
- **Discovery is incremental.** The boundary moves only when a line completes, and each time the splitter parses only the source after the boundary. Blocks before it are closed and need no document context.
- **Head parts are sealed at 2,000 characters.** Each completed block re-renders the head part it lands in. Only the last part grows, so that work stays bounded. A single head would re-render all closed blocks each time a block completes.
- **The first part keeps its React key from the first frame to the completed message.** Completion re-renders it in place instead of remounting it, and the parts share one image occurrence key, so an image keeps its acquisition when its block moves into the head.
Two kinds of source fall back to a growing render, because later source can change how earlier source reads. A link definition can turn an earlier `[label]` into a link, so a message with one renders as one document until it completes. HTML needs its enclosing source, so HTML and every block after it stay in the tail. A single long block also carries its full cost.
Completion renders one view per Mermaid-delimited segment, so native selection crosses prose paragraphs again; while streaming it crosses only within a part. JS reveal remains the pacing source; native opacity animation stays disabled.
## Measuring
+5 -3
View File
@@ -94,6 +94,7 @@ workspace for a directory clears it. The store lives in memory and resets on dae
| `server/directory-sync/` | Daemon-global latest-state sequences for projects, workspaces, and agents |
| `server/workspace-labels/` | Host-local label catalog, assignment mutations, and explicit subscriptions |
| `server/agent/agent-manager.ts` | Agent lifecycle state machine, timeline tracking, subscriber management |
| `server/agent/timeline/` | Owned agent history, provider children, rewind retirements, behind a backend |
| `server/agent/agent-storage.ts` | File-backed JSON persistence at `$PASEO_HOME/agents/` |
| `server/agent/tools/` | Transport-neutral catalog for workspaces, agents, permissions, and automation |
| `server/agent/mcp-server.ts` | Thin MCP adapter that registers the Paseo tool catalog with the MCP SDK |
@@ -218,9 +219,9 @@ file after the daemon confirms persistence.
> **Window-state v1 limitation:** only the _first_ window of a session restores and persists saved geometry (size/position/maximized). Windows opened via ⌘⇧N / second-instance / "Open in new window" open at the default size, OS-cascaded, and do not persist — this avoids every window stacking on the same restored bounds and fighting over the single window-state store. Lifting this needs per-window state keys.
>
> **In-app browser profile.** Every browser guest uses one stable persistent Electron session, so cookies, authentication, cache, and site storage are shared across tabs, workspaces, and desktop windows and survive tab or app closure. Browser identity is independent of that storage partition: after every `did-attach`, the renderer explicitly registers its browser id, workspace id, and current guest `WebContents` id, and main accepts the registration only when that guest belongs to the calling renderer and the shared profile. Registration is intentionally repeated because reparenting a retained `<webview>` can replace its guest without replacing the DOM element. Settings > General > Clear browser data is the sole profile-deletion path; it clears the shared session and reloads live guests without deleting saved tabs or URLs.
> **In-app browser profiles.** Each local browser tab runs in a persistent Electron partition and can switch profiles at any time; switching replaces the `<webview>` under the new partition and reloads the current URL in that profile's session. Partition names are the identity: `persist:paseo-browser` is **Default** and preserves cookies from before profiles; `persist:paseo-profile-<slug>` is a named profile. Display names and colors live in the main-owned catalog `<userData>/browser-profiles.json`, so editing a profile's name or color keeps sign-ins intact and updates open tabs live. Main admits only `persist:paseo-browser`, `persist:paseo-profile-<slug>`, and active host-proxy partitions (`persist:paseo-browser-host-<16hex>`) at `will-attach-webview`. The tab's chosen profile slug lives in its `workspace-browser-store` record. After every `did-attach`, the renderer registers its browser id, workspace id, partition, and current guest `WebContents` id, and main accepts it only when that guest belongs to the calling renderer and its session matches the partition. Registration is intentionally repeated because reparenting a retained `<webview>` can replace its guest without replacing the DOM element. Settings > Chat & panes manages profiles: clearing a profile clears its storage/cache and reloads its open tabs; removing a named profile closes its open tabs, removes it from the catalog, clears its session, and deletes its `Partitions/paseo-profile-<slug>` directory from disk. Default cannot be removed.
>
> **In-app browser window opens.** Ordinary link opens, including Shift-clicked links, become Paseo workspace tabs. Script-created opens with popup features or a named window target and POST-backed opens remain secured Electron child windows in the shared browser profile, preserving `window.opener`, `postMessage`, named-window reuse, request bodies, and `window.close()` for OAuth, payment, and similar popup protocols. Unsupported URL schemes are denied before either path.
> **In-app browser window opens.** Ordinary link opens, including Shift-clicked links, become Paseo workspace tabs and inherit the opener tab's browser profile. Script-created opens with popup features or a named window target and POST-backed opens remain secured Electron child windows in the opener’s browser profile, preserving `window.opener`, `postMessage`, named-window reuse, request bodies, and `window.close()` for OAuth, payment, and similar popup protocols. Unsupported URL schemes are denied before either path.
>
> **In-app browser ownership.** Each registered guest records its owning host window. The active browser is keyed by `(host window, workspace)`, and application-menu Reload / Force Reload resolve only within the window Electron supplies to the menu callback. A non-null active update must name a browser owned by that host; a null update clears only that host/workspace. Browser automation continues to target explicit browser ids returned by `browser_new_tab` or `browser_list_tabs`.
>
@@ -402,7 +403,7 @@ initializing → idle ⇄ running
client-side dedup; the default fetch page is 200 items.
- Timeline row `timestamp` values are canonical daemon-owned timestamps. Providers may supply original replay timestamps, but clients must not guess timestamp trust or hide time UI based on local clock heuristics.
- Events stream to connected clients in real time; correctness is backed by authoritative timeline fetches and paged-to-completion catch-up.
- Agent state persists to `$PASEO_HOME/agents/{cwd-with-dashes}/{agent-id}.json`. Timeline rows are runtime memory; provider history is the durable transcript authority and resumed agents rebuild from it. That storage path is derived from `cwd`, not from workspace id.
- Agent state persists to `$PASEO_HOME/agents/{cwd-with-dashes}/{agent-id}.json`. That storage path is derived from `cwd`, not from workspace id. Timeline rows persist in the daemon database, `$PASEO_HOME/paseo.db`. They are the transcript authority after the first import of provider history. See [owned history](timeline-sync.md#owned-history).
## Right-sidebar boundary: directory-backed vs workspace-owned
@@ -478,6 +479,7 @@ Providers that can accept native tool definitions should set `supportsNativePase
```
$PASEO_HOME/
├── agents/{cwd-with-dashes}/{agent-id}.json # Agent record
├── paseo.db # Daemon database (SQLite): agent timelines
├── projects/projects.json # Project registry
├── projects/workspaces.json # Workspace registry
├── projects/icons/ # Custom project icon images
+6 -5
View File
@@ -37,7 +37,7 @@ npm run build:main --workspace=@getpaseo/desktop
PASEO_CAPTURE_HARNESS_GROUP=automation npm run capture-harness --workspace=@getpaseo/desktop
```
Run the shared browser profile fixture with:
Run the persistent browser profile fixture with:
```bash
PASEO_CAPTURE_HARNESS_GROUP=browser-profile npm run capture-harness --workspace=@getpaseo/desktop
@@ -55,10 +55,11 @@ window movement, including button clicks and a portal over the titlebar. Leave
the mouse idle during this group. It reads the app's production CSS and writes
screenshots and window bounds to the output directory.
The browser profile group runs two Electron processes in sequence. It verifies that each
renderer-side `did-attach` identity maps to the correct main-process guest, that two live
tabs share cookies and local storage through one persistent session, and that the data is
still present after the first Electron process exits and the second starts.
The browser profile group launches two Electron processes against the same test origin
and user data. It matches renderer registrations to the main-process guests, checks sharing
within a profile and isolation between named profiles, and verifies that a child popup
inherits its opener’s session. The second launch checks the saved cookies and local storage.
The toolbar profile journey runs in the [desktop browser regression](testing.md#desktop-browser-regression).
The automation group uses a real guest webview to verify the page-side ref contract:
ARIA-like snapshot text includes headings, static text, and controls; refs survive
+51 -5
View File
@@ -34,7 +34,7 @@ Workspace archive runs lifecycle teardown from the exact `cwd` but removes only
`worktreeRoot` after its last active reference disappears. Worktree recovery recreates that backing
checkout from `mainRepoRoot`, then restores the relative path from `worktreeRoot` to `cwd`.
Paseo uses **file-based JSON persistence** instead of a traditional database. All data is validated at runtime with Zod schemas. Most stores write atomically (write to temp file, then rename); a few still use plain `writeFile` — see each section. There is no schema-versioning/migration framework — schemas rely on optional fields with defaults for forward compatibility, with a small amount of inline normalization in `persisted-config.ts` for legacy provider/speech entries.
Paseo persists most stores as JSON files, and agent timelines in the [daemon database](#daemon-database). JSON data is validated at runtime with Zod schemas. Most JSON stores write atomically (write to temp file, then rename); a few still use plain `writeFile` — see each section. JSON stores have no schema-versioning/migration framework — schemas rely on optional fields with defaults for forward compatibility, with a small amount of inline normalization in `persisted-config.ts` for legacy provider/speech entries.
All server-side stores live under `$PASEO_HOME` (defaults to `~/.paseo`).
@@ -53,12 +53,16 @@ $PASEO_HOME/
├── daemon-keypair.json # E2EE keypair for relay (mode 0600)
├── paseo.pid # Daemon PID lock file
├── local-credential # Per-run local client credential (mode 0600)
├── paseo.db # Daemon database (SQLite, with -wal and -shm files)
├── daemon.log # Default log file (path configurable)
├── agents/
│ └── {sanitized-cwd}/
│ └── {agentId}.json # One file per agent
├── schedules/
│ └── {scheduleId}.json # One file per schedule
├── agent-queues/
│ ├── {agentId}.json # Undelivered messages for one agent; removed when empty
│ └── {agentId}.json.corrupt.{ms} # Unreadable queue file, set aside at startup
├── projects/
│ ├── projects.json # Project registry
│ ├── workspaces.json # Workspace registry
@@ -181,6 +185,45 @@ Terminal activity contributes to the workspace status bucket **per `workspaceId`
---
## Daemon database
`$PASEO_HOME/paseo.db` is one SQLite file that the daemon opens at startup with `node:sqlite`
(`packages/server/src/server/database/`). Agent timelines are its only store today. Each store is a
`SchemaModule`: its own table-name prefix and an append-only list of migrations.
- **Migrations.** Startup runs every module's pending migrations in one transaction, so a failed
migration leaves the file as it was. `schema_versions` records each module's version and
`min_reader_version`. Mark a migration `breaking` when an older daemon cannot read the result,
for example a dropped or renamed column. An older daemon then refuses to start with
`DatabaseSchemaTooNewError`. Additive migrations leave older daemons working, and they ignore
modules they do not know. This matters because the app and the daemon update separately, and a
user can run an older daemon on the same `$PASEO_HOME`.
- **Failure.** A file that SQLite cannot open stops the daemon with `DatabaseOpenError`, which
names the path. The daemon does not delete or recreate the file.
- **Access.** The file holds every prompt and reply, so the daemon sets it and its `-wal` and `-shm`
files to mode `0600` on every open. SQLite gives the WAL files it creates the mode of the database
file.
- **Durability.** The database uses WAL with `synchronous = NORMAL`. A power loss can drop the
last commits but does not corrupt the file.
- **Checkpoints.** A checkpoint syncs the file to disk and takes up to 100 ms. SQLite's
auto-checkpoint runs it on the committing thread, which stalled the event loop during streaming.
The daemon turns it off and checkpoints from a worker thread with its own connection. If the
worker exits, the daemon turns auto-checkpoint back on.
- **Transactions.** `write` and `read` callbacks are synchronous, so a transaction never spans an
`await` and transactions never interleave.
- **Node.** `node:sqlite` needs Node 22.16 or later. Node 22 prints an experimental warning once,
when the daemon opens the database.
### Agent timelines
`AgentTimeline` owns each agent's history, and its SQLite backend stores the projected rows, the
source ranges, retirements, the open rewind, and provider children in `timeline_*` tables. The text
of a streamed assistant or reasoning message is stored as one chunk per source event, beside its
row, so a chunk never rewrites the message. An earlier file store rewrote the whole transcript on
every update. See [owned history](timeline-sync.md#owned-history).
---
## 2. Daemon Configuration
**Path:** `$PASEO_HOME/config.json`
@@ -209,7 +252,8 @@ snapshot so a mixed edit can apply its live subset and still name the paths that
listen: "127.0.0.1:6767",
hostnames: true | string[], // legacy alias `allowedHosts` is migrated on load
trustedProxies: true | string[], // defaults to ["loopback"]; Express proxy names/CIDRs
mcp: { enabled: boolean, injectIntoAgents: boolean },
tools: { enabled: boolean, groups: { orchestration, schedules, changeRequests, browser: boolean } },
mcp: { enabled: boolean, injectIntoAgents: boolean }, // legacy, read only when `tools` is absent
git: { maxProcessesPerSecond: number, maxProcessConcurrency: number },
appendSystemPrompt: string, // appended to supported provider system/developer prompts
terminalProfiles: TerminalProfile[], // named shell commands; omitted means DEFAULT_TERMINAL_PROFILES
@@ -311,12 +355,14 @@ Each entry may include a Paseo-tool policy:
Absent `paseoTools`, or absent fields within it, means Paseo tools are enabled and all tools are
allowed. `enabled: false` disables the provider's Paseo catalog; `disabledTools` lists exact tool
IDs to omit. The policy covers the core and browser catalog, not the voice-only `speak` tool.
Browser tools also require `daemon.browserTools.enabled` and a connected browser host.
Browser tools also require `daemon.tools.groups.browser` and a connected browser host.
This policy controls the catalog presented to an agent. It is not an authorization boundary for
agents that can access the host through a shell.
`daemon.mcp.injectIntoAgents` is the global override. When it is `false`, no provider receives
Paseo tools; otherwise the provider policy applies. Provider and global policy are resolved when a
`daemon.tools` is the global override. When `enabled` is `false`, no provider receives Paseo or
plugin tools; otherwise each group in `daemon.tools.groups` and then the provider policy applies.
When `daemon.tools` is absent, the daemon reads the legacy `daemon.mcp.injectIntoAgents` and
`daemon.browserTools.enabled` fields. Provider and global policy are resolved when a
session is created, resumed, imported, or reloaded, so configuration changes affect the next
session rather than an already-running one.
+2 -2
View File
@@ -255,9 +255,9 @@ Status pills use the status token for text on the shared `surface3` and `border`
Status dots — the small filled circles next to a host or agent name — are `borderRadius.full` filled with the status token. Which token a given agent state maps to is owned by `getStatusDotColor` (`packages/app/src/utils/status-dot-color.ts`); a row, a group header, and a project icon all call it rather than restating the mapping. They sit in the trailing slot of a sidebar row or as a leading marker on a status pill.
Identity badges — the project icon, the sidebar host badge, and the PR-panel participant avatar — do not use the theme palette. They draw from the fixed ten-color identity table in `packages/app/src/styles/identity-colors.ts`, whose hexes are held to one contrast band so a color identifies rather than ranks. Project icons and PR avatars use it as a fill with a white letter — that is `identityColor`, one theme-independent hex per identity. Host badges use it as a _foreground_ on both the glyph and the label, which is a different contrast problem that the fill table cannot solve: no single hex clears 4.5:1 against both a near-white and a dark sidebar. Foregrounds therefore come from `identityForeground(name, colorScheme)`, one set per scheme, hue unchanged. That set is generated on the **status family's** lightness and chroma fraction, because a meta row puts a host badge beside a CI check and a diff stat, and two families at different lightness make the brighter one shout. Change the status band and this one changes with it. A host with no color assigned falls back to `foregroundMuted`. The table is theme-independent by design; do not fork it per theme, and do not add hexes to it without recomputing the band.
Identity badges — the project icon, the sidebar host badge, workspace label chips, browser profile badges, and the PR-panel participant avatar — do not use the theme palette. They draw from the fixed ten-color identity table in `packages/app/src/styles/identity-colors.ts`, whose hexes are held to one contrast band so a color identifies rather than ranks. Project icons and PR avatars use it as a fill with a white letter — that is `identityColor`, one theme-independent hex per identity. Host badges use it as a _foreground_ on both the glyph and the label, which is a different contrast problem that the fill table cannot solve: no single hex clears 4.5:1 against both a near-white and a dark sidebar. Foregrounds therefore come from `identityForeground(name, colorScheme)`, one set per scheme, hue unchanged. That set is generated on the **status family's** lightness and chroma fraction, because a meta row puts a host badge beside a CI check and a diff stat, and two families at different lightness make the brighter one shout. Change the status band and this one changes with it. A host with no color assigned falls back to `foregroundMuted`. Translucent badge and chip grounds behind identity-colored ink come from `identityTint(name, colorScheme)` (12% light / 16% dark, matching `status*Tint`). For an identity-colored icon inside a tinted circle — such as browser profiles in toolbars, menus, and settings rows — use `<IdentityIconBadge>` (`packages/app/src/components/ui/identity-icon-badge.tsx`), which pairs `identityTint` with `identityForeground` and falls back to `interactionHighlight` + `foregroundMuted` when uncolored. The table is theme-independent by design; do not fork it per theme, and do not add hexes to it without recomputing the band.
New status pills use `<StatusBadge>`. Identity, shortcut, and interactive link badges remain separate because color does not encode status there.
New status pills use `<StatusBadge>`. Identity icon badges use `<IdentityIconBadge>`. Identity, shortcut, and interactive link badges remain separate because color does not encode status there.
---
+10 -10
View File
@@ -440,15 +440,13 @@ that reads what it needs from `process.env` and invoke it as
Every `scripts` entry with `"type": "service"` receives these environment variables:
| Variable | Value |
| --------------------------- | ------------------------------------------------------------------------------------------------------------------------- |
| `PASEO_SERVICE_<NAME>_URL` | Proxied URL for a declared peer service. Prefer this for peer discovery; it survives peer restarts. |
| `PASEO_SERVICE_<NAME>_PORT` | Raw ephemeral port for a declared peer service. Use only as a bypass escape hatch; it can go stale if that peer restarts. |
| `PASEO_URL` | Self alias for `PASEO_SERVICE_<SELF>_URL`. |
| `PASEO_PORT` | Self alias for `PASEO_SERVICE_<SELF>_PORT`. |
| `HOST` | Bind host for the service process. |
Service proxy hostnames use the double-dash shape: `web--feature-auth--project.localhost` or, on the default branch, `web--project.localhost`. Optional public aliases use the same leftmost label under the configured public base host.
| Variable | Value |
| --------------------------- | ---------------------------------------------------------------- |
| `PASEO_SERVICE_<NAME>_URL` | Local `http://localhost:<port>` URL for a declared peer service. |
| `PASEO_SERVICE_<NAME>_PORT` | Allocated port for a declared peer service. |
| `PASEO_URL` | Self alias for `PASEO_SERVICE_<SELF>_URL`. |
| `PASEO_PORT` | Self alias for `PASEO_SERVICE_<SELF>_PORT`. |
| `HOST` | Bind host for the service process. |
`<NAME>` is normalized from the script name by uppercasing it, replacing each run of non-`A-Z0-9` characters with `_`, and trimming leading or trailing `_`. For example, `app-server` and `app.server` both normalize to `APP_SERVER`; that collision fails at spawn time with an actionable error.
@@ -505,7 +503,7 @@ Or persist it in `config.json`:
}
```
When enabled, opening the daemon HTTP origin (for example `http://localhost:6767/`) serves the web app. The same HTTP server continues to serve `/api/*`, `/mcp/*`, `/public/*`, the WebSocket upgrade, and service-proxy routes. Static files load without daemon bearer auth; API and WebSocket calls still enforce auth.
When enabled, opening the daemon HTTP origin (for example `http://localhost:6767/`) serves the web app. The same HTTP server continues to serve `/api/*`, `/mcp/*`, `/public/*`, and the WebSocket upgrade. Static files load without daemon bearer auth; API and WebSocket calls still enforce auth.
The served app auto-bootstraps a connection to the same origin, so opening `http://localhost:6767/` directly usually skips the Add Host step.
@@ -523,6 +521,8 @@ Measured bundle size for a standard Expo web export:
- gzip: 2.55 MiB
- brotli: 1.93 MiB
`npm run build:desktop` runs the same `scripts/precompress-assets.mjs` over `packages/app/dist` before electron-builder copies it to `app-dist`, so the desktop-served UI also gets `.br`/`.gz` siblings.
The desktop-managed daemon disables the bundled web UI by default (`PASEO_WEB_UI_ENABLED=false`) because the desktop app already ships the renderer as `app-dist`. Shipping the same assets again inside `@getpaseo/server` would duplicate the ~10.8 MiB install. Desktop packaging also excludes `node_modules/@getpaseo/server/dist/server/web-ui/**` from the packaged app.
## Built workspace packages
+4
View File
@@ -36,6 +36,10 @@ ordinary `WorkspaceTab` (`SheetTab` in the store) and is an `IsolatedBottomSheet
other sheet in the app, so it sits on the one app-wide stack: a sheet opened from any sheet lands on
top of it, and closing the top sheet (drag, Close, backdrop, or Android Back) uncovers the one below.
Because that stack is app-wide and hidden workspace screens stay mounted, a sheet is not presented
until its workspace has been on screen. A target opened in a workspace before the user gets there
waits in the store and appears on arrival.
A subagent chosen from the subagents list is the exception. It opens as a page of the list's own
sheet and replaces the list in place: Back returns to the list, Close ends both, and Open parent
closes the list, landing on the pane the list was opened from. The store's `selectSheetTab` describes
+11 -4
View File
@@ -447,10 +447,17 @@ wide layouts keep local geometry. That export is
what `patches/@gorhom+bottom-sheet+*.patch` adds.
A sheet whose owner may veto the close (unsaved work) passes `enableDismissOnClose={false}`. Every
close path then parks the sheet at index -1 with its content mounted; the owner hears
`onChange(-1)`, runs its guard, and either snaps back to 0 or drops its state, which unmounts the
sheet and takes it off the stack. Calling `dismiss()` on such a sheet bypasses the guard and
unmounts it, so its backdrop and Back press call `close()`.
close path then parks the sheet at index -1 with its content mounted; the owner runs its guard and
either snaps back to 0 or drops its state, which unmounts the sheet and takes it off the stack.
Calling `dismiss()` on such a sheet bypasses the guard and unmounts it, so its backdrop and Back
press call `close()`.
Run that guard from the wrapper's `onClosed`. Gorhom only calls `onChange` when a close ends at a
different index than the one it already recorded, and an interrupted mount animation leaves that
record at -1, so the close that follows is invisible: the sheet parks with its backdrop still over
the app, and every tap in the covered area is lost. `onClosed` watches the close animation settle at
the closed detent and reports it either way. Keeping `onChange` as well is harmless as long as the
guard is idempotent.
The wrapper must give Gorhom an object ref. Gorhom accepts a callback ref at the React boundary
but stores it in the modal queue and later reads `.current`; provider dismissal, replacement,
+2 -2
View File
@@ -57,8 +57,8 @@ Authoritative terminology. UI label wins. Don't invent synonyms; use what's here
- **Composer toolbar** — The bottom control row inside the composer input. Contains agent controls, attachment button, voice controls, and stop/send controls. Code: `leftContent`, `beforeVoiceContent`, and `rightContent` slots in `MessageInput` (`packages/app/src/composer/input/input.tsx`). Forbidden: "Status bar".
- **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. 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".
- **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](agent-lifecycle.md#the-queue-track) is a lane inside the composer itself. Code: `ComposerQueueTrack` (`packages/app/src/composer/queue/track.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 lists the messages the host holds until the turn ends. A queued message does not enter 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 it does for a person's queued message. 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).
+1 -1
View File
@@ -4,7 +4,7 @@ Paseo Hub is an explicit opt-in connection from one Paseo daemon to one Hub. Run
not register it with a Hub. The relationship begins only when a user runs
`paseo hub connect [url]` from the daemon machine with an explicit API key or matching stored CLI login.
The human CLI login and daemon relationship are separate identities. `paseo hub login [url]` stores a durable organization-scoped CLI credential keyed by normalized Hub origin under `PASEO_HOME`. Interactive login optionally connects the local daemon, then points to the Hub UI for trigger configuration; it does not scaffold or deploy configuration. `paseo hub init` remains the explicit triggers-as-code scaffold: it writes one self-contained organization trigger under `.paseo/triggers/`, validates it through the trigger API, and optionally installs it. `paseo hub deploy` validates and installs every trigger in that directory; passing `--project` keeps deploying the legacy project bundle instead. `paseo hub export [directory]` writes the active organization's current triggers in the same layout, using the active login unless another Hub or API key is selected. Origin resolution uses explicit command input, `PASEO_HUB_URL`, active login, then `https://hub.paseo.sh`. Connect uses exact-origin authority to request a one-time enrollment token, then passes only that token to the daemon. The daemon generates and persists its own relationship credential.
The human CLI login and daemon relationship are separate identities. `paseo hub login [url]` stores a durable organization-scoped CLI credential keyed by normalized Hub origin under `PASEO_HOME`. Interactive login optionally connects the local daemon, then points to the Hub UI for trigger configuration; it does not scaffold or deploy configuration. `paseo hub init` remains the explicit triggers-as-code scaffold: it writes one self-contained organization trigger under `.paseo/triggers/`, validates it through the trigger API, and optionally installs it. `paseo hub deploy` validates and installs every trigger in that directory; passing `--project` keeps deploying the legacy project bundle instead. `paseo hub export [directory]` writes the active organization's current triggers in the same layout, using the active login unless another Hub or API key is selected. `paseo hub run` dispatches a `manual.run` trigger through `POST /api/v1/manual-runs`, which takes inputs and prompt as one string; the CLI rejects what Hub would silently read as prompt text (`packages/cli/src/commands/hub/run/`). Origin resolution uses explicit command input, `PASEO_HUB_URL`, active login, then `https://hub.paseo.sh`. Connect uses exact-origin authority to request a one-time enrollment token, then passes only that token to the daemon. The daemon generates and persists its own relationship credential.
## Connection and authority
+8
View File
@@ -32,6 +32,11 @@ text controls do not type them. Android takes no claims: a focused `EditText`
types nothing for these combos. Keep the stream as the sole shortcut emitter: a command-owned
press is still observed by the window.
Register composer Return on every iOS device. Only a physical key press runs a
`UIKeyCommand`, so the on-screen keyboard's Return still inserts a newline. Do not
gate it on the interface idiom, which excludes iPhones with a keyboard attached, or
on `GCKeyboard`, which the command does not need.
The source spike used an iPad Pro 11-inch (M4) simulator on iOS 18.6 with a
`UITextView` first responder. Both `UIWindow.sendEvent` and the root controller's
`pressesBegan` received Cmd+B, Cmd+P and Escape. With Escape registered as a
@@ -48,6 +53,9 @@ through rebinds. For numeric injection, use AppleScript physical key codes (for
25 for 9); `keystroke "9"` did not deliver a digit in the QA session.
Simulator exposes a virtual `GCKeyboard` even with Connect Hardware Keyboard off.
Verify the iOS absence case on a physical iPhone.
Xcode 27.2 has Device Hub in place of Simulator. AppleScript keystrokes reach the
device only while its view has Mac focus. Give it focus with a real mouse click
(a `CGEvent`); keystrokes sent elsewhere drive Device Hub's own controls.
Never register Backspace: it would take deletion away from text fields. Changes
to the native module require a native rebuild; an over-the-air JavaScript update
+5 -5
View File
@@ -2,11 +2,11 @@
Use `MarkdownRenderer` for chat replies, file previews, plans, pull requests and changelog content. It uses `react-native-enriched-markdown` on iOS, Android and web. Keep source adaptation and renderer configuration in `components/markdown`; consumers supply Markdown and, when needed, its file location.
Native selection belongs to the library's text view. Keep an assistant message in one row so selection can cross paragraphs, headings and lists. Code blocks and tables use the library's native views and their selection behavior. Web uses browser selection over semantic HTML. Once its WASM parser is initialized, the library parses synchronously for the first commit of each mounted row; an empty interim row would corrupt virtualized measurements and move the reader. Chat owns paced reveal, the web render cap, message identity and list measurement. Native renders completed messages together. While streaming, it keeps closed blocks in one head view and updates a separate tail, then reunites the text on completion. See [native parsing cost](agent-stream-performance.md#native-parsing-cost) for the boundary and pacing constraints.
Native selection belongs to the library's text view. Keep an assistant message in one row so selection can cross paragraphs, headings and lists. Code blocks and tables use the library's native views and their selection behavior. Web uses browser selection over semantic HTML. Once its WASM parser is initialized, the library parses synchronously for the first commit of each mounted row; an empty interim row would corrupt virtualized measurements and move the reader. Chat owns paced reveal, the web render cap, message identity and list measurement. A completed message renders as one document. While streaming, the renderer keeps closed blocks in head parts and updates a separate tail, then reunites the text on completion. See [Markdown parsing cost](agent-stream-performance.md#markdown-parsing-cost) for the boundary and pacing constraints.
## Block spacing
Every block is separated by one gap, `density.blockGap`: 12 on compact layouts, 16 wider. Inside the library's text, every element style ends with that gap and the library drops it after the last block. Views stacked outside the library (Mermaid segments, streaming head and tail) use the same gap through `MarkdownBlockStack`. Do not give a block type its own margins; change the gap.
Every block is separated by one gap, `density.blockGap`: 12 on compact layouts, 16 wider. Inside the library's text, every element style ends with that gap and the library drops it after the last block. Views stacked outside the library (Mermaid segments, streaming head parts and tail) use the same gap through `MarkdownBlockStack`. Do not give a block type its own margins; change the gap.
## Links and images
@@ -26,7 +26,7 @@ The package keeps the npm tarball's layout, including its build output:
- Metro, Vitest and TypeScript load `lib/`, not `src/`. A JavaScript change edits `src/` and the matching `lib/module` and `lib/typescript` files.
- `android/generated` and `ios/generated` are checked-in codegen output (`includesGeneratedCode`). A change to a native component spec regenerates both; `scripts/postinstall-patches.test.mjs` compares them against the specs.
- `src/web/wasm/md4c.js` and `lib/module/web/wasm/md4c.js` are an Emscripten build of `cpp/md4c`. A parser change rebuilds them with upstream's `packages/core/cpp/wasm/build.sh`.
- `src/web/wasm/md4c.js` and `lib/module/web/wasm/md4c.js` are an Emscripten build of `cpp/md4c`, `cpp/parser` and `cpp/wasm`. A parser change rebuilds both, or web keeps the old behavior while iOS and Android change. Run `cpp/wasm/build.sh` with `OUT_DIR` set to `src/web/wasm`, in `emscripten/emsdk:4.0.10` with the `-s GROWABLE_ARRAYBUFFERS=0` line removed. That version reproduces the committed JavaScript glue and has no such setting. The `lib/module` copy is the Babel output of the new file.
- Upstream's Gradle, CMake and CocoaPods scripts detect upstream's own monorepo by the paths `packages/core` and a root `vendor/`. Do not add either path to this repository.
- `postinstall.mjs` downloads the tree-sitter grammars into the ignored `cpp/highlight/vendor/grammars` and `vendor/tree-sitter`. The `enriched-markdown` block in `packages/app/package.json` chooses the languages.
@@ -42,7 +42,7 @@ Some fork changes are backports. A sync past the upstream version drops them in
## Engine constraints
Math and video are disabled. Task lists and admonitions are enabled; task checkboxes are read-only. Source adaptation spaces adjacent empty GFM table delimiters before escaping prose spoiler delimiters and decodes entity text before the engine can discard it. Code spans and fences keep their literal source. Comment HTML is normalized to Markdown before parsing; details show their summary and body expanded.
Math and video are disabled. Task lists and admonitions are enabled; task checkboxes are read-only. Source adaptation spaces adjacent empty GFM table delimiters before escaping prose spoiler delimiters and decodes entity text before the engine can discard it. Code spans and fences keep their literal source. Comment HTML is normalized to Markdown before parsing; details show their summary and body expanded. `<br>` becomes a Markdown hard break, except inside a table, where a newline would end the row. There it becomes U+2028, and `cpp/parser/MD4CParser.cpp` turns U+2028 back into a line break in table cell text, never in code.
Mermaid fences use the existing isolated diagram runtime and fullscreen viewer. Web dispatches them through the library’s code-block override. Native has no block-renderer hook, so the renderer extracts only Mermaid fences and places the existing WebView host between library-rendered segments. This is the only block exception; see [native selection limitations](native-text-selection.md) for diagram grouping and leading inline images. Streaming keeps the last valid diagram visible while the next revision renders.
@@ -58,7 +58,7 @@ On iOS a newly mounted Markdown view paints empty for a frame or more after it i
Android measurements use a size-only, 512-entry LRU across view unmounts, matching the library’s existing iOS cache. Scrolling back through history can reuse layout sizes without parsing those rows again. Content, layout props and width identify each entry; font-scale changes and native layout invalidation discard affected sizes. The cache retains no views or spans.
The library determines how incomplete Markdown appears during streaming. Completed text uses the same component and engine as history. Find and scroll-to-message address source message ids; selection-copy understands semantic HTML and the web code component's copy metadata.
While `streaming` is true, `stabilizeStreamingMarkdown` in `components/markdown/streaming.ts` closes unfinished inline constructs (code spans, emphasis, strikethrough, links) and withholds incomplete block prefixes (headings, Setext underlines after paragraphs, list/task markers, empty quotes and admonitions, opening and partial closing code fences, unconfirmed tables, images and HTML tags/comments) before `prepareMarkdownSource` runs. Incomplete links render with link styling through `PENDING_MARKDOWN_LINK` without becoming interactive anchors or opening link actions until their destination closes. Completed text bypasses stabilization and uses the same component and engine as history. Find and scroll-to-message address source message ids; selection-copy understands semantic HTML and the web code component's copy metadata.
## Verification
+10
View File
@@ -72,6 +72,11 @@ matches:
</MenuSurface>
```
A row that cannot be drawn as a `MenuItem`, such as the compact Tunnel sub-row in the Scripts
menu, takes the same anchor, hover intent and navigation from `useMenuSubTrigger` and draws its
own look. Put the anchor on a `View` that spans the surface. A narrower anchor adds its inset to
the flyout's overlap.
Pages are data rather than nested children because the popover renders them as _siblings_ of the
root surface — a flyout nested inside the root's box would be clipped by its `overflow: hidden`.
Declaring them separately is what lets one model drive both presentations.
@@ -127,6 +132,11 @@ of backdrop between the two that belongs to neither surface, and every pixel of
dismiss the menu you are reaching for. Overlapping deletes the strip; don't reintroduce the gap
and try to cover it with a longer timer.
A flyout opens on the right of its row. If the right side has no room and the left has more, it
opens on the left, so a menu at the right edge of the window is not covered by its own flyout. It
chooses its side once, when it is first placed. Content that arrives later does not move it out
from under the pointer.
On top of that, a flyout opens after the pointer rests ~90ms, closes ~260ms after it leaves, and
cancels its own pending close while the pointer is inside it. The grace still matters because the
pointer crosses sibling rows on the way down into the flyout.
+4 -3
View File
@@ -146,9 +146,10 @@ definition, no longer eligible to begin.
- Panels whose gesture wrapper already owns visibility use `RetainedPanelActivity` to provide the
same active signal without adding another layout root. Persistent animations, timers, polling, and
shared clocks must subscribe to that signal and stop when their final visible consumer leaves.
- Synchronized step animations use one wall-clock-aligned source. Register a local shared value only
while its retained panel is active so hidden animated styles remain mounted without receiving clock
updates. Do not give every instance its own loop or leave hidden styles subscribed to the source.
- Synchronized step animations use one source. Do not give every instance its own loop. A hidden
instance stops running the source and keeps its place, because the active signal changes after the
panel has slid into view; see
[running-indicators.md](running-indicators.md#hidden-panels).
- Retention order and render order are separate concerns. LRU metadata may change on every switch;
keyed retained roots must keep a stable sibling order. Moving large retained roots triggered Fabric
Differ failures (`addViewAt` / `removeViewAt` view reuse) on Android.
+1 -1
View File
@@ -52,7 +52,7 @@ type Grant = {
A delegating principal can grant only authority it already possesses. A session may attenuate its principal's grants but cannot widen them.
Workspace-scoped grants require every resource-bearing operation and outbound observation to enforce the same workspace boundary. File preview currently accepts any daemon-readable regular file, so it must gain resource enforcement before workspace-specific access ships.
Workspace-scoped grants require every resource-bearing operation and outbound observation to enforce the same workspace boundary. File preview currently accepts any daemon-readable regular file outside daemon state (see [SECURITY.md](../SECURITY.md#local-daemon-trust-boundary)), so it must gain resource enforcement before workspace-specific access ships.
## Hub
+6 -2
View File
@@ -267,6 +267,10 @@ Plugin UI runs on desktop and mobile across multiple themes: color every `Text`
`theme.colors.foreground` or `theme.colors.foregroundMuted`, and size layout from `layout.compact`.
See `public-docs/plugins/reference.md`.
A plugin reads and arranges panes and tabs through `PluginWorkspaceLayout`. Its host,
`packages/app/src/plugins/workspace-layout/`, is a facade over the layout store and `workspace-tabs`,
so add behavior to those owners and keep layout mechanics out of the SDK types.
### SDK import boundaries
Classify every SDK export before adding it. All client entry points and implementations live under
@@ -1018,8 +1022,8 @@ payload that cannot be rendered intact. The daemon advertises this RPC through
`addSlashCommand` registers an agent- or workspace-context command in the composer. The
callback runs in the app, receives the trimmed text after the command name as `args`, and receives
the same `paseo`, `rpc`, `openScreen`, workspace, agent, and `openPanel` capabilities as the matching
Command Center callback.
the same `paseo`, `rpc`, `openScreen`, workspace, agent, and `workspaceLayout` capabilities as the
matching Command Center callback.
```ts
client.addSlashCommand({
@@ -0,0 +1,89 @@
# Online client replacement: timeline recovery
Verified on macOS arm64 with Node 22.20.0, Chromium 145 (Playwright), and a real isolated daemon. Replies use the deterministic test provider; no external AI API is involved.
## Reproduction
1. Open two chats on one host and return to the first.
2. Delay the active connection's real pong frames by 1 second, forwarding all real traffic, and wait for a measured liveness RTT.
3. Add another direct endpoint for the same daemon.
4. Advance the browser clock in 10-second steps. Each step waits for real delayed heartbeat replies and the public probe-cycle completion barrier, including replacement handshakes. The production selector and its timer constants are unchanged.
5. Verify that every observed host snapshot stays online with a client, then confirm exactly one client-generation change to the faster endpoint.
6. Require the Reconnecting alert to disappear within 3 seconds and verify a new message in the visible chat.
7. Commit a message to the hidden second chat before reopening it. Verify that message is recovered, then verify another live message.
The two paths are localhost and 127.0.0.1 to the same daemon. The test does not force host state or replace a private client field. It controls browser time, not the daemon clock or real socket responses. Subscription assertions require the needed agents without requiring all other agents to be absent; exact matching remains the shared helper's default. The test has a 180-second timeout and a bounded clock-step budget allowing one candidate backoff. Observers, handles, timers, and scenario data are cleaned up even on failure.
## Before: exact final test source
Temporarily remove only the production `sync.setConnected(...)` seed, run the final regression, and restore the source in a `finally` block. The host remains online and changes to generation 2, but Reconnecting does not settle:
```text
Error: expect(locator).toHaveCount(expected) failed
Locator: getByRole('alert').filter({ hasText: 'Reconnecting' })
Expected: 0
Received: 1
Timeout: 3000ms
1 failed
```
The frame below is extracted without modification from that final RED trace while the assertion was waiting, before fixture cleanup.
![Before: Reconnecting remains after online replacement](before.jpeg)
## After
Restore the production seed without changing the test files, then run:
```sh
npm run test:e2e --workspace=@getpaseo/app -- \
e2e/browser/viewed-agent-timelines.spec.ts \
--grep 'online connection replacement|visible chat reports updating until reconnect' \
--workers=1
```
```text
✓ an online connection replacement keeps every open chat synchronized (1.6m)
✓ a visible chat reports updating until reconnect catch-up completes (35.9s)
2 passed (2.3m)
```
The online replacement case previously took 4.8 minutes with wall-clock probe waits. The final controlled-clock run takes 1.6 minutes. [Recorded hashes](red-green.json) confirm both test files are identical between final RED and GREEN and the production source was restored exactly.
![After: hidden history recovers and both chats receive messages](after.png)
## Other checks
```sh
npm run typecheck
npm run lint -- packages/app/e2e/browser/viewed-agent-timelines.spec.ts packages/app/e2e/support/helpers/timeline-delivery.ts
npm run format
```
Whole-workspace typecheck exited 0. Changed-file lint reported `Found 0 warnings and 0 errors.` Formatting passed.
The original runtime fix is unchanged by this test follow-up. Its previous native validation remains: both unmodified and fixed renderers exported with `PASEO_WEB_PLATFORM=electron npm exec -- expo export --platform web`; server dependencies and desktop main built through repository scripts; both packaged locally with `electron-builder --config electron-builder.yml --publish never --mac --arm64 --dir -c.mac.notarize=false`, with certificate discovery disabled.
The existing `packages/desktop/e2e/packaged-app-smoke.js --app <built-app>` passed for both packages with fresh temporary user data/daemon homes and loopback ports:
```text
Packaged desktop smoke: real app renderer and preload bridge loaded
Packaged desktop smoke: renderer-started desktop daemon reported running
Packaged desktop smoke: every built-in plugin started
Packaged desktop smoke: running bundled CLI shim daemon status
Packaged desktop smoke: creating terminal through bundled CLI shim
Packaged desktop smoke: terminal hook command completed
Packaged desktop smoke passed: real renderer and preload loaded; renderer-started desktop daemon;
CLI shim daemon status and terminal smoke succeeded
```
The final summary omits ephemeral PID/listen values. The native smoke establishes packaged startup and terminal functionality, not native reconnect coverage.
## Coverage limits
- Web: real browser/daemon regression, with controlled browser scheduling, before and after.
- macOS desktop: prior arm64 packaging and native startup/CLI/terminal smoke of the unchanged runtime fix.
- iOS, Android, Windows desktop, Linux desktop: not tested.
- External relay transport and a real provider turn: not tested by this regression.
- The test requires eventual history recovery; it does not change the product's hidden-chat subscription policy or prohibit every transient toast frame.
- These are local results. No full-suite or GitHub CI pass is claimed.
Binary file not shown.

After

Width:  |  Height:  |  Size: 128 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 57 KiB

@@ -0,0 +1,18 @@
{
"production_source_restored": true,
"test_sha256": {
"packages/app/e2e/browser/viewed-agent-timelines.spec.ts": "1857d0ca187648d8377557cd82428a64546530795cf884c7474e921a1118c003",
"packages/app/e2e/support/helpers/timeline-delivery.ts": "23d0adb9f92daac6d0841d584abb7aa272a2981861d7d211c8213e98a9af90da"
},
"red": {
"result": "expected failure",
"assertion": "Reconnecting alert expected 0, received 1",
"timeout_ms": 3000
},
"green": {
"passed": 2,
"online_replacement_duration": "1.6m",
"ordinary_reconnect_duration": "35.9s",
"total_duration": "2.3m"
}
}
+173
View File
@@ -0,0 +1,173 @@
# Running indicators
Three things animate for as long as an agent works: the six-dot loader in the turn footer
(`components/synced-loader`), the status ring on a running workspace or tab
(`components/status-ring`), and the highlight that sweeps a running tool call's label
(`components/label-shimmer`). A turn can run for an hour, so each of them must cost nothing on the
thread that runs React.
## The rule
A perpetual animation is handed to the platform's animation engine once and then left alone. It
does not go through React state, `requestAnimationFrame`, a timer per frame, or a Reanimated shared
value.
`components/indicator-motion` owns the two pieces every indicator shares:
- `useIndicatorMotion()` says what an indicator does now. Ask this hook; do not read reduced motion
or visibility yourself.
- `moving`: it runs.
- `held`: nobody can see it, in a retained panel that is not showing or in an app in the
background. It runs nothing and keeps its place.
- `resting`: the system asks for reduced motion. It draws its resting frame and runs nothing.
- The driver: `loop.web.ts` on web, `clock.ts` on native.
Animate only `transform` and `opacity`. Anything else is painted on the main thread every frame.
## Hidden panels
A phone's sidebar slides into view before its panel counts as showing: the panel's active signal
changes when the slide settles, never during it (see [mobile-panels.md](mobile-panels.md)). An
indicator that changes what it draws on that signal changes it in front of the user. A held ring
that drew its resting position jumped to the running position at the end of every slide.
So on native a held indicator stays bound to its clock and stops running it:
- The clock and the loader's ticker count the time they have run, and hold it while nothing runs
them. They are never set back to zero or to the wall clock.
- While another panel runs the clock, a held view follows it. Measured on an Android emulator with
six held rings behind a running chat, the app drew the same frames a second as with the rings
unbound, and CPU on each thread differed by less than it does between two runs.
- While nothing runs the clock, a held view costs nothing: behind an idle chat the app draws no
frames.
- One commit can stop the last moving indicator and start another, as when the sidebar replaces the
chat. The clock stops after the commit, so it counts through that without a restart.
Web does not do this: a held indicator on web cancels its loop and draws its resting frame.
## Frames
Keeping the animation off the React thread does not make it free. Every time an indicator moves,
the platform composes and presents the whole window again: `RenderThread` on Android, the GPU
process and macOS's WindowServer on desktop. An indicator that moves with the display holds the
window at 60 or 120 frames a second for as long as an agent runs, with nothing else changing.
So an indicator moves in steps, and the step count is its frame rate:
| Indicator | Positions | Frames a second |
| ----------------- | ------------------------------------------------------ | --------------- |
| Loader | 6 per 950 ms | 6 |
| Status ring | 27 per 900 ms (`STATUS_RING_STEPS`) | 30 |
| Tool-call shimmer | 30 to 69 per pass, by label length (`getShimmerCycle`) | 30 |
The ring is the one that matters most: it is on screen in the sidebar and the tab bar whenever any
agent runs, including while you read an idle chat. Its steps are positions the smooth turn passes
through, 1.2 px apart on a 12 px ring. Fewer steps start to read as ticking and buy little: measured
on an Android emulator with one ring on screen, the app used 12–15% of a core with a smooth ring,
8–10% with 27 steps, and 6–7% with either 18 or 12, because the native driver's own tick is what is
left.
Two indicators only share frames when their steps turn over at the same instants. So the ring and
the shimmer move on one grid of steps, `INDICATOR_STEP_MS` in `indicator-motion/steps.ts`: one step
every 1000/30 ms, counted from one origin. A chat with a running tool call in view then draws 30
frames a second for both. A shimmer whose steps fell between the ring's would hold the window at 60.
- The shimmer's pass is a whole number of steps, the one closest to its smooth length. The pass
changes by at most half a step, 17 ms in 1 to 2.3 seconds.
- Each shimmer still starts its own pass when it appears, so the highlight enters from the left.
The pass starts at the beginning of the current step, not at mount.
- The loader's steps are 158 ms long and are not on the grid. Measured in Chromium, a running turn
draws about 36 frames a second: 30 for the ring and the shimmer, the rest for the loader and the
elapsed counter.
## Web
`useIndicatorLoop` runs a keyframe loop through the Web Animations API (`element.animate`). The
compositor carries it; the page runs no script, restyles nothing and repaints nothing to keep it
moving.
Do not declare these as CSS `@keyframes`. A CSS animation fires `animationiteration`, React listens
for it at the root, and Chromium wakes the main thread around the end of every cycle of every CSS
animation in a document that has such a listener. Measured on a quiet running turn: 13 main-thread
commits and 14 style recalculations a second with `@keyframes`, against the 3 commits a second the
page produces with nothing moving. The Web Animations API has no iteration event.
Two more reasons the stylesheet route does not work here:
- Unistyles owns style conversion on web, so React Native Web's `animationKeyframes` is ignored.
- React Native Web's `StyleSheet.create` validation deletes `animationName` in development.
Indicators that must move together use `phase: "shared"`, which starts the loop at the document
timeline's origin instead of at mount. Every ring and every loader is then at the same point of its
cycle wherever and whenever it mounted. `phase: "own"` starts the loop at the beginning of the
current grid step, so its steps still turn over with the shared loops. A stepped animation sets its easing on the keyframes:
`step-end` to hold each keyframe until the next, `steps(n)` to cross between two keyframes in `n`
even steps. The compositor then draws a frame when a step changes and none in between.
## Native
Reanimated commits a cloned shadow tree on the UI thread for every frame a shared value changes.
For a transition that is fine. For an indicator that runs for an hour it was 22–28% of a core on
the UI thread of an Android emulator.
React Native's own `Animated` with `useNativeDriver: true` updates the view from the native driver
and commits nothing. `clock.ts` builds a clock out of it: a linear timing at one unit per
millisecond is the time since the clock started. `Animated.modulo` and `interpolate` turn the clock
into a rotation or a translation, all inside the native driver.
The timing counts in spans of ten minutes. The end of a span is the one event that reaches the JS
thread, which starts the next span where that one ended, so a cycle keeps its place from one span to
the next.
The native driver owns the clock's value. The JS thread starts and stops the counting and never
sets the value, so a stopped clock keeps the value its views show. When the clock stops, the driver
reports the value it stopped at, and the next start counts on from it.
Do not drive the clock with a decay. A decay that never slows counts time without spans, but the
driver ends a decay when its value moves less than 0.1 between two frames, whatever the
deceleration. Two frames that carry the same millisecond are enough, and then every indicator on
the clock freezes. Starting the decay again from the JS thread shows as a pause and a jump each
time.
Android replays a timing as 60 positions a second at any refresh rate, and iOS interpolates between
them. Every cycle on the clock is stepped at 30 positions a second, so this does not show. A cycle
without steps would move 60 times a second on a 120 Hz Android display.
`cycle(periodMs, { steps })` holds the position at each step. The driver still ticks every frame,
but a view whose transform did not change is not invalidated, so nothing is drawn between steps.
The native clock starts on the frame where the driver picks it up, so two clocks started at
different times turn their steps over on different frames. That is why the shimmer rides
`sharedIndicatorClock`, the rings' clock, with `phase: "own"`: its pass starts at the clock's
current step. The JS thread works out that step from the time it started the clock and the value
the clock started from. The driver
starts the clock a frame or two later, so a pass can start one step early or late. The band starts
one band width outside the label, so this does not show.
The loader changes six times per cycle, so it does not ride the frame clock. `step-ticker.ts` wakes
the JS thread once per step and publishes the step into a native `Animated.Value`. A wake-up that
arrives late publishes the step that is current by then, so the loader never drifts. Every loader
reads the one value, so they all show the same step.
Do not apply Unistyles dynamic styles to these `Animated.View`s; see
[unistyles.md](unistyles.md#reanimated-animatedview--dynamic-styles-crashes).
## Measuring
`e2e/browser/running-indicators.spec.ts` holds the web budgets: animation-frame callbacks, style
recalculations, paints and main-thread commits per second on a quiet running turn, React renders of
the indicator components, the loader's and the ring's cadence, the frames a ring draws beside an
idle chat and beside a running tool call, whether the shimmer moves only on the ring's frames,
reduced motion, and a hidden tab. Run it with
`PASEO_RUNNING_INDICATORS_FRAMES=1` to also save reference frames of every indicator at fixed
points of its cycle, for a pixel comparison across a change.
To hold a turn in the running state without streaming, send the mock load-test agent
`Hold a running shell tool call for <N>ms`.
On Android, compare `adb shell dumpsys gfxinfo <package>` frame counts and per-thread CPU from
`/proc/<pid>/task/*/stat` over a fixed window. A regression in how an indicator is driven shows up
on the UI thread (`sh.paseo.debug`); one in how often it moves shows up as frames rendered and on
`RenderThread`. `dumpsys gfxinfo <package> framestats` lists each frame's vsync, which shows whether
the steps are evenly spaced. On the emulator gfxinfo counts every frame that follows an idle vsync
as janky; read the frame count and the percentiles instead.
-141
View File
@@ -1,141 +0,0 @@
# Service Proxy
Paseo proxies HTTP traffic to services running inside your workspaces. Localhost service URLs are always enabled; optional public aliases and a separate service-only listener can be layered on through config.
## How it works
When a `paseo.json` script of `"type": "service"` starts, Paseo assigns it a local port and registers a route in the service proxy. Incoming requests whose `Host` header matches the script's generated hostname are forwarded to that port. HTTP requests, WebSocket upgrades, and service health checks select the reachable IPv4 or IPv6 loopback address. Services can bind to `127.0.0.1` or `::1` without changing their proxy URL.
The generated hostname is built from the script name, branch, and project:
```
<script>--<branch>--<project>.localhost
```
If the branch is `main` or `master`, the branch segment is omitted:
```
<script>--<project>.localhost
```
**Example:** a script named `dev` in the `miniweb` project on branch `feature/auth` would be reachable at:
```
dev--feature-auth--miniweb.localhost
```
Local and public routes use one combined leftmost label (`script--branch--project`). This keeps the hostname compatible with normal single-level wildcard DNS and TLS. If the combined label would exceed DNS's 63-character label limit, Paseo truncates it with a deterministic hash suffix to avoid collisions.
## Managing workspace scripts
Configured `paseo.json` scripts can be managed without addressing their backing terminal directly:
```bash
paseo script ls [--cwd <path> | --workspace <workspace-id>]
paseo script start <name> [--cwd <path> | --workspace <workspace-id>]
paseo script stop <name> [--cwd <path> | --workspace <workspace-id>]
```
The commands return the same script metadata shown by the workspace: lifecycle, service port, proxy URLs, health, exit code, and supervised terminal ID. `stop` terminates the managed terminal rather than only removing the proxy route, so normal script lifecycle cleanup remains authoritative. MCP exposes matching `list_workspace_scripts`, `start_workspace_script`, and `stop_workspace_script` tools; those require an explicit workspace ID.
## Configuration
Add a `serviceProxy` block under `daemon` in `~/.paseo/config.json`:
```json
{
"version": 1,
"daemon": {
"serviceProxy": {
"listen": "0.0.0.0:8080",
"publicBaseUrl": "https://paseoapps.my.domain.com"
}
}
}
```
| Field | Required | Description |
| --------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| `listen` | No | Starts a separate service-only listener at this address. If omitted, services are still reachable on the daemon listener via localhost hosts. |
| `publicBaseUrl` | No | Adds public service host aliases and public service links. If omitted, links use localhost addresses only. |
`enabled` is accepted for old configs but no longer enables a mode. `enabled: false` suppresses optional `listen`/`publicBaseUrl` layers only; localhost service proxying remains always enabled.
## DNS and reverse proxy setup
For generated URLs to be reachable, you need wildcard DNS pointing to the machine running the Paseo daemon.
**Example:** to expose services at `https://dev--miniweb.paseoapps.my.domain.com` where the daemon host is `10.1.1.1`:
1. Configure a wildcard DNS record:
```
*.paseoapps.my.domain.com → 10.1.1.1
```
2. Set `publicBaseUrl` to `https://paseoapps.my.domain.com` in your config.
3. If you put a reverse proxy (nginx, Caddy, Traefik, etc.) in front of Paseo, point it at either the daemon listener or the optional service-only listener and ensure it forwards the `Host` header unchanged. The proxy uses the `Host` header to route requests to the correct service — rewriting it will break routing.
Public service URLs expose the workspace service itself. Daemon password authentication protects daemon APIs; it does not protect proxied dev services.
If the same reverse proxy serves the daemon web UI over HTTPS, it must also set `X-Forwarded-Proto` so the web UI can auto-connect with `wss://`. The daemon trusts forwarded headers from loopback proxies by default. If your proxy reaches the daemon from another address, configure the proxy ranges explicitly:
```json
{
"version": 1,
"daemon": {
"trustedProxies": ["loopback", "172.16.0.0/12"]
}
}
```
`PASEO_TRUSTED_PROXIES` accepts the same comma-separated values, for example `loopback,172.16.0.0/12`. Use `true` only when the final trusted proxy overwrites client-supplied `X-Forwarded-*` headers.
Nginx example:
```nginx
server {
listen 443 ssl;
server_name *.paseoapps.my.domain.com;
location / {
proxy_pass http://10.1.1.1:8080;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
```
Nginx's `$host` drops the port. If you terminate on a non-default port, use `$http_host` instead so the port survives — that is what "forwards the `Host` header unchanged" means here.
## Forwarded headers
Paseo sets these when it forwards a request to a workspace service:
| Header | Value |
| ------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| `X-Forwarded-Host` | The `Host` header verbatim, including the port when the client used one |
| `X-Forwarded-Proto` | The request scheme (`http` on the WebSocket upgrade path) |
| `X-Forwarded-For` | The immediate peer address. Replaces any existing chain, so behind your own reverse proxy this is the proxy's address, not the client's |
| `X-Forwarded-Port` | The port from the `Host` header when it has one, otherwise whatever your proxy already set |
`X-Forwarded-Port` follows the same trust rule as `X-Forwarded-Host`: the authority Paseo observed wins. When the `Host` header carries a port, that port is reported and replaces any inbound `X-Forwarded-Port`, so a client cannot forge one. When `Host` carries no port there is nothing to observe, so a value your reverse proxy set survives untouched — that is the case where nginx's `$host` drops the port and `X-Forwarded-Port` is the only source. Paseo never derives the port from the scheme. Any other `X-Forwarded-*` header your proxy sends is passed through untouched.
Services that build absolute URLs should prefer `Host` or `X-Forwarded-Host`.
### The forwarded authority is not authenticated
Route lookup normalizes the port away before matching a service hostname, so a client can address the daemon with any port in `Host` and still reach the service. That port is what lands in `X-Forwarded-Host` and `X-Forwarded-Port`. Paseo also does not check whether an inbound `X-Forwarded-Port` came from a proxy in `trustedProxies` — when `Host` carries no port, a client-supplied value is passed through.
Treat the forwarded authority as client-influenced input. A service that builds password reset links, absolute redirects, or cached URLs from it should pin its own public origin in configuration rather than deriving one from request headers. This is not specific to `X-Forwarded-Port`: the `Host` header has always carried a client-chosen port.
## Environment variables
The listen address and public base URL can also be set via environment variables, which take precedence over `config.json`:
| Variable | Description |
| ------------------------------------- | ------------------------------------------------------------------------- |
| `PASEO_SERVICE_PROXY_ENABLED` | Compatibility shim; `false` suppresses optional public/listen layers only |
| `PASEO_SERVICE_PROXY_LISTEN` | Starts the optional service-only listener, e.g. `0.0.0.0:8080` |
| `PASEO_SERVICE_PROXY_PUBLIC_BASE_URL` | Adds public service aliases and links |
+2
View File
@@ -148,6 +148,8 @@ Run it locally with the same command owned by the Ubuntu `desktop-tests` require
npm run test:e2e:browser-tabs --workspace=@getpaseo/desktop
```
Its last step is the per-tab browser profile journey. It creates colored profiles inline, verifies isolation across an Electron relaunch and `target="_blank"` profile inheritance, then tests clearing, renaming, and removing profiles through Settings. Run only that journey with `PASEO_DESKTOP_BROWSER_PROFILES_ONLY=1`. Set `PASEO_DESKTOP_BROWSER_E2E_ARTIFACT_DIR` to keep its screenshots and `profiles.json`.
## Test organization
- Collocate tests with implementation: `thing.ts` + `thing.test.ts`
+72 -14
View File
@@ -5,15 +5,9 @@ Agent chat delivery has two paths:
1. **Live stream** — `agent_stream` WebSocket messages for immediacy. These may be delta-shaped lifecycle updates.
2. **Authoritative history** — `fetch_agent_timeline_request` for correctness. This always returns full projected timeline items, never lifecycle deltas.
The daemon retains projected items in memory. Each source event advances the stream sequence,
then replaces the previous tool state or merges into the current text item. Intermediate payloads
are never retained for history or catch-up. Provider history is the durable transcript authority
and rebuilds the projection when an agent resumes.
Pagination bounds each read, not total resident history. Active and idle agents retain their
projected transcript; archive releases it and later history reads rebuild it from the provider.
Streaming overhead must remain proportional to the retained transcript. Cumulative text snapshots
must be released after their deltas have been consumed.
Pagination bounds each read, not total resident history. Streaming overhead must remain
proportional to the retained transcript. Cumulative text snapshots must be released after their
deltas have been consumed.
The invariants are:
@@ -32,6 +26,50 @@ bounded item is used for runtime timeline rows and live stream events. Provider
applies the same rule so reopening an agent cannot restore an oversized payload. Fetches apply it
again to assistant and reasoning rows the projection merges from many chunks.
## Owned history
The daemon owns each agent's history in `AgentTimeline`
(`packages/server/src/server/agent/timeline/`): one ordered history per agent, with each provider
child's descriptor and history in a child scope of the same agent. Each source event advances the
stream sequence, then replaces the previous tool state or merges into the current text item.
Intermediate payloads are never retained for history or catch-up.
History is append-only: rewind, import, reload and archive never delete or rewrite a row. Only
deleting the agent, or a provider removing one of its own children, deletes history.
- **Rewind** retires a range of rows. They leave the conversation and stay stored, in the same
epoch. See [Rewind retires rows](#rewind-retires-rows).
- **Provider history** is imported only into an agent that has no history. After that, resume
does not read it. Reload agent and Unarchive require the provider history to start with the
same prompt IDs and text in order. They then append whole new turns, starting at the next
prompt. Existing replies, including partial replies, stay as recorded. If the prompts differ,
for example because the provider stored expanded attachment text, the chat stays unchanged and
Paseo reports a mismatch. A provider child Paseo already holds, listed or retired, is never imported again.
- **Archive and reload** keep the history and the provider children. An archived chat reads them
without its provider. Opening a stored agent that has no provider session to resume starts its
first session on the same history.
- **Delete** removes the agent's history and every child's, retired ones included, before the
agent record. If the history cannot be removed, the request fails and the agent stays listed. The
user can keep using it and delete it again.
`epoch` is the stored history's identity, minted once when the history is created.
`AgentTimeline` serializes every operation of one agent, child scopes included, and keeps its
state in an `AgentTimelineBackend`: the sequence, the rows and retirements, prompt identities, the
open rewind, and the children. The backend contract suite is `agent-timeline.test.ts`, run over
`TIMELINE_CONTRACT_BACKENDS` in `timeline/testing.ts`. The daemon uses the SQLite backend in the
[daemon database](data-model.md#daemon-database). History, retirements, the open rewind, and
provider children survive a daemon restart in the same epoch, so clients keep their cursors. A
closed or archived agent holds no history in memory. Each fetch reads the page from the database
and starts no provider. An internal agent, such as the one that writes a commit message, keeps its
history in a memory backend instead, so it leaves nothing on disk. The memory backend also serves
tests.
An open rewind is stored with the history. Resuming an agent whose history holds one settles it
before the agent takes prompts: a recorded provider cut is committed, and an unknown outcome is
judged from the resumed provider history. When that history proves nothing, the rewind stays open
and the agent refuses prompts with the unknown-outcome error.
## Presence is not delivery
Client heartbeat reports presence:
@@ -134,9 +172,10 @@ is offline and until a reconnected chat's check answers, so an unchanged chat ne
toast. Returning from background on a socket that stayed connected shows nothing until the check
answers: the chat stayed subscribed, so a slow answer is no reason to doubt it, and a socket that
died without closing fails the foreground liveness probe and becomes a reconnect. Updating messages
appears for a chat that is behind, until the fetch completes, and for an opened chat whose check is
still unanswered `FRESHNESS_CHECK_QUIET_MS` after it was sent. That delay measures the daemon, so it
starts at the request: on a cold start the cache read alone can take longer. Socket connectivity
appears for a chat that is behind, until the fetch completes, and for an opened chat whose check or
cursorless initial tail catch-up (such as a display-only cache) is still unanswered
`FRESHNESS_CHECK_QUIET_MS` after the subscribe request was sent. That delay measures the daemon, so
it starts at the request: on a cold start the cache read alone can take longer. Socket connectivity
alone cannot certify that the displayed conversation is current. The timeline owner publishes freshness; the view renders it without a toast timer or a
separate resume workflow.
@@ -173,7 +212,7 @@ or retry backoff. This cannot keep a mobile socket alive after the operating sys
bookkeeping without replacing timeline arrays, preserving an upward-scrolled viewport.
- When the page overlaps or is adjacent to the local end cursor, only projected items newer than
that cursor are applied. Already-covered rows are not replayed.
- A true middle gap, epoch change, or rewind atomically replaces stale canonical history with the
- A true middle gap or epoch change atomically replaces stale canonical history with the
latest tail. The replacement reconciles positioned live rows beyond its coverage and unresolved
local submissions; it never retains two discontiguous canonical ranges.
@@ -186,6 +225,24 @@ history replay. The pending approval UI can hide that tool from presentation, bu
must retain its position. Creating a new history card on rejection places it after the prompt that
rejected it; changing steer-event ordering would also put new assistant output before that prompt.
## Rewind retires rows
A conversation rewind commits a retirement `{ seq, retireFromSeq }`: active rows anchored in
`[retireFromSeq, seq)` leave the conversation, and `seq` is the retirement's own position in the
sequence. The provider children spawned by retired tool calls, and their descendants, are retired
in the same commit. They leave the listing, keep their history, and drop late provider events.
Clients learn of a retirement live through `agent.timeline.rewind`, and on pages through
`retirements`, which lists the retirements whose `seq` lies inside the page's span. The client
drops the rows it holds in that range; rows without a timeline position are unechoed local sends
and stay. Retired ranges and the retirement's `seq` count as covered, so forward cursors advance
through them. Tail, before and prompt-jump pages are served from active rows, so one served before
a retirement the client already applied is stale and is refetched (`viewed-timeline-sync.ts`).
Clients without `timeline_rewind_operations` cannot drop retired rows. For them the session derives
a wire epoch that changes with each retirement, so they take the destructive replacement they
always took on rewind. The shim is tagged `COMPAT(timelineRewindOperations)`.
## Provider child history
Child transcripts use the same projected-page reconciliation as the main conversation. The client
@@ -379,7 +436,7 @@ the draft-create handoff is the one boundary that also permits the legacy canoni
arrived first. Generic reducers and consumers do not reimplement message identity matching.
Ordinary bootstrap, same-epoch reset, and catch-up replacement preserve unmatched locally submitted
rows because a provider may never echo them. A known epoch change or rewind replaces history and
rows because a provider may never echo them. A known epoch change replaces history and
drops acknowledged local rows omitted by the new canonical epoch; every transaction not yet
acknowledged by the provider, and no other local row, crosses that destructive boundary. A cold
reset without an existing epoch is destructive because the client has no continuity anchor.
@@ -395,6 +452,7 @@ canonical assistant prefix, it stays in the head lane. No row may be returned in
## Relevant code
- Server owned history: `packages/server/src/server/agent/timeline/`
- Server live stream forwarding: `packages/server/src/server/session.ts`
- App sync planning: `packages/app/src/timeline/timeline-sync-plan.ts`
- App viewed-agent synchronization: `packages/app/src/timeline/viewed-timeline-sync.ts`
+1 -1
View File
@@ -1 +1 @@
sha256-34bUBmRmjekbUSp93597GLTmSWKt23TCHaK3ViXG+iU=
sha256-04BfmBEaEZy3ohSi3Z8S3/a3xBsLKhls+8mcjJ0Y2/A=
+21 -1
View File
@@ -46,6 +46,9 @@
"react-dom": "19.2.3",
"typescript": "^5.9.3",
"ws": "^8.20.0"
},
"engines": {
"node": ">=22.16.0"
}
},
"node_modules/@0no-co/graphql.web": {
@@ -39721,6 +39724,9 @@
"typescript": "^5.2.2",
"vitest": "^4.1.6",
"zx": "^8.8.5"
},
"engines": {
"node": ">=22.16.0"
}
},
"packages/cli/node_modules/@vitest/expect": {
@@ -39969,6 +39975,7 @@
"license": "Apache-2.0",
"dependencies": {
"@getpaseo/cli": "*",
"@getpaseo/client": "*",
"@getpaseo/server": "*",
"electron-log": "^5.4.3",
"electron-updater": "^6.6.2",
@@ -40649,7 +40656,7 @@
"@playwright/test": "^1.56.1",
"@types/express": "^4.17.20",
"@types/markdown-it": "^14.2.0",
"@types/node": "^20.9.0",
"@types/node": "^22.16.0",
"@types/qrcode": "^1.5.6",
"@types/uuid": "^9.0.7",
"@types/ws": "^8.5.8",
@@ -40657,6 +40664,9 @@
"cross-env": "^10.1.0",
"tsx": "^4.6.0",
"vitest": "^4.1.6"
},
"engines": {
"node": ">=22.16.0"
}
},
"packages/server/node_modules/@esbuild/aix-ppc64": {
@@ -41104,6 +41114,16 @@
"@types/mdurl": "^2"
}
},
"packages/server/node_modules/@types/node": {
"version": "22.20.5",
"resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.5.tgz",
"integrity": "sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==",
"dev": true,
"license": "MIT",
"dependencies": {
"undici-types": "~6.21.0"
}
},
"packages/server/node_modules/@vitest/expect": {
"version": "4.1.6",
"resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.6.tgz",
+4 -1
View File
@@ -99,7 +99,7 @@
"web": "npm run web --workspace=@getpaseo/app",
"dev:desktop": "cross-env PASEO_LISTEN=127.0.0.1:6768 npm run dev --workspace=@getpaseo/desktop",
"dev:win:desktop": "npm run dev:win --workspace=@getpaseo/desktop",
"build:desktop": "npm run build:app-deps:clean && cd packages/app && cross-env PASEO_WEB_PLATFORM=electron npx expo export --platform web && cd ../.. && npm run build --workspace=@getpaseo/desktop --",
"build:desktop": "npm run build:app-deps:clean && cd packages/app && cross-env PASEO_WEB_PLATFORM=electron npx expo export --platform web && cd ../.. && node scripts/precompress-assets.mjs packages/app/dist && npm run build --workspace=@getpaseo/desktop --",
"db:query": "npm run db:query --workspace=@getpaseo/server --",
"cli": "./scripts/dev-home.sh npx tsx packages/cli/src/index.js",
"version": "npm run version:sync-internal && npm run fdroid:changelogs && npm run release:prepare && git add -A",
@@ -172,5 +172,8 @@
"tiny-async-pool": {
"semver@^5": "5.7.2"
}
},
"engines": {
"node": ">=22.16.0"
}
}
@@ -13,6 +13,13 @@ import {
import { expectNearBottom, scrollChatAwayFromBottom } from "../support/helpers/agent-bottom-anchor";
import { holdRewindCompletion } from "../support/helpers/agent-timeline-gate";
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
import { userScrollsTimelineToHistoryStart } from "../support/helpers/timeline-pagination";
import {
closeWorkspaceAgentTab,
fetchAgentArchivedAt,
primeAdditionalPage,
resetSeededPageState,
} from "../support/helpers/archive-tab";
async function completeSubmittedTurn(
page: Page,
@@ -48,26 +55,98 @@ async function expectTurnCompletesNormally(
await expectAgentIdle(page);
}
async function openAgentOnAnotherClient(
page: Page,
agent: Awaited<ReturnType<typeof seedMockAgentWorkspace>>,
): Promise<void> {
await primeAdditionalPage(page);
await resetSeededPageState(page);
await openAgentRoute(page, agent);
await expectComposerVisible(page);
}
/** The prompts the chat shows, in order, each exactly once. */
async function expectPrompts(page: Page, prompts: string[]): Promise<void> {
const messages = page.getByTestId("user-message");
await expect(messages).toHaveCount(prompts.length);
await expect(messages).toContainText(prompts);
}
async function reloadAgentFromTabMenu(page: Page, agentId: string): Promise<void> {
const tabId = `workspace-tab-agent_${agentId}`;
await page.getByTestId(tabId).filter({ visible: true }).first().click({ button: "right" });
await page.getByTestId(`workspace-tab-context-agent_${agentId}-reload-agent`).click();
}
async function archiveAgentByClosingTab(
page: Page,
agent: Awaited<ReturnType<typeof seedMockAgentWorkspace>>,
): Promise<void> {
await closeWorkspaceAgentTab(page, agent.agentId);
await expect.poll(() => fetchAgentArchivedAt(agent.client, agent.agentId)).not.toBeNull();
}
async function unarchiveAgent(page: Page): Promise<void> {
await page.getByRole("button", { name: "Unarchive", exact: true }).click();
await expect(page.getByText("This agent is archived", { exact: true })).toHaveCount(0, {
timeout: 30_000,
});
}
async function expectToast(page: Page, message: string): Promise<void> {
await expect(page.getByTestId("app-toast-message")).toHaveText(message, { timeout: 30_000 });
}
/** The prompts of the whole conversation, after scrolling up through its older pages. */
async function expectConversationPrompts(page: Page, prompts: string[]): Promise<void> {
const messages = page.getByTestId("user-message");
await expect
.poll(async () => {
await userScrollsTimelineToHistoryStart(page);
return await messages.count();
})
.toBe(prompts.length);
await expect(messages).toContainText(prompts);
}
// A row React remounts loses this attribute; one that stays mounted keeps it.
async function markMounted(row: Locator): Promise<void> {
await row.evaluate((element) => element.setAttribute("data-e2e-mounted", "before-rewind"));
}
async function expectStillMounted(row: Locator): Promise<void> {
await expect(row).toHaveAttribute("data-e2e-mounted", "before-rewind");
}
test.describe("Agent message rewind", () => {
test("rewinds a submitted prompt without replaying history and preserves a human draft", async ({
test("rewinds a prompt in place on every open client and keeps a human draft", async ({
page,
}) => {
test.setTimeout(90_000);
test.setTimeout(150_000);
const retainedPrompt = "Keep this completed turn after rewind.";
const rewoundPrompt = "Remove this completed turn after rewind.";
const nextPrompt = "Continue after the rewind.";
const preservedDraft = "Keep this human draft after rewind.";
const agent = await seedMockAgentWorkspace({
repoPrefix: "message-rewind-roundtrip-",
title: "Message rewind roundtrip",
model: "ten-second-stream",
});
const otherClient = await page.context().newPage();
try {
const rewindCompletion = await holdRewindCompletion(page, agent.agentId);
await openAgentRoute(page, agent);
await expectComposerVisible(page);
await completeSubmittedTurn(page, agent, retainedPrompt);
const retainedMessage = await completeSubmittedTurn(page, agent, retainedPrompt);
const userMessage = await completeSubmittedTurn(page, agent, rewoundPrompt);
await test.step("a second client opens the same chat", async () => {
await openAgentOnAnotherClient(otherClient, agent);
await expectPrompts(otherClient, [retainedPrompt, rewoundPrompt]);
});
await markMounted(retainedMessage);
await scrollChatAwayFromBottom(page, {
deltaY: -900,
minDistanceFromBottom: 300,
@@ -76,19 +155,91 @@ test.describe("Agent message rewind", () => {
await blurComposerInput(page);
rewindCompletion.clearTimelineStreamCount();
const rewind = rewindConversation(page, userMessage, rewoundPrompt);
await rewindCompletion.waitForDelayedResponse();
await expect(page.getByTestId("rewind-menu-conversation")).toBeDisabled();
expect(rewindCompletion.timelineStreamCount()).toBe(0);
rewindCompletion.release();
await rewind;
await test.step("the rewind stays pending until the daemon answers", async () => {
const rewind = rewindConversation(page, userMessage, rewoundPrompt);
await rewindCompletion.waitForDelayedResponse();
await expect(page.getByTestId("rewind-menu-conversation")).toBeDisabled();
expect(rewindCompletion.timelineStreamCount()).toBe(0);
rewindCompletion.release();
await rewind;
});
await expect(page.getByTestId("user-message").filter({ hasText: rewoundPrompt })).toHaveCount(
0,
);
await expectComposerDraft(page, preservedDraft);
await expectComposerNotFocused(page);
await expectNearBottom(page);
await test.step("the rewound turn leaves without reloading the chat", async () => {
await expectPrompts(page, [retainedPrompt]);
await expectStillMounted(retainedMessage);
expect(rewindCompletion.timelineFetchCount()).toBe(0);
await expectComposerDraft(page, preservedDraft);
await expectComposerNotFocused(page);
await expectNearBottom(page);
await expectPrompts(otherClient, [retainedPrompt]);
});
await test.step("the next prompt appears once on both clients", async () => {
await completeSubmittedTurn(otherClient, agent, nextPrompt);
await expectPrompts(otherClient, [retainedPrompt, nextPrompt]);
await expectPrompts(page, [retainedPrompt, nextPrompt]);
});
await test.step("a reconnecting client loads the rewound conversation", async () => {
await otherClient.reload();
await expectPrompts(otherClient, [retainedPrompt, nextPrompt]);
});
} finally {
await otherClient.close();
await agent.cleanup();
}
});
test("keeps the rewound conversation through Reload agent, archive and unarchive", async ({
page,
}) => {
test.setTimeout(150_000);
const keptPrompt = "Keep this turn through reload and archive.";
const rewoundPrompt = "Rewind this turn before reloading.";
const nextPrompt = "Continue after the rewind, then reload.";
const agent = await seedMockAgentWorkspace({
repoPrefix: "message-rewind-reload-archive-",
title: "Message rewind reload archive",
model: "ten-second-stream",
});
try {
await openAgentRoute(page, agent);
await expectComposerVisible(page);
await completeSubmittedTurn(page, agent, keptPrompt);
const rewound = await completeSubmittedTurn(page, agent, rewoundPrompt);
await rewindConversation(page, rewound, rewoundPrompt);
await expectPrompts(page, [keptPrompt]);
await completeSubmittedTurn(page, agent, nextPrompt);
await expectPrompts(page, [keptPrompt, nextPrompt]);
await test.step("Reload agent keeps the rewound conversation", async () => {
await reloadAgentFromTabMenu(page, agent.agentId);
await expectToast(page, "Reloaded agent");
await expectPrompts(page, [keptPrompt, nextPrompt]);
await expectComposerVisible(page);
});
await test.step("the archived chat shows the rewound conversation", async () => {
await archiveAgentByClosingTab(page, agent);
await openAgentRoute(page, agent);
await expect(page.getByText("This agent is archived", { exact: true })).toBeVisible({
timeout: 30_000,
});
await expectConversationPrompts(page, [keptPrompt, nextPrompt]);
});
await test.step("unarchiving keeps the rewound conversation", async () => {
await unarchiveAgent(page);
await expectComposerVisible(page);
await expectConversationPrompts(page, [keptPrompt, nextPrompt]);
});
await test.step("a reconnecting client loads the same conversation", async () => {
await page.reload();
await expectComposerVisible(page);
await expectConversationPrompts(page, [keptPrompt, nextPrompt]);
});
} finally {
await agent.cleanup();
}
@@ -18,6 +18,7 @@ import {
expectComposerVisible,
cancelAgent,
composerLocator,
configureComposerInterruptSend,
expectQueuedMessageButton,
fillComposerDraft,
holdSendButton,
@@ -404,15 +405,6 @@ async function queueMessage(page: Page, prompt: string): Promise<void> {
await sendDraftToQueue(page);
}
async function expectQueuedSendFailuresRestored(page: Page, prompts: string[]): Promise<void> {
await expect(page.getByRole("button", { name: "Send queued message now" })).toHaveCount(
prompts.length,
);
for (const prompt of prompts) {
await expect(page.getByTestId("user-message").filter({ hasText: prompt })).toHaveCount(0);
}
}
async function expectFailedSubmissionRestored(page: Page, prompt: string): Promise<void> {
await expectComposerDraft(page, prompt);
await expectComposerEditable(page);
@@ -431,14 +423,14 @@ async function expectInterruptedTurnOrderAfterReconnect(
});
const prompt = "Keep this prompt before its response.";
try {
await configureComposerInterruptSend(page);
await openAgentRoute(page, { workspaceId: agent.workspaceId, agentId: agent.agentId });
await expectComposerVisible(page);
await agent.client.sendAgentMessage(agent.agentId, "Start the turn that will be interrupted.");
await expect(page.getByRole("button", { name: /stop|cancel/i }).first()).toBeVisible();
await expect(page.getByText("Cycle 1", { exact: true })).toBeVisible();
await queueMessage(page, prompt);
gate.setAgentStreamSuppressed(true);
await page.getByRole("button", { name: "Send queued message now" }).click();
await submitMessage(page, prompt);
const promptRow = page.getByTestId("user-message").filter({ hasText: prompt });
await expect(promptRow).toBeVisible();
await gate.waitForServerMessage("send_agent_message_response");
@@ -659,14 +651,14 @@ async function expectLegacyAssistantStartsAfterInterruptedPrompt(
});
const prompt = "Start the replacement answer after this prompt.";
try {
await configureComposerInterruptSend(page);
await openAgentRoute(page, { workspaceId: agent.workspaceId, agentId: agent.agentId });
await expectComposerVisible(page);
await agent.client.sendAgentMessage(agent.agentId, "Start the interrupted answer.");
await expect(page.getByText("Cycle 1", { exact: true })).toBeVisible();
await queueMessage(page, prompt);
gate.setAssistantMessageIdsStripped(true);
gate.setAgentStreamEventSuppressed("turn_canceled", true);
await page.getByRole("button", { name: "Send queued message now" }).click();
await submitMessage(page, prompt);
const promptRow = page.getByTestId("user-message").filter({ hasText: prompt });
const replacementAnswer = page.getByText("(end of synthetic stream)", { exact: true }).last();
await expect(promptRow).toBeVisible();
@@ -1098,6 +1090,7 @@ test.describe("Agent message submission", () => {
gate.holdNextServerMessage("cancel_agent_response");
await page.getByRole("button", { name: "Stop agent", exact: true }).click();
await gate.waitForHeldServerMessage();
await page.getByRole("button", { name: "Send queued message now" }).click();
await expect(page.getByTestId("user-message").filter({ hasText: secondPrompt })).toHaveCount(
1,
@@ -1343,6 +1336,8 @@ test.describe("Agent message submission", () => {
await test.step("holding Send queues the draft", async () => {
await fillComposerDraft(page, queuedPrompt);
await holdSendButton(page, "Send and steer");
expect((await gate.waitForRequest()).activeTurnBehavior).toBe("queue");
gate.accept();
await expectQueuedMessageButton(page);
await expectComposerDraft(page, "");
await expectAgentReadyToInterrupt(page);
@@ -1351,19 +1346,22 @@ test.describe("Agent message submission", () => {
).toHaveCount(0);
});
await test.step("tapping Send still steers", async () => {
await test.step("tapping Send still steers and takes the queued row along", async () => {
const steeredPrompt = "Steer this turn with a tap.";
await fillComposerDraft(page, steeredPrompt);
await page.getByRole("button", { name: "Send and steer", exact: true }).click();
const request = await gate.waitForRequest();
const request = await gate.waitForRequest(2);
expect(request.text).toBe(steeredPrompt);
expect(request.activeTurnBehavior).toBe("steer");
gate.accept();
gate.accept(1);
await expect(
page.getByTestId("user-message").filter({ hasText: steeredPrompt }),
).toHaveCount(1);
await expectQueuedMessageButton(page);
await expect(page.getByRole("button", { name: "Send queued message now" })).toHaveCount(0);
await expect(
page.getByTestId("user-message").filter({ hasText: queuedPrompt }),
).toHaveCount(1);
});
} finally {
await agent.cleanup();
@@ -1380,26 +1378,21 @@ test.describe("Agent message submission", () => {
await replaySteeredSleepTurnInBrowser(page, testInfo, "codex");
});
test("restores overlapping queued sends when their connection fails", async ({
page,
}, testInfo) => {
test("restores the draft when queueing loses the connection", async ({ page }, testInfo) => {
test.setTimeout(120_000);
const gate = await gateNextAgentMessage(page);
const agent = await startRunningMockAgent(page, {
prefix: `overlapping-queued-send-${testInfo.workerIndex}-`,
prefix: `queue-connection-lost-${testInfo.workerIndex}-`,
model: "one-minute-stream",
prompt: "Keep the agent running while messages queue.",
prompt: "Keep the agent running while a message queues.",
});
const prompts = ["Restore the first queued send.", "Restore the second queued send."];
const prompt = "Keep this draft if queueing fails.";
try {
await queueMessage(page, prompts[0]);
await queueMessage(page, prompts[1]);
await page.getByRole("button", { name: "Send queued message now" }).first().click();
await gate.waitForRequest(1);
await page.getByRole("button", { name: "Send queued message now" }).first().click();
await gate.waitForRequest(2);
await fillComposerDraft(page, prompt);
await sendDraftToQueue(page);
await gate.waitForRequest();
await gate.disconnect();
await expectQueuedSendFailuresRestored(page, prompts);
await expectFailedSubmissionRestored(page, prompt);
} finally {
await agent.cleanup();
}
@@ -44,6 +44,26 @@ const PROFILE = {
const PROFILE_SUMMARY = "Mock Load Test · One minute stream · Approval test";
// Isolate this suite to the sole mock provider so it tests single-provider picker
// behavior deterministically regardless of which CLIs are installed on the host.
test.use({
e2eDaemonConfig: {
version: 1,
agents: {
providers: {
claude: { enabled: false },
codex: { enabled: false },
copilot: { enabled: false },
opencode: { enabled: false },
pi: { enabled: false },
omp: { enabled: false },
antigravity: { enabled: false },
hoplite: { enabled: false },
},
},
},
});
test.describe("Agent profiles in the model picker", () => {
test("an empty host still exposes agent profile settings from the picker", async ({ page }) => {
const seed = await seedAgentProfiles([]);
@@ -68,8 +88,8 @@ test.describe("Agent profiles in the model picker", () => {
page,
}) => {
const seed = await seedAgentProfiles([PROFILE]);
// A live agent is one provider's process, so the profile has to name that
// same provider or the picker will not offer it at all.
// With only the mock provider enabled on this host, the picker opens
// directly into its models and shows its pinned profile.
const workspace = await seedMockAgentWorkspace({
repoPrefix: "agent-profiles-picker-",
title: "Agent profiles picker",
@@ -14,6 +14,7 @@ import {
answerFreshnessCheck,
commitTimelineTurnsWhileDisconnected,
disconnectViewedTimeline,
expectCleanLoadingSurfaces,
expectEmptyChatSynced,
expectPromptAndWholeReply,
expectResumeAnsweredWithoutFetch,
@@ -29,8 +30,10 @@ import {
seedStreamingReplyAgent,
sendPromptWhileDisconnected,
stopStreamingReply,
waitForDisplayOnlyTimelineCache,
waitForResumeAnswer,
reopenAppWatchingForUpdatingToast,
watchColdAndReloadLoadingSurfaces,
watchForUpdatingToast,
} from "../support/helpers/timeline-resume";
@@ -176,4 +179,36 @@ test.describe("Agent timeline resume", () => {
await agent.cleanup();
}
});
test("cold opens and display-only cache reloads stay textless, steady, and free of Updating messages", async ({
page,
}) => {
test.setTimeout(120_000);
const gate = await installDaemonWebSocketGate(page);
const agent = await seedLongMockAgentTimeline({ turns: 30 });
try {
await watchColdAndReloadLoadingSurfaces(page);
await test.step("cold open fetches one tail without flashing Updating messages", async () => {
const requests = rememberTimelineRequestCounts(gate, agent.agentId);
await openAgentTimeline(page, agent);
await expectTimelinePromptVisible(page, agent.newestPrompt);
await expectCleanLoadingSurfaces(page, gate, requests);
});
await test.step("display-only cached reload settles quietly without Updating messages", async () => {
await scrollTimelineUntilOlderHistoryIsReachable(page, agent.firstOlderPagePrompt);
await waitForDisplayOnlyTimelineCache(page, agent);
const requests = rememberTimelineRequestCounts(gate, agent.agentId);
await page.reload();
await expectTimelinePromptVisible(page, agent.newestPrompt);
await waitForResumeAnswer(gate, requests);
await expectCleanLoadingSurfaces(page, gate, requests);
});
} finally {
gate.restore();
await agent.cleanup();
}
});
});
@@ -0,0 +1,299 @@
import { writeFile } from "node:fs/promises";
import type { Browser, CDPSession, Page } from "@playwright/test";
import { test, expect } from "../support/fixtures";
import { openAgentRoute } from "../support/helpers/mock-agent";
import {
readReactCommits,
readReactRenders,
recordReactRenders,
resetReactRenders,
} from "../support/helpers/react-renders";
import { seedWorkspace, type SeededWorkspace } from "../support/helpers/seed-client";
/*
* What the app costs per agent update while agents the user is not looking at work.
*
* One workspace is open on one idle agent. Other workspaces hold idle agents. During the load
* window some of those agents run mock turns back to back. Like a working agent, they send
* `agent_update` messages that mostly change only `lastUsage` and `updatedAt`. The spec samples renderer CPU,
* main-thread task time, React commits and component renders over the window and divides by
* the `agent_update` messages the page received.
*
* PASEO_AGENT_UPDATE_PERF_E2E=1 run the spec
* PASEO_AGENT_UPDATE_WORKSPACES=20 background workspaces
* PASEO_AGENT_UPDATE_AGENTS=20 idle agents per background workspace
* PASEO_AGENT_UPDATE_RUNNING=10 agents running a turn during the load window
* PASEO_AGENT_UPDATE_WINDOW_MS=20000 length of the idle and load windows
* PASEO_AGENT_UPDATE_RUNS=3 load windows to sample
* PASEO_AGENT_UPDATE_OUT=<file> write the samples as JSON
* PASEO_AGENT_UPDATE_CPU_PROFILE=<file> write a CPU profile of the first load window
*/
const RUN = process.env.PASEO_AGENT_UPDATE_PERF_E2E === "1";
const WORKSPACES = Number(process.env.PASEO_AGENT_UPDATE_WORKSPACES ?? 20);
const AGENTS_PER_WORKSPACE = Number(process.env.PASEO_AGENT_UPDATE_AGENTS ?? 20);
const RUNNING = Number(process.env.PASEO_AGENT_UPDATE_RUNNING ?? 10);
const WINDOW_MS = Number(process.env.PASEO_AGENT_UPDATE_WINDOW_MS ?? 20_000);
const RUNS = Number(process.env.PASEO_AGENT_UPDATE_RUNS ?? 3);
const OUT = process.env.PASEO_AGENT_UPDATE_OUT;
const CPU_PROFILE = process.env.PASEO_AGENT_UPDATE_CPU_PROFILE;
// Emits a usage update about every 1.5 s, like a working Claude agent.
const RUNNING_MODEL = "ten-second-stream";
interface WindowSample {
agentUpdates: number;
rendererCpuMs: number;
taskMs: number;
scriptMs: number;
reactCommits: number;
taskMsPerUpdate: number;
rendererCpuMsPerUpdate: number;
commitsPerUpdate: number;
changeSets: Record<string, number>;
topRenders: Array<[string, number]>;
}
const describe = RUN ? test.describe : test.describe.skip;
describe("Agent update cost", () => {
const background: Array<{ workspace: SeededWorkspace; agentIds: string[] }> = [];
let open: SeededWorkspace;
let openAgentId: string;
test.beforeAll(async () => {
test.setTimeout(900_000);
open = await seedWorkspace({ repoPrefix: "update-cost-open-", title: "Open" });
openAgentId = await createIdleAgent(open, "Open agent");
for (let index = 0; index < WORKSPACES; index += 1) {
const workspace = await seedWorkspace({
repoPrefix: `update-cost-${index}-`,
title: `Background ${index + 1}`,
});
const agentIds = await Promise.all(
Array.from({ length: AGENTS_PER_WORKSPACE }, (_, agentIndex) =>
createIdleAgent(workspace, `Agent ${index + 1}.${agentIndex + 1}`),
),
);
background.push({ workspace, agentIds });
}
});
test.afterAll(async () => {
for (const { workspace } of background) await workspace.cleanup();
await open?.cleanup();
});
test("renderer work per agent update", async ({ page, browser }) => {
test.setTimeout(WINDOW_MS * (RUNS + 1) * 4 + 300_000);
await recordReactRenders(page);
const traffic = countAgentUpdates(page);
await page.setViewportSize({ width: 1440, height: 900 });
await openAgentRoute(page, { workspaceId: open.workspaceId, agentId: openAgentId });
await expect(
page.getByTestId(`workspace-tab-agent_${openAgentId}`).filter({ visible: true }).first(),
).toBeVisible({ timeout: 60_000 });
await expect(page.getByText(`Background ${WORKSPACES}`, { exact: true }).first()).toBeVisible({
timeout: 60_000,
});
await page.waitForTimeout(5_000);
const meter = await openMeter(page, browser);
try {
const idle = await meter.sample(traffic, () => page.waitForTimeout(WINDOW_MS));
const loads: WindowSample[] = [];
for (let run = 0; run < RUNS; run += 1) {
const running = pickRunning(background, run);
const work = keepWorking(running);
// Let the turns start so the window measures steady work, not the start burst.
await page.waitForTimeout(3_000);
const profile = CPU_PROFILE && run === 0 ? CPU_PROFILE : null;
loads.push(await meter.sample(traffic, () => page.waitForTimeout(WINDOW_MS), profile));
await work.stop();
await page.waitForTimeout(3_000);
}
const result = {
config: {
workspaces: WORKSPACES,
agentsPerWorkspace: AGENTS_PER_WORKSPACE,
running: RUNNING,
windowMs: WINDOW_MS,
},
idle,
loads,
median: {
taskMsPerUpdate: median(loads.map((load) => load.taskMsPerUpdate)),
rendererCpuMsPerUpdate: median(loads.map((load) => load.rendererCpuMsPerUpdate)),
commitsPerUpdate: median(loads.map((load) => load.commitsPerUpdate)),
agentUpdatesPerSecond: median(
loads.map((load) => load.agentUpdates / (WINDOW_MS / 1000)),
),
},
};
console.log(`[agent-update-cost] ${JSON.stringify(result, null, 2)}`);
if (OUT) await writeFile(OUT, JSON.stringify(result, null, 2));
expect(loads.every((load) => load.agentUpdates > 0)).toBe(true);
} finally {
await meter.close();
}
});
});
async function createIdleAgent(workspace: SeededWorkspace, title: string): Promise<string> {
const agent = await workspace.client.createAgent({
provider: "mock",
cwd: workspace.repoPath,
workspaceId: workspace.workspaceId,
title,
modeId: "load-test",
model: RUNNING_MODEL,
});
return agent.id;
}
/** Spreads the running agents over the workspaces, a different agent each run. */
function pickRunning(
background: ReadonlyArray<{ workspace: SeededWorkspace; agentIds: string[] }>,
run: number,
): Array<{ workspace: SeededWorkspace; agentId: string }> {
return Array.from({ length: RUNNING }, (_, index) => {
const entry = background[index % background.length];
const agentId =
entry.agentIds[(run + Math.floor(index / background.length)) % entry.agentIds.length];
return { workspace: entry.workspace, agentId };
});
}
/** Starts a turn on each agent and another one whenever it finishes, until stopped. */
function keepWorking(running: ReadonlyArray<{ workspace: SeededWorkspace; agentId: string }>) {
const state = { stopped: false };
const loops = running.map(async ({ workspace, agentId }) => {
while (!state.stopped) {
await workspace.client.sendAgentMessage(agentId, "work");
await workspace.client.waitForFinish(agentId, 60_000);
}
});
return {
async stop() {
state.stopped = true;
await Promise.all(
running.map(({ workspace, agentId }) => workspace.client.cancelAgent(agentId)),
);
await Promise.allSettled(loops);
},
};
}
interface AgentUpdateTraffic {
read(): number;
/** How often each set of changed agent fields arrived, since the last call. */
takeChangeSets(): Record<string, number>;
}
/** Counts the `agent_update` messages the page receives and which agent fields each changed. */
function countAgentUpdates(page: Page): AgentUpdateTraffic {
let count = 0;
let changeSets: Record<string, number> = {};
const previous = new Map<string, Record<string, unknown>>();
page.on("websocket", (socket) => {
socket.on("framereceived", ({ payload }) => {
if (typeof payload !== "string" || !payload.includes('"type":"agent_update"')) return;
const frame = JSON.parse(payload) as {
message?: { type?: string; payload?: { kind?: string; agent?: Record<string, unknown> } };
};
if (frame.message?.type !== "agent_update") return;
count += 1;
const agent = frame.message.payload?.agent;
if (frame.message.payload?.kind !== "upsert" || !agent) return;
const id = String(agent.id);
const prior = previous.get(id);
previous.set(id, agent);
const changed = prior
? Object.keys({ ...prior, ...agent })
.filter((key) => JSON.stringify(prior[key]) !== JSON.stringify(agent[key]))
.sort()
.join(",") || "<nothing>"
: "<first>";
changeSets[changed] = (changeSets[changed] ?? 0) + 1;
});
});
return {
read: () => count,
takeChangeSets: () => {
const taken = changeSets;
changeSets = {};
return taken;
},
};
}
async function openMeter(page: Page, browser: Browser) {
const pageSession: CDPSession = await page.context().newCDPSession(page);
const browserSession: CDPSession = await browser.newBrowserCDPSession();
await pageSession.send("Performance.enable");
const readMetrics = async () => {
const { metrics } = await pageSession.send("Performance.getMetrics");
const value = (name: string) => metrics.find((metric) => metric.name === name)?.value ?? 0;
const { processInfo } = await browserSession.send("SystemInfo.getProcessInfo");
const rendererCpu = processInfo
.filter((process) => process.type === "renderer")
.reduce((total, process) => total + process.cpuTime, 0);
return { task: value("TaskDuration"), script: value("ScriptDuration"), rendererCpu };
};
return {
async sample(
traffic: AgentUpdateTraffic,
during: () => Promise<void>,
profilePath: string | null = null,
) {
await resetReactRenders(page);
traffic.takeChangeSets();
const updatesBefore = traffic.read();
if (profilePath) {
await pageSession.send("Profiler.enable");
await pageSession.send("Profiler.start");
}
const before = await readMetrics();
await during();
const after = await readMetrics();
if (profilePath) {
const { profile } = await pageSession.send("Profiler.stop");
await writeFile(profilePath, JSON.stringify(profile));
}
const renders = await readReactRenders(page);
const agentUpdates = traffic.read() - updatesBefore;
const reactCommits = await readReactCommits(page);
const taskMs = (after.task - before.task) * 1000;
const rendererCpuMs = (after.rendererCpu - before.rendererCpu) * 1000;
const perUpdate = (value: number) => (agentUpdates > 0 ? value / agentUpdates : 0);
return {
agentUpdates,
rendererCpuMs: Math.round(rendererCpuMs),
taskMs: Math.round(taskMs),
scriptMs: Math.round((after.script - before.script) * 1000),
reactCommits,
taskMsPerUpdate: round(perUpdate(taskMs)),
rendererCpuMsPerUpdate: round(perUpdate(rendererCpuMs)),
commitsPerUpdate: round(perUpdate(reactCommits)),
changeSets: traffic.takeChangeSets(),
topRenders: Object.entries(renders)
.sort((left, right) => right[1] - left[1])
.slice(0, 40),
} satisfies WindowSample;
},
async close() {
await pageSession.detach().catch(() => undefined);
await browserSession.detach().catch(() => undefined);
},
};
}
function median(values: number[]): number {
const sorted = [...values].sort((left, right) => left - right);
return sorted[Math.floor(sorted.length / 2)] ?? 0;
}
function round(value: number): number {
return Math.round(value * 100) / 100;
}
@@ -2,7 +2,8 @@ import { expect, test } from "../support/fixtures";
import { gotoAppShell } from "../support/helpers/app";
import { seedWorkspace } from "../support/helpers/seed-client";
import { getServerId } from "../support/helpers/server-id";
import { openSettingsSection } from "../support/helpers/settings";
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
import { clickSettingsBackToWorkspace, openSettingsSection } from "../support/helpers/settings";
test("shows Pure black in the appearance picker", async ({ page }, testInfo) => {
await page.goto("/settings");
@@ -96,3 +97,43 @@ test("applies the interface font size to settings text", async ({ page }) => {
await expect(contentSizeInput).toHaveValue("21");
await expect(sectionTitle).toHaveCSS("font-size", "10px");
});
test("applies the content font size to an already-open chat", async ({ page }) => {
const agent = await seedMockAgentWorkspace({ repoPrefix: "chat-font-size-", title: "Font size" });
const prompt = "Existing message for the font size check";
try {
await agent.client.sendAgentMessage(agent.agentId, prompt);
await agent.client.waitForFinish(agent.agentId, 30_000);
await openAgentRoute(page, agent);
const userText = page.getByText(prompt, { exact: true });
const assistantText = page.getByTestId("assistant-message").first().locator("p").first();
const initialSize = await test.step("Read both messages at the default size", async () => {
await expect(userText).toBeVisible();
await expect(assistantText).toBeVisible();
return userText.evaluate((element) => getComputedStyle(element).fontSize);
});
const timeOrigin = await page.evaluate(() => performance.timeOrigin);
await test.step("Increase Content font size and return to the same chat", async () => {
await page.getByTestId("sidebar-settings").filter({ visible: true }).first().click();
await openSettingsSection(page, "appearance");
const size = page.getByRole("textbox", { name: "Content font size", exact: true });
await size.fill("21");
await size.press("Tab");
await expect(size).toHaveValue("21");
await clickSettingsBackToWorkspace(page);
});
await test.step("Read both messages at the new size without reloading", async () => {
expect(await page.evaluate(() => performance.timeOrigin)).toBe(timeOrigin);
await expect(assistantText).not.toHaveCSS("font-size", initialSize);
const updatedSize = await assistantText.evaluate(
(element) => getComputedStyle(element).fontSize,
);
await expect(userText).toHaveCSS("font-size", updatedSize);
});
} finally {
await agent.cleanup();
}
});
@@ -1,5 +1,11 @@
import { expect, test, type Page } from "../support/fixtures";
import { composerLocator, expectComposerVisible, submitMessage } from "../support/helpers/composer";
import { withDirectoryPlugin } from "../support/helpers/plugin-timeline";
import {
attachImageFromMenu,
composerLocator,
expectComposerVisible,
submitMessage,
} from "../support/helpers/composer";
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
import {
expectSessionRowArchived,
@@ -140,6 +146,47 @@ async function waitForReplacementAgentId(page: Page, oldAgentId: string): Promis
}
test.describe("Client slash commands", () => {
test("keeps the draft when a typed plugin slash command has an attachment", async ({ page }) => {
test.setTimeout(90_000);
await withDirectoryPlugin({
pluginId: "attachment-slash-e2e",
source: `
export default function contribute(client) {
client.addSlashCommand({name:"picture", description:"Review an attached picture", argumentHint:"<question>", context:"agent",
onSubmit(){throw new Error("Plugin handler unexpectedly received this command");}});
return () => {};
}`,
run: async () => {
await withOpenReadyMockAgent(page, { title: "Attached slash command" }, async () => {
const input = composerLocator(page);
await input.fill("/pict");
await expect(
page.getByText("Review an attached picture", { exact: true }).first(),
).toBeVisible();
await input.fill("");
await attachImageFromMenu(page, {
name: "picture.png",
mimeType: "image/png",
buffer: Buffer.from(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==",
"base64",
),
});
await input.fill("/picture what is this?");
await input.press("Enter");
await expect(
page.getByRole("alert").filter({ hasText: "Remove attachments to run /picture." }),
).toBeVisible();
await expect(input).toHaveValue("/picture what is this?");
await expect(page.getByTestId("composer-image-attachment-pill")).toBeVisible();
await expect(
page.getByTestId("user-message").filter({ hasText: "/picture what is this?" }),
).toHaveCount(0);
});
},
});
});
test("slash quit archives the active agent and removes its tab", async ({ page }) => {
await withOpenReadyMockAgent(page, { title: "Slash quit e2e" }, async ({ agentId, title }) => {
await runClientSlashCommand(page, "/quit");
@@ -1,6 +1,6 @@
import { readFile, writeFile } from "node:fs/promises";
import path from "node:path";
import { expect, test } from "../support/fixtures";
import { expect, test, type Page } from "../support/fixtures";
import { expectComposerVisible } from "../support/helpers/composer";
import { installDaemonWebSocketGate } from "../support/helpers/daemon-websocket-gate";
import { installLocalDesktopHost } from "../support/helpers/local-desktop-host";
@@ -282,3 +282,63 @@ test("compact opens files and subagents in a sheet, leaving the tabs for agents"
await workspace.cleanup();
}
});
async function openFileAndDismissDuringAnimation(page: Page) {
const fileLink = page.getByText(FILE_LINK, { exact: true });
await expect(fileLink).toBeVisible({ timeout: 15_000 });
// Check and press in the same browser frame so automation cannot outlast the opening animation.
await fileLink.evaluate((link) => {
if (!(link instanceof HTMLElement)) throw new Error("Expected an HTML file link");
return new Promise<void>((resolve, reject) => {
const timeout = window.setTimeout(() => {
cancelAnimationFrame(frame);
reject(new Error("The file sheet did not pass through the opening position"));
}, 5_000);
const dismissDuringOpening = () => {
const header = document.querySelector('[data-testid="sheet-tab-header"]');
const top = header?.getBoundingClientRect().top ?? window.innerHeight;
const pressTarget = document.elementFromPoint(10, 10);
if (
top > window.innerHeight / 2 &&
top < window.innerHeight &&
pressTarget instanceof HTMLElement &&
pressTarget.getAttribute("aria-label") === "Bottom sheet backdrop"
) {
window.clearTimeout(timeout);
pressTarget.click();
resolve();
return;
}
frame = requestAnimationFrame(dismissDuringOpening);
};
let frame = requestAnimationFrame(dismissDuringOpening);
link.click();
});
});
}
test("a sheet dismissed while it is still opening closes its tab", async ({ page }) => {
await page.setViewportSize({ width: 390, height: 844 });
const workspace = await seedMockAgentWorkspace({
repoPrefix: "compact-sheet-opening-dismiss-",
title: "Sheet parent",
initialPrompt: promptMentioning(FILE_LINK),
});
try {
await writeFile(path.join(workspace.cwd, "linked.ts"), "one\ntwo\nthree\n", "utf8");
await openAgentRoute(page, { workspaceId: workspace.workspaceId, agentId: workspace.agentId });
await openFileAndDismissDuringAnimation(page);
await expectNoSheetOpen(page);
await expectOpenTabCount(page, 1);
await page
.getByRole("button", { name: /Switch tabs/ })
.filter({ visible: true })
.click();
await expect(page.getByText("Workspace tabs", { exact: true })).toBeVisible();
} finally {
await workspace.cleanup();
}
});
@@ -0,0 +1,320 @@
import { expect, test } from "../support/fixtures";
import { expectAgentIdle } from "../support/helpers/agent-stream";
import {
attachComposerTestImage,
cancelAgent,
composerLocator,
expectAttachmentPill,
expectComposerDraft,
expectComposerVisible,
fillComposerDraft,
sendDraftToQueue,
} from "../support/helpers/composer";
import {
cancelQueuedMessage,
editQueuedMessage,
expectDeliveredImage,
expectComposerOnScreen,
expectDeliveredOnce,
expectSenderIconUnsquashed,
openSecondClient,
queuedRow,
queuedRows,
queueMessage,
queuePausedNotice,
queueThroughHost,
reopenAgent,
scrollQueueFrom,
seedAgentWithOpenTurn,
sendQueuedMessageNow,
} from "../support/helpers/composer-queue";
import { openAgentRoute } from "../support/helpers/mock-agent";
test.describe("Composer queue", () => {
test("a queued image prompt can be edited, survives a reload, and is delivered once", async ({
page,
}) => {
const prompt = "Describe this screenshot.";
const revised = "Describe this screenshot in one line.";
const agent = await seedAgentWithOpenTurn({ repoPrefix: "queue-edit-", title: "Queue edit" });
try {
await openAgentRoute(page, agent);
await expectComposerVisible(page);
await test.step("queue a prompt with an image", async () => {
await attachComposerTestImage(page);
await expectAttachmentPill(page, "composer-image-attachment-pill");
await queueMessage(page, prompt);
await expect(queuedRow(page, prompt)).toContainText("1 attachment");
});
await test.step("Edit takes the text and image back into the composer", async () => {
await editQueuedMessage(page, prompt);
await expect(queuedRows(page)).toHaveCount(0);
await expectComposerDraft(page, prompt);
await expectAttachmentPill(page, "composer-image-attachment-pill");
await expect(composerLocator(page)).toBeFocused();
});
await test.step("queue the revised prompt with the same image", async () => {
await queueMessage(page, revised);
await expect(queuedRow(page, revised)).toContainText("1 attachment");
});
await test.step("the row is still there after a reload", async () => {
await page.reload();
await expect(queuedRow(page, revised)).toBeVisible({ timeout: 30_000 });
await expect(queuedRows(page)).toHaveCount(1);
});
await test.step("the prompt is delivered once when the turn ends", async () => {
await agent.finishTurn();
await expectDeliveredOnce(page, revised);
await expectDeliveredImage(page, revised);
await expect(queuedRows(page)).toHaveCount(0);
});
} finally {
await agent.cleanup();
}
});
test("Stop pauses the queue until the user sends a row", async ({ page }) => {
const prompt = "Run after I say so.";
const agent = await seedAgentWithOpenTurn({ repoPrefix: "queue-held-", title: "Queue held" });
try {
await openAgentRoute(page, agent);
await expectComposerVisible(page);
await queueMessage(page, prompt);
await expect(queuePausedNotice(page)).toHaveCount(0);
await cancelAgent(page);
await expectAgentIdle(page);
await expect(queuePausedNotice(page)).toBeVisible();
await expect(queuedRow(page, prompt)).toBeVisible();
await sendQueuedMessageNow(page, prompt);
await expectDeliveredOnce(page, prompt);
await expect(queuePausedNotice(page)).toHaveCount(0);
} finally {
await agent.cleanup();
}
});
test("the host delivers a queued prompt with every client closed", async ({ page }) => {
const prompt = "Continue while I am away.";
const agent = await seedAgentWithOpenTurn({
repoPrefix: "queue-closed-",
title: "Queue closed",
});
try {
await openAgentRoute(page, agent);
await expectComposerVisible(page);
await queueMessage(page, prompt);
await page.close();
await agent.finishTurn();
await agent.client.waitForFinish(agent.agentId, 30_000);
const reopened = await reopenAgent(page, agent);
await expectDeliveredOnce(reopened, prompt);
await expect(queuedRows(reopened)).toHaveCount(0);
} finally {
await agent.cleanup();
}
});
test("two clients share one queue", async ({ browser, page }) => {
const unwanted = "Do not run this one.";
const urgent = "Run this one now.";
const agent = await seedAgentWithOpenTurn({ repoPrefix: "queue-sync-", title: "Queue sync" });
try {
await openAgentRoute(page, agent);
await expectComposerVisible(page);
const second = await openSecondClient(browser, page, agent);
try {
await expectComposerVisible(second.page);
await test.step("a row queued on one client appears on the other", async () => {
await queueMessage(page, unwanted);
await expect(queuedRow(second.page, unwanted)).toBeVisible();
await fillComposerDraft(second.page, urgent);
await sendDraftToQueue(second.page);
await expect(queuedRows(page)).toContainText([unwanted, urgent]);
});
await test.step("Cancel on one client removes the row on the other", async () => {
await cancelQueuedMessage(second.page, unwanted);
await expect(queuedRow(page, unwanted)).toHaveCount(0);
});
await test.step("Send now on one client updates the other", async () => {
await sendQueuedMessageNow(page, urgent);
await expectDeliveredOnce(second.page, urgent);
await expect(
second.page.getByTestId("user-message").filter({ hasText: unwanted }),
).toHaveCount(0);
});
} finally {
await second.close();
}
} finally {
await agent.cleanup();
}
});
test("switching away from a retained agent tab and returning catches up on queue changes", async ({
page,
}) => {
const initial = "Initial queued row.";
const hidden = "Arrived while hidden.";
const agent = await seedAgentWithOpenTurn({
repoPrefix: "queue-hidden-",
title: "Queue first",
});
try {
await agent.client.createAgent({
provider: "mock",
cwd: agent.cwd,
workspaceId: agent.workspaceId,
title: "Queue second",
modeId: "load-test",
model: "e2e-fast-stream",
});
await openAgentRoute(page, agent);
await expectComposerVisible(page);
await queueMessage(page, initial);
await page.getByRole("button", { name: "Queue second", exact: true }).click();
await queueThroughHost(agent, [hidden]);
await page.getByRole("button", { name: "Queue first", exact: true }).click();
await expect(queuedRows(page)).toContainText([initial, hidden]);
} finally {
await agent.cleanup();
}
});
test("a long queue scrolls without pushing the composer off screen", async ({ page }) => {
const texts = Array.from({ length: 20 }, (_, index) => `Queued update ${index + 1}.`);
const first = "Queued update 1.";
const last = "Queued update 20.";
const agent = await seedAgentWithOpenTurn({ repoPrefix: "queue-long-", title: "Queue long" });
try {
await openAgentRoute(page, agent);
await expectComposerVisible(page);
await queueThroughHost(agent, texts);
await expect(queuedRows(page)).toHaveCount(20);
for (const viewport of [
{ width: 1280, height: 800 },
{ width: 390, height: 844 },
// A phone with its keyboard open.
{ width: 390, height: 500 },
]) {
await test.step(`${viewport.width}x${viewport.height}`, async () => {
await page.setViewportSize(viewport);
await expect(queuedRow(page, first)).toBeVisible();
await expectComposerOnScreen(page);
await scrollQueueFrom(page, first, 5000);
// Scrolled to the end, a fractional frame height can clip a sub-pixel of the row.
await expect(queuedRow(page, last)).toBeInViewport({ ratio: 0.99 });
await expectComposerOnScreen(page);
await scrollQueueFrom(page, last, -5000);
await expect(queuedRow(page, first)).toBeInViewport({ ratio: 1 });
});
}
} finally {
await agent.cleanup();
}
});
test("a message queued by another agent can be cancelled but not edited", async ({ page }) => {
const message = "The release notes are ready for review.";
const agent = await seedAgentWithOpenTurn({
repoPrefix: "queue-sender-",
title: "Queue recipient",
});
try {
const sender = await agent.client.createAgent({
provider: "mock",
cwd: agent.cwd,
workspaceId: agent.workspaceId,
title: "Release coordination and changelog verification helper for the mobile team",
model: "e2e-fast-stream",
});
await openAgentRoute(page, agent);
await expectComposerVisible(page);
await agent.client.sendAgentMessage(agent.agentId, message, {
sourceAgentId: sender.id,
activeTurnBehavior: "queue",
});
const row = queuedRow(page, message);
await expect(row).toContainText("Sent by Release coordination");
await expect(row.getByRole("button", { name: "Send queued message now" })).toBeEnabled();
await expect(row.getByRole("button", { name: "Cancel queued message" })).toBeEnabled();
await expect(row.getByRole("button", { name: "Edit queued message" })).toHaveCount(0);
await test.step("a long sender name truncates without squashing its icon", async () => {
await page.setViewportSize({ width: 390, height: 844 });
await expect(row).toBeInViewport();
await expectSenderIconUnsquashed(row);
});
await cancelQueuedMessage(page, message);
await expect(queuedRows(page)).toHaveCount(0);
} finally {
await agent.cleanup();
}
});
test("editing a queued image prompt on a short phone viewport keeps remaining queued rows visible", async ({
page,
}) => {
const withImage = "Describe this screenshot.";
const remaining = Array.from({ length: 4 }, (_, index) => `Remaining update ${index + 1}.`);
const agent = await seedAgentWithOpenTurn({
repoPrefix: "queue-compact-edit-",
title: "Queue compact edit",
});
try {
await openAgentRoute(page, agent);
await expectComposerVisible(page);
await attachComposerTestImage(page);
await expectAttachmentPill(page, "composer-image-attachment-pill");
await queueMessage(page, withImage);
await queueThroughHost(agent, remaining);
await expect(queuedRows(page)).toHaveCount(5);
await page.setViewportSize({ width: 390, height: 500 });
await editQueuedMessage(page, withImage);
await expectComposerDraft(page, withImage);
await expectAttachmentPill(page, "composer-image-attachment-pill");
await expect(composerLocator(page)).toBeInViewport({ ratio: 1 });
await expect(
page.getByRole("button", { name: "Send and steer", exact: true }),
).toBeInViewport({
ratio: 1,
});
// The queue scroll viewport must keep a readable slice (>= 90px) above the restored image pill,
// not collapse to a sliver inside a 0.6*viewport slot clamp.
const scrollFrameHeight = await page
.getByRole("list", { name: "Queued messages" })
.evaluate((list) => {
const scrollView = list.parentElement?.parentElement;
return scrollView ? scrollView.getBoundingClientRect().height : 0;
});
expect(scrollFrameHeight).toBeGreaterThanOrEqual(90);
} finally {
await agent.cleanup();
}
});
});
@@ -9,6 +9,7 @@ import {
expectHostBadgeIconOnly,
expectHostBadgeName,
expectHostBadgeTinted,
expectHostSelectorStatusIcon,
expectNoHostBadge,
leaveHostAppearanceSettings,
openHostAppearanceSettings,
@@ -116,14 +117,29 @@ test("customizes a host badge and preserves its appearance after reload", async
expect(widths.content).toBeLessThanOrEqual(widths.client);
});
await test.step("preview a color and icon and apply them to the sidebar badge and host popover", async () => {
await test.step("preview a color and icon and apply them to the sidebar badge, host selectors, and host popover", async () => {
await openHostAppearanceSettings(page, badge.serverId);
await chooseHostColor(page, "Teal");
await chooseHostIcon(page, "Laptop");
await expectHostAppearancePreview(page, { serverId: badge.serverId, hostName, color: "teal" });
// The Settings sidebar host selector shows the host's resolved icon badged with its status dot.
const settingsHostPicker = page.getByTestId("settings-host-picker");
await settingsHostPicker.click();
await page.getByTestId(`settings-host-picker-item-${badge.serverId}`).click();
await expectHostSelectorStatusIcon(settingsHostPicker, { color: "teal" });
await leaveHostAppearanceSettings(page);
await expectHostBadgeTinted(page, { ...badge, hostName, color: "teal" });
// The New Workspace host selector also shows the host icon with its status dot.
await page.getByTestId("sidebar-global-new-workspace").click();
const newWorkspaceHostTrigger = page.getByTestId("host-picker-trigger");
await expect(newWorkspaceHostTrigger).toBeVisible();
await newWorkspaceHostTrigger.click();
await page.getByTestId(`new-workspace-host-picker-option-${badge.serverId}`).click();
await expectHostSelectorStatusIcon(newWorkspaceHostTrigger, { color: "teal" });
await page.getByTestId("sidebar-hosts-trigger").click();
const hostRow = page.getByTestId(`sidebar-host-row-${badge.serverId}`);
await expect(hostRow).toBeVisible();
@@ -6,10 +6,12 @@ import {
cancelHostConfirmation,
connectToConfirmedHost,
expectHostConfirmationFor,
expectHostIdentityChangedWarning,
expectHostInHostPicker,
hostConfirmation,
openPairingLink,
reopenPairingLinkWithSavedHosts,
replaceHostIdentity,
type LinkedHost,
} from "../support/helpers/host-confirmation";
@@ -48,3 +50,46 @@ test("a pairing link asks before saving a host and reconnects without asking aga
await expect(hostConfirmation(page)).toHaveCount(0);
});
});
test("a pairing link with a different key for a saved host warns before replacing its identity", async ({
page,
}) => {
const rotatedHost: LinkedHost = {
...linkedHost,
daemonPublicKeyB64: "cm90YXRlZEhvc3RJZGVudGl0eQ",
};
const rotatedLink = buildPairingLink(rotatedHost);
const warning = {
savedHost: linkedHost.serverId,
savedKey: "bGlu a0Nv … lvbk tleQ",
newKey: "cm90 YXRl … VudG l0eQ",
relayEndpoint: linkedHost.relayEndpoint,
};
await test.step("save the host", async () => {
await openPairingLink(page, buildPairingLink(linkedHost));
await expectHostConfirmationFor(page, linkedHost);
await connectToConfirmedHost(page);
await expectAppRoute(page, "/open-project");
});
await test.step("Cancel keeps the saved identity", async () => {
await reopenPairingLinkWithSavedHosts(page, rotatedLink);
await expectHostIdentityChangedWarning(page, warning);
await cancelHostConfirmation(page);
await expectAppRoute(page, "/settings/general");
});
await test.step("Replace host identity saves the new key", async () => {
await reopenPairingLinkWithSavedHosts(page, rotatedLink);
await expectHostIdentityChangedWarning(page, warning);
await replaceHostIdentity(page);
await expectAppRoute(page, "/open-project");
});
await test.step("the new key is now the saved identity", async () => {
await reopenPairingLinkWithSavedHosts(page, rotatedLink);
await expectAppRoute(page, "/open-project", { timeout: 30_000 });
await expect(hostConfirmation(page)).toHaveCount(0);
});
});
+28 -1
View File
@@ -10,6 +10,7 @@ import {
finishSetup,
goToSetupStep,
hostGivesAgentsPaseoTools,
hostToolGroups,
openAppAsNewUser,
openRelayPairingFromSetup,
closeRelayPairing,
@@ -24,6 +25,7 @@ import {
recordFirstLaunch,
setupModal,
setupPrimaryButton,
setHostTools,
setupSheet,
showSetupAgainFromSettings,
skipSetup,
@@ -426,6 +428,30 @@ test("setup choices carry over to Settings and the phone step pairs over relay",
}
});
test("setup offers only Enable tools and keeps the host's tool groups", async ({ page }) => {
const host = await startSetupHost("tool-groups");
try {
await setHostTools(host, { groups: { schedules: false, browser: true } });
await openAppAsNewUser(page, host);
await expectSetupStep(page, "Welcome to Paseo");
await goToSetupStep(page, "Orchestration");
await expectSetupStep(page, "Let agents use Paseo");
await expect(paseoToolsSwitch(setupModal(page))).toBeChecked();
// Setup offers only the main switch; tool groups live in Settings.
await expect(
setupModal(page).getByRole("switch", { name: "Browser", exact: true }),
).toHaveCount(0);
await continueSetup(page);
await expectSetupStep(page, "Take your agents with you");
await expect.poll(() => hostGivesAgentsPaseoTools(host), { timeout: 30_000 }).toBe(true);
expect(await hostToolGroups(host)).toMatchObject({ schedules: false, browser: true });
} finally {
await host.close();
}
});
test("with no skills picked, skills read as off and Continue moves on", async ({ page }) => {
const host = await startSetupHost("no-skills");
@@ -463,6 +489,7 @@ test("in the compact layout, Finish on Orchestration applies its switches", asyn
const primary = (label: string) => page.getByRole("button", { name: label, exact: true });
try {
await setHostTools(host, { enabled: false });
await openAppAsNewUser(page, host);
await step("Welcome to Paseo");
await primary("Continue").click();
@@ -471,7 +498,7 @@ test("in the compact layout, Finish on Orchestration applies its switches", asyn
await step("Add your projects");
await primary("Continue").click();
// The setup host starts with Paseo tools off; the switch starts on.
// The host has tools off; the setup switch still starts on.
expect(await hostGivesAgentsPaseoTools(host)).toBe(false);
await step("Let agents use Paseo");
await expect(paseoToolsSwitch(page)).toBeChecked();
@@ -1,3 +1,5 @@
import { createHostClient } from "@getpaseo/client/node";
import { expect } from "@playwright/test";
import { gotoAppShell, openSettings } from "../support/helpers/app";
import {
addDirectHostFromSettings,
@@ -24,11 +26,51 @@ import {
slowConnectionToHost,
expectTailscaleUpdateRequired,
expectCompletePairingQr,
expectConnectedClientRow,
expectRelayConsent,
expandConnectedClientRow,
openDevicesPage,
openPairDeviceModal,
preparePairingHost,
returnFromRelayToWaysToConnect,
} from "../support/helpers/pair-device";
test("lists connected clients with scopes and navigates Pair a device → Relay → Back", async ({
page,
}) => {
const daemon = await startIsolatedHostDaemon("pair-device-connected-clients", {
mutableRelay: { enabled: true },
});
const viewer = createHostClient(`127.0.0.1:${daemon.port}`, {
clientId: "cid_e2e_phone_viewer",
clientType: "mobile",
appVersion: "0.18.1",
clientInfo: { name: "Test Phone", platform: "ios" },
sessionPermissions: ["daemon.read", "workspace.read"],
reconnect: { enabled: false },
});
try {
await openDevicesPage(page, daemon);
await expectConnectedClientRow(page, "This device", "Full access");
await expandConnectedClientRow(page, "This device");
await expect(
page
.getByTestId("devices-connected-clients-card")
.getByText("access.manage", { exact: true }),
).toBeVisible();
await viewer.connect();
await expectConnectedClientRow(page, "Test Phone", "Read-only");
await openPairDeviceModal(page);
await expectPairingOffer(page);
await returnFromRelayToWaysToConnect(page);
} finally {
await viewer.close();
await daemon.close();
}
});
test("opens relay consent in browser web", async ({ page }) => {
const daemon = await startIsolatedHostDaemon("pair-device-browser-relay-off", {
mutableRelay: { enabled: false },
@@ -81,7 +123,7 @@ test("turns Tailscale on and off from Devices, asking first over Tailscale", asy
}, testInfo) => {
test.skip(process.platform !== "linux", "Uses a second IPv4 loopback address");
// The journey opens Devices or the setup six times, two of them over a slowed connection.
test.setTimeout(120_000);
test.setTimeout(180_000);
if (!baseURL) throw new Error("Expected the app base URL");
const daemon = await startTailscaleTestDaemon(baseURL);
try {
@@ -1,3 +1,5 @@
import path from "node:path";
import { expect } from "../support/fixtures";
import {
test,
expectStillBrowsing,
@@ -22,3 +24,59 @@ test("installs a listed plugin from Browse and uninstalls it from either of its
await openFromInstalledTab(page);
await uninstallFromPage(page);
});
test("shows scorecard progressive disclosure, updates, custom links, and related plugins", async ({
page,
directoryHost,
}) => {
const captureDir = process.env.PASEO_CAPTURE_DIR;
if (captureDir) {
await page.emulateMedia({ colorScheme: "dark" });
}
await page.setViewportSize({ width: 1280, height: 960 });
await openDirectory(page, directoryHost);
await openListingPage(page);
await expect(page.getByText("Related plugins", { exact: true })).toBeVisible();
await expect(page.getByTestId("plugin-related-acme/pr-radar")).toBeVisible();
if (captureDir) {
await page.waitForTimeout(300);
await page.screenshot({ path: path.join(captureDir, "live-app-desktop-overview.png") });
}
// Open Scorecard tab and expand a capability row.
await page.getByTestId("plugin-page-tab-scorecard").click();
await expect(page.getByText("This plugin is actively maintained.")).toBeVisible();
const panelRow = page.getByRole("button", { name: /Workspace panel/ });
await panelRow.click();
await expect(page.getByText(/index\.client\.ts/)).toBeVisible();
if (captureDir) {
await page.waitForTimeout(300);
await page.screenshot({ path: path.join(captureDir, "live-app-desktop-scorecard.png") });
}
// Open Updates tab and custom actions menu.
await page.getByTestId("plugin-page-tab-updates").click();
await expect(page.getByText("v1.2.0", { exact: true })).toBeVisible();
await expect(page.getByText("c81a4f2", { exact: true })).toBeVisible();
await page.getByTestId("plugin-actions-acme/directory-example").click();
await expect(page.getByText("Documentation", { exact: true })).toBeVisible();
if (captureDir) {
await page.waitForTimeout(300);
await page.screenshot({ path: path.join(captureDir, "live-app-desktop-updates.png") });
}
await page.keyboard.press("Escape");
// Verify compact mobile layout on the same listing page.
await page.setViewportSize({ width: 390, height: 844 });
await page.getByTestId("plugin-page-tab-scorecard").click();
await expect(page.getByText("This plugin is actively maintained.")).toBeVisible();
if (captureDir) {
await page.waitForTimeout(300);
await page.screenshot({ path: path.join(captureDir, "live-app-mobile-scorecard.png") });
}
});
@@ -0,0 +1,324 @@
import { writeFile } from "node:fs/promises";
import path from "node:path";
import type { Locator } from "@playwright/test";
import { expect, test, type Page } from "../support/fixtures";
import { openCommandCenter } from "../support/helpers/command-center";
import { runWorkspaceActionFromCommandCenter } from "../support/helpers/command-center-workspace-actions";
import { submitMessageWithButton } from "../support/helpers/composer";
import { openFileExplorer, openFileFromExplorer } from "../support/helpers/file-explorer";
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
import { connectNewWorkspaceDaemonClient } from "../support/helpers/new-workspace";
import { copyPluginExample } from "../support/helpers/plugin-fixture";
import { runCommand } from "../support/helpers/plugin-sidebar-items";
import {
closeSheet,
expectNoSheetOpen,
expectOneSheetOpen,
promptMentioning,
sheet,
} from "../support/helpers/sheet";
import {
closeMobileExplorer,
expectMobileExplorerHidden,
expectMobileExplorerVisible,
openMobileAgentSidebar,
selectWorkspaceInSidebar,
} from "../support/helpers/sidebar";
import { getServerId } from "../support/helpers/server-id";
const WIDE = { width: 1600, height: 900 };
const COMPACT = { width: 390, height: 844 };
const AGENT_TITLE = "Layout agent";
const FILE_LINK = "README.md:1";
const NO_FILE = "Focus a file to see its outline";
const REPO_FILES = [
{ path: "README.md", content: "# Guide\n\n## Install\n" },
{ path: "notes.md", content: "# Notes\n\n## Open questions\n" },
{ path: "src/app.ts", content: "// TODO: handle errors\nexport const ready = true;\n" },
];
const REVIEW_TAB = "workspace-tab-plugin_agent_16_workspace-layout_6_review_";
const FINDINGS_TAB = "workspace-tab-plugin_workspace_16_workspace-layout_8_findings";
const OUTLINE_TAB = "workspace-tab-plugin_workspace_16_workspace-layout_7_outline";
async function withLayoutExample(
initialPrompt: string | undefined,
run: (agent: { agentId: string; workspaceId: string }) => Promise<void>,
): Promise<void> {
const example = await copyPluginExample("workspace-layout");
const workspace = await seedMockAgentWorkspace({
repoPrefix: "plugin-workspace-layout-",
title: AGENT_TITLE,
repo: { files: REPO_FILES },
initialPrompt,
});
try {
await withPluginInstalled(example.directory, () => run(workspace));
} finally {
await workspace.cleanup();
await example.cleanup();
}
}
async function withPluginInstalled(directory: string, run: () => Promise<void>): Promise<void> {
const client = await connectNewWorkspaceDaemonClient({ ownProjects: false });
const previous = await client.getDaemonConfig();
try {
await client.patchDaemonConfig({ pluginsEnabled: true });
await client.installDirectoryPlugin(directory);
await run();
} finally {
await client.removePlugin("workspace-layout").catch(() => undefined);
await client.patchDaemonConfig({ pluginsEnabled: previous.config.pluginsEnabled ?? false });
await client.close();
}
}
/** `/open-elsewhere <id>` opens a file in that workspace, then one where the command ran. */
const OPEN_ELSEWHERE_ENTRY = `import type { PluginClientContext } from "@getpaseo/plugin/client";
export default function contribute(client: PluginClientContext) {
client.addSlashCommand({
name: "open-elsewhere",
description: "Open a file there, then one here",
argumentHint: "<workspaceId>",
context: "agent",
onSubmit({ args, workspaceLayout }) {
const there = client.workspaceLayout(args.trim());
there.open({ panelId: "paseo/file", params: { path: "README.md" } });
workspaceLayout.open({ panelId: "paseo/file", params: { path: "notes.md" } });
},
});
return () => {};
}
`;
async function withTwoWorkspaces(
run: (workspaces: {
first: { agentId: string; workspaceId: string };
second: { agentId: string; workspaceId: string };
}) => Promise<void>,
): Promise<void> {
const example = await copyPluginExample("workspace-layout");
await writeFile(path.join(example.directory, "index.client.tsx"), OPEN_ELSEWHERE_ENTRY);
const seed = (title: string) =>
seedMockAgentWorkspace({
repoPrefix: "plugin-workspace-layout-",
title,
repo: { files: REPO_FILES },
});
const first = await seed("First agent");
const second = await seed("Second agent");
try {
await withPluginInstalled(example.directory, () => run({ first, second }));
} finally {
await second.cleanup();
await first.cleanup();
await example.cleanup();
}
}
/** Picks a workspace in a phone's agent list. */
async function switchToWorkspace(page: Page, workspaceId: string): Promise<void> {
await openMobileAgentSidebar(page);
await selectWorkspaceInSidebar(page, workspaceId);
await expect(
page.getByTestId(`workspace-deck-entry-${getServerId()}:${workspaceId}`),
).toBeVisible();
await expect(composerIn(page.locator("body"))).toBeEditable({ timeout: 30_000 });
}
function mainPanes(page: Page): Locator {
return page.locator('[data-testid^="workspace-pane-"]').filter({ visible: true });
}
function explorer(page: Page): Locator {
return page.getByTestId("workspace-explorer-sidebar");
}
function agentTabs(scope: Locator): Locator {
return scope.locator('[data-testid^="workspace-tab-agent_"]');
}
function composerIn(scope: Locator): Locator {
return scope.getByRole("textbox", { name: "Message agent..." }).filter({ visible: true });
}
async function sendToMainChat(page: Page, text: string): Promise<void> {
const composer = composerIn(mainPanes(page).first());
await expect(composer).toBeEditable({ timeout: 30_000 });
await composer.fill(text);
await composer.press("Enter");
}
async function expectAsideChat(page: Page, input: { message: string; tabs: number }) {
const chats = agentTabs(explorer(page));
await expect(chats).toHaveCount(input.tabs, { timeout: 30_000 });
await expect(chats.last()).toHaveAttribute("aria-selected", "true");
await expect(
explorer(page).getByTestId("user-message").getByText(input.message, { exact: true }),
).toBeVisible();
await expect(composerIn(explorer(page))).toBeEditable();
}
/** Every visible tab chip, pane by pane, to compare the arrangement before and after. */
async function tabsByPane(page: Page): Promise<string[][]> {
const scopes = [...(await mainPanes(page).all()), explorer(page)];
return Promise.all(
scopes.map((scope) =>
scope
.getByTestId("workspace-tabs-row")
.locator('[data-testid^="workspace-tab-"]:not([data-testid^="workspace-tab-tooltip"])')
.evaluateAll((chips) => chips.map((chip) => chip.getAttribute("data-testid") ?? "")),
),
);
}
async function expectReviewLayout(page: Page, agentId: string): Promise<void> {
await expect(mainPanes(page)).toHaveCount(2);
const left = mainPanes(page).first();
const right = mainPanes(page).last();
await expect(left.getByTestId(`workspace-tab-agent_${agentId}`)).toBeVisible();
const review = right.getByTestId(`${REVIEW_TAB}${agentId.length}_${agentId}`);
await expect(review).toHaveAttribute("aria-selected", "true");
await expect(right.getByText(`Reviewing ${AGENT_TITLE}`, { exact: true })).toBeVisible();
await expect(right.getByTestId("workspace-tab-working_diff")).toHaveAttribute(
"aria-selected",
"false",
);
await expect(explorer(page).getByTestId(FINDINGS_TAB)).toBeVisible();
const [leftBox, rightBox] = [await left.boundingBox(), await right.boundingBox()];
if (!leftBox || !rightBox) throw new Error("Review layout panes have no bounds");
expect(rightBox.x).toBeGreaterThan(leftBox.x);
expect(rightBox.width / (leftBox.width + rightBox.width)).toBeCloseTo(0.4, 1);
}
async function openFileInFocusedPane(page: Page, name: string): Promise<void> {
await openFileExplorer(page);
await openFileFromExplorer(page, name);
await expect(mainPanes(page).getByTestId(`workspace-tab-file_${name}`)).toBeVisible();
}
async function expectOutline(page: Page, lines: string[]): Promise<void> {
const outline = page.getByTestId("workspace-layout-outline");
for (const line of lines) {
await expect(outline.getByText(line, { exact: true })).toHaveCount(1);
}
}
test("the workspace layout example arranges a wide workspace", async ({ page }) => {
test.setTimeout(180_000);
await withLayoutExample(undefined, async ({ agentId, workspaceId }) => {
await page.setViewportSize(WIDE);
await openAgentRoute(page, { workspaceId, agentId });
await test.step("/aside opens the child agent's chat in the Explorer", async () => {
await sendToMainChat(page, "/aside hey");
await expectAsideChat(page, { message: "hey", tabs: 1 });
await expect(agentTabs(mainPanes(page))).toHaveCount(1);
});
await test.step("a second /aside adds a second tab", async () => {
await sendToMainChat(page, "/aside again");
await expectAsideChat(page, { message: "again", tabs: 2 });
await expect(agentTabs(mainPanes(page))).toHaveCount(1);
});
await test.step("Review layout splits the workspace, and running it again changes nothing", async () => {
await runCommand(page, "Review layout");
await expectReviewLayout(page, agentId);
const arranged = await tabsByPane(page);
await mainPanes(page).first().getByTestId(`workspace-tab-agent_${agentId}`).click();
await runCommand(page, "Review layout");
await expectReviewLayout(page, agentId);
expect(await tabsByPane(page)).toEqual(arranged);
});
await test.step("the outline follows the focused file across split panes", async () => {
await mainPanes(page).first().getByTestId(`workspace-tab-agent_${agentId}`).click();
await runCommand(page, "Show outline");
await expectOutline(page, [NO_FILE]);
await openFileInFocusedPane(page, "README.md");
await explorer(page).getByTestId(OUTLINE_TAB).click();
await expectOutline(page, ["README.md", "Guide", "Install"]);
await runWorkspaceActionFromCommandCenter(page, "Split pane right");
await expect(mainPanes(page)).toHaveCount(3);
await openFileInFocusedPane(page, "notes.md");
await explorer(page).getByTestId(OUTLINE_TAB).click();
await expectOutline(page, ["notes.md", "Notes", "Open questions"]);
await mainPanes(page).getByTestId("workspace-tab-file_README.md").click();
await expectOutline(page, ["README.md", "Guide", "Install"]);
});
});
});
test("the workspace layout example opens over a phone's chat", async ({ page }) => {
test.setTimeout(180_000);
await withLayoutExample(promptMentioning(FILE_LINK), async ({ agentId, workspaceId }) => {
await page.setViewportSize(COMPACT);
await openAgentRoute(page, { workspaceId, agentId });
await test.step("/aside opens the Explorer over the chat", async () => {
await submitMessageWithButton(page, "/aside hey");
await expectMobileExplorerVisible(page);
await expectAsideChat(page, { message: "hey", tabs: 1 });
await closeMobileExplorer(page);
await expectMobileExplorerHidden(page);
await expect(
page.getByRole("button", { name: "Switch tabs (1 open)" }).filter({ visible: true }),
).toBeVisible();
});
await test.step("a file sheet updates the outline, and closing it restores it", async () => {
await openMobileAgentSidebar(page);
const commandCenter = await openCommandCenter(page);
await commandCenter.getByTestId("command-center-input").fill("Show outline");
await commandCenter.getByRole("button", { name: "Show outline", exact: true }).click();
await expectMobileExplorerVisible(page);
await expectOutline(page, [NO_FILE]);
await closeMobileExplorer(page);
await expectMobileExplorerHidden(page);
await page.getByText(FILE_LINK, { exact: true }).first().click();
await expect(sheet(page, "README.md")).toBeVisible();
// The sheet covers the Explorer, so the outline can only be read, not seen.
await expectOutline(page, ["README.md", "Guide", "Install"]);
await closeSheet(page, "README.md");
await expectOutline(page, [NO_FILE]);
});
});
});
test("a file a plugin opens in another workspace waits there on a phone", async ({ page }) => {
test.setTimeout(180_000);
await withTwoWorkspaces(async ({ first, second }) => {
await page.setViewportSize(COMPACT);
// Visiting the first workspace leaves its screen mounted behind the second.
await openAgentRoute(page, first);
await expect(composerIn(page.locator("body"))).toBeEditable({ timeout: 30_000 });
await switchToWorkspace(page, second.workspaceId);
await test.step("only the sheet of the workspace on screen is shown", async () => {
await submitMessageWithButton(page, `/open-elsewhere ${first.workspaceId}`);
await expect(sheet(page, "notes.md")).toBeVisible();
await expectOneSheetOpen(page);
await closeSheet(page, "notes.md");
await expectNoSheetOpen(page);
});
await test.step("the other sheet is there when the user goes to its workspace", async () => {
await switchToWorkspace(page, first.workspaceId);
await expect(sheet(page, "README.md")).toBeVisible();
await expectOneSheetOpen(page);
await closeSheet(page, "README.md");
await expectNoSheetOpen(page);
});
});
});
@@ -0,0 +1,605 @@
import { mkdir } from "node:fs/promises";
import path from "node:path";
import type { Locator } from "@playwright/test";
import { expect, test, type Page } from "../support/fixtures";
import { expectAgentIdle, expectAgentReadyToInterrupt } from "../support/helpers/agent-stream";
import {
drillIntoProvider,
expectComposerMode,
expectComposerModel,
openModelPicker,
selectModelRow,
} from "../support/helpers/agent-profiles";
import { expectWorkspaceAgentConfiguration } from "../support/helpers/command-center-agent-controls";
import {
expectComposerVisible,
expectQueuedMessageButton,
submitMessage,
submitMessageWithButton,
} from "../support/helpers/composer";
import { connectDaemonClient } from "../support/helpers/daemon-client-loader";
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
import { copyPluginExample } from "../support/helpers/plugin-fixture";
import { userScrollsTimelineToHistoryStart } from "../support/helpers/timeline-pagination";
const DIRECT_PROVIDER = {
id: "direct-example",
label: "Direct provider example",
pluginId: "provider-direct-example",
modelId: "example-1",
modelLabel: "Example 1",
modeLabel: "Build",
} as const;
// Disable external CLIs so the E2E host deterministically exposes only Mock +
// the installed Direct provider plugin on both developer machines and CI.
test.use({
e2eDaemonConfig: {
version: 1,
agents: {
providers: {
claude: { enabled: false },
codex: { enabled: false },
copilot: { enabled: false },
opencode: { enabled: false },
pi: { enabled: false },
omp: { enabled: false },
antigravity: { enabled: false },
hoplite: { enabled: false },
},
},
},
});
interface PluginInstallDaemonClient {
connect(): Promise<void>;
close(): Promise<void>;
getDaemonConfig(): Promise<{ config: { pluginsEnabled?: boolean } }>;
patchDaemonConfig(config: { pluginsEnabled?: boolean }): Promise<unknown>;
installDirectoryPlugin(directory: string): Promise<unknown>;
removePlugin(pluginId: string): Promise<void>;
getProvidersSnapshot(): Promise<{
entries: Array<{ provider: string; available?: boolean }>;
}>;
}
async function hasDirectProvider(client: PluginInstallDaemonClient): Promise<boolean> {
const snapshot = await client.getProvidersSnapshot();
return snapshot.entries.some((entry) => entry.provider === DIRECT_PROVIDER.id);
}
async function expectSwitchMarkerCountAfterScroll(page: Page, expected: number): Promise<void> {
await expect
.poll(
async () => {
await userScrollsTimelineToHistoryStart(page);
return await page.getByTestId("provider-switch-marker").count();
},
{ timeout: 30_000 },
)
.toBe(expected);
}
async function captureQaScreenshot(page: Page, fileName: string): Promise<void> {
const dir = process.env.PASEO_QA_SCREENSHOT_DIR?.trim();
if (!dir) return;
await mkdir(dir, { recursive: true });
await page.screenshot({ path: path.join(dir, fileName), fullPage: false });
}
async function expectNoHorizontalOverflow(page: Page): Promise<void> {
const overflow = await page.evaluate(() => {
const doc = document.documentElement;
return Math.ceil(doc.scrollWidth - doc.clientWidth);
});
expect(overflow).toBeLessThanOrEqual(1);
}
async function startSwitchOrderGuard(page: Page): Promise<void> {
await page.evaluate(() => {
const violations: string[] = [];
let stopped = false;
const step = () => {
const msgs = Array.from(document.querySelectorAll('[data-testid="user-message"]'));
const markers = Array.from(
document.querySelectorAll('[data-testid="provider-switch-marker"]'),
);
const banner = document.querySelector('[data-testid="staged-provider-switch-banner"]');
if (msgs.length >= 2) {
const secondMsg = msgs[msgs.length - 1];
const lastMarker = markers[markers.length - 1];
if (!lastMarker) {
violations.push("user-message painted without switch marker");
} else {
const msgRect = secondMsg.getBoundingClientRect();
const markerRect = lastMarker.getBoundingClientRect();
if (markerRect.top > msgRect.top) {
violations.push(
`switch marker painted below user-message (${Math.round(markerRect.top)} > ${Math.round(msgRect.top)})`,
);
}
}
if (banner && banner.getBoundingClientRect().height > 0) {
violations.push("staged-provider-switch-banner stayed visible after submit");
}
}
if (!stopped) requestAnimationFrame(step);
};
requestAnimationFrame(step);
(window as unknown as { __stopSwitchOrderGuard?: () => string[] }).__stopSwitchOrderGuard =
() => {
stopped = true;
return violations;
};
});
}
async function stopSwitchOrderGuard(page: Page): Promise<string[]> {
return await page.evaluate(
() =>
(
window as unknown as { __stopSwitchOrderGuard?: () => string[] }
).__stopSwitchOrderGuard?.() ?? [],
);
}
async function completeMockTurn(
page: Page,
agent: Awaited<ReturnType<typeof seedMockAgentWorkspace>>,
prompt: string,
): Promise<Locator> {
await submitMessage(page, prompt);
const userMessage = page.getByTestId("user-message").filter({ hasText: prompt });
await expect(userMessage).toBeVisible({ timeout: 30_000 });
const finish = await agent.client.waitForFinish(agent.agentId, 30_000);
expect(finish.status).toBe("idle");
await expectAgentIdle(page);
await expect(userMessage).toHaveAttribute("aria-busy", "false");
return userMessage;
}
async function completeDirectTurn(
page: Page,
agent: Awaited<ReturnType<typeof seedMockAgentWorkspace>>,
prompt: string,
options?: { useSendButton?: boolean },
): Promise<Locator> {
if (options?.useSendButton) {
await submitMessageWithButton(page, prompt);
} else {
await submitMessage(page, prompt);
}
const userMessage = page.getByTestId("user-message").filter({ hasText: prompt });
await expect(userMessage).toBeVisible({ timeout: 30_000 });
const finish = await agent.client.waitForFinish(agent.agentId, 30_000);
expect(finish.status).toBe("idle");
await expectAgentIdle(page);
await expect(userMessage).toHaveAttribute("aria-busy", "false");
return userMessage;
}
async function stageProviderDesktop(
page: Page,
providerId: string,
modelId: string,
): Promise<void> {
await openModelPicker(page);
const picker = page.getByTestId("combobox-desktop-container");
const backButton = picker.getByTestId("sheet-header-back");
if (await backButton.isVisible()) {
await backButton.click();
}
await drillIntoProvider(page, providerId);
await selectModelRow(page, { provider: providerId, modelId });
await expect(page.getByTestId("staged-provider-switch-banner")).toBeVisible({ timeout: 30_000 });
}
async function stageDirectProviderDesktop(page: Page): Promise<void> {
await stageProviderDesktop(page, DIRECT_PROVIDER.id, DIRECT_PROVIDER.modelId);
}
async function stageDirectProviderCompact(page: Page): Promise<void> {
await page.getByTestId("combined-model-selector").filter({ visible: true }).first().click();
await expect(page.getByTestId("agent-controls-model")).toBeVisible({ timeout: 30_000 });
await page.getByTestId("agent-controls-model").click();
const modelPage = page.getByTestId("mobile-model-page");
await expect(modelPage).toBeVisible({ timeout: 30_000 });
const collapsedProvider = modelPage.getByTestId(`model-provider-${DIRECT_PROVIDER.id}`);
if (await collapsedProvider.isVisible()) {
await collapsedProvider.click();
}
await modelPage.getByTestId(`model-row-${DIRECT_PROVIDER.id}-${DIRECT_PROVIDER.modelId}`).click();
await expect(page.getByTestId("agent-controls-settings-list")).toBeVisible({ timeout: 30_000 });
// Dismiss the agent-controls sheet so the composer and banner are ready to submit.
await page.getByRole("button", { name: "Close", exact: true }).last().click();
await expect(page.getByTestId("agent-controls-model")).toHaveCount(0, { timeout: 30_000 });
await expect(page.getByTestId("staged-provider-switch-banner")).toBeVisible({ timeout: 30_000 });
}
async function rewindConversation(page: Page, userMessage: Locator, prompt: string): Promise<void> {
await userMessage.getByText(prompt, { exact: true }).hover();
await userMessage.getByRole("button", { name: "Rewind to this message", exact: true }).click();
await page.getByRole("menuitem", { name: "Rewind conversation", exact: true }).click();
}
test.describe.serial("Provider switching in chat", () => {
let pluginClient: PluginInstallDaemonClient;
let pluginFixture: Awaited<ReturnType<typeof copyPluginExample>>;
let previousPluginsEnabled: boolean | undefined;
test.beforeAll(async () => {
pluginClient = await connectDaemonClient<PluginInstallDaemonClient>({
clientIdPrefix: "provider-switching-e2e",
});
pluginFixture = await copyPluginExample("provider-direct");
previousPluginsEnabled = (await pluginClient.getDaemonConfig()).config.pluginsEnabled;
await pluginClient.patchDaemonConfig({ pluginsEnabled: true });
await pluginClient.installDirectoryPlugin(pluginFixture.directory);
await expect.poll(() => hasDirectProvider(pluginClient), { timeout: 30_000 }).toBe(true);
});
test.afterAll(async () => {
await pluginClient?.removePlugin(DIRECT_PROVIDER.pluginId).catch(() => undefined);
await pluginClient
?.patchDaemonConfig({ pluginsEnabled: previousPluginsEnabled })
.catch(() => undefined);
await pluginClient?.close().catch(() => undefined);
await pluginFixture?.cleanup().catch(() => undefined);
});
test("stages, cancels, switches providers, inspects marker, scopes rewind, and survives reload", async ({
page,
}) => {
test.setTimeout(150_000);
await page.setViewportSize({ width: 1280, height: 800 });
const preSwitchPrompt = "First prompt on Mock before switching.";
const postSwitchPrompt = "Follow up on Direct provider after switching.";
const postRewindPrompt = "Continue on Direct provider after rewinding.";
const workspace = await seedMockAgentWorkspace({
repoPrefix: "provider-switch-desktop-",
title: "Provider switch desktop",
model: "e2e-fast-stream",
modeId: "load-test",
});
try {
await openAgentRoute(page, workspace);
await expectComposerVisible(page);
await expectComposerMode(page, "Load test");
const initialUrl = page.url();
await completeMockTurn(page, workspace, preSwitchPrompt);
await test.step("staging updates only draft state and Cancel restores the live provider", async () => {
await stageDirectProviderDesktop(page);
await expectComposerModel(page, DIRECT_PROVIDER.modelLabel);
await expectComposerMode(page, DIRECT_PROVIDER.modeLabel);
await expect(page.getByTestId("staged-provider-switch-banner")).toContainText(
DIRECT_PROVIDER.label,
);
await expectWorkspaceAgentConfiguration(workspace, {
id: workspace.agentId,
provider: "mock",
model: "e2e-fast-stream",
modeId: "load-test",
});
// Editing a staged provider option must keep all staged option controls visible.
const conciseToggle = page.getByRole("button", { name: /Concise responses/i }).first();
const voiceSelect = page.getByRole("button", { name: /Voice/i }).first();
await expect(conciseToggle).toBeVisible();
await expect(voiceSelect).toBeVisible();
await conciseToggle.click();
await expect(conciseToggle).toBeVisible();
await expect(voiceSelect).toBeVisible();
await expectNoHorizontalOverflow(page);
await captureQaScreenshot(page, "desktop-staged-switch.png");
await page.getByTestId("cancel-staged-provider-switch").click();
await expect(page.getByTestId("staged-provider-switch-banner")).toHaveCount(0);
await expectComposerMode(page, "Load test");
// Returning to the live provider by choosing a different model clears the staged switch
// and applies the newly chosen model directly to the live provider.
await stageDirectProviderDesktop(page);
await openModelPicker(page);
const picker = page.getByTestId("combobox-desktop-container");
const backButton = picker.getByTestId("sheet-header-back");
if (await backButton.isVisible()) {
await backButton.click();
}
await drillIntoProvider(page, "mock");
await selectModelRow(page, { provider: "mock", modelId: "one-minute-stream" });
await expect(page.getByTestId("staged-provider-switch-banner")).toHaveCount(0);
await expectComposerModel(page, "One minute stream");
await expectWorkspaceAgentConfiguration(workspace, {
id: workspace.agentId,
provider: "mock",
model: "one-minute-stream",
modeId: "load-test",
});
});
await test.step("submitting commits the switch in place with clean user display text and inspectable marker", async () => {
await stageDirectProviderDesktop(page);
await startSwitchOrderGuard(page);
const switchedMessage = await completeDirectTurn(page, workspace, postSwitchPrompt);
expect(await stopSwitchOrderGuard(page)).toEqual([]);
expect(page.url()).toBe(initialUrl);
await expect(page.getByTestId("staged-provider-switch-banner")).toHaveCount(0);
await expectWorkspaceAgentConfiguration(workspace, {
id: workspace.agentId,
provider: DIRECT_PROVIDER.id,
model: DIRECT_PROVIDER.modelId,
modeId: "build",
});
// Clean display text: handoff summary must never leak into the visible user bubble.
await expect(switchedMessage).toContainText(postSwitchPrompt);
await expect(switchedMessage).not.toContainText("<chat-history-summary>");
// Direct provider echoes its prompt, proving bounded pre-switch context was attached.
const directReply = page
.getByTestId("assistant-message")
.filter({ hasText: "Echo:" })
.last();
await expect(directReply).toContainText(preSwitchPrompt);
await expect(directReply).toContainText(postSwitchPrompt);
// Switch marker is visible and expands to show context handoff details.
const marker = page.getByTestId("provider-switch-marker");
await expect(marker).toBeVisible({ timeout: 30_000 });
await marker.scrollIntoViewIfNeeded();
await marker.getByTestId("provider-switch-marker-toggle").click();
const details = marker.getByTestId("provider-switch-marker-details");
await expect(details).toBeVisible();
await expect(details).toContainText("Mock");
await expect(details).toContainText(DIRECT_PROVIDER.label);
await marker.scrollIntoViewIfNeeded();
await expectNoHorizontalOverflow(page);
await captureQaScreenshot(page, "desktop-switched-expanded.png");
await marker.getByTestId("provider-switch-marker-toggle").click();
await expect(details).toHaveCount(0);
});
await test.step("switching back to Mock enforces segment-scoped rewind and preserves pre-switch turns", async () => {
const backToMockPrompt = "Switch back to Mock for segment-scoped rewind.";
await stageProviderDesktop(page, "mock", "ten-second-stream");
await expect(page.getByTestId("staged-provider-switch-banner")).toContainText("Mock");
const backToMockMessage = await completeMockTurn(page, workspace, backToMockPrompt);
await expect(backToMockMessage).not.toContainText("<chat-history-summary>");
await expect(page.getByTestId("provider-switch-marker")).toHaveCount(2, {
timeout: 30_000,
});
await expectWorkspaceAgentConfiguration(workspace, {
id: workspace.agentId,
provider: "mock",
model: "ten-second-stream",
modeId: "load-test",
});
// Pre-switch prompts from earlier segments must not expose rewind even though Mock supports it.
const preSwitchMessage = page
.getByTestId("user-message")
.filter({ hasText: preSwitchPrompt });
await preSwitchMessage.scrollIntoViewIfNeeded();
await preSwitchMessage.getByText(preSwitchPrompt, { exact: true }).hover();
await expect(
preSwitchMessage.getByRole("button", { name: "Rewind to this message", exact: true }),
).toHaveCount(0);
const directMessage = page
.getByTestId("user-message")
.filter({ hasText: postSwitchPrompt });
await directMessage.scrollIntoViewIfNeeded();
await directMessage.getByText(postSwitchPrompt, { exact: true }).hover();
await expect(
directMessage.getByRole("button", { name: "Rewind to this message", exact: true }),
).toHaveCount(0);
// Post-switch prompt on Mock CAN rewind without retiring earlier segments or markers.
await backToMockMessage.scrollIntoViewIfNeeded();
await rewindConversation(page, backToMockMessage, backToMockPrompt);
await expect(
page.getByTestId("user-message").filter({ hasText: backToMockPrompt }),
).toHaveCount(0, { timeout: 30_000 });
await expect(
page.getByTestId("user-message").filter({ hasText: preSwitchPrompt }),
).toBeVisible();
await expect(
page.getByTestId("user-message").filter({ hasText: postSwitchPrompt }),
).toBeVisible();
await expect(page.getByTestId("provider-switch-marker")).toHaveCount(2);
// Continuing in the now-empty active segment completes cleanly.
const retriedMessage = await completeMockTurn(page, workspace, postRewindPrompt);
await expect(retriedMessage).not.toContainText("<chat-history-summary>");
});
await test.step("reload preserves the switched provider, markers, and rewind boundary", async () => {
await page.reload();
await expectComposerVisible(page);
await expectComposerModel(page, "Ten second stream");
await expectSwitchMarkerCountAfterScroll(page, 2);
const reloadedDirect = page
.getByTestId("user-message")
.filter({ hasText: postSwitchPrompt });
await expect(reloadedDirect).toBeVisible();
await expect(
page.getByTestId("user-message").filter({ hasText: postRewindPrompt }),
).toBeVisible();
await reloadedDirect.scrollIntoViewIfNeeded();
await reloadedDirect.getByText(postSwitchPrompt, { exact: true }).hover();
await expect(
reloadedDirect.getByRole("button", { name: "Rewind to this message", exact: true }),
).toHaveCount(0);
});
} finally {
await workspace.cleanup();
}
});
test("stages a switch mid-turn, queues the prompt, and switches cleanly between turns", async ({
page,
}) => {
test.setTimeout(150_000);
await page.setViewportSize({ width: 1280, height: 800 });
const runningPrompt = "Run a ten-second mock turn first.";
const queuedPrompt = "Queued handoff prompt for Direct provider.";
const workspace = await seedMockAgentWorkspace({
repoPrefix: "provider-switch-midturn-",
title: "Provider switch midturn",
model: "ten-second-stream",
modeId: "load-test",
});
try {
await openAgentRoute(page, workspace);
await expectComposerVisible(page);
await submitMessage(page, runningPrompt);
await expectAgentReadyToInterrupt(page);
// Stage Direct provider while Mock is actively streaming.
await stageDirectProviderDesktop(page);
await expectWorkspaceAgentConfiguration(workspace, {
id: workspace.agentId,
provider: "mock",
model: "ten-second-stream",
modeId: "load-test",
});
// Submitting queues the prompt instead of racing the live turn.
await submitMessage(page, queuedPrompt);
await expectQueuedMessageButton(page);
// Once the mock turn completes, the queue drains and commits the switch.
await expect(page.getByTestId("provider-switch-marker")).toBeVisible({ timeout: 45_000 });
await expect(page.getByTestId("staged-provider-switch-banner")).toHaveCount(0, {
timeout: 30_000,
});
await expect(
page.getByTestId("assistant-message").filter({ hasText: queuedPrompt }).last(),
).toBeVisible({ timeout: 30_000 });
await expectAgentIdle(page);
await expectWorkspaceAgentConfiguration(workspace, {
id: workspace.agentId,
provider: DIRECT_PROVIDER.id,
model: DIRECT_PROVIDER.modelId,
modeId: "build",
});
} finally {
await workspace.cleanup();
}
});
test("edits a queued switch and sends it now, cutting the running turn", async ({ page }) => {
test.setTimeout(150_000);
await page.setViewportSize({ width: 1280, height: 800 });
const queuedPrompt = "Take over now on the Direct provider.";
const workspace = await seedMockAgentWorkspace({
repoPrefix: "provider-switch-queued-edit-",
title: "Provider switch queued edit",
model: "one-minute-stream",
modeId: "load-test",
});
try {
await openAgentRoute(page, workspace);
await expectComposerVisible(page);
await submitMessage(page, "Run a one-minute mock turn first.");
await expectAgentReadyToInterrupt(page);
await stageDirectProviderDesktop(page);
const banner = page.getByTestId("staged-provider-switch-banner");
const queuedRow = page.getByRole("listitem").filter({ hasText: queuedPrompt });
await submitMessage(page, queuedPrompt);
await expect(queuedRow).toContainText(`Switches to ${DIRECT_PROVIDER.label}`);
await expect(banner).toHaveCount(0);
await captureQaScreenshot(page, "queued-provider-switch.png");
await queuedRow.getByRole("button", { name: "Edit queued message" }).click();
await expect(queuedRow).toHaveCount(0);
await expect(banner).toBeVisible();
await submitMessage(page, queuedPrompt);
await expect(queuedRow).toContainText(`Switches to ${DIRECT_PROVIDER.label}`);
await queuedRow.getByRole("button", { name: "Send queued message now" }).click();
await expect(page.getByTestId("provider-switch-marker")).toBeVisible({ timeout: 30_000 });
await expect(
page.getByTestId("assistant-message").filter({ hasText: queuedPrompt }).last(),
).toBeVisible({ timeout: 30_000 });
await expectAgentIdle(page);
await expectWorkspaceAgentConfiguration(workspace, {
id: workspace.agentId,
provider: DIRECT_PROVIDER.id,
model: DIRECT_PROVIDER.modelId,
modeId: "build",
});
} finally {
await workspace.cleanup();
}
});
test("switches providers cleanly on a compact viewport with zero horizontal overflow", async ({
page,
}) => {
test.setTimeout(150_000);
await page.setViewportSize({ width: 390, height: 844 });
const preSwitchPrompt = "Compact turn on Mock.";
const postSwitchPrompt = "Compact handoff on Direct.";
const workspace = await seedMockAgentWorkspace({
repoPrefix: "provider-switch-compact-",
title: "Provider switch compact",
model: "e2e-fast-stream",
modeId: "load-test",
});
try {
await openAgentRoute(page, workspace);
await expectComposerVisible(page);
await submitMessageWithButton(page, preSwitchPrompt);
await expect(
page.getByTestId("user-message").filter({ hasText: preSwitchPrompt }),
).toBeVisible({ timeout: 30_000 });
const firstFinish = await workspace.client.waitForFinish(workspace.agentId, 30_000);
expect(firstFinish.status).toBe("idle");
await expectAgentIdle(page);
await stageDirectProviderCompact(page);
await expectNoHorizontalOverflow(page);
await captureQaScreenshot(page, "compact-staged-switch.png");
const switchedMessage = await completeDirectTurn(page, workspace, postSwitchPrompt, {
useSendButton: true,
});
await expect(switchedMessage).not.toContainText("<chat-history-summary>");
const marker = page.getByTestId("provider-switch-marker");
await expect(marker).toBeVisible({ timeout: 30_000 });
await marker.scrollIntoViewIfNeeded();
const toggle = marker.getByTestId("provider-switch-marker-toggle");
const toggleBox = await toggle.boundingBox();
expect(toggleBox).not.toBeNull();
expect((toggleBox?.x ?? 0) + (toggleBox?.width ?? 0)).toBeLessThanOrEqual(390);
await toggle.click();
await expect(marker.getByTestId("provider-switch-marker-details")).toBeVisible();
await marker.scrollIntoViewIfNeeded();
await expectNoHorizontalOverflow(page);
await captureQaScreenshot(page, "compact-switched-expanded.png");
} finally {
await workspace.cleanup();
}
});
});
@@ -235,7 +235,7 @@ test.describe("Rewind sheet", () => {
await expect(page.getByTestId("rewind-menu-content")).toHaveCount(0);
await expect(userMessage(page, secondPrompt)).toHaveCount(0);
await expect(page.getByText("Cycle 1", { exact: true })).toHaveCount(0);
await expectUserMessageCount(page, 1);
await expectUserMessageCount(page, 0);
await expectComposerDraft(page, firstPrompt);
await expectComposerFocused(page);
@@ -243,7 +243,7 @@ test.describe("Rewind sheet", () => {
await expectUserMessageVisible(page, replacementPrompt);
await expect(userMessage(page, secondPrompt)).toHaveCount(0);
await expect(page.getByText("Cycle 1", { exact: true })).toHaveCount(0);
await expectUserMessageCount(page, 2);
await expectUserMessageCount(page, 1);
await fillComposerDraft(page, "");
await composerLocator(page).evaluate((element) => element.blur());
@@ -254,7 +254,19 @@ test.describe("Rewind sheet", () => {
await expect(page.getByTestId("rewind-menu-content")).toHaveCount(0);
await expectComposerDraft(page, "");
await expectComposerNotFocused(page);
await expectUserMessageCount(page, 2);
await expectUserMessageCount(page, 1);
const preservedDraft = "Keep this human draft after rewind.";
await fillComposerDraft(page, preservedDraft);
await composerLocator(page).evaluate((element) => element.blur());
await userMessage(page, replacementPrompt).hover();
await page.getByTestId("rewind-menu-trigger").last().click();
await expect(page.getByTestId("rewind-menu-content")).toBeVisible();
await selectRewindOption(page, "Rewind files");
await expect(page.getByTestId("rewind-menu-content")).toHaveCount(0);
await expectComposerDraft(page, preservedDraft);
await expectComposerNotFocused(page);
await expectUserMessageCount(page, 1);
await fillComposerDraft(page, "");
await composerLocator(page).evaluate((element) => element.blur());
@@ -265,7 +277,7 @@ test.describe("Rewind sheet", () => {
await expect(page.getByTestId("rewind-menu-content")).toHaveCount(0);
await expectComposerDraft(page, replacementPrompt);
await expectComposerFocused(page);
await expectUserMessageCount(page, 1);
await expectUserMessageCount(page, 0);
} finally {
await session.cleanup();
}
@@ -0,0 +1,296 @@
import { writeFile } from "node:fs/promises";
import { test, expect } from "../support/fixtures";
import {
readReactRenders,
recordReactRenders,
resetReactRenders,
} from "../support/helpers/react-renders";
import {
captureLoaderSteps,
freezeAnimationsAt,
openIdleChatBesideRunningAgent,
openQuietRunningTurn,
readAnimatingTargets,
readLoaderStep,
readRunningAnimations,
recordIndicatorTurnovers,
recordLoaderStepChanges,
recordRingAngles,
runningToolCall,
statusRings,
workingLoader,
} from "../support/helpers/running-indicators";
import { measureSteadyStateActivity } from "../support/helpers/steady-state-activity";
import { setTabVisibility } from "../support/helpers/workspace-ui";
/**
* A running turn that is otherwise quiet shows three animated indicators: the six-dot loader, the
* tool-call label shimmer and the status rings. None of them may cost main-thread work: the
* browser's compositor carries them, so the page neither runs script, restyles nor repaints to
* keep them moving.
*
* The budgets sit between what the rest of the page does on its own and the cheapest way these
* indicators have been measured getting it wrong. With nothing moving, the main thread still
* commits to the compositor about three times a second (the elapsed counter and the app's own
* timers), and each commit restyles whatever is animating. Declaring the same animations as CSS
* `@keyframes` costs thirteen commits and fourteen restyles a second; driving them from script
* costs sixty frames a second.
*/
const SAMPLE_WINDOW_MS = 5_000;
const ANIMATION_FRAME_CALLBACKS_PER_SECOND_BUDGET = 2;
const STYLE_RECALCS_PER_SECOND_BUDGET = 8;
const MAIN_THREAD_COMMITS_PER_SECOND_BUDGET = 8;
const PAINTS_PER_SECOND_BUDGET = 4;
// The elapsed counter's repaint reports the whole viewport as its clip once a second. Sixty
// indicator frames a second repainted seventy viewports' worth.
const PAINTED_VIEWPORTS_PER_SECOND_BUDGET = 4;
const LOADER_PERIOD_MS = 950;
const LOADER_STEP_MS = LOADER_PERIOD_MS / 6;
const STATUS_RING_PERIOD_MS = 900;
const STATUS_RING_STEPS = 27;
// Thirty ring positions a second, plus the few frames a second the rest of the page draws. A ring
// that turns with the display draws sixty or more.
const RING_ONLY_FRAMES_PER_SECOND_BUDGET = 36;
// Thirty ring and shimmer positions a second, the loader's six, and the few frames a second the
// rest of the page draws. A shimmer that moves with the display draws sixty or more, and one whose
// steps fall between the ring's draws up to sixty.
const RUNNING_TURN_FRAMES_PER_SECOND_BUDGET = 42;
// A pass of the shimmer is a whole number of steps of 1000 / 30 ms; the mock's tool call label
// gives a pass of about 1.4 s.
const SHIMMER_MIN_STEPS = 30;
const SHIMMER_MAX_STEPS = 69;
// React renders these once when the indicator appears. Rendering again while the turn is quiet
// means the animation is being driven through React.
const INDICATOR_COMPONENTS = /SyncedLoader|StatusRing|Shimmer|ExpandableBadge|WorkingIndicator/;
function indicatorRenders(renders: Record<string, number>): string[] {
return Object.keys(renders).filter((name) => INDICATOR_COMPONENTS.test(name));
}
test.describe("Running indicators", () => {
test("keep moving without waking the main thread", async ({ page, browser }, testInfo) => {
test.setTimeout(180_000);
await recordReactRenders(page);
const agent = await openQuietRunningTurn(page);
try {
await resetReactRenders(page);
const activity = await measureSteadyStateActivity({
browser,
page,
windowMs: SAMPLE_WINDOW_MS,
});
const renders = await readReactRenders(page);
const animations = await readRunningAnimations(page);
const stepChanges = await recordLoaderStepChanges(page, 3_000);
const evidence = { activity, renders, animations, stepChanges };
await writeFile(testInfo.outputPath("evidence.json"), JSON.stringify(evidence, null, 2));
expect
.soft(activity.animationFrameCallbacksPerSecond)
.toBeLessThan(ANIMATION_FRAME_CALLBACKS_PER_SECOND_BUDGET);
expect.soft(activity.styleRecalcsPerSecond).toBeLessThan(STYLE_RECALCS_PER_SECOND_BUDGET);
expect.soft(activity.paintsPerSecond).toBeLessThan(PAINTS_PER_SECOND_BUDGET);
expect
.soft(activity.paintedViewportsPerSecond)
.toBeLessThan(PAINTED_VIEWPORTS_PER_SECOND_BUDGET);
expect
.soft(activity.mainThreadCommitsPerSecond)
.toBeLessThan(MAIN_THREAD_COMMITS_PER_SECOND_BUDGET);
expect.soft(indicatorRenders(renders)).toEqual([]);
// The cadence is part of the design: six even steps in 950 ms, in order.
const steps = stepChanges.slice(1);
expect.soft(steps.length).toBeGreaterThan(12);
for (let index = 1; index < steps.length; index += 1) {
expect.soft(steps[index].step).toBe((steps[index - 1].step + 1) % 6);
}
const measuredStepMs = (steps.at(-1)!.atMs - steps[0].atMs) / (steps.length - 1);
expect.soft(Math.abs(measuredStepMs - LOADER_STEP_MS)).toBeLessThan(8);
const ringAnimations = animations.filter((animation) => animation.target === "status-ring");
expect.soft(ringAnimations.length).toBeGreaterThan(0);
for (const ring of ringAnimations) {
expect.soft(ring).toMatchObject({
durationMs: STATUS_RING_PERIOD_MS,
easing: "linear",
iterations: Number.POSITIVE_INFINITY,
properties: ["transform"],
});
}
} finally {
await agent.cleanup();
}
});
test("a ring beside an idle chat redraws the window thirty times a second", async ({
page,
browser,
}, testInfo) => {
test.setTimeout(180_000);
const scene = await openIdleChatBesideRunningAgent(page);
try {
const animating = await readAnimatingTargets(page);
const activity = await measureSteadyStateActivity({
browser,
page,
windowMs: SAMPLE_WINDOW_MS,
});
const angles = await recordRingAngles(page, STATUS_RING_PERIOD_MS * 3);
await writeFile(
testInfo.outputPath("evidence.json"),
JSON.stringify({ animating, activity, angles }, null, 2),
);
// Nothing but rings is moving, so every frame drawn is a ring's.
expect.soft(new Set(animating)).toEqual(new Set(["status-ring"]));
expect
.soft(activity.compositorFramesPerSecond)
.toBeLessThan(RING_ONLY_FRAMES_PER_SECOND_BUDGET);
// The cadence is part of the design: the quarter is only ever at one of its even steps.
const stepDegrees = 360 / STATUS_RING_STEPS;
const offStep = angles.filter((angle) => {
const stepsAlong = angle / stepDegrees;
return Math.abs(stepsAlong - Math.round(stepsAlong)) * stepDegrees > 0.05;
});
expect.soft(offStep).toEqual([]);
expect.soft(angles.length).toBeGreaterThan(STATUS_RING_STEPS / 2);
expect.soft(angles.length).toBeLessThanOrEqual(STATUS_RING_STEPS);
} finally {
await scene.cleanup();
}
});
test("a running tool call beside a ring redraws the window thirty times a second", async ({
page,
browser,
}, testInfo) => {
test.setTimeout(180_000);
const agent = await openQuietRunningTurn(page);
try {
const activity = await measureSteadyStateActivity({
browser,
page,
windowMs: SAMPLE_WINDOW_MS,
});
const turnovers = await recordIndicatorTurnovers(page, 3_000);
await writeFile(
testInfo.outputPath("evidence.json"),
JSON.stringify({ activity, turnovers }, null, 2),
);
expect
.soft(activity.compositorFramesPerSecond)
.toBeLessThan(RUNNING_TURN_FRAMES_PER_SECOND_BUDGET);
// The shimmer moves in steps, and only on the frames the ring moves, so the two cost the
// window one set of frames between them.
expect.soft(turnovers.shimmer.length).toBeGreaterThan(60);
expect.soft(turnovers.shimmer.length).toBeLessThan(turnovers.frames * 0.6);
expect.soft(turnovers.shimmer.filter((frame) => !turnovers.ring.includes(frame))).toEqual([]);
// It still crosses the whole label, held at each of its even steps.
expect.soft(turnovers.shimmerOffsets.length).toBeGreaterThanOrEqual(SHIMMER_MIN_STEPS);
expect.soft(turnovers.shimmerOffsets.length).toBeLessThanOrEqual(SHIMMER_MAX_STEPS);
} finally {
await agent.cleanup();
}
});
test("hold still when the system asks for reduced motion", async ({
page,
browser,
}, testInfo) => {
test.setTimeout(180_000);
await page.emulateMedia({ reducedMotion: "reduce" });
await recordReactRenders(page);
const agent = await openQuietRunningTurn(page);
try {
await resetReactRenders(page);
const activity = await measureSteadyStateActivity({
browser,
page,
windowMs: SAMPLE_WINDOW_MS,
});
const renders = await readReactRenders(page);
const animations = await readRunningAnimations(page);
await writeFile(
testInfo.outputPath("evidence.json"),
JSON.stringify({ activity, renders, animations }, null, 2),
);
await page.screenshot({ path: testInfo.outputPath("page-reduced-motion.png") });
await workingLoader(page).screenshot({ path: testInfo.outputPath("loader.png") });
await runningToolCall(page).screenshot({ path: testInfo.outputPath("tool-call.png") });
await statusRings(page)
.first()
.screenshot({ path: testInfo.outputPath("status-ring.png") });
expect.soft(animations).toEqual([]);
expect.soft(await readLoaderStep(page)).toBe(0);
expect
.soft(activity.animationFrameCallbacksPerSecond)
.toBeLessThan(ANIMATION_FRAME_CALLBACKS_PER_SECOND_BUDGET);
expect.soft(activity.styleRecalcsPerSecond).toBeLessThan(STYLE_RECALCS_PER_SECOND_BUDGET);
expect.soft(activity.paintsPerSecond).toBeLessThan(PAINTS_PER_SECOND_BUDGET);
// With nothing moving the compositor only draws for the elapsed counter.
expect.soft(activity.compositorFramesPerSecond).toBeLessThan(4);
expect.soft(indicatorRenders(renders)).toEqual([]);
} finally {
await agent.cleanup();
}
});
test("stop while the tab is hidden and resume when it is shown", async ({ page }) => {
test.setTimeout(180_000);
const agent = await openQuietRunningTurn(page);
try {
const everyIndicator = expect.arrayContaining([
"status-ring",
"synced-loader-dot",
"label-shimmer",
]);
await expect.poll(() => readAnimatingTargets(page)).toEqual(everyIndicator);
await setTabVisibility(page, "hidden");
await expect.poll(() => readAnimatingTargets(page)).toEqual([]);
expect(await readLoaderStep(page)).toBe(0);
await setTabVisibility(page, "visible");
await expect.poll(() => readAnimatingTargets(page)).toEqual(everyIndicator);
} finally {
await agent.cleanup();
}
});
test("look the same frame for frame", async ({ page }, testInfo) => {
test.setTimeout(180_000);
test.skip(
process.env.PASEO_RUNNING_INDICATORS_FRAMES !== "1",
"Captures reference frames for a before/after comparison; not an assertion.",
);
const agent = await openQuietRunningTurn(page);
try {
const capturedSteps = await captureLoaderSteps(page, (step) =>
testInfo.outputPath(`loader-step-${step}.png`),
);
expect(capturedSteps).toEqual([0, 1, 2, 3, 4, 5]);
for (const progress of [0, 0.13, 0.31, 0.5, 0.77, 0.94]) {
await freezeAnimationsAt(page, progress);
const label = String(Math.round(progress * 100)).padStart(2, "0");
await runningToolCall(page).screenshot({
path: testInfo.outputPath(`tool-call-${label}.png`),
});
await statusRings(page)
.first()
.screenshot({ path: testInfo.outputPath(`status-ring-${label}.png`) });
await page.screenshot({
path: testInfo.outputPath(`page-${label}.png`),
mask: [page.getByTestId("turn-footer")],
});
}
} finally {
await agent.cleanup();
}
});
});
@@ -35,7 +35,13 @@ import {
expectSettingsHeader,
openAddHostFlow,
selectHostConnectionType,
toggleHostAdvanced,
selectDirectConnectionMode,
expectDirectConnectionMode,
expectDirectFormModeDisabled,
connectDirectHost,
connectDirectHostExpectingPassword,
pasteIntoDirectHost,
fillDirectHostPromptPassword,
openCompactSettings,
expectCompactSettingsList,
expectSettingsSidebarVisible,
@@ -50,11 +56,11 @@ import {
fillDirectHostUri,
expectDirectHostFormValues,
expectDirectHostSslEnabled,
expectDirectHostSslDisabled,
fillDirectHostAddress,
toggleDirectHostSsl,
expectDirectHostUriValue,
expectDirectHostUriHidden,
expectDirectFormFullyVisible,
expectDiagnosticsContent,
expectAboutContent,
expectGeneralContent,
@@ -71,6 +77,7 @@ import {
bindCommandCenterToEnter,
} from "../support/helpers/settings";
import { getServerId } from "../support/helpers/server-id";
import { startIsolatedHostDaemon } from "../support/helpers/isolated-host-daemon";
import { expectAppRoute } from "../support/helpers/route-assertions";
import { clickNewChat, gotoWorkspace } from "../support/helpers/launcher";
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
@@ -327,44 +334,105 @@ test.describe("Settings sidebar navigation", () => {
await verifyLegacyHostSettingsRedirect(page);
});
test("direct connection advanced URI round-trips SSL and password into the form", async ({
page,
}) => {
test("direct connection converts between Form and URI modes", async ({ page }) => {
await gotoAppShell(page);
await openSettings(page);
await openAddHostFlow(page);
await expectAddHostMethodOptions(page);
await selectHostConnectionType(page, "direct");
await expectDirectConnectionMode(page, "Form");
await fillDirectHostAddress(page, "example.paseo.test", "7443");
await expectDirectHostSslDisabled(page);
await toggleDirectHostSsl(page);
await expectDirectHostSslEnabled(page);
await toggleHostAdvanced(page);
await expectDirectHostUriValue(page, "tcp://example.paseo.test:7443?ssl=true");
await toggleHostAdvanced(page);
await toggleDirectHostSsl(page);
await expectDirectHostSslDisabled(page);
await toggleHostAdvanced(page);
await fillDirectHostUri(page, "tcp://example.paseo.test:7443?ssl=true&password=shared-secret");
await toggleHostAdvanced(page);
await expectDirectHostFormValues(page, {
host: "example.paseo.test",
port: "7443",
password: "shared-secret",
await test.step("Form fields become a URI", async () => {
await fillDirectHostAddress(page, "example.paseo.test", "7443");
await toggleDirectHostSsl(page);
await selectDirectConnectionMode(page, "URI");
await expectDirectHostUriValue(page, "tcp://example.paseo.test:7443?ssl=true");
});
await expectDirectHostSslEnabled(page);
await expectDirectHostUriHidden(page);
await toggleHostAdvanced(page);
await expectDirectHostUriValue(
page,
"tcp://example.paseo.test:7443?ssl=true&password=shared-secret",
);
await toggleHostAdvanced(page);
await expectDirectHostUriHidden(page);
await test.step("a URI becomes Form fields", async () => {
await fillDirectHostUri(
page,
"tcp://example.paseo.test:7443?ssl=true&password=shared-secret",
);
await selectDirectConnectionMode(page, "Form");
await expectDirectHostFormValues(page, {
host: "example.paseo.test",
port: "7443",
password: "shared-secret",
});
await expectDirectHostSslEnabled(page);
await expectDirectHostUriHidden(page);
});
await test.step("a pairing link pasted into Host stays a URI", async () => {
const link = "relay://relay.paseo.test:443/srv_e2e_pairing?key=daemon-key&ssl=true";
await pasteIntoDirectHost(page, link);
await expectDirectConnectionMode(page, "URI");
await expectDirectHostUriValue(page, link);
await expectDirectFormModeDisabled(page);
});
});
test("direct connection connects to a URI with Host blank", async ({ page }) => {
await gotoAppShell(page);
await openSettings(page);
await openAddHostFlow(page);
await selectHostConnectionType(page, "direct");
await selectDirectConnectionMode(page, "URI");
await fillDirectHostUri(page, `tcp://127.0.0.1:${getE2EDaemonPort()}`);
await connectDirectHost(page);
});
test("direct connection connects to an edited URI instead of the form", async ({ page }) => {
await gotoAppShell(page);
await openSettings(page);
await openAddHostFlow(page);
await selectHostConnectionType(page, "direct");
await fillDirectHostAddress(page, "127.0.0.1", "9");
await selectDirectConnectionMode(page, "URI");
await expectDirectHostUriValue(page, "tcp://127.0.0.1:9");
await fillDirectHostUri(page, `tcp://127.0.0.1:${getE2EDaemonPort()}`);
await connectDirectHost(page);
});
test("direct connection sends the password in a URI and asks again when it is wrong", async ({
page,
}) => {
const password = "e2e uri password";
const daemon = await startIsolatedHostDaemon("srv_e2e_uri_password_host", {
environment: { ...process.env, PASEO_PASSWORD: password },
});
try {
await gotoAppShell(page);
await openSettings(page);
await test.step("a URI with the password connects with one tap", async () => {
await openAddHostFlow(page);
await selectHostConnectionType(page, "direct");
await selectDirectConnectionMode(page, "URI");
await fillDirectHostUri(
page,
`tcp://127.0.0.1:${daemon.port}?password=${encodeURIComponent(password)}`,
);
await connectDirectHost(page);
});
await test.step("a wrong password asks for the host's password inline", async () => {
await openAddHostFlow(page);
await selectHostConnectionType(page, "direct");
await selectDirectConnectionMode(page, "URI");
await fillDirectHostUri(page, `tcp://127.0.0.1:${daemon.port}?password=wrong`);
await connectDirectHostExpectingPassword(page, `127.0.0.1:${daemon.port}`);
await fillDirectHostPromptPassword(page, password);
await connectDirectHost(page);
});
} finally {
await daemon.close();
}
});
test("Escape lets settings dropdowns and modals close before leaving settings", async ({
@@ -697,3 +765,16 @@ test("docked navigation keeps its density and Settings preserves reading width",
await expectSettingsSidebarHidden(page);
await expectAppearanceContent(page);
});
test.describe("Settings — small phone", () => {
test.use({ viewport: { width: 360, height: 640 } });
test("direct connection shows the whole form above Cancel and Connect", async ({ page }) => {
await gotoAppShell(page);
await openCompactSidebar(page);
await openSettingsFromCompactSidebar(page);
await openAddHostFlow(page);
await selectHostConnectionType(page, "direct");
await expectDirectFormFullyVisible(page);
});
});
@@ -52,17 +52,28 @@ async function exitSelection(page: Page) {
}
/**
* Walks the Finder click matrix on four rows, starting with the first row open: a modifier click
* from normal mode selects only the clicked row, Cmd/Ctrl+click toggles, Shift+click extends and
* shrinks a range from the anchor, and plain clicks keep toggling while select mode is on.
* Walks the sidebar selection click matrix on four rows: Cmd/Ctrl+click (and Cmd/Ctrl+Shift+click)
* from normal mode navigates instead of entering select mode, Shift+click enters select mode on the
* clicked row alone, Cmd/Ctrl+click and plain clicks toggle while select mode is active, and
* Shift+click extends, shrinks, and flips a range from the anchor.
*/
async function exerciseClickMatrix(page: Page, rows: readonly Locator[]) {
const [first, second, third, fourth] = rows;
await first.click();
await expect(first).toHaveAttribute("aria-selected", "true");
// Cmd/Ctrl+click and Cmd/Ctrl+Shift+click outside select mode navigate normally.
await third.click({ modifiers: [MOD] });
await expect(third).toHaveAttribute("aria-selected", "true");
await expect(page.getByTestId("workspace-selection-toast")).toHaveCount(0);
await first.click({ modifiers: [MOD, "Shift"] });
await expect(first).toHaveAttribute("aria-selected", "true");
await expect(page.getByTestId("workspace-selection-toast")).toHaveCount(0);
const openWorkspaceUrl = page.url();
await third.click({ modifiers: [MOD] });
// Shift+click enters select mode on the clicked row alone; Cmd/Ctrl+click and plain clicks toggle.
await third.click({ modifiers: ["Shift"] });
await expectSelectedCount(page, 1);
await expectChecked(rows, [false, false, true, false]);
@@ -102,7 +113,7 @@ test.describe("sidebar workspace selection clicks", () => {
seeded = null;
});
test("Cmd/Ctrl+click and Shift+click select like Finder in project grouping", async ({
test("Shift+click enters select mode while Cmd/Ctrl+click navigates in project grouping", async ({
page,
}) => {
seeded = await seedProjectWithWorkspaces(4);
@@ -111,7 +122,9 @@ test.describe("sidebar workspace selection clicks", () => {
await exerciseClickMatrix(page, await rowsInSidebarOrder(page, seeded.workspaceIds));
});
test("Cmd/Ctrl+click and Shift+click select like Finder in status grouping", async ({ page }) => {
test("Shift+click enters select mode while Cmd/Ctrl+click navigates in status grouping", async ({
page,
}) => {
seeded = await seedProjectWithWorkspaces(4);
await gotoAppShell(page);
await waitForSidebarHydration(page);
@@ -5,30 +5,34 @@ import { expectComposerVisible } from "../support/helpers/composer";
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
interface ShimmerEvidence {
animationDuration: string;
durationMs: number;
endPx: number;
label: string;
renderedWidth: number;
startPx: number;
}
async function readShimmerEvidence(locator: Locator): Promise<ShimmerEvidence> {
return locator.evaluate((root) => {
const shimmer = Array.from(root.querySelectorAll<HTMLElement>("*")).find((element) =>
getComputedStyle(element).animationName.includes("paseo-toolcall-shimmer"),
);
if (!shimmer) {
throw new Error("Expected a running shimmer inside the badge");
}
const style = getComputedStyle(shimmer);
return {
animationDuration: style.animationDuration,
endPx: Number.parseFloat(style.getPropertyValue("--paseo-shimmer-end")),
label: shimmer.textContent ?? "",
renderedWidth: shimmer.getBoundingClientRect().width,
startPx: Number.parseFloat(style.getPropertyValue("--paseo-shimmer-start")),
};
});
// The band is the shimmer's moving window; its animation carries the sweep it was measured for.
async function readShimmerEvidence(badge: Locator): Promise<ShimmerEvidence> {
return badge
.getByTestId("label-shimmer")
.first()
.evaluate((shimmer) => {
const effect = shimmer.firstElementChild?.getAnimations()[0]?.effect;
if (!(effect instanceof KeyframeEffect)) {
throw new Error("Expected a running shimmer inside the badge");
}
const [startPx, endPx] = effect
.getKeyframes()
.map((keyframe) => new DOMMatrix(String(keyframe.transform)).m41);
return {
durationMs: Number(effect.getComputedTiming().duration),
endPx,
label: shimmer.textContent ?? "",
renderedWidth: shimmer.getBoundingClientRect().width,
startPx,
};
});
}
test("measures an overview heading that becomes loading after its idle mount", async ({
@@ -63,11 +67,11 @@ test("measures an overview heading that becomes loading after its idle mount", a
if (!idleGroupHandle) {
throw new Error("Expected the idle tool-call group to be mounted");
}
await expect(group.locator('[style*="paseo-toolcall-shimmer"]')).toHaveCount(0);
await expect(group.getByTestId("label-shimmer")).toHaveCount(0);
await gate.waitForSecondRunning();
gate.releaseSecondRunning();
await expect(group.locator('[style*="paseo-toolcall-shimmer"]')).not.toHaveCount(0);
await expect(group.getByTestId("label-shimmer")).not.toHaveCount(0);
const sameGroupNode = await group.evaluate(
(node, previous) => node === previous,
idleGroupHandle,
@@ -34,7 +34,9 @@ function report(input: {
sourceLabel: input.sourceLabel,
icon: ICON,
report:
input.report.status === "error" || input.report.status === "unavailable"
input.report.status === "error" ||
input.report.status === "unavailable" ||
input.report.status === "not_fetched"
? input.report
: {
status: "available",
@@ -138,6 +140,45 @@ test.describe("usage settings", () => {
await expect(card.getByText("64% used")).toBeVisible();
});
test("a manual report asks for Refresh and changes only on the user's Refresh", async ({
page,
}) => {
test.setTimeout(120_000);
const serverId = getServerId();
const manual = (entry: UsageReportEntry): UsageReportEntry => ({ ...entry, refresh: "manual" });
const usage = await installUsageReportsFixture(page, {
lists: [
(request) => [
manual(
report({
sourceId: "quota",
sourceLabel: "Quota",
report: request.forceRefresh
? { status: "available", windows: [{ id: "w", label: "Weekly", usedPct: 12 }] }
: { status: "not_fetched" },
}),
),
],
],
});
await gotoAppShell(page);
await openSettings(page);
await openSettingsHostSection(page, serverId, "usage");
const card = page.getByTestId("usage-report-quota:account");
await expect(
card.getByText("Not checked yet. Quota usage updates only when you refresh it."),
).toBeVisible({ timeout: 10_000 });
await expect(card.getByText("Error", { exact: true })).toHaveCount(0);
expect(forcedRefreshCount(usage)).toBe(0);
await card.getByTestId("usage-refresh").click();
await expect(card.getByText("12% used")).toBeVisible();
expect(usage.listRequests().filter((request) => request.forceRefresh)).toEqual([
{ forceRefresh: true, reportIds: ["quota:account"] },
]);
});
test("asks to update a host without usage support and never calls it", async ({ page }) => {
test.setTimeout(120_000);
const serverId = getServerId();
@@ -3,6 +3,7 @@ import { buildHostAgentDetailRoute } from "@/utils/host-routes";
import { test } from "../support/fixtures";
import { seedWorkspace, type SeedDaemonClient } from "../support/helpers/seed-client";
import { getServerId } from "../support/helpers/server-id";
import { getE2EDaemonPort } from "../support/helpers/daemon-port";
import { observeTimelineSubscriptions } from "../support/helpers/timeline-delivery";
import { waitForWorkspaceTabsVisible } from "../support/helpers/workspace-tabs";
import { selectWorkspaceInSidebar } from "../support/helpers/sidebar";
@@ -254,7 +255,226 @@ async function expectCurrentChatWithoutCatchUp(page: Page, message: string) {
await expect(page.getByRole("alert").filter({ hasText: "Updating messages" })).toHaveCount(0);
}
async function delayActiveDaemonPongs(page: Page, port: string) {
let deliveredPongs = 0;
let inFlightPings = 0;
const delayedPongs = new Set<ReturnType<typeof setTimeout>>();
await page.routeWebSocket(
(url) => url.hostname === "localhost" && url.port === port,
(socket) => {
const server = socket.connectToServer();
socket.onMessage((message) => {
if (typeof message === "string" && JSON.parse(message).type === "ping") inFlightPings += 1;
server.send(message);
});
server.onMessage((message) => {
if (typeof message === "string" && JSON.parse(message).type === "pong") {
const timer = setTimeout(() => {
delayedPongs.delete(timer);
socket.send(message);
deliveredPongs += 1;
inFlightPings -= 1;
}, 1_000);
delayedPongs.add(timer);
} else {
socket.send(message);
}
});
},
);
return {
delivered: () => deliveredPongs,
settled: () => inFlightPings === 0 && delayedPongs.size === 0,
dispose: () => {
for (const timer of delayedPongs) clearTimeout(timer);
},
};
}
async function readActiveLivenessRtt(page: Page): Promise<number> {
return page.evaluate((serverId) => {
const runtime = Reflect.get(globalThis, "__paseoHostRuntimeStore") as {
getClient(id: string): { getLastLivenessRttMs(): number | null } | null;
};
return runtime.getClient(serverId)?.getLastLivenessRttMs() ?? 0;
}, getServerId());
}
async function readHostConnection(page: Page) {
return page.evaluate((serverId) => {
const runtime = Reflect.get(globalThis, "__paseoHostRuntimeStore") as {
getSnapshot(id: string): {
clientGeneration: number;
connectionStatus: string;
activeConnectionId: string;
};
};
const snapshot = runtime.getSnapshot(serverId);
return {
generation: snapshot.clientGeneration,
status: snapshot.connectionStatus,
connection: snapshot.activeConnectionId,
};
}, getServerId());
}
async function settleHostProbeCycle(page: Page): Promise<void> {
await page.evaluate(async (serverId) => {
const runtime = Reflect.get(globalThis, "__paseoHostRuntimeStore") as {
runProbeCycleNow(id: string): Promise<void>;
};
// Joins any in-flight cycle through its final replacement handshake.
await runtime.runProbeCycleNow(serverId);
}, getServerId());
}
async function observeContinuousHostConnection(page: Page) {
const observation = await page.evaluateHandle((serverId) => {
const runtime = Reflect.get(globalThis, "__paseoHostRuntimeStore") as {
getSnapshot(id: string): { connectionStatus: string; client: unknown } | null;
subscribe(id: string, listener: () => void): () => void;
};
const connected: boolean[] = [];
const record = () => {
const snapshot = runtime.getSnapshot(serverId);
connected.push(snapshot?.connectionStatus === "online" && snapshot.client !== null);
};
record();
const unsubscribe = runtime.subscribe(serverId, record);
return {
stop() {
unsubscribe();
return connected;
},
};
}, getServerId());
let stopped: Promise<boolean[]> | null = null;
return {
stop() {
stopped ??= observation
.evaluate((recorder) => recorder.stop())
.finally(() => observation.dispose());
return stopped;
},
};
}
async function advanceToOnlineReplacement(
page: Page,
delayedPongs: Awaited<ReturnType<typeof delayActiveDaemonPongs>>,
beforeGeneration: number,
) {
// Advance scheduling, not the sockets: settle real heartbeat and probe replies
// between hops, including the replacement handshake, without altering production timers.
for (let step = 0; step < 60; step += 1) {
if ((await readHostConnection(page)).generation !== beforeGeneration) break;
await expect.poll(delayedPongs.settled, { timeout: 10_000 }).toBe(true);
await settleHostProbeCycle(page);
const pongsBefore = delayedPongs.delivered();
await page.clock.fastForward(10_000);
await expect
.poll(
async () =>
(await readHostConnection(page)).generation !== beforeGeneration ||
delayedPongs.delivered() > pongsBefore,
{ timeout: 10_000 },
)
.toBe(true);
await settleHostProbeCycle(page);
}
}
test.describe("Viewed agent timelines", () => {
test("an online connection replacement keeps every open chat synchronized", async ({
page,
}, testInfo) => {
test.setTimeout(180_000);
await page.clock.install();
const port = getE2EDaemonPort();
const delayedEndpoint = `localhost:${port}`;
const fasterEndpoint = `127.0.0.1:${port}`;
const delayedPongs = await delayActiveDaemonPongs(page, port);
const subscriptions = observeTimelineSubscriptions(page);
const scenario = await seedViewedTimelineScenario();
let connectionObservation:
| Awaited<ReturnType<typeof observeContinuousHostConnection>>
| undefined;
try {
await commitMessage(scenario, scenario.firstAgentId, "BEFORE_CONNECTION_REPLACEMENT");
await openAgent(page, scenario, scenario.firstAgentId);
await selectAgent(page, "Second viewed chat");
await selectAgent(page, "First viewed chat");
await subscriptions.waitForSubscribedAgents([scenario.firstAgentId, scenario.secondAgentId]);
await expectReconnectingToastGone(page);
// The adaptive selector needs an RTT from the active socket, not only its startup probe.
await expect.poll(delayedPongs.delivered, { timeout: 30_000 }).toBeGreaterThan(1);
await expect
.poll(() => readActiveLivenessRtt(page), { timeout: 30_000 })
.toBeGreaterThanOrEqual(800);
// Add another real route to the same daemon. Delaying only the active route's real
// pong frames gives the ordinary adaptive selector three consistently faster probes.
// No host state is forced offline and no client or timeline owner is replaced by the test.
connectionObservation = await observeContinuousHostConnection(page);
const beforeGeneration = await page.evaluate(
async ({ serverId, endpoint, activeEndpoint }) => {
const runtime = Reflect.get(globalThis, "__paseoHostRuntimeStore") as {
getSnapshot(id: string): {
clientGeneration: number;
connectionStatus: string;
activeConnectionId: string;
};
upsertDirectConnection(input: { serverId: string; endpoint: string }): Promise<unknown>;
};
const before = runtime.getSnapshot(serverId);
if (
before.connectionStatus !== "online" ||
before.activeConnectionId !== `direct:${activeEndpoint}`
) {
throw new Error("Expected the initial real connection to be online");
}
await runtime.upsertDirectConnection({ serverId, endpoint });
return before.clientGeneration;
},
{ serverId: getServerId(), endpoint: fasterEndpoint, activeEndpoint: delayedEndpoint },
);
subscriptions.reset();
await advanceToOnlineReplacement(page, delayedPongs, beforeGeneration);
await expect
.poll(() => readHostConnection(page), { timeout: 3_000 })
.toEqual({
generation: beforeGeneration + 1,
status: "online",
connection: `direct:${fasterEndpoint}`,
});
expect(await connectionObservation.stop()).not.toContain(false);
await expectReconnectingToastGone(page, { timeout: 3_000 });
await page.screenshot({
path: testInfo.outputPath("after-online-connection-replacement.png"),
});
await subscriptions.waitForSubscribedAgents([scenario.firstAgentId], { match: "includes" });
await commitMessage(scenario, scenario.firstAgentId, "FIRST_CHAT_AFTER_REPLACEMENT");
await expect(page.getByText("FIRST_CHAT_AFTER_REPLACEMENT", { exact: true })).toBeVisible();
await commitMessage(scenario, scenario.secondAgentId, "SECOND_CHAT_WHILE_HIDDEN");
await selectAgent(page, "Second viewed chat");
await expectReconnectingToastGone(page, { timeout: 3_000 });
await expect(page.getByText("SECOND_CHAT_WHILE_HIDDEN", { exact: true })).toBeVisible();
await subscriptions.waitForSubscribedAgents([scenario.firstAgentId, scenario.secondAgentId], {
match: "includes",
});
await commitMessage(scenario, scenario.secondAgentId, "SECOND_CHAT_AFTER_REPLACEMENT");
await expect(page.getByText("SECOND_CHAT_AFTER_REPLACEMENT", { exact: true })).toBeVisible();
await page.screenshot({ path: testInfo.outputPath("both-chats-synchronized.png") });
} finally {
try {
await connectionObservation?.stop();
} finally {
delayedPongs.dispose();
await scenario.cleanup();
}
}
});
test("a reloaded layout subscribes only the chat it restores into", async ({ page }) => {
test.setTimeout(120_000);
const subscriptions = observeTimelineSubscriptions(page);
@@ -30,7 +30,7 @@ import {
pressArchiveShortcut,
pressUndoShortcut,
readSidebarListLayout,
recordLastRowBottomPerFrame,
recordLastRowDuringToastExpiry,
resizeSidebarToMinimum,
rowArchiveButton,
rowKebab,
@@ -187,7 +187,6 @@ test.describe("Workspace archive undo", () => {
test("a long list scrolls its last row clear of the toast, and settles back smoothly after it", async ({
page,
}) => {
await page.clock.install({ time: Date.now() });
const fillers: Array<{ path: string; cleanup: () => Promise<void> }> = [];
const fillerProjectIds: string[] = [];
try {
@@ -204,30 +203,30 @@ test.describe("Workspace archive undo", () => {
await archiveFromRowButton(page, worktree.workspaceId);
await page.mouse.move(0, 0);
const toastBox = await archivedToast(page).boundingBox();
if (!toastBox) throw new Error("Toast is not laid out");
// The list keeps its usual end gap, measured from the toast's top instead of its own bottom.
// Read both edges together because the sidebar can resize while the toast is open.
await expect
.poll(async () => {
const layout = await scrollSidebarListToEnd(page);
const toastBox = await archivedToast(page).boundingBox();
if (!toastBox) throw new Error("Toast is not laid out");
return Math.round(toastBox.y - layout.rowBottoms.at(-1)!);
})
.toBe(Math.round(restingEndGap));
.toBeGreaterThanOrEqual(Math.round(restingEndGap));
const frames = recordLastRowBottomPerFrame(page, 40);
await outlastUndoWindow(page);
const bottoms = await frames;
await expect(archivedToast(page)).toHaveCount(0);
const bottoms = await recordLastRowDuringToastExpiry(page);
// Without scrolling again, the list ends just below its last row once more.
// Without scrolling again, the list returns to its usual gap below the last row.
const settled = await readSidebarListLayout(page);
expect(settled.listBottom - settled.rowBottoms.at(-1)!).toBeCloseTo(restingEndGap, 0);
// The rows travel down by the toast's height over several frames, never in one jump.
const travel = bottoms.at(-1)! - bottoms[0]!;
expect(travel).toBeGreaterThan(toastBox.height);
const steps = bottoms.slice(1).map((bottom, index) => bottom - bottoms[index]!);
const settledBottom = settled.rowBottoms.at(-1)!;
expect(settled.listBottom - settledBottom).toBeCloseTo(restingEndGap, 0);
// The last row moves through an intermediate position without reversing direction.
const startBottom = bottoms[0]!;
expect(bottoms.some((bottom) => bottom > startBottom && bottom < settledBottom)).toBe(true);
const steps = [...bottoms, settledBottom]
.slice(1)
.map((bottom, index) => bottom - bottoms[index]!);
expect(Math.min(...steps)).toBeGreaterThanOrEqual(0);
expect(Math.max(...steps)).toBeLessThan(travel / 2);
} finally {
for (const projectId of fillerProjectIds) {
await client.removeProject(projectId).catch(() => undefined);
@@ -17,6 +17,7 @@ import { getServerId } from "../support/helpers/server-id";
import {
clickArchiveWorkspaceMenuItem,
expectWorkspaceAbsentFromSidebar,
selectSidebarStatusGrouping,
} from "../support/helpers/sidebar";
import { createTempGitRepo } from "../support/helpers/workspace";
import {
@@ -99,6 +100,10 @@ async function clickRowArchiveButton(page: Page, workspaceId: string): Promise<v
await rowArchiveButton(page, workspaceId).click();
}
function rowArchivePendingIndicator(page: Page, workspaceId: string) {
return workspaceRow(page, workspaceId).getByTestId("workspace-archive-pending-indicator");
}
async function cycleThemeAndWaitForSidebar(page: Page, workspaceId: string): Promise<void> {
const rowBeforeThemeChange = await workspaceRow(page, workspaceId).elementHandle();
if (!rowBeforeThemeChange)
@@ -363,10 +368,96 @@ test.describe("Workspace archive risk warning for worktree backing", () => {
expect(warning.message()).toContain("1 unpushed commit");
await expectWorktreeKept(page, worktree);
await expect(rowArchivePendingIndicator(page, worktree.workspaceId)).toHaveCount(0);
expect(relay.archiveRequests()).toBe(0);
expect(existsSync(path.join(worktree.workspaceDirectory, "DIRTY.md"))).toBe(true);
});
test("the row shows a trailing archive spinner without changing status or shifting layout", async ({
page,
}) => {
const worktree = await createWorktree("archive-risk-pending");
const statusRequest = await holdCheckoutStatusRequest(page, worktree);
await openSidebarRow(page, worktree.workspaceId);
const row = workspaceRow(page, worktree.workspaceId);
const title = page.getByTestId(
`sidebar-workspace-title-${getServerId()}:${worktree.workspaceId}`,
);
await expect(rowArchivePendingIndicator(page, worktree.workspaceId)).toHaveCount(0);
await expect(row.getByTestId("workspace-status-indicator-done")).toBeVisible();
const idleRowBox = await row.boundingBox();
const idleTitleBox = await title.boundingBox();
expect(idleRowBox).not.toBeNull();
expect(idleTitleBox).not.toBeNull();
statusRequest.arm();
await clickRowArchiveButton(page, worktree.workspaceId);
await statusRequest.waitForHeld();
try {
await expect(rowArchivePendingIndicator(page, worktree.workspaceId)).toBeVisible();
// Leading status must stay done — never turn into the Working status ring.
await expect(row.getByTestId("workspace-status-indicator-done")).toBeVisible();
await expect(row.getByTestId("workspace-status-indicator-loading")).toHaveCount(0);
await expect(row.getByTestId("workspace-status-indicator-running")).toHaveCount(0);
const archivingRowBox = await row.boundingBox();
const archivingTitleBox = await title.boundingBox();
expect(archivingRowBox).toEqual(idleRowBox);
expect(archivingTitleBox).toEqual(idleTitleBox);
expect(statusRequest.archiveRequests()).toBe(0);
} finally {
statusRequest.release();
}
await expectWorkspaceAbsentFromSidebar(page, worktree.workspaceId);
await expect(undoButton(page)).toBeVisible();
});
test("status grouping keeps the row in its original group with no Working badge while archiving", async ({
page,
}) => {
const worktree = await createWorktree("archive-risk-status-pending");
const statusRequest = await holdCheckoutStatusRequest(page, worktree);
await openSidebarRow(page, worktree.workspaceId);
await selectSidebarStatusGrouping(page);
const doneRows = page.getByTestId("sidebar-status-group-rows-done");
const row = doneRows.getByTestId(
`sidebar-workspace-row-${getServerId()}:${worktree.workspaceId}`,
);
const title = row.getByTestId(
`sidebar-workspace-title-${getServerId()}:${worktree.workspaceId}`,
);
await expect(row).toBeVisible();
await expect(row.getByTestId("project-status-badge")).toHaveCount(0);
const idleRowBox = await row.boundingBox();
const idleTitleBox = await title.boundingBox();
expect(idleRowBox).not.toBeNull();
expect(idleTitleBox).not.toBeNull();
statusRequest.arm();
await row.hover();
await rowArchiveButton(page, worktree.workspaceId).click();
await statusRequest.waitForHeld();
try {
await expect(row.getByTestId("workspace-archive-pending-indicator")).toBeVisible();
// Must remain in the Done group and never gain a Working status ring badge.
await expect(row).toBeVisible();
await expect(row.getByTestId("project-status-badge")).toHaveCount(0);
const archivingRowBox = await row.boundingBox();
const archivingTitleBox = await title.boundingBox();
expect(archivingRowBox).toEqual(idleRowBox);
expect(archivingTitleBox).toEqual(idleTitleBox);
} finally {
statusRequest.release();
}
await expectWorkspaceAbsentFromSidebar(page, worktree.workspaceId);
});
test("a worktree holding only new files warns when the repository hides untracked files", async ({
page,
}) => {
@@ -7,9 +7,29 @@ code-to-body size ratio at every heading level; fenced code keeps the code-size
token. Bold and links preserve the resulting size. Check the glyphs, not the background height: native backgrounds use
line metrics.
Use a development client rebuilt from this checkout. Follow the temporary entry
point and Metro workflow in [status-ring](../status-ring/README.md), importing
`MarkdownFormattingRegression` from `./e2e/mobile/markdown-formatting/native`.
Use a development client rebuilt from this checkout. In a disposable checkout,
temporarily replace `packages/app/index.ts` with:
```tsx
import "./src/polyfills/install-early";
import "./src/styles/unistyles";
import { registerRootComponent } from "expo";
import MarkdownFormattingRegression from "./e2e/mobile/markdown-formatting/native";
registerRootComponent(MarkdownFormattingRegression);
```
Start Metro in `packages/app`:
```sh
APP_VARIANT=development npx expo start --localhost --port 8096
```
With one Android emulator running, open that bundle:
```sh
agent-device open sh.paseo.debug 'exp+voice-mobile://expo-development-client/?url=http%3A%2F%2F10.0.2.2%3A8096' --platform android --session <session> --metro-port 8096
```
Open the same Metro URL in a browser to compare web. Restore `index.ts` afterward.
With this fixture open in an Android Agent Device session, run:
@@ -111,7 +111,7 @@ Keep generated screenshots, recordings, and run logs outside the repository.
confirmation. It first types without tapping the input to verify autofocus, then cancels the
confirmation, closes and reopens the underlying sheet, confirms again,
and completes the password retry. `stacked-settings.ad` checks the same return and retry through
Settings → add host → Direct connection → Advanced. Run both on phones and tablets so both the
Settings → add host → Direct connection → URI. Run both on phones and tablets so both the
bottom sheet and centered dialog are exercised.
These integration journeys require the host-confirmation flow in the test app. Include both the
@@ -146,7 +146,7 @@ Android uses the same journeys: copy each script outside the repository, change
artifacts, and sessions separate from other runs. These host-dependent journeys remain outside the
default mobile suite, alongside the existing modal-sheet scripts.
On iPhone, bulk replacement or bulk keyboard entry of the advanced URI field triggers a
On iPhone, bulk replacement or bulk keyboard entry of the Connection URI field triggers a
repeated-update error with both the parent and stacked-sheet implementations. Entering the complete
URI one character at a time passed with both implementations; faster typing remains unverified.
On iPad, replacing the field a second time appends text. For this Settings journey, use the
@@ -10,7 +10,7 @@ wait "id=\"add-host-method-direct\"" 10000
screenshot "${OUT}/10-add-host-methods.png"
press "id=\"add-host-method-direct\""
wait stable
press "id=\"direct-host-advanced-toggle\""
press "id=\"direct-mode-uri\""
wait stable
fill "id=\"direct-host-uri-input\"" "${PAIRING_LINK}"
wait stable
@@ -32,9 +32,9 @@ wait "id=\"host-confirmation-connect\"" 10000
screenshot "${OUT}/14-add-host-confirmation-reopens.png"
press "id=\"host-confirmation-connect\""
wait stable
wait "id=\"direct-password-input\"" 20000
wait "id=\"direct-uri-password-input\"" 20000
screenshot "${OUT}/15-add-host-password.png"
fill "id=\"direct-password-input\"" "${PASSWORD}"
fill "id=\"direct-uri-password-input\"" "${PASSWORD}"
wait stable
press "id=\"direct-host-submit\""
wait stable
@@ -13,6 +13,8 @@ function ad(...args) {
});
}
ad("press", 'label="Pair a device"', "--settle");
ad("wait", "text", "Relay", "10000");
ad("press", 'label="Relay"', "--settle");
ad("wait", "text", "Pairing QR code", "10000");
const { data } = JSON.parse(ad("snapshot", "-i", "--json"));
@@ -1,45 +0,0 @@
# Native retained status-ring regression
This runs the production native ring and clock inside real retained panels with
Reanimated on Android. A probe consumes the same public rotation hook and counts
UI-runtime value changes. No Reanimated mocks or provider processes are used.
Use an Android development client compatible with the checkout's native dependencies.
In a disposable checkout, temporarily replace `packages/app/index.ts` with:
```tsx
import "./src/polyfills/install-early";
import "./src/styles/unistyles";
import { registerRootComponent } from "expo";
import NativeRingRegression from "./e2e/mobile/status-ring/native";
registerRootComponent(NativeRingRegression);
```
Start Metro in `packages/app`:
```sh
APP_VARIANT=development npx expo start --localhost --port 8096
```
With one Android emulator running, open that bundle:
```sh
agent-device open sh.paseo.debug 'exp+voice-mobile://expo-development-client/?url=http%3A%2F%2F10.0.2.2%3A8096' --platform android --session status-ring --metro-port 8096
```
From the repository root:
```sh
node packages/app/e2e/mobile/status-ring/android.mjs status-ring http://127.0.0.1:8096
```
The test checks visible rotation, hidden-panel inactivity while another ring is
visible, inactivity with both panels hidden, and synchronized resumption. Each
sample reads counters on the UI runtime; elapsed time includes device-command
latency. The baseline fails at the first hidden-panel assertion.
Restore the original `packages/app/index.ts`, close the agent-device session,
and stop Metro afterward. The fixture substitutes running rings for a live agent
and toggles retained panels directly; it does not exercise workspace navigation
or measure whole-app CPU usage. It is excluded from routine unit tests because
it requires a native runtime.
@@ -1,71 +0,0 @@
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import { setTimeout as delay } from "node:timers/promises";
const [, , session, metroUrl] = process.argv;
assert(session && metroUrl, "Pass an agent-device session and Metro URL serving native.tsx");
function ad(...args) {
return execFileSync("agent-device", ["--session", session, ...args], {
encoding: "utf8",
timeout: 60_000,
});
}
function evaluate(expression) {
const value = ad("cdp", "runtime", "eval", "--expr", expression, "--json").trim();
return value === "undefined" ? undefined : JSON.parse(value);
}
let target;
const deadline = Date.now() + 30_000;
do {
target = ad("cdp", "target", "list", "--url", metroUrl)
.split("\n")
.find((line) => line.includes("sh.paseo.debug"));
if (!target) await delay(250);
} while (!target && Date.now() < deadline);
assert(target, "Open the Android dev client on this Metro bundle first");
ad("cdp", "target", "select", target.split(/\s+/)[0]);
let ready = false;
do {
ready = evaluate("Object.keys(globalThis.__ringReaders ?? {}).length === 2");
if (!ready) await delay(250);
} while (!ready && Date.now() < deadline);
assert(ready, "The two native probes must mount before sampling");
async function sample() {
evaluate("Object.values(globalThis.__ringReaders).forEach(read => read())");
await delay(100);
return JSON.parse(evaluate("JSON.stringify(globalThis.__ringSamples)"));
}
async function observe(label) {
const before = await sample();
await delay(600);
const after = await sample();
const deltas = Object.fromEntries(
Object.keys(before).map((key) => [key, after[key].updates - before[key].updates]),
);
console.log(JSON.stringify({ label, deltas, after }));
return { deltas, after };
}
const visible = await observe("both visible");
assert(visible.deltas.first > 0 && visible.deltas.second > 0);
assert.equal(visible.after.first.rotation, visible.after.second.rotation);
ad("press", 'label="HIDE FIRST"');
await delay(200);
const hidden = await observe("first hidden, second visible");
assert.equal(hidden.deltas.first, 0, "A retained hidden ring must stop UI-thread rotation updates");
assert(hidden.deltas.second > 0, "Visible rings must continue rotating");
ad("press", 'label="HIDE SECOND"');
await delay(200);
const allHidden = await observe("both hidden");
assert.equal(allHidden.deltas.first, 0);
assert.equal(allHidden.deltas.second, 0);
ad("press", 'label="SHOW FIRST"');
ad("press", 'label="SHOW SECOND"');
await delay(200);
const restored = await observe("both shown again");
assert(restored.deltas.first > 0 && restored.deltas.second > 0);
assert.equal(
restored.after.first.rotation,
restored.after.second.rotation,
"Restored rings must share the current phase",
);
console.log("PASS native retained-ring lifecycle");
@@ -1,69 +0,0 @@
import { useCallback, useLayoutEffect, useState } from "react";
import { Button, Text, View } from "react-native";
import { useAnimatedReaction, useSharedValue } from "react-native-reanimated";
import { scheduleOnRN, scheduleOnUI } from "react-native-worklets";
import { RetainedPanel } from "@/components/retained-panel";
import { useStatusRingRotation } from "@/components/status-ring/clock";
import { StatusRing } from "@/components/status-ring";
interface Sample {
updates: number;
rotation: number;
}
declare global {
var __ringSamples: Record<string, Sample>;
var __ringReaders: Record<string, () => void>;
}
function recordSample(name: string, value: { updates: number; rotation: number }) {
globalThis.__ringSamples[name] = value;
}
function Probe({ name }: { name: string }) {
const rotation = useStatusRingRotation();
const updates = useSharedValue(0);
useAnimatedReaction(
() => rotation.value,
() => {
updates.value += 1;
},
);
// Read the real UI runtime, without scheduling a continuous JS observer.
useLayoutEffect(() => {
globalThis.__ringSamples ??= {};
globalThis.__ringReaders ??= {};
globalThis.__ringReaders[name] = () =>
scheduleOnUI(() => {
"worklet";
const sample = { updates: updates.value, rotation: rotation.value };
scheduleOnRN(recordSample, name, sample);
});
return () => {
delete globalThis.__ringReaders[name];
};
}, [name, rotation, updates]);
return <StatusRing />;
}
const containerStyle = { flex: 1, padding: 60, backgroundColor: "white" };
export default function NativeRingRegression() {
const [first, setFirst] = useState(true);
const [second, setSecond] = useState(true);
const toggleFirst = useCallback(() => setFirst((value) => !value), []);
const toggleSecond = useCallback(() => setSecond((value) => !value), []);
return (
<View style={containerStyle}>
<Text>Native retained status rings</Text>
<Button title={first ? "Hide first" : "Show first"} onPress={toggleFirst} />
<Button title={second ? "Hide second" : "Show second"} onPress={toggleSecond} />
<RetainedPanel active={first}>
<Probe name="first" />
</RetainedPanel>
<RetainedPanel active={second}>
<Probe name="second" />
</RetainedPanel>
</View>
);
}
@@ -1,5 +1,6 @@
import { expect, type Page } from "@playwright/test";
import { readScrollMetrics, waitForContentGrowth, expectNearBottom } from "./agent-bottom-anchor";
import { agentStopButton } from "./composer";
export async function awaitAssistantMessage(page: Page, hasText?: string | RegExp): Promise<void> {
const messages = page.getByTestId("assistant-message");
@@ -14,7 +15,7 @@ export async function awaitToolCall(page: Page, toolName: string | RegExp): Prom
}
export async function expectAgentIdle(page: Page, timeout = 30_000): Promise<void> {
await expect(page.getByRole("button", { name: /stop|cancel/i })).toHaveCount(0, { timeout });
await expect(agentStopButton(page)).toHaveCount(0, { timeout });
}
// The working indicator is an animated spinner View — no semantic ARIA role, testId is correct.
@@ -31,6 +31,8 @@ export interface RewindCompletionGate {
clearTimelineStreamCount(): void;
release(): void;
timelineStreamCount(): number;
/** Timeline reads this page sent since the last clear. */
timelineFetchCount(): number;
waitForDelayedResponse(): Promise<void>;
}
@@ -186,12 +188,20 @@ export async function holdDaemonHydration(page: Page): Promise<DaemonHydrationGa
};
}
// The rewind response and the timeline change it causes; the change removes the rewound row too.
const REWIND_COMPLETION_MESSAGES = new Set([
"agent.rewind.response",
"agent.timeline.rewind",
"agent.timeline.replacement",
]);
export async function holdRewindCompletion(
page: Page,
agentId: string,
): Promise<RewindCompletionGate> {
let released = false;
let timelineStreamCount = 0;
let timelineFetchCount = 0;
const delayedForwards: Array<() => void> = [];
let resolveDelayedResponse: (() => void) | null = null;
const delayedResponse = new Promise<void>((resolve) => {
@@ -200,7 +210,16 @@ export async function holdRewindCompletion(
await page.routeWebSocket(daemonWsRoutePattern(), (ws) => {
const server = ws.connectToServer();
ws.onMessage((message) => server.send(message));
ws.onMessage((message) => {
const sessionMessage = getSessionMessage(message);
if (
sessionMessage?.type === "fetch_agent_timeline_request" &&
sessionMessage.agentId === agentId
) {
timelineFetchCount += 1;
}
server.send(message);
});
server.onMessage((message) => {
const sessionMessage = getSessionMessage(message);
const payload = sessionMessage ? getPayload(sessionMessage) : null;
@@ -216,11 +235,11 @@ export async function holdRewindCompletion(
}
if (
!released &&
(sessionMessage?.type === "agent.rewind.response" ||
sessionMessage?.type === "agent.timeline.replacement") &&
sessionMessage &&
REWIND_COMPLETION_MESSAGES.has(String(sessionMessage.type)) &&
payload?.agentId === agentId
) {
// The replacement also signals completion and removes the rewound row/menu.
// The rewind also signals completion and removes the rewound row/menu.
// Hold it with the response so the pending-state assertion observes a pending rewind.
delayedForwards.push(() => ws.send(message));
if (sessionMessage.type === "agent.rewind.response") resolveDelayedResponse?.();
@@ -233,6 +252,7 @@ export async function holdRewindCompletion(
return {
clearTimelineStreamCount() {
timelineStreamCount = 0;
timelineFetchCount = 0;
},
release() {
released = true;
@@ -241,6 +261,7 @@ export async function holdRewindCompletion(
}
},
timelineStreamCount: () => timelineStreamCount,
timelineFetchCount: () => timelineFetchCount,
waitForDelayedResponse: () => delayedResponse,
};
}
@@ -0,0 +1,141 @@
import { expect, type Browser, type Locator, type Page } from "@playwright/test";
import { hideDeveloperToasts } from "../developer-ui.mjs";
import {
agentStopButton,
composerLocator,
expectComposerDraft,
fillComposerDraft,
sendDraftToQueue,
} from "./composer";
import { openAgentRoute, seedMockAgentWorkspace, type MockAgentWorkspace } from "./mock-agent";
export interface AgentWithOpenTurn extends MockAgentWorkspace {
/** Ends the open turn from outside the app, so it also works with every page closed. */
finishTurn(): Promise<void>;
}
/**
* A mock agent whose first turn stays open on a plan approval. The turn ends when the test
* answers it, so nothing here depends on how long a stream runs.
*/
export async function seedAgentWithOpenTurn(input: {
repoPrefix: string;
title: string;
}): Promise<AgentWithOpenTurn> {
const agent = await seedMockAgentWorkspace({
...input,
initialPrompt: "Emit synthetic plan approval.",
});
await agent.client.waitForFinish(agent.agentId, 30_000);
return {
...agent,
async finishTurn() {
const fetched = await agent.client.fetchAgent({ agentId: agent.agentId });
const request = fetched?.agent.pendingPermissions[0];
if (!request) throw new Error("The agent has no open turn to finish");
await agent.client.respondToPermission(agent.agentId, request.id, { behavior: "allow" });
},
};
}
export function queuedRows(page: Page): Locator {
return page.getByRole("list", { name: "Queued messages" }).getByRole("listitem");
}
export function queuedRow(page: Page, text: string): Locator {
return queuedRows(page).filter({ hasText: text });
}
export async function queueMessage(page: Page, text: string): Promise<void> {
await fillComposerDraft(page, text);
await sendDraftToQueue(page);
await expect(queuedRow(page, text)).toBeVisible();
await expectComposerDraft(page, "");
}
export async function editQueuedMessage(page: Page, text: string): Promise<void> {
await queuedRow(page, text)
.getByRole("button", { name: "Edit queued message", exact: true })
.click();
}
export async function cancelQueuedMessage(page: Page, text: string): Promise<void> {
await queuedRow(page, text)
.getByRole("button", { name: "Cancel queued message", exact: true })
.click();
}
export async function sendQueuedMessageNow(page: Page, text: string): Promise<void> {
await queuedRow(page, text)
.getByRole("button", { name: "Send queued message now", exact: true })
.click();
}
export function queuePausedNotice(page: Page): Locator {
return page.getByText("Queue paused until you send a message", { exact: true });
}
/** Queues through the host, for tests that need more rows than are worth typing. */
export async function queueThroughHost(agent: AgentWithOpenTurn, texts: string[]): Promise<void> {
for (const text of texts) {
await agent.client.sendAgentMessage(agent.agentId, text, { activeTurnBehavior: "queue" });
}
}
/** The composer input and Stop are both fully on screen. */
export async function expectComposerOnScreen(page: Page): Promise<void> {
await expect(composerLocator(page)).toBeInViewport({ ratio: 1 });
await expect(agentStopButton(page)).toBeInViewport({ ratio: 1 });
}
/** Turns the mouse wheel over one row, as a user does to move through the queue. */
export async function scrollQueueFrom(page: Page, text: string, deltaY: number): Promise<void> {
await queuedRow(page, text).hover();
await page.mouse.wheel(0, deltaY);
}
/** The icon leading a row's "Sent by" line is drawn at its full width. */
export async function expectSenderIconUnsquashed(row: Locator): Promise<void> {
const icon = await row.locator("svg").first().boundingBox();
if (!icon) throw new Error("The row has no visible sender icon");
expect(icon.width).toBeGreaterThanOrEqual(icon.height);
}
/** The queued prompt reached the transcript exactly once and left the queue. */
export async function expectDeliveredOnce(page: Page, text: string): Promise<void> {
await expect(page.getByTestId("user-message").filter({ hasText: text })).toHaveCount(1, {
timeout: 30_000,
});
await expect(queuedRow(page, text)).toHaveCount(0);
}
export async function expectDeliveredImage(page: Page, text: string): Promise<void> {
await expect(
page
.getByTestId("user-message")
.filter({ hasText: text })
.getByRole("button", { name: "Open image attachment" }),
).toHaveCount(1);
}
/** A page opened after the first one was closed, with the same stored app data. */
export async function reopenAgent(page: Page, agent: AgentWithOpenTurn): Promise<Page> {
const reopened = await page.context().newPage();
await hideDeveloperToasts(reopened);
await openAgentRoute(reopened, agent);
return reopened;
}
/** A second client of the same host: its own browser context and its own client id. */
export async function openSecondClient(
browser: Browser,
page: Page,
agent: AgentWithOpenTurn,
): Promise<{ page: Page; close(): Promise<void> }> {
const context = await browser.newContext({ storageState: await page.context().storageState() });
const second = await context.newPage();
await second.addInitScript(() => localStorage.removeItem("@paseo:client-id-v1"));
await hideDeveloperToasts(second);
await openAgentRoute(second, agent);
return { page: second, close: () => context.close() };
}
+13 -4
View File
@@ -103,8 +103,13 @@ export async function expectQueuedMessageButton(page: Page): Promise<void> {
});
}
/** The composer's Stop button. Queued rows also have a Cancel button, so match the whole name. */
export function agentStopButton(page: Page) {
return page.getByRole("button", { name: /^(stop|canceling) agent$/i });
}
export async function cancelAgent(page: Page): Promise<void> {
const stopButton = page.getByRole("button", { name: /stop|cancel/i }).first();
const stopButton = agentStopButton(page).first();
await expect(stopButton).toBeVisible({ timeout: 10_000 });
await stopButton.click();
}
@@ -300,9 +305,7 @@ export async function startRunningMockAgent(
await page.goto(agentUrl);
await expectComposerVisible(page);
await client.sendAgentMessage(agent.id, opts.prompt);
await expect(page.getByRole("button", { name: /stop|cancel/i }).first()).toBeVisible({
timeout: 30_000,
});
await expect(agentStopButton(page).first()).toBeVisible({ timeout: 30_000 });
return {
client,
repo,
@@ -467,6 +470,12 @@ export async function configureComposerQueueSend(page: Page): Promise<void> {
);
}
export async function configureComposerInterruptSend(page: Page): Promise<void> {
await page.addInitScript(() =>
localStorage.setItem("@paseo:app-settings", JSON.stringify({ sendBehavior: "interrupt" })),
);
}
/** Drive the real tab chooser's commands even when fullscreen covers its pointer surface.
* This exercises retained activity changes, not a claim that covered chrome is clickable.
*/
@@ -55,6 +55,31 @@ export async function expectHostConfirmationFor(page: Page, host: LinkedHost): P
await expect(sheet.getByTestId("host-confirmation-relay")).toHaveText(host.relayEndpoint);
}
/** The warning shown when a link names a saved host but carries a different daemon key. */
export async function expectHostIdentityChangedWarning(
page: Page,
expected: { savedHost: string; savedKey: string; newKey: string; relayEndpoint: string },
): Promise<void> {
const sheet = hostConfirmation(page);
await expect(sheet.getByText("Host identity changed", { exact: true })).toBeVisible({
timeout: 30_000,
});
await expect(sheet.getByTestId("host-confirmation-saved-host")).toHaveText(expected.savedHost);
await expect(sheet.getByTestId("host-confirmation-saved-fingerprint")).toHaveText(
expected.savedKey,
);
await expect(sheet.getByTestId("host-confirmation-fingerprint")).toHaveText(expected.newKey);
await expect(sheet.getByTestId("host-confirmation-relay")).toHaveText(expected.relayEndpoint);
await expect(sheet.getByText(/clears any saved password for this host/)).toBeVisible();
}
export async function replaceHostIdentity(page: Page): Promise<void> {
await hostConfirmation(page)
.getByRole("button", { name: "Replace host identity", exact: true })
.click();
await expect(hostConfirmation(page)).toHaveCount(0);
}
export async function cancelHostConfirmation(page: Page): Promise<void> {
await hostConfirmation(page).getByRole("button", { name: "Cancel", exact: true }).click();
await expect(hostConfirmation(page)).toHaveCount(0);
+15 -1
View File
@@ -1,4 +1,4 @@
import { expect, type Page } from "@playwright/test";
import { expect, type Locator, type Page } from "@playwright/test";
import { identityForeground, type IdentityColorName } from "@/styles/identity-colors";
import { openSettings } from "./app";
import { buildSeededHost } from "./daemon-registry";
@@ -289,6 +289,20 @@ export async function expectHostAppearancePreview(
);
}
export async function expectHostSelectorStatusIcon(
trigger: Locator,
options?: { color?: IdentityColorName },
): Promise<void> {
const icon = trigger.getByTestId("host-status-icon");
await expect(icon).toBeVisible({ timeout: 15_000 });
await expect(icon.getByTestId("host-status-icon-dot")).toBeVisible();
const svg = icon.locator("svg");
await expect(svg).toBeVisible();
if (options?.color) {
await expect(svg).toHaveAttribute("stroke", identityForeground(options.color, "light"));
}
}
// The auto-seed fixture rewrites the host registry on every navigation. Setting the
// disable-once flag to the current nonce makes it skip exactly one reload, which is what proves
// the appearance survived rather than being reseeded.
+36 -2
View File
@@ -4,6 +4,10 @@ import { tmpdir } from "node:os";
import path from "node:path";
import { expect, type Locator, type Page } from "@playwright/test";
import type { DaemonClient as InternalDaemonClient } from "@getpaseo/client/internal/daemon-client";
import type {
MutableDaemonToolGroups,
MutableDaemonToolsConfigPatch,
} from "@getpaseo/protocol/messages";
import { addProjectFlow, addProjectFlowInput, expectAddProjectTab } from "./add-project-flow";
import { connectDaemonClient } from "./daemon-client-loader";
import { buildCreateAgentPreferences, buildSeededHost } from "./daemon-registry";
@@ -138,7 +142,7 @@ export async function goToSetupStep(page: Page, label: string): Promise<void> {
}
export function paseoToolsSwitch(scope: Page | Locator): Locator {
return scope.getByRole("switch", { name: "Inject Paseo tools", exact: true });
return scope.getByRole("switch", { name: "Enable tools", exact: true });
}
/** Whether the host gives its agents Paseo tools, read from the host itself. */
@@ -147,7 +151,37 @@ export async function hostGivesAgentsPaseoTools(host: { port: number }): Promise
Pick<InternalDaemonClient, "connect" | "close" | "getDaemonConfig">
>({ clientIdPrefix: "app-e2e-onboarding", port: host.port });
try {
return (await client.getDaemonConfig()).config.mcp.injectIntoAgents !== false;
const config = (await client.getDaemonConfig()).config;
return config.tools?.enabled ?? config.mcp.injectIntoAgents !== false;
} finally {
await client.close();
}
}
/** The host's saved tool groups, read from the host itself. */
export async function hostToolGroups(host: {
port: number;
}): Promise<MutableDaemonToolGroups | undefined> {
const client = await connectDaemonClient<
Pick<InternalDaemonClient, "connect" | "close" | "getDaemonConfig">
>({ clientIdPrefix: "app-e2e-onboarding", port: host.port });
try {
return (await client.getDaemonConfig()).config.tools?.groups;
} finally {
await client.close();
}
}
/** Saves tool settings on the host, the way Settings does. */
export async function setHostTools(
host: { port: number },
tools: MutableDaemonToolsConfigPatch,
): Promise<void> {
const client = await connectDaemonClient<
Pick<InternalDaemonClient, "connect" | "close" | "patchDaemonConfig">
>({ clientIdPrefix: "app-e2e-onboarding", port: host.port });
try {
await client.patchDaemonConfig({ tools });
} finally {
await client.close();
}
@@ -66,6 +66,56 @@ type PairingHost =
| Pick<IsolatedHostDaemon, "serverId" | "port">
| Pick<OutdatedDaemon, "serverId" | "endpoint">;
export async function openDevicesPage(page: Page, daemon: PairingHost): Promise<void> {
await openAppOnPairingHost(page, daemon);
await openSettings(page);
await openSettingsHost(page, daemon.serverId);
await openSettingsHostSection(page, daemon.serverId, "devices");
await expect(page.getByTestId("devices-connected-clients-card")).toBeVisible();
}
export async function expectConnectedClientRow(
page: Page,
title: string,
scopeLabel: string,
): Promise<void> {
const card = page.getByTestId("devices-connected-clients-card");
const row = card.getByRole("button", { name: title, exact: true });
await expect(row).toBeVisible();
await expect(card.getByText(scopeLabel, { exact: true }).first()).toBeVisible();
}
export async function expandConnectedClientRow(page: Page, title: string): Promise<void> {
const card = page.getByTestId("devices-connected-clients-card");
await card.getByRole("button", { name: title, exact: true }).click();
await expect(card.getByText("Permissions", { exact: true })).toBeVisible();
}
export async function returnFromRelayToWaysToConnect(page: Page): Promise<void> {
await page
.getByTestId("devices-relay-pairing")
.getByRole("button", { name: "Back", exact: true })
.click();
await expect(page.getByTestId("devices-relay")).toBeVisible();
await expect(page.getByRole("switch", { name: "Tailscale", exact: true })).toBeVisible();
}
export async function openPairDeviceWaysSheet(page: Page): Promise<void> {
await expect(page.getByTestId("devices-pair-button")).toBeVisible();
await page.getByTestId("devices-pair-button").click();
await expect(page.getByTestId("devices-relay")).toBeVisible();
}
async function ensurePairDeviceWaysSheetOpen(page: Page): Promise<void> {
const relayRow = page.getByTestId("devices-relay");
const pairButton = page.getByTestId("devices-pair-button");
await relayRow.or(pairButton).first().waitFor({ state: "visible" });
if (!(await relayRow.isVisible())) {
await pairButton.click();
await expect(relayRow).toBeVisible();
}
}
export async function preparePairingHost(
page: Page,
daemon: PairingHost,
@@ -74,9 +124,9 @@ export async function preparePairingHost(
await openAppOnPairingHost(page, daemon, additionalHosts);
await openSettings(page);
await openSettingsHost(page, daemon.serverId);
await expect(page.getByTestId("devices-relay")).toHaveCount(0);
await expect(page.getByTestId("devices-pair-button")).toHaveCount(0);
await openSettingsHostSection(page, daemon.serverId, "devices");
await expect(page.getByTestId("devices-relay")).toBeVisible();
await openPairDeviceWaysSheet(page);
}
/** Loads the app afresh with `daemon` as its first host, then opens the setup's Mobile step. */
@@ -185,10 +235,12 @@ export async function cancelTailscaleTurnOff(page: Page, address: string): Promi
*/
export async function confirmTailscaleTurnOff(page: Page, address: string): Promise<void> {
const question = answerNextDialog(page, "accept");
await page.getByRole("switch", { name: "Tailscale", exact: true }).click();
const sheet = page.getByTestId("devices-pair-sheet");
const scope = (await sheet.isVisible()) ? sheet : page;
await scope.getByRole("switch", { name: "Tailscale", exact: true }).click();
expect(await question).toBe(TURN_OFF_QUESTION);
await expect(page.getByText("Host is not connected", { exact: true })).toBeVisible();
await expect(page.getByRole("switch", { name: "Tailscale", exact: true })).toHaveCount(0);
await expect(scope.getByText("Host is not connected", { exact: true })).toBeVisible();
await expect(scope.getByRole("switch", { name: "Tailscale", exact: true })).toHaveCount(0);
await expectHostUnreachableAt(address);
}
@@ -372,9 +424,12 @@ function deliverInOrderAfter(delay: () => number, deliver: (message: string | Bu
}
export async function expectTailscaleUpdateRequired(page: Page): Promise<void> {
await expect(page.getByRole("switch", { name: "Tailscale", exact: true })).toBeDisabled();
await expect(page.getByText("Update this host to use Tailscale", { exact: true })).toBeVisible();
await expect(page.getByRole("link", { name: "How to update", exact: true })).toBeVisible();
await ensurePairDeviceWaysSheetOpen(page);
const sheet = page.getByTestId("devices-pair-sheet");
const scope = (await sheet.isVisible()) ? sheet : page;
await expect(scope.getByRole("switch", { name: "Tailscale", exact: true })).toBeDisabled();
await expect(scope.getByText("Update this host to use Tailscale", { exact: true })).toBeVisible();
await expect(scope.getByRole("link", { name: "How to update", exact: true })).toBeVisible();
}
export async function expectTailscaleUnavailable(page: Page): Promise<void> {
@@ -460,6 +515,7 @@ export function observeDaemonStatusPolling(page: Page, port: number) {
}
export async function openPairDeviceModal(page: Page): Promise<void> {
await ensurePairDeviceWaysSheetOpen(page);
await page.getByRole("button", { name: "Relay", exact: true }).click();
await expect(page.getByTestId("devices-relay-pairing")).toBeVisible();
}
@@ -579,9 +635,14 @@ export async function expectPairingDisconnected(page: Page): Promise<void> {
}
export async function switchPairDeviceToHost(page: Page, serverId: string): Promise<void> {
const sheet = page.getByTestId("devices-pair-sheet");
if (await sheet.isVisible()) {
await sheet.getByRole("button", { name: "Close", exact: true }).click();
await expect(sheet).toHaveCount(0);
}
await selectSettingsHost(page, serverId);
await expectAppRoute(page, buildSettingsHostSectionRoute(serverId, "devices"));
await expect(page.getByTestId("devices-relay")).toBeVisible();
await openPairDeviceWaysSheet(page);
}
export async function openRelaySecurityDocs(page: Page): Promise<void> {
@@ -80,17 +80,38 @@ async function createListedPlugin(root: string) {
git("add", "-A");
git("commit", "-m", "initial");
const date = "2026-10-03T00:00:00.000Z";
const commit = git("rev-parse", "HEAD");
return {
id: LISTING.id,
name: LISTING.name,
description: LISTING.description,
license: "MIT",
requirements: { paseo: ">=0.8.0" },
categories: ["tools"],
author: { github: "acme", name: "Acme" },
repository: { url: "https://github.com/acme/directory-example" },
author: {
github: "acme",
name: "Acme",
bio: "Building developer workflow plugins for Paseo.",
website: "https://acme.dev",
},
repository: { url: "https://github.com/acme/directory-example", commit },
artifact: {
kind: "git",
remote: pathToFileURL(repository).href,
commit: git("rev-parse", "HEAD"),
commit,
},
links: [
{ label: "Documentation", url: "https://acme.dev/docs", icon: "book" },
{
label: "Changelog",
url: "https://github.com/acme/directory-example/releases",
icon: "changelog",
},
],
funding: [{ platform: "github", url: "https://github.com/sponsors/acme" }],
scorecardSummary: {
health: { grade: "excellent" },
review: { status: "passed", score: 4, noteCount: 0 },
},
media: [],
submittedAt: date,
@@ -101,21 +122,169 @@ async function createListedPlugin(root: string) {
};
}
function createRelatedFixtures(date: string) {
const specs = [
[
"acme/pr-radar",
"PR Radar",
"Monitors pull requests and CI checks across connected hosts.",
1400,
],
[
"acme/commit-diff",
"Commit Diff",
"Compact commit history and inline file tree diff viewer.",
980,
],
[
"acme/sidebar-plus",
"Sidebar Plus",
"Groups workspaces into folders with custom status pills.",
1120,
],
[
"acme/linear-sync",
"Linear Sync",
"Attaches Linear tickets to workspaces from slash commands.",
860,
],
[
"acme/worktree-guard",
"Worktree Guard",
"Fast-forwards base branches before creating new worktrees.",
740,
],
[
"acme/usage-meter",
"Usage Meter",
"Shows live token usage and session pacing in the sidebar.",
650,
],
] as const;
return specs.map(([id, name, description, installs]) => ({
id,
name,
description,
license: "MIT",
categories: ["tools"],
author: { github: "acme", name: "Acme" },
repository: { url: `https://github.com/${id}` },
artifact: { kind: "git", remote: `https://github.com/${id}.git`, commit: "a".repeat(40) },
scorecardSummary: {
health: { grade: "good" },
review: { status: "passed", score: 4, noteCount: 0 },
},
media: [],
submittedAt: date,
reviewedAt: date,
updatedAt: date,
publishedAt: date,
installs,
}));
}
async function startRegistry(listing: Record<string, unknown>) {
const date = "2026-10-03T00:00:00.000Z";
const commit = (listing.artifact as { commit: string }).commit;
const related = createRelatedFixtures(date);
const detailDocument = {
...listing,
readme: `# ${LISTING.name}\n\n${LISTING.overview}\n\n## Capabilities\n\n- Adds a lightweight review checklist panel to every workspace.\n- Works across Desktop, Web, and Mobile without extra setup.`,
health: {
grade: "excellent",
summary: "This plugin is actively maintained.",
signals: [
{
id: "hygiene",
summary: "Overview, MIT license, and Paseo version requirement present.",
},
{
id: "maintenance",
summary: "Last commit 2 days ago. 64 commits in the past year.",
},
{
id: "responsiveness",
summary: "Closed 94% of 18 issues. 2 active contributors.",
},
{ id: "adoption", summary: "1.2k installations, 86 stars." },
],
},
review: {
status: "passed",
score: 4,
reviewedAt: date,
reviewUrl: "https://github.com/getpaseo/plugins/pull/2410",
policyUrl: "https://github.com/getpaseo/plugins/blob/main/REVIEW.md",
platforms: ["desktop", "web", "ios", "android"],
notes: [],
passed: [
{ id: "integrity", summary: "Artifact matches pinned Git commit hash." },
{ id: "lockfile", summary: "No external runtime dependencies or install scripts." },
{ id: "obfuscation", summary: "No obfuscation detected." },
{ id: "network", summary: "No suspicious network or exfiltration patterns found." },
],
capabilities: [
{
id: "cap.workspace",
label: "Workspace panel",
summary: "Renders a checklist tab inside Paseo workspaces.",
details:
"Registers a client workspace panel via @getpaseo/plugin/client in index.client.ts.",
},
{
id: "cap.storage",
label: "Plugin settings",
summary: "Stores checklist templates in plugin-scoped settings.",
details:
"Uses registerSettings with Zod schema validation; writes no files outside plugin storage.",
},
],
},
history: [
{
label: "v1.2.0",
kind: "git",
commit,
tag: "v1.2.0",
publishedAt: date,
url: "https://github.com/acme/directory-example/releases/tag/v1.2.0",
reviewUrl: "https://github.com/getpaseo/plugins/pull/2410",
},
{
label: "v1.1.0",
kind: "git",
commit: "b".repeat(40),
tag: "v1.1.0",
publishedAt: "2026-09-20T00:00:00.000Z",
url: "https://github.com/acme/directory-example/releases/tag/v1.1.0",
reviewUrl: "https://github.com/getpaseo/plugins/pull/2180",
},
{
label: "c81a4f2",
kind: "git",
commit: "c81a4f2".padEnd(40, "0"),
publishedAt: "2026-09-05T00:00:00.000Z",
url: `https://github.com/acme/directory-example/commit/${"c81a4f2".padEnd(40, "0")}`,
},
],
};
const documents: Record<string, unknown> = {
"/index.json": {
schemaVersion: 1,
registry: { name: "Local", url: "http://127.0.0.1" },
categories: [{ slug: "tools", label: "Tools" }],
plugins: [listing],
plugins: [listing, ...related],
featured: [],
generatedAt: "2026-10-03T00:00:00.000Z",
},
[`/plugins/${LISTING.id}.json`]: {
...listing,
readme: `# ${LISTING.name}\n\n${LISTING.overview}`,
generatedAt: date,
},
[`/plugins/${LISTING.id}.json`]: detailDocument,
};
for (const item of related) {
documents[`/plugins/${item.id}.json`] = {
...item,
readme: `# ${item.name}\n\n${item.description}`,
};
}
const server = createServer((request, response) => {
const document = request.url ? documents[request.url] : undefined;
if (!document) {
@@ -2,6 +2,7 @@ import type { Page } from "@playwright/test";
declare global {
var __PASEO_E2E_REACT_RENDERS__: Record<string, number> | undefined;
var __PASEO_E2E_REACT_COMMITS__: number | undefined;
}
/**
@@ -54,6 +55,8 @@ export async function recordReactRenders(page: Page): Promise<void> {
checkDCE() {},
onScheduleFiberRoot() {},
onCommitFiberRoot(_rendererId: number, root: { current: Fiber }) {
globalThis.__PASEO_E2E_REACT_COMMITS__ =
(globalThis.__PASEO_E2E_REACT_COMMITS__ ?? 0) + 1;
record(root.current);
},
onPostCommitFiberRoot() {},
@@ -66,6 +69,7 @@ export async function recordReactRenders(page: Page): Promise<void> {
export async function resetReactRenders(page: Page): Promise<void> {
await page.evaluate(() => {
globalThis.__PASEO_E2E_REACT_RENDERS__ = {};
globalThis.__PASEO_E2E_REACT_COMMITS__ = 0;
});
}
@@ -76,3 +80,11 @@ export async function readReactRenders(page: Page): Promise<Record<string, numbe
return { ...globalThis.__PASEO_E2E_REACT_RENDERS__ };
});
}
/** React commits since the last reset, read after the next painted frame. */
export async function readReactCommits(page: Page): Promise<number> {
return page.evaluate(async () => {
await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)));
return globalThis.__PASEO_E2E_REACT_COMMITS__ ?? 0;
});
}
@@ -0,0 +1,334 @@
import { writeFile } from "node:fs/promises";
import { expect, type Locator, type Page } from "@playwright/test";
import {
SYNCED_LOADER_DOT_COUNT,
getSyncedLoaderDotOpacity,
} from "../../../src/components/synced-loader/state";
import { expectComposerVisible } from "./composer";
import { openAgentRoute, seedMockAgentWorkspace, type MockAgentWorkspace } from "./mock-agent";
const HELD_TOOL_CALL_PROMPT = "Hold a running shell tool call for 600000ms.";
export function workingLoader(page: Page): Locator {
return page.getByTestId("synced-loader").filter({ visible: true });
}
function loaderDots(page: Page): Locator {
return page.getByTestId("synced-loader-dot").filter({ visible: true });
}
export function statusRings(page: Page): Locator {
return page.getByTestId("status-ring").filter({ visible: true });
}
export function runningToolCall(page: Page): Locator {
return page.getByTestId("tool-call-badge").last();
}
/**
* Opens an agent whose turn is one running tool call and nothing else: the six-dot loader, the
* tool-call label shimmer and the status rings are all on screen, and nothing streams.
*/
export async function openQuietRunningTurn(page: Page): Promise<MockAgentWorkspace> {
const agent = await seedMockAgentWorkspace({
repoPrefix: "running-indicators-",
title: "Running indicators",
});
try {
await openAgentRoute(page, { workspaceId: agent.workspaceId, agentId: agent.agentId });
await expectComposerVisible(page);
await agent.client.sendAgentMessage(agent.agentId, HELD_TOOL_CALL_PROMPT);
await expect(workingLoader(page)).toBeVisible({ timeout: 30_000 });
await expect(runningToolCall(page)).toBeVisible();
await expect(statusRings(page).first()).toBeVisible();
// Park the pointer on empty chat so no hover state repaints during a measurement.
await page.mouse.move(900, 300);
return agent;
} catch (error) {
await agent.cleanup();
throw error;
}
}
/**
* Opens an idle chat while an agent runs in another workspace: the only thing moving on screen is
* the running workspace's status ring in the sidebar.
*/
export async function openIdleChatBesideRunningAgent(page: Page): Promise<{
cleanup(): Promise<void>;
}> {
const running = await seedMockAgentWorkspace({
repoPrefix: "running-beside-",
title: "Running beside",
initialPrompt: HELD_TOOL_CALL_PROMPT,
});
try {
const idle = await seedMockAgentWorkspace({ repoPrefix: "idle-chat-", title: "Idle chat" });
const cleanup = async () => {
await idle.cleanup();
await running.cleanup();
};
try {
await openAgentRoute(page, { workspaceId: idle.workspaceId, agentId: idle.agentId });
await expectComposerVisible(page);
await expect(statusRings(page).first()).toBeVisible({ timeout: 30_000 });
await expect(workingLoader(page)).toHaveCount(0);
await page.mouse.move(900, 300);
return { cleanup };
} catch (error) {
await cleanup();
throw error;
}
} catch (error) {
await running.cleanup().catch(() => undefined);
throw error;
}
}
/** Every angle the first visible status ring's quarter is seen at over the window, in degrees. */
export async function recordRingAngles(page: Page, windowMs: number): Promise<number[]> {
return statusRings(page)
.first()
.evaluate(
(ring, sampleWindowMs) =>
new Promise<number[]>((resolve, reject) => {
const turning = document
.getAnimations()
.map((animation) => animation.effect)
.filter((effect): effect is KeyframeEffect => effect instanceof KeyframeEffect)
.find((effect) => effect.target && ring.contains(effect.target));
const quarter = turning?.target;
if (!quarter) {
reject(new Error("The status ring is not turning"));
return;
}
const angles = new Set<number>();
const startedAt = performance.now();
const sample = () => {
const { a, b } = new DOMMatrixReadOnly(getComputedStyle(quarter).transform);
const degrees = (Math.atan2(b, a) * 180) / Math.PI;
angles.add(Math.round(((degrees + 360) % 360) * 100) / 100);
if (performance.now() - startedAt >= sampleWindowMs) {
resolve([...angles].sort((first, second) => first - second));
return;
}
requestAnimationFrame(sample);
};
sample();
}),
windowMs,
);
}
export interface IndicatorTurnovers {
/** Frames sampled, one per animation frame. */
frames: number;
/** The frames on which the ring's quarter moved. */
ring: number[];
/** The frames on which the tool-call shimmer's band moved. */
shimmer: number[];
/** Every horizontal offset the shimmer's band was seen at, in px. */
shimmerOffsets: number[];
}
/**
* Watches the first visible status ring and the running tool call's shimmer on every animation
* frame over the window, and reports on which frames each of them moved.
*/
export async function recordIndicatorTurnovers(
page: Page,
windowMs: number,
): Promise<IndicatorTurnovers> {
const ring = await statusRings(page).first().elementHandle();
const shimmer = await runningToolCall(page).getByTestId("label-shimmer").elementHandle();
return page.evaluate(
({ ring: ringRoot, shimmer: shimmerRoot, sampleWindowMs }) =>
new Promise<IndicatorTurnovers>((resolve, reject) => {
const movingTarget = (root: Element | null) =>
document
.getAnimations()
.map((animation) => animation.effect)
.filter((effect): effect is KeyframeEffect => effect instanceof KeyframeEffect)
.find((effect) => effect.target && root?.contains(effect.target))?.target;
const quarter = movingTarget(ringRoot);
const band = movingTarget(shimmerRoot);
if (!quarter || !band) {
reject(new Error("The status ring and the shimmer are not both moving"));
return;
}
const read = (element: Element) => getComputedStyle(element).transform;
const turnovers: IndicatorTurnovers = {
frames: 0,
ring: [],
shimmer: [],
shimmerOffsets: [],
};
const offsets = new Set<number>();
let previous = { ring: read(quarter), shimmer: read(band) };
const startedAt = performance.now();
const sample = () => {
const current = { ring: read(quarter), shimmer: read(band) };
turnovers.frames += 1;
if (current.ring !== previous.ring) turnovers.ring.push(turnovers.frames);
if (current.shimmer !== previous.shimmer) turnovers.shimmer.push(turnovers.frames);
offsets.add(Math.round(new DOMMatrixReadOnly(current.shimmer).e * 100) / 100);
previous = current;
if (performance.now() - startedAt >= sampleWindowMs) {
turnovers.shimmerOffsets = [...offsets].sort((first, second) => first - second);
resolve(turnovers);
return;
}
requestAnimationFrame(sample);
};
requestAnimationFrame(sample);
}),
{ ring, shimmer, sampleWindowMs: windowMs },
);
}
/** The loader's current step, or null while the dots are between two readable states. */
export async function readLoaderStep(page: Page): Promise<number | null> {
const opacities = await loaderDots(page).evaluateAll((dots) =>
dots.map((dot) => Number.parseFloat(getComputedStyle(dot).opacity)),
);
if (opacities.length !== SYNCED_LOADER_DOT_COUNT) {
throw new Error(`Expected ${SYNCED_LOADER_DOT_COUNT} loader dots, found ${opacities.length}`);
}
for (let step = 0; step < SYNCED_LOADER_DOT_COUNT; step += 1) {
const matches = opacities.every(
(opacity, dot) => Math.abs(opacity - getSyncedLoaderDotOpacity(step, dot)) < 0.005,
);
if (matches) {
return step;
}
}
return null;
}
export interface LoaderStepChange {
step: number;
atMs: number;
}
/** Every step change the loader shows over the window, timestamped on the page's clock. */
export async function recordLoaderStepChanges(
page: Page,
windowMs: number,
): Promise<LoaderStepChange[]> {
const states = Array.from({ length: SYNCED_LOADER_DOT_COUNT }, (_, step) =>
Array.from({ length: SYNCED_LOADER_DOT_COUNT }, (__, dot) =>
getSyncedLoaderDotOpacity(step, dot),
),
);
return loaderDots(page).evaluateAll(
(dots, input) =>
new Promise<LoaderStepChange[]>((resolve) => {
const readStep = () => {
const opacities = dots.map((dot) => Number.parseFloat(getComputedStyle(dot).opacity));
return input.states.findIndex((state) =>
state.every((opacity, dot) => Math.abs(opacity - opacities[dot]) < 0.005),
);
};
const changes: LoaderStepChange[] = [];
const startedAt = performance.now();
const sample = () => {
const atMs = performance.now() - startedAt;
const step = readStep();
if (step !== -1 && step !== changes.at(-1)?.step) {
changes.push({ step, atMs });
}
if (atMs >= input.windowMs) {
resolve(changes);
return;
}
requestAnimationFrame(sample);
};
sample();
}),
{ states, windowMs },
);
}
export interface RunningAnimation {
name: string;
target: string;
durationMs: number;
easing: string;
iterations: number;
properties: string[];
}
/** Every animation the document is currently running, by what it animates. */
export async function readRunningAnimations(page: Page): Promise<RunningAnimation[]> {
return page.evaluate(() => {
const timingKeys = new Set(["offset", "computedOffset", "easing", "composite"]);
const running: RunningAnimation[] = [];
for (const animation of document.getAnimations()) {
const effect = animation.effect;
if (animation.playState !== "running" || !(effect instanceof KeyframeEffect)) {
continue;
}
const properties = new Set<string>();
for (const keyframe of effect.getKeyframes()) {
for (const key of Object.keys(keyframe)) {
if (!timingKeys.has(key)) {
properties.add(key);
}
}
}
const timing = effect.getComputedTiming();
const target = effect.target;
running.push({
name: animation instanceof CSSAnimation ? animation.animationName : "script",
target:
target?.closest("[data-testid]")?.getAttribute("data-testid") ?? target?.tagName ?? "",
durationMs: Number(timing.duration),
easing: String(timing.easing),
iterations: Number(timing.iterations),
properties: [...properties],
});
}
return running;
});
}
/** What is currently animating, by test id. */
export async function readAnimatingTargets(page: Page): Promise<string[]> {
const animations = await readRunningAnimations(page);
return animations.map((animation) => animation.target);
}
/** Freezes every running animation at the same point of its cycle so a frame can be compared. */
export async function freezeAnimationsAt(page: Page, progress: number): Promise<void> {
await page.evaluate(async (cycleProgress) => {
for (const animation of document.getAnimations()) {
const duration = Number(animation.effect?.getComputedTiming().duration);
animation.pause();
animation.currentTime = duration * cycleProgress;
}
await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)));
}, progress);
}
/** Saves one image of the loader for each of its steps, named by step. */
export async function captureLoaderSteps(
page: Page,
pathForStep: (step: number) => string,
): Promise<number[]> {
const loader = workingLoader(page);
const captured = new Set<number>();
for (let attempt = 0; attempt < 200 && captured.size < SYNCED_LOADER_DOT_COUNT; attempt += 1) {
const before = await readLoaderStep(page);
if (before === null || captured.has(before)) {
continue;
}
const image = await loader.screenshot();
// The step can turn over mid-capture; only an image bracketed by one step is that step.
if ((await readLoaderStep(page)) !== before) {
continue;
}
await writeFile(pathForStep(before), image);
captured.add(before);
}
return [...captured].sort((a, b) => a - b);
}
@@ -168,6 +168,11 @@ export interface SeedDaemonClient {
timeout?: number,
): Promise<{ status: string }>;
cancelAgent(agentId: string): Promise<void>;
respondToPermission(
agentId: string,
requestId: string,
response: { behavior: "allow" },
): Promise<void>;
sendAgentMessage(
agentId: string,
text: string,
@@ -182,9 +187,9 @@ export interface SeedDaemonClient {
): Promise<{ status: string; final?: { lastError?: string | null } | null }>;
archiveAgent(agentId: string): Promise<{ archivedAt: string }>;
refreshAgent(agentId: string): Promise<unknown>;
fetchAgent(options: {
agentId: string;
}): Promise<{ agent: { id: string; archivedAt?: string | null } } | null>;
fetchAgent(options: { agentId: string }): Promise<{
agent: { id: string; archivedAt?: string | null; pendingPermissions: Array<{ id: string }> };
} | null>;
getLastServerInfoMessage(): {
features?: {
projectAdd?: boolean;
+42 -3
View File
@@ -258,8 +258,37 @@ export async function expectAddHostFieldDrawnAsInput(page: Page, testId: string)
await expect(field).not.toHaveCSS("background-color", "rgba(0, 0, 0, 0)");
}
export async function toggleHostAdvanced(page: Page): Promise<void> {
await page.getByTestId("direct-host-advanced-toggle").click();
function directConnectionModeSegment(page: Page, mode: "Form" | "URI") {
return page.getByTestId("direct-mode").getByRole("button", { name: mode, exact: true });
}
export async function selectDirectConnectionMode(page: Page, mode: "Form" | "URI"): Promise<void> {
await directConnectionModeSegment(page, mode).click();
await expectDirectConnectionMode(page, mode);
}
export async function expectDirectConnectionMode(page: Page, mode: "Form" | "URI"): Promise<void> {
await expect(directConnectionModeSegment(page, mode)).toHaveAttribute("aria-selected", "true");
}
export async function expectDirectFormModeDisabled(page: Page): Promise<void> {
await expect(directConnectionModeSegment(page, "Form")).toBeDisabled();
}
export async function connectDirectHost(page: Page): Promise<void> {
await page.getByTestId("direct-host-submit").click();
await expect(page.getByTestId("add-host-modal")).toHaveCount(0, { timeout: 30_000 });
}
export async function connectDirectHostExpectingPassword(page: Page, host: string): Promise<void> {
await page.getByTestId("direct-host-submit").click();
await expect(page.getByText(`Password for ${host}`, { exact: true })).toBeVisible({
timeout: 30_000,
});
}
export async function fillDirectHostPromptPassword(page: Page, password: string): Promise<void> {
await page.getByRole("textbox", { name: "Host password", exact: true }).fill(password);
}
export async function openCompactSettings(page: Page, expectedStartRoute: string): Promise<void> {
@@ -422,6 +451,10 @@ export async function fillDirectHostAddress(page: Page, host: string, port: stri
await page.getByRole("textbox", { name: "Port", exact: true }).fill(port);
}
export async function pasteIntoDirectHost(page: Page, text: string): Promise<void> {
await page.getByRole("textbox", { name: "Host", exact: true }).fill(text);
}
export async function toggleDirectHostSsl(page: Page): Promise<void> {
await page.getByRole("checkbox", { name: "Use SSL", exact: true }).click();
}
@@ -439,6 +472,12 @@ export async function expectDirectHostUriHidden(page: Page): Promise<void> {
await expect(page.getByTestId("direct-host-uri-input")).toHaveCount(0);
}
/** The whole form shows above Cancel and Connect, with nothing cut off by the footer. */
export async function expectDirectFormFullyVisible(page: Page): Promise<void> {
await expect(page.getByTestId("direct-password-input")).toBeInViewport({ ratio: 1 });
await expect(page.getByTestId("direct-password-visibility-toggle")).toBeInViewport({ ratio: 1 });
}
export async function expectDiagnosticsContent(page: Page): Promise<void> {
await expect(page.getByRole("button", { name: "Run" })).toBeVisible();
await expect(page.getByRole("button", { name: "Play test" })).toBeVisible();
@@ -480,7 +519,7 @@ export async function expectHostConnectionsCard(page: Page, port: string): Promi
export async function expectHostInjectMcpCard(page: Page): Promise<void> {
const card = page.getByTestId("host-page-inject-mcp-card");
await expect(card).toBeVisible();
await expect(card.getByRole("switch", { name: "Inject Paseo tools" })).toBeVisible();
await expect(card.getByRole("switch", { name: "Enable tools" })).toBeVisible();
}
function idleAgentReleaseSwitch(page: Page) {
@@ -0,0 +1,157 @@
import type { Browser, CDPSession, Page } from "@playwright/test";
/**
* What a page costs while nothing on it is supposed to be changing: how often the main thread is
* woken, how much it restyles and repaints, and how much CPU the renderer burns doing it.
* Rates are per second of the sampled window.
*/
export interface SteadyStateActivity {
animationFrameCallbacksPerSecond: number;
timerCallbacksPerSecond: number;
styleRecalcsPerSecond: number;
layoutsPerSecond: number;
paintsPerSecond: number;
/** Repainted area per second, in viewports. */
paintedViewportsPerSecond: number;
/** Times the main thread committed new work to the compositor. */
mainThreadCommitsPerSecond: number;
rasterTasksPerSecond: number;
/** Frames the compositor drew, with or without the main thread. */
compositorFramesPerSecond: number;
mainThreadBusyMsPerSecond: number;
rendererCpuPercent: number;
gpuCpuPercent: number;
}
interface TraceEvent {
name: string;
ph: string;
pid: number;
args?: {
data?: {
clip?: number[];
};
};
}
const TRACE_CATEGORIES = [
"devtools.timeline",
"disabled-by-default-devtools.timeline",
"disabled-by-default-devtools.timeline.frame",
];
async function readProcessCpuSeconds(session: CDPSession): Promise<Map<string, number>> {
const { processInfo } = await session.send("SystemInfo.getProcessInfo");
const cpuByType = new Map<string, number>();
for (const process of processInfo) {
cpuByType.set(process.type, (cpuByType.get(process.type) ?? 0) + process.cpuTime);
}
return cpuByType;
}
async function readMainThreadBusySeconds(session: CDPSession): Promise<number> {
const { metrics } = await session.send("Performance.getMetrics");
return metrics.find((metric) => metric.name === "TaskDuration")?.value ?? 0;
}
function quadArea(clip: number[] | undefined): number {
if (!clip || clip.length !== 8) {
return 0;
}
const xs = [clip[0], clip[2], clip[4], clip[6]];
const ys = [clip[1], clip[3], clip[5], clip[7]];
return (Math.max(...xs) - Math.min(...xs)) * (Math.max(...ys) - Math.min(...ys));
}
function summarizeTrace(input: {
events: TraceEvent[];
seconds: number;
viewportArea: number;
}): Pick<
SteadyStateActivity,
| "animationFrameCallbacksPerSecond"
| "timerCallbacksPerSecond"
| "styleRecalcsPerSecond"
| "layoutsPerSecond"
| "paintsPerSecond"
| "paintedViewportsPerSecond"
| "mainThreadCommitsPerSecond"
| "rasterTasksPerSecond"
| "compositorFramesPerSecond"
> {
const { events, seconds, viewportArea } = input;
const counts = new Map<string, number>();
let paintedArea = 0;
for (const event of events) {
// "B"/"X" open a slice and "I" is an instant; skipping "E" keeps begin/end pairs at one count.
if (event.ph === "E") {
continue;
}
counts.set(event.name, (counts.get(event.name) ?? 0) + 1);
if (event.name === "Paint") {
paintedArea += quadArea(event.args?.data?.clip);
}
}
const perSecond = (name: string) => (counts.get(name) ?? 0) / seconds;
return {
animationFrameCallbacksPerSecond: perSecond("FireAnimationFrame"),
timerCallbacksPerSecond: perSecond("TimerFire"),
styleRecalcsPerSecond: perSecond("UpdateLayoutTree"),
layoutsPerSecond: perSecond("Layout"),
paintsPerSecond: perSecond("Paint"),
paintedViewportsPerSecond: paintedArea / viewportArea / seconds,
mainThreadCommitsPerSecond: perSecond("BeginCommitCompositorFrame"),
rasterTasksPerSecond: perSecond("RasterTask"),
compositorFramesPerSecond: perSecond("DrawFrame"),
};
}
/**
* Samples the page twice: once untraced for CPU and main-thread time, so the tracer's own cost
* stays out of those numbers, then once traced for the per-event counts.
*/
export async function measureSteadyStateActivity(input: {
browser: Browser;
page: Page;
windowMs: number;
}): Promise<SteadyStateActivity> {
const { browser, page, windowMs } = input;
const seconds = windowMs / 1000;
const viewport = page.viewportSize();
if (!viewport) {
throw new Error("Steady-state activity needs a fixed viewport");
}
const pageSession = await page.context().newCDPSession(page);
const browserSession = await browser.newBrowserCDPSession();
try {
await pageSession.send("Performance.enable");
const cpuBefore = await readProcessCpuSeconds(browserSession);
const busyBefore = await readMainThreadBusySeconds(pageSession);
await page.waitForTimeout(windowMs);
const busyAfter = await readMainThreadBusySeconds(pageSession);
const cpuAfter = await readProcessCpuSeconds(browserSession);
await browser.startTracing(page, { categories: TRACE_CATEGORIES });
await page.waitForTimeout(windowMs);
const trace = JSON.parse((await browser.stopTracing()).toString("utf8")) as {
traceEvents: TraceEvent[];
};
const cpuPercent = (type: string) =>
(((cpuAfter.get(type) ?? 0) - (cpuBefore.get(type) ?? 0)) / seconds) * 100;
return {
...summarizeTrace({
events: trace.traceEvents,
seconds,
viewportArea: viewport.width * viewport.height,
}),
mainThreadBusyMsPerSecond: ((busyAfter - busyBefore) * 1000) / seconds,
rendererCpuPercent: cpuPercent("renderer"),
gpuCpuPercent: cpuPercent("GPU"),
};
} finally {
await pageSession.detach().catch(() => undefined);
await browserSession.detach().catch(() => undefined);
}
}
@@ -45,7 +45,10 @@ export async function requestStreamingMarkdown(agent: StreamingMarkdownAgent): P
export async function expectUnfinishedBold(page: Page): Promise<void> {
const message = page.getByTestId("assistant-message").last();
await expect(message.locator(".enrm-text")).toContainText("Bold");
const bold = message.locator("strong");
await expect(bold).toContainText("Bold");
await expect(bold).toHaveCSS("font-weight", "700");
await expect(message).not.toContainText("*");
await expect(message).not.toContainText("stays bold");
}
@@ -58,6 +61,7 @@ export async function expectUnfinishedLink(
await agent.stream.showThrough("**Bold text stays bold** and [Paseo docs");
await expect(message).toContainText("Paseo docs");
await expect(message.getByRole("link", { name: "Paseo docs" })).toHaveCount(0);
await expect(message).not.toContainText("[");
await expect(message).not.toContainText("https:");
await captureMarkdown(page, testInfo, "unfinished-link");
}
@@ -9,6 +9,7 @@ interface SessionMessage {
interface TimelineSubscriptionWaitOptions {
timeout?: number;
match?: "exact" | "includes";
}
function readSessionMessage(message: WebSocketMessage): SessionMessage | null {
@@ -56,7 +57,7 @@ export function observeTimelineSubscriptions(page: Page) {
.poll(() => acknowledgedAgentIds?.slice().sort() ?? null, {
timeout: options.timeout ?? 15_000,
})
.toEqual(expected);
.toEqual(options.match === "includes" ? expect.arrayContaining(expected) : expected);
},
};
}
@@ -324,6 +324,124 @@ export async function stopStreamingReply(agent: StreamingReplyAgent): Promise<st
return reply;
}
interface LoadingSurfaceRecord {
loaderText: string[];
spinnerYsByTestId: Record<string, number[]>;
sawUpdatingToast: boolean;
}
declare global {
interface Window {
__loadingSurfaceRecord?: LoadingSurfaceRecord;
}
}
function recordLoadingSurfaces(): void {
const record: LoadingSurfaceRecord = {
loaderText: [],
spinnerYsByTestId: {},
sawUpdatingToast: false,
};
window.__loadingSurfaceRecord = record;
const isVisible = (el: Element | null): el is HTMLElement => {
if (!(el instanceof HTMLElement)) return false;
const style = window.getComputedStyle(el);
if (style.display === "none" || style.visibility === "hidden" || style.opacity === "0") {
return false;
}
const rect = el.getBoundingClientRect();
return rect.width > 0 && rect.height > 0;
};
const sample = () => {
if (!document.body) return;
for (const testId of [
"workspace-loading",
"agent-loading",
"agent-history-overlay",
"agent-initial-fill",
]) {
const el = document.querySelector(`[data-testid="${testId}"]`);
if (!isVisible(el)) continue;
const text = (el.textContent ?? "").trim();
if (text.length > 0 && !record.loaderText.includes(text)) {
record.loaderText.push(text);
}
const spinner = el.querySelector('[role="progressbar"]');
if (spinner) {
const y = Math.round(spinner.getBoundingClientRect().y);
const list = record.spinnerYsByTestId[testId] ?? [];
if (!list.includes(y)) list.push(y);
record.spinnerYsByTestId[testId] = list;
}
}
if (document.querySelector('[data-testid="agent-updating-toast"]') !== null) {
record.sawUpdatingToast = true;
}
};
const start = () => {
const observer = new MutationObserver(sample);
observer.observe(document.documentElement ?? document, {
childList: true,
subtree: true,
attributes: true,
characterData: true,
});
sample();
};
if (document.documentElement) start();
else document.addEventListener("DOMContentLoaded", start, { once: true });
}
/** Records loading text, spinner Y positions, and any Updating messages toast from first paint. */
export async function watchColdAndReloadLoadingSurfaces(page: Page): Promise<void> {
await page.addInitScript(recordLoadingSurfaces);
}
/** Asserts every loading surface stayed textless, unshifted, and free of Updating messages. */
export async function expectCleanLoadingSurfaces(
page: Page,
gate: DaemonWebSocketGate,
before: TimelineRequestCounts,
): Promise<void> {
await waitForNextPaint(page);
const record = await page.evaluate(() => window.__loadingSurfaceRecord as LoadingSurfaceRecord);
expect(record.loaderText, "loading states must not render visible text").toEqual([]);
expect(record.sawUpdatingToast, "Updating messages must not flash after chat loads").toBe(false);
for (const [testId, ys] of Object.entries(record.spinnerYsByTestId)) {
expect(
ys.length,
`${testId} spinner shifted vertically (${ys.join(", ")})`,
).toBeLessThanOrEqual(1);
}
expect(
gate.getTimelineRequestCount("after", before.agentId) - before.after,
"initial tail load must not trigger a redundant after catch-up",
).toBe(0);
}
/** Waits until the persisted replica cache drops coverage to a display-only snapshot. */
export async function waitForDisplayOnlyTimelineCache(
page: Page,
agent: LongTimelineAgent,
): Promise<void> {
await expect
.poll(
async () => {
const cache = await readReplicaCache(page);
const timeline = cache?.hosts
?.flatMap((host) => host.timelines)
.find((entry) => entry.agentId === agent.agentId);
return timeline?.items ? { items: timeline.items.length, range: timeline.range } : null;
},
{ timeout: 15_000 },
)
.toMatchObject({ range: null });
}
export async function expectPromptAndWholeReply(
page: Page,
agent: StreamingReplyAgent,
@@ -204,25 +204,25 @@ export async function readSidebarListLayout(page: Page): Promise<SidebarListLayo
});
}
/**
* Starts recording the bottom edge of the sidebar list's last row once per painted frame.
* Resolves with one value per frame after `frameCount` frames.
*/
export function recordLastRowBottomPerFrame(page: Page, frameCount: number): Promise<number[]> {
/** Records the last row's positions until the archive toast finishes fading out. */
export function recordLastRowDuringToastExpiry(page: Page): Promise<number[]> {
return page.getByTestId(SIDEBAR_LIST).evaluate(
(element, count) =>
(element) =>
new Promise<number[]>((resolve) => {
const bottoms: number[] = [];
const sample = () => {
const rows = element.querySelectorAll<HTMLElement>(
'[data-testid^="sidebar-workspace-row-"],[data-testid^="sidebar-project-row-"]',
);
bottoms.push(Math.max(...Array.from(rows, (row) => row.getBoundingClientRect().bottom)));
if (bottoms.length >= count) resolve(bottoms);
else requestAnimationFrame(sample);
const bottom = Math.max(...Array.from(rows, (row) => row.getBoundingClientRect().bottom));
if (bottom !== bottoms.at(-1)) bottoms.push(bottom);
if (document.querySelector('[data-testid="workspace-archived-toast"]')) {
requestAnimationFrame(sample);
} else {
resolve(bottoms);
}
};
requestAnimationFrame(sample);
sample();
}),
frameCount,
);
}
@@ -180,9 +180,7 @@ public final class PaseoHardwareKeyboardWindow: UIWindow {
}
public override var keyCommands: [UIKeyCommand]? {
var commands = super.keyCommands ?? []
if isHardwareSubmitEnabled && !isPlainReturnClaimed && !isComposingText()
&& UIDevice.current.userInterfaceIdiom == .pad
{
if isHardwareSubmitEnabled && !isPlainReturnClaimed && !isComposingText() {
commands.append(makeSubmitCommand())
}
if !isComposingText() {
@@ -63,6 +63,8 @@ using namespace facebook::react;
- (instancetype)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame]) {
// The iOS status-bar tap region can overlap app header buttons (#11027).
self.scrollView.scrollsToTop = NO;
#if defined(__IPHONE_26_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_26_0
if (@available(iOS 26.0, *)) {
UIScrollView *scrollView = self.scrollView;
+1
View File
@@ -24,6 +24,7 @@
"test:e2e": "playwright test --project=browser",
"test:e2e:diff-performance": "cross-env PASEO_DIFF_PERF_E2E=1 playwright test --project=browser e2e/browser/diff-performance.spec.ts",
"test:e2e:stream-smoothness": "cross-env PASEO_AGENT_STREAM_PERF_E2E=1 playwright test --project=browser e2e/browser/agent-stream-smoothness.spec.ts",
"test:e2e:agent-update-cost": "cross-env PASEO_AGENT_UPDATE_PERF_E2E=1 playwright test --project=browser e2e/browser/agent-update-cost.spec.ts",
"test:e2e:real": "cross-env E2E_FORK_PASEO_HOME_FROM=../../.dev/paseo-home playwright test --project=real-provider",
"test:e2e:relay-deployment": "npm --prefix ../.. run build:server && npm --prefix ../.. run build:daemon-web-ui && cross-env E2E_FORK_PASEO_HOME_FROM=../../.dev/paseo-home playwright test --project=relay-deployment e2e/browser/relay-deployment-reconnect.real.spec.ts",
"test:e2e:ui": "playwright test --ui",
+12 -4
View File
@@ -3,16 +3,19 @@ import { Text, View } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { Folder, FolderPlus, Plus } from "lucide-react-native";
import { AdaptiveModalSheet, type SheetKeyboard } from "@/components/adaptive-modal-sheet";
import { HostStatusDot } from "@/components/host-status-dot";
import { HostPicker } from "@/components/hosts/host-picker";
import { GitHubIcon } from "@/components/icons/github-icon";
import { Button } from "@/components/ui/button";
import { SegmentedControl, type SegmentedControlOption } from "@/components/ui/segmented-control";
import { useIsCompactFormFactor } from "@/constants/layout";
import { useAddHost } from "@/hosts/add-host";
import { HostStatusIcon } from "@/hosts/host-status-icon";
import { useHardwareKeyboardPresent, type KeyboardInputEvent } from "@/keyboard";
import { Shortcut } from "@/components/ui/shortcut";
import { FieldTrigger } from "@/screens/new-workspace/form/field-trigger";
import {
FieldTrigger,
type FieldTriggerInteractionState,
} from "@/screens/new-workspace/form/field-trigger";
import {
useAddProjectFlowStore,
type AddProjectFlowRequest,
@@ -362,7 +365,12 @@ function HostPill({
const [open, setOpen] = useState(false);
const openPicker = useCallback(() => setOpen(true), []);
const label = hosts.find((host) => host.serverId === hostId)?.label ?? hostId;
const icon = useMemo(() => <HostStatusDot serverId={hostId} />, [hostId]);
const renderIcon = useCallback(
({ backdrop }: FieldTriggerInteractionState) => (
<HostStatusIcon serverId={hostId} size="sm" backdrop={backdrop} />
),
[hostId],
);
return (
<HostPicker
hosts={hosts}
@@ -383,7 +391,7 @@ function HostPill({
label="Host"
accessibilityLabel="Project host"
tooltip="Host"
icon={icon}
icon={renderIcon}
value={label}
onPress={openPicker}
disabled={disabled}
+3 -14
View File
@@ -3,9 +3,12 @@ import { useTranslation } from "react-i18next";
import { i18n } from "@/i18n/i18next";
import { useProviderIcon } from "@/components/provider-icons";
import type { PanelDescriptor } from "@/panels/panel-registry";
import { resolveAgentLabel } from "@/panels/tab-labels";
import { useSessionStore, selectAgentTurnPresentation, type Agent } from "@/stores/session-store";
import { deriveSidebarStateBucket } from "@/utils/sidebar-agent-state";
export { resolveAgentLabel };
function formatProviderLabel(provider: Agent["provider"]): string {
if (!provider) {
return "Agent";
@@ -17,20 +20,6 @@ function formatProviderLabel(provider: Agent["provider"]): string {
.join(" ");
}
export function resolveAgentLabel(title: string | null | undefined): string | null {
if (typeof title !== "string") {
return null;
}
const normalized = title.trim();
if (!normalized) {
return null;
}
if (normalized.toLowerCase() === "new agent") {
return null;
}
return normalized;
}
export function useAgentDescriptor(
target: { kind: "agent"; agentId: string },
context: { serverId: string },
@@ -23,7 +23,15 @@ export interface DraftAgentProfileControls {
}
export type AgentProfileApplyTarget =
| { kind: "agent"; agentId: string; availableModeIds: readonly string[] | null }
| {
kind: "agent";
agentId: string;
availableModeIds: readonly string[] | null;
currentProvider?: string | null;
isSwitchInFlight?: () => boolean;
onApplySameProvider?: () => void;
onStageProviderSwitch?: (profile: MaterializedAgentProfile) => void;
}
| { kind: "draft"; controls: DraftAgentProfileControls };
/** Everything the model picker renders for one profile. It never sees the profile itself. */
@@ -148,6 +156,16 @@ export function useAgentProfilePicker(
return;
}
if (
target.onStageProviderSwitch &&
(target.isSwitchInFlight?.() ||
(target.currentProvider && resolved.provider !== target.currentProvider))
) {
target.onStageProviderSwitch(resolved);
return;
}
target.onApplySameProvider?.();
const reconciled = reconcileMaterializedProfileMode(resolved, target.availableModeIds);
if (!reconciled) {
return;
@@ -157,7 +175,11 @@ export function useAgentProfilePicker(
return;
}
void client
.applyAgentConfig(target.agentId, toAgentConfigApply(reconciled))
.applyAgentConfig(
target.agentId,
toAgentConfigApply(reconciled),
target.currentProvider ? { expectedProvider: target.currentProvider } : undefined,
)
.then((notice) => showProviderNoticeToast(toast, notice))
.catch((error) => {
console.warn("[useAgentProfilePicker] applyAgentConfig failed", error);
+16
View File
@@ -0,0 +1,16 @@
import { useActivatedStore } from "@/sync";
import { createAgentQueueModel, type AgentQueueModel, type AgentQueueSnapshot } from "./model";
export type { AgentQueueModel, AgentQueueSnapshot } from "./model";
export { optimisticEnqueueAgentMessage } from "./overlays";
/** Observes one agent's queue while the caller is mounted in a visible panel. */
export function useAgentQueue(
serverId: string,
agentId: string,
): { model: AgentQueueModel; queue: AgentQueueSnapshot } {
const { store, snapshot } = useActivatedStore(JSON.stringify([serverId, agentId]), (active) =>
createAgentQueueModel({ serverId, agentId, initialActive: active }),
);
return { model: store, queue: snapshot };
}
+198
View File
@@ -0,0 +1,198 @@
import { afterEach, expect, test } from "vitest";
import {
queuedItem,
queueOf,
startAgentQueueDaemon,
type AgentQueueDaemon,
} from "@/test/agent-queue-daemon";
import { createAgentQueueModel } from "./model";
const daemons: AgentQueueDaemon[] = [];
afterEach(async () => {
await Promise.all(daemons.splice(0).map((daemon) => daemon.close()));
});
/** An observed queue model over a daemon that already holds the given rows. */
async function observeQueue(
queue = queueOf("a", "b"),
options?: Parameters<typeof startAgentQueueDaemon>[0],
) {
const daemon = await startAgentQueueDaemon(options);
daemons.push(daemon);
await daemon.publish("agent", queue);
const model = createAgentQueueModel({ serverId: "host", agentId: "agent", host: daemon.host });
model.subscribe(() => {});
await daemon.settle();
const rowIds = () => model.getSnapshot().items.map((entry) => entry.id);
return { daemon, model, rowIds };
}
test("shows the queue the host holds and follows its changes", async () => {
const held = { held: true, items: [queuedItem("a", { held: true })] };
const { daemon, model, rowIds } = await observeQueue(held);
expect(model.getSnapshot()).toEqual({ status: "ready", ...held, busy: new Set() });
expect(model.getSnapshot()).toBe(model.getSnapshot());
await daemon.publish("agent", queueOf("b"));
await daemon.settle();
expect(rowIds()).toEqual(["b"]);
expect(model.getSnapshot().held).toBe(false);
});
test("releases the host subscription while inactive and catches up on its changes", async () => {
const { daemon, model, rowIds } = await observeQueue();
model.setActive(false);
await daemon.settle();
expect(daemon.liveSubscriptions()).toEqual([]);
expect(model.getSnapshot().status).toBe("stale");
expect(rowIds()).toEqual(["a", "b"]);
await daemon.publish("agent", queueOf("b", "c"));
model.setActive(true);
await daemon.settle();
expect(daemon.syncAnswers()).toEqual(["snapshot", "changes"]);
expect(model.getSnapshot().status).toBe("ready");
expect(rowIds()).toEqual(["b", "c"]);
});
test("offers a retry when the queue cannot be read", async () => {
const daemon = await startAgentQueueDaemon();
daemons.push(daemon);
await daemon.publish("agent", queueOf("a"));
daemon.failNextSync("queue unavailable");
const model = createAgentQueueModel({ serverId: "host", agentId: "agent", host: daemon.host });
model.subscribe(() => {});
await daemon.settle();
expect(model.getSnapshot().status).toBe("error");
model.retry();
expect(model.getSnapshot().status).toBe("retrying");
await daemon.settle();
expect(model.getSnapshot()).toMatchObject({ status: "ready", items: [queuedItem("a")] });
});
test("marks a row busy while it is withdrawn, then hides it ahead of the host update", async () => {
const { daemon, model, rowIds } = await observeQueue();
const first = model.withdraw("a");
const second = model.withdraw("a");
expect(model.getSnapshot().busy).toEqual(new Set(["a"]));
expect(await first).toEqual({ withdrawn: true, item: queuedItem("a") });
expect(await second).toBeNull();
expect(daemon.commands()).toHaveLength(1);
expect(model.getSnapshot().busy).toEqual(new Set());
expect(rowIds()).toEqual(["b"]);
expect(await model.withdraw("a")).toBeNull();
// A later change to the row is the host's truth again.
await daemon.publish("agent", {
held: false,
items: [queuedItem("a", { text: "edited" }), queuedItem("b", { seq: 2 })],
});
await daemon.settle();
expect(rowIds()).toEqual(["a", "b"]);
});
test("hides a withdrawn row even when an older update overtakes the answer", async () => {
const { daemon, model, rowIds } = await observeQueue();
daemon.holdCommands();
const result = model.withdraw("a");
await daemon.publish("agent", queueOf("a", "b", "c"));
daemon.releaseCommands();
await result;
await daemon.settle();
expect(rowIds()).toEqual(["b", "c"]);
});
test("optimistic cancel hides the row immediately and restores it if the host refuses", async () => {
const { daemon, model, rowIds } = await observeQueue();
daemon.holdCommands();
const pending = model.withdraw("a", { optimistic: true });
expect(rowIds()).toEqual(["b"]);
daemon.refuseWithdrawals("already_dispatching");
daemon.releaseCommands();
expect(await pending).toEqual({ withdrawn: false, reason: "already_dispatching" });
expect(rowIds()).toEqual(["a", "b"]);
});
test("optimistic promote marks the row dispatching, clears held, and rolls back if refused", async () => {
const { daemon, model } = await observeQueue({
held: true,
items: [queuedItem("a", { held: true }), queuedItem("b", { seq: 2, held: true })],
});
daemon.holdCommands();
const pending = model.promote("b", "interrupt");
expect(model.getSnapshot().held).toBe(false);
expect(model.getSnapshot().items.find((item) => item.id === "b")?.state).toBe("dispatching");
daemon.refusePromotions("already_dispatching");
daemon.releaseCommands();
expect(await pending).toEqual({ promoted: false, reason: "already_dispatching" });
expect(model.getSnapshot().held).toBe(true);
expect(model.getSnapshot().items.find((item) => item.id === "b")?.state).toBe("queued");
});
test("keeps the row when the host already started sending it", async () => {
const { daemon, model, rowIds } = await observeQueue();
daemon.refuseWithdrawals("already_dispatching");
expect(await model.withdraw("a")).toEqual({ withdrawn: false, reason: "already_dispatching" });
expect(rowIds()).toEqual(["a", "b"]);
expect(model.getSnapshot().busy).toEqual(new Set());
});
test("takes no command for a dispatching or absent row", async () => {
const { daemon, model } = await observeQueue({
held: false,
items: [queuedItem("a", { state: "dispatching" })],
});
expect(await model.withdraw("a")).toBeNull();
expect(await model.promote("missing", "steer")).toBeNull();
expect(daemon.commands()).toEqual([]);
});
test("promotes a row with the chosen send behavior", async () => {
const { daemon, model } = await observeQueue();
expect(await model.promote("b", "interrupt")).toEqual({ promoted: true });
expect(daemon.commands()).toMatchObject([
{
type: "agent.queue.promote.request",
agentId: "agent",
messageId: "b",
activeTurnBehavior: "interrupt",
},
]);
});
test("rejects a command and releases the row while the host is disconnected", async () => {
const { daemon, model, rowIds } = await observeQueue();
await daemon.disconnect();
await daemon.settle();
await expect(model.withdraw("a")).rejects.toThrow("Host disconnected");
expect(daemon.commands()).toEqual([]);
expect(model.getSnapshot()).toMatchObject({ status: "stale", busy: new Set() });
expect(rowIds()).toEqual(["a", "b"]);
});
test("has no queue and asks nothing of a host without the feature", async () => {
const { daemon, model } = await observeQueue(queueOf("a"), { features: {} });
expect(model.getSnapshot()).toMatchObject({ status: "ready", items: [] });
expect(daemon.requestCount()).toBe(0);
});
+156
View File
@@ -0,0 +1,156 @@
import { AgentQueueCollection, type PaseoAgentQueueItem, type SyncStatus } from "@getpaseo/client";
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
import type { ActiveTurnBehavior } from "@getpaseo/protocol/messages";
import {
createHostSyncStore,
type HostSyncConnection,
hostRuntimeSyncHost,
type SyncClient,
} from "@/sync";
import { optimisticPromoteAgentQueueItem, optimisticRemoveAgentQueueItem } from "./overlays";
type AgentQueueClient = SyncClient &
Pick<DaemonClient, "withdrawAgentQueueItem" | "promoteAgentQueueItem">;
export interface AgentQueueSnapshot {
status: SyncStatus;
/** The host waits for Send now or the next prompt before it sends these. */
held: boolean;
/** Admission order. The first row is sent next. */
items: readonly PaseoAgentQueueItem[];
/** Rows with a command or optimistic enqueue in flight. */
busy: ReadonlySet<string>;
}
/**
* One agent's queue as the host holds it, with optimistic overlays for in-flight queue commands.
*/
export function createAgentQueueModel({
serverId,
agentId,
initialActive,
host = hostRuntimeSyncHost(serverId),
}: {
serverId: string;
agentId: string;
initialActive?: boolean;
host?: HostSyncConnection<AgentQueueClient>;
}) {
const store = createHostSyncStore({
host,
resource: AgentQueueCollection,
args: { agentId },
// COMPAT(agentMessageQueue): added in v0.18.2, remove gate after 2027-06-01.
feature: "agentMessageQueue",
active: initialActive,
});
let busy: ReadonlySet<string> = new Set();
let view: { source: unknown; busy: ReadonlySet<string>; snapshot: AgentQueueSnapshot } | null =
null;
const listeners = new Set<() => void>();
const getSnapshot = (): AgentQueueSnapshot => {
const source = store.getSnapshot();
if (view?.source !== source || view.busy !== busy) {
view = {
source,
busy,
snapshot: {
status: source.status,
held: source.data?.meta.held ?? false,
items: source.data?.items ?? [],
busy: mergeSets(busy, source.pending),
},
};
}
return view.snapshot;
};
const changed = () => {
view = null;
for (const listener of listeners) listener();
};
const connected = (): AgentQueueClient => {
const client = host.getClient();
if (!client?.getLastServerInfoMessage()) throw new Error("Host disconnected");
return client;
};
/** Runs one command per row at a time. Returns null when the row cannot take one. */
const command = async <T>(
messageId: string,
run: (client: AgentQueueClient) => Promise<T>,
): Promise<T | null> => {
const snapshot = getSnapshot();
const row = snapshot.items.find((entry) => entry.id === messageId);
if (!row || row.state === "dispatching" || snapshot.busy.has(messageId)) return null;
const client = connected();
busy = new Set(busy).add(messageId);
changed();
try {
return await run(client);
} finally {
const next = new Set(busy);
next.delete(messageId);
busy = next;
changed();
}
};
return {
getSnapshot,
subscribe(listener: () => void) {
listeners.add(listener);
const unsubscribe = store.subscribe(listener);
return () => {
listeners.delete(listener);
unsubscribe();
};
},
setActive: store.setActive,
retry: store.retry,
withdraw: (messageId: string, options?: { optimistic?: boolean }) =>
command(messageId, async (client) => {
if (options?.optimistic) {
const overlay = optimisticRemoveAgentQueueItem(client, agentId, messageId);
try {
const result = await client.withdrawAgentQueueItem(agentId, messageId);
if (result.withdrawn) overlay.commit();
else overlay.rollback();
return result;
} catch (error) {
overlay.rollback();
throw error;
}
}
const result = await client.withdrawAgentQueueItem(agentId, messageId);
// The host confirmed the removal. Hide the row now so it is not pressable again
// between this answer and the next update.
if (result.withdrawn) optimisticRemoveAgentQueueItem(client, agentId, messageId).commit();
return result;
}),
promote: (messageId: string, activeTurnBehavior: ActiveTurnBehavior) =>
command(messageId, async (client) => {
const overlay = optimisticPromoteAgentQueueItem(client, agentId, messageId);
try {
const result = await client.promoteAgentQueueItem(agentId, messageId, activeTurnBehavior);
if (result.promoted) overlay.commit();
else overlay.rollback();
return result;
} catch (error) {
overlay.rollback();
throw error;
}
}),
};
}
function mergeSets(left: ReadonlySet<string>, right: ReadonlySet<string>): ReadonlySet<string> {
if (left.size === 0) return right;
if (right.size === 0) return left;
const merged = new Set(left);
for (const value of right) merged.add(value);
return merged;
}
export type AgentQueueModel = ReturnType<typeof createAgentQueueModel>;
+89
View File
@@ -0,0 +1,89 @@
import {
AgentQueueCollection,
type CollectionState,
type PaseoAgentQueueItem,
type SyncOptimisticHandle,
} from "@getpaseo/client";
import type { SyncClient } from "@/sync";
type QueueCollectionState = CollectionState<PaseoAgentQueueItem, { held: boolean }>;
function buildQueueState(
byId: Map<string, PaseoAgentQueueItem>,
meta: { held: boolean },
): QueueCollectionState {
const items = Array.from(byId.values());
if (AgentQueueCollection.compare) items.sort(AgentQueueCollection.compare);
return { items, byId, meta };
}
/**
* Shows a newly queued message immediately in FIFO order and clears any paused banner until the
* host confirms or rejects the send.
*/
export function optimisticEnqueueAgentMessage(
client: Pick<SyncClient, "sync">,
agentId: string,
item: Omit<PaseoAgentQueueItem, "seq">,
): SyncOptimisticHandle {
return client.sync(AgentQueueCollection, { agentId }).optimistic({
key: item.id,
apply: (state) => {
if (state?.byId.has(item.id)) return state;
let maxSeq = 0;
if (state) {
for (const existing of state.items) {
if (existing.seq > maxSeq) maxSeq = existing.seq;
}
}
const byId = new Map(state?.byId);
byId.set(item.id, { ...item, seq: maxSeq + 1 });
return buildQueueState(byId, { held: false });
},
settled: (authoritative) => authoritative.byId.has(item.id),
});
}
/** Hides a withdrawn or cancelled row until the host update removes it. */
export function optimisticRemoveAgentQueueItem(
client: Pick<SyncClient, "sync">,
agentId: string,
messageId: string,
): SyncOptimisticHandle {
return client.sync(AgentQueueCollection, { agentId }).optimistic({
apply: (state) => {
if (!state || !state.byId.has(messageId)) return state;
const byId = new Map(state.byId);
byId.delete(messageId);
return {
items: state.items.filter((item) => item.id !== messageId),
byId,
meta: state.meta,
};
},
settled: (authoritative) => !authoritative.byId.has(messageId),
});
}
/** Marks a promoted row dispatching and clears any paused banner while the host dispatches it. */
export function optimisticPromoteAgentQueueItem(
client: Pick<SyncClient, "sync">,
agentId: string,
messageId: string,
): SyncOptimisticHandle {
return client.sync(AgentQueueCollection, { agentId }).optimistic({
apply: (state) => {
if (!state) return state;
const existing = state.byId.get(messageId);
if (!existing) return state;
if (existing.state === "dispatching" && !state.meta.held) return state;
const byId = new Map(state.byId);
byId.set(messageId, { ...existing, state: "dispatching", held: false });
return buildQueueState(byId, { held: false });
},
settled: (authoritative) => {
const item = authoritative.byId.get(messageId);
return !item || item.state === "dispatching";
},
});
}
@@ -56,6 +56,7 @@ export function ChatFind({
agentId,
serverId,
epoch,
rewindSeq,
items,
viewportRef,
revealLoadedMessage,
@@ -95,8 +96,8 @@ export function ChatFind({
);
const state = useSyncExternalStore(model.subscribe, model.getSnapshot, model.getSnapshot);
useEffect(() => {
model.updateHistory(epoch, items);
}, [model, epoch, items]);
model.updateHistory(epoch, items, rewindSeq);
}, [model, epoch, items, rewindSeq]);
useEffect(() => () => model.close(), [model]);
useEffect(() => {
if (!active) model.close();
@@ -18,7 +18,7 @@ function message(seq: number, text = "target"): StreamItem {
kind: "assistant_message",
text,
timestamp: new Date(0),
timelineCursor: { epoch: "epoch", seq },
timelineCursor: { epoch: "epoch", seq, anchorSeq: seq },
};
}
@@ -39,7 +39,7 @@ it("loads an older location and searches a response merged across suppressed tas
source.map((item, index) => ({
event: { type: "timeline" as const, provider: "claude" as const, item },
timestamp: new Date(0),
timelineCursor: { epoch: "epoch", seq: index + 1 },
timelineCursor: { epoch: "epoch", seq: index + 1, anchorSeq: index + 1 },
})),
{ source: "canonical" },
);
@@ -55,7 +55,7 @@ it("loads an older location and searches a response merged across suppressed tas
},
async load(_epoch, seq) {
loaded.push(seq);
model.updateHistory("epoch", history);
model.updateHistory("epoch", history, null);
},
async reveal(_id, _query, occurrence) {
revealed.push(occurrence);
@@ -64,7 +64,7 @@ it("loads an older location and searches a response merged across suppressed tas
clear() {},
});
try {
model.updateHistory("epoch", []);
model.updateHistory("epoch", [], null);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
@@ -99,7 +99,7 @@ it("skips a source-only candidate and highlights a displayed match", async () =>
clear() {},
});
try {
model.updateHistory("epoch", [message(1), message(2)]);
model.updateHistory("epoch", [message(1), message(2)], null);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().selectedItemId).toBe("row-2");
@@ -129,7 +129,7 @@ it("ignores replies after closing and does not navigate", async () => {
},
clear() {},
});
model.updateHistory("epoch", [message(1)]);
model.updateHistory("epoch", [message(1)], null);
model.open();
model.setQuery("target");
await expect.poll(() => calls).toEqual(["search"]);
@@ -155,7 +155,7 @@ it("retains a failed search for retry and distinguishes failure from zero matche
};
const model = new ChatFindModel(operations);
try {
model.updateHistory("epoch", []);
model.updateHistory("epoch", [], null);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().phase).toBe("error");
@@ -185,7 +185,7 @@ it("reports a failed timeline load as a connection failure", async () => {
clear() {},
});
try {
model.updateHistory("epoch", []);
model.updateHistory("epoch", [], null);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().phase).toBe("error");
@@ -207,24 +207,160 @@ it("reports a search result that outlived its epoch as a changed history", async
clear() {},
});
try {
model.updateHistory("epoch", [message(1)]);
model.updateHistory("epoch", [message(1)], null);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
model.updateHistory("epoch-2", [message(1)]);
model.updateHistory("epoch-2", [message(1)], null);
expect(model.getSnapshot()).toMatchObject({ phase: "error", failure: "historyChanged" });
} finally {
model.close();
}
});
it("reports results that a rewind took messages from as a changed history", async () => {
const model = new ChatFindModel({
async search() {
return response([{ seq: 2, role: "assistant" }]);
},
async load() {},
async reveal() {
return { count: 1, occurrence: 0 };
},
clear() {},
});
try {
model.updateHistory("epoch", [message(1), message(2)], null);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
expect(model.getSnapshot()).toMatchObject({ selectedItemId: "row-2", count: 1 });
// Another client rewinds the turn holding the match; the epoch stays.
model.updateHistory("epoch", [message(1)], 3);
expect(model.getSnapshot()).toMatchObject({
phase: "error",
failure: "historyChanged",
selectedItemId: null,
});
} finally {
model.close();
}
});
it("stops a search still receiving pages when a rewind lands between them", async () => {
let pages = 0;
let releaseSecondPage!: () => void;
const secondPage = new Promise<void>((resolve) => {
releaseSecondPage = resolve;
});
const model = new ChatFindModel({
async search(_query, cursor) {
pages += 1;
if (cursor === undefined)
return { ...response([{ seq: 2, role: "assistant" }]), nextCursor: 2 };
await secondPage;
return response([{ seq: 1, role: "assistant" }]);
},
async load() {},
async reveal() {
return { count: 1, occurrence: 0 };
},
clear() {},
});
try {
model.updateHistory("epoch", [message(1), message(2)], null);
model.open();
model.setQuery("target");
await expect.poll(() => pages).toBe(2);
model.updateHistory("epoch", [message(1)], 3);
releaseSecondPage();
await expect.poll(() => model.getSnapshot().failure).toBe("historyChanged");
expect(model.getSnapshot()).toMatchObject({ phase: "error", selectedItemId: null });
} finally {
model.close();
}
});
it.each([
["Next", "next"],
["Previous", "previous"],
] as const)("reports a rewind after %s as a changed history", async (_label, step) => {
const model = new ChatFindModel({
async search() {
return response([
{ seq: 1, role: "assistant" },
{ seq: 2, role: "assistant" },
]);
},
async load() {},
async reveal() {
return { count: 1, occurrence: 0 };
},
clear() {},
});
try {
model.updateHistory("epoch", [message(1), message(2)], null);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
model[step]();
await expect.poll(() => model.getSnapshot().selectedItemId).toBe("row-2");
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
model.updateHistory("epoch", [message(1)], 3);
expect(model.getSnapshot()).toMatchObject({
phase: "error",
failure: "historyChanged",
selectedItemId: null,
});
} finally {
model.close();
}
});
it("stops a pending Next when a rewind lands before it reveals", async () => {
let reveals = 0;
let revealSecond!: () => void;
const secondReveal = new Promise<void>((resolve) => {
revealSecond = resolve;
});
const model = new ChatFindModel({
async search() {
return response([
{ seq: 1, role: "assistant" },
{ seq: 2, role: "assistant" },
]);
},
async load() {},
async reveal() {
reveals += 1;
if (reveals > 1) await secondReveal;
return { count: 1, occurrence: 0 };
},
clear() {},
});
try {
model.updateHistory("epoch", [message(1), message(2)], null);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
model.next();
await expect.poll(() => reveals).toBe(2);
model.updateHistory("epoch", [message(1)], 3);
revealSecond();
await expect.poll(() => model.getSnapshot().failure).toBe("historyChanged");
expect(model.getSnapshot()).toMatchObject({ phase: "error", selectedItemId: null });
} finally {
model.close();
}
});
it("can load a search location before the initial chat history has arrived", async () => {
const model = new ChatFindModel({
async search() {
return response([{ seq: 1, role: "assistant" }]);
},
async load() {
model.updateHistory("epoch", [message(1)]);
model.updateHistory("epoch", [message(1)], null);
},
async reveal() {
return { count: 1, occurrence: 0 };
@@ -232,7 +368,7 @@ it("can load a search location before the initial chat history has arrived", asy
clear() {},
});
try {
model.updateHistory(null, []);
model.updateHistory(null, [], null);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
@@ -260,7 +396,7 @@ it("reports the position across the whole chat and corrects it with rendered cou
clear() {},
});
try {
model.updateHistory("epoch", [message(1), message(2)]);
model.updateHistory("epoch", [message(1), message(2)], null);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
@@ -297,7 +433,7 @@ it("counts one match per message from a host that reports no counts", async () =
clear() {},
});
try {
model.updateHistory("epoch", [message(1), message(2)]);
model.updateHistory("epoch", [message(1), message(2)], null);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
@@ -76,6 +76,10 @@ export class ChatFindModel {
private items: StreamItem[] = [];
private epoch: string | null = null;
private resultEpoch: string | null = null;
/** The latest rewind applied to the history. A rewind keeps the epoch and retires messages. */
private rewindSeq: number | null = null;
/** The latest rewind when the current result set's search started; undefined until a search starts. */
private searchedRewindSeq: number | null | undefined = undefined;
private locations: Location[] = [];
private resolved = new Map<Location, Target>();
private current = -1;
@@ -113,6 +117,7 @@ export class ChatFindModel {
this.cancel();
this.locations = [];
this.resultEpoch = null;
this.searchedRewindSeq = undefined;
this.resolved.clear();
this.current = -1;
this.inMessage = { occurrence: 0, count: 0 };
@@ -144,6 +149,7 @@ export class ChatFindModel {
});
}
private async search(signal: AbortSignal) {
this.searchedRewindSeq = this.rewindSeq;
try {
let cursor: number | undefined;
do {
@@ -168,15 +174,14 @@ export class ChatFindModel {
this.fail(error, signal);
}
}
updateHistory(epoch: string | null, items: StreamItem[]) {
if (
this.resultEpoch !== null &&
epoch !== null &&
epoch !== this.resultEpoch &&
this.state.open
) {
/** `rewindSeq` is the sequence number of the latest rewind applied to this history. */
updateHistory(epoch: string | null, items: StreamItem[], rewindSeq: number | null) {
const replaced = this.resultEpoch !== null && epoch !== null && epoch !== this.resultEpoch;
const rewound = this.searchedRewindSeq !== undefined && rewindSeq !== this.searchedRewindSeq;
if ((replaced || rewound) && this.state.open) {
this.fail(new ChatFindFailureError("historyChanged"), this.abort.signal);
}
this.rewindSeq = rewindSeq;
this.epoch = epoch;
this.items = items;
this.historyListeners.forEach((listener) => listener());
@@ -9,6 +9,8 @@ export interface ChatFindProps {
agentId: string;
serverId: string;
epoch: string | null;
/** The sequence number of the latest rewind applied to this history, if any. */
rewindSeq: number | null;
items: StreamItem[];
viewportRef: RefObject<StreamViewportHandle | null>;
revealLoadedMessage(messageId: string): boolean;
@@ -139,7 +139,7 @@ describe("useChatOutline", () => {
kind: "user_message",
text: "live prompt",
timestamp: new Date(seq),
timelineCursor: { epoch: "epoch-1", seq },
timelineCursor: { epoch: "epoch-1", seq, anchorSeq: seq },
});
rerender({ tail: [loadedPrompt(2)] });
await waitFor(() => expect(runtime.listAgentTimelinePrompts).toHaveBeenCalledTimes(2));
@@ -198,7 +198,7 @@ describe("useChatOutline", () => {
kind: "assistant_message",
text: "chunk",
timestamp: new Date(),
timelineCursor: { epoch: "epoch-1", seq: 2 },
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 2 },
},
],
timelineEpoch: "epoch-1",
@@ -219,7 +219,7 @@ describe("useChatOutline", () => {
kind: "user_message",
text: "Replaced conversation",
timestamp: new Date(2),
timelineCursor: { epoch: "epoch-2", seq: 1 },
timelineCursor: { epoch: "epoch-2", seq: 1, anchorSeq: 1 },
},
],
timelineEpoch: "epoch-2",
@@ -275,7 +275,7 @@ describe("useChatOutline", () => {
kind: "user_message" as const,
text: "prompt",
timestamp: new Date(1),
timelineCursor: { epoch: "epoch-1", seq: 1 },
timelineCursor: { epoch: "epoch-1", seq: 1, anchorSeq: 1 },
},
];
const { result, rerender } = renderHook(
@@ -326,7 +326,7 @@ describe("useChatOutline", () => {
kind: "user_message" as const,
text: "prompt",
timestamp: new Date(1),
timelineCursor: { epoch: "epoch-1", seq: 1 },
timelineCursor: { epoch: "epoch-1", seq: 1, anchorSeq: 1 },
};
const { result, rerender } = renderHook(
({ tail, mountedHistoryMessageIds }) =>
@@ -381,7 +381,7 @@ describe("useChatOutline", () => {
kind: "user_message" as const,
text: "prompt",
timestamp: new Date(2),
timelineCursor: { epoch: "epoch-1", seq: 2 },
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 2 },
};
const revealLoadedMessage = vi.fn();
revealLoadedMessage.mockReturnValue(false);
@@ -58,7 +58,11 @@ function installProbe(
return function() {};
} };
})`;
const evaluated = runPluginClientBundle("probe-plugin", clientBundle, runtime);
const evaluated = runPluginClientBundle(
{ serverId: "test-host", pluginId: "probe-plugin" },
clientBundle,
runtime,
);
return {
...evaluated,
serverId: "host-1",
@@ -322,7 +326,7 @@ describe("stream presentation through installed plugins", () => {
const source = harness.source();
const live = source.head[0];
if (live?.kind !== "assistant_message") throw new Error("Expected a live assistant message");
const canonical = { ...live, timelineCursor: { epoch: "epoch-1", seq: 42 } };
const canonical = { ...live, timelineCursor: { epoch: "epoch-1", seq: 42, anchorSeq: 42 } };
const present = createStreamPresentation();
present({ ...presentationOptions, tail: [], head: [live], transform: undefined });
const repointed = rows(
@@ -332,7 +336,7 @@ describe("stream presentation through installed plugins", () => {
{
id: streamed[0]!.id,
text: "Streamed answer",
timelineCursor: { epoch: "epoch-1", seq: 42 },
timelineCursor: { epoch: "epoch-1", seq: 42, anchorSeq: 42 },
},
]);
});
@@ -519,7 +523,7 @@ describe("timeline presentation", () => {
messageId: "provider-message",
clientMessageId: "client-message",
turnId: "turn-1",
timelineCursor: { epoch: "epoch", seq: 12 },
timelineCursor: { epoch: "epoch", seq: 12, anchorSeq: 12 },
});
const presentMessage = () =>
present({
@@ -166,4 +166,92 @@ describe("reading anchor", () => {
),
).toBe(0);
});
it("transfers ownership to the next visible row and compensates simultaneous growth above when the anchor is hidden", () => {
const anchor = createReadingAnchor();
const initial = [
{ id: "above", top: 0, height: 500 },
{ id: "plugin", top: 500, height: 24 },
{ id: "next", top: 524, height: 200 },
];
anchor.reconcile(500, initial);
expect(anchor.getRowId()).toBe("plugin");
// In one layout commit, "plugin" is hidden and "above" grows by 80px.
const nextRows = [
{ id: "above", top: 0, height: 580 },
{ id: "next", top: 580, height: 200 },
];
expect(anchor.reconcile(500, nextRows, false, undefined, new Set(["plugin"]))).toBe(580);
expect(anchor.getRowId()).toBe("next");
});
it("preserves top margin and avoids overshooting when hiding a tall or top-inset anchor", () => {
const topInsetAnchor = createReadingAnchor();
topInsetAnchor.reconcile(0, [
{ id: "plugin", top: 48, height: 40 },
{ id: "next", top: 88, height: 100 },
]);
expect(
topInsetAnchor.reconcile(
0,
[{ id: "next", top: 48, height: 100 }],
false,
undefined,
new Set(["plugin"]),
),
).toBe(0);
expect(topInsetAnchor.getRowId()).toBe("next");
const tallAnchor = createReadingAnchor();
tallAnchor.reconcile(650, [
{ id: "above", top: 0, height: 500 },
{ id: "tall-plugin", top: 500, height: 300 },
{ id: "next", top: 800, height: 100 },
]);
expect(
tallAnchor.reconcile(
650,
[
{ id: "above", top: 0, height: 580 },
{ id: "next", top: 580, height: 100 },
],
false,
undefined,
new Set(["tall-plugin"]),
),
).toBe(580);
expect(tallAnchor.getRowId()).toBe("next");
});
it("falls back to the preceding visible row when the hidden anchor was the last row", () => {
const anchor = createReadingAnchor();
anchor.reconcile(500, [
{ id: "above", top: 0, height: 300 },
{ id: "prev", top: 300, height: 200 },
{ id: "last-plugin", top: 500, height: 40 },
]);
expect(anchor.getRowId()).toBe("last-plugin");
expect(
anchor.reconcile(
500,
[
{ id: "above", top: 0, height: 380 },
{ id: "prev", top: 380, height: 200 },
],
false,
undefined,
new Set(["last-plugin"]),
),
).toBe(580);
expect(anchor.getRowId()).toBe("prev");
});
it("still retains an unmounted virtual anchor when it is not marked hidden", () => {
const anchor = createReadingAnchor();
anchor.reconcile(600, rows);
expect(anchor.reconcile(600, [rows[2]!], false, undefined, new Set(["other"]))).toBe(600);
expect(anchor.getRowId()).toBe("reading");
});
});
@@ -16,6 +16,48 @@ export interface ReadingRowReplacements {
}
const NO_REPLACEMENTS: ReadingRowReplacements = new Map();
function findHiddenAnchorReplacement(input: {
previousGeometry: readonly RowGeometry[];
rows: readonly RowGeometry[];
anchorId: string;
originalAnchorId: string;
baseScrollTop: number;
}): { row: RowGeometry; correctedTop: number } | null {
const { previousGeometry, rows, anchorId, originalAnchorId, baseScrollTop } = input;
const oldIndex = previousGeometry.findIndex(
(row) => row.id === anchorId || row.id === originalAnchorId,
);
const oldAnchor = oldIndex >= 0 ? previousGeometry[oldIndex] : undefined;
if (!oldAnchor) {
return null;
}
const rowsById = new Map(rows.map((row) => [row.id, row]));
for (let index = oldIndex + 1; index < previousGeometry.length; index += 1) {
const candidate = rowsById.get(previousGeometry[index]!.id);
if (!candidate) continue;
return {
row: candidate,
correctedTop: Math.max(
0,
Math.min(baseScrollTop, oldAnchor.top) + (candidate.top - oldAnchor.top),
),
};
}
for (let index = oldIndex - 1; index >= 0; index -= 1) {
const oldPrev = previousGeometry[index]!;
const candidate = rowsById.get(oldPrev.id);
if (!candidate) continue;
return {
row: candidate,
correctedTop: Math.max(
0,
baseScrollTop + (candidate.top + candidate.height) - (oldPrev.top + oldPrev.height),
),
};
}
return null;
}
// Content coordinates survive user scrolling. Layout commits replace the geometry;
// scroll events reuse it, without another DOM measurement pass.
export function createReadingAnchor() {
@@ -64,12 +106,31 @@ export function createReadingAnchor() {
rows: readonly RowGeometry[],
userScrolled = false,
replacements = NO_REPLACEMENTS,
hiddenRowIds?: ReadonlySet<string>,
): number {
const previousGeometry = geometry;
geometry = rows;
const previous = anchor && rows.find((row) => row.id === getRowId(replacements));
// The first virtualized commit can precede its mounted range. Keep the
// pinned reader until it mounts, rather than adopting an unrelated row.
if (anchor && !previous && !userScrolled) return scrollTop;
const anchorId = getRowId(replacements);
const previous = anchor && rows.find((row) => row.id === anchorId);
if (anchor && !previous && !userScrolled) {
// The first virtualized commit can precede its mounted range. Keep the
// pinned reader until it mounts, rather than adopting an unrelated row.
if (!anchorId || !hiddenRowIds?.has(anchorId)) return scrollTop;
const replacement = findHiddenAnchorReplacement({
previousGeometry,
rows,
anchorId,
originalAnchorId: anchor.id,
baseScrollTop: anchor.pinnedScrollTop ?? scrollTop,
});
if (replacement) {
anchor = anchorTop(replacement.row);
return replacement.correctedTop;
}
const fallback = readingRow(scrollTop);
anchor = fallback ? anchorTop(fallback) : null;
return scrollTop;
}
const correctedTop = project(scrollTop, previous ?? undefined, replacements);
// A prepend can expose the bottom of an estimated row above the reader.
// Do not transfer ownership to it until the user moves the reading position.
@@ -26,7 +26,6 @@ import {
} from "@legendapp/list/react-native";
import { withUnistyles } from "react-native-unistyles";
import { LoadingSpinner } from "@/components/ui/loading-spinner";
import { LoadingState } from "@/components/ui/loading-state";
import { Button } from "@/components/ui/button";
import { useRetainedPanelActive } from "@/components/retained-panel";
import { useNativeSplashHold } from "@/native-splash";
@@ -123,15 +122,6 @@ function distanceFromEnd(input: {
return Math.max(0, input.contentHeight - input.viewportHeight - input.offsetY);
}
const viewportStyle: ViewStyle = { flex: 1 };
const initialFillStyle: ViewStyle = {
position: "absolute",
top: 0,
right: 0,
bottom: 0,
left: 0,
alignItems: "center",
justifyContent: "center",
};
function keyExtractor(item: { id: string }): string {
return item.id;
@@ -159,6 +149,7 @@ function NativeStreamViewport(props: StreamRenderInput & { strategy: StreamStrat
isAuthoritativeHistoryReady,
isInitialHistoryLoading,
revealInitialHistory,
onInitialHistoryVisibilityChange,
onNearBottomChange,
onNearHistoryStart,
isLoadingOlderHistory,
@@ -265,6 +256,12 @@ function NativeStreamViewport(props: StreamRenderInput & { strategy: StreamStrat
() => historyStartPagination.state.status === "settling",
);
const finishInitialFill = useStableEvent(() => historyStartPagination.reveal());
const reportInitialHistoryVisibility = useStableEvent((visible: boolean) => {
onInitialHistoryVisibilityChange?.(visible);
});
useLayoutEffect(() => {
reportInitialHistoryVisibility(historyStartPaginationState.visible);
}, [historyStartPaginationState.visible, reportInitialHistoryVisibility]);
const retryHistoryStart = useStableEvent(() => historyStartPagination.rearm());
const scheduleHistoryStartSettle = useStableEvent(() => {
let scheduler = historyStartSettleSchedulerRef.current;
@@ -811,11 +808,6 @@ function NativeStreamViewport(props: StreamRenderInput & { strategy: StreamStrat
{canExpandDrawDistance ? (
<InitialDrawDistanceExpansion schedule={drawDistanceExpansion.schedule} />
) : null}
{!historyStartPaginationState.visible ? (
<View pointerEvents="none" style={initialFillStyle}>
<LoadingState testID="agent-initial-fill" title={t("agentPanel.states.loadingHistory")} />
</View>
) : null}
</View>
);
}

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