Compare commits

..
Author SHA1 Message Date
Mohamed Boudra 6c744f903d fix(server): clear dirty flag before reading in memory collection backend
Clear partition.dirty before awaiting options.read() (restoring it on error)
and loop in read() while dirty so a mutation arriving during an unsubscribed
read cannot leave the cached partition stale.

Also add a real-browser Playwright test in composer-queue.spec.ts verifying
that switching away from a retained agent tab and returning catches up on
queue changes made while hidden.
2026-11-30 16:59:24 +01:00
Mohamed Boudra fe99a08b9d refactor(protocol,server,client,app): replace synced-resource with storage-agnostic sync library
Replace the whole-snapshot synced-resource layer with a storage-agnostic
cursor-sync protocol and library across protocol, server, client, and app:

- protocol (src/sync/): zero-Zod descriptors (defineSyncStream,
  defineSyncCollection, AgentQueueCollection) and pure zod-aot schemas with
  nested args, { epoch, afterSeq } cursors, mode: snapshot | changes deltas,
  tail/after/before paging, and per-subscription prevSeq on updates.
- server (server/sync/): SyncBackend interface for in-memory or durable
  backends, handleSyncRequest (authorize, attach-before-read, live buffering,
  per-session projectResponse/projectLive, prevSeq stamping), shared
  VersionedCollection (reused by directory-sync), and bounded-LRU lazy-diff
  createMemoryCollectionBackend. Rewire agent.queue onto agent.queue.sync.*.
- client (src/sync/): SyncedStoreRegistry with single subscribe()->unsub API
  (no .release()), ref-counting, real delta merging, gap/epoch catch-up loops,
  backward loadOlder() paging, exponential backoff with reconnect recovery,
  and pluggable SyncPersistence.
- app (src/sync/): thin useSync / useSyncCollection hooks gated on
  useRetainedPanelActive() and host features; slim agent-queue to queue
  commands and busy guards.
- End-to-end proofs covering production agent.queue, a chat timeline over
  both memory and durable node:sqlite (restart epoch survival, paging, chunks,
  rewinds, gap recovery, cold-start persistence), and a filtered agent
  directory (normalized keys, tombstones, per-session filtering without false
  gaps, LRU eviction, backoff).
2026-11-30 16:48:12 +01:00
Mohamed Boudra 1999c5bddb fix(protocol,client): keep synced resource descriptors free of zod
Split the zero-Zod SyncedResourceDescriptor and AgentQueueResource descriptor
out of @getpaseo/protocol/messages so @getpaseo/client and thin CLI commands
do not pull messages.ts or zod into the static startup graph.
2026-11-30 14:43:04 +01:00
Mohamed Boudra 05af294572 refactor(protocol,server,client,app): add cursor-synced resource primitive for agent queue
Replace the daemon-wide agent.queue.update event subscription and separate
list fetch with a shared cursor-synced resource primitive:

- protocol: defineSyncedResource({ prefix, scope, value }) generates list
  request/response/update schemas with optional subscribe and generation/seq
  sync cursors; remove agent.queue.update from SessionEventSubscriptionSchema.
- server: daemon-scoped SyncedResourceSource + handleSyncedResourceListRequest
  track per-scope monotonic seq, answer matching cursors with mode: unchanged
  without reading, and emit scoped updates only to active subscribers.
- client: SyncedResourceRegistry ref-counts one server subscription per
  (prefix, scopeKey), retains cursors in a bounded LRU cache on release, and
  resumes with afterSeq on reconnect or re-focus.
- app: synced-resource model and useSyncedResource hook gate subscriptions on
  panel visibility and host features; agent-queue composes on top for withdraw,
  promote, and per-row busy guards.
2026-11-30 14:23:54 +01:00
Mohamed Boudra 91fd0a7685 fix(app): cap composer input independently of dock queue track
ComposerViewportContent previously applied the 0.6x inline editing cap to the entire composer slot, including ComposerQueueTrack. On compact phones after keyboard open/close, restoring an attachment pill grew MessageInput enough to collapse the queued message list to ~10px.

Bound the outer dock slot to the full viewport capacity, move the 0.6x inline cap onto ComposerInputCap around the input box, and cap compact queue rows at 140dp so ~2 queued rows stay usable alongside a restored image pill.
2026-11-30 12:49:40 +01:00
Mohamed Boudra 45be9ebe6c fix(app): steer instead of interrupting on a host without a message queue
A "queue" send behavior fell back to "interrupt" on an older host, which
killed the running turn the user meant to wait for.
2026-11-30 11:53:40 +01:00
Mohamed Boudra e771e671f9 feat(app): queue a staged provider switch with its message
A prompt sent mid-turn with a staged switch goes to the host's queue with
the switch. Its row names the target provider, and Edit stages the switch
again.

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

Refs #8436, #9023
2026-11-30 11:53:40 +01:00
Mohamed Boudra 1f07c32cf9 test(server): cover a queued message the timeline already holds after a crash 2026-11-30 11:53:39 +01:00
Mohamed Boudra 071ea27448 feat(protocol,server,client): queue a provider switch behind a running turn
A switch staged mid-turn relied on the app holding the prompt until the
turn ended. The host owns the queue now, so the queued message carries the
target provider and settings and the host switches when its turn comes.

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

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

Refs #8436, #9023
2026-11-30 11:53:39 +01:00
Mohamed Boudra 33e0a862d8 fix(server): set aside a corrupt agent queue file instead of failing startup
One unreadable file under agent-queues/ stopped the daemon from booting.
It is renamed so it can be inspected, a warning is logged, and every other
queue loads.
2026-11-30 11:53:39 +01:00
Mohamed Boudra c3ea1a90c0 fix(app): keep the composer on screen with a long message queue
The queue list had no height limit and could not shrink, so enough rows
pushed the message input and Stop past the bottom of the window with no way
to scroll back. The rows now scroll in a capped frame that gives up height
before the input does. The frame is a View because the web build drops
Unistyles styles on the shared ScrollView.

Also keeps row icons from being squashed by a long sender name, puts row
text on the composer's text rail, and focuses the input after Edit.
2026-11-30 11:05:42 +01:00
Mohamed Boudra 6c05edbc5d feat(app): show the host's message queue above the composer
The app kept its own queue and sent it when it saw the agent stop. A
reload lost the queued messages, nothing was sent with the app closed,
and other clients and agent senders could not be seen. The host now owns
the queue; the app only lists it and asks the host to withdraw or send a
row.

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

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

Refs #8436, #9023
2026-11-30 11:05:42 +01:00
Mohamed Boudra 5bb8e4f77b feat(protocol,server,client): add agent message queue RPCs and client sync
Expose the daemon's durable per-agent message queue over the session protocol so clients can hydrate, observe live updates, withdraw, and promote queued messages without maintaining a local queue.

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

Refs #8436, #9023
2026-11-30 11:02:36 +01:00
Mohamed Boudra 63d3fc3df3 feat(server): keep queued agent messages across daemon restarts
Queued messages lived in memory. A crash lost them, a restored finish
subscription then reported a child that never ran its task, and a clean
shutdown forced a flush into busy agents and swallowed the failures.

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

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

Refs #8436
2026-11-30 11:02:31 +01:00
Mohamed Boudra 89826f0961 feat(server): add durable agent message queue store
Define the AgentMessageQueueStore interface along with atomic per-agent JSON and in-memory adapters and shared contract tests.

This is the persistence foundation for unifying human and agent message queues behind a SQLite-ready store boundary. Withdraw and promote return atomic discriminated outcomes inside the per-recipient lock so callers avoid racy pre-reads against active dispatches.
2026-11-30 11:00:20 +01:00
401 changed files with 21422 additions and 15895 deletions
+1 -1
View File
@@ -45,6 +45,7 @@ At the start of non-trivial work, list `docs/` and skim anything relevant to the
| [docs/custom-providers.md](docs/custom-providers.md) | Custom provider config: Z.AI, Alibaba/Qwen, ACP agents, profiles, custom binaries | | [docs/custom-providers.md](docs/custom-providers.md) | Custom provider config: Z.AI, Alibaba/Qwen, ACP agents, profiles, custom binaries |
| [docs/plugins.md](docs/plugins.md) | Local plugin manifest, directory source config, RPCs, native surfaces, and attachment sources | | [docs/plugins.md](docs/plugins.md) | Local plugin manifest, directory source config, RPCs, native surfaces, and attachment sources |
| [docs/website-i18n.md](docs/website-i18n.md) | Website languages: locale URLs, translated Markdown pairs, `{#id}` anchors, Chinese style | | [docs/website-i18n.md](docs/website-i18n.md) | Website languages: locale URLs, translated Markdown pairs, `{#id}` anchors, Chinese style |
| [docs/service-proxy.md](docs/service-proxy.md) | Service proxy: exposing workspace scripts at public URLs, DNS setup, reverse proxy config |
| [docs/relay-endpoint-security.md](docs/relay-endpoint-security.md) | Relay E2EE modes: Noise NK mapping, record framing, negotiation, the `requireProtectedSecurity` flag, close codes | | [docs/relay-endpoint-security.md](docs/relay-endpoint-security.md) | Relay E2EE modes: Noise NK mapping, record framing, negotiation, the `requireProtectedSecurity` flag, close codes |
| [docs/development.md](docs/development.md) | Dev server, build sync gotchas, CLI reference, agent state, Playwright MCP | | [docs/development.md](docs/development.md) | Dev server, build sync gotchas, CLI reference, agent state, Playwright MCP |
| [docs/rpc-namespacing.md](docs/rpc-namespacing.md) | WebSocket RPC naming convention — dotted namespaces and `.request`/`.response` pairs | | [docs/rpc-namespacing.md](docs/rpc-namespacing.md) | WebSocket RPC naming convention — dotted namespaces and `.request`/`.response` pairs |
@@ -57,7 +58,6 @@ 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/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-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/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/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/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 | | [docs/file-observation.md](docs/file-observation.md) | Recursive watcher ownership, Linux constraints, teardown invariants, and Parcel comparison |
+79 -13
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. `notifyOnFinish` defaults to `true` for agent-scoped creation and prompt follow-ups because most delegated work needs to report back to the creating agent. Set it to `false` for explicit reporting or no completion callback.
Agent-originated messages and automatic notifications share a recipient-daemon delivery module. A queued receipt acknowledges admission before provider dispatch. The module keeps one ordered queue per recipient, and the recipient reads its prompts in the order the daemon admitted them. Nothing overtakes an older queued message. A prompt takes its place when the daemon admits it, even while the provider is still starting an earlier turn, and a message stays in the queue until the turn that carries it starts. The turn has started when the agent manager acknowledges the run start; a turn that fails after that point is not delivered again. Agent-originated messages and automatic notifications share a recipient-daemon delivery module. The daemon saves a queued message, then acknowledges it with a receipt, before provider dispatch. The module keeps one ordered queue per recipient, and the recipient reads its prompts in the order the daemon admitted them. Nothing overtakes an older queued message. A prompt takes its place when the daemon admits it, even while the provider is still starting an earlier turn, and a message stays in the queue until the turn that carries it starts. The turn has started when the agent manager acknowledges the run start; a turn that fails after that point is not delivered again.
Any sender picks `queue`, `steer`, or `interrupt` with `activeTurnBehavior`. Agent senders default to `queue`; non-agent senders (app, CLI, plugins, Hub, top-level MCP) default to `interrupt`. Each kind of prompt is released this way: Any sender picks `queue`, `steer`, or `interrupt` with `activeTurnBehavior`. Agent senders default to `queue`; non-agent senders (app, CLI, plugins, Hub, top-level MCP) default to `interrupt`. Each kind of prompt is released this way:
@@ -170,33 +170,64 @@ A command the provider accepts out of band is the one exception to admission ord
One provider prompt has one session mode. A batch released by a steer, an interrupt, or a person's prompt uses the latest explicit choice in it, the person's own first. Queued messages with conflicting choices keep separate ordered dispatches. One provider prompt has one session mode. A batch released by a steer, an interrupt, or a person's prompt uses the latest explicit choice in it, the person's own first. Queued messages with conflicting choices keep separate ordered dispatches.
The pending message window is in memory. Clean shutdown flushes it, held messages included, before A provider switch can wait in the queue too (`agent.provider.switch.request` with
closing agents; an abrupt crash can lose queued prompts. A durable send receipt remains pending until actual dispatch `activeTurnBehavior: "queue"`). The message carries the target provider and settings, shares a prompt
acknowledgment, so a lost window never becomes a completed receipt. Completion waits cover queued with nothing, and divides the queue: what is ahead of it goes to the current provider, and it and
admission within their original timeout and cancellation scope, and return at permission what follows go to the target. A direct prompt therefore takes along only the queued rows ahead of
checkpoints and when a Stop holds the queue. the switch. Promoting the switch cuts the running turn once the target is known to be usable. A chat
already on the target takes the message and its settings as a plain prompt. A switch that fails keeps
the message and holds the queue; the reason is in the daemon log.
The queue is saved in `$PASEO_HOME/agent-queues/` ([data model](data-model.md#directory-layout)),
and a message is saved before its receipt is sent. Inline images are first saved as uploads, so the
queue file holds references. An empty message is refused, and a recipient holds at most 100
messages.
A message is marked `dispatching` before the provider can receive it and removed when the provider
admits it. A dispatch that is not admitted returns the message to its place. A refused turn start
also holds the queue: retrying by itself would be refused again and would add the prompt to the
history each time. A message that cannot be sent is removed so that it does not block the ones
behind it.
Shutdown does not send the queue. It waits only for dispatches already in flight, and everything
else stays saved, held messages included. Closing an idle runtime keeps the queue. Archiving or
deleting the agent clears it.
Bootstrap restores queues before restart recovery resumes agents, and before finish subscriptions,
change-request watches, and ingress start. A held queue stays held. Other queues are sent, after the
resume prompt for an agent that restart recovery resumes. A crash can leave a message marked
`dispatching`, so the daemon looks for it in the recipient's history: a message found there is
removed, and one not found, or whose history cannot be read, is sent again.
A client that retries a queued message with the same `messageId` is acknowledged again at once. The
completed send receipt is written after dispatch, and a different request under that `messageId`
conflicts. Completion waits cover queued admission within their original timeout and cancellation
scope, and return at permission checkpoints and when the queue is held.
Finish notification intent has a separate daemon-owned lifetime. The finish-subscriptions module 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 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 `$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 acknowledgment promises a notification. A pending replacement retains its predecessor until dispatch
accepts; rejected dispatch removes only the candidate. Recovery coalesces registrations for the same accepts; rejected dispatch removes only the candidate. The record keeps the prompt's `messageId`, so
caller, child, and host into one watch. withdrawing that message removes the subscription, also after a restart. Recovery coalesces
registrations for the same caller, child, and host into one watch.
Bootstrap restores these watches after repairing stale running records to `closed` and before opening 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 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 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 recovery is observed only after its resume was sent, so the parent never hears that it was closed
in between. Archived or deleted parents suppress delivery; in between. A subscription whose prompt is still queued stays pending until that prompt is
dispatched, so a held follow-up reports nothing. Archived or deleted parents suppress delivery;
parent-owned creation watches also stop parent-owned creation watches also stop
reporting after detachment. reporting after detachment.
Intent remains stored until the parent's notification dispatch is acknowledged. Dispatch failure 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 retries the captured notification; it does not change the child's reported outcome. Remote host loss
follows the [connected-host observation policy](connected-hosts.md#delegating-agents). Shutdown stops observation before flushing message delivery, retaining follows the [connected-host observation policy](connected-hosts.md#delegating-agents). Shutdown stops
outstanding intent. A crash after successful dispatch but before removal commits can repeat the observation and retains outstanding intent. A final or permission notice has an id derived from its
notification. Clean shutdown can also flush an already queued callback while retaining its intent, subscription, so observing the same outcome again while the notice is queued adds nothing. A crash
so that callback can repeat after restart. This is an at-least-once wakeup, without turn attribution or exactly-once delivery. after successful dispatch but before removal commits can repeat the notification. This is an
at-least-once wakeup, without turn attribution or exactly-once delivery.
A turn end is not always a settled child. A child can end its turn with work that will start its next 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 turn by itself: a running turn, queued messages, a pending provider wake-up
@@ -397,6 +428,41 @@ that leaves the lifecycle at `error`, and replaces unread `finished` attention;
agent would show the green dot or none. Subagents track marks are the exception: they follow the 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. 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 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`. 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,6 +60,9 @@ $PASEO_HOME/
│ └── {agentId}.json # One file per agent │ └── {agentId}.json # One file per agent
├── schedules/ ├── schedules/
│ └── {scheduleId}.json # One file per schedule │ └── {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/
│ ├── projects.json # Project registry │ ├── projects.json # Project registry
│ ├── workspaces.json # Workspace registry │ ├── workspaces.json # Workspace registry
@@ -249,8 +252,7 @@ snapshot so a mixed edit can apply its live subset and still name the paths that
listen: "127.0.0.1:6767", listen: "127.0.0.1:6767",
hostnames: true | string[], // legacy alias `allowedHosts` is migrated on load hostnames: true | string[], // legacy alias `allowedHosts` is migrated on load
trustedProxies: true | string[], // defaults to ["loopback"]; Express proxy names/CIDRs trustedProxies: true | string[], // defaults to ["loopback"]; Express proxy names/CIDRs
tools: { enabled: boolean, groups: { orchestration, schedules, changeRequests, browser: boolean } }, mcp: { enabled: boolean, injectIntoAgents: boolean },
mcp: { enabled: boolean, injectIntoAgents: boolean }, // legacy, read only when `tools` is absent
git: { maxProcessesPerSecond: number, maxProcessConcurrency: number }, git: { maxProcessesPerSecond: number, maxProcessConcurrency: number },
appendSystemPrompt: string, // appended to supported provider system/developer prompts appendSystemPrompt: string, // appended to supported provider system/developer prompts
terminalProfiles: TerminalProfile[], // named shell commands; omitted means DEFAULT_TERMINAL_PROFILES terminalProfiles: TerminalProfile[], // named shell commands; omitted means DEFAULT_TERMINAL_PROFILES
@@ -352,14 +354,12 @@ Each entry may include a Paseo-tool policy:
Absent `paseoTools`, or absent fields within it, means Paseo tools are enabled and all tools are 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 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. IDs to omit. The policy covers the core and browser catalog, not the voice-only `speak` tool.
Browser tools also require `daemon.tools.groups.browser` and a connected browser host. Browser tools also require `daemon.browserTools.enabled` and a connected browser host.
This policy controls the catalog presented to an agent. It is not an authorization boundary for 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. agents that can access the host through a shell.
`daemon.tools` is the global override. When `enabled` is `false`, no provider receives Paseo or `daemon.mcp.injectIntoAgents` is the global override. When it is `false`, no provider receives
plugin tools; otherwise each group in `daemon.tools.groups` and then the provider policy applies. Paseo tools; otherwise the provider policy applies. Provider and global policy are resolved when a
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 is created, resumed, imported, or reloaded, so configuration changes affect the next
session rather than an already-running one. session rather than an already-running one.
+10 -8
View File
@@ -440,13 +440,15 @@ that reads what it needs from `process.env` and invoke it as
Every `scripts` entry with `"type": "service"` receives these environment variables: Every `scripts` entry with `"type": "service"` receives these environment variables:
| Variable | Value | | Variable | Value |
| --------------------------- | ---------------------------------------------------------------- | | --------------------------- | ------------------------------------------------------------------------------------------------------------------------- |
| `PASEO_SERVICE_<NAME>_URL` | Local `http://localhost:<port>` URL for a declared peer service. | | `PASEO_SERVICE_<NAME>_URL` | Proxied URL for a declared peer service. Prefer this for peer discovery; it survives peer restarts. |
| `PASEO_SERVICE_<NAME>_PORT` | Allocated port for a declared peer service. | | `PASEO_SERVICE_<NAME>_PORT` | Raw ephemeral port for a declared peer service. Use only as a bypass escape hatch; it can go stale if that peer restarts. |
| `PASEO_URL` | Self alias for `PASEO_SERVICE_<SELF>_URL`. | | `PASEO_URL` | Self alias for `PASEO_SERVICE_<SELF>_URL`. |
| `PASEO_PORT` | Self alias for `PASEO_SERVICE_<SELF>_PORT`. | | `PASEO_PORT` | Self alias for `PASEO_SERVICE_<SELF>_PORT`. |
| `HOST` | Bind host for the service process. | | `HOST` | Bind host for the service process. |
Service proxy hostnames use the double-dash shape: `web--feature-auth--project.localhost` or, on the default branch, `web--project.localhost`. Optional public aliases use the same leftmost label under the configured public base host.
`<NAME>` is normalized from the script name by uppercasing it, replacing each run of non-`A-Z0-9` characters with `_`, and trimming leading or trailing `_`. For example, `app-server` and `app.server` both normalize to `APP_SERVER`; that collision fails at spawn time with an actionable error. `<NAME>` is normalized from the script name by uppercasing it, replacing each run of non-`A-Z0-9` characters with `_`, and trimming leading or trailing `_`. For example, `app-server` and `app.server` both normalize to `APP_SERVER`; that collision fails at spawn time with an actionable error.
@@ -503,7 +505,7 @@ Or persist it in `config.json`:
} }
``` ```
When enabled, opening the daemon HTTP origin (for example `http://localhost:6767/`) serves the web app. The same HTTP server continues to serve `/api/*`, `/mcp/*`, `/public/*`, and the WebSocket upgrade. Static files load without daemon bearer auth; API and WebSocket calls still enforce auth. When enabled, opening the daemon HTTP origin (for example `http://localhost:6767/`) serves the web app. The same HTTP server continues to serve `/api/*`, `/mcp/*`, `/public/*`, the WebSocket upgrade, and service-proxy routes. Static files load without daemon bearer auth; API and WebSocket calls still enforce auth.
The served app auto-bootstraps a connection to the same origin, so opening `http://localhost:6767/` directly usually skips the Add Host step. The served app auto-bootstraps a connection to the same origin, so opening `http://localhost:6767/` directly usually skips the Add Host step.
+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". - **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". - **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 footer** — Optional area rendered below the composer input but still inside the keyboard-shifted composer layout. Code: `Composer.footer` (`packages/app/src/composer/index.tsx`).
- **Composer track** — A contextual lane at the foot of a pane, by the composer input. Specific tracks use the `<thing> track` form: **Queue track**, **Subagents track**, **Tasks track**. The subagents and tasks tracks are pills floating over the transcript, each opening a panel with its rows; the queue track is a lane inside the composer itself. Code: queue track inside `Composer` (`packages/app/src/composer/index.tsx`), pill and panel frame in `packages/app/src/composer/tracks.tsx`, `SubagentsTrack` (`packages/app/src/subagents/track.tsx`), `AgentTaskList` (`packages/app/src/composer/task-list/index.tsx`). - **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 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". - **Steer** — A follow-up admitted into an agent's already-running turn instead of interrupting it. Interrupting the turn discards steers the provider has not read yet; there is no take-back short of that, and no provider offers one. The stop button and Escape both interrupt. A steer the provider never read keeps its transcript row, matching Codex. Sending while the agent waits on a permission denies that request first, so the message reaches the same turn instead of stalling behind it. UI: "Send and steer". Code: `steerActiveTurn` (`packages/server/src/server/agent/agent-sdk-types.ts`). Don't confuse with **Queue track**, which lists the messages the host holds until the turn ends. A queued message does not enter the running turn. An agent sender's `activeTurnBehavior: "steer"` (CLI `--behavior steer`) means the same as a person's steer. Agent senders default to `queue` instead: the daemon holds the message until the running turn ends, as it does for a person's queued message. Forbidden: "Delivery", "Queued prompt".
- **Subagent** — User-facing term for an agent session related to a parent agent session. Use **subagents** in UI copy and docs. Internal daemon/provider plumbing may say "child agent" or `child_session`, especially for provider-managed imports; do not surface "child agent" as a product term. - **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". - **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). - **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).
-8
View File
@@ -32,11 +32,6 @@ text controls do not type them. Android takes no claims: a focused `EditText`
types nothing for these combos. Keep the stream as the sole shortcut emitter: a command-owned types nothing for these combos. Keep the stream as the sole shortcut emitter: a command-owned
press is still observed by the window. press is still observed by the window.
Register composer Return on every iOS device. Only a physical key press runs a
`UIKeyCommand`, so the on-screen keyboard's Return still inserts a newline. Do not
gate it on the interface idiom, which excludes iPhones with a keyboard attached, or
on `GCKeyboard`, which the command does not need.
The source spike used an iPad Pro 11-inch (M4) simulator on iOS 18.6 with a The source spike used an iPad Pro 11-inch (M4) simulator on iOS 18.6 with a
`UITextView` first responder. Both `UIWindow.sendEvent` and the root controller's `UITextView` first responder. Both `UIWindow.sendEvent` and the root controller's
`pressesBegan` received Cmd+B, Cmd+P and Escape. With Escape registered as a `pressesBegan` received Cmd+B, Cmd+P and Escape. With Escape registered as a
@@ -53,9 +48,6 @@ through rebinds. For numeric injection, use AppleScript physical key codes (for
25 for 9); `keystroke "9"` did not deliver a digit in the QA session. 25 for 9); `keystroke "9"` did not deliver a digit in the QA session.
Simulator exposes a virtual `GCKeyboard` even with Connect Hardware Keyboard off. Simulator exposes a virtual `GCKeyboard` even with Connect Hardware Keyboard off.
Verify the iOS absence case on a physical iPhone. Verify the iOS absence case on a physical iPhone.
Xcode 27.2 has Device Hub in place of Simulator. AppleScript keystrokes reach the
device only while its view has Mac focus. Give it focus with a real mouse click
(a `CGEvent`); keystrokes sent elsewhere drive Device Hub's own controls.
Never register Backspace: it would take deletion away from text fields. Changes Never register Backspace: it would take deletion away from text fields. Changes
to the native module require a native rebuild; an over-the-air JavaScript update to the native module require a native rebuild; an over-the-air JavaScript update
+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. - 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. - `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`, `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. - `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`.
- 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. - 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. - `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 ## 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. `<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. 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.
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. 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.
-10
View File
@@ -72,11 +72,6 @@ matches:
</MenuSurface> </MenuSurface>
``` ```
A row that cannot be drawn as a `MenuItem`, such as the compact Tunnel sub-row in the Scripts
menu, takes the same anchor, hover intent and navigation from `useMenuSubTrigger` and draws its
own look. Put the anchor on a `View` that spans the surface. A narrower anchor adds its inset to
the flyout's overlap.
Pages are data rather than nested children because the popover renders them as _siblings_ of the Pages are data rather than nested children because the popover renders them as _siblings_ of the
root surface — a flyout nested inside the root's box would be clipped by its `overflow: hidden`. root surface — a flyout nested inside the root's box would be clipped by its `overflow: hidden`.
Declaring them separately is what lets one model drive both presentations. Declaring them separately is what lets one model drive both presentations.
@@ -132,11 +127,6 @@ of backdrop between the two that belongs to neither surface, and every pixel of
dismiss the menu you are reaching for. Overlapping deletes the strip; don't reintroduce the gap dismiss the menu you are reaching for. Overlapping deletes the strip; don't reintroduce the gap
and try to cover it with a longer timer. and try to cover it with a longer timer.
A flyout opens on the right of its row. If the right side has no room and the left has more, it
opens on the left, so a menu at the right edge of the window is not covered by its own flyout. It
chooses its side once, when it is first placed. Content that arrives later does not move it out
from under the pointer.
On top of that, a flyout opens after the pointer rests ~90ms, closes ~260ms after it leaves, and On top of that, a flyout opens after the pointer rests ~90ms, closes ~260ms after it leaves, and
cancels its own pending close while the pointer is inside it. The grace still matters because the cancels its own pending close while the pointer is inside it. The grace still matters because the
pointer crosses sibling rows on the way down into the flyout. pointer crosses sibling rows on the way down into the flyout.
@@ -1,89 +0,0 @@
# 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.

