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
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
100 changed files with 4013 additions and 771 deletions
+7 -1
View File
@@ -1,9 +1,15 @@
# Changelog
## 0.11.3 - 2026-10-15
## 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))
+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
+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
@@ -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(
@@ -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,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) =>
@@ -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}>
@@ -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%",
+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[] {
@@ -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)) {
+3
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: {
+3
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: {
+3
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: {
+4
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: {
+3
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: {
+3
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: {
+3
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: {
+3
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: {
+3
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: {
@@ -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);
@@ -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,
};
}
+16
View File
@@ -257,6 +257,22 @@ describe("settleReports", () => {
expect(settleReports([refreshed, beta], [alpha, beta])).toEqual([refreshed, beta]);
});
it("keeps the displayed order when providers finish a refresh in reverse order", () => {
const refreshed = entry({ sourceId: "alpha", planLabel: "New" });
const streamed = upsertReport(upsertReport([alpha, beta], beta), refreshed);
expect(settleReports(streamed, [beta, refreshed])).toEqual([refreshed, beta]);
});
it("drops missing reports and appends new ones without moving surviving reports", () => {
const gamma = entry({ sourceId: "gamma" });
const delta = entry({ sourceId: "delta" });
expect(settleReports([alpha, beta, gamma], [delta, gamma, alpha])).toEqual([
alpha,
gamma,
delta,
]);
});
it("takes the finished list as is when nothing was shown yet", () => {
expect(settleReports(undefined, [alpha, beta])).toEqual([alpha, beta]);
});
+13 -6
View File
@@ -82,17 +82,24 @@ export function upsertReport(
}
/**
* The list a finished request leaves: its reports, dropping any the host no longer has, except
* that a copy on screen fetched after the request's copy stays.
* Keep displayed reports in place: the finished list is in fetch-completion order, which can
* change on every refresh. Drop missing reports, append new ones, and keep newer fetched copies.
*/
export function settleReports(
shown: readonly UsageReportEntry[] | undefined,
finished: readonly UsageReportEntry[],
): UsageReportEntry[] {
return finished.map((report) => {
const copy = shown?.find((entry) => entry.id === report.id);
return copy ? laterFetched(copy, report) : report;
});
const remaining = new Map(finished.map((report) => [report.id, report]));
const settled: UsageReportEntry[] = [];
for (const report of shown ?? []) {
const arriving = remaining.get(report.id);
if (!arriving) {
continue;
}
settled.push(laterFetched(report, arriving));
remaining.delete(report.id);
}
return [...settled, ...remaining.values()];
}
export interface UsageQueryState {
@@ -1,3 +1,5 @@
import { clickNewChat, gotoWorkspace } from "../../app/e2e/support/helpers/launcher";
import { clickSettingsBackToWorkspace } from "../../app/e2e/support/helpers/settings";
import type { Page } from "@playwright/test";
import { test, expect } from "../../app/e2e/support/fixtures";
import { gotoAppShell, openSettings } from "../../app/e2e/support/helpers/app";
@@ -213,3 +215,49 @@ for (const { platform, keys, label, firstCombo, secondCombo } of [
await expectInterruptShortcut(page, label);
});
}
async function rebindTabNumbers(page: Page) {
await captureShortcut(page, "Jump to tab", "workspace-tab-jump-index", "Control+1");
await page.getByRole("button", { name: "Done", exact: true }).click();
}
async function expectTabNumberRange(page: Page) {
const row = page.getByText("Jump to tab", { exact: true }).locator("..");
await expect(row.getByText("⌃1-9", { exact: true })).toBeVisible();
}
async function openTwoDraftTabs(page: Page, workspaceId: string) {
await installDesktopBridge(page);
await gotoWorkspace(page, workspaceId);
await clickNewChat(page);
await clickNewChat(page);
await expect(
page.locator('[data-testid^="workspace-tab-draft_"]').filter({ visible: true }),
).toHaveCount(2);
await openSettings(page);
await openSettingsSection(page, "shortcuts");
}
async function expectTabNumberNavigation(page: Page) {
const tabs = page.locator('[data-testid^="workspace-tab-draft_"]').filter({ visible: true });
await page.keyboard.press("Control+1");
await expect(tabs.nth(0)).toHaveAttribute("aria-selected", "true");
await page.keyboard.press("Control+2");
await expect(tabs.nth(1)).toHaveAttribute("aria-selected", "true");
}
test("rebinding Jump to tab preserves the number group after reload", async ({
page,
withWorkspace,
}) => {
const workspace = await withWorkspace({ prefix: "tab-number-rebind-" });
await openTwoDraftTabs(page, workspace.workspaceId);
await rebindTabNumbers(page);
await clickSettingsBackToWorkspace(page);
await expectTabNumberNavigation(page);
await page.reload();
await expectTabNumberNavigation(page);
await openSettings(page);
await openSettingsSection(page, "shortcuts");
await expectTabNumberRange(page);
});
@@ -127,7 +127,7 @@ function inspectChatDragExclusions(scroll: Element) {
const headerRect = header.getBoundingClientRect();
const headerY = headerRect.top + headerRect.height / 2;
const content = scroll.firstElementChild;
const focusScope = scroll.closest("[tabindex]");
const focusScope = scroll.closest("[data-window-content]")?.parentElement?.closest("[tabindex]");
if (!content || !focusScope) throw new Error("Expected chat content and its focus scope");
const contentRect = content.getBoundingClientRect();
const chatX = (contentRect.left + contentRect.right) / 2;
@@ -547,8 +547,13 @@ class AcpRuntime {
return sessionCapabilities;
}
async discover(cwd = process.cwd()): Promise<ProviderCatalog> {
const response = await this.call(this.connection.newSession({ cwd, mcpServers: [] }));
async discover(cwd?: string): Promise<ProviderCatalog> {
if (cwd === undefined && this.options.options.acpOptions?.workspaceOnlyCatalog) {
return { models: [], modes: [] };
}
const response = await this.call(
this.connection.newSession({ cwd: cwd ?? process.cwd(), mcpServers: [] }),
);
this.nativeSessionId = response.sessionId;
this.modes = response.modes;
this.configOptions = response.configOptions ?? [];
+33
View File
@@ -272,6 +272,39 @@ lines.on("line", (line) => {
}
});
it("still reports initialization failures for workspace-only global discovery", async () => {
let unavailable = false;
const { connector } = connectorHarness({
handleRequest(instance, request) {
if (unavailable && request.method === "initialize") {
instance.reject(request, "Bridge unavailable");
return true;
}
return false;
},
});
const registration = runAcpProvider({
id: "workspace-acp",
label: "Workspace ACP",
connector,
acpOptions: { workspaceOnlyCatalog: true },
});
const connection = await registration.connect({ versions: [1], capabilities: [] });
const events: ProviderEvent[] = [];
connection.onEvent((event) => events.push(event));
try {
unavailable = true;
await connection.send({ type: "catalog", requestId: "global" });
expect(await waitForEvent(events, (event) => event.type === "request.failed")).toMatchObject({
requestId: "global",
error: { message: expect.stringContaining("Bridge unavailable") },
});
expect(events.some((event) => event.type === "catalog")).toBe(false);
} finally {
await connection.close();
}
});
it("rejects connection cleanly when the ACP executable does not exist", async () => {
const registration = runAcpProvider({
id: "missing-acp",
+2
View File
@@ -44,6 +44,8 @@ export type AcpConnector = () => AcpStream | Promise<AcpStream>;
export interface AcpOptions {
protocol?: "auto" | "v1";
startupTimeoutMs?: number;
/** Global discovery initializes ACP but returns an empty catalog without opening a session. */
workspaceOnlyCatalog?: boolean;
waitForInitialCommands?: boolean;
initialCommandsTimeoutMs?: number;
}
+1 -1
View File
@@ -89,7 +89,7 @@
"speech:transcribe:local": "tsx scripts/transcribe-local-wav.ts",
"test": "npm run test:unit && npm run test:integration",
"test:unit": "vitest run --fileParallelism --exclude \"**/*.e2e.test.ts\"",
"test:integration": "vitest run --maxWorkers=1 src/server/git-filename-diffs.e2e.test.ts src/server/daemon-e2e/checkout-diff-content.e2e.test.ts src/server/daemon-e2e/filesystem.e2e.test.ts src/server/daemon-e2e/file-download.e2e.test.ts src/server/daemon-e2e/cli-logs-follow.e2e.test.ts src/server/creation/creation.e2e.test.ts src/server/daemon-e2e/terminal-workspace-sdk.e2e.test.ts src/server/daemon-e2e/models.e2e.test.ts src/server/daemon-e2e/live-preferences.e2e.test.ts src/server/daemon-e2e/oversized-message.e2e.test.ts src/server/agent/model-catalog.e2e.test.ts src/server/plugins/plugin-paseo-api.e2e.test.ts && vitest run --maxWorkers=1 src/server/daemon-e2e/git-operations.e2e.test.ts -t \"merges into\" && vitest run --maxWorkers=1 src/server/session.create-agent-worktree-autoarchive.e2e.test.ts -t \"creates a worktree and auto-archives both\" && vitest run --maxWorkers=1 src/server/agent/providers/opencode-bridge.local.e2e.test.ts -t \"versioned runtime\" && vitest run --maxWorkers=1 src/server/daemon-e2e/relay-transport.e2e.test.ts -t \"oversized attachments\"",
"test:integration": "vitest run --maxWorkers=1 src/server/git-filename-diffs.e2e.test.ts src/server/daemon-e2e/checkout-diff-content.e2e.test.ts src/server/daemon-e2e/filesystem.e2e.test.ts src/server/daemon-e2e/file-download.e2e.test.ts src/server/daemon-e2e/cli-logs-follow.e2e.test.ts src/server/creation/creation.e2e.test.ts src/server/daemon-e2e/terminal-workspace-sdk.e2e.test.ts src/server/workspace-create-worktree-source.e2e.test.ts src/server/daemon-e2e/models.e2e.test.ts src/server/daemon-e2e/live-preferences.e2e.test.ts src/server/daemon-e2e/oversized-message.e2e.test.ts src/server/agent/model-catalog.e2e.test.ts src/server/plugins/plugin-paseo-api.e2e.test.ts && vitest run --maxWorkers=1 src/server/daemon-e2e/git-operations.e2e.test.ts -t \"merges into\" && vitest run --maxWorkers=1 src/server/session.create-agent-worktree-autoarchive.e2e.test.ts -t \"creates a worktree and auto-archives both\" && vitest run --maxWorkers=1 src/server/agent/providers/opencode-bridge.local.e2e.test.ts -t \"versioned runtime\" && vitest run --maxWorkers=1 src/server/daemon-e2e/relay-transport.e2e.test.ts -t \"oversized attachments\"",
"test:hub-cli-contract": "vitest run --maxWorkers=1 src/server/hub/hub-cli-contract.test.ts",
"test:integration:all": "npm run test:e2e",
"test:integration:real": "vitest run real.e2e.test.ts",
@@ -0,0 +1,40 @@
import { spawnSync } from "node:child_process";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { afterEach, describe, expect, test } from "vitest";
const tempDirs: string[] = [];
afterEach(() => {
for (const dir of tempDirs.splice(0)) {
rmSync(dir, { recursive: true, force: true });
}
});
describe("transcribe-local-wav CLI", () => {
test("initializes the complete speech provider configuration", () => {
const modelsDir = mkdtempSync(path.join(tmpdir(), "paseo-transcribe-local-"));
tempDirs.push(modelsDir);
const missingWav = path.join(modelsDir, "missing.wav");
const scriptPath = fileURLToPath(new URL("./transcribe-local-wav.ts", import.meta.url));
const result = spawnSync(
process.execPath,
["--import", "tsx", scriptPath, missingWav, "--models-dir", modelsDir],
{
encoding: "utf8",
timeout: 15_000,
},
);
expect(result.error).toBeUndefined();
expect(result.status).not.toBe(0);
// The worker client is lazy, so reaching the missing WAV proves provider initialization completed first.
expect(result.stderr).toContain("ENOENT");
expect(result.stderr).toContain(missingWav);
expect(result.stderr).not.toContain("Cannot read properties of undefined");
});
});
@@ -120,6 +120,7 @@ async function main(): Promise<void> {
const providers: RequestedSpeechProviders = {
dictationStt: { provider: "local", explicit: true },
voiceTurnDetection: { provider: "local", explicit: false, enabled: false },
voiceStt: { provider: "local", explicit: true },
// Not used here, but required by the shared runtime config shape.
voiceTts: { provider: "openai", explicit: false },
@@ -20,6 +20,13 @@ readline.createInterface({ input: process.stdin }).on("line", (line) => {
let result = {};
if (request.method === "initialize")
result = { protocolVersion: 1, agentCapabilities: {}, authMethods: [] };
if (request.method === "session/new" && request.params.cwd !== process.env.HOPLITE_TEST_CWD) {
send({
id: request.id,
error: { code: -32602, message: "No Hoplite project for this directory" },
});
return;
}
if (request.method === "session/new")
result = {
sessionId: "hoplite-fixture",
@@ -199,10 +199,13 @@ test("bundled Hoplite requires a config entry and removal survives restart", asy
hoplite: {
enabled: true,
command: [process.execPath, path.resolve(import.meta.dirname, "hoplite-fixture.cjs")],
env: { HOPLITE_TEST_RECORD: record },
env: { HOPLITE_TEST_RECORD: record, HOPLITE_TEST_CWD: root },
},
},
});
const globalModels = await client.listProviderModels("hoplite");
expect(globalModels.error).toBeNull();
expect(globalModels.models).toEqual([]);
await expect
.poll(
async () =>
@@ -211,9 +214,14 @@ test("bundled Hoplite requires a config entry and removal survives restart", asy
)?.status,
)
.toBe("ready");
expect((await client.listProviderModels("hoplite")).models.map((model) => model.id)).toEqual([
"fixture-model",
]);
const workspaceModels = await client.listProviderModels("hoplite", { cwd: root });
expect(workspaceModels.error).toBeNull();
expect(workspaceModels.models.map((model) => model.id)).toEqual(["fixture-model"]);
await client.refreshProvidersSnapshot({ providers: ["hoplite"] });
expect((await client.listProviderModels("hoplite")).models).toEqual([]);
expect(
(await client.listProviderModels("hoplite", { cwd: root })).models.map((model) => model.id),
).toEqual(["fixture-model"]);
const agent = await client.createAgent({
provider: "hoplite",
cwd: root,
@@ -1,5 +1,6 @@
import { execFileSync } from "node:child_process";
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { existsSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
import { rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { expect, onTestFinished, test } from "vitest";
@@ -18,6 +19,7 @@ function createGitRepoWithBranch(): { repoDir: string; tempRoot: string } {
const tempRoot = mkdtempSync(path.join(tmpdir(), "workspace-create-worktree-source-"));
const repoDir = path.join(tempRoot, "repo");
execFileSync("git", ["init", "-b", "main", repoDir], { stdio: "pipe" });
execFileSync("git", ["config", "core.autocrlf", "false"], { cwd: repoDir, stdio: "pipe" });
execFileSync("git", ["config", "user.email", "test@getpaseo.local"], {
cwd: repoDir,
stdio: "pipe",
@@ -60,10 +62,134 @@ test("workspace.create worktree source forwards action=checkout + refName into t
} finally {
await client.close().catch(() => undefined);
await daemon.close();
rmSync(tempRoot, { recursive: true, force: true });
await rm(tempRoot, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
}
}, 180000);
test.each([false, true])(
"workspace.create opens worktree.terminals (setup service: %s)",
async (withSetupService) => {
const daemon = await createTestPaseoDaemon();
const { repoDir, tempRoot } = createGitRepoWithBranch();
writeFileSync(
path.join(repoDir, "paseo.json"),
JSON.stringify({
worktree: {
...(withSetupService
? {
// Launch the Windows service asynchronously so it outlives
// the setup command instead of holding setup open.
setup:
process.platform === "win32"
? "Start-Process -FilePath node -ArgumentList 'setup.cjs','serve' -WorkingDirectory (Get-Location).Path -WindowStyle Hidden; while (!(Test-Path setup-pid.txt)) { Start-Sleep -Milliseconds 25 }"
: "node setup.cjs",
}
: {}),
terminals: [
{ name: "preview", command: "echo paseo-auto-terminal >> terminal-marker.txt" },
],
},
}),
);
writeFileSync(
path.join(repoDir, "setup.cjs"),
`
const fs = require("node:fs");
if (process.argv[2] === "serve") {
require("node:net").createServer().listen(Number(process.env.PASEO_WORKTREE_PORT), "127.0.0.1", () => {
fs.writeFileSync("setup-pid.txt", String(process.pid));
process.send?.("ready");
});
} else {
const child = require("node:child_process").spawn(process.execPath, [__filename, "serve"], {
detached: true,
stdio: ["ignore", "ignore", "ignore", "ipc"],
});
child.once("message", () => { child.disconnect(); child.unref(); });
}
`,
);
execFileSync("git", ["add", "paseo.json", "setup.cjs"], { cwd: repoDir, stdio: "pipe" });
execFileSync("git", ["-c", "commit.gpgsign=false", "commit", "-m", "add paseo.json"], {
cwd: repoDir,
stdio: "pipe",
});
const client = new DaemonClient({
url: `ws://127.0.0.1:${daemon.port}/ws`,
appVersion: "0.1.82",
});
let workspaceCwd: string | undefined;
try {
await client.connect();
// This is the request the New Workspace screen sends: the workspace is
// created on its own, with no agent in the same request.
const result = await client.createWorkspace({
source: {
kind: "worktree",
cwd: repoDir,
action: "branch-off",
branchName: "feature/auto-terminals",
worktreeSlug: "feature-auto-terminals",
baseBranch: "main",
},
});
expect(result.error).toBeNull();
const workspace = result.workspace;
if (!workspace) {
throw new Error("Expected a created workspace");
}
workspaceCwd = workspace.workspaceDirectory;
if (withSetupService) {
await expect
.poll(() => existsSync(path.join(workspaceCwd!, "setup-pid.txt")), { timeout: 30000 })
.toBe(true);
}
await expect
.poll(async () => (await client.fetchWorkspaceSetupStatus(workspace.id)).snapshot, {
timeout: 30000,
})
.toMatchObject({ status: "completed", error: null });
await expect
.poll(
async () =>
(
await client.listTerminals(workspace.workspaceDirectory, undefined, {
workspaceId: workspace.id,
})
).terminals.map((terminal) => terminal.name),
{ timeout: 30000 },
)
.toContain("preview");
await expect
.poll(
() => {
const marker = path.join(workspaceCwd!, "terminal-marker.txt");
return existsSync(marker) ? readFileSync(marker, "utf8").trim() : null;
},
{ timeout: 10000 },
)
.toBe("paseo-auto-terminal");
expect(
(await client.listTerminals(workspaceCwd, undefined, { workspaceId: workspace.id }))
.terminals,
).toHaveLength(1);
} finally {
const pidFile = workspaceCwd && path.join(workspaceCwd, "setup-pid.txt");
if (pidFile && existsSync(pidFile)) {
process.kill(Number(readFileSync(pidFile, "utf8")));
}
await client.close().catch(() => undefined);
await daemon.close();
await rm(tempRoot, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
}
},
180000,
);
test("existing branch changes remain visible after archive and restore", async () => {
const daemon = await createTestPaseoDaemon();
const { repoDir, tempRoot } = createGitRepoWithBranch();
@@ -74,7 +200,7 @@ test("existing branch changes remain visible after archive and restore", async (
onTestFinished(async () => {
await client.close().catch(() => undefined);
await daemon.close();
rmSync(tempRoot, { recursive: true, force: true });
await rm(tempRoot, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
});
runGit(repoDir, "switch", "feature/existing-branch");
commitFile(repoDir, "feature.txt", "feature change\n");
@@ -134,7 +260,7 @@ test("workspace.create keeps a branch-off name separate from its worktree slug",
} finally {
await client.close().catch(() => undefined);
await daemon.close();
rmSync(tempRoot, { recursive: true, force: true });
await rm(tempRoot, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
}
}, 180000);
@@ -168,7 +294,7 @@ test("workspace.create accepts a Git-valid branch-off name outside Paseo slug sy
} finally {
await client.close().catch(() => undefined);
await daemon.close();
rmSync(tempRoot, { recursive: true, force: true });
await rm(tempRoot, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
}
}, 180000);
@@ -210,7 +336,7 @@ test("workspace.create always creates a new worktree when the slug is already oc
} finally {
await client.close().catch(() => undefined);
await daemon.close();
rmSync(tempRoot, { recursive: true, force: true });
await rm(tempRoot, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
}
}, 180000);
@@ -255,7 +381,7 @@ test("workspace.create suffixes past an occupied detached worktree", async () =>
} finally {
await client.close().catch(() => undefined);
await daemon.close();
rmSync(tempRoot, { recursive: true, force: true });
await rm(tempRoot, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
}
}, 180000);
@@ -297,7 +423,7 @@ test("workspace.create suffixes an occupied checkout branch", async () => {
} finally {
await client.close().catch(() => undefined);
await daemon.close();
rmSync(tempRoot, { recursive: true, force: true });
await rm(tempRoot, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
}
}, 180000);
@@ -340,7 +466,7 @@ async function createRestorableWorkspace(baseRef: string) {
onTestFinished(async () => {
await client.close().catch(() => undefined);
await daemon.close();
rmSync(tempRoot, { recursive: true, force: true });
await rm(tempRoot, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
});
createDivergentBases(repoDir);
await client.connect();
@@ -593,13 +593,10 @@ export async function runWorktreeAutoTerminals(options: {
workspaceId: string;
worktree: WorktreeConfig;
workspaceCwd: string;
runtimeEnv: WorktreeRuntimeEnv;
terminalManager: TerminalManager | null;
logger?: Logger;
}): Promise<void> {
const runtimeEnv = await resolveWorktreeRuntimeEnv({
worktreePath: options.worktree.worktreePath,
branchName: options.worktree.branchName,
});
await runWorktreeTerminalBootstrap(
{
agentId: options.workspaceId,
@@ -610,7 +607,7 @@ export async function runWorktreeAutoTerminals(options: {
appendTimelineItem: async () => true,
logger: options.logger,
},
runtimeEnv,
options.runtimeEnv,
);
}
+17 -20
View File
@@ -817,7 +817,6 @@ export async function handleWorkspaceSetupRunRequest(
slug: basename(worktree.worktreePath),
worktreePath: worktree.worktreePath,
workspaceCwd: workspace.cwd,
runAutoTerminals: true,
},
signal,
),
@@ -857,7 +856,6 @@ export async function runWorktreeSetupInBackground(
slug: string;
worktreePath: string;
workspaceCwd?: string;
runAutoTerminals?: boolean;
},
signal?: AbortSignal,
): Promise<void> {
@@ -898,18 +896,18 @@ export async function runWorktreeSetupInBackground(
} else {
const workspaceCwd = options.workspaceCwd ?? worktree.worktreePath;
const setupCommands = getWorktreeSetupCommands(workspaceCwd);
const runtimeEnv = await resolveWorktreeRuntimeEnv({
worktreePath: worktree.worktreePath,
branchName: worktree.branchName,
repoRootPath: options.repoRoot,
});
dependencies.terminalManager?.registerCwdEnv({
cwd: workspaceCwd,
env: runtimeEnv,
});
if (setupCommands.length === 0) {
emitSetupProgress("completed", null);
} else {
const runtimeEnv = await resolveWorktreeRuntimeEnv({
worktreePath: worktree.worktreePath,
branchName: worktree.branchName,
repoRootPath: options.repoRoot,
});
dependencies.terminalManager?.registerCwdEnv({
cwd: workspaceCwd,
env: runtimeEnv,
});
setupResults = await runWorktreeSetupCommands({
worktreePath: workspaceCwd,
branchName: worktree.branchName,
@@ -924,15 +922,14 @@ export async function runWorktreeSetupInBackground(
});
emitSetupProgress("completed", null);
}
if (options.runAutoTerminals) {
await runWorktreeAutoTerminals({
workspaceId,
worktree,
workspaceCwd,
terminalManager: dependencies.terminalManager,
logger: dependencies.sessionLogger,
});
}
await runWorktreeAutoTerminals({
workspaceId,
worktree,
workspaceCwd,
runtimeEnv,
terminalManager: dependencies.terminalManager,
logger: dependencies.sessionLogger,
});
}
} catch (error) {
if (error instanceof WorktreeSetupError) {
@@ -11,6 +11,7 @@ export function createHopliteProvider(): ProviderRegistration {
description: "Hoplite's coding agent through the local `hoplite acp` bridge",
icon: "icon.svg",
command: ["hoplite", "acp"],
acpOptions: { workspaceOnlyCatalog: true },
transformers: [runPhaseTransformer],
}),
};