Compare commits

...
Author SHA1 Message Date
paseo-bot[bot]andHannah 533f504dfd fix(app): restore retained terminal focus on current main
Keep the workspace autofocus request pending until its renderer is ready,
while preserving overlay and explicitly selected control focus. Reconcile
with current overlay handling and keep the changelog in release format.
Give the button-focus regression a fixed browser clock origin so its pause
cannot precede the installed time.

Co-authored-by: Hannah <hannah@interagent.io>
2026-10-16 14:52:47 +02:00
Mohamed Boudra c1558d29ea fix(app): keep background workspaces hidden after reload (#7141)
* fix(app): preserve background workspace visibility after reload

Persist the background flag and reject workspace rows that predate it so the existing cache repair clears their workspace cursor and refreshes the baseline.

* test(app): make legacy workspace cache read paths explicit
2026-10-16 18:48:13 +07:00
Mohamed Boudra 8d9a7123ba feat(app): polish compact header, composer, and settings menu (#7129)
Header islands lose their filled background and shadow; the round tap
highlight stays. The floating header's fade now carries the icon contrast
the island fill used to give, so it stays solid through the header and
runs a longer tail into the content. The fade lives inside the overlay
because Android clips children that overhang their parent, and keeps
three gradient stops because Android rendered a four-stop version far
more transparent than specified.

Single-line header titles read one step larger. The compact composer
gets a soft drop shadow. The compact settings root groups App and Host
into islands of tiles, driven by breakpoint style values so desktop
keeps its plain list.
2026-10-16 18:05:11 +07:00
Mohamed Boudra 6017706cc1 fix(app): avoid restoring composer focus on touch navigation (#7130)
Limit implicit pane and remount focus replay to the existing fine-pointer policy. Fullscreen keeps one editor mounted, so touch navigation does not need the restoration introduced for the former portal handoff.
2026-10-16 17:27:06 +07:00
Mohamed Boudra 62ab2deb27 Run and watch workspace scripts from the phone header menu (#7122)
* feat(app): run and watch workspace scripts from the compact header menu

The compact header redesign dropped the mobile scripts button, so phones had
no way to run, stop, or restart workspace scripts. Scripts are now a page of
the ⋯ sheet: the root row shows what is running, tinted by health, and the ⋯
carries a dot while a running service is unhealthy. Desktop keeps its popover;
both surfaces share one set of script actions and one status model.

Script status also froze on native whenever the sidebar was closed and no
agent tab was viewed. DirectorySynchronizer releases its subscriptions,
including script_status_update, when nothing demands the directory, and the
workspace screen never demanded the workspace it shows. Web hid this because
the favicon sync holds demand for the whole session. The focused workspace now
holds directory demand, which also lets Restart's second half (start once the
daemon reports the script stopped) complete.

* perf(app): keep workspace script status live without syncing the directory

The focused workspace held full directory demand so the scripts menu saw
script_status_update on phones with the sidebar closed and no agent tab.
That fetched the host's agent and workspace lists on every focus and
streamed every agent and workspace update for the whole host.

Script status now has its own event subscription, which a workspace
screen can hold alone. It fetches the workspace's scripts once when the
subscription lands, because the subscription only carries changes.
Directory demand also holds it, so the sidebar and agent tabs see the
same updates as before.
2026-10-16 17:26:44 +07:00
48b310c8a2 Keep Android chat still when selecting text (#7131)
Android's scroll guard now reads the view's transform matrix, so React Native's inverted chat list (scale: -1, decomposed into a 180-degree rotation with positive scaleY) no longer scrolls on text focus or selection.

Closes #7125

Co-authored-by: luke <luopeihuan@gmail.com>
Co-authored-by: RoundRedDot <roundreddot@gmail.com>
2026-10-16 12:21:58 +02:00
5acfbb3777 Let Escape close plugin previews before stopping agents (#7110)
* fix(app): let Escape close an open popover before it interrupts the agent

The agent.interrupt shortcut listens on the window in the capture phase, so
it sees Escape before anything else. Registered overlays get first refusal
through dispatchTopWebOverlayKeyDown, but plugins cannot register, and draw
their floating panels with the Popover API instead. With such a panel open
and the composer focused while an agent runs, Escape closed the panel and
interrupted the agent in the same press.

While a popover is open, Escape is left to it and no app shortcut runs. A
second Escape, with nothing open, interrupts as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: RoundRedDot <roundreddot@gmail.com>

* test(app): cover Escape with a popover open through the shortcut path

The first test only checked hasOpenDomPopover and would still pass with the
guard removed from useKeyboardShortcuts. The check is now keyBelongsToDomPopover,
called by the hook, and a browser test drives it the way the app does: a
window capture listener for shortcuts, a popover closed by its own document
Escape listener, focus in a textarea. The first Escape closes the popover
with no interrupt; the second interrupts. Both new tests fail with the guard
removed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: RoundRedDot <roundreddot@gmail.com>

* test(app): exercise plugin Escape through the real composer

Keep the contributor fix and replace the substitute shortcut-listener test with an installed-plugin browser regression. The first Escape must close the preview without cancelling the turn; the second must cancel it.

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

* test(app): check dismissed model pickers leave the viewport

---------

Co-authored-by: luke <luopeihuan@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: RoundRedDot <roundreddot@gmail.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-10-16 09:14:10 +02:00
4117dce2d3 Fix local WAV transcription startup (#7103)
* fix(speech): complete local transcription providers

* test(speech): document lazy worker assumption

Co-authored-by: LauraGPT <18321252+LauraGPT@users.noreply.github.com>

---------

Co-authored-by: LauraGPT <lauragpt@users.noreply.github.com>
Co-authored-by: LauraGPT <18321252+LauraGPT@users.noreply.github.com>
2026-10-16 08:19:21 +02:00
paseo-bot[bot]andsuperheher 8388f16186 Keep Add Project keyboard selection visible (#7081)
* fix(app): scroll the Add Project results to the keyboard-selected row

The results list had no scroll ref, so ArrowUp/ArrowDown moved the selection off-screen; the autocomplete reveal math is now shared through useRevealActiveItem.

* test(app): verify the directory selected beyond the results viewport

Check scrolling in both directions and across wrapping, then confirm Enter opens the selected directory. The previous regression used an aria-selected attribute that result buttons do not render.

Co-authored-by: superheher <heh@vivaldi.net>

* test(app): verify scroll reveal through browser behavior

Keep pure offset checks and cover keyboard navigation, wrapping, and replacing search results in the real Add Project flow.

* fix(app): measure retained Add Project rows when revealing selection

* fix(app): measure scroll content through a native View reference

---------

Co-authored-by: superheher <heh@vivaldi.net>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-10-16 07:04:35 +02:00
paseo-bot[bot]anddbunk903 5c2a1552df fix(app): preserve number groups when rebinding navigation shortcuts (#7065)
Recording a digit for tab or workspace navigation replaced the existing
1–9 wildcard with one literal key. Preserve the group when capturing a
replacement and display its range after saving and reloading.

Adapted the number-group fix from getpaseo/paseo#5237, with independent
failing-first renderer reproduction and tab/workspace matcher coverage.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: dbunk903 <74584941+dbunk903@users.noreply.github.com>
2026-10-16 04:14:28 +02:00
e0de0fdf6f Read cached chats while other agents stream (#7074)
* perf(app): overlay pending replica rows on read instead of forcing persists

readRows flushed every pending change to storage, read, and retried
whenever the host revision moved. Every stream reducer flush (48 ms) and
every agent delta advanced that revision, so opening another agent or
workspace on a host with a streaming agent re-serialized the whole
pending batch per iteration and could spin until the stream paused.

Reads now run on the write queue, so no drained batch is mid-apply while
a read runs, and rows still pending in memory are overlaid for the
requested keys. A read never forces a persist and never waits for the
host to go quiet.

Persist retries after a storage failure back off exponentially (1 s to
60 s) and log the failure instead of re-serializing every second.

Before: one readAgent during a 200-commit stream cost 201 store reads and
200 forced persists; a permanently failing store was written 30 times in
30 s. After: 1 read, 0 persists; 5 writes in 30 s.

Fixes #4813
Refs #4814

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

* fix(app): log replica persist retry failures

---------

Co-authored-by: Ivan Malison <IvanMalison@gmail.com>
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: paseo-bot[bot] <paseo-bot[bot]@users.noreply.github.com>
2026-10-16 03:15:23 +02:00
8d424e039e Reduce rendering cost in long chats (#7052)
* perf(app): stop re-walking the timeline on every streamed delta

Every coalesced delta rebuilds the stream render model with the same
tail. The model re-sliced the tail at the history-window start on every
call, so the rendered tail was a fresh array per delta and every WeakMap
keyed on it (ordering, history split, turn timing, the layout history
cache, row revision) missed each time. Cache the slice by tail identity
and window start.

Turn timing then still walked the whole rendered tail per delta and
allocated a new assistant-timing Map, which the layout memo depends on.
Split the walk: the tail is walked once per tail identity and the head is
walked from the carried open turn per delta. The Map keeps its identity
while the head adds no completed turn.

Adds identity-contract tests and a vitest bench for the per-delta
pipeline. 200 deltas over a 2,000-item timeline, mean per run:
default mounted window 5.68ms -> 2.82ms, history fully revealed
16.95ms -> 1.81ms.

Fixes #4816

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

* perf(app): keep the stream view's per-delta work bounded by the head

The chat outline concatenated tail and head, reduced over the result in
the render body, and rebuilt jumpToPrompt on every delta even when the
outline was disabled, which is every native viewport. Memoize the tail's
contribution, scan only the head per delta, do nothing while disabled,
make jumpToPrompt a stable event so the rail's memo holds, and republish
the active prompt only when the index or reading position changes.

The view built a Set of every mounted id plus the live head per delta for
the outline's pending-jump check; key it on mounted history only and
treat live head rows as always mounted. Split plugin projection so a head
change does not re-project the tail, memoize the history-window boundary
lookup, and read the turn presentation's submission flag with some()
instead of allocating a filtered array.

Refs #4816

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

* test(app): confirm full history before measuring streaming

---------

Co-authored-by: Ivan Malison <IvanMalison@gmail.com>
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-10-16 01:15:40 +02:00
paseo-bot[bot]andIvan Pantic d9b874f9d0 Scroll chat with Page Up and Page Down after clicking messages (#7033)
* fix(app): focus chat feed when clicking message content

* test(app): wait for new chat output before checking scroll position

Co-authored-by: Ivan Pantic <panta@talentkit.io>

* test(app): capture the keyboard paging regression

* test(app): verify paged chat text stays in place

---------

Co-authored-by: Ivan Pantic <panta@talentkit.io>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-10-16 00:14:23 +02:00
f56c013928 Open configured terminals after worktree setup (#6999)
* fix(server): open worktree.terminals when a workspace is created on its own

runWorktreeSetupInBackground only opened the paseo.json worktree.terminals
when its caller passed runAutoTerminals, and only the fork-PR "allow setup"
handler did. workspace.create, the request the New Workspace screen sends,
ran worktree.setup and then skipped the terminals.

Both callers want the terminals, so the flag goes away: terminals follow a
successful setup on a newly created worktree. Reused worktrees stay excluded
by shouldBootstrap, and the agent setup continuation never reaches this
function, so nothing opens twice.

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

* test(server): run automatic terminal regressions in CI

Include workspace creation in the existing integration command, and append to the terminal marker so repeated command execution fails the regression.

* test(server): make workspace fixtures portable on Windows

Run the setup fixture through a command accepted by PowerShell, await its readiness, and fix the fixture Git line-ending policy. Allow Windows directory locks to settle during cleanup.

* test(server): expose setup failures and await fixture cleanup

Check the public setup status before terminal startup so failures distinguish setup errors from terminal creation. Use asynchronous directory removal so Windows cleanup retries leave the event loop available.

* test(server): start the Windows setup service asynchronously

The Windows regression starts its service but setup stays running, so terminal bootstrap is never reached. Launch the fixture service explicitly with Start-Process and retain the readiness and setup-completion assertions.

---------

Co-authored-by: David Yang <9925+davidyang@users.noreply.github.com>
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-10-15 23:11:13 +02:00
paseo-bot[bot]andSleroq 208e323035 Keep usage providers in place after refresh (#6947)
* fix(app): preserve usage provider order across refreshes

* test(usage): keep refresh and scrolling journeys stable

Usage reports can follow the long fixture card, so a fixed wheel distance
can scroll past its final window. Target the named windows with wheel
input while preserving the visibility checks. Assert refreshed provider
order through visible names and keep viewport setup in journey helpers.

Co-authored-by: Sleroq <hireme@sleroq.link>

---------

Co-authored-by: Sleroq <hireme@sleroq.link>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-10-15 21:16:52 +02:00
Mohamed Boudra ec7446add4 docs(readme): enlarge sponsor logos 2026-10-15 21:11:51 +02:00
Mohamed Boudra b30302b630 docs(changelog): 0.11.4 2026-10-15 20:26:28 +02:00
Mohamed Boudra 7aa3fac069 fix(providers): scope project-dependent model discovery to workspaces
Global discovery has no linked project. Initialize the bridge to check availability, but only open discovery sessions when a workspace is supplied.
2026-10-16 01:19:00 +07:00
Mohamed Boudra fd1e7a34ce docs(changelog): welcome Hoplite as first sponsor in 0.11.3 2026-10-15 19:06:24 +02:00
Mohamed Boudra ce0f21e2ff docs(changelog): 0.11.3
Cherry-picked from ed53a7193 on release/0.11.3-hoplite (tag v0.11.3).
2026-10-15 18:58:16 +02:00
paseo-bot[bot] d172d060a5 server: keep streamed OpenCode v2 chunks from holding their whole message (#6262)
Each streamed text or reasoning chunk was cut from the accumulated
message with slice, which can share the source string's storage. The
timeline store keeps every chunk, so a 128 KB reasoning part retained
about 128 MB: every chunk held the full message as it stood when the
chunk arrived. Long OpenCode v2 reasoning streams exhausted the daemon
worker's heap.

The timeline now emits an independent copy of each suffix, so retained
memory follows the length of the text.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-10-15 18:28:07 +02:00
Mohamed Boudra 2d86b94b2f Refine provider catalog buttons and show Add errors as toasts (#7030)
* fix(app): refine provider catalog actions and error feedback

Use compact row tiles and the shared error toast so failed Add actions remain visible while browsing the catalog. Point Hoplite installation instructions at the CLI install section.

* test(app): supply toast context in provider settings tests

Import the toast API independently of its renderer so the provider section only depends on the context it consumes.
2026-10-15 22:45:12 +07:00
Mohamed Boudra d6d4084a06 docs(plugins): make registry publishing requirements actionable (#6996)
* docs(plugins): explain registry publishing requirements

* docs(plugins): trim publishing guidance to author tasks
2026-10-15 21:38:38 +07:00
Mohamed BoudraandOdin Glynn-Martin 16bb179e67 feat(providers): add opt-in Hoplite and searchable provider grid (#6953)
Preserve the bundled Hoplite ACP adapter and provisioning transformer, activate it only after Add, and provide a searchable provider grid. Restore the contributor's original icon without the copyright mark.

Co-authored-by: Odin Glynn-Martin <odin.glynn@icloud.com>
2026-10-15 21:25:23 +07:00
Mohamed Boudra e08389065c fix(plugins): allow protocol type imports without local dependencies (#7023)
Protocol contracts are available through the SDK peer dependency during development, but clean Git installs lack that dependency tree. Accept erased protocol type imports while retaining runtime dependency resolution and SDK ownership checks.
2026-10-15 21:13:00 +07:00
paseo-bot[bot]andGrant Ammons 80badb3b8f fix(opencode): answer multi-select v2 questions from the question card (#6149)
Closes #6135

Co-authored-by: Grant Ammons <grant@grant.dev>
2026-10-15 15:15:19 +02:00
Hannah ebc4ebc007 fix(app): retain deferred terminal focus within overlays
Keep autofocus pending when focus moves inside the top registered overlay scope, while preserving cancellation for outside controls and workspace or pane loss.

Add a real-browser regression that fails before the fix and passes with terminal typing after overlay dismissal.
2026-10-06 15:58:37 +08:00
Hannah 72d14325e6 fix(app): preserve button focus during deferred terminal autofocus 2026-10-06 15:05:31 +08:00
Hannah 5ead2a8811 fix(app): retry deferred terminal focus after controls release 2026-10-06 14:53:22 +08:00
Hannah 3a10500fcf fix(app): refocus retained terminals after workspace switches 2026-10-06 14:38:47 +08:00
152 changed files with 5657 additions and 1170 deletions
+23
View File
@@ -1,5 +1,28 @@
# Changelog
## 0.11.4 - 2026-10-15
[Hoplite](https://hoplite.sh) joins Paseo as our first sponsor through the company sponsorship program. Hoplite builds cloud coding agents that turn tasks from GitHub, Linear, Slack and more into pull requests. Thank you to the Hoplite team for supporting Paseo.
### Fixed
- Fixed Hoplite showing an error in Settings → Providers instead of discovering models in workspaces linked to a Hoplite project
## 0.11.3 - 2026-10-15
### Added
- Added Hoplite as an opt-in provider in the ACP provider catalog ([#6953](https://github.com/getpaseo/paseo/pull/6953) by [@odinglyn0](https://github.com/odinglyn0))
- Added search to the Add provider catalog ([#6953](https://github.com/getpaseo/paseo/pull/6953), [#7030](https://github.com/getpaseo/paseo/pull/7030))
### Changed
- Changed Add provider failures to show as a toast ([#7030](https://github.com/getpaseo/paseo/pull/7030))
### Fixed
- Fixed Remove being offered for plugin providers such as Antigravity and Muse Code ([#6568](https://github.com/getpaseo/paseo/pull/6568) by [@Ctrl-Creeper](https://github.com/Ctrl-Creeper))
## 0.11.2 - 2026-10-09
### Fixed
+1 -1
View File
@@ -57,7 +57,7 @@ Paseo is an open source agentic development environment for desktop, mobile, web
<!-- Sponsors: one cell per sponsor in the order of packages/website/src/data/sponsors.ts, then "become a sponsor" cells up to three. -->
<table>
<tr>
<td align="center" width="33%"><a href="https://hoplite.sh/?utm_source=paseo&utm_medium=readme&utm_campaign=sponsor"><picture><source media="(prefers-color-scheme: dark)" srcset="packages/website/public/sponsors/hoplite-on-dark.svg"><img src="packages/website/public/sponsors/hoplite-on-light.svg" alt="Hoplite" height="40"></picture></a><br><sub>Cloud coding agents</sub></td>
<td align="center" width="33%"><a href="https://hoplite.sh/?utm_source=paseo&utm_medium=readme&utm_campaign=sponsor"><picture><source media="(prefers-color-scheme: dark)" srcset="packages/website/public/sponsors/hoplite-on-dark.svg"><img src="packages/website/public/sponsors/hoplite-on-light.svg" alt="Hoplite" height="56"></picture></a><br><sub>Cloud coding agents</sub></td>
<td align="center" width="33%"><a href="https://paseo.sh/sponsor">Become a sponsor</a></td>
<td align="center" width="33%"><a href="https://paseo.sh/sponsor">Become a sponsor</a></td>
</tr>
+5
View File
@@ -58,12 +58,17 @@ So arrival sets a _target_ and the reveal rate is derived from the backlog inste
through that hook; the web viewport once skipped it and history hosts of a live tool group went
stale. A new field on `StreamLayoutItem` must be added to `areLayoutItemsEquivalent`, or sharing
silently stops.
- **Streaming cost must not grow with revealed history.** Reading older messages must not
make the next reply progressively more expensive to display. Reuse unchanged history work
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.
## Measuring
- **Smoothness (user-perceived):** `packages/app/e2e/browser/agent-stream-smoothness.spec.ts`, gated behind `PASEO_AGENT_STREAM_PERF_E2E=1`. Drives the mock provider's `bursty-stream` model and reports coefficient of variation of characters painted per frame (smoothness) plus p95 gap between visible updates (stalls). Both numbers are needed: a stalled stream is perfectly smooth.
- **Reproducing bursty arrival:** the `bursty-stream` model in `mock-load-test-agent.ts` emits uneven runs of tokens separated by idle gaps. Burst sizes come from a seeded generator, so a run repeats exactly.
- **Rate policy in isolation:** `computeRevealStep` in `packages/app/src/agent-stream/text-reveal.ts` is pure; `text-reveal.test.ts` covers convergence and burst flattening without a renderer.
- **Per-delta cost on a long timeline:** `npx vitest bench --project unit src/agent-stream/stream-tick.bench.ts` from `packages/app` replays 200 deltas over a 2,000-item timeline through the pure model and layout pipeline, with the default mounted window and with history fully revealed. It measures the JS work per delta, not paint.
Healthy numbers (2026-08, Expo web against a local dev daemon, real Claude Haiku agent, ~8.5s samples during active streaming). Setting `TEXT_REVEAL_HORIZON_MS` to 0 makes the reveal paint on arrival, which is how the baseline column was taken:
+3 -1
View File
@@ -124,7 +124,9 @@ This is the Android counterpart of the iOS local-simulator flow in [development.
Android focus and selection visibility requests must not reposition inverted timelines. The
`modules/paseo-scroll` package keeps React Native's scroll manager interface and returns zero for
child-reveal scroll calculations when the vertical scale is inverted. Dragging and explicit scroll
child-reveal scroll calculations when the view's transform matrix inverts the vertical axis. React
Native's Android list uses `scale: -1`, which decomposes into a 180-degree rotation with positive
`scaleY`; checking the scale property alone misses it. Dragging and explicit scroll
commands still work; non-inverted scroll views keep Android's default behavior.
Register this package before React Native's core package through its Expo config plugin. Normal
+1 -1
View File
@@ -484,7 +484,7 @@ The [Agent Client Protocol (ACP)](https://agentclientprotocol.com) is an open st
ACP agents communicate over JSON-RPC 2.0 on stdio. Paseo spawns the agent process and talks to it through stdin/stdout.
Paseo also ships an in-app ACP provider catalog for common agents, including CodeWhale, Cursor, DeepAgents, DimCode, Gemini CLI, Hermes, Qwen Code, and Kimi Code. Catalog entries create the same `extends: "acp"` provider config shown below.
Paseo also ships an in-app ACP provider catalog for common agents, including CodeWhale, Cursor, DeepAgents, DimCode, Gemini CLI, Hermes, Qwen Code, and Kimi Code. Most catalog entries create the same `extends: "acp"` provider config shown below. Hoplite activates its [bundled provider](plugins.md#built-in-plugins) instead.
### Adding a generic ACP provider
+4 -1
View File
@@ -589,7 +589,10 @@ host, kinds, and ids. Opening a cached workspace uses exact workspace and projec
directory scan. One invalid row is deleted and returned as a miss without affecting other rows.
An invalid directory row and its affected checkpoint cursor are repaired in one transaction, so a
later launch cannot accept a checkpoint for a partial baseline. Directory changes and their
checkpoint are also applied in one transaction.
checkpoint are also applied in one transaction. Reads wait for accepted changes to reach storage,
then retry only when a requested row changes during the read. Unrelated agent streams do not
invalidate the read. Directory baseline replacements and host removal or renaming still invalidate
the affected reads.
The cache is capped at 32 MiB and evicts whole hosts in least-recently-written order. Budget
bookkeeping may scan opaque row sizes during a deferred write, never during host registry startup or
+15 -11
View File
@@ -95,6 +95,11 @@ highest painted scope alone receives overlay keys, traps focus, and restores
focus when it closes. Hover cards register with `manageFocus={false}`: they claim overlay keys without moving or trapping focus on pointer hover. Do not add component-local global Escape listeners: two
stacked overlays would both close on one keypress.
When deferring workspace terminal autofocus, distinguish movement within the
top registered overlay scope from a new focus owner outside it. Internal focus
movement must keep the request pending until the overlay closes; an outside
control cancels it so its next keystroke is not sent to the terminal.
If an overlay is rendered by a global host rather than beneath its opener in
the React tree, carry the opener's current layer through the host store and
restore it with `OverlayLayerProvider`. Otherwise painting and keyboard
@@ -204,10 +209,11 @@ still-mounted content, paints its own surface under the safe areas, and turns
the surface translation off. The composer's single tree keeps the editing
surface at the same position in both modes, so the mounted editor, its native
buffer, selection, and focus survive the toggle and Send's clear always reaches
the live input. The one remount left is a viewport crossing the compact
breakpoint: the app shell swaps its gesture wrapper and the workspace screen
the live input. A viewport crossing the compact breakpoint still remounts it:
the app shell swaps its gesture wrapper and the workspace screen
mounts tabs in different trees, so every screen below remounts. The draft owner
restores the text and the editing session restores the caret and focus intent.
restores the text and the editing session restores the caret. Focus restoration
is limited to mouse-driven UIs, using the same fine-pointer policy as autofocus.
New workspace keys its sessions by draft in the app-level store for the same
reason. The centered form honors fullscreen by style alone: no centering, no
translation, setup fields hidden, slot filling the stationary viewport. The
@@ -217,14 +223,12 @@ sheet suspends pane focus, and the composer gives up input from the moment the
user asks for the compact agent list or explorer, before the panel's motion
settles. Pane focus itself stays put under those panels: the agent panel reads
it as "the user is in this chat" for attention clearing, and opening the agent
list must not clear the attention it shows. Focus restoration follows pane
focus, not the active composer. The editor keeps its focus intent only across
a blur that lands while its pane is not the user's (a retained tab hidden, a
sheet over it) and refocuses when the pane comes back. A blur while the pane is
theirs drops the intent in every layout mode, and the keyboard the compact
panels dismiss when they settle is such a blur, so closing the agent list or
explorer never reopens the keyboard. Keying restoration on the active composer
made that dismiss look like a hidden-tab blur and refocused on close.
list must not clear the attention it shows. On mouse-driven UIs, focus restoration
follows pane focus, not the active composer. Keying it on the active composer
made sidebar dismissal look like a hidden-tab blur and refocused on close.
Native and touch-web navigation must not replay old editor focus, including
when blur arrives after pane deactivation or the editor unmounts before blur.
Fullscreen toggles keep the editor mounted and need no focus restoration.
The band beside the inline editor where the fullscreen glyph sits is the input's
own right padding, so a tap anywhere in it focuses the editor whether or not the
glyph shows. On web the slot is a fixed box over the visible viewport, which is
+6
View File
@@ -107,6 +107,12 @@ absent from the installed plugin list and source configuration; their client bun
appear in the plugin catalog. Editing one in development requires a daemon restart.
Directory, Git, and npm installs cannot use a built-in ID.
A provider registration with `requiresConfiguration: true` participates only while its ID exists
under `agents.providers`. Hoplite uses this for catalog opt-in. Add writes `{ "enabled": true }`
without `extends`, so it selects the bundled adapter. Remove deletes the config entry; setting
`enabled: false` keeps the entry. The bundled JavaScript still loads at startup, but an absent
provider does not enter executable resolution or catalog discovery.
Provider plugins use separate installation and provider IDs. `muse-provider` registers the
selectable `muse` provider (Muse Code) and a usage source. Its `status({ launch })` reports
availability and a diagnostic after the daemon resolves the executable. Configure command,
@@ -1,13 +1,24 @@
import { test } from "../support/fixtures";
import {
closeModelPicker,
openModelPicker,
seedAgentProfiles,
} from "../support/helpers/agent-profiles";
import { expectComposerVisible } from "../support/helpers/composer";
import { clickNewChat, gotoWorkspace } from "../support/helpers/launcher";
import { seedWorkspace } from "../support/helpers/seed-client";
import { writeFile } from "node:fs/promises";
import { expect, test } from "../support/fixtures";
import { gotoAppShell, openSettings } from "../support/helpers/app";
import { connectDaemonClient } from "../support/helpers/daemon-client-loader";
import { getServerId } from "../support/helpers/server-id";
import {
expectProviderInstalledInSettings,
findAcpCatalogProvider,
installAcpCatalogProvider,
openAddProviderArea,
openSettingsHost,
openSettingsHostSection,
seedSavedSettingsHosts,
} from "../support/helpers/settings";
const ACP_PROVIDER = {
@@ -16,8 +27,13 @@ const ACP_PROVIDER = {
};
interface ProviderCatalogDaemonClient {
getLastServerInfoMessage(): {
features?: { hopliteProvider?: boolean; plugins?: boolean };
} | null;
connect(): Promise<void>;
close(): Promise<void>;
getDaemonConfig(): Promise<{ config: { providers?: Record<string, unknown> } }>;
getProvidersSnapshot(): Promise<{ entries: Array<{ provider: string }> }>;
patchDaemonConfig(config: { removeProviders?: string[] }): Promise<unknown>;
}
@@ -41,3 +57,124 @@ test.describe("ACP provider catalog", () => {
}
});
});
for (const theme of ["light", "dark"] as const) {
test(`adds Hoplite from the catalog in ${theme} theme`, async ({ page }, testInfo) => {
const client = await connectDaemonClient<ProviderCatalogDaemonClient>({
clientIdPrefix: "hoplite-catalog-e2e",
});
try {
expect(client.getLastServerInfoMessage()?.features?.hopliteProvider).toBe(true);
await client.patchDaemonConfig({ removeProviders: ["hoplite"] });
expect(
(await client.getProvidersSnapshot()).entries.some((entry) => entry.provider === "hoplite"),
).toBe(false);
await page.addInitScript((value) => {
localStorage.setItem("@paseo:app-settings", JSON.stringify({ theme: value }));
}, theme);
await gotoAppShell(page);
await openSettings(page);
await openSettingsHost(page, getServerId());
await openSettingsHostSection(page, getServerId(), "providers");
await expect(
page.getByRole("button", { name: "Hoplite provider details", exact: true }),
).toHaveCount(0);
await openAddProviderArea(page);
await findAcpCatalogProvider(page, "Hoplite");
await page.screenshot({ path: testInfo.outputPath(`hoplite-catalog-${theme}.png`) });
await installAcpCatalogProvider(page, "Hoplite");
await expectProviderInstalledInSettings(page, "Hoplite");
await page.screenshot({ path: testInfo.outputPath(`hoplite-installed-${theme}.png`) });
expect((await client.getDaemonConfig()).config.providers?.hoplite).toEqual({ enabled: true });
await writeFile(
testInfo.outputPath(`hoplite-added-${theme}.json`),
JSON.stringify(await client.getProvidersSnapshot(), null, 2),
);
await removeHoplite(page);
await expect(
page.getByRole("button", { name: "Hoplite provider details", exact: true }),
).toHaveCount(0);
expect((await client.getDaemonConfig()).config.providers?.hoplite).toBeUndefined();
expect(
(await client.getProvidersSnapshot()).entries.some((entry) => entry.provider === "hoplite"),
).toBe(false);
await writeFile(
testInfo.outputPath(`hoplite-removed-${theme}.json`),
JSON.stringify(await client.getProvidersSnapshot(), null, 2),
);
await openAddProviderArea(page);
await findAcpCatalogProvider(page, "Hoplite");
await page.screenshot({ path: testInfo.outputPath(`hoplite-removed-${theme}.png`) });
await installAcpCatalogProvider(page, "Hoplite");
await expectProviderInstalledInSettings(page, "Hoplite");
} finally {
await client.patchDaemonConfig({ removeProviders: ["hoplite"] }).catch(() => undefined);
await client.close().catch(() => undefined);
}
});
}
async function removeHoplite(page: import("@playwright/test").Page): Promise<void> {
await page.getByTestId("provider-actions-hoplite").click();
page.once("dialog", (dialog) => {
void dialog.accept();
});
await page.getByTestId("provider-remove-hoplite").click();
}
test("unsupported host asks for an update without writing Hoplite config", async ({
page,
outdatedDaemon,
}, testInfo) => {
const client = await connectDaemonClient<ProviderCatalogDaemonClient>({
clientIdPrefix: "hoplite-unsupported",
port: Number(new URL(`http://${outdatedDaemon.endpoint}`).port),
});
try {
expect(client.getLastServerInfoMessage()?.features?.plugins).toBe(true);
expect(client.getLastServerInfoMessage()?.features?.hopliteProvider).toBe(false);
const before = await client.getDaemonConfig();
await seedSavedSettingsHosts(page, [outdatedDaemon]);
await page.reload();
await openSettings(page);
await openSettingsHost(page, outdatedDaemon.serverId);
await openSettingsHostSection(page, outdatedDaemon.serverId, "providers");
await openAddProviderArea(page);
await page.getByRole("button", { name: "Add Hoplite", exact: true }).click();
const errorToast = page.getByTestId("app-toast-message");
await expect(errorToast).toHaveText("Update the host to add Hoplite.");
await expect(errorToast).toBeInViewport();
expect((await client.getDaemonConfig()).config).toEqual(before.config);
await expect(
page.getByRole("button", { name: "Hoplite provider details", exact: true }),
).toHaveCount(0);
await page.screenshot({ path: testInfo.outputPath("hoplite-update-host.png") });
} finally {
await client.close();
}
});
test("model selector excludes Hoplite before opt-in", async ({ page }, testInfo) => {
const client = await connectDaemonClient<ProviderCatalogDaemonClient>({
clientIdPrefix: "hoplite-picker",
});
const profiles = await seedAgentProfiles([
{ id: "hoplite-picker-anchor", name: "Picker anchor", provider: "mock" },
]);
const workspace = await seedWorkspace({ repoPrefix: "hoplite-picker-" });
try {
await client.patchDaemonConfig({ removeProviders: ["hoplite"] });
await gotoWorkspace(page, workspace.workspaceId);
await clickNewChat(page);
await expectComposerVisible(page);
await openModelPicker(page);
await expect(page.getByTestId("model-provider-mock")).toBeVisible();
await expect(page.getByTestId("model-provider-hoplite")).toHaveCount(0);
await page.screenshot({ path: testInfo.outputPath("hoplite-model-selector-absent.png") });
await closeModelPicker(page);
} finally {
await workspace.cleanup();
await profiles.restore();
await client.close();
}
});
@@ -1,6 +1,6 @@
import { randomUUID } from "node:crypto";
import { mkdtemp, rm, stat } from "node:fs/promises";
import { tmpdir } from "node:os";
import { mkdir, mkdtemp, rm, stat } from "node:fs/promises";
import { homedir, tmpdir } from "node:os";
import path from "node:path";
import { test, expect } from "../support/fixtures";
import {
@@ -12,12 +12,15 @@ import {
chooseAddProjectMethod,
expectAddProjectPage,
expectNewWorkspaceForAddedProject,
expectAddProjectResultVisible,
navigateAddProjectResults,
openAddProjectFlow,
openAddProjectHostSelection,
} from "../support/helpers/add-project-flow";
import { gotoAppShell } from "../support/helpers/app";
import {
addConnectedHostAndReload,
addConnectedHostsAndReload,
addOfflineHostAndReload,
waitForConnectedHost,
} from "../support/helpers/hosts";
@@ -214,6 +217,60 @@ test.describe("Add Project command-center flow", () => {
});
});
test("filtered hosts keep the keyboard-selected row visible", async ({ page }) => {
const hosts: IsolatedHostDaemon[] = [];
try {
for (let index = 1; index <= 3; index += 1) {
hosts.push(await startIsolatedHostDaemon(`scroll-host-${index}`));
}
await page.setViewportSize({ width: 1280, height: 360 });
await gotoAppShell(page);
await addConnectedHostsAndReload(
page,
hosts.map((host, index) => ({
serverId: host.serverId,
port: host.port,
label: index < 2 ? `Fleet 0${index + 1}` : "Other host",
})),
{ primaryLabel: "Fleet 00" },
);
for (const host of hosts) {
await waitForConnectedHost(page, {
serverId: host.serverId,
endpoint: `localhost:${host.port}`,
});
}
await openAddProjectHostSelection(page);
await expect(
addProjectFlow(page).getByRole("button").filter({ hasText: "Other host" }),
).toBeVisible();
await addProjectFlowInput(page).fill("Fleet");
await expect(addProjectFlowHost(page, hosts[2]!.serverId)).toHaveCount(0);
await navigateAddProjectResults(page, "ArrowDown", 2);
await expectAddProjectResultVisible(page, "Fleet 02");
// Filtering out the first host moves retained rows to new positions.
await addProjectFlowInput(page).fill("scroll-host");
await expect(addProjectFlowHost(page, getServerId())).toHaveCount(0);
await expectAddProjectResultVisible(page, "Fleet 01");
await navigateAddProjectResults(page, "ArrowDown", 2);
await expectAddProjectResultVisible(page, "Other host");
await navigateAddProjectResults(page, "ArrowDown", 1);
await expectAddProjectResultVisible(page, "Fleet 01");
await addProjectFlowInput(page).fill("Fleet");
await expectAddProjectResultVisible(page, "Fleet 00");
await navigateAddProjectResults(page, "ArrowDown", 2);
await expectAddProjectResultVisible(page, "Fleet 02");
await page.keyboard.press("Enter");
await expectAddProjectPage(page, "method");
await expect(addProjectFlow(page)).toContainText("Fleet 02");
} finally {
await Promise.all(hosts.map((host) => host.close()));
}
});
test("keyboard directory search adds the selected Project", async ({
page,
projectPickerFixture,
@@ -241,6 +298,59 @@ test.describe("Add Project command-center flow", () => {
await expectProjectHasNoWorkspaces(projectId);
});
test("keyboard navigation keeps the selected row inside the visible results", async ({
page,
}) => {
const parentDirectory = await mkdtemp(path.join(homedir(), "paseo-e2e-scroll-"));
const rowPath = (index: number) =>
path.join(parentDirectory, `scroll-probe-${String(index).padStart(2, "0")}`);
let projectId: string | null = null;
try {
await Promise.all(Array.from({ length: 16 }, (_, index) => mkdir(rowPath(index))));
await gotoAppShell(page);
await openAddProjectFlow(page);
await chooseAddProjectMethod(page, "directory-search");
await addProjectFlowInput(page).fill(path.basename(parentDirectory));
const results = page.getByTestId("add-project-flow-results");
await expect(results.getByRole("button", { name: /scroll-probe-/ })).toHaveCount(16, {
timeout: 30_000,
});
await navigateAddProjectResults(page, "ArrowDown", 12);
await expectAddProjectResultVisible(page, rowPath(11));
await navigateAddProjectResults(page, "ArrowUp", 12);
await expectAddProjectResultVisible(page, parentDirectory);
await navigateAddProjectResults(page, "ArrowUp", 1);
await expectAddProjectResultVisible(page, rowPath(15));
await navigateAddProjectResults(page, "ArrowDown", 1);
await expectAddProjectResultVisible(page, parentDirectory);
await navigateAddProjectResults(page, "ArrowDown", 12);
await expectAddProjectResultVisible(page, rowPath(11));
await addProjectFlowInput(page).fill(`${path.basename(parentDirectory)}probe`);
await expect(results.getByRole("button")).toHaveCount(16);
await expectAddProjectResultVisible(page, rowPath(0));
await navigateAddProjectResults(page, "ArrowDown", 12);
await expectAddProjectResultVisible(page, rowPath(12));
await addProjectFlowInput(page).fill(path.basename(parentDirectory));
await expect(results.getByRole("button")).toHaveCount(17);
await expectAddProjectResultVisible(page, parentDirectory);
await navigateAddProjectResults(page, "ArrowDown", 12);
await expectAddProjectResultVisible(page, rowPath(11));
await page.keyboard.press("Enter");
projectId = await expectOpenedProject(page, "scroll-probe-11");
await expectNewWorkspaceForAddedProject(page, {
serverId: getServerId(),
projectId,
projectName: "scroll-probe-11",
projectPath: rowPath(11),
});
} finally {
if (projectId) await removeCreatedProject(rowPath(11), projectId);
await rm(parentDirectory, { recursive: true, force: true });
}
});
test("a complete repository URL remains selectable without a GitHub search result", async ({
page,
}) => {
@@ -1,6 +1,13 @@
import { test, expect } from "../support/fixtures";
import { awaitAssistantMessage } from "../support/helpers/agent-stream";
import { startRunningMockAgent } from "../support/helpers/composer";
import { startRunningMockAgent, submitMessage } from "../support/helpers/composer";
import {
seedLongMockAgentTimeline,
openAgentTimeline,
scrollTimelineUntilOlderHistoryIsReachable,
scrollTimelineToNewestLoadedEdge,
expectTimelinePromptVisible,
} from "../support/helpers/timeline-pagination";
import {
sampleStreamFrames,
summarizeStreamSmoothness,
@@ -102,6 +109,40 @@ agentStreamPerfDescribe("Agent stream smoothness", () => {
await agent.cleanup();
}
});
test("keeps streaming work bounded after revealing older history", async ({ page }, testInfo) => {
test.setTimeout(120_000);
await page.addInitScript(() => {
Reflect.set(globalThis, "__PASEO_RENDER_PROFILE_ENABLED__", true);
});
const agent = await seedLongMockAgentTimeline({ turns: 80, liveTurns: "thirty-minute-stream" });
try {
await openAgentTimeline(page, agent);
await expect(page.getByRole("textbox", { name: "Message agent..." }).first()).toBeVisible();
await scrollTimelineUntilOlderHistoryIsReachable(page, agent.oldestPrompt);
await expectTimelinePromptVisible(page, agent.oldestPrompt);
await scrollTimelineToNewestLoadedEdge(page);
await submitMessage(page, "Stream a long answer after reading older messages.");
await awaitAssistantMessage(page);
for (let sample = 0; sample < 3; sample += 1) {
await page.evaluate(() => globalThis.__PASEO_RESET_RENDER_PROFILE__?.());
const frames = await sampleStreamFrames(page, { sampleWindowMs: SAMPLE_WINDOW_MS });
const smoothness = summarizeStreamSmoothness(frames, SAMPLE_WINDOW_MS);
const react = summarizeReactCommits(await readStreamReactCommits(page));
await testInfo.attach(`revealed-history-stream-${sample}`, {
body: JSON.stringify({ smoothness, react }, null, 2),
contentType: "application/json",
});
console.log(`[perf] Revealed history stream: ${JSON.stringify({ smoothness, react })}`);
expect(smoothness.growthFrames).toBeGreaterThan(20);
expect(react.count).toBeGreaterThan(20);
expect(react.actualDurationP95Ms).toBeLessThan(REACT_COMMIT_P95_BUDGET_MS);
}
} finally {
await agent.cleanup();
}
});
});
async function readStreamReactCommits(
@@ -133,6 +133,58 @@ test("scroll detector accounts for delayed wheel input and growth below the new
).toHaveLength(1);
});
test("scroll detector follows the entered image through resize and virtual offset correction", () => {
for (const height of [225, 1632]) {
const before: ScrollFrame = {
at: 1000,
scrollTop: 2208,
scrollHeight: 5000,
viewportHeight: 516,
virtualized: true,
loading: false,
rows: [
{ id: "image", top: -704, height: 560 },
{ id: "caption", top: -144, height: 100 },
{ id: "old-reader", top: -44, height: 127 },
],
anchor: "old-reader",
wheelTotal: 0,
lastWheelAt: 0,
inputFinishedAt: null,
imageLoads: 0,
mounted: 3,
unmounted: 0,
};
const resize = height - 560;
const after: ScrollFrame = {
...before,
at: 1060,
// The virtualizer corrects 110px of estimates while the wheel moves 160px.
scrollTop: 1938,
scrollHeight: 5000 + resize - 110,
wheelTotal: 160,
lastWheelAt: 1020,
imageLoads: 1,
rows: [
{ id: "image", top: -544, height },
{ id: "caption", top: 16 + resize, height: 100 },
{ id: "old-reader", top: 116 + resize, height: 127 },
],
};
expect(findScrollJumps([before, after])).toEqual([]);
// Resizing must not excuse additional viewport movement.
expect(
findScrollJumps([
before,
{
...after,
rows: after.rows.map((row) => ({ id: row.id, height: row.height, top: row.top + 100 })),
},
]),
).toHaveLength(1);
}
});
for (const cadence of scrollCadences) {
test(`varied timeline preserves reading position during ${cadence.name} upward scrolling`, async ({
page,
@@ -89,9 +89,11 @@ async function dismissStackedModelPickerWithBackdrop(page: Page) {
.getByTestId("agent-controls-settings-list")
.getByRole("button", { name: /Select model/ })
.click();
await expect(page.getByTestId("agent-controls-model-browser-sheet")).toBeVisible();
await expect(page.getByTestId("agent-controls-model-browser-sheet")).toBeInViewport();
await page.mouse.click(MOBILE_VIEWPORT.width / 2, 24);
await expect(page.getByTestId("agent-controls-model-browser-sheet")).not.toBeVisible();
// In CI, Gorhom retains the dismissed sheet below the viewport.
// Dismissal is complete when it leaves the displayed surface.
await expect(page.getByTestId("agent-controls-model-browser-sheet")).not.toBeInViewport();
await expect(page.getByTestId("agent-controls-model-sheet")).toBeVisible();
await expect(page.getByTestId("agent-controls-settings-list")).toBeVisible();
}
@@ -139,7 +141,7 @@ test.describe("mobile bottom sheet reopen", () => {
await expect(sheet).toBeVisible();
await expect(page.getByTestId("agent-controls-settings-list")).toBeVisible();
await expect(page.getByTestId("agent-controls-model")).toContainText("Ten second stream");
await expect(page.getByTestId("agent-controls-model-browser-sheet")).not.toBeVisible();
await expect(page.getByTestId("agent-controls-model-browser-sheet")).not.toBeInViewport();
});
} finally {
await session.cleanup();
@@ -3,6 +3,18 @@ import { test, expect } from "../support/fixtures";
import { seedWorkspace } from "../support/helpers/seed-client";
import { openAgentRoute } from "../support/helpers/mock-agent";
import { getServerId } from "../support/helpers/server-id";
import { expectOpenTabCount } from "../support/helpers/sheet";
import {
closeCompactWorkspaceMenu,
goBackInMenu,
menuRow,
openCompactWorkspaceMenu,
openRunningScriptPage,
openScriptsPage,
runScriptFromScriptsPage,
scriptRow,
scriptsMenuRow,
} from "../support/helpers/compact-workspace-scripts";
const labels = {
long: {
@@ -38,11 +50,13 @@ async function openNamedWorkspace(page: Page, names: typeof labels.long) {
}
async function expectHeaderContentsFit(page: Page, info: TestInfo, long: boolean) {
const menu = page.getByTestId("menu-button").filter({ visible: true });
const title = page.getByTestId("workspace-header-title");
const project = page.getByTestId("workspace-header-subtitle");
const badge = page.getByTestId(`host-badge-${getServerId()}`).filter({ visible: true });
const trigger = page.getByRole("button", { name: /Switch tabs/ });
const measure = async () => ({
menu: await menu.boundingBox(),
title: await title.boundingBox(),
project: await project.boundingBox(),
badge: await badge.boundingBox(),
@@ -54,23 +68,21 @@ async function expectHeaderContentsFit(page: Page, info: TestInfo, long: boolean
await page.screenshot({ path: info.outputPath("header.png") });
await expect(async () => {
const bounds = await measure();
expect(bounds.menu).not.toBeNull();
expect(bounds.title).not.toBeNull();
expect(bounds.project).not.toBeNull();
expect(bounds.badge).not.toBeNull();
expect(bounds.icon).not.toBeNull();
expect(bounds.trigger).not.toBeNull();
// Approved geometry: 12px outside margin, 46px leading island, 8px title gap.
expect(bounds.title!.x).toBe(66);
// The labels sit between the menu button and the actions without overlapping either.
expect(bounds.title!.x).toBeGreaterThan(bounds.menu!.x + bounds.menu!.width);
expect(bounds.project!.x).toBe(bounds.title!.x);
expect(bounds.trigger!.width).toBe(32);
expect(bounds.trigger!.height).toBe(32);
// The action frame starts 7px inside its island; preserve the 8px gap before it.
const contentRight = bounds.trigger!.x - 15;
for (const box of [bounds.title!, bounds.project!, bounds.badge!, bounds.icon!]) {
expect(box.x + box.width).toBeLessThanOrEqual(contentRight + 1);
expect(box.x + box.width).toBeLessThan(bounds.trigger!.x);
}
expect(bounds.project!.width).toBeGreaterThan(20);
expect(bounds.icon!.width).toBe(12);
// Long labels truncate instead of squeezing the host icon.
expect(bounds.icon!.width).toBe(bounds.icon!.height);
expect(bounds.badge!.x).toBeGreaterThan(bounds.project!.x + bounds.project!.width);
expect(bounds.titleTruncated).toBe(long);
expect(bounds.projectTruncated).toBe(long);
@@ -94,3 +106,87 @@ for (const width of [320, 390]) {
});
}
}
const KEEP_ALIVE = 'node -e "setInterval(() => {}, 1000)"';
const WEB_SERVER =
"node -e \"require('http').createServer((q, r) => r.end('ok')).listen(process.env.PASEO_PORT)\"";
async function openWorkspaceWithScripts(page: Page) {
const workspace = await seedWorkspace({
repoPrefix: "compact-scripts-",
repo: {
paseoConfig: {
scripts: {
lint: { type: "script", command: KEEP_ALIVE },
web: { type: "service", command: WEB_SERVER },
},
},
},
});
try {
const agent = await workspace.client.createAgent({
provider: "mock",
cwd: workspace.repoPath,
workspaceId: workspace.workspaceId,
title: "Scripts menu check",
modeId: "load-test",
model: "e2e-fast-stream",
});
await openAgentRoute(page, { workspaceId: workspace.workspaceId, agentId: agent.id });
return workspace;
} catch (error) {
await workspace.cleanup();
throw error;
}
}
test("compact header menu runs, shows, and stops workspace scripts", async ({ page }) => {
await page.setViewportSize({ width: 390, height: 844 });
const workspace = await openWorkspaceWithScripts(page);
try {
await expectOpenTabCount(page, 1);
await test.step("nothing running: the Scripts row has no value", async () => {
await openCompactWorkspaceMenu(page);
await expect(scriptsMenuRow(page)).toHaveAccessibleName("Scripts");
await closeCompactWorkspaceMenu(page);
});
await test.step("a stopped script runs from the Scripts page into a terminal tab", async () => {
await runScriptFromScriptsPage(page, "lint");
await expectOpenTabCount(page, 2);
await openCompactWorkspaceMenu(page);
await expect(scriptsMenuRow(page)).toHaveAccessibleName(/^Scripts\s*lint$/);
await closeCompactWorkspaceMenu(page);
});
await test.step("two running scripts are counted on the root row", async () => {
await runScriptFromScriptsPage(page, "web");
await expectOpenTabCount(page, 3);
await openCompactWorkspaceMenu(page);
await expect(scriptsMenuRow(page)).toHaveAccessibleName(/^Scripts\s*2 running$/);
await closeCompactWorkspaceMenu(page);
});
await test.step("stopping a script keeps its page open in the stopped state", async () => {
await openRunningScriptPage(page, "web");
await expect(menuRow(page, "View service")).toBeVisible();
await menuRow(page, "Stop").click();
await expect(menuRow(page, "Run")).toBeVisible({ timeout: 15_000 });
await expect(menuRow(page, "Stop")).toHaveCount(0);
await goBackInMenu(page);
await expect(scriptRow(page, "web")).toHaveAccessibleName(/^web\s*exit \d+$/);
await expect(scriptRow(page, "lint")).toHaveAccessibleName(/^lint\s*Running$/);
await closeCompactWorkspaceMenu(page);
});
await test.step("the root row names the one script still running", async () => {
await openScriptsPage(page);
await goBackInMenu(page);
await expect(scriptsMenuRow(page)).toHaveAccessibleName(/^Scripts\s*lint$/);
});
} finally {
await workspace.cleanup();
}
});
+151 -1
View File
@@ -1,7 +1,7 @@
import { expect, test, type Page } from "../support/fixtures";
import {
composerLocator,
blurComposerInput,
composerLocator,
enterComposerFullscreen,
exitComposerFullscreen,
expectComposerDraft,
@@ -15,6 +15,9 @@ import {
typeIntoFocusedComposer,
} from "../support/helpers/composer";
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
import { createMockIdleAgent, openWorkspaceWithAgents } from "../support/helpers/archive-tab";
import { seedWorkspace } from "../support/helpers/seed-client";
import { switchComposerTabWithKeyboard } from "../support/helpers/composer";
import {
closeMobileAgentSidebar,
closeMobileExplorer,
@@ -25,6 +28,100 @@ import {
swipeOpenMobileAgentSidebar,
swipeOpenMobileExplorer,
} from "../support/helpers/sidebar";
import { readScrollMetrics } from "../support/helpers/agent-bottom-anchor";
import {
expectTimelinePromptPositionPreserved,
rememberTimelinePromptPosition,
seedLongMockAgentTimeline,
waitForTimelineGeometryToSettle,
} from "../support/helpers/timeline-pagination";
test("clicking chat text or background focuses the feed for keyboard paging", async ({
page,
}, testInfo) => {
const agent = await seedLongMockAgentTimeline({ turns: 8 });
try {
await openAgentRoute(page, agent);
const composer = composerLocator(page);
const feed = page.getByTestId("agent-chat-scroll").filter({ visible: true });
await composer.fill("Keep this draft");
await feed.getByText(agent.newestPrompt, { exact: true }).click();
await expect(feed).toBeFocused();
const beforePaging = await readScrollMetrics(page);
expect(beforePaging.offsetY).toBeGreaterThan(beforePaging.viewportHeight);
await page.keyboard.press("PageUp");
await expect
.poll(async () => (await readScrollMetrics(page)).offsetY)
.toBeLessThan(beforePaging.offsetY - beforePaging.viewportHeight / 2);
await page.screenshot({ path: testInfo.outputPath("chat-keyboard-paging.png") });
await page.keyboard.press("PageDown");
await expect
.poll(async () => (await readScrollMetrics(page)).distanceFromBottom)
.toBeLessThanOrEqual(2);
await composer.click();
await expectComposerFocused(page);
await feed.click({ position: { x: 2, y: 40 } });
await expect(feed).toBeFocused();
await page.keyboard.press("PageUp");
await expect
.poll(async () => (await readScrollMetrics(page)).distanceFromBottom)
.toBeGreaterThan(beforePaging.viewportHeight / 2);
await waitForTimelineGeometryToSettle(page);
const readingPrompt = agent.prompts[4];
await expect(feed.getByText(readingPrompt, { exact: true })).toBeInViewport();
const readingPosition = await rememberTimelinePromptPosition(page, readingPrompt);
await agent.client.sendAgentMessage(agent.agentId, "emit 2 coalesced agent stream updates");
await agent.client.waitForFinish(agent.agentId, 15_000);
// The daemon finishing does not mean its response has reached the browser.
await expect(feed.getByText(/stress-update-1/)).toHaveCount(1);
await waitForTimelineGeometryToSettle(page);
await expectTimelinePromptPositionPreserved(page, readingPosition);
await expectComposerDraft(page, "Keep this draft");
} finally {
await agent.cleanup();
}
});
test("focusing the feed preserves assistant text selection and code copy controls", async ({
page,
context,
}) => {
const sentence = "Select this assistant sentence.";
const agent = await seedMockAgentWorkspace({
repoPrefix: "chat-focus-selection-",
title: "Chat focus selection",
initialPrompt: "Render text and code.",
featureValues: {
mockAssistantResponse: `${sentence}\n\n\`\`\`bash\necho example\n\`\`\``,
},
});
try {
await context.grantPermissions(["clipboard-read", "clipboard-write"]);
await agent.client.waitForFinish(agent.agentId, 15_000);
await openAgentRoute(page, agent);
await composerLocator(page).fill("Keep this draft");
const feed = page.getByTestId("agent-chat-scroll").filter({ visible: true });
await feed.getByText(sentence, { exact: true }).click({ clickCount: 3 });
await expect(feed).toBeFocused();
expect(await page.evaluate(() => window.getSelection()?.toString().trim())).toBe(sentence);
await page.keyboard.press("ControlOrMeta+c");
expect((await page.evaluate(() => navigator.clipboard.readText())).trim()).toBe(sentence);
const code = feed.locator('[data-paseo-markdown-language="bash"]');
await code.hover();
await code.locator("[data-paseo-markdown-ignore]").click();
await expect(feed).not.toBeFocused();
expect(await page.evaluate(() => navigator.clipboard.readText())).toBe("echo example");
await expectComposerDraft(page, "Keep this draft");
} finally {
await agent.cleanup();
}
});
test("submitting a message leaves the composer ready for the next message", async ({ page }) => {
const agent = await seedMockAgentWorkspace({
@@ -73,6 +170,59 @@ test.describe("touch screen wide enough for the desktop layout", () => {
// composer there raises the on-screen keyboard over the conversation.
test.use({ viewport: { width: 1024, height: 768 }, isMobile: true, hasTouch: true });
test("remounting an inline composer does not restore focus on touch", async ({ page }) => {
const agent = await seedMockAgentWorkspace({
repoPrefix: "composer-touch-remount-",
title: "Touch remount",
});
try {
await openAgentRoute(page, agent);
await composerLocator(page).fill("Keep this draft through resize");
await expectComposerFocused(page);
await resizeComposerViewport(page, "portrait");
await expectComposerDraft(page, "Keep this draft through resize");
await expectComposerNotFocused(page);
await composerLocator(page).tap();
await expectComposerFocused(page);
} finally {
await agent.cleanup();
}
});
test("returning to an inactive inline composer does not restore focus on touch", async ({
page,
}) => {
const workspace = await seedWorkspace({ repoPrefix: "composer-touch-retained-" });
try {
const first = await createMockIdleAgent(workspace.client, {
cwd: workspace.repoPath,
workspaceId: workspace.workspaceId,
title: "First touch chat",
});
const second = await createMockIdleAgent(workspace.client, {
cwd: workspace.repoPath,
workspaceId: workspace.workspaceId,
title: "Second touch chat",
});
await openWorkspaceWithAgents(page, [first, second]);
await composerLocator(page).fill("Keep this touch draft");
await expectComposerFocused(page);
// An external keyboard changes tabs without a pointer click blurring the
// editor first. The device still has a touch-primary focus policy.
await switchComposerTabWithKeyboard(page, "previous");
await expectComposerDraft(page, "");
await switchComposerTabWithKeyboard(page, "next");
await expectComposerDraft(page, "Keep this touch draft");
await expectComposerNotFocused(page);
await composerLocator(page).tap();
await expectComposerFocused(page);
await typeIntoFocusedComposer(page, " after return");
await expectComposerDraft(page, "Keep this touch draft after return");
} finally {
await workspace.cleanup();
}
});
test("opening an agent leaves the composer unfocused", async ({ page }) => {
const agent = await seedMockAgentWorkspace({
repoPrefix: "composer-focus-touch-",
@@ -0,0 +1,110 @@
import path from "node:path";
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
import { expect, test, type Page } from "../support/fixtures";
import { gotoAppShell, openSettings } from "../support/helpers/app";
import {
closeModelPicker,
drillIntoProvider,
openModelPicker,
} from "../support/helpers/agent-profiles";
import { expectComposerVisible, expectComposerFocused } from "../support/helpers/composer";
import { connectDaemonClient } from "../support/helpers/daemon-client-loader";
import { clickNewChat, gotoWorkspace } from "../support/helpers/launcher";
import { getServerId } from "../support/helpers/server-id";
import { openSettingsHost, openSettingsHostSection } from "../support/helpers/settings";
// Use an existing repository linked to the signed-in user's Hoplite project.
const cwd = process.env.E2E_HOPLITE_CWD ?? path.resolve(__dirname, "../../../..");
test.use({
viewport: { width: 1440, height: 1000 },
e2eDaemonConfig: { version: 1, agents: { providers: { hoplite: { enabled: true } } } },
});
async function openHopliteSettings(page: Page): Promise<void> {
await gotoAppShell(page);
await openSettings(page);
await openSettingsHost(page, getServerId());
await openSettingsHostSection(page, getServerId(), "providers");
await page.getByRole("button", { name: "Hoplite provider details", exact: true }).click();
}
async function expectEmptyGlobalCatalog(page: Page, client: DaemonClient): Promise<void> {
const models = await client.listProviderModels("hoplite");
expect(models.error).toBeNull();
expect(models.models).toEqual([]);
const snapshot = await client.getProvidersSnapshot();
expect(snapshot.entries.find((entry) => entry.provider === "hoplite")).toMatchObject({
status: "ready",
models: [],
});
await expect(page.getByText("No models detected", { exact: true })).toBeVisible();
await expect(page.getByRole("button", { name: "Retry", exact: true })).toHaveCount(0);
}
async function refreshGlobalCatalog(page: Page): Promise<void> {
await page.getByRole("button", { name: "Refresh", exact: true }).click();
await expect(page.getByRole("button", { name: "Refresh", exact: true })).toBeEnabled({
timeout: 120_000,
});
}
async function openWorkspaceModels(page: Page, workspaceId: string): Promise<void> {
await gotoWorkspace(page, workspaceId);
await clickNewChat(page);
await expectComposerVisible(page);
await expectComposerFocused(page);
await openModelPicker(page);
await page.getByTestId("sheet-header-back").click();
await drillIntoProvider(page, "hoplite");
}
test("real Hoplite has an empty global catalog and discovers models in its linked workspace", async ({
page,
e2eWorkerClient,
}, testInfo) => {
test.setTimeout(180_000);
const client = await connectDaemonClient<DaemonClient>({ clientIdPrefix: "hoplite-discovery" });
const created = await e2eWorkerClient.createWorkspace({
source: { kind: "directory", path: cwd },
title: "Hoplite discovery QA",
});
expect(created.error).toBeNull();
const workspace = created.workspace!;
try {
await test.step("global settings succeed with no models, including refresh", async () => {
await openHopliteSettings(page);
await expectEmptyGlobalCatalog(page, client);
await refreshGlobalCatalog(page);
await expectEmptyGlobalCatalog(page, client);
await page.screenshot({ path: testInfo.outputPath("hoplite-global-empty.png") });
});
await test.step("the linked workspace discovers real models", async () => {
const models = await client.listProviderModels("hoplite", { cwd });
expect(models.error).toBeNull();
expect(models.models!.length).toBeGreaterThan(0);
await testInfo.attach("workspace-models", {
body: JSON.stringify(models, null, 2),
contentType: "application/json",
});
await openWorkspaceModels(page, workspace.id);
await expect(page.getByText(models.models![0]!.label, { exact: true }).last()).toBeVisible();
await page.screenshot({ path: testInfo.outputPath("hoplite-workspace-models.png") });
await closeModelPicker(page);
});
await test.step("workspace discovery does not populate the global catalog", async () => {
await openHopliteSettings(page);
await expectEmptyGlobalCatalog(page, client);
await refreshGlobalCatalog(page);
await expectEmptyGlobalCatalog(page, client);
const models = await client.listProviderModels("hoplite", { cwd });
expect(models.error).toBeNull();
expect(models.models!.length).toBeGreaterThan(0);
});
} finally {
await client.close();
await e2eWorkerClient.removeProject(workspace.projectId);
}
});
@@ -0,0 +1,47 @@
import { expect, test, type Page } from "../support/fixtures";
import { composerLocator, submitMessageWithButton } from "../support/helpers/composer";
import { seedMockAgentWorkspace, openAgentRoute } from "../support/helpers/mock-agent";
import { withPopoverTimelinePlugin } from "../support/helpers/plugin-timeline";
async function openPreviewWhileTyping(page: Page): Promise<void> {
await composerLocator(page).focus();
await page.getByRole("button", { name: "Hover plugin preview", exact: true }).hover();
await expect(page.getByRole("dialog", { name: "Plugin preview" })).toBeVisible();
await expect(composerLocator(page)).toBeFocused();
}
async function dismissPreview(page: Page): Promise<void> {
await page.keyboard.press("Escape");
await expect(page.getByRole("dialog", { name: "Plugin preview" })).not.toBeVisible();
}
test("Escape dismisses a plugin preview before interrupting the agent", async ({ page }) => {
test.setTimeout(120_000);
const agent = await seedMockAgentWorkspace({
repoPrefix: "plugin-popover-",
title: "Plugin preview keyboard regression",
model: "e2e-fast-stream",
});
try {
await withPopoverTimelinePlugin(async () => {
await openAgentRoute(page, agent);
await submitMessageWithButton(page, "Show the plugin preview.");
await agent.client.waitForFinish(agent.agentId, 30_000);
await expect(page.getByRole("button", { name: "Hover plugin preview" })).toBeVisible();
await submitMessageWithButton(page, "withhold synthetic user message until interrupted");
const stop = page.getByRole("button", { name: "Stop agent", exact: true });
await expect(stop).toBeVisible();
await openPreviewWhileTyping(page);
await dismissPreview(page);
await expect(stop).toBeVisible();
await expect(composerLocator(page)).toBeFocused();
await page.keyboard.press("Escape");
await expect(stop).not.toBeVisible();
await agent.client.waitForFinish(agent.agentId, 15_000);
});
} finally {
await agent.cleanup();
}
});
@@ -1,6 +1,7 @@
import type { Page } from "@playwright/test";
import { expect, test } from "../support/fixtures";
import { TerminalE2EHarness } from "../support/helpers/terminal-dsl";
import { openCommandCenter, closeCommandCenter } from "../support/helpers/command-center";
interface AttachOverlayProbeWindow extends Window {
__terminalAttachOverlaySeen?: boolean;
@@ -59,4 +60,87 @@ test.describe("retained terminal tab streams", () => {
expect(await terminalAttachOverlayWasSeen(page)).toBe(false);
});
test("workspace number shortcuts refocus a retained terminal", async ({ page }) => {
const first = await harness.createTerminal({ name: "focus-first" });
const other = await harness.createOtherWorkspace();
const second = await other.createTerminal({ name: "focus-second" });
await harness.openTerminal(page, { terminalId: first.id });
await other.openTerminal(page, { terminalId: second.id });
await other.expectTerminalFocused(page);
await harness.switchToWorkspaceByShortcut(page);
await harness.expectTerminalFocused(page);
await other.switchToWorkspaceByShortcut(page);
await other.expectTerminalFocused(page);
await other.typeCommandAndExpectOutput(page, {
terminalId: second.id,
command: "printf 'WORKSPACE_FOCUS_OK\\n'",
output: "WORKSPACE_FOCUS_OK",
});
});
test("closing an overlay after returning to a workspace refocuses its terminal", async ({
page,
}) => {
const first = await harness.createTerminal({ name: "overlay-first" });
const other = await harness.createOtherWorkspace();
const second = await other.createTerminal({ name: "overlay-second" });
await harness.openTerminal(page, { terminalId: first.id });
await other.openTerminal(page, { terminalId: second.id });
await harness.switchToWorkspaceByShortcut(page);
await harness.expectTerminalFocused(page);
await harness.rememberWorkspaceForHistoryReturn(page);
await other.switchToWorkspaceByShortcut(page);
const overlay = await openCommandCenter(page);
await harness.returnToWorkspaceThroughHistory(page);
await expect(overlay.getByTestId("command-center-input")).toBeFocused();
await closeCommandCenter(page);
await harness.expectTerminalFocused(page);
await harness.typeCommandAndExpectOutput(page, {
terminalId: first.id,
command: "printf 'OVERLAY_FOCUS_OK\\n'",
output: "OVERLAY_FOCUS_OK",
});
});
test("moving focus inside an overlay preserves deferred terminal focus", async ({ page }) => {
const first = await harness.createTerminal({ name: "overlay-move-first" });
const other = await harness.createOtherWorkspace();
const second = await other.createTerminal({ name: "overlay-move-second" });
await harness.openTerminal(page, { terminalId: first.id });
await other.openTerminal(page, { terminalId: second.id });
await harness.switchToWorkspaceByShortcut(page);
await harness.expectTerminalFocused(page);
await harness.rememberWorkspaceForHistoryReturn(page);
await other.switchToWorkspaceByShortcut(page);
await openCommandCenter(page);
await harness.returnToWorkspaceThroughHistory(page);
await harness.moveFocusWithinCommandCenter(page);
await closeCommandCenter(page);
await harness.expectTerminalFocused(page);
await harness.typeCommandAndExpectOutput(page, {
terminalId: first.id,
command: "printf 'OVERLAY_MOVE_FOCUS_OK\\n'",
output: "OVERLAY_MOVE_FOCUS_OK",
});
});
test("deferred terminal focus does not steal focus from a button", async ({ page }) => {
const first = await harness.createTerminal({ name: "button-first" });
const other = await harness.createOtherWorkspace();
const second = await other.createTerminal({ name: "button-second" });
await harness.openTerminal(page, { terminalId: first.id });
await other.openTerminal(page, { terminalId: second.id });
await harness.switchToWorkspaceByShortcut(page);
await harness.expectTerminalFocused(page);
await harness.rememberWorkspaceForHistoryReturn(page);
await other.switchToWorkspaceByShortcut(page);
const overlay = await openCommandCenter(page);
await harness.returnToWorkspaceThroughHistory(page);
await expect(overlay.getByTestId("command-center-input")).toBeFocused();
await harness.closeOverlayAndFocusButtonBeforeRetry(page);
await expect(page.getByTestId("sidebar-search")).toBeFocused();
await page.keyboard.press("Enter");
await expect(overlay).toBeVisible();
});
});
@@ -100,6 +100,40 @@ function weeklyReport(sourceId: string, usedPct: number): UsageReportEntry {
};
}
function installReversedUsageRefresh(page: Page) {
const initial = [weeklyReport("opencode", 31), weeklyReport("openai", 12)];
const refreshed = [weeklyReport("openai", 22), weeklyReport("opencode", 41)];
return installUsageReportsFixture(page, {
lists: [(request) => (request.forceRefresh ? refreshed : initial)],
});
}
async function openUsageSummaryAtWidth(page: Page, width: number) {
await page.setViewportSize({ width, height: 900 });
await gotoAppShell(page);
if (width === 390) await openCompactSidebar(page);
await expectPinnedUsage(page, ["31% Weekly", "12% Weekly"]);
await openUsageFromItem(page);
}
async function expectUsageProviderOrder(page: Page, summary: string[]) {
const group = page.getByTestId(`usage-host-${getServerId()}`);
await expect(group.getByText(/^(opencode|openai) plan$/)).toHaveText([
"opencode plan",
"openai plan",
]);
await expectPinnedUsage(page, summary);
}
async function refreshUsageAndWaitForReports(page: Page, usage: UsageReportsFixture) {
const requestCount = usage.listRequests().length;
await refreshAllUsage(page);
await usage.waitForListRequests(requestCount + 1);
const group = page.getByTestId(`usage-host-${getServerId()}`);
await expect(group.getByText("41%", { exact: true })).toBeVisible();
await expect(page.getByRole("button", { name: "Refresh all", exact: true })).toBeEnabled();
}
test.describe("usage modal", () => {
test("opens from the sidebar on the host's reports, with no host filter for one host", async ({
page,
@@ -152,6 +186,21 @@ test.describe("usage modal", () => {
await expect(group.getByTestId("usage-freshness")).toHaveCount(0);
});
for (const width of [1440, 390]) {
test(`keeps sidebar and modal provider order across a reversed refresh at width ${width}`, async ({
page,
}) => {
const usage = await installReversedUsageRefresh(page);
await openUsageSummaryAtWidth(page, width);
await expectUsageProviderOrder(page, ["31% Weekly", "12% Weekly"]);
await qaScreenshot(page, `usage-order-${width}-before-refresh`);
await refreshUsageAndWaitForReports(page, usage);
await expectUsageProviderOrder(page, ["41% Weekly", "22% Weekly"]);
await qaScreenshot(page, `usage-order-${width}-after-refresh`);
});
}
test("refreshes one report from its card", async ({ page }) => {
test.setTimeout(120_000);
const serverId = getServerId();
@@ -30,7 +30,7 @@ import {
openUsageFromIcon,
openUsageFromItem,
pinRow,
scrollUsage,
scrollUsageToWindow,
setSummaryInSidebar,
openUsageOptions,
showUsageAs,
@@ -146,7 +146,9 @@ test.describe("Usage item", () => {
compact: { viewport: COMPACT, showSidebar: openCompactSidebar },
};
for (const [size, { viewport, showSidebar }] of Object.entries(layouts)) {
test(`long usage reports scroll to the final window on ${size}`, async ({ page }) => {
test(`long usage reports scroll between their first and last windows on ${size}`, async ({
page,
}) => {
test.setTimeout(120_000);
const source = await installTallUsageSource();
try {
@@ -161,10 +163,10 @@ test.describe("Usage item", () => {
await waitForSettledPosition(content);
await expect(content.getByText("Window 20", { exact: true })).not.toBeInViewport();
await qaScreenshot(page, `${size}-usage-scroll-top`);
await scrollUsage(page, 5_000);
await scrollUsageToWindow(page, "Window 20");
await expect(content.getByText("Window 20", { exact: true })).toBeInViewport();
await qaScreenshot(page, `${size}-usage-scroll-bottom`);
await scrollUsage(page, -5_000);
await scrollUsageToWindow(page, "Window 1");
await expect(content.getByText("Window 20", { exact: true })).not.toBeInViewport();
} finally {
await source.cleanup();
@@ -0,0 +1,15 @@
# Native compact workspace scripts flow
`native-compact-workspace-scripts.android.ad` covers live script status in the compact ⋯ → Scripts sheet when nothing else keeps the host directory live. Start on a phone with a workspace open, the sidebar closed, and no agent tab selected. A viewed agent tab or the open sidebar hides the failure, because either one keeps the directory subscribed.
The workspace's `paseo.json` needs a long-running plain script, stopped before the run. `SCRIPT` defaults to `worker`:
```json
{ "scripts": { "worker": { "command": "node -e \"setInterval(() => {}, 1000)\"" } } }
```
The flow starts the script, checks that Stop flips its page to Run, runs it again, and checks that Restart brings it back to running with no other interaction. It ends with the script stopped and the sheet dismissed, so it can be replayed.
```sh
agent-device replay packages/app/e2e/mobile/agent-device/native-compact-workspace-scripts.android.ad --platform android --serial emulator-5590 --metro-port 8137
```
@@ -0,0 +1,45 @@
context platform=android timeout=120000 retries=0
env APP_ID=sh.paseo.debug
env SCRIPT=worker
open "${APP_ID}"
wait "id=\"workspace-header-menu-trigger\"" 45000
wait stable 1000 15000
press "id=\"workspace-header-menu-trigger\""
wait "id=\"workspace-header-scripts\"" 10000
press "id=\"workspace-header-scripts\""
wait "id=\"workspace-scripts-row-${SCRIPT}\"" 10000
press "id=\"workspace-scripts-row-${SCRIPT}\""
wait stable 1000 15000
wait "id=\"workspace-header-menu-trigger\"" 10000
press "id=\"workspace-header-menu-trigger\""
wait "id=\"workspace-header-scripts\"" 10000
press "id=\"workspace-header-scripts\""
wait "text" "Running" 10000
press "id=\"workspace-scripts-row-${SCRIPT}\""
wait "id=\"workspace-script-${SCRIPT}-stop\"" 10000
press "id=\"workspace-script-${SCRIPT}-stop\""
wait "id=\"workspace-script-${SCRIPT}-run\"" 10000
press "id=\"workspace-script-${SCRIPT}-run\""
wait stable 1000 15000
wait "id=\"workspace-header-menu-trigger\"" 10000
press "id=\"workspace-header-menu-trigger\""
wait "id=\"workspace-header-scripts\"" 10000
press "id=\"workspace-header-scripts\""
wait "text" "Running" 10000
press "id=\"workspace-scripts-row-${SCRIPT}\""
wait "id=\"workspace-script-${SCRIPT}-restart\"" 10000
press "id=\"workspace-script-${SCRIPT}-restart\""
wait stable 1000 15000
wait "id=\"workspace-header-menu-trigger\"" 10000
press "id=\"workspace-header-menu-trigger\""
wait "id=\"workspace-header-scripts\"" 10000
press "id=\"workspace-header-scripts\""
wait "text" "Running" 15000
press "id=\"workspace-scripts-row-${SCRIPT}\""
wait "id=\"workspace-script-${SCRIPT}-stop\"" 10000
press "id=\"workspace-script-${SCRIPT}-stop\""
wait "id=\"workspace-script-${SCRIPT}-run\"" 10000
back
wait stable 1000 15000
close
@@ -90,3 +90,26 @@ export async function expectNewWorkspaceForAddedProject(
{ timeout: 30_000 },
);
}
export async function navigateAddProjectResults(
page: Page,
key: "ArrowDown" | "ArrowUp",
count: number,
): Promise<void> {
for (let index = 0; index < count; index += 1) await page.keyboard.press(key);
}
export async function expectAddProjectResultVisible(page: Page, text: string): Promise<void> {
const results = page.getByTestId("add-project-flow-results");
const row = results.getByRole("button").filter({ has: page.getByText(text, { exact: true }) });
await expect
.poll(async () => {
const viewport = await results.boundingBox();
const bounds = await row.boundingBox();
if (!viewport || !bounds) return false;
return (
bounds.y >= viewport.y - 1 && bounds.y + bounds.height <= viewport.y + viewport.height + 1
);
})
.toBe(true);
}
@@ -0,0 +1,61 @@
import { expect, type Locator, type Page } from "@playwright/test";
/** The compact ⋯ sheet. Its trigger shares "Workspace actions" with the sidebar row kebabs. */
export function compactWorkspaceMenu(page: Page): Locator {
return page.getByTestId("workspace-header-menu-content");
}
export async function openCompactWorkspaceMenu(page: Page): Promise<void> {
await page.getByTestId("workspace-header-menu-trigger").click();
await expect(compactWorkspaceMenu(page)).toBeVisible({ timeout: 10_000 });
}
export function menuRow(page: Page, name: string | RegExp): Locator {
return compactWorkspaceMenu(page).getByRole("menuitem", { name });
}
/** The root row that leads to the Scripts page; its accessible name carries its value. */
export function scriptsMenuRow(page: Page): Locator {
return menuRow(page, /^Scripts/);
}
/** A row on the Scripts page. A running script's name is followed by "Running". */
export function scriptRow(page: Page, scriptName: string): Locator {
return menuRow(page, new RegExp(`^${scriptName}`));
}
export async function openScriptsPage(page: Page): Promise<void> {
await openCompactWorkspaceMenu(page);
await scriptsMenuRow(page).click();
await expect(scriptsMenuRow(page)).toHaveCount(0);
await expect(backButton(page)).toBeVisible();
}
export async function openRunningScriptPage(page: Page, scriptName: string): Promise<void> {
await openScriptsPage(page);
await scriptRow(page, scriptName).click();
await expect(menuRow(page, "Stop")).toBeVisible();
}
/** Taps a stopped script on the Scripts page, which runs it and closes the sheet. */
export async function runScriptFromScriptsPage(page: Page, scriptName: string): Promise<void> {
await openScriptsPage(page);
await scriptRow(page, scriptName).click();
await expect(compactWorkspaceMenu(page)).toBeHidden({ timeout: 10_000 });
}
export async function goBackInMenu(page: Page): Promise<void> {
await backButton(page).click();
}
export async function closeCompactWorkspaceMenu(page: Page): Promise<void> {
await page
.getByRole("button", { name: "Bottom sheet backdrop" })
.first()
.click({ position: { x: 12, y: 12 } });
await expect(compactWorkspaceMenu(page)).toBeHidden({ timeout: 10_000 });
}
function backButton(page: Page): Locator {
return compactWorkspaceMenu(page).getByRole("button", { name: "Back" });
}
@@ -231,3 +231,46 @@ export async function attachPromptTimelineEvidence(page: Page, info: TestInfo):
contentType: "image/png",
});
}
const POPOVER_CLIENT_SOURCE = `import React, { useEffect, useRef } from "react";
import { z } from "zod";
function Preview() {
const panel = useRef(null);
useEffect(() => {
const close = (event) => {
if (event.key === "Escape" && panel.current.matches(":popover-open")) {
panel.current.hidePopover();
}
};
document.addEventListener("keydown", close, true);
return () => document.removeEventListener("keydown", close, true);
}, []);
return <div>
<button onMouseEnter={() => panel.current.showPopover()}>Hover plugin preview</button>
<div ref={panel} popover="manual" role="dialog" aria-label="Plugin preview">Plugin hover preview</div>
</div>;
}
export default function contribute(client) {
client.addTimelineTransformer({
id: "preview", query: { itemType: "user_message" },
transform({ item }) {
if (item.text !== "Show the plugin preview.") return;
return { items: [{ type: "plugin", kind: "preview", version: 1, data: {} }] };
},
});
client.addTimelineRenderer({
kind: "preview", version: 1, schema: z.object({}), Component: Preview,
});
return () => {};
}`;
/** Installs a timeline preview that owns Escape through the DOM Popover API. */
export async function withPopoverTimelinePlugin(run: () => Promise<void>): Promise<void> {
await withDirectoryPlugin({
pluginId: "timeline-popover-e2e",
source: POPOVER_CLIENT_SOURCE,
run,
});
}
+1 -1
View File
@@ -370,7 +370,7 @@ export async function findAcpCatalogProvider(page: Page, providerName: string):
export async function installAcpCatalogProvider(page: Page, providerName: string): Promise<void> {
await findAcpCatalogProvider(page, providerName);
await page.getByRole("button", { name: "Add", exact: true }).click();
await page.getByRole("button", { name: `Add ${providerName}`, exact: true }).click();
}
export async function expectProviderInstalledInSettings(
@@ -1,4 +1,4 @@
import type { Page } from "@playwright/test";
import { expect, type Page } from "@playwright/test";
import type { TerminalActivity, TerminalActivityState } from "@getpaseo/protocol/terminal-activity";
import { createTempGitRepo } from "./workspace";
import { navigateToTerminal, setupDeterministicPrompt } from "./terminal-perf";
@@ -30,6 +30,7 @@ export class TerminalE2EHarness {
readonly tempRepo: TempRepo;
readonly projectId: string;
readonly workspaceId: string;
private readonly otherWorkspaces: TerminalE2EHarness[] = [];
private constructor(input: {
client: SeedDaemonClient;
@@ -63,6 +64,7 @@ export class TerminalE2EHarness {
}
async cleanup(): Promise<void> {
for (const workspace of this.otherWorkspaces) await workspace.cleanup();
await this.client.removeProject(this.projectId).catch(() => {});
await this.client.close().catch(() => {});
await this.tempRepo.cleanup().catch(() => {});
@@ -131,6 +133,78 @@ export class TerminalE2EHarness {
});
}
async createOtherWorkspace(): Promise<TerminalE2EHarness> {
const workspace = await TerminalE2EHarness.create({ tempPrefix: "terminal-workspace-focus-" });
this.otherWorkspaces.push(workspace);
return workspace;
}
async switchToWorkspaceByShortcut(page: Page): Promise<void> {
const rows = page.locator('[data-testid^="sidebar-workspace-row-"]').filter({ visible: true });
const rowIds = await rows.evaluateAll((elements) =>
elements.map((element) => element.getAttribute("data-testid")),
);
const index = rowIds.findIndex((id) => id?.endsWith(`:${this.workspaceId}`)) + 1;
expect(index).toBeGreaterThan(0);
expect(index).toBeLessThanOrEqual(9);
// Browser Alt+Digit routes the same workspace action as desktop Cmd+Digit.
await page.keyboard.press(`Alt+${index}`);
await expect(page).toHaveURL(new RegExp(`/workspace/${this.workspaceId}`));
}
async rememberWorkspaceForHistoryReturn(page: Page): Promise<void> {
// Workspace shortcuts replace the current route; preserve an in-app history entry.
await page.evaluate(() =>
window.history.pushState(window.history.state, "", window.location.href),
);
}
async returnToWorkspaceThroughHistory(page: Page): Promise<void> {
await page.goBack();
await expect(page).toHaveURL(new RegExp(`/workspace/${this.workspaceId}`));
}
async moveFocusWithinCommandCenter(page: Page): Promise<void> {
const panel = page.getByTestId("command-center-panel");
await expect(panel.getByTestId("command-center-input")).toBeFocused();
await page.keyboard.press("Tab");
await expect(panel.getByRole("button").first()).toBeFocused();
}
async closeOverlayAndFocusButtonBeforeRetry(page: Page): Promise<void> {
// Give the browser clock a fixed origin before pausing it in the future.
await page.clock.install({ time: new Date("2026-01-01T00:00:00Z") });
await page.clock.pauseAt(new Date("2026-01-01T00:01:00Z"));
await page.keyboard.press("Escape");
await expect(page.getByTestId("command-center-panel")).toBeHidden();
await page.getByTestId("sidebar-search").focus();
await page.clock.runFor(100);
await page.clock.resume();
await page.evaluate(
() =>
new Promise<void>((resolve) =>
requestAnimationFrame(() => requestAnimationFrame(() => resolve())),
),
);
}
async expectTerminalFocused(page: Page): Promise<void> {
await expect(
this.terminalSurface(page).filter({ visible: true }).locator(".xterm-helper-textarea"),
).toBeFocused();
}
async typeCommandAndExpectOutput(
page: Page,
input: { terminalId: string; command: string; output: string },
): Promise<void> {
await page.keyboard.type(input.command);
await page.keyboard.press("Enter");
await expect
.poll(async () => (await this.client.captureTerminal(input.terminalId)).lines)
.toContain(input.output);
}
terminalSurface(page: Page) {
return page.locator('[data-testid="terminal-surface"]');
}
@@ -544,7 +544,7 @@ async function readTimelineViewport(page: Page): Promise<TimelineViewportSnapsho
});
}
async function waitForTimelineGeometryToSettle(page: Page): Promise<void> {
export async function waitForTimelineGeometryToSettle(page: Page): Promise<void> {
const scroll = page.locator('[data-testid="agent-chat-scroll"]:visible').first();
await scroll.evaluate(
(element) =>
@@ -297,11 +297,7 @@ export function findScrollJumps(frames: ScrollFrame[]) {
// Follow that intended row, not text now below the image.
const recent = frames.findLast((frame) => frame.at <= previous.at - 100);
const wheelBudget = current.wheelTotal - (recent?.wheelTotal ?? 0);
const frameScroll = Math.max(0, previous.scrollTop - current.scrollTop);
const availableScroll = Math.min(frameScroll, wheelBudget, previous.scrollTop);
const readingLine = 8 - availableScroll;
const currentRows = new Map(current.rows.map((row) => [row.id, row]));
const intendedRow = previous.rows.find((row) => row.top + row.height > readingLine);
const anchor = previous.anchor;
const before = currentRows.has(anchor)
? previous.rows.find((row) => row.id === anchor)!
@@ -316,25 +312,33 @@ export function findScrollJumps(frames: ScrollFrame[]) {
// A busy main thread can deliver wheel movement hundreds of milliseconds
// after its event. Only assert idle stability after the driver stops input.
const idle = current.inputFinishedAt !== null && previous.at - current.inputFinishedAt > 250;
// Wheel events can precede their scroll update, or include input already
// applied in earlier frames. Locate the reader with this frame's scroll,
// bounded by recent input. Growth below it can move the old anchor without
// moving the reading line.
const readerFollowsInput =
intendedRow &&
currentRows.has(intendedRow.id) &&
Math.abs(currentRows.get(intendedRow.id)!.top - intendedRow.top - availableScroll) <= 32;
const enteredRowGrowth = readerFollowsInput
// scrollTop also includes virtualizer estimate corrections. Locate the row
// entered by wheel input from its viewport movement instead. Its old height
// identifies the reader before a simultaneous image resize takes effect.
const intendedRow = previous.rows.find((row) => {
const next = currentRows.get(row.id);
if (!next || idle || wheelBudget <= 0) return false;
const travel = next.top - row.top;
return (
travel >= -8 &&
travel <= Math.min(wheelBudget, previous.scrollTop) + 32 &&
(next.top <= 8 || current.scrollTop === 0) &&
next.top + row.height > 8
);
});
const enteredRowResize = intendedRow
? previous.rows.reduce((growth, row) => {
if (row.top < intendedRow.top || row.top >= before.top) return growth;
const height = currentRows.get(row.id)?.height ?? row.height;
return growth + Math.max(0, height - row.height);
return growth + height - row.height;
}, 0)
: 0;
const excessForward = movement > wheelBudget + enteredRowGrowth + 32;
const readingMovement = movement - enteredRowResize;
const excessForward = readingMovement > wheelBudget + 32;
// Upward wheel input moves the same text DOWN the viewport. A negative move
// is a reversal, independent of legitimate scrollTop compensation on prepend.
if (movement >= -8 && (!idle || Math.abs(movement) <= 8) && !excessForward) return [];
if (readingMovement >= -8 && (!idle || Math.abs(readingMovement) <= 8) && !excessForward)
return [];
return [
{
frame: index,
@@ -212,6 +212,14 @@ export async function scrollUsage(page: Page, deltaY: number): Promise<void> {
await page.mouse.wheel(0, deltaY);
}
/** Reach a window with the wheel even when other reports follow its card. */
export async function scrollUsageToWindow(page: Page, label: string): Promise<void> {
const target = await usageModal(page).getByText(label, { exact: true }).boundingBox();
const viewport = page.viewportSize();
if (!target || !viewport) throw new Error("Usage window must exist before scrolling to it.");
await scrollUsage(page, target.y + target.height / 2 - viewport.height / 2);
}
/** The modal's own Close button. */
export async function closeUsage(page: Page): Promise<void> {
await visible(page, "usage-modal").getByRole("button", { name: "Close", exact: true }).click();
@@ -9,7 +9,11 @@ import android.widget.TextView
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import com.facebook.react.bridge.BridgeReactContext
import com.facebook.react.bridge.JavaOnlyArray
import com.facebook.react.bridge.JavaOnlyMap
import com.facebook.react.soloader.OpenSourceMergedSoMapping
import com.facebook.react.uimanager.DisplayMetricsHolder
import com.facebook.react.uimanager.ReactStylesDiffMap
import com.facebook.react.uimanager.ThemedReactContext
import com.facebook.react.views.scroll.ReactScrollView
import com.facebook.react.views.scroll.ReactScrollViewManager
@@ -47,16 +51,29 @@ class ScrollSelectionTest {
assertNotEquals(before, scroll.scrollY)
}
private fun withScroll(inverted: Boolean, check: (ReactScrollView, TextView) -> Unit) {
@Test fun verticalScaleStillKeepsFocusAndSelectionInPlace() = withScroll(inverted = true, transform = "scaleY") { scroll, text ->
val before = scroll.scrollY
assertTrue(text.requestFocus())
text.requestRectangleOnScreen(Rect(0, 0, 80, 40), true)
assertEquals(before, scroll.scrollY)
}
@Test fun horizontalScaleStillRevealsSelectedText() = withScroll(inverted = true, transform = "scaleX") { scroll, text ->
val before = scroll.scrollY
text.requestRectangleOnScreen(Rect(0, 0, 80, 40), true)
assertNotEquals(before, scroll.scrollY)
}
private fun withScroll(inverted: Boolean, transform: String = "scale", check: (ReactScrollView, TextView) -> Unit) {
val instrumentation = InstrumentationRegistry.getInstrumentation()
instrumentation.runOnMainSync {
val appContext = instrumentation.targetContext
DisplayMetricsHolder.initDisplayMetricsIfNotInitialized(appContext)
SoLoader.init(appContext, OpenSourceMergedSoMapping)
val reactContext = BridgeReactContext(appContext)
val context = ThemedReactContext(reactContext, appContext)
val manager = PaseoScrollPackage().createViewManager(reactContext, ReactScrollViewManager.REACT_CLASS) as ReactScrollViewManager
val scroll = manager.createViewInstance(context)
scroll.scaleY = if (inverted) -1f else 1f
val content = FrameLayout(context)
val text = TextView(context).apply {
setText("Selectable timeline text", TextView.BufferType.SPANNABLE)
@@ -68,6 +85,13 @@ class ScrollSelectionTest {
content.layout(0, 0, 300, 2000)
scroll.measure(exact(300), exact(300))
scroll.layout(0, 0, 300, 300)
// Apply RN's actual Android inversion through the manager's transform decomposition.
val transforms = JavaOnlyArray.of(JavaOnlyMap.of(transform, if (inverted) -1.0 else 1.0))
manager.updateProperties(scroll, ReactStylesDiffMap(JavaOnlyMap.of("transform", transforms)))
if (inverted && transform == "scale") {
assertEquals(1f, scroll.scaleY, 0f)
assertEquals(180f, kotlin.math.abs(scroll.rotation), 0f)
}
scroll.scrollTo(0, 400)
check(scroll, text)
}
@@ -1,5 +1,6 @@
package sh.paseo.scroll
import android.graphics.Matrix
import android.graphics.Rect
import com.facebook.react.ReactPackage
import com.facebook.react.ViewManagerOnDemandReactPackage
@@ -27,9 +28,15 @@ private class PaseoScrollViewManager : ReactScrollViewManager() {
}
private class PaseoScrollView(context: ThemedReactContext) : ReactScrollView(context) {
private val transformValues = FloatArray(9)
// Both RN focus handling and Android selection visibility requests use this calculation.
// Its coordinates ignore inversion. Keep focus/selection bookkeeping, but leave timeline
// movement to user gestures and explicit scroll commands.
override fun computeScrollDeltaToGetChildRectOnScreen(rect: Rect): Int =
if (scaleY < 0) 0 else super.computeScrollDeltaToGetChildRectOnScreen(rect)
override fun computeScrollDeltaToGetChildRectOnScreen(rect: Rect): Int {
// RN's Android scale: -1 becomes a 180-degree rotation with positive scaleY.
matrix.getValues(transformValues)
if (transformValues[Matrix.MSCALE_Y] < 0) return 0
return super.computeScrollDeltaToGetChildRectOnScreen(rect)
}
}
@@ -2,6 +2,9 @@ import type { ReactNode, RefObject } from "react";
import type { StreamItem } from "@/types/stream";
import type { StreamViewportHandle } from "../strategy";
export interface MountedMessageIds {
has(messageId: string): boolean;
}
export interface ChatFindProps {
agentId: string;
serverId: string;
@@ -9,7 +12,7 @@ export interface ChatFindProps {
items: StreamItem[];
viewportRef: RefObject<StreamViewportHandle | null>;
revealLoadedMessage(messageId: string): boolean;
visibleMessageIds: ReadonlySet<string>;
visibleMessageIds: MountedMessageIds;
children: ReactNode;
}
export interface ChatFindExpansionProps {
@@ -178,7 +178,7 @@ describe("useChatOutline", () => {
timelineEpoch,
enabled,
viewportRef,
visibleMessageIds: new Set(),
mountedHistoryMessageIds: new Set(),
onJumpError: vi.fn(),
}),
{
@@ -278,7 +278,7 @@ describe("useChatOutline", () => {
},
];
const { result, rerender } = renderHook(
({ visibleMessageIds }) =>
({ mountedHistoryMessageIds }) =>
useChatOutline({
agentId: "agent-1",
serverId: "server-1",
@@ -288,10 +288,10 @@ describe("useChatOutline", () => {
enabled: true,
viewportRef,
onJumpError: vi.fn(),
visibleMessageIds,
mountedHistoryMessageIds,
revealLoadedMessage,
}),
{ initialProps: { visibleMessageIds: new Set<string>() } },
{ initialProps: { mountedHistoryMessageIds: new Set<string>() } },
);
await waitFor(() => expect(result.current.prompts).toHaveLength(1));
@@ -299,7 +299,7 @@ describe("useChatOutline", () => {
expect(revealLoadedMessage).toHaveBeenCalledWith("older-prompt");
expect(scrollToMessage).not.toHaveBeenCalled();
rerender({ visibleMessageIds: new Set(["older-prompt"]) });
rerender({ mountedHistoryMessageIds: new Set(["older-prompt"]) });
await waitFor(() => expect(scrollToMessage).toHaveBeenCalledWith("older-prompt"));
});
@@ -327,7 +327,7 @@ describe("useChatOutline", () => {
timelineCursor: { epoch: "epoch-1", seq: 1 },
};
const { result, rerender } = renderHook(
({ tail, visibleMessageIds }) =>
({ tail, mountedHistoryMessageIds }) =>
useChatOutline({
agentId: "agent-1",
serverId: "server-1",
@@ -337,13 +337,13 @@ describe("useChatOutline", () => {
enabled: true,
viewportRef,
onJumpError: vi.fn(),
visibleMessageIds,
mountedHistoryMessageIds,
revealLoadedMessage,
}),
{
initialProps: {
tail: [] as (typeof fetchedPrompt)[],
visibleMessageIds: new Set<string>(),
mountedHistoryMessageIds: new Set<string>(),
},
},
);
@@ -352,11 +352,11 @@ describe("useChatOutline", () => {
act(() => result.current.jumpToPrompt(1));
await waitFor(() => expect(runtime.fetchAgentTimeline).toHaveBeenCalledOnce());
rerender({ tail: [fetchedPrompt], visibleMessageIds: new Set<string>() });
rerender({ tail: [fetchedPrompt], mountedHistoryMessageIds: new Set<string>() });
await waitFor(() => expect(revealLoadedMessage).toHaveBeenCalledWith(fetchedPrompt.id));
expect(scrollToMessage).not.toHaveBeenCalled();
rerender({ tail: [fetchedPrompt], visibleMessageIds: new Set([fetchedPrompt.id]) });
rerender({ tail: [fetchedPrompt], mountedHistoryMessageIds: new Set([fetchedPrompt.id]) });
await waitFor(() => expect(scrollToMessage).toHaveBeenCalledOnce());
expect(scrollToMessage).toHaveBeenCalledWith(fetchedPrompt.id);
await act(async () => fetch.resolve());
@@ -392,7 +392,7 @@ describe("useChatOutline", () => {
enabled: true,
viewportRef: { current: viewport },
onJumpError: vi.fn(),
visibleMessageIds: new Set([livePrompt.id]),
mountedHistoryMessageIds: new Set<string>(),
revealLoadedMessage,
}),
);
@@ -1,4 +1,4 @@
import { useCallback, useEffect, useMemo, useRef, useState, type RefObject } from "react";
import { useEffect, useMemo, useRef, useState, type RefObject } from "react";
import type { AgentTimelinePromptIndexPayload } from "@getpaseo/client/internal/daemon-client";
import { isWeb } from "@/constants/platform";
import { useStableEvent } from "@/hooks/use-stable-event";
@@ -33,7 +33,8 @@ export interface UseChatOutlineInput {
enabled: boolean;
viewportRef: RefObject<StreamViewportHandle | null>;
onJumpError: () => void;
visibleMessageIds?: ReadonlySet<string>;
// Message ids of the history the viewport has mounted. Live head messages are always mounted.
mountedHistoryMessageIds?: ReadonlySet<string>;
revealLoadedMessage?: (messageId: string) => boolean;
}
@@ -44,6 +45,24 @@ export interface ChatOutline {
reportReadingPosition: (seq: number | null) => void;
}
function latestPromptSeqIn(items: StreamItem[], timelineEpoch: string | null): number {
let latest = -1;
for (const item of items) {
if (item.kind === "user_message" && item.timelineCursor?.epoch === timelineEpoch) {
latest = Math.max(latest, item.timelineCursor.seq);
}
}
return latest;
}
function findLoadedItem(
tail: StreamItem[],
head: StreamItem[],
predicate: (item: StreamItem) => boolean,
): StreamItem | undefined {
return tail.find(predicate) ?? head.find(predicate);
}
export function useChatOutline({
agentId,
serverId,
@@ -53,7 +72,7 @@ export function useChatOutline({
enabled,
viewportRef,
onJumpError,
visibleMessageIds,
mountedHistoryMessageIds,
revealLoadedMessage,
}: UseChatOutlineInput): ChatOutline {
const [index, setIndex] = useState<AgentTimelinePromptIndexPayload | null>(null);
@@ -62,18 +81,19 @@ export function useChatOutline({
const readingSeqRef = useRef<number | null>(null);
const nextJumpRequestIdRef = useRef(0);
const nextIndexRequestIdRef = useRef(0);
const loadedItems = useMemo(() => [...tail, ...(head ?? NO_STREAM_ITEMS)], [head, tail]);
// A disabled outline (every native viewport) must not pay for the timeline per delta.
const loadedTail = enabled ? tail : NO_STREAM_ITEMS;
const loadedHead = enabled ? (head ?? NO_STREAM_ITEMS) : NO_STREAM_ITEMS;
const prompts = enabled ? (index?.prompts ?? NO_PROMPTS) : NO_PROMPTS;
// The viewed timeline already owns live delivery and reconnect catch-up. Its complete
// loaded items (including rows outside the mounted window) invalidate the prompt index.
const latestPromptSeq = loadedItems.reduce(
(latest, item) =>
item.kind === "user_message" && item.timelineCursor?.epoch === timelineEpoch
? Math.max(latest, item.timelineCursor.seq)
: latest,
-1,
// Only the head changes per streamed delta, so the tail's contribution is memoized.
const tailPromptSeq = useMemo(
() => latestPromptSeqIn(loadedTail, timelineEpoch),
[loadedTail, timelineEpoch],
);
const latestPromptSeq = Math.max(tailPromptSeq, latestPromptSeqIn(loadedHead, timelineEpoch));
useEffect(() => setIndex(null), [agentId, enabled, serverId, timelineEpoch]);
@@ -135,10 +155,18 @@ export function useChatOutline({
useEffect(() => {
if (pendingJump === null) return;
const target = loadedItems.find((item) => item.timelineCursor?.seq === pendingJump.seq);
const target = findLoadedItem(
loadedTail,
loadedHead,
(item) => item.timelineCursor?.seq === pendingJump.seq,
);
if (target) {
if (pendingJump.hasScrolled) return;
if (visibleMessageIds?.has(target.id) === false) {
const isMounted =
mountedHistoryMessageIds === undefined ||
mountedHistoryMessageIds.has(target.id) ||
loadedHead.includes(target);
if (!isMounted) {
revealLoadedMessage?.(target.id);
return;
}
@@ -150,40 +178,48 @@ export function useChatOutline({
return;
}
if (pendingJump.fetchSettled) setPendingJump(null);
}, [loadedItems, pendingJump, revealLoadedMessage, viewportRef, visibleMessageIds]);
}, [
loadedHead,
loadedTail,
mountedHistoryMessageIds,
pendingJump,
revealLoadedMessage,
viewportRef,
]);
const jumpToPrompt = useCallback(
(seq: number) => {
nextJumpRequestIdRef.current += 1;
setPendingJump(null);
const loaded = loadedItems.find((item) => item.timelineCursor?.seq === seq);
if (loaded) {
if (revealLoadedMessage?.(loaded.id)) {
const requestId = nextJumpRequestIdRef.current;
setPendingJump({ requestId, seq, fetchSettled: true, hasScrolled: false });
return;
}
viewportRef.current?.scrollToMessage?.(loaded.id);
const jumpToPrompt = useStableEvent((seq: number) => {
nextJumpRequestIdRef.current += 1;
setPendingJump(null);
const loaded = findLoadedItem(
loadedTail,
loadedHead,
(item) => item.timelineCursor?.seq === seq,
);
if (loaded) {
if (revealLoadedMessage?.(loaded.id)) {
const requestId = nextJumpRequestIdRef.current;
setPendingJump({ requestId, seq, fetchSettled: true, hasScrolled: false });
return;
}
if (!index) return;
const requestId = nextJumpRequestIdRef.current;
setPendingJump({ requestId, seq, fetchSettled: false, hasScrolled: false });
void getHostRuntimeStore()
.fetchAgentTimeline(serverId, agentId, planTimelinePromptJump({ epoch: index.epoch, seq }))
.catch((error: unknown) => {
console.warn("Failed to load a Chat outline window", error);
onJumpError();
})
.finally(() => {
setPendingJump((current) => {
if (current?.requestId !== requestId) return current;
return { ...current, fetchSettled: true };
});
viewportRef.current?.scrollToMessage?.(loaded.id);
return;
}
if (!index) return;
const requestId = nextJumpRequestIdRef.current;
setPendingJump({ requestId, seq, fetchSettled: false, hasScrolled: false });
void getHostRuntimeStore()
.fetchAgentTimeline(serverId, agentId, planTimelinePromptJump({ epoch: index.epoch, seq }))
.catch((error: unknown) => {
console.warn("Failed to load a Chat outline window", error);
onJumpError();
})
.finally(() => {
setPendingJump((current) => {
if (current?.requestId !== requestId) return current;
return { ...current, fetchSettled: true };
});
},
[agentId, index, loadedItems, onJumpError, revealLoadedMessage, serverId, viewportRef],
);
});
});
return { prompts, activePrompt, jumpToPrompt, reportReadingPosition };
}
@@ -0,0 +1,51 @@
import { expect, it } from "vitest";
import { setFlagsFromString } from "node:v8";
import { runInNewContext } from "node:vm";
import { buildAgentStreamRenderModel } from "./model";
import type { StreamItem } from "@/types/stream";
function revealHistory(tail: StreamItem[]): WeakRef<StreamItem[]>[] {
const windows: WeakRef<StreamItem[]>[] = [];
for (let start = tail.length - 20; start >= 20; start -= 20) {
const model = buildAgentStreamRenderModel({
tail,
head: [],
historyStart: start,
platform: "web",
isMobileBreakpoint: false,
isTurnActive: false,
activeTurnStartedAt: null,
});
windows.push(new WeakRef(model.history));
}
return windows;
}
it("releases obsolete history windows and their source timeline", async () => {
setFlagsFromString("--expose_gc");
const gc = runInNewContext("gc") as () => void;
setFlagsFromString("--no-expose_gc");
async function collect() {
for (let i = 0; i < 3; i++) {
await new Promise((resolve) => setTimeout(resolve, 0));
gc();
}
}
let tail: StreamItem[] = Array.from({ length: 1000 }, (_, i) => ({
kind: i % 2 ? "assistant_message" : "user_message",
id: `row-${i}`,
text: "text",
timestamp: new Date(1700000000000 + i * 1000),
}));
const windows = revealHistory(tail);
await collect();
expect(windows.filter((ref) => ref.deref() !== undefined)).toHaveLength(1);
windows.push(...revealHistory(tail));
await collect();
expect(windows.filter((ref) => ref.deref() !== undefined)).toHaveLength(1);
tail = [];
await collect();
expect(windows.every((ref) => ref.deref() === undefined)).toBe(true);
});
@@ -240,4 +240,47 @@ describe("buildAgentStreamRenderModel", () => {
expect(model.turnTiming.byAssistantId.size).toBe(0);
});
it.each(["web", "native"] as const)(
"reuses rendered history and timing across live-head updates inside a history window on %s",
(platform) => {
const at = (seed: number) => new Date(Date.UTC(2026, 0, 1, 0, 0, seed));
const tail: StreamItem[] = [];
for (let index = 0; index < 40; index += 1) {
tail.push(
{ ...userMessage(`u${index}`, 0), timestamp: at(index * 2) },
{ ...assistantMessage(`a${index}`, 0), timestamp: at(index * 2 + 1) },
);
}
const live = (text: string): StreamItem => ({
kind: "assistant_message",
id: "live",
text,
timestamp: at(81),
});
const build = (head: StreamItem[]) =>
buildAgentStreamRenderModel({
isTurnActive: true,
activeTurnStartedAt: tail.at(-2)?.timestamp ?? null,
tail,
head,
platform,
isMobileBreakpoint: false,
historyStart: 60,
});
const first = build([live("live")]);
const second = build([live("live grows")]);
expect(second.history).toBe(first.history);
expect(second.segments.historyMounted).toBe(first.segments.historyMounted);
expect(second.turnTiming.byAssistantId).toBe(first.turnTiming.byAssistantId);
expect(first.history).toHaveLength(20);
expect(first.turnTiming.byAssistantId.has("a29")).toBe(false);
expect(first.turnTiming.byAssistantId.get("a38")).toEqual({
completedAt: tail[77]?.timestamp,
durationMs: 1000,
});
},
);
});
+22 -30
View File
@@ -53,11 +53,29 @@ const splitHistoryCache = new WeakMap<
StreamItem[],
Map<string, Pick<AgentStreamRenderModel, "history" | "segments">>
>();
const turnTimingCache = new WeakMap<
// A streamed delta rebuilds the model with the same tail. Everything below is keyed on
// the rendered tail's identity, so the slice has to be reused, not recomputed.
const renderedTailCache = new WeakMap<
StreamItem[],
WeakMap<StreamItem[], Map<string, StreamTurnTiming>>
{ historyStart: number; rendered: StreamItem[] }
>();
function getRenderedTail(tail: StreamItem[], historyStart: number | undefined): StreamItem[] {
if (!historyStart) {
renderedTailCache.delete(tail);
return tail;
}
const cached = renderedTailCache.get(tail);
if (cached?.historyStart === historyStart) {
return cached.rendered;
}
const rendered = tail.slice(historyStart);
// Revealing older history replaces the previous window, allowing its arrays and
// downstream layouts to be collected while the unchanged source tail stays alive.
renderedTailCache.set(tail, { historyStart, rendered });
return rendered;
}
function getOrderedItems(params: {
cache: WeakMap<StreamItem[], Map<string, StreamItem[]>>;
source: StreamItem[];
@@ -129,32 +147,6 @@ function splitOrderedTail(params: {
return split;
}
function getTurnTiming(params: {
isTurnActive: boolean;
activeTurnStartedAt: Date | null;
tail: StreamItem[];
head: StreamItem[];
}): StreamTurnTiming {
let cachedByHead = turnTimingCache.get(params.tail);
if (!cachedByHead) {
cachedByHead = new WeakMap();
turnTimingCache.set(params.tail, cachedByHead);
}
let cachedByActivity = cachedByHead.get(params.head);
if (!cachedByActivity) {
cachedByActivity = new Map();
cachedByHead.set(params.head, cachedByActivity);
}
const activityKey = `${params.isTurnActive}:${params.activeTurnStartedAt?.getTime() ?? "none"}`;
const cached = cachedByActivity.get(activityKey);
if (cached) {
return cached;
}
const timing = deriveStreamTurnTiming(params);
cachedByActivity.set(activityKey, timing);
return timing;
}
export function buildAgentStreamRenderModel(
input: BuildAgentStreamRenderModelInput,
): AgentStreamRenderModel {
@@ -163,7 +155,7 @@ export function buildAgentStreamRenderModel(
isMobileBreakpoint: input.isMobileBreakpoint,
});
const orderingCacheKey = `${input.platform}:${input.isMobileBreakpoint}`;
const renderedTail = input.historyStart ? input.tail.slice(input.historyStart) : input.tail;
const renderedTail = getRenderedTail(input.tail, input.historyStart);
const orderedTail = getOrderedItems({
cache: orderedTailCache,
source: renderedTail,
@@ -189,7 +181,7 @@ export function buildAgentStreamRenderModel(
platform: input.platform,
isMobileBreakpoint: input.isMobileBreakpoint,
});
const turnTiming = getTurnTiming({
const turnTiming = deriveStreamTurnTiming({
isTurnActive: input.isTurnActive,
activeTurnStartedAt: input.activeTurnStartedAt,
tail: renderedTail,
@@ -1298,6 +1298,8 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
<div style={viewportStyle} data-window-content>
<div
ref={handleScrollContainerRef}
// Let clicks focus the feed for browser keyboard scrolling without adding a Tab stop.
tabIndex={-1}
data-testid="agent-chat-scroll"
data-overlay-scrollbar={scrollEnabled && !isMobileBreakpoint ? "true" : undefined}
id={`agent-chat-scroll-${shouldUseVirtualizer ? "web-dom-virtualized" : "web-dom-scroll"}`}
@@ -0,0 +1,132 @@
import { bench, describe } from "vitest";
import type { StreamItem, ToolCallItem } from "@/types/stream";
import {
prepareToolCallHistory,
projectToolCallDetailLevel,
} from "@/tool-calls/detail-level/projection";
import { findMountedWindowStart, getMountedRecentStreamItems } from "./history-window";
import { layoutStream } from "./layout";
import { buildAgentStreamRenderModel } from "./model";
import { resolveStreamRenderStrategy } from "./strategy-resolver";
// One coalesced delta replaces the stream head. This is the pure work AgentStreamView
// does per delta on a long timeline, without React:
// npx vitest bench --project unit src/agent-stream/stream-tick.bench.ts
const TIMELINE_ITEMS = 2_000;
const TICKS = 200;
function timestamp(seed: number): Date {
return new Date(1_700_000_000_000 + seed * 1000);
}
function toolCall(id: string, seed: number): ToolCallItem {
return {
kind: "tool_call",
id,
timestamp: timestamp(seed),
payload: {
source: "agent",
data: {
provider: "claude",
callId: id,
name: "shell",
status: "completed",
error: null,
detail: { type: "shell", command: id },
},
},
};
}
function buildTimeline(count: number): StreamItem[] {
const items: StreamItem[] = [];
let seed = 0;
while (items.length < count) {
const turn = items.length;
items.push({
kind: "user_message",
id: `u${turn}`,
text: "prompt",
timestamp: timestamp(seed++),
});
items.push(toolCall(`t${turn}a`, seed++));
items.push(toolCall(`t${turn}b`, seed++));
items.push({
kind: "assistant_message",
id: `a${turn}`,
text: "answer",
timestamp: timestamp(seed++),
});
}
return items.slice(0, count);
}
function buildHeads(base: StreamItem[], ticks: number): StreamItem[][] {
let text = "";
const heads: StreamItem[][] = [];
for (let tick = 0; tick < ticks; tick += 1) {
text += "token ";
heads.push([
{
kind: "assistant_message",
id: "live",
text,
timestamp: timestamp(base.length + tick),
},
]);
}
return heads;
}
function runTicks(input: { tail: StreamItem[]; historyStart: number; heads: StreamItem[][] }) {
const { tail, historyStart, heads } = input;
const strategy = resolveStreamRenderStrategy({ platform: "web", isMobileBreakpoint: false });
const prepared = prepareToolCallHistory("overview", tail);
const boundaryId = tail[historyStart]?.id ?? null;
const activeTurnStartedAt = tail.at(-1)?.timestamp ?? null;
for (const head of heads) {
const projected = projectToolCallDetailLevel({
level: "overview",
tail,
head,
preparedHistory: prepared,
isTurnActive: true,
});
const boundaryIndex = boundaryId
? projected.tail.findIndex((item) => item.id === boundaryId)
: -1;
const model = buildAgentStreamRenderModel({
isTurnActive: true,
activeTurnStartedAt,
tail: projected.tail,
head: projected.head,
platform: "web",
isMobileBreakpoint: false,
historyStart: boundaryIndex >= 0 ? boundaryIndex : historyStart,
});
layoutStream({
strategy,
isTurnActive: true,
history: model.history,
liveHead: model.segments.liveHead,
timingByAssistantId: model.turnTiming.byAssistantId,
});
}
}
const tail = buildTimeline(TIMELINE_ITEMS);
const heads = buildHeads(tail, TICKS);
const defaultWindowStart = findMountedWindowStart({
items: tail,
minMountedCount: getMountedRecentStreamItems(),
});
describe(`${TICKS} streamed deltas over a ${TIMELINE_ITEMS}-item timeline`, () => {
bench("default mounted window (recent items only)", () => {
runTicks({ tail, historyStart: defaultWindowStart, heads });
});
bench("history fully revealed (scrolled to top)", () => {
runTicks({ tail, historyStart: 0, heads });
});
});
@@ -70,10 +70,11 @@ export function useStreamHistoryWindow(input: {
boundaryItemId: initialBoundaryItemId,
initialized: items.length > 0,
}));
const boundaryIndex =
window.agentId === agentId && window.boundaryItemId !== null
? items.findIndex((item) => item.id === window.boundaryItemId)
: -1;
const boundaryItemId = window.agentId === agentId ? window.boundaryItemId : null;
const boundaryIndex = useMemo(
() => (boundaryItemId === null ? -1 : items.findIndex((item) => item.id === boundaryItemId)),
[boundaryItemId, items],
);
let start = initialStart;
if (window.agentId === agentId && window.initialized) {
if (window.boundaryItemId === null) {
+16 -11
View File
@@ -607,16 +607,21 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
toast?.error(t("agentStream.historyLoadFailed"));
}, [t, toast]);
// Chat find and the chat outline address messages, and an assistant message is a
// group of block rows, so this is a set of message ids and never of row ids.
const visibleMessageIds = useMemo(
() =>
new Set(
[...baseRenderModel.history, ...baseRenderModel.segments.liveHead].map(
getStreamItemMessageId,
),
),
[baseRenderModel.history, baseRenderModel.segments.liveHead],
// group of block rows, so these hold message ids and never row ids. Only the head
// changes per streamed delta, so the history set is keyed on mounted history alone.
const mountedHistoryMessageIds = useMemo(
() => new Set(baseRenderModel.history.map(getStreamItemMessageId)),
[baseRenderModel.history],
);
const mountedMessageIds = useMemo(() => {
const liveHeadMessageIds = new Set(
baseRenderModel.segments.liveHead.map(getStreamItemMessageId),
);
return {
has: (messageId: string) =>
mountedHistoryMessageIds.has(messageId) || liveHeadMessageIds.has(messageId),
};
}, [baseRenderModel.segments.liveHead, mountedHistoryMessageIds]);
const chatOutline = useChatOutline({
agentId,
serverId: resolvedServerId,
@@ -626,7 +631,7 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
enabled: supportsChatOutline && chatOutlineEnabled,
viewportRef,
onJumpError: handleTimelineHistoryLoadError,
visibleMessageIds,
mountedHistoryMessageIds,
revealLoadedMessage: revealLoadedHistory,
});
@@ -1105,7 +1110,7 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
items={findItems}
viewportRef={viewportRef}
revealLoadedMessage={revealLoadedHistory}
visibleMessageIds={visibleMessageIds}
visibleMessageIds={mountedMessageIds}
>
<ToolCallSheetProvider>
<AssistantSelectionCopySurface style={stylesheet.container}>
@@ -48,6 +48,8 @@ export const ACP_PROVIDER_ICON_SVGS = {
goose:
'<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24">\n <path fill="currentColor" d="M20.9093 19.3861L19.5185 18.2413C18.7624 17.619 18.1189 16.8713 17.6157 16.0313C16.9205 14.8706 15.9599 13.8912 14.8133 13.1735L14.2533 12.8475C14.0614 12.7141 13.9276 12.5062 13.9086 12.2716C13.8963 12.1204 13.9326 11.9852 14.0171 11.8662C14.3087 11.4553 15.896 9.74698 16.1722 9.51845C16.528 9.22442 16.9243 8.97987 17.2921 8.69986C17.3443 8.66 17.3968 8.62035 17.4485 8.57989C17.4503 8.57808 17.4529 8.57668 17.4545 8.57508C17.5725 8.48195 17.6838 8.383 17.7724 8.26563C18.2036 7.76631 18.195 7.3443 18.195 7.3443C18.195 7.3443 18.1954 7.3439 18.1956 7.3437C18.1497 7.23133 17.9847 6.88163 17.6492 6.71759C17.9458 6.71178 18.2805 6.82294 18.4323 6.97156C18.6148 6.68534 18.7328 6.49967 18.9162 6.18762C18.9599 6.11352 18.9831 5.97652 18.8996 5.89981C18.8996 5.89981 18.8992 5.89981 18.8988 5.89981C18.8988 5.89981 18.8988 5.8994 18.8988 5.899C18.8972 5.8974 18.8952 5.8962 18.8936 5.8946C18.892 5.893 18.891 5.89119 18.8892 5.88939C18.8892 5.88939 18.8888 5.88939 18.8884 5.88939C18.8884 5.88939 18.8884 5.88899 18.8884 5.88859C18.885 5.88518 18.8812 5.88258 18.8776 5.87938C18.8754 5.87717 18.8736 5.87457 18.8716 5.87217C18.8692 5.87016 18.8665 5.86836 18.8643 5.86616C18.8609 5.86275 18.8587 5.85855 18.8551 5.85534C18.8551 5.85534 18.8545 5.85514 18.8543 5.85534C18.8543 5.85534 18.8543 5.85494 18.8543 5.85454C18.8527 5.85294 18.8507 5.85174 18.8491 5.85013C18.8475 5.84853 18.8463 5.84653 18.8447 5.84493C18.8447 5.84493 18.8441 5.84473 18.8439 5.84493C18.8439 5.84493 18.8439 5.84453 18.8439 5.84413C18.7672 5.7606 18.6302 5.78384 18.5561 5.8275C18.1503 6.06625 17.7555 6.32322 17.3996 6.54855C17.3996 6.54855 16.9778 6.53973 16.4783 6.97116C16.3607 7.05989 16.2618 7.17125 16.1688 7.28902C16.167 7.29082 16.1654 7.29322 16.164 7.29503C16.1234 7.3465 16.0837 7.39898 16.0441 7.45145C15.7639 7.81939 15.5195 8.21556 15.2255 8.57128C14.9971 8.84768 13.2887 10.4348 12.8777 10.7264C12.7587 10.8109 12.6237 10.8474 12.4723 10.835C12.2379 10.8161 12.0298 10.6821 11.8965 10.4903L11.5704 9.93024C10.8527 8.78318 9.87332 7.82299 8.71264 7.12778C7.87262 6.62466 7.12514 5.98092 6.50264 5.22503L5.35778 3.83421C5.3013 3.76571 5.19314 3.77693 5.15268 3.85585C5.02249 4.10941 4.77393 4.64479 4.58346 5.36483C4.57885 5.38186 4.58286 5.39988 4.59407 5.4135C4.83082 5.69952 5.37901 6.32983 6.03196 6.863C6.07742 6.90005 6.04017 6.97336 5.98369 6.95774C5.42047 6.80432 4.87288 6.55796 4.46308 6.34805C4.42964 6.33103 4.38918 6.35226 4.38437 6.38951C4.32068 6.89985 4.30425 7.46027 4.37155 8.05112C4.37355 8.07035 4.38577 8.08697 4.4036 8.09479C4.87088 8.29808 5.61816 8.59311 6.40269 8.78078C6.45958 8.7944 6.45777 8.87632 6.40029 8.88733C5.78941 9.0023 5.14968 9.02794 4.62973 9.02113C4.59327 9.02073 4.56643 9.05518 4.57625 9.09023C4.6806 9.45896 4.822 9.8339 5.00847 10.2115C5.08559 10.3811 5.16951 10.5475 5.25944 10.7104C5.27486 10.7382 5.3047 10.7548 5.33655 10.7534C5.76577 10.7324 6.28452 10.6871 6.80608 10.595C6.89501 10.5794 6.94268 10.6964 6.86757 10.7466C6.51345 10.9834 6.13571 11.1873 5.7844 11.3551C5.73733 11.3777 5.72211 11.4378 5.75315 11.4797C5.96186 11.7625 6.19139 12.0301 6.44075 12.2794C6.44075 12.2794 7.66853 13.5441 7.70198 13.6432C8.41841 12.9096 9.59612 12.0964 10.8966 11.3864C9.15488 12.8036 8.18387 13.8499 7.69517 14.4444L7.35447 14.9225C7.17742 15.1708 7.02379 15.4346 6.89541 15.7112C6.46579 16.6356 5.75756 18.5051 5.75756 18.5051C5.70328 18.6515 5.74754 18.7959 5.84168 18.89C5.84388 18.8922 5.84609 18.8944 5.84849 18.8964C5.85069 18.8986 5.8527 18.901 5.8549 18.9032C5.94924 18.9976 6.09345 19.0416 6.23986 18.9874C6.23986 18.9874 8.10897 18.2791 9.03371 17.8495C9.31031 17.7211 9.57429 17.5673 9.82245 17.3905L10.349 17.0153C10.6278 16.8166 11.0096 16.8483 11.2517 17.0904L12.4655 18.3042C12.7148 18.5535 12.9824 18.7831 13.2652 18.9918C13.3073 19.0226 13.3672 19.0076 13.3898 18.9605C13.5579 18.6094 13.7618 18.2313 13.9983 17.8774C14.0486 17.8022 14.1657 17.8501 14.1499 17.9388C14.0576 18.4606 14.0127 18.9794 13.9915 19.4084C13.9899 19.44 14.0067 19.4701 14.0345 19.4855C14.1972 19.5756 14.3636 19.6595 14.5335 19.7364C14.911 19.9229 15.2862 20.0645 15.6547 20.1687C15.6897 20.1785 15.7242 20.1516 15.7238 20.1152C15.7168 19.595 15.7424 18.9553 15.8576 18.3446C15.8684 18.2869 15.9503 18.2851 15.9641 18.3422C16.1516 19.127 16.4466 19.8742 16.6501 20.3413C16.6579 20.3591 16.6744 20.3712 16.6938 20.3734C17.2847 20.4407 17.8451 20.4242 18.3554 20.3606C18.3929 20.3559 18.4141 20.3155 18.3969 20.2818C18.187 19.872 17.9406 19.3241 17.7872 18.7612C17.7718 18.7046 17.8449 18.6675 17.8819 18.713C18.4151 19.3659 19.0454 19.9141 19.3314 20.1508C19.345 20.1621 19.3633 20.1659 19.3801 20.1615C20.1003 19.9712 20.6357 19.7226 20.8891 19.5922C20.968 19.5518 20.9792 19.4436 20.9107 19.3871L20.9093 19.3861Z"/>\n</svg>\n',
grok: '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 1024 1024" fill="none">\n <path fill="currentColor" d="M395.479 633.828L735.91 381.105C752.599 368.715 776.454 373.548 784.406 392.792C826.26 494.285 807.561 616.253 724.288 699.996C641.016 783.739 525.151 802.104 419.247 760.277L303.556 814.143C469.49 928.202 670.987 899.995 796.901 773.282C896.776 672.843 927.708 535.937 898.785 412.476L899.047 412.739C857.105 231.37 909.358 158.874 1016.4 10.6326C1018.93 7.11771 1021.47 3.60279 1024 0L883.144 141.651V141.212L395.392 633.916"/>\n <path fill="currentColor" d="M325.226 695.251C206.128 580.84 226.662 403.776 328.285 301.668C403.431 226.097 526.549 195.254 634.026 240.596L749.454 186.994C728.657 171.88 702.007 155.623 671.424 144.2C533.19 86.9942 367.693 115.465 255.323 228.382C147.234 337.081 113.244 504.215 171.613 646.833C215.216 753.423 143.739 828.818 71.7385 904.916C46.2237 931.893 20.6216 958.87 0 987.429L325.139 695.339"/>\n</svg>\n',
hoplite:
'<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="1.394 1.679 8.494 7.828" fill="currentColor"><path d="M8.237 7.813C8.276 7.789 8.327 7.796 8.358 7.83L9.741 9.346C9.797 9.407 9.754 9.506 9.671 9.507H8.977C8.924 9.507 8.881 9.463 8.881 9.41V9.125C8.881 9.089 8.861 9.057 8.83 9.04L7.589 8.379C7.524 8.344 7.521 8.251 7.584 8.212L8.237 7.813ZM3.944 1.679C4.502 1.679 5.052 1.82 5.54 2.09L5.962 2.323C6.024 2.358 6.029 2.446 5.97 2.486L5.091 3.09C5.065 3.108 5.05 3.137 5.05 3.169V3.495C5.05 3.529 5.032 3.561 5.003 3.578L4.68 3.769C4.594 3.82 4.498 3.722 4.549 3.637L4.592 3.566C4.63 3.502 4.584 3.421 4.51 3.421H4.028C3.925 3.421 3.894 3.562 3.989 3.604L4.377 3.775C4.448 3.806 4.455 3.904 4.389 3.944L3.77 4.323C3.755 4.332 3.737 4.337 3.72 4.337H3.361C3.309 4.337 3.268 4.379 3.268 4.431C3.268 4.484 3.309 4.526 3.361 4.526H3.779C3.797 4.526 3.814 4.521 3.829 4.513L7.599 2.272C8.135 1.954 8.815 2.008 9.294 2.407C9.307 2.418 9.314 2.434 9.314 2.451V2.729C9.315 2.812 9.413 2.856 9.475 2.8L9.728 2.57C9.789 2.514 9.888 2.558 9.888 2.641V5.812C9.888 5.865 9.845 5.908 9.792 5.908H9.359C9.331 5.908 9.303 5.895 9.285 5.873L8.374 4.773C8.337 4.728 8.268 4.728 8.229 4.771L7.468 5.625C7.429 5.669 7.438 5.737 7.487 5.769L9.038 6.776C9.098 6.815 9.096 6.903 9.035 6.939L6.618 8.363C6.556 8.4 6.478 8.358 6.474 8.286L6.439 7.633C6.437 7.578 6.48 7.532 6.535 7.532H6.925C6.948 7.532 6.971 7.523 6.988 7.508L7.211 7.31C7.276 7.252 7.236 7.144 7.148 7.142L5.991 7.118H1.49C1.437 7.118 1.394 7.075 1.394 7.022V3.308C1.394 3.255 1.437 3.212 1.49 3.212H2.544C2.597 3.212 2.64 3.169 2.64 3.116V2.969C2.64 2.916 2.597 2.873 2.544 2.873H1.461C1.366 2.873 1.329 2.75 1.408 2.697L2.134 2.221C2.672 1.867 3.301 1.679 3.944 1.679Z"/></svg>\n',
junie:
'<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 40 40" fill="none">\n <path d="M25 15H35V16.75C35 29 30.5001 35 16.5001 35H15V25H16.5001C22.6251 25 25 22.875 25 16.75V15Z" fill="currentColor"/>\n <rect x="5" y="15" width="10" height="10" fill="currentColor"/>\n <rect x="15" y="5" width="10" height="10" fill="currentColor"/>\n</svg>\n',
kilo: '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 40 40">\n <path fill="currentColor" d="M27.9998324,34.6666921h6.6666279v5.3333023h-8.3809037l-3.6190266-3.6190266v-8.3809037h5.3333023v6.6666279ZM39.9997627,26.2857884l-3.6190266-3.6190266h-8.3809037v5.3333023h6.6666279v6.6666279h5.3333023v-8.3809037ZM17.3332326,22.6667578h-5.3333023v5.3333023h5.3333023v-5.3333023ZM0,36.3809638l3.6190266,3.6190266h13.714206v-5.3333023H5.3333023v-11.9999302H0v13.714206ZM33.9600959,11.9999247V3.619021L30.3410693-.0000056h-7.6745392v5.3333023h5.9602634v6.6666279h-5.9602634v5.3333023h17.3332326v-5.3333023h-6.0396668ZM5.3333023,0H0v17.3332326h5.3333023v-5.9999651h6.6666279v5.9999651h5.3333023v-5.9999651l-5.3333023-5.3333023h-6.6666279V0ZM17.3332326,0h-5.3333023v5.9999651h5.3333023V0Z"/>\n</svg>\n',
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="1.394 1.679 8.494 7.828" fill="currentColor"><path d="M8.237 7.813C8.276 7.789 8.327 7.796 8.358 7.83L9.741 9.346C9.797 9.407 9.754 9.506 9.671 9.507H8.977C8.924 9.507 8.881 9.463 8.881 9.41V9.125C8.881 9.089 8.861 9.057 8.83 9.04L7.589 8.379C7.524 8.344 7.521 8.251 7.584 8.212L8.237 7.813ZM3.944 1.679C4.502 1.679 5.052 1.82 5.54 2.09L5.962 2.323C6.024 2.358 6.029 2.446 5.97 2.486L5.091 3.09C5.065 3.108 5.05 3.137 5.05 3.169V3.495C5.05 3.529 5.032 3.561 5.003 3.578L4.68 3.769C4.594 3.82 4.498 3.722 4.549 3.637L4.592 3.566C4.63 3.502 4.584 3.421 4.51 3.421H4.028C3.925 3.421 3.894 3.562 3.989 3.604L4.377 3.775C4.448 3.806 4.455 3.904 4.389 3.944L3.77 4.323C3.755 4.332 3.737 4.337 3.72 4.337H3.361C3.309 4.337 3.268 4.379 3.268 4.431C3.268 4.484 3.309 4.526 3.361 4.526H3.779C3.797 4.526 3.814 4.521 3.829 4.513L7.599 2.272C8.135 1.954 8.815 2.008 9.294 2.407C9.307 2.418 9.314 2.434 9.314 2.451V2.729C9.315 2.812 9.413 2.856 9.475 2.8L9.728 2.57C9.789 2.514 9.888 2.558 9.888 2.641V5.812C9.888 5.865 9.845 5.908 9.792 5.908H9.359C9.331 5.908 9.303 5.895 9.285 5.873L8.374 4.773C8.337 4.728 8.268 4.728 8.229 4.771L7.468 5.625C7.429 5.669 7.438 5.737 7.487 5.769L9.038 6.776C9.098 6.815 9.096 6.903 9.035 6.939L6.618 8.363C6.556 8.4 6.478 8.358 6.474 8.286L6.439 7.633C6.437 7.578 6.48 7.532 6.535 7.532H6.925C6.948 7.532 6.971 7.523 6.988 7.508L7.211 7.31C7.276 7.252 7.236 7.144 7.148 7.142L5.991 7.118H1.49C1.437 7.118 1.394 7.075 1.394 7.022V3.308C1.394 3.255 1.437 3.212 1.49 3.212H2.544C2.597 3.212 2.64 3.169 2.64 3.116V2.969C2.64 2.916 2.597 2.873 2.544 2.873H1.461C1.366 2.873 1.329 2.75 1.408 2.697L2.134 2.221C2.672 1.867 3.301 1.679 3.944 1.679Z"/></svg>

After

Width:  |  Height:  |  Size: 1.7 KiB

@@ -19,6 +19,7 @@ import {
useRef,
useState,
type ComponentType,
type RefObject,
} from "react";
import {
Modal,
@@ -71,6 +72,7 @@ import {
type ProjectPickerOption,
} from "@/components/project-picker-options";
import { Shortcut } from "@/components/ui/shortcut";
import { useRevealActiveItem } from "@/components/ui/scroll-reveal";
import { useKeyboardShortcutsAvailable } from "@/keyboard/availability";
import { getIsElectronRuntime } from "@/constants/layout";
import { isNative, isWeb } from "@/constants/platform";
@@ -252,7 +254,17 @@ function pathTestId(path: string): string {
return `add-project-flow-path-${encodeURIComponent(path)}`;
}
function FlowRow({ option, active }: { option: FlowRowOption; active: boolean }) {
function FlowRow({
option,
active,
activeItemRef,
onRowLayout,
}: {
option: FlowRowOption;
active: boolean;
activeItemRef: RefObject<View | null>;
onRowLayout: () => void;
}) {
const accessibilityState = useMemo(
() => ({ disabled: option.disabled === true, selected: active }),
[active, option.disabled],
@@ -270,6 +282,8 @@ function FlowRow({ option, active }: { option: FlowRowOption; active: boolean })
accessibilityRole="button"
accessibilityState={accessibilityState}
disabled={option.disabled}
ref={active ? activeItemRef : undefined}
onLayout={active ? onRowLayout : undefined}
onPress={option.select}
style={rowStyle}
testID={option.testID}
@@ -384,6 +398,7 @@ export function AddProjectFlow({ request, onClose }: AddProjectFlowProps) {
);
const setHasHydratedWorkspaces = useSessionStore((store) => store.setHasHydratedWorkspaces);
const inputRef = useRef<EditingTextInputHandle>(null);
const resultsRef = useRef<ScrollView>(null);
const submissionInFlightRef = useRef(false);
const browseInFlightRef = useRef(false);
const query = page.kind === "new-directory-name" || page.kind === "method" ? "" : page.query;
@@ -715,6 +730,13 @@ export function AddProjectFlow({ request, onClose }: AddProjectFlowProps) {
]);
const activeIndex = rows.length === 0 ? 0 : Math.min(page.activeIndex, rows.length - 1);
const rowListKey = useMemo(() => rows.map((row) => row.id).join("\u0000"), [rows]);
const { activeItemRef, contentRef, onItemLayout, onViewportLayout, onScroll } =
useRevealActiveItem({
activeIndex,
listKey: rowListKey,
scrollRef: resultsRef,
});
const createDirectory = useCallback(async () => {
if (page.kind !== "new-directory-name" || !client) return;
const name = page.name.trim();
@@ -905,53 +927,64 @@ export function AddProjectFlow({ request, onClose }: AddProjectFlowProps) {
) : null}
</View>
<ScrollView
ref={resultsRef}
style={styles.results}
contentContainerStyle={styles.resultsContent}
keyboardShouldPersistTaps="always"
onLayout={onViewportLayout}
onScroll={onScroll}
scrollEventThrottle={16}
showsVerticalScrollIndicator={false}
testID="add-project-flow-results"
>
{preview ? (
<Text style={styles.preview} testID="add-project-flow-path-preview">
{shortenPath(preview)}
</Text>
) : null}
{isSubmitting ? (
<Text style={styles.stateText} testID="add-project-flow-progress">
{progressText(page)}
</Text>
) : null}
{!isSubmitting && page.error ? (
<Text style={styles.errorText} testID="add-project-flow-error">
{page.error}
</Text>
) : null}
{!isSubmitting && queryError ? (
<Text style={styles.errorText} testID="add-project-flow-query-error">
{queryError}
</Text>
) : null}
{!isSubmitting && loading ? (
<Text style={styles.stateText} testID="add-project-flow-loading">
Loading...
</Text>
) : null}
{!isSubmitting &&
(!loading || page.kind === "github-search") &&
(!queryError || page.kind === "github-search")
? rows.map((option, index) => (
<FlowRow key={option.id} option={option} active={index === activeIndex} />
))
: null}
{!isSubmitting &&
!loading &&
!queryError &&
rows.length === 0 &&
page.kind !== "new-directory-name" ? (
<Text style={styles.stateText} testID="add-project-flow-empty">
{emptyText(page, host ?? null)}
</Text>
) : null}
<View ref={contentRef} collapsable={false} style={styles.resultsContent}>
{preview ? (
<Text style={styles.preview} testID="add-project-flow-path-preview">
{shortenPath(preview)}
</Text>
) : null}
{isSubmitting ? (
<Text style={styles.stateText} testID="add-project-flow-progress">
{progressText(page)}
</Text>
) : null}
{!isSubmitting && page.error ? (
<Text style={styles.errorText} testID="add-project-flow-error">
{page.error}
</Text>
) : null}
{!isSubmitting && queryError ? (
<Text style={styles.errorText} testID="add-project-flow-query-error">
{queryError}
</Text>
) : null}
{!isSubmitting && loading ? (
<Text style={styles.stateText} testID="add-project-flow-loading">
Loading...
</Text>
) : null}
{!isSubmitting &&
(!loading || page.kind === "github-search") &&
(!queryError || page.kind === "github-search")
? rows.map((option, index) => (
<FlowRow
key={option.id}
option={option}
activeItemRef={activeItemRef}
active={index === activeIndex}
onRowLayout={onItemLayout}
/>
))
: null}
{!isSubmitting &&
!loading &&
!queryError &&
rows.length === 0 &&
page.kind !== "new-directory-name" ? (
<Text style={styles.stateText} testID="add-project-flow-empty">
{emptyText(page, host ?? null)}
</Text>
) : null}
</View>
</ScrollView>
<View style={styles.footer} testID="add-project-flow-footer">
<FlowHint keys={NAVIGATION_HINT_KEYS} action="Navigate" />
@@ -1,11 +1,12 @@
import { useCallback, useId, useState, type ReactNode } from "react";
import { useCallback, useState, type ReactNode } from "react";
import { View, type LayoutChangeEvent } from "react-native";
import Svg, { Defs, LinearGradient as SvgLinearGradient, Rect, Stop } from "react-native-svg";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import type { Theme } from "@/styles/theme";
import { StyleSheet } from "react-native-unistyles";
import { EdgeFade } from "@/components/ui/edge-fade";
/** How far the fade runs past the header's bottom edge, so content dissolves instead of clipping. */
const FADE_OVERHANG = 24;
const FADE_OVERHANG = 48;
/** Share of the fade that stays opaque, so the header's title and icons keep contrast. */
const FADE_SOLID_FRACTION = 0.57;
interface FloatingHeaderLayoutProps {
header: ReactNode;
@@ -29,51 +30,22 @@ export function FloatingHeaderLayout({ header, floating, children }: FloatingHea
{floating ? null : header}
<View style={styles.content}>{children(floating ? headerHeight : 0)}</View>
{floating ? (
<View style={styles.overlay} pointerEvents="box-none" onLayout={handleHeaderLayout}>
<FloatingHeaderFade />
{header}
<View style={styles.overlay} pointerEvents="box-none">
<EdgeFade
edge="top"
solidFraction={FADE_SOLID_FRACTION}
backdrop="surfaceWorkspace"
style={styles.fade}
/>
<View pointerEvents="box-none" onLayout={handleHeaderLayout}>
{header}
</View>
</View>
) : null}
</View>
);
}
function FloatingHeaderFadeSvg({ gradientId, color }: { gradientId: string; color: string }) {
return (
<Svg width="100%" height="100%" preserveAspectRatio="none">
<Defs>
<SvgLinearGradient id={gradientId} x1="0%" y1="0%" x2="0%" y2="100%">
{/* Vary opacity rather than interpolating toward `transparent`, which crosses black in
some engines and leaves a grey fringe. */}
<Stop offset="0%" stopColor={color} stopOpacity={1} />
<Stop offset="50%" stopColor={color} stopOpacity={0.97} />
<Stop offset="75%" stopColor={color} stopOpacity={0.8} />
<Stop offset="100%" stopColor={color} stopOpacity={0} />
</SvgLinearGradient>
</Defs>
<Rect x="0" y="0" width="100%" height="100%" fill={`url(#${gradientId})`} />
</Svg>
);
}
const ThemedFloatingHeaderFadeSvg = withUnistyles(FloatingHeaderFadeSvg);
const workspaceSurfaceColorMapping = (theme: Theme) => ({
color: theme.colors.surfaceWorkspace,
});
function FloatingHeaderFade() {
// React-generated ids contain characters that are invalid inside SVG fragment references.
const gradientId = `floating-header-fade-${useId().replace(/[^a-zA-Z0-9_-]/g, "")}`;
return (
<View style={styles.fade} pointerEvents="none">
<ThemedFloatingHeaderFadeSvg
gradientId={gradientId}
uniProps={workspaceSurfaceColorMapping}
/>
</View>
);
}
const styles = StyleSheet.create({
root: {
flex: 1,
@@ -88,12 +60,14 @@ const styles = StyleSheet.create({
top: 0,
left: 0,
right: 0,
// The fade's tail lives inside the overlay so Android does not clip it.
paddingBottom: FADE_OVERHANG,
},
fade: {
position: "absolute",
top: 0,
left: 0,
right: 0,
bottom: -FADE_OVERHANG,
bottom: 0,
},
});
@@ -17,7 +17,6 @@ import type { ShortcutKey } from "@/utils/format-shortcut";
const ThemedArrowLeft = withUnistyles(ArrowLeft);
const ISLAND_PADDING = 7;
const NO_SHORTCUT: ShortcutKey[] = [];
interface CompactHeaderProps {
@@ -37,8 +36,9 @@ interface CompactHeaderProps {
/**
* The phone header: the navigation button and the screen's actions sit in islands, with the title
* left-aligned between them. It has no background of its own, so it reads the same in flow and floating
* over content (see `FloatingHeaderLayout`). Its height matches the old flat header, so anything
* left-aligned between them. Neither the header nor its islands draw a background, so it reads the
* same in flow and floating over content (see `FloatingHeaderLayout`, whose fade gives the icons
* contrast). Its height matches the old flat header, so anything
* offset by the header height still lines up.
*/
export function CompactHeader({
@@ -90,7 +90,11 @@ function CompactHeaderTitle({
return (
<>
{title ? (
<Text style={styles.title} numberOfLines={1} testID={titleTestID}>
<Text
style={subtitle ? styles.title : styles.singleLineTitle}
numberOfLines={1}
testID={titleTestID}
>
{title}
</Text>
) : null}
@@ -146,10 +150,6 @@ const styles = StyleSheet.create((theme) => ({
island: {
flexDirection: "row",
alignItems: "center",
padding: ISLAND_PADDING,
borderRadius: theme.borderRadius.full,
backgroundColor: theme.colors.surface2,
...theme.shadow.sm,
},
title: {
fontSize: theme.fontSize.base,
@@ -157,6 +157,13 @@ const styles = StyleSheet.create((theme) => ({
color: theme.colors.foreground,
textAlign: "left",
},
// A title without a subtitle has the header to itself, so it reads one step larger.
singleLineTitle: {
fontSize: theme.fontSize.lg,
fontWeight: theme.fontWeight.medium,
color: theme.colors.foreground,
textAlign: "left",
},
titleSkeleton: {
width: 140,
maxWidth: "100%",
@@ -1,19 +1,21 @@
import { useCallback, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { Pressable, Text, View } from "react-native";
import { Text, View, type LayoutChangeEvent } from "react-native";
import { SvgXml } from "react-native-svg";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { ExternalLink, PackagePlus, Search } from "lucide-react-native";
import { PackagePlus } from "lucide-react-native";
import { Button } from "@/components/ui/button";
import { isWeb } from "@/constants/platform";
import { ExternalLink } from "@/components/ui/external-link";
import { SearchField } from "@/components/ui/search-field";
import { StatusBadge } from "@/components/ui/status-badge";
import { rankProviderCatalog } from "@/components/provider-catalog-search";
import {
useAcpProviderCatalog,
type AcpProviderCatalogItem,
} from "@/hooks/use-acp-provider-catalog";
import { useProvidersSnapshot } from "@/hooks/use-providers-snapshot";
import type { Theme } from "@/styles/theme";
import { openExternalUrl } from "@/utils/open-external-url";
import { EditingTextInput as TextInput } from "@/components/ui/text-input";
import { SPACING, type Theme } from "@/styles/theme";
import { settingsStyles } from "@/styles/settings";
interface ProviderCatalogListProps {
serverId: string;
@@ -21,52 +23,43 @@ interface ProviderCatalogListProps {
onInstall: (entry: AcpProviderCatalogItem) => Promise<void> | void;
}
const SEARCH_ICON_SIZE = 16;
const PROVIDER_FALLBACK_ICON_SIZE = 20;
const PROVIDER_REMOTE_ICON_SIZE = 24;
const TILE_GAP = SPACING[3];
/** Narrowest tile that keeps the icon, type badge, install link, and Add on one row. */
const MIN_TILE_WIDTH = 300;
const MAX_COLUMNS = 4;
const ThemedPackagePlus = withUnistyles(PackagePlus);
const ThemedSvgXml = withUnistyles(SvgXml);
const ThemedSearch = withUnistyles(Search);
const ThemedExternalLink = withUnistyles(ExternalLink);
const ThemedTextInput = withUnistyles(TextInput, (theme) => ({
placeholderTextColor: theme.colors.foregroundMuted,
}));
const foregroundColorMapping = (theme: Theme) => ({ color: theme.colors.foreground });
const foregroundMutedColorMapping = (theme: Theme) => ({
color: theme.colors.foregroundMuted,
});
function matchesSearch(entry: AcpProviderCatalogItem, query: string): boolean {
const normalized = query.trim().toLowerCase();
if (!normalized) return true;
return [entry.title, entry.id, entry.description].some((value) =>
value.toLowerCase().includes(normalized),
);
function columnCountForWidth(width: number): number {
const fits = Math.floor((width + TILE_GAP) / (MIN_TILE_WIDTH + TILE_GAP));
return Math.min(MAX_COLUMNS, Math.max(1, fits));
}
interface CatalogRowProps {
interface CatalogTileProps {
entry: AcpProviderCatalogItem;
/** `undefined` until the grid is measured, or in a single column; the tile fills the row. */
width: number | undefined;
installing: boolean;
onInstall: (entry: AcpProviderCatalogItem) => void;
}
function CatalogRow({ entry, installing, onInstall }: CatalogRowProps) {
function CatalogTile({ entry, width, installing, onInstall }: CatalogTileProps) {
const { t } = useTranslation();
const actionLabel = installing
? t("providerCatalog.actions.adding")
: t("providerCatalog.actions.add");
const handleInstall = useCallback(() => {
onInstall(entry);
}, [entry, onInstall]);
const handleOpenInstallLink = useCallback(() => {
void openExternalUrl(entry.installLink);
}, [entry.installLink]);
const tileStyle = useMemo(
() => [settingsStyles.card, styles.tile, width === undefined ? styles.tileFull : { width }],
[width],
);
return (
<View style={styles.row}>
<View style={tileStyle} testID={`provider-catalog-tile-${entry.id}`}>
<View style={styles.iconFrame}>
{entry.iconSvg ? (
<ThemedSvgXml
@@ -79,42 +72,33 @@ function CatalogRow({ entry, installing, onInstall }: CatalogRowProps) {
<ThemedPackagePlus size={PROVIDER_FALLBACK_ICON_SIZE} uniProps={foregroundColorMapping} />
)}
</View>
<View style={styles.textColumn}>
<View style={styles.titleRow}>
<Text style={styles.name} numberOfLines={1}>
{entry.title}
</Text>
<Text style={styles.version} numberOfLines={1}>
{entry.version}
</Text>
</View>
<Text style={styles.description} numberOfLines={1}>
{entry.description || entry.id}
<View style={styles.details}>
<Text style={styles.name} numberOfLines={1}>
{entry.title}
</Text>
<Pressable
accessibilityRole="link"
accessibilityLabel={t("providerCatalog.actions.installInstructionsFor", {
provider: entry.title,
})}
onPress={handleOpenInstallLink}
style={styles.installLink}
>
<Text style={styles.installLinkText} numberOfLines={1}>
{t("providerCatalog.actions.installInstructions")}
</Text>
<ThemedExternalLink size={12} uniProps={foregroundMutedColorMapping} />
</Pressable>
<View style={styles.metaRow}>
{/* The catalog is the ACP registry, so every entry it offers is an ACP provider. */}
<StatusBadge label={t("providerCatalog.types.acp")} size="xs" />
<ExternalLink
href={entry.installLink}
label={t("providerCatalog.actions.installInstructions")}
accessibilityLabel={t("providerCatalog.actions.installInstructionsFor", {
provider: entry.title,
})}
/>
</View>
</View>
<Button
size="sm"
variant="default"
size="xs"
variant="outline"
disabled={installing}
loading={installing}
onPress={handleInstall}
style={styles.actionButton}
accessibilityLabel={t("providerCatalog.actions.addProvider", { provider: entry.title })}
style={styles.addButton}
testID={`install-provider-${entry.id}`}
>
{actionLabel}
{installing ? t("providerCatalog.actions.adding") : t("providerCatalog.actions.add")}
</Button>
</View>
);
@@ -129,6 +113,7 @@ export function ProviderCatalogList({
const { entries: catalogEntries } = useAcpProviderCatalog();
const { entries: providerEntries } = useProvidersSnapshot(serverId);
const [search, setSearch] = useState("");
const [gridWidth, setGridWidth] = useState<number | null>(null);
const installedIds = useMemo(
() => new Set(providerEntries?.map((entry) => entry.provider) ?? []),
@@ -137,41 +122,48 @@ export function ProviderCatalogList({
const availableEntries = useMemo(
() =>
catalogEntries
.filter((entry) => !installedIds.has(entry.id))
.filter((entry) => matchesSearch(entry, search)),
rankProviderCatalog(
catalogEntries.filter((entry) => !installedIds.has(entry.id)),
search,
),
[catalogEntries, installedIds, search],
);
const handleGridLayout = useCallback((event: LayoutChangeEvent) => {
setGridWidth(event.nativeEvent.layout.width);
}, []);
const tileWidth = useMemo(() => {
if (gridWidth === null) return undefined;
const columns = columnCountForWidth(gridWidth);
if (columns === 1) return undefined;
return Math.floor((gridWidth - TILE_GAP * (columns - 1)) / columns);
}, [gridWidth]);
return (
<View>
<View style={styles.searchField}>
<View style={styles.searchIcon}>
<ThemedSearch size={SEARCH_ICON_SIZE} uniProps={foregroundMutedColorMapping} />
</View>
<ThemedTextInput
testID="provider-catalog-search"
initialValue={search}
<View style={styles.searchRail}>
<SearchField
value={search}
onChangeText={setSearch}
accessibilityLabel={t("providerCatalog.search")}
placeholder={t("providerCatalog.search")}
// @ts-expect-error - outlineStyle is web-only
style={[styles.searchInput, isWeb && { outlineStyle: "none" }]}
autoCapitalize="none"
autoCorrect={false}
clearAccessibilityLabel={t("providerCatalog.clearSearch")}
testID="provider-catalog-search"
clearTestID="provider-catalog-search-clear"
/>
</View>
{availableEntries.length === 0 ? (
<View style={styles.stateBox}>
<View style={[settingsStyles.card, styles.stateBox]}>
<Text style={styles.stateText}>{t("providerCatalog.noProviders")}</Text>
</View>
) : (
<View style={styles.list}>
<View style={styles.grid} onLayout={handleGridLayout}>
{availableEntries.map((entry) => (
<CatalogRow
<CatalogTile
key={entry.id}
entry={entry}
width={tileWidth}
installing={installingProviderId === entry.id}
onInstall={onInstall}
/>
@@ -183,101 +175,56 @@ export function ProviderCatalogList({
}
const styles = StyleSheet.create((theme) => ({
searchField: {
searchRail: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[2],
backgroundColor: theme.colors.surface2,
borderRadius: theme.borderRadius.lg,
borderWidth: 1,
borderColor: theme.colors.border,
paddingHorizontal: theme.spacing[3],
marginBottom: theme.spacing[3],
},
searchIcon: {
width: 18,
alignItems: "center",
grid: {
flexDirection: "row",
flexWrap: "wrap",
gap: TILE_GAP,
},
searchInput: {
flex: 1,
minWidth: 0,
paddingVertical: theme.spacing[3],
color: theme.colors.foreground,
fontSize: theme.fontSize.base,
},
list: {
borderRadius: theme.borderRadius.lg,
borderWidth: 1,
borderColor: theme.colors.border,
overflow: "hidden",
},
row: {
tile: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[3],
padding: theme.spacing[3],
borderBottomWidth: 1,
borderBottomColor: theme.colors.border,
},
tileFull: {
width: "100%",
},
details: {
flex: 1,
minWidth: 0,
gap: theme.spacing[1],
},
iconFrame: {
flexShrink: 0,
width: 36,
height: 36,
borderRadius: theme.borderRadius.md,
backgroundColor: theme.colors.surface2,
alignItems: "center",
justifyContent: "center",
},
addButton: {
flexShrink: 0,
},
textColumn: {
flex: 1,
minWidth: 0,
gap: theme.spacing[1],
},
titleRow: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[2],
minWidth: 0,
},
name: {
color: theme.colors.foreground,
fontSize: theme.fontSize.base,
fontWeight: theme.fontWeight.medium,
flexShrink: 1,
fontWeight: theme.fontWeight.normal,
},
version: {
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.sm,
flexShrink: 0,
},
description: {
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.sm,
},
installLink: {
alignSelf: "flex-start",
metaRow: {
flexDirection: "row",
flexWrap: "wrap",
alignItems: "center",
gap: theme.spacing[1],
maxWidth: "100%",
},
installLinkText: {
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.sm,
},
actionButton: {
width: 92,
flexShrink: 0,
gap: theme.spacing[2],
},
stateBox: {
minHeight: 96,
borderRadius: theme.borderRadius.lg,
borderWidth: 1,
borderColor: theme.colors.border,
backgroundColor: theme.colors.surface1,
alignItems: "center",
justifyContent: "center",
gap: theme.spacing[3],
padding: theme.spacing[4],
},
stateText: {
@@ -0,0 +1,45 @@
import { describe, expect, it } from "vitest";
import { rankProviderCatalog } from "./provider-catalog-search";
const entries = [
{ id: "kiro-cli", title: "Kiro CLI" },
{ id: "goose", title: "goose" },
{ id: "kimi", title: "Kimi Code CLI" },
{ id: "gemini", title: "Gemini CLI" },
{ id: "qwen-code", title: "Qwen Code" },
{ id: "codex-acp", title: "Codex" },
];
function titles(list: { title: string }[]): string[] {
return list.map((entry) => entry.title);
}
describe("rankProviderCatalog", () => {
it("lists every provider alphabetically by name without a query", () => {
expect(titles(rankProviderCatalog(entries, " "))).toEqual([
"Codex",
"Gemini CLI",
"goose",
"Kimi Code CLI",
"Kiro CLI",
"Qwen Code",
]);
});
it("ranks the strongest match first and drops providers that do not match", () => {
expect(titles(rankProviderCatalog(entries, "cod"))).toEqual([
"Codex",
"Kimi Code CLI",
"Qwen Code",
]);
});
it("matches in-word subsequences and multiple tokens like the other pickers", () => {
expect(titles(rankProviderCatalog(entries, "gmni"))).toEqual(["Gemini CLI"]);
expect(titles(rankProviderCatalog(entries, "qw cod"))).toEqual(["Qwen Code"]);
});
it("matches the provider id", () => {
expect(titles(rankProviderCatalog(entries, "kiro-cli"))).toEqual(["Kiro CLI"]);
});
});
@@ -0,0 +1,34 @@
import {
compareMatchScores,
scoreTextFields,
type MatchScore,
} from "@getpaseo/protocol/search/text-match";
export interface SearchableCatalogEntry {
id: string;
title: string;
}
function compareTitles(a: SearchableCatalogEntry, b: SearchableCatalogEntry): number {
return a.title.localeCompare(b.title, undefined, { sensitivity: "base" });
}
/**
* Orders the Add provider catalog. Without a query the list is alphabetical by
* name. With a query it uses the pickers' ranked matcher over the fields the
* tile shows (name and id), best match first, ties alphabetical.
*/
export function rankProviderCatalog<T extends SearchableCatalogEntry>(
entries: readonly T[],
query: string,
): T[] {
if (!query.trim()) return [...entries].sort(compareTitles);
const scored: { entry: T; score: MatchScore }[] = [];
for (const entry of entries) {
const score = scoreTextFields(query, [entry.title, entry.id]);
if (score) scored.push({ entry, score });
}
scored.sort((a, b) => compareMatchScores(a.score, b.score) || compareTitles(a.entry, b.entry));
return scored.map(({ entry }) => entry);
}
+59 -6
View File
@@ -2,6 +2,11 @@ import { TerminalFind, type TerminalPaneFindHandle } from "@/terminal/find";
import type { TerminalFindResult } from "@/terminal/runtime/terminal-emulator-runtime";
import { LoadingSpinner } from "@/components/ui/loading-spinner";
import { useRetainedPanelActive } from "@/components/retained-panel";
import {
hasActiveWebOverlay,
isWithinActiveWebOverlay,
subscribeWebOverlayChanges,
} from "@/lib/overlay-root";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import * as Clipboard from "expo-clipboard";
import {
@@ -68,7 +73,7 @@ import {
type TerminalResizeRequest,
} from "./terminal-resize-debouncer";
import { useIsCompactFormFactor } from "@/constants/layout";
import { isNative } from "@/constants/platform";
import { isNative, isWeb } from "@/constants/platform";
import {
applyTerminalRendererReadyChange,
resolveTerminalStreamTarget,
@@ -377,19 +382,67 @@ export function TerminalPane({
);
useEffect(() => {
if (isMobile || !isPaneFocused || !terminalId) {
if (isMobile || !isPaneFocused || !isWorkspaceFocused || !terminalId) {
lastAutoFocusKeyRef.current = null;
return;
}
if (!isWorkspaceFocused) {
if (rendererReadyStreamKey !== terminalStreamKey) {
return;
}
const focusKey = `${scopeKey}:${terminalId}`;
if (lastAutoFocusKeyRef.current !== focusKey) {
lastAutoFocusKeyRef.current = focusKey;
if (lastAutoFocusKeyRef.current === focusKey) return;
function tryAutoFocus(): boolean {
if (isWeb) {
const active = document.activeElement;
const hasFocusedInput =
active instanceof HTMLElement &&
active.matches('input, textarea, [contenteditable="true"]') &&
!active.matches(".xterm-helper-textarea") &&
active.getClientRects().length > 0;
if (hasActiveWebOverlay() || hasFocusedInput) {
return false;
}
}
requestTerminalFocus();
lastAutoFocusKeyRef.current = focusKey;
return true;
}
}, [isMobile, isPaneFocused, isWorkspaceFocused, requestTerminalFocus, scopeKey, terminalId]);
if (tryAutoFocus() || !isWeb) return;
let retryFrame: number | null = null;
function stopRetrying(): void {
document.removeEventListener("focusout", scheduleRetry);
document.removeEventListener("focusin", handleFocusIn);
unsubscribeOverlayChanges();
if (retryFrame !== null) window.cancelAnimationFrame(retryFrame);
}
function handleFocusIn(event: FocusEvent): void {
// Moving within the overlay does not replace the deferred workspace focus owner.
if (!isWithinActiveWebOverlay(event.target)) stopRetrying();
}
function scheduleRetry(): void {
if (retryFrame !== null) return;
// Let blur, overlay teardown, and focus restoration settle before checking ownership.
retryFrame = window.requestAnimationFrame(() => {
retryFrame = null;
if (tryAutoFocus()) stopRetrying();
});
}
const unsubscribeOverlayChanges = subscribeWebOverlayChanges(scheduleRetry);
document.addEventListener("focusout", scheduleRetry);
// A new focus owner outside the overlay wins over deferred workspace autofocus.
document.addEventListener("focusin", handleFocusIn);
return stopRetrying;
}, [
isMobile,
isPaneFocused,
isWorkspaceFocused,
rendererReadyStreamKey,
requestTerminalFocus,
scopeKey,
terminalId,
terminalStreamKey,
]);
useEffect(() => {
const canRequest = canRequestFocusClaim({
@@ -1,10 +1,6 @@
import { describe, expect, it } from "vitest";
import {
getAutocompleteFallbackIndex,
getAutocompleteScrollOffset,
orderAutocompleteOptions,
} from "./autocomplete-utils";
import { getAutocompleteFallbackIndex, orderAutocompleteOptions } from "./autocomplete-utils";
const OPTIONS = ["alpha", "beta", "gamma"];
@@ -28,27 +24,3 @@ describe("getAutocompleteFallbackIndex", () => {
expect(getAutocompleteFallbackIndex(3, "below-input")).toBe(0);
});
});
describe("getAutocompleteScrollOffset", () => {
it("scrolls up when the active item is above the viewport", () => {
expect(
getAutocompleteScrollOffset({
currentOffset: 120,
viewportHeight: 80,
itemTop: 90,
itemHeight: 20,
}),
).toBe(90);
});
it("scrolls down when the active item is below the viewport", () => {
expect(
getAutocompleteScrollOffset({
currentOffset: 0,
viewportHeight: 100,
itemTop: 150,
itemHeight: 24,
}),
).toBe(74);
});
});
@@ -29,28 +29,3 @@ export function getAutocompleteNextIndex(args: {
}): number {
return getNextActiveIndex(args);
}
export function getAutocompleteScrollOffset(args: {
currentOffset: number;
viewportHeight: number;
itemTop: number;
itemHeight: number;
}): number {
if (args.viewportHeight <= 0) {
return args.currentOffset;
}
const itemBottom = args.itemTop + args.itemHeight;
const viewportTop = args.currentOffset;
const viewportBottom = args.currentOffset + args.viewportHeight;
if (args.itemTop < viewportTop) {
return Math.max(0, args.itemTop);
}
if (itemBottom > viewportBottom) {
return Math.max(0, itemBottom - args.viewportHeight);
}
return args.currentOffset;
}
@@ -13,7 +13,7 @@ import { StyleSheet, useUnistyles } from "react-native-unistyles";
import { useTranslation } from "react-i18next";
import { File, Folder } from "lucide-react-native";
import type { Theme } from "@/styles/theme";
import { getAutocompleteScrollOffset } from "./autocomplete-utils";
import { getScrollOffsetToRevealItem } from "./scroll-reveal";
export interface AutocompleteOption {
id: string;
@@ -146,7 +146,7 @@ export function Autocomplete({
return;
}
const nextOffset = getAutocompleteScrollOffset({
const nextOffset = getScrollOffsetToRevealItem({
currentOffset: scrollOffsetRef.current,
viewportHeight: viewportHeightRef.current,
itemTop: layout.top,
@@ -0,0 +1,72 @@
import { useId } from "react";
import { View, type StyleProp, type ViewStyle } from "react-native";
import Svg, { Defs, LinearGradient as SvgLinearGradient, Rect, Stop } from "react-native-svg";
import { withUnistyles } from "react-native-unistyles";
import type { Theme } from "@/styles/theme";
type EdgeFadeBackdrop = "surface0" | "surfaceWorkspace";
const backdropColorMappings: Record<EdgeFadeBackdrop, (theme: Theme) => { color: string }> = {
surface0: (theme) => ({ color: theme.colors.surface0 }),
surfaceWorkspace: (theme) => ({ color: theme.colors.surfaceWorkspace }),
};
interface EdgeFadeSvgProps {
gradientId: string;
color: string;
edge: "top" | "bottom";
solidFraction: number;
}
function EdgeFadeSvg({ gradientId, color, edge, solidFraction }: EdgeFadeSvgProps) {
const fromTop = edge === "top";
return (
<Svg width="100%" height="100%" preserveAspectRatio="none">
<Defs>
<SvgLinearGradient
id={gradientId}
x1="0%"
y1={fromTop ? "0%" : "100%"}
x2="0%"
y2={fromTop ? "100%" : "0%"}
>
{/* Vary opacity rather than interpolating toward `transparent`, which crosses black in
some engines and leaves a grey fringe. Keep it to three stops: Android rendered a
four-stop version far more transparent than its stops specify. */}
<Stop offset={0} stopColor={color} stopOpacity={1} />
<Stop offset={solidFraction} stopColor={color} stopOpacity={1} />
<Stop offset={1} stopColor={color} stopOpacity={0} />
</SvgLinearGradient>
</Defs>
<Rect x="0" y="0" width="100%" height="100%" fill={`url(#${gradientId})`} />
</Svg>
);
}
const ThemedEdgeFadeSvg = withUnistyles(EdgeFadeSvg);
interface EdgeFadeProps {
/** The solid edge; content dissolves moving away from it. */
edge: "top" | "bottom";
/** Share of the fade, measured from the solid edge, that stays fully opaque. */
solidFraction: number;
backdrop: EdgeFadeBackdrop;
/** Position and size. Keep the fade inside its parent: Android clips overhanging children. */
style: StyleProp<ViewStyle>;
}
/** Dissolves content into the surface behind chrome that floats over it. */
export function EdgeFade({ edge, solidFraction, backdrop, style }: EdgeFadeProps) {
// React-generated ids contain characters that are invalid inside SVG fragment references.
const gradientId = `edge-fade-${useId().replace(/[^a-zA-Z0-9_-]/g, "")}`;
return (
<View style={style} pointerEvents="none">
<ThemedEdgeFadeSvg
gradientId={gradientId}
edge={edge}
solidFraction={solidFraction}
uniProps={backdropColorMappings[backdrop]}
/>
</View>
);
}
@@ -0,0 +1,48 @@
import { describe, expect, it } from "vitest";
import { getScrollOffsetToRevealItem } from "./scroll-reveal";
describe("getScrollOffsetToRevealItem", () => {
it("keeps the offset when the item is already inside the viewport", () => {
expect(
getScrollOffsetToRevealItem({
currentOffset: 40,
viewportHeight: 200,
itemTop: 100,
itemHeight: 40,
}),
).toBe(40);
});
it("scrolls up to the item top when the item is above the viewport", () => {
expect(
getScrollOffsetToRevealItem({
currentOffset: 300,
viewportHeight: 200,
itemTop: 240,
itemHeight: 40,
}),
).toBe(240);
});
it("scrolls down just far enough to reveal the item bottom", () => {
expect(
getScrollOffsetToRevealItem({
currentOffset: 0,
viewportHeight: 200,
itemTop: 380,
itemHeight: 40,
}),
).toBe(220);
});
it("stays put before the viewport has been measured", () => {
expect(
getScrollOffsetToRevealItem({
currentOffset: 120,
viewportHeight: 0,
itemTop: 400,
itemHeight: 40,
}),
).toBe(120);
});
});
@@ -0,0 +1,110 @@
import { useCallback, useLayoutEffect, useRef, type RefObject } from "react";
import type {
LayoutChangeEvent,
NativeScrollEvent,
NativeSyntheticEvent,
ScrollView,
View,
} from "react-native";
export function getScrollOffsetToRevealItem(args: {
currentOffset: number;
viewportHeight: number;
itemTop: number;
itemHeight: number;
}): number {
if (args.viewportHeight <= 0) {
return args.currentOffset;
}
const itemBottom = args.itemTop + args.itemHeight;
const viewportTop = args.currentOffset;
const viewportBottom = args.currentOffset + args.viewportHeight;
if (args.itemTop < viewportTop) {
return Math.max(0, args.itemTop);
}
if (itemBottom > viewportBottom) {
return Math.max(0, itemBottom - args.viewportHeight);
}
return args.currentOffset;
}
export interface RevealActiveItemHandlers {
activeItemRef: RefObject<View | null>;
contentRef: RefObject<View | null>;
onItemLayout: () => void;
onViewportLayout: (event: LayoutChangeEvent) => void;
onScroll: (event: NativeSyntheticEvent<NativeScrollEvent>) => void;
}
/**
* Reveals the keyboard-selected row using its current position in the scroll
* content. Measuring on selection/list changes also covers retained rows that
* move or keep their size without emitting another onLayout event on web.
* A list replacement resets to the top only when selection restarts there.
* Bottom-anchored lists share only getScrollOffsetToRevealItem.
*/
export function useRevealActiveItem(options: {
activeIndex: number;
listKey: string;
scrollRef: RefObject<ScrollView | null>;
}): RevealActiveItemHandlers {
const { activeIndex, listKey, scrollRef } = options;
const activeItemRef = useRef<View | null>(null);
const contentRef = useRef<View | null>(null);
const viewportHeightRef = useRef(0);
const offsetRef = useRef(0);
const measurementRef = useRef(0);
const reveal = useCallback(() => {
const request = ++measurementRef.current;
const item = activeItemRef.current;
const scroll = scrollRef.current;
const content = contentRef.current;
if (!item || !scroll || !content) return;
item.measureLayout(content, (_left, top, _width, height) => {
if (request !== measurementRef.current || activeItemRef.current !== item) return;
const nextOffset = getScrollOffsetToRevealItem({
currentOffset: offsetRef.current,
viewportHeight: viewportHeightRef.current,
itemTop: top,
itemHeight: height,
});
if (Math.abs(nextOffset - offsetRef.current) < 1) return;
offsetRef.current = nextOffset;
scroll.scrollTo({ y: nextOffset, animated: false });
});
}, [scrollRef]);
const prevListKeyRef = useRef(listKey);
useLayoutEffect(() => {
if (prevListKeyRef.current !== listKey && activeIndex === 0) {
offsetRef.current = 0;
scrollRef.current?.scrollTo({ y: 0, animated: false });
}
prevListKeyRef.current = listKey;
reveal();
return () => {
// Measurements are asynchronous; a previous selection must not scroll us.
measurementRef.current += 1;
};
}, [activeIndex, listKey, reveal, scrollRef]);
const onViewportLayout = useCallback(
(event: LayoutChangeEvent) => {
viewportHeightRef.current = event.nativeEvent.layout.height;
reveal();
},
[reveal],
);
const onScroll = useCallback((event: NativeSyntheticEvent<NativeScrollEvent>) => {
offsetRef.current = event.nativeEvent.contentOffset.y;
}, []);
return { activeItemRef, contentRef, onItemLayout: reveal, onViewportLayout, onScroll };
}
+16 -7
View File
@@ -28,6 +28,7 @@ import { useTranslation } from "react-i18next";
import { ICON_SIZE, type Theme } from "@/styles/theme";
import { ArrowUp, Mic, MicOff, CornerDownLeft, Plus, Square } from "lucide-react-native";
import { useDictation } from "@/hooks/use-dictation";
import { hasFinePointer } from "@/hooks/use-fine-pointer";
import { DictationOverlay } from "@/components/dictation-controls";
import { RealtimeVoiceOverlay } from "@/components/realtime-voice-overlay";
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
@@ -1289,12 +1290,14 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
webTextareaRef.current = element;
setWebTextArea(element);
}, []);
// Focus intent outlives a blur only while the pane is not the user's pane (a retained
// tab hidden, a sheet over it); the pane coming back restores focus. A blur while the
// pane is theirs drops it, whatever the layout mode: the user dismissed the keyboard,
// or a compact overlay panel did on their behalf, and nothing later refocuses.
// Only mouse-driven UIs restore editing focus on navigation. Touch users return
// to the conversation; replaying old focus would reopen their software keyboard.
// Read pointer capability when restoring, without making a pointer change itself
// a focus trigger.
useLayoutEffect(() => {
if (isPaneFocused && focusIntentRef.current) textInputRef.current?.focus();
if (isPaneFocused && focusIntentRef.current && hasFinePointer()) {
textInputRef.current?.focus();
}
}, [isPaneFocused]);
// The compact and desktop screens mount the editor in different trees, so a
// viewport that crosses the breakpoint remounts it. The draft owner brings the
@@ -1311,7 +1314,7 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
retainedSelectionRef.current = retained.selection;
selectionRef.current = selection;
textInputRef.current?.setSelection(selection);
if (retained.focused) {
if (retained.focused && hasFinePointer()) {
focusIntentRef.current = true;
if (paneFocusedRef.current) textInputRef.current?.focus();
}
@@ -1818,6 +1821,7 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
}, [onFocusChange]);
const handleInputBlur = useCallback(() => {
// A blur in the active pane is a dismissal; only hiding the pane preserves intent.
if (paneFocusedRef.current) focusIntentRef.current = false;
isInputFocusedRef.current = false;
setIsInputFocused(false);
@@ -1858,11 +1862,12 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
const inputWrapperCombinedStyle = useMemo(
() => [
styles.inputWrapper,
isCompact && !isFullscreen && styles.inputWrapperCompact,
readOnly && styles.inputWrapperReadOnly,
inputWrapperStyle,
{ opacity: surfacePresentation.input.opacity },
],
[inputWrapperStyle, readOnly, surfacePresentation.input.opacity],
[inputWrapperStyle, isCompact, isFullscreen, readOnly, surfacePresentation.input.opacity],
);
// `withUnistyles` maps this component's `style` into a `.hash > *` child
// rule, which ties on specificity with react-native-web's own
@@ -2219,6 +2224,10 @@ const styles = StyleSheet.create((theme: Theme) => ({
}
: {}),
},
// Lifts the composer off the chat it sits under on phones.
inputWrapperCompact: {
boxShadow: "0px 4px 16px rgba(0, 0, 0, 0.2)",
},
// Dotted says "this surface is the same box, but there is nothing to type
// into it" without swapping the border colour, which reads as an error state.
inputWrapperReadOnly: {
+2 -4
View File
@@ -8,10 +8,8 @@ import {
interface ComposerKeyboardScopeValue {
/**
* The pane this composer sits in is the user's pane. Focus restoration follows it:
* the editor keeps its focus intent across blurs that happen while the pane is not
* the user's (a retained tab hidden, a sheet over it) and brings focus back when
* the pane is theirs again.
* The pane this composer sits in is the user's pane. Mouse-driven focus
* restoration follows it; touch navigation does not restore editor focus.
*/
isPaneFocused: boolean;
/**
@@ -17,6 +17,14 @@ export function getActiveMessageSubmissions(
);
}
export function hasActiveMessageSubmission(
submissions: readonly MessageSubmissionRecord[] | null | undefined,
): boolean {
return (submissions ?? EMPTY_MESSAGE_SUBMISSIONS).some(
(submission) => !submission.providerAcknowledged,
);
}
export function getSendingClientMessageIds(
submissions: readonly MessageSubmissionRecord[] | null | undefined,
): string[] {
@@ -8,6 +8,7 @@ export interface AcpProviderCatalogEntry {
iconSvg: string | null;
installLink: string;
command: readonly [string, ...string[]];
bundledProvider?: boolean;
env?: Readonly<Record<string, string>>;
params?: Readonly<Record<string, unknown>>;
}
@@ -238,6 +239,16 @@ const CATALOG_DATA = [
installLink: "https://hermes-agent.nousresearch.com/docs/user-guide/features/acp",
command: ["hermes", "acp"],
},
{
id: "hoplite",
bundledProvider: true,
title: "Hoplite",
description: "Cloud coding agent through the local hoplite acp bridge",
version: "manual",
iconId: "hoplite",
installLink: "https://hoplite.sh/docs/cli#install",
command: ["hoplite", "acp"],
},
{
id: "junie",
title: "Junie",
@@ -389,6 +400,7 @@ export const ACP_PROVIDER_CATALOG: AcpProviderCatalogEntry[] = CATALOG_DATA.map(
version: entry.version,
installLink: entry.installLink,
command: entry.command,
bundledProvider: "bundledProvider" in entry ? entry.bundledProvider : undefined,
env: "env" in entry ? entry.env : undefined,
params: "params" in entry ? entry.params : undefined,
iconSvg: entry.iconId ? (ACP_PROVIDER_ICON_SVGS[entry.iconId] ?? null) : null,
@@ -44,6 +44,7 @@ describe("ACP provider catalog", () => {
expect(findProvider("codewhale").command).toEqual(["codewhale", "serve", "--acp"]);
expect(findProvider("devin").command).toEqual(["devin", "acp"]);
expect(findProvider("goose").command).toEqual(["goose", "acp"]);
expect(findProvider("hoplite").command).toEqual(["hoplite", "acp"]);
expect(findProvider("junie").command).toEqual(["junie", "--acp", "true"]);
expect(findProvider("kiro").command).toEqual(["kiro-cli", "acp"]);
expect(findProvider("poolside").command).toEqual(["pool", "acp"]);
@@ -59,6 +60,32 @@ describe("ACP provider catalog", () => {
expect(findProvider("minimax-code").iconSvg).toContain("<svg");
});
it("offers Hoplite through its local ACP bridge with the Hoplite mark", () => {
expect(findProvider("hoplite")).toMatchObject({
title: "Hoplite",
command: ["hoplite", "acp"],
installLink: "https://hoplite.sh/docs/cli#install",
});
expect(buildAcpProviderConfigPatch(findProvider("hoplite"), true)).toEqual({
providers: {
hoplite: { enabled: true },
},
});
const ids = getAcpProviderCatalog().map((entry) => entry.id);
expect(ids.indexOf("hermes")).toBeLessThan(ids.indexOf("hoplite"));
expect(ids.indexOf("hoplite")).toBeLessThan(ids.indexOf("junie"));
expect(findProvider("hoplite").iconSvg).toContain('fill="currentColor"');
});
it.each([undefined, false])(
"rejects unsupported bundled Hoplite before producing a patch (%s)",
(supported) => {
expect(() => buildAcpProviderConfigPatch(findProvider("hoplite"), supported)).toThrow(
"Update the host to add Hoplite.",
);
},
);
it("maps a catalog entry to the daemon provider config patch", () => {
expect(buildAcpProviderConfigPatch(findProvider("amp-acp"))).toEqual({
providers: {
@@ -10,7 +10,13 @@ export function getAcpProviderCatalog(): AcpProviderCatalogItem[] {
export function buildAcpProviderConfigPatch(
entry: AcpProviderCatalogItem,
supportsHopliteProvider = false,
): MutableDaemonConfigPatch {
if (entry.bundledProvider) {
// COMPAT(hopliteProvider): added after v0.11.2, remove after 2027-04-15 once host floor includes the bundled adapter.
if (!supportsHopliteProvider) throw new Error("Update the host to add Hoplite.");
return { providers: { [entry.id]: { enabled: true } } };
}
return {
providers: {
[entry.id]: {
@@ -40,7 +40,7 @@ import {
navigateToLastWorkspace,
useActiveWorkspaceSelection,
} from "@/stores/navigation-active-workspace-store";
import { dispatchTopWebOverlayKeyDown } from "@/lib/overlay-root";
import { dispatchTopWebOverlayKeyDown, keyBelongsToDomPopover } from "@/lib/overlay-root";
export function useKeyboardShortcuts({
enabled,
@@ -321,6 +321,10 @@ export function useKeyboardShortcuts({
return;
}
if (keyBelongsToDomPopover(event)) {
return;
}
// During IME composition, Enter confirms the candidate selection and must
// not route through global shortcuts like message send.
if (isImeComposingKeyboardEvent(event)) {
+8
View File
@@ -729,6 +729,7 @@ export const ar: TranslationResources = {
header: {
actions: {
workspaceActions: "إجراءات Workspace",
workspaceActionsUnhealthy: "إجراءات Workspace، توجد خدمة غير سليمة",
newAgent: "وكيل جديد",
newTerminal: "محطة جديدة",
newBrowser: "علامة تبويب متصفح جديدة",
@@ -776,6 +777,8 @@ export const ar: TranslationResources = {
exitCode: "الخروج من{{code}}",
startFailed: "فشل بدء تشغيل{{scriptName}}",
stopFailed: "فشل إيقاف{{scriptName}}",
running: "قيد التشغيل",
runningCount: "{{count}} قيد التشغيل",
},
},
tree: {
@@ -1657,14 +1660,19 @@ export const ar: TranslationResources = {
title: "إضافة مزود",
search: "مقدمي البحث",
noProviders: "لم يتم العثور على مقدمي الخدمات",
clearSearch: "مسح البحث",
actions: {
add: "يضيف",
addProvider: "إضافة {{provider}}",
adding: "إضافة",
installed: "تم التثبيت",
cancel: "يلغي",
installInstructions: "تعليمات التثبيت",
installInstructionsFor: "تعليمات تثبيت{{provider}}",
},
types: {
acp: "ACP",
},
errors: {
unableToInstall: "غير قادر على تثبيت الموفر",
},
+8
View File
@@ -724,6 +724,7 @@ export const en = {
header: {
actions: {
workspaceActions: "Workspace actions",
workspaceActionsUnhealthy: "Workspace actions, a service is unhealthy",
newAgent: "New agent",
newTerminal: "New terminal",
newBrowser: "New browser tab",
@@ -771,6 +772,8 @@ export const en = {
exitCode: "exit {{code}}",
startFailed: "Failed to start {{scriptName}}",
stopFailed: "Failed to stop {{scriptName}}",
running: "Running",
runningCount: "{{count}} running",
},
},
tree: {
@@ -1682,14 +1685,19 @@ export const en = {
title: "Add provider",
search: "Search providers",
noProviders: "No providers found",
clearSearch: "Clear search",
actions: {
add: "Add",
addProvider: "Add {{provider}}",
adding: "Adding",
installed: "Installed",
cancel: "Cancel",
installInstructions: "Install instructions",
installInstructionsFor: "{{provider}} install instructions",
},
types: {
acp: "ACP",
},
errors: {
unableToInstall: "Unable to install provider",
},
+8
View File
@@ -736,6 +736,7 @@ export const es: TranslationResources = {
header: {
actions: {
workspaceActions: "AccionesWorkspace",
workspaceActionsUnhealthy: "Acciones del workspace, hay un servicio con problemas",
newAgent: "Nuevo agente",
newTerminal: "Nueva terminal",
newBrowser: "Nueva pestaña del navegador",
@@ -784,6 +785,8 @@ export const es: TranslationResources = {
exitCode: "salir de{{code}}",
startFailed: "No se pudo iniciar{{scriptName}}",
stopFailed: "No se pudo detener{{scriptName}}",
running: "En ejecución",
runningCount: "{{count}} en ejecución",
},
},
tree: {
@@ -1703,14 +1706,19 @@ export const es: TranslationResources = {
title: "Agregar proveedor",
search: "Proveedores de búsqueda",
noProviders: "No se encontraron proveedores",
clearSearch: "Borrar búsqueda",
actions: {
add: "Agregar",
addProvider: "Añadir {{provider}}",
adding: "Añadiendo",
installed: "Instalado",
cancel: "Cancelar",
installInstructions: "Instrucciones de instalación",
installInstructionsFor: "Instrucciones de instalación de{{provider}}",
},
types: {
acp: "ACP",
},
errors: {
unableToInstall: "No se puede instalar el proveedor",
},
+9
View File
@@ -735,6 +735,8 @@ export const fr: TranslationResources = {
header: {
actions: {
workspaceActions: "Actions de l’espace de travail",
workspaceActionsUnhealthy:
"Actions de l’espace de travail, un service est en mauvaise santé",
newAgent: "Nouvel agent",
newTerminal: "Nouveau terminal",
newBrowser: "Nouvel onglet de navigateur",
@@ -783,6 +785,8 @@ export const fr: TranslationResources = {
exitCode: "sortie {{code}}",
startFailed: "Impossible de démarrer {{scriptName}}",
stopFailed: "Impossible d’arrêter {{scriptName}}",
running: "En cours",
runningCount: "{{count}} en cours",
},
},
tree: {
@@ -1699,14 +1703,19 @@ export const fr: TranslationResources = {
title: "Ajouter un fournisseur",
search: "Rechercher des fournisseurs",
noProviders: "Aucun fournisseur trouvé",
clearSearch: "Effacer la recherche",
actions: {
add: "Ajouter",
addProvider: "Ajouter {{provider}}",
adding: "Ajout…",
installed: "Installé",
cancel: "Annuler",
installInstructions: "Instructions d’installation",
installInstructionsFor: "Instructions d’installation de {{provider}}",
},
types: {
acp: "ACP",
},
errors: {
unableToInstall: "Impossible d’installer le fournisseur",
},
+8
View File
@@ -733,6 +733,7 @@ export const ja: TranslationResources = {
header: {
actions: {
workspaceActions: "ワークスペースアクション",
workspaceActionsUnhealthy: "ワークスペースアクション、異常なサービスがあります",
newAgent: "新しいエージェント",
newTerminal: "新しいターミナル",
newBrowser: "新しいブラウザタブ",
@@ -780,6 +781,8 @@ export const ja: TranslationResources = {
exitCode: "終了コード: {{code}}",
startFailed: "{{scriptName}}の起動に失敗しました",
stopFailed: "{{scriptName}}の停止に失敗しました",
running: "実行中",
runningCount: "{{count}} 件実行中",
},
},
tree: {
@@ -1674,14 +1677,19 @@ export const ja: TranslationResources = {
title: "プロバイダーを追加",
search: "プロバイダーを検索",
noProviders: "プロバイダーが見つかりません",
clearSearch: "検索をクリア",
actions: {
add: "追加",
addProvider: "{{provider}} を追加",
adding: "追加中",
installed: "インストール済み",
cancel: "キャンセル",
installInstructions: "インストール手順",
installInstructionsFor: "{{provider}}のインストール手順",
},
types: {
acp: "ACP",
},
errors: {
unableToInstall: "プロバイダーをインストールできません",
},
+8
View File
@@ -729,6 +729,7 @@ export const ko: TranslationResources = {
header: {
actions: {
workspaceActions: "워크스페이스 작업",
workspaceActionsUnhealthy: "워크스페이스 작업, 비정상 서비스가 있습니다",
newAgent: "새 에이전트",
newTerminal: "새 터미널",
newBrowser: "새 브라우저 탭",
@@ -776,6 +777,8 @@ export const ko: TranslationResources = {
exitCode: "종료 {{code}}",
startFailed: "{{scriptName}}을(를) 시작하지 못했습니다",
stopFailed: "{{scriptName}}를 중지하지 못했습니다.",
running: "실행 중",
runningCount: "{{count}}개 실행 중",
},
},
tree: {
@@ -1667,14 +1670,19 @@ export const ko: TranslationResources = {
title: "프로바이더 추가",
search: "프로바이더 검색",
noProviders: "프로바이더를 찾을 수 없습니다",
clearSearch: "검색 지우기",
actions: {
add: "추가",
addProvider: "{{provider}} 추가",
adding: "추가 중",
installed: "설치됨",
cancel: "취소",
installInstructions: "설치 안내",
installInstructionsFor: "{{provider}} 설치 안내",
},
types: {
acp: "ACP",
},
errors: {
unableToInstall: "프로바이더를 설치할 수 없습니다",
},
+8
View File
@@ -733,6 +733,7 @@ export const ptBR: TranslationResources = {
header: {
actions: {
workspaceActions: "Ações do workspace",
workspaceActionsUnhealthy: "Ações do workspace, há um serviço com problema",
newAgent: "Novo agente",
newTerminal: "Novo terminal",
newBrowser: "Nova aba de navegador",
@@ -780,6 +781,8 @@ export const ptBR: TranslationResources = {
exitCode: "saída {{code}}",
startFailed: "Falha ao iniciar {{scriptName}}",
stopFailed: "Falha ao parar {{scriptName}}",
running: "Em execução",
runningCount: "{{count}} em execução",
},
},
tree: {
@@ -1688,14 +1691,19 @@ export const ptBR: TranslationResources = {
title: "Adicionar provedor",
search: "Buscar provedores",
noProviders: "Nenhum provedor encontrado",
clearSearch: "Limpar pesquisa",
actions: {
add: "Adicionar",
addProvider: "Adicionar {{provider}}",
adding: "Adicionando",
installed: "Instalado",
cancel: "Cancelar",
installInstructions: "Instruções de instalação",
installInstructionsFor: "Instruções de instalação de {{provider}}",
},
types: {
acp: "ACP",
},
errors: {
unableToInstall: "Não foi possível instalar provedor",
},
+8
View File
@@ -736,6 +736,7 @@ export const ru: TranslationResources = {
header: {
actions: {
workspaceActions: "Действия с рабочим пространством",
workspaceActionsUnhealthy: "Действия с рабочим пространством, есть неисправный сервис",
newAgent: "Новый агент",
newTerminal: "Новый терминал",
newBrowser: "Новая вкладка браузера",
@@ -784,6 +785,8 @@ export const ru: TranslationResources = {
exitCode: "Код выхода: {{code}}",
startFailed: "Не удалось запустить скрипт {{scriptName}}",
stopFailed: "Не удалось остановить скрипт {{scriptName}}",
running: "Запущен",
runningCount: "Запущено: {{count}}",
},
},
tree: {
@@ -1686,14 +1689,19 @@ export const ru: TranslationResources = {
title: "Добавить провайдера",
search: "Поиск провайдеров",
noProviders: "Провайдеры не найдены",
clearSearch: "Очистить поиск",
actions: {
add: "Добавить",
addProvider: "Добавить {{provider}}",
adding: "Добавление",
installed: "Установлено",
cancel: "Отмена",
installInstructions: "Инструкции по установке",
installInstructionsFor: "Инструкции по установке {{provider}}",
},
types: {
acp: "ACP",
},
errors: {
unableToInstall: "Не удалось установить провайдера",
},
+8
View File
@@ -725,6 +725,7 @@ export const zhCN: TranslationResources = {
header: {
actions: {
workspaceActions: "Workspace 操作",
workspaceActionsUnhealthy: "Workspace 操作,有服务异常",
newAgent: "新建 Agent",
newTerminal: "新建 Terminal",
newBrowser: "新建浏览器标签",
@@ -772,6 +773,8 @@ export const zhCN: TranslationResources = {
exitCode: "exit {{code}}",
startFailed: "启动 {{scriptName}} 失败",
stopFailed: "停止 {{scriptName}} 失败",
running: "运行中",
runningCount: "{{count}} 个运行中",
},
},
tree: {
@@ -1640,14 +1643,19 @@ export const zhCN: TranslationResources = {
title: "添加 provider",
search: "搜索 providers",
noProviders: "未找到 providers",
clearSearch: "清除搜索",
actions: {
add: "添加",
addProvider: "添加 {{provider}}",
adding: "正在添加",
installed: "已安装",
cancel: "取消",
installInstructions: "安装说明",
installInstructionsFor: "{{provider}} 安装说明",
},
types: {
acp: "ACP",
},
errors: {
unableToInstall: "无法安装 provider",
},
@@ -4,6 +4,7 @@ import { keyboardEventToComboString } from "./shortcut-string";
import {
buildKeyboardShortcutHelpSections,
buildEffectiveBindings,
normalizeCapturedShortcutCombo,
getBindingIdForAction,
getDefaultKeysForAction,
getWorkspaceIndexJumpModifierKey,
@@ -823,9 +824,9 @@ describe("keyboard-shortcut help sections", () => {
expect(rowChord({}, "show-shortcuts")).toEqual([["?"]]);
});
it("replaces the default-only wildcard when the index jump is rebound", () => {
it("keeps the digit range readable when the index jump is rebound", () => {
expect(rowChord({ [MAC_INDEX_BINDING]: "Ctrl+Digit" }, "workspace-jump-index")).toEqual([
["ctrl", "Digit"],
["ctrl", "1-9"],
]);
});
@@ -1347,3 +1348,45 @@ describe("direct new-tab target shortcuts", () => {
).toEqual([["ctrl", "shift", "H"]]);
});
});
describe("number-group shortcut capture", () => {
const tabBindingId = "workspace-tab-navigate-index-cmd-alt-digit-mac-desktop";
it.each([
{ id: tabBindingId, action: "workspace.tab.navigate.index", row: "workspace-tab-jump-index" },
{
id: "workspace-navigate-index-cmd-digit-mac",
action: "workspace.navigate.index",
row: "workspace-jump-index",
},
])("captures Ctrl+1 as the entire number group for $row", ({ id, action, row }) => {
const combo = normalizeCapturedShortcutCombo(id, "Ctrl+1");
expect(combo).toBe("Ctrl+Digit");
const overrides = { [id]: combo };
const bindings = buildEffectiveBindings(overrides);
for (let index = 1; index <= 9; index++) {
const result = resolveShortcut({
event: { key: String(index), code: `Digit${index}`, ctrlKey: true },
context: { isMac: true, isDesktop: true, focusScope: "message-input" },
bindings,
});
expect(result.match?.action).toBe(action);
expect(result.match?.payload).toEqual({ index });
}
expect(resolveShortcutKeysForAction(row, overrides, { isMac: true, isDesktop: true })).toEqual([
["ctrl", "1-9"],
]);
expect(
resolveShortcut({
event: { key: "0", code: "Digit0", ctrlKey: true },
context: { isMac: true, isDesktop: true },
bindings,
}).match,
).toBeNull();
});
it("preserves literal numbers for non-index actions and existing nonnumeric combos", () => {
expect(normalizeCapturedShortcutCombo("show-shortcuts", "Ctrl+1")).toBe("Ctrl+1");
expect(normalizeCapturedShortcutCombo(tabBindingId, "Ctrl+K")).toBe("Ctrl+K");
expect(normalizeCapturedShortcutCombo(tabBindingId, "Ctrl+0")).toBe("Ctrl+0");
expect(normalizeCapturedShortcutCombo(tabBindingId, "Ctrl+9")).toBe("Ctrl+Digit");
});
});
@@ -1210,6 +1210,13 @@ export const DEFAULT_BINDINGS: readonly ParsedShortcutBinding[] =
export type ShortcutOverrides = Record<string, string | null>;
/** Keep number-group actions bound to all nine indices when recording a new modifier. */
export function normalizeCapturedShortcutCombo(bindingId: string, combo: string): string {
const binding = DEFAULT_BINDINGS.find((candidate) => candidate.id === bindingId);
if (binding?.payload?.type !== "index") return combo;
return combo.replace(/(^|\+)[1-9]$/, "$1Digit");
}
export function buildEffectiveBindings(overrides: ShortcutOverrides): ParsedShortcutBinding[] {
return DEFAULT_BINDINGS.map(function (binding) {
const override = overrides[binding.id];
@@ -192,6 +192,7 @@ const MODIFIER_CODES = new Set([
* override on a named key renders as a raw code — `ARROWLEFT`, not `←`.
*/
const DISPLAY_KEY_ALIASES: Record<string, string> = {
Digit: "1-9",
ArrowLeft: "Left",
ArrowRight: "Right",
ArrowUp: "Up",
@@ -2,7 +2,11 @@ import React, { type RefCallback } from "react";
import { flushSync } from "react-dom";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { useWebOverlayRegistration } from "./overlay-root";
import {
hasOpenDomPopover,
keyBelongsToDomPopover,
useWebOverlayRegistration,
} from "./overlay-root";
function nextFrame(): Promise<void> {
return new Promise((resolve) => requestAnimationFrame(() => resolve()));
@@ -68,3 +72,35 @@ describe("useWebOverlayRegistration in the browser", () => {
expect(openerFocusCalls).toBe(1);
});
});
describe("hasOpenDomPopover", () => {
afterEach(() => {
document.body.replaceChildren();
});
it("is true only while a popover is shown", () => {
const panel = document.createElement("div");
panel.setAttribute("popover", "manual");
document.body.append(panel);
expect(hasOpenDomPopover()).toBe(false);
panel.showPopover();
expect(hasOpenDomPopover()).toBe(true);
panel.hidePopover();
expect(hasOpenDomPopover()).toBe(false);
});
});
describe("Escape with a plugin popover open", () => {
afterEach(() => {
document.body.replaceChildren();
});
it("leaves other keys to the shortcuts while a popover is open", () => {
const panel = document.createElement("div");
panel.setAttribute("popover", "manual");
document.body.append(panel);
panel.showPopover();
expect(keyBelongsToDomPopover({ key: "Enter" })).toBe(false);
expect(keyBelongsToDomPopover({ key: "Escape" })).toBe(true);
});
});
+43
View File
@@ -95,6 +95,7 @@ const webOverlayEntries: WebOverlayEntry[] = [];
let webOverlayOrder = 0;
let webOverlayListenersAttached = false;
let webOverlayFocusCheckQueued = false;
const webOverlayChangeListeners = new Set<() => void>();
interface RemoveWebOverlayOptions {
restoreFocus?: boolean;
@@ -112,6 +113,46 @@ export function hasActiveWebOverlay(): boolean {
return getTopWebOverlay() !== undefined;
}
export function isWithinActiveWebOverlay(target: EventTarget | null): boolean {
return target instanceof Node && (getTopWebOverlay()?.getScope()?.contains(target) ?? false);
}
export function subscribeWebOverlayChanges(listener: () => void): () => void {
webOverlayChangeListeners.add(listener);
return () => {
webOverlayChangeListeners.delete(listener);
};
}
function notifyWebOverlayChanges(): void {
for (const listener of webOverlayChangeListeners) listener();
}
/**
* True while an element shown with the Popover API is open. Such a layer
* floats above the app like a registered overlay but lives outside the
* registry: plugins draw their panels this way, since they cannot register.
*/
export function hasOpenDomPopover(): boolean {
if (typeof document === "undefined") return false;
try {
return document.querySelector(":popover-open") !== null;
} catch {
// An engine without the Popover API rejects the selector, and has none open.
return false;
}
}
/**
* Whether a key belongs to an open popover rather than to the app's shortcuts.
* An open popover (a plugin's panel) is the top layer and closes on its own
* Escape listener, which runs after the shortcut engine's capture listener:
* Escape must not also interrupt the running agent.
*/
export function keyBelongsToDomPopover(event: Pick<KeyboardEvent, "key">): boolean {
return event.key === "Escape" && hasOpenDomPopover();
}
function getFocusableElements(scope: HTMLElement): HTMLElement[] {
const selector = [
"a[href]",
@@ -214,6 +255,7 @@ function detachWebOverlayListeners(): void {
function addWebOverlay(entry: WebOverlayEntry): (options?: RemoveWebOverlayOptions) => void {
webOverlayEntries.push(entry);
attachWebOverlayListeners();
notifyWebOverlayChanges();
const focusFrame = window.requestAnimationFrame(() => {
const scope = entry.getScope();
@@ -240,6 +282,7 @@ function addWebOverlay(entry: WebOverlayEntry): (options?: RemoveWebOverlayOptio
) {
entry.restoreFocus.focus();
}
notifyWebOverlayChanges();
};
}
@@ -31,6 +31,7 @@ import { subscriptionFixture } from "../subscription-fixture";
type WorkspaceFetchResult = Awaited<ReturnType<DaemonClient["fetchWorkspaces"]>>;
type ProjectListResult = Awaited<ReturnType<DaemonClient["listProjects"]>>;
type AgentFetchResult = Awaited<ReturnType<DaemonClient["fetchAgents"]>>;
type WorkspaceScriptsResult = Awaited<ReturnType<DaemonClient["listWorkspaceScripts"]>>;
class FakeDirectoryClient {
supportsBackgroundWorkspaces(): boolean {
@@ -181,6 +182,14 @@ class FakeDirectoryClient {
};
}
listWorkspaceScriptsCalls = 0;
workspaceScripts: WorkspaceScriptsResult["scripts"] = [];
async listWorkspaceScripts(workspaceId: string): Promise<WorkspaceScriptsResult> {
this.listWorkspaceScriptsCalls += 1;
return { requestId: "scripts", workspaceId, scripts: this.workspaceScripts, error: null };
}
getLastServerInfoMessage() {
return this.supportsWorkspaceLabels ? { features: { workspaceLabels: true } } : null;
}
@@ -482,6 +491,52 @@ describe("DirectorySync session readiness", () => {
directory.dispose();
});
it("keeps a workspace's script status live without demanding the directory", async () => {
const serverId = "script-status-demand";
const { client, directory } = createDirectory(serverId);
useSessionStore.getState().initializeSession(serverId, client as unknown as DaemonClient, 1);
const workspace = normalizeWorkspaceDescriptor({
...createWorkspaceEntry("workspace-1"),
scripts: [],
});
directory.acceptWorkspaces([workspace]);
const script = {
scriptName: "worker",
type: "script" as const,
hostname: "worker.paseo.localhost",
port: null,
proxyUrl: null,
lifecycle: "running" as const,
health: null,
exitCode: null,
terminalId: "terminal-1",
};
const lifecycle = () =>
useSessionStore.getState().sessions[serverId]?.workspaces.get(workspace.id)?.scripts[0]
?.lifecycle;
client.workspaceScripts = [script];
const source = {};
directory.setScriptStatusDemand(source, workspace.id);
await expect.poll(lifecycle).toBe("running");
client.emit({
type: "script_status_update",
payload: { workspaceId: workspace.id, scripts: [{ ...script, lifecycle: "stopped" }] },
});
expect(lifecycle()).toBe("stopped");
expect(client.fetchAgentsCalls).toBe(0);
expect(client.fetchWorkspacesCalls).toBe(0);
directory.setScriptStatusDemand(source, null);
client.emit({
type: "script_status_update",
payload: { workspaceId: workspace.id, scripts: [script] },
});
expect(lifecycle()).toBe("stopped");
directory.dispose();
});
it("subscribes to live agent updates when the directory is demanded", async () => {
const serverId = "demanded-directory-subscription";
const { client, directory } = createDirectory(serverId);
@@ -150,6 +150,7 @@ export class DirectorySync {
private agentSubscription: OwnedSubscription<FetchAgentsPayload> | null = null;
private workspaceSubscription: OwnedSubscription<FetchWorkspacesPayload> | null = null;
private eventSubscription: ReturnType<DaemonClient["observeEvents"]> | null = null;
private scriptStatusSubscription: ReturnType<DaemonClient["observeEvents"]> | null = null;
private readonly abortSessionWaits = new Set<() => void>();
private cacheLoad: Promise<void> | null = null;
private cacheAccepted = false;
@@ -157,6 +158,7 @@ export class DirectorySync {
private workspaceRevision = 0;
private readonly routeDemandIds = new Set<string>();
private readonly fullDemandSources = new Set<object>();
private readonly scriptStatusDemand = new Map<object, string>();
private demandRefresh: Promise<void> | null = null;
private satisfiedDemandSource: DirectorySourceToken | null = null;
private cursors: DirectoryCheckpoint = {};
@@ -189,10 +191,12 @@ export class DirectorySync {
}
this.flushAbortedTransactions();
this.releaseSubscriptions();
this.releaseScriptStatusEvents();
workspaceLabels.disconnect(this.serverId);
this.connection = connection;
this.abortPendingSessionWaits();
if (!connection.client || connection.status !== "online") return true;
if (this.scriptStatusDemand.size > 0) this.observeScriptStatusEvents();
// Reattach labels here because route-only demand can satisfy the epoch before full demand requests them.
void this.connectWorkspaceLabels().catch(() => undefined);
if (this.hasDemand()) void this.requestDemandRefresh().catch(() => undefined);
@@ -226,10 +230,32 @@ export class DirectorySync {
}
}
/**
* Keeps one workspace's script status live without demanding the directory: a
* script_status_update subscription, plus one scripts fetch to cover what changed before it.
*/
setScriptStatusDemand(source: object, workspaceId: string | null): void {
if (!workspaceId) {
this.scriptStatusDemand.delete(source);
if (!this.wantsScriptStatus()) this.releaseScriptStatusEvents();
return;
}
this.scriptStatusDemand.set(source, workspaceId);
if (!this.getOnlineConnection()) return;
// A new subscription fetches every demanded workspace once its snapshot lands.
if (!this.scriptStatusSubscription) this.observeScriptStatusEvents();
else
void this.scriptStatusSubscription.ready
.then(() => this.fetchScriptStatus(workspaceId))
.catch(() => undefined);
}
dispose(): void {
this.flushAbortedTransactions();
this.abortPendingSessionWaits();
this.scriptStatusDemand.clear();
this.releaseSubscriptions();
this.releaseScriptStatusEvents();
this.fullDemandSources.clear();
this.routeDemandIds.clear();
workspaceLabels.disconnect(this.serverId);
@@ -247,6 +273,12 @@ export class DirectorySync {
this.workspaceSubscription = null;
this.eventSubscription = null;
this.satisfiedDemandSource = null;
if (!this.wantsScriptStatus()) this.releaseScriptStatusEvents();
}
private releaseScriptStatusEvents(): void {
void this.scriptStatusSubscription?.release().catch(() => undefined);
this.scriptStatusSubscription = null;
}
private receiveAgentDelta(source: DirectorySourceToken, delta: AgentDirectoryDelta): void {
@@ -276,22 +308,51 @@ export class DirectorySync {
private observeDirectoryEvents(): void {
if (this.eventSubscription) return;
const { client, source } = this.requireOnline();
this.eventSubscription = client.observeEvents(["project.update", "script_status_update"]);
this.eventSubscription = client.observeEvents(["project.update"]);
this.eventSubscription.subscribe({
snapshot: () => {},
update: (message) => {
if (!this.isCurrent(client, source)) return;
if (message.type === "project.update") this.receiveWorkspaceDelta(source, message.payload);
if (message.type === "script_status_update")
this.receiveWorkspaceDelta(source, { kind: "script_status", update: message.payload });
},
});
}
// Script status has its own subscription so a workspace screen can hold it without the directory.
private observeScriptStatusEvents(): void {
if (this.scriptStatusSubscription) return;
const { client, source } = this.requireOnline();
this.scriptStatusSubscription = client.observeEvents(["script_status_update"]);
this.scriptStatusSubscription.subscribe({
snapshot: () => {
for (const workspaceId of new Set(this.scriptStatusDemand.values()))
void this.fetchScriptStatus(workspaceId).catch(() => undefined);
},
update: (message) => {
if (!this.isCurrent(client, source) || message.type !== "script_status_update") return;
this.receiveWorkspaceDelta(source, { kind: "script_status", update: message.payload });
},
});
}
private async fetchScriptStatus(workspaceId: string): Promise<void> {
const { client, source } = this.requireOnline();
const result = await client.listWorkspaceScripts(workspaceId);
if (!this.isCurrent(client, source) || result.error || !result.scripts) return;
this.receiveWorkspaceDelta(source, {
kind: "script_status",
update: { workspaceId, scripts: result.scripts },
});
}
private hasDemand(): boolean {
return this.fullDemandSources.size > 0 || this.routeDemandIds.size > 0;
}
private wantsScriptStatus(): boolean {
return this.hasDemand() || this.scriptStatusDemand.size > 0;
}
private requestDemandRefresh(force = false): Promise<void> {
if (this.demandRefresh) return this.demandRefresh;
if (!this.hasDemand()) return Promise.resolve();
@@ -299,6 +360,7 @@ export class DirectorySync {
return this.fullDemandSources.size > 0 ? this.loadCachedDirectory() : Promise.resolve();
}
this.observeDirectoryEvents();
this.observeScriptStatusEvents();
const source = this.connection.source;
if (
!force &&
+8
View File
@@ -2606,6 +2606,14 @@ export class HostRuntimeStore {
return () => directory.setDemand(source, false);
}
acquireScriptStatusDemand(serverId: string, workspaceId: string): () => void {
const directory = this.directorySyncByServer.get(serverId);
if (!directory) return () => undefined;
const source = {};
directory.setScriptStatusDemand(source, workspaceId);
return () => directory.setScriptStatusDemand(source, null);
}
async prepareAgentRoute(serverId: string, agentId: string): Promise<void> {
const directory = this.directorySyncByServer.get(serverId);
if (!directory) throw new Error(`Unknown host runtime for serverId ${serverId}`);
@@ -255,7 +255,93 @@ function deleteDirectory(cache: ReplicaCache, serverId: string): void {
]);
}
async function cacheWithoutBackgroundVisibility() {
const storage = new MemoryStorage();
const writer = createCache(storage);
const checkpoint = {
agents: { generation: "g", afterSeq: 12 },
projects: { generation: "g", afterSeq: 4 },
workspaces: { generation: "g", afterSeq: 8 },
};
const baseline = directory(checkpoint);
commitDirectory(writer, SERVER_ID, baseline);
writer.commitTimeline(SERVER_ID, "agent-1", timeline());
await writer.flush();
const key = `${SERVER_ID}:workspace:workspace-1`;
const row = storage.rows.get(key)!;
const payload = JSON.parse(row.payload) as Record<string, unknown>;
delete payload.background;
storage.rows.set(key, { ...row, payload: JSON.stringify(payload) });
return { storage, baseline, reader: createCache(storage) };
}
async function expectLegacyWorkspaceRefresh({
storage,
baseline,
reader,
}: Awaited<ReturnType<typeof cacheWithoutBackgroundVisibility>>): Promise<void> {
const restored = await reader.readDirectory(SERVER_ID);
expect(restored.workspaces.size).toBe(0);
expect(restored.checkpoint).toEqual({
agents: baseline.checkpoint.agents,
projects: baseline.checkpoint.projects,
});
expect(restored.agents).toEqual(baseline.agents);
expect(restored.projects).toEqual(baseline.projects);
expect(await reader.readTimeline(SERVER_ID, "agent-1")).toEqual(timeline());
expect((await createCache(storage).readDirectory(SERVER_ID)).checkpoint).toEqual(
restored.checkpoint,
);
baseline.workspaces.set(
"workspace-1",
normalizeWorkspaceDescriptor({ ...workspacePayload(), background: true }),
);
reader.replaceDirectoryBaseline(SERVER_ID, baseline);
await reader.flush();
const refreshed = await createCache(storage).readDirectory(SERVER_ID);
expect(refreshed.workspaces.get("workspace-1")?.background).toBe(true);
expect(refreshed.checkpoint).toEqual(baseline.checkpoint);
}
describe("ReplicaCache", () => {
it.each([true, false, undefined])(
"preserves background visibility (%s) when reopening a cached workspace",
async (background) => {
const storage = new MemoryStorage();
const writer = createCache(storage);
const baseline = directory();
baseline.workspaces.set(
"workspace-1",
normalizeWorkspaceDescriptor({ ...workspacePayload(), background }),
);
commitDirectory(writer, SERVER_ID, baseline);
await writer.flush();
const reader = createCache(storage);
expect(
(await reader.readDirectory(SERVER_ID)).workspaces.get("workspace-1")?.background,
).toBe(background ?? false);
expect((await reader.readWorkspace(SERVER_ID, "workspace-1"))?.workspace.background).toBe(
background ?? false,
);
},
);
it("refetches workspaces cached without background visibility after a directory read", async () => {
const cached = await cacheWithoutBackgroundVisibility();
await expectLegacyWorkspaceRefresh(cached);
});
it("refetches workspaces cached without background visibility after a workspace read", async () => {
const cached = await cacheWithoutBackgroundVisibility();
expect(await cached.reader.readWorkspace(SERVER_ID, "workspace-1")).toBeUndefined();
await expectLegacyWorkspaceRefresh(cached);
});
it("rejects pre-baseline-fix checkpoints without discarding cached rows or timelines", async () => {
const storage = new MemoryStorage();
const writer = createCache(storage);
@@ -464,6 +550,19 @@ describe("ReplicaCache", () => {
expect((await cache.readDirectory(SERVER_ID)).projects.size).toBe(0);
});
it("does not return an accepted agent that storage rejected", async () => {
const storage = new MemoryStorage();
const cache = createCache(storage);
storage.persistentWriteFailure = new Error("disk unavailable");
commitDirectory(cache, SERVER_ID, directory());
await cache.flush();
const result = await cache.readAgent(SERVER_ID, "agent-1");
expect(storage.rows.size).toBe(0);
expect(result).toBeUndefined();
});
it("fails closed when an accepted deletion cannot be persisted before a read", async () => {
const storage = new MemoryStorage();
const cache = createCache(storage);
@@ -504,6 +603,25 @@ describe("ReplicaCache", () => {
expect((await cache.readWorkspace(SERVER_ID, "workspace-1"))?.workspace.id).toBe("workspace-1");
});
it("discards an in-flight read across host removal and reactivation", async () => {
const storage = new MemoryStorage();
const cache = createCache(storage);
commitDirectory(cache, SERVER_ID, directory());
await cache.flush();
const started = deferred();
const release = deferred();
storage.onRead = started.resolve;
storage.readGate = release.promise;
const reading = cache.readAgent(SERVER_ID, "agent-1");
await started.promise;
cache.setHosts([]);
cache.setHosts([SERVER_ID]);
release.resolve();
expect(await reading).toBeUndefined();
});
it("discards a durable read when the host changes while it is in flight", async () => {
const storage = new MemoryStorage();
const cache = createCache(storage);
@@ -522,6 +640,36 @@ describe("ReplicaCache", () => {
expect(await reading).toBeUndefined();
});
it("retries a timeline read when that same timeline changes in flight", async () => {
const storage = new MemoryStorage();
const cache = createCache(storage);
cache.commitTimeline(SERVER_ID, "agent-1", timeline("Old"));
await cache.flush();
storage.onRead = () => {
storage.onRead = null;
cache.commitTimeline(SERVER_ID, "agent-1", timeline("New"));
};
expect((await cache.readTimeline(SERVER_ID, "agent-1"))?.items).toEqual([timelineItem("New")]);
expect(storage.reads).toHaveLength(2);
});
it("discards a requested row removed by a directory baseline replacement in flight", async () => {
const storage = new MemoryStorage();
const cache = createCache(storage);
commitDirectory(cache, SERVER_ID, directory());
await cache.flush();
const replacement = directory();
replacement.agents.clear();
storage.onRead = () => {
storage.onRead = null;
cache.replaceDirectoryBaseline(SERVER_ID, replacement);
};
expect(await cache.readAgent(SERVER_ID, "agent-1")).toBeUndefined();
expect(storage.reads).toHaveLength(2);
});
it("never reads a timeline older than an accepted deferred replacement", async () => {
const storage = new MemoryStorage();
const cache = createCache(storage);
@@ -796,7 +944,7 @@ describe("ReplicaCache", () => {
]);
});
it("retries a timeline read invalidated by a concurrent directory commit", async () => {
it("reads a persisted timeline across a concurrent directory commit", async () => {
const storage = new MemoryStorage();
const cache = createCache(storage);
cache.commitTimeline(SERVER_ID, "agent-1", timeline("Persisted timeline"));
@@ -858,6 +1006,90 @@ describe("ReplicaCache", () => {
expect(storage.cleanups).toBe(1);
});
describe.each(["timeline", "directory"] as const)(
"while another agent streams %s updates",
(kind) => {
async function streamingCache() {
const storage = new MemoryStorage();
const cache = createCache(storage);
commitDirectory(cache, SERVER_ID, directory());
cache.commitTimeline(SERVER_ID, "agent-1", timeline());
await cache.flush();
const readsBefore = storage.reads.length;
const writesBefore = storage.writes;
let chunks = 0;
storage.onRead = () => {
if (chunks >= 200) return;
chunks += 1;
if (kind === "timeline") {
cache.commitTimeline(SERVER_ID, "agent-2", {
...timeline(`chunk ${chunks}`),
agentId: "agent-2",
});
} else {
cache.commitDirectoryMutations(
SERVER_ID,
[{ type: "upsert", kind: "agent", id: "agent-2", value: agent("agent-2") }],
{ agents: { generation: "g", afterSeq: 12 + chunks } },
);
}
};
return {
cache,
expectReads: (count: number, writes = 0) => {
expect(storage.reads.length - readsBefore).toBe(count);
expect(storage.writes - writesBefore).toBe(writes);
expect(chunks).toBe(count);
},
};
}
it("reads another cached agent without waiting for the stream to stop", async () => {
const { cache, expectReads } = await streamingCache();
expect((await cache.readAgent(SERVER_ID, "agent-1"))?.title).toBe("Cached agent");
expectReads(1);
await cache.flush();
});
it("reads another cached workspace without waiting for the stream to stop", async () => {
const { cache, expectReads } = await streamingCache();
expect((await cache.readWorkspace(SERVER_ID, "workspace-1"))?.workspace.name).toBe("main");
expectReads(2, 1);
await cache.flush();
});
it("reads another cached timeline without waiting for the stream to stop", async () => {
const { cache, expectReads } = await streamingCache();
expect(await cache.readTimeline(SERVER_ID, "agent-1")).toEqual(timeline());
expectReads(1);
await cache.flush();
});
},
);
it("reads the directory after persisting a pending baseline replacement", async () => {
const storage = new MemoryStorage();
const cache = createCache(storage);
commitDirectory(cache, SERVER_ID, directory());
cache.commitTimeline(SERVER_ID, "agent-1", timeline());
await cache.flush();
const replacement = directory({ agents: { generation: "g2", afterSeq: 1 } });
replacement.projects.clear();
replacement.agents.set("agent-2", agent("agent-2"));
cache.replaceDirectoryBaseline(SERVER_ID, replacement);
const read = await cache.readDirectory(SERVER_ID);
expect([...read.agents.keys()].sort()).toEqual(["agent-1", "agent-2"]);
expect(read.projects.size).toBe(0);
expect(read.checkpoint).toEqual({ agents: { generation: "g2", afterSeq: 1 } });
expect(await cache.readTimeline(SERVER_ID, "agent-1")).toEqual(timeline());
expect(storage.writes).toBe(2);
});
});
it("retains semantic agent messages across disk-cache reconstruction", async () => {
+67 -19
View File
@@ -306,6 +306,8 @@ const StoredWorkspaceSchema = z.strictObject({
worktreeSlug: z.string().optional(),
projectKind: z.enum(["git", "non_git", "directory"]),
workspaceKind: z.enum(["directory", "local_checkout", "checkout", "worktree"]),
// Require the flag so older rows that lost background visibility invalidate the workspace cursor.
background: z.boolean(),
name: z.string(),
title: z.string().nullable(),
pinnedAt: z.string().nullable(),
@@ -698,6 +700,7 @@ function serializeWorkspace(workspace: WorkspaceDescriptor): StoredWorkspace {
worktreeSlug: workspace.worktreeSlug,
projectKind: workspace.projectKind,
workspaceKind: workspace.workspaceKind,
background: workspace.background ?? false,
name: workspace.name,
title: workspace.title ?? null,
pinnedAt: workspace.pinnedAt ?? null,
@@ -880,9 +883,24 @@ function directoryEntityForRow(row: ReplicaRow): keyof DirectoryCheckpoint | und
return undefined;
}
interface ReplicaRead {
serverId: string;
kinds: readonly ReplicaRowKind[];
ids?: readonly string[];
invalidated: boolean;
}
function matchesReplicaRead(read: ReplicaRead, row: ReplicaRowKey): boolean {
return (
read.serverId === row.serverId &&
read.kinds.includes(row.kind) &&
(!read.ids || read.ids.includes(row.id))
);
}
export class ReplicaCache {
private readonly activeServerIds = new Set<string>();
private readonly hostRevisions = new Map<string, number>();
private readonly activeReads = new Set<ReplicaRead>();
private readonly storedRows = new Map<string, Map<string, ReplicaRow>>();
private readonly hostBytes = new Map<string, number>();
private readonly hostWriteOrder = new Map<string, true>();
@@ -1004,10 +1022,22 @@ export class ReplicaCache {
// accepted commits to land. A store that rejects them will keep rejecting them: fail closed
// rather than re-attempt the write on every pass. A write rejected for another host leaves
// this host's stored rows readable.
if (!(await this.syncPending()) && this.hasPendingHostChanges(serverId)) return [];
const revision = this.hostRevisions.get(serverId) ?? 0;
const rows = await this.rowStore.read(serverId, kinds, ids);
if (this.canReadHostRevision(serverId, revision)) return rows;
const read: ReplicaRead = { serverId, kinds, ids, invalidated: false };
this.activeReads.add(read);
try {
if (!(await this.syncPending()) && this.hasPendingHostChanges(serverId)) return [];
if (read.invalidated || this.hasPendingReadChanges(read)) continue;
const rows = await this.rowStore.read(serverId, kinds, ids);
if (
this.activeServerIds.has(serverId) &&
!read.invalidated &&
!this.hasPendingReadChanges(read)
) {
return rows;
}
} finally {
this.activeReads.delete(read);
}
}
return [];
} catch {
@@ -1092,7 +1122,6 @@ export class ReplicaCache {
): void {
if (!this.activeServerIds.has(serverId)) return;
if (this.invalidatedHosts.has(serverId)) return;
this.advanceHostRevision(serverId);
for (const mutation of mutations) {
if (mutation.type === "delete") {
this.queueEntityDelete(serverId, mutation.kind, mutation.id);
@@ -1118,7 +1147,7 @@ export class ReplicaCache {
replaceDirectoryBaseline(serverId: string, directory: CachedDirectory): void {
if (!this.activeServerIds.has(serverId)) return;
this.advanceHostRevision(serverId);
this.invalidateHostReads(serverId, ["agent", "workspace", "project", "checkpoint"]);
// Replacing the directory must not discard independently accepted timeline changes.
for (const [key, row] of this.pendingUpserts) {
if (row.serverId === serverId && row.kind !== "timeline") this.pendingUpserts.delete(key);
@@ -1150,7 +1179,6 @@ export class ReplicaCache {
commitTimeline(serverId: string, agentId: string, timeline: CachedTimeline): void {
if (!this.activeServerIds.has(serverId)) return;
if (timeline.agentId !== agentId) throw new Error("Timeline cache key does not match payload");
this.advanceHostRevision(serverId);
this.queueUpsert({ serverId, kind: "timeline", id: agentId, value: timeline });
this.schedulePersist();
}
@@ -1159,7 +1187,7 @@ export class ReplicaCache {
const next = new Set(serverIds);
const removed = [...this.activeServerIds].filter((serverId) => !next.has(serverId));
const added = [...next].filter((serverId) => !this.activeServerIds.has(serverId));
for (const serverId of [...removed, ...added]) this.advanceHostRevision(serverId);
for (const serverId of [...removed, ...added]) this.invalidateHostReads(serverId);
this.activeServerIds.clear();
for (const serverId of next) this.activeServerIds.add(serverId);
for (const serverId of removed) {
@@ -1171,8 +1199,8 @@ export class ReplicaCache {
}
reconcileServerId(oldServerId: string, newServerId: string): void {
this.advanceHostRevision(oldServerId);
this.advanceHostRevision(newServerId);
this.invalidateHostReads(oldServerId);
this.invalidateHostReads(newServerId);
const rows = this.storedRows.get(oldServerId);
if (rows) {
const newRows = this.storedRows.get(newServerId) ?? new Map<string, ReplicaRow>();
@@ -1250,12 +1278,14 @@ export class ReplicaCache {
}
private queueUpsert(row: StructuredReplicaUpsert): void {
this.invalidateRowReads(row);
const key = pendingRowKey(row);
this.pendingDeletes.delete(key);
this.pendingUpserts.set(key, row);
}
private queueDelete(key: ReplicaRowKey): void {
this.invalidateRowReads(key);
const pendingKey = pendingRowKey(key);
this.pendingUpserts.delete(pendingKey);
this.pendingDeletes.set(pendingKey, key);
@@ -1267,14 +1297,36 @@ export class ReplicaCache {
);
}
private canReadHostRevision(serverId: string, revision: number): boolean {
private hasPendingReadChanges(read: ReplicaRead): boolean {
if (
this.pendingBaselines.has(read.serverId) &&
read.kinds.some((kind) => kind !== "timeline")
) {
return true;
}
return (
this.activeServerIds.has(serverId) &&
(this.hostRevisions.get(serverId) ?? 0) === revision &&
!this.hasPendingHostChanges(serverId)
[...this.pendingUpserts.values()].some((row) => matchesReplicaRead(read, row)) ||
[...this.pendingDeletes.values()].some((row) => matchesReplicaRead(read, row))
);
}
private invalidateRowReads(row: ReplicaRowKey): void {
for (const read of this.activeReads) {
if (matchesReplicaRead(read, row)) read.invalidated = true;
}
}
private invalidateHostReads(serverId: string, kinds?: readonly ReplicaRowKind[]): void {
for (const read of this.activeReads) {
if (
read.serverId === serverId &&
(!kinds || kinds.some((kind) => read.kinds.includes(kind)))
) {
read.invalidated = true;
}
}
}
private hasPendingHostChanges(serverId: string): boolean {
if (this.pendingBaselines.has(serverId)) return true;
for (const row of this.pendingUpserts.values()) {
@@ -1286,10 +1338,6 @@ export class ReplicaCache {
return false;
}
private advanceHostRevision(serverId: string): void {
this.hostRevisions.set(serverId, (this.hostRevisions.get(serverId) ?? 0) + 1);
}
private drainPendingChanges(): PendingReplicaChanges {
const changes = {
upserts: [...this.pendingUpserts.values()],
+47 -30
View File
@@ -120,6 +120,7 @@ import { MetadataGenerationPage } from "@/screens/settings/metadata-generation-p
import ProjectsScreen from "@/screens/projects-screen";
import ProjectSettingsScreen from "@/screens/project-settings-screen";
import { SETTINGS_DESKTOP_SIDEBAR_WIDTH, useIsCompactFormFactor } from "@/constants/layout";
import { densityIconBox, densityIconSize } from "@/styles/density";
import { useLocalDaemonServerId } from "@/hooks/use-is-local-daemon";
import {
type EnableBuiltInDaemonOption,
@@ -758,7 +759,7 @@ function SidebarSectionButton({
isSelected,
onSelect,
}: SidebarSectionButtonProps) {
const { theme } = useUnistyles();
const { theme, rt } = useUnistyles();
const handlePress = useCallback(() => {
onSelect(itemId);
}, [onSelect, itemId]);
@@ -775,7 +776,7 @@ function SidebarSectionButton({
style={isSelected ? selectedSidebarItemStyle : sidebarItemStyle}
>
<IconComponent
size={theme.iconSize.md}
size={densityIconSize(rt, "md")}
color={isSelected ? theme.colors.foreground : theme.colors.foregroundMuted}
strokeWidth={SIDEBAR_ICON_STROKE_WIDTH}
/>
@@ -801,7 +802,7 @@ function SidebarHostSectionButton({
isSelected,
onSelect,
}: SidebarHostSectionButtonProps) {
const { theme } = useUnistyles();
const { theme, rt } = useUnistyles();
const handlePress = useCallback(() => {
onSelect(itemId);
}, [onSelect, itemId]);
@@ -819,7 +820,7 @@ function SidebarHostSectionButton({
style={isSelected ? selectedSidebarItemStyle : sidebarItemStyle}
>
<IconComponent
size={theme.iconSize.md}
size={densityIconSize(rt, "md")}
color={isSelected ? theme.colors.foreground : theme.colors.foregroundMuted}
strokeWidth={SIDEBAR_ICON_STROKE_WIDTH}
/>
@@ -912,6 +913,16 @@ function HostPicker({
);
}
/** A labelled group of sidebar rows. On compact layouts the rows sit together in one island. */
function SidebarGroup({ label, children }: { label?: string; children: ReactNode }) {
return (
<View style={sidebarStyles.group}>
{label ? <Text style={sidebarStyles.groupLabel}>{label}</Text> : null}
<View style={sidebarStyles.island}>{children}</View>
</View>
);
}
interface SettingsSidebarProps {
view: SettingsView;
onSelectSection: (section: SettingsSectionSlug) => void;
@@ -933,7 +944,7 @@ function SettingsSidebar({
activeHostServerId,
layout,
}: SettingsSidebarProps) {
const { theme } = useUnistyles();
const { theme, rt } = useUnistyles();
const { t } = useTranslation();
const hosts = useHosts();
const localServerId = useLocalDaemonServerId();
@@ -960,8 +971,7 @@ function SettingsSidebar({
const sidebarBody = (
<>
<View style={sidebarStyles.list}>
<Text style={sidebarStyles.groupLabel}>{t("settings.groups.app")}</Text>
<SidebarGroup label={t("settings.groups.app")}>
{items.map((item) => (
<SidebarSectionButton
key={item.id}
@@ -972,10 +982,9 @@ function SettingsSidebar({
onSelect={onSelectSection}
/>
))}
</View>
</SidebarGroup>
{hasHosts ? (
<View style={sidebarStyles.list}>
<Text style={sidebarStyles.groupLabel}>{t("settings.groups.host")}</Text>
<SidebarGroup label={t("settings.groups.host")}>
<HostPicker
activeServerId={activeHostServerId}
sortedHosts={sortedHosts}
@@ -993,9 +1002,9 @@ function SettingsSidebar({
onSelect={onSelectHostSection}
/>
))}
</View>
</SidebarGroup>
) : (
<View style={sidebarStyles.list}>
<SidebarGroup>
<Pressable
accessibilityRole="button"
accessibilityLabel={t("settings.addHost")}
@@ -1004,7 +1013,7 @@ function SettingsSidebar({
style={sidebarItemStyle}
>
<Plus
size={theme.iconSize.md}
size={densityIconSize(rt, "md")}
color={theme.colors.foregroundMuted}
strokeWidth={SIDEBAR_ICON_STROKE_WIDTH}
/>
@@ -1021,7 +1030,7 @@ function SettingsSidebar({
style={sidebarItemStyle}
>
<Server
size={theme.iconSize.md}
size={densityIconSize(rt, "md")}
color={theme.colors.foregroundMuted}
strokeWidth={SIDEBAR_ICON_STROKE_WIDTH}
/>
@@ -1030,7 +1039,7 @@ function SettingsSidebar({
</Text>
</Pressable>
) : null}
</View>
</SidebarGroup>
)}
</>
);
@@ -1572,26 +1581,33 @@ const sidebarStyles = StyleSheet.create((theme) => ({
paddingVertical: theme.spacing[2],
paddingHorizontal: theme.spacing[2],
},
list: {
// Compact values draw each group as an island of tiles; desktop keeps a plain list.
group: {
paddingVertical: theme.spacing[2],
paddingHorizontal: theme.spacing[2],
gap: theme.spacing[0.5],
gap: { xs: theme.spacing[1], md: theme.spacing[0.5] },
},
groupLabel: {
fontSize: theme.fontSize.base,
fontWeight: theme.fontWeight.normal,
color: theme.colors.foregroundExtraMuted,
paddingHorizontal: theme.spacing[2],
paddingHorizontal: { xs: theme.spacing[4], md: theme.spacing[2] },
paddingVertical: theme.spacing[1],
},
island: {
gap: { xs: 2, md: theme.spacing[0.5] },
borderRadius: { xs: theme.borderRadius["2xl"], md: 0 },
overflow: "hidden",
},
item: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[2],
minHeight: 28,
gap: { xs: theme.spacing[3], md: theme.spacing[2] },
minHeight: { xs: 52, md: 28 },
paddingVertical: theme.spacing[1],
paddingHorizontal: theme.spacing[2],
borderRadius: theme.borderRadius.lg,
paddingHorizontal: { xs: theme.spacing[4], md: theme.spacing[2] },
borderRadius: { xs: 0, md: theme.borderRadius.lg },
backgroundColor: { xs: theme.colors.surface1, md: "transparent" },
},
itemHovered: {
backgroundColor: theme.colors.surfaceSidebarHover,
@@ -1600,7 +1616,7 @@ const sidebarStyles = StyleSheet.create((theme) => ({
backgroundColor: theme.colors.surfaceSidebarHover,
},
label: {
fontSize: theme.fontSize.base,
fontSize: { xs: theme.fontSize.lg, md: theme.fontSize.base },
color: theme.colors.foregroundMuted,
fontWeight: theme.fontWeight.normal,
flex: 1,
@@ -1608,11 +1624,12 @@ const sidebarStyles = StyleSheet.create((theme) => ({
pickerTrigger: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[2],
minHeight: 28,
gap: { xs: theme.spacing[3], md: theme.spacing[2] },
minHeight: { xs: 52, md: 28 },
paddingVertical: theme.spacing[1],
paddingHorizontal: theme.spacing[2],
borderRadius: theme.borderRadius.lg,
paddingHorizontal: { xs: theme.spacing[4], md: theme.spacing[2] },
borderRadius: { xs: 0, md: theme.borderRadius.lg },
backgroundColor: { xs: theme.colors.surface1, md: "transparent" },
},
pickerTriggerHovered: {
backgroundColor: theme.colors.surfaceSidebarHover,
@@ -1620,14 +1637,14 @@ const sidebarStyles = StyleSheet.create((theme) => ({
pickerTriggerLabel: {
flex: 1,
minWidth: 0,
fontSize: theme.fontSize.base,
fontSize: { xs: theme.fontSize.lg, md: theme.fontSize.base },
color: theme.colors.foreground,
fontWeight: theme.fontWeight.normal,
},
// Match the setting items' icon footprint so the host label aligns with them.
pickerTriggerDot: {
width: theme.iconSize.md,
height: theme.iconSize.md,
width: densityIconBox("md"),
height: densityIconBox("md"),
alignItems: "center",
justifyContent: "center",
},
@@ -19,6 +19,7 @@ import { useKeyboardShortcutOverrides } from "@/hooks/use-keyboard-shortcut-over
import {
buildKeyboardShortcutHelpSections,
getBindingIdForAction,
normalizeCapturedShortcutCombo,
getDefaultKeysForAction,
resolveShortcutKeysForAction,
type KeyboardShortcutHelpRow,
@@ -389,7 +390,8 @@ export function KeyboardShortcutsSection() {
}
setHeldModifiers(null);
setCapturedCombos((current) => [...current, comboString]);
const capturedCombo = normalizeCapturedShortcutCombo(capturingBindingId!, comboString);
setCapturedCombos((current) => [...current, capturedCombo]);
}
window.addEventListener("keydown", handleKeyDown, true);
@@ -6,6 +6,7 @@ import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { ProviderSnapshotEntry } from "@getpaseo/protocol/agent-types";
import type { MutableDaemonConfig } from "@getpaseo/protocol/messages";
import { ToastApiProvider } from "@/contexts/toast-api-context";
const { theme, snapshotState, configState, patchConfigMock, openProviderSettingsMock } = vi.hoisted(
() => ({
@@ -281,6 +282,12 @@ vi.mock("@/utils/confirm-dialog", () => ({
import { ProvidersSection } from "./providers-section";
function unexpectedToast(): never {
throw new Error("Provider row interactions should not display a toast");
}
const toastApi = { show: unexpectedToast, copied: unexpectedToast, error: unexpectedToast };
const claudeEntry: ProviderSnapshotEntry = {
provider: "claude",
status: "ready",
@@ -366,7 +373,11 @@ describe("ProvidersSection", () => {
function render(): void {
act(() => {
root?.render(<ProvidersSection serverId="server-1" />);
root?.render(
<ToastApiProvider api={toastApi}>
<ProvidersSection serverId="server-1" />
</ToastApiProvider>,
);
});
}
@@ -11,6 +11,7 @@ import {
} from "react-native";
import { StyleSheet, useUnistyles } from "react-native-unistyles";
import { useIsCompactFormFactor } from "@/constants/layout";
import { useToast } from "@/contexts/toast-api-context";
import { settingsStyles } from "@/styles/settings";
import { useHostRuntimeIsConnected } from "@/runtime/host-runtime";
import { useHostFeature } from "@/runtime/host-features";
@@ -19,6 +20,7 @@ import { useDaemonConfig } from "@/hooks/use-daemon-config";
import { buildProviderDefinitions } from "@/utils/provider-definitions";
import {
buildAcpProviderConfigPatch,
getAcpProviderCatalog,
type AcpProviderCatalogItem,
} from "@/hooks/use-acp-provider-catalog";
import { ProviderCatalogList } from "@/components/provider-catalog-list";
@@ -325,7 +327,9 @@ export interface ProvidersSectionProps {
export function ProvidersSection({ serverId }: ProvidersSectionProps) {
const { t } = useTranslation();
const toast = useToast();
const isConnected = useHostRuntimeIsConnected(serverId);
const supportsHopliteProvider = useHostFeature(serverId, "hopliteProvider");
const supportsProviderRemoval = useHostFeature(serverId, "providerRemoval");
const { entries, isLoading, refresh } = useProvidersSnapshot(serverId);
const { config, patchConfig } = useDaemonConfig(serverId);
@@ -338,9 +342,16 @@ export function ProvidersSection({ serverId }: ProvidersSectionProps) {
const providerDefinitions = useMemo(() => buildProviderDefinitions(entries), [entries]);
const hasServer = serverId.length > 0;
/** Custom providers are deletable only when config.json holds their `extends` definition. */
/** Config owns derived providers and opt-in bundled catalog providers. */
const isConfigOwnedProvider = useCallback(
(providerId: string) => Boolean(config?.providers?.[providerId]?.extends),
(providerId: string) =>
Boolean(
config?.providers?.[providerId] &&
(config.providers[providerId].extends ||
getAcpProviderCatalog().some(
(entry) => entry.id === providerId && entry.bundledProvider,
)),
),
[config],
);
@@ -405,18 +416,15 @@ export function ProvidersSection({ serverId }: ProvidersSectionProps) {
if (installingProviderId) return;
setInstallingProviderId(entry.id);
try {
await patchConfig(buildAcpProviderConfigPatch(entry));
await patchConfig(buildAcpProviderConfigPatch(entry, supportsHopliteProvider));
await refresh([entry.id]);
} catch (error) {
Alert.alert(
t("settings.providers.addErrorTitle"),
error instanceof Error ? error.message : String(error),
);
toast.error(error instanceof Error ? error.message : String(error));
} finally {
setInstallingProviderId((current) => (current === entry.id ? null : current));
}
},
[installingProviderId, patchConfig, refresh, t],
[installingProviderId, patchConfig, refresh, supportsHopliteProvider, toast],
);
return (
@@ -0,0 +1,10 @@
/**
* Workspace scripts: the desktop header popover, and the pages the compact header menu carries.
* Both share one set of actions and one reading of script status.
*/
export { WorkspaceScriptsButton } from "./workspace-scripts-button";
export {
useWorkspaceScriptsMenuPages,
type UseWorkspaceScriptsMenuPagesInput,
type WorkspaceScriptsMenuPages,
} from "./workspace-scripts-menu-pages";
@@ -0,0 +1,78 @@
import type { ReactElement } from "react";
import { Text, View } from "react-native";
import { Globe, SquareTerminal } from "lucide-react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { useTranslation } from "react-i18next";
import type { WorkspaceDescriptor } from "@/stores/session-store";
import type { WorkspaceScriptLinkKind } from "@/utils/workspace-script-links";
import { scriptStatus, scriptToneColorMapping } from "./script-status";
const ThemedGlobe = withUnistyles(Globe);
const ThemedSquareTerminal = withUnistyles(SquareTerminal);
/** A globe for a service, a terminal for a plain script, in the colour of what it is doing. */
export function ScriptIcon({
script,
size,
}: {
script: WorkspaceDescriptor["scripts"][number];
size: number;
}): ReactElement {
const Icon = script.type === "service" ? ThemedGlobe : ThemedSquareTerminal;
return (
<Icon
size={size}
uniProps={scriptToneColorMapping(scriptStatus(script))}
style={styles.scriptIcon}
/>
);
}
export function ExitCodeBadge({ code }: { code: number }): ReactElement {
const { t } = useTranslation();
const exitTextStyle =
code === 0 ? styles.exitBadgeText : [styles.exitBadgeText, styles.exitBadgeTextError];
return (
<View style={styles.exitBadge}>
<Text style={exitTextStyle}>{t("workspace.scripts.states.exitCode", { code })}</Text>
</View>
);
}
/** The label of a URL route, as the user picks between them. */
export function routeLabelKey(
kind: WorkspaceScriptLinkKind,
):
| "workspace.scripts.routes.public"
| "workspace.scripts.routes.paseo"
| "workspace.scripts.routes.direct" {
switch (kind) {
case "public":
return "workspace.scripts.routes.public";
case "paseo":
return "workspace.scripts.routes.paseo";
case "direct":
return "workspace.scripts.routes.direct";
}
}
const styles = StyleSheet.create((theme) => ({
scriptIcon: {
flexShrink: 0,
},
exitBadge: {
paddingHorizontal: theme.spacing[1.5],
paddingVertical: 1,
borderRadius: 2,
backgroundColor: theme.colors.surface2,
},
exitBadgeText: {
fontSize: 10,
lineHeight: 12,
fontWeight: theme.fontWeight.medium,
color: theme.colors.foregroundMuted,
},
exitBadgeTextError: {
color: theme.colors.statusDanger,
},
}));
@@ -0,0 +1,89 @@
import { describe, expect, it } from "vitest";
import type { WorkspaceScriptPayload } from "@getpaseo/protocol/messages";
import { scriptStatus, summarizeScripts } from "./script-status";
function service(
scriptName: string,
state: Pick<WorkspaceScriptPayload, "lifecycle" | "health">,
): WorkspaceScriptPayload {
return { ...script(scriptName, state.lifecycle), type: "service", health: state.health };
}
function script(
scriptName: string,
lifecycle: WorkspaceScriptPayload["lifecycle"],
): WorkspaceScriptPayload {
return {
scriptName,
type: "script",
hostname: scriptName,
port: null,
proxyUrl: null,
lifecycle,
health: null,
exitCode: null,
terminalId: null,
};
}
describe("scriptStatus", () => {
it("colours services by their health and plain scripts by whether they run", () => {
expect(scriptStatus(script("lint", "stopped"))).toBe("idle");
expect(scriptStatus(script("lint", "running"))).toBe("running");
expect(scriptStatus(service("web", { lifecycle: "stopped", health: "unhealthy" }))).toBe(
"idle",
);
expect(scriptStatus(service("web", { lifecycle: "running", health: null }))).toBe("running");
expect(scriptStatus(service("web", { lifecycle: "running", health: "healthy" }))).toBe(
"healthy",
);
expect(scriptStatus(service("web", { lifecycle: "running", health: "unhealthy" }))).toBe(
"unhealthy",
);
});
});
describe("summarizeScripts", () => {
it("is idle with nothing running when nothing runs", () => {
expect(summarizeScripts([])).toEqual({ tone: "idle", running: [] });
expect(summarizeScripts([script("lint", "stopped")])).toEqual({ tone: "idle", running: [] });
});
it("lists the running scripts by name", () => {
expect(
summarizeScripts([
script("lint", "stopped"),
service("web", { lifecycle: "running", health: null }),
]),
).toEqual({ tone: "running", running: ["web"] });
});
it("is unhealthy when any running service is", () => {
expect(
summarizeScripts([
service("web", { lifecycle: "running", health: "healthy" }),
service("api", { lifecycle: "running", health: "unhealthy" }),
]),
).toEqual({ tone: "unhealthy", running: ["web", "api"] });
});
it("is healthy only when every running service reports healthy", () => {
expect(
summarizeScripts([
script("lint", "running"),
service("web", { lifecycle: "running", health: "healthy" }),
service("api", { lifecycle: "stopped", health: "unhealthy" }),
]),
).toEqual({ tone: "healthy", running: ["lint", "web"] });
expect(
summarizeScripts([
service("web", { lifecycle: "running", health: "healthy" }),
service("api", { lifecycle: "running", health: null }),
]),
).toEqual({ tone: "running", running: ["web", "api"] });
expect(summarizeScripts([script("lint", "running")])).toEqual({
tone: "running",
running: ["lint"],
});
});
});
@@ -0,0 +1,63 @@
import type { WorkspaceScriptPayload } from "@getpaseo/protocol/messages";
import type { Theme } from "@/styles/theme";
/**
* What a script, or a set of them, is doing, as the one colour its ▶ or row icon is drawn in.
*
* Health is a service's own report, so it only colours running services. A plain script that is
* running is just running.
*/
export type ScriptTone = "idle" | "running" | "healthy" | "unhealthy";
export interface ScriptsSummary {
tone: ScriptTone;
/** Names of the running scripts, in the order the workspace lists them. */
running: string[];
}
export function scriptStatus(script: WorkspaceScriptPayload): ScriptTone {
if (script.lifecycle !== "running") return "idle";
if (script.type !== "service") return "running";
if (script.health === "healthy") return "healthy";
if (script.health === "unhealthy") return "unhealthy";
return "running";
}
/**
* One unhealthy service makes the whole set unhealthy. The set reads healthy only when every
* running service says so; a service that has not reported yet keeps it at plain running.
*/
export function summarizeScripts(scripts: readonly WorkspaceScriptPayload[]): ScriptsSummary {
const running = scripts.filter((script) => script.lifecycle === "running");
if (running.length === 0) return { tone: "idle", running: [] };
return { tone: aggregateTone(running), running: running.map((script) => script.scriptName) };
}
function aggregateTone(running: readonly WorkspaceScriptPayload[]): ScriptTone {
const serviceTones = running
.filter((script) => script.type === "service")
.map((script) => scriptStatus(script));
if (serviceTones.includes("unhealthy")) return "unhealthy";
if (serviceTones.length > 0 && serviceTones.every((tone) => tone === "healthy")) {
return "healthy";
}
return "running";
}
const idleColorMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
const runningColorMapping = (theme: Theme) => ({ color: theme.colors.palette.blue[500] });
const healthyColorMapping = (theme: Theme) => ({ color: theme.colors.palette.green[500] });
const unhealthyColorMapping = (theme: Theme) => ({ color: theme.colors.palette.red[500] });
export function scriptToneColorMapping(tone: ScriptTone): (theme: Theme) => { color: string } {
switch (tone) {
case "idle":
return idleColorMapping;
case "running":
return runningColorMapping;
case "healthy":
return healthyColorMapping;
case "unhealthy":
return unhealthyColorMapping;
}
}
@@ -0,0 +1,191 @@
import { useCallback, useEffect, useMemo, useRef } from "react";
import * as Clipboard from "expo-clipboard";
import { useMutation } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import type { WorkspaceDescriptor } from "@/stores/session-store";
import { useSessionStore } from "@/stores/session-store";
import { useHostRuntimeSnapshot } from "@/runtime/host-runtime";
import { useToast } from "@/contexts/toast-context";
import {
resolveWorkspaceScriptLink,
type WorkspaceScriptLinkKind,
type WorkspaceScriptLinkTarget,
} from "@/utils/workspace-script-links";
import { useWorkspaceServiceRoutePreferencesStore } from "@/workspace-service-routes/store";
type WorkspaceScript = WorkspaceDescriptor["scripts"][number];
export interface WorkspaceScriptLinks {
/** The URL this host's route preference picks, or null when the script serves none. */
selected: WorkspaceScriptLinkTarget | null;
targets: WorkspaceScriptLinkTarget[];
}
export interface WorkspaceScriptActions {
start: (scriptName: string) => void;
stop: (scriptName: string) => void;
/** Stops the script, then starts it again once the daemon reports it stopped. */
restart: (scriptName: string) => void;
copyUrl: (target: WorkspaceScriptLinkTarget) => void;
selectRoute: (kind: WorkspaceScriptLinkKind) => void;
resolveLinks: (script: WorkspaceScript) => WorkspaceScriptLinks;
isStartPending: boolean;
isStopPending: boolean;
}
export interface UseWorkspaceScriptActionsInput {
serverId: string;
workspaceId: string;
scripts: WorkspaceDescriptor["scripts"];
onScriptTerminalStarted?: (terminalId: string) => void;
}
/**
* Run, stop, restart and URL handling for a workspace's scripts, shared by every surface that
* lists them.
*
* A restart outlives the press that asked for it — the second half waits for the daemon to
* report the script stopped — so mount this with whatever owns the menu, not inside a menu page
* that unmounts when the menu closes.
*/
export function useWorkspaceScriptActions({
serverId,
workspaceId,
scripts,
onScriptTerminalStarted,
}: UseWorkspaceScriptActionsInput): WorkspaceScriptActions {
const { t } = useTranslation();
const toast = useToast();
const client = useSessionStore((state) => state.sessions[serverId]?.client ?? null);
const activeConnection = useHostRuntimeSnapshot(serverId)?.activeConnection ?? null;
const preferredRouteKind = useWorkspaceServiceRoutePreferencesStore(
(state) => state.byServerId[serverId] ?? null,
);
const setPreferredRoute = useWorkspaceServiceRoutePreferencesStore(
(state) => state.setPreferredRoute,
);
const pendingRestartRef = useRef<Set<string>>(new Set());
const startScriptMutation = useMutation({
mutationFn: async (scriptName: string) => {
if (!client) {
throw new Error(t("common.errors.daemonClientUnavailable"));
}
const result = await client.startWorkspaceScript(workspaceId, scriptName);
if (result.error) {
throw new Error(result.error);
}
return result;
},
onError: (error, scriptName) => {
toast.show(
error instanceof Error
? error.message
: t("workspace.scripts.states.startFailed", { scriptName }),
{
variant: "error",
},
);
},
onSuccess: (result) => {
if (result.terminalId) {
onScriptTerminalStarted?.(result.terminalId);
}
},
});
const startScript = startScriptMutation.mutate;
const stopScriptMutation = useMutation({
mutationFn: async (scriptName: string) => {
if (!client) {
throw new Error(t("common.errors.daemonClientUnavailable"));
}
const terminalId = scripts.find((s) => s.scriptName === scriptName)?.terminalId;
if (!terminalId) {
throw new Error(t("workspace.scripts.states.stopFailed", { scriptName }));
}
const result = await client.killTerminal(terminalId);
if (!result.success) {
throw new Error(t("workspace.scripts.states.stopFailed", { scriptName }));
}
},
onError: (error, scriptName) => {
pendingRestartRef.current.delete(scriptName);
toast.show(
error instanceof Error
? error.message
: t("workspace.scripts.states.stopFailed", { scriptName }),
{
variant: "error",
},
);
},
});
const stopScript = stopScriptMutation.mutate;
// Restart = kill the script terminal, then start again once the daemon
// reports the script as stopped (it tears the runtime entry down on exit).
useEffect(() => {
const pending = pendingRestartRef.current;
if (pending.size === 0) return;
for (const script of scripts) {
if (!pending.has(script.scriptName) || script.lifecycle === "running") continue;
pending.delete(script.scriptName);
startScript(script.scriptName);
}
}, [scripts, startScript]);
const restart = useCallback(
(scriptName: string) => {
pendingRestartRef.current.add(scriptName);
stopScript(scriptName);
},
[stopScript],
);
const copyUrl = useCallback(
(target: WorkspaceScriptLinkTarget) => {
void Clipboard.setStringAsync(target.url);
toast.copied(target.label);
},
[toast],
);
const selectRoute = useCallback(
(kind: WorkspaceScriptLinkKind) => setPreferredRoute(serverId, kind),
[serverId, setPreferredRoute],
);
const resolveLinks = useCallback(
(script: WorkspaceScript): WorkspaceScriptLinks => {
const link = resolveWorkspaceScriptLink({ script, activeConnection });
const selected =
link.targets.find((target) => target.kind === preferredRouteKind) ?? link.primary;
return { selected, targets: link.targets };
},
[activeConnection, preferredRouteKind],
);
return useMemo(
() => ({
start: startScript,
stop: stopScript,
restart,
copyUrl,
selectRoute,
resolveLinks,
isStartPending: startScriptMutation.isPending,
isStopPending: stopScriptMutation.isPending,
}),
[
startScript,
stopScript,
restart,
copyUrl,
selectRoute,
resolveLinks,
startScriptMutation.isPending,
stopScriptMutation.isPending,
],
);
}
@@ -8,7 +8,7 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import type { WorkspaceScriptPayload } from "@getpaseo/protocol/messages";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { createRoot } from "react-dom/client";
import { WorkspaceScriptsButton } from "@/screens/workspace/workspace-scripts-button";
import { WorkspaceScriptsButton } from "./workspace-scripts-button";
void testI18n;
@@ -235,7 +235,6 @@ const LIVE_TERMINAL_IDS: string[] = ["terminal-script-1"];
interface RenderScriptsOptions {
hideLabels?: boolean;
presentation?: "split" | "ghost";
}
function renderScripts(
@@ -264,7 +263,6 @@ function renderScripts(
scripts={nextScripts}
liveTerminalIds={LIVE_TERMINAL_IDS}
hideLabels={options.hideLabels}
presentation={options.presentation}
/>
</QueryClientProvider>
);
@@ -431,17 +429,6 @@ describe("WorkspaceScriptsButton", () => {
);
});
it("removes the trigger caret in ghost presentation", () => {
current = renderScripts([script({ scriptName: "dev" })], {
hideLabels: true,
presentation: "ghost",
});
const trigger = document.querySelector('[data-testid="workspace-scripts-button"]');
expect(trigger?.querySelector('[data-icon="Play"]')?.getAttribute("data-size")).toBe("16");
expect(trigger?.querySelector('[data-icon="ChevronDown"]')).toBeNull();
});
it("keeps the trigger caret in split presentation", () => {
current = renderScripts([script({ scriptName: "dev" })]);
@@ -1,13 +1,10 @@
import { useCallback, useEffect, useMemo, useRef, type ReactElement } from "react";
import { useCallback, useMemo, type ReactElement } from "react";
import type { GestureResponderEvent } from "react-native";
import { Pressable, Text, View } from "react-native";
import * as Clipboard from "expo-clipboard";
import { useMutation } from "@tanstack/react-query";
import {
ChevronDown,
Copy,
Eye,
Globe,
Play,
RotateCw,
Square,
@@ -16,8 +13,6 @@ import {
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { useTranslation } from "react-i18next";
import type { WorkspaceDescriptor } from "@/stores/session-store";
import { useSessionStore } from "@/stores/session-store";
import { useHostRuntimeSnapshot } from "@/runtime/host-runtime";
import {
DropdownMenu,
DropdownMenuContent,
@@ -27,17 +22,20 @@ import {
} from "@/components/ui/dropdown-menu";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { MENU_ITEM_HEIGHT } from "@/components/ui/menu/menu-geometry";
import { useToast } from "@/contexts/toast-context";
import { openServiceUrl } from "@/utils/open-service-url";
import {
resolveWorkspaceScriptLink,
type WorkspaceScriptLinkKind,
type WorkspaceScriptLinkTarget,
import type {
WorkspaceScriptLinkKind,
WorkspaceScriptLinkTarget,
} from "@/utils/workspace-script-links";
import type { Theme } from "@/styles/theme";
import { useWorkspaceServiceRoutePreferencesStore } from "@/workspace-service-routes/store";
import { buttonControlHeight, HEADER_CONTROL_HEIGHT } from "@/components/ui/control-geometry";
import { extraMutedIconColorMapping } from "@/components/ui/icon-color";
import { ExitCodeBadge, routeLabelKey, ScriptIcon } from "./script-marks";
import { scriptToneColorMapping } from "./script-status";
import {
useWorkspaceScriptActions,
type WorkspaceScriptActions,
} from "./use-workspace-script-actions";
type RowActionIcon = "copy" | "open" | "restart" | "start" | "stop" | "terminal";
@@ -50,37 +48,23 @@ interface WorkspaceScriptsButtonProps {
onViewTerminal?: (terminalId: string) => void;
onOpenUrlInBrowserTab?: (url: string) => void;
hideLabels?: boolean;
presentation?: "split" | "ghost";
}
const ThemedPlay = withUnistyles(Play);
const ThemedSquareTerminal = withUnistyles(SquareTerminal);
const ThemedGlobe = withUnistyles(Globe);
const ThemedChevronDown = withUnistyles(ChevronDown);
const ThemedEye = withUnistyles(Eye);
const ThemedCopy = withUnistyles(Copy);
const ThemedRotateCw = withUnistyles(RotateCw);
const ThemedSquare = withUnistyles(Square);
const GHOST_TRIGGER_ICON_SIZE = 16;
const foregroundColorMapping = (theme: Theme) => ({
color: theme.colors.foreground,
});
const mutedColorMapping = (theme: Theme) => ({
color: theme.colors.foregroundMuted,
});
const blueColorMapping = (theme: Theme) => ({
color: theme.colors.palette.blue[500],
});
const greenColorMapping = (theme: Theme) => ({
color: theme.colors.palette.green[500],
});
const redColorMapping = (theme: Theme) => ({
color: theme.colors.palette.red[500],
});
const playFillTransparent = { fill: "transparent" };
const ghostPlayStroke = { strokeWidth: 1.5 };
interface ScriptRowActionButtonProps {
accessibilityLabel: string;
@@ -163,23 +147,7 @@ interface ServiceLinkRowProps {
targets: WorkspaceScriptLinkTarget[];
scriptName: string;
onSelectKind: (kind: WorkspaceScriptLinkKind) => void;
onCopy: (url: string, label: string) => void;
}
function routeLabelKey(
kind: WorkspaceScriptLinkKind,
):
| "workspace.scripts.routes.public"
| "workspace.scripts.routes.paseo"
| "workspace.scripts.routes.direct" {
switch (kind) {
case "public":
return "workspace.scripts.routes.public";
case "paseo":
return "workspace.scripts.routes.paseo";
case "direct":
return "workspace.scripts.routes.direct";
}
onCopy: (target: WorkspaceScriptLinkTarget) => void;
}
function ServiceRouteOption({
@@ -298,12 +266,12 @@ function ServiceLinkRow({
}: ServiceLinkRowProps): ReactElement {
const { t } = useTranslation();
const closeMenu = useDropdownMenuClose();
const { label, url } = selectedTarget;
const { label } = selectedTarget;
const handleCopy = useCallback(() => {
closeMenu();
onCopy(url, label);
}, [url, label, onCopy, closeMenu]);
onCopy(selectedTarget);
}, [selectedTarget, onCopy, closeMenu]);
return (
<View style={styles.hostRow}>
@@ -333,84 +301,29 @@ function ServiceLinkRow({
);
}
function ExitCodeBadge({ code }: { code: number }): ReactElement {
const { t } = useTranslation();
const exitTextStyle =
code === 0 ? styles.exitBadgeText : [styles.exitBadgeText, styles.exitBadgeTextError];
return (
<View style={styles.exitBadge}>
<Text style={exitTextStyle}>{t("workspace.scripts.states.exitCode", { code })}</Text>
</View>
);
}
interface ScriptRowProps {
script: WorkspaceDescriptor["scripts"][number];
liveTerminalIdSet: Set<string>;
activeConnection: ReturnType<typeof useHostRuntimeSnapshot> extends infer R
? R extends { activeConnection: infer A }
? A
: null
: null;
isStartPending: boolean;
isStopPending: boolean;
onStartScript: (scriptName: string) => void;
onStopScript: (scriptName: string) => void;
onRestartScript: (scriptName: string) => void;
onCopyUrl: (url: string, label: string) => void;
preferredRouteKind: WorkspaceScriptLinkKind | null;
onSelectRouteKind: (kind: WorkspaceScriptLinkKind) => void;
actions: WorkspaceScriptActions;
onViewTerminal?: (terminalId: string) => void;
onOpenUrlInBrowserTab?: (url: string) => void;
}
function resolveScriptIconColorMapping(args: {
script: WorkspaceDescriptor["scripts"][number];
isService: boolean;
isRunning: boolean;
}): (theme: Theme) => { color: string } {
const { script, isService, isRunning } = args;
if (isService) {
if (isRunning && script.health === "healthy") return greenColorMapping;
if (isRunning && script.health === "unhealthy") return redColorMapping;
if (isRunning) return blueColorMapping;
return mutedColorMapping;
}
if (isRunning) return blueColorMapping;
return mutedColorMapping;
}
function ScriptRow({
script,
liveTerminalIdSet,
activeConnection,
isStartPending,
isStopPending,
onStartScript,
onStopScript,
onRestartScript,
onCopyUrl,
preferredRouteKind,
onSelectRouteKind,
actions,
onViewTerminal,
onOpenUrlInBrowserTab,
}: ScriptRowProps): ReactElement {
const { t } = useTranslation();
const isRunning = script.lifecycle === "running";
const isService = (script.type ?? "service") === "service";
const exitCode = script.exitCode ?? null;
const serviceLink = resolveWorkspaceScriptLink({ script, activeConnection });
const selectedLink =
isService && isRunning
? (serviceLink.targets.find((target) => target.kind === preferredRouteKind) ??
serviceLink.primary)
: null;
const { selected: selectedLink, targets: linkTargets } = actions.resolveLinks(script);
const liveTerminalId =
script.terminalId && liveTerminalIdSet.has(script.terminalId) ? script.terminalId : null;
const iconColorMapping = resolveScriptIconColorMapping({ script, isService, isRunning });
const ScriptIcon = isService ? ThemedGlobe : ThemedSquareTerminal;
const showExitBadge = !isRunning && exitCode !== null;
const { start, stop, restart } = actions;
const closeMenu = useDropdownMenuClose();
const handleOpenService = useCallback(() => {
@@ -424,16 +337,16 @@ function ScriptRow({
}, [liveTerminalId, onViewTerminal]);
const handleRun = useCallback(() => {
onStartScript(script.scriptName);
}, [onStartScript, script.scriptName]);
start(script.scriptName);
}, [start, script.scriptName]);
const handleStop = useCallback(() => {
onStopScript(script.scriptName);
}, [onStopScript, script.scriptName]);
stop(script.scriptName);
}, [stop, script.scriptName]);
const handleRestart = useCallback(() => {
onRestartScript(script.scriptName);
}, [onRestartScript, script.scriptName]);
restart(script.scriptName);
}, [restart, script.scriptName]);
const scriptNameStyle = useMemo(
() => (isRunning ? [styles.scriptName, styles.scriptNameActive] : styles.scriptName),
@@ -471,7 +384,7 @@ function ScriptRow({
scriptName: script.scriptName,
})}
testID={`workspace-scripts-stop-${script.scriptName}`}
disabled={isStopPending}
disabled={actions.isStopPending}
icon="stop"
onPress={handleStop}
tooltipLabel={t("workspace.scripts.actions.stop")}
@@ -482,7 +395,7 @@ function ScriptRow({
scriptName: script.scriptName,
})}
testID={`workspace-scripts-start-${script.scriptName}`}
disabled={isStartPending}
disabled={actions.isStartPending}
icon="start"
onPress={handleRun}
tooltipLabel={t("workspace.scripts.actions.run")}
@@ -497,7 +410,7 @@ function ScriptRow({
})}
>
<View style={styles.scriptHeader}>
<ScriptIcon size={14} uniProps={iconColorMapping} style={styles.scriptIcon} />
<ScriptIcon script={script} size={14} />
<Text style={scriptNameStyle} numberOfLines={1}>
{script.scriptName}
</Text>
@@ -511,7 +424,7 @@ function ScriptRow({
scriptName: script.scriptName,
})}
testID={`workspace-scripts-restart-${script.scriptName}`}
disabled={isStopPending}
disabled={actions.isStopPending}
icon="restart"
onPress={handleRestart}
tooltipLabel={t("workspace.scripts.actions.restart")}
@@ -523,10 +436,10 @@ function ScriptRow({
<View style={styles.hostList}>
<ServiceLinkRow
selectedTarget={selectedLink}
targets={serviceLink.targets}
targets={linkTargets}
scriptName={script.scriptName}
onSelectKind={onSelectRouteKind}
onCopy={onCopyUrl}
onSelectKind={actions.selectRoute}
onCopy={actions.copyUrl}
/>
</View>
) : null}
@@ -543,142 +456,35 @@ export function WorkspaceScriptsButton({
onViewTerminal,
onOpenUrlInBrowserTab,
hideLabels,
presentation = "split",
}: WorkspaceScriptsButtonProps): ReactElement | null {
const { t } = useTranslation();
const toast = useToast();
const client = useSessionStore((state) => state.sessions[serverId]?.client ?? null);
const activeConnection = useHostRuntimeSnapshot(serverId)?.activeConnection ?? null;
const preferredRouteKind = useWorkspaceServiceRoutePreferencesStore(
(state) => state.byServerId[serverId] ?? null,
);
const setPreferredRoute = useWorkspaceServiceRoutePreferencesStore(
(state) => state.setPreferredRoute,
);
const actions = useWorkspaceScriptActions({
serverId,
workspaceId,
scripts,
onScriptTerminalStarted,
});
const liveTerminalIdSet = useMemo(() => new Set(liveTerminalIds), [liveTerminalIds]);
const pendingRestartRef = useRef<Set<string>>(new Set());
const startScriptMutation = useMutation({
mutationFn: async (scriptName: string) => {
if (!client) {
throw new Error(t("common.errors.daemonClientUnavailable"));
}
const result = await client.startWorkspaceScript(workspaceId, scriptName);
if (result.error) {
throw new Error(result.error);
}
return result;
},
onError: (error, scriptName) => {
toast.show(
error instanceof Error
? error.message
: t("workspace.scripts.states.startFailed", { scriptName }),
{
variant: "error",
},
);
},
onSuccess: (result) => {
if (result.terminalId) {
onScriptTerminalStarted?.(result.terminalId);
}
},
});
const startScript = startScriptMutation.mutate;
const stopScriptMutation = useMutation({
mutationFn: async (scriptName: string) => {
if (!client) {
throw new Error(t("common.errors.daemonClientUnavailable"));
}
const terminalId = scripts.find((s) => s.scriptName === scriptName)?.terminalId;
if (!terminalId) {
throw new Error(t("workspace.scripts.states.stopFailed", { scriptName }));
}
const result = await client.killTerminal(terminalId);
if (!result.success) {
throw new Error(t("workspace.scripts.states.stopFailed", { scriptName }));
}
},
onError: (error, scriptName) => {
pendingRestartRef.current.delete(scriptName);
toast.show(
error instanceof Error
? error.message
: t("workspace.scripts.states.stopFailed", { scriptName }),
{
variant: "error",
},
);
},
});
// Restart = kill the script terminal, then start again once the daemon
// reports the script as stopped (it tears the runtime entry down on exit).
useEffect(() => {
const pending = pendingRestartRef.current;
if (pending.size === 0) return;
for (const script of scripts) {
if (!pending.has(script.scriptName) || script.lifecycle === "running") continue;
pending.delete(script.scriptName);
startScript(script.scriptName);
}
}, [scripts, startScript]);
const triggerStyle = useCallback(
({ hovered, pressed, open }: { hovered: boolean; pressed: boolean; open: boolean }) => [
presentation === "ghost" ? styles.ghostButton : styles.splitButtonPrimary,
(hovered || pressed || open) &&
(presentation === "ghost" ? styles.ghostButtonHovered : styles.splitButtonPrimaryHovered),
styles.splitButtonPrimary,
(hovered || pressed || open) && styles.splitButtonPrimaryHovered,
],
[presentation],
);
const handleStartScript = useCallback(
(scriptName: string) => startScriptMutation.mutate(scriptName),
[startScriptMutation],
);
const handleStopScript = useCallback(
(scriptName: string) => stopScriptMutation.mutate(scriptName),
[stopScriptMutation],
);
const handleRestartScript = useCallback(
(scriptName: string) => {
pendingRestartRef.current.add(scriptName);
stopScriptMutation.mutate(scriptName);
},
[stopScriptMutation],
);
const handleCopyUrl = useCallback(
(url: string, label: string) => {
void Clipboard.setStringAsync(url);
toast.copied(label);
},
[toast],
);
const handleSelectRouteKind = useCallback(
(kind: WorkspaceScriptLinkKind) => setPreferredRoute(serverId, kind),
[serverId, setPreferredRoute],
[],
);
if (scripts.length === 0) {
return null;
}
// The trigger only says whether anything runs; health is for the rows inside.
const hasAnyRunning = scripts.some((s) => s.lifecycle === "running");
const triggerPlayMapping = hasAnyRunning ? blueColorMapping : mutedColorMapping;
const triggerIconSize = presentation === "ghost" ? GHOST_TRIGGER_ICON_SIZE : 14;
const triggerPlayProps =
presentation === "ghost" ? { ...playFillTransparent, ...ghostPlayStroke } : playFillTransparent;
const triggerPlayMapping = scriptToneColorMapping(hasAnyRunning ? "running" : "idle");
return (
<View style={styles.row}>
<View style={presentation === "ghost" ? styles.ghostButtonFrame : styles.splitButton}>
<View style={styles.splitButton}>
<DropdownMenu>
<DropdownMenuTrigger
testID="workspace-scripts-button"
@@ -687,17 +493,11 @@ export function WorkspaceScriptsButton({
accessibilityLabel={t("workspace.scripts.accessibility.trigger")}
>
<View style={styles.splitButtonContent}>
<ThemedPlay
size={triggerIconSize}
uniProps={triggerPlayMapping}
{...triggerPlayProps}
/>
<ThemedPlay size={14} uniProps={triggerPlayMapping} {...playFillTransparent} />
{!hideLabels && (
<Text style={styles.splitButtonText}>{t("workspace.scripts.title")}</Text>
)}
{presentation === "split" ? (
<ThemedChevronDown size={16} uniProps={extraMutedIconColorMapping} />
) : null}
<ThemedChevronDown size={16} uniProps={extraMutedIconColorMapping} />
</View>
</DropdownMenuTrigger>
<DropdownMenuContent
@@ -711,15 +511,7 @@ export function WorkspaceScriptsButton({
key={script.scriptName}
script={script}
liveTerminalIdSet={liveTerminalIdSet}
activeConnection={activeConnection}
isStartPending={startScriptMutation.isPending}
isStopPending={stopScriptMutation.isPending}
onStartScript={handleStartScript}
onStopScript={handleStopScript}
onRestartScript={handleRestartScript}
onCopyUrl={handleCopyUrl}
preferredRouteKind={preferredRouteKind}
onSelectRouteKind={handleSelectRouteKind}
actions={actions}
onViewTerminal={onViewTerminal}
onOpenUrlInBrowserTab={onOpenUrlInBrowserTab}
/>
@@ -750,21 +542,6 @@ const styles = StyleSheet.create((theme) => ({
borderColor: theme.colors.borderAccent,
overflow: "hidden",
},
ghostButtonFrame: {
flexDirection: "row",
alignItems: "stretch",
},
ghostButton: {
width: theme.spacing[8],
height: theme.spacing[8],
padding: 0,
borderRadius: theme.borderRadius.lg,
alignItems: "center",
justifyContent: "center",
},
ghostButtonHovered: {
backgroundColor: theme.colors.surface2,
},
splitButtonPrimary: {
paddingHorizontal: {
xs: theme.spacing[3],
@@ -798,9 +575,6 @@ const styles = StyleSheet.create((theme) => ({
paddingHorizontal: theme.spacing[3],
minHeight: MENU_ITEM_HEIGHT,
},
scriptIcon: {
flexShrink: 0,
},
scriptName: {
fontSize: theme.fontSize.base,
fontWeight: theme.fontWeight.normal,
@@ -844,21 +618,6 @@ const styles = StyleSheet.create((theme) => ({
hostLabelActive: {
color: theme.colors.foreground,
},
exitBadge: {
paddingHorizontal: theme.spacing[1.5],
paddingVertical: 1,
borderRadius: 2,
backgroundColor: theme.colors.surface2,
},
exitBadgeText: {
fontSize: 10,
lineHeight: 12,
fontWeight: theme.fontWeight.medium,
color: theme.colors.foregroundMuted,
},
exitBadgeTextError: {
color: theme.colors.palette.red[300],
},
iconActionButton: {
padding: 2,
},
@@ -0,0 +1,416 @@
import { useCallback, useMemo, type ReactElement } from "react";
import { View } from "react-native";
import { Copy, Eye, Play, RotateCw, Square, SquareTerminal } from "lucide-react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { useTranslation } from "react-i18next";
import {
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuSubTrigger,
type MenuPageDefinition,
} from "@/components/ui/dropdown-menu";
import type { WorkspaceDescriptor } from "@/stores/session-store";
import type { Theme } from "@/styles/theme";
import { openServiceUrl } from "@/utils/open-service-url";
import type {
WorkspaceScriptLinkKind,
WorkspaceScriptLinkTarget,
} from "@/utils/workspace-script-links";
import { ExitCodeBadge, routeLabelKey, ScriptIcon } from "./script-marks";
import { scriptToneColorMapping, summarizeScripts, type ScriptsSummary } from "./script-status";
import {
useWorkspaceScriptActions,
type WorkspaceScriptActions,
} from "./use-workspace-script-actions";
type WorkspaceScript = WorkspaceDescriptor["scripts"][number];
const ThemedPlay = withUnistyles(Play);
const ThemedEye = withUnistyles(Eye);
const ThemedSquareTerminal = withUnistyles(SquareTerminal);
const ThemedCopy = withUnistyles(Copy);
const ThemedRotateCw = withUnistyles(RotateCw);
const ThemedSquare = withUnistyles(Square);
const mutedColorMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
const playFillTransparent = { fill: "transparent" };
const ROW_ICON_SIZE = 16;
const TRAILING_ICON_SIZE = 14;
const OPEN_SERVICE_ICON = <ThemedEye size={ROW_ICON_SIZE} uniProps={mutedColorMapping} />;
const VIEW_TERMINAL_ICON = (
<ThemedSquareTerminal size={ROW_ICON_SIZE} uniProps={mutedColorMapping} />
);
const COPY_URL_ICON = <ThemedCopy size={ROW_ICON_SIZE} uniProps={mutedColorMapping} />;
const RESTART_ICON = <ThemedRotateCw size={ROW_ICON_SIZE} uniProps={mutedColorMapping} />;
const STOP_ICON = <ThemedSquare size={ROW_ICON_SIZE} uniProps={mutedColorMapping} />;
const RUN_ICON = (
<ThemedPlay size={ROW_ICON_SIZE} uniProps={mutedColorMapping} {...playFillTransparent} />
);
const SCRIPTS_PAGE_ID = "workspace-scripts";
function scriptPageId(scriptName: string): string {
return `${SCRIPTS_PAGE_ID}/${scriptName}`;
}
export interface UseWorkspaceScriptsMenuPagesInput {
serverId: string;
workspaceId: string;
scripts: WorkspaceDescriptor["scripts"];
liveTerminalIds: readonly string[];
onScriptTerminalStarted: (terminalId: string) => void;
onViewTerminal: (terminalId: string) => void;
onOpenUrlInBrowserTab: (url: string) => void;
}
export interface WorkspaceScriptsMenuPages {
/** The root row that leads to the scripts page. Null when the workspace has no scripts. */
trigger: ReactElement | null;
pages: MenuPageDefinition[];
/** A running service reports unhealthy, so the menu's own trigger should say so. */
needsAttention: boolean;
}
/**
* Workspace scripts as pages of a sheet menu: a Scripts row on the root, a page listing every
* script, and one page per script.
*
* Every script gets a page whether or not it runs, so stopping one from its own page flips that
* page to its stopped state instead of pulling it out from under the user.
*
* The actions live here rather than in a page, so call this from whatever owns the menu: a restart
* finishes after the sheet has closed.
*/
export function useWorkspaceScriptsMenuPages({
serverId,
workspaceId,
scripts,
liveTerminalIds,
onScriptTerminalStarted,
onViewTerminal,
onOpenUrlInBrowserTab,
}: UseWorkspaceScriptsMenuPagesInput): WorkspaceScriptsMenuPages {
const { t } = useTranslation();
const actions = useWorkspaceScriptActions({
serverId,
workspaceId,
scripts,
onScriptTerminalStarted,
});
const summary = useMemo(() => summarizeScripts(scripts), [scripts]);
const trigger = useMemo(
() => (scripts.length === 0 ? null : <ScriptsMenuTrigger summary={summary} />),
[scripts.length, summary],
);
const pages = useMemo<MenuPageDefinition[]>(() => {
if (scripts.length === 0) return [];
const liveTerminalIdSet = new Set(liveTerminalIds);
return [
{
id: SCRIPTS_PAGE_ID,
title: t("workspace.scripts.title"),
content: <ScriptsPage scripts={scripts} actions={actions} />,
},
...scripts.map((script) => ({
id: scriptPageId(script.scriptName),
title: script.scriptName,
content: (
<ScriptPage
script={script}
actions={actions}
liveTerminalId={
script.terminalId && liveTerminalIdSet.has(script.terminalId)
? script.terminalId
: null
}
onViewTerminal={onViewTerminal}
onOpenUrlInBrowserTab={onOpenUrlInBrowserTab}
/>
),
})),
];
}, [actions, liveTerminalIds, onOpenUrlInBrowserTab, onViewTerminal, scripts, t]);
return { trigger, pages, needsAttention: summary.tone === "unhealthy" };
}
/** The root row: ▶ in the colour of the whole set, and what is running as its value. */
function ScriptsMenuTrigger({ summary }: { summary: ScriptsSummary }): ReactElement {
const { t } = useTranslation();
const leading = useMemo(
() => (
<ThemedPlay
size={ROW_ICON_SIZE}
uniProps={scriptToneColorMapping(summary.tone)}
{...playFillTransparent}
/>
),
[summary.tone],
);
const [onlyRunning] = summary.running;
const value =
summary.running.length > 1
? t("workspace.scripts.states.runningCount", { count: summary.running.length })
: onlyRunning;
return (
<DropdownMenuSubTrigger
id={SCRIPTS_PAGE_ID}
value={value}
leading={leading}
testID="workspace-header-scripts"
>
{t("workspace.scripts.title")}
</DropdownMenuSubTrigger>
);
}
function ScriptsPage({
scripts,
actions,
}: {
scripts: WorkspaceDescriptor["scripts"];
actions: WorkspaceScriptActions;
}): ReactElement {
return (
<>
{scripts.map((script) =>
script.lifecycle === "running" ? (
<RunningScriptRow key={script.scriptName} script={script} />
) : (
<StoppedScriptRow key={script.scriptName} script={script} actions={actions} />
),
)}
</>
);
}
function RunningScriptRow({ script }: { script: WorkspaceScript }): ReactElement {
const { t } = useTranslation();
const leading = useMemo(() => <ScriptIcon script={script} size={ROW_ICON_SIZE} />, [script]);
return (
<DropdownMenuSubTrigger
id={scriptPageId(script.scriptName)}
value={t("workspace.scripts.states.running")}
leading={leading}
testID={`workspace-scripts-row-${script.scriptName}`}
>
{script.scriptName}
</DropdownMenuSubTrigger>
);
}
/** Pressing a stopped script runs it. Starting opens its terminal tab, so the sheet closes. */
function StoppedScriptRow({
script,
actions,
}: {
script: WorkspaceScript;
actions: WorkspaceScriptActions;
}): ReactElement {
const { start } = actions;
const handleSelect = useCallback(() => start(script.scriptName), [start, script.scriptName]);
const exitCode = script.exitCode ?? null;
const leading = useMemo(() => <ScriptIcon script={script} size={ROW_ICON_SIZE} />, [script]);
const trailing = useMemo(
() => (
<View style={styles.trailing}>
{exitCode === null ? null : <ExitCodeBadge code={exitCode} />}
<ThemedPlay
size={TRAILING_ICON_SIZE}
uniProps={mutedColorMapping}
{...playFillTransparent}
/>
</View>
),
[exitCode],
);
return (
<DropdownMenuItem
leading={leading}
trailing={trailing}
disabled={actions.isStartPending}
onSelect={handleSelect}
testID={`workspace-scripts-row-${script.scriptName}`}
>
{script.scriptName}
</DropdownMenuItem>
);
}
interface ScriptPageProps {
script: WorkspaceScript;
actions: WorkspaceScriptActions;
liveTerminalId: string | null;
onViewTerminal: (terminalId: string) => void;
onOpenUrlInBrowserTab: (url: string) => void;
}
function ScriptPage(props: ScriptPageProps): ReactElement {
return props.script.lifecycle === "running" ? (
<RunningScriptPage {...props} />
) : (
<StoppedScriptPage script={props.script} actions={props.actions} />
);
}
/**
* Rows that open something — the service, the terminal, the clipboard toast — close the sheet.
* Stop and the URL choice stay: the page is where their result shows.
*/
function RunningScriptPage({
script,
actions,
liveTerminalId,
onViewTerminal,
onOpenUrlInBrowserTab,
}: ScriptPageProps): ReactElement {
const { t } = useTranslation();
const { scriptName } = script;
const { selected, targets } = actions.resolveLinks(script);
const { stop, restart, copyUrl, selectRoute } = actions;
const handleOpenService = useCallback(() => {
if (!selected) return;
void openServiceUrl(selected.url, { openInApp: onOpenUrlInBrowserTab });
}, [selected, onOpenUrlInBrowserTab]);
const handleViewTerminal = useCallback(() => {
if (liveTerminalId) onViewTerminal(liveTerminalId);
}, [liveTerminalId, onViewTerminal]);
const handleCopyUrl = useCallback(() => {
if (selected) copyUrl(selected);
}, [selected, copyUrl]);
const handleRestart = useCallback(() => restart(scriptName), [restart, scriptName]);
const handleStop = useCallback(() => stop(scriptName), [stop, scriptName]);
return (
<>
{selected ? (
<DropdownMenuItem
leading={OPEN_SERVICE_ICON}
onSelect={handleOpenService}
testID={`workspace-script-${scriptName}-open`}
>
{t("workspace.scripts.actions.openService")}
</DropdownMenuItem>
) : null}
{liveTerminalId ? (
<DropdownMenuItem
leading={VIEW_TERMINAL_ICON}
onSelect={handleViewTerminal}
testID={`workspace-script-${scriptName}-view`}
>
{t("workspace.scripts.actions.view")}
</DropdownMenuItem>
) : null}
{selected ? (
<DropdownMenuItem
leading={COPY_URL_ICON}
description={selected.label}
onSelect={handleCopyUrl}
testID={`workspace-script-${scriptName}-copy`}
>
{t("workspace.scripts.actions.copyUrl")}
</DropdownMenuItem>
) : null}
<DropdownMenuItem
leading={RESTART_ICON}
disabled={actions.isStopPending}
onSelect={handleRestart}
testID={`workspace-script-${scriptName}-restart`}
>
{t("workspace.scripts.actions.restart")}
</DropdownMenuItem>
<DropdownMenuItem
leading={STOP_ICON}
disabled={actions.isStopPending}
closeOnSelect={false}
onSelect={handleStop}
testID={`workspace-script-${scriptName}-stop`}
>
{t("workspace.scripts.actions.stop")}
</DropdownMenuItem>
{selected && targets.length > 1 ? (
<>
<DropdownMenuSeparator />
{targets.map((target) => (
<ServiceRouteOption
key={target.kind}
scriptName={scriptName}
target={target}
selected={target.kind === selected.kind}
onSelect={selectRoute}
/>
))}
</>
) : null}
</>
);
}
/** A pick-one URL route. Choosing one keeps the page open so the check moves under the thumb. */
function ServiceRouteOption({
scriptName,
target,
selected,
onSelect,
}: {
scriptName: string;
target: WorkspaceScriptLinkTarget;
selected: boolean;
onSelect: (kind: WorkspaceScriptLinkKind) => void;
}): ReactElement {
const { t } = useTranslation();
const handleSelect = useCallback(() => onSelect(target.kind), [onSelect, target.kind]);
return (
<DropdownMenuItem
selected={selected}
showSelectedCheck
description={target.label}
closeOnSelect={false}
onSelect={handleSelect}
testID={`workspace-script-${scriptName}-route-${target.kind}`}
>
{t(routeLabelKey(target.kind))}
</DropdownMenuItem>
);
}
function StoppedScriptPage({
script,
actions,
}: {
script: WorkspaceScript;
actions: WorkspaceScriptActions;
}): ReactElement {
const { t } = useTranslation();
const { start } = actions;
const handleRun = useCallback(() => start(script.scriptName), [start, script.scriptName]);
const exitCode = script.exitCode ?? null;
const trailing = useMemo(
() => (exitCode === null ? null : <ExitCodeBadge code={exitCode} />),
[exitCode],
);
return (
<DropdownMenuItem
leading={RUN_ICON}
trailing={trailing}
disabled={actions.isStartPending}
onSelect={handleRun}
testID={`workspace-script-${script.scriptName}-run`}
>
{t("workspace.scripts.actions.run")}
</DropdownMenuItem>
);
}
const styles = StyleSheet.create((theme) => ({
trailing: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[1.5],
},
}));
@@ -27,6 +27,10 @@ import {
} from "@getpaseo/protocol/terminal-profiles";
import { buildSettingsHostSectionRoute } from "@/utils/host-routes";
import type { Theme } from "@/styles/theme";
import {
useWorkspaceScriptsMenuPages,
type UseWorkspaceScriptsMenuPagesInput,
} from "@/screens/workspace/scripts";
const ThemedEllipsis = withUnistyles(Ellipsis);
const ThemedCopy = withUnistyles(Copy);
@@ -49,6 +53,16 @@ function WorkspaceHeaderMenuTriggerIcon() {
);
}
/** The ⋯ with a dot on it, for when something inside the menu needs looking at. */
function WorkspaceHeaderMenuAttentionTriggerIcon() {
return (
<View>
<WorkspaceHeaderMenuTriggerIcon />
<View style={styles.attentionDot} testID="workspace-header-menu-attention" />
</View>
);
}
/**
* The compact header buttons draw at 32pt, under the 44pt touch minimum, and sit flush against
* each other — so the slop can only grow vertically. Widening it would put two buttons' slop over
@@ -192,6 +206,7 @@ function HeaderMenuProfileItem({
export interface WorkspaceHeaderMenuMobileProps extends WorkspaceHeaderWorkspaceActions {
normalizedServerId: string;
scripts: UseWorkspaceScriptsMenuPagesInput;
showCreateBrowserTab: boolean;
createTerminalDisabled: boolean;
onCreateTerminalWithProfile: (profile: TerminalProfile) => void;
@@ -201,9 +216,13 @@ export interface WorkspaceHeaderMenuMobileProps extends WorkspaceHeaderWorkspace
/**
* Compact layouts have no tab strip. New agent and New terminal sit in the tab switcher's footer;
* the rarer launches stay here alongside the workspace actions.
*
* The header has no room for a scripts button either, so scripts are a page of this menu, and the
* ⋯ carries a dot while a running service is unhealthy.
*/
export function WorkspaceHeaderMenuMobile({
normalizedServerId,
scripts,
showCreateBrowserTab,
createTerminalDisabled,
onCreateTerminalWithProfile,
@@ -222,6 +241,7 @@ export function WorkspaceHeaderMenuMobile({
const handleEditProfiles = useCallback(() => {
router.push(buildSettingsHostSectionRoute(normalizedServerId, "terminals") as Href);
}, [normalizedServerId, router]);
const scriptsMenu = useWorkspaceScriptsMenuPages(scripts);
return (
<DropdownMenu compactMode="sheet">
@@ -230,16 +250,26 @@ export function WorkspaceHeaderMenuMobile({
style={triggerStyle}
hitSlop={COMPACT_HEADER_BUTTON_HIT_SLOP}
accessibilityRole="button"
accessibilityLabel={t("workspace.header.actions.workspaceActions")}
accessibilityLabel={
scriptsMenu.needsAttention
? t("workspace.header.actions.workspaceActionsUnhealthy")
: t("workspace.header.actions.workspaceActions")
}
>
<WorkspaceHeaderMenuTriggerIcon />
{scriptsMenu.needsAttention ? (
<WorkspaceHeaderMenuAttentionTriggerIcon />
) : (
<WorkspaceHeaderMenuTriggerIcon />
)}
</DropdownMenuTrigger>
<DropdownMenuContent
align="start"
width={220}
testID="workspace-header-menu"
pages={scriptsMenu.pages}
sheetTitle={t("workspace.header.actions.workspaceActions")}
>
{scriptsMenu.trigger}
{showCreateBrowserTab ? (
<DropdownMenuItem
testID="workspace-header-new-browser"
@@ -272,9 +302,21 @@ export function WorkspaceHeaderMenuMobile({
);
}
const styles = StyleSheet.create({
const ATTENTION_DOT_SIZE = 6;
const styles = StyleSheet.create((theme) => ({
headerMenuProfileIconWrapper: {
width: 16,
height: 16,
},
});
// Same red as the Scripts row's unhealthy ▶, so the dot and the row it leads to agree.
attentionDot: {
position: "absolute",
top: -1,
right: -2,
width: ATTENTION_DOT_SIZE,
height: ATTENTION_DOT_SIZE,
borderRadius: theme.borderRadius.full,
backgroundColor: theme.colors.palette.red[500],
},
}));
@@ -47,7 +47,7 @@ import { SplitContainer } from "@/components/split-container";
import { RetainedPanel } from "@/components/retained-panel";
import { WorkspaceActions } from "@/git/workspace-actions";
import { WorkspaceOpenInEditorButton } from "@/workspace/open-in-editor/button";
import { WorkspaceScriptsButton } from "@/screens/workspace/workspace-scripts-button";
import { WorkspaceScriptsButton } from "@/screens/workspace/scripts";
import { ImportSessionSheet } from "@/components/import-session-sheet";
import { useNavigateToImportedAgent } from "@/hooks/use-import-session";
import { useToast } from "@/contexts/toast-context";
@@ -1026,6 +1026,15 @@ function WorkspaceScreenContent({
.prepareWorkspaceRoute(normalizedServerId, normalizedWorkspaceId)
.catch(() => undefined);
}, [normalizedServerId, normalizedWorkspaceId, workspaceDescriptor]);
// The focused workspace keeps its script status live even when no sidebar or viewed agent
// timeline demands the directory. Retained, hidden workspaces release it.
useEffect(() => {
if (!isRouteFocused || !normalizedServerId || !normalizedWorkspaceId) return;
return getHostRuntimeStore().acquireScriptStatusDemand(
normalizedServerId,
normalizedWorkspaceId,
);
}, [isRouteFocused, normalizedServerId, normalizedWorkspaceId]);
const workspaceScripts = getWorkspaceScripts(workspaceDescriptor);
const { handleRetryHost, handleManageHost, handleDismissMissingWorkspace } =
useWorkspaceRouteActions(normalizedServerId);
@@ -3373,6 +3382,26 @@ function WorkspaceScreenContent({
isWorkspaceHeaderSubtitleDistinct,
],
);
const compactHeaderScripts = useMemo(
() => ({
serverId: normalizedServerId,
workspaceId: normalizedWorkspaceId,
scripts: workspaceScripts,
liveTerminalIds,
onScriptTerminalStarted: handleScriptTerminalStarted,
onViewTerminal: handleViewScriptTerminal,
onOpenUrlInBrowserTab: handleOpenUrlInBrowserTab,
}),
[
normalizedServerId,
normalizedWorkspaceId,
workspaceScripts,
liveTerminalIds,
handleScriptTerminalStarted,
handleViewScriptTerminal,
handleOpenUrlInBrowserTab,
],
);
const compactWorkspaceHeader = useMemo(
() =>
isMobile ? (
@@ -3408,6 +3437,7 @@ function WorkspaceScreenContent({
/>
<WorkspaceHeaderMenuMobile
normalizedServerId={normalizedServerId}
scripts={compactHeaderScripts}
currentBranchName={currentBranchName}
showWorkspaceSetup={showWorkspaceSetup}
showCreateBrowserTab={showCreateBrowserTab}
@@ -3426,6 +3456,7 @@ function WorkspaceScreenContent({
[
activeTabKey,
canOpenImportSheet,
compactHeaderScripts,
createTerminalDisabled,
currentBranchName,
explorerSidebarToggleAccessibilityState,
+2 -2
View File
@@ -15,7 +15,7 @@ import {
import {
acceptMessageSubmission,
beginMessageSubmission,
getActiveMessageSubmissions,
hasActiveMessageSubmission,
observeMessageSubmissionCanonical,
rejectMessageSubmission,
type MessageSubmissionRecord,
@@ -348,7 +348,7 @@ export function selectAgentTurnPresentation(
session?.agents.get(agentId)?.turn ??
session?.agentDetails.get(agentId)?.turn ??
TURN_LIVENESS_IDLE,
getActiveMessageSubmissions(session?.messageSubmissions.get(agentId)).length > 0,
hasActiveMessageSubmission(session?.messageSubmissions.get(agentId)),
);
}
+95 -2
View File
@@ -12,11 +12,11 @@ function user(id: string, timestamp: Date): StreamItem {
};
}
function assistant(id: string, timestamp: Date): StreamItem {
function assistant(id: string, timestamp: Date, text = id): StreamItem {
return {
kind: "assistant_message",
id,
text: id,
text,
timestamp,
};
}
@@ -125,4 +125,97 @@ describe("deriveStreamTurnTiming", () => {
durationMs: null,
});
});
it("keeps the timing map identity while a streamed delta grows the live head", () => {
const tail = [
user("u1", new Date("2026-05-15T00:00:00.000Z")),
assistant("a1", new Date("2026-05-15T00:00:07.000Z")),
user("u2", new Date("2026-05-15T00:01:00.000Z")),
];
const derive = (text: string, at: string) =>
deriveStreamTurnTiming({
isTurnActive: true,
activeTurnStartedAt: tail[2]?.timestamp ?? null,
tail,
head: [assistant("a2", new Date(at), text)],
});
const first = derive("one", "2026-05-15T00:01:04.000Z");
const second = derive("one two", "2026-05-15T00:01:05.000Z");
assert.equal(second.byAssistantId, first.byAssistantId);
assert.deepEqual(first.byAssistantId.get("a1"), {
completedAt: tail[1]?.timestamp,
durationMs: 7000,
});
assert.equal(first.byAssistantId.has("a2"), false);
});
it("keeps the timing map identity when the head closed the tail's open turn", () => {
const lastTailAt = new Date("2026-05-15T00:00:07.000Z");
const tail = [user("u1", new Date("2026-05-15T00:00:00.000Z")), assistant("a1", lastTailAt)];
const derive = (text: string, at: string) =>
deriveStreamTurnTiming({
isTurnActive: true,
activeTurnStartedAt: null,
tail,
head: [
user("u2", new Date("2026-05-15T00:01:00.000Z")),
assistant("a2", new Date(at), text),
],
});
const first = derive("one", "2026-05-15T00:01:04.000Z");
const second = derive("one two", "2026-05-15T00:01:05.000Z");
assert.equal(second.byAssistantId, first.byAssistantId);
assert.deepEqual(first.byAssistantId.get("a1"), {
completedAt: lastTailAt,
durationMs: 7000,
});
});
it("produces a new timing map when the streamed turn completes", () => {
const tail = [user("u1", new Date("2026-05-15T00:00:00.000Z"))];
const completedAt = new Date("2026-05-15T00:00:09.000Z");
const head = [assistant("a1", completedAt)];
const active = deriveStreamTurnTiming({
isTurnActive: true,
activeTurnStartedAt: tail[0]?.timestamp ?? null,
tail,
head,
});
const completed = deriveStreamTurnTiming({
isTurnActive: false,
activeTurnStartedAt: null,
tail,
head,
});
assert.notEqual(completed.byAssistantId, active.byAssistantId);
assert.equal(active.byAssistantId.has("a1"), false);
assert.deepEqual(completed.byAssistantId.get("a1"), { completedAt, durationMs: 9000 });
});
it("derives fresh timing when the tail itself changes", () => {
const firstTail = [
user("u1", new Date("2026-05-15T00:00:00.000Z")),
assistant("a1", new Date("2026-05-15T00:00:07.000Z")),
user("u2", new Date("2026-05-15T00:01:00.000Z")),
];
const secondTail = [...firstTail, assistant("a2", new Date("2026-05-15T00:01:03.000Z"))];
const derive = (tail: StreamItem[]) =>
deriveStreamTurnTiming({ isTurnActive: false, activeTurnStartedAt: null, tail, head: [] });
const first = derive(firstTail);
const second = derive(secondTail);
assert.notEqual(second.byAssistantId, first.byAssistantId);
assert.equal(first.byAssistantId.has("a2"), false);
assert.deepEqual(second.byAssistantId.get("a2"), {
completedAt: secondTail[3]?.timestamp,
durationMs: 3000,
});
});
});
+121 -47
View File
@@ -11,61 +11,135 @@ export interface StreamTurnTiming {
runningStartedAt: Date | null;
}
interface OpenTurn {
userAt: Date | null;
lastItemAt: Date | null;
assistantIds: readonly string[];
previousItem: StreamItem | null;
}
interface HeadTurnTiming {
additions: Map<string, TurnTiming>;
byAssistantId: Map<string, TurnTiming>;
}
interface TailTurnTiming {
completed: Map<string, TurnTiming>;
openTurn: OpenTurn;
lastHead: HeadTurnTiming | null;
}
const EMPTY_OPEN_TURN: OpenTurn = {
userAt: null,
lastItemAt: null,
assistantIds: [],
previousItem: null,
};
function closeTurn(turn: OpenTurn, into: Map<string, TurnTiming>): void {
if (!turn.lastItemAt || turn.assistantIds.length === 0) {
return;
}
const timing: TurnTiming = {
completedAt: turn.lastItemAt,
durationMs: turn.userAt ? Math.max(0, turn.lastItemAt.getTime() - turn.userAt.getTime()) : null,
};
for (const id of turn.assistantIds) {
into.set(id, timing);
}
}
function walkTurns(
items: readonly StreamItem[],
from: OpenTurn,
into: Map<string, TurnTiming>,
): OpenTurn {
let userAt = from.userAt;
let lastItemAt = from.lastItemAt;
let assistantIds = [...from.assistantIds];
let previousItem = from.previousItem;
for (const item of items) {
if (startsNewTurn(item, previousItem)) {
closeTurn({ userAt, lastItemAt, assistantIds, previousItem }, into);
userAt = item.kind === "user_message" ? item.timestamp : null;
lastItemAt = null;
assistantIds = [];
}
lastItemAt = item.timestamp;
if (item.kind === "assistant_message") {
assistantIds.push(item.id);
}
previousItem = item;
}
return { userAt, lastItemAt, assistantIds, previousItem };
}
function areTimingsEqual(a: Map<string, TurnTiming>, b: Map<string, TurnTiming>): boolean {
if (a.size !== b.size) {
return false;
}
for (const [id, timing] of a) {
const other = b.get(id);
if (
!other ||
other.completedAt.getTime() !== timing.completedAt.getTime() ||
other.durationMs !== timing.durationMs
) {
return false;
}
}
return true;
}
// The tail walk is cached by array identity so a streamed delta, which only replaces the
// head, walks the head from the carried open turn. The returned Map keeps its identity
// while the head adds no completed turn, so memos keyed on it do not miss per tick.
const tailTurnTimingCache = new WeakMap<StreamItem[], TailTurnTiming>();
function getTailTurnTiming(tail: StreamItem[]): TailTurnTiming {
const cached = tailTurnTimingCache.get(tail);
if (cached) {
return cached;
}
const completed = new Map<string, TurnTiming>();
const openTurn = walkTurns(tail, EMPTY_OPEN_TURN, completed);
const timing: TailTurnTiming = { completed, openTurn, lastHead: null };
tailTurnTimingCache.set(tail, timing);
return timing;
}
function resolveByAssistantId(
tail: TailTurnTiming,
additions: Map<string, TurnTiming>,
): Map<string, TurnTiming> {
if (additions.size === 0) {
return tail.completed;
}
if (tail.lastHead && areTimingsEqual(tail.lastHead.additions, additions)) {
return tail.lastHead.byAssistantId;
}
const byAssistantId = new Map(tail.completed);
for (const [id, timing] of additions) {
byAssistantId.set(id, timing);
}
tail.lastHead = { additions, byAssistantId };
return byAssistantId;
}
export function deriveStreamTurnTiming(params: {
isTurnActive: boolean;
activeTurnStartedAt: Date | null;
tail: StreamItem[];
head: StreamItem[];
}): StreamTurnTiming {
const byAssistantId = new Map<string, TurnTiming>();
let currentUserAt: Date | null = null;
let currentLastItemAt: Date | null = null;
let currentAssistantIds: string[] = [];
let previousItem: StreamItem | null = null;
const flushCompletedTurn = () => {
if (!currentLastItemAt || currentAssistantIds.length === 0) {
return;
}
const timing: TurnTiming = {
completedAt: currentLastItemAt,
durationMs: currentUserAt
? Math.max(0, currentLastItemAt.getTime() - currentUserAt.getTime())
: null,
};
for (const id of currentAssistantIds) {
byAssistantId.set(id, timing);
}
};
const visitItem = (item: StreamItem) => {
if (startsNewTurn(item, previousItem)) {
flushCompletedTurn();
currentUserAt = item.kind === "user_message" ? item.timestamp : null;
currentLastItemAt = null;
currentAssistantIds = [];
}
currentLastItemAt = item.timestamp;
if (item.kind === "assistant_message") {
currentAssistantIds.push(item.id);
}
previousItem = item;
};
for (const item of params.tail) {
visitItem(item);
}
for (const item of params.head) {
visitItem(item);
}
const runningStartedAt = params.isTurnActive ? params.activeTurnStartedAt : null;
const tail = getTailTurnTiming(params.tail);
const additions = new Map<string, TurnTiming>();
const openTurn = walkTurns(params.head, tail.openTurn, additions);
if (!params.isTurnActive) {
flushCompletedTurn();
closeTurn(openTurn, additions);
}
return {
byAssistantId,
runningStartedAt,
byAssistantId: resolveByAssistantId(tail, additions),
runningStartedAt: params.isTurnActive ? params.activeTurnStartedAt : null,
};
}

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