Compare commits

..
Author SHA1 Message Date
Mohamed Boudra d71ac161e8 fix(app): stop Cmd/Ctrl+click from entering sidebar select mode
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-11-30 17:56:44 +01: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
284 changed files with 9215 additions and 16013 deletions
+1
View File
@@ -58,6 +58,7 @@ At the start of non-trivial work, list `docs/` and skim anything relevant to the
| [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 |
+13 -79
View File
@@ -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. 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.
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.
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,64 +170,33 @@ 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.
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.
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.
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. 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.
accepts; rejected dispatch removes only the candidate. 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. 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;
in between. 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 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.
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.
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
@@ -428,41 +397,6 @@ 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`.
+7 -7
View File
@@ -60,9 +60,6 @@ $PASEO_HOME/
│ └── {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
@@ -252,7 +249,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
@@ -354,12 +352,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
@@ -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](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".
- **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".
- **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).
+2 -2
View File
@@ -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.
@@ -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"
}
}
+82
View File
@@ -0,0 +1,82 @@
# 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()` decides whether an indicator may move: not under reduced motion, not in a
retained panel that is not showing, not while the app is in the background. An indicator that may
not move draws its resting frame and runs nothing. Ask this hook; do not read reduced motion or
visibility yourself.
- 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.
## 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. A stepped animation sets `easing: "step-end"` on each
keyframe; 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 decay that never slows, at one unit per
millisecond, is the time since it started. Decay is the one native-driven animation that computes
its value from the frame timestamp instead of replaying a 60 fps recording, so it is exact at any
refresh rate and needs no loop restart. `Animated.modulo` and `interpolate` turn the clock into a
rotation or a translation, all inside the native driver.
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, aligned to wall-clock step boundaries, 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 and every loader shows 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 cadence, 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. The UI thread (`sh.paseo.debug`) is the one a
regression shows up on; `RenderThread` draws 60 frames a second whenever a ring or a shimmer is on
screen, and that part is the cost of the motion itself.
@@ -18,7 +18,6 @@ import {
expectComposerVisible,
cancelAgent,
composerLocator,
configureComposerInterruptSend,
expectQueuedMessageButton,
fillComposerDraft,
holdSendButton,
@@ -405,6 +404,15 @@ 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);
@@ -423,14 +431,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 submitMessage(page, prompt);
await page.getByRole("button", { name: "Send queued message now" }).click();
const promptRow = page.getByTestId("user-message").filter({ hasText: prompt });
await expect(promptRow).toBeVisible();
await gate.waitForServerMessage("send_agent_message_response");
@@ -651,14 +659,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 submitMessage(page, prompt);
await page.getByRole("button", { name: "Send queued message now" }).click();
const promptRow = page.getByTestId("user-message").filter({ hasText: prompt });
const replacementAnswer = page.getByText("(end of synthetic stream)", { exact: true }).last();
await expect(promptRow).toBeVisible();
@@ -1090,7 +1098,6 @@ 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,
@@ -1336,8 +1343,6 @@ 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);
@@ -1346,22 +1351,19 @@ test.describe("Agent message submission", () => {
).toHaveCount(0);
});
await test.step("tapping Send still steers and takes the queued row along", async () => {
await test.step("tapping Send still steers", 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(2);
const request = await gate.waitForRequest();
expect(request.text).toBe(steeredPrompt);
expect(request.activeTurnBehavior).toBe("steer");
gate.accept(1);
gate.accept();
await expect(
page.getByTestId("user-message").filter({ hasText: steeredPrompt }),
).toHaveCount(1);
await expect(page.getByRole("button", { name: "Send queued message now" })).toHaveCount(0);
await expect(
page.getByTestId("user-message").filter({ hasText: queuedPrompt }),
).toHaveCount(1);
await expectQueuedMessageButton(page);
});
} finally {
await agent.cleanup();
@@ -1378,21 +1380,26 @@ test.describe("Agent message submission", () => {
await replaySteeredSleepTurnInBrowser(page, testInfo, "codex");
});
test("restores the draft when queueing loses the connection", async ({ page }, testInfo) => {
test("restores overlapping queued sends when their connection fails", async ({
page,
}, testInfo) => {
test.setTimeout(120_000);
const gate = await gateNextAgentMessage(page);
const agent = await startRunningMockAgent(page, {
prefix: `queue-connection-lost-${testInfo.workerIndex}-`,
prefix: `overlapping-queued-send-${testInfo.workerIndex}-`,
model: "one-minute-stream",
prompt: "Keep the agent running while a message queues.",
prompt: "Keep the agent running while messages queue.",
});
const prompt = "Keep this draft if queueing fails.";
const prompts = ["Restore the first queued send.", "Restore the second queued send."];
try {
await fillComposerDraft(page, prompt);
await sendDraftToQueue(page);
await gate.waitForRequest();
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 gate.disconnect();
await expectFailedSubmissionRestored(page, prompt);
await expectQueuedSendFailuresRestored(page, prompts);
} finally {
await agent.cleanup();
}
@@ -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,320 +0,0 @@
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();
}
});
});
+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();
@@ -499,56 +499,6 @@ test.describe.serial("Provider switching in chat", () => {
}
});
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,
}) => {
@@ -0,0 +1,208 @@
import { writeFile } from "node:fs/promises";
import { test, expect } from "../support/fixtures";
import {
readReactRenders,
recordReactRenders,
resetReactRenders,
} from "../support/helpers/react-renders";
import {
captureLoaderSteps,
freezeAnimationsAt,
openQuietRunningTurn,
readAnimatingTargets,
readLoaderStep,
readRunningAnimations,
recordLoaderStepChanges,
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;
// 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("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();
}
});
});
@@ -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,
@@ -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);
@@ -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:
@@ -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,6 +1,5 @@
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");
@@ -15,7 +14,7 @@ export async function awaitToolCall(page: Page, toolName: string | RegExp): Prom
}
export async function expectAgentIdle(page: Page, timeout = 30_000): Promise<void> {
await expect(agentStopButton(page)).toHaveCount(0, { timeout });
await expect(page.getByRole("button", { name: /stop|cancel/i })).toHaveCount(0, { timeout });
}
// The working indicator is an animated spinner View — no semantic ARIA role, testId is correct.
@@ -1,141 +0,0 @@
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() };
}
+4 -13
View File
@@ -103,13 +103,8 @@ 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 = agentStopButton(page).first();
const stopButton = page.getByRole("button", { name: /stop|cancel/i }).first();
await expect(stopButton).toBeVisible({ timeout: 10_000 });
await stopButton.click();
}
@@ -305,7 +300,9 @@ export async function startRunningMockAgent(
await page.goto(agentUrl);
await expectComposerVisible(page);
await client.sendAgentMessage(agent.id, opts.prompt);
await expect(agentStopButton(page).first()).toBeVisible({ timeout: 30_000 });
await expect(page.getByRole("button", { name: /stop|cancel/i }).first()).toBeVisible({
timeout: 30_000,
});
return {
client,
repo,
@@ -470,12 +467,6 @@ 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.
*/
+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();
}
@@ -0,0 +1,198 @@
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;
}
}
/** 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,11 +168,6 @@ 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,
@@ -187,9 +182,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; pendingPermissions: Array<{ id: string }> };
} | null>;
fetchAgent(options: {
agentId: string;
}): Promise<{ agent: { id: string; archivedAt?: string | null } } | null>;
getLastServerInfoMessage(): {
features?: {
projectAdd?: boolean;
+1 -1
View File
@@ -519,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);
}
}
@@ -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);
},
};
}
@@ -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,
);
}
-15
View File
@@ -1,15 +0,0 @@
import { useActivatedStore } from "@/sync";
import { createAgentQueueModel, type AgentQueueModel, type AgentQueueSnapshot } from "./model";
export type { AgentQueueModel, AgentQueueSnapshot } from "./model";
/** 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 };
}
-165
View File
@@ -1,165 +0,0 @@
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();
const result = model.withdraw("a");
await daemon.publish("agent", queueOf("a", "b", "c"));
await result;
await daemon.settle();
expect(rowIds()).toEqual(["b", "c"]);
});
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);
});
-128
View File
@@ -1,128 +0,0 @@
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";
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 in flight. */
busy: ReadonlySet<string>;
}
/**
* One agent's queue as the host holds it. The host is the only writer: a command changes
* nothing here until the host answers it.
*/
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();
// Rows the host confirmed it removed. A later change to a row arrives as a new row object.
const withdrawn = new WeakSet<PaseoAgentQueueItem>();
let view: { source: unknown; snapshot: AgentQueueSnapshot } | null = null;
const listeners = new Set<() => void>();
const getSnapshot = (): AgentQueueSnapshot => {
const source = store.getSnapshot();
if (view?.source !== source) {
view = {
source,
snapshot: {
status: source.status,
held: source.data?.meta.held ?? false,
items: source.data?.items.filter((item) => !withdrawn.has(item)) ?? [],
busy,
},
};
}
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;
};
// The row as the host last sent it, which an update during a command may have replaced.
const hide = (messageId: string) => {
const row = store.getSnapshot().data?.items.find((entry) => entry.id === messageId);
if (row) withdrawn.add(row);
};
/** Runs one command per row at a time. Returns null when the row cannot take one. */
const command = async <T>(messageId: string, run: () => Promise<T>): Promise<T | null> => {
const row = getSnapshot().items.find((entry) => entry.id === messageId);
if (!row || row.state === "dispatching" || busy.has(messageId)) return null;
busy = new Set(busy).add(messageId);
changed();
try {
return await run();
} 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) =>
command(messageId, async () => {
const result = await connected().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) hide(messageId);
return result;
}),
promote: (messageId: string, activeTurnBehavior: ActiveTurnBehavior) =>
command(messageId, async () =>
connected().promoteAgentQueueItem(agentId, messageId, activeTurnBehavior),
),
};
}
export type AgentQueueModel = ReturnType<typeof createAgentQueueModel>;
@@ -954,6 +954,19 @@ it("keeps table cell pipes escaped in text/plain table syntax and literal in tex
expect(content?.html).toContain("<td>Value | detail</td>");
});
it("keeps a table cell's line breaks inside its row", () => {
const message = mountFixture();
message.innerHTML =
"<table><thead><tr><th>Name<br>label</th><th>Note</th></tr></thead><tbody><tr><td>first<br>second</td><td>&lt;br&gt; stays text</td></tr></tbody></table>";
const content = createAssistantSelectionClipboardContent(selectNodeContents(message));
expect(content?.plainText).toBe(
"| Name<br>label | Note |\n| --- | --- |\n| first<br>second | <br> stays text |",
);
expect(content?.html).toContain("<th>Name<br>\nlabel</th>");
expect(content?.html).toContain("<td>first<br>\nsecond</td>");
expect(content?.html).toContain("<td>&lt;br&gt; stays text</td>");
});
it("copies a workspace image path instead of its temporary display URL", () => {
const message = mountFixture();
const sources = JSON.stringify({ "blob:preview": "assets/chart.png" });
@@ -69,12 +69,13 @@ function createTurndown(flavor: "markdown" | "plain"): TurndownService {
});
turndown.use(gfm);
// text/plain still carries tables as GFM syntax, so a cell's pipe stays escaped there.
// A row is one line, so a cell's line break goes back to `<br>`.
turndown.addRule("escapedGfmTableCell", {
filter: ["th", "td"],
replacement: (content, node) => {
const index = node.parentNode ? Array.from(node.parentNode.childNodes).indexOf(node) : 0;
const prefix = index === 0 ? "| " : " ";
return `${prefix}${content.replace(/\|/g, "\\|")} |`;
return `${prefix}${content.replace(/\|/g, "\\|").replace(/ *\n/g, "<br>")} |`;
},
});
// A link Paseo recognized pastes as the text the reply showed. Rich paste keeps it as a
-2
View File
@@ -108,8 +108,6 @@ export type UserComposerAttachment =
| { kind: "file"; attachment: UploadedFileAttachment }
| WorkspaceFileComposerAttachment
| PluginResourceComposerAttachment
// An attachment taken back from a queued message. The host already holds it in wire form.
| { kind: "agent_attachment"; attachment: AgentAttachment }
| { kind: "forge_issue"; item: ForgeSearchItem }
| { kind: "forge_change_request"; item: ForgeSearchItem }
// COMPAT(githubAttachmentKinds): legacy persisted attachment kinds retained
@@ -131,18 +131,13 @@ export function AttachmentLabel({ icon, title, subtitle }: AttachmentLabelProps)
);
}
/** Holds a thumbnail's space while its image loads. */
export function AttachmentThumbnailPlaceholder() {
return <View style={styles.thumbnailPlaceholder} />;
}
/** Square image preview pill body. */
export function AttachmentThumbnail({ metadata }: { metadata: AttachmentMetadata }) {
const preview = useAttachmentPreviewUrl(metadata);
const uri = preview.status === "ready" ? preview.url : null;
const source = useMemo(() => (uri ? { uri } : null), [uri]);
if (!source) {
return <AttachmentThumbnailPlaceholder />;
return <View style={styles.thumbnailPlaceholder} />;
}
return <Image source={source} style={styles.thumbnail} />;
}
@@ -0,0 +1,60 @@
import { useEffect } from "react";
import { Animated } from "react-native";
// A decay that never slows is a clock: with a velocity of one unit per millisecond the value is the
// time since it started. Decay is the one native-driven animation that computes its value from the
// frame's timestamp instead of replaying a 60 fps recording, so the motion is exact at any refresh
// rate and never ends or loops.
const CLOCK_CONFIG = { velocity: 1, deceleration: 1 - 1e-12, useNativeDriver: true };
/**
* Milliseconds, counted on the UI thread by React Native's native animation driver.
*
* Views bound to it are updated by the native driver directly. Nothing reaches the JS thread, React
* does not render, and no shadow tree is committed — which is what a Reanimated shared value costs
* on every frame it changes.
*/
export interface IndicatorClock {
/** Where a cycle of `periodMs` currently is, as milliseconds into the cycle. */
cycle(periodMs: number): Animated.AnimatedModulo<number>;
/** Runs the clock until the returned function is called. It restarts from zero when idle. */
run(): () => void;
}
export function createIndicatorClock(): IndicatorClock {
const elapsedMs = new Animated.Value(0, { useNativeDriver: true });
let runners = 0;
let ticking: Animated.CompositeAnimation | null = null;
return {
cycle(periodMs) {
return Animated.modulo(elapsedMs, periodMs);
},
run() {
runners += 1;
if (!ticking) {
elapsedMs.setValue(0);
ticking = Animated.decay(elapsedMs, CLOCK_CONFIG);
ticking.start();
}
return () => {
runners -= 1;
if (runners === 0) {
ticking?.stop();
ticking = null;
}
};
},
};
}
/** One clock for indicators that must move as one, wherever they are on screen. */
export const sharedIndicatorClock = createIndicatorClock();
/** Runs the clock for as long as an indicator bound to it is moving. */
export function useRunningClock(clock: IndicatorClock, moving: boolean): void {
useEffect(() => {
if (!moving) return;
return clock.run();
}, [clock, moving]);
}
@@ -0,0 +1,49 @@
import { useSyncExternalStore } from "react";
import { AccessibilityInfo } from "react-native";
import { useReducedMotion as useReducedMotionAtLaunch } from "react-native-reanimated";
import { useRetainedPanelActive } from "@/components/retained-panel";
import { useAppVisible } from "@/hooks/use-app-visible";
// Reanimated knows the setting synchronously but only as it was at launch; React Native reports
// every later change but answers the first question asynchronously. Together they are right from
// the first render onwards.
let reducedMotionSinceLaunch: boolean | null = null;
const reducedMotionListeners = new Set<() => void>();
AccessibilityInfo.addEventListener("reduceMotionChanged", (reducedMotion) => {
reducedMotionSinceLaunch = reducedMotion;
for (const listener of reducedMotionListeners) listener();
});
function subscribeToReducedMotion(listener: () => void): () => void {
reducedMotionListeners.add(listener);
return () => reducedMotionListeners.delete(listener);
}
function getReducedMotionSinceLaunch(): boolean | null {
return reducedMotionSinceLaunch;
}
function useReducedMotion(): boolean {
const atLaunch = useReducedMotionAtLaunch();
const sinceLaunch = useSyncExternalStore(
subscribeToReducedMotion,
getReducedMotionSinceLaunch,
getReducedMotionSinceLaunch,
);
return sinceLaunch ?? atLaunch;
}
/**
* Whether a running indicator may move right now. It holds still when the system asks for reduced
* motion, and while nobody can see it: in a retained panel that is not showing, or in an app that
* is in the background.
*
* An indicator that is not moving draws its resting frame and runs nothing.
*/
export function useIndicatorMotion(): boolean {
const panelActive = useRetainedPanelActive();
const appVisible = useAppVisible();
const reducedMotion = useReducedMotion();
return panelActive && appVisible && !reducedMotion;
}
@@ -0,0 +1,50 @@
import { useLayoutEffect, useRef, type RefObject } from "react";
import type { View } from "react-native";
const TIMELINE_ORIGIN_MS = 0;
export interface IndicatorLoop {
/** One cycle. Keep the array's identity stable: a new array restarts the loop. */
keyframes: Keyframe[];
durationMs: number;
/**
* `shared` puts every instance at the same point of the cycle, wherever and whenever it mounted:
* the loop counts from the document timeline's origin instead of from its own start. `own` starts
* the cycle when the loop does.
*/
phase: "shared" | "own";
}
/**
* Repeats `loop` on the element the returned ref is attached to, for as long as `loop` is given.
*
* The browser's animation engine runs it. A loop over `transform` or `opacity` is carried by the
* compositor, so the page does no work per frame: no script, no style, no paint.
*
* It is declared through the Web Animations API, not a CSS `@keyframes` rule, on purpose. A CSS
* animation fires `animationiteration`, React listens for that event at the root, and a document
* with a listener for it makes Chromium bring the main thread up around the end of every cycle of
* every CSS animation. A script-declared animation has no such event and never wakes it.
*/
export function useIndicatorLoop(loop: IndicatorLoop | null): RefObject<View | null> {
const target = useRef<View | null>(null);
useLayoutEffect(() => {
const element: unknown = target.current;
if (!loop || !(element instanceof HTMLElement)) {
return;
}
const animation = element.animate(loop.keyframes, {
duration: loop.durationMs,
iterations: Number.POSITIVE_INFINITY,
});
// An explicit start also keeps loops that start in the same commit exactly together.
animation.startTime =
loop.phase === "shared" ? TIMELINE_ORIGIN_MS : document.timeline.currentTime;
return () => {
animation.cancel();
};
}, [loop]);
return target;
}
@@ -0,0 +1,140 @@
import { memo, useMemo, useState } from "react";
import { Animated, StyleSheet, Text, View } from "react-native";
import MaskedView from "@react-native-masked-view/masked-view";
import Svg, { Defs, Rect, Stop, LinearGradient as SvgLinearGradient } from "react-native-svg";
import { useIndicatorMotion } from "@/components/indicator-motion";
import { createIndicatorClock, useRunningClock } from "@/components/indicator-motion/clock";
import { type LabelShimmerProps, getRowSweep, getShimmerDurationMs } from "./sweep";
export { useLabelMeasurements } from "./measurements";
const MASK_TEXT = { color: "#000000", opacity: 1 };
// Plain React Native styles: the band is an `Animated.View` the native animation driver writes to,
// and a theme-tracked style on the same node gives it two writers. See docs/unistyles.md.
const styles = StyleSheet.create({
overlay: {
position: "absolute",
top: 0,
right: 0,
bottom: 0,
left: 0,
flexDirection: "row",
alignItems: "center",
overflow: "hidden",
},
track: {
position: "absolute",
top: 0,
right: 0,
bottom: 0,
left: 0,
overflow: "hidden",
},
maskRow: {
flexDirection: "row",
alignItems: "center",
},
band: {
position: "absolute",
top: 0,
bottom: 0,
left: 0,
},
spacer: {
flex: 1,
},
});
/**
* Native label shimmer: a gradient band slides behind a mask cut in the shape of the label. The
* native animation driver moves the band; see `indicator-motion/clock.ts`. Each shimmer has its own
* clock so the highlight enters from the left when the label appears.
*/
export const LabelShimmer = memo(function LabelShimmer({
label,
secondaryLabel,
labelStyle,
secondaryLabelStyle,
measurements,
}: LabelShimmerProps) {
const { rowSize } = measurements;
const measured = rowSize.width > 0 && rowSize.height > 0;
const moving = useIndicatorMotion() && measured;
const [clock] = useState(createIndicatorClock);
const [gradientId] = useState(
() => `shimmer-gradient-${Math.random().toString(36).substring(2, 9)}`,
);
useRunningClock(clock, moving);
const durationMs = getShimmerDurationMs(label, secondaryLabel);
const { peakWidth, fromX, toX } = getRowSweep(rowSize.width);
const { width, height } = rowSize;
const trackStyle = useMemo(() => [styles.track, { width, height }], [height, width]);
const bandStyle = useMemo(
() => [
styles.band,
{ width: peakWidth, height },
{
transform: [
{
translateX: clock.cycle(durationMs).interpolate({
inputRange: [0, durationMs],
outputRange: [fromX, toX],
}),
},
],
},
],
[clock, durationMs, fromX, height, peakWidth, toX],
);
const maskElement = useMemo(
() => (
<View pointerEvents="none" style={[styles.maskRow, { width, height }]}>
<Text style={[labelStyle, MASK_TEXT]} numberOfLines={1}>
{label}
</Text>
{secondaryLabel ? (
<Text style={[secondaryLabelStyle, MASK_TEXT]} numberOfLines={1}>
{secondaryLabel}
</Text>
) : (
<View style={styles.spacer} />
)}
</View>
),
[height, label, labelStyle, secondaryLabel, secondaryLabelStyle, width],
);
if (!moving) {
return null;
}
return (
<View style={styles.overlay} pointerEvents="none">
<MaskedView pointerEvents="none" style={trackStyle} maskElement={maskElement}>
<View pointerEvents="none" style={trackStyle}>
<Animated.View pointerEvents="none" style={bandStyle}>
<BandGradient id={gradientId} />
</Animated.View>
</View>
</MaskedView>
</View>
);
});
function BandGradient({ id }: { id: string }) {
return (
<Svg width="100%" height="100%" preserveAspectRatio="none">
<Defs>
<SvgLinearGradient id={id} x1="0%" y1="0%" x2="100%" y2="0%">
<Stop offset="0%" stopColor="#ffffff" stopOpacity={0} />
<Stop offset="50%" stopColor="#ffffff" stopOpacity={1} />
<Stop offset="100%" stopColor="#ffffff" stopOpacity={0} />
</SvgLinearGradient>
</Defs>
<Rect x="0" y="0" width="100%" height="100%" fill={`url(#${id})`} />
</Svg>
);
}
@@ -0,0 +1,116 @@
import { memo, useMemo } from "react";
import { Text, View, type TextStyle, type ViewStyle } from "react-native";
import { useIndicatorMotion } from "@/components/indicator-motion";
import { type IndicatorLoop, useIndicatorLoop } from "@/components/indicator-motion/loop.web";
import { type LabelShimmerProps, getShimmerDurationMs, getTextSweep } from "./sweep";
export { useLabelMeasurements } from "./measurements";
const BAND_GRADIENT =
"linear-gradient(90deg, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.45) 24%, #ffffff 40%, #ffffff 60%, rgba(255, 255, 255, 0.45) 76%, rgba(255, 255, 255, 0) 100%)";
// Solid white text. Filling the glyphs through a clipped background instead of colouring them keeps
// the rasteriser on the path the highlight has always been drawn with; plain white text is drawn
// measurably heavier.
const WHITE_TEXT = {
opacity: 1,
color: "transparent",
WebkitTextFillColor: "transparent",
backgroundColor: "#ffffff",
backgroundClip: "text",
WebkitBackgroundClip: "text",
} as TextStyle;
const FILL: ViewStyle = { position: "absolute", top: 0, right: 0, bottom: 0, left: 0 };
// React Native's style types do not know the CSS mask properties.
const overlayStyle: ViewStyle = { ...FILL, overflow: "hidden" };
// The window: the row, cut down by a mask to a band with soft edges.
const bandBaseStyle = {
...FILL,
maskImage: BAND_GRADIENT,
WebkitMaskImage: BAND_GRADIENT,
maskRepeat: "no-repeat",
WebkitMaskRepeat: "no-repeat",
} as ViewStyle;
// The white text seen through the window, laid out exactly over the label.
const textStyle: ViewStyle = { ...FILL, flexDirection: "row", alignItems: "center" };
const spacerStyle: ViewStyle = { flex: 1 };
function slide(fromX: number, toX: number, durationMs: number): IndicatorLoop {
return {
keyframes: [{ transform: `translateX(${fromX}px)` }, { transform: `translateX(${toX}px)` }],
durationMs,
phase: "own",
};
}
/**
* Web label shimmer. The window slides across the row while the text seen through it slides back by
* the same amount, and so stays where it is. Both are `transform` loops, so the browser's
* compositor moves two layers it has already painted; see `loop.web.ts`. Animating the highlight as
* a text-clipped background instead repaints the text on the main thread every frame.
*/
export const LabelShimmer = memo(function LabelShimmer({
label,
secondaryLabel,
labelStyle,
secondaryLabelStyle,
measurements,
}: LabelShimmerProps) {
const { labelSpan, secondarySpan } = measurements;
const moving = useIndicatorMotion();
const durationMs = getShimmerDurationMs(label, secondaryLabel);
const sweep = getTextSweep({ labelSpan, secondarySpan: secondaryLabel ? secondarySpan : null });
// Both loops change together, so they restart together and stay exactly opposed.
const bandLoop = useMemo(
() => (moving ? slide(sweep.fromX, sweep.toX, durationMs) : null),
[durationMs, moving, sweep.fromX, sweep.toX],
);
const textLoop = useMemo(
() => (moving ? slide(-sweep.fromX, -sweep.toX, durationMs) : null),
[durationMs, moving, sweep.fromX, sweep.toX],
);
const bandRef = useIndicatorLoop(bandLoop);
const textRef = useIndicatorLoop(textLoop);
const bandStyle = useMemo(
() => [
bandBaseStyle,
{
maskSize: `${sweep.peakWidth}px 100%`,
WebkitMaskSize: `${sweep.peakWidth}px 100%`,
} as ViewStyle,
],
[sweep.peakWidth],
);
const labelTextStyle = useMemo(() => [labelStyle, WHITE_TEXT], [labelStyle]);
const secondaryTextStyle = useMemo(
() => [secondaryLabelStyle, WHITE_TEXT],
[secondaryLabelStyle],
);
if (!moving) {
return null;
}
return (
<View style={overlayStyle} pointerEvents="none" testID="label-shimmer">
<View ref={bandRef} style={bandStyle}>
<View ref={textRef} style={textStyle}>
<Text style={labelTextStyle} numberOfLines={1}>
{label}
</Text>
{secondaryLabel ? (
<Text style={secondaryTextStyle} numberOfLines={1}>
{secondaryLabel}
</Text>
) : (
<View style={spacerStyle} />
)}
</View>
</View>
</View>
);
});
@@ -0,0 +1,67 @@
import { useCallback, useMemo, useState } from "react";
import type { LayoutChangeEvent } from "react-native";
import { isNative, isWeb } from "@/constants/platform";
import type { LabelMeasurements, LabelRowSize, LabelSpan } from "./sweep";
type LayoutHandler = (event: LayoutChangeEvent) => void;
export interface LabelMeasuring {
measurements: LabelMeasurements;
/** Attach each to its element's `onLayout`. One that is undefined needs no measuring. */
onRowLayout: LayoutHandler | undefined;
onLabelLayout: LayoutHandler | undefined;
onSecondaryLayout: LayoutHandler | undefined;
}
const UNMEASURED_ROW_SIZE: LabelRowSize = { width: 0, height: 0 };
const UNMEASURED_SPAN: LabelSpan = { x: 0, width: 0 };
// Layout reports sub-pixel noise; a measurement that moved less than half a pixel is the same one.
function isSameMeasurement(previous: number, next: number): boolean {
return Math.abs(previous - next) <= 0.5;
}
function isSameSpan(previous: LabelSpan, x: number, width: number): boolean {
return isSameMeasurement(previous.x, x) && isSameMeasurement(previous.width, width);
}
/**
* Measures a label row for its shimmer. The web highlight follows the two pieces of text; the
* native one crosses the whole row.
*/
export function useLabelMeasurements(shimmering: boolean): LabelMeasuring {
const [rowSize, setRowSize] = useState(UNMEASURED_ROW_SIZE);
const [labelSpan, setLabelSpan] = useState(UNMEASURED_SPAN);
const [secondarySpan, setSecondarySpan] = useState(UNMEASURED_SPAN);
const handleRowLayout = useCallback((event: LayoutChangeEvent) => {
const { width, height } = event.nativeEvent.layout;
setRowSize((previous) =>
isSameMeasurement(previous.width, width) && isSameMeasurement(previous.height, height)
? previous
: { width, height },
);
}, []);
const handleLabelLayout = useCallback((event: LayoutChangeEvent) => {
const { x, width } = event.nativeEvent.layout;
setLabelSpan((previous) => (isSameSpan(previous, x, width) ? previous : { x, width }));
}, []);
const handleSecondaryLayout = useCallback((event: LayoutChangeEvent) => {
const { x, width } = event.nativeEvent.layout;
setSecondarySpan((previous) => (isSameSpan(previous, x, width) ? previous : { x, width }));
}, []);
const measurements = useMemo(
() => ({ rowSize, labelSpan, secondarySpan }),
[rowSize, labelSpan, secondarySpan],
);
return {
measurements,
onRowLayout: isNative && shimmering ? handleRowLayout : undefined,
// React Native Web only observes a node when onLayout exists at mount. Measure while idle too,
// so a retained row has its dimensions when it starts shimmering.
onLabelLayout: isWeb ? handleLabelLayout : undefined,
onSecondaryLayout: isWeb ? handleSecondaryLayout : undefined,
};
}
@@ -0,0 +1,48 @@
import { describe, expect, test } from "vitest";
import { getRowSweep, getShimmerDurationMs, getTextSweep } from "./sweep";
describe("label shimmer sweep", () => {
test("takes longer on longer labels, between one and 2.3 seconds", () => {
expect(getShimmerDurationMs("Shell", "sleep 600")).toBeCloseTo(1362);
expect(getShimmerDurationMs("Read", undefined)).toBeCloseTo(1032);
expect(getShimmerDurationMs(" Edit ", " a.ts ")).toBe(getShimmerDurationMs("Edit", "a.ts"));
expect(getShimmerDurationMs("", undefined)).toBe(1000);
expect(getShimmerDurationMs("x".repeat(400), undefined)).toBe(2300);
});
test("crosses the text from one band width before the label to the end of the last text", () => {
const sweep = getTextSweep({
labelSpan: { x: 20, width: 36 },
secondarySpan: { x: 64, width: 400 },
});
expect(sweep.peakWidth).toBeCloseTo(97.68);
expect(sweep.fromX).toBeCloseTo(20 - 97.68);
expect(sweep.toX).toBe(464);
});
test("ends at the label when there is no secondary text", () => {
expect(getTextSweep({ labelSpan: { x: 20, width: 36 }, secondarySpan: null })).toEqual({
peakWidth: 42,
fromX: -22,
toX: 56,
});
});
test("keeps the band between 42 and 120 wide on text", () => {
const wide = getTextSweep({ labelSpan: { x: 0, width: 2000 }, secondarySpan: null });
const unmeasured = getTextSweep({ labelSpan: { x: 0, width: 0 }, secondarySpan: null });
expect(wide.peakWidth).toBe(120);
expect(unmeasured).toEqual({ peakWidth: 42, fromX: -42, toX: 0 });
});
test("crosses the whole row with one band width of run-in and run-out", () => {
const sweep = getRowSweep(300);
expect(sweep.peakWidth).toBeCloseTo(84);
expect(sweep.fromX).toBeCloseTo(-84);
expect(sweep.toX).toBeCloseTo(384);
expect(getRowSweep(50)).toEqual({ peakWidth: 32, fromX: -32, toX: 82 });
expect(getRowSweep(2000)).toEqual({ peakWidth: 120, fromX: -120, toX: 2120 });
});
});
@@ -0,0 +1,62 @@
import type { StyleProp, TextStyle } from "react-native";
/** Where a piece of text sits on the label row, as the row's layout reported it. */
export interface LabelSpan {
x: number;
width: number;
}
export interface LabelRowSize {
width: number;
height: number;
}
/** The row's measured geometry. A measurement that has not arrived yet is zero. */
export interface LabelMeasurements {
rowSize: LabelRowSize;
labelSpan: LabelSpan;
secondarySpan: LabelSpan;
}
export interface LabelShimmerProps {
label: string;
secondaryLabel?: string;
/** The row's own text styles: the highlight is set in the same type, at the same place. */
labelStyle: StyleProp<TextStyle>;
secondaryLabelStyle: StyleProp<TextStyle>;
measurements: LabelMeasurements;
}
/** One pass of the highlight: a band `peakWidth` wide whose left edge travels `fromX` to `toX`. */
export interface ShimmerSweep {
peakWidth: number;
fromX: number;
toX: number;
}
/** Longer labels take longer to cross, within limits, so the highlight's speed reads the same. */
export function getShimmerDurationMs(label: string, secondaryLabel: string | undefined): number {
const characters = label.trim().length + (secondaryLabel?.trim().length ?? 0);
const shortLabelAdjustment = characters <= 12 ? 0.25 : 0;
const seconds = Math.max(1, Math.min(2.3, 1.25 + characters * 0.008 - shortLabelAdjustment));
return seconds * 1000;
}
/** Sweeps the text itself: in from just left of the label, out at the end of the last text. */
export function getTextSweep(input: {
labelSpan: LabelSpan;
secondarySpan: LabelSpan | null;
}): ShimmerSweep {
const startX = input.labelSpan.x;
const endX = input.secondarySpan
? input.secondarySpan.x + input.secondarySpan.width
: input.labelSpan.x + input.labelSpan.width;
const peakWidth = Math.max(42, Math.min(120, Math.max(1, endX - startX) * 0.22));
return { peakWidth, fromX: startX - peakWidth, toX: endX };
}
/** Sweeps the whole row: in from just left of it, out just right of it. */
export function getRowSweep(rowWidth: number): ShimmerSweep {
const peakWidth = Math.max(32, Math.min(120, rowWidth * 0.28));
return { peakWidth, fromX: -peakWidth, toX: rowWidth + peakWidth };
}
+86 -2
View File
@@ -1,5 +1,7 @@
import { Parser } from "htmlparser2";
import { fromMarkdown } from "mdast-util-from-markdown";
import { gfmTableFromMarkdown } from "mdast-util-gfm-table";
import { gfmTable } from "micromark-extension-gfm-table";
import { decodeString } from "micromark-util-decode-string";
import type { Nodes } from "mdast";
@@ -53,6 +55,8 @@ export function normalizeMarkdownHtml(source: string): string {
} else if ("children" in node) node.children.forEach(protectCode);
}
protectCode(tree);
// Only `<br>` reads these, so a source without one skips the extra parse.
const tableRanges = /<br/i.test(source) ? collectTableRanges(source, codeRanges) : [];
const links: (string | undefined)[] = [];
let previousTag: { name: string; end: number } | null = null;
const convert = (raw: string, offset: number): string => {
@@ -84,7 +88,16 @@ export function normalizeMarkdownHtml(source: string): string {
: /^\s*$/.test(source.slice(0, offset));
previousTag = { name, end: offset + raw.length };
if (EMPHASIS[name]) return EMPHASIS[name];
const boundary = layoutBoundary(name, source, raw, offset, closing, startsAfterBoundary);
const inTable = tableRanges.some(({ start, end }) => offset >= start && offset < end);
const boundary = layoutBoundary(
name,
source,
raw,
offset,
closing,
startsAfterBoundary,
inTable,
);
if (boundary !== null) return boundary;
if (name === "a") return markdownAnchor(raw, closing, links);
if (name === "img" && !closing) {
@@ -167,8 +180,15 @@ function layoutBoundary(
offset: number,
closing: boolean,
startsAfterBoundary: boolean,
inTable: boolean,
): string | null {
if (name === "br") return closing ? "" : " \n";
// Inside GFM table cells, emit ` \u2028 ` so row boundaries stay intact while giving flanking
// emphasis/strikethrough delimiters and URLs/autolinks whitespace boundaries on both sides before
// the cell-scoped parser turns ` \u2028 ` back into a `LineBreak` node.
if (name === "br") {
if (closing) return "";
return inTable ? " \u2028 " : " \n";
}
if (name === "summary") return closing ? "**\n\n" : "**";
if (name === "details")
return (closing ? offset + raw.length === source.length : offset === 0) ? "" : "\n\n";
@@ -177,3 +197,67 @@ function layoutBoundary(
return /^<t[dh]\b/i.test(source.slice(offset + raw.length)) ? " " : "";
return null;
}
function hasNonWhitespaceAfterNewline(value: string): boolean {
const lastNewline = value.lastIndexOf("\n");
return /[^\s]/.test(lastNewline === -1 ? value : value.slice(lastNewline + 1));
}
function isTableWrapperTag(raw: string, inCode: boolean): boolean {
if (inCode) return false;
if (raw.startsWith("<!--")) return true;
const name = /^<\/?([A-Za-z][A-Za-z0-9-]*)/.exec(raw)?.[1].toLowerCase();
return name === "summary" || name === "details" || (name !== undefined && BLOCK_TAGS.has(name));
}
function collectTableRanges(
source: string,
codeRanges: readonly { start: number; end: number }[],
): { start: number; end: number }[] {
let cursor = 0;
let codeIndex = 0;
let lineHasPrefixText = false;
// Advance line/code state monotonically in a single forward pass so large single-line HTML tables stay O(n)
// while nested leading wrappers (e.g. `<details><summary>Results</summary><div>| A | B |`) follow
// line breaks introduced by earlier masked tags.
const tableSource = source.replace(HTML, (raw, offset: number) => {
for (let index = cursor; index < offset; index++) {
const code = source.charCodeAt(index);
if (code === 10) lineHasPrefixText = false;
else if (code !== 32 && code !== 9 && code !== 13) lineHasPrefixText = true;
}
cursor = offset + raw.length;
while (codeIndex < codeRanges.length && codeRanges[codeIndex].end <= offset) codeIndex++;
const inCode = codeIndex < codeRanges.length && offset >= codeRanges[codeIndex].start;
if (!isTableWrapperTag(raw, inCode)) {
if (inCode || /^<code\b/i.test(raw)) {
if (hasNonWhitespaceAfterNewline(raw)) lineHasPrefixText = true;
else if (raw.includes("\n")) lineHasPrefixText = false;
} else if (raw.includes("\n")) {
lineHasPrefixText = false;
}
return raw;
}
const blanked = raw.replace(/[^\n]/g, " ");
if (!lineHasPrefixText && blanked.length > 0 && !blanked.endsWith("\n")) {
return `${blanked.slice(0, -1)}\n`;
}
if (blanked.includes("\n")) lineHasPrefixText = false;
return blanked;
});
const tableRanges: { start: number; end: number }[] = [];
function findTables(node: Nodes) {
if (node.type === "table" && node.position) {
const start = node.position.start.offset;
const end = node.position.end.offset;
if (start !== undefined && end !== undefined) tableRanges.push({ start, end });
} else if ("children" in node) node.children.forEach(findTables);
}
findTables(
fromMarkdown(tableSource, {
extensions: [{ disable: { null: ["htmlFlow", "htmlText"] } }, gfmTable()],
mdastExtensions: [gfmTableFromMarkdown()],
}),
);
return tableRanges;
}
@@ -838,6 +838,188 @@ describe("GitHub comment HTML normalization", () => {
])("normalizes %s without changing code", (source, expected) => {
expect(prepareMarkdownSource(source).render()).toBe(expected);
});
it("keeps <br> line breaks inside GFM table headers and cells within a single row", async () => {
const source = [
"| Col<br>One | Col<br />Two |",
"| --- | --- |",
"| First<br>Second<br/>Third | Plain |",
].join("\n");
const tree = await parseMarkdown(prepareMarkdownSource(source).render(), {
hardSoftBreaks: true,
latexMath: false,
});
const table = tree.children?.find((node) => node.type === "Table");
expect(table).toBeDefined();
const headRows = table?.children?.find((node) => node.type === "TableHead")?.children ?? [];
const bodyRows = table?.children?.find((node) => node.type === "TableBody")?.children ?? [];
expect(headRows).toHaveLength(1);
expect(bodyRows).toHaveLength(1);
const [headCells, bodyCells] = [headRows[0].children ?? [], bodyRows[0].children ?? []];
expect(headCells[0].children).toEqual([
{ type: "Text", content: "Col" },
{ type: "LineBreak" },
{ type: "Text", content: "One" },
]);
expect(headCells[1].children).toEqual([
{ type: "Text", content: "Col" },
{ type: "LineBreak" },
{ type: "Text", content: "Two" },
]);
expect(bodyCells[0].children).toEqual([
{ type: "Text", content: "First" },
{ type: "LineBreak" },
{ type: "Text", content: "Second" },
{ type: "LineBreak" },
{ type: "Text", content: "Third" },
]);
});
it.each([
"<details><summary>Results</summary>\n\n| A | B |\n| - | - |\n| 1<br>2 | 3 |\n</details>",
"<details><summary>Results</summary>| A | B |\n| - | - |\n| 1<br>2 | 3 |</details>",
"<details><summary>Results</summary><div>| A | B |\n| - | - |\n| 1<br>2 | 3 |</div></details>",
"<span></span><div>| A | B |\n| - | - |\n| 1<br>2 | 3 |</div>",
])("keeps table <br> inside wrapped table cells: %s", async (source) => {
const tree = await parseMarkdown(prepareMarkdownSource(source).render(), {
hardSoftBreaks: true,
latexMath: false,
});
const table = tree.children?.find((node) => node.type === "Table");
expect(table).toBeDefined();
const body = table?.children?.find((node) => node.type === "TableBody");
expect(body?.children).toHaveLength(1);
expect(body?.children?.[0]?.children?.[0]?.children).toEqual([
{ type: "Text", content: "1" },
{ type: "LineBreak" },
{ type: "Text", content: "2" },
]);
});
it("recognizes file paths and URLs separated by <br> inside table cells", async () => {
const source = [
"| Paths | Mixed | URLs |",
"| --- | --- | --- |",
"| src/first.ts<br>src/second.ts | https://example.com/first<br>src/second.ts | https://example.com/first<br>https://example.com/second |",
].join("\n");
const prepared = prepareMarkdownSource(source);
const linked = recognizeTextLinks(
await parseMarkdown(prepared.render(), {
hardSoftBreaks: true,
latexMath: false,
}),
prepared.linkRecognition.text,
prepared.linkRecognition.inlineCode,
);
const table = linked.children?.find((node) => node.type === "Table");
const row = table?.children?.find((node) => node.type === "TableBody")?.children?.[0];
expect(row?.children?.[0]?.children).toEqual([
{
type: "Link",
attributes: { url: "src/first.ts", recognizedLink: "true" },
children: [{ type: "Text", content: "src/first.ts" }],
},
{ type: "LineBreak" },
{
type: "Link",
attributes: { url: "src/second.ts", recognizedLink: "true" },
children: [{ type: "Text", content: "src/second.ts" }],
},
]);
expect(row?.children?.[1]?.children).toEqual([
{
type: "Link",
attributes: { url: "https://example.com/first" },
children: [{ type: "Text", content: "https://example.com/first" }],
},
{ type: "LineBreak" },
{
type: "Link",
attributes: { url: "src/second.ts", recognizedLink: "true" },
children: [{ type: "Text", content: "src/second.ts" }],
},
]);
expect(row?.children?.[2]?.children).toEqual([
{
type: "Link",
attributes: { url: "https://example.com/first" },
children: [{ type: "Text", content: "https://example.com/first" }],
},
{ type: "LineBreak" },
{
type: "Link",
attributes: { url: "https://example.com/second" },
children: [{ type: "Text", content: "https://example.com/second" }],
},
]);
});
it("keeps literal U+2028 outside tables, inline code, and escaped <br> untouched", async () => {
const source = [
"before\u2028after `before\u2028after`",
"",
"| Inline | Escaped | Entity |",
"| --- | --- | --- |",
"| `before\u2028after` | \\<br> | &lt;br&gt; `<br>` |",
].join("\n");
const tree = await parseMarkdown(prepareMarkdownSource(source).render(), {
hardSoftBreaks: true,
latexMath: false,
});
const collectLineBreaks = (node: ASTNode): number =>
(node.type === "LineBreak" ? 1 : 0) +
(node.children?.reduce((count, child) => count + collectLineBreaks(child), 0) ?? 0);
expect(collectLineBreaks(tree)).toBe(0);
const paragraph = tree.children?.find((node) => node.type === "Paragraph");
expect(paragraph?.children).toEqual([
{ type: "Text", content: "before\u2028after " },
{ type: "Code", children: [{ type: "Text", content: "before\u2028after" }] },
]);
const row = tree.children
?.find((node) => node.type === "Table")
?.children?.find((node) => node.type === "TableBody")?.children?.[0];
expect(row?.children?.[0]?.children).toEqual([
{ type: "Code", children: [{ type: "Text", content: "before\u2028after" }] },
]);
expect(row?.children?.[1]?.children).toEqual([{ type: "Text", content: "<br>" }]);
expect(row?.children?.[2]?.children).toEqual([
{ type: "Text", content: "<br> " },
{ type: "Code", children: [{ type: "Text", content: "<br>" }] },
]);
expect(prepareMarkdownSource("<table><tr><td>a<br>b</td></tr></table>").render()).toBe(
"a \nb",
);
});
it("preserves emphasis and strong delimiters adjacent to <br> inside table cells", async () => {
const source = [
"| A | B |",
"| --- | --- |",
"| **方案 B(最猛 · 推荐)**<br>阶梯首充 | **`基准 → 30% → 50%`**<br>*(复购:基准)* |",
].join("\n");
const tree = await parseMarkdown(prepareMarkdownSource(source).render(), {
hardSoftBreaks: true,
latexMath: false,
});
const row = tree.children
?.find((node) => node.type === "Table")
?.children?.find((node) => node.type === "TableBody")?.children?.[0];
expect(row?.children?.[0]?.children).toEqual([
{ type: "Strong", children: [{ type: "Text", content: "方案 B(最猛 · 推荐)" }] },
{ type: "LineBreak" },
{ type: "Text", content: "阶梯首充" },
]);
expect(row?.children?.[1]?.children).toEqual([
{
type: "Strong",
children: [{ type: "Code", children: [{ type: "Text", content: "基准 → 30% → 50%" }] }],
},
{ type: "LineBreak" },
{ type: "Emphasis", children: [{ type: "Text", content: "(复购:基准)" }] },
]);
});
});
it("preserves backslashes and decodes entities inside HTML code", () => {
+23 -526
View File
@@ -1,3 +1,4 @@
import { AppearanceText } from "@/appearance/text";
import { useDisclosureHold } from "@/agent-stream/disclosure";
import { MessagePreview, MessageSender } from "@/components/user-message";
import { useStableEvent } from "@/hooks/use-stable-event";
@@ -13,7 +14,6 @@ import {
AttachmentThumbnail,
} from "@/components/attachment-pill";
import { MarkdownRenderer } from "@/components/markdown/renderer";
import { useRetainedPanelActive } from "@/components/retained-panel";
import {
isRewindableMessage,
RewindMenu,
@@ -29,6 +29,7 @@ import { useProvidersSnapshot } from "@/hooks/use-providers-snapshot";
import { useRevealedText, type MarkdownPhase } from "@/hooks/use-revealed-text";
import { ICON_SIZE, type Theme } from "@/styles/theme";
import { inlineUnistylesStyle } from "@/styles/unistyles-inline-style";
import { LabelShimmer, useLabelMeasurements } from "@/components/label-shimmer";
import { buildToolCallPresentation } from "@/tool-calls/presentation";
import type {
DaemonUploadedImageAttachment,
@@ -54,7 +55,6 @@ import type {
ToolCallDetail,
} from "@getpaseo/protocol/agent-types";
import type { AgentAttachment } from "@getpaseo/protocol/messages";
import MaskedView from "@react-native-masked-view/masked-view";
import {
ArrowRightLeft,
Check,
@@ -94,15 +94,6 @@ import {
type LayoutChangeEvent,
type TextStyle,
} from "react-native";
import Animated, {
Easing,
cancelAnimation,
useAnimatedStyle,
useSharedValue,
withRepeat,
withTiming,
} from "react-native-reanimated";
import Svg, { Defs, Rect, Stop, LinearGradient as SvgLinearGradient } from "react-native-svg";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { capAssistantMessageForRender, getUtf8ByteLength } from "./assistant-message-render-limit";
import { getTurnDurationLabel } from "./assistant-turn-footer-label";
@@ -153,8 +144,6 @@ function useDisableOuterSpacing(disableOuterSpacing: boolean | undefined) {
return disableOuterSpacing ?? contextValue;
}
const WEB_TOOLCALL_SHIMMER_KEYFRAME_ID = "paseo-toolcall-shimmer-keyframes";
const WEB_TOOLCALL_SHIMMER_ANIMATION_NAME = "paseo-toolcall-shimmer";
const ThemedMicVocal = withUnistyles(MicVocal);
const ThemedFileSymlinkIcon = withUnistyles(FileSymlink);
const ThemedTriangleAlertIcon = withUnistyles(TriangleAlertIcon);
@@ -173,17 +162,6 @@ const mutedForegroundColorMapping = (theme: Theme) => ({
const destructiveColorMapping = (theme: Theme) => ({ color: theme.colors.destructive });
const infoColorMapping = (theme: Theme) => ({ color: theme.colors.palette.blue[300] });
const warningColorMapping = (theme: Theme) => ({ color: theme.colors.palette.amber[500] });
const WEB_TOOLCALL_SHIMMER_KEYFRAME_CSS = `
@keyframes ${WEB_TOOLCALL_SHIMMER_ANIMATION_NAME} {
0% {
background-position: var(--paseo-shimmer-start, -200px) 0;
}
100% {
background-position: var(--paseo-shimmer-end, 200px) 0;
}
}
`;
let webToolCallShimmerRegistered = false;
const SCROLL_EDGE_EPSILON = 0.5;
// Font size for stream metadata (timestamps, durations, live elapsed timer).
@@ -191,31 +169,6 @@ const SCROLL_EDGE_EPSILON = 0.5;
export const STREAM_METADATA_FONT_SIZE = 13;
type ScrollAxis = "x" | "y";
function ensureWebToolCallShimmerKeyframes() {
if (isNative) {
return;
}
if (typeof document === "undefined") {
return;
}
const existing = document.getElementById(WEB_TOOLCALL_SHIMMER_KEYFRAME_ID);
if (existing) {
if (existing.textContent !== WEB_TOOLCALL_SHIMMER_KEYFRAME_CSS) {
existing.textContent = WEB_TOOLCALL_SHIMMER_KEYFRAME_CSS;
}
webToolCallShimmerRegistered = true;
return;
}
if (webToolCallShimmerRegistered) {
return;
}
const styleElement = document.createElement("style");
styleElement.id = WEB_TOOLCALL_SHIMMER_KEYFRAME_ID;
styleElement.textContent = WEB_TOOLCALL_SHIMMER_KEYFRAME_CSS;
document.head.appendChild(styleElement);
webToolCallShimmerRegistered = true;
}
function getWheelEventElementTarget(event: WheelEvent, fallback: HTMLElement): HTMLElement {
const { target } = event;
if (target instanceof HTMLElement) {
@@ -618,9 +571,13 @@ export const UserMessage = memo(function UserMessage({
</View>
) : null}
{hasText ? (
<Text selectable style={userMessageStylesheet.text} dataSet={MESSAGE_TEXT_DATASET}>
<AppearanceText
selectable
style={userMessageStylesheet.text}
dataSet={MESSAGE_TEXT_DATASET}
>
{message}
</Text>
</AppearanceText>
) : null}
</MessagePreview>
</View>
@@ -1091,14 +1048,6 @@ const expandableBadgeStylesheet = StyleSheet.create((theme) => ({
secondaryLabelActive: {
color: theme.colors.foreground,
},
shimmerText: {
color: "transparent",
fontSize: theme.fontSize.base,
fontWeight: theme.fontWeight.normal,
},
spacer: {
flex: 1,
},
chevron: {
flexShrink: 0,
},
@@ -1137,160 +1086,8 @@ const expandableBadgeStylesheet = StyleSheet.create((theme) => ({
detailWrapperBorderless: {
borderWidth: 0,
},
shimmerOverlay: {
position: "absolute",
top: 0,
right: 0,
bottom: 0,
left: 0,
flexDirection: "row",
alignItems: "center",
overflow: "hidden",
},
shimmerMaskRow: {
flexDirection: "row",
alignItems: "center",
width: "100%",
height: "100%",
},
nativeShimmerTrack: {
position: "absolute",
top: 0,
right: 0,
bottom: 0,
left: 0,
overflow: "hidden",
},
nativeShimmerPeak: {
position: "absolute",
top: 0,
bottom: 0,
left: 0,
},
}));
interface NativeExpandableBadgeShimmerProps {
label: string;
secondaryLabel?: string;
rowWidth: number;
rowHeight: number;
peakWidth: number;
durationSeconds: number;
gradientId: string;
}
const NativeExpandableBadgeShimmer = memo(function NativeExpandableBadgeShimmer({
label,
secondaryLabel,
rowWidth,
rowHeight,
peakWidth,
durationSeconds,
gradientId,
}: NativeExpandableBadgeShimmerProps) {
const isPanelActive = useRetainedPanelActive();
const shimmerTranslateX = useSharedValue(0);
useEffect(() => {
if (!isPanelActive) {
cancelAnimation(shimmerTranslateX);
return;
}
const startPosition = -peakWidth;
const endPosition = rowWidth + peakWidth;
shimmerTranslateX.value = startPosition;
shimmerTranslateX.value = withRepeat(
withTiming(endPosition, {
duration: durationSeconds * 1000,
easing: Easing.linear,
}),
-1,
false,
);
return () => {
cancelAnimation(shimmerTranslateX);
};
}, [durationSeconds, isPanelActive, peakWidth, rowWidth, shimmerTranslateX]);
const nativeShimmerPeakStyle = useAnimatedStyle(() => ({
transform: [{ translateX: shimmerTranslateX.value }],
}));
const nativeShimmerTrackStyle = useMemo(
() => [expandableBadgeStylesheet.nativeShimmerTrack, { width: rowWidth, height: rowHeight }],
[rowHeight, rowWidth],
);
const nativeShimmerMaskStyle = useMemo(
() => [expandableBadgeStylesheet.shimmerMaskRow, { width: rowWidth, height: rowHeight }],
[rowHeight, rowWidth],
);
const nativeLabelMaskStyle = useMemo(
() => [expandableBadgeStylesheet.label, { color: "#000000", opacity: 1 }],
[],
);
const nativeSecondaryMaskStyle = useMemo(
() => [expandableBadgeStylesheet.secondaryLabel, { color: "#000000", opacity: 1 }],
[],
);
const nativeShimmerPeakCombinedStyle = useMemo(
() => [
expandableBadgeStylesheet.nativeShimmerPeak,
nativeShimmerPeakStyle,
{ width: peakWidth, height: rowHeight },
],
[nativeShimmerPeakStyle, peakWidth, rowHeight],
);
const maskElement = useMemo(
() => (
<View pointerEvents="none" style={nativeShimmerMaskStyle}>
<Text style={nativeLabelMaskStyle} numberOfLines={1}>
{label}
</Text>
{secondaryLabel ? (
<Text style={nativeSecondaryMaskStyle} numberOfLines={1}>
{secondaryLabel}
</Text>
) : (
<View style={expandableBadgeStylesheet.spacer} />
)}
</View>
),
[nativeShimmerMaskStyle, nativeLabelMaskStyle, nativeSecondaryMaskStyle, label, secondaryLabel],
);
return (
<View style={expandableBadgeStylesheet.shimmerOverlay} pointerEvents="none">
<MaskedView pointerEvents="none" style={nativeShimmerTrackStyle} maskElement={maskElement}>
<View pointerEvents="none" style={nativeShimmerTrackStyle}>
<Animated.View pointerEvents="none" style={nativeShimmerPeakCombinedStyle}>
<NativeShimmerPeakSvg gradientId={gradientId} />
</Animated.View>
</View>
</MaskedView>
</View>
);
});
function NativeShimmerPeakSvg({ gradientId }: { gradientId: string }) {
return (
<Svg width="100%" height="100%" preserveAspectRatio="none">
<Defs>
<SvgLinearGradient id={gradientId} x1="0%" y1="0%" x2="100%" y2="0%">
<Stop offset="0%" stopColor="#ffffff" stopOpacity={0} />
<Stop offset="50%" stopColor="#ffffff" stopOpacity={1} />
<Stop offset="100%" stopColor="#ffffff" stopOpacity={0} />
</SvgLinearGradient>
</Defs>
<Rect x="0" y="0" width="100%" height="100%" fill={`url(#${gradientId})`} />
</Svg>
);
}
export const AssistantMessage = memo(function AssistantMessage({
renderFullContent = false,
occurrenceKey,
@@ -1884,77 +1681,30 @@ interface ExpandableBadgeProps {
interface ExpandableBadgeSecondaryLabelProps {
secondaryLabel?: string;
secondaryLabelStyle: StyleProp<TextStyle>;
shouldMeasureWebShimmer: boolean;
onSecondaryLayout: (event: LayoutChangeEvent) => void;
onLayout: ((event: LayoutChangeEvent) => void) | undefined;
}
function ExpandableBadgeSecondaryLabel({
secondaryLabel,
secondaryLabelStyle,
shouldMeasureWebShimmer,
onSecondaryLayout,
onLayout,
}: ExpandableBadgeSecondaryLabelProps) {
if (!secondaryLabel) {
return null;
}
return (
<Text
style={secondaryLabelStyle}
numberOfLines={1}
onLayout={shouldMeasureWebShimmer ? onSecondaryLayout : undefined}
>
<Text style={secondaryLabelStyle} numberOfLines={1} onLayout={onLayout}>
{secondaryLabel}
</Text>
);
}
interface ExpandableBadgeWebShimmerOverlayProps {
label: string;
secondaryLabel?: string;
shimmerLabelTextStyle: StyleProp<TextStyle>;
shimmerSecondaryTextStyle: StyleProp<TextStyle>;
}
function ExpandableBadgeWebShimmerOverlay({
label,
secondaryLabel,
shimmerLabelTextStyle,
shimmerSecondaryTextStyle,
}: ExpandableBadgeWebShimmerOverlayProps) {
return (
<View style={expandableBadgeStylesheet.shimmerOverlay} pointerEvents="none">
<Text style={shimmerLabelTextStyle} numberOfLines={1}>
{label}
</Text>
{secondaryLabel ? (
<Text style={shimmerSecondaryTextStyle} numberOfLines={1}>
{secondaryLabel}
</Text>
) : null}
{!secondaryLabel ? <View style={expandableBadgeStylesheet.spacer} /> : null}
</View>
);
}
interface ExpandableBadgeLabelRowProps {
label: string;
labelStyle: StyleProp<TextStyle>;
secondaryLabel?: string;
secondaryLabelStyle: StyleProp<TextStyle>;
shouldMeasureWebShimmer: boolean;
shouldMeasureNativeShimmer: boolean;
isWebShimmer: boolean;
isNativeShimmer: boolean;
shimmerLabelTextStyle: StyleProp<TextStyle>;
shimmerSecondaryTextStyle: StyleProp<TextStyle>;
labelRowWidth: number;
labelRowHeight: number;
nativeShimmerPeakWidth: number;
shimmerDuration: number;
nativeGradientId: string;
onLabelRowLayout: (event: LayoutChangeEvent) => void;
onLabelLayout: (event: LayoutChangeEvent) => void;
onSecondaryLayout: (event: LayoutChangeEvent) => void;
isLoading: boolean;
}
function ExpandableBadgeLabelRow({
@@ -1962,56 +1712,26 @@ function ExpandableBadgeLabelRow({
labelStyle,
secondaryLabel,
secondaryLabelStyle,
shouldMeasureWebShimmer,
shouldMeasureNativeShimmer,
isWebShimmer,
isNativeShimmer,
shimmerLabelTextStyle,
shimmerSecondaryTextStyle,
labelRowWidth,
labelRowHeight,
nativeShimmerPeakWidth,
shimmerDuration,
nativeGradientId,
onLabelRowLayout,
onLabelLayout,
onSecondaryLayout,
isLoading,
}: ExpandableBadgeLabelRowProps) {
const measuring = useLabelMeasurements(isLoading);
return (
<View
style={expandableBadgeStylesheet.labelRow}
onLayout={shouldMeasureNativeShimmer ? onLabelRowLayout : undefined}
>
<Text
style={labelStyle}
numberOfLines={1}
onLayout={shouldMeasureWebShimmer ? onLabelLayout : undefined}
>
<View style={expandableBadgeStylesheet.labelRow} onLayout={measuring.onRowLayout}>
<Text style={labelStyle} numberOfLines={1} onLayout={measuring.onLabelLayout}>
{label}
</Text>
<ExpandableBadgeSecondaryLabel
secondaryLabel={secondaryLabel}
secondaryLabelStyle={secondaryLabelStyle}
shouldMeasureWebShimmer={shouldMeasureWebShimmer}
onSecondaryLayout={onSecondaryLayout}
onLayout={measuring.onSecondaryLayout}
/>
{isWebShimmer ? (
<ExpandableBadgeWebShimmerOverlay
{isLoading ? (
<LabelShimmer
label={label}
secondaryLabel={secondaryLabel}
shimmerLabelTextStyle={shimmerLabelTextStyle}
shimmerSecondaryTextStyle={shimmerSecondaryTextStyle}
/>
) : null}
{isNativeShimmer ? (
<NativeExpandableBadgeShimmer
label={label}
secondaryLabel={secondaryLabel}
rowWidth={labelRowWidth}
rowHeight={labelRowHeight}
peakWidth={nativeShimmerPeakWidth}
durationSeconds={shimmerDuration}
gradientId={nativeGradientId}
labelStyle={expandableBadgeStylesheet.label}
secondaryLabelStyle={expandableBadgeStylesheet.secondaryLabel}
measurements={measuring.measurements}
/>
) : null}
</View>
@@ -2086,55 +1806,6 @@ function renderExpandableBadgeIconSlot({
return iconNode;
}
function computeShimmerMetrics(input: {
label: string;
secondaryLabel: string | undefined;
isLoading: boolean;
labelRowWidth: number;
labelRowHeight: number;
labelOffsetX: number;
labelWidth: number;
secondaryOffsetX: number;
secondaryWidth: number;
}) {
const totalShimmerChars = input.label.trim().length + (input.secondaryLabel?.trim().length ?? 0);
const shortTextDurationAdjustment = totalShimmerChars <= 12 ? 0.25 : 0;
const shimmerDuration = Math.max(
1,
Math.min(2.3, 1.25 + totalShimmerChars * 0.008 - shortTextDurationAdjustment),
);
const nativeShimmerPeakWidth = Math.max(
32,
Math.min(120, input.labelRowWidth > 0 ? input.labelRowWidth * 0.28 : 0),
);
const isWebShimmer = input.isLoading && isWeb;
// React Native Web only observes a node when onLayout exists at mount. Keep
// measuring while idle so a retained badge has dimensions when it starts loading.
const shouldMeasureWebShimmer = isWeb;
const shouldMeasureNativeShimmer = input.isLoading && isNative;
const isNativeShimmer =
shouldMeasureNativeShimmer && input.labelRowWidth > 0 && input.labelRowHeight > 0;
const webShimmerSpanStartX = input.labelOffsetX;
const webShimmerSpanEndX = input.secondaryLabel
? input.secondaryOffsetX + input.secondaryWidth
: input.labelOffsetX + input.labelWidth;
const webShimmerSpanWidth = Math.max(1, webShimmerSpanEndX - webShimmerSpanStartX);
const webShimmerPeakWidth = Math.max(42, Math.min(120, webShimmerSpanWidth * 0.22));
const webShimmerTrackStart = webShimmerSpanStartX - webShimmerPeakWidth;
const webShimmerTrackEnd = webShimmerSpanEndX;
return {
shimmerDuration,
nativeShimmerPeakWidth,
isWebShimmer,
shouldMeasureWebShimmer,
shouldMeasureNativeShimmer,
isNativeShimmer,
webShimmerPeakWidth,
webShimmerTrackStart,
webShimmerTrackEnd,
};
}
function useDetailWheelPropagationBlocker(input: {
detailWrapperRef: React.RefObject<View | null>;
enabled: boolean;
@@ -2161,33 +1832,6 @@ function useDetailWheelPropagationBlocker(input: {
}, [detailWrapperRef, enabled]);
}
const SHIMMER_GRADIENT =
"linear-gradient(90deg, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.45) 24%, #ffffff 40%, #ffffff 60%, rgba(255, 255, 255, 0.45) 76%, rgba(255, 255, 255, 0) 100%)";
function buildShimmerTextStyle(input: {
isWebShimmer: boolean;
webShimmerPeakWidth: number;
shimmerDuration: number;
webShimmerTrackStart: number;
webShimmerTrackEnd: number;
offsetX: number;
}): object | null {
if (!input.isWebShimmer) return null;
return inlineUnistylesStyle({
opacity: 1,
color: "transparent",
backgroundImage: SHIMMER_GRADIENT,
backgroundSize: `${input.webShimmerPeakWidth}px 100%`,
backgroundRepeat: "no-repeat",
backgroundClip: "text",
WebkitBackgroundClip: "text",
WebkitTextFillColor: "transparent",
animation: `${WEB_TOOLCALL_SHIMMER_ANIMATION_NAME} ${input.shimmerDuration}s linear infinite`,
"--paseo-shimmer-start": `${input.webShimmerTrackStart - input.offsetX}px`,
"--paseo-shimmer-end": `${input.webShimmerTrackEnd - input.offsetX}px`,
});
}
export const ExpandableBadge = memo(function ExpandableBadge({
label,
style,
@@ -2231,126 +1875,11 @@ export const ExpandableBadge = memo(function ExpandableBadge({
const handleOpenFileHoverIn = useCallback(() => setIsOpenFileHovered(true), []);
const handleOpenFileHoverOut = useCallback(() => setIsOpenFileHovered(false), []);
const nativeGradientIdRef = useRef(
`shimmer-gradient-${Math.random().toString(36).substring(2, 9)}`,
);
const [labelRowWidth, setLabelRowWidth] = useState(0);
const [labelRowHeight, setLabelRowHeight] = useState(0);
const [labelOffsetX, setLabelOffsetX] = useState(0);
const [labelWidth, setLabelWidth] = useState(0);
const [secondaryOffsetX, setSecondaryOffsetX] = useState(0);
const [secondaryWidth, setSecondaryWidth] = useState(0);
const {
shimmerDuration,
nativeShimmerPeakWidth,
isWebShimmer,
shouldMeasureWebShimmer,
shouldMeasureNativeShimmer,
isNativeShimmer,
webShimmerPeakWidth,
webShimmerTrackStart,
webShimmerTrackEnd,
} = computeShimmerMetrics({
label,
secondaryLabel,
isLoading,
labelRowWidth,
labelRowHeight,
labelOffsetX,
labelWidth,
secondaryOffsetX,
secondaryWidth,
});
const handleLabelRowLayout = useCallback(
(event: LayoutChangeEvent) => {
if (!shouldMeasureNativeShimmer) {
return;
}
const { width, height } = event.nativeEvent.layout;
setLabelRowWidth((previous) => (Math.abs(previous - width) > 0.5 ? width : previous));
setLabelRowHeight((previous) => (Math.abs(previous - height) > 0.5 ? height : previous));
},
[shouldMeasureNativeShimmer],
);
const handleLabelLayout = useCallback(
(event: LayoutChangeEvent) => {
if (!shouldMeasureWebShimmer) {
return;
}
const { x, width } = event.nativeEvent.layout;
setLabelOffsetX((previous) => (Math.abs(previous - x) > 0.5 ? x : previous));
setLabelWidth((previous) => (Math.abs(previous - width) > 0.5 ? width : previous));
},
[shouldMeasureWebShimmer],
);
const handleSecondaryLayout = useCallback(
(event: LayoutChangeEvent) => {
if (!shouldMeasureWebShimmer || !secondaryLabel) {
return;
}
const { x, width } = event.nativeEvent.layout;
setSecondaryOffsetX((previous) => (Math.abs(previous - x) > 0.5 ? x : previous));
setSecondaryWidth((previous) => (Math.abs(previous - width) > 0.5 ? width : previous));
},
[shouldMeasureWebShimmer, secondaryLabel],
);
useEffect(() => {
if (!isWebShimmer) {
return;
}
ensureWebToolCallShimmerKeyframes();
}, [isWebShimmer]);
useDetailWheelPropagationBlocker({
detailWrapperRef,
enabled: !isNative && isExpanded && hasDetailContent,
});
const shimmerLabelStyle = useMemo<StyleProp<TextStyle>>(
() =>
buildShimmerTextStyle({
isWebShimmer,
webShimmerPeakWidth,
shimmerDuration,
webShimmerTrackStart,
webShimmerTrackEnd,
offsetX: labelOffsetX,
}),
[
isWebShimmer,
webShimmerPeakWidth,
shimmerDuration,
webShimmerTrackStart,
webShimmerTrackEnd,
labelOffsetX,
],
);
const shimmerSecondaryStyle = useMemo<StyleProp<TextStyle>>(
() =>
buildShimmerTextStyle({
isWebShimmer,
webShimmerPeakWidth,
shimmerDuration,
webShimmerTrackStart,
webShimmerTrackEnd,
offsetX: secondaryOffsetX,
}),
[
isWebShimmer,
webShimmerPeakWidth,
shimmerDuration,
webShimmerTrackStart,
webShimmerTrackEnd,
secondaryOffsetX,
],
);
const containerStyle = useMemo(
() => [
expandableBadgeStylesheet.container,
@@ -2408,25 +1937,6 @@ export const ExpandableBadge = memo(function ExpandableBadge({
[isActive],
);
const shimmerLabelTextStyle = useMemo(
() => [
expandableBadgeStylesheet.label,
isLoading && expandableBadgeStylesheet.labelLoading,
expandableBadgeStylesheet.shimmerText,
shimmerLabelStyle,
],
[isLoading, shimmerLabelStyle],
);
const shimmerSecondaryTextStyle = useMemo(
() => [
expandableBadgeStylesheet.secondaryLabel,
expandableBadgeStylesheet.shimmerText,
shimmerSecondaryStyle,
],
[shimmerSecondaryStyle],
);
const chevronStyle = useMemo(
() => [
expandableBadgeStylesheet.chevron,
@@ -2475,20 +1985,7 @@ export const ExpandableBadge = memo(function ExpandableBadge({
labelStyle={labelStyle}
secondaryLabel={secondaryLabel}
secondaryLabelStyle={secondaryLabelStyle}
shouldMeasureWebShimmer={shouldMeasureWebShimmer}
shouldMeasureNativeShimmer={shouldMeasureNativeShimmer}
isWebShimmer={isWebShimmer}
isNativeShimmer={isNativeShimmer}
shimmerLabelTextStyle={shimmerLabelTextStyle}
shimmerSecondaryTextStyle={shimmerSecondaryTextStyle}
labelRowWidth={labelRowWidth}
labelRowHeight={labelRowHeight}
nativeShimmerPeakWidth={nativeShimmerPeakWidth}
shimmerDuration={shimmerDuration}
nativeGradientId={nativeGradientIdRef.current}
onLabelRowLayout={handleLabelRowLayout}
onLabelLayout={handleLabelLayout}
onSecondaryLayout={handleSecondaryLayout}
isLoading={isLoading}
/>
</Pressable>
{onOpenFile && isHovered ? (
@@ -2,12 +2,19 @@ import { useCallback, useMemo, useState, type ReactNode } from "react";
import { View } from "react-native";
import { isWeb } from "@/constants/platform";
import { SettingsRowChildren } from "./row-children";
import { SettingsRowHeader } from "./row-header";
import { SettingsRowHeader, type SettingsRowHintStatus } from "./row-header";
interface SettingsCollapsibleRowProps {
label: string;
/** A line under the label explaining the group. */
hint?: string;
hintStatus?: SettingsRowHintStatus;
/** A short status shown before the chevron, so the row says something while collapsed. */
summary?: string;
/** A control acting on the row's subject in place, such as a switch, before the chevron. */
control?: ReactNode;
/** Names the expand/collapse button for assistive tech when the label alone is not enough. */
accessibilityLabel?: string;
defaultExpanded?: boolean;
testID?: string;
/** The rows revealed underneath, separated like the rows of a `SettingsCard` and laid out as nested rows. */
@@ -21,7 +28,11 @@ interface SettingsCollapsibleRowProps {
*/
export function SettingsCollapsibleRow({
label,
hint,
hintStatus,
summary,
control,
accessibilityLabel,
defaultExpanded = false,
testID,
children,
@@ -39,7 +50,11 @@ export function SettingsCollapsibleRow({
<View testID={testID}>
<SettingsRowHeader
label={label}
hint={hint}
hintStatus={hintStatus}
summary={summary}
control={control}
accessibilityLabel={accessibilityLabel}
onPress={toggle}
expanded={expanded}
accessibilityState={accessibilityState}
@@ -555,6 +555,7 @@ function ProjectMenuItems({
}) {
const { t } = useTranslation();
const toast = useToast();
const localDaemonServerId = useLocalDaemonServerId();
const handleOpenProjectSettings = useCallback(() => {
if (!settingsTarget) return;
router.navigate(buildProjectSettingsRoute(settingsTarget.serverId, settingsTarget.projectId));
@@ -594,6 +595,7 @@ function ProjectMenuItems({
</ProjectMenuItem>
) : null}
<OpenInFileManagerMenuItem
serverId={localDaemonServerId}
surface={surface}
path={projectPath}
testID={`sidebar-project-menu-open-folder-${projectViewKey}`}
@@ -268,6 +268,7 @@ function SidebarWorkspaceMenuItems({
</DropdownMenuSubTrigger>
) : null}
<OpenInFileManagerMenuItem
serverId={serverId}
surface={surface}
path={openInFileManagerPath}
testID={`sidebar-workspace-menu-open-folder-${workspaceKey}`}
@@ -1,74 +0,0 @@
import { useLayoutEffect, useState } from "react";
import { makeMutable, type SharedValue, useSharedValue } from "react-native-reanimated";
import { scheduleOnUI } from "react-native-worklets";
import { useRetainedPanelActive } from "@/components/retained-panel";
import { getStatusRingRotation } from "@/components/status-ring/geometry";
const sharedRotation = makeMutable(getStatusRingRotation(Date.now()));
const activeRingCount = makeMutable(0);
const clockRunning = makeMutable(false);
let nextListenerId = 1;
function advanceSharedRotation(): void {
"worklet";
if (activeRingCount.value === 0) {
clockRunning.value = false;
return;
}
sharedRotation.value = getStatusRingRotation(Date.now());
requestAnimationFrame(advanceSharedRotation);
}
function registerStatusRing(
rotation: SharedValue<number>,
registered: SharedValue<boolean>,
listenerId: number,
): void {
"worklet";
if (registered.value) {
return;
}
registered.value = true;
rotation.value = getStatusRingRotation(Date.now());
sharedRotation.addListener(listenerId, (value) => {
rotation.value = value;
});
activeRingCount.value += 1;
if (!clockRunning.value) {
clockRunning.value = true;
sharedRotation.value = getStatusRingRotation(Date.now());
requestAnimationFrame(advanceSharedRotation);
}
}
function unregisterStatusRing(registered: SharedValue<boolean>, listenerId: number): void {
"worklet";
if (!registered.value) {
return;
}
registered.value = false;
sharedRotation.removeListener(listenerId);
activeRingCount.value -= 1;
}
export function useStatusRingRotation(): SharedValue<number> {
const active = useRetainedPanelActive();
// Hidden retained views must not subscribe their animated styles to the shared clock.
const rotation = useSharedValue(getStatusRingRotation(Date.now()));
const registered = useSharedValue(false);
const [listenerId] = useState(() => nextListenerId++);
useLayoutEffect(() => {
if (!active) return;
scheduleOnUI(registerStatusRing, rotation, registered, listenerId);
return () => {
scheduleOnUI(unregisterStatusRing, registered, listenerId);
};
}, [active, listenerId, registered, rotation]);
return rotation;
}
@@ -1,35 +0,0 @@
import { useCallback, useLayoutEffect, useRef, type RefCallback } from "react";
import type { View as NativeView } from "react-native";
import { STATUS_RING_PERIOD_MS } from "@/components/status-ring/geometry";
const STATUS_RING_KEYFRAMES: PropertyIndexedKeyframes = {
transform: ["rotate(0deg)", "rotate(360deg)"],
};
const STATUS_RING_TIMING: KeyframeAnimationOptions = {
duration: STATUS_RING_PERIOD_MS,
easing: "linear",
iterations: Number.POSITIVE_INFINITY,
};
const STATUS_RING_TIMELINE_START_MS = 0;
export function useStatusRingAnimationRef(): RefCallback<NativeView> {
const arcElement = useRef<HTMLElement | null>(null);
const setArcElement = useCallback((instance: NativeView | null) => {
arcElement.current = instance instanceof HTMLElement ? instance : null;
}, []);
useLayoutEffect(() => {
const element = arcElement.current;
if (!element) {
return;
}
const animation = element.animate(STATUS_RING_KEYFRAMES, STATUS_RING_TIMING);
animation.startTime = STATUS_RING_TIMELINE_START_MS;
return () => {
animation.cancel();
};
}, []);
return setArcElement;
}
@@ -32,7 +32,7 @@ export interface StatusRingProps {
*/
export function StatusRingFrame({ backdrop, children }: StatusRingProps & { children: ReactNode }) {
return (
<View style={[styles.frame, getBackdropStyle(backdrop)]}>
<View style={[styles.frame, getBackdropStyle(backdrop)]} testID="status-ring">
<View style={styles.track} />
{children}
<View style={styles.centerDot} />
@@ -60,10 +60,9 @@ function getBackdropStyle(backdrop: SurfaceBackdrop | null | undefined) {
}
// The rotating quarter's geometry, deliberately plain React Native rather than Unistyles: on
// native this style lands on a Reanimated `Animated.View`, and applying a theme-tracked style to
// one crashes when the theme changes — Unistyles and Reanimated both mutate the same native node.
// See docs/unistyles.md. The colour it needs lives on `styles.arc`, one level in, on a view
// Reanimated never touches.
// native this style lands on an `Animated.View` the native animation driver writes to, and a
// theme-tracked style on the same node gives it two writers. See docs/unistyles.md. The colour it
// needs lives on `styles.arc`, one level in, on a view nothing animates.
export const rotatorStyles = RNStyleSheet.create({
rotator: {
position: "absolute",
@@ -26,17 +26,11 @@ export const STATUS_RING_FRAME_SIZE = STATUS_RING_SIZE + STATUS_RING_HALO_INSET
export const STATUS_RING_TRACK_OPACITY = 0.3;
export const STATUS_RING_HEAD_OPACITY = 0.9;
// One period for every ring in the app. Each platform owns one mount-independent timeline: web
// animations share an absolute document-timeline start, while native publishes this wall-clock
// phase from one UI-thread clock. A row that appears mid-flight therefore lands in step with the
// rings already turning.
// One period for every ring in the app. Each platform runs the rings off one clock that does not
// depend on when a ring mounted, so a row that appears mid-flight lands in step with the rings
// already turning.
export const STATUS_RING_PERIOD_MS = 900;
export function getStatusRingRotation(nowMs: number): number {
"worklet";
return ((nowMs % STATUS_RING_PERIOD_MS) / STATUS_RING_PERIOD_MS) * 360;
}
/**
* Re-anchors a corner status dot's offset for the ring that replaces it.
*
@@ -1,30 +1,31 @@
import { memo } from "react";
import { View } from "react-native";
import Animated, { useAnimatedStyle } from "react-native-reanimated";
import { Animated, View } from "react-native";
import { useIndicatorMotion } from "@/components/indicator-motion";
import { sharedIndicatorClock, useRunningClock } from "@/components/indicator-motion/clock";
import {
StatusRingFrame,
type StatusRingProps,
rotatorStyles,
styles,
} from "@/components/status-ring/frame";
import { useStatusRingRotation } from "@/components/status-ring/clock";
import { STATUS_RING_PERIOD_MS } from "@/components/status-ring/geometry";
/**
* Native running indicator. The rotation is published by one shared UI-thread clock rather than
* per-instance timing, so a ring that mounts mid-flight is already in phase — see `clock.ts`.
*
* The rotated view carries no theme-tracked style; the coloured arc is nested inside it. Putting
* a Unistyles style on a Reanimated view crashes on theme change (docs/unistyles.md).
*/
// One rotation for every ring in the app, so a row that appears mid-flight lands in step with the
// rings already turning.
const rotation = sharedIndicatorClock.cycle(STATUS_RING_PERIOD_MS).interpolate({
inputRange: [0, STATUS_RING_PERIOD_MS],
outputRange: ["0deg", "360deg"],
});
const turning = { transform: [{ rotate: rotation }] };
/** Native running indicator. The native animation driver turns the quarter; see `clock.ts`. */
export const StatusRing = memo(function StatusRing({ backdrop }: StatusRingProps) {
const rotation = useStatusRingRotation();
const rotatorStyle = useAnimatedStyle(() => ({
transform: [{ rotate: `${rotation.value}deg` }],
}));
const moving = useIndicatorMotion();
useRunningClock(sharedIndicatorClock, moving);
return (
<StatusRingFrame backdrop={backdrop}>
<Animated.View style={[rotatorStyles.rotator, rotatorStyle]}>
<Animated.View style={[rotatorStyles.rotator, moving && turning]}>
<View style={styles.arc} />
</Animated.View>
</StatusRingFrame>
@@ -1,20 +1,27 @@
import { memo } from "react";
import { View } from "react-native";
import { useIndicatorMotion } from "@/components/indicator-motion";
import { type IndicatorLoop, useIndicatorLoop } from "@/components/indicator-motion/loop.web";
import {
StatusRingFrame,
type StatusRingProps,
rotatorStyles,
styles,
} from "@/components/status-ring/frame";
import { useStatusRingAnimationRef } from "@/components/status-ring/clock.web";
import { STATUS_RING_PERIOD_MS } from "@/components/status-ring/geometry";
/**
* Web running indicator. A sidebar full of agents can hold dozens of these at once, so the browser
* drives the rotation from one absolute document-timeline epoch rather than from mount time — see
* `clock.web.ts`.
*/
// A sidebar full of agents can hold dozens of rings at once; the shared phase keeps them turning as
// one, and a row that appears mid-flight lands in step with the rings already turning.
const TURNING: IndicatorLoop = {
keyframes: [{ transform: "rotate(0deg)" }, { transform: "rotate(360deg)" }],
durationMs: STATUS_RING_PERIOD_MS,
phase: "shared",
};
/** Web running indicator. The browser's compositor turns the quarter; see `loop.web.ts`. */
export const StatusRing = memo(function StatusRing({ backdrop }: StatusRingProps) {
const rotatorRef = useStatusRingAnimationRef();
const moving = useIndicatorMotion();
const rotatorRef = useIndicatorLoop(moving ? TURNING : null);
return (
<StatusRingFrame backdrop={backdrop}>
@@ -1,184 +0,0 @@
import { useLayoutEffect, useMemo, useState } from "react";
import { View } from "react-native";
import Animated, {
makeMutable,
type SharedValue,
useAnimatedStyle,
useReducedMotion,
useSharedValue,
} from "react-native-reanimated";
import { scheduleOnUI } from "react-native-worklets";
import { useRetainedPanelActive } from "@/components/retained-panel";
import {
SYNCED_LOADER_DOT_COUNT,
getSyncedLoaderDotOpacity,
getSyncedLoaderStep,
} from "@/components/synced-loader-state";
const GRID_COLUMNS = 2;
const DOT_KEYS = Array.from({ length: SYNCED_LOADER_DOT_COUNT }, (_, i) => `dot-${i}`);
const sharedStep = makeMutable(0);
const activeLoaderCount = makeMutable(0);
const clockRunning = makeMutable(false);
let nextStepListenerId = 1;
function advanceSharedStep(): void {
"worklet";
if (activeLoaderCount.value === 0) {
clockRunning.value = false;
return;
}
const nextStep = getSyncedLoaderStep(Date.now());
if (sharedStep.value !== nextStep) {
sharedStep.value = nextStep;
}
requestAnimationFrame(advanceSharedStep);
}
function registerStepListener(
step: SharedValue<number>,
registered: SharedValue<boolean>,
listenerId: number,
): void {
"worklet";
if (registered.value) {
return;
}
registered.value = true;
step.value = getSyncedLoaderStep(Date.now());
sharedStep.addListener(listenerId, (nextStep) => {
step.value = nextStep;
});
activeLoaderCount.value += 1;
if (!clockRunning.value) {
clockRunning.value = true;
sharedStep.value = step.value;
requestAnimationFrame(advanceSharedStep);
}
}
function unregisterStepListener(registered: SharedValue<boolean>, listenerId: number): void {
"worklet";
if (!registered.value) {
return;
}
registered.value = false;
sharedStep.removeListener(listenerId);
activeLoaderCount.value -= 1;
}
function useSyncedLoaderStep(active: boolean, reduceMotion: boolean): SharedValue<number> {
// The local value lets retained loaders detach from the app-wide clock without
// unmounting their animated views or leaving hidden style worklets subscribed.
const step = useSharedValue(reduceMotion ? 0 : getSyncedLoaderStep(Date.now()));
const registered = useSharedValue(false);
const [listenerId] = useState(() => nextStepListenerId++);
useLayoutEffect(() => {
if (!active || reduceMotion) {
return;
}
scheduleOnUI(registerStepListener, step, registered, listenerId);
return () => {
scheduleOnUI(unregisterStepListener, registered, listenerId);
};
}, [active, listenerId, reduceMotion, registered, step]);
return step;
}
export function SyncedLoader({ size = 10, color }: { size?: number; color: string }) {
const active = useRetainedPanelActive();
const reduceMotion = useReducedMotion();
const step = useSyncedLoaderStep(active, reduceMotion);
// The 2x3 grid fills `size` exactly on its long axis: the dot is whatever is left after
// the two gaps, not a floored integer. Flooring cost the grid up to a third of a dot per
// row — at size 10 it drew 8pt of ink in a 10pt box and read as a small mark in a large
// slot. Fractional dots are fine here; these are sub-pixel radii on a moving glyph.
const gap = Math.max(1, Math.round(size * 0.12));
const dotSize = Math.max(2, (size - gap * 2) / 3);
const gridWidth = dotSize * 2 + gap;
const gridHeight = dotSize * 3 + gap * 2;
const gridStyle = useMemo(
() => ({ width: gridWidth, height: gridHeight }),
[gridHeight, gridWidth],
);
const containerStyle = useMemo(
() =>
({
width: size,
height: size,
alignItems: "center",
justifyContent: "center",
}) as const,
[size],
);
return (
<View style={containerStyle}>
<View style={gridStyle}>
{Array.from({ length: SYNCED_LOADER_DOT_COUNT }).map((_, dotIndex) => {
const rowIndex = Math.floor(dotIndex / GRID_COLUMNS);
const columnIndex = dotIndex % GRID_COLUMNS;
return (
<SpinnerDot
key={DOT_KEYS[dotIndex]}
color={color}
dotSize={dotSize}
dotIndex={dotIndex}
step={step}
left={columnIndex * (dotSize + gap)}
top={rowIndex * (dotSize + gap)}
/>
);
})}
</View>
</View>
);
}
function SpinnerDot({
color,
dotSize,
dotIndex,
step,
left,
top,
}: {
color: string;
dotSize: number;
dotIndex: number;
step: SharedValue<number>;
left: number;
top: number;
}) {
const animatedStyle = useAnimatedStyle(() => ({
opacity: getSyncedLoaderDotOpacity(step.value, dotIndex),
}));
const dotStyle = useMemo(
() => [
animatedStyle,
{
width: dotSize,
height: dotSize,
borderRadius: dotSize / 2,
backgroundColor: color,
position: "absolute" as const,
left,
top,
},
],
[animatedStyle, dotSize, color, left, top],
);
return <Animated.View style={dotStyle} />;
}
@@ -0,0 +1,58 @@
import { useEffect } from "react";
import { Animated, View } from "react-native";
import { useIndicatorMotion } from "@/components/indicator-motion";
import { type SyncedLoaderProps, useSyncedLoaderLayout } from "./layout";
import {
SYNCED_LOADER_DOT_COUNT,
SYNCED_LOADER_RESTING_STEP,
getSyncedLoaderDotOpacity,
} from "./state";
import { createSyncedLoaderStepTicker } from "./step-ticker";
const DOTS = Array.from({ length: SYNCED_LOADER_DOT_COUNT }, (_, dot) => dot);
const STEPS = DOTS;
// The step every loader in the app is on. It lives in the native animation driver: setting it
// updates the dots on the UI thread without a React render or a shadow tree commit.
const step = new Animated.Value(SYNCED_LOADER_RESTING_STEP, { useNativeDriver: true });
const ticker = createSyncedLoaderStepTicker((nextStep) => step.setValue(nextStep));
const blinking = DOTS.map((dot) => ({
opacity: step.interpolate({
inputRange: STEPS,
outputRange: STEPS.map((atStep) => getSyncedLoaderDotOpacity(atStep, dot)),
}),
}));
const resting = DOTS.map((dot) => ({
opacity: getSyncedLoaderDotOpacity(SYNCED_LOADER_RESTING_STEP, dot),
}));
/**
* Native loader. The step changes six times a cycle, so a timer wakes the JS thread six times a
* cycle and hands the step to the native animation driver. No frame callback runs between steps.
*/
export function SyncedLoader(props: SyncedLoaderProps) {
const layout = useSyncedLoaderLayout(props);
const moving = useIndicatorMotion();
const motion = moving ? blinking : resting;
useEffect(() => {
if (!moving) return;
return ticker.run();
}, [moving]);
return (
<View style={layout.container} testID="synced-loader">
<View style={layout.grid}>
{DOTS.map((dot) => (
<Animated.View
key={dot}
style={[layout.dots[dot], motion[dot]]}
testID="synced-loader-dot"
/>
))}
</View>
</View>
);
}
@@ -0,0 +1,55 @@
import { View, type ViewStyle } from "react-native";
import { useIndicatorMotion } from "@/components/indicator-motion";
import { type IndicatorLoop, useIndicatorLoop } from "@/components/indicator-motion/loop.web";
import { type SyncedLoaderProps, useSyncedLoaderLayout } from "./layout";
import {
SYNCED_LOADER_DOT_COUNT,
SYNCED_LOADER_DURATION_MS,
SYNCED_LOADER_RESTING_STEP,
getSyncedLoaderDotOpacity,
} from "./state";
const DOTS = Array.from({ length: SYNCED_LOADER_DOT_COUNT }, (_, dot) => dot);
// One keyframe per step, held until the next: `step-end` makes the opacity jump instead of fade.
// The shared phase keeps every loader in the app on the same step.
const BLINKING: IndicatorLoop[] = DOTS.map((dot) => ({
keyframes: [
...DOTS.map((step) => ({
offset: step / SYNCED_LOADER_DOT_COUNT,
opacity: getSyncedLoaderDotOpacity(step, dot),
easing: "step-end",
})),
{ offset: 1, opacity: getSyncedLoaderDotOpacity(0, dot) },
],
durationMs: SYNCED_LOADER_DURATION_MS,
phase: "shared",
}));
const RESTING = DOTS.map(
(dot): ViewStyle => ({ opacity: getSyncedLoaderDotOpacity(SYNCED_LOADER_RESTING_STEP, dot) }),
);
/**
* Web loader. Each dot steps through its six opacities on the browser's compositor, which draws a
* frame when a step changes and nothing in between; see `loop.web.ts`.
*/
export function SyncedLoader(props: SyncedLoaderProps) {
const layout = useSyncedLoaderLayout(props);
const moving = useIndicatorMotion();
return (
<View style={layout.container} testID="synced-loader">
<View style={layout.grid}>
{DOTS.map((dot) => (
<Dot key={dot} dot={dot} style={layout.dots[dot]} moving={moving} />
))}
</View>
</View>
);
}
function Dot({ dot, style, moving }: { dot: number; style: ViewStyle; moving: boolean }) {
const dotRef = useIndicatorLoop(moving ? BLINKING[dot] : null);
return <View ref={dotRef} style={[style, RESTING[dot]]} testID="synced-loader-dot" />;
}
@@ -0,0 +1,43 @@
import { useMemo } from "react";
import type { ViewStyle } from "react-native";
import { SYNCED_LOADER_DOT_COUNT } from "./state";
const GRID_COLUMNS = 2;
export interface SyncedLoaderProps {
size?: number;
color: string;
}
export interface SyncedLoaderLayout {
container: ViewStyle;
grid: ViewStyle;
/** One entry per dot, in the order the opacity states list them. */
dots: ViewStyle[];
}
/** Where the loader's six dots sit and what they look like. The platform files own how they blink. */
export function useSyncedLoaderLayout({ size = 10, color }: SyncedLoaderProps): SyncedLoaderLayout {
return useMemo(() => {
// The 2x3 grid fills `size` exactly on its long axis: the dot is whatever is left after
// the two gaps, not a floored integer. Flooring cost the grid up to a third of a dot per
// row — at size 10 it drew 8pt of ink in a 10pt box and read as a small mark in a large
// slot. Fractional dots are fine here; these are sub-pixel radii on a moving glyph.
const gap = Math.max(1, Math.round(size * 0.12));
const dotSize = Math.max(2, (size - gap * 2) / 3);
return {
container: { width: size, height: size, alignItems: "center", justifyContent: "center" },
grid: { width: dotSize * 2 + gap, height: dotSize * 3 + gap * 2 },
dots: Array.from({ length: SYNCED_LOADER_DOT_COUNT }, (_, dot) => ({
position: "absolute",
left: (dot % GRID_COLUMNS) * (dotSize + gap),
top: Math.floor(dot / GRID_COLUMNS) * (dotSize + gap),
width: dotSize,
height: dotSize,
borderRadius: dotSize / 2,
backgroundColor: color,
})),
};
}, [color, size]);
}
@@ -1,5 +1,5 @@
import { describe, expect, test } from "vitest";
import { getSyncedLoaderDotOpacity, getSyncedLoaderStep } from "./synced-loader-state";
import { getSyncedLoaderDotOpacity, getSyncedLoaderStep } from "./state";
describe("synced loader state", () => {
test("advances through six wall-clock-aligned steps every 950 milliseconds", () => {
@@ -1,4 +1,4 @@
const SYNCED_LOADER_DURATION_MS = 950;
export const SYNCED_LOADER_DURATION_MS = 950;
export const SYNCED_LOADER_DOT_COUNT = 6;
const SYNCED_LOADER_OPACITY_STATES = [
@@ -10,13 +10,22 @@ const SYNCED_LOADER_OPACITY_STATES = [
[0, 0, 1, 0.34, 0.78, 0.56],
] as const;
// The frame a loader rests on when it is not moving.
export const SYNCED_LOADER_RESTING_STEP = 0;
export function getSyncedLoaderStep(nowMs: number): number {
"worklet";
const elapsedMs = nowMs % SYNCED_LOADER_DURATION_MS;
return Math.floor((elapsedMs * SYNCED_LOADER_DOT_COUNT) / SYNCED_LOADER_DURATION_MS);
}
/** How long after `nowMs` the loader shows its next step. Always at least a millisecond. */
export function getSyncedLoaderStepRemainingMs(nowMs: number): number {
const elapsedMs = nowMs % SYNCED_LOADER_DURATION_MS;
const nextStepAtMs =
((getSyncedLoaderStep(nowMs) + 1) * SYNCED_LOADER_DURATION_MS) / SYNCED_LOADER_DOT_COUNT;
return Math.max(1, Math.ceil(nextStepAtMs - elapsedMs));
}
export function getSyncedLoaderDotOpacity(step: number, dot: number): number {
"worklet";
return SYNCED_LOADER_OPACITY_STATES[step]?.[dot] ?? 0;
}
@@ -0,0 +1,93 @@
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import { createSyncedLoaderStepTicker } from "./step-ticker";
interface PublishedStep {
step: number;
atMs: number;
}
function startRecordingTicker() {
const published: PublishedStep[] = [];
const ticker = createSyncedLoaderStepTicker((step) => {
published.push({ step, atMs: Date.now() });
});
return { ticker, published };
}
describe("synced loader step ticker", () => {
beforeEach(() => {
vi.useFakeTimers();
vi.setSystemTime(0);
});
afterEach(() => {
vi.useRealTimers();
});
test("wakes once per step, six times a cycle", () => {
const { ticker, published } = startRecordingTicker();
const stop = ticker.run();
vi.advanceTimersByTime(949);
stop();
expect(published).toEqual([
{ step: 0, atMs: 0 },
{ step: 1, atMs: 159 },
{ step: 2, atMs: 317 },
{ step: 3, atMs: 475 },
{ step: 4, atMs: 634 },
{ step: 5, atMs: 792 },
]);
});
test("starts mid-cycle on the step the wall clock is on", () => {
vi.setSystemTime(950 * 4 + 500);
const { ticker, published } = startRecordingTicker();
const stop = ticker.run();
vi.advanceTimersByTime(140);
stop();
expect(published).toEqual([
{ step: 3, atMs: 950 * 4 + 500 },
{ step: 4, atMs: 950 * 4 + 634 },
]);
});
test("catches up to the wall clock after a late wake-up instead of drifting", () => {
const { ticker, published } = startRecordingTicker();
const stop = ticker.run();
// The thread is busy for 400 ms, so the wake-up due at 159 ms happens at 559 ms.
vi.setSystemTime(400);
vi.advanceTimersByTime(159);
vi.advanceTimersByTime(75);
stop();
expect(published).toEqual([
{ step: 0, atMs: 0 },
{ step: 3, atMs: 559 },
{ step: 4, atMs: 634 },
]);
});
test("keeps one timer for every loader and stops with the last one", () => {
const { ticker, published } = startRecordingTicker();
const stopFirst = ticker.run();
const stopSecond = ticker.run();
vi.advanceTimersByTime(160);
expect(published.map((entry) => entry.step)).toEqual([0, 1]);
expect(vi.getTimerCount()).toBe(1);
stopFirst();
vi.advanceTimersByTime(158);
expect(published.map((entry) => entry.step)).toEqual([0, 1, 2]);
stopSecond();
expect(vi.getTimerCount()).toBe(0);
vi.advanceTimersByTime(950);
expect(published.map((entry) => entry.step)).toEqual([0, 1, 2]);
});
});
@@ -0,0 +1,42 @@
import { getSyncedLoaderStep, getSyncedLoaderStepRemainingMs } from "./state";
/**
* Publishes the loader's step each time it changes, and at no other time.
*
* The loader has six frames a cycle, so it needs six wake-ups a cycle. Each wake-up reads the wall
* clock and sleeps until the next step is due, which keeps a late timer from pushing every later
* step back and keeps every loader in the app on the same step.
*/
export interface SyncedLoaderStepTicker {
/** Ticks until the returned function is called. Publishes the current step at once. */
run(): () => void;
}
export function createSyncedLoaderStepTicker(
publish: (step: number) => void,
): SyncedLoaderStepTicker {
let runners = 0;
let timer: ReturnType<typeof setTimeout> | null = null;
function tick(): void {
const nowMs = Date.now();
publish(getSyncedLoaderStep(nowMs));
timer = setTimeout(tick, getSyncedLoaderStepRemainingMs(nowMs));
}
return {
run() {
runners += 1;
if (timer === null) {
tick();
}
return () => {
runners -= 1;
if (runners === 0 && timer !== null) {
clearTimeout(timer);
timer = null;
}
};
},
};
}
+138 -160
View File
@@ -25,18 +25,22 @@ import {
uploadFileAttachments,
cancelComposerAgent,
dispatchComposerAgentMessage,
enqueueComposerAgentMessage,
editQueuedComposerMessage,
findForgeItemByOption,
isAttachmentSelectedForForgeItem,
openComposerAttachment,
pickAndPersistImages,
queueComposerMessage,
removeComposerAttachmentAtIndex,
sendQueuedComposerMessageNow,
toggleForgeAttachment,
toggleForgeAttachmentFromPicker,
type MessageSubmissionWriter,
type AttachmentPersister,
type ComposerCancelClient,
type ComposerSendClient,
type QueueWriter,
type QueuedComposerMessage,
} from "./actions";
const imageMetadata: AttachmentMetadata = {
@@ -180,7 +184,7 @@ interface FakeSendCall {
text: string;
options: {
messageId: string;
activeTurnBehavior?: "interrupt" | "steer" | "queue";
activeTurnBehavior?: "interrupt" | "steer";
images?: Array<{ data: string; mimeType: string }>;
attachments: AgentAttachment[];
};
@@ -302,6 +306,19 @@ function writeSubmission(fake: FakeStream, agentId: string, state: FakeSubmissio
submissionsByFakeStream.set(fake, submissions);
}
function createFakeQueue(
initial: Map<string, QueuedComposerMessage[]> = new Map(),
): QueueWriter & { state: Map<string, QueuedComposerMessage[]> } {
const fake: QueueWriter & { state: Map<string, QueuedComposerMessage[]> } = {
state: new Map(initial),
read: (agentId) => fake.state.get(agentId) ?? [],
write: (updater) => {
fake.state = updater(fake.state);
},
};
return fake;
}
const passthroughUploadImages = async (
images: AttachmentMetadata[],
): Promise<UploadedFileAttachment[]> =>
@@ -738,186 +755,147 @@ describe("dispatchComposerAgentMessage", () => {
});
});
describe("enqueueComposerAgentMessage", () => {
it("hands a trimmed message to the host queue without adding a timeline row", async () => {
const client = createFakeSendClient();
const review = reviewWorkspaceAttachment("Queued review.");
await enqueueComposerAgentMessage({
client,
describe("queueComposerMessage", () => {
it("queues a trimmed message under the agent id and returns the new entry", () => {
const queue = createFakeQueue();
const result = queueComposerMessage({
agentId: "agent",
text: " queue this ",
attachments: [{ kind: "image", metadata: imageWithId("img-queue") }, review],
uploadImages: passthroughUploadImages,
text: " draft ",
attachments: [],
queue,
});
expect(client.calls).toEqual([
{
agentId: "agent",
text: "queue this",
options: {
messageId: expect.any(String),
activeTurnBehavior: "queue",
attachments: [
review.attachment,
expect.objectContaining({
type: "uploaded_file",
id: "upload_img-queue",
role: "image",
}),
],
},
},
expect(result.queued?.text).toBe("draft");
expect(queue.state.get("agent")).toEqual([
{ id: result.queued?.id, text: "draft", attachments: [] },
]);
});
it("sends nothing for an empty message with no attachments", async () => {
const client = createFakeSendClient();
await enqueueComposerAgentMessage({ client, agentId: "agent", text: " ", attachments: [] });
expect(client.calls).toEqual([]);
});
it("queues a staged provider switch with the message so the host runs it on that provider", async () => {
const client = createFakeSendClient();
const switches: unknown[] = [];
let queuedSwitches = 0;
const input: Parameters<typeof enqueueComposerAgentMessage>[0] = {
client: {
...client,
switchAgentProvider: async (agentId, options) => {
switches.push({ agentId, options });
return {};
},
},
it("does not queue an empty message with no attachments", () => {
const queue = createFakeQueue();
const result = queueComposerMessage({
agentId: "agent",
text: "do Z",
text: " ",
attachments: [],
stagedProviderSwitch: {
provider: "codex",
model: "gpt-5.4",
modeId: "auto",
thinkingOptionId: null,
providerOptions: { fast_mode: true },
},
onProviderSwitchQueued: () => {
queuedSwitches += 1;
},
};
await enqueueComposerAgentMessage(input);
// Nothing to send leaves the switch with the composer.
await enqueueComposerAgentMessage({ ...input, text: " " });
expect(queuedSwitches).toBe(1);
expect(client.calls).toEqual([]);
expect(switches).toEqual([
{
agentId: "agent",
options: {
provider: "codex",
model: "gpt-5.4",
modeId: "auto",
thinkingOptionId: null,
providerOptions: { fast_mode: true },
text: "do Z",
messageId: expect.any(String),
activeTurnBehavior: "queue",
attachments: [],
},
},
]);
queue,
});
expect(result.queued).toBeNull();
expect(queue.state.get("agent")).toBeUndefined();
});
it("rejects when the host refuses the message", async () => {
const rejection = new Error("Agent not found");
const client = createFakeSendClient({ rejection });
it("captures workspace review attachments at queue time alongside user attachments", () => {
const queue = createFakeQueue();
const review = reviewWorkspaceAttachment("Initial queued review.");
const image = imageWithId("img-queue");
queueComposerMessage({
agentId: "agent",
text: "queue this",
attachments: [{ kind: "image", metadata: image }, review],
queue,
});
await expect(
enqueueComposerAgentMessage({ client, agentId: "agent", text: "hello", attachments: [] }),
).rejects.toBe(rejection);
expect(queue.state.get("agent")?.[0]?.attachments).toEqual([
{ kind: "image", metadata: image },
review,
]);
});
});
describe("attachments restored from a queued message", () => {
const uploadedImage: Extract<AgentAttachment, { type: "uploaded_file" }> = {
type: "uploaded_file",
id: "upload_restored",
fileName: "photo.png",
mimeType: "image/png",
size: 42,
path: "/home/user/.paseo/uploads/upload_restored/photo.png",
role: "image",
};
const restoredImage: UserComposerAttachment = {
kind: "agent_attachment",
attachment: uploadedImage,
};
const restoredIssue: UserComposerAttachment = {
kind: "agent_attachment",
attachment: {
type: "forge_issue",
mimeType: "application/paseo-forge-issue",
forge: "github",
number: issueItem.number,
title: issueItem.title,
url: issueItem.url,
},
};
describe("editQueuedComposerMessage", () => {
it("returns null and leaves the queue untouched when the message id is missing", () => {
const queue = createFakeQueue(
new Map([["agent", [{ id: "other", text: "other", attachments: [] }]]]),
);
const result = editQueuedComposerMessage({ agentId: "agent", messageId: "missing", queue });
expect(result).toBeNull();
expect(queue.state.get("agent")).toHaveLength(1);
});
it("queues the same uploaded image again without uploading it", async () => {
const client = createFakeSendClient();
it("returns the text and only user attachments, removing the queued entry", () => {
const review = reviewWorkspaceAttachment("Queued snapshot.");
const image = imageWithId("img-queued-edit");
const queue = createFakeQueue(
new Map([
[
"agent",
[
{
id: "msg-1",
text: "queued draft",
attachments: [{ kind: "image", metadata: image }, review],
},
],
],
]),
);
await enqueueComposerAgentMessage({
client,
agentId: "agent",
text: "again",
attachments: [restoredImage],
const result = editQueuedComposerMessage({ agentId: "agent", messageId: "msg-1", queue });
expect(result).toEqual({
text: "queued draft",
attachments: [{ kind: "image", metadata: image }],
});
expect(client.uploadCalls).toEqual([]);
expect(client.calls[0]?.options.attachments).toEqual([uploadedImage]);
expect(queue.state.get("agent")).toEqual([]);
});
});
it("shows a sent uploaded image as an image on the optimistic message", async () => {
const client = createFakeSendClient();
const stream = createFakeStream();
await dispatchComposerAgentMessage({
client,
describe("sendQueuedComposerMessageNow", () => {
it("returns missing without submitting when the message id is gone", async () => {
const queue = createFakeQueue();
const submitted: Array<{ text: string; attachments: ComposerAttachment[] }> = [];
const result = await sendQueuedComposerMessageNow({
agentId: "agent",
text: "look",
attachments: [restoredImage],
submission: stream,
});
const { type: _type, role: _role, ...upload } = uploadedImage;
const shown = [...(stream.tail.get("agent") ?? []), ...(stream.head.get("agent") ?? [])];
expect(shown).toEqual([
expect.objectContaining({ images: [{ ...upload, storageType: "daemon-upload" }] }),
]);
expect(client.uploadCalls).toEqual([]);
expect(client.calls[0]?.options.attachments).toEqual([uploadedImage]);
});
it("counts a restored forge item as selected and toggles it off", () => {
expect(isAttachmentSelectedForForgeItem([restoredIssue], issueItem)).toBe(true);
expect(isAttachmentSelectedForForgeItem([restoredIssue], prItem)).toBe(false);
expect(toggleForgeAttachment([restoredIssue], issueItem)).toEqual([]);
});
it("opens the URL of a restored forge item", () => {
const urls: string[] = [];
openComposerAttachment({
attachment: restoredIssue,
setLightboxMetadata: () => {
throw new Error("unexpected lightbox call");
messageId: "msg-1",
queue,
submitMessage: async (input) => {
submitted.push(input);
},
openWorkspaceAttachment: () => false,
openExternalUrl: (url) => urls.push(url),
});
expect(urls).toEqual([issueItem.url]);
expect(result).toEqual({ status: "missing" });
expect(submitted).toEqual([]);
});
it("removes the queued entry and submits its text + attachments", async () => {
const review = reviewWorkspaceAttachment("Queued for send.");
const queue = createFakeQueue(
new Map([["agent", [{ id: "msg-1", text: "send me", attachments: [review] }]]]),
);
const submitted: Array<{ text: string; attachments: ComposerAttachment[] }> = [];
const result = await sendQueuedComposerMessageNow({
agentId: "agent",
messageId: "msg-1",
queue,
submitMessage: async (input) => {
submitted.push(input);
},
});
expect(result).toEqual({ status: "submitted" });
expect(queue.state.get("agent")).toEqual([]);
expect(submitted).toEqual([{ text: "send me", attachments: [review] }]);
});
it("restores the queued entry to the front and surfaces the error message on failure", async () => {
const queue = createFakeQueue(
new Map([
[
"agent",
[
{ id: "msg-1", text: "first", attachments: [] },
{ id: "msg-2", text: "second", attachments: [] },
],
],
]),
);
const result = await sendQueuedComposerMessageNow({
agentId: "agent",
messageId: "msg-1",
queue,
submitMessage: async () => {
throw new Error("network down");
},
});
expect(result).toEqual({ status: "failed", errorMessage: "network down" });
const state = queue.state.get("agent");
expect(state?.map((m) => m.id)).toEqual(["msg-1", "msg-2"]);
});
});
+155 -83
View File
@@ -4,8 +4,6 @@ import { FILE_UPLOAD_MAX_BYTES } from "@/attachments/upload-limit";
import type { AgentProvider, ProviderOptions } from "@getpaseo/protocol/agent-types";
import type {
ActiveTurnBehavior,
AgentActiveTurnBehavior,
AgentAttachment,
AgentSnapshotPayload,
ForgeSearchItem,
UploadedFileAttachment,
@@ -17,8 +15,10 @@ import type {
ComposerAttachment,
UserComposerAttachment,
} from "@/attachments/types";
import { isWorkspaceAttachment } from "@/attachments/workspace-attachment-utils";
import { forgeItemKey } from "@/composer/attachments/forge-item-key";
import {
isWorkspaceAttachment,
userAttachmentsOnly,
} from "@/attachments/workspace-attachment-utils";
import {
splitComposerAttachmentsForSubmit,
type ComposerAttachmentSubmitFormat,
@@ -27,7 +27,6 @@ import {
createPendingProviderSwitchItem,
createUserMessage,
generateMessageId,
toDaemonUploadedImageAttachments,
type ProviderSwitchItem,
type UserMessageItem,
} from "@/types/stream";
@@ -35,6 +34,12 @@ import type { MessageSubmissionRejectionOutcome } from "@/composer/submission/mo
import type { PickedImageAttachmentInput } from "@/hooks/image-attachment-picker";
import { i18n } from "@/i18n/i18next";
export interface QueuedComposerMessage {
id: string;
text: string;
attachments: ComposerAttachment[];
}
export interface AttachmentPersister {
persistFromBlob: (input: {
blob: Blob;
@@ -60,7 +65,7 @@ export interface ComposerSendClient {
text: string,
options: {
messageId: string;
activeTurnBehavior?: AgentActiveTurnBehavior;
activeTurnBehavior?: ActiveTurnBehavior;
images?: Array<{ data: string; mimeType: string }>;
attachments: ReturnType<typeof splitComposerAttachmentsForSubmit>["attachments"];
},
@@ -77,7 +82,6 @@ export interface ComposerSendClient {
messageId: string;
images?: Array<{ data: string; mimeType: string }>;
attachments?: ReturnType<typeof splitComposerAttachmentsForSubmit>["attachments"];
activeTurnBehavior?: "queue";
},
) => Promise<{ agent?: AgentSnapshotPayload }>;
uploadFile: (input: { fileName: string; mimeType: string; bytes: Uint8Array }) => Promise<{
@@ -102,6 +106,13 @@ export interface MessageSubmissionWriter {
reject: (agentId: string, clientMessageId: string) => MessageSubmissionRejectionOutcome;
}
export interface QueueWriter {
read: (agentId: string) => QueuedComposerMessage[];
write: (
updater: (prev: Map<string, QueuedComposerMessage[]>) => Map<string, QueuedComposerMessage[]>,
) => void;
}
export async function pickAndPersistImages(input: {
pickImages: () => Promise<PickedImageAttachmentInput[] | null>;
persister: Pick<
@@ -247,13 +258,12 @@ export async function dispatchComposerAgentMessage(
});
const clientMessageId = generateMessageId();
const timestamp = new Date();
const sent = separateUploadedImages(wirePayload.attachments);
const userMessage = createUserMessage({
clientMessageId,
text: input.text,
timestamp,
images: [...wirePayload.images, ...sent.images],
attachments: sent.attachments,
images: wirePayload.images,
attachments: wirePayload.attachments,
...(input.activeTurnBehavior === "steer" && input.activeTurnId && !input.stagedProviderSwitch
? { turnId: input.activeTurnId }
: {}),
@@ -265,7 +275,12 @@ export async function dispatchComposerAgentMessage(
pendingProviderSwitch ? { providerSwitch: pendingProviderSwitch } : undefined,
);
try {
const imagePayload = await prepareImagePayload(input, wirePayload.images);
const imagePayload = input.uploadImages
? { attachments: await input.uploadImages(wirePayload.images) }
: await prepareImageAttachmentsForSend({
client: input.client,
images: wirePayload.images,
});
if (input.stagedProviderSwitch && input.client.switchAgentProvider) {
const result = await input.client.switchAgentProvider(input.agentId, {
provider: input.stagedProviderSwitch.provider,
@@ -298,70 +313,108 @@ export async function dispatchComposerAgentMessage(
}
}
async function prepareImagePayload(
input: Pick<DispatchComposerAgentMessageInput, "client" | "uploadImages">,
images: AttachmentMetadata[],
) {
if (input.uploadImages) return { attachments: await input.uploadImages(images) };
return await prepareImageAttachmentsForSend({ client: input.client, images });
export interface QueueComposerMessageInput {
agentId: string;
text: string;
attachments: ComposerAttachment[];
queue: QueueWriter;
}
/** Images the host already holds render as images, the way its timeline echo does. */
function separateUploadedImages(attachments: AgentAttachment[]) {
const uploads: UploadedFileAttachment[] = [];
const rest: AgentAttachment[] = [];
for (const attachment of attachments) {
if (attachment.type === "uploaded_file" && attachment.role === "image") {
uploads.push(attachment);
} else {
rest.push(attachment);
}
export interface QueueComposerMessageResult {
queued: QueuedComposerMessage | null;
}
export function queueComposerMessage(input: QueueComposerMessageInput): QueueComposerMessageResult {
const trimmed = input.text.trim();
if (!trimmed && input.attachments.length === 0) {
return { queued: null };
}
const images = toDaemonUploadedImageAttachments(
uploads.map(({ id, fileName, mimeType, size, path }) => ({
id,
fileName,
mimeType,
size,
path,
})),
);
return { images: images ?? [], attachments: rest };
}
/**
* Hands a message to the host's queue. The timeline gets no row until the host dispatches it;
* until then the queue track shows it. A staged provider switch goes with the message: the host
* switches when the message's turn comes.
*/
export async function enqueueComposerAgentMessage(
input: Omit<
DispatchComposerAgentMessageInput,
"submission" | "activeTurnBehavior" | "activeTurnId" | "onProviderSwitchCommitted"
> & { onProviderSwitchQueued?: () => void },
): Promise<void> {
const text = input.text.trim();
if (!text && input.attachments.length === 0) return;
const wirePayload = splitComposerAttachmentsForSubmit(input.attachments, {
format: input.attachmentSubmitFormat,
});
const imagePayload = await prepareImagePayload(input, wirePayload.images);
const queued = {
messageId: generateMessageId(),
activeTurnBehavior: "queue" as const,
...(imagePayload.images ? { images: imagePayload.images } : {}),
attachments: [...wirePayload.attachments, ...(imagePayload.attachments ?? [])],
const item: QueuedComposerMessage = {
id: generateMessageId(),
text: trimmed,
attachments: input.attachments,
};
if (input.stagedProviderSwitch && input.client.switchAgentProvider) {
await input.client.switchAgentProvider(input.agentId, {
...input.stagedProviderSwitch,
...queued,
text,
input.queue.write((prev) => {
const next = new Map(prev);
next.set(input.agentId, [...(prev.get(input.agentId) ?? []), item]);
return next;
});
return { queued: item };
}
export interface EditQueuedComposerMessageInput {
agentId: string;
messageId: string;
queue: QueueWriter;
}
export interface EditQueuedComposerMessageResult {
text: string;
attachments: UserComposerAttachment[];
}
export function editQueuedComposerMessage(
input: EditQueuedComposerMessageInput,
): EditQueuedComposerMessageResult | null {
const item = input.queue.read(input.agentId).find((q) => q.id === input.messageId);
if (!item) return null;
input.queue.write((prev) => {
const next = new Map(prev);
next.set(
input.agentId,
(prev.get(input.agentId) ?? []).filter((q) => q.id !== input.messageId),
);
return next;
});
return {
text: item.text,
attachments: userAttachmentsOnly(item.attachments),
};
}
export interface SendQueuedComposerMessageNowInput {
agentId: string;
messageId: string;
queue: QueueWriter;
submitMessage: (input: { text: string; attachments: ComposerAttachment[] }) => Promise<void>;
failedToSendMessage?: string;
}
export type SendQueuedComposerMessageNowResult =
| { status: "missing" }
| { status: "submitted" }
| { status: "failed"; errorMessage: string };
export async function sendQueuedComposerMessageNow(
input: SendQueuedComposerMessageNowInput,
): Promise<SendQueuedComposerMessageNowResult> {
const item = input.queue.read(input.agentId).find((q) => q.id === input.messageId);
if (!item) return { status: "missing" };
input.queue.write((prev) => {
const next = new Map(prev);
next.set(
input.agentId,
(prev.get(input.agentId) ?? []).filter((q) => q.id !== input.messageId),
);
return next;
});
try {
await input.submitMessage({ text: item.text, attachments: item.attachments });
return { status: "submitted" };
} catch (error) {
input.queue.write((prev) => {
const next = new Map(prev);
next.set(input.agentId, [item, ...(prev.get(input.agentId) ?? [])]);
return next;
});
input.onProviderSwitchQueued?.();
return;
return {
status: "failed",
errorMessage:
error instanceof Error
? error.message
: (input.failedToSendMessage ?? i18n.t("composer.errors.failedToSend")),
};
}
await input.client.sendAgentMessage(input.agentId, text, queued);
}
export interface OpenComposerAttachmentInput {
@@ -379,13 +432,6 @@ export function openComposerAttachment(input: OpenComposerAttachmentInput): void
if (input.attachment.kind === "file" || input.attachment.kind === "workspace_file") {
return;
}
if (input.attachment.kind === "agent_attachment") {
// An uploaded image opens through its pill, which holds the downloaded copy.
if ("url" in input.attachment.attachment) {
input.openExternalUrl(input.attachment.attachment.url);
}
return;
}
if (isWorkspaceAttachment(input.attachment)) {
input.openWorkspaceAttachment({ attachment: input.attachment });
return;
@@ -399,11 +445,31 @@ export function buildForgeAttachment(item: ForgeSearchItem): UserComposerAttachm
: { kind: "forge_issue", item };
}
function isForgeAttachment(
attachment: UserComposerAttachment,
): attachment is Extract<
UserComposerAttachment,
{ kind: "forge_issue" | "forge_change_request" | "github_issue" | "github_pr" }
> {
return (
attachment.kind === "forge_issue" ||
attachment.kind === "forge_change_request" ||
// COMPAT(githubAttachmentKinds): accept legacy persisted attachment kinds
// until 2027-01-17, when supported floors are >= v0.2.0 and old drafts no
// longer require them.
attachment.kind === "github_issue" ||
attachment.kind === "github_pr"
);
}
export function toggleForgeAttachment(
current: UserComposerAttachment[],
item: ForgeSearchItem,
): UserComposerAttachment[] {
const matches = (attachment: UserComposerAttachment) => isSameForgeItem(attachment, item);
const matches = (attachment: UserComposerAttachment) =>
isForgeAttachment(attachment) &&
attachment.item.kind === item.kind &&
attachment.item.number === item.number;
if (current.some(matches)) {
return current.filter((attachment) => !matches(attachment));
}
@@ -421,7 +487,12 @@ export function toggleForgeAttachmentFromPicker({
item,
markForgeAttachmentRemoved,
}: ToggleForgeAttachmentFromPickerInput): UserComposerAttachment[] {
const existingAttachment = current.find((attachment) => isSameForgeItem(attachment, item));
const existingAttachment = current.find(
(attachment) =>
isForgeAttachment(attachment) &&
attachment.item.kind === item.kind &&
attachment.item.number === item.number,
);
if (existingAttachment) {
markForgeAttachmentRemoved(existingAttachment);
}
@@ -439,9 +510,10 @@ export function isAttachmentSelectedForForgeItem(
current: readonly ComposerAttachment[],
item: ForgeSearchItem,
): boolean {
return current.some((attachment) => isSameForgeItem(attachment, item));
}
function isSameForgeItem(attachment: ComposerAttachment, item: ForgeSearchItem): boolean {
return forgeItemKey(attachment) === `${item.kind}:${item.number}`;
return userAttachmentsOnly(current).some(
(attachment) =>
isForgeAttachment(attachment) &&
attachment.item.kind === item.kind &&
attachment.item.number === item.number,
);
}
@@ -1,33 +0,0 @@
import type { ComposerAttachment } from "@/attachments/types";
import type { AgentAttachment } from "@getpaseo/protocol/messages";
/** `issue:101` or `change_request:202` for an attachment that points at a forge item. */
export function forgeItemKey(attachment: ComposerAttachment | undefined): string | null {
switch (attachment?.kind) {
case "forge_issue":
case "forge_change_request":
// COMPAT(githubAttachmentKinds): accept legacy persisted attachment kinds
// until 2027-01-17, when supported floors are >= v0.2.0 and old drafts no
// longer require them.
case "github_issue":
case "github_pr":
return `${attachment.item.kind}:${attachment.item.number}`;
case "agent_attachment":
return agentAttachmentForgeKey(attachment.attachment);
default:
return null;
}
}
function agentAttachmentForgeKey(attachment: AgentAttachment): string | null {
switch (attachment.type) {
case "forge_issue":
case "github_issue":
return `issue:${attachment.number}`;
case "forge_change_request":
case "github_pr":
return `change_request:${attachment.number}`;
default:
return null;
}
}
@@ -1,102 +0,0 @@
import { useCallback, useMemo, type ReactElement } from "react";
import { useTranslation } from "react-i18next";
import {
AttachmentLabel,
AttachmentPill,
AttachmentThumbnail,
AttachmentThumbnailPlaceholder,
} from "@/components/attachment-pill";
import { getAgentAttachmentPillContent } from "@/attachments/attachment-pill-content";
import type { ComposerAttachment } from "@/attachments/types";
import { useDaemonUploadedImage } from "@/attachments/use-daemon-uploaded-image";
import { useHostRuntimeClient } from "@/runtime/host-runtime";
import type { UploadedFileAttachment } from "@getpaseo/protocol/messages";
type RestoredAttachment = Extract<ComposerAttachment, { kind: "agent_attachment" }>;
interface RestoredAttachmentPillProps {
serverId: string;
attachment: RestoredAttachment;
index: number;
disabled: boolean;
onOpen: (attachment: ComposerAttachment) => void;
onRemove: (index: number) => void;
openImageLabel: string;
removeImageLabel: string;
}
/** The tray pill for an attachment taken back from a queued message. */
export function RestoredAttachmentPill(props: RestoredAttachmentPillProps): ReactElement {
const wire = props.attachment.attachment;
if (wire.type === "uploaded_file" && wire.role === "image") {
return <RestoredImagePill {...props} upload={wire} />;
}
return <RestoredLabelPill {...props} />;
}
/** An image the host holds. It is downloaded to preview it, and sent again by reference. */
function RestoredImagePill({
serverId,
upload,
index,
disabled,
onOpen,
onRemove,
openImageLabel,
removeImageLabel,
}: RestoredAttachmentPillProps & { upload: UploadedFileAttachment }): ReactElement {
const client = useHostRuntimeClient(serverId);
const image = useMemo(
() => ({
id: upload.id,
fileName: upload.fileName,
mimeType: upload.mimeType,
size: upload.size,
path: upload.path,
storageType: "daemon-upload" as const,
}),
[upload],
);
const metadata = useDaemonUploadedImage({ image, client, serverId });
const handleOpen = useCallback(() => {
if (metadata) onOpen({ kind: "image", metadata });
}, [metadata, onOpen]);
const handleRemove = useCallback(() => onRemove(index), [onRemove, index]);
return (
<AttachmentPill
testID="composer-image-attachment-pill"
onOpen={handleOpen}
onRemove={handleRemove}
openAccessibilityLabel={openImageLabel}
removeAccessibilityLabel={removeImageLabel}
disabled={disabled}
>
{metadata ? <AttachmentThumbnail metadata={metadata} /> : <AttachmentThumbnailPlaceholder />}
</AttachmentPill>
);
}
function RestoredLabelPill({
attachment,
index,
disabled,
onOpen,
onRemove,
}: RestoredAttachmentPillProps): ReactElement {
const { t } = useTranslation();
const content = getAgentAttachmentPillContent(attachment.attachment, t);
const handleOpen = useCallback(() => onOpen(attachment), [onOpen, attachment]);
const handleRemove = useCallback(() => onRemove(index), [onRemove, index]);
return (
<AttachmentPill
testID="composer-restored-attachment-pill"
onOpen={handleOpen}
onRemove={handleRemove}
openAccessibilityLabel={content.title}
removeAccessibilityLabel={t("composer.attachments.removeAttachment")}
disabled={disabled}
>
<AttachmentLabel icon={content.icon} title={content.title} subtitle={content.subtitle} />
</AttachmentPill>
);
}
@@ -55,11 +55,6 @@ export function splitComposerAttachmentsForSubmit(
continue;
}
if (attachment.kind === "agent_attachment") {
agentAttachments.push(attachment.attachment);
continue;
}
if (attachment.kind === "workspace_file") {
agentAttachments.push(workspaceFileAttachmentToAgentAttachment(attachment));
continue;
@@ -209,7 +209,7 @@ function useWorkspaceAttachmentBinding({
const completeSubmit = useCallback(
({ result, outgoingAttachments }: CompleteSubmitInput) => {
if (result === "submitted" || result === "queued") {
if (result === "submitted") {
clearSentAttachments(outgoingAttachments);
}
if (result === "queued" || result === "submitted" || result === "failed") {
@@ -82,8 +82,9 @@ function ComposerViewport({
);
}
/** Bound the complete composer slot (tracks and input) to the visible viewport capacity. */
/** Bound the complete composer (including its controls), not just the text input. */
function ComposerViewportContent({ style, ...props }: ViewProps) {
const compact = useIsCompactFormFactor();
const sizing = useContext(ViewportSizing);
if (!sizing) throw new Error("ComposerViewportContent requires ComposerViewport");
const constraint = useAnimatedStyle(() => ({
@@ -92,60 +93,11 @@ function ComposerViewportContent({ style, ...props }: ViewProps) {
// Fullscreen styles override it with a static minHeight instead of feeding the mode
// in here: Reanimated applies a dependency change frames after the React commit,
// so the fullscreen slot would paint clamped to the inline cap first.
maxHeight: sizing.value?.capacity,
}));
return (
<Animated.View testID="composer-viewport-content" {...props} style={[style, constraint]} />
);
}
interface ComposerInputCapProps {
fullscreen?: boolean;
children: ReactNode;
}
/**
* Cap the inline editing box below the dock's viewport capacity so tracks above it
* (like the queued message list) keep room instead of collapsing when an attachment pill
* or multi-line draft grows the input.
*/
export function ComposerInputCap({ fullscreen = false, children }: ComposerInputCapProps) {
const compact = useIsCompactFormFactor();
const sizing = useContext(ViewportSizing);
if (!sizing) {
return (
<View style={fullscreen ? dockStyles.fullscreenFill : dockStyles.composer}>{children}</View>
);
}
return (
<ConstrainedComposerInputCap sizing={sizing} compact={compact} fullscreen={fullscreen}>
{children}
</ConstrainedComposerInputCap>
);
}
function ConstrainedComposerInputCap({
sizing,
compact,
fullscreen,
children,
}: {
sizing: SharedValue<ComposerCapacity | undefined>;
compact: boolean;
fullscreen: boolean;
children: ReactNode;
}) {
const constraint = useAnimatedStyle(() => ({
maxHeight: resolveInlineComposerCapacity(sizing.value?.capacity, compact),
}));
return (
<Animated.View
style={[fullscreen ? dockStyles.fullscreenSurface : dockStyles.composer, constraint]}
>
{children}
</Animated.View>
<Animated.View testID="composer-viewport-content" {...props} style={[style, constraint]} />
);
}
@@ -342,7 +294,6 @@ const dockStyles = StyleSheet.create({
// Yoga applies minHeight after maxHeight, so this fills the viewport over the
// inline cap that ComposerViewportContent keeps animating.
fullscreenSurface: { flex: 1, minHeight: "100%" },
fullscreenFill: { flex: 1, minHeight: 0, width: "100%" },
centeredViewport: { flex: 1, alignItems: "center", justifyContent: "center" },
centered: { flexShrink: 1, width: "100%" },
// Reserve the composer's own capped height before the setup scroll view shrinks.
+24 -65
View File
@@ -1,25 +1,14 @@
export { ComposerDockBackground } from "./internal/background";
export { ComposerFullscreenBody, ComposerFullscreenFooter } from "./internal/fullscreen";
import { ScrollView } from "@/components/ui/scroll-view";
import {
createContext,
useCallback,
useContext,
useMemo,
useRef,
useState,
type ReactNode,
} from "react";
import { useState, useCallback, useMemo, useRef, type ReactNode } from "react";
import { View } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { inlineUnistylesStyle } from "@/styles/unistyles-inline-style";
import { resolveInlineComposerCapacity } from "./internal/capacity";
import { useFullscreenSlotFrame } from "./internal/fullscreen";
import { useIsCompactFormFactor } from "@/constants/layout";
import { HEADER_INNER_HEIGHT } from "@/constants/layout";
const ViewportHeightContext = createContext<number | undefined>(undefined);
interface ComposerDockProps {
children: [ReactNode, ReactNode, ReactNode?];
centered?: boolean;
@@ -32,39 +21,40 @@ export function ComposerDock({
centered = false,
fullscreen = false,
}: ComposerDockProps) {
const compact = useIsCompactFormFactor();
const [surfaceSize, setSurfaceSize] = useState<{ width: number; height: number }>();
const surfaceRef = useRef<View>(null);
const fullscreenFrame = useFullscreenSlotFrame(fullscreen, surfaceRef, surfaceSize);
const constraint = useMemo(
() =>
surfaceSize?.height !== undefined
? inlineUnistylesStyle({ maxHeight: surfaceSize.height })
: undefined,
[surfaceSize?.height],
() => ({ maxHeight: resolveInlineComposerCapacity(surfaceSize?.height, compact) }),
[surfaceSize?.height, compact],
);
const measureViewport = useCallback((event: import("react-native").LayoutChangeEvent) => {
const { width, height } = event.nativeEvent.layout;
if (height > 0) setSurfaceSize({ width, height });
}, []);
const body = centered ? (
<View ref={surfaceRef} style={styles.centered} onLayout={measureViewport}>
<View style={styles.form}>
<ScrollView style={styles.setup} keyboardShouldPersistTaps="handled">
{content}
</ScrollView>
<View
style={
fullscreen
? [styles.fullscreenComposer, fullscreenFrame]
: [styles.centeredComposer, constraint]
}
>
{composer}
if (centered) {
return (
<View ref={surfaceRef} style={styles.centered} onLayout={measureViewport}>
<View style={styles.form}>
<ScrollView style={styles.setup} keyboardShouldPersistTaps="handled">
{content}
</ScrollView>
<View
style={
fullscreen
? [styles.fullscreenComposer, fullscreenFrame]
: [styles.centeredComposer, constraint]
}
>
{composer}
</View>
{overlay}
</View>
{overlay}
</View>
</View>
) : (
);
}
return (
<View ref={surfaceRef} style={styles.surface} onLayout={measureViewport}>
<View style={styles.content}>{content}</View>
<View
@@ -77,43 +67,12 @@ export function ComposerDock({
{overlay}
</View>
);
return (
<ViewportHeightContext.Provider value={surfaceSize?.height}>
{body}
</ViewportHeightContext.Provider>
);
}
/** Cap the inline editing box below the viewport capacity so tracks above it keep room. */
export function ComposerInputCap({
fullscreen = false,
children,
}: {
fullscreen?: boolean;
children: ReactNode;
}) {
const compact = useIsCompactFormFactor();
const viewportHeight = useContext(ViewportHeightContext);
const cap = useMemo(
() =>
!fullscreen && viewportHeight !== undefined
? inlineUnistylesStyle({
maxHeight: resolveInlineComposerCapacity(viewportHeight, compact),
})
: undefined,
[compact, fullscreen, viewportHeight],
);
return (
<View style={fullscreen ? styles.fullscreenFill : [styles.inputCap, cap]}>{children}</View>
);
}
const styles = StyleSheet.create((theme) => ({
surface: { flex: 1, overflow: "hidden" },
content: { flex: 1, justifyContent: "flex-end" },
composer: { width: "100%", flexShrink: 1, paddingBottom: theme.spacing[4] },
inputCap: { width: "100%", flexShrink: 1 },
fullscreenFill: { flex: 1, minHeight: 0, width: "100%" },
// Fixed, not absolute: a touch pan that starts inside an overflow-hidden ancestor
// never reaches the zoomed visual viewport, while a fixed box chains to the viewport
// directly. React Native Web renders `fixed`; React Native's style type omits it.
+14 -3
View File
@@ -14,7 +14,6 @@ import { buildForgeSearchQueryOptions, type ForgeSearchClient } from "@/git/use-
import { extractForgeRefs, type ForgeRef } from "@/git/forge-refs";
import type { ForgeSearchItem } from "@getpaseo/protocol/messages";
import { isAttachmentSelectedForForgeItem, toggleForgeAttachment } from "./actions";
import { forgeItemKey } from "./attachments/forge-item-key";
const AUTO_ATTACH_DEBOUNCE_MS = 300;
@@ -149,7 +148,7 @@ export function useComposerForgeAutoAttach(
]);
const markForgeAttachmentRemoved = useCallback((attachment: ComposerAttachment | undefined) => {
const key = forgeItemKey(attachment);
const key = attachmentKey(attachment);
if (key) {
removedRefKeysRef.current.add(key);
}
@@ -506,7 +505,7 @@ function isSameLookupTarget(
}
function hasForgeAttachment(attachments: UserComposerAttachment[], ref: ForgeRef): boolean {
return attachments.some((attachment) => forgeItemKey(attachment) === forgeRefKey(ref));
return attachments.some((attachment) => attachmentKey(attachment) === forgeRefKey(ref));
}
function forgeItemMatchesRef(item: ForgeSearchItem, ref: ForgeRef): boolean {
@@ -520,3 +519,15 @@ function forgeItemKind(ref: ForgeRef): ForgeSearchItem["kind"] {
function forgeRefKey(ref: ForgeRef): string {
return `${forgeItemKind(ref)}:${ref.number}`;
}
function attachmentKey(attachment: ComposerAttachment | undefined): string | null {
if (
attachment?.kind !== "forge_change_request" &&
attachment?.kind !== "forge_issue" &&
attachment?.kind !== "github_pr" &&
attachment?.kind !== "github_issue"
) {
return null;
}
return `${attachment.item.kind}:${attachment.item.number}`;
}
+315 -184
View File
@@ -17,17 +17,16 @@ import {
getStagedProviderSwitch,
isStagedProviderSwitchInFlight,
settleCommittedProviderSwitch,
settleStagedProviderSwitch,
useFailedStartupSettings,
useIsStagedProviderSwitchInFlight,
useStagedProviderSwitch,
useStagedProviderSwitchStore,
} from "@/composer/provider-switch";
import { useProvidersSnapshot } from "@/hooks/use-providers-snapshot";
import { normalizeAgentSnapshot } from "@/utils/agent-snapshots";
import { resolveProviderLabel } from "@/utils/provider-definitions";
import {
View,
Pressable,
Text,
StyleSheet as RNStyleSheet,
type PressableStateCallbackType,
@@ -65,7 +64,9 @@ import { usePointerCapabilities } from "@/hooks/pointer-capabilities";
import { useShallow } from "zustand/shallow";
import {
ArrowRightLeft,
ArrowUp,
Square,
Pencil,
AudioLines,
CircleDot,
FileText,
@@ -105,15 +106,19 @@ import { focusWithRetries } from "@/utils/web-focus";
import {
cancelComposerAgent,
dispatchComposerAgentMessage,
enqueueComposerAgentMessage,
editQueuedComposerMessage,
findForgeItemByOption,
isAttachmentSelectedForForgeItem,
openComposerAttachment,
pickAndPersistImages,
queueComposerMessage,
removeComposerAttachmentAtIndex,
sendQueuedComposerMessageNow,
toggleForgeAttachmentFromPicker,
uploadFileAttachments,
type AttachmentPersister,
type QueueWriter,
type QueuedComposerMessage,
} from "@/composer/actions";
import { useVoiceOptional } from "@/contexts/voice-context";
import { useToast } from "@/contexts/toast-context";
@@ -173,12 +178,6 @@ import type { ComposerFocusOptions } from "@/composer/model";
import { useRetainedPanelActive } from "@/components/retained-panel";
import { insertAtSelection } from "@/composer/insert-text";
import { composerWorkspaceAttachment } from "@/composer/attachments/workspace";
import { forgeItemKey } from "@/composer/attachments/forge-item-key";
import { RestoredAttachmentPill } from "@/composer/attachments/restored-pill";
import type { RestoredQueuedMessage } from "@/composer/queue/actions";
import { ComposerQueueTrack } from "@/composer/queue/track";
import { ComposerInputCap } from "@/composer/dock";
import { useHostFeature } from "@/runtime/host-features";
import { useWorkspaceAttachmentsForScopes } from "@/attachments/workspace-attachments-store";
import { droppedItemsToSelectedFiles } from "@/composer/attachments/drop";
import { getFileTypeLabel } from "@/attachments/file-types";
@@ -221,6 +220,8 @@ const composerImageAttachmentPersister: Pick<
persistFromFileUri: persistAttachmentFromFileUri,
};
type QueuedMessage = QueuedComposerMessage;
type AttachmentListUpdater =
| UserComposerAttachment[]
| ((prev: UserComposerAttachment[]) => UserComposerAttachment[]);
@@ -434,6 +435,34 @@ function renderAttachmentTray(args: RenderAttachmentTrayArgs): ReactElement | nu
);
}
interface RenderQueueTrackArgs {
queuedMessages: readonly QueuedMessage[];
handleEditQueuedMessage: (id: string) => void;
handleSendQueuedNow: (id: string) => Promise<void>;
editLabel: string;
sendNowLabel: string;
}
function renderQueueTrack(args: RenderQueueTrackArgs): ReactElement | null {
const { queuedMessages, handleEditQueuedMessage, handleSendQueuedNow, editLabel, sendNowLabel } =
args;
if (queuedMessages.length === 0) return null;
return (
<View style={styles.queueTrack}>
{queuedMessages.map((item) => (
<QueuedMessageRow
key={item.id}
item={item}
onEdit={handleEditQueuedMessage}
onSendNow={handleSendQueuedNow}
editLabel={editLabel}
sendNowLabel={sendNowLabel}
/>
))}
</View>
);
}
interface RenderComposerAttachmentPillArgs {
serverId: string;
attachment: ComposerAttachment;
@@ -493,22 +522,6 @@ function renderComposerAttachmentPill(args: RenderComposerAttachmentPillArgs): R
onRemove,
});
}
if (attachment.kind === "agent_attachment") {
const wire = attachment.attachment;
return (
<RestoredAttachmentPill
key={wire.type === "uploaded_file" ? wire.id : `${wire.type}:${index}`}
serverId={args.serverId}
attachment={attachment}
index={index}
disabled={disabled}
onOpen={onOpen}
onRemove={onRemove}
openImageLabel={labels.openImage}
removeImageLabel={labels.removeImage}
/>
);
}
if (attachment.kind === "plugin_resource") {
return (
<PluginResourceAttachmentPill
@@ -712,6 +725,54 @@ function resolveMessageInputPassthroughAction(
}
}
interface QueuedMessageRowProps {
item: QueuedMessage;
onEdit: (id: string) => void;
onSendNow: (id: string) => void;
editLabel: string;
sendNowLabel: string;
}
function QueuedMessageRow({
item,
onEdit,
onSendNow,
editLabel,
sendNowLabel,
}: QueuedMessageRowProps) {
const handleEdit = useCallback(() => {
onEdit(item.id);
}, [onEdit, item.id]);
const handleSendNow = useCallback(() => {
onSendNow(item.id);
}, [onSendNow, item.id]);
return (
<View style={styles.queueItem}>
<Text style={styles.queueText} numberOfLines={2} ellipsizeMode="tail">
{item.text}
</Text>
<View style={styles.queueActions}>
<Pressable
onPress={handleEdit}
style={styles.queueActionButton}
accessibilityLabel={editLabel}
accessibilityRole="button"
>
<ThemedPencil size={ICON_SIZE.sm} uniProps={iconForegroundMapping} />
</Pressable>
<Pressable
onPress={handleSendNow}
style={[styles.queueActionButton, styles.queueSendButton]}
accessibilityLabel={sendNowLabel}
accessibilityRole="button"
>
<ThemedArrowUp size={ICON_SIZE.sm} uniProps={iconAccentForegroundMapping} />
</Pressable>
</View>
</View>
);
}
interface ImageAttachmentPillProps {
attachment: Extract<ComposerAttachment, { kind: "image" }>;
index: number;
@@ -994,6 +1055,7 @@ interface ComposerProps {
error?: string | null;
}
const EMPTY_ARRAY: readonly QueuedMessage[] = [];
const StableMessageInput = memo(MessageInput);
interface ComposerAutocompleteHandle {
@@ -1336,10 +1398,6 @@ function ComposerContentImpl({
const stagedProviderLabel = stagedSwitch
? resolveProviderLabel(stagedSwitch.provider, providerSnapshotEntries)
: null;
const providerLabel = useCallback(
(provider: string) => resolveProviderLabel(provider, providerSnapshotEntries),
[providerSnapshotEntries],
);
useEffect(() => {
if (
@@ -1355,6 +1413,7 @@ function ComposerContentImpl({
const handleCancelStagedSwitch = useCallback(() => {
clearStagedProviderSwitch(serverId, agentId);
setSendError(null);
useSessionStore.getState().setQueuedSendError(serverId, agentId, null);
}, [agentId, serverId]);
const handleRetryFailedStartupSettings = useCallback(() => {
@@ -1367,6 +1426,16 @@ function ComposerContentImpl({
void getHostRuntimeStore().recoverFailedStartupSettings(serverId, agentId, "discard");
}, [agentId, serverId]);
const queuedMessagesRaw = useSessionStore((state) =>
state.sessions[serverId]?.queuedMessages?.get(agentId),
);
const queuedSendError = useSessionStore(
(state) => state.sessions[serverId]?.queuedSendErrors?.get(agentId) ?? null,
);
const queuedMessages = queuedMessagesRaw ?? EMPTY_ARRAY;
const setQueuedMessages = useSessionStore((state) => state.setQueuedMessages);
const isCompactFormFactor = useIsCompactFormFactor();
const isCompactLayout = resolveCompactLayout(isCompactLayoutOverride, isCompactFormFactor);
const controlSizing = controlSizingForLayout(isCompactFormFactor);
@@ -1384,6 +1453,7 @@ function ComposerContentImpl({
removeAttachment,
openAttachment,
beginSubmit,
clearSentAttachments,
completeSubmit,
resetSuppression,
} = composerWorkspaceAttachment.useBinding({
@@ -1731,6 +1801,7 @@ function ComposerContentImpl({
const pendingSwitch = canSwitch ? getStagedProviderSwitch(serverId, targetAgentId) : null;
const stagedProviderSwitch =
pendingSwitch && pendingSwitch.provider !== liveProvider ? pendingSwitch : null;
useSessionStore.getState().setQueuedSendError(serverId, targetAgentId, null);
if (stagedProviderSwitch) {
beginStagedProviderSwitch(serverId, targetAgentId);
}
@@ -1806,37 +1877,43 @@ function ComposerContentImpl({
}
return false;
});
// COMPAT(agentMessageQueue): added in v0.18.2, remove gate after 2027-06-01.
const supportsQueue = useHostFeature(serverId, "agentMessageQueue");
const activeSendBehavior = resolveActiveSendBehavior(
appSettings.sendBehavior,
hasPendingPermission,
supportsQueue,
);
const hasAgent = agentState.status !== null;
const enqueueMessage = useCallback(
async (text: string, queuedAttachments: ComposerAttachment[]) => {
if (!client) {
throw new Error(t("workspace.terminal.hostDisconnected"));
}
const targetAgentId = agentIdRef.current;
await enqueueComposerAgentMessage({
client,
agentId: targetAgentId,
text,
const queueWriter = useMemo<QueueWriter>(
() => ({
read: (id) => useSessionStore.getState().sessions[serverId]?.queuedMessages?.get(id) ?? [],
write: (updater) => setQueuedMessages(serverId, updater),
}),
[serverId, setQueuedMessages],
);
const queueMessage = useCallback(
(queuedMessage: string, queuedAttachments: ComposerAttachment[]) => {
const result = queueComposerMessage({
agentId,
text: queuedMessage,
attachments: queuedAttachments,
attachmentSubmitFormat: resolveComposerAttachmentSubmitFormat({
supportsForgeAttachments: supportsForgeSearch,
}),
stagedProviderSwitch: stagedSwitch,
// The host owns the switch now. A choice made since then stays staged.
onProviderSwitchQueued: () => {
if (stagedSwitch) settleStagedProviderSwitch(serverId, targetAgentId, stagedSwitch);
},
queue: queueWriter,
});
if (!result.queued) return;
replaceUserInput("");
setSelectedAttachments([]);
resetSuppression();
clearSentAttachments(queuedAttachments);
},
[client, serverId, stagedSwitch, supportsForgeSearch, t],
[
agentId,
clearSentAttachments,
queueWriter,
resetSuppression,
setSelectedAttachments,
replaceUserInput,
],
);
const sendMessageWithContent = useCallback(
@@ -1852,15 +1929,12 @@ function ComposerContentImpl({
allowEmptySubmit,
forceSend: stagedSwitch && isAgentRunning ? false : forceSend,
submitBehavior,
isAgentRunning: isAgentRunning && supportsQueue,
isAgentRunning,
// Parent-managed submits are still valid submit paths even when the
// transport is disconnected, because the parent decides the failure mode.
canSubmit: Boolean(sendAgentMessageRef.current || onSubmitMessageRef.current),
queueMessage: async ({ message: queuedText, attachments: queuedAttachments }) => {
if (submitBehavior !== "preserve-and-lock") {
beginSubmit(queuedAttachments);
}
await enqueueMessage(queuedText, queuedAttachments);
queueMessage: ({ message: queuedText, attachments: queuedAttachments }) => {
queueMessage(queuedText, queuedAttachments);
},
submitMessage: async ({ message: submitText, attachments: submitAttachments }) => {
if (submitBehavior !== "preserve-and-lock") {
@@ -1890,10 +1964,9 @@ function ComposerContentImpl({
beginSubmit,
clearDraft,
completeSubmit,
enqueueMessage,
hasExternalContent,
isAgentRunning,
supportsQueue,
queueMessage,
setSelectedAttachments,
replaceUserInput,
stagedSwitch,
@@ -2141,25 +2214,39 @@ function ComposerContentImpl({
});
}, [agentId, hasAgent, isConnected, serverId, voice]);
const handleRestoreQueuedMessage = useCallback(
(message: RestoredQueuedMessage) => {
replaceUserInput(message.text);
setSelectedAttachments(message.attachments);
if (message.providerSwitch) {
useStagedProviderSwitchStore.getState().stage(serverId, agentId, message.providerSwitch);
}
focusInput();
const handleEditQueuedMessage = useCallback(
(id: string) => {
const result = editQueuedComposerMessage({
agentId,
messageId: id,
queue: queueWriter,
});
if (!result) return;
useSessionStore.getState().setQueuedSendError(serverId, agentId, null);
replaceUserInput(result.text);
setSelectedAttachments(result.attachments);
},
[agentId, focusInput, replaceUserInput, serverId, setSelectedAttachments],
[agentId, queueWriter, replaceUserInput, serverId, setSelectedAttachments],
);
const handleQueuedMessageAlreadySending = useCallback(() => {
toastErrorRef.current(t("composer.queue.alreadySending"));
}, [t]);
const handleQueueError = useCallback(
(error: unknown) => {
setSendError(resolveErrorMessage(error) ?? t("composer.errors.failedToSend"));
const handleSendQueuedNow = useCallback(
async (id: string) => {
if (!sendAgentMessageRef.current && !onSubmitMessageRef.current) return;
useSessionStore.getState().setQueuedSendError(serverId, agentId, null);
// Reuse the regular send path; server-side send atomically interrupts any active run.
const result = await sendQueuedComposerMessageNow({
agentId,
messageId: id,
queue: queueWriter,
submitMessage: ({ text, attachments: queuedAttachments }) =>
submitMessage(text, queuedAttachments),
failedToSendMessage: t("composer.errors.failedToSend"),
});
if (result.status === "failed") {
setSendError(result.errorMessage);
}
},
[t],
[agentId, queueWriter, serverId, submitMessage, t],
);
const handleQueue = useCallback(
@@ -2178,15 +2265,15 @@ function ComposerContentImpl({
commands: pluginClientSlashCommands,
});
if (pluginSlashCommand && runPluginClientSlashCommand(pluginSlashCommand)) return;
void sendMessageWithContent(payload.text, outgoingAttachments);
queueMessage(payload.text, outgoingAttachments);
},
[
attachments,
buildOutgoingAttachments,
pluginClientSlashCommands,
queueMessage,
runClientSlashCommand,
runPluginClientSlashCommand,
sendMessageWithContent,
],
);
@@ -2305,7 +2392,14 @@ function ComposerContentImpl({
);
const hasGithubAttachment = useMemo(
() => selectedAttachments.some((attachment) => forgeItemKey(attachment) !== null),
() =>
selectedAttachments.some(
(attachment) =>
attachment.kind === "forge_change_request" ||
attachment.kind === "forge_issue" ||
attachment.kind === "github_pr" ||
attachment.kind === "github_issue",
),
[selectedAttachments],
);
// Composer stays mounted for each focused agent, so avoid a forge CLI call
@@ -2551,6 +2645,18 @@ function ComposerContentImpl({
],
);
const queueList = useMemo(
() =>
renderQueueTrack({
queuedMessages,
handleEditQueuedMessage,
handleSendQueuedNow,
editLabel: t("composer.attachments.editQueuedMessage"),
sendNowLabel: t("composer.attachments.sendQueuedMessageNow"),
}),
[handleEditQueuedMessage, handleSendQueuedNow, queuedMessages, t],
);
const autocompleteConfiguration = useMemo(
() => ({
setUserInput: replaceUserInput,
@@ -2593,7 +2699,8 @@ function ComposerContentImpl({
// Focusing the composer on a touch screen raises the on-screen keyboard over the conversation.
const messageInputAutoFocus = autoFocus && isDesktopWebBreakpoint && hasFinePointer;
const submitLoadingPressHandler = isAgentRunning ? handleCancelAgent : undefined;
const displayError = externalError || sendError || failedStartupSettings?.errorMessage;
const displayError =
externalError || sendError || failedStartupSettings?.errorMessage || queuedSendError;
const sendErrorNode = useMemo(
() =>
displayError ? (
@@ -2664,60 +2771,6 @@ function ComposerContentImpl({
t,
]);
const messageInputNode = (
<RenderProfile id="MessageInput">
<StableMessageInput
ref={messageInputRef}
editingSession={editingSession}
submissionError={sendErrorNode}
value={textSource.getSnapshot()}
onChangeText={setUserInput}
onSubmit={handleSubmit}
hasExternalContent={hasExternalContent}
allowEmptySubmit={allowEmptySubmit}
submitButtonAccessibilityLabel={submitButtonAccessibilityLabel}
submitButtonTestID={submitButtonTestID}
submitIcon={submitIcon}
isSubmitDisabled={isSubmitDisabled}
isSubmitLoading={isSubmitLoadingVisible}
preserveHeightOnSubmit={submitBehavior === "preserve-and-lock"}
attachments={selectedAttachments}
cwd={cwd}
attachmentMenuItems={attachmentMenuItems}
onAttachButtonRef={handleAttachButtonRef}
onAddImages={addImages}
onPasteImages={handleNativePasteImages}
client={client}
isReadyForDictation={isDictationReady}
placeholder={messagePlaceholder}
autoFocus={messageInputAutoFocus}
autoFocusKey={`${serverId}:${agentId}:${autoFocusKey ?? ""}`}
disabled={isSubmitLoading}
leftContent={leftContent}
beforeVoiceContent={beforeVoiceContent}
voiceModeContent={voiceModeContent}
activeActionContent={activeActionContent}
voiceServerId={serverId}
voiceAgentId={agentId}
isAgentRunning={isAgentRunning}
defaultSendBehavior={activeSendBehavior}
sendShortcut={appSettings.sendShortcut}
onQueue={supportsQueue ? handleQueue : undefined}
onSubmitLoadingPress={submitLoadingPressHandler}
onKeyPress={handleCommandKeyPress}
onSelectionChange={handleSelectionChange}
onFocusChange={handleFocusChange}
onHeightChange={onComposerHeightChange}
inputWrapperStyle={inputWrapperStyle}
attachmentSlot={attachmentTray}
inputMode={inputMode}
readOnly={readOnly}
textReplacement={textReplacement}
submitLabel={submitLabel}
/>
</RenderProfile>
);
return (
<>
<ComposerKeyboardRegistration
@@ -2742,63 +2795,101 @@ function ComposerContentImpl({
dataSet={isFullscreen ? undefined : CHAT_COLUMN_RAIL_DATASET}
>
<View style={inputAreaContentStyle}>
{!isFullscreen && hasAgent && supportsQueue ? (
<ComposerQueueTrack
serverId={serverId}
agentId={agentId}
sendBehavior={appSettings.sendBehavior}
providerLabel={providerLabel}
onRestore={handleRestoreQueuedMessage}
onAlreadySending={handleQueuedMessageAlreadySending}
onError={handleQueueError}
/>
) : null}
{isFullscreen ? null : queueList}
{isFullscreen ? null : stagedSwitchBannerNode}
{!isFullscreen && sendErrorNode}
<ComposerInputCap fullscreen={isFullscreen}>
<ComposerAutocompleteBinding
<ComposerAutocompleteBinding
text={textSource}
cursor={cursor}
recall={recall}
inputRef={messageInputRef}
anchorStyle={messageInputContainerStyle}
show={mode.showAutocomplete && !isFullscreen && !isComposerLocked}
ref={autocompleteRef}
configuration={autocompleteConfiguration}
>
<ComposerForgeBinding
text={textSource}
cursor={cursor}
recall={recall}
inputRef={messageInputRef}
anchorStyle={messageInputContainerStyle}
show={mode.showAutocomplete && !isFullscreen && !isComposerLocked}
ref={autocompleteRef}
configuration={autocompleteConfiguration}
>
<ComposerForgeBinding
text={textSource}
configuration={forgeConfiguration}
ref={forgeAutoAttachRef}
onResolvingChange={setIsForgeResolving}
/>
configuration={forgeConfiguration}
ref={forgeAutoAttachRef}
onResolvingChange={setIsForgeResolving}
/>
{/* MessageInput handles everything: text, dictation, attachments, all buttons */}
{messageInputNode}
<Combobox
options={githubSearchOptions}
value=""
onSelect={noop}
keepOpenOnSelect
searchable
searchPlaceholder={t("composer.github.searchPlaceholder", {
context: forgePresentation.changeRequestContext,
})}
title={t("composer.github.title", {
context: forgePresentation.changeRequestContext,
})}
open={isGithubPickerOpen}
onOpenChange={handleGithubPickerOpenChange}
onSearchQueryChange={setGithubSearchQuery}
desktopPlacement="top-start"
anchorRef={attachButtonRef}
emptyText={githubEmptyText}
renderOption={renderGithubPickerOption}
{/* MessageInput handles everything: text, dictation, attachments, all buttons */}
<RenderProfile id="MessageInput">
<StableMessageInput
ref={messageInputRef}
editingSession={editingSession}
submissionError={sendErrorNode}
value={textSource.getSnapshot()}
onChangeText={setUserInput}
onSubmit={handleSubmit}
hasExternalContent={hasExternalContent}
allowEmptySubmit={allowEmptySubmit}
submitButtonAccessibilityLabel={submitButtonAccessibilityLabel}
submitButtonTestID={submitButtonTestID}
submitIcon={submitIcon}
isSubmitDisabled={isSubmitDisabled}
isSubmitLoading={isSubmitLoadingVisible}
preserveHeightOnSubmit={submitBehavior === "preserve-and-lock"}
attachments={selectedAttachments}
cwd={cwd}
attachmentMenuItems={attachmentMenuItems}
onAttachButtonRef={handleAttachButtonRef}
onAddImages={addImages}
onPasteImages={handleNativePasteImages}
client={client}
isReadyForDictation={isDictationReady}
placeholder={messagePlaceholder}
autoFocus={messageInputAutoFocus}
autoFocusKey={`${serverId}:${agentId}:${autoFocusKey ?? ""}`}
disabled={isSubmitLoading}
leftContent={leftContent}
beforeVoiceContent={beforeVoiceContent}
voiceModeContent={voiceModeContent}
activeActionContent={activeActionContent}
voiceServerId={serverId}
voiceAgentId={agentId}
isAgentRunning={isAgentRunning}
defaultSendBehavior={activeSendBehavior}
sendShortcut={appSettings.sendShortcut}
onQueue={handleQueue}
onSubmitLoadingPress={submitLoadingPressHandler}
onKeyPress={handleCommandKeyPress}
onSelectionChange={handleSelectionChange}
onFocusChange={handleFocusChange}
onHeightChange={onComposerHeightChange}
inputWrapperStyle={inputWrapperStyle}
attachmentSlot={attachmentTray}
inputMode={inputMode}
readOnly={readOnly}
textReplacement={textReplacement}
submitLabel={submitLabel}
/>
{pluginAttachments.picker}
</ComposerAutocompleteBinding>
</ComposerInputCap>
</RenderProfile>
<Combobox
options={githubSearchOptions}
value=""
onSelect={noop}
keepOpenOnSelect
searchable
searchPlaceholder={t("composer.github.searchPlaceholder", {
context: forgePresentation.changeRequestContext,
})}
title={t("composer.github.title", {
context: forgePresentation.changeRequestContext,
})}
open={isGithubPickerOpen}
onOpenChange={handleGithubPickerOpenChange}
onSearchQueryChange={setGithubSearchQuery}
desktopPlacement="top-start"
anchorRef={attachButtonRef}
emptyText={githubEmptyText}
renderOption={renderGithubPickerOption}
/>
{pluginAttachments.picker}
</ComposerAutocompleteBinding>
</View>
</View>
</View>
@@ -2924,6 +3015,43 @@ const styles = StyleSheet.create((theme: Theme) => ({
buttonDisabled: {
opacity: 0.5,
},
queueTrack: {
flexDirection: "column",
gap: theme.spacing[2],
},
queueItem: {
flexDirection: "row",
alignItems: "center",
justifyContent: "space-between",
paddingHorizontal: theme.spacing[3],
paddingVertical: theme.spacing[2],
backgroundColor: theme.colors.surface1,
borderRadius: theme.borderRadius.lg,
borderWidth: theme.borderWidth[1],
borderColor: theme.colors.border,
gap: theme.spacing[2],
},
queueText: {
flex: 1,
color: theme.colors.foreground,
fontSize: theme.fontSize.base,
},
queueActions: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[2],
},
queueActionButton: {
width: 32,
height: 32,
borderRadius: theme.borderRadius.full,
alignItems: "center",
justifyContent: "center",
backgroundColor: theme.colors.surface2,
},
queueSendButton: {
backgroundColor: theme.colors.accent,
},
stagedSwitchBanner: {
flexDirection: "row",
alignItems: "center",
@@ -2953,6 +3081,8 @@ const styles = StyleSheet.create((theme: Theme) => ({
const ThemedAttachmentSpinner = withUnistyles(LoadingSpinner);
const ThemedArrowRightLeft = withUnistyles(ArrowRightLeft);
const ThemedPencil = withUnistyles(Pencil);
const ThemedArrowUp = withUnistyles(ArrowUp);
const ThemedGitPullRequest = withUnistyles(GitPullRequest);
const ThemedCircleDot = withUnistyles(CircleDot);
const ThemedAudioLines = withUnistyles(AudioLines);
@@ -2962,6 +3092,7 @@ const ThemedClipboardPaste = withUnistyles(ClipboardPaste);
const ThemedFileText = withUnistyles(FileText);
const iconForegroundMapping = (theme: Theme) => ({ color: theme.colors.foreground });
const iconForegroundMutedMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
const iconAccentForegroundMapping = (theme: Theme) => ({ color: theme.colors.accentForeground });
function renderForgeAttachmentIcon(icon: string): ReactElement {
return (
@@ -0,0 +1,67 @@
import React, { act, useCallback, useMemo, useRef, useState, type FormEvent } from "react";
import { createRoot } from "react-dom/client";
import { expect, it } from "vitest";
import { useComposerHeight } from "./height.web";
it("keeps height measurement bounded when editing a long multiline draft", () => {
function Composer() {
const textarea = useRef<HTMLTextAreaElement>(null);
const [renderedLines, setRenderedLines] = useState(1);
const getText = useCallback(() => textarea.current?.value ?? "", []);
const sizing = useComposerHeight({
getText,
textareaRef: textarea,
minHeight: 24,
maxHeight: 96,
onRenderedLinesChange: setRenderedLines,
});
if (sizing.mode !== "measured") throw new Error("Expected web height measurement");
const { onTextChange } = sizing;
const edit = useCallback(
(event: FormEvent<HTMLTextAreaElement>) => onTextChange("", event.currentTarget.value),
[onTextChange],
);
const style = useMemo(
() => ({ height: Number(sizing.style.height), width: 400, lineHeight: "20px" }),
[sizing.style.height],
);
return (
<textarea ref={textarea} onInput={edit} style={style} data-multiline={renderedLines > 2} />
);
}
const container = document.body.appendChild(document.createElement("div"));
const root = createRoot(container);
try {
act(() => root.render(<Composer />));
const editor = container.querySelector("textarea")!;
const draft = "Review the resulting change.\n".repeat(9_000);
function replaceText(text: string) {
act(() => {
editor.value = text;
editor.dispatchEvent(new InputEvent("input", { bubbles: true }));
});
}
replaceText(draft);
replaceText(draft + "x");
expect(editor.value).toBe(draft + "x");
expect(editor.style.height).toBe("96px");
expect(editor.dataset.multiline).toBe("true");
const measurement = document.querySelector<HTMLTextAreaElement>(
'textarea[aria-hidden="true"]',
)!;
expect(measurement.value.length).toBeLessThan(400);
replaceText("Short draft");
expect(editor.style.height).toBe("24px");
expect(editor.dataset.multiline).toBe("false");
} finally {
act(() => root.unmount());
container.remove();
}
});
+29 -6
View File
@@ -33,6 +33,15 @@ const COPIED_STYLES = [
"paddingLeft",
] as const;
function prefixThroughHardLines(text: string, lines: number): string {
let lineEnd = -1;
for (let line = 0; line < lines; line += 1) {
lineEnd = text.indexOf("\n", lineEnd + 1);
if (lineEnd === -1) return text;
}
return text.slice(0, lineEnd + 1);
}
export function useComposerHeight({
getText,
textareaRef,
@@ -68,15 +77,29 @@ export function useComposerHeight({
mirror.style[property] = computedStyle[property];
}
mirror.style.width = `${sourceWidth}px`;
mirror.value = text.endsWith("\n") ? `${text} ` : text;
const padding =
parseFloat(computedStyle.paddingTop) + parseFloat(computedStyle.paddingBottom);
const lineHeight = parseFloat(computedStyle.lineHeight);
if (lineHeight > 0)
paramsRef.current.onRenderedLinesChange?.(
Math.round((mirror.scrollHeight - padding) / lineHeight),
);
setBoundedHeight(mirror.scrollHeight);
const { maxHeight: currentMax, onRenderedLinesChange: reportLines } = paramsRef.current;
// Complete hard lines can prove the height cap and the three-line fullscreen threshold.
// Keep measuring the whole draft when the prefix cannot prove both.
const measuredText =
Number.isFinite(currentMax) && lineHeight > 0
? prefixThroughHardLines(
text,
Math.max(3, Math.ceil((currentMax - padding) / lineHeight)),
)
: text;
mirror.value = measuredText.endsWith("\n") ? `${measuredText} ` : measuredText;
let scrollHeight = mirror.scrollHeight;
if (measuredText !== text && scrollHeight < currentMax) {
mirror.value = text.endsWith("\n") ? `${text} ` : text;
scrollHeight = mirror.scrollHeight;
}
if (lineHeight > 0) {
reportLines?.(Math.round((scrollHeight - padding) / lineHeight));
}
setBoundedHeight(scrollHeight);
},
[setBoundedHeight, textareaRef],
);
+3 -10
View File
@@ -196,16 +196,9 @@ describe("dictation transcript behavior", () => {
describe("composer send behavior", () => {
it("sends immediately when queue mode cannot advance past a permission", () => {
expect(resolveActiveSendBehavior("queue", true, true)).toBe("interrupt");
expect(resolveActiveSendBehavior("queue", false, true)).toBe("queue");
expect(resolveActiveSendBehavior("steer", true, true)).toBe("steer");
});
it("steers instead of queueing on a host without a message queue, keeping the turn", () => {
expect(resolveActiveSendBehavior("queue", false, false)).toBe("steer");
expect(resolveActiveSendBehavior("queue", true, false)).toBe("interrupt");
expect(resolveActiveSendBehavior("steer", false, false)).toBe("steer");
expect(resolveActiveSendBehavior("interrupt", false, false)).toBe("interrupt");
expect(resolveActiveSendBehavior("queue", true)).toBe("interrupt");
expect(resolveActiveSendBehavior("queue", false)).toBe("queue");
expect(resolveActiveSendBehavior("steer", true)).toBe("steer");
});
function actions() {
+1 -6
View File
@@ -9,13 +9,8 @@ export type SendBehavior = ActiveTurnBehavior | "queue";
export function resolveActiveSendBehavior(
sendBehavior: SendBehavior,
hasPendingPermission: boolean,
hostHasMessageQueue: boolean,
): SendBehavior {
if (sendBehavior !== "queue") return sendBehavior;
if (hasPendingPermission) return "interrupt";
// COMPAT(agentMessageQueue): added in v0.18.2, remove gate after 2027-06-01.
// Steering keeps the running turn alive on a host that cannot hold the message.
return hostHasMessageQueue ? "queue" : "steer";
return sendBehavior === "queue" && hasPendingPermission ? "interrupt" : sendBehavior;
}
interface ComposerSurfaceState {
@@ -9,7 +9,6 @@ export {
isStagedProviderSwitchInFlight,
settleCommittedProviderSwitch,
settleStagedProviderSwitch,
toStagedProviderSwitch,
useFailedStartupSettings,
useIsStagedProviderSwitchInFlight,
useStagedProviderSwitch,
@@ -27,7 +27,6 @@ import {
clearStagedProviderSwitch,
getFailedStartupSettings,
getStagedProviderSwitch,
settleCommittedProviderSwitch,
useStagedProviderSwitchStore,
} from "./index";
@@ -402,115 +401,798 @@ describe("app provider switching integration", () => {
expect(collapsed.tail.some((item) => item.kind === "provider_switch")).toBe(true);
});
const sentDraft = {
provider: "codex",
model: "gpt-5.3",
thinkingOptionId: "low",
modeId: "auto",
providerOptions: { plan_mode: false },
};
it("blocks M2 drain while M1's staged provider switch is in-flight, then sends M2 normally to P2", async () => {
const serverId = "srv_multi_queue_switch";
let resolveSwitch!: (value: { agent: AgentSnapshotPayload }) => void;
const switchPromise = new Promise<{ agent: AgentSnapshotPayload }>((resolve) => {
resolveSwitch = resolve;
});
const switchedCalls: string[] = [];
const sentCalls: string[] = [];
const fakeClient = {
switchAgentProvider: vi.fn(async (_agentId: string, opts: { text: string }) => {
switchedCalls.push(opts.text);
return await switchPromise;
}),
sendAgentMessage: vi.fn(async (_agentId: string, text: string) => {
sentCalls.push(text);
}),
uploadFile: vi.fn(),
} as unknown as DaemonClient;
it("forwards target provider setting edits made during switch startup to the live agent", async () => {
const serverId = "srv-startup-edits";
const applied: unknown[] = [];
const record =
(setting: string) => async (_agentId: string, value: unknown, opts?: unknown) => {
applied.push({ setting, value, opts });
};
useStagedProviderSwitchStore.getState().stage(serverId, "agent-1", sentDraft);
const runtime = new HostRuntimeStore({
deps: {
createClient: () => fakeClient,
connectToDaemon: async () => ({ client: fakeClient, serverId, hostname: null }),
getClientId: async () => "cid_multi_queue_switch",
},
});
const sessionStore = useSessionStore.getState();
sessionStore.initializeSession(serverId, fakeClient, 1);
useSessionStore.setState((state) => ({
sessions: {
...state.sessions,
[serverId]: {
...state.sessions[serverId]!,
serverInfo: {
serverId,
hostname: "localhost",
version: "0.18.0",
features: { providerSwitching: true },
},
},
},
}));
sessionStore.setAgents(
serverId,
new Map([
[
"agent-1",
{
...agentSnapshot("claude"),
serverId,
parentAgentId: null,
createdAt: new Date(TS),
updatedAt: new Date(TS),
lastUserMessageAt: null,
lastActivityAt: new Date(TS),
attentionTimestamp: null,
archivedAt: null,
turn: { phase: "idle", cancellationRequestId: null },
},
],
]),
);
sessionStore.setQueuedMessages(
serverId,
new Map([
[
"agent-1",
[
{ id: "m1", text: "First queued switch prompt", attachments: [] },
{ id: "m2", text: "Second queued follow-up", attachments: [] },
],
],
]),
);
useStagedProviderSwitchStore.getState().stage(serverId, "agent-1", {
provider: "codex",
model: "gpt-5.4",
thinkingOptionId: null,
modeId: null,
providerOptions: {},
});
// M1 begins switching
runtime.drainQueuedAgentMessage(serverId, "agent-1");
await vi.waitFor(() => {
expect(switchedCalls).toEqual(["First queued switch prompt"]);
});
// Concurrent drain trigger while M1's switch is still running MUST NOT drain M2!
sessionStore.setAgents(
serverId,
new Map([
[
"agent-1",
{
...agentSnapshot("codex"),
serverId,
parentAgentId: null,
createdAt: new Date(TS),
updatedAt: new Date(TS),
lastUserMessageAt: null,
lastActivityAt: new Date(TS),
attentionTimestamp: null,
archivedAt: null,
status: "running",
turn: {
phase: "open",
turnId: "t1",
startedAt: new Date(TS),
cancellationRequestId: null,
},
},
],
]),
);
runtime.drainQueuedAgentMessage(serverId, "agent-1");
expect(sentCalls).toEqual([]);
expect(switchedCalls).toHaveLength(1);
expect(useSessionStore.getState().sessions[serverId]?.queuedMessages.get("agent-1")).toEqual([
{ id: "m2", text: "Second queued follow-up", attachments: [] },
]);
// M1 switch completes while P2 is still running -> staged switch clears, M2 stays queued until idle.
resolveSwitch({ agent: { ...agentSnapshot("codex"), status: "running" } });
await vi.waitFor(() => {
expect(getStagedProviderSwitch(serverId, "agent-1")).toBeNull();
});
expect(sentCalls).toEqual([]);
// Once P2 goes idle and triggers drain, M2 drains as a plain sendAgentMessage to Codex.
sessionStore.setAgents(
serverId,
new Map([
[
"agent-1",
{
...agentSnapshot("codex"),
serverId,
parentAgentId: null,
createdAt: new Date(TS),
updatedAt: new Date(TS),
lastUserMessageAt: null,
lastActivityAt: new Date(TS),
attentionTimestamp: null,
archivedAt: null,
status: "idle",
turn: { phase: "idle", cancellationRequestId: null },
},
],
]),
);
runtime.drainQueuedAgentMessage(serverId, "agent-1");
await vi.waitFor(() => {
expect(sentCalls).toEqual(["Second queued follow-up"]);
});
expect(switchedCalls).toHaveLength(1);
sessionStore.clearSession(serverId);
});
it("re-drains M2 automatically if a fast switch turn finishes before the switch RPC replies", async () => {
const serverId = "srv-fast-queue-switch";
const switchedCalls: string[] = [];
const sentCalls: string[] = [];
let resolveSwitch!: (value: { agent?: AgentSnapshotPayload }) => void;
const fakeClient = {
switchAgentProvider: vi.fn(
(_agentId: string, opts: { text: string }) =>
new Promise<{ agent?: AgentSnapshotPayload }>((resolve) => {
switchedCalls.push(opts.text);
resolveSwitch = resolve;
}),
),
sendAgentMessage: vi.fn(async (_agentId: string, text: string) => {
sentCalls.push(text);
return { messageId: "m2-ack" };
}),
uploadFile: vi.fn(),
} as unknown as DaemonClient;
const runtime = new HostRuntimeStore({
deps: {
createClient: () => fakeClient,
connectToDaemon: async () => ({ client: fakeClient, serverId, hostname: null }),
getClientId: async () => "cid_fast_queue_switch",
},
});
const sessionStore = useSessionStore.getState();
sessionStore.initializeSession(serverId, fakeClient, 1);
useSessionStore.setState((state) => ({
sessions: {
...state.sessions,
[serverId]: {
...state.sessions[serverId]!,
serverInfo: {
serverId,
hostname: "localhost",
version: "0.18.0",
features: { providerSwitching: true },
},
},
},
}));
sessionStore.setAgents(
serverId,
new Map([
[
"agent-1",
{
...agentSnapshot("claude"),
serverId,
parentAgentId: null,
createdAt: new Date(TS),
updatedAt: new Date(TS),
lastUserMessageAt: null,
lastActivityAt: new Date(TS),
attentionTimestamp: null,
archivedAt: null,
status: "idle",
turn: { phase: "idle", cancellationRequestId: null },
},
],
]),
);
sessionStore.setQueuedMessages(
serverId,
new Map([
[
"agent-1",
[
{ id: "m1", text: "Fast switch prompt", attachments: [] },
{ id: "m2", text: "Follow-up after fast switch", attachments: [] },
],
],
]),
);
useStagedProviderSwitchStore.getState().stage(serverId, "agent-1", {
provider: "codex",
model: "gpt-5.4",
thinkingOptionId: null,
modeId: null,
providerOptions: {},
});
// M1 begins switching
runtime.drainQueuedAgentMessage(serverId, "agent-1");
await vi.waitFor(() => {
expect(switchedCalls).toEqual(["Fast switch prompt"]);
});
// Fast provider completes M1's turn BEFORE switch RPC replies: status is idle and turn-end
// calls drainQueuedAgentMessage while the lock is held.
runtime.drainQueuedAgentMessage(serverId, "agent-1");
expect(sentCalls).toEqual([]);
// Switch RPC replies with idle agent -> finally MUST automatically drain M2 without another trigger!
resolveSwitch({ agent: { ...agentSnapshot("codex"), status: "idle" } });
await vi.waitFor(() => {
expect(sentCalls).toEqual(["Follow-up after fast switch"]);
});
expect(switchedCalls).toHaveLength(1);
sessionStore.clearSession(serverId);
});
it("preserves a newer staged provider choice made while an earlier queued switch reply is pending", async () => {
const serverId = "srv-newer-choice-queue";
const switchedCalls: Array<{ provider: string; text: string }> = [];
const sentCalls: string[] = [];
let resolveFirstSwitch!: (value: { agent?: AgentSnapshotPayload }) => void;
const fakeClient = {
switchAgentProvider: vi.fn((_agentId: string, opts: { provider: string; text: string }) => {
switchedCalls.push({ provider: opts.provider, text: opts.text });
if (switchedCalls.length === 1) {
return new Promise<{ agent?: AgentSnapshotPayload }>((resolve) => {
resolveFirstSwitch = resolve;
});
}
return Promise.resolve({
agent: { ...agentSnapshot(opts.provider), status: "running" },
});
}),
sendAgentMessage: vi.fn(async (_agentId: string, text: string) => {
sentCalls.push(text);
return { messageId: "unexpected-plain-send" };
}),
uploadFile: vi.fn(),
} as unknown as DaemonClient;
const runtime = new HostRuntimeStore({
deps: {
createClient: () => fakeClient,
connectToDaemon: async () => ({ client: fakeClient, serverId, hostname: null }),
getClientId: async () => "cid_newer_choice_queue",
},
});
const sessionStore = useSessionStore.getState();
sessionStore.initializeSession(serverId, fakeClient, 1);
useSessionStore.setState((state) => ({
sessions: {
...state.sessions,
[serverId]: {
...state.sessions[serverId]!,
serverInfo: {
serverId,
hostname: "localhost",
version: "0.18.0",
features: { providerSwitching: true },
},
},
},
}));
sessionStore.setAgents(
serverId,
new Map([
[
"agent-1",
{
...agentSnapshot("claude"),
serverId,
parentAgentId: null,
createdAt: new Date(TS),
updatedAt: new Date(TS),
lastUserMessageAt: null,
lastActivityAt: new Date(TS),
attentionTimestamp: null,
archivedAt: null,
status: "idle",
turn: { phase: "idle", cancellationRequestId: null },
},
],
]),
);
sessionStore.setQueuedMessages(
serverId,
new Map([
[
"agent-1",
[
{ id: "m1", text: "First switch to Codex", attachments: [] },
{ id: "m2", text: "Second switch to Copilot", attachments: [] },
],
],
]),
);
useStagedProviderSwitchStore.getState().stage(serverId, "agent-1", {
provider: "codex",
model: "gpt-5.4",
thinkingOptionId: null,
modeId: null,
providerOptions: {},
});
// M1 begins switching to Codex.
runtime.drainQueuedAgentMessage(serverId, "agent-1");
await vi.waitFor(() => {
expect(switchedCalls).toEqual([{ provider: "codex", text: "First switch to Codex" }]);
});
// While Codex switch reply is still pending, user selects Copilot for the next prompt.
useStagedProviderSwitchStore.getState().stage(serverId, "agent-1", {
provider: "copilot",
model: "gpt-5",
thinkingOptionId: null,
modeId: null,
providerOptions: {},
});
// Codex switch reply arrives -> MUST NOT clear the newer Copilot draft!
resolveFirstSwitch({ agent: { ...agentSnapshot("codex"), status: "running" } });
await new Promise((resolve) => setTimeout(resolve, 30));
expect(getStagedProviderSwitch(serverId, "agent-1")?.provider).toBe("copilot");
// Once Codex goes idle and queue resumes, M2 MUST switch to Copilot (not send plainly to Codex).
sessionStore.setAgents(
serverId,
new Map([
[
"agent-1",
{
...agentSnapshot("codex"),
serverId,
parentAgentId: null,
createdAt: new Date(TS),
updatedAt: new Date(TS),
lastUserMessageAt: null,
lastActivityAt: new Date(TS),
attentionTimestamp: null,
archivedAt: null,
status: "idle",
turn: { phase: "idle", cancellationRequestId: null },
},
],
]),
);
runtime.drainQueuedAgentMessage(serverId, "agent-1");
await vi.waitFor(() => {
expect(switchedCalls).toEqual([
{ provider: "codex", text: "First switch to Codex" },
{ provider: "copilot", text: "Second switch to Copilot" },
]);
});
expect(sentCalls).toEqual([]);
expect(getStagedProviderSwitch(serverId, "agent-1")).toBeNull();
sessionStore.clearSession(serverId);
});
it("forwards target provider setting edits made during switch startup to the live agent and surfaces failed automatic drain errors", async () => {
const serverId = "srv-edited-and-failed-queue";
let resolveSwitch!: (value: { agent?: AgentSnapshotPayload }) => void;
const setAgentModel = vi.fn().mockResolvedValue(undefined);
const setAgentMode = vi.fn().mockResolvedValue(null);
const setAgentThinkingOption = vi.fn().mockResolvedValue(undefined);
const setAgentOptions = vi.fn().mockResolvedValue(undefined);
let failNextSwitch = false;
const fakeClient = {
switchAgentProvider: vi.fn((_agentId: string, _opts: { provider: string; text: string }) => {
if (failNextSwitch) {
return Promise.reject(new Error("Codex CLI is not available"));
}
return new Promise<{ agent?: AgentSnapshotPayload }>((resolve) => {
resolveSwitch = resolve;
});
}),
sendAgentMessage: vi.fn(),
setAgentModel,
setAgentMode,
setAgentThinkingOption,
setAgentOptions,
uploadFile: vi.fn(),
} as unknown as DaemonClient;
const runtime = new HostRuntimeStore({
deps: {
createClient: () => fakeClient,
connectToDaemon: async () => ({ client: fakeClient, serverId, hostname: null }),
getClientId: async () => "cid_edited_and_failed_queue",
},
});
const sessionStore = useSessionStore.getState();
sessionStore.initializeSession(serverId, fakeClient, 1);
useSessionStore.setState((state) => ({
sessions: {
...state.sessions,
[serverId]: {
...state.sessions[serverId]!,
serverInfo: {
serverId,
hostname: "localhost",
version: "0.18.0",
features: { providerSwitching: true },
},
},
},
}));
sessionStore.setAgents(
serverId,
new Map([
[
"agent-1",
{
...agentSnapshot("claude"),
serverId,
parentAgentId: null,
createdAt: new Date(TS),
updatedAt: new Date(TS),
lastUserMessageAt: null,
lastActivityAt: new Date(TS),
attentionTimestamp: null,
archivedAt: null,
status: "idle",
turn: { phase: "idle", cancellationRequestId: null },
},
],
]),
);
sessionStore.setQueuedMessages(
serverId,
new Map([["agent-1", [{ id: "m1", text: "Switch with startup edit", attachments: [] }]]]),
);
useStagedProviderSwitchStore.getState().stage(serverId, "agent-1", {
provider: "codex",
model: "gpt-5.3",
thinkingOptionId: "low",
modeId: "auto",
providerOptions: { fast_mode: false },
});
// 1. Pre-commit automatic drain failure restores queue item and exposes error in session store.
failNextSwitch = true;
runtime.drainQueuedAgentMessage(serverId, "agent-1");
await vi.waitFor(() => {
expect(useSessionStore.getState().sessions[serverId]?.queuedSendErrors.get("agent-1")).toBe(
"Codex CLI is not available",
);
});
expect(useSessionStore.getState().sessions[serverId]?.queuedMessages.get("agent-1")).toEqual([
{ id: "m1", text: "Switch with startup edit", attachments: [] },
]);
// 2. Retry succeeds: while switch reply is pending, user edits Codex model/thinking/mode/options.
failNextSwitch = false;
runtime.drainQueuedAgentMessage(serverId, "agent-1");
await vi.waitFor(() => {
expect(fakeClient.switchAgentProvider).toHaveBeenCalledTimes(2);
});
expect(useSessionStore.getState().sessions[serverId]?.queuedSendErrors.get("agent-1")).toBe(
undefined,
);
useStagedProviderSwitchStore.getState().patch(serverId, "agent-1", (current) => ({
...current,
model: "gpt-5.4",
modeId: "full-auto",
thinkingOptionId: "high",
providerOptions: { fast_mode: true },
}));
resolveSwitch({ agent: { ...agentSnapshot("codex"), status: "running" } });
await vi.waitFor(() => {
expect(getStagedProviderSwitch(serverId, "agent-1")).toBeNull();
expect(setAgentModel).toHaveBeenCalledWith("agent-1", "gpt-5.4", {
expectedProvider: "codex",
});
expect(setAgentMode).toHaveBeenCalledWith("agent-1", "full-auto", {
expectedProvider: "codex",
});
expect(setAgentThinkingOption).toHaveBeenCalledWith("agent-1", "high", {
expectedProvider: "codex",
});
expect(setAgentOptions).toHaveBeenCalledWith(
"agent-1",
{ fast_mode: true },
{ expectedProvider: "codex" },
);
});
sessionStore.clearSession(serverId);
});
it("holds queued follow-up M2 until edited startup settings (including plan_mode) finish applying, and retains the draft if an edit rejects", async () => {
const serverId = "srv-startup-edit-ordering";
const callOrder: string[] = [];
let resolveSwitch!: (value: { agent?: AgentSnapshotPayload }) => void;
let resolveApplyConfig!: () => void;
let rejectApplyConfig: ((err: Error) => void) | null = null;
const fakeClient = {
switchAgentProvider: vi.fn((_agentId: string, _opts: { provider: string; text: string }) => {
callOrder.push("switch:codex");
return new Promise<{ agent?: AgentSnapshotPayload }>((resolve) => {
resolveSwitch = resolve;
});
}),
applyAgentConfig: vi.fn((_agentId: string, config: unknown, opts?: unknown) => {
callOrder.push(`applyConfig:${JSON.stringify({ config, opts })}`);
return new Promise<null>((resolve, reject) => {
resolveApplyConfig = () => resolve(null);
rejectApplyConfig = reject;
});
}),
sendAgentMessage: vi.fn(async (_agentId: string, text: string) => {
callOrder.push(`send:${text}`);
return { messageId: "m2-ack" };
}),
uploadFile: vi.fn(),
} as unknown as DaemonClient;
const runtime = new HostRuntimeStore({
deps: {
createClient: () => fakeClient,
connectToDaemon: async () => ({ client: fakeClient, serverId, hostname: null }),
getClientId: async () => "cid_startup_edit_ordering",
},
});
const sessionStore = useSessionStore.getState();
sessionStore.initializeSession(serverId, fakeClient, 1);
useSessionStore.setState((state) => ({
sessions: {
...state.sessions,
[serverId]: {
...state.sessions[serverId]!,
serverInfo: {
serverId,
hostname: "localhost",
version: "0.18.0",
features: { providerSwitching: true },
},
},
},
}));
sessionStore.setAgents(
serverId,
new Map([
[
"agent-1",
{
...agentSnapshot("claude"),
serverId,
parentAgentId: null,
createdAt: new Date(TS),
updatedAt: new Date(TS),
lastUserMessageAt: null,
lastActivityAt: new Date(TS),
attentionTimestamp: null,
archivedAt: null,
status: "idle",
turn: { phase: "idle", cancellationRequestId: null },
},
],
]),
);
sessionStore.setQueuedMessages(
serverId,
new Map([
[
"agent-1",
[
{ id: "m1", text: "First prompt", attachments: [] },
{ id: "m2", text: "Follow-up in Plan mode", attachments: [] },
],
],
]),
);
useStagedProviderSwitchStore.getState().stage(serverId, "agent-1", {
provider: "codex",
model: "gpt-5.3",
thinkingOptionId: null,
modeId: null,
providerOptions: { plan_mode: false },
});
// M1 starts switching; while Codex opens, user changes model AND enables plan_mode.
runtime.drainQueuedAgentMessage(serverId, "agent-1");
await vi.waitFor(() => {
expect(callOrder).toEqual(["switch:codex"]);
});
useStagedProviderSwitchStore.getState().patch(serverId, "agent-1", (current) => ({
...current,
model: "gpt-5.4",
providerOptions: { plan_mode: true },
}));
const settled = await settleCommittedProviderSwitch({
serverId,
agentId: "agent-1",
sentDraft,
committedProvider: "codex",
client: {
setAgentModel: record("model"),
setAgentMode: record("mode"),
setAgentThinkingOption: record("thinking"),
setAgentOptions: record("options"),
},
});
// Fast turn finishes idle and triggers queue drain BEFORE switch + settings edits complete.
runtime.drainQueuedAgentMessage(serverId, "agent-1");
resolveSwitch({ agent: { ...agentSnapshot("codex"), status: "idle" } });
const opts = { expectedProvider: "codex" };
expect(settled).toEqual({ applied: true });
expect(applied).toEqual([
{ setting: "model", value: "gpt-5.4", opts },
{ setting: "mode", value: "full-auto", opts },
{ setting: "thinking", value: "high", opts },
{ setting: "options", value: { plan_mode: true }, opts },
]);
await vi.waitFor(() => {
expect(callOrder).toHaveLength(2);
});
// M2 MUST NOT have sent yet while applyAgentConfig (model + plan_mode: true) is still pending!
expect(callOrder.some((entry) => entry.startsWith("send:"))).toBe(false);
// Once applyAgentConfig completes, M2 drains strictly AFTER plan_mode: true took effect!
resolveApplyConfig();
await vi.waitFor(() => {
expect(callOrder).toHaveLength(3);
});
expect(callOrder[1]).toContain('"plan_mode":true');
expect(callOrder[1]).toContain('"modelId":"gpt-5.4"');
expect(callOrder[1]).toContain('"expectedProvider":"codex"');
expect(callOrder[2]).toBe("send:Follow-up in Plan mode");
expect(getStagedProviderSwitch(serverId, "agent-1")).toBeNull();
});
it("keeps rejected startup settings until the user retries or dismisses them", async () => {
const serverId = "srv-rejected-startup-edits";
const configs: unknown[] = [];
let rejection: Error | null = new Error("Plan mode rejected by provider");
const client = {
applyAgentConfig: async (_agentId: string, config: unknown, opts?: unknown) => {
configs.push({ config, opts });
if (rejection) throw rejection;
return null;
},
} as unknown as DaemonClient;
const runtime = new HostRuntimeStore({
deps: {
createClient: () => client,
connectToDaemon: async () => ({ client, serverId, hostname: null }),
getClientId: async () => "cid_rejected_startup_edits",
},
// Case 2: If daemon rejects the edited settings, draft is RETAINED, error is surfaced, and M2 is HELD.
callOrder.length = 0;
sessionStore.setQueuedMessages(
serverId,
new Map([
[
"agent-1",
[
{ id: "m3", text: "Switch with rejected edit", attachments: [] },
{ id: "m4", text: "Must stay queued", attachments: [] },
],
],
]),
);
useStagedProviderSwitchStore.getState().stage(serverId, "agent-1", {
provider: "codex",
model: "gpt-5.3",
thinkingOptionId: null,
modeId: null,
providerOptions: { plan_mode: false },
});
runtime.drainQueuedAgentMessage(serverId, "agent-1");
await vi.waitFor(() => {
expect(callOrder).toEqual(["switch:codex"]);
});
useStagedProviderSwitchStore.getState().patch(serverId, "agent-1", (current) => ({
...current,
providerOptions: { plan_mode: true },
}));
runtime.drainQueuedAgentMessage(serverId, "agent-1");
resolveSwitch({ agent: { ...agentSnapshot("codex"), status: "idle" } });
await vi.waitFor(() => {
expect(callOrder).toHaveLength(2);
});
useSessionStore.getState().initializeSession(serverId, client, 1);
const rejectEdit = async () => {
useStagedProviderSwitchStore.getState().stage(serverId, "agent-1", sentDraft);
useStagedProviderSwitchStore.getState().patch(serverId, "agent-1", (current) => ({
...current,
providerOptions: { plan_mode: true },
}));
return await settleCommittedProviderSwitch({
serverId,
agentId: "agent-1",
sentDraft,
committedProvider: "codex",
client,
});
};
expect(await rejectEdit()).toEqual({
applied: false,
errorMessage: "Plan mode rejected by provider",
rejectApplyConfig!(new Error("Plan mode rejected by provider"));
await vi.waitFor(() => {
expect(useSessionStore.getState().sessions[serverId]?.queuedSendErrors.get("agent-1")).toBe(
"Plan mode rejected by provider",
);
});
// The model picker clears the staged draft on a live change. The failure stays.
clearStagedProviderSwitch(serverId, "agent-1");
expect(getFailedStartupSettings(serverId, "agent-1")?.bundle).toEqual({
options: { plan_mode: true },
});
rejection = null;
expect(await runtime.recoverFailedStartupSettings(serverId, "agent-1", "retry")).toBe(true);
expect(configs).toEqual(
Array(2).fill({
config: { options: { plan_mode: true } },
opts: { expectedProvider: "codex" },
}),
// Ordinary draft actions (like the model picker calling clearStagedProviderSwitch on a live
// Codex model change) and later drain callbacks MUST leave failedStartupSettings and the queue
// hold intact until the user explicitly chooses Retry or Dismiss!
clearStagedProviderSwitch(serverId, "agent-1");
runtime.drainQueuedAgentMessage(serverId, "agent-1");
await new Promise((resolve) => setTimeout(resolve, 25));
expect(useSessionStore.getState().sessions[serverId]?.queuedSendErrors.get("agent-1")).toBe(
"Plan mode rejected by provider",
);
expect(getFailedStartupSettings(serverId, "agent-1")?.bundle).toEqual({
options: { plan_mode: true },
});
expect(callOrder.some((entry) => entry.startsWith("send:"))).toBe(false);
expect(useSessionStore.getState().sessions[serverId]?.queuedMessages.get("agent-1")).toEqual([
{ id: "m4", text: "Must stay queued", attachments: [] },
]);
// Retrying via the single recovery action re-applies the exact failed bundle (plan_mode: true)
// and automatically resumes the idle queue strictly AFTER the retry succeeds!
const retryPromise = runtime.recoverFailedStartupSettings(serverId, "agent-1", "retry");
await vi.waitFor(() => {
expect(callOrder).toHaveLength(3);
});
expect(callOrder[2]).toContain('"plan_mode":true');
// Still waiting for applyAgentConfig response -> M4 MUST NOT send yet!
expect(callOrder.some((entry) => entry.startsWith("send:"))).toBe(false);
resolveApplyConfig();
expect(await retryPromise).toBe(true);
await vi.waitFor(() => {
expect(callOrder).toContain("send:Must stay queued");
});
expect(getFailedStartupSettings(serverId, "agent-1")).toBeNull();
expect(useSessionStore.getState().sessions[serverId]?.queuedSendErrors.get("agent-1")).toBe(
undefined,
);
// Case 3: Explicit discard clears the failed settings and resumes an idle queue immediately.
callOrder.length = 0;
sessionStore.setQueuedMessages(
serverId,
new Map([
[
"agent-1",
[
{ id: "m5", text: "Switch with discarded edit", attachments: [] },
{ id: "m6", text: "Send after explicit discard", attachments: [] },
],
],
]),
);
useStagedProviderSwitchStore.getState().stage(serverId, "agent-1", {
provider: "codex",
model: "gpt-5.3",
thinkingOptionId: null,
modeId: null,
providerOptions: { plan_mode: false },
});
runtime.drainQueuedAgentMessage(serverId, "agent-1");
await vi.waitFor(() => {
expect(callOrder).toEqual(["switch:codex"]);
});
useStagedProviderSwitchStore.getState().patch(serverId, "agent-1", (current) => ({
...current,
providerOptions: { plan_mode: true },
}));
runtime.drainQueuedAgentMessage(serverId, "agent-1");
resolveSwitch({ agent: { ...agentSnapshot("codex"), status: "idle" } });
await vi.waitFor(() => {
expect(callOrder).toHaveLength(2);
});
rejectApplyConfig!(new Error("Disconnected"));
await vi.waitFor(() => {
expect(getFailedStartupSettings(serverId, "agent-1")?.errorMessage).toBe("Disconnected");
});
expect(callOrder.some((entry) => entry.startsWith("send:"))).toBe(false);
rejection = new Error("Disconnected");
await rejectEdit();
expect(await runtime.recoverFailedStartupSettings(serverId, "agent-1", "discard")).toBe(true);
await vi.waitFor(() => {
expect(callOrder).toContain("send:Send after explicit discard");
});
expect(getFailedStartupSettings(serverId, "agent-1")).toBeNull();
expect(configs).toHaveLength(3);
useSessionStore.getState().clearSession(serverId);
sessionStore.clearSession(serverId);
});
it("places optimistic switch marker above submitted message, upgrades in place on commit, and handles failure and cache cleanly", async () => {
@@ -1,6 +1,6 @@
import { create } from "zustand";
import type { AgentProvider, ProviderOptions } from "@getpaseo/protocol/agent-types";
import type { AgentConfigApply, QueuedProviderSwitch } from "@getpaseo/protocol/messages";
import type { AgentConfigApply } from "@getpaseo/protocol/messages";
export interface StagedProviderSwitch {
provider: AgentProvider;
@@ -187,17 +187,6 @@ export const useStagedProviderSwitchStore = create<StagedProviderSwitchState>((s
}),
}));
/** A switch the host holds in its queue, as the composer stages it. */
export function toStagedProviderSwitch(queued: QueuedProviderSwitch): StagedProviderSwitch {
return {
provider: queued.provider,
model: queued.model ?? null,
modeId: queued.modeId ?? null,
thinkingOptionId: queued.thinkingOptionId ?? null,
providerOptions: queued.providerOptions ?? {},
};
}
export function getStagedProviderSwitch(
serverId: string,
agentId: string,
@@ -1,144 +0,0 @@
import type { PaseoAgentQueueItem } from "@getpaseo/client";
import { afterEach, describe, expect, it } from "vitest";
import { createAgentQueueModel } from "@/agent-queue/model";
import { startAgentQueueDaemon, type AgentQueueDaemon } from "@/test/agent-queue-daemon";
import { cancelQueuedMessage, editQueuedMessage, sendQueuedMessageNow } from "./actions";
const upload = {
type: "uploaded_file" as const,
id: "upload-1",
fileName: "photo.png",
mimeType: "image/png",
size: 1,
path: "/tmp/photo.png",
role: "image" as const,
};
const queued: PaseoAgentQueueItem = {
id: "a",
seq: 1,
enqueuedAt: "2026-11-30T00:00:00.000Z",
text: "look at this",
attachments: [upload],
sender: { kind: "user" },
held: false,
state: "queued",
};
const daemons: AgentQueueDaemon[] = [];
afterEach(async () => {
await Promise.all(daemons.splice(0).map((daemon) => daemon.close()));
});
/** A real queue model over a host that already holds one message. */
async function queueHolding(
message: PaseoAgentQueueItem,
options: { refuse?: "already_dispatching" } = {},
) {
const daemon = await startAgentQueueDaemon();
daemons.push(daemon);
await daemon.publish("agent", { held: false, items: [message] });
if (options.refuse) daemon.refuseWithdrawals(options.refuse);
const model = createAgentQueueModel({ serverId: "host", agentId: "agent", host: daemon.host });
model.subscribe(() => {});
await daemon.settle();
const restored: Array<{ text: string; attachments: unknown[] }> = [];
let alreadySending = 0;
return {
model,
promoted: () =>
daemon.commands().map((command) => `${command.messageId}:${command.activeTurnBehavior}`),
restored,
alreadySendingCount: () => alreadySending,
composer: {
restore: (value: { text: string; attachments: unknown[] }) => restored.push(value),
alreadySending: () => {
alreadySending += 1;
},
},
};
}
describe("editQueuedMessage", () => {
it("puts the withdrawn text and attachments back in the composer", async () => {
const queue = await queueHolding(queued);
await editQueuedMessage({ model: queue.model, messageId: "a", ...queue.composer });
expect(queue.restored).toEqual([
{
text: "look at this",
attachments: [{ kind: "agent_attachment", attachment: upload }],
providerSwitch: null,
},
]);
expect(queue.alreadySendingCount()).toBe(0);
expect(queue.model.getSnapshot().items).toEqual([]);
});
it("gives back the provider switch the message was queued with", async () => {
const queue = await queueHolding({
...queued,
providerSwitch: { provider: "codex", model: "gpt-5.4" },
});
await editQueuedMessage({ model: queue.model, messageId: "a", ...queue.composer });
expect(queue.restored).toMatchObject([
{
providerSwitch: {
provider: "codex",
model: "gpt-5.4",
modeId: null,
thinkingOptionId: null,
providerOptions: {},
},
},
]);
});
it("leaves the composer alone when the message already started sending", async () => {
const queue = await queueHolding(queued, { refuse: "already_dispatching" });
await editQueuedMessage({ model: queue.model, messageId: "a", ...queue.composer });
expect(queue.restored).toEqual([]);
expect(queue.alreadySendingCount()).toBe(1);
});
});
describe("cancelQueuedMessage", () => {
it("withdraws the message without touching the composer", async () => {
const queue = await queueHolding(queued);
await cancelQueuedMessage({ model: queue.model, messageId: "a", ...queue.composer });
expect(queue.model.getSnapshot().items).toEqual([]);
expect(queue.restored).toEqual([]);
expect(queue.alreadySendingCount()).toBe(0);
});
it("says so when the message already started sending", async () => {
const queue = await queueHolding(queued, { refuse: "already_dispatching" });
await cancelQueuedMessage({ model: queue.model, messageId: "a", ...queue.composer });
expect(queue.alreadySendingCount()).toBe(1);
});
});
describe("sendQueuedMessageNow", () => {
it.each([
["steer", "a:steer"],
["interrupt", "a:interrupt"],
["queue", "a:interrupt"],
] as const)("with the %s send behavior promotes as %s", async (sendBehavior, expected) => {
const queue = await queueHolding(queued);
await sendQueuedMessageNow({ model: queue.model, messageId: "a", sendBehavior });
expect(queue.promoted()).toEqual([expected]);
});
});
@@ -1,56 +0,0 @@
import type { AgentQueueModel } from "@/agent-queue";
import type { UserComposerAttachment } from "@/attachments/types";
import type { SendBehavior } from "@/composer/input/state";
import { toStagedProviderSwitch, type StagedProviderSwitch } from "@/composer/provider-switch";
export interface RestoredQueuedMessage {
text: string;
attachments: UserComposerAttachment[];
/** The switch the message was queued with, to stage again. */
providerSwitch: StagedProviderSwitch | null;
}
interface WithdrawInput {
model: Pick<AgentQueueModel, "withdraw">;
messageId: string;
/** The message left the queue before the host got the request. */
alreadySending: () => void;
}
/** Moves a queued message back into the composer. Only the host can say it is still queued. */
export async function editQueuedMessage(
input: WithdrawInput & { restore: (message: RestoredQueuedMessage) => void },
): Promise<void> {
const result = await input.model.withdraw(input.messageId);
if (!result) return;
if (!result.withdrawn) {
input.alreadySending();
return;
}
input.restore({
text: result.item.text,
attachments: (result.item.attachments ?? []).map((attachment) => ({
kind: "agent_attachment",
attachment,
})),
providerSwitch: result.item.providerSwitch
? toStagedProviderSwitch(result.item.providerSwitch)
: null,
});
}
export async function cancelQueuedMessage(input: WithdrawInput): Promise<void> {
const result = await input.model.withdraw(input.messageId);
if (result && !result.withdrawn) input.alreadySending();
}
export async function sendQueuedMessageNow(input: {
model: Pick<AgentQueueModel, "promote">;
messageId: string;
sendBehavior: SendBehavior;
}): Promise<void> {
await input.model.promote(
input.messageId,
input.sendBehavior === "steer" ? "steer" : "interrupt",
);
}
-334
View File
@@ -1,334 +0,0 @@
import { useCallback, useMemo, type ReactElement, type ReactNode } from "react";
import { Text, View } from "react-native";
import { useTranslation } from "react-i18next";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { useShallow } from "zustand/shallow";
import {
ArrowRightLeft,
ArrowUp,
Bot,
GitPullRequest,
Paperclip,
Pause,
Pencil,
X,
} from "lucide-react-native";
import type { PaseoAgentQueueItem } from "@getpaseo/client";
import { useAgentQueue } from "@/agent-queue";
import { Button } from "@/components/ui/button";
import { mutedIconColorMapping } from "@/components/ui/icon-button-chrome";
import { paneContentToolbarIconSize, ToolbarButton } from "@/components/ui/pane-content-toolbar";
import { ScrollView } from "@/components/ui/scroll-view";
import { useIsCompactFormFactor } from "@/constants/layout";
import type { SendBehavior } from "@/composer/input/state";
import { COMPOSER_PADDING_HORIZONTAL } from "@/composer/input/toolbar-rails";
import { useSessionStore } from "@/stores/session-store";
import { ICON_SIZE } from "@/styles/theme";
import {
cancelQueuedMessage,
editQueuedMessage,
sendQueuedMessageNow,
type RestoredQueuedMessage,
} from "./actions";
import { presentQueue, type QueueRowView } from "./view";
const ThemedArrowRightLeft = withUnistyles(ArrowRightLeft);
const ThemedArrowUp = withUnistyles(ArrowUp);
const ThemedBot = withUnistyles(Bot);
const ThemedGitPullRequest = withUnistyles(GitPullRequest);
const ThemedPaperclip = withUnistyles(Paperclip);
const ThemedPause = withUnistyles(Pause);
const ThemedPencil = withUnistyles(Pencil);
const ThemedX = withUnistyles(X);
/** A few rows and the top of the next, so a longer queue reads as scrollable. */
const QUEUE_MAX_HEIGHT = 240;
/** Keep ~2 rows readable on phones without crowding the conversation or composer. */
const QUEUE_MAX_HEIGHT_COMPACT = 140;
interface ComposerQueueTrackProps {
serverId: string;
agentId: string;
/** The user's send behavior setting. Send now steers or interrupts accordingly. */
sendBehavior: SendBehavior;
providerLabel: (provider: string) => string;
onRestore: (message: RestoredQueuedMessage) => void;
onAlreadySending: () => void;
onError: (error: unknown) => void;
}
/** The messages the host holds for this agent, in the order it will send them. */
export function ComposerQueueTrack({
serverId,
agentId,
sendBehavior,
providerLabel,
onRestore,
onAlreadySending,
onError,
}: ComposerQueueTrackProps): ReactElement | null {
const { t } = useTranslation();
const isCompact = useIsCompactFormFactor();
const { model, queue } = useAgentQueue(serverId, agentId);
const titles = useSessionStore(useShallow(selectSenderTitles(queue.items, serverId)));
const view = useMemo(
() =>
presentQueue(queue, {
t,
agentTitle: (senderId) => titles[senderId] ?? null,
providerLabel,
}),
[providerLabel, queue, t, titles],
);
const handleEdit = useCallback(
(messageId: string) => {
editQueuedMessage({
model,
messageId,
restore: onRestore,
alreadySending: onAlreadySending,
}).catch(onError);
},
[model, onRestore, onAlreadySending, onError],
);
const handleCancel = useCallback(
(messageId: string) => {
cancelQueuedMessage({ model, messageId, alreadySending: onAlreadySending }).catch(onError);
},
[model, onAlreadySending, onError],
);
const handleSendNow = useCallback(
(messageId: string) => {
sendQueuedMessageNow({ model, messageId, sendBehavior }).catch(onError);
},
[model, sendBehavior, onError],
);
const failedToLoad = queue.status === "error";
if (view.rows.length === 0 && !failedToLoad) return null;
return (
<View style={styles.track}>
{failedToLoad ? (
<View style={styles.status}>
<Text style={styles.muted}>{t("composer.queue.loadFailed")}</Text>
<Button variant="ghost" size="sm" onPress={model.retry}>
{t("composer.queue.retry")}
</Button>
</View>
) : null}
{view.notice ? (
<View style={styles.status}>
<LineIcon>
<ThemedPause size={ICON_SIZE.xs} uniProps={mutedIconColorMapping} />
</LineIcon>
<Text style={styles.muted}>{view.notice}</Text>
</View>
) : null}
{/* The frame sizes the list: a style on this ScrollView is dropped on web. */}
<View style={[styles.rowsFrame, isCompact && styles.rowsFrameCompact]}>
<ScrollView keyboardShouldPersistTaps="handled" nestedScrollEnabled>
<View style={styles.rows} role="list" aria-label={t("composer.queue.title")}>
{view.rows.map((row) => (
<QueueRow
key={row.id}
row={row}
onEdit={handleEdit}
onCancel={handleCancel}
onSendNow={handleSendNow}
/>
))}
</View>
</ScrollView>
</View>
</View>
);
}
/** An icon beside text that truncates keeps its size; the text gives up the width. */
function LineIcon({ children }: { children: ReactNode }): ReactElement {
return <View style={styles.lineIcon}>{children}</View>;
}
function selectSenderTitles(items: readonly PaseoAgentQueueItem[], hostId: string) {
return (state: ReturnType<typeof useSessionStore.getState>): Record<string, string> => {
const titles: Record<string, string> = {};
for (const { sender } of items) {
if (sender.kind !== "agent_message" && sender.kind !== "agent_notification") continue;
const session = state.sessions[sender.serverId ?? hostId];
const agent =
session?.agents.get(sender.agentId) ?? session?.agentDetails.get(sender.agentId);
if (agent?.title) titles[sender.agentId] = agent.title;
}
return titles;
};
}
function QueueRow({
row,
onEdit,
onCancel,
onSendNow,
}: {
row: QueueRowView;
onEdit: (messageId: string) => void;
onCancel: (messageId: string) => void;
onSendNow: (messageId: string) => void;
}): ReactElement {
const { t } = useTranslation();
const isCompact = useIsCompactFormFactor();
const iconSize = paneContentToolbarIconSize(isCompact);
const handleEdit = useCallback(() => onEdit(row.id), [onEdit, row.id]);
const handleCancel = useCallback(() => onCancel(row.id), [onCancel, row.id]);
const handleSendNow = useCallback(() => onSendNow(row.id), [onSendNow, row.id]);
return (
<View style={styles.row} role="listitem">
<View style={styles.body}>
{row.label ? (
<View style={styles.meta}>
<LineIcon>
{row.icon === "change_request" ? (
<ThemedGitPullRequest size={ICON_SIZE.xs} uniProps={mutedIconColorMapping} />
) : (
<ThemedBot size={ICON_SIZE.xs} uniProps={mutedIconColorMapping} />
)}
</LineIcon>
<Text style={styles.metaText} numberOfLines={1}>
{row.label}
</Text>
</View>
) : null}
{row.preview ? (
<Text style={styles.preview} numberOfLines={2} ellipsizeMode="tail">
{row.preview}
</Text>
) : null}
{row.attachmentLabel ? (
<View style={styles.meta}>
<LineIcon>
<ThemedPaperclip size={ICON_SIZE.xs} uniProps={mutedIconColorMapping} />
</LineIcon>
<Text style={styles.metaText}>{row.attachmentLabel}</Text>
</View>
) : null}
{row.switchLabel ? (
<View style={styles.meta}>
<LineIcon>
<ThemedArrowRightLeft size={ICON_SIZE.xs} uniProps={mutedIconColorMapping} />
</LineIcon>
<Text style={styles.metaText} numberOfLines={1}>
{row.switchLabel}
</Text>
</View>
) : null}
</View>
<View style={styles.actions}>
{row.canEdit ? (
<ToolbarButton
label={t("composer.queue.edit")}
tooltipSide="top"
compact={isCompact}
disabled={row.disabled}
onPress={handleEdit}
>
<ThemedPencil size={iconSize} uniProps={mutedIconColorMapping} />
</ToolbarButton>
) : null}
<ToolbarButton
label={t("composer.queue.sendNow")}
tooltipSide="top"
compact={isCompact}
disabled={row.disabled}
onPress={handleSendNow}
>
<ThemedArrowUp size={iconSize} uniProps={mutedIconColorMapping} />
</ToolbarButton>
<ToolbarButton
label={t("composer.queue.cancel")}
tooltipSide="top"
compact={isCompact}
disabled={row.disabled}
onPress={handleCancel}
>
<ThemedX size={iconSize} uniProps={mutedIconColorMapping} />
</ToolbarButton>
</View>
</View>
);
}
const styles = StyleSheet.create((theme) => ({
// The composer's height is capped. When it runs out, the queue gives up height and its rows
// scroll before the message input shrinks.
track: {
flexShrink: 1000,
minHeight: 0,
gap: theme.spacing[2],
},
// Rows put their text on the composer's text rail: the same border, then the same padding.
// The status line carries a clear border to land there too.
status: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[2],
paddingHorizontal: COMPOSER_PADDING_HORIZONTAL,
borderLeftWidth: theme.borderWidth[1],
borderColor: "transparent",
},
muted: {
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.sm,
},
rowsFrame: {
flexShrink: 1,
minHeight: 0,
maxHeight: QUEUE_MAX_HEIGHT,
},
rowsFrameCompact: {
maxHeight: QUEUE_MAX_HEIGHT_COMPACT,
},
rows: {
gap: theme.spacing[2],
},
row: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[2],
paddingLeft: COMPOSER_PADDING_HORIZONTAL,
paddingRight: theme.spacing[2],
paddingVertical: theme.spacing[2],
backgroundColor: theme.colors.surface1,
borderRadius: theme.borderRadius.lg,
borderWidth: theme.borderWidth[1],
borderColor: theme.colors.border,
},
body: {
flex: 1,
minWidth: 0,
gap: theme.spacing[1],
},
meta: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[1],
},
lineIcon: {
flexShrink: 0,
},
metaText: {
flexShrink: 1,
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.sm,
},
preview: {
color: theme.colors.foreground,
fontSize: theme.fontSize.base,
},
actions: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[1],
},
}));
@@ -1,156 +0,0 @@
import type { PaseoAgentQueueItem } from "@getpaseo/client";
import { describe, expect, it } from "vitest";
import { i18n } from "@/i18n/i18next";
import { presentQueue } from "./view";
function item(id: string, patch: Partial<PaseoAgentQueueItem> = {}): PaseoAgentQueueItem {
return {
id,
seq: 1,
enqueuedAt: "2026-11-30T00:00:00.000Z",
text: `message ${id}`,
sender: { kind: "user" },
held: false,
state: "queued",
...patch,
};
}
function present(
items: PaseoAgentQueueItem[],
options: { held?: boolean; busy?: string[]; titles?: Record<string, string> } = {},
) {
return presentQueue(
{
status: "ready",
held: options.held ?? false,
items,
busy: new Set(options.busy),
},
{
t: i18n.t,
agentTitle: (agentId) => options.titles?.[agentId] ?? null,
providerLabel: (provider) => provider.toUpperCase(),
},
);
}
describe("presentQueue", () => {
it("lists a user message with its attachments and lets it be edited", () => {
const queue = present([
item("a", {
text: "line one\nline two",
attachments: [
{
type: "uploaded_file",
id: "upload-1",
fileName: "photo.png",
mimeType: "image/png",
size: 1,
path: "/tmp/photo.png",
role: "image",
},
],
}),
]);
expect(queue.rows).toEqual([
{
id: "a",
icon: null,
label: null,
preview: "line one\nline two",
attachmentLabel: "1 attachment",
switchLabel: null,
canEdit: true,
disabled: false,
},
]);
});
it("says which provider a queued message switches the chat to", () => {
const [row] = present([item("a", { providerSwitch: { provider: "codex" } })]).rows;
expect(row).toMatchObject({ switchLabel: "Switches to CODEX" });
});
it("names the agent that sent a message and does not offer Edit", () => {
const sender = { kind: "agent_message" as const, agentId: "child", title: "Old title" };
const [row] = present([item("a", { sender })], { titles: { child: "Reviewer" } }).rows;
expect(row).toMatchObject({ icon: "agent", label: "Sent by Reviewer", canEdit: false });
});
it("falls back to the title the host recorded, then to the agent id", () => {
const rows = present([
item("a", { sender: { kind: "agent_message", agentId: "one", title: "Recorded" } }),
item("b", { sender: { kind: "agent_message", agentId: "two" } }),
]).rows;
expect(rows.map((row) => row.label)).toEqual(["Sent by Recorded", "Sent by two"]);
});
it("labels each agent notification with what happened", () => {
const events = ["finished", "errored", "permission-required", "closed"] as const;
const rows = present(
events.map((event) =>
item(event, {
text: "Agent child (Builder) finished.\n\n<agent-response>\nDone\n</agent-response>",
sender: { kind: "agent_notification", agentId: "child", title: "Builder", event },
}),
),
).rows;
expect(rows.map((row) => row.label)).toEqual([
"Builder finished",
"Builder errored",
"Builder needs permission",
"Builder closed",
]);
expect(rows[0]).toMatchObject({
icon: "agent",
canEdit: false,
preview: "Agent child (Builder) finished. <agent-response> Done </agent-response>",
});
});
it("shows a change request update with its URL, named for the forge", () => {
const rows = present([
item("pr", {
sender: { kind: "change_request_update", url: "https://github.com/acme/app/pull/4" },
}),
item("mr", {
sender: {
kind: "change_request_update",
url: "https://gitlab.com/acme/app/-/merge_requests/4",
},
}),
]).rows;
expect(rows).toMatchObject([
{
icon: "change_request",
label: "PR update",
preview: "https://github.com/acme/app/pull/4",
canEdit: false,
},
{ icon: "change_request", label: "MR update" },
]);
});
it("disables a row that is dispatching or already running a command", () => {
const rows = present([item("a", { state: "dispatching" }), item("b"), item("c")], {
busy: ["b"],
}).rows;
expect(rows.map((row) => row.disabled)).toEqual([true, true, false]);
});
it("says the queue is paused without naming a cause", () => {
expect(present([item("a", { held: true })], { held: true }).notice).toBe(
"Queue paused until you send a message",
);
expect(present([item("a")]).notice).toBeNull();
expect(present([], { held: true }).notice).toBeNull();
});
});
-82
View File
@@ -1,82 +0,0 @@
import type { PaseoAgentQueueItem } from "@getpaseo/client";
import type { TFunction } from "i18next";
import type { AgentQueueSnapshot } from "@/agent-queue";
export interface QueueRowView {
id: string;
icon: "agent" | "change_request" | null;
/** Who or what queued the message. Null for the user's own messages. */
label: string | null;
preview: string;
attachmentLabel: string | null;
/** Names the provider the chat moves to when this message is sent. */
switchLabel: string | null;
canEdit: boolean;
disabled: boolean;
}
export interface QueueView {
/** In send order: the first row goes next. */
rows: QueueRowView[];
notice: string | null;
}
interface PresentQueueContext {
t: TFunction;
/** The current title of an agent this app knows about. */
agentTitle: (agentId: string, serverId?: string) => string | null;
providerLabel: (provider: string) => string;
}
export function presentQueue(queue: AgentQueueSnapshot, context: PresentQueueContext): QueueView {
return {
rows: queue.items.map((item) => ({
id: item.id,
...presentSender(item, context),
attachmentLabel: item.attachments?.length
? context.t("composer.queue.attachmentCount", { count: item.attachments.length })
: null,
switchLabel: item.providerSwitch
? context.t("composer.queue.switchesTo", {
provider: context.providerLabel(item.providerSwitch.provider),
})
: null,
canEdit: item.sender.kind === "user",
disabled: item.state === "dispatching" || queue.busy.has(item.id),
})),
notice: queue.held && queue.items.length > 0 ? context.t("composer.queue.paused") : null,
};
}
function presentSender(
item: PaseoAgentQueueItem,
{ t, agentTitle }: PresentQueueContext,
): Pick<QueueRowView, "icon" | "label" | "preview"> {
const { sender } = item;
if (sender.kind === "user") {
return { icon: null, label: null, preview: item.text };
}
if (sender.kind === "change_request_update") {
const isMergeRequest = sender.url.includes("/merge_requests/");
return {
icon: "change_request",
label: t("composer.queue.changeRequestUpdate", { context: isMergeRequest ? "mr" : "" }),
preview: sender.url,
};
}
const title = agentTitle(sender.agentId, sender.serverId) || sender.title || sender.agentId;
// Messages written for agents open with blank lines and markup. Run them together so the
// two preview lines carry text.
const preview = item.text.replace(/\s+/g, " ").trim();
if (sender.kind === "agent_message") {
return { icon: "agent", label: t("composer.queue.sentBy", { title }), preview };
}
return { icon: "agent", label: t(NOTIFICATION_KEYS[sender.event], { title }), preview };
}
const NOTIFICATION_KEYS = {
finished: "composer.queue.agentFinished",
errored: "composer.queue.agentErrored",
"permission-required": "composer.queue.agentNeedsPermission",
closed: "composer.queue.agentClosed",
} as const;
+28 -58
View File
@@ -104,71 +104,41 @@ describe("submitAgentInput", () => {
expect(clearDraft).toHaveBeenCalledWith("sent");
});
function queueingComposer(queueMessage: () => Promise<void>) {
const composer = {
text: " queued message ",
attachments: [{ id: "img-1" }],
error: null as string | null,
draft: "active",
isProcessing: false,
};
const sent: string[] = [];
const submit = () =>
it("queues while the agent is running and clears the composer immediately", async () => {
const queueMessage = vi.fn();
const submitMessage = vi.fn();
const clearDraft = vi.fn();
const setUserInput = vi.fn();
const setAttachments = vi.fn();
const setSendError = vi.fn();
const setIsProcessing = vi.fn();
await expect(
submitAgentInput({
message: composer.text,
attachments: composer.attachments,
message: " queued message ",
attachments: [{ id: "img-1" }],
isAgentRunning: true,
canSubmit: true,
queueMessage,
submitMessage: async ({ message }) => {
sent.push(message);
},
clearDraft: (lifecycle) => {
composer.draft = lifecycle;
},
setUserInput: (text) => {
composer.text = text;
},
setAttachments: (attachments) => {
composer.attachments = attachments;
},
setSendError: (message) => {
composer.error = message;
},
setIsProcessing: (isProcessing) => {
composer.isProcessing = isProcessing;
},
});
return { composer, sent, submit };
}
submitMessage,
clearDraft,
setUserInput,
setAttachments,
setSendError,
setIsProcessing,
}),
).resolves.toBe("queued");
it("queues while the agent is running and stays busy until the host accepts", async () => {
const accepted = createDeferredPromise<void>();
const { composer, sent, submit } = queueingComposer(() => accepted.promise);
const result = submit();
expect(composer).toMatchObject({ text: "", attachments: [], isProcessing: true });
accepted.resolve();
await expect(result).resolves.toBe("queued");
expect(composer).toMatchObject({ draft: "sent", isProcessing: false, error: null });
expect(sent).toEqual([]);
});
it("restores the composer when the host does not accept a queued message", async () => {
const { composer, submit } = queueingComposer(async () => {
throw new Error("Host disconnected");
});
await expect(submit()).resolves.toBe("failed");
expect(composer).toEqual({
text: "queued message",
expect(queueMessage).toHaveBeenCalledWith({
message: "queued message",
attachments: [{ id: "img-1" }],
error: "Host disconnected",
draft: "active",
isProcessing: false,
});
expect(submitMessage).not.toHaveBeenCalled();
expect(setUserInput).toHaveBeenCalledWith("");
expect(setAttachments).toHaveBeenCalledWith([]);
expect(setSendError).not.toHaveBeenCalled();
expect(setIsProcessing).not.toHaveBeenCalled();
expect(clearDraft).not.toHaveBeenCalled();
});
it("restores the composer when submit fails", async () => {
+11 -6
View File
@@ -11,8 +11,7 @@ export interface AgentInputSubmitActionInput<TAttachment> {
forceSend?: boolean;
isAgentRunning: boolean;
canSubmit: boolean;
/** Resolves once the host has the message in its queue. */
queueMessage: (input: { message: string; attachments: TAttachment[] }) => Promise<void>;
queueMessage: (input: { message: string; attachments: TAttachment[] }) => void;
submitMessage: (input: { message: string; attachments: TAttachment[] }) => Promise<void>;
clearDraft: (lifecycle: "sent" | "abandoned") => void;
setUserInput: (text: string) => void;
@@ -43,7 +42,14 @@ export async function submitAgentInput<TAttachment>(
return "noop";
}
const shouldQueue = input.isAgentRunning && !input.forceSend;
if (input.isAgentRunning && !input.forceSend) {
input.queueMessage({ message: trimmedMessage, attachments });
if (shouldClearOnSubmit) {
input.setUserInput("");
input.setAttachments([]);
}
return "queued";
}
// Clear immediately so the submitted timeline row and composer state stay in sync.
if (shouldClearOnSubmit) {
@@ -54,11 +60,10 @@ export async function submitAgentInput<TAttachment>(
input.setIsProcessing(true);
try {
const deliver = shouldQueue ? input.queueMessage : input.submitMessage;
await deliver({ message: trimmedMessage, attachments });
await input.submitMessage({ message: trimmedMessage, attachments });
input.clearDraft("sent");
input.setIsProcessing(false);
return shouldQueue ? "queued" : "submitted";
return "submitted";
} catch (error) {
input.onSubmitError?.(error);
if (shouldClearOnSubmit) {
@@ -366,6 +366,8 @@ function SessionProviderInternal({ children, serverId, client }: SessionProvider
viewedTimelineSyncRef.current = sync;
setViewedTimelineSync(serverId, sync);
sync.setActive(getIsAppVisible(appStateRef.current));
// An online client replacement leaves isConnected unchanged, so seed each new owner.
sync.setConnected(client.getConnectionState().status === "connected");
const stopObservingOpenChats = observeOpenWorkspaceAgentIds(serverId, (agentIds) =>
sync.replaceOpenTabAgentIds(agentIds),
);
+1 -1
View File
@@ -385,7 +385,7 @@ describe("translation resources", () => {
expect(en.settings.host.notFound).toBe("Host not found");
expect(en.settings.host.connections.title).toBe("Connections");
expect(en.settings.host.daemon.restart.title).toBe("Restart daemon");
expect(en.settings.host.orchestration.enableTools.title).toBe("Enable Paseo tools");
expect(en.settings.host.orchestration.enableTools.title).toBe("Enable tools");
expect(en.settings.providers.title).toBe("Providers");
expect(en.settings.providers.models.addModel).toBe("Add model");
expect(en.settings.providers.diagnostic.title).toBe("Diagnostic");
+26 -25
View File
@@ -173,26 +173,6 @@ export const ar: TranslationResources = {
dictation: "الإملاء",
interruptBeforeVoice: "قم بمقاطعة الوكيل قبل بدء الوضع الصوتي",
},
queue: {
title: "الرسائل المنتظرة",
edit: "تعديل الرسالة في قائمة الانتظار",
sendNow: "إرسال الرسالة المنتظرة الآن",
cancel: "إلغاء الرسالة المنتظرة",
paused: "قائمة الانتظار متوقفة حتى ترسل رسالة",
sentBy: "أُرسلت بواسطة {{title}}",
agentFinished: "انتهى {{title}}",
agentErrored: "حدث خطأ في {{title}}",
agentNeedsPermission: "يحتاج {{title}} إلى إذن",
agentClosed: "أُغلق {{title}}",
changeRequestUpdate: "تحديث PR",
changeRequestUpdate_mr: "تحديث MR",
switchesTo: "ينتقل إلى {{provider}}",
attachmentCount_one: "المرفقات: {{count}}",
attachmentCount_other: "المرفقات: {{count}}",
alreadySending: "الرسالة قيد الإرسال بالفعل",
loadFailed: "تعذر تحميل قائمة الانتظار",
retry: "إعادة المحاولة",
},
attachments: {
addImage: "أضف صورة",
pasteImage: "لصق صورة",
@@ -201,8 +181,9 @@ export const ar: TranslationResources = {
addIssueOrPr_mr: "أضف مشكلة أو MR",
dropImagesHere: "إسقاط الصور هنا",
dropFilesHere: "Drop files here",
editQueuedMessage: "تحرير الرسالة في قائمة الانتظار",
sendQueuedMessageNow: "إرسال رسالة في قائمة الانتظار الآن",
openImage: "فتح مرفق الصورة",
removeAttachment: "إزالة المرفق",
removeImage: "إزالة مرفق الصورة",
removeFile: "Remove file attachment",
openGithub: "افتح {{kind}} {{number}}",
@@ -3166,15 +3147,35 @@ export const ar: TranslationResources = {
tools: {
instructionsTitle: "التعليمات",
toolsTitle: "أدوات الوكلاء",
pluginNote: "الأدوات التي تضيفها الإضافات تتبع أيضًا خيار تمكين الأدوات",
updateHostForGroups: "حدّث هذا المضيف لضبط مجموعات الأدوات الفردية",
groups: {
orchestration: {
title: "التنسيق",
hint: "إدارة مساحات العمل والوكلاء والطرفيات والسكربتات",
},
schedules: {
title: "الجداول الزمنية",
hint: "إنشاء وإدارة الجداول الزمنية ونبضات المتابعة",
},
changeRequests: {
title: "مراقبة طلبات السحب",
hint: "مراقبة تحديثات طلبات السحب والدمج",
},
browser: {
title: "المتصفح",
hint: "التحكم في علامات تبويب متصفح Paseo بما في ذلك الجلسات المسجّل الدخول إليها. فعّل هذا الخيار فقط للوكلاء الموثوقين.",
},
},
},
orchestration: {
title: "التنسيق",
unavailable: "اتصل بهذا المضيف لإدارة التنسيق",
enableTools: {
title: "تمكين أدوات Paseo",
hint: "سيتمكن الوكلاء من إدارة أشجار العمل والوكلاء والجداول الزمنية",
accessibilityLabel: "حقن أدوات Paseo",
updateFailed: "تعذر تحديث أدوات Paseo.",
title: "تمكين الأدوات",
hint: "يسمح لـ Paseo والإضافات بتوفير الأدوات للوكلاء.",
accessibilityLabel: "تمكين الأدوات",
updateFailed: "تعذر تحديث الأدوات.",
},
systemPrompt: {
title: "موجه النظام",
+26 -25
View File
@@ -171,26 +171,6 @@ export const en = {
dictation: "Dictation",
interruptBeforeVoice: "Interrupt the agent before starting voice mode",
},
queue: {
title: "Queued messages",
edit: "Edit queued message",
sendNow: "Send queued message now",
cancel: "Cancel queued message",
paused: "Queue paused until you send a message",
sentBy: "Sent by {{title}}",
agentFinished: "{{title}} finished",
agentErrored: "{{title}} errored",
agentNeedsPermission: "{{title}} needs permission",
agentClosed: "{{title}} closed",
changeRequestUpdate: "PR update",
changeRequestUpdate_mr: "MR update",
switchesTo: "Switches to {{provider}}",
attachmentCount_one: "{{count}} attachment",
attachmentCount_other: "{{count}} attachments",
alreadySending: "Message is already sending",
loadFailed: "Couldn't load the queue",
retry: "Retry",
},
attachments: {
addImage: "Add image",
pasteImage: "Paste image",
@@ -199,8 +179,9 @@ export const en = {
addIssueOrPr_mr: "Add issue or MR",
dropImagesHere: "Drop images here",
dropFilesHere: "Drop files here",
editQueuedMessage: "Edit queued message",
sendQueuedMessageNow: "Send queued message now",
openImage: "Open image attachment",
removeAttachment: "Remove attachment",
removeImage: "Remove image attachment",
removeFile: "Remove file attachment",
openGithub: "Open {{kind}} {{number}}",
@@ -3266,15 +3247,35 @@ export const en = {
tools: {
instructionsTitle: "Instructions",
toolsTitle: "Agent tools",
pluginNote: "Tools added by plugins also follow Enable tools",
updateHostForGroups: "Update this host to configure individual tool groups",
groups: {
orchestration: {
title: "Orchestration",
hint: "Manage workspaces, agents, terminals, and scripts",
},
schedules: {
title: "Schedules",
hint: "Create and manage schedules and heartbeats",
},
changeRequests: {
title: "PR watching",
hint: "Watch pull requests and merge requests for updates",
},
browser: {
title: "Browser",
hint: "Control Paseo browser tabs, including logged-in state. Enable only for agents you trust.",
},
},
},
orchestration: {
title: "Orchestration",
unavailable: "Connect to this host to manage orchestration",
enableTools: {
title: "Enable Paseo tools",
hint: "Agents will be able to manage worktrees, agents and schedules",
accessibilityLabel: "Inject Paseo tools",
updateFailed: "Unable to update Paseo tools.",
title: "Enable tools",
hint: "Let Paseo and plugins give tools to agents.",
accessibilityLabel: "Enable tools",
updateFailed: "Unable to update tools.",
},
systemPrompt: {
title: "System prompt",
+26 -25
View File
@@ -174,26 +174,6 @@ export const es: TranslationResources = {
dictation: "Dictado",
interruptBeforeVoice: "Interrumpir al agente antes de iniciar el modo de voz.",
},
queue: {
title: "Mensajes en cola",
edit: "Editar mensaje en cola",
sendNow: "Enviar ahora el mensaje en cola",
cancel: "Cancelar mensaje en cola",
paused: "Cola en pausa hasta que envíes un mensaje",
sentBy: "Enviado por {{title}}",
agentFinished: "{{title}} terminó",
agentErrored: "{{title}} falló",
agentNeedsPermission: "{{title}} necesita permiso",
agentClosed: "{{title}} se cerró",
changeRequestUpdate: "Actualización de PR",
changeRequestUpdate_mr: "Actualización de MR",
switchesTo: "Cambia a {{provider}}",
attachmentCount_one: "{{count}} adjunto",
attachmentCount_other: "{{count}} adjuntos",
alreadySending: "El mensaje ya se está enviando",
loadFailed: "No se pudo cargar la cola",
retry: "Reintentar",
},
attachments: {
addImage: "Agregar imagen",
pasteImage: "Pegar imagen",
@@ -202,8 +182,9 @@ export const es: TranslationResources = {
addIssueOrPr_mr: "Agregar problema o MR",
dropImagesHere: "Suelta imágenes aquí",
dropFilesHere: "Drop files here",
editQueuedMessage: "Editar mensaje en cola",
sendQueuedMessageNow: "Enviar mensaje en cola ahora",
openImage: "Abrir imagen adjunta",
removeAttachment: "Quitar adjunto",
removeImage: "Quitar imagen adjunta",
removeFile: "Remove file attachment",
openGithub: "Abrir {{kind}} {{number}}",
@@ -3199,15 +3180,35 @@ export const es: TranslationResources = {
tools: {
instructionsTitle: "Instrucciones",
toolsTitle: "Herramientas de agentes",
pluginNote: "Las herramientas de los plugins también siguen Habilitar herramientas",
updateHostForGroups: "Actualiza este host para configurar grupos de herramientas",
groups: {
orchestration: {
title: "Orquestación",
hint: "Gestiona workspaces, agentes, terminales y scripts",
},
schedules: {
title: "Programaciones",
hint: "Crea y gestiona programaciones y heartbeats",
},
changeRequests: {
title: "Seguimiento de PR",
hint: "Supervisa pull requests y merge requests para ver actualizaciones",
},
browser: {
title: "Navegador",
hint: "Controla las pestañas del navegador de Paseo, incluido el estado con sesión iniciada. Actívalo solo para agentes de confianza.",
},
},
},
orchestration: {
title: "Orquestación",
unavailable: "Conéctese a este host para administrar la orquestación",
enableTools: {
title: "Habilitar herramientasPaseo",
hint: "Los agentes podrán gestionar árboles de trabajo, agentes y horarios.",
accessibilityLabel: "Inyectar herramientasPaseo",
updateFailed: "No se pudieron actualizar las herramientas de Paseo.",
title: "Habilitar herramientas",
hint: "Permite que Paseo y los plugins proporcionen herramientas a los agentes.",
accessibilityLabel: "Habilitar herramientas",
updateFailed: "No se pudieron actualizar las herramientas.",
},
systemPrompt: {
title: "Aviso del sistema",
+26 -25
View File
@@ -175,26 +175,6 @@ export const fr: TranslationResources = {
dictation: "Dictée",
interruptBeforeVoice: "Interrompez l’agent avant de démarrer le mode vocal",
},
queue: {
title: "Messages en attente",
edit: "Modifier le message en attente",
sendNow: "Envoyer maintenant le message en attente",
cancel: "Annuler le message en attente",
paused: "File en pause jusqu'à l'envoi d'un message",
sentBy: "Envoyé par {{title}}",
agentFinished: "{{title}} a terminé",
agentErrored: "{{title}} a échoué",
agentNeedsPermission: "{{title}} demande une autorisation",
agentClosed: "{{title}} s'est fermé",
changeRequestUpdate: "Mise à jour de PR",
changeRequestUpdate_mr: "Mise à jour de MR",
switchesTo: "Passe à {{provider}}",
attachmentCount_one: "{{count}} pièce jointe",
attachmentCount_other: "{{count}} pièces jointes",
alreadySending: "Le message est déjà en cours d'envoi",
loadFailed: "Impossible de charger la file",
retry: "Réessayer",
},
attachments: {
addImage: "Ajouter une image",
pasteImage: "Coller une image",
@@ -203,8 +183,9 @@ export const fr: TranslationResources = {
addIssueOrPr_mr: "Ajouter un ticket ou une MR",
dropImagesHere: "Déposez des images ici",
dropFilesHere: "Déposez des fichiers ici",
editQueuedMessage: "Modifier le message en file d’attente",
sendQueuedMessageNow: "Envoyer maintenant le message en file d’attente",
openImage: "Ouvrir l’image jointe",
removeAttachment: "Supprimer la pièce jointe",
removeImage: "Retirer l’image jointe",
removeFile: "Retirer le fichier joint",
openGithub: "Ouvrir {{kind}} {{number}}",
@@ -3201,15 +3182,35 @@ export const fr: TranslationResources = {
tools: {
instructionsTitle: "Instructions",
toolsTitle: "Outils des agents",
pluginNote: "Les outils ajoutés par les plugins suivent aussi Activer les outils",
updateHostForGroups: "Mettez à jour cet hôte pour configurer chaque groupe d'outils",
groups: {
orchestration: {
title: "Orchestration",
hint: "Gérer les workspaces, les agents, les terminaux et les scripts",
},
schedules: {
title: "Planifications",
hint: "Créer et gérer des planifications et des heartbeats",
},
changeRequests: {
title: "Suivi des PR",
hint: "Surveiller les pull requests et merge requests",
},
browser: {
title: "Navigateur",
hint: "Contrôler les onglets du navigateur Paseo, y compris les sessions connectées. Activez uniquement pour des agents de confiance.",
},
},
},
orchestration: {
title: "Orchestration",
unavailable: "Connectez-vous à cet hôte pour gérer l’orchestration",
enableTools: {
title: "Activer les outils Paseo",
hint: "Les agents pourront gérer les worktrees, les agents et les planifications",
accessibilityLabel: "Injecter les outils Paseo",
updateFailed: "Impossible de mettre à jour les outils Paseo.",
title: "Activer les outils",
hint: "Autorise Paseo et les plugins à fournir des outils aux agents.",
accessibilityLabel: "Activer les outils",
updateFailed: "Impossible de mettre à jour les outils.",
},
systemPrompt: {
title: "Prompt système",
+26 -25
View File
@@ -174,26 +174,6 @@ export const ja: TranslationResources = {
dictation: "音声入力",
interruptBeforeVoice: "音声モードを開始する前にエージェントを中断してください",
},
queue: {
title: "キュー内のメッセージ",
edit: "キュー内のメッセージを編集",
sendNow: "キュー内のメッセージを今すぐ送信",
cancel: "キュー内のメッセージを取り消す",
paused: "メッセージを送信するまでキューは一時停止します",
sentBy: "{{title}} から送信",
agentFinished: "{{title}} が完了",
agentErrored: "{{title}} でエラー",
agentNeedsPermission: "{{title}} に許可が必要",
agentClosed: "{{title}} が終了",
changeRequestUpdate: "PR の更新",
changeRequestUpdate_mr: "MR の更新",
switchesTo: "{{provider}} に切り替え",
attachmentCount_one: "添付 {{count}} 件",
attachmentCount_other: "添付 {{count}} 件",
alreadySending: "メッセージはすでに送信中です",
loadFailed: "キューを読み込めませんでした",
retry: "再試行",
},
attachments: {
addImage: "画像を追加",
pasteImage: "画像を貼り付け",
@@ -202,8 +182,9 @@ export const ja: TranslationResources = {
addIssueOrPr_mr: "イシューまたはMRを追加",
dropImagesHere: "ここに画像をドロップ",
dropFilesHere: "ここにファイルをドロップ",
editQueuedMessage: "キューに入れたメッセージを編集",
sendQueuedMessageNow: "キューに入れたメッセージを今すぐ送信",
openImage: "画像添付ファイルを開く",
removeAttachment: "添付を削除",
removeImage: "画像添付ファイルを削除",
removeFile: "ファイル添付ファイルを削除",
openGithub: "{{kind}} {{number}}を開く",
@@ -3161,15 +3142,35 @@ export const ja: TranslationResources = {
tools: {
instructionsTitle: "指示",
toolsTitle: "エージェントツール",
pluginNote: "プラグインが追加するツールもこのスイッチに従います",
updateHostForGroups: "ツールグループを個別に設定するにはホストを更新してください",
groups: {
orchestration: {
title: "オーケストレーション",
hint: "ワークスペース、エージェント、ターミナル、スクリプトを管理します",
},
schedules: {
title: "スケジュール",
hint: "スケジュールとハートビートを作成・管理します",
},
changeRequests: {
title: "PRの監視",
hint: "プルリクエストやマージリクエストの更新を監視します",
},
browser: {
title: "ブラウザ",
hint: "ログイン状態を含む Paseo のブラウザタブを操作します。信頼できるエージェントにのみ有効にしてください。",
},
},
},
orchestration: {
title: "オーケストレーション",
unavailable: "オーケストレーションを管理するにはこのホストに接続してください",
enableTools: {
title: "Paseoツールを有効にする",
hint: "エージェントがワークツリー、エージェント、スケジュールを管理できるようになります",
accessibilityLabel: "Paseoツールを有効にする",
updateFailed: "Paseoツールを更新できませんでした。",
title: "ツールを有効にする",
hint: "Paseo とプラグインからエージェントへツールを提供します。",
accessibilityLabel: "ツールを有効にする",
updateFailed: "ツールを更新できませんでした。",
},
systemPrompt: {
title: "システムプロンプト",

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