Before

Width:  |  Height:  |  Size: 128 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 57 KiB

@@ -1,18 +0,0 @@
{
"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"
}
}
-114
View File
@@ -1,114 +0,0 @@
# 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.
## Frames
Keeping the animation off the React thread does not make it free. Every time an indicator moves,
the platform composes and presents the whole window again: `RenderThread` on Android, the GPU
process and macOS's WindowServer on desktop. An indicator that moves with the display holds the
window at 60 or 120 frames a second for as long as an agent runs, with nothing else changing.
So an indicator moves in steps, and the step count is its frame rate:
| Indicator | Positions | Frames a second |
| ----------------- | ----------------------------------- | --------------- |
| Loader | 6 per 950 ms | 6 |
| Status ring | 27 per 900 ms (`STATUS_RING_STEPS`) | 30 |
| Tool-call shimmer | every display frame | 60 or 120 |
The ring is the one that matters most: it is on screen in the sidebar and the tab bar whenever any
agent runs, including while you read an idle chat. Its steps are positions the smooth turn passes
through, 1.2 px apart on a 12 px ring. Fewer steps start to read as ticking and buy little: measured
on an Android emulator with one ring on screen, the app used 12–15% of a core with a smooth ring,
8–10% with 27 steps, and 6–7% with either 18 or 12, because the native driver's own tick is what is
left.
Two indicators only share frames when their steps turn over at the same instants. The shimmer still
moves every frame, so a chat with a running tool call in view draws at the display's rate.
## 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 its easing on the keyframes:
`step-end` to hold each keyframe until the next, `steps(n)` to cross between two keyframes in `n`
even steps. The compositor then draws a frame when a step changes and none in between.
## Native
Reanimated commits a cloned shadow tree on the UI thread for every frame a shared value changes.
For a transition that is fine. For an indicator that runs for an hour it was 22–28% of a core on
the UI thread of an Android emulator.
React Native's own `Animated` with `useNativeDriver: true` updates the view from the native driver
and commits nothing. `clock.ts` builds a clock out of it: a 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.
`cycle(periodMs, steps)` holds the position at each step. The driver still ticks every frame, but a
view whose transform did not change is not invalidated, so nothing is drawn between steps.
The 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 and the ring's cadence, the frames a ring draws beside an
idle chat, reduced motion, and a hidden tab. Run it with
`PASEO_RUNNING_INDICATORS_FRAMES=1` to also save reference frames of every indicator at fixed
points of its cycle, for a pixel comparison across a change.
To hold a turn in the running state without streaming, send the mock load-test agent
`Hold a running shell tool call for <N>ms`.
On Android, compare `adb shell dumpsys gfxinfo <package>` frame counts and per-thread CPU from
`/proc/<pid>/task/*/stat` over a fixed window. A regression in how an indicator is driven shows up
on the UI thread (`sh.paseo.debug`); one in how often it moves shows up as frames rendered and on
`RenderThread`. `dumpsys gfxinfo <package> framestats` lists each frame's vsync, which shows whether
the steps are evenly spaced. On the emulator gfxinfo counts every frame that follows an idle vsync
as janky; read the frame count and the percentiles instead.
+141
View File
@@ -0,0 +1,141 @@
# Service Proxy
Paseo proxies HTTP traffic to services running inside your workspaces. Localhost service URLs are always enabled; optional public aliases and a separate service-only listener can be layered on through config.
## How it works
When a `paseo.json` script of `"type": "service"` starts, Paseo assigns it a local port and registers a route in the service proxy. Incoming requests whose `Host` header matches the script's generated hostname are forwarded to that port. HTTP requests, WebSocket upgrades, and service health checks select the reachable IPv4 or IPv6 loopback address. Services can bind to `127.0.0.1` or `::1` without changing their proxy URL.
The generated hostname is built from the script name, branch, and project:
```
<script>--<branch>--<project>.localhost
```
If the branch is `main` or `master`, the branch segment is omitted:
```
<script>--<project>.localhost
```
**Example:** a script named `dev` in the `miniweb` project on branch `feature/auth` would be reachable at:
```
dev--feature-auth--miniweb.localhost
```
Local and public routes use one combined leftmost label (`script--branch--project`). This keeps the hostname compatible with normal single-level wildcard DNS and TLS. If the combined label would exceed DNS's 63-character label limit, Paseo truncates it with a deterministic hash suffix to avoid collisions.
## Managing workspace scripts
Configured `paseo.json` scripts can be managed without addressing their backing terminal directly:
```bash
paseo script ls [--cwd <path> | --workspace <workspace-id>]
paseo script start <name> [--cwd <path> | --workspace <workspace-id>]
paseo script stop <name> [--cwd <path> | --workspace <workspace-id>]
```
The commands return the same script metadata shown by the workspace: lifecycle, service port, proxy URLs, health, exit code, and supervised terminal ID. `stop` terminates the managed terminal rather than only removing the proxy route, so normal script lifecycle cleanup remains authoritative. MCP exposes matching `list_workspace_scripts`, `start_workspace_script`, and `stop_workspace_script` tools; those require an explicit workspace ID.
## Configuration
Add a `serviceProxy` block under `daemon` in `~/.paseo/config.json`:
```json
{
"version": 1,
"daemon": {
"serviceProxy": {
"listen": "0.0.0.0:8080",
"publicBaseUrl": "https://paseoapps.my.domain.com"
}
}
}
```
| Field | Required | Description |
| --------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| `listen` | No | Starts a separate service-only listener at this address. If omitted, services are still reachable on the daemon listener via localhost hosts. |
| `publicBaseUrl` | No | Adds public service host aliases and public service links. If omitted, links use localhost addresses only. |
`enabled` is accepted for old configs but no longer enables a mode. `enabled: false` suppresses optional `listen`/`publicBaseUrl` layers only; localhost service proxying remains always enabled.
## DNS and reverse proxy setup
For generated URLs to be reachable, you need wildcard DNS pointing to the machine running the Paseo daemon.
**Example:** to expose services at `https://dev--miniweb.paseoapps.my.domain.com` where the daemon host is `10.1.1.1`:
1. Configure a wildcard DNS record:
```
*.paseoapps.my.domain.com → 10.1.1.1
```
2. Set `publicBaseUrl` to `https://paseoapps.my.domain.com` in your config.
3. If you put a reverse proxy (nginx, Caddy, Traefik, etc.) in front of Paseo, point it at either the daemon listener or the optional service-only listener and ensure it forwards the `Host` header unchanged. The proxy uses the `Host` header to route requests to the correct service — rewriting it will break routing.
Public service URLs expose the workspace service itself. Daemon password authentication protects daemon APIs; it does not protect proxied dev services.
If the same reverse proxy serves the daemon web UI over HTTPS, it must also set `X-Forwarded-Proto` so the web UI can auto-connect with `wss://`. The daemon trusts forwarded headers from loopback proxies by default. If your proxy reaches the daemon from another address, configure the proxy ranges explicitly:
```json
{
"version": 1,
"daemon": {
"trustedProxies": ["loopback", "172.16.0.0/12"]
}
}
```
`PASEO_TRUSTED_PROXIES` accepts the same comma-separated values, for example `loopback,172.16.0.0/12`. Use `true` only when the final trusted proxy overwrites client-supplied `X-Forwarded-*` headers.
Nginx example:
```nginx
server {
listen 443 ssl;
server_name *.paseoapps.my.domain.com;
location / {
proxy_pass http://10.1.1.1:8080;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
```
Nginx's `$host` drops the port. If you terminate on a non-default port, use `$http_host` instead so the port survives — that is what "forwards the `Host` header unchanged" means here.
## Forwarded headers
Paseo sets these when it forwards a request to a workspace service:
| Header | Value |
| ------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| `X-Forwarded-Host` | The `Host` header verbatim, including the port when the client used one |
| `X-Forwarded-Proto` | The request scheme (`http` on the WebSocket upgrade path) |
| `X-Forwarded-For` | The immediate peer address. Replaces any existing chain, so behind your own reverse proxy this is the proxy's address, not the client's |
| `X-Forwarded-Port` | The port from the `Host` header when it has one, otherwise whatever your proxy already set |
`X-Forwarded-Port` follows the same trust rule as `X-Forwarded-Host`: the authority Paseo observed wins. When the `Host` header carries a port, that port is reported and replaces any inbound `X-Forwarded-Port`, so a client cannot forge one. When `Host` carries no port there is nothing to observe, so a value your reverse proxy set survives untouched — that is the case where nginx's `$host` drops the port and `X-Forwarded-Port` is the only source. Paseo never derives the port from the scheme. Any other `X-Forwarded-*` header your proxy sends is passed through untouched.
Services that build absolute URLs should prefer `Host` or `X-Forwarded-Host`.
### The forwarded authority is not authenticated
Route lookup normalizes the port away before matching a service hostname, so a client can address the daemon with any port in `Host` and still reach the service. That port is what lands in `X-Forwarded-Host` and `X-Forwarded-Port`. Paseo also does not check whether an inbound `X-Forwarded-Port` came from a proxy in `trustedProxies` — when `Host` carries no port, a client-supplied value is passed through.
Treat the forwarded authority as client-influenced input. A service that builds password reset links, absolute redirects, or cached URLs from it should pin its own public origin in configuration rather than deriving one from request headers. This is not specific to `X-Forwarded-Port`: the `Host` header has always carried a client-chosen port.
## Environment variables
The listen address and public base URL can also be set via environment variables, which take precedence over `config.json`:
| Variable | Description |
| ------------------------------------- | ------------------------------------------------------------------------- |
| `PASEO_SERVICE_PROXY_ENABLED` | Compatibility shim; `false` suppresses optional public/listen layers only |
| `PASEO_SERVICE_PROXY_LISTEN` | Starts the optional service-only listener, e.g. `0.0.0.0:8080` |
| `PASEO_SERVICE_PROXY_PUBLIC_BASE_URL` | Adds public service aliases and links |
@@ -18,6 +18,7 @@ import {
expectComposerVisible, expectComposerVisible,
cancelAgent, cancelAgent,
composerLocator, composerLocator,
configureComposerInterruptSend,
expectQueuedMessageButton, expectQueuedMessageButton,
fillComposerDraft, fillComposerDraft,
holdSendButton, holdSendButton,
@@ -404,15 +405,6 @@ async function queueMessage(page: Page, prompt: string): Promise<void> {
await sendDraftToQueue(page); 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> { async function expectFailedSubmissionRestored(page: Page, prompt: string): Promise<void> {
await expectComposerDraft(page, prompt); await expectComposerDraft(page, prompt);
await expectComposerEditable(page); await expectComposerEditable(page);
@@ -431,14 +423,14 @@ async function expectInterruptedTurnOrderAfterReconnect(
}); });
const prompt = "Keep this prompt before its response."; const prompt = "Keep this prompt before its response.";
try { try {
await configureComposerInterruptSend(page);
await openAgentRoute(page, { workspaceId: agent.workspaceId, agentId: agent.agentId }); await openAgentRoute(page, { workspaceId: agent.workspaceId, agentId: agent.agentId });
await expectComposerVisible(page); await expectComposerVisible(page);
await agent.client.sendAgentMessage(agent.agentId, "Start the turn that will be interrupted."); 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.getByRole("button", { name: /stop|cancel/i }).first()).toBeVisible();
await expect(page.getByText("Cycle 1", { exact: true })).toBeVisible(); await expect(page.getByText("Cycle 1", { exact: true })).toBeVisible();
await queueMessage(page, prompt);
gate.setAgentStreamSuppressed(true); gate.setAgentStreamSuppressed(true);
await page.getByRole("button", { name: "Send queued message now" }).click(); await submitMessage(page, prompt);
const promptRow = page.getByTestId("user-message").filter({ hasText: prompt }); const promptRow = page.getByTestId("user-message").filter({ hasText: prompt });
await expect(promptRow).toBeVisible(); await expect(promptRow).toBeVisible();
await gate.waitForServerMessage("send_agent_message_response"); await gate.waitForServerMessage("send_agent_message_response");
@@ -659,14 +651,14 @@ async function expectLegacyAssistantStartsAfterInterruptedPrompt(
}); });
const prompt = "Start the replacement answer after this prompt."; const prompt = "Start the replacement answer after this prompt.";
try { try {
await configureComposerInterruptSend(page);
await openAgentRoute(page, { workspaceId: agent.workspaceId, agentId: agent.agentId }); await openAgentRoute(page, { workspaceId: agent.workspaceId, agentId: agent.agentId });
await expectComposerVisible(page); await expectComposerVisible(page);
await agent.client.sendAgentMessage(agent.agentId, "Start the interrupted answer."); await agent.client.sendAgentMessage(agent.agentId, "Start the interrupted answer.");
await expect(page.getByText("Cycle 1", { exact: true })).toBeVisible(); await expect(page.getByText("Cycle 1", { exact: true })).toBeVisible();
await queueMessage(page, prompt);
gate.setAssistantMessageIdsStripped(true); gate.setAssistantMessageIdsStripped(true);
gate.setAgentStreamEventSuppressed("turn_canceled", true); gate.setAgentStreamEventSuppressed("turn_canceled", true);
await page.getByRole("button", { name: "Send queued message now" }).click(); await submitMessage(page, prompt);
const promptRow = page.getByTestId("user-message").filter({ hasText: prompt }); const promptRow = page.getByTestId("user-message").filter({ hasText: prompt });
const replacementAnswer = page.getByText("(end of synthetic stream)", { exact: true }).last(); const replacementAnswer = page.getByText("(end of synthetic stream)", { exact: true }).last();
await expect(promptRow).toBeVisible(); await expect(promptRow).toBeVisible();
@@ -1098,6 +1090,7 @@ test.describe("Agent message submission", () => {
gate.holdNextServerMessage("cancel_agent_response"); gate.holdNextServerMessage("cancel_agent_response");
await page.getByRole("button", { name: "Stop agent", exact: true }).click(); await page.getByRole("button", { name: "Stop agent", exact: true }).click();
await gate.waitForHeldServerMessage(); await gate.waitForHeldServerMessage();
await page.getByRole("button", { name: "Send queued message now" }).click();
await expect(page.getByTestId("user-message").filter({ hasText: secondPrompt })).toHaveCount( await expect(page.getByTestId("user-message").filter({ hasText: secondPrompt })).toHaveCount(
1, 1,
@@ -1343,6 +1336,8 @@ test.describe("Agent message submission", () => {
await test.step("holding Send queues the draft", async () => { await test.step("holding Send queues the draft", async () => {
await fillComposerDraft(page, queuedPrompt); await fillComposerDraft(page, queuedPrompt);
await holdSendButton(page, "Send and steer"); await holdSendButton(page, "Send and steer");
expect((await gate.waitForRequest()).activeTurnBehavior).toBe("queue");
gate.accept();
await expectQueuedMessageButton(page); await expectQueuedMessageButton(page);
await expectComposerDraft(page, ""); await expectComposerDraft(page, "");
await expectAgentReadyToInterrupt(page); await expectAgentReadyToInterrupt(page);
@@ -1351,19 +1346,22 @@ test.describe("Agent message submission", () => {
).toHaveCount(0); ).toHaveCount(0);
}); });
await test.step("tapping Send still steers", async () => { await test.step("tapping Send still steers and takes the queued row along", async () => {
const steeredPrompt = "Steer this turn with a tap."; const steeredPrompt = "Steer this turn with a tap.";
await fillComposerDraft(page, steeredPrompt); await fillComposerDraft(page, steeredPrompt);
await page.getByRole("button", { name: "Send and steer", exact: true }).click(); await page.getByRole("button", { name: "Send and steer", exact: true }).click();
const request = await gate.waitForRequest(); const request = await gate.waitForRequest(2);
expect(request.text).toBe(steeredPrompt); expect(request.text).toBe(steeredPrompt);
expect(request.activeTurnBehavior).toBe("steer"); expect(request.activeTurnBehavior).toBe("steer");
gate.accept(); gate.accept(1);
await expect( await expect(
page.getByTestId("user-message").filter({ hasText: steeredPrompt }), page.getByTestId("user-message").filter({ hasText: steeredPrompt }),
).toHaveCount(1); ).toHaveCount(1);
await expectQueuedMessageButton(page); await expect(page.getByRole("button", { name: "Send queued message now" })).toHaveCount(0);
await expect(
page.getByTestId("user-message").filter({ hasText: queuedPrompt }),
).toHaveCount(1);
}); });
} finally { } finally {
await agent.cleanup(); await agent.cleanup();
@@ -1380,26 +1378,21 @@ test.describe("Agent message submission", () => {
await replaySteeredSleepTurnInBrowser(page, testInfo, "codex"); await replaySteeredSleepTurnInBrowser(page, testInfo, "codex");
}); });
test("restores overlapping queued sends when their connection fails", async ({ test("restores the draft when queueing loses the connection", async ({ page }, testInfo) => {
page,
}, testInfo) => {
test.setTimeout(120_000); test.setTimeout(120_000);
const gate = await gateNextAgentMessage(page); const gate = await gateNextAgentMessage(page);
const agent = await startRunningMockAgent(page, { const agent = await startRunningMockAgent(page, {
prefix: `overlapping-queued-send-${testInfo.workerIndex}-`, prefix: `queue-connection-lost-${testInfo.workerIndex}-`,
model: "one-minute-stream", model: "one-minute-stream",
prompt: "Keep the agent running while messages queue.", prompt: "Keep the agent running while a message queues.",
}); });
const prompts = ["Restore the first queued send.", "Restore the second queued send."]; const prompt = "Keep this draft if queueing fails.";
try { try {
await queueMessage(page, prompts[0]); await fillComposerDraft(page, prompt);
await queueMessage(page, prompts[1]); await sendDraftToQueue(page);
await page.getByRole("button", { name: "Send queued message now" }).first().click(); await gate.waitForRequest();
await gate.waitForRequest(1);
await page.getByRole("button", { name: "Send queued message now" }).first().click();
await gate.waitForRequest(2);
await gate.disconnect(); await gate.disconnect();
await expectQueuedSendFailuresRestored(page, prompts); await expectFailedSubmissionRestored(page, prompt);
} finally { } finally {
await agent.cleanup(); await agent.cleanup();
} }
@@ -2,8 +2,7 @@ import { expect, test } from "../support/fixtures";
import { gotoAppShell } from "../support/helpers/app"; import { gotoAppShell } from "../support/helpers/app";
import { seedWorkspace } from "../support/helpers/seed-client"; import { seedWorkspace } from "../support/helpers/seed-client";
import { getServerId } from "../support/helpers/server-id"; import { getServerId } from "../support/helpers/server-id";
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent"; import { openSettingsSection } from "../support/helpers/settings";
import { clickSettingsBackToWorkspace, openSettingsSection } from "../support/helpers/settings";
test("shows Pure black in the appearance picker", async ({ page }, testInfo) => { test("shows Pure black in the appearance picker", async ({ page }, testInfo) => {
await page.goto("/settings"); await page.goto("/settings");
@@ -97,43 +96,3 @@ test("applies the interface font size to settings text", async ({ page }) => {
await expect(contentSizeInput).toHaveValue("21"); await expect(contentSizeInput).toHaveValue("21");
await expect(sectionTitle).toHaveCSS("font-size", "10px"); 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,11 +1,5 @@
import { expect, test, type Page } from "../support/fixtures"; import { expect, test, type Page } from "../support/fixtures";
import { withDirectoryPlugin } from "../support/helpers/plugin-timeline"; import { composerLocator, expectComposerVisible, submitMessage } from "../support/helpers/composer";
import {
attachImageFromMenu,
composerLocator,
expectComposerVisible,
submitMessage,
} from "../support/helpers/composer";
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent"; import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
import { import {
expectSessionRowArchived, expectSessionRowArchived,
@@ -146,47 +140,6 @@ async function waitForReplacementAgentId(page: Page, oldAgentId: string): Promis
} }
test.describe("Client slash commands", () => { test.describe("Client slash commands", () => {
test("keeps the draft when a typed plugin slash command has an attachment", async ({ page }) => {
test.setTimeout(90_000);
await withDirectoryPlugin({
pluginId: "attachment-slash-e2e",
source: `
export default function contribute(client) {
client.addSlashCommand({name:"picture", description:"Review an attached picture", argumentHint:"<question>", context:"agent",
onSubmit(){throw new Error("Plugin handler unexpectedly received this command");}});
return () => {};
}`,
run: async () => {
await withOpenReadyMockAgent(page, { title: "Attached slash command" }, async () => {
const input = composerLocator(page);
await input.fill("/pict");
await expect(
page.getByText("Review an attached picture", { exact: true }).first(),
).toBeVisible();
await input.fill("");
await attachImageFromMenu(page, {
name: "picture.png",
mimeType: "image/png",
buffer: Buffer.from(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==",
"base64",
),
});
await input.fill("/picture what is this?");
await input.press("Enter");
await expect(
page.getByRole("alert").filter({ hasText: "Remove attachments to run /picture." }),
).toBeVisible();
await expect(input).toHaveValue("/picture what is this?");
await expect(page.getByTestId("composer-image-attachment-pill")).toBeVisible();
await expect(
page.getByTestId("user-message").filter({ hasText: "/picture what is this?" }),
).toHaveCount(0);
});
},
});
});
test("slash quit archives the active agent and removes its tab", async ({ page }) => { test("slash quit archives the active agent and removes its tab", async ({ page }) => {
await withOpenReadyMockAgent(page, { title: "Slash quit e2e" }, async ({ agentId, title }) => { await withOpenReadyMockAgent(page, { title: "Slash quit e2e" }, async ({ agentId, title }) => {
await runClientSlashCommand(page, "/quit"); await runClientSlashCommand(page, "/quit");
@@ -0,0 +1,320 @@
import { expect, test } from "../support/fixtures";
import { expectAgentIdle } from "../support/helpers/agent-stream";
import {
attachComposerTestImage,
cancelAgent,
composerLocator,
expectAttachmentPill,
expectComposerDraft,
expectComposerVisible,
fillComposerDraft,
sendDraftToQueue,
} from "../support/helpers/composer";
import {
cancelQueuedMessage,
editQueuedMessage,
expectDeliveredImage,
expectComposerOnScreen,
expectDeliveredOnce,
expectSenderIconUnsquashed,
openSecondClient,
queuedRow,
queuedRows,
queueMessage,
queuePausedNotice,
queueThroughHost,
reopenAgent,
scrollQueueFrom,
seedAgentWithOpenTurn,
sendQueuedMessageNow,
} from "../support/helpers/composer-queue";
import { openAgentRoute } from "../support/helpers/mock-agent";
test.describe("Composer queue", () => {
test("a queued image prompt can be edited, survives a reload, and is delivered once", async ({
page,
}) => {
const prompt = "Describe this screenshot.";
const revised = "Describe this screenshot in one line.";
const agent = await seedAgentWithOpenTurn({ repoPrefix: "queue-edit-", title: "Queue edit" });
try {
await openAgentRoute(page, agent);
await expectComposerVisible(page);
await test.step("queue a prompt with an image", async () => {
await attachComposerTestImage(page);
await expectAttachmentPill(page, "composer-image-attachment-pill");
await queueMessage(page, prompt);
await expect(queuedRow(page, prompt)).toContainText("1 attachment");
});
await test.step("Edit takes the text and image back into the composer", async () => {
await editQueuedMessage(page, prompt);
await expect(queuedRows(page)).toHaveCount(0);
await expectComposerDraft(page, prompt);
await expectAttachmentPill(page, "composer-image-attachment-pill");
await expect(composerLocator(page)).toBeFocused();
});
await test.step("queue the revised prompt with the same image", async () => {
await queueMessage(page, revised);
await expect(queuedRow(page, revised)).toContainText("1 attachment");
});
await test.step("the row is still there after a reload", async () => {
await page.reload();
await expect(queuedRow(page, revised)).toBeVisible({ timeout: 30_000 });
await expect(queuedRows(page)).toHaveCount(1);
});
await test.step("the prompt is delivered once when the turn ends", async () => {
await agent.finishTurn();
await expectDeliveredOnce(page, revised);
await expectDeliveredImage(page, revised);
await expect(queuedRows(page)).toHaveCount(0);
});
} finally {
await agent.cleanup();
}
});
test("Stop pauses the queue until the user sends a row", async ({ page }) => {
const prompt = "Run after I say so.";
const agent = await seedAgentWithOpenTurn({ repoPrefix: "queue-held-", title: "Queue held" });
try {
await openAgentRoute(page, agent);
await expectComposerVisible(page);
await queueMessage(page, prompt);
await expect(queuePausedNotice(page)).toHaveCount(0);
await cancelAgent(page);
await expectAgentIdle(page);
await expect(queuePausedNotice(page)).toBeVisible();
await expect(queuedRow(page, prompt)).toBeVisible();
await sendQueuedMessageNow(page, prompt);
await expectDeliveredOnce(page, prompt);
await expect(queuePausedNotice(page)).toHaveCount(0);
} finally {
await agent.cleanup();
}
});
test("the host delivers a queued prompt with every client closed", async ({ page }) => {
const prompt = "Continue while I am away.";
const agent = await seedAgentWithOpenTurn({
repoPrefix: "queue-closed-",
title: "Queue closed",
});
try {
await openAgentRoute(page, agent);
await expectComposerVisible(page);
await queueMessage(page, prompt);
await page.close();
await agent.finishTurn();
await agent.client.waitForFinish(agent.agentId, 30_000);
const reopened = await reopenAgent(page, agent);
await expectDeliveredOnce(reopened, prompt);
await expect(queuedRows(reopened)).toHaveCount(0);
} finally {
await agent.cleanup();
}
});
test("two clients share one queue", async ({ browser, page }) => {
const unwanted = "Do not run this one.";
const urgent = "Run this one now.";
const agent = await seedAgentWithOpenTurn({ repoPrefix: "queue-sync-", title: "Queue sync" });
try {
await openAgentRoute(page, agent);
await expectComposerVisible(page);
const second = await openSecondClient(browser, page, agent);
try {
await expectComposerVisible(second.page);
await test.step("a row queued on one client appears on the other", async () => {
await queueMessage(page, unwanted);
await expect(queuedRow(second.page, unwanted)).toBeVisible();
await fillComposerDraft(second.page, urgent);
await sendDraftToQueue(second.page);
await expect(queuedRows(page)).toContainText([unwanted, urgent]);
});
await test.step("Cancel on one client removes the row on the other", async () => {
await cancelQueuedMessage(second.page, unwanted);
await expect(queuedRow(page, unwanted)).toHaveCount(0);
});
await test.step("Send now on one client updates the other", async () => {
await sendQueuedMessageNow(page, urgent);
await expectDeliveredOnce(second.page, urgent);
await expect(
second.page.getByTestId("user-message").filter({ hasText: unwanted }),
).toHaveCount(0);
});
} finally {
await second.close();
}
} finally {
await agent.cleanup();
}
});
test("switching away from a retained agent tab and returning catches up on queue changes", async ({
page,
}) => {
const initial = "Initial queued row.";
const hidden = "Arrived while hidden.";
const agent = await seedAgentWithOpenTurn({
repoPrefix: "queue-hidden-",
title: "Queue first",
});
try {
await agent.client.createAgent({
provider: "mock",
cwd: agent.cwd,
workspaceId: agent.workspaceId,
title: "Queue second",
modeId: "load-test",
model: "e2e-fast-stream",
});
await openAgentRoute(page, agent);
await expectComposerVisible(page);
await queueMessage(page, initial);
await page.getByRole("button", { name: "Queue second", exact: true }).click();
await queueThroughHost(agent, [hidden]);
await page.getByRole("button", { name: "Queue first", exact: true }).click();
await expect(queuedRows(page)).toContainText([initial, hidden]);
} finally {
await agent.cleanup();
}
});
test("a long queue scrolls without pushing the composer off screen", async ({ page }) => {
const texts = Array.from({ length: 20 }, (_, index) => `Queued update ${index + 1}.`);
const first = "Queued update 1.";
const last = "Queued update 20.";
const agent = await seedAgentWithOpenTurn({ repoPrefix: "queue-long-", title: "Queue long" });
try {
await openAgentRoute(page, agent);
await expectComposerVisible(page);
await queueThroughHost(agent, texts);
await expect(queuedRows(page)).toHaveCount(20);
for (const viewport of [
{ width: 1280, height: 800 },
{ width: 390, height: 844 },
// A phone with its keyboard open.
{ width: 390, height: 500 },
]) {
await test.step(`${viewport.width}x${viewport.height}`, async () => {
await page.setViewportSize(viewport);
await expect(queuedRow(page, first)).toBeVisible();
await expectComposerOnScreen(page);
await scrollQueueFrom(page, first, 5000);
// Scrolled to the end, a fractional frame height can clip a sub-pixel of the row.
await expect(queuedRow(page, last)).toBeInViewport({ ratio: 0.99 });
await expectComposerOnScreen(page);
await scrollQueueFrom(page, last, -5000);
await expect(queuedRow(page, first)).toBeInViewport({ ratio: 1 });
});
}
} finally {
await agent.cleanup();
}
});
test("a message queued by another agent can be cancelled but not edited", async ({ page }) => {
const message = "The release notes are ready for review.";
const agent = await seedAgentWithOpenTurn({
repoPrefix: "queue-sender-",
title: "Queue recipient",
});
try {
const sender = await agent.client.createAgent({
provider: "mock",
cwd: agent.cwd,
workspaceId: agent.workspaceId,
title: "Release coordination and changelog verification helper for the mobile team",
model: "e2e-fast-stream",
});
await openAgentRoute(page, agent);
await expectComposerVisible(page);
await agent.client.sendAgentMessage(agent.agentId, message, {
sourceAgentId: sender.id,
activeTurnBehavior: "queue",
});
const row = queuedRow(page, message);
await expect(row).toContainText("Sent by Release coordination");
await expect(row.getByRole("button", { name: "Send queued message now" })).toBeEnabled();
await expect(row.getByRole("button", { name: "Cancel queued message" })).toBeEnabled();
await expect(row.getByRole("button", { name: "Edit queued message" })).toHaveCount(0);
await test.step("a long sender name truncates without squashing its icon", async () => {
await page.setViewportSize({ width: 390, height: 844 });
await expect(row).toBeInViewport();
await expectSenderIconUnsquashed(row);
});
await cancelQueuedMessage(page, message);
await expect(queuedRows(page)).toHaveCount(0);
} finally {
await agent.cleanup();
}
});
test("editing a queued image prompt on a short phone viewport keeps remaining queued rows visible", async ({
page,
}) => {
const withImage = "Describe this screenshot.";
const remaining = Array.from({ length: 4 }, (_, index) => `Remaining update ${index + 1}.`);
const agent = await seedAgentWithOpenTurn({
repoPrefix: "queue-compact-edit-",
title: "Queue compact edit",
});
try {
await openAgentRoute(page, agent);
await expectComposerVisible(page);
await attachComposerTestImage(page);
await expectAttachmentPill(page, "composer-image-attachment-pill");
await queueMessage(page, withImage);
await queueThroughHost(agent, remaining);
await expect(queuedRows(page)).toHaveCount(5);
await page.setViewportSize({ width: 390, height: 500 });
await editQueuedMessage(page, withImage);
await expectComposerDraft(page, withImage);
await expectAttachmentPill(page, "composer-image-attachment-pill");
await expect(composerLocator(page)).toBeInViewport({ ratio: 1 });
await expect(
page.getByRole("button", { name: "Send and steer", exact: true }),
).toBeInViewport({
ratio: 1,
});
// The queue scroll viewport must keep a readable slice (>= 90px) above the restored image pill,
// not collapse to a sliver inside a 0.6*viewport slot clamp.
const scrollFrameHeight = await page
.getByRole("list", { name: "Queued messages" })
.evaluate((list) => {
const scrollView = list.parentElement?.parentElement;
return scrollView ? scrollView.getBoundingClientRect().height : 0;
});
expect(scrollFrameHeight).toBeGreaterThanOrEqual(90);
} finally {
await agent.cleanup();
}
});
});
+1 -28
View File
@@ -10,7 +10,6 @@ import {
finishSetup, finishSetup,
goToSetupStep, goToSetupStep,
hostGivesAgentsPaseoTools, hostGivesAgentsPaseoTools,
hostToolGroups,
openAppAsNewUser, openAppAsNewUser,
openRelayPairingFromSetup, openRelayPairingFromSetup,
closeRelayPairing, closeRelayPairing,
@@ -25,7 +24,6 @@ import {
recordFirstLaunch, recordFirstLaunch,
setupModal, setupModal,
setupPrimaryButton, setupPrimaryButton,
setHostTools,
setupSheet, setupSheet,
showSetupAgainFromSettings, showSetupAgainFromSettings,
skipSetup, skipSetup,
@@ -428,30 +426,6 @@ 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 }) => { test("with no skills picked, skills read as off and Continue moves on", async ({ page }) => {
const host = await startSetupHost("no-skills"); const host = await startSetupHost("no-skills");
@@ -489,7 +463,6 @@ test("in the compact layout, Finish on Orchestration applies its switches", asyn
const primary = (label: string) => page.getByRole("button", { name: label, exact: true }); const primary = (label: string) => page.getByRole("button", { name: label, exact: true });
try { try {
await setHostTools(host, { enabled: false });
await openAppAsNewUser(page, host); await openAppAsNewUser(page, host);
await step("Welcome to Paseo"); await step("Welcome to Paseo");
await primary("Continue").click(); await primary("Continue").click();
@@ -498,7 +471,7 @@ test("in the compact layout, Finish on Orchestration applies its switches", asyn
await step("Add your projects"); await step("Add your projects");
await primary("Continue").click(); await primary("Continue").click();
// The host has tools off; the setup switch still starts on. // The setup host starts with Paseo tools off; the switch starts on.
expect(await hostGivesAgentsPaseoTools(host)).toBe(false); expect(await hostGivesAgentsPaseoTools(host)).toBe(false);
await step("Let agents use Paseo"); await step("Let agents use Paseo");
await expect(paseoToolsSwitch(page)).toBeChecked(); await expect(paseoToolsSwitch(page)).toBeChecked();
@@ -499,6 +499,56 @@ 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 ({ test("switches providers cleanly on a compact viewport with zero horizontal overflow", async ({
page, page,
}) => { }) => {
@@ -1,253 +0,0 @@
import { writeFile } from "node:fs/promises";
import { test, expect } from "../support/fixtures";
import {
readReactRenders,
recordReactRenders,
resetReactRenders,
} from "../support/helpers/react-renders";
import {
captureLoaderSteps,
freezeAnimationsAt,
openIdleChatBesideRunningAgent,
openQuietRunningTurn,
readAnimatingTargets,
readLoaderStep,
readRunningAnimations,
recordLoaderStepChanges,
recordRingAngles,
runningToolCall,
statusRings,
workingLoader,
} from "../support/helpers/running-indicators";
import { measureSteadyStateActivity } from "../support/helpers/steady-state-activity";
import { setTabVisibility } from "../support/helpers/workspace-ui";
/**
* A running turn that is otherwise quiet shows three animated indicators: the six-dot loader, the
* tool-call label shimmer and the status rings. None of them may cost main-thread work: the
* browser's compositor carries them, so the page neither runs script, restyles nor repaints to
* keep them moving.
*
* The budgets sit between what the rest of the page does on its own and the cheapest way these
* indicators have been measured getting it wrong. With nothing moving, the main thread still
* commits to the compositor about three times a second (the elapsed counter and the app's own
* timers), and each commit restyles whatever is animating. Declaring the same animations as CSS
* `@keyframes` costs thirteen commits and fourteen restyles a second; driving them from script
* costs sixty frames a second.
*/
const SAMPLE_WINDOW_MS = 5_000;
const ANIMATION_FRAME_CALLBACKS_PER_SECOND_BUDGET = 2;
const STYLE_RECALCS_PER_SECOND_BUDGET = 8;
const MAIN_THREAD_COMMITS_PER_SECOND_BUDGET = 8;
const PAINTS_PER_SECOND_BUDGET = 4;
// The elapsed counter's repaint reports the whole viewport as its clip once a second. Sixty
// indicator frames a second repainted seventy viewports' worth.
const PAINTED_VIEWPORTS_PER_SECOND_BUDGET = 4;
const LOADER_PERIOD_MS = 950;
const LOADER_STEP_MS = LOADER_PERIOD_MS / 6;
const STATUS_RING_PERIOD_MS = 900;
const STATUS_RING_STEPS = 27;
// Thirty ring positions a second, plus the few frames a second the rest of the page draws. A ring
// that turns with the display draws sixty or more.
const RING_ONLY_FRAMES_PER_SECOND_BUDGET = 36;
// React renders these once when the indicator appears. Rendering again while the turn is quiet
// means the animation is being driven through React.
const INDICATOR_COMPONENTS = /SyncedLoader|StatusRing|Shimmer|ExpandableBadge|WorkingIndicator/;
function indicatorRenders(renders: Record<string, number>): string[] {
return Object.keys(renders).filter((name) => INDICATOR_COMPONENTS.test(name));
}
test.describe("Running indicators", () => {
test("keep moving without waking the main thread", async ({ page, browser }, testInfo) => {
test.setTimeout(180_000);
await recordReactRenders(page);
const agent = await openQuietRunningTurn(page);
try {
await resetReactRenders(page);
const activity = await measureSteadyStateActivity({
browser,
page,
windowMs: SAMPLE_WINDOW_MS,
});
const renders = await readReactRenders(page);
const animations = await readRunningAnimations(page);
const stepChanges = await recordLoaderStepChanges(page, 3_000);
const evidence = { activity, renders, animations, stepChanges };
await writeFile(testInfo.outputPath("evidence.json"), JSON.stringify(evidence, null, 2));
expect
.soft(activity.animationFrameCallbacksPerSecond)
.toBeLessThan(ANIMATION_FRAME_CALLBACKS_PER_SECOND_BUDGET);
expect.soft(activity.styleRecalcsPerSecond).toBeLessThan(STYLE_RECALCS_PER_SECOND_BUDGET);
expect.soft(activity.paintsPerSecond).toBeLessThan(PAINTS_PER_SECOND_BUDGET);
expect
.soft(activity.paintedViewportsPerSecond)
.toBeLessThan(PAINTED_VIEWPORTS_PER_SECOND_BUDGET);
expect
.soft(activity.mainThreadCommitsPerSecond)
.toBeLessThan(MAIN_THREAD_COMMITS_PER_SECOND_BUDGET);
expect.soft(indicatorRenders(renders)).toEqual([]);
// The cadence is part of the design: six even steps in 950 ms, in order.
const steps = stepChanges.slice(1);
expect.soft(steps.length).toBeGreaterThan(12);
for (let index = 1; index < steps.length; index += 1) {
expect.soft(steps[index].step).toBe((steps[index - 1].step + 1) % 6);
}
const measuredStepMs = (steps.at(-1)!.atMs - steps[0].atMs) / (steps.length - 1);
expect.soft(Math.abs(measuredStepMs - LOADER_STEP_MS)).toBeLessThan(8);
const ringAnimations = animations.filter((animation) => animation.target === "status-ring");
expect.soft(ringAnimations.length).toBeGreaterThan(0);
for (const ring of ringAnimations) {
expect.soft(ring).toMatchObject({
durationMs: STATUS_RING_PERIOD_MS,
easing: "linear",
iterations: Number.POSITIVE_INFINITY,
properties: ["transform"],
});
}
} finally {
await agent.cleanup();
}
});
test("a ring beside an idle chat redraws the window thirty times a second", async ({
page,
browser,
}, testInfo) => {
test.setTimeout(180_000);
const scene = await openIdleChatBesideRunningAgent(page);
try {
const animating = await readAnimatingTargets(page);
const activity = await measureSteadyStateActivity({
browser,
page,
windowMs: SAMPLE_WINDOW_MS,
});
const angles = await recordRingAngles(page, STATUS_RING_PERIOD_MS * 3);
await writeFile(
testInfo.outputPath("evidence.json"),
JSON.stringify({ animating, activity, angles }, null, 2),
);
// Nothing but rings is moving, so every frame drawn is a ring's.
expect.soft(new Set(animating)).toEqual(new Set(["status-ring"]));
expect
.soft(activity.compositorFramesPerSecond)
.toBeLessThan(RING_ONLY_FRAMES_PER_SECOND_BUDGET);
// The cadence is part of the design: the quarter is only ever at one of its even steps.
const stepDegrees = 360 / STATUS_RING_STEPS;
const offStep = angles.filter((angle) => {
const stepsAlong = angle / stepDegrees;
return Math.abs(stepsAlong - Math.round(stepsAlong)) * stepDegrees > 0.05;
});
expect.soft(offStep).toEqual([]);
expect.soft(angles.length).toBeGreaterThan(STATUS_RING_STEPS / 2);
expect.soft(angles.length).toBeLessThanOrEqual(STATUS_RING_STEPS);
} finally {
await scene.cleanup();
}
});
test("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,28 +52,17 @@ async function exitSelection(page: Page) {
} }
/** /**
* Walks the sidebar selection click matrix on four rows: Cmd/Ctrl+click (and Cmd/Ctrl+Shift+click) * Walks the Finder click matrix on four rows, starting with the first row open: a modifier click
* from normal mode navigates instead of entering select mode, Shift+click enters select mode on the * from normal mode selects only the clicked row, Cmd/Ctrl+click toggles, Shift+click extends and
* clicked row alone, Cmd/Ctrl+click and plain clicks toggle while select mode is active, and * shrinks a range from the anchor, and plain clicks keep toggling while select mode is on.
* Shift+click extends, shrinks, and flips a range from the anchor.
*/ */
async function exerciseClickMatrix(page: Page, rows: readonly Locator[]) { async function exerciseClickMatrix(page: Page, rows: readonly Locator[]) {
const [first, second, third, fourth] = rows; const [first, second, third, fourth] = rows;
await first.click(); await first.click();
await expect(first).toHaveAttribute("aria-selected", "true"); 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(); const openWorkspaceUrl = page.url();
// Shift+click enters select mode on the clicked row alone; Cmd/Ctrl+click and plain clicks toggle. await third.click({ modifiers: [MOD] });
await third.click({ modifiers: ["Shift"] });
await expectSelectedCount(page, 1); await expectSelectedCount(page, 1);
await expectChecked(rows, [false, false, true, false]); await expectChecked(rows, [false, false, true, false]);
@@ -113,7 +102,7 @@ test.describe("sidebar workspace selection clicks", () => {
seeded = null; seeded = null;
}); });
test("Shift+click enters select mode while Cmd/Ctrl+click navigates in project grouping", async ({ test("Cmd/Ctrl+click and Shift+click select like Finder in project grouping", async ({
page, page,
}) => { }) => {
seeded = await seedProjectWithWorkspaces(4); seeded = await seedProjectWithWorkspaces(4);
@@ -122,9 +111,7 @@ test.describe("sidebar workspace selection clicks", () => {
await exerciseClickMatrix(page, await rowsInSidebarOrder(page, seeded.workspaceIds)); await exerciseClickMatrix(page, await rowsInSidebarOrder(page, seeded.workspaceIds));
}); });
test("Shift+click enters select mode while Cmd/Ctrl+click navigates in status grouping", async ({ test("Cmd/Ctrl+click and Shift+click select like Finder in status grouping", async ({ page }) => {
page,
}) => {
seeded = await seedProjectWithWorkspaces(4); seeded = await seedProjectWithWorkspaces(4);
await gotoAppShell(page); await gotoAppShell(page);
await waitForSidebarHydration(page); await waitForSidebarHydration(page);
@@ -5,34 +5,30 @@ import { expectComposerVisible } from "../support/helpers/composer";
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent"; import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
interface ShimmerEvidence { interface ShimmerEvidence {
durationMs: number; animationDuration: string;
endPx: number; endPx: number;
label: string; label: string;
renderedWidth: number; renderedWidth: number;
startPx: number; startPx: number;
} }
// The band is the shimmer's moving window; its animation carries the sweep it was measured for. async function readShimmerEvidence(locator: Locator): Promise<ShimmerEvidence> {
async function readShimmerEvidence(badge: Locator): Promise<ShimmerEvidence> { return locator.evaluate((root) => {
return badge const shimmer = Array.from(root.querySelectorAll<HTMLElement>("*")).find((element) =>
.getByTestId("label-shimmer") getComputedStyle(element).animationName.includes("paseo-toolcall-shimmer"),
.first() );
.evaluate((shimmer) => { if (!shimmer) {
const effect = shimmer.firstElementChild?.getAnimations()[0]?.effect; throw new Error("Expected a running shimmer inside the badge");
if (!(effect instanceof KeyframeEffect)) { }
throw new Error("Expected a running shimmer inside the badge"); const style = getComputedStyle(shimmer);
} return {
const [startPx, endPx] = effect animationDuration: style.animationDuration,
.getKeyframes() endPx: Number.parseFloat(style.getPropertyValue("--paseo-shimmer-end")),
.map((keyframe) => new DOMMatrix(String(keyframe.transform)).m41); label: shimmer.textContent ?? "",
return { renderedWidth: shimmer.getBoundingClientRect().width,
durationMs: Number(effect.getComputedTiming().duration), startPx: Number.parseFloat(style.getPropertyValue("--paseo-shimmer-start")),
endPx, };
label: shimmer.textContent ?? "", });
renderedWidth: shimmer.getBoundingClientRect().width,
startPx,
};
});
} }
test("measures an overview heading that becomes loading after its idle mount", async ({ test("measures an overview heading that becomes loading after its idle mount", async ({
@@ -67,11 +63,11 @@ test("measures an overview heading that becomes loading after its idle mount", a
if (!idleGroupHandle) { if (!idleGroupHandle) {
throw new Error("Expected the idle tool-call group to be mounted"); throw new Error("Expected the idle tool-call group to be mounted");
} }
await expect(group.getByTestId("label-shimmer")).toHaveCount(0); await expect(group.locator('[style*="paseo-toolcall-shimmer"]')).toHaveCount(0);
await gate.waitForSecondRunning(); await gate.waitForSecondRunning();
gate.releaseSecondRunning(); gate.releaseSecondRunning();
await expect(group.getByTestId("label-shimmer")).not.toHaveCount(0); await expect(group.locator('[style*="paseo-toolcall-shimmer"]')).not.toHaveCount(0);
const sameGroupNode = await group.evaluate( const sameGroupNode = await group.evaluate(
(node, previous) => node === previous, (node, previous) => node === previous,
idleGroupHandle, idleGroupHandle,
@@ -3,7 +3,6 @@ import { buildHostAgentDetailRoute } from "@/utils/host-routes";
import { test } from "../support/fixtures"; import { test } from "../support/fixtures";
import { seedWorkspace, type SeedDaemonClient } from "../support/helpers/seed-client"; import { seedWorkspace, type SeedDaemonClient } from "../support/helpers/seed-client";
import { getServerId } from "../support/helpers/server-id"; import { getServerId } from "../support/helpers/server-id";
import { getE2EDaemonPort } from "../support/helpers/daemon-port";
import { observeTimelineSubscriptions } from "../support/helpers/timeline-delivery"; import { observeTimelineSubscriptions } from "../support/helpers/timeline-delivery";
import { waitForWorkspaceTabsVisible } from "../support/helpers/workspace-tabs"; import { waitForWorkspaceTabsVisible } from "../support/helpers/workspace-tabs";
import { selectWorkspaceInSidebar } from "../support/helpers/sidebar"; import { selectWorkspaceInSidebar } from "../support/helpers/sidebar";
@@ -255,226 +254,7 @@ async function expectCurrentChatWithoutCatchUp(page: Page, message: string) {
await expect(page.getByRole("alert").filter({ hasText: "Updating messages" })).toHaveCount(0); 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.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("a reloaded layout subscribes only the chat it restores into", async ({ page }) => {
test.setTimeout(120_000); test.setTimeout(120_000);
const subscriptions = observeTimelineSubscriptions(page); const subscriptions = observeTimelineSubscriptions(page);
@@ -30,7 +30,7 @@ import {
pressArchiveShortcut, pressArchiveShortcut,
pressUndoShortcut, pressUndoShortcut,
readSidebarListLayout, readSidebarListLayout,
recordLastRowDuringToastExpiry, recordLastRowBottomPerFrame,
resizeSidebarToMinimum, resizeSidebarToMinimum,
rowArchiveButton, rowArchiveButton,
rowKebab, rowKebab,
@@ -187,6 +187,7 @@ test.describe("Workspace archive undo", () => {
test("a long list scrolls its last row clear of the toast, and settles back smoothly after it", async ({ test("a long list scrolls its last row clear of the toast, and settles back smoothly after it", async ({
page, page,
}) => { }) => {
await page.clock.install({ time: Date.now() });
const fillers: Array<{ path: string; cleanup: () => Promise<void> }> = []; const fillers: Array<{ path: string; cleanup: () => Promise<void> }> = [];
const fillerProjectIds: string[] = []; const fillerProjectIds: string[] = [];
try { try {
@@ -203,30 +204,30 @@ test.describe("Workspace archive undo", () => {
await archiveFromRowButton(page, worktree.workspaceId); await archiveFromRowButton(page, worktree.workspaceId);
await page.mouse.move(0, 0); await page.mouse.move(0, 0);
// Read both edges together because the sidebar can resize while the toast is open. 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.
await expect await expect
.poll(async () => { .poll(async () => {
const layout = await scrollSidebarListToEnd(page); 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)!); return Math.round(toastBox.y - layout.rowBottoms.at(-1)!);
}) })
.toBeGreaterThanOrEqual(Math.round(restingEndGap)); .toBe(Math.round(restingEndGap));
const bottoms = await recordLastRowDuringToastExpiry(page); const frames = recordLastRowBottomPerFrame(page, 40);
await outlastUndoWindow(page);
const bottoms = await frames;
await expect(archivedToast(page)).toHaveCount(0);
// Without scrolling again, the list returns to its usual gap below the last row. // Without scrolling again, the list ends just below its last row once more.
const settled = await readSidebarListLayout(page); const settled = await readSidebarListLayout(page);
const settledBottom = settled.rowBottoms.at(-1)!; expect(settled.listBottom - settled.rowBottoms.at(-1)!).toBeCloseTo(restingEndGap, 0);
expect(settled.listBottom - settledBottom).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]!;
// The last row moves through an intermediate position without reversing direction. expect(travel).toBeGreaterThan(toastBox.height);
const startBottom = bottoms[0]!; const steps = bottoms.slice(1).map((bottom, index) => bottom - bottoms[index]!);
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.min(...steps)).toBeGreaterThanOrEqual(0);
expect(Math.max(...steps)).toBeLessThan(travel / 2);
} finally { } finally {
for (const projectId of fillerProjectIds) { for (const projectId of fillerProjectIds) {
await client.removeProject(projectId).catch(() => undefined); await client.removeProject(projectId).catch(() => undefined);
@@ -99,10 +99,6 @@ async function clickRowArchiveButton(page: Page, workspaceId: string): Promise<v
await rowArchiveButton(page, workspaceId).click(); await rowArchiveButton(page, workspaceId).click();
} }
function rowArchivePendingIndicator(page: Page, workspaceId: string) {
return workspaceRow(page, workspaceId).getByTestId("workspace-status-indicator-loading");
}
async function cycleThemeAndWaitForSidebar(page: Page, workspaceId: string): Promise<void> { async function cycleThemeAndWaitForSidebar(page: Page, workspaceId: string): Promise<void> {
const rowBeforeThemeChange = await workspaceRow(page, workspaceId).elementHandle(); const rowBeforeThemeChange = await workspaceRow(page, workspaceId).elementHandle();
if (!rowBeforeThemeChange) if (!rowBeforeThemeChange)
@@ -367,33 +363,10 @@ test.describe("Workspace archive risk warning for worktree backing", () => {
expect(warning.message()).toContain("1 unpushed commit"); expect(warning.message()).toContain("1 unpushed commit");
await expectWorktreeKept(page, worktree); await expectWorktreeKept(page, worktree);
await expect(rowArchivePendingIndicator(page, worktree.workspaceId)).toHaveCount(0);
expect(relay.archiveRequests()).toBe(0); expect(relay.archiveRequests()).toBe(0);
expect(existsSync(path.join(worktree.workspaceDirectory, "DIRTY.md"))).toBe(true); expect(existsSync(path.join(worktree.workspaceDirectory, "DIRTY.md"))).toBe(true);
}); });
test("the row shows the archive as pending from the press until the host answers", async ({
page,
}) => {
const worktree = await createWorktree("archive-risk-pending");
const statusRequest = await holdCheckoutStatusRequest(page, worktree);
await openSidebarRow(page, worktree.workspaceId);
await expect(rowArchivePendingIndicator(page, worktree.workspaceId)).toHaveCount(0);
statusRequest.arm();
await clickRowArchiveButton(page, worktree.workspaceId);
await statusRequest.waitForHeld();
try {
await expect(rowArchivePendingIndicator(page, worktree.workspaceId)).toBeVisible();
expect(statusRequest.archiveRequests()).toBe(0);
} finally {
statusRequest.release();
}
await expectWorkspaceAbsentFromSidebar(page, worktree.workspaceId);
await expect(undoButton(page)).toBeVisible();
});
test("a worktree holding only new files warns when the repository hides untracked files", async ({ test("a worktree holding only new files warns when the repository hides untracked files", async ({
page, page,
}) => { }) => {
@@ -7,29 +7,9 @@ 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 token. Bold and links preserve the resulting size. Check the glyphs, not the background height: native backgrounds use
line metrics. line metrics.
Use a development client rebuilt from this checkout. In a disposable checkout, Use a development client rebuilt from this checkout. Follow the temporary entry
temporarily replace `packages/app/index.ts` with: point and Metro workflow in [status-ring](../status-ring/README.md), importing
`MarkdownFormattingRegression` from `./e2e/mobile/markdown-formatting/native`.
```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. 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: With this fixture open in an Android Agent Device session, run:
@@ -0,0 +1,45 @@
# 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.
@@ -0,0 +1,71 @@
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");
@@ -0,0 +1,69 @@
import { useCallback, useLayoutEffect, useState } from "react";
import { Button, Text, View } from "react-native";
import { useAnimatedReaction, useSharedValue } from "react-native-reanimated";
import { scheduleOnRN, scheduleOnUI } from "react-native-worklets";
import { RetainedPanel } from "@/components/retained-panel";
import { useStatusRingRotation } from "@/components/status-ring/clock";
import { StatusRing } from "@/components/status-ring";
interface Sample {
updates: number;
rotation: number;
}
declare global {
var __ringSamples: Record<string, Sample>;
var __ringReaders: Record<string, () => void>;
}
function recordSample(name: string, value: { updates: number; rotation: number }) {
globalThis.__ringSamples[name] = value;
}
function Probe({ name }: { name: string }) {
const rotation = useStatusRingRotation();
const updates = useSharedValue(0);
useAnimatedReaction(
() => rotation.value,
() => {
updates.value += 1;
},
);
// Read the real UI runtime, without scheduling a continuous JS observer.
useLayoutEffect(() => {
globalThis.__ringSamples ??= {};
globalThis.__ringReaders ??= {};
globalThis.__ringReaders[name] = () =>
scheduleOnUI(() => {
"worklet";
const sample = { updates: updates.value, rotation: rotation.value };
scheduleOnRN(recordSample, name, sample);
});
return () => {
delete globalThis.__ringReaders[name];
};
}, [name, rotation, updates]);
return <StatusRing />;
}
const containerStyle = { flex: 1, padding: 60, backgroundColor: "white" };
export default function NativeRingRegression() {
const [first, setFirst] = useState(true);
const [second, setSecond] = useState(true);
const toggleFirst = useCallback(() => setFirst((value) => !value), []);
const toggleSecond = useCallback(() => setSecond((value) => !value), []);
return (
<View style={containerStyle}>
<Text>Native retained status rings</Text>
<Button title={first ? "Hide first" : "Show first"} onPress={toggleFirst} />
<Button title={second ? "Hide second" : "Show second"} onPress={toggleSecond} />
<RetainedPanel active={first}>
<Probe name="first" />
</RetainedPanel>
<RetainedPanel active={second}>
<Probe name="second" />
</RetainedPanel>
</View>
);
}
@@ -1,5 +1,6 @@
import { expect, type Page } from "@playwright/test"; import { expect, type Page } from "@playwright/test";
import { readScrollMetrics, waitForContentGrowth, expectNearBottom } from "./agent-bottom-anchor"; import { readScrollMetrics, waitForContentGrowth, expectNearBottom } from "./agent-bottom-anchor";
import { agentStopButton } from "./composer";
export async function awaitAssistantMessage(page: Page, hasText?: string | RegExp): Promise<void> { export async function awaitAssistantMessage(page: Page, hasText?: string | RegExp): Promise<void> {
const messages = page.getByTestId("assistant-message"); const messages = page.getByTestId("assistant-message");
@@ -14,7 +15,7 @@ export async function awaitToolCall(page: Page, toolName: string | RegExp): Prom
} }
export async function expectAgentIdle(page: Page, timeout = 30_000): Promise<void> { export async function expectAgentIdle(page: Page, timeout = 30_000): Promise<void> {
await expect(page.getByRole("button", { name: /stop|cancel/i })).toHaveCount(0, { timeout }); await expect(agentStopButton(page)).toHaveCount(0, { timeout });
} }
// The working indicator is an animated spinner View — no semantic ARIA role, testId is correct. // The working indicator is an animated spinner View — no semantic ARIA role, testId is correct.
@@ -0,0 +1,141 @@
import { expect, type Browser, type Locator, type Page } from "@playwright/test";
import { hideDeveloperToasts } from "../developer-ui.mjs";
import {
agentStopButton,
composerLocator,
expectComposerDraft,
fillComposerDraft,
sendDraftToQueue,
} from "./composer";
import { openAgentRoute, seedMockAgentWorkspace, type MockAgentWorkspace } from "./mock-agent";
export interface AgentWithOpenTurn extends MockAgentWorkspace {
/** Ends the open turn from outside the app, so it also works with every page closed. */
finishTurn(): Promise<void>;
}
/**
* A mock agent whose first turn stays open on a plan approval. The turn ends when the test
* answers it, so nothing here depends on how long a stream runs.
*/
export async function seedAgentWithOpenTurn(input: {
repoPrefix: string;
title: string;
}): Promise<AgentWithOpenTurn> {
const agent = await seedMockAgentWorkspace({
...input,
initialPrompt: "Emit synthetic plan approval.",
});
await agent.client.waitForFinish(agent.agentId, 30_000);
return {
...agent,
async finishTurn() {
const fetched = await agent.client.fetchAgent({ agentId: agent.agentId });
const request = fetched?.agent.pendingPermissions[0];
if (!request) throw new Error("The agent has no open turn to finish");
await agent.client.respondToPermission(agent.agentId, request.id, { behavior: "allow" });
},
};
}
export function queuedRows(page: Page): Locator {
return page.getByRole("list", { name: "Queued messages" }).getByRole("listitem");
}
export function queuedRow(page: Page, text: string): Locator {
return queuedRows(page).filter({ hasText: text });
}
export async function queueMessage(page: Page, text: string): Promise<void> {
await fillComposerDraft(page, text);
await sendDraftToQueue(page);
await expect(queuedRow(page, text)).toBeVisible();
await expectComposerDraft(page, "");
}
export async function editQueuedMessage(page: Page, text: string): Promise<void> {
await queuedRow(page, text)
.getByRole("button", { name: "Edit queued message", exact: true })
.click();
}
export async function cancelQueuedMessage(page: Page, text: string): Promise<void> {
await queuedRow(page, text)
.getByRole("button", { name: "Cancel queued message", exact: true })
.click();
}
export async function sendQueuedMessageNow(page: Page, text: string): Promise<void> {
await queuedRow(page, text)
.getByRole("button", { name: "Send queued message now", exact: true })
.click();
}
export function queuePausedNotice(page: Page): Locator {
return page.getByText("Queue paused until you send a message", { exact: true });
}
/** Queues through the host, for tests that need more rows than are worth typing. */
export async function queueThroughHost(agent: AgentWithOpenTurn, texts: string[]): Promise<void> {
for (const text of texts) {
await agent.client.sendAgentMessage(agent.agentId, text, { activeTurnBehavior: "queue" });
}
}
/** The composer input and Stop are both fully on screen. */
export async function expectComposerOnScreen(page: Page): Promise<void> {
await expect(composerLocator(page)).toBeInViewport({ ratio: 1 });
await expect(agentStopButton(page)).toBeInViewport({ ratio: 1 });
}
/** Turns the mouse wheel over one row, as a user does to move through the queue. */
export async function scrollQueueFrom(page: Page, text: string, deltaY: number): Promise<void> {
await queuedRow(page, text).hover();
await page.mouse.wheel(0, deltaY);
}
/** The icon leading a row's "Sent by" line is drawn at its full width. */
export async function expectSenderIconUnsquashed(row: Locator): Promise<void> {
const icon = await row.locator("svg").first().boundingBox();
if (!icon) throw new Error("The row has no visible sender icon");
expect(icon.width).toBeGreaterThanOrEqual(icon.height);
}
/** The queued prompt reached the transcript exactly once and left the queue. */
export async function expectDeliveredOnce(page: Page, text: string): Promise<void> {
await expect(page.getByTestId("user-message").filter({ hasText: text })).toHaveCount(1, {
timeout: 30_000,
});
await expect(queuedRow(page, text)).toHaveCount(0);
}
export async function expectDeliveredImage(page: Page, text: string): Promise<void> {
await expect(
page
.getByTestId("user-message")
.filter({ hasText: text })
.getByRole("button", { name: "Open image attachment" }),
).toHaveCount(1);
}
/** A page opened after the first one was closed, with the same stored app data. */
export async function reopenAgent(page: Page, agent: AgentWithOpenTurn): Promise<Page> {
const reopened = await page.context().newPage();
await hideDeveloperToasts(reopened);
await openAgentRoute(reopened, agent);
return reopened;
}
/** A second client of the same host: its own browser context and its own client id. */
export async function openSecondClient(
browser: Browser,
page: Page,
agent: AgentWithOpenTurn,
): Promise<{ page: Page; close(): Promise<void> }> {
const context = await browser.newContext({ storageState: await page.context().storageState() });
const second = await context.newPage();
await second.addInitScript(() => localStorage.removeItem("@paseo:client-id-v1"));
await hideDeveloperToasts(second);
await openAgentRoute(second, agent);
return { page: second, close: () => context.close() };
}
+13 -4
View File
@@ -103,8 +103,13 @@ export async function expectQueuedMessageButton(page: Page): Promise<void> {
}); });
} }
/** The composer's Stop button. Queued rows also have a Cancel button, so match the whole name. */
export function agentStopButton(page: Page) {
return page.getByRole("button", { name: /^(stop|canceling) agent$/i });
}
export async function cancelAgent(page: Page): Promise<void> { export async function cancelAgent(page: Page): Promise<void> {
const stopButton = page.getByRole("button", { name: /stop|cancel/i }).first(); const stopButton = agentStopButton(page).first();
await expect(stopButton).toBeVisible({ timeout: 10_000 }); await expect(stopButton).toBeVisible({ timeout: 10_000 });
await stopButton.click(); await stopButton.click();
} }
@@ -300,9 +305,7 @@ export async function startRunningMockAgent(
await page.goto(agentUrl); await page.goto(agentUrl);
await expectComposerVisible(page); await expectComposerVisible(page);
await client.sendAgentMessage(agent.id, opts.prompt); await client.sendAgentMessage(agent.id, opts.prompt);
await expect(page.getByRole("button", { name: /stop|cancel/i }).first()).toBeVisible({ await expect(agentStopButton(page).first()).toBeVisible({ timeout: 30_000 });
timeout: 30_000,
});
return { return {
client, client,
repo, repo,
@@ -467,6 +470,12 @@ export async function configureComposerQueueSend(page: Page): Promise<void> {
); );
} }
export async function configureComposerInterruptSend(page: Page): Promise<void> {
await page.addInitScript(() =>
localStorage.setItem("@paseo:app-settings", JSON.stringify({ sendBehavior: "interrupt" })),
);
}
/** Drive the real tab chooser's commands even when fullscreen covers its pointer surface. /** 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. * This exercises retained activity changes, not a claim that covered chrome is clickable.
*/ */
+2 -36
View File
@@ -4,10 +4,6 @@ import { tmpdir } from "node:os";
import path from "node:path"; import path from "node:path";
import { expect, type Locator, type Page } from "@playwright/test"; import { expect, type Locator, type Page } from "@playwright/test";
import type { DaemonClient as InternalDaemonClient } from "@getpaseo/client/internal/daemon-client"; 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 { addProjectFlow, addProjectFlowInput, expectAddProjectTab } from "./add-project-flow";
import { connectDaemonClient } from "./daemon-client-loader"; import { connectDaemonClient } from "./daemon-client-loader";
import { buildCreateAgentPreferences, buildSeededHost } from "./daemon-registry"; import { buildCreateAgentPreferences, buildSeededHost } from "./daemon-registry";
@@ -142,7 +138,7 @@ export async function goToSetupStep(page: Page, label: string): Promise<void> {
} }
export function paseoToolsSwitch(scope: Page | Locator): Locator { export function paseoToolsSwitch(scope: Page | Locator): Locator {
return scope.getByRole("switch", { name: "Enable tools", exact: true }); return scope.getByRole("switch", { name: "Inject Paseo tools", exact: true });
} }
/** Whether the host gives its agents Paseo tools, read from the host itself. */ /** Whether the host gives its agents Paseo tools, read from the host itself. */
@@ -151,37 +147,7 @@ export async function hostGivesAgentsPaseoTools(host: { port: number }): Promise
Pick<InternalDaemonClient, "connect" | "close" | "getDaemonConfig"> Pick<InternalDaemonClient, "connect" | "close" | "getDaemonConfig">
>({ clientIdPrefix: "app-e2e-onboarding", port: host.port }); >({ clientIdPrefix: "app-e2e-onboarding", port: host.port });
try { try {
const config = (await client.getDaemonConfig()).config; return (await client.getDaemonConfig()).config.mcp.injectIntoAgents !== false;
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 { } finally {
await client.close(); await client.close();
} }
@@ -1,268 +0,0 @@
import { writeFile } from "node:fs/promises";
import { expect, type Locator, type Page } from "@playwright/test";
import {
SYNCED_LOADER_DOT_COUNT,
getSyncedLoaderDotOpacity,
} from "../../../src/components/synced-loader/state";
import { expectComposerVisible } from "./composer";
import { openAgentRoute, seedMockAgentWorkspace, type MockAgentWorkspace } from "./mock-agent";
const HELD_TOOL_CALL_PROMPT = "Hold a running shell tool call for 600000ms.";
export function workingLoader(page: Page): Locator {
return page.getByTestId("synced-loader").filter({ visible: true });
}
function loaderDots(page: Page): Locator {
return page.getByTestId("synced-loader-dot").filter({ visible: true });
}
export function statusRings(page: Page): Locator {
return page.getByTestId("status-ring").filter({ visible: true });
}
export function runningToolCall(page: Page): Locator {
return page.getByTestId("tool-call-badge").last();
}
/**
* Opens an agent whose turn is one running tool call and nothing else: the six-dot loader, the
* tool-call label shimmer and the status rings are all on screen, and nothing streams.
*/
export async function openQuietRunningTurn(page: Page): Promise<MockAgentWorkspace> {
const agent = await seedMockAgentWorkspace({
repoPrefix: "running-indicators-",
title: "Running indicators",
});
try {
await openAgentRoute(page, { workspaceId: agent.workspaceId, agentId: agent.agentId });
await expectComposerVisible(page);
await agent.client.sendAgentMessage(agent.agentId, HELD_TOOL_CALL_PROMPT);
await expect(workingLoader(page)).toBeVisible({ timeout: 30_000 });
await expect(runningToolCall(page)).toBeVisible();
await expect(statusRings(page).first()).toBeVisible();
// Park the pointer on empty chat so no hover state repaints during a measurement.
await page.mouse.move(900, 300);
return agent;
} catch (error) {
await agent.cleanup();
throw error;
}
}
/**
* Opens an idle chat while an agent runs in another workspace: the only thing moving on screen is
* the running workspace's status ring in the sidebar.
*/
export async function openIdleChatBesideRunningAgent(page: Page): Promise<{
cleanup(): Promise<void>;
}> {
const running = await seedMockAgentWorkspace({
repoPrefix: "running-beside-",
title: "Running beside",
initialPrompt: HELD_TOOL_CALL_PROMPT,
});
try {
const idle = await seedMockAgentWorkspace({ repoPrefix: "idle-chat-", title: "Idle chat" });
const cleanup = async () => {
await idle.cleanup();
await running.cleanup();
};
try {
await openAgentRoute(page, { workspaceId: idle.workspaceId, agentId: idle.agentId });
await expectComposerVisible(page);
await expect(statusRings(page).first()).toBeVisible({ timeout: 30_000 });
await expect(workingLoader(page)).toHaveCount(0);
await page.mouse.move(900, 300);
return { cleanup };
} catch (error) {
await cleanup();
throw error;
}
} catch (error) {
await running.cleanup().catch(() => undefined);
throw error;
}
}
/** Every angle the first visible status ring's quarter is seen at over the window, in degrees. */
export async function recordRingAngles(page: Page, windowMs: number): Promise<number[]> {
return statusRings(page)
.first()
.evaluate(
(ring, sampleWindowMs) =>
new Promise<number[]>((resolve, reject) => {
const turning = document
.getAnimations()
.map((animation) => animation.effect)
.filter((effect): effect is KeyframeEffect => effect instanceof KeyframeEffect)
.find((effect) => effect.target && ring.contains(effect.target));
const quarter = turning?.target;
if (!quarter) {
reject(new Error("The status ring is not turning"));
return;
}
const angles = new Set<number>();
const startedAt = performance.now();
const sample = () => {
const { a, b } = new DOMMatrixReadOnly(getComputedStyle(quarter).transform);
const degrees = (Math.atan2(b, a) * 180) / Math.PI;
angles.add(Math.round(((degrees + 360) % 360) * 100) / 100);
if (performance.now() - startedAt >= sampleWindowMs) {
resolve([...angles].sort((first, second) => first - second));
return;
}
requestAnimationFrame(sample);
};
sample();
}),
windowMs,
);
}
/** The loader's current step, or null while the dots are between two readable states. */
export async function readLoaderStep(page: Page): Promise<number | null> {
const opacities = await loaderDots(page).evaluateAll((dots) =>
dots.map((dot) => Number.parseFloat(getComputedStyle(dot).opacity)),
);
if (opacities.length !== SYNCED_LOADER_DOT_COUNT) {
throw new Error(`Expected ${SYNCED_LOADER_DOT_COUNT} loader dots, found ${opacities.length}`);
}
for (let step = 0; step < SYNCED_LOADER_DOT_COUNT; step += 1) {
const matches = opacities.every(
(opacity, dot) => Math.abs(opacity - getSyncedLoaderDotOpacity(step, dot)) < 0.005,
);
if (matches) {
return step;
}
}
return null;
}
export interface LoaderStepChange {
step: number;
atMs: number;
}
/** Every step change the loader shows over the window, timestamped on the page's clock. */
export async function recordLoaderStepChanges(
page: Page,
windowMs: number,
): Promise<LoaderStepChange[]> {
const states = Array.from({ length: SYNCED_LOADER_DOT_COUNT }, (_, step) =>
Array.from({ length: SYNCED_LOADER_DOT_COUNT }, (__, dot) =>
getSyncedLoaderDotOpacity(step, dot),
),
);
return loaderDots(page).evaluateAll(
(dots, input) =>
new Promise<LoaderStepChange[]>((resolve) => {
const readStep = () => {
const opacities = dots.map((dot) => Number.parseFloat(getComputedStyle(dot).opacity));
return input.states.findIndex((state) =>
state.every((opacity, dot) => Math.abs(opacity - opacities[dot]) < 0.005),
);
};
const changes: LoaderStepChange[] = [];
const startedAt = performance.now();
const sample = () => {
const atMs = performance.now() - startedAt;
const step = readStep();
if (step !== -1 && step !== changes.at(-1)?.step) {
changes.push({ step, atMs });
}
if (atMs >= input.windowMs) {
resolve(changes);
return;
}
requestAnimationFrame(sample);
};
sample();
}),
{ states, windowMs },
);
}
export interface RunningAnimation {
name: string;
target: string;
durationMs: number;
easing: string;
iterations: number;
properties: string[];
}
/** Every animation the document is currently running, by what it animates. */
export async function readRunningAnimations(page: Page): Promise<RunningAnimation[]> {
return page.evaluate(() => {
const timingKeys = new Set(["offset", "computedOffset", "easing", "composite"]);
const running: RunningAnimation[] = [];
for (const animation of document.getAnimations()) {
const effect = animation.effect;
if (animation.playState !== "running" || !(effect instanceof KeyframeEffect)) {
continue;
}
const properties = new Set<string>();
for (const keyframe of effect.getKeyframes()) {
for (const key of Object.keys(keyframe)) {
if (!timingKeys.has(key)) {
properties.add(key);
}
}
}
const timing = effect.getComputedTiming();
const target = effect.target;
running.push({
name: animation instanceof CSSAnimation ? animation.animationName : "script",
target:
target?.closest("[data-testid]")?.getAttribute("data-testid") ?? target?.tagName ?? "",
durationMs: Number(timing.duration),
easing: String(timing.easing),
iterations: Number(timing.iterations),
properties: [...properties],
});
}
return running;
});
}
/** What is currently animating, by test id. */
export async function readAnimatingTargets(page: Page): Promise<string[]> {
const animations = await readRunningAnimations(page);
return animations.map((animation) => animation.target);
}
/** Freezes every running animation at the same point of its cycle so a frame can be compared. */
export async function freezeAnimationsAt(page: Page, progress: number): Promise<void> {
await page.evaluate(async (cycleProgress) => {
for (const animation of document.getAnimations()) {
const duration = Number(animation.effect?.getComputedTiming().duration);
animation.pause();
animation.currentTime = duration * cycleProgress;
}
await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)));
}, progress);
}
/** Saves one image of the loader for each of its steps, named by step. */
export async function captureLoaderSteps(
page: Page,
pathForStep: (step: number) => string,
): Promise<number[]> {
const loader = workingLoader(page);
const captured = new Set<number>();
for (let attempt = 0; attempt < 200 && captured.size < SYNCED_LOADER_DOT_COUNT; attempt += 1) {
const before = await readLoaderStep(page);
if (before === null || captured.has(before)) {
continue;
}
const image = await loader.screenshot();
// The step can turn over mid-capture; only an image bracketed by one step is that step.
if ((await readLoaderStep(page)) !== before) {
continue;
}
await writeFile(pathForStep(before), image);
captured.add(before);
}
return [...captured].sort((a, b) => a - b);
}
@@ -168,6 +168,11 @@ export interface SeedDaemonClient {
timeout?: number, timeout?: number,
): Promise<{ status: string }>; ): Promise<{ status: string }>;
cancelAgent(agentId: string): Promise<void>; cancelAgent(agentId: string): Promise<void>;
respondToPermission(
agentId: string,
requestId: string,
response: { behavior: "allow" },
): Promise<void>;
sendAgentMessage( sendAgentMessage(
agentId: string, agentId: string,
text: string, text: string,
@@ -182,9 +187,9 @@ export interface SeedDaemonClient {
): Promise<{ status: string; final?: { lastError?: string | null } | null }>; ): Promise<{ status: string; final?: { lastError?: string | null } | null }>;
archiveAgent(agentId: string): Promise<{ archivedAt: string }>; archiveAgent(agentId: string): Promise<{ archivedAt: string }>;
refreshAgent(agentId: string): Promise<unknown>; refreshAgent(agentId: string): Promise<unknown>;
fetchAgent(options: { fetchAgent(options: { agentId: string }): Promise<{
agentId: string; agent: { id: string; archivedAt?: string | null; pendingPermissions: Array<{ id: string }> };
}): Promise<{ agent: { id: string; archivedAt?: string | null } } | null>; } | null>;
getLastServerInfoMessage(): { getLastServerInfoMessage(): {
features?: { features?: {
projectAdd?: boolean; 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> { export async function expectHostInjectMcpCard(page: Page): Promise<void> {
const card = page.getByTestId("host-page-inject-mcp-card"); const card = page.getByTestId("host-page-inject-mcp-card");
await expect(card).toBeVisible(); await expect(card).toBeVisible();
await expect(card.getByRole("switch", { name: "Enable tools" })).toBeVisible(); await expect(card.getByRole("switch", { name: "Inject Paseo tools" })).toBeVisible();
} }
function idleAgentReleaseSwitch(page: Page) { function idleAgentReleaseSwitch(page: Page) {
@@ -1,157 +0,0 @@
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,7 +9,6 @@ interface SessionMessage {
interface TimelineSubscriptionWaitOptions { interface TimelineSubscriptionWaitOptions {
timeout?: number; timeout?: number;
match?: "exact" | "includes";
} }
function readSessionMessage(message: WebSocketMessage): SessionMessage | null { function readSessionMessage(message: WebSocketMessage): SessionMessage | null {
@@ -57,7 +56,7 @@ export function observeTimelineSubscriptions(page: Page) {
.poll(() => acknowledgedAgentIds?.slice().sort() ?? null, { .poll(() => acknowledgedAgentIds?.slice().sort() ?? null, {
timeout: options.timeout ?? 15_000, timeout: options.timeout ?? 15_000,
}) })
.toEqual(options.match === "includes" ? expect.arrayContaining(expected) : expected); .toEqual(expected);
}, },
}; };
} }
@@ -204,25 +204,25 @@ export async function readSidebarListLayout(page: Page): Promise<SidebarListLayo
}); });
} }
/** Records the last row's positions until the archive toast finishes fading out. */ /**
export function recordLastRowDuringToastExpiry(page: Page): Promise<number[]> { * 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[]> {
return page.getByTestId(SIDEBAR_LIST).evaluate( return page.getByTestId(SIDEBAR_LIST).evaluate(
(element) => (element, count) =>
new Promise<number[]>((resolve) => { new Promise<number[]>((resolve) => {
const bottoms: number[] = []; const bottoms: number[] = [];
const sample = () => { const sample = () => {
const rows = element.querySelectorAll<HTMLElement>( const rows = element.querySelectorAll<HTMLElement>(
'[data-testid^="sidebar-workspace-row-"],[data-testid^="sidebar-project-row-"]', '[data-testid^="sidebar-workspace-row-"],[data-testid^="sidebar-project-row-"]',
); );
const bottom = Math.max(...Array.from(rows, (row) => row.getBoundingClientRect().bottom)); bottoms.push(Math.max(...Array.from(rows, (row) => row.getBoundingClientRect().bottom)));
if (bottom !== bottoms.at(-1)) bottoms.push(bottom); if (bottoms.length >= count) resolve(bottoms);
if (document.querySelector('[data-testid="workspace-archived-toast"]')) { else requestAnimationFrame(sample);
requestAnimationFrame(sample);
} else {
resolve(bottoms);
}
}; };
sample(); requestAnimationFrame(sample);
}), }),
frameCount,
); );
} }
@@ -180,7 +180,9 @@ public final class PaseoHardwareKeyboardWindow: UIWindow {
} }
public override var keyCommands: [UIKeyCommand]? { public override var keyCommands: [UIKeyCommand]? {
var commands = super.keyCommands ?? [] var commands = super.keyCommands ?? []
if isHardwareSubmitEnabled && !isPlainReturnClaimed && !isComposingText() { if isHardwareSubmitEnabled && !isPlainReturnClaimed && !isComposingText()
&& UIDevice.current.userInterfaceIdiom == .pad
{
commands.append(makeSubmitCommand()) commands.append(makeSubmitCommand())
} }
if !isComposingText() { if !isComposingText() {
+15
View File
@@ -0,0 +1,15 @@
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
@@ -0,0 +1,165 @@
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
@@ -0,0 +1,128 @@
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,19 +954,6 @@ it("keeps table cell pipes escaped in text/plain table syntax and literal in tex
expect(content?.html).toContain("<td>Value | detail</td>"); 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", () => { it("copies a workspace image path instead of its temporary display URL", () => {
const message = mountFixture(); const message = mountFixture();
const sources = JSON.stringify({ "blob:preview": "assets/chart.png" }); const sources = JSON.stringify({ "blob:preview": "assets/chart.png" });
@@ -69,13 +69,12 @@ function createTurndown(flavor: "markdown" | "plain"): TurndownService {
}); });
turndown.use(gfm); turndown.use(gfm);
// text/plain still carries tables as GFM syntax, so a cell's pipe stays escaped there. // 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", { turndown.addRule("escapedGfmTableCell", {
filter: ["th", "td"], filter: ["th", "td"],
replacement: (content, node) => { replacement: (content, node) => {
const index = node.parentNode ? Array.from(node.parentNode.childNodes).indexOf(node) : 0; const index = node.parentNode ? Array.from(node.parentNode.childNodes).indexOf(node) : 0;
const prefix = index === 0 ? "| " : " "; const prefix = index === 0 ? "| " : " ";
return `${prefix}${content.replace(/\|/g, "\\|").replace(/ *\n/g, "<br>")} |`; return `${prefix}${content.replace(/\|/g, "\\|")} |`;
}, },
}); });
// A link Paseo recognized pastes as the text the reply showed. Rich paste keeps it as a // A link Paseo recognized pastes as the text the reply showed. Rich paste keeps it as a
+2
View File
@@ -108,6 +108,8 @@ export type UserComposerAttachment =
| { kind: "file"; attachment: UploadedFileAttachment } | { kind: "file"; attachment: UploadedFileAttachment }
| WorkspaceFileComposerAttachment | WorkspaceFileComposerAttachment
| PluginResourceComposerAttachment | 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_issue"; item: ForgeSearchItem }
| { kind: "forge_change_request"; item: ForgeSearchItem } | { kind: "forge_change_request"; item: ForgeSearchItem }
// COMPAT(githubAttachmentKinds): legacy persisted attachment kinds retained // COMPAT(githubAttachmentKinds): legacy persisted attachment kinds retained
@@ -131,13 +131,18 @@ 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. */ /** Square image preview pill body. */
export function AttachmentThumbnail({ metadata }: { metadata: AttachmentMetadata }) { export function AttachmentThumbnail({ metadata }: { metadata: AttachmentMetadata }) {
const preview = useAttachmentPreviewUrl(metadata); const preview = useAttachmentPreviewUrl(metadata);
const uri = preview.status === "ready" ? preview.url : null; const uri = preview.status === "ready" ? preview.url : null;
const source = useMemo(() => (uri ? { uri } : null), [uri]); const source = useMemo(() => (uri ? { uri } : null), [uri]);
if (!source) { if (!source) {
return <View style={styles.thumbnailPlaceholder} />; return <AttachmentThumbnailPlaceholder />;
} }
return <Image source={source} style={styles.thumbnail} />; return <Image source={source} style={styles.thumbnail} />;
} }
@@ -1,79 +0,0 @@
import { Animated } from "react-native";
import { describe, expect, test } from "vitest";
import { createIndicatorClock } from "./clock";
const PERIOD_MS = 900;
const STEPS = 27;
const STEP_MS = PERIOD_MS / STEPS;
// Animated only pushes a derived value to a mounted view, so this asks the node for it the way the
// view's props do.
function read(node: object): number {
if (!("__getValue" in node) || typeof node.__getValue !== "function") {
throw new Error("Not an Animated node");
}
return Number(node.__getValue());
}
// Where the cycle is at each of the given clock readings.
function positionsAt(elapsed: number[], steps?: number): number[] {
const elapsedMs = new Animated.Value(0);
const position = createIndicatorClock(elapsedMs).cycle(PERIOD_MS, steps);
return elapsed.map((ms) => {
elapsedMs.setValue(ms);
return Math.round(read(position) * 1e6) / 1e6;
});
}
// A display's frames, as the native driver's clock counts them: whole frames from zero.
function frames(hz: number, count: number): number[] {
return Array.from({ length: count }, (_, frame) => (frame * 1000) / hz);
}
describe("indicator clock", () => {
test("a cycle without steps advances with every frame", () => {
expect(positionsAt([0, 16, 450, 899, 900, 916])).toEqual([0, 16, 450, 899, 0, 16]);
});
test("a stepped cycle only ever sits on one of its even steps", () => {
const positions = positionsAt(frames(60, 3 * 54), STEPS);
expect(new Set(positions).size).toBe(STEPS);
for (const position of positions) {
expect(position / STEP_MS).toBeCloseTo(Math.round(position / STEP_MS), 4);
expect(position).toBeLessThan(PERIOD_MS);
}
});
test.each([60, 90, 120])("at %i Hz every step is held for the same number of frames", (hz) => {
const positions = positionsAt(frames(hz, hz * 3), STEPS);
const heldFor: number[] = [];
let run = 1;
for (let frame = 1; frame < positions.length; frame += 1) {
if (positions[frame] === positions[frame - 1]) {
run += 1;
} else {
heldFor.push(run);
run = 1;
}
}
// The first step is cut short by the lead; every step after it is whole.
expect(new Set(heldFor.slice(1))).toEqual(new Set([hz / 30]));
});
test("a frame that lands a hair early or late shows the same step", () => {
const onTime = positionsAt(frames(60, 120), STEPS);
const early = positionsAt(
frames(60, 120).map((ms) => ms - 0.2),
STEPS,
).slice(1);
const late = positionsAt(
frames(60, 120).map((ms) => ms + 0.2),
STEPS,
);
expect(early).toEqual(onTime.slice(1));
expect(late).toEqual(onTime);
});
});
@@ -1,77 +0,0 @@
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 };
// The clock starts on a frame and advances a whole frame at a time, so at 60, 90 and 120 Hz a step
// that is a whole number of frames long would turn over exactly on a frame, and rounding would
// decide frame by frame which side of the step it fell on. Turning each step over this fraction of
// a step early puts the turn between two frames at all three rates.
const STEP_LEAD = 1 / 8;
/**
* 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.
*
* With `steps`, the position holds at each of that many even steps instead of advancing every
* frame. A view bound to a held position is not redrawn until the step turns over.
*/
cycle(periodMs: number, steps?: number): Animated.AnimatedInterpolation<number>;
/** Runs the clock until the returned function is called. It restarts from zero when idle. */
run(): () => void;
}
export function createIndicatorClock(
elapsedMs = new Animated.Value(0, { useNativeDriver: true }),
): IndicatorClock {
let runners = 0;
let ticking: Animated.CompositeAnimation | null = null;
return {
cycle(periodMs, steps) {
if (!steps) {
return Animated.modulo(elapsedMs, periodMs);
}
const stepMs = periodMs / steps;
const position = Animated.modulo(Animated.add(elapsedMs, stepMs * STEP_LEAD), periodMs);
return Animated.subtract(position, Animated.modulo(position, stepMs));
},
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]);
}
@@ -1,49 +0,0 @@
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;
}
@@ -1,50 +0,0 @@
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;
}
@@ -1,140 +0,0 @@
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>
);
}
@@ -1,116 +0,0 @@
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>
);
});
@@ -1,67 +0,0 @@
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,
};
}
@@ -1,48 +0,0 @@
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 });
});
});
@@ -1,62 +0,0 @@
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 };
}
+2 -86
View File
@@ -1,7 +1,5 @@
import { Parser } from "htmlparser2"; import { Parser } from "htmlparser2";
import { fromMarkdown } from "mdast-util-from-markdown"; 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 { decodeString } from "micromark-util-decode-string";
import type { Nodes } from "mdast"; import type { Nodes } from "mdast";
@@ -55,8 +53,6 @@ export function normalizeMarkdownHtml(source: string): string {
} else if ("children" in node) node.children.forEach(protectCode); } else if ("children" in node) node.children.forEach(protectCode);
} }
protectCode(tree); 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)[] = []; const links: (string | undefined)[] = [];
let previousTag: { name: string; end: number } | null = null; let previousTag: { name: string; end: number } | null = null;
const convert = (raw: string, offset: number): string => { const convert = (raw: string, offset: number): string => {
@@ -88,16 +84,7 @@ export function normalizeMarkdownHtml(source: string): string {
: /^\s*$/.test(source.slice(0, offset)); : /^\s*$/.test(source.slice(0, offset));
previousTag = { name, end: offset + raw.length }; previousTag = { name, end: offset + raw.length };
if (EMPHASIS[name]) return EMPHASIS[name]; if (EMPHASIS[name]) return EMPHASIS[name];
const inTable = tableRanges.some(({ start, end }) => offset >= start && offset < end); const boundary = layoutBoundary(name, source, raw, offset, closing, startsAfterBoundary);
const boundary = layoutBoundary(
name,
source,
raw,
offset,
closing,
startsAfterBoundary,
inTable,
);
if (boundary !== null) return boundary; if (boundary !== null) return boundary;
if (name === "a") return markdownAnchor(raw, closing, links); if (name === "a") return markdownAnchor(raw, closing, links);
if (name === "img" && !closing) { if (name === "img" && !closing) {
@@ -180,15 +167,8 @@ function layoutBoundary(
offset: number, offset: number,
closing: boolean, closing: boolean,
startsAfterBoundary: boolean, startsAfterBoundary: boolean,
inTable: boolean,
): string | null { ): string | null {
// Inside GFM table cells, emit ` \u2028 ` so row boundaries stay intact while giving flanking if (name === "br") return closing ? "" : " \n";
// 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 === "summary") return closing ? "**\n\n" : "**";
if (name === "details") if (name === "details")
return (closing ? offset + raw.length === source.length : offset === 0) ? "" : "\n\n"; return (closing ? offset + raw.length === source.length : offset === 0) ? "" : "\n\n";
@@ -197,67 +177,3 @@ function layoutBoundary(
return /^<t[dh]\b/i.test(source.slice(offset + raw.length)) ? " " : ""; return /^<t[dh]\b/i.test(source.slice(offset + raw.length)) ? " " : "";
return null; 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,188 +838,6 @@ describe("GitHub comment HTML normalization", () => {
])("normalizes %s without changing code", (source, expected) => { ])("normalizes %s without changing code", (source, expected) => {
expect(prepareMarkdownSource(source).render()).toBe(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", () => { it("preserves backslashes and decodes entities inside HTML code", () => {
+526 -23
View File
@@ -1,4 +1,3 @@
import { AppearanceText } from "@/appearance/text";
import { useDisclosureHold } from "@/agent-stream/disclosure"; import { useDisclosureHold } from "@/agent-stream/disclosure";
import { MessagePreview, MessageSender } from "@/components/user-message"; import { MessagePreview, MessageSender } from "@/components/user-message";
import { useStableEvent } from "@/hooks/use-stable-event"; import { useStableEvent } from "@/hooks/use-stable-event";
@@ -14,6 +13,7 @@ import {
AttachmentThumbnail, AttachmentThumbnail,
} from "@/components/attachment-pill"; } from "@/components/attachment-pill";
import { MarkdownRenderer } from "@/components/markdown/renderer"; import { MarkdownRenderer } from "@/components/markdown/renderer";
import { useRetainedPanelActive } from "@/components/retained-panel";
import { import {
isRewindableMessage, isRewindableMessage,
RewindMenu, RewindMenu,
@@ -29,7 +29,6 @@ import { useProvidersSnapshot } from "@/hooks/use-providers-snapshot";
import { useRevealedText, type MarkdownPhase } from "@/hooks/use-revealed-text"; import { useRevealedText, type MarkdownPhase } from "@/hooks/use-revealed-text";
import { ICON_SIZE, type Theme } from "@/styles/theme"; import { ICON_SIZE, type Theme } from "@/styles/theme";
import { inlineUnistylesStyle } from "@/styles/unistyles-inline-style"; import { inlineUnistylesStyle } from "@/styles/unistyles-inline-style";
import { LabelShimmer, useLabelMeasurements } from "@/components/label-shimmer";
import { buildToolCallPresentation } from "@/tool-calls/presentation"; import { buildToolCallPresentation } from "@/tool-calls/presentation";
import type { import type {
DaemonUploadedImageAttachment, DaemonUploadedImageAttachment,
@@ -55,6 +54,7 @@ import type {
ToolCallDetail, ToolCallDetail,
} from "@getpaseo/protocol/agent-types"; } from "@getpaseo/protocol/agent-types";
import type { AgentAttachment } from "@getpaseo/protocol/messages"; import type { AgentAttachment } from "@getpaseo/protocol/messages";
import MaskedView from "@react-native-masked-view/masked-view";
import { import {
ArrowRightLeft, ArrowRightLeft,
Check, Check,
@@ -94,6 +94,15 @@ import {
type LayoutChangeEvent, type LayoutChangeEvent,
type TextStyle, type TextStyle,
} from "react-native"; } 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 { StyleSheet, withUnistyles } from "react-native-unistyles";
import { capAssistantMessageForRender, getUtf8ByteLength } from "./assistant-message-render-limit"; import { capAssistantMessageForRender, getUtf8ByteLength } from "./assistant-message-render-limit";
import { getTurnDurationLabel } from "./assistant-turn-footer-label"; import { getTurnDurationLabel } from "./assistant-turn-footer-label";
@@ -144,6 +153,8 @@ function useDisableOuterSpacing(disableOuterSpacing: boolean | undefined) {
return disableOuterSpacing ?? contextValue; 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 ThemedMicVocal = withUnistyles(MicVocal);
const ThemedFileSymlinkIcon = withUnistyles(FileSymlink); const ThemedFileSymlinkIcon = withUnistyles(FileSymlink);
const ThemedTriangleAlertIcon = withUnistyles(TriangleAlertIcon); const ThemedTriangleAlertIcon = withUnistyles(TriangleAlertIcon);
@@ -162,6 +173,17 @@ const mutedForegroundColorMapping = (theme: Theme) => ({
const destructiveColorMapping = (theme: Theme) => ({ color: theme.colors.destructive }); const destructiveColorMapping = (theme: Theme) => ({ color: theme.colors.destructive });
const infoColorMapping = (theme: Theme) => ({ color: theme.colors.palette.blue[300] }); const infoColorMapping = (theme: Theme) => ({ color: theme.colors.palette.blue[300] });
const warningColorMapping = (theme: Theme) => ({ color: theme.colors.palette.amber[500] }); 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; const SCROLL_EDGE_EPSILON = 0.5;
// Font size for stream metadata (timestamps, durations, live elapsed timer). // Font size for stream metadata (timestamps, durations, live elapsed timer).
@@ -169,6 +191,31 @@ const SCROLL_EDGE_EPSILON = 0.5;
export const STREAM_METADATA_FONT_SIZE = 13; export const STREAM_METADATA_FONT_SIZE = 13;
type ScrollAxis = "x" | "y"; 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 { function getWheelEventElementTarget(event: WheelEvent, fallback: HTMLElement): HTMLElement {
const { target } = event; const { target } = event;
if (target instanceof HTMLElement) { if (target instanceof HTMLElement) {
@@ -571,13 +618,9 @@ export const UserMessage = memo(function UserMessage({
</View> </View>
) : null} ) : null}
{hasText ? ( {hasText ? (
<AppearanceText <Text selectable style={userMessageStylesheet.text} dataSet={MESSAGE_TEXT_DATASET}>
selectable
style={userMessageStylesheet.text}
dataSet={MESSAGE_TEXT_DATASET}
>
{message} {message}
</AppearanceText> </Text>
) : null} ) : null}
</MessagePreview> </MessagePreview>
</View> </View>
@@ -1048,6 +1091,14 @@ const expandableBadgeStylesheet = StyleSheet.create((theme) => ({
secondaryLabelActive: { secondaryLabelActive: {
color: theme.colors.foreground, color: theme.colors.foreground,
}, },
shimmerText: {
color: "transparent",
fontSize: theme.fontSize.base,
fontWeight: theme.fontWeight.normal,
},
spacer: {
flex: 1,
},
chevron: { chevron: {
flexShrink: 0, flexShrink: 0,
}, },
@@ -1086,8 +1137,160 @@ const expandableBadgeStylesheet = StyleSheet.create((theme) => ({
detailWrapperBorderless: { detailWrapperBorderless: {
borderWidth: 0, 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({ export const AssistantMessage = memo(function AssistantMessage({
renderFullContent = false, renderFullContent = false,
occurrenceKey, occurrenceKey,
@@ -1681,30 +1884,77 @@ interface ExpandableBadgeProps {
interface ExpandableBadgeSecondaryLabelProps { interface ExpandableBadgeSecondaryLabelProps {
secondaryLabel?: string; secondaryLabel?: string;
secondaryLabelStyle: StyleProp<TextStyle>; secondaryLabelStyle: StyleProp<TextStyle>;
onLayout: ((event: LayoutChangeEvent) => void) | undefined; shouldMeasureWebShimmer: boolean;
onSecondaryLayout: (event: LayoutChangeEvent) => void;
} }
function ExpandableBadgeSecondaryLabel({ function ExpandableBadgeSecondaryLabel({
secondaryLabel, secondaryLabel,
secondaryLabelStyle, secondaryLabelStyle,
onLayout, shouldMeasureWebShimmer,
onSecondaryLayout,
}: ExpandableBadgeSecondaryLabelProps) { }: ExpandableBadgeSecondaryLabelProps) {
if (!secondaryLabel) { if (!secondaryLabel) {
return null; return null;
} }
return ( return (
<Text style={secondaryLabelStyle} numberOfLines={1} onLayout={onLayout}> <Text
style={secondaryLabelStyle}
numberOfLines={1}
onLayout={shouldMeasureWebShimmer ? onSecondaryLayout : undefined}
>
{secondaryLabel} {secondaryLabel}
</Text> </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 { interface ExpandableBadgeLabelRowProps {
label: string; label: string;
labelStyle: StyleProp<TextStyle>; labelStyle: StyleProp<TextStyle>;
secondaryLabel?: string; secondaryLabel?: string;
secondaryLabelStyle: StyleProp<TextStyle>; secondaryLabelStyle: StyleProp<TextStyle>;
isLoading: boolean; 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;
} }
function ExpandableBadgeLabelRow({ function ExpandableBadgeLabelRow({
@@ -1712,26 +1962,56 @@ function ExpandableBadgeLabelRow({
labelStyle, labelStyle,
secondaryLabel, secondaryLabel,
secondaryLabelStyle, secondaryLabelStyle,
isLoading, shouldMeasureWebShimmer,
shouldMeasureNativeShimmer,
isWebShimmer,
isNativeShimmer,
shimmerLabelTextStyle,
shimmerSecondaryTextStyle,
labelRowWidth,
labelRowHeight,
nativeShimmerPeakWidth,
shimmerDuration,
nativeGradientId,
onLabelRowLayout,
onLabelLayout,
onSecondaryLayout,
}: ExpandableBadgeLabelRowProps) { }: ExpandableBadgeLabelRowProps) {
const measuring = useLabelMeasurements(isLoading);
return ( return (
<View style={expandableBadgeStylesheet.labelRow} onLayout={measuring.onRowLayout}> <View
<Text style={labelStyle} numberOfLines={1} onLayout={measuring.onLabelLayout}> style={expandableBadgeStylesheet.labelRow}
onLayout={shouldMeasureNativeShimmer ? onLabelRowLayout : undefined}
>
<Text
style={labelStyle}
numberOfLines={1}
onLayout={shouldMeasureWebShimmer ? onLabelLayout : undefined}
>
{label} {label}
</Text> </Text>
<ExpandableBadgeSecondaryLabel <ExpandableBadgeSecondaryLabel
secondaryLabel={secondaryLabel} secondaryLabel={secondaryLabel}
secondaryLabelStyle={secondaryLabelStyle} secondaryLabelStyle={secondaryLabelStyle}
onLayout={measuring.onSecondaryLayout} shouldMeasureWebShimmer={shouldMeasureWebShimmer}
onSecondaryLayout={onSecondaryLayout}
/> />
{isLoading ? ( {isWebShimmer ? (
<LabelShimmer <ExpandableBadgeWebShimmerOverlay
label={label} label={label}
secondaryLabel={secondaryLabel} secondaryLabel={secondaryLabel}
labelStyle={expandableBadgeStylesheet.label} shimmerLabelTextStyle={shimmerLabelTextStyle}
secondaryLabelStyle={expandableBadgeStylesheet.secondaryLabel} shimmerSecondaryTextStyle={shimmerSecondaryTextStyle}
measurements={measuring.measurements} />
) : null}
{isNativeShimmer ? (
<NativeExpandableBadgeShimmer
label={label}
secondaryLabel={secondaryLabel}
rowWidth={labelRowWidth}
rowHeight={labelRowHeight}
peakWidth={nativeShimmerPeakWidth}
durationSeconds={shimmerDuration}
gradientId={nativeGradientId}
/> />
) : null} ) : null}
</View> </View>
@@ -1806,6 +2086,55 @@ function renderExpandableBadgeIconSlot({
return iconNode; 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: { function useDetailWheelPropagationBlocker(input: {
detailWrapperRef: React.RefObject<View | null>; detailWrapperRef: React.RefObject<View | null>;
enabled: boolean; enabled: boolean;
@@ -1832,6 +2161,33 @@ function useDetailWheelPropagationBlocker(input: {
}, [detailWrapperRef, enabled]); }, [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({ export const ExpandableBadge = memo(function ExpandableBadge({
label, label,
style, style,
@@ -1875,11 +2231,126 @@ export const ExpandableBadge = memo(function ExpandableBadge({
const handleOpenFileHoverIn = useCallback(() => setIsOpenFileHovered(true), []); const handleOpenFileHoverIn = useCallback(() => setIsOpenFileHovered(true), []);
const handleOpenFileHoverOut = useCallback(() => setIsOpenFileHovered(false), []); 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({ useDetailWheelPropagationBlocker({
detailWrapperRef, detailWrapperRef,
enabled: !isNative && isExpanded && hasDetailContent, 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( const containerStyle = useMemo(
() => [ () => [
expandableBadgeStylesheet.container, expandableBadgeStylesheet.container,
@@ -1937,6 +2408,25 @@ export const ExpandableBadge = memo(function ExpandableBadge({
[isActive], [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( const chevronStyle = useMemo(
() => [ () => [
expandableBadgeStylesheet.chevron, expandableBadgeStylesheet.chevron,
@@ -1985,7 +2475,20 @@ export const ExpandableBadge = memo(function ExpandableBadge({
labelStyle={labelStyle} labelStyle={labelStyle}
secondaryLabel={secondaryLabel} secondaryLabel={secondaryLabel}
secondaryLabelStyle={secondaryLabelStyle} secondaryLabelStyle={secondaryLabelStyle}
isLoading={isLoading} 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}
/> />
</Pressable> </Pressable>
{onOpenFile && isHovered ? ( {onOpenFile && isHovered ? (
@@ -2,19 +2,12 @@ import { useCallback, useMemo, useState, type ReactNode } from "react";
import { View } from "react-native"; import { View } from "react-native";
import { isWeb } from "@/constants/platform"; import { isWeb } from "@/constants/platform";
import { SettingsRowChildren } from "./row-children"; import { SettingsRowChildren } from "./row-children";
import { SettingsRowHeader, type SettingsRowHintStatus } from "./row-header"; import { SettingsRowHeader } from "./row-header";
interface SettingsCollapsibleRowProps { interface SettingsCollapsibleRowProps {
label: string; 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. */ /** A short status shown before the chevron, so the row says something while collapsed. */
summary?: string; 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; defaultExpanded?: boolean;
testID?: string; testID?: string;
/** The rows revealed underneath, separated like the rows of a `SettingsCard` and laid out as nested rows. */ /** The rows revealed underneath, separated like the rows of a `SettingsCard` and laid out as nested rows. */
@@ -28,11 +21,7 @@ interface SettingsCollapsibleRowProps {
*/ */
export function SettingsCollapsibleRow({ export function SettingsCollapsibleRow({
label, label,
hint,
hintStatus,
summary, summary,
control,
accessibilityLabel,
defaultExpanded = false, defaultExpanded = false,
testID, testID,
children, children,
@@ -50,11 +39,7 @@ export function SettingsCollapsibleRow({
<View testID={testID}> <View testID={testID}>
<SettingsRowHeader <SettingsRowHeader
label={label} label={label}
hint={hint}
hintStatus={hintStatus}
summary={summary} summary={summary}
control={control}
accessibilityLabel={accessibilityLabel}
onPress={toggle} onPress={toggle}
expanded={expanded} expanded={expanded}
accessibilityState={accessibilityState} accessibilityState={accessibilityState}
@@ -555,7 +555,6 @@ function ProjectMenuItems({
}) { }) {
const { t } = useTranslation(); const { t } = useTranslation();
const toast = useToast(); const toast = useToast();
const localDaemonServerId = useLocalDaemonServerId();
const handleOpenProjectSettings = useCallback(() => { const handleOpenProjectSettings = useCallback(() => {
if (!settingsTarget) return; if (!settingsTarget) return;
router.navigate(buildProjectSettingsRoute(settingsTarget.serverId, settingsTarget.projectId)); router.navigate(buildProjectSettingsRoute(settingsTarget.serverId, settingsTarget.projectId));
@@ -595,7 +594,6 @@ function ProjectMenuItems({
</ProjectMenuItem> </ProjectMenuItem>
) : null} ) : null}
<OpenInFileManagerMenuItem <OpenInFileManagerMenuItem
serverId={localDaemonServerId}
surface={surface} surface={surface}
path={projectPath} path={projectPath}
testID={`sidebar-project-menu-open-folder-${projectViewKey}`} testID={`sidebar-project-menu-open-folder-${projectViewKey}`}
@@ -1287,6 +1285,7 @@ function WorkspaceRowWithMenu({
const toast = useToast(); const toast = useToast();
const [isHidingWorkspace, setIsHidingWorkspace] = useState(false); const [isHidingWorkspace, setIsHidingWorkspace] = useState(false);
const rename = useSidebarWorkspaceRename(workspace); const rename = useSidebarWorkspaceRename(workspace);
const isArchiving = workspace.archivingAt !== null || isHidingWorkspace;
const redirectAfterArchive = useCallback(() => { const redirectAfterArchive = useCallback(() => {
redirectIfArchivingActiveWorkspace({ redirectIfArchivingActiveWorkspace({
serverId: workspace.serverId, serverId: workspace.serverId,
@@ -1305,8 +1304,6 @@ function WorkspaceRowWithMenu({
onArchiveStarted: redirectAfterArchive, onArchiveStarted: redirectAfterArchive,
onSetHiding: setIsHidingWorkspace, onSetHiding: setIsHidingWorkspace,
}); });
const isArchiving =
workspace.archivingAt !== null || isHidingWorkspace || archiveController.isConfirming;
const handleArchive = useCallback(() => { const handleArchive = useCallback(() => {
if (isArchiving) { if (isArchiving) {
@@ -720,6 +720,7 @@ function StatusWorkspaceRowWithMenu({
const toast = useToast(); const toast = useToast();
const [isHidingWorkspace, setIsHidingWorkspace] = useState(false); const [isHidingWorkspace, setIsHidingWorkspace] = useState(false);
const rename = useSidebarWorkspaceRename(workspace); const rename = useSidebarWorkspaceRename(workspace);
const isArchiving = workspace.archivingAt !== null || isHidingWorkspace;
const redirectAfterArchive = useCallback(() => { const redirectAfterArchive = useCallback(() => {
redirectIfArchivingActiveWorkspace({ redirectIfArchivingActiveWorkspace({
@@ -741,8 +742,6 @@ function StatusWorkspaceRowWithMenu({
onArchiveStarted: redirectAfterArchive, onArchiveStarted: redirectAfterArchive,
onSetHiding: setIsHidingWorkspace, onSetHiding: setIsHidingWorkspace,
}); });
const isArchiving =
workspace.archivingAt !== null || isHidingWorkspace || archiveController.isConfirming;
const handleArchive = useCallback(() => { const handleArchive = useCallback(() => {
if (isArchiving) return; if (isArchiving) return;
@@ -268,7 +268,6 @@ function SidebarWorkspaceMenuItems({
</DropdownMenuSubTrigger> </DropdownMenuSubTrigger>
) : null} ) : null}
<OpenInFileManagerMenuItem <OpenInFileManagerMenuItem
serverId={serverId}
surface={surface} surface={surface}
path={openInFileManagerPath} path={openInFileManagerPath}
testID={`sidebar-workspace-menu-open-folder-${workspaceKey}`} testID={`sidebar-workspace-menu-open-folder-${workspaceKey}`}
@@ -0,0 +1,74 @@
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;
}
@@ -0,0 +1,35 @@
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 }) { export function StatusRingFrame({ backdrop, children }: StatusRingProps & { children: ReactNode }) {
return ( return (
<View style={[styles.frame, getBackdropStyle(backdrop)]} testID="status-ring"> <View style={[styles.frame, getBackdropStyle(backdrop)]}>
<View style={styles.track} /> <View style={styles.track} />
{children} {children}
<View style={styles.centerDot} /> <View style={styles.centerDot} />
@@ -60,9 +60,10 @@ function getBackdropStyle(backdrop: SurfaceBackdrop | null | undefined) {
} }
// The rotating quarter's geometry, deliberately plain React Native rather than Unistyles: on // The rotating quarter's geometry, deliberately plain React Native rather than Unistyles: on
// native this style lands on an `Animated.View` the native animation driver writes to, and a // native this style lands on a Reanimated `Animated.View`, and applying a theme-tracked style to
// theme-tracked style on the same node gives it two writers. See docs/unistyles.md. The colour it // one crashes when the theme changes — Unistyles and Reanimated both mutate the same native node.
// needs lives on `styles.arc`, one level in, on a view nothing animates. // See docs/unistyles.md. The colour it needs lives on `styles.arc`, one level in, on a view
// Reanimated never touches.
export const rotatorStyles = RNStyleSheet.create({ export const rotatorStyles = RNStyleSheet.create({
rotator: { rotator: {
position: "absolute", position: "absolute",
@@ -26,16 +26,16 @@ 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_TRACK_OPACITY = 0.3;
export const STATUS_RING_HEAD_OPACITY = 0.9; export const STATUS_RING_HEAD_OPACITY = 0.9;
// One period for every ring in the app. Each platform runs the rings off one clock that does not // One period for every ring in the app. Each platform owns one mount-independent timeline: web
// depend on when a ring mounted, so a row that appears mid-flight lands in step with the rings // animations share an absolute document-timeline start, while native publishes this wall-clock
// already turning. // phase from one UI-thread clock. A row that appears mid-flight therefore lands in step with the
// rings already turning.
export const STATUS_RING_PERIOD_MS = 900; export const STATUS_RING_PERIOD_MS = 900;
// The quarter takes thirty positions a second, not one per display refresh. A window is redrawn export function getStatusRingRotation(nowMs: number): number {
// every time the ring moves, so a ring that moves with the display holds the whole window at the "worklet";
// display's rate for as long as an agent runs. Each position is one the smooth turn passes through, return ((nowMs % STATUS_RING_PERIOD_MS) / STATUS_RING_PERIOD_MS) * 360;
// 1.2 px further along a 12 px ring. }
export const STATUS_RING_STEPS = 27;
/** /**
* Re-anchors a corner status dot's offset for the ring that replaces it. * Re-anchors a corner status dot's offset for the ring that replaces it.
@@ -1,31 +1,30 @@
import { memo } from "react"; import { memo } from "react";
import { Animated, View } from "react-native"; import { View } from "react-native";
import { useIndicatorMotion } from "@/components/indicator-motion"; import Animated, { useAnimatedStyle } from "react-native-reanimated";
import { sharedIndicatorClock, useRunningClock } from "@/components/indicator-motion/clock";
import { import {
StatusRingFrame, StatusRingFrame,
type StatusRingProps, type StatusRingProps,
rotatorStyles, rotatorStyles,
styles, styles,
} from "@/components/status-ring/frame"; } from "@/components/status-ring/frame";
import { STATUS_RING_PERIOD_MS, STATUS_RING_STEPS } from "@/components/status-ring/geometry"; import { useStatusRingRotation } from "@/components/status-ring/clock";
// One rotation for every ring in the app, so a row that appears mid-flight lands in step with the /**
// rings already turning. * Native running indicator. The rotation is published by one shared UI-thread clock rather than
const rotation = sharedIndicatorClock.cycle(STATUS_RING_PERIOD_MS, STATUS_RING_STEPS).interpolate({ * per-instance timing, so a ring that mounts mid-flight is already in phase — see `clock.ts`.
inputRange: [0, STATUS_RING_PERIOD_MS], *
outputRange: ["0deg", "360deg"], * 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).
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) { export const StatusRing = memo(function StatusRing({ backdrop }: StatusRingProps) {
const moving = useIndicatorMotion(); const rotation = useStatusRingRotation();
useRunningClock(sharedIndicatorClock, moving); const rotatorStyle = useAnimatedStyle(() => ({
transform: [{ rotate: `${rotation.value}deg` }],
}));
return ( return (
<StatusRingFrame backdrop={backdrop}> <StatusRingFrame backdrop={backdrop}>
<Animated.View style={[rotatorStyles.rotator, moving && turning]}> <Animated.View style={[rotatorStyles.rotator, rotatorStyle]}>
<View style={styles.arc} /> <View style={styles.arc} />
</Animated.View> </Animated.View>
</StatusRingFrame> </StatusRingFrame>
@@ -1,30 +1,20 @@
import { memo } from "react"; import { memo } from "react";
import { View } from "react-native"; import { View } from "react-native";
import { useIndicatorMotion } from "@/components/indicator-motion";
import { type IndicatorLoop, useIndicatorLoop } from "@/components/indicator-motion/loop.web";
import { import {
StatusRingFrame, StatusRingFrame,
type StatusRingProps, type StatusRingProps,
rotatorStyles, rotatorStyles,
styles, styles,
} from "@/components/status-ring/frame"; } from "@/components/status-ring/frame";
import { STATUS_RING_PERIOD_MS, STATUS_RING_STEPS } from "@/components/status-ring/geometry"; import { useStatusRingAnimationRef } from "@/components/status-ring/clock.web";
// 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. * Web running indicator. A sidebar full of agents can hold dozens of these at once, so the browser
const TURNING: IndicatorLoop = { * drives the rotation from one absolute document-timeline epoch rather than from mount time — see
keyframes: [ * `clock.web.ts`.
{ transform: "rotate(0deg)", easing: `steps(${STATUS_RING_STEPS})` }, */
{ 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) { export const StatusRing = memo(function StatusRing({ backdrop }: StatusRingProps) {
const moving = useIndicatorMotion(); const rotatorRef = useStatusRingAnimationRef();
const rotatorRef = useIndicatorLoop(moving ? TURNING : null);
return ( return (
<StatusRingFrame backdrop={backdrop}> <StatusRingFrame backdrop={backdrop}>
@@ -1,5 +1,5 @@
import { describe, expect, test } from "vitest"; import { describe, expect, test } from "vitest";
import { getSyncedLoaderDotOpacity, getSyncedLoaderStep } from "./state"; import { getSyncedLoaderDotOpacity, getSyncedLoaderStep } from "./synced-loader-state";
describe("synced loader state", () => { describe("synced loader state", () => {
test("advances through six wall-clock-aligned steps every 950 milliseconds", () => { test("advances through six wall-clock-aligned steps every 950 milliseconds", () => {
@@ -1,4 +1,4 @@
export const SYNCED_LOADER_DURATION_MS = 950; const SYNCED_LOADER_DURATION_MS = 950;
export const SYNCED_LOADER_DOT_COUNT = 6; export const SYNCED_LOADER_DOT_COUNT = 6;
const SYNCED_LOADER_OPACITY_STATES = [ const SYNCED_LOADER_OPACITY_STATES = [
@@ -10,22 +10,13 @@ const SYNCED_LOADER_OPACITY_STATES = [
[0, 0, 1, 0.34, 0.78, 0.56], [0, 0, 1, 0.34, 0.78, 0.56],
] as const; ] 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 { export function getSyncedLoaderStep(nowMs: number): number {
"worklet";
const elapsedMs = nowMs % SYNCED_LOADER_DURATION_MS; const elapsedMs = nowMs % SYNCED_LOADER_DURATION_MS;
return Math.floor((elapsedMs * SYNCED_LOADER_DOT_COUNT) / 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 { export function getSyncedLoaderDotOpacity(step: number, dot: number): number {
"worklet";
return SYNCED_LOADER_OPACITY_STATES[step]?.[dot] ?? 0; return SYNCED_LOADER_OPACITY_STATES[step]?.[dot] ?? 0;
} }
@@ -0,0 +1,184 @@
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} />;
}
@@ -1,58 +0,0 @@
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>
);
}
@@ -1,55 +0,0 @@
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" />;
}
@@ -1,43 +0,0 @@
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,93 +0,0 @@
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]);
});
});
@@ -1,42 +0,0 @@
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;
}
};
},
};
}
+3 -4
View File
@@ -36,9 +36,8 @@ export function measureElement(element: View): Promise<Rect> {
* there is more room above. Both conditions matter: flipping into a side that is equally * there is more room above. Both conditions matter: flipping into a side that is equally
* cramped just moves the clipping, so a surface taller than the whole viewport stays put. * cramped just moves the clipping, so a surface taller than the whole viewport stays put.
* *
* Horizontal flipping is opt-in. Hover cards and submenu flyouts use it; a flyout chooses its * Horizontal flipping is opt-in for hover cards. Submenus choose their direction up front so
* side once, when it opens, so it does not move out from under the pointer travelling toward it * they do not move out from under the pointer travelling toward them.
* (see `useAnchoredPosition`).
*/ */
function flipPlacement(input: { function flipPlacement(input: {
placement: Placement; placement: Placement;
@@ -157,7 +156,7 @@ export function computePosition({
placement: Placement; placement: Placement;
alignment: Alignment; alignment: Alignment;
offset: number; offset: number;
/** Lets a left or right placement open on the other side when its own has no room. */ /** Hover cards can choose either side; submenu direction is owned by the menu. */
flipHorizontal?: boolean; flipHorizontal?: boolean;
}): { x: number; y: number; actualPlacement: Placement } { }): { x: number; y: number; actualPlacement: Placement } {
const actualPlacement = flipPlacement({ const actualPlacement = flipPlacement({
@@ -35,10 +35,7 @@ export type {
MenuItemProps as DropdownMenuItemProps, MenuItemProps as DropdownMenuItemProps,
} from "@/components/ui/menu"; } from "@/components/ui/menu";
export type { MenuPageDefinition } from "@/components/ui/menu"; export type { MenuPageDefinition } from "@/components/ui/menu";
export { export { MenuSubTrigger as DropdownMenuSubTrigger } from "@/components/ui/menu";
MenuSubTrigger as DropdownMenuSubTrigger,
useMenuSubTrigger as useDropdownMenuSubTrigger,
} from "@/components/ui/menu";
export function DropdownMenuContent(props: MenuSurfaceProps): ReactElement | null { export function DropdownMenuContent(props: MenuSurfaceProps): ReactElement | null {
return <MenuSurface {...props} />; return <MenuSurface {...props} />;
+1 -1
View File
@@ -17,7 +17,7 @@ export {
type MenuPageDefinition, type MenuPageDefinition,
type MenuSurfaceProps, type MenuSurfaceProps,
} from "./menu-surface"; } from "./menu-surface";
export { MenuSubTrigger, useMenuSubTrigger, type MenuSubTriggerBinding } from "./menu-sub"; export { MenuSubTrigger } from "./menu-sub";
export { export {
MenuCheckboxItem, MenuCheckboxItem,
MenuHint, MenuHint,
@@ -192,61 +192,3 @@ describe("submenu flyout on a touch screen", () => {
expect(document.querySelector('[data-testid="show-option"]')).not.toBeNull(); expect(document.querySelector('[data-testid="show-option"]')).not.toBeNull();
}); });
}); });
/**
* A flyout overlaps its parent by a few points (`SUBMENU_OVERLAP`, plus the surface border on the
* left side). It must stop short of the 13pt inset where the parent's labels start.
*/
const MAX_OVERLAP = 12;
/** Past the hover-open delay and the surface's first placement. */
const FLYOUT_PLACED_MS = 400;
const AT_RIGHT_EDGE = { position: "absolute", top: 40, right: 8 } as const;
const AWAY_FROM_EDGE = { position: "absolute", top: 40, left: 40 } as const;
function mountSubmenuAt(position: typeof AT_RIGHT_EDGE | typeof AWAY_FROM_EDGE): void {
mount(
<View style={position}>
<MenuRoot>
<MenuTrigger testID="pill" accessibilityLabel="Open menu">
<Text>Open menu</Text>
</MenuTrigger>
<MenuSurface pages={SUB_PAGES} align="end" minWidth={220} testID="panel">
<MenuSubTrigger id="show" testID="show-row">
Show
</MenuSubTrigger>
</MenuSurface>
</MenuRoot>
</View>,
);
act(() => element("pill").click());
}
describe("submenu flyout side", () => {
beforeEach(async () => {
await page.viewport(1280, 900);
});
it("opens to the left of a menu at the right edge instead of covering it", async () => {
mountSubmenuAt(AT_RIGHT_EDGE);
await wait(FLYOUT_PLACED_MS);
act(() => element("show-row").click());
await wait(FLYOUT_PLACED_MS);
const panel = element("panel").getBoundingClientRect();
const flyout = element("panel-show").getBoundingClientRect();
expect(flyout.right).toBeLessThanOrEqual(panel.left + MAX_OVERLAP);
expect(flyout.left).toBeGreaterThanOrEqual(0);
});
it("opens to the right when there is room", async () => {
mountSubmenuAt(AWAY_FROM_EDGE);
await wait(FLYOUT_PLACED_MS);
act(() => element("show-row").click());
await wait(FLYOUT_PLACED_MS);
const panel = element("panel").getBoundingClientRect();
const flyout = element("panel-show").getBoundingClientRect();
expect(flyout.left).toBeGreaterThanOrEqual(panel.right - MAX_OVERLAP);
});
});
@@ -7,7 +7,6 @@ import {
useId, useId,
useLayoutEffect, useLayoutEffect,
useMemo, useMemo,
useRef,
useState, useState,
type ReactElement, type ReactElement,
type RefObject, type RefObject,
@@ -102,7 +101,6 @@ export function useAnchoredPosition({
offset, offset,
scrollable, scrollable,
maxHeight, maxHeight,
flipHorizontal = false,
}: { }: {
open: boolean; open: boolean;
anchorRect: Rect | null; anchorRect: Rect | null;
@@ -112,18 +110,11 @@ export function useAnchoredPosition({
offset: number; offset: number;
scrollable: boolean; scrollable: boolean;
maxHeight?: number; maxHeight?: number;
/**
* Lets a side placement open on the other side when its own side has no room. The side is
* chosen at the first placement and held while the surface is open, so content that grows
* later never moves the surface out from under a pointer travelling toward it.
*/
flipHorizontal?: boolean;
}) { }) {
const [triggerRect, setTriggerRect] = useState<Rect | null>(null); const [triggerRect, setTriggerRect] = useState<Rect | null>(null);
const [contentSize, setContentSize] = useState<Size | null>(null); const [contentSize, setContentSize] = useState<Size | null>(null);
const [position, setPosition] = useState<SurfacePosition | null>(null); const [position, setPosition] = useState<SurfacePosition | null>(null);
const [actualPlacement, setActualPlacement] = useState<Placement>(side); const [actualPlacement, setActualPlacement] = useState<Placement>(side);
const heldSideRef = useRef<Placement | null>(null);
const visibleContentSize = useMemo(() => { const visibleContentSize = useMemo(() => {
if (!contentSize) return null; if (!contentSize) return null;
@@ -145,7 +136,6 @@ export function useAnchoredPosition({
setTriggerRect(null); setTriggerRect(null);
setContentSize(null); setContentSize(null);
setPosition(null); setPosition(null);
heldSideRef.current = null;
return undefined; return undefined;
} }
@@ -179,21 +169,18 @@ export function useAnchoredPosition({
const { width: screenWidth, height: screenHeight } = Dimensions.get("window"); const { width: screenWidth, height: screenHeight } = Dimensions.get("window");
// measureInWindow and Modal both use full-screen coordinates, so the display area starts at 0. // measureInWindow and Modal both use full-screen coordinates, so the display area starts at 0.
const heldSide = heldSideRef.current;
const result = computePosition({ const result = computePosition({
triggerRect, triggerRect,
contentSize: visibleContentSize, contentSize: visibleContentSize,
displayArea: { x: 0, y: 0, width: screenWidth, height: screenHeight }, displayArea: { x: 0, y: 0, width: screenWidth, height: screenHeight },
placement: heldSide ?? side, placement: side,
alignment: align, alignment: align,
offset, offset,
flipHorizontal: flipHorizontal && heldSide === null,
}); });
if (flipHorizontal) heldSideRef.current = result.actualPlacement;
setPosition(holdSurfaceEdge(result, visibleContentSize.height)); setPosition(holdSurfaceEdge(result, visibleContentSize.height));
setActualPlacement(result.actualPlacement); setActualPlacement(result.actualPlacement);
}, [triggerRect, visibleContentSize, side, align, offset, flipHorizontal]); }, [triggerRect, visibleContentSize, side, align, offset]);
const onContentLayout = useCallback( const onContentLayout = useCallback(
(event: { nativeEvent: { layout: { width: number; height: number } } }) => { (event: { nativeEvent: { layout: { width: number; height: number } } }) => {
@@ -227,8 +214,6 @@ export interface AnchoredSurfaceProps {
scrollable?: boolean; scrollable?: boolean;
/** A submenu sits inside its parent's overlay and must not paint a second backdrop. */ /** A submenu sits inside its parent's overlay and must not paint a second backdrop. */
backdrop?: boolean; backdrop?: boolean;
/** See `useAnchoredPosition`. Submenus set it so a flyout near the edge opens on the far side. */
flipHorizontal?: boolean;
/** /**
* Hover tracking for the surface box, per docs/hover.md: plain View, pointer events, never * Hover tracking for the surface box, per docs/hover.md: plain View, pointer events, never
* a Pressable. Web-only by nature, which is all a flyout needs. * a Pressable. Web-only by nature, which is all a flyout needs.
@@ -261,7 +246,6 @@ export function AnchoredSurface({
horizontalPadding = 16, horizontalPadding = 16,
scrollable = false, scrollable = false,
backdrop = true, backdrop = true,
flipHorizontal = false,
onPointerEnter, onPointerEnter,
onPointerLeave, onPointerLeave,
testID, testID,
@@ -279,7 +263,6 @@ export function AnchoredSurface({
offset, offset,
scrollable, scrollable,
maxHeight, maxHeight,
flipHorizontal,
}); });
// The surface is placed once both measurements land. Until then it sits off-screen so it can // The surface is placed once both measurements land. Until then it sits off-screen so it can
@@ -5,7 +5,6 @@ import {
useRef, useRef,
type PropsWithChildren, type PropsWithChildren,
type ReactElement, type ReactElement,
type RefObject,
} from "react"; } from "react";
import { Text, View, type PointerEvent } from "react-native"; import { Text, View, type PointerEvent } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles"; import { StyleSheet, withUnistyles } from "react-native-unistyles";
@@ -54,56 +53,6 @@ export function MenuSubTrigger({
disabled?: boolean; disabled?: boolean;
testID?: string; testID?: string;
}>): ReactElement { }>): ReactElement {
const { anchorRef, isOpen, open, anchorProps } = useMenuSubTrigger({ id, disabled });
const trailing = useMemo(
() => <MenuSubTrailing value={value} indicator={indicator} />,
[value, indicator],
);
return (
<View ref={anchorRef} collapsable={false} {...anchorProps}>
<MenuItem
active={isOpen}
closeOnSelect={false}
disabled={disabled}
onSelect={open}
leading={leading}
trailing={trailing}
testID={testID}
>
{children}
</MenuItem>
</View>
);
}
export interface MenuSubTriggerBinding {
/** Goes on the `View` the flyout anchors to. Span the surface's width so the flyout clears it. */
anchorRef: RefObject<View | null>;
/** Spread on that same `View`: hover intent on web popovers, nothing elsewhere. */
anchorProps: {
onPointerEnter?: (event: PointerEvent) => void;
onPointerLeave?: (event: PointerEvent) => void;
};
/** The page this trigger leads to is open. */
isOpen: boolean;
/** Opens the page. Call it from the row's press. */
open: () => void;
}
/**
* The wiring behind `MenuSubTrigger`, for a row that cannot be drawn as a `MenuItem`, such as a
* compact sub-row under a custom header. The row keeps the engine's anchor, hover intent and
* page navigation; only its look is its own.
*/
export function useMenuSubTrigger({
id,
disabled = false,
}: {
id: string;
disabled?: boolean;
}): MenuSubTriggerBinding {
const menu = useMenuContext("MenuSubTrigger"); const menu = useMenuContext("MenuSubTrigger");
const depth = useMenuDepth(); const depth = useMenuDepth();
const { registerSubAnchor, hoverOpen, hoverClose, cancelHoverClose } = const { registerSubAnchor, hoverOpen, hoverClose, cancelHoverClose } =
@@ -115,12 +64,11 @@ export function useMenuSubTrigger({
}, [id, registerSubAnchor]); }, [id, registerSubAnchor]);
const isOpen = isSubPageOpen(menu.path, { id, depth }); const isOpen = isSubPageOpen(menu.path, { id, depth });
const tracksHover = menu.presentation === "popover" && !disabled; const isPopover = menu.presentation === "popover";
const { openSub } = menu;
const open = useCallback(() => { const handleSelect = useCallback(() => {
openSub({ id, depth }); menu.openSub({ id, depth });
}, [openSub, id, depth]); }, [menu, id, depth]);
const handlePointerEnter = useCallback( const handlePointerEnter = useCallback(
(event: PointerEvent) => { (event: PointerEvent) => {
@@ -139,13 +87,31 @@ export function useMenuSubTrigger({
[hoverClose, depth], [hoverClose, depth],
); );
const anchorProps = useMemo( const trailing = useMemo(
() => () => <MenuSubTrailing value={value} indicator={indicator} />,
tracksHover ? { onPointerEnter: handlePointerEnter, onPointerLeave: handlePointerLeave } : {}, [value, indicator],
[tracksHover, handlePointerEnter, handlePointerLeave],
); );
return { anchorRef, anchorProps, isOpen, open }; return (
<View
ref={anchorRef}
collapsable={false}
onPointerEnter={isPopover && !disabled ? handlePointerEnter : undefined}
onPointerLeave={isPopover && !disabled ? handlePointerLeave : undefined}
>
<MenuItem
active={isOpen}
closeOnSelect={false}
disabled={disabled}
onSelect={handleSelect}
leading={leading}
trailing={trailing}
testID={testID}
>
{children}
</MenuItem>
</View>
);
} }
function MenuSubTrailing({ function MenuSubTrailing({
@@ -351,7 +351,6 @@ function MenuFlyout({
anchorRect={null} anchorRect={null}
anchorRef={anchorRef} anchorRef={anchorRef}
side="right" side="right"
flipHorizontal
align="start" align="start"
offset={-SUBMENU_OVERLAP} offset={-SUBMENU_OVERLAP}
minWidth={minWidth} minWidth={minWidth}
+156 -134
View File
@@ -25,22 +25,18 @@ import {
uploadFileAttachments, uploadFileAttachments,
cancelComposerAgent, cancelComposerAgent,
dispatchComposerAgentMessage, dispatchComposerAgentMessage,
editQueuedComposerMessage, enqueueComposerAgentMessage,
findForgeItemByOption, findForgeItemByOption,
isAttachmentSelectedForForgeItem, isAttachmentSelectedForForgeItem,
openComposerAttachment, openComposerAttachment,
pickAndPersistImages, pickAndPersistImages,
queueComposerMessage,
removeComposerAttachmentAtIndex, removeComposerAttachmentAtIndex,
sendQueuedComposerMessageNow,
toggleForgeAttachment, toggleForgeAttachment,
toggleForgeAttachmentFromPicker, toggleForgeAttachmentFromPicker,
type MessageSubmissionWriter, type MessageSubmissionWriter,
type AttachmentPersister, type AttachmentPersister,
type ComposerCancelClient, type ComposerCancelClient,
type ComposerSendClient, type ComposerSendClient,
type QueueWriter,
type QueuedComposerMessage,
} from "./actions"; } from "./actions";
const imageMetadata: AttachmentMetadata = { const imageMetadata: AttachmentMetadata = {
@@ -184,7 +180,7 @@ interface FakeSendCall {
text: string; text: string;
options: { options: {
messageId: string; messageId: string;
activeTurnBehavior?: "interrupt" | "steer"; activeTurnBehavior?: "interrupt" | "steer" | "queue";
images?: Array<{ data: string; mimeType: string }>; images?: Array<{ data: string; mimeType: string }>;
attachments: AgentAttachment[]; attachments: AgentAttachment[];
}; };
@@ -306,19 +302,6 @@ function writeSubmission(fake: FakeStream, agentId: string, state: FakeSubmissio
submissionsByFakeStream.set(fake, submissions); 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 ( const passthroughUploadImages = async (
images: AttachmentMetadata[], images: AttachmentMetadata[],
): Promise<UploadedFileAttachment[]> => ): Promise<UploadedFileAttachment[]> =>
@@ -755,147 +738,186 @@ describe("dispatchComposerAgentMessage", () => {
}); });
}); });
describe("queueComposerMessage", () => { describe("enqueueComposerAgentMessage", () => {
it("queues a trimmed message under the agent id and returns the new entry", () => { it("hands a trimmed message to the host queue without adding a timeline row", async () => {
const queue = createFakeQueue(); const client = createFakeSendClient();
const result = queueComposerMessage({ const review = reviewWorkspaceAttachment("Queued review.");
await enqueueComposerAgentMessage({
client,
agentId: "agent", agentId: "agent",
text: " draft ", text: " queue this ",
attachments: [], attachments: [{ kind: "image", metadata: imageWithId("img-queue") }, review],
queue, uploadImages: passthroughUploadImages,
}); });
expect(result.queued?.text).toBe("draft"); expect(client.calls).toEqual([
expect(queue.state.get("agent")).toEqual([ {
{ id: result.queued?.id, text: "draft", attachments: [] }, 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",
}),
],
},
},
]); ]);
}); });
it("does not queue an empty message with no attachments", () => { it("sends nothing for an empty message with no attachments", async () => {
const queue = createFakeQueue(); const client = createFakeSendClient();
const result = queueComposerMessage({
agentId: "agent", await enqueueComposerAgentMessage({ client, agentId: "agent", text: " ", attachments: [] });
text: " ",
attachments: [], expect(client.calls).toEqual([]);
queue,
});
expect(result.queued).toBeNull();
expect(queue.state.get("agent")).toBeUndefined();
}); });
it("captures workspace review attachments at queue time alongside user attachments", () => { it("queues a staged provider switch with the message so the host runs it on that provider", async () => {
const queue = createFakeQueue(); const client = createFakeSendClient();
const review = reviewWorkspaceAttachment("Initial queued review."); const switches: unknown[] = [];
const image = imageWithId("img-queue"); let queuedSwitches = 0;
queueComposerMessage({
agentId: "agent",
text: "queue this",
attachments: [{ kind: "image", metadata: image }, review],
queue,
});
expect(queue.state.get("agent")?.[0]?.attachments).toEqual([ const input: Parameters<typeof enqueueComposerAgentMessage>[0] = {
{ kind: "image", metadata: image }, client: {
review, ...client,
switchAgentProvider: async (agentId, options) => {
switches.push({ agentId, options });
return {};
},
},
agentId: "agent",
text: "do Z",
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: [],
},
},
]); ]);
}); });
});
describe("editQueuedComposerMessage", () => { it("rejects when the host refuses the message", async () => {
it("returns null and leaves the queue untouched when the message id is missing", () => { const rejection = new Error("Agent not found");
const queue = createFakeQueue( const client = createFakeSendClient({ rejection });
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("returns the text and only user attachments, removing the queued entry", () => { await expect(
const review = reviewWorkspaceAttachment("Queued snapshot."); enqueueComposerAgentMessage({ client, agentId: "agent", text: "hello", attachments: [] }),
const image = imageWithId("img-queued-edit"); ).rejects.toBe(rejection);
const queue = createFakeQueue(
new Map([
[
"agent",
[
{
id: "msg-1",
text: "queued draft",
attachments: [{ kind: "image", metadata: image }, review],
},
],
],
]),
);
const result = editQueuedComposerMessage({ agentId: "agent", messageId: "msg-1", queue });
expect(result).toEqual({
text: "queued draft",
attachments: [{ kind: "image", metadata: image }],
});
expect(queue.state.get("agent")).toEqual([]);
}); });
}); });
describe("sendQueuedComposerMessageNow", () => { describe("attachments restored from a queued message", () => {
it("returns missing without submitting when the message id is gone", async () => { const uploadedImage: Extract<AgentAttachment, { type: "uploaded_file" }> = {
const queue = createFakeQueue(); type: "uploaded_file",
const submitted: Array<{ text: string; attachments: ComposerAttachment[] }> = []; id: "upload_restored",
const result = await sendQueuedComposerMessageNow({ 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,
},
};
it("queues the same uploaded image again without uploading it", async () => {
const client = createFakeSendClient();
await enqueueComposerAgentMessage({
client,
agentId: "agent", agentId: "agent",
messageId: "msg-1", text: "again",
queue, attachments: [restoredImage],
submitMessage: async (input) => {
submitted.push(input);
},
}); });
expect(result).toEqual({ status: "missing" });
expect(submitted).toEqual([]); expect(client.uploadCalls).toEqual([]);
expect(client.calls[0]?.options.attachments).toEqual([uploadedImage]);
}); });
it("removes the queued entry and submits its text + attachments", async () => { it("shows a sent uploaded image as an image on the optimistic message", async () => {
const review = reviewWorkspaceAttachment("Queued for send."); const client = createFakeSendClient();
const queue = createFakeQueue( const stream = createFakeStream();
new Map([["agent", [{ id: "msg-1", text: "send me", attachments: [review] }]]]),
); await dispatchComposerAgentMessage({
const submitted: Array<{ text: string; attachments: ComposerAttachment[] }> = []; client,
const result = await sendQueuedComposerMessageNow({
agentId: "agent", agentId: "agent",
messageId: "msg-1", text: "look",
queue, attachments: [restoredImage],
submitMessage: async (input) => { submission: stream,
submitted.push(input);
},
}); });
expect(result).toEqual({ status: "submitted" });
expect(queue.state.get("agent")).toEqual([]); const { type: _type, role: _role, ...upload } = uploadedImage;
expect(submitted).toEqual([{ text: "send me", attachments: [review] }]); 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("restores the queued entry to the front and surfaces the error message on failure", async () => { it("counts a restored forge item as selected and toggles it off", () => {
const queue = createFakeQueue( expect(isAttachmentSelectedForForgeItem([restoredIssue], issueItem)).toBe(true);
new Map([ expect(isAttachmentSelectedForForgeItem([restoredIssue], prItem)).toBe(false);
[ expect(toggleForgeAttachment([restoredIssue], issueItem)).toEqual([]);
"agent", });
[
{ id: "msg-1", text: "first", attachments: [] }, it("opens the URL of a restored forge item", () => {
{ id: "msg-2", text: "second", attachments: [] }, const urls: string[] = [];
], openComposerAttachment({
], attachment: restoredIssue,
]), setLightboxMetadata: () => {
); throw new Error("unexpected lightbox call");
const result = await sendQueuedComposerMessageNow({
agentId: "agent",
messageId: "msg-1",
queue,
submitMessage: async () => {
throw new Error("network down");
}, },
openWorkspaceAttachment: () => false,
openExternalUrl: (url) => urls.push(url),
}); });
expect(result).toEqual({ status: "failed", errorMessage: "network down" }); expect(urls).toEqual([issueItem.url]);
const state = queue.state.get("agent");
expect(state?.map((m) => m.id)).toEqual(["msg-1", "msg-2"]);
}); });
}); });
+83 -155
View File
@@ -4,6 +4,8 @@ import { FILE_UPLOAD_MAX_BYTES } from "@/attachments/upload-limit";
import type { AgentProvider, ProviderOptions } from "@getpaseo/protocol/agent-types"; import type { AgentProvider, ProviderOptions } from "@getpaseo/protocol/agent-types";
import type { import type {
ActiveTurnBehavior, ActiveTurnBehavior,
AgentActiveTurnBehavior,
AgentAttachment,
AgentSnapshotPayload, AgentSnapshotPayload,
ForgeSearchItem, ForgeSearchItem,
UploadedFileAttachment, UploadedFileAttachment,
@@ -15,10 +17,8 @@ import type {
ComposerAttachment, ComposerAttachment,
UserComposerAttachment, UserComposerAttachment,
} from "@/attachments/types"; } from "@/attachments/types";
import { import { isWorkspaceAttachment } from "@/attachments/workspace-attachment-utils";
isWorkspaceAttachment, import { forgeItemKey } from "@/composer/attachments/forge-item-key";
userAttachmentsOnly,
} from "@/attachments/workspace-attachment-utils";
import { import {
splitComposerAttachmentsForSubmit, splitComposerAttachmentsForSubmit,
type ComposerAttachmentSubmitFormat, type ComposerAttachmentSubmitFormat,
@@ -27,6 +27,7 @@ import {
createPendingProviderSwitchItem, createPendingProviderSwitchItem,
createUserMessage, createUserMessage,
generateMessageId, generateMessageId,
toDaemonUploadedImageAttachments,
type ProviderSwitchItem, type ProviderSwitchItem,
type UserMessageItem, type UserMessageItem,
} from "@/types/stream"; } from "@/types/stream";
@@ -34,12 +35,6 @@ import type { MessageSubmissionRejectionOutcome } from "@/composer/submission/mo
import type { PickedImageAttachmentInput } from "@/hooks/image-attachment-picker"; import type { PickedImageAttachmentInput } from "@/hooks/image-attachment-picker";
import { i18n } from "@/i18n/i18next"; import { i18n } from "@/i18n/i18next";
export interface QueuedComposerMessage {
id: string;
text: string;
attachments: ComposerAttachment[];
}
export interface AttachmentPersister { export interface AttachmentPersister {
persistFromBlob: (input: { persistFromBlob: (input: {
blob: Blob; blob: Blob;
@@ -65,7 +60,7 @@ export interface ComposerSendClient {
text: string, text: string,
options: { options: {
messageId: string; messageId: string;
activeTurnBehavior?: ActiveTurnBehavior; activeTurnBehavior?: AgentActiveTurnBehavior;
images?: Array<{ data: string; mimeType: string }>; images?: Array<{ data: string; mimeType: string }>;
attachments: ReturnType<typeof splitComposerAttachmentsForSubmit>["attachments"]; attachments: ReturnType<typeof splitComposerAttachmentsForSubmit>["attachments"];
}, },
@@ -82,6 +77,7 @@ export interface ComposerSendClient {
messageId: string; messageId: string;
images?: Array<{ data: string; mimeType: string }>; images?: Array<{ data: string; mimeType: string }>;
attachments?: ReturnType<typeof splitComposerAttachmentsForSubmit>["attachments"]; attachments?: ReturnType<typeof splitComposerAttachmentsForSubmit>["attachments"];
activeTurnBehavior?: "queue";
}, },
) => Promise<{ agent?: AgentSnapshotPayload }>; ) => Promise<{ agent?: AgentSnapshotPayload }>;
uploadFile: (input: { fileName: string; mimeType: string; bytes: Uint8Array }) => Promise<{ uploadFile: (input: { fileName: string; mimeType: string; bytes: Uint8Array }) => Promise<{
@@ -106,13 +102,6 @@ export interface MessageSubmissionWriter {
reject: (agentId: string, clientMessageId: string) => MessageSubmissionRejectionOutcome; 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: { export async function pickAndPersistImages(input: {
pickImages: () => Promise<PickedImageAttachmentInput[] | null>; pickImages: () => Promise<PickedImageAttachmentInput[] | null>;
persister: Pick< persister: Pick<
@@ -258,12 +247,13 @@ export async function dispatchComposerAgentMessage(
}); });
const clientMessageId = generateMessageId(); const clientMessageId = generateMessageId();
const timestamp = new Date(); const timestamp = new Date();
const sent = separateUploadedImages(wirePayload.attachments);
const userMessage = createUserMessage({ const userMessage = createUserMessage({
clientMessageId, clientMessageId,
text: input.text, text: input.text,
timestamp, timestamp,
images: wirePayload.images, images: [...wirePayload.images, ...sent.images],
attachments: wirePayload.attachments, attachments: sent.attachments,
...(input.activeTurnBehavior === "steer" && input.activeTurnId && !input.stagedProviderSwitch ...(input.activeTurnBehavior === "steer" && input.activeTurnId && !input.stagedProviderSwitch
? { turnId: input.activeTurnId } ? { turnId: input.activeTurnId }
: {}), : {}),
@@ -275,12 +265,7 @@ export async function dispatchComposerAgentMessage(
pendingProviderSwitch ? { providerSwitch: pendingProviderSwitch } : undefined, pendingProviderSwitch ? { providerSwitch: pendingProviderSwitch } : undefined,
); );
try { try {
const imagePayload = input.uploadImages const imagePayload = await prepareImagePayload(input, wirePayload.images);
? { attachments: await input.uploadImages(wirePayload.images) }
: await prepareImageAttachmentsForSend({
client: input.client,
images: wirePayload.images,
});
if (input.stagedProviderSwitch && input.client.switchAgentProvider) { if (input.stagedProviderSwitch && input.client.switchAgentProvider) {
const result = await input.client.switchAgentProvider(input.agentId, { const result = await input.client.switchAgentProvider(input.agentId, {
provider: input.stagedProviderSwitch.provider, provider: input.stagedProviderSwitch.provider,
@@ -313,108 +298,70 @@ export async function dispatchComposerAgentMessage(
} }
} }
export interface QueueComposerMessageInput { async function prepareImagePayload(
agentId: string; input: Pick<DispatchComposerAgentMessageInput, "client" | "uploadImages">,
text: string; images: AttachmentMetadata[],
attachments: ComposerAttachment[]; ) {
queue: QueueWriter; if (input.uploadImages) return { attachments: await input.uploadImages(images) };
return await prepareImageAttachmentsForSend({ client: input.client, images });
} }
export interface QueueComposerMessageResult { /** Images the host already holds render as images, the way its timeline echo does. */
queued: QueuedComposerMessage | null; function separateUploadedImages(attachments: AgentAttachment[]) {
} const uploads: UploadedFileAttachment[] = [];
const rest: AgentAttachment[] = [];
export function queueComposerMessage(input: QueueComposerMessageInput): QueueComposerMessageResult { for (const attachment of attachments) {
const trimmed = input.text.trim(); if (attachment.type === "uploaded_file" && attachment.role === "image") {
if (!trimmed && input.attachments.length === 0) { uploads.push(attachment);
return { queued: null }; } else {
rest.push(attachment);
}
} }
const item: QueuedComposerMessage = { const images = toDaemonUploadedImageAttachments(
id: generateMessageId(), uploads.map(({ id, fileName, mimeType, size, path }) => ({
text: trimmed, id,
attachments: input.attachments, 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 ?? [])],
}; };
input.queue.write((prev) => { if (input.stagedProviderSwitch && input.client.switchAgentProvider) {
const next = new Map(prev); await input.client.switchAgentProvider(input.agentId, {
next.set(input.agentId, [...(prev.get(input.agentId) ?? []), item]); ...input.stagedProviderSwitch,
return next; ...queued,
}); text,
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;
}); });
return { input.onProviderSwitchQueued?.();
status: "failed", return;
errorMessage:
error instanceof Error
? error.message
: (input.failedToSendMessage ?? i18n.t("composer.errors.failedToSend")),
};
} }
await input.client.sendAgentMessage(input.agentId, text, queued);
} }
export interface OpenComposerAttachmentInput { export interface OpenComposerAttachmentInput {
@@ -432,6 +379,13 @@ export function openComposerAttachment(input: OpenComposerAttachmentInput): void
if (input.attachment.kind === "file" || input.attachment.kind === "workspace_file") { if (input.attachment.kind === "file" || input.attachment.kind === "workspace_file") {
return; 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)) { if (isWorkspaceAttachment(input.attachment)) {
input.openWorkspaceAttachment({ attachment: input.attachment }); input.openWorkspaceAttachment({ attachment: input.attachment });
return; return;
@@ -445,31 +399,11 @@ export function buildForgeAttachment(item: ForgeSearchItem): UserComposerAttachm
: { kind: "forge_issue", item }; : { 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( export function toggleForgeAttachment(
current: UserComposerAttachment[], current: UserComposerAttachment[],
item: ForgeSearchItem, item: ForgeSearchItem,
): UserComposerAttachment[] { ): UserComposerAttachment[] {
const matches = (attachment: UserComposerAttachment) => const matches = (attachment: UserComposerAttachment) => isSameForgeItem(attachment, item);
isForgeAttachment(attachment) &&
attachment.item.kind === item.kind &&
attachment.item.number === item.number;
if (current.some(matches)) { if (current.some(matches)) {
return current.filter((attachment) => !matches(attachment)); return current.filter((attachment) => !matches(attachment));
} }
@@ -487,12 +421,7 @@ export function toggleForgeAttachmentFromPicker({
item, item,
markForgeAttachmentRemoved, markForgeAttachmentRemoved,
}: ToggleForgeAttachmentFromPickerInput): UserComposerAttachment[] { }: ToggleForgeAttachmentFromPickerInput): UserComposerAttachment[] {
const existingAttachment = current.find( const existingAttachment = current.find((attachment) => isSameForgeItem(attachment, item));
(attachment) =>
isForgeAttachment(attachment) &&
attachment.item.kind === item.kind &&
attachment.item.number === item.number,
);
if (existingAttachment) { if (existingAttachment) {
markForgeAttachmentRemoved(existingAttachment); markForgeAttachmentRemoved(existingAttachment);
} }
@@ -510,10 +439,9 @@ export function isAttachmentSelectedForForgeItem(
current: readonly ComposerAttachment[], current: readonly ComposerAttachment[],
item: ForgeSearchItem, item: ForgeSearchItem,
): boolean { ): boolean {
return userAttachmentsOnly(current).some( return current.some((attachment) => isSameForgeItem(attachment, item));
(attachment) => }
isForgeAttachment(attachment) &&
attachment.item.kind === item.kind && function isSameForgeItem(attachment: ComposerAttachment, item: ForgeSearchItem): boolean {
attachment.item.number === item.number, return forgeItemKey(attachment) === `${item.kind}:${item.number}`;
);
} }
@@ -0,0 +1,33 @@
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;
}
}
@@ -0,0 +1,102 @@
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,6 +55,11 @@ export function splitComposerAttachmentsForSubmit(
continue; continue;
} }
if (attachment.kind === "agent_attachment") {
agentAttachments.push(attachment.attachment);
continue;
}
if (attachment.kind === "workspace_file") { if (attachment.kind === "workspace_file") {
agentAttachments.push(workspaceFileAttachmentToAgentAttachment(attachment)); agentAttachments.push(workspaceFileAttachmentToAgentAttachment(attachment));
continue; continue;
@@ -209,7 +209,7 @@ function useWorkspaceAttachmentBinding({
const completeSubmit = useCallback( const completeSubmit = useCallback(
({ result, outgoingAttachments }: CompleteSubmitInput) => { ({ result, outgoingAttachments }: CompleteSubmitInput) => {
if (result === "submitted") { if (result === "submitted" || result === "queued") {
clearSentAttachments(outgoingAttachments); clearSentAttachments(outgoingAttachments);
} }
if (result === "queued" || result === "submitted" || result === "failed") { if (result === "queued" || result === "submitted" || result === "failed") {
@@ -82,9 +82,8 @@ function ComposerViewport({
); );
} }
/** Bound the complete composer (including its controls), not just the text input. */ /** Bound the complete composer slot (tracks and input) to the visible viewport capacity. */
function ComposerViewportContent({ style, ...props }: ViewProps) { function ComposerViewportContent({ style, ...props }: ViewProps) {
const compact = useIsCompactFormFactor();
const sizing = useContext(ViewportSizing); const sizing = useContext(ViewportSizing);
if (!sizing) throw new Error("ComposerViewportContent requires ComposerViewport"); if (!sizing) throw new Error("ComposerViewportContent requires ComposerViewport");
const constraint = useAnimatedStyle(() => ({ const constraint = useAnimatedStyle(() => ({
@@ -93,7 +92,7 @@ function ComposerViewportContent({ style, ...props }: ViewProps) {
// Fullscreen styles override it with a static minHeight instead of feeding the mode // 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, // in here: Reanimated applies a dependency change frames after the React commit,
// so the fullscreen slot would paint clamped to the inline cap first. // so the fullscreen slot would paint clamped to the inline cap first.
maxHeight: resolveInlineComposerCapacity(sizing.value?.capacity, compact), maxHeight: sizing.value?.capacity,
})); }));
return ( return (
@@ -101,6 +100,55 @@ function ComposerViewportContent({ style, ...props }: ViewProps) {
); );
} }
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>
);
}
/** /**
* The keyboard only needs to move a centered form once it reaches the form's resting bottom. * The keyboard only needs to move a centered form once it reaches the form's resting bottom.
* Fullscreen keeps the inline measurements: it does not translate, and re-measuring the * Fullscreen keeps the inline measurements: it does not translate, and re-measuring the
@@ -294,6 +342,7 @@ const dockStyles = StyleSheet.create({
// Yoga applies minHeight after maxHeight, so this fills the viewport over the // Yoga applies minHeight after maxHeight, so this fills the viewport over the
// inline cap that ComposerViewportContent keeps animating. // inline cap that ComposerViewportContent keeps animating.
fullscreenSurface: { flex: 1, minHeight: "100%" }, fullscreenSurface: { flex: 1, minHeight: "100%" },
fullscreenFill: { flex: 1, minHeight: 0, width: "100%" },
centeredViewport: { flex: 1, alignItems: "center", justifyContent: "center" }, centeredViewport: { flex: 1, alignItems: "center", justifyContent: "center" },
centered: { flexShrink: 1, width: "100%" }, centered: { flexShrink: 1, width: "100%" },
// Reserve the composer's own capped height before the setup scroll view shrinks. // Reserve the composer's own capped height before the setup scroll view shrinks.
+65 -24
View File
@@ -1,14 +1,25 @@
export { ComposerDockBackground } from "./internal/background"; export { ComposerDockBackground } from "./internal/background";
export { ComposerFullscreenBody, ComposerFullscreenFooter } from "./internal/fullscreen"; export { ComposerFullscreenBody, ComposerFullscreenFooter } from "./internal/fullscreen";
import { ScrollView } from "@/components/ui/scroll-view"; import { ScrollView } from "@/components/ui/scroll-view";
import { useState, useCallback, useMemo, useRef, type ReactNode } from "react"; import {
createContext,
useCallback,
useContext,
useMemo,
useRef,
useState,
type ReactNode,
} from "react";
import { View } from "react-native"; import { View } from "react-native";
import { StyleSheet } from "react-native-unistyles"; import { StyleSheet } from "react-native-unistyles";
import { inlineUnistylesStyle } from "@/styles/unistyles-inline-style";
import { resolveInlineComposerCapacity } from "./internal/capacity"; import { resolveInlineComposerCapacity } from "./internal/capacity";
import { useFullscreenSlotFrame } from "./internal/fullscreen"; import { useFullscreenSlotFrame } from "./internal/fullscreen";
import { useIsCompactFormFactor } from "@/constants/layout"; import { useIsCompactFormFactor } from "@/constants/layout";
import { HEADER_INNER_HEIGHT } from "@/constants/layout"; import { HEADER_INNER_HEIGHT } from "@/constants/layout";
const ViewportHeightContext = createContext<number | undefined>(undefined);
interface ComposerDockProps { interface ComposerDockProps {
children: [ReactNode, ReactNode, ReactNode?]; children: [ReactNode, ReactNode, ReactNode?];
centered?: boolean; centered?: boolean;
@@ -21,40 +32,39 @@ export function ComposerDock({
centered = false, centered = false,
fullscreen = false, fullscreen = false,
}: ComposerDockProps) { }: ComposerDockProps) {
const compact = useIsCompactFormFactor();
const [surfaceSize, setSurfaceSize] = useState<{ width: number; height: number }>(); const [surfaceSize, setSurfaceSize] = useState<{ width: number; height: number }>();
const surfaceRef = useRef<View>(null); const surfaceRef = useRef<View>(null);
const fullscreenFrame = useFullscreenSlotFrame(fullscreen, surfaceRef, surfaceSize); const fullscreenFrame = useFullscreenSlotFrame(fullscreen, surfaceRef, surfaceSize);
const constraint = useMemo( const constraint = useMemo(
() => ({ maxHeight: resolveInlineComposerCapacity(surfaceSize?.height, compact) }), () =>
[surfaceSize?.height, compact], surfaceSize?.height !== undefined
? inlineUnistylesStyle({ maxHeight: surfaceSize.height })
: undefined,
[surfaceSize?.height],
); );
const measureViewport = useCallback((event: import("react-native").LayoutChangeEvent) => { const measureViewport = useCallback((event: import("react-native").LayoutChangeEvent) => {
const { width, height } = event.nativeEvent.layout; const { width, height } = event.nativeEvent.layout;
if (height > 0) setSurfaceSize({ width, height }); if (height > 0) setSurfaceSize({ width, height });
}, []); }, []);
if (centered) { const body = centered ? (
return ( <View ref={surfaceRef} style={styles.centered} onLayout={measureViewport}>
<View ref={surfaceRef} style={styles.centered} onLayout={measureViewport}> <View style={styles.form}>
<View style={styles.form}> <ScrollView style={styles.setup} keyboardShouldPersistTaps="handled">
<ScrollView style={styles.setup} keyboardShouldPersistTaps="handled"> {content}
{content} </ScrollView>
</ScrollView> <View
<View style={
style={ fullscreen
fullscreen ? [styles.fullscreenComposer, fullscreenFrame]
? [styles.fullscreenComposer, fullscreenFrame] : [styles.centeredComposer, constraint]
: [styles.centeredComposer, constraint] }
} >
> {composer}
{composer}
</View>
{overlay}
</View> </View>
{overlay}
</View> </View>
); </View>
} ) : (
return (
<View ref={surfaceRef} style={styles.surface} onLayout={measureViewport}> <View ref={surfaceRef} style={styles.surface} onLayout={measureViewport}>
<View style={styles.content}>{content}</View> <View style={styles.content}>{content}</View>
<View <View
@@ -67,12 +77,43 @@ export function ComposerDock({
{overlay} {overlay}
</View> </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) => ({ const styles = StyleSheet.create((theme) => ({
surface: { flex: 1, overflow: "hidden" }, surface: { flex: 1, overflow: "hidden" },
content: { flex: 1, justifyContent: "flex-end" }, content: { flex: 1, justifyContent: "flex-end" },
composer: { width: "100%", flexShrink: 1, paddingBottom: theme.spacing[4] }, 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 // 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 // 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. // directly. React Native Web renders `fixed`; React Native's style type omits it.
+3 -14
View File
@@ -14,6 +14,7 @@ import { buildForgeSearchQueryOptions, type ForgeSearchClient } from "@/git/use-
import { extractForgeRefs, type ForgeRef } from "@/git/forge-refs"; import { extractForgeRefs, type ForgeRef } from "@/git/forge-refs";
import type { ForgeSearchItem } from "@getpaseo/protocol/messages"; import type { ForgeSearchItem } from "@getpaseo/protocol/messages";
import { isAttachmentSelectedForForgeItem, toggleForgeAttachment } from "./actions"; import { isAttachmentSelectedForForgeItem, toggleForgeAttachment } from "./actions";
import { forgeItemKey } from "./attachments/forge-item-key";
const AUTO_ATTACH_DEBOUNCE_MS = 300; const AUTO_ATTACH_DEBOUNCE_MS = 300;
@@ -148,7 +149,7 @@ export function useComposerForgeAutoAttach(
]); ]);
const markForgeAttachmentRemoved = useCallback((attachment: ComposerAttachment | undefined) => { const markForgeAttachmentRemoved = useCallback((attachment: ComposerAttachment | undefined) => {
const key = attachmentKey(attachment); const key = forgeItemKey(attachment);
if (key) { if (key) {
removedRefKeysRef.current.add(key); removedRefKeysRef.current.add(key);
} }
@@ -505,7 +506,7 @@ function isSameLookupTarget(
} }
function hasForgeAttachment(attachments: UserComposerAttachment[], ref: ForgeRef): boolean { function hasForgeAttachment(attachments: UserComposerAttachment[], ref: ForgeRef): boolean {
return attachments.some((attachment) => attachmentKey(attachment) === forgeRefKey(ref)); return attachments.some((attachment) => forgeItemKey(attachment) === forgeRefKey(ref));
} }
function forgeItemMatchesRef(item: ForgeSearchItem, ref: ForgeRef): boolean { function forgeItemMatchesRef(item: ForgeSearchItem, ref: ForgeRef): boolean {
@@ -519,15 +520,3 @@ function forgeItemKind(ref: ForgeRef): ForgeSearchItem["kind"] {
function forgeRefKey(ref: ForgeRef): string { function forgeRefKey(ref: ForgeRef): string {
return `${forgeItemKind(ref)}:${ref.number}`; 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}`;
}
+193 -336
View File
@@ -17,16 +17,17 @@ import {
getStagedProviderSwitch, getStagedProviderSwitch,
isStagedProviderSwitchInFlight, isStagedProviderSwitchInFlight,
settleCommittedProviderSwitch, settleCommittedProviderSwitch,
settleStagedProviderSwitch,
useFailedStartupSettings, useFailedStartupSettings,
useIsStagedProviderSwitchInFlight, useIsStagedProviderSwitchInFlight,
useStagedProviderSwitch, useStagedProviderSwitch,
useStagedProviderSwitchStore,
} from "@/composer/provider-switch"; } from "@/composer/provider-switch";
import { useProvidersSnapshot } from "@/hooks/use-providers-snapshot"; import { useProvidersSnapshot } from "@/hooks/use-providers-snapshot";
import { normalizeAgentSnapshot } from "@/utils/agent-snapshots"; import { normalizeAgentSnapshot } from "@/utils/agent-snapshots";
import { resolveProviderLabel } from "@/utils/provider-definitions"; import { resolveProviderLabel } from "@/utils/provider-definitions";
import { import {
View, View,
Pressable,
Text, Text,
StyleSheet as RNStyleSheet, StyleSheet as RNStyleSheet,
type PressableStateCallbackType, type PressableStateCallbackType,
@@ -64,9 +65,7 @@ import { usePointerCapabilities } from "@/hooks/pointer-capabilities";
import { useShallow } from "zustand/shallow"; import { useShallow } from "zustand/shallow";
import { import {
ArrowRightLeft, ArrowRightLeft,
ArrowUp,
Square, Square,
Pencil,
AudioLines, AudioLines,
CircleDot, CircleDot,
FileText, FileText,
@@ -106,19 +105,15 @@ import { focusWithRetries } from "@/utils/web-focus";
import { import {
cancelComposerAgent, cancelComposerAgent,
dispatchComposerAgentMessage, dispatchComposerAgentMessage,
editQueuedComposerMessage, enqueueComposerAgentMessage,
findForgeItemByOption, findForgeItemByOption,
isAttachmentSelectedForForgeItem, isAttachmentSelectedForForgeItem,
openComposerAttachment, openComposerAttachment,
pickAndPersistImages, pickAndPersistImages,
queueComposerMessage,
removeComposerAttachmentAtIndex, removeComposerAttachmentAtIndex,
sendQueuedComposerMessageNow,
toggleForgeAttachmentFromPicker, toggleForgeAttachmentFromPicker,
uploadFileAttachments, uploadFileAttachments,
type AttachmentPersister, type AttachmentPersister,
type QueueWriter,
type QueuedComposerMessage,
} from "@/composer/actions"; } from "@/composer/actions";
import { useVoiceOptional } from "@/contexts/voice-context"; import { useVoiceOptional } from "@/contexts/voice-context";
import { useToast } from "@/contexts/toast-context"; import { useToast } from "@/contexts/toast-context";
@@ -178,6 +173,12 @@ import type { ComposerFocusOptions } from "@/composer/model";
import { useRetainedPanelActive } from "@/components/retained-panel"; import { useRetainedPanelActive } from "@/components/retained-panel";
import { insertAtSelection } from "@/composer/insert-text"; import { insertAtSelection } from "@/composer/insert-text";
import { composerWorkspaceAttachment } from "@/composer/attachments/workspace"; 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 { useWorkspaceAttachmentsForScopes } from "@/attachments/workspace-attachments-store";
import { droppedItemsToSelectedFiles } from "@/composer/attachments/drop"; import { droppedItemsToSelectedFiles } from "@/composer/attachments/drop";
import { getFileTypeLabel } from "@/attachments/file-types"; import { getFileTypeLabel } from "@/attachments/file-types";
@@ -220,8 +221,6 @@ const composerImageAttachmentPersister: Pick<
persistFromFileUri: persistAttachmentFromFileUri, persistFromFileUri: persistAttachmentFromFileUri,
}; };
type QueuedMessage = QueuedComposerMessage;
type AttachmentListUpdater = type AttachmentListUpdater =
| UserComposerAttachment[] | UserComposerAttachment[]
| ((prev: UserComposerAttachment[]) => UserComposerAttachment[]); | ((prev: UserComposerAttachment[]) => UserComposerAttachment[]);
@@ -435,34 +434,6 @@ 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 { interface RenderComposerAttachmentPillArgs {
serverId: string; serverId: string;
attachment: ComposerAttachment; attachment: ComposerAttachment;
@@ -522,6 +493,22 @@ function renderComposerAttachmentPill(args: RenderComposerAttachmentPillArgs): R
onRemove, 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") { if (attachment.kind === "plugin_resource") {
return ( return (
<PluginResourceAttachmentPill <PluginResourceAttachmentPill
@@ -725,54 +712,6 @@ 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 { interface ImageAttachmentPillProps {
attachment: Extract<ComposerAttachment, { kind: "image" }>; attachment: Extract<ComposerAttachment, { kind: "image" }>;
index: number; index: number;
@@ -1055,7 +994,6 @@ interface ComposerProps {
error?: string | null; error?: string | null;
} }
const EMPTY_ARRAY: readonly QueuedMessage[] = [];
const StableMessageInput = memo(MessageInput); const StableMessageInput = memo(MessageInput);
interface ComposerAutocompleteHandle { interface ComposerAutocompleteHandle {
@@ -1398,6 +1336,10 @@ function ComposerContentImpl({
const stagedProviderLabel = stagedSwitch const stagedProviderLabel = stagedSwitch
? resolveProviderLabel(stagedSwitch.provider, providerSnapshotEntries) ? resolveProviderLabel(stagedSwitch.provider, providerSnapshotEntries)
: null; : null;
const providerLabel = useCallback(
(provider: string) => resolveProviderLabel(provider, providerSnapshotEntries),
[providerSnapshotEntries],
);
useEffect(() => { useEffect(() => {
if ( if (
@@ -1413,7 +1355,6 @@ function ComposerContentImpl({
const handleCancelStagedSwitch = useCallback(() => { const handleCancelStagedSwitch = useCallback(() => {
clearStagedProviderSwitch(serverId, agentId); clearStagedProviderSwitch(serverId, agentId);
setSendError(null); setSendError(null);
useSessionStore.getState().setQueuedSendError(serverId, agentId, null);
}, [agentId, serverId]); }, [agentId, serverId]);
const handleRetryFailedStartupSettings = useCallback(() => { const handleRetryFailedStartupSettings = useCallback(() => {
@@ -1426,16 +1367,6 @@ function ComposerContentImpl({
void getHostRuntimeStore().recoverFailedStartupSettings(serverId, agentId, "discard"); void getHostRuntimeStore().recoverFailedStartupSettings(serverId, agentId, "discard");
}, [agentId, serverId]); }, [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 isCompactFormFactor = useIsCompactFormFactor();
const isCompactLayout = resolveCompactLayout(isCompactLayoutOverride, isCompactFormFactor); const isCompactLayout = resolveCompactLayout(isCompactLayoutOverride, isCompactFormFactor);
const controlSizing = controlSizingForLayout(isCompactFormFactor); const controlSizing = controlSizingForLayout(isCompactFormFactor);
@@ -1453,7 +1384,6 @@ function ComposerContentImpl({
removeAttachment, removeAttachment,
openAttachment, openAttachment,
beginSubmit, beginSubmit,
clearSentAttachments,
completeSubmit, completeSubmit,
resetSuppression, resetSuppression,
} = composerWorkspaceAttachment.useBinding({ } = composerWorkspaceAttachment.useBinding({
@@ -1671,16 +1601,7 @@ function ComposerContentImpl({
); );
const runPluginClientSlashCommand = useCallback( const runPluginClientSlashCommand = useCallback(
( (resolved: { command: (typeof pluginClientSlashCommands)[number]; args: string }): boolean => {
resolved: { command: (typeof pluginClientSlashCommands)[number]; args: string },
hasAttachments: boolean,
) => {
if (hasAttachments) {
setSendError(
t("composer.errors.removePluginCommandAttachments", { command: resolved.command.name }),
);
return;
}
if (blurOnSubmit) messageInputRef.current?.blur(); if (blurOnSubmit) messageInputRef.current?.blur();
clearDraft("sent"); clearDraft("sent");
replaceUserInput(""); replaceUserInput("");
@@ -1695,8 +1616,9 @@ function ComposerContentImpl({
toastErrorRef.current(error instanceof Error ? error.message : String(error)); toastErrorRef.current(error instanceof Error ? error.message : String(error));
}, },
}); });
return true;
}, },
[blurOnSubmit, clearDraft, replaceUserInput, resetSuppression, setSelectedAttachments, t], [blurOnSubmit, clearDraft, replaceUserInput, resetSuppression, setSelectedAttachments],
); );
const { pickImages } = useImageAttachmentPicker(); const { pickImages } = useImageAttachmentPicker();
@@ -1809,7 +1731,6 @@ function ComposerContentImpl({
const pendingSwitch = canSwitch ? getStagedProviderSwitch(serverId, targetAgentId) : null; const pendingSwitch = canSwitch ? getStagedProviderSwitch(serverId, targetAgentId) : null;
const stagedProviderSwitch = const stagedProviderSwitch =
pendingSwitch && pendingSwitch.provider !== liveProvider ? pendingSwitch : null; pendingSwitch && pendingSwitch.provider !== liveProvider ? pendingSwitch : null;
useSessionStore.getState().setQueuedSendError(serverId, targetAgentId, null);
if (stagedProviderSwitch) { if (stagedProviderSwitch) {
beginStagedProviderSwitch(serverId, targetAgentId); beginStagedProviderSwitch(serverId, targetAgentId);
} }
@@ -1885,43 +1806,37 @@ function ComposerContentImpl({
} }
return false; return false;
}); });
// COMPAT(agentMessageQueue): added in v0.18.2, remove gate after 2027-06-01.
const supportsQueue = useHostFeature(serverId, "agentMessageQueue");
const activeSendBehavior = resolveActiveSendBehavior( const activeSendBehavior = resolveActiveSendBehavior(
appSettings.sendBehavior, appSettings.sendBehavior,
hasPendingPermission, hasPendingPermission,
supportsQueue,
); );
const hasAgent = agentState.status !== null; const hasAgent = agentState.status !== null;
const queueWriter = useMemo<QueueWriter>( const enqueueMessage = useCallback(
() => ({ async (text: string, queuedAttachments: ComposerAttachment[]) => {
read: (id) => useSessionStore.getState().sessions[serverId]?.queuedMessages?.get(id) ?? [], if (!client) {
write: (updater) => setQueuedMessages(serverId, updater), throw new Error(t("workspace.terminal.hostDisconnected"));
}), }
[serverId, setQueuedMessages], const targetAgentId = agentIdRef.current;
); await enqueueComposerAgentMessage({
client,
const queueMessage = useCallback( agentId: targetAgentId,
(queuedMessage: string, queuedAttachments: ComposerAttachment[]) => { text,
const result = queueComposerMessage({
agentId,
text: queuedMessage,
attachments: queuedAttachments, attachments: queuedAttachments,
queue: queueWriter, 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);
},
}); });
if (!result.queued) return;
replaceUserInput("");
setSelectedAttachments([]);
resetSuppression();
clearSentAttachments(queuedAttachments);
}, },
[ [client, serverId, stagedSwitch, supportsForgeSearch, t],
agentId,
clearSentAttachments,
queueWriter,
resetSuppression,
setSelectedAttachments,
replaceUserInput,
],
); );
const sendMessageWithContent = useCallback( const sendMessageWithContent = useCallback(
@@ -1937,12 +1852,15 @@ function ComposerContentImpl({
allowEmptySubmit, allowEmptySubmit,
forceSend: stagedSwitch && isAgentRunning ? false : forceSend, forceSend: stagedSwitch && isAgentRunning ? false : forceSend,
submitBehavior, submitBehavior,
isAgentRunning, isAgentRunning: isAgentRunning && supportsQueue,
// Parent-managed submits are still valid submit paths even when the // Parent-managed submits are still valid submit paths even when the
// transport is disconnected, because the parent decides the failure mode. // transport is disconnected, because the parent decides the failure mode.
canSubmit: Boolean(sendAgentMessageRef.current || onSubmitMessageRef.current), canSubmit: Boolean(sendAgentMessageRef.current || onSubmitMessageRef.current),
queueMessage: ({ message: queuedText, attachments: queuedAttachments }) => { queueMessage: async ({ message: queuedText, attachments: queuedAttachments }) => {
queueMessage(queuedText, queuedAttachments); if (submitBehavior !== "preserve-and-lock") {
beginSubmit(queuedAttachments);
}
await enqueueMessage(queuedText, queuedAttachments);
}, },
submitMessage: async ({ message: submitText, attachments: submitAttachments }) => { submitMessage: async ({ message: submitText, attachments: submitAttachments }) => {
if (submitBehavior !== "preserve-and-lock") { if (submitBehavior !== "preserve-and-lock") {
@@ -1972,9 +1890,10 @@ function ComposerContentImpl({
beginSubmit, beginSubmit,
clearDraft, clearDraft,
completeSubmit, completeSubmit,
enqueueMessage,
hasExternalContent, hasExternalContent,
isAgentRunning, isAgentRunning,
queueMessage, supportsQueue,
setSelectedAttachments, setSelectedAttachments,
replaceUserInput, replaceUserInput,
stagedSwitch, stagedSwitch,
@@ -1996,12 +1915,10 @@ function ComposerContentImpl({
} }
const pluginSlashCommand = resolvePluginClientSlashCommand({ const pluginSlashCommand = resolvePluginClientSlashCommand({
text: payload.text, text: payload.text,
hasAttachments: outgoingAttachments.length > 0,
commands: pluginClientSlashCommands, commands: pluginClientSlashCommands,
}); });
if (pluginSlashCommand) { if (pluginSlashCommand && runPluginClientSlashCommand(pluginSlashCommand)) return;
runPluginClientSlashCommand(pluginSlashCommand, outgoingAttachments.length > 0);
return;
}
if (blurOnSubmit) { if (blurOnSubmit) {
messageInputRef.current?.blur(); messageInputRef.current?.blur();
@@ -2224,39 +2141,25 @@ function ComposerContentImpl({
}); });
}, [agentId, hasAgent, isConnected, serverId, voice]); }, [agentId, hasAgent, isConnected, serverId, voice]);
const handleEditQueuedMessage = useCallback( const handleRestoreQueuedMessage = useCallback(
(id: string) => { (message: RestoredQueuedMessage) => {
const result = editQueuedComposerMessage({ replaceUserInput(message.text);
agentId, setSelectedAttachments(message.attachments);
messageId: id, if (message.providerSwitch) {
queue: queueWriter, useStagedProviderSwitchStore.getState().stage(serverId, agentId, message.providerSwitch);
});
if (!result) return;
useSessionStore.getState().setQueuedSendError(serverId, agentId, null);
replaceUserInput(result.text);
setSelectedAttachments(result.attachments);
},
[agentId, queueWriter, replaceUserInput, serverId, setSelectedAttachments],
);
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);
} }
focusInput();
}, },
[agentId, queueWriter, serverId, submitMessage, t], [agentId, focusInput, 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"));
},
[t],
); );
const handleQueue = useCallback( const handleQueue = useCallback(
@@ -2271,21 +2174,19 @@ function ComposerContentImpl({
} }
const pluginSlashCommand = resolvePluginClientSlashCommand({ const pluginSlashCommand = resolvePluginClientSlashCommand({
text: payload.text, text: payload.text,
hasAttachments: outgoingAttachments.length > 0,
commands: pluginClientSlashCommands, commands: pluginClientSlashCommands,
}); });
if (pluginSlashCommand) { if (pluginSlashCommand && runPluginClientSlashCommand(pluginSlashCommand)) return;
runPluginClientSlashCommand(pluginSlashCommand, outgoingAttachments.length > 0); void sendMessageWithContent(payload.text, outgoingAttachments);
return;
}
queueMessage(payload.text, outgoingAttachments);
}, },
[ [
attachments, attachments,
buildOutgoingAttachments, buildOutgoingAttachments,
pluginClientSlashCommands, pluginClientSlashCommands,
queueMessage,
runClientSlashCommand, runClientSlashCommand,
runPluginClientSlashCommand, runPluginClientSlashCommand,
sendMessageWithContent,
], ],
); );
@@ -2404,14 +2305,7 @@ function ComposerContentImpl({
); );
const hasGithubAttachment = useMemo( 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], [selectedAttachments],
); );
// Composer stays mounted for each focused agent, so avoid a forge CLI call // Composer stays mounted for each focused agent, so avoid a forge CLI call
@@ -2657,18 +2551,6 @@ 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( const autocompleteConfiguration = useMemo(
() => ({ () => ({
setUserInput: replaceUserInput, setUserInput: replaceUserInput,
@@ -2711,8 +2593,7 @@ function ComposerContentImpl({
// Focusing the composer on a touch screen raises the on-screen keyboard over the conversation. // Focusing the composer on a touch screen raises the on-screen keyboard over the conversation.
const messageInputAutoFocus = autoFocus && isDesktopWebBreakpoint && hasFinePointer; const messageInputAutoFocus = autoFocus && isDesktopWebBreakpoint && hasFinePointer;
const submitLoadingPressHandler = isAgentRunning ? handleCancelAgent : undefined; const submitLoadingPressHandler = isAgentRunning ? handleCancelAgent : undefined;
const displayError = const displayError = externalError || sendError || failedStartupSettings?.errorMessage;
externalError || sendError || failedStartupSettings?.errorMessage || queuedSendError;
const sendErrorNode = useMemo( const sendErrorNode = useMemo(
() => () =>
displayError ? ( displayError ? (
@@ -2783,6 +2664,60 @@ function ComposerContentImpl({
t, 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 ( return (
<> <>
<ComposerKeyboardRegistration <ComposerKeyboardRegistration
@@ -2807,101 +2742,63 @@ function ComposerContentImpl({
dataSet={isFullscreen ? undefined : CHAT_COLUMN_RAIL_DATASET} dataSet={isFullscreen ? undefined : CHAT_COLUMN_RAIL_DATASET}
> >
<View style={inputAreaContentStyle}> <View style={inputAreaContentStyle}>
{isFullscreen ? null : queueList} {!isFullscreen && hasAgent && supportsQueue ? (
<ComposerQueueTrack
serverId={serverId}
agentId={agentId}
sendBehavior={appSettings.sendBehavior}
providerLabel={providerLabel}
onRestore={handleRestoreQueuedMessage}
onAlreadySending={handleQueuedMessageAlreadySending}
onError={handleQueueError}
/>
) : null}
{isFullscreen ? null : stagedSwitchBannerNode} {isFullscreen ? null : stagedSwitchBannerNode}
{!isFullscreen && sendErrorNode} {!isFullscreen && sendErrorNode}
<ComposerAutocompleteBinding <ComposerInputCap fullscreen={isFullscreen}>
text={textSource} <ComposerAutocompleteBinding
cursor={cursor}
recall={recall}
inputRef={messageInputRef}
anchorStyle={messageInputContainerStyle}
show={mode.showAutocomplete && !isFullscreen && !isComposerLocked}
ref={autocompleteRef}
configuration={autocompleteConfiguration}
>
<ComposerForgeBinding
text={textSource} text={textSource}
configuration={forgeConfiguration} cursor={cursor}
ref={forgeAutoAttachRef} recall={recall}
onResolvingChange={setIsForgeResolving} inputRef={messageInputRef}
/> anchorStyle={messageInputContainerStyle}
show={mode.showAutocomplete && !isFullscreen && !isComposerLocked}
{/* MessageInput handles everything: text, dictation, attachments, all buttons */} ref={autocompleteRef}
<RenderProfile id="MessageInput"> configuration={autocompleteConfiguration}
<StableMessageInput >
ref={messageInputRef} <ComposerForgeBinding
editingSession={editingSession} text={textSource}
submissionError={sendErrorNode} configuration={forgeConfiguration}
value={textSource.getSnapshot()} ref={forgeAutoAttachRef}
onChangeText={setUserInput} onResolvingChange={setIsForgeResolving}
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}
/> />
</RenderProfile>
<Combobox {/* MessageInput handles everything: text, dictation, attachments, all buttons */}
options={githubSearchOptions} {messageInputNode}
value="" <Combobox
onSelect={noop} options={githubSearchOptions}
keepOpenOnSelect value=""
searchable onSelect={noop}
searchPlaceholder={t("composer.github.searchPlaceholder", { keepOpenOnSelect
context: forgePresentation.changeRequestContext, searchable
})} searchPlaceholder={t("composer.github.searchPlaceholder", {
title={t("composer.github.title", { context: forgePresentation.changeRequestContext,
context: forgePresentation.changeRequestContext, })}
})} title={t("composer.github.title", {
open={isGithubPickerOpen} context: forgePresentation.changeRequestContext,
onOpenChange={handleGithubPickerOpenChange} })}
onSearchQueryChange={setGithubSearchQuery} open={isGithubPickerOpen}
desktopPlacement="top-start" onOpenChange={handleGithubPickerOpenChange}
anchorRef={attachButtonRef} onSearchQueryChange={setGithubSearchQuery}
emptyText={githubEmptyText} desktopPlacement="top-start"
renderOption={renderGithubPickerOption} anchorRef={attachButtonRef}
/> emptyText={githubEmptyText}
{pluginAttachments.picker} renderOption={renderGithubPickerOption}
</ComposerAutocompleteBinding> />
{pluginAttachments.picker}
</ComposerAutocompleteBinding>
</ComposerInputCap>
</View> </View>
</View> </View>
</View> </View>
@@ -3027,43 +2924,6 @@ const styles = StyleSheet.create((theme: Theme) => ({
buttonDisabled: { buttonDisabled: {
opacity: 0.5, 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: { stagedSwitchBanner: {
flexDirection: "row", flexDirection: "row",
alignItems: "center", alignItems: "center",
@@ -3093,8 +2953,6 @@ const styles = StyleSheet.create((theme: Theme) => ({
const ThemedAttachmentSpinner = withUnistyles(LoadingSpinner); const ThemedAttachmentSpinner = withUnistyles(LoadingSpinner);
const ThemedArrowRightLeft = withUnistyles(ArrowRightLeft); const ThemedArrowRightLeft = withUnistyles(ArrowRightLeft);
const ThemedPencil = withUnistyles(Pencil);
const ThemedArrowUp = withUnistyles(ArrowUp);
const ThemedGitPullRequest = withUnistyles(GitPullRequest); const ThemedGitPullRequest = withUnistyles(GitPullRequest);
const ThemedCircleDot = withUnistyles(CircleDot); const ThemedCircleDot = withUnistyles(CircleDot);
const ThemedAudioLines = withUnistyles(AudioLines); const ThemedAudioLines = withUnistyles(AudioLines);
@@ -3104,7 +2962,6 @@ const ThemedClipboardPaste = withUnistyles(ClipboardPaste);
const ThemedFileText = withUnistyles(FileText); const ThemedFileText = withUnistyles(FileText);
const iconForegroundMapping = (theme: Theme) => ({ color: theme.colors.foreground }); const iconForegroundMapping = (theme: Theme) => ({ color: theme.colors.foreground });
const iconForegroundMutedMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted }); const iconForegroundMutedMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
const iconAccentForegroundMapping = (theme: Theme) => ({ color: theme.colors.accentForeground });
function renderForgeAttachmentIcon(icon: string): ReactElement { function renderForgeAttachmentIcon(icon: string): ReactElement {
return ( return (
@@ -1,67 +0,0 @@
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();
}
});
+6 -29
View File
@@ -33,15 +33,6 @@ const COPIED_STYLES = [
"paddingLeft", "paddingLeft",
] as const; ] 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({ export function useComposerHeight({
getText, getText,
textareaRef, textareaRef,
@@ -77,29 +68,15 @@ export function useComposerHeight({
mirror.style[property] = computedStyle[property]; mirror.style[property] = computedStyle[property];
} }
mirror.style.width = `${sourceWidth}px`; mirror.style.width = `${sourceWidth}px`;
mirror.value = text.endsWith("\n") ? `${text} ` : text;
const padding = const padding =
parseFloat(computedStyle.paddingTop) + parseFloat(computedStyle.paddingBottom); parseFloat(computedStyle.paddingTop) + parseFloat(computedStyle.paddingBottom);
const lineHeight = parseFloat(computedStyle.lineHeight); const lineHeight = parseFloat(computedStyle.lineHeight);
const { maxHeight: currentMax, onRenderedLinesChange: reportLines } = paramsRef.current; if (lineHeight > 0)
// Complete hard lines can prove the height cap and the three-line fullscreen threshold. paramsRef.current.onRenderedLinesChange?.(
// Keep measuring the whole draft when the prefix cannot prove both. Math.round((mirror.scrollHeight - padding) / lineHeight),
const measuredText = );
Number.isFinite(currentMax) && lineHeight > 0 setBoundedHeight(mirror.scrollHeight);
? 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], [setBoundedHeight, textareaRef],
); );
+10 -3
View File
@@ -196,9 +196,16 @@ describe("dictation transcript behavior", () => {
describe("composer send behavior", () => { describe("composer send behavior", () => {
it("sends immediately when queue mode cannot advance past a permission", () => { it("sends immediately when queue mode cannot advance past a permission", () => {
expect(resolveActiveSendBehavior("queue", true)).toBe("interrupt"); expect(resolveActiveSendBehavior("queue", true, true)).toBe("interrupt");
expect(resolveActiveSendBehavior("queue", false)).toBe("queue"); expect(resolveActiveSendBehavior("queue", false, true)).toBe("queue");
expect(resolveActiveSendBehavior("steer", true)).toBe("steer"); 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");
}); });
function actions() { function actions() {
+6 -1
View File
@@ -9,8 +9,13 @@ export type SendBehavior = ActiveTurnBehavior | "queue";
export function resolveActiveSendBehavior( export function resolveActiveSendBehavior(
sendBehavior: SendBehavior, sendBehavior: SendBehavior,
hasPendingPermission: boolean, hasPendingPermission: boolean,
hostHasMessageQueue: boolean,
): SendBehavior { ): SendBehavior {
return sendBehavior === "queue" && hasPendingPermission ? "interrupt" : 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";
} }
interface ComposerSurfaceState { interface ComposerSurfaceState {
@@ -9,6 +9,7 @@ export {
isStagedProviderSwitchInFlight, isStagedProviderSwitchInFlight,
settleCommittedProviderSwitch, settleCommittedProviderSwitch,
settleStagedProviderSwitch, settleStagedProviderSwitch,
toStagedProviderSwitch,
useFailedStartupSettings, useFailedStartupSettings,
useIsStagedProviderSwitchInFlight, useIsStagedProviderSwitchInFlight,
useStagedProviderSwitch, useStagedProviderSwitch,

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