mirror of
https://github.com/getpaseo/paseo.git
synced 2026-12-01 20:56:02 +00:00
Compare commits
43
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
32fe3074a0 | ||
|
|
5b1ccba548 | ||
|
|
6cffd3994d | ||
|
|
4101519112 | ||
|
|
da58a57998 | ||
|
|
f76fd024fb | ||
|
|
2f7e22e621 | ||
|
|
9592f88fdf | ||
|
|
0d244c192a | ||
|
|
6354565748 | ||
|
|
e06218e9f4 | ||
|
|
fec7454c31 | ||
|
|
5adfd4961c | ||
|
|
d1ee5dee63 | ||
|
|
1adabf70c8 | ||
|
|
87427c2aa1 | ||
|
|
cfa4536358 | ||
|
|
7f75b0e166 | ||
|
|
b0ca089d54 | ||
|
|
91e7713721 | ||
|
|
e20ea2aaf2 | ||
|
|
806214d285 | ||
|
|
e5edb6efd5 | ||
|
|
0a0544fa4f | ||
|
|
914143e8b0 | ||
|
|
1969fb331c | ||
|
|
16b4c0b25c | ||
|
|
82ef763fc2 | ||
|
|
b6220fd9c6 | ||
|
|
c3e627e1cb | ||
|
|
78633752b1 | ||
|
|
22a4447431 | ||
|
|
5b99e6699c | ||
|
|
9626465912 | ||
|
|
40a8d9bdd2 | ||
|
|
576a1430a0 | ||
|
|
4e31842453 | ||
|
|
0b5b9b5111 | ||
|
|
bc626e838d | ||
|
|
24a2e8f07c | ||
|
|
809650f0de | ||
|
|
753947a118 | ||
|
|
6fffbb8c18 |
+19
-1
@@ -44,6 +44,12 @@ The QR code or pairing link is the trust anchor. It contains the daemon's public
|
||||
|
||||
When a daemon password is configured, relay clients send it in the encrypted `hello` message, so the relay never sees it. The daemon rejects a relay client that sends a wrong password or none, so a leaked pairing link alone does not grant access to a password-protected daemon.
|
||||
|
||||
The app binds each saved host to one daemon key. If you open a pairing link for a saved host with a different key, the app shows a "Host identity changed" warning. The warning displays both the saved key fingerprint and the new one.
|
||||
|
||||
If you cancel, the app leaves your saved host unchanged. If you replace the host identity, the app removes all relay connections to the old key and clears the saved password. The app never sends a password saved for one daemon to another.
|
||||
|
||||
You will see this warning once after you reset Paseo on a host. If you did not reset that host, cancel the prompt. Someone could be trying to impersonate your host.
|
||||
|
||||
## Local daemon trust boundary
|
||||
|
||||
By default, the daemon binds to `127.0.0.1`. With no password configured, anything that can reach the daemon socket can control the daemon. Loopback is reachable by other users on the machine and by some forwarding tools.
|
||||
@@ -52,7 +58,19 @@ The daemon supports an optional shared-secret password (set via `auth.password`
|
||||
|
||||
The daemon writes a new `$PASEO_HOME/local-credential` on every run with mode `0600` and removes it on shutdown. The CLI and desktop main process read it only for the daemon whose PID lock `listen` matches their connection target. A same-user process can read this credential, so the password protects against network clients and other OS users, not processes running as the daemon user. Protect `$PASEO_HOME` accordingly. Relay traffic remains end-to-end encrypted independently of password admission.
|
||||
|
||||
Connected clients are trusted operators of the daemon user. File previews follow that authority: a preview request may read any regular file the daemon process can read, while keeping path normalization and symlink checks in the daemon file service. Workspace-relative paths remain a UI convenience, not a security boundary.
|
||||
Connected clients act with the permissions of the daemon user. Through the daemon file API, a client can access any regular file the daemon user can read outside `$PASEO_HOME`. Workspace paths are a UI convenience, so they do not restrict which files a client can open.
|
||||
|
||||
To protect daemon secrets, the file API refuses secret files inside `$PASEO_HOME` for every client, including owners. This blocks reads, writes, directory listings, watches, downloads, and path suggestions for `local-credential`, `daemon-keypair.json`, `hub-relationship.json`, `hub-credentials.json`, `hosts.json`, and `terminal-worker/`. The daemon resolves `..` and symlinks before checking the path, so it also refuses links from a workspace into those files.
|
||||
|
||||
Clients with owner permissions (`daemon.manage` and `access.manage`) can still access non-secret files inside `$PASEO_HOME`, such as `config.json` and `daemon.log`. For scoped clients without those permissions, the file API refuses all of `$PASEO_HOME` except five user-content folders:
|
||||
|
||||
- The managed worktrees folder (`worktrees/`, or `worktrees.root` when it is inside `$PASEO_HOME`)
|
||||
- `uploads/`
|
||||
- `paseo-attachments/`
|
||||
- `desktop-attachments/`
|
||||
- `plans/`
|
||||
|
||||
This restriction applies only to client file requests. Every other file the daemon user can read remains accessible. Coding agents and terminals run as the daemon user and can still read `$PASEO_HOME` directly.
|
||||
|
||||
When Paseo checks out a change request from a different repository, it does not run that workspace's `paseo.json` setup, automatic terminals, named scripts, or teardown until you explicitly run setup for that workspace. The decision lasts for the workspace and does not re-prompt after new commits. Same-repository changes, ordinary branches, local workspaces, agent launches, terminals, explicit shell commands, and metadata-generation instructions are outside this gate.
|
||||
|
||||
|
||||
+96
-24
@@ -152,7 +152,7 @@ Users can also detach an existing subagent from the subagents track. Detach is d
|
||||
|
||||
`notifyOnFinish` defaults to `true` for agent-scoped creation and prompt follow-ups because most delegated work needs to report back to the creating agent. Set it to `false` for explicit reporting or no completion callback.
|
||||
|
||||
Agent-originated messages and automatic notifications share a recipient-daemon delivery module. A queued receipt acknowledges admission before provider dispatch. The module keeps one ordered queue per recipient, and the recipient reads its prompts in the order the daemon admitted them. Nothing overtakes an older queued message. A prompt takes its place when the daemon admits it, even while the provider is still starting an earlier turn, and a message stays in the queue until the turn that carries it starts. The turn has started when the agent manager acknowledges the run start; a turn that fails after that point is not delivered again.
|
||||
Agent-originated messages and automatic notifications share a recipient-daemon delivery module. The daemon saves a queued message, then acknowledges it with a receipt, before provider dispatch. The module keeps one ordered queue per recipient, and the recipient reads its prompts in the order the daemon admitted them. Nothing overtakes an older queued message. A prompt takes its place when the daemon admits it, even while the provider is still starting an earlier turn, and a message stays in the queue until the turn that carries it starts. The turn has started when the agent manager acknowledges the run start; a turn that fails after that point is not delivered again.
|
||||
|
||||
Any sender picks `queue`, `steer`, or `interrupt` with `activeTurnBehavior`. Agent senders default to `queue`; non-agent senders (app, CLI, plugins, Hub, top-level MCP) default to `interrupt`. Each kind of prompt is released this way:
|
||||
|
||||
@@ -170,33 +170,64 @@ A command the provider accepts out of band is the one exception to admission ord
|
||||
|
||||
One provider prompt has one session mode. A batch released by a steer, an interrupt, or a person's prompt uses the latest explicit choice in it, the person's own first. Queued messages with conflicting choices keep separate ordered dispatches.
|
||||
|
||||
The pending message window is in memory. Clean shutdown flushes it, held messages included, before
|
||||
closing agents; an abrupt crash can lose queued prompts. A durable send receipt remains pending until actual dispatch
|
||||
acknowledgment, so a lost window never becomes a completed receipt. Completion waits cover queued
|
||||
admission within their original timeout and cancellation scope, and return at permission
|
||||
checkpoints and when a Stop holds the queue.
|
||||
A provider switch can wait in the queue too (`agent.provider.switch.request` with
|
||||
`activeTurnBehavior: "queue"`). The message carries the target provider and settings, shares a prompt
|
||||
with nothing, and divides the queue: what is ahead of it goes to the current provider, and it and
|
||||
what follows go to the target. A direct prompt therefore takes along only the queued rows ahead of
|
||||
the switch. Promoting the switch cuts the running turn once the target is known to be usable. A chat
|
||||
already on the target takes the message and its settings as a plain prompt. A switch that fails keeps
|
||||
the message and holds the queue; the reason is in the daemon log.
|
||||
|
||||
The queue is saved in `$PASEO_HOME/agent-queues/` ([data model](data-model.md#directory-layout)),
|
||||
and a message is saved before its receipt is sent. Inline images are first saved as uploads, so the
|
||||
queue file holds references. An empty message is refused, and a recipient holds at most 100
|
||||
messages.
|
||||
|
||||
A message is marked `dispatching` before the provider can receive it and removed when the provider
|
||||
admits it. A dispatch that is not admitted returns the message to its place. A refused turn start
|
||||
also holds the queue: retrying by itself would be refused again and would add the prompt to the
|
||||
history each time. A message that cannot be sent is removed so that it does not block the ones
|
||||
behind it.
|
||||
|
||||
Shutdown does not send the queue. It waits only for dispatches already in flight, and everything
|
||||
else stays saved, held messages included. Closing an idle runtime keeps the queue. Archiving or
|
||||
deleting the agent clears it.
|
||||
|
||||
Bootstrap restores queues before restart recovery resumes agents, and before finish subscriptions,
|
||||
change-request watches, and ingress start. A held queue stays held. Other queues are sent, after the
|
||||
resume prompt for an agent that restart recovery resumes. A crash can leave a message marked
|
||||
`dispatching`, so the daemon looks for it in the recipient's history: a message found there is
|
||||
removed, and one not found, or whose history cannot be read, is sent again.
|
||||
|
||||
A client that retries a queued message with the same `messageId` is acknowledged again at once. The
|
||||
completed send receipt is written after dispatch, and a different request under that `messageId`
|
||||
conflicts. Completion waits cover queued admission within their original timeout and cancellation
|
||||
scope, and return at permission checkpoints and when the queue is held.
|
||||
|
||||
Finish notification intent has a separate daemon-owned lifetime. The finish-subscriptions module
|
||||
persists caller, child, host, and ownership policy through an injectable store; its JSON adapter uses
|
||||
`$PASEO_HOME/finish-subscriptions.json`. Registration must commit before creation or queued-prompt
|
||||
acknowledgment promises a notification. A pending replacement retains its predecessor until dispatch
|
||||
accepts; rejected dispatch removes only the candidate. Recovery coalesces registrations for the same
|
||||
caller, child, and host into one watch.
|
||||
accepts; rejected dispatch removes only the candidate. The record keeps the prompt's `messageId`, so
|
||||
withdrawing that message removes the subscription, also after a restart. Recovery coalesces
|
||||
registrations for the same caller, child, and host into one watch.
|
||||
|
||||
Bootstrap restores these watches after repairing stale running records to `closed` and before opening
|
||||
ingress. Reading a closed child's result does not load its provider. A finish notification reports that
|
||||
the child has settled (see below); the parent decides whether its task is complete. A child chosen for restart
|
||||
recovery is observed only after its resume was sent, so the parent never hears that it was closed
|
||||
in between. Archived or deleted parents suppress delivery;
|
||||
in between. A subscription whose prompt is still queued stays pending until that prompt is
|
||||
dispatched, so a held follow-up reports nothing. Archived or deleted parents suppress delivery;
|
||||
parent-owned creation watches also stop
|
||||
reporting after detachment.
|
||||
|
||||
Intent remains stored until the parent's notification dispatch is acknowledged. Dispatch failure
|
||||
retries the captured notification; it does not change the child's reported outcome. Remote host loss
|
||||
follows the [connected-host observation policy](connected-hosts.md#delegating-agents). Shutdown stops observation before flushing message delivery, retaining
|
||||
outstanding intent. A crash after successful dispatch but before removal commits can repeat the
|
||||
notification. Clean shutdown can also flush an already queued callback while retaining its intent,
|
||||
so that callback can repeat after restart. This is an at-least-once wakeup, without turn attribution or exactly-once delivery.
|
||||
follows the [connected-host observation policy](connected-hosts.md#delegating-agents). Shutdown stops
|
||||
observation and retains outstanding intent. A final or permission notice has an id derived from its
|
||||
subscription, so observing the same outcome again while the notice is queued adds nothing. A crash
|
||||
after successful dispatch but before removal commits can repeat the notification. This is an
|
||||
at-least-once wakeup, without turn attribution or exactly-once delivery.
|
||||
|
||||
A turn end is not always a settled child. A child can end its turn with work that will start its next
|
||||
turn by itself: a running turn, queued messages, a pending provider wake-up
|
||||
@@ -205,17 +236,23 @@ wake-ups), or the child's own outstanding finish subscriptions as a caller. Hear
|
||||
crons, change-request watches, and other daemon background items never count: they are external
|
||||
triggers, not work the caller is waiting for.
|
||||
|
||||
Every turn end reports `finished` at once. When work is still pending, the notice names it and the
|
||||
subscription follows the child: each later turn end reports `finished` again, and the child settling
|
||||
with nothing pending sends a final `finished` and removes the subscription, even when the work
|
||||
drains without another turn. Reporting at once keeps a long-lived task, such as a dev server, from
|
||||
leaving the caller without the child's reply. Following is what lets the caller hear the reply a
|
||||
background task wakes up later ([#6346](https://github.com/getpaseo/paseo/issues/6346)). A work change
|
||||
that leaves work pending sends nothing. Errors, permission requests, and closes report as they
|
||||
happen. `followingSince` is stored when following starts, so a restart keeps following instead of
|
||||
waiting for another turn end. After 24 hours of following, the caller gets a final `finished` with
|
||||
the child's last reply and the subscription ends. Remote children and providers without the probe
|
||||
report their first turn end as a settled `finished`.
|
||||
Every turn end reports `finished` at once, unless the child already sent an agent message to its
|
||||
caller during that turn and started no further tool work afterwards. In that case the child's
|
||||
message already delivered its reply, so the redundant `finished` notice is skipped: a settled watch
|
||||
ends silently, and a watch with pending work keeps following silently until a later turn starts or
|
||||
the work drains. Starting another non-reporting tool call or a new turn clears that mark (plain text output after the
|
||||
message does not), and errors, permission requests, cancellations, and closes are never suppressed. When work is still
|
||||
pending on an unreported turn end, the notice names it and the subscription follows the child: each
|
||||
later turn end reports `finished` again, and the child settling with nothing pending sends a final
|
||||
`finished` and removes the subscription, even when the work drains without another turn. Reporting
|
||||
at once keeps a long-lived task, such as a dev server, from leaving the caller without the child's
|
||||
reply. Following is what lets the caller hear the reply a background task wakes up later
|
||||
([#6346](https://github.com/getpaseo/paseo/issues/6346)). A work change that leaves work pending
|
||||
sends nothing. Errors, permission requests, and closes report as they happen. `followingSince` is
|
||||
stored when following starts, so a restart keeps following instead of waiting for another turn end.
|
||||
After 24 hours of following, the caller gets a final `finished` with the child's last reply and the
|
||||
subscription ends. Remote children and providers without the probe report their first turn end as a
|
||||
settled `finished`.
|
||||
|
||||
Permission requests are notification checkpoints, not the end of that subscription. The caller is notified again after a permission response when the child finishes, errors, or requests another permission.
|
||||
The permission notification includes the normalized request plus the child and request IDs, so the caller can inspect it and respond without fetching agent status.
|
||||
@@ -397,6 +434,41 @@ that leaves the lifecycle at `error`, and replaces unread `finished` attention;
|
||||
agent would show the green dot or none. Subagents track marks are the exception: they follow the
|
||||
child's lifecycle, because the track is where a failed child stays visible.
|
||||
|
||||
## The queue track
|
||||
|
||||
The queue track is the list above the composer of the messages the host holds for the open agent
|
||||
(`packages/app/src/composer/queue/`). One list covers every sender, in the order the host sends
|
||||
them: your queued prompts, agent messages, finish notifications, and change-request updates.
|
||||
|
||||
The host owns the [queue](#relationships). `packages/app/src/agent-queue/` reads it as the open
|
||||
agent's `agent.queue` synced collection through `packages/app/src/sync/`, subscribed while the
|
||||
agent's panel is visible. A hidden panel keeps its last rows and releases the subscription. When you
|
||||
return or the host reconnects, the client sends its cursor and gets back only the rows added,
|
||||
changed, or removed since. A queued message therefore survives a reload, is sent with
|
||||
every client closed, and shows on every client that views the agent. Files upload to the host before
|
||||
the message is queued, so any device can open a row's attachments.
|
||||
|
||||
Rows take these commands:
|
||||
|
||||
- **Send now** promotes the row with your send behavior setting: `steer`, otherwise `interrupt`.
|
||||
- **Edit** is offered on your own messages only. It withdraws the row, then replaces the composer
|
||||
draft with its text and attachments, and stages the row's provider switch again. If the host
|
||||
already started sending the row, the draft stays as it is.
|
||||
- **Cancel** withdraws the row.
|
||||
|
||||
A message you send directly (`steer` or `interrupt`) takes the queued rows with it, ahead of your
|
||||
text.
|
||||
|
||||
A message sent mid-turn with a staged provider switch is queued whatever the send behavior, and its
|
||||
row names the target.
|
||||
|
||||
A row the host is `dispatching` takes no command. A held queue shows a paused notice. The notice
|
||||
does not name Stop, because a refused turn start holds the queue too.
|
||||
|
||||
A host without `server_info.features.agentMessageQueue` has no queue track. The composer offers no
|
||||
Queue action there, and a `queue` send behavior sends as `steer`, so it does not cut the running
|
||||
turn.
|
||||
|
||||
## The subagents track
|
||||
|
||||
The track is a pill at the foot of an agent's pane (`packages/app/src/subagents/track.tsx`): a count you can read at a glance, and a panel behind it — a popover on wide screens, a sheet on compact ones — holding the rows. It floats over the transcript rather than sitting in a band above the composer, so the timeline scrolls underneath it; `packages/app/src/panels/agent-tracks.tsx` owns that placement, and the pill frame is shared with the task list in `packages/app/src/composer/tracks.tsx`.
|
||||
|
||||
@@ -29,7 +29,7 @@ So arrival sets a _target_ and the reveal rate is derived from the backlog inste
|
||||
- **The coalescer is leading + trailing.** The first delta after an idle window flushes synchronously; only the rest of the burst waits for the trailing timer. Reverting to trailing-only adds a full window to the first character of every turn. Same shape and the same reason as `TerminalOutputCoalescer`.
|
||||
- **The leading flush adds a canonical row, and that is fine.** A burst's first chunk lands as its own timeline row. `mergeAssistantChunks` / `mergeReasoningChunks` in `timeline-projection.ts` join contiguous same-turn rows, and clients read the projected timeline, so history is unaffected. Tests that assert on raw rows have to account for the extra row; tests that assert on what a client sees do not.
|
||||
- **The store holds the full text; only the rendered slice is paced.** Copy, selection, the chat outline, and scroll geometry all read the same string the user can see. Pacing the store instead would leave the bottom anchor chasing a content height that is ahead of the reveal.
|
||||
- **One source assistant message is one display row.** Presentation projects plugin output and caches unchanged history. The shared [Markdown renderer](markdown-renderer.md) owns rendering on every platform. Chat paces the visible source and applies a 32,000-character render cap on web; native keeps the complete message. The native renderer keeps closed blocks in a stable head and sends the paced suffix to a separate tail view during streaming; completion reunites them for selection. This stays inside the renderer, without promoting blocks into timeline history.
|
||||
- **One source assistant message is one display row.** Presentation projects plugin output and caches unchanged history. The shared [Markdown renderer](markdown-renderer.md) owns rendering on every platform. Chat paces the visible source and applies a 32,000-character render cap on web; native keeps the complete message. While streaming, the renderer keeps closed blocks in head parts and sends the paced suffix to a separate tail; completion reunites them for selection. This stays inside the renderer, without promoting blocks into timeline history.
|
||||
- **Message identity survives completion.** Assistant row ids are source message ids. Plugin rows can replace a source, so find, scroll-to-message and history reveal still use `getStreamItemMessageId`. Width-specific measurements describe whole rendered messages.
|
||||
- **First sight of a text is revealed whole.** Only growth is paced. This is what makes history hydration, timeline replay, a virtualized row remounting on scroll, and an already-finished message all render complete on first paint without a special case for each.
|
||||
- **Leaving `phase: "streaming"` snaps the reveal.** A completed turn must never be left holding characters. `layoutStream` sets the phase, so anything outside the live head with an active turn is already complete.
|
||||
@@ -49,11 +49,19 @@ So arrival sets a _target_ and the reveal rate is derived from the backlog inste
|
||||
while text arrives, and release obsolete window caches as the reader reveals more history;
|
||||
window caches must stay bounded while their source timeline remains loaded.
|
||||
|
||||
## Native parsing cost
|
||||
## Markdown parsing cost
|
||||
|
||||
The native library reparses and measures its entire `markdown` prop on each update. During streaming, the renderer splits source at an mdast block boundary and memoizes the head, so per-frame updates parse only the tail. Boundary discovery runs when a source line completes, rather than on every reveal frame. The unfinished line and final parsed block stay in the tail, preserving list continuation, setext headings, tables and open fences. Reference-dependent source and HTML retain a larger tail because later source can change their meaning. A single long block therefore still carries its full parsing cost.
|
||||
Both engines reparse their entire `markdown` prop on each update: md4c in C++ on native, md4c in WASM plus a JSON tree on web. Source adaptation adds a full mdast parse for some text, such as any `&`, at about 1 µs per character. Rendering a growing reply whole on each reveal frame therefore makes the reply quadratic to stream.
|
||||
|
||||
Completion restores one native text view per Mermaid-delimited segment, so selection crosses prose paragraphs again. The head retains its trailing block margin while split. JS reveal remains the pacing source; native opacity animation stays disabled.
|
||||
While streaming, `createStreamingMarkdownSplitter` in `components/markdown/streaming.ts` splits the message into head parts and a tail, on every platform. The tail is the last block and the unfinished line, so list continuation, setext headings, tables and open fences render as they will when complete. Rules that keep the cost per frame flat as the reply grows:
|
||||
|
||||
- **Discovery is incremental.** The boundary moves only when a line completes, and each time the splitter parses only the source after the boundary. Blocks before it are closed and need no document context.
|
||||
- **Head parts are sealed at 2,000 characters.** Each completed block re-renders the head part it lands in. Only the last part grows, so that work stays bounded. A single head would re-render all closed blocks each time a block completes.
|
||||
- **The first part keeps its React key from the first frame to the completed message.** Completion re-renders it in place instead of remounting it, and the parts share one image occurrence key, so an image keeps its acquisition when its block moves into the head.
|
||||
|
||||
Two kinds of source fall back to a growing render, because later source can change how earlier source reads. A link definition can turn an earlier `[label]` into a link, so a message with one renders as one document until it completes. HTML needs its enclosing source, so HTML and every block after it stay in the tail. A single long block also carries its full cost.
|
||||
|
||||
Completion renders one view per Mermaid-delimited segment, so native selection crosses prose paragraphs again; while streaming it crosses only within a part. JS reveal remains the pacing source; native opacity animation stays disabled.
|
||||
|
||||
## Measuring
|
||||
|
||||
|
||||
@@ -219,9 +219,9 @@ file after the daemon confirms persistence.
|
||||
|
||||
> **Window-state v1 limitation:** only the _first_ window of a session restores and persists saved geometry (size/position/maximized). Windows opened via ⌘⇧N / second-instance / "Open in new window" open at the default size, OS-cascaded, and do not persist — this avoids every window stacking on the same restored bounds and fighting over the single window-state store. Lifting this needs per-window state keys.
|
||||
>
|
||||
> **In-app browser profile.** Every browser guest uses one stable persistent Electron session, so cookies, authentication, cache, and site storage are shared across tabs, workspaces, and desktop windows and survive tab or app closure. Browser identity is independent of that storage partition: after every `did-attach`, the renderer explicitly registers its browser id, workspace id, and current guest `WebContents` id, and main accepts the registration only when that guest belongs to the calling renderer and the shared profile. Registration is intentionally repeated because reparenting a retained `<webview>` can replace its guest without replacing the DOM element. Settings > General > Clear browser data is the sole profile-deletion path; it clears the shared session and reloads live guests without deleting saved tabs or URLs.
|
||||
> **In-app browser profiles.** Each local browser tab runs in a persistent Electron partition and can switch profiles at any time; switching replaces the `<webview>` under the new partition and reloads the current URL in that profile's session. Partition names are the identity: `persist:paseo-browser` is **Default** and preserves cookies from before profiles; `persist:paseo-profile-<slug>` is a named profile. Display names and colors live in the main-owned catalog `<userData>/browser-profiles.json`, so editing a profile's name or color keeps sign-ins intact and updates open tabs live. Main admits only `persist:paseo-browser`, `persist:paseo-profile-<slug>`, and active host-proxy partitions (`persist:paseo-browser-host-<16hex>`) at `will-attach-webview`. The tab's chosen profile slug lives in its `workspace-browser-store` record. After every `did-attach`, the renderer registers its browser id, workspace id, partition, and current guest `WebContents` id, and main accepts it only when that guest belongs to the calling renderer and its session matches the partition. Registration is intentionally repeated because reparenting a retained `<webview>` can replace its guest without replacing the DOM element. Settings > Chat & panes manages profiles: clearing a profile clears its storage/cache and reloads its open tabs; removing a named profile closes its open tabs, removes it from the catalog, clears its session, and deletes its `Partitions/paseo-profile-<slug>` directory from disk. Default cannot be removed.
|
||||
>
|
||||
> **In-app browser window opens.** Ordinary link opens, including Shift-clicked links, become Paseo workspace tabs. Script-created opens with popup features or a named window target and POST-backed opens remain secured Electron child windows in the shared browser profile, preserving `window.opener`, `postMessage`, named-window reuse, request bodies, and `window.close()` for OAuth, payment, and similar popup protocols. Unsupported URL schemes are denied before either path.
|
||||
> **In-app browser window opens.** Ordinary link opens, including Shift-clicked links, become Paseo workspace tabs and inherit the opener tab's browser profile. Script-created opens with popup features or a named window target and POST-backed opens remain secured Electron child windows in the opener’s browser profile, preserving `window.opener`, `postMessage`, named-window reuse, request bodies, and `window.close()` for OAuth, payment, and similar popup protocols. Unsupported URL schemes are denied before either path.
|
||||
>
|
||||
> **In-app browser ownership.** Each registered guest records its owning host window. The active browser is keyed by `(host window, workspace)`, and application-menu Reload / Force Reload resolve only within the window Electron supplies to the menu callback. A non-null active update must name a browser owned by that host; a null update clears only that host/workspace. Browser automation continues to target explicit browser ids returned by `browser_new_tab` or `browser_list_tabs`.
|
||||
>
|
||||
|
||||
@@ -37,7 +37,7 @@ npm run build:main --workspace=@getpaseo/desktop
|
||||
PASEO_CAPTURE_HARNESS_GROUP=automation npm run capture-harness --workspace=@getpaseo/desktop
|
||||
```
|
||||
|
||||
Run the shared browser profile fixture with:
|
||||
Run the persistent browser profile fixture with:
|
||||
|
||||
```bash
|
||||
PASEO_CAPTURE_HARNESS_GROUP=browser-profile npm run capture-harness --workspace=@getpaseo/desktop
|
||||
@@ -55,10 +55,11 @@ window movement, including button clicks and a portal over the titlebar. Leave
|
||||
the mouse idle during this group. It reads the app's production CSS and writes
|
||||
screenshots and window bounds to the output directory.
|
||||
|
||||
The browser profile group runs two Electron processes in sequence. It verifies that each
|
||||
renderer-side `did-attach` identity maps to the correct main-process guest, that two live
|
||||
tabs share cookies and local storage through one persistent session, and that the data is
|
||||
still present after the first Electron process exits and the second starts.
|
||||
The browser profile group launches two Electron processes against the same test origin
|
||||
and user data. It matches renderer registrations to the main-process guests, checks sharing
|
||||
within a profile and isolation between named profiles, and verifies that a child popup
|
||||
inherits its opener’s session. The second launch checks the saved cookies and local storage.
|
||||
The toolbar profile journey runs in the [desktop browser regression](testing.md#desktop-browser-regression).
|
||||
|
||||
The automation group uses a real guest webview to verify the page-side ref contract:
|
||||
ARIA-like snapshot text includes headings, static text, and controls; refs survive
|
||||
|
||||
@@ -60,6 +60,9 @@ $PASEO_HOME/
|
||||
│ └── {agentId}.json # One file per agent
|
||||
├── schedules/
|
||||
│ └── {scheduleId}.json # One file per schedule
|
||||
├── agent-queues/
|
||||
│ ├── {agentId}.json # Undelivered messages for one agent; removed when empty
|
||||
│ └── {agentId}.json.corrupt.{ms} # Unreadable queue file, set aside at startup
|
||||
├── projects/
|
||||
│ ├── projects.json # Project registry
|
||||
│ ├── workspaces.json # Workspace registry
|
||||
|
||||
+2
-2
@@ -255,9 +255,9 @@ Status pills use the status token for text on the shared `surface3` and `border`
|
||||
|
||||
Status dots — the small filled circles next to a host or agent name — are `borderRadius.full` filled with the status token. Which token a given agent state maps to is owned by `getStatusDotColor` (`packages/app/src/utils/status-dot-color.ts`); a row, a group header, and a project icon all call it rather than restating the mapping. They sit in the trailing slot of a sidebar row or as a leading marker on a status pill.
|
||||
|
||||
Identity badges — the project icon, the sidebar host badge, and the PR-panel participant avatar — do not use the theme palette. They draw from the fixed ten-color identity table in `packages/app/src/styles/identity-colors.ts`, whose hexes are held to one contrast band so a color identifies rather than ranks. Project icons and PR avatars use it as a fill with a white letter — that is `identityColor`, one theme-independent hex per identity. Host badges use it as a _foreground_ on both the glyph and the label, which is a different contrast problem that the fill table cannot solve: no single hex clears 4.5:1 against both a near-white and a dark sidebar. Foregrounds therefore come from `identityForeground(name, colorScheme)`, one set per scheme, hue unchanged. That set is generated on the **status family's** lightness and chroma fraction, because a meta row puts a host badge beside a CI check and a diff stat, and two families at different lightness make the brighter one shout. Change the status band and this one changes with it. A host with no color assigned falls back to `foregroundMuted`. The table is theme-independent by design; do not fork it per theme, and do not add hexes to it without recomputing the band.
|
||||
Identity badges — the project icon, the sidebar host badge, workspace label chips, browser profile badges, and the PR-panel participant avatar — do not use the theme palette. They draw from the fixed ten-color identity table in `packages/app/src/styles/identity-colors.ts`, whose hexes are held to one contrast band so a color identifies rather than ranks. Project icons and PR avatars use it as a fill with a white letter — that is `identityColor`, one theme-independent hex per identity. Host badges use it as a _foreground_ on both the glyph and the label, which is a different contrast problem that the fill table cannot solve: no single hex clears 4.5:1 against both a near-white and a dark sidebar. Foregrounds therefore come from `identityForeground(name, colorScheme)`, one set per scheme, hue unchanged. That set is generated on the **status family's** lightness and chroma fraction, because a meta row puts a host badge beside a CI check and a diff stat, and two families at different lightness make the brighter one shout. Change the status band and this one changes with it. A host with no color assigned falls back to `foregroundMuted`. Translucent badge and chip grounds behind identity-colored ink come from `identityTint(name, colorScheme)` (12% light / 16% dark, matching `status*Tint`). For an identity-colored icon inside a tinted circle — such as browser profiles in toolbars, menus, and settings rows — use `<IdentityIconBadge>` (`packages/app/src/components/ui/identity-icon-badge.tsx`), which pairs `identityTint` with `identityForeground` and falls back to `interactionHighlight` + `foregroundMuted` when uncolored. The table is theme-independent by design; do not fork it per theme, and do not add hexes to it without recomputing the band.
|
||||
|
||||
New status pills use `<StatusBadge>`. Identity, shortcut, and interactive link badges remain separate because color does not encode status there.
|
||||
New status pills use `<StatusBadge>`. Identity icon badges use `<IdentityIconBadge>`. Identity, shortcut, and interactive link badges remain separate because color does not encode status there.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -324,13 +324,10 @@ Fabric's transform-free `measureLayout` instead. Re-measure when `isMoving`
|
||||
settles; the composer's resting position changes as the draft grows.
|
||||
|
||||
A measured rect is an asynchronous copy, so it lands after the anchor's new
|
||||
layout has painted. Layout shifts while a surface is open: a wrapped line, a
|
||||
toggled or resized sidebar, a split-pane drag, a sibling button appearing, or a
|
||||
window resize. Use `useAnchorLayoutObserver` from `@/components/ui/anchor` so
|
||||
anchored surfaces follow those moves: on web it watches the anchor, its layout
|
||||
ancestors, the host, and element movement, committing placement with `flushSync`
|
||||
after layout and before paint; on native it listens for `Dimensions` changes.
|
||||
On native autocomplete, a Reanimated frame callback
|
||||
layout has painted. The composer resizes while the autocomplete is open: a
|
||||
wrapped line, cleared text, a window resize. On web a `ResizeObserver` reads
|
||||
the anchor's rect against the layer and commits the placement with `flushSync`,
|
||||
which runs after layout and before paint. On native a Reanimated frame callback
|
||||
reads only the anchor's height on the UI thread and holds its bottom edge at
|
||||
the rest measurement. A height carries no transform. On iOS the absolute
|
||||
position does not follow the keyboard while it moves: the lift runs on the
|
||||
|
||||
+2
-2
@@ -57,8 +57,8 @@ Authoritative terminology. UI label wins. Don't invent synonyms; use what's here
|
||||
- **Composer toolbar** — The bottom control row inside the composer input. Contains agent controls, attachment button, voice controls, and stop/send controls. Code: `leftContent`, `beforeVoiceContent`, and `rightContent` slots in `MessageInput` (`packages/app/src/composer/input/input.tsx`). Forbidden: "Status bar".
|
||||
- **Agent controls** — Provider, model, mode, thinking, and provider-feature controls for an agent or draft agent. Code: `AgentControls` / `DraftAgentControls` (`packages/app/src/composer/agent-controls/index.tsx`). Forbidden: "Agent status bar".
|
||||
- **Composer footer** — Optional area rendered below the composer input but still inside the keyboard-shifted composer layout. Code: `Composer.footer` (`packages/app/src/composer/index.tsx`).
|
||||
- **Composer track** — A contextual lane at the foot of a pane, by the composer input. Specific tracks use the `<thing> track` form: **Queue track**, **Subagents track**, **Tasks track**. The subagents and tasks tracks are pills floating over the transcript, each opening a panel with its rows; the queue track is a lane inside the composer itself. Code: queue track inside `Composer` (`packages/app/src/composer/index.tsx`), pill and panel frame in `packages/app/src/composer/tracks.tsx`, `SubagentsTrack` (`packages/app/src/subagents/track.tsx`), `AgentTaskList` (`packages/app/src/composer/task-list/index.tsx`).
|
||||
- **Steer** — A follow-up admitted into an agent's already-running turn instead of interrupting it. Interrupting the turn discards steers the provider has not read yet; there is no take-back short of that, and no provider offers one. The stop button and Escape both interrupt. A steer the provider never read keeps its transcript row, matching Codex. Sending while the agent waits on a permission denies that request first, so the message reaches the same turn instead of stalling behind it. UI: "Send and steer". Code: `steerActiveTurn` (`packages/server/src/server/agent/agent-sdk-types.ts`). Don't confuse with **Queue track**, which holds messages client-side until the turn ends and never enters the running turn. An agent sender's `activeTurnBehavior: "steer"` (CLI `--behavior steer`) means the same as a person's steer. Agent senders default to `queue` instead: the daemon holds the message until the running turn ends, as the queue track does for a person. Forbidden: "Delivery", "Queued prompt".
|
||||
- **Composer track** — A contextual lane at the foot of a pane, by the composer input. Specific tracks use the `<thing> track` form: **Queue track**, **Subagents track**, **Tasks track**. The subagents and tasks tracks are pills floating over the transcript, each opening a panel with its rows; the [queue track](agent-lifecycle.md#the-queue-track) is a lane inside the composer itself. Code: `ComposerQueueTrack` (`packages/app/src/composer/queue/track.tsx`), pill and panel frame in `packages/app/src/composer/tracks.tsx`, `SubagentsTrack` (`packages/app/src/subagents/track.tsx`), `AgentTaskList` (`packages/app/src/composer/task-list/index.tsx`).
|
||||
- **Steer** — A follow-up admitted into an agent's already-running turn instead of interrupting it. Interrupting the turn discards steers the provider has not read yet; there is no take-back short of that, and no provider offers one. The stop button and Escape both interrupt. A steer the provider never read keeps its transcript row, matching Codex. Sending while the agent waits on a permission denies that request first, so the message reaches the same turn instead of stalling behind it. UI: "Send and steer". Code: `steerActiveTurn` (`packages/server/src/server/agent/agent-sdk-types.ts`). Don't confuse with **Queue track**, which lists the messages the host holds until the turn ends. A queued message does not enter the running turn. An agent sender's `activeTurnBehavior: "steer"` (CLI `--behavior steer`) means the same as a person's steer. Agent senders default to `queue` instead: the daemon holds the message until the running turn ends, as it does for a person's queued message. Forbidden: "Delivery", "Queued prompt".
|
||||
- **Subagent** — User-facing term for an agent session related to a parent agent session. Use **subagents** in UI copy and docs. Internal daemon/provider plumbing may say "child agent" or `child_session`, especially for provider-managed imports; do not surface "child agent" as a product term.
|
||||
- **Attachment tray** — The selected-attachments row inside the composer input, above the text input. Code: `renderAttachmentTray` (`packages/app/src/composer/index.tsx`). Forbidden: "Attachment bar".
|
||||
- **Fork** — Starting a NEW agent session seeded with a copy of another session's curated chat history. The history rides along as a `chat_history` composer attachment on a draft; the fork does **not** resume or branch the provider-side session, and the source session keeps running untouched. Two targets, one surface, one RPC (`agent.fork_context`, gated on the `agentForkContext` host feature). UI: the fork menu lives in the assistant turn footer and offers "Fork in a new tab" / "Fork in a new workspace". On a **completed** turn it sits beside the copy button and pins a boundary to that turn, so the fork stops where the turn ended. On the **in-flight** turn it sits beside the progress loader and elapsed timer, and omits the boundary entirely — `selectForkContextRows` projects the whole timeline when no boundary is given, so the fork captures everything **up to now**, including the response still streaming. That omission is what makes mid-run forking work; pinning a boundary there would silently drop the live response. Forbidden on provider-subagent (read-only) panes. Code: `useForkAgent` (`packages/app/src/hooks/use-fork-agent.ts`), `selectForkContextRows` (`packages/server/src/server/agent/activity-curator.ts`). Don't confuse with: git fork (unrelated; Paseo has no such concept), **Worktree** (filesystem isolation, not history copying).
|
||||
|
||||
+1
-1
@@ -4,7 +4,7 @@ Paseo Hub is an explicit opt-in connection from one Paseo daemon to one Hub. Run
|
||||
not register it with a Hub. The relationship begins only when a user runs
|
||||
`paseo hub connect [url]` from the daemon machine with an explicit API key or matching stored CLI login.
|
||||
|
||||
The human CLI login and daemon relationship are separate identities. `paseo hub login [url]` stores a durable organization-scoped CLI credential keyed by normalized Hub origin under `PASEO_HOME`. Interactive login optionally connects the local daemon, then points to the Hub UI for trigger configuration; it does not scaffold or deploy configuration. `paseo hub init` remains the explicit triggers-as-code scaffold: it writes one self-contained organization trigger under `.paseo/triggers/`, validates it through the trigger API, and optionally installs it. `paseo hub deploy` validates and installs every trigger in that directory; passing `--project` keeps deploying the legacy project bundle instead. `paseo hub export [directory]` writes the active organization's current triggers in the same layout, using the active login unless another Hub or API key is selected. Origin resolution uses explicit command input, `PASEO_HUB_URL`, active login, then `https://hub.paseo.sh`. Connect uses exact-origin authority to request a one-time enrollment token, then passes only that token to the daemon. The daemon generates and persists its own relationship credential.
|
||||
The human CLI login and daemon relationship are separate identities. `paseo hub login [url]` stores a durable organization-scoped CLI credential keyed by normalized Hub origin under `PASEO_HOME`. Interactive login optionally connects the local daemon, then points to the Hub UI for trigger configuration; it does not scaffold or deploy configuration. `paseo hub init` remains the explicit triggers-as-code scaffold: it writes one self-contained organization trigger under `.paseo/triggers/`, validates it through the trigger API, and optionally installs it. `paseo hub deploy` validates and installs every trigger in that directory; passing `--project` keeps deploying the legacy project bundle instead. `paseo hub export [directory]` writes the active organization's current triggers in the same layout, using the active login unless another Hub or API key is selected. `paseo hub run` dispatches a `manual.run` trigger through `POST /api/v1/manual-runs`, which takes inputs and prompt as one string; the CLI rejects what Hub would silently read as prompt text (`packages/cli/src/commands/hub/run/`). Origin resolution uses explicit command input, `PASEO_HUB_URL`, active login, then `https://hub.paseo.sh`. Connect uses exact-origin authority to request a one-time enrollment token, then passes only that token to the daemon. The daemon generates and persists its own relationship credential.
|
||||
|
||||
## Connection and authority
|
||||
|
||||
|
||||
@@ -2,11 +2,11 @@
|
||||
|
||||
Use `MarkdownRenderer` for chat replies, file previews, plans, pull requests and changelog content. It uses `react-native-enriched-markdown` on iOS, Android and web. Keep source adaptation and renderer configuration in `components/markdown`; consumers supply Markdown and, when needed, its file location.
|
||||
|
||||
Native selection belongs to the library's text view. Keep an assistant message in one row so selection can cross paragraphs, headings and lists. Code blocks and tables use the library's native views and their selection behavior. Web uses browser selection over semantic HTML. Once its WASM parser is initialized, the library parses synchronously for the first commit of each mounted row; an empty interim row would corrupt virtualized measurements and move the reader. Chat owns paced reveal, the web render cap, message identity and list measurement. Native renders completed messages together. While streaming, it keeps closed blocks in one head view and updates a separate tail, then reunites the text on completion. See [native parsing cost](agent-stream-performance.md#native-parsing-cost) for the boundary and pacing constraints.
|
||||
Native selection belongs to the library's text view. Keep an assistant message in one row so selection can cross paragraphs, headings and lists. Code blocks and tables use the library's native views and their selection behavior. Web uses browser selection over semantic HTML. Once its WASM parser is initialized, the library parses synchronously for the first commit of each mounted row; an empty interim row would corrupt virtualized measurements and move the reader. Chat owns paced reveal, the web render cap, message identity and list measurement. A completed message renders as one document. While streaming, the renderer keeps closed blocks in head parts and updates a separate tail, then reunites the text on completion. See [Markdown parsing cost](agent-stream-performance.md#markdown-parsing-cost) for the boundary and pacing constraints.
|
||||
|
||||
## Block spacing
|
||||
|
||||
Every block is separated by one gap, `density.blockGap`: 12 on compact layouts, 16 wider. Inside the library's text, every element style ends with that gap and the library drops it after the last block. Views stacked outside the library (Mermaid segments, streaming head and tail) use the same gap through `MarkdownBlockStack`. Do not give a block type its own margins; change the gap.
|
||||
Every block is separated by one gap, `density.blockGap`: 12 on compact layouts, 16 wider. Inside the library's text, every element style ends with that gap and the library drops it after the last block. Views stacked outside the library (Mermaid segments, streaming head parts and tail) use the same gap through `MarkdownBlockStack`. Do not give a block type its own margins; change the gap.
|
||||
|
||||
## Links and images
|
||||
|
||||
@@ -58,7 +58,7 @@ On iOS a newly mounted Markdown view paints empty for a frame or more after it i
|
||||
|
||||
Android measurements use a size-only, 512-entry LRU across view unmounts, matching the library’s existing iOS cache. Scrolling back through history can reuse layout sizes without parsing those rows again. Content, layout props and width identify each entry; font-scale changes and native layout invalidation discard affected sizes. The cache retains no views or spans.
|
||||
|
||||
The library determines how incomplete Markdown appears during streaming. Completed text uses the same component and engine as history. Find and scroll-to-message address source message ids; selection-copy understands semantic HTML and the web code component's copy metadata.
|
||||
While `streaming` is true, `stabilizeStreamingMarkdown` in `components/markdown/streaming.ts` closes unfinished inline constructs (code spans, emphasis, strikethrough, links) and withholds incomplete block prefixes (headings, Setext underlines after paragraphs, list/task markers, empty quotes and admonitions, opening and partial closing code fences, unconfirmed tables, images and HTML tags/comments) before `prepareMarkdownSource` runs. Incomplete links render with link styling through `PENDING_MARKDOWN_LINK` without becoming interactive anchors or opening link actions until their destination closes. Completed text bypasses stabilization and uses the same component and engine as history. Find and scroll-to-message address source message ids; selection-copy understands semantic HTML and the web code component's copy metadata.
|
||||
|
||||
## Verification
|
||||
|
||||
|
||||
@@ -146,9 +146,10 @@ definition, no longer eligible to begin.
|
||||
- Panels whose gesture wrapper already owns visibility use `RetainedPanelActivity` to provide the
|
||||
same active signal without adding another layout root. Persistent animations, timers, polling, and
|
||||
shared clocks must subscribe to that signal and stop when their final visible consumer leaves.
|
||||
- Synchronized step animations use one wall-clock-aligned source. Register a local shared value only
|
||||
while its retained panel is active so hidden animated styles remain mounted without receiving clock
|
||||
updates. Do not give every instance its own loop or leave hidden styles subscribed to the source.
|
||||
- Synchronized step animations use one source. Do not give every instance its own loop. A hidden
|
||||
instance stops running the source and keeps its place, because the active signal changes after the
|
||||
panel has slid into view; see
|
||||
[running-indicators.md](running-indicators.md#hidden-panels).
|
||||
- Retention order and render order are separate concerns. LRU metadata may change on every switch;
|
||||
keyed retained roots must keep a stable sibling order. Moving large retained roots triggered Fabric
|
||||
Differ failures (`addViewAt` / `removeViewAt` view reuse) on Android.
|
||||
|
||||
+1
-1
@@ -52,7 +52,7 @@ type Grant = {
|
||||
|
||||
A delegating principal can grant only authority it already possesses. A session may attenuate its principal's grants but cannot widen them.
|
||||
|
||||
Workspace-scoped grants require every resource-bearing operation and outbound observation to enforce the same workspace boundary. File preview currently accepts any daemon-readable regular file, so it must gain resource enforcement before workspace-specific access ships.
|
||||
Workspace-scoped grants require every resource-bearing operation and outbound observation to enforce the same workspace boundary. File preview currently accepts any daemon-readable regular file outside daemon state (see [SECURITY.md](../SECURITY.md#local-daemon-trust-boundary)), so it must gain resource enforcement before workspace-specific access ships.
|
||||
|
||||
## Hub
|
||||
|
||||
|
||||
+82
-23
@@ -14,14 +14,37 @@ 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.
|
||||
- `useIndicatorMotion()` says what an indicator does now. Ask this hook; do not read reduced motion
|
||||
or visibility yourself.
|
||||
- `moving`: it runs.
|
||||
- `held`: nobody can see it, in a retained panel that is not showing or in an app in the
|
||||
background. It runs nothing and keeps its place.
|
||||
- `resting`: the system asks for reduced motion. It draws its resting frame and runs nothing.
|
||||
- The driver: `loop.web.ts` on web, `clock.ts` on native.
|
||||
|
||||
Animate only `transform` and `opacity`. Anything else is painted on the main thread every frame.
|
||||
|
||||
## Hidden panels
|
||||
|
||||
A phone's sidebar slides into view before its panel counts as showing: the panel's active signal
|
||||
changes when the slide settles, never during it (see [mobile-panels.md](mobile-panels.md)). An
|
||||
indicator that changes what it draws on that signal changes it in front of the user. A held ring
|
||||
that drew its resting position jumped to the running position at the end of every slide.
|
||||
|
||||
So on native a held indicator stays bound to its clock and stops running it:
|
||||
|
||||
- The clock and the loader's ticker count the time they have run, and hold it while nothing runs
|
||||
them. They are never set back to zero or to the wall clock.
|
||||
- While another panel runs the clock, a held view follows it. Measured on an Android emulator with
|
||||
six held rings behind a running chat, the app drew the same frames a second as with the rings
|
||||
unbound, and CPU on each thread differed by less than it does between two runs.
|
||||
- While nothing runs the clock, a held view costs nothing: behind an idle chat the app draws no
|
||||
frames.
|
||||
- One commit can stop the last moving indicator and start another, as when the sidebar replaces the
|
||||
chat. The clock stops after the commit, so it counts through that without a restart.
|
||||
|
||||
Web does not do this: a held indicator on web cancels its loop and draws its resting frame.
|
||||
|
||||
## Frames
|
||||
|
||||
Keeping the animation off the React thread does not make it free. Every time an indicator moves,
|
||||
@@ -31,11 +54,11 @@ window at 60 or 120 frames a second for as long as an agent runs, with nothing e
|
||||
|
||||
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 |
|
||||
| Indicator | Positions | Frames a second |
|
||||
| ----------------- | ------------------------------------------------------ | --------------- |
|
||||
| Loader | 6 per 950 ms | 6 |
|
||||
| Status ring | 27 per 900 ms (`STATUS_RING_STEPS`) | 30 |
|
||||
| Tool-call shimmer | 30 to 69 per pass, by label length (`getShimmerCycle`) | 30 |
|
||||
|
||||
The ring is the one that matters most: it is on screen in the sidebar and the tab bar whenever any
|
||||
agent runs, including while you read an idle chat. Its steps are positions the smooth turn passes
|
||||
@@ -44,8 +67,18 @@ on an Android emulator with one ring on screen, the app used 12–15% of a core
|
||||
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.
|
||||
Two indicators only share frames when their steps turn over at the same instants. So the ring and
|
||||
the shimmer move on one grid of steps, `INDICATOR_STEP_MS` in `indicator-motion/steps.ts`: one step
|
||||
every 1000/30 ms, counted from one origin. A chat with a running tool call in view then draws 30
|
||||
frames a second for both. A shimmer whose steps fell between the ring's would hold the window at 60.
|
||||
|
||||
- The shimmer's pass is a whole number of steps, the one closest to its smooth length. The pass
|
||||
changes by at most half a step, 17 ms in 1 to 2.3 seconds.
|
||||
- Each shimmer still starts its own pass when it appears, so the highlight enters from the left.
|
||||
The pass starts at the beginning of the current step, not at mount.
|
||||
- The loader's steps are 158 ms long and are not on the grid. Measured in Chromium, a running turn
|
||||
draws about 36 frames a second: 30 for the ring and the shimmer, the rest for the loader and the
|
||||
elapsed counter.
|
||||
|
||||
## Web
|
||||
|
||||
@@ -66,7 +99,8 @@ Two more reasons the stylesheet route does not work here:
|
||||
|
||||
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:
|
||||
cycle wherever and whenever it mounted. `phase: "own"` starts the loop at the beginning of the
|
||||
current grid step, so its steps still turn over with the shared loops. A stepped animation sets its easing on the keyframes:
|
||||
`step-end` to hold each keyframe until the next, `steps(n)` to cross between two keyframes in `n`
|
||||
even steps. The compositor then draws a frame when a step changes and none in between.
|
||||
|
||||
@@ -77,19 +111,43 @@ For a transition that is fine. For an indicator that runs for an hour it was 22
|
||||
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.
|
||||
and commits nothing. `clock.ts` builds a clock out of it: a linear timing at one unit per
|
||||
millisecond is the time since the clock started. `Animated.modulo` and `interpolate` turn the clock
|
||||
into a rotation or a translation, all inside the native driver.
|
||||
|
||||
`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 timing counts in spans of ten minutes. The end of a span is the one event that reaches the JS
|
||||
thread, which starts the next span where that one ended, so a cycle keeps its place from one span to
|
||||
the next.
|
||||
|
||||
The native driver owns the clock's value. The JS thread starts and stops the counting and never
|
||||
sets the value, so a stopped clock keeps the value its views show. When the clock stops, the driver
|
||||
reports the value it stopped at, and the next start counts on from it.
|
||||
|
||||
Do not drive the clock with a decay. A decay that never slows counts time without spans, but the
|
||||
driver ends a decay when its value moves less than 0.1 between two frames, whatever the
|
||||
deceleration. Two frames that carry the same millisecond are enough, and then every indicator on
|
||||
the clock freezes. Starting the decay again from the JS thread shows as a pause and a jump each
|
||||
time.
|
||||
|
||||
Android replays a timing as 60 positions a second at any refresh rate, and iOS interpolates between
|
||||
them. Every cycle on the clock is stepped at 30 positions a second, so this does not show. A cycle
|
||||
without steps would move 60 times a second on a 120 Hz Android display.
|
||||
|
||||
`cycle(periodMs, { steps })` holds the position at each step. The driver still ticks every frame,
|
||||
but a view whose transform did not change is not invalidated, so nothing is drawn between steps.
|
||||
|
||||
The native clock starts on the frame where the driver picks it up, so two clocks started at
|
||||
different times turn their steps over on different frames. That is why the shimmer rides
|
||||
`sharedIndicatorClock`, the rings' clock, with `phase: "own"`: its pass starts at the clock's
|
||||
current step. The JS thread works out that step from the time it started the clock and the value
|
||||
the clock started from. The driver
|
||||
starts the clock a frame or two later, so a pass can start one step early or late. The band starts
|
||||
one band width outside the label, so this does not show.
|
||||
|
||||
The loader changes six times per cycle, so it does not ride the frame clock. `step-ticker.ts` wakes
|
||||
the JS thread once per step, 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.
|
||||
the JS thread once per step and publishes the step into a native `Animated.Value`. A wake-up that
|
||||
arrives late publishes the step that is current by then, so the loader never drifts. Every loader
|
||||
reads the one value, so they all show the same step.
|
||||
|
||||
Do not apply Unistyles dynamic styles to these `Animated.View`s; see
|
||||
[unistyles.md](unistyles.md#reanimated-animatedview--dynamic-styles-crashes).
|
||||
@@ -99,7 +157,8 @@ Do not apply Unistyles dynamic styles to these `Animated.View`s; see
|
||||
`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
|
||||
idle chat and beside a running tool call, whether the shimmer moves only on the ring's frames,
|
||||
reduced motion, and a hidden tab. Run it with
|
||||
`PASEO_RUNNING_INDICATORS_FRAMES=1` to also save reference frames of every indicator at fixed
|
||||
points of its cycle, for a pixel comparison across a change.
|
||||
|
||||
|
||||
@@ -148,6 +148,8 @@ Run it locally with the same command owned by the Ubuntu `desktop-tests` require
|
||||
npm run test:e2e:browser-tabs --workspace=@getpaseo/desktop
|
||||
```
|
||||
|
||||
Its last step is the per-tab browser profile journey. It creates colored profiles inline, verifies isolation across an Electron relaunch and `target="_blank"` profile inheritance, then tests clearing, renaming, and removing profiles through Settings. Run only that journey with `PASEO_DESKTOP_BROWSER_PROFILES_ONLY=1`. Set `PASEO_DESKTOP_BROWSER_E2E_ARTIFACT_DIR` to keep its screenshots and `profiles.json`.
|
||||
|
||||
## Test organization
|
||||
|
||||
- Collocate tests with implementation: `thing.ts` + `thing.test.ts`
|
||||
|
||||
@@ -172,9 +172,10 @@ is offline and until a reconnected chat's check answers, so an unchanged chat ne
|
||||
toast. Returning from background on a socket that stayed connected shows nothing until the check
|
||||
answers: the chat stayed subscribed, so a slow answer is no reason to doubt it, and a socket that
|
||||
died without closing fails the foreground liveness probe and becomes a reconnect. Updating messages
|
||||
appears for a chat that is behind, until the fetch completes, and for an opened chat whose check is
|
||||
still unanswered `FRESHNESS_CHECK_QUIET_MS` after it was sent. That delay measures the daemon, so it
|
||||
starts at the request: on a cold start the cache read alone can take longer. Socket connectivity
|
||||
appears for a chat that is behind, until the fetch completes, and for an opened chat whose check or
|
||||
cursorless initial tail catch-up (such as a display-only cache) is still unanswered
|
||||
`FRESHNESS_CHECK_QUIET_MS` after the subscribe request was sent. That delay measures the daemon, so
|
||||
it starts at the request: on a cold start the cache read alone can take longer. Socket connectivity
|
||||
alone cannot certify that the displayed conversation is current. The timeline owner publishes freshness; the view renders it without a toast timer or a
|
||||
separate resume workflow.
|
||||
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
sha256-ZVIrRfb7oyTwx7kz6F51hs/ctT45qUdZM4v0QRLW9zA=
|
||||
sha256-04BfmBEaEZy3ohSi3Z8S3/a3xBsLKhls+8mcjJ0Y2/A=
|
||||
|
||||
Generated
+1
@@ -39975,6 +39975,7 @@
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@getpaseo/cli": "*",
|
||||
"@getpaseo/client": "*",
|
||||
"@getpaseo/server": "*",
|
||||
"electron-log": "^5.4.3",
|
||||
"electron-updater": "^6.6.2",
|
||||
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
expectComposerVisible,
|
||||
cancelAgent,
|
||||
composerLocator,
|
||||
configureComposerInterruptSend,
|
||||
expectQueuedMessageButton,
|
||||
fillComposerDraft,
|
||||
holdSendButton,
|
||||
@@ -404,15 +405,6 @@ async function queueMessage(page: Page, prompt: string): Promise<void> {
|
||||
await sendDraftToQueue(page);
|
||||
}
|
||||
|
||||
async function expectQueuedSendFailuresRestored(page: Page, prompts: string[]): Promise<void> {
|
||||
await expect(page.getByRole("button", { name: "Send queued message now" })).toHaveCount(
|
||||
prompts.length,
|
||||
);
|
||||
for (const prompt of prompts) {
|
||||
await expect(page.getByTestId("user-message").filter({ hasText: prompt })).toHaveCount(0);
|
||||
}
|
||||
}
|
||||
|
||||
async function expectFailedSubmissionRestored(page: Page, prompt: string): Promise<void> {
|
||||
await expectComposerDraft(page, prompt);
|
||||
await expectComposerEditable(page);
|
||||
@@ -431,14 +423,14 @@ async function expectInterruptedTurnOrderAfterReconnect(
|
||||
});
|
||||
const prompt = "Keep this prompt before its response.";
|
||||
try {
|
||||
await configureComposerInterruptSend(page);
|
||||
await openAgentRoute(page, { workspaceId: agent.workspaceId, agentId: agent.agentId });
|
||||
await expectComposerVisible(page);
|
||||
await agent.client.sendAgentMessage(agent.agentId, "Start the turn that will be interrupted.");
|
||||
await expect(page.getByRole("button", { name: /stop|cancel/i }).first()).toBeVisible();
|
||||
await expect(page.getByText("Cycle 1", { exact: true })).toBeVisible();
|
||||
await queueMessage(page, prompt);
|
||||
gate.setAgentStreamSuppressed(true);
|
||||
await page.getByRole("button", { name: "Send queued message now" }).click();
|
||||
await submitMessage(page, prompt);
|
||||
const promptRow = page.getByTestId("user-message").filter({ hasText: prompt });
|
||||
await expect(promptRow).toBeVisible();
|
||||
await gate.waitForServerMessage("send_agent_message_response");
|
||||
@@ -659,14 +651,14 @@ async function expectLegacyAssistantStartsAfterInterruptedPrompt(
|
||||
});
|
||||
const prompt = "Start the replacement answer after this prompt.";
|
||||
try {
|
||||
await configureComposerInterruptSend(page);
|
||||
await openAgentRoute(page, { workspaceId: agent.workspaceId, agentId: agent.agentId });
|
||||
await expectComposerVisible(page);
|
||||
await agent.client.sendAgentMessage(agent.agentId, "Start the interrupted answer.");
|
||||
await expect(page.getByText("Cycle 1", { exact: true })).toBeVisible();
|
||||
await queueMessage(page, prompt);
|
||||
gate.setAssistantMessageIdsStripped(true);
|
||||
gate.setAgentStreamEventSuppressed("turn_canceled", true);
|
||||
await page.getByRole("button", { name: "Send queued message now" }).click();
|
||||
await submitMessage(page, prompt);
|
||||
const promptRow = page.getByTestId("user-message").filter({ hasText: prompt });
|
||||
const replacementAnswer = page.getByText("(end of synthetic stream)", { exact: true }).last();
|
||||
await expect(promptRow).toBeVisible();
|
||||
@@ -1098,6 +1090,7 @@ test.describe("Agent message submission", () => {
|
||||
gate.holdNextServerMessage("cancel_agent_response");
|
||||
await page.getByRole("button", { name: "Stop agent", exact: true }).click();
|
||||
await gate.waitForHeldServerMessage();
|
||||
await page.getByRole("button", { name: "Send queued message now" }).click();
|
||||
|
||||
await expect(page.getByTestId("user-message").filter({ hasText: secondPrompt })).toHaveCount(
|
||||
1,
|
||||
@@ -1343,6 +1336,8 @@ test.describe("Agent message submission", () => {
|
||||
await test.step("holding Send queues the draft", async () => {
|
||||
await fillComposerDraft(page, queuedPrompt);
|
||||
await holdSendButton(page, "Send and steer");
|
||||
expect((await gate.waitForRequest()).activeTurnBehavior).toBe("queue");
|
||||
gate.accept();
|
||||
await expectQueuedMessageButton(page);
|
||||
await expectComposerDraft(page, "");
|
||||
await expectAgentReadyToInterrupt(page);
|
||||
@@ -1351,19 +1346,22 @@ test.describe("Agent message submission", () => {
|
||||
).toHaveCount(0);
|
||||
});
|
||||
|
||||
await test.step("tapping Send still steers", async () => {
|
||||
await test.step("tapping Send still steers and takes the queued row along", async () => {
|
||||
const steeredPrompt = "Steer this turn with a tap.";
|
||||
await fillComposerDraft(page, steeredPrompt);
|
||||
await page.getByRole("button", { name: "Send and steer", exact: true }).click();
|
||||
|
||||
const request = await gate.waitForRequest();
|
||||
const request = await gate.waitForRequest(2);
|
||||
expect(request.text).toBe(steeredPrompt);
|
||||
expect(request.activeTurnBehavior).toBe("steer");
|
||||
gate.accept();
|
||||
gate.accept(1);
|
||||
await expect(
|
||||
page.getByTestId("user-message").filter({ hasText: steeredPrompt }),
|
||||
).toHaveCount(1);
|
||||
await expectQueuedMessageButton(page);
|
||||
await expect(page.getByRole("button", { name: "Send queued message now" })).toHaveCount(0);
|
||||
await expect(
|
||||
page.getByTestId("user-message").filter({ hasText: queuedPrompt }),
|
||||
).toHaveCount(1);
|
||||
});
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
@@ -1380,26 +1378,21 @@ test.describe("Agent message submission", () => {
|
||||
await replaySteeredSleepTurnInBrowser(page, testInfo, "codex");
|
||||
});
|
||||
|
||||
test("restores overlapping queued sends when their connection fails", async ({
|
||||
page,
|
||||
}, testInfo) => {
|
||||
test("restores the draft when queueing loses the connection", async ({ page }, testInfo) => {
|
||||
test.setTimeout(120_000);
|
||||
const gate = await gateNextAgentMessage(page);
|
||||
const agent = await startRunningMockAgent(page, {
|
||||
prefix: `overlapping-queued-send-${testInfo.workerIndex}-`,
|
||||
prefix: `queue-connection-lost-${testInfo.workerIndex}-`,
|
||||
model: "one-minute-stream",
|
||||
prompt: "Keep the agent running while messages queue.",
|
||||
prompt: "Keep the agent running while a message queues.",
|
||||
});
|
||||
const prompts = ["Restore the first queued send.", "Restore the second queued send."];
|
||||
const prompt = "Keep this draft if queueing fails.";
|
||||
try {
|
||||
await queueMessage(page, prompts[0]);
|
||||
await queueMessage(page, prompts[1]);
|
||||
await page.getByRole("button", { name: "Send queued message now" }).first().click();
|
||||
await gate.waitForRequest(1);
|
||||
await page.getByRole("button", { name: "Send queued message now" }).first().click();
|
||||
await gate.waitForRequest(2);
|
||||
await fillComposerDraft(page, prompt);
|
||||
await sendDraftToQueue(page);
|
||||
await gate.waitForRequest();
|
||||
await gate.disconnect();
|
||||
await expectQueuedSendFailuresRestored(page, prompts);
|
||||
await expectFailedSubmissionRestored(page, prompt);
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
answerFreshnessCheck,
|
||||
commitTimelineTurnsWhileDisconnected,
|
||||
disconnectViewedTimeline,
|
||||
expectCleanLoadingSurfaces,
|
||||
expectEmptyChatSynced,
|
||||
expectPromptAndWholeReply,
|
||||
expectResumeAnsweredWithoutFetch,
|
||||
@@ -26,11 +27,14 @@ import {
|
||||
restoreViewedTimelineWithHeldResponse,
|
||||
restoreViewedTimelineWithLiveRowsFirst,
|
||||
reopenWithFreshnessCheckUnanswered,
|
||||
reopenWithTimelineTailUnanswered,
|
||||
seedStreamingReplyAgent,
|
||||
sendPromptWhileDisconnected,
|
||||
stopStreamingReply,
|
||||
waitForDisplayOnlyTimelineCache,
|
||||
waitForResumeAnswer,
|
||||
reopenAppWatchingForUpdatingToast,
|
||||
watchColdAndReloadLoadingSurfaces,
|
||||
watchForUpdatingToast,
|
||||
} from "../support/helpers/timeline-resume";
|
||||
|
||||
@@ -176,4 +180,36 @@ test.describe("Agent timeline resume", () => {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("cold opens and display-only cache reloads keep loading steady and reserve Updating messages for slow replies", async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(120_000);
|
||||
const gate = await installDaemonWebSocketGate(page);
|
||||
const agent = await seedLongMockAgentTimeline({ turns: 30 });
|
||||
try {
|
||||
await watchColdAndReloadLoadingSurfaces(page);
|
||||
|
||||
await test.step("cold open fetches one tail without showing a premature toast", async () => {
|
||||
const requests = rememberTimelineRequestCounts(gate, agent.agentId);
|
||||
await openAgentTimeline(page, agent);
|
||||
await expectTimelinePromptVisible(page, agent.newestPrompt);
|
||||
await expectCleanLoadingSurfaces(page, gate, requests);
|
||||
});
|
||||
|
||||
await test.step("display-only cached reload shows Updating messages until the overdue tail arrives", async () => {
|
||||
await scrollTimelineUntilOlderHistoryIsReachable(page, agent.firstOlderPagePrompt);
|
||||
await waitForDisplayOnlyTimelineCache(page, agent);
|
||||
|
||||
const requests = rememberTimelineRequestCounts(gate, agent.agentId);
|
||||
await reopenWithTimelineTailUnanswered({ page, gate, agentId: agent.agentId });
|
||||
await expectTimelinePromptVisible(page, agent.newestPrompt);
|
||||
gate.releaseHeldTimelineResponses();
|
||||
await expectCleanLoadingSurfaces(page, gate, requests);
|
||||
});
|
||||
} finally {
|
||||
gate.restore();
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,299 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import type { Browser, CDPSession, Page } from "@playwright/test";
|
||||
import { test, expect } from "../support/fixtures";
|
||||
import { openAgentRoute } from "../support/helpers/mock-agent";
|
||||
import {
|
||||
readReactCommits,
|
||||
readReactRenders,
|
||||
recordReactRenders,
|
||||
resetReactRenders,
|
||||
} from "../support/helpers/react-renders";
|
||||
import { seedWorkspace, type SeededWorkspace } from "../support/helpers/seed-client";
|
||||
|
||||
/*
|
||||
* What the app costs per agent update while agents the user is not looking at work.
|
||||
*
|
||||
* One workspace is open on one idle agent. Other workspaces hold idle agents. During the load
|
||||
* window some of those agents run mock turns back to back. Like a working agent, they send
|
||||
* `agent_update` messages that mostly change only `lastUsage` and `updatedAt`. The spec samples renderer CPU,
|
||||
* main-thread task time, React commits and component renders over the window and divides by
|
||||
* the `agent_update` messages the page received.
|
||||
*
|
||||
* PASEO_AGENT_UPDATE_PERF_E2E=1 run the spec
|
||||
* PASEO_AGENT_UPDATE_WORKSPACES=20 background workspaces
|
||||
* PASEO_AGENT_UPDATE_AGENTS=20 idle agents per background workspace
|
||||
* PASEO_AGENT_UPDATE_RUNNING=10 agents running a turn during the load window
|
||||
* PASEO_AGENT_UPDATE_WINDOW_MS=20000 length of the idle and load windows
|
||||
* PASEO_AGENT_UPDATE_RUNS=3 load windows to sample
|
||||
* PASEO_AGENT_UPDATE_OUT=<file> write the samples as JSON
|
||||
* PASEO_AGENT_UPDATE_CPU_PROFILE=<file> write a CPU profile of the first load window
|
||||
*/
|
||||
|
||||
const RUN = process.env.PASEO_AGENT_UPDATE_PERF_E2E === "1";
|
||||
const WORKSPACES = Number(process.env.PASEO_AGENT_UPDATE_WORKSPACES ?? 20);
|
||||
const AGENTS_PER_WORKSPACE = Number(process.env.PASEO_AGENT_UPDATE_AGENTS ?? 20);
|
||||
const RUNNING = Number(process.env.PASEO_AGENT_UPDATE_RUNNING ?? 10);
|
||||
const WINDOW_MS = Number(process.env.PASEO_AGENT_UPDATE_WINDOW_MS ?? 20_000);
|
||||
const RUNS = Number(process.env.PASEO_AGENT_UPDATE_RUNS ?? 3);
|
||||
const OUT = process.env.PASEO_AGENT_UPDATE_OUT;
|
||||
const CPU_PROFILE = process.env.PASEO_AGENT_UPDATE_CPU_PROFILE;
|
||||
// Emits a usage update about every 1.5 s, like a working Claude agent.
|
||||
const RUNNING_MODEL = "ten-second-stream";
|
||||
|
||||
interface WindowSample {
|
||||
agentUpdates: number;
|
||||
rendererCpuMs: number;
|
||||
taskMs: number;
|
||||
scriptMs: number;
|
||||
reactCommits: number;
|
||||
taskMsPerUpdate: number;
|
||||
rendererCpuMsPerUpdate: number;
|
||||
commitsPerUpdate: number;
|
||||
changeSets: Record<string, number>;
|
||||
topRenders: Array<[string, number]>;
|
||||
}
|
||||
|
||||
const describe = RUN ? test.describe : test.describe.skip;
|
||||
|
||||
describe("Agent update cost", () => {
|
||||
const background: Array<{ workspace: SeededWorkspace; agentIds: string[] }> = [];
|
||||
let open: SeededWorkspace;
|
||||
let openAgentId: string;
|
||||
|
||||
test.beforeAll(async () => {
|
||||
test.setTimeout(900_000);
|
||||
open = await seedWorkspace({ repoPrefix: "update-cost-open-", title: "Open" });
|
||||
openAgentId = await createIdleAgent(open, "Open agent");
|
||||
for (let index = 0; index < WORKSPACES; index += 1) {
|
||||
const workspace = await seedWorkspace({
|
||||
repoPrefix: `update-cost-${index}-`,
|
||||
title: `Background ${index + 1}`,
|
||||
});
|
||||
const agentIds = await Promise.all(
|
||||
Array.from({ length: AGENTS_PER_WORKSPACE }, (_, agentIndex) =>
|
||||
createIdleAgent(workspace, `Agent ${index + 1}.${agentIndex + 1}`),
|
||||
),
|
||||
);
|
||||
background.push({ workspace, agentIds });
|
||||
}
|
||||
});
|
||||
|
||||
test.afterAll(async () => {
|
||||
for (const { workspace } of background) await workspace.cleanup();
|
||||
await open?.cleanup();
|
||||
});
|
||||
|
||||
test("renderer work per agent update", async ({ page, browser }) => {
|
||||
test.setTimeout(WINDOW_MS * (RUNS + 1) * 4 + 300_000);
|
||||
await recordReactRenders(page);
|
||||
const traffic = countAgentUpdates(page);
|
||||
await page.setViewportSize({ width: 1440, height: 900 });
|
||||
await openAgentRoute(page, { workspaceId: open.workspaceId, agentId: openAgentId });
|
||||
await expect(
|
||||
page.getByTestId(`workspace-tab-agent_${openAgentId}`).filter({ visible: true }).first(),
|
||||
).toBeVisible({ timeout: 60_000 });
|
||||
await expect(page.getByText(`Background ${WORKSPACES}`, { exact: true }).first()).toBeVisible({
|
||||
timeout: 60_000,
|
||||
});
|
||||
await page.waitForTimeout(5_000);
|
||||
|
||||
const meter = await openMeter(page, browser);
|
||||
try {
|
||||
const idle = await meter.sample(traffic, () => page.waitForTimeout(WINDOW_MS));
|
||||
const loads: WindowSample[] = [];
|
||||
for (let run = 0; run < RUNS; run += 1) {
|
||||
const running = pickRunning(background, run);
|
||||
const work = keepWorking(running);
|
||||
// Let the turns start so the window measures steady work, not the start burst.
|
||||
await page.waitForTimeout(3_000);
|
||||
const profile = CPU_PROFILE && run === 0 ? CPU_PROFILE : null;
|
||||
loads.push(await meter.sample(traffic, () => page.waitForTimeout(WINDOW_MS), profile));
|
||||
await work.stop();
|
||||
await page.waitForTimeout(3_000);
|
||||
}
|
||||
const result = {
|
||||
config: {
|
||||
workspaces: WORKSPACES,
|
||||
agentsPerWorkspace: AGENTS_PER_WORKSPACE,
|
||||
running: RUNNING,
|
||||
windowMs: WINDOW_MS,
|
||||
},
|
||||
idle,
|
||||
loads,
|
||||
median: {
|
||||
taskMsPerUpdate: median(loads.map((load) => load.taskMsPerUpdate)),
|
||||
rendererCpuMsPerUpdate: median(loads.map((load) => load.rendererCpuMsPerUpdate)),
|
||||
commitsPerUpdate: median(loads.map((load) => load.commitsPerUpdate)),
|
||||
agentUpdatesPerSecond: median(
|
||||
loads.map((load) => load.agentUpdates / (WINDOW_MS / 1000)),
|
||||
),
|
||||
},
|
||||
};
|
||||
console.log(`[agent-update-cost] ${JSON.stringify(result, null, 2)}`);
|
||||
if (OUT) await writeFile(OUT, JSON.stringify(result, null, 2));
|
||||
expect(loads.every((load) => load.agentUpdates > 0)).toBe(true);
|
||||
} finally {
|
||||
await meter.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
async function createIdleAgent(workspace: SeededWorkspace, title: string): Promise<string> {
|
||||
const agent = await workspace.client.createAgent({
|
||||
provider: "mock",
|
||||
cwd: workspace.repoPath,
|
||||
workspaceId: workspace.workspaceId,
|
||||
title,
|
||||
modeId: "load-test",
|
||||
model: RUNNING_MODEL,
|
||||
});
|
||||
return agent.id;
|
||||
}
|
||||
|
||||
/** Spreads the running agents over the workspaces, a different agent each run. */
|
||||
function pickRunning(
|
||||
background: ReadonlyArray<{ workspace: SeededWorkspace; agentIds: string[] }>,
|
||||
run: number,
|
||||
): Array<{ workspace: SeededWorkspace; agentId: string }> {
|
||||
return Array.from({ length: RUNNING }, (_, index) => {
|
||||
const entry = background[index % background.length];
|
||||
const agentId =
|
||||
entry.agentIds[(run + Math.floor(index / background.length)) % entry.agentIds.length];
|
||||
return { workspace: entry.workspace, agentId };
|
||||
});
|
||||
}
|
||||
|
||||
/** Starts a turn on each agent and another one whenever it finishes, until stopped. */
|
||||
function keepWorking(running: ReadonlyArray<{ workspace: SeededWorkspace; agentId: string }>) {
|
||||
const state = { stopped: false };
|
||||
const loops = running.map(async ({ workspace, agentId }) => {
|
||||
while (!state.stopped) {
|
||||
await workspace.client.sendAgentMessage(agentId, "work");
|
||||
await workspace.client.waitForFinish(agentId, 60_000);
|
||||
}
|
||||
});
|
||||
return {
|
||||
async stop() {
|
||||
state.stopped = true;
|
||||
await Promise.all(
|
||||
running.map(({ workspace, agentId }) => workspace.client.cancelAgent(agentId)),
|
||||
);
|
||||
await Promise.allSettled(loops);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
interface AgentUpdateTraffic {
|
||||
read(): number;
|
||||
/** How often each set of changed agent fields arrived, since the last call. */
|
||||
takeChangeSets(): Record<string, number>;
|
||||
}
|
||||
|
||||
/** Counts the `agent_update` messages the page receives and which agent fields each changed. */
|
||||
function countAgentUpdates(page: Page): AgentUpdateTraffic {
|
||||
let count = 0;
|
||||
let changeSets: Record<string, number> = {};
|
||||
const previous = new Map<string, Record<string, unknown>>();
|
||||
page.on("websocket", (socket) => {
|
||||
socket.on("framereceived", ({ payload }) => {
|
||||
if (typeof payload !== "string" || !payload.includes('"type":"agent_update"')) return;
|
||||
const frame = JSON.parse(payload) as {
|
||||
message?: { type?: string; payload?: { kind?: string; agent?: Record<string, unknown> } };
|
||||
};
|
||||
if (frame.message?.type !== "agent_update") return;
|
||||
count += 1;
|
||||
const agent = frame.message.payload?.agent;
|
||||
if (frame.message.payload?.kind !== "upsert" || !agent) return;
|
||||
const id = String(agent.id);
|
||||
const prior = previous.get(id);
|
||||
previous.set(id, agent);
|
||||
const changed = prior
|
||||
? Object.keys({ ...prior, ...agent })
|
||||
.filter((key) => JSON.stringify(prior[key]) !== JSON.stringify(agent[key]))
|
||||
.sort()
|
||||
.join(",") || "<nothing>"
|
||||
: "<first>";
|
||||
changeSets[changed] = (changeSets[changed] ?? 0) + 1;
|
||||
});
|
||||
});
|
||||
return {
|
||||
read: () => count,
|
||||
takeChangeSets: () => {
|
||||
const taken = changeSets;
|
||||
changeSets = {};
|
||||
return taken;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function openMeter(page: Page, browser: Browser) {
|
||||
const pageSession: CDPSession = await page.context().newCDPSession(page);
|
||||
const browserSession: CDPSession = await browser.newBrowserCDPSession();
|
||||
await pageSession.send("Performance.enable");
|
||||
|
||||
const readMetrics = async () => {
|
||||
const { metrics } = await pageSession.send("Performance.getMetrics");
|
||||
const value = (name: string) => metrics.find((metric) => metric.name === name)?.value ?? 0;
|
||||
const { processInfo } = await browserSession.send("SystemInfo.getProcessInfo");
|
||||
const rendererCpu = processInfo
|
||||
.filter((process) => process.type === "renderer")
|
||||
.reduce((total, process) => total + process.cpuTime, 0);
|
||||
return { task: value("TaskDuration"), script: value("ScriptDuration"), rendererCpu };
|
||||
};
|
||||
|
||||
return {
|
||||
async sample(
|
||||
traffic: AgentUpdateTraffic,
|
||||
during: () => Promise<void>,
|
||||
profilePath: string | null = null,
|
||||
) {
|
||||
await resetReactRenders(page);
|
||||
traffic.takeChangeSets();
|
||||
const updatesBefore = traffic.read();
|
||||
if (profilePath) {
|
||||
await pageSession.send("Profiler.enable");
|
||||
await pageSession.send("Profiler.start");
|
||||
}
|
||||
const before = await readMetrics();
|
||||
await during();
|
||||
const after = await readMetrics();
|
||||
if (profilePath) {
|
||||
const { profile } = await pageSession.send("Profiler.stop");
|
||||
await writeFile(profilePath, JSON.stringify(profile));
|
||||
}
|
||||
const renders = await readReactRenders(page);
|
||||
const agentUpdates = traffic.read() - updatesBefore;
|
||||
const reactCommits = await readReactCommits(page);
|
||||
const taskMs = (after.task - before.task) * 1000;
|
||||
const rendererCpuMs = (after.rendererCpu - before.rendererCpu) * 1000;
|
||||
const perUpdate = (value: number) => (agentUpdates > 0 ? value / agentUpdates : 0);
|
||||
return {
|
||||
agentUpdates,
|
||||
rendererCpuMs: Math.round(rendererCpuMs),
|
||||
taskMs: Math.round(taskMs),
|
||||
scriptMs: Math.round((after.script - before.script) * 1000),
|
||||
reactCommits,
|
||||
taskMsPerUpdate: round(perUpdate(taskMs)),
|
||||
rendererCpuMsPerUpdate: round(perUpdate(rendererCpuMs)),
|
||||
commitsPerUpdate: round(perUpdate(reactCommits)),
|
||||
changeSets: traffic.takeChangeSets(),
|
||||
topRenders: Object.entries(renders)
|
||||
.sort((left, right) => right[1] - left[1])
|
||||
.slice(0, 40),
|
||||
} satisfies WindowSample;
|
||||
},
|
||||
async close() {
|
||||
await pageSession.detach().catch(() => undefined);
|
||||
await browserSession.detach().catch(() => undefined);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function median(values: number[]): number {
|
||||
const sorted = [...values].sort((left, right) => left - right);
|
||||
return sorted[Math.floor(sorted.length / 2)] ?? 0;
|
||||
}
|
||||
|
||||
function round(value: number): number {
|
||||
return Math.round(value * 100) / 100;
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -439,7 +439,7 @@ test("usage arriving after the card opens never moves its bottom edge", async ({
|
||||
expect(new Set(frames.map((frame) => frame.bottom)).size).toBe(1);
|
||||
});
|
||||
|
||||
test("context details support keyboard entry and follow when the viewport resizes", async ({
|
||||
test("context details support keyboard entry and dismiss when the viewport moves", async ({
|
||||
page,
|
||||
agent,
|
||||
}) => {
|
||||
@@ -480,86 +480,9 @@ test("context details support keyboard entry and follow when the viewport resize
|
||||
await trigger.press("ArrowDown");
|
||||
await expect(details).toBeVisible();
|
||||
await page.setViewportSize({ width: 1280, height: 850 });
|
||||
await expect(details).toBeVisible();
|
||||
await expect(details).toBeInViewport({ ratio: 1 });
|
||||
const meterAfterResize = await meter.boundingBox();
|
||||
const cardAfterResize = await details.boundingBox();
|
||||
expect(meterAfterResize).not.toBeNull();
|
||||
expect(cardAfterResize).not.toBeNull();
|
||||
const expectedLeft = Math.max(
|
||||
8,
|
||||
Math.min(
|
||||
1280 - cardAfterResize!.width - 8,
|
||||
meterAfterResize!.x + meterAfterResize!.width / 2 - cardAfterResize!.width / 2,
|
||||
),
|
||||
);
|
||||
expect(Math.abs(cardAfterResize!.x - expectedLeft)).toBeLessThan(2);
|
||||
expect(
|
||||
Math.abs(meterAfterResize!.y - (cardAfterResize!.y + cardAfterResize!.height) - 8),
|
||||
).toBeLessThan(2);
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(details).toHaveCount(0);
|
||||
});
|
||||
|
||||
test("context details follow when left and right sidebars toggle", async ({ page, agent }) => {
|
||||
test.setTimeout(180_000);
|
||||
const usage = await scriptAgentUsage(page);
|
||||
const [claude] = claudeAndCodexReports();
|
||||
usage.answerNext([onPersonalLogin(claude!)]);
|
||||
await page.setViewportSize({ width: 1280, height: 800 });
|
||||
await openAgent(page, agent);
|
||||
|
||||
const meter = page.getByTestId("context-window-meter");
|
||||
await expect(meter).toBeVisible({ timeout: 30_000 });
|
||||
|
||||
const expectCardAnchoredToMeter = async (card: Locator) => {
|
||||
await expect(card).toBeVisible();
|
||||
await expect(card).toBeInViewport({ ratio: 1 });
|
||||
const meterBox = await meter.boundingBox();
|
||||
const cardBox = await card.boundingBox();
|
||||
expect(meterBox).not.toBeNull();
|
||||
expect(cardBox).not.toBeNull();
|
||||
const expectedLeft = Math.max(
|
||||
8,
|
||||
Math.min(1280 - cardBox!.width - 8, meterBox!.x + meterBox!.width / 2 - cardBox!.width / 2),
|
||||
);
|
||||
expect(Math.abs(cardBox!.x - expectedLeft)).toBeLessThan(2);
|
||||
expect(cardBox!.x + cardBox!.width).toBeLessThanOrEqual(1280 - 8 + 1);
|
||||
expect(Math.abs(meterBox!.y - (cardBox!.y + cardBox!.height) - 8)).toBeLessThan(2);
|
||||
};
|
||||
|
||||
// Start with the left sidebar closed, open the card, and rest the pointer on the card.
|
||||
await page.keyboard.press("ControlOrMeta+b");
|
||||
const card = await hoverContextWindowMeter(page);
|
||||
await moveOntoContextWindowDetails(page, card);
|
||||
await expectCardAnchoredToMeter(card);
|
||||
|
||||
// Open the left sidebar while the card stays open: the card must follow and stay on screen.
|
||||
const meterXBeforeLeftOpen = (await meter.boundingBox())!.x;
|
||||
await page.keyboard.press("ControlOrMeta+b");
|
||||
await expect
|
||||
.poll(async () => (await meter.boundingBox())?.x ?? meterXBeforeLeftOpen)
|
||||
.toBeGreaterThan(meterXBeforeLeftOpen + 100);
|
||||
await expectCardAnchoredToMeter(card);
|
||||
|
||||
// Open the right explorer sidebar while the card stays open: the card must follow left.
|
||||
const meterXBeforeExplorerOpen = (await meter.boundingBox())!.x;
|
||||
await page.keyboard.press("ControlOrMeta+e");
|
||||
await expect
|
||||
.poll(async () => (await meter.boundingBox())?.x ?? meterXBeforeExplorerOpen)
|
||||
.toBeLessThan(meterXBeforeExplorerOpen - 100);
|
||||
await expectCardAnchoredToMeter(card);
|
||||
|
||||
// Close the right explorer sidebar: the card must follow back right.
|
||||
await page.keyboard.press("ControlOrMeta+e");
|
||||
await expect
|
||||
.poll(async () => (await meter.boundingBox())?.x ?? 0)
|
||||
.toBeGreaterThan(meterXBeforeExplorerOpen - 10);
|
||||
await expectCardAnchoredToMeter(card);
|
||||
|
||||
await leaveContextWindowMeter(page);
|
||||
});
|
||||
|
||||
test("context details stay open while the chat streams", async ({ page }) => {
|
||||
test.setTimeout(120_000);
|
||||
await page.setViewportSize(DESKTOP);
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
expectHostBadgeIconOnly,
|
||||
expectHostBadgeName,
|
||||
expectHostBadgeTinted,
|
||||
expectHostSelectorStatusIcon,
|
||||
expectNoHostBadge,
|
||||
leaveHostAppearanceSettings,
|
||||
openHostAppearanceSettings,
|
||||
@@ -116,14 +117,29 @@ test("customizes a host badge and preserves its appearance after reload", async
|
||||
expect(widths.content).toBeLessThanOrEqual(widths.client);
|
||||
});
|
||||
|
||||
await test.step("preview a color and icon and apply them to the sidebar badge and host popover", async () => {
|
||||
await test.step("preview a color and icon and apply them to the sidebar badge, host selectors, and host popover", async () => {
|
||||
await openHostAppearanceSettings(page, badge.serverId);
|
||||
await chooseHostColor(page, "Teal");
|
||||
await chooseHostIcon(page, "Laptop");
|
||||
await expectHostAppearancePreview(page, { serverId: badge.serverId, hostName, color: "teal" });
|
||||
|
||||
// The Settings sidebar host selector shows the host's resolved icon badged with its status dot.
|
||||
const settingsHostPicker = page.getByTestId("settings-host-picker");
|
||||
await settingsHostPicker.click();
|
||||
await page.getByTestId(`settings-host-picker-item-${badge.serverId}`).click();
|
||||
await expectHostSelectorStatusIcon(settingsHostPicker, { color: "teal" });
|
||||
|
||||
await leaveHostAppearanceSettings(page);
|
||||
await expectHostBadgeTinted(page, { ...badge, hostName, color: "teal" });
|
||||
|
||||
// The New Workspace host selector also shows the host icon with its status dot.
|
||||
await page.getByTestId("sidebar-global-new-workspace").click();
|
||||
const newWorkspaceHostTrigger = page.getByTestId("host-picker-trigger");
|
||||
await expect(newWorkspaceHostTrigger).toBeVisible();
|
||||
await newWorkspaceHostTrigger.click();
|
||||
await page.getByTestId(`new-workspace-host-picker-option-${badge.serverId}`).click();
|
||||
await expectHostSelectorStatusIcon(newWorkspaceHostTrigger, { color: "teal" });
|
||||
|
||||
await page.getByTestId("sidebar-hosts-trigger").click();
|
||||
const hostRow = page.getByTestId(`sidebar-host-row-${badge.serverId}`);
|
||||
await expect(hostRow).toBeVisible();
|
||||
|
||||
@@ -6,10 +6,12 @@ import {
|
||||
cancelHostConfirmation,
|
||||
connectToConfirmedHost,
|
||||
expectHostConfirmationFor,
|
||||
expectHostIdentityChangedWarning,
|
||||
expectHostInHostPicker,
|
||||
hostConfirmation,
|
||||
openPairingLink,
|
||||
reopenPairingLinkWithSavedHosts,
|
||||
replaceHostIdentity,
|
||||
type LinkedHost,
|
||||
} from "../support/helpers/host-confirmation";
|
||||
|
||||
@@ -48,3 +50,46 @@ test("a pairing link asks before saving a host and reconnects without asking aga
|
||||
await expect(hostConfirmation(page)).toHaveCount(0);
|
||||
});
|
||||
});
|
||||
|
||||
test("a pairing link with a different key for a saved host warns before replacing its identity", async ({
|
||||
page,
|
||||
}) => {
|
||||
const rotatedHost: LinkedHost = {
|
||||
...linkedHost,
|
||||
daemonPublicKeyB64: "cm90YXRlZEhvc3RJZGVudGl0eQ",
|
||||
};
|
||||
const rotatedLink = buildPairingLink(rotatedHost);
|
||||
const warning = {
|
||||
savedHost: linkedHost.serverId,
|
||||
savedKey: "bGlu a0Nv … lvbk tleQ",
|
||||
newKey: "cm90 YXRl … VudG l0eQ",
|
||||
relayEndpoint: linkedHost.relayEndpoint,
|
||||
};
|
||||
|
||||
await test.step("save the host", async () => {
|
||||
await openPairingLink(page, buildPairingLink(linkedHost));
|
||||
await expectHostConfirmationFor(page, linkedHost);
|
||||
await connectToConfirmedHost(page);
|
||||
await expectAppRoute(page, "/open-project");
|
||||
});
|
||||
|
||||
await test.step("Cancel keeps the saved identity", async () => {
|
||||
await reopenPairingLinkWithSavedHosts(page, rotatedLink);
|
||||
await expectHostIdentityChangedWarning(page, warning);
|
||||
await cancelHostConfirmation(page);
|
||||
await expectAppRoute(page, "/settings/general");
|
||||
});
|
||||
|
||||
await test.step("Replace host identity saves the new key", async () => {
|
||||
await reopenPairingLinkWithSavedHosts(page, rotatedLink);
|
||||
await expectHostIdentityChangedWarning(page, warning);
|
||||
await replaceHostIdentity(page);
|
||||
await expectAppRoute(page, "/open-project");
|
||||
});
|
||||
|
||||
await test.step("the new key is now the saved identity", async () => {
|
||||
await reopenPairingLinkWithSavedHosts(page, rotatedLink);
|
||||
await expectAppRoute(page, "/open-project", { timeout: 30_000 });
|
||||
await expect(hostConfirmation(page)).toHaveCount(0);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { createHostClient } from "@getpaseo/client/node";
|
||||
import { expect } from "@playwright/test";
|
||||
import { gotoAppShell, openSettings } from "../support/helpers/app";
|
||||
import {
|
||||
addDirectHostFromSettings,
|
||||
@@ -24,11 +26,51 @@ import {
|
||||
slowConnectionToHost,
|
||||
expectTailscaleUpdateRequired,
|
||||
expectCompletePairingQr,
|
||||
expectConnectedClientRow,
|
||||
expectRelayConsent,
|
||||
expandConnectedClientRow,
|
||||
openDevicesPage,
|
||||
openPairDeviceModal,
|
||||
preparePairingHost,
|
||||
returnFromRelayToWaysToConnect,
|
||||
} from "../support/helpers/pair-device";
|
||||
|
||||
test("lists connected clients with scopes and navigates Pair a device → Relay → Back", async ({
|
||||
page,
|
||||
}) => {
|
||||
const daemon = await startIsolatedHostDaemon("pair-device-connected-clients", {
|
||||
mutableRelay: { enabled: true },
|
||||
});
|
||||
const viewer = createHostClient(`127.0.0.1:${daemon.port}`, {
|
||||
clientId: "cid_e2e_phone_viewer",
|
||||
clientType: "mobile",
|
||||
appVersion: "0.18.1",
|
||||
clientInfo: { name: "Test Phone", platform: "ios" },
|
||||
sessionPermissions: ["daemon.read", "workspace.read"],
|
||||
reconnect: { enabled: false },
|
||||
});
|
||||
try {
|
||||
await openDevicesPage(page, daemon);
|
||||
await expectConnectedClientRow(page, "This device", "Full access");
|
||||
await expandConnectedClientRow(page, "This device");
|
||||
await expect(
|
||||
page
|
||||
.getByTestId("devices-connected-clients-card")
|
||||
.getByText("access.manage", { exact: true }),
|
||||
).toBeVisible();
|
||||
|
||||
await viewer.connect();
|
||||
await expectConnectedClientRow(page, "Test Phone", "Read-only");
|
||||
|
||||
await openPairDeviceModal(page);
|
||||
await expectPairingOffer(page);
|
||||
await returnFromRelayToWaysToConnect(page);
|
||||
} finally {
|
||||
await viewer.close();
|
||||
await daemon.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("opens relay consent in browser web", async ({ page }) => {
|
||||
const daemon = await startIsolatedHostDaemon("pair-device-browser-relay-off", {
|
||||
mutableRelay: { enabled: false },
|
||||
@@ -81,7 +123,7 @@ test("turns Tailscale on and off from Devices, asking first over Tailscale", asy
|
||||
}, testInfo) => {
|
||||
test.skip(process.platform !== "linux", "Uses a second IPv4 loopback address");
|
||||
// The journey opens Devices or the setup six times, two of them over a slowed connection.
|
||||
test.setTimeout(120_000);
|
||||
test.setTimeout(180_000);
|
||||
if (!baseURL) throw new Error("Expected the app base URL");
|
||||
const daemon = await startTailscaleTestDaemon(baseURL);
|
||||
try {
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import path from "node:path";
|
||||
import { expect } from "../support/fixtures";
|
||||
import {
|
||||
test,
|
||||
expectStillBrowsing,
|
||||
@@ -22,3 +24,59 @@ test("installs a listed plugin from Browse and uninstalls it from either of its
|
||||
await openFromInstalledTab(page);
|
||||
await uninstallFromPage(page);
|
||||
});
|
||||
|
||||
test("shows scorecard progressive disclosure, updates, custom links, and related plugins", async ({
|
||||
page,
|
||||
directoryHost,
|
||||
}) => {
|
||||
const captureDir = process.env.PASEO_CAPTURE_DIR;
|
||||
if (captureDir) {
|
||||
await page.emulateMedia({ colorScheme: "dark" });
|
||||
}
|
||||
await page.setViewportSize({ width: 1280, height: 960 });
|
||||
await openDirectory(page, directoryHost);
|
||||
await openListingPage(page);
|
||||
|
||||
await expect(page.getByText("Related plugins", { exact: true })).toBeVisible();
|
||||
await expect(page.getByTestId("plugin-related-acme/pr-radar")).toBeVisible();
|
||||
|
||||
if (captureDir) {
|
||||
await page.waitForTimeout(300);
|
||||
await page.screenshot({ path: path.join(captureDir, "live-app-desktop-overview.png") });
|
||||
}
|
||||
|
||||
// Open Scorecard tab and expand a capability row.
|
||||
await page.getByTestId("plugin-page-tab-scorecard").click();
|
||||
await expect(page.getByText("This plugin is actively maintained.")).toBeVisible();
|
||||
const panelRow = page.getByRole("button", { name: /Workspace panel/ });
|
||||
await panelRow.click();
|
||||
await expect(page.getByText(/index\.client\.ts/)).toBeVisible();
|
||||
|
||||
if (captureDir) {
|
||||
await page.waitForTimeout(300);
|
||||
await page.screenshot({ path: path.join(captureDir, "live-app-desktop-scorecard.png") });
|
||||
}
|
||||
|
||||
// Open Updates tab and custom actions menu.
|
||||
await page.getByTestId("plugin-page-tab-updates").click();
|
||||
await expect(page.getByText("v1.2.0", { exact: true })).toBeVisible();
|
||||
await expect(page.getByText("c81a4f2", { exact: true })).toBeVisible();
|
||||
await page.getByTestId("plugin-actions-acme/directory-example").click();
|
||||
await expect(page.getByText("Documentation", { exact: true })).toBeVisible();
|
||||
|
||||
if (captureDir) {
|
||||
await page.waitForTimeout(300);
|
||||
await page.screenshot({ path: path.join(captureDir, "live-app-desktop-updates.png") });
|
||||
}
|
||||
await page.keyboard.press("Escape");
|
||||
|
||||
// Verify compact mobile layout on the same listing page.
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
await page.getByTestId("plugin-page-tab-scorecard").click();
|
||||
await expect(page.getByText("This plugin is actively maintained.")).toBeVisible();
|
||||
|
||||
if (captureDir) {
|
||||
await page.waitForTimeout(300);
|
||||
await page.screenshot({ path: path.join(captureDir, "live-app-mobile-scorecard.png") });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -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 ({
|
||||
page,
|
||||
}) => {
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
readAnimatingTargets,
|
||||
readLoaderStep,
|
||||
readRunningAnimations,
|
||||
recordIndicatorTurnovers,
|
||||
recordLoaderStepChanges,
|
||||
recordRingAngles,
|
||||
runningToolCall,
|
||||
@@ -51,6 +52,14 @@ const STATUS_RING_STEPS = 27;
|
||||
// Thirty ring positions a second, plus the few frames a second the rest of the page draws. A ring
|
||||
// that turns with the display draws sixty or more.
|
||||
const RING_ONLY_FRAMES_PER_SECOND_BUDGET = 36;
|
||||
// Thirty ring and shimmer positions a second, the loader's six, and the few frames a second the
|
||||
// rest of the page draws. A shimmer that moves with the display draws sixty or more, and one whose
|
||||
// steps fall between the ring's draws up to sixty.
|
||||
const RUNNING_TURN_FRAMES_PER_SECOND_BUDGET = 42;
|
||||
// A pass of the shimmer is a whole number of steps of 1000 / 30 ms; the mock's tool call label
|
||||
// gives a pass of about 1.4 s.
|
||||
const SHIMMER_MIN_STEPS = 30;
|
||||
const SHIMMER_MAX_STEPS = 69;
|
||||
|
||||
// React renders these once when the indicator appears. Rendering again while the turn is quiet
|
||||
// means the animation is being driven through React.
|
||||
@@ -154,6 +163,40 @@ test.describe("Running indicators", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("a running tool call beside a ring redraws the window thirty times a second", async ({
|
||||
page,
|
||||
browser,
|
||||
}, testInfo) => {
|
||||
test.setTimeout(180_000);
|
||||
const agent = await openQuietRunningTurn(page);
|
||||
try {
|
||||
const activity = await measureSteadyStateActivity({
|
||||
browser,
|
||||
page,
|
||||
windowMs: SAMPLE_WINDOW_MS,
|
||||
});
|
||||
const turnovers = await recordIndicatorTurnovers(page, 3_000);
|
||||
await writeFile(
|
||||
testInfo.outputPath("evidence.json"),
|
||||
JSON.stringify({ activity, turnovers }, null, 2),
|
||||
);
|
||||
|
||||
expect
|
||||
.soft(activity.compositorFramesPerSecond)
|
||||
.toBeLessThan(RUNNING_TURN_FRAMES_PER_SECOND_BUDGET);
|
||||
// The shimmer moves in steps, and only on the frames the ring moves, so the two cost the
|
||||
// window one set of frames between them.
|
||||
expect.soft(turnovers.shimmer.length).toBeGreaterThan(60);
|
||||
expect.soft(turnovers.shimmer.length).toBeLessThan(turnovers.frames * 0.6);
|
||||
expect.soft(turnovers.shimmer.filter((frame) => !turnovers.ring.includes(frame))).toEqual([]);
|
||||
// It still crosses the whole label, held at each of its even steps.
|
||||
expect.soft(turnovers.shimmerOffsets.length).toBeGreaterThanOrEqual(SHIMMER_MIN_STEPS);
|
||||
expect.soft(turnovers.shimmerOffsets.length).toBeLessThanOrEqual(SHIMMER_MAX_STEPS);
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("hold still when the system asks for reduced motion", async ({
|
||||
page,
|
||||
browser,
|
||||
|
||||
@@ -34,7 +34,9 @@ function report(input: {
|
||||
sourceLabel: input.sourceLabel,
|
||||
icon: ICON,
|
||||
report:
|
||||
input.report.status === "error" || input.report.status === "unavailable"
|
||||
input.report.status === "error" ||
|
||||
input.report.status === "unavailable" ||
|
||||
input.report.status === "not_fetched"
|
||||
? input.report
|
||||
: {
|
||||
status: "available",
|
||||
@@ -138,6 +140,45 @@ test.describe("usage settings", () => {
|
||||
await expect(card.getByText("64% used")).toBeVisible();
|
||||
});
|
||||
|
||||
test("a manual report asks for Refresh and changes only on the user's Refresh", async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(120_000);
|
||||
const serverId = getServerId();
|
||||
const manual = (entry: UsageReportEntry): UsageReportEntry => ({ ...entry, refresh: "manual" });
|
||||
const usage = await installUsageReportsFixture(page, {
|
||||
lists: [
|
||||
(request) => [
|
||||
manual(
|
||||
report({
|
||||
sourceId: "quota",
|
||||
sourceLabel: "Quota",
|
||||
report: request.forceRefresh
|
||||
? { status: "available", windows: [{ id: "w", label: "Weekly", usedPct: 12 }] }
|
||||
: { status: "not_fetched" },
|
||||
}),
|
||||
),
|
||||
],
|
||||
],
|
||||
});
|
||||
|
||||
await gotoAppShell(page);
|
||||
await openSettings(page);
|
||||
await openSettingsHostSection(page, serverId, "usage");
|
||||
const card = page.getByTestId("usage-report-quota:account");
|
||||
await expect(
|
||||
card.getByText("Not checked yet. Quota usage updates only when you refresh it."),
|
||||
).toBeVisible({ timeout: 10_000 });
|
||||
await expect(card.getByText("Error", { exact: true })).toHaveCount(0);
|
||||
expect(forcedRefreshCount(usage)).toBe(0);
|
||||
|
||||
await card.getByTestId("usage-refresh").click();
|
||||
await expect(card.getByText("12% used")).toBeVisible();
|
||||
expect(usage.listRequests().filter((request) => request.forceRefresh)).toEqual([
|
||||
{ forceRefresh: true, reportIds: ["quota:account"] },
|
||||
]);
|
||||
});
|
||||
|
||||
test("asks to update a host without usage support and never calls it", async ({ page }) => {
|
||||
test.setTimeout(120_000);
|
||||
const serverId = getServerId();
|
||||
|
||||
@@ -3,12 +3,17 @@ import type { Locator, Page } from "@playwright/test";
|
||||
import { expect, test } from "../support/fixtures";
|
||||
import { createIdleAgent } from "../support/helpers/archive-tab";
|
||||
import { expectComposerVisible } from "../support/helpers/composer";
|
||||
import { clickNewTerminal, terminalSurfaceLocator } from "../support/helpers/launcher";
|
||||
import {
|
||||
clickNewChat,
|
||||
clickNewTerminal,
|
||||
terminalSurfaceLocator,
|
||||
} from "../support/helpers/launcher";
|
||||
import { renameModalInput } from "../support/helpers/rename";
|
||||
import { seedWorkspace } from "../support/helpers/seed-client";
|
||||
import { getServerId } from "../support/helpers/server-id";
|
||||
import { clickSettingsBackToWorkspace, openCompactSettings } from "../support/helpers/settings";
|
||||
import { openSettings } from "../support/helpers/app";
|
||||
import { gotoAppShell, openSettings } from "../support/helpers/app";
|
||||
import { selectWorkspaceInSidebar } from "../support/helpers/sidebar";
|
||||
import { runWorkspaceActionFromCommandCenter } from "../support/helpers/command-center-workspace-actions";
|
||||
import {
|
||||
clickFirstTerminalTab,
|
||||
@@ -35,8 +40,12 @@ async function expectSameRenderedNode(
|
||||
);
|
||||
}
|
||||
|
||||
function isRenderedNodeConnected(node: Awaited<ReturnType<typeof captureRenderedNode>>) {
|
||||
return node.evaluate((candidate) => candidate.isConnected);
|
||||
}
|
||||
|
||||
async function expectNodeConnected(node: Awaited<ReturnType<typeof captureRenderedNode>>) {
|
||||
expect(await node.evaluate((candidate) => candidate.isConnected)).toBe(true);
|
||||
expect(await isRenderedNodeConnected(node)).toBe(true);
|
||||
}
|
||||
|
||||
async function getSettingsShortcut(page: Page) {
|
||||
@@ -50,6 +59,34 @@ async function waitForWorkspaceRoute(page: Page, route: string) {
|
||||
}
|
||||
|
||||
test.describe("Workspace pane mounting", () => {
|
||||
test("inactive composers expire while switching between other workspaces", async ({
|
||||
page,
|
||||
withWorkspace,
|
||||
}) => {
|
||||
const first = await withWorkspace({ prefix: "deck-expiry-first-" });
|
||||
const second = await withWorkspace({ prefix: "deck-expiry-second-" });
|
||||
const third = await withWorkspace({ prefix: "deck-expiry-third-" });
|
||||
const oneMinute = 60_000;
|
||||
|
||||
await page.clock.install();
|
||||
await gotoAppShell(page);
|
||||
await selectWorkspaceInSidebar(page, first.workspaceId);
|
||||
await clickNewChat(page);
|
||||
const composer = await captureRenderedNode(
|
||||
page.getByTestId("message-input-root").filter({ visible: true }),
|
||||
);
|
||||
|
||||
await selectWorkspaceInSidebar(page, second.workspaceId);
|
||||
await expect(page).toHaveURL(buildHostWorkspaceRoute(getServerId(), second.workspaceId));
|
||||
await page.clock.fastForward(9 * oneMinute);
|
||||
await expectNodeConnected(composer);
|
||||
|
||||
await selectWorkspaceInSidebar(page, third.workspaceId);
|
||||
await expect(page).toHaveURL(buildHostWorkspaceRoute(getServerId(), third.workspaceId));
|
||||
await page.clock.fastForward(2 * oneMinute);
|
||||
await expect.poll(() => isRenderedNodeConnected(composer)).toBe(false);
|
||||
});
|
||||
|
||||
test("workspace navigation keeps the existing agent composer mounted", async ({ page }) => {
|
||||
test.setTimeout(90_000);
|
||||
// Keep both split panes wide enough for the tab-rail interactions below.
|
||||
|
||||
@@ -17,6 +17,7 @@ import { getServerId } from "../support/helpers/server-id";
|
||||
import {
|
||||
clickArchiveWorkspaceMenuItem,
|
||||
expectWorkspaceAbsentFromSidebar,
|
||||
selectSidebarStatusGrouping,
|
||||
} from "../support/helpers/sidebar";
|
||||
import { createTempGitRepo } from "../support/helpers/workspace";
|
||||
import {
|
||||
@@ -100,7 +101,7 @@ async function clickRowArchiveButton(page: Page, workspaceId: string): Promise<v
|
||||
}
|
||||
|
||||
function rowArchivePendingIndicator(page: Page, workspaceId: string) {
|
||||
return workspaceRow(page, workspaceId).getByTestId("workspace-status-indicator-loading");
|
||||
return workspaceRow(page, workspaceId).getByTestId("workspace-archive-pending-indicator");
|
||||
}
|
||||
|
||||
async function cycleThemeAndWaitForSidebar(page: Page, workspaceId: string): Promise<void> {
|
||||
@@ -372,19 +373,38 @@ test.describe("Workspace archive risk warning for worktree backing", () => {
|
||||
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 ({
|
||||
test("the row shows a trailing archive spinner without changing status or shifting layout", async ({
|
||||
page,
|
||||
}) => {
|
||||
const worktree = await createWorktree("archive-risk-pending");
|
||||
const statusRequest = await holdCheckoutStatusRequest(page, worktree);
|
||||
await openSidebarRow(page, worktree.workspaceId);
|
||||
const row = workspaceRow(page, worktree.workspaceId);
|
||||
const title = page.getByTestId(
|
||||
`sidebar-workspace-title-${getServerId()}:${worktree.workspaceId}`,
|
||||
);
|
||||
await expect(rowArchivePendingIndicator(page, worktree.workspaceId)).toHaveCount(0);
|
||||
await expect(row.getByTestId("workspace-status-indicator-done")).toBeVisible();
|
||||
|
||||
const idleRowBox = await row.boundingBox();
|
||||
const idleTitleBox = await title.boundingBox();
|
||||
expect(idleRowBox).not.toBeNull();
|
||||
expect(idleTitleBox).not.toBeNull();
|
||||
|
||||
statusRequest.arm();
|
||||
await clickRowArchiveButton(page, worktree.workspaceId);
|
||||
await statusRequest.waitForHeld();
|
||||
try {
|
||||
await expect(rowArchivePendingIndicator(page, worktree.workspaceId)).toBeVisible();
|
||||
// Leading status must stay done — never turn into the Working status ring.
|
||||
await expect(row.getByTestId("workspace-status-indicator-done")).toBeVisible();
|
||||
await expect(row.getByTestId("workspace-status-indicator-loading")).toHaveCount(0);
|
||||
await expect(row.getByTestId("workspace-status-indicator-running")).toHaveCount(0);
|
||||
|
||||
const archivingRowBox = await row.boundingBox();
|
||||
const archivingTitleBox = await title.boundingBox();
|
||||
expect(archivingRowBox).toEqual(idleRowBox);
|
||||
expect(archivingTitleBox).toEqual(idleTitleBox);
|
||||
expect(statusRequest.archiveRequests()).toBe(0);
|
||||
} finally {
|
||||
statusRequest.release();
|
||||
@@ -394,6 +414,50 @@ test.describe("Workspace archive risk warning for worktree backing", () => {
|
||||
await expect(undoButton(page)).toBeVisible();
|
||||
});
|
||||
|
||||
test("status grouping keeps the row in its original group with no Working badge while archiving", async ({
|
||||
page,
|
||||
}) => {
|
||||
const worktree = await createWorktree("archive-risk-status-pending");
|
||||
const statusRequest = await holdCheckoutStatusRequest(page, worktree);
|
||||
await openSidebarRow(page, worktree.workspaceId);
|
||||
await selectSidebarStatusGrouping(page);
|
||||
|
||||
const doneRows = page.getByTestId("sidebar-status-group-rows-done");
|
||||
const row = doneRows.getByTestId(
|
||||
`sidebar-workspace-row-${getServerId()}:${worktree.workspaceId}`,
|
||||
);
|
||||
const title = row.getByTestId(
|
||||
`sidebar-workspace-title-${getServerId()}:${worktree.workspaceId}`,
|
||||
);
|
||||
await expect(row).toBeVisible();
|
||||
await expect(row.getByTestId("project-status-badge")).toHaveCount(0);
|
||||
|
||||
const idleRowBox = await row.boundingBox();
|
||||
const idleTitleBox = await title.boundingBox();
|
||||
expect(idleRowBox).not.toBeNull();
|
||||
expect(idleTitleBox).not.toBeNull();
|
||||
|
||||
statusRequest.arm();
|
||||
await row.hover();
|
||||
await rowArchiveButton(page, worktree.workspaceId).click();
|
||||
await statusRequest.waitForHeld();
|
||||
try {
|
||||
await expect(row.getByTestId("workspace-archive-pending-indicator")).toBeVisible();
|
||||
// Must remain in the Done group and never gain a Working status ring badge.
|
||||
await expect(row).toBeVisible();
|
||||
await expect(row.getByTestId("project-status-badge")).toHaveCount(0);
|
||||
|
||||
const archivingRowBox = await row.boundingBox();
|
||||
const archivingTitleBox = await title.boundingBox();
|
||||
expect(archivingRowBox).toEqual(idleRowBox);
|
||||
expect(archivingTitleBox).toEqual(idleTitleBox);
|
||||
} finally {
|
||||
statusRequest.release();
|
||||
}
|
||||
|
||||
await expectWorkspaceAbsentFromSidebar(page, worktree.workspaceId);
|
||||
});
|
||||
|
||||
test("a worktree holding only new files warns when the repository hides untracked files", async ({
|
||||
page,
|
||||
}) => {
|
||||
|
||||
@@ -13,6 +13,8 @@ function ad(...args) {
|
||||
});
|
||||
}
|
||||
|
||||
ad("press", 'label="Pair a device"', "--settle");
|
||||
ad("wait", "text", "Relay", "10000");
|
||||
ad("press", 'label="Relay"', "--settle");
|
||||
ad("wait", "text", "Pairing QR code", "10000");
|
||||
const { data } = JSON.parse(ad("snapshot", "-i", "--json"));
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { expect, type Page } from "@playwright/test";
|
||||
import { readScrollMetrics, waitForContentGrowth, expectNearBottom } from "./agent-bottom-anchor";
|
||||
import { agentStopButton } from "./composer";
|
||||
|
||||
export async function awaitAssistantMessage(page: Page, hasText?: string | RegExp): Promise<void> {
|
||||
const messages = page.getByTestId("assistant-message");
|
||||
@@ -14,7 +15,7 @@ export async function awaitToolCall(page: Page, toolName: string | RegExp): Prom
|
||||
}
|
||||
|
||||
export async function expectAgentIdle(page: Page, timeout = 30_000): Promise<void> {
|
||||
await expect(page.getByRole("button", { name: /stop|cancel/i })).toHaveCount(0, { timeout });
|
||||
await expect(agentStopButton(page)).toHaveCount(0, { timeout });
|
||||
}
|
||||
|
||||
// The working indicator is an animated spinner View — no semantic ARIA role, testId is correct.
|
||||
|
||||
@@ -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() };
|
||||
}
|
||||
@@ -103,8 +103,13 @@ export async function expectQueuedMessageButton(page: Page): Promise<void> {
|
||||
});
|
||||
}
|
||||
|
||||
/** The composer's Stop button. Queued rows also have a Cancel button, so match the whole name. */
|
||||
export function agentStopButton(page: Page) {
|
||||
return page.getByRole("button", { name: /^(stop|canceling) agent$/i });
|
||||
}
|
||||
|
||||
export async function cancelAgent(page: Page): Promise<void> {
|
||||
const stopButton = page.getByRole("button", { name: /stop|cancel/i }).first();
|
||||
const stopButton = agentStopButton(page).first();
|
||||
await expect(stopButton).toBeVisible({ timeout: 10_000 });
|
||||
await stopButton.click();
|
||||
}
|
||||
@@ -300,9 +305,7 @@ export async function startRunningMockAgent(
|
||||
await page.goto(agentUrl);
|
||||
await expectComposerVisible(page);
|
||||
await client.sendAgentMessage(agent.id, opts.prompt);
|
||||
await expect(page.getByRole("button", { name: /stop|cancel/i }).first()).toBeVisible({
|
||||
timeout: 30_000,
|
||||
});
|
||||
await expect(agentStopButton(page).first()).toBeVisible({ timeout: 30_000 });
|
||||
return {
|
||||
client,
|
||||
repo,
|
||||
@@ -467,6 +470,12 @@ export async function configureComposerQueueSend(page: Page): Promise<void> {
|
||||
);
|
||||
}
|
||||
|
||||
export async function configureComposerInterruptSend(page: Page): Promise<void> {
|
||||
await page.addInitScript(() =>
|
||||
localStorage.setItem("@paseo:app-settings", JSON.stringify({ sendBehavior: "interrupt" })),
|
||||
);
|
||||
}
|
||||
|
||||
/** Drive the real tab chooser's commands even when fullscreen covers its pointer surface.
|
||||
* This exercises retained activity changes, not a claim that covered chrome is clickable.
|
||||
*/
|
||||
|
||||
@@ -55,6 +55,31 @@ export async function expectHostConfirmationFor(page: Page, host: LinkedHost): P
|
||||
await expect(sheet.getByTestId("host-confirmation-relay")).toHaveText(host.relayEndpoint);
|
||||
}
|
||||
|
||||
/** The warning shown when a link names a saved host but carries a different daemon key. */
|
||||
export async function expectHostIdentityChangedWarning(
|
||||
page: Page,
|
||||
expected: { savedHost: string; savedKey: string; newKey: string; relayEndpoint: string },
|
||||
): Promise<void> {
|
||||
const sheet = hostConfirmation(page);
|
||||
await expect(sheet.getByText("Host identity changed", { exact: true })).toBeVisible({
|
||||
timeout: 30_000,
|
||||
});
|
||||
await expect(sheet.getByTestId("host-confirmation-saved-host")).toHaveText(expected.savedHost);
|
||||
await expect(sheet.getByTestId("host-confirmation-saved-fingerprint")).toHaveText(
|
||||
expected.savedKey,
|
||||
);
|
||||
await expect(sheet.getByTestId("host-confirmation-fingerprint")).toHaveText(expected.newKey);
|
||||
await expect(sheet.getByTestId("host-confirmation-relay")).toHaveText(expected.relayEndpoint);
|
||||
await expect(sheet.getByText(/clears any saved password for this host/)).toBeVisible();
|
||||
}
|
||||
|
||||
export async function replaceHostIdentity(page: Page): Promise<void> {
|
||||
await hostConfirmation(page)
|
||||
.getByRole("button", { name: "Replace host identity", exact: true })
|
||||
.click();
|
||||
await expect(hostConfirmation(page)).toHaveCount(0);
|
||||
}
|
||||
|
||||
export async function cancelHostConfirmation(page: Page): Promise<void> {
|
||||
await hostConfirmation(page).getByRole("button", { name: "Cancel", exact: true }).click();
|
||||
await expect(hostConfirmation(page)).toHaveCount(0);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { expect, type Page } from "@playwright/test";
|
||||
import { expect, type Locator, type Page } from "@playwright/test";
|
||||
import { identityForeground, type IdentityColorName } from "@/styles/identity-colors";
|
||||
import { openSettings } from "./app";
|
||||
import { buildSeededHost } from "./daemon-registry";
|
||||
@@ -289,6 +289,20 @@ export async function expectHostAppearancePreview(
|
||||
);
|
||||
}
|
||||
|
||||
export async function expectHostSelectorStatusIcon(
|
||||
trigger: Locator,
|
||||
options?: { color?: IdentityColorName },
|
||||
): Promise<void> {
|
||||
const icon = trigger.getByTestId("host-status-icon");
|
||||
await expect(icon).toBeVisible({ timeout: 15_000 });
|
||||
await expect(icon.getByTestId("host-status-icon-dot")).toBeVisible();
|
||||
const svg = icon.locator("svg");
|
||||
await expect(svg).toBeVisible();
|
||||
if (options?.color) {
|
||||
await expect(svg).toHaveAttribute("stroke", identityForeground(options.color, "light"));
|
||||
}
|
||||
}
|
||||
|
||||
// The auto-seed fixture rewrites the host registry on every navigation. Setting the
|
||||
// disable-once flag to the current nonce makes it skip exactly one reload, which is what proves
|
||||
// the appearance survived rather than being reseeded.
|
||||
|
||||
@@ -66,6 +66,56 @@ type PairingHost =
|
||||
| Pick<IsolatedHostDaemon, "serverId" | "port">
|
||||
| Pick<OutdatedDaemon, "serverId" | "endpoint">;
|
||||
|
||||
export async function openDevicesPage(page: Page, daemon: PairingHost): Promise<void> {
|
||||
await openAppOnPairingHost(page, daemon);
|
||||
await openSettings(page);
|
||||
await openSettingsHost(page, daemon.serverId);
|
||||
await openSettingsHostSection(page, daemon.serverId, "devices");
|
||||
await expect(page.getByTestId("devices-connected-clients-card")).toBeVisible();
|
||||
}
|
||||
|
||||
export async function expectConnectedClientRow(
|
||||
page: Page,
|
||||
title: string,
|
||||
scopeLabel: string,
|
||||
): Promise<void> {
|
||||
const card = page.getByTestId("devices-connected-clients-card");
|
||||
const row = card.getByRole("button", { name: title, exact: true });
|
||||
await expect(row).toBeVisible();
|
||||
await expect(card.getByText(scopeLabel, { exact: true }).first()).toBeVisible();
|
||||
}
|
||||
|
||||
export async function expandConnectedClientRow(page: Page, title: string): Promise<void> {
|
||||
const card = page.getByTestId("devices-connected-clients-card");
|
||||
await card.getByRole("button", { name: title, exact: true }).click();
|
||||
await expect(card.getByText("Permissions", { exact: true })).toBeVisible();
|
||||
}
|
||||
|
||||
export async function returnFromRelayToWaysToConnect(page: Page): Promise<void> {
|
||||
await page
|
||||
.getByTestId("devices-relay-pairing")
|
||||
.getByRole("button", { name: "Back", exact: true })
|
||||
.click();
|
||||
await expect(page.getByTestId("devices-relay")).toBeVisible();
|
||||
await expect(page.getByRole("switch", { name: "Tailscale", exact: true })).toBeVisible();
|
||||
}
|
||||
|
||||
export async function openPairDeviceWaysSheet(page: Page): Promise<void> {
|
||||
await expect(page.getByTestId("devices-pair-button")).toBeVisible();
|
||||
await page.getByTestId("devices-pair-button").click();
|
||||
await expect(page.getByTestId("devices-relay")).toBeVisible();
|
||||
}
|
||||
|
||||
async function ensurePairDeviceWaysSheetOpen(page: Page): Promise<void> {
|
||||
const relayRow = page.getByTestId("devices-relay");
|
||||
const pairButton = page.getByTestId("devices-pair-button");
|
||||
await relayRow.or(pairButton).first().waitFor({ state: "visible" });
|
||||
if (!(await relayRow.isVisible())) {
|
||||
await pairButton.click();
|
||||
await expect(relayRow).toBeVisible();
|
||||
}
|
||||
}
|
||||
|
||||
export async function preparePairingHost(
|
||||
page: Page,
|
||||
daemon: PairingHost,
|
||||
@@ -74,9 +124,9 @@ export async function preparePairingHost(
|
||||
await openAppOnPairingHost(page, daemon, additionalHosts);
|
||||
await openSettings(page);
|
||||
await openSettingsHost(page, daemon.serverId);
|
||||
await expect(page.getByTestId("devices-relay")).toHaveCount(0);
|
||||
await expect(page.getByTestId("devices-pair-button")).toHaveCount(0);
|
||||
await openSettingsHostSection(page, daemon.serverId, "devices");
|
||||
await expect(page.getByTestId("devices-relay")).toBeVisible();
|
||||
await openPairDeviceWaysSheet(page);
|
||||
}
|
||||
|
||||
/** Loads the app afresh with `daemon` as its first host, then opens the setup's Mobile step. */
|
||||
@@ -185,10 +235,12 @@ export async function cancelTailscaleTurnOff(page: Page, address: string): Promi
|
||||
*/
|
||||
export async function confirmTailscaleTurnOff(page: Page, address: string): Promise<void> {
|
||||
const question = answerNextDialog(page, "accept");
|
||||
await page.getByRole("switch", { name: "Tailscale", exact: true }).click();
|
||||
const sheet = page.getByTestId("devices-pair-sheet");
|
||||
const scope = (await sheet.isVisible()) ? sheet : page;
|
||||
await scope.getByRole("switch", { name: "Tailscale", exact: true }).click();
|
||||
expect(await question).toBe(TURN_OFF_QUESTION);
|
||||
await expect(page.getByText("Host is not connected", { exact: true })).toBeVisible();
|
||||
await expect(page.getByRole("switch", { name: "Tailscale", exact: true })).toHaveCount(0);
|
||||
await expect(scope.getByText("Host is not connected", { exact: true })).toBeVisible();
|
||||
await expect(scope.getByRole("switch", { name: "Tailscale", exact: true })).toHaveCount(0);
|
||||
await expectHostUnreachableAt(address);
|
||||
}
|
||||
|
||||
@@ -372,9 +424,12 @@ function deliverInOrderAfter(delay: () => number, deliver: (message: string | Bu
|
||||
}
|
||||
|
||||
export async function expectTailscaleUpdateRequired(page: Page): Promise<void> {
|
||||
await expect(page.getByRole("switch", { name: "Tailscale", exact: true })).toBeDisabled();
|
||||
await expect(page.getByText("Update this host to use Tailscale", { exact: true })).toBeVisible();
|
||||
await expect(page.getByRole("link", { name: "How to update", exact: true })).toBeVisible();
|
||||
await ensurePairDeviceWaysSheetOpen(page);
|
||||
const sheet = page.getByTestId("devices-pair-sheet");
|
||||
const scope = (await sheet.isVisible()) ? sheet : page;
|
||||
await expect(scope.getByRole("switch", { name: "Tailscale", exact: true })).toBeDisabled();
|
||||
await expect(scope.getByText("Update this host to use Tailscale", { exact: true })).toBeVisible();
|
||||
await expect(scope.getByRole("link", { name: "How to update", exact: true })).toBeVisible();
|
||||
}
|
||||
|
||||
export async function expectTailscaleUnavailable(page: Page): Promise<void> {
|
||||
@@ -460,6 +515,7 @@ export function observeDaemonStatusPolling(page: Page, port: number) {
|
||||
}
|
||||
|
||||
export async function openPairDeviceModal(page: Page): Promise<void> {
|
||||
await ensurePairDeviceWaysSheetOpen(page);
|
||||
await page.getByRole("button", { name: "Relay", exact: true }).click();
|
||||
await expect(page.getByTestId("devices-relay-pairing")).toBeVisible();
|
||||
}
|
||||
@@ -579,9 +635,14 @@ export async function expectPairingDisconnected(page: Page): Promise<void> {
|
||||
}
|
||||
|
||||
export async function switchPairDeviceToHost(page: Page, serverId: string): Promise<void> {
|
||||
const sheet = page.getByTestId("devices-pair-sheet");
|
||||
if (await sheet.isVisible()) {
|
||||
await sheet.getByRole("button", { name: "Close", exact: true }).click();
|
||||
await expect(sheet).toHaveCount(0);
|
||||
}
|
||||
await selectSettingsHost(page, serverId);
|
||||
await expectAppRoute(page, buildSettingsHostSectionRoute(serverId, "devices"));
|
||||
await expect(page.getByTestId("devices-relay")).toBeVisible();
|
||||
await openPairDeviceWaysSheet(page);
|
||||
}
|
||||
|
||||
export async function openRelaySecurityDocs(page: Page): Promise<void> {
|
||||
|
||||
@@ -80,17 +80,38 @@ async function createListedPlugin(root: string) {
|
||||
git("add", "-A");
|
||||
git("commit", "-m", "initial");
|
||||
const date = "2026-10-03T00:00:00.000Z";
|
||||
const commit = git("rev-parse", "HEAD");
|
||||
return {
|
||||
id: LISTING.id,
|
||||
name: LISTING.name,
|
||||
description: LISTING.description,
|
||||
license: "MIT",
|
||||
requirements: { paseo: ">=0.8.0" },
|
||||
categories: ["tools"],
|
||||
author: { github: "acme", name: "Acme" },
|
||||
repository: { url: "https://github.com/acme/directory-example" },
|
||||
author: {
|
||||
github: "acme",
|
||||
name: "Acme",
|
||||
bio: "Building developer workflow plugins for Paseo.",
|
||||
website: "https://acme.dev",
|
||||
},
|
||||
repository: { url: "https://github.com/acme/directory-example", commit },
|
||||
artifact: {
|
||||
kind: "git",
|
||||
remote: pathToFileURL(repository).href,
|
||||
commit: git("rev-parse", "HEAD"),
|
||||
commit,
|
||||
},
|
||||
links: [
|
||||
{ label: "Documentation", url: "https://acme.dev/docs", icon: "book" },
|
||||
{
|
||||
label: "Changelog",
|
||||
url: "https://github.com/acme/directory-example/releases",
|
||||
icon: "changelog",
|
||||
},
|
||||
],
|
||||
funding: [{ platform: "github", url: "https://github.com/sponsors/acme" }],
|
||||
scorecardSummary: {
|
||||
health: { grade: "excellent" },
|
||||
review: { status: "passed", score: 4, noteCount: 0 },
|
||||
},
|
||||
media: [],
|
||||
submittedAt: date,
|
||||
@@ -101,21 +122,169 @@ async function createListedPlugin(root: string) {
|
||||
};
|
||||
}
|
||||
|
||||
function createRelatedFixtures(date: string) {
|
||||
const specs = [
|
||||
[
|
||||
"acme/pr-radar",
|
||||
"PR Radar",
|
||||
"Monitors pull requests and CI checks across connected hosts.",
|
||||
1400,
|
||||
],
|
||||
[
|
||||
"acme/commit-diff",
|
||||
"Commit Diff",
|
||||
"Compact commit history and inline file tree diff viewer.",
|
||||
980,
|
||||
],
|
||||
[
|
||||
"acme/sidebar-plus",
|
||||
"Sidebar Plus",
|
||||
"Groups workspaces into folders with custom status pills.",
|
||||
1120,
|
||||
],
|
||||
[
|
||||
"acme/linear-sync",
|
||||
"Linear Sync",
|
||||
"Attaches Linear tickets to workspaces from slash commands.",
|
||||
860,
|
||||
],
|
||||
[
|
||||
"acme/worktree-guard",
|
||||
"Worktree Guard",
|
||||
"Fast-forwards base branches before creating new worktrees.",
|
||||
740,
|
||||
],
|
||||
[
|
||||
"acme/usage-meter",
|
||||
"Usage Meter",
|
||||
"Shows live token usage and session pacing in the sidebar.",
|
||||
650,
|
||||
],
|
||||
] as const;
|
||||
return specs.map(([id, name, description, installs]) => ({
|
||||
id,
|
||||
name,
|
||||
description,
|
||||
license: "MIT",
|
||||
categories: ["tools"],
|
||||
author: { github: "acme", name: "Acme" },
|
||||
repository: { url: `https://github.com/${id}` },
|
||||
artifact: { kind: "git", remote: `https://github.com/${id}.git`, commit: "a".repeat(40) },
|
||||
scorecardSummary: {
|
||||
health: { grade: "good" },
|
||||
review: { status: "passed", score: 4, noteCount: 0 },
|
||||
},
|
||||
media: [],
|
||||
submittedAt: date,
|
||||
reviewedAt: date,
|
||||
updatedAt: date,
|
||||
publishedAt: date,
|
||||
installs,
|
||||
}));
|
||||
}
|
||||
|
||||
async function startRegistry(listing: Record<string, unknown>) {
|
||||
const date = "2026-10-03T00:00:00.000Z";
|
||||
const commit = (listing.artifact as { commit: string }).commit;
|
||||
const related = createRelatedFixtures(date);
|
||||
const detailDocument = {
|
||||
...listing,
|
||||
readme: `# ${LISTING.name}\n\n${LISTING.overview}\n\n## Capabilities\n\n- Adds a lightweight review checklist panel to every workspace.\n- Works across Desktop, Web, and Mobile without extra setup.`,
|
||||
health: {
|
||||
grade: "excellent",
|
||||
summary: "This plugin is actively maintained.",
|
||||
signals: [
|
||||
{
|
||||
id: "hygiene",
|
||||
summary: "Overview, MIT license, and Paseo version requirement present.",
|
||||
},
|
||||
{
|
||||
id: "maintenance",
|
||||
summary: "Last commit 2 days ago. 64 commits in the past year.",
|
||||
},
|
||||
{
|
||||
id: "responsiveness",
|
||||
summary: "Closed 94% of 18 issues. 2 active contributors.",
|
||||
},
|
||||
{ id: "adoption", summary: "1.2k installations, 86 stars." },
|
||||
],
|
||||
},
|
||||
review: {
|
||||
status: "passed",
|
||||
score: 4,
|
||||
reviewedAt: date,
|
||||
reviewUrl: "https://github.com/getpaseo/plugins/pull/2410",
|
||||
policyUrl: "https://github.com/getpaseo/plugins/blob/main/REVIEW.md",
|
||||
platforms: ["desktop", "web", "ios", "android"],
|
||||
notes: [],
|
||||
passed: [
|
||||
{ id: "integrity", summary: "Artifact matches pinned Git commit hash." },
|
||||
{ id: "lockfile", summary: "No external runtime dependencies or install scripts." },
|
||||
{ id: "obfuscation", summary: "No obfuscation detected." },
|
||||
{ id: "network", summary: "No suspicious network or exfiltration patterns found." },
|
||||
],
|
||||
capabilities: [
|
||||
{
|
||||
id: "cap.workspace",
|
||||
label: "Workspace panel",
|
||||
summary: "Renders a checklist tab inside Paseo workspaces.",
|
||||
details:
|
||||
"Registers a client workspace panel via @getpaseo/plugin/client in index.client.ts.",
|
||||
},
|
||||
{
|
||||
id: "cap.storage",
|
||||
label: "Plugin settings",
|
||||
summary: "Stores checklist templates in plugin-scoped settings.",
|
||||
details:
|
||||
"Uses registerSettings with Zod schema validation; writes no files outside plugin storage.",
|
||||
},
|
||||
],
|
||||
},
|
||||
history: [
|
||||
{
|
||||
label: "v1.2.0",
|
||||
kind: "git",
|
||||
commit,
|
||||
tag: "v1.2.0",
|
||||
publishedAt: date,
|
||||
url: "https://github.com/acme/directory-example/releases/tag/v1.2.0",
|
||||
reviewUrl: "https://github.com/getpaseo/plugins/pull/2410",
|
||||
},
|
||||
{
|
||||
label: "v1.1.0",
|
||||
kind: "git",
|
||||
commit: "b".repeat(40),
|
||||
tag: "v1.1.0",
|
||||
publishedAt: "2026-09-20T00:00:00.000Z",
|
||||
url: "https://github.com/acme/directory-example/releases/tag/v1.1.0",
|
||||
reviewUrl: "https://github.com/getpaseo/plugins/pull/2180",
|
||||
},
|
||||
{
|
||||
label: "c81a4f2",
|
||||
kind: "git",
|
||||
commit: "c81a4f2".padEnd(40, "0"),
|
||||
publishedAt: "2026-09-05T00:00:00.000Z",
|
||||
url: `https://github.com/acme/directory-example/commit/${"c81a4f2".padEnd(40, "0")}`,
|
||||
},
|
||||
],
|
||||
};
|
||||
const documents: Record<string, unknown> = {
|
||||
"/index.json": {
|
||||
schemaVersion: 1,
|
||||
registry: { name: "Local", url: "http://127.0.0.1" },
|
||||
categories: [{ slug: "tools", label: "Tools" }],
|
||||
plugins: [listing],
|
||||
plugins: [listing, ...related],
|
||||
featured: [],
|
||||
generatedAt: "2026-10-03T00:00:00.000Z",
|
||||
},
|
||||
[`/plugins/${LISTING.id}.json`]: {
|
||||
...listing,
|
||||
readme: `# ${LISTING.name}\n\n${LISTING.overview}`,
|
||||
generatedAt: date,
|
||||
},
|
||||
[`/plugins/${LISTING.id}.json`]: detailDocument,
|
||||
};
|
||||
for (const item of related) {
|
||||
documents[`/plugins/${item.id}.json`] = {
|
||||
...item,
|
||||
readme: `# ${item.name}\n\n${item.description}`,
|
||||
};
|
||||
}
|
||||
const server = createServer((request, response) => {
|
||||
const document = request.url ? documents[request.url] : undefined;
|
||||
if (!document) {
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { Page } from "@playwright/test";
|
||||
|
||||
declare global {
|
||||
var __PASEO_E2E_REACT_RENDERS__: Record<string, number> | undefined;
|
||||
var __PASEO_E2E_REACT_COMMITS__: number | undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -54,6 +55,8 @@ export async function recordReactRenders(page: Page): Promise<void> {
|
||||
checkDCE() {},
|
||||
onScheduleFiberRoot() {},
|
||||
onCommitFiberRoot(_rendererId: number, root: { current: Fiber }) {
|
||||
globalThis.__PASEO_E2E_REACT_COMMITS__ =
|
||||
(globalThis.__PASEO_E2E_REACT_COMMITS__ ?? 0) + 1;
|
||||
record(root.current);
|
||||
},
|
||||
onPostCommitFiberRoot() {},
|
||||
@@ -66,6 +69,7 @@ export async function recordReactRenders(page: Page): Promise<void> {
|
||||
export async function resetReactRenders(page: Page): Promise<void> {
|
||||
await page.evaluate(() => {
|
||||
globalThis.__PASEO_E2E_REACT_RENDERS__ = {};
|
||||
globalThis.__PASEO_E2E_REACT_COMMITS__ = 0;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -76,3 +80,11 @@ export async function readReactRenders(page: Page): Promise<Record<string, numbe
|
||||
return { ...globalThis.__PASEO_E2E_REACT_RENDERS__ };
|
||||
});
|
||||
}
|
||||
|
||||
/** React commits since the last reset, read after the next painted frame. */
|
||||
export async function readReactCommits(page: Page): Promise<number> {
|
||||
return page.evaluate(async () => {
|
||||
await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)));
|
||||
return globalThis.__PASEO_E2E_REACT_COMMITS__ ?? 0;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -120,6 +120,72 @@ export async function recordRingAngles(page: Page, windowMs: number): Promise<nu
|
||||
);
|
||||
}
|
||||
|
||||
export interface IndicatorTurnovers {
|
||||
/** Frames sampled, one per animation frame. */
|
||||
frames: number;
|
||||
/** The frames on which the ring's quarter moved. */
|
||||
ring: number[];
|
||||
/** The frames on which the tool-call shimmer's band moved. */
|
||||
shimmer: number[];
|
||||
/** Every horizontal offset the shimmer's band was seen at, in px. */
|
||||
shimmerOffsets: number[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Watches the first visible status ring and the running tool call's shimmer on every animation
|
||||
* frame over the window, and reports on which frames each of them moved.
|
||||
*/
|
||||
export async function recordIndicatorTurnovers(
|
||||
page: Page,
|
||||
windowMs: number,
|
||||
): Promise<IndicatorTurnovers> {
|
||||
const ring = await statusRings(page).first().elementHandle();
|
||||
const shimmer = await runningToolCall(page).getByTestId("label-shimmer").elementHandle();
|
||||
return page.evaluate(
|
||||
({ ring: ringRoot, shimmer: shimmerRoot, sampleWindowMs }) =>
|
||||
new Promise<IndicatorTurnovers>((resolve, reject) => {
|
||||
const movingTarget = (root: Element | null) =>
|
||||
document
|
||||
.getAnimations()
|
||||
.map((animation) => animation.effect)
|
||||
.filter((effect): effect is KeyframeEffect => effect instanceof KeyframeEffect)
|
||||
.find((effect) => effect.target && root?.contains(effect.target))?.target;
|
||||
const quarter = movingTarget(ringRoot);
|
||||
const band = movingTarget(shimmerRoot);
|
||||
if (!quarter || !band) {
|
||||
reject(new Error("The status ring and the shimmer are not both moving"));
|
||||
return;
|
||||
}
|
||||
const read = (element: Element) => getComputedStyle(element).transform;
|
||||
const turnovers: IndicatorTurnovers = {
|
||||
frames: 0,
|
||||
ring: [],
|
||||
shimmer: [],
|
||||
shimmerOffsets: [],
|
||||
};
|
||||
const offsets = new Set<number>();
|
||||
let previous = { ring: read(quarter), shimmer: read(band) };
|
||||
const startedAt = performance.now();
|
||||
const sample = () => {
|
||||
const current = { ring: read(quarter), shimmer: read(band) };
|
||||
turnovers.frames += 1;
|
||||
if (current.ring !== previous.ring) turnovers.ring.push(turnovers.frames);
|
||||
if (current.shimmer !== previous.shimmer) turnovers.shimmer.push(turnovers.frames);
|
||||
offsets.add(Math.round(new DOMMatrixReadOnly(current.shimmer).e * 100) / 100);
|
||||
previous = current;
|
||||
if (performance.now() - startedAt >= sampleWindowMs) {
|
||||
turnovers.shimmerOffsets = [...offsets].sort((first, second) => first - second);
|
||||
resolve(turnovers);
|
||||
return;
|
||||
}
|
||||
requestAnimationFrame(sample);
|
||||
};
|
||||
requestAnimationFrame(sample);
|
||||
}),
|
||||
{ ring, shimmer, sampleWindowMs: windowMs },
|
||||
);
|
||||
}
|
||||
|
||||
/** The loader's current step, or null while the dots are between two readable states. */
|
||||
export async function readLoaderStep(page: Page): Promise<number | null> {
|
||||
const opacities = await loaderDots(page).evaluateAll((dots) =>
|
||||
|
||||
@@ -168,6 +168,11 @@ export interface SeedDaemonClient {
|
||||
timeout?: number,
|
||||
): Promise<{ status: string }>;
|
||||
cancelAgent(agentId: string): Promise<void>;
|
||||
respondToPermission(
|
||||
agentId: string,
|
||||
requestId: string,
|
||||
response: { behavior: "allow" },
|
||||
): Promise<void>;
|
||||
sendAgentMessage(
|
||||
agentId: string,
|
||||
text: string,
|
||||
@@ -182,9 +187,9 @@ export interface SeedDaemonClient {
|
||||
): Promise<{ status: string; final?: { lastError?: string | null } | null }>;
|
||||
archiveAgent(agentId: string): Promise<{ archivedAt: string }>;
|
||||
refreshAgent(agentId: string): Promise<unknown>;
|
||||
fetchAgent(options: {
|
||||
agentId: string;
|
||||
}): Promise<{ agent: { id: string; archivedAt?: string | null } } | null>;
|
||||
fetchAgent(options: { agentId: string }): Promise<{
|
||||
agent: { id: string; archivedAt?: string | null; pendingPermissions: Array<{ id: string }> };
|
||||
} | null>;
|
||||
getLastServerInfoMessage(): {
|
||||
features?: {
|
||||
projectAdd?: boolean;
|
||||
|
||||
@@ -45,7 +45,10 @@ export async function requestStreamingMarkdown(agent: StreamingMarkdownAgent): P
|
||||
|
||||
export async function expectUnfinishedBold(page: Page): Promise<void> {
|
||||
const message = page.getByTestId("assistant-message").last();
|
||||
await expect(message.locator(".enrm-text")).toContainText("Bold");
|
||||
const bold = message.locator("strong");
|
||||
await expect(bold).toContainText("Bold");
|
||||
await expect(bold).toHaveCSS("font-weight", "700");
|
||||
await expect(message).not.toContainText("*");
|
||||
await expect(message).not.toContainText("stays bold");
|
||||
}
|
||||
|
||||
@@ -58,6 +61,7 @@ export async function expectUnfinishedLink(
|
||||
await agent.stream.showThrough("**Bold text stays bold** and [Paseo docs");
|
||||
await expect(message).toContainText("Paseo docs");
|
||||
await expect(message.getByRole("link", { name: "Paseo docs" })).toHaveCount(0);
|
||||
await expect(message).not.toContainText("[");
|
||||
await expect(message).not.toContainText("https:");
|
||||
await captureMarkdown(page, testInfo, "unfinished-link");
|
||||
}
|
||||
|
||||
@@ -175,6 +175,22 @@ export async function reopenWithFreshnessCheckUnanswered(
|
||||
await expect(page.getByRole("alert").filter({ hasText: "Updating messages" })).toBeVisible();
|
||||
}
|
||||
|
||||
/** Reopens display-only history with the tail held until the app shows the outstanding update. */
|
||||
export async function reopenWithTimelineTailUnanswered({
|
||||
page,
|
||||
gate,
|
||||
agentId,
|
||||
}: {
|
||||
page: Page;
|
||||
gate: DaemonWebSocketGate;
|
||||
agentId: string;
|
||||
}): Promise<void> {
|
||||
gate.holdTimelineResponses(agentId);
|
||||
await page.reload();
|
||||
await gate.waitForHeldTimelineResponse();
|
||||
await expect(page.getByRole("alert").filter({ hasText: "Updating messages" })).toBeVisible();
|
||||
}
|
||||
|
||||
export async function answerFreshnessCheck(page: Page, gate: DaemonWebSocketGate): Promise<void> {
|
||||
gate.releaseHeldClientRequest();
|
||||
await expect(page.getByRole("alert").filter({ hasText: "Updating messages" })).toHaveCount(0);
|
||||
@@ -324,6 +340,121 @@ export async function stopStreamingReply(agent: StreamingReplyAgent): Promise<st
|
||||
return reply;
|
||||
}
|
||||
|
||||
interface LoadingSurfaceRecord {
|
||||
loaderText: string[];
|
||||
spinnerYsByTestId: Record<string, number[]>;
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
__loadingSurfaceRecord?: LoadingSurfaceRecord;
|
||||
}
|
||||
}
|
||||
|
||||
function recordLoadingSurfaces(): void {
|
||||
const record: LoadingSurfaceRecord = {
|
||||
loaderText: [],
|
||||
spinnerYsByTestId: {},
|
||||
};
|
||||
window.__loadingSurfaceRecord = record;
|
||||
|
||||
const isVisible = (el: Element | null): el is HTMLElement => {
|
||||
if (!(el instanceof HTMLElement)) return false;
|
||||
const style = window.getComputedStyle(el);
|
||||
if (style.display === "none" || style.visibility === "hidden" || style.opacity === "0") {
|
||||
return false;
|
||||
}
|
||||
const rect = el.getBoundingClientRect();
|
||||
return rect.width > 0 && rect.height > 0;
|
||||
};
|
||||
|
||||
const sample = () => {
|
||||
if (!document.body) return;
|
||||
for (const testId of [
|
||||
"workspace-loading",
|
||||
"agent-loading",
|
||||
"agent-history-overlay",
|
||||
"agent-initial-fill",
|
||||
]) {
|
||||
const el = document.querySelector(`[data-testid="${testId}"]`);
|
||||
if (!isVisible(el)) continue;
|
||||
const text = (el.textContent ?? "").trim();
|
||||
if (text.length > 0 && !record.loaderText.includes(text)) {
|
||||
record.loaderText.push(text);
|
||||
}
|
||||
const spinner = el.querySelector('[role="progressbar"]');
|
||||
if (spinner) {
|
||||
const y = Math.round(spinner.getBoundingClientRect().y);
|
||||
const list = record.spinnerYsByTestId[testId] ?? [];
|
||||
if (!list.includes(y)) list.push(y);
|
||||
record.spinnerYsByTestId[testId] = list;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const start = () => {
|
||||
const observer = new MutationObserver(sample);
|
||||
observer.observe(document.documentElement ?? document, {
|
||||
childList: true,
|
||||
subtree: true,
|
||||
attributes: true,
|
||||
characterData: true,
|
||||
});
|
||||
sample();
|
||||
};
|
||||
|
||||
if (document.documentElement) start();
|
||||
else document.addEventListener("DOMContentLoaded", start, { once: true });
|
||||
}
|
||||
|
||||
/** Records loading text, spinner Y positions, and any Updating messages toast from first paint. */
|
||||
export async function watchColdAndReloadLoadingSurfaces(page: Page): Promise<void> {
|
||||
await page.addInitScript(recordLoadingSurfaces);
|
||||
await page.addInitScript(recordUpdatingToastTiming);
|
||||
}
|
||||
|
||||
/** Checks loading geometry and verifies the toast waits for a slow daemon reply. */
|
||||
export async function expectCleanLoadingSurfaces(
|
||||
page: Page,
|
||||
gate: DaemonWebSocketGate,
|
||||
before: TimelineRequestCounts,
|
||||
): Promise<void> {
|
||||
await gate.waitForServerMessage(TIMELINE_RESPONSE, before.fetches + 1);
|
||||
await expect(page.getByRole("alert").filter({ hasText: "Updating messages" })).toHaveCount(0);
|
||||
await expectToastWaitedForTheDaemon(page);
|
||||
const record = await page.evaluate(() => window.__loadingSurfaceRecord as LoadingSurfaceRecord);
|
||||
expect(record.loaderText, "loading states must not render visible text").toEqual([]);
|
||||
for (const [testId, ys] of Object.entries(record.spinnerYsByTestId)) {
|
||||
expect(
|
||||
ys.length,
|
||||
`${testId} spinner shifted vertically (${ys.join(", ")})`,
|
||||
).toBeLessThanOrEqual(1);
|
||||
}
|
||||
expect(
|
||||
gate.getTimelineRequestCount("after", before.agentId) - before.after,
|
||||
"initial tail load must not trigger a redundant after catch-up",
|
||||
).toBe(0);
|
||||
}
|
||||
|
||||
/** Waits until the persisted replica cache drops coverage to a display-only snapshot. */
|
||||
export async function waitForDisplayOnlyTimelineCache(
|
||||
page: Page,
|
||||
agent: LongTimelineAgent,
|
||||
): Promise<void> {
|
||||
await expect
|
||||
.poll(
|
||||
async () => {
|
||||
const cache = await readReplicaCache(page);
|
||||
const timeline = cache?.hosts
|
||||
?.flatMap((host) => host.timelines)
|
||||
.find((entry) => entry.agentId === agent.agentId);
|
||||
return timeline?.items ? { items: timeline.items.length, range: timeline.range } : null;
|
||||
},
|
||||
{ timeout: 15_000 },
|
||||
)
|
||||
.toMatchObject({ range: null });
|
||||
}
|
||||
|
||||
export async function expectPromptAndWholeReply(
|
||||
page: Page,
|
||||
agent: StreamingReplyAgent,
|
||||
|
||||
@@ -24,6 +24,7 @@
|
||||
"test:e2e": "playwright test --project=browser",
|
||||
"test:e2e:diff-performance": "cross-env PASEO_DIFF_PERF_E2E=1 playwright test --project=browser e2e/browser/diff-performance.spec.ts",
|
||||
"test:e2e:stream-smoothness": "cross-env PASEO_AGENT_STREAM_PERF_E2E=1 playwright test --project=browser e2e/browser/agent-stream-smoothness.spec.ts",
|
||||
"test:e2e:agent-update-cost": "cross-env PASEO_AGENT_UPDATE_PERF_E2E=1 playwright test --project=browser e2e/browser/agent-update-cost.spec.ts",
|
||||
"test:e2e:real": "cross-env E2E_FORK_PASEO_HOME_FROM=../../.dev/paseo-home playwright test --project=real-provider",
|
||||
"test:e2e:relay-deployment": "npm --prefix ../.. run build:server && npm --prefix ../.. run build:daemon-web-ui && cross-env E2E_FORK_PASEO_HOME_FROM=../../.dev/paseo-home playwright test --project=relay-deployment e2e/browser/relay-deployment-reconnect.real.spec.ts",
|
||||
"test:e2e:ui": "playwright test --ui",
|
||||
@@ -40,7 +41,7 @@
|
||||
"dev:ios": "npm --prefix ../.. run build:client && cross-env APP_VARIANT=development expo run:ios",
|
||||
"build:apk": "npm --prefix ../.. run build:apk",
|
||||
"build:apk:arm64": "npm --prefix ../.. run build:apk:arm64",
|
||||
"test:android": "expo prebuild --platform android --no-install && cd android && ./gradlew :paseo-native-trace:testReleaseUnitTest :paseo-hardware-keyboard:testReleaseUnitTest :react-native-enriched-markdown:testReleaseUnitTest --tests '*InlineCodeFormattingTest' --tests '*ListRenderingTest' --tests '*TaskListInteractionTest' --tests '*ListBlockquoteMeasurementTest' --tests '*BlockquoteCopyTest' --tests '*CodeBlockCopyButtonConstructionTest' --tests '*LongPressSelectionInterceptTest' --no-daemon --max-workers=2 -Dorg.gradle.parallel=false"
|
||||
"test:android": "expo prebuild --platform android --no-install && cd android && ./gradlew :paseo-native-trace:testReleaseUnitTest :paseo-hardware-keyboard:testReleaseUnitTest :expo-modules-core:testReleaseUnitTest --tests expo.modules.kotlin.activityresult.AppContextActivityResultRegistryRecreationTest :react-native-enriched-markdown:testReleaseUnitTest --tests '*InlineCodeFormattingTest' --tests '*ListRenderingTest' --tests '*TaskListInteractionTest' --tests '*ListBlockquoteMeasurementTest' --tests '*BlockquoteCopyTest' --tests '*CodeBlockCopyButtonConstructionTest' --tests '*LongPressSelectionInterceptTest' --no-daemon --max-workers=2 -Dorg.gradle.parallel=false"
|
||||
},
|
||||
"dependencies": {
|
||||
"@codemirror/commands": "6.10.4",
|
||||
|
||||
@@ -3,16 +3,19 @@ import { Text, View } from "react-native";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import { Folder, FolderPlus, Plus } from "lucide-react-native";
|
||||
import { AdaptiveModalSheet, type SheetKeyboard } from "@/components/adaptive-modal-sheet";
|
||||
import { HostStatusDot } from "@/components/host-status-dot";
|
||||
import { HostPicker } from "@/components/hosts/host-picker";
|
||||
import { GitHubIcon } from "@/components/icons/github-icon";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { SegmentedControl, type SegmentedControlOption } from "@/components/ui/segmented-control";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { useAddHost } from "@/hosts/add-host";
|
||||
import { HostStatusIcon } from "@/hosts/host-status-icon";
|
||||
import { useHardwareKeyboardPresent, type KeyboardInputEvent } from "@/keyboard";
|
||||
import { Shortcut } from "@/components/ui/shortcut";
|
||||
import { FieldTrigger } from "@/screens/new-workspace/form/field-trigger";
|
||||
import {
|
||||
FieldTrigger,
|
||||
type FieldTriggerInteractionState,
|
||||
} from "@/screens/new-workspace/form/field-trigger";
|
||||
import {
|
||||
useAddProjectFlowStore,
|
||||
type AddProjectFlowRequest,
|
||||
@@ -362,7 +365,12 @@ function HostPill({
|
||||
const [open, setOpen] = useState(false);
|
||||
const openPicker = useCallback(() => setOpen(true), []);
|
||||
const label = hosts.find((host) => host.serverId === hostId)?.label ?? hostId;
|
||||
const icon = useMemo(() => <HostStatusDot serverId={hostId} />, [hostId]);
|
||||
const renderIcon = useCallback(
|
||||
({ backdrop }: FieldTriggerInteractionState) => (
|
||||
<HostStatusIcon serverId={hostId} size="sm" backdrop={backdrop} />
|
||||
),
|
||||
[hostId],
|
||||
);
|
||||
return (
|
||||
<HostPicker
|
||||
hosts={hosts}
|
||||
@@ -383,7 +391,7 @@ function HostPill({
|
||||
label="Host"
|
||||
accessibilityLabel="Project host"
|
||||
tooltip="Host"
|
||||
icon={icon}
|
||||
icon={renderIcon}
|
||||
value={label}
|
||||
onPress={openPicker}
|
||||
disabled={disabled}
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
import { useActivatedStore } from "@/sync";
|
||||
import { createAgentQueueModel, type AgentQueueModel, type AgentQueueSnapshot } from "./model";
|
||||
|
||||
export type { AgentQueueModel, AgentQueueSnapshot } from "./model";
|
||||
export { optimisticEnqueueAgentMessage } from "./overlays";
|
||||
|
||||
/** Observes one agent's queue while the caller is mounted in a visible panel. */
|
||||
export function useAgentQueue(
|
||||
serverId: string,
|
||||
agentId: string,
|
||||
): { model: AgentQueueModel; queue: AgentQueueSnapshot } {
|
||||
const { store, snapshot } = useActivatedStore(JSON.stringify([serverId, agentId]), (active) =>
|
||||
createAgentQueueModel({ serverId, agentId, initialActive: active }),
|
||||
);
|
||||
return { model: store, queue: snapshot };
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
import { afterEach, expect, test } from "vitest";
|
||||
import {
|
||||
queuedItem,
|
||||
queueOf,
|
||||
startAgentQueueDaemon,
|
||||
type AgentQueueDaemon,
|
||||
} from "@/test/agent-queue-daemon";
|
||||
import { createAgentQueueModel } from "./model";
|
||||
|
||||
const daemons: AgentQueueDaemon[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(daemons.splice(0).map((daemon) => daemon.close()));
|
||||
});
|
||||
|
||||
/** An observed queue model over a daemon that already holds the given rows. */
|
||||
async function observeQueue(
|
||||
queue = queueOf("a", "b"),
|
||||
options?: Parameters<typeof startAgentQueueDaemon>[0],
|
||||
) {
|
||||
const daemon = await startAgentQueueDaemon(options);
|
||||
daemons.push(daemon);
|
||||
await daemon.publish("agent", queue);
|
||||
const model = createAgentQueueModel({ serverId: "host", agentId: "agent", host: daemon.host });
|
||||
model.subscribe(() => {});
|
||||
await daemon.settle();
|
||||
const rowIds = () => model.getSnapshot().items.map((entry) => entry.id);
|
||||
return { daemon, model, rowIds };
|
||||
}
|
||||
|
||||
test("shows the queue the host holds and follows its changes", async () => {
|
||||
const held = { held: true, items: [queuedItem("a", { held: true })] };
|
||||
const { daemon, model, rowIds } = await observeQueue(held);
|
||||
expect(model.getSnapshot()).toEqual({ status: "ready", ...held, busy: new Set() });
|
||||
expect(model.getSnapshot()).toBe(model.getSnapshot());
|
||||
|
||||
await daemon.publish("agent", queueOf("b"));
|
||||
await daemon.settle();
|
||||
|
||||
expect(rowIds()).toEqual(["b"]);
|
||||
expect(model.getSnapshot().held).toBe(false);
|
||||
});
|
||||
|
||||
test("releases the host subscription while inactive and catches up on its changes", async () => {
|
||||
const { daemon, model, rowIds } = await observeQueue();
|
||||
|
||||
model.setActive(false);
|
||||
await daemon.settle();
|
||||
expect(daemon.liveSubscriptions()).toEqual([]);
|
||||
expect(model.getSnapshot().status).toBe("stale");
|
||||
expect(rowIds()).toEqual(["a", "b"]);
|
||||
|
||||
await daemon.publish("agent", queueOf("b", "c"));
|
||||
model.setActive(true);
|
||||
await daemon.settle();
|
||||
expect(daemon.syncAnswers()).toEqual(["snapshot", "changes"]);
|
||||
expect(model.getSnapshot().status).toBe("ready");
|
||||
expect(rowIds()).toEqual(["b", "c"]);
|
||||
});
|
||||
|
||||
test("offers a retry when the queue cannot be read", async () => {
|
||||
const daemon = await startAgentQueueDaemon();
|
||||
daemons.push(daemon);
|
||||
await daemon.publish("agent", queueOf("a"));
|
||||
daemon.failNextSync("queue unavailable");
|
||||
const model = createAgentQueueModel({ serverId: "host", agentId: "agent", host: daemon.host });
|
||||
model.subscribe(() => {});
|
||||
await daemon.settle();
|
||||
expect(model.getSnapshot().status).toBe("error");
|
||||
|
||||
model.retry();
|
||||
expect(model.getSnapshot().status).toBe("retrying");
|
||||
await daemon.settle();
|
||||
|
||||
expect(model.getSnapshot()).toMatchObject({ status: "ready", items: [queuedItem("a")] });
|
||||
});
|
||||
|
||||
test("marks a row busy while it is withdrawn, then hides it ahead of the host update", async () => {
|
||||
const { daemon, model, rowIds } = await observeQueue();
|
||||
|
||||
const first = model.withdraw("a");
|
||||
const second = model.withdraw("a");
|
||||
expect(model.getSnapshot().busy).toEqual(new Set(["a"]));
|
||||
|
||||
expect(await first).toEqual({ withdrawn: true, item: queuedItem("a") });
|
||||
expect(await second).toBeNull();
|
||||
expect(daemon.commands()).toHaveLength(1);
|
||||
expect(model.getSnapshot().busy).toEqual(new Set());
|
||||
expect(rowIds()).toEqual(["b"]);
|
||||
expect(await model.withdraw("a")).toBeNull();
|
||||
|
||||
// A later change to the row is the host's truth again.
|
||||
await daemon.publish("agent", {
|
||||
held: false,
|
||||
items: [queuedItem("a", { text: "edited" }), queuedItem("b", { seq: 2 })],
|
||||
});
|
||||
await daemon.settle();
|
||||
expect(rowIds()).toEqual(["a", "b"]);
|
||||
});
|
||||
|
||||
test("hides a withdrawn row even when an older update overtakes the answer", async () => {
|
||||
const { daemon, model, rowIds } = await observeQueue();
|
||||
|
||||
daemon.holdCommands();
|
||||
const result = model.withdraw("a");
|
||||
await daemon.publish("agent", queueOf("a", "b", "c"));
|
||||
daemon.releaseCommands();
|
||||
await result;
|
||||
await daemon.settle();
|
||||
|
||||
expect(rowIds()).toEqual(["b", "c"]);
|
||||
});
|
||||
|
||||
test("optimistic cancel hides the row immediately and restores it if the host refuses", async () => {
|
||||
const { daemon, model, rowIds } = await observeQueue();
|
||||
|
||||
daemon.holdCommands();
|
||||
const pending = model.withdraw("a", { optimistic: true });
|
||||
expect(rowIds()).toEqual(["b"]);
|
||||
|
||||
daemon.refuseWithdrawals("already_dispatching");
|
||||
daemon.releaseCommands();
|
||||
expect(await pending).toEqual({ withdrawn: false, reason: "already_dispatching" });
|
||||
expect(rowIds()).toEqual(["a", "b"]);
|
||||
});
|
||||
|
||||
test("optimistic promote marks the row dispatching, clears held, and rolls back if refused", async () => {
|
||||
const { daemon, model } = await observeQueue({
|
||||
held: true,
|
||||
items: [queuedItem("a", { held: true }), queuedItem("b", { seq: 2, held: true })],
|
||||
});
|
||||
|
||||
daemon.holdCommands();
|
||||
const pending = model.promote("b", "interrupt");
|
||||
expect(model.getSnapshot().held).toBe(false);
|
||||
expect(model.getSnapshot().items.find((item) => item.id === "b")?.state).toBe("dispatching");
|
||||
|
||||
daemon.refusePromotions("already_dispatching");
|
||||
daemon.releaseCommands();
|
||||
expect(await pending).toEqual({ promoted: false, reason: "already_dispatching" });
|
||||
expect(model.getSnapshot().held).toBe(true);
|
||||
expect(model.getSnapshot().items.find((item) => item.id === "b")?.state).toBe("queued");
|
||||
});
|
||||
|
||||
test("keeps the row when the host already started sending it", async () => {
|
||||
const { daemon, model, rowIds } = await observeQueue();
|
||||
daemon.refuseWithdrawals("already_dispatching");
|
||||
|
||||
expect(await model.withdraw("a")).toEqual({ withdrawn: false, reason: "already_dispatching" });
|
||||
|
||||
expect(rowIds()).toEqual(["a", "b"]);
|
||||
expect(model.getSnapshot().busy).toEqual(new Set());
|
||||
});
|
||||
|
||||
test("takes no command for a dispatching or absent row", async () => {
|
||||
const { daemon, model } = await observeQueue({
|
||||
held: false,
|
||||
items: [queuedItem("a", { state: "dispatching" })],
|
||||
});
|
||||
|
||||
expect(await model.withdraw("a")).toBeNull();
|
||||
expect(await model.promote("missing", "steer")).toBeNull();
|
||||
expect(daemon.commands()).toEqual([]);
|
||||
});
|
||||
|
||||
test("promotes a row with the chosen send behavior", async () => {
|
||||
const { daemon, model } = await observeQueue();
|
||||
|
||||
expect(await model.promote("b", "interrupt")).toEqual({ promoted: true });
|
||||
|
||||
expect(daemon.commands()).toMatchObject([
|
||||
{
|
||||
type: "agent.queue.promote.request",
|
||||
agentId: "agent",
|
||||
messageId: "b",
|
||||
activeTurnBehavior: "interrupt",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test("rejects a command and releases the row while the host is disconnected", async () => {
|
||||
const { daemon, model, rowIds } = await observeQueue();
|
||||
await daemon.disconnect();
|
||||
await daemon.settle();
|
||||
|
||||
await expect(model.withdraw("a")).rejects.toThrow("Host disconnected");
|
||||
|
||||
expect(daemon.commands()).toEqual([]);
|
||||
expect(model.getSnapshot()).toMatchObject({ status: "stale", busy: new Set() });
|
||||
expect(rowIds()).toEqual(["a", "b"]);
|
||||
});
|
||||
|
||||
test("has no queue and asks nothing of a host without the feature", async () => {
|
||||
const { daemon, model } = await observeQueue(queueOf("a"), { features: {} });
|
||||
|
||||
expect(model.getSnapshot()).toMatchObject({ status: "ready", items: [] });
|
||||
expect(daemon.requestCount()).toBe(0);
|
||||
});
|
||||
@@ -0,0 +1,156 @@
|
||||
import { AgentQueueCollection, type PaseoAgentQueueItem, type SyncStatus } from "@getpaseo/client";
|
||||
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
import type { ActiveTurnBehavior } from "@getpaseo/protocol/messages";
|
||||
import {
|
||||
createHostSyncStore,
|
||||
type HostSyncConnection,
|
||||
hostRuntimeSyncHost,
|
||||
type SyncClient,
|
||||
} from "@/sync";
|
||||
import { optimisticPromoteAgentQueueItem, optimisticRemoveAgentQueueItem } from "./overlays";
|
||||
|
||||
type AgentQueueClient = SyncClient &
|
||||
Pick<DaemonClient, "withdrawAgentQueueItem" | "promoteAgentQueueItem">;
|
||||
|
||||
export interface AgentQueueSnapshot {
|
||||
status: SyncStatus;
|
||||
/** The host waits for Send now or the next prompt before it sends these. */
|
||||
held: boolean;
|
||||
/** Admission order. The first row is sent next. */
|
||||
items: readonly PaseoAgentQueueItem[];
|
||||
/** Rows with a command or optimistic enqueue in flight. */
|
||||
busy: ReadonlySet<string>;
|
||||
}
|
||||
|
||||
/**
|
||||
* One agent's queue as the host holds it, with optimistic overlays for in-flight queue commands.
|
||||
*/
|
||||
export function createAgentQueueModel({
|
||||
serverId,
|
||||
agentId,
|
||||
initialActive,
|
||||
host = hostRuntimeSyncHost(serverId),
|
||||
}: {
|
||||
serverId: string;
|
||||
agentId: string;
|
||||
initialActive?: boolean;
|
||||
host?: HostSyncConnection<AgentQueueClient>;
|
||||
}) {
|
||||
const store = createHostSyncStore({
|
||||
host,
|
||||
resource: AgentQueueCollection,
|
||||
args: { agentId },
|
||||
// COMPAT(agentMessageQueue): added in v0.18.2, remove gate after 2027-06-01.
|
||||
feature: "agentMessageQueue",
|
||||
active: initialActive,
|
||||
});
|
||||
let busy: ReadonlySet<string> = new Set();
|
||||
let view: { source: unknown; busy: ReadonlySet<string>; snapshot: AgentQueueSnapshot } | null =
|
||||
null;
|
||||
const listeners = new Set<() => void>();
|
||||
|
||||
const getSnapshot = (): AgentQueueSnapshot => {
|
||||
const source = store.getSnapshot();
|
||||
if (view?.source !== source || view.busy !== busy) {
|
||||
view = {
|
||||
source,
|
||||
busy,
|
||||
snapshot: {
|
||||
status: source.status,
|
||||
held: source.data?.meta.held ?? false,
|
||||
items: source.data?.items ?? [],
|
||||
busy: mergeSets(busy, source.pending),
|
||||
},
|
||||
};
|
||||
}
|
||||
return view.snapshot;
|
||||
};
|
||||
const changed = () => {
|
||||
view = null;
|
||||
for (const listener of listeners) listener();
|
||||
};
|
||||
|
||||
const connected = (): AgentQueueClient => {
|
||||
const client = host.getClient();
|
||||
if (!client?.getLastServerInfoMessage()) throw new Error("Host disconnected");
|
||||
return client;
|
||||
};
|
||||
|
||||
/** Runs one command per row at a time. Returns null when the row cannot take one. */
|
||||
const command = async <T>(
|
||||
messageId: string,
|
||||
run: (client: AgentQueueClient) => Promise<T>,
|
||||
): Promise<T | null> => {
|
||||
const snapshot = getSnapshot();
|
||||
const row = snapshot.items.find((entry) => entry.id === messageId);
|
||||
if (!row || row.state === "dispatching" || snapshot.busy.has(messageId)) return null;
|
||||
const client = connected();
|
||||
busy = new Set(busy).add(messageId);
|
||||
changed();
|
||||
try {
|
||||
return await run(client);
|
||||
} finally {
|
||||
const next = new Set(busy);
|
||||
next.delete(messageId);
|
||||
busy = next;
|
||||
changed();
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
getSnapshot,
|
||||
subscribe(listener: () => void) {
|
||||
listeners.add(listener);
|
||||
const unsubscribe = store.subscribe(listener);
|
||||
return () => {
|
||||
listeners.delete(listener);
|
||||
unsubscribe();
|
||||
};
|
||||
},
|
||||
setActive: store.setActive,
|
||||
retry: store.retry,
|
||||
withdraw: (messageId: string, options?: { optimistic?: boolean }) =>
|
||||
command(messageId, async (client) => {
|
||||
if (options?.optimistic) {
|
||||
const overlay = optimisticRemoveAgentQueueItem(client, agentId, messageId);
|
||||
try {
|
||||
const result = await client.withdrawAgentQueueItem(agentId, messageId);
|
||||
if (result.withdrawn) overlay.commit();
|
||||
else overlay.rollback();
|
||||
return result;
|
||||
} catch (error) {
|
||||
overlay.rollback();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
const result = await client.withdrawAgentQueueItem(agentId, messageId);
|
||||
// The host confirmed the removal. Hide the row now so it is not pressable again
|
||||
// between this answer and the next update.
|
||||
if (result.withdrawn) optimisticRemoveAgentQueueItem(client, agentId, messageId).commit();
|
||||
return result;
|
||||
}),
|
||||
promote: (messageId: string, activeTurnBehavior: ActiveTurnBehavior) =>
|
||||
command(messageId, async (client) => {
|
||||
const overlay = optimisticPromoteAgentQueueItem(client, agentId, messageId);
|
||||
try {
|
||||
const result = await client.promoteAgentQueueItem(agentId, messageId, activeTurnBehavior);
|
||||
if (result.promoted) overlay.commit();
|
||||
else overlay.rollback();
|
||||
return result;
|
||||
} catch (error) {
|
||||
overlay.rollback();
|
||||
throw error;
|
||||
}
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
function mergeSets(left: ReadonlySet<string>, right: ReadonlySet<string>): ReadonlySet<string> {
|
||||
if (left.size === 0) return right;
|
||||
if (right.size === 0) return left;
|
||||
const merged = new Set(left);
|
||||
for (const value of right) merged.add(value);
|
||||
return merged;
|
||||
}
|
||||
|
||||
export type AgentQueueModel = ReturnType<typeof createAgentQueueModel>;
|
||||
@@ -0,0 +1,89 @@
|
||||
import {
|
||||
AgentQueueCollection,
|
||||
type CollectionState,
|
||||
type PaseoAgentQueueItem,
|
||||
type SyncOptimisticHandle,
|
||||
} from "@getpaseo/client";
|
||||
import type { SyncClient } from "@/sync";
|
||||
|
||||
type QueueCollectionState = CollectionState<PaseoAgentQueueItem, { held: boolean }>;
|
||||
|
||||
function buildQueueState(
|
||||
byId: Map<string, PaseoAgentQueueItem>,
|
||||
meta: { held: boolean },
|
||||
): QueueCollectionState {
|
||||
const items = Array.from(byId.values());
|
||||
if (AgentQueueCollection.compare) items.sort(AgentQueueCollection.compare);
|
||||
return { items, byId, meta };
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows a newly queued message immediately in FIFO order and clears any paused banner until the
|
||||
* host confirms or rejects the send.
|
||||
*/
|
||||
export function optimisticEnqueueAgentMessage(
|
||||
client: Pick<SyncClient, "sync">,
|
||||
agentId: string,
|
||||
item: Omit<PaseoAgentQueueItem, "seq">,
|
||||
): SyncOptimisticHandle {
|
||||
return client.sync(AgentQueueCollection, { agentId }).optimistic({
|
||||
key: item.id,
|
||||
apply: (state) => {
|
||||
if (state?.byId.has(item.id)) return state;
|
||||
let maxSeq = 0;
|
||||
if (state) {
|
||||
for (const existing of state.items) {
|
||||
if (existing.seq > maxSeq) maxSeq = existing.seq;
|
||||
}
|
||||
}
|
||||
const byId = new Map(state?.byId);
|
||||
byId.set(item.id, { ...item, seq: maxSeq + 1 });
|
||||
return buildQueueState(byId, { held: false });
|
||||
},
|
||||
settled: (authoritative) => authoritative.byId.has(item.id),
|
||||
});
|
||||
}
|
||||
|
||||
/** Hides a withdrawn or cancelled row until the host update removes it. */
|
||||
export function optimisticRemoveAgentQueueItem(
|
||||
client: Pick<SyncClient, "sync">,
|
||||
agentId: string,
|
||||
messageId: string,
|
||||
): SyncOptimisticHandle {
|
||||
return client.sync(AgentQueueCollection, { agentId }).optimistic({
|
||||
apply: (state) => {
|
||||
if (!state || !state.byId.has(messageId)) return state;
|
||||
const byId = new Map(state.byId);
|
||||
byId.delete(messageId);
|
||||
return {
|
||||
items: state.items.filter((item) => item.id !== messageId),
|
||||
byId,
|
||||
meta: state.meta,
|
||||
};
|
||||
},
|
||||
settled: (authoritative) => !authoritative.byId.has(messageId),
|
||||
});
|
||||
}
|
||||
|
||||
/** Marks a promoted row dispatching and clears any paused banner while the host dispatches it. */
|
||||
export function optimisticPromoteAgentQueueItem(
|
||||
client: Pick<SyncClient, "sync">,
|
||||
agentId: string,
|
||||
messageId: string,
|
||||
): SyncOptimisticHandle {
|
||||
return client.sync(AgentQueueCollection, { agentId }).optimistic({
|
||||
apply: (state) => {
|
||||
if (!state) return state;
|
||||
const existing = state.byId.get(messageId);
|
||||
if (!existing) return state;
|
||||
if (existing.state === "dispatching" && !state.meta.held) return state;
|
||||
const byId = new Map(state.byId);
|
||||
byId.set(messageId, { ...existing, state: "dispatching", held: false });
|
||||
return buildQueueState(byId, { held: false });
|
||||
},
|
||||
settled: (authoritative) => {
|
||||
const item = authoritative.byId.get(messageId);
|
||||
return !item || item.state === "dispatching";
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -166,4 +166,92 @@ describe("reading anchor", () => {
|
||||
),
|
||||
).toBe(0);
|
||||
});
|
||||
|
||||
it("transfers ownership to the next visible row and compensates simultaneous growth above when the anchor is hidden", () => {
|
||||
const anchor = createReadingAnchor();
|
||||
const initial = [
|
||||
{ id: "above", top: 0, height: 500 },
|
||||
{ id: "plugin", top: 500, height: 24 },
|
||||
{ id: "next", top: 524, height: 200 },
|
||||
];
|
||||
anchor.reconcile(500, initial);
|
||||
expect(anchor.getRowId()).toBe("plugin");
|
||||
|
||||
// In one layout commit, "plugin" is hidden and "above" grows by 80px.
|
||||
const nextRows = [
|
||||
{ id: "above", top: 0, height: 580 },
|
||||
{ id: "next", top: 580, height: 200 },
|
||||
];
|
||||
expect(anchor.reconcile(500, nextRows, false, undefined, new Set(["plugin"]))).toBe(580);
|
||||
expect(anchor.getRowId()).toBe("next");
|
||||
});
|
||||
|
||||
it("preserves top margin and avoids overshooting when hiding a tall or top-inset anchor", () => {
|
||||
const topInsetAnchor = createReadingAnchor();
|
||||
topInsetAnchor.reconcile(0, [
|
||||
{ id: "plugin", top: 48, height: 40 },
|
||||
{ id: "next", top: 88, height: 100 },
|
||||
]);
|
||||
expect(
|
||||
topInsetAnchor.reconcile(
|
||||
0,
|
||||
[{ id: "next", top: 48, height: 100 }],
|
||||
false,
|
||||
undefined,
|
||||
new Set(["plugin"]),
|
||||
),
|
||||
).toBe(0);
|
||||
expect(topInsetAnchor.getRowId()).toBe("next");
|
||||
|
||||
const tallAnchor = createReadingAnchor();
|
||||
tallAnchor.reconcile(650, [
|
||||
{ id: "above", top: 0, height: 500 },
|
||||
{ id: "tall-plugin", top: 500, height: 300 },
|
||||
{ id: "next", top: 800, height: 100 },
|
||||
]);
|
||||
expect(
|
||||
tallAnchor.reconcile(
|
||||
650,
|
||||
[
|
||||
{ id: "above", top: 0, height: 580 },
|
||||
{ id: "next", top: 580, height: 100 },
|
||||
],
|
||||
false,
|
||||
undefined,
|
||||
new Set(["tall-plugin"]),
|
||||
),
|
||||
).toBe(580);
|
||||
expect(tallAnchor.getRowId()).toBe("next");
|
||||
});
|
||||
|
||||
it("falls back to the preceding visible row when the hidden anchor was the last row", () => {
|
||||
const anchor = createReadingAnchor();
|
||||
anchor.reconcile(500, [
|
||||
{ id: "above", top: 0, height: 300 },
|
||||
{ id: "prev", top: 300, height: 200 },
|
||||
{ id: "last-plugin", top: 500, height: 40 },
|
||||
]);
|
||||
expect(anchor.getRowId()).toBe("last-plugin");
|
||||
|
||||
expect(
|
||||
anchor.reconcile(
|
||||
500,
|
||||
[
|
||||
{ id: "above", top: 0, height: 380 },
|
||||
{ id: "prev", top: 380, height: 200 },
|
||||
],
|
||||
false,
|
||||
undefined,
|
||||
new Set(["last-plugin"]),
|
||||
),
|
||||
).toBe(580);
|
||||
expect(anchor.getRowId()).toBe("prev");
|
||||
});
|
||||
|
||||
it("still retains an unmounted virtual anchor when it is not marked hidden", () => {
|
||||
const anchor = createReadingAnchor();
|
||||
anchor.reconcile(600, rows);
|
||||
expect(anchor.reconcile(600, [rows[2]!], false, undefined, new Set(["other"]))).toBe(600);
|
||||
expect(anchor.getRowId()).toBe("reading");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -16,6 +16,48 @@ export interface ReadingRowReplacements {
|
||||
}
|
||||
const NO_REPLACEMENTS: ReadingRowReplacements = new Map();
|
||||
|
||||
function findHiddenAnchorReplacement(input: {
|
||||
previousGeometry: readonly RowGeometry[];
|
||||
rows: readonly RowGeometry[];
|
||||
anchorId: string;
|
||||
originalAnchorId: string;
|
||||
baseScrollTop: number;
|
||||
}): { row: RowGeometry; correctedTop: number } | null {
|
||||
const { previousGeometry, rows, anchorId, originalAnchorId, baseScrollTop } = input;
|
||||
const oldIndex = previousGeometry.findIndex(
|
||||
(row) => row.id === anchorId || row.id === originalAnchorId,
|
||||
);
|
||||
const oldAnchor = oldIndex >= 0 ? previousGeometry[oldIndex] : undefined;
|
||||
if (!oldAnchor) {
|
||||
return null;
|
||||
}
|
||||
const rowsById = new Map(rows.map((row) => [row.id, row]));
|
||||
for (let index = oldIndex + 1; index < previousGeometry.length; index += 1) {
|
||||
const candidate = rowsById.get(previousGeometry[index]!.id);
|
||||
if (!candidate) continue;
|
||||
return {
|
||||
row: candidate,
|
||||
correctedTop: Math.max(
|
||||
0,
|
||||
Math.min(baseScrollTop, oldAnchor.top) + (candidate.top - oldAnchor.top),
|
||||
),
|
||||
};
|
||||
}
|
||||
for (let index = oldIndex - 1; index >= 0; index -= 1) {
|
||||
const oldPrev = previousGeometry[index]!;
|
||||
const candidate = rowsById.get(oldPrev.id);
|
||||
if (!candidate) continue;
|
||||
return {
|
||||
row: candidate,
|
||||
correctedTop: Math.max(
|
||||
0,
|
||||
baseScrollTop + (candidate.top + candidate.height) - (oldPrev.top + oldPrev.height),
|
||||
),
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Content coordinates survive user scrolling. Layout commits replace the geometry;
|
||||
// scroll events reuse it, without another DOM measurement pass.
|
||||
export function createReadingAnchor() {
|
||||
@@ -64,12 +106,31 @@ export function createReadingAnchor() {
|
||||
rows: readonly RowGeometry[],
|
||||
userScrolled = false,
|
||||
replacements = NO_REPLACEMENTS,
|
||||
hiddenRowIds?: ReadonlySet<string>,
|
||||
): number {
|
||||
const previousGeometry = geometry;
|
||||
geometry = rows;
|
||||
const previous = anchor && rows.find((row) => row.id === getRowId(replacements));
|
||||
// The first virtualized commit can precede its mounted range. Keep the
|
||||
// pinned reader until it mounts, rather than adopting an unrelated row.
|
||||
if (anchor && !previous && !userScrolled) return scrollTop;
|
||||
const anchorId = getRowId(replacements);
|
||||
const previous = anchor && rows.find((row) => row.id === anchorId);
|
||||
if (anchor && !previous && !userScrolled) {
|
||||
// The first virtualized commit can precede its mounted range. Keep the
|
||||
// pinned reader until it mounts, rather than adopting an unrelated row.
|
||||
if (!anchorId || !hiddenRowIds?.has(anchorId)) return scrollTop;
|
||||
const replacement = findHiddenAnchorReplacement({
|
||||
previousGeometry,
|
||||
rows,
|
||||
anchorId,
|
||||
originalAnchorId: anchor.id,
|
||||
baseScrollTop: anchor.pinnedScrollTop ?? scrollTop,
|
||||
});
|
||||
if (replacement) {
|
||||
anchor = anchorTop(replacement.row);
|
||||
return replacement.correctedTop;
|
||||
}
|
||||
const fallback = readingRow(scrollTop);
|
||||
anchor = fallback ? anchorTop(fallback) : null;
|
||||
return scrollTop;
|
||||
}
|
||||
const correctedTop = project(scrollTop, previous ?? undefined, replacements);
|
||||
// A prepend can expose the bottom of an estimated row above the reader.
|
||||
// Do not transfer ownership to it until the user moves the reading position.
|
||||
|
||||
@@ -26,7 +26,6 @@ import {
|
||||
} from "@legendapp/list/react-native";
|
||||
import { withUnistyles } from "react-native-unistyles";
|
||||
import { LoadingSpinner } from "@/components/ui/loading-spinner";
|
||||
import { LoadingState } from "@/components/ui/loading-state";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useRetainedPanelActive } from "@/components/retained-panel";
|
||||
import { useNativeSplashHold } from "@/native-splash";
|
||||
@@ -123,15 +122,6 @@ function distanceFromEnd(input: {
|
||||
return Math.max(0, input.contentHeight - input.viewportHeight - input.offsetY);
|
||||
}
|
||||
const viewportStyle: ViewStyle = { flex: 1 };
|
||||
const initialFillStyle: ViewStyle = {
|
||||
position: "absolute",
|
||||
top: 0,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
left: 0,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
};
|
||||
|
||||
function keyExtractor(item: { id: string }): string {
|
||||
return item.id;
|
||||
@@ -159,6 +149,7 @@ function NativeStreamViewport(props: StreamRenderInput & { strategy: StreamStrat
|
||||
isAuthoritativeHistoryReady,
|
||||
isInitialHistoryLoading,
|
||||
revealInitialHistory,
|
||||
onInitialHistoryVisibilityChange,
|
||||
onNearBottomChange,
|
||||
onNearHistoryStart,
|
||||
isLoadingOlderHistory,
|
||||
@@ -265,6 +256,12 @@ function NativeStreamViewport(props: StreamRenderInput & { strategy: StreamStrat
|
||||
() => historyStartPagination.state.status === "settling",
|
||||
);
|
||||
const finishInitialFill = useStableEvent(() => historyStartPagination.reveal());
|
||||
const reportInitialHistoryVisibility = useStableEvent((visible: boolean) => {
|
||||
onInitialHistoryVisibilityChange?.(visible);
|
||||
});
|
||||
useLayoutEffect(() => {
|
||||
reportInitialHistoryVisibility(historyStartPaginationState.visible);
|
||||
}, [historyStartPaginationState.visible, reportInitialHistoryVisibility]);
|
||||
const retryHistoryStart = useStableEvent(() => historyStartPagination.rearm());
|
||||
const scheduleHistoryStartSettle = useStableEvent(() => {
|
||||
let scheduler = historyStartSettleSchedulerRef.current;
|
||||
@@ -811,11 +808,6 @@ function NativeStreamViewport(props: StreamRenderInput & { strategy: StreamStrat
|
||||
{canExpandDrawDistance ? (
|
||||
<InitialDrawDistanceExpansion schedule={drawDistanceExpansion.schedule} />
|
||||
) : null}
|
||||
{!historyStartPaginationState.visible ? (
|
||||
<View pointerEvents="none" style={initialFillStyle}>
|
||||
<LoadingState testID="agent-initial-fill" title={t("agentPanel.states.loadingHistory")} />
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -44,9 +44,42 @@ function thoughtRow(index: number, height = ROW_HEIGHT): Extract<StreamItem, { k
|
||||
};
|
||||
}
|
||||
|
||||
function pluginRow(
|
||||
index: number,
|
||||
height: number | null = ROW_HEIGHT,
|
||||
idPrefix = "plugin",
|
||||
): Extract<StreamItem, { kind: "plugin" }> {
|
||||
return {
|
||||
kind: "plugin",
|
||||
id: `${idPrefix}-${index}`,
|
||||
timestamp: new Date(`2026-04-20T00:00:${String(index % 60).padStart(2, "0")}.000Z`),
|
||||
pluginId: "test-plugin",
|
||||
pluginItemId: `${idPrefix}-${index}`,
|
||||
itemKind: height === null ? "empty" : "compact",
|
||||
version: 1,
|
||||
data: { height },
|
||||
};
|
||||
}
|
||||
|
||||
const rowStyleByHeight = new Map<number, { height: number }>();
|
||||
|
||||
function renderRow(item: StreamItem) {
|
||||
if (item.kind === "plugin") {
|
||||
const pluginHeight =
|
||||
item.data && typeof item.data === "object" && !Array.isArray(item.data)
|
||||
? (item.data as { height?: number | null }).height
|
||||
: ROW_HEIGHT;
|
||||
if (pluginHeight === null) {
|
||||
return null;
|
||||
}
|
||||
const resolvedHeight = typeof pluginHeight === "number" ? pluginHeight : ROW_HEIGHT;
|
||||
let style = rowStyleByHeight.get(resolvedHeight);
|
||||
if (!style) {
|
||||
style = { height: resolvedHeight };
|
||||
rowStyleByHeight.set(resolvedHeight, style);
|
||||
}
|
||||
return <div style={style}>{item.id}</div>;
|
||||
}
|
||||
const height =
|
||||
item.kind === "user_message" || item.kind === "assistant_message" || item.kind === "thought"
|
||||
? Number(item.text)
|
||||
@@ -61,6 +94,14 @@ function renderRow(item: StreamItem) {
|
||||
|
||||
let root: Root;
|
||||
let host: HTMLDivElement;
|
||||
const injectedStyles: HTMLStyleElement[] = [];
|
||||
|
||||
function injectTestStyle(cssText: string) {
|
||||
const style = document.createElement("style");
|
||||
style.textContent = cssText;
|
||||
document.head.appendChild(style);
|
||||
injectedStyles.push(style);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
host = document.createElement("div");
|
||||
@@ -72,6 +113,9 @@ beforeEach(() => {
|
||||
afterEach(() => {
|
||||
act(() => root.unmount());
|
||||
host.remove();
|
||||
for (const style of injectedStyles.splice(0)) {
|
||||
style.remove();
|
||||
}
|
||||
});
|
||||
|
||||
type OlderHistoryInput = Pick<
|
||||
@@ -83,7 +127,10 @@ interface MountTimelineOptions {
|
||||
olderHistory?: OlderHistoryInput;
|
||||
isMobileBreakpoint?: boolean;
|
||||
historyVirtualized?: StreamItem[];
|
||||
liveHead?: StreamItem[];
|
||||
viewportHeight?: number;
|
||||
hostMarginTop?: number;
|
||||
onReadingPositionChange?: StreamRenderInput["onReadingPositionChange"];
|
||||
}
|
||||
|
||||
function mountTimeline(
|
||||
@@ -92,19 +139,23 @@ function mountTimeline(
|
||||
olderHistory,
|
||||
isMobileBreakpoint = true,
|
||||
historyVirtualized = [],
|
||||
liveHead = [],
|
||||
viewportHeight = VIEWPORT_HEIGHT,
|
||||
hostMarginTop = 0,
|
||||
onReadingPositionChange,
|
||||
}: MountTimelineOptions = {},
|
||||
) {
|
||||
host.style.height = `${viewportHeight}px`;
|
||||
host.style.marginTop = hostMarginTop > 0 ? `${hostMarginTop}px` : "";
|
||||
const strategy = createWebStreamStrategy({ isMobileBreakpoint });
|
||||
const viewportRef = React.createRef<StreamViewportHandle>();
|
||||
let currentInput: StreamRenderInput = {
|
||||
agentId: "agent",
|
||||
segments: { historyVirtualized, historyMounted, liveHead: [] },
|
||||
segments: { historyVirtualized, historyMounted, liveHead },
|
||||
boundary: {
|
||||
hasVirtualizedHistory: historyVirtualized.length > 0,
|
||||
hasMountedHistory: historyMounted.length > 0,
|
||||
hasLiveHead: false,
|
||||
hasLiveHead: liveHead.length > 0,
|
||||
},
|
||||
renderers: {
|
||||
renderHistoryVirtualizedRow: renderRow,
|
||||
@@ -117,6 +168,7 @@ function mountTimeline(
|
||||
routeBottomAnchorRequest: null,
|
||||
isAuthoritativeHistoryReady: true,
|
||||
onNearBottomChange: () => {},
|
||||
onReadingPositionChange,
|
||||
onNearHistoryStart: async () => true,
|
||||
isLoadingOlderHistory: false,
|
||||
hasOlderHistory: false,
|
||||
@@ -509,4 +561,345 @@ describe("web virtualizer reconcile stability", () => {
|
||||
expect(timeline.rowTop("message-99")).toBe(1008);
|
||||
expect(timeline.rowTop("thought-0")).toBe(48);
|
||||
});
|
||||
|
||||
it("scrolls smoothly up across mixed compact, 0px, and display:none plugin rows without anchor jumps", async () => {
|
||||
injectTestStyle(`[data-history-row-id^="hidden-plugin-"] { display: none !important; }`);
|
||||
const virtualized = Array.from({ length: 120 }, (_, index) => {
|
||||
if (index % 3 === 0) return pluginRow(index, 24, "hidden-plugin");
|
||||
if (index % 3 === 1) return pluginRow(index, null, "empty-plugin");
|
||||
return pluginRow(index, 24, "plugin");
|
||||
});
|
||||
const mounted = Array.from({ length: 10 }, (_, index) => row(120 + index, 40));
|
||||
const reportedReadingIds: (string | null)[] = [];
|
||||
const timeline = mountTimeline(mounted, {
|
||||
historyVirtualized: virtualized,
|
||||
viewportHeight: 320,
|
||||
hostMarginTop: 60,
|
||||
onReadingPositionChange: (rowId) => {
|
||||
reportedReadingIds.push(rowId);
|
||||
},
|
||||
});
|
||||
await timeline.settle(8);
|
||||
expect(timeline.distanceFromEnd()).toBeLessThanOrEqual(1);
|
||||
|
||||
const scrollContainer = host.querySelector<HTMLElement>('[data-testid="agent-chat-scroll"]')!;
|
||||
expect(scrollContainer.getBoundingClientRect().top).toBeGreaterThanOrEqual(60);
|
||||
|
||||
const findVisibleRowNearTop = () => {
|
||||
const containerTop = scrollContainer.getBoundingClientRect().top;
|
||||
for (const element of host.querySelectorAll<HTMLElement>("[data-history-row-id]")) {
|
||||
const bounds = element.getBoundingClientRect();
|
||||
if (bounds.height <= 0) continue;
|
||||
const relativeTop = bounds.top - containerTop;
|
||||
if (relativeTop >= 0 && relativeTop < 160) {
|
||||
return { id: element.dataset.historyRowId!, top: relativeTop };
|
||||
}
|
||||
}
|
||||
throw new Error("Expected a visible non-empty row near the top of the viewport");
|
||||
};
|
||||
|
||||
const stepPx = 120;
|
||||
for (let step = 0; step < 6; step += 1) {
|
||||
const anchor = findVisibleRowNearTop();
|
||||
timeline.scrollUp(stepPx);
|
||||
await timeline.settle(8);
|
||||
expect(timeline.rowTop(anchor.id)).toBe(anchor.top + stepPx);
|
||||
}
|
||||
|
||||
expect(reportedReadingIds.some((id) => id?.startsWith("hidden-plugin-"))).toBe(false);
|
||||
expect(reportedReadingIds.at(-1)).toMatch(/^(plugin|message)-/);
|
||||
});
|
||||
|
||||
it("preserves mounted anchor projection when display:none plugin rows lead or precede the anchor", async () => {
|
||||
injectTestStyle(`[data-history-row-id^="hidden-plugin-"] { display: none !important; }`);
|
||||
const mounted: StreamItem[] = [
|
||||
pluginRow(200, 24, "hidden-plugin"),
|
||||
row(100, 40),
|
||||
pluginRow(201, 24, "hidden-plugin"),
|
||||
pluginRow(202, null, "empty-plugin"),
|
||||
...Array.from({ length: 8 }, (_, index) => row(101 + index, 40)),
|
||||
];
|
||||
const reportedReadingIds: (string | null)[] = [];
|
||||
const timeline = mountTimeline(mounted, {
|
||||
viewportHeight: 200,
|
||||
hostMarginTop: 60,
|
||||
onReadingPositionChange: (rowId) => {
|
||||
reportedReadingIds.push(rowId);
|
||||
},
|
||||
});
|
||||
await timeline.settle();
|
||||
timeline.scrollUp(120);
|
||||
await timeline.settle();
|
||||
|
||||
const readingTop = timeline.rowTop("message-101");
|
||||
|
||||
const firstVirtualizedBatch = Array.from({ length: 60 }, (_, index) => {
|
||||
if (index === 59) return pluginRow(index, 24, "plugin");
|
||||
if (index % 3 === 0) return pluginRow(index, 24, "hidden-plugin");
|
||||
if (index % 3 === 1) return pluginRow(index, null, "empty-plugin");
|
||||
return pluginRow(index, 24, "plugin");
|
||||
});
|
||||
timeline.render({
|
||||
historyVirtualized: firstVirtualizedBatch,
|
||||
historyMounted: mounted,
|
||||
});
|
||||
await timeline.settle(8);
|
||||
|
||||
expect(timeline.rowTop("message-101")).toBe(readingTop);
|
||||
expect(timeline.rowBottom("plugin-59")).toBe(timeline.rowTop("message-100"));
|
||||
|
||||
const olderVirtualizedBatch = Array.from({ length: 40 }, (_, index) =>
|
||||
index % 2 === 0
|
||||
? pluginRow(1000 + index, 24, "hidden-plugin")
|
||||
: pluginRow(1000 + index, 24, "plugin"),
|
||||
);
|
||||
timeline.render({
|
||||
historyVirtualized: [...olderVirtualizedBatch, ...firstVirtualizedBatch],
|
||||
historyMounted: mounted,
|
||||
});
|
||||
await timeline.settle(8);
|
||||
|
||||
expect(timeline.rowTop("message-101")).toBe(readingTop);
|
||||
expect(timeline.rowBottom("plugin-59")).toBe(timeline.rowTop("message-100"));
|
||||
expect(reportedReadingIds.some((id) => id?.startsWith("hidden-plugin-"))).toBe(false);
|
||||
});
|
||||
|
||||
it.each(["historyMounted", "liveHead", "historyVirtualized"] as const)(
|
||||
"hands anchor ownership to the next visible row when the anchored %s plugin row becomes display:none",
|
||||
async (lane) => {
|
||||
const items: StreamItem[] = [
|
||||
...Array.from({ length: 10 }, (_, index) => row(index, 40)),
|
||||
pluginRow(10, 40, "dynamic-anchor"),
|
||||
...Array.from({ length: 9 }, (_, index) => row(11 + index, 40)),
|
||||
];
|
||||
const splitSegments = (source: StreamItem[]) => {
|
||||
if (lane === "liveHead") {
|
||||
return {
|
||||
historyVirtualized: [],
|
||||
historyMounted: source.slice(0, 8),
|
||||
liveHead: source.slice(8),
|
||||
};
|
||||
}
|
||||
if (lane === "historyVirtualized") {
|
||||
return {
|
||||
historyVirtualized: source.slice(0, 16),
|
||||
historyMounted: source.slice(16),
|
||||
liveHead: [],
|
||||
};
|
||||
}
|
||||
return {
|
||||
historyVirtualized: [],
|
||||
historyMounted: source,
|
||||
liveHead: [],
|
||||
};
|
||||
};
|
||||
|
||||
const initial = splitSegments(items);
|
||||
const reportedReadingIds: (string | null)[] = [];
|
||||
const timeline = mountTimeline(initial.historyMounted, {
|
||||
historyVirtualized: initial.historyVirtualized,
|
||||
liveHead: initial.liveHead,
|
||||
viewportHeight: 200,
|
||||
onReadingPositionChange: (rowId) => {
|
||||
reportedReadingIds.push(rowId);
|
||||
},
|
||||
});
|
||||
await timeline.settle(8);
|
||||
timeline.scrollUp(216);
|
||||
await timeline.settle(8);
|
||||
|
||||
expect(reportedReadingIds.at(-1)).toBe("dynamic-anchor-10");
|
||||
const scrollTopBeforeHide = timeline.scrollTop();
|
||||
|
||||
injectTestStyle(`[data-history-row-id="dynamic-anchor-10"] { display: none !important; }`);
|
||||
await timeline.settle(8);
|
||||
|
||||
expect(reportedReadingIds.at(-1)).toBe("message-11");
|
||||
expect(timeline.scrollTop()).toBe(scrollTopBeforeHide);
|
||||
const nextVisibleTop = timeline.rowTop("message-11");
|
||||
|
||||
const grownItems = items.map((item, index) => (index === 8 ? row(8, 120) : item));
|
||||
timeline.render(splitSegments(grownItems));
|
||||
await timeline.settle(8);
|
||||
|
||||
expect(timeline.rowTop("message-11")).toBe(nextVisibleTop);
|
||||
expect(reportedReadingIds.at(-1)).toBe("message-11");
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["historyMounted", "liveHead", "historyVirtualized"] as const)(
|
||||
"compensates upper-row growth in the same commit when the anchored %s plugin row becomes display:none",
|
||||
async (lane) => {
|
||||
const items: StreamItem[] = [
|
||||
...Array.from({ length: 10 }, (_, index) => row(index, 40)),
|
||||
pluginRow(10, 40, "same-commit-anchor"),
|
||||
...Array.from({ length: 9 }, (_, index) => row(11 + index, 40)),
|
||||
];
|
||||
const splitSegments = (source: StreamItem[]) => {
|
||||
if (lane === "liveHead") {
|
||||
return {
|
||||
historyVirtualized: [],
|
||||
historyMounted: source.slice(0, 8),
|
||||
liveHead: source.slice(8),
|
||||
};
|
||||
}
|
||||
if (lane === "historyVirtualized") {
|
||||
return {
|
||||
historyVirtualized: source.slice(0, 16),
|
||||
historyMounted: source.slice(16),
|
||||
liveHead: [],
|
||||
};
|
||||
}
|
||||
return {
|
||||
historyVirtualized: [],
|
||||
historyMounted: source,
|
||||
liveHead: [],
|
||||
};
|
||||
};
|
||||
|
||||
const initial = splitSegments(items);
|
||||
const reportedReadingIds: (string | null)[] = [];
|
||||
const timeline = mountTimeline(initial.historyMounted, {
|
||||
historyVirtualized: initial.historyVirtualized,
|
||||
liveHead: initial.liveHead,
|
||||
viewportHeight: 200,
|
||||
onReadingPositionChange: (rowId) => {
|
||||
reportedReadingIds.push(rowId);
|
||||
},
|
||||
});
|
||||
await timeline.settle(8);
|
||||
timeline.scrollUp(216);
|
||||
await timeline.settle(8);
|
||||
|
||||
expect(reportedReadingIds.at(-1)).toBe("same-commit-anchor-10");
|
||||
expect(timeline.rowTop("same-commit-anchor-10")).toBe(0);
|
||||
|
||||
// Hide the current anchor and grow an upper row by 80px in the same layout commit.
|
||||
const grownItems = items.map((item, index) => (index === 8 ? row(8, 120) : item));
|
||||
injectTestStyle(
|
||||
`[data-history-row-id="same-commit-anchor-10"] { display: none !important; }`,
|
||||
);
|
||||
timeline.render(splitSegments(grownItems));
|
||||
await timeline.settle(8);
|
||||
|
||||
expect(timeline.rowTop("message-11")).toBe(0);
|
||||
expect(reportedReadingIds.at(-1)).toBe("message-11");
|
||||
},
|
||||
);
|
||||
|
||||
it("keeps the next visible virtualized row mounted and anchored when a hidden virtual anchor shifts past the viewport window", async () => {
|
||||
const virtualized: StreamItem[] = [
|
||||
...Array.from({ length: 100 }, (_, index) => thoughtRow(index, 40)),
|
||||
pluginRow(100, 40, "cross-window-anchor"),
|
||||
row(101, 40),
|
||||
...Array.from({ length: 38 }, (_, index) => thoughtRow(102 + index, 40)),
|
||||
];
|
||||
const mounted = Array.from({ length: 10 }, (_, index) => row(140 + index, 40));
|
||||
const reportedReadingIds: (string | null)[] = [];
|
||||
const timeline = mountTimeline(mounted, {
|
||||
historyVirtualized: virtualized,
|
||||
viewportHeight: 200,
|
||||
onReadingPositionChange: (rowId) => {
|
||||
reportedReadingIds.push(rowId);
|
||||
},
|
||||
});
|
||||
await timeline.settle(8);
|
||||
timeline.scrollUp(1776);
|
||||
await timeline.settle(8);
|
||||
timeline.scrollUp(40);
|
||||
await timeline.settle(8);
|
||||
|
||||
expect(reportedReadingIds.at(-1)).toBe("cross-window-anchor-100");
|
||||
expect(timeline.rowTop("cross-window-anchor-100")).toBe(0);
|
||||
|
||||
// Hide the anchored virtual row and grow an upper row by +600px (> viewport + overscan) in one commit.
|
||||
const grownVirtualized = virtualized.map((item, index) =>
|
||||
index === 92 ? thoughtRow(92, 640) : item,
|
||||
);
|
||||
injectTestStyle(
|
||||
`[data-history-row-id="cross-window-anchor-100"] { display: none !important; }`,
|
||||
);
|
||||
timeline.render({
|
||||
historyVirtualized: grownVirtualized,
|
||||
historyMounted: mounted,
|
||||
});
|
||||
await timeline.settle(8);
|
||||
|
||||
expect(host.querySelector('[data-history-row-id="message-101"]')).not.toBeNull();
|
||||
expect(timeline.rowTop("message-101")).toBe(0);
|
||||
expect(reportedReadingIds.at(-1)).toBe("message-101");
|
||||
});
|
||||
|
||||
it("clears cached positive height when a measured mounted plugin row becomes display:none before virtualization", async () => {
|
||||
const tallPlugin = pluginRow(0, 800, "tall-plugin");
|
||||
const trailingRows = Array.from({ length: 50 }, (_, index) => row(index + 1, 40));
|
||||
const timeline = mountTimeline([tallPlugin, ...trailingRows], {
|
||||
viewportHeight: 200,
|
||||
});
|
||||
await timeline.settle(8);
|
||||
|
||||
const scrollContainer = host.querySelector<HTMLElement>('[data-testid="agent-chat-scroll"]')!;
|
||||
expect(scrollContainer.scrollHeight).toBe(48 + 800 + 50 * 40 + 16);
|
||||
|
||||
injectTestStyle(`[data-history-row-id="tall-plugin-0"] { display: none !important; }`);
|
||||
await timeline.settle(8);
|
||||
|
||||
timeline.render({
|
||||
historyVirtualized: [tallPlugin, ...trailingRows.slice(0, 44)],
|
||||
historyMounted: trailingRows.slice(44),
|
||||
});
|
||||
await timeline.settle(8);
|
||||
|
||||
expect(host.querySelector('[data-history-row-id="tall-plugin-0"]')).toBeNull();
|
||||
expect(scrollContainer.scrollHeight).toBe(48 + 50 * 40 + 16);
|
||||
});
|
||||
|
||||
it("ignores layout and reading reports while an active viewport is hidden by an ancestor display:none", async () => {
|
||||
const mounted = Array.from({ length: 30 }, (_, index) => row(index, 40));
|
||||
const reportedReadingIds: (string | null)[] = [];
|
||||
const timeline = mountTimeline(mounted, {
|
||||
viewportHeight: 200,
|
||||
onReadingPositionChange: (rowId) => {
|
||||
reportedReadingIds.push(rowId);
|
||||
},
|
||||
});
|
||||
await timeline.settle(8);
|
||||
timeline.scrollUp(616);
|
||||
await timeline.settle(8);
|
||||
|
||||
expect(reportedReadingIds.at(-1)).toBe("message-10");
|
||||
const readingTopBeforeHide = timeline.rowTop("message-10");
|
||||
const scrollTopBeforeHide = timeline.scrollTop();
|
||||
reportedReadingIds.length = 0;
|
||||
|
||||
host.style.display = "none";
|
||||
await timeline.settle(4);
|
||||
timeline.render({ historyMounted: [...mounted] });
|
||||
await timeline.settle(4);
|
||||
|
||||
expect(reportedReadingIds).toEqual([]);
|
||||
|
||||
host.style.display = "flex";
|
||||
await timeline.settle(8);
|
||||
|
||||
expect(reportedReadingIds.at(-1)).toBe("message-10");
|
||||
expect(timeline.scrollTop()).toBe(scrollTopBeforeHide);
|
||||
expect(timeline.rowTop("message-10")).toBe(readingTopBeforeHide);
|
||||
|
||||
const grown = mounted.map((item, index) => (index === 5 ? row(5, 120) : item));
|
||||
timeline.render({ historyMounted: grown });
|
||||
await timeline.settle(8);
|
||||
|
||||
expect(timeline.rowTop("message-10")).toBe(readingTopBeforeHide);
|
||||
|
||||
// Jumping back to top right after becoming visible must not snap back to the pre-hide offset.
|
||||
host.style.display = "none";
|
||||
await timeline.settle(4);
|
||||
host.style.display = "flex";
|
||||
timeline.scrollTo(0);
|
||||
timeline.render({ historyMounted: [...grown] });
|
||||
await timeline.settle(4);
|
||||
|
||||
expect(timeline.scrollTop()).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -572,38 +572,61 @@ describe("createWebStreamStrategy", () => {
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
|
||||
const renderInput: StreamRenderInput = {
|
||||
agentId: "agent",
|
||||
segments: {
|
||||
historyVirtualized: [],
|
||||
historyMounted: [userMessage(1)],
|
||||
liveHead: [userMessage(2)],
|
||||
},
|
||||
boundary: {
|
||||
hasVirtualizedHistory: false,
|
||||
hasMountedHistory: true,
|
||||
hasLiveHead: true,
|
||||
},
|
||||
renderers: createRenderers(vi.fn()),
|
||||
listEmptyComponent: null,
|
||||
viewportRef,
|
||||
routeBottomAnchorRequest: null,
|
||||
isAuthoritativeHistoryReady: true,
|
||||
onNearBottomChange: vi.fn(),
|
||||
onReadingPositionChange,
|
||||
onNearHistoryStart: vi.fn().mockReturnValue(true),
|
||||
isLoadingOlderHistory: false,
|
||||
hasOlderHistory: false,
|
||||
olderHistoryProgressKey: null,
|
||||
scrollEnabled: true,
|
||||
listStyle: null,
|
||||
baseListContentContainerStyle: null,
|
||||
forwardListContentContainerStyle: null,
|
||||
contentMaxWidth: DEFAULT_CONTENT_MAX_WIDTH,
|
||||
};
|
||||
|
||||
act(() => {
|
||||
root?.render(
|
||||
strategy.render({
|
||||
agentId: "agent",
|
||||
segments: {
|
||||
historyVirtualized: [],
|
||||
historyMounted: [userMessage(1)],
|
||||
liveHead: [userMessage(2)],
|
||||
},
|
||||
boundary: {
|
||||
hasVirtualizedHistory: false,
|
||||
hasMountedHistory: true,
|
||||
hasLiveHead: true,
|
||||
},
|
||||
renderers: createRenderers(vi.fn()),
|
||||
listEmptyComponent: null,
|
||||
viewportRef,
|
||||
routeBottomAnchorRequest: null,
|
||||
isAuthoritativeHistoryReady: true,
|
||||
onNearBottomChange: vi.fn(),
|
||||
onReadingPositionChange,
|
||||
onNearHistoryStart: vi.fn().mockReturnValue(true),
|
||||
isLoadingOlderHistory: false,
|
||||
hasOlderHistory: false,
|
||||
olderHistoryProgressKey: null,
|
||||
scrollEnabled: true,
|
||||
listStyle: null,
|
||||
baseListContentContainerStyle: null,
|
||||
forwardListContentContainerStyle: null,
|
||||
contentMaxWidth: DEFAULT_CONTENT_MAX_WIDTH,
|
||||
}),
|
||||
);
|
||||
root?.render(strategy.render(renderInput));
|
||||
});
|
||||
|
||||
const scrollContainer = container.querySelector('[data-testid="agent-chat-scroll"]');
|
||||
const firstRow = container.querySelector('[data-history-row-id="message-1"]');
|
||||
const secondRow = container.querySelector('[data-history-row-id="message-2"]');
|
||||
if (
|
||||
!(scrollContainer instanceof HTMLElement) ||
|
||||
!(firstRow instanceof HTMLElement) ||
|
||||
!(secondRow instanceof HTMLElement)
|
||||
) {
|
||||
throw new Error("Expected scroll container and rendered history rows");
|
||||
}
|
||||
scrollContainer.getBoundingClientRect = () => ({ top: 0, height: 500, bottom: 500 }) as DOMRect;
|
||||
firstRow.getBoundingClientRect = () => ({ top: -40, height: 40, bottom: 0 }) as DOMRect;
|
||||
secondRow.getBoundingClientRect = () => ({ top: 0, height: 40, bottom: 40 }) as DOMRect;
|
||||
Object.defineProperty(scrollContainer, "clientHeight", { configurable: true, value: 500 });
|
||||
Object.defineProperty(scrollContainer, "scrollHeight", { configurable: true, value: 1000 });
|
||||
|
||||
act(() => {
|
||||
root?.render(strategy.render({ ...renderInput, segments: { ...renderInput.segments } }));
|
||||
});
|
||||
act(() => {
|
||||
scrollContainer.dispatchEvent(new Event("scroll"));
|
||||
});
|
||||
|
||||
expect(onReadingPositionChange).toHaveBeenLastCalledWith("message-2");
|
||||
|
||||
@@ -19,7 +19,6 @@ import { flushSync } from "react-dom";
|
||||
import { withUnistyles } from "react-native-unistyles";
|
||||
import { useRetainedPanelActive } from "@/components/retained-panel";
|
||||
import { LoadingSpinner } from "@/components/ui/loading-spinner";
|
||||
import { LoadingState } from "@/components/ui/loading-state";
|
||||
import { useStableEvent } from "@/hooks/use-stable-event";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { getStreamItemMessageId, type StreamItem } from "@/types/stream";
|
||||
@@ -77,14 +76,6 @@ const historyStartSlotStyle: CSSProperties = {
|
||||
};
|
||||
|
||||
const streamRowsHostStyle: CSSProperties = { position: "relative", width: "100%" };
|
||||
const initialFillStyle: CSSProperties = {
|
||||
position: "absolute",
|
||||
inset: 0,
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
pointerEvents: "none",
|
||||
};
|
||||
|
||||
// Rows and the live auxiliary (turn footer, pending permissions) center their content with
|
||||
// `alignSelf`, which only applies inside a flex container.
|
||||
@@ -121,6 +112,14 @@ function isScrollContainerMeasurable(
|
||||
return scrollContainer.clientHeight > 0 && scrollContainer.scrollHeight > 0;
|
||||
}
|
||||
|
||||
function hasLayoutBox(element: HTMLElement, bounds?: DOMRect): boolean {
|
||||
if (element.getClientRects().length > 0) {
|
||||
return true;
|
||||
}
|
||||
const rect = bounds ?? element.getBoundingClientRect();
|
||||
return rect.width > 0 || rect.height > 0;
|
||||
}
|
||||
|
||||
function getUnclampedScrollTop(
|
||||
scrollContainer: Pick<HTMLElement, "scrollTop" | "clientHeight" | "scrollHeight">,
|
||||
lastKnownScrollTop: number,
|
||||
@@ -431,6 +430,7 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
|
||||
isAuthoritativeHistoryReady,
|
||||
isInitialHistoryLoading,
|
||||
revealInitialHistory,
|
||||
onInitialHistoryVisibilityChange,
|
||||
onNearBottomChange,
|
||||
onReadingPositionChange,
|
||||
onNearHistoryStart,
|
||||
@@ -699,6 +699,12 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
|
||||
() => historyStartPagination.state.status === "settling",
|
||||
);
|
||||
const finishInitialFill = useStableEvent(() => historyStartPagination.reveal());
|
||||
const reportInitialHistoryVisibility = useStableEvent((visible: boolean) => {
|
||||
onInitialHistoryVisibilityChange?.(visible);
|
||||
});
|
||||
useLayoutEffect(() => {
|
||||
reportInitialHistoryVisibility(historyStartPaginationState.visible);
|
||||
}, [historyStartPaginationState.visible, reportInitialHistoryVisibility]);
|
||||
const rearmHistoryStartFromUserIntent = useStableEvent(() => historyStartPagination.rearm());
|
||||
const scheduleHistoryStartPrependSettle = useStableEvent(() => {
|
||||
let scheduler = historyStartSettleSchedulerRef.current;
|
||||
@@ -720,6 +726,13 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
|
||||
});
|
||||
|
||||
const measureVirtualizedRows = useStableEvent(() => {
|
||||
const container = scrollContainerRef.current;
|
||||
if (
|
||||
!container ||
|
||||
(!hasLayoutBox(container) && container.offsetWidth === 0 && container.offsetHeight === 0)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
let resized = false;
|
||||
for (const element of contentRef.current?.querySelectorAll<HTMLElement>(
|
||||
"[data-history-row-id][data-index]",
|
||||
@@ -896,6 +909,9 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
|
||||
onReadingPositionChange(null);
|
||||
return;
|
||||
}
|
||||
if (!hasLayoutBox(scrollContainer)) {
|
||||
return;
|
||||
}
|
||||
onReadingPositionChange(readingAnchor.getReadingRowId(scrollContainer.scrollTop));
|
||||
});
|
||||
|
||||
@@ -928,7 +944,11 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
|
||||
const container = scrollContainerRef.current;
|
||||
const content = contentRef.current;
|
||||
if (!container || !content) return null;
|
||||
const viewportTop = container.getBoundingClientRect().top;
|
||||
const containerBounds = container.getBoundingClientRect();
|
||||
if (!hasLayoutBox(container, containerBounds)) {
|
||||
return null;
|
||||
}
|
||||
const viewportTop = containerBounds.top;
|
||||
const scrollTop = container.scrollTop;
|
||||
const width = readContentWidth() ?? 0;
|
||||
const virtualSpacerHeight = virtualSpacerRef.current?.getBoundingClientRect().height ?? 0;
|
||||
@@ -939,29 +959,36 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
|
||||
mountedOffsets.clear();
|
||||
let firstRowId: string | null = null;
|
||||
let mountedIndex = 0;
|
||||
const rows = Array.from(
|
||||
content.querySelectorAll<HTMLElement>("[data-history-row-id]"),
|
||||
(element) => {
|
||||
const bounds = element.getBoundingClientRect();
|
||||
const id = element.dataset.historyRowId!;
|
||||
const top = bounds.top - viewportTop + scrollTop;
|
||||
measuredRowHeights.current.set(id, { width, height: bounds.height });
|
||||
if (!element.hasAttribute("data-index")) {
|
||||
if (shouldTrackMountedOffsets) {
|
||||
if (firstRowId === null) {
|
||||
firstRowId = id;
|
||||
}
|
||||
mountedOffsets.set(id, {
|
||||
topWithoutVirtual: top - virtualSpacerHeight,
|
||||
height: bounds.height,
|
||||
mountedIndex,
|
||||
});
|
||||
}
|
||||
mountedIndex += 1;
|
||||
const rows: { id: string; top: number; height: number }[] = [];
|
||||
const hiddenIds = new Set<string>();
|
||||
for (const element of content.querySelectorAll<HTMLElement>("[data-history-row-id]")) {
|
||||
const id = element.dataset.historyRowId!;
|
||||
const isMountedRow = !element.hasAttribute("data-index");
|
||||
const rowMountedIndex = mountedIndex;
|
||||
if (isMountedRow) {
|
||||
if (shouldTrackMountedOffsets && firstRowId === null) {
|
||||
firstRowId = id;
|
||||
}
|
||||
return { id, top, height: bounds.height };
|
||||
},
|
||||
);
|
||||
mountedIndex += 1;
|
||||
}
|
||||
const bounds = element.getBoundingClientRect();
|
||||
if (!hasLayoutBox(element, bounds)) {
|
||||
hiddenIds.add(id);
|
||||
// Clear any stale positive cached height so unmounted virtualized estimates do not retain it.
|
||||
measuredRowHeights.current.set(id, { width, height: 0 });
|
||||
continue;
|
||||
}
|
||||
const top = bounds.top - viewportTop + scrollTop;
|
||||
measuredRowHeights.current.set(id, { width, height: bounds.height });
|
||||
if (isMountedRow && shouldTrackMountedOffsets) {
|
||||
mountedOffsets.set(id, {
|
||||
topWithoutVirtual: top - virtualSpacerHeight,
|
||||
height: bounds.height,
|
||||
mountedIndex: rowMountedIndex,
|
||||
});
|
||||
}
|
||||
rows.push({ id, top, height: bounds.height });
|
||||
}
|
||||
mountedRowSnapshotRef.current.firstRowId = firstRowId;
|
||||
committedLayoutMetricsRef.current = {
|
||||
hasCommittedFlowHeight: true,
|
||||
@@ -973,7 +1000,7 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
|
||||
CONTENT_PADDING_BOTTOM_PX,
|
||||
nonVirtualRowCount: mountedIndex,
|
||||
};
|
||||
return rows;
|
||||
return { rows, hiddenIds: hiddenIds as ReadonlySet<string> };
|
||||
});
|
||||
|
||||
const scheduleDeferredLayoutPass = useStableEvent(() => {
|
||||
@@ -1017,8 +1044,9 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
|
||||
const reconcileReadingPosition = useStableEvent(() => {
|
||||
const container = scrollContainerRef.current;
|
||||
if (!isActiveRef.current || !container) return;
|
||||
const rows = measureRows();
|
||||
if (!rows) return;
|
||||
const measured = measureRows();
|
||||
if (!measured) return;
|
||||
const { rows, hiddenIds } = measured;
|
||||
const shouldAnchor = !followOutputRef.current && !isJumpSettling();
|
||||
if (!shouldAnchor) readingAnchor.reset();
|
||||
const anchorScrollTop = shouldAnchor
|
||||
@@ -1029,6 +1057,7 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
|
||||
rows,
|
||||
false,
|
||||
props.readingRowReplacements,
|
||||
hiddenIds,
|
||||
);
|
||||
if (!shouldAnchor) {
|
||||
readingAnchor.reset();
|
||||
@@ -1514,7 +1543,7 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
|
||||
holdRow: (rowId, apply, triggerEdge) => {
|
||||
cancelPendingStickToBottom();
|
||||
setFollowOutput(false);
|
||||
const row = measureRows()?.find((candidate) => candidate.id === rowId);
|
||||
const row = measureRows()?.rows.find((candidate) => candidate.id === rowId);
|
||||
const scrollTop = scrollContainerRef.current?.scrollTop;
|
||||
if (scrollTop !== undefined) {
|
||||
lastClampedBaselineScrollTopRef.current = scrollTop;
|
||||
@@ -1719,11 +1748,6 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
|
||||
{shouldRenderEmpty ? listEmptyComponent : null}
|
||||
</div>
|
||||
</div>
|
||||
{!historyStartPaginationState.visible ? (
|
||||
<div style={initialFillStyle}>
|
||||
<LoadingState testID="agent-initial-fill" title={t("agentPanel.states.loadingHistory")} />
|
||||
</div>
|
||||
) : null}
|
||||
{scrollEnabled && !isMobileBreakpoint ? (
|
||||
<DomOverlayScrollbar
|
||||
scrollContainerRef={scrollContainerRef}
|
||||
|
||||
@@ -94,6 +94,8 @@ export interface StreamRenderInput {
|
||||
isAuthoritativeHistoryReady: boolean;
|
||||
isInitialHistoryLoading?: boolean;
|
||||
revealInitialHistory?: boolean;
|
||||
/** When supplied, the host pane owns the full-pane initial-fill loading overlay. */
|
||||
onInitialHistoryVisibilityChange?: (visible: boolean) => void;
|
||||
onNearBottomChange: (value: boolean) => void;
|
||||
// The history row under the top of the viewport, for surfaces that mark where the reader
|
||||
// is in the transcript. Only the web viewport measures it today.
|
||||
|
||||
@@ -258,6 +258,8 @@ export interface AgentStreamViewProps {
|
||||
isAuthoritativeHistoryReady?: boolean;
|
||||
isInitialHistoryLoading?: boolean;
|
||||
revealInitialHistory?: boolean;
|
||||
/** When supplied, the host pane owns the full-pane initial-fill loading overlay. */
|
||||
onInitialHistoryVisibilityChange?: (visible: boolean) => void;
|
||||
/** Tail space required by a transparent overlay rendered at the bottom edge. */
|
||||
bottomOverlayTailClearance?: number;
|
||||
/** Bottom offset required for controls floating above that overlay. */
|
||||
@@ -357,6 +359,7 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
|
||||
isAuthoritativeHistoryReady = true,
|
||||
isInitialHistoryLoading,
|
||||
revealInitialHistory,
|
||||
onInitialHistoryVisibilityChange,
|
||||
bottomOverlayTailClearance = 0,
|
||||
bottomOverlayControlClearance,
|
||||
toast,
|
||||
@@ -1231,6 +1234,7 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
|
||||
isAuthoritativeHistoryReady,
|
||||
isInitialHistoryLoading,
|
||||
revealInitialHistory,
|
||||
onInitialHistoryVisibilityChange,
|
||||
onNearBottomChange: nearBottom.set,
|
||||
onReadingPositionChange: handleReadingPositionChange,
|
||||
onNearHistoryStart: loadOlder,
|
||||
@@ -1384,6 +1388,9 @@ function agentStreamViewPropsEqual(
|
||||
if (left.revealInitialHistory !== right.revealInitialHistory) {
|
||||
reasons.push("revealInitialHistory");
|
||||
}
|
||||
if (left.onInitialHistoryVisibilityChange !== right.onInitialHistoryVisibilityChange) {
|
||||
reasons.push("onInitialHistoryVisibilityChange");
|
||||
}
|
||||
if (left.bottomOverlayTailClearance !== right.bottomOverlayTailClearance) {
|
||||
reasons.push("bottomOverlayTailClearance");
|
||||
}
|
||||
|
||||
@@ -66,6 +66,19 @@ function thought(id: string, seed: number): StreamItem {
|
||||
};
|
||||
}
|
||||
|
||||
function pluginItem(id: string, seed: number): StreamItem {
|
||||
return {
|
||||
kind: "plugin",
|
||||
id,
|
||||
timestamp: createTimestamp(seed),
|
||||
pluginId: "test-plugin",
|
||||
pluginItemId: id,
|
||||
itemKind: "compact",
|
||||
version: 1,
|
||||
data: {},
|
||||
};
|
||||
}
|
||||
|
||||
function indexEntries(items: StreamItem[]): IndexedStreamItem[] {
|
||||
return items.map((item, index) => ({ item, index }));
|
||||
}
|
||||
@@ -211,6 +224,12 @@ describe("estimateStreamItemHeight", () => {
|
||||
contentMaxWidth: DEFAULT_CONTENT_MAX_WIDTH,
|
||||
}),
|
||||
).toBe(40);
|
||||
expect(
|
||||
estimateStreamItemHeight({
|
||||
item: pluginItem("plugin", 3),
|
||||
contentMaxWidth: DEFAULT_CONTENT_MAX_WIDTH,
|
||||
}),
|
||||
).toBe(40);
|
||||
});
|
||||
|
||||
it("uses a larger estimate for user messages with image attachments", () => {
|
||||
|
||||
@@ -70,6 +70,10 @@ export function estimateStreamItemHeight({
|
||||
case "thought":
|
||||
case "turn_summary":
|
||||
return COLLAPSED_TOOL_SEQUENCE_ROW_HEIGHT_ESTIMATE;
|
||||
case "plugin":
|
||||
// Common plugin rows (route badges, collapsed thought/tool cards, hidden markers) are mostly
|
||||
// compact single-line rows, so reuse 40px to avoid large overestimation shrinkage.
|
||||
return COLLAPSED_TOOL_SEQUENCE_ROW_HEIGHT_ESTIMATE;
|
||||
case "todo_list":
|
||||
return 144;
|
||||
case "notification":
|
||||
|
||||
@@ -147,6 +147,9 @@ function HostWorkspaceRouteContent() {
|
||||
}
|
||||
|
||||
function WorkspaceDeck() {
|
||||
// The compiler caches render-time Date.now() without this directive.
|
||||
"use no memo";
|
||||
|
||||
const activeSelection = useActiveWorkspaceSelection();
|
||||
const [retainedSelections, setRetainedSelections] = useState<RetainedWorkspaceSelection[]>(() =>
|
||||
activeSelection ? [{ selection: activeSelection, inactiveSince: null }] : [],
|
||||
|
||||
@@ -108,6 +108,8 @@ export type UserComposerAttachment =
|
||||
| { kind: "file"; attachment: UploadedFileAttachment }
|
||||
| WorkspaceFileComposerAttachment
|
||||
| PluginResourceComposerAttachment
|
||||
// An attachment taken back from a queued message. The host already holds it in wire form.
|
||||
| { kind: "agent_attachment"; attachment: AgentAttachment }
|
||||
| { kind: "forge_issue"; item: ForgeSearchItem }
|
||||
| { kind: "forge_change_request"; item: ForgeSearchItem }
|
||||
// COMPAT(githubAttachmentKinds): legacy persisted attachment kinds retained
|
||||
|
||||
@@ -131,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. */
|
||||
export function AttachmentThumbnail({ metadata }: { metadata: AttachmentMetadata }) {
|
||||
const preview = useAttachmentPreviewUrl(metadata);
|
||||
const uri = preview.status === "ready" ? preview.url : null;
|
||||
const source = useMemo(() => (uri ? { uri } : null), [uri]);
|
||||
if (!source) {
|
||||
return <View style={styles.thumbnailPlaceholder} />;
|
||||
return <AttachmentThumbnailPlaceholder />;
|
||||
}
|
||||
return <Image source={source} style={styles.thumbnail} />;
|
||||
}
|
||||
|
||||
@@ -2,16 +2,15 @@ import { useCallback, useMemo, useRef, useState, type ReactElement } from "react
|
||||
import { Text, View } from "react-native";
|
||||
import { Server } from "lucide-react-native";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { HOST_STATUS_DOT_SIZE } from "@/components/host-status-dot";
|
||||
import { ComboboxTrigger } from "@/components/ui/combobox-trigger";
|
||||
import { ComboboxTrigger, type ComboboxTriggerState } from "@/components/ui/combobox-trigger";
|
||||
import { mapLayout } from "@/components/ui/control-sizing";
|
||||
import { HostStatusIcon } from "@/hosts/host-status-icon";
|
||||
import { density } from "@/styles/density";
|
||||
import { ICON_SIZE, type Theme } from "@/styles/theme";
|
||||
import {
|
||||
ALL_HOSTS_OPTION_ID,
|
||||
getHostPickerLabel,
|
||||
HostPicker,
|
||||
HostStatusDotSlot,
|
||||
type HostPickerHost,
|
||||
} from "@/components/hosts/host-picker";
|
||||
|
||||
@@ -65,12 +64,8 @@ export function HostFilter({
|
||||
const handleFilterOpen = useCallback(() => setIsFilterOpen(true), []);
|
||||
const showsAllHosts = selectedHost === ALL_HOSTS_OPTION_ID;
|
||||
const slotStyle = useMemo(
|
||||
() => [
|
||||
styles.triggerSlot,
|
||||
hang && styles.triggerSlotHang,
|
||||
hang && (showsAllHosts ? styles.glyphHang : styles.dotHang),
|
||||
],
|
||||
[hang, showsAllHosts],
|
||||
() => [styles.triggerSlot, hang && styles.triggerSlotHang, hang && styles.glyphHang],
|
||||
[hang],
|
||||
);
|
||||
|
||||
const triggerStyle = useCallback(
|
||||
@@ -82,6 +77,26 @@ export function HostFilter({
|
||||
[],
|
||||
);
|
||||
|
||||
const renderTriggerContent = useCallback(
|
||||
({ hovered, pressed }: ComboboxTriggerState) => (
|
||||
<>
|
||||
{showsAllHosts ? (
|
||||
<ThemedServer size={ICON_SIZE.sm} uniProps={mutedColorMapping} />
|
||||
) : (
|
||||
<HostStatusIcon
|
||||
serverId={selectedHost}
|
||||
size="sm"
|
||||
backdrop={hovered || pressed ? "surface2" : "surface0"}
|
||||
/>
|
||||
)}
|
||||
<Text style={styles.label} numberOfLines={1}>
|
||||
{selectedHostLabel}
|
||||
</Text>
|
||||
</>
|
||||
),
|
||||
[selectedHost, selectedHostLabel, showsAllHosts],
|
||||
);
|
||||
|
||||
return (
|
||||
<HostPicker
|
||||
hosts={hosts}
|
||||
@@ -105,14 +120,7 @@ export function HostFilter({
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={`Filter: ${selectedHostLabel}`}
|
||||
>
|
||||
{showsAllHosts ? (
|
||||
<ThemedServer size={ICON_SIZE.sm} uniProps={mutedColorMapping} />
|
||||
) : (
|
||||
<HostStatusDotSlot serverId={selectedHost} />
|
||||
)}
|
||||
<Text style={styles.label} numberOfLines={1}>
|
||||
{selectedHostLabel}
|
||||
</Text>
|
||||
{renderTriggerContent}
|
||||
</ComboboxTrigger>
|
||||
</View>
|
||||
</HostPicker>
|
||||
@@ -132,14 +140,10 @@ const styles = StyleSheet.create((theme) => ({
|
||||
triggerSlotHang: {
|
||||
marginVertical: mapLayout(density.tightRowHeight, (height) => (LABEL_LINE - height) / 2),
|
||||
},
|
||||
// Hangs the padding, so the server glyph's box sits on the rail.
|
||||
// Hangs the padding, so the leading glyph's box sits on the rail.
|
||||
glyphHang: {
|
||||
marginLeft: -theme.spacing[2],
|
||||
},
|
||||
// Hangs the padding and the dot's inset in its icon slot, so the dot's ink sits on the rail.
|
||||
dotHang: {
|
||||
marginLeft: -(theme.spacing[2] + (ICON_SIZE.sm - HOST_STATUS_DOT_SIZE) / 2),
|
||||
},
|
||||
// The Settings host trigger: a borderless row that fills on hover and press.
|
||||
trigger: {
|
||||
flexShrink: 1,
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { useCallback, useMemo, type ReactElement } from "react";
|
||||
import { View } from "react-native";
|
||||
import { HostStatusDot } from "@/components/host-status-dot";
|
||||
import { MenuItem } from "@/components/ui/menu";
|
||||
import { HostStatusIcon } from "@/hosts/host-status-icon";
|
||||
|
||||
interface HostMenuItemProps {
|
||||
serverId: string;
|
||||
@@ -14,7 +13,7 @@ interface HostMenuItemProps {
|
||||
statusTestID?: string;
|
||||
}
|
||||
|
||||
/** A host as a menu option: its live status dot leads, and the chosen host carries the check. */
|
||||
/** A host as a menu option: its resolved icon with live status dot leads, and the chosen host carries the check. */
|
||||
export function HostMenuItem({
|
||||
serverId,
|
||||
label,
|
||||
@@ -27,9 +26,12 @@ export function HostMenuItem({
|
||||
const handleSelect = useCallback(() => onSelect(serverId), [onSelect, serverId]);
|
||||
const leading = useMemo(
|
||||
() => (
|
||||
<View testID={statusTestID}>
|
||||
<HostStatusDot serverId={serverId} />
|
||||
</View>
|
||||
<HostStatusIcon
|
||||
serverId={serverId}
|
||||
size="sm"
|
||||
backdrop="surface1"
|
||||
statusTestID={statusTestID}
|
||||
/>
|
||||
),
|
||||
[serverId, statusTestID],
|
||||
);
|
||||
|
||||
@@ -54,14 +54,6 @@ export interface HostPickerHost {
|
||||
label: string;
|
||||
}
|
||||
|
||||
export function HostStatusDotSlot({ serverId }: { serverId: string }): ReactElement {
|
||||
return (
|
||||
<View style={styles.statusDotSlot}>
|
||||
<HostStatusDot serverId={serverId} />
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
export interface HostPickerOptionProps {
|
||||
serverId: string;
|
||||
label: string;
|
||||
@@ -415,12 +407,6 @@ export function HostPicker({
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
statusDotSlot: {
|
||||
width: theme.iconSize.sm,
|
||||
height: theme.iconSize.sm,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
rowEnvelope: {
|
||||
position: "relative",
|
||||
},
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Animated } from "react-native";
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { createIndicatorClock } from "./clock";
|
||||
import { type ClockDriver, createIndicatorClock } from "./clock";
|
||||
|
||||
const PERIOD_MS = 900;
|
||||
const STEPS = 27;
|
||||
@@ -15,13 +15,18 @@ function read(node: object): number {
|
||||
return Number(node.__getValue());
|
||||
}
|
||||
|
||||
// Float arithmetic in the driver leaves noise far below a pixel.
|
||||
function rounded(position: number): number {
|
||||
return Math.round(position * 1e6) / 1e6;
|
||||
}
|
||||
|
||||
// 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);
|
||||
const position = createIndicatorClock(elapsedMs).cycle(PERIOD_MS, { steps });
|
||||
return elapsed.map((ms) => {
|
||||
elapsedMs.setValue(ms);
|
||||
return Math.round(read(position) * 1e6) / 1e6;
|
||||
return rounded(read(position));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -30,6 +35,44 @@ function frames(hz: number, count: number): number[] {
|
||||
return Array.from({ length: count }, (_, frame) => (frame * 1000) / hz);
|
||||
}
|
||||
|
||||
// A driver that advances nothing by itself, so the test decides when each span ends and when the
|
||||
// native driver says where a stopped clock is.
|
||||
function heldDriver() {
|
||||
const spansFromMs: number[] = [];
|
||||
const reports: ((heldMs: number) => void)[] = [];
|
||||
let onEnd: ((result: { finished: boolean }) => void) | null = null;
|
||||
function end(finished: boolean) {
|
||||
const ended = onEnd;
|
||||
onEnd = null;
|
||||
ended?.({ finished });
|
||||
}
|
||||
return {
|
||||
drive(_elapsedMs: Animated.Value, fromMs: number): ClockDriver {
|
||||
spansFromMs.push(fromMs);
|
||||
return {
|
||||
start(ended) {
|
||||
onEnd = ended;
|
||||
},
|
||||
stop(onHeld) {
|
||||
reports.push(onHeld);
|
||||
end(false);
|
||||
},
|
||||
};
|
||||
},
|
||||
/** What the native driver reports when it has counted a whole span. */
|
||||
finish: () => end(true),
|
||||
/** The native driver's answer to the oldest stop it has not answered. */
|
||||
reportHeld: (heldMs: number) => reports.shift()?.(heldMs),
|
||||
running: () => onEnd !== null,
|
||||
spansFromMs,
|
||||
};
|
||||
}
|
||||
|
||||
// The clock stops after the commit that took its last indicator away.
|
||||
async function commit(): Promise<void> {
|
||||
await Promise.resolve();
|
||||
}
|
||||
|
||||
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]);
|
||||
@@ -76,4 +119,152 @@ describe("indicator clock", () => {
|
||||
expect(early).toEqual(onTime.slice(1));
|
||||
expect(late).toEqual(onTime);
|
||||
});
|
||||
|
||||
test("a cycle with its own phase starts at its first step and turns over with the others", () => {
|
||||
const shimmerSteps = 41;
|
||||
const shimmerPeriodMs = shimmerSteps * STEP_MS;
|
||||
let nowMs = 0;
|
||||
const elapsedMs = new Animated.Value(0);
|
||||
const clock = createIndicatorClock(elapsedMs, () => nowMs, heldDriver().drive);
|
||||
const stop = clock.run();
|
||||
|
||||
// The shared clock has been running for a while when the shimmer appears.
|
||||
nowMs = 1010;
|
||||
const ring = clock.cycle(PERIOD_MS, { steps: STEPS });
|
||||
const shimmer = clock.cycle(shimmerPeriodMs, { steps: shimmerSteps, phase: "own" });
|
||||
const readings = frames(60, 3 * 60)
|
||||
.map((ms) => ms + 1010)
|
||||
.map((ms) => {
|
||||
elapsedMs.setValue(ms);
|
||||
return { ring: rounded(read(ring)), shimmer: rounded(read(shimmer)) };
|
||||
});
|
||||
stop();
|
||||
|
||||
expect(readings[0].shimmer).toBeLessThan(STEP_MS);
|
||||
const shimmerTurns: number[] = [];
|
||||
const ringTurns: number[] = [];
|
||||
for (let frame = 1; frame < readings.length; frame += 1) {
|
||||
if (readings[frame].shimmer !== readings[frame - 1].shimmer) shimmerTurns.push(frame);
|
||||
if (readings[frame].ring !== readings[frame - 1].ring) ringTurns.push(frame);
|
||||
}
|
||||
expect(shimmerTurns.length).toBeGreaterThan(80);
|
||||
expect(shimmerTurns).toEqual(ringTurns);
|
||||
});
|
||||
|
||||
test("a cycle with its own phase on an idle clock starts with the clock", () => {
|
||||
const elapsedMs = new Animated.Value(0);
|
||||
const clock = createIndicatorClock(elapsedMs, () => 5000);
|
||||
const shimmer = clock.cycle(41 * STEP_MS, { steps: 41, phase: "own" });
|
||||
|
||||
expect(read(shimmer)).toBe(0);
|
||||
});
|
||||
|
||||
test("a span that ends under a running indicator is followed by one from where it ended", async () => {
|
||||
let nowMs = 0;
|
||||
const driver = heldDriver();
|
||||
const clock = createIndicatorClock(new Animated.Value(0), () => nowMs, driver.drive);
|
||||
const stop = clock.run();
|
||||
|
||||
// The JS thread hears about the end a few milliseconds after it.
|
||||
nowMs = 600_012;
|
||||
driver.finish();
|
||||
|
||||
expect(driver.running()).toBe(true);
|
||||
expect(driver.spansFromMs).toEqual([0, 600_000]);
|
||||
|
||||
stop();
|
||||
await commit();
|
||||
expect(driver.running()).toBe(false);
|
||||
});
|
||||
|
||||
test("a stopped clock holds its time and counts on from it", async () => {
|
||||
let nowMs = 0;
|
||||
const driver = heldDriver();
|
||||
const clock = createIndicatorClock(new Animated.Value(0), () => nowMs, driver.drive);
|
||||
|
||||
const stop = clock.run();
|
||||
nowMs = 5000;
|
||||
stop();
|
||||
await commit();
|
||||
expect(driver.running()).toBe(false);
|
||||
// The native driver started counting a frame after the JS thread asked.
|
||||
driver.reportHeld(4983);
|
||||
|
||||
nowMs = 90_000;
|
||||
clock.run();
|
||||
|
||||
expect(driver.spansFromMs).toEqual([0, 4983]);
|
||||
});
|
||||
|
||||
test("a clock restarted before the driver reports counts on from its own reading", async () => {
|
||||
let nowMs = 0;
|
||||
const driver = heldDriver();
|
||||
const clock = createIndicatorClock(new Animated.Value(0), () => nowMs, driver.drive);
|
||||
|
||||
const stopFirst = clock.run();
|
||||
nowMs = 5000;
|
||||
stopFirst();
|
||||
await commit();
|
||||
const stopSecond = clock.run();
|
||||
nowMs = 7000;
|
||||
stopSecond();
|
||||
await commit();
|
||||
// The answer to the first stop arrives after the second.
|
||||
driver.reportHeld(4983);
|
||||
clock.run();
|
||||
|
||||
expect(driver.spansFromMs).toEqual([0, 5000, 7000]);
|
||||
});
|
||||
|
||||
test("the clock keeps counting when one indicator takes over from another in a commit", async () => {
|
||||
const driver = heldDriver();
|
||||
const clock = createIndicatorClock(new Animated.Value(0), () => 0, driver.drive);
|
||||
|
||||
const stopChat = clock.run();
|
||||
stopChat();
|
||||
const stopSidebar = clock.run();
|
||||
await commit();
|
||||
|
||||
expect(driver.running()).toBe(true);
|
||||
expect(driver.spansFromMs).toEqual([0]);
|
||||
|
||||
stopSidebar();
|
||||
await commit();
|
||||
expect(driver.running()).toBe(false);
|
||||
});
|
||||
|
||||
test("a cycle with its own phase on a stopped clock starts where the clock will count on", async () => {
|
||||
let nowMs = 0;
|
||||
const elapsedMs = new Animated.Value(0);
|
||||
const driver = heldDriver();
|
||||
const clock = createIndicatorClock(elapsedMs, () => nowMs, driver.drive);
|
||||
const stop = clock.run();
|
||||
nowMs = 5000;
|
||||
stop();
|
||||
await commit();
|
||||
driver.reportHeld(4983);
|
||||
|
||||
const shimmer = clock.cycle(41 * STEP_MS, { steps: 41, phase: "own" });
|
||||
elapsedMs.setValue(4983);
|
||||
|
||||
expect(read(shimmer)).toBeLessThan(STEP_MS);
|
||||
});
|
||||
|
||||
test("a cycle with its own phase starts at its first step in a later span too", () => {
|
||||
let nowMs = 0;
|
||||
const elapsedMs = new Animated.Value(0);
|
||||
const driver = heldDriver();
|
||||
const clock = createIndicatorClock(elapsedMs, () => nowMs, driver.drive);
|
||||
const stop = clock.run();
|
||||
|
||||
nowMs = 600_012;
|
||||
driver.finish();
|
||||
// The second span started at 600 000 on the clock, 12 ms late on the JS thread.
|
||||
nowMs = 640_012;
|
||||
const shimmer = clock.cycle(41 * STEP_MS, { steps: 41, phase: "own" });
|
||||
elapsedMs.setValue(640_000);
|
||||
stop();
|
||||
|
||||
expect(read(shimmer)).toBeLessThan(STEP_MS);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,11 +1,17 @@
|
||||
import { useEffect } from "react";
|
||||
import { Animated } from "react-native";
|
||||
import { Animated, Easing } 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 counts time in spans this long: a linear timing of one unit per millisecond, which the
|
||||
// native driver reads off the frame's timestamp. Only the end of a span comes back to the JS
|
||||
// thread, which starts the next one where that one ended.
|
||||
//
|
||||
// A decay that never slows would count without spans, but the driver ends a decay whose value did
|
||||
// not move between two frames, and two frames that carry the same millisecond are enough. A timing
|
||||
// has no such check.
|
||||
//
|
||||
// The timing is sent to the driver as one value for every 60th of a second, so a longer span costs
|
||||
// more each time the clock starts.
|
||||
const SPAN_MS = 10 * 60 * 1000;
|
||||
|
||||
// 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
|
||||
@@ -14,52 +20,124 @@ const CLOCK_CONFIG = { velocity: 1, deceleration: 1 - 1e-12, useNativeDriver: tr
|
||||
const STEP_LEAD = 1 / 8;
|
||||
|
||||
/**
|
||||
* Milliseconds, counted on the UI thread by React Native's native animation driver.
|
||||
* Milliseconds for which the clock has run, 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 {
|
||||
export interface CycleOptions {
|
||||
/**
|
||||
* 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.
|
||||
* Hold the position at each of this many even steps instead of advancing it every frame. A view
|
||||
* bound to a held position is not redrawn until the step turns over.
|
||||
*/
|
||||
steps?: number;
|
||||
/**
|
||||
* `shared`, the default, counts the cycle from the clock's start, so every cycle of the same
|
||||
* length is at the same point. `own` starts the cycle at the clock's latest step, so it begins at
|
||||
* its first position; it still turns over with every other cycle of the same step length.
|
||||
*/
|
||||
phase?: "shared" | "own";
|
||||
}
|
||||
|
||||
export interface IndicatorClock {
|
||||
/** Where a cycle of `periodMs` currently is, as milliseconds into the cycle. */
|
||||
cycle(periodMs: number, options?: CycleOptions): Animated.AnimatedInterpolation<number>;
|
||||
/**
|
||||
* Runs the clock until the returned function is called. A clock nobody runs holds its time, and
|
||||
* counts on from it when it runs again, so a view bound to it stays where it stopped.
|
||||
*/
|
||||
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;
|
||||
}
|
||||
|
||||
/** What advances the clock's value through one span, or until it is stopped. */
|
||||
export interface ClockDriver {
|
||||
start(onEnd: (result: { finished: boolean }) => void): void;
|
||||
/** Stops counting, then reports the time the clock stopped at. */
|
||||
stop(onHeld: (heldMs: number) => void): void;
|
||||
}
|
||||
|
||||
function countSpan(elapsedMs: Animated.Value, fromMs: number): ClockDriver {
|
||||
const span = Animated.timing(elapsedMs, {
|
||||
toValue: fromMs + SPAN_MS,
|
||||
duration: SPAN_MS,
|
||||
easing: Easing.linear,
|
||||
useNativeDriver: true,
|
||||
});
|
||||
return {
|
||||
start: (onEnd) => span.start(onEnd),
|
||||
stop: (onHeld) => elapsedMs.stopAnimation(onHeld),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The native driver owns the clock's time: the JS thread never sets it, only starts and stops the
|
||||
* counting. `now` lets the JS thread follow along. The native driver starts counting a frame or two
|
||||
* after it is asked, so a cycle with its own phase can start a step into its pass, or a step
|
||||
* before it; the run-in before the first position hides either.
|
||||
*/
|
||||
export function createIndicatorClock(
|
||||
elapsedMs = new Animated.Value(0, { useNativeDriver: true }),
|
||||
now: () => number = () => performance.now(),
|
||||
drive: (elapsedMs: Animated.Value, fromMs: number) => ClockDriver = countSpan,
|
||||
): IndicatorClock {
|
||||
let runners = 0;
|
||||
let ticking: Animated.CompositeAnimation | null = null;
|
||||
let ticking: ClockDriver | null = null;
|
||||
// While the clock counts: when, on the JS thread, it read zero.
|
||||
let zeroAtMs = 0;
|
||||
// While it does not: the time it holds.
|
||||
let heldMs = 0;
|
||||
let lastStopped: ClockDriver | null = null;
|
||||
|
||||
function currentStepStartMs(stepMs: number): number {
|
||||
const elapsed = ticking ? now() - zeroAtMs : heldMs;
|
||||
return Math.floor(elapsed / stepMs) * stepMs;
|
||||
}
|
||||
|
||||
function count(fromMs: number) {
|
||||
zeroAtMs = now() - fromMs;
|
||||
const driver = drive(elapsedMs, fromMs);
|
||||
ticking = driver;
|
||||
driver.start(({ finished }) => {
|
||||
if (finished && ticking === driver) count(fromMs + SPAN_MS);
|
||||
});
|
||||
}
|
||||
|
||||
function hold() {
|
||||
if (runners > 0 || !ticking) return;
|
||||
const stopped = ticking;
|
||||
ticking = null;
|
||||
lastStopped = stopped;
|
||||
// The JS thread's reading stands until the native driver reports its own.
|
||||
heldMs = now() - zeroAtMs;
|
||||
stopped.stop((reportedMs) => {
|
||||
if (!ticking && lastStopped === stopped) heldMs = reportedMs;
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
cycle(periodMs, steps) {
|
||||
cycle(periodMs, { steps, phase = "shared" } = {}) {
|
||||
const stepMs = steps ? periodMs / steps : 0;
|
||||
const lead = stepMs * STEP_LEAD;
|
||||
// Shift by a whole number of steps, forwards, so the position never goes negative.
|
||||
const shift = phase === "own" ? periodMs - (currentStepStartMs(stepMs || 1) % periodMs) : 0;
|
||||
const position = Animated.modulo(Animated.add(elapsedMs, lead + shift), periodMs);
|
||||
if (!steps) {
|
||||
return Animated.modulo(elapsedMs, periodMs);
|
||||
return position;
|
||||
}
|
||||
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();
|
||||
count(heldMs);
|
||||
}
|
||||
return () => {
|
||||
runners -= 1;
|
||||
if (runners === 0) {
|
||||
ticking?.stop();
|
||||
ticking = null;
|
||||
}
|
||||
// One commit can take the last indicator away and bring another, as when a panel replaces
|
||||
// another. Stopping after the commit keeps the clock counting through that.
|
||||
if (runners === 0) queueMicrotask(hold);
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
@@ -35,15 +35,21 @@ function useReducedMotion(): boolean {
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* What a running indicator does right now.
|
||||
*
|
||||
* An indicator that is not moving draws its resting frame and runs nothing.
|
||||
* - `moving`: it runs.
|
||||
* - `held`: nobody can see it, in a retained panel that is not showing or in an app that is in the
|
||||
* background. It runs nothing and keeps its place, so it continues from there when it is seen
|
||||
* again. A panel slides into view before it counts as showing, and an indicator that dropped to
|
||||
* its resting frame would jump when the slide ends.
|
||||
* - `resting`: the system asks for reduced motion. It draws its resting frame and runs nothing.
|
||||
*/
|
||||
export function useIndicatorMotion(): boolean {
|
||||
export type IndicatorMotion = "moving" | "held" | "resting";
|
||||
|
||||
export function useIndicatorMotion(): IndicatorMotion {
|
||||
const panelActive = useRetainedPanelActive();
|
||||
const appVisible = useAppVisible();
|
||||
const reducedMotion = useReducedMotion();
|
||||
return panelActive && appVisible && !reducedMotion;
|
||||
if (reducedMotion) return "resting";
|
||||
return panelActive && appVisible ? "moving" : "held";
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useLayoutEffect, useRef, type RefObject } from "react";
|
||||
import type { View } from "react-native";
|
||||
import { INDICATOR_STEP_MS } from "./steps";
|
||||
|
||||
const TIMELINE_ORIGIN_MS = 0;
|
||||
|
||||
@@ -10,11 +11,18 @@ export interface IndicatorLoop {
|
||||
/**
|
||||
* `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.
|
||||
* the cycle at the step of the indicator step grid the loop starts in, so a stepped loop turns
|
||||
* over with every other; see `steps.ts`.
|
||||
*/
|
||||
phase: "shared" | "own";
|
||||
}
|
||||
|
||||
// The start of the step of the indicator step grid the document timeline is in now.
|
||||
function currentStepStartMs(): number {
|
||||
const now = Number(document.timeline.currentTime ?? 0);
|
||||
return Math.floor(now / INDICATOR_STEP_MS) * INDICATOR_STEP_MS;
|
||||
}
|
||||
|
||||
/**
|
||||
* Repeats `loop` on the element the returned ref is attached to, for as long as `loop` is given.
|
||||
*
|
||||
@@ -39,8 +47,7 @@ export function useIndicatorLoop(loop: IndicatorLoop | null): RefObject<View | n
|
||||
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;
|
||||
animation.startTime = loop.phase === "shared" ? TIMELINE_ORIGIN_MS : currentStepStartMs();
|
||||
return () => {
|
||||
animation.cancel();
|
||||
};
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
/**
|
||||
* How long a stepped indicator holds each position: thirty positions a second.
|
||||
*
|
||||
* A window is drawn again every time something in it moves, and two indicators only share a frame
|
||||
* when their steps turn over at the same instant. Every stepped indicator moves on this one grid,
|
||||
* counted from the same origin, so a ring and a shimmer on screen together still cost thirty frames
|
||||
* a second.
|
||||
*/
|
||||
export const INDICATOR_STEP_MS = 1000 / 30;
|
||||
|
||||
/** The whole number of indicator steps closest to `periodMs`, and never fewer than one. */
|
||||
export function getIndicatorSteps(periodMs: number): number {
|
||||
return Math.max(1, Math.round(periodMs / INDICATOR_STEP_MS));
|
||||
}
|
||||
@@ -3,8 +3,8 @@ 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";
|
||||
import { sharedIndicatorClock, useRunningClock } from "@/components/indicator-motion/clock";
|
||||
import { type LabelShimmerProps, getRowSweep, getShimmerCycle } from "./sweep";
|
||||
|
||||
export { useLabelMeasurements } from "./measurements";
|
||||
|
||||
@@ -48,8 +48,9 @@ const styles = StyleSheet.create({
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* native animation driver moves the band; see `indicator-motion/clock.ts`. The band rides the
|
||||
* shared clock, so its steps turn over on the same frames as the status rings', and starts its own
|
||||
* pass so the highlight enters from the left when it appears.
|
||||
*/
|
||||
export const LabelShimmer = memo(function LabelShimmer({
|
||||
label,
|
||||
@@ -60,34 +61,38 @@ export const LabelShimmer = memo(function LabelShimmer({
|
||||
}: LabelShimmerProps) {
|
||||
const { rowSize } = measurements;
|
||||
const measured = rowSize.width > 0 && rowSize.height > 0;
|
||||
const moving = useIndicatorMotion() && measured;
|
||||
const [clock] = useState(createIndicatorClock);
|
||||
const motion = useIndicatorMotion();
|
||||
// A held band stays on the clock, so it keeps its place and its pass.
|
||||
const sweeping = motion !== "resting" && measured;
|
||||
const [gradientId] = useState(
|
||||
() => `shimmer-gradient-${Math.random().toString(36).substring(2, 9)}`,
|
||||
);
|
||||
useRunningClock(clock, moving);
|
||||
useRunningClock(sharedIndicatorClock, motion === "moving" && measured);
|
||||
|
||||
const durationMs = getShimmerDurationMs(label, secondaryLabel);
|
||||
const { durationMs, steps } = getShimmerCycle(label, secondaryLabel);
|
||||
const { peakWidth, fromX, toX } = getRowSweep(rowSize.width);
|
||||
const { width, height } = rowSize;
|
||||
|
||||
const trackStyle = useMemo(() => [styles.track, { width, height }], [height, width]);
|
||||
// Built again each time the band appears, so each appearance begins a new pass.
|
||||
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],
|
||||
() =>
|
||||
sweeping
|
||||
? [
|
||||
styles.band,
|
||||
{ width: peakWidth, height },
|
||||
{
|
||||
transform: [
|
||||
{
|
||||
translateX: sharedIndicatorClock
|
||||
.cycle(durationMs, { steps, phase: "own" })
|
||||
.interpolate({ inputRange: [0, durationMs], outputRange: [fromX, toX] }),
|
||||
},
|
||||
],
|
||||
},
|
||||
]
|
||||
: null,
|
||||
[durationMs, fromX, height, sweeping, peakWidth, steps, toX],
|
||||
);
|
||||
const maskElement = useMemo(
|
||||
() => (
|
||||
@@ -107,7 +112,7 @@ export const LabelShimmer = memo(function LabelShimmer({
|
||||
[height, label, labelStyle, secondaryLabel, secondaryLabelStyle, width],
|
||||
);
|
||||
|
||||
if (!moving) {
|
||||
if (!sweeping) {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ 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";
|
||||
import { type LabelShimmerProps, type ShimmerCycle, getShimmerCycle, getTextSweep } from "./sweep";
|
||||
|
||||
export { useLabelMeasurements } from "./measurements";
|
||||
|
||||
@@ -37,10 +37,16 @@ const bandBaseStyle = {
|
||||
const textStyle: ViewStyle = { ...FILL, flexDirection: "row", alignItems: "center" };
|
||||
const spacerStyle: ViewStyle = { flex: 1 };
|
||||
|
||||
function slide(fromX: number, toX: number, durationMs: number): IndicatorLoop {
|
||||
// `steps(n)` holds each of the pass's positions for a step; the compositor draws a frame when the
|
||||
// step changes and none in between. The loop starts on the indicators' step grid, so its steps turn
|
||||
// over with the status rings'.
|
||||
function slide(fromX: number, toX: number, cycle: ShimmerCycle): IndicatorLoop {
|
||||
return {
|
||||
keyframes: [{ transform: `translateX(${fromX}px)` }, { transform: `translateX(${toX}px)` }],
|
||||
durationMs,
|
||||
keyframes: [
|
||||
{ transform: `translateX(${fromX}px)`, easing: `steps(${cycle.steps})` },
|
||||
{ transform: `translateX(${toX}px)` },
|
||||
],
|
||||
durationMs: cycle.durationMs,
|
||||
phase: "own",
|
||||
};
|
||||
}
|
||||
@@ -59,18 +65,18 @@ export const LabelShimmer = memo(function LabelShimmer({
|
||||
measurements,
|
||||
}: LabelShimmerProps) {
|
||||
const { labelSpan, secondarySpan } = measurements;
|
||||
const moving = useIndicatorMotion();
|
||||
const durationMs = getShimmerDurationMs(label, secondaryLabel);
|
||||
const moving = useIndicatorMotion() === "moving";
|
||||
const { durationMs, steps } = getShimmerCycle(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],
|
||||
() => (moving ? slide(sweep.fromX, sweep.toX, { durationMs, steps }) : null),
|
||||
[durationMs, moving, steps, sweep.fromX, sweep.toX],
|
||||
);
|
||||
const textLoop = useMemo(
|
||||
() => (moving ? slide(-sweep.fromX, -sweep.toX, durationMs) : null),
|
||||
[durationMs, moving, sweep.fromX, sweep.toX],
|
||||
() => (moving ? slide(-sweep.fromX, -sweep.toX, { durationMs, steps }) : null),
|
||||
[durationMs, moving, steps, sweep.fromX, sweep.toX],
|
||||
);
|
||||
const bandRef = useIndicatorLoop(bandLoop);
|
||||
const textRef = useIndicatorLoop(textLoop);
|
||||
|
||||
@@ -1,13 +1,26 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { getRowSweep, getShimmerDurationMs, getTextSweep } from "./sweep";
|
||||
import { getRowSweep, getShimmerCycle, getTextSweep } from "./sweep";
|
||||
|
||||
const STEP_MS = 1000 / 30;
|
||||
|
||||
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);
|
||||
expect(getShimmerCycle("Shell", "sleep 600").durationMs).toBeCloseTo(1362, -1);
|
||||
expect(getShimmerCycle("Read", undefined).durationMs).toBeCloseTo(1032, -1);
|
||||
expect(getShimmerCycle(" Edit ", " a.ts ")).toEqual(getShimmerCycle("Edit", "a.ts"));
|
||||
expect(getShimmerCycle("", undefined).durationMs).toBeCloseTo(1000);
|
||||
expect(getShimmerCycle("x".repeat(400), undefined).durationMs).toBeCloseTo(2300);
|
||||
});
|
||||
|
||||
test("moves thirty times a second, so a pass is a whole number of steps", () => {
|
||||
for (const label of ["", "Read", "Shell", "x".repeat(40), "x".repeat(400)]) {
|
||||
const { durationMs, steps } = getShimmerCycle(label, "sleep 600");
|
||||
expect(Number.isInteger(steps)).toBe(true);
|
||||
expect(durationMs / steps).toBeCloseTo(STEP_MS, 9);
|
||||
}
|
||||
// The nearest whole step: within half a step of the smooth pass, so the speed reads the same.
|
||||
expect(getShimmerCycle("Shell", "sleep 600").steps).toBe(41);
|
||||
expect(getShimmerCycle("Read", undefined).steps).toBe(31);
|
||||
});
|
||||
|
||||
test("crosses the text from one band width before the label to the end of the last text", () => {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { INDICATOR_STEP_MS, getIndicatorSteps } from "@/components/indicator-motion/steps";
|
||||
import type { StyleProp, TextStyle } from "react-native";
|
||||
|
||||
/** Where a piece of text sits on the label row, as the row's layout reported it. */
|
||||
@@ -34,12 +35,24 @@ export interface ShimmerSweep {
|
||||
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 {
|
||||
/** One pass of the highlight, in time: `steps` positions over `durationMs`. */
|
||||
export interface ShimmerCycle {
|
||||
durationMs: number;
|
||||
steps: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Longer labels take longer to cross, within limits, so the highlight's speed reads the same.
|
||||
*
|
||||
* The highlight moves on the indicators' step grid, so a pass is a whole number of steps: the one
|
||||
* closest to the smooth pass, which changes its length by at most half a step.
|
||||
*/
|
||||
export function getShimmerCycle(label: string, secondaryLabel: string | undefined): ShimmerCycle {
|
||||
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;
|
||||
const steps = getIndicatorSteps(seconds * 1000);
|
||||
return { durationMs: steps * INDICATOR_STEP_MS, steps };
|
||||
}
|
||||
|
||||
/** Sweeps the text itself: in from just left of the label, out at the end of the last text. */
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { createContext, useContext } from "react";
|
||||
import { useContext } from "react";
|
||||
import { withUnistyles } from "react-native-unistyles";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
import { MarkdownStreamingContext } from "../../streaming-context";
|
||||
import { MermaidFenceHost } from "./host";
|
||||
export { splitMermaidFences } from "./segments";
|
||||
export const MermaidStreamingContext = createContext(false);
|
||||
const ThemedHost = withUnistyles(MermaidFenceHost);
|
||||
const styles = (theme: Theme) => ({
|
||||
inheritedStyles: {
|
||||
@@ -14,6 +14,6 @@ const styles = (theme: Theme) => ({
|
||||
textStyle: { backgroundColor: theme.colors.surface2, padding: 12, borderRadius: 8 },
|
||||
});
|
||||
export function MermaidFence({ code }: { code: string }) {
|
||||
const streaming = useContext(MermaidStreamingContext);
|
||||
const streaming = useContext(MarkdownStreamingContext);
|
||||
return <ThemedHost code={code} phase={streaming ? "streaming" : "complete"} uniProps={styles} />;
|
||||
}
|
||||
|
||||
@@ -43,8 +43,11 @@ export function useMarkdownSource(
|
||||
forgeReferencePattern?: string;
|
||||
external?: boolean;
|
||||
} = {},
|
||||
/** Identity of this occurrence's image acquisitions. Defaults to one per call site. */
|
||||
occurrence?: string,
|
||||
) {
|
||||
const occurrenceKey = useId();
|
||||
const ownOccurrence = useId();
|
||||
const occurrenceKey = occurrence ?? ownOccurrence;
|
||||
const { commandNames, forgeReferencePattern, external } = links;
|
||||
const prepared = useMemo(
|
||||
() =>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { memo, useMemo, useState, type ComponentProps } from "react";
|
||||
import { memo, useId, useMemo, useRef, useState, type ComponentProps } from "react";
|
||||
import { EnrichedMarkdownText, type LinkPressEvent } from "react-native-enriched-markdown";
|
||||
import { withUnistyles } from "react-native-unistyles";
|
||||
import {
|
||||
@@ -21,10 +21,15 @@ import { LinkMenu, useLinkMenuLongPress, type LinkMenuSubject } from "./link-men
|
||||
import { WEB_RENDERERS } from "./renderers";
|
||||
import { createMarkdownStyles } from "./styles";
|
||||
import { PENDING_MARKDOWN_IMAGE } from "./source";
|
||||
import { splitStreamingMarkdown } from "./streaming";
|
||||
import {
|
||||
createStreamingMarkdownSplitter,
|
||||
createStreamingMarkdownStabilizer,
|
||||
PENDING_MARKDOWN_LINK,
|
||||
} from "./streaming";
|
||||
import { MarkdownStreamingContext } from "./streaming-context";
|
||||
import { useMarkdownSource, type MarkdownImageContext } from "./images";
|
||||
|
||||
import { MermaidFence, MermaidStreamingContext, splitMermaidFences } from "./fence/mermaid";
|
||||
import { MermaidFence, splitMermaidFences } from "./fence/mermaid";
|
||||
|
||||
const ThemedMarkdown = withUnistyles(EnrichedMarkdownText);
|
||||
const MD4C_FLAGS = { latexMath: false, hardSoftBreaks: true, admonitions: true };
|
||||
@@ -68,24 +73,60 @@ export interface MarkdownRendererProps extends MarkdownImageContext {
|
||||
|
||||
/** All Markdown surfaces share the same engine and source adaptation. */
|
||||
export const MarkdownRenderer = memo(function MarkdownRenderer(props: MarkdownRendererProps) {
|
||||
const streaming = !isWeb && !!props.streaming;
|
||||
// Only completed lines affect block closure. Do not run mdast on every reveal frame.
|
||||
const completeLines = streaming ? props.text.slice(0, props.text.lastIndexOf("\n") + 1) : "";
|
||||
const boundary = useMemo(
|
||||
() => splitStreamingMarkdown(completeLines, true).head.length,
|
||||
[completeLines],
|
||||
);
|
||||
const [split] = useState(createStreamingMarkdownSplitter);
|
||||
const [stabilizeTail] = useState(() => createStreamingMarkdownStabilizer().stabilize);
|
||||
// Head and tail are one message: an image keeps its acquisition when its block moves into the head.
|
||||
const imageOccurrence = useId();
|
||||
const Part = props.agentCommands ? CommandMarkdownPart : MarkdownPart;
|
||||
if (!streaming || boundary === 0) return <Part {...props} />;
|
||||
const { head, tail } = props.streaming ? split(props.text) : { head: [], tail: "" };
|
||||
// Without a head, the whole message is the first part.
|
||||
const parts =
|
||||
head.length === 0
|
||||
? [{ text: props.text, streaming: props.streaming }]
|
||||
: head.map((text) => ({ text, streaming: false }));
|
||||
const stableTail = head.length === 0 ? "" : stabilizeTail(tail);
|
||||
// The first part stays mounted from the first streamed frame to the completed message, so
|
||||
// completion and every boundary move re-render it instead of replacing it. That needs the same
|
||||
// children shape in every render: the parts, then the tail slot. Sealed head parts keep their
|
||||
// text, so they do not render again. A part is keyed by where it starts in the message, which
|
||||
// never changes while it streams.
|
||||
let partStart = 0;
|
||||
return (
|
||||
<MarkdownBlockStack>
|
||||
<Part {...props} text={props.text.slice(0, boundary)} />
|
||||
<Part {...props} text={props.text.slice(boundary)} />
|
||||
{parts.map((part) => {
|
||||
const start = partStart;
|
||||
partStart += part.text.length;
|
||||
return (
|
||||
<Part
|
||||
key={start}
|
||||
{...props}
|
||||
text={part.text}
|
||||
streaming={part.streaming}
|
||||
imageOccurrence={imageOccurrence}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
{stableTail.trim().length > 0 ? (
|
||||
<Part
|
||||
key="tail"
|
||||
{...props}
|
||||
text={stableTail}
|
||||
streaming
|
||||
preStabilized
|
||||
imageOccurrence={imageOccurrence}
|
||||
/>
|
||||
) : null}
|
||||
</MarkdownBlockStack>
|
||||
);
|
||||
});
|
||||
|
||||
const CommandMarkdownPart = memo(function CommandMarkdownPart(props: MarkdownRendererProps) {
|
||||
interface MarkdownPartProps extends MarkdownRendererProps {
|
||||
preStabilized?: boolean;
|
||||
/** Identity of the message's image acquisitions, shared by its parts. */
|
||||
imageOccurrence: string;
|
||||
}
|
||||
|
||||
const CommandMarkdownPart = memo(function CommandMarkdownPart(props: MarkdownPartProps) {
|
||||
const commandHints = useAgentCommandHints();
|
||||
return <MarkdownPart {...props} commandHints={commandHints} />;
|
||||
});
|
||||
@@ -108,12 +149,14 @@ const MarkdownPart = memo(function MarkdownPart({
|
||||
muted = false,
|
||||
selectable = true,
|
||||
streaming = false,
|
||||
preStabilized = false,
|
||||
onLinkPress,
|
||||
agentCommands: _agentCommands,
|
||||
external = false,
|
||||
commandHints = null,
|
||||
imageOccurrence,
|
||||
...imageContext
|
||||
}: MarkdownRendererProps & { commandHints?: CommandHints | null }) {
|
||||
}: MarkdownPartProps & { commandHints?: CommandHints | null }) {
|
||||
const environment = useAssistantFileLinkEnvironment();
|
||||
const actions = useAssistantFileLinkActions();
|
||||
const workspaceForgeShorthand = useForgeShorthand();
|
||||
@@ -125,8 +168,13 @@ const MarkdownPart = memo(function MarkdownPart({
|
||||
(environmentMatchesHost && environment.client?.readFile
|
||||
? { readFile: environment.client.readFile.bind(environment.client) }
|
||||
: undefined);
|
||||
const stabilizerRef = useRef<ReturnType<typeof createStreamingMarkdownStabilizer> | null>(null);
|
||||
const stabilizedText = useMemo(() => {
|
||||
if (!streaming || preStabilized) return text;
|
||||
return (stabilizerRef.current ??= createStreamingMarkdownStabilizer()).stabilize(text);
|
||||
}, [streaming, preStabilized, text]);
|
||||
const { markdown, imageSources, linkRecognition, linkSource } = useMarkdownSource(
|
||||
text,
|
||||
stabilizedText,
|
||||
{
|
||||
workspaceRoot: environmentMatchesHost ? environment.workspaceRoot : undefined,
|
||||
serverId: environment.serverId,
|
||||
@@ -138,10 +186,12 @@ const MarkdownPart = memo(function MarkdownPart({
|
||||
forgeReferencePattern: forgeShorthand?.pattern,
|
||||
external,
|
||||
},
|
||||
imageOccurrence,
|
||||
);
|
||||
const [image, setImage] = useState<ImageLightboxSource | null>(null);
|
||||
// What a link is, for pressing it and for its menu alike.
|
||||
const readLink = useStableEvent(({ url, sourceType }: LinkPressEvent): ReadMarkdownLink => {
|
||||
if (streaming && url === PENDING_MARKDOWN_LINK) return { kind: "inert" };
|
||||
if (external) {
|
||||
// The parser still autolinks bare http, www and email text; only https links open.
|
||||
const safe = pluginOverviewUrl(url);
|
||||
@@ -188,7 +238,7 @@ const MarkdownPart = memo(function MarkdownPart({
|
||||
[markdown],
|
||||
);
|
||||
return (
|
||||
<MermaidStreamingContext.Provider value={streaming}>
|
||||
<MarkdownStreamingContext.Provider value={streaming}>
|
||||
<LinkMenu describeLink={describeLink}>
|
||||
<MarkdownBlockStack imageSources={imageSources}>
|
||||
{segments.map((segment) =>
|
||||
@@ -217,6 +267,6 @@ const MarkdownPart = memo(function MarkdownPart({
|
||||
</MarkdownBlockStack>
|
||||
</LinkMenu>
|
||||
{image ? <AttachmentLightbox source={image} onClose={closeImage} /> : null}
|
||||
</MermaidStreamingContext.Provider>
|
||||
</MarkdownStreamingContext.Provider>
|
||||
);
|
||||
});
|
||||
|
||||
@@ -4,6 +4,8 @@ import { createRoot, type Root } from "react-dom/client";
|
||||
import { afterEach, beforeEach, expect, it } from "vitest";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
import { WEB_RENDERERS } from "./renderers.web";
|
||||
import { PENDING_MARKDOWN_LINK } from "./streaming";
|
||||
import { MarkdownStreamingContext } from "./streaming-context";
|
||||
|
||||
const Link = WEB_RENDERERS.link;
|
||||
const LINK_TEXT = "src/index.ts";
|
||||
@@ -59,3 +61,32 @@ it("leaves an authored link wrapped", () => {
|
||||
const anchor = renderAnchor({ url: "https://example.test/doc", sourceType: "markdown" });
|
||||
expect(anchor.hasAttribute("data-paseo-markdown-recognized-link")).toBe(false);
|
||||
});
|
||||
|
||||
const PENDING_LINK = { url: PENDING_MARKDOWN_LINK, sourceType: "markdown" as const };
|
||||
const PENDING_ANCHOR_PROPS = {
|
||||
href: PENDING_MARKDOWN_LINK,
|
||||
style: { color: "rgb(56, 189, 248)" },
|
||||
};
|
||||
|
||||
it("renders a pending streaming link as a non-interactive link-styled span", () => {
|
||||
if (!Link) {
|
||||
throw new Error("Expected a web link renderer");
|
||||
}
|
||||
const client = new QueryClient();
|
||||
act(() =>
|
||||
root.render(
|
||||
<QueryClientProvider client={client}>
|
||||
<MarkdownStreamingContext.Provider value={true}>
|
||||
<Link link={PENDING_LINK} anchorProps={PENDING_ANCHOR_PROPS}>
|
||||
Paseo docs
|
||||
</Link>
|
||||
</MarkdownStreamingContext.Provider>
|
||||
</QueryClientProvider>,
|
||||
),
|
||||
);
|
||||
expect(container.querySelector("a")).toBeNull();
|
||||
const span = container.querySelector("span");
|
||||
expect(span?.textContent).toBe("Paseo docs");
|
||||
expect(span?.style.color).toBe("rgb(56, 189, 248)");
|
||||
expect(span?.style.overflowWrap).toBe("anywhere");
|
||||
});
|
||||
|
||||
@@ -2,6 +2,7 @@ import { Text } from "react-native";
|
||||
import {
|
||||
forwardRef,
|
||||
useCallback,
|
||||
useContext,
|
||||
useMemo,
|
||||
useState,
|
||||
type ComponentProps,
|
||||
@@ -23,6 +24,8 @@ import { useStableEvent } from "@/hooks/use-stable-event";
|
||||
import { useOpenLinkMenu } from "./link-menu";
|
||||
import { MermaidFence } from "./fence/mermaid";
|
||||
import { isRecognizedLink, markdownLinkSource } from "./source";
|
||||
import { PENDING_MARKDOWN_LINK } from "./streaming";
|
||||
import { MarkdownStreamingContext } from "./streaming-context";
|
||||
import { WebBlockquote } from "./quote-block.web";
|
||||
|
||||
const ThemedCodeBlock = withUnistyles(HighlightedCodeBlock);
|
||||
@@ -42,7 +45,26 @@ function WebCodeBlock({ code, language }: CodeBlockRendererProps) {
|
||||
// The library styles links inline, so a stylesheet :hover rule cannot underline them.
|
||||
const LINK_HOVER_STYLE = { textDecoration: "underline" } as const;
|
||||
|
||||
function WebLink({ link, anchorProps, children }: LinkRendererProps) {
|
||||
function PendingWebLink({
|
||||
anchorProps,
|
||||
children,
|
||||
}: Pick<LinkRendererProps, "anchorProps" | "children">) {
|
||||
const style = useMemo(
|
||||
() => ({ ...anchorProps.style, overflowWrap: "anywhere" as const }),
|
||||
[anchorProps.style],
|
||||
);
|
||||
return <span style={style}>{children}</span>;
|
||||
}
|
||||
|
||||
function WebLink(props: LinkRendererProps) {
|
||||
const streaming = useContext(MarkdownStreamingContext);
|
||||
if (streaming && props.link.url === PENDING_MARKDOWN_LINK) {
|
||||
return <PendingWebLink anchorProps={props.anchorProps}>{props.children}</PendingWebLink>;
|
||||
}
|
||||
return <InteractiveWebLink {...props} />;
|
||||
}
|
||||
|
||||
function InteractiveWebLink({ link, anchorProps, children }: LinkRendererProps) {
|
||||
const forgeShorthand = useForgeShorthand();
|
||||
// A forge reference like `#12` carries its web URL so hover, copy and new-tab opens work.
|
||||
const forgeUrl = link.sourceType === "text" ? forgeShorthand?.resolve(link.url) : null;
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
import { createContext } from "react";
|
||||
|
||||
/** Shared streaming state for Markdown sub-renderers (pending links, Mermaid diagrams). */
|
||||
export const MarkdownStreamingContext = createContext(false);
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,15 +1,76 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { parseMarkdown } from "react-native-enriched-markdown/src/web/parseMarkdown";
|
||||
import { recognizeTextLinks } from "react-native-enriched-markdown/src/web/recognizeTextLinks";
|
||||
import type { ASTNode } from "react-native-enriched-markdown/src/web/types";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { splitStreamingMarkdown } from "./streaming";
|
||||
import { prepareMarkdownSource } from "./source";
|
||||
import { fromMarkdown } from "mdast-util-from-markdown";
|
||||
import {
|
||||
createStreamingMarkdownSplitter,
|
||||
createStreamingMarkdownStabilizer,
|
||||
PENDING_MARKDOWN_LINK,
|
||||
stabilizeStreamingMarkdown,
|
||||
} from "./streaming";
|
||||
|
||||
describe("native streaming Markdown", () => {
|
||||
it("keeps completed messages together for selection", () => {
|
||||
const text = "First.\n\nSecond.\n\nThird.";
|
||||
expect(splitStreamingMarkdown(text, false)).toEqual({ head: text, tail: "" });
|
||||
});
|
||||
/** Feeds each prefix of `source` to one splitter, the way a streaming message grows. */
|
||||
function streamSplits(source: string, step = 1) {
|
||||
const split = createStreamingMarkdownSplitter();
|
||||
const splits: { text: string; parts: string[]; head: string; tail: string }[] = [];
|
||||
for (let end = 0; end <= source.length; end += step) {
|
||||
const text = source.slice(0, end);
|
||||
const { head, tail } = split(text);
|
||||
splits.push({ text, parts: head, head: head.join(""), tail });
|
||||
}
|
||||
return splits;
|
||||
}
|
||||
|
||||
function splitOnce(text: string) {
|
||||
const { head, tail } = createStreamingMarkdownSplitter()(text);
|
||||
return { head: head.join(""), tail };
|
||||
}
|
||||
|
||||
// The shape of a long agent reply: sections of headings, nested lists, task lists, quotes,
|
||||
// links, literal brackets, entities, inline code, images and tables.
|
||||
function longReply(sections: number): string {
|
||||
return Array.from(
|
||||
{ length: sections },
|
||||
(_, index) => `## ${index + 1}. Area ${index}
|
||||
|
||||
The list batches the pending text node only when the [text](https://example.com/${index}) changed. Q&A, \`a && b\` and [x] stay literal.
|
||||
|
||||
- Keep **first paint** under \`${index}ms\`
|
||||
- Measured with \`performance.mark("${index}")\`
|
||||
- Avoid layout thrash during \`scroll\`
|
||||
|
||||
1. Snapshot the state
|
||||
1. Freeze everything before the last blank line
|
||||
2. Commit once per frame
|
||||
|
||||
> **Note:** the anchor invalidates a frozen prefix.
|
||||
>
|
||||
> > Nested: the parser measures the tool output.
|
||||
|
||||
#### Checklist
|
||||
|
||||
- [x] Baseline captured on desktop
|
||||
- [ ] Baseline captured on Android
|
||||
|
||||
| Step | Result |
|
||||
| --- | --- |
|
||||
| ${index} | Ready |
|
||||
|
||||

|
||||
|
||||
---
|
||||
|
||||
`,
|
||||
).join("");
|
||||
}
|
||||
|
||||
describe("streaming Markdown split", () => {
|
||||
it("commits earlier blocks only after the following source line is complete", () => {
|
||||
expect(splitStreamingMarkdown("First.\n\nSecond", true).head).toBe("");
|
||||
expect(splitStreamingMarkdown("First.\n\nSecond\n", true)).toEqual({
|
||||
expect(splitOnce("First.\n\nSecond").head).toBe("");
|
||||
expect(splitOnce("First.\n\nSecond\n")).toEqual({
|
||||
head: "First.\n\n",
|
||||
tail: "Second\n",
|
||||
});
|
||||
@@ -24,48 +85,462 @@ describe("native streaming Markdown", () => {
|
||||
"| A | B |\n| --- | --- |\n| x | y |\n",
|
||||
"```ts\nconst value = 1;\n```\n",
|
||||
"<div>\nbody\n\nmore\n</div>\n",
|
||||
"[label]\n\n[label]: /target\n",
|
||||
"[label]: /target\n\n[label]\n",
|
||||
"- [x] done\n- [ ] open\n",
|
||||
])("keeps an unfinished construct together: %s", (block) => {
|
||||
const prefix = "Introduction.\n\n";
|
||||
const source = prefix + block;
|
||||
const split = splitStreamingMarkdown(source, true);
|
||||
const split = splitOnce(source);
|
||||
expect(split.head.length).toBeLessThanOrEqual(prefix.length);
|
||||
expect(split.head + split.tail).toBe(source);
|
||||
let previous = 0;
|
||||
for (let end = 0; end <= source.length; end++) {
|
||||
const prefixSplit = splitStreamingMarkdown(source.slice(0, end), true);
|
||||
expect(prefixSplit.head.length, `prefix ${end} of ${source}`).toBeGreaterThanOrEqual(
|
||||
previous,
|
||||
);
|
||||
previous = prefixSplit.head.length;
|
||||
for (const { text, head } of streamSplits(source)) {
|
||||
expect(head.length, `prefix ${text.length} of ${source}`).toBeGreaterThanOrEqual(previous);
|
||||
previous = head.length;
|
||||
}
|
||||
});
|
||||
it("preserves the indentation that controls fence content and list continuation", () => {
|
||||
for (const tail of [" ```ts\n const n = 1;\n", " - first\n continued\n"]) {
|
||||
expect(splitStreamingMarkdown(`Intro.\n\n${tail}`, true)).toEqual({
|
||||
head: "Intro.\n\n",
|
||||
tail,
|
||||
});
|
||||
expect(splitOnce(`Intro.\n\n${tail}`)).toEqual({ head: "Intro.\n\n", tail });
|
||||
}
|
||||
});
|
||||
it("keeps unresolved references and HTML in the tail even after later blocks", () => {
|
||||
for (const block of ["[label]", "[label]: /target", "<div>body</div>"]) {
|
||||
expect(splitStreamingMarkdown(`Intro.\n\n${block}\n\nNext.\n\nEnd.\n`, true).head).toBe(
|
||||
"Intro.\n\n",
|
||||
it("commits task lists and literal brackets once a later block starts", () => {
|
||||
for (const block of ["- [x] done\n- [ ] open", "Read [the notes] first.", "Q&A: `a && b`"]) {
|
||||
expect(splitOnce(`Intro.\n\n${block}\n\nNext.\n\nEnd.\n`).head).toBe(
|
||||
`Intro.\n\n${block}\n\nNext.\n\n`,
|
||||
);
|
||||
}
|
||||
});
|
||||
it("never retreats or loses source across every prefix of mixed Markdown", () => {
|
||||
it("keeps HTML and everything after it in the tail", () => {
|
||||
expect(splitOnce("Intro.\n\n<div>body</div>\n\nNext.\n\nEnd.\n").head).toBe("Intro.\n\n");
|
||||
});
|
||||
it("renders a message with a link definition as one document", () => {
|
||||
const source = "See [label].\n\nNext.\n\n[label]: /target\n\nEnd.\n";
|
||||
const definitionEnd = source.indexOf("/target\n") + "/target\n".length;
|
||||
for (const { text, head } of streamSplits(source)) {
|
||||
if (text.length >= definitionEnd) expect(head, `prefix ${text.length}`).toBe("");
|
||||
}
|
||||
// Before the definition arrives, the reference is plain text and its block commits.
|
||||
expect(splitOnce(source.slice(0, source.indexOf("[label]:"))).head).toBe("See [label].\n\n");
|
||||
expect(splitOnce("[label]: /target\n\nSee [label].\n\nEnd.\n").head).toBe("");
|
||||
});
|
||||
it("never loses source and only retreats for a definition across every prefix", () => {
|
||||
const fixture = readFileSync(new URL("./streaming.fixture.md", import.meta.url), "utf8");
|
||||
let previous = 0;
|
||||
for (let end = 0; end <= fixture.length; end++) {
|
||||
const text = fixture.slice(0, end);
|
||||
const { head, tail } = splitStreamingMarkdown(text, true);
|
||||
expect(head.length, `prefix ${end}`).toBeGreaterThanOrEqual(previous);
|
||||
for (const { text, head, tail } of streamSplits(fixture)) {
|
||||
expect(head.length, `prefix ${text.length}`).toBeGreaterThanOrEqual(previous);
|
||||
expect(head + tail).toBe(text);
|
||||
previous = head.length;
|
||||
}
|
||||
expect(previous).toBeGreaterThan(1000);
|
||||
}, 15000);
|
||||
it("keeps the tail to the last block across a long reply", () => {
|
||||
const reply = longReply(40);
|
||||
const split = createStreamingMarkdownSplitter();
|
||||
let longestTail = 0;
|
||||
for (let end = reply.indexOf("\n") + 1; end > 0; end = reply.indexOf("\n", end) + 1) {
|
||||
longestTail = Math.max(longestTail, split(reply.slice(0, end)).tail.length);
|
||||
}
|
||||
// The longest block is one section's task list or table, not the reply.
|
||||
expect(reply.length).toBeGreaterThan(20_000);
|
||||
expect(longestTail).toBeLessThan(400);
|
||||
}, 15000);
|
||||
it("re-renders a bounded amount of the head per frame however long the reply grows", () => {
|
||||
const reply = longReply(40);
|
||||
let previous: string[] = [];
|
||||
let mostInOneFrame = 0;
|
||||
for (const { parts, head } of streamSplits(reply, 7)) {
|
||||
const rerendered = parts
|
||||
.filter((part, index) => part !== previous[index])
|
||||
.reduce((sum, part) => sum + part.length, 0);
|
||||
mostInOneFrame = Math.max(mostInOneFrame, rerendered);
|
||||
expect(head).toBe(reply.slice(0, head.length));
|
||||
previous = parts;
|
||||
}
|
||||
expect(previous.length).toBeGreaterThan(5);
|
||||
// One sealed part's worth plus a block, not the reply.
|
||||
expect(mostInOneFrame).toBeLessThan(2500);
|
||||
}, 15000);
|
||||
it("finds the same split incrementally as from scratch at every prefix", () => {
|
||||
const fixture = readFileSync(new URL("./streaming.fixture.md", import.meta.url), "utf8");
|
||||
for (const source of [
|
||||
fixture,
|
||||
longReply(3),
|
||||
"Intro.\n\n[label]\n\nNext.\n\n[label]: /target\n\nEnd.\n",
|
||||
"Intro.\n\n- one\n\n continued\n\nAfter.\n\n<div>\nbody\n</div>\n\nTail.\n",
|
||||
]) {
|
||||
for (const { text, head } of streamSplits(source)) {
|
||||
expect(head, `prefix ${text.length}`).toBe(splitOnce(text).head);
|
||||
}
|
||||
}
|
||||
}, 30000);
|
||||
it("parses only the source after the settled head", () => {
|
||||
const parsed: string[] = [];
|
||||
const split = createStreamingMarkdownSplitter((completeLines) => {
|
||||
parsed.push(completeLines);
|
||||
return fromMarkdown(completeLines);
|
||||
});
|
||||
const blocks = Array.from({ length: 200 }, (_, index) => `Paragraph ${index}.\n\n`).join("");
|
||||
split(blocks);
|
||||
parsed.length = 0;
|
||||
expect(split(`${blocks}Next.\n`).head.join("")).toBe(blocks);
|
||||
expect(parsed).toEqual(["Paragraph 199.\n\nNext.\n"]);
|
||||
parsed.length = 0;
|
||||
split(`${blocks}Next.\nmore`);
|
||||
expect(parsed).toEqual([]);
|
||||
});
|
||||
it("starts over when the source no longer extends what it split", () => {
|
||||
const split = createStreamingMarkdownSplitter();
|
||||
expect(split("First.\n\nSecond.\n").head).toEqual(["First.\n\n"]);
|
||||
expect(split("Other.\n\nText.\n").head).toEqual(["Other.\n\n"]);
|
||||
expect(split("[a]: /b\n\nOther.\n").head).toEqual([]);
|
||||
expect(split("Fresh.\n\nText.\n").head).toEqual(["Fresh.\n\n"]);
|
||||
});
|
||||
});
|
||||
|
||||
const STREAM_FLAGS = { latexMath: false, hardSoftBreaks: true, admonitions: true };
|
||||
|
||||
function collectNodes(node: ASTNode, result: ASTNode[] = []): ASTNode[] {
|
||||
result.push(node);
|
||||
node.children?.forEach((child) => collectNodes(child, result));
|
||||
return result;
|
||||
}
|
||||
|
||||
describe("stabilizeStreamingMarkdown — inline code spans", () => {
|
||||
it("withholds dangling opening backticks and closes open inline code spans", () => {
|
||||
expect(stabilizeStreamingMarkdown("Use `")).toBe("Use ");
|
||||
expect(stabilizeStreamingMarkdown("Use ``")).toBe("Use ");
|
||||
expect(stabilizeStreamingMarkdown("Use `inlineblock")).toBe("Use `inlineblock`");
|
||||
expect(stabilizeStreamingMarkdown("Use `inlineblock`")).toBe("Use `inlineblock`");
|
||||
expect(stabilizeStreamingMarkdown("Use ``foo ` bar")).toBe("Use ``foo ` bar``");
|
||||
expect(stabilizeStreamingMarkdown("Use ``foo ` bar`")).toBe("Use ``foo ` bar``");
|
||||
expect(stabilizeStreamingMarkdown("Use ``foo ` bar``")).toBe("Use ``foo ` bar``");
|
||||
});
|
||||
|
||||
it("ignores escaped backticks and leaves closed spans alone", () => {
|
||||
expect(stabilizeStreamingMarkdown("Use \\`literal")).toBe("Use \\`literal");
|
||||
expect(stabilizeStreamingMarkdown("Use `a` and `b")).toBe("Use `a` and `b`");
|
||||
});
|
||||
|
||||
it("lets inline-code file paths resolve before the closing backtick arrives", async () => {
|
||||
const stabilized = stabilizeStreamingMarkdown(
|
||||
"Open `packages/app/src/components/markdown/renderer.tsx",
|
||||
);
|
||||
expect(stabilized).toBe("Open `packages/app/src/components/markdown/renderer.tsx`");
|
||||
const prepared = prepareMarkdownSource(stabilized, "/repo");
|
||||
const ast = recognizeTextLinks(
|
||||
await parseMarkdown(prepared.render(), STREAM_FLAGS),
|
||||
prepared.linkRecognition.text,
|
||||
prepared.linkRecognition.inlineCode,
|
||||
);
|
||||
const links = collectNodes(ast).filter((node) => node.type === "Link");
|
||||
expect(links.map((link) => link.attributes?.url)).toEqual([
|
||||
"packages/app/src/components/markdown/renderer.tsx",
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("stabilizeStreamingMarkdown — emphasis, strong, and strikethrough", () => {
|
||||
it("withholds bare openers, closes across spaces, and strips partial closers", async () => {
|
||||
expect(stabilizeStreamingMarkdown("This is *")).toBe("This is ");
|
||||
expect(stabilizeStreamingMarkdown("This is **")).toBe("This is ");
|
||||
expect(stabilizeStreamingMarkdown("This is ***")).toBe("This is ");
|
||||
expect(stabilizeStreamingMarkdown("This is ~~")).toBe("This is ");
|
||||
expect(stabilizeStreamingMarkdown("This is _")).toBe("This is ");
|
||||
expect(stabilizeStreamingMarkdown("This is __")).toBe("This is ");
|
||||
|
||||
expect(stabilizeStreamingMarkdown("This is **bold")).toBe("This is **bold**");
|
||||
expect(stabilizeStreamingMarkdown("This is **very ")).toBe("This is **very** ");
|
||||
expect(stabilizeStreamingMarkdown("This is **bold*")).toBe("This is **bold**");
|
||||
expect(stabilizeStreamingMarkdown("This is **bold**")).toBe("This is **bold**");
|
||||
expect(stabilizeStreamingMarkdown("This is ***bold italic*")).toBe("This is ***bold italic***");
|
||||
expect(stabilizeStreamingMarkdown("This is ***bold italic**")).toBe(
|
||||
"This is ***bold italic***",
|
||||
);
|
||||
expect(stabilizeStreamingMarkdown("This is ~~strike~")).toBe("This is ~~strike~~");
|
||||
expect(stabilizeStreamingMarkdown("This is __under_")).toBe("This is __under__");
|
||||
|
||||
// Trailing space inside open bold must still parse as Strong in MD4C.
|
||||
const ast = await parseMarkdown(stabilizeStreamingMarkdown("This is **very "), STREAM_FLAGS);
|
||||
expect(collectNodes(ast).some((node) => node.type === "Strong")).toBe(true);
|
||||
});
|
||||
|
||||
it("closes nested inline constructs in LIFO order", () => {
|
||||
expect(stabilizeStreamingMarkdown("**bold and *italic")).toBe("**bold and *italic***");
|
||||
expect(stabilizeStreamingMarkdown("**bold and *italic* more")).toBe(
|
||||
"**bold and *italic* more**",
|
||||
);
|
||||
expect(stabilizeStreamingMarkdown("**using `code")).toBe("**using `code`**");
|
||||
expect(stabilizeStreamingMarkdown("**using `")).toBe("**using** ");
|
||||
expect(stabilizeStreamingMarkdown("**see [the `config")).toBe(
|
||||
`**see [the \`config\`](${PENDING_MARKDOWN_LINK})**`,
|
||||
);
|
||||
});
|
||||
|
||||
it("does not misread intraword underscores, multiplication, or single tildes", () => {
|
||||
expect(stabilizeStreamingMarkdown("Use my_var_name")).toBe("Use my_var_name");
|
||||
expect(stabilizeStreamingMarkdown("Use my_")).toBe("Use my_");
|
||||
expect(stabilizeStreamingMarkdown("Result is 2 * 3")).toBe("Result is 2 * 3");
|
||||
expect(stabilizeStreamingMarkdown("Result is 2*3")).toBe("Result is 2*3");
|
||||
expect(stabilizeStreamingMarkdown("Takes ~50ms in ~/dev")).toBe("Takes ~50ms in ~/dev");
|
||||
expect(stabilizeStreamingMarkdown("Escaped \\*text")).toBe("Escaped \\*text");
|
||||
});
|
||||
});
|
||||
|
||||
describe("stabilizeStreamingMarkdown — links, images, and reference definitions", () => {
|
||||
it("stabilizes links across every streaming stage without leaking URLs", () => {
|
||||
expect(stabilizeStreamingMarkdown("See [")).toBe("See ");
|
||||
expect(stabilizeStreamingMarkdown("See [Paseo docs")).toBe(
|
||||
`See [Paseo docs](${PENDING_MARKDOWN_LINK})`,
|
||||
);
|
||||
expect(stabilizeStreamingMarkdown("See [Paseo docs]")).toBe(
|
||||
`See [Paseo docs](${PENDING_MARKDOWN_LINK})`,
|
||||
);
|
||||
expect(stabilizeStreamingMarkdown("See [Paseo docs](")).toBe(
|
||||
`See [Paseo docs](${PENDING_MARKDOWN_LINK})`,
|
||||
);
|
||||
expect(stabilizeStreamingMarkdown("See [Paseo docs](https://example.com/very/long/url")).toBe(
|
||||
`See [Paseo docs](${PENDING_MARKDOWN_LINK})`,
|
||||
);
|
||||
expect(stabilizeStreamingMarkdown("See [Paseo docs][ref")).toBe(
|
||||
`See [Paseo docs](${PENDING_MARKDOWN_LINK})`,
|
||||
);
|
||||
expect(stabilizeStreamingMarkdown("See [Paseo docs](https://example.com/doc)")).toBe(
|
||||
"See [Paseo docs](https://example.com/doc)",
|
||||
);
|
||||
});
|
||||
|
||||
it("handles nested formatting, balanced parens in URLs, identifier brackets, and CJK", () => {
|
||||
expect(stabilizeStreamingMarkdown("See [`src/foo.ts")).toBe(
|
||||
`See [\`src/foo.ts\`](${PENDING_MARKDOWN_LINK})`,
|
||||
);
|
||||
expect(
|
||||
stabilizeStreamingMarkdown("See [Wiki](https://en.wikipedia.org/wiki/Function_(math"),
|
||||
).toBe(`See [Wiki](${PENDING_MARKDOWN_LINK})`);
|
||||
expect(
|
||||
stabilizeStreamingMarkdown("See [Wiki](https://en.wikipedia.org/wiki/Function_(math))"),
|
||||
).toBe("See [Wiki](https://en.wikipedia.org/wiki/Function_(math))");
|
||||
expect(stabilizeStreamingMarkdown("Check arr[0")).toBe("Check arr[0");
|
||||
expect(stabilizeStreamingMarkdown("Check arr[0]")).toBe("Check arr[0]");
|
||||
expect(stabilizeStreamingMarkdown("查看[文档")).toBe(`查看[文档](${PENDING_MARKDOWN_LINK})`);
|
||||
expect(stabilizeStreamingMarkdown("See [TODO] next")).toBe("See [TODO] next");
|
||||
});
|
||||
|
||||
it("withholds incomplete images and reference definitions without affecting exclamation marks", () => {
|
||||
expect(stabilizeStreamingMarkdown("Done!")).toBe("Done!");
|
||||
expect(stabilizeStreamingMarkdown("See ).toBe("See ");
|
||||
expect(stabilizeStreamingMarkdown("See ")).toBe(
|
||||
"See ",
|
||||
);
|
||||
expect(stabilizeStreamingMarkdown("Intro.\n\n[ref]: https://example.com")).toBe("Intro.\n\n");
|
||||
});
|
||||
});
|
||||
|
||||
describe("stabilizeStreamingMarkdown — headings, lists, blockquotes, and admonitions", () => {
|
||||
it("withholds unfinished ATX headings and empty heading formatting", () => {
|
||||
expect(stabilizeStreamingMarkdown("#")).toBe("");
|
||||
expect(stabilizeStreamingMarkdown("##")).toBe("");
|
||||
expect(stabilizeStreamingMarkdown("## ")).toBe("");
|
||||
expect(stabilizeStreamingMarkdown("## **")).toBe("");
|
||||
expect(stabilizeStreamingMarkdown("## Title")).toBe("## Title");
|
||||
expect(stabilizeStreamingMarkdown("## **Title")).toBe("## **Title**");
|
||||
expect(stabilizeStreamingMarkdown("#hashtag")).toBe("#hashtag");
|
||||
});
|
||||
|
||||
it("prevents a bullet list dash after a paragraph from flashing as a Setext H2", async () => {
|
||||
for (const prefix of ["Steps:\n-", "Steps:\n- ", "Steps:\n--", "Steps:\n="]) {
|
||||
const stabilized = stabilizeStreamingMarkdown(prefix);
|
||||
expect(stabilized).toBe("Steps:\n");
|
||||
const ast = await parseMarkdown(stabilized, STREAM_FLAGS);
|
||||
expect(ast.children?.map((node) => node.type)).toEqual(["Paragraph"]);
|
||||
}
|
||||
const listAst = await parseMarkdown(
|
||||
stabilizeStreamingMarkdown("Steps:\n- First"),
|
||||
STREAM_FLAGS,
|
||||
);
|
||||
expect(listAst.children?.map((node) => node.type)).toEqual(["Paragraph", "UnorderedList"]);
|
||||
});
|
||||
|
||||
it("withholds empty list markers, task checkboxes, thematic break prefixes, and bare ***", () => {
|
||||
for (const input of [
|
||||
"-",
|
||||
"- ",
|
||||
"- [",
|
||||
"- [ ",
|
||||
"- [x",
|
||||
"- [ ]",
|
||||
"- [ ] ",
|
||||
"1",
|
||||
"1.",
|
||||
"1. ",
|
||||
"1. **",
|
||||
"--",
|
||||
"***",
|
||||
"___",
|
||||
]) {
|
||||
expect(stabilizeStreamingMarkdown(input), input).toBe("");
|
||||
}
|
||||
expect(stabilizeStreamingMarkdown("- Item")).toBe("- Item");
|
||||
expect(stabilizeStreamingMarkdown("- [ ] Task")).toBe("- [ ] Task");
|
||||
expect(stabilizeStreamingMarkdown("- [Link")).toBe(`- [Link](${PENDING_MARKDOWN_LINK})`);
|
||||
expect(stabilizeStreamingMarkdown("1. **First")).toBe("1. **First**");
|
||||
expect(stabilizeStreamingMarkdown("100 items")).toBe("100 items");
|
||||
});
|
||||
|
||||
it("withholds empty new blockquotes and incomplete admonitions until body text arrives", () => {
|
||||
for (const input of [
|
||||
">",
|
||||
"> ",
|
||||
"> [",
|
||||
"> [!",
|
||||
"> [!NOTE",
|
||||
"> [!NOTE]",
|
||||
"> [!NOTE]\n",
|
||||
"> [!NOTE]\n> ",
|
||||
]) {
|
||||
expect(stabilizeStreamingMarkdown(input), input).toBe("");
|
||||
}
|
||||
expect(stabilizeStreamingMarkdown("> [Click")).toBe(`> [Click](${PENDING_MARKDOWN_LINK})`);
|
||||
expect(stabilizeStreamingMarkdown("> [!NOTE]\n> Body")).toBe("> [!NOTE]\n> Body");
|
||||
expect(stabilizeStreamingMarkdown("> Line 1\n>")).toBe("> Line 1\n>");
|
||||
});
|
||||
});
|
||||
|
||||
describe("stabilizeStreamingMarkdown — fences, tables, HTML, and full prefix stability", () => {
|
||||
it("withholds opening fences until content arrives and partial closing fences in quotes/lists", () => {
|
||||
for (const input of [
|
||||
"Intro\n\n`",
|
||||
"Intro\n\n``",
|
||||
"Intro\n\n```",
|
||||
"Intro\n\n```mermaid",
|
||||
"Intro\n\n```mermaid\n",
|
||||
]) {
|
||||
expect(stabilizeStreamingMarkdown(input), input).toBe("Intro\n\n");
|
||||
}
|
||||
expect(stabilizeStreamingMarkdown("Intro\n\n```mermaid\ngraph LR")).toBe(
|
||||
"Intro\n\n```mermaid\ngraph LR",
|
||||
);
|
||||
// Inline syntax inside open code fences stays verbatim.
|
||||
expect(stabilizeStreamingMarkdown("```ts\nconst s = `template **not bold")).toBe(
|
||||
"```ts\nconst s = `template **not bold",
|
||||
);
|
||||
// Partial closing fences inside top-level, blockquotes, and deep list items.
|
||||
expect(stabilizeStreamingMarkdown("```ts\nconst a = 1;\n``")).toBe("```ts\nconst a = 1;\n");
|
||||
expect(stabilizeStreamingMarkdown("```ts\nconst a = 1;\n`` ")).toBe("```ts\nconst a = 1;\n`` ");
|
||||
expect(stabilizeStreamingMarkdown("> ```ts\n> const a = 1;\n> ``")).toBe(
|
||||
"> ```ts\n> const a = 1;\n",
|
||||
);
|
||||
expect(stabilizeStreamingMarkdown("10. ```ts\n const a = 1;\n ``")).toBe(
|
||||
"10. ```ts\n const a = 1;\n",
|
||||
);
|
||||
});
|
||||
|
||||
it("withholds unconfirmed table headers, partial separators, and incomplete body rows", () => {
|
||||
expect(stabilizeStreamingMarkdown("Intro\n\n| A | B |")).toBe("Intro\n\n");
|
||||
expect(stabilizeStreamingMarkdown("Intro\n\n| A | B |\n| --- |")).toBe("Intro\n\n");
|
||||
expect(stabilizeStreamingMarkdown("Intro\n\n| A | B |\n| --- | --- |")).toBe(
|
||||
"Intro\n\n| A | B |\n| --- | --- |",
|
||||
);
|
||||
expect(stabilizeStreamingMarkdown("Intro\n\n| A | B |\n| --- | --- |\n| 1 | t")).toBe(
|
||||
"Intro\n\n| A | B |\n| --- | --- |\n",
|
||||
);
|
||||
expect(stabilizeStreamingMarkdown("Intro\n\n| A | B |\n| --- | --- |\n| 1 | 2 |")).toBe(
|
||||
"Intro\n\n| A | B |\n| --- | --- |\n| 1 | 2 |",
|
||||
);
|
||||
// Non-table pipe text falls through once line 2 is not a separator.
|
||||
expect(stabilizeStreamingMarkdown("| bitwise\nnot a table")).toBe("| bitwise\nnot a table");
|
||||
});
|
||||
|
||||
it("withholds incomplete HTML tags and comments without touching math comparisons", () => {
|
||||
expect(stabilizeStreamingMarkdown("Before<br")).toBe("Before");
|
||||
expect(stabilizeStreamingMarkdown("Before<!-- hidden")).toBe("Before");
|
||||
expect(stabilizeStreamingMarkdown("a < b && c > d")).toBe("a < b && c > d");
|
||||
expect(stabilizeStreamingMarkdown("List<string")).toBe("List<string");
|
||||
});
|
||||
|
||||
it("stays idempotent and produces jump-free MD4C ASTs across every character prefix", async () => {
|
||||
const sample = [
|
||||
"## Summary of `MarkdownRenderer`",
|
||||
"",
|
||||
"Check **important details** and [Paseo docs](https://example.com/very/long/documentation) plus `packages/app/src/components/markdown/renderer.tsx`.",
|
||||
"",
|
||||
"Here are the next steps:",
|
||||
"- First item with ~~old~~ and *new*",
|
||||
"- [ ] Task item",
|
||||
"",
|
||||
"1. **Ordered** item",
|
||||
"",
|
||||
"> [!NOTE]",
|
||||
"> Helpful callout body.",
|
||||
"",
|
||||
"```mermaid",
|
||||
"graph LR",
|
||||
"A --> B",
|
||||
"```",
|
||||
"",
|
||||
"| Stage | Result |",
|
||||
"| --- | --- |",
|
||||
"| Step 1 | Ready |",
|
||||
"| Step 2 | Done |",
|
||||
"",
|
||||
"Finished.",
|
||||
].join("\n");
|
||||
|
||||
const incremental = createStreamingMarkdownStabilizer();
|
||||
for (let end = 0; end <= sample.length; end++) {
|
||||
const prefix = sample.slice(0, end);
|
||||
const stabilized = stabilizeStreamingMarkdown(prefix);
|
||||
// Incremental checkpoint must match cold stabilization on every prefix.
|
||||
expect(incremental.stabilize(prefix), `incremental parity at ${end}`).toBe(stabilized);
|
||||
// Idempotence invariant
|
||||
expect(stabilizeStreamingMarkdown(stabilized), `idempotent at ${end}`).toBe(stabilized);
|
||||
|
||||
if (!stabilized) continue;
|
||||
const ast = await parseMarkdown(
|
||||
prepareMarkdownSource(stabilized, "/repo").render(),
|
||||
STREAM_FLAGS,
|
||||
);
|
||||
const nodes = collectNodes(ast);
|
||||
|
||||
for (const node of nodes) {
|
||||
// Never emit empty headings, blockquotes, admonitions, code blocks, or list items.
|
||||
if (
|
||||
node.type === "Heading" ||
|
||||
node.type === "Blockquote" ||
|
||||
node.type === "Admonition" ||
|
||||
node.type === "CodeBlock" ||
|
||||
node.type === "ListItem"
|
||||
) {
|
||||
expect(
|
||||
(node.children?.length ?? 0) > 0,
|
||||
`non-empty ${node.type} at prefix ${end}: ${JSON.stringify(stabilized)}`,
|
||||
).toBe(true);
|
||||
}
|
||||
// Mermaid opening fence never flashes as a partial-language non-mermaid CodeBlock.
|
||||
if (node.type === "CodeBlock") {
|
||||
expect(node.attributes?.language, `code language at ${end}`).toBe("mermaid");
|
||||
}
|
||||
// "Here are the next steps:" never explodes into a Setext heading.
|
||||
if (node.type === "Heading") {
|
||||
const text = collectNodes(node)
|
||||
.map((child) => child.content ?? "")
|
||||
.join("");
|
||||
expect(text, `no setext explosion at ${end}`).not.toContain("Here are the next steps");
|
||||
}
|
||||
// Raw Markdown delimiters and URLs never leak into prose text nodes.
|
||||
if (node.type === "Text") {
|
||||
const content = node.content ?? "";
|
||||
expect(content, `no raw ** at ${end}`).not.toContain("**");
|
||||
expect(content, `no raw backtick at ${end}`).not.toContain("`");
|
||||
expect(content, `no raw URL leak at ${end}`).not.toContain("https://example.com");
|
||||
expect(content, `no raw table pipe at ${end}`).not.toContain("| Stage");
|
||||
expect(content, `no raw admonition tag at ${end}`).not.toContain("[!NOTE");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Switching to an unrelated or shorter message resets the checkpoint cleanly.
|
||||
expect(incremental.stabilize("```ts\nconst x = 1;\n`")).toBe("```ts\nconst x = 1;\n");
|
||||
expect(incremental.stabilize("Plain\nCheck `inline")).toBe("Plain\nCheck `inline`");
|
||||
}, 20000);
|
||||
});
|
||||
|
||||
@@ -1,32 +1,104 @@
|
||||
import { fromMarkdown } from "mdast-util-from-markdown";
|
||||
import { gfmTable } from "micromark-extension-gfm-table";
|
||||
import { gfmTableFromMarkdown } from "mdast-util-gfm-table";
|
||||
import type { Nodes } from "mdast";
|
||||
import type { Nodes, Root } from "mdast";
|
||||
|
||||
// A later definition can resolve even a currently plain-text shortcut reference.
|
||||
// Keep its entire containing block, and all definitions, in the shared tail.
|
||||
// HTML normalization likewise needs the complete enclosing source.
|
||||
function needsDocumentContext(node: Nodes): boolean {
|
||||
if (node.type === "html" || node.type === "definition") return true;
|
||||
if (node.type === "linkReference" || node.type === "imageReference") return true;
|
||||
if (node.type === "text" && node.value.includes("[")) return true;
|
||||
return "children" in node && node.children.some(needsDocumentContext);
|
||||
export {
|
||||
createStreamingMarkdownStabilizer,
|
||||
PENDING_MARKDOWN_LINK,
|
||||
stabilizeStreamingMarkdown,
|
||||
} from "./streaming-stabilize";
|
||||
|
||||
export interface StreamingMarkdownSplit {
|
||||
/**
|
||||
* Closed blocks, which render the same whatever arrives later. Only the last part grows; a part
|
||||
* that reached `HEAD_PART_LENGTH` never changes again.
|
||||
*/
|
||||
head: string[];
|
||||
/** The last block and the unfinished line. */
|
||||
tail: string;
|
||||
}
|
||||
|
||||
/** The last parsed block and unfinished line are mutable; earlier blocks are closed. */
|
||||
export function splitStreamingMarkdown(text: string, streaming: boolean) {
|
||||
if (!streaming) return { head: text, tail: "" };
|
||||
const completeLines = text.slice(0, text.lastIndexOf("\n") + 1);
|
||||
const tree = fromMarkdown(completeLines, {
|
||||
// Each completed block re-renders the head part it lands in. Sealing parts at this length keeps
|
||||
// that work bounded as the reply grows, with a few views for a long reply.
|
||||
const HEAD_PART_LENGTH = 2000;
|
||||
|
||||
export type StreamingMarkdownParser = (completeLines: string) => Root;
|
||||
|
||||
const parseBlocks: StreamingMarkdownParser = (completeLines) =>
|
||||
fromMarkdown(completeLines, {
|
||||
extensions: [gfmTable()],
|
||||
mdastExtensions: [gfmTableFromMarkdown()],
|
||||
});
|
||||
|
||||
// HTML normalization needs the complete enclosing source, so HTML and every block after it
|
||||
// stay in the tail.
|
||||
function needsDocumentContext(node: Nodes): boolean {
|
||||
if (node.type === "html") return true;
|
||||
return "children" in node && node.children.some(needsDocumentContext);
|
||||
}
|
||||
|
||||
// A definition can turn `[label]` anywhere in the message into a link, including in blocks that
|
||||
// already closed. mdast only creates a reference for a label that is defined.
|
||||
function hasDefinition(node: Nodes): boolean {
|
||||
if (node.type === "definition") return true;
|
||||
return "children" in node && node.children.some(hasDefinition);
|
||||
}
|
||||
|
||||
/**
|
||||
* Splits one growing message into head parts that stay fixed and a tail that changes with each
|
||||
* reveal frame. Create one per streaming message.
|
||||
*
|
||||
* Only completed lines can close a block, so the boundary moves when a line completes. Blocks
|
||||
* before the boundary are closed and need no document context, so each line parses only the
|
||||
* source after the boundary, and the work per line stays bounded by the last block. A message with
|
||||
* a link definition renders as one document, the way it will when it completes.
|
||||
*/
|
||||
export function createStreamingMarkdownSplitter(
|
||||
parse: StreamingMarkdownParser = parseBlocks,
|
||||
): (text: string) => StreamingMarkdownSplit {
|
||||
let completeLines = "";
|
||||
let boundary = 0;
|
||||
for (let index = 0; index < tree.children.length - 1; index++) {
|
||||
if (needsDocumentContext(tree.children[index])) break;
|
||||
// mdast starts some nodes after their indentation; the next parser needs it too.
|
||||
const nextStart = tree.children[index + 1].position!.start.offset!;
|
||||
boundary = text.lastIndexOf("\n", nextStart - 1) + 1;
|
||||
let partStarts = [0];
|
||||
let hasDefinitions = false;
|
||||
|
||||
function advance(lines: string) {
|
||||
if (lines === completeLines) return;
|
||||
if (!lines.startsWith(completeLines)) {
|
||||
// Not an append: nothing settled so far is known to hold.
|
||||
boundary = 0;
|
||||
partStarts = [0];
|
||||
hasDefinitions = false;
|
||||
}
|
||||
completeLines = lines;
|
||||
if (hasDefinitions) return;
|
||||
const open = lines.slice(boundary);
|
||||
const tree = parse(open);
|
||||
if (tree.children.some(hasDefinition)) {
|
||||
hasDefinitions = true;
|
||||
boundary = 0;
|
||||
partStarts = [0];
|
||||
return;
|
||||
}
|
||||
let settled = 0;
|
||||
for (let index = 0; index < tree.children.length - 1; index++) {
|
||||
if (needsDocumentContext(tree.children[index])) break;
|
||||
// mdast starts some nodes after their indentation; the next parser needs it too.
|
||||
const nextStart = tree.children[index + 1].position!.start.offset!;
|
||||
settled = open.lastIndexOf("\n", nextStart - 1) + 1;
|
||||
}
|
||||
if (settled === 0) return;
|
||||
if (boundary - partStarts[partStarts.length - 1] >= HEAD_PART_LENGTH) partStarts.push(boundary);
|
||||
boundary += settled;
|
||||
}
|
||||
return { head: text.slice(0, boundary), tail: text.slice(boundary) };
|
||||
|
||||
return (text) => {
|
||||
advance(text.slice(0, text.lastIndexOf("\n") + 1));
|
||||
if (boundary === 0) return { head: [], tail: text };
|
||||
const ends = [...partStarts.slice(1), boundary];
|
||||
return {
|
||||
head: partStarts.map((start, index) => text.slice(start, ends[index])),
|
||||
tail: text.slice(boundary),
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
@@ -137,9 +137,9 @@ export function PageTitle({
|
||||
descriptionTestID,
|
||||
}: PageTitleProps) {
|
||||
return (
|
||||
<View style={styles.titleBlock} testID={testID}>
|
||||
<View style={styles.titleBlock}>
|
||||
<View style={styles.titleRow}>
|
||||
<View style={styles.titleParts}>
|
||||
<View style={styles.titleParts} testID={testID}>
|
||||
{parent ? (
|
||||
<PressHighlight
|
||||
accessibilityRole="button"
|
||||
|
||||
@@ -19,7 +19,7 @@ import { AdaptiveModalSheet, type SheetHeader } from "@/components/adaptive-moda
|
||||
import { ComboboxItem } from "@/components/ui/combobox";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { CombinedModelSelector } from "@/components/combined-model-selector";
|
||||
import { HostStatusDotSlot } from "@/components/hosts/host-picker";
|
||||
import { HostStatusIcon } from "@/hosts/host-status-icon";
|
||||
import { createControlGeometry, type ControlSize } from "@/components/ui/control-geometry";
|
||||
import { Field, FormTextInput } from "@/components/ui/form-field";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
@@ -659,6 +659,13 @@ function ScheduleTargetFields({
|
||||
(input: SelectFieldRenderOptionInput<string>) => <ThinkingOptionItem {...input} />,
|
||||
[],
|
||||
);
|
||||
const hostTriggerLeading = useMemo(
|
||||
() =>
|
||||
state.selectedServerId ? (
|
||||
<HostStatusIcon serverId={state.selectedServerId} size="md" backdrop="surface2" />
|
||||
) : null,
|
||||
[state.selectedServerId],
|
||||
);
|
||||
const modelTriggerLeading = useMemo(
|
||||
() => <ProviderGlyph provider={state.selectedProvider} serverId={state.selectedServerId} />,
|
||||
[state.selectedProvider, state.selectedServerId],
|
||||
@@ -714,6 +721,7 @@ function ScheduleTargetFields({
|
||||
searchable={false}
|
||||
title="Host"
|
||||
size={controlSize}
|
||||
triggerLeading={hostTriggerLeading}
|
||||
triggerTestID="schedule-host-trigger"
|
||||
renderOption={renderHostOption}
|
||||
/>
|
||||
@@ -952,7 +960,16 @@ function HostOptionItem({
|
||||
active,
|
||||
onPress,
|
||||
}: SelectFieldRenderOptionInput<string>): ReactElement {
|
||||
const leadingSlot = useMemo(() => <HostStatusDotSlot serverId={option.value} />, [option.value]);
|
||||
const leadingSlot = useMemo(
|
||||
() => (
|
||||
<HostStatusIcon
|
||||
serverId={option.value}
|
||||
size="md"
|
||||
backdrop={active ? "surface1" : "surface0"}
|
||||
/>
|
||||
),
|
||||
[active, option.value],
|
||||
);
|
||||
|
||||
return (
|
||||
<ComboboxItem
|
||||
|
||||
@@ -6,6 +6,8 @@ import { SettingsRowHeader, type SettingsRowHintStatus } from "./row-header";
|
||||
|
||||
interface SettingsCollapsibleRowProps {
|
||||
label: string;
|
||||
/** An icon or status indicator shown before the label. */
|
||||
leading?: ReactNode;
|
||||
/** A line under the label explaining the group. */
|
||||
hint?: string;
|
||||
hintStatus?: SettingsRowHintStatus;
|
||||
@@ -13,6 +15,8 @@ interface SettingsCollapsibleRowProps {
|
||||
summary?: string;
|
||||
/** A control acting on the row's subject in place, such as a switch, before the chevron. */
|
||||
control?: ReactNode;
|
||||
/** Passive trailing element (such as a pill) shown before the chevron. */
|
||||
trailing?: ReactNode;
|
||||
/** Names the expand/collapse button for assistive tech when the label alone is not enough. */
|
||||
accessibilityLabel?: string;
|
||||
defaultExpanded?: boolean;
|
||||
@@ -28,10 +32,12 @@ interface SettingsCollapsibleRowProps {
|
||||
*/
|
||||
export function SettingsCollapsibleRow({
|
||||
label,
|
||||
leading,
|
||||
hint,
|
||||
hintStatus,
|
||||
summary,
|
||||
control,
|
||||
trailing,
|
||||
accessibilityLabel,
|
||||
defaultExpanded = false,
|
||||
testID,
|
||||
@@ -50,10 +56,12 @@ export function SettingsCollapsibleRow({
|
||||
<View testID={testID}>
|
||||
<SettingsRowHeader
|
||||
label={label}
|
||||
leading={leading}
|
||||
hint={hint}
|
||||
hintStatus={hintStatus}
|
||||
summary={summary}
|
||||
control={control}
|
||||
trailing={trailing}
|
||||
accessibilityLabel={accessibilityLabel}
|
||||
onPress={toggle}
|
||||
expanded={expanded}
|
||||
|
||||
@@ -36,6 +36,8 @@ export interface SettingsRowHeaderProps {
|
||||
summary?: string;
|
||||
/** An icon drawn directly before the summary text, such as a provider glyph beside a model name. */
|
||||
summaryLeading?: ReactNode;
|
||||
/** Passive trailing element (such as a status pill) shown before the chevron; lets presses pass through to the row. */
|
||||
trailing?: ReactNode;
|
||||
onPress: () => void;
|
||||
disabled?: boolean;
|
||||
/** Turns the chevron down, for a row whose children are revealed in place. */
|
||||
@@ -75,6 +77,7 @@ export function SettingsRowHeader({
|
||||
hintStatus,
|
||||
summary,
|
||||
summaryLeading,
|
||||
trailing,
|
||||
onPress,
|
||||
disabled,
|
||||
expanded = false,
|
||||
@@ -135,6 +138,14 @@ export function SettingsRowHeader({
|
||||
<ControlSizeProvider size={layout.controlSize}>{control}</ControlSizeProvider>
|
||||
</View>
|
||||
) : null}
|
||||
{trailing ? (
|
||||
<View
|
||||
style={[styles.trailingAccessory, styles.passThrough]}
|
||||
{...HIDDEN_FROM_ASSISTIVE_TECH}
|
||||
>
|
||||
{trailing}
|
||||
</View>
|
||||
) : null}
|
||||
<RowTrailing
|
||||
hinted={hinted}
|
||||
external={external}
|
||||
@@ -250,6 +261,10 @@ const styles = StyleSheet.create((theme) => ({
|
||||
control: {
|
||||
marginRight: theme.spacing[3],
|
||||
},
|
||||
trailingAccessory: {
|
||||
marginRight: theme.spacing[2],
|
||||
flexShrink: 0,
|
||||
},
|
||||
// The button under the row's content; it fills the row, padding included.
|
||||
pressTarget: {
|
||||
...StyleSheet.absoluteFill,
|
||||
|
||||
@@ -288,6 +288,7 @@ interface WorkspaceRowInnerProps {
|
||||
drag?: () => void;
|
||||
isDragging: boolean;
|
||||
isArchiving: boolean;
|
||||
showArchiveIndicator: boolean;
|
||||
isCreating?: boolean;
|
||||
dragHandleProps?: DraggableListDragHandleProps;
|
||||
menuController: ReturnType<typeof useContextMenu> | null;
|
||||
@@ -620,6 +621,7 @@ function WorkspaceRowRightGroup({
|
||||
isHovered,
|
||||
isTouchPlatform,
|
||||
isCreating,
|
||||
showArchiveIndicator,
|
||||
isSelectionMode,
|
||||
showShortcutBadge,
|
||||
shortcutNumber,
|
||||
@@ -642,6 +644,7 @@ function WorkspaceRowRightGroup({
|
||||
isHovered: boolean;
|
||||
isTouchPlatform: boolean;
|
||||
isCreating: boolean;
|
||||
showArchiveIndicator: boolean;
|
||||
isSelectionMode: boolean;
|
||||
showShortcutBadge: boolean;
|
||||
shortcutNumber: number | null;
|
||||
@@ -667,6 +670,7 @@ function WorkspaceRowRightGroup({
|
||||
trailingPresentation,
|
||||
showKebab: showKebabInSlot,
|
||||
showArchiveButton,
|
||||
showArchivingSpinner,
|
||||
showScrim,
|
||||
renderSlot,
|
||||
reserveSlotWidth,
|
||||
@@ -678,6 +682,7 @@ function WorkspaceRowRightGroup({
|
||||
isTouchPlatform,
|
||||
showShortcut,
|
||||
isSelectionMode,
|
||||
showArchiveIndicator,
|
||||
});
|
||||
const kebab = useOpenKebabMenuVisibility(showKebabInSlot);
|
||||
|
||||
@@ -700,6 +705,7 @@ function WorkspaceRowRightGroup({
|
||||
scrimBackdrop={showScrim ? backdrop : undefined}
|
||||
workspaceKey={workspace.workspaceKey}
|
||||
onArchiveButtonPress={showArchiveButton ? onArchive : undefined}
|
||||
showArchiveIndicator={showArchivingSpinner}
|
||||
>
|
||||
{onArchive ? (
|
||||
<SidebarWorkspaceMenu
|
||||
@@ -1078,6 +1084,7 @@ function WorkspaceRowInner({
|
||||
drag,
|
||||
isDragging,
|
||||
isArchiving,
|
||||
showArchiveIndicator,
|
||||
isCreating = false,
|
||||
dragHandleProps,
|
||||
menuController,
|
||||
@@ -1139,6 +1146,7 @@ function WorkspaceRowInner({
|
||||
isDragging={isDragging}
|
||||
isEditingTitle={isEditingTitle}
|
||||
isSelectionMode={isSelectionMode}
|
||||
showArchiveIndicator={showArchiveIndicator}
|
||||
>
|
||||
{({ isHovered, contextMenuOpen, onContextMenuOpenChange, hoverHandlers }) => {
|
||||
const isDesktop = !isTouchPlatform;
|
||||
@@ -1206,8 +1214,9 @@ function WorkspaceRowInner({
|
||||
serviceSummary={serviceSummary}
|
||||
backdrop={backdrop}
|
||||
isHovered={isHovered}
|
||||
isLoading={isArchiving || isCreating}
|
||||
isLoading={isCreating}
|
||||
isCreating={isCreating}
|
||||
showArchiveIndicator={showArchiveIndicator}
|
||||
isSelectionMode={isSelectionMode}
|
||||
isBulkSelected={isBulkSelected}
|
||||
shortcutNumber={shortcutNumber}
|
||||
@@ -1221,6 +1230,7 @@ function WorkspaceRowInner({
|
||||
isHovered={isHovered}
|
||||
isTouchPlatform={isTouchPlatform}
|
||||
isCreating={isCreating}
|
||||
showArchiveIndicator={showArchiveIndicator}
|
||||
isSelectionMode={isSelectionMode}
|
||||
showShortcutBadge={showShortcutBadge}
|
||||
shortcutNumber={shortcutNumber}
|
||||
@@ -1307,6 +1317,8 @@ function WorkspaceRowWithMenu({
|
||||
});
|
||||
const isArchiving =
|
||||
workspace.archivingAt !== null || isHidingWorkspace || archiveController.isConfirming;
|
||||
const showArchiveIndicator =
|
||||
workspace.archivingAt !== null || archiveController.isShowingArchiveIndicator;
|
||||
|
||||
const handleArchive = useCallback(() => {
|
||||
if (isArchiving) {
|
||||
@@ -1365,11 +1377,12 @@ function WorkspaceRowWithMenu({
|
||||
drag={drag}
|
||||
isDragging={isDragging}
|
||||
isArchiving={isArchiving}
|
||||
showArchiveIndicator={showArchiveIndicator}
|
||||
isCreating={isCreating}
|
||||
dragHandleProps={dragHandleProps}
|
||||
menuController={null}
|
||||
archiveLabel={t("sidebar.workspace.actions.archive")}
|
||||
archiveStatus={isArchiving ? "pending" : "idle"}
|
||||
archiveStatus={showArchiveIndicator ? "pending" : "idle"}
|
||||
archivePendingLabel={t("sidebar.workspace.actions.archiving")}
|
||||
onSelectWorkspace={handleSelectWorkspace}
|
||||
onArchive={handleArchive}
|
||||
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
Settings,
|
||||
} from "lucide-react-native";
|
||||
import { withUnistyles } from "react-native-unistyles";
|
||||
import { HostStatusDotSlot } from "@/components/hosts/host-picker";
|
||||
import { HostStatusIcon } from "@/hosts/host-status-icon";
|
||||
import type { SidebarFooterAction } from "@/components/sidebar-footer-layout";
|
||||
import {
|
||||
DropdownMenu,
|
||||
@@ -232,7 +232,10 @@ function HostRow({
|
||||
() => onOpenHostSettings(serverId),
|
||||
[onOpenHostSettings, serverId],
|
||||
);
|
||||
const leading = useMemo(() => <HostStatusDotSlot serverId={serverId} />, [serverId]);
|
||||
const leading = useMemo(
|
||||
() => <HostStatusIcon serverId={serverId} size="sm" backdrop="surface1" />,
|
||||
[serverId],
|
||||
);
|
||||
return (
|
||||
<DropdownMenuItem
|
||||
testID={`sidebar-host-row-${serverId}`}
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
/**
|
||||
* @vitest-environment jsdom
|
||||
*/
|
||||
import { renderHook } from "@testing-library/react";
|
||||
import type { ReactNode } from "react";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { SidebarModelProvider, useSidebarModel } from "./sidebar-model";
|
||||
|
||||
function Provider({ children }: { children: ReactNode }) {
|
||||
return <SidebarModelProvider active>{children}</SidebarModelProvider>;
|
||||
}
|
||||
|
||||
describe("sidebar model", () => {
|
||||
// Every sidebar surface reads this model, so a new value re-renders the whole sidebar.
|
||||
it("keeps the model while a render changes none of its inputs", () => {
|
||||
const { result, rerender } = renderHook(() => useSidebarModel(), { wrapper: Provider });
|
||||
const previous = result.current;
|
||||
|
||||
rerender();
|
||||
|
||||
expect(result.current).toBe(previous);
|
||||
});
|
||||
});
|
||||
@@ -743,6 +743,8 @@ function StatusWorkspaceRowWithMenu({
|
||||
});
|
||||
const isArchiving =
|
||||
workspace.archivingAt !== null || isHidingWorkspace || archiveController.isConfirming;
|
||||
const showArchiveIndicator =
|
||||
workspace.archivingAt !== null || archiveController.isShowingArchiveIndicator;
|
||||
|
||||
const handleArchive = useCallback(() => {
|
||||
if (isArchiving) return;
|
||||
@@ -797,8 +799,9 @@ function StatusWorkspaceRowWithMenu({
|
||||
showShortcutBadge={showShortcutBadge}
|
||||
onPress={onPress}
|
||||
isArchiving={isArchiving}
|
||||
showArchiveIndicator={showArchiveIndicator}
|
||||
archiveLabel={t("sidebar.workspace.actions.archive")}
|
||||
archiveStatus={isArchiving ? "pending" : "idle"}
|
||||
archiveStatus={showArchiveIndicator ? "pending" : "idle"}
|
||||
archivePendingLabel={t("sidebar.workspace.actions.archiving")}
|
||||
onSelectWorkspace={handleSelectWorkspace}
|
||||
onArchive={handleArchive}
|
||||
@@ -832,6 +835,7 @@ interface StatusWorkspaceRowInnerProps {
|
||||
showShortcutBadge: boolean;
|
||||
onPress: () => void;
|
||||
isArchiving: boolean;
|
||||
showArchiveIndicator: boolean;
|
||||
archiveLabel?: string;
|
||||
archiveStatus?: "idle" | "pending" | "success";
|
||||
archivePendingLabel?: string;
|
||||
@@ -882,6 +886,7 @@ function StatusWorkspaceRowInnerContent({
|
||||
showShortcutBadge,
|
||||
onPress,
|
||||
isArchiving,
|
||||
showArchiveIndicator,
|
||||
archiveLabel,
|
||||
archiveStatus = "idle",
|
||||
archivePendingLabel,
|
||||
@@ -949,6 +954,7 @@ function StatusWorkspaceRowInnerContent({
|
||||
isDragging={isDragging}
|
||||
isEditingTitle={isEditingTitle}
|
||||
isSelectionMode={isSelectionMode}
|
||||
showArchiveIndicator={showArchiveIndicator}
|
||||
>
|
||||
{({ isHovered, contextMenuOpen, onContextMenuOpenChange, hoverHandlers }) => {
|
||||
const showShortcut = showShortcutBadge && shortcutNumber !== null;
|
||||
@@ -956,6 +962,7 @@ function StatusWorkspaceRowInnerContent({
|
||||
trailingPresentation,
|
||||
showKebab: showKebabInSlot,
|
||||
showArchiveButton,
|
||||
showArchivingSpinner,
|
||||
showScrim,
|
||||
renderSlot,
|
||||
reserveSlotWidth,
|
||||
@@ -967,6 +974,7 @@ function StatusWorkspaceRowInnerContent({
|
||||
isTouchPlatform,
|
||||
showShortcut,
|
||||
isSelectionMode,
|
||||
showArchiveIndicator,
|
||||
});
|
||||
const workspaceRowStyle = getStatusWorkspaceRowStyle({
|
||||
selected: rowSelected,
|
||||
@@ -1033,7 +1041,8 @@ function StatusWorkspaceRowInnerContent({
|
||||
serviceSummary={serviceSummary}
|
||||
backdrop={backdrop}
|
||||
isHovered={isHovered}
|
||||
isLoading={isArchiving}
|
||||
isLoading={false}
|
||||
showArchiveIndicator={showArchiveIndicator}
|
||||
isSelectionMode={isSelectionMode}
|
||||
isBulkSelected={isBulkSelected}
|
||||
shortcutNumber={shortcutNumber}
|
||||
@@ -1049,6 +1058,7 @@ function StatusWorkspaceRowInnerContent({
|
||||
trailingPresentation={trailingPresentation}
|
||||
showKebab={showKebabInSlot}
|
||||
showArchiveButton={showArchiveButton}
|
||||
showArchivingSpinner={showArchivingSpinner}
|
||||
showScrim={showScrim}
|
||||
reserveSlotWidth={reserveSlotWidth}
|
||||
isPinned={isPinned}
|
||||
@@ -1083,6 +1093,7 @@ function StatusWorkspaceActionSlot({
|
||||
trailingPresentation,
|
||||
showKebab,
|
||||
showArchiveButton,
|
||||
showArchivingSpinner,
|
||||
showScrim,
|
||||
reserveSlotWidth,
|
||||
isPinned,
|
||||
@@ -1105,6 +1116,7 @@ function StatusWorkspaceActionSlot({
|
||||
trailingPresentation: SidebarWorkspaceTrailingPresentation;
|
||||
showKebab: boolean;
|
||||
showArchiveButton: boolean;
|
||||
showArchivingSpinner: boolean;
|
||||
showScrim: boolean;
|
||||
reserveSlotWidth: boolean;
|
||||
isPinned?: boolean;
|
||||
@@ -1136,6 +1148,7 @@ function StatusWorkspaceActionSlot({
|
||||
scrimBackdrop={showScrim ? backdrop : undefined}
|
||||
workspaceKey={workspace.workspaceKey}
|
||||
onArchiveButtonPress={showArchiveButton ? onArchive : undefined}
|
||||
showArchiveIndicator={showArchivingSpinner}
|
||||
>
|
||||
{kebab.showKebab && onArchive ? (
|
||||
<SidebarWorkspaceMenu
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import { memo, useMemo, useCallback, useState, type ReactNode } from "react";
|
||||
import { Text, View, type ViewStyle } from "react-native";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { Check, CircleAlert, Folder, FolderGit2, Monitor } from "lucide-react-native";
|
||||
import { bySizing } from "@/components/ui/control-geometry";
|
||||
import { LoadingSpinner } from "@/components/ui/loading-spinner";
|
||||
import { ProjectStatusIndicator } from "@/components/sidebar/project-leading-visual";
|
||||
import type { SidebarSurfaceBackdrop } from "@/styles/surface-backdrop";
|
||||
import {
|
||||
@@ -44,15 +46,20 @@ const needsInputColorMapping = (theme: Theme) => ({
|
||||
const checkedIconMapping = (theme: Theme) => ({
|
||||
color: theme.colors.accentForeground,
|
||||
});
|
||||
const foregroundMutedColorMapping = (theme: Theme) => ({
|
||||
color: theme.colors.foregroundMuted,
|
||||
});
|
||||
|
||||
const ThemedCheck = withUnistyles(Check);
|
||||
const ThemedCircleAlert = withUnistyles(CircleAlert);
|
||||
const ThemedLoadingSpinner = withUnistyles(LoadingSpinner);
|
||||
|
||||
export function SidebarWorkspaceRowFrame({
|
||||
workspace,
|
||||
isDragging = false,
|
||||
isEditingTitle = false,
|
||||
isSelectionMode = false,
|
||||
showArchiveIndicator = false,
|
||||
children,
|
||||
}: {
|
||||
workspace: SidebarWorkspaceEntry;
|
||||
@@ -61,6 +68,7 @@ export function SidebarWorkspaceRowFrame({
|
||||
isEditingTitle?: boolean;
|
||||
/** Hover cards would cover neighbouring rows while the user clicks through a selection. */
|
||||
isSelectionMode?: boolean;
|
||||
showArchiveIndicator?: boolean;
|
||||
children: (input: {
|
||||
isHovered: boolean;
|
||||
contextMenuOpen: boolean;
|
||||
@@ -88,7 +96,7 @@ export function SidebarWorkspaceRowFrame({
|
||||
workspace={workspace}
|
||||
prHint={workspace.prHint}
|
||||
isDragging={isDragging}
|
||||
disabled={contextMenuOpen || isEditingTitle || isSelectionMode}
|
||||
disabled={contextMenuOpen || isEditingTitle || isSelectionMode || showArchiveIndicator}
|
||||
>
|
||||
{children({
|
||||
isHovered: isHovered && !contextMenuOpen && !isDragging && !isEditingTitle,
|
||||
@@ -110,6 +118,7 @@ export const SidebarWorkspaceRowContent = memo(function SidebarWorkspaceRowConte
|
||||
isHovered,
|
||||
isLoading,
|
||||
isCreating = false,
|
||||
showArchiveIndicator = false,
|
||||
isSelectionMode = false,
|
||||
isBulkSelected = false,
|
||||
shortcutNumber = null,
|
||||
@@ -129,6 +138,8 @@ export const SidebarWorkspaceRowContent = memo(function SidebarWorkspaceRowConte
|
||||
isHovered: boolean;
|
||||
isLoading: boolean;
|
||||
isCreating?: boolean;
|
||||
/** Dims the row's status, title, and metadata while keeping the trailing spinner crisp. */
|
||||
showArchiveIndicator?: boolean;
|
||||
isSelectionMode?: boolean;
|
||||
isBulkSelected?: boolean;
|
||||
shortcutNumber?: number | null;
|
||||
@@ -151,8 +162,17 @@ export const SidebarWorkspaceRowContent = memo(function SidebarWorkspaceRowConte
|
||||
styles.workspaceBranchText,
|
||||
(isHovered || isBulkSelected) && styles.workspaceBranchTextHovered,
|
||||
isCreating && styles.workspaceBranchTextCreating,
|
||||
showArchiveIndicator && styles.workspaceBranchTextArchiving,
|
||||
],
|
||||
[isHovered, isBulkSelected, isCreating],
|
||||
[isHovered, isBulkSelected, isCreating, showArchiveIndicator],
|
||||
);
|
||||
const leadingWrapperStyle = useMemo(
|
||||
() => [styles.leadingVisualWrapper, showArchiveIndicator && styles.archivingDimmed],
|
||||
[showArchiveIndicator],
|
||||
);
|
||||
const metaWrapperStyle = useMemo(
|
||||
() => (showArchiveIndicator ? styles.archivingDimmed : undefined),
|
||||
[showArchiveIndicator],
|
||||
);
|
||||
|
||||
let leadingVisual: ReactNode;
|
||||
@@ -186,7 +206,7 @@ export const SidebarWorkspaceRowContent = memo(function SidebarWorkspaceRowConte
|
||||
return (
|
||||
<View style={styles.workspaceRowContent}>
|
||||
<View style={styles.workspaceRowMain}>
|
||||
{leadingVisual}
|
||||
<View style={leadingWrapperStyle}>{leadingVisual}</View>
|
||||
<View style={styles.workspaceContentColumn}>
|
||||
<View style={styles.workspaceTitleRow}>
|
||||
{titleEditor ? (
|
||||
@@ -202,16 +222,18 @@ export const SidebarWorkspaceRowContent = memo(function SidebarWorkspaceRowConte
|
||||
)}
|
||||
<View style={sidebarWorkspaceRowStyles.rowRight}>{children}</View>
|
||||
</View>
|
||||
<WorkspaceMetaRow
|
||||
backdrop={backdrop}
|
||||
currentBranch={workspace.currentBranch}
|
||||
projectName={leadingProjectName}
|
||||
hostBadge={hostBadge ?? null}
|
||||
prHint={workspace.prHint}
|
||||
serviceSummary={serviceSummary}
|
||||
labels={labels}
|
||||
workspace={workspace}
|
||||
/>
|
||||
<View style={metaWrapperStyle}>
|
||||
<WorkspaceMetaRow
|
||||
backdrop={backdrop}
|
||||
currentBranch={workspace.currentBranch}
|
||||
projectName={leadingProjectName}
|
||||
hostBadge={hostBadge ?? null}
|
||||
prHint={workspace.prHint}
|
||||
serviceSummary={serviceSummary}
|
||||
labels={labels}
|
||||
workspace={workspace}
|
||||
/>
|
||||
</View>
|
||||
</View>
|
||||
</View>
|
||||
{!isSelectionMode && showShortcutBadge && shortcutNumber !== null ? (
|
||||
@@ -422,6 +444,7 @@ export function resolveTrailingActionVisibility({
|
||||
isTouchPlatform,
|
||||
showShortcut,
|
||||
isSelectionMode = false,
|
||||
showArchiveIndicator = false,
|
||||
}: {
|
||||
workspace: SidebarWorkspaceEntry;
|
||||
trailing: SidebarWorkspaceTrailing;
|
||||
@@ -430,20 +453,42 @@ export function resolveTrailingActionVisibility({
|
||||
isTouchPlatform: boolean;
|
||||
showShortcut: boolean;
|
||||
isSelectionMode?: boolean;
|
||||
showArchiveIndicator?: boolean;
|
||||
}): {
|
||||
trailingPresentation: SidebarWorkspaceTrailingPresentation;
|
||||
showKebab: boolean;
|
||||
showArchiveButton: boolean;
|
||||
showArchivingSpinner: boolean;
|
||||
showScrim: boolean;
|
||||
renderSlot: boolean;
|
||||
reserveSlotWidth: boolean;
|
||||
} {
|
||||
const hasTrailing = hasSidebarWorkspaceTrailing({ workspace, trailing });
|
||||
const allowRowActions = hasArchiveAction && !isSelectionMode;
|
||||
const showKebab = Boolean(allowRowActions && (isHovered || isTouchPlatform)) && !showShortcut;
|
||||
// Touch permanently replaces the stats with the menu. Only temporary shortcut hints
|
||||
// conceal content while retaining its width, so desktop rows do not shift.
|
||||
// Touch permanently replaces the stats with the menu. Only temporary shortcut hints and the
|
||||
// archiving spinner conceal content while retaining its width, so desktop rows do not shift.
|
||||
const hasContent = hasTrailing && !(allowRowActions && isTouchPlatform);
|
||||
// The slot only holds width for something that permanently sits in it. Trailing content
|
||||
// does; the kebab only does on touch, where there is no hover for it to appear on and so
|
||||
// no scrim to let it overlay the title. Keeping this invariant across archiving ensures the
|
||||
// title column never changes width.
|
||||
const reserveSlotWidth = hasContent || (allowRowActions && isTouchPlatform);
|
||||
|
||||
if (showArchiveIndicator) {
|
||||
return {
|
||||
trailingPresentation: hasContent ? "hidden" : "absent",
|
||||
showKebab: false,
|
||||
showArchiveButton: false,
|
||||
showArchivingSpinner: true,
|
||||
// On a pointer row without trailing content, scrim the title tail behind the spinner
|
||||
// using the row's current backdrop so the title never reflows.
|
||||
showScrim: !hasContent && !isTouchPlatform,
|
||||
renderSlot: true,
|
||||
reserveSlotWidth,
|
||||
};
|
||||
}
|
||||
|
||||
const showKebab = Boolean(allowRowActions && (isHovered || isTouchPlatform)) && !showShortcut;
|
||||
let trailingPresentation: SidebarWorkspaceTrailingPresentation = "absent";
|
||||
if (hasContent) trailingPresentation = showShortcut ? "hidden" : "visible";
|
||||
return {
|
||||
@@ -452,16 +497,13 @@ export function resolveTrailingActionVisibility({
|
||||
// One-click archive is a pointer affordance: on touch it would sit a few pixels from the
|
||||
// kebab and turn a miss into an archive.
|
||||
showArchiveButton: showKebab && isHovered && !isTouchPlatform,
|
||||
showArchivingSpinner: false,
|
||||
// The scrim paints the row's own hover background, so it can only be drawn on a hovered
|
||||
// row — over an unhovered one the gradient fades to the wrong color. That is also why
|
||||
// touch, which shows the kebab without ever hovering, never gets one.
|
||||
showScrim: showKebab && isHovered,
|
||||
renderSlot: allowRowActions || hasTrailing,
|
||||
// The slot only holds width for something that permanently sits in it. Trailing content
|
||||
// does; the kebab only does on touch, where there is no hover for it to appear on and so
|
||||
// no scrim to let it overlay the title. Everywhere else the width goes back to the title
|
||||
// and the kebab fades in over its tail.
|
||||
reserveSlotWidth: hasContent || (allowRowActions && isTouchPlatform),
|
||||
reserveSlotWidth,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -505,6 +547,7 @@ export function SidebarWorkspaceTrailingActionOverlay({
|
||||
scrimBackdrop,
|
||||
workspaceKey,
|
||||
onArchiveButtonPress,
|
||||
showArchiveIndicator = false,
|
||||
children,
|
||||
}: {
|
||||
visible: boolean;
|
||||
@@ -516,8 +559,36 @@ export function SidebarWorkspaceTrailingActionOverlay({
|
||||
* the scrim widens to cover it rather than the slot reserving its width.
|
||||
*/
|
||||
onArchiveButtonPress?: () => void;
|
||||
/** Replaces hover actions with a neutral spinner in the same trailing slot. */
|
||||
showArchiveIndicator?: boolean;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
if (showArchiveIndicator) {
|
||||
return (
|
||||
<>
|
||||
{scrimBackdrop ? (
|
||||
<TrailingActionScrim
|
||||
backdrop={scrimBackdrop}
|
||||
width={SCRIM_WIDTH}
|
||||
testID="sidebar-workspace-trailing-scrim"
|
||||
/>
|
||||
) : null}
|
||||
<View
|
||||
style={sidebarWorkspaceRowStyles.trailingActionOverlay}
|
||||
testID="workspace-archive-pending-indicator"
|
||||
>
|
||||
<View style={styles.archivingSpinnerSlot}>
|
||||
<ThemedLoadingSpinner
|
||||
size={14}
|
||||
uniProps={foregroundMutedColorMapping}
|
||||
accessibilityLabel={t("sidebar.workspace.actions.archiving")}
|
||||
/>
|
||||
</View>
|
||||
</View>
|
||||
</>
|
||||
);
|
||||
}
|
||||
if (!visible || !children) return null;
|
||||
return (
|
||||
<>
|
||||
@@ -554,6 +625,18 @@ const styles = StyleSheet.create((theme) => ({
|
||||
gap: theme.spacing[2],
|
||||
width: "100%",
|
||||
},
|
||||
leadingVisualWrapper: {
|
||||
flexShrink: 0,
|
||||
},
|
||||
archivingDimmed: {
|
||||
opacity: 0.55,
|
||||
},
|
||||
archivingSpinnerSlot: {
|
||||
width: 18,
|
||||
height: TITLE_LINE_HEIGHT,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
workspaceContentColumn: {
|
||||
flex: 1,
|
||||
minWidth: 0,
|
||||
@@ -641,6 +724,9 @@ const styles = StyleSheet.create((theme) => ({
|
||||
workspaceBranchTextHovered: {
|
||||
opacity: 1,
|
||||
},
|
||||
workspaceBranchTextArchiving: {
|
||||
opacity: 0.45,
|
||||
},
|
||||
statusDotNeedsInput: {
|
||||
backgroundColor: getStatusDotColor({ theme, bucket: "needs_input" }) ?? undefined,
|
||||
borderColor: theme.colors.surface0,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { getIndicatorSteps } from "@/components/indicator-motion/steps";
|
||||
import { STATUS_INDICATOR_FILLED_DOT_SIZE } from "@/utils/status-indicator-geometry";
|
||||
|
||||
// The running indicator is a status dot with a rotating ring around it, and the whole set of
|
||||
@@ -31,11 +32,11 @@ export const STATUS_RING_HEAD_OPACITY = 0.9;
|
||||
// already turning.
|
||||
export const STATUS_RING_PERIOD_MS = 900;
|
||||
|
||||
// The quarter takes thirty positions a second, not one per display refresh. A window is redrawn
|
||||
// every time the ring moves, so a ring that moves with the display holds the whole window at the
|
||||
// display's rate for as long as an agent runs. Each position is one the smooth turn passes through,
|
||||
// 1.2 px further along a 12 px ring.
|
||||
export const STATUS_RING_STEPS = 27;
|
||||
// The quarter takes thirty positions a second, not one per display refresh: 27 per turn, on the
|
||||
// indicators' step grid. A window is redrawn every time the ring moves, so a ring that moves with
|
||||
// the display holds the whole window at the display's rate for as long as an agent runs. Each
|
||||
// position is one the smooth turn passes through, 1.2 px further along a 12 px ring.
|
||||
export const STATUS_RING_STEPS = getIndicatorSteps(STATUS_RING_PERIOD_MS);
|
||||
|
||||
/**
|
||||
* Re-anchors a corner status dot's offset for the ring that replaces it.
|
||||
|
||||
@@ -12,20 +12,22 @@ import { STATUS_RING_PERIOD_MS, STATUS_RING_STEPS } from "@/components/status-ri
|
||||
|
||||
// One rotation for every ring in the app, so a row that appears mid-flight lands in step with the
|
||||
// rings already turning.
|
||||
const rotation = sharedIndicatorClock.cycle(STATUS_RING_PERIOD_MS, STATUS_RING_STEPS).interpolate({
|
||||
inputRange: [0, STATUS_RING_PERIOD_MS],
|
||||
outputRange: ["0deg", "360deg"],
|
||||
});
|
||||
const rotation = sharedIndicatorClock
|
||||
.cycle(STATUS_RING_PERIOD_MS, { steps: STATUS_RING_STEPS })
|
||||
.interpolate({
|
||||
inputRange: [0, STATUS_RING_PERIOD_MS],
|
||||
outputRange: ["0deg", "360deg"],
|
||||
});
|
||||
const turning = { transform: [{ rotate: rotation }] };
|
||||
|
||||
/** Native running indicator. The native animation driver turns the quarter; see `clock.ts`. */
|
||||
export const StatusRing = memo(function StatusRing({ backdrop }: StatusRingProps) {
|
||||
const moving = useIndicatorMotion();
|
||||
useRunningClock(sharedIndicatorClock, moving);
|
||||
const motion = useIndicatorMotion();
|
||||
useRunningClock(sharedIndicatorClock, motion === "moving");
|
||||
|
||||
return (
|
||||
<StatusRingFrame backdrop={backdrop}>
|
||||
<Animated.View style={[rotatorStyles.rotator, moving && turning]}>
|
||||
<Animated.View style={[rotatorStyles.rotator, motion !== "resting" && turning]}>
|
||||
<View style={styles.arc} />
|
||||
</Animated.View>
|
||||
</StatusRingFrame>
|
||||
|
||||
@@ -23,7 +23,7 @@ const TURNING: IndicatorLoop = {
|
||||
|
||||
/** Web running indicator. The browser's compositor turns the quarter; see `loop.web.ts`. */
|
||||
export const StatusRing = memo(function StatusRing({ backdrop }: StatusRingProps) {
|
||||
const moving = useIndicatorMotion();
|
||||
const moving = useIndicatorMotion() === "moving";
|
||||
const rotatorRef = useIndicatorLoop(moving ? TURNING : null);
|
||||
|
||||
return (
|
||||
|
||||
@@ -34,8 +34,9 @@ const resting = DOTS.map((dot) => ({
|
||||
*/
|
||||
export function SyncedLoader(props: SyncedLoaderProps) {
|
||||
const layout = useSyncedLoaderLayout(props);
|
||||
const moving = useIndicatorMotion();
|
||||
const motion = moving ? blinking : resting;
|
||||
const motion = useIndicatorMotion();
|
||||
const dots = motion === "resting" ? resting : blinking;
|
||||
const moving = motion === "moving";
|
||||
|
||||
useEffect(() => {
|
||||
if (!moving) return;
|
||||
@@ -48,7 +49,7 @@ export function SyncedLoader(props: SyncedLoaderProps) {
|
||||
{DOTS.map((dot) => (
|
||||
<Animated.View
|
||||
key={dot}
|
||||
style={[layout.dots[dot], motion[dot]]}
|
||||
style={[layout.dots[dot], dots[dot]]}
|
||||
testID="synced-loader-dot"
|
||||
/>
|
||||
))}
|
||||
|
||||
@@ -36,7 +36,7 @@ const RESTING = DOTS.map(
|
||||
*/
|
||||
export function SyncedLoader(props: SyncedLoaderProps) {
|
||||
const layout = useSyncedLoaderLayout(props);
|
||||
const moving = useIndicatorMotion();
|
||||
const moving = useIndicatorMotion() === "moving";
|
||||
|
||||
return (
|
||||
<View style={layout.container} testID="synced-loader">
|
||||
|
||||
@@ -41,21 +41,28 @@ describe("synced loader step ticker", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
test("starts mid-cycle on the step the wall clock is on", () => {
|
||||
vi.setSystemTime(950 * 4 + 500);
|
||||
test("holds its step while no loader runs and continues from it", () => {
|
||||
const { ticker, published } = startRecordingTicker();
|
||||
|
||||
const stop = ticker.run();
|
||||
vi.advanceTimersByTime(140);
|
||||
vi.advanceTimersByTime(400);
|
||||
stop();
|
||||
vi.advanceTimersByTime(10_000);
|
||||
const stopAgain = ticker.run();
|
||||
vi.advanceTimersByTime(80);
|
||||
stopAgain();
|
||||
|
||||
// Stopped 83 ms into step 2, so step 3 comes 75 ms after the loader runs again.
|
||||
expect(published).toEqual([
|
||||
{ step: 3, atMs: 950 * 4 + 500 },
|
||||
{ step: 4, atMs: 950 * 4 + 634 },
|
||||
{ step: 0, atMs: 0 },
|
||||
{ step: 1, atMs: 159 },
|
||||
{ step: 2, atMs: 317 },
|
||||
{ step: 2, atMs: 10_400 },
|
||||
{ step: 3, atMs: 10_475 },
|
||||
]);
|
||||
});
|
||||
|
||||
test("catches up to the wall clock after a late wake-up instead of drifting", () => {
|
||||
test("catches up after a late wake-up instead of drifting", () => {
|
||||
const { ticker, published } = startRecordingTicker();
|
||||
|
||||
const stop = ticker.run();
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